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

GitHub aien-dev/aien-sovereign-core-mv#167 (code only)

closed derived f9e4533119effe7f #167

Imported from GitHub aien-dev/aien-sovereign-core-mv#167 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base df5c32a7332b3b1334b6286a595cf3f4bf1ea09c · Head 037dd2e7c0b7c5f1bc3bca5feaf30906608780d8

Apply it

git checkout -b patch-f9e4533119effe7f df5c32a7332b3b1334b6286a595cf3f4bf1ea09c
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/f9e4533119effe7f.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
167
037dd2e7c0b7c5f1bc3bca5feaf30906608780d8
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":167,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/167","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:10Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/tools/aien-test/Cargo.toml b/tools/aien-test/Cargo.toml
index 90a07cb2..c6f55347 100644
--- a/tools/aien-test/Cargo.toml
+++ b/tools/aien-test/Cargo.toml
@@ -4,7 +4,7 @@ version.workspace = true
 edition.workspace = true
 license.workspace = true
 authors.workspace = true
-description = "AIEN-TEST Slice A: gate manifest parser, verdict derivation, immutable evidence receipts, host-pool serial runner (ADR 0028)"
+description = "AIEN-TEST Slices A and B: gate manifests, verdict derivation, immutable evidence receipts, dependency graph, resource pools with GPU locks, parallel runner and why (ADR 0028)"
 
 [dependencies]
 libc = "0.2"
diff --git a/tools/aien-test/mutations/aien-test.mutants b/tools/aien-test/mutations/aien-test.mutants
index edc1031e..c7c5d326 100644
--- a/tools/aien-test/mutations/aien-test.mutants
+++ b/tools/aien-test/mutations/aien-test.mutants
@@ -11,7 +11,7 @@ kill_leader_only	process.rs	s#libc::kill(-pid, sig);#libc::kill(pid, sig);#	time
 escape_hex_uppercase	evidence.rs	s#u{:04x}#u{:04X}#	canonical encoding escapes control characters with upper-case hex
 duplicate_key_allowed	manifest.rs	s#if entries.iter().any(|e| e.key == k) {#if false {#	a repeated top-level key is accepted
 unknown_key_allowed	manifest.rs	s#if !KNOWN.contains(&e.key.as_str()) {#if false {#	an unknown top-level key is ignored
-missing_exec_ignored	verdict.rs	s#if !exec_exists {#if false {#	a missing run.exec is not MISSING_IMPLEMENTATION
+missing_exec_ignored	verdict.rs	s#if !f.exec_exists {#if false {#	a missing run.exec is not MISSING_IMPLEMENTATION
 last_value_becomes_first	verdict.rs	s#compare(rule.op, vals\[vals.len() - 1\], &rule.value)#compare(rule.op, vals[0], \&rule.value)#	a repeated observation uses the first value, not the last
 evidence_inside_not_refused	runner.rs	s#let evidence_inside = resolve(&opts.evidence_dir).starts_with(resolve(root));#let evidence_inside = false;#	evidence may be written inside the tree under test
 operator_gate_not_blocked	verdict.rs	s#if m.requires.iter().any(|r| r == "operator") {#if false {#	a gate needing an operator runs anyway
@@ -19,3 +19,17 @@ timeout_checked_after_exit	verdict.rs	s#let (verdict, reason) = if f.timed_out {
 discover_ignores_gate_files	runner.rs	s#} else if ft.is_file() && name.ends_with(".gate") {#} else if false {#	the walk finds no .gate file, so a repository-wide parse check silently covers nothing
 discover_not_recursive	runner.rs	s#walk(&path, out);#let _ = \&path;#	the walk does not descend into directories, so gates under crates/ or tests/ are never parsed
 unknown_child_key_allowed	manifest.rs	s#if !allowed.contains(&k.as_str()) {#if false {#	a mistyped child key such as exce under run is not rejected
+dep_blocked_ignored	verdict.rs	s#return Some((v, format!("DEP_BLOCKED:{d}")));#return Some((Verdict::NotRun, format!("DEP_NOT_PASS:{d}")));#	a blocked dependency no longer passes its blocked verdict on
+dep_not_pass_ignored	verdict.rs	s#\.find(|d| dep_verdict(&f.deps, d) != Some(Verdict::Pass))#.find(|_d| false)#	a gate runs although a dependency is not PASS
+no_hardware_not_blocked	verdict.rs	s#"gb10" if !f.gb10_present => {#"gb10" if false => {#	a gb10 gate on a machine without the GPU is not BLOCKED_HARDWARE
+campaign_takes_the_mildest	verdict.rs	s#\.max_by_key(|v| v.exit_code())#.min_by_key(|v| v.exit_code())#	a campaign reports its mildest verdict instead of its worst
+cycle_not_detected	graph.rs	s#if order.len() != nodes.len() {#if false {#	a dependency cycle is accepted as a graph
+topo_order_takes_highest_first	graph.rs	s#ready\.pop_first()#ready.pop_last()#	the topological order is no longer lowest-id first and stable
+gb10_timeout_enforced	runner.rs	s#enforce_timeout: m.pool() != "gb10",#enforce_timeout: true,#	a gb10 job is killed at its timeout
+quiet_flag_ignored	resources.rs	s#if fs::symlink_metadata(flag).is_ok() {#if false {#	the quiet flag no longer stops a GPU job
+gpu_lock_shared	resources.rs	s#libc::LOCK_EX | libc::LOCK_NB#libc::LOCK_SH | libc::LOCK_NB#	two GPU jobs can hold the lock at once
+slot_released_twice	resources.rs	s#\*free += 1;#*free += 2;#	finishing a job frees two pool slots instead of one
+stale_receipt_counts_as_pass	why.rs	s#Evidence::Other(_) => State::Stale,#Evidence::Other(_) => State::Pass,#	why reports a receipt from another commit as PASS
+pass_over_failed_dependency	why.rs	s#let state = if own == State::Pass && !deps_pass {#let state = if false {#	why reports PASS although a dependency is not PASS
+gpu_release_not_gated	resources.rs	s#let _gate = crate::process::spawn_gate();#let _gate = ();#	the GPU guard closes its lock descriptors without the spawn gate, so a child between fork and exec can keep the lock held after the release
+spawn_not_gated	process.rs	s#let _gate = spawn_gate();#let _gate = ();#	child spawns no longer take the spawn gate, so a lock release does not wait for a child between fork and exec
diff --git a/tools/aien-test/src/cli.rs b/tools/aien-test/src/cli.rs
index 270ea2fe..c442aafe 100644
--- a/tools/aien-test/src/cli.rs
+++ b/tools/aien-test/src/cli.rs
@@ -1,30 +1,82 @@
-//! Argument parsing for `aien-test run GATE_FILE_OR_NAME [flags] [-- args]`.
-//! Hand-written; the surface is small (ADR 0028 Decision 1 and 8).
+//! Argument parsing for the `aien-test` commands (ADR 0028 Decision 1 and 8).
+//! Hand-written; the surface is small.
+//!
+//! ```text
+//! aien-test run GATE_FILE_OR_NAME [flags] [-- ARGS...]
+//! aien-test test ./... | gate:NAME [flags]
+//! aien-test why GATE_FILE_OR_NAME [flags]
+//! aien-test list [flags]
+//! ```
+//!
+//! `test changed`, `test crate:NAME`, `--host/--qemu/--gb10`, `--mutants`,
+//! `--release` and `--no-cache` come in later slices and are refused here.
 
+use crate::resources::{parse_jobs, JobsSpec};
 use std::path::PathBuf;
 
-pub const USAGE: &str =
-    "usage: aien-test run GATE_FILE_OR_NAME [--evidence-dir DIR] [--allow-dirty] [-- ARGS...]";
+pub const USAGE: &str = "usage:
+  aien-test run GATE_FILE_OR_NAME [flags] [-- ARGS...]
+  aien-test test ./... | gate:NAME [flags]
+  aien-test why GATE_FILE_OR_NAME [flags]
+  aien-test list [flags]
+flags: --evidence-dir DIR  --allow-dirty  --jobs host=N,qemu=M  --wait-gpu";
+
+/// Which gates `test` runs.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Selection {
+    /// `./...`: every gate in the repository.
+    All,
+    /// `gate:NAME`: that gate and everything it depends on.
+    Gate(String),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Command {
+    Run { gate: String },
+    Test(Selection),
+    Why { gate: String },
+    List,
+}
 
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct Cli {
-    pub gate: String,
+    pub command: Command,
     pub evidence_dir: Option<PathBuf>,
     pub allow_dirty: bool,
-    /// Arguments after `--`; they replace `run.args` (CR-061).
+    /// Arguments after `--`; they replace `run.args` (CR-061). `run` only.
     pub args: Option<Vec<String>>,
+    /// `--jobs host=N,qemu=M`: the pool sizes that were named.
+    pub jobs: JobsSpec,
+    /// `--wait-gpu`: wait for a held GPU lock instead of refusing.
+    pub wait_gpu: bool,
+}
+
+fn parse_selection(s: &str) -> Result<Selection, String> {
+    if s == "./..." {
+        return Ok(Selection::All);
+    }
+    match s.strip_prefix("gate:") {
+        Some(name) if !name.is_empty() => Ok(Selection::Gate(name.to_string())),
+        _ => Err(format!(
+            "unsupported test selection {s:?}: only ./... and gate:NAME exist so far"
+        )),
+    }
 }
 
 pub fn parse_args(argv: &[String]) -> Result<Cli, String> {
-    match argv.first().map(|s| s.as_str()) {
-        Some("run") => {}
-        Some(other) => return Err(format!("unknown command {other:?}")),
-        None => return Err("no command".to_string()),
+    let name = argv
+        .first()
+        .map(|s| s.as_str())
+        .ok_or_else(|| "no command".to_string())?;
+    if !["run", "test", "why", "list"].contains(&name) {
+        return Err(format!("unknown command {name:?}"));
     }
-    let mut gate: Option<String> = None;
+    let mut positional: Option<String> = None;
     let mut evidence_dir: Option<PathBuf> = None;
     let mut allow_dirty = false;
     let mut args: Option<Vec<String>> = None;
+    let mut jobs = JobsSpec::default();
+    let mut wait_gpu = false;
     let mut i = 1;
     while i < argv.len() {
         let a = argv[i].as_str();
@@ -37,26 +89,54 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> {
                 Some(v) => evidence_dir = Some(PathBuf::from(v)),
                 None => return Err("--evidence-dir needs a value".to_string()),
             }
+        } else if a == "--jobs" {
+            i += 1;
+            match argv.get(i) {
+                Some(v) => jobs = parse_jobs(v)?,
+                None => return Err("--jobs needs a value".to_string()),
+            }
         } else if a == "--allow-dirty" {
             allow_dirty = true;
+        } else if a == "--wait-gpu" {
+            wait_gpu = true;
         } else if a.starts_with('-') {
             return Err(format!("unknown argument {a:?}"));
-        } else if gate.is_none() {
-            gate = Some(a.to_string());
+        } else if positional.is_none() {
+            positional = Some(a.to_string());
         } else {
             return Err(format!("unexpected argument {a:?}"));
         }
         i += 1;
     }
-    match gate {
-        Some(gate) => Ok(Cli {
-            gate,
-            evidence_dir,
-            allow_dirty,
-            args,
-        }),
-        None => Err("missing GATE_FILE_OR_NAME".to_string()),
+    if args.is_some() && name != "run" {
+        return Err("-- ARGS only apply to the run command".to_string());
     }
+    let command = match name {
+        "run" => Command::Run {
+            gate: positional.ok_or("missing GATE_FILE_OR_NAME")?,
+        },
+        "why" => Command::Why {
+            gate: positional.ok_or("missing GATE_FILE_OR_NAME")?,
+        },
+        "test" => {
+            let selection = positional.ok_or("missing ./... or gate:NAME")?;
+            Command::Test(parse_selection(&selection)?)
+        }
+        _ => {
+            if let Some(p) = positional {
+                return Err(format!("unexpected argument {p:?}"));
+            }
+            Command::List
+        }
+    };
+    Ok(Cli {
+        command,
+        evidence_dir,
+        allow_dirty,
+        args,
+        jobs,
+        wait_gpu,
+    })
 }
 
 #[cfg(test)]
@@ -67,13 +147,22 @@ mod tests {
         a.iter().map(|s| s.to_string()).collect()
     }
 
+    fn run_gate(c: &Cli) -> &str {
+        match &c.command {
+            Command::Run { gate } => gate,
+            other => panic!("expected run, got {other:?}"),
+        }
+    }
+
     #[test]
     fn minimal() {
         let c = parse_args(&v(&["run", "G"])).unwrap();
-        assert_eq!(c.gate, "G");
+        assert_eq!(run_gate(&c), "G");
         assert!(!c.allow_dirty);
+        assert!(!c.wait_gpu);
         assert_eq!(c.args, None);
         assert_eq!(c.evidence_dir, None);
+        assert_eq!(c.jobs, JobsSpec::default());
     }
 
     #[test]
@@ -89,6 +178,7 @@ mod tests {
             "y",
         ]))
         .unwrap();
+        assert_eq!(run_gate(&c), "G");
         assert!(c.allow_dirty);
         assert_eq!(c.evidence_dir, Some(PathBuf::from("/e")));
         assert_eq!(c.args, Some(v(&["-x", "y"])));
@@ -100,10 +190,77 @@ mod tests {
         assert_eq!(c.args, Some(Vec::new()));
     }
 
+    #[test]
+    fn test_selections() {
+        let c = parse_args(&v(&["test", "./..."])).unwrap();
+        assert_eq!(c.command, Command::Test(Selection::All));
+        let c = parse_args(&v(&["test", "gate:G-1"])).unwrap();
+        assert_eq!(c.command, Command::Test(Selection::Gate("G-1".to_string())));
+    }
+
+    #[test]
+    fn unsupported_selections_are_refused() {
+        for bad in ["changed", "crate:x", "gate:", "G", "./", "."] {
+            assert!(parse_args(&v(&["test", bad])).is_err(), "{bad}");
+        }
+        assert!(parse_args(&v(&["test"])).is_err());
+    }
+
+    #[test]
+    fn jobs_and_wait_gpu() {
+        let c = parse_args(&v(&[
+            "test",
+            "./...",
+            "--jobs",
+            "host=3,qemu=2",
+            "--wait-gpu",
+        ]))
+        .unwrap();
+        assert_eq!(c.jobs.host, Some(3));
+        assert_eq!(c.jobs.qemu, Some(2));
+        assert!(c.wait_gpu);
+        let c = parse_args(&v(&["test", "./...", "--jobs", "qemu=1"])).unwrap();
+        assert_eq!(c.jobs.host, None);
+        assert_eq!(c.jobs.qemu, Some(1));
+    }
+
+    #[test]
+    fn bad_jobs_are_refused() {
+        for bad in ["host=0", "gb10=2", "host", "host=x", "disk=1", ""] {
+            assert!(
+                parse_args(&v(&["test", "./...", "--jobs", bad])).is_err(),
+                "{bad}"
+            );
+        }
+        assert!(parse_args(&v(&["test", "./...", "--jobs"])).is_err());
+    }
+
+    #[test]
+    fn why_and_list() {
+        let c = parse_args(&v(&["why", "G-1"])).unwrap();
+        assert_eq!(
+            c.command,
+            Command::Why {
+                gate: "G-1".to_string()
+            }
+        );
+        let c = parse_args(&v(&["list"])).unwrap();
+        assert_eq!(c.command, Command::List);
+        assert!(parse_args(&v(&["why"])).is_err());
+        assert!(parse_args(&v(&["list", "extra"])).is_err());
+    }
+
+    #[test]
+    fn override_args_only_for_run() {
+        assert!(parse_args(&v(&["test", "./...", "--", "x"])).is_err());
+        assert!(parse_args(&v(&["why", "G", "--", "x"])).is_err());
+    }
+
     #[test]
     fn errors() {
         assert!(parse_args(&[]).is_err());
         assert!(parse_args(&v(&["test", "G"])).is_err());
+        assert!(parse_args(&v(&["bogus", "G"])).is_err());
         assert!(parse_args(&v(&["run"])).is_err());
         assert!(parse_args(&v(&["run", "G", "H"])).is_err());
         assert!(parse_args(&v(&["run", "G", "--bogus"])).is_err());
diff --git a/tools/aien-test/src/evidence.rs b/tools/aien-test/src/evidence.rs
index f89a0b78..6c9827cd 100644
--- a/tools/aien-test/src/evidence.rs
+++ b/tools/aien-test/src/evidence.rs
@@ -1,6 +1,8 @@
 //! EvidenceReceiptV1 (ADR 0028 Decision 4): canonical JSON, sha256 digest,
-//! content-addressed stdout/stderr blobs, immutable write (never overwrite).
+//! content-addressed stdout/stderr blobs, immutable write (never overwrite),
+//! and read-back of the receipts already in a store.
 
+use crate::verdict::{DepFact, Verdict};
 use serde_json::{json, Value};
 use sha2::{Digest, Sha256};
 use std::fmt;
@@ -8,9 +10,16 @@ use std::fs;
 use std::io::{ErrorKind, Write};
 use std::os::unix::fs::OpenOptionsExt;
 use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::SystemTime;
 
 pub const SCHEMA: &str = "aien-test/EvidenceReceiptV1";
 
+/// Makes every blob temp file name unique inside one process, so gates
+/// running on different threads can store the same bytes (an empty stderr,
+/// say) at the same moment.
+static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
+
 pub fn sha256_hex(bytes: &[u8]) -> String {
     let mut h = Sha256::new();
     h.update(bytes);
@@ -161,7 +170,8 @@ impl Store {
             }
             return Ok(sha);
         }
-        let tmp = blobs.join(format!(".tmp-{sha}-{}", std::process::id()));
+        let n = TMP_COUNTER.fetch_add(1, Ordering::SeqCst);
+        let tmp = blobs.join(format!(".tmp-{sha}-{}-{n}", std::process::id()));
         {
             let mut f = fs::OpenOptions::new()
                 .write(true)
@@ -219,6 +229,143 @@ impl Store {
     }
 }
 
+/// A receipt read back from a store. `digest` comes from the file name and
+/// has been checked against the file's bytes.
+#[derive(Debug, Clone)]
+pub struct Stored {
+    pub digest: String,
+    pub value: Value,
+    modified: Option<SystemTime>,
+}
+
+impl Stored {
+    fn text(&self, section: &str, key: &str) -> &str {
+        self.value[section][key].as_str().unwrap_or("")
+    }
+
+    pub fn gate(&self) -> &str {
+        self.text("core", "gate")
+    }
+
+    pub fn commit(&self) -> &str {
+        self.text("core", "commit")
+    }
+
+    pub fn reason(&self) -> &str {
+        self.text("core", "reason")
+    }
+
+    pub fn finished_utc(&self) -> &str {
+        self.text("volatile", "finished_utc")
+    }
+
+    pub fn verdict(&self) -> Option<Verdict> {
+        Verdict::parse(self.text("core", "derived_verdict"))
+    }
+}
+
+fn is_sha256_hex(s: &str) -> bool {
+    s.len() == 64
+        && s.bytes()
+            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+}
+
+/// All verified receipts of one store, oldest first.
+#[derive(Debug, Clone, Default)]
+pub struct Index {
+    receipts: Vec<Stored>,
+}
+
+impl Index {
+    /// Read every `<digest>.json` in the store. A file is skipped, never
+    /// trusted, if its bytes do not hash to its name, it is not JSON, or it
+    /// does not carry the receipt schema. Order is by recorded finish time,
+    /// then by file modification time (receipts finished in the same second),
+    /// then by digest.
+    pub fn load(store: &Store) -> Index {
+        let mut receipts = Vec::new();
+        let rd = match fs::read_dir(store.dir()) {
+            Ok(r) => r,
+            Err(_) => return Index::default(),
+        };
+        for e in rd.flatten() {
+            let name = e.file_name().to_string_lossy().into_owned();
+            let digest = match name.strip_suffix(".json") {
+                Some(d) if is_sha256_hex(d) => d.to_string(),
+                _ => continue,
+            };
+            let bytes = match fs::read(e.path()) {
+                Ok(b) => b,
+                Err(_) => continue,
+            };
+            let body = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
+            if sha256_hex(body) != digest {
+                continue;
+            }
+            let value: Value = match serde_json::from_slice(body) {
+                Ok(v) => v,
+                Err(_) => continue,
+            };
+            if value["schema"] != SCHEMA {
+                continue;
+            }
+            let modified = e.metadata().and_then(|m| m.modified()).ok();
+            receipts.push(Stored {
+                digest,
+                value,
+                modified,
+            });
+        }
+        receipts.sort_by(|a, b| {
+            a.finished_utc()
+                .cmp(b.finished_utc())
+                .then_with(|| a.modified.cmp(&b.modified))
+                .then_with(|| a.digest.cmp(&b.digest))
+        });
+        Index { receipts }
+    }
+
+    pub fn len(&self) -> usize {
+        self.receipts.len()
+    }
+
+    pub fn is_empty(&self) -> bool {
+        self.receipts.is_empty()
+    }
+
+    /// The newest receipt of `gate`, for any commit.
+    pub fn latest(&self, gate: &str) -> Option<&Stored> {
+        self.receipts.iter().rev().find(|r| r.gate() == gate)
+    }
+
+    /// The newest receipt of `gate` made at exactly `commit`.
+    pub fn latest_at(&self, gate: &str, commit: &str) -> Option<&Stored> {
+        self.receipts
+            .iter()
+            .rev()
+            .find(|r| r.gate() == gate && r.commit() == commit)
+    }
+
+    /// What is known about each of `deps` at `commit`, in the given order. A
+    /// dependency without a receipt for this commit has no verdict.
+    pub fn dep_facts(&self, deps: &[String], commit: &str) -> Vec<DepFact> {
+        deps.iter()
+            .map(|d| match self.latest_at(d, commit) {
+                Some(r) => DepFact {
+                    gate: d.clone(),
+                    verdict: r.verdict(),
+                    receipt: Some(r.digest.clone()),
+                },
+                None => DepFact {
+                    gate: d.clone(),
+                    verdict: None,
+                    receipt: None,
+                },
+            })
+            .collect()
+    }
+}
+
 /// Format seconds since the Unix epoch as `YYYY-MM-DDTHH:MM:SSZ`.
 pub fn utc_string(secs: u64) -> String {
     let days = (secs / 86_400) as i64;
@@ -366,4 +513,115 @@ mod tests {
             other => panic!("expected collision, got {other:?}"),
         }
     }
+
+    fn receipt(gate: &str, commit: &str, verdict: &str, finished: &str) -> Value {
+        build_receipt(
+            json!({"gate": gate, "commit": commit, "derived_verdict": verdict, "reason": ""}),
+            json!({"finished_utc": finished}),
+        )
+    }
+
+    #[test]
+    fn index_finds_the_newest_receipt_per_gate_and_commit() {
+        let t = TempDir::new("ev6");
+        let store = Store::new(t.path());
+        let c1 = "1".repeat(40);
+        let c2 = "2".repeat(40);
+        store
+            .put_receipt(&receipt("G", &c1, "FAIL", "2026-10-02T01:00:00Z"))
+            .unwrap();
+        let (newer, _) = store
+            .put_receipt(&receipt("G", &c1, "PASS", "2026-10-02T02:00:00Z"))
+            .unwrap();
+        let (other_commit, _) = store
+            .put_receipt(&receipt("G", &c2, "FAIL", "2026-10-02T03:00:00Z"))
+            .unwrap();
+        store
+            .put_receipt(&receipt(
+                "H",
+                &c1,
+                "BLOCKED_HARDWARE",
+                "2026-10-02T01:30:00Z",
+            ))
+            .unwrap();
+        let ix = Index::load(&store);
+        assert_eq!(ix.len(), 4);
+        assert!(!ix.is_empty());
+        assert_eq!(ix.latest("G").unwrap().digest, other_commit);
+        let at = ix.latest_at("G", &c1).unwrap();
+        assert_eq!(at.digest, newer);
+        assert_eq!(at.verdict(), Some(Verdict::Pass));
+        assert_eq!((at.gate(), at.commit()), ("G", c1.as_str()));
+        assert!(ix.latest_at("G", &"3".repeat(40)).is_none());
+        assert!(ix.latest("nope").is_none());
+        let want = vec!["H".to_string(), "G".to_string(), "Z".to_string()];
+        let facts = ix.dep_facts(&want, &c1);
+        assert_eq!(facts.len(), 3);
+        assert_eq!(facts[0].verdict, Some(Verdict::BlockedHardware));
+        assert_eq!(facts[1].verdict, Some(Verdict::Pass));
+        assert_eq!(facts[1].receipt.as_deref(), Some(newer.as_str()));
+        assert_eq!(
+            facts[2],
+            DepFact {
+                gate: "Z".to_string(),
+                verdict: None,
+                receipt: None
+            }
+        );
+    }
+
+    #[test]
+    fn index_skips_files_that_are_not_trustworthy_receipts() {
+        let t = TempDir::new("ev7");
+        let store = Store::new(t.path());
+        let c = "1".repeat(40);
+        store
+            .put_receipt(&receipt("G", &c, "PASS", "2026-10-02T01:00:00Z"))
+            .unwrap();
+        // The file name does not match the bytes.
+        let forged = canonical(&receipt("G", &c, "FAIL", "2026-10-02T09:00:00Z")).unwrap();
+        fs::write(t.path().join(format!("{}.json", "0".repeat(64))), forged).unwrap();
+        // The right name, but not a receipt of this schema.
+        let alien = canonical(&json!({"schema": "something/else", "core": {"gate": "G"}})).unwrap();
+        fs::write(
+            t.path().join(format!("{}.json", sha256_hex(&alien))),
+            &alien,
+        )
+        .unwrap();
+        // Not JSON at all, with the right name.
+        let junk = b"not json".to_vec();
+        fs::write(t.path().join(format!("{}.json", sha256_hex(&junk))), &junk).unwrap();
+        fs::write(t.path().join("notes.txt"), b"hello").unwrap();
+        let ix = Index::load(&store);
+        assert_eq!(ix.len(), 1);
+        assert_eq!(ix.latest("G").unwrap().verdict(), Some(Verdict::Pass));
+        let missing = Store::new(&t.path().join("no-such-dir"));
+        assert!(Index::load(&missing).is_empty());
+    }
+
+    #[test]
+    fn identical_blobs_stored_at_the_same_moment_do_not_collide() {
+        let t = TempDir::new("ev8");
+        let store = Store::new(t.path());
+        let barrier = std::sync::Barrier::new(8);
+        std::thread::scope(|s| {
+            for _ in 0..8 {
+                s.spawn(|| {
+                    barrier.wait();
+                    for _ in 0..20 {
+                        store.put_blob(b"same bytes").expect("concurrent put_blob");
+                    }
+                });
+            }
+        });
+        let sha = sha256_hex(b"same bytes");
+        let blob = t.path().join("blobs").join(format!("{sha}.log"));
+        assert_eq!(fs::read(blob).unwrap(), b"same bytes");
+        let leftovers = fs::read_dir(t.path().join("blobs"))
+            .unwrap()
+            .flatten()
+            .filter(|e| e.file_name().to_string_lossy().starts_with(".tmp-"))
+            .count();
+        assert_eq!(leftovers, 0, "no temp file may be left behind");
+    }
 }
