Skip to content

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:

  1. The two ANTLR4 Map DSL grammars (elthoria-map-dsl) — TTRPGMap.g4 for tactical/dungeon square grids and HexMap.g4 for overland campaign hex maps, plus their parser, fallback, and DTO extraction pipeline.
  2. 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:

text
┌──────────────────────────────────────────────────────────────────────────────┐
│  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) ​

CategoryGrammar section markersPurpose
Core structure## HEADER, ## GRID_DEFINITION, ## GRIDMap metadata (Title, Author, Campaign, Scale, etc.), grid dimensions/legend, and row-by-row ASCII cell grid
Party & combat## PARTY, ## ENTITY_STATS, ## ENTITIES, ## ENCOUNTERSPlayer 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, ## MARKERSInteractive 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_STATUSNamed 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, ## LEGENDSQuests, structured objectives, narrative background, story hooks, and free-form map legends

Tactical grid cell symbols (## GRID) ​

SymbolMeaningSymbolMeaning
#Wall (impassable)~Water / Difficult terrain
.Floor (traversable)^Mountain / High obstacle
+Door*Forest / Foliage
>Stairs DownTTrap
<Stairs UpPPuzzle / Secret
SSecret DoorLLoot / Treasure
XObstacle / PillarMMarker (user-defined)
OPit / 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 ​

text
## 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 ring

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

  1. preprocessAntlrText(text) — strips fenced code blocks (```), canonicalizes ## <section> casing and spacing, and ensures a trailing newline.
  2. Strict ANTLR4 parse — TTRPGMapLexer → CommonTokenStream → TTRPGMapParser.dungeon() → ParseTreeWalker.walk(TTRPGMapDataExtractor, tree) → extractor.linkEntitiesToStatBlocks().
  3. Graceful fallback (fallbackSectionParse) — if ANTLR encounters syntax errors or returns incomplete sections, regex-based section extractors recover HEADER, ROOMS, PASSAGES, TRAPS, LOOT, PUZZLES, ENTITY_STATS, and ENTITIES so 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) ​

RequirementSection markerKey fields / entries
Required (1)## HEADERtitle (quoted), created (ISO datetime), campaign, scale (<int> <unit>, e.g. 6 miles), season, date
Required (2)## MAP_DEFINITIONcoordinate_system (offset-odd-r, offset-even-r, axial, or cube), width, height
Required (3)## HEX_GRIDRow-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, ## METADATASettlements & 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) ​

CodeTerrainCodeTerrain
PPlainsTTundra
FForestJJungle
MMountainsCCoast
HHillsVVolcanic
DDesertrRoad
SSwampdDungeon entrance
WWater / Ocean / LakeXImpassable
RRiver.Void / Empty
?Unexplored (fog of war)

Minimal valid HexMap.g4 example ​

text
## 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 fieldTypeSource & role
mapEntityId / managedMapEntityIdsLong / List<Long>Campaign DB primary hex map ID and any simulator-managed tactical/region map IDs (masked from deterministic state hash)
mapAttributesMap<String, Object>Full HexMap.g4 projection (header, map definition, terrain grid, locations, connections, factions, regions)
hexMapAttributesMap<String, Map<String, Object>>Per-coordinate ("x,y") derived spatial layer index for fast lookup by travel, incidents, and location state
tacticalMapAttributesMap<String, Map<String, Object>>Full TTRPGMap.g4 projections keyed by tactical grid ID
tacticalCellAttributesMap<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 ​

GroupFieldsWhat changes over time
Identity & clocksimConfigVersion, runId, seed, scaleMode, week, season, gameSettings, difficultyTuning, feedbackweek increments each tick; season derives from Season.forWeek(week); difficultyTuning and feedback adapt to campaign pressure
Spatial projectionsgameId, mapEntityId, managedMapEntityIds, mapAttributes, hexMapAttributes, tacticalMapAttributes, tacticalCellAttributesMirrors HexMap.g4 and TTRPGMap.g4 state as terrain, locations, or tactical scenes evolve
Macro cast & geographyagents, 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 layerglobalWorldState, locationStates, sceneTrajectoryOpen-schema prose world dimensions (GlobalWorldState), nested physical locations and props (LocationState → EntityState), and rolling played-scene history (SceneTrajectory)
Dynamic pressures & timependingWorldEvents, pressurePackets, activeSituations, activeIncidents, activeConversations, activeDeadlines, delayedConsequencesCampaign-injected events, active pressures, visible/hidden incidents, ticking deadlines, and scheduled future aftershocks
Beliefs, intrigue & social webrumors, rumorBeliefs, relationships, relationshipProvenance, intrigueSecretsCirculating rumors with subjective-logic opinions (SimOpinion), 8-dimensional directed agent relationships with provenance, and secret knowledge graphs
Reasoning, quests & auditgraphSnapshot, predicamentHierarchy, worldFacts, eventLedger, tableOracle, quests, narrativeCandidateDispositions, objectiveLedger, lastKgeWeek, emergingTiesWeekly 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:

  1. Sorted-ID iteration: WorldSimState exposes non-getter deterministic traversal helpers (sortedAgentIds(), sortedFactionIds(), sortedHouseIds(), sortedRegionIds(), sortedSettlementIds(), sortedLoreObjectIds(), sortedRumorIds(), sortedSecretIds()) so iteration order never depends on hash buckets when consuming the seeded SimRng. Non-getter names also stay out of Jackson JSON serialization.
  2. Canonical SHA-256 hash (WeekResultBuilder#hashState): After each week, WeekResultBuilder serializes WorldSimState with an ObjectMapper configured with SORT_PROPERTIES_ALPHABETICALLY and ORDER_MAP_ENTRIES_BY_KEYS, then computes a SHA-256 hex digest.
  3. 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, managedMapEntityIds
    • quests (keyed by DB-generated campaign thread IDs)
    • mapAttributes.header.created (wall-clock map creation timestamp)
    • emergingTies (advisory KGE link forecasts)
    • graphSnapshot.attributions and graphSnapshot.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 on GlobalWorldState.dimensions and 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:
ChangeabilityEvidence thresholdIntended timescale
Fast0.6Mood, immediate intent — can shift in a single scene
Moderate1.6Attitudes, working relationships — requires reinforcing scenes
Slow3.2Personality, 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-character EntityState objects (Kind: Fixture, Prop, Hazard, Resource, Threshold, Vehicle, Remains, Sign) with prose state, condition (1.0 pristine → 0.0 destroyed), visible, lastChangedWeek, and lastChangedSceneId.
  • SceneTrajectory:
    • Retains a rolling window of played Scene objects (totalScenes counts the lifetime total) plus TrajectoryMetrics. Older scenes can be dropped from the window without losing world memory because their durable effects are already written into GlobalWorldState, LocationState, EntityState, and character profiles.

2.4 Dynamic Pressures, Beliefs, Causality & Temporal Change ​

Between ticks and across weeks, state transitions flow through five specialized data structures:

  1. 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 (from API, AUTO_HOOK, or UI).
    • Phase 1 (immediate): When a player kills an NPC or burns a granary at the table, the local truth is written immediately and immediateApplied = true is set so the GM and UI see it right away.
    • Phase 2 (next weekly tick): IngestionSystem consumes pendingWorldEvents and triggers the world's reaction (rumors, grief, succession, delayed consequences) under deterministic tick ordering without double-applying the local mutation.
  2. Pressures & compound consequence chains (PressurePacket, DelayedConsequence)
    • PressurePacket models a directional unit of stress (source: war, famine, debt, rumor, scheme, relationship, deadline, succession, temple, trade_blockade, uprising, corruption, collapse) with magnitude, urgency, visibility, volatility, emotionalCharge, and affected agents/factions/locations.
    • DelayedConsequence schedules future fallout (createdWeek → maturesWeek, optional expiresWeek, Status: Pending | Matured | Resolved | Expired) across scopes (Party, House, Faction, Province, Government, Polity, World). Related consequences share a correlationKey so ConsequenceSystem can escalate overlapping aftershocks into compound crises (CompoundHouseCrisis, CompoundFactionCrisis, CompoundPolityCrisis, etc.).
  3. Rumors & subjective-logic beliefs (Rumor, RumorBelief)
    • Rumor tracks a circulating claim (27 ClaimType values from treason and war_profiteering to planted_falsehood and spy_leak) with ground truthValue, virality, decayRate, distortion, evidenceQuality, politicalUtility, and scandalValue.
    • RumorBelief (keyed agentId → rumorId) tracks each agent's epistemic state (Ignorant, Spreader, BelieverSilent, Skeptic, Stifler) backed by an authoritative subjective-logic SimOpinion (belief = opinion.expectation(), certainty = 1.0 - opinion.uncertainty).
  4. 8-dimensional directed relationships (RelationshipVector)
    • Keyed fromAgentId → toAgentId, storing eight normalized [0, 1] axes: affinity, attraction, envy, fear, obligation, respect, suspicion, and trust, paired with relationshipProvenance entries explaining what shifted each axis.
  5. Reasoning, facts & contradiction diagnostics (GraphSnapshot, WorldFact)
    • GraphSnapshot is an app-owned POJO projection of the weekly intrigue graph (typed Nodes and Edges, Louvain communities, rankedNodes, PSL influenceResults with KKT traceContext, OWL RL worldInconsistencies, Belnap beliefContension / beliefConflictCount / claimReports, and lore claimDossiers).
    • WorldFact records both observed evidence (observed = true) and FOL-derived facts (observed = false) with atomKey, value, confidence, supportingFactKeys, supportingRuleIds, and normalized runId ("seed:week") powering explain_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:

text
 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 to state.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 a payload map.
  • WeekResult (returned to GM / persisted per week): Visibility-filtered GM digest separating Direct incidents (majorEvents), Report/SecondhandRumor (newIncidents), and Trace/DistantTrace (traces) while keeping Hidden incidents out of player-facing views, plus worldChanges, relationshipChanges, deadlineChanges, npcConversations, graph/Belnap/OWL RL insights, gameplayChoices (with ChoiceContinuity and ChoiceVisibility spoiler gates: Known | Suspected | Unknown | SpoilerLocked), staged scenes, trajectoryMetrics, metrics, and debug (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 LayerElthoria Service(s)Kompile Primitives UsedWhat It Computes
Epistemic Theory-of-MindBeliefWorldServiceSubgraphMaterializer, BayesianNetwork (NoisyOrCpt), VariableElimination, MostRelevantExplanation, WeightOfEvidence, ProbabilisticContradictionDetectorMaterializes 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 ArbitrationPolicyCollisionSearch, CombatTacticalDecisionService, GraphReasoningSystemNested Qbaf, QeSemantics, AdjudicatorConfig.qe(), DossierAdjudicator, QbafWeightLearnerSmooth 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 PlanningActorKnowledgeGate, PolicyCollisionSearch, SceneMotivationSystemSubgraphMaterializer, shortest social path, Brandes betweenness centralityPrevents 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 AbductionWorldInsightService, TerminalStateSystemSensitivityAnalyzer, InformationGainEstimator, MostRelevantExplanation, WeightOfEvidenceSpies 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 & CounterfactualsTruthMaintenanceService, CandidateReasoningService, WorldQuantitativeScenarioServiceBeliefReviser.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 LearningRuleWeightLearningService, NarrativeInferenceServiceStructuredPerceptronLearner, MebnWeightLearner, QbafWeightLearner, FileWeightStoreVersions 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:

RecordLifecycleKey columns / fieldsRole
WorldSimulationRecordMutable 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, stateVersionAuthoritative latest WorldSimState JSON document + settings
WorldSimWeekResultRecordAppend-only (one row per simulated week)id, simulationId, week, resultJson, createdAtSerialized WeekResult digest for fast weekly recaps without re-simulating
WorldSimEventLogRecordAppend-only queryable ledgerid, simulationId, gameId, week, type, source, severity, summary, applied, npcId, characterId, locationRef, detailsJson, createdAtDurable historical timeline indexed by NPC, character, location, and week (get_world_chronology, get_world_event_log)
WorldSimArtifactRecordKeyed upsert (simulationId + artifactKey)id, gameId, simulationId, week, kind, artifactKey, name, contentType, payloadJson, payloadBytes, createdAt, updatedAtDerived 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:

json
{
  "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
    }
  ]
}

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