Persistent NPC Architecture, Attributes & Lifecycle
This deep dive documents how persistent NPCs are represented, persisted, promoted from campaign data, and evolved over time across elthoria-domain, elthoria-world-simulation-model, and elthoria-world-simulation-engine.
TIP
Looking for the plain-English Game Master guide to persistent NPCs? Read How Persistent NPCs Work.
Two-Layer NPC Persistence Model
Elthoria keeps campaign-side NPC records cleanly decoupled from simulation-side SimAgent state, bridged by explicit foreign IDs and MCP tools (NpcAgentMcpTools):
┌──────────────────────────────────────────────────────────────────────────────┐
│ Campaign Database (JPA / H2 — `elthoria-domain`) │
│ │
│ NPC (tactical statblock, sheet, bio, location, campaign status) │
│ └── NpcAgent (`npc_agents` table) │
│ • id, npcId, gameId, campaignId, name, enabled │
│ • agentType: ANTAGONIST | FACTION_LEADER | ALLY | QUEST_GIVER | │
│ MERCHANT | DIALOGUE | AMBIENT │
│ • autonomyLevel: FULLY_AUTONOMOUS | SEMI_AUTONOMOUS | CONTROLLED │
│ • decisionFrequency: EVERY_SCENE | EVERY_ACT | EVERY_SESSION | MANUAL │
│ • dispositionToParty, primaryGoal, currentActivity, currentPlan, │
│ knownFacts, secrets, relationships │
└────────────────────────────────────┬─────────────────────────────────────────┘
│ register_npc_agent / update_npc_agent
│ (sourceNpcId, sourceNpcAgentId)
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ Living World Snapshot (`WorldSimulationRecord.stateJson` → `WorldSimState`) │
│ │
│ SimAgent (`state.agents.get(agentId)`) │
│ • Identity & linkage: id, name, role, tier (A/B/C), status, │
│ sourceNpcId, sourceNpcAgentId, houseId, factionId, factionIds, │
│ locationId (region), sceneLocationId (LocationState) │
│ • Numeric state: traits (12), needs (9), resources (4), skills (10), │
│ publicVector (attention, scandal, virtue) │
│ • Persistence & growth: persistent, importance [0,1], importanceTags, │
│ experience (capped at 50.0/bucket), personalEvents (cap 40) │
│ • Agency & memory: goals (cap 4), continuity (AgentContinuity), │
│ lastArbitration (PolicyArbitration), lastPosteriors (ToM map) │
│ • Narrative evolution: profile (OpenSchemaProfile), │
│ hiddenTracker (HiddenTracker), sceneMotivation │
└──────────────────────────────────────────────────────────────────────────────┘Because SimAgent lives inside WorldSimState (serialized to WorldSimulationRecord.stateJson with optimistic locking via stateVersion), every attribute, relationship, belief, personal event, and hidden profile signal survives server restarts and can be cloned deterministically for counterfactual previews (preview_world_story_choice).
Complete SimAgent Attribute Reference
1. Classification, Linkage & Lifecycle Status
| Field | Type / Values | Semantics |
|---|---|---|
id | String | Deterministic world-sim ID (e.g. "agent.voss"), used for all cross-references and sorted iteration |
role | AgentRole: PARTY, FAMILY, RIVAL, ALLY, ANTAGONIST_CANDIDATE, FACTION_HEAD, QUEST_TARGET, SIDE_NPC | Narrative/structural role; PARTY is the focal party agent |
tier | ActorTier: A, B, C | Fidelity tier: A = full multi-solver planning + Bayesian ToM; B = reduced planning; C = ambient reaction only |
status | AgentStatus: ACTIVE, DEAD, MISSING, DEPARTED | isActive() is status == ACTIVE; inactive agents stop planning and reacting |
sourceNpcId / sourceNpcAgentId | Long (nullable) | Campaign JPA linkage to NPC.id and NpcAgent.id; automatically grants +0.30 importance and forces persistent = true when sourceNpcAgentId != null |
houseId / factionId / factionIds | String / List<String> | Household and multi-faction memberships (multi-faction membership across tense factions feeds DoubleAgentRisk derivation) |
locationId / sceneLocationId | String | locationId = macro SimRegion ID; sceneLocationId = micro LocationState ID for staged scenes |
2. Canonical Numeric Vectors (SimKeys, all normalized [0, 1])
Dynamic map storage (Map<String, Double>) lets GeneticPlanSearch, PolicyCollisionSearch, and NpcDevelopmentSystem address every attribute uniformly by canonical key:
Map on SimAgent | Default fallback | Canonical keys (SimKeys) |
|---|---|---|
traits (12) | 0.5 | ambition, cowardice, cruelty, curiosity, discipline, dutyBias, empathy, jealousy, opportunism, piety, pride, romanticism |
needs (9) | 0.5 | affection, autonomy, certainty, legitimacy, revenge, security, status, stress, wealth |
resources (4) | 0.3 | information, influence, money, reputation |
skills (10) | 0.3 | charisma, commerce, divinePower, etiquette, intelligence, magic, politics, resilience, stealth, swordplay |
3. Public Standing (PublicVector) & Directed Social Web
PublicVector:attention(default0.2),scandal(default0.0),virtue(default0.5).WorldSimState.relationships(fromId → toId → RelationshipVector): Eight directed[0, 1]axes (affinity,attraction,envy,fear,obligation,respect,suspicion,trust) backed byrelationshipProvenance.WorldSimState.rumorBeliefs(agentId → rumorId → RumorBelief): Per-agent subjective-logicSimOpinion(belief,disbelief,uncertainty,baseRate) and spreading state (Ignorant | Spreader | BelieverSilent | Skeptic | Stifler).lastPosteriors(Map<String, Double>): Cached Bayesian theory-of-mind posteriors (WillBetray(<target>),IsLoyal(<target>)) computed strictly from the agent's non-omniscient ego-subgraph.
4. Behavioral Continuity (AgentContinuity) & Planning State
goals: Up to 4 activeAgentGoals (prioritydecays× 0.97per week, dropped below0.15), sourced from need thresholds,WillBetrayposteriors, network centrality, Belnap accusation conflict, disputedClaimDossiers, and temporal attributions.AgentContinuity:currentActionState/previousActionState/phaseState(12enum states:Idle,Investigating,Scheming,Recovering,Supporting,Opposing,GatheringRumors,ManagingResources,SeekingProtection,Guarding,SocialPositioning,QuestWatching).loyaltyVector(PartyAligned,HouseAligned,SelfAligned,FactionAligned,QuestAligned,Unknown) +loyaltyStrength.partyPredisposition(Devoted,Friendly,Neutral,Wary,Rivalrous,Fearful,Hostile,Unknown) +partyPredispositionScore.momentum,friction,startedWeek,weeksInState,lastUpdatedWeek,currentGoalId,targetId,lastPlanId,incentiveTags,continuityTags.
lastArbitration: FullPolicyArbitrationsnapshot (candidate proposals across solvers, QE dialectical strengths, suppressed proposals, selectedPlanGenesequence, and rationale).
Persistence Promotion & Off-Screen Development (NpcDevelopmentSystem)
Every weekly tick (immediately after NPC planning), NpcDevelopmentSystem.updatePersistentNpcDevelopment(state, rng) evaluates every active non-party agent in sorted ID order:
1. Dynamic Importance Scoring & Auto-Promotion to persistent = true
Base score starts at 0.10 and accumulates deterministic contributions:
| Signal | Importance delta | Tag added |
|---|---|---|
tier == A / tier == B | +0.35 / +0.18 | tier_a / tier_b |
Campaign linkage (sourceNpcId != null or sourceNpcAgentId != null) | +0.30 | campaign_npc |
Important AgentRole (FACTION_HEAD +0.28, ANTAGONIST_CANDIDATE +0.25, ALLY/RIVAL +0.22, QUEST_TARGET +0.20, FAMILY +0.18) | +0.18..+0.28 | important_role |
Heads any SimFaction | +0.20 | faction_head |
Strong partyPredispositionScore (> 0.35 → +0.20, > 0.65 → extra +0.08) or party relationship (> 0.20 → +0.12) or party-targeting goal (+0.08) | +0.08..+0.48 | party_related |
Has existing personalEvents | +0.10 | recurring |
Active direct pressure (> 0.45) | +0.08 | under_pressure |
Persistence latch: Once agent.isPersistent() || score >= 0.55 || agent.getSourceNpcAgentId() != null, persistent latches to true (sticky across future weeks) and importance floors at 0.55. Material shifts (≥ 0.04 or persistence promotion) append an NPC_IMPORTANCE_UPDATED SimEvent.
2. Off-Screen Personal Events, Experience & Skill Growth
Any agent with persistent == true || importance >= 0.55 is eligible for off-screen AgentPersonalEvent generation (rate-limited by lastPersonalEventWeek, chance min(0.68, 0.08 + importance * 0.32 + directPressure * 0.18 [+ 0.15 for pressured faction heads])):
- 5 weighted sources (
FACTION,PARTY,RELATIONSHIP,WORLD,PERSONAL) produce 9 event types:FACTION_ASSIGNMENT,FACTION_PRESSURE,PARTY_ALLY_SUPPORT,PARTY_RIVALRY,RELATIONSHIP_SHIFT,PERSONAL_TRAINING,PERSONAL_SETBACK,PERSONAL_OPPORTUNITY,WORLD_INCIDENT. applyPersonalEvent(state, agent, event)(also callable directly from GM play viaapply_npc_personal_event):- Permanently increments canonical
SimKeys.SKILLS(clamped[0, 1]). - Accumulates named
experiencebuckets (faction,party_alliance,party_rivalry,social,survival,personal, etc.), capped at50.0per bucket. - Nudges
publicVector.attentionproportionally to eventvisibility. - Appends the
AgentPersonalEventtoagent.personalEvents(bounded rolling history of40events) and emitsNPC_PERSONAL_EVENTontostate.eventLedger.
- Permanently increments canonical
Gradual Narrative Evolution (OpenSchemaProfile & HiddenTracker)
Complementing the numeric vectors above, every SimAgent carries an EvolvingWorld open-schema narrative face:
OpenSchemaProfile:dimensions:Map<String, OpenSchemaDimension>(genre-specific prose keys likecover_identity,core_drive,harvest_debt),shortDescription(refreshed after scenes), andspeechMarkers.
HiddenTracker:- Holds sub-threshold
HiddenSignalobservations (dimensionKey,note,proposedValue,polarity,weight,firstSeenWeek,lastSeenWeek,sourceRefs). - Signals decay if unreinforced across weeks, so a single bad week does not permanently rewrite a character.
EvidencePromoter/CharacterEvolutionSystemonly commits a rewrite toOpenSchemaProfileonce accumulated signal weight crosses the target dimension'sOpenSchemaDimension.Changeabilitythreshold:Fast(0.6) — mood, immediate intentModerate(1.6) — attitudes, working relationshipsSlow(3.2) — core personality, loyalty, worldviewAnchor(∞) — name, bloodline, species (never rewritten by simulation)
- Holds sub-threshold
Two-Phase Death & Status Persistence (InboundWorldEvent)
When an NPC dies or changes status during live table play (report_world_event with NPC_DEATH or NPC_STATUS_CHANGE):
- Immediate Phase (
immediateApplied = true):statustransitions immediately on the liveSimAgent(ACTIVE→DEAD/MISSING/DEPARTED) and the campaign NPC record updates in the same breath so GM narration and UI never show a dead NPC acting. - Weekly Reaction Phase (
IngestionSystem): On the nextadvance_world_week, the engine consumes the queuedInboundWorldEventwithout re-writing local status and triggers deterministic world fallout —AGENT_DEATH_APPLIEDledger entry, grief/relationship shifts,DeathAftershockdelayed consequences, faction head succession pressure, and circulating rumors.
Related Developer Documentation
- Living World Architecture & Entity Hierarchy — Polities, regions, settlements, factions, noble houses, locations, props, and bidirectional propagation.
- Agent Reasoning & Decision-Making Deep Dive — Epistemic Bayesian ToM, nested QE QBAFs, target-scoped
ActorKnowledgeGate, andBeliefReviser. - Living World, Scenes & Lore MCP Tools —
register_npc_agent,update_npc_agent,remove_npc_agent,get_npc_world_context,apply_npc_personal_event, andreport_world_event. - How Persistent NPCs Work (GM Guide) — Plain-English tabletop guide for Game Masters.