Skip to content

Persistent History, Causal Propagation & Decision Impact ​

This deep dive documents how elthoria-world-simulation-model, elthoria-world-simulation-engine, and elthoria-world-simulation-persistence-api maintain durable, deterministic world history and translate player/character decisions into physical room changes, buffered profile evolution, delayed aftershocks, compound crises, epistemic belief revision, and bidirectional macro-micro propagation.

TIP

Looking for the plain-English Game Master overview? Read Persistent History & How Player Choices Change the World.


Architecture: How Decisions Become Permanent History ​

text
  CHARACTER / TABLE DECISION
  ├── Freeform table event (report_world_event / auto-hooks) ──► InboundWorldEvent
  ├── Weekly party choice / story candidate commit           ──► PartyAction (25 ActionIds)
  └── Played scene turns & NPC dialogue                      ──► Scene + SceneTurn
                                         │
          ┌──────────────────────────────┼──────────────────────────────┐
          ▼                              ▼                              ▼
  1. IMMEDIATE TRUTH             2. WEEKLY TICK PIPELINE        3. SCENE EVOLUTION
  IngestionSystem                WorldSimEngine.simulateWeek    SceneDirector
  .applyImmediateEffects()       ├── applyInboundWorldEvents    ├── WorldStateUpdateSystem
  • Local mutation NOW           │   (reactions, no double-     │   (EntityState wear/state,
    (death, town status,         │    write if immediateApplied)│    LocationChange, locality,
    party casualty)              ├── PartyActionSystem          │    GlobalWorldState >= 0.6)
  • immediateApplied=true        ├── ConsequenceSystem          └── EvidencePromoter
  • Visible immediately in       │   (Pending → Matured +           (HiddenTracker signals →
    WorldSimulationContext       │    correlationKey compound        threshold-gated permanent
    Formatter ("Since the        │    crises)                        OpenSchemaProfile updates
    last week turned")           ├── RumorSystem + TruthMaint.       on NPCs, Factions, Houses,
                                 ├── PropagationSystem               and Places)
                                 │   (Upward hop-decay +
                                 │    Downward polity→region
                                 │    →settlement cascade)
                                 └── MacroWorld & Collapse
                                         │
                                         ▼
  4. FOUR-LAYER DURABLE HISTORY (H2 via elthoria-world-simulation-persistence-api)
     ├── WorldSimulationRecord       (latest optimistic-locked WorldSimState JSON)
     ├── WorldSimWeekResultRecord    (append-only weekly visibility-filtered digests)
     ├── WorldSimEventLogRecord      (append-only queryable SimEvent ledger)
     └── WorldSimArtifactRecord      (weekly application/vnd.kompile.unified-graph archives)

1. The Six Layers of Persistent World History ​

1.1 Physical Locality & Room Permanence (WorldStateUpdateSystem) ​

  • During played scenes, WorldStateUpdateSystem.applyTurn applies physical wear (condition -= wear) and state transitions directly onto each mutated EntityState inside a LocationState, stamping lastChangedWeek and lastChangedSceneId and appending an immutable LocationState.LocationChange record (week, sceneId, turnIndex, entityId, summary, causeActorId).
  • When a scene closes, applyScene stores the room's aftermath mood and emits SimEvent.Type.LOCATION_STATE_UPDATED.
  • Locality invariant: Locations that hosted no scene carry their exact LocationState and EntityState forward untouched across weeks — nothing drifts merely because time passed elsewhere.

1.2 Buffered Open-Schema Evolution (EvidencePromoter & HiddenTracker) ​

  • Characters (CharacterEvolutionSystem), factions and noble houses (GroupEvolutionSystem), and towns/provinces (PlaceEvolutionSystem) share a single gate: EvidencePromoter.promote(state, scene, subject, maxPromotions, thresholdScale).
  • Instead of rewriting an NPC or faction on one noisy turn, scene outcomes accumulate HiddenSignal entries in each subject's HiddenTracker.
  • A signal promotes into a permanent OpenSchemaDimension update only when signal.weight >= dimension.evidenceThreshold() * thresholdScale (and only if dimension.isEvolvable()).
  • Ready signals are sorted by descending weight (tie-broken by ID) and capped at maxPromotions per scene so no actor or faction lurches abruptly. Each promoted dimension retains confidence = min(1.0, 0.4 + reinforcements * 0.15), promotedWeek, and up to 8 provenance source refs. Sub-threshold reinforcements emit private HIDDEN_SIGNAL_ACCUMULATED (visibility = 0.0) ledger entries.

1.3 Global Prose History (GlobalWorldState) ​

  • WorldStateUpdateSystem.applyScene computes consequenceOf(scene) and only lifts a scene into GlobalWorldState when consequence >= 0.6 (for example, a high-tension ScenarioResolved or an open public breach).
  • Updates write to open-schema global dimensions (e.g., open_conflicts) and append to a bounded changeLog.

1.4 Append-Only Event Ledger & Weekly Digests (SimEvent, WorldSimEventLogRecord, WorldSimWeekResultRecord) ​

  • Every simulation subsystem appends typed SimEvent entries (week, type, actorId, targetId, sourceId, severity, visibility, tags, payload) to WorldSimState.eventLedger.
  • Persistence writes two append-only historical tables per week:
    • WorldSimWeekResultRecord: Serialized WeekResult digest separating Direct (majorEvents), Report/SecondhandRumor (newIncidents), and Trace/DistantTrace (traces) while excluding Hidden incidents from player-facing views.
    • WorldSimEventLogRecord: Queryable historical ledger indexed by simulationId, gameId, week, npcId, characterId, and locationRef — backing get_world_chronology (WorldSimulationChronologyPort, default event_limit = 100, max 500) and get_world_event_log.

1.5 Immutable Weekly Unified-Graph Archives (WorldSimArtifactRecord & query_historical_world_graph) ​

  • Each simulated week persists a application/vnd.kompile.unified-graph binary artifact keyed by (simulationId, week) in WorldSimArtifactRecord.
  • query_historical_world_graph executes bounded, read-only graph queries (intent, entity_id, target_id, relation_type, query_text, max_depth, top_k) against any archived past week without touching live WorldSimState (missing or corrupt archives fail closed with an explicit error).
  • get_world_sim_unified_graph_archive exposes raw metadata and base64 archive bytes for external tooling.

1.6 Campaign Journal & Lorebook Persistence (JournalEntry, Lorebook, HistoricalEvent) ​

  • Human/GM-authored narrative canon sits in H2 alongside the simulation tables, feeding spoiler-free /elthoria-recap reads and keyword-triggered get_activated_entries recall without mutating numeric simulation vectors.

2. How Character Decisions Propagate Into the World ​

2.1 Two-Phase Live Event Ingestion (IngestionSystem & InboundWorldEvent) ​

Freeform table outcomes enter the living world via report_world_event or gameplay auto-hooks as InboundWorldEvent records (NPC_DEATH, NPC_STATUS_CHANGE, LOCATION_STATUS_CHANGE, FACTION_EVENT, PARTY_MEMBER_DEATH, PARTY_MEMBER_STATUS, CUSTOM_GM_EVENT):

  1. Phase 1 — Immediate Local Truth (IngestionSystem.applyImmediateEffects):
    • Runs synchronously outside the weekly tick, writing only order-independent local state (this NPC is dead, this town burned, this party member fell) and setting immediateApplied = true.
    • Never spawns rumors, succession, or RNG-dependent ripples — keeping weekly ticks bit-for-bit reproducible.
    • Surfaces immediately in WorldSimulationContextFormatter under Since the last week turned (already true — react to it) and Party members the world has news of.
  2. Phase 2 — Deterministic Weekly Reaction (IngestionSystem.applyInboundWorldEvents):
    • Drains pendingWorldEvents in exact submission order (deliberately unsorted — submission order is the external-event determinism contract).
    • Skips local mutation when immediateApplied == true (localOwed = !event.isImmediateApplied()), executing only the world reaction (reactToNpcDeath, reactToLocationStatusChange, reactToFactionEvent, reactToPartyMemberStatus, etc.) and appending WORLD_EVENT_INGESTED.

2.2 Weekly Party Actions (PartyActionSystem) & Counterfactual Story Branches ​

PartyActionSystem.resolvePartyAction(state, action) resolves all 25 PartyAction.ActionId values (scaled by intensity ∈ [0, 1], recording PARTY_ACTION on the ledger):

CategoryPartyAction.ActionId valuesPrimary world mutations
Civic & RealmAidCommoners, FundRelief, CourtAudience, PetitionTempleparty.reputation, feedback.commonerUnrestPressure, partyHouse.wealth, partyAgent.influence / scandal
Social & RelationshipsSocialVisit, SpendTimeWithNpc, HostGathering, NegotiateAlliance, RecruitAllyBidirectional 8-axis RelationshipVector (affinity, trust, etc.) + RelationshipProvenance, publicVector.attention, localGossipHeat
Information & RumorsGatherInformation, InvestigateRumor, SpreadRumor, SuppressRumor, HuntQuestCluepartyAgent.information, rumor virality/truthValue/belief states, localGossipHeat, quest clue links
Direct & Covert ActionConfrontRival, ProtectTarget, BribeOfficialTarget hostility/suspicion, scandal exposure, schedules aggressive DelayedConsequence records
Assets, Training & TravelTradeVenture, ManageAssets, PayDownDebt, FortifyBase, StudyOrTrain, RestAndRecover, TravelToRegion, WaitAndObservepartyHouse wealth/debt/security, deterministic RNG skill growth (SimKeys.SKILLS), stress recovery, overland travel
  • Counterfactual Previews (preview_world_story_choice → choose_world_story_candidate / reject_world_story_candidate):
    • Previews clone WorldSimState in isolation, simulate committing the candidate's PartyAction (choiceId, branchKey, sourceEventIds, sourcePressurePacketIds, sourceSituationIds), and return the delta without mutating persisted state.
    • Committing (choose_world_story_candidate) or declining (reject_world_story_candidate) updates party disposition and removes the candidate from the active set.

2.3 Delayed Aftershocks & Compound Crises (ConsequenceSystem) ​

Consequences do not all fire on the same turn a decision is made:

  1. Scheduling (scheduleDelayedConsequencesFromCurrentWeek): Every current-week ObservableIncident with severity >= 0.45 — plus aggressive PartyActions — schedules a Pending DelayedConsequence with a future maturesWeek, optional expiresWeek, scope (Party | House | Faction | Province | Government | Polity | World), kind (HouseDebtAftershock, TempleInquiryAftershock, WarMobilizationAftershock, SpyBlowbackAftershock, etc.), and correlationKey.
  2. Maturation (processDelayedConsequences): Iterates due Pending consequences (maturesWeek <= week) sorted by ID, flips status to Matured, applies state impact, spawns a follow-up PressurePacket, and appends DELAYED_CONSEQUENCE_MATURED. Past-deadline items mark Expired.
  3. Compound Escalation: Overlapping matured/pending consequences sharing a correlationKey correlate into compound crises (CompoundHouseCrisis, CompoundFactionCrisis, CompoundPolityCrisis).

2.4 Bidirectional Propagation & Epistemic Belief Revision (PropagationSystem, RumorSystem, TruthMaintenanceService) ​

  • Upward (PropagationSystem.applyUpwardEventPropagation):
    • Scans current-week SimEvent entries with severity >= upwardResonanceCutoff.
    • Applies scaled desperation/opportunity to the actor's faction (upwardDirectFactionScale), propagates up the parent-faction hierarchy decaying by upwardHopDecay per hop until upwardHopFloor (bounded by SimMath.hopBudget), and feeds government/royal-court shifts into PolityState legitimacy and successionPressure (upwardGovernmentScale, soft-capped by factionReactionPressureSoftCap).
  • Epistemic Spread & Debunking (RumorSystem + TruthMaintenanceService):
    • Rumors propagate across the social graph via subjective-logic SimOpinion beliefs (Ignorant, Spreader, BelieverSilent, Skeptic, Stifler).
    • When a character exposes or debunks a claim, TruthMaintenanceService runs BeliefReviser.retractReviseAndPurge over the JustificationIndex — purging solely-dependent derived WorldFacts while retaining and MAP-downgrading facts still supported by independent evidence.
  • Downward (PropagationSystem.applyDownwardPropagation):
    • On the next tick, updated PolityState (collapseRisk, corruption) and MacroWorldState (warPrevalence) trickle back down to every sorted SimRegion (localUnrest += collapseRisk * 0.015 + war * 0.01, safety -= war * 0.015 + collapseRisk * 0.01, lawOrder -= corruption * 0.008, militaryPresence += war * 0.02), every SimSettlement (security, lawOrder, unrestRisk), and faction morale fear (+= collapseRisk * 0.01) — closing the macro ↔ micro causal loop.

Determinism & Debugging Invariants ​

  • Strict sorted iteration before RNG: All consequence queues, regions, settlements, factions, and skill lists sort deterministically by stable string ID before calling SimRng(seed, simConfigVersion, week).
  • Submission-order contract for external events: IngestionSystem preserves the exact submission order of pendingWorldEvents without re-sorting.
  • Causal auditability: Every weekly tick stamps a canonical SHA-256 hash into WeekResult.debug and records WorldFact derivations (supportingFactKeys, supportingRuleIds, runId = "seed:week") powering explain_world_fact and WHY / WHY_NOT / PATH queries.

Key Source Files ​

  • Two-phase event ingestion: elthoria-world-simulation-engine/.../systems/IngestionSystem.java
  • Weekly party decisions: elthoria-world-simulation-engine/.../systems/PartyActionSystem.java, elthoria-world-simulation-model/.../PartyAction.java
  • Delayed & compound crises: elthoria-world-simulation-engine/.../systems/ConsequenceSystem.java
  • Upward/downward cascade: elthoria-world-simulation-engine/.../systems/PropagationSystem.java
  • Room permanence & global prose: elthoria-world-simulation-engine/.../scene/WorldStateUpdateSystem.java
  • Threshold-gated profile permanence: elthoria-world-simulation-engine/.../scene/EvidencePromoter.java
  • Chronology & historical graph MCP tools (in elthoria-game): WorldSimMcpTools.java (get_world_chronology, query_historical_world_graph, get_world_sim_unified_graph_archive, report_world_event) and WorldNarrativeMcpTools.java (preview_world_story_choice, choose_world_story_candidate, reject_world_story_candidate)

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