diff --git a/tools/aien-test/src/graph.rs b/tools/aien-test/src/graph.rs
new file mode 100644
index 00000000..f3647900
--- /dev/null
+++ b/tools/aien-test/src/graph.rs
@@ -0,0 +1,512 @@
+//! The gate dependency graph (ADR 0028 Decisions 3 and 6).
+//!
+//! `load` finds every `*.gate` file under a repository root (the D1
+//! convention, via `runner::discover`), parses each one strictly, and builds
+//! a DAG from the `depends_on` lists. A bad manifest, a repeated gate id, an
+//! unknown dependency and a cycle are all hard errors that name what is wrong.
+//! Nodes are sorted by gate id, so node numbers, the topological order and
+//! every query below are deterministic.
+
+use crate::manifest::{self, Manifest};
+use crate::runner::discover;
+use std::collections::{BTreeMap, BTreeSet};
+use std::fmt;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+#[derive(Debug, Clone)]
+pub struct Node {
+    pub id: String,
+    pub path: PathBuf,
+    pub manifest: Manifest,
+    /// Node numbers of the gates this gate depends on: sorted, no repeats.
+    pub deps: Vec<usize>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum GraphError {
+    Io(String),
+    BadManifest {
+        path: PathBuf,
+        message: String,
+    },
+    DuplicateGate {
+        id: String,
+        paths: Vec<PathBuf>,
+    },
+    UnknownDependency {
+        gate: String,
+        dep: String,
+    },
+    /// Gate ids around the cycle; the first id is repeated at the end.
+    Cycle(Vec<String>),
+}
+
+impl fmt::Display for GraphError {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            GraphError::Io(m) => f.write_str(m),
+            GraphError::BadManifest { path, message } => {
+                write!(f, "BAD_MANIFEST {}: {message}", path.display())
+            }
+            GraphError::DuplicateGate { id, paths } => {
+                let list: Vec<String> = paths.iter().map(|p| p.display().to_string()).collect();
+                write!(f, "duplicate gate id {id} in: {}", list.join(", "))
+            }
+            GraphError::UnknownDependency { gate, dep } => {
+                write!(f, "gate {gate} depends on unknown gate {dep}")
+            }
+            GraphError::Cycle(ids) => {
+                write!(f, "dependency cycle: {}", ids.join(" -> "))
+            }
+        }
+    }
+}
+
+#[derive(Debug, Clone)]
+pub struct Graph {
+    nodes: Vec<Node>,
+    index: BTreeMap<String, usize>,
+    dependents: Vec<Vec<usize>>,
+    order: Vec<usize>,
+}
+
+/// Discover, parse and link every gate under `root`.
+pub fn load(root: &Path) -> Result<Graph, GraphError> {
+    let mut entries = Vec::new();
+    for path in discover(root) {
+        let bytes = fs::read(&path)
+            .map_err(|e| GraphError::Io(format!("cannot read {}: {e}", path.display())))?;
+        let m = manifest::parse(&bytes).map_err(|e| GraphError::BadManifest {
+            path: path.clone(),
+            message: e.0,
+        })?;
+        entries.push((path, m));
+    }
+    build(entries)
+}
+
+/// Link already parsed manifests (path, manifest) into a graph.
+pub fn build(mut entries: Vec<(PathBuf, Manifest)>) -> Result<Graph, GraphError> {
+    entries.sort_by(|a, b| a.1.gate.cmp(&b.1.gate).then_with(|| a.0.cmp(&b.0)));
+    for pair in entries.windows(2) {
+        if pair[0].1.gate == pair[1].1.gate {
+            let id = pair[0].1.gate.clone();
+            let paths = entries
+                .iter()
+                .filter(|e| e.1.gate == id)
+                .map(|e| e.0.clone())
+                .collect();
+            return Err(GraphError::DuplicateGate { id, paths });
+        }
+    }
+    let index: BTreeMap<String, usize> = entries
+        .iter()
+        .enumerate()
+        .map(|(i, e)| (e.1.gate.clone(), i))
+        .collect();
+    let mut nodes: Vec<Node> = Vec::with_capacity(entries.len());
+    for (path, m) in entries {
+        let mut deps: BTreeSet<usize> = BTreeSet::new();
+        for d in &m.depends_on {
+            match index.get(d) {
+                Some(&i) => {
+                    deps.insert(i);
+                }
+                None => {
+                    return Err(GraphError::UnknownDependency {
+                        gate: m.gate.clone(),
+                        dep: d.clone(),
+                    })
+                }
+            }
+        }
+        nodes.push(Node {
+            id: m.gate.clone(),
+            path,
+            manifest: m,
+            deps: deps.into_iter().collect(),
+        });
+    }
+    let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];
+    for (i, n) in nodes.iter().enumerate() {
+        for &d in &n.deps {
+            dependents[d].push(i);
+        }
+    }
+    let order = topological_order(&nodes, &dependents);
+    if order.len() != nodes.len() {
+        let adj: Vec<&[usize]> = nodes.iter().map(|n| n.deps.as_slice()).collect();
+        let cycle = find_cycle(&adj).unwrap_or_default();
+        let ids = cycle.into_iter().map(|i| nodes[i].id.clone()).collect();
+        return Err(GraphError::Cycle(ids));
+    }
+    Ok(Graph {
+        nodes,
+        index,
+        dependents,
+        order,
+    })
+}
+
+/// Kahn's algorithm, always taking the lowest node number (lowest gate id)
+/// among the ready ones. Gates on a cycle never become ready, so the result
+/// is shorter than the node list exactly when a cycle exists.
+fn topological_order(nodes: &[Node], dependents: &[Vec<usize>]) -> Vec<usize> {
+    let mut waiting: Vec<usize> = nodes.iter().map(|n| n.deps.len()).collect();
+    let mut ready: BTreeSet<usize> = waiting
+        .iter()
+        .enumerate()
+        .filter(|(_, w)| **w == 0)
+        .map(|(i, _)| i)
+        .collect();
+    let mut order = Vec::with_capacity(nodes.len());
+    while let Some(i) = ready.pop_first() {
+        order.push(i);
+        for &j in &dependents[i] {
+            waiting[j] -= 1;
+            if waiting[j] == 0 {
+                ready.insert(j);
+            }
+        }
+    }
+    order
+}
+
+/// Depth-first search for one cycle. Returns the node numbers along it with
+/// the first one repeated at the end, or None if the graph is acyclic.
+fn find_cycle(deps: &[&[usize]]) -> Option<Vec<usize>> {
+    fn visit(
+        n: usize,
+        deps: &[&[usize]],
+        state: &mut [u8],
+        stack: &mut Vec<usize>,
+    ) -> Option<Vec<usize>> {
+        state[n] = 1;
+        stack.push(n);
+        for &d in deps[n] {
+            if state[d] == 1 {
+                let start = stack.iter().position(|&x| x == d).unwrap_or(0);
+                let mut cycle: Vec<usize> = stack[start..].to_vec();
+                cycle.push(d);
+                return Some(cycle);
+            }
+            if state[d] == 0 {
+                if let Some(c) = visit(d, deps, state, stack) {
+                    return Some(c);
+                }
+            }
+        }
+        stack.pop();
+        state[n] = 2;
+        None
+    }
+    let mut state = vec![0u8; deps.len()];
+    let mut stack = Vec::new();
+    (0..deps.len()).find_map(|n| {
+        if state[n] == 0 {
+            visit(n, deps, &mut state, &mut stack)
+        } else {
+            None
+        }
+    })
+}
+
+/// Every node reachable from `start` by one or more steps of `next`.
+fn reach<'a>(start: &[usize], next: impl Fn(usize) -> &'a [usize]) -> BTreeSet<usize> {
+    let mut seen = BTreeSet::new();
+    let mut stack: Vec<usize> = start.to_vec();
+    while let Some(n) = stack.pop() {
+        for &m in next(n) {
+            if seen.insert(m) {
+                stack.push(m);
+            }
+        }
+    }
+    seen
+}
+
+impl Graph {
+    pub fn len(&self) -> usize {
+        self.nodes.len()
+    }
+
+    pub fn is_empty(&self) -> bool {
+        self.nodes.is_empty()
+    }
+
+    pub fn nodes(&self) -> &[Node] {
+        &self.nodes
+    }
+
+    pub fn node(&self, i: usize) -> &Node {
+        &self.nodes[i]
+    }
+
+    pub fn index_of(&self, id: &str) -> Option<usize> {
+        self.index.get(id).copied()
+    }
+
+    /// Topological order: every gate comes after all the gates it depends on.
+    pub fn order(&self) -> &[usize] {
+        &self.order
+    }
+
+    /// Gates that list `i` directly in their `depends_on`.
+    pub fn direct_dependents(&self, i: usize) -> &[usize] {
+        &self.dependents[i]
+    }
+
+    /// All gates `i` rests on, directly or through other gates (not `i`).
+    pub fn transitive_deps(&self, i: usize) -> BTreeSet<usize> {
+        reach(&[i], |n| self.nodes[n].deps.as_slice())
+    }
+
+    /// All gates that rest on `i`, directly or through other gates (not `i`).
+    pub fn transitive_dependents(&self, i: usize) -> BTreeSet<usize> {
+        reach(&[i], |n| self.dependents[n].as_slice())
+    }
+
+    /// `targets` plus everything they depend on: the set to run to check them.
+    pub fn with_dependencies(&self, targets: &[usize]) -> BTreeSet<usize> {
+        let mut set = reach(targets, |n| self.nodes[n].deps.as_slice());
+        set.extend(targets.iter().copied());
+        set
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::testutil::{write_file, TempDir};
+
+    fn gate_text(id: &str, deps: &[&str]) -> String {
+        let dep_block = if deps.is_empty() {
+            String::new()
+        } else {
+            format!(
+                "depends_on:\n{}",
+                deps.iter()
+                    .map(|d| format!("  - {d}\n"))
+                    .collect::<String>()
+            )
+        };
+        format!(
+            "gate: {id}\nmanifest_version: 1\nowner: o\nrequires:\n  - host\nrun:\n  exec: x.sh\nexpects:\n  exit: 0\n  observe: []\n  verdict: PASS\ntimeout: 5s\n{dep_block}"
+        )
+    }
+
+    fn gate(id: &str, deps: &[&str]) -> (PathBuf, Manifest) {
+        (
+            PathBuf::from(format!("tests/{id}.gate")),
+            manifest::parse(gate_text(id, deps).as_bytes()).unwrap(),
+        )
+    }
+
+    fn graph(spec: &[(&str, &[&str])]) -> Result<Graph, GraphError> {
+        build(spec.iter().map(|(id, deps)| gate(id, deps)).collect())
+    }
+
+    fn ids(g: &Graph, set: &BTreeSet<usize>) -> Vec<String> {
+        set.iter().map(|&i| g.node(i).id.clone()).collect()
+    }
+
+    /// A -> B, A -> C, B -> D, C -> D (an arrow means "depends on").
+    fn diamond() -> Graph {
+        graph(&[("A", &["B", "C"]), ("B", &["D"]), ("C", &["D"]), ("D", &[])]).unwrap()
+    }
+
+    #[test]
+    fn order_puts_dependencies_first() {
+        let g = diamond();
+        let order: Vec<&str> = g.order().iter().map(|&i| g.node(i).id.as_str()).collect();
+        assert_eq!(order, vec!["D", "B", "C", "A"]);
+        let pos = |id: &str| order.iter().position(|x| *x == id).unwrap();
+        for n in g.nodes() {
+            for &d in &n.deps {
+                assert!(
+                    pos(&g.node(d).id) < pos(&n.id),
+                    "{} before {}",
+                    g.node(d).id,
+                    n.id
+                );
+            }
+        }
+    }
+
+    #[test]
+    fn order_is_independent_of_input_order() {
+        let a = graph(&[("X", &[]), ("Y", &["X"]), ("Z", &[])]).unwrap();
+        let b = graph(&[("Z", &[]), ("Y", &["X"]), ("X", &[])]).unwrap();
+        assert_eq!(a.order(), b.order());
+        let names: Vec<&str> = a.order().iter().map(|&i| a.node(i).id.as_str()).collect();
+        assert_eq!(names, vec!["X", "Y", "Z"]);
+    }
+
+    #[test]
+    fn unknown_dependency_names_both_gates() {
+        let e = graph(&[("A", &["GHOST"])]).unwrap_err();
+        assert_eq!(
+            e,
+            GraphError::UnknownDependency {
+                gate: "A".to_string(),
+                dep: "GHOST".to_string()
+            }
+        );
+        let msg = e.to_string();
+        assert!(msg.contains("A") && msg.contains("GHOST"), "{msg}");
+    }
+
+    #[test]
+    fn cycle_is_named() {
+        let e = graph(&[("A", &["B"]), ("B", &["C"]), ("C", &["A"])]).unwrap_err();
+        assert_eq!(
+            e,
+            GraphError::Cycle(vec![
+                "A".to_string(),
+                "B".to_string(),
+                "C".to_string(),
+                "A".to_string()
+            ])
+        );
+        assert_eq!(e.to_string(), "dependency cycle: A -> B -> C -> A");
+    }
+
+    #[test]
+    fn cycle_behind_an_acyclic_prefix_is_found() {
+        let e = graph(&[
+            ("A", &["B"]),
+            ("B", &[]),
+            ("C", &["D"]),
+            ("D", &["E"]),
+            ("E", &["D"]),
+        ])
+        .unwrap_err();
+        assert_eq!(e.to_string(), "dependency cycle: D -> E -> D");
+    }
+
+    #[test]
+    fn self_dependency_is_a_cycle() {
+        let e = graph(&[("A", &["A"])]).unwrap_err();
+        assert_eq!(e.to_string(), "dependency cycle: A -> A");
+    }
+
+    #[test]
+    fn duplicate_gate_ids_name_both_files() {
+        let mut entries = vec![gate("A", &[]), gate("B", &[])];
+        let mut second = gate("A", &[]);
+        second.0 = PathBuf::from("other/a.gate");
+        entries.push(second);
+        match build(entries).unwrap_err() {
+            GraphError::DuplicateGate { id, paths } => {
+                assert_eq!(id, "A");
+                assert_eq!(
+                    paths,
+                    vec![PathBuf::from("other/a.gate"), PathBuf::from("tests/A.gate")]
+                );
+            }
+            other => panic!("expected DuplicateGate, got {other:?}"),
+        }
+    }
+
+    #[test]
+    fn repeated_depends_on_entries_collapse() {
+        let g = graph(&[("A", &["B", "B"]), ("B", &[])]).unwrap();
+        let a = g.index_of("A").unwrap();
+        assert_eq!(g.node(a).deps.len(), 1);
+        assert_eq!(g.direct_dependents(g.index_of("B").unwrap()), &[a]);
+    }
+
+    #[test]
+    fn transitive_queries() {
+        let g = diamond();
+        let i = |id: &str| g.index_of(id).unwrap();
+        assert_eq!(ids(&g, &g.transitive_deps(i("A"))), vec!["B", "C", "D"]);
+        assert_eq!(ids(&g, &g.transitive_deps(i("B"))), vec!["D"]);
+        assert!(g.transitive_deps(i("D")).is_empty());
+        assert_eq!(
+            ids(&g, &g.transitive_dependents(i("D"))),
+            vec!["A", "B", "C"]
+        );
+        assert_eq!(ids(&g, &g.transitive_dependents(i("B"))), vec!["A"]);
+        assert!(g.transitive_dependents(i("A")).is_empty());
+        assert_eq!(ids(&g, &g.with_dependencies(&[i("B")])), vec!["B", "D"]);
+        assert_eq!(
+            ids(&g, &g.with_dependencies(&[i("B"), i("C")])),
+            vec!["B", "C", "D"]
+        );
+        assert_eq!(ids(&g, &g.with_dependencies(&[i("D")])), vec!["D"]);
+    }
+
+    #[test]
+    fn lookup_and_size() {
+        let g = diamond();
+        assert_eq!(g.len(), 4);
+        assert!(!g.is_empty());
+        assert_eq!(g.nodes().len(), 4);
+        assert_eq!(g.index_of("C").map(|i| g.node(i).id.as_str()), Some("C"));
+        assert_eq!(g.index_of("nope"), None);
+        let empty = build(Vec::new()).unwrap();
+        assert!(empty.is_empty() && empty.order().is_empty());
+    }
+
+    #[test]
+    fn load_finds_gates_and_skips_build_dirs() {
+        let t = TempDir::new("graph-load");
+        write_file(t.path(), "tests/a/a.gate", &gate_text("A", &["B"]), false);
+        write_file(t.path(), "tests/b/b.gate", &gate_text("B", &[]), false);
+        write_file(
+            t.path(),
+            "target/ghost.gate",
+            &gate_text("GHOST", &[]),
+            false,
+        );
+        let g = load(t.path()).unwrap();
+        assert_eq!(g.len(), 2);
+        let order: Vec<&str> = g.order().iter().map(|&i| g.node(i).id.as_str()).collect();
+        assert_eq!(order, vec!["B", "A"]);
+        assert!(g
+            .node(g.index_of("A").unwrap())
+            .path
+            .ends_with("tests/a/a.gate"));
+    }
+
+    #[test]
+    fn load_fails_closed_on_a_bad_manifest() {
+        let t = TempDir::new("graph-bad");
+        write_file(t.path(), "tests/bad.gate", "gate: X\nbogus: 1\n", false);
+        match load(t.path()).unwrap_err() {
+            GraphError::BadManifest { path, message } => {
+                assert!(path.ends_with("tests/bad.gate"));
+                assert!(!message.is_empty());
+            }
+            other => panic!("expected BadManifest, got {other:?}"),
+        }
+    }
+
+    #[test]
+    fn error_messages_are_plain() {
+        assert_eq!(
+            GraphError::DuplicateGate {
+                id: "A".to_string(),
+                paths: vec![PathBuf::from("x.gate"), PathBuf::from("y.gate")]
+            }
+            .to_string(),
+            "duplicate gate id A in: x.gate, y.gate"
+        );
+        assert_eq!(
+            GraphError::UnknownDependency {
+                gate: "A".to_string(),
+                dep: "B".to_string()
+            }
+            .to_string(),
+            "gate A depends on unknown gate B"
+        );
+        assert_eq!(GraphError::Io("boom".to_string()).to_string(), "boom");
+        let bad = GraphError::BadManifest {
+            path: PathBuf::from("p.gate"),
+            message: "line 1: nope".to_string(),
+        };
+        assert_eq!(bad.to_string(), "BAD_MANIFEST p.gate: line 1: nope");
+    }
+}
diff --git a/tools/aien-test/src/lib.rs b/tools/aien-test/src/lib.rs
index 955423af..c64d1ff0 100644
--- a/tools/aien-test/src/lib.rs
+++ b/tools/aien-test/src/lib.rs
@@ -1,15 +1,20 @@
-//! AIEN-TEST Slice A (ADR 0028): one gate, host pool, serial.
+//! AIEN-TEST (ADR 0028), Slices A and B: gate manifests, verdict derivation,
+//! immutable evidence receipts, and a runner for one gate or a whole graph of
+//! gates with resource pools, GPU locks, dependency handling and `why`.
 //!
 //! Tests report observations; this crate derives the verdict and writes an
 //! immutable, content-addressed receipt. See `manifest`, `verdict`,
-//! `evidence`, `process`, `runner`.
+//! `evidence`, `process`, `runner`, `graph`, `resources`, `why`.
 
 pub mod cli;
 pub mod evidence;
+pub mod graph;
 pub mod manifest;
 pub mod process;
+pub mod resources;
 pub mod runner;
 pub mod verdict;
+pub mod why;
 
 #[cfg(test)]
 pub mod testutil;
diff --git a/tools/aien-test/src/main.rs b/tools/aien-test/src/main.rs
index 6f1e775f..a0ff6fcd 100644
--- a/tools/aien-test/src/main.rs
+++ b/tools/aien-test/src/main.rs
@@ -1,11 +1,21 @@
-//! `aien-test run GATE_FILE_OR_NAME`: run one gate, print the verdict, exit
-//! non-zero unless PASS (0 PASS, 1 FAIL or BAD_MANIFEST, 2 NOT_RUN or usage,
-//! 3 BLOCKED_HARDWARE, 4 BLOCKED_OPERATOR, 5 MISSING_IMPLEMENTATION).
+//! aien-test: run gates and report verdicts (ADR 0028).
+//!
+//! - `run GATE`: run one gate. Exit 0 PASS, 1 FAIL or BAD_MANIFEST, 2 NOT_RUN
+//!   or usage, 3 BLOCKED_HARDWARE, 4 BLOCKED_OPERATOR, 5 MISSING_IMPLEMENTATION.
+//! - `test ./...` and `test gate:NAME`: run many gates, dependencies first,
+//!   with worker threads that honour the resource pools. The exit code is the
+//!   campaign verdict: any FAIL gives 1, else the worst of 2 to 5, else 0.
+//! - `why GATE`: explain a gate's state from the receipts already written.
+//! - `list`: list the gates and their dependencies.
 
-use aien_test::cli::{parse_args, USAGE};
+use aien_test::cli::{parse_args, Cli, Command, Selection, USAGE};
+use aien_test::evidence::{Index, Store};
+use aien_test::graph::{self, GraphError};
 use aien_test::runner::{self, Options, RunError};
 use aien_test::verdict::Verdict;
-use std::path::PathBuf;
+use aien_test::why;
+use std::collections::BTreeSet;
+use std::path::{Path, PathBuf};
 
 fn main() {
     std::process::exit(real_main());
@@ -28,43 +38,75 @@ fn real_main() -> i32 {
             return 2;
         }
     };
-    let manifest_path = match runner::locate_gate(&cwd, &cli.gate) {
+    match &cli.command {
+        Command::Run { gate } => cmd_run(&cli, gate, &cwd),
+        Command::Test(selection) => cmd_test(&cli, selection, &cwd),
+        Command::Why { gate } => cmd_why(&cli, gate, &cwd),
+        Command::List => cmd_list(&cwd),
+    }
+}
+
+/// Options for the real machine, with the command line applied.
+fn options(cli: &Cli, root: &Path) -> Result<Options, i32> {
+    let evidence_dir = match &cli.evidence_dir {
+        Some(d) => d.clone(),
+        None => match runner::default_evidence_dir(root) {
+            Some(d) => d,
+            None => {
+                eprintln!("aien-test: HOME is not set and no --evidence-dir given");
+                return Err(2);
+            }
+        },
+    };
+    let mut opts = Options::new(evidence_dir);
+    opts.allow_dirty = cli.allow_dirty;
+    opts.args_override = cli.args.clone();
+    opts.pool_sizes = opts.pool_sizes.with(cli.jobs);
+    opts.gpu.wait = cli.wait_gpu;
+    Ok(opts)
+}
+
+fn run_error(e: &RunError) -> i32 {
+    match e {
+        RunError::BadManifest(m) => println!("AIEN_TEST: BAD_MANIFEST {m}"),
+        RunError::Fatal(m) => println!("AIEN_TEST: FAIL {m}"),
+    }
+    1
+}
+
+fn graph_error(e: &GraphError) -> i32 {
+    match e {
+        // The message already starts with BAD_MANIFEST.
+        GraphError::BadManifest { .. } => println!("AIEN_TEST: {e}"),
+        _ => println!("AIEN_TEST: FAIL {e}"),
+    }
+    1
+}
+
+fn repo_root_or_report(cwd: &Path) -> Result<PathBuf, i32> {
+    runner::repo_root(cwd).map_err(|e| {
+        println!("AIEN_TEST: FAIL {e}");
+        1
+    })
+}
+
+fn cmd_run(cli: &Cli, gate: &str, cwd: &Path) -> i32 {
+    let manifest_path = match runner::locate_gate(cwd, gate) {
         Ok(p) => p,
         Err(e) => {
             println!("AIEN_TEST: BAD_MANIFEST {e}");
             return 1;
         }
     };
-    let parent = manifest_path.parent().unwrap_or(&cwd).to_path_buf();
-    let root = match runner::repo_root(&parent) {
+    let parent = manifest_path.parent().unwrap_or(cwd).to_path_buf();
+    let root = match repo_root_or_report(&parent) {
         Ok(r) => r,
-        Err(e) => {
-            println!("AIEN_TEST: FAIL {e}");
-            return 1;
-        }
+        Err(code) => return code,
     };
-    let evidence_dir = match cli.evidence_dir {
-        Some(d) => d,
-        None => match std::env::var_os("HOME") {
-            Some(h) => {
-                let name = root
-                    .file_name()
-                    .map(|n| n.to_string_lossy().into_owned())
-                    .unwrap_or_else(|| "repo".to_string());
-                PathBuf::from(h)
-                    .join("workspace")
-                    .join("evidence-out")
-                    .join(name)
-            }
-            None => {
-                eprintln!("aien-test: HOME is not set and no --evidence-dir given");
-                return 2;
-            }
-        },
+    let opts = match options(cli, &root) {
+        Ok(o) => o,
+        Err(code) => return code,
     };
-    let mut opts = Options::new(evidence_dir);
-    opts.allow_dirty = cli.allow_dirty;
-    opts.args_override = cli.args;
     match runner::run_gate(&root, &manifest_path, &opts) {
         Ok(o) => {
             if o.verdict == Verdict::NotRun && !o.reason.is_empty() {
@@ -80,13 +122,119 @@ fn real_main() -> i32 {
             }
             o.verdict.exit_code()
         }
-        Err(RunError::BadManifest(m)) => {
-            println!("AIEN_TEST: BAD_MANIFEST {m}");
-            1
+        Err(e) => run_error(&e),
+    }
+}
+
+fn cmd_test(cli: &Cli, selection: &Selection, cwd: &Path) -> i32 {
+    let root = match repo_root_or_report(cwd) {
+        Ok(r) => r,
+        Err(code) => return code,
+    };
+    let graph = match graph::load(&root) {
+        Ok(g) => g,
+        Err(e) => return graph_error(&e),
+    };
+    let chosen: BTreeSet<usize> = match selection {
+        Selection::All => (0..graph.len()).collect(),
+        Selection::Gate(name) => match graph.index_of(name) {
+            Some(i) => graph.with_dependencies(&[i]),
+            None => {
+                println!("AIEN_TEST: BAD_MANIFEST no gate named {name}");
+                return 1;
+            }
+        },
+    };
+    if chosen.is_empty() {
+        println!("AIEN_TEST: NOT_RUN no gates found under {}", root.display());
+        return 2;
+    }
+    let opts = match options(cli, &root) {
+        Ok(o) => o,
+        Err(code) => return code,
+    };
+    match runner::run_graph(&root, &graph, &chosen, &opts) {
+        Ok(campaign) => {
+            for (id, o) in &campaign.results {
+                if o.reason.is_empty() {
+                    println!("GATE {id} {}", o.verdict.as_str());
+                } else {
+                    println!("GATE {id} {} {}", o.verdict.as_str(), o.reason);
+                }
+                if let Some(p) = &o.receipt_path {
+                    println!("RECEIPT {}", p.display());
+                }
+            }
+            println!("AIEN_TEST: {}", campaign.verdict().as_str());
+            campaign.exit_code()
+        }
+        Err(e) => run_error(&e),
+    }
+}
+
+fn cmd_why(cli: &Cli, gate: &str, cwd: &Path) -> i32 {
+    let root = match repo_root_or_report(cwd) {
+        Ok(r) => r,
+        Err(code) => return code,
+    };
+    let graph = match graph::load(&root) {
+        Ok(g) => g,
+        Err(e) => return graph_error(&e),
+    };
+    let target = match why::resolve_target(&graph, cwd, gate) {
+        Ok(i) => i,
+        Err(e) => {
+            println!("AIEN_TEST: BAD_MANIFEST {e}");
+            return 1;
         }
-        Err(RunError::Fatal(m)) => {
-            println!("AIEN_TEST: FAIL {m}");
-            1
+    };
+    let opts = match options(cli, &root) {
+        Ok(o) => o,
+        Err(code) => return code,
+    };
+    let commit = match runner::head(&root) {
+        Ok(c) => c,
+        Err(e) => {
+            println!("AIEN_TEST: FAIL {e}");
+            return 1;
         }
+    };
+    let index = Index::load(&Store::new(&opts.evidence_dir));
+    for line in why::explain(&graph, &index, &commit, target) {
+        println!("{line}");
+    }
+    0
+}
+
+fn cmd_list(cwd: &Path) -> i32 {
+    let root = match repo_root_or_report(cwd) {
+        Ok(r) => r,
+        Err(code) => return code,
+    };
+    let graph = match graph::load(&root) {
+        Ok(g) => g,
+        Err(e) => return graph_error(&e),
+    };
+    for &i in graph.order() {
+        let node = graph.node(i);
+        let file = node.path.strip_prefix(&root).unwrap_or(&node.path);
+        let deps: Vec<&str> = node
+            .deps
+            .iter()
+            .map(|&d| graph.node(d).id.as_str())
+            .collect();
+        println!(
+            "{} pool={} depends_on={} file={}",
+            node.id,
+            node.manifest.pool(),
+            if deps.is_empty() {
+                "-".to_string()
+            } else {
+                deps.join(",")
+            },
+            file.display()
+        );
     }
+    println!("{} gates", graph.len());
+    0
 }
diff --git a/tools/aien-test/src/process.rs b/tools/aien-test/src/process.rs
index 823b714e..8984d5e1 100644
--- a/tools/aien-test/src/process.rs
+++ b/tools/aien-test/src/process.rs
@@ -6,8 +6,8 @@
 use std::io::{self, Read};
 use std::os::unix::process::{CommandExt, ExitStatusExt};
 use std::path::PathBuf;
-use std::process::{Child, Command, ExitStatus, Stdio};
-use std::sync::mpsc;
+use std::process::{Child, Command, ExitStatus, Output, Stdio};
+use std::sync::{mpsc, Mutex, MutexGuard};
 use std::thread;
 use std::time::{Duration, Instant};
 
@@ -18,6 +18,10 @@ pub struct RunSpec {
     pub timeout: Duration,
     /// Time between SIGTERM and SIGKILL (ADR 0028 Decision 6 says 10 s).
     pub kill_grace: Duration,
+    /// false: the job is never signalled and never timed out (ADR 0028
+    /// Decision 6, gb10 jobs). `timeout` is then advisory and only sets
+    /// `timeout_exceeded`.
+    pub enforce_timeout: bool,
 }
 
 #[derive(Debug)]
@@ -27,7 +31,10 @@ pub struct RunOutput {
     pub signal: Option<i32>,
     pub stdout: Vec<u8>,
     pub stderr: Vec<u8>,
+    /// The runner killed the job because `timeout` passed.
     pub timed_out: bool,
+    /// The job ran longer than `timeout`, whether or not it was killed.
+    pub timeout_exceeded: bool,
     pub duration_ms: u64,
 }
 
@@ -46,6 +53,51 @@ fn lost() -> io::Error {
     io::Error::other("waiter thread lost")
 }
 
+/// Held around every child spawn in this crate and around the release of the
+/// GPU lock descriptors (`resources::GpuGuard`), so the two never overlap.
+///
+/// Why: `flock(2)` locks belong to the open file description, and a child
+/// created by fork (or clone) gets its own copy of the descriptor table. The
+/// lock descriptor is close-on-exec (std opens every file with `O_CLOEXEC`,
+/// `library/std/src/sys/fs/unix.rs` `open_c`), so a child drops its copy at
+/// exec. Between the fork and the exec the child still holds the file
+/// description, and the lock looks held even after the parent closed its own
+/// descriptor. With several threads (parallel gates in the runner, parallel
+/// unit tests) another thread's child can sit in that window exactly when a
+/// guard is dropped, and the next `acquire_gpu` is refused with `LockHeld`
+/// although nobody holds the lock (an intermittent failure of
+/// `gpu_lock_is_exclusive_and_released_on_drop` was seen once on the forge).
+///
+/// `Command::spawn` returns only after the child has exec'd or failed (std
+/// reads the close-on-exec pipe until it closes, `process/unix/unix.rs`
+/// `spawn`). So a spawn made under this mutex has no child left in the window
+/// when the mutex is released, and a guard released under it can only be
+/// copied by spawns that start after the descriptors are already closed.
+/// A genuinely held lock is still refused at once (ADR 0028 Decision 6).
+static SPAWN_GATE: Mutex<()> = Mutex::new(());
+
+/// Take the spawn gate. It is a leaf lock: nothing else is taken while it is
+/// held, and a poisoned gate is still usable (it guards no data).
+pub(crate) fn spawn_gate() -> MutexGuard<'static, ()> {
+    SPAWN_GATE.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+/// `cmd.spawn()` under the spawn gate. Every child this crate starts goes
+/// through here (or `output_gated`), never through a bare `Command::spawn`.
+pub(crate) fn spawn_gated(cmd: &mut Command) -> io::Result<Child> {
+    let _gate = spawn_gate();
+    cmd.spawn()
+}
+
+/// `cmd.output()` with the spawn under the spawn gate. Waiting for the output
+/// happens after the gate is released, so a slow child never blocks others.
+pub(crate) fn output_gated(cmd: &mut Command) -> io::Result<Output> {
+    cmd.stdin(Stdio::null())
+        .stdout(Stdio::piped())
+        .stderr(Stdio::piped());
+    spawn_gated(cmd)?.wait_with_output()
+}
+
 fn spawn(spec: &RunSpec) -> io::Result<Child> {
     let mut cmd = Command::new(&spec.program);
     cmd.args(&spec.args)
@@ -56,7 +108,8 @@ fn spawn(spec: &RunSpec) -> io::Result<Child> {
         .process_group(0);
     let mut attempt = 0;
     loop {
-        match cmd.spawn() {
+        // One attempt per gate hold: the retry sleep below is outside it.
+        match spawn_gated(&mut cmd) {
             Ok(c) => return Ok(c),
             // A script written moments ago can be briefly busy when another
             // thread forks while its write descriptor is still open.
@@ -104,16 +157,24 @@ pub fn run(spec: &RunSpec) -> io::Result<RunOutput> {
     });
 
     let mut timed_out = false;
-    let waited: Waited = match rx.recv_timeout(spec.timeout) {
-        Ok(r) => r,
-        Err(mpsc::RecvTimeoutError::Timeout) => {
-            timed_out = true;
-            terminate(pid, &rx, spec.kill_grace)?
+    let waited: Waited = if !spec.enforce_timeout {
+        // Advisory timeout: wait for the job however long it takes.
+        rx.recv().map_err(|_| lost())?
+    } else {
+        match rx.recv_timeout(spec.timeout) {
+            Ok(r) => r,
+            Err(mpsc::RecvTimeoutError::Timeout) => {
+                timed_out = true;
+                terminate(pid, &rx, spec.kill_grace)?
+            }
+            Err(mpsc::RecvTimeoutError::Disconnected) => return Err(lost()),
         }
-        Err(mpsc::RecvTimeoutError::Disconnected) => return Err(lost()),
     };
-    // Whatever the leader did, nothing it started may outlive the run.
-    signal_group(pid, libc::SIGKILL);
+    let waited_for = start.elapsed();
+    if spec.enforce_timeout {
+        // Whatever the leader did, nothing it started may outlive the run.
+        signal_group(pid, libc::SIGKILL);
+    }
     let status = waited?;
     let stdout = h_out.join().unwrap_or_default();
     let stderr = h_err.join().unwrap_or_default();
@@ -123,6 +184,7 @@ pub fn run(spec: &RunSpec) -> io::Result<RunOutput> {
         stdout,
         stderr,
         timed_out,
+        timeout_exceeded: timed_out || (!spec.enforce_timeout && waited_for > spec.timeout),
         duration_ms: start.elapsed().as_millis() as u64,
     })
 }
@@ -138,6 +200,7 @@ mod tests {
             cwd: PathBuf::from("/"),
             timeout: Duration::from_millis(timeout_ms),
             kill_grace: Duration::from_millis(500),
+            enforce_timeout: true,
         }
     }
 
@@ -183,6 +246,28 @@ mod tests {
         assert!(o.duration_ms < 10_000, "took {} ms", o.duration_ms);
     }
 
+    #[test]
+    fn advisory_timeout_never_signals_the_job() {
+        let mut s = sh("sleep 1; echo done", 100);
+        s.enforce_timeout = false;
+        let o = run(&s).unwrap();
+        assert_eq!(o.exit_code, Some(0));
+        assert_eq!(o.stdout, b"done\n");
+        assert!(!o.timed_out, "an advisory timeout must not kill");
+        assert!(o.timeout_exceeded, "but it must be reported");
+        assert!(o.signal.is_none());
+    }
+
+    #[test]
+    fn within_the_limit_is_not_exceeded() {
+        let mut s = sh("echo quick", 20_000);
+        s.enforce_timeout = false;
+        let o = run(&s).unwrap();
+        assert!(!o.timeout_exceeded);
+        let o = run(&sh("echo quick", 20_000)).unwrap();
+        assert!(!o.timeout_exceeded && !o.timed_out);
+    }
+
     #[test]
     fn missing_program_is_an_error() {
         let mut s = sh("true", 1000);
diff --git a/tools/aien-test/src/resources.rs b/tools/aien-test/src/resources.rs
new file mode 100644
index 00000000..fe55128e
--- /dev/null
+++ b/tools/aien-test/src/resources.rs
@@ -0,0 +1,795 @@
+//! Resource pools and the GPU locks (ADR 0028 Decision 6).
+//!
+//! Three counting semaphores inside one runner process: `host` (default size
+//! is the CPU count), `qemu` (default `min(4, host / 2)`, a guess that is
+//! overridable with `--jobs`), and `gb10` (fixed at 1). A job holds exactly
+//! one pool slot. Semaphores are plain `Mutex` plus `Condvar`; a `Permit` is
+//! an RAII guard that returns its slot when dropped.
+//!
+//! Deadlock rule: whenever more than one resource is taken, they are taken in
+//! one fixed order. Pools are ordered by `Pool`'s derived `Ord` (gb10, then
+//! qemu, then host). For a gb10 job the order is: the in-process gb10 slot,
+//! then `/tmp/aien-gb10.lock`, then aien-proof's `slots/gpu.lock` when the
+//! aien-proof board directory exists.
+//!
+//! GPU job protocol (CR-028, CR-029, CR-033, CR-052, CR-053): refuse at once
+//! (never wait, never steal) if the quiet flag file exists or an `est_load`
+//! process is running, then take `flock(2)` locks without blocking. A held lock
+//! is a refusal, not a wait, unless the operator asked for `--wait-gpu`. The
+//! lock files are created if absent and never deleted. Dropping a
+//! `GpuGuard` closes the descriptors, and the kernel releases the locks (a
+//! dead holder frees them too).
+//!
+//! Fork window: a `flock` lives as long as any copy of the open file
+//! description does, and a child that another thread forks while a lock
+//! descriptor is open holds a copy until it execs (the descriptor is
+//! close-on-exec, so it never survives the exec). The guard therefore closes
+//! its descriptors under `process::spawn_gate`, the mutex every child spawn
+//! in this crate also takes, so no child is in that window at the moment the
+//! lock is released and the next `acquire_gpu` is not refused by a lock
+//! nobody holds.
+
+use std::fmt;
+use std::fs::{self, File, OpenOptions};
+use std::io;
+use std::os::unix::io::AsRawFd;
+use std::path::{Path, PathBuf};
+use std::sync::{Condvar, Mutex, MutexGuard};
+
+pub const DEFAULT_GPU_LOCK: &str = "/tmp/aien-gb10.lock";
+
+pub(crate) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
+    m.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+/// A counting semaphore.
+#[derive(Debug)]
+pub struct Semaphore {
+    size: usize,
+    free: Mutex<usize>,
+    cv: Condvar,
+}
+
+impl Semaphore {
+    /// A semaphore with `size` slots (at least 1).
+    pub fn new(size: usize) -> Semaphore {
+        let size = size.max(1);
+        Semaphore {
+            size,
+            free: Mutex::new(size),
+            cv: Condvar::new(),
+        }
+    }
+
+    pub fn size(&self) -> usize {
+        self.size
+    }
+
+    pub fn available(&self) -> usize {
+        *lock(&self.free)
+    }
+
+    /// Block until a slot is free.
+    pub fn acquire(&self) -> Permit<'_> {
+        let mut free = lock(&self.free);
+        while *free == 0 {
+            free = self.cv.wait(free).unwrap_or_else(|e| e.into_inner());
+        }
+        *free -= 1;
+        Permit { sem: self }
+    }
+
+    /// Take a slot if one is free right now.
+    pub fn try_acquire(&self) -> Option<Permit<'_>> {
+        let mut free = lock(&self.free);
+        if *free == 0 {
+            return None;
+        }
+        *free -= 1;
+        Some(Permit { sem: self })
+    }
+}
+
+/// One held slot. Dropping it frees the slot and wakes one waiter.
+#[derive(Debug)]
+pub struct Permit<'a> {
+    sem: &'a Semaphore,
+}
+
+impl Drop for Permit<'_> {
+    fn drop(&mut self) {
+        let mut free = lock(&self.sem.free);
+        *free += 1;
+        self.sem.cv.notify_one();
+    }
+}
+
+/// The pool a job is scheduled in. The derived `Ord` is the fixed acquire
+/// order: scarcest first.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum Pool {
+    Gb10,
+    Qemu,
+    Host,
+}
+
+impl Pool {
+    pub fn name(self) -> &'static str {
+        match self {
+            Pool::Gb10 => "gb10",
+            Pool::Qemu => "qemu",
+            Pool::Host => "host",
+        }
+    }
+
+    pub fn from_name(s: &str) -> Option<Pool> {
+        match s {
+            "gb10" => Some(Pool::Gb10),
+            "qemu" => Some(Pool::Qemu),
+            "host" => Some(Pool::Host),
+            _ => None,
+        }
+    }
+}
+
+/// Sizes of the two resizable pools. The gb10 pool is fixed at 1.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PoolSizes {
+    pub host: usize,
+    pub qemu: usize,
+}
+
+/// `--jobs host=N,qemu=M`: only the pools that were named.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct JobsSpec {
+    pub host: Option<usize>,
+    pub qemu: Option<usize>,
+}
+
+impl PoolSizes {
+    /// ADR defaults for a machine with `cpus` CPUs: host = cpus, qemu =
+    /// min(4, host / 2), never below 1.
+    pub fn defaults_for(cpus: usize) -> PoolSizes {
+        let host = cpus.max(1);
+        PoolSizes {
+            host,
+            qemu: (host / 2).clamp(1, 4),
+        }
+    }
+
+    pub fn detect() -> PoolSizes {
+        let cpus = std::thread::available_parallelism()
+            .map(|n| n.get())
+            .unwrap_or(1);
+        PoolSizes::defaults_for(cpus)
+    }
+
+    pub fn with(self, jobs: JobsSpec) -> PoolSizes {
+        PoolSizes {
+            host: jobs.host.unwrap_or(self.host),
+            qemu: jobs.qemu.unwrap_or(self.qemu),
+        }
+    }
+}
+
+/// Parse `host=N,qemu=M` (either part may be left out; N, M at least 1).
+pub fn parse_jobs(spec: &str) -> Result<JobsSpec, String> {
+    let mut out = JobsSpec::default();
+    for part in spec.split(',') {
+        let (name, value) = part
+            .split_once('=')
+            .ok_or_else(|| format!("--jobs entry {part:?} must look like host=N or qemu=M"))?;
+        let n: usize = value
+            .parse()
+            .map_err(|_| format!("--jobs {name} needs a whole number, got {value:?}"))?;
+        if n == 0 {
+            return Err(format!("--jobs {name} must be at least 1"));
+        }
+        match name {
+            "host" => out.host = Some(n),
+            "qemu" => out.qemu = Some(n),
+            "gb10" => return Err("the gb10 pool is fixed at 1".to_string()),
+            other => return Err(format!("unknown pool {other:?} in --jobs")),
+        }
+    }
+    Ok(out)
+}
+
+/// The three semaphores of one runner process.
+#[derive(Debug)]
+pub struct Pools {
+    host: Semaphore,
+    qemu: Semaphore,
+    gb10: Semaphore,
+}
+
+impl Pools {
+    pub fn new(sizes: PoolSizes) -> Pools {
+        Pools {
+            host: Semaphore::new(sizes.host),
+            qemu: Semaphore::new(sizes.qemu),
+            gb10: Semaphore::new(1),
+        }
+    }
+
+    pub fn semaphore(&self, pool: Pool) -> &Semaphore {
+        match pool {
+            Pool::Host => &self.host,
+            Pool::Qemu => &self.qemu,
+            Pool::Gb10 => &self.gb10,
+        }
+    }
+
+    pub fn acquire(&self, pool: Pool) -> Permit<'_> {
+        self.semaphore(pool).acquire()
+    }
+
+    pub fn try_acquire(&self, pool: Pool) -> Option<Permit<'_>> {
+        self.semaphore(pool).try_acquire()
+    }
+
+    /// Take several pools in the fixed order (duplicates collapse), so two
+    /// callers asking for the same set can never deadlock each other.
+    pub fn acquire_many(&self, pools: &[Pool]) -> Vec<Permit<'_>> {
+        let mut order: Vec<Pool> = pools.to_vec();
+        order.sort();
+        order.dedup();
+        order.into_iter().map(|p| self.acquire(p)).collect()
+    }
+}
+
+/// Which special hardware this machine has. A heuristic, recorded in the
+/// receipt's `machine` object (UNVERIFIED: `/dev/nvidiactl` for the GB10).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Hardware {
+    pub gb10_present: bool,
+    pub qemu_available: bool,
+}
+
+fn which(name: &str) -> bool {
+    match std::env::var_os("PATH") {
+        Some(p) => std::env::split_paths(&p).any(|d| d.join(name).is_file()),
+        None => false,
+    }
+}
+
+impl Hardware {
+    pub fn detect() -> Hardware {
+        Hardware {
+            gb10_present: Path::new("/dev/nvidiactl").exists(),
+            qemu_available: which("qemu-system-aarch64") || which("qemu-system-x86_64"),
+        }
+    }
+}
+
+/// Where the GPU lock files and the refusal checks live. Passed in explicitly
+/// (never read from the environment by the lock code), so a test can point
+/// every path at a scratch directory and never touch the real locks.
+#[derive(Debug, Clone)]
+pub struct GpuConfig {
+    /// `/tmp/aien-gb10.lock`, taken first.
+    pub lock_path: PathBuf,
+    /// aien-proof's `slots/gpu.lock`, taken second, only when its board
+    /// directory exists (ADR Decision 6, stopgap until the locks are unified).
+    pub proof_lock_path: Option<PathBuf>,
+    /// `~/workspace/.spark-quiet`; None when HOME is unknown.
+    pub quiet_flag: Option<PathBuf>,
+    /// Where to look for an `est_load` process (`/proc`).
+    pub proc_dir: PathBuf,
+    /// `--wait-gpu`: block on a held lock instead of refusing.
+    pub wait: bool,
+}
+
+impl GpuConfig {
+    /// The real machine: default lock, HOME-relative quiet flag, aien-proof
+    /// board from `AIEN_PROOF_DIR` or `~/.local/state/aien-proof`.
+    pub fn detect() -> GpuConfig {
+        let home = std::env::var_os("HOME").map(PathBuf::from);
+        let board = match std::env::var_os("AIEN_PROOF_DIR") {
+            Some(d) => Some(PathBuf::from(d)),
+            None => home.as_ref().map(|h| h.join(".local/state/aien-proof")),
+        };
+        GpuConfig {
+            lock_path: PathBuf::from(DEFAULT_GPU_LOCK),
+            proof_lock_path: board
+                .filter(|b| b.is_dir())
+                .map(|b| b.join("slots/gpu.lock")),
+            quiet_flag: home.map(|h| h.join("workspace/.spark-quiet")),
+            proc_dir: PathBuf::from("/proc"),
+            wait: false,
+        }
+    }
+
+    /// Every path inside `dir` (a scratch directory): own lock, own quiet
+    /// flag, no aien-proof lock, no `est_load`.
+    pub fn rooted_at(dir: &Path) -> GpuConfig {
+        GpuConfig {
+            lock_path: dir.join("gb10.lock"),
+            proof_lock_path: None,
+            quiet_flag: Some(dir.join("quiet-flag")),
+            proc_dir: dir.join("proc"),
+            wait: false,
+        }
+    }
+}
+
+/// Why a GPU job was refused. `reason()` is the stable code for the receipt.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum GpuRefusal {
+    /// The quiet flag exists; carries its text (CR-028).
+    QuietFlag(String),
+    /// An `est_load` process is running (CR-029).
+    EstLoad,
+    /// A lock file could not be opened (CR-033, `gpu_open`).
+    LockOpen(String),
+    /// Another holder has `/tmp/aien-gb10.lock` (CR-033, `gpu_lock`).
+    LockHeld(PathBuf),
+    /// Another holder has aien-proof's `slots/gpu.lock` (`gpu_lock_proof`).
+    ProofLockHeld(PathBuf),
+}
+
+impl GpuRefusal {
+    pub fn reason(&self) -> &'static str {
+        match self {
+            GpuRefusal::QuietFlag(_) => "quiet_flag",
+            GpuRefusal::EstLoad => "est_load",
+            GpuRefusal::LockOpen(_) => "gpu_open",
+            GpuRefusal::LockHeld(_) => "gpu_lock",
+            GpuRefusal::ProofLockHeld(_) => "gpu_lock_proof",
+        }
+    }
+}
+
+impl fmt::Display for GpuRefusal {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            GpuRefusal::QuietFlag(t) => write!(f, "quiet flag is up: {t}"),
+            GpuRefusal::EstLoad => write!(f, "an est_load process is running"),
+            GpuRefusal::LockOpen(m) => write!(f, "cannot open GPU lock: {m}"),
+            GpuRefusal::LockHeld(p) => write!(f, "GPU lock {} is held", p.display()),
+            GpuRefusal::ProofLockHeld(p) => {
+                write!(f, "aien-proof GPU lock {} is held", p.display())
+            }
+        }
+    }
+}
+
+/// True if any process under `proc_dir` has a name containing `est_load`
+/// (what `pgrep est_load` matches, CR-029).
+pub fn est_load_running(proc_dir: &Path) -> bool {
+    let rd = match fs::read_dir(proc_dir) {
+        Ok(r) => r,
+        Err(_) => return false,
+    };
+    for e in rd.flatten() {
+        let name = e.file_name();
+        let name = name.to_string_lossy();
+        if name.is_empty() || !name.bytes().all(|b| b.is_ascii_digit()) {
+            continue;
+        }
+        if let Ok(comm) = fs::read_to_string(e.path().join("comm")) {
+            if comm.trim().contains("est_load") {
+                return true;
+            }
+        }
+    }
+    false
+}
+
+/// The cheap refusals that need no lock: quiet flag, then `est_load`. The
+/// flag is never created, changed or removed here (CR-050).
+pub fn preflight(cfg: &GpuConfig) -> Option<GpuRefusal> {
+    if let Some(flag) = &cfg.quiet_flag {
+        if fs::symlink_metadata(flag).is_ok() {
+            let text = fs::read_to_string(flag).unwrap_or_default();
+            return Some(GpuRefusal::QuietFlag(text.trim().to_string()));
+        }
+    }
+    if est_load_running(&cfg.proc_dir) {
+        return Some(GpuRefusal::EstLoad);
+    }
+    None
+}
+
+/// Descriptors holding the GPU locks. Drop releases them, under the spawn
+/// gate (see the module comment, "Fork window").
+#[derive(Debug)]
+pub struct GpuGuard {
+    files: Vec<File>,
+}
+
+impl Drop for GpuGuard {
+    fn drop(&mut self) {
+        let _gate = crate::process::spawn_gate();
+        self.files.clear();
+    }
+}
+
+fn open_lock(path: &Path) -> io::Result<File> {
+    if let Some(parent) = path.parent() {
+        if !parent.as_os_str().is_empty() {
+            fs::create_dir_all(parent)?;
+        }
+    }
+    OpenOptions::new().create(true).append(true).open(path)
+}
+
+/// `flock(LOCK_EX)`: Ok(true) when taken, Ok(false) when held by someone else
+/// and `wait` is off.
+fn flock_exclusive(file: &File, wait: bool) -> io::Result<bool> {
+    let op = if wait {
+        libc::LOCK_EX
+    } else {
+        libc::LOCK_EX | libc::LOCK_NB
+    };
+    loop {
+        // SAFETY: flock on a descriptor that `file` keeps open for this call.
+        let rc = unsafe { libc::flock(file.as_raw_fd(), op) };
+        if rc == 0 {
+            return Ok(true);
+        }
+        let err = io::Error::last_os_error();
+        match err.raw_os_error() {
+            Some(libc::EINTR) => {}
+            Some(libc::EWOULDBLOCK) => return Ok(false),
+            _ => return Err(err),
+        }
+    }
+}
+
+fn take_lock(path: &Path, wait: bool) -> Result<Option<File>, GpuRefusal> {
+    let file =
+        open_lock(path).map_err(|e| GpuRefusal::LockOpen(format!("{}: {e}", path.display())))?;
+    match flock_exclusive(&file, wait) {
+        Ok(true) => Ok(Some(file)),
+        Ok(false) => Ok(None),
+        Err(e) => Err(GpuRefusal::LockOpen(format!("{}: {e}", path.display()))),
+    }
+}
+
+/// The GPU job protocol up to the point of running: refusals first, then the
+/// locks in the fixed order. Call it after taking the in-process gb10 slot.
+pub fn acquire_gpu(cfg: &GpuConfig) -> Result<GpuGuard, GpuRefusal> {
+    if let Some(r) = preflight(cfg) {
+        return Err(r);
+    }
+    let primary = match take_lock(&cfg.lock_path, cfg.wait)? {
+        Some(f) => f,
+        None => return Err(GpuRefusal::LockHeld(cfg.lock_path.clone())),
+    };
+    let mut guard = GpuGuard {
+        files: vec![primary],
+    };
+    if let Some(p) = &cfg.proof_lock_path {
+        match take_lock(p, cfg.wait)? {
+            Some(f) => guard.files.push(f),
+            // Returning drops `guard`, so the first lock is not left held,
+            // and it is released through the spawn gate like any other.
+            None => return Err(GpuRefusal::ProofLockHeld(p.clone())),
+        }
+    }
+    Ok(guard)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::testutil::{write_file, TempDir};
+    use std::sync::mpsc;
+    use std::thread;
+    use std::time::Duration;
+
+    #[test]
+    fn semaphore_counts_slots() {
+        let s = Semaphore::new(2);
+        assert_eq!((s.size(), s.available()), (2, 2));
+        let a = s.try_acquire();
+        let b = s.try_acquire();
+        assert!(a.is_some() && b.is_some());
+        assert_eq!(s.available(), 0);
+        assert!(s.try_acquire().is_none());
+        drop(a);
+        assert_eq!(s.available(), 1);
+        assert!(s.try_acquire().is_some());
+    }
+
+    #[test]
+    fn zero_size_is_one_slot() {
+        assert_eq!(Semaphore::new(0).size(), 1);
+    }
+
+    #[test]
+    fn acquire_waits_for_a_release() {
+        let sem = Semaphore::new(1);
+        let held = sem.acquire();
+        let (tx, rx) = mpsc::channel();
+        thread::scope(|s| {
+            s.spawn(|| {
+                let _p = sem.acquire();
+                tx.send(()).unwrap();
+            });
+            thread::sleep(Duration::from_millis(150));
+            assert!(rx.try_recv().is_err(), "the second acquire must wait");
+            drop(held);
+            rx.recv_timeout(Duration::from_secs(20))
+                .expect("the waiter gets the slot after the release");
+        });
+    }
+
+    #[test]
+    fn gb10_pool_is_serialized() {
+        let p = Pools::new(PoolSizes { host: 4, qemu: 2 });
+        let first = p.try_acquire(Pool::Gb10);
+        assert!(first.is_some());
+        assert!(p.try_acquire(Pool::Gb10).is_none(), "gb10 has one slot");
+        assert_eq!(p.semaphore(Pool::Gb10).size(), 1);
+        assert_eq!(p.semaphore(Pool::Host).size(), 4);
+        assert_eq!(p.semaphore(Pool::Qemu).size(), 2);
+        drop(first);
+        assert!(p.try_acquire(Pool::Gb10).is_some());
+    }
+
+    #[test]
+    fn pool_names_round_trip() {
+        for pool in [Pool::Gb10, Pool::Qemu, Pool::Host] {
+            assert_eq!(Pool::from_name(pool.name()), Some(pool));
+        }
+        assert_eq!(Pool::from_name("gpu"), None);
+        assert!(Pool::Gb10 < Pool::Qemu && Pool::Qemu < Pool::Host);
+    }
+
+    #[test]
+    fn default_sizes_follow_the_adr() {
+        assert_eq!(PoolSizes::defaults_for(8), PoolSizes { host: 8, qemu: 4 });
+        assert_eq!(PoolSizes::defaults_for(20), PoolSizes { host: 20, qemu: 4 });
+        assert_eq!(PoolSizes::defaults_for(4), PoolSizes { host: 4, qemu: 2 });
+        assert_eq!(PoolSizes::defaults_for(1), PoolSizes { host: 1, qemu: 1 });
+        assert_eq!(PoolSizes::defaults_for(0), PoolSizes { host: 1, qemu: 1 });
+        assert!(PoolSizes::detect().host >= 1);
+    }
+
+    #[test]
+    fn jobs_option_parses_and_overrides() {
+        let j = parse_jobs("host=3,qemu=2").unwrap();
+        assert_eq!(
+            j,
+            JobsSpec {
+                host: Some(3),
+                qemu: Some(2)
+            }
+        );
+        let j = parse_jobs("qemu=5").unwrap();
+        assert_eq!(j.host, None);
+        let base = PoolSizes { host: 8, qemu: 4 };
+        assert_eq!(base.with(j), PoolSizes { host: 8, qemu: 5 });
+        for bad in [
+            "", "host", "host=", "host=0", "host=x", "gb10=2", "disk=1", "host=1,",
+        ] {
+            assert!(parse_jobs(bad).is_err(), "{bad:?} must be rejected");
+        }
+    }
+
+    #[test]
+    fn acquire_many_uses_one_order() {
+        let p = Pools::new(PoolSizes { host: 1, qemu: 1 });
+        // Opposite orders and repeats: the fixed order keeps them deadlock free.
+        thread::scope(|s| {
+            for flip in [false, true] {
+                let p = &p;
+                s.spawn(move || {
+                    for _ in 0..100 {
+                        let want = if flip {
+                            [Pool::Host, Pool::Qemu, Pool::Gb10, Pool::Host]
+                        } else {
+                            [Pool::Gb10, Pool::Qemu, Pool::Host, Pool::Gb10]
+                        };
+                        let permits = p.acquire_many(&want);
+                        assert_eq!(permits.len(), 3);
+                    }
+                });
+            }
+        });
+        for pool in [Pool::Gb10, Pool::Qemu, Pool::Host] {
+            assert_eq!(p.semaphore(pool).available(), 1, "{pool:?} slot leaked");
+        }
+    }
+
+    #[test]
+    fn gpu_lock_is_exclusive_and_released_on_drop() {
+        let d = TempDir::new("gpu");
+        let cfg = GpuConfig::rooted_at(d.path());
+        let g = acquire_gpu(&cfg).expect("free lock");
+        match acquire_gpu(&cfg) {
+            Err(GpuRefusal::LockHeld(p)) => assert_eq!(p, cfg.lock_path),
+            other => panic!("expected LockHeld, got {other:?}"),
+        }
+        drop(g);
+        let again = acquire_gpu(&cfg);
+        assert!(again.is_ok(), "released by drop: {again:?}");
+        assert!(cfg.lock_path.exists(), "the lock file is never deleted");
+    }
+
+    /// Regression for the forge flake at e703501c: a child that is between
+    /// fork and exec holds a copy of the lock's open file description, so the
+    /// lock looked held after the guard was dropped. The child below stays in
+    /// that window for 150 ms (its `pre_exec` hook sleeps), the guard is
+    /// dropped meanwhile, and the next acquire must succeed. The drop waits for
+    /// the spawn to finish (the spawn gate), so this passes whatever the
+    /// scheduling; without the gate it fails because the child still holds the
+    /// lock when the re-acquire runs.
+    #[test]
+    fn gpu_lock_release_waits_for_a_child_between_fork_and_exec() {
+        use std::os::unix::process::CommandExt;
+        use std::process::Command;
+
+        let d = TempDir::new("gpu");
+        let cfg = GpuConfig::rooted_at(d.path());
+        let mut fds: [libc::c_int; 2] = [0, 0];
+        // SAFETY: `fds` has room for the two descriptors pipe2 writes.
+        let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) };
+        assert_eq!(rc, 0, "pipe2");
+        let (ready_r, ready_w) = (fds[0], fds[1]);
+
+        for round in 0..3 {
+            let g = acquire_gpu(&cfg).unwrap_or_else(|e| panic!("round {round}: {e}"));
+            thread::scope(|s| {
+                let spawner = s.spawn(move || {
+                    let mut cmd = Command::new("/bin/true");
+                    // SAFETY: the hook runs between fork and exec and only
+                    // calls write(2) and poll(2), which are async-signal-safe;
+                    // it allocates nothing and touches no lock.
+                    unsafe {
+                        cmd.pre_exec(move || {
+                            let byte = [1u8];
+                            libc::write(ready_w, byte.as_ptr().cast(), 1);
+                            // poll with no descriptors is a sleep: 150 ms.
+                            libc::poll(std::ptr::null_mut(), 0, 150);
+                            Ok(())
+                        });
+                    }
+                    let mut child = crate::process::spawn_gated(&mut cmd).expect("spawn");
+                    child.wait().expect("wait")
+                });
+                // The child is now alive and between fork and exec.
+                let mut pfd = libc::pollfd {
+                    fd: ready_r,
+                    events: libc::POLLIN,
+                    revents: 0,
+                };
+                // SAFETY: one valid pollfd.
+                let n = unsafe { libc::poll(&mut pfd, 1, 20_000) };
+                assert_eq!(n, 1, "round {round}: the child never reached pre_exec");
+                let mut byte = [0u8; 1];
+                // SAFETY: reads at most one byte into a one byte buffer.
+                let got = unsafe { libc::read(ready_r, byte.as_mut_ptr().cast(), 1) };
+                assert_eq!(got, 1, "round {round}: ready byte");
+
+                drop(g);
+                let again = acquire_gpu(&cfg);
+                assert!(
+                    again.is_ok(),
+                    "round {round}: a child between fork and exec kept the lock: {again:?}"
+                );
+                drop(again);
+                let status = spawner.join().expect("spawner thread");
+                assert!(status.success(), "round {round}: /bin/true failed");
+            });
+        }
+        // SAFETY: both descriptors are ours and no thread is using them now.
+        unsafe {
+            libc::close(ready_r);
+            libc::close(ready_w);
+        }
+    }
+
+    #[test]
+    fn held_lock_reason_is_gpu_lock() {
+        let d = TempDir::new("gpu");
+        let cfg = GpuConfig::rooted_at(d.path());
+        let _g = acquire_gpu(&cfg).unwrap();
+        let e = acquire_gpu(&cfg).unwrap_err();
+        assert_eq!(e.reason(), "gpu_lock");
+        assert!(e.to_string().contains("is held"));
+    }
+
+    #[test]
+    fn open_handle_without_flock_does_not_block() {
+        // CR-052: only a flock holder blocks; a plain open handle does not.
+        let d = TempDir::new("gpu");
+        let cfg = GpuConfig::rooted_at(d.path());
+        write_file(d.path(), "gb10.lock", "", false);
+        let _plain = File::open(&cfg.lock_path).unwrap();
+        assert!(acquire_gpu(&cfg).is_ok());
+    }
+
+    #[test]
+    fn quiet_flag_refuses_and_is_left_alone() {
+        let d = TempDir::new("gpu");
+        let cfg = GpuConfig::rooted_at(d.path());
+        write_file(d.path(), "quiet-flag", "drake start=now\n", false);
+        match acquire_gpu(&cfg) {
+            Err(GpuRefusal::QuietFlag(t)) => assert_eq!(t, "drake start=now"),
+            other => panic!("expected QuietFlag, got {other:?}"),
+        }
+        assert_eq!(
+            fs::read_to_string(d.path().join("quiet-flag")).unwrap(),
+            "drake start=now\n",
+            "the flag must never be changed"
+        );
+        assert!(!cfg.lock_path.exists(), "refused before touching the lock");
+        assert_eq!(preflight(&cfg).unwrap().reason(), "quiet_flag");
+    }
+
+    #[test]
+    fn est_load_process_refuses() {
+        let d = TempDir::new("gpu");
+        let cfg = GpuConfig::rooted_at(d.path());
+        assert!(preflight(&cfg).is_none(), "no proc dir means no est_load");
+        write_file(d.path(), "proc/101/comm", "bash\n", false);
+        write_file(d.path(), "proc/self/comm", "est_load\n", false);
+        assert!(
+            !est_load_running(&cfg.proc_dir),
+            "non-numeric entries are ignored"
+        );
+        write_file(d.path(), "proc/202/comm", "est_load\n", false);
+        assert!(est_load_running(&cfg.proc_dir));
+        match acquire_gpu(&cfg) {
+            Err(GpuRefusal::EstLoad) => {}
+            other => panic!("expected EstLoad, got {other:?}"),
+        }
+    }
+
+    #[test]
+    fn proof_lock_is_second_and_blocks_the_whole_acquire() {
+        let d = TempDir::new("gpu");
+        let mut cfg = GpuConfig::rooted_at(d.path());
+        let proof = d.path().join("board/slots/gpu.lock");
+        cfg.proof_lock_path = Some(proof.clone());
+        // Someone else (aien-proof) holds its lock. A `GpuGuard` stands in for
+        // that holder so its release goes through the spawn gate too.
+        let other = open_lock(&proof).unwrap();
+        assert!(flock_exclusive(&other, false).unwrap());
+        let other = GpuGuard { files: vec![other] };
+        match acquire_gpu(&cfg) {
+            Err(GpuRefusal::ProofLockHeld(p)) => assert_eq!(p, proof),
+            got => panic!("expected ProofLockHeld, got {got:?}"),
+        }
+        // The failed attempt must not leave the first lock held.
+        let mut only_first = cfg.clone();
+        only_first.proof_lock_path = None;
+        assert!(acquire_gpu(&only_first).is_ok());
+        drop(other);
+        let both = acquire_gpu(&cfg).expect("both free now");
+        // While both are held, each is refused to a second holder.
+        assert!(matches!(acquire_gpu(&cfg), Err(GpuRefusal::LockHeld(_))));
+        drop(both);
+    }
+
+    #[test]
+    fn wait_mode_blocks_until_the_holder_releases() {
+        let d = TempDir::new("gpu");
+        let mut cfg = GpuConfig::rooted_at(d.path());
+        let held = acquire_gpu(&cfg).unwrap();
+        cfg.wait = true;
+        let (tx, rx) = mpsc::channel();
+        thread::scope(|s| {
+            s.spawn(|| {
+                let g = acquire_gpu(&cfg);
+                tx.send(g.is_ok()).unwrap();
+            });
+            thread::sleep(Duration::from_millis(150));
+            assert!(rx.try_recv().is_err(), "wait mode must block");
+            drop(held);
+            assert!(rx.recv_timeout(Duration::from_secs(20)).unwrap());
+        });
+    }
+
+    #[test]
+    fn detect_builds_a_config_without_touching_anything() {
+        let c = GpuConfig::detect();
+        assert_eq!(c.lock_path, PathBuf::from(DEFAULT_GPU_LOCK));
+        assert!(!c.wait);
+        assert_eq!(c.proc_dir, PathBuf::from("/proc"));
+        let _ = Hardware::detect();
+    }
+}
diff --git a/tools/aien-test/src/runner.rs b/tools/aien-test/src/runner.rs
index 667ddf30..afa23d74 100644
--- a/tools/aien-test/src/runner.rs
+++ b/tools/aien-test/src/runner.rs
@@ -1,29 +1,45 @@
-//! Serial, host-pool runner for one gate (ADR 0028, Slice A).
+//! The runner (ADR 0028, Slices A and B): one gate, or a whole graph of gates
+//! run by worker threads that honour the resource pools and the dependencies.
 //!
