From a46872dcf0e715810a2a1163580095b73bf72468 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 11:57:54 -0500 Subject: [PATCH] aienos-explain: grounded explanation bridge over a versioned evidence-graph contract New crate crates/aienos-explain (EXPLAIN, lane43). Think in graphs, speak in paths: - contract: aien.explain.evidence-graph v1, language-neutral JSON with fixed-width status/kind/relation codes and explicit u16 error codes (docs/EXPLAIN_EVIDENCE_GRAPH_V1.md). - build: bounded backward walk over support edges, loop cutting, deterministic linearization (target last), visible uncertainty (missing parent/link, unsupported, untested hypothesis, inferred, unknown, truncated, conflicting evidence), sha256 bundle digest. - adapters: read-only producers from aienos-cortex records/journals and agent-state branches (branch scope = referenced records plus their support ancestry). - render: deterministic Summary / StepByStep / Technical / Analogy at levels 0-4; analogies live only in the renderer and are labelled illustration, not evidence. - session: clarification and rewind without recomputation; CLI aienos-explain. - tests: 16 behavioural tests plus a pinned cross-repo RSI fixture shared with aien-dev/spark-rsi and a CLI test. Read-only and observational: grants no authority, no LLM, no native/ changes. Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 11 + Cargo.toml | 1 + crates/aienos-explain/Cargo.toml | 19 + .../docs/EXPLAIN_EVIDENCE_GRAPH_V1.md | 77 +++ crates/aienos-explain/src/adapters.rs | 297 +++++++++ crates/aienos-explain/src/build.rs | 495 +++++++++++++++ crates/aienos-explain/src/bundle.rs | 306 +++++++++ crates/aienos-explain/src/contract.rs | 463 ++++++++++++++ crates/aienos-explain/src/lib.rs | 29 + crates/aienos-explain/src/main.rs | 194 ++++++ crates/aienos-explain/src/render.rs | 535 ++++++++++++++++ crates/aienos-explain/src/session.rs | 198 ++++++ crates/aienos-explain/tests/explain.rs | 569 +++++++++++++++++ .../tests/fixtures/rsi_kv_cycle.evidence.json | 590 ++++++++++++++++++ crates/aienos-explain/tests/rsi_and_cli.rs | 198 ++++++ 15 files changed, 3982 insertions(+) create mode 100644 crates/aienos-explain/Cargo.toml create mode 100644 crates/aienos-explain/docs/EXPLAIN_EVIDENCE_GRAPH_V1.md create mode 100644 crates/aienos-explain/src/adapters.rs create mode 100644 crates/aienos-explain/src/build.rs create mode 100644 crates/aienos-explain/src/bundle.rs create mode 100644 crates/aienos-explain/src/contract.rs create mode 100644 crates/aienos-explain/src/lib.rs create mode 100644 crates/aienos-explain/src/main.rs create mode 100644 crates/aienos-explain/src/render.rs create mode 100644 crates/aienos-explain/src/session.rs create mode 100644 crates/aienos-explain/tests/explain.rs create mode 100644 crates/aienos-explain/tests/fixtures/rsi_kv_cycle.evidence.json create mode 100644 crates/aienos-explain/tests/rsi_and_cli.rs diff --git a/Cargo.lock b/Cargo.lock index d1c4229c..ad81e10d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,6 +97,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "aienos-explain" +version = "0.1.0" +dependencies = [ + "aienos-agent-state", + "aienos-cortex", + "aienos-crypto", + "serde", + "serde_json", +] + [[package]] name = "aienos-kernel" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 5361f370..460b5419 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ members = [ "crates/aienos-artifact-tool", "crates/aienos-evidence", "crates/aienos-store-tool", + "crates/aienos-explain", ] [workspace.package] diff --git a/crates/aienos-explain/Cargo.toml b/crates/aienos-explain/Cargo.toml new file mode 100644 index 00000000..cdc4fab4 --- /dev/null +++ b/crates/aienos-explain/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "aienos-explain" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +description = "Host-side explanation bridge: grounded, bounded paths through explicit evidence graphs (Cortex, agent branches, RSI)" + +[dependencies] +aienos-crypto = { path = "../aienos-crypto" } +aienos-cortex = { workspace = true } +aienos-agent-state = { workspace = true } +serde = { version = "1.0", features = ["derive", "std"] } +serde_json = { version = "1.0", features = ["std"] } + +[[bin]] +name = "aienos-explain" +path = "src/main.rs" diff --git a/crates/aienos-explain/docs/EXPLAIN_EVIDENCE_GRAPH_V1.md b/crates/aienos-explain/docs/EXPLAIN_EVIDENCE_GRAPH_V1.md new file mode 100644 index 00000000..4371625e --- /dev/null +++ b/crates/aienos-explain/docs/EXPLAIN_EVIDENCE_GRAPH_V1.md @@ -0,0 +1,77 @@ +# Evidence graph contract `aien.explain.evidence-graph` v1 + +Language-neutral input of the explanation bridge. Any producer (Rust, C, Omega) +writes this JSON document; `aienos-explain` turns it into a grounded explanation +path. Field names, codes and meanings below are the contract; the Rust structs in +`src/contract.rs` are one implementation of it. + +## Document + +| field | type | meaning | +|---|---|---| +| `format` | string | always `aien.explain.evidence-graph` | +| `version` | u16 | `1` | +| `producer` | string | who wrote it, e.g. `spark-rsi/explain` | +| `nodes` | array of node | at most 65536 | +| `truncated_at` | array of string | node ids whose parents the producer did not expand because of its own limits (optional) | +| `scope` | object | optional `{ "branch": id, "referenced": [ids] }`: records a reasoning branch referenced directly | + +## Node + +| field | type | meaning | +|---|---|---| +| `id` | string | unique; namespaced by source, e.g. `cortex:<32 hex>`, `branch:<64 hex>`, `rsi:hypothesis:` | +| `kind` | u16 | artifact kind code (below) | +| `status` | u8 | epistemic status code (below) | +| `statement` | string | the claim or record, as recorded by the source | +| `source` | object | `{ system, artifact, reference, digest? }`; `digest` is lowercase hex | +| `confidence_permille` | u16 0..=1000 | only where the source has the concept (optional) | +| `confidence_basis` | string | where that number came from, e.g. "declared, not measured" (optional) | +| `recorded_at_utc` | u64 | informational only; never used for ordering or linking (optional) | +| `parents` | array of `{ to, relation }` | at most 1024; explicit links only | +| `measurements` | array of `{ name, value, unit }` | `value` is a decimal string formatted by the producer | +| `missing` | array of `{ expected, reason }` | links the producer knows should exist but has no artifact for | +| `notes` | array of string | caveats from the producer | + +## Codes + +Status (`status`), identical to aienos Cortex `EpistemicStatus` for 1..6: +0 Unclassified, 1 DirectObservation, 2 VerifiedFact, 3 Inference, 4 Hypothesis, +5 Contradiction, 6 OperatorDecision. Grounding statuses: 1, 2, 6. + +Kind (`kind`): 1 CortexRecord, 2 CapabilityMetric, 3 CapabilityAnalysis, +4 Diagnostic, 5 Hypothesis, 6 Prediction, 7 Falsification, 8 EvaluationReceipt, +9 PromotionState, 10 OperatorDecision, 11 AgentBranch, 12 Conclusion, 13 Alternative. + +Relation (`parents[].relation`), from the node to the parent: +1 SupportedBy, 2 Evaluates, 3 PartOf, 4 Contradicts, 5 AlternativeTo, 6 References. +Only 1, 2, 3 and 6 are support and are walked. 4 and 5 are disclosed (conflicts, +alternatives) and never count as support. +References (6) is the weak form of support: the producer uses it when a link is +inferred from matching content rather than a recorded id, and should also declare +the missing recorded link in `missing`. + +Errors (stable numeric codes): 1 BadFormat, 2 UnsupportedVersion, 3 UnknownCode, +4 DuplicateNodeId, 5 TargetNotFound, 6 GraphTooLarge, 7 StepOutOfRange, +8 NotInBranchScope, 9 Journal, 10 InvalidLimits. + +## Builder guarantees + +- Bounded: `max_depth` (default 32, cap 256) and `max_nodes` (default 256, cap 4096). +- Breadth-first walk from the target over support edges, parents in (relation, id) + order; grounding nodes end the walk. +- Loops are cut and reported (`Cycle`); unknown parents are reported + (`MissingParent`), never filled in; producer `missing` entries become `MissingLink`. +- A Contradicts edge is disclosed when either end is on the path, whatever the status + of the node carrying it (`ConflictingEvidence`). Contradicting nodes are never walked. +- Every visited node listed in `truncated_at` is reported as `Truncated`. +- Linear order: every step after the steps it rests on; ties by narrative role + (Observed, Analysis, Hypothesis, Prediction, Falsification, Evaluation, Decision, + Conclusion), then by id. The target is last. +- Deterministic: same document and limits give the same bundle and digest. +- The bundle has no field for prose or analogies and grants no authority. + +## Versioning + +Any change to a field meaning or a code is a new `version`. Adding an optional field +with a default is allowed within v1 only if old readers can ignore it safely. diff --git a/crates/aienos-explain/src/adapters.rs b/crates/aienos-explain/src/adapters.rs new file mode 100644 index 00000000..c32a2c6d --- /dev/null +++ b/crates/aienos-explain/src/adapters.rs @@ -0,0 +1,297 @@ +//! Producers of the evidence-graph contract from aienos Cortex records and agent +//! branches. Read-only: nothing here writes to Cortex or to agent state. +//! +//! The walk over Cortex is bounded by the same [`Limits`] the builder uses, plus one +//! level of headroom, and records where it stopped (`truncated_at`) so the builder can +//! say "cut short" instead of "missing". + +use crate::bundle::{hex, Limits}; +use crate::contract::{ + EdgeDoc, EvidenceGraph, ExplainError, NodeDoc, NodeKind, Relation, ScopeDoc, SourceRef, Status, +}; +use aienos_agent_state::LogicalBranch; +use aienos_cortex::{CortexStore, EpistemicRecord, EpistemicStatus}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; + +/// Node id of a Cortex record in the contract. +pub fn cortex_node_id(id: &[u8; 16]) -> String { + format!("cortex:{}", hex(id)) +} + +/// Node id of an agent branch in the contract. +pub fn branch_node_id(branch: &LogicalBranch) -> String { + format!("branch:{}", hex(&branch.branch_id.0)) +} + +fn status_code(s: EpistemicStatus) -> u8 { + s as u8 +} + +fn record_to_node(r: &EpistemicRecord) -> NodeDoc { + let rel = if r.status == EpistemicStatus::Contradiction { + Relation::Contradicts + } else { + Relation::SupportedBy + }; + let mut notes = Vec::new(); + if let Some(v) = &r.verified_by { + notes.push(format!("verified by {v}")); + } + let conf = r.confidence; + let permille = if conf.is_finite() { + Some((conf.clamp(0.0, 1.0) * 1000.0).round() as u16) + } else { + None + }; + NodeDoc { + id: cortex_node_id(&r.id), + kind: NodeKind::CortexRecord.code(), + status: status_code(r.status), + statement: r.statement.clone(), + source: SourceRef { + system: "aienos-cortex".into(), + artifact: "EpistemicRecord".into(), + reference: r.provenance_source.clone(), + digest: Some(hex(&r.evidence_hash)), + }, + confidence_permille: permille, + confidence_basis: permille.map(|_| "Cortex record confidence".to_string()), + recorded_at_utc: Some(r.created_at_utc), + parents: r + .causal_parents + .iter() + .map(|p| EdgeDoc { + to: cortex_node_id(p), + relation: rel.code(), + }) + .collect(), + measurements: Vec::new(), + missing: Vec::new(), + notes, + } +} + +/// Bounded backward walk over Cortex from `roots`, emitting reachable records plus +/// contradiction records that involve them. `lookup` is any read-only view of the +/// store (the real `CortexStore`, an imported journal, a test map). +pub fn cortex_graph_from<'a, F>( + roots: &[[u8; 16]], + lookup: F, + contradictions: &[&'a EpistemicRecord], + limits: Limits, +) -> EvidenceGraph +where + F: Fn(&[u8; 16]) -> Option<&'a EpistemicRecord>, +{ + let mut g = EvidenceGraph::new("aienos-explain/cortex-adapter"); + // Headroom: one extra level and node so the builder, not the adapter, decides + // where the explanation is cut. + let max_depth = limits.max_depth.saturating_add(1); + let max_nodes = limits.max_nodes.saturating_add(1) as usize; + let mut depth: BTreeMap<[u8; 16], u32> = BTreeMap::new(); + let mut order: Vec<[u8; 16]> = Vec::new(); + let mut queue: VecDeque<[u8; 16]> = VecDeque::new(); + let mut truncated: BTreeSet<[u8; 16]> = BTreeSet::new(); + let mut roots_sorted: Vec<[u8; 16]> = roots.to_vec(); + roots_sorted.sort(); + roots_sorted.dedup(); + for r in &roots_sorted { + if depth.contains_key(r) || lookup(r).is_none() { + continue; + } + if depth.len() >= max_nodes { + // Roots beyond the cap are dropped; mark every admitted root as cut so the + // builder says "cut short" rather than presenting a complete picture. + truncated.extend(depth.keys().copied()); + break; + } + depth.insert(*r, 0); + queue.push_back(*r); + } + while let Some(id) = queue.pop_front() { + let Some(rec) = lookup(&id) else { continue }; + order.push(id); + // Grounding records end the walk (except a root, which the builder may expand + // as its target). Contradiction records' parents are what they contradict, + // not support, so they are never walked. + if (rec.status.is_ground_truth() && !roots.contains(&id)) + || rec.status == EpistemicStatus::Contradiction + { + continue; + } + let d = depth[&id]; + let mut parents: Vec<[u8; 16]> = rec.causal_parents.clone(); + parents.sort(); + parents.dedup(); + for p in &parents { + if depth.contains_key(p) || lookup(p).is_none() { + continue; + } + if d + 1 > max_depth || depth.len() >= max_nodes { + truncated.insert(id); + continue; + } + depth.insert(*p, d + 1); + queue.push_back(*p); + } + } + let in_set: BTreeSet<[u8; 16]> = order.iter().copied().collect(); + let mut emitted: BTreeSet<[u8; 16]> = BTreeSet::new(); + for id in &order { + if let Some(r) = lookup(id) { + if emitted.insert(*id) { + g.nodes.push(record_to_node(r)); + } + } + } + // Contradictions about records in the set (disclosure, never support). + // Fixed order whatever order the store was built in. + let mut contradictions: Vec<&EpistemicRecord> = contradictions.to_vec(); + contradictions.sort_by_key(|r| (r.created_at_utc, r.id)); + contradictions.dedup_by(|a, b| a.id == b.id); + let mut extra = 0usize; + for c in contradictions { + if c.status != EpistemicStatus::Contradiction || emitted.contains(&c.id) { + continue; + } + if c.causal_parents.iter().any(|p| in_set.contains(p)) { + if extra >= max_nodes { + // Disclosure cap reached: mark the records this contradiction involves + // as cut so the builder reports that not everything was collected. + truncated.extend(c.causal_parents.iter().filter(|p| in_set.contains(*p))); + continue; + } + extra += 1; + emitted.insert(c.id); + g.nodes.push(record_to_node(c)); + } + } + g.truncated_at = truncated.iter().map(cortex_node_id).collect(); + g +} + +/// Evidence graph explaining one Cortex record. +pub fn cortex_graph_for_record( + store: &CortexStore, + record: &[u8; 16], + limits: Limits, +) -> Result { + if store.get(record).is_none() { + return Err(ExplainError::TargetNotFound(cortex_node_id(record))); + } + let contradictions = store.find_by_status(EpistemicStatus::Contradiction); + Ok(cortex_graph_from( + &[*record], + |id| store.get(id), + &contradictions, + limits, + )) +} + +/// Read a sealed Cortex journal (as written by `CortexStore::export_journal`) into a +/// fresh store. The seal is checked; the live store is never touched. +pub fn store_from_journal(bytes: &[u8]) -> Result { + let mut s = CortexStore::new(); + s.import_journal(bytes) + .map_err(|e| ExplainError::Journal(e.to_string()))?; + Ok(s) +} + +fn branch_node(branch: &LogicalBranch) -> NodeDoc { + let parent = branch + .parent_branch_id + .map(|p| hex(&p.0)[..16].to_string()) + .unwrap_or_else(|| "none (root branch)".into()); + NodeDoc { + id: branch_node_id(branch), + kind: NodeKind::AgentBranch.code(), + status: Status::Unclassified.code(), + statement: format!( + "Agent branch {} (lineage depth {}, parent {}) depends on {} referenced Cortex record(s)", + &hex(&branch.branch_id.0)[..16], + branch.lineage.depth, + parent, + branch.epistemic_refs.len() + ), + source: SourceRef { + system: "aienos-agent-state".into(), + artifact: "LogicalBranch".into(), + reference: hex(&branch.branch_id.0), + digest: None, + }, + confidence_permille: None, + confidence_basis: None, + recorded_at_utc: Some(branch.created_at_utc), + parents: branch + .epistemic_refs + .records() + .iter() + .map(|r| EdgeDoc { + to: cortex_node_id(r), + relation: Relation::References.code(), + }) + .collect(), + measurements: Vec::new(), + missing: Vec::new(), + notes: Vec::new(), + } +} + +/// "What evidence did this branch actually depend on?" The graph holds the branch, +/// the records it references, and their bounded causal ancestry. Records that exist +/// in Cortex but that the branch never referenced are not included. +pub fn branch_graph(store: &CortexStore, branch: &LogicalBranch, limits: Limits) -> EvidenceGraph { + let refs: Vec<[u8; 16]> = branch.epistemic_refs.records().to_vec(); + let contradictions = store.find_by_status(EpistemicStatus::Contradiction); + let mut g = cortex_graph_from(&refs, |id| store.get(id), &contradictions, limits); + g.producer = "aienos-explain/branch-adapter".into(); + g.nodes.insert(0, branch_node(branch)); + g.scope = Some(ScopeDoc { + branch: branch_node_id(branch), + referenced: refs.iter().map(cortex_node_id).collect(), + }); + g +} + +/// Explain one record as seen from a branch. Fails with `NotInBranchScope` when the +/// record is neither referenced by the branch nor in the support ancestry of a +/// referenced record, so unrelated Cortex facts cannot be pulled in to strengthen a +/// branch. Contradiction records that are only disclosed (they point at the branch's +/// evidence) are not in scope as targets. +pub fn branch_graph_for_record( + store: &CortexStore, + branch: &LogicalBranch, + record: &[u8; 16], + limits: Limits, +) -> Result { + let g = branch_graph(store, branch, limits); + let want = cortex_node_id(record); + let by_id: BTreeMap<&str, &NodeDoc> = g.nodes.iter().map(|n| (n.id.as_str(), n)).collect(); + let mut seen: BTreeSet<&str> = BTreeSet::new(); + let mut queue: VecDeque<&str> = VecDeque::new(); + if let Some(s) = &g.scope { + for r in &s.referenced { + if by_id.contains_key(r.as_str()) && seen.insert(r.as_str()) { + queue.push_back(r.as_str()); + } + } + } + while let Some(id) = queue.pop_front() { + for e in &by_id[id].parents { + let support = Relation::from_code(e.relation).map(|r| r.is_support()); + if support == Ok(true) + && by_id.contains_key(e.to.as_str()) + && seen.insert(e.to.as_str()) + { + queue.push_back(e.to.as_str()); + } + } + } + if !seen.contains(want.as_str()) { + return Err(ExplainError::NotInBranchScope(format!( + "{want} is not evidence that branch {} depends on", + branch_node_id(branch) + ))); + } + Ok(g) +} diff --git a/crates/aienos-explain/src/build.rs b/crates/aienos-explain/src/build.rs new file mode 100644 index 00000000..b84b1e60 --- /dev/null +++ b/crates/aienos-explain/src/build.rs @@ -0,0 +1,495 @@ +//! Bounded causal backtracking and linearization. +//! +//! Given an evidence graph and a target node, walk support edges backward +//! (breadth first, deterministic order), stop at grounding nodes and at the limits, +//! cut loops, keep every gap visible, then order the visited sub-graph so that +//! every step comes after the steps it rests on. Only explicit edges are followed; +//! time stamps are never used to order or connect steps. + +use crate::bundle::{ + hex, Alternative, CausalStep, ContradictionRef, EvidenceRef, ExplanationBundle, + ExplanationProvenance, Limits, Role, SupportLink, Uncertainty, UncertaintyKind, +}; +use crate::contract::{EvidenceGraph, ExplainError, NodeDoc, NodeKind, Relation, Status}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; + +/// Builder identity recorded in every bundle. +pub const BUILDER: &str = "aienos-explain/1"; + +struct Node<'a> { + doc: &'a NodeDoc, + kind: NodeKind, + status: Status, + /// Support parents, sorted by (relation code, id), duplicates removed. + support: Vec<(Relation, &'a str)>, +} + +fn index(graph: &EvidenceGraph) -> Result>, ExplainError> { + graph.validate()?; + let mut map = BTreeMap::new(); + for doc in &graph.nodes { + let kind = NodeKind::from_code(doc.kind)?; + let status = Status::from_code(doc.status)?; + let mut support: Vec<(Relation, &str)> = Vec::new(); + for e in &doc.parents { + let rel = Relation::from_code(e.relation)?; + if rel.is_support() { + support.push((rel, e.to.as_str())); + } + } + support.sort(); + support.dedup(); + map.insert( + doc.id.as_str(), + Node { + doc, + kind, + status, + support, + }, + ); + } + Ok(map) +} + +fn check_limits(l: &Limits) -> Result<(), ExplainError> { + if l.max_depth == 0 || l.max_nodes == 0 { + return Err(ExplainError::InvalidLimits( + "limits must be at least 1".into(), + )); + } + if l.max_depth > Limits::HARD_MAX_DEPTH || l.max_nodes > Limits::HARD_MAX_NODES { + return Err(ExplainError::InvalidLimits(format!( + "max_depth <= {}, max_nodes <= {}", + Limits::HARD_MAX_DEPTH, + Limits::HARD_MAX_NODES + ))); + } + Ok(()) +} + +/// Build the grounded explanation of `target` from `graph`. +pub fn build_bundle( + graph: &EvidenceGraph, + target: &str, + limits: Limits, +) -> Result { + check_limits(&limits)?; + let nodes = index(graph)?; + if !nodes.contains_key(target) { + return Err(ExplainError::TargetNotFound(target.to_string())); + } + let producer_truncated: BTreeSet<&str> = + graph.truncated_at.iter().map(|s| s.as_str()).collect(); + let scope_refs: BTreeSet<&str> = graph + .scope + .as_ref() + .map(|s| s.referenced.iter().map(|r| r.as_str()).collect()) + .unwrap_or_default(); + + let mut unc: Vec = Vec::new(); + + // 1. Bounded breadth-first discovery. depth = shortest edge count from target. + let mut depth: BTreeMap<&str, u32> = BTreeMap::new(); + let mut queue: VecDeque<&str> = VecDeque::new(); + depth.insert(target, 0); + queue.push_back(target); + let mut truncated_nodes: BTreeSet<&str> = BTreeSet::new(); + while let Some(id) = queue.pop_front() { + let n = &nodes[id]; + let d = depth[id]; + // Grounding nodes end the walk: their own parents are not needed to explain. + if n.status.is_grounding() && id != target { + continue; + } + for (_, pid) in &n.support { + if depth.contains_key(pid) { + continue; + } + if !nodes.contains_key(pid) { + if !producer_truncated.contains(id) { + unc.push(Uncertainty { + kind: UncertaintyKind::MissingParent, + node_id: id.to_string(), + related: Some(pid.to_string()), + detail: format!( + "{id} lists {pid} as support, but no such artifact is available; \ + the system has no evidence for that link" + ), + }); + } + continue; + } + if d + 1 > limits.max_depth || depth.len() as u32 >= limits.max_nodes { + truncated_nodes.insert(id); + continue; + } + depth.insert(*pid, d + 1); + queue.push_back(*pid); + } + } + for id in &truncated_nodes { + unc.push(Uncertainty { + kind: UncertaintyKind::Truncated, + node_id: id.to_string(), + related: None, + detail: format!( + "support of {id} was not followed further (depth limit {}, node limit {})", + limits.max_depth, limits.max_nodes + ), + }); + } + + // The producer also stopped somewhere (its own limits). Say so for every visited + // node it marked, even when no parent is visibly missing. + for id in &producer_truncated { + if depth.contains_key(id) && !truncated_nodes.contains(id) { + unc.push(Uncertainty { + kind: UncertaintyKind::Truncated, + node_id: id.to_string(), + related: None, + detail: format!( + "the producer of this graph stopped collecting evidence around {id} at \ + its own limits; more support or contradictions may exist" + ), + }); + } + } + + // 2. Visited support edges (child -> parent) restricted to the visited set. + let visited: BTreeSet<&str> = depth.keys().copied().collect(); + let mut edges: BTreeMap<&str, Vec<(Relation, &str)>> = BTreeMap::new(); + for id in &visited { + let n = &nodes[id]; + let keep: Vec<(Relation, &str)> = if n.status.is_grounding() && *id != target { + Vec::new() + } else { + n.support + .iter() + .filter(|(_, p)| visited.contains(p)) + .copied() + .collect() + }; + edges.insert(*id, keep); + } + + // 3. Cycle detection: iterative DFS with colors from the target; cut back edges. + let mut color: BTreeMap<&str, u8> = visited.iter().map(|v| (*v, 0u8)).collect(); + let mut cut: BTreeSet<(&str, &str)> = BTreeSet::new(); + let mut stack: Vec<(&str, usize)> = vec![(target, 0)]; + color.insert(target, 1); + while let Some((id, i)) = stack.pop() { + let es = &edges[id]; + if i < es.len() { + stack.push((id, i + 1)); + let p = es[i].1; + match color[p] { + 0 => { + color.insert(p, 1); + stack.push((p, 0)); + } + 1 => { + cut.insert((id, p)); + } + _ => {} + } + } else { + color.insert(id, 2); + } + } + for (from, to) in &cut { + unc.push(Uncertainty { + kind: UncertaintyKind::Cycle, + node_id: from.to_string(), + related: Some(to.to_string()), + detail: format!( + "{from} rests on {to}, which already rests on {from}; the loop was cut and \ + this support is circular, not grounding" + ), + }); + } + let dag: BTreeMap<&str, Vec<(Relation, &str)>> = edges + .iter() + .map(|(id, es)| { + ( + *id, + es.iter() + .filter(|(_, p)| !cut.contains(&(*id, *p))) + .copied() + .collect(), + ) + }) + .collect(); + + // 4. Linearize (Kahn): a node is ready once all its parents are placed. + // Ties are broken by narrative role, then by id. The target is always last. + let mut remaining: BTreeMap<&str, usize> = dag.iter().map(|(id, es)| (*id, es.len())).collect(); + let mut children: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); + for (id, es) in &dag { + for (_, p) in es { + children.entry(*p).or_default().push(*id); + } + } + let key = |id: &str| -> (Role, String) { + let n = &nodes[id]; + (Role::of(n.kind, n.status), id.to_string()) + }; + let mut ready: BTreeSet<(Role, String)> = remaining + .iter() + .filter(|(id, c)| **c == 0 && **id != target) + .map(|(id, _)| key(id)) + .collect(); + let mut order: Vec<&str> = Vec::new(); + while let Some(k) = ready.iter().next().cloned() { + ready.remove(&k); + let id: &str = visited.get(k.1.as_str()).copied().expect("visited id"); + order.push(id); + if let Some(cs) = children.get(id) { + for c in cs { + let r = remaining.get_mut(c).expect("child"); + *r -= 1; + if *r == 0 && *c != target { + ready.insert(key(c)); + } + } + } + } + order.push(target); + debug_assert_eq!(order.len(), visited.len()); + + // 5. Steps. + let pos: BTreeMap<&str, u32> = order + .iter() + .enumerate() + .map(|(i, id)| (*id, i as u32 + 1)) + .collect(); + let mut steps: Vec = Vec::with_capacity(order.len()); + for id in &order { + let n = &nodes[id]; + let mut supported_by: Vec = dag[id] + .iter() + .map(|(rel, p)| SupportLink { + step: pos[p], + relation: *rel, + }) + .collect(); + supported_by.sort_by_key(|s| (s.step, s.relation)); + steps.push(CausalStep { + index: pos[id], + node_id: id.to_string(), + kind: n.kind, + status: n.status, + role: Role::of(n.kind, n.status), + statement: n.doc.statement.clone(), + source: n.doc.source.clone(), + confidence_permille: n.doc.confidence_permille, + confidence_basis: n.doc.confidence_basis.clone(), + recorded_at_utc: n.doc.recorded_at_utc, + measurements: n.doc.measurements.clone(), + notes: n.doc.notes.clone(), + supported_by, + depth: depth[id], + grounding: n.status.is_grounding(), + branch_referenced: scope_refs.contains(id), + }); + } + + // 6. Per-step uncertainty that stays visible. + for s in &steps { + let n = &nodes[s.node_id.as_str()]; + for m in &n.doc.missing { + unc.push(Uncertainty { + kind: UncertaintyKind::MissingLink, + node_id: s.node_id.clone(), + related: Some(m.expected.clone()), + detail: format!("no evidence for: {} ({})", m.expected, m.reason), + }); + } + for note in &n.doc.notes { + unc.push(Uncertainty { + kind: UncertaintyKind::ProducerNote, + node_id: s.node_id.clone(), + related: None, + detail: note.clone(), + }); + } + if s.kind == NodeKind::AgentBranch { + continue; + } + let has_support = !n.support.is_empty() || !n.doc.missing.is_empty(); + match s.status { + Status::Unclassified => unc.push(Uncertainty { + kind: UncertaintyKind::Unknown, + node_id: s.node_id.clone(), + related: None, + detail: format!( + "the epistemic status of step {} is not known; it is neither observed \ + nor verified", + s.index + ), + }), + Status::Inference | Status::Hypothesis if !has_support => unc.push(Uncertainty { + kind: UncertaintyKind::Unsupported, + node_id: s.node_id.clone(), + related: None, + detail: format!( + "step {} is a {} with no recorded support", + s.index, + s.status.name() + ), + }), + Status::Inference => unc.push(Uncertainty { + kind: UncertaintyKind::Inferred, + node_id: s.node_id.clone(), + related: None, + detail: format!( + "step {} is inferred from earlier steps, not observed directly", + s.index + ), + }), + _ => {} + } + let is_hypothesis = s.kind == NodeKind::Hypothesis + || (s.kind == NodeKind::CortexRecord && s.status == Status::Hypothesis); + if is_hypothesis { + let tested = steps.iter().any(|o| { + let os = &nodes[o.node_id.as_str()].support; + (o.kind == NodeKind::EvaluationReceipt + && os + .iter() + .any(|(rel, p)| *rel == Relation::Evaluates && *p == s.node_id)) + || (o.kind == NodeKind::CortexRecord + && o.status == Status::VerifiedFact + && os.iter().any(|(_, p)| *p == s.node_id)) + }); + if !tested { + unc.push(Uncertainty { + kind: UncertaintyKind::HypothesisNotFalsified, + node_id: s.node_id.clone(), + related: None, + detail: format!( + "hypothesis at step {} has no evaluation that tests it directly; it \ + remains a hypothesis", + s.index + ), + }); + } + } + } + + // 7. Contradictions and alternatives that touch the path. A Contradicts edge is + // disclosed when either end is on the path, in either direction, whatever the + // status of the node that carries it. Bounded by the input size cap; never + // followed further. + let mut contradictions = Vec::new(); + let mut alternatives = Vec::new(); + for (id, n) in &nodes { + let mut targets: Vec = Vec::new(); + let mut alt_to: Option = None; + for e in &n.doc.parents { + let rel = Relation::from_code(e.relation)?; + match rel { + Relation::Contradicts => targets.push(e.to.clone()), + Relation::AlternativeTo if alt_to.is_none() && visited.contains(e.to.as_str()) => { + alt_to = Some(e.to.clone()) + } + _ => {} + } + } + let self_on_path = visited.contains(id); + let mut involves: Vec = targets + .iter() + .filter(|t| visited.contains(t.as_str())) + .cloned() + .collect(); + if !targets.is_empty() && self_on_path { + involves.push(id.to_string()); + } + involves.sort(); + involves.dedup(); + if !involves.is_empty() { + targets.sort(); + targets.dedup(); + let statement = if n.status == Status::Contradiction { + n.doc.statement.clone() + } else { + format!( + "{id} contradicts {}: {}", + targets.join(", "), + n.doc.statement + ) + }; + for t in &involves { + let other = if t.as_str() == *id { + targets.first().cloned().unwrap_or_default() + } else { + id.to_string() + }; + unc.push(Uncertainty { + kind: UncertaintyKind::ConflictingEvidence, + node_id: t.clone(), + related: Some(other), + detail: format!("{t} is involved in a recorded contradiction: {statement}"), + }); + } + contradictions.push(ContradictionRef { + node_id: id.to_string(), + statement, + source: n.doc.source.clone(), + involves, + }); + } + if let (NodeKind::Alternative, Some(to)) = (n.kind, alt_to) { + alternatives.push(Alternative { + node_id: id.to_string(), + statement: n.doc.statement.clone(), + source: n.doc.source.clone(), + alternative_to: to, + measurements: n.doc.measurements.clone(), + }); + } + } + + // 8. Evidence pointers: every step with a digest or measurements. + let evidence: Vec = steps + .iter() + .filter(|s| s.source.digest.is_some() || !s.measurements.is_empty()) + .map(|s| EvidenceRef { + step: s.index, + node_id: s.node_id.clone(), + source: s.source.clone(), + measurements: s.measurements.clone(), + }) + .collect(); + + unc.sort_by(|a, b| { + (a.kind, &a.node_id, &a.related, &a.detail) + .cmp(&(b.kind, &b.node_id, &b.related, &b.detail)) + }); + unc.dedup(); + + let provenance = ExplanationProvenance { + builder: BUILDER.to_string(), + contract_format: graph.format.clone(), + contract_version: graph.version, + producer: graph.producer.clone(), + input_digest: hex(&aienos_crypto::sha256::hash(&graph.to_json())), + target: target.to_string(), + limits, + branch_scope: graph.scope.as_ref().map(|s| s.branch.clone()), + visited_nodes: visited.len() as u32, + graph_nodes: graph.nodes.len() as u32, + }; + let mut bundle = ExplanationBundle { + conclusion_step: order.len() as u32, + steps, + evidence, + uncertainties: unc, + contradictions, + alternatives, + provenance, + bundle_digest: String::new(), + }; + bundle.bundle_digest = bundle.compute_digest(); + Ok(bundle) +} diff --git a/crates/aienos-explain/src/bundle.rs b/crates/aienos-explain/src/bundle.rs new file mode 100644 index 00000000..c01529b3 --- /dev/null +++ b/crates/aienos-explain/src/bundle.rs @@ -0,0 +1,306 @@ +//! The grounded explanation bundle: the authoritative, deterministic output of the +//! builder. Renderers only read it. It has no field for analogies or prose, and it +//! grants no authority (explanation is observational). + +use crate::contract::{Measurement, NodeKind, Relation, SourceRef, Status}; +use serde::{Serialize, Serializer}; + +fn ser_status(s: &Status, ser: S) -> Result { + ser.serialize_str(s.name()) +} +fn ser_kind(k: &NodeKind, ser: S) -> Result { + ser.serialize_str(k.name()) +} +fn ser_relation(r: &Relation, ser: S) -> Result { + ser.serialize_str(r.name()) +} + +/// Narrative role of a step in the path. Derived only from kind and status. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] +pub enum Role { + Observed, + Analysis, + Hypothesis, + Prediction, + Falsification, + Evaluation, + Decision, + Conclusion, +} + +impl Role { + pub fn of(kind: NodeKind, status: Status) -> Self { + match kind { + NodeKind::CapabilityMetric => Self::Observed, + NodeKind::CapabilityAnalysis | NodeKind::Diagnostic => Self::Analysis, + NodeKind::Hypothesis => Self::Hypothesis, + NodeKind::Prediction => Self::Prediction, + NodeKind::Falsification => Self::Falsification, + NodeKind::EvaluationReceipt => Self::Evaluation, + NodeKind::PromotionState | NodeKind::OperatorDecision => Self::Decision, + NodeKind::Conclusion | NodeKind::AgentBranch => Self::Conclusion, + NodeKind::Alternative => Self::Analysis, + NodeKind::CortexRecord => match status { + Status::DirectObservation | Status::VerifiedFact => Self::Observed, + Status::OperatorDecision => Self::Decision, + Status::Hypothesis => Self::Hypothesis, + Status::Inference | Status::Contradiction | Status::Unclassified => Self::Analysis, + }, + } + } + + pub fn heading(self) -> &'static str { + match self { + Self::Observed => "Observed", + Self::Analysis => "System analysis", + Self::Hypothesis => "Hypothesis", + Self::Prediction => "Prediction", + Self::Falsification => "Falsification", + Self::Evaluation => "Evaluation", + Self::Decision => "Decision", + Self::Conclusion => "Conclusion", + } + } +} + +/// A support link from a step to an earlier step. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct SupportLink { + /// 1-based index of the supporting step. + pub step: u32, + #[serde(serialize_with = "ser_relation")] + pub relation: Relation, +} + +/// One step of the linear path, in causal (parents first) order. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct CausalStep { + /// 1-based position in the path. + pub index: u32, + pub node_id: String, + #[serde(serialize_with = "ser_kind")] + pub kind: NodeKind, + #[serde(serialize_with = "ser_status")] + pub status: Status, + pub role: Role, + pub statement: String, + pub source: SourceRef, + pub confidence_permille: Option, + pub confidence_basis: Option, + pub recorded_at_utc: Option, + pub measurements: Vec, + pub notes: Vec, + /// Earlier steps this step rests on. + pub supported_by: Vec, + /// Shortest number of support edges from the conclusion. + pub depth: u32, + /// True when the status is a grounding status (observation, verified fact, + /// operator decision). + pub grounding: bool, + /// True when the branch in scope referenced this record directly. + pub branch_referenced: bool, +} + +/// Kinds of uncertainty kept visible in the explanation. Codes are stable. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] +pub enum UncertaintyKind { + /// A support edge points into itself through a loop; the loop edge was cut. + Cycle, + /// A contradiction record involves a step of this path. + ConflictingEvidence, + /// A parent id is listed but no such artifact exists. + MissingParent, + /// The producer declared a link it expected but has no artifact for. + MissingLink, + /// A derived claim (inference, hypothesis) has no recorded support at all. + Unsupported, + /// A hypothesis on the path has no evaluation step attached to it. + HypothesisNotFalsified, + /// The path is inferred (contains an inference that is not grounded only). + Inferred, + /// The artifact's epistemic status is unknown. + Unknown, + /// Traversal stopped at the depth or node limit. + Truncated, + /// Free-form caveat recorded by the producer (e.g. declared, not measured). + ProducerNote, +} + +impl UncertaintyKind { + pub fn code(self) -> u16 { + match self { + Self::Cycle => 1, + Self::ConflictingEvidence => 2, + Self::MissingParent => 3, + Self::MissingLink => 4, + Self::Unsupported => 5, + Self::HypothesisNotFalsified => 6, + Self::Inferred => 7, + Self::Unknown => 8, + Self::Truncated => 9, + Self::ProducerNote => 10, + } + } + + pub fn label(self) -> &'static str { + match self { + Self::Cycle => "circular support", + Self::ConflictingEvidence => "conflicting evidence", + Self::MissingParent => "missing evidence", + Self::MissingLink => "missing link", + Self::Unsupported => "unsupported claim", + Self::HypothesisNotFalsified => "hypothesis not yet tested", + Self::Inferred => "inferred step", + Self::Unknown => "unknown status", + Self::Truncated => "explanation cut short", + Self::ProducerNote => "caveat", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Uncertainty { + pub kind: UncertaintyKind, + /// Node the uncertainty is attached to. + pub node_id: String, + /// Other id involved (missing parent, loop target, expected link). + pub related: Option, + pub detail: String, +} + +/// A contradiction record that involves the path. Always shown. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct ContradictionRef { + pub node_id: String, + pub statement: String, + pub source: SourceRef, + /// Path node ids the contradiction involves. + pub involves: Vec, +} + +/// An alternative explanation that the evidence explicitly records. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Alternative { + pub node_id: String, + pub statement: String, + pub source: SourceRef, + pub alternative_to: String, + pub measurements: Vec, +} + +/// An evidence pointer (digest, receipt, measurements) attached to a step. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct EvidenceRef { + pub step: u32, + pub node_id: String, + pub source: SourceRef, + pub measurements: Vec, +} + +/// Limits used for the traversal. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct Limits { + pub max_depth: u32, + pub max_nodes: u32, +} + +impl Limits { + pub const HARD_MAX_DEPTH: u32 = 256; + pub const HARD_MAX_NODES: u32 = 4096; +} + +impl Default for Limits { + fn default() -> Self { + Self { + max_depth: 32, + max_nodes: 256, + } + } +} + +/// How the bundle was built. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct ExplanationProvenance { + pub builder: String, + pub contract_format: String, + pub contract_version: u16, + pub producer: String, + /// sha256 of the canonical input graph JSON, lowercase hex. + pub input_digest: String, + pub target: String, + pub limits: Limits, + pub branch_scope: Option, + /// Number of nodes visited out of the number in the input graph. + pub visited_nodes: u32, + pub graph_nodes: u32, +} + +/// The authoritative explanation. Deterministic for identical input and limits. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct ExplanationBundle { + /// The conclusion is always the last step. + pub conclusion_step: u32, + pub steps: Vec, + pub evidence: Vec, + pub uncertainties: Vec, + pub contradictions: Vec, + pub alternatives: Vec, + pub provenance: ExplanationProvenance, + /// sha256 of the canonical JSON of every field above, lowercase hex. + pub bundle_digest: String, +} + +impl ExplanationBundle { + pub fn conclusion(&self) -> &CausalStep { + &self.steps[(self.conclusion_step - 1) as usize] + } + + pub fn step(&self, index: u32) -> Option<&CausalStep> { + if index == 0 { + return None; + } + self.steps.get((index - 1) as usize) + } + + /// Canonical JSON of the bundle. + pub fn to_json(&self) -> String { + serde_json::to_string_pretty(self).expect("bundle serializes") + } + + /// Recompute the digest over the content (excluding the digest field). + pub fn compute_digest(&self) -> String { + #[derive(Serialize)] + struct Content<'a> { + conclusion_step: u32, + steps: &'a [CausalStep], + evidence: &'a [EvidenceRef], + uncertainties: &'a [Uncertainty], + contradictions: &'a [ContradictionRef], + alternatives: &'a [Alternative], + provenance: &'a ExplanationProvenance, + } + let c = Content { + conclusion_step: self.conclusion_step, + steps: &self.steps, + evidence: &self.evidence, + uncertainties: &self.uncertainties, + contradictions: &self.contradictions, + alternatives: &self.alternatives, + provenance: &self.provenance, + }; + hex(&aienos_crypto::sha256::hash( + &serde_json::to_vec(&c).expect("bundle serializes"), + )) + } +} + +/// Lowercase hex. +pub fn hex(bytes: &[u8]) -> String { + const H: &[u8; 16] = b"0123456789abcdef"; + let mut s = String::with_capacity(bytes.len() * 2); + for b in bytes { + s.push(H[(b >> 4) as usize] as char); + s.push(H[(b & 15) as usize] as char); + } + s +} diff --git a/crates/aienos-explain/src/contract.rs b/crates/aienos-explain/src/contract.rs new file mode 100644 index 00000000..933ede0b --- /dev/null +++ b/crates/aienos-explain/src/contract.rs @@ -0,0 +1,463 @@ +//! Evidence graph contract `aien.explain.evidence-graph` version 1. +//! +//! This is the language-neutral boundary of the explanation bridge. Any producer +//! (the aienos Cortex adapter, spark-rsi, a future omega `rx_cortex` exporter written +//! in C or Omega) emits this plain JSON document; the builder consumes it. The +//! canonical form is the JSON described in `docs/EXPLAIN_EVIDENCE_GRAPH_V1.md`: +//! string ids, small unsigned integer codes, per-mille integer confidence, and +//! producer-formatted decimal strings for measurements. No Rust enum layout and no +//! floating point value is part of the canonical format. + +use serde::{Deserialize, Serialize}; + +/// Format tag every v1 document carries. +pub const FORMAT: &str = "aien.explain.evidence-graph"; +/// Contract version understood by this crate. +pub const VERSION: u16 = 1; +/// Hard cap on nodes in one input document (adversarial input bound). +pub const MAX_GRAPH_NODES: usize = 65_536; +/// Hard cap on parent edges of one node. +pub const MAX_PARENTS_PER_NODE: usize = 1_024; + +/// Explicit error codes. The numeric code is part of the contract (stable across +/// languages); the message is for humans. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ExplainError { + /// 1: document is not valid JSON or misses required fields. + BadFormat(String), + /// 2: `format` or `version` is not one this crate understands. + UnsupportedVersion(String), + /// 3: an integer code (status, kind, relation) is outside the contract. + UnknownCode { field: &'static str, value: u32 }, + /// 4: two nodes share an id. + DuplicateNodeId(String), + /// 5: the artifact to explain is not in the graph. + TargetNotFound(String), + /// 6: the document exceeds a hard size cap. + GraphTooLarge(String), + /// 7: a clarification asked for a step that does not exist. + StepOutOfRange(u32), + /// 8: the record is not part of the evidence the branch depends on. + NotInBranchScope(String), + /// 9: the Cortex journal could not be read or failed its seal. + Journal(String), + /// 10: limits are zero or above the hard caps. + InvalidLimits(String), +} + +impl ExplainError { + /// Stable numeric error code. + pub fn code(&self) -> u16 { + match self { + Self::BadFormat(_) => 1, + Self::UnsupportedVersion(_) => 2, + Self::UnknownCode { .. } => 3, + Self::DuplicateNodeId(_) => 4, + Self::TargetNotFound(_) => 5, + Self::GraphTooLarge(_) => 6, + Self::StepOutOfRange(_) => 7, + Self::NotInBranchScope(_) => 8, + Self::Journal(_) => 9, + Self::InvalidLimits(_) => 10, + } + } +} + +impl core::fmt::Display for ExplainError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let code = self.code(); + match self { + Self::BadFormat(m) => write!(f, "E{code} bad format: {m}"), + Self::UnsupportedVersion(m) => write!(f, "E{code} unsupported version: {m}"), + Self::UnknownCode { field, value } => { + write!(f, "E{code} unknown code {value} in field {field}") + } + Self::DuplicateNodeId(id) => write!(f, "E{code} duplicate node id {id}"), + Self::TargetNotFound(id) => write!(f, "E{code} artifact not found: {id}"), + Self::GraphTooLarge(m) => write!(f, "E{code} graph too large: {m}"), + Self::StepOutOfRange(n) => write!(f, "E{code} no step {n} in this explanation"), + Self::NotInBranchScope(m) => write!(f, "E{code} not in branch scope: {m}"), + Self::Journal(m) => write!(f, "E{code} Cortex journal: {m}"), + Self::InvalidLimits(m) => write!(f, "E{code} invalid limits: {m}"), + } + } +} + +impl std::error::Error for ExplainError {} + +/// Epistemic status code. 1..=6 are exactly the aienos Cortex `EpistemicStatus` +/// numbering; 0 means the producer could not classify the artifact. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Status { + Unclassified, + DirectObservation, + VerifiedFact, + Inference, + Hypothesis, + Contradiction, + OperatorDecision, +} + +impl Status { + pub fn from_code(code: u8) -> Result { + Ok(match code { + 0 => Self::Unclassified, + 1 => Self::DirectObservation, + 2 => Self::VerifiedFact, + 3 => Self::Inference, + 4 => Self::Hypothesis, + 5 => Self::Contradiction, + 6 => Self::OperatorDecision, + v => { + return Err(ExplainError::UnknownCode { + field: "status", + value: v as u32, + }) + } + }) + } + + pub fn code(self) -> u8 { + match self { + Self::Unclassified => 0, + Self::DirectObservation => 1, + Self::VerifiedFact => 2, + Self::Inference => 3, + Self::Hypothesis => 4, + Self::Contradiction => 5, + Self::OperatorDecision => 6, + } + } + + /// Grounding statuses end a backward walk (same set as Cortex `is_ground_truth`). + pub fn is_grounding(self) -> bool { + matches!( + self, + Self::DirectObservation | Self::VerifiedFact | Self::OperatorDecision + ) + } + + /// Technical name (matches the Cortex enum variant names). + pub fn name(self) -> &'static str { + match self { + Self::Unclassified => "Unclassified", + Self::DirectObservation => "DirectObservation", + Self::VerifiedFact => "VerifiedFact", + Self::Inference => "Inference", + Self::Hypothesis => "Hypothesis", + Self::Contradiction => "Contradiction", + Self::OperatorDecision => "OperatorDecision", + } + } +} + +/// What kind of artifact a node is. Codes are part of the contract. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum NodeKind { + CortexRecord, + CapabilityMetric, + CapabilityAnalysis, + Diagnostic, + Hypothesis, + Prediction, + Falsification, + EvaluationReceipt, + PromotionState, + OperatorDecision, + AgentBranch, + Conclusion, + Alternative, +} + +impl NodeKind { + pub fn from_code(code: u16) -> Result { + Ok(match code { + 1 => Self::CortexRecord, + 2 => Self::CapabilityMetric, + 3 => Self::CapabilityAnalysis, + 4 => Self::Diagnostic, + 5 => Self::Hypothesis, + 6 => Self::Prediction, + 7 => Self::Falsification, + 8 => Self::EvaluationReceipt, + 9 => Self::PromotionState, + 10 => Self::OperatorDecision, + 11 => Self::AgentBranch, + 12 => Self::Conclusion, + 13 => Self::Alternative, + v => { + return Err(ExplainError::UnknownCode { + field: "kind", + value: v as u32, + }) + } + }) + } + + pub fn code(self) -> u16 { + match self { + Self::CortexRecord => 1, + Self::CapabilityMetric => 2, + Self::CapabilityAnalysis => 3, + Self::Diagnostic => 4, + Self::Hypothesis => 5, + Self::Prediction => 6, + Self::Falsification => 7, + Self::EvaluationReceipt => 8, + Self::PromotionState => 9, + Self::OperatorDecision => 10, + Self::AgentBranch => 11, + Self::Conclusion => 12, + Self::Alternative => 13, + } + } + + pub fn name(self) -> &'static str { + match self { + Self::CortexRecord => "CortexRecord", + Self::CapabilityMetric => "CapabilityMetric", + Self::CapabilityAnalysis => "CapabilityAnalysis", + Self::Diagnostic => "Diagnostic", + Self::Hypothesis => "Hypothesis", + Self::Prediction => "Prediction", + Self::Falsification => "Falsification", + Self::EvaluationReceipt => "EvaluationReceipt", + Self::PromotionState => "PromotionState", + Self::OperatorDecision => "OperatorDecision", + Self::AgentBranch => "AgentBranch", + Self::Conclusion => "Conclusion", + Self::Alternative => "Alternative", + } + } +} + +/// How a node relates to one of its listed parents. Codes are part of the contract. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Relation { + /// The node rests on the parent (causal parent, derived from, input to). + SupportedBy, + /// The node is an evaluation or test result of the parent. + Evaluates, + /// The node is a component of the parent (prediction of a hypothesis). + PartOf, + /// The node records a conflict involving the parent (not support). + Contradicts, + /// The node is an explicitly recorded alternative to the parent (not support). + AlternativeTo, + /// A branch references the parent as evidence it depends on. + References, +} + +impl Relation { + pub fn from_code(code: u16) -> Result { + Ok(match code { + 1 => Self::SupportedBy, + 2 => Self::Evaluates, + 3 => Self::PartOf, + 4 => Self::Contradicts, + 5 => Self::AlternativeTo, + 6 => Self::References, + v => { + return Err(ExplainError::UnknownCode { + field: "relation", + value: v as u32, + }) + } + }) + } + + pub fn code(self) -> u16 { + match self { + Self::SupportedBy => 1, + Self::Evaluates => 2, + Self::PartOf => 3, + Self::Contradicts => 4, + Self::AlternativeTo => 5, + Self::References => 6, + } + } + + /// Only these relations are followed backward as support. Contradiction and + /// alternative links are disclosed separately and never count as support. + pub fn is_support(self) -> bool { + matches!( + self, + Self::SupportedBy | Self::Evaluates | Self::PartOf | Self::References + ) + } + + pub fn name(self) -> &'static str { + match self { + Self::SupportedBy => "SupportedBy", + Self::Evaluates => "Evaluates", + Self::PartOf => "PartOf", + Self::Contradicts => "Contradicts", + Self::AlternativeTo => "AlternativeTo", + Self::References => "References", + } + } +} + +/// Where a node came from. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SourceRef { + /// Producing system, e.g. `aienos-cortex`, `aienos-agent-state`, `spark-rsi`. + pub system: String, + /// Artifact type in that system, e.g. `EpistemicRecord`, `HypothesisContract`. + pub artifact: String, + /// Identifier or provenance string inside that system. + pub reference: String, + /// Content digest or receipt digest as lowercase hex, when one exists. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub digest: Option, +} + +/// One named measurement. The value is a decimal string formatted by the producer. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Measurement { + pub name: String, + pub value: String, + #[serde(default)] + pub unit: String, +} + +/// A parent edge as written in the document. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EdgeDoc { + pub to: String, + pub relation: u16, +} + +/// A link the producer knows should exist but has no artifact for. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct MissingDoc { + pub expected: String, + pub reason: String, +} + +/// One evidence node as written in the document. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct NodeDoc { + pub id: String, + pub kind: u16, + pub status: u8, + pub statement: String, + pub source: SourceRef, + /// Confidence in thousandths, only where the source system has the concept. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub confidence_permille: Option, + /// Where the confidence number came from (declared, computed, recorded). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub confidence_basis: Option, + /// Recording time from the source, informational only. Never used for ordering: + /// time order is not causal order. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub recorded_at_utc: Option, + #[serde(default)] + pub parents: Vec, + #[serde(default)] + pub measurements: Vec, + #[serde(default)] + pub missing: Vec, + #[serde(default)] + pub notes: Vec, +} + +/// Optional branch scope: which records a reasoning branch actually referenced. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ScopeDoc { + pub branch: String, + pub referenced: Vec, +} + +/// The whole document. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EvidenceGraph { + pub format: String, + pub version: u16, + pub producer: String, + pub nodes: Vec, + /// Nodes whose parents the producer did not expand because of its own limits. + #[serde(default)] + pub truncated_at: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scope: Option, +} + +impl EvidenceGraph { + /// Empty v1 document for a producer. + pub fn new(producer: impl Into) -> Self { + Self { + format: FORMAT.to_string(), + version: VERSION, + producer: producer.into(), + nodes: Vec::new(), + truncated_at: Vec::new(), + scope: None, + } + } + + /// Parse and validate a JSON document. + pub fn from_json(bytes: &[u8]) -> Result { + let g: Self = + serde_json::from_slice(bytes).map_err(|e| ExplainError::BadFormat(e.to_string()))?; + g.validate()?; + Ok(g) + } + + /// Canonical JSON bytes (field order fixed by the struct, node order as given). + pub fn to_json(&self) -> Vec { + serde_json::to_vec(self).expect("evidence graph serializes") + } + + /// Check format tag, version, size caps, codes and id uniqueness. + pub fn validate(&self) -> Result<(), ExplainError> { + if self.format != FORMAT { + return Err(ExplainError::UnsupportedVersion(format!( + "format {:?}, expected {:?}", + self.format, FORMAT + ))); + } + if self.version != VERSION { + return Err(ExplainError::UnsupportedVersion(format!( + "version {}, expected {}", + self.version, VERSION + ))); + } + if self.nodes.len() > MAX_GRAPH_NODES { + return Err(ExplainError::GraphTooLarge(format!( + "{} nodes, cap {}", + self.nodes.len(), + MAX_GRAPH_NODES + ))); + } + let mut seen = std::collections::BTreeSet::new(); + for n in &self.nodes { + if !seen.insert(n.id.as_str()) { + return Err(ExplainError::DuplicateNodeId(n.id.clone())); + } + NodeKind::from_code(n.kind)?; + Status::from_code(n.status)?; + if n.parents.len() > MAX_PARENTS_PER_NODE { + return Err(ExplainError::GraphTooLarge(format!( + "node {} has {} parents, cap {}", + n.id, + n.parents.len(), + MAX_PARENTS_PER_NODE + ))); + } + for e in &n.parents { + Relation::from_code(e.relation)?; + } + if let Some(c) = n.confidence_permille { + if c > 1000 { + return Err(ExplainError::UnknownCode { + field: "confidence_permille", + value: c as u32, + }); + } + } + } + Ok(()) + } +} diff --git a/crates/aienos-explain/src/lib.rs b/crates/aienos-explain/src/lib.rs new file mode 100644 index 00000000..479e5b46 --- /dev/null +++ b/crates/aienos-explain/src/lib.rs @@ -0,0 +1,29 @@ +//! AIENOS explanation bridge: think in graphs, speak in paths. +//! +//! Machine artifacts (Cortex records, agent branches, RSI hypothesis contracts, +//! evaluation receipts) are expressed in the language-neutral evidence-graph contract +//! ([`contract`]). The builder ([`build`]) walks explicit support edges backward with +//! hard limits, cuts loops, keeps gaps visible and orders the result into a path: the +//! [`bundle::ExplanationBundle`], which is the authoritative explanation. Renderers +//! ([`render`], [`session`]) are pure projections of the bundle. +//! +//! Boundaries: +//! - host-side only; nothing here is part of the C kernel or the boot path; +//! - read-only: no function writes to Cortex or agent state; +//! - no hidden reasoning: inputs are records, never token histories or model text; +//! - analogies live only in the renderer and are never evidence; +//! - an explanation grants no authority and is not an approval of anything; +//! - no network, no model, no outside service. + +pub mod adapters; +pub mod build; +pub mod bundle; +pub mod contract; +pub mod render; +pub mod session; + +pub use build::build_bundle; +pub use bundle::{ExplanationBundle, Limits}; +pub use contract::{EvidenceGraph, ExplainError}; +pub use render::{render, Audience, ExplanationRequest, Mode}; +pub use session::ExplanationSession; diff --git a/crates/aienos-explain/src/main.rs b/crates/aienos-explain/src/main.rs new file mode 100644 index 00000000..5d65ec5d --- /dev/null +++ b/crates/aienos-explain/src/main.rs @@ -0,0 +1,194 @@ +//! `aienos-explain`: host-side operator command for grounded explanations. +//! +//! aienos-explain explain (--graph FILE | --cortex-journal FILE) --artifact ID +//! [--summary | --why | --technical | --analogy] [--depth 0-4] [--evidence] +//! [--uncertain] [--alternatives] [--step N] [--source N] +//! [--audience general|operator|developer|systems-engineer|researcher] +//! [--max-depth N] [--max-nodes N] [--json] +//! +//! Exit codes: 0 ok, 2 usage error, 10 + contract error code on explanation errors. + +use aienos_explain::adapters::{cortex_graph_for_record, store_from_journal}; +use aienos_explain::contract::{EvidenceGraph, ExplainError}; +use aienos_explain::{ + build_bundle, render, Audience, ExplanationRequest, ExplanationSession, Limits, Mode, +}; +use std::process::ExitCode; + +const USAGE: &str = + "usage: aienos-explain explain (--graph FILE | --cortex-journal FILE) --artifact ID \ +[--summary|--why|--technical|--analogy] [--depth 0-4] [--evidence] [--uncertain] [--alternatives] \ +[--step N] [--source N] [--audience general|operator|developer|systems-engineer|researcher] \ +[--max-depth N] [--max-nodes N] [--json]"; + +struct Args { + graph: Option, + journal: Option, + artifact: Option, + mode: Mode, + depth: Option, + evidence: bool, + uncertain: bool, + alternatives: bool, + step: Option, + source: Option, + audience: Audience, + limits: Limits, + json: bool, +} + +fn parse(argv: &[String]) -> Result { + if argv.first().map(String::as_str) != Some("explain") { + return Err(USAGE.into()); + } + let mut a = Args { + graph: None, + journal: None, + artifact: None, + mode: Mode::StepByStep, + depth: None, + evidence: false, + uncertain: false, + alternatives: false, + step: None, + source: None, + audience: Audience::Operator, + limits: Limits::default(), + json: false, + }; + let mut i = 1; + let val = |i: &mut usize| -> Result { + *i += 1; + argv.get(*i) + .cloned() + .ok_or_else(|| format!("missing value for {}", argv[*i - 1])) + }; + let num = |s: String| -> Result { + s.parse::().map_err(|_| format!("not a number: {s}")) + }; + while i < argv.len() { + match argv[i].as_str() { + "--graph" => a.graph = Some(val(&mut i)?), + "--cortex-journal" => a.journal = Some(val(&mut i)?), + "--artifact" => a.artifact = Some(val(&mut i)?), + "--summary" => a.mode = Mode::Summary, + "--why" => a.mode = Mode::StepByStep, + "--technical" => a.mode = Mode::Technical, + "--analogy" => a.mode = Mode::Analogy, + "--depth" => { + let d = num(val(&mut i)?)?; + if d > 4 { + return Err("--depth is 0 to 4".into()); + } + a.depth = Some(d as u8); + } + "--evidence" => a.evidence = true, + "--uncertain" => a.uncertain = true, + "--alternatives" => a.alternatives = true, + "--step" => a.step = Some(num(val(&mut i)?)?), + "--source" => a.source = Some(num(val(&mut i)?)?), + "--audience" => { + let v = val(&mut i)?; + a.audience = Audience::parse(&v).ok_or_else(|| format!("unknown audience {v}"))?; + } + "--max-depth" => a.limits.max_depth = num(val(&mut i)?)?, + "--max-nodes" => a.limits.max_nodes = num(val(&mut i)?)?, + "--json" => a.json = true, + other => return Err(format!("unknown argument {other}\n{USAGE}")), + } + i += 1; + } + if a.graph.is_some() == a.journal.is_some() { + return Err(format!( + "give exactly one of --graph or --cortex-journal\n{USAGE}" + )); + } + if a.artifact.is_none() { + return Err(format!("--artifact is required\n{USAGE}")); + } + Ok(a) +} + +fn parse_cortex_id(s: &str) -> Result<[u8; 16], ExplainError> { + let h = s.strip_prefix("cortex:").unwrap_or(s); + if h.len() != 32 || !h.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(ExplainError::TargetNotFound(format!( + "{s} is not a 32-hex-digit Cortex record id" + ))); + } + let mut id = [0u8; 16]; + for (k, b) in id.iter_mut().enumerate() { + *b = u8::from_str_radix(&h[2 * k..2 * k + 2], 16).expect("hex checked"); + } + Ok(id) +} + +fn run(a: Args) -> Result { + let artifact = a.artifact.clone().expect("checked"); + let (graph, target) = if let Some(path) = &a.graph { + let bytes = + std::fs::read(path).map_err(|e| ExplainError::BadFormat(format!("{path}: {e}")))?; + (EvidenceGraph::from_json(&bytes)?, artifact) + } else { + let path = a.journal.as_ref().expect("checked"); + let bytes = + std::fs::read(path).map_err(|e| ExplainError::Journal(format!("{path}: {e}")))?; + let store = store_from_journal(&bytes)?; + let id = parse_cortex_id(&artifact)?; + let g = cortex_graph_for_record(&store, &id, a.limits)?; + (g, aienos_explain::adapters::cortex_node_id(&id)) + }; + let bundle = build_bundle(&graph, &target, a.limits)?; + if a.json { + return Ok(bundle.to_json() + "\n"); + } + let session = ExplanationSession::new(bundle, a.audience); + if let Some(n) = a.step { + return session.step(n); + } + if let Some(n) = a.source { + return session.source(n); + } + let mut out = render( + session.bundle(), + &ExplanationRequest { + mode: a.mode, + level: a.depth, + audience: a.audience, + }, + ); + if a.evidence { + out.push_str("\nEvidence:\n"); + out.push_str(&session.evidence()); + } + if a.uncertain { + out.push_str("\nUncertain about:\n"); + out.push_str(&session.uncertainties()); + } + if a.alternatives { + out.push_str("\nAlternatives:\n"); + out.push_str(&session.alternatives()); + } + Ok(out) +} + +fn main() -> ExitCode { + let argv: Vec = std::env::args().skip(1).collect(); + let args = match parse(&argv) { + Ok(a) => a, + Err(e) => { + eprintln!("{e}"); + return ExitCode::from(2); + } + }; + match run(args) { + Ok(text) => { + print!("{text}"); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("error {e}"); + ExitCode::from(10 + e.code() as u8) + } + } +} diff --git a/crates/aienos-explain/src/render.rs b/crates/aienos-explain/src/render.rs new file mode 100644 index 00000000..e3698562 --- /dev/null +++ b/crates/aienos-explain/src/render.rs @@ -0,0 +1,535 @@ +//! Deterministic presentation of an [`ExplanationBundle`]. +//! +//! Every function here takes the bundle by shared reference and returns text. The +//! renderer can drop detail, but it can never change a step's status, add a step, or +//! add evidence. Analogies come from a fixed catalog in this module, are always +//! labelled as illustrations, and are always followed by the evidence itself. + +use crate::bundle::{CausalStep, ExplanationBundle, Role, Uncertainty, UncertaintyKind}; +use crate::contract::{NodeKind, Relation, Status}; +use std::fmt::Write; + +/// Presentation mode. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// Conclusion, strongest reason, strongest evidence, material uncertainty. + Summary, + /// The path, step by step, grouped under role headings. + StepByStep, + /// Identifiers, statuses, digests, measurements, uncertainty codes. + Technical, + /// A familiar picture first (labelled), then the evidence path. + Analogy, +} + +/// Who is reading. Explicit only; nothing is inferred about the reader. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Audience { + General, + Operator, + Developer, + SystemsEngineer, + Researcher, +} + +impl Audience { + pub fn parse(s: &str) -> Option { + Some(match s { + "general" => Self::General, + "operator" => Self::Operator, + "developer" => Self::Developer, + "systems-engineer" => Self::SystemsEngineer, + "researcher" => Self::Researcher, + _ => return None, + }) + } + + fn shows_ids(self) -> bool { + !matches!(self, Self::General) + } +} + +/// Progressive disclosure: 0 conclusion, 1 principal reasons, 2 causal path, +/// 3 evidence and measurements, 4 raw provenance references. +pub const MAX_LEVEL: u8 = 4; + +/// What to show. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ExplanationRequest { + pub mode: Mode, + /// Disclosure level 0..=4; `None` uses the mode's default. + pub level: Option, + pub audience: Audience, +} + +impl ExplanationRequest { + pub fn new(mode: Mode) -> Self { + Self { + mode, + level: None, + audience: Audience::Operator, + } + } + + pub fn effective_level(&self) -> u8 { + let d = match self.mode { + Mode::Summary => 1, + Mode::StepByStep | Mode::Analogy => 2, + Mode::Technical => 4, + }; + self.level.unwrap_or(d).min(MAX_LEVEL) + } +} + +/// Plain words for a status. A hypothesis is never described as verified or proven. +pub fn status_words(s: Status) -> &'static str { + match s { + Status::DirectObservation => "observed", + Status::VerifiedFact => "checked fact", + Status::Inference => "inferred, not checked", + Status::Hypothesis => "hypothesis, not yet established", + Status::Contradiction => "conflict between records", + Status::OperatorDecision => "operator decision", + Status::Unclassified => "status unknown", + } +} + +fn short(id: &str) -> String { + match id.split_once(':') { + Some((ns, rest)) if rest.chars().count() > 12 => { + format!("{ns}:{}", rest.chars().take(12).collect::()) + } + _ => id.to_string(), + } +} + +fn step_line(s: &CausalStep, level: u8, aud: Audience) -> String { + let mut out = format!("{}. [{}] {}", s.index, status_words(s.status), s.statement); + if level >= 2 { + let strong: Vec = s + .supported_by + .iter() + .filter(|l| l.relation != Relation::References) + .map(|l| l.step.to_string()) + .collect(); + let weak: Vec = s + .supported_by + .iter() + .filter(|l| l.relation == Relation::References) + .map(|l| l.step.to_string()) + .collect(); + if !strong.is_empty() { + let _ = write!(out, " (rests on step {})", strong.join(", ")); + } + if !weak.is_empty() { + let _ = write!( + out, + " (refers to step {}; a weak link, not a recorded one)", + weak.join(", ") + ); + } + } + if aud.shows_ids() { + let _ = write!(out, " [{} {}]", s.source.system, short(&s.node_id)); + } else { + let _ = write!(out, " [from {}]", s.source.system); + } + if s.branch_referenced { + out.push_str(" (referenced by the branch)"); + } + out +} + +fn measurements_line(s: &CausalStep) -> Option { + if s.measurements.is_empty() { + return None; + } + let ms: Vec = s + .measurements + .iter() + .map(|m| { + if m.unit.is_empty() { + format!("{}={}", m.name, m.value) + } else { + format!("{}={} {}", m.name, m.value, m.unit) + } + }) + .collect(); + Some(format!(" measurements: {}", ms.join(", "))) +} + +fn severity(k: UncertaintyKind) -> u8 { + match k { + UncertaintyKind::Cycle => 0, + UncertaintyKind::ConflictingEvidence => 1, + UncertaintyKind::MissingParent => 2, + UncertaintyKind::MissingLink => 3, + UncertaintyKind::Unsupported => 4, + UncertaintyKind::HypothesisNotFalsified => 5, + UncertaintyKind::Unknown => 6, + UncertaintyKind::Truncated => 7, + UncertaintyKind::ProducerNote => 8, + UncertaintyKind::Inferred => 9, + } +} + +fn material(b: &ExplanationBundle) -> Option<&Uncertainty> { + b.uncertainties + .iter() + .min_by_key(|u| (severity(u.kind), u.node_id.clone(), u.detail.clone())) +} + +fn uncertainty_line(u: &Uncertainty) -> String { + format!("- {}: {}", u.kind.label(), u.detail) +} + +/// The direct support of the conclusion with the best grounding. +fn strongest_reason(b: &ExplanationBundle) -> Option<&CausalStep> { + let c = b.conclusion(); + c.supported_by + .iter() + .filter(|l| l.relation != Relation::References) + .filter_map(|l| b.step(l.step)) + .max_by_key(|s| { + ( + s.grounding, + s.status != Status::Hypothesis, + s.confidence_permille.unwrap_or(0), + s.index, + ) + }) +} + +/// The grounding step with evidence (digest or measurement) closest to the conclusion. +fn strongest_evidence(b: &ExplanationBundle) -> Option<&CausalStep> { + b.evidence + .iter() + .filter_map(|e| b.step(e.step)) + .filter(|s| s.grounding) + .min_by_key(|s| (s.depth, s.index)) +} + +fn header(b: &ExplanationBundle, aud: Audience) -> String { + let c = b.conclusion(); + let mut s = format!("Conclusion: {} [{}]", c.statement, status_words(c.status)); + if aud.shows_ids() { + let _ = write!(s, " ({})", short(&c.node_id)); + } + s.push('\n'); + s +} + +fn render_summary(b: &ExplanationBundle, level: u8, aud: Audience) -> String { + let mut out = header(b, aud); + if level == 0 { + return out; + } + match strongest_reason(b) { + Some(r) => { + let _ = writeln!( + out, + "Main reason: {} [{}]", + r.statement, + status_words(r.status) + ); + } + None => out.push_str( + "Main reason: none recorded. The system has no evidence supporting this conclusion.\n", + ), + } + match strongest_evidence(b) { + Some(e) => { + let _ = writeln!( + out, + "Strongest evidence: {} [{}]", + e.statement, + status_words(e.status) + ); + if let Some(m) = measurements_line(e) { + let _ = writeln!(out, "{}", m.trim_start()); + } + } + None => out.push_str("Strongest evidence: no observed or checked evidence on this path.\n"), + } + match material(b) { + Some(u) => { + let _ = writeln!(out, "Main uncertainty: {}", u.detail); + } + None => out.push_str("Main uncertainty: none recorded on this path.\n"), + } + if level >= 2 { + out.push('\n'); + out.push_str(&render_steps(b, level, aud)); + } + out +} + +fn render_steps(b: &ExplanationBundle, level: u8, aud: Audience) -> String { + let mut out = String::new(); + if level == 0 { + return header(b, aud); + } + let shown: Vec<&CausalStep> = if level == 1 { + let c = b.conclusion(); + let mut v: Vec<&CausalStep> = c + .supported_by + .iter() + .filter_map(|l| b.step(l.step)) + .collect(); + v.push(c); + v + } else { + b.steps.iter().collect() + }; + let mut last: Option = None; + for s in shown { + if last != Some(s.role) { + let _ = writeln!(out, "{}:", s.role.heading()); + last = Some(s.role); + } + if s.index == b.conclusion_step { + let _ = writeln!( + out, + "{}. Therefore: {} [{}]", + s.index, + s.statement, + status_words(s.status) + ); + } else { + let _ = writeln!(out, "{}", step_line(s, level, aud)); + } + if level >= 3 { + if let Some(m) = measurements_line(s) { + let _ = writeln!(out, "{m}"); + } + } + if level >= 4 { + let _ = writeln!( + out, + " source: {} {} {}{}", + s.source.system, + s.source.artifact, + s.source.reference, + s.source + .digest + .as_ref() + .map(|d| format!(" digest {d}")) + .unwrap_or_default() + ); + } + } + out.push_str("Uncertainty:\n"); + let visible: Vec<&Uncertainty> = b + .uncertainties + .iter() + .filter(|u| level >= 3 || u.kind != UncertaintyKind::Inferred) + .collect(); + if visible.is_empty() { + out.push_str("- no gaps recorded on this path (inferred steps are marked as such)\n"); + } + for u in visible { + let _ = writeln!(out, "{}", uncertainty_line(u)); + } + if !b.contradictions.is_empty() { + out.push_str("Conflicts:\n"); + for c in &b.contradictions { + let _ = writeln!( + out, + "- {} (involves {} step(s))", + c.statement, + c.involves.len() + ); + } + } + if level >= 2 && !b.alternatives.is_empty() { + out.push_str("Other explanations the system recorded:\n"); + for a in &b.alternatives { + let _ = writeln!(out, "- {}", a.statement); + } + } + out +} + +fn render_technical(b: &ExplanationBundle, level: u8) -> String { + let mut out = String::new(); + let c = b.conclusion(); + let _ = writeln!( + out, + "explanation target={} producer={} builder={} contract={} v{}", + b.provenance.target, + b.provenance.producer, + b.provenance.builder, + b.provenance.contract_format, + b.provenance.contract_version + ); + let _ = writeln!( + out, + "conclusion step={} id={} status={} kind={}", + c.index, + c.node_id, + c.status.name(), + c.kind.name() + ); + if level == 0 { + return out; + } + for s in &b.steps { + let sup: Vec = s + .supported_by + .iter() + .map(|l| format!("{}:{}", l.relation.name(), l.step)) + .collect(); + let _ = writeln!( + out, + "step {} id={} kind={} status={} role={:?} depth={} grounding={} supported_by=[{}]", + s.index, + s.node_id, + s.kind.name(), + s.status.name(), + s.role, + s.depth, + s.grounding, + sup.join(",") + ); + let _ = writeln!(out, " statement: {}", s.statement); + if let Some(p) = s.confidence_permille { + let _ = writeln!( + out, + " confidence_permille={} basis={}", + p, + s.confidence_basis.as_deref().unwrap_or("unspecified") + ); + } + if level >= 3 { + if let Some(m) = measurements_line(s) { + let _ = writeln!(out, " {}", m.trim_start()); + } + } + if level >= 4 { + let _ = writeln!( + out, + " source system={} artifact={} reference={} digest={}", + s.source.system, + s.source.artifact, + s.source.reference, + s.source.digest.as_deref().unwrap_or("-") + ); + if let Some(t) = s.recorded_at_utc { + let _ = writeln!( + out, + " recorded_at_utc={t} (informational, not used for order)" + ); + } + } + for n in &s.notes { + let _ = writeln!(out, " note: {n}"); + } + } + for u in &b.uncertainties { + let _ = writeln!( + out, + "uncertainty code={} kind={:?} node={} related={} detail={}", + u.kind.code(), + u.kind, + u.node_id, + u.related.as_deref().unwrap_or("-"), + u.detail + ); + } + for c in &b.contradictions { + let _ = writeln!( + out, + "contradiction id={} involves=[{}] statement={}", + c.node_id, + c.involves.join(","), + c.statement + ); + } + for a in &b.alternatives { + let _ = writeln!( + out, + "alternative id={} to={} statement={}", + a.node_id, a.alternative_to, a.statement + ); + } + if level >= 4 { + let _ = writeln!( + out, + "input_digest={} bundle_digest={} visited={}/{} limits=depth:{},nodes:{}", + b.provenance.input_digest, + b.bundle_digest, + b.provenance.visited_nodes, + b.provenance.graph_nodes, + b.provenance.limits.max_depth, + b.provenance.limits.max_nodes + ); + } + out +} + +/// Fixed, presentation-only analogy catalog keyed by artifact kind and status. +/// These sentences are illustrations. They are not stored anywhere, not part of the +/// bundle, and not evidence for anything. +pub fn analogy_for(kind: NodeKind, status: Status) -> Option<&'static str> { + Some(match (kind, status) { + (NodeKind::CapabilityAnalysis, _) => { + "The flagged part acts like a toll booth on a busy road: every request has to pass through it, so when it slows down, everything behind it queues up." + } + (NodeKind::Hypothesis, _) | (NodeKind::CortexRecord, Status::Hypothesis) => { + "A hypothesis is like a mechanic's first guess about a noise in the engine: useful for deciding what to check, but not a finding until the check is done." + } + (NodeKind::Falsification, _) => { + "A falsification test is like agreeing in advance which gauge reading would prove the repair did not work." + } + (NodeKind::EvaluationReceipt, _) => { + "The evaluation receipt is like an inspection sheet signed after a test drive: it records what was measured, not what was hoped." + } + (NodeKind::AgentBranch, _) => { + "A branch is like one line of investigation in a case file: it lists the documents it actually relied on, not every document in the archive." + } + (_, Status::Contradiction) => { + "A contradiction is like two witnesses whose accounts do not match: the system keeps both and flags the conflict instead of picking one quietly." + } + _ => return None, + }) +} + +fn render_analogy(b: &ExplanationBundle, level: u8, aud: Audience) -> String { + let mut out = String::new(); + let pick = b + .steps + .iter() + .rev() + .find_map(|s| analogy_for(s.kind, s.status).map(|a| (s.index, a))); + match pick { + Some((i, a)) => { + let _ = writeln!( + out, + "Analogy (illustration only, not evidence; about step {i}):" + ); + let _ = writeln!(out, " {a}"); + } + None => out.push_str("Analogy: none available for this explanation.\n"), + } + out.push_str("\nThe evidence itself:\n"); + out.push_str(&render_steps(b, level.max(1), aud)); + out +} + +/// Render the bundle. Pure function of (bundle, request). +pub fn render(b: &ExplanationBundle, req: &ExplanationRequest) -> String { + let level = req.effective_level(); + match req.mode { + Mode::Summary => render_summary(b, level, req.audience), + Mode::StepByStep => { + let mut s = header(b, req.audience); + if level > 0 { + s.push('\n'); + s.push_str(&render_steps(b, level, req.audience)); + } + s + } + Mode::Technical => render_technical(b, level), + Mode::Analogy => render_analogy(b, level, req.audience), + } +} diff --git a/crates/aienos-explain/src/session.rs b/crates/aienos-explain/src/session.rs new file mode 100644 index 00000000..a0ea6e38 --- /dev/null +++ b/crates/aienos-explain/src/session.rs @@ -0,0 +1,198 @@ +//! Clarification and rewind over one bundle, without recomputing anything. +//! +//! "Explain that", "explain step 4", "go one level deeper", "where did that come +//! from?", "show the evidence", "explain it technically / simply", "give me an +//! analogy", "what are you uncertain about?", "what else was considered?" all read +//! the same immutable bundle. + +use crate::bundle::ExplanationBundle; +use crate::contract::{ExplainError, Relation}; +use crate::render::{render, status_words, Audience, ExplanationRequest, Mode, MAX_LEVEL}; +use std::fmt::Write; + +/// A conversation about one explanation. +pub struct ExplanationSession { + bundle: ExplanationBundle, + level: u8, + audience: Audience, +} + +impl ExplanationSession { + pub fn new(bundle: ExplanationBundle, audience: Audience) -> Self { + Self { + bundle, + level: 0, + audience, + } + } + + pub fn bundle(&self) -> &ExplanationBundle { + &self.bundle + } + + pub fn level(&self) -> u8 { + self.level + } + + fn req(&self, mode: Mode, level: u8) -> ExplanationRequest { + ExplanationRequest { + mode, + level: Some(level), + audience: self.audience, + } + } + + /// "Explain that": the conclusion only (level 0). + pub fn explain(&mut self) -> String { + self.level = 0; + render(&self.bundle, &self.req(Mode::StepByStep, 0)) + } + + /// "Go one level deeper." + pub fn deeper(&mut self) -> String { + self.level = (self.level + 1).min(MAX_LEVEL); + render(&self.bundle, &self.req(Mode::StepByStep, self.level)) + } + + /// "Back up one level." + pub fn shallower(&mut self) -> String { + self.level = self.level.saturating_sub(1); + render(&self.bundle, &self.req(Mode::StepByStep, self.level)) + } + + /// "Explain step n": the step, what it rests on, and what rests on it. + pub fn step(&self, n: u32) -> Result { + let s = self.bundle.step(n).ok_or(ExplainError::StepOutOfRange(n))?; + let mut out = format!( + "Step {}: {} [{}]\n", + s.index, + s.statement, + status_words(s.status) + ); + if s.supported_by.is_empty() { + if s.grounding { + out.push_str("It is a starting point: recorded directly, not derived.\n"); + } else { + out.push_str("Nothing earlier on the path supports it.\n"); + } + } else { + for l in &s.supported_by { + let p = self.bundle.step(l.step).expect("support index valid"); + let verb = if l.relation == Relation::References { + "It refers to (weak link, not a recorded one)" + } else { + "It rests on" + }; + let _ = writeln!( + out, + "{verb} step {} ({}): {}", + p.index, + l.relation.name(), + p.statement + ); + } + } + for later in &self.bundle.steps { + if later.supported_by.iter().any(|l| l.step == s.index) { + let _ = writeln!(out, "Step {} rests on it.", later.index); + } + } + for u in self + .bundle + .uncertainties + .iter() + .filter(|u| u.node_id == s.node_id) + { + let _ = writeln!(out, "Caveat: {}", u.detail); + } + Ok(out) + } + + /// "Where did that claim come from?" + pub fn source(&self, n: u32) -> Result { + let s = self.bundle.step(n).ok_or(ExplainError::StepOutOfRange(n))?; + Ok(format!( + "Step {} comes from {} ({}), reference {}{}; node {}; status {}.\n", + s.index, + s.source.system, + s.source.artifact, + s.source.reference, + s.source + .digest + .as_ref() + .map(|d| format!(", digest {d}")) + .unwrap_or_default(), + s.node_id, + s.status.name() + )) + } + + /// "Show the evidence." + pub fn evidence(&self) -> String { + let mut out = String::new(); + if self.bundle.evidence.is_empty() { + out.push_str("No digests, receipts or measurements are attached to this path.\n"); + } + for e in &self.bundle.evidence { + let _ = write!( + out, + "Step {}: {} {} {}", + e.step, e.source.system, e.source.artifact, e.source.reference + ); + if let Some(d) = &e.source.digest { + let _ = write!(out, " digest {d}"); + } + out.push('\n'); + for m in &e.measurements { + let _ = writeln!(out, " {} = {} {}", m.name, m.value, m.unit); + } + } + out + } + + pub fn technical(&self) -> String { + render(&self.bundle, &self.req(Mode::Technical, MAX_LEVEL)) + } + + pub fn simple(&self) -> String { + render( + &self.bundle, + &ExplanationRequest { + mode: Mode::Summary, + level: Some(1), + audience: Audience::General, + }, + ) + } + + pub fn analogy(&self) -> String { + render(&self.bundle, &self.req(Mode::Analogy, 2)) + } + + /// "What are you uncertain about?" + pub fn uncertainties(&self) -> String { + if self.bundle.uncertainties.is_empty() && self.bundle.contradictions.is_empty() { + return "No uncertainty is recorded on this path.\n".into(); + } + let mut out = String::new(); + for u in &self.bundle.uncertainties { + let _ = writeln!(out, "- {}: {}", u.kind.label(), u.detail); + } + for c in &self.bundle.contradictions { + let _ = writeln!(out, "- conflict: {}", c.statement); + } + out + } + + /// "What other explanations were considered?" Only explicitly recorded ones. + pub fn alternatives(&self) -> String { + if self.bundle.alternatives.is_empty() { + return "No alternative explanations are recorded in the evidence.\n".into(); + } + let mut out = String::new(); + for a in &self.bundle.alternatives { + let _ = writeln!(out, "- {}", a.statement); + } + out + } +} diff --git a/crates/aienos-explain/tests/explain.rs b/crates/aienos-explain/tests/explain.rs new file mode 100644 index 00000000..b89150ae --- /dev/null +++ b/crates/aienos-explain/tests/explain.rs @@ -0,0 +1,569 @@ +//! Behavioural tests for the explanation bridge (brief section 20). + +use aienos_agent_state::{AgentStateAbi, AgentStateManager, LogicalAgentId}; +use aienos_cortex::{CortexStore, EpistemicRecord, EpistemicStatus}; +use aienos_explain::adapters::{ + branch_graph, branch_graph_for_record, cortex_graph_for_record, cortex_graph_from, + cortex_node_id, store_from_journal, +}; +use aienos_explain::bundle::{Role, UncertaintyKind}; +use aienos_explain::contract::{ + EdgeDoc, EvidenceGraph, NodeDoc, NodeKind, Relation, SourceRef, Status, +}; +use aienos_explain::render::status_words; +use aienos_explain::{ + build_bundle, render, Audience, ExplanationBundle, ExplanationRequest, ExplanationSession, + Limits, Mode, +}; +use std::collections::HashMap; + +fn n(id: &str, kind: NodeKind, status: Status, parents: &[(&str, Relation)]) -> NodeDoc { + NodeDoc { + id: id.into(), + kind: kind.code(), + status: status.code(), + statement: format!("statement of {id}"), + source: SourceRef { + system: "test".into(), + artifact: "Node".into(), + reference: id.into(), + digest: None, + }, + confidence_permille: None, + confidence_basis: None, + recorded_at_utc: None, + parents: parents + .iter() + .map(|(t, r)| EdgeDoc { + to: (*t).into(), + relation: r.code(), + }) + .collect(), + measurements: vec![], + missing: vec![], + notes: vec![], + } +} + +fn graph(nodes: Vec) -> EvidenceGraph { + let mut g = EvidenceGraph::new("test"); + g.nodes = nodes; + g +} + +fn ids(b: &ExplanationBundle) -> Vec<&str> { + b.steps.iter().map(|s| s.node_id.as_str()).collect() +} + +fn has(b: &ExplanationBundle, k: UncertaintyKind) -> bool { + b.uncertainties.iter().any(|u| u.kind == k) +} + +const SUP: Relation = Relation::SupportedBy; +const REC: NodeKind = NodeKind::CortexRecord; + +#[test] +fn linear_chain_is_ordered_parents_first() { + let mut c = CortexStore::new(); + let obs = c.record_observation("allocator queue depth 900", "telemetry:kv", b"900", 10); + let i1 = c + .record_inference( + "allocator is saturated", + "rule:queue>512", + vec![obs.id], + 0.9, + 20, + ) + .unwrap(); + let i2 = c + .record_inference( + "p95 latency is allocator bound", + "rule:join", + vec![i1.id], + 0.8, + 30, + ) + .unwrap(); + let g = cortex_graph_for_record(&c, &i2.id, Limits::default()).unwrap(); + let b = build_bundle(&g, &cortex_node_id(&i2.id), Limits::default()).unwrap(); + assert_eq!( + ids(&b), + vec![ + cortex_node_id(&obs.id), + cortex_node_id(&i1.id), + cortex_node_id(&i2.id) + ] + ); + assert_eq!(b.conclusion().node_id, cortex_node_id(&i2.id)); + assert_eq!(b.steps[1].supported_by[0].step, 1); + assert_eq!(b.steps[2].supported_by[0].step, 2); + assert!(b.steps[0].grounding); + assert_eq!(b.steps[0].role, Role::Observed); + assert!(!has(&b, UncertaintyKind::MissingParent)); +} + +#[test] +fn branching_support_is_deterministic_regardless_of_input_order() { + let nodes = vec![ + n( + "c", + REC, + Status::Inference, + &[("z", SUP), ("a", SUP), ("m", SUP)], + ), + n("z", REC, Status::DirectObservation, &[]), + n("a", REC, Status::VerifiedFact, &[]), + n("m", REC, Status::OperatorDecision, &[]), + ]; + let b1 = build_bundle(&graph(nodes.clone()), "c", Limits::default()).unwrap(); + let mut rev = nodes; + rev.reverse(); + let b2 = build_bundle(&graph(rev), "c", Limits::default()).unwrap(); + assert_eq!(b1.steps, b2.steps); + // Observed (a, z) before Decision (m), ids break ties, conclusion last. + assert_eq!(ids(&b1), vec!["a", "z", "m", "c"]); +} + +#[test] +fn shared_parent_appears_once() { + let nodes = vec![ + n("concl", REC, Status::Inference, &[("i1", SUP), ("i2", SUP)]), + n("i1", REC, Status::Inference, &[("obs", SUP)]), + n("i2", REC, Status::Inference, &[("obs", SUP)]), + n("obs", REC, Status::DirectObservation, &[]), + ]; + let mut g = graph(nodes); + g.nodes[3].source.digest = Some("ab".repeat(32)); + let b = build_bundle(&g, "concl", Limits::default()).unwrap(); + assert_eq!(b.steps.len(), 4); + assert_eq!(ids(&b).iter().filter(|i| **i == "obs").count(), 1); + assert_eq!(b.evidence.len(), 1); + assert_eq!(b.steps[0].node_id, "obs"); +} + +#[test] +fn cycle_terminates_and_is_reported() { + let nodes = vec![ + n("A", REC, Status::Inference, &[("B", SUP)]), + n("B", REC, Status::Inference, &[("C", SUP)]), + n("C", REC, Status::Inference, &[("A", SUP)]), + ]; + let b = build_bundle(&graph(nodes), "A", Limits::default()).unwrap(); + assert_eq!(b.steps.len(), 3); + assert_eq!(b.conclusion().node_id, "A"); + let cyc: Vec<_> = b + .uncertainties + .iter() + .filter(|u| u.kind == UncertaintyKind::Cycle) + .collect(); + assert_eq!(cyc.len(), 1); + assert_eq!(cyc[0].node_id, "C"); + assert_eq!(cyc[0].related.as_deref(), Some("A")); + let text = render(&b, &ExplanationRequest::new(Mode::StepByStep)); + assert!(text.contains("circular")); +} + +#[test] +fn cycle_through_imported_cortex_journal_terminates() { + // Cortex refuses cycles on write, but an imported journal is not re-verified. + let mk = |tag: u8, parents: Vec<[u8; 16]>| { + let mut r = EpistemicRecord::new( + EpistemicStatus::Inference, + format!("claim {tag}"), + "test", + &[tag], + tag as u64, + 0.5, + None, + parents, + ); + r.id = [tag; 16]; + r + }; + let a = mk(1, vec![[2; 16]]); + let bb = mk(2, vec![[3; 16]]); + let c = mk(3, vec![[1; 16]]); + let map: HashMap<[u8; 16], EpistemicRecord> = + [a.clone(), bb, c].into_iter().map(|r| (r.id, r)).collect(); + let g = cortex_graph_from(&[a.id], |id| map.get(id), &[], Limits::default()); + let b = build_bundle(&g, &cortex_node_id(&a.id), Limits::default()).unwrap(); + assert_eq!(b.steps.len(), 3); + assert!(has(&b, UncertaintyKind::Cycle)); +} + +#[test] +fn missing_parent_stays_missing() { + let nodes = vec![ + n( + "concl", + REC, + Status::Inference, + &[("obs", SUP), ("ghost", SUP)], + ), + n("obs", REC, Status::DirectObservation, &[]), + ]; + let b = build_bundle(&graph(nodes), "concl", Limits::default()).unwrap(); + assert_eq!( + ids(&b), + vec!["obs", "concl"], + "no step is invented for the gap" + ); + let u = b + .uncertainties + .iter() + .find(|u| u.kind == UncertaintyKind::MissingParent) + .expect("gap reported"); + assert_eq!(u.related.as_deref(), Some("ghost")); + let text = render(&b, &ExplanationRequest::new(Mode::Summary)); + assert!(text.contains("no evidence for that link"), "{text}"); +} + +#[test] +fn unsupported_claim_is_flagged() { + let nodes = vec![n("lonely", REC, Status::Inference, &[])]; + let b = build_bundle(&graph(nodes), "lonely", Limits::default()).unwrap(); + assert!(has(&b, UncertaintyKind::Unsupported)); +} + +#[test] +fn contradiction_remains_visible() { + let mut c = CortexStore::new(); + let o1 = c.record_observation("sensor A says 70C", "sensor:a", b"70", 1); + let o2 = c.record_observation("sensor B says 40C", "sensor:b", b"40", 2); + let _x = c + .flag_contradiction(o1.id, o2.id, "A and B disagree", 3) + .unwrap(); + let inf = c + .record_inference("die is hot", "rule:max", vec![o1.id], 0.7, 4) + .unwrap(); + let g = cortex_graph_for_record(&c, &inf.id, Limits::default()).unwrap(); + let b = build_bundle(&g, &cortex_node_id(&inf.id), Limits::default()).unwrap(); + assert_eq!(b.contradictions.len(), 1); + assert_eq!(b.contradictions[0].involves, vec![cortex_node_id(&o1.id)]); + assert!(has(&b, UncertaintyKind::ConflictingEvidence)); + // The contradiction is disclosure, never a support step. + assert_eq!(b.steps.len(), 2); + let text = render(&b, &ExplanationRequest::new(Mode::StepByStep)); + assert!(text.contains("Conflicts:")); + assert!(text.contains("A and B disagree")); + let s = render(&b, &ExplanationRequest::new(Mode::Summary)); + assert!(s.contains("Main uncertainty"), "{s}"); + assert!(s.contains("contradiction"), "{s}"); +} + +#[test] +fn hypothesis_is_never_rendered_as_fact() { + let mut c = CortexStore::new(); + let o = c.record_observation("cache misses up 40%", "perf:llc", b"40", 1); + let h = c + .record_hypothesis("prefetcher is mis-trained", "agent:rsi", vec![o.id], 2) + .unwrap(); + let i = c + .record_inference("retune prefetcher", "planner", vec![h.id], 0.6, 3) + .unwrap(); + let g = cortex_graph_for_record(&c, &i.id, Limits::default()).unwrap(); + let b = build_bundle(&g, &cortex_node_id(&i.id), Limits::default()).unwrap(); + let hs = b + .steps + .iter() + .find(|s| s.node_id == cortex_node_id(&h.id)) + .unwrap(); + assert_eq!(hs.status, Status::Hypothesis); + assert!(!hs.grounding); + assert!(has(&b, UncertaintyKind::HypothesisNotFalsified)); + for mode in [ + Mode::Summary, + Mode::StepByStep, + Mode::Technical, + Mode::Analogy, + ] { + for aud in [Audience::General, Audience::Developer] { + let t = render( + &b, + &ExplanationRequest { + mode, + level: Some(4), + audience: aud, + }, + ); + for line in t + .lines() + .filter(|l| l.contains("prefetcher is mis-trained")) + { + assert!(!line.contains("checked fact"), "{line}"); + assert!(!line.contains("VerifiedFact"), "{line}"); + assert!(!line.contains("observed]"), "{line}"); + } + } + } + assert!(status_words(Status::Hypothesis).contains("not yet established")); +} + +fn branch_fixture() -> ( + CortexStore, + AgentStateManager, + aienos_agent_state::LogicalBranchId, + [u8; 16], + [u8; 16], + [u8; 16], +) { + let mut c = CortexStore::new(); + let used = c.record_observation("link 3 dropped 2% packets", "nic:3", b"2", 1); + let derived = c + .record_inference("link 3 is flaky", "rule:loss>1", vec![used.id], 0.7, 2) + .unwrap(); + let unrelated = c + .record_verified_fact( + "firmware 1.2 is signed", + "boot", + "sha256", + b"sig", + vec![], + 3, + ) + .unwrap(); + let m = AgentStateManager::new(1); + let agent = LogicalAgentId::from_seed("explain-branch"); + let root = m.register_agent(agent, 1); + let child = m.fork_branch(root).unwrap(); + m.add_epistemic_ref(child, derived.id).unwrap(); + (c, m, child, used.id, derived.id, unrelated.id) +} + +#[test] +fn branch_explanation_uses_only_what_the_branch_depended_on() { + let (c, m, child, used, derived, unrelated) = branch_fixture(); + let br = m.get_branch(&child).unwrap(); + let g = branch_graph(&c, &br, Limits::default()); + let b = build_bundle(&g, &g.nodes[0].id, Limits::default()).unwrap(); + let got = ids(&b); + assert!(got.contains(&cortex_node_id(&used).as_str())); + assert!(got.contains(&cortex_node_id(&derived).as_str())); + assert!( + !got.contains(&cortex_node_id(&unrelated).as_str()), + "no opportunistic facts" + ); + assert_eq!(b.conclusion().kind, NodeKind::AgentBranch); + let d = b + .steps + .iter() + .find(|s| s.node_id == cortex_node_id(&derived)) + .unwrap(); + assert!(d.branch_referenced); + let u = b + .steps + .iter() + .find(|s| s.node_id == cortex_node_id(&used)) + .unwrap(); + assert!(!u.branch_referenced, "ancestry, not a direct reference"); + let err = branch_graph_for_record(&c, &br, &unrelated, Limits::default()).unwrap_err(); + assert_eq!(err.code(), 8); + assert!(branch_graph_for_record(&c, &br, &used, Limits::default()).is_ok()); +} + +#[test] +fn token_history_never_enters_the_explanation() { + let (c, m, child, ..) = branch_fixture(); + let before = branch_graph(&c, &m.get_branch(&child).unwrap(), Limits::default()); + m.append_tokens(child, &[11, 22, 33, 44]).unwrap(); + let after = branch_graph(&c, &m.get_branch(&child).unwrap(), Limits::default()); + assert_eq!( + before, after, + "explanations are built from records, not token streams" + ); +} + +#[test] +fn analogy_is_isolated_from_evidence() { + let mut c = CortexStore::new(); + let o = c.record_observation("x", "s", b"x", 1); + let h = c.record_hypothesis("y", "agent", vec![o.id], 2).unwrap(); + let journal_before = c.export_journal().unwrap(); + let g = cortex_graph_for_record(&c, &h.id, Limits::default()).unwrap(); + let b = build_bundle(&g, &cortex_node_id(&h.id), Limits::default()).unwrap(); + let digest = b.bundle_digest.clone(); + let json_before = b.to_json(); + let a = render(&b, &ExplanationRequest::new(Mode::Analogy)); + assert!(a.contains("illustration only, not evidence")); + assert!(a.contains("The evidence itself:")); + // Deleting the analogy leaves a complete explanation. + let plain = render(&b, &ExplanationRequest::new(Mode::StepByStep)); + for s in &b.steps { + assert!(plain.contains(&s.statement)); + assert!(a.contains(&s.statement)); + } + // No mutation of the bundle or of Cortex; analogy text is not in the bundle. + assert_eq!(b.bundle_digest, digest); + assert_eq!(b.compute_digest(), digest); + assert_eq!(b.to_json(), json_before); + assert!(!json_before.contains("mechanic")); + assert_eq!(c.export_journal().unwrap(), journal_before); + assert_eq!(c.len(), 2); +} + +#[test] +fn identical_input_gives_identical_bundle_and_text() { + let mut c = CortexStore::new(); + let o = c.record_observation("o", "s", b"o", 1); + let i = c.record_inference("i", "m", vec![o.id], 0.5, 2).unwrap(); + let journal = c.export_journal().unwrap(); + let c2 = store_from_journal(&journal).unwrap(); + let mk = |s: &CortexStore| { + let g = cortex_graph_for_record(s, &i.id, Limits::default()).unwrap(); + build_bundle(&g, &cortex_node_id(&i.id), Limits::default()).unwrap() + }; + let (b1, b2) = (mk(&c), mk(&c2)); + assert_eq!(b1.to_json(), b2.to_json()); + assert_eq!(b1.bundle_digest, b2.bundle_digest); + for mode in [ + Mode::Summary, + Mode::StepByStep, + Mode::Technical, + Mode::Analogy, + ] { + let r = ExplanationRequest::new(mode); + assert_eq!(render(&b1, &r), render(&b2, &r)); + } +} + +#[test] +fn depth_and_node_limits_bound_the_walk() { + let mut nodes = vec![n("n0", REC, Status::DirectObservation, &[])]; + for k in 1..50 { + let p = format!("n{}", k - 1); + nodes.push(n( + &format!("n{k}"), + REC, + Status::Inference, + &[(p.as_str(), SUP)], + )); + } + let g = graph(nodes); + let lim = Limits { + max_depth: 3, + max_nodes: 256, + }; + let b = build_bundle(&g, "n49", lim).unwrap(); + assert_eq!(b.steps.len(), 4); + assert!(has(&b, UncertaintyKind::Truncated)); + // Wide fan-in: node limit holds. + let mut wide = vec![]; + let parents: Vec = (0..3000).map(|k| format!("p{k}")).collect(); + let refs: Vec<(&str, Relation)> = parents.iter().map(|p| (p.as_str(), SUP)).collect(); + // Parents are capped per node by the contract; split over 3 intermediate nodes. + wide.push(n( + "top", + REC, + Status::Inference, + &[("m0", SUP), ("m1", SUP), ("m2", SUP)], + )); + for (j, chunk) in refs.chunks(1000).enumerate() { + wide.push(n(&format!("m{j}"), REC, Status::Inference, chunk)); + } + for p in &parents { + wide.push(n(p, REC, Status::DirectObservation, &[])); + } + let lim = Limits { + max_depth: 32, + max_nodes: 100, + }; + let b = build_bundle(&graph(wide), "top", lim).unwrap(); + assert!(b.steps.len() <= 100); + assert!(has(&b, UncertaintyKind::Truncated)); + // Limits are validated. + assert_eq!( + build_bundle( + &g, + "n1", + Limits { + max_depth: 0, + max_nodes: 1 + } + ) + .unwrap_err() + .code(), + 10 + ); + assert_eq!( + build_bundle( + &g, + "n1", + Limits { + max_depth: 1, + max_nodes: 1_000_000 + } + ) + .unwrap_err() + .code(), + 10 + ); +} + +#[test] +fn malformed_input_fails_safely() { + assert_eq!( + EvidenceGraph::from_json(b"{not json").unwrap_err().code(), + 1 + ); + let mut g = graph(vec![n("a", REC, Status::Inference, &[])]); + g.version = 2; + assert_eq!(g.validate().unwrap_err().code(), 2); + let mut g = graph(vec![n("a", REC, Status::Inference, &[])]); + g.nodes[0].status = 9; + assert_eq!( + build_bundle(&g, "a", Limits::default()).unwrap_err().code(), + 3 + ); + let g = graph(vec![ + n("a", REC, Status::Inference, &[]), + n("a", REC, Status::Inference, &[]), + ]); + assert_eq!( + build_bundle(&g, "a", Limits::default()).unwrap_err().code(), + 4 + ); + let g = graph(vec![n("a", REC, Status::Inference, &[])]); + assert_eq!( + build_bundle(&g, "zz", Limits::default()) + .unwrap_err() + .code(), + 5 + ); + let mut j = CortexStore::new(); + j.record_observation("o", "s", b"o", 1); + let mut bytes = j.export_journal().unwrap(); + let k = bytes.len() / 2; + bytes[k] ^= 1; + assert!(store_from_journal(&bytes).is_err()); +} + +#[test] +fn clarification_reads_the_same_bundle() { + let nodes = vec![ + n("concl", REC, Status::Inference, &[("i1", SUP)]), + n("i1", REC, Status::Inference, &[("obs", SUP)]), + n("obs", REC, Status::DirectObservation, &[]), + ]; + let b = build_bundle(&graph(nodes), "concl", Limits::default()).unwrap(); + let digest = b.bundle_digest.clone(); + let mut s = ExplanationSession::new(b, Audience::Operator); + let l0 = s.explain(); + assert!(l0.contains("statement of concl")); + assert!(!l0.contains("statement of obs")); + let l1 = s.deeper(); + assert!(l1.contains("statement of i1")); + assert!(!l1.contains("statement of obs")); + let l2 = s.deeper(); + assert!(l2.contains("statement of obs")); + assert_eq!(s.level(), 2); + assert!(s.step(2).unwrap().contains("rests on step 1")); + assert!(s.step(1).unwrap().contains("starting point")); + assert!(s.source(1).unwrap().contains("test (Node)")); + assert_eq!(s.step(9).unwrap_err().code(), 7); + assert!(s.technical().contains("step 1 id=obs")); + assert!(s.simple().contains("Conclusion:")); + assert!(s.analogy().contains("The evidence itself:")); + assert!(s.uncertainties().contains("inferred")); + assert!(s.alternatives().contains("No alternative")); + assert_eq!(s.bundle().bundle_digest, digest); +} diff --git a/crates/aienos-explain/tests/fixtures/rsi_kv_cycle.evidence.json b/crates/aienos-explain/tests/fixtures/rsi_kv_cycle.evidence.json new file mode 100644 index 00000000..842cd550 --- /dev/null +++ b/crates/aienos-explain/tests/fixtures/rsi_kv_cycle.evidence.json @@ -0,0 +1,590 @@ +{ + "format": "aien.explain.evidence-graph", + "version": 1, + "producer": "spark-rsi/explain", + "nodes": [ + { + "id": "rsi:capability:kv_allocator", + "kind": 2, + "status": 0, + "statement": "'Unified LPDDR5x KV Allocator' (memory) has p95 latency 4200.0 us, error rate 8.00%, resident memory 32768 KiB", + "source": { + "system": "spark-rsi", + "artifact": "CapabilityNode", + "reference": "kv_allocator" + }, + "parents": [], + "measurements": [ + { + "name": "latency_p95_us", + "value": "4200.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.080000", + "unit": "fraction" + }, + { + "name": "memory_rss_kb", + "value": "32768", + "unit": "KiB" + } + ], + "missing": [], + "notes": [ + "metric values for 'Unified LPDDR5x KV Allocator' were declared in the capability graph, not measured" + ] + }, + { + "id": "rsi:capability:mojo_kernel", + "kind": 2, + "status": 0, + "statement": "'Mojo Blackwell GEMM Kernel' (compute) has p95 latency 1800.0 us, error rate 1.00%, resident memory 16384 KiB", + "source": { + "system": "spark-rsi", + "artifact": "CapabilityNode", + "reference": "mojo_kernel" + }, + "parents": [], + "measurements": [ + { + "name": "latency_p95_us", + "value": "1800.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.010000", + "unit": "fraction" + }, + { + "name": "memory_rss_kb", + "value": "16384", + "unit": "KiB" + } + ], + "missing": [], + "notes": [ + "metric values for 'Mojo Blackwell GEMM Kernel' were declared in the capability graph, not measured" + ] + }, + { + "id": "rsi:capability:req_gateway", + "kind": 2, + "status": 0, + "statement": "'Request Gateway' (network) has p95 latency 120.0 us, error rate 0.00%, resident memory 1024 KiB", + "source": { + "system": "spark-rsi", + "artifact": "CapabilityNode", + "reference": "req_gateway" + }, + "parents": [], + "measurements": [ + { + "name": "latency_p95_us", + "value": "120.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.000000", + "unit": "fraction" + }, + { + "name": "memory_rss_kb", + "value": "1024", + "unit": "KiB" + } + ], + "missing": [], + "notes": [ + "metric values for 'Request Gateway' were declared in the capability graph, not measured" + ] + }, + { + "id": "rsi:capability:sampler", + "kind": 2, + "status": 0, + "statement": "'Greedy Token Sampler' (inference) has p95 latency 150.0 us, error rate 0.00%, resident memory 1024 KiB", + "source": { + "system": "spark-rsi", + "artifact": "CapabilityNode", + "reference": "sampler" + }, + "parents": [], + "measurements": [ + { + "name": "latency_p95_us", + "value": "150.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.000000", + "unit": "fraction" + }, + { + "name": "memory_rss_kb", + "value": "1024", + "unit": "KiB" + } + ], + "missing": [], + "notes": [ + "metric values for 'Greedy Token Sampler' were declared in the capability graph, not measured" + ] + }, + { + "id": "rsi:capability:scheduler", + "kind": 2, + "status": 0, + "statement": "'Batch Scheduler' (scheduling) has p95 latency 340.0 us, error rate 0.00%, resident memory 2048 KiB", + "source": { + "system": "spark-rsi", + "artifact": "CapabilityNode", + "reference": "scheduler" + }, + "parents": [], + "measurements": [ + { + "name": "latency_p95_us", + "value": "340.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.000000", + "unit": "fraction" + }, + { + "name": "memory_rss_kb", + "value": "2048", + "unit": "KiB" + } + ], + "missing": [], + "notes": [ + "metric values for 'Batch Scheduler' were declared in the capability graph, not measured" + ] + }, + { + "id": "rsi:bottleneck:cycle-kv-0001", + "kind": 3, + "status": 3, + "statement": "The capability graph ranks 'Unified LPDDR5x KV Allocator' (memory) as bottleneck #1 of 5 (Centrality=0.333, LatencyRatio=3.18x, ErrorRate=8.0%)", + "source": { + "system": "spark-rsi", + "artifact": "BottleneckRank", + "reference": "kv_allocator" + }, + "parents": [ + { + "to": "rsi:capability:kv_allocator", + "relation": 1 + }, + { + "to": "rsi:capability:mojo_kernel", + "relation": 1 + }, + { + "to": "rsi:capability:req_gateway", + "relation": 1 + }, + { + "to": "rsi:capability:sampler", + "relation": 1 + }, + { + "to": "rsi:capability:scheduler", + "relation": 1 + } + ], + "measurements": [ + { + "name": "bottleneck_score", + "value": "1.4841", + "unit": "" + }, + { + "name": "centrality", + "value": "0.3333", + "unit": "" + }, + { + "name": "latency_p95_us", + "value": "4200.000", + "unit": "us" + }, + { + "name": "error_rate", + "value": "0.080000", + "unit": "fraction" + } + ], + "missing": [], + "notes": [ + "ranking computed by CapabilityGraph::rank_bottlenecks" + ] + }, + { + "id": "rsi:alternative:cycle-kv-0001:mojo_kernel", + "kind": 13, + "status": 3, + "statement": "Alternative bottleneck candidate #2: 'Mojo Blackwell GEMM Kernel' (compute), score 0.6546", + "source": { + "system": "spark-rsi", + "artifact": "BottleneckRank", + "reference": "mojo_kernel" + }, + "parents": [ + { + "to": "rsi:bottleneck:cycle-kv-0001", + "relation": 5 + } + ], + "measurements": [ + { + "name": "bottleneck_score", + "value": "0.6546", + "unit": "" + } + ], + "missing": [], + "notes": [] + }, + { + "id": "rsi:alternative:cycle-kv-0001:scheduler", + "kind": 13, + "status": 3, + "statement": "Alternative bottleneck candidate #3: 'Batch Scheduler' (scheduling), score 0.2029", + "source": { + "system": "spark-rsi", + "artifact": "BottleneckRank", + "reference": "scheduler" + }, + "parents": [ + { + "to": "rsi:bottleneck:cycle-kv-0001", + "relation": 5 + } + ], + "measurements": [ + { + "name": "bottleneck_score", + "value": "0.2029", + "unit": "" + } + ], + "missing": [], + "notes": [] + }, + { + "id": "rsi:alternative:cycle-kv-0001:sampler", + "kind": 13, + "status": 3, + "statement": "Alternative bottleneck candidate #4: 'Greedy Token Sampler' (inference), score 0.0454", + "source": { + "system": "spark-rsi", + "artifact": "BottleneckRank", + "reference": "sampler" + }, + "parents": [ + { + "to": "rsi:bottleneck:cycle-kv-0001", + "relation": 5 + } + ], + "measurements": [ + { + "name": "bottleneck_score", + "value": "0.0454", + "unit": "" + } + ], + "missing": [], + "notes": [] + }, + { + "id": "rsi:hypothesis:hypo-kv-0001", + "kind": 5, + "status": 4, + "statement": "Suspected root cause: High latency on 'Unified LPDDR5x KV Allocator': Centrality=0.333, LatencyRatio=3.18x, ErrorRate=8.0%. Observed problem: System throughput limited by bottleneck node 'Unified LPDDR5x KV Allocator' (centrality=0.3333)", + "source": { + "system": "spark-rsi", + "artifact": "HypothesisContract", + "reference": "hypo-kv-0001" + }, + "confidence_permille": 850, + "confidence_basis": "declared in the HypothesisContract, not measured", + "parents": [ + { + "to": "rsi:bottleneck:cycle-kv-0001", + "relation": 6 + } + ], + "measurements": [], + "missing": [ + { + "expected": "a recorded reference from the hypothesis to the bottleneck ranking", + "reason": "linked only because the hypothesis text names 'Unified LPDDR5x KV Allocator' and its baseline equals that bottleneck's p95 latency" + } + ], + "notes": [] + }, + { + "id": "rsi:hypothesis:hypo-kv-0001:prediction", + "kind": 6, + "status": 4, + "statement": "Predicts latency_us improves by 15.0% from baseline 4200.000", + "source": { + "system": "spark-rsi", + "artifact": "HypothesisContract", + "reference": "hypo-kv-0001" + }, + "parents": [ + { + "to": "rsi:hypothesis:hypo-kv-0001", + "relation": 3 + } + ], + "measurements": [ + { + "name": "target_metric", + "value": "latency_us", + "unit": "" + }, + { + "name": "baseline_value", + "value": "4200.000", + "unit": "" + }, + { + "name": "predicted_delta_pct", + "value": "15.000", + "unit": "%" + } + ], + "missing": [], + "notes": [] + }, + { + "id": "rsi:hypothesis:hypo-kv-0001:falsification", + "kind": 7, + "status": 4, + "statement": "Refuted if this check fails: assert!(receipt.passed_all_hard_invariants). Protected metrics: p95_latency may degrade at most 1.0%; p99_latency may degrade at most 1.0%; max_rss_kb may degrade at most 2.0%; correctness may degrade at most 0.0%", + "source": { + "system": "spark-rsi", + "artifact": "HypothesisContract", + "reference": "hypo-kv-0001" + }, + "parents": [ + { + "to": "rsi:hypothesis:hypo-kv-0001", + "relation": 3 + } + ], + "measurements": [ + { + "name": "protected.p95_latency.max_degradation_pct", + "value": "1.000", + "unit": "%" + }, + { + "name": "protected.p99_latency.max_degradation_pct", + "value": "1.000", + "unit": "%" + }, + { + "name": "protected.max_rss_kb.max_degradation_pct", + "value": "2.000", + "unit": "%" + }, + { + "name": "protected.correctness.max_degradation_pct", + "value": "0.000", + "unit": "%" + } + ], + "missing": [], + "notes": [] + }, + { + "id": "rsi:diagnostic:cycle-kv-0001", + "kind": 4, + "status": 3, + "statement": "Diagnosis for src/kv_allocator.rs: primary defect PerformanceRegression; Bottleneck identified at Unified LPDDR5x KV Allocator", + "source": { + "system": "spark-rsi", + "artifact": "DiagnosticContext", + "reference": "cycle-kv-0001" + }, + "parents": [ + { + "to": "rsi:hypothesis:hypo-kv-0001", + "relation": 1 + } + ], + "measurements": [], + "missing": [], + "notes": [ + "1 recalled lesson(s) from the outside memory service were left out: they are free text, not evidence" + ] + }, + { + "id": "rsi:receipt:cycle-kv-0001:cand-kv-0001", + "kind": 8, + "status": 2, + "statement": "Evaluation of candidate cand-kv-0001 (parent parent): admitted=true, 2 evaluation layer result(s)", + "source": { + "system": "spark-rsi", + "artifact": "EvaluationReceipt", + "reference": "cand-kv-0001", + "digest": "c0cae9f3e257ef2f7b46f5cd3770f9fe1c21f8b6dfb2ee2e2449714b0c7e99d0" + }, + "parents": [], + "measurements": [ + { + "name": "layer.Correctness.passed", + "value": "true", + "unit": "" + }, + { + "name": "layer.Correctness.score", + "value": "1.0000", + "unit": "" + }, + { + "name": "layer.Performance.passed", + "value": "true", + "unit": "" + }, + { + "name": "layer.Performance.score", + "value": "0.8200", + "unit": "" + } + ], + "missing": [], + "notes": [ + "receipt is unsigned" + ] + }, + { + "id": "rsi:receipt:cycle-kv-0001:cand-kv-0001:summary", + "kind": 8, + "status": 0, + "statement": "The evaluator reports: hard invariants passed=true, statistical gates passed=true", + "source": { + "system": "spark-rsi", + "artifact": "EvaluationReceipt", + "reference": "cand-kv-0001" + }, + "parents": [ + { + "to": "rsi:receipt:cycle-kv-0001:cand-kv-0001", + "relation": 3 + } + ], + "measurements": [ + { + "name": "latency_delta_pct", + "value": "-17.500", + "unit": "%" + }, + { + "name": "p_value", + "value": "0.004000", + "unit": "" + }, + { + "name": "p95_ci_upper_degradation_pct", + "value": "-9.000", + "unit": "%" + }, + { + "name": "p99_ci_upper_degradation_pct", + "value": "-4.000", + "unit": "%" + }, + { + "name": "rss_growth_pct", + "value": "0.500", + "unit": "%" + } + ], + "missing": [], + "notes": [ + "these fields are not covered by the receipt digest, so they are reported, not verified" + ] + }, + { + "id": "rsi:ratification:cand-kv-0001", + "kind": 9, + "status": 1, + "statement": "Ratification record for proposal cand-kv-0001: status Ratified (test record)", + "source": { + "system": "spark-rsi", + "artifact": "RatificationRecord", + "reference": "cand-kv-0001" + }, + "parents": [ + { + "to": "rsi:receipt:cycle-kv-0001:cand-kv-0001", + "relation": 1 + } + ], + "measurements": [], + "missing": [], + "notes": [] + }, + { + "id": "rsi:conclusion:cycle-kv-0001", + "kind": 12, + "status": 3, + "statement": "RSI proposes changing src/kv_allocator.rs to address PerformanceRegression (cycle cycle-kv-0001)", + "source": { + "system": "spark-rsi", + "artifact": "RsiCycle", + "reference": "cycle-kv-0001" + }, + "parents": [ + { + "to": "rsi:diagnostic:cycle-kv-0001", + "relation": 1 + }, + { + "to": "rsi:hypothesis:hypo-kv-0001:prediction", + "relation": 1 + }, + { + "to": "rsi:hypothesis:hypo-kv-0001:falsification", + "relation": 1 + }, + { + "to": "rsi:receipt:cycle-kv-0001:cand-kv-0001", + "relation": 1 + }, + { + "to": "rsi:receipt:cycle-kv-0001:cand-kv-0001:summary", + "relation": 1 + }, + { + "to": "rsi:ratification:cand-kv-0001", + "relation": 1 + } + ], + "measurements": [], + "missing": [ + { + "expected": "an artifact linking candidate cand-kv-0001 to hypothesis hypo-kv-0001", + "reason": "both belong to cycle cycle-kv-0001, but no RSI artifact records that the candidate was generated from this hypothesis, so the evaluation is not shown as testing it" + } + ], + "notes": [ + "this explanation is observational; it does not authorize promotion or any change" + ] + } + ], + "truncated_at": [] +} diff --git a/crates/aienos-explain/tests/rsi_and_cli.rs b/crates/aienos-explain/tests/rsi_and_cli.rs new file mode 100644 index 00000000..28fbbba2 --- /dev/null +++ b/crates/aienos-explain/tests/rsi_and_cli.rs @@ -0,0 +1,198 @@ +//! Cross-repo fixture from spark-rsi (the RSI KV-cache cycle) and the CLI. +//! +//! The fixture is produced by spark-rsi `tests/test_explain_evidence_graph.rs`; both +//! repos pin the same sha256 so a contract drift on either side fails a test. + +use aienos_explain::bundle::{Role, UncertaintyKind}; +use aienos_explain::contract::{ + EdgeDoc, EvidenceGraph, NodeDoc, NodeKind, Relation, SourceRef, Status, +}; +use aienos_explain::{build_bundle, render, ExplanationRequest, Limits, Mode}; +use std::process::Command; + +const FIXTURE: &[u8] = include_bytes!("fixtures/rsi_kv_cycle.evidence.json"); +const FIXTURE_SHA256: &str = "0c04376ca36d95d677942d7e97c0a3eef3728ef72dc3cdf070494174e6a6cc31"; +const TARGET: &str = "rsi:conclusion:cycle-kv-0001"; + +fn hexs(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +fn fixture() -> EvidenceGraph { + EvidenceGraph::from_json(FIXTURE).expect("fixture parses") +} + +#[test] +fn rsi_fixture_is_pinned() { + assert_eq!( + hexs(&aienos_crypto::sha256::hash(FIXTURE)), + FIXTURE_SHA256, + "fixture changed; regenerate in spark-rsi and update both pins" + ); +} + +#[test] +fn rsi_cycle_explains_in_causal_order() { + let g = fixture(); + assert_eq!(g.producer, "spark-rsi/explain"); + let b = build_bundle(&g, TARGET, Limits::default()).expect("bundle"); + assert_eq!(b.conclusion().node_id, TARGET); + // Role order along the path never goes backwards for this cycle. + let roles: Vec = b.steps.iter().map(|s| s.role).collect(); + let first = |r: Role| roles.iter().position(|x| *x == r).expect("role present"); + assert!(first(Role::Observed) < first(Role::Analysis)); + assert!(first(Role::Analysis) < first(Role::Hypothesis)); + assert!(first(Role::Hypothesis) < first(Role::Prediction)); + assert!(first(Role::Prediction) < first(Role::Falsification)); + assert!(first(Role::Falsification) < first(Role::Evaluation)); + assert!(first(Role::Evaluation) < first(Role::Decision)); + assert_eq!(*roles.last().unwrap(), Role::Conclusion); + + let kinds: Vec = b.uncertainties.iter().map(|u| u.kind).collect(); + // Candidate -> hypothesis link is not recorded by RSI, so it stays visible. + assert!(kinds.contains(&UncertaintyKind::MissingLink)); + // The receipt does not evaluate the hypothesis directly. + assert!(kinds.contains(&UncertaintyKind::HypothesisNotFalsified)); + // Gate flags are outside the receipt digest: reported, status unknown. + assert!(kinds.contains(&UncertaintyKind::Unknown)); + assert_eq!(b.alternatives.len(), 3); + + let receipt = b + .steps + .iter() + .find(|s| s.kind == NodeKind::EvaluationReceipt && s.source.digest.is_some()) + .expect("receipt step"); + assert_eq!(receipt.status, Status::VerifiedFact); + let summary = b + .steps + .iter() + .find(|s| s.kind == NodeKind::EvaluationReceipt && s.source.digest.is_none()) + .expect("receipt summary step"); + assert_eq!(summary.status, Status::Unclassified); + // The hypothesis is never presented as fact. + let h = b + .steps + .iter() + .find(|s| s.kind == NodeKind::Hypothesis) + .expect("hypothesis"); + assert_eq!(h.status, Status::Hypothesis); + + let text = render(&b, &ExplanationRequest::new(Mode::StepByStep)); + for heading in [ + "Observed", + "System analysis", + "Hypothesis", + "Prediction", + "Falsification", + "Evaluation", + "Decision", + "Conclusion", + ] { + assert!(text.contains(heading), "missing heading {heading}:\n{text}"); + } + // Determinism across runs. + let again = build_bundle(&fixture(), TARGET, Limits::default()).unwrap(); + assert_eq!(b.bundle_digest, again.bundle_digest); +} + +fn node(id: &str, status: Status, parents: &[(&str, Relation)]) -> NodeDoc { + NodeDoc { + id: id.into(), + kind: NodeKind::CortexRecord.code(), + status: status.code(), + statement: format!("statement of {id}"), + source: SourceRef { + system: "test".into(), + artifact: "Node".into(), + reference: id.into(), + digest: None, + }, + confidence_permille: None, + confidence_basis: None, + recorded_at_utc: None, + parents: parents + .iter() + .map(|(to, r)| EdgeDoc { + to: (*to).into(), + relation: r.code(), + }) + .collect(), + measurements: Vec::new(), + missing: Vec::new(), + notes: Vec::new(), + } +} + +#[test] +fn contradiction_disclosed_in_both_directions() { + let mut g = EvidenceGraph::new("test"); + g.nodes = vec![ + node("t:obs", Status::DirectObservation, &[]), + // An ordinary record (not a Contradiction record) that contradicts the path. + node( + "t:rival", + Status::DirectObservation, + &[("t:obs", Relation::Contradicts)], + ), + // The target itself contradicts something off the path. + node( + "t:claim", + Status::Inference, + &[ + ("t:obs", Relation::SupportedBy), + ("t:other", Relation::Contradicts), + ], + ), + node("t:other", Status::DirectObservation, &[]), + ]; + let b = build_bundle(&g, "t:claim", Limits::default()).unwrap(); + let ids: Vec<&str> = b + .contradictions + .iter() + .map(|c| c.node_id.as_str()) + .collect(); + assert!(ids.contains(&"t:rival"), "{ids:?}"); + assert!(ids.contains(&"t:claim"), "{ids:?}"); + // Contradicting nodes are disclosed, never walked as support. + assert!(b + .steps + .iter() + .all(|s| s.node_id != "t:rival" && s.node_id != "t:other")); +} + +#[test] +fn cli_explains_fixture() { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/rsi_kv_cycle.evidence.json" + ); + let bin = env!("CARGO_BIN_EXE_aienos-explain"); + let out = Command::new(bin) + .args(["explain", "--graph", path, "--artifact", TARGET, "--why"]) + .output() + .expect("run cli"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let text = String::from_utf8(out.stdout).unwrap(); + assert!(text.contains("Conclusion")); + let json = Command::new(bin) + .args(["explain", "--graph", path, "--artifact", TARGET, "--json"]) + .output() + .unwrap(); + assert!(json.status.success()); + assert!(String::from_utf8_lossy(&json.stdout).contains("bundle_digest")); + let bad = Command::new(bin) + .args(["explain", "--graph", path, "--artifact", "no:such"]) + .output() + .unwrap(); + assert_eq!( + bad.status.code(), + Some(15), + "TargetNotFound is code 5, exit 10+5" + ); + let usage = Command::new(bin).args(["explain"]).output().unwrap(); + assert_eq!(usage.status.code(), Some(2)); +}