Skip to content

Total Campaign Save State & Persistence Architecture ​

This deep dive maps every persisted byte that makes up a total Elthoria campaign save state across elthoria-harness, elthoria-game, and the upstream Kompile harness — detailing exact filesystem paths, H2 datasource invariants, JPA entity groups, the 4-record living-world persistence schema, the immutable Content Workbench store, learned reasoning weights, partial export boundaries, and safe cold-backup/restore contracts.

TIP

Looking for the plain-English Game Master backup & migration guide? Read Campaign Save Files, Backups & Moving Machines.


Complete Save-State Topology (Four Persistence Planes) ​

A total campaign's durable state spans four cleanly separated persistence planes. Authoritative RPG state lives under ELTHORIA_HOME (default ~/.elthoria); cross-vendor chat transcripts and credentials stay in Kompile's own root (~/.kompile):

text
~/.elthoria/                                     (ELTHORIA_HOME — campaign vault root)
├── data/                                        [Plane 1: Authoritative H2 Relational DB]
│   ├── elthoria.mv.db                           # Single-owner H2 database (WRITE_DELAY=0)
│   └── .elthoria-server.lock                    # Advisory single-writer lock (ServerDataOwnership)
│
├── runtime/                                     [Plane 2: Runtime Weights, Config & WAL]
│   ├── application.properties                   # Optional local overrides (chmod 0600)
│   └── data/
│       ├── worldsim-weights/                    # FileWeightStore: learned PSL / MEBN / QBAF weights
│       │   ├── worldsim-<simId>/                #   PSL rumor/secret/trust/fear/suspicion weights
│       │   ├── worldsim-mebn-<simId>/           #   MEBN narrative propagation weights
│       │   └── worldsim-qbaf-<simId>/           #   QE QBAF per-evidence-kind weights
│       └── wal/                                 # Optional WAL dir (scheduled archiving disabled)
│
└── kompile-harness/                             [Plane 3: Workspace Knowledge, Workbench & Memory]
    ├── data/
    │   ├── input_documents/elthoria/            # Player-safe rulebooks & published derivatives (source)
    │   ├── crawls/kompile-harness-knowledge/    # Reproducible FTS/vector index + graph.kgraph
    │   └── content/                             # Private WorkbenchStore (NOFOLLOW, immutable revisions)
    │       ├── sources/<id>/<rev>/manifest.json #   Registered original PDFs & immutable source metadata
    │       ├── profiles/<id>/<rev>/manifest.json#   Pinned parsing profiles
    │       ├── runs/<id>/<rev>/manifest.json    #   Extraction plans & captured draft outputs
    │       ├── library/<id>/<rev>/manifest.json #   Reviewed/accepted records & publication receipts
    │       └── previews/<id>/<rev>/manifest.json#   Two-step publish / playable-import previews
    ├── .content-workbench.lock                  # Cross-JVM FileLock serializing WorkbenchStore writes
    ├── .kompile/memory/                         # Workspace-local standing GM memory Markdown files
    └── (.mcp.json, AGENTS.md, .kompile/roles/,  # Generated harness wiring (regenerated on launch
         .kompile/skills/)                       #   unless ELTHORIA_HARNESS_SYNC=0)

~/.kompile/                                      [Plane 4: Kompile Global State — Shared Across Vaults]
├── conversations/                               # Provider-neutral ConversationLedger transcripts
│   ├── <session-id>.jsonl                       #   Portable chat history (--continue / --resume / switch)
│   └── <session-id>.model-ladder.json           #   Per-session failover ladder & cooldown state
├── memory/                                      # User-global persistent Kompile memory
└── (credentials / model-ladder.json)            # SECRET — OAuth tokens & API keys (never export!)

Plane 1: Authoritative H2 Relational Database (ELTHORIA_DATA_DIR) ​

Storage Policy & Concurrency Contract (ProductMcpBootstrap) ​

