Skip to content

Reasoning Traces & Explainability ​

Every inference in Kompile — whether from Datalog/FOL rules, Probabilistic Soft Logic (PSL), MEBN/Bayesian networks, Subjective Logic fusion, quantitative formulas, or process mining — can be normalized into a single, walkable, serializable proof tree: ReasoningTrace.

Instead of exposing opaque scores or engine-specific internals, reasoning traces give agents, auditors, and UIs one consistent contract to inspect why a conclusion holds, which sources support or rebut it, what evidence is missing or contested, and how to export provenance to W3C PROV.


1. The unified ReasoningTrace model ​

A ReasoningTrace is a rooted tree of immutable ReasoningTrace.Step records. The root is the conclusion; each step's premises are the sub-steps that derived it, down to observed FACT or ASSUMPTION leaves.

Step fields ​

FieldTypeMeaning
kindStepKindCategory of reasoning step (11 kinds, listed below)
conclusionStringClaim, atom, or value established by this step
operationStringRule ID, solver operation, or operator (e.g. observed, psl-map value=0.72, w=2.0 d=0.05 dir=up)
confidencedoubleScalar confidence in [0.0, 1.0] (NaN sentinel coerced to 0.0)
sourceStringOptional provenance source identifier (document, chunk, fact ID, run ID)
premisesList<Step>Supporting or rebutting child steps (empty for leaves)
opinionOpinion (nullable)Optional full Subjective Logic opinion (belief, disbelief, uncertainty, baseRate)
metaMap<String, String>Arbitrary annotations (e.g. learnedScore, revision state, rule metadata)

The 11 StepKind categories ​

StepKindRole in the proof tree
FACTObserved base fact from the graph or corpus (leaf)
ASSUMPTIONHypothesized or counterfactual input (leaf)
RULELogical (FOL / Datalog / OWL-RL) rule application
FUSIONSubjective-logic or multi-signal evidence fusion
INFERENCEProbabilistic inference (PSL / HL-MRF, Bayesian network, MEBN)
QUERYRetrieval or graph lookup step
CALCULATIONDeterministic numeric calculation or aggregation
VALIDATIONUnit, dimensional, replay, or reconciliation check
OPTIMIZATIONGoal-seek (SOLVE_TARGET) or constrained optimization step
REBUTTALCounter-evidence or argument that attacks/rebuts the parent conclusion
REVISIONBelief-revision event (prior conclusion revised or retracted by BeliefReviser)

2. How each reasoning engine produces traces ​

Engine / ComponentAdapter / ProducerWhat the trace captures
FOL / Datalog / TMSReasoningTrace.fromDerivation(DerivationTree)Full rule-firing derivation tree down to observed FACT leaves, preserving provenance and surfacing REBUTTAL / REVISION steps when BeliefReviser accepts defeating evidence or retracts facts.
PSL / HL-MRF (ADMM)PslTraceAdapterKKT rule-force view: root INFERENCE (psl-map value=...) → up to 12 strongest RULE premises sorted by weighted potential (w, distance d, push direction dir=up/down, pot) → observed FACT leaves with Fact.sourceId() provenance.
Subjective Logic FusionOpinionTree, EvidenceAccumulator, ask_graph_explain_fusedPreserves per-step Opinion(b, d, u, a) across modalities (ModalityKind, ModalityEvidence, ConfidenceBreakdown) rather than collapsing disagreement into one float.
Dialectical Claim Adjudication (QBAF)DossierAdjudicator + ClaimAdjudicatorConverts a ClaimDossier into PRO supporters and CON attackers scored under DF-QuAD semantics (DfQuadSemantics), surfacing refuting items as first-class REBUTTAL steps.
Quantitative Modelsgraph_reasoning_query (CALCULATE / SCENARIO / SOLVE_TARGET)Deterministic CALCULATION, VALIDATION, and OPTIMIZATION steps recording inputs, baseline vs. intervention deltas, and goal-seek convergence.
Process MiningProcessReasoningTraceBuilder, ProcessReasoningTraceStore, ProcessReasoningTraceSseBridgeMined-process discovery and suggestion traces, persisted under models/process/reasoning-traces/v1/ and mirrored into ReasoningTraceStore for chat/UI streaming.

Example PSL KKT trace structure ​

text
INFERENCE  "isActive(alice)"  "psl-map value=0.72"  confidence=0.72
  RULE     "worksFor(x, org) & activeOrg(org) -> isActive(x)"  "w=2.0 d=0.05 dir=up pot=0.10"  confidence=0.95
    FACT   "worksFor(alice, acme)"  "observed"  confidence=0.90  source=doc:hr-roster#chunk-4
    FACT   "activeOrg(acme)"        "observed"  confidence=1.00  source=doc:filing-2026#chunk-1
  REBUTTAL "onLeave(alice)"         "observed"  confidence=0.40  source=doc:calendar#chunk-9

3. Rendering, citeable attribution & gap analysis ​

Kompile separates rendering for LLMs, structured citation indexing, and deterministic gap detection over the same step IDs:

