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#170 (code only)

closed derived 8e45221232aceb69 #170

Imported from GitHub aien-dev/aien-sovereign-core-mv#170 (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 40dd3732f1e4172c25f7110e444487883b676386 · Head 4993ea8f7c163db142355d68c59e0e13f65858be

Apply it

git checkout -b patch-8e45221232aceb69 40dd3732f1e4172c25f7110e444487883b676386
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/8e45221232aceb69.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
170
4993ea8f7c163db142355d68c59e0e13f65858be
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":170,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/170","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:11Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/tools/aien-test/Cargo.toml b/tools/aien-test/Cargo.toml
index c6f55347..6eb12fb2 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 Slices A and B: gate manifests, verdict derivation, immutable evidence receipts, dependency graph, resource pools with GPU locks, parallel runner and why (ADR 0028)"
+description = "AIEN-TEST Slices A to C: gate manifests, verdict derivation, immutable evidence receipts, dependency graph, resource pools with GPU locks, parallel runner, why, and the digest cache (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 c7c5d326..b743d208 100644
--- a/tools/aien-test/mutations/aien-test.mutants
+++ b/tools/aien-test/mutations/aien-test.mutants
@@ -33,3 +33,21 @@ stale_receipt_counts_as_pass	why.rs	s#Evidence::Other(_) => State::Stale,#Eviden
 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
