ANTLR Map DSLs & World Simulator Data Format
This deep dive documents the two core text and JSON data formats that bridge spatial map representation and changing world state across Elthoria Harness:
- The two ANTLR4 Map DSL grammars (
elthoria-map-dsl) —TTRPGMap.g4for tactical/dungeon square grids andHexMap.g4for overland campaign hex maps, plus their parser, fallback, and DTO extraction pipeline. - The World Simulator state, tick, and persistence formats (
elthoria-world-simulation-*) —WorldSimState(elthoria_world_sim_v1), how ANTLR map projections embed into simulator state, how numeric macro state and open-schema narrative state co-evolve across weeks, deterministic SHA-256 state hashing, the weekly tick pipeline (WorldSimEngine→WeekResult+SimEvent), and the four-record persistence schema.
TIP
Looking for the plain-English Game Master guide to using maps and the living world with your AI assistant? Read How Your AI GM Uses Maps & the Living World, or try Walkthrough 3 and Walkthrough 4.
How the ANTLR DSLs and World Simulator connect
Elthoria does not treat maps and world simulation as separate silos. Both ANTLR4 grammars parse into structured Java DTOs (ParsedHexMapData and ParsedAntlrData) and are projected directly onto WorldSimState so weekly simulation systems, travel advancement, scene staging, and browser boards all share the same spatial coordinates:
┌──────────────────────────────────────────────────────────────────────────────┐
│ ANTLR4 Map DSLs (`elthoria-map-dsl`) │
│ │
│ TTRPGMap.g4 (Tactical / Dungeon) HexMap.g4 (Overland Campaign) │
│ └─ AntlrParserService └─ HexMapParserService │
│ ├─ preprocessAntlrText() └─ HexMapLexer / HexMapParser │
│ ├─ TTRPGMapLexer / Parser └─ HexMapDataExtractor │
│ ├─ TTRPGMapDataExtractor └─ ParsedHexMapData │
│ └─ regex fallback recovery │
│ └─ ParsedAntlrData │
└───────────────────┬─────────────────────────────────────────┬────────────────┘
│ tacticalMapAttributes / │ mapAttributes /
│ tacticalCellAttributes │ hexMapAttributes
▼ ▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ WorldSimState (`simConfigVersion: "elthoria_world_sim_v1"`) │
│ Single deterministic JSON document per simulation (`WorldSimulationRecord`) │
│ │
│ • Spatial bindings: mapAttributes (HexMap.g4), hexMapAttributes, │
│ tacticalMapAttributes (TTRPGMap.g4), tacticalCellAttributes │
│ • Macro numeric world: MacroWorldState, SimRegion, SimSettlement, │
│ SimFaction, SimHouse, SimAgent, CollapseState │
│ • EvolvingWorld narrative layer: GlobalWorldState (OpenSchemaDimension), │
│ LocationState + EntityState, SceneTrajectory │
│ • Temporal & belief dynamics: InboundWorldEvent, PressurePacket, │
│ DelayedConsequence, DeadlineState, Rumor + RumorBelief (SimOpinion), │
│ 8-dim RelationshipVector, IntrigueSecret │
│ • Reasoning & audit: GraphSnapshot (PSL/OWL RL/Belnap), WorldFact, │
│ eventLedger (SimEvent), TableOracleState, ObjectiveLedgerState │
└───────────────────┬──────────────────────────────────────────────────────────┘
│ WorldSimEngine.simulateWeek(state, partyAction)
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ Durable Persistence (`elthoria-world-simulation-persistence-api`) │
│ 1. WorldSimulationRecord — latest mutable WorldSimState JSON + lock ver │
│ 2. WorldSimWeekResultRecord — per-week GM digest (`WeekResult` JSON) │
│ 3. WorldSimEventLogRecord — queryable durable historical event rows │
│ 4. WorldSimArtifactRecord — keyed JSON/binary snapshots & artifacts │
└──────────────────────────────────────────────────────────────────────────────┘Part 1: ANTLR4 Map DSL Formats (elthoria-map-dsl)
Both grammars live under elthoria-map-dsl/src/main/antlr4/ai/elthoria/grammar/ and use a Markdown-inspired ## SECTION_NAME block structure so both procedural generators and LLMs can author, inspect, and round-trip maps cleanly.
1.1 Tactical & Dungeon Map Grammar (TTRPGMap.g4)
- Entry rule:
dungeon : section+ EOF ; - Parser service:
ai.elthoria.services.AntlrParserService#parseAntlrText(String) - Output DTO:
ai.elthoria.models.dto.ParsedAntlrData(elthoria-domain) - MCP round-trip tools:
parse_antlr_grid,get_grid_antlr_text,generate_ttrpg_map
Section markers (28 grammar sections)
| Category | Grammar section markers | Purpose |
|---|---|---|
| Core structure | ## HEADER, ## GRID_DEFINITION, ## GRID | Map metadata (Title, Author, Campaign, Scale, etc.), grid dimensions/legend, and row-by-row ASCII cell grid |
| Party & combat | ## PARTY, ## ENTITY_STATS, ## ENTITIES, ## ENCOUNTERS | Player party definition for encounter balancing, reusable Pathfinder/d20 stat blocks, coordinate entity placements referencing stat / cr / npc IDs, and encounter groups with triggers (proximity, time, event, always) |
| Dungeon elements | ## TRAPS, ## PUZZLES, ## LOOT, ## NPCS, ## OBSTACLES, ## ROOMS, ## PASSAGES, ## MARKERS | Interactive dungeon features, non-combatants, logical room definitions, connecting passages, and GM markers |
| Terrain & environment | ## TERRAIN_TYPES, ## TERRAIN_MAP, ## BIOME, ## ROOM_TEMPLATES, ## RESOURCE_NODES, ## MAGICAL_FEATURES, ## NATURAL_FEATURES, ## META_STATUS | Named terrain types, per-coordinate terrain overrides, biome context, reusable templates, harvestable nodes, arcane/natural hazards, and status tags |
| Narrative hooks | ## QUESTS, ## QUEST_OBJECTIVES, ## STORY, ## STORY_ELEMENTS, ## LEGENDS | Quests, structured objectives, narrative background, story hooks, and free-form map legends |
Tactical grid cell symbols (## GRID)
| Symbol | Meaning | Symbol | Meaning |
|---|---|---|---|
# | Wall (impassable) | ~ | Water / Difficult terrain |
. | Floor (traversable) | ^ | Mountain / High obstacle |
+ | Door | * | Forest / Foliage |
> | Stairs Down | T | Trap |
< | Stairs Up | P | Puzzle / Secret |
S | Secret Door | L | Loot / Treasure |
X | Obstacle / Pillar | M | Marker (user-defined) |
O | Pit / Chasm | (space) | Void / Unexplored |
NOTE
Entities are intentionally not encoded as single-letter glyphs inside ## GRID. Instead, ## ENTITIES places each entity by (x, y) coordinate and links it to a stat block in ## ENTITY_STATS (or a cr / database npc reference), with optional instance overrides (name, hp, max_hp, status: healthy|wounded|bloodied|unconscious|dead, faction, attitude: hostile|unfriendly|neutral|friendly|helpful).
Minimal valid TTRPGMap.g4 example
## HEADER
Title: Sunken Watchtower Cellar
Author: GM
Scale: 5ft
## GRID_DEFINITION
Width: 6
Height: 4
## GRID
######
#..+.#
#.T.L#
######
## ENTITY_STATS
goblin_scout:
name: "Goblin Scout"
cr: 1/3
ac: 16
hp: 6
speed: 30ft
## ENTITIES
gob_1: 4,1 stat goblin_scout hp 6, status healthy, attitude hostile
## ENCOUNTERS
enc_cellar: "Cellar Ambush" entities [gob_1] trigger proximity
## TRAPS
(2,2) Tripwire Bell: Perception DC 15, Disable Device DC 15
## LOOT
(4,2) Ironbound Coffer: 45 gp, rusted signet ringAI-resilient parse & recovery pipeline (AntlrParserService)
Because LLMs occasionally emit minor syntax deviations (lowercase headers like ## Traps, missing trailing newlines, or Markdown code fences), AntlrParserService runs a three-stage pipeline:
preprocessAntlrText(text)— strips fenced code blocks (```), canonicalizes## <section>casing and spacing, and ensures a trailing newline.- Strict ANTLR4 parse —
TTRPGMapLexer→CommonTokenStream→TTRPGMapParser.dungeon()→ParseTreeWalker.walk(TTRPGMapDataExtractor, tree)→extractor.linkEntitiesToStatBlocks(). - Graceful fallback (
fallbackSectionParse) — if ANTLR encounters syntax errors or returns incomplete sections, regex-based section extractors recoverHEADER,ROOMS,PASSAGES,TRAPS,LOOT,PUZZLES,ENTITY_STATS, andENTITIESso GM/AI-authored content is never silently discarded.
1.2 Overland Hex Campaign Map Grammar (HexMap.g4)
- Entry rule:
hexCampaignMap : header mapDefinition hexGrid optionalSection* EOF ; - Parser service:
ai.elthoria.services.HexMapParserService#parseHexMapText(String) - Output DTO:
ai.elthoria.models.dto.ParsedHexMapData(elthoria-domain) - MCP round-trip tools:
parse_hex_map_text,generate_hex_map_text,get_hex_map_antlr_text
Required sections vs. optional sections (19 grammar sections)
| Requirement | Section marker | Key fields / entries |
|---|---|---|
| Required (1) | ## HEADER | title (quoted), created (ISO datetime), campaign, scale (<int> <unit>, e.g. 6 miles), season, date |
| Required (2) | ## MAP_DEFINITION | coordinate_system (offset-odd-r, offset-even-r, axial, or cube), width, height |
| Required (3) | ## HEX_GRID | Row-by-row terrain code grid (see table below) |
| Optional (16) | ## LOCATIONS, ## POINTS_OF_INTEREST, ## CONNECTIONS, ## BLOCKERS, ## EVENTS, ## ENCOUNTERS, ## WEATHER, ## RESOURCES, ## TIME_CALENDAR, ## VISIBILITY, ## TRAVEL_MODIFIERS, ## TACTICAL_INFO, ## MAGICAL_FEATURES, ## FACTIONS, ## REGIONS, ## METADATA | Settlements & POIs (name, population, notable_npcs, quests, services, danger_level, faction_control, rumor), roads/routes (from, to, travel_time, difficulty, encounter_rate), terrain blockers, scheduled events, encounter tables, weather/resources/calendar, fog-of-war visibility, travel modifiers, magical zones, factions, and regions |
Hex terrain codes (## HEX_GRID)
| Code | Terrain | Code | Terrain |
|---|---|---|---|
P | Plains | T | Tundra |
F | Forest | J | Jungle |
M | Mountains | C | Coast |
H | Hills | V | Volcanic |
D | Desert | r | Road |
S | Swamp | d | Dungeon entrance |
W | Water / Ocean / Lake | X | Impassable |
R | River | . | Void / Empty |
? | Unexplored (fog of war) |
Minimal valid HexMap.g4 example
## HEADER
title = "Vaelor Border Marches"
created = 2026-04-12T10:00:00Z
campaign = "Crown of Ash"
scale = 6 miles
season = Autumn
date = "14th of Harvestmoon"
## MAP_DEFINITION
coordinate_system = offset-odd-r
width = 5
height = 3
## HEX_GRID
P P F H M
P r F H M
C P P S W
## LOCATIONS
ashford: (1,1) name = "Ashford Crossing" population = 620 danger_level = 2 faction_control = iron_wardens services = ["Inn", "Smithy"] rumor = "Caravans from the north are two weeks overdue."
## CONNECTIONS
old_king_road: from = (0,1) to = (1,1) travel_time = 1 days difficulty = easy condition = "Rutted by supply wagons" encounter_rate = "1d6 per day"1.3 How ANTLR Projections Bind into the Simulator & Persisted Boards
When a world simulation is initialized or linked to a campaign map, both ANTLR grammars are projected directly onto WorldSimState:
WorldSimState field | Type | Source & role |
|---|---|---|
mapEntityId / managedMapEntityIds | Long / List<Long> | Campaign DB primary hex map ID and any simulator-managed tactical/region map IDs (masked from deterministic state hash) |
mapAttributes | Map<String, Object> | Full HexMap.g4 projection (header, map definition, terrain grid, locations, connections, factions, regions) |
hexMapAttributes | Map<String, Map<String, Object>> | Per-coordinate ("x,y") derived spatial layer index for fast lookup by travel, incidents, and location state |
tacticalMapAttributes | Map<String, Map<String, Object>> | Full TTRPGMap.g4 projections keyed by tactical grid ID |
tacticalCellAttributes | Map<String, Map<String, Object>> | Per-cell ("gridId:x,y") derived tactical attribute index |
NOTE
ANTLR DSL vs. Persisted Board Wire Contracts: The ANTLR DSLs (TTRPGMap.g4, HexMap.g4) are the authoring, procedural generation, and simulation projection formats. Live browser panels and MCP board mutations (get_tactical_board, apply_tactical_board_command, get_hex_board, apply_hex_board_command) exchange revision-checked JSON contracts with optimistic concurrency (expected_revision) and idempotency (command_id). See Maps, Hexes & Tactical Boards.
Part 2: World Simulator Changing-World-State Data Format (elthoria-world-simulation-*)
The living world simulator is split into three focused modules:
elthoria-world-simulation-model— framework-neutral Java POJOs representing the serialized state document, weekly digest, event ledger, and reasoning projections.elthoria-world-simulation-engine— deterministic weekly tick orchestrator (WorldSimEngine), domain systems, EvolvingWorld scene director, and canonical state hashing (WeekResultBuilder).elthoria-world-simulation-persistence-api— framework-neutral storage records separating the mutable state snapshot from append-only weekly digests, historical event logs, and artifacts.
2.1 Root State Document (WorldSimState)
One living world simulation is serialized as one JSON document modeled by ai.elthoria.worldsim.model.WorldSimState with schema version SIM_CONFIG_VERSION = "elthoria_world_sim_v1".
All cross-references inside the document use stable string IDs (for example "agent.voss", "faction.iron_wardens", "region.marches", "loc.ashford_tavern") rather than Java object references or database primary keys, so the entire world graph can be cloned in memory for counterfactual story previews (preview_world_story_choice) without mutating canon.
Top-level field groups in WorldSimState
| Group | Fields | What changes over time |
|---|---|---|
| Identity & clock | simConfigVersion, runId, seed, scaleMode, week, season, gameSettings, difficultyTuning, feedback | week increments each tick; season derives from Season.forWeek(week); difficultyTuning and feedback adapt to campaign pressure |
| Spatial projections | gameId, mapEntityId, managedMapEntityIds, mapAttributes, hexMapAttributes, tacticalMapAttributes, tacticalCellAttributes | Mirrors HexMap.g4 and TTRPGMap.g4 state as terrain, locations, or tactical scenes evolve |
| Macro cast & geography | agents, houses, factions, factionRelations, regions, settlements, loreObjects, party, macro (MacroWorldState) | Polity stability, active wars, commodity scarcity (KingdomEconomy), faction morale/relations, regional unrest, agent goals/status/deaths, and party travel state |
| EvolvingWorld narrative layer | globalWorldState, locationStates, sceneTrajectory | Open-schema prose world dimensions (GlobalWorldState), nested physical locations and props (LocationState → EntityState), and rolling played-scene history (SceneTrajectory) |
| Dynamic pressures & time | pendingWorldEvents, pressurePackets, activeSituations, activeIncidents, activeConversations, activeDeadlines, delayedConsequences | Campaign-injected events, active pressures, visible/hidden incidents, ticking deadlines, and scheduled future aftershocks |
| Beliefs, intrigue & social web | rumors, rumorBeliefs, relationships, relationshipProvenance, intrigueSecrets | Circulating rumors with subjective-logic opinions (SimOpinion), 8-dimensional directed agent relationships with provenance, and secret knowledge graphs |
| Reasoning, quests & audit | graphSnapshot, predicamentHierarchy, worldFacts, eventLedger, tableOracle, quests, narrativeCandidateDispositions, objectiveLedger, lastKgeWeek, emergingTies | Weekly intrigue graph & Belnap/OWL RL diagnostics, FOL-derived WorldFact records, append-only SimEvent ledger, Mythic-style oracle chaos factor, quest signals, and player candidate dispositions |
2.2 Determinism & Canonical State Hashing
Two runs with the same seed, settings, and sequence of inputs must produce byte-identical world evolution:
- Sorted-ID iteration:
WorldSimStateexposes non-getter deterministic traversal helpers (sortedAgentIds(),sortedFactionIds(),sortedHouseIds(),sortedRegionIds(),sortedSettlementIds(),sortedLoreObjectIds(),sortedRumorIds(),sortedSecretIds()) so iteration order never depends on hash buckets when consuming the seededSimRng. Non-getter names also stay out of Jackson JSON serialization. - Canonical SHA-256 hash (
WeekResultBuilder#hashState): After each week,WeekResultBuilderserializesWorldSimStatewith anObjectMapperconfigured withSORT_PROPERTIES_ALPHABETICALLYandORDER_MAP_ENTRIES_BY_KEYS, then computes a SHA-256 hex digest. - Explicitly masked identity & advisory fields: Before hashing (
canonicalStateBytes), the builder temporarily masks out fields that depend on database row identity, wall-clock timestamps, or non-authoritative advisory subsystems so same-seed simulations across different campaign rows hash equal:runId,gameId,mapEntityId,managedMapEntityIdsquests(keyed by DB-generated campaign thread IDs)mapAttributes.header.created(wall-clock map creation timestamp)emergingTies(advisory KGE link forecasts)graphSnapshot.attributionsandgraphSnapshot.unifiedGraphMeta.graphId
2.3 Dual-Layer Changing State: Numeric Macro + Open-Schema EvolvingWorld
A key design feature of Elthoria's simulator is that changing world state lives in two synchronized layers:
1. Numeric Macro Layer (MacroWorldState, SimRegion, SimSettlement, SimFaction, SimAgent)
Tracks quantitative systemic indicators in [0, 1] and structured counters:
MacroWorldState:polities(PolityState),activeWars(WarState),kingdomEconomy(KingdomEconomy/ commodity scarcity), plus continent-wide pressures (continentStability,warPrevalence,faminePressure,plaguePressure,refugeePressure,magicCatastrophePressure,tradeConnectivity).- Regional & actor state: settlement unrest/development, faction relations/morale/collapse risk, house debt/prestige, agent goals, plans, and survival status.
2. Open-Schema EvolvingWorld Layer (GlobalWorldState, LocationState, EntityState, SceneTrajectory)
Models prose-level narrative and physical continuity (following EvolvingWorld, arXiv:2607.17250) so a siege campaign can track supply_lines and sworn_oaths while a mercantile campaign tracks guild_writ without changing Java schemas:
OpenSchemaDimension(used onGlobalWorldState.dimensionsand character profiles):- Fields:
key,value(prose),changeability,confidence,lastChangedWeek,revisions,provenance(supporting scene/incident/pressure IDs). - Changeability thresholds gate how much hidden-tracker evidence must accumulate before a rewrite is allowed:
- Fields:
Changeability | Evidence threshold | Intended timescale |
|---|---|---|
Fast | 0.6 | Mood, immediate intent — can shift in a single scene |
Moderate | 1.6 | Attitudes, working relationships — requires reinforcing scenes |
Slow | 3.2 | Personality, loyalty, worldview — requires sustained patterns |
Anchor | ∞ (POSITIVE_INFINITY) | Name, bloodline, species — structural facts never rewritten by simulation |
LocationState+EntityState:- Locations nest hierarchically (
parentLocationId,childLocationIds) and link back to the macro layer (regionId,settlementId,hexCoordinate). - Each location holds a bounded
changeLog(last 24 physical changes) and a map of tracked non-characterEntityStateobjects (Kind:Fixture,Prop,Hazard,Resource,Threshold,Vehicle,Remains,Sign) with prosestate,condition(1.0pristine →0.0destroyed),visible,lastChangedWeek, andlastChangedSceneId.
- Locations nest hierarchically (
SceneTrajectory:- Retains a rolling window of played
Sceneobjects (totalScenescounts the lifetime total) plusTrajectoryMetrics. Older scenes can be dropped from the window without losing world memory because their durable effects are already written intoGlobalWorldState,LocationState,EntityState, and character profiles.
- Retains a rolling window of played
2.4 Dynamic Pressures, Beliefs, Causality & Temporal Change
Between ticks and across weeks, state transitions flow through five specialized data structures:
- Two-phase campaign ingestion (
InboundWorldEvent)- Event types:
NPC_DEATH,NPC_STATUS_CHANGE,LOCATION_STATUS_CHANGE,FACTION_EVENT,CUSTOM_GM_EVENT,PARTY_MEMBER_DEATH,PARTY_MEMBER_STATUS(fromAPI,AUTO_HOOK, orUI). - Phase 1 (immediate): When a player kills an NPC or burns a granary at the table, the local truth is written immediately and
immediateApplied = trueis set so the GM and UI see it right away. - Phase 2 (next weekly tick):
IngestionSystemconsumespendingWorldEventsand triggers the world's reaction (rumors, grief, succession, delayed consequences) under deterministic tick ordering without double-applying the local mutation.
- Event types:
- Pressures & compound consequence chains (
PressurePacket,DelayedConsequence)PressurePacketmodels a directional unit of stress (source:war,famine,debt,rumor,scheme,relationship,deadline,succession,temple,trade_blockade,uprising,corruption,collapse) withmagnitude,urgency,visibility,volatility,emotionalCharge, and affected agents/factions/locations.DelayedConsequenceschedules future fallout (createdWeek→maturesWeek, optionalexpiresWeek,Status:Pending | Matured | Resolved | Expired) across scopes (Party,House,Faction,Province,Government,Polity,World). Related consequences share acorrelationKeysoConsequenceSystemcan escalate overlapping aftershocks into compound crises (CompoundHouseCrisis,CompoundFactionCrisis,CompoundPolityCrisis, etc.).
- Rumors & subjective-logic beliefs (
Rumor,RumorBelief)Rumortracks a circulating claim (27ClaimTypevalues fromtreasonandwar_profiteeringtoplanted_falsehoodandspy_leak) with groundtruthValue,virality,decayRate,distortion,evidenceQuality,politicalUtility, andscandalValue.RumorBelief(keyedagentId → rumorId) tracks each agent's epistemic state (Ignorant,Spreader,BelieverSilent,Skeptic,Stifler) backed by an authoritative subjective-logicSimOpinion(belief = opinion.expectation(),certainty = 1.0 - opinion.uncertainty).
- 8-dimensional directed relationships (
RelationshipVector)- Keyed
fromAgentId → toAgentId, storing eight normalized[0, 1]axes:affinity,attraction,envy,fear,obligation,respect,suspicion, andtrust, paired withrelationshipProvenanceentries explaining what shifted each axis.
- Keyed
- Reasoning, facts & contradiction diagnostics (
GraphSnapshot,WorldFact)GraphSnapshotis an app-owned POJO projection of the weekly intrigue graph (typedNodes andEdges, Louvaincommunities,rankedNodes, PSLinfluenceResultswith KKTtraceContext, OWL RLworldInconsistencies, BelnapbeliefContension/beliefConflictCount/claimReports, and loreclaimDossiers).WorldFactrecords both observed evidence (observed = true) and FOL-derived facts (observed = false) withatomKey,value,confidence,supportingFactKeys,supportingRuleIds, and normalizedrunId("seed:week") poweringexplain_world_fact.
2.5 Weekly Tick Pipeline (WorldSimEngine → WeekResult & SimEvent)
Calling advance_world_week executes WorldSimEngine.simulateWeek(state, action) in a strict, reproducible phase order:
1. Ingestion & Difficulty applyInboundWorldEvents → advanceDifficultyTuning
2. Macro & Downward Cascade MacroWorld → Economy → Factions → Collapse (pass 1)
→ DownwardPropagation → ImmersiveDifficultyReset
3. Pressures & Maturation PressurePackets → TableOracle → DelayedConsequences
→ CharacterSituations → OpeningSituation
4. Party Action & Travel PartyAction + SocialEffects → WorldTravelAdvancer
5. Graph & NPC Planning IntrigueGraph (pre-plan) → TheoryOfMind → AgentGoals
→ VoI InformationGoals → Continuity → Faction/Agent
Planning → CovertSchemes → PersistentNpcDevelopment
6. Incidents, Rumors & Chains ObservableIncidents + Visibility → RumorGeneration
→ Schedule/Correlate DelayedConsequences
→ Propagate Rumors & Beliefs
7. Epistemic Reconciliation BeliefReconciliation → TruthMaintenance
8. Graph Reasoning & Quests IntrigueGraph (post-tick) → PredicamentHierarchy
→ GraphInfluence → NarrativeInference (FOL/PSL)
→ QuestStorySignals → ObjectiveLedger
9. Upward Feedback & Collapse UpwardPropagation → Relationships/Reputation
→ MacroFeedback → Collapse (pass 2) → ChaosFactor
→ NpcConversations
10. EvolvingWorld Scene Layer SceneDirector.stageWeek → TrajectoryEvaluator
11. Foresight & Digest Build EmergingTies (KGE, unhashed) → TerminalForecasts
→ WorldSensitivity → WeekResultBuilder (+ SHA-256)
→ DecisionSystem → state.week++ & Season.forWeek()Outputs of a tick
SimEvent(appended tostate.eventLedger): Structured audit entries with deterministic ID ("evt.<week>.<index>"),type(64 typed enum values spanning macro events, collapse updates, delayed consequence escalation, rumor lifecycle, contradiction detection, belief revision, travel milestones, oracle triggers, and live world edits),actorId,targetId,sourceId,severity,visibility,tags, and apayloadmap.WeekResult(returned to GM / persisted per week): Visibility-filtered GM digest separatingDirectincidents (majorEvents),Report/SecondhandRumor(newIncidents), andTrace/DistantTrace(traces) while keepingHiddenincidents out of player-facing views, plusworldChanges,relationshipChanges,deadlineChanges,npcConversations, graph/Belnap/OWL RL insights,gameplayChoices(withChoiceContinuityandChoiceVisibilityspoiler gates:Known | Suspected | Unknown | SpoilerLocked), stagedscenes,trajectoryMetrics,metrics, anddebug(wall time + canonical state hash).
2.6 Agent Reasoning & Decision-Making Pipeline (kompile-graph-reasoning)
Both NPCs (elthoria-world-simulation-engine) and combat advisors (elthoria-rules-engine) make decisions using Kompile's graph-reasoning primitives rather than flat scalar rules:
| Decision Layer | Elthoria Service(s) | Kompile Primitives Used | What It Computes |
|---|---|---|---|
| Epistemic Theory-of-Mind | BeliefWorldService | SubgraphMaterializer, BayesianNetwork (NoisyOrCpt), VariableElimination, MostRelevantExplanation, WeightOfEvidence, ProbabilisticContradictionDetector | Materializes a strictly non-omniscient per-agent ego-subgraph, runs multi-hop Bayesian inference (HostileIntermediary → CompromisedByIntermediary → WillBetray), and extracts parsimonious MRE/WoE causal drivers |
| Dialectical Policy & Combat Arbitration | PolicyCollisionSearch, CombatTacticalDecisionService, GraphReasoningSystem | Nested Qbaf, QeSemantics, AdjudicatorConfig.qe(), DossierAdjudicator, QbafWeightLearner | Smooth Quadratic-Energy gradual argumentation with nested premise rebuttals (e.g. Belnap conflict attacking beliefFor, lowConfidence attacking impact, riskTolerance mitigating risk) without DF-QuAD ceiling saturation |
| Target-Scoped Knowledge Gate & Graph Planning | ActorKnowledgeGate, PolicyCollisionSearch, SceneMotivationSystem | SubgraphMaterializer, shortest social path, Brandes betweenness centrality | Prevents unrelated rumors from unlocking intrigue against other targets; BOUNDED_GOAP unlocks missing epistemic facets (whyNotUnlock=...); INFLUENCE_GRAPH_SEARCH discovers multi-hop social bridges (socialPath=...) and network brokers (broker=...); scenes reflect WillBetray posteriors and contested dossiers |
| Sensitivity, VoI & Crisis Abduction | WorldInsightService, TerminalStateSystem | SensitivityAnalyzer, InformationGainEstimator, MostRelevantExplanation, WeightOfEvidence | Spies target highest exact Bayesian EIG + sensitivity unknowns; weekly "world hinges on..." uses SensitivityAnalyzer.rankBySensitivity; terminal crises surface mre= root causes and woe: log-odds attributions |
| Belief Revision & Counterfactuals | TruthMaintenanceService, CandidateReasoningService, WorldQuantitativeScenarioService | BeliefReviser.retractReviseAndPurge, JustificationIndex, GraphQueryEngine (WHY, WHY_NOT, PATH, SCENARIO, SOLVE_TARGET) | Purges solely-dependent facts on debunk while preserving and MAP-downgrading multi-support weakened atoms; surfaces WHY_NOT candidate gaps; supports counterfactual SCENARIO interventions and SOLVE_TARGET goal-seeking over realm stability formulas |
| Campaign-Adaptive Weight Learning | RuleWeightLearningService, NarrativeInferenceService | StructuredPerceptronLearner, MebnWeightLearner, QbafWeightLearner, FileWeightStore | Versions and learns PSL spread weights, MEBN propagation weights (kind="mebn.*" / learnMebnTheory), and per-evidence-kind QE QBAF weights per campaign |
2.7 Durable Persistence Schema (elthoria-world-simulation-persistence-api)
Rather than stuffing every historical digest and binary artifact into the hot mutable state blob, elthoria-world-simulation-persistence-api separates durable storage into four framework-neutral Java records:
| Record | Lifecycle | Key columns / fields | Role |
|---|---|---|---|
WorldSimulationRecord | Mutable current snapshot (optimistic lock via stateVersion) | id, gameId, name, seed, simConfigVersion ("elthoria_world_sim_v1"), currentWeek, season, status (RUNNING | PAUSED | ENDED), mapEntityId, primary, stateJson, settingsJson, stateVersion | Authoritative latest WorldSimState JSON document + settings |
WorldSimWeekResultRecord | Append-only (one row per simulated week) | id, simulationId, week, resultJson, createdAt | Serialized WeekResult digest for fast weekly recaps without re-simulating |
WorldSimEventLogRecord | Append-only queryable ledger | id, simulationId, gameId, week, type, source, severity, summary, applied, npcId, characterId, locationRef, detailsJson, createdAt | Durable historical timeline indexed by NPC, character, location, and week (get_world_chronology, get_world_event_log) |
WorldSimArtifactRecord | Keyed upsert (simulationId + artifactKey) | id, gameId, simulationId, week, kind, artifactKey, name, contentType, payloadJson, payloadBytes, createdAt, updatedAt | Derived JSON or binary artifacts (unified graph archives, dossiers, exported snapshots) |
2.8 Annotated JSON Skeleton (WorldSimState)
Below is a compact, field-accurate skeleton showing how the spatial ANTLR projections, numeric macro state, open-schema EvolvingWorld state, dynamic pressures, and reasoning outputs fit together inside one WorldSimulationRecord.stateJson:
{
"simConfigVersion": "elthoria_world_sim_v1",
"runId": "sim-104",
"seed": "crown-of-ash-42",
"scaleMode": "Kingdom",
"week": 6,
"season": "Autumn",
"mapAttributes": {
"header": { "title": "Vaelor Border Marches", "scale": "6 miles" },
"mapDefinition": { "coordinateSystem": "offset-odd-r", "width": 5, "height": 3 }
},
"hexMapAttributes": {
"1,1": { "terrain": "r", "locationId": "ashford", "factionControl": "iron_wardens" }
},
"tacticalMapAttributes": {
"grid_cellar_1": { "header": { "title": "Sunken Watchtower Cellar" }, "width": 6, "height": 4 }
},
"macro": {
"continentStability": 0.62,
"warPrevalence": 0.28,
"faminePressure": 0.34,
"tradeConnectivity": 0.51
},
"globalWorldState": {
"dimensions": {
"supply_lines": {
"key": "supply_lines",
"value": "Northern grain wagons are delayed by banditry along the Old King Road.",
"changeability": "Moderate",
"confidence": 0.82,
"lastChangedWeek": 5,
"revisions": 2,
"provenance": ["inc.5.2", "scene.5.1"]
}
}
},
"locationStates": {
"loc.ashford_granary": {
"id": "loc.ashford_granary",
"name": "Ashford Mill & Granary",
"regionId": "region.marches",
"hexCoordinate": "1,1",
"entities": {
"ent.north_gate": {
"id": "ent.north_gate",
"name": "North Timber Gate",
"kind": "Threshold",
"state": "Barred with iron chains since the night raid",
"condition": 0.75,
"visible": true,
"lastChangedWeek": 5
}
}
}
},
"pressurePackets": [
{
"id": "pp.5.1",
"source": "trade_blockade",
"magnitude": 0.65,
"urgency": 0.58,
"visibility": 0.70,
"affectedFactions": ["faction.iron_wardens"],
"affectedLocations": ["loc.ashford_granary"],
"createdWeek": 5
}
],
"delayedConsequences": [
{
"id": "dc.5.1",
"kind": "GuildCreditAftershock",
"scope": "Faction",
"status": "Pending",
"correlationKey": "ashford_supply_crunch",
"createdWeek": 5,
"maturesWeek": 8
}
],
"rumorBeliefs": {
"agent.warden_voss": {
"rumor.4.2": {
"heard": true,
"state": "Spreader",
"belief": 0.74,
"certainty": 0.68,
"heardWeek": 4
}
}
},
"worldFacts": [
{
"atomKey": "supply_strained(region.marches)",
"value": 0.81,
"confidence": 0.90,
"supportingFactKeys": ["road_raided(old_king_road)", "famine_pressure(region.marches)"],
"supportingRuleIds": ["rule.supply_chain_disruption"],
"runId": "crown-of-ash-42:5",
"week": 5,
"observed": false
}
]
}Related developer documentation
- Agent Reasoning & Decision-Making Deep Dive — Full technical walkthrough of epistemic Bayesian ToM, nested QE QBAFs, MRE/WoE/Sensitivity,
WHY_NOT,BeliefReviser, quantitativeSCENARIO/SOLVE_TARGET, and multi-engine weight learning. - Memory Architecture Deep Dive — How Kompile memory,
CampaignMemoryPort, and the living world simulation form the five-layer campaign memory stack. - Living World, Scenes & Lore Tools — Complete MCP tool reference for
WorldSimMcpTools,WorldNarrativeMcpTools,NpcAgentMcpTools, andSceneExperienceMcpTools. - Maps, Hexes & Tactical Boards Tools — MCP tool reference for
HexMcpTools,GridMcpTools, revision-checked boards, and zero-Angular browser board views.