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