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