Agent Reasoning & Decision-Making Deep Dive
This guide explains how Elthoria applies kompile-graph-reasoning across its four deterministic decision loops — NPC weekly planning, tactical combat recommendations, story candidate & counterfactual reasoning, and EvolvingWorld scene staging — without invoking an LLM in the loop and while preserving byte-identical seeded determinism.
TIP
Looking for the plain-English tabletop guide for Game Masters? Read How NPCs, Villains & Your World Make Decisions.
Architecture: Four Decision Loops Over One Graph Stack
All four decision loops share kompile-graph-reasoning primitives (no extra Maven dependencies beyond kompile-graph-reasoning) and keep every external reasoning object projected into Elthoria's own serializable POJOs before hitting WorldSimState or WeekResult:
┌──────────────────────────────────────────────────────────────────────────────┐
│ 1. Epistemic Belief & Theory-of-Mind (`BeliefWorldService`) │
│ SubgraphMaterializer (non-omniscient ego-subgraph) │
│ → Multi-hop BayesianNetwork (NoisyOrCpt) + VariableElimination │
│ → MostRelevantExplanation + WeightOfEvidence + ContradictionDetector │
└────────────────────────────────────┬─────────────────────────────────────────┘
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ 2. Goal Targeting, Preconditions & Policy Arbitration │
│ • WorldInsightService: InformationGainEstimator + SensitivityAnalyzer │
│ • ActorKnowledgeGate: target-scoped epistemic subgraph + missingFacets │
│ • PolicyCollisionSearch: │
│ - BOUNDED_GOAP (WHY_NOT facet-unlocking setup genes) │
│ - INFLUENCE_GRAPH_SEARCH (shortest social path + Brandes brokers) │
│ - Nested QBAF + QeSemantics + AdjudicatorConfig.qe() dossiers │
└───────────────────┬─────────────────────────────────────┬────────────────────┘
▼ ▼
┌─────────────────────────────────────────┐ ┌──────────────────────────────────┐
│ 3. Truth Maintenance, Candidates & │ │ 4. Combat Tactics & Scenes │
│ Quantitative Counterfactuals │ │ • CombatTacticalDecisionService │
│ • TruthMaintenanceService: │ │ Nested QBAF + QeSemantics │
│ Atms + BeliefReviser │ │ + QbafWeightLearner │
│ (retractReviseAndPurge → MAP) │ │ • SceneMotivationSystem: │
│ • CandidateReasoningService: │ │ WillBetray posteriors & │
│ GraphQueryEngine (WHY/WHY_NOT/PATH) │ │ contested ClaimDossiers │
│ + AdjudicatorConfig.qe() + PSL VoI │ │ │
│ • TerminalStateSystem: │ │ Adaptive Campaign Learning │
│ BayesianNetwork + MRE + WoE │ │ • RuleWeightLearningService: │
│ • WorldQuantitativeScenarioService: │ │ PSL StructuredPerceptron + │
│ CALCULATE / SCENARIO / SOLVE_TARGET │ │ MebnWeightLearner + │
│ │ │ QbafWeightLearner (FileStore) │
└─────────────────────────────────────────┘ └──────────────────────────────────┘1. Epistemic Ego-Subgraphs & Multi-Hop Bayesian Theory-of-Mind
Source: elthoria-world-simulation-engine/.../reasoning/BeliefWorldService.java
Instead of letting NPCs inspect omniscient world state or relying on 1-hop scalar heuristics, BeliefWorldService constructs an isolated epistemic model for each Tier-A planner:
- Strictly non-omniscient ego-subgraph (
materializeEpistemicSubgraph):- Populates a
UnifiedGraphusing only the actor's own outgoingRelationshipVectorrows, heardRumorBeliefs (belief.isHeard()), held/knownIntrigueSecrets, and second-hop ties strictly among shared-faction peers or trusted contacts (trust > 0.55). - Materializes a bounded ego view via
SubgraphMaterializer.INSTANCE.materialize(epistemic, SubgraphSpec.builder().seedId(agentId).radius(radius).maxNodes(48).build()).
- Populates a
- Multi-hop Bayesian Network (
buildEpistemicNetwork):- Builds a deterministic
BayesianNetworkper reachable target usingNoisyOrCpt:- Direct priors:
DirectSuspicion,HeardTreason,Distrust,SecretExposure - Multi-hop intermediary chain:
HostileIntermediary → CompromisedByIntermediary → WillBetray(activated when a target holds a strong trust/obligation bond to a rival the actor already distrusts inside its ego-subgraph) - Loyalty branch:
DirectTrust,HeardVirtue,Obligation → IsLoyal
- Direct priors:
- Evaluates exact marginals via
VariableElimination.query(network, "WillBetray" | "IsLoyal", Map.of()).
- Builds a deterministic
- Abduction & contradiction surfacing:
- When
P(WillBetray) > 0.55, runsMostRelevantExplanation.explain(network, Map.of("WillBetray", 1), null, 2, 1e-4)andWeightOfEvidence.decompose(network, "WillBetray", 1, activeCauses)to extract the parsimonious root causes and per-finding log-odds weights. - Feeds all per-target posteriors into
ProbabilisticContradictionDetector.detect(posteriors, meta), converting mutual-exclusion clashes (WillBetrayvs.IsLoyal) intocertaintyneed andCONTRADICTION_DETECTEDevents.
- When
2. Nested QBAF, Smooth QeSemantics & Dossier Adjudication
Sources:
elthoria-rules-engine/.../rules/CombatTacticalDecisionService.javaelthoria-world-simulation-engine/.../policy/PolicyCollisionSearch.javaelthoria-world-simulation-engine/.../systems/GraphReasoningSystem.javaelthoria-world-simulation-engine/.../reasoning/CandidateReasoningService.java
Why QeSemantics + Nested Rebuttals Replaced Flat DF-QuAD
Flat star-shaped QBAFs under DF-QuAD suffer from two practical limits in game AI:
- Multiple positive arguments saturate DF-QuAD's ceiling (
1.0), drowning out refuting dossiers or secondary signals. - Premise qualifiers (like low hit probability, contested Belnap evidence, or high risk tolerance) cannot directly weaken the specific premise they qualify.
Both decision engines now build nested QBAFs evaluated under Kompile's smooth Quadratic-Energy semantics (QeSemantics.evaluate(qbaf)):
Tactical Combat (
CombatTacticalDecisionService):textlowConfidence ──(attack)──► impact ──(support)──► action (CLAIM) weakEvidence ──(attack)──► fit ──(support)──► action (CLAIM) riskMitigation ──(attack)──► exposure ──(attack)───► action (CLAIM) resourceMitig. ──(attack)──► cost ──(attack)───► action (CLAIM)Supports optional learned per-evidence-kind multipliers (
recommend(candidates, context, learnedKindWeights)) trained viaQbafWeightLearner(SemanticsStrategy.QE).NPC Policy Arbitration (
PolicyCollisionSearch):riskToleranceattacksrisk; Belnapconflictattacks bothbeliefForandplan.- Target
ClaimDossierInsightsupporting/refuting items are adjudicated viaAdjudicatorConfig.qe().adjudicate(...)and wired intodossierFor/dossierAgainstwithout any manual saturation offset. GraphReasoningSystem.buildLoreClaimDossiersalso adjudicates each rawClaimDossierthroughDossierAdjudicator, blending calibrated log-odds (0.6) with dialectical strength (0.4).
3. Target-Scoped Knowledge Gate, WHY_NOT Planning & Graph-Search Strategy
Sources:
elthoria-world-simulation-engine/.../policy/ActorKnowledgeGate.javaelthoria-world-simulation-engine/.../policy/PolicyCollisionSearch.javaelthoria-world-simulation-engine/.../reasoning/CandidateReasoningService.javaelthoria-world-simulation-engine/.../scene/SceneMotivationSystem.java
- Target-scoped epistemic gating (
ActorKnowledgeGate.profileForTarget/gateGenesForTarget):- When an agent targets entity
Y,ActorKnowledgeGatematerializes the actor's 2-hop epistemic subgraph and checks only secrets and rumors connected toY. Knowing a witness rumor about Noble A unlocksCoerceWitnessagainst Noble A, not against unrelated Noble B.
- When an agent targets entity
WHY_NOTprecondition unlocking (BOUNDED_GOAP&CandidateReasoningService):ActorKnowledgeGate.missingFacetsFor(targetProfile, payoff)reports which epistemic facet blocks the desired payoff gene (SPY,EVIDENCE,RECORD,WITNESS,SUCCESSION,COURIER,DANGER), lettingBOUNDED_GOAPselect the targeted setup gene (PlaceInformant,VerifyEvidence,OpenBackchannel,SpyOnFaction) withwhyNotUnlock=<FACET>rationale instead of blind fallback.CandidateReasoningServiceinvokesGraphQueryEngine.Query.claim(Intent.WHY_NOT, ...)whenever a candidate lacks a direct supported edge, attachinggraph gap: ...evidence labels for GMs and players.
- Real graph search in
INFLUENCE_GRAPH_SEARCH:- After checking FOL-derived
LeverageChain/DoubleAgentRiskfacts, computes a deterministic BFSshortestSocialPathoverGraphSnapshotedges: if the target is ≥ 2 hops away (A → B → C), targets the intermediary bridge (socialPath=A->B->C,bridge=B). - Otherwise computes deterministic Brandes betweenness centrality (
brandesBetweenness) overGraphSnapshotto identify the top network information broker (broker=<nodeId>) and plans broker cultivation or infiltration.
- After checking FOL-derived
- Graph-grounded scene motivations (
SceneMotivationSystem):- Before staging an EvolvingWorld scene, checks each cast member's Bayesian
WillBetray(counterpart)posterior (> 0.65) and contestedClaimDossierpresence on the counterpart so dialogue and inner thoughts directly reflect the reasoning layer.
- Before staging an EvolvingWorld scene, checks each cast member's Bayesian
4. Bayesian Sensitivity, Exact EIG & Crisis Abduction
Sources:
elthoria-world-simulation-engine/.../systems/TerminalStateSystem.javaelthoria-world-simulation-engine/.../reasoning/WorldInsightService.javaTerminal crisis diagnosis (
TerminalStateSystem):buildTerminalNetwork(terminalId, drivers)builds a deterministic Noisy-ORBayesianNetworkper terminal arc (kingdom_collapse,party_house_ruin,war_engulfment,economic_ruin,regional_uprising).- Alongside exact
VariableEliminationprobability, runsMostRelevantExplanation.explain(...)(appendingmre=<driver>=1,...) andWeightOfEvidence.decompose(...)(appending topwoe:<driver>=±X.XXnats attributions).
World sensitivity & espionage VoI (
WorldInsightService):computeSensitivity(state)builds a unifiedrealm_crisisBayesian network viaTerminalStateSystem.buildTerminalNetworkand runsSensitivityAnalyzer.rankBySensitivity(crisisNet, Map.of(), "realm_crisis")to find the single driver maximizingE[|ΔP(crisis)|].targetInformationGoals(state)builds each agent's epistemicBayesianNetworkper candidate target and combinesInformationGainEstimator.rankCandidatesByEIGwithSensitivityAnalyzer.rankBySensitivity(retainingPslInformationGainApproximator.covarianceProxyEIGfor partially known secrets).
5. Consistent MAP Belief Revision (BeliefReviser)
Source: elthoria-world-simulation-engine/.../reasoning/TruthMaintenanceService.java
When a high-visibility exculpatory incident (such as PublicRescue refuting cowardice) debunks a low-truth rumor:
TruthMaintenanceServicebuilds a compact PSL dependency program over all derivedWorldFacts citingRumor(<id>), registers their supports in aFactStore+InMemoryInferredFactStore, solves pre-retraction MAP, and indexes justifications viaJustificationIndex.build(preResult, factStore).- Calls
BeliefReviser.retractReviseAndPurge(retractedKey, reviseProgram, factStore, index, inferredStore). - Enforces
BeliefReviser's distinction cleanly:unsupportedAtoms(solely dependent on the debunked rumor) are purged fromstate.getWorldFacts().weakenedAtoms(retaining at least one independent support) are preserved and have their soft-truthvalueupdated from the post-retraction MAP solution, with bothunsupportedAtomsandweakenedAtomsrecorded on theBELIEF_REVISEDSimEvent.
6. Quantitative Counterfactuals & Goal-Seeking (SCENARIO / SOLVE_TARGET)
Source: elthoria-world-simulation-engine/.../reasoning/WorldQuantitativeScenarioService.java
Projects validated world-state metrics into a sidecar UnifiedGraph (Party reputation, Party risk = 1 - REPUTATION, Crown legitimacy, Crown debt, Famine pressure, War prevalence, Trade connectivity, Realm stability index = (LEGITIMACY + TRADE - DEBT - FAMINE + 2) / 4, Crisis pressure = (DEBT + FAMINE + WAR) / 3) and exposes three non-mutating queries through Kompile's GraphQueryEngine:
evaluate(state)/evaluateMetric(state, label, id)→GraphQueryEngine.Query.calculate(...)scenario(state, targetLabel, interventions)→GraphQueryEngine.Query.scenario(QuantitativeQuery.scenario(...))solveTarget(state, targetLabel, controlLabel, targetValue, min, max)→GraphQueryEngine.Query.solveTarget(QuantitativeQuery.solveTarget(...))
7. Multi-Engine Campaign Weight Learning
Sources:
elthoria-world-simulation-engine/.../reasoning/RuleWeightLearningService.javaelthoria-world-simulation-engine/.../reasoning/NarrativeInferenceService.java
All three reasoning families persist versioned, revertible campaign weights through Kompile's FileWeightStore:
| Weight Family | Store Prefix | Kompile Learner | Trigger / API |
|---|---|---|---|
| PSL propagation rules | worldsim-<simId> | StructuredPerceptronLearner | applyFeedback(simId, state, labels) for rumor|secret|trust|fear|suspicion |
| MEBN narrative propagation | worldsim-mebn-<simId> | MebnWeightLearner | applyFeedback(...) with kind="mebn.*" or learnMebnTheory(simId, theory, graph, targets, epochs) → loaded into NarrativeInferenceService.setPropagationStrength(...) |
| QE QBAF evidence kinds | worldsim-qbaf-<simId> | QbafWeightLearner (SemanticsStrategy.QE) | learnQbafWeights(simId, labeledClaims) / loadQbafWeights(simId) and CombatTacticalDecisionService.learnWeights(...) |
Determinism & Test Verification
Every reasoning pass preserves Elthoria's canonical state-hash contract (WeekResultBuilder#hashState and SimRngDeterminismTest):
- All graph traversals, map iterations, and tie-breaks use sorted keys (
TreeMap,TreeSet, or deterministicComparatorchains). - Timestamps passed into Kompile
Factrecords use deterministic week-derivedInstant.EPOCH.plusSeconds(week)rather than wall-clock time. - Unit & integration suites covering these paths:
elthoria-rules-engine:CombatTacticalDecisionServiceTest(nested QE QBAF +QbafWeightLearner).elthoria-world-simulation-engine:AgentReasoningUpgradesTest(multi-hop epistemic Bayesian ToM, MRE/WoE terminals, Bayesian sensitivity, QE + social path + Brandes brokers, target-scopedActorKnowledgeGate,BeliefReviserMAP revision, quantitativeSCENARIO/SOLVE_TARGET, MEBN/QBAF weight learning, and ToM-grounded scene motivation).
Related Documentation
- ANTLR Map DSLs & World Simulator Data Format —
TTRPGMap.g4,HexMap.g4,WorldSimState(elthoria_world_sim_v1), tick pipeline, and persistence records. - Memory Architecture Deep Dive — Five-layer campaign memory architecture and causal grounding.
- How NPCs, Villains & Your World Make Decisions (GM Guide) — Plain-English tabletop overview for Game Masters.