interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-explain / src / main.rs

209 lines · 7279 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//! `aienos-explain`: host-side operator command for grounded explanations.
17//!
18//! aienos-explain explain (--graph FILE | --cortex-journal FILE) --artifact ID
19//! [--summary | --why | --technical | --analogy] [--depth 0-4] [--evidence]
20//! [--uncertain] [--alternatives] [--step N] [--source N]
21//! [--audience general|operator|developer|systems-engineer|researcher]
22//! [--max-depth N] [--max-nodes N] [--json]
23//!
24//! Exit codes: 0 ok, 2 usage error, 10 + contract error code on explanation errors.
25
26use aienos_explain::adapters::{cortex_graph_for_record, store_from_journal};
27use aienos_explain::contract::{EvidenceGraph, ExplainError};
28use aienos_explain::{
29 build_bundle, render, Audience, ExplanationRequest, ExplanationSession, Limits, Mode,
30};
31use std::process::ExitCode;
32
33const USAGE: &str =
34 "usage: aienos-explain explain (--graph FILE | --cortex-journal FILE) --artifact ID \
35[--summary|--why|--technical|--analogy] [--depth 0-4] [--evidence] [--uncertain] [--alternatives] \
36[--step N] [--source N] [--audience general|operator|developer|systems-engineer|researcher] \
37[--max-depth N] [--max-nodes N] [--json]";
38
39struct Args {
40 graph: Option<String>,
41 journal: Option<String>,
42 artifact: Option<String>,
43 mode: Mode,
44 depth: Option<u8>,
45 evidence: bool,
46 uncertain: bool,
47 alternatives: bool,
48 step: Option<u32>,
49 source: Option<u32>,
50 audience: Audience,
51 limits: Limits,
52 json: bool,
53}
54
55fn parse(argv: &[String]) -> Result<Args, String> {
56 if argv.first().map(String::as_str) != Some("explain") {
57 return Err(USAGE.into());
58 }
59 let mut a = Args {
60 graph: None,
61 journal: None,
62 artifact: None,
63 mode: Mode::StepByStep,
64 depth: None,
65 evidence: false,
66 uncertain: false,
67 alternatives: false,
68 step: None,
69 source: None,
70 audience: Audience::Operator,
71 limits: Limits::default(),
72 json: false,
73 };
74 let mut i = 1;
75 let val = |i: &mut usize| -> Result<String, String> {
76 *i += 1;
77 argv.get(*i)
78 .cloned()
79 .ok_or_else(|| format!("missing value for {}", argv[*i - 1]))
80 };
81 let num = |s: String| -> Result<u32, String> {
82 s.parse::<u32>().map_err(|_| format!("not a number: {s}"))
83 };
84 while i < argv.len() {
85 match argv[i].as_str() {
86 "--graph" => a.graph = Some(val(&mut i)?),
87 "--cortex-journal" => a.journal = Some(val(&mut i)?),
88 "--artifact" => a.artifact = Some(val(&mut i)?),
89 "--summary" => a.mode = Mode::Summary,
90 "--why" => a.mode = Mode::StepByStep,
91 "--technical" => a.mode = Mode::Technical,
92 "--analogy" => a.mode = Mode::Analogy,
93 "--depth" => {
94 let d = num(val(&mut i)?)?;
95 if d > 4 {
96 return Err("--depth is 0 to 4".into());
97 }
98 a.depth = Some(d as u8);
99 }
100 "--evidence" => a.evidence = true,
101 "--uncertain" => a.uncertain = true,
102 "--alternatives" => a.alternatives = true,
103 "--step" => a.step = Some(num(val(&mut i)?)?),
104 "--source" => a.source = Some(num(val(&mut i)?)?),
105 "--audience" => {
106 let v = val(&mut i)?;
107 a.audience = Audience::parse(&v).ok_or_else(|| format!("unknown audience {v}"))?;
108 }
109 "--max-depth" => a.limits.max_depth = num(val(&mut i)?)?,
110 "--max-nodes" => a.limits.max_nodes = num(val(&mut i)?)?,
111 "--json" => a.json = true,
112 other => return Err(format!("unknown argument {other}\n{USAGE}")),
113 }
114 i += 1;
115 }
116 if a.graph.is_some() == a.journal.is_some() {
117 return Err(format!(
118 "give exactly one of --graph or --cortex-journal\n{USAGE}"
119 ));
120 }
121 if a.artifact.is_none() {
122 return Err(format!("--artifact is required\n{USAGE}"));
123 }
124 Ok(a)
125}
126
127fn parse_cortex_id(s: &str) -> Result<[u8; 16], ExplainError> {
128 let h = s.strip_prefix("cortex:").unwrap_or(s);
129 if h.len() != 32 || !h.bytes().all(|b| b.is_ascii_hexdigit()) {
130 return Err(ExplainError::TargetNotFound(format!(
131 "{s} is not a 32-hex-digit Cortex record id"
132 )));
133 }
134 let mut id = [0u8; 16];
135 for (k, b) in id.iter_mut().enumerate() {
136 *b = u8::from_str_radix(&h[2 * k..2 * k + 2], 16).expect("hex checked");
137 }
138 Ok(id)
139}
140
141fn run(a: Args) -> Result<String, ExplainError> {
142 let artifact = a.artifact.clone().expect("checked");
143 let (graph, target) = if let Some(path) = &a.graph {
144 let bytes =
145 std::fs::read(path).map_err(|e| ExplainError::BadFormat(format!("{path}: {e}")))?;
146 (EvidenceGraph::from_json(&bytes)?, artifact)
147 } else {
148 let path = a.journal.as_ref().expect("checked");
149 let bytes =
150 std::fs::read(path).map_err(|e| ExplainError::Journal(format!("{path}: {e}")))?;
151 let store = store_from_journal(&bytes)?;
152 let id = parse_cortex_id(&artifact)?;
153 let g = cortex_graph_for_record(&store, &id, a.limits)?;
154 (g, aienos_explain::adapters::cortex_node_id(&id))
155 };
156 let bundle = build_bundle(&graph, &target, a.limits)?;
157 if a.json {
158 return Ok(bundle.to_json() + "\n");
159 }
160 let session = ExplanationSession::new(bundle, a.audience);
161 if let Some(n) = a.step {
162 return session.step(n);
163 }
164 if let Some(n) = a.source {
165 return session.source(n);
166 }
167 let mut out = render(
168 session.bundle(),
169 &ExplanationRequest {
170 mode: a.mode,
171 level: a.depth,
172 audience: a.audience,
173 },
174 );
175 if a.evidence {
176 out.push_str("\nEvidence:\n");
177 out.push_str(&session.evidence());
178 }
179 if a.uncertain {
180 out.push_str("\nUncertain about:\n");
181 out.push_str(&session.uncertainties());
182 }
183 if a.alternatives {
184 out.push_str("\nAlternatives:\n");
185 out.push_str(&session.alternatives());
186 }
187 Ok(out)
188}
189
190fn main() -> ExitCode {
191 let argv: Vec<String> = std::env::args().skip(1).collect();
192 let args = match parse(&argv) {
193 Ok(a) => a,
194 Err(e) => {
195 eprintln!("{e}");
196 return ExitCode::from(2);
197 }
198 };
199 match run(args) {
200 Ok(text) => {
201 print!("{text}");
202 ExitCode::SUCCESS
203 }
204 Err(e) => {
205 eprintln!("error {e}");
206 ExitCode::from(10 + e.code() as u8)
207 }
208 }
209}