+cache_ignores_input_digest	cache.rs	s#"build_inputs_digest": e.build_inputs_digest,#"build_inputs_digest": "",#	the cache key ignores the declared input files, so a changed input is still a hit
+cache_ignores_program	cache.rs	s#"binary_sha256": e.binary_sha256,#"binary_sha256": "",#	the cache key ignores the program, so an edited script is still a hit
+cache_ignores_manifest	cache.rs	s#"manifest_digest": e.manifest_digest,#"manifest_digest": "",#	the cache key ignores the manifest, so an edited gate contract is still a hit
+cache_ignores_machine	cache.rs	s#"machine_digest": e.machine_digest,#"machine_digest": "",#	the cache key ignores the machine, so a result from other hardware is a hit
+cache_ignores_dependencies	cache.rs	s#"dependencies": deps,#"dependencies": [],#	the cache key ignores dependency receipts, so a gate resting on a changed dependency is a hit
+cache_dependency_not_followed_to_origin	cache.rs	s#Some(r) if r.value\["volatile"\]\["cache"\]\["reused"\] == true => #Some(r) if r.value["volatile"]["cache"]["reused"] == "never" => #	a reused dependency keeps its own new digest, so every dependent misses and a whole graph is never reused
+cache_args_override_not_in_key	cache.rs	s#if let Some(args) = &e.args_override {#if let Some(args) = \&None::<Vec<String>> {#	a run with replacement args gets the same key as the ordinary run
+cache_stored_key_trusted	cache.rs	s#if recomputed.as_deref() != Some(key) {#if false {#	a receipt is believed when it claims a key, without hashing its own contents
+cache_reused_receipt_is_source	cache.rs	s#if vol\["cache"\]\["reused"\] != false {#if false {#	a reuse receipt can itself be the source of a later reuse
+cache_not_run_receipt_reused	cache.rs	s#if !matches!(src.verdict(), Some(Verdict::Pass | Verdict::Fail)) {#if false {#	a NOT_RUN or BLOCKED receipt is reused as if it were an experiment
+cache_dirty_source_trusted	cache.rs	s#if core\["tree_clean_before"\] != true || core\["tree_clean_after"\] != true {#if false {#	a receipt made on a dirty tree can be reused
+cache_timeout_source_trusted	cache.rs	s#if vol\["timeout_exceeded"\] != false {#if false {#	a run that went past its time limit can be reused
+cache_env_ignored	cache.rs	s#if &core\["env"\] != env {#if false {#	a result made under other compiler flags or locale is reused
+cache_blob_check_removed	cache.rs	s#Some(sha) if store.blob_exists(sha) => {}#Some(_) => {}#	a result whose logs are gone from the store is reused
+cache_never_ignored	cache.rs	s#if !cache_allowed {#if false {#	a gate that says cache: never is reused anyway
+cache_reuse_keeps_old_commit	cache.rs	s#core\["commit"\] = json!(commit);#let _ = commit;#	a reuse receipt still names the old commit, so the new commit looks unchecked
+cache_dirty_tree_looks_up	runner.rs	s#if mode == cache::Mode::Allow \&\& (opts.args_override.is_some() || !tree_clean) {#if false {#	a tree with uncommitted changes (or replacement args) still consults the cache
+cache_no_cache_ignored	runner.rs	s#cache::policy(m.cache_allowed, opts.no_cache)#cache::policy(m.cache_allowed, false)#	--no-cache does not force a fresh run
diff --git a/tools/aien-test/src/cache.rs b/tools/aien-test/src/cache.rs
new file mode 100644
index 00000000..5263a0ed
--- /dev/null
+++ b/tools/aien-test/src/cache.rs
@@ -0,0 +1,1209 @@
+//! The digest cache (ADR 0028 Decision 7, Slice C).
+//!
+//! A gate's result is reused, not rerun, only when an earlier fresh receipt
+//! describes the very same experiment: the manifest bytes, the program, every
+//! declared input, the machine and the receipts the gate depends on all have
+//! identical digests (the "cache key"). Anything else runs the gate again.
+//!
+//! The cache is keyed on the receipt bytes and digests exactly as the runner
+//! writes them today. It adds no receipt member and changes no receipt format
+//! (ADR 0029 will own that). Where the ADR says "index" this slice reads the
+//! receipts themselves: every receipt already carries `volatile.cache.key`,
+//! so a separate `index.jsonl` would only be a second copy that could drift.
+//!
+//! Choices where the ADR is silent or contradicts itself (recorded in the PR):
+//! - A reused receipt is the source receipt's `core` with one change: its
+//!   `commit` is the commit being checked. The ADR says "identical core" and
+//!   also "records that this commit was checked"; both cannot hold, and
+//!   `why`, `run` and the dependency lookups all match receipts by commit.
+//! - Dependencies enter the key as receipt digests, resolved to the original
+//!   fresh receipt when the dependency itself was reused. Without that step a
+//!   reused dependency would get a new digest and every dependent would miss.
+//! - A source receipt must pass extra checks the key cannot express (see
+//!   [`Unusable`]); failing any one of them is a miss, never a hit.
+//! - `args` after `--` are not in the ADR key. A run with replacement args
+//!   never consults the cache, and its key carries the args so it can never
+//!   be mistaken for a run with the manifest's own args.
+
+use crate::evidence::{canonical_digest, Index, Store, StoreError, Stored, SCHEMA};
+use crate::runner;
+use crate::verdict::Verdict;
+use serde_json::{json, Value};
+use std::collections::BTreeMap;
+use std::path::Path;
+
+/// `volatile.cache.mode` (ADR Decision 4).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Mode {
+    /// The cache may be consulted.
+    Allow,
+    /// The manifest says `cache: never`.
+    Never,
+    /// Lookups were switched off for this run (`--no-cache`, replacement
+    /// args, or a tree with uncommitted changes).
+    Disabled,
+}
+
+impl Mode {
+    pub fn as_str(self) -> &'static str {
+        match self {
+            Mode::Allow => "allow",
+            Mode::Never => "never",
+            Mode::Disabled => "disabled",
+        }
+    }
+}
+
+/// The mode the manifest and the command line ask for. `cache: never` wins
+/// over everything: it is the gate author's rule, not a flag.
+pub fn policy(cache_allowed: bool, no_cache: bool) -> Mode {
+    if !cache_allowed {
+        Mode::Never
+    } else if no_cache {
+        Mode::Disabled
+    } else {
+        Mode::Allow
+    }
+}
+
+/// The members the cache key is made of.
+#[derive(Debug, Clone)]
+pub struct Experiment {
+    pub manifest_digest: String,
+    pub binary_sha256: Option<String>,
+    pub build_inputs_digest: String,
+    pub machine_digest: String,
+    /// `(gate, receipt digest)` as recorded in `core.dependencies`.
+    pub dependencies: Vec<(String, String)>,
+    pub pins: Value,
+    /// Replacement arguments given after `--`, if any.
+    pub args_override: Option<Vec<String>>,
+}
+
+/// A receipt digest, followed through `reused_from` to the fresh receipt it
+/// stands for. A digest the store does not hold is returned as it is.
+pub fn origin_digest(index: &Index, digest: &str) -> String {
+    match index.get(digest) {
+        Some(r) if r.value["volatile"]["cache"]["reused"] == true => r.value["volatile"]["cache"]
+            ["reused_from"]
+            .as_str()
+            .unwrap_or(digest)
+            .to_string(),
+        _ => digest.to_string(),
+    }
+}
+
+/// `cache.key`: sha256 over the canonical bytes of the key object.
+pub fn key(e: &Experiment, index: &Index) -> Result<String, StoreError> {
+    let deps: Vec<Value> = e
+        .dependencies
+        .iter()
+        .map(|(gate, receipt)| json!({ "gate": gate, "receipt": origin_digest(index, receipt) }))
+        .collect();
+    let mut obj = json!({
+        "manifest_digest": e.manifest_digest,
+        "binary_sha256": e.binary_sha256,
+        "build_inputs_digest": e.build_inputs_digest,
+        "machine_digest": e.machine_digest,
+        "dependencies": deps,
+        "runner_schema": SCHEMA,
+        "pins": e.pins,
+    });
+    if let Some(args) = &e.args_override {
+        obj["args_override"] = json!(args);
+    }
+    canonical_digest(&obj)
+}
+
+/// The key members of a stored receipt, read from its `core`.
+fn experiment_of(src: &Stored) -> Option<Experiment> {
+    let core = &src.value["core"];
+    let text = |k: &str| core[k].as_str().map(str::to_string);
+    let deps = core["dependencies"]
+        .as_array()?
+        .iter()
+        .map(|d| {
+            Some((
+                d["gate"].as_str()?.to_string(),
+                d["receipt"].as_str()?.to_string(),
+            ))
+        })
+        .collect::<Option<Vec<_>>>()?;
+    Some(Experiment {
+        manifest_digest: text("manifest_digest")?,
+        binary_sha256: text("binary_sha256"),
+        build_inputs_digest: text("build_inputs_digest")?,
+        machine_digest: text("machine_digest")?,
+        dependencies: deps,
+        pins: core.get("pins")?.clone(),
+        args_override: None,
+    })
+}
+
+/// Why an earlier receipt that carries the right key still cannot be reused.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Unusable {
+    /// It was itself a reuse; only fresh results are sources.
+    AlreadyReused,
+    /// Its verdict describes a situation, not an experiment (NOT_RUN,
+    /// BLOCKED_*, MISSING_IMPLEMENTATION).
+    NotAnExperiment,
+    /// The tree was dirty before or after the run.
+    UncleanTree,
+    /// HEAD moved during the run.
+    HeadMoved,
+    /// The run went past its time limit.
+    TimedOut,
+    /// The key written in the receipt is not what its own contents hash to.
+    KeyMismatch,
+    /// The machine descriptor does not hash to the machine digest.
+    MachineMismatch,
+    /// The captured environment differs from the current one.
+    EnvDiffers,
+    /// A stdout or stderr blob it names is missing from the store.
+    BlobMissing,
+}
+
+impl Unusable {
+    pub fn text(self) -> &'static str {
+        match self {
+            Unusable::AlreadyReused => "it was itself a reuse, not a fresh run",
+            Unusable::NotAnExperiment => "its verdict is not PASS or FAIL",
+            Unusable::UncleanTree => "the tree had uncommitted changes when it ran",
+            Unusable::HeadMoved => "HEAD moved while it ran",
+            Unusable::TimedOut => "it ran past its time limit",
+            Unusable::KeyMismatch => "its recorded key does not match its own contents",
+            Unusable::MachineMismatch => "its machine descriptor does not match its machine digest",
+            Unusable::EnvDiffers => "the captured environment differs from the current one",
+            Unusable::BlobMissing => "a log it refers to is missing from the evidence store",
+        }
+    }
+}
+
+/// May `src` (which carries `key`) stand in for a run now? Fail closed: the
+/// first problem found makes it unusable.
+pub fn usable(
+    src: &Stored,
+    key: &str,
+    index: &Index,
+    store: &Store,
+    env: &Value,
+) -> Result<(), Unusable> {
+    let (core, vol) = (&src.value["core"], &src.value["volatile"]);
+    if vol["cache"]["reused"] != false {
+        return Err(Unusable::AlreadyReused);
+    }
+    if !matches!(src.verdict(), Some(Verdict::Pass | Verdict::Fail)) {
+        return Err(Unusable::NotAnExperiment);
+    }
+    if core["tree_clean_before"] != true || core["tree_clean_after"] != true {
+        return Err(Unusable::UncleanTree);
+    }
+    if core["commit_unchanged_after"] != true {
+        return Err(Unusable::HeadMoved);
+    }
+    if vol["timeout_exceeded"] != false {
+        return Err(Unusable::TimedOut);
+    }
+    // Recompute the key from the receipt's own contents; never trust the
+    // stored value alone.
+    let recomputed = experiment_of(src).and_then(|e| self::key(&e, index).ok());
+    if recomputed.as_deref() != Some(key) {
+        return Err(Unusable::KeyMismatch);
+    }
+    let machine_digest = core.get("machine").and_then(|m| canonical_digest(m).ok());
+    if machine_digest.as_deref() != core["machine_digest"].as_str() {
+        return Err(Unusable::MachineMismatch);
+    }
+    if &core["env"] != env {
+        return Err(Unusable::EnvDiffers);
+    }
+    for member in ["stdout_sha256", "stderr_sha256"] {
+        match core[member].as_str() {
+            Some(sha) if store.blob_exists(sha) => {}
+            _ => return Err(Unusable::BlobMissing),
+        }
+    }
+    Ok(())
+}
+
+/// Why there is no hit.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Miss {
+    /// No receipt in the store carries this key.
+    NoReceipt,
+    /// The newest receipt with this key cannot be reused.
+    Unusable { digest: String, why: Unusable },
+}
+
+impl Miss {
+    pub fn text(&self) -> String {
+        match self {
+            Miss::NoReceipt => "no earlier receipt has this key".to_string(),
+            Miss::Unusable { digest, why } => format!(
+                "the newest receipt with this key ({}) cannot be reused: {}",
+                digest.chars().take(12).collect::<String>(),
+                why.text()
+            ),
+        }
+    }
+}
+
+#[derive(Debug)]
+pub enum Lookup<'a> {
+    Hit(&'a Stored),
+    Miss(Miss),
+}
+
+/// The newest usable fresh receipt whose `cache.key` is `key`.
+pub fn lookup<'a>(index: &'a Index, store: &Store, key: &str, env: &Value) -> Lookup<'a> {
+    let mut first_rejection: Option<Miss> = None;
+    for r in index.receipts().iter().rev() {
+        if r.value["volatile"]["cache"]["key"] != key {
+            continue;
+        }
+        match usable(r, key, index, store, env) {
+            Ok(()) => return Lookup::Hit(r),
+            Err(why) => {
+                first_rejection.get_or_insert(Miss::Unusable {
+                    digest: r.digest.clone(),
+                    why,
+                });
+            }
+        }
+    }
+    Lookup::Miss(first_rejection.unwrap_or(Miss::NoReceipt))
+}
+
+/// The `core` of a reuse receipt: the source's core, with `commit` set to the
+/// commit being checked.
+pub fn reused_core(src: &Stored, commit: &str) -> Value {
+    let mut core = src.value["core"].clone();
+    core["commit"] = json!(commit);
+    core
+}
+
+/// The `volatile.cache` member.
+pub fn cache_member(key: &str, reused_from: Option<&str>, mode: Mode) -> Value {
+    json!({
+        "key": key,
+        "reused": reused_from.is_some(),
+        "reused_from": reused_from,
+        "mode": mode.as_str(),
+    })
+}
+
+/// Which key members of `src` differ from `now`, in plain words.
+pub fn differences(src: &Stored, now: &Experiment, index: &Index) -> Vec<&'static str> {
+    let then = match experiment_of(src) {
+        Some(t) => t,
+        None => return vec!["the receipt itself (it is missing key members)"],
+    };
+    let resolve = |e: &Experiment| -> Vec<(String, String)> {
+        e.dependencies
+            .iter()
+            .map(|(g, r)| (g.clone(), origin_digest(index, r)))
+            .collect()
+    };
+    let mut out = Vec::new();
+    if then.manifest_digest != now.manifest_digest {
+        out.push("the gate manifest");
+    }
+    if then.binary_sha256 != now.binary_sha256 {
+        out.push("the program (run.exec)");
+    }
+    if then.build_inputs_digest != now.build_inputs_digest {
+        out.push("the declared input files");
+    }
+    if then.machine_digest != now.machine_digest {
+        out.push("the machine");
+    }
+    if resolve(&then) != resolve(now) {
+        out.push("a dependency's receipt");
+    }
+    if then.pins != now.pins {
+        out.push("the pinned dependencies");
+    }
+    out
+}
+
+fn short(s: &str) -> String {
+    s.chars().take(12).collect()
+}
+
+/// For `why`: what a run of `target` and of everything it depends on would do
+/// about the cache right now, one list of plain lines per gate (node number).
+/// Nothing is run and nothing is written.
+pub fn explain_chain(
+    root: &Path,
+    graph: &crate::graph::Graph,
+    index: &Index,
+    opts: &runner::Options,
+    commit: &str,
+    target: usize,
+) -> BTreeMap<usize, Vec<String>> {
+    let store = Store::new(&opts.evidence_dir);
+    let env = runner::captured_env();
+    let dirty = runner::working_tree_dirty(root);
+    let chain = graph.with_dependencies(&[target]);
+    let mut out: BTreeMap<usize, Vec<String>> = BTreeMap::new();
+    // The receipt a dependency would stand on after a run: Some only if that
+    // dependency would itself be reused.
+    let mut stands_on: BTreeMap<usize, Option<String>> = BTreeMap::new();
+    for &i in graph.order() {
+        if !chain.contains(&i) {
+            continue;
+        }
+        let node = graph.node(i);
+        let m = &node.manifest;
+        let mut lines: Vec<String> = Vec::new();
+        let mode = policy(m.cache_allowed, opts.no_cache);
+        let mut reuse: Option<String> = None;
+        match (mode, dirty.as_ref()) {
+            (Mode::Never, _) => {
+                lines.push("cache: never (the manifest says cache: never), so it always runs".to_string())
+            }
+            (Mode::Disabled, _) => lines.push("cache: switched off by --no-cache, so it would run".to_string()),
+            (_, Err(e)) => lines.push(format!("cache: not used, the tree state is unknown ({e})")),
+            (_, Ok(&true)) => lines.push(
+                "cache: not used, the tree has uncommitted changes (a run is refused until it is clean)"
+                    .to_string(),
+            ),
+            (Mode::Allow, Ok(&false)) => {
+                let waiting: Vec<&str> = m
+                    .depends_on
+                    .iter()
+                    .filter(|d| {
+                        graph
+                            .index_of(d)
+                            .is_none_or(|di| stands_on.get(&di).is_none_or(|s| s.is_none()))
+                    })
+                    .map(String::as_str)
+                    .collect();
+                if let Some(first) = waiting.first() {
+                    lines.push(format!(
+                        "cache: miss, it depends on {first}, which would run again, so its receipt would change"
+                    ));
+                } else {
+                    match runner::identity(root, &node.path, m, &opts.hardware) {
+                        Err(e) => lines.push(format!("cache: miss, cannot digest the inputs ({e})")),
+                        Ok(id) => {
+                            let deps: Vec<(String, String)> = m
+                                .depends_on
+                                .iter()
+                                .filter_map(|d| {
+                                    let di = graph.index_of(d)?;
+                                    Some((d.clone(), stands_on.get(&di)?.clone()?))
+                                })
+                                .collect();
+                            let now = Experiment {
+                                manifest_digest: m.digest.clone(),
+                                binary_sha256: id.binary_sha.clone(),
+                                build_inputs_digest: id.inputs_digest.clone(),
+                                machine_digest: id.machine_digest.clone(),
+                                dependencies: deps,
+                                pins: json!([]),
+                                args_override: None,
+                            };
+                            match key(&now, index) {
+                                Err(e) => lines.push(format!("cache: miss, cannot build the key ({e})")),
+                                Ok(k) => match lookup(index, &store, &k, &env) {
+                                    Lookup::Hit(src) => {
+                                        lines.push(format!(
+                                            "cache: hit, a run would reuse receipt {} ({}, made at commit {}); key {}",
+                                            short(&src.digest),
+                                            src.verdict().map_or("UNKNOWN", |v| v.as_str()),
+                                            short(src.commit()),
+                                            short(&k)
+                                        ));
+                                        reuse = Some(src.digest.clone());
+                                    }
+                                    Lookup::Miss(miss) => {
+                                        lines.push(format!("cache: miss, {} (key {})", miss.text(), short(&k)));
+                                        if let Some(prev) = index.latest(&node.id) {
+                                            let d = differences(prev, &now, index);
+                                            if !d.is_empty() {
+                                                lines.push(format!(
+                                                    "cache: since its newest receipt {} these changed: {}",
+                                                    short(&prev.digest),
+                                                    d.join(", ")
+                                                ));
+                                            }
+                                        }
+                                    }
+                                },
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        if let Some(r) = index.latest_at(&node.id, commit) {
+            if r.value["volatile"]["cache"]["reused"] == true {
+                lines.push(format!(
+                    "the receipt for this commit ({}) was reused from {}, not run; it is not qualification evidence",
+                    short(&r.digest),
+                    short(r.value["volatile"]["cache"]["reused_from"].as_str().unwrap_or(""))
+                ));
+            }
+        }
+        stands_on.insert(i, reuse);
+        out.insert(i, lines);
+    }
+    out
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::graph;
+    use crate::resources::{GpuConfig, Hardware};
+    use crate::runner::{self, CacheNote, Options, Outcome};
+    use crate::testutil::{git, init_repo, write_file, TempDir};
+    use std::collections::BTreeSet;
+    use std::fs;
+    use std::path::PathBuf;
+    use std::time::Duration;
+
+    const SCRIPT: &str = "#!/bin/sh\necho x >> \"$1\"\necho \"AIEN-OBS n 3\"\necho PASS\n";
+    const FAILING_SCRIPT: &str = "#!/bin/sh\necho x >> \"$1\"\necho \"AIEN-OBS n 3\"\nexit 1\n";
+
+    fn gate_text(id: &str, deps: &[&str], counter: &Path, extra: &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: t\nrequires:\n  - host\n{dep_block}inputs:\n  - data/\nrun:\n  exec: tools/run.sh\n  args: [\"{}\"]\nexpects:\n  exit: 0\n  observe: [\"n == 3\"]\n  verdict: PASS\ntimeout: 20s\n{extra}",
+            counter.display()
+        )
+    }
+
+    struct Fx {
+        repo: TempDir,
+        ev: TempDir,
+        scratch: TempDir,
+    }
+
+    impl Fx {
+        fn new(script: &str) -> Fx {
+            let scratch = TempDir::new("c-scratch");
+            let counter = scratch.path().join("a.count");
+            let gate = gate_text("C-A", &[], &counter, "");
+            let repo = init_repo(
+                "c-repo",
+                &[
+                    ("tools/run.sh", script, true),
+                    ("tests/a.gate", gate.as_str(), false),
+                    ("data/in.txt", "one\n", false),
+                    ("README", "hello\n", false),
+                ],
+            );
+            Fx {
+                repo,
+                ev: TempDir::new("c-ev"),
+                scratch,
+            }
+        }
+        fn counter(&self, name: &str) -> PathBuf {
+            self.scratch.path().join(format!("{name}.count"))
+        }
+        /// How many times the gate's program really ran.
+        fn runs(&self, name: &str) -> usize {
+            fs::read_to_string(self.counter(name)).map_or(0, |s| s.lines().count())
+        }
+        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
+        }
+        fn store(&self) -> Store {
+            Store::new(&self.ev.path().join("out"))
+        }
+        fn run(&self, opts: &Options) -> Outcome {
+            runner::run_gate(
+                self.repo.path(),
+                &self.repo.path().join("tests/a.gate"),
+                opts,
+            )
+            .unwrap()
+        }
+        fn commit(&self, rel: &str, content: &str) {
+            write_file(self.repo.path(), rel, content, false);
+            git(self.repo.path(), &["add", "-A"]);
+            git(self.repo.path(), &["commit", "-q", "-m", rel]);
+        }
+        fn head(&self) -> String {
+            runner::head(self.repo.path()).unwrap()
+        }
+        fn receipt(&self, o: &Outcome) -> Value {
+            serde_json::from_slice(&fs::read(o.receipt_path.as_ref().unwrap()).unwrap()).unwrap()
+        }
+    }
+
+    fn reused_from(o: &Outcome) -> Option<&str> {
+        match &o.cache {
+            CacheNote::Reused { from } => Some(from),
+            _ => None,
+        }
+    }
+
+    fn fresh_pass(fx: &Fx) -> Outcome {
+        let o = fx.run(&fx.opts());
+        assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason);
+        assert_eq!(reused_from(&o), None);
+        o
+    }
+
+    // ---- hit -----------------------------------------------------------
+
+    #[test]
+    fn identical_experiment_is_reused_and_not_rerun() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        assert_eq!(fx.runs("a"), 1);
+        let second = fx.run(&fx.opts());
+        assert_eq!(second.verdict, Verdict::Pass);
+        assert_eq!(
+            reused_from(&second),
+            first.receipt_digest.as_deref(),
+            "must name the receipt it took the result from"
+        );
+        assert_eq!(fx.runs("a"), 1, "the program must not run again");
+        let (r1, r2) = (fx.receipt(&first), fx.receipt(&second));
+        assert_ne!(first.receipt_digest, second.receipt_digest);
+        assert_eq!(r2["volatile"]["cache"]["reused"], true);
+        assert_eq!(
+            r2["volatile"]["cache"]["reused_from"],
+            json!(first.receipt_digest)
+        );
+        assert_eq!(
+            r2["volatile"]["cache"]["key"],
+            r1["volatile"]["cache"]["key"]
+        );
+        assert_eq!(r2["volatile"]["cache"]["mode"], "allow");
+        assert_eq!(r1["volatile"]["cache"]["reused"], false);
+        assert_eq!(r1["volatile"]["cache"]["mode"], "allow");
+        assert_eq!(r1["core"], r2["core"], "same commit: identical core");
+    }
+
+    #[test]
+    fn reuse_across_commits_records_the_commit_that_was_checked() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        let old_head = fx.head();
+        // A change to a file the gate does not depend on.
+        fx.commit("README", "changed\n");
+        assert_ne!(fx.head(), old_head);
+        let second = fx.run(&fx.opts());
+        assert_eq!(reused_from(&second), first.receipt_digest.as_deref());
+        assert_eq!(fx.runs("a"), 1);
+        let (mut c1, mut c2) = (
+            fx.receipt(&first)["core"].clone(),
+            fx.receipt(&second)["core"].clone(),
+        );
+        assert_eq!(c1["commit"], old_head);
+        assert_eq!(
+            c2["commit"],
+            fx.head(),
+            "the reuse receipt is for this commit"
+        );
+        c1["commit"] = Value::Null;
+        c2["commit"] = Value::Null;
+        assert_eq!(c1, c2, "everything else in core is the source's");
+    }
+
+    #[test]
+    fn a_failed_result_is_reused_too_and_still_fails() {
+        let fx = Fx::new(FAILING_SCRIPT);
+        let first = fx.run(&fx.opts());
+        assert_eq!(first.verdict, Verdict::Fail);
+        let second = fx.run(&fx.opts());
+        assert_eq!(second.verdict, Verdict::Fail);
+        assert_eq!(second.reason, first.reason);
+        assert_eq!(reused_from(&second), first.receipt_digest.as_deref());
+        assert_eq!(fx.runs("a"), 1);
+    }
+
+    // ---- misses --------------------------------------------------------
+
+    #[test]
+    fn miss_when_a_declared_input_changes() {
+        let fx = Fx::new(SCRIPT);
+        fresh_pass(&fx);
+        fx.commit("data/in.txt", "two\n");
+        let second = fx.run(&fx.opts());
+        assert_eq!(second.verdict, Verdict::Pass);
+        assert!(
+            matches!(second.cache, CacheNote::Miss(_)),
+            "{:?}",
+            second.cache
+        );
+        assert_eq!(fx.runs("a"), 2, "the program must run again");
+        // And the new result is now the one that is reused.
+        let third = fx.run(&fx.opts());
+        assert_eq!(reused_from(&third), second.receipt_digest.as_deref());
+        assert_eq!(fx.runs("a"), 2);
+    }
+
+    #[test]
+    fn miss_when_the_program_changes() {
+        let fx = Fx::new(SCRIPT);
+        fresh_pass(&fx);
+        fx.commit("tools/run.sh", &format!("{SCRIPT}# edited\n"));
+        let second = fx.run(&fx.opts());
+        assert!(
+            matches!(second.cache, CacheNote::Miss(_)),
+            "{:?}",
+            second.cache
+        );
+        assert_eq!(fx.runs("a"), 2);
+    }
+
+    #[test]
+    fn miss_when_the_manifest_changes_even_by_a_comment() {
+        let fx = Fx::new(SCRIPT);
+        fresh_pass(&fx);
+        let text = fs::read_to_string(fx.repo.path().join("tests/a.gate")).unwrap();
+        fx.commit("tests/a.gate", &format!("# note\n{text}"));
+        let second = fx.run(&fx.opts());
+        assert!(
+            matches!(second.cache, CacheNote::Miss(_)),
+            "{:?}",
+            second.cache
+        );
+        assert_eq!(fx.runs("a"), 2);
+    }
+
+    #[test]
+    fn miss_when_the_machine_differs() {
+        let fx = Fx::new(SCRIPT);
+        fresh_pass(&fx);
+        let mut o = fx.opts();
+        o.hardware.qemu_available = true;
+        let second = fx.run(&o);
+        assert!(
+            matches!(second.cache, CacheNote::Miss(_)),
+            "{:?}",
+            second.cache
+        );
+        assert_eq!(fx.runs("a"), 2);
+    }
+
+    #[test]
+    fn a_dirty_tree_is_refused_not_answered_from_the_cache() {
+        let fx = Fx::new(SCRIPT);
+        fresh_pass(&fx);
+        write_file(fx.repo.path(), "README", "dirty\n", false);
+        let second = fx.run(&fx.opts());
+        assert_eq!(second.verdict, Verdict::NotRun);
+        assert_eq!(second.reason, "dirty_tree");
+        assert_eq!(reused_from(&second), None);
+        assert_eq!(fx.runs("a"), 1);
+    }
+
+    #[test]
+    fn miss_on_a_dirty_tree_even_when_the_run_is_allowed() {
+        let fx = Fx::new(SCRIPT);
+        fresh_pass(&fx);
+        write_file(fx.repo.path(), "README", "dirty\n", false);
+        let mut o = fx.opts();
+        o.allow_dirty = true;
+        let second = fx.run(&o);
+        assert_eq!(second.verdict, Verdict::Pass);
+        assert!(
+            matches!(second.cache, CacheNote::Skipped(_)),
+            "{:?}",
+            second.cache
+        );
+        assert_eq!(fx.runs("a"), 2, "a dirty tree always runs");
+        let r = fx.receipt(&second);
+        assert_eq!(r["volatile"]["cache"]["mode"], "disabled");
+        assert_eq!(r["volatile"]["cache"]["reused"], false);
+    }
+
+    #[test]
+    fn a_receipt_from_a_dirty_tree_is_never_a_source() {
+        let fx = Fx::new(SCRIPT);
+        write_file(fx.repo.path(), "README", "dirty\n", false);
+        let mut o = fx.opts();
+        o.allow_dirty = true;
+        let dirty_run = fx.run(&o);
+        assert_eq!(dirty_run.verdict, Verdict::Pass);
+        git(fx.repo.path(), &["checkout", "--", "README"]);
+        let clean_run = fx.run(&fx.opts());
+        assert!(
+            matches!(clean_run.cache, CacheNote::Miss(_)),
+            "{:?}",
+            clean_run.cache
+        );
+        assert_eq!(fx.runs("a"), 2);
+    }
+
+    #[test]
+    fn miss_when_there_is_no_receipt_or_the_receipt_is_gone() {
+        let fx = Fx::new(SCRIPT);
+        // Nothing in the store at all.
+        let first = fx.run(&fx.opts());
+        assert!(
+            matches!(first.cache, CacheNote::Miss(_)),
+            "{:?}",
+            first.cache
+        );
+        assert_eq!(fx.runs("a"), 1);
+        // The only receipt is removed.
+        fs::remove_file(first.receipt_path.as_ref().unwrap()).unwrap();
+        let second = fx.run(&fx.opts());
+        assert!(
+            matches!(second.cache, CacheNote::Miss(_)),
+            "{:?}",
+            second.cache
+        );
+        assert_eq!(fx.runs("a"), 2);
+    }
+
+    #[test]
+    fn miss_when_a_log_the_receipt_names_is_missing() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        let sha = fx.receipt(&first)["core"]["stdout_sha256"]
+            .as_str()
+            .unwrap()
+            .to_string();
+        fs::remove_file(fx.ev.path().join("out/blobs").join(format!("{sha}.log"))).unwrap();
+        let second = fx.run(&fx.opts());
+        assert!(
+            matches!(second.cache, CacheNote::Miss(_)),
+            "{:?}",
+            second.cache
+        );
+        assert_eq!(fx.runs("a"), 2);
+    }
+
+    #[test]
+    fn a_receipt_that_is_itself_a_reuse_is_not_a_source() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        let second = fx.run(&fx.opts());
+        assert!(reused_from(&second).is_some());
+        // Only the reuse receipt is left.
+        fs::remove_file(first.receipt_path.as_ref().unwrap()).unwrap();
+        let third = fx.run(&fx.opts());
+        assert!(
+            matches!(third.cache, CacheNote::Miss(_)),
+            "{:?}",
+            third.cache
+        );
+        assert_eq!(fx.runs("a"), 2);
+    }
+
+    // ---- forced rerun and never ---------------------------------------
+
+    #[test]
+    fn no_cache_forces_a_fresh_run_and_says_so_in_the_receipt() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        let mut o = fx.opts();
+        o.no_cache = true;
+        let second = fx.run(&o);
+        assert_eq!(second.verdict, Verdict::Pass);
+        assert!(
+            matches!(second.cache, CacheNote::Skipped(_)),
+            "{:?}",
+            second.cache
+        );
+        assert_eq!(fx.runs("a"), 2);
+        let r = fx.receipt(&second);
+        assert_eq!(r["volatile"]["cache"]["mode"], "disabled");
+        assert_eq!(r["volatile"]["cache"]["reused"], false);
+        assert_eq!(r["volatile"]["cache"]["reused_from"], Value::Null);
+        // The fresh result is a valid source for a later ordinary run.
+        let third = fx.run(&fx.opts());
+        assert_eq!(reused_from(&third), second.receipt_digest.as_deref());
+        assert_ne!(reused_from(&third), first.receipt_digest.as_deref());
+        assert_eq!(fx.runs("a"), 2);
+    }
+
+    #[test]
+    fn a_gate_that_says_cache_never_always_runs() {
+        let fx = Fx::new(SCRIPT);
+        let counter = fx.counter("a");
+        let text = gate_text("C-A", &[], &counter, "cache: never\n");
+        fx.commit("tests/a.gate", &text);
+        let first = fx.run(&fx.opts());
+        assert_eq!(first.verdict, Verdict::Pass);
+        let second = fx.run(&fx.opts());
+        assert!(
+            matches!(second.cache, CacheNote::Skipped(_)),
+            "{:?}",
+            second.cache
+        );
+        assert_eq!(fx.runs("a"), 2);
+        assert_eq!(fx.receipt(&second)["volatile"]["cache"]["mode"], "never");
+    }
+
+    #[test]
+    fn replacement_args_never_use_or_feed_the_cache() {
+        let fx = Fx::new(SCRIPT);
+        let other = fx.counter("other");
+        let mut o = fx.opts();
+        o.args_override = Some(vec![other.display().to_string()]);
+        // 1. A run with replacement args does not reuse an ordinary run.
+        fresh_pass(&fx);
+        let with_args = fx.run(&o);
+        assert!(
+            matches!(with_args.cache, CacheNote::Skipped(_)),
+            "{:?}",
+            with_args.cache
+        );
+        assert_eq!(fx.runs("other"), 1);
+        // 2. And an ordinary run does not reuse the replacement-args run:
+        //    remove the ordinary receipt, the other one must not stand in.
+        let fx2 = Fx::new(SCRIPT);
+        let other2 = fx2.counter("other");
+        let mut o2 = fx2.opts();
+        o2.args_override = Some(vec![other2.display().to_string()]);
+        let first = fx2.run(&o2);
+        assert_eq!(first.verdict, Verdict::Pass);
+        let plain = fx2.run(&fx2.opts());
+        assert!(
+            matches!(plain.cache, CacheNote::Miss(_)),
+            "{:?}",
+            plain.cache
+        );
+        assert_eq!(fx2.runs("a"), 1, "the ordinary run really ran");
+    }
+
+    // ---- dependencies ---------------------------------------------------
+
+    fn two_gate_fixture() -> Fx {
+        let fx = Fx::new(SCRIPT);
+        let b = gate_text("C-B", &["C-A"], &fx.counter("b"), "");
+        fx.commit("tests/b.gate", &b);
+        fx
+    }
+
+    fn run_all(fx: &Fx, opts: &Options) -> BTreeMap<String, Outcome> {
+        let g = graph::load(fx.repo.path()).unwrap();
+        let all: BTreeSet<usize> = (0..g.len()).collect();
+        runner::run_graph(fx.repo.path(), &g, &all, opts)
+            .unwrap()
+            .results
+            .into_iter()
+            .collect()
+    }
+
+    #[test]
+    fn a_whole_graph_is_reused_including_gates_that_rest_on_a_reused_gate() {
+        let fx = two_gate_fixture();
+        let first = run_all(&fx, &fx.opts());
+        assert!(first.values().all(|o| o.verdict == Verdict::Pass));
+        assert_eq!((fx.runs("a"), fx.runs("b")), (1, 1));
+        let second = run_all(&fx, &fx.opts());
+        assert_eq!(
+            reused_from(&second["C-A"]),
+            first["C-A"].receipt_digest.as_deref()
+        );
+        assert_eq!(
+            reused_from(&second["C-B"]),
+            first["C-B"].receipt_digest.as_deref(),
+            "B rests on a reused A and must still be a hit"
+        );
+        assert_eq!((fx.runs("a"), fx.runs("b")), (1, 1));
+    }
+
+    #[test]
+    fn a_change_under_a_dependency_reruns_it_and_everything_that_rests_on_it() {
+        let fx = two_gate_fixture();
+        run_all(&fx, &fx.opts());
+        // Gate A's own input (data/ is shared by both gates here, so give B a
+        // different one first to see that only the chain moves).
+        let b = gate_text("C-B", &["C-A"], &fx.counter("b"), "").replace("data/", "other/");
+        fx.commit("other/x.txt", "x\n");
+        fx.commit("tests/b.gate", &b);
+        run_all(&fx, &fx.opts());
+        assert_eq!((fx.runs("a"), fx.runs("b")), (1, 2), "only B changed");
+        fx.commit("data/in.txt", "two\n");
+        let after = run_all(&fx, &fx.opts());
+        assert!(after.values().all(|o| reused_from(o).is_none()));
+        assert_eq!(
+            (fx.runs("a"), fx.runs("b")),
+            (2, 3),
+            "A changed, so B reruns too"
+        );
+    }
+
+    // ---- the key itself -------------------------------------------------
+
+    fn base() -> Experiment {
+        Experiment {
+            manifest_digest: "m".repeat(64),
+            binary_sha256: Some("b".repeat(64)),
+            build_inputs_digest: "i".repeat(64),
+            machine_digest: "c".repeat(64),
+            dependencies: vec![("G".to_string(), "d".repeat(64))],
+            pins: json!([]),
+            args_override: None,
+        }
+    }
+
+    #[test]
+    fn the_key_is_deterministic() {
+        let idx = Index::default();
+        assert_eq!(key(&base(), &idx).unwrap(), key(&base(), &idx).unwrap());
+        assert_eq!(key(&base(), &idx).unwrap().len(), 64);
+    }
+
+    #[test]
+    fn every_key_member_changes_the_key() {
+        let idx = Index::default();
+        let k0 = key(&base(), &idx).unwrap();
+        let mut variants: Vec<(&str, Experiment)> = Vec::new();
+        let mut e = base();
+        e.manifest_digest = "x".repeat(64);
+        variants.push(("manifest", e));
+        let mut e = base();
+        e.binary_sha256 = Some("x".repeat(64));
+        variants.push(("binary", e));
+        let mut e = base();
+        e.binary_sha256 = None;
+        variants.push(("no binary", e));
+        let mut e = base();
+        e.build_inputs_digest = "x".repeat(64);
+        variants.push(("inputs", e));
+        let mut e = base();
+        e.machine_digest = "x".repeat(64);
+        variants.push(("machine", e));
+        let mut e = base();
+        e.dependencies = vec![("G".to_string(), "x".repeat(64))];
+        variants.push(("dependency receipt", e));
+        let mut e = base();
+        e.dependencies = vec![];
+        variants.push(("no dependency", e));
+        let mut e = base();
+        e.pins = json!([{ "name": "p", "commit": "c" }]);
+        variants.push(("pins", e));
+        let mut e = base();
+        e.args_override = Some(vec!["x".to_string()]);
+        variants.push(("replacement args", e));
+        for (what, e) in variants {
+            assert_ne!(key(&e, &idx).unwrap(), k0, "{what} must change the key");
+        }
+    }
+
+    #[test]
+    fn policy_cache_never_beats_everything() {
+        assert_eq!(policy(true, false), Mode::Allow);
+        assert_eq!(policy(true, true), Mode::Disabled);
+        assert_eq!(policy(false, false), Mode::Never);
+        assert_eq!(policy(false, true), Mode::Never);
+        assert_eq!(Mode::Allow.as_str(), "allow");
+        assert_eq!(Mode::Never.as_str(), "never");
+        assert_eq!(Mode::Disabled.as_str(), "disabled");
+    }
+
+    // ---- receipts that carry the right key but cannot be trusted ---------
+
+    /// A store holding one forged copy of `first`'s receipt (and its logs), so
+    /// the original cannot mask the result.
+    fn forged(fx: &Fx, first: &Outcome, edit: impl FnOnce(&mut Value)) -> (TempDir, Value) {
+        let original = fx.receipt(first);
+        let dir = TempDir::new("c-forged");
+        let blobs = dir.path().join("blobs");
+        fs::create_dir_all(&blobs).unwrap();
+        for e in fs::read_dir(fx.ev.path().join("out/blobs"))
+            .unwrap()
+            .flatten()
+        {
+            fs::copy(e.path(), blobs.join(e.file_name())).unwrap();
+        }
+        let mut v = original.clone();
+        edit(&mut v);
+        Store::new(dir.path()).put_receipt(&v).unwrap();
+        (dir, original)
+    }
+
+    fn lookup_in(dir: &TempDir, original: &Value) -> Result<Unusable, ()> {
+        let store = Store::new(dir.path());
+        let index = Index::load(&store);
+        let k = original["volatile"]["cache"]["key"].as_str().unwrap();
+        match lookup(&index, &store, k, &runner::captured_env()) {
+            Lookup::Hit(_) => Err(()),
+            Lookup::Miss(Miss::Unusable { why, .. }) => Ok(why),
+            Lookup::Miss(Miss::NoReceipt) => panic!("the forged receipt must be found by its key"),
+        }
+    }
+
+    #[test]
+    fn the_unedited_copy_is_a_hit_so_the_forgery_tests_mean_something() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        let (dir, original) = forged(&fx, &first, |_| {});
+        assert_eq!(lookup_in(&dir, &original), Err(()));
+    }
+
+    #[test]
+    fn not_run_and_blocked_receipts_are_never_sources() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        for verdict in [
+            "NOT_RUN",
+            "BLOCKED_HARDWARE",
+            "BLOCKED_OPERATOR",
+            "MISSING_IMPLEMENTATION",
+        ] {
+            let (dir, o) = forged(&fx, &first, |v| {
+                v["core"]["derived_verdict"] = json!(verdict)
+            });
+            assert_eq!(
+                lookup_in(&dir, &o),
+                Ok(Unusable::NotAnExperiment),
+                "{verdict}"
+            );
+        }
+    }
+
+    #[test]
+    fn unclean_moved_or_timed_out_receipts_are_never_sources() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        let (dir, o) = forged(&fx, &first, |v| {
+            v["core"]["tree_clean_before"] = json!(false)
+        });
+        assert_eq!(lookup_in(&dir, &o), Ok(Unusable::UncleanTree));
+        let (dir, o) = forged(&fx, &first, |v| {
+            v["core"]["tree_clean_after"] = json!(false)
+        });
+        assert_eq!(lookup_in(&dir, &o), Ok(Unusable::UncleanTree));
+        let (dir, o) = forged(&fx, &first, |v| {
+            v["core"]["commit_unchanged_after"] = json!(false)
+        });
+        assert_eq!(lookup_in(&dir, &o), Ok(Unusable::HeadMoved));
+        let (dir, o) = forged(&fx, &first, |v| {
+            v["volatile"]["timeout_exceeded"] = json!(true)
+        });
+        assert_eq!(lookup_in(&dir, &o), Ok(Unusable::TimedOut));
+    }
+
+    #[test]
+    fn a_stored_key_that_its_own_contents_do_not_hash_to_is_not_trusted() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        // The receipt claims the key but its inputs digest says otherwise.
+        let (dir, o) = forged(&fx, &first, |v| {
+            v["core"]["build_inputs_digest"] = json!("0".repeat(64))
+        });
+        assert_eq!(lookup_in(&dir, &o), Ok(Unusable::KeyMismatch));
+        let (dir, o) = forged(&fx, &first, |v| {
+            v["core"]["manifest_digest"] = json!("0".repeat(64))
+        });
+        assert_eq!(lookup_in(&dir, &o), Ok(Unusable::KeyMismatch));
+    }
+
+    #[test]
+    fn a_machine_descriptor_that_does_not_match_its_digest_is_not_trusted() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        let (dir, o) = forged(&fx, &first, |v| {
+            v["core"]["machine"]["cpu_count"] = json!(9999)
+        });
+        assert_eq!(lookup_in(&dir, &o), Ok(Unusable::MachineMismatch));
+    }
+
+    #[test]
+    fn a_different_captured_environment_is_not_the_same_experiment() {
+        let fx = Fx::new(SCRIPT);
+        let first = fresh_pass(&fx);
+        let (dir, o) = forged(&fx, &first, |v| {
+            v["core"]["env"]["RUSTFLAGS"] = json!("-C opt-level=3")
+        });
+        assert_eq!(lookup_in(&dir, &o), Ok(Unusable::EnvDiffers));
+    }
+
+    // ---- why --------------------------------------------------------------
+
+    fn why_lines(fx: &Fx) -> String {
+        let g = graph::load(fx.repo.path()).unwrap();
+        let store = fx.store();
+        let index = Index::load(&store);
+        let target = g.index_of("C-A").unwrap();
+        let facts = explain_chain(fx.repo.path(), &g, &index, &fx.opts(), &fx.head(), target);
+        facts[&target].join("\n")
+    }
+
+    #[test]
+    fn why_explains_a_hit_and_then_a_miss_and_what_changed() {
+        let fx = Fx::new(SCRIPT);
+        let before = why_lines(&fx);
+        assert!(before.contains("cache: miss"), "{before}");
+        assert!(
+            before.contains("no earlier receipt has this key"),
+            "{before}"
+        );
+        let first = fresh_pass(&fx);
+        fx.commit("README", "changed\n");
+        let hit = why_lines(&fx);
+        assert!(hit.contains("cache: hit"), "{hit}");
+        assert!(
+            hit.contains(&first.receipt_digest.clone().unwrap()[..12]),
+            "{hit}"
+        );
+        fx.commit("data/in.txt", "two\n");
+        let miss = why_lines(&fx);
+        assert!(miss.contains("cache: miss"), "{miss}");
+        assert!(
+            miss.contains("these changed: the declared input files"),
+            "{miss}"
+        );
+    }
+
+    #[test]
+    fn why_says_so_when_a_receipt_was_reused_and_when_the_tree_is_dirty() {
+        let fx = Fx::new(SCRIPT);
+        fresh_pass(&fx);
+        let reused = fx.run(&fx.opts());
+        assert!(reused_from(&reused).is_some());
+        let text = why_lines(&fx);
+        assert!(text.contains("was reused from"), "{text}");
+        assert!(text.contains("not qualification evidence"), "{text}");
+        write_file(fx.repo.path(), "README", "dirty\n", false);
+        let dirty = why_lines(&fx);
+        assert!(dirty.contains("uncommitted changes"), "{dirty}");
+        assert!(!dirty.contains("cache: hit"), "{dirty}");
+    }
+
+    #[test]
+    fn why_for_a_dependent_follows_a_reused_dependency() {
+        let fx = two_gate_fixture();
+        run_all(&fx, &fx.opts());
+        fx.commit("README", "changed\n");
+        let g = graph::load(fx.repo.path()).unwrap();
+        let index = Index::load(&fx.store());
+        let b = g.index_of("C-B").unwrap();
+        let facts = explain_chain(fx.repo.path(), &g, &index, &fx.opts(), &fx.head(), b);
+        assert!(
+            facts[&b].join("\n").contains("cache: hit"),
+            "{:?}",
+            facts[&b]
+        );
+        fx.commit("data/in.txt", "two\n");
+        let index = Index::load(&fx.store());
+        let facts = explain_chain(fx.repo.path(), &g, &index, &fx.opts(), &fx.head(), b);
+        let text = facts[&b].join("\n");
+        assert!(
+            text.contains("depends on C-A, which would run again"),
+            "{text}"
+        );
+    }
+}
diff --git a/tools/aien-test/src/cli.rs b/tools/aien-test/src/cli.rs
index c442aafe..92851cbe 100644
--- a/tools/aien-test/src/cli.rs
+++ b/tools/aien-test/src/cli.rs
@@ -8,8 +8,8 @@
 //! 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.
