Skip to main content

amont_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//! The note's key is the tree, which makes the record a per-FINGERPRINT one
64//! for free: two runs of one gate against one tree are two lines in one note,
65//! and if they disagree the gate is flaky on content that did not change.
66//!
67//! Why a notes ref and not config: notes are keyed by commit, garbage-collect
68//! with unreachable commits (an `amont.checked.<hash>` config key would
69//! outlive every rebase forever), stay local (notes refs are not pushed by
70//! default), and stay out of `git log` (only `refs/notes/commits` displays by
71//! default). `amont uninstall` deletes the ref; see `uninstall_repo_hooks`.
72
73use std::collections::{HashMap, HashSet};
74use std::path::PathBuf;
75
76/// First token of the marker file and of every note body. Versioned like
77/// `staged_only::FORMAT`: a future amont that changes the shape bumps this,
78/// and an old record is ignored rather than misread.
79pub const FORMAT: &str = "amont-gate-v1";
80
81/// The notes ref, spelled the way `git notes --ref` wants it.
82pub const NOTES_REF: &str = "amont-gate";
83
84/// The same ref, fully qualified — what `git update-ref -d` needs.
85pub const NOTES_FULL_REF: &str = "refs/notes/amont-gate";
86
87/// The marker's filename inside `$GIT_DIR`.
88const MARKER: &str = "amont-gate";
89
90/// The switch for push-time stamps — both writing them and honouring them.
91/// On by default: a stamp is amont's own record of a gate it ran on exactly
92/// this content, the same trust the commit-time stamps have always carried.
93const PUSH_STAMPS: &str = "amont.pushStamps";
94
95/// Does this repository reuse push-time stamps?
96pub fn push_stamps_enabled(settings: &crate::config::Settings) -> bool {
97    crate::config::boolean_or(settings, PUSH_STAMPS, true)
98}
99
100/// The switch for commit-time reuse — a pre-commit gate that already ran
101/// clean against exactly this staged tree is not run again. On by default,
102/// for the same reason `pushStamps` is: the record is amont's own, bound to
103/// the content, and identical content is what a test suite reads.
104const COMMIT_STAMPS: &str = "amont.commitStamps";
105
106/// Does this repository reuse a gate's verdict across commit attempts of
107/// one tree?
108pub fn commit_stamps_enabled(settings: &crate::config::Settings) -> bool {
109    crate::config::boolean_or(settings, COMMIT_STAMPS, true)
110}
111
112/// The first word of an evidence line. A line that does not start with it is
113/// not one, and is dropped rather than guessed at.
114const RUN: &str = "run";
115
116/// How many runs one note keeps, newest last. A note is read and rewritten on
117/// the push path, so it has to stay small; 64 runs of one tree is already far
118/// more retries than any content sees, and the statistics this feeds are
119/// computed ACROSS notes, not within one.
120const MAX_RUNS: usize = 64;
121
122/// How a single run of one gate ended.
123///
124/// The check vocabulary, kept whole rather than flattened to pass/fail:
125/// `Unavailable` is the outcome the fleet audit of 2026-09-19 kept finding —
126/// a gate that could not run, reported as a warning, counted by nobody — and
127/// collapsing it into "fail" would hide it all over again.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum RunOutcome {
130    Passed,
131    Failed,
132    Warned,
133    Fixed,
134    Unavailable,
135    Inert,
136    // Tree gates (ADR-0024): why a commit's tree was NOT proven. None is a
137    // verdict about the content; together they are the hit rate's misses.
138    /// No completion marker in the current cache namespace.
139    Cold,
140    /// Another run held the gate's cache lock.
141    Busy,
142    /// The tool the gate would run is not the one CI resolves.
143    Skew,
144    /// The tree was not exactly the commit's (unstaged, untracked, ignored
145    /// outside the allow-list, or an operation in progress).
146    Withheld,
147    /// Still running when the commit was ready, or past its deadline.
148    Cancelled,
149    /// Not started: its last run would not fit in this commit's cover plus
150    /// the slack.
151    Slow,
152}
153
154impl RunOutcome {
155    pub fn as_str(self) -> &'static str {
156        match self {
157            RunOutcome::Passed => "pass",
158            RunOutcome::Failed => "fail",
159            RunOutcome::Warned => "warn",
160            RunOutcome::Fixed => "fixed",
161            RunOutcome::Unavailable => "unavailable",
162            RunOutcome::Inert => "inert",
163            RunOutcome::Cold => "cold",
164            RunOutcome::Busy => "busy",
165            RunOutcome::Skew => "skew",
166            RunOutcome::Withheld => "withheld",
167            RunOutcome::Cancelled => "cancelled",
168            RunOutcome::Slow => "slow",
169        }
170    }
171
172    /// The parse side. `None` for anything unknown — a future amont may write
173    /// an outcome this one has never heard of, and inventing a meaning for it
174    /// would be worse than dropping the line.
175    pub fn parse(s: &str) -> Option<RunOutcome> {
176        Some(match s {
177            "pass" => RunOutcome::Passed,
178            "fail" => RunOutcome::Failed,
179            "warn" => RunOutcome::Warned,
180            "fixed" => RunOutcome::Fixed,
181            "unavailable" => RunOutcome::Unavailable,
182            "inert" => RunOutcome::Inert,
183            "cold" => RunOutcome::Cold,
184            "busy" => RunOutcome::Busy,
185            "skew" => RunOutcome::Skew,
186            "withheld" => RunOutcome::Withheld,
187            "cancelled" => RunOutcome::Cancelled,
188            "slow" => RunOutcome::Slow,
189            _ => return None,
190        })
191    }
192
193    /// Did this run reach a verdict about the content? Only these two are
194    /// evidence about whether a gate works — the rest are a gate declining to
195    /// judge, and counting them as passes is how a no-op looks healthy.
196    pub fn is_verdict(self) -> bool {
197        matches!(self, RunOutcome::Passed | RunOutcome::Failed)
198    }
199}
200
201/// One run of one gate: when, which, how it ended, how long it took.
202///
203/// Wall clock, in milliseconds, measured around the check's own `run` — not
204/// CPU time and not the hook's total, because the number this exists to catch
205/// is "the suite that used to take eleven minutes returned in 0.4 seconds",
206/// and that is a wall-clock claim.
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct Run {
209    /// Seconds since the epoch, as the machine that ran it saw them.
210    pub at: u64,
211    pub gate: String,
212    pub outcome: RunOutcome,
213    pub ms: u64,
214}
215
216impl Run {
217    fn render(&self) -> String {
218        format!(
219            "{RUN} {} {} {} {}",
220            self.at,
221            self.gate,
222            self.outcome.as_str(),
223            self.ms
224        )
225    }
226
227    /// `run <epoch> <gate> <outcome> <ms>`, or nothing. Every field must be
228    /// there and parse; a half-understood line is dropped whole.
229    fn parse(line: &str) -> Option<Run> {
230        let mut t = line.split_whitespace();
231        if t.next() != Some(RUN) {
232            return None;
233        }
234        let at = t.next()?.parse().ok()?;
235        let gate = t.next()?.to_string();
236        let outcome = RunOutcome::parse(t.next()?)?;
237        let ms = t.next()?.parse().ok()?;
238        Some(Run {
239            at,
240            gate,
241            outcome,
242            ms,
243        })
244    }
245}
246
247/// A parsed note body: the skip tokens, and the runs recorded against this
248/// key.
249///
250/// THE reader and THE writer of the format, so that the three callers that
251/// rewrite a note cannot each drop a half of it they were not thinking
252/// about. `stamp_push` merging tokens used to render the note from its own
253/// token list alone, which — once runs existed — would have erased every one
254/// of them on the next push.
255#[derive(Debug, Clone, Default, PartialEq, Eq)]
256pub struct Note {
257    pub tokens: Vec<String>,
258    pub runs: Vec<Run>,
259}
260
261impl Note {
262    /// Parse a note body. A first line that is not ours yields an EMPTY note:
263    /// a note somebody else wrote into our ref vouches for nothing, and its
264    /// remaining lines are not evidence either.
265    pub fn parse(body: &str) -> Note {
266        let mut lines = body.lines();
267        let Some(first) = lines.next() else {
268            return Note::default();
269        };
270        let mut tokens = first.split_whitespace();
271        if tokens.next() != Some(FORMAT) {
272            return Note::default();
273        }
274        Note {
275            tokens: tokens.map(str::to_string).collect(),
276            runs: lines.filter_map(Run::parse).collect(),
277        }
278    }
279
280    /// The bytes to hand `git notes add -m`. Line one is exactly what it has
281    /// always been, so every reader that stops there sees no change at all.
282    pub fn render(&self) -> String {
283        let mut body = format!("{FORMAT} {}", self.tokens.join(" "));
284        for run in &self.runs {
285            body.push('\n');
286            body.push_str(&run.render());
287        }
288        body
289    }
290
291    fn add_tokens(&mut self, tokens: &[String]) {
292        for t in tokens {
293            if !self.tokens.iter().any(|have| have == t) {
294                self.tokens.push(t.clone());
295            }
296        }
297    }
298
299    /// Append runs, keeping the newest [`MAX_RUNS`].
300    fn add_runs(&mut self, runs: &[Run]) {
301        self.runs.extend(runs.iter().cloned());
302        if self.runs.len() > MAX_RUNS {
303            self.runs.drain(..self.runs.len() - MAX_RUNS);
304        }
305    }
306}
307
308/// The note at `key`, parsed. An absent note, an absent ref and a git that
309/// would not answer are all an empty note — the same direction everything
310/// here fails in.
311fn note_at(key: &str) -> Note {
312    crate::git::stdout(&["notes", "--ref", NOTES_REF, "show", key])
313        .map(|body| Note::parse(&body))
314        .unwrap_or_default()
315}
316
317/// The stamp tokens on `tree` (a tree object id). Tree gates are read here
318/// and only here (ADR-0024): `tree:<name>` on the pushed tree proves the gate
319/// on exactly that content, whichever commit carried it.
320pub fn tree_tokens(tree: &str) -> Vec<String> {
321    note_at(tree).tokens
322}
323
324/// Add `tokens` to the gate note on `tree` — how a rehearsal records tree
325/// gates it proved in its snapshot of exactly that tree. Merged, never
326/// rendered from the tokens alone, so evidence already on the note survives.
327pub fn stamp_tree(tree: &str, tokens: &[String]) -> bool {
328    let mut note = note_at(tree);
329    note.add_tokens(tokens);
330    write_note(tree, &note)
331}
332
333/// Write `note` at `key`. Best-effort, like every writer here.
334fn write_note(key: &str, note: &Note) -> bool {
335    let body = note.render();
336    crate::git::succeeds(&["notes", "--ref", NOTES_REF, "add", "-f", "-m", &body, key])
337}
338
339/// Record what a gate run COST and how it ENDED, against the content it ran
340/// on.
341///
342/// Evidence only: nothing in this module reads these back to decide whether a
343/// check may be skipped, which is why recording a FAILED run — the case the
344/// stamp path deliberately has no opinion about — is safe here.
345///
346/// Best-effort and silent. A note git refused costs a row in a report nobody
347/// is blocked on; warning about it on every push would train people to ignore
348/// the warnings that do gate something.
349pub fn record_runs(key: &str, runs: &[Run]) {
350    // A gate name with whitespace in it would forge a second field on read.
351    // Refused rather than escaped: every id this repository can produce is
352    // already free of it, so the escaping would be a code path no real input
353    // ever reaches — untested by construction.
354    let runs: Vec<Run> = runs
355        .iter()
356        .filter(|r| !r.gate.is_empty() && !r.gate.contains(char::is_whitespace))
357        .cloned()
358        .collect();
359    if runs.is_empty() {
360        return;
361    }
362    let mut note = note_at(key);
363    note.add_runs(&runs);
364    let _ = write_note(key, &note);
365}
366
367/// `$GIT_DIR/amont-gate` — the worktree-PRIVATE gitdir, deliberately: the
368/// commit this marker waits for happens in this worktree. The stamps the
369/// marker becomes live in the common dir (a notes ref) and are shared.
370fn marker_path() -> Option<PathBuf> {
371    let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
372    Some(std::path::Path::new(&dir).join(MARKER))
373}
374
375/// pre-commit: record that `scripts` ran clean against the tree the commit
376/// will carry.
377///
378/// Called on EVERY pre-commit verdict, with an empty list when nothing
379/// qualifying ran (or the commit is about to be blocked) — an aborted or
380/// unchecked attempt must not inherit a previous attempt's marker.
381///
382/// Best-effort throughout: a failure to record costs one redundant gate run
383/// at push time, which is the safe direction, and a pre-commit that failed a
384/// COMMIT over bookkeeping would be the tail wagging the dog.
385pub fn record(scripts: &[&str]) {
386    let Some(path) = marker_path() else { return };
387    if scripts.is_empty() {
388        let _ = std::fs::remove_file(&path);
389        return;
390    }
391    // The index, as the object id `git commit` is about to seal. Inherits
392    // `GIT_INDEX_FILE`, so `git commit -a`'s temporary index answers here
393    // too. Pure read of the index: writes objects, touches no ref.
394    let Some(tree) = crate::git::stdout(&["write-tree"]) else {
395        // Not "nothing ran": git could not name the tree, so nothing may be
396        // vouched for. Dropping the marker is the fail-safe half (the gate
397        // re-runs at push); saying so is the half that was missing.
398        crate::hooks::common::warn(
399            "git would not name the staged tree — this commit records no gate stamp",
400        );
401        let _ = std::fs::remove_file(&path);
402        return;
403    };
404    let mut body = format!("{FORMAT}\n{tree}\n");
405    for s in scripts {
406        body.push_str(s);
407        body.push('\n');
408    }
409    let _ = std::fs::write(&path, body);
410}
411
412/// pre-commit, before a gate runs: the scripts a previous run already
413/// vouched for against the tree this commit is about to seal.
414///
415/// Two records answer, both bound to the TREE (`git write-tree` of the index
416/// under the staged-only hold — the commit's content, not the working
417/// tree):
418///
419/// 1. the one-shot marker [`record`] left behind. post-commit consumes it,
420///    so a marker that is still there belongs to an attempt that never
421///    reached post-commit — a `commit-msg` refusal, an editor closed on an
422///    empty message, a Ctrl-C at the prompt. The gates ran, the tree is the
423///    same, the verdict stands: measured on this machine, a subject three
424///    characters too long replayed a ten-minute suite for nothing.
425/// 2. the tree note [`bind_to_head`] writes — a reword, a `reset --soft` and
426///    re-commit, or a rebase that kept the tree.
427///
428/// Every failure mode reads as "nothing is vouched for", which runs the
429/// gate: no `write-tree`, a marker for another tree, a wrong format, a git
430/// that would not answer. Reuse can only ever skip a run the record proves
431/// happened on this exact content; it can never let unjudged content
432/// through — the direction every function in this module fails in.
433///
434/// Repo-controlled inputs to the gate (its command line, its scope) live in
435/// the manifest, which is part of the tree: a changed declaration is a
436/// changed tree, and nothing is reused.
437pub fn vouched_for_staged_tree() -> HashSet<String> {
438    let mut out = HashSet::new();
439    let Some(tree) = crate::git::stdout(&["write-tree"]) else {
440        return out;
441    };
442    if let Some(path) = marker_path() {
443        if let Ok(body) = std::fs::read_to_string(&path) {
444            let mut lines = body.lines();
445            if lines.next() == Some(FORMAT) && lines.next() == Some(tree.as_str()) {
446                out.extend(lines.filter(|l| !l.trim().is_empty()).map(str::to_string));
447            }
448        }
449    }
450    // The tree note: `notes show` fails loudly on an absent note, and a
451    // failure here is simply "no note" — the marker's answer stands alone.
452    // Commit-time tokens are script names; push-time ones are full ids
453    // (`pre-push-…`), which no pre-commit declaration is named after —
454    // harmless in the set. The note's `run` lines are evidence and are not
455    // tokens: `Note` keeps the two apart so nothing here can be skipped by a
456    // line that only records how long something took.
457    out.extend(note_at(&tree).tokens);
458    out
459}
460
461/// post-commit: consume the marker; stamp HEAD when the tree still matches.
462///
463/// One-shot by construction — the marker is deleted before anything is
464/// judged, so no path through here can leave it to vouch for a later commit.
465///
466/// Returns the scripts it actually stamped (empty on every no-stamp path,
467/// including a note git refused). The caller subtracts this from what the
468/// manifest declares to learn what the commit dodged — [`crate::bypass`]
469/// keeps that count. Two records, two questions: the stamp gates a check,
470/// the ledger only counts.
471pub fn bind_to_head() -> Vec<String> {
472    let Some(path) = marker_path() else {
473        return Vec::new();
474    };
475    let Ok(body) = std::fs::read_to_string(&path) else {
476        return Vec::new(); // no marker: nothing ran at pre-commit, nothing to stamp
477    };
478    let _ = std::fs::remove_file(&path);
479    let mut lines = body.lines();
480    if lines.next() != Some(FORMAT) {
481        return Vec::new();
482    }
483    let Some(tree) = lines.next() else {
484        return Vec::new();
485    };
486    let scripts: Vec<&str> = lines.filter(|l| !l.trim().is_empty()).collect();
487    if scripts.is_empty() {
488        return Vec::new();
489    }
490    let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
491        crate::hooks::common::warn(
492            "git would not name this commit's tree — no gate stamp was written",
493        );
494        return Vec::new();
495    };
496    // A different tree means this commit is not the one pre-commit judged —
497    // the marker is a dead letter from an aborted attempt.
498    if head_tree != tree {
499        return Vec::new();
500    }
501    let scripts: Vec<String> = scripts.iter().map(|s| s.to_string()).collect();
502    // The stamp goes on the TREE as well as the commit, and the tree is the
503    // one that survives the way work actually reaches `main`.
504    //
505    // A squash-merge is performed by the forge: it produces a commit nobody
506    // here ever saw, carrying no note, so a later `git push` of a tag on
507    // that commit re-ran every gate the branch had already proved. Measured
508    // on this repository: a branch push took 13 seconds and the tag push
509    // that followed took the full suite and died on a reset connection.
510    //
511    // The tree is identical across that merge whenever the base has not
512    // moved — five of five merges in one afternoon here — and identical
513    // trees are identical CONTENT, which is the only thing a test suite
514    // reads. That is the same argument `attest` makes for signing the tree
515    // rather than the commit, and this module's marker has been tree-bound
516    // since it was written; this only carries the binding through to the
517    // note.
518    //
519    // Both, not either: the commit note is what a `git log --notes` reader
520    // sees, and dropping it would make the stamps invisible in the place
521    // people look for them.
522    // MERGED into whatever is there, never rendered from the scripts alone:
523    // a pre-push run against this same tree may already have recorded
524    // evidence lines on it, and an `add -f` built from this list would erase
525    // them.
526    let mut tree_note = note_at(&head_tree);
527    tree_note.add_tokens(&scripts);
528    let _ = write_note(&head_tree, &tree_note);
529    let mut head_note = note_at("HEAD");
530    head_note.add_tokens(&scripts);
531    if !write_note("HEAD", &head_note) {
532        // A note git refused is not a stamp — and the push will re-run these
533        // checks, which is right but looks arbitrary unless it is said.
534        crate::hooks::common::warn(
535            "git refused to write the gate stamp — these checks will run again at push",
536        );
537        return Vec::new();
538    }
539    scripts
540}
541
542/// pre-push, after every block gate passed: record that `gates` passed
543/// against `tree`, the content of `commit` — MERGING with whatever the note
544/// already says, because a commit-time stamp (`test`) may already sit there
545/// and `notes add -f` would otherwise erase it.
546///
547/// Best-effort, like every writer here: a stamp that could not be written
548/// costs one redundant gate run on the next push, which is the safe
549/// direction. Returns whether the commit's note was written.
550pub fn stamp_push(commit: &str, tree: &str, gates: &[String]) -> bool {
551    if gates.is_empty() {
552        return false;
553    }
554    let mut written = false;
555    for key in [tree, commit] {
556        let mut note = note_at(key);
557        note.add_tokens(gates);
558        let ok = write_note(key, &note);
559        if key == commit {
560            written = ok;
561        }
562    }
563    if !written {
564        crate::hooks::common::warn(
565            "git refused to write the push stamp — these gates will run again on the next push",
566        );
567    }
568    written
569}
570
571/// pre-push: which of `commits` carry a stamp, and for which scripts.
572///
573/// One `notes list` narrows the reads to commits that have a note at all;
574/// absent ref, unparseable note, wrong format version — all read as "no
575/// stamp", which re-runs the gate.
576pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
577    let mut out = HashMap::new();
578    if commits.is_empty() {
579        return out;
580    }
581    let Some(list) = crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]) else {
582        // NOT the absent-ref case, whatever an older comment here claimed:
583        // `notes list` exits 0 with empty output when the ref does not exist,
584        // so that arrives as `Some("")` and falls through as "nothing is
585        // stamped" — correctly. Reaching HERE means git could not answer at
586        // all. Same verdict (the gates re-run: never skip work on a question
587        // we could not ask), different sentence, because a transient git
588        // failure that reads as "nothing is stamped" is indistinguishable
589        // from the real thing — which is exactly how one flaky spawn cost a
590        // day of not-diagnosing.
591        crate::hooks::common::warn(
592            "git would not list the gate stamps — every gated check will run again",
593        );
594        return out;
595    };
596    let noted: HashSet<&str> = list
597        .lines()
598        .filter_map(|l| l.split_whitespace().nth(1))
599        .collect();
600    // Commit -> tree, in ONE spawn rather than one per commit: this is the
601    // push path, and a `rev-parse` each would be a process per pushed
602    // commit to answer a question `git log` answers in a batch.
603    let mut trees: HashMap<String, String> = HashMap::new();
604    {
605        let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
606        args.extend(commits.iter().map(String::as_str));
607        if let Some(out) = crate::git::stdout(&args) {
608            for line in out.lines() {
609                let mut it = line.split_whitespace();
610                if let (Some(c), Some(t)) = (it.next(), it.next()) {
611                    trees.insert(c.to_string(), t.to_string());
612                }
613            }
614        }
615        // No mapping is not an error: every commit simply falls back to the
616        // commit-keyed lookup below, which is what happened before trees
617        // were stamped at all.
618    }
619
620    for commit in commits {
621        // The commit's own note first, then its TREE's. A squash-merge
622        // produces a commit this machine never saw — no note — while the
623        // content, and therefore the tree, is the one the gates ran on.
624        // Falling through to the tree is what lets a tag push on a merged
625        // commit skip work the branch already proved.
626        //
627        // The direction of failure is unchanged: no note on either, an
628        // unparseable one, or a git that would not answer all mean "no
629        // stamp", and no stamp runs the gate.
630        let key: &str = if noted.contains(commit.as_str()) {
631            commit
632        } else {
633            match trees.get(commit).filter(|t| noted.contains(t.as_str())) {
634                Some(tree) => tree,
635                None => continue,
636            }
637        };
638        let tokens = note_at(key).tokens;
639        if tokens.is_empty() {
640            continue;
641        }
642        out.insert(commit.clone(), tokens);
643    }
644    out
645}
646
647/// uninstall: forget everything this module ever wrote here.
648///
649/// The stamps are OUR bookkeeping — unlike `hook.skip` and `amont.severity`,
650/// which are the user's statements and are never touched.
651pub fn forget() -> bool {
652    let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
653    let notes = crate::git::succeeds(&["update-ref", "-d", NOTES_FULL_REF]);
654    marker || notes
655}
656
657/// The same, for a repository this process is not standing in.
658pub fn forget_in(repo: &std::path::Path) -> bool {
659    let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
660        .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
661    let notes = crate::git::succeeds_in(repo, &["update-ref", "-d", NOTES_FULL_REF]);
662    marker || notes
663}
664
665#[cfg(test)]
666mod tests {
667    use super::*;
668    use std::path::Path;
669
670    /// A real repository, because every function here is a conversation with
671    /// git — hand-rolled fixtures would test the conversation we imagined.
672    fn repo(name: &str) -> PathBuf {
673        let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
674        let _ = std::fs::remove_dir_all(&dir);
675        std::fs::create_dir_all(&dir).unwrap();
676        git(&dir, &["init", "-q", "--template=", "."]);
677        git(&dir, &["config", "user.email", "t@t.test"]);
678        git(&dir, &["config", "user.name", "t"]);
679        dir
680    }
681
682    /// A fixture git call that FAILS where it fails.
683    ///
684    /// This used to discard the exit status, and that is how a rare flake
685    /// stayed unreadable for a day: if the setup `git commit` did not
686    /// happen, the test carried on to an unborn HEAD, and the panic landed
687    /// three lines later on a missing gate stamp — a product-shaped
688    /// failure for a fixture-shaped cause. Same rule the checks obey:
689    /// git failing is not git answering.
690    fn git(dir: &Path, args: &[&str]) -> String {
691        let out = std::process::Command::new("git")
692            .arg("-C")
693            .arg(dir)
694            .args(args)
695            .output()
696            .expect("git");
697        assert!(
698            out.status.success(),
699            "fixture: git {args:?} in {} exited {:?}: {}",
700            dir.display(),
701            out.status.code(),
702            String::from_utf8_lossy(&out.stderr).trim()
703        );
704        String::from_utf8_lossy(&out.stdout).trim().to_string()
705    }
706
707    /// The module talks to the repo at the process cwd; these tests each set
708    /// it. Serialised via the crate-wide lock, because cwd is process-global
709    /// and `attest`'s tests move it too.
710    fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
711        let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
712        let prev = std::env::current_dir().unwrap();
713        std::env::set_current_dir(dir).unwrap();
714        let r = f();
715        std::env::set_current_dir(prev).unwrap();
716        r
717    }
718
719    #[test]
720    fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
721        let dir = repo("roundtrip");
722        std::fs::write(dir.join("a.ts"), "x").unwrap();
723        git(&dir, &["add", "a.ts"]);
724        in_repo(&dir, || {
725            record(&["typecheck", "test"]);
726            git(&dir, &["commit", "-qm", "chore: a"]);
727            let stamped = bind_to_head();
728            assert_eq!(
729                stamped,
730                vec!["typecheck".to_string(), "test".to_string()],
731                "bind_to_head reports the scripts it stamped"
732            );
733            let head = git(&dir, &["rev-parse", "HEAD"]);
734            let stamps = stamps_for(std::slice::from_ref(&head));
735            assert_eq!(
736                stamps.get(&head).map(Vec::as_slice),
737                Some(&["typecheck".to_string(), "test".to_string()][..])
738            );
739            // One-shot: the marker is gone.
740            // One-shot: the marker is gone. The fixture's own path, not
741            // `marker_path()` — that helper spawns git, and a transient
742            // spawn failure on a loaded runner reads as `None` here while
743            // production code correctly treats it as "no marker". Seen once,
744            // on Windows, as an unwrap panic in a sibling test.
745            assert!(!dir.join(".git").join(MARKER).exists());
746        });
747        let _ = std::fs::remove_dir_all(&dir);
748    }
749
750    #[test]
751    fn a_marker_for_a_different_tree_stamps_nothing() {
752        let dir = repo("stale");
753        std::fs::write(dir.join("a.ts"), "x").unwrap();
754        git(&dir, &["add", "a.ts"]);
755        in_repo(&dir, || {
756            record(&["typecheck"]);
757            // The commit that actually lands carries DIFFERENT content — the
758            // aborted-attempt-then-different-retry shape.
759            std::fs::write(dir.join("a.ts"), "y").unwrap();
760            git(&dir, &["add", "a.ts"]);
761            git(&dir, &["commit", "-qm", "chore: different"]);
762            assert!(
763                bind_to_head().is_empty(),
764                "bind_to_head reports nothing when the tree moved"
765            );
766            let head = git(&dir, &["rev-parse", "HEAD"]);
767            assert!(
768                stamps_for(&[head]).is_empty(),
769                "a stale marker must not vouch"
770            );
771            assert!(
772                !dir.join(".git").join(MARKER).exists(),
773                "consumed either way"
774            );
775        });
776        let _ = std::fs::remove_dir_all(&dir);
777    }
778
779    #[test]
780    fn an_empty_record_clears_a_previous_marker() {
781        let dir = repo("clears");
782        std::fs::write(dir.join("a.ts"), "x").unwrap();
783        git(&dir, &["add", "a.ts"]);
784        in_repo(&dir, || {
785            record(&["typecheck"]);
786            assert!(dir.join(".git").join(MARKER).exists());
787            record(&[]);
788            assert!(!dir.join(".git").join(MARKER).exists());
789        });
790        let _ = std::fs::remove_dir_all(&dir);
791    }
792
793    /// The version guard's REJECT branch, fed a hand-written marker: an old
794    /// (or future) format is ignored rather than misread — the doc's claim,
795    /// now pinned. Every other test's markers come from record() itself and
796    /// so always carry the current FORMAT.
797    #[test]
798    fn a_marker_in_an_unknown_format_stamps_nothing() {
799        let dir = repo("wrongformat");
800        std::fs::write(dir.join("a.ts"), "x").unwrap();
801        git(&dir, &["add", "a.ts"]);
802        in_repo(&dir, || {
803            let tree = git(&dir, &["write-tree"]);
804            let marker = dir.join(".git").join(MARKER);
805            std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
806            git(&dir, &["commit", "-qm", "chore: a"]);
807            bind_to_head();
808            let head = git(&dir, &["rev-parse", "HEAD"]);
809            assert!(
810                stamps_for(std::slice::from_ref(&head)).is_empty(),
811                "an unknown format was trusted"
812            );
813            assert!(!marker.exists(), "consumed either way");
814        });
815        let _ = std::fs::remove_dir_all(&dir);
816    }
817
818    /// A note somebody else wrote into OUR ref is not a stamp. Absent this,
819    /// `git notes --ref=amont-gate add` would be a one-line way to vouch for
820    /// an unchecked commit — the parsing trust boundary of the whole chain.
821    #[test]
822    fn a_foreign_note_is_not_a_stamp() {
823        let dir = repo("foreignnote");
824        std::fs::write(dir.join("a.ts"), "x").unwrap();
825        git(&dir, &["add", "a.ts"]);
826        in_repo(&dir, || {
827            git(&dir, &["commit", "-qm", "chore: a"]);
828            git(
829                &dir,
830                &[
831                    "notes",
832                    "--ref",
833                    NOTES_REF,
834                    "add",
835                    "-m",
836                    "typecheck test",
837                    "HEAD",
838                ],
839            );
840            let head = git(&dir, &["rev-parse", "HEAD"]);
841            assert!(
842                stamps_for(std::slice::from_ref(&head)).is_empty(),
843                "a note without the format token was trusted"
844            );
845        });
846        let _ = std::fs::remove_dir_all(&dir);
847    }
848
849    /// An absent notes ref is `Some("")`, not `None` — the distinction the
850    /// warning on that branch depends on. If git ever starts failing here
851    /// instead, this test fails and the warning stops being a lie.
852    #[test]
853    fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
854        let dir = repo("no-stamps");
855        std::fs::write(dir.join("a.ts"), "x").unwrap();
856        git(&dir, &["add", "a.ts"]);
857        git(&dir, &["commit", "-qm", "chore: a"]);
858        in_repo(&dir, || {
859            assert_eq!(
860                crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
861                Some(""),
862                "an absent notes ref must be an ANSWER, not a failure — the \
863                 no-stamps path and the git-is-broken path are told apart by it"
864            );
865            let head = git(&dir, &["rev-parse", "HEAD"]);
866            assert!(stamps_for(&[head]).is_empty());
867        });
868        let _ = std::fs::remove_dir_all(&dir);
869    }
870
871    /// The compatibility promise, in both directions.
872    ///
873    /// A note written before evidence lines existed is ONE line, and it must
874    /// parse to exactly the tokens it always did — every skip decision in
875    /// this module reads that line, and a reader that needed the new shape
876    /// would stop honouring every stamp on every machine the day it shipped.
877    #[test]
878    fn a_note_from_before_the_run_lines_parses_unchanged() {
879        let note = Note::parse("amont-gate-v1 typecheck test");
880        assert_eq!(note.tokens, vec!["typecheck", "test"]);
881        assert!(note.runs.is_empty());
882        // And round-trips to the same bytes, so an old amont reading a note
883        // this one rewrote sees what it wrote.
884        assert_eq!(note.render(), "amont-gate-v1 typecheck test");
885    }
886
887    /// The new shape: line one unchanged, evidence after it.
888    #[test]
889    fn run_lines_are_read_without_disturbing_the_tokens() {
890        let body = "amont-gate-v1 pre-push-cargo-test\n\
891                    run 1726900000 pre-push-cargo-test pass 412391\n\
892                    run 1726903600 pre-push-audit-js fail 903\n";
893        let note = Note::parse(body);
894        assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
895        assert_eq!(note.runs.len(), 2);
896        assert_eq!(
897            note.runs[0],
898            Run {
899                at: 1_726_900_000,
900                gate: "pre-push-cargo-test".into(),
901                outcome: RunOutcome::Passed,
902                ms: 412_391,
903            }
904        );
905        assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
906        assert_eq!(note.render(), body.trim_end());
907    }
908
909    /// A line this version does not understand is dropped, not guessed at —
910    /// so a future amont may add a field (or an outcome) without an older one
911    /// inventing a meaning for it.
912    #[test]
913    fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
914        let note = Note::parse(
915            "amont-gate-v1 test\n\
916             run 1726900000 pre-push-cargo-test pass 400\n\
917             run tomorrow pre-push-cargo-test pass 400\n\
918             run 1726900001 pre-push-cargo-test sideways 400\n\
919             banana\n\
920             run 1726900002 pre-push-cargo-test fail 500\n",
921        );
922        assert_eq!(note.tokens, vec!["test"]);
923        assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
924        assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
925    }
926
927    /// A note somebody else wrote into our ref is not evidence either. The
928    /// token line is the trust boundary for BOTH halves of the note.
929    #[test]
930    fn a_foreign_note_yields_no_runs() {
931        let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
932        assert!(note.tokens.is_empty() && note.runs.is_empty());
933    }
934
935    /// Recording evidence must never cost a stamp. `stamp_push` and
936    /// `bind_to_head` rewrite the same note, and the first version of this
937    /// rendered the note from its own token list — which would have erased
938    /// every run line on the next push.
939    #[test]
940    fn a_stamp_and_its_evidence_survive_each_other() {
941        let dir = repo("evidence");
942        std::fs::write(dir.join("a.ts"), "x").unwrap();
943        git(&dir, &["add", "a.ts"]);
944        in_repo(&dir, || {
945            git(&dir, &["commit", "-qm", "chore: a"]);
946            let head = git(&dir, &["rev-parse", "HEAD"]);
947            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
948            record_runs(
949                &tree,
950                &[Run {
951                    at: 1_726_900_000,
952                    gate: "pre-push-cargo-test".into(),
953                    outcome: RunOutcome::Failed,
954                    ms: 412_391,
955                }],
956            );
957            // …and now a later push of the same content passes and stamps it.
958            assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
959            let note = note_at(&tree);
960            assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
961            assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
962            // The stamp still reads back as a stamp.
963            let stamps = stamps_for(std::slice::from_ref(&head));
964            assert_eq!(
965                stamps.get(&head).map(Vec::as_slice),
966                Some(&["pre-push-cargo-test".to_string()][..])
967            );
968        });
969        let _ = std::fs::remove_dir_all(&dir);
970    }
971
972    /// The whole point of the evidence half: it is not a stamp. A recorded
973    /// run — even a passing one — must not let the gate be skipped, because
974    /// skipping is decided by the token line and nothing else.
975    #[test]
976    fn a_recorded_run_is_not_a_stamp() {
977        let dir = repo("not-a-stamp");
978        std::fs::write(dir.join("a.ts"), "x").unwrap();
979        git(&dir, &["add", "a.ts"]);
980        in_repo(&dir, || {
981            git(&dir, &["commit", "-qm", "chore: a"]);
982            let head = git(&dir, &["rev-parse", "HEAD"]);
983            let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
984            record_runs(
985                &tree,
986                &[Run {
987                    at: 1_726_900_000,
988                    gate: "pre-push-cargo-test".into(),
989                    outcome: RunOutcome::Passed,
990                    ms: 412_391,
991                }],
992            );
993            assert!(
994                stamps_for(std::slice::from_ref(&head)).is_empty(),
995                "a run line vouched for a gate — evidence must never gate"
996            );
997            assert!(
998                !vouched_for_staged_tree().contains("pre-push-cargo-test"),
999                "a run line vouched at commit time"
1000            );
1001            // It IS readable as history, though.
1002            let history = crate::gate_evidence::history_in(&dir);
1003            assert_eq!(history.runs.len(), 1);
1004            assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
1005        });
1006        let _ = std::fs::remove_dir_all(&dir);
1007    }
1008
1009    #[test]
1010    fn forget_removes_the_stamps() {
1011        let dir = repo("forget");
1012        std::fs::write(dir.join("a.ts"), "x").unwrap();
1013        git(&dir, &["add", "a.ts"]);
1014        in_repo(&dir, || {
1015            record(&["typecheck"]);
1016            git(&dir, &["commit", "-qm", "chore: a"]);
1017            bind_to_head();
1018            let head = git(&dir, &["rev-parse", "HEAD"]);
1019            assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
1020            forget();
1021            assert!(stamps_for(&[head]).is_empty());
1022        });
1023        let _ = std::fs::remove_dir_all(&dir);
1024    }
1025
1026    /// A squash-merge produces a commit this machine never saw, and the
1027    /// stamp has to survive it.
1028    ///
1029    /// This is the case that motivated tree-stamping. A branch is verified
1030    /// locally and stamped; the forge squashes it onto `main` as a NEW
1031    /// commit with no note; pushing a tag on that commit re-ran every gate
1032    /// the branch had already proved. Measured on this repository: 13
1033    /// seconds for the branch push, then the full suite for the tag push,
1034    /// which died on a reset connection.
1035    ///
1036    /// The tree is what the gates actually read, and it is identical across
1037    /// that merge whenever the base has not moved — five of five merges in
1038    /// one afternoon here.
1039    #[test]
1040    fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
1041        let dir = repo("squashed");
1042        std::fs::write(dir.join("a.ts"), "x").unwrap();
1043        git(&dir, &["add", "a.ts"]);
1044        in_repo(&dir, || {
1045            record(&["test"]);
1046            git(&dir, &["commit", "-qm", "feat: on a branch"]);
1047            assert_eq!(bind_to_head(), vec!["test".to_string()]);
1048            let branch_tip = git(&dir, &["rev-parse", "HEAD"]);
1049
1050            // Stand in for the forge's squash: a DIFFERENT commit object
1051            // with the SAME tree. `--amend` with a new message is the
1052            // cheapest way to get exactly that shape.
1053            git(
1054                &dir,
1055                &[
1056                    "commit",
1057                    "-q",
1058                    "--amend",
1059                    "-m",
1060                    "feat: squashed by the forge",
1061                ],
1062            );
1063            let merged = git(&dir, &["rev-parse", "HEAD"]);
1064            assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
1065            assert_eq!(
1066                git(&dir, &["rev-parse", "HEAD^{tree}"]),
1067                git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
1068                "…carrying the same tree, which is the whole premise"
1069            );
1070
1071            let stamps = stamps_for(std::slice::from_ref(&merged));
1072            assert_eq!(
1073                stamps.get(&merged).map(Vec::as_slice),
1074                Some(&["test".to_string()][..]),
1075                "the stamp must follow the content, not the commit hash"
1076            );
1077        });
1078        let _ = std::fs::remove_dir_all(&dir);
1079    }
1080
1081    /// And it must not follow anything else. A commit whose tree was never
1082    /// stamped gets nothing, however many other stamps exist — otherwise
1083    /// this widening would vouch for content nobody checked.
1084    #[test]
1085    fn a_different_tree_gets_no_stamp_from_the_fallback() {
1086        let dir = repo("othertree");
1087        std::fs::write(dir.join("a.ts"), "x").unwrap();
1088        git(&dir, &["add", "a.ts"]);
1089        in_repo(&dir, || {
1090            record(&["test"]);
1091            git(&dir, &["commit", "-qm", "chore: stamped"]);
1092            assert_eq!(bind_to_head(), vec!["test".to_string()]);
1093
1094            // Different CONTENT, so a different tree, and no marker: this
1095            // commit was never judged.
1096            std::fs::write(dir.join("b.ts"), "y").unwrap();
1097            git(&dir, &["add", "b.ts"]);
1098            git(&dir, &["commit", "-qm", "chore: unjudged"]);
1099            let unstamped = git(&dir, &["rev-parse", "HEAD"]);
1100
1101            assert!(
1102                stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
1103                "a tree nobody stamped must not inherit one"
1104            );
1105        });
1106        let _ = std::fs::remove_dir_all(&dir);
1107    }
1108}