-//! Order: parse manifest (BAD_MANIFEST means no receipt), pin the commit,
-//! record whether the tree is clean, decide refusals, run, measure what
-//! changed, derive the verdict, write blobs and an immutable receipt.
+//! Order for one gate: parse manifest (BAD_MANIFEST means no receipt), pin the
+//! commit, record whether the tree is clean, decide refusals, take the GPU
+//! locks if it is a gb10 gate, run, measure what changed, derive the verdict,
+//! write blobs and an immutable receipt.
 //!
-//! Slice A choices where the ADR is silent (recorded in the PR):
+//! Choices where the ADR is silent (recorded in the PRs):
 //! - A dirty tree is refused unless the operator passes `--allow-dirty` (the
 //!   manifest grammar has no key for it and P4 forbids adding one here). A
 //!   run allowed this way is recorded with `tree_clean_before = false`.
 //! - "Tree changed after the run" means `git status --porcelain` differs from
 //!   the pre-run output, so it also catches a run that dirties an already
-//!   allowed-dirty tree further.
-//! - `pins` is always empty and `dependencies` is always empty.
+//!   allowed-dirty tree further. In a graph run the check is per job and does
+//!   not know which job wrote a file, so when one gate dirties the tree, gates
+//!   that were running at the same moment fail with it. That is the safe side.
+//! - `pins` is always empty.
 //! - `gb10_present` is a heuristic: `/dev/nvidiactl` exists (UNVERIFIED).
