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/contract.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 / contract.rs` 478 lines ยท 16840 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 //! Evidence graph contract `aien.explain.evidence-graph` version 1. 17 //! 18 //! This is the language-neutral boundary of the explanation bridge. Any producer 19 //! (the aienos Cortex adapter, spark-rsi, a future omega `rx_cortex` exporter written 20 //! in C or Omega) emits this plain JSON document; the builder consumes it. The 21 //! canonical form is the JSON described in `docs/EXPLAIN_EVIDENCE_GRAPH_V1.md`: 22 //! string ids, small unsigned integer codes, per-mille integer confidence, and 23 //! producer-formatted decimal strings for measurements. No Rust enum layout and no 24 //! floating point value is part of the canonical format. 25 26 use serde::{Deserialize, Serialize}; 27 28 /// Format tag every v1 document carries. 29 pub const FORMAT: &str = "aien.explain.evidence-graph"; 30 /// Contract version understood by this crate. 31 pub const VERSION: u16 = 1; 32 /// Hard cap on nodes in one input document (adversarial input bound). 33 pub const MAX_GRAPH_NODES: usize = 65_536; 34 /// Hard cap on parent edges of one node. 35 pub const MAX_PARENTS_PER_NODE: usize = 1_024; 36 37 /// Explicit error codes. The numeric code is part of the contract (stable across 38 /// languages); the message is for humans. 39 #[derive(Clone, Debug, PartialEq, Eq)] 40 pub enum ExplainError { 41 /// 1: document is not valid JSON or misses required fields. 42 BadFormat(String), 43 /// 2: `format` or `version` is not one this crate understands. 44 UnsupportedVersion(String), 45 /// 3: an integer code (status, kind, relation) is outside the contract. 46 UnknownCode { field: &'static str, value: u32 }, 47 /// 4: two nodes share an id. 48 DuplicateNodeId(String), 49 /// 5: the artifact to explain is not in the graph. 50 TargetNotFound(String), 51 /// 6: the document exceeds a hard size cap. 52 GraphTooLarge(String), 53 /// 7: a clarification asked for a step that does not exist. 54 StepOutOfRange(u32), 55 /// 8: the record is not part of the evidence the branch depends on. 56 NotInBranchScope(String), 57 /// 9: the Cortex journal could not be read or failed its seal. 58 Journal(String), 59 /// 10: limits are zero or above the hard caps. 60 InvalidLimits(String), 61 } 62 63 impl ExplainError { 64 /// Stable numeric error code. 65 pub fn code(&self) -> u16 { 66 match self { 67 Self::BadFormat(_) => 1, 68 Self::UnsupportedVersion(_) => 2, 69 Self::UnknownCode { .. } => 3, 70 Self::DuplicateNodeId(_) => 4, 71 Self::TargetNotFound(_) => 5, 72 Self::GraphTooLarge(_) => 6, 73 Self::StepOutOfRange(_) => 7, 74 Self::NotInBranchScope(_) => 8, 75 Self::Journal(_) => 9, 76 Self::InvalidLimits(_) => 10, 77 } 78 } 79 } 80 81 impl core::fmt::Display for ExplainError { 82 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 83 let code = self.code(); 84 match self { 85 Self::BadFormat(m) => write!(f, "E{code} bad format: {m}"), 86 Self::UnsupportedVersion(m) => write!(f, "E{code} unsupported version: {m}"), 87 Self::UnknownCode { field, value } => { 88 write!(f, "E{code} unknown code {value} in field {field}") 89 } 90 Self::DuplicateNodeId(id) => write!(f, "E{code} duplicate node id {id}"), 91 Self::TargetNotFound(id) => write!(f, "E{code} artifact not found: {id}"), 92 Self::GraphTooLarge(m) => write!(f, "E{code} graph too large: {m}"), 93 Self::StepOutOfRange(n) => write!(f, "E{code} no step {n} in this explanation"), 94 Self::NotInBranchScope(m) => write!(f, "E{code} not in branch scope: {m}"), 95 Self::Journal(m) => write!(f, "E{code} Cortex journal: {m}"), 96 Self::InvalidLimits(m) => write!(f, "E{code} invalid limits: {m}"), 97 } 98 } 99 } 100 101 impl std::error::Error for ExplainError {} 102 103 /// Epistemic status code. 1..=6 are exactly the aienos Cortex `EpistemicStatus` 104 /// numbering; 0 means the producer could not classify the artifact. 105 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 106 pub enum Status { 107 Unclassified, 108 DirectObservation, 109 VerifiedFact, 110 Inference, 111 Hypothesis, 112 Contradiction, 113 OperatorDecision, 114 } 115 116 impl Status { 117 pub fn from_code(code: u8) -> Result { 118 Ok(match code { 119 0 => Self::Unclassified, 120 1 => Self::DirectObservation, 121 2 => Self::VerifiedFact, 122 3 => Self::Inference, 123 4 => Self::Hypothesis, 124 5 => Self::Contradiction, 125 6 => Self::OperatorDecision, 126 v => { 127 return Err(ExplainError::UnknownCode { 128 field: "status", 129 value: v as u32, 130 }) 131 } 132 }) 133 } 134 135 pub fn code(self) -> u8 { 136 match self { 137 Self::Unclassified => 0, 138 Self::DirectObservation => 1, 139 Self::VerifiedFact => 2, 140 Self::Inference => 3, 141 Self::Hypothesis => 4, 142 Self::Contradiction => 5, 143 Self::OperatorDecision => 6, 144 } 145 } 146 147 /// Grounding statuses end a backward walk (same set as Cortex `is_ground_truth`). 148 pub fn is_grounding(self) -> bool { 149 matches!( 150 self, 151 Self::DirectObservation | Self::VerifiedFact | Self::OperatorDecision 152 ) 153 } 154 155 /// Technical name (matches the Cortex enum variant names). 156 pub fn name(self) -> &'static str { 157 match self { 158 Self::Unclassified => "Unclassified", 159 Self::DirectObservation => "DirectObservation", 160 Self::VerifiedFact => "VerifiedFact", 161 Self::Inference => "Inference", 162 Self::Hypothesis => "Hypothesis", 163 Self::Contradiction => "Contradiction", 164 Self::OperatorDecision => "OperatorDecision", 165 } 166 } 167 } 168 169 /// What kind of artifact a node is. Codes are part of the contract. 170 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 171 pub enum NodeKind { 172 CortexRecord, 173 CapabilityMetric, 174 CapabilityAnalysis, 175 Diagnostic, 176 Hypothesis, 177 Prediction, 178 Falsification, 179 EvaluationReceipt, 180 PromotionState, 181 OperatorDecision, 182 AgentBranch, 183 Conclusion, 184 Alternative, 185 } 186 187 impl NodeKind { 188 pub fn from_code(code: u16) -> Result { 189 Ok(match code { 190 1 => Self::CortexRecord, 191 2 => Self::CapabilityMetric, 192 3 => Self::CapabilityAnalysis, 193 4 => Self::Diagnostic, 194 5 => Self::Hypothesis, 195 6 => Self::Prediction, 196 7 => Self::Falsification, 197 8 => Self::EvaluationReceipt, 198 9 => Self::PromotionState, 199 10 => Self::OperatorDecision, 200 11 => Self::AgentBranch, 201 12 => Self::Conclusion, 202 13 => Self::Alternative, 203 v => { 204 return Err(ExplainError::UnknownCode { 205 field: "kind", 206 value: v as u32, 207 }) 208 } 209 }) 210 } 211 212 pub fn code(self) -> u16 { 213 match self { 214 Self::CortexRecord => 1, 215 Self::CapabilityMetric => 2, 216 Self::CapabilityAnalysis => 3, 217 Self::Diagnostic => 4, 218 Self::Hypothesis => 5, 219 Self::Prediction => 6, 220 Self::Falsification => 7, 221 Self::EvaluationReceipt => 8, 222 Self::PromotionState => 9, 223 Self::OperatorDecision => 10, 224 Self::AgentBranch => 11, 225 Self::Conclusion => 12, 226 Self::Alternative => 13, 227 } 228 } 229 230 pub fn name(self) -> &'static str { 231 match self { 232 Self::CortexRecord => "CortexRecord", 233 Self::CapabilityMetric => "CapabilityMetric", 234 Self::CapabilityAnalysis => "CapabilityAnalysis", 235 Self::Diagnostic => "Diagnostic", 236 Self::Hypothesis => "Hypothesis", 237 Self::Prediction => "Prediction", 238 Self::Falsification => "Falsification", 239 Self::EvaluationReceipt => "EvaluationReceipt", 240 Self::PromotionState => "PromotionState", 241 Self::OperatorDecision => "OperatorDecision", 242 Self::AgentBranch => "AgentBranch", 243 Self::Conclusion => "Conclusion", 244 Self::Alternative => "Alternative", 245 } 246 } 247 } 248 249 /// How a node relates to one of its listed parents. Codes are part of the contract. 250 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 251 pub enum Relation { 252 /// The node rests on the parent (causal parent, derived from, input to). 253 SupportedBy, 254 /// The node is an evaluation or test result of the parent. 255 Evaluates, 256 /// The node is a component of the parent (prediction of a hypothesis). 257 PartOf, 258 /// The node records a conflict involving the parent (not support). 259 Contradicts, 260 /// The node is an explicitly recorded alternative to the parent (not support). 261 AlternativeTo, 262 /// A branch references the parent as evidence it depends on. 263 References, 264 } 265 266 impl Relation { 267 pub fn from_code(code: u16) -> Result { 268 Ok(match code { 269 1 => Self::SupportedBy, 270 2 => Self::Evaluates, 271 3 => Self::PartOf, 272 4 => Self::Contradicts, 273 5 => Self::AlternativeTo, 274 6 => Self::References, 275 v => { 276 return Err(ExplainError::UnknownCode { 277 field: "relation", 278 value: v as u32, 279 }) 280 } 281 }) 282 } 283 284 pub fn code(self) -> u16 { 285 match self { 286 Self::SupportedBy => 1, 287 Self::Evaluates => 2, 288 Self::PartOf => 3, 289 Self::Contradicts => 4, 290 Self::AlternativeTo => 5, 291 Self::References => 6, 292 } 293 } 294 295 /// Only these relations are followed backward as support. Contradiction and 296 /// alternative links are disclosed separately and never count as support. 297 pub fn is_support(self) -> bool { 298 matches!( 299 self, 300 Self::SupportedBy | Self::Evaluates | Self::PartOf | Self::References 301 ) 302 } 303 304 pub fn name(self) -> &'static str { 305 match self { 306 Self::SupportedBy => "SupportedBy", 307 Self::Evaluates => "Evaluates", 308 Self::PartOf => "PartOf", 309 Self::Contradicts => "Contradicts", 310 Self::AlternativeTo => "AlternativeTo", 311 Self::References => "References", 312 } 313 } 314 } 315 316 /// Where a node came from. 317 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 318 pub struct SourceRef { 319 /// Producing system, e.g. `aienos-cortex`, `aienos-agent-state`, `spark-rsi`. 320 pub system: String, 321 /// Artifact type in that system, e.g. `EpistemicRecord`, `HypothesisContract`. 322 pub artifact: String, 323 /// Identifier or provenance string inside that system. 324 pub reference: String, 325 /// Content digest or receipt digest as lowercase hex, when one exists. 326 #[serde(default, skip_serializing_if = "Option::is_none")] 327 pub digest: Option, 328 } 329 330 /// One named measurement. The value is a decimal string formatted by the producer. 331 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 332 pub struct Measurement { 333 pub name: String, 334 pub value: String, 335 #[serde(default)] 336 pub unit: String, 337 } 338 339 /// A parent edge as written in the document. 340 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 341 pub struct EdgeDoc { 342 pub to: String, 343 pub relation: u16, 344 } 345 346 /// A link the producer knows should exist but has no artifact for. 347 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 348 pub struct MissingDoc { 349 pub expected: String, 350 pub reason: String, 351 } 352 353 /// One evidence node as written in the document. 354 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 355 pub struct NodeDoc { 356 pub id: String, 357 pub kind: u16, 358 pub status: u8, 359 pub statement: String, 360 pub source: SourceRef, 361 /// Confidence in thousandths, only where the source system has the concept. 362 #[serde(default, skip_serializing_if = "Option::is_none")] 363 pub confidence_permille: Option, 364 /// Where the confidence number came from (declared, computed, recorded). 365 #[serde(default, skip_serializing_if = "Option::is_none")] 366 pub confidence_basis: Option, 367 /// Recording time from the source, informational only. Never used for ordering: 368 /// time order is not causal order. 369 #[serde(default, skip_serializing_if = "Option::is_none")] 370 pub recorded_at_utc: Option, 371 #[serde(default)] 372 pub parents: Vec, 373 #[serde(default)] 374 pub measurements: Vec, 375 #[serde(default)] 376 pub missing: Vec, 377 #[serde(default)] 378 pub notes: Vec, 379 } 380 381 /// Optional branch scope: which records a reasoning branch actually referenced. 382 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 383 pub struct ScopeDoc { 384 pub branch: String, 385 pub referenced: Vec, 386 } 387 388 /// The whole document. 389 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 390 pub struct EvidenceGraph { 391 pub format: String, 392 pub version: u16, 393 pub producer: String, 394 pub nodes: Vec, 395 /// Nodes whose parents the producer did not expand because of its own limits. 396 #[serde(default)] 397 pub truncated_at: Vec, 398 #[serde(default, skip_serializing_if = "Option::is_none")] 399 pub scope: Option, 400 } 401 402 impl EvidenceGraph { 403 /// Empty v1 document for a producer. 404 pub fn new(producer: impl Into) -> Self { 405 Self { 406 format: FORMAT.to_string(), 407 version: VERSION, 408 producer: producer.into(), 409 nodes: Vec::new(), 410 truncated_at: Vec::new(), 411 scope: None, 412 } 413 } 414 415 /// Parse and validate a JSON document. 416 pub fn from_json(bytes: &[u8]) -> Result { 417 let g: Self = 418 serde_json::from_slice(bytes).map_err(|e| ExplainError::BadFormat(e.to_string()))?; 419 g.validate()?; 420 Ok(g) 421 } 422 423 /// Canonical JSON bytes (field order fixed by the struct, node order as given). 424 pub fn to_json(&self) -> Vec { 425 serde_json::to_vec(self).expect("evidence graph serializes") 426 } 427 428 /// Check format tag, version, size caps, codes and id uniqueness. 429 pub fn validate(&self) -> Result<(), ExplainError> { 430 if self.format != FORMAT { 431 return Err(ExplainError::UnsupportedVersion(format!( 432 "format {:?}, expected {:?}", 433 self.format, FORMAT 434 ))); 435 } 436 if self.version != VERSION { 437 return Err(ExplainError::UnsupportedVersion(format!( 438 "version {}, expected {}", 439 self.version, VERSION 440 ))); 441 } 442 if self.nodes.len() > MAX_GRAPH_NODES { 443 return Err(ExplainError::GraphTooLarge(format!( 444 "{} nodes, cap {}", 445 self.nodes.len(), 446 MAX_GRAPH_NODES 447 ))); 448 } 449 let mut seen = std::collections::BTreeSet::new(); 450 for n in &self.nodes { 451 if !seen.insert(n.id.as_str()) { 452 return Err(ExplainError::DuplicateNodeId(n.id.clone())); 453 } 454 NodeKind::from_code(n.kind)?; 455 Status::from_code(n.status)?; 456 if n.parents.len() > MAX_PARENTS_PER_NODE { 457 return Err(ExplainError::GraphTooLarge(format!( 458 "node {} has {} parents, cap {}", 459 n.id, 460 n.parents.len(), 461 MAX_PARENTS_PER_NODE 462 ))); 463 } 464 for e in &n.parents { 465 Relation::from_code(e.relation)?; 466 } 467 if let Some(c) = n.confidence_permille { 468 if c > 1000 { 469 return Err(ExplainError::UnknownCode { 470 field: "confidence_permille", 471 value: c as u32, 472 }); 473 } 474 } 475 } 476 Ok(()) 477 } 478 }