Skip to content

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 ​

text
                  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`              │
 └──────────────────────────────┘ └──────────────────────────────┘ └──────────────────────────────┘
SurfacePrimary consumerAudience / spoiler boundaryHard size boundHow it stays fresh
1. External Harness + get_play_dashboardelthoria, elthoria web, Claude Desktop, Codex, AntigravityPlayer-safe allowlist on dashboard; explicit audience: GM, playerSafe: false tagging on GM board reads7 lines × <= 100 chars; title <= 80 chars; metadata <= 160 charsAuto-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 turnsGM 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 generationStrictly epistemic per-speaker (requiredFacts + forbiddenFacts enforced via ActorKnowledgeGate)Single scene turn + bounded trait/goal/continuity/recentDialogue listsBuilt 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:

  1. Workspace & Role Contract (AGENTS.md + active skill): Defines the external GM contract (canon over prose, roll before narrating uncertain outcomes, never leak playerSafe: false snapshots, refresh dashboard after mutations, fail-closed PDF workbench rules).
  2. Kompile Persistent Memory (<memory_context>): Cross-session preferences and notes injected by Kompile (never authoritative over live Elthoria canon — see Memory Architecture).
  3. Pinned Play Dashboard (mcp__elthoria__get_play_dashboard, schema kompile.dashboard.v1):
    • Implemented in PlayDashboardMcpTools (in elthoria-game) using an explicit allowlist of visible fields — it never serializes raw world aggregates, combat entities, secrets, or mutable rule configuration.
    • Configured in .mcp.json under kompile.dashboard with readOnly: true and an explicit refreshAfterTools trigger list.
    • Emits 7 bounded summary lines (<= 100 chars each) alongside 7 allowlisted structured sections (game, character, world, scene, combat, map, setup):
text
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.
  1. 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_search and graph_reasoning_query against kompile-harness-knowledge (graph.kgraph)

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) ​

text
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:

  1. actionParsingPort.parse(content) extracts structured tool/game actions.
  2. narrativeExtractionPort.extractNarrative(content) isolates player-facing prose.
  3. narrationGroundingPort validates the narration against live world/campaign canon. If a contradiction is detected, a corrective alert is queued and prepended to step 4a on the next turn.
  4. turnMemoryPort.remember(...) records the turn summary into CampaignMemoryPort (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 headingCapSelection & sorting ruleAudience note
1Header & Realm:1 lineweek, season, primary polity stability, collapseRisk, macro warPrevalence, faminePressure, party.reputation (%)Macro backdrop
2Active map:1 linemapEntityId (HexCampaignMapEntity #<id>) and count of managedMapEntityIdsSpatial link
3Party location: & Party travel:1–2 linescurrentRegionId, currentHexCoordinate, currentSettlementId; if traveling: status, originHex → destinationHex, currentHex, remainingCost travel-hours, etaWeekLive party position
4Party members the world has news of6party.fallenMemberNames + non-alive/non-dead memberStatuses (omitted if everyone is healthy)High-salience casualty memory
5Since the last week turned (already true — react to it)6pendingWorldEvents (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
6Map regions4Sorted region IDs: name, hex count, localUnrest %, localFear %Regional tension
7Map settlements4Sorted settlement IDs with hex coords: name, coord, security %, unrestRisk %Local stability
8ANTLR map attributes2HexMap.g4 section counts + current-hex attribute map from WorldSimulationProjectionAuthoritative hex semantics
9ANTLR tactical map attributes3TTRPGMap.g4 section counts, up to 3 tactical grid summaries, current-hex tactical cell attributesAuthoritative grid semantics
10Active situations4Sorted by intensity descendingUrgent pressures
11Rumors in circulation4Sorted by virality descending; includes virality % and actually X% trueGM ground truth — LLM knows what is true vs. distorted
12Quest story pressure4storyPressure > 0.05 or non-null currentStoryBeat, sorted by storyPressure desc; includes linked rumor/info counts + current beatPacing & plot hooks
13Notable NPC activity6Active non-party agents with ActorTier.A or persistent or importance >= 0.55, sorted by importance desc; shows current action, importance %, partyPredisposition, and latest AgentPersonalEventPersistent NPC continuity
14Predicaments near the party3predicamentHierarchy nodes with non-null graphDistanceToParty, showing label + playerVisibleConflictProximity-scoped drama
15Intrigue graph facts3Top graphSnapshot.derivedFacts atom keysGM-level causal derivations
16Emerging threads (forecast, not yet fact)3emergingTies: fromLabel → toLabel (relationType)Explicitly labeled forecast, not canon

Example Rendered ## LIVING WORLD SIMULATION Block ​

text
## 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"):

json
{
  "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 ​

  • requiredFacts anchors the line to verified world events and WorldFact derivations the speaker actually holds.
  • forbiddenFacts is populated through ActorKnowledgeGate (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:

InvariantMechanismWhy it exists
1. Canon beats memory & proseLive 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 fencedTurn 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 separationget_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 distinctionWorldSimulationContextFormatter 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 boundingWorldSimulationContextFormatter (<= 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.md and .kompile/skills/elthoria-*.md

Built on the upstream Kompile harness. Released under the MIT License.