aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / aienos-explain / src / build.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Bounded causal backtracking and linearization. |
| 17 | //! |
| 18 | //! Given an evidence graph and a target node, walk support edges backward |
| 19 | //! (breadth first, deterministic order), stop at grounding nodes and at the limits, |
| 20 | //! cut loops, keep every gap visible, then order the visited sub-graph so that |
| 21 | //! every step comes after the steps it rests on. Only explicit edges are followed; |
| 22 | //! time stamps are never used to order or connect steps. |
| 23 | |
| 24 | use crate::bundle::{ |
| 25 | hex, Alternative, CausalStep, ContradictionRef, EvidenceRef, ExplanationBundle, |
| 26 | ExplanationProvenance, Limits, Role, SupportLink, Uncertainty, UncertaintyKind, |
| 27 | }; |
| 28 | use crate::contract::{EvidenceGraph, ExplainError, NodeDoc, NodeKind, Relation, Status}; |
| 29 | use std::collections::{BTreeMap, BTreeSet, VecDeque}; |
| 30 | |
| 31 | /// Builder identity recorded in every bundle. |
| 32 | pub const BUILDER: &str = "aienos-explain/1"; |
| 33 | |
| 34 | struct Node<'a> { |
| 35 | doc: &'a NodeDoc, |
| 36 | kind: NodeKind, |
| 37 | status: Status, |
| 38 | /// Support parents, sorted by (relation code, id), duplicates removed. |
| 39 | support: Vec<(Relation, &'a str)>, |
| 40 | } |
| 41 | |
| 42 | fn index(graph: &EvidenceGraph) -> Result<BTreeMap<&str, Node<'_>>, ExplainError> { |
| 43 | graph.validate()?; |
| 44 | let mut map = BTreeMap::new(); |
| 45 | for doc in &graph.nodes { |
| 46 | let kind = NodeKind::from_code(doc.kind)?; |
| 47 | let status = Status::from_code(doc.status)?; |
| 48 | let mut support: Vec<(Relation, &str)> = Vec::new(); |
| 49 | for e in &doc.parents { |
| 50 | let rel = Relation::from_code(e.relation)?; |
| 51 | if rel.is_support() { |
| 52 | support.push((rel, e.to.as_str())); |
| 53 | } |
| 54 | } |
| 55 | support.sort(); |
| 56 | support.dedup(); |
| 57 | map.insert( |
| 58 | doc.id.as_str(), |
| 59 | Node { |
| 60 | doc, |
| 61 | kind, |
| 62 | status, |
| 63 | support, |
| 64 | }, |
| 65 | ); |
| 66 | } |
| 67 | Ok(map) |
| 68 | } |
| 69 | |
| 70 | fn check_limits(l: &Limits) -> Result<(), ExplainError> { |
| 71 | if l.max_depth == 0 || l.max_nodes == 0 { |
| 72 | return Err(ExplainError::InvalidLimits( |
| 73 | "limits must be at least 1".into(), |
| 74 | )); |
| 75 | } |
| 76 | if l.max_depth > Limits::HARD_MAX_DEPTH || l.max_nodes > Limits::HARD_MAX_NODES { |
| 77 | return Err(ExplainError::InvalidLimits(format!( |
| 78 | "max_depth <= {}, max_nodes <= {}", |
| 79 | Limits::HARD_MAX_DEPTH, |
| 80 | Limits::HARD_MAX_NODES |
| 81 | ))); |
| 82 | } |
| 83 | Ok(()) |
| 84 | } |
| 85 | |
| 86 | /// Build the grounded explanation of `target` from `graph`. |
| 87 | pub fn build_bundle( |
| 88 | graph: &EvidenceGraph, |
| 89 | target: &str, |
| 90 | limits: Limits, |
| 91 | ) -> Result<ExplanationBundle, ExplainError> { |
| 92 | check_limits(&limits)?; |
| 93 | let nodes = index(graph)?; |
| 94 | if !nodes.contains_key(target) { |
| 95 | return Err(ExplainError::TargetNotFound(target.to_string())); |
| 96 | } |
| 97 | let producer_truncated: BTreeSet<&str> = |
| 98 | graph.truncated_at.iter().map(|s| s.as_str()).collect(); |
| 99 | let scope_refs: BTreeSet<&str> = graph |
| 100 | .scope |
| 101 | .as_ref() |
| 102 | .map(|s| s.referenced.iter().map(|r| r.as_str()).collect()) |
| 103 | .unwrap_or_default(); |
| 104 | |
| 105 | let mut unc: Vec<Uncertainty> = Vec::new(); |
| 106 | |
| 107 | // 1. Bounded breadth-first discovery. depth = shortest edge count from target. |
| 108 | let mut depth: BTreeMap<&str, u32> = BTreeMap::new(); |
| 109 | let mut queue: VecDeque<&str> = VecDeque::new(); |
| 110 | depth.insert(target, 0); |
| 111 | queue.push_back(target); |
| 112 | let mut truncated_nodes: BTreeSet<&str> = BTreeSet::new(); |
| 113 | while let Some(id) = queue.pop_front() { |
| 114 | let n = &nodes[id]; |
| 115 | let d = depth[id]; |
| 116 | // Grounding nodes end the walk: their own parents are not needed to explain. |
| 117 | if n.status.is_grounding() && id != target { |
| 118 | continue; |
| 119 | } |
| 120 | for (_, pid) in &n.support { |
| 121 | if depth.contains_key(pid) { |
| 122 | continue; |
| 123 | } |
| 124 | if !nodes.contains_key(pid) { |
| 125 | if !producer_truncated.contains(id) { |
| 126 | unc.push(Uncertainty { |
| 127 | kind: UncertaintyKind::MissingParent, |
| 128 | node_id: id.to_string(), |
| 129 | related: Some(pid.to_string()), |
| 130 | detail: format!( |
| 131 | "{id} lists {pid} as support, but no such artifact is available; \ |
| 132 | the system has no evidence for that link" |
| 133 | ), |
| 134 | }); |
| 135 | } |
| 136 | continue; |
| 137 | } |
| 138 | if d + 1 > limits.max_depth || depth.len() as u32 >= limits.max_nodes { |
| 139 | truncated_nodes.insert(id); |
| 140 | continue; |
| 141 | } |
| 142 | depth.insert(*pid, d + 1); |
| 143 | queue.push_back(*pid); |
| 144 | } |
| 145 | } |
| 146 | for id in &truncated_nodes { |
| 147 | unc.push(Uncertainty { |
| 148 | kind: UncertaintyKind::Truncated, |
| 149 | node_id: id.to_string(), |
| 150 | related: None, |
| 151 | detail: format!( |
| 152 | "support of {id} was not followed further (depth limit {}, node limit {})", |
| 153 | limits.max_depth, limits.max_nodes |
| 154 | ), |
| 155 | }); |
| 156 | } |
| 157 | |
| 158 | // The producer also stopped somewhere (its own limits). Say so for every visited |
| 159 | // node it marked, even when no parent is visibly missing. |
| 160 | for id in &producer_truncated { |
| 161 | if depth.contains_key(id) && !truncated_nodes.contains(id) { |
| 162 | unc.push(Uncertainty { |
| 163 | kind: UncertaintyKind::Truncated, |
| 164 | node_id: id.to_string(), |
| 165 | related: None, |
| 166 | detail: format!( |
| 167 | "the producer of this graph stopped collecting evidence around {id} at \ |
| 168 | its own limits; more support or contradictions may exist" |
| 169 | ), |
| 170 | }); |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | // 2. Visited support edges (child -> parent) restricted to the visited set. |
| 175 | let visited: BTreeSet<&str> = depth.keys().copied().collect(); |
| 176 | let mut edges: BTreeMap<&str, Vec<(Relation, &str)>> = BTreeMap::new(); |
| 177 | for id in &visited { |
| 178 | let n = &nodes[id]; |
| 179 | let keep: Vec<(Relation, &str)> = if n.status.is_grounding() && *id != target { |
| 180 | Vec::new() |
| 181 | } else { |
| 182 | n.support |
| 183 | .iter() |
| 184 | .filter(|(_, p)| visited.contains(p)) |
| 185 | .copied() |
| 186 | .collect() |
| 187 | }; |
| 188 | edges.insert(*id, keep); |
| 189 | } |
| 190 | |
| 191 | // 3. Cycle detection: iterative DFS with colors from the target; cut back edges. |
| 192 | let mut color: BTreeMap<&str, u8> = visited.iter().map(|v| (*v, 0u8)).collect(); |
| 193 | let mut cut: BTreeSet<(&str, &str)> = BTreeSet::new(); |
| 194 | let mut stack: Vec<(&str, usize)> = vec![(target, 0)]; |
| 195 | color.insert(target, 1); |
| 196 | while let Some((id, i)) = stack.pop() { |
| 197 | let es = &edges[id]; |
| 198 | if i < es.len() { |
| 199 | stack.push((id, i + 1)); |
| 200 | let p = es[i].1; |
| 201 | match color[p] { |
| 202 | 0 => { |
| 203 | color.insert(p, 1); |
| 204 | stack.push((p, 0)); |
| 205 | } |
| 206 | 1 => { |
| 207 | cut.insert((id, p)); |
| 208 | } |
| 209 | _ => {} |
| 210 | } |
| 211 | } else { |
| 212 | color.insert(id, 2); |
| 213 | } |
| 214 | } |
| 215 | for (from, to) in &cut { |
| 216 | unc.push(Uncertainty { |
| 217 | kind: UncertaintyKind::Cycle, |
| 218 | node_id: from.to_string(), |
| 219 | related: Some(to.to_string()), |
| 220 | detail: format!( |
| 221 | "{from} rests on {to}, which already rests on {from}; the loop was cut and \ |
| 222 | this support is circular, not grounding" |
| 223 | ), |
| 224 | }); |
| 225 | } |
| 226 | let dag: BTreeMap<&str, Vec<(Relation, &str)>> = edges |
| 227 | .iter() |
| 228 | .map(|(id, es)| { |
| 229 | ( |
| 230 | *id, |
| 231 | es.iter() |
| 232 | .filter(|(_, p)| !cut.contains(&(*id, *p))) |
| 233 | .copied() |
| 234 | .collect(), |
| 235 | ) |
| 236 | }) |
| 237 | .collect(); |
| 238 | |
| 239 | // 4. Linearize (Kahn): a node is ready once all its parents are placed. |
| 240 | // Ties are broken by narrative role, then by id. The target is always last. |
| 241 | let mut remaining: BTreeMap<&str, usize> = dag.iter().map(|(id, es)| (*id, es.len())).collect(); |
| 242 | let mut children: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); |
| 243 | for (id, es) in &dag { |
| 244 | for (_, p) in es { |
| 245 | children.entry(*p).or_default().push(*id); |
| 246 | } |
| 247 | } |
| 248 | let key = |id: &str| -> (Role, String) { |
| 249 | let n = &nodes[id]; |
| 250 | (Role::of(n.kind, n.status), id.to_string()) |
| 251 | }; |
| 252 | let mut ready: BTreeSet<(Role, String)> = remaining |
| 253 | .iter() |
| 254 | .filter(|(id, c)| **c == 0 && **id != target) |
| 255 | .map(|(id, _)| key(id)) |
| 256 | .collect(); |
| 257 | let mut order: Vec<&str> = Vec::new(); |
| 258 | while let Some(k) = ready.iter().next().cloned() { |
| 259 | ready.remove(&k); |
| 260 | let id: &str = visited.get(k.1.as_str()).copied().expect("visited id"); |
| 261 | order.push(id); |
| 262 | if let Some(cs) = children.get(id) { |
| 263 | for c in cs { |
| 264 | let r = remaining.get_mut(c).expect("child"); |
| 265 | *r -= 1; |
| 266 | if *r == 0 && *c != target { |
| 267 | ready.insert(key(c)); |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | order.push(target); |
| 273 | debug_assert_eq!(order.len(), visited.len()); |
| 274 | |
| 275 | // 5. Steps. |
| 276 | let pos: BTreeMap<&str, u32> = order |
| 277 | .iter() |
| 278 | .enumerate() |
| 279 | .map(|(i, id)| (*id, i as u32 + 1)) |
| 280 | .collect(); |
| 281 | let mut steps: Vec<CausalStep> = Vec::with_capacity(order.len()); |
| 282 | for id in &order { |
| 283 | let n = &nodes[id]; |
| 284 | let mut supported_by: Vec<SupportLink> = dag[id] |
| 285 | .iter() |
| 286 | .map(|(rel, p)| SupportLink { |
| 287 | step: pos[p], |
| 288 | relation: *rel, |
| 289 | }) |
| 290 | .collect(); |
| 291 | supported_by.sort_by_key(|s| (s.step, s.relation)); |
| 292 | steps.push(CausalStep { |
| 293 | index: pos[id], |
| 294 | node_id: id.to_string(), |
| 295 | kind: n.kind, |
| 296 | status: n.status, |
| 297 | role: Role::of(n.kind, n.status), |
| 298 | statement: n.doc.statement.clone(), |
| 299 | source: n.doc.source.clone(), |
| 300 | confidence_permille: n.doc.confidence_permille, |
| 301 | confidence_basis: n.doc.confidence_basis.clone(), |
| 302 | recorded_at_utc: n.doc.recorded_at_utc, |
| 303 | measurements: n.doc.measurements.clone(), |
| 304 | notes: n.doc.notes.clone(), |
| 305 | supported_by, |
| 306 | depth: depth[id], |
| 307 | grounding: n.status.is_grounding(), |
| 308 | branch_referenced: scope_refs.contains(id), |
| 309 | }); |
| 310 | } |
| 311 | |
| 312 | // 6. Per-step uncertainty that stays visible. |
| 313 | for s in &steps { |
| 314 | let n = &nodes[s.node_id.as_str()]; |
| 315 | for m in &n.doc.missing { |
| 316 | unc.push(Uncertainty { |
| 317 | kind: UncertaintyKind::MissingLink, |
| 318 | node_id: s.node_id.clone(), |
| 319 | related: Some(m.expected.clone()), |
| 320 | detail: format!("no evidence for: {} ({})", m.expected, m.reason), |
| 321 | }); |
| 322 | } |
| 323 | for note in &n.doc.notes { |
| 324 | unc.push(Uncertainty { |
| 325 | kind: UncertaintyKind::ProducerNote, |
| 326 | node_id: s.node_id.clone(), |
| 327 | related: None, |
| 328 | detail: note.clone(), |
| 329 | }); |
| 330 | } |
| 331 | if s.kind == NodeKind::AgentBranch { |
| 332 | continue; |
| 333 | } |
| 334 | let has_support = !n.support.is_empty() || !n.doc.missing.is_empty(); |
| 335 | match s.status { |
| 336 | Status::Unclassified => unc.push(Uncertainty { |
| 337 | kind: UncertaintyKind::Unknown, |
| 338 | node_id: s.node_id.clone(), |
| 339 | related: None, |
| 340 | detail: format!( |
| 341 | "the epistemic status of step {} is not known; it is neither observed \ |
| 342 | nor verified", |
| 343 | s.index |
| 344 | ), |
| 345 | }), |
| 346 | Status::Inference | Status::Hypothesis if !has_support => unc.push(Uncertainty { |
| 347 | kind: UncertaintyKind::Unsupported, |
| 348 | node_id: s.node_id.clone(), |
| 349 | related: None, |
| 350 | detail: format!( |
| 351 | "step {} is a {} with no recorded support", |
| 352 | s.index, |
| 353 | s.status.name() |
| 354 | ), |
| 355 | }), |
| 356 | Status::Inference => unc.push(Uncertainty { |
| 357 | kind: UncertaintyKind::Inferred, |
| 358 | node_id: s.node_id.clone(), |
| 359 | related: None, |
| 360 | detail: format!( |
| 361 | "step {} is inferred from earlier steps, not observed directly", |
| 362 | s.index |
| 363 | ), |
| 364 | }), |
| 365 | _ => {} |
| 366 | } |
| 367 | let is_hypothesis = s.kind == NodeKind::Hypothesis |
| 368 | || (s.kind == NodeKind::CortexRecord && s.status == Status::Hypothesis); |
| 369 | if is_hypothesis { |
| 370 | let tested = steps.iter().any(|o| { |
| 371 | let os = &nodes[o.node_id.as_str()].support; |
| 372 | (o.kind == NodeKind::EvaluationReceipt |
| 373 | && os |
| 374 | .iter() |
| 375 | .any(|(rel, p)| *rel == Relation::Evaluates && *p == s.node_id)) |
| 376 | || (o.kind == NodeKind::CortexRecord |
| 377 | && o.status == Status::VerifiedFact |
| 378 | && os.iter().any(|(_, p)| *p == s.node_id)) |
| 379 | }); |
| 380 | if !tested { |
| 381 | unc.push(Uncertainty { |
| 382 | kind: UncertaintyKind::HypothesisNotFalsified, |
| 383 | node_id: s.node_id.clone(), |
| 384 | related: None, |
| 385 | detail: format!( |
| 386 | "hypothesis at step {} has no evaluation that tests it directly; it \ |
| 387 | remains a hypothesis", |
| 388 | s.index |
| 389 | ), |
| 390 | }); |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | // 7. Contradictions and alternatives that touch the path. A Contradicts edge is |
| 396 | // disclosed when either end is on the path, in either direction, whatever the |
| 397 | // status of the node that carries it. Bounded by the input size cap; never |
| 398 | // followed further. |
| 399 | let mut contradictions = Vec::new(); |
| 400 | let mut alternatives = Vec::new(); |
| 401 | for (id, n) in &nodes { |
| 402 | let mut targets: Vec<String> = Vec::new(); |
| 403 | let mut alt_to: Option<String> = None; |
| 404 | for e in &n.doc.parents { |
| 405 | let rel = Relation::from_code(e.relation)?; |
| 406 | match rel { |
| 407 | Relation::Contradicts => targets.push(e.to.clone()), |
| 408 | Relation::AlternativeTo if alt_to.is_none() && visited.contains(e.to.as_str()) => { |
| 409 | alt_to = Some(e.to.clone()) |
| 410 | } |
| 411 | _ => {} |
| 412 | } |
| 413 | } |
| 414 | let self_on_path = visited.contains(id); |
| 415 | let mut involves: Vec<String> = targets |
| 416 | .iter() |
| 417 | .filter(|t| visited.contains(t.as_str())) |
| 418 | .cloned() |
| 419 | .collect(); |
| 420 | if !targets.is_empty() && self_on_path { |
| 421 | involves.push(id.to_string()); |
| 422 | } |
| 423 | involves.sort(); |
| 424 | involves.dedup(); |
| 425 | if !involves.is_empty() { |
| 426 | targets.sort(); |
| 427 | targets.dedup(); |
| 428 | let statement = if n.status == Status::Contradiction { |
| 429 | n.doc.statement.clone() |
| 430 | } else { |
| 431 | format!( |
| 432 | "{id} contradicts {}: {}", |
| 433 | targets.join(", "), |
| 434 | n.doc.statement |
| 435 | ) |
| 436 | }; |
| 437 | for t in &involves { |
| 438 | let other = if t.as_str() == *id { |
| 439 | targets.first().cloned().unwrap_or_default() |
| 440 | } else { |
| 441 | id.to_string() |
| 442 | }; |
| 443 | unc.push(Uncertainty { |
| 444 | kind: UncertaintyKind::ConflictingEvidence, |
| 445 | node_id: t.clone(), |
| 446 | related: Some(other), |
| 447 | detail: format!("{t} is involved in a recorded contradiction: {statement}"), |
| 448 | }); |
| 449 | } |
| 450 | contradictions.push(ContradictionRef { |
| 451 | node_id: id.to_string(), |
| 452 | statement, |
| 453 | source: n.doc.source.clone(), |
| 454 | involves, |
| 455 | }); |
| 456 | } |
| 457 | if let (NodeKind::Alternative, Some(to)) = (n.kind, alt_to) { |
| 458 | alternatives.push(Alternative { |
| 459 | node_id: id.to_string(), |
| 460 | statement: n.doc.statement.clone(), |
| 461 | source: n.doc.source.clone(), |
| 462 | alternative_to: to, |
| 463 | measurements: n.doc.measurements.clone(), |
| 464 | }); |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | // 8. Evidence pointers: every step with a digest or measurements. |
| 469 | let evidence: Vec<EvidenceRef> = steps |
| 470 | .iter() |
| 471 | .filter(|s| s.source.digest.is_some() || !s.measurements.is_empty()) |
| 472 | .map(|s| EvidenceRef { |
| 473 | step: s.index, |
| 474 | node_id: s.node_id.clone(), |
| 475 | source: s.source.clone(), |
| 476 | measurements: s.measurements.clone(), |
| 477 | }) |
| 478 | .collect(); |
| 479 | |
| 480 | unc.sort_by(|a, b| { |
| 481 | (a.kind, &a.node_id, &a.related, &a.detail) |
| 482 | .cmp(&(b.kind, &b.node_id, &b.related, &b.detail)) |
| 483 | }); |
| 484 | unc.dedup(); |
| 485 | |
| 486 | let provenance = ExplanationProvenance { |
| 487 | builder: BUILDER.to_string(), |
| 488 | contract_format: graph.format.clone(), |
| 489 | contract_version: graph.version, |
| 490 | producer: graph.producer.clone(), |
| 491 | input_digest: hex(&aienos_crypto::sha256::hash(&graph.to_json())), |
| 492 | target: target.to_string(), |
| 493 | limits, |
| 494 | branch_scope: graph.scope.as_ref().map(|s| s.branch.clone()), |
| 495 | visited_nodes: visited.len() as u32, |
| 496 | graph_nodes: graph.nodes.len() as u32, |
| 497 | }; |
| 498 | let mut bundle = ExplanationBundle { |
| 499 | conclusion_step: order.len() as u32, |
| 500 | steps, |
| 501 | evidence, |
| 502 | uncertainties: unc, |
| 503 | contradictions, |
| 504 | alternatives, |
| 505 | provenance, |
| 506 | bundle_digest: String::new(), |
| 507 | }; |
| 508 | bundle.bundle_digest = bundle.compute_digest(); |
| 509 | Ok(bundle) |
| 510 | } |