World State as Presented to an LLM
Elthoria never dumps a raw WorldSimState document, database dump, or full tactical grid JSON into an LLM context window. Doing so would blow past token budgets, leak hidden GM secrets into player-facing prose, blur authoritative canon with untrusted memory, and invite the model to hallucinate state changes instead of calling deterministic tools.
Instead, Elthoria projects the authoritative game and world state through three purpose-built, token-bounded presentation pipelines — each with an explicit audience boundary, trust contract, and refresh cadence.
TIP
Looking for the underlying data structures? See Living World Architecture for the WorldSimState entity hierarchy, ANTLR DSL & World Sim Data Format for persistence schemas, and Memory Architecture Deep Dive for the five-layer memory stack.
High-Level Architecture: Three LLM Context Surfaces
Authoritative State (H2 / JPA + WorldSimState)
├── Campaigns, Characters, Inventory, Buffs, Journal
├── InitiativeRuntime, Combat, StealthRuntime, Boards (Hex & Tactical)
└── WorldSimState (Macro, Regions, Settlements, Factions, NPCs, Rumors, Graph)
│
┌────────────────────────────────┼────────────────────────────────┐
▼ ▼ ▼
1. External Harness / MCP 2. In-App Campaign Turn 3. NPC Dialogue Realization
(`elthoria` / `elthoria web`) (`CampaignTurnService`) (`CampaignDialogueRealizationAdapter`)
┌──────────────────────────────┐ ┌──────────────────────────────┐ ┌──────────────────────────────┐
│ • AGENTS.md + active skill │ │ • MCP tool injection prefix │ │ • Strict `fantasy-dialogue- │
│ • Kompile `<memory_context>` │ │ • Composed prompt template │ │ v1` JSON DTO │
│ • Pinned `get_play_dashboard`│ │ • `## CURRENT GAME STATE`: │ │ • `speaker` / `listener` │
│ (`kompile.dashboard.v1`, │ │ 1. Grounding drift alert │ │ • `relationship` & `scene` │
│ strictly player-safe) │ │ 2. `PromptContextPort` │ │ • `causalFrame` & magnitudes │
│ • On-demand scoped MCP reads │ │ (chars/map/journal) │ │ • `requiredFacts` │
│ (`get_world_sim_overview`, │ │ 3. `<untrusted-memory>` │ │ • `forbiddenFacts` │
│ `get_tactical_board`, │ │ 4. `WorldContextPort` │ │ (ActorKnowledgeGate fence) │
│ `get_activated_entries`, │ │ (`<= 3,200 chars`) │ │ • `recentDialogue` │
│ `knowledge_search`, ...) │ │ 5. Active grid / hex IDs │ │ • `constraints` │
└──────────────────────────────┘ └──────────────────────────────┘ └──────────────────────────────┘| Surface | Primary consumer | Audience / spoiler boundary | Hard size bound | How it stays fresh |
|---|---|---|---|---|
1. External Harness + get_play_dashboard | elthoria, elthoria web, Claude Desktop, Codex, Antigravity | Player-safe allowlist on dashboard; explicit audience: GM, playerSafe: false tagging on GM board reads | 7 lines × <= 100 chars; title <= 80 chars; metadata <= 160 chars | Auto-refreshed by Kompile refreshAfterTools after gameplay mutations; deeper reads pulled on demand via mcp_tool_call |
2. In-App Turn Prompt (CampaignTurnService) | Embedded single-player / app chat turns | GM context (includes rumor truth % and intrigue graph facts; optional fog-of-war filtering on tactical maps) | WorldSimulationContextFormatter capped at 3,200 chars; journal default 5 entries; per-section caps (2–6 items) | Rebuilt fresh on every turn; post-turn NarrationGroundingPort queues a drift alert onto the next turn if narration contradicted canon |
3. Dialogue Realization (fantasy-dialogue-v1) | In-character NPC dialogue generation | Strictly epistemic per-speaker (requiredFacts + forbiddenFacts enforced via ActorKnowledgeGate) | Single scene turn + bounded trait/goal/continuity/recentDialogue lists | Built per dialogue beat directly from the active SceneDirector beat and speaker/listener state |
Surface 1: External Harness & Pinned Play Dashboard (elthoria / elthoria web)
When an external LLM runs inside the Kompile harness (elthoria or elthoria web), Elthoria does not stuff full character sheets, world graphs, and maps into every user turn. Instead, the LLM starts each turn with a small, stable baseline and pulls deeper slices through MCP only when the action calls for them:
- Workspace & Role Contract (
AGENTS.md+ active skill): Defines the external GM contract (canon over prose, roll before narrating uncertain outcomes, never leakplayerSafe: falsesnapshots, refresh dashboard after mutations, fail-closed PDF workbench rules). - Kompile Persistent Memory (
<memory_context>): Cross-session preferences and notes injected by Kompile (never authoritative over live Elthoria canon — see Memory Architecture). - Pinned Play Dashboard (
mcp__elthoria__get_play_dashboard, schemakompile.dashboard.v1):- Implemented in
PlayDashboardMcpTools(inelthoria-game) using an explicit allowlist of visible fields — it never serializes raw world aggregates, combat entities, secrets, or mutable rule configuration. - Configured in
.mcp.jsonunderkompile.dashboardwithreadOnly: trueand an explicitrefreshAfterToolstrigger list. - Emits 7 bounded summary lines (
<= 100chars each) alongside 7 allowlisted structured sections (game,character,world,scene,combat,map,setup):
- Implemented in
Title: Elthoria Play — Lanterns at Greywater
Lines:
Campaign: Lanterns at Greywater
Hero: Rowan Vane (Fighter 1) — HP 12/12, AC 16
World: Greywater Reach — Week 4, Autumn (Reputation 58%)
Scene: Greywater Harbor — Fogbound Pier
Combat: Active — Round 2, Turn: Rowan Vane
Map: Hex Map #3 (Greywater Coast) | Tactical Grid #9 (South Beacon Pier)
Next: The campaign context is ready for play.- On-Demand Scoped MCP Reads: Whenever a turn needs deeper detail, the LLM discovers and calls narrow read tools rather than loading the entire database:
- Character / combat math:
get_character,get_combat_status,get_tactical_board(audience: GM,playerSafe: false) - Living world & reasoning:
get_world_sim_overview,get_world_latest_week,get_world_story_candidates(player-safe),explain_world_fact,get_npc_world_context(GM-only) - Maps & Lorebooks:
get_hex_board(player-safe),get_hex_location_by_coords,get_activated_entries(keyword-triggered World Info) - Indexed bookshelf: Kompile's native
knowledge_searchandgraph_reasoning_queryagainstkompile-harness-knowledge(graph.kgraph)
- Character / combat math:
Surface 2: In-App Campaign Turn Prompt (CampaignTurnService)
For direct campaign turns orchestrated by elthoria-campaign-runtime's CampaignTurnService, Elthoria assembles a complete ## CURRENT GAME STATE block on every turn in a deterministic order.
Exact Prompt Assembly Order (CampaignTurnService.buildContext & buildPrompt)
1. [Optional] MCP tool injection prefix (mcpToolCatalogPort.injectionPrefix)
2. Composed system prompt templates (promptTemplatePort.compose)
3. [Optional] Conversation history (chatPromptPort.build when includeHistory=true)
4. ## CURRENT GAME STATE
├── 4a. Pending Narration Grounding Alert (prepended if prior turn drifted from canon)
├── 4b. Modular Campaign Context (PromptContextPort → ContextInjectionService)
│ • ## PLAYER CHARACTERS (race, classes/levels, stats, optional buffs/inventory)
│ • ## CURRENT MAP (frontend grid text, optional fog-of-war / revealed traps)
│ • Recent Journal Entries (default max 5 entries)
│ • Chat Folder Reference Files (file paths the agent may read)
├── 4c. Campaign Pin + Quarantined Memory ("Current campaign ID: <id>" + <untrusted-memory>)
├── 4d. ## LIVING WORLD SIMULATION (WorldContextPort → WorldSimulationContextFormatter, <= 3,200 chars)
├── 4e. Active Board Handles (Active grid ID + Active hex campaign map ID)
└── 4f. Participant Backgrounds (ParticipantContextFormatter, when enabled)
5. user: <current turn message>Post-Turn Grounding Loop
After the LLM replies, CampaignTurnService closes the loop so state drift cannot snowball silently across turns:
actionParsingPort.parse(content)extracts structured tool/game actions.narrativeExtractionPort.extractNarrative(content)isolates player-facing prose.narrationGroundingPortvalidates the narration against live world/campaign canon. If a contradiction is detected, a corrective alert is queued and prepended to step4aon the next turn.turnMemoryPort.remember(...)records the turn summary intoCampaignMemoryPort(where future recall always returns inside<untrusted-memory>delimiters so prose can never override canon).
Inside WorldSimulationContextFormatter: Exact World State Projection
The living-world slice injected at step 4d is produced by WorldSimulationContextFormatter.format(WorldSimState) in elthoria-world-simulation-projection. It is a pure, side-effect-free, deterministic formatter with strict per-section caps and a hard 3,200-character ceiling (\n…(truncated)\n if exceeded).
| # | Section heading | Cap | Selection & sorting rule | Audience note |
|---|---|---|---|---|
| 1 | Header & Realm: | 1 line | week, season, primary polity stability, collapseRisk, macro warPrevalence, faminePressure, party.reputation (%) | Macro backdrop |
| 2 | Active map: | 1 line | mapEntityId (HexCampaignMapEntity #<id>) and count of managedMapEntityIds | Spatial link |
| 3 | Party location: & Party travel: | 1–2 lines | currentRegionId, currentHexCoordinate, currentSettlementId; if traveling: status, originHex → destinationHex, currentHex, remainingCost travel-hours, etaWeek | Live party position |
| 4 | Party members the world has news of | 6 | party.fallenMemberNames + non-alive/non-dead memberStatuses (omitted if everyone is healthy) | High-salience casualty memory |
| 5 | Since the last week turned (already true — react to it) | 6 | pendingWorldEvents (with immediate-applied vs. next-week tag), backfilled from recent SimEvent ledger deaths/status events (week - 1..week) | Bridges intra-week table events before the next weekly tick |
| 6 | Map regions | 4 | Sorted region IDs: name, hex count, localUnrest %, localFear % | Regional tension |
| 7 | Map settlements | 4 | Sorted settlement IDs with hex coords: name, coord, security %, unrestRisk % | Local stability |
| 8 | ANTLR map attributes | 2 | HexMap.g4 section counts + current-hex attribute map from WorldSimulationProjection | Authoritative hex semantics |
| 9 | ANTLR tactical map attributes | 3 | TTRPGMap.g4 section counts, up to 3 tactical grid summaries, current-hex tactical cell attributes | Authoritative grid semantics |
| 10 | Active situations | 4 | Sorted by intensity descending | Urgent pressures |
| 11 | Rumors in circulation | 4 | Sorted by virality descending; includes virality % and actually X% true | GM ground truth — LLM knows what is true vs. distorted |
| 12 | Quest story pressure | 4 | storyPressure > 0.05 or non-null currentStoryBeat, sorted by storyPressure desc; includes linked rumor/info counts + current beat | Pacing & plot hooks |
| 13 | Notable NPC activity | 6 | Active non-party agents with ActorTier.A or persistent or importance >= 0.55, sorted by importance desc; shows current action, importance %, partyPredisposition, and latest AgentPersonalEvent | Persistent NPC continuity |
| 14 | Predicaments near the party | 3 | predicamentHierarchy nodes with non-null graphDistanceToParty, showing label + playerVisibleConflict | Proximity-scoped drama |
| 15 | Intrigue graph facts | 3 | Top graphSnapshot.derivedFacts atom keys | GM-level causal derivations |
| 16 | Emerging threads (forecast, not yet fact) | 3 | emergingTies: fromLabel → toLabel (relationType) | Explicitly labeled forecast, not canon |
Example Rendered ## LIVING WORLD SIMULATION Block
## LIVING WORLD SIMULATION (week 4, AUTUMN)
The world below is simulated weekly. Treat it as ground truth for NPC moods, rumors, and political pressure. Use world_sim tools for details.
Realm: stability 64%, collapse risk 18%, war 12%, famine 9%, party reputation 58%
Active map: HexCampaignMapEntity #3; refreshed sim map artifacts 2
Party location: region reg_greywater_coast, hex 4,6, settlement set_greywater_harbor
Since the last week turned (already true — react to it):
- South Beacon lantern extinguished and watchman missing (in effect now; the world reacts when the week turns)
Map regions:
- Greywater Reach (120 hexes, unrest 34%, fear 41%)
Map settlements:
- Greywater Harbor at 4,6 (security 52%, unrest risk 38%)
Active situations:
- Dockmasters' Guild Tariff Squeeze (intensity 72%)
Rumors in circulation:
- "Smugglers bribed the beacon tender to darken the south shoals" (virality 81%, actually 90% true)
Quest story pressure:
- Lanterns at Greywater (pressure 78%, rumors 2, info 1): South Beacon darkened ahead of autumn convoy
Notable NPC activity:
- Harbor Master Pell: Inspecting dock manifests (importance 76%, CAUTIOUS toward party; recent: Questioned by Rowan Vane on South Pier)
- Tide-Stalker Smuggler: Moving contraband crates at low tide (importance 62%, HOSTILE toward party)
Predicaments near the party:
- Darkened Beacon — Merchant ships refuse to dock until the South Beacon burns again
Intrigue graph facts:
- covert_sponsorship(fac_dockmasters, ag_smuggler)
Emerging threads (forecast, not yet fact):
- Harbor Watch → Dockmasters' Guild (INVESTIGATION)Surface 3: In-Character NPC Dialogue (fantasy-dialogue-v1)
When Elthoria realizes an in-character line of NPC dialogue through elthoria-world-simulation-realization, the model does not see the GM-wide world state at all. Instead, CampaignDialogueRealizationAdapter constructs a strictly ordered DialogueRealizationRequest (schemaVersion: "fantasy-dialogue-v1"):
{
"schemaVersion": "fantasy-dialogue-v1",
"requestId": "req-week4-beat-02",
"domain": "fantasy",
"speaker": {
"id": "ag_pell",
"name": "Harbor Master Pell",
"role": "OFFICIAL",
"faction": "fac_dockmasters",
"location": "Greywater Harbor — South Pier",
"traits": ["cautious", "bureaucratic"],
"goals": ["Keep the autumn fleet docking on schedule"],
"continuity": ["Questioned by Rowan Vane about the darkened beacon"]
},
"listener": {
"id": "party",
"name": "Rowan Vane",
"role": "PARTY",
"location": "Greywater Harbor — South Pier"
},
"relationship": { "trust": "cautious", "debt": "none" },
"scene": {
"location": "South Beacon Pier",
"time": "dusk",
"weather": "thick harbor fog",
"publicness": "semi-public",
"terrain": ["wet timber planks", "stacked cargo crates"],
"nearbyEntities": ["brass-padlocked lantern housing"]
},
"causalFrame": {
"topic": "South Beacon outage",
"pressure": "dockmasters_tariff_squeeze",
"situation": "autumn_convoy_delay",
"move": "DEFLECT_WITH_PROCEDURE",
"intensity": "moderate",
"objective": "Avoid implicating the Guild without provoking the watch",
"informationQuality": "firsthand_partial",
"sourceTags": ["harbor_ledger"],
"sourceIds": ["ev_beacon_dark_w4"]
},
"requiredFacts": [
"Only the Dockmasters' Guild holds the brass keys to the upper shutter."
],
"forbiddenFacts": [
"Tide-Stalker Smuggler is currently hidden behind the east crates.",
"covert_sponsorship(fac_dockmasters, ag_smuggler)"
],
"recentDialogue": [
"Rowan: Two nights dark, Pell. Who holds the brass key to the South Beacon shutter?"
],
"constraints": { "maxWords": 80, "inCharacterOnly": true }
}Why requiredFacts + forbiddenFacts Matter
requiredFactsanchors the line to verified world events andWorldFactderivations the speaker actually holds.forbiddenFactsis populated throughActorKnowledgeGate(see Agent Reasoning & Decisions) so an NPC cannot blurt out secrets they do not know, hidden enemy coordinates, or omniscient GM graph facts — even when the underlying simulation knows them.
Trust, Visibility & Boundary Invariants
Every developer extending Elthoria's prompts, MCP tools, or projections must preserve these five invariants:
| Invariant | Mechanism | Why it exists |
|---|---|---|
| 1. Canon beats memory & prose | Live MCP reads and WorldSimState projections override recalled <untrusted-memory>, <memory_context>, Lorebook text, and prior chat prose. | Prevents HP, spell slots, board coordinates, and world state from drifting across long sessions. |
| 2. Untrusted data is explicitly fenced | Turn recall is wrapped in <untrusted-memory>…</untrusted-memory>; PDF Workbench text is treated as untrusted data outside data/input_documents/elthoria/. | Prevents prompt injection from user notes, journal text, or extracted PDF pages. |
| 3. Player-safe vs. GM-only separation | get_play_dashboard, get_hex_board, get_world_story_candidates, and VttSceneSyncSnapshot.toPlayerSafe() strip hidden tokens, gmNotes, and secret derivations. GM board reads are explicitly tagged audience: GM, playerSafe: false. | Keeps hidden stealthed ambushers, traps, and faction schemes off player-facing screens and recaps. |
| 4. Forecast vs. fact distinction | WorldSimulationContextFormatter labels Emerging threads (forecast, not yet fact) separately from Since the last week turned (already true — react to it) and Intrigue graph facts. | Stops the LLM from narrating predicted future ties as already-committed canon. |
| 5. Strict token bounding | WorldSimulationContextFormatter (<= 3,200 chars, per-section caps 2–6), PlayDashboardMcpTools (<= 100 chars/line), ContextInjectionService (maxJournalEntries = 5), and on-demand MCP tool pulls. | Keeps prompt latency and cost stable even in 200-week campaigns with hundreds of NPCs and hexes. |
Key Source Files
- Turn prompt orchestration:
elthoria-campaign-runtime/.../campaign/turn/CampaignTurnService.java - Living-world prompt formatter:
elthoria-world-simulation-projection/.../worldsim/projection/WorldSimulationContextFormatter.java - Structured projections & overlays:
elthoria-world-simulation-projection/.../worldsim/projection/WorldSimulationProjection.java - Dialogue realization DTO & adapter:
elthoria-world-simulation-realization/.../worldsim/realization/DialogueRealizationRequest.java,CampaignDialogueRealizationAdapter.java - Pinned player-safe dashboard (in
elthoria-game):elthoria-app/.../mcp/PlayDashboardMcpTools.java - Modular campaign context injection (in
elthoria-game):elthoria-app/.../services/agent/ContextInjectionService.java - External harness policy & skills:
elthoria-mcp-server/src/main/harness/AGENTS.mdand.kompile/skills/elthoria-*.md