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 / render.rs

550 lines · 17784 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//! Deterministic presentation of an [`ExplanationBundle`].
17//!
18//! Every function here takes the bundle by shared reference and returns text. The
19//! renderer can drop detail, but it can never change a step's status, add a step, or
20//! add evidence. Analogies come from a fixed catalog in this module, are always
21//! labelled as illustrations, and are always followed by the evidence itself.
22
23use crate::bundle::{CausalStep, ExplanationBundle, Role, Uncertainty, UncertaintyKind};
24use crate::contract::{NodeKind, Relation, Status};
25use std::fmt::Write;
26
27/// Presentation mode.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum Mode {
30 /// Conclusion, strongest reason, strongest evidence, material uncertainty.
31 Summary,
32 /// The path, step by step, grouped under role headings.
33 StepByStep,
34 /// Identifiers, statuses, digests, measurements, uncertainty codes.
35 Technical,
36 /// A familiar picture first (labelled), then the evidence path.
37 Analogy,
38}
39
40/// Who is reading. Explicit only; nothing is inferred about the reader.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum Audience {
43 General,
44 Operator,
45 Developer,
46 SystemsEngineer,
47 Researcher,
48}
49
50impl Audience {
51 pub fn parse(s: &str) -> Option<Self> {
52 Some(match s {
53 "general" => Self::General,
54 "operator" => Self::Operator,
55 "developer" => Self::Developer,
56 "systems-engineer" => Self::SystemsEngineer,
57 "researcher" => Self::Researcher,
58 _ => return None,
59 })
60 }
61
62 fn shows_ids(self) -> bool {
63 !matches!(self, Self::General)
64 }
65}
66
67/// Progressive disclosure: 0 conclusion, 1 principal reasons, 2 causal path,
68/// 3 evidence and measurements, 4 raw provenance references.
69pub const MAX_LEVEL: u8 = 4;
70
71/// What to show.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub struct ExplanationRequest {
74 pub mode: Mode,
75 /// Disclosure level 0..=4; `None` uses the mode's default.
76 pub level: Option<u8>,
77 pub audience: Audience,
78}
79
80impl ExplanationRequest {
81 pub fn new(mode: Mode) -> Self {
82 Self {
83 mode,
84 level: None,
85 audience: Audience::Operator,
86 }
87 }
88
89 pub fn effective_level(&self) -> u8 {
90 let d = match self.mode {
91 Mode::Summary => 1,
92 Mode::StepByStep | Mode::Analogy => 2,
93 Mode::Technical => 4,
94 };
95 self.level.unwrap_or(d).min(MAX_LEVEL)
96 }
97}
98
99/// Plain words for a status. A hypothesis is never described as verified or proven.
100pub fn status_words(s: Status) -> &'static str {
101 match s {
102 Status::DirectObservation => "observed",
103 Status::VerifiedFact => "checked fact",
104 Status::Inference => "inferred, not checked",
105 Status::Hypothesis => "hypothesis, not yet established",
106 Status::Contradiction => "conflict between records",
107 Status::OperatorDecision => "operator decision",
108 Status::Unclassified => "status unknown",
109 }
110}
111
112fn short(id: &str) -> String {
113 match id.split_once(':') {
114 Some((ns, rest)) if rest.chars().count() > 12 => {
115 format!("{ns}:{}", rest.chars().take(12).collect::<String>())
116 }
117 _ => id.to_string(),
118 }
119}
120
121fn step_line(s: &CausalStep, level: u8, aud: Audience) -> String {
122 let mut out = format!("{}. [{}] {}", s.index, status_words(s.status), s.statement);
123 if level >= 2 {
124 let strong: Vec<String> = s
125 .supported_by
126 .iter()
127 .filter(|l| l.relation != Relation::References)
128 .map(|l| l.step.to_string())
129 .collect();
130 let weak: Vec<String> = s
131 .supported_by
132 .iter()
133 .filter(|l| l.relation == Relation::References)
134 .map(|l| l.step.to_string())
135 .collect();
136 if !strong.is_empty() {
137 let _ = write!(out, " (rests on step {})", strong.join(", "));
138 }
139 if !weak.is_empty() {
140 let _ = write!(
141 out,
142 " (refers to step {}; a weak link, not a recorded one)",
143 weak.join(", ")
144 );
145 }
146 }
147 if aud.shows_ids() {
148 let _ = write!(out, " [{} {}]", s.source.system, short(&s.node_id));
149 } else {
150 let _ = write!(out, " [from {}]", s.source.system);
151 }
152 if s.branch_referenced {
153 out.push_str(" (referenced by the branch)");
154 }
155 out
156}
157
158fn measurements_line(s: &CausalStep) -> Option<String> {
159 if s.measurements.is_empty() {
160 return None;
161 }
162 let ms: Vec<String> = s
163 .measurements
164 .iter()
165 .map(|m| {
166 if m.unit.is_empty() {
167 format!("{}={}", m.name, m.value)
168 } else {
169 format!("{}={} {}", m.name, m.value, m.unit)
170 }
171 })
172 .collect();
173 Some(format!(" measurements: {}", ms.join(", ")))
174}
175
176fn severity(k: UncertaintyKind) -> u8 {
177 match k {
178 UncertaintyKind::Cycle => 0,
179 UncertaintyKind::ConflictingEvidence => 1,
180 UncertaintyKind::MissingParent => 2,
181 UncertaintyKind::MissingLink => 3,
182 UncertaintyKind::Unsupported => 4,
183 UncertaintyKind::HypothesisNotFalsified => 5,
184 UncertaintyKind::Unknown => 6,
185 UncertaintyKind::Truncated => 7,
186 UncertaintyKind::ProducerNote => 8,
187 UncertaintyKind::Inferred => 9,
188 }
189}
190
191fn material(b: &ExplanationBundle) -> Option<&Uncertainty> {
192 b.uncertainties
193 .iter()
194 .min_by_key(|u| (severity(u.kind), u.node_id.clone(), u.detail.clone()))
195}
196
197fn uncertainty_line(u: &Uncertainty) -> String {
198 format!("- {}: {}", u.kind.label(), u.detail)
199}
200
201/// The direct support of the conclusion with the best grounding.
202fn strongest_reason(b: &ExplanationBundle) -> Option<&CausalStep> {
203 let c = b.conclusion();
204 c.supported_by
205 .iter()
206 .filter(|l| l.relation != Relation::References)
207 .filter_map(|l| b.step(l.step))
208 .max_by_key(|s| {
209 (
210 s.grounding,
211 s.status != Status::Hypothesis,
212 s.confidence_permille.unwrap_or(0),
213 s.index,
214 )
215 })
216}
217
218/// The grounding step with evidence (digest or measurement) closest to the conclusion.
219fn strongest_evidence(b: &ExplanationBundle) -> Option<&CausalStep> {
220 b.evidence
221 .iter()
222 .filter_map(|e| b.step(e.step))
223 .filter(|s| s.grounding)
224 .min_by_key(|s| (s.depth, s.index))
225}
226
227fn header(b: &ExplanationBundle, aud: Audience) -> String {
228 let c = b.conclusion();
229 let mut s = format!("Conclusion: {} [{}]", c.statement, status_words(c.status));
230 if aud.shows_ids() {
231 let _ = write!(s, " ({})", short(&c.node_id));
232 }
233 s.push('\n');
234 s
235}
236
237fn render_summary(b: &ExplanationBundle, level: u8, aud: Audience) -> String {
238 let mut out = header(b, aud);
239 if level == 0 {
240 return out;
241 }
242 match strongest_reason(b) {
243 Some(r) => {
244 let _ = writeln!(
245 out,
246 "Main reason: {} [{}]",
247 r.statement,
248 status_words(r.status)
249 );
250 }
251 None => out.push_str(
252 "Main reason: none recorded. The system has no evidence supporting this conclusion.\n",
253 ),
254 }
255 match strongest_evidence(b) {
256 Some(e) => {
257 let _ = writeln!(
258 out,
259 "Strongest evidence: {} [{}]",
260 e.statement,
261 status_words(e.status)
262 );
263 if let Some(m) = measurements_line(e) {
264 let _ = writeln!(out, "{}", m.trim_start());
265 }
266 }
267 None => out.push_str("Strongest evidence: no observed or checked evidence on this path.\n"),
268 }
269 match material(b) {
270 Some(u) => {
271 let _ = writeln!(out, "Main uncertainty: {}", u.detail);
272 }
273 None => out.push_str("Main uncertainty: none recorded on this path.\n"),
274 }
275 if level >= 2 {
276 out.push('\n');
277 out.push_str(&render_steps(b, level, aud));
278 }
279 out
280}
281
282fn render_steps(b: &ExplanationBundle, level: u8, aud: Audience) -> String {
283 let mut out = String::new();
284 if level == 0 {
285 return header(b, aud);
286 }
287 let shown: Vec<&CausalStep> = if level == 1 {
288 let c = b.conclusion();
289 let mut v: Vec<&CausalStep> = c
290 .supported_by
291 .iter()
292 .filter_map(|l| b.step(l.step))
293 .collect();
294 v.push(c);
295 v
296 } else {
297 b.steps.iter().collect()
298 };
299 let mut last: Option<Role> = None;
300 for s in shown {
301 if last != Some(s.role) {
302 let _ = writeln!(out, "{}:", s.role.heading());
303 last = Some(s.role);
304 }
305 if s.index == b.conclusion_step {
306 let _ = writeln!(
307 out,
308 "{}. Therefore: {} [{}]",
309 s.index,
310 s.statement,
311 status_words(s.status)
312 );
313 } else {
314 let _ = writeln!(out, "{}", step_line(s, level, aud));
315 }
316 if level >= 3 {
317 if let Some(m) = measurements_line(s) {
318 let _ = writeln!(out, "{m}");
319 }
320 }
321 if level >= 4 {
322 let _ = writeln!(
323 out,
324 " source: {} {} {}{}",
325 s.source.system,
326 s.source.artifact,
327 s.source.reference,
328 s.source
329 .digest
330 .as_ref()
331 .map(|d| format!(" digest {d}"))
332 .unwrap_or_default()
333 );
334 }
335 }
336 out.push_str("Uncertainty:\n");
337 let visible: Vec<&Uncertainty> = b
338 .uncertainties
339 .iter()
340 .filter(|u| level >= 3 || u.kind != UncertaintyKind::Inferred)
341 .collect();
342 if visible.is_empty() {
343 out.push_str("- no gaps recorded on this path (inferred steps are marked as such)\n");
344 }
345 for u in visible {
346 let _ = writeln!(out, "{}", uncertainty_line(u));
347 }
348 if !b.contradictions.is_empty() {
349 out.push_str("Conflicts:\n");
350 for c in &b.contradictions {
351 let _ = writeln!(
352 out,
353 "- {} (involves {} step(s))",
354 c.statement,
355 c.involves.len()
356 );
357 }
358 }
359 if level >= 2 && !b.alternatives.is_empty() {
360 out.push_str("Other explanations the system recorded:\n");
361 for a in &b.alternatives {
362 let _ = writeln!(out, "- {}", a.statement);
363 }
364 }
365 out
366}
367
368fn render_technical(b: &ExplanationBundle, level: u8) -> String {
369 let mut out = String::new();
370 let c = b.conclusion();
371 let _ = writeln!(
372 out,
373 "explanation target={} producer={} builder={} contract={} v{}",
374 b.provenance.target,
375 b.provenance.producer,
376 b.provenance.builder,
377 b.provenance.contract_format,
378 b.provenance.contract_version
379 );
380 let _ = writeln!(
381 out,
382 "conclusion step={} id={} status={} kind={}",
383 c.index,
384 c.node_id,
385 c.status.name(),
386 c.kind.name()
387 );
388 if level == 0 {
389 return out;
390 }
391 for s in &b.steps {
392 let sup: Vec<String> = s
393 .supported_by
394 .iter()
395 .map(|l| format!("{}:{}", l.relation.name(), l.step))
396 .collect();
397 let _ = writeln!(
398 out,
399 "step {} id={} kind={} status={} role={:?} depth={} grounding={} supported_by=[{}]",
400 s.index,
401 s.node_id,
402 s.kind.name(),
403 s.status.name(),
404 s.role,
405 s.depth,
406 s.grounding,
407 sup.join(",")
408 );
409 let _ = writeln!(out, " statement: {}", s.statement);
410 if let Some(p) = s.confidence_permille {
411 let _ = writeln!(
412 out,
413 " confidence_permille={} basis={}",
414 p,
415 s.confidence_basis.as_deref().unwrap_or("unspecified")
416 );
417 }
418 if level >= 3 {
419 if let Some(m) = measurements_line(s) {
420 let _ = writeln!(out, " {}", m.trim_start());
421 }
422 }
423 if level >= 4 {
424 let _ = writeln!(
425 out,
426 " source system={} artifact={} reference={} digest={}",
427 s.source.system,
428 s.source.artifact,
429 s.source.reference,
430 s.source.digest.as_deref().unwrap_or("-")
431 );
432 if let Some(t) = s.recorded_at_utc {
433 let _ = writeln!(
434 out,
435 " recorded_at_utc={t} (informational, not used for order)"
436 );
437 }
438 }
439 for n in &s.notes {
440 let _ = writeln!(out, " note: {n}");
441 }
442 }
443 for u in &b.uncertainties {
444 let _ = writeln!(
445 out,
446 "uncertainty code={} kind={:?} node={} related={} detail={}",
447 u.kind.code(),
448 u.kind,
449 u.node_id,
450 u.related.as_deref().unwrap_or("-"),
451 u.detail
452 );
453 }
454 for c in &b.contradictions {
455 let _ = writeln!(
456 out,
457 "contradiction id={} involves=[{}] statement={}",
458 c.node_id,
459 c.involves.join(","),
460 c.statement
461 );
462 }
463 for a in &b.alternatives {
464 let _ = writeln!(
465 out,
466 "alternative id={} to={} statement={}",
467 a.node_id, a.alternative_to, a.statement
468 );
469 }
470 if level >= 4 {
471 let _ = writeln!(
472 out,
473 "input_digest={} bundle_digest={} visited={}/{} limits=depth:{},nodes:{}",
474 b.provenance.input_digest,
475 b.bundle_digest,
476 b.provenance.visited_nodes,
477 b.provenance.graph_nodes,
478 b.provenance.limits.max_depth,
479 b.provenance.limits.max_nodes
480 );
481 }
482 out
483}
484
485/// Fixed, presentation-only analogy catalog keyed by artifact kind and status.
486/// These sentences are illustrations. They are not stored anywhere, not part of the
487/// bundle, and not evidence for anything.
488pub fn analogy_for(kind: NodeKind, status: Status) -> Option<&'static str> {
489 Some(match (kind, status) {
490 (NodeKind::CapabilityAnalysis, _) => {
491 "The flagged part acts like a toll booth on a busy road: every request has to pass through it, so when it slows down, everything behind it queues up."
492 }
493 (NodeKind::Hypothesis, _) | (NodeKind::CortexRecord, Status::Hypothesis) => {
494 "A hypothesis is like a mechanic's first guess about a noise in the engine: useful for deciding what to check, but not a finding until the check is done."
495 }
496 (NodeKind::Falsification, _) => {
497 "A falsification test is like agreeing in advance which gauge reading would prove the repair did not work."
498 }
499 (NodeKind::EvaluationReceipt, _) => {
500 "The evaluation receipt is like an inspection sheet signed after a test drive: it records what was measured, not what was hoped."
501 }
502 (NodeKind::AgentBranch, _) => {
503 "A branch is like one line of investigation in a case file: it lists the documents it actually relied on, not every document in the archive."
504 }
505 (_, Status::Contradiction) => {
506 "A contradiction is like two witnesses whose accounts do not match: the system keeps both and flags the conflict instead of picking one quietly."
507 }
508 _ => return None,
509 })
510}
511
512fn render_analogy(b: &ExplanationBundle, level: u8, aud: Audience) -> String {
513 let mut out = String::new();
514 let pick = b
515 .steps
516 .iter()
517 .rev()
518 .find_map(|s| analogy_for(s.kind, s.status).map(|a| (s.index, a)));
519 match pick {
520 Some((i, a)) => {
521 let _ = writeln!(
522 out,
523 "Analogy (illustration only, not evidence; about step {i}):"
524 );
525 let _ = writeln!(out, " {a}");
526 }
527 None => out.push_str("Analogy: none available for this explanation.\n"),
528 }
529 out.push_str("\nThe evidence itself:\n");
530 out.push_str(&render_steps(b, level.max(1), aud));
531 out
532}
533
534/// Render the bundle. Pure function of (bundle, request).
535pub fn render(b: &ExplanationBundle, req: &ExplanationRequest) -> String {
536 let level = req.effective_level();
537 match req.mode {
538 Mode::Summary => render_summary(b, level, req.audience),
539 Mode::StepByStep => {
540 let mut s = header(b, req.audience);
541 if level > 0 {
542 s.push('\n');
543 s.push_str(&render_steps(b, level, req.audience));
544 }
545 s
546 }
547 Mode::Technical => render_technical(b, level),
548 Mode::Analogy => render_analogy(b, level, req.audience),
549 }
550}