Skip to content

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

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

FieldType / ValuesSemantics
idStringDeterministic world-sim ID (e.g. "agent.voss"), used for all cross-references and sorted iteration
roleAgentRole: PARTY, FAMILY, RIVAL, ALLY, ANTAGONIST_CANDIDATE, FACTION_HEAD, QUEST_TARGET, SIDE_NPCNarrative/structural role; PARTY is the focal party agent
tierActorTier: A, B, CFidelity tier: A = full multi-solver planning + Bayesian ToM; B = reduced planning; C = ambient reaction only
statusAgentStatus: ACTIVE, DEAD, MISSING, DEPARTEDisActive() is status == ACTIVE; inactive agents stop planning and reacting
sourceNpcId / sourceNpcAgentIdLong (nullable)Campaign JPA linkage to NPC.id and NpcAgent.id; automatically grants +0.30 importance and forces persistent = true when sourceNpcAgentId != null
houseId / factionId / factionIdsString / List<String>Household and multi-faction memberships (multi-faction membership across tense factions feeds DoubleAgentRisk derivation)
locationId / sceneLocationIdStringlocationId = 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 SimAgentDefault fallbackCanonical keys (SimKeys)
traits (12)0.5ambition, cowardice, cruelty, curiosity, discipline, dutyBias, empathy, jealousy, opportunism, piety, pride, romanticism
needs (9)0.5affection, autonomy, certainty, legitimacy, revenge, security, status, stress, wealth
resources (4)0.3information, influence, money, reputation
skills (10)0.3charisma, commerce, divinePower, etiquette, intelligence, magic, politics, resilience, stealth, swordplay

3. Public Standing (PublicVector) & Directed Social Web ​

  • PublicVector: attention (default 0.2), scandal (default 0.0), virtue (default 0.5).
  • WorldSimState.relationships (fromId → toId → RelationshipVector): Eight directed [0, 1] axes (affinity, attraction, envy, fear, obligation, respect, suspicion, trust) backed by relationshipProvenance.
  • WorldSimState.rumorBeliefs (agentId → rumorId → RumorBelief): Per-agent subjective-logic SimOpinion (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 active AgentGoals (priority decays × 0.97 per week, dropped below 0.15), sourced from need thresholds, WillBetray posteriors, network centrality, Belnap accusation conflict, disputed ClaimDossiers, and temporal attributions.
  • AgentContinuity:
    • currentActionState / previousActionState / phaseState (12 enum 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: Full PolicyArbitration snapshot (candidate proposals across solvers, QE dialectical strengths, suppressed proposals, selected PlanGene sequence, 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:

SignalImportance deltaTag added
tier == A / tier == B+0.35 / +0.18tier_a / tier_b
Campaign linkage (sourceNpcId != null or sourceNpcAgentId != null)+0.30campaign_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.28important_role
Heads any SimFaction+0.20faction_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.48party_related
Has existing personalEvents+0.10recurring
Active direct pressure (> 0.45)+0.08under_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 via apply_npc_personal_event):
    • Permanently increments canonical SimKeys.SKILLS (clamped [0, 1]).
    • Accumulates named experience buckets (faction, party_alliance, party_rivalry, social, survival, personal, etc.), capped at 50.0 per bucket.
    • Nudges publicVector.attention proportionally to event visibility.
    • Appends the AgentPersonalEvent to agent.personalEvents (bounded rolling history of 40 events) and emits NPC_PERSONAL_EVENT onto state.eventLedger.

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 like cover_identity, core_drive, harvest_debt), shortDescription (refreshed after scenes), and speechMarkers.
  • HiddenTracker:
    • Holds sub-threshold HiddenSignal observations (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 / CharacterEvolutionSystem only commits a rewrite to OpenSchemaProfile once accumulated signal weight crosses the target dimension's OpenSchemaDimension.Changeability threshold:
      • Fast (0.6) — mood, immediate intent
      • Moderate (1.6) — attitudes, working relationships
      • Slow (3.2) — core personality, loyalty, worldview
      • Anchor (∞) — name, bloodline, species (never rewritten by simulation)

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

  1. Immediate Phase (immediateApplied = true): status transitions immediately on the live SimAgent (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.
  2. Weekly Reaction Phase (IngestionSystem): On the next advance_world_week, the engine consumes the queued InboundWorldEvent without re-writing local status and triggers deterministic world fallout — AGENT_DEATH_APPLIED ledger entry, grief/relationship shifts, DeathAftershock delayed consequences, faction head succession pressure, and circulating rumors.

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