When launched via elthoria, ProductMcpBootstrap enforces strict ownership and durability invariants before Spring Boot touches the database:

  • Datasource URL: jdbc:h2:file:<ELTHORIA_DATA_DIR>/elthoria;DB_CLOSE_ON_EXIT=FALSE;WRITE_DELAY=0
    • WRITE_DELAY=0 flushes committed transactions immediately rather than buffering in H2's delayed-write window.
    • ELTHORIA_DATA_DIR is rejected if it contains ; (prevents H2 URL option injection such as ;AUTO_SERVER=TRUE).
  • Single-writer ownership (ServerDataOwnership): Acquires <ELTHORIA_DATA_DIR>/.elthoria-server.lock before opening elthoria.mv.db (ELTHORIA_ALLOW_CONCURRENT=0). Neither elthoria web nor external GM panels ever open a second H2 owner — they attach to the active runtime via get_play_connection.
  • Symlink hardening: Rejects symlinks (LinkOption.NOFOLLOW_LINKS) on .elthoria-server.lock, elthoria{.mv.db,.h2.db,.lock.db,.trace.db,.temp.db}, runtime/application.properties, and runtime/data/wal.
  • No silent background mutation: elthoria.worldsim.auto-advance.enabled=false and spring.h2.console.enabled=false are pinned on startup.

Complete JPA Entity Inventory (Grouped by Domain) ​

All authoritative RPG state in elthoria.mv.db spans JPA entities in elthoria-domain (ai.elthoria.models.*) and elthoria-app (elthoria-game):

Domain groupAuthoritative JPA Entities / RecordsWhat is persisted
Campaign, Narrative & Rules ConfigGame, Party, Act, Scene, Thread, PlotElement, Challenge, JournalEntry, Note, HistoricalEvent, GroundingAlert, FateChartOutcome, Lorebook, LorebookEntry, RuleEnforcementConfig, RulesSnapshot (SnapshotClass, SnapshotRace, SnapshotFeat, SnapshotSpell, SnapshotItem), DataMigrationCampaign spine, acts/scenes/threads, durable session journal, Lorebook triggers, canon-drift grounding alerts, pinned rules snapshots
Characters, Stats, Gear & SpellsRPGCharacter, StatBlock, Ability, HitDice, CharacterClass, CharacterSkill, CharacterFeat, CharacterSpell, CharacterBuff, BuffLoadout, BuffLoadoutEntry, CharacterProfilePicture, Inventory, InventoryItem, Item, Weapon, Armor, Shield, Accessory, SpellBook, PreparedSpell, SpellSlotUsage, SpellsPerDay, ResourcePool, ResourcePoolLevel, ResourcePoolUsage, UnifiedBonus, UnifiedBonusApplication, BonusSource, CalculatedBonus, ModifierComplete hero sheets, multiclass levels, exact typed bonus graphs, buffs & loadouts, equipped gear, spell slots & class resource pools
System Rules CatalogRPGSystem, RPGClass, ClassFeature, ClassFeatAvailability, LevelFeatGrant, LevelUpRequirements, Race, Feat, Spell, SpellLevel, SpellComponent, SpellEffect, SaveRequirement, Buff, Dice, BonusDice, God, Pantheon, Religion, MagicSystemBase and homebrew d20/Pathfinder-style rules catalog
Combat, Initiative & StealthCombatSession, CombatSessionEntity, CombatantHP, InitiativeTracker, InitiativeEntry, CombatCommandReceipt (combat_command_receipts), StealthMiniGame, StealthNpcStateEntity (stealth_npc_state)Active encounter rounds/turns, HP/nonlethal/dying state, idempotent combat command receipts, GM-only hidden stealth coordinates & movement queues
NPCs & Custom TablesNPC, NPCEncounter, NPCEncounterEntry, NpcAgent, TableRoller (table_rollers), TableRollerEntry (table_roller_entries), PlayableImportReceiptStatblocks, encounter rosters, campaign-to-worldsim NPC links (NpcAgent), weighted custom roll tables, idempotency receipts for Workbench table imports
Maps, Boards & Media RefsHexCampaignMapEntity, HexLocation, HexMap, SavedGrid, SavedMap, Region, Location, PointOfInterest, FactionOrganization, ContentAsset, GeneratedMediaAsset (generated_media_asset)Revisioned overland hex maps, tactical battle grids + linked hexes, campaign regions/factions/POIs, durable media catalog references
Living World Simulation (4-Record Schema)WorldSimulationRecord, WorldSimWeekResultRecord, WorldSimEventLogRecord, WorldSimArtifactRecord (elthoria-world-simulation-persistence-api)Latest optimistic-locked WorldSimState (elthoria_world_sim_v1 stateJson + settingsJson + stateVersion), append-only weekly WeekResult digests, indexed historical event ledger, keyed graph/dossier artifacts
In-App Chat & FoldersChatSession, ChatMessage, ChatAction, ChatFolder, ChatFolderFile, Conversation, ConversationMessage, ConversationReply, PromptTemplate, AgentProvider, CustomIcon, CustomTheme, DefaultSetting, KompileConfig, RemoteInstance, UserEmbedded Elthoria Game chat history, prompt templates, folder file attachments, and UI preferences

