Skip to main content

greengate_runtime/
gate_stamp.rs

1//! The record that turns "a declaration exists" into "the check ran".
2//!
3//! Moving a gate entry to commit time (`docs/checks.md`, "Moving a gate entry
4//! earlier") makes the push gate skip a script because a `pre-commit`
5//! declaration covers it. A declaration is a promise on paper: a commit made
6//! with `--no-verify`, from a libgit2 client that runs no hooks, or on a
7//! machine without amont was never judged by it — and until this module
8//! existed, push time had no way to tell those commits from checked ones.
9//!
10//! Three hooks share one record:
11//!
12//! 1. **pre-commit** ([`record`]) writes a one-shot marker into `$GIT_DIR`
13//!    naming the gate scripts that actually ran, bound to the tree the commit
14//!    is about to write (`git write-tree` — during pre-commit the index IS
15//!    the commit's content; `staged_only` parks only the working tree).
16//! 2. **post-commit** ([`bind_to_head`]) consumes the marker and, when the
17//!    marker's tree matches `HEAD^{tree}`, stamps the commit in a notes ref.
18//!    `--no-verify` skips pre-commit but NOT post-commit, so an unchecked
19//!    commit arrives here with no marker and gets no stamp — which is the
20//!    entire point. The tree comparison makes an aborted commit's leftover
21//!    marker harmless, and a retried commit of the SAME tree correctly
22//!    stamped: the check really did run on exactly that content.
23//! 3. **pre-push** ([`stamps_for`]) reads the stamps back and suppresses a
24//!    gate script only for pushes whose relevant commits all carry it.
25//! 4. **pre-push, on the way out** ([`stamp_push`]) writes the push-time
26//!    gates that PASSED onto each pushed tip — and `amont run pre-push`,
27//!    which drives the same dispatcher, writes the same stamp for `HEAD`.
28//!    The next push of that tree finds the stamp and skips the gate. That is
29//!    what lets the suite run BEFORE git opens its connection: a rehearsal
30//!    stamps, the push verifies. And a push that passed the gate but died on
31//!    the wire — a remote that dropped the idle session while the suite ran
32//!    — retries in seconds instead of minutes. Push-time tokens are full
33//!    ids (`pre-push-run-tests-js`), commit-time ones are script names
34//!    (`test`); the two share a note and never collide.
35//!
36//! Every failure mode points the same direction: no marker, a mismatched
37//! tree, a missing note, a rewritten hash — all mean "no stamp", and no stamp
38//! means the push gate RUNS. Nothing here can let an unchecked commit
39//! through; it can only cost a redundant gate run.
40//!
41//! # The second half of the note: what a run COST, and how it ENDED
42//!
43//! The token line above answers one question — may this gate be skipped for
44//! this content — and it is deliberately a set, with no history in it. A
45//! stamp says a gate passed; it cannot say a gate has been passing in four
46//! seconds since the day its test runner stopped finding any tests.
47//!
48//! So the note carries optional extra lines, one per RUN:
49//!
50//! ```text
51//! amont-gate-v1 pre-push-cargo-test
52//! run 1726900000 pre-push-cargo-test pass 412391
53//! run 1726903600 pre-push-audit-js fail 903
54//! ```
55//!
56//! Additive on purpose, and in the only direction that is safe: every reader
57//! that existed before these lines did reads `body.lines().next()` and is
58//! unaffected, and an amont old enough to rewrite the note without them loses
59//! history — never a verdict. The `run` lines are EVIDENCE, read by
60//! [`crate::gate_evidence`]; nothing in this module's skip decisions consults
61//! them, so a corrupted or forged one cannot make a check be skipped.
62//!
63//! One more kind of line, and the one exception to that rule (ADR-0013):
64//!
65//! ```text
66//! deferred cargo-test
67//! ```
68//!
69//! A commit-time gate the busy policy deferred to CI. Pre-push reads it
70//! ([`deferred_for`]) so the gate's push twin defers too instead of running
71//! the suite with the remote's connection held open. It can only ever move a
72//! gate to CI — it is never a token, never stamps, never attests — so a
73//! forged line makes CI run more, never less. Kept apart from the `run`
74//! history, whose [`MAX_RUNS`] trim must not forget it.
75//!
76//! The note's key is the tree, which makes the record a per-FINGERPRINT one
77//! for free: two runs of one gate against one tree are two lines in one note,
78//! and if they disagree the gate is flaky on content that did not change.
79//!
80//! Why a notes ref and not config: notes are keyed by commit, garbage-collect
81//! with unreachable commits (an `greengate.checked.<hash>` config key would
82//! outlive every rebase forever), stay local (notes refs are not pushed by
83//! default), and stay out of `git log` (only `refs/notes/commits` displays by
84//! default). `amont uninstall` deletes the ref; see `uninstall_repo_hooks`.
85
86use std::collections::{HashMap, HashSet};
87use std::path::PathBuf;
88
89/// One complete set of the names a gate stamp lives under: its header, its
90/// four notes refs, the domain of its canonical key, and the attest name set
91/// whose input domain keys its inputs ref (decisions ADR-0068, plan
92/// "greengate signs its notes under green names"). A note is read WHOLE
93/// under one set: the ref it sits in names the set, and its header must be
94/// that set's, so the two never mix inside one note.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub(crate) struct GateNames {
97    /// First line of every note body (and of the marker file).
98    pub format: &'static str,
99    /// The tree- and commit-keyed stamps.
100    pub notes_ref: &'static str,
101    /// The fingerprint-keyed stamps.
102    pub inputs_ref: &'static str,
103    /// The cluster passes (ADR-0016).
104    pub cluster_ref: &'static str,
105    /// The completions that did not pass (ADR-0018).
106    pub done_ref: &'static str,
107    /// Domain of the canonical key in the inputs ref.
108    pub canon_domain: &'static str,
109    /// The attest names whose input domain keys a declared gate's
110    /// fingerprint in the inputs ref.
111    pub attest: git_attest::format::Names,
112}
113
114/// The names stamps have been written under since amont 1.x, and still are
115/// until [`WRITE`] becomes [`GREEN`] (the plan's Phase 4). Removed at the
116/// census.
117pub(crate) const LEGACY: GateNames = GateNames {
118    format: "amont-gate-v1",
119    notes_ref: "amont-gate",
120    inputs_ref: "amont-gate-inputs",
121    cluster_ref: "amont-gate-cluster",
122    done_ref: "amont-gate-done",
123    canon_domain: "amont-gate-canon",
124    attest: git_attest::format::LEGACY,
125};
126
127/// The names stamps are written under from Phase 4. Read first today.
128pub(crate) const GREEN: GateNames = GateNames {
129    format: "greengate-gate-v1",
130    notes_ref: "greengate-gate",
131    inputs_ref: "greengate-gate-inputs",
132    cluster_ref: "greengate-gate-cluster",
133    done_ref: "greengate-gate-done",
134    canon_domain: "greengate-gate-canon",
135    attest: git_attest::format::GREEN,
136};
137
138/// The ONE owner of what is written: [`FORMAT`] and the short `*_REF`
139/// constants below derive from it. The `*_FULL_REF` constants are literals,
140/// held equal to `refs/notes/{short}` by a test. LEGACY until Phase 4.
141pub(crate) const WRITE: GateNames = LEGACY;
142
143/// The order a stamp is read in: the green set first, the legacy one only
144/// for a key the green ref holds no note for.
145pub(crate) const READ: [GateNames; 2] = [GREEN, LEGACY];
146
147/// First token of the marker file and of every note body. Versioned like
148/// `staged_only::FORMAT`: a future amont that changes the shape bumps this,
149/// and an old record is ignored rather than misread.
150pub const FORMAT: &str = WRITE.format;
151
152/// The notes ref, spelled the way `git notes --ref` wants it.
153pub const NOTES_REF: &str = WRITE.notes_ref;
154
155/// The same ref, fully qualified — what `git update-ref -d` needs. A literal,
156/// not derived from [`WRITE`]; a test holds it equal to `refs/notes/{NOTES_REF}`.
157pub const NOTES_FULL_REF: &str = "refs/notes/amont-gate";
158
159/// The second ref: stamps keyed by a gate's declared-input fingerprint
160/// (`.github/attest-inputs`, see [`crate::attest_inputs`]) instead of by the
161/// whole tree. A gate whose inputs a repository declares is reused on any tree
162/// where those inputs are byte-identical — the closing plan commit changes the
163/// tree and none of them. Every key there is an oid that is not an object, as
164/// in attest's own inputs ref, so `git notes prune` on it would drop
165/// everything: never run it, and never merge the ref with `cat_sort_uniq`.
166pub const INPUTS_REF: &str = WRITE.inputs_ref;
167
168/// Where CLUSTER passes are recorded (ADR-0016): the same note format, keyed
169/// by the judged tree, holding tokens of `gate_identity::cluster_token`.
170/// Never `amont-gate` (ADR-0015): a local token here would let the laptop
171/// sign a pass it never ran.
172pub const CLUSTER_REF: &str = WRITE.cluster_ref;
173pub const CLUSTER_FULL_REF: &str = "refs/notes/amont-gate-cluster";
174
175/// Where a gate that COMPLETED without passing is recorded (ADR-0018): a
176/// warn-severity failure, or a gate that could not run. The same note format,
177/// keyed by the tree, holding `gate_identity` tokens. Never `amont-gate`: a
178/// completion is not a pass, and nothing reads this ref to attest or to skip a
179/// gate in an inline push. Only the refusing push (`greengate.pushGates refuse`)
180/// and land's own push read it, so that what a rehearsal or land's pre-stage
181/// already ran is not refused as "not run".
182pub const DONE_REF: &str = WRITE.done_ref;
183pub const DONE_FULL_REF: &str = "refs/notes/amont-gate-done";
184
185/// The reserved first word of a provenance line: where a token came from
186/// (platform, observed imageID, Job UID). Never a token, never a run, and
187/// every reader of tokens drops it.
188pub const PROVENANCE: &str = "provenance";
189pub const INPUTS_FULL_REF: &str = "refs/notes/amont-gate-inputs";
190
191/// The marker's filename inside `$GIT_DIR`.
192const MARKER: &str = crate::names::GATE_MARKER;
193
194/// The switch for push-time stamps — both writing them and honouring them.
195/// On by default: a stamp is amont's own record of a gate it ran on exactly
196/// this content, the same trust the commit-time stamps have always carried.
197const PUSH_STAMPS: &str = "greengate.pushStamps";
198
199/// Does this repository reuse push-time stamps?
200pub fn push_stamps_enabled(settings: &crate::config::Settings) -> bool {
201    crate::config::boolean_or(settings, PUSH_STAMPS, true)
202}
203
204/// The switch for commit-time reuse — a pre-commit gate that already ran
205/// clean against exactly this staged tree is not run again. On by default,
206/// for the same reason `pushStamps` is: the record is amont's own, bound to
207/// the content, and identical content is what a test suite reads.
208const COMMIT_STAMPS: &str = "greengate.commitStamps";
209
210/// Does this repository reuse a gate's verdict across commit attempts of
211/// one tree?
212pub fn commit_stamps_enabled(settings: &crate::config::Settings) -> bool {
213    crate::config::boolean_or(settings, COMMIT_STAMPS, true)
214}
215
216/// The first word of an evidence line. A line that does not start with it is
217/// not one, and is dropped rather than guessed at.
218const RUN: &str = "run";
219
220/// How many runs one note keeps, newest last. A note is read and rewritten on
221/// the push path, so it has to stay small; 64 runs of one tree is already far
222/// more retries than any content sees, and the statistics this feeds are
223/// computed ACROSS notes, not within one.
224const MAX_RUNS: usize = 64;
225
226/// How a single run of one gate ended.
227///
228/// The check vocabulary, kept whole rather than flattened to pass/fail:
229/// `Unavailable` is the outcome the fleet audit of 2026-09-19 kept finding —
230/// a gate that could not run, reported as a warning, counted by nobody — and
231/// collapsing it into "fail" would hide it all over again.
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum RunOutcome {
234    Passed,
235    Failed,
236    Warned,
237    Fixed,
238    Unavailable,
239    Inert,
240    // Tree gates (ADR-0024): why a commit's tree was NOT proven. None is a
241    // verdict about the content; together they are the hit rate's misses.
242    /// No completion marker in the current cache namespace.
243    Cold,
244    /// Another run held the gate's cache lock.
245    Busy,
246    /// The tool the gate would run is not the one CI resolves.
247    Skew,
248    /// The tree was not exactly the commit's (unstaged, untracked, ignored
249    /// outside the allow-list, or an operation in progress).
250    Withheld,
251    /// Still running when the commit was ready, or past its deadline.
252    Cancelled,
253    /// Not started: its last run would not fit in this commit's cover plus
254    /// the slack.
255    Slow,
256    /// Not run: the busy policy deferred it to CI (ADR-0013).
257    Deferred,
258}
259
260impl RunOutcome {
261    pub fn as_str(self) -> &'static str {
262        match self {
263            RunOutcome::Passed => "pass",
264            RunOutcome::Failed => "fail",
265            RunOutcome::Warned => "warn",
266            RunOutcome::Fixed => "fixed",
267            RunOutcome::Unavailable => "unavailable",
268            RunOutcome::Inert => "inert",
269            RunOutcome::Cold => "cold",
270            RunOutcome::Busy => "busy",
271            RunOutcome::Skew => "skew",
272            RunOutcome::Withheld => "withheld",
273            RunOutcome::Cancelled => "cancelled",
274            RunOutcome::Slow => "slow",
275            RunOutcome::Deferred => "deferred",
276        }
277    }
278
279    /// The parse side. `None` for anything unknown — a future amont may write
280    /// an outcome this one has never heard of, and inventing a meaning for it
281    /// would be worse than dropping the line.
282    pub fn parse(s: &str) -> Option<RunOutcome> {
283        Some(match s {
284            "pass" => RunOutcome::Passed,
285            "fail" => RunOutcome::Failed,
286            "warn" => RunOutcome::Warned,
287            "fixed" => RunOutcome::Fixed,
288            "unavailable" => RunOutcome::Unavailable,
289            "inert" => RunOutcome::Inert,
290            "cold" => RunOutcome::Cold,
291            "busy" => RunOutcome::Busy,
292            "skew" => RunOutcome::Skew,
293            "withheld" => RunOutcome::Withheld,
294            "cancelled" => RunOutcome::Cancelled,
295            "slow" => RunOutcome::Slow,
296            "deferred" => RunOutcome::Deferred,
297            _ => return None,
298        })
299    }
300
301    /// Did this run reach a verdict about the content? Only these two are
302    /// evidence about whether a gate works — the rest are a gate declining to
303    /// judge, and counting them as passes is how a no-op looks healthy.
304    pub fn is_verdict(self) -> bool {
305        matches!(self, RunOutcome::Passed | RunOutcome::Failed)
306    }
307}
308
309/// One run of one gate: when, which, how it ended, how long it took.
310///
311/// Wall clock, in milliseconds, measured around the check's own `run` — not
312/// CPU time and not the hook's total, because the number this exists to catch
313/// is "the suite that used to take eleven minutes returned in 0.4 seconds",
314/// and that is a wall-clock claim.
315#[derive(Debug, Clone, PartialEq, Eq)]
316pub struct Run {
317    /// Seconds since the epoch, as the machine that ran it saw them.
318    pub at: u64,
319    pub gate: String,
320    pub outcome: RunOutcome,
321    pub ms: u64,
322}
323
324impl Run {
325    fn render(&self) -> String {
326        format!(
327            "{RUN} {} {} {} {}",
328            self.at,
329            self.gate,
330            self.outcome.as_str(),
331            self.ms
332        )
333    }
334
335    /// `run <epoch> <gate> <outcome> <ms>`, or nothing. Every field must be
336    /// there and parse; a half-understood line is dropped whole.
337    fn parse(line: &str) -> Option<Run> {
338        let mut t = line.split_whitespace();
339        if t.next() != Some(RUN) {
340            return None;
341        }
342        let at = t.next()?.parse().ok()?;
343        let gate = t.next()?.to_string();
344        let outcome = RunOutcome::parse(t.next()?)?;
345        let ms = t.next()?.parse().ok()?;
346        Some(Run {
347            at,
348            gate,
349            outcome,
350            ms,
351        })
352    }
353}
354
355/// A parsed note body: the skip tokens, and the runs recorded against this
356/// key.
357///
358/// THE reader and THE writer of the format, so that the three callers that
359/// rewrite a note cannot each drop a half of it they were not thinking
360/// about. `stamp_push` merging tokens used to render the note from its own
361/// token list alone, which — once runs existed — would have erased every one
362/// of them on the next push.
363#[derive(Debug, Clone, Default, PartialEq, Eq)]
364pub struct Note {
365    pub tokens: Vec<String>,
366    /// Commit-time gates deferred to CI on this content; see the module
367    /// documentation. Never trimmed with the runs.
368    pub deferred: Vec<String>,
369    pub runs: Vec<Run>,
370    /// [`PROVENANCE`] lines, verbatim, kept through every rewrite.
371    pub provenance: Vec<String>,
372}
373
374/// The first word of a deferral line.
375const DEFERRED: &str = "deferred";
376
377impl Note {
378    /// Parse a note body. A first line that is not ours yields an EMPTY note:
379    /// a note somebody else wrote into our ref vouches for nothing, and its
380    /// remaining lines are not evidence either.
381    pub fn parse(body: &str) -> Note {
382        Note::parse_as(body, FORMAT)
383    }
384
385    /// [`Note::parse`] for a note read from a ref of the set whose header is
386    /// `format`: any other first word, the other set's included, is not
387    /// ours there and yields an empty note.
388    fn parse_as(body: &str, format: &str) -> Note {
389        let mut lines = body.lines();
390        let Some(first) = lines.next() else {
391            return Note::default();
392        };
393        let mut tokens = first.split_whitespace();
394        if tokens.next() != Some(format) {
395            return Note::default();
396        }
397        let mut deferred = Vec::new();
398        let mut runs = Vec::new();
399        let mut provenance = Vec::new();
400        for line in lines {
401            if is_provenance(line) {
402                provenance.push(line.trim().to_string());
403                continue;
404            }
405            let mut t = line.split_whitespace();
406            match (t.next(), t.next(), t.next()) {
407                (Some(DEFERRED), Some(gate), None) => {
408                    if !deferred.iter().any(|d| d == gate) {
409                        deferred.push(gate.to_string());
410                    }
411                }
412                _ => runs.extend(Run::parse(line)),
413            }
414        }
415        Note {
416            tokens: tokens.map(str::to_string).collect(),
417            deferred,
418            runs,
419            provenance,
420        }
421    }
422
423    /// The bytes to hand `git notes add -m`. Line one is exactly what it has
424    /// always been, so every reader that stops there sees no change at all.
425    pub fn render(&self) -> String {
426        let mut body = format!("{FORMAT} {}", self.tokens.join(" "));
427        for gate in &self.deferred {
428            body.push('\n');
429            body.push_str(&format!("{DEFERRED} {gate}"));
430        }
431        for run in &self.runs {
432            body.push('\n');
433            body.push_str(&run.render());
434        }
435        for line in &self.provenance {
436            body.push('\n');
437            body.push_str(line);
438        }
439        body
440    }
441
442    fn add_tokens(&mut self, tokens: &[String]) {
443        for t in tokens {
444            if !self.tokens.iter().any(|have| have == t) {
445                self.tokens.push(t.clone());
446            }
447        }
448    }
449
450    /// Append runs, keeping the newest [`MAX_RUNS`].
451    fn add_runs(&mut self, runs: &[Run]) {
452        self.runs.extend(runs.iter().cloned());
453        if self.runs.len() > MAX_RUNS {
454            self.runs.drain(..self.runs.len() - MAX_RUNS);
455        }
456    }
457}
458
459/// Is `line` a [`PROVENANCE`] line? Every token reader asks, so a line that
460/// says where a pass came from can never be read as the pass itself.
461pub fn is_provenance(line: &str) -> bool {
462    line.split_whitespace().next() == Some(PROVENANCE)
463}
464
465/// The note at `key` in the WRITTEN ref, parsed: the base a writer merges
466/// into. Only the written ref, never a note read under another name set, so
467/// a rewrite can never carry the other set's tokens under this header. An
468/// absent note, an absent ref and a git that would not answer are all an
469/// empty note — the same direction everything here fails in.
470fn note_at(key: &str) -> Note {
471    note_in(NOTES_REF, key)
472}
473
474fn note_in(notes_ref: &str, key: &str) -> Note {
475    crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
476        .map(|body| Note::parse(&body))
477        .unwrap_or_default()
478}
479
480/// The stamp at `key` as a READER sees it: the note in `which` ref of the
481/// first set of [`READ`] that holds one, parsed under that set's header. A
482/// green ref's note is the answer even when its header is wrong (it then
483/// vouches for nothing): the legacy ref is read only for a key the green
484/// ref has no note for.
485fn stamp_in(which: fn(&GateNames) -> &'static str, key: &str) -> Note {
486    READ.iter()
487        .find_map(|set| read_in(set, which(set), key))
488        .unwrap_or_default()
489}
490
491/// The note at `key` in `notes_ref`, one of `set`'s refs, parsed under
492/// `set`'s header; `None` when the ref holds no note there (or git would not
493/// answer, which reads the same: no stamp).
494///
495/// A git failure on the green ref returns `None`, so a legacy note may answer
496/// in its place. That is the safe direction: the gate then re-runs, or reads
497/// the older stamp.
498fn read_in(set: &GateNames, notes_ref: &str, key: &str) -> Option<Note> {
499    crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
500        .map(|body| Note::parse_as(&body, set.format))
501}
502
503/// [`stamp_in`] on the tree- and commit-keyed ref.
504fn stamp_at(key: &str) -> Note {
505    stamp_in(|s| s.notes_ref, key)
506}
507
508/// The tokens of the gates `tree`'s declared inputs vouch for: for each gate
509/// the spec at `tree` declares, the note filed under `K(gate, fingerprint)`.
510///
511/// Only a token written under that gate's own name is honoured from the note
512/// at its key: a note somebody else wrote into the ref cannot vouch for a
513/// gate it was not filed under. No spec, an invalid or ambiguous one, a gate
514/// with no fingerprint on `tree` (a required path missing), a git that would
515/// not answer: all contribute nothing, and nothing means the gate runs.
516fn input_tokens(tree: &str) -> Vec<String> {
517    let Some(spec) = crate::attest_inputs::spec_at(tree) else {
518        return canon_tokens(tree);
519    };
520    let mut out: Vec<String> = Vec::new();
521    for (gate, _) in &spec.gates {
522        if !manifest_is_an_input(tree, &spec, gate) {
523            continue;
524        }
525        let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
526            continue;
527        };
528        // Each set computes its own key and reads its own ref; the legacy
529        // one only when the green ref has no note at the green key.
530        let note = READ.iter().find_map(|set| {
531            let key = crate::attest_inputs::input_key(&set.attest, gate, &fp)?;
532            read_in(set, set.inputs_ref, &key)
533        });
534        for t in note.unwrap_or_default().tokens {
535            if crate::gate_identity::base(&t) == gate.as_str() && !out.contains(&t) {
536                out.push(t);
537            }
538        }
539    }
540    out
541}
542
543/// The tokens `tree`'s canonical fingerprint vouches for: a repository that
544/// declares nothing is reused on any tree that differs only in the CONTENT of
545/// its plans (attest SPEC, "Canonical tree"). One note per fingerprint holds
546/// the tokens of every gate that passed on it, as the tree note does for a
547/// tree. A declared (even invalid) spec, an opt-out, or a git that would not
548/// answer: no canonical route, nothing contributed, the gate runs.
549fn canon_tokens(tree: &str) -> Vec<String> {
550    let Some(canon) = crate::attest_inputs::canonical_route(tree) else {
551        return Vec::new();
552    };
553    READ.iter()
554        .find_map(|set| {
555            let key = crate::attest_inputs::canon_gate_key(set.canon_domain, &canon)?;
556            read_in(set, set.inputs_ref, &key)
557        })
558        .map(|note| note.tokens)
559        .unwrap_or_default()
560}
561
562/// The key of the canonical note of `tree` in the WRITTEN set, if the
563/// canonical route is open.
564fn canon_key_of(tree: &str) -> Option<String> {
565    let canon = crate::attest_inputs::canonical_route(tree)?;
566    crate::attest_inputs::canon_gate_key(WRITE.canon_domain, &canon)
567}
568
569/// File `tokens` under the canonical key of `tree`. Best-effort and merged,
570/// like [`file_inputs`]. The manifest needs no rule here: `amont.conf` is part
571/// of the canonical tree, so a changed declaration is a changed fingerprint.
572fn file_canon(tree: &str, tokens: &[String]) {
573    let Some(key) = canon_key_of(tree) else {
574        return;
575    };
576    let mut note = note_in(INPUTS_REF, &key);
577    note.add_tokens(tokens);
578    let _ = write_note_in(INPUTS_REF, &key, &note);
579}
580
581/// File `tokens` under the fingerprint keys of the gates `tree` declares, in
582/// addition to wherever the caller put them by tree; with no spec at all, under
583/// the canonical key. Best-effort, silent, and merged: a miss here is one
584/// redundant gate run, which is the safe direction.
585fn file_inputs(tree: &str, tokens: &[String]) {
586    if tokens.is_empty() {
587        return;
588    }
589    let Some(spec) = crate::attest_inputs::spec_at(tree) else {
590        file_canon(tree, tokens);
591        return;
592    };
593    for (gate, _) in &spec.gates {
594        let mine: Vec<String> = tokens
595            .iter()
596            .filter(|t| crate::gate_identity::base(t) == gate.as_str())
597            .cloned()
598            .collect();
599        if mine.is_empty() || !manifest_is_an_input(tree, &spec, gate) {
600            continue;
601        }
602        let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
603            continue;
604        };
605        let Some(key) = crate::attest_inputs::input_key(&WRITE.attest, gate, &fp) else {
606            continue;
607        };
608        let mut note = note_in(INPUTS_REF, &key);
609        note.add_tokens(&mine);
610        let _ = write_note_in(INPUTS_REF, &key, &note);
611    }
612}
613
614/// May a gate's stamp travel by fingerprint on `tree`? A gate's scope and its
615/// opt-ins live in the manifest, and under a whole-tree key a manifest change
616/// was a tree change; under a fingerprint it is one only if the gate declares
617/// the manifest. So a tree that tracks its manifest offers the route only to a
618/// gate whose declared inputs cover it, and a scope-only edit then misses.
619fn manifest_is_an_input(tree: &str, spec: &crate::attest_inputs::Spec, gate: &str) -> bool {
620    // The name the tree tracks: an unswept tree still has the 3.x one.
621    let tracked = [crate::manifest::MANIFEST, crate::names::old::MANIFEST]
622        .into_iter()
623        .find(|name| crate::git::succeeds(&["cat-file", "-e", &format!("{tree}:{name}")]));
624    tracked.map_or(true, |name| {
625        crate::attest_inputs::declares(spec, gate, name)
626    })
627}
628
629/// Does either set's inputs ref exist here? One spawn per set that lets a
630/// repository nothing was ever filed for (an opted-out one, or one whose
631/// stamps never passed) skip the fingerprint and canonical routes entirely on
632/// the push path.
633fn inputs_ref_exists() -> bool {
634    READ.iter().any(|set| {
635        crate::git::succeeds(&[
636            "rev-parse",
637            "-q",
638            "--verify",
639            &format!("refs/notes/{}", set.inputs_ref),
640        ])
641    })
642}
643
644/// The stamp tokens on `tree` (a tree object id). Tree gates are read here
645/// and only here (ADR-0024): `tree:<name>` on the pushed tree proves the gate
646/// on exactly that content, whichever commit carried it.
647pub fn tree_tokens(tree: &str) -> Vec<String> {
648    let mut tokens = stamp_at(tree).tokens;
649    if inputs_ref_exists() {
650        for t in input_tokens(tree) {
651            if !tokens.contains(&t) {
652                tokens.push(t);
653            }
654        }
655    }
656    tokens
657}
658
659/// Add `tokens` to the gate note on `tree` — how a rehearsal records tree
660/// gates it proved in its snapshot of exactly that tree. Merged, never
661/// rendered from the tokens alone, so evidence already on the note survives.
662pub fn stamp_tree(tree: &str, tokens: &[String]) -> bool {
663    let mut note = note_at(tree);
664    note.add_tokens(tokens);
665    let ok = write_note(tree, &note);
666    file_inputs(tree, tokens);
667    ok
668}
669
670/// Write `note` at `key`. Best-effort, like every writer here.
671fn write_note(key: &str, note: &Note) -> bool {
672    write_note_in(NOTES_REF, key, note)
673}
674
675fn write_note_in(notes_ref: &str, key: &str, note: &Note) -> bool {
676    let body = note.render();
677    crate::git::succeeds(&["notes", "--ref", notes_ref, "add", "-f", "-m", &body, key])
678}
679
680/// Record what a gate run COST and how it ENDED, against the content it ran
681/// on.
682///
683/// Evidence only: nothing in this module reads these back to decide whether a
684/// check may be skipped, which is why recording a FAILED run — the case the
685/// stamp path deliberately has no opinion about — is safe here.
686///
687/// Best-effort and silent. A note git refused costs a row in a report nobody
688/// is blocked on; warning about it on every push would train people to ignore
689/// the warnings that do gate something.
690pub fn record_runs(key: &str, runs: &[Run]) {
691    // A gate name with whitespace in it would forge a second field on read.
692    // Refused rather than escaped: every id this repository can produce is
693    // already free of it, so the escaping would be a code path no real input
694    // ever reaches — untested by construction.
695    let runs: Vec<Run> = runs
696        .iter()
697        .filter(|r| !r.gate.is_empty() && !r.gate.contains(char::is_whitespace))
698        .cloned()
699        .collect();
700    if runs.is_empty() {
701        return;
702    }
703    let mut note = note_at(key);
704    note.add_runs(&runs);
705    let _ = write_note(key, &note);
706}
707
708/// pre-commit: record on `tree` (the staged tree, which is the commit's)
709/// that the busy policy deferred `gates`, by their commit-time script names.
710/// Best-effort and silent: a lost line runs the push twin, the safe way.
711pub fn record_deferred(tree: &str, gates: &[String]) {
712    let gates: Vec<&String> = gates
713        .iter()
714        .filter(|g| !g.is_empty() && !g.contains(char::is_whitespace))
715        .collect();
716    if gates.is_empty() {
717        return;
718    }
719    let mut note = note_at(tree);
720    for g in gates {
721        if !note.deferred.contains(g) {
722            note.deferred.push(g.clone());
723        }
724    }
725    let _ = write_note(tree, &note); // best-effort: a lost line runs the push twin, the safe way
726}
727
728/// The commit-time gates the busy policy deferred on `tree`, by script name.
729/// What `amont stamps` reports as `deferred`; never a token.
730pub fn deferred_on(tree: &str) -> Vec<String> {
731    stamp_at(tree).deferred
732}
733
734/// Which of `commits` carry a deferral of `gate` on their tree's note (or
735/// their own). Read only to defer a push twin, never to skip one: a commit
736/// in this set still has no stamp.
737pub fn deferred_for(commits: &[String], gate: &str) -> HashSet<String> {
738    let mut out = HashSet::new();
739    if commits.is_empty() {
740        return out;
741    }
742    let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
743    args.extend(commits.iter().map(String::as_str));
744    let Some(list) = crate::git::stdout(&args) else {
745        return out;
746    };
747    for line in list.lines() {
748        let mut it = line.split_whitespace();
749        let (Some(commit), Some(tree)) = (it.next(), it.next()) else {
750            continue;
751        };
752        if [commit, tree]
753            .iter()
754            .any(|key| stamp_at(key).deferred.iter().any(|d| d == gate))
755        {
756            out.insert(commit.to_string());
757        }
758    }
759    out
760}
761
762/// `$GIT_DIR/amont-gate` — the worktree-PRIVATE gitdir, deliberately: the
763/// commit this marker waits for happens in this worktree. The stamps the
764/// marker becomes live in the common dir (a notes ref) and are shared.
765fn marker_path() -> Option<PathBuf> {
766    let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
767    Some(std::path::Path::new(&dir).join(MARKER))
768}
769
770/// pre-commit: record that `scripts` ran clean against the tree the commit
771/// will carry.
772///
773/// Called on EVERY pre-commit verdict, with an empty list when nothing
774/// qualifying ran (or the commit is about to be blocked) — an aborted or
775/// unchecked attempt must not inherit a previous attempt's marker.
776///
777/// Best-effort throughout: a failure to record costs one redundant gate run
778/// at push time, which is the safe direction, and a pre-commit that failed a
779/// COMMIT over bookkeeping would be the tail wagging the dog.
780pub fn record(scripts: &[&str]) {
781    let Some(path) = marker_path() else { return };
782    if scripts.is_empty() {
783        let _ = std::fs::remove_file(&path);
784        return;
785    }
786    // The index, as the object id `git commit` is about to seal. Inherits
787    // `GIT_INDEX_FILE`, so `git commit -a`'s temporary index answers here
788    // too. Pure read of the index: writes objects, touches no ref.
789    let Some(tree) = crate::git::stdout(&["write-tree"]) else {
790        // Not "nothing ran": git could not name the tree, so nothing may be
791        // vouched for. Dropping the marker is the fail-safe half (the gate
792        // re-runs at push); saying so is the half that was missing.
793        crate::hooks::common::warn(
794            "git would not name the staged tree — this commit records no gate stamp",
795        );
796        let _ = std::fs::remove_file(&path);
797        return;
798    };
799    let mut body = format!("{FORMAT}\n{tree}\n");
800    for s in scripts {
801        body.push_str(s);
802        body.push('\n');
803    }
804    let _ = std::fs::write(&path, body);
805}
806
807/// pre-commit, before a gate runs: the scripts a previous run already
808/// vouched for against the tree this commit is about to seal.
809///
810/// Two records answer, both bound to the TREE (`git write-tree` of the index
811/// under the staged-only hold — the commit's content, not the working
812/// tree):
813///
814/// 1. the one-shot marker [`record`] left behind. post-commit consumes it,
815///    so a marker that is still there belongs to an attempt that never
816///    reached post-commit — a `commit-msg` refusal, an editor closed on an
817///    empty message, a Ctrl-C at the prompt. The gates ran, the tree is the
818///    same, the verdict stands: measured on this machine, a subject three
819///    characters too long replayed a ten-minute suite for nothing.
820/// 2. the tree note [`bind_to_head`] writes — a reword, a `reset --soft` and
821///    re-commit, or a rebase that kept the tree.
822///
823/// Every failure mode reads as "nothing is vouched for", which runs the
824/// gate: no `write-tree`, a marker for another tree, a wrong format, a git
825/// that would not answer. Reuse can only ever skip a run the record proves
826/// happened on this exact content; it can never let unjudged content
827/// through — the direction every function in this module fails in.
828///
829/// Repo-controlled inputs to the gate (its command line, its scope) live in
830/// the manifest, which is part of the tree: a changed declaration is a
831/// changed tree, and nothing is reused by tree. A gate reused by fingerprint
832/// gets the same guarantee only if it declares the manifest as an input
833/// ([`manifest_is_an_input`]); otherwise it is not offered the route at all.
834pub fn vouched_for_staged_tree() -> HashSet<String> {
835    let mut out = HashSet::new();
836    let Some(tree) = crate::git::stdout(&["write-tree"]) else {
837        return out;
838    };
839    if let Some(path) = marker_path() {
840        if let Ok(body) = std::fs::read_to_string(&path) {
841            let mut lines = body.lines();
842            if lines.next() == Some(FORMAT) && lines.next() == Some(tree.as_str()) {
843                out.extend(
844                    lines
845                        .filter(|l| !l.trim().is_empty() && !is_provenance(l))
846                        .map(str::to_string),
847                );
848            }
849        }
850    }
851    // The tree note: `notes show` fails loudly on an absent note, and a
852    // failure here is simply "no note" — the marker's answer stands alone.
853    // Tokens are `<name>@<identity>` (`gate_identity`): commit-time ones are
854    // named by script, push-time ones by full id (`pre-push-…`), which no
855    // pre-commit declaration is named after — harmless in the set, and a
856    // reader skips only on the complete token. The note's `run` lines are evidence and are not
857    // tokens: `Note` keeps the two apart so nothing here can be skipped by a
858    // line that only records how long something took.
859    out.extend(stamp_at(&tree).tokens);
860    // A gate the repository declares inputs for is also vouched for by any
861    // earlier tree whose declared inputs are byte-identical to this staged
862    // tree's: a plan-only commit changes the tree and none of them. The tree
863    // here is the INDEX's (`write-tree`), so partial staging is judged on what
864    // is about to be committed, not on the working copy.
865    if inputs_ref_exists() {
866        out.extend(input_tokens(&tree));
867    }
868    out
869}
870
871/// post-commit: consume the marker; stamp HEAD when the tree still matches.
872///
873/// One-shot by construction — the marker is deleted before anything is
874/// judged, so no path through here can leave it to vouch for a later commit.
875///
876/// Returns the scripts it actually stamped (empty on every no-stamp path,
877/// including a note git refused). The caller subtracts this from what the
878/// manifest declares to learn what the commit dodged — [`crate::bypass`]
879/// keeps that count. Two records, two questions: the stamp gates a check,
880/// the ledger only counts.
881pub fn bind_to_head() -> Vec<String> {
882    let Some(path) = marker_path() else {
883        return Vec::new();
884    };
885    let Ok(body) = std::fs::read_to_string(&path) else {
886        return Vec::new(); // no marker: nothing ran at pre-commit, nothing to stamp
887    };
888    let _ = std::fs::remove_file(&path);
889    let mut lines = body.lines();
890    if lines.next() != Some(FORMAT) {
891        return Vec::new();
892    }
893    let Some(tree) = lines.next() else {
894        return Vec::new();
895    };
896    let scripts: Vec<&str> = lines
897        .filter(|l| !l.trim().is_empty() && !is_provenance(l))
898        .collect();
899    if scripts.is_empty() {
900        return Vec::new();
901    }
902    let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
903        crate::hooks::common::warn(
904            "git would not name this commit's tree — no gate stamp was written",
905        );
906        return Vec::new();
907    };
908    // A different tree means this commit is not the one pre-commit judged —
909    // the marker is a dead letter from an aborted attempt.
910    if head_tree != tree {
911        return Vec::new();
912    }
913    let scripts: Vec<String> = scripts.iter().map(|s| s.to_string()).collect();
914    // The stamp goes on the TREE as well as the commit, and the tree is the
915    // one that survives the way work actually reaches `main`.
916    //
917    // A squash-merge is performed by the forge: it produces a commit nobody
918    // here ever saw, carrying no note, so a later `git push` of a tag on
919    // that commit re-ran every gate the branch had already proved. Measured
920    // on this repository: a branch push took 13 seconds and the tag push
921    // that followed took the full suite and died on a reset connection.
922    //
923    // The tree is identical across that merge whenever the base has not
924    // moved — five of five merges in one afternoon here — and identical
925    // trees are identical CONTENT, which is the only thing a test suite
926    // reads. That is the same argument `attest` makes for signing the tree
927    // rather than the commit, and this module's marker has been tree-bound
928    // since it was written; this only carries the binding through to the
929    // note.
930    //
931    // Both, not either: the commit note is what a `git log --notes` reader
932    // sees, and dropping it would make the stamps invisible in the place
933    // people look for them.
934    // MERGED into whatever is there, never rendered from the scripts alone:
935    // a pre-push run against this same tree may already have recorded
936    // evidence lines on it, and an `add -f` built from this list would erase
937    // them.
938    let mut tree_note = note_at(&head_tree);
939    tree_note.add_tokens(&scripts);
940    let _ = write_note(&head_tree, &tree_note);
941    file_inputs(&head_tree, &scripts);
942    let mut head_note = note_at("HEAD");
943    head_note.add_tokens(&scripts);
944    if !write_note("HEAD", &head_note) {
945        // A note git refused is not a stamp — and the push will re-run these
946        // checks, which is right but looks arbitrary unless it is said.
947        crate::hooks::common::warn(
948            "git refused to write the gate stamp — these checks will run again at push",
949        );
950        return Vec::new();
951    }
952    // The ledger counts NAMES: what the commit dodged is judged against what
953    // the manifest declares, and the identity is the stamp's business alone.
954    scripts
955        .iter()
956        .map(|s| crate::gate_identity::base(s).to_string())
957        .collect()
958}
959
960/// pre-push, after every block gate passed: record that `gates` passed
961/// against `tree`, the content of `commit` — MERGING with whatever the note
962/// already says, because a commit-time stamp (`test`) may already sit there
963/// and `notes add -f` would otherwise erase it.
964///
965/// Best-effort, like every writer here: a stamp that could not be written
966/// costs one redundant gate run on the next push, which is the safe
967/// direction. Returns whether the commit's note was written.
968pub fn stamp_push(commit: &str, tree: &str, gates: &[String]) -> bool {
969    if gates.is_empty() {
970        return false;
971    }
972    let mut written = false;
973    for key in [tree, commit] {
974        let mut note = note_at(key);
975        note.add_tokens(gates);
976        let ok = write_note(key, &note);
977        if key == commit {
978            written = ok;
979        }
980    }
981    file_inputs(tree, gates);
982    if !written {
983        crate::hooks::common::warn(
984            "git refused to write the push stamp — these gates will run again on the next push",
985        );
986    }
987    written
988}
989
990/// How a gate completed without passing (ADR-0018). The kind is part of the
991/// record, so each answers only for as long as it should.
992#[derive(Debug, Clone, Copy, PartialEq, Eq)]
993pub enum Completion {
994    /// The gate reported a warning itself.
995    Warned,
996    /// The gate failed while its severity was `warn`: answers only while it
997    /// still is, since a gate set back to `block` must run again.
998    FailedUnderWarn,
999    /// The gate could not run (a tool missing): answers for an hour, then
1000    /// the gate is tried again.
1001    Unavailable,
1002}
1003
1004/// How long an `Unavailable` completion answers for.
1005const UNAVAILABLE_FOR_SECS: u64 = 60 * 60;
1006
1007/// The record word for `token` completed as `how`, at `now`.
1008fn completion_word(how: Completion, token: &str, now: u64) -> String {
1009    match how {
1010        Completion::Warned => format!("warned:{token}"),
1011        Completion::FailedUnderWarn => format!("failed-under-warn:{token}"),
1012        Completion::Unavailable => format!("unavailable:{now}:{token}"),
1013    }
1014}
1015
1016/// Does record word `word` answer for `token` now, under `severity`?
1017fn completion_answers(word: &str, token: &str, severity: crate::check::Severity, now: u64) -> bool {
1018    if word.strip_prefix("warned:") == Some(token) {
1019        return true;
1020    }
1021    if word.strip_prefix("failed-under-warn:") == Some(token) {
1022        return severity == crate::check::Severity::Warn;
1023    }
1024    word.strip_prefix("unavailable:")
1025        .and_then(|rest| rest.split_once(':'))
1026        .is_some_and(|(at, tok)| {
1027            tok == token
1028                && at
1029                    .parse::<u64>()
1030                    .is_ok_and(|at| now.saturating_sub(at) <= UNAVAILABLE_FOR_SECS)
1031        })
1032}
1033
1034fn now_secs() -> u64 {
1035    std::time::SystemTime::now()
1036        .duration_since(std::time::UNIX_EPOCH)
1037        .map(|d| d.as_secs())
1038        .unwrap_or(0)
1039}
1040
1041/// Record on `tree` that the gates behind `tokens` completed there without
1042/// passing, as `how` (ADR-0018). Merged into the note; an `Unavailable`
1043/// record replaces the one before it for the same gate, so a tree's note does
1044/// not grow by a word per run. The error names the tree, for the caller to
1045/// say: a record that was not written costs a refused push.
1046pub fn record_done(tree: &str, tokens: &[String], how: Completion) -> Result<(), String> {
1047    if tokens.is_empty() {
1048        return Ok(());
1049    }
1050    let now = now_secs();
1051    let mut note = note_in(DONE_REF, tree);
1052    if how == Completion::Unavailable {
1053        note.tokens.retain(|word| {
1054            !word
1055                .strip_prefix("unavailable:")
1056                .and_then(|rest| rest.split_once(':'))
1057                .is_some_and(|(_, token)| tokens.iter().any(|t| t == token))
1058        });
1059    }
1060    let words: Vec<String> = tokens
1061        .iter()
1062        .map(|t| completion_word(how, t, now))
1063        .collect();
1064    note.add_tokens(&words);
1065    if write_note_in(DONE_REF, tree, &note) {
1066        Ok(())
1067    } else {
1068        Err(format!(
1069            "git refused to record the completed gates on {tree}"
1070        ))
1071    }
1072}
1073
1074/// Did the gate behind `token` complete without passing on the tree of every
1075/// one of `commits`, by a record that still answers under `severity`? An
1076/// unreadable tree or note is "no", the direction that refuses rather than
1077/// skips.
1078pub fn done_on_every(commits: &[String], token: &str, severity: crate::check::Severity) -> bool {
1079    let now = now_secs();
1080    !commits.is_empty()
1081        && commits.iter().all(|c| {
1082            crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]).is_some_and(|tree| {
1083                stamp_in(|s| s.done_ref, &tree)
1084                    .tokens
1085                    .iter()
1086                    .any(|word| completion_answers(word, token, severity, now))
1087            })
1088        })
1089}
1090
1091/// pre-push: which of `commits` carry a stamp, and for which scripts.
1092///
1093/// One `notes list` narrows the reads to commits that have a note at all;
1094/// absent ref, unparseable note, wrong format version — all read as "no
1095/// stamp", which re-runs the gate.
1096pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
1097    let mut out = HashMap::new();
1098    if commits.is_empty() {
1099        return out;
1100    }
1101    // Both sets' lists, unioned: a commit noted only under the green ref is
1102    // a stamped commit too ([`stamp_at`] then picks which note answers).
1103    let lists: Option<Vec<String>> = READ
1104        .iter()
1105        .map(|set| crate::git::stdout(&["notes", "--ref", set.notes_ref, "list"]))
1106        .collect();
1107    let Some(lists) = lists else {
1108        // NOT the absent-ref case, whatever an older comment here claimed:
1109        // `notes list` exits 0 with empty output when the ref does not exist,
1110        // so that arrives as `Some("")` and falls through as "nothing is
1111        // stamped" — correctly. Reaching HERE means git could not answer at
1112        // all. Same verdict (the gates re-run: never skip work on a question
1113        // we could not ask), different sentence, because a transient git
1114        // failure that reads as "nothing is stamped" is indistinguishable
1115        // from the real thing — which is exactly how one flaky spawn cost a
1116        // day of not-diagnosing.
1117        crate::hooks::common::warn(
1118            "git would not list the gate stamps — every gated check will run again",
1119        );
1120        return out;
1121    };
1122    let noted: HashSet<&str> = lists
1123        .iter()
1124        .flat_map(|list| list.lines())
1125        .filter_map(|l| l.split_whitespace().nth(1))
1126        .collect();
1127    // Commit -> tree, in ONE spawn rather than one per commit: this is the
1128    // push path, and a `rev-parse` each would be a process per pushed
1129    // commit to answer a question `git log` answers in a batch.
1130    let mut trees: HashMap<String, String> = HashMap::new();
1131    {
1132        let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
1133        args.extend(commits.iter().map(String::as_str));
1134        if let Some(out) = crate::git::stdout(&args) {
1135            for line in out.lines() {
1136                let mut it = line.split_whitespace();
1137                if let (Some(c), Some(t)) = (it.next(), it.next()) {
1138                    trees.insert(c.to_string(), t.to_string());
1139                }
1140            }
1141        }
1142        // No mapping is not an error: every commit simply falls back to the
1143        // commit-keyed lookup below, which is what happened before trees
1144        // were stamped at all.
1145    }
1146
1147    // Declared-input stamps are keyed by fingerprint, not by tree, so a commit
1148    // whose tree carries no note can still be vouched for. Asked only when the
1149    // ref exists: a repository nothing was filed for pays one spawn. Once
1150    // stamps are filed (declared or canonical), each pushed commit pays the
1151    // few git spawns of its route.
1152    let by_inputs = inputs_ref_exists();
1153
1154    for commit in commits {
1155        // The commit's own note AND its TREE's, merged. Both are written only
1156        // for that tree (`bind_to_head` checks `HEAD^{tree}`, `stamp_push` is
1157        // handed the commit's own tree), so every token on either vouches for
1158        // exactly this content.
1159        //
1160        // Not "the commit's note, else the tree's". A squash-merge produces a
1161        // commit this machine never saw — no note — while the content, and
1162        // therefore the tree, is the one the gates ran on, and falling through
1163        // to the tree is what lets a tag push on a merged commit skip work the
1164        // branch already proved. But the same preference hid the tree's push
1165        // tokens behind a commit note after an AMEND that kept the tree:
1166        // post-commit wrote a commit note holding only the commit-time
1167        // scripts, `stamps_for` then stopped there, and the push gate ran
1168        // again for content it had already judged.
1169        //
1170        // The direction of failure is unchanged: no note on either, an
1171        // unparseable one, or a git that would not answer all mean "no
1172        // stamp", and no stamp runs the gate.
1173        let mut tokens: Vec<String> = Vec::new();
1174        let mut keys: Vec<&str> = Vec::new();
1175        if noted.contains(commit.as_str()) {
1176            keys.push(commit);
1177        }
1178        if let Some(tree) = trees.get(commit).filter(|t| noted.contains(t.as_str())) {
1179            keys.push(tree);
1180        }
1181        for key in keys {
1182            for t in stamp_at(key).tokens {
1183                if !tokens.contains(&t) {
1184                    tokens.push(t);
1185                }
1186            }
1187        }
1188        if by_inputs {
1189            if let Some(tree) = trees.get(commit) {
1190                for t in input_tokens(tree) {
1191                    if !tokens.contains(&t) {
1192                        tokens.push(t);
1193                    }
1194                }
1195            }
1196        }
1197        if tokens.is_empty() {
1198            continue;
1199        }
1200        out.insert(commit.clone(), tokens);
1201    }
1202    out
1203}
1204
1205/// uninstall: forget everything this module ever wrote here.
1206///
1207/// The stamps are OUR bookkeeping — unlike `hook.skip` and `greengate.severity`,
1208/// which are the user's statements and are never touched.
1209pub fn forget() -> bool {
1210    let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
1211    // Every ref of every name set: a green note is ours too.
1212    let mut deleted = false;
1213    for set in READ {
1214        for r in full_refs(&set) {
1215            deleted |= crate::git::succeeds(&["update-ref", "-d", &r]);
1216        }
1217    }
1218    marker || deleted
1219}
1220
1221/// The four fully qualified refs of one name set.
1222fn full_refs(set: &GateNames) -> [String; 4] {
1223    [set.notes_ref, set.inputs_ref, set.cluster_ref, set.done_ref]
1224        .map(|short| format!("refs/notes/{short}"))
1225}
1226
1227/// The cluster tokens on `tree` (ADR-0016). Read only for a trusted
1228/// `platform=any` gate, so a repository with none never pays the spawn.
1229pub(crate) fn cluster_tokens(tree: &str) -> Vec<String> {
1230    stamp_in(|s| s.cluster_ref, tree).tokens
1231}
1232
1233/// Record a cluster pass: `token` on the note at `tree`, with its provenance
1234/// line. Merged, like every writer here; best-effort.
1235pub(crate) fn stamp_cluster(tree: &str, token: &str, provenance: &str) -> bool {
1236    let mut note = note_in(CLUSTER_REF, tree);
1237    note.add_tokens(&[token.to_string()]);
1238    let line = format!("{PROVENANCE} {token} {provenance}");
1239    note.provenance
1240        .retain(|l| l.split_whitespace().nth(1) != Some(token));
1241    note.provenance.push(line);
1242    write_note_in(CLUSTER_REF, tree, &note)
1243}
1244
1245/// pre-push: the tree and the cluster tokens of each of `commits`. Asked only
1246/// when a trusted `platform=any` gate is in play; a commit whose tree carries
1247/// no cluster note is absent from the map.
1248pub(crate) fn cluster_stamps_for(commits: &[String]) -> HashMap<String, (String, Vec<String>)> {
1249    let mut out = HashMap::new();
1250    for commit in commits {
1251        let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")]) else {
1252            continue;
1253        };
1254        let tokens = cluster_tokens(&tree);
1255        if !tokens.is_empty() {
1256            out.insert(commit.clone(), (tree, tokens));
1257        }
1258    }
1259    out
1260}
1261
1262/// The same, for a repository this process is not standing in.
1263pub fn forget_in(repo: &std::path::Path) -> bool {
1264    let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
1265        .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
1266    let mut deleted = false;
1267    for set in READ {
1268        for r in full_refs(&set) {
1269            deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &r]);
1270        }
1271    }
1272    marker || deleted
1273}
1274
1275#[cfg(test)]
1276mod tests {
1277    use super::*;
1278    use std::path::Path;
1279
1280    /// A completion answers only as long as it should (ADR-0018): a failure
1281    /// under `warn` stops answering once the gate blocks again, and a gate
1282    /// that could not run is tried again after an hour.
1283    #[test]
1284    fn a_completion_answers_only_while_it_should() {
1285        use crate::check::Severity::{Block, Warn};
1286        let now = 1_700_000_000;
1287        let word = |how| completion_word(how, "gate-tok", now);
1288        assert!(completion_answers(
1289            &word(Completion::Warned),
1290            "gate-tok",
1291            Block,
1292            now
1293        ));
1294        assert!(completion_answers(
1295            &word(Completion::FailedUnderWarn),
1296            "gate-tok",
1297            Warn,
1298            now
1299        ));
1300        assert!(!completion_answers(
1301            &word(Completion::FailedUnderWarn),
1302            "gate-tok",
1303            Block,
1304            now
1305        ));
1306        let unavailable = word(Completion::Unavailable);
1307        assert!(completion_answers(
1308            &unavailable,
1309            "gate-tok",
1310            Block,
1311            now + 3600
1312        ));
1313        assert!(!completion_answers(
1314            &unavailable,
1315            "gate-tok",
1316            Block,
1317            now + 3601
1318        ));
1319        assert!(!completion_answers(
1320            &word(Completion::Warned),
1321            "other-tok",
1322            Warn,
1323            now
1324        ));
1325    }
1326
1327    /// A real repository, because every function here is a conversation with
1328    /// git — hand-rolled fixtures would test the conversation we imagined.
1329    fn repo(name: &str) -> PathBuf {
1330        let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
1331        let _ = std::fs::remove_dir_all(&dir);
1332        std::fs::create_dir_all(&dir).unwrap();
1333        git(&dir, &["init", "-q", "--template=", "."]);
1334        git(&dir, &["config", "user.email", "t@t.test"]);
1335        git(&dir, &["config", "user.name", "t"]);
1336        dir
1337    }
1338
1339    /// A fixture git call that FAILS where it fails.
1340    ///
1341    /// This used to discard the exit status, and that is how a rare flake
1342    /// stayed unreadable for a day: if the setup `git commit` did not
1343    /// happen, the test carried on to an unborn HEAD, and the panic landed
1344    /// three lines later on a missing gate stamp — a product-shaped
1345    /// failure for a fixture-shaped cause. Same rule the checks obey:
1346    /// git failing is not git answering.
1347    fn git(dir: &Path, args: &[&str]) -> String {
1348        let out = std::process::Command::new("git")
1349            .arg("-C")
1350            .arg(dir)
1351            .args(args)
1352            .output()
1353            .expect("git");
1354        assert!(
1355            out.status.success(),
1356            "fixture: git {args:?} in {} exited {:?}: {}",
1357            dir.display(),
1358            out.status.code(),
1359            String::from_utf8_lossy(&out.stderr).trim()
1360        );
1361        String::from_utf8_lossy(&out.stdout).trim().to_string()
1362    }
1363
1364    /// The module talks to the repo at the process cwd; these tests each set
1365    /// it. Serialised via the crate-wide lock, because cwd is process-global
1366    /// and `attest`'s tests move it too.
1367    fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1368        let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1369        let prev = std::env::current_dir().unwrap();
1370        std::env::set_current_dir(dir).unwrap();
1371        let r = f();
1372        std::env::set_current_dir(prev).unwrap();
1373        r
1374    }
1375
1376    #[test]
1377    fn the_commit_note_does_not_hide_the_tree_notes_push_tokens() {
1378        let dir = repo("union");
1379        std::fs::write(dir.join("a.ts"), "x").unwrap();
1380        git(&dir, &["add", "a.ts"]);
1381        in_repo(&dir, || {
1382            record(&["test"]);
1383            git(&dir, &["commit", "-qm", "chore: a"]);
1384            bind_to_head();
1385            let head = git(&dir, &["rev-parse", "HEAD"]);
1386            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1387            // A push-time stamp lands on the TREE only (the shape a rehearsal
1388            // leaves), while the commit note keeps just the commit-time script.
1389            assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1390            assert_eq!(note_at(&head).tokens, vec!["test".to_string()]);
1391            let stamps = stamps_for(std::slice::from_ref(&head));
1392            assert_eq!(
1393                stamps.get(&head).map(Vec::as_slice),
1394                Some(&["test".to_string(), "pre-push-cargo-test".to_string()][..]),
1395                "both notes speak for the same tree"
1396            );
1397        });
1398        let _ = std::fs::remove_dir_all(&dir);
1399    }
1400
1401    /// An `unavailable` record replaces the one before it for the same gate,
1402    /// and leaves every other gate's record alone: a tree's note does not grow
1403    /// by a word per run (ADR-0018).
1404    #[test]
1405    fn an_unavailable_record_replaces_its_predecessor_only() {
1406        let dir = repo("done-unavailable");
1407        std::fs::write(dir.join("a.ts"), "x").unwrap();
1408        git(&dir, &["add", "a.ts"]);
1409        git(&dir, &["commit", "-qm", "chore: a"]);
1410        in_repo(&dir, || {
1411            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1412            let one = |t: &str| vec![t.to_string()];
1413            record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("first");
1414            record_done(&tree, &one("lint@b"), Completion::Unavailable).expect("other gate");
1415            record_done(&tree, &one("lint@b"), Completion::Warned).expect("a warning");
1416            record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("again");
1417            let words = note_in(DONE_REF, &tree).tokens;
1418            let unavailable_for = |token: &str| {
1419                words
1420                    .iter()
1421                    .filter(|w| w.starts_with("unavailable:") && w.ends_with(&format!(":{token}")))
1422                    .count()
1423            };
1424            assert_eq!(unavailable_for("suite@a"), 1, "{words:?}");
1425            assert_eq!(unavailable_for("lint@b"), 1, "{words:?}");
1426            assert!(words.contains(&"warned:lint@b".to_string()), "{words:?}");
1427        });
1428        let _ = std::fs::remove_dir_all(&dir); // a temp fixture; `repo` clears it on the next run
1429    }
1430
1431    #[test]
1432    fn a_commit_with_only_a_tree_note_still_reads_the_tree_tokens() {
1433        let dir = repo("tree-only");
1434        std::fs::write(dir.join("a.ts"), "x").unwrap();
1435        git(&dir, &["add", "a.ts"]);
1436        git(&dir, &["commit", "-qm", "chore: a"]);
1437        in_repo(&dir, || {
1438            let head = git(&dir, &["rev-parse", "HEAD"]);
1439            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1440            assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1441            let stamps = stamps_for(std::slice::from_ref(&head));
1442            assert_eq!(
1443                stamps.get(&head).map(Vec::as_slice),
1444                Some(&["pre-push-cargo-test".to_string()][..])
1445            );
1446        });
1447        let _ = std::fs::remove_dir_all(&dir);
1448    }
1449
1450    #[test]
1451    fn a_commit_with_only_a_commit_note_still_reads_its_tokens() {
1452        let dir = repo("commit-only");
1453        std::fs::write(dir.join("a.ts"), "x").unwrap();
1454        git(&dir, &["add", "a.ts"]);
1455        git(&dir, &["commit", "-qm", "chore: a"]);
1456        in_repo(&dir, || {
1457            let head = git(&dir, &["rev-parse", "HEAD"]);
1458            let mut note = Note::default();
1459            note.add_tokens(&["typecheck".to_string()]);
1460            assert!(write_note(&head, &note));
1461            let stamps = stamps_for(std::slice::from_ref(&head));
1462            assert_eq!(
1463                stamps.get(&head).map(Vec::as_slice),
1464                Some(&["typecheck".to_string()][..])
1465            );
1466        });
1467        let _ = std::fs::remove_dir_all(&dir);
1468    }
1469
1470    #[test]
1471    fn a_token_on_both_notes_is_read_once() {
1472        let dir = repo("dedup");
1473        std::fs::write(dir.join("a.ts"), "x").unwrap();
1474        git(&dir, &["add", "a.ts"]);
1475        in_repo(&dir, || {
1476            record(&["test"]);
1477            git(&dir, &["commit", "-qm", "chore: a"]);
1478            bind_to_head(); // writes `test` on the commit AND the tree
1479            let head = git(&dir, &["rev-parse", "HEAD"]);
1480            let stamps = stamps_for(std::slice::from_ref(&head));
1481            assert_eq!(
1482                stamps.get(&head).map(Vec::as_slice),
1483                Some(&["test".to_string()][..])
1484            );
1485        });
1486        let _ = std::fs::remove_dir_all(&dir);
1487    }
1488
1489    #[test]
1490    fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
1491        let dir = repo("roundtrip");
1492        std::fs::write(dir.join("a.ts"), "x").unwrap();
1493        git(&dir, &["add", "a.ts"]);
1494        in_repo(&dir, || {
1495            record(&["typecheck", "test"]);
1496            git(&dir, &["commit", "-qm", "chore: a"]);
1497            let stamped = bind_to_head();
1498            assert_eq!(
1499                stamped,
1500                vec!["typecheck".to_string(), "test".to_string()],
1501                "bind_to_head reports the scripts it stamped"
1502            );
1503            let head = git(&dir, &["rev-parse", "HEAD"]);
1504            let stamps = stamps_for(std::slice::from_ref(&head));
1505            assert_eq!(
1506                stamps.get(&head).map(Vec::as_slice),
1507                Some(&["typecheck".to_string(), "test".to_string()][..])
1508            );
1509            // One-shot: the marker is gone.
1510            // One-shot: the marker is gone. The fixture's own path, not
1511            // `marker_path()` — that helper spawns git, and a transient
1512            // spawn failure on a loaded runner reads as `None` here while
1513            // production code correctly treats it as "no marker". Seen once,
1514            // on Windows, as an unwrap panic in a sibling test.
1515            assert!(!dir.join(".git").join(MARKER).exists());
1516        });
1517        let _ = std::fs::remove_dir_all(&dir);
1518    }
1519
1520    #[test]
1521    fn a_marker_for_a_different_tree_stamps_nothing() {
1522        let dir = repo("stale");
1523        std::fs::write(dir.join("a.ts"), "x").unwrap();
1524        git(&dir, &["add", "a.ts"]);
1525        in_repo(&dir, || {
1526            record(&["typecheck"]);
1527            // The commit that actually lands carries DIFFERENT content — the
1528            // aborted-attempt-then-different-retry shape.
1529            std::fs::write(dir.join("a.ts"), "y").unwrap();
1530            git(&dir, &["add", "a.ts"]);
1531            git(&dir, &["commit", "-qm", "chore: different"]);
1532            assert!(
1533                bind_to_head().is_empty(),
1534                "bind_to_head reports nothing when the tree moved"
1535            );
1536            let head = git(&dir, &["rev-parse", "HEAD"]);
1537            assert!(
1538                stamps_for(&[head]).is_empty(),
1539                "a stale marker must not vouch"
1540            );
1541            assert!(
1542                !dir.join(".git").join(MARKER).exists(),
1543                "consumed either way"
1544            );
1545        });
1546        let _ = std::fs::remove_dir_all(&dir);
1547    }
1548
1549    #[test]
1550    fn an_empty_record_clears_a_previous_marker() {
1551        let dir = repo("clears");
1552        std::fs::write(dir.join("a.ts"), "x").unwrap();
1553        git(&dir, &["add", "a.ts"]);
1554        in_repo(&dir, || {
1555            record(&["typecheck"]);
1556            assert!(dir.join(".git").join(MARKER).exists());
1557            record(&[]);
1558            assert!(!dir.join(".git").join(MARKER).exists());
1559        });
1560        let _ = std::fs::remove_dir_all(&dir);
1561    }
1562
1563    /// The version guard's REJECT branch, fed a hand-written marker: an old
1564    /// (or future) format is ignored rather than misread — the doc's claim,
1565    /// now pinned. Every other test's markers come from record() itself and
1566    /// so always carry the current FORMAT.
1567    #[test]
1568    fn a_marker_in_an_unknown_format_stamps_nothing() {
1569        let dir = repo("wrongformat");
1570        std::fs::write(dir.join("a.ts"), "x").unwrap();
1571        git(&dir, &["add", "a.ts"]);
1572        in_repo(&dir, || {
1573            let tree = git(&dir, &["write-tree"]);
1574            let marker = dir.join(".git").join(MARKER);
1575            std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
1576            git(&dir, &["commit", "-qm", "chore: a"]);
1577            bind_to_head();
1578            let head = git(&dir, &["rev-parse", "HEAD"]);
1579            assert!(
1580                stamps_for(std::slice::from_ref(&head)).is_empty(),
1581                "an unknown format was trusted"
1582            );
1583            assert!(!marker.exists(), "consumed either way");
1584        });
1585        let _ = std::fs::remove_dir_all(&dir);
1586    }
1587
1588    /// A note somebody else wrote into OUR ref is not a stamp. Absent this,
1589    /// `git notes --ref=amont-gate add` would be a one-line way to vouch for
1590    /// an unchecked commit — the parsing trust boundary of the whole chain.
1591    #[test]
1592    fn a_foreign_note_is_not_a_stamp() {
1593        let dir = repo("foreignnote");
1594        std::fs::write(dir.join("a.ts"), "x").unwrap();
1595        git(&dir, &["add", "a.ts"]);
1596        in_repo(&dir, || {
1597            git(&dir, &["commit", "-qm", "chore: a"]);
1598            git(
1599                &dir,
1600                &[
1601                    "notes",
1602                    "--ref",
1603                    NOTES_REF,
1604                    "add",
1605                    "-m",
1606                    "typecheck test",
1607                    "HEAD",
1608                ],
1609            );
1610            let head = git(&dir, &["rev-parse", "HEAD"]);
1611            assert!(
1612                stamps_for(std::slice::from_ref(&head)).is_empty(),
1613                "a note without the format token was trusted"
1614            );
1615        });
1616        let _ = std::fs::remove_dir_all(&dir);
1617    }
1618
1619    /// An absent notes ref is `Some("")`, not `None` — the distinction the
1620    /// warning on that branch depends on. If git ever starts failing here
1621    /// instead, this test fails and the warning stops being a lie.
1622    #[test]
1623    fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
1624        let dir = repo("no-stamps");
1625        std::fs::write(dir.join("a.ts"), "x").unwrap();
1626        git(&dir, &["add", "a.ts"]);
1627        git(&dir, &["commit", "-qm", "chore: a"]);
1628        in_repo(&dir, || {
1629            assert_eq!(
1630                crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
1631                Some(""),
1632                "an absent notes ref must be an ANSWER, not a failure — the \
1633                 no-stamps path and the git-is-broken path are told apart by it"
1634            );
1635            let head = git(&dir, &["rev-parse", "HEAD"]);
1636            assert!(stamps_for(&[head]).is_empty());
1637        });
1638        let _ = std::fs::remove_dir_all(&dir);
1639    }
1640
1641    /// The compatibility promise, in both directions.
1642    ///
1643    /// A note written before evidence lines existed is ONE line, and it must
1644    /// parse to exactly the tokens it always did — every skip decision in
1645    /// this module reads that line, and a reader that needed the new shape
1646    /// would stop honouring every stamp on every machine the day it shipped.
1647    #[test]
1648    fn a_note_from_before_the_run_lines_parses_unchanged() {
1649        let note = Note::parse("amont-gate-v1 typecheck test");
1650        assert_eq!(note.tokens, vec!["typecheck", "test"]);
1651        assert!(note.runs.is_empty());
1652        // And round-trips to the same bytes, so an old amont reading a note
1653        // this one rewrote sees what it wrote.
1654        assert_eq!(note.render(), "amont-gate-v1 typecheck test");
1655    }
1656
1657    /// The new shape: line one unchanged, evidence after it.
1658    #[test]
1659    fn run_lines_are_read_without_disturbing_the_tokens() {
1660        let body = "amont-gate-v1 pre-push-cargo-test\n\
1661                    run 1726900000 pre-push-cargo-test pass 412391\n\
1662                    run 1726903600 pre-push-audit-js fail 903\n";
1663        let note = Note::parse(body);
1664        assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1665        assert_eq!(note.runs.len(), 2);
1666        assert_eq!(
1667            note.runs[0],
1668            Run {
1669                at: 1_726_900_000,
1670                gate: "pre-push-cargo-test".into(),
1671                outcome: RunOutcome::Passed,
1672                ms: 412_391,
1673            }
1674        );
1675        assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1676        assert_eq!(note.render(), body.trim_end());
1677    }
1678
1679    /// A line this version does not understand is dropped, not guessed at —
1680    /// so a future amont may add a field (or an outcome) without an older one
1681    /// inventing a meaning for it.
1682    #[test]
1683    fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
1684        let note = Note::parse(
1685            "amont-gate-v1 test\n\
1686             run 1726900000 pre-push-cargo-test pass 400\n\
1687             run tomorrow pre-push-cargo-test pass 400\n\
1688             run 1726900001 pre-push-cargo-test sideways 400\n\
1689             banana\n\
1690             run 1726900002 pre-push-cargo-test fail 500\n",
1691        );
1692        assert_eq!(note.tokens, vec!["test"]);
1693        assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
1694        assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1695    }
1696
1697    /// A deferral line (ADR-0013) round-trips, is never a token, and is not
1698    /// trimmed with the run history: more than [`MAX_RUNS`] later runs on the
1699    /// same tree must not make the push twin forget the commit deferred it.
1700    #[test]
1701    fn a_deferral_is_never_a_token_and_outlives_the_run_trim() {
1702        let mut note = Note::parse("amont-gate-v1 lint\ndeferred cargo-test\n");
1703        assert_eq!(note.tokens, vec!["lint"]);
1704        assert_eq!(note.deferred, vec!["cargo-test"]);
1705        let runs: Vec<Run> = (0..MAX_RUNS as u64 + 10)
1706            .map(|i| Run {
1707                at: 1_726_900_000 + i,
1708                gate: "pre-push-audit-js".into(),
1709                outcome: RunOutcome::Passed,
1710                ms: 1,
1711            })
1712            .collect();
1713        note.add_runs(&runs);
1714        let again = Note::parse(&note.render());
1715        assert_eq!(again.runs.len(), MAX_RUNS);
1716        assert_eq!(again.deferred, vec!["cargo-test"]);
1717        assert_eq!(again.tokens, vec!["lint"]);
1718    }
1719
1720    /// A note somebody else wrote into our ref is not evidence either. The
1721    /// token line is the trust boundary for BOTH halves of the note.
1722    #[test]
1723    fn a_foreign_note_yields_no_runs() {
1724        let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
1725        assert!(note.tokens.is_empty() && note.runs.is_empty());
1726    }
1727
1728    /// Recording evidence must never cost a stamp. `stamp_push` and
1729    /// `bind_to_head` rewrite the same note, and the first version of this
1730    /// rendered the note from its own token list — which would have erased
1731    /// every run line on the next push.
1732    #[test]
1733    fn a_stamp_and_its_evidence_survive_each_other() {
1734        let dir = repo("evidence");
1735        std::fs::write(dir.join("a.ts"), "x").unwrap();
1736        git(&dir, &["add", "a.ts"]);
1737        in_repo(&dir, || {
1738            git(&dir, &["commit", "-qm", "chore: a"]);
1739            let head = git(&dir, &["rev-parse", "HEAD"]);
1740            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1741            record_runs(
1742                &tree,
1743                &[Run {
1744                    at: 1_726_900_000,
1745                    gate: "pre-push-cargo-test".into(),
1746                    outcome: RunOutcome::Failed,
1747                    ms: 412_391,
1748                }],
1749            );
1750            // …and now a later push of the same content passes and stamps it.
1751            assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
1752            let note = note_at(&tree);
1753            assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1754            assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
1755            // The stamp still reads back as a stamp.
1756            let stamps = stamps_for(std::slice::from_ref(&head));
1757            assert_eq!(
1758                stamps.get(&head).map(Vec::as_slice),
1759                Some(&["pre-push-cargo-test".to_string()][..])
1760            );
1761        });
1762        let _ = std::fs::remove_dir_all(&dir);
1763    }
1764
1765    /// The whole point of the evidence half: it is not a stamp. A recorded
1766    /// run — even a passing one — must not let the gate be skipped, because
1767    /// skipping is decided by the token line and nothing else.
1768    #[test]
1769    fn a_recorded_run_is_not_a_stamp() {
1770        let dir = repo("not-a-stamp");
1771        std::fs::write(dir.join("a.ts"), "x").unwrap();
1772        git(&dir, &["add", "a.ts"]);
1773        in_repo(&dir, || {
1774            git(&dir, &["commit", "-qm", "chore: a"]);
1775            let head = git(&dir, &["rev-parse", "HEAD"]);
1776            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1777            record_runs(
1778                &tree,
1779                &[Run {
1780                    at: 1_726_900_000,
1781                    gate: "pre-push-cargo-test".into(),
1782                    outcome: RunOutcome::Passed,
1783                    ms: 412_391,
1784                }],
1785            );
1786            assert!(
1787                stamps_for(std::slice::from_ref(&head)).is_empty(),
1788                "a run line vouched for a gate — evidence must never gate"
1789            );
1790            assert!(
1791                !vouched_for_staged_tree().contains("pre-push-cargo-test"),
1792                "a run line vouched at commit time"
1793            );
1794            // It IS readable as history, though.
1795            let history = crate::gate_evidence::history_in(&dir);
1796            assert_eq!(history.runs.len(), 1);
1797            assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
1798        });
1799        let _ = std::fs::remove_dir_all(&dir);
1800    }
1801
1802    #[test]
1803    fn forget_removes_the_stamps() {
1804        let dir = repo("forget");
1805        std::fs::write(dir.join("a.ts"), "x").unwrap();
1806        git(&dir, &["add", "a.ts"]);
1807        in_repo(&dir, || {
1808            record(&["typecheck"]);
1809            git(&dir, &["commit", "-qm", "chore: a"]);
1810            bind_to_head();
1811            let head = git(&dir, &["rev-parse", "HEAD"]);
1812            assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
1813            forget();
1814            assert!(stamps_for(&[head]).is_empty());
1815        });
1816        let _ = std::fs::remove_dir_all(&dir);
1817    }
1818
1819    /// A squash-merge produces a commit this machine never saw, and the
1820    /// stamp has to survive it.
1821    ///
1822    /// This is the case that motivated tree-stamping. A branch is verified
1823    /// locally and stamped; the forge squashes it onto `main` as a NEW
1824    /// commit with no note; pushing a tag on that commit re-ran every gate
1825    /// the branch had already proved. Measured on this repository: 13
1826    /// seconds for the branch push, then the full suite for the tag push,
1827    /// which died on a reset connection.
1828    ///
1829    /// The tree is what the gates actually read, and it is identical across
1830    /// that merge whenever the base has not moved — five of five merges in
1831    /// one afternoon here.
1832    #[test]
1833    fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
1834        let dir = repo("squashed");
1835        std::fs::write(dir.join("a.ts"), "x").unwrap();
1836        git(&dir, &["add", "a.ts"]);
1837        in_repo(&dir, || {
1838            record(&["test"]);
1839            git(&dir, &["commit", "-qm", "feat: on a branch"]);
1840            assert_eq!(bind_to_head(), vec!["test".to_string()]);
1841            let branch_tip = git(&dir, &["rev-parse", "HEAD"]);
1842
1843            // Stand in for the forge's squash: a DIFFERENT commit object
1844            // with the SAME tree. `--amend` with a new message is the
1845            // cheapest way to get exactly that shape.
1846            git(
1847                &dir,
1848                &[
1849                    "commit",
1850                    "-q",
1851                    "--amend",
1852                    "-m",
1853                    "feat: squashed by the forge",
1854                ],
1855            );
1856            let merged = git(&dir, &["rev-parse", "HEAD"]);
1857            assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
1858            assert_eq!(
1859                git(&dir, &["rev-parse", "HEAD^{tree}"]),
1860                git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
1861                "…carrying the same tree, which is the whole premise"
1862            );
1863
1864            let stamps = stamps_for(std::slice::from_ref(&merged));
1865            assert_eq!(
1866                stamps.get(&merged).map(Vec::as_slice),
1867                Some(&["test".to_string()][..]),
1868                "the stamp must follow the content, not the commit hash"
1869            );
1870        });
1871        let _ = std::fs::remove_dir_all(&dir);
1872    }
1873
1874    /// And it must not follow anything else. A commit whose tree was never
1875    /// stamped gets nothing, however many other stamps exist — otherwise
1876    /// this widening would vouch for content nobody checked.
1877    #[test]
1878    fn a_different_tree_gets_no_stamp_from_the_fallback() {
1879        let dir = repo("othertree");
1880        std::fs::write(dir.join("a.ts"), "x").unwrap();
1881        git(&dir, &["add", "a.ts"]);
1882        in_repo(&dir, || {
1883            record(&["test"]);
1884            git(&dir, &["commit", "-qm", "chore: stamped"]);
1885            assert_eq!(bind_to_head(), vec!["test".to_string()]);
1886
1887            // Different CONTENT, so a different tree, and no marker: this
1888            // commit was never judged.
1889            std::fs::write(dir.join("b.ts"), "y").unwrap();
1890            git(&dir, &["add", "b.ts"]);
1891            git(&dir, &["commit", "-qm", "chore: unjudged"]);
1892            let unstamped = git(&dir, &["rev-parse", "HEAD"]);
1893
1894            assert!(
1895                stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
1896                "a tree nobody stamped must not inherit one"
1897            );
1898        });
1899        let _ = std::fs::remove_dir_all(&dir);
1900    }
1901
1902    // ---- declared-input reuse (`.github/attest-inputs`) -------------------
1903
1904    /// A repository declaring that gate `test` reads only `a.ts`, with one
1905    /// commit stamped `test@abc`. The plans directory is where a later,
1906    /// plan-only commit will change the tree without touching any input.
1907    fn declared(name: &str, spec: &str) -> PathBuf {
1908        let dir = repo(name);
1909        std::fs::create_dir_all(dir.join(".github")).unwrap();
1910        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1911        std::fs::write(dir.join("a.ts"), "x").unwrap();
1912        std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
1913        std::fs::write(dir.join(".github/attest-inputs"), spec).unwrap();
1914        git(&dir, &["add", "-A"]);
1915        in_repo(&dir, || {
1916            record(&["test@abc"]);
1917            git(&dir, &["commit", "-qm", "feat: judged"]);
1918            assert_eq!(bind_to_head(), vec!["test".to_string()]);
1919        });
1920        dir
1921    }
1922
1923    /// Change only the plan and commit it WITHOUT a marker: nothing was
1924    /// judged for this tree, so only the fingerprint route can speak.
1925    fn plan_only_commit(dir: &Path) -> String {
1926        std::fs::write(dir.join("docs/plans/p.md"), "plan v2, closing").unwrap();
1927        git(dir, &["add", "docs/plans/p.md"]);
1928        git(dir, &["commit", "-qm", "docs(plan): done"]);
1929        git(dir, &["rev-parse", "HEAD"])
1930    }
1931
1932    #[test]
1933    fn a_plan_only_commit_reuses_the_stamp_of_a_declared_gate() {
1934        let dir = declared("plan-only", "test a.ts\n");
1935        in_repo(&dir, || {
1936            let head = plan_only_commit(&dir);
1937            let stamps = stamps_for(std::slice::from_ref(&head));
1938            assert_eq!(
1939                stamps.get(&head).map(Vec::as_slice),
1940                Some(&["test@abc".to_string()][..]),
1941                "the closing commit changed the tree and none of the declared inputs"
1942            );
1943        });
1944        let _ = std::fs::remove_dir_all(&dir);
1945    }
1946
1947    #[test]
1948    fn the_staged_tree_of_a_plan_only_commit_is_vouched_for() {
1949        let dir = declared("staged", "test a.ts\n");
1950        in_repo(&dir, || {
1951            std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1952            git(&dir, &["add", "docs/plans/p.md"]);
1953            assert!(vouched_for_staged_tree().contains("test@abc"));
1954        });
1955        let _ = std::fs::remove_dir_all(&dir);
1956    }
1957
1958    #[test]
1959    fn partial_staging_is_judged_on_the_index_not_the_working_copy() {
1960        let dir = declared("partial", "test a.ts\n");
1961        in_repo(&dir, || {
1962            // The plan is staged; an unstaged edit to a declared input sits in
1963            // the working copy. The commit would carry only the plan.
1964            std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1965            git(&dir, &["add", "docs/plans/p.md"]);
1966            std::fs::write(dir.join("a.ts"), "unstaged edit").unwrap();
1967            assert!(vouched_for_staged_tree().contains("test@abc"));
1968
1969            // The other way round: the input IS staged, so it misses even
1970            // though the working copy was put back.
1971            std::fs::write(dir.join("a.ts"), "staged edit").unwrap();
1972            git(&dir, &["add", "a.ts"]);
1973            std::fs::write(dir.join("a.ts"), "x").unwrap();
1974            assert!(!vouched_for_staged_tree().contains("test@abc"));
1975        });
1976        let _ = std::fs::remove_dir_all(&dir);
1977    }
1978
1979    #[test]
1980    fn a_changed_declared_input_misses() {
1981        let dir = declared("input-changed", "test a.ts\n");
1982        in_repo(&dir, || {
1983            std::fs::write(dir.join("a.ts"), "changed").unwrap();
1984            git(&dir, &["add", "a.ts"]);
1985            git(&dir, &["commit", "-qm", "feat: unjudged"]);
1986            let head = git(&dir, &["rev-parse", "HEAD"]);
1987            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1988        });
1989        let _ = std::fs::remove_dir_all(&dir);
1990    }
1991
1992    #[test]
1993    fn a_changed_declaration_misses() {
1994        let dir = declared("declaration-changed", "test a.ts\n");
1995        in_repo(&dir, || {
1996            // The spec's own blob is in every fingerprint: widening what the
1997            // gate reads is a different declaration, so nothing is reused.
1998            std::fs::write(dir.join("b.ts"), "y").unwrap();
1999            std::fs::write(dir.join(".github/attest-inputs"), "test a.ts b.ts\n").unwrap();
2000            git(&dir, &["add", "-A"]);
2001            git(&dir, &["commit", "-qm", "chore: widen the declaration"]);
2002            let head = git(&dir, &["rev-parse", "HEAD"]);
2003            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2004        });
2005        let _ = std::fs::remove_dir_all(&dir);
2006    }
2007
2008    #[test]
2009    fn a_declared_config_file_is_an_input_like_any_other() {
2010        // A gate's scope lives in a tracked file (`amont.conf`). Declared, a
2011        // scope-only edit changes the fingerprint and the stamp misses.
2012        let dir = declared("config", "test a.ts amont.conf\n");
2013        in_repo(&dir, || {
2014            // `declared` ran before amont.conf existed: it is a required path,
2015            // so that first commit had no fingerprint and filed nothing.
2016            assert!(!inputs_ref_exists());
2017
2018            std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2019            git(&dir, &["add", "amont.conf"]);
2020            record(&["test@abc"]);
2021            git(&dir, &["commit", "-qm", "chore: config"]);
2022            assert_eq!(bind_to_head(), vec!["test".to_string()]);
2023
2024            std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
2025            git(&dir, &["add", "docs/plans/p.md"]);
2026            git(&dir, &["commit", "-qm", "docs(plan): done"]);
2027            let plan = git(&dir, &["rev-parse", "HEAD"]);
2028            assert!(stamps_for(std::slice::from_ref(&plan)).contains_key(&plan));
2029
2030            std::fs::write(dir.join("amont.conf"), "scope = lib\n").unwrap();
2031            git(&dir, &["add", "amont.conf"]);
2032            git(&dir, &["commit", "-qm", "chore: scope-only change"]);
2033            let scope = git(&dir, &["rev-parse", "HEAD"]);
2034            assert!(
2035                stamps_for(std::slice::from_ref(&scope)).is_empty(),
2036                "a scope-only change must miss"
2037            );
2038        });
2039        let _ = std::fs::remove_dir_all(&dir);
2040    }
2041
2042    #[test]
2043    fn a_declared_stamp_is_read_back_as_its_complete_token() {
2044        // The identity comparison lives in the readers (`pair_verdict`, the
2045        // push gate): they skip only on the complete token they compute. This
2046        // pins what the new route owes them: tokens come back verbatim, never
2047        // widened to the gate's name, and a second identity under the same key
2048        // is kept apart from the first.
2049        let dir = declared("identity", "test a.ts\n");
2050        in_repo(&dir, || {
2051            let head = plan_only_commit(&dir);
2052            let tokens = stamps_for(std::slice::from_ref(&head))
2053                .remove(&head)
2054                .unwrap_or_default();
2055            assert_eq!(tokens, vec!["test@abc".to_string()]);
2056
2057            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2058            assert!(stamp_tree(&tree, &["test@def".to_string()]));
2059            let tokens = tree_tokens(&tree);
2060            assert!(tokens.contains(&"test@abc".to_string()));
2061            assert!(tokens.contains(&"test@def".to_string()));
2062            assert!(!tokens.contains(&"test@zzz".to_string()));
2063            assert!(!tokens.contains(&"test".to_string()));
2064        });
2065        let _ = std::fs::remove_dir_all(&dir);
2066    }
2067
2068    #[test]
2069    fn a_gate_that_does_not_declare_the_manifest_is_not_offered_the_route() {
2070        // `amont.conf` is tracked but the gate's declaration omits it: a
2071        // scope-only edit would be invisible to the fingerprint, so the route
2072        // is refused outright. Nothing is filed and nothing is reused.
2073        let dir = repo("manifest-undeclared");
2074        std::fs::create_dir_all(dir.join(".github")).unwrap();
2075        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2076        std::fs::write(dir.join("a.ts"), "x").unwrap();
2077        std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2078        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2079        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2080        git(&dir, &["add", "-A"]);
2081        in_repo(&dir, || {
2082            record(&["test@abc"]);
2083            git(&dir, &["commit", "-qm", "feat: judged"]);
2084            bind_to_head();
2085            assert!(!inputs_ref_exists(), "the route must not open");
2086            let head = plan_only_commit(&dir);
2087            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2088        });
2089        let _ = std::fs::remove_dir_all(&dir);
2090    }
2091
2092    #[test]
2093    fn a_gate_declaring_the_manifest_opens_the_route() {
2094        // The counterpart: with `amont.conf` among its declared inputs the
2095        // gate is filed by fingerprint again.
2096        let dir = declared("manifest-declared", "test a.ts amont.conf\n");
2097        in_repo(&dir, || {
2098            std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2099            git(&dir, &["add", "amont.conf"]);
2100            record(&["test@abc"]);
2101            git(&dir, &["commit", "-qm", "chore: config"]);
2102            bind_to_head();
2103            assert!(inputs_ref_exists());
2104        });
2105        let _ = std::fs::remove_dir_all(&dir);
2106    }
2107
2108    #[test]
2109    fn an_undeclared_gate_keeps_whole_tree_behaviour() {
2110        let dir = declared("undeclared", "test a.ts\n");
2111        in_repo(&dir, || {
2112            // `lint` passed on the first tree but the spec declares only
2113            // `test`: the plan-only commit is a new tree for `lint`.
2114            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2115            assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2116            let head = plan_only_commit(&dir);
2117            let tokens = stamps_for(std::slice::from_ref(&head))
2118                .remove(&head)
2119                .unwrap_or_default();
2120            assert!(tokens.contains(&"test@abc".to_string()));
2121            assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2122        });
2123        let _ = std::fs::remove_dir_all(&dir);
2124    }
2125
2126    #[test]
2127    fn an_invalid_or_ambiguous_spec_falls_back_to_whole_tree_behaviour() {
2128        // A glob invalidates the whole spec.
2129        let dir = declared("invalid", "test src/*\n");
2130        in_repo(&dir, || {
2131            assert!(!inputs_ref_exists(), "no valid spec, nothing is filed");
2132            let head = plan_only_commit(&dir);
2133            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2134        });
2135        let _ = std::fs::remove_dir_all(&dir);
2136
2137        // Both locations present: ambiguous, the route is off.
2138        let dir = repo("ambiguous");
2139        std::fs::create_dir_all(dir.join(".github")).unwrap();
2140        std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2141        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2142        std::fs::write(dir.join("a.ts"), "x").unwrap();
2143        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2144        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2145        std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
2146        git(&dir, &["add", "-A"]);
2147        in_repo(&dir, || {
2148            record(&["test@abc"]);
2149            git(&dir, &["commit", "-qm", "feat: judged"]);
2150            bind_to_head();
2151            assert!(!inputs_ref_exists());
2152            let head = plan_only_commit(&dir);
2153            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2154        });
2155        let _ = std::fs::remove_dir_all(&dir);
2156    }
2157
2158    #[test]
2159    fn a_gate_that_did_not_pass_leaves_no_declared_input_stamp() {
2160        let dir = repo("failed");
2161        std::fs::create_dir_all(dir.join(".github")).unwrap();
2162        std::fs::write(dir.join("a.ts"), "x").unwrap();
2163        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2164        git(&dir, &["add", "-A"]);
2165        in_repo(&dir, || {
2166            // pre-commit blocked or ran nothing: an empty record, no marker.
2167            record(&[]);
2168            git(&dir, &["commit", "-qm", "feat: unjudged"]);
2169            assert!(bind_to_head().is_empty());
2170            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2171            let head = git(&dir, &["rev-parse", "HEAD"]);
2172            assert!(!stamp_push(&head, &tree, &[]));
2173            assert!(!inputs_ref_exists());
2174        });
2175        let _ = std::fs::remove_dir_all(&dir);
2176    }
2177
2178    #[test]
2179    fn stamp_tree_and_tree_tokens_use_the_inputs_ref() {
2180        let dir = declared("rehearsal", "test a.ts\n");
2181        in_repo(&dir, || {
2182            // A rehearsal proves a gate in a snapshot of this tree …
2183            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2184            assert!(stamp_tree(&tree, &["test@rehearsed".to_string()]));
2185            // … and a later tree with identical declared inputs reads it back.
2186            plan_only_commit(&dir);
2187            let later = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2188            assert_ne!(later, tree);
2189            assert!(tree_tokens(&later).contains(&"test@rehearsed".to_string()));
2190        });
2191        let _ = std::fs::remove_dir_all(&dir);
2192    }
2193
2194    #[test]
2195    fn the_inputs_ref_is_keyed_the_way_attest_keys_its_own() {
2196        let dir = declared("key", "test a.ts\n");
2197        in_repo(&dir, || {
2198            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2199            let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2200            let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2201            let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
2202            let listed = git(&dir, &["notes", "--ref", INPUTS_REF, "list"]);
2203            assert!(
2204                listed
2205                    .lines()
2206                    .any(|l| l.split_whitespace().nth(1) == Some(key.as_str())),
2207                "{listed}"
2208            );
2209        });
2210        let _ = std::fs::remove_dir_all(&dir);
2211    }
2212
2213    #[test]
2214    fn a_foreign_token_in_the_inputs_ref_vouches_for_nothing() {
2215        let dir = declared("foreign", "test a.ts\n");
2216        in_repo(&dir, || {
2217            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2218            let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2219            let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2220            let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
2221            // Somebody files a token for ANOTHER gate under `test`'s key.
2222            let mut note = note_in(INPUTS_REF, &key);
2223            note.add_tokens(&["publish@evil".to_string()]);
2224            assert!(write_note_in(INPUTS_REF, &key, &note));
2225            assert!(!tree_tokens(&tree).contains(&"publish@evil".to_string()));
2226        });
2227        let _ = std::fs::remove_dir_all(&dir);
2228    }
2229
2230    #[test]
2231    fn forget_removes_the_inputs_ref_too() {
2232        let dir = declared("forget-inputs", "test a.ts\n");
2233        in_repo(&dir, || {
2234            assert!(inputs_ref_exists());
2235            assert!(forget());
2236            assert!(!inputs_ref_exists());
2237        });
2238        let _ = std::fs::remove_dir_all(&dir);
2239    }
2240
2241    /// A repository that declares nothing: `a.ts`, a plan, and optionally an
2242    /// `amont.conf`, judged once (`test@abc`).
2243    fn canonical(name: &str, conf: Option<&str>) -> PathBuf {
2244        let dir = repo(name);
2245        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2246        std::fs::write(dir.join("a.ts"), "x").unwrap();
2247        std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
2248        if let Some(conf) = conf {
2249            std::fs::write(dir.join("amont.conf"), conf).unwrap();
2250        }
2251        git(&dir, &["add", "-A"]);
2252        in_repo(&dir, || {
2253            record(&["test@abc"]);
2254            git(&dir, &["commit", "-qm", "feat: judged"]);
2255            assert_eq!(bind_to_head(), vec!["test".to_string()]);
2256        });
2257        dir
2258    }
2259
2260    fn vouched(dir: &Path, commit: &str) -> Vec<String> {
2261        in_repo(dir, || {
2262            stamps_for(std::slice::from_ref(&commit.to_string()))
2263                .remove(commit)
2264                .unwrap_or_default()
2265        })
2266    }
2267
2268    #[test]
2269    fn with_no_spec_a_plans_only_commit_is_vouched_for_canonically() {
2270        let dir = canonical("canon-plan-edit", None);
2271        in_repo(&dir, || {
2272            assert!(inputs_ref_exists(), "the canonical stamp is filed");
2273            let head = plan_only_commit(&dir);
2274            assert_eq!(
2275                stamps_for(std::slice::from_ref(&head))
2276                    .remove(&head)
2277                    .unwrap_or_default(),
2278                vec!["test@abc".to_string()]
2279            );
2280            // The staged tree, as pre-commit judges it, is vouched for too.
2281            std::fs::write(dir.join("docs/plans/p.md"), "plan v3").unwrap();
2282            git(&dir, &["add", "docs/plans/p.md"]);
2283            assert!(vouched_for_staged_tree().contains("test@abc"));
2284        });
2285        let _ = std::fs::remove_dir_all(&dir);
2286    }
2287
2288    #[test]
2289    fn a_plan_added_deleted_or_renamed_is_not_vouched_for() {
2290        let dir = canonical("canon-plan-exists", None);
2291        std::fs::write(dir.join("docs/plans/q.md"), "second plan").unwrap();
2292        git(&dir, &["add", "docs/plans/q.md"]);
2293        git(&dir, &["commit", "-qm", "docs(plan): add"]);
2294        let added = git(&dir, &["rev-parse", "HEAD"]);
2295        assert!(vouched(&dir, &added).is_empty(), "a plan added");
2296        git(&dir, &["mv", "docs/plans/p.md", "docs/plans/r.md"]);
2297        git(&dir, &["commit", "-qm", "docs(plan): rename"]);
2298        let renamed = git(&dir, &["rev-parse", "HEAD"]);
2299        assert!(vouched(&dir, &renamed).is_empty(), "a plan renamed");
2300        let _ = std::fs::remove_dir_all(&dir);
2301    }
2302
2303    #[test]
2304    fn with_no_spec_any_other_change_is_not_vouched_for() {
2305        let dir = canonical("canon-code-edit", Some("gate test = make test\n"));
2306        std::fs::write(dir.join("a.ts"), "changed").unwrap();
2307        git(&dir, &["commit", "-qam", "feat: code"]);
2308        let code = git(&dir, &["rev-parse", "HEAD"]);
2309        assert!(vouched(&dir, &code).is_empty(), "a source edit");
2310        // amont.conf is part of the canonical tree: a scope-only edit misses.
2311        std::fs::write(dir.join("amont.conf"), "gate test = make other\n").unwrap();
2312        git(&dir, &["commit", "-qam", "chore: config"]);
2313        let conf = git(&dir, &["rev-parse", "HEAD"]);
2314        assert!(vouched(&dir, &conf).is_empty(), "a manifest edit");
2315        let _ = std::fs::remove_dir_all(&dir);
2316    }
2317
2318    #[test]
2319    fn plan_exempt_off_closes_the_canonical_route() {
2320        for (name, conf) in [
2321            ("off", "set planExempt off\n"),
2322            ("spelled", "SET  PLANEXEMPT\tOff\r\n"),
2323            ("after", "set planExempt on\nset planExempt off\n"),
2324        ] {
2325            let dir = canonical(&format!("canon-off-{name}"), Some(conf));
2326            in_repo(&dir, || {
2327                assert!(!inputs_ref_exists(), "{name}: nothing is filed");
2328                let head = plan_only_commit(&dir);
2329                assert!(
2330                    stamps_for(std::slice::from_ref(&head)).is_empty(),
2331                    "{name}: a plans-only commit is a new tree"
2332                );
2333            });
2334            let _ = std::fs::remove_dir_all(&dir);
2335        }
2336        // `on`, a trailing comment and a comment line do not opt out.
2337        for (name, conf) in [
2338            ("on", "set planExempt on\n"),
2339            ("comment", "set planExempt off # no\n"),
2340            ("commented", "# set planExempt off\n"),
2341        ] {
2342            let dir = canonical(&format!("canon-on-{name}"), Some(conf));
2343            let head = plan_only_commit(&dir);
2344            assert!(!vouched(&dir, &head).is_empty(), "{name}: still canonical");
2345            let _ = std::fs::remove_dir_all(&dir);
2346        }
2347    }
2348
2349    #[test]
2350    fn a_spec_that_cannot_be_used_means_no_canonical_stamps() {
2351        // A directory where the spec should be: listed, unreadable as a blob.
2352        let dir = repo("canon-unreadable-spec");
2353        std::fs::create_dir_all(dir.join(".github/attest-inputs")).unwrap();
2354        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2355        std::fs::write(dir.join(".github/attest-inputs/x"), "x").unwrap();
2356        std::fs::write(dir.join("a.ts"), "x").unwrap();
2357        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2358        git(&dir, &["add", "-A"]);
2359        in_repo(&dir, || {
2360            record(&["test@abc"]);
2361            git(&dir, &["commit", "-qm", "feat: judged"]);
2362            bind_to_head();
2363            assert!(!inputs_ref_exists(), "an unreadable spec opens nothing");
2364            let head = plan_only_commit(&dir);
2365            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2366        });
2367        let _ = std::fs::remove_dir_all(&dir);
2368    }
2369
2370    #[test]
2371    fn two_specs_mean_no_canonical_stamps() {
2372        let dir = repo("canon-ambiguous");
2373        std::fs::create_dir_all(dir.join(".github")).unwrap();
2374        std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2375        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2376        std::fs::write(dir.join("a.ts"), "x").unwrap();
2377        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2378        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2379        std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
2380        git(&dir, &["add", "-A"]);
2381        in_repo(&dir, || {
2382            record(&["test@abc"]);
2383            git(&dir, &["commit", "-qm", "feat: judged"]);
2384            bind_to_head();
2385            assert!(!inputs_ref_exists());
2386            let head = plan_only_commit(&dir);
2387            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2388        });
2389        let _ = std::fs::remove_dir_all(&dir);
2390    }
2391
2392    #[test]
2393    fn a_valid_spec_keeps_precedence_over_the_canonical_route() {
2394        // `lint` is not declared: it must NOT ride the canonical route.
2395        let dir = declared("canon-precedence", "test a.ts\n");
2396        in_repo(&dir, || {
2397            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2398            assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2399            let head = plan_only_commit(&dir);
2400            let tokens = stamps_for(std::slice::from_ref(&head))
2401                .remove(&head)
2402                .unwrap_or_default();
2403            assert!(tokens.contains(&"test@abc".to_string()));
2404            assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2405        });
2406        let _ = std::fs::remove_dir_all(&dir);
2407    }
2408
2409    // Both name sets (decisions ADR-0068, plan "greengate signs its notes
2410    // under green names", Phase 2): read green first, legacy only for a key
2411    // the green ref has no note for, a note's header matching its ref.
2412
2413    /// A repository with one unjudged commit: no stamp under either set.
2414    fn unstamped(name: &str) -> (PathBuf, String, String) {
2415        let dir = repo(name);
2416        std::fs::write(dir.join("a.ts"), "x").unwrap();
2417        git(&dir, &["add", "a.ts"]);
2418        git(&dir, &["commit", "-qm", "feat: a"]);
2419        let head = git(&dir, &["rev-parse", "HEAD"]);
2420        let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2421        (dir, head, tree)
2422    }
2423
2424    /// Plant `body` at `key` in `notes_ref`, as another greengate would.
2425    fn plant(dir: &Path, notes_ref: &str, key: &str, body: &str) {
2426        git(
2427            dir,
2428            &["notes", "--ref", notes_ref, "add", "-f", "-m", body, key],
2429        );
2430    }
2431
2432    fn stamps_of(commit: &str) -> Vec<String> {
2433        stamps_for(&[commit.to_string()])
2434            .remove(commit)
2435            .unwrap_or_default()
2436    }
2437
2438    #[test]
2439    fn a_pass_is_found_under_either_gate_ref() {
2440        for (i, set) in READ.iter().enumerate() {
2441            let (dir, head, tree) = unstamped(&format!("either-{i}"));
2442            plant(
2443                &dir,
2444                set.notes_ref,
2445                &head,
2446                &format!("{} test@c", set.format),
2447            );
2448            plant(
2449                &dir,
2450                set.notes_ref,
2451                &tree,
2452                &format!("{} test@t", set.format),
2453            );
2454            plant(
2455                &dir,
2456                set.cluster_ref,
2457                &tree,
2458                &format!("{} suite@k", set.format),
2459            );
2460            plant(
2461                &dir,
2462                set.done_ref,
2463                &tree,
2464                &format!("{} warned:lint@w", set.format),
2465            );
2466            in_repo(&dir, || {
2467                let mut got = stamps_of(&head);
2468                got.sort();
2469                assert_eq!(got, ["test@c", "test@t"], "{}", set.notes_ref);
2470                assert_eq!(tree_tokens(&tree), ["test@t"], "{}", set.notes_ref);
2471                assert_eq!(cluster_tokens(&tree), ["suite@k"], "{}", set.cluster_ref);
2472                assert!(
2473                    done_on_every(
2474                        std::slice::from_ref(&head),
2475                        "lint@w",
2476                        crate::check::Severity::Block
2477                    ),
2478                    "{}",
2479                    set.done_ref
2480                );
2481            });
2482            let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
2483        }
2484    }
2485
2486    #[test]
2487    fn with_notes_under_both_refs_the_green_note_is_read() {
2488        let (dir, head, tree) = unstamped("both-refs");
2489        for key in [&head, &tree] {
2490            plant(
2491                &dir,
2492                LEGACY.notes_ref,
2493                key,
2494                &format!("{} test@old", LEGACY.format),
2495            );
2496            plant(
2497                &dir,
2498                GREEN.notes_ref,
2499                key,
2500                &format!("{} test@new", GREEN.format),
2501            );
2502        }
2503        plant(
2504            &dir,
2505            LEGACY.cluster_ref,
2506            &tree,
2507            &format!("{} suite@old", LEGACY.format),
2508        );
2509        plant(
2510            &dir,
2511            GREEN.cluster_ref,
2512            &tree,
2513            &format!("{} suite@new", GREEN.format),
2514        );
2515        in_repo(&dir, || {
2516            assert_eq!(stamps_of(&head), ["test@new"]);
2517            assert_eq!(tree_tokens(&tree), ["test@new"]);
2518            assert_eq!(cluster_tokens(&tree), ["suite@new"]);
2519        });
2520        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
2521    }
2522
2523    #[test]
2524    fn a_note_whose_header_is_the_other_sets_reads_as_unstamped() {
2525        for (i, (sits_in, header_of)) in [(LEGACY, GREEN), (GREEN, LEGACY)].iter().enumerate() {
2526            let (dir, head, tree) = unstamped(&format!("mixed-{i}"));
2527            for key in [&head, &tree] {
2528                plant(
2529                    &dir,
2530                    sits_in.notes_ref,
2531                    key,
2532                    &format!("{} test@x", header_of.format),
2533                );
2534            }
2535            plant(
2536                &dir,
2537                sits_in.cluster_ref,
2538                &tree,
2539                &format!("{} suite@x", header_of.format),
2540            );
2541            in_repo(&dir, || {
2542                assert!(stamps_of(&head).is_empty(), "{}", sits_in.notes_ref);
2543                assert!(tree_tokens(&tree).is_empty(), "{}", sits_in.notes_ref);
2544                assert!(cluster_tokens(&tree).is_empty(), "{}", sits_in.cluster_ref);
2545            });
2546            let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
2547        }
2548    }
2549
2550    /// A green inputs note is filed under the GREEN key (its own input
2551    /// domain) and answers before the legacy one; the legacy key in the
2552    /// green ref is not read.
2553    #[test]
2554    fn the_green_inputs_ref_is_read_first_under_its_own_key() {
2555        let dir = declared("green-inputs", "test a.ts\n");
2556        in_repo(&dir, || {
2557            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2558            let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2559            let fp = crate::attest_inputs::fingerprint(&tree, &spec, "test").expect("fp");
2560            let green = crate::attest_inputs::input_key(&GREEN.attest, "test", &fp).expect("key");
2561            let legacy = crate::attest_inputs::input_key(&LEGACY.attest, "test", &fp).expect("key");
2562            assert_ne!(green, legacy, "each set keys with its own domain");
2563            let head = plan_only_commit(&dir);
2564            // The legacy key in the green ref is no green stamp.
2565            plant(
2566                &dir,
2567                GREEN.inputs_ref,
2568                &legacy,
2569                &format!("{} test@wrongkey", GREEN.format),
2570            );
2571            assert_eq!(stamps_of(&head), ["test@abc"]);
2572            plant(
2573                &dir,
2574                GREEN.inputs_ref,
2575                &green,
2576                &format!("{} test@green", GREEN.format),
2577            );
2578            assert_eq!(stamps_of(&head), ["test@green"]);
2579        });
2580        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
2581    }
2582
2583    #[test]
2584    fn a_green_canonical_note_is_read_under_the_green_domain() {
2585        let dir = canonical("green-canon", None);
2586        in_repo(&dir, || {
2587            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2588            let canon = crate::attest_inputs::canonical_route(&tree).expect("canon");
2589            let key =
2590                crate::attest_inputs::canon_gate_key(GREEN.canon_domain, &canon).expect("key");
2591            plant(
2592                &dir,
2593                GREEN.inputs_ref,
2594                &key,
2595                &format!("{} test@green", GREEN.format),
2596            );
2597            let head = plan_only_commit(&dir);
2598            assert_eq!(stamps_of(&head), ["test@green"]);
2599        });
2600        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
2601    }
2602
2603    #[test]
2604    fn forget_removes_the_refs_of_both_name_sets() {
2605        let (dir, _head, tree) = unstamped("forget-both");
2606        plant(
2607            &dir,
2608            GREEN.notes_ref,
2609            &tree,
2610            &format!("{} test@g", GREEN.format),
2611        );
2612        plant(
2613            &dir,
2614            LEGACY.notes_ref,
2615            &tree,
2616            &format!("{} test@l", LEGACY.format),
2617        );
2618        for set in READ {
2619            plant(&dir, set.done_ref, &tree, "done");
2620        }
2621        in_repo(&dir, || {
2622            assert_eq!(tree_tokens(&tree).len(), 1);
2623            assert!(forget());
2624            assert!(tree_tokens(&tree).is_empty(), "{:?}", tree_tokens(&tree));
2625        });
2626        for set in READ {
2627            for r in full_refs(&set) {
2628                let out = std::process::Command::new("git")
2629                    .args(["-C"])
2630                    .arg(&dir)
2631                    .args(["rev-parse", "--verify", "-q", &r])
2632                    .output()
2633                    .unwrap();
2634                assert!(!out.status.success(), "{r} survived forget");
2635            }
2636        }
2637        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
2638    }
2639
2640    #[test]
2641    fn writes_stay_under_the_legacy_names_and_each_full_ref_names_its_ref() {
2642        assert_eq!(WRITE, LEGACY);
2643        for (full, short) in [
2644            (NOTES_FULL_REF, NOTES_REF),
2645            (INPUTS_FULL_REF, INPUTS_REF),
2646            (CLUSTER_FULL_REF, CLUSTER_REF),
2647            (DONE_FULL_REF, DONE_REF),
2648        ] {
2649            assert_eq!(full, format!("refs/notes/{short}"));
2650        }
2651        // A writer's merge base is the written ref alone: a green note on
2652        // the key is never copied under the legacy header.
2653        let (dir, head, tree) = unstamped("write-legacy");
2654        plant(
2655            &dir,
2656            GREEN.notes_ref,
2657            &tree,
2658            &format!("{} test@new", GREEN.format),
2659        );
2660        in_repo(&dir, || {
2661            assert!(stamp_push(&head, &tree, &["suite@p".to_string()]));
2662            let written = git(&dir, &["notes", "--ref", LEGACY.notes_ref, "show", &tree]);
2663            assert_eq!(written, format!("{} suite@p", LEGACY.format));
2664        });
2665        let _ = std::fs::remove_dir_all(&dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
2666    }
2667}