+//! `test changed`, `test crate:NAME`, `--host/--qemu/--gb10`, `--mutants` and
+//! `--release` come in later slices and are refused here.
 
 use crate::resources::{parse_jobs, JobsSpec};
 use std::path::PathBuf;
@@ -19,7 +19,7 @@ pub const USAGE: &str = "usage:
   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";
+flags: --evidence-dir DIR  --allow-dirty  --no-cache  --jobs host=N,qemu=M  --wait-gpu";
 
 /// Which gates `test` runs.
 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -43,6 +43,8 @@ pub struct Cli {
     pub command: Command,
     pub evidence_dir: Option<PathBuf>,
     pub allow_dirty: bool,
+    /// `--no-cache`: never reuse an earlier result; run every gate fresh.
+    pub no_cache: bool,
     /// 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.
@@ -74,6 +76,7 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> {
     let mut positional: Option<String> = None;
     let mut evidence_dir: Option<PathBuf> = None;
     let mut allow_dirty = false;
+    let mut no_cache = false;
     let mut args: Option<Vec<String>> = None;
     let mut jobs = JobsSpec::default();
     let mut wait_gpu = false;
@@ -97,6 +100,8 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> {
             }
         } else if a == "--allow-dirty" {
             allow_dirty = true;
+        } else if a == "--no-cache" {
+            no_cache = true;
         } else if a == "--wait-gpu" {
             wait_gpu = true;
         } else if a.starts_with('-') {
@@ -133,6 +138,7 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> {
         command,
         evidence_dir,
         allow_dirty,
+        no_cache,
         args,
         jobs,
         wait_gpu,
@@ -159,6 +165,7 @@ mod tests {
         let c = parse_args(&v(&["run", "G"])).unwrap();
         assert_eq!(run_gate(&c), "G");
         assert!(!c.allow_dirty);
+        assert!(!c.no_cache);
         assert!(!c.wait_gpu);
         assert_eq!(c.args, None);
         assert_eq!(c.evidence_dir, None);
@@ -184,6 +191,17 @@ mod tests {
         assert_eq!(c.args, Some(v(&["-x", "y"])));
     }
 
+    #[test]
+    fn no_cache_flag() {
+        let c = parse_args(&v(&["run", "G", "--no-cache"])).unwrap();
+        assert!(c.no_cache);
+        let c = parse_args(&v(&["test", "--no-cache", "./..."])).unwrap();
+        assert!(c.no_cache);
+        assert_eq!(c.command, Command::Test(Selection::All));
+        // --release (qualification mode) is a later slice and stays refused.
+        assert!(parse_args(&v(&["run", "G", "--release"])).is_err());
+    }
+
     #[test]
     fn empty_override_args_are_kept() {
         let c = parse_args(&v(&["run", "G", "--"])).unwrap();
diff --git a/tools/aien-test/src/evidence.rs b/tools/aien-test/src/evidence.rs
index 6c9827cd..1c425e6e 100644
--- a/tools/aien-test/src/evidence.rs
+++ b/tools/aien-test/src/evidence.rs
@@ -192,6 +192,16 @@ impl Store {
         Ok(sha)
     }
 
+    /// True if the stdout/stderr blob `sha` is present in this store (it is
+    /// not read or re-hashed here).
+    pub fn blob_exists(&self, sha: &str) -> bool {
+        sha.len() == 64
+            && sha
+                .bytes()
+                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+            && self.dir.join("blobs").join(format!("{sha}.log")).is_file()
+    }
+
     /// Write `<digest>.json` exclusively, mode 0444, canonical bytes plus one
     /// LF. Identical existing content is success; different content is a
     /// fatal collision. Never overwrites.
@@ -325,6 +335,16 @@ impl Index {
         Index { receipts }
     }
 
+    /// Every verified receipt, oldest first.
+    pub fn receipts(&self) -> &[Stored] {
+        &self.receipts
+    }
+
+    /// The receipt with exactly this digest, if the store has it.
+    pub fn get(&self, digest: &str) -> Option<&Stored> {
+        self.receipts.iter().find(|r| r.digest == digest)
+    }
+
     pub fn len(&self) -> usize {
         self.receipts.len()
     }
diff --git a/tools/aien-test/src/lib.rs b/tools/aien-test/src/lib.rs
index c64d1ff0..d3db6cbe 100644
--- a/tools/aien-test/src/lib.rs
+++ b/tools/aien-test/src/lib.rs
@@ -1,11 +1,13 @@
-//! 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`.
+//! AIEN-TEST (ADR 0028), Slices A to C: gate manifests, verdict derivation,
+//! immutable evidence receipts, a runner for one gate or a whole graph of
+//! gates with resource pools, GPU locks, dependency handling and `why`, and
+//! the digest cache that reuses a result only for an identical experiment.
 //!
 //! Tests report observations; this crate derives the verdict and writes an
 //! immutable, content-addressed receipt. See `manifest`, `verdict`,
-//! `evidence`, `process`, `runner`, `graph`, `resources`, `why`.
+//! `evidence`, `process`, `runner`, `graph`, `resources`, `why`, `cache`.
 
+pub mod cache;
 pub mod cli;
 pub mod evidence;
 pub mod graph;
diff --git a/tools/aien-test/src/main.rs b/tools/aien-test/src/main.rs
index a0ff6fcd..9172b2aa 100644
--- a/tools/aien-test/src/main.rs
+++ b/tools/aien-test/src/main.rs
@@ -11,7 +11,7 @@
 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::runner::{self, CacheNote, Options, RunError};
 use aien_test::verdict::Verdict;
 use aien_test::why;
 use std::collections::BTreeSet;
@@ -60,6 +60,7 @@ fn options(cli: &Cli, root: &Path) -> Result<Options, i32> {
     };
     let mut opts = Options::new(evidence_dir);
     opts.allow_dirty = cli.allow_dirty;
+    opts.no_cache = cli.no_cache;
     opts.args_override = cli.args.clone();
     opts.pool_sizes = opts.pool_sizes.with(cli.jobs);
     opts.gpu.wait = cli.wait_gpu;
@@ -90,6 +91,21 @@ fn repo_root_or_report(cwd: &Path) -> Result<PathBuf, i32> {
     })
 }
 
+/// Say plainly what the cache did. A reused result is never presented as a
+/// fresh run.
+fn print_cache(note: &CacheNote) {
+    match note {
+        CacheNote::Reused { from } => {
+            println!("REUSED {from}");
+            println!(
+                "CACHE reused: an earlier run of exactly this experiment already has this result, so it was not run again (use --no-cache to force a fresh run)"
+            );
+        }
+        CacheNote::Miss(why) => println!("CACHE miss: {why}; the gate was run"),
+        CacheNote::Skipped(why) => println!("CACHE not used: {why}"),
+    }
+}
+
 fn cmd_run(cli: &Cli, gate: &str, cwd: &Path) -> i32 {
     let manifest_path = match runner::locate_gate(cwd, gate) {
         Ok(p) => p,
@@ -115,6 +131,7 @@ fn cmd_run(cli: &Cli, gate: &str, cwd: &Path) -> i32 {
             if let Some(p) = &o.receipt_path {
                 println!("RECEIPT {}", p.display());
             }
+            print_cache(&o.cache);
             if o.reason.is_empty() {
                 println!("AIEN_TEST: {}", o.verdict.as_str());
             } else {
@@ -164,6 +181,7 @@ fn cmd_test(cli: &Cli, selection: &Selection, cwd: &Path) -> i32 {
                 if let Some(p) = &o.receipt_path {
                     println!("RECEIPT {}", p.display());
                 }
+                print_cache(&o.cache);
             }
             println!("AIEN_TEST: {}", campaign.verdict().as_str());
             campaign.exit_code()
@@ -200,7 +218,9 @@ fn cmd_why(cli: &Cli, gate: &str, cwd: &Path) -> i32 {
         }
     };
     let index = Index::load(&Store::new(&opts.evidence_dir));
-    for line in why::explain(&graph, &index, &commit, target) {
+    let cache_facts =
+        aien_test::cache::explain_chain(&root, &graph, &index, &opts, &commit, target);
+    for line in why::explain(&graph, &index, &commit, target, &cache_facts) {
         println!("{line}");
     }
     0
diff --git a/tools/aien-test/src/runner.rs b/tools/aien-test/src/runner.rs
index afa23d74..1b26e405 100644
--- a/tools/aien-test/src/runner.rs
+++ b/tools/aien-test/src/runner.rs
@@ -21,9 +21,8 @@
 //!   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, Index, Store, SCHEMA,
-};
+use crate::cache;
+use crate::evidence::{build_receipt, canonical_digest, sha256_hex, utc_string, Index, Store};
 use crate::graph::Graph;
 use crate::manifest::{self, Manifest};
 use crate::process::{self, RunSpec};
@@ -45,6 +44,8 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
 pub struct Options {
     pub evidence_dir: PathBuf,
     pub allow_dirty: bool,
+    /// `--no-cache`: never reuse an earlier result; every gate runs fresh.
+    pub no_cache: bool,
     pub args_override: Option<Vec<String>>,
     pub kill_grace: Duration,
     /// Sizes of the host and qemu pools (the gb10 pool is always 1).
@@ -62,6 +63,7 @@ impl Options {
         Options {
             evidence_dir,
             allow_dirty: false,
+            no_cache: false,
             args_override: None,
             kill_grace: Duration::from_secs(10),
             pool_sizes: PoolSizes::detect(),
@@ -94,6 +96,20 @@ pub struct Outcome {
     pub reason: String,
     pub receipt_path: Option<PathBuf>,
     pub receipt_digest: Option<String>,
+    /// What the digest cache did for this gate.
+    pub cache: CacheNote,
+}
+
+/// What the cache did, in words the report prints.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum CacheNote {
+    /// The result was reused, not rerun. Holds the digest of the fresh
+    /// receipt it was taken from.
+    Reused { from: String },
+    /// The cache was consulted and had nothing usable; the gate ran.
+    Miss(String),
+    /// The cache was not consulted; the gate ran (or was refused). Holds why.
+    Skipped(String),
 }
 
 fn git_out(root: &Path, args: &[&str]) -> Result<String, String> {
@@ -377,7 +393,7 @@ fn machine(hw: &Hardware) -> Value {
     })
 }
 
-fn captured_env() -> Value {
+pub(crate) fn captured_env() -> Value {
     let mut m = Map::new();
     for k in [
         "AIEN_PROOF_OFF",
@@ -396,6 +412,43 @@ fn captured_env() -> Value {
     Value::Object(m)
 }
 
+/// Whether the working tree has uncommitted changes (including untracked
+/// files).
+pub(crate) fn working_tree_dirty(root: &Path) -> Result<bool, String> {
+    porcelain(root).map(|p| !p.is_empty())
+}
+
+/// The digests that identify one experiment besides its manifest and
+/// dependencies: the program, the declared inputs, the machine.
+pub(crate) struct Identity {
+    pub binary_sha: Option<String>,
+    pub inputs_digest: String,
+    pub machine: Value,
+    pub machine_digest: String,
+}
+
+pub(crate) fn identity(
+    root: &Path,
+    manifest_path: &Path,
+    m: &Manifest,
+    hw: &Hardware,
+) -> Result<Identity, crate::evidence::StoreError> {
+    let exec_path = root.join(&m.exec);
+    let binary_sha = if exec_path.is_file() {
+        fs::read(&exec_path).ok().map(|b| sha256_hex(&b))
+    } else {
+        None
+    };
+    let manifest_rel = manifest_path.strip_prefix(root).ok();
+    let machine = machine(hw);
+    let machine_digest = canonical_digest(&machine)?;
+    Ok(Identity {
+        binary_sha,
+        inputs_digest: build_inputs_digest(root, manifest_rel, m),
+        machine,
+        machine_digest,
+    })
+}
 fn now_secs() -> u64 {
     SystemTime::now()
         .duration_since(UNIX_EPOCH)
@@ -457,6 +510,83 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru
         ..Facts::default()
     };
 
+    // Identify the experiment before anything runs, so the cache lookup and
+    // the receipt agree on what was hashed (ADR Decision 7).
+    let id = identity(root, job.manifest_path, m, &opts.hardware).map_err(fatal)?;
+    let store = Store::new(&opts.evidence_dir);
+    let tree_clean = before.is_empty();
+    let mut mode = cache::policy(m.cache_allowed, opts.no_cache);
+    let off_reason: &str = if opts.no_cache {
+        "--no-cache"
+    } else if opts.args_override.is_some() {
+        "replacement arguments were given after --"
+    } else {
+        "the tree has uncommitted changes"
+    };
+    if mode == cache::Mode::Allow && (opts.args_override.is_some() || !tree_clean) {
+        mode = cache::Mode::Disabled;
+    }
+    let dependencies: Vec<(String, String)> = dependency_rows(&facts.deps).into_iter().collect();
+    // Receipts are read when a lookup may happen, and to follow a reused
+    // dependency back to the receipt it stands for.
+    let index = if mode == cache::Mode::Allow || !dependencies.is_empty() {
+        Index::load(&store)
+    } else {
+        Index::default()
+    };
+    let experiment = cache::Experiment {
+        manifest_digest: m.digest.clone(),
+        binary_sha256: id.binary_sha.clone(),
+        build_inputs_digest: id.inputs_digest.clone(),
+        machine_digest: id.machine_digest.clone(),
+        dependencies,
+        pins: json!([]),
+        args_override: opts.args_override.clone(),
+    };
+    let cache_key = cache::key(&experiment, &index).map_err(fatal)?;
+    let mut note = match mode {
+        cache::Mode::Never => CacheNote::Skipped("the manifest says cache: never".to_string()),
+        cache::Mode::Disabled => CacheNote::Skipped(off_reason.to_string()),
+        cache::Mode::Allow => {
+            CacheNote::Skipped("the gate cannot run now, so there was nothing to reuse".to_string())
+        }
+    };
+    // Reuse only when the gate would really have run: a refusal, a blocked
+    // verdict or a dependency that is not PASS is reported as it is, never
+    // hidden behind an old result.
+    if mode == cache::Mode::Allow && !evidence_inside && verdict::pre_run(m, &facts).is_none() {
+        match cache::lookup(&index, &store, &cache_key, &captured_env()) {
+            cache::Lookup::Hit(src) => {
+                let reused_verdict = src
+                    .verdict()
+                    .ok_or_else(|| fatal("a reusable receipt has no verdict"))?;
+                let volatile = json!({
+                    "started_utc": utc_string(started),
+                    "finished_utc": utc_string(now_secs()),
+                    "duration_ms": t0.elapsed().as_millis() as u64,
+                    "pool": m.pool(),
+                    "pool_wait_ms": job.pool_wait_ms,
+                    "runner": { "name": "aien-test", "version": env!("CARGO_PKG_VERSION"), "impl": "rust" },
+                    "cache": cache::cache_member(&cache_key, Some(&src.digest), mode),
+                    "timeout_exceeded": false,
+                });
+                let receipt = build_receipt(cache::reused_core(src, &commit), volatile);
+                let (digest, path) = store.put_receipt(&receipt).map_err(fatal)?;
+                drop(permit);
+                return Ok(Outcome {
+                    verdict: reused_verdict,
+                    reason: src.reason().to_string(),
+                    receipt_path: Some(path),
+                    receipt_digest: Some(digest),
+                    cache: CacheNote::Reused {
+                        from: src.digest.clone(),
+                    },
+                });
+            }
+            cache::Lookup::Miss(miss) => note = CacheNote::Miss(miss.text()),
+        }
+    }
+
     // 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() {
@@ -516,25 +646,12 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru
             reason: derived.reason,
             receipt_path: None,
             receipt_digest: None,
+            cache: note,
         });
     }
 
-    let store = Store::new(&opts.evidence_dir);
     let stdout_sha = store.put_blob(&stdout).map_err(fatal)?;
     let stderr_sha = store.put_blob(&stderr).map_err(fatal)?;
-    let binary_sha = if exec_exists {
-        fs::read(&exec_path).ok().map(|b| sha256_hex(&b))
-    } else {
-        None
-    };
-    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(&opts.hardware);
-    let machine_digest = canonical_digest(&machine_v).map_err(fatal)?;
 
     let observations: Vec<Value> = facts
         .observations
@@ -554,7 +671,8 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru
             json!({ "name": c, "passed": passed })
         })
         .collect();
-    let dependencies: Vec<Value> = dependency_rows(&facts.deps)
+    let dependency_values: Vec<Value> = experiment
+        .dependencies
         .iter()
         .map(|(gate, receipt)| json!({ "gate": gate, "receipt": receipt }))
         .collect();
@@ -568,13 +686,13 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru
     core.insert("tree_clean_before".into(), json!(before.is_empty()));
     core.insert("tree_clean_after".into(), json!(after.is_empty()));
     core.insert("commit_unchanged_after".into(), json!(!facts.head_moved));
-    if let Some(b) = &binary_sha {
+    if let Some(b) = &id.binary_sha {
         core.insert("binary_sha256".into(), json!(b));
     }
-    core.insert("build_inputs_digest".into(), json!(inputs_digest));
+    core.insert("build_inputs_digest".into(), json!(id.inputs_digest));
     core.insert("env".into(), captured_env());
-    core.insert("machine".into(), machine_v);
-    core.insert("machine_digest".into(), json!(machine_digest));
+    core.insert("machine".into(), id.machine.clone());
+    core.insert("machine_digest".into(), json!(id.machine_digest));
     core.insert("exit_status".into(), json!(facts.exit_status));
     core.insert("stdout_sha256".into(), json!(stdout_sha));
     core.insert("stderr_sha256".into(), json!(stderr_sha));
@@ -584,18 +702,7 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru
     core.insert("reason".into(), json!(derived.reason));
     core.insert("mutants".into(), json!([]));
     core.insert("checks".into(), Value::Array(checks));
-    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,
-        "runner_schema": SCHEMA,
-        "pins": [],
-    }))
-    .map_err(fatal)?;
+    core.insert("dependencies".into(), Value::Array(dependency_values));
 
     let volatile = json!({
         "started_utc": utc_string(started),
@@ -604,7 +711,7 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru
         "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" },
+        "cache": cache::cache_member(&cache_key, None, mode),
         "timeout_exceeded": timeout_exceeded,
     });
 
@@ -615,6 +722,7 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru
         reason: derived.reason,
         receipt_path: Some(path),
         receipt_digest: Some(digest),
+        cache: note,
     })
 }
 
