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 / bundle.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 | //! The grounded explanation bundle: the authoritative, deterministic output of the |
| 17 | //! builder. Renderers only read it. It has no field for analogies or prose, and it |
| 18 | //! grants no authority (explanation is observational). |
| 19 | |
| 20 | use crate::contract::{Measurement, NodeKind, Relation, SourceRef, Status}; |
| 21 | use serde::{Serialize, Serializer}; |
| 22 | |
| 23 | fn ser_status<S: Serializer>(s: &Status, ser: S) -> Result<S::Ok, S::Error> { |
| 24 | ser.serialize_str(s.name()) |
| 25 | } |
| 26 | fn ser_kind<S: Serializer>(k: &NodeKind, ser: S) -> Result<S::Ok, S::Error> { |
| 27 | ser.serialize_str(k.name()) |
| 28 | } |
| 29 | fn ser_relation<S: Serializer>(r: &Relation, ser: S) -> Result<S::Ok, S::Error> { |
| 30 | ser.serialize_str(r.name()) |
| 31 | } |
| 32 | |
| 33 | /// Narrative role of a step in the path. Derived only from kind and status. |
| 34 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] |
| 35 | pub enum Role { |
| 36 | Observed, |
| 37 | Analysis, |
| 38 | Hypothesis, |
| 39 | Prediction, |
| 40 | Falsification, |
| 41 | Evaluation, |
| 42 | Decision, |
| 43 | Conclusion, |
| 44 | } |
| 45 | |
| 46 | impl Role { |
| 47 | pub fn of(kind: NodeKind, status: Status) -> Self { |
| 48 | match kind { |
| 49 | NodeKind::CapabilityMetric => Self::Observed, |
| 50 | NodeKind::CapabilityAnalysis | NodeKind::Diagnostic => Self::Analysis, |
| 51 | NodeKind::Hypothesis => Self::Hypothesis, |
| 52 | NodeKind::Prediction => Self::Prediction, |
| 53 | NodeKind::Falsification => Self::Falsification, |
| 54 | NodeKind::EvaluationReceipt => Self::Evaluation, |
| 55 | NodeKind::PromotionState | NodeKind::OperatorDecision => Self::Decision, |
| 56 | NodeKind::Conclusion | NodeKind::AgentBranch => Self::Conclusion, |
| 57 | NodeKind::Alternative => Self::Analysis, |
| 58 | NodeKind::CortexRecord => match status { |
| 59 | Status::DirectObservation | Status::VerifiedFact => Self::Observed, |
| 60 | Status::OperatorDecision => Self::Decision, |
| 61 | Status::Hypothesis => Self::Hypothesis, |
| 62 | Status::Inference | Status::Contradiction | Status::Unclassified => Self::Analysis, |
| 63 | }, |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | pub fn heading(self) -> &'static str { |
| 68 | match self { |
| 69 | Self::Observed => "Observed", |
| 70 | Self::Analysis => "System analysis", |
| 71 | Self::Hypothesis => "Hypothesis", |
| 72 | Self::Prediction => "Prediction", |
| 73 | Self::Falsification => "Falsification", |
| 74 | Self::Evaluation => "Evaluation", |
| 75 | Self::Decision => "Decision", |
| 76 | Self::Conclusion => "Conclusion", |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// A support link from a step to an earlier step. |
| 82 | #[derive(Clone, Debug, PartialEq, Eq, Serialize)] |
| 83 | pub struct SupportLink { |
| 84 | /// 1-based index of the supporting step. |
| 85 | pub step: u32, |
| 86 | #[serde(serialize_with = "ser_relation")] |
| 87 | pub relation: Relation, |
| 88 | } |
| 89 | |
| 90 | /// One step of the linear path, in causal (parents first) order. |
| 91 | #[derive(Clone, Debug, PartialEq, Serialize)] |
| 92 | pub struct CausalStep { |
| 93 | /// 1-based position in the path. |
| 94 | pub index: u32, |
| 95 | pub node_id: String, |
| 96 | #[serde(serialize_with = "ser_kind")] |
| 97 | pub kind: NodeKind, |
| 98 | #[serde(serialize_with = "ser_status")] |
| 99 | pub status: Status, |
| 100 | pub role: Role, |
| 101 | pub statement: String, |
| 102 | pub source: SourceRef, |
| 103 | pub confidence_permille: Option<u16>, |
| 104 | pub confidence_basis: Option<String>, |
| 105 | pub recorded_at_utc: Option<u64>, |
| 106 | pub measurements: Vec<Measurement>, |
| 107 | pub notes: Vec<String>, |
| 108 | /// Earlier steps this step rests on. |
| 109 | pub supported_by: Vec<SupportLink>, |
| 110 | /// Shortest number of support edges from the conclusion. |
| 111 | pub depth: u32, |
| 112 | /// True when the status is a grounding status (observation, verified fact, |
| 113 | /// operator decision). |
| 114 | pub grounding: bool, |
| 115 | /// True when the branch in scope referenced this record directly. |
| 116 | pub branch_referenced: bool, |
| 117 | } |
| 118 | |
| 119 | /// Kinds of uncertainty kept visible in the explanation. Codes are stable. |
| 120 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] |
| 121 | pub enum UncertaintyKind { |
| 122 | /// A support edge points into itself through a loop; the loop edge was cut. |
| 123 | Cycle, |
| 124 | /// A contradiction record involves a step of this path. |
| 125 | ConflictingEvidence, |
| 126 | /// A parent id is listed but no such artifact exists. |
| 127 | MissingParent, |
| 128 | /// The producer declared a link it expected but has no artifact for. |
| 129 | MissingLink, |
| 130 | /// A derived claim (inference, hypothesis) has no recorded support at all. |
| 131 | Unsupported, |
| 132 | /// A hypothesis on the path has no evaluation step attached to it. |
| 133 | HypothesisNotFalsified, |
| 134 | /// The path is inferred (contains an inference that is not grounded only). |
| 135 | Inferred, |
| 136 | /// The artifact's epistemic status is unknown. |
| 137 | Unknown, |
| 138 | /// Traversal stopped at the depth or node limit. |
| 139 | Truncated, |
| 140 | /// Free-form caveat recorded by the producer (e.g. declared, not measured). |
| 141 | ProducerNote, |
| 142 | } |
| 143 | |
| 144 | impl UncertaintyKind { |
| 145 | pub fn code(self) -> u16 { |
| 146 | match self { |
| 147 | Self::Cycle => 1, |
| 148 | Self::ConflictingEvidence => 2, |
| 149 | Self::MissingParent => 3, |
| 150 | Self::MissingLink => 4, |
| 151 | Self::Unsupported => 5, |
| 152 | Self::HypothesisNotFalsified => 6, |
| 153 | Self::Inferred => 7, |
| 154 | Self::Unknown => 8, |
| 155 | Self::Truncated => 9, |
| 156 | Self::ProducerNote => 10, |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | pub fn label(self) -> &'static str { |
| 161 | match self { |
| 162 | Self::Cycle => "circular support", |
| 163 | Self::ConflictingEvidence => "conflicting evidence", |
| 164 | Self::MissingParent => "missing evidence", |
| 165 | Self::MissingLink => "missing link", |
| 166 | Self::Unsupported => "unsupported claim", |
| 167 | Self::HypothesisNotFalsified => "hypothesis not yet tested", |
| 168 | Self::Inferred => "inferred step", |
| 169 | Self::Unknown => "unknown status", |
| 170 | Self::Truncated => "explanation cut short", |
| 171 | Self::ProducerNote => "caveat", |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | #[derive(Clone, Debug, PartialEq, Eq, Serialize)] |
| 177 | pub struct Uncertainty { |
| 178 | pub kind: UncertaintyKind, |
| 179 | /// Node the uncertainty is attached to. |
| 180 | pub node_id: String, |
| 181 | /// Other id involved (missing parent, loop target, expected link). |
| 182 | pub related: Option<String>, |
| 183 | pub detail: String, |
| 184 | } |
| 185 | |
| 186 | /// A contradiction record that involves the path. Always shown. |
| 187 | #[derive(Clone, Debug, PartialEq, Serialize)] |
| 188 | pub struct ContradictionRef { |
| 189 | pub node_id: String, |
| 190 | pub statement: String, |
| 191 | pub source: SourceRef, |
| 192 | /// Path node ids the contradiction involves. |
| 193 | pub involves: Vec<String>, |
| 194 | } |
| 195 | |
| 196 | /// An alternative explanation that the evidence explicitly records. |
| 197 | #[derive(Clone, Debug, PartialEq, Serialize)] |
| 198 | pub struct Alternative { |
| 199 | pub node_id: String, |
| 200 | pub statement: String, |
| 201 | pub source: SourceRef, |
| 202 | pub alternative_to: String, |
| 203 | pub measurements: Vec<Measurement>, |
| 204 | } |
| 205 | |
| 206 | /// An evidence pointer (digest, receipt, measurements) attached to a step. |
| 207 | #[derive(Clone, Debug, PartialEq, Eq, Serialize)] |
| 208 | pub struct EvidenceRef { |
| 209 | pub step: u32, |
| 210 | pub node_id: String, |
| 211 | pub source: SourceRef, |
| 212 | pub measurements: Vec<Measurement>, |
| 213 | } |
| 214 | |
| 215 | /// Limits used for the traversal. |
| 216 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] |
| 217 | pub struct Limits { |
| 218 | pub max_depth: u32, |
| 219 | pub max_nodes: u32, |
| 220 | } |
| 221 | |
| 222 | impl Limits { |
| 223 | pub const HARD_MAX_DEPTH: u32 = 256; |
| 224 | pub const HARD_MAX_NODES: u32 = 4096; |
| 225 | } |
| 226 | |
| 227 | impl Default for Limits { |
| 228 | fn default() -> Self { |
| 229 | Self { |
| 230 | max_depth: 32, |
| 231 | max_nodes: 256, |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /// How the bundle was built. |
| 237 | #[derive(Clone, Debug, PartialEq, Eq, Serialize)] |
| 238 | pub struct ExplanationProvenance { |
| 239 | pub builder: String, |
| 240 | pub contract_format: String, |
| 241 | pub contract_version: u16, |
| 242 | pub producer: String, |
| 243 | /// sha256 of the canonical input graph JSON, lowercase hex. |
| 244 | pub input_digest: String, |
| 245 | pub target: String, |
| 246 | pub limits: Limits, |
| 247 | pub branch_scope: Option<String>, |
| 248 | /// Number of nodes visited out of the number in the input graph. |
| 249 | pub visited_nodes: u32, |
| 250 | pub graph_nodes: u32, |
| 251 | } |
| 252 | |
| 253 | /// The authoritative explanation. Deterministic for identical input and limits. |
| 254 | #[derive(Clone, Debug, PartialEq, Serialize)] |
| 255 | pub struct ExplanationBundle { |
| 256 | /// The conclusion is always the last step. |
| 257 | pub conclusion_step: u32, |
| 258 | pub steps: Vec<CausalStep>, |
| 259 | pub evidence: Vec<EvidenceRef>, |
| 260 | pub uncertainties: Vec<Uncertainty>, |
| 261 | pub contradictions: Vec<ContradictionRef>, |
| 262 | pub alternatives: Vec<Alternative>, |
| 263 | pub provenance: ExplanationProvenance, |
| 264 | /// sha256 of the canonical JSON of every field above, lowercase hex. |
| 265 | pub bundle_digest: String, |
| 266 | } |
| 267 | |
| 268 | impl ExplanationBundle { |
| 269 | pub fn conclusion(&self) -> &CausalStep { |
| 270 | &self.steps[(self.conclusion_step - 1) as usize] |
| 271 | } |
| 272 | |
| 273 | pub fn step(&self, index: u32) -> Option<&CausalStep> { |
| 274 | if index == 0 { |
| 275 | return None; |
| 276 | } |
| 277 | self.steps.get((index - 1) as usize) |
| 278 | } |
| 279 | |
| 280 | /// Canonical JSON of the bundle. |
| 281 | pub fn to_json(&self) -> String { |
| 282 | serde_json::to_string_pretty(self).expect("bundle serializes") |
| 283 | } |
| 284 | |
| 285 | /// Recompute the digest over the content (excluding the digest field). |
| 286 | pub fn compute_digest(&self) -> String { |
| 287 | #[derive(Serialize)] |
| 288 | struct Content<'a> { |
| 289 | conclusion_step: u32, |
| 290 | steps: &'a [CausalStep], |
| 291 | evidence: &'a [EvidenceRef], |
| 292 | uncertainties: &'a [Uncertainty], |
| 293 | contradictions: &'a [ContradictionRef], |
| 294 | alternatives: &'a [Alternative], |
| 295 | provenance: &'a ExplanationProvenance, |
| 296 | } |
| 297 | let c = Content { |
| 298 | conclusion_step: self.conclusion_step, |
| 299 | steps: &self.steps, |
| 300 | evidence: &self.evidence, |
| 301 | uncertainties: &self.uncertainties, |
| 302 | contradictions: &self.contradictions, |
| 303 | alternatives: &self.alternatives, |
| 304 | provenance: &self.provenance, |
| 305 | }; |
| 306 | hex(&aienos_crypto::sha256::hash( |
| 307 | &serde_json::to_vec(&c).expect("bundle serializes"), |
| 308 | )) |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | /// Lowercase hex. |
| 313 | pub fn hex(bytes: &[u8]) -> String { |
| 314 | const H: &[u8; 16] = b"0123456789abcdef"; |
| 315 | let mut s = String::with_capacity(bytes.len() * 2); |
| 316 | for b in bytes { |
| 317 | s.push(H[(b >> 4) as usize] as char); |
| 318 | s.push(H[(b & 15) as usize] as char); |
| 319 | } |
| 320 | s |
| 321 | } |