Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-explain/src/adapters.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-explain / src / adapters.rs` 312 lines ยท 11753 bytes Raw Blame History 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 //! Producers of the evidence-graph contract from aienos Cortex records and agent 17 //! branches. Read-only: nothing here writes to Cortex or to agent state. 18 //! 19 //! The walk over Cortex is bounded by the same [`Limits`] the builder uses, plus one 20 //! level of headroom, and records where it stopped (`truncated_at`) so the builder can 21 //! say "cut short" instead of "missing". 22 23 use crate::bundle::{hex, Limits}; 24 use crate::contract::{ 25 EdgeDoc, EvidenceGraph, ExplainError, NodeDoc, NodeKind, Relation, ScopeDoc, SourceRef, Status, 26 }; 27 use aienos_agent_state::LogicalBranch; 28 use aienos_cortex::{CortexStore, EpistemicRecord, EpistemicStatus}; 29 use std::collections::{BTreeMap, BTreeSet, VecDeque}; 30 31 /// Node id of a Cortex record in the contract. 32 pub fn cortex_node_id(id: &[u8; 16]) -> String { 33 format!("cortex:{}", hex(id)) 34 } 35 36 /// Node id of an agent branch in the contract. 37 pub fn branch_node_id(branch: &LogicalBranch) -> String { 38 format!("branch:{}", hex(&branch.branch_id.0)) 39 } 40 41 fn status_code(s: EpistemicStatus) -> u8 { 42 s as u8 43 } 44 45 fn record_to_node(r: &EpistemicRecord) -> NodeDoc { 46 let rel = if r.status == EpistemicStatus::Contradiction { 47 Relation::Contradicts 48 } else { 49 Relation::SupportedBy 50 }; 51 let mut notes = Vec::new(); 52 if let Some(v) = &r.verified_by { 53 notes.push(format!("verified by {v}")); 54 } 55 let conf = r.confidence; 56 let permille = if conf.is_finite() { 57 Some((conf.clamp(0.0, 1.0) * 1000.0).round() as u16) 58 } else { 59 None 60 }; 61 NodeDoc { 62 id: cortex_node_id(&r.id), 63 kind: NodeKind::CortexRecord.code(), 64 status: status_code(r.status), 65 statement: r.statement.clone(), 66 source: SourceRef { 67 system: "aienos-cortex".into(), 68 artifact: "EpistemicRecord".into(), 69 reference: r.provenance_source.clone(), 70 digest: Some(hex(&r.evidence_hash)), 71 }, 72 confidence_permille: permille, 73 confidence_basis: permille.map(|_| "Cortex record confidence".to_string()), 74 recorded_at_utc: Some(r.created_at_utc), 75 parents: r 76 .causal_parents 77 .iter() 78 .map(|p| EdgeDoc { 79 to: cortex_node_id(p), 80 relation: rel.code(), 81 }) 82 .collect(), 83 measurements: Vec::new(), 84 missing: Vec::new(), 85 notes, 86 } 87 } 88 89 /// Bounded backward walk over Cortex from `roots`, emitting reachable records plus 90 /// contradiction records that involve them. `lookup` is any read-only view of the 91 /// store (the real `CortexStore`, an imported journal, a test map). 92 pub fn cortex_graph_from<'a, F>( 93 roots: &[[u8; 16]], 94 lookup: F, 95 contradictions: &[&'a EpistemicRecord], 96 limits: Limits, 97 ) -> EvidenceGraph 98 where 99 F: Fn(&[u8; 16]) -> Option<&'a EpistemicRecord>, 100 { 101 let mut g = EvidenceGraph::new("aienos-explain/cortex-adapter"); 102 // Headroom: one extra level and node so the builder, not the adapter, decides 103 // where the explanation is cut. 104 let max_depth = limits.max_depth.saturating_add(1); 105 let max_nodes = limits.max_nodes.saturating_add(1) as usize; 106 let mut depth: BTreeMap<[u8; 16], u32> = BTreeMap::new(); 107 let mut order: Vec<[u8; 16]> = Vec::new(); 108 let mut queue: VecDeque<[u8; 16]> = VecDeque::new(); 109 let mut truncated: BTreeSet<[u8; 16]> = BTreeSet::new(); 110 let mut roots_sorted: Vec<[u8; 16]> = roots.to_vec(); 111 roots_sorted.sort(); 112 roots_sorted.dedup(); 113 for r in &roots_sorted { 114 if depth.contains_key(r) || lookup(r).is_none() { 115 continue; 116 } 117 if depth.len() >= max_nodes { 118 // Roots beyond the cap are dropped; mark every admitted root as cut so the 119 // builder says "cut short" rather than presenting a complete picture. 120 truncated.extend(depth.keys().copied()); 121 break; 122 } 123 depth.insert(*r, 0); 124 queue.push_back(*r); 125 } 126 while let Some(id) = queue.pop_front() { 127 let Some(rec) = lookup(&id) else { continue }; 128 order.push(id); 129 // Grounding records end the walk (except a root, which the builder may expand 130 // as its target). Contradiction records' parents are what they contradict, 131 // not support, so they are never walked. 132 if (rec.status.is_ground_truth() && !roots.contains(&id)) 133 || rec.status == EpistemicStatus::Contradiction 134 { 135 continue; 136 } 137 let d = depth[&id]; 138 let mut parents: Vec<[u8; 16]> = rec.causal_parents.clone(); 139 parents.sort(); 140 parents.dedup(); 141 for p in &parents { 142 if depth.contains_key(p) || lookup(p).is_none() { 143 continue; 144 } 145 if d + 1 > max_depth || depth.len() >= max_nodes { 146 truncated.insert(id); 147 continue; 148 } 149 depth.insert(*p, d + 1); 150 queue.push_back(*p); 151 } 152 } 153 let in_set: BTreeSet<[u8; 16]> = order.iter().copied().collect(); 154 let mut emitted: BTreeSet<[u8; 16]> = BTreeSet::new(); 155 for id in &order { 156 if let Some(r) = lookup(id) { 157 if emitted.insert(*id) { 158 g.nodes.push(record_to_node(r)); 159 } 160 } 161 } 162 // Contradictions about records in the set (disclosure, never support). 163 // Fixed order whatever order the store was built in. 164 let mut contradictions: Vec<&EpistemicRecord> = contradictions.to_vec(); 165 contradictions.sort_by_key(|r| (r.created_at_utc, r.id)); 166 contradictions.dedup_by(|a, b| a.id == b.id); 167 let mut extra = 0usize; 168 for c in contradictions { 169 if c.status != EpistemicStatus::Contradiction || emitted.contains(&c.id) { 170 continue; 171 } 172 if c.causal_parents.iter().any(|p| in_set.contains(p)) { 173 if extra >= max_nodes { 174 // Disclosure cap reached: mark the records this contradiction involves 175 // as cut so the builder reports that not everything was collected. 176 truncated.extend(c.causal_parents.iter().filter(|p| in_set.contains(*p))); 177 continue; 178 } 179 extra += 1; 180 emitted.insert(c.id); 181 g.nodes.push(record_to_node(c)); 182 } 183 } 184 g.truncated_at = truncated.iter().map(cortex_node_id).collect(); 185 g 186 } 187 188 /// Evidence graph explaining one Cortex record. 189 pub fn cortex_graph_for_record( 190 store: &CortexStore, 191 record: &[u8; 16], 192 limits: Limits, 193 ) -> Result { 194 if store.get(record).is_none() { 195 return Err(ExplainError::TargetNotFound(cortex_node_id(record))); 196 } 197 let contradictions = store.find_by_status(EpistemicStatus::Contradiction); 198 Ok(cortex_graph_from( 199 &[*record], 200 |id| store.get(id), 201 &contradictions, 202 limits, 203 )) 204 } 205 206 /// Read a sealed Cortex journal (as written by `CortexStore::export_journal`) into a 207 /// fresh store. The seal is checked; the live store is never touched. 208 pub fn store_from_journal(bytes: &[u8]) -> Result { 209 let mut s = CortexStore::new(); 210 s.import_journal(bytes) 211 .map_err(|e| ExplainError::Journal(e.to_string()))?; 212 Ok(s) 213 } 214 215 fn branch_node(branch: &LogicalBranch) -> NodeDoc { 216 let parent = branch 217 .parent_branch_id 218 .map(|p| hex(&p.0)[..16].to_string()) 219 .unwrap_or_else(|| "none (root branch)".into()); 220 NodeDoc { 221 id: branch_node_id(branch), 222 kind: NodeKind::AgentBranch.code(), 223 status: Status::Unclassified.code(), 224 statement: format!( 225 "Agent branch {} (lineage depth {}, parent {}) depends on {} referenced Cortex record(s)", 226 &hex(&branch.branch_id.0)[..16], 227 branch.lineage.depth, 228 parent, 229 branch.epistemic_refs.len() 230 ), 231 source: SourceRef { 232 system: "aienos-agent-state".into(), 233 artifact: "LogicalBranch".into(), 234 reference: hex(&branch.branch_id.0), 235 digest: None, 236 }, 237 confidence_permille: None, 238 confidence_basis: None, 239 recorded_at_utc: Some(branch.created_at_utc), 240 parents: branch 241 .epistemic_refs 242 .records() 243 .iter() 244 .map(|r| EdgeDoc { 245 to: cortex_node_id(r), 246 relation: Relation::References.code(), 247 }) 248 .collect(), 249 measurements: Vec::new(), 250 missing: Vec::new(), 251 notes: Vec::new(), 252 } 253 } 254 255 /// "What evidence did this branch actually depend on?" The graph holds the branch, 256 /// the records it references, and their bounded causal ancestry. Records that exist 257 /// in Cortex but that the branch never referenced are not included. 258 pub fn branch_graph(store: &CortexStore, branch: &LogicalBranch, limits: Limits) -> EvidenceGraph { 259 let refs: Vec<[u8; 16]> = branch.epistemic_refs.records().to_vec(); 260 let contradictions = store.find_by_status(EpistemicStatus::Contradiction); 261 let mut g = cortex_graph_from(&refs, |id| store.get(id), &contradictions, limits); 262 g.producer = "aienos-explain/branch-adapter".into(); 263 g.nodes.insert(0, branch_node(branch)); 264 g.scope = Some(ScopeDoc { 265 branch: branch_node_id(branch), 266 referenced: refs.iter().map(cortex_node_id).collect(), 267 }); 268 g 269 } 270 271 /// Explain one record as seen from a branch. Fails with `NotInBranchScope` when the 272 /// record is neither referenced by the branch nor in the support ancestry of a 273 /// referenced record, so unrelated Cortex facts cannot be pulled in to strengthen a 274 /// branch. Contradiction records that are only disclosed (they point at the branch's 275 /// evidence) are not in scope as targets. 276 pub fn branch_graph_for_record( 277 store: &CortexStore, 278 branch: &LogicalBranch, 279 record: &[u8; 16], 280 limits: Limits, 281 ) -> Result { 282 let g = branch_graph(store, branch, limits); 283 let want = cortex_node_id(record); 284 let by_id: BTreeMap<&str, &NodeDoc> = g.nodes.iter().map(|n| (n.id.as_str(), n)).collect(); 285 let mut seen: BTreeSet<&str> = BTreeSet::new(); 286 let mut queue: VecDeque<&str> = VecDeque::new(); 287 if let Some(s) = &g.scope { 288 for r in &s.referenced { 289 if by_id.contains_key(r.as_str()) && seen.insert(r.as_str()) { 290 queue.push_back(r.as_str()); 291 } 292 } 293 } 294 while let Some(id) = queue.pop_front() { 295 for e in &by_id[id].parents { 296 let support = Relation::from_code(e.relation).map(|r| r.is_support()); 297 if support == Ok(true) 298 && by_id.contains_key(e.to.as_str()) 299 && seen.insert(e.to.as_str()) 300 { 301 queue.push_back(e.to.as_str()); 302 } 303 } 304 } 305 if !seen.contains(want.as_str()) { 306 return Err(ExplainError::NotInBranchScope(format!( 307 "{want} is not evidence that branch {} depends on", 308 branch_node_id(branch) 309 ))); 310 } 311 Ok(g) 312 }