Plane 2: Runtime-Relative Learned Weights (ELTHORIA_RUNTIME_DIR) ​

RuleWeightLearningService (in elthoria-world-simulation-engine) persists campaign-adaptive reasoning weights outside the H2 blob via Kompile's FileWeightStore under <ELTHORIA_RUNTIME_DIR>/data/worldsim-weights/:

  • worldsim-<simulationId> — Versioned PSL rule weights (trustSpreadWeight, rumorSpreadWeight, fearSpreadWeight, secretLeakWeight, suspicionFromSecretWeight, skepticPriorWeight) trained by StructuredPerceptronLearner.
  • worldsim-mebn-<simulationId> — Versioned MEBN narrative propagation weights trained by MebnWeightLearner.
  • worldsim-qbaf-<simulationId> — Versioned per-evidence-kind Quadratic-Energy QBAF dialectical weights trained by QbafWeightLearner.

Because each program is versioned per simulationId, losing runtime/data/worldsim-weights/ does not corrupt WorldSimState canon — the engine falls back cleanly to default weights — but backing it up preserves the campaign's learned tone and GM feedback history.


Plane 3: Workspace Knowledge, Private Workbench & GM Memory (ELTHORIA_WORKSPACE) ​

  1. Player-Safe Retrieval Sources (data/input_documents/elthoria/):
    • Strictly validated as a descendant of data/input_documents/ (no symlinks).
    • Holds user-owned Markdown/text rulebooks and explicitly published player_safe derivatives from the Content Workbench.
  2. Reproducible Crawl Index & Knowledge Graph (data/crawls/kompile-harness-knowledge/):
    • Contains the folder-scoped lexical/vector index and graph.kgraph.
    • Regenerable: Can be excluded from compact backups and rebuilt deterministically via elthoria crawl --pipeline-id standard-text (note: Content Workbench index_verify receipts pin the corpus baseline, so if you exclude data/crawls/ from a backup, re-run index_plan / crawl after restore).
  3. Private Immutable Content Workbench (data/content/ via WorkbenchStore):
    • Serialized across threads and JVMs with a ReentrantLock + POSIX FileLock on .content-workbench.lock.
    • All reads, writes, and renames use SecureDirectoryStream + LinkOption.NOFOLLOW_LINKS.
    • Append-only optimistic concurrency (expectedRevision) writes immutable manifests at data/content/<collection>/<id>/<revision>/manifest.json across five collections: sources, profiles, runs, library, and previews.
    • Never crawled automatically — keeps original user-owned PDF bytes and unpublished GM drafts strictly isolated from player search.
  4. Workspace GM Memory (.kompile/memory/):
    • Standing Markdown notes scoped to this Elthoria workspace (house rules, pacing preferences, campaign conventions).

Plane 4: Kompile Transcripts & Global State (~/.kompile/) ​

