interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / tools / aien-test / src / verify.rs

1079 lines · 42100 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//! `aien-test verify COMMIT`: the independent check of a local verification
17//! (ADR 0033 Decision 10, contracts C4 to C6, amendments A1 and A7).
18//!
19//! It reads the signed bundle the worker wrote, checks it against the public
20//! keys the repository committed at BASE (`.aien/verify.pub`, one hex key per
21//! line), recomputes the plan for BASE..COMMIT in the scope the bundle signs
22//! (`plan.scope`: full or changed) and compares the graph digest,
23//! checks that every `run` entry has its receipt on disk, judges the verdict
24//! with the planner's algebra, asks `crumb verify` about the tree at COMMIT
25//! (reported only; READY does not depend on it since DRA-97 retired Crumbs),
26//! and prints the fixed report block. Exit 0 only on MERGE ELIGIBILITY READY.
27
28use crate::bundle::{self, Expect};
29use crate::evidence::{self, utc_secs, Index, Store};
30use crate::manifest::CacheScope;
31use crate::plan::{self, Known, Plan, Request, Section};
32use crate::process;
33use crate::verdict::Verdict;
34use crate::worker::StateDir;
35use serde_json::Value;
36use std::collections::BTreeMap;
37use std::fs;
38use std::path::{Path, PathBuf};
39use std::process::Command;
40
41pub const KEYS_FILE: &str = ".aien/verify.pub";
42
43/// What the verifier was asked to do.
44#[derive(Debug, Clone)]
45pub struct Ask {
46 pub state: StateDir,
47 pub commit: String,
48 pub base: String,
49 pub repository: Option<String>,
50 pub release: bool,
51 pub operator: bool,
52 pub hardware_identity: String,
53 /// The crumb command; None skips the crumb check (status STALE).
54 pub crumb: Option<String>,
55 /// Keys to trust instead of `.aien/verify.pub` at BASE (tests).
56 pub keys_override: Option<Vec<String>>,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct Report {
61 pub lines: Vec<String>,
62 pub ready: bool,
63}
64
65/// Public keys from `.aien/verify.pub` at `commit`, one hex key per line,
66/// `#` comments and blank lines ignored.
67pub fn keys_at(root: &Path, commit: &str) -> Vec<String> {
68 let Some(bytes) = plan::show(root, commit, KEYS_FILE) else {
69 return Vec::new();
70 };
71 parse_keys(&String::from_utf8_lossy(&bytes))
72}
73
74pub fn parse_keys(text: &str) -> Vec<String> {
75 text.lines()
76 .map(|l| {
77 l.split('#')
78 .next()
79 .unwrap_or("")
80 .trim()
81 .to_ascii_lowercase()
82 })
83 .filter(|l| l.len() == 64 && l.bytes().all(|b| b.is_ascii_hexdigit()))
84 .collect()
85}
86
87/// A receipt the bundle points at, found in the commit's evidence directory.
88struct Found {
89 index: Index,
90}
91
92impl Found {
93 fn load(dir: &Path) -> Found {
94 Found {
95 index: Index::load(&Store::new(dir)),
96 }
97 }
98 fn get(&self, digest: &str) -> Option<&evidence::Stored> {
99 self.index.get(digest)
100 }
101}
102
103/// The sum of `volatile<pointer>` (a JSON pointer such as `/pool_wait_ms`)
104/// over the receipts; None when no receipt has it.
105fn sum_u64(index: &Index, digests: &[String], pointer: &str) -> Option<u64> {
106 let mut total = 0u64;
107 let mut any = false;
108 for d in digests {
109 if let Some(s) = index.get(d) {
110 if let Some(v) = s
111 .value
112 .get("volatile")
113 .and_then(|o| o.pointer(pointer))
114 .and_then(Value::as_u64)
115 {
116 total += v;
117 any = true;
118 }
119 }
120 }
121 any.then_some(total)
122}
123
124/// The file at the repository root that pins the crumb tool: one
125/// aien-architecture commit (sc#602).
126pub const CRUMB_LOCK: &str = "crumb.lock";
127
128/// The pinned commit in a `crumb.lock` text: exactly one 40-hex sha, surrounding
129/// whitespace ignored. None for anything else (a malformed lock pins nothing and
130/// the report says so).
131pub fn parse_crumb_lock(text: &str) -> Option<String> {
132 let pin = text.trim();
133 (pin.len() == 40 && pin.bytes().all(|b| b.is_ascii_hexdigit()))
134 .then(|| pin.to_ascii_lowercase())
135}
136
137/// Which crumb tool the readiness check ran, for the report's `Crumb tool:` line.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub enum CrumbTool {
140 /// Built only from the independently trusted base revision's pin/source.
141 Pinned { pin: String, path: PathBuf },
142 /// An absolute operator-selected command, never resolved in candidate CWD.
143 Unpinned(String),
144 /// The trusted tool could not be resolved or built.
145 Unavailable(String),
146}
147
148/// Resolve a checker from the trusted BASE, never the candidate being checked.
149/// BASE already supplies verification keys and pipeline policy. A proposed
150/// checker runs only in the untrusted gate; promoting it requires updating BASE.
151/// The separate cache namespace does not reuse legacy candidate-selected builds.
152pub fn crumb_tool_for(root: &Path, commit: &str, fallback: &str, cache: &Path) -> CrumbTool {
153 let pin = match plan::show(root, commit, CRUMB_LOCK) {
154 Some(bytes) => match parse_crumb_lock(&String::from_utf8_lossy(&bytes)) {
155 Some(pin) => pin,
156 None => {
157 return CrumbTool::Unavailable(format!(
158 "{CRUMB_LOCK} at {commit} is not one 40-hex commit"
159 ));
160 }
161 },
162 None if owns_crumb_tool(root, commit) => commit.to_ascii_lowercase(),
163 None => {
164 let command = if fallback == "crumb" {
165 "/usr/local/bin/crumb"
166 } else {
167 fallback
168 };
169 if !Path::new(command).is_absolute() {
170 return CrumbTool::Unavailable("crumb command must be absolute".into());
171 }
172 return CrumbTool::Unpinned(command.to_string());
173 }
174 };
175 let cache = cache.join("trusted-base-v1");
176 let built = cache.join(&pin).join("tools").join("crumb").join("crumb");
177 if built.is_file() {
178 return CrumbTool::Pinned { pin, path: built };
179 }
180 let Some(clone) = root.parent().map(|p| p.join("aien-architecture")) else {
181 return CrumbTool::Unavailable("repository root has no parent directory".into());
182 };
183 if !clone.join(".git").exists() {
184 return CrumbTool::Unavailable(format!(
185 "no trusted clone at {} to build crumb {pin} from",
186 clone.display()
187 ));
188 }
189 let dir = cache.join(&pin);
190 let _ = fs::remove_dir_all(&dir);
191 if let Err(e) = fs::create_dir_all(&dir) {
192 return CrumbTool::Unavailable(format!("cannot create {}: {e}", dir.display()));
193 }
194 let tar = dir.join("crumb-tool.tar");
195 let mut archive = Command::new("git");
196 archive
197 .args(["archive", "--format=tar", "-o"])
198 .arg(&tar)
199 .arg(&pin)
200 .arg("tools/crumb")
201 .current_dir(&clone)
202 .env("GIT_OPTIONAL_LOCKS", "0");
203 if let Err(e) = run_ok(&mut archive) {
204 return CrumbTool::Unavailable(format!("git archive {pin} tools/crumb: {e}"));
205 }
206 let mut untar = Command::new("tar");
207 untar.args(["-x", "-f"]).arg(&tar).arg("-C").arg(&dir);
208 if let Err(e) = run_ok(&mut untar) {
209 return CrumbTool::Unavailable(format!("tar: {e}"));
210 }
211 let _ = fs::remove_file(&tar);
212 let mut make = Command::new("make");
213 make.args(["-s", "-C"])
214 .arg(dir.join("tools").join("crumb"))
215 .arg("crumb");
216 if let Err(e) = run_ok(&mut make) {
217 return CrumbTool::Unavailable(format!("make crumb at {pin}: {e}"));
218 }
219 if built.is_file() {
220 CrumbTool::Pinned { pin, path: built }
221 } else {
222 CrumbTool::Unavailable(format!("make produced no {}", built.display()))
223 }
224}
225
226/// True only for the trusted architecture base revision carrying the tool.
227fn owns_crumb_tool(root: &Path, commit: &str) -> bool {
228 root.file_name().is_some_and(|n| n == "aien-architecture")
229 && plan::show(root, commit, "tools/crumb/crumb.c").is_some()
230}
231
232fn run_ok(cmd: &mut Command) -> Result<(), String> {
233 match process::output_gated(cmd) {
234 Ok(o) if o.status.success() => Ok(()),
235 Ok(o) => Err(String::from_utf8_lossy(&o.stderr)
236 .lines()
237 .last()
238 .unwrap_or("failed")
239 .trim()
240 .to_string()),
241 Err(e) => Err(e.to_string()),
242 }
243}
244
245/// `crumb verify` over the tree at COMMIT, in a temporary detached worktree.
246/// CURRENT only when crumb says OK; STALE otherwise, also when the command is
247/// unavailable (the tree is then not proven current).
248pub fn crumb_status(root: &Path, commit: &str, crumb: Option<&str>) -> (String, String) {
249 let Some(crumb) = crumb else {
250 return ("STALE".into(), "crumb check skipped".into());
251 };
252 let tmp = std::env::temp_dir().join(format!(
253 "aien-verify-{}-{}",
254 std::process::id(),
255 &commit[..12]
256 ));
257 let _ = fs::remove_dir_all(&tmp);
258 let mut add = Command::new("git");
259 add.args(["worktree", "add", "--detach", "--quiet"])
260 .arg(&tmp)
261 .arg(commit)
262 .current_dir(root)
263 .env("GIT_OPTIONAL_LOCKS", "0");
264 let out = match process::output_gated(&mut add) {
265 Ok(o) if o.status.success() => o,
266 Ok(o) => {
267 return (
268 "STALE".into(),
269 format!(
270 "cannot check out {commit}: {}",
271 String::from_utf8_lossy(&o.stderr).trim()
272 ),
273 );
274 }
275 Err(e) => return ("STALE".into(), format!("cannot run git: {e}")),
276 };
277 drop(out);
278 // The crumb tool decides, exactly as the CRUMB-VERIFY gate does. A repository with no crumbs at all
279 // (benchmarks, interplane) is "OK: 0 crumbs current" to the tool; calling it STALE here published every
280 // PASS head of those repos as BLOCKED/error (2026-10-16..19).
281 let result = {
282 let mut cmd = Command::new(crumb);
283 cmd.args(["verify", "."]).current_dir(&tmp);
284 match process::output_gated(&mut cmd) {
285 Ok(o) if o.status.success() => (
286 "CURRENT".to_string(),
287 String::from_utf8_lossy(&o.stdout)
288 .lines()
289 .next()
290 .unwrap_or("")
291 .trim()
292 .to_string(),
293 ),
294 Ok(o) => (
295 "STALE".to_string(),
296 format!(
297 "{} {}",
298 String::from_utf8_lossy(&o.stdout)
299 .lines()
300 .last()
301 .unwrap_or("")
302 .trim(),
303 String::from_utf8_lossy(&o.stderr)
304 .lines()
305 .last()
306 .unwrap_or("")
307 .trim()
308 )
309 .trim()
310 .to_string(),
311 ),
312 Err(e) => ("STALE".to_string(), format!("cannot run {crumb}: {e}")),
313 }
314 };
315 let mut rm = Command::new("git");
316 rm.args(["worktree", "remove", "--force"])
317 .arg(&tmp)
318 .current_dir(root);
319 let _ = process::output_gated(&mut rm);
320 let _ = fs::remove_dir_all(&tmp);
321 let mut prune = Command::new("git");
322 prune.args(["worktree", "prune"]).current_dir(root);
323 let _ = process::output_gated(&mut prune);
324 result
325}
326
327fn verdict_line(v: &str) -> &str {
328 match v {
329 "PASS" | "FAIL" | "NOT_RUN" => v,
330 "BLOCKED_HARDWARE" | "BLOCKED_OPERATOR" => "BLOCKED",
331 _ => "NOT_RUN",
332 }
333}
334
335/// Verify one commit's bundle against the repository at `root`.
336pub fn run(root: &Path, ask: &Ask) -> Report {
337 let repository = plan::repository_name(root, ask.repository.as_deref());
338 let repo = StateDir::repo_key(&repository);
339 let commit = ask.commit.to_ascii_lowercase();
340 let mut lines: Vec<String> = vec!["AIEN LOCAL VERIFICATION".to_string()];
341 let mut problems: Vec<String> = Vec::new();
342
343 // The commit and base must exist here.
344 let commit_ok = plan::resolve(root, &commit)
345 .map(|c| c == commit)
346 .unwrap_or(false);
347 // The worker's BASE rule: a commit already on the base line is checked
348 // against its first parent, any other against the base ref.
349 let base = if commit_ok {
350 plan::base_for(root, &ask.base, &commit).map(|(b, _)| b)
351 } else {
352 plan::resolve(root, &ask.base)
353 };
354 lines.push(format!("Repository: {repository}"));
355 lines.push(format!("Commit: {commit}"));
356 if !commit_ok {
357 problems.push(format!("commit {commit} is not in this repository"));
358 }
359 let base = match base {
360 Ok(b) => Some(b),
361 Err(e) => {
362 problems.push(e);
363 None
364 }
365 };
366
367 // The bundle.
368 let bundle_path = ask.state.bundle_path(&repo, &commit);
369 let bundle: Option<Value> = match fs::read(&bundle_path) {
370 Ok(b) => match serde_json::from_slice::<Value>(&b) {
371 Ok(v) => Some(v),
372 Err(e) => {
373 problems.push(format!("bundle is not JSON: {e}"));
374 None
375 }
376 },
377 Err(_) => {
378 problems.push(format!("no bundle at {}", bundle_path.display()));
379 None
380 }
381 };
382
383 // The plan, fresh, in the scope the bundle says the worker planned
384 // (`plan.scope`, signed: a forged scope fails the signature below).
385 let full = bundle
386 .as_ref()
387 .is_some_and(|b| bundle::scope_of(b) == bundle::SCOPE_FULL);
388 let plan: Option<Plan> = match (&base, commit_ok) {
389 (Some(b), true) => {
390 let mut req = Request::new(b, &commit);
391 req.operator = ask.operator;
392 req.full = full;
393 req.hardware_identity = ask.hardware_identity.clone();
394 match plan::compute(root, &req) {
395 Ok(p) => Some(p),
396 Err(e) => {
397 problems.push(format!("cannot plan: {e}"));
398 None
399 }
400 }
401 }
402 _ => None,
403 };
404
405 // Keys at BASE (A1, A7): pick the one the bundle names; otherwise UNKNOWN_KEY.
406 let keys = match (&ask.keys_override, &base) {
407 (Some(k), _) => k.clone(),
408 (None, Some(b)) => keys_at(root, b),
409 (None, None) => Vec::new(),
410 };
411 let required: Vec<String> = plan
412 .as_ref()
413 .map(|p| {
414 p.entries
415 .iter()
416 .filter(|e| e.required && e.section != Section::Blocked)
417 .map(|e| e.gate.clone())
418 .collect()
419 })
420 .unwrap_or_default();
421 let mut evidence_status = "INVALID".to_string();
422 let mut evidence_note = String::new();
423 let mut verified: Option<bundle::Verified> = None;
424 if let Some(b) = &bundle {
425 if keys.is_empty() {
426 evidence_note = format!("no trusted keys ({KEYS_FILE} at BASE is missing or empty)");
427 } else {
428 let named = b["signature"]["pubkey"]
429 .as_str()
430 .unwrap_or("")
431 .to_ascii_lowercase();
432 let key = keys
433 .iter()
434 .find(|k| **k == named)
435 .cloned()
436 .unwrap_or_else(|| keys[0].clone());
437 let expect = Expect {
438 repository: repository.clone(),
439 commit: commit.clone(),
440 pubkey_hex: key,
441 required: required.clone(),
442 require_full: false,
443 allow_host_only: false,
444 };
445 match bundle::verify(b, &expect) {
446 Ok(v) => {
447 evidence_status = "VERIFIED".to_string();
448 verified = Some(v);
449 }
450 Err(r) => evidence_note = r.to_string(),
451 }
452 }
453 }
454
455 // Bundle against plan: graph digest, receipts, release rule.
456 let mut known: BTreeMap<String, Known> = BTreeMap::new();
457 let mut executed: Vec<String> = Vec::new();
458 let mut cached: Vec<String> = Vec::new();
459 let mut failed: Vec<String> = Vec::new();
460 let mut blocked: Vec<String> = Vec::new();
461 let mut run_digests: Vec<String> = Vec::new();
462 let evidence_dir = ask.state.evidence(&repo, &commit);
463 let found = Found::load(&evidence_dir);
464 if let (Some(b), Some(p)) = (&bundle, &plan) {
465 if b["graph_digest"].as_str() != Some(p.graph_digest.as_str()) {
466 evidence_status = "INVALID".to_string();
467 let note = format!(
468 "GRAPH_MISMATCH: bundle graph {} but the plan for {}..{} gives {}",
469 b["graph_digest"].as_str().unwrap_or("?"),
470 &p.base[..12.min(p.base.len())],
471 &commit[..12],
472 p.graph_digest
473 );
474 if evidence_note.is_empty() {
475 evidence_note = note;
476 } else {
477 problems.push(note);
478 }
479 }
480 let by_gate: BTreeMap<String, &plan::Entry> =
481 p.entries.iter().map(|e| (e.gate.clone(), e)).collect();
482 for c in b["checks"].as_array().map(Vec::as_slice).unwrap_or(&[]) {
483 let gate = c["gate"].as_str().unwrap_or("").to_string();
484 let status = c["status"].as_str().unwrap_or("");
485 let v = Verdict::parse(c["verdict"].as_str().unwrap_or("")).unwrap_or(Verdict::NotRun);
486 let entry = by_gate.get(&gate);
487 let mut reason = String::new();
488 let mut verdict = v;
489 // The entry must name the check the plan computes for this gate
490 // at COMMIT; an entry for another check id never counts.
491 if let Some(e) = entry {
492 if c["check_id"].as_str() != Some(e.check_id.as_str()) {
493 verdict = Verdict::NotRun;
494 reason = "CHECK_ID_MISMATCH".into();
495 problems.push(format!(
496 "{gate}: CHECK_ID_MISMATCH bundle {} but the plan gives {}",
497 c["check_id"].as_str().unwrap_or("?"),
498 e.check_id
499 ));
500 }
501 }
502 // The manifest digest of this gate at COMMIT, for the receipt check.
503 let manifest_digest = p
504 .graph
505 .index_of(&gate)
506 .map(|i| p.graph.node(i).manifest.digest.clone());
507 match status {
508 "run" => {
509 let d = c["receipt"].as_str().unwrap_or("").to_string();
510 let receipt_manifest = |s: &evidence::Stored| {
511 s.value["core"]["manifest_digest"]
512 .as_str()
513 .map(str::to_string)
514 };
515 match found.get(&d) {
516 Some(s)
517 if s.gate() == gate
518 && s.commit() == commit
519 && s.verdict() == Some(v)
520 && manifest_digest.is_some()
521 && receipt_manifest(s) == manifest_digest =>
522 {
523 if reason.is_empty() {
524 executed.push(gate.clone());
525 run_digests.push(d.clone());
526 }
527 }
528 Some(s) if s.gate() == gate && receipt_manifest(s) != manifest_digest => {
529 verdict = Verdict::NotRun;
530 reason = "MANIFEST_MISMATCH".into();
531 problems.push(format!(
532 "{gate}: MANIFEST_MISMATCH receipt {d} was made from another manifest than the one at {}",
533 &commit[..12]
534 ));
535 }
536 Some(_) => {
537 verdict = Verdict::NotRun;
538 reason = "RECEIPT_MISMATCH".into();
539 problems.push(format!(
540 "{gate}: receipt {d} does not match the bundle entry"
541 ));
542 }
543 None => {
544 verdict = Verdict::NotRun;
545 reason = "RECEIPT_MISSING".into();
546 problems.push(format!(
547 "{gate}: receipt {d} is not in {}",
548 evidence_dir.display()
549 ));
550 }
551 }
552 if v == Verdict::Fail {
553 failed.push(gate.clone());
554 }
555 }
556 "cached" => {
557 let scope = entry.map(|e| e.cache_scope);
558 if ask.release && scope == Some(CacheScope::Hardware) {
559 verdict = Verdict::NotRun;
560 reason = "CACHE_SCOPE_HARDWARE_RELEASE".into();
561 problems.push(format!(
562 "{gate}: a cached hardware-scoped result cannot satisfy --release"
563 ));
564 } else {
565 cached.push(gate.clone());
566 }
567 if v == Verdict::Fail {
568 failed.push(gate.clone());
569 }
570 }
571 "blocked" => {
572 blocked.push(gate.clone());
573 if !matches!(v, Verdict::BlockedHardware | Verdict::BlockedOperator) {
574 verdict = Verdict::BlockedOperator;
575 }
576 reason = "BLOCKED".into();
577 }
578 _ => {
579 if v == Verdict::Fail {
580 failed.push(gate.clone());
581 }
582 reason = "NOT_RUN".into();
583 }
584 }
585 if entry.is_none() {
586 problems.push(format!("{gate}: in the bundle but not in the plan"));
587 }
588 known.insert(
589 gate,
590 Known {
591 verdict,
592 reason,
593 receipt: c["receipt"]
594 .as_str()
595 .or_else(|| c["resolution"]["resolved_from"].as_str())
596 .map(str::to_string),
597 },
598 );
599 }
600 }
601 let judged = plan.as_ref().map(|p| plan::judge(p, &known));
602
603 // The report body.
604 let changed = plan.as_ref().map(|p| p.changed.len()).unwrap_or(0);
605 let affected: Vec<String> = plan
606 .as_ref()
607 .map(|p| p.entries.iter().map(|e| e.gate.clone()).collect())
608 .unwrap_or_default();
609 let unmapped = plan
610 .as_ref()
611 .map(|p| p.unmapped.clone())
612 .unwrap_or_default();
613 lines.push(format!("Changed files: {changed}"));
614 lines.push(format!("Affected gates: {}", list(&affected)));
615 lines.push(format!("Executed gates: {}", list(&executed)));
616 lines.push(format!("Cached gates: {}", list(&cached)));
617 lines.push(format!("Failed gates: {}", list(&failed)));
618 lines.push(format!("Blocked gates: {}", list(&blocked)));
619 // No checker execution for missing/invalid evidence or blocked plans.
620 let (crumb, crumb_note, crumb_tool) = if !commit_ok
621 || evidence_status != "VERIFIED"
622 || !problems.is_empty()
623 || !blocked.is_empty()
624 || !judged.as_ref().is_some_and(|j| j.verdict == Verdict::Pass)
625 {
626 (
627 "STALE".to_string(),
628 "verification prerequisites not satisfied; checker not run".to_string(),
629 None,
630 )
631 } else {
632 match ask.crumb.as_deref() {
633 None => {
634 let (s, n) = crumb_status(root, &commit, None);
635 (s, n, None)
636 }
637 Some(fallback) => {
638 let cache = ask.state.root.join("crumb-tool");
639 match crumb_tool_for(
640 root,
641 base.as_deref().expect("verified plan has a base"),
642 fallback,
643 &cache,
644 ) {
645 CrumbTool::Pinned { pin, path } => {
646 let (s, n) = crumb_status(root, &commit, path.to_str());
647 (s, n, Some(format!("trusted-base {pin}")))
648 }
649 CrumbTool::Unpinned(cmd) => {
650 let (s, n) = crumb_status(root, &commit, Some(&cmd));
651 (
652 s,
653 n,
654 Some(format!("{cmd} (operator command; no lock at BASE)")),
655 )
656 }
657 CrumbTool::Unavailable(why) => (
658 "STALE".to_string(),
659 format!("pinned crumb tool unavailable: {why}"),
660 Some("pinned, not built".to_string()),
661 ),
662 }
663 }
664 }
665 };
666 lines.push(format!("Crumb status: {crumb}"));
667 if let Some(tool) = crumb_tool {
668 lines.push(format!("Crumb tool: {tool}"));
669 }
670 lines.push(format!("Evidence status: {evidence_status}"));
671 let hardware = match &plan {
672 Some(p)
673 if p.entries
674 .iter()
675 .any(|e| e.section == Section::NeedsGb10 || e.section == Section::NeedsSpark) =>
676 {
677 let hw: Vec<&plan::Entry> = p
678 .entries
679 .iter()
680 .filter(|e| e.section == Section::NeedsGb10 || e.section == Section::NeedsSpark)
681 .collect();
682 if hw.iter().all(|e| {
683 known
684 .get(&e.gate)
685 .map(|k| k.verdict == Verdict::Pass)
686 .unwrap_or(false)
687 }) {
688 "QUALIFIED"
689 } else {
690 "BLOCKED"
691 }
692 }
693 Some(_) => "NOT_REQUIRED",
694 None => "BLOCKED",
695 };
696 lines.push(format!("Hardware status: {hardware}"));
697 let final_verdict = match (&judged, evidence_status.as_str()) {
698 (Some(j), "VERIFIED") => verdict_line(j.verdict.as_str()).to_string(),
699 (Some(j), _) if j.verdict == Verdict::Fail => "FAIL".to_string(),
700 (Some(j), _)
701 if matches!(
702 j.verdict,
703 Verdict::BlockedHardware | Verdict::BlockedOperator
704 ) =>
705 {
706 "BLOCKED".to_string()
707 }
708 _ => "NOT_RUN".to_string(),
709 };
710 lines.push(format!("Final verdict: {final_verdict}"));
711 // A gate's batch-slot and target-dir waits fall inside its `duration_ms`;
712 // they are queue time, not test time.
713 let held = sum_u64(&found.index, &run_digests, "/batch_wait_ms").unwrap_or(0)
714 + sum_u64(&found.index, &run_digests, "/target_wait_ms").unwrap_or(0);
715 let queue = sum_u64(&found.index, &run_digests, "/pool_wait_ms").map(|q| q + held);
716 let test = sum_u64(&found.index, &run_digests, "/duration_ms").map(|t| t.saturating_sub(held));
717 let gpu_wait = sum_u64(&found.index, &run_digests, "/gpu_wait/waited_ms");
718 let total = bundle.as_ref().and_then(|b| {
719 let s = utc_secs(b["started_utc"].as_str()?)?;
720 let f = utc_secs(b["finished_utc"].as_str()?)?;
721 Some(f.saturating_sub(s) * 1000)
722 });
723 lines.push(format!("Queue time: {}", ms(queue)));
724 lines.push(format!("GPU lock wait: {}", ms(gpu_wait)));
725 lines.push("Build time: n/a".to_string());
726 lines.push(format!("Test time: {}", ms(test)));
727 lines.push(format!("Total time: {}", ms(total)));
728 // Crumb status is reported for history only: Crumbs are retired from the active workflow
729 // (DRA-97, 2026-11-07), so READY no longer requires crumbs CURRENT.
730 let ready = evidence_status == "VERIFIED"
731 && final_verdict == "PASS"
732 && unmapped.is_empty()
733 && blocked.is_empty()
734 && problems.is_empty()
735 && judged.as_ref().is_some_and(|j| j.verdict == Verdict::Pass)
736 && verified.as_ref().is_some_and(|v| v.verdict == "PASS");
737 lines.push(format!(
738 "MERGE ELIGIBILITY: {}",
739 if ready { "READY" } else { "BLOCKED" }
740 ));
741 if !evidence_note.is_empty() {
742 lines.push(format!("Evidence note: {evidence_note}"));
743 }
744 if !crumb_note.is_empty() {
745 lines.push(format!("Crumb note: {crumb_note}"));
746 }
747 if let Some(j) = &judged {
748 if !j.reason.is_empty() {
749 lines.push(format!("Verdict reason: {}", j.reason));
750 }
751 }
752 if !unmapped.is_empty() {
753 lines.push(format!("Unmapped: {}", unmapped.join(" ")));
754 }
755 for p in &problems {
756 lines.push(format!("Problem: {p}"));
757 }
758 lines.push(format!("Bundle: {}", bundle_path.display()));
759 Report { lines, ready }
760}
761
762fn list(v: &[String]) -> String {
763 if v.is_empty() {
764 "none".to_string()
765 } else {
766 format!("{} ({})", v.len(), v.join(" "))
767 }
768}
769
770fn ms(v: Option<u64>) -> String {
771 match v {
772 Some(ms) => format!("{ms} ms"),
773 None => "n/a".to_string(),
774 }
775}
776
777/// Where the trusted clone of `repository` is expected (`~/workspace/<repo>`).
778pub fn default_clone(repository: &str) -> Option<PathBuf> {
779 let home = std::env::var_os("HOME")?;
780 Some(
781 PathBuf::from(home)
782 .join("workspace")
783 .join(StateDir::repo_key(repository)),
784 )
785}
786
787#[cfg(test)]
788mod tests {
789 use super::*;
790
791 #[test]
792 fn crumb_lock_parses_one_sha_only() {
793 let sha = "107a2796c7b9ad6dff6f94a01d6567eb1ec9c995";
794 assert_eq!(
795 parse_crumb_lock(&format!(" {}\n", sha.to_uppercase())),
796 Some(sha.into())
797 );
798 assert_eq!(parse_crumb_lock("107a279\n"), None);
799 assert_eq!(parse_crumb_lock(&format!("{sha}\n{sha}\n")), None);
800 assert_eq!(
801 parse_crumb_lock("not a sha at all, forty characters long!"),
802 None
803 );
804 assert_eq!(parse_crumb_lock(""), None);
805 }
806
807 #[test]
808 fn commit_without_crumb_lock_uses_absolute_operator_command() {
809 let repo = crate::testutil::init_repo("crumb-unpinned", &[("README", "x\n", false)]);
810 let head = plan::resolve(repo.path(), "HEAD").unwrap();
811 let cache = crate::testutil::TempDir::new("crumb-cache");
812 assert_eq!(
813 crumb_tool_for(repo.path(), &head, "crumb", cache.path()),
814 CrumbTool::Unpinned("/usr/local/bin/crumb".into())
815 );
816 }
817
818 #[test]
819 fn malformed_crumb_lock_pins_nothing_and_says_so() {
820 let repo = crate::testutil::init_repo("crumb-badlock", &[(CRUMB_LOCK, "107a279\n", false)]);
821 let head = plan::resolve(repo.path(), "HEAD").unwrap();
822 let cache = crate::testutil::TempDir::new("crumb-cache");
823 match crumb_tool_for(repo.path(), &head, "crumb", cache.path()) {
824 CrumbTool::Unavailable(why) => assert!(why.contains("not one 40-hex commit"), "{why}"),
825 other => panic!("expected Unavailable, got {other:?}"),
826 }
827 }
828
829 /// A pinned tool is built from `<parent of root>/aien-architecture` at the
830 /// pin and reused from the cache: a fake sibling whose Makefile writes a
831 /// one-line `crumb` script stands in for the real tool.
832 #[test]
833 fn pinned_tool_is_built_from_the_sibling_clone_and_cached() {
834 let base = crate::testutil::TempDir::new("crumb-pinned");
835 let sib = base.path().join("aien-architecture");
836 let tool_dir = sib.join("tools").join("crumb");
837 fs::create_dir_all(&tool_dir).unwrap();
838 fs::write(
839 tool_dir.join("Makefile"),
840 "crumb:\n\tprintf '#!/bin/sh\\necho fake crumb\\n' > crumb && chmod +x crumb\n",
841 )
842 .unwrap();
843 crate::testutil::git(&sib, &["init", "-q"]);
844 crate::testutil::git(&sib, &["add", "."]);
845 crate::testutil::git(&sib, &["commit", "-q", "-m", "tool"]);
846 let pin = plan::resolve(&sib, "HEAD").unwrap();
847 let repo = base.path().join("repo");
848 fs::create_dir_all(&repo).unwrap();
849 fs::write(repo.join(CRUMB_LOCK), format!("{pin}\n")).unwrap();
850 crate::testutil::git(&repo, &["init", "-q"]);
851 crate::testutil::git(&repo, &["add", "."]);
852 crate::testutil::git(&repo, &["commit", "-q", "-m", "pin"]);
853 let head = plan::resolve(&repo, "HEAD").unwrap();
854 let cache = base.path().join("cache");
855 let built = cache
856 .join("trusted-base-v1")
857 .join(&pin)
858 .join("tools")
859 .join("crumb")
860 .join("crumb");
861 assert_eq!(
862 crumb_tool_for(&repo, &head, "crumb", &cache),
863 CrumbTool::Pinned {
864 pin: pin.clone(),
865 path: built.clone()
866 }
867 );
868 assert!(built.is_file());
869 // Second call: the sibling is gone, the cached build still answers.
870 fs::remove_dir_all(&sib).unwrap();
871 assert_eq!(
872 crumb_tool_for(&repo, &head, "crumb", &cache),
873 CrumbTool::Pinned { pin, path: built }
874 );
875 }
876
877 /// The trusted architecture base may supply its own checker source.
878 #[test]
879 fn architecture_uses_tool_from_trusted_base() {
880 let base = crate::testutil::TempDir::new("crumb-self");
881 let makefile =
882 "crumb:\n\tprintf '#!/bin/sh\\necho fake crumb\\n' > crumb && chmod +x crumb\n";
883 for name in ["aien-architecture", "other"] {
884 let tool_dir = base.path().join(name).join("tools").join("crumb");
885 fs::create_dir_all(&tool_dir).unwrap();
886 fs::write(tool_dir.join("Makefile"), makefile).unwrap();
887 fs::write(tool_dir.join("crumb.c"), "int main(void){return 0;}\n").unwrap();
888 let repo = base.path().join(name);
889 crate::testutil::git(&repo, &["init", "-q"]);
890 crate::testutil::git(&repo, &["add", "."]);
891 crate::testutil::git(&repo, &["commit", "-q", "-m", "tool"]);
892 }
893 let arch = base.path().join("aien-architecture");
894 let head = plan::resolve(&arch, "HEAD").unwrap();
895 let cache = base.path().join("cache");
896 let built = cache
897 .join("trusted-base-v1")
898 .join(&head)
899 .join("tools")
900 .join("crumb")
901 .join("crumb");
902 assert_eq!(
903 crumb_tool_for(&arch, &head, "crumb", &cache),
904 CrumbTool::Pinned {
905 pin: head.clone(),
906 path: built.clone()
907 }
908 );
909 assert!(built.is_file());
910 let other = base.path().join("other");
911 let head = plan::resolve(&other, "HEAD").unwrap();
912 assert_eq!(
913 crumb_tool_for(&other, &head, "crumb", &cache),
914 CrumbTool::Unpinned("/usr/local/bin/crumb".into())
915 );
916 }
917
918 #[test]
919 fn invalid_evidence_never_builds_or_executes_candidate_checker() {
920 let dir = crate::testutil::TempDir::new("untrusted-crumb");
921 let root = dir.path().join("aien-architecture");
922 fs::create_dir_all(root.join("tools/crumb")).unwrap();
923 let built_marker = dir.path().join("built");
924 let ran_marker = dir.path().join("ran");
925 fs::write(
926 root.join("tools/crumb/crumb.c"),
927 "int main(void){return 0;}\n",
928 )
929 .unwrap();
930 fs::write(
931 root.join("tools/crumb/Makefile"),
932 format!(
933 "crumb:\n\ttouch {}\n\tprintf '#!/bin/sh\\ntouch {}\\n' > crumb\n\tchmod +x crumb\n",
934 built_marker.display(), ran_marker.display()
935 ),
936 )
937 .unwrap();
938 crate::testutil::git(&root, &["init", "-q"]);
939 crate::testutil::git(&root, &["add", "."]);
940 crate::testutil::git(&root, &["commit", "-q", "-m", "candidate checker"]);
941 let head = plan::resolve(&root, "HEAD").unwrap();
942 let report = run(
943 &root,
944 &Ask {
945 state: StateDir::new(&dir.path().join("state")),
946 commit: head.clone(),
947 base: head.clone(),
948 repository: Some("github.com/t/aien-architecture".into()),
949 release: false,
950 operator: false,
951 hardware_identity: String::new(),
952 crumb: Some("crumb".into()),
953 keys_override: None,
954 },
955 );
956 assert!(!report.ready);
957 assert!(
958 !built_marker.exists(),
959 "candidate Makefile ran as trusted worker"
960 );
961 assert!(
962 !ran_marker.exists(),
963 "candidate checker ran as trusted worker"
964 );
965 // Negative control proves both marker payloads are live, not inert fixtures.
966 let tool = crumb_tool_for(&root, &head, "crumb", &dir.path().join("control"));
967 let CrumbTool::Pinned { path, .. } = tool else {
968 panic!("control tool unavailable")
969 };
970 assert!(built_marker.exists());
971 assert_eq!(crumb_status(&root, &head, path.to_str()).0, "CURRENT");
972 assert!(ran_marker.exists());
973 }
974
975 #[test]
976 fn trusted_base_ignores_candidate_lock_and_legacy_cached_checker() {
977 let repo = crate::testutil::init_repo("crumb-base", &[("README", "base\n", false)]);
978 let base = plan::resolve(repo.path(), "HEAD").unwrap();
979 let pin = "a".repeat(40);
980 fs::write(repo.path().join(CRUMB_LOCK), &pin).unwrap();
981 crate::testutil::git(repo.path(), &["add", "."]);
982 crate::testutil::git(repo.path(), &["commit", "-q", "-m", "candidate lock"]);
983 let cache = crate::testutil::TempDir::new("legacy-crumb-cache");
984 let legacy = cache.path().join(&pin).join("tools/crumb");
985 fs::create_dir_all(&legacy).unwrap();
986 fs::write(legacy.join("crumb"), "candidate controlled").unwrap();
987 assert_eq!(
988 crumb_tool_for(repo.path(), &base, "crumb", cache.path()),
989 CrumbTool::Unpinned("/usr/local/bin/crumb".into())
990 );
991 assert!(matches!(
992 crumb_tool_for(repo.path(), &base, "./crumb", cache.path()),
993 CrumbTool::Unavailable(_)
994 ));
995 }
996
997 #[test]
998 fn keys_parse() {
999 let a = "a".repeat(64);
1000 let text = format!(
1001 "# keys\n{a}\n\n {} # second\nnot-a-key\n",
1002 "B".repeat(64)
1003 );
1004 let k = parse_keys(&text);
1005 assert_eq!(k, vec![a, "b".repeat(64)]);
1006 }
1007
1008 #[test]
1009 fn verdict_lines() {
1010 assert_eq!(verdict_line("PASS"), "PASS");
1011 assert_eq!(verdict_line("BLOCKED_HARDWARE"), "BLOCKED");
1012 assert_eq!(verdict_line("MISSING_IMPLEMENTATION"), "NOT_RUN");
1013 assert_eq!(list(&[]), "none");
1014 assert_eq!(list(&["a".into(), "b".into()]), "2 (a b)");
1015 assert_eq!(ms(None), "n/a");
1016 assert_eq!(ms(Some(12)), "12 ms");
1017 }
1018
1019 #[test]
1020 fn missing_bundle_is_blocked_not_ready() {
1021 let repo = crate::testutil::init_repo("verify-empty", &[("README", "x\n", false)]);
1022 let head = plan::resolve(repo.path(), "HEAD").unwrap();
1023 let state = crate::testutil::TempDir::new("verify-state");
1024 let ask = Ask {
1025 state: StateDir::new(state.path()),
1026 commit: head.clone(),
1027 base: "HEAD".into(),
1028 repository: Some("github.com/t/r".into()),
1029 release: false,
1030 operator: false,
1031 hardware_identity: String::new(),
1032 crumb: None,
1033 keys_override: None,
1034 };
1035 let r = run(repo.path(), &ask);
1036 assert!(!r.ready);
1037 assert_eq!(r.lines[0], "AIEN LOCAL VERIFICATION");
1038 assert!(r.lines.iter().any(|l| l == "Evidence status: INVALID"));
1039 assert!(r.lines.iter().any(|l| l == "MERGE ELIGIBILITY: BLOCKED"));
1040 assert!(r
1041 .lines
1042 .iter()
1043 .any(|l| l.starts_with("Problem: no bundle at ")));
1044 }
1045
1046 /// A fake crumb on disk that prints `out` and exits `rc`.
1047 fn fake_crumb(dir: &Path, out: &str, rc: i32) -> String {
1048 use std::os::unix::fs::PermissionsExt;
1049 let p = dir.join("crumb");
1050 fs::write(&p, format!("#!/bin/sh\necho '{out}'\nexit {rc}\n")).unwrap();
1051 fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
1052 p.display().to_string()
1053 }
1054
1055 #[test]
1056 fn repo_without_crumbs_asks_the_tool() {
1057 // benchmarks and interplane have no .crumb at all; the gate's tool says OK, so readiness must too.
1058 let repo = crate::testutil::init_repo("verify-nocrumb", &[("README", "x\n", false)]);
1059 let head = plan::resolve(repo.path(), "HEAD").unwrap();
1060 let bin = crate::testutil::TempDir::new("verify-fake-crumb");
1061 let ok = fake_crumb(bin.path(), "crumb verify: OK: 0 crumbs current", 0);
1062 assert_eq!(
1063 crumb_status(repo.path(), &head, Some(&ok)),
1064 (
1065 "CURRENT".to_string(),
1066 "crumb verify: OK: 0 crumbs current".to_string()
1067 )
1068 );
1069 // The tool still has the last word: if it fails, readiness is STALE.
1070 let bad = fake_crumb(
1071 bin.path(),
1072 "crumb verify: FAIL: 1 of 1 crumbs stale; run: crumb compile",
1073 1,
1074 );
1075 assert_eq!(crumb_status(repo.path(), &head, Some(&bad)).0, "STALE");
1076 // No tool configured: still STALE (not proven current).
1077 assert_eq!(crumb_status(repo.path(), &head, None).0, "STALE");
1078 }
1079}