+//! - `run GATE` never starts a gate's dependencies. It looks their receipts
+//!   up in the evidence store, for the current commit, and says NOT_RUN if one
+//!   is not a PASS. `run_graph` starts them.
 
-use crate::evidence::{build_receipt, canonical_digest, sha256_hex, utc_string, Store, SCHEMA};
+use crate::evidence::{
+    build_receipt, canonical_digest, sha256_hex, utc_string, Index, Store, SCHEMA,
+};
+use crate::graph::Graph;
 use crate::manifest::{self, Manifest};
 use crate::process::{self, RunSpec};
-use crate::verdict::{self, derive, parse_observations, Facts, Verdict};
+use crate::resources::{
+    acquire_gpu, lock, GpuConfig, GpuGuard, Hardware, Permit, Pool, PoolSizes, Pools,
+};
+use crate::verdict::{self, campaign_verdict, derive, parse_observations, DepFact, Facts, Verdict};
 use serde_json::{json, Map, Value};
-use std::collections::BTreeSet;
+use std::collections::{BTreeMap, BTreeSet};
 use std::fmt;
 use std::fs;
+use std::panic::{catch_unwind, AssertUnwindSafe};
 use std::path::{Component, Path, PathBuf};
 use std::process::Command;
+use std::sync::{Condvar, Mutex};
+use std::thread;
 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
 
 pub struct Options {
@@ -31,15 +47,26 @@ pub struct Options {
     pub allow_dirty: bool,
     pub args_override: Option<Vec<String>>,
     pub kill_grace: Duration,
+    /// Sizes of the host and qemu pools (the gb10 pool is always 1).
+    pub pool_sizes: PoolSizes,
+    /// Which special hardware this machine has.
+    pub hardware: Hardware,
+    /// Lock files and refusal checks for gb10 gates.
+    pub gpu: GpuConfig,
 }
 
 impl Options {
+    /// Options for the real machine: detected pool sizes, hardware and GPU
+    /// paths. Tests overwrite the last three with scratch values.
     pub fn new(evidence_dir: PathBuf) -> Options {
         Options {
             evidence_dir,
             allow_dirty: false,
             args_override: None,
             kill_grace: Duration::from_secs(10),
+            pool_sizes: PoolSizes::detect(),
+            hardware: Hardware::detect(),
+            gpu: GpuConfig::detect(),
         }
     }
 }
@@ -70,12 +97,16 @@ pub struct Outcome {
 }
 
 fn git_out(root: &Path, args: &[&str]) -> Result<String, String> {
-    let out = Command::new("git")
+    // Several jobs may ask for the status at once; the status command must
+    // not take the index lock (and fail the other caller) to refresh it.
+    let mut cmd = Command::new("git");
+    cmd.env("GIT_OPTIONAL_LOCKS", "0")
         .arg("-C")
         .arg(root)
-        .args(args)
-        .output()
-        .map_err(|e| format!("cannot run git: {e}"))?;
+        .args(args);
+    // The spawn goes through the spawn gate (see `process::SPAWN_GATE`) so a
+    // git child never holds a GPU lock descriptor past the lock's release.
+    let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run git: {e}"))?;
     if !out.status.success() {
         return Err(format!(
             "git {:?} failed: {}",
@@ -91,7 +122,8 @@ pub fn repo_root(dir: &Path) -> Result<PathBuf, String> {
     Ok(PathBuf::from(s.trim()))
 }
 
-fn head(root: &Path) -> Result<String, String> {
+/// The full commit id of HEAD (40 lower-case hex digits).
+pub fn head(root: &Path) -> Result<String, String> {
     let s = git_out(root, &["rev-parse", "HEAD"])?.trim().to_string();
     if s.len() == 40
         && s.chars()
@@ -107,6 +139,22 @@ fn porcelain(root: &Path) -> Result<String, String> {
     git_out(root, &["status", "--porcelain"])
 }
 
+/// Where receipts go when `--evidence-dir` is not given:
+/// `$HOME/workspace/evidence-out/<repository directory name>`.
+pub fn default_evidence_dir(root: &Path) -> Option<PathBuf> {
+    let home = std::env::var_os("HOME")?;
+    let name = root
+        .file_name()
+        .map(|n| n.to_string_lossy().into_owned())
+        .unwrap_or_else(|| "repo".to_string());
+    Some(
+        PathBuf::from(home)
+            .join("workspace")
+            .join("evidence-out")
+            .join(name),
+    )
+}
+
 /// Absolute, lexically normalized path whose deepest existing ancestor is
 /// canonicalized, so a not-yet-created evidence dir can still be compared.
 fn resolve(p: &Path) -> PathBuf {
@@ -247,7 +295,7 @@ fn collect_files(root: &Path, rel: &str, out: &mut BTreeSet<String>) {
 /// sha256 over the canonical list of (path, file sha256) for the explicit
 /// `inputs` plus the D3 convention-implied inputs of `tests/<dir>/<name>.gate`.
 /// A listed path that does not exist is recorded with a null digest. Compiler
-/// identity is not included in Slice A because Slice A does not build.
+/// identity is not included yet because nothing here builds.
 pub fn build_inputs_digest(root: &Path, manifest_rel: Option<&Path>, m: &Manifest) -> String {
     let mut paths: BTreeSet<String> = BTreeSet::new();
     for i in &m.inputs {
@@ -297,14 +345,7 @@ pub fn build_inputs_digest(root: &Path, manifest_rel: Option<&Path>, m: &Manifes
     canonical_digest(&json!({ "inputs": entries })).unwrap_or_default()
 }
 
-fn which(name: &str) -> bool {
-    match std::env::var_os("PATH") {
-        Some(p) => std::env::split_paths(&p).any(|d| d.join(name).is_file()),
-        None => false,
-    }
-}
-
-fn machine() -> Value {
+fn machine(hw: &Hardware) -> Value {
     let kernel = fs::read_to_string("/proc/sys/kernel/osrelease")
         .map(|s| s.trim().to_string())
         .unwrap_or_default();
@@ -325,16 +366,14 @@ fn machine() -> Value {
         .and_then(|l| l.split_whitespace().nth(1))
         .and_then(|v| v.parse::<u64>().ok())
         .unwrap_or(0);
-    let gb10 = Path::new("/dev/nvidiactl").exists();
-    let qemu = which("qemu-system-aarch64") || which("qemu-system-x86_64");
     json!({
         "arch": std::env::consts::ARCH,
         "kernel_release": kernel,
         "cpu_model": cpu_model,
         "cpu_count": cpus,
         "mem_total_kib": mem_kib,
-        "gb10_present": gb10,
-        "qemu_available": qemu,
+        "gb10_present": hw.gb10_present,
+        "qemu_available": hw.qemu_available,
     })
 }
 
@@ -368,10 +407,31 @@ fn fatal<E: fmt::Display>(e: E) -> RunError {
     RunError::Fatal(e.to_string())
 }
 
-pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result<Outcome, RunError> {
-    let bytes = fs::read(manifest_path)
-        .map_err(|e| RunError::Fatal(format!("cannot read manifest: {e}")))?;
-    let m = manifest::parse(&bytes).map_err(|e| RunError::BadManifest(e.0))?;
+/// `core.dependencies`: gate to receipt digest, sorted by gate, only for the
+/// dependencies that have a receipt for this commit.
+fn dependency_rows(deps: &[DepFact]) -> BTreeMap<String, String> {
+    deps.iter()
+        .filter_map(|d| d.receipt.as_ref().map(|r| (d.gate.clone(), r.clone())))
+        .collect()
+}
+
+/// Everything `execute_gate` needs besides the permit.
+struct Job<'a> {
+    root: &'a Path,
+    manifest_path: &'a Path,
+    m: &'a Manifest,
+    opts: &'a Options,
+    /// What is known about each `depends_on` gate right now.
+    deps: Vec<DepFact>,
+    /// How long the job waited for a pool slot.
+    pool_wait_ms: u64,
+}
+
+/// Run one gate that has been parsed already. `permit` is the pool slot the
+/// job holds (None for a lone `run`, and for gates that cannot run anyway); it
+/// is released as soon as the job ends.
+fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, RunError> {
+    let (root, m, opts) = (job.root, job.m, job.opts);
     let started = now_secs();
     let t0 = Instant::now();
 
@@ -388,16 +448,34 @@ pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result<Out
 
     let exec_path = root.join(&m.exec);
     let exec_exists = exec_path.is_file();
-    let will_run = verdict::pre_run(&m, &refusal, exec_exists).is_none();
-
     let mut facts = Facts {
         refusal,
         exec_exists,
+        deps: job.deps.clone(),
+        gb10_present: opts.hardware.gb10_present,
+        qemu_available: opts.hardware.qemu_available,
         ..Facts::default()
     };
+
+    // A gb10 gate takes the GPU locks only when nothing else already stops it.
+    // A refusal (quiet flag, est_load, a held lock) becomes the gate's reason.
+    let gpu: Option<GpuGuard> = if m.pool() == "gb10" && verdict::pre_run(m, &facts).is_none() {
+        match acquire_gpu(&opts.gpu) {
+            Ok(g) => Some(g),
+            Err(r) => {
+                facts.refusal = Some(r.reason().to_string());
+                None
+            }
+        }
+    } else {
+        None
+    };
+    let will_run = verdict::pre_run(m, &facts).is_none();
+
     let mut stdout: Vec<u8> = Vec::new();
     let mut stderr: Vec<u8> = Vec::new();
     let mut after = before.clone();
+    let mut timeout_exceeded = false;
     if will_run {
         let spec = RunSpec {
             program: exec_path.clone(),
@@ -405,11 +483,15 @@ pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result<Out
             cwd: root.to_path_buf(),
             timeout: Duration::from_millis(m.timeout_ms),
             kill_grace: opts.kill_grace,
+            // gb10 jobs are never killed (ADR 0028 Decision 6): the timeout
+            // only marks the receipt.
+            enforce_timeout: m.pool() != "gb10",
         };
         match process::run(&spec) {
             Ok(o) => {
                 facts.exit_status = o.exit_code.map(i64::from);
                 facts.timed_out = o.timed_out;
+                timeout_exceeded = o.timeout_exceeded;
                 stdout = o.stdout;
                 stderr = o.stderr;
             }
@@ -417,13 +499,16 @@ pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result<Out
                 stderr = format!("aien-test: cannot run {}: {e}\n", m.exec).into_bytes();
             }
         }
+        // The job is over: close the lock descriptors at once.
+        drop(gpu);
         after = porcelain(root).map_err(RunError::Fatal)?;
         let head_after = head(root).unwrap_or_default();
         facts.tree_changed_after = after != before;
         facts.head_moved = head_after != commit;
         facts.observations = parse_observations(&stdout);
     }
-    let derived = derive(&m, &facts);
+    drop(permit);
+    let derived = derive(m, &facts);
 
     if evidence_inside {
         return Ok(Outcome {
@@ -442,12 +527,13 @@ pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result<Out
     } else {
         None
     };
-    let manifest_rel = manifest_path
+    let manifest_rel = job
+        .manifest_path
         .strip_prefix(root)
         .ok()
         .map(|p| p.to_path_buf());
-    let inputs_digest = build_inputs_digest(root, manifest_rel.as_deref(), &m);
-    let machine_v = machine();
+    let inputs_digest = build_inputs_digest(root, manifest_rel.as_deref(), m);
+    let machine_v = machine(&opts.hardware);
     let machine_digest = canonical_digest(&machine_v).map_err(fatal)?;
 
     let observations: Vec<Value> = facts
@@ -468,6 +554,10 @@ pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result<Out
             json!({ "name": c, "passed": passed })
         })
         .collect();
+    let dependencies: Vec<Value> = dependency_rows(&facts.deps)
+        .iter()
+        .map(|(gate, receipt)| json!({ "gate": gate, "receipt": receipt }))
+        .collect();
 
     let mut core = Map::new();
     core.insert("gate".into(), json!(m.gate));
@@ -494,14 +584,14 @@ pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result<Out
     core.insert("reason".into(), json!(derived.reason));
     core.insert("mutants".into(), json!([]));
     core.insert("checks".into(), Value::Array(checks));
-    core.insert("dependencies".into(), json!([]));
+    core.insert("dependencies".into(), Value::Array(dependencies.clone()));
 
     let cache_key = canonical_digest(&json!({
         "manifest_digest": m.digest,
         "binary_sha256": binary_sha,
         "build_inputs_digest": inputs_digest,
         "machine_digest": machine_digest,
-        "dependencies": [],
+        "dependencies": dependencies,
         "runner_schema": SCHEMA,
         "pins": [],
     }))
@@ -511,11 +601,11 @@ pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result<Out
         "started_utc": utc_string(started),
         "finished_utc": utc_string(now_secs()),
         "duration_ms": t0.elapsed().as_millis() as u64,
-        "pool": "host",
-        "pool_wait_ms": 0,
+        "pool": m.pool(),
+        "pool_wait_ms": job.pool_wait_ms,
         "runner": { "name": "aien-test", "version": env!("CARGO_PKG_VERSION"), "impl": "rust" },
         "cache": { "key": cache_key, "reused": false, "reused_from": null, "mode": "disabled" },
-        "timeout_exceeded": facts.timed_out,
+        "timeout_exceeded": timeout_exceeded,
     });
 
     let receipt = build_receipt(Value::Object(core), volatile);
@@ -528,6 +618,302 @@ pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result<Out
     })
 }
 
+/// Run one gate. Its dependencies are not started: their receipts for the
+/// current commit are read from the evidence store, and a dependency without a
+/// PASS receipt makes this gate NOT_RUN (ADR row 5).
+pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result<Outcome, RunError> {
+    let bytes = fs::read(manifest_path)
+        .map_err(|e| RunError::Fatal(format!("cannot read manifest: {e}")))?;
+    let m = manifest::parse(&bytes).map_err(|e| RunError::BadManifest(e.0))?;
+    let deps = if m.depends_on.is_empty() {
+        Vec::new()
+    } else {
+        let commit = head(root).map_err(RunError::Fatal)?;
+        Index::load(&Store::new(&opts.evidence_dir)).dep_facts(&m.depends_on, &commit)
+    };
+    let job = Job {
+        root,
+        manifest_path,
+        m: &m,
+        opts,
+        deps,
+        pool_wait_ms: 0,
+    };
+    execute_gate(&job, None)
+}
+
+/// The result of a graph run: one outcome per selected gate, in topological
+/// order (a gate always comes after the gates it depends on).
+#[derive(Debug, Clone)]
+pub struct Campaign {
+    pub results: Vec<(String, Outcome)>,
+}
+
+impl Campaign {
+    /// ADR 0028 exit rule: any FAIL is FAIL, else the worst of the other
+    /// non-PASS verdicts, else PASS.
+    pub fn verdict(&self) -> Verdict {
+        let all: Vec<Verdict> = self.results.iter().map(|(_, o)| o.verdict).collect();
+        campaign_verdict(&all)
+    }
+
+    pub fn exit_code(&self) -> i32 {
+        self.verdict().exit_code()
+    }
+}
+
+/// What the scheduler shares between worker threads.
+struct Sched {
+    /// Selected gates whose dependencies have all finished and that have not
+    /// started.
+    ready: BTreeSet<usize>,
+    /// Per gate: selected dependencies that have not finished yet.
+    waiting_on: Vec<usize>,
+    /// When each gate became ready (for `pool_wait_ms`).
+    ready_at: Vec<Option<Instant>>,
+    results: Vec<Option<Outcome>>,
+    /// Selected gates that have not finished.
+    remaining: usize,
+    /// The first fatal error; it stops the campaign.
+    error: Option<RunError>,
+}
+
+/// A gate chosen to start, with the facts about its dependencies and the pool
+/// slot it holds (None when it cannot run, so it needs no slot).
+struct Pick<'a> {
+    node: usize,
+    deps: Vec<DepFact>,
+    permit: Option<Permit<'a>>,
+}
+
+struct GraphRun<'a> {
+    root: &'a Path,
+    graph: &'a Graph,
+    selection: &'a BTreeSet<usize>,
+    opts: &'a Options,
+    pools: Pools,
+    state: Mutex<Sched>,
+    cv: Condvar,
+    /// Facts about dependencies outside the selection, read from the store.
+    outside: BTreeMap<String, DepFact>,
+}
+
+fn pool_of(m: &Manifest) -> Pool {
+    Pool::from_name(m.pool()).unwrap_or(Pool::Host)
+}
+
+impl GraphRun<'_> {
+    fn dep_facts(&self, results: &[Option<Outcome>], node: usize) -> Vec<DepFact> {
+        self.graph
+            .node(node)
+            .manifest
+            .depends_on
+            .iter()
+            .map(|id| {
+                let finished = self.graph.index_of(id).and_then(|d| results[d].as_ref());
+                match finished {
+                    Some(o) => DepFact {
+                        gate: id.clone(),
+                        verdict: Some(o.verdict),
+                        receipt: o.receipt_digest.clone(),
+                    },
+                    None => self.outside.get(id).cloned().unwrap_or_else(|| DepFact {
+                        gate: id.clone(),
+                        verdict: None,
+                        receipt: None,
+                    }),
+                }
+            })
+            .collect()
+    }
+
+    /// Choose a ready gate that can start now. A gate whose dependencies are
+    /// not all PASS cannot run, so it needs no pool slot and goes first; any
+    /// other gate needs a free slot in its pool, and if there is none the
+    /// next ready gate is tried (so a busy gb10 pool never holds up host
+    /// work). Called with the scheduler lock held.
+    fn pick(&self, st: &mut Sched) -> Option<Pick<'_>> {
+        let mut chosen = None;
+        for &i in &st.ready {
+            let deps = self.dep_facts(&st.results, i);
+            if !deps.iter().all(|d| d.verdict == Some(Verdict::Pass)) {
+                chosen = Some(Pick {
+                    node: i,
+                    deps,
+                    permit: None,
+                });
+                break;
+            }
+            let pool = pool_of(&self.graph.node(i).manifest);
+            if let Some(permit) = self.pools.try_acquire(pool) {
+                chosen = Some(Pick {
+                    node: i,
+                    deps,
+                    permit: Some(permit),
+                });
+                break;
+            }
+        }
+        if let Some(p) = &chosen {
+            st.ready.remove(&p.node);
+        }
+        chosen
+    }
+
+    fn worker(&self) {
+        loop {
+            let (pick, waited_ms) = {
+                let mut st = lock(&self.state);
+                let pick = loop {
+                    if st.remaining == 0 || st.error.is_some() {
+                        return;
+                    }
+                    if let Some(p) = self.pick(&mut st) {
+                        break p;
+                    }
+                    st = self.cv.wait(st).unwrap_or_else(|e| e.into_inner());
+                };
+                let waited = st.ready_at[pick.node].map_or(0, |t| t.elapsed().as_millis() as u64);
+                (pick, waited)
+            };
+            let i = pick.node;
+            let node = self.graph.node(i);
+            let job = Job {
+                root: self.root,
+                manifest_path: &node.path,
+                m: &node.manifest,
+                opts: self.opts,
+                deps: pick.deps,
+                pool_wait_ms: waited_ms,
+            };
+            let permit = pick.permit;
+            let ran = catch_unwind(AssertUnwindSafe(|| execute_gate(&job, permit)));
+            let outcome = match ran {
+                Ok(r) => r,
+                Err(_) => Err(RunError::Fatal(format!(
+                    "internal error while running gate {}",
+                    node.id
+                ))),
+            };
+            let mut st = lock(&self.state);
+            match outcome {
+                Ok(o) => {
+                    st.results[i] = Some(o);
+                    st.remaining = st.remaining.saturating_sub(1);
+                    for &d in self.graph.direct_dependents(i) {
+                        if self.selection.contains(&d) {
+                            st.waiting_on[d] = st.waiting_on[d].saturating_sub(1);
+                            if st.waiting_on[d] == 0 {
+                                st.ready.insert(d);
+                                st.ready_at[d] = Some(Instant::now());
+                            }
+                        }
+                    }
+                }
+                Err(e) => {
+                    if st.error.is_none() {
+                        st.error = Some(e);
+                    }
+                }
+            }
+            drop(st);
+            // The permit went back inside `execute_gate`, so waiting workers
+            // can use the slot as soon as they wake.
+            self.cv.notify_all();
+        }
+    }
+}
+
+/// Run the gates in `selection` (node numbers of `graph`) with worker threads.
+/// A gate starts when every selected gate it depends on has finished and its
+/// pool has a free slot (host, qemu, or gb10 with the GPU locks). A gate whose
+/// dependency did not PASS is not started: it gets a receipt saying NOT_RUN,
+/// or the blocked verdict of the dependency (ADR rows 4 and 5). `selection`
+/// should include the dependencies of its members; one that is left out is
+/// looked up in the evidence store for the current commit.
+pub fn run_graph(
+    root: &Path,
+    graph: &Graph,
+    selection: &BTreeSet<usize>,
+    opts: &Options,
+) -> Result<Campaign, RunError> {
+    if selection.is_empty() {
+        return Ok(Campaign {
+            results: Vec::new(),
+        });
+    }
+    let commit = head(root).map_err(RunError::Fatal)?;
+    let index = Index::load(&Store::new(&opts.evidence_dir));
+    let start = Instant::now();
+
+    let mut outside: BTreeMap<String, DepFact> = BTreeMap::new();
+    let mut waiting_on = vec![0usize; graph.len()];
+    let mut ready: BTreeSet<usize> = BTreeSet::new();
+    let mut ready_at: Vec<Option<Instant>> = vec![None; graph.len()];
+    for &i in selection {
+        for &d in &graph.node(i).deps {
+            if selection.contains(&d) {
+                waiting_on[i] += 1;
+            } else {
+                let id = graph.node(d).id.clone();
+                let facts = index.dep_facts(std::slice::from_ref(&id), &commit);
+                if let Some(f) = facts.into_iter().next() {
+                    outside.insert(id, f);
+                }
+            }
+        }
+        if waiting_on[i] == 0 {
+            ready.insert(i);
+            ready_at[i] = Some(start);
+        }
+    }
+
+    let run = GraphRun {
+        root,
+        graph,
+        selection,
+        opts,
+        pools: Pools::new(opts.pool_sizes),
+        state: Mutex::new(Sched {
+            ready,
+            waiting_on,
+            ready_at,
+            results: vec![None; graph.len()],
+            remaining: selection.len(),
+            error: None,
+        }),
+        cv: Condvar::new(),
+        outside,
+    };
+
+    // Enough workers for every slot of every pool to be busy at once.
+    let workers = (opts.pool_sizes.host + opts.pool_sizes.qemu + 1)
+        .min(selection.len())
+        .max(1);
+    thread::scope(|s| {
+        for _ in 0..workers {
+            s.spawn(|| run.worker());
+        }
+    });
+
+    let mut st = lock(&run.state);
+    if let Some(e) = st.error.take() {
+        return Err(e);
+    }
+    let mut results = Vec::with_capacity(selection.len());
+    for &i in graph.order() {
+        if !selection.contains(&i) {
+            continue;
+        }
+        let id = &graph.node(i).id;
+        match st.results[i].take() {
+            Some(o) => results.push((id.clone(), o)),
+            None => return Err(RunError::Fatal(format!("no result for gate {id}"))),
+        }
+    }
+    Ok(Campaign { results })
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -567,6 +953,11 @@ mod tests {
         fn opts(&self) -> Options {
             let mut o = Options::new(self.ev.path().join("out"));
             o.kill_grace = Duration::from_millis(300);
+            o.hardware = Hardware {
+                gb10_present: false,
+                qemu_available: false,
+            };
+            o.gpu = GpuConfig::rooted_at(self.scratch.path());
             o
         }
     }
@@ -637,6 +1028,7 @@ mod tests {
         assert_eq!(core["binary_sha256"], sha256_hex(&script_bytes));
         let gate_bytes = fs::read(fx.manifest()).unwrap();
         assert_eq!(core["manifest_digest"], sha256_hex(&gate_bytes));
+        assert_eq!(core["dependencies"], json!([]));
         assert_eq!(r["volatile"]["pool"], "host");
         assert_eq!(r["volatile"]["timeout_exceeded"], false);
         // Receipt is read-only and named by its digest.
@@ -824,7 +1216,7 @@ mod tests {
     }
 
     #[test]
-    fn operator_and_other_pool_gates_do_not_run() {
+    fn operator_and_missing_hardware_gates_do_not_run() {
         let fx = ok_fixture();
         let gate = fs::read_to_string(fx.manifest()).unwrap();
         write_file(
@@ -849,7 +1241,7 @@ mod tests {
         let o = run(&fx, &fx.opts());
         assert_eq!(
             (o.verdict, o.reason.as_str()),
-            (Verdict::NotRun, "pool_unsupported:gb10")
+            (Verdict::BlockedHardware, "NO_GB10")
         );
         assert!(!fx.marker().exists());
     }
@@ -943,4 +1335,458 @@ mod tests {
         let p = resolve(&t.path().join("a/b/../c"));
         assert_eq!(p, t.path().join("a/c"));
     }
+
+    // ---- Slice B: pools, dependencies, graph runs ----
+
+    fn gb10_fixture(script: &str, timeout: &str) -> Fx {
+        let fx = fixture(script, 0, &[], timeout, "");
+        let gate = fs::read_to_string(fx.manifest()).unwrap();
+        write_file(
+            fx.repo.path(),
+            "tests/t.gate",
+            &gate.replace("  - host\n", "  - gb10\n"),
+            false,
+        );
+        git(fx.repo.path(), &["add", "-A"]);
+        git(fx.repo.path(), &["commit", "-q", "-m", "gb10"]);
+        fx
+    }
+
+    fn gb10_opts(fx: &Fx) -> Options {
+        let mut o = fx.opts();
+        o.hardware.gb10_present = true;
+        o
+    }
+
+    const TOUCH_MARKER: &str = "#!/bin/sh\ntouch \"$1\"\n";
+
+    #[test]
+    fn gb10_gate_runs_under_the_gpu_lock_and_records_its_pool() {
+        let fx = gb10_fixture(TOUCH_MARKER, "20s");
+        let opts = gb10_opts(&fx);
+        let o = run(&fx, &opts);
+        assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason);
+        assert!(fx.marker().exists());
+        let r = read_json(&o.receipt_path.unwrap());
+        assert_eq!(r["volatile"]["pool"], "gb10");
+        assert_eq!(r["volatile"]["timeout_exceeded"], false);
+        assert_eq!(r["core"]["machine"]["gb10_present"], true);
+        assert!(opts.gpu.lock_path.exists(), "the lock file is created");
+        assert!(
+            acquire_gpu(&opts.gpu).is_ok(),
+            "the lock is released after the job"
+        );
+    }
+
+    #[test]
+    fn gb10_gate_without_the_hardware_is_blocked() {
+        let fx = gb10_fixture(TOUCH_MARKER, "20s");
+        let o = run(&fx, &fx.opts());
+        assert_eq!(
+            (o.verdict, o.reason.as_str()),
+            (Verdict::BlockedHardware, "NO_GB10")
+        );
+        assert!(!fx.marker().exists());
+    }
+
+    #[test]
+    fn gb10_gate_is_refused_while_the_quiet_flag_exists() {
+        let fx = gb10_fixture(TOUCH_MARKER, "20s");
+        let opts = gb10_opts(&fx);
+        let flag = opts.gpu.quiet_flag.clone().unwrap();
+        fs::write(&flag, "hold: testing\n").unwrap();
+        let o = run(&fx, &opts);
+        assert_eq!(
+            (o.verdict, o.reason.as_str()),
+            (Verdict::NotRun, "quiet_flag")
+        );
+        assert!(!fx.marker().exists());
+        assert_eq!(fs::read_to_string(&flag).unwrap(), "hold: testing\n");
+        let r = read_json(&o.receipt_path.unwrap());
+        assert_eq!(r["core"]["reason"], "quiet_flag");
+    }
+
+    #[test]
+    fn gb10_gate_is_refused_while_another_holder_has_the_lock() {
+        let fx = gb10_fixture(TOUCH_MARKER, "20s");
+        let opts = gb10_opts(&fx);
+        let held = acquire_gpu(&opts.gpu).unwrap();
+        let o = run(&fx, &opts);
+        assert_eq!(
+            (o.verdict, o.reason.as_str()),
+            (Verdict::NotRun, "gpu_lock")
+        );
+        assert!(!fx.marker().exists(), "a refused job must not run");
+        drop(held);
+        let o = run(&fx, &opts);
+        assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason);
+        assert!(fx.marker().exists());
+    }
+
+    #[test]
+    fn gb10_timeout_is_advisory_and_never_kills_the_job() {
+        let fx = gb10_fixture("#!/bin/sh\nsleep 1\ntouch \"$1\"\n", "300ms");
+        let o = run(&fx, &gb10_opts(&fx));
+        assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason);
+        assert!(fx.marker().exists(), "the job must be left to finish");
+        let r = read_json(&o.receipt_path.unwrap());
+        assert_eq!(r["volatile"]["timeout_exceeded"], true);
+    }
+
+    /// `(gate id, depends_on ids separated by spaces, requires, script)`.
+    type GateSpec = (&'static str, &'static str, &'static str, String);
+
+    fn graph_gate_text(id: &str, deps: &str, requires: &str) -> String {
+        let dep_block = if deps.trim().is_empty() {
+            String::new()
+        } else {
+            format!(
+                "depends_on:\n{}",
+                deps.split_whitespace()
+                    .map(|d| format!("  - {d}\n"))
+                    .collect::<String>()
+            )
+        };
+        format!(
+            "gate: {id}\nmanifest_version: 1\nowner: t\nrequires:\n  - {requires}\nrun:\n  exec: tools/{id}.sh\n  args: []\nexpects:\n  exit: 0\n  observe: []\n  verdict: PASS\ntimeout: 20s\n{dep_block}"
+        )
+    }
+
+    /// Script that appends `ran-<id>` to the shared log and exits with `exit`.
+    fn logging(id: &str, exit: i32) -> String {
+        format!("#!/bin/sh\necho ran-{id} >> \"@S@/log\"\nexit {exit}\n")
+    }
+
+    /// Script that logs `start-<id>`, takes a moment, then logs `end-<id>`.
+    fn slow(id: &str) -> String {
+        format!(
+            "#!/bin/sh\necho start-{id} >> \"@S@/log\"\nsleep 0.2\necho end-{id} >> \"@S@/log\"\n"
+        )
+    }
+
+    /// Script that proves another job is running at the same time: it waits
+    /// (at most about ten seconds) for the other script's start marker.
+    fn rendezvous(me: &str, other: &str) -> String {
+        format!(
+            "#!/bin/sh\ntouch \"@S@/started-{me}\"\ni=0\nwhile [ ! -f \"@S@/started-{other}\" ] && [ $i -lt 100 ]; do sleep 0.1; i=$((i+1)); done\nif [ -f \"@S@/started-{other}\" ]; then touch \"@S@/saw-{me}\"; fi\n"
+        )
+    }
+
+    struct Gfx {
+        repo: TempDir,
+        ev: TempDir,
+        scratch: TempDir,
+    }
+
+    /// A repository with one gate (tests/<id>.gate) and script
+    /// (tools/<id>.sh) per entry; `@S@` in a script is the scratch directory.
+    fn gfx(gates: &[GateSpec]) -> Gfx {
+        let scratch = TempDir::new("gscratch");
+        let s = scratch.path().to_str().unwrap().to_string();
+        let mut files: Vec<(String, String, bool)> = Vec::new();
+        for (id, deps, requires, script) in gates {
+            files.push((format!("tools/{id}.sh"), script.replace("@S@", &s), true));
+            files.push((
+                format!("tests/{id}.gate"),
+                graph_gate_text(id, deps, requires),
+                false,
+            ));
+        }
+        let refs: Vec<(&str, &str, bool)> = files
+            .iter()
+            .map(|(p, c, x)| (p.as_str(), c.as_str(), *x))
+            .collect();
+        let repo = init_repo("grepo", &refs);
+        Gfx {
+            repo,
+            ev: TempDir::new("gev"),
+            scratch,
+        }
+    }
+
+    impl Gfx {
+        fn gate_path(&self, id: &str) -> PathBuf {
+            self.repo.path().join(format!("tests/{id}.gate"))
+        }
+
+        fn opts(&self) -> Options {
+            let mut o = Options::new(self.ev.path().join("out"));
+            o.kill_grace = Duration::from_millis(300);
+            o.hardware = Hardware {
+                gb10_present: false,
+                qemu_available: false,
+            };
+            o.gpu = GpuConfig::rooted_at(self.scratch.path());
+            o.pool_sizes = PoolSizes { host: 2, qemu: 1 };
+            o
+        }
+
+        fn graph(&self) -> Graph {
+            crate::graph::load(self.repo.path()).unwrap()
+        }
+
+        fn campaign(&self, opts: &Options) -> Campaign {
+            let g = self.graph();
+            let all: BTreeSet<usize> = (0..g.len()).collect();
+            run_graph(self.repo.path(), &g, &all, opts).unwrap()
+        }
+
+        fn log(&self) -> Vec<String> {
+            fs::read_to_string(self.scratch.path().join("log"))
+                .unwrap_or_default()
+                .lines()
+                .map(|l| l.to_string())
+                .collect()
+        }
+    }
+
+    fn outcome<'a>(c: &'a Campaign, id: &str) -> &'a Outcome {
+        &c.results
+            .iter()
+            .find(|(g, _)| g == id)
+            .expect("gate is in the campaign")
+            .1
+    }
+
+    fn verdict_and_reason<'a>(c: &'a Campaign, id: &str) -> (Verdict, &'a str) {
+        let o = outcome(c, id);
+        (o.verdict, o.reason.as_str())
+    }
+
+    #[test]
+    fn a_chain_runs_in_order_and_each_receipt_names_its_dependencies() {
+        let fx = gfx(&[
+            ("G-A", "", "host", logging("G-A", 0)),
+            ("G-B", "G-A", "host", logging("G-B", 0)),
+            ("G-C", "G-B", "host", logging("G-C", 0)),
+        ]);
+        let c = fx.campaign(&fx.opts());
+        assert_eq!(c.exit_code(), 0);
+        let ids: Vec<&str> = c.results.iter().map(|(g, _)| g.as_str()).collect();
+        assert_eq!(ids, vec!["G-A", "G-B", "G-C"]);
+        assert!(c.results.iter().all(|(_, o)| o.verdict == Verdict::Pass));
+        assert_eq!(fx.log(), vec!["ran-G-A", "ran-G-B", "ran-G-C"]);
+        let a = outcome(&c, "G-A").receipt_digest.clone().unwrap();
+        let ra = read_json(outcome(&c, "G-A").receipt_path.as_ref().unwrap());
+        let rb = read_json(outcome(&c, "G-B").receipt_path.as_ref().unwrap());
+        assert_eq!(ra["core"]["dependencies"], json!([]));
+        assert_eq!(
+            rb["core"]["dependencies"],
+            json!([{ "gate": "G-A", "receipt": a }])
+        );
+        assert!(rb["volatile"]["pool_wait_ms"].is_u64());
+    }
+
+    #[test]
+    fn a_failed_dependency_makes_dependents_not_run_with_the_reason_recorded() {
+        let fx = gfx(&[
+            ("G-A", "", "host", logging("G-A", 1)),
+            ("G-B", "G-A", "host", logging("G-B", 0)),
+            ("G-C", "G-B", "host", logging("G-C", 0)),
+            ("G-D", "", "host", logging("G-D", 0)),
+        ]);
+        let c = fx.campaign(&fx.opts());
+        assert_eq!(verdict_and_reason(&c, "G-A"), (Verdict::Fail, "rc_nonzero"));
+        assert_eq!(
+            verdict_and_reason(&c, "G-B"),
+            (Verdict::NotRun, "DEP_NOT_PASS:G-A")
+        );
+        assert_eq!(
+            verdict_and_reason(&c, "G-C"),
+            (Verdict::NotRun, "DEP_NOT_PASS:G-B")
+        );
+        assert_eq!(verdict_and_reason(&c, "G-D"), (Verdict::Pass, ""));
+        assert_eq!(c.exit_code(), 1);
+        let mut log = fx.log();
+        log.sort();
+        assert_eq!(log, vec!["ran-G-A", "ran-G-D"], "B and C must not run");
+        let a = outcome(&c, "G-A").receipt_digest.clone().unwrap();
+        let rb = read_json(outcome(&c, "G-B").receipt_path.as_ref().unwrap());
+        assert_eq!(rb["core"]["derived_verdict"], "NOT_RUN");
+        assert_eq!(rb["core"]["reason"], "DEP_NOT_PASS:G-A");
+        assert_eq!(rb["core"]["exit_status"], Value::Null);
+        assert_eq!(
+            rb["core"]["dependencies"],
+            json!([{ "gate": "G-A", "receipt": a }])
+        );
+    }
+
+    #[test]
+    fn a_blocked_dependency_blocks_its_dependents_the_same_way() {
+        let fx = gfx(&[
+            ("G-A", "", "gb10", logging("G-A", 0)),
+            ("G-B", "G-A", "host", logging("G-B", 0)),
+            ("G-C", "G-B", "host", logging("G-C", 0)),
+        ]);
+        let c = fx.campaign(&fx.opts());
+        assert_eq!(
+            verdict_and_reason(&c, "G-A"),
+            (Verdict::BlockedHardware, "NO_GB10")
+        );
+        assert_eq!(
+            verdict_and_reason(&c, "G-B"),
+            (Verdict::BlockedHardware, "DEP_BLOCKED:G-A")
+        );
+        assert_eq!(
+            verdict_and_reason(&c, "G-C"),
+            (Verdict::BlockedHardware, "DEP_BLOCKED:G-B")
+        );
+        assert!(fx.log().is_empty(), "nothing may run");
+        assert_eq!(c.exit_code(), 3);
+    }
+
+    #[test]
+    fn independent_gates_run_at_the_same_time_when_the_pool_allows() {
+        let fx = gfx(&[
+            ("G-A", "", "host", rendezvous("a", "b")),
+            ("G-B", "", "host", rendezvous("b", "a")),
+        ]);
+        let c = fx.campaign(&fx.opts());
+        assert_eq!(c.exit_code(), 0);
+        assert!(fx.scratch.path().join("saw-a").exists(), "A never saw B");
+        assert!(fx.scratch.path().join("saw-b").exists(), "B never saw A");
+    }
+
+    #[test]
+    fn a_pool_of_one_runs_gates_one_at_a_time() {
+        let fx = gfx(&[
+            ("G-A", "", "host", slow("G-A")),
+            ("G-B", "", "host", slow("G-B")),
+            ("G-C", "", "host", slow("G-C")),
+        ]);
+        let mut opts = fx.opts();
+        opts.pool_sizes = PoolSizes { host: 1, qemu: 1 };
+        let c = fx.campaign(&opts);
+        assert_eq!(c.exit_code(), 0);
+        let log = fx.log();
+        assert_eq!(log.len(), 6, "{log:?}");
+        for pair in log.chunks(2) {
+            assert!(pair[0].starts_with("start-"), "{log:?}");
+            assert_eq!(pair[1], pair[0].replacen("start-", "end-", 1), "{log:?}");
+        }
+    }
+
+    #[test]
+    fn gb10_and_host_gates_run_together_and_record_their_pools() {
+        let fx = gfx(&[
+            ("G-A", "", "gb10", logging("G-A", 0)),
+            ("G-B", "", "host", logging("G-B", 0)),
+        ]);
+        let mut opts = fx.opts();
+        opts.hardware.gb10_present = true;
+        let c = fx.campaign(&opts);
+        assert_eq!(c.exit_code(), 0);
+        let r = read_json(outcome(&c, "G-A").receipt_path.as_ref().unwrap());
+        assert_eq!(r["volatile"]["pool"], "gb10");
+        let r = read_json(outcome(&c, "G-B").receipt_path.as_ref().unwrap());
+        assert_eq!(r["volatile"]["pool"], "host");
+    }
+
+    #[test]
+    fn a_held_gpu_lock_refuses_the_gb10_gate_and_its_dependents_do_not_run() {
+        let fx = gfx(&[
+            ("G-A", "", "gb10", logging("G-A", 0)),
+            ("G-B", "G-A", "host", logging("G-B", 0)),
+        ]);
+        let mut opts = fx.opts();
+        opts.hardware.gb10_present = true;
+        let held = acquire_gpu(&opts.gpu).unwrap();
+        let c = fx.campaign(&opts);
+        drop(held);
+        assert_eq!(verdict_and_reason(&c, "G-A"), (Verdict::NotRun, "gpu_lock"));
+        assert_eq!(
+            verdict_and_reason(&c, "G-B"),
+            (Verdict::NotRun, "DEP_NOT_PASS:G-A")
+        );
+        assert!(fx.log().is_empty());
+        assert_eq!(c.exit_code(), 2);
+    }
+
+    #[test]
+    fn run_gate_reads_dependency_receipts_from_the_store() {
+        let fx = gfx(&[
+            ("G-A", "", "host", logging("G-A", 0)),
+            ("G-B", "G-A", "host", logging("G-B", 0)),
+        ]);
+        let opts = fx.opts();
+        let run_one = |id: &str| run_gate(fx.repo.path(), &fx.gate_path(id), &opts).unwrap();
+        let o = run_one("G-B");
+        assert_eq!(
+            (o.verdict, o.reason.as_str()),
+            (Verdict::NotRun, "DEP_NOT_PASS:G-A")
+        );
+        assert!(fx.log().is_empty(), "no receipt for A, so B must not run");
+        assert_eq!(run_one("G-A").verdict, Verdict::Pass);
+        let o = run_one("G-B");
+        assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason);
+        assert_eq!(fx.log(), vec!["ran-G-A", "ran-G-B"]);
+        // A receipt for an older commit does not count.
+        git(
+            fx.repo.path(),
+            &["commit", "-q", "--allow-empty", "-m", "next"],
+        );
+        let o = run_one("G-B");
+        assert_eq!(
+            (o.verdict, o.reason.as_str()),
+            (Verdict::NotRun, "DEP_NOT_PASS:G-A")
+        );
+        assert_eq!(fx.log().len(), 2);
+    }
+
+    #[test]
+    fn a_dependency_outside_the_selection_comes_from_the_store() {
+        let fx = gfx(&[
+            ("G-A", "", "host", logging("G-A", 0)),
+            ("G-B", "G-A", "host", logging("G-B", 0)),
+        ]);
+        let opts = fx.opts();
+        let g = fx.graph();
+        let only_b: BTreeSet<usize> = [g.index_of("G-B").unwrap()].into_iter().collect();
+        let c = run_graph(fx.repo.path(), &g, &only_b, &opts).unwrap();
+        assert_eq!(c.results.len(), 1);
+        assert_eq!(
+            verdict_and_reason(&c, "G-B"),
+            (Verdict::NotRun, "DEP_NOT_PASS:G-A")
+        );
+        let a = run_gate(fx.repo.path(), &fx.gate_path("G-A"), &opts).unwrap();
+        assert_eq!(a.verdict, Verdict::Pass);
+        let c = run_graph(fx.repo.path(), &g, &only_b, &opts).unwrap();
+        assert_eq!(verdict_and_reason(&c, "G-B"), (Verdict::Pass, ""));
+    }
+
+    #[test]
+    fn an_empty_selection_is_an_empty_campaign() {
+        let fx = gfx(&[("G-A", "", "host", logging("G-A", 0))]);
+        let g = fx.graph();
+        let c = run_graph(fx.repo.path(), &g, &BTreeSet::new(), &fx.opts()).unwrap();
+        assert!(c.results.is_empty());
+        assert_eq!(c.exit_code(), 0);
+    }
+
+    #[test]
+    fn a_fatal_error_stops_the_campaign_instead_of_hanging() {
+        let fx = gfx(&[
+            ("G-A", "", "host", logging("G-A", 0)),
+            ("G-B", "G-A", "host", logging("G-B", 0)),
+            ("G-C", "", "host", logging("G-C", 0)),
+        ]);
+        let blocker = fx.scratch.path().join("not-a-directory");
+        fs::write(&blocker, "x").unwrap();
+        let mut opts = fx.opts();
+        opts.evidence_dir = blocker.join("out");
+        let g = fx.graph();
+        let all: BTreeSet<usize> = (0..g.len()).collect();
+        match run_graph(fx.repo.path(), &g, &all, &opts) {
+            Err(RunError::Fatal(_)) => {}
+            other => panic!("expected a fatal error, got {other:?}"),
+        }
+    }
+
+    #[test]
+    fn default_evidence_dir_is_named_after_the_repository() {
+        let p = default_evidence_dir(Path::new("/some/where/my-repo"));
+        if let Some(p) = p {
+            assert!(p.ends_with("workspace/evidence-out/my-repo"), "{p:?}");
+        }
+    }
 }
diff --git a/tools/aien-test/src/testutil.rs b/tools/aien-test/src/testutil.rs
index 8099aaf8..7c52eb79 100644
--- a/tools/aien-test/src/testutil.rs
+++ b/tools/aien-test/src/testutil.rs
@@ -40,8 +40,8 @@ impl Drop for TempDir {
 }
 
 pub fn git(dir: &Path, args: &[&str]) {
-    let out = Command::new("git")
-        .arg("-C")
+    let mut cmd = Command::new("git");
+    cmd.arg("-C")
         .arg(dir)
         .args([
             "-c",
@@ -51,9 +51,9 @@ pub fn git(dir: &Path, args: &[&str]) {
             "-c",
             "commit.gpgsign=false",
         ])
-        .args(args)
-        .output()
-        .expect("run git");
+        .args(args);
+    // Gated like every spawn: see `process::SPAWN_GATE`.
+    let out = crate::process::output_gated(&mut cmd).expect("run git");
     assert!(
         out.status.success(),
         "git {:?} failed: {}",
diff --git a/tools/aien-test/src/verdict.rs b/tools/aien-test/src/verdict.rs
index e92a20bb..baf79a44 100644
--- a/tools/aien-test/src/verdict.rs
+++ b/tools/aien-test/src/verdict.rs
@@ -3,10 +3,11 @@
 //! expectations and facts the runner measured. Only the last row can yield
 //! PASS.
 //!
-//! Slice A scope (host pool, serial, one gate): rows 2 to 15 are implemented
-//! as below. Where Slice A cannot do what a row presumes (dependencies, other
-//! pools, build, symbol checks, operator attestations) it refuses with NOT_RUN
-//! or BLOCKED_OPERATOR and a reason code; it never guesses a PASS.
+//! Scope (Slice B): rows 2 to 15 are implemented as below, including the
+//! hardware verdict (row 3) and the dependency verdicts (rows 4 and 5). Where
+//! the runner still cannot do what a row presumes (build, symbol checks,
+//! operator attestations) it refuses with NOT_RUN or BLOCKED_OPERATOR and a
+//! reason code; it never guesses a PASS.
 //!
 //! Deviation from the ADR table order (recorded): timeout (row 14) is tested
 //! before the exit status (row 10), because a killed process has no exit code
@@ -26,6 +27,20 @@ pub enum Verdict {
 }
 
 impl Verdict {
+    pub const ALL: [Verdict; 6] = [
+        Verdict::Pass,
+        Verdict::Fail,
+        Verdict::NotRun,
+        Verdict::BlockedHardware,
+        Verdict::BlockedOperator,
+        Verdict::MissingImplementation,
+    ];
+
+    /// The verdict with this exact name, as written by `as_str`.
+    pub fn parse(s: &str) -> Option<Verdict> {
+        Verdict::ALL.into_iter().find(|v| v.as_str() == s)
+    }
+
     pub fn as_str(self) -> &'static str {
         match self {
             Verdict::Pass => "PASS",
@@ -51,6 +66,20 @@ impl Verdict {
     }
 }
 
+/// The verdict of a campaign of gates: any FAIL makes it FAIL, otherwise the
+/// highest-numbered of NOT_RUN, BLOCKED_HARDWARE, BLOCKED_OPERATOR and
+/// MISSING_IMPLEMENTATION (ADR 0028 Decision 5), otherwise PASS. An empty list
+/// is PASS here; a caller that ran nothing must say so itself.
+pub fn campaign_verdict(vs: &[Verdict]) -> Verdict {
+    if vs.contains(&Verdict::Fail) {
+        return Verdict::Fail;
+    }
+    vs.iter()
+        .copied()
+        .max_by_key(|v| v.exit_code())
+        .unwrap_or(Verdict::Pass)
+}
+
 #[derive(Debug, Clone, PartialEq)]
 pub struct Observation {
     pub name: String,
@@ -116,6 +145,20 @@ pub fn eval_rule(rule: &Rule, obs: &[Observation]) -> bool {
     }
 }
 
+/// What the runner knows about one dependency of a gate: its current verdict
+/// (None when there is no usable receipt: absent, or not for this commit) and
+/// the receipt that verdict came from.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DepFact {
+    pub gate: String,
+    pub verdict: Option<Verdict>,
+    pub receipt: Option<String>,
+}
+
+fn dep_verdict(deps: &[DepFact], gate: &str) -> Option<Verdict> {
+    deps.iter().find(|d| d.gate == gate).and_then(|d| d.verdict)
+}
+
 /// Facts the runner measured. For a gate that did not run, `exit_status` is
 /// None and `observations` is empty.
 #[derive(Debug, Clone, Default)]
@@ -123,6 +166,12 @@ pub struct Facts {
     /// Refusal id decided before running (dirty_tree, evidence_inside, ...).
     pub refusal: Option<String>,
     pub exec_exists: bool,
+    /// Current verdicts of the gate's `depends_on` gates. A dependency with no
+    /// entry here counts as having no verdict.
+    pub deps: Vec<DepFact>,
+    /// `machine.gb10_present` and `machine.qemu_available` (row 3).
+    pub gb10_present: bool,
+    pub qemu_available: bool,
     pub exit_status: Option<i64>,
     pub observations: Vec<Observation>,
     pub timed_out: bool,
@@ -140,24 +189,39 @@ pub struct Derived {
 }
 
 /// Rows 2 to 7: decided before anything runs. Some(..) means do not run.
-pub fn pre_run(
-    m: &Manifest,
-    refusal: &Option<String>,
-    exec_exists: bool,
-) -> Option<(Verdict, String)> {
+pub fn pre_run(m: &Manifest, f: &Facts) -> Option<(Verdict, String)> {
     if m.requires.iter().any(|r| r == "operator") {
-        // Slice A has no operator attestation files, so this is always pending.
+        // There are no operator attestation files yet, so this is always pending.
         return Some((
             Verdict::BlockedOperator,
             "OPERATOR_STEP_PENDING".to_string(),
         ));
     }
-    if let Some(d) = m.depends_on.first() {
-        // Slice A has no dependency graph; it cannot show the dependency passed.
-        return Some((Verdict::NotRun, format!("DEP_NOT_PASS:{d}")));
+    // Row 3: the gate's pool needs hardware this machine does not have.
+    match m.pool() {
+        "gb10" if !f.gb10_present => {
+            return Some((Verdict::BlockedHardware, "NO_GB10".to_string()));
+        }
+        "qemu" if !f.qemu_available => {
+            return Some((Verdict::BlockedHardware, "NO_QEMU".to_string()));
+        }
+        _ => {}
+    }
+    // Row 4 before row 5: a blocked dependency passes its blocked verdict on.
+    for d in &m.depends_on {
+        if let Some(v @ (Verdict::BlockedHardware | Verdict::BlockedOperator)) =
+            dep_verdict(&f.deps, d)
+        {
+            return Some((v, format!("DEP_BLOCKED:{d}")));
+        }
     }
-    if m.pool() != "host" {
-        return Some((Verdict::NotRun, format!("pool_unsupported:{}", m.pool())));
+    // Row 5: every other dependency must currently be PASS.
+    if let Some(d) = m
+        .depends_on
+        .iter()
+        .find(|d| dep_verdict(&f.deps, d) != Some(Verdict::Pass))
+    {
+        return Some((Verdict::NotRun, format!("DEP_NOT_PASS:{d}")));
     }
     if let Some(b) = &m.build {
         if b.tool != "none" {
@@ -167,17 +231,17 @@ pub fn pre_run(
     if let Some(c) = m.checks.iter().find(|c| c.as_str() != "clean_tree_after") {
         return Some((Verdict::NotRun, format!("check_unsupported:{c}")));
     }
-    if let Some(r) = refusal {
+    if let Some(r) = &f.refusal {
         return Some((Verdict::NotRun, r.clone()));
     }
-    if !exec_exists {
+    if !f.exec_exists {
         return Some((Verdict::MissingImplementation, "NO_RUN_EXEC".to_string()));
     }
     None
 }
 
 pub fn derive(m: &Manifest, f: &Facts) -> Derived {
-    if let Some((verdict, reason)) = pre_run(m, &f.refusal, f.exec_exists) {
+    if let Some((verdict, reason)) = pre_run(m, f) {
         return Derived {
             verdict,
             reason,
@@ -237,6 +301,9 @@ mod tests {
         Facts {
             refusal: None,
             exec_exists: true,
+            deps: Vec::new(),
+            gb10_present: true,
+            qemu_available: true,
             exit_status: Some(0),
             observations: vec![obs("n", json!(3)), obs("k", json!(1)), obs("k", json!(2))],
             timed_out: false,
@@ -371,20 +438,194 @@ mod tests {
     }
 
     #[test]
-    fn other_pools_dependencies_build_and_checks_are_not_run() {
+    fn missing_hardware_blocks_the_gate() {
+        let mut f = good_facts();
         let g = m(Some(("  - host\n", "  - gb10\n")));
-        assert_eq!(derive(&g, &good_facts()).reason, "pool_unsupported:gb10");
+        assert_eq!(derive(&g, &f).verdict, Verdict::Pass);
+        f.gb10_present = false;
+        let d = derive(&g, &f);
+        assert_eq!(
+            (d.verdict, d.reason.as_str()),
+            (Verdict::BlockedHardware, "NO_GB10")
+        );
         let q = m(Some(("  - host\n", "  - qemu\n")));
-        assert_eq!(derive(&q, &good_facts()).reason, "pool_unsupported:qemu");
-        let d = m(Some((
-            "timeout: 5s\n",
-            "timeout: 5s\ndepends_on:\n  - OTHER\n",
-        )));
-        let r = derive(&d, &good_facts());
+        assert_eq!(
+            derive(&q, &f).verdict,
+            Verdict::Pass,
+            "gb10 is irrelevant to qemu"
+        );
+        f.qemu_available = false;
+        let d = derive(&q, &f);
+        assert_eq!(
+            (d.verdict, d.reason.as_str()),
+            (Verdict::BlockedHardware, "NO_QEMU")
+        );
+        // A host gate never needs the special hardware.
+        assert_eq!(derive(&m(None), &f).verdict, Verdict::Pass);
+        // gb10 beats qemu when both are listed (the scarcest pool decides).
+        let both = m(Some(("  - host\n", "  - qemu\n  - gb10\n")));
+        f.qemu_available = true;
+        assert_eq!(derive(&both, &f).reason, "NO_GB10");
+    }
+
+    fn dep(gate: &str, verdict: Option<Verdict>) -> DepFact {
+        DepFact {
+            gate: gate.to_string(),
+            verdict,
+            receipt: verdict.map(|_| format!("digest-of-{gate}")),
+        }
+    }
+
+    fn gate_with(requires: &str, deps: &str) -> Manifest {
+        let dep_block = if deps.is_empty() {
+            String::new()
+        } else {
+            format!("depends_on:\n{deps}")
+        };
+        let text = format!(
+            "gate: G\nmanifest_version: 1\nowner: o\nrequires:\n{requires}run:\n  exec: x.sh\nexpects:\n  exit: 0\n  observe: [\"n == 3\", \"all k <= 2\"]\n  verdict: PASS\ntimeout: 5s\n{dep_block}"
+        );
+        manifest::parse(text.as_bytes()).unwrap()
+    }
+
+    fn with_deps(list: &str) -> Manifest {
+        gate_with("  - host\n", list)
+    }
+
+    #[test]
+    fn a_passing_dependency_lets_the_gate_run() {
+        let mut f = good_facts();
+        f.deps = vec![dep("OTHER", Some(Verdict::Pass))];
+        let d = derive(&with_deps("  - OTHER\n"), &f);
+        assert_eq!(d.verdict, Verdict::Pass);
+    }
+
+    #[test]
+    fn a_dependency_that_is_not_pass_makes_not_run() {
+        let one = with_deps("  - OTHER\n");
+        let mut f = good_facts();
+        // No fact at all (absent or stale).
+        let r = derive(&one, &f);
         assert_eq!(
             (r.verdict, r.reason.as_str()),
             (Verdict::NotRun, "DEP_NOT_PASS:OTHER")
         );
+        for v in [
+            None,
+            Some(Verdict::Fail),
+            Some(Verdict::NotRun),
+            Some(Verdict::MissingImplementation),
+        ] {
+            f.deps = vec![dep("OTHER", v)];
+            let r = derive(&one, &f);
+            assert_eq!(
+                (r.verdict, r.reason.as_str()),
+                (Verdict::NotRun, "DEP_NOT_PASS:OTHER"),
+                "dependency verdict {v:?}"
+            );
+            assert!(r.rules.iter().all(|x| !x.1), "nothing was checked");
+        }
+    }
+
+    #[test]
+    fn the_first_dependency_that_is_not_pass_is_named() {
+        let two = with_deps("  - FIRST\n  - SECOND\n");
+        let mut f = good_facts();
+        f.deps = vec![dep("FIRST", Some(Verdict::Pass)), dep("SECOND", None)];
+        assert_eq!(derive(&two, &f).reason, "DEP_NOT_PASS:SECOND");
+        f.deps = vec![dep("FIRST", Some(Verdict::Fail)), dep("SECOND", None)];
+        assert_eq!(derive(&two, &f).reason, "DEP_NOT_PASS:FIRST");
+    }
+
+    #[test]
+    fn a_blocked_dependency_passes_its_verdict_on() {
+        let one = with_deps("  - OTHER\n");
+        let mut f = good_facts();
+        f.deps = vec![dep("OTHER", Some(Verdict::BlockedOperator))];
+        let r = derive(&one, &f);
+        assert_eq!(
+            (r.verdict, r.reason.as_str()),
+            (Verdict::BlockedOperator, "DEP_BLOCKED:OTHER")
+        );
+        f.deps = vec![dep("OTHER", Some(Verdict::BlockedHardware))];
+        let r = derive(&one, &f);
+        assert_eq!(
+            (r.verdict, r.reason.as_str()),
+            (Verdict::BlockedHardware, "DEP_BLOCKED:OTHER")
+        );
+    }
+
+    #[test]
+    fn blocked_beats_failed_across_dependencies() {
+        // Row 4 is checked before row 5, whatever the order in the manifest.
+        let two = with_deps("  - FAILED\n  - BLOCKED\n");
+        let mut f = good_facts();
+        f.deps = vec![
+            dep("FAILED", Some(Verdict::Fail)),
+            dep("BLOCKED", Some(Verdict::BlockedHardware)),
+        ];
+        let r = derive(&two, &f);
+        assert_eq!(
+            (r.verdict, r.reason.as_str()),
+            (Verdict::BlockedHardware, "DEP_BLOCKED:BLOCKED")
+        );
+    }
+
+    #[test]
+    fn rows_are_checked_in_order() {
+        let mut f = good_facts();
+        f.gb10_present = false;
+        f.refusal = Some("dirty_tree".to_string());
+        // Row 2 (operator) beats row 3 (hardware).
+        let op = gate_with("  - gb10\n  - operator\n", "  - OTHER\n");
+        assert_eq!(derive(&op, &f).reason, "OPERATOR_STEP_PENDING");
+        // Row 3 (hardware) beats rows 4 and 5 (dependencies).
+        let gb = gate_with("  - gb10\n", "  - OTHER\n");
+        assert_eq!(derive(&gb, &f).reason, "NO_GB10");
+        // Rows 4 and 5 beat the refusal (row 6).
+        let host = gate_with("  - host\n", "  - OTHER\n");
+        assert_eq!(derive(&host, &f).reason, "DEP_NOT_PASS:OTHER");
+        f.deps = vec![dep("OTHER", Some(Verdict::Pass))];
+        assert_eq!(derive(&host, &f).reason, "dirty_tree");
+        // Row 6 beats row 7.
+        f.exec_exists = false;
+        assert_eq!(derive(&host, &f).reason, "dirty_tree");
+        f.refusal = None;
+        assert_eq!(derive(&host, &f).reason, "NO_RUN_EXEC");
+    }
+
+    #[test]
+    fn campaign_verdict_follows_the_exit_code_rule() {
+        use Verdict::*;
+        assert_eq!(campaign_verdict(&[]), Pass);
+        assert_eq!(campaign_verdict(&[Pass, Pass]), Pass);
+        assert_eq!(campaign_verdict(&[Pass, NotRun]), NotRun);
+        assert_eq!(
+            campaign_verdict(&[NotRun, BlockedHardware]),
+            BlockedHardware
+        );
+        assert_eq!(
+            campaign_verdict(&[BlockedOperator, MissingImplementation, NotRun]),
+            MissingImplementation
+        );
+        // Any FAIL wins, even over the higher-numbered codes.
+        assert_eq!(campaign_verdict(&[MissingImplementation, Fail, Pass]), Fail);
+        assert_eq!(campaign_verdict(&[Fail]).exit_code(), 1);
+        assert_eq!(campaign_verdict(&[BlockedOperator, Pass]).exit_code(), 4);
+    }
+
+    #[test]
+    fn verdict_names_parse_back() {
+        for v in Verdict::ALL {
+            assert_eq!(Verdict::parse(v.as_str()), Some(v));
+        }
+        assert_eq!(Verdict::parse("pass"), None);
+        assert_eq!(Verdict::parse(""), None);
+        assert_eq!(Verdict::ALL.len(), 6);
+    }
+
+    #[test]
+    fn build_and_checks_are_not_run() {
         let b = m(Some((
             "timeout: 5s\n",
             "timeout: 5s\nbuild:\n  target: t\n  tool: make\n",
diff --git a/tools/aien-test/src/why.rs b/tools/aien-test/src/why.rs
new file mode 100644
index 00000000..d0a7fb55
--- /dev/null
+++ b/tools/aien-test/src/why.rs
@@ -0,0 +1,596 @@
+//! `aien-test why GATE`: the evidence chain behind one gate, read from the
+//! receipts already in the evidence store (ADR 0028 Decision 8).
+//!
+//! The report is plain lines, one fact per line, starting at the gate and
+//! walking down its dependencies. Each gate gets one state:
+//!
+//! - PASS: the newest receipt for this commit says PASS and everything the
+//!   gate depends on is PASS too.
+//! - FAILED: the newest receipt for this commit says FAIL.
+//! - BLOCKED: hardware or an operator step is missing.
+//! - MISSING IMPLEMENTATION: the gate has no `run.exec` to run.
+//! - NEEDS RERUN: no receipt for this commit, a NOT_RUN receipt, or a PASS
+//!   that rests on a dependency which is not PASS.
+//! - STALE: there are receipts, but only for other commits.
+//!
+//! What this checks, and says so in its output: that a receipt exists, what
+//! its verdict is, and whether it was made at the current commit. It does not
+//! yet look at whether inputs, the program or the machine changed since the
+//! receipt was made. The digest-based reuse check is Slice C.
+
+use crate::evidence::{Index, Stored};
+use crate::graph::Graph;
+use crate::manifest;
+use crate::verdict::Verdict;
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs;
+use std::path::Path;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum State {
+    Pass,
+    Failed,
+    Blocked,
+    MissingImplementation,
+    NeedsRerun,
+    Stale,
+}
+
+impl State {
+    pub fn label(self) -> &'static str {
+        match self {
+            State::Pass => "PASS",
+            State::Failed => "FAILED",
+            State::Blocked => "BLOCKED",
+            State::MissingImplementation => "MISSING IMPLEMENTATION",
+            State::NeedsRerun => "NEEDS RERUN",
+            State::Stale => "STALE",
+        }
+    }
+}
+
+/// What the store holds for one gate.
+enum Evidence<'a> {
+    /// Newest receipt made at the current commit.
+    Current(&'a Stored),
+    /// No receipt for this commit; the newest one for any other commit.
+    Other(&'a Stored),
+    Absent,
+}
+
+fn evidence<'a>(index: &'a Index, commit: &str, gate: &str) -> Evidence<'a> {
+    if let Some(r) = index.latest_at(gate, commit) {
+        return Evidence::Current(r);
+    }
+    match index.latest(gate) {
+        Some(r) => Evidence::Other(r),
+        None => Evidence::Absent,
+    }
+}
+
+fn own_state(e: &Evidence<'_>) -> State {
+    match e {
+        Evidence::Current(r) => match r.verdict() {
+            Some(Verdict::Pass) => State::Pass,
+            Some(Verdict::Fail) => State::Failed,
+            Some(Verdict::BlockedHardware) | Some(Verdict::BlockedOperator) => State::Blocked,
+            Some(Verdict::MissingImplementation) => State::MissingImplementation,
+            Some(Verdict::NotRun) | None => State::NeedsRerun,
+        },
+        Evidence::Other(_) => State::Stale,
+        Evidence::Absent => State::NeedsRerun,
+    }
+}
+
+/// The first 12 characters, enough to recognise a digest or commit.
+fn short(s: &str) -> String {
+    s.chars().take(12).collect()
+}
+
+fn last_observation(r: &Stored, name: &str) -> Option<String> {
+    let all = r.value["core"]["observations"].as_array()?;
+    all.iter()
+        .rev()
+        .find(|o| o["name"] == name)
+        .map(|o| o["value"].to_string())
+}
+
+/// For a FAIL receipt: the first expectation rule that did not hold, with the
+/// value the test reported for it.
+fn failing_rule_fact(r: &Stored) -> Option<String> {
+    let rules = r.value["core"]["rules"].as_array()?;
+    let first = rules.iter().find(|x| x["held"] == false)?;
+    let text = first["rule"].as_str()?;
+    let seen = manifest::parse_rule(text)
+        .ok()
+        .and_then(|rule| last_observation(r, &rule.name));
+    Some(match seen {
+        Some(v) => format!("first rule that did not hold: {text} (observed {v})"),
+        None => format!("first rule that did not hold: {text} (no such observation)"),
+    })
+}
+
+fn receipt_facts(r: &Stored) -> Vec<String> {
+    let verdict = r.verdict().map_or("UNKNOWN", |v| v.as_str());
+    let mut facts = Vec::new();
+    if r.reason().is_empty() {
+        facts.push(format!(
+            "receipt {} for this commit: {verdict}",
+            short(&r.digest)
+        ));
+    } else {
+        facts.push(format!(
+            "receipt {} for this commit: {verdict}, reason {}",
+            short(&r.digest),
+            r.reason()
+        ));
+    }
+    if r.verdict() == Some(Verdict::Fail) {
+        match r.reason() {
+            "rc_nonzero" => {
+                if let Some(code) = r.value["core"]["exit_status"].as_i64() {
+                    facts.push(format!("the program exited with status {code}"));
+                }
+            }
+            "timeout" => facts.push("the run hit its time limit and was stopped".to_string()),
+            _ => {}
+        }
+        if let Some(f) = failing_rule_fact(r) {
+            facts.push(f);
+        }
+    }
+    let exceeded = r.value["volatile"]["timeout_exceeded"] == true;
+    if exceeded && r.value["volatile"]["pool"] == "gb10" && r.reason() != "timeout" {
+        facts.push(
+            "ran past its time limit; gb10 jobs are never killed, so it was left to finish"
+                .to_string(),
+        );
+    }
+    if r.value["core"]["tree_clean_before"] == false {
+        facts.push("the working tree had uncommitted changes when it ran".to_string());
+    }
+    facts
+}
+
+struct Report<'a> {
+    graph: &'a Graph,
+    index: &'a Index,
+    commit: &'a str,
+    /// The state of every gate in the chain, dependencies included.
+    states: BTreeMap<usize, State>,
+    shown: BTreeSet<usize>,
+    lines: Vec<String>,
+}
+
+impl Report<'_> {
+    fn state(&self, i: usize) -> State {
+        self.states.get(&i).copied().unwrap_or(State::NeedsRerun)
+    }
+
+    fn facts(&self, i: usize) -> Vec<String> {
+        let node = self.graph.node(i);
+        let ev = evidence(self.index, self.commit, &node.id);
+        let mut facts = match &ev {
+            Evidence::Current(r) => receipt_facts(r),
+            Evidence::Other(r) => vec![format!(
+                "newest receipt {} is for commit {}, not the current commit {}",
+                short(&r.digest),
+                short(r.commit()),
+                short(self.commit)
+            )],
+            Evidence::Absent => vec!["no receipt in the evidence store".to_string()],
+        };
+        if own_state(&ev) == State::Pass {
+            for &d in &node.deps {
+                if self.state(d) != State::Pass {
+                    facts.push(format!(
+                        "rests on {}, which is {}",
+                        self.graph.node(d).id,
+                        self.state(d).label()
+                    ));
+                }
+            }
+        }
+        facts
+    }
+
+    fn render(&mut self, i: usize, depth: usize) {
+        let pad = "  ".repeat(depth);
+        let id = self.graph.node(i).id.clone();
+        let label = self.state(i).label();
+        if !self.shown.insert(i) {
+            self.lines.push(format!("{pad}{id}: {label} (shown above)"));
+            return;
+        }
+        self.lines.push(format!("{pad}{id}: {label}"));
+        for fact in self.facts(i) {
+            self.lines.push(format!("{pad}  - {fact}"));
+        }
+        let deps = self.graph.node(i).deps.clone();
+        for d in deps {
+            self.render(d, depth + 1);
+        }
+    }
+}
+
+/// The state of every gate `target` rests on, and of `target` itself: a gate
+/// whose own receipt is PASS still counts as needing a rerun when something it
+/// depends on is not PASS.
+pub fn states(graph: &Graph, index: &Index, commit: &str, target: usize) -> BTreeMap<usize, State> {
+    let chain = graph.with_dependencies(&[target]);
+    let mut out: BTreeMap<usize, State> = BTreeMap::new();
+    // Dependencies come before the gates that need them in this order.
+    for &i in graph.order() {
+        if !chain.contains(&i) {
+            continue;
+        }
+        let node = graph.node(i);
+        let own = own_state(&evidence(index, commit, &node.id));
+        let deps_pass = node.deps.iter().all(|d| out.get(d) == Some(&State::Pass));
+        let state = if own == State::Pass && !deps_pass {
+            State::NeedsRerun
+        } else {
+            own
+        };
+        out.insert(i, state);
+    }
+    out
+}
+
+/// The full report for `target` at `commit`, as lines to print.
+pub fn explain(graph: &Graph, index: &Index, commit: &str, target: usize) -> Vec<String> {
+    let mut report = Report {
+        graph,
+        index,
+        commit,
+        states: states(graph, index, commit, target),
+        shown: BTreeSet::new(),
+        lines: Vec::new(),
+    };
+    report.lines.push(format!(
+        "why {} at commit {}",
+        graph.node(target).id,
+        short(commit)
+    ));
+    report.render(target, 0);
+    report.lines.push(
+        "checked: whether a receipt exists, its verdict, and whether it is for the current commit"
+            .to_string(),
+    );
+    report.lines.push(
+        "not checked yet: whether files, the program or the machine changed since a receipt was made (digest-based reuse is Slice C)"
+            .to_string(),
+    );
+    report.lines
+}
+
+/// Find the gate a user means by `name`: a gate id, or the path of a `.gate`
+/// file (relative to `cwd`) whose gate id is in the graph.
+pub fn resolve_target(graph: &Graph, cwd: &Path, name: &str) -> Result<usize, String> {
+    if let Some(i) = graph.index_of(name) {
+        return Ok(i);
+    }
+    let path = cwd.join(name);
+    if path.is_file() {
+        let bytes = fs::read(&path).map_err(|e| format!("cannot read {name}: {e}"))?;
+        let m = manifest::parse(&bytes).map_err(|e| e.0)?;
+        return graph.index_of(&m.gate).ok_or_else(|| {
+            format!(
+                "gate {} in {name} is not part of this repository's gate graph",
+                m.gate
+            )
+        });
+    }
+    Err(format!("no gate named {name}"))
+}
+
+/// The state of `target` alone, for callers that only need the verdict word.
+pub fn state_of(graph: &Graph, index: &Index, commit: &str, target: usize) -> State {
+    states(graph, index, commit, target)
+        .get(&target)
+        .copied()
+        .unwrap_or(State::NeedsRerun)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::evidence::{build_receipt, Store};
+    use crate::graph;
+    use crate::testutil::{write_file, TempDir};
+    use serde_json::json;
+    use std::path::PathBuf;
+
+    const X: &str = "1111111111111111111111111111111111111111";
+    const Y: &str = "2222222222222222222222222222222222222222";
+
+    fn gate_text(id: &str, deps: &[&str]) -> String {
+        let dep_block = if deps.is_empty() {
+            String::new()
+        } else {
+            format!(
+                "depends_on:\n{}",
+                deps.iter()
+                    .map(|d| format!("  - {d}\n"))
+                    .collect::<String>()
+            )
+        };
+        format!(
+            "gate: {id}\nmanifest_version: 1\nowner: o\nrequires:\n  - host\nrun:\n  exec: x.sh\nexpects:\n  exit: 0\n  observe: []\n  verdict: PASS\ntimeout: 5s\n{dep_block}"
+        )
+    }
+
+    fn graph_of(spec: &[(&str, &[&str])]) -> Graph {
+        let entries = spec
+            .iter()
+            .map(|(id, deps)| {
+                (
+                    PathBuf::from(format!("tests/{id}.gate")),
+                    manifest::parse(gate_text(id, deps).as_bytes()).unwrap(),
+                )
+            })
+            .collect();
+        graph::build(entries).unwrap()
+    }
+
+    /// Write one receipt; `finished` orders receipts of the same gate.
+    fn put(store: &Store, gate: &str, commit: &str, verdict: &str, reason: &str, finished: &str) {
+        let r = build_receipt(
+            json!({
+                "gate": gate,
+                "commit": commit,
+                "derived_verdict": verdict,
+                "reason": reason,
+                "exit_status": null,
+                "observations": [],
+                "rules": [],
+                "tree_clean_before": true,
+                "dependencies": [],
+            }),
+            json!({ "finished_utc": finished, "pool": "host", "timeout_exceeded": false }),
+        );
+        store.put_receipt(&r).unwrap();
+    }
+
+    fn pass(store: &Store, gate: &str, commit: &str) {
+        put(store, gate, commit, "PASS", "", "2026-10-02T10:00:00Z");
+    }
+
+    fn text(lines: &[String]) -> String {
+        lines.join("\n")
+    }
+
+    fn id(g: &Graph, name: &str) -> usize {
+        g.index_of(name).unwrap()
+    }
+
+    #[test]
+    fn a_chain_shows_each_gate_with_its_state() {
+        let g = graph_of(&[("G-A", &[]), ("G-B", &["G-A"]), ("G-C", &["G-B"])]);
+        let ev = TempDir::new("why1");
+        let store = Store::new(ev.path());
+        pass(&store, "G-A", X);
+        let r = build_receipt(
+            json!({
+                "gate": "G-B", "commit": X, "derived_verdict": "FAIL", "reason": "rc_nonzero",
+                "exit_status": 2,
+                "observations": [{ "name": "n", "value": 4 }],
+                "rules": [{ "rule": "n == 3", "held": false }],
+                "tree_clean_before": true, "dependencies": [],
+            }),
+            json!({ "finished_utc": "2026-10-02T10:00:01Z", "pool": "host", "timeout_exceeded": false }),
+        );
+        store.put_receipt(&r).unwrap();
+        let index = Index::load(&store);
+        let out = text(&explain(&g, &index, X, id(&g, "G-C")));
+        assert!(out.contains("G-C: NEEDS RERUN"), "{out}");
+        assert!(out.contains("no receipt in the evidence store"), "{out}");
+        assert!(out.contains("G-B: FAILED"), "{out}");
+        assert!(out.contains("the program exited with status 2"), "{out}");
+        assert!(
+            out.contains("first rule that did not hold: n == 3 (observed 4)"),
+            "{out}"
+        );
+        assert!(out.contains("G-A: PASS"), "{out}");
+        // The tree reads top down: C, then B, then A.
+        let (c, b, a) = (
+            out.find("G-C:").unwrap(),
+            out.find("G-B:").unwrap(),
+            out.find("G-A:").unwrap(),
+        );
+        assert!(c < b && b < a, "{out}");
+    }
+
+    #[test]
+    fn receipts_for_other_commits_are_stale() {
+        let g = graph_of(&[("G-A", &[])]);
+        let ev = TempDir::new("why2");
+        let store = Store::new(ev.path());
+        pass(&store, "G-A", Y);
+        let index = Index::load(&store);
+        assert_eq!(state_of(&g, &index, X, 0), State::Stale);
+        let out = text(&explain(&g, &index, X, 0));
+        assert!(out.contains("G-A: STALE"), "{out}");
+        assert!(out.contains("is for commit 222222222222"), "{out}");
+        assert_eq!(state_of(&g, &index, Y, 0), State::Pass);
+    }
+
+    #[test]
+    fn a_pass_resting_on_a_failure_needs_a_rerun() {
+        let g = graph_of(&[("G-A", &[]), ("G-B", &["G-A"])]);
+        let ev = TempDir::new("why3");
+        let store = Store::new(ev.path());
+        put(
+            &store,
+            "G-A",
+            X,
+            "FAIL",
+            "rc_nonzero",
+            "2026-10-02T10:00:00Z",
+        );
+        pass(&store, "G-B", X);
+        let index = Index::load(&store);
+        assert_eq!(state_of(&g, &index, X, id(&g, "G-B")), State::NeedsRerun);
+        let out = text(&explain(&g, &index, X, id(&g, "G-B")));
+        assert!(out.contains("rests on G-A, which is FAILED"), "{out}");
+    }
+
+    #[test]
+    fn blocked_and_missing_implementation_have_their_own_states() {
+        let g = graph_of(&[("G-A", &[]), ("G-B", &[]), ("G-C", &[])]);
+        let ev = TempDir::new("why4");
+        let store = Store::new(ev.path());
+        put(
+            &store,
+            "G-A",
+            X,
+            "BLOCKED_HARDWARE",
+            "NO_GB10",
+            "2026-10-02T10:00:00Z",
+        );
+        put(
+            &store,
+            "G-B",
+            X,
+            "MISSING_IMPLEMENTATION",
+            "NO_RUN_EXEC",
+            "2026-10-02T10:00:00Z",
+        );
+        put(
+            &store,
+            "G-C",
+            X,
+            "NOT_RUN",
+            "dirty_tree",
+            "2026-10-02T10:00:00Z",
+        );
+        let index = Index::load(&store);
+        assert_eq!(state_of(&g, &index, X, id(&g, "G-A")), State::Blocked);
+        assert_eq!(
+            state_of(&g, &index, X, id(&g, "G-B")),
+            State::MissingImplementation
+        );
+        assert_eq!(state_of(&g, &index, X, id(&g, "G-C")), State::NeedsRerun);
+        let out = text(&explain(&g, &index, X, id(&g, "G-A")));
+        assert!(out.contains("BLOCKED_HARDWARE, reason NO_GB10"), "{out}");
+    }
+
+    #[test]
+    fn the_newest_receipt_for_the_commit_wins() {
+        let g = graph_of(&[("G-A", &[])]);
+        let ev = TempDir::new("why5");
+        let store = Store::new(ev.path());
+        put(
+            &store,
+            "G-A",
+            X,
+            "FAIL",
+            "rc_nonzero",
+            "2026-10-02T10:00:00Z",
+        );
+        put(&store, "G-A", X, "PASS", "", "2026-10-02T11:00:00Z");
+        let index = Index::load(&store);
+        assert_eq!(state_of(&g, &index, X, 0), State::Pass);
+        put(&store, "G-A", X, "FAIL", "timeout", "2026-10-02T12:00:00Z");
+        let index = Index::load(&store);
+        assert_eq!(state_of(&g, &index, X, 0), State::Failed);
+    }
+
+    #[test]
+    fn an_exceeded_gb10_timeout_is_reported() {
+        let g = graph_of(&[("G-A", &[])]);
+        let ev = TempDir::new("why6");
+        let store = Store::new(ev.path());
+        let r = build_receipt(
+            json!({
+                "gate": "G-A", "commit": X, "derived_verdict": "PASS", "reason": "",
+                "exit_status": 0, "observations": [], "rules": [],
+                "tree_clean_before": true, "dependencies": [],
+            }),
+            json!({ "finished_utc": "2026-10-02T10:00:00Z", "pool": "gb10", "timeout_exceeded": true }),
+        );
+        store.put_receipt(&r).unwrap();
+        let index = Index::load(&store);
+        let out = text(&explain(&g, &index, X, 0));
+        assert!(out.contains("gb10 jobs are never killed"), "{out}");
+        assert!(out.contains("G-A: PASS"), "{out}");
+    }
+
+    #[test]
+    fn a_gate_reached_twice_is_expanded_once() {
+        let g = graph_of(&[
+            ("G-A", &[]),
+            ("G-B", &["G-A"]),
+            ("G-C", &["G-A"]),
+            ("G-D", &["G-B", "G-C"]),
+        ]);
+        let ev = TempDir::new("why7");
+        let store = Store::new(ev.path());
+        for gate in ["G-A", "G-B", "G-C", "G-D"] {
+            pass(&store, gate, X);
+        }
+        let index = Index::load(&store);
+        let lines = explain(&g, &index, X, id(&g, "G-D"));
+        let out = text(&lines);
+        assert_eq!(out.matches("G-A: PASS").count(), 2, "{out}");
+        assert_eq!(out.matches("(shown above)").count(), 1, "{out}");
+        assert_eq!(out.matches("for this commit: PASS").count(), 4, "{out}");
+    }
+
+    #[test]
+    fn the_report_says_what_it_does_not_check() {
+        let g = graph_of(&[("G-A", &[])]);
+        let ev = TempDir::new("why8");
+        let index = Index::load(&Store::new(ev.path()));
+        let lines = explain(&g, &index, X, 0);
+        let out = text(&lines);
+        assert!(out.contains("checked: whether a receipt exists"), "{out}");
+        assert!(out.contains("not checked yet"), "{out}");
+        assert!(out.contains("Slice C"), "{out}");
+        assert!(lines[0].starts_with("why G-A at commit 111111111111"));
+    }
+
+    #[test]
+    fn a_gate_is_found_by_id_or_by_file() {
+        let g = graph_of(&[("G-A", &[]), ("G-B", &["G-A"])]);
+        let dir = TempDir::new("why10");
+        write_file(
+            dir.path(),
+            "tests/b.gate",
+            &gate_text("G-B", &["G-A"]),
+            false,
+        );
+        assert_eq!(resolve_target(&g, dir.path(), "G-B"), Ok(1));
+        assert_eq!(resolve_target(&g, dir.path(), "tests/b.gate"), Ok(1));
+        assert!(resolve_target(&g, dir.path(), "G-NOPE").is_err());
+        write_file(dir.path(), "tests/z.gate", &gate_text("G-Z", &[]), false);
+        let e = resolve_target(&g, dir.path(), "tests/z.gate").unwrap_err();
+        assert!(e.contains("not part of"), "{e}");
+    }
+
+    #[test]
+    fn short_never_splits_a_character() {
+        assert_eq!(short("abc"), "abc");
+        assert_eq!(short("0123456789abcdef"), "0123456789ab");
+        assert_eq!(short("ééééééééééééééé").chars().count(), 12);
+    }
+
+    #[test]
+    fn a_receipt_that_ran_on_a_dirty_tree_says_so() {
+        let g = graph_of(&[("G-A", &[])]);
+        let ev = TempDir::new("why9");
+        let store = Store::new(ev.path());
+        let r = build_receipt(
+            json!({
+                "gate": "G-A", "commit": X, "derived_verdict": "PASS", "reason": "",
+                "exit_status": 0, "observations": [], "rules": [],
+                "tree_clean_before": false, "dependencies": [],
+            }),
+            json!({ "finished_utc": "2026-10-02T10:00:00Z", "pool": "host", "timeout_exceeded": false }),
+        );
+        store.put_receipt(&r).unwrap();
+        let index = Index::load(&store);
+        let out = text(&explain(&g, &index, X, 0));
+        assert!(out.contains("uncommitted changes"), "{out}");
+    }
+}