Kompile intentionally separates conversation transcripts and provider auth from the RPG vault:

  • ~/.kompile/conversations/ stores the provider-neutral ConversationLedger transcripts (enabling elthoria chat --continue, elthoria chat --resume <id>, mid-conversation vendor switching, and per-session <id>.model-ladder.json failover state).
  • Decoupled from RPG canon: A campaign in ~/.elthoria/data/elthoria.mv.db is 100% playable without its old Kompile transcripts — opening a new chat and calling /elthoria-play + /elthoria-recap reconstructs player-facing context directly from authoritative Elthoria state.
  • Credentials boundary: ~/.kompile/ also holds OAuth tokens, API keys, and global model-ladder.json. Never bundle ~/.kompile/ into a shareable campaign archive.

Classification Matrix: Authoritative vs. Regenerable vs. Private/Secret ​

Artifact / DirectoryAuthoritative?Regenerable?Contains GM secrets?Contains user credentials?Include in full cold backup?
ELTHORIA_DATA_DIR/elthoria.mv.dbYes (primary)NoYes (stealth, hidden world state, GM notes)NoRequired (only while stopped!)
ELTHORIA_DATA_DIR/.elthoria-server.lockNo (runtime lock)YesNoNoSkip
ELTHORIA_RUNTIME_DIR/data/worldsim-weights/Learned stateResets to defaultsNoNoRecommended
ELTHORIA_WORKSPACE/data/input_documents/elthoria/Yes (sources)NoNo (player_safe only)NoRequired
ELTHORIA_WORKSPACE/data/content/Yes (workbench)NoYes (raw PDFs, unpublished drafts)NoRequired (omit if sharing player-safe)
ELTHORIA_WORKSPACE/data/crawls/<kb>/Derived indexYes (elthoria crawl)No (player_safe only)NoOptional (saves space)
ELTHORIA_WORKSPACE/.kompile/memory/Yes (GM notes)NoPossiblyNoRecommended
ELTHORIA_WORKSPACE/.mcp.json, AGENTS.md, .kompile/{roles,skills}/GeneratedYes (on launch)NoNoSkip (unless ELTHORIA_HARNESS_SYNC=0)
~/.kompile/conversations/<id>*Chat historyNo (canon survives without it)PossiblyNoOptional (per-session only)
~/.kompile/ auth & configAuth stateRe-loginNoYESNEVER share

Partial Exports vs. Total Campaign Backup ​

Elthoria ships three targeted export services in elthoria-game for content portability, not full disaster recovery:

ServiceOutput formatScopeWhat it intentionally excludes
ImportExportService (ContentIoRuntime)ContentBundle JSON10 authoring ContentType catalogs (RPG_CLASSES, RACES, FEATS, SPELLS, BUFFS, ITEMS, WEAPONS, ARMORS, ACCESSORIES, CLASS_FEATURES)Campaigns, characters, combat, maps, living world, journals, Lorebooks, PDF workbench
CharacterExportServiceSQL (INSERT + identity resets)Selected RPGCharacter rows + statblock, abilities, hit dice, inventoryWorld simulation, boards, campaign journal, other rules catalogs
GameMechanicsExportServiceSQL (INSERT + identity resets)Rules/mechanics tables (RPGSYSTEM, RPG_CLASS, FEATS, SPELLS, ITEM, BUFF, GOD, etc.)Characters, character-dependent state, living world, boards

Safe Cold-Backup & Vault Isolation Contract ​

  1. Always stop the server before copying elthoria.mv.db: Even with WRITE_DELAY=0, copying an open H2 MVStore file while a JVM holds .elthoria-server.lock risks an inconsistent snapshot. Shut down elthoria / elthoria web cleanly first.
  2. Preserve NOFOLLOW regular-file invariants on restore: Do not replace elthoria.mv.db, data/input_documents/elthoria, data/content/, or data/crawls/ with symlinks — ProductMcpBootstrap and WorkbenchStore fail closed on symlinked data paths.
  3. Multi-vault isolation via ELTHORIA_HOME: Because ELTHORIA_DATA_DIR, ELTHORIA_RUNTIME_DIR, and ELTHORIA_WORKSPACE all default under ELTHORIA_HOME, setting a dedicated ELTHORIA_HOME creates a completely self-contained campaign vault (independent H2 database, weights, bookshelf, crawl KB, and Content Workbench) with zero cross-contamination.

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