diff --git a/tools/aien-test/src/why.rs b/tools/aien-test/src/why.rs
index d0a7fb55..1434891b 100644
--- a/tools/aien-test/src/why.rs
+++ b/tools/aien-test/src/why.rs
@@ -14,9 +14,10 @@
 //! - 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.
+//! its verdict is, and whether it was made at the current commit. Since Slice
+//! C it also says, per gate, what the digest cache would do now: reuse an
+//! earlier receipt, or run again and which of the manifest, program, inputs,
+//! machine or dependencies changed (`crate::cache::explain_chain`).
 
 use crate::evidence::{Index, Stored};
 use crate::graph::Graph;
@@ -160,6 +161,8 @@ struct Report<'a> {
     states: BTreeMap<usize, State>,
     shown: BTreeSet<usize>,
     lines: Vec<String>,
+    /// Plain lines about the digest cache, per gate.
+    cache: &'a BTreeMap<usize, Vec<String>>,
 }
 
 impl Report<'_> {
@@ -180,6 +183,13 @@ impl Report<'_> {
             )],
             Evidence::Absent => vec!["no receipt in the evidence store".to_string()],
         };
+        if let Some(c) = self
+            .graph
+            .index_of(&node.id)
+            .and_then(|i| self.cache.get(&i))
+        {
+            facts.extend(c.iter().cloned());
+        }
         if own_state(&ev) == State::Pass {
             for &d in &node.deps {
                 if self.state(d) != State::Pass {
@@ -238,7 +248,13 @@ pub fn states(graph: &Graph, index: &Index, commit: &str, target: usize) -> BTre
 }
 
 /// The full report for `target` at `commit`, as lines to print.
-pub fn explain(graph: &Graph, index: &Index, commit: &str, target: usize) -> Vec<String> {
+pub fn explain(
+    graph: &Graph,
+    index: &Index,
+    commit: &str,
+    target: usize,
+    cache: &BTreeMap<usize, Vec<String>>,
+) -> Vec<String> {
     let mut report = Report {
         graph,
         index,
@@ -246,6 +262,7 @@ pub fn explain(graph: &Graph, index: &Index, commit: &str, target: usize) -> Vec
         states: states(graph, index, commit, target),
         shown: BTreeSet::new(),
         lines: Vec::new(),
+        cache,
     };
     report.lines.push(format!(
         "why {} at commit {}",
@@ -258,7 +275,7 @@ pub fn explain(graph: &Graph, index: &Index, commit: &str, target: usize) -> Vec
             .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)"
+        "cache: a result is reused only when the manifest, program, declared inputs, machine and dependency receipts all have the same digests as an earlier fresh run; anything else, a dirty tree, or --no-cache runs the gate"
             .to_string(),
     );
     report.lines
@@ -382,7 +399,7 @@ mod tests {
         );
         store.put_receipt(&r).unwrap();
         let index = Index::load(&store);
-        let out = text(&explain(&g, &index, X, id(&g, "G-C")));
+        let out = text(&explain(&g, &index, X, id(&g, "G-C"), &BTreeMap::new()));
         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}");
@@ -409,7 +426,7 @@ mod tests {
         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));
+        let out = text(&explain(&g, &index, X, 0, &BTreeMap::new()));
         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);
@@ -431,7 +448,7 @@ mod tests {
         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")));
+        let out = text(&explain(&g, &index, X, id(&g, "G-B"), &BTreeMap::new()));
         assert!(out.contains("rests on G-A, which is FAILED"), "{out}");
     }
 
@@ -471,7 +488,7 @@ mod tests {
             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")));
+        let out = text(&explain(&g, &index, X, id(&g, "G-A"), &BTreeMap::new()));
         assert!(out.contains("BLOCKED_HARDWARE, reason NO_GB10"), "{out}");
     }
 
@@ -511,7 +528,7 @@ mod tests {
         );
         store.put_receipt(&r).unwrap();
         let index = Index::load(&store);
-        let out = text(&explain(&g, &index, X, 0));
+        let out = text(&explain(&g, &index, X, 0, &BTreeMap::new()));
         assert!(out.contains("gb10 jobs are never killed"), "{out}");
         assert!(out.contains("G-A: PASS"), "{out}");
     }
