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