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 `amont.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 (`amont.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 = "amont-gate";
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 = "amont.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 = "amont.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 `amont.conf` 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    let tracked = crate::git::succeeds(&[
514        "cat-file",
515        "-e",
516        &format!("{tree}:{}", crate::manifest::MANIFEST),
517    ]);
518    !tracked || crate::attest_inputs::declares(spec, gate, crate::manifest::MANIFEST)
519}
520
521/// Does the inputs ref exist here? One spawn that lets a repository nothing
522/// was ever filed for (an opted-out one, or one whose stamps never passed)
523/// skip the fingerprint and canonical routes entirely on the push path.
524fn inputs_ref_exists() -> bool {
525    crate::git::succeeds(&["rev-parse", "-q", "--verify", INPUTS_FULL_REF])
526}
527
528/// The stamp tokens on `tree` (a tree object id). Tree gates are read here
529/// and only here (ADR-0024): `tree:<name>` on the pushed tree proves the gate
530/// on exactly that content, whichever commit carried it.
531pub fn tree_tokens(tree: &str) -> Vec<String> {
532    let mut tokens = note_at(tree).tokens;
533    if inputs_ref_exists() {
534        for t in input_tokens(tree) {
535            if !tokens.contains(&t) {
536                tokens.push(t);
537            }
538        }
539    }
540    tokens
541}
542
543/// Add `tokens` to the gate note on `tree` — how a rehearsal records tree
544/// gates it proved in its snapshot of exactly that tree. Merged, never
545/// rendered from the tokens alone, so evidence already on the note survives.
546pub fn stamp_tree(tree: &str, tokens: &[String]) -> bool {
547    let mut note = note_at(tree);
548    note.add_tokens(tokens);
549    let ok = write_note(tree, &note);
550    file_inputs(tree, tokens);
551    ok
552}
553
554/// Write `note` at `key`. Best-effort, like every writer here.
555fn write_note(key: &str, note: &Note) -> bool {
556    write_note_in(NOTES_REF, key, note)
557}
558
559fn write_note_in(notes_ref: &str, key: &str, note: &Note) -> bool {
560    let body = note.render();
561    crate::git::succeeds(&["notes", "--ref", notes_ref, "add", "-f", "-m", &body, key])
562}
563
564/// Record what a gate run COST and how it ENDED, against the content it ran
565/// on.
566///
567/// Evidence only: nothing in this module reads these back to decide whether a
568/// check may be skipped, which is why recording a FAILED run — the case the
569/// stamp path deliberately has no opinion about — is safe here.
570///
571/// Best-effort and silent. A note git refused costs a row in a report nobody
572/// is blocked on; warning about it on every push would train people to ignore
573/// the warnings that do gate something.
574pub fn record_runs(key: &str, runs: &[Run]) {
575    // A gate name with whitespace in it would forge a second field on read.
576    // Refused rather than escaped: every id this repository can produce is
577    // already free of it, so the escaping would be a code path no real input
578    // ever reaches — untested by construction.
579    let runs: Vec<Run> = runs
580        .iter()
581        .filter(|r| !r.gate.is_empty() && !r.gate.contains(char::is_whitespace))
582        .cloned()
583        .collect();
584    if runs.is_empty() {
585        return;
586    }
587    let mut note = note_at(key);
588    note.add_runs(&runs);
589    let _ = write_note(key, &note);
590}
591
592/// pre-commit: record on `tree` (the staged tree, which is the commit's)
593/// that the busy policy deferred `gates`, by their commit-time script names.
594/// Best-effort and silent: a lost line runs the push twin, the safe way.
595pub fn record_deferred(tree: &str, gates: &[String]) {
596    let gates: Vec<&String> = gates
597        .iter()
598        .filter(|g| !g.is_empty() && !g.contains(char::is_whitespace))
599        .collect();
600    if gates.is_empty() {
601        return;
602    }
603    let mut note = note_at(tree);
604    for g in gates {
605        if !note.deferred.contains(g) {
606            note.deferred.push(g.clone());
607        }
608    }
609    let _ = write_note(tree, &note); // best-effort: a lost line runs the push twin, the safe way
610}
611
612/// The commit-time gates the busy policy deferred on `tree`, by script name.
613/// What `amont stamps` reports as `deferred`; never a token.
614pub fn deferred_on(tree: &str) -> Vec<String> {
615    note_at(tree).deferred
616}
617
618/// Which of `commits` carry a deferral of `gate` on their tree's note (or
619/// their own). Read only to defer a push twin, never to skip one: a commit
620/// in this set still has no stamp.
621pub fn deferred_for(commits: &[String], gate: &str) -> HashSet<String> {
622    let mut out = HashSet::new();
623    if commits.is_empty() {
624        return out;
625    }
626    let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
627    args.extend(commits.iter().map(String::as_str));
628    let Some(list) = crate::git::stdout(&args) else {
629        return out;
630    };
631    for line in list.lines() {
632        let mut it = line.split_whitespace();
633        let (Some(commit), Some(tree)) = (it.next(), it.next()) else {
634            continue;
635        };
636        if [commit, tree]
637            .iter()
638            .any(|key| note_at(key).deferred.iter().any(|d| d == gate))
639        {
640            out.insert(commit.to_string());
641        }
642    }
643    out
644}
645
646/// `$GIT_DIR/amont-gate` — the worktree-PRIVATE gitdir, deliberately: the
647/// commit this marker waits for happens in this worktree. The stamps the
648/// marker becomes live in the common dir (a notes ref) and are shared.
649fn marker_path() -> Option<PathBuf> {
650    let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
651    Some(std::path::Path::new(&dir).join(MARKER))
652}
653
654/// pre-commit: record that `scripts` ran clean against the tree the commit
655/// will carry.
656///
657/// Called on EVERY pre-commit verdict, with an empty list when nothing
658/// qualifying ran (or the commit is about to be blocked) — an aborted or
659/// unchecked attempt must not inherit a previous attempt's marker.
660///
661/// Best-effort throughout: a failure to record costs one redundant gate run
662/// at push time, which is the safe direction, and a pre-commit that failed a
663/// COMMIT over bookkeeping would be the tail wagging the dog.
664pub fn record(scripts: &[&str]) {
665    let Some(path) = marker_path() else { return };
666    if scripts.is_empty() {
667        let _ = std::fs::remove_file(&path);
668        return;
669    }
670    // The index, as the object id `git commit` is about to seal. Inherits
671    // `GIT_INDEX_FILE`, so `git commit -a`'s temporary index answers here
672    // too. Pure read of the index: writes objects, touches no ref.
673    let Some(tree) = crate::git::stdout(&["write-tree"]) else {
674        // Not "nothing ran": git could not name the tree, so nothing may be
675        // vouched for. Dropping the marker is the fail-safe half (the gate
676        // re-runs at push); saying so is the half that was missing.
677        crate::hooks::common::warn(
678            "git would not name the staged tree — this commit records no gate stamp",
679        );
680        let _ = std::fs::remove_file(&path);
681        return;
682    };
683    let mut body = format!("{FORMAT}\n{tree}\n");
684    for s in scripts {
685        body.push_str(s);
686        body.push('\n');
687    }
688    let _ = std::fs::write(&path, body);
689}
690
691/// pre-commit, before a gate runs: the scripts a previous run already
692/// vouched for against the tree this commit is about to seal.
693///
694/// Two records answer, both bound to the TREE (`git write-tree` of the index
695/// under the staged-only hold — the commit's content, not the working
696/// tree):
697///
698/// 1. the one-shot marker [`record`] left behind. post-commit consumes it,
699///    so a marker that is still there belongs to an attempt that never
700///    reached post-commit — a `commit-msg` refusal, an editor closed on an
701///    empty message, a Ctrl-C at the prompt. The gates ran, the tree is the
702///    same, the verdict stands: measured on this machine, a subject three
703///    characters too long replayed a ten-minute suite for nothing.
704/// 2. the tree note [`bind_to_head`] writes — a reword, a `reset --soft` and
705///    re-commit, or a rebase that kept the tree.
706///
707/// Every failure mode reads as "nothing is vouched for", which runs the
708/// gate: no `write-tree`, a marker for another tree, a wrong format, a git
709/// that would not answer. Reuse can only ever skip a run the record proves
710/// happened on this exact content; it can never let unjudged content
711/// through — the direction every function in this module fails in.
712///
713/// Repo-controlled inputs to the gate (its command line, its scope) live in
714/// the manifest, which is part of the tree: a changed declaration is a
715/// changed tree, and nothing is reused by tree. A gate reused by fingerprint
716/// gets the same guarantee only if it declares the manifest as an input
717/// ([`manifest_is_an_input`]); otherwise it is not offered the route at all.
718pub fn vouched_for_staged_tree() -> HashSet<String> {
719    let mut out = HashSet::new();
720    let Some(tree) = crate::git::stdout(&["write-tree"]) else {
721        return out;
722    };
723    if let Some(path) = marker_path() {
724        if let Ok(body) = std::fs::read_to_string(&path) {
725            let mut lines = body.lines();
726            if lines.next() == Some(FORMAT) && lines.next() == Some(tree.as_str()) {
727                out.extend(
728                    lines
729                        .filter(|l| !l.trim().is_empty() && !is_provenance(l))
730                        .map(str::to_string),
731                );
732            }
733        }
734    }
735    // The tree note: `notes show` fails loudly on an absent note, and a
736    // failure here is simply "no note" — the marker's answer stands alone.
737    // Tokens are `<name>@<identity>` (`gate_identity`): commit-time ones are
738    // named by script, push-time ones by full id (`pre-push-…`), which no
739    // pre-commit declaration is named after — harmless in the set, and a
740    // reader skips only on the complete token. The note's `run` lines are evidence and are not
741    // tokens: `Note` keeps the two apart so nothing here can be skipped by a
742    // line that only records how long something took.
743    out.extend(note_at(&tree).tokens);
744    // A gate the repository declares inputs for is also vouched for by any
745    // earlier tree whose declared inputs are byte-identical to this staged
746    // tree's: a plan-only commit changes the tree and none of them. The tree
747    // here is the INDEX's (`write-tree`), so partial staging is judged on what
748    // is about to be committed, not on the working copy.
749    if inputs_ref_exists() {
750        out.extend(input_tokens(&tree));
751    }
752    out
753}
754
755/// post-commit: consume the marker; stamp HEAD when the tree still matches.
756///
757/// One-shot by construction — the marker is deleted before anything is
758/// judged, so no path through here can leave it to vouch for a later commit.
759///
760/// Returns the scripts it actually stamped (empty on every no-stamp path,
761/// including a note git refused). The caller subtracts this from what the
762/// manifest declares to learn what the commit dodged — [`crate::bypass`]
763/// keeps that count. Two records, two questions: the stamp gates a check,
764/// the ledger only counts.
765pub fn bind_to_head() -> Vec<String> {
766    let Some(path) = marker_path() else {
767        return Vec::new();
768    };
769    let Ok(body) = std::fs::read_to_string(&path) else {
770        return Vec::new(); // no marker: nothing ran at pre-commit, nothing to stamp
771    };
772    let _ = std::fs::remove_file(&path);
773    let mut lines = body.lines();
774    if lines.next() != Some(FORMAT) {
775        return Vec::new();
776    }
777    let Some(tree) = lines.next() else {
778        return Vec::new();
779    };
780    let scripts: Vec<&str> = lines
781        .filter(|l| !l.trim().is_empty() && !is_provenance(l))
782        .collect();
783    if scripts.is_empty() {
784        return Vec::new();
785    }
786    let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
787        crate::hooks::common::warn(
788            "git would not name this commit's tree — no gate stamp was written",
789        );
790        return Vec::new();
791    };
792    // A different tree means this commit is not the one pre-commit judged —
793    // the marker is a dead letter from an aborted attempt.
794    if head_tree != tree {
795        return Vec::new();
796    }
797    let scripts: Vec<String> = scripts.iter().map(|s| s.to_string()).collect();
798    // The stamp goes on the TREE as well as the commit, and the tree is the
799    // one that survives the way work actually reaches `main`.
800    //
801    // A squash-merge is performed by the forge: it produces a commit nobody
802    // here ever saw, carrying no note, so a later `git push` of a tag on
803    // that commit re-ran every gate the branch had already proved. Measured
804    // on this repository: a branch push took 13 seconds and the tag push
805    // that followed took the full suite and died on a reset connection.
806    //
807    // The tree is identical across that merge whenever the base has not
808    // moved — five of five merges in one afternoon here — and identical
809    // trees are identical CONTENT, which is the only thing a test suite
810    // reads. That is the same argument `attest` makes for signing the tree
811    // rather than the commit, and this module's marker has been tree-bound
812    // since it was written; this only carries the binding through to the
813    // note.
814    //
815    // Both, not either: the commit note is what a `git log --notes` reader
816    // sees, and dropping it would make the stamps invisible in the place
817    // people look for them.
818    // MERGED into whatever is there, never rendered from the scripts alone:
819    // a pre-push run against this same tree may already have recorded
820    // evidence lines on it, and an `add -f` built from this list would erase
821    // them.
822    let mut tree_note = note_at(&head_tree);
823    tree_note.add_tokens(&scripts);
824    let _ = write_note(&head_tree, &tree_note);
825    file_inputs(&head_tree, &scripts);
826    let mut head_note = note_at("HEAD");
827    head_note.add_tokens(&scripts);
828    if !write_note("HEAD", &head_note) {
829        // A note git refused is not a stamp — and the push will re-run these
830        // checks, which is right but looks arbitrary unless it is said.
831        crate::hooks::common::warn(
832            "git refused to write the gate stamp — these checks will run again at push",
833        );
834        return Vec::new();
835    }
836    // The ledger counts NAMES: what the commit dodged is judged against what
837    // the manifest declares, and the identity is the stamp's business alone.
838    scripts
839        .iter()
840        .map(|s| crate::gate_identity::base(s).to_string())
841        .collect()
842}
843
844/// pre-push, after every block gate passed: record that `gates` passed
845/// against `tree`, the content of `commit` — MERGING with whatever the note
846/// already says, because a commit-time stamp (`test`) may already sit there
847/// and `notes add -f` would otherwise erase it.
848///
849/// Best-effort, like every writer here: a stamp that could not be written
850/// costs one redundant gate run on the next push, which is the safe
851/// direction. Returns whether the commit's note was written.
852pub fn stamp_push(commit: &str, tree: &str, gates: &[String]) -> bool {
853    if gates.is_empty() {
854        return false;
855    }
856    let mut written = false;
857    for key in [tree, commit] {
858        let mut note = note_at(key);
859        note.add_tokens(gates);
860        let ok = write_note(key, &note);
861        if key == commit {
862            written = ok;
863        }
864    }
865    file_inputs(tree, gates);
866    if !written {
867        crate::hooks::common::warn(
868            "git refused to write the push stamp — these gates will run again on the next push",
869        );
870    }
871    written
872}
873
874/// How a gate completed without passing (ADR-0018). The kind is part of the
875/// record, so each answers only for as long as it should.
876#[derive(Debug, Clone, Copy, PartialEq, Eq)]
877pub enum Completion {
878    /// The gate reported a warning itself.
879    Warned,
880    /// The gate failed while its severity was `warn`: answers only while it
881    /// still is, since a gate set back to `block` must run again.
882    FailedUnderWarn,
883    /// The gate could not run (a tool missing): answers for an hour, then
884    /// the gate is tried again.
885    Unavailable,
886}
887
888/// How long an `Unavailable` completion answers for.
889const UNAVAILABLE_FOR_SECS: u64 = 60 * 60;
890
891/// The record word for `token` completed as `how`, at `now`.
892fn completion_word(how: Completion, token: &str, now: u64) -> String {
893    match how {
894        Completion::Warned => format!("warned:{token}"),
895        Completion::FailedUnderWarn => format!("failed-under-warn:{token}"),
896        Completion::Unavailable => format!("unavailable:{now}:{token}"),
897    }
898}
899
900/// Does record word `word` answer for `token` now, under `severity`?
901fn completion_answers(word: &str, token: &str, severity: crate::check::Severity, now: u64) -> bool {
902    if word.strip_prefix("warned:") == Some(token) {
903        return true;
904    }
905    if word.strip_prefix("failed-under-warn:") == Some(token) {
906        return severity == crate::check::Severity::Warn;
907    }
908    word.strip_prefix("unavailable:")
909        .and_then(|rest| rest.split_once(':'))
910        .is_some_and(|(at, tok)| {
911            tok == token
912                && at
913                    .parse::<u64>()
914                    .is_ok_and(|at| now.saturating_sub(at) <= UNAVAILABLE_FOR_SECS)
915        })
916}
917
918fn now_secs() -> u64 {
919    std::time::SystemTime::now()
920        .duration_since(std::time::UNIX_EPOCH)
921        .map(|d| d.as_secs())
922        .unwrap_or(0)
923}
924
925/// Record on `tree` that the gates behind `tokens` completed there without
926/// passing, as `how` (ADR-0018). Merged into the note; an `Unavailable`
927/// record replaces the one before it for the same gate, so a tree's note does
928/// not grow by a word per run. The error names the tree, for the caller to
929/// say: a record that was not written costs a refused push.
930pub fn record_done(tree: &str, tokens: &[String], how: Completion) -> Result<(), String> {
931    if tokens.is_empty() {
932        return Ok(());
933    }
934    let now = now_secs();
935    let mut note = note_in(DONE_REF, tree);
936    if how == Completion::Unavailable {
937        note.tokens.retain(|word| {
938            !word
939                .strip_prefix("unavailable:")
940                .and_then(|rest| rest.split_once(':'))
941                .is_some_and(|(_, token)| tokens.iter().any(|t| t == token))
942        });
943    }
944    let words: Vec<String> = tokens
945        .iter()
946        .map(|t| completion_word(how, t, now))
947        .collect();
948    note.add_tokens(&words);
949    if write_note_in(DONE_REF, tree, &note) {
950        Ok(())
951    } else {
952        Err(format!(
953            "git refused to record the completed gates on {tree}"
954        ))
955    }
956}
957
958/// Did the gate behind `token` complete without passing on the tree of every
959/// one of `commits`, by a record that still answers under `severity`? An
960/// unreadable tree or note is "no", the direction that refuses rather than
961/// skips.
962pub fn done_on_every(commits: &[String], token: &str, severity: crate::check::Severity) -> bool {
963    let now = now_secs();
964    !commits.is_empty()
965        && commits.iter().all(|c| {
966            crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]).is_some_and(|tree| {
967                note_in(DONE_REF, &tree)
968                    .tokens
969                    .iter()
970                    .any(|word| completion_answers(word, token, severity, now))
971            })
972        })
973}
974
975/// pre-push: which of `commits` carry a stamp, and for which scripts.
976///
977/// One `notes list` narrows the reads to commits that have a note at all;
978/// absent ref, unparseable note, wrong format version — all read as "no
979/// stamp", which re-runs the gate.
980pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
981    let mut out = HashMap::new();
982    if commits.is_empty() {
983        return out;
984    }
985    let Some(list) = crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]) else {
986        // NOT the absent-ref case, whatever an older comment here claimed:
987        // `notes list` exits 0 with empty output when the ref does not exist,
988        // so that arrives as `Some("")` and falls through as "nothing is
989        // stamped" — correctly. Reaching HERE means git could not answer at
990        // all. Same verdict (the gates re-run: never skip work on a question
991        // we could not ask), different sentence, because a transient git
992        // failure that reads as "nothing is stamped" is indistinguishable
993        // from the real thing — which is exactly how one flaky spawn cost a
994        // day of not-diagnosing.
995        crate::hooks::common::warn(
996            "git would not list the gate stamps — every gated check will run again",
997        );
998        return out;
999    };
1000    let noted: HashSet<&str> = list
1001        .lines()
1002        .filter_map(|l| l.split_whitespace().nth(1))
1003        .collect();
1004    // Commit -> tree, in ONE spawn rather than one per commit: this is the
1005    // push path, and a `rev-parse` each would be a process per pushed
1006    // commit to answer a question `git log` answers in a batch.
1007    let mut trees: HashMap<String, String> = HashMap::new();
1008    {
1009        let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
1010        args.extend(commits.iter().map(String::as_str));
1011        if let Some(out) = crate::git::stdout(&args) {
1012            for line in out.lines() {
1013                let mut it = line.split_whitespace();
1014                if let (Some(c), Some(t)) = (it.next(), it.next()) {
1015                    trees.insert(c.to_string(), t.to_string());
1016                }
1017            }
1018        }
1019        // No mapping is not an error: every commit simply falls back to the
1020        // commit-keyed lookup below, which is what happened before trees
1021        // were stamped at all.
1022    }
1023
1024    // Declared-input stamps are keyed by fingerprint, not by tree, so a commit
1025    // whose tree carries no note can still be vouched for. Asked only when the
1026    // ref exists: a repository nothing was filed for pays one spawn. Once
1027    // stamps are filed (declared or canonical), each pushed commit pays the
1028    // few git spawns of its route.
1029    let by_inputs = inputs_ref_exists();
1030
1031    for commit in commits {
1032        // The commit's own note AND its TREE's, merged. Both are written only
1033        // for that tree (`bind_to_head` checks `HEAD^{tree}`, `stamp_push` is
1034        // handed the commit's own tree), so every token on either vouches for
1035        // exactly this content.
1036        //
1037        // Not "the commit's note, else the tree's". A squash-merge produces a
1038        // commit this machine never saw — no note — while the content, and
1039        // therefore the tree, is the one the gates ran on, and falling through
1040        // to the tree is what lets a tag push on a merged commit skip work the
1041        // branch already proved. But the same preference hid the tree's push
1042        // tokens behind a commit note after an AMEND that kept the tree:
1043        // post-commit wrote a commit note holding only the commit-time
1044        // scripts, `stamps_for` then stopped there, and the push gate ran
1045        // again for content it had already judged.
1046        //
1047        // The direction of failure is unchanged: no note on either, an
1048        // unparseable one, or a git that would not answer all mean "no
1049        // stamp", and no stamp runs the gate.
1050        let mut tokens: Vec<String> = Vec::new();
1051        let mut keys: Vec<&str> = Vec::new();
1052        if noted.contains(commit.as_str()) {
1053            keys.push(commit);
1054        }
1055        if let Some(tree) = trees.get(commit).filter(|t| noted.contains(t.as_str())) {
1056            keys.push(tree);
1057        }
1058        for key in keys {
1059            for t in note_at(key).tokens {
1060                if !tokens.contains(&t) {
1061                    tokens.push(t);
1062                }
1063            }
1064        }
1065        if by_inputs {
1066            if let Some(tree) = trees.get(commit) {
1067                for t in input_tokens(tree) {
1068                    if !tokens.contains(&t) {
1069                        tokens.push(t);
1070                    }
1071                }
1072            }
1073        }
1074        if tokens.is_empty() {
1075            continue;
1076        }
1077        out.insert(commit.clone(), tokens);
1078    }
1079    out
1080}
1081
1082/// uninstall: forget everything this module ever wrote here.
1083///
1084/// The stamps are OUR bookkeeping — unlike `hook.skip` and `amont.severity`,
1085/// which are the user's statements and are never touched.
1086pub fn forget() -> bool {
1087    let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
1088    let notes = crate::git::succeeds(&["update-ref", "-d", NOTES_FULL_REF]);
1089    let inputs = crate::git::succeeds(&["update-ref", "-d", INPUTS_FULL_REF]);
1090    let cluster = crate::git::succeeds(&["update-ref", "-d", CLUSTER_FULL_REF]);
1091    marker || notes || inputs || cluster
1092}
1093
1094/// The cluster tokens on `tree` (ADR-0016). Read only for a trusted
1095/// `platform=any` gate, so a repository with none never pays the spawn.
1096pub(crate) fn cluster_tokens(tree: &str) -> Vec<String> {
1097    note_in(CLUSTER_REF, tree).tokens
1098}
1099
1100/// Record a cluster pass: `token` on the note at `tree`, with its provenance
1101/// line. Merged, like every writer here; best-effort.
1102pub(crate) fn stamp_cluster(tree: &str, token: &str, provenance: &str) -> bool {
1103    let mut note = note_in(CLUSTER_REF, tree);
1104    note.add_tokens(&[token.to_string()]);
1105    let line = format!("{PROVENANCE} {token} {provenance}");
1106    note.provenance
1107        .retain(|l| l.split_whitespace().nth(1) != Some(token));
1108    note.provenance.push(line);
1109    write_note_in(CLUSTER_REF, tree, &note)
1110}
1111
1112/// pre-push: the tree and the cluster tokens of each of `commits`. Asked only
1113/// when a trusted `platform=any` gate is in play; a commit whose tree carries
1114/// no cluster note is absent from the map.
1115pub(crate) fn cluster_stamps_for(commits: &[String]) -> HashMap<String, (String, Vec<String>)> {
1116    let mut out = HashMap::new();
1117    for commit in commits {
1118        let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")]) else {
1119            continue;
1120        };
1121        let tokens = cluster_tokens(&tree);
1122        if !tokens.is_empty() {
1123            out.insert(commit.clone(), (tree, tokens));
1124        }
1125    }
1126    out
1127}
1128
1129/// The same, for a repository this process is not standing in.
1130pub fn forget_in(repo: &std::path::Path) -> bool {
1131    let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
1132        .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
1133    let notes = crate::git::succeeds_in(repo, &["update-ref", "-d", NOTES_FULL_REF]);
1134    let inputs = crate::git::succeeds_in(repo, &["update-ref", "-d", INPUTS_FULL_REF]);
1135    let cluster = crate::git::succeeds_in(repo, &["update-ref", "-d", CLUSTER_FULL_REF]);
1136    marker || notes || inputs || cluster
1137}
1138
1139#[cfg(test)]
1140mod tests {
1141    use super::*;
1142    use std::path::Path;
1143
1144    /// A completion answers only as long as it should (ADR-0018): a failure
1145    /// under `warn` stops answering once the gate blocks again, and a gate
1146    /// that could not run is tried again after an hour.
1147    #[test]
1148    fn a_completion_answers_only_while_it_should() {
1149        use crate::check::Severity::{Block, Warn};
1150        let now = 1_700_000_000;
1151        let word = |how| completion_word(how, "gate-tok", now);
1152        assert!(completion_answers(
1153            &word(Completion::Warned),
1154            "gate-tok",
1155            Block,
1156            now
1157        ));
1158        assert!(completion_answers(
1159            &word(Completion::FailedUnderWarn),
1160            "gate-tok",
1161            Warn,
1162            now
1163        ));
1164        assert!(!completion_answers(
1165            &word(Completion::FailedUnderWarn),
1166            "gate-tok",
1167            Block,
1168            now
1169        ));
1170        let unavailable = word(Completion::Unavailable);
1171        assert!(completion_answers(
1172            &unavailable,
1173            "gate-tok",
1174            Block,
1175            now + 3600
1176        ));
1177        assert!(!completion_answers(
1178            &unavailable,
1179            "gate-tok",
1180            Block,
1181            now + 3601
1182        ));
1183        assert!(!completion_answers(
1184            &word(Completion::Warned),
1185            "other-tok",
1186            Warn,
1187            now
1188        ));
1189    }
1190
1191    /// A real repository, because every function here is a conversation with
1192    /// git — hand-rolled fixtures would test the conversation we imagined.
1193    fn repo(name: &str) -> PathBuf {
1194        let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
1195        let _ = std::fs::remove_dir_all(&dir);
1196        std::fs::create_dir_all(&dir).unwrap();
1197        git(&dir, &["init", "-q", "--template=", "."]);
1198        git(&dir, &["config", "user.email", "t@t.test"]);
1199        git(&dir, &["config", "user.name", "t"]);
1200        dir
1201    }
1202
1203    /// A fixture git call that FAILS where it fails.
1204    ///
1205    /// This used to discard the exit status, and that is how a rare flake
1206    /// stayed unreadable for a day: if the setup `git commit` did not
1207    /// happen, the test carried on to an unborn HEAD, and the panic landed
1208    /// three lines later on a missing gate stamp — a product-shaped
1209    /// failure for a fixture-shaped cause. Same rule the checks obey:
1210    /// git failing is not git answering.
1211    fn git(dir: &Path, args: &[&str]) -> String {
1212        let out = std::process::Command::new("git")
1213            .arg("-C")
1214            .arg(dir)
1215            .args(args)
1216            .output()
1217            .expect("git");
1218        assert!(
1219            out.status.success(),
1220            "fixture: git {args:?} in {} exited {:?}: {}",
1221            dir.display(),
1222            out.status.code(),
1223            String::from_utf8_lossy(&out.stderr).trim()
1224        );
1225        String::from_utf8_lossy(&out.stdout).trim().to_string()
1226    }
1227
1228    /// The module talks to the repo at the process cwd; these tests each set
1229    /// it. Serialised via the crate-wide lock, because cwd is process-global
1230    /// and `attest`'s tests move it too.
1231    fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1232        let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1233        let prev = std::env::current_dir().unwrap();
1234        std::env::set_current_dir(dir).unwrap();
1235        let r = f();
1236        std::env::set_current_dir(prev).unwrap();
1237        r
1238    }
1239
1240    #[test]
1241    fn the_commit_note_does_not_hide_the_tree_notes_push_tokens() {
1242        let dir = repo("union");
1243        std::fs::write(dir.join("a.ts"), "x").unwrap();
1244        git(&dir, &["add", "a.ts"]);
1245        in_repo(&dir, || {
1246            record(&["test"]);
1247            git(&dir, &["commit", "-qm", "chore: a"]);
1248            bind_to_head();
1249            let head = git(&dir, &["rev-parse", "HEAD"]);
1250            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1251            // A push-time stamp lands on the TREE only (the shape a rehearsal
1252            // leaves), while the commit note keeps just the commit-time script.
1253            assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1254            assert_eq!(note_at(&head).tokens, vec!["test".to_string()]);
1255            let stamps = stamps_for(std::slice::from_ref(&head));
1256            assert_eq!(
1257                stamps.get(&head).map(Vec::as_slice),
1258                Some(&["test".to_string(), "pre-push-cargo-test".to_string()][..]),
1259                "both notes speak for the same tree"
1260            );
1261        });
1262        let _ = std::fs::remove_dir_all(&dir);
1263    }
1264
1265    /// An `unavailable` record replaces the one before it for the same gate,
1266    /// and leaves every other gate's record alone: a tree's note does not grow
1267    /// by a word per run (ADR-0018).
1268    #[test]
1269    fn an_unavailable_record_replaces_its_predecessor_only() {
1270        let dir = repo("done-unavailable");
1271        std::fs::write(dir.join("a.ts"), "x").unwrap();
1272        git(&dir, &["add", "a.ts"]);
1273        git(&dir, &["commit", "-qm", "chore: a"]);
1274        in_repo(&dir, || {
1275            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1276            let one = |t: &str| vec![t.to_string()];
1277            record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("first");
1278            record_done(&tree, &one("lint@b"), Completion::Unavailable).expect("other gate");
1279            record_done(&tree, &one("lint@b"), Completion::Warned).expect("a warning");
1280            record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("again");
1281            let words = note_in(DONE_REF, &tree).tokens;
1282            let unavailable_for = |token: &str| {
1283                words
1284                    .iter()
1285                    .filter(|w| w.starts_with("unavailable:") && w.ends_with(&format!(":{token}")))
1286                    .count()
1287            };
1288            assert_eq!(unavailable_for("suite@a"), 1, "{words:?}");
1289            assert_eq!(unavailable_for("lint@b"), 1, "{words:?}");
1290            assert!(words.contains(&"warned:lint@b".to_string()), "{words:?}");
1291        });
1292        let _ = std::fs::remove_dir_all(&dir); // a temp fixture; `repo` clears it on the next run
1293    }
1294
1295    #[test]
1296    fn a_commit_with_only_a_tree_note_still_reads_the_tree_tokens() {
1297        let dir = repo("tree-only");
1298        std::fs::write(dir.join("a.ts"), "x").unwrap();
1299        git(&dir, &["add", "a.ts"]);
1300        git(&dir, &["commit", "-qm", "chore: a"]);
1301        in_repo(&dir, || {
1302            let head = git(&dir, &["rev-parse", "HEAD"]);
1303            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1304            assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1305            let stamps = stamps_for(std::slice::from_ref(&head));
1306            assert_eq!(
1307                stamps.get(&head).map(Vec::as_slice),
1308                Some(&["pre-push-cargo-test".to_string()][..])
1309            );
1310        });
1311        let _ = std::fs::remove_dir_all(&dir);
1312    }
1313
1314    #[test]
1315    fn a_commit_with_only_a_commit_note_still_reads_its_tokens() {
1316        let dir = repo("commit-only");
1317        std::fs::write(dir.join("a.ts"), "x").unwrap();
1318        git(&dir, &["add", "a.ts"]);
1319        git(&dir, &["commit", "-qm", "chore: a"]);
1320        in_repo(&dir, || {
1321            let head = git(&dir, &["rev-parse", "HEAD"]);
1322            let mut note = Note::default();
1323            note.add_tokens(&["typecheck".to_string()]);
1324            assert!(write_note(&head, &note));
1325            let stamps = stamps_for(std::slice::from_ref(&head));
1326            assert_eq!(
1327                stamps.get(&head).map(Vec::as_slice),
1328                Some(&["typecheck".to_string()][..])
1329            );
1330        });
1331        let _ = std::fs::remove_dir_all(&dir);
1332    }
1333
1334    #[test]
1335    fn a_token_on_both_notes_is_read_once() {
1336        let dir = repo("dedup");
1337        std::fs::write(dir.join("a.ts"), "x").unwrap();
1338        git(&dir, &["add", "a.ts"]);
1339        in_repo(&dir, || {
1340            record(&["test"]);
1341            git(&dir, &["commit", "-qm", "chore: a"]);
1342            bind_to_head(); // writes `test` on the commit AND the tree
1343            let head = git(&dir, &["rev-parse", "HEAD"]);
1344            let stamps = stamps_for(std::slice::from_ref(&head));
1345            assert_eq!(
1346                stamps.get(&head).map(Vec::as_slice),
1347                Some(&["test".to_string()][..])
1348            );
1349        });
1350        let _ = std::fs::remove_dir_all(&dir);
1351    }
1352
1353    #[test]
1354    fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
1355        let dir = repo("roundtrip");
1356        std::fs::write(dir.join("a.ts"), "x").unwrap();
1357        git(&dir, &["add", "a.ts"]);
1358        in_repo(&dir, || {
1359            record(&["typecheck", "test"]);
1360            git(&dir, &["commit", "-qm", "chore: a"]);
1361            let stamped = bind_to_head();
1362            assert_eq!(
1363                stamped,
1364                vec!["typecheck".to_string(), "test".to_string()],
1365                "bind_to_head reports the scripts it stamped"
1366            );
1367            let head = git(&dir, &["rev-parse", "HEAD"]);
1368            let stamps = stamps_for(std::slice::from_ref(&head));
1369            assert_eq!(
1370                stamps.get(&head).map(Vec::as_slice),
1371                Some(&["typecheck".to_string(), "test".to_string()][..])
1372            );
1373            // One-shot: the marker is gone.
1374            // One-shot: the marker is gone. The fixture's own path, not
1375            // `marker_path()` — that helper spawns git, and a transient
1376            // spawn failure on a loaded runner reads as `None` here while
1377            // production code correctly treats it as "no marker". Seen once,
1378            // on Windows, as an unwrap panic in a sibling test.
1379            assert!(!dir.join(".git").join(MARKER).exists());
1380        });
1381        let _ = std::fs::remove_dir_all(&dir);
1382    }
1383
1384    #[test]
1385    fn a_marker_for_a_different_tree_stamps_nothing() {
1386        let dir = repo("stale");
1387        std::fs::write(dir.join("a.ts"), "x").unwrap();
1388        git(&dir, &["add", "a.ts"]);
1389        in_repo(&dir, || {
1390            record(&["typecheck"]);
1391            // The commit that actually lands carries DIFFERENT content — the
1392            // aborted-attempt-then-different-retry shape.
1393            std::fs::write(dir.join("a.ts"), "y").unwrap();
1394            git(&dir, &["add", "a.ts"]);
1395            git(&dir, &["commit", "-qm", "chore: different"]);
1396            assert!(
1397                bind_to_head().is_empty(),
1398                "bind_to_head reports nothing when the tree moved"
1399            );
1400            let head = git(&dir, &["rev-parse", "HEAD"]);
1401            assert!(
1402                stamps_for(&[head]).is_empty(),
1403                "a stale marker must not vouch"
1404            );
1405            assert!(
1406                !dir.join(".git").join(MARKER).exists(),
1407                "consumed either way"
1408            );
1409        });
1410        let _ = std::fs::remove_dir_all(&dir);
1411    }
1412
1413    #[test]
1414    fn an_empty_record_clears_a_previous_marker() {
1415        let dir = repo("clears");
1416        std::fs::write(dir.join("a.ts"), "x").unwrap();
1417        git(&dir, &["add", "a.ts"]);
1418        in_repo(&dir, || {
1419            record(&["typecheck"]);
1420            assert!(dir.join(".git").join(MARKER).exists());
1421            record(&[]);
1422            assert!(!dir.join(".git").join(MARKER).exists());
1423        });
1424        let _ = std::fs::remove_dir_all(&dir);
1425    }
1426
1427    /// The version guard's REJECT branch, fed a hand-written marker: an old
1428    /// (or future) format is ignored rather than misread — the doc's claim,
1429    /// now pinned. Every other test's markers come from record() itself and
1430    /// so always carry the current FORMAT.
1431    #[test]
1432    fn a_marker_in_an_unknown_format_stamps_nothing() {
1433        let dir = repo("wrongformat");
1434        std::fs::write(dir.join("a.ts"), "x").unwrap();
1435        git(&dir, &["add", "a.ts"]);
1436        in_repo(&dir, || {
1437            let tree = git(&dir, &["write-tree"]);
1438            let marker = dir.join(".git").join(MARKER);
1439            std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
1440            git(&dir, &["commit", "-qm", "chore: a"]);
1441            bind_to_head();
1442            let head = git(&dir, &["rev-parse", "HEAD"]);
1443            assert!(
1444                stamps_for(std::slice::from_ref(&head)).is_empty(),
1445                "an unknown format was trusted"
1446            );
1447            assert!(!marker.exists(), "consumed either way");
1448        });
1449        let _ = std::fs::remove_dir_all(&dir);
1450    }
1451
1452    /// A note somebody else wrote into OUR ref is not a stamp. Absent this,
1453    /// `git notes --ref=amont-gate add` would be a one-line way to vouch for
1454    /// an unchecked commit — the parsing trust boundary of the whole chain.
1455    #[test]
1456    fn a_foreign_note_is_not_a_stamp() {
1457        let dir = repo("foreignnote");
1458        std::fs::write(dir.join("a.ts"), "x").unwrap();
1459        git(&dir, &["add", "a.ts"]);
1460        in_repo(&dir, || {
1461            git(&dir, &["commit", "-qm", "chore: a"]);
1462            git(
1463                &dir,
1464                &[
1465                    "notes",
1466                    "--ref",
1467                    NOTES_REF,
1468                    "add",
1469                    "-m",
1470                    "typecheck test",
1471                    "HEAD",
1472                ],
1473            );
1474            let head = git(&dir, &["rev-parse", "HEAD"]);
1475            assert!(
1476                stamps_for(std::slice::from_ref(&head)).is_empty(),
1477                "a note without the format token was trusted"
1478            );
1479        });
1480        let _ = std::fs::remove_dir_all(&dir);
1481    }
1482
1483    /// An absent notes ref is `Some("")`, not `None` — the distinction the
1484    /// warning on that branch depends on. If git ever starts failing here
1485    /// instead, this test fails and the warning stops being a lie.
1486    #[test]
1487    fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
1488        let dir = repo("no-stamps");
1489        std::fs::write(dir.join("a.ts"), "x").unwrap();
1490        git(&dir, &["add", "a.ts"]);
1491        git(&dir, &["commit", "-qm", "chore: a"]);
1492        in_repo(&dir, || {
1493            assert_eq!(
1494                crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
1495                Some(""),
1496                "an absent notes ref must be an ANSWER, not a failure — the \
1497                 no-stamps path and the git-is-broken path are told apart by it"
1498            );
1499            let head = git(&dir, &["rev-parse", "HEAD"]);
1500            assert!(stamps_for(&[head]).is_empty());
1501        });
1502        let _ = std::fs::remove_dir_all(&dir);
1503    }
1504
1505    /// The compatibility promise, in both directions.
1506    ///
1507    /// A note written before evidence lines existed is ONE line, and it must
1508    /// parse to exactly the tokens it always did — every skip decision in
1509    /// this module reads that line, and a reader that needed the new shape
1510    /// would stop honouring every stamp on every machine the day it shipped.
1511    #[test]
1512    fn a_note_from_before_the_run_lines_parses_unchanged() {
1513        let note = Note::parse("amont-gate-v1 typecheck test");
1514        assert_eq!(note.tokens, vec!["typecheck", "test"]);
1515        assert!(note.runs.is_empty());
1516        // And round-trips to the same bytes, so an old amont reading a note
1517        // this one rewrote sees what it wrote.
1518        assert_eq!(note.render(), "amont-gate-v1 typecheck test");
1519    }
1520
1521    /// The new shape: line one unchanged, evidence after it.
1522    #[test]
1523    fn run_lines_are_read_without_disturbing_the_tokens() {
1524        let body = "amont-gate-v1 pre-push-cargo-test\n\
1525                    run 1726900000 pre-push-cargo-test pass 412391\n\
1526                    run 1726903600 pre-push-audit-js fail 903\n";
1527        let note = Note::parse(body);
1528        assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1529        assert_eq!(note.runs.len(), 2);
1530        assert_eq!(
1531            note.runs[0],
1532            Run {
1533                at: 1_726_900_000,
1534                gate: "pre-push-cargo-test".into(),
1535                outcome: RunOutcome::Passed,
1536                ms: 412_391,
1537            }
1538        );
1539        assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1540        assert_eq!(note.render(), body.trim_end());
1541    }
1542
1543    /// A line this version does not understand is dropped, not guessed at —
1544    /// so a future amont may add a field (or an outcome) without an older one
1545    /// inventing a meaning for it.
1546    #[test]
1547    fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
1548        let note = Note::parse(
1549            "amont-gate-v1 test\n\
1550             run 1726900000 pre-push-cargo-test pass 400\n\
1551             run tomorrow pre-push-cargo-test pass 400\n\
1552             run 1726900001 pre-push-cargo-test sideways 400\n\
1553             banana\n\
1554             run 1726900002 pre-push-cargo-test fail 500\n",
1555        );
1556        assert_eq!(note.tokens, vec!["test"]);
1557        assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
1558        assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1559    }
1560
1561    /// A deferral line (ADR-0013) round-trips, is never a token, and is not
1562    /// trimmed with the run history: more than [`MAX_RUNS`] later runs on the
1563    /// same tree must not make the push twin forget the commit deferred it.
1564    #[test]
1565    fn a_deferral_is_never_a_token_and_outlives_the_run_trim() {
1566        let mut note = Note::parse("amont-gate-v1 lint\ndeferred cargo-test\n");
1567        assert_eq!(note.tokens, vec!["lint"]);
1568        assert_eq!(note.deferred, vec!["cargo-test"]);
1569        let runs: Vec<Run> = (0..MAX_RUNS as u64 + 10)
1570            .map(|i| Run {
1571                at: 1_726_900_000 + i,
1572                gate: "pre-push-audit-js".into(),
1573                outcome: RunOutcome::Passed,
1574                ms: 1,
1575            })
1576            .collect();
1577        note.add_runs(&runs);
1578        let again = Note::parse(&note.render());
1579        assert_eq!(again.runs.len(), MAX_RUNS);
1580        assert_eq!(again.deferred, vec!["cargo-test"]);
1581        assert_eq!(again.tokens, vec!["lint"]);
1582    }
1583
1584    /// A note somebody else wrote into our ref is not evidence either. The
1585    /// token line is the trust boundary for BOTH halves of the note.
1586    #[test]
1587    fn a_foreign_note_yields_no_runs() {
1588        let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
1589        assert!(note.tokens.is_empty() && note.runs.is_empty());
1590    }
1591
1592    /// Recording evidence must never cost a stamp. `stamp_push` and
1593    /// `bind_to_head` rewrite the same note, and the first version of this
1594    /// rendered the note from its own token list — which would have erased
1595    /// every run line on the next push.
1596    #[test]
1597    fn a_stamp_and_its_evidence_survive_each_other() {
1598        let dir = repo("evidence");
1599        std::fs::write(dir.join("a.ts"), "x").unwrap();
1600        git(&dir, &["add", "a.ts"]);
1601        in_repo(&dir, || {
1602            git(&dir, &["commit", "-qm", "chore: a"]);
1603            let head = git(&dir, &["rev-parse", "HEAD"]);
1604            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1605            record_runs(
1606                &tree,
1607                &[Run {
1608                    at: 1_726_900_000,
1609                    gate: "pre-push-cargo-test".into(),
1610                    outcome: RunOutcome::Failed,
1611                    ms: 412_391,
1612                }],
1613            );
1614            // …and now a later push of the same content passes and stamps it.
1615            assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
1616            let note = note_at(&tree);
1617            assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1618            assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
1619            // The stamp still reads back as a stamp.
1620            let stamps = stamps_for(std::slice::from_ref(&head));
1621            assert_eq!(
1622                stamps.get(&head).map(Vec::as_slice),
1623                Some(&["pre-push-cargo-test".to_string()][..])
1624            );
1625        });
1626        let _ = std::fs::remove_dir_all(&dir);
1627    }
1628
1629    /// The whole point of the evidence half: it is not a stamp. A recorded
1630    /// run — even a passing one — must not let the gate be skipped, because
1631    /// skipping is decided by the token line and nothing else.
1632    #[test]
1633    fn a_recorded_run_is_not_a_stamp() {
1634        let dir = repo("not-a-stamp");
1635        std::fs::write(dir.join("a.ts"), "x").unwrap();
1636        git(&dir, &["add", "a.ts"]);
1637        in_repo(&dir, || {
1638            git(&dir, &["commit", "-qm", "chore: a"]);
1639            let head = git(&dir, &["rev-parse", "HEAD"]);
1640            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1641            record_runs(
1642                &tree,
1643                &[Run {
1644                    at: 1_726_900_000,
1645                    gate: "pre-push-cargo-test".into(),
1646                    outcome: RunOutcome::Passed,
1647                    ms: 412_391,
1648                }],
1649            );
1650            assert!(
1651                stamps_for(std::slice::from_ref(&head)).is_empty(),
1652                "a run line vouched for a gate — evidence must never gate"
1653            );
1654            assert!(
1655                !vouched_for_staged_tree().contains("pre-push-cargo-test"),
1656                "a run line vouched at commit time"
1657            );
1658            // It IS readable as history, though.
1659            let history = crate::gate_evidence::history_in(&dir);
1660            assert_eq!(history.runs.len(), 1);
1661            assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
1662        });
1663        let _ = std::fs::remove_dir_all(&dir);
1664    }
1665
1666    #[test]
1667    fn forget_removes_the_stamps() {
1668        let dir = repo("forget");
1669        std::fs::write(dir.join("a.ts"), "x").unwrap();
1670        git(&dir, &["add", "a.ts"]);
1671        in_repo(&dir, || {
1672            record(&["typecheck"]);
1673            git(&dir, &["commit", "-qm", "chore: a"]);
1674            bind_to_head();
1675            let head = git(&dir, &["rev-parse", "HEAD"]);
1676            assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
1677            forget();
1678            assert!(stamps_for(&[head]).is_empty());
1679        });
1680        let _ = std::fs::remove_dir_all(&dir);
1681    }
1682
1683    /// A squash-merge produces a commit this machine never saw, and the
1684    /// stamp has to survive it.
1685    ///
1686    /// This is the case that motivated tree-stamping. A branch is verified
1687    /// locally and stamped; the forge squashes it onto `main` as a NEW
1688    /// commit with no note; pushing a tag on that commit re-ran every gate
1689    /// the branch had already proved. Measured on this repository: 13
1690    /// seconds for the branch push, then the full suite for the tag push,
1691    /// which died on a reset connection.
1692    ///
1693    /// The tree is what the gates actually read, and it is identical across
1694    /// that merge whenever the base has not moved — five of five merges in
1695    /// one afternoon here.
1696    #[test]
1697    fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
1698        let dir = repo("squashed");
1699        std::fs::write(dir.join("a.ts"), "x").unwrap();
1700        git(&dir, &["add", "a.ts"]);
1701        in_repo(&dir, || {
1702            record(&["test"]);
1703            git(&dir, &["commit", "-qm", "feat: on a branch"]);
1704            assert_eq!(bind_to_head(), vec!["test".to_string()]);
1705            let branch_tip = git(&dir, &["rev-parse", "HEAD"]);
1706
1707            // Stand in for the forge's squash: a DIFFERENT commit object
1708            // with the SAME tree. `--amend` with a new message is the
1709            // cheapest way to get exactly that shape.
1710            git(
1711                &dir,
1712                &[
1713                    "commit",
1714                    "-q",
1715                    "--amend",
1716                    "-m",
1717                    "feat: squashed by the forge",
1718                ],
1719            );
1720            let merged = git(&dir, &["rev-parse", "HEAD"]);
1721            assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
1722            assert_eq!(
1723                git(&dir, &["rev-parse", "HEAD^{tree}"]),
1724                git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
1725                "…carrying the same tree, which is the whole premise"
1726            );
1727
1728            let stamps = stamps_for(std::slice::from_ref(&merged));
1729            assert_eq!(
1730                stamps.get(&merged).map(Vec::as_slice),
1731                Some(&["test".to_string()][..]),
1732                "the stamp must follow the content, not the commit hash"
1733            );
1734        });
1735        let _ = std::fs::remove_dir_all(&dir);
1736    }
1737
1738    /// And it must not follow anything else. A commit whose tree was never
1739    /// stamped gets nothing, however many other stamps exist — otherwise
1740    /// this widening would vouch for content nobody checked.
1741    #[test]
1742    fn a_different_tree_gets_no_stamp_from_the_fallback() {
1743        let dir = repo("othertree");
1744        std::fs::write(dir.join("a.ts"), "x").unwrap();
1745        git(&dir, &["add", "a.ts"]);
1746        in_repo(&dir, || {
1747            record(&["test"]);
1748            git(&dir, &["commit", "-qm", "chore: stamped"]);
1749            assert_eq!(bind_to_head(), vec!["test".to_string()]);
1750
1751            // Different CONTENT, so a different tree, and no marker: this
1752            // commit was never judged.
1753            std::fs::write(dir.join("b.ts"), "y").unwrap();
1754            git(&dir, &["add", "b.ts"]);
1755            git(&dir, &["commit", "-qm", "chore: unjudged"]);
1756            let unstamped = git(&dir, &["rev-parse", "HEAD"]);
1757
1758            assert!(
1759                stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
1760                "a tree nobody stamped must not inherit one"
1761            );
1762        });
1763        let _ = std::fs::remove_dir_all(&dir);
1764    }
1765
1766    // ---- declared-input reuse (`.github/attest-inputs`) -------------------
1767
1768    /// A repository declaring that gate `test` reads only `a.ts`, with one
1769    /// commit stamped `test@abc`. The plans directory is where a later,
1770    /// plan-only commit will change the tree without touching any input.
1771    fn declared(name: &str, spec: &str) -> PathBuf {
1772        let dir = repo(name);
1773        std::fs::create_dir_all(dir.join(".github")).unwrap();
1774        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1775        std::fs::write(dir.join("a.ts"), "x").unwrap();
1776        std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
1777        std::fs::write(dir.join(".github/attest-inputs"), spec).unwrap();
1778        git(&dir, &["add", "-A"]);
1779        in_repo(&dir, || {
1780            record(&["test@abc"]);
1781            git(&dir, &["commit", "-qm", "feat: judged"]);
1782            assert_eq!(bind_to_head(), vec!["test".to_string()]);
1783        });
1784        dir
1785    }
1786
1787    /// Change only the plan and commit it WITHOUT a marker: nothing was
1788    /// judged for this tree, so only the fingerprint route can speak.
1789    fn plan_only_commit(dir: &Path) -> String {
1790        std::fs::write(dir.join("docs/plans/p.md"), "plan v2, closing").unwrap();
1791        git(dir, &["add", "docs/plans/p.md"]);
1792        git(dir, &["commit", "-qm", "docs(plan): done"]);
1793        git(dir, &["rev-parse", "HEAD"])
1794    }
1795
1796    #[test]
1797    fn a_plan_only_commit_reuses_the_stamp_of_a_declared_gate() {
1798        let dir = declared("plan-only", "test a.ts\n");
1799        in_repo(&dir, || {
1800            let head = plan_only_commit(&dir);
1801            let stamps = stamps_for(std::slice::from_ref(&head));
1802            assert_eq!(
1803                stamps.get(&head).map(Vec::as_slice),
1804                Some(&["test@abc".to_string()][..]),
1805                "the closing commit changed the tree and none of the declared inputs"
1806            );
1807        });
1808        let _ = std::fs::remove_dir_all(&dir);
1809    }
1810
1811    #[test]
1812    fn the_staged_tree_of_a_plan_only_commit_is_vouched_for() {
1813        let dir = declared("staged", "test a.ts\n");
1814        in_repo(&dir, || {
1815            std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1816            git(&dir, &["add", "docs/plans/p.md"]);
1817            assert!(vouched_for_staged_tree().contains("test@abc"));
1818        });
1819        let _ = std::fs::remove_dir_all(&dir);
1820    }
1821
1822    #[test]
1823    fn partial_staging_is_judged_on_the_index_not_the_working_copy() {
1824        let dir = declared("partial", "test a.ts\n");
1825        in_repo(&dir, || {
1826            // The plan is staged; an unstaged edit to a declared input sits in
1827            // the working copy. The commit would carry only the plan.
1828            std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1829            git(&dir, &["add", "docs/plans/p.md"]);
1830            std::fs::write(dir.join("a.ts"), "unstaged edit").unwrap();
1831            assert!(vouched_for_staged_tree().contains("test@abc"));
1832
1833            // The other way round: the input IS staged, so it misses even
1834            // though the working copy was put back.
1835            std::fs::write(dir.join("a.ts"), "staged edit").unwrap();
1836            git(&dir, &["add", "a.ts"]);
1837            std::fs::write(dir.join("a.ts"), "x").unwrap();
1838            assert!(!vouched_for_staged_tree().contains("test@abc"));
1839        });
1840        let _ = std::fs::remove_dir_all(&dir);
1841    }
1842
1843    #[test]
1844    fn a_changed_declared_input_misses() {
1845        let dir = declared("input-changed", "test a.ts\n");
1846        in_repo(&dir, || {
1847            std::fs::write(dir.join("a.ts"), "changed").unwrap();
1848            git(&dir, &["add", "a.ts"]);
1849            git(&dir, &["commit", "-qm", "feat: unjudged"]);
1850            let head = git(&dir, &["rev-parse", "HEAD"]);
1851            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1852        });
1853        let _ = std::fs::remove_dir_all(&dir);
1854    }
1855
1856    #[test]
1857    fn a_changed_declaration_misses() {
1858        let dir = declared("declaration-changed", "test a.ts\n");
1859        in_repo(&dir, || {
1860            // The spec's own blob is in every fingerprint: widening what the
1861            // gate reads is a different declaration, so nothing is reused.
1862            std::fs::write(dir.join("b.ts"), "y").unwrap();
1863            std::fs::write(dir.join(".github/attest-inputs"), "test a.ts b.ts\n").unwrap();
1864            git(&dir, &["add", "-A"]);
1865            git(&dir, &["commit", "-qm", "chore: widen the declaration"]);
1866            let head = git(&dir, &["rev-parse", "HEAD"]);
1867            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1868        });
1869        let _ = std::fs::remove_dir_all(&dir);
1870    }
1871
1872    #[test]
1873    fn a_declared_config_file_is_an_input_like_any_other() {
1874        // A gate's scope lives in a tracked file (`amont.conf`). Declared, a
1875        // scope-only edit changes the fingerprint and the stamp misses.
1876        let dir = declared("config", "test a.ts amont.conf\n");
1877        in_repo(&dir, || {
1878            // `declared` ran before amont.conf existed: it is a required path,
1879            // so that first commit had no fingerprint and filed nothing.
1880            assert!(!inputs_ref_exists());
1881
1882            std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
1883            git(&dir, &["add", "amont.conf"]);
1884            record(&["test@abc"]);
1885            git(&dir, &["commit", "-qm", "chore: config"]);
1886            assert_eq!(bind_to_head(), vec!["test".to_string()]);
1887
1888            std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1889            git(&dir, &["add", "docs/plans/p.md"]);
1890            git(&dir, &["commit", "-qm", "docs(plan): done"]);
1891            let plan = git(&dir, &["rev-parse", "HEAD"]);
1892            assert!(stamps_for(std::slice::from_ref(&plan)).contains_key(&plan));
1893
1894            std::fs::write(dir.join("amont.conf"), "scope = lib\n").unwrap();
1895            git(&dir, &["add", "amont.conf"]);
1896            git(&dir, &["commit", "-qm", "chore: scope-only change"]);
1897            let scope = git(&dir, &["rev-parse", "HEAD"]);
1898            assert!(
1899                stamps_for(std::slice::from_ref(&scope)).is_empty(),
1900                "a scope-only change must miss"
1901            );
1902        });
1903        let _ = std::fs::remove_dir_all(&dir);
1904    }
1905
1906    #[test]
1907    fn a_declared_stamp_is_read_back_as_its_complete_token() {
1908        // The identity comparison lives in the readers (`pair_verdict`, the
1909        // push gate): they skip only on the complete token they compute. This
1910        // pins what the new route owes them: tokens come back verbatim, never
1911        // widened to the gate's name, and a second identity under the same key
1912        // is kept apart from the first.
1913        let dir = declared("identity", "test a.ts\n");
1914        in_repo(&dir, || {
1915            let head = plan_only_commit(&dir);
1916            let tokens = stamps_for(std::slice::from_ref(&head))
1917                .remove(&head)
1918                .unwrap_or_default();
1919            assert_eq!(tokens, vec!["test@abc".to_string()]);
1920
1921            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1922            assert!(stamp_tree(&tree, &["test@def".to_string()]));
1923            let tokens = tree_tokens(&tree);
1924            assert!(tokens.contains(&"test@abc".to_string()));
1925            assert!(tokens.contains(&"test@def".to_string()));
1926            assert!(!tokens.contains(&"test@zzz".to_string()));
1927            assert!(!tokens.contains(&"test".to_string()));
1928        });
1929        let _ = std::fs::remove_dir_all(&dir);
1930    }
1931
1932    #[test]
1933    fn a_gate_that_does_not_declare_the_manifest_is_not_offered_the_route() {
1934        // `amont.conf` is tracked but the gate's declaration omits it: a
1935        // scope-only edit would be invisible to the fingerprint, so the route
1936        // is refused outright. Nothing is filed and nothing is reused.
1937        let dir = repo("manifest-undeclared");
1938        std::fs::create_dir_all(dir.join(".github")).unwrap();
1939        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1940        std::fs::write(dir.join("a.ts"), "x").unwrap();
1941        std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
1942        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
1943        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
1944        git(&dir, &["add", "-A"]);
1945        in_repo(&dir, || {
1946            record(&["test@abc"]);
1947            git(&dir, &["commit", "-qm", "feat: judged"]);
1948            bind_to_head();
1949            assert!(!inputs_ref_exists(), "the route must not open");
1950            let head = plan_only_commit(&dir);
1951            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1952        });
1953        let _ = std::fs::remove_dir_all(&dir);
1954    }
1955
1956    #[test]
1957    fn a_gate_declaring_the_manifest_opens_the_route() {
1958        // The counterpart: with `amont.conf` among its declared inputs the
1959        // gate is filed by fingerprint again.
1960        let dir = declared("manifest-declared", "test a.ts amont.conf\n");
1961        in_repo(&dir, || {
1962            std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
1963            git(&dir, &["add", "amont.conf"]);
1964            record(&["test@abc"]);
1965            git(&dir, &["commit", "-qm", "chore: config"]);
1966            bind_to_head();
1967            assert!(inputs_ref_exists());
1968        });
1969        let _ = std::fs::remove_dir_all(&dir);
1970    }
1971
1972    #[test]
1973    fn an_undeclared_gate_keeps_whole_tree_behaviour() {
1974        let dir = declared("undeclared", "test a.ts\n");
1975        in_repo(&dir, || {
1976            // `lint` passed on the first tree but the spec declares only
1977            // `test`: the plan-only commit is a new tree for `lint`.
1978            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1979            assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
1980            let head = plan_only_commit(&dir);
1981            let tokens = stamps_for(std::slice::from_ref(&head))
1982                .remove(&head)
1983                .unwrap_or_default();
1984            assert!(tokens.contains(&"test@abc".to_string()));
1985            assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
1986        });
1987        let _ = std::fs::remove_dir_all(&dir);
1988    }
1989
1990    #[test]
1991    fn an_invalid_or_ambiguous_spec_falls_back_to_whole_tree_behaviour() {
1992        // A glob invalidates the whole spec.
1993        let dir = declared("invalid", "test src/*\n");
1994        in_repo(&dir, || {
1995            assert!(!inputs_ref_exists(), "no valid spec, nothing is filed");
1996            let head = plan_only_commit(&dir);
1997            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1998        });
1999        let _ = std::fs::remove_dir_all(&dir);
2000
2001        // Both locations present: ambiguous, the route is off.
2002        let dir = repo("ambiguous");
2003        std::fs::create_dir_all(dir.join(".github")).unwrap();
2004        std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2005        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2006        std::fs::write(dir.join("a.ts"), "x").unwrap();
2007        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2008        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2009        std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
2010        git(&dir, &["add", "-A"]);
2011        in_repo(&dir, || {
2012            record(&["test@abc"]);
2013            git(&dir, &["commit", "-qm", "feat: judged"]);
2014            bind_to_head();
2015            assert!(!inputs_ref_exists());
2016            let head = plan_only_commit(&dir);
2017            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2018        });
2019        let _ = std::fs::remove_dir_all(&dir);
2020    }
2021
2022    #[test]
2023    fn a_gate_that_did_not_pass_leaves_no_declared_input_stamp() {
2024        let dir = repo("failed");
2025        std::fs::create_dir_all(dir.join(".github")).unwrap();
2026        std::fs::write(dir.join("a.ts"), "x").unwrap();
2027        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2028        git(&dir, &["add", "-A"]);
2029        in_repo(&dir, || {
2030            // pre-commit blocked or ran nothing: an empty record, no marker.
2031            record(&[]);
2032            git(&dir, &["commit", "-qm", "feat: unjudged"]);
2033            assert!(bind_to_head().is_empty());
2034            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2035            let head = git(&dir, &["rev-parse", "HEAD"]);
2036            assert!(!stamp_push(&head, &tree, &[]));
2037            assert!(!inputs_ref_exists());
2038        });
2039        let _ = std::fs::remove_dir_all(&dir);
2040    }
2041
2042    #[test]
2043    fn stamp_tree_and_tree_tokens_use_the_inputs_ref() {
2044        let dir = declared("rehearsal", "test a.ts\n");
2045        in_repo(&dir, || {
2046            // A rehearsal proves a gate in a snapshot of this tree …
2047            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2048            assert!(stamp_tree(&tree, &["test@rehearsed".to_string()]));
2049            // … and a later tree with identical declared inputs reads it back.
2050            plan_only_commit(&dir);
2051            let later = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2052            assert_ne!(later, tree);
2053            assert!(tree_tokens(&later).contains(&"test@rehearsed".to_string()));
2054        });
2055        let _ = std::fs::remove_dir_all(&dir);
2056    }
2057
2058    #[test]
2059    fn the_inputs_ref_is_keyed_the_way_attest_keys_its_own() {
2060        let dir = declared("key", "test a.ts\n");
2061        in_repo(&dir, || {
2062            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2063            let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2064            let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2065            let key = crate::attest_inputs::input_key("test", &fp).expect("key");
2066            let listed = git(&dir, &["notes", "--ref", INPUTS_REF, "list"]);
2067            assert!(
2068                listed
2069                    .lines()
2070                    .any(|l| l.split_whitespace().nth(1) == Some(key.as_str())),
2071                "{listed}"
2072            );
2073        });
2074        let _ = std::fs::remove_dir_all(&dir);
2075    }
2076
2077    #[test]
2078    fn a_foreign_token_in_the_inputs_ref_vouches_for_nothing() {
2079        let dir = declared("foreign", "test a.ts\n");
2080        in_repo(&dir, || {
2081            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2082            let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2083            let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2084            let key = crate::attest_inputs::input_key("test", &fp).expect("key");
2085            // Somebody files a token for ANOTHER gate under `test`'s key.
2086            let mut note = note_in(INPUTS_REF, &key);
2087            note.add_tokens(&["publish@evil".to_string()]);
2088            assert!(write_note_in(INPUTS_REF, &key, &note));
2089            assert!(!tree_tokens(&tree).contains(&"publish@evil".to_string()));
2090        });
2091        let _ = std::fs::remove_dir_all(&dir);
2092    }
2093
2094    #[test]
2095    fn forget_removes_the_inputs_ref_too() {
2096        let dir = declared("forget-inputs", "test a.ts\n");
2097        in_repo(&dir, || {
2098            assert!(inputs_ref_exists());
2099            assert!(forget());
2100            assert!(!inputs_ref_exists());
2101        });
2102        let _ = std::fs::remove_dir_all(&dir);
2103    }
2104
2105    /// A repository that declares nothing: `a.ts`, a plan, and optionally an
2106    /// `amont.conf`, judged once (`test@abc`).
2107    fn canonical(name: &str, conf: Option<&str>) -> PathBuf {
2108        let dir = repo(name);
2109        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2110        std::fs::write(dir.join("a.ts"), "x").unwrap();
2111        std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
2112        if let Some(conf) = conf {
2113            std::fs::write(dir.join("amont.conf"), conf).unwrap();
2114        }
2115        git(&dir, &["add", "-A"]);
2116        in_repo(&dir, || {
2117            record(&["test@abc"]);
2118            git(&dir, &["commit", "-qm", "feat: judged"]);
2119            assert_eq!(bind_to_head(), vec!["test".to_string()]);
2120        });
2121        dir
2122    }
2123
2124    fn vouched(dir: &Path, commit: &str) -> Vec<String> {
2125        in_repo(dir, || {
2126            stamps_for(std::slice::from_ref(&commit.to_string()))
2127                .remove(commit)
2128                .unwrap_or_default()
2129        })
2130    }
2131
2132    #[test]
2133    fn with_no_spec_a_plans_only_commit_is_vouched_for_canonically() {
2134        let dir = canonical("canon-plan-edit", None);
2135        in_repo(&dir, || {
2136            assert!(inputs_ref_exists(), "the canonical stamp is filed");
2137            let head = plan_only_commit(&dir);
2138            assert_eq!(
2139                stamps_for(std::slice::from_ref(&head))
2140                    .remove(&head)
2141                    .unwrap_or_default(),
2142                vec!["test@abc".to_string()]
2143            );
2144            // The staged tree, as pre-commit judges it, is vouched for too.
2145            std::fs::write(dir.join("docs/plans/p.md"), "plan v3").unwrap();
2146            git(&dir, &["add", "docs/plans/p.md"]);
2147            assert!(vouched_for_staged_tree().contains("test@abc"));
2148        });
2149        let _ = std::fs::remove_dir_all(&dir);
2150    }
2151
2152    #[test]
2153    fn a_plan_added_deleted_or_renamed_is_not_vouched_for() {
2154        let dir = canonical("canon-plan-exists", None);
2155        std::fs::write(dir.join("docs/plans/q.md"), "second plan").unwrap();
2156        git(&dir, &["add", "docs/plans/q.md"]);
2157        git(&dir, &["commit", "-qm", "docs(plan): add"]);
2158        let added = git(&dir, &["rev-parse", "HEAD"]);
2159        assert!(vouched(&dir, &added).is_empty(), "a plan added");
2160        git(&dir, &["mv", "docs/plans/p.md", "docs/plans/r.md"]);
2161        git(&dir, &["commit", "-qm", "docs(plan): rename"]);
2162        let renamed = git(&dir, &["rev-parse", "HEAD"]);
2163        assert!(vouched(&dir, &renamed).is_empty(), "a plan renamed");
2164        let _ = std::fs::remove_dir_all(&dir);
2165    }
2166
2167    #[test]
2168    fn with_no_spec_any_other_change_is_not_vouched_for() {
2169        let dir = canonical("canon-code-edit", Some("gate test = make test\n"));
2170        std::fs::write(dir.join("a.ts"), "changed").unwrap();
2171        git(&dir, &["commit", "-qam", "feat: code"]);
2172        let code = git(&dir, &["rev-parse", "HEAD"]);
2173        assert!(vouched(&dir, &code).is_empty(), "a source edit");
2174        // amont.conf is part of the canonical tree: a scope-only edit misses.
2175        std::fs::write(dir.join("amont.conf"), "gate test = make other\n").unwrap();
2176        git(&dir, &["commit", "-qam", "chore: config"]);
2177        let conf = git(&dir, &["rev-parse", "HEAD"]);
2178        assert!(vouched(&dir, &conf).is_empty(), "a manifest edit");
2179        let _ = std::fs::remove_dir_all(&dir);
2180    }
2181
2182    #[test]
2183    fn plan_exempt_off_closes_the_canonical_route() {
2184        for (name, conf) in [
2185            ("off", "set planExempt off\n"),
2186            ("spelled", "SET  PLANEXEMPT\tOff\r\n"),
2187            ("after", "set planExempt on\nset planExempt off\n"),
2188        ] {
2189            let dir = canonical(&format!("canon-off-{name}"), Some(conf));
2190            in_repo(&dir, || {
2191                assert!(!inputs_ref_exists(), "{name}: nothing is filed");
2192                let head = plan_only_commit(&dir);
2193                assert!(
2194                    stamps_for(std::slice::from_ref(&head)).is_empty(),
2195                    "{name}: a plans-only commit is a new tree"
2196                );
2197            });
2198            let _ = std::fs::remove_dir_all(&dir);
2199        }
2200        // `on`, a trailing comment and a comment line do not opt out.
2201        for (name, conf) in [
2202            ("on", "set planExempt on\n"),
2203            ("comment", "set planExempt off # no\n"),
2204            ("commented", "# set planExempt off\n"),
2205        ] {
2206            let dir = canonical(&format!("canon-on-{name}"), Some(conf));
2207            let head = plan_only_commit(&dir);
2208            assert!(!vouched(&dir, &head).is_empty(), "{name}: still canonical");
2209            let _ = std::fs::remove_dir_all(&dir);
2210        }
2211    }
2212
2213    #[test]
2214    fn a_spec_that_cannot_be_used_means_no_canonical_stamps() {
2215        // A directory where the spec should be: listed, unreadable as a blob.
2216        let dir = repo("canon-unreadable-spec");
2217        std::fs::create_dir_all(dir.join(".github/attest-inputs")).unwrap();
2218        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2219        std::fs::write(dir.join(".github/attest-inputs/x"), "x").unwrap();
2220        std::fs::write(dir.join("a.ts"), "x").unwrap();
2221        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2222        git(&dir, &["add", "-A"]);
2223        in_repo(&dir, || {
2224            record(&["test@abc"]);
2225            git(&dir, &["commit", "-qm", "feat: judged"]);
2226            bind_to_head();
2227            assert!(!inputs_ref_exists(), "an unreadable spec opens nothing");
2228            let head = plan_only_commit(&dir);
2229            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2230        });
2231        let _ = std::fs::remove_dir_all(&dir);
2232    }
2233
2234    #[test]
2235    fn two_specs_mean_no_canonical_stamps() {
2236        let dir = repo("canon-ambiguous");
2237        std::fs::create_dir_all(dir.join(".github")).unwrap();
2238        std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2239        std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2240        std::fs::write(dir.join("a.ts"), "x").unwrap();
2241        std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2242        std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2243        std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
2244        git(&dir, &["add", "-A"]);
2245        in_repo(&dir, || {
2246            record(&["test@abc"]);
2247            git(&dir, &["commit", "-qm", "feat: judged"]);
2248            bind_to_head();
2249            assert!(!inputs_ref_exists());
2250            let head = plan_only_commit(&dir);
2251            assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2252        });
2253        let _ = std::fs::remove_dir_all(&dir);
2254    }
2255
2256    #[test]
2257    fn a_valid_spec_keeps_precedence_over_the_canonical_route() {
2258        // `lint` is not declared: it must NOT ride the canonical route.
2259        let dir = declared("canon-precedence", "test a.ts\n");
2260        in_repo(&dir, || {
2261            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2262            assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2263            let head = plan_only_commit(&dir);
2264            let tokens = stamps_for(std::slice::from_ref(&head))
2265                .remove(&head)
2266                .unwrap_or_default();
2267            assert!(tokens.contains(&"test@abc".to_string()));
2268            assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2269        });
2270        let _ = std::fs::remove_dir_all(&dir);
2271    }
2272}