@@ -530,7 +547,7 @@ mod tests {
             pass(&store, gate, X);
         }
         let index = Index::load(&store);
-        let lines = explain(&g, &index, X, id(&g, "G-D"));
+        let lines = explain(&g, &index, X, id(&g, "G-D"), &BTreeMap::new());
         let out = text(&lines);
         assert_eq!(out.matches("G-A: PASS").count(), 2, "{out}");
         assert_eq!(out.matches("(shown above)").count(), 1, "{out}");
@@ -538,15 +555,15 @@ mod tests {
     }
 
     #[test]
-    fn the_report_says_what_it_does_not_check() {
+    fn the_report_says_what_it_checks_and_how_the_cache_decides() {
         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 lines = explain(&g, &index, X, 0, &BTreeMap::new());
         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!(out.contains("cache: a result is reused only when"), "{out}");
+        assert!(!out.contains("Slice C"), "{out}");
         assert!(lines[0].starts_with("why G-A at commit 111111111111"));
     }
 
@@ -590,7 +607,7 @@ mod tests {
         );
         store.put_receipt(&r).unwrap();
         let index = Index::load(&store);
-        let out = text(&explain(&g, &index, X, 0));
+        let out = text(&explain(&g, &index, X, 0, &BTreeMap::new()));
         assert!(out.contains("uncommitted changes"), "{out}");
     }
 }