Skip to main content

greengate_runtime/
dispatch.rs

1//! The two dispatchers.
2//!
3//! They are NOT the same shape, and both shapes are load-bearing:
4//!
5//! - `pre-commit` runs its checks CONCURRENTLY and reports EVERY failure.
6//!   Serial would be a visible slowdown on each commit; stopping at the first
7//!   failure would hide the rest, so you'd fix one lint error, commit, and
8//!   immediately meet the next.
9//! - `pre-push` runs them SERIALLY and stops at the FIRST failure, naming just
10//!   that check. The steps are ordered and expensive (protected branch, then
11//!   branch name, then rebase, then the whole test suite) and there is no point
12//!   running tests after a rebase conflict.
13//!
14//! Resist the tempting shared `run_all` helper — collapsing these is the
15//! obvious way to silently lose the distinction. `tests/it/dispatchers.rs` pins
16//! both.
17//!
18//! Checks are FUNCTIONS in this binary, called directly. They used to be files:
19//! `.git/hooks/pre-commit-*`, each an identical `sh` shim whose only job was to
20//! re-exec this same binary and tell it its own name. One commit therefore cost
21//! 27 processes — a shim, the binary, then 13 more shims and 13 more binaries —
22//! to do work the binary already had in a table.
23//!
24//! Deleting that removed the filename glob (order was lexicographic, so a
25//! rename could silently reorder a gate), the shebang emulation Windows needed
26//! because it cannot execute a `#!` script, and the spawn plumbing under both.
27//! Order is now a declared list in `registry`.
28
29use std::sync::Mutex;
30
31use crate::check::{Check, Outcome, Severity, Stage, Verdict};
32use crate::configured_skips;
33use crate::names::BIN;
34use crate::registry::{all_stage_checks, Ctx, Overrides};
35use crate::ui::{highlight, valid_sign, warning_sign};
36
37/// The checks for a stage, minus anything `hook.skip` filters out. Resolution
38/// goes through `names_check`, the one rule this and the severity lookup share:
39/// `git config hook.skip ruff` skips `pre-commit-ruff` by short name.
40fn selected<'a>(
41    settings: &crate::config::Settings,
42    stage: Stage,
43    manifest: &'a crate::manifest::Manifest,
44) -> Vec<&'a dyn Check> {
45    selected_during(settings, stage, &[], manifest)
46}
47
48/// Do this repository's hooks apply the CONVENTIONS, or only the safety net?
49///
50/// `git config amont.conventions declared` (usually `--global`, set by
51/// `amont enroll`) scopes the house rules to repositories that commit an
52/// `amont.conf` — the standing grant of `init.templateDir` then becomes safe
53/// to hand a whole team: a clone of somebody else's project gets conflict,
54/// secret, size and debug-leftover protection, and none of this team's
55/// opinions about commit subjects or branch names. The default,
56/// `everywhere`, keeps today's behaviour exactly.
57///
58/// Presence of the manifest is the declaration; its CONTENT stays
59/// trust-gated. Reading presence executes nothing, so no consent is needed.
60pub fn conventions_apply(
61    settings: &crate::config::Settings,
62    manifest: &crate::manifest::Manifest,
63) -> bool {
64    manifest.declared || !declared_mode(settings)
65}
66
67/// One config read per process — this sits on the hook path of every commit.
68fn declared_mode(settings: &crate::config::Settings) -> bool {
69    *settings.declared_mode.get_or_init(|| {
70        crate::config::enumerated_or(
71            settings,
72            "amont.conventions",
73            &["everywhere", "declared"],
74            "everywhere",
75        ) == "declared"
76    })
77}
78
79/// The checks for a stage, minus `hook.skip` and minus anything that declares
80/// it does not run during an operation currently in progress.
81fn selected_during<'a>(
82    settings: &crate::config::Settings,
83    stage: Stage,
84    in_progress: &[crate::check::GitState],
85    manifest: &'a crate::manifest::Manifest,
86) -> Vec<&'a dyn Check> {
87    let skips = configured_skips(settings);
88    // Externals are included here, so `hook.skip` and the severity override
89    // govern a declared command exactly as they govern a built-in. A repository
90    // that can add a check it cannot disable would be a worse deal than not
91    // being able to add one.
92    let (kept, dropped): (Vec<_>, Vec<_>) = all_stage_checks(stage, manifest)
93        .into_iter()
94        .partition(|c| !skips.iter().any(|s| crate::skip_suppresses(c.name(), s)));
95    let names: Vec<&str> = dropped.iter().map(|c| c.name()).collect();
96    announce_skips(settings, &names);
97
98    // Announced separately from `hook.skip`, and with the operation named: "not
99    // during a rebase" is a property of the moment and will be true again in a
100    // minute, which is a different thing to tell a reader than "you disabled
101    // this".
102    let (kept, paused): (Vec<_>, Vec<_>) = kept.into_iter().partition(|check| {
103        !check
104            .scope()
105            .not_during
106            .iter()
107            .any(|state| in_progress.contains(state))
108    });
109    if !paused.is_empty() {
110        let what = in_progress
111            .iter()
112            .map(|s| s.as_str())
113            .collect::<Vec<_>>()
114            .join(" and ");
115        println!(
116            "{} {} check(s) paused during {what}: {}",
117            warning_sign(),
118            paused.len(),
119            paused
120                .iter()
121                .map(|c| c.name())
122                .collect::<Vec<_>>()
123                .join(", ")
124        );
125    }
126
127    // The conventions split, last: a held-back check was neither skipped (a
128    // choice about THIS repository) nor paused (a property of the moment) —
129    // this repository simply never subscribed. One line, count not names:
130    // in the clone-of-somebody-else's-project case this prints on every
131    // commit, and fifteen names every time is how a safety message becomes
132    // scroll-past noise.
133    if conventions_apply(settings, manifest) {
134        return kept;
135    }
136    let (kept, held): (Vec<_>, Vec<_>) = kept
137        .into_iter()
138        .partition(|check| check.reach() == crate::check::Reach::Safety);
139    if !held.is_empty() {
140        println!(
141            "{} {} convention check(s) held back — no amont.conf here and \
142             amont.conventions is `declared`; the safety net still runs",
143            warning_sign(),
144            held.len(),
145        );
146    }
147    kept
148}
149
150/// The key that turns evidence ordering on. `declared` — the registry's
151/// order, the one this file's header argues for — is the default and nothing
152/// about it changes.
153const ORDER: &str = "amont.order";
154
155/// How far back [`crate::gate_evidence::order_by_evidence`] looks. Not a
156/// config key: it is an input to an ordering that changes nothing about what
157/// runs, and a knob nobody can predict the effect of is a knob that invites
158/// cargo-culting. Ninety days is the same window the report defaults to, so
159/// the ordering a push takes is the ordering `amont-fleet gates` explains.
160const ORDER_WINDOW_DAYS: u64 = 90;
161
162/// Does this repository want its push gates ordered by what the record says?
163fn evidence_ordering(settings: &crate::config::Settings) -> bool {
164    crate::config::enumerated_or(settings, ORDER, &["declared", "evidence"], "declared")
165        == "evidence"
166}
167
168/// Reorder the SCOPED push gates — the suites and audits — by the local
169/// record, leaving everything else exactly where the registry put it.
170///
171/// Two halves, and the split is the safety property. The unscoped pre-push
172/// checks ask about the PUSH — is this branch protected, is the name legal,
173/// is the branch behind, is there a secret in it — and the registry orders
174/// them "cheapest and most decisive first" for a reason: discovering a
175/// protected branch after twenty minutes of tests is precisely the waste this
176/// feature exists to remove, and promoting a suite above them would
177/// reintroduce it. So they keep their positions absolutely.
178///
179/// The scoped gates are permuted among the positions they already occupy.
180/// Nothing is added, removed or skipped — [`crate::gate_evidence`] argues
181/// that at length — and with no history the permutation is the identity.
182fn ordered_by_evidence<'a>(
183    settings: &crate::config::Settings,
184    checks: Vec<&'a dyn Check>,
185) -> Vec<&'a dyn Check> {
186    if !evidence_ordering(settings) || checks.len() < 2 {
187        return checks;
188    }
189    let slots: Vec<usize> = checks
190        .iter()
191        .enumerate()
192        .filter(|(_, c)| !c.scope().is_unscoped())
193        .map(|(i, _)| i)
194        .collect();
195    if slots.len() < 2 {
196        return checks;
197    }
198    let names: Vec<String> = slots
199        .iter()
200        .map(|&i| checks[i].name().to_string())
201        .collect();
202    let history = crate::gate_evidence::history_in(std::path::Path::new("."));
203    if history.is_empty() {
204        return checks;
205    }
206    let order = crate::gate_evidence::order_by_evidence(
207        &names,
208        &history,
209        crate::gate_evidence::now(),
210        ORDER_WINDOW_DAYS,
211    );
212    let mut out = checks.clone();
213    for (slot, &pick) in slots.iter().zip(&order) {
214        out[*slot] = checks[slots[pick]];
215    }
216    if out
217        .iter()
218        .map(|c| c.name())
219        .ne(checks.iter().map(|c| c.name()))
220    {
221        crate::say!(
222            "{} gate order from this repository's own record: {}",
223            valid_sign(),
224            slots
225                .iter()
226                .map(|&i| out[i].name())
227                .collect::<Vec<_>>()
228                .join(", ")
229        );
230    }
231    out
232}
233
234/// Say out loud which checks did not run.
235///
236/// A skip is otherwise invisible at exactly the moment it matters. With
237/// `hook.skip = merge-conflict` set, a commit printed six green ticks and no
238/// hint that a seventh check had been disabled — the developer sees a clean run
239/// and concludes they are covered.
240///
241/// It is worse than it sounds, because one value can silence a whole stage:
242/// `hook.skip = pre-commit` suppresses all fifteen. That is now something
243/// somebody meant rather than the accident it once was — `e` used to cost
244/// twenty by substring reach — but a commit under it still looks exactly like a
245/// commit that had nothing to report.
246///
247/// One line, only when something was actually skipped, so a normal commit is
248/// unchanged. This reaches every skip however it was created — hand-edited
249/// config included — which no dashboard can claim.
250fn announce_skips(settings: &crate::config::Settings, dropped: &[&str]) {
251    if dropped.is_empty() {
252        return;
253    }
254    // Two lines, not one: "you decided this" (hook.skip on this machine)
255    // and "your team decided this" (a skip line in the committed
256    // amont.conf) are different things to be told — the same reason paused
257    // and held-back get their own sentences. A name both sources suppress
258    // is announced as the machine's: the local decision is the nearer one.
259    let (machine, _policy) = crate::skips_by_source(settings);
260    let (yours, theirs): (Vec<&&str>, Vec<&&str>) = dropped
261        .iter()
262        .partition(|name| machine.iter().any(|s| crate::skip_suppresses(name, s)));
263    let say = |names: &[&&str], via: &str| {
264        if names.is_empty() {
265            return;
266        }
267        let plural = if names.len() == 1 { "check" } else { "checks" };
268        println!(
269            "{} {} {plural} skipped by {}: {}",
270            warning_sign(),
271            names.len(),
272            highlight(via),
273            names.iter().map(|n| **n).collect::<Vec<_>>().join(", ")
274        );
275    };
276    say(&yours, "hook.skip");
277    say(&theirs, "amont.conf");
278}
279
280/// Say, once per stage, what the manifest's policy could not do — withheld
281/// behind trust, or aiming at names that exist nowhere. Policy that silently
282/// does not apply is a silent behaviour change, which is the one kind this
283/// codebase does not allow itself.
284fn announce_policy_state(settings: &crate::config::Settings, manifest: &crate::manifest::Manifest) {
285    if let Some(why) = manifest.policy_withheld {
286        println!(
287            "{} {} policy not applied: {why}",
288            warning_sign(),
289            highlight(crate::manifest::MANIFEST),
290        );
291    }
292    for note in &manifest.policy_notes {
293        println!("{} {}", warning_sign(), note);
294    }
295    // The version floor rides the same two call sites: once per stage,
296    // beside the other "this repository expects something you lack" lines.
297    crate::skew::announce_minimum(settings);
298}
299
300/// Run every item concurrently and collect `(name, code)` in the INPUT order.
301///
302/// Extracted so the concurrency itself can be tested with a rendezvous instead
303/// of a stopwatch — an earlier wall-clock test was flaky the moment the machine
304/// was busy, and a threshold that trips under load teaches you to ignore it.
305fn run_concurrently<T, R, F>(items: &[T], run: F, if_thread_died: R) -> Vec<R>
306where
307    T: Sync,
308    R: Send + Sync + Clone,
309    F: Fn(&T) -> R + Sync,
310{
311    let slots: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
312    std::thread::scope(|scope| {
313        for (item, slot) in items.iter().zip(&slots) {
314            let run = &run;
315            let died = &if_thread_died;
316            scope.spawn(move || {
317                // CAUGHT, not propagated. `thread::scope` re-raises a child
318                // panic in the parent, which would abort the whole hook with a
319                // backtrace and throw away the other nineteen checks' results —
320                // and would make `if_thread_died` unreachable, which is what it
321                // was until this test existed to notice.
322                let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(item)))
323                    .unwrap_or_else(|_| died.clone());
324                *slot.lock().expect("poisoned") = Some(outcome);
325            });
326        }
327    });
328    slots
329        .into_iter()
330        .map(|s| {
331            s.into_inner()
332                .expect("poisoned")
333                .unwrap_or_else(|| if_thread_died.clone())
334        })
335        .collect()
336}
337
338/// Take the index-fidelity hold, or say why the caller must stop.
339///
340/// Extracted from `pre_commit` so that `amont run` — which its own doc
341/// comment calls "a rehearsal of the hook" — can take exactly the same hold
342/// rather than judging the working tree while a real commit judges the index.
343///
344/// Around the WHOLE fan-out, not per check: twenty checks run concurrently and
345/// would fight over one working tree.
346fn hold_unstaged() -> Result<crate::staged_only::StagedOnly, Verdict> {
347    // BEFORE `enter()`, not after: `enter()` is what checks out the tree and
348    // parks the unstaged half, and a signal landing in the gap between that
349    // and the handler being armed would hit the default disposition — dead
350    // process, tree left checked out, nothing restored. The handler no-ops
351    // harmlessly on a signal that arrives before there is anything held.
352    crate::staged_only::install_signal_handler();
353    match crate::staged_only::StagedOnly::enter() {
354        Ok(guard) => Ok(guard),
355        Err(e) => {
356            // Refusing to check the wrong content is the safe direction; a
357            // check that read the tree would be answering about a commit
358            // nobody is making.
359            eprintln!("{e}");
360            Err(Verdict::Block)
361        }
362    }
363}
364
365pub fn pre_commit(ctx: &Ctx) -> Verdict {
366    let settings = ctx.settings;
367    // A detached rehearsal's passes become cluster tokens before any gate
368    // asks for one (ADR-0017). Costs one `stat` when nothing is pending, and
369    // nothing in a repository that declares no `platform=any` gate.
370    crate::cluster::collect_if_declared(ctx.manifest);
371    // Before anything runs: a pinned tool at the wrong version makes every
372    // verdict below it suspect, and the warning costs one --version per pin.
373    crate::manifest::verify_tool_pins(&ctx.manifest.pins);
374    announce_policy_state(ctx.settings, ctx.manifest);
375    let in_progress = crate::git_states_in_progress();
376    let checks = selected_during(ctx.settings, Stage::PreCommit, &in_progress, ctx.manifest);
377
378    // Tree gates (ADR-0024): judged BEFORE the hold, which is the only moment
379    // unstaged edits are visible; started AFTER it, so they lint the commit's
380    // tree. They never decide the commit.
381    let tree_gates = if ctx.manifest.tree.is_empty() || !crate::tree_lint::enabled(settings) {
382        None
383    } else {
384        match crate::tree_lint::guard(settings) {
385            Some(why) => {
386                crate::hooks::common::say("  tree lint not proven — CI will lint:");
387                crate::hooks::common::say(&crate::tree_lint::fit_line("    ", &why, ""));
388                crate::tree_lint::note_withheld(&ctx.manifest.tree);
389                None
390            }
391            None => Some(&ctx.manifest.tree),
392        }
393    };
394
395    let held = match hold_unstaged() {
396        Ok(guard) => guard,
397        Err(verdict) => return verdict,
398    };
399
400    let root = crate::hooks::common::repo_root();
401    // How long this commit's own declared checks are expected to run — the
402    // cover a tree gate can hide behind — from their last measured runs.
403    let decls =
404        crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals);
405    // Only declarations whose scope this commit touches RUN; the others
406    // return at once, and their duration says nothing about cover.
407    let staged = if ctx.manifest.tree.is_empty() {
408        Vec::new()
409    } else {
410        crate::hooks::common::staged_files(&[])
411    };
412    // A declaration in scope that was never measured is UNKNOWN cover, and
413    // unknown means run: the run teaches both numbers, exactly as an unknown
414    // gate time does. Guessing 0 would skip the one commit that could learn.
415    let cover_ms = if tree_gates.is_some() {
416        decls
417            .iter()
418            .filter(|d| d.scope.touches(&staged))
419            .map(|d| crate::tree_cache::duration_of(&d.id).unwrap_or(u64::MAX))
420            .max()
421            .unwrap_or(0)
422    } else {
423        0
424    };
425    let side_car = tree_gates.and_then(|g| {
426        crate::tree_lint::start(
427            settings,
428            std::path::Path::new(&root),
429            g,
430            &ctx.manifest.pins,
431            cover_ms,
432        )
433    });
434
435    let severities = Overrides::read(settings);
436    // Resolved once and handed down (ADR-0020): the stage and the wave
437    // ledger below ask the same question, and each read of a git setting is
438    // a spawn the commit's budget counts (`spawn_budget.rs`).
439    let waves = Waves::resolve(settings);
440    let (verdict, outcomes, durations) =
441        run_stage_traced(settings, &checks, ctx, &severities, waves);
442    // Remember how long the declared checks that judged something took, for
443    // the next commit's cover estimate.
444    if !ctx.manifest.tree.is_empty() {
445        let measured: Vec<(String, u64)> = checks
446            .iter()
447            .zip(outcomes.iter().zip(&durations))
448            .filter(|(c, (o, _))| {
449                matches!(o, Outcome::Passed | Outcome::Failed)
450                    && decls
451                        .iter()
452                        .any(|d| d.id == c.name() && d.scope.touches(&staged))
453            })
454            .map(|(c, (_, ms))| (c.name().to_string(), *ms))
455            .collect();
456        crate::tree_cache::record_durations(&measured);
457    }
458
459    // The wave ledger (ADR-0020): how long the Light wave held the Heavy one
460    // back, and what a blocking Light failure skipped. Hook only, never
461    // `amont run`, like the downgrade ledger below.
462    if waves == Waves::LightThenHeavy {
463        let light_ms = checks
464            .iter()
465            .zip(&durations)
466            .filter(|(c, _)| !is_heavy(**c))
467            .map(|(_, ms)| *ms)
468            .max()
469            .unwrap_or(0);
470        let skipped: Vec<&str> = checks
471            .iter()
472            .zip(&outcomes)
473            .filter(|(_, o)| **o == Outcome::Skipped)
474            .map(|(c, _)| c.name())
475            .collect();
476        // Heavy checks this change reached that judged something, or would
477        // have: clippy on a `.txt`-only commit returns `Passed` having judged
478        // nothing, and one that came back `Inert`, `Unavailable` or `Deferred`
479        // waited for nothing either. A commit with none writes no line, and
480        // spends no git spawn on the ledger's path (`spawn_budget.rs`). The
481        // staged list is the stage's own, cached; the tracked list is read
482        // only for a Heavy check this change touched (`would_judge` asks it
483        // only then), so an ordinary commit pays nothing here.
484        let staged = crate::hooks::common::staged_files(&[]);
485        let heavy_checks = checks
486            .iter()
487            .zip(&outcomes)
488            .filter(|(c, o)| is_heavy(**c) && o.judged_or_skipped())
489            .filter(|(c, _)| c.scope().touches(&staged))
490            .filter(|(c, _)| {
491                c.would_judge(&staged, crate::hooks::common::tracked_files().as_deref())
492            })
493            .count();
494        crate::waves::note(light_ms, heavy_checks, &skipped);
495    }
496
497    // The shadow-mode ledger. Silent, best-effort, and never consulted by any
498    // verdict — see `crate::downgrade`.
499    crate::downgrade::note(
500        settings,
501        &downgraded_events(&checks, &outcomes, &severities),
502    );
503
504    // What post-commit will bind to the commit: the gate-declared checks
505    // that RAN clean, recorded while the index still is the commit's tree.
506    // Called on every verdict — an empty record clears any leftover marker,
507    // so a blocked attempt (or a repo with nothing declared) cannot leave an
508    // earlier attempt's marker to vouch for the next commit. `Unavailable`
509    // deliberately does not qualify: a check whose tool is missing judged
510    // nothing, and stamping it would be the paper promise this exists to
511    // replace.
512    // EVERY blocking declaration, not only the npm GATE names: a custom
513    // `pre-commit check … block …` earns its stamp the same way, and a
514    // same-named pre-push declaration defers to it (see `pair_verdict`).
515    let ran: Vec<String> = if matches!(verdict, Verdict::Block) {
516        Vec::new()
517    } else {
518        crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals)
519            .into_iter()
520            .filter(|d| {
521                checks
522                    .iter()
523                    .zip(&outcomes)
524                    .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Passed | Outcome::Fixed))
525            })
526            // A pass the cluster proved is recorded in its own ref and never
527            // becomes a local token (ADR-0016).
528            .filter(|d| !crate::cluster::proved_on_index(&d.id))
529            // The token, not the bare script: a skip is honoured only for the
530            // same command run by the same program (`gate_identity`). A
531            // declaration whose program cannot be identified earns no stamp.
532            .filter_map(|d| {
533                ctx.manifest
534                    .externals
535                    .iter()
536                    .find(|e| e.id == d.id)
537                    .and_then(|e| crate::gate_identity::external_token(e, &d.script))
538            })
539            .collect()
540    };
541    // A rewrite means the tree the gates linted is not the one committed.
542    let stampable =
543        !matches!(verdict, Verdict::Block) && !outcomes.iter().any(|o| matches!(o, Outcome::Fixed));
544    let mut ran = ran;
545    if let Some(car) = side_car {
546        ran.extend(crate::tree_lint::finish(settings, car, stampable));
547    }
548    let ran: Vec<&str> = ran.iter().map(String::as_str).collect();
549    crate::gate_stamp::record(&ran);
550    // The blocking declarations the busy policy deferred, by script name, on
551    // the staged tree (the commit's, under the hold): pre-push reads them to
552    // defer the push twin too (ADR-0013). Never a token: nothing is stamped.
553    let deferred: Vec<String> =
554        crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals)
555            .into_iter()
556            .filter(|d| {
557                checks
558                    .iter()
559                    .zip(&outcomes)
560                    .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Deferred))
561            })
562            .map(|d| d.script)
563            .collect();
564    if !deferred.is_empty() {
565        if let Some(tree) = crate::git::stdout(&["write-tree"]) {
566            crate::gate_stamp::record_deferred(&tree, &deferred);
567        }
568    }
569    // Under the hold, the index IS the commit's tree: its evidence goes there.
570    if !ctx.manifest.tree.is_empty() {
571        if let Some(tree) = crate::git::stdout(&["write-tree"]) {
572            crate::tree_lint::flush_evidence(&tree);
573        }
574    }
575
576    drop(held);
577    verdict
578}
579
580/// The checks that FAILED without blocking, each with why — the shadow-mode
581/// signal [`crate::downgrade`] keeps.
582///
583/// Derived at the hook entry points and deliberately NOT inside
584/// [`run_stage_traced`], which is where `classify` already computes the same
585/// set. `run_all` reaches that function too, so recording there would let
586/// every `amont run` rehearsal inflate a ledger a lead is going to read as a
587/// count of real commits — and `run --all-files` over a dirty tree would add
588/// dozens of events for content nobody is committing.
589///
590/// A check that DECLARES `warn` is counted but is not evidence about a
591/// rollout: it was never going to block, so calling it "would have blocked"
592/// would inflate the one number the whole feature exists to produce. Only an
593/// override of a blocking check earns that.
594fn downgraded_events(
595    checks: &[&dyn Check],
596    outcomes: &[Outcome],
597    severities: &Overrides,
598) -> Vec<(String, crate::downgrade::Origin)> {
599    checks
600        .iter()
601        .zip(outcomes)
602        .filter(|(_, o)| matches!(o, Outcome::Failed))
603        .filter(|(c, _)| matches!(severities.of(**c), Severity::Warn))
604        .map(|(c, _)| (c.name().to_string(), downgrade_origin(*c, severities)))
605        .collect()
606}
607
608/// Why this check did not block. Shared, because `pre_push` fail-fasts and
609/// never builds an outcomes vector to hand to [`downgraded_events`].
610fn downgrade_origin(check: &dyn Check, severities: &Overrides) -> crate::downgrade::Origin {
611    use crate::downgrade::Origin;
612    use crate::registry::Source;
613    if matches!(check.severity(), Severity::Warn) {
614        return Origin::Declared;
615    }
616    match severities.applied_with_source(check.name()) {
617        Some((_, _, Source::Config)) => Origin::Config,
618        Some((_, _, Source::Policy)) => Origin::Policy,
619        // Declared `block`, resolved `warn`, and nothing claims to have
620        // overridden it: a contradiction. Count it, but not as evidence — the
621        // conservative direction for a number whose only failure mode is
622        // being too alarming.
623        None => Origin::Declared,
624    }
625}
626
627/// The pre-commit body, over the checks it is GIVEN.
628///
629/// A seam, so a test can hand it a check that panics. Without it the value
630/// standing in for a dead check was a literal at one call site that no test
631/// could reach — the rule was asserted on the runner and merely hoped for here.
632fn run_stage(checks: &[&dyn Check], ctx: &Ctx, severities: &Overrides) -> Verdict {
633    let settings = ctx.settings;
634    run_stage_traced(settings, checks, ctx, severities, Waves::resolve(settings)).0
635}
636
637/// [`run_stage`], keeping the per-check outcomes — index-aligned with
638/// `checks` — alive past the verdict. `pre_commit` needs them to know which
639/// gate-declared checks actually ran (`gate_stamp`); `Report` cannot answer
640/// that, because `classify` deliberately drops the names of `Passed`.
641fn run_stage_traced(
642    settings: &crate::config::Settings,
643    checks: &[&dyn Check],
644    ctx: &Ctx,
645    severities: &Overrides,
646    waves: Waves,
647) -> (Verdict, Vec<Outcome>, Vec<u64>) {
648    if checks.is_empty() {
649        return (Verdict::Proceed, Vec::new(), Vec::new());
650    }
651    // One slot per check: everything a check says lands in its own buffer
652    // and reaches stdout as ONE block when it finishes — see `live`. Off
653    // (`amont.progress false`), no sink is ever installed and every print
654    // streams exactly as it always did.
655    let stage = crate::live::enabled(settings).then(|| {
656        let names: Vec<&str> = checks.iter().map(|c| c.name()).collect();
657        crate::live::Stage::begin(settings, &names)
658    });
659    let items: Vec<(usize, &&dyn Check)> = checks.iter().enumerate().collect();
660    let run_one = |(idx, check): &(usize, &&dyn Check)| -> (Outcome, u64) {
661        let started = std::time::Instant::now();
662        let _sink = stage.as_ref().map(|s| s.enter(*idx));
663        // The block is emitted however the check leaves — a panicking
664        // check's partial output still reaches the reader, above the
665        // dead-check verdict `run_concurrently` fills in.
666        let flush = stage
667            .as_ref()
668            .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, *idx));
669        let sub = Ctx {
670            name: check.name(),
671            args: ctx.args,
672            hooks_dir: ctx.hooks_dir,
673            push: ctx.push,
674            manifest: ctx.manifest,
675            settings: ctx.settings,
676            handed_to_cluster: ctx.handed_to_cluster,
677            land: ctx.land,
678            audits: ctx.audits,
679            source_worktree: ctx.source_worktree,
680        };
681        let slot = enter(**check, || severities.of(**check));
682        let outcome = deferred_or(&slot, check.run(&sub));
683        if let Some(f) = &flush {
684            f.outcome(outcome);
685        }
686        // The record measures the check, not its wait for a host slot.
687        let ran = started.elapsed().saturating_sub(slot.queued());
688        let ms = u64::try_from(ran.as_millis()).unwrap_or(u64::MAX);
689        (outcome, ms)
690    };
691    // A check whose thread died has not passed. Stated here, where the slot
692    // is filled, rather than hidden in a `Default` impl that every future
693    // `#[derive(Default)]` would silently inherit.
694    let died = (Outcome::Failed, 0);
695    let timed = match waves {
696        Waves::LightThenHeavy => in_waves(&items, &run_one, died, severities),
697        Waves::One => run_concurrently(&items, run_one, died),
698    };
699    let (outcomes, durations): (Vec<Outcome>, Vec<u64>) = timed.into_iter().unzip();
700
701    let report = classify(checks, &outcomes, severities);
702    announce(settings, &report);
703    (report.verdict(), outcomes, durations)
704}
705
706/// How a pre-commit stage runs its checks (ADR-0020).
707#[derive(Debug, Clone, Copy, PartialEq, Eq)]
708enum Waves {
709    /// Every check at once, as before 2.1 (`amont.failFast false`).
710    One,
711    /// The Light checks, then the Heavy ones only if none blocked.
712    LightThenHeavy,
713}
714
715impl Waves {
716    /// `AMONT_FAIL_FAST` for one run, then `amont.failFast` (git config, then
717    /// a trusted `set failFast` in `amont.conf`), then on. Read once by the
718    /// caller and handed down, never cached behind the settings it takes.
719    fn resolve(settings: &crate::config::Settings) -> Waves {
720        if resolve_fail_fast(std::env::var(FAIL_FAST_ENV).ok().as_deref(), settings) {
721            Waves::LightThenHeavy
722        } else {
723            Waves::One
724        }
725    }
726}
727
728/// Heavy checks take a host slot and run in the second wave (ADR-0009,
729/// ADR-0020); everything else is Light.
730fn is_heavy(check: &dyn Check) -> bool {
731    check.weight() == crate::host_slots::Weight::Heavy
732}
733
734const FAIL_FAST_ENV: &str = "AMONT_FAIL_FAST";
735
736/// [`Waves::resolve`] with the environment value handed in: the testable seam,
737/// because setting a variable in a threaded test binary races its siblings.
738fn resolve_fail_fast(from_env: Option<&str>, settings: &crate::config::Settings) -> bool {
739    match from_env
740        .filter(|v| !v.is_empty())
741        .map(str::to_ascii_lowercase)
742        .as_deref()
743    {
744        Some("true" | "1" | "yes" | "on") => true,
745        Some("false" | "0" | "no" | "off") => false,
746        Some(other) => {
747            crate::config::complain(
748                FAIL_FAST_ENV,
749                &format!("{other:?} is not true or false"),
750                "amont.failFast",
751            );
752            crate::config::boolean_or(settings, "amont.failFast", true)
753        }
754        None => crate::config::boolean_or(settings, "amont.failFast", true),
755    }
756}
757
758/// The stage in two waves (ADR-0020): every Light check at once, then — only
759/// if none of them FAILED at a blocking severity — every Heavy check at once.
760/// A Heavy check the first wave condemned never starts: it takes no host
761/// slot, earns no stamp, and comes back `Skipped`. Results stay index-aligned
762/// with `items`, as `run_concurrently`'s do.
763///
764/// Waves, not cancellation: the check runner kills only a tool's direct child
765/// (`wait_within`), so stopping a running `cargo test` would orphan its test
766/// binaries. A wave that never starts needs no kill.
767fn in_waves<'a, F>(
768    items: &[(usize, &&'a dyn Check)],
769    run: &F,
770    died: (Outcome, u64),
771    severities: &Overrides,
772) -> Vec<(Outcome, u64)>
773where
774    F: Fn(&(usize, &&'a dyn Check)) -> (Outcome, u64) + Sync,
775{
776    let (light, heavies): (Vec<_>, Vec<_>) =
777        items.iter().copied().partition(|(_, c)| !is_heavy(**c));
778    let mut out = vec![died; items.len()];
779    let light_out = if light.is_empty() {
780        Vec::new()
781    } else {
782        run_concurrently(&light, run, died)
783    };
784    // A dead Light thread reads `Failed` and so condemns the Heavy wave: a
785    // check that died has not passed.
786    let blocked = light
787        .iter()
788        .zip(&light_out)
789        .any(|((_, c), (o, _))| *o == Outcome::Failed && severities.of(**c) == Severity::Block);
790    for ((idx, _), r) in light.iter().zip(light_out) {
791        out[*idx] = r;
792    }
793    if heavies.is_empty() {
794        return out;
795    }
796    if blocked {
797        // Only a check that would have judged something is SKIPPED; the rest
798        // would have come back `Inert` (clippy in a repository with no Rust),
799        // and naming them would list checks that never apply here. The check
800        // answers for itself (`Check::would_judge`).
801        let staged = crate::hooks::common::staged_files(&[]);
802        let tracked = crate::hooks::common::tracked_files();
803        for (idx, c) in &heavies {
804            out[*idx] = if c.would_judge(&staged, tracked.as_deref()) {
805                (Outcome::Skipped, 0)
806            } else {
807                (Outcome::Inert, 0)
808            };
809        }
810        return out;
811    }
812    for ((idx, _), r) in heavies.iter().zip(run_concurrently(&heavies, run, died)) {
813        out[*idx] = r;
814    }
815    out
816}
817
818/// What a stage concluded, before anything is printed or exited.
819///
820/// A VALUE, so the classification can be asserted directly. While this was one
821/// function that classified, printed and returned an exit code, its tests could
822/// only check the code — whether the right thing was SAID went untested.
823#[derive(Debug, Default, PartialEq, Eq)]
824struct Report<'a> {
825    /// Repaired. The commit proceeds, but the author's files changed under
826    /// them and that must be said out loud.
827    fixed: Vec<&'a str>,
828    /// Failed, and the severity that applies blocks.
829    blocked: Vec<&'a str>,
830    /// Failed, but configured to warn. The check printed an error and meant it,
831    /// so somebody has to say it did not block.
832    downgraded: Vec<&'a str>,
833    /// Could not run. Distinct from "passed", which is the whole point.
834    unavailable: Vec<&'a str>,
835    /// Deferred to CI by the busy policy (ADR-0013). Not passed, not a gap
836    /// on this machine's part either: said so, with what to do about it.
837    deferred: Vec<(&'a str, Severity)>,
838    /// Heavy checks that never started because a Light one blocked first
839    /// (ADR-0020). Said in quiet mode too: a refused commit whose suite did
840    /// not run must never read as one whose suite passed.
841    skipped: Vec<&'a str>,
842    /// How many passed outright. Only read when `amont.quiet` swallowed their
843    /// individual lines — a run that says nothing at all is indistinguishable
844    /// from a gate that never ran, and that is the one thing this crate will
845    /// not let a reader believe.
846    passed: usize,
847}
848
849impl Report<'_> {
850    fn verdict(&self) -> Verdict {
851        Verdict::blocking(!self.blocked.is_empty())
852    }
853}
854
855/// Pure: outcomes and severities in, a verdict out. No IO.
856fn classify<'a>(
857    checks: &[&'a dyn Check],
858    outcomes: &[Outcome],
859    severities: &Overrides,
860) -> Report<'a> {
861    let mut report = Report::default();
862    for (check, outcome) in checks.iter().zip(outcomes) {
863        match outcome {
864            Outcome::Passed => report.passed += 1,
865            // `Warned` needs nothing: a check that chose to warn has already
866            // said what it wanted to, and a roll-up would only repeat it.
867            Outcome::Warned => {}
868            Outcome::Fixed => report.fixed.push(check.name()),
869            Outcome::Unavailable => report.unavailable.push(check.name()),
870            // Judged nothing, said nothing: not a pass to count, not a gap
871            // to announce.
872            Outcome::Inert => {}
873            Outcome::Deferred => report.deferred.push((check.name(), severities.of(*check))),
874            Outcome::Skipped => report.skipped.push(check.name()),
875            Outcome::Failed => match severities.of(*check) {
876                Severity::Block => report.blocked.push(check.name()),
877                Severity::Warn => report.downgraded.push(check.name()),
878            },
879        }
880    }
881    report
882}
883
884/// Says what happened. Prints; decides nothing.
885fn announce(settings: &crate::config::Settings, report: &Report) {
886    if crate::live::quiet(settings) && report.passed > 0 {
887        println!("{} {} check(s) passed", valid_sign(), report.passed);
888    }
889    if !report.fixed.is_empty() {
890        // Louder than a pass, because files on disk are not what the author
891        // left them: they asked for the repair, but they did not watch it.
892        println!(
893            "{} {} check(s) fixed and re-staged: {}",
894            valid_sign(),
895            report.fixed.len(),
896            report.fixed.join(", ")
897        );
898    }
899    if !report.unavailable.is_empty() {
900        // Distinct from "passed". Silence here is how a repo looks verified
901        // when nothing actually ran — the trailing count is the one line
902        // guaranteed to be read, whatever the twenty blocks above said.
903        println!(
904            "{} {} check(s) could not run: {}",
905            warning_sign(),
906            report.unavailable.len(),
907            report.unavailable.join(", ")
908        );
909    }
910    if !report.deferred.is_empty() {
911        announce_deferred(&report.deferred);
912    }
913    if !report.downgraded.is_empty() {
914        println!(
915            "{} {} check(s) reported a problem but are set to warn: {}",
916            warning_sign(),
917            report.downgraded.len(),
918            report.downgraded.join(", ")
919        );
920    }
921    if !report.skipped.is_empty() {
922        announce_skipped(&report.skipped, &report.blocked);
923    }
924    if report.blocked.is_empty() {
925        return;
926    }
927    println!("\n🚨  Error raised by:");
928    for name in &report.blocked {
929        println!("    - {}", highlight(name));
930    }
931}
932
933/// Point every check at `git ls-files` instead of the index.
934///
935/// THE definition, called from both entry points. There used to be two: this
936/// one, and a copy in `main.rs` built from a RAW `ls-files` — no `-z` — whose
937/// output git QUOTES for any unusual byte, so `é.json` arrived as the nine-byte
938/// literal `"\303\251.json"` and was handed to prettier and eslint as a path
939/// that does not exist. And because `override_file_set` writes a `OnceLock`,
940/// main's quoted list WON: whichever ran first was the one that counted, and
941/// main's ran first. `git.rs` documents this exact failure.
942pub fn enter_all_files_mode() {
943    crate::hooks::common::override_file_set(
944        crate::git::stdout_paths(&["ls-files"]).unwrap_or_default(),
945    );
946}
947
948/// `amont run` — every applicable check, on demand.
949///
950/// Two questions, and the mode says which it answers:
951///
952/// - **staged** (default) is "would my commit pass" — the same set a commit
953///   would check, so it is a rehearsal of the hook, and it takes the same
954///   index-fidelity hold the hook takes.
955/// - **`--all-files`** is "does my working tree pass". Deliberately NOT the same
956///   question: on a dirty tree it reports on content that is not committed and
957///   may never be. That is right for adopting a check into an existing
958///   repository, where `git add .` is not an acceptable way to measure the mess,
959///   and it is why `--all-files` takes no stash — there is no staged/unstaged
960///   distinction to protect when the answer is "all of it".
961pub fn run_all(ctx: &Ctx, all_files: bool) -> Verdict {
962    let settings = ctx.settings;
963    // ORDER: the override goes in FIRST. It is what tells `fixing_enabled` and
964    // `restage` that the file set is not the index, and both are consulted
965    // from inside the checks below.
966    if all_files {
967        enter_all_files_mode();
968        if crate::hooks::common::fixing_requested(settings) {
969            println!(
970                "{} {} is set, but fixing is off for {}: the input set is the \
971                 working tree, not the index",
972                warning_sign(),
973                highlight("amont.fix"),
974                highlight("--all-files")
975            );
976        }
977        // Stash-free, per decision 1 of docs/index-fidelity-and-run-modes.md:
978        // there is no staged/unstaged distinction to protect when the input
979        // set is `git ls-files`, so a hold would be surprising extra mutation
980        // with no correctness upside.
981        return run_stage(
982            &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
983            ctx,
984            &Overrides::read(settings),
985        );
986    }
987
988    // Staged mode IS a rehearsal of the commit, so it takes the same hold the
989    // commit does. Without it, `amont run` failed on garbage in the tree
990    // that `git commit` — which holds the unstaged half aside — passed, and
991    // vice versa: the two modes disagreed about the same repository, which is
992    // exactly what this mode exists not to do.
993    let held = match hold_unstaged() {
994        Ok(guard) => guard,
995        Err(verdict) => return verdict,
996    };
997    let verdict = run_stage(
998        &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
999        ctx,
1000        &Overrides::read(settings),
1001    );
1002    // AFTER the report has been printed: dropping earlier would put the
1003    // unstaged content back under a check that is still reading files.
1004    drop(held);
1005    verdict
1006}
1007
1008/// `amont run <check>` — one check by name. `None` when there is no such
1009/// check, which the caller turns into a usage error.
1010///
1011/// Lives here rather than in `main.rs` so `registry::lookup` stays inside the
1012/// runtime, and so the hold decision is made once: a named check takes the
1013/// index-fidelity hold only when it is a `Stage::PreCommit` check running in
1014/// staged mode. A pre-push or commit-msg check invoked by name must never
1015/// touch the working tree — nothing about a push is a staging operation.
1016/// Resolve what `amont run <name>` means, exactly as `hook.skip` resolves a
1017/// name — the rest of the tool taught `ban-terms`; making `run` demand the
1018/// full id was a pointless second vocabulary. Ambiguity is an answer, not a
1019/// guess: the two `branch-pattern` checks are different code at different
1020/// stages.
1021///
1022/// Public because the CALLER needs the answer before anything else happens:
1023/// main decides whether to synthesize push refs from the resolved name, and
1024/// an ambiguous name must say so rather than fail on a missing upstream it
1025/// was never going to use.
1026pub fn resolve_check_name(name: &str, manifest: &crate::manifest::Manifest) -> Named2 {
1027    if crate::registry::lookup(name, manifest).is_some() {
1028        return Named2::Resolved(name.to_string());
1029    }
1030    let mut matches: Vec<String> = crate::registry::CHECKS
1031        .iter()
1032        .map(|c| c.name.to_string())
1033        .chain(manifest.externals.iter().map(|e| e.id.clone()))
1034        .filter(|id| crate::skip_suppresses(id, name))
1035        .collect();
1036    matches.dedup();
1037    match matches.len() {
1038        0 => Named2::Unknown,
1039        1 => Named2::Resolved(matches.remove(0)),
1040        _ => Named2::Ambiguous(matches),
1041    }
1042}
1043
1044/// How a run name resolved.
1045pub enum Named2 {
1046    Resolved(String),
1047    Unknown,
1048    Ambiguous(Vec<String>),
1049}
1050
1051pub fn run_named(ctx: &Ctx, name: &str, all_files: bool) -> Named {
1052    let full: String = match resolve_check_name(name, ctx.manifest) {
1053        Named2::Resolved(id) => id,
1054        Named2::Unknown => return Named::Unknown,
1055        Named2::Ambiguous(ids) => return Named::Ambiguous(ids),
1056    };
1057    let name = full.as_str();
1058    let Some(run_check) = crate::registry::lookup(name, ctx.manifest) else {
1059        return Named::Unknown;
1060    };
1061    // The Ctx must carry the RESOLVED id: lookup's closure re-resolves
1062    // through `ctx.name`, and handing it the short name back would panic on
1063    // the very ambiguity this function just settled.
1064    let ctx = &Ctx {
1065        name,
1066        args: ctx.args,
1067        hooks_dir: ctx.hooks_dir,
1068        push: ctx.push,
1069        manifest: ctx.manifest,
1070        settings: ctx.settings,
1071        handed_to_cluster: ctx.handed_to_cluster,
1072        land: ctx.land,
1073        audits: ctx.audits,
1074        source_worktree: ctx.source_worktree,
1075    };
1076    // Under quiet, a check run by name is captured like one inside its stage
1077    // — one slot, its tool's output to a log, one line on a pass — whatever
1078    // `amont.progress` says: the person who asked for quiet asked for this.
1079    let check = crate::registry::one_named(name, ctx.manifest);
1080    let run = |ctx: &Ctx| match check.filter(|_| crate::live::quiet(ctx.settings)) {
1081        Some(check) => run_quiet(ctx, check),
1082        None => run_check(ctx),
1083    };
1084    if all_files {
1085        enter_all_files_mode();
1086        return Named::Ran(run(ctx));
1087    }
1088    let is_pre_commit_check = check.is_some_and(|c| c.stage() == Stage::PreCommit);
1089    if !is_pre_commit_check {
1090        return Named::Ran(run(ctx));
1091    }
1092    let held = match hold_unstaged() {
1093        Ok(guard) => guard,
1094        Err(verdict) => return Named::Ran(verdict),
1095    };
1096    let verdict = run(ctx);
1097    drop(held);
1098    Named::Ran(verdict)
1099}
1100
1101/// One check by name, in a one-slot stage. The verdict is the one
1102/// `registry::lookup` gives a check: blocking only a failed `block` check.
1103/// Enter `check` for the host-slot bookkeeping: a heavy check whose severity
1104/// is `warn` never waits for a slot (`host_slots::never_waits`), except inside
1105/// a rehearsal snapshot, where no push connection is open, no commit waits,
1106/// and land's pre-stage needs the check's evidence: there it follows the
1107/// busy policy the rehearsal sets, except in land's pre-stage, where a `warn`
1108/// check waits at most `amont.warnSlotWait` and then runs unqueued
1109/// (`host_slots::wait_bounded_for_warn`). Only a heavy check can wait, so only it
1110/// asks `severity`, which the caller answers from its stage's severity fold
1111/// when it has one: a git-config read per check broke the commit's git-spawn
1112/// budget.
1113fn enter(check: &dyn Check, severity: impl FnOnce() -> Severity) -> crate::host_slots::CheckGuard {
1114    let guard = crate::host_slots::enter_check(check.name(), check.weight());
1115    if check.weight() == crate::host_slots::Weight::Heavy {
1116        if !crate::rehearsal::in_snapshot() {
1117            if matches!(severity(), Severity::Warn) {
1118                crate::host_slots::never_waits();
1119            }
1120        } else if crate::rehearsal::in_prestage() && matches!(severity(), Severity::Warn) {
1121            crate::host_slots::wait_bounded_for_warn();
1122        }
1123    }
1124    guard
1125}
1126
1127fn run_quiet(ctx: &Ctx, check: &dyn Check) -> Verdict {
1128    let stage = crate::live::Stage::begin(ctx.settings, &[check.name()]);
1129    stage.named();
1130    let _sink = stage.enter(0);
1131    let flush = crate::live::FinishOnDrop::new(ctx.settings, &stage, 0);
1132    let outcome = {
1133        let slot = enter(check, || crate::registry::severity_of(ctx.settings, check));
1134        deferred_or(&slot, check.run(ctx))
1135    };
1136    flush.outcome(outcome);
1137    // The block prints here, before anything the caller says after it.
1138    drop(flush);
1139    // The same rule `registry::lookup` applies, with every variant named.
1140    let blocks = match outcome {
1141        Outcome::Failed => match crate::registry::severity_of(ctx.settings, check) {
1142            Severity::Block => true,
1143            Severity::Warn => false,
1144        },
1145        Outcome::Passed
1146        | Outcome::Warned
1147        | Outcome::Fixed
1148        | Outcome::Unavailable
1149        | Outcome::Inert
1150        | Outcome::Deferred
1151        | Outcome::Skipped => false,
1152    };
1153    Verdict::blocking(blocks)
1154}
1155
1156/// What `run_named` resolved a name to.
1157pub enum Named {
1158    Ran(Verdict),
1159    /// Nothing matches — full id, short name, or entrypoint.
1160    Unknown,
1161    /// A short name that reaches more than one check; the caller lists them
1162    /// so the user can pick a full id.
1163    Ambiguous(Vec<String>),
1164}
1165
1166/// Why a pre-push gate need not run in this push (ADR-0018: the refusal and
1167/// the loop ask the same question, through `pre_push`'s `decide`).
1168enum Skip {
1169    /// The rehearsal that made this snapshot gave it to the cluster.
1170    HandedToCluster,
1171    /// Its stamp, or its cluster token, is on every pushed tip.
1172    Stamped,
1173    /// It completed without passing on every pushed tip's tree, in a
1174    /// rehearsal or land's pre-stage (ADR-0018). Never a pass: it is not
1175    /// attested, and only a push that would otherwise refuse honours it.
1176    CompletedEarlier,
1177    /// Its commit-time twin was proved on the cluster for every tip.
1178    TwinOnCluster(String),
1179    /// Its commit-time pair covered the push; `coverage` says whether by every
1180    /// pushed commit's stamp or by the tips' own stamp keys (ADR-0019).
1181    GatedAtCommit {
1182        name: String,
1183        coverage: crate::hooks::run_tests::Coverage,
1184    },
1185    /// Its commit-time pair was deferred to CI on this many pushed commits.
1186    DeferredAtCommit(String, usize),
1187}
1188
1189/// What `decide` says about one gate: skip it, for a reason, or run it —
1190/// noting the commit-time pair that left this many pushed commits unstamped.
1191enum Decision {
1192    Skip(Skip),
1193    Run {
1194        unstamped_pair: Option<(String, usize)>,
1195    },
1196}
1197
1198/// `amont.pushStamps`, as the refusal needs it: whether anything run before
1199/// the push can let it skip its gates.
1200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1201pub(crate) enum StampReuse {
1202    On,
1203    Off,
1204}
1205
1206/// The tag a push carries, if it pushes one: its refusal names
1207/// `amont land --tag`, since `amont land` alone pushes the branch.
1208fn pushed_tag(refs: &[crate::pushrefs::PushRef]) -> Option<&str> {
1209    refs.iter()
1210        .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
1211        .find_map(|r| r.remote_ref.strip_prefix("refs/tags/"))
1212}
1213
1214/// The bare push's refusal (ADR-0018), one command per line, each line at most
1215/// 80 columns, so each copies cleanly. With stamp reuse off, nothing amont can
1216/// run beforehand lets this push skip its gates, so `rehearse` is not
1217/// offered. A tag push is offered `amont land --tag`, never the branch
1218/// remedies, whose records do not answer for a release.
1219pub(crate) fn push_refusal(
1220    short: &str,
1221    missing: &[&str],
1222    reuse: StampReuse,
1223    tag: Option<&str>,
1224) -> Vec<String> {
1225    let mut out = vec![format!(
1226        "{BIN}: push refused: {} push gate{} {} not run on {short}:",
1227        missing.len(),
1228        if missing.len() == 1 { "" } else { "s" },
1229        if missing.len() == 1 { "has" } else { "have" },
1230    )];
1231    out.extend(wrap_names(missing));
1232    let land = match tag {
1233        Some(tag) => format!("{BIN} land --tag {tag}"),
1234        None => format!("{BIN} land"),
1235    };
1236    if reuse == StampReuse::Off {
1237        out.push("    stamp reuse is off (amont.pushStamps false); turn it on:".to_string());
1238        out.push("        git config amont.pushStamps true".to_string());
1239        out.push("    then run the gates before git connects, and push:".to_string());
1240        out.push(format!("        {land}"));
1241    } else {
1242        out.push("    run them before git connects, then push:".to_string());
1243        out.push(format!("        {land}"));
1244        if tag.is_none() {
1245            out.push("    or stamp this tree first:".to_string());
1246            out.push(format!("        {BIN} rehearse --wait"));
1247        }
1248    }
1249    out.push("    or run them in this push:".to_string());
1250    out.push("        git config amont.pushGates inline".to_string());
1251    out
1252}
1253
1254/// The refusal inside `amont land`'s own push, led by the sentinel `land`
1255/// matches. `land` is what land's pre-stage saw: a pushed range whose remote
1256/// side differs is the remote moving under land; anything else is evidence
1257/// the pre-stage should have left and did not.
1258pub(crate) fn land_refusal(
1259    land: &crate::rehearsal::LandLine,
1260    refs: &[crate::pushrefs::PushRef],
1261    missing: &[&str],
1262) -> Vec<String> {
1263    let moved = refs
1264        .iter()
1265        .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
1266        .any(|r| r.remote_oid != land.remote_tip);
1267    let mut out = Vec::new();
1268    if moved {
1269        out.push(crate::land::LAND_REMOTE_MOVED.to_string());
1270        out.push(format!(
1271            "{BIN}: the remote moved during land; run {BIN} land again"
1272        ));
1273    } else {
1274        out.push(crate::land::LAND_EVIDENCE_MISSING.to_string());
1275        out.push(format!("{BIN}: land's pre-stage left no evidence for:"));
1276    }
1277    out.extend(wrap_names(missing));
1278    out
1279}
1280
1281/// Gate names as indented lines of at most 80 columns.
1282pub(crate) fn wrap_names(names: &[&str]) -> Vec<String> {
1283    let mut lines = Vec::new();
1284    let mut line = String::from("       ");
1285    for name in names {
1286        if line.len() + 1 + name.len() > 80 && !line.trim().is_empty() {
1287            lines.push(std::mem::replace(&mut line, String::from("       ")));
1288        }
1289        line.push(' ');
1290        line.push_str(name);
1291    }
1292    if !line.trim().is_empty() {
1293        lines.push(line);
1294    }
1295    lines
1296}
1297
1298pub fn pre_push(ctx: &Ctx) -> Verdict {
1299    let settings = ctx.settings;
1300    // `amont.treeLintWait` counts from HERE, so no earlier wait (a test
1301    // rehearsal's `amont.rehearsalWait`) can extend it.
1302    let push_started = std::time::Instant::now();
1303    // The notes push `attest` makes re-enters this hook; its ref list is only
1304    // ever the attest ref, so there is nothing to prove — and proving it
1305    // would recurse.
1306    if crate::attest::push_guard_active() {
1307        return Verdict::Proceed;
1308    }
1309    // Before the stamps are read: what a detached rehearsal finished while the
1310    // laptop was away counts at this push (ADR-0017). Not inside a rehearsal's
1311    // own snapshot, which stands in for a push that is not happening.
1312    if !crate::rehearsal::in_snapshot() {
1313        crate::cluster::collect_if_declared(ctx.manifest);
1314    }
1315    crate::manifest::verify_tool_pins(&ctx.manifest.pins);
1316    announce_policy_state(ctx.settings, ctx.manifest);
1317    // NB: no CHERRY_PICK_HEAD check here — the zsh pre-push had none either.
1318    let severities = Overrides::read(settings);
1319    // pre-push had NO state guard at all, with a comment admitting it existed
1320    // only because the zsh version had none. Now it asks the same question
1321    // pre-commit does and each check answers for itself.
1322    let in_progress = crate::git_states_in_progress();
1323    // Declared order unless this repository asked for the other one. The
1324    // permutation is decided BEFORE the live stage is begun, because the
1325    // stage draws the list in the order it is given.
1326    let pre_push_checks = ordered_by_evidence(
1327        settings,
1328        selected_during(ctx.settings, Stage::PrePush, &in_progress, ctx.manifest),
1329    );
1330    let stage = crate::live::enabled(settings).then(|| {
1331        let names: Vec<&str> = pre_push_checks.iter().map(|c| c.name()).collect();
1332        crate::live::Stage::begin(settings, &names)
1333    });
1334    // What actually PASSED, for the attestation at the bottom. `Warned` and
1335    // `Unavailable` stay out — "could not run" is not "passed" — and a
1336    // commit-time-gated pair counts, because its stamps say the check ran on
1337    // every pushed tree.
1338    let mut passed: Vec<String> = Vec::new();
1339    // Accumulated rather than written per check: one append at the end costs a
1340    // single file open, and the loop below can leave early.
1341    let mut downgraded: Vec<(String, crate::downgrade::Origin)> = Vec::new();
1342    // PUSH STAMPS. The tips being pushed, and what earlier runs of THIS gate
1343    // recorded against their trees — an `amont run pre-push` rehearsal, or a
1344    // push whose gate passed and whose transport then died. A scoped gate
1345    // (a test suite: its verdict is a function of the tree alone) whose
1346    // stamp sits on every tip is not run again; the unscoped ones
1347    // (branch-protect, secrets — questions about the push, not the content)
1348    // always run. `amont.pushStamps false` turns the reuse off.
1349    //
1350    // Reading `ctx.push` here may consume stdin, exactly as `attest` does
1351    // below; every pre-push check reads it anyway.
1352    let tips: Vec<String> = {
1353        let mut t: Vec<String> = ctx
1354            .push
1355            .get()
1356            .iter()
1357            .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
1358            // An annotated tag pushes its tag object; what was tested, stamped
1359            // and recorded is the commit it points at (ADR-0018).
1360            .map(|r| {
1361                crate::git::stdout(&[
1362                    "rev-parse",
1363                    "--verify",
1364                    "-q",
1365                    &format!("{}^{{commit}}", r.local_oid),
1366                ])
1367                .unwrap_or_else(|| r.local_oid.clone())
1368            })
1369            .collect();
1370        t.sort_unstable();
1371        t.dedup();
1372        t
1373    };
1374    let reuse_stamps = crate::gate_stamp::push_stamps_enabled(settings);
1375    // The working tree AS THE SUITE WILL BE HANDED IT, captured before any
1376    // gate has run.
1377    //
1378    // Timing is the point. Asking afterwards means a gate that modifies a
1379    // tracked file — a formatter, a suite that updates a snapshot fixture —
1380    // disqualifies its OWN stamp. What a stamp needs to know is what the
1381    // suite could READ, which is the state it was handed; a change the suite
1382    // itself made was never an input to it.
1383    //
1384    // Tracked modifications only. `stamp_tips` argues that gap, which is a
1385    // deliberate one.
1386    //
1387    // Read whatever `reuse_stamps` says: the attestation asks it too (#289),
1388    // and an empty string here would read as a clean tree.
1389    let tree_at_start =
1390        crate::git::stdout(&["status", "--porcelain", "--untracked-files=no"]).unwrap_or_default();
1391    // Inside a rehearsal snapshot only the content gates make sense: the
1392    // unscoped checks ask about a PUSH — its branch name, its target, its
1393    // secrets — and no push is happening. Said once, not per check.
1394    let rehearsing = crate::rehearsal::in_snapshot();
1395    let handed_to_cluster = ctx.handed_to_cluster;
1396    // The push `amont land` makes after its pre-stage ran the gates
1397    // (ADR-0018), as `<sha> <remote tip>`.
1398    let land = match ctx.land {
1399        crate::rehearsal::LandEnv::Absent => None,
1400        crate::rehearsal::LandEnv::Valid(line) => Some(line),
1401        crate::rehearsal::LandEnv::Malformed(raw) => {
1402            eprintln!(
1403                "{BIN}: push refused: {} is not `<sha> <remote tip>` ({raw:?})",
1404                crate::rehearsal::LAND_ENV
1405            );
1406            eprintln!(
1407                "    unset it, then push again:  unset {}",
1408                crate::rehearsal::LAND_ENV
1409            );
1410            return Verdict::Block;
1411        }
1412    };
1413    // ADR-0018: a heavy gate never runs while git holds the remote's
1414    // connection open, unless this machine asked for that
1415    // (`amont.pushGates inline`). Land's own push expects its pre-stage's
1416    // evidence; a bare push under `refuse` (the default) refuses at once.
1417    // Neither waits for a background rehearsal: that wait would itself hold
1418    // the connection.
1419    let gate_before_push =
1420        !rehearsing && (land.is_some() || crate::rehearsal::refuse_push_gates(settings));
1421    // A background rehearsal of one of these tips may be mid-suite right
1422    // now. Waiting for it is strictly less work than starting over, and
1423    // its stamp — read AFTER the wait, below — is the hand-off.
1424    // Only when this push has test gates for the rehearsal to vouch for: a
1425    // rehearsal that is only proving tree lint is waited for by the tree
1426    // verdict alone, under its own `amont.treeLintWait` (ADR-0024), never
1427    // under `amont.rehearsalWait`.
1428    if reuse_stamps && !tips.is_empty() && !gate_before_push {
1429        let changed = crate::pushrefs::changed_files(ctx.push.get());
1430        if !scoped_push_gates(settings, ctx.manifest, &changed).is_empty() {
1431            crate::rehearsal::await_for(settings, &tips);
1432        }
1433    }
1434    let push_stamps = if reuse_stamps && !tips.is_empty() {
1435        crate::gate_stamp::stamps_for(&tips)
1436    } else {
1437        Default::default()
1438    };
1439    if rehearsing {
1440        crate::say!(
1441            "rehearsal: running the test gates only — the push-shaped checks run at push time"
1442        );
1443    }
1444    let stamped_on_every_tip = |name: &str| -> bool {
1445        // The complete token, or nothing: a gate whose identity cannot be
1446        // worked out is never skipped on a stamp.
1447        let Some(token) = crate::gate_identity::token(&ctx.manifest.externals, name) else {
1448            return false;
1449        };
1450        !tips.is_empty()
1451            && tips
1452                .iter()
1453                .all(|t| push_stamps.get(t).is_some_and(|s| s.contains(&token)))
1454    };
1455    // A trusted `platform=any` gate is also vouched for by its cluster token
1456    // on every tip's tree (ADR-0016). Asked only for such a gate, so a
1457    // repository with none pays no spawn.
1458    let cluster_stamped = |name: &str| -> bool {
1459        reuse_stamps
1460            && ctx
1461                .manifest
1462                .externals
1463                .iter()
1464                .find(|e| e.id == name)
1465                .is_some_and(|e| crate::cluster::vouched_on_every(settings, e, &tips))
1466    };
1467    // Why a gate need not run in this push, or that it must. ONE function,
1468    // asked by the loop below and by the refusal before it, so a gate the
1469    // loop would skip is never refused, and one it would run never passes
1470    // the refusal (ADR-0018).
1471    let decide = |check: &dyn Check| -> Decision {
1472        // Handed to the cluster by the rehearsal that made this snapshot: not
1473        // repeated here, its pass comes back as a cluster token.
1474        if rehearsing && handed_to_cluster.iter().any(|gate| gate == check.name()) {
1475            return Decision::Skip(Skip::HandedToCluster);
1476        }
1477        // A dependency audit is never skipped: its verdict depends on the
1478        // day's advisories and the push's stakes, so it replays a fresh
1479        // record instead, inside the check (ADR-0018).
1480        if crate::hooks::audit::is_audit(check.name()) {
1481            return Decision::Run {
1482                unstamped_pair: None,
1483            };
1484        }
1485        if stamped_push_gate(check)
1486            && (stamped_on_every_tip(check.name()) || cluster_stamped(check.name()))
1487        {
1488            return Decision::Skip(Skip::Stamped);
1489        }
1490        if gate_before_push && reuse_stamps && stamped_push_gate(check) {
1491            let done = crate::gate_identity::token(&ctx.manifest.externals, check.name())
1492                .is_some_and(|token| {
1493                    crate::gate_stamp::done_on_every(&tips, &token, severities.of(check))
1494                });
1495            if done {
1496                return Decision::Skip(Skip::CompletedEarlier);
1497            }
1498        }
1499        let declared = ctx
1500            .manifest
1501            .externals
1502            .iter()
1503            .find(|e| e.stage == Stage::PrePush && e.id == check.name());
1504        // A `platform=any` push gate whose commit twin declares the same suite
1505        // and was proved on the cluster on every tip's tree is gated at commit
1506        // too, and counts as a cluster pass under its own id (ADR-0016).
1507        if let Some(push_gate) = declared.filter(|_| reuse_stamps) {
1508            let claimed_from_twin = ctx
1509                .manifest
1510                .externals
1511                .iter()
1512                .filter(|e| e.stage == Stage::PreCommit && e.short_name == push_gate.short_name)
1513                .any(|twin| {
1514                    crate::cluster::claim_twin_cluster_pass(settings, push_gate, twin, &tips)
1515                });
1516            if claimed_from_twin {
1517                return Decision::Skip(Skip::TwinOnCluster(push_gate.short_name.clone()));
1518            }
1519        }
1520        // The push side of a pair is `(name, scope)`, from whichever of the
1521        // two kinds of check this is. A declared pre-push external supplies
1522        // its own; anything else is a BUILT-IN, and `pairing_name` plus the
1523        // registry's scope say the same two things about it.
1524        let builtin_scope = check.scope();
1525        let pairing: Option<(&str, &crate::check::Scope)> = match declared {
1526            Some(ext) => match &ext.kind {
1527                crate::manifest::Kind::Runnable { scope, .. } => {
1528                    Some((ext.short_name.as_str(), scope))
1529                }
1530                // A declared pre-push entry that runs nothing has no scope to
1531                // judge with, and is not a built-in either. Nothing to pair.
1532                _ => None,
1533            },
1534            None => Some((check.pairing_name(), &builtin_scope)),
1535        };
1536        let Some((name, push_scope)) = pairing else {
1537            return Decision::Run {
1538                unstamped_pair: None,
1539            };
1540        };
1541        match crate::hooks::run_tests::pair_verdict(
1542            ctx.settings,
1543            name,
1544            push_scope,
1545            ctx.manifest,
1546            ctx.push,
1547        ) {
1548            crate::hooks::run_tests::PairVerdict::Gated(coverage) => {
1549                Decision::Skip(Skip::GatedAtCommit {
1550                    name: name.to_string(),
1551                    coverage,
1552                })
1553            }
1554            crate::hooks::run_tests::PairVerdict::Deferred(n) => {
1555                Decision::Skip(Skip::DeferredAtCommit(name.to_string(), n))
1556            }
1557            crate::hooks::run_tests::PairVerdict::Unstamped(n) => Decision::Run {
1558                unstamped_pair: Some((name.to_string(), n)),
1559            },
1560            crate::hooks::run_tests::PairVerdict::NotPaired => Decision::Run {
1561                unstamped_pair: None,
1562            },
1563        }
1564    };
1565    // The question `amont list` answers with "inert here — needs go.sum",
1566    // asked of the index once (see the loop below).
1567    let tracked = crate::tracked_paths();
1568    // ADR-0018: refuse before any heavy gate starts. The gates this push
1569    // owes are the scoped ones its range touches (`scoped_push_gates`, the
1570    // same set a rehearsal stamps); each is asked `decide`, and any it would
1571    // have to RUN means the push refuses.
1572    if gate_before_push && !tips.is_empty() {
1573        let changed = crate::pushrefs::changed_files(ctx.push.get());
1574        let owed = scoped_push_gates(settings, ctx.manifest, &changed);
1575        let missing: Vec<&str> = pre_push_checks
1576            .iter()
1577            .filter(|c| {
1578                if crate::hooks::audit::is_audit(c.name()) {
1579                    // Owed on every push it is opted into, whatever the
1580                    // range touches, unless a fresh record answers for it.
1581                    c.scope().opted_in(&tracked)
1582                        && crate::hooks::audit::owed(settings, ctx.audits, c.name(), ctx.push.get())
1583                } else {
1584                    // A declared command whose program is not installed can
1585                    // never be stamped or recorded, so no pre-stage could
1586                    // answer for it: owing it would refuse every push for
1587                    // good. It runs below instead, fails to start, and warns,
1588                    // as before 2.0. Only that: a gate whose token failed for
1589                    // another reason stays owed.
1590                    owed.iter().any(|o| o == c.name())
1591                        && !crate::gate_identity::program_missing(&ctx.manifest.externals, c.name())
1592                        && matches!(decide(**c), Decision::Run { .. })
1593                }
1594            })
1595            .map(|c| c.name())
1596            .collect();
1597        if !missing.is_empty() {
1598            let short: String = tips
1599                .first()
1600                .map(|t| t.chars().take(8).collect())
1601                .unwrap_or_default();
1602            let lines = match land {
1603                Some(line) => land_refusal(line, ctx.push.get(), &missing),
1604                None => push_refusal(
1605                    &short,
1606                    &missing,
1607                    if reuse_stamps {
1608                        StampReuse::On
1609                    } else {
1610                        StampReuse::Off
1611                    },
1612                    pushed_tag(ctx.push.get()),
1613                ),
1614            };
1615            for line in lines {
1616                eprintln!("{line}");
1617            }
1618            return Verdict::Block;
1619        }
1620    }
1621    // What actually RAN and passed here (as opposed to being vouched for by
1622    // a stamp) — the set this run may stamp in turn.
1623    let mut ran_and_passed: Vec<String> = Vec::new();
1624    // Scoped gates that RAN here and completed without passing — a warning,
1625    // or a tool that was missing (ADR-0018): recorded beside the stamps, never
1626    // as one, so a refusing push does not ask for them again.
1627    let mut completed_otherwise: Vec<(String, crate::gate_stamp::Completion)> = Vec::new();
1628    // What each gate COST and how it ENDED, for the record `gate_evidence`
1629    // reads. Every outcome, failures included: the stamp deliberately has no
1630    // opinion about a gate that failed, and a dataset that kept only the
1631    // passes could never say a gate is flaky.
1632    let mut evidence: Vec<crate::gate_stamp::Run> = Vec::new();
1633    // The question `amont list` answers with "inert here — needs go.sum":
1634    // does this repository carry the marker that turns the check on? Asked
1635    // of the index, once, and answered the same way here — a check the
1636    // registry calls inert used to run anyway, find its tool or lockfile
1637    // missing, and warn that it "could not run" on every push of a
1638    // repository it was never meant to touch.
1639    // Inside a rehearsal a heavy gate hands its slot to the next one; the
1640    // scope releases what is parked on every way out of this function.
1641    let park = crate::host_slots::ParkScope::begin();
1642    for (idx, check) in pre_push_checks.iter().enumerate() {
1643        if !check.scope().opted_in(&tracked) {
1644            continue;
1645        }
1646        let _sink = stage.as_ref().map(|s| s.enter(idx));
1647        let flush = stage
1648            .as_ref()
1649            .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, idx));
1650        // A declared pre-push external whose NAME is also declared at
1651        // pre-commit (blocking) is a gate pair: the commit-time side earned
1652        // per-commit stamps, and this side runs only for pushes carrying
1653        // commits with no record of it — the same contract the npm gate has
1654        // always had, for vocabularies npm never heard of (`cargo test`,
1655        // `pytest`, anything). Messages mirror the npm gate's exactly;
1656        // docs/checks.md quotes them. `decide` holds the reasoning, shared
1657        // with the refusal above.
1658        // The dependency audits are unscoped too (opted in by a lockfile,
1659        // with no file scope), but a rehearsal is exactly where their record
1660        // is earned (ADR-0018), so they run here.
1661        if rehearsing && !stamped_push_gate(*check) && !crate::hooks::audit::is_audit(check.name())
1662        {
1663            continue;
1664        }
1665        // A push of deletions only (or of no ref at all: git ran the hook
1666        // with nothing to push) has no commit for an audit to answer for, and
1667        // running one would hold the connection open for nothing (ADR-0018).
1668        if gate_before_push && tips.is_empty() && crate::hooks::audit::is_audit(check.name()) {
1669            continue;
1670        }
1671        match decide(*check) {
1672            Decision::Skip(Skip::HandedToCluster) => {
1673                crate::say!(
1674                    "{} {} runs on the cluster — the next commit or push collects it",
1675                    valid_sign(),
1676                    highlight(check.name()),
1677                );
1678                continue;
1679            }
1680            Decision::Skip(Skip::Stamped) => {
1681                crate::say!(
1682                    "{} {} passed on this exact tree earlier — not repeating it here",
1683                    valid_sign(),
1684                    highlight(check.name()),
1685                );
1686                passed.push(check.name().to_string());
1687                continue;
1688            }
1689            Decision::Skip(Skip::CompletedEarlier) => {
1690                crate::say!(
1691                    "{} {} ran on this tree earlier and did not pass cleanly (it warned or \
1692                     could not run) — not repeating it here",
1693                    warning_sign(),
1694                    highlight(check.name()),
1695                );
1696                continue;
1697            }
1698            Decision::Skip(Skip::TwinOnCluster(short)) => {
1699                crate::say!(
1700                    "{} {} gated at commit on the cluster instead — not repeating it here",
1701                    valid_sign(),
1702                    highlight(&short),
1703                );
1704                passed.push(check.name().to_string());
1705                continue;
1706            }
1707            Decision::Skip(Skip::GatedAtCommit { name, coverage }) => {
1708                crate::say!(
1709                    "{} {} gated at commit instead — not repeating it here",
1710                    valid_sign(),
1711                    highlight(&name),
1712                );
1713                // A second line only when a TIP vouched alone: the plain line
1714                // has always meant "every pushed commit carries its stamp",
1715                // and a reader who pushed an unstamped commit deserves to see
1716                // what the skip rests on. Its own line, so the first stays
1717                // within 80 columns; "the code at", because a plans-only tip
1718                // never ran the gate itself — its canonical tree did.
1719                if let crate::hooks::run_tests::Coverage::Tips(tips) = coverage {
1720                    crate::say!("    the code at tip {} passed at commit", tips.join(", "));
1721                }
1722                passed.push(check.name().to_string());
1723                continue;
1724            }
1725            Decision::Skip(Skip::DeferredAtCommit(name, n)) => {
1726                crate::say!(
1727                    "{} {} was deferred to CI at commit on {n} pushed commit{} \
1728                     — deferring it here too",
1729                    warning_sign(),
1730                    highlight(&name),
1731                    if n == 1 { "" } else { "s" },
1732                );
1733                evidence.push(crate::gate_stamp::Run {
1734                    at: crate::gate_evidence::now(),
1735                    gate: check.name().to_string(),
1736                    outcome: crate::gate_stamp::RunOutcome::Deferred,
1737                    ms: 0,
1738                });
1739                continue;
1740            }
1741            Decision::Run {
1742                unstamped_pair: Some((name, n)),
1743            } => {
1744                // `amont.unstampedPush refuse`: never run a suite with
1745                // the remote's connection held open — say how to earn
1746                // the stamp instead. Not inside a rehearsal snapshot:
1747                // running there is how the stamp is earned.
1748                if !rehearsing && crate::rehearsal::refuse_unstamped(ctx.settings) {
1749                    crate::say!(
1750                        "{} {} is declared at commit time, but {n} pushed \
1751                         commit{} carr{} no record of it (rewritten by a \
1752                         rebase or amend, or made without the hooks) — \
1753                         refusing the push",
1754                        warning_sign(),
1755                        name,
1756                        if n == 1 { "" } else { "s" },
1757                        if n == 1 { "ies" } else { "y" },
1758                    );
1759                    crate::say!(
1760                        "    Test this tree first, with no push waiting on it: {} — then push again",
1761                        highlight(&format!("{BIN} rehearse --wait")),
1762                    );
1763                    crate::downgrade::note(settings, &downgraded);
1764                    record_evidence(&tips, &evidence);
1765                    println!("\n🚨  Error raised by hook {}", highlight(check.name()));
1766                    return Verdict::Block;
1767                }
1768                crate::say!(
1769                    "{} {} is declared at commit time, but {n} pushed \
1770                     commit{} carr{} no record of it — running it here",
1771                    warning_sign(),
1772                    name,
1773                    if n == 1 { "" } else { "s" },
1774                    if n == 1 { "ies" } else { "y" },
1775                );
1776            }
1777            Decision::Run {
1778                unstamped_pair: None,
1779            } => {}
1780        }
1781        let sub = Ctx {
1782            name: check.name(),
1783            args: ctx.args,
1784            hooks_dir: ctx.hooks_dir,
1785            push: ctx.push,
1786            manifest: ctx.manifest,
1787            settings: ctx.settings,
1788            handed_to_cluster: ctx.handed_to_cluster,
1789            land: ctx.land,
1790            audits: ctx.audits,
1791            source_worktree: ctx.source_worktree,
1792        };
1793        // Wall clock around the check itself, not around the hook: the number
1794        // that catches a suite which stopped finding tests is how long THAT
1795        // gate took, and everything outside this call is bookkeeping.
1796        let started = std::time::Instant::now();
1797        let mut severity_read: Option<Severity> = None;
1798        let slot = enter(*check, || {
1799            let severity = crate::registry::severity_of(ctx.settings, *check);
1800            severity_read = Some(severity);
1801            severity
1802        });
1803        let outcome = deferred_or(&slot, check.run(&sub));
1804        if let Some(f) = &flush {
1805            f.outcome(outcome);
1806        }
1807        let ran = started.elapsed().saturating_sub(slot.queued());
1808        drop(slot);
1809        evidence.push(crate::gate_stamp::Run {
1810            at: crate::gate_evidence::now(),
1811            gate: check.name().to_string(),
1812            outcome: run_outcome(outcome),
1813            ms: ran.as_millis().min(u128::from(u64::MAX)) as u64,
1814        });
1815        match outcome {
1816            Outcome::Passed => {
1817                passed.push(check.name().to_string());
1818                // An audit's pass is a record of its report, never a stamp.
1819                if stamped_push_gate(*check) {
1820                    ran_and_passed.push(check.name().to_string());
1821                }
1822            }
1823            // Announced, never fatal: a check that could not run has not
1824            // invalidated anything, and neither has a warning.
1825            Outcome::Unavailable => {
1826                if stamped_push_gate(*check) {
1827                    completed_otherwise.push((
1828                        check.name().to_string(),
1829                        crate::gate_stamp::Completion::Unavailable,
1830                    ));
1831                }
1832                println!(
1833                    "{} {} could not run",
1834                    warning_sign(),
1835                    highlight(check.name())
1836                )
1837            }
1838            Outcome::Warned => {
1839                if stamped_push_gate(*check) {
1840                    completed_otherwise.push((
1841                        check.name().to_string(),
1842                        crate::gate_stamp::Completion::Warned,
1843                    ));
1844                }
1845            }
1846            // Not run, never fatal, never passed: CI runs it (ADR-0013).
1847            Outcome::Deferred => announce_deferred(&[(
1848                check.name(),
1849                severity_read.unwrap_or_else(|| crate::registry::severity_of(ctx.settings, *check)),
1850            )]),
1851            // Nothing to judge: not passed (nothing to stamp or attest), not
1852            // a gap (nothing is missing). The dispatcher asked the registry's
1853            // opt-in question above; this is a check answering it for itself.
1854            Outcome::Inert => {}
1855            // Cannot occur: `Fix::Rewrite` is refused on a pre-push
1856            // declaration, so nothing here can repair anything.
1857            Outcome::Fixed => {}
1858            // Cannot occur: pre-push is serial and stops at the first failure
1859            // on its own; only pre-commit's waves skip (ADR-0020).
1860            Outcome::Skipped => {}
1861            Outcome::Failed => match severities.of(*check) {
1862                Severity::Warn => {
1863                    if stamped_push_gate(*check) {
1864                        completed_otherwise.push((
1865                            check.name().to_string(),
1866                            crate::gate_stamp::Completion::FailedUnderWarn,
1867                        ));
1868                    }
1869                    downgraded.push((
1870                        check.name().to_string(),
1871                        downgrade_origin(*check, &severities),
1872                    ));
1873                    println!(
1874                        "{} {} reported a problem (severity warn)",
1875                        warning_sign(),
1876                        highlight(check.name())
1877                    );
1878                }
1879                // Fail-fast applies ONLY to Block: the later steps are
1880                // expensive and their preconditions are gone.
1881                Severity::Block => {
1882                    // Record what already warned before leaving. Those checks
1883                    // ran and reported; a later check blocking does not unmake
1884                    // them, and dropping them here would make the ledger quietly
1885                    // under-count every push that ended badly.
1886                    crate::downgrade::note(settings, &downgraded);
1887                    // The same argument for the evidence, and it matters more
1888                    // here: this is the path a FAILURE leaves by, and a record
1889                    // written only on the way out of a successful push would
1890                    // be a dataset of passes calling itself a dataset of runs.
1891                    record_evidence(&tips, &evidence);
1892                    println!("\n🚨  Error raised by hook {}", highlight(check.name()));
1893                    return Verdict::Block;
1894                }
1895            },
1896        }
1897    }
1898    drop(park);
1899    // Every block gate passed — stamp the tips with the scoped gates that
1900    // RAN here, so the next push of this content (a retry after a dropped
1901    // connection, or the real push after an `amont run pre-push` rehearsal)
1902    // skips them. Only when what ran is what is being pushed: with
1903    // `amont.testPushedTree` the suite ran on the tip itself — unless the
1904    // snapshot could not be made, which `stamp_tips` asks about rather than
1905    // assuming; otherwise it ran on the working tree, which vouches for the
1906    // tip only when the two are the same content — HEAD, with nothing
1907    // modified and nothing untracked.
1908    // The same proxy `attestable` uses, for the same reason: a scoped gate
1909    // whose files the push never touched returns `Passed` having run
1910    // nothing, and a stamp for THAT would let a later push that does touch
1911    // them skip a suite nobody ran.
1912    if reuse_stamps && !ran_and_passed.is_empty() {
1913        let changed = crate::pushrefs::changed_files(ctx.push.get());
1914        let really_ran: Vec<String> = pre_push_checks
1915            .iter()
1916            .filter(|c| ran_and_passed.iter().any(|p| p == c.name()))
1917            .filter(|c| c.scope().touches(&changed))
1918            .map(|c| c.name().to_string())
1919            .collect();
1920        stamp_tips(&ctx.manifest.externals, &tips, &really_ran, &tree_at_start);
1921    }
1922    record_audits(ctx.audits, &tree_at_start);
1923    if reuse_stamps && !completed_otherwise.is_empty() {
1924        let changed = crate::pushrefs::changed_files(ctx.push.get());
1925        let really_ran: Vec<(String, crate::gate_stamp::Completion)> = completed_otherwise
1926            .into_iter()
1927            .filter(|(name, _)| {
1928                pre_push_checks
1929                    .iter()
1930                    .any(|c| c.name() == name && c.scope().touches(&changed))
1931            })
1932            .collect();
1933        record_completions(&ctx.manifest.externals, &tips, &really_ran, &tree_at_start);
1934    }
1935    // …and say so to CI, if this repository opted in.
1936    // Gated behind `enabled()` HERE, not just inside `attest_push`: reading
1937    // `ctx.push` may consume stdin, and a disabled repo should leave stdin
1938    // exactly as it found it.
1939    // Tree gates (ADR-0024) are not push checks: nothing runs here. Each is
1940    // attested only when the TREE of every pushed tip carries its commit-time
1941    // proof; a whole-tree proof needs no changed-files scope. Fail-closed:
1942    // anything else is simply not attested, and CI lints.
1943    let (tree_proven, tree_unproven) =
1944        if !ctx.manifest.tree.is_empty() && crate::attest::enabled(settings) {
1945            crate::tree_lint::await_verdict(settings, &ctx.manifest.tree, &tips, push_started)
1946        } else {
1947            (Vec::new(), Vec::new())
1948        };
1949    if !tree_unproven.is_empty() {
1950        crate::hooks::common::say(&crate::tree_lint::fit_line(
1951            "  lint not attested (cold or changed tree): ",
1952            &tree_unproven.join(" "),
1953            " — CI will lint",
1954        ));
1955    }
1956    if (!passed.is_empty() || !tree_proven.is_empty()) && crate::attest::enabled(settings) {
1957        let remote = ctx
1958            .args
1959            .first()
1960            .map(|a| a.to_string_lossy().into_owned())
1961            .unwrap_or_default();
1962        let changed = crate::pushrefs::changed_files(ctx.push.get());
1963        // Only local passes enter the laptop's attestation (ADR-0016); the
1964        // cluster's go to the linux block, which `attest_push` narrows per tip
1965        // to the trees the cluster actually judged.
1966        let (cluster_passed, local): (Vec<String>, Vec<String>) = passed
1967            .iter()
1968            .cloned()
1969            .partition(|p| crate::cluster::proved_anywhere(p));
1970        let vouched = attestable(&pre_push_checks, &local, &changed);
1971        let cluster_vouched = attestable(&pre_push_checks, &cluster_passed, &changed);
1972        // Per tip, the gates whose run saw that tip's content: the working
1973        // tree was the tip when they started, or they ran in a checkout of it
1974        // (#289; the rule `stamp_tips` applies). A tree gate's proof is the
1975        // tree's own commit-time record, so it needs no witness.
1976        let witness = TipWitness::new(&tree_at_start);
1977        let gates_for = |tip: &str| -> Vec<String> {
1978            vouched
1979                .iter()
1980                .filter(|g| witness.vouches(g, tip))
1981                .chain(tree_proven.iter())
1982                .cloned()
1983                .collect()
1984        };
1985        crate::attest::attest_push_per_tip(
1986            ctx.settings,
1987            &remote,
1988            ctx.push.get(),
1989            &gates_for,
1990            &cluster_vouched,
1991        );
1992    }
1993    // Outside the `passed` branch above on purpose: a push that changes only
1994    // documentation or its plan still carries a plan and a review to record.
1995    // holds-until: a dispatch-level test drives a push where no gate passed;
1996    // until one exists, moving this call inside that branch fails no test.
1997    if crate::attest::enabled(settings) {
1998        let remote = ctx
1999            .args
2000            .first()
2001            .map(|a| a.to_string_lossy().into_owned())
2002            .unwrap_or_default();
2003        crate::attest::provenance_push(ctx.settings, &remote, ctx.push.get());
2004    }
2005    crate::downgrade::note(settings, &downgraded);
2006    record_evidence(&tips, &evidence);
2007    Verdict::Proceed
2008}
2009
2010/// What one check's outcome is called in the record.
2011fn run_outcome(outcome: Outcome) -> crate::gate_stamp::RunOutcome {
2012    use crate::gate_stamp::RunOutcome as R;
2013    match outcome {
2014        Outcome::Passed => R::Passed,
2015        Outcome::Failed => R::Failed,
2016        Outcome::Warned => R::Warned,
2017        Outcome::Fixed => R::Fixed,
2018        Outcome::Unavailable => R::Unavailable,
2019        Outcome::Inert => R::Inert,
2020        Outcome::Deferred => R::Deferred,
2021        // Never produced at pre-push (ADR-0020); were it, it judged nothing.
2022        Outcome::Skipped => R::Inert,
2023    }
2024}
2025
2026/// The check's outcome, unless the busy policy deferred it: then Deferred,
2027/// whatever the check made of its refused spawn (ADR-0013).
2028fn deferred_or(slot: &crate::host_slots::CheckGuard, outcome: Outcome) -> Outcome {
2029    if slot.deferred().is_some() {
2030        Outcome::Deferred
2031    } else {
2032        outcome
2033    }
2034}
2035
2036/// The Heavy checks a blocking Light failure kept from starting (ADR-0020),
2037/// what blocked, and how to run each one now: `amont run` takes one name, so
2038/// one line per check, each short enough for an 80-column terminal.
2039fn announce_skipped(names: &[&str], blocked_by: &[&str]) {
2040    let names_list = names
2041        .iter()
2042        .map(|n| highlight(n))
2043        .collect::<Vec<_>>()
2044        .join(", ");
2045    match blocked_by {
2046        [one] => println!(
2047            "{} {} check(s) skipped because {} failed: {names_list}",
2048            crate::ui::skipped_sign(),
2049            names.len(),
2050            highlight(one),
2051        ),
2052        _ => println!(
2053            "{} {} check(s) skipped, a blocking check failed: {names_list}",
2054            crate::ui::skipped_sign(),
2055            names.len(),
2056        ),
2057    }
2058    println!("  fix the failures above and commit again; to run one now:");
2059    for n in names {
2060        println!("    {}", highlight(&format!("{BIN} run {n}")));
2061    }
2062}
2063
2064/// The deferral roll-up: which checks, then how to run each now and how to
2065/// stop deferring. Printed in quiet mode too, like `could not run`: a gate
2066/// skipped without a word looks exactly like a pass. Each deferred check is
2067/// advised the command that waits for its slot; the `onBusy wait` hint is
2068/// offered only for `block` checks, since a `warn` check never waits on a
2069/// commit or a push and the hint cannot stop it deferring there.
2070fn announce_deferred(deferred: &[(&str, Severity)]) {
2071    for line in deferral_advice(deferred) {
2072        println!("{line}");
2073    }
2074}
2075
2076/// The lines [`announce_deferred`] prints: the roll-up, then one `run now:`
2077/// command per deferred check (`amont run` takes one check by name, and a
2078/// `--raw` run waits for its slot under `AMONT_ON_BUSY=wait`, warn or block),
2079/// then the `onBusy wait` hint only when a `block` check is in the list,
2080/// since only a `block` check stops deferring under it.
2081fn deferral_advice(deferred: &[(&str, Severity)]) -> Vec<String> {
2082    let names: Vec<&str> = deferred.iter().map(|(name, _)| *name).collect();
2083    let mut lines = vec![format!(
2084        "{} {} check(s) deferred to CI, no host slot freed: {}",
2085        warning_sign(),
2086        names.len(),
2087        names.join(", ")
2088    )];
2089    let mut any_block = false;
2090    for (name, severity) in deferred {
2091        match severity {
2092            Severity::Block => any_block = true,
2093            Severity::Warn => {}
2094        }
2095        lines.push(format!(
2096            "  run now: {}",
2097            highlight(&format!("AMONT_ON_BUSY=wait {BIN} run --raw {name}"))
2098        ));
2099    }
2100    if any_block {
2101        lines.push(format!(
2102            "  stop deferring the block checks: {}",
2103            highlight("set onBusy wait")
2104        ));
2105    }
2106    lines
2107}
2108
2109/// File this push's runs under the content they judged.
2110///
2111/// ONE key, not one per tip: a push of two branches ran each gate once, and
2112/// writing the same run onto both trees would make a report count it twice.
2113/// The first tip's tree is that key, falling back to `HEAD` — and to nothing
2114/// at all when git will not name either, which costs a row in a report and
2115/// never a verdict.
2116fn record_evidence(tips: &[String], runs: &[crate::gate_stamp::Run]) {
2117    if runs.is_empty() {
2118        return;
2119    }
2120    let tree = tips
2121        .first()
2122        .and_then(|tip| crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]))
2123        .or_else(|| crate::git::stdout(&["rev-parse", "HEAD^{tree}"]));
2124    if let Some(tree) = tree {
2125        crate::gate_stamp::record_runs(&tree, runs);
2126    }
2127}
2128
2129/// Is `check` a push gate that runs before git connects, and is stamped for
2130/// it (ADR-0018)? A scoped one, or a declared `heavy` one whatever its scope:
2131/// a `*` declaration can be any command, and one that runs for a minute on
2132/// the open connection is the failure ADR-0018 exists to stop (#414). The
2133/// built-in unscoped checks (branch-protect, secrets) are light and need the
2134/// push's own refs, so they stay in the hook; the dependency audits answer
2135/// through their own record.
2136pub fn stamped_push_gate(check: &dyn Check) -> bool {
2137    !crate::hooks::audit::is_audit(check.name())
2138        && (!check.scope().is_unscoped() || check.weight() == crate::host_slots::Weight::Heavy)
2139}
2140
2141/// The stamped pre-push gates ([`stamped_push_gate`]) — test suites, and
2142/// declared heavy gates — that have work to do for a push that changed
2143/// `changed`: what a rehearsal would run, and therefore what its stamp would
2144/// have to name before a push may skip anything.
2145///
2146/// The same two filters `pre_push` applies before stamping (selected here,
2147/// and `scope().touches` the change), so the rehearsal's idea of "nothing to
2148/// do" is the push's idea of "nothing to stamp".
2149pub fn scoped_push_gates(
2150    settings: &crate::config::Settings,
2151    manifest: &crate::manifest::Manifest,
2152    changed: &[String],
2153) -> Vec<String> {
2154    let in_progress = crate::git_states_in_progress();
2155    let tracked = crate::tracked_paths();
2156    selected_during(settings, Stage::PrePush, &in_progress, manifest)
2157        .into_iter()
2158        .filter(|c| stamped_push_gate(*c) && c.scope().touches(changed))
2159        // The same opt-in gate `pre_push` applies: a suite the repository
2160        // never turned on is not work a rehearsal owes a stamp for.
2161        .filter(|c| c.scope().opted_in(&tracked))
2162        .map(|c| c.name().to_string())
2163        .collect()
2164}
2165
2166/// The dependency audits a push of `refs` owes (ADR-0018): opted in, and
2167/// with no fresh record for the pushed commits in the push's mode. Owed
2168/// whatever the range touches, unlike `scoped_push_gates`.
2169pub fn owed_audits(
2170    settings: &crate::config::Settings,
2171    manifest: &crate::manifest::Manifest,
2172    ledger: &crate::hooks::audit::Ledger,
2173    refs: &[crate::pushrefs::PushRef],
2174) -> Vec<String> {
2175    let in_progress = crate::git_states_in_progress();
2176    let tracked = crate::tracked_paths();
2177    selected_during(settings, Stage::PrePush, &in_progress, manifest)
2178        .into_iter()
2179        .filter(|c| crate::hooks::audit::is_audit(c.name()))
2180        .filter(|c| c.scope().opted_in(&tracked))
2181        .filter(|c| crate::hooks::audit::owed(settings, ledger, c.name(), refs))
2182        .map(|c| c.name().to_string())
2183        .collect()
2184}
2185
2186/// Push-stamp every tip whose content is what the gates actually tested.
2187///
2188/// See the comment at the call site for the two cases. Silent when nothing
2189/// qualifies — a dirty working tree is the ordinary state of a machine
2190/// mid-work, and a note on every push would teach people to ignore it.
2191fn stamp_tips(
2192    externals: &[crate::manifest::External],
2193    tips: &[String],
2194    gates: &[String],
2195    tree_at_start: &str,
2196) {
2197    let witness = TipWitness::new(tree_at_start);
2198    // TRACKED modifications only — a KNOWN gap, kept deliberately, and
2199    // spelled out because the comment that used to sit here argued it
2200    // backwards ("untracked files are not in any tree the suite could have
2201    // been asked about"). That is not the reason. The danger is not that the
2202    // tree lacks them, it is that the RUN had them: a new test file, a
2203    // fixture, a local `.env`, present while the suite ran and absent from
2204    // the tree the stamp vouches for.
2205    //
2206    // Counting them was tried, and is worse than the gap. Gates leave
2207    // artefacts — a log, a coverage directory, whatever a declared
2208    // `amont.conf` command writes — and nothing cleans them up, so a
2209    // repository using declared gates would stop earning stamps permanently
2210    // after its first commit. That does not merely lose an optimisation: it
2211    // puts the suite back INSIDE the push, which is the failure the whole
2212    // stamping mechanism exists to prevent. amont's own push flow
2213    // (`flows/push.rs`, steps `first push` and `retry`) is exactly that
2214    // shape, and CI is where it surfaced — a `*.log` line in one developer's
2215    // global gitignore had hidden it on the machine that wrote the change.
2216    //
2217    // `amont.testPushedTree true` closes the gap properly for anyone who
2218    // wants it closed: it runs the suite in a checkout of the commit, where
2219    // no untracked file exists to be read.
2220    //
2221    // `tree_at_start` — not a fresh `git status`. The gates have run by now
2222    // and may have written into the tree; what a stamp needs to know is what
2223    // the suite could READ, which is the state it was handed. See the
2224    // capture in `pre_push`.
2225    let mut stamped: Vec<String> = Vec::new();
2226    for tip in tips {
2227        // PER GATE, from what each one actually did — not from the config.
2228        // `amont.testPushedTree` is a request; `pushed_tree::ran_on_tip` is
2229        // the record of which gates were handed a checkout of this tip. A
2230        // gate that ran somewhere else (a snapshot that could not be made,
2231        // or a check that ran in the working tree) may vouch for the tip
2232        // only when the working tree WAS the tip. Deciding from the flag
2233        // stamped every passing gate onto a tip that one of them had never
2234        // seen.
2235        let vouched: Vec<String> = gates
2236            .iter()
2237            .filter(|g| witness.vouches(g, tip))
2238            .cloned()
2239            .collect();
2240        if vouched.is_empty() {
2241            continue;
2242        }
2243        let spec = format!("{tip}^{{tree}}");
2244        let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
2245            continue;
2246        };
2247        // A gate the cluster proved on this tree is already recorded in its
2248        // own ref: a local push stamp would let the laptop vouch for it.
2249        let vouched: Vec<String> = vouched
2250            .into_iter()
2251            .filter(|g| !crate::cluster::proved(g, &tree))
2252            .collect();
2253        // Tokens, not names; a gate with no identity is not stamped.
2254        let tokens: Vec<String> = vouched
2255            .iter()
2256            .filter_map(|g| crate::gate_identity::token(externals, g))
2257            .collect();
2258        if crate::gate_stamp::stamp_push(tip, &tree, &tokens) {
2259            for g in vouched {
2260                if !stamped.contains(&g) {
2261                    stamped.push(g);
2262                }
2263            }
2264        }
2265    }
2266    if !stamped.is_empty() {
2267        crate::say!(
2268            "{} stamped {} for this tree — the next push of it skips them ({})",
2269            valid_sign(),
2270            highlight(&stamped.join(" ")),
2271            crate::gate_stamp::NOTES_REF,
2272        );
2273    }
2274}
2275
2276/// Write the audit records this push produced (ADR-0018), only for a commit
2277/// the working tree IS: HEAD, inside a rehearsal snapshot or with a clean
2278/// worktree — the tools read the working tree, not the commit.
2279fn record_audits(ledger: &crate::hooks::audit::Ledger, tree_at_start: &str) {
2280    let pending = ledger.take_pending();
2281    if pending.is_empty() {
2282        return;
2283    }
2284    let witness = TipWitness::new(tree_at_start);
2285    for record in pending {
2286        if !witness.tree_is_tip(&record.tip) {
2287            continue;
2288        }
2289        if let Err(why) = crate::hooks::audit::write_pending(&record) {
2290            crate::hooks::common::warn(&format!(
2291                "{why} — the next push of this tree owes the audit again"
2292            ));
2293        }
2294    }
2295}
2296
2297/// Record the gates that completed without passing (ADR-0018), on exactly the
2298/// tips `stamp_tips` would stamp: a tip whose content is what the gates ran
2299/// on — HEAD, inside a rehearsal snapshot or with a clean worktree. One note
2300/// write per tree and kind of completion.
2301fn record_completions(
2302    externals: &[crate::manifest::External],
2303    tips: &[String],
2304    gates: &[(String, crate::gate_stamp::Completion)],
2305    tree_at_start: &str,
2306) {
2307    if gates.is_empty() {
2308        return;
2309    }
2310    let witness = TipWitness::new(tree_at_start);
2311    let mut by_kind: Vec<(crate::gate_stamp::Completion, Vec<String>)> = Vec::new();
2312    for (gate, how) in gates {
2313        let Some(token) = crate::gate_identity::token(externals, gate) else {
2314            continue;
2315        };
2316        match by_kind.iter_mut().find(|(kind, _)| kind == how) {
2317            Some((_, tokens)) => tokens.push(token),
2318            None => by_kind.push((*how, vec![token])),
2319        }
2320    }
2321    for tip in tips {
2322        if !witness.tree_is_tip(tip) {
2323            continue;
2324        }
2325        let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]) else {
2326            continue;
2327        };
2328        for (how, tokens) in &by_kind {
2329            if let Err(why) = crate::gate_stamp::record_done(&tree, tokens, *how) {
2330                crate::hooks::common::warn(&format!(
2331                    "{why} — the next push of this tree owes those gates again"
2332                ));
2333            }
2334        }
2335    }
2336}
2337
2338/// Of the checks that passed, the ones an attestation may actually VOUCH for.
2339///
2340/// A language gate whose scope the push never touched returns `Passed` having
2341/// run nothing — `cargo_test` walks its refs, finds no crate root, and falls
2342/// out of the loop green. That is right for a push gate (there was nothing to
2343/// object to) and wrong for an attestation: a JS-only push was minting
2344/// `gates … pre-push-cargo-test pre-push-go-test pre-push-pytest`, and in a
2345/// MIXED repository CI would then skip a suite that nobody ran on that tree.
2346///
2347/// The declared `scope` is the honest filter, and the same data `amont list`
2348/// already reports. Unscoped checks (`Scope::ALWAYS` — branch-protect,
2349/// secrets) match everything and are vouched for, which is accurate: they
2350/// really did run. An empty `changed` vouches for nothing scoped, which is
2351/// the safe direction — CI runs the suite.
2352///
2353/// [`Scope::touches`], NOT `Scope::matches`. `matches` also asks whether the
2354/// repository has opted in — whether a `Cargo.toml` exists — and asking that
2355/// of a push DIFF can only answer no unless the push happened to touch the
2356/// marker. So `pre-push-cargo-test` was vouched for by a push that edited
2357/// `Cargo.toml` and never by one that edited only `.rs` files, which is the
2358/// ordinary case and the one worth skipping CI for. The feature attested
2359/// almost nothing, silently, and looked like it worked.
2360///
2361/// WHAT THIS IS STILL A PROXY FOR, stated plainly because the trust path
2362/// deserves it: the honest question is "did this gate actually run", and no
2363/// gate reports that. `rust_tools::test` returns `Passed` whether it ran a
2364/// suite or found no crate root and fell out of its loop — the very thing
2365/// the first paragraph describes. Scope is the closest available stand-in.
2366/// It is now a good one: a gate is vouched for only if the push changed a
2367/// file its extensions cover.
2368///
2369/// The gap that remains is narrow and one-directional: a `.rs` file outside
2370/// every crate would be covered here while `cargo test` had nothing to say
2371/// about it. Closing it properly means an outcome that distinguishes "ran
2372/// and passed" from "found nothing to do", which is a change to every gate
2373/// and to `Outcome` itself — worth doing, not worth smuggling into this.
2374/// Which pushed tips a gate's run in this process saw (#289): the working
2375/// tree was the tip when the gates started, or the gate ran in a checkout of
2376/// it (`pushed_tree::ran_on_tip`). Shared by the push stamps and the
2377/// attestation, so the two never disagree about what was tested.
2378struct TipWitness {
2379    head: Option<String>,
2380    /// The working tree held HEAD's content when the gates started: clean
2381    /// of tracked changes, or a rehearsal snapshot. A snapshot is a checkout
2382    /// git made of the commit, and whatever `amont.snapshotPrepare` added to
2383    /// make it runnable (a `node_modules`, a virtualenv) is not a reason to
2384    /// distrust it.
2385    tree_is_head: bool,
2386}
2387
2388impl TipWitness {
2389    fn new(tree_at_start: &str) -> Self {
2390        Self::from_parts(
2391            crate::git::stdout(&["rev-parse", "HEAD"]),
2392            crate::rehearsal::in_snapshot(),
2393            tree_at_start,
2394        )
2395    }
2396
2397    fn from_parts(head: Option<String>, in_snapshot: bool, tree_at_start: &str) -> Self {
2398        TipWitness {
2399            head,
2400            tree_is_head: in_snapshot || tree_at_start.trim().is_empty(),
2401        }
2402    }
2403
2404    /// The working tree was `tip` when the gates started.
2405    fn tree_is_tip(&self, tip: &str) -> bool {
2406        self.tree_is_head && self.head.as_deref() == Some(tip)
2407    }
2408
2409    fn vouches(&self, gate: &str, tip: &str) -> bool {
2410        self.tree_is_tip(tip) || crate::pushed_tree::ran_on_tip(gate, tip)
2411    }
2412}
2413
2414fn attestable(checks: &[&dyn Check], passed: &[String], changed: &[String]) -> Vec<String> {
2415    checks
2416        .iter()
2417        .filter(|c| passed.iter().any(|p| p == c.name()))
2418        .filter(|c| c.scope().touches(changed))
2419        .map(|c| c.name().to_string())
2420        .collect()
2421}
2422
2423#[cfg(test)]
2424mod tests {
2425    use super::*;
2426    use crate::check::{Builtin, Scope};
2427    use std::sync::atomic::{AtomicUsize, Ordering};
2428
2429    /// #289: a dirty working tree witnesses no tip, even HEAD; a clean one,
2430    /// or a snapshot, witnesses HEAD only.
2431    #[test]
2432    fn only_a_clean_head_or_a_snapshot_witnesses_a_tip() {
2433        let head = Some("a".repeat(40));
2434        let tip = "a".repeat(40);
2435        let other = "b".repeat(40);
2436        let dirty = TipWitness::from_parts(head.clone(), false, " M src/lib.rs\n");
2437        assert!(!dirty.tree_is_tip(&tip));
2438        let clean = TipWitness::from_parts(head.clone(), false, "");
2439        assert!(clean.tree_is_tip(&tip));
2440        assert!(!clean.tree_is_tip(&other));
2441        let snapshot = TipWitness::from_parts(head, true, " M node_modules/x\n");
2442        assert!(snapshot.tree_is_tip(&tip));
2443    }
2444
2445    /// ADR-0018: the refusals fit 80 columns, put each command on its own
2446    /// line, and name only amont's own commands (every Green Harness part is
2447    /// optional: amont runs without relais, the skills or amont-agent).
2448    #[test]
2449    fn the_push_refusals_fit_and_name_only_amont() {
2450        let many: Vec<String> = (0..12)
2451            .map(|i| format!("pre-push-gate-number-{i}"))
2452            .collect();
2453        let names: Vec<&str> = many.iter().map(String::as_str).collect();
2454        let refs = vec![crate::pushrefs::PushRef {
2455            local_ref: "refs/heads/x".into(),
2456            local_oid: "a".repeat(40),
2457            remote_ref: "refs/heads/x".into(),
2458            remote_oid: "b".repeat(40),
2459        }];
2460        let sets = [
2461            push_refusal("abcdef12", &names, StampReuse::On, None),
2462            push_refusal("abcdef12", &names, StampReuse::Off, None),
2463            land_refusal(
2464                &crate::rehearsal::LandLine {
2465                    sha: "a".repeat(40),
2466                    remote_tip: "b".repeat(40),
2467                },
2468                &refs,
2469                &names,
2470            ),
2471            land_refusal(
2472                &crate::rehearsal::LandLine {
2473                    sha: "a".repeat(40),
2474                    remote_tip: "c".repeat(40),
2475                },
2476                &refs,
2477                &names,
2478            ),
2479            push_refusal(
2480                "abcdef12",
2481                &names,
2482                StampReuse::On,
2483                Some("v12.345.6789-rc.1+build.2026-11-05"),
2484            ),
2485        ];
2486        for lines in &sets {
2487            for line in lines {
2488                assert!(line.chars().count() <= 80, "{line:?}");
2489                for foreign in ["relais", "skill", "amont-agent"] {
2490                    assert!(!line.contains(foreign), "{line:?}");
2491                }
2492            }
2493            let joined = lines.join("\n");
2494            for name in &names {
2495                assert!(joined.contains(name), "every gate is named: {joined}");
2496            }
2497        }
2498        assert!(sets[0].iter().any(|l| l.ends_with(&format!("{BIN} land"))));
2499        assert!(sets[0]
2500            .iter()
2501            .any(|l| l.ends_with(&format!("{BIN} rehearse --wait"))));
2502        assert!(
2503            !sets[1].iter().any(|l| l.contains("rehearse")),
2504            "{:?}",
2505            sets[1]
2506        );
2507        assert!(sets[1].iter().any(|l| l.contains("amont.pushStamps true")));
2508        assert!(sets[1].iter().any(|l| l.ends_with(&format!("{BIN} land"))));
2509        assert_eq!(sets[2][0], crate::land::LAND_EVIDENCE_MISSING);
2510        assert_eq!(sets[3][0], crate::land::LAND_REMOTE_MOVED);
2511        assert!(sets[0][0].starts_with(&format!("{BIN}: push refused:")));
2512        // A tag push is offered the tag's own land, never the branch remedies.
2513        assert!(
2514            sets[4].iter().any(|l| l.ends_with(&format!(
2515                "{BIN} land --tag v12.345.6789-rc.1+build.2026-11-05"
2516            ))),
2517            "{:?}",
2518            sets[4]
2519        );
2520        assert!(
2521            !sets[4].iter().any(|l| l.contains("rehearse")),
2522            "{:?}",
2523            sets[4]
2524        );
2525    }
2526
2527    /// A check whose only job is to carry a name and a severity into `report`.
2528    /// Its `run` is never called — `report` is fed outcomes directly, which is
2529    /// what makes `Unavailable` testable at all: the real thing needs a missing
2530    /// binary, and a test that uninstalls the developer's toolchain is worse
2531    /// than no test.
2532    const fn stub(name: &'static str, severity: Severity) -> Builtin {
2533        Builtin {
2534            name,
2535            stage: Stage::PreCommit,
2536            scope: Scope::ALWAYS,
2537            severity,
2538            run: |_| Outcome::Passed,
2539            fix: crate::check::Fix::None,
2540            reach: crate::check::Reach::Convention,
2541        }
2542    }
2543
2544    /// A pre-push gate with an OPT-IN file, as the real Rust and Python
2545    /// gates have: `.rs` files, but only where a `Cargo.toml` exists.
2546    const fn opt_in(
2547        name: &'static str,
2548        exts: &'static [&'static str],
2549        names: &'static [&'static str],
2550    ) -> Builtin {
2551        Builtin {
2552            name,
2553            stage: Stage::PrePush,
2554            scope: Scope::new(exts, names),
2555            severity: Severity::Block,
2556            run: |_| Outcome::Passed,
2557            fix: crate::check::Fix::None,
2558            reach: crate::check::Reach::Convention,
2559        }
2560    }
2561
2562    /// A pre-push gate scoped to one language's files.
2563    const fn scoped(name: &'static str, exts: &'static [&'static str]) -> Builtin {
2564        Builtin {
2565            name,
2566            stage: Stage::PrePush,
2567            scope: Scope::new(exts, &[]),
2568            severity: Severity::Block,
2569            run: |_| Outcome::Passed,
2570            fix: crate::check::Fix::None,
2571            reach: crate::check::Reach::Convention,
2572        }
2573    }
2574
2575    /// The over-claim this filter exists to stop, caught in the wild: a
2576    /// JS-only push minted `gates … pre-push-cargo-test pre-push-go-test
2577    /// pre-push-pytest`, because each of those gates finds nothing of its
2578    /// language to do and returns `Passed` having run NOTHING. Harmless in a
2579    /// single-language repo, unsound in a mixed one — CI would skip a suite
2580    /// nobody ran on that tree.
2581    #[test]
2582    fn a_gate_whose_language_the_push_never_touched_is_not_vouched_for() {
2583        let js = scoped("pre-push-run-tests-js", &[".ts", ".js"]);
2584        let rust = scoped("pre-push-cargo-test", &[".rs"]);
2585        let py = scoped("pre-push-pytest", &[".py"]);
2586        let always = stub("pre-push-secrets", Severity::Block);
2587        let checks: Vec<&dyn Check> = vec![&js, &rust, &py, &always];
2588        let passed: Vec<String> = checks.iter().map(|c| c.name().to_string()).collect();
2589
2590        let changed = vec!["app/routes/home.ts".to_string()];
2591        let vouched = attestable(&checks, &passed, &changed);
2592        assert_eq!(
2593            vouched,
2594            vec![
2595                "pre-push-run-tests-js".to_string(),
2596                "pre-push-secrets".to_string()
2597            ],
2598            "only the gate that had work, plus the unscoped one that always runs"
2599        );
2600
2601        // Nothing computed about the push vouches for nothing scoped — the
2602        // safe direction, since CI then runs the suite.
2603        assert_eq!(
2604            attestable(&checks, &passed, &[]),
2605            vec!["pre-push-secrets".to_string()]
2606        );
2607
2608        // A check that did NOT pass is never vouched for, whatever its scope.
2609        let only_rust_passed = vec!["pre-push-cargo-test".to_string()];
2610        assert!(attestable(&checks, &only_rust_passed, &changed).is_empty());
2611    }
2612
2613    /// No overrides configured. `report` takes them as a VALUE now, so its
2614    /// tests need no repository and no git at all.
2615    fn none() -> Overrides {
2616        Overrides::default()
2617    }
2618
2619    static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
2620    static WARNER: Builtin = stub("stub-warner", Severity::Warn);
2621
2622    /// The unit tests hold `&dyn Check` for the same reason the dispatcher
2623    /// does: `report` must not be able to tell a built-in from an external.
2624    const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
2625        [cs[0], cs[1], cs[2]]
2626    }
2627
2628    /// The classification itself, which used to be unreachable: while one
2629    /// function classified AND printed AND returned a code, a test could assert
2630    /// the code and nothing else.
2631    #[test]
2632    fn every_outcome_lands_in_the_right_bucket() {
2633        let checks: [&dyn Check; 5] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER, &BLOCKER];
2634        let got = classify(
2635            &checks,
2636            &[
2637                Outcome::Passed,
2638                Outcome::Unavailable,
2639                Outcome::Failed,
2640                Outcome::Failed,
2641                Outcome::Inert,
2642            ],
2643            &none(),
2644        );
2645        assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
2646        assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
2647        assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
2648        assert_eq!(got.passed, 1, "inert is not a pass: {got:?}");
2649    }
2650
2651    /// A clean stage concludes nothing at all — not an empty message, no
2652    /// message. Twenty checks that passed should print no roll-ups.
2653    ///
2654    /// `passed` is a tally, not a roll-up. It exists so that `amont.quiet` can
2655    /// say how many lines it swallowed, and it must never be the reason this
2656    /// report looks like it has something to announce.
2657    #[test]
2658    fn a_clean_stage_has_nothing_to_report() {
2659        let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
2660        let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
2661        assert!(
2662            got.fixed.is_empty()
2663                && got.blocked.is_empty()
2664                && got.downgraded.is_empty()
2665                && got.unavailable.is_empty(),
2666            "a clean stage found something to announce: {got:?}"
2667        );
2668        assert_eq!(got.passed, 1, "the pass was not tallied: {got:?}");
2669        assert_eq!(got.verdict(), Verdict::Proceed);
2670    }
2671
2672    #[test]
2673    fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
2674        let b: &dyn Check = &BLOCKER;
2675        let w: &dyn Check = &WARNER;
2676        assert_eq!(
2677            classify(&[b], &[Outcome::Failed], &none()).verdict(),
2678            Verdict::Block
2679        );
2680        assert_eq!(
2681            classify(&[b], &[Outcome::Passed], &none()).verdict(),
2682            Verdict::Proceed
2683        );
2684        // Every non-blocking shape, one at a time, so a regression cannot hide
2685        // behind a passing sibling.
2686        assert_eq!(
2687            classify(&[b], &[Outcome::Warned], &none()).verdict(),
2688            Verdict::Proceed
2689        );
2690        assert_eq!(
2691            classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
2692            Verdict::Proceed
2693        );
2694        assert_eq!(
2695            classify(&[w], &[Outcome::Failed], &none()).verdict(),
2696            Verdict::Proceed
2697        );
2698        // A skipped Heavy check never blocks by itself: the Light failure
2699        // that skipped it does (ADR-0020). It is listed, never counted passed.
2700        let skipped = classify(&[b], &[Outcome::Skipped], &none());
2701        assert_eq!(skipped.verdict(), Verdict::Proceed);
2702        assert_eq!(skipped.skipped, vec![b.name()]);
2703        assert_eq!(skipped.passed, 0);
2704    }
2705
2706    #[test]
2707    fn the_environment_word_on_fail_fast_wins_and_a_bad_one_falls_back() {
2708        let settings = crate::config::Settings::default();
2709        assert!(!resolve_fail_fast(Some("false"), &settings));
2710        assert!(!resolve_fail_fast(Some("0"), &settings));
2711        assert!(resolve_fail_fast(Some("TRUE"), &settings));
2712        // Unset or unreadable: the configured value, here the default.
2713        assert!(resolve_fail_fast(None, &settings));
2714        assert!(resolve_fail_fast(Some(""), &settings));
2715        assert!(resolve_fail_fast(Some("sometimes"), &settings));
2716    }
2717
2718    #[test]
2719    fn one_blocking_failure_among_many_still_fails() {
2720        let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
2721        assert_eq!(
2722            classify(
2723                &checks,
2724                &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
2725                &none()
2726            )
2727            .verdict(),
2728            Verdict::Block
2729        );
2730        // Same shape, with the only *blocking* failure removed.
2731        assert_eq!(
2732            classify(
2733                &checks,
2734                &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
2735                &none()
2736            )
2737            .verdict(),
2738            Verdict::Proceed
2739        );
2740    }
2741
2742    /// The slot of a check whose thread died. Reading that as a pass is how a
2743    /// crash becomes a green commit.
2744    ///
2745    /// Asserted through the RUNNER, not through a `Default` impl: the rule
2746    /// belongs to this call site, and a test on `Outcome::default()` proved
2747    /// only that a trait impl existed, not that the runner used it.
2748    /// A check that PANICS must fail the commit, not pass it — and must not
2749    /// take the other checks down with it.
2750    ///
2751    /// Driven through the stage body rather than the runner, because the value
2752    /// that stands in for a dead check is chosen at the call site and the
2753    /// runner's own test cannot see that choice.
2754    #[test]
2755    fn a_panicking_check_blocks_the_commit() {
2756        static DIES: Builtin = Builtin {
2757            name: "stub-dies",
2758            stage: Stage::PreCommit,
2759            scope: Scope::ALWAYS,
2760            severity: Severity::Block,
2761            run: |_| panic!("this check died"),
2762            fix: crate::check::Fix::None,
2763            reach: crate::check::Reach::Convention,
2764        };
2765        let hook = std::panic::take_hook();
2766        std::panic::set_hook(Box::new(|_| {}));
2767        let push = crate::pushrefs::PushRefs::default();
2768        let manifest = crate::manifest::Manifest::default();
2769        let settings = crate::config::Settings::default();
2770        let ctx = Ctx {
2771            name: "pre-commit",
2772            args: &[],
2773            hooks_dir: std::path::Path::new("."),
2774            push: &push,
2775            manifest: &manifest,
2776            settings: &settings,
2777            handed_to_cluster: &[],
2778            land: &crate::rehearsal::LandEnv::Absent,
2779            audits: &Default::default(),
2780            source_worktree: None,
2781        };
2782        let verdict = run_stage(&[&DIES], &ctx, &none());
2783        std::panic::set_hook(hook);
2784        assert_eq!(
2785            verdict,
2786            Verdict::Block,
2787            "a check that died must not let the commit through"
2788        );
2789    }
2790
2791    #[test]
2792    fn a_thread_that_dies_leaves_a_failure_behind() {
2793        // The default hook would print a backtrace for the deliberate panic and
2794        // make a passing run look broken.
2795        let hook = std::panic::take_hook();
2796        std::panic::set_hook(Box::new(|_| {}));
2797        let items = ["a", "b", "c"];
2798        let out = run_concurrently(
2799            &items,
2800            |n: &&str| {
2801                if *n == "b" {
2802                    panic!("this check died");
2803                }
2804                Outcome::Passed
2805            },
2806            Outcome::Failed,
2807        );
2808        std::panic::set_hook(hook);
2809        assert_eq!(
2810            out,
2811            vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
2812            "a dead check must not read as one that passed, \
2813             and must not take the other checks down with it"
2814        );
2815    }
2816    use std::time::{Duration, Instant};
2817
2818    /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
2819    /// observe all the others arrive. Were the runner serial, the first task
2820    /// would wait alone, time out, and return non-zero — a failure, not a hang.
2821    #[test]
2822    fn run_concurrently_actually_overlaps() {
2823        static ARRIVED: AtomicUsize = AtomicUsize::new(0);
2824        ARRIVED.store(0, Ordering::SeqCst);
2825        let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
2826        let n = names.len();
2827
2828        let out = run_concurrently(
2829            &names,
2830            move |_: &&str| {
2831                ARRIVED.fetch_add(1, Ordering::SeqCst);
2832                let deadline = Instant::now() + Duration::from_secs(10);
2833                while ARRIVED.load(Ordering::SeqCst) < n {
2834                    if Instant::now() > deadline {
2835                        return 1; // never met the others — execution was serial
2836                    }
2837                    std::thread::yield_now();
2838                }
2839                0
2840            },
2841            1,
2842        );
2843        assert!(
2844            out.iter().all(|c| *c == 0),
2845            "tasks did not overlap: {out:?}"
2846        );
2847    }
2848
2849    #[test]
2850    fn results_come_back_in_input_order() {
2851        let names: Vec<&'static str> = vec!["first", "second", "third"];
2852        let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
2853        assert_eq!(out, vec![0, 7, 0], "results keep the input order");
2854    }
2855
2856    /// The filter calls the shared resolver rather than restating it. This test
2857    /// used to inline `n.contains(s)` — its own copy of the rule — and so went
2858    /// on passing after the rule changed underneath it.
2859    #[test]
2860    fn skips_are_filtered_by_the_shared_resolver() {
2861        let all = ["pre-commit-ruff", "pre-commit-prettier"];
2862        let skips = ["ruff".to_string()];
2863        let kept: Vec<_> = all
2864            .iter()
2865            .copied()
2866            .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
2867            .collect();
2868        assert_eq!(kept, vec!["pre-commit-prettier"]);
2869    }
2870
2871    /// The ordinary Rust push: source changed, `Cargo.toml` untouched.
2872    ///
2873    /// This test used to assert the OPPOSITE, and said so — it pinned
2874    /// `attestable` filtering on `Scope::matches`, which also asks whether
2875    /// the repository has opted in. Asking that of a push diff meant a
2876    /// `.rs`-only push, in a repository with a `Cargo.toml` sitting right
2877    /// there, attested nothing. Since that is what nearly every Rust push
2878    /// looks like, the feature was attesting almost nothing at all — quietly,
2879    /// while appearing to work.
2880    #[test]
2881    fn an_ordinary_source_push_is_vouched_for() {
2882        let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
2883        let checks: Vec<&dyn Check> = vec![&rust];
2884        let passed = vec!["pre-push-cargo-test".to_string()];
2885
2886        let changed = vec!["crates/greengate/src/main.rs".to_string()];
2887        assert_eq!(
2888            attestable(&checks, &passed, &changed),
2889            vec!["pre-push-cargo-test".to_string()],
2890            "a push that changed Rust must vouch for the Rust gate"
2891        );
2892
2893        // And still when the marker IS in the diff — the opt-in file is not
2894        // required, but it is not disqualifying either.
2895        let changed = vec![
2896            "crates/greengate/src/main.rs".to_string(),
2897            "Cargo.toml".to_string(),
2898        ];
2899        assert_eq!(
2900            attestable(&checks, &passed, &changed),
2901            vec!["pre-push-cargo-test".to_string()]
2902        );
2903    }
2904
2905    /// The over-claim the filter exists to stop, with an opt-in gate: a
2906    /// JS-only push must not vouch for the Rust suite, whatever files the
2907    /// repository contains.
2908    ///
2909    /// This is the half of the contract the fix above must not have broken,
2910    /// and it is the reason `touches` asks about EXTENSIONS rather than
2911    /// dropping the scope test altogether.
2912    #[test]
2913    fn an_opt_in_gate_is_not_vouched_for_by_a_push_in_another_language() {
2914        let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
2915        let checks: Vec<&dyn Check> = vec![&rust];
2916        let passed = vec!["pre-push-cargo-test".to_string()];
2917
2918        for changed in [
2919            vec!["app/routes/home.ts".to_string()],
2920            // Even the marker alone: editing Cargo.toml changes no Rust
2921            // source, so the suite has nothing new to have verified.
2922            vec!["Cargo.toml".to_string()],
2923            vec![],
2924        ] {
2925            assert!(
2926                attestable(&checks, &passed, &changed).is_empty(),
2927                "must not vouch for the Rust gate on {changed:?}"
2928            );
2929        }
2930    }
2931
2932    /// amont #431: `onBusy wait` cannot stop a `warn` gate deferring, so a
2933    /// list of warn gates is advised only the command that waits, once per
2934    /// gate, and the hint is never offered.
2935    #[test]
2936    fn deferred_warn_gates_are_each_advised_the_command_that_waits() {
2937        let lines = deferral_advice(&[
2938            ("pre-push-probe", Severity::Warn),
2939            ("pre-push-lint", Severity::Warn),
2940        ]);
2941        let said = lines.join("\n");
2942        assert!(said.contains("2 check(s) deferred to CI"), "{said}");
2943        for gate in ["pre-push-probe", "pre-push-lint"] {
2944            assert!(
2945                said.contains(&format!("AMONT_ON_BUSY=wait {BIN} run --raw {gate}")),
2946                "{said}"
2947            );
2948        }
2949        assert!(!said.contains("set onBusy wait"), "{said}");
2950    }
2951
2952    /// A list mixing a `block` and a `warn` gate: both get their command,
2953    /// and the `onBusy wait` hint says it stops only the block checks.
2954    #[test]
2955    fn a_mixed_deferral_names_every_gate_and_scopes_the_hint() {
2956        let lines = deferral_advice(&[
2957            ("pre-push-probe", Severity::Warn),
2958            ("pre-push-cargo-test", Severity::Block),
2959        ]);
2960        let said = lines.join("\n");
2961        for gate in ["pre-push-probe", "pre-push-cargo-test"] {
2962            assert!(
2963                said.contains(&format!("AMONT_ON_BUSY=wait {BIN} run --raw {gate}")),
2964                "{said}"
2965            );
2966        }
2967        let hint = lines
2968            .iter()
2969            .find(|l| l.contains("set onBusy wait"))
2970            .expect("the hint, for the block gate");
2971        assert!(hint.contains("block checks"), "{hint}");
2972        assert_eq!(lines.len(), 4, "roll-up, two commands, one hint: {said}");
2973    }
2974}