Skip to content

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:

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

  1. Strictly non-omniscient ego-subgraph (materializeEpistemicSubgraph):
    • Populates a UnifiedGraph using only the actor's own outgoing RelationshipVector rows, heard RumorBeliefs (belief.isHeard()), held/known IntrigueSecrets, 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()).
  2. Multi-hop Bayesian Network (buildEpistemicNetwork):
    • Builds a deterministic BayesianNetwork per reachable target using NoisyOrCpt:
      • 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
    • Evaluates exact marginals via VariableElimination.query(network, "WillBetray" | "IsLoyal", Map.of()).
  3. Abduction & contradiction surfacing:
    • When P(WillBetray) > 0.55, runs MostRelevantExplanation.explain(network, Map.of("WillBetray", 1), null, 2, 1e-4) and WeightOfEvidence.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 (WillBetray vs. IsLoyal) into certainty need and CONTRADICTION_DETECTED events.

2. Nested QBAF, Smooth QeSemantics & Dossier Adjudication ​

Sources:

  • elthoria-rules-engine/.../rules/CombatTacticalDecisionService.java
  • elthoria-world-simulation-engine/.../policy/PolicyCollisionSearch.java
  • elthoria-world-simulation-engine/.../systems/GraphReasoningSystem.java
  • elthoria-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:

  1. Multiple positive arguments saturate DF-QuAD's ceiling (1.0), drowning out refuting dossiers or secondary signals.
  2. 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):

    text
    lowConfidence  ──(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 via QbafWeightLearner (SemanticsStrategy.QE).

  • NPC Policy Arbitration (PolicyCollisionSearch):

    • riskTolerance attacks risk; Belnap conflict attacks both beliefFor and plan.
    • Target ClaimDossierInsight supporting/refuting items are adjudicated via AdjudicatorConfig.qe().adjudicate(...) and wired into dossierFor / dossierAgainst without any manual saturation offset.
    • GraphReasoningSystem.buildLoreClaimDossiers also adjudicates each raw ClaimDossier through DossierAdjudicator, 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.java
  • elthoria-world-simulation-engine/.../policy/PolicyCollisionSearch.java
  • elthoria-world-simulation-engine/.../reasoning/CandidateReasoningService.java
  • elthoria-world-simulation-engine/.../scene/SceneMotivationSystem.java
  1. Target-scoped epistemic gating (ActorKnowledgeGate.profileForTarget / gateGenesForTarget):
    • When an agent targets entity Y, ActorKnowledgeGate materializes the actor's 2-hop epistemic subgraph and checks only secrets and rumors connected to Y. Knowing a witness rumor about Noble A unlocks CoerceWitness against Noble A, not against unrelated Noble B.
  2. WHY_NOT precondition unlocking (BOUNDED_GOAP & CandidateReasoningService):
    • ActorKnowledgeGate.missingFacetsFor(targetProfile, payoff) reports which epistemic facet blocks the desired payoff gene (SPY, EVIDENCE, RECORD, WITNESS, SUCCESSION, COURIER, DANGER), letting BOUNDED_GOAP select the targeted setup gene (PlaceInformant, VerifyEvidence, OpenBackchannel, SpyOnFaction) with whyNotUnlock=<FACET> rationale instead of blind fallback.
    • CandidateReasoningService invokes GraphQueryEngine.Query.claim(Intent.WHY_NOT, ...) whenever a candidate lacks a direct supported edge, attaching graph gap: ... evidence labels for GMs and players.
  3. Real graph search in INFLUENCE_GRAPH_SEARCH:
    • After checking FOL-derived LeverageChain / DoubleAgentRisk facts, computes a deterministic BFS shortestSocialPath over GraphSnapshot edges: 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) over GraphSnapshot to identify the top network information broker (broker=<nodeId>) and plans broker cultivation or infiltration.
  4. Graph-grounded scene motivations (SceneMotivationSystem):
    • Before staging an EvolvingWorld scene, checks each cast member's Bayesian WillBetray(counterpart) posterior (> 0.65) and contested ClaimDossier presence on the counterpart so dialogue and inner thoughts directly reflect the reasoning layer.

4. Bayesian Sensitivity, Exact EIG & Crisis Abduction ​

Sources:

  • elthoria-world-simulation-engine/.../systems/TerminalStateSystem.java

  • elthoria-world-simulation-engine/.../reasoning/WorldInsightService.java

  • Terminal crisis diagnosis (TerminalStateSystem):

    • buildTerminalNetwork(terminalId, drivers) builds a deterministic Noisy-OR BayesianNetwork per terminal arc (kingdom_collapse, party_house_ruin, war_engulfment, economic_ruin, regional_uprising).
    • Alongside exact VariableElimination probability, runs MostRelevantExplanation.explain(...) (appending mre=<driver>=1,...) and WeightOfEvidence.decompose(...) (appending top woe:<driver>=±X.XX nats attributions).
  • World sensitivity & espionage VoI (WorldInsightService):

    • computeSensitivity(state) builds a unified realm_crisis Bayesian network via TerminalStateSystem.buildTerminalNetwork and runs SensitivityAnalyzer.rankBySensitivity(crisisNet, Map.of(), "realm_crisis") to find the single driver maximizing E[|ΔP(crisis)|].
    • targetInformationGoals(state) builds each agent's epistemic BayesianNetwork per candidate target and combines InformationGainEstimator.rankCandidatesByEIG with SensitivityAnalyzer.rankBySensitivity (retaining PslInformationGainApproximator.covarianceProxyEIG for 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:

  1. TruthMaintenanceService builds a compact PSL dependency program over all derived WorldFacts citing Rumor(<id>), registers their supports in a FactStore + InMemoryInferredFactStore, solves pre-retraction MAP, and indexes justifications via JustificationIndex.build(preResult, factStore).
  2. Calls BeliefReviser.retractReviseAndPurge(retractedKey, reviseProgram, factStore, index, inferredStore).
  3. Enforces BeliefReviser's distinction cleanly:
    • unsupportedAtoms (solely dependent on the debunked rumor) are purged from state.getWorldFacts().
    • weakenedAtoms (retaining at least one independent support) are preserved and have their soft-truth value updated from the post-retraction MAP solution, with both unsupportedAtoms and weakenedAtoms recorded on the BELIEF_REVISED SimEvent.

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.java
  • elthoria-world-simulation-engine/.../reasoning/NarrativeInferenceService.java

All three reasoning families persist versioned, revertible campaign weights through Kompile's FileWeightStore:

Weight FamilyStore PrefixKompile LearnerTrigger / API
PSL propagation rulesworldsim-<simId>StructuredPerceptronLearnerapplyFeedback(simId, state, labels) for rumor|secret|trust|fear|suspicion
MEBN narrative propagationworldsim-mebn-<simId>MebnWeightLearnerapplyFeedback(...) with kind="mebn.*" or learnMebnTheory(simId, theory, graph, targets, epochs) → loaded into NarrativeInferenceService.setPropagationStrength(...)
QE QBAF evidence kindsworldsim-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 deterministic Comparator chains).
  • Timestamps passed into Kompile Fact records use deterministic week-derived Instant.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-scoped ActorKnowledgeGate, BeliefReviser MAP revision, quantitative SCENARIO/SOLVE_TARGET, MEBN/QBAF weight learning, and ToM-grounded scene motivation).

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