Skip to main content

greengate_runtime/
gate_stamp.rs

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