Compact LLM rendering & attribution index (ReasoningTraceRenderer) ​

  • toLlmContext(trace, maxLines): renders any ReasoningTrace, ReasoningTrail, CompositeReasoningTrail, or DerivationTree into bounded plain text (default 20 lines, 280 chars/line) preserving target, confidence, opinions, modalities, rules, and derivation hierarchy.
  • attributionIndex(...): produces a flat list of citeable AttributionStep(stepId, kind, conclusion, operation, confidence, source, evidenceRefs). Each EvidenceReference parses structured identifiers (nodeId, edgeId, documentId, chunkId, factSheetId, runId, atomKey, findingKey, ruleId, modality) so downstream agents and UIs can link directly back to source chunks and graph elements.

Deterministic gap analysis (ReasoningTraceGapAnalyzer) ​

ReasoningTraceGapAnalyzer.traceGaps(trace) answers "what should the agent or user verify next?" by emitting bounded, step-ID-addressable TraceGap(gapType, severity, question, reason, relatedStepIds) records (default cap: 12):

gapTypeTrigger condition
UNCERTAIN_OPINIONA step carries an Opinion with uncertainty >= 0.6 (thin evidence — takes precedence over scalar LOW_CONFIDENCE).
CONTESTED_EVIDENCEA step carries an Opinion with both belief >= 0.3 and disbelief >= 0.3, or sibling premises have pairwise conflict >= 0.25.
LOW_CONFIDENCEScalar-only root step (no Opinion) has confidence < 0.60 (HIGH severity below 0.40, MEDIUM otherwise).
MODALITY_DISAGREEMENTMultiple reasoning modalities disagree by >= 0.35.
MISSING_PROVENANCEA step lacks citeable source/document/chunk references.
MISSING_SUPPORT / MISSING_SUPPORT_FINDINGSDerived conclusion or entailment has no grounded base support.
UNCERTAIN_EVIDENCEStep text contains fallback/uncertainty markers (unknown, unavailable, no signal, missing, failed).
MISSING_TRACE / MISSING_CONFIDENCETrace payload or confidence value is absent.
MISSING_MODALITIES / MISSING_MODALITY_DETAILComposite trail is missing expected modality breakdowns.

4. Portable JSON, .kgraph storage & W3C PROV export ​

Bounded portable JSON (ReasoningTraceJsonCodec) ​

ReasoningTraceJsonCodec serializes and validates traces in a strict, bounded envelope (format: "kompile.reasoning-trace", formatVersion: 1):

  • Hard safety bounds: 1 MiB max payload, 512 max steps, depth 64, 64 premises/step, 64 metadata entries/step, 4,096 bytes max text field.
  • Preserves step IDs, Opinion(b, d, u, a), and meta maps without Java serialization.

.kgraph trace artifacts & compact graph context (CompactGraphContextService) ​

Traces can travel inside a .kgraph ZIP container under models/:

.kgraph artifactContents
models/reasoning/traces.jsonPersisted reasoning trace DTOs
models/process/suggestions.jsonProcess-mining suggestion payloads
models/process/reasoning-traces/v1/<id>.jsonVersioned kompile.reasoning-trace v1 process traces

When building grounded chat context (kompile.compact-graph.v1), CompactGraphContextService enforces strict scoping and provenance hygiene:

  • Only neighborhood nodes and relations for the retrieved seeds are read (bounded at 32 nodes / 96 relations / 4 traces / 16 steps).
  • A reasoning trace is included only if it references at least one retrieved node.
  • Stored opinions are emitted as learnedScore, never conflated with raw extraction confidence.

W3C PROV export (ProvSerializer) ​

For external compliance, auditing, or lineage pipelines, ProvSerializer exports any ReasoningTrace to standard W3C PROV-N or PROV-JSON (export-only):

ReasoningTrace stepW3C PROV-DM mapping
FACT (leaf)prov:Entity (deduplicated by conclusion)
ASSUMPTION (leaf)prov:Entity annotated with kompile:assumed "true"
RULE / INFERENCE / FUSION / QUERY / derivedprov:Entity (conclusion) + prov:Activity (operation), linked via prov:wasGeneratedBy, prov:used, and prov:wasDerivedFrom

5. Inspecting traces via MCP tools ​

Agents inspect reasoning traces directly through Kompile's MCP grounding tools (working both folder-locally over .kgraph and against a Kompile server):

ToolWhat it returnsExample call
ask_graph_explainStep-by-step derivation tree rendered via ReasoningTraceRenderer, showing which rules fired and which observed facts produced the verdict.ask_graph_explain atom="worksFor(Alice, Acme)"
ask_graph_explain_fusedFused Subjective Logic breakdown (belief, disbelief, uncertainty, support vs. counter-evidence) across reasoning modalities.ask_graph_explain_fused target="worksFor(Alice, Acme)"
graph_reasonOne-call verdict or entity dossier combining evidence, learned scores, and rendered reasoning trace.graph_reason target="worksFor(Alice, Acme)"
graph_reasoning_queryTyped VERIFY, WHY (why a relation holds), and WHY_NOT (why it fails and what missing facts/paths would change it) with compact trace output, opinions, and learned scores.graph_reasoning_query operation="WHY_NOT" entity="Alice" target="Acme" relationTypes=["WORKS_FOR"]
ask_graph_claimMulti-signal claim dossier + dialectical QBAF adjudication (DossierAdjudicator) with PRO support and CON REBUTTAL steps.ask_graph_claim claim="Alice leads Platform Engineering"
process_miningProcess discovery and conformance results with a reasoningTraceId (mirrored to ReasoningTraceStore via ProcessReasoningTraceSseBridge on server deployments).process_mining action="discover" fact_sheet_id=1

Released under the Apache-2.0 License.