Skip to main content

amont_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/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::registry::{all_stage_checks, Ctx, Overrides};
34use crate::ui::{highlight, valid_sign, warning_sign};
35
36/// The checks for a stage, minus anything `hook.skip` filters out. Resolution
37/// goes through `names_check`, the one rule this and the severity lookup share:
38/// `git config hook.skip ruff` skips `pre-commit-ruff` by short name.
39fn selected<'a>(
40    settings: &crate::config::Settings,
41    stage: Stage,
42    manifest: &'a crate::manifest::Manifest,
43) -> Vec<&'a dyn Check> {
44    selected_during(settings, stage, &[], manifest)
45}
46
47/// Do this repository's hooks apply the CONVENTIONS, or only the safety net?
48///
49/// `git config amont.conventions declared` (usually `--global`, set by
50/// `amont enroll`) scopes the house rules to repositories that commit an
51/// `amont.conf` — the standing grant of `init.templateDir` then becomes safe
52/// to hand a whole team: a clone of somebody else's project gets conflict,
53/// secret, size and debug-leftover protection, and none of this team's
54/// opinions about commit subjects or branch names. The default,
55/// `everywhere`, keeps today's behaviour exactly.
56///
57/// Presence of the manifest is the declaration; its CONTENT stays
58/// trust-gated. Reading presence executes nothing, so no consent is needed.
59pub fn conventions_apply(
60    settings: &crate::config::Settings,
61    manifest: &crate::manifest::Manifest,
62) -> bool {
63    manifest.declared || !declared_mode(settings)
64}
65
66/// One config read per process — this sits on the hook path of every commit.
67fn declared_mode(settings: &crate::config::Settings) -> bool {
68    *settings.declared_mode.get_or_init(|| {
69        crate::config::enumerated_or(
70            settings,
71            "amont.conventions",
72            &["everywhere", "declared"],
73            "everywhere",
74        ) == "declared"
75    })
76}
77
78/// The checks for a stage, minus `hook.skip` and minus anything that declares
79/// it does not run during an operation currently in progress.
80fn selected_during<'a>(
81    settings: &crate::config::Settings,
82    stage: Stage,
83    in_progress: &[crate::check::GitState],
84    manifest: &'a crate::manifest::Manifest,
85) -> Vec<&'a dyn Check> {
86    let skips = configured_skips(settings);
87    // Externals are included here, so `hook.skip` and the severity override
88    // govern a declared command exactly as they govern a built-in. A repository
89    // that can add a check it cannot disable would be a worse deal than not
90    // being able to add one.
91    let (kept, dropped): (Vec<_>, Vec<_>) = all_stage_checks(stage, manifest)
92        .into_iter()
93        .partition(|c| !skips.iter().any(|s| crate::skip_suppresses(c.name(), s)));
94    let names: Vec<&str> = dropped.iter().map(|c| c.name()).collect();
95    announce_skips(settings, &names);
96
97    // Announced separately from `hook.skip`, and with the operation named: "not
98    // during a rebase" is a property of the moment and will be true again in a
99    // minute, which is a different thing to tell a reader than "you disabled
100    // this".
101    let (kept, paused): (Vec<_>, Vec<_>) = kept.into_iter().partition(|check| {
102        !check
103            .scope()
104            .not_during
105            .iter()
106            .any(|state| in_progress.contains(state))
107    });
108    if !paused.is_empty() {
109        let what = in_progress
110            .iter()
111            .map(|s| s.as_str())
112            .collect::<Vec<_>>()
113            .join(" and ");
114        println!(
115            "{} {} check(s) paused during {what}: {}",
116            warning_sign(),
117            paused.len(),
118            paused
119                .iter()
120                .map(|c| c.name())
121                .collect::<Vec<_>>()
122                .join(", ")
123        );
124    }
125
126    // The conventions split, last: a held-back check was neither skipped (a
127    // choice about THIS repository) nor paused (a property of the moment) —
128    // this repository simply never subscribed. One line, count not names:
129    // in the clone-of-somebody-else's-project case this prints on every
130    // commit, and fifteen names every time is how a safety message becomes
131    // scroll-past noise.
132    if conventions_apply(settings, manifest) {
133        return kept;
134    }
135    let (kept, held): (Vec<_>, Vec<_>) = kept
136        .into_iter()
137        .partition(|check| check.reach() == crate::check::Reach::Safety);
138    if !held.is_empty() {
139        println!(
140            "{} {} convention check(s) held back — no amont.conf here and \
141             amont.conventions is `declared`; the safety net still runs",
142            warning_sign(),
143            held.len(),
144        );
145    }
146    kept
147}
148
149/// The key that turns evidence ordering on. `declared` — the registry's
150/// order, the one this file's header argues for — is the default and nothing
151/// about it changes.
152const ORDER: &str = "amont.order";
153
154/// How far back [`crate::gate_evidence::order_by_evidence`] looks. Not a
155/// config key: it is an input to an ordering that changes nothing about what
156/// runs, and a knob nobody can predict the effect of is a knob that invites
157/// cargo-culting. Ninety days is the same window the report defaults to, so
158/// the ordering a push takes is the ordering `amont-fleet gates` explains.
159const ORDER_WINDOW_DAYS: u64 = 90;
160
161/// Does this repository want its push gates ordered by what the record says?
162fn evidence_ordering(settings: &crate::config::Settings) -> bool {
163    crate::config::enumerated_or(settings, ORDER, &["declared", "evidence"], "declared")
164        == "evidence"
165}
166
167/// Reorder the SCOPED push gates — the suites and audits — by the local
168/// record, leaving everything else exactly where the registry put it.
169///
170/// Two halves, and the split is the safety property. The unscoped pre-push
171/// checks ask about the PUSH — is this branch protected, is the name legal,
172/// is the branch behind, is there a secret in it — and the registry orders
173/// them "cheapest and most decisive first" for a reason: discovering a
174/// protected branch after twenty minutes of tests is precisely the waste this
175/// feature exists to remove, and promoting a suite above them would
176/// reintroduce it. So they keep their positions absolutely.
177///
178/// The scoped gates are permuted among the positions they already occupy.
179/// Nothing is added, removed or skipped — [`crate::gate_evidence`] argues
180/// that at length — and with no history the permutation is the identity.
181fn ordered_by_evidence<'a>(
182    settings: &crate::config::Settings,
183    checks: Vec<&'a dyn Check>,
184) -> Vec<&'a dyn Check> {
185    if !evidence_ordering(settings) || checks.len() < 2 {
186        return checks;
187    }
188    let slots: Vec<usize> = checks
189        .iter()
190        .enumerate()
191        .filter(|(_, c)| !c.scope().is_unscoped())
192        .map(|(i, _)| i)
193        .collect();
194    if slots.len() < 2 {
195        return checks;
196    }
197    let names: Vec<String> = slots
198        .iter()
199        .map(|&i| checks[i].name().to_string())
200        .collect();
201    let history = crate::gate_evidence::history_in(std::path::Path::new("."));
202    if history.is_empty() {
203        return checks;
204    }
205    let order = crate::gate_evidence::order_by_evidence(
206        &names,
207        &history,
208        crate::gate_evidence::now(),
209        ORDER_WINDOW_DAYS,
210    );
211    let mut out = checks.clone();
212    for (slot, &pick) in slots.iter().zip(&order) {
213        out[*slot] = checks[slots[pick]];
214    }
215    if out
216        .iter()
217        .map(|c| c.name())
218        .ne(checks.iter().map(|c| c.name()))
219    {
220        crate::say!(
221            "{} gate order from this repository's own record: {}",
222            valid_sign(),
223            slots
224                .iter()
225                .map(|&i| out[i].name())
226                .collect::<Vec<_>>()
227                .join(", ")
228        );
229    }
230    out
231}
232
233/// Say out loud which checks did not run.
234///
235/// A skip is otherwise invisible at exactly the moment it matters. With
236/// `hook.skip = merge-conflict` set, a commit printed six green ticks and no
237/// hint that a seventh check had been disabled — the developer sees a clean run
238/// and concludes they are covered.
239///
240/// It is worse than it sounds, because one value can silence a whole stage:
241/// `hook.skip = pre-commit` suppresses all fifteen. That is now something
242/// somebody meant rather than the accident it once was — `e` used to cost
243/// twenty by substring reach — but a commit under it still looks exactly like a
244/// commit that had nothing to report.
245///
246/// One line, only when something was actually skipped, so a normal commit is
247/// unchanged. This reaches every skip however it was created — hand-edited
248/// config included — which no dashboard can claim.
249fn announce_skips(settings: &crate::config::Settings, dropped: &[&str]) {
250    if dropped.is_empty() {
251        return;
252    }
253    // Two lines, not one: "you decided this" (hook.skip on this machine)
254    // and "your team decided this" (a skip line in the committed
255    // amont.conf) are different things to be told — the same reason paused
256    // and held-back get their own sentences. A name both sources suppress
257    // is announced as the machine's: the local decision is the nearer one.
258    let (machine, _policy) = crate::skips_by_source(settings);
259    let (yours, theirs): (Vec<&&str>, Vec<&&str>) = dropped
260        .iter()
261        .partition(|name| machine.iter().any(|s| crate::skip_suppresses(name, s)));
262    let say = |names: &[&&str], via: &str| {
263        if names.is_empty() {
264            return;
265        }
266        let plural = if names.len() == 1 { "check" } else { "checks" };
267        println!(
268            "{} {} {plural} skipped by {}: {}",
269            warning_sign(),
270            names.len(),
271            highlight(via),
272            names.iter().map(|n| **n).collect::<Vec<_>>().join(", ")
273        );
274    };
275    say(&yours, "hook.skip");
276    say(&theirs, "amont.conf");
277}
278
279/// Say, once per stage, what the manifest's policy could not do — withheld
280/// behind trust, or aiming at names that exist nowhere. Policy that silently
281/// does not apply is a silent behaviour change, which is the one kind this
282/// codebase does not allow itself.
283fn announce_policy_state(settings: &crate::config::Settings, manifest: &crate::manifest::Manifest) {
284    if let Some(why) = manifest.policy_withheld {
285        println!(
286            "{} {} policy not applied: {why}",
287            warning_sign(),
288            highlight(crate::manifest::MANIFEST),
289        );
290    }
291    for note in &manifest.policy_notes {
292        println!("{} {}", warning_sign(), note);
293    }
294    // The version floor rides the same two call sites: once per stage,
295    // beside the other "this repository expects something you lack" lines.
296    crate::skew::announce_minimum(settings);
297}
298
299/// Run every item concurrently and collect `(name, code)` in the INPUT order.
300///
301/// Extracted so the concurrency itself can be tested with a rendezvous instead
302/// of a stopwatch — an earlier wall-clock test was flaky the moment the machine
303/// was busy, and a threshold that trips under load teaches you to ignore it.
304fn run_concurrently<T, R, F>(items: &[T], run: F, if_thread_died: R) -> Vec<R>
305where
306    T: Sync,
307    R: Send + Sync + Clone,
308    F: Fn(&T) -> R + Sync,
309{
310    let slots: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
311    std::thread::scope(|scope| {
312        for (item, slot) in items.iter().zip(&slots) {
313            let run = &run;
314            let died = &if_thread_died;
315            scope.spawn(move || {
316                // CAUGHT, not propagated. `thread::scope` re-raises a child
317                // panic in the parent, which would abort the whole hook with a
318                // backtrace and throw away the other nineteen checks' results —
319                // and would make `if_thread_died` unreachable, which is what it
320                // was until this test existed to notice.
321                let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(item)))
322                    .unwrap_or_else(|_| died.clone());
323                *slot.lock().expect("poisoned") = Some(outcome);
324            });
325        }
326    });
327    slots
328        .into_iter()
329        .map(|s| {
330            s.into_inner()
331                .expect("poisoned")
332                .unwrap_or_else(|| if_thread_died.clone())
333        })
334        .collect()
335}
336
337/// Take the index-fidelity hold, or say why the caller must stop.
338///
339/// Extracted from `pre_commit` so that `amont run` — which its own doc
340/// comment calls "a rehearsal of the hook" — can take exactly the same hold
341/// rather than judging the working tree while a real commit judges the index.
342///
343/// Around the WHOLE fan-out, not per check: twenty checks run concurrently and
344/// would fight over one working tree.
345fn hold_unstaged() -> Result<crate::staged_only::StagedOnly, Verdict> {
346    // BEFORE `enter()`, not after: `enter()` is what checks out the tree and
347    // parks the unstaged half, and a signal landing in the gap between that
348    // and the handler being armed would hit the default disposition — dead
349    // process, tree left checked out, nothing restored. The handler no-ops
350    // harmlessly on a signal that arrives before there is anything held.
351    crate::staged_only::install_signal_handler();
352    match crate::staged_only::StagedOnly::enter() {
353        Ok(guard) => Ok(guard),
354        Err(e) => {
355            // Refusing to check the wrong content is the safe direction; a
356            // check that read the tree would be answering about a commit
357            // nobody is making.
358            eprintln!("{e}");
359            Err(Verdict::Block)
360        }
361    }
362}
363
364pub fn pre_commit(ctx: &Ctx) -> Verdict {
365    let settings = ctx.settings;
366    // Before anything runs: a pinned tool at the wrong version makes every
367    // verdict below it suspect, and the warning costs one --version per pin.
368    crate::manifest::verify_tool_pins(&ctx.manifest.pins);
369    announce_policy_state(ctx.settings, ctx.manifest);
370    let in_progress = crate::git_states_in_progress();
371    let checks = selected_during(ctx.settings, Stage::PreCommit, &in_progress, ctx.manifest);
372
373    // Tree gates (ADR-0024): judged BEFORE the hold, which is the only moment
374    // unstaged edits are visible; started AFTER it, so they lint the commit's
375    // tree. They never decide the commit.
376    let tree_gates = if ctx.manifest.tree.is_empty() || !crate::tree_lint::enabled(settings) {
377        None
378    } else {
379        match crate::tree_lint::guard(settings) {
380            Some(why) => {
381                crate::hooks::common::say("  tree lint not proven — CI will lint:");
382                crate::hooks::common::say(&crate::tree_lint::fit_line("    ", &why, ""));
383                crate::tree_lint::note_withheld(&ctx.manifest.tree);
384                None
385            }
386            None => Some(&ctx.manifest.tree),
387        }
388    };
389
390    let held = match hold_unstaged() {
391        Ok(guard) => guard,
392        Err(verdict) => return verdict,
393    };
394
395    let root = crate::hooks::common::repo_root();
396    // How long this commit's own declared checks are expected to run — the
397    // cover a tree gate can hide behind — from their last measured runs.
398    let decls =
399        crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals);
400    // Only declarations whose scope this commit touches RUN; the others
401    // return at once, and their duration says nothing about cover.
402    let staged = if ctx.manifest.tree.is_empty() {
403        Vec::new()
404    } else {
405        crate::hooks::common::staged_files(&[])
406    };
407    // A declaration in scope that was never measured is UNKNOWN cover, and
408    // unknown means run: the run teaches both numbers, exactly as an unknown
409    // gate time does. Guessing 0 would skip the one commit that could learn.
410    let cover_ms = if tree_gates.is_some() {
411        decls
412            .iter()
413            .filter(|d| d.scope.touches(&staged))
414            .map(|d| crate::tree_cache::duration_of(&d.id).unwrap_or(u64::MAX))
415            .max()
416            .unwrap_or(0)
417    } else {
418        0
419    };
420    let side_car = tree_gates.and_then(|g| {
421        crate::tree_lint::start(
422            settings,
423            std::path::Path::new(&root),
424            g,
425            &ctx.manifest.pins,
426            cover_ms,
427        )
428    });
429
430    let severities = Overrides::read(settings);
431    let (verdict, outcomes, durations) = run_stage_traced(settings, &checks, ctx, &severities);
432    // Remember how long the declared checks that judged something took, for
433    // the next commit's cover estimate.
434    if !ctx.manifest.tree.is_empty() {
435        let measured: Vec<(String, u64)> = checks
436            .iter()
437            .zip(outcomes.iter().zip(&durations))
438            .filter(|(c, (o, _))| {
439                matches!(o, Outcome::Passed | Outcome::Failed)
440                    && decls
441                        .iter()
442                        .any(|d| d.id == c.name() && d.scope.touches(&staged))
443            })
444            .map(|(c, (_, ms))| (c.name().to_string(), *ms))
445            .collect();
446        crate::tree_cache::record_durations(&measured);
447    }
448
449    // The shadow-mode ledger. Silent, best-effort, and never consulted by any
450    // verdict — see `crate::downgrade`.
451    crate::downgrade::note(
452        settings,
453        &downgraded_events(&checks, &outcomes, &severities),
454    );
455
456    // What post-commit will bind to the commit: the gate-declared checks
457    // that RAN clean, recorded while the index still is the commit's tree.
458    // Called on every verdict — an empty record clears any leftover marker,
459    // so a blocked attempt (or a repo with nothing declared) cannot leave an
460    // earlier attempt's marker to vouch for the next commit. `Unavailable`
461    // deliberately does not qualify: a check whose tool is missing judged
462    // nothing, and stamping it would be the paper promise this exists to
463    // replace.
464    // EVERY blocking declaration, not only the npm GATE names: a custom
465    // `pre-commit check … block …` earns its stamp the same way, and a
466    // same-named pre-push declaration defers to it (see `pair_verdict`).
467    let ran: Vec<String> = if matches!(verdict, Verdict::Block) {
468        Vec::new()
469    } else {
470        crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals)
471            .into_iter()
472            .filter(|d| {
473                checks
474                    .iter()
475                    .zip(&outcomes)
476                    .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Passed | Outcome::Fixed))
477            })
478            .map(|d| d.script)
479            .collect()
480    };
481    // A rewrite means the tree the gates linted is not the one committed.
482    let stampable =
483        !matches!(verdict, Verdict::Block) && !outcomes.iter().any(|o| matches!(o, Outcome::Fixed));
484    let mut ran = ran;
485    if let Some(car) = side_car {
486        ran.extend(crate::tree_lint::finish(settings, car, stampable));
487    }
488    let ran: Vec<&str> = ran.iter().map(String::as_str).collect();
489    crate::gate_stamp::record(&ran);
490    // Under the hold, the index IS the commit's tree: its evidence goes there.
491    if !ctx.manifest.tree.is_empty() {
492        if let Some(tree) = crate::git::stdout(&["write-tree"]) {
493            crate::tree_lint::flush_evidence(&tree);
494        }
495    }
496
497    drop(held);
498    verdict
499}
500
501/// The checks that FAILED without blocking, each with why — the shadow-mode
502/// signal [`crate::downgrade`] keeps.
503///
504/// Derived at the hook entry points and deliberately NOT inside
505/// [`run_stage_traced`], which is where `classify` already computes the same
506/// set. `run_all` reaches that function too, so recording there would let
507/// every `amont run` rehearsal inflate a ledger a lead is going to read as a
508/// count of real commits — and `run --all-files` over a dirty tree would add
509/// dozens of events for content nobody is committing.
510///
511/// A check that DECLARES `warn` is counted but is not evidence about a
512/// rollout: it was never going to block, so calling it "would have blocked"
513/// would inflate the one number the whole feature exists to produce. Only an
514/// override of a blocking check earns that.
515fn downgraded_events(
516    checks: &[&dyn Check],
517    outcomes: &[Outcome],
518    severities: &Overrides,
519) -> Vec<(String, crate::downgrade::Origin)> {
520    checks
521        .iter()
522        .zip(outcomes)
523        .filter(|(_, o)| matches!(o, Outcome::Failed))
524        .filter(|(c, _)| matches!(severities.of(**c), Severity::Warn))
525        .map(|(c, _)| (c.name().to_string(), downgrade_origin(*c, severities)))
526        .collect()
527}
528
529/// Why this check did not block. Shared, because `pre_push` fail-fasts and
530/// never builds an outcomes vector to hand to [`downgraded_events`].
531fn downgrade_origin(check: &dyn Check, severities: &Overrides) -> crate::downgrade::Origin {
532    use crate::downgrade::Origin;
533    use crate::registry::Source;
534    if matches!(check.severity(), Severity::Warn) {
535        return Origin::Declared;
536    }
537    match severities.applied_with_source(check.name()) {
538        Some((_, _, Source::Config)) => Origin::Config,
539        Some((_, _, Source::Policy)) => Origin::Policy,
540        // Declared `block`, resolved `warn`, and nothing claims to have
541        // overridden it: a contradiction. Count it, but not as evidence — the
542        // conservative direction for a number whose only failure mode is
543        // being too alarming.
544        None => Origin::Declared,
545    }
546}
547
548/// The pre-commit body, over the checks it is GIVEN.
549///
550/// A seam, so a test can hand it a check that panics. Without it the value
551/// standing in for a dead check was a literal at one call site that no test
552/// could reach — the rule was asserted on the runner and merely hoped for here.
553fn run_stage(checks: &[&dyn Check], ctx: &Ctx, severities: &Overrides) -> Verdict {
554    let settings = ctx.settings;
555    run_stage_traced(settings, checks, ctx, severities).0
556}
557
558/// [`run_stage`], keeping the per-check outcomes — index-aligned with
559/// `checks` — alive past the verdict. `pre_commit` needs them to know which
560/// gate-declared checks actually ran (`gate_stamp`); `Report` cannot answer
561/// that, because `classify` deliberately drops the names of `Passed`.
562fn run_stage_traced(
563    settings: &crate::config::Settings,
564    checks: &[&dyn Check],
565    ctx: &Ctx,
566    severities: &Overrides,
567) -> (Verdict, Vec<Outcome>, Vec<u64>) {
568    if checks.is_empty() {
569        return (Verdict::Proceed, Vec::new(), Vec::new());
570    }
571    // One slot per check: everything a check says lands in its own buffer
572    // and reaches stdout as ONE block when it finishes — see `live`. Off
573    // (`amont.progress false`), no sink is ever installed and every print
574    // streams exactly as it always did.
575    let stage = crate::live::enabled(settings).then(|| {
576        let names: Vec<&str> = checks.iter().map(|c| c.name()).collect();
577        crate::live::Stage::begin(settings, &names)
578    });
579    let items: Vec<(usize, &&dyn Check)> = checks.iter().enumerate().collect();
580    let timed = run_concurrently(
581        &items,
582        |(idx, check)| {
583            let started = std::time::Instant::now();
584            let _sink = stage.as_ref().map(|s| s.enter(*idx));
585            // The block is emitted however the check leaves — a panicking
586            // check's partial output still reaches the reader, above the
587            // dead-check verdict `run_concurrently` fills in.
588            let _flush = stage
589                .as_ref()
590                .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, *idx));
591            let sub = Ctx {
592                name: check.name(),
593                args: ctx.args,
594                hooks_dir: ctx.hooks_dir,
595                push: ctx.push,
596                manifest: ctx.manifest,
597                settings: ctx.settings,
598            };
599            let slot = crate::host_slots::enter_check(check.name());
600            let outcome = check.run(&sub);
601            // The record measures the check, not its wait for a host slot.
602            let ran = started.elapsed().saturating_sub(slot.queued());
603            let ms = u64::try_from(ran.as_millis()).unwrap_or(u64::MAX);
604            (outcome, ms)
605        },
606        // A check whose thread died has not passed. Stated here, where the slot
607        // is filled, rather than hidden in a `Default` impl that every future
608        // `#[derive(Default)]` would silently inherit.
609        (Outcome::Failed, 0),
610    );
611    let (outcomes, durations): (Vec<Outcome>, Vec<u64>) = timed.into_iter().unzip();
612
613    let report = classify(checks, &outcomes, severities);
614    announce(settings, &report);
615    (report.verdict(), outcomes, durations)
616}
617
618/// What a stage concluded, before anything is printed or exited.
619///
620/// A VALUE, so the classification can be asserted directly. While this was one
621/// function that classified, printed and returned an exit code, its tests could
622/// only check the code — whether the right thing was SAID went untested.
623#[derive(Debug, Default, PartialEq, Eq)]
624struct Report<'a> {
625    /// Repaired. The commit proceeds, but the author's files changed under
626    /// them and that must be said out loud.
627    fixed: Vec<&'a str>,
628    /// Failed, and the severity that applies blocks.
629    blocked: Vec<&'a str>,
630    /// Failed, but configured to warn. The check printed an error and meant it,
631    /// so somebody has to say it did not block.
632    downgraded: Vec<&'a str>,
633    /// Could not run. Distinct from "passed", which is the whole point.
634    unavailable: Vec<&'a str>,
635    /// How many passed outright. Only read when `amont.quiet` swallowed their
636    /// individual lines — a run that says nothing at all is indistinguishable
637    /// from a gate that never ran, and that is the one thing this crate will
638    /// not let a reader believe.
639    passed: usize,
640}
641
642impl Report<'_> {
643    fn verdict(&self) -> Verdict {
644        Verdict::blocking(!self.blocked.is_empty())
645    }
646}
647
648/// Pure: outcomes and severities in, a verdict out. No IO.
649fn classify<'a>(
650    checks: &[&'a dyn Check],
651    outcomes: &[Outcome],
652    severities: &Overrides,
653) -> Report<'a> {
654    let mut report = Report::default();
655    for (check, outcome) in checks.iter().zip(outcomes) {
656        match outcome {
657            Outcome::Passed => report.passed += 1,
658            // `Warned` needs nothing: a check that chose to warn has already
659            // said what it wanted to, and a roll-up would only repeat it.
660            Outcome::Warned => {}
661            Outcome::Fixed => report.fixed.push(check.name()),
662            Outcome::Unavailable => report.unavailable.push(check.name()),
663            // Judged nothing, said nothing: not a pass to count, not a gap
664            // to announce.
665            Outcome::Inert => {}
666            Outcome::Failed => match severities.of(*check) {
667                Severity::Block => report.blocked.push(check.name()),
668                Severity::Warn => report.downgraded.push(check.name()),
669            },
670        }
671    }
672    report
673}
674
675/// Says what happened. Prints; decides nothing.
676fn announce(settings: &crate::config::Settings, report: &Report) {
677    if crate::live::quiet(settings) && report.passed > 0 {
678        println!("{} {} check(s) passed", valid_sign(), report.passed);
679    }
680    if !report.fixed.is_empty() {
681        // Louder than a pass, because files on disk are not what the author
682        // left them: they asked for the repair, but they did not watch it.
683        println!(
684            "{} {} check(s) fixed and re-staged: {}",
685            valid_sign(),
686            report.fixed.len(),
687            report.fixed.join(", ")
688        );
689    }
690    if !report.unavailable.is_empty() {
691        // Distinct from "passed". Silence here is how a repo looks verified
692        // when nothing actually ran — the trailing count is the one line
693        // guaranteed to be read, whatever the twenty blocks above said.
694        println!(
695            "{} {} check(s) could not run: {}",
696            warning_sign(),
697            report.unavailable.len(),
698            report.unavailable.join(", ")
699        );
700    }
701    if !report.downgraded.is_empty() {
702        println!(
703            "{} {} check(s) reported a problem but are set to warn: {}",
704            warning_sign(),
705            report.downgraded.len(),
706            report.downgraded.join(", ")
707        );
708    }
709    if report.blocked.is_empty() {
710        return;
711    }
712    println!("\n🚨  Error raised by:");
713    for name in &report.blocked {
714        println!("    - {}", highlight(name));
715    }
716}
717
718/// Point every check at `git ls-files` instead of the index.
719///
720/// THE definition, called from both entry points. There used to be two: this
721/// one, and a copy in `main.rs` built from a RAW `ls-files` — no `-z` — whose
722/// output git QUOTES for any unusual byte, so `é.json` arrived as the nine-byte
723/// literal `"\303\251.json"` and was handed to prettier and eslint as a path
724/// that does not exist. And because `override_file_set` writes a `OnceLock`,
725/// main's quoted list WON: whichever ran first was the one that counted, and
726/// main's ran first. `git.rs` documents this exact failure.
727pub fn enter_all_files_mode() {
728    crate::hooks::common::override_file_set(
729        crate::git::stdout_paths(&["ls-files"]).unwrap_or_default(),
730    );
731}
732
733/// `amont run` — every applicable check, on demand.
734///
735/// Two questions, and the mode says which it answers:
736///
737/// - **staged** (default) is "would my commit pass" — the same set a commit
738///   would check, so it is a rehearsal of the hook, and it takes the same
739///   index-fidelity hold the hook takes.
740/// - **`--all-files`** is "does my working tree pass". Deliberately NOT the same
741///   question: on a dirty tree it reports on content that is not committed and
742///   may never be. That is right for adopting a check into an existing
743///   repository, where `git add .` is not an acceptable way to measure the mess,
744///   and it is why `--all-files` takes no stash — there is no staged/unstaged
745///   distinction to protect when the answer is "all of it".
746pub fn run_all(ctx: &Ctx, all_files: bool) -> Verdict {
747    let settings = ctx.settings;
748    // ORDER: the override goes in FIRST. It is what tells `fixing_enabled` and
749    // `restage` that the file set is not the index, and both are consulted
750    // from inside the checks below.
751    if all_files {
752        enter_all_files_mode();
753        if crate::hooks::common::fixing_requested(settings) {
754            println!(
755                "{} {} is set, but fixing is off for {}: the input set is the \
756                 working tree, not the index",
757                warning_sign(),
758                highlight("amont.fix"),
759                highlight("--all-files")
760            );
761        }
762        // Stash-free, per decision 1 of docs/index-fidelity-and-run-modes.md:
763        // there is no staged/unstaged distinction to protect when the input
764        // set is `git ls-files`, so a hold would be surprising extra mutation
765        // with no correctness upside.
766        return run_stage(
767            &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
768            ctx,
769            &Overrides::read(settings),
770        );
771    }
772
773    // Staged mode IS a rehearsal of the commit, so it takes the same hold the
774    // commit does. Without it, `amont run` failed on garbage in the tree
775    // that `git commit` — which holds the unstaged half aside — passed, and
776    // vice versa: the two modes disagreed about the same repository, which is
777    // exactly what this mode exists not to do.
778    let held = match hold_unstaged() {
779        Ok(guard) => guard,
780        Err(verdict) => return verdict,
781    };
782    let verdict = run_stage(
783        &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
784        ctx,
785        &Overrides::read(settings),
786    );
787    // AFTER the report has been printed: dropping earlier would put the
788    // unstaged content back under a check that is still reading files.
789    drop(held);
790    verdict
791}
792
793/// `amont run <check>` — one check by name. `None` when there is no such
794/// check, which the caller turns into a usage error.
795///
796/// Lives here rather than in `main.rs` so `registry::lookup` stays inside the
797/// runtime, and so the hold decision is made once: a named check takes the
798/// index-fidelity hold only when it is a `Stage::PreCommit` check running in
799/// staged mode. A pre-push or commit-msg check invoked by name must never
800/// touch the working tree — nothing about a push is a staging operation.
801/// Resolve what `amont run <name>` means, exactly as `hook.skip` resolves a
802/// name — the rest of the tool taught `ban-terms`; making `run` demand the
803/// full id was a pointless second vocabulary. Ambiguity is an answer, not a
804/// guess: the two `branch-pattern` checks are different code at different
805/// stages.
806///
807/// Public because the CALLER needs the answer before anything else happens:
808/// main decides whether to synthesize push refs from the resolved name, and
809/// an ambiguous name must say so rather than fail on a missing upstream it
810/// was never going to use.
811pub fn resolve_check_name(name: &str, manifest: &crate::manifest::Manifest) -> Named2 {
812    if crate::registry::lookup(name, manifest).is_some() {
813        return Named2::Resolved(name.to_string());
814    }
815    let mut matches: Vec<String> = crate::registry::CHECKS
816        .iter()
817        .map(|c| c.name.to_string())
818        .chain(manifest.externals.iter().map(|e| e.id.clone()))
819        .filter(|id| crate::skip_suppresses(id, name))
820        .collect();
821    matches.dedup();
822    match matches.len() {
823        0 => Named2::Unknown,
824        1 => Named2::Resolved(matches.remove(0)),
825        _ => Named2::Ambiguous(matches),
826    }
827}
828
829/// How a run name resolved.
830pub enum Named2 {
831    Resolved(String),
832    Unknown,
833    Ambiguous(Vec<String>),
834}
835
836pub fn run_named(ctx: &Ctx, name: &str, all_files: bool) -> Named {
837    let full: String = match resolve_check_name(name, ctx.manifest) {
838        Named2::Resolved(id) => id,
839        Named2::Unknown => return Named::Unknown,
840        Named2::Ambiguous(ids) => return Named::Ambiguous(ids),
841    };
842    let name = full.as_str();
843    let Some(run_check) = crate::registry::lookup(name, ctx.manifest) else {
844        return Named::Unknown;
845    };
846    // The Ctx must carry the RESOLVED id: lookup's closure re-resolves
847    // through `ctx.name`, and handing it the short name back would panic on
848    // the very ambiguity this function just settled.
849    let ctx = &Ctx {
850        name,
851        args: ctx.args,
852        hooks_dir: ctx.hooks_dir,
853        push: ctx.push,
854        manifest: ctx.manifest,
855        settings: ctx.settings,
856    };
857    if all_files {
858        enter_all_files_mode();
859        return Named::Ran(run_check(ctx));
860    }
861    let is_pre_commit_check = crate::registry::one_named(name, ctx.manifest)
862        .is_some_and(|c| c.stage() == Stage::PreCommit);
863    if !is_pre_commit_check {
864        return Named::Ran(run_check(ctx));
865    }
866    let held = match hold_unstaged() {
867        Ok(guard) => guard,
868        Err(verdict) => return Named::Ran(verdict),
869    };
870    let verdict = run_check(ctx);
871    drop(held);
872    Named::Ran(verdict)
873}
874
875/// What `run_named` resolved a name to.
876pub enum Named {
877    Ran(Verdict),
878    /// Nothing matches — full id, short name, or entrypoint.
879    Unknown,
880    /// A short name that reaches more than one check; the caller lists them
881    /// so the user can pick a full id.
882    Ambiguous(Vec<String>),
883}
884
885pub fn pre_push(ctx: &Ctx) -> Verdict {
886    let settings = ctx.settings;
887    // `amont.treeLintWait` counts from HERE, so no earlier wait (a test
888    // rehearsal's `amont.rehearsalWait`) can extend it.
889    let push_started = std::time::Instant::now();
890    // The notes push `attest` makes re-enters this hook; its ref list is only
891    // ever the attest ref, so there is nothing to prove — and proving it
892    // would recurse.
893    if crate::attest::push_guard_active() {
894        return Verdict::Proceed;
895    }
896    crate::manifest::verify_tool_pins(&ctx.manifest.pins);
897    announce_policy_state(ctx.settings, ctx.manifest);
898    // NB: no CHERRY_PICK_HEAD check here — the zsh pre-push had none either.
899    let severities = Overrides::read(settings);
900    // pre-push had NO state guard at all, with a comment admitting it existed
901    // only because the zsh version had none. Now it asks the same question
902    // pre-commit does and each check answers for itself.
903    let in_progress = crate::git_states_in_progress();
904    // Declared order unless this repository asked for the other one. The
905    // permutation is decided BEFORE the live stage is begun, because the
906    // stage draws the list in the order it is given.
907    let pre_push_checks = ordered_by_evidence(
908        settings,
909        selected_during(ctx.settings, Stage::PrePush, &in_progress, ctx.manifest),
910    );
911    let stage = crate::live::enabled(settings).then(|| {
912        let names: Vec<&str> = pre_push_checks.iter().map(|c| c.name()).collect();
913        crate::live::Stage::begin(settings, &names)
914    });
915    // What actually PASSED, for the attestation at the bottom. `Warned` and
916    // `Unavailable` stay out — "could not run" is not "passed" — and a
917    // commit-time-gated pair counts, because its stamps say the check ran on
918    // every pushed tree.
919    let mut passed: Vec<String> = Vec::new();
920    // Accumulated rather than written per check: one append at the end costs a
921    // single file open, and the loop below can leave early.
922    let mut downgraded: Vec<(String, crate::downgrade::Origin)> = Vec::new();
923    // PUSH STAMPS. The tips being pushed, and what earlier runs of THIS gate
924    // recorded against their trees — an `amont run pre-push` rehearsal, or a
925    // push whose gate passed and whose transport then died. A scoped gate
926    // (a test suite: its verdict is a function of the tree alone) whose
927    // stamp sits on every tip is not run again; the unscoped ones
928    // (branch-protect, secrets — questions about the push, not the content)
929    // always run. `amont.pushStamps false` turns the reuse off.
930    //
931    // Reading `ctx.push` here may consume stdin, exactly as `attest` does
932    // below; every pre-push check reads it anyway.
933    let tips: Vec<String> = {
934        let mut t: Vec<String> = ctx
935            .push
936            .get()
937            .iter()
938            .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
939            .map(|r| r.local_oid.clone())
940            .collect();
941        t.dedup();
942        t
943    };
944    let reuse_stamps = crate::gate_stamp::push_stamps_enabled(settings);
945    // The working tree AS THE SUITE WILL BE HANDED IT, captured before any
946    // gate has run.
947    //
948    // Timing is the point. Asking afterwards means a gate that modifies a
949    // tracked file — a formatter, a suite that updates a snapshot fixture —
950    // disqualifies its OWN stamp. What a stamp needs to know is what the
951    // suite could READ, which is the state it was handed; a change the suite
952    // itself made was never an input to it.
953    //
954    // Tracked modifications only. `stamp_tips` argues that gap, which is a
955    // deliberate one.
956    let tree_at_start = if reuse_stamps {
957        crate::git::stdout(&["status", "--porcelain", "--untracked-files=no"]).unwrap_or_default()
958    } else {
959        String::new()
960    };
961    // A background rehearsal of one of these tips may be mid-suite right
962    // now. Waiting for it is strictly less work than starting over, and
963    // its stamp — read AFTER the wait, below — is the hand-off.
964    // Only when this push has test gates for the rehearsal to vouch for: a
965    // rehearsal that is only proving tree lint is waited for by the tree
966    // verdict alone, under its own `amont.treeLintWait` (ADR-0024), never
967    // under `amont.rehearsalWait`.
968    if reuse_stamps && !tips.is_empty() {
969        let changed = crate::pushrefs::changed_files(ctx.push.get());
970        if !scoped_push_gates(settings, ctx.manifest, &changed).is_empty() {
971            crate::rehearsal::await_for(settings, &tips);
972        }
973    }
974    let push_stamps = if reuse_stamps && !tips.is_empty() {
975        crate::gate_stamp::stamps_for(&tips)
976    } else {
977        Default::default()
978    };
979    // Inside a rehearsal snapshot only the content gates make sense: the
980    // unscoped checks ask about a PUSH — its branch name, its target, its
981    // secrets — and no push is happening. Said once, not per check.
982    let rehearsing = crate::rehearsal::in_snapshot();
983    if rehearsing {
984        crate::say!(
985            "rehearsal: running the test gates only — the push-shaped checks run at push time"
986        );
987    }
988    let stamped_on_every_tip = |name: &str| -> bool {
989        !tips.is_empty()
990            && tips.iter().all(|t| {
991                push_stamps
992                    .get(t)
993                    .is_some_and(|s| s.iter().any(|g| g == name))
994            })
995    };
996    // What actually RAN and passed here (as opposed to being vouched for by
997    // a stamp) — the set this run may stamp in turn.
998    let mut ran_and_passed: Vec<String> = Vec::new();
999    // What each gate COST and how it ENDED, for the record `gate_evidence`
1000    // reads. Every outcome, failures included: the stamp deliberately has no
1001    // opinion about a gate that failed, and a dataset that kept only the
1002    // passes could never say a gate is flaky.
1003    let mut evidence: Vec<crate::gate_stamp::Run> = Vec::new();
1004    // The question `amont list` answers with "inert here — needs go.sum":
1005    // does this repository carry the marker that turns the check on? Asked
1006    // of the index, once, and answered the same way here — a check the
1007    // registry calls inert used to run anyway, find its tool or lockfile
1008    // missing, and warn that it "could not run" on every push of a
1009    // repository it was never meant to touch.
1010    let tracked = crate::tracked_paths();
1011    for (idx, check) in pre_push_checks.iter().enumerate() {
1012        if !check.scope().opted_in(&tracked) {
1013            continue;
1014        }
1015        let _sink = stage.as_ref().map(|s| s.enter(idx));
1016        let _flush = stage
1017            .as_ref()
1018            .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, idx));
1019        // A declared pre-push external whose NAME is also declared at
1020        // pre-commit (blocking) is a gate pair: the commit-time side earned
1021        // per-commit stamps, and this side runs only for pushes carrying
1022        // commits with no record of it — the same contract the npm gate has
1023        // always had, for vocabularies npm never heard of (`cargo test`,
1024        // `pytest`, anything). Messages mirror the npm gate's exactly;
1025        // docs/checks.md quotes them.
1026        // The push side of a pair is `(name, scope)`, from whichever of the
1027        // two kinds of check this is. A declared pre-push external supplies
1028        // its own; anything else is a BUILT-IN, and `pairing_name` plus the
1029        // registry's scope say the same two things about it.
1030        //
1031        // The external is tried FIRST and its inputs are unchanged, so the
1032        // declared path behaves exactly as before — that is what the
1033        // untouched declared-pair tests prove.
1034        if rehearsing && check.scope().is_unscoped() {
1035            continue;
1036        }
1037        if !check.scope().is_unscoped() && stamped_on_every_tip(check.name()) {
1038            crate::say!(
1039                "{} {} passed on this exact tree earlier — not repeating it here",
1040                valid_sign(),
1041                highlight(check.name()),
1042            );
1043            passed.push(check.name().to_string());
1044            continue;
1045        }
1046        let declared = ctx
1047            .manifest
1048            .externals
1049            .iter()
1050            .find(|e| e.stage == Stage::PrePush && e.id == check.name());
1051        let builtin_scope = check.scope();
1052        let pairing: Option<(&str, &crate::check::Scope)> = match declared {
1053            Some(ext) => match &ext.kind {
1054                crate::manifest::Kind::Runnable { scope, .. } => {
1055                    Some((ext.short_name.as_str(), scope))
1056                }
1057                // A declared pre-push entry that runs nothing has no scope to
1058                // judge with, and is not a built-in either. Nothing to pair.
1059                _ => None,
1060            },
1061            None => Some((check.pairing_name(), &builtin_scope)),
1062        };
1063        if let Some((name, push_scope)) = pairing {
1064            match crate::hooks::run_tests::pair_verdict(
1065                ctx.settings,
1066                name,
1067                push_scope,
1068                ctx.manifest,
1069                ctx.push,
1070            ) {
1071                crate::hooks::run_tests::PairVerdict::Gated => {
1072                    crate::say!(
1073                        "{} {} gated at commit instead — not repeating it here",
1074                        valid_sign(),
1075                        highlight(name),
1076                    );
1077                    passed.push(check.name().to_string());
1078                    continue;
1079                }
1080                crate::hooks::run_tests::PairVerdict::Unstamped(n) => {
1081                    // `amont.unstampedPush refuse`: never run a suite with
1082                    // the remote's connection held open — say how to earn
1083                    // the stamp instead. Not inside a rehearsal snapshot:
1084                    // running there is how the stamp is earned.
1085                    if !rehearsing && crate::rehearsal::refuse_unstamped(ctx.settings) {
1086                        crate::say!(
1087                            "{} {} is declared at commit time, but {n} pushed \
1088                             commit{} carr{} no record of it (rewritten by a \
1089                             rebase or amend, or made without the hooks) — \
1090                             refusing the push",
1091                            warning_sign(),
1092                            name,
1093                            if n == 1 { "" } else { "s" },
1094                            if n == 1 { "ies" } else { "y" },
1095                        );
1096                        crate::say!(
1097                            "    Test this tree first, with no push waiting on it: {} — then push again",
1098                            highlight("amont rehearse --wait"),
1099                        );
1100                        crate::downgrade::note(settings, &downgraded);
1101                        record_evidence(&tips, &evidence);
1102                        println!("\n🚨  Error raised by hook {}", highlight(check.name()));
1103                        return Verdict::Block;
1104                    }
1105                    crate::say!(
1106                        "{} {} is declared at commit time, but {n} pushed \
1107                         commit{} carr{} no record of it — running it here",
1108                        warning_sign(),
1109                        name,
1110                        if n == 1 { "" } else { "s" },
1111                        if n == 1 { "ies" } else { "y" },
1112                    );
1113                }
1114                crate::hooks::run_tests::PairVerdict::NotPaired => {}
1115            }
1116        }
1117        let sub = Ctx {
1118            name: check.name(),
1119            args: ctx.args,
1120            hooks_dir: ctx.hooks_dir,
1121            push: ctx.push,
1122            manifest: ctx.manifest,
1123            settings: ctx.settings,
1124        };
1125        // Wall clock around the check itself, not around the hook: the number
1126        // that catches a suite which stopped finding tests is how long THAT
1127        // gate took, and everything outside this call is bookkeeping.
1128        let started = std::time::Instant::now();
1129        let slot = crate::host_slots::enter_check(check.name());
1130        let outcome = check.run(&sub);
1131        let ran = started.elapsed().saturating_sub(slot.queued());
1132        drop(slot);
1133        evidence.push(crate::gate_stamp::Run {
1134            at: crate::gate_evidence::now(),
1135            gate: check.name().to_string(),
1136            outcome: run_outcome(outcome),
1137            ms: ran.as_millis().min(u128::from(u64::MAX)) as u64,
1138        });
1139        match outcome {
1140            Outcome::Passed => {
1141                passed.push(check.name().to_string());
1142                if !check.scope().is_unscoped() {
1143                    ran_and_passed.push(check.name().to_string());
1144                }
1145            }
1146            // Announced, never fatal: a check that could not run has not
1147            // invalidated anything, and neither has a warning.
1148            Outcome::Unavailable => {
1149                println!(
1150                    "{} {} could not run",
1151                    warning_sign(),
1152                    highlight(check.name())
1153                )
1154            }
1155            Outcome::Warned => {}
1156            // Nothing to judge: not passed (nothing to stamp or attest), not
1157            // a gap (nothing is missing). The dispatcher asked the registry's
1158            // opt-in question above; this is a check answering it for itself.
1159            Outcome::Inert => {}
1160            // Cannot occur: `Fix::Rewrite` is refused on a pre-push
1161            // declaration, so nothing here can repair anything.
1162            Outcome::Fixed => {}
1163            Outcome::Failed => match severities.of(*check) {
1164                Severity::Warn => {
1165                    downgraded.push((
1166                        check.name().to_string(),
1167                        downgrade_origin(*check, &severities),
1168                    ));
1169                    println!(
1170                        "{} {} reported a problem (severity warn)",
1171                        warning_sign(),
1172                        highlight(check.name())
1173                    );
1174                }
1175                // Fail-fast applies ONLY to Block: the later steps are
1176                // expensive and their preconditions are gone.
1177                Severity::Block => {
1178                    // Record what already warned before leaving. Those checks
1179                    // ran and reported; a later check blocking does not unmake
1180                    // them, and dropping them here would make the ledger quietly
1181                    // under-count every push that ended badly.
1182                    crate::downgrade::note(settings, &downgraded);
1183                    // The same argument for the evidence, and it matters more
1184                    // here: this is the path a FAILURE leaves by, and a record
1185                    // written only on the way out of a successful push would
1186                    // be a dataset of passes calling itself a dataset of runs.
1187                    record_evidence(&tips, &evidence);
1188                    println!("\n🚨  Error raised by hook {}", highlight(check.name()));
1189                    return Verdict::Block;
1190                }
1191            },
1192        }
1193    }
1194    // Every block gate passed — stamp the tips with the scoped gates that
1195    // RAN here, so the next push of this content (a retry after a dropped
1196    // connection, or the real push after an `amont run pre-push` rehearsal)
1197    // skips them. Only when what ran is what is being pushed: with
1198    // `amont.testPushedTree` the suite ran on the tip itself — unless the
1199    // snapshot could not be made, which `stamp_tips` asks about rather than
1200    // assuming; otherwise it ran on the working tree, which vouches for the
1201    // tip only when the two are the same content — HEAD, with nothing
1202    // modified and nothing untracked.
1203    // The same proxy `attestable` uses, for the same reason: a scoped gate
1204    // whose files the push never touched returns `Passed` having run
1205    // nothing, and a stamp for THAT would let a later push that does touch
1206    // them skip a suite nobody ran.
1207    if reuse_stamps && !ran_and_passed.is_empty() {
1208        let changed = crate::pushrefs::changed_files(ctx.push.get());
1209        let really_ran: Vec<String> = pre_push_checks
1210            .iter()
1211            .filter(|c| ran_and_passed.iter().any(|p| p == c.name()))
1212            .filter(|c| c.scope().touches(&changed))
1213            .map(|c| c.name().to_string())
1214            .collect();
1215        stamp_tips(&tips, &really_ran, &tree_at_start);
1216    }
1217    // …and say so to CI, if this repository opted in.
1218    // Gated behind `enabled()` HERE, not just inside `attest_push`: reading
1219    // `ctx.push` may consume stdin, and a disabled repo should leave stdin
1220    // exactly as it found it.
1221    // Tree gates (ADR-0024) are not push checks: nothing runs here. Each is
1222    // attested only when the TREE of every pushed tip carries its commit-time
1223    // proof; a whole-tree proof needs no changed-files scope. Fail-closed:
1224    // anything else is simply not attested, and CI lints.
1225    let (tree_proven, tree_unproven) =
1226        if !ctx.manifest.tree.is_empty() && crate::attest::enabled(settings) {
1227            crate::tree_lint::await_verdict(settings, &ctx.manifest.tree, &tips, push_started)
1228        } else {
1229            (Vec::new(), Vec::new())
1230        };
1231    if !tree_unproven.is_empty() {
1232        crate::hooks::common::say(&crate::tree_lint::fit_line(
1233            "  lint not attested (cold or changed tree): ",
1234            &tree_unproven.join(" "),
1235            " — CI will lint",
1236        ));
1237    }
1238    if (!passed.is_empty() || !tree_proven.is_empty()) && crate::attest::enabled(settings) {
1239        let remote = ctx
1240            .args
1241            .first()
1242            .map(|a| a.to_string_lossy().into_owned())
1243            .unwrap_or_default();
1244        let changed = crate::pushrefs::changed_files(ctx.push.get());
1245        let mut vouched = attestable(&pre_push_checks, &passed, &changed);
1246        vouched.extend(tree_proven);
1247        crate::attest::attest_push(ctx.settings, &remote, ctx.push.get(), &vouched);
1248    }
1249    crate::downgrade::note(settings, &downgraded);
1250    record_evidence(&tips, &evidence);
1251    Verdict::Proceed
1252}
1253
1254/// What one check's outcome is called in the record.
1255fn run_outcome(outcome: Outcome) -> crate::gate_stamp::RunOutcome {
1256    use crate::gate_stamp::RunOutcome as R;
1257    match outcome {
1258        Outcome::Passed => R::Passed,
1259        Outcome::Failed => R::Failed,
1260        Outcome::Warned => R::Warned,
1261        Outcome::Fixed => R::Fixed,
1262        Outcome::Unavailable => R::Unavailable,
1263        Outcome::Inert => R::Inert,
1264    }
1265}
1266
1267/// File this push's runs under the content they judged.
1268///
1269/// ONE key, not one per tip: a push of two branches ran each gate once, and
1270/// writing the same run onto both trees would make a report count it twice.
1271/// The first tip's tree is that key, falling back to `HEAD` — and to nothing
1272/// at all when git will not name either, which costs a row in a report and
1273/// never a verdict.
1274fn record_evidence(tips: &[String], runs: &[crate::gate_stamp::Run]) {
1275    if runs.is_empty() {
1276        return;
1277    }
1278    let tree = tips
1279        .first()
1280        .and_then(|tip| crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]))
1281        .or_else(|| crate::git::stdout(&["rev-parse", "HEAD^{tree}"]));
1282    if let Some(tree) = tree {
1283        crate::gate_stamp::record_runs(&tree, runs);
1284    }
1285}
1286
1287/// The scoped pre-push gates — test suites — that have work to do for a
1288/// push that changed `changed`: what a rehearsal would run, and therefore
1289/// what its stamp would have to name before a push may skip anything.
1290///
1291/// The same two filters `pre_push` applies before stamping (selected here,
1292/// and `scope().touches` the change), so the rehearsal's idea of "nothing to
1293/// do" is the push's idea of "nothing to stamp".
1294pub fn scoped_push_gates(
1295    settings: &crate::config::Settings,
1296    manifest: &crate::manifest::Manifest,
1297    changed: &[String],
1298) -> Vec<String> {
1299    let in_progress = crate::git_states_in_progress();
1300    let tracked = crate::tracked_paths();
1301    selected_during(settings, Stage::PrePush, &in_progress, manifest)
1302        .into_iter()
1303        .filter(|c| !c.scope().is_unscoped() && c.scope().touches(changed))
1304        // The same opt-in gate `pre_push` applies: a suite the repository
1305        // never turned on is not work a rehearsal owes a stamp for.
1306        .filter(|c| c.scope().opted_in(&tracked))
1307        .map(|c| c.name().to_string())
1308        .collect()
1309}
1310
1311/// Push-stamp every tip whose content is what the gates actually tested.
1312///
1313/// See the comment at the call site for the two cases. Silent when nothing
1314/// qualifies — a dirty working tree is the ordinary state of a machine
1315/// mid-work, and a note on every push would teach people to ignore it.
1316fn stamp_tips(tips: &[String], gates: &[String], tree_at_start: &str) {
1317    let head = crate::git::stdout(&["rev-parse", "HEAD"]);
1318    // TRACKED modifications only — a KNOWN gap, kept deliberately, and
1319    // spelled out because the comment that used to sit here argued it
1320    // backwards ("untracked files are not in any tree the suite could have
1321    // been asked about"). That is not the reason. The danger is not that the
1322    // tree lacks them, it is that the RUN had them: a new test file, a
1323    // fixture, a local `.env`, present while the suite ran and absent from
1324    // the tree the stamp vouches for.
1325    //
1326    // Counting them was tried, and is worse than the gap. Gates leave
1327    // artefacts — a log, a coverage directory, whatever a declared
1328    // `amont.conf` command writes — and nothing cleans them up, so a
1329    // repository using declared gates would stop earning stamps permanently
1330    // after its first commit. That does not merely lose an optimisation: it
1331    // puts the suite back INSIDE the push, which is the failure the whole
1332    // stamping mechanism exists to prevent. amont's own
1333    // `a_push_stamp_merges_with_a_commit_time_stamp` fixture is exactly that
1334    // shape, and CI is where it surfaced — a `*.log` line in one developer's
1335    // global gitignore had hidden it on the machine that wrote the change.
1336    //
1337    // `amont.testPushedTree true` closes the gap properly for anyone who
1338    // wants it closed: it runs the suite in a checkout of the commit, where
1339    // no untracked file exists to be read.
1340    //
1341    // `tree_at_start` — not a fresh `git status`. The gates have run by now
1342    // and may have written into the tree; what a stamp needs to know is what
1343    // the suite could READ, which is the state it was handed. See the
1344    // capture in `pre_push`.
1345    let worktree_clean = tree_at_start.trim().is_empty();
1346    let in_snapshot = crate::rehearsal::in_snapshot();
1347    let mut stamped: Vec<String> = Vec::new();
1348    for tip in tips {
1349        // Inside a rehearsal the working tree IS a checkout git made of this
1350        // commit, so it is the tip's content by construction — and whatever
1351        // `amont.snapshotPrepare` had to add to make it runnable (a
1352        // `node_modules`, a virtualenv) is not a reason to distrust it. That
1353        // is the same argument a pushed-tree snapshot makes.
1354        let is_head = head.as_deref() == Some(tip.as_str());
1355        let tree_is_tip = is_head && (in_snapshot || worktree_clean);
1356        // PER GATE, from what each one actually did — not from the config.
1357        // `amont.testPushedTree` is a request; `pushed_tree::ran_on_tip` is
1358        // the record of which gates were handed a checkout of this tip. A
1359        // gate that ran somewhere else (a snapshot that could not be made,
1360        // or a check that ran in the working tree) may vouch for the tip
1361        // only when the working tree WAS the tip. Deciding from the flag
1362        // stamped every passing gate onto a tip that one of them had never
1363        // seen.
1364        let vouched: Vec<String> = gates
1365            .iter()
1366            .filter(|g| tree_is_tip || crate::pushed_tree::ran_on_tip(g, tip))
1367            .cloned()
1368            .collect();
1369        if vouched.is_empty() {
1370            continue;
1371        }
1372        let spec = format!("{tip}^{{tree}}");
1373        let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
1374            continue;
1375        };
1376        if crate::gate_stamp::stamp_push(tip, &tree, &vouched) {
1377            for g in vouched {
1378                if !stamped.contains(&g) {
1379                    stamped.push(g);
1380                }
1381            }
1382        }
1383    }
1384    if !stamped.is_empty() {
1385        crate::say!(
1386            "{} stamped {} for this tree — the next push of it skips them ({})",
1387            valid_sign(),
1388            highlight(&stamped.join(" ")),
1389            crate::gate_stamp::NOTES_REF,
1390        );
1391    }
1392}
1393
1394/// Of the checks that passed, the ones an attestation may actually VOUCH for.
1395///
1396/// A language gate whose scope the push never touched returns `Passed` having
1397/// run nothing — `cargo_test` walks its refs, finds no crate root, and falls
1398/// out of the loop green. That is right for a push gate (there was nothing to
1399/// object to) and wrong for an attestation: a JS-only push was minting
1400/// `gates … pre-push-cargo-test pre-push-go-test pre-push-pytest`, and in a
1401/// MIXED repository CI would then skip a suite that nobody ran on that tree.
1402///
1403/// The declared `scope` is the honest filter, and the same data `amont list`
1404/// already reports. Unscoped checks (`Scope::ALWAYS` — branch-protect,
1405/// secrets) match everything and are vouched for, which is accurate: they
1406/// really did run. An empty `changed` vouches for nothing scoped, which is
1407/// the safe direction — CI runs the suite.
1408///
1409/// [`Scope::touches`], NOT `Scope::matches`. `matches` also asks whether the
1410/// repository has opted in — whether a `Cargo.toml` exists — and asking that
1411/// of a push DIFF can only answer no unless the push happened to touch the
1412/// marker. So `pre-push-cargo-test` was vouched for by a push that edited
1413/// `Cargo.toml` and never by one that edited only `.rs` files, which is the
1414/// ordinary case and the one worth skipping CI for. The feature attested
1415/// almost nothing, silently, and looked like it worked.
1416///
1417/// WHAT THIS IS STILL A PROXY FOR, stated plainly because the trust path
1418/// deserves it: the honest question is "did this gate actually run", and no
1419/// gate reports that. `rust_tools::test` returns `Passed` whether it ran a
1420/// suite or found no crate root and fell out of its loop — the very thing
1421/// the first paragraph describes. Scope is the closest available stand-in.
1422/// It is now a good one: a gate is vouched for only if the push changed a
1423/// file its extensions cover.
1424///
1425/// The gap that remains is narrow and one-directional: a `.rs` file outside
1426/// every crate would be covered here while `cargo test` had nothing to say
1427/// about it. Closing it properly means an outcome that distinguishes "ran
1428/// and passed" from "found nothing to do", which is a change to every gate
1429/// and to `Outcome` itself — worth doing, not worth smuggling into this.
1430fn attestable(checks: &[&dyn Check], passed: &[String], changed: &[String]) -> Vec<String> {
1431    checks
1432        .iter()
1433        .filter(|c| passed.iter().any(|p| p == c.name()))
1434        .filter(|c| c.scope().touches(changed))
1435        .map(|c| c.name().to_string())
1436        .collect()
1437}
1438
1439#[cfg(test)]
1440mod tests {
1441    use super::*;
1442    use crate::check::{Builtin, Scope};
1443    use std::sync::atomic::{AtomicUsize, Ordering};
1444
1445    /// A check whose only job is to carry a name and a severity into `report`.
1446    /// Its `run` is never called — `report` is fed outcomes directly, which is
1447    /// what makes `Unavailable` testable at all: the real thing needs a missing
1448    /// binary, and a test that uninstalls the developer's toolchain is worse
1449    /// than no test.
1450    const fn stub(name: &'static str, severity: Severity) -> Builtin {
1451        Builtin {
1452            name,
1453            stage: Stage::PreCommit,
1454            scope: Scope::ALWAYS,
1455            severity,
1456            run: |_| Outcome::Passed,
1457            fix: crate::check::Fix::None,
1458            reach: crate::check::Reach::Convention,
1459        }
1460    }
1461
1462    /// A pre-push gate with an OPT-IN file, as the real Rust and Python
1463    /// gates have: `.rs` files, but only where a `Cargo.toml` exists.
1464    const fn opt_in(
1465        name: &'static str,
1466        exts: &'static [&'static str],
1467        names: &'static [&'static str],
1468    ) -> Builtin {
1469        Builtin {
1470            name,
1471            stage: Stage::PrePush,
1472            scope: Scope::new(exts, names),
1473            severity: Severity::Block,
1474            run: |_| Outcome::Passed,
1475            fix: crate::check::Fix::None,
1476            reach: crate::check::Reach::Convention,
1477        }
1478    }
1479
1480    /// A pre-push gate scoped to one language's files.
1481    const fn scoped(name: &'static str, exts: &'static [&'static str]) -> Builtin {
1482        Builtin {
1483            name,
1484            stage: Stage::PrePush,
1485            scope: Scope::new(exts, &[]),
1486            severity: Severity::Block,
1487            run: |_| Outcome::Passed,
1488            fix: crate::check::Fix::None,
1489            reach: crate::check::Reach::Convention,
1490        }
1491    }
1492
1493    /// The over-claim this filter exists to stop, caught in the wild: a
1494    /// JS-only push minted `gates … pre-push-cargo-test pre-push-go-test
1495    /// pre-push-pytest`, because each of those gates finds nothing of its
1496    /// language to do and returns `Passed` having run NOTHING. Harmless in a
1497    /// single-language repo, unsound in a mixed one — CI would skip a suite
1498    /// nobody ran on that tree.
1499    #[test]
1500    fn a_gate_whose_language_the_push_never_touched_is_not_vouched_for() {
1501        let js = scoped("pre-push-run-tests-js", &[".ts", ".js"]);
1502        let rust = scoped("pre-push-cargo-test", &[".rs"]);
1503        let py = scoped("pre-push-pytest", &[".py"]);
1504        let always = stub("pre-push-secrets", Severity::Block);
1505        let checks: Vec<&dyn Check> = vec![&js, &rust, &py, &always];
1506        let passed: Vec<String> = checks.iter().map(|c| c.name().to_string()).collect();
1507
1508        let changed = vec!["app/routes/home.ts".to_string()];
1509        let vouched = attestable(&checks, &passed, &changed);
1510        assert_eq!(
1511            vouched,
1512            vec![
1513                "pre-push-run-tests-js".to_string(),
1514                "pre-push-secrets".to_string()
1515            ],
1516            "only the gate that had work, plus the unscoped one that always runs"
1517        );
1518
1519        // Nothing computed about the push vouches for nothing scoped — the
1520        // safe direction, since CI then runs the suite.
1521        assert_eq!(
1522            attestable(&checks, &passed, &[]),
1523            vec!["pre-push-secrets".to_string()]
1524        );
1525
1526        // A check that did NOT pass is never vouched for, whatever its scope.
1527        let only_rust_passed = vec!["pre-push-cargo-test".to_string()];
1528        assert!(attestable(&checks, &only_rust_passed, &changed).is_empty());
1529    }
1530
1531    /// No overrides configured. `report` takes them as a VALUE now, so its
1532    /// tests need no repository and no git at all.
1533    fn none() -> Overrides {
1534        Overrides::default()
1535    }
1536
1537    static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
1538    static WARNER: Builtin = stub("stub-warner", Severity::Warn);
1539
1540    /// The unit tests hold `&dyn Check` for the same reason the dispatcher
1541    /// does: `report` must not be able to tell a built-in from an external.
1542    const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
1543        [cs[0], cs[1], cs[2]]
1544    }
1545
1546    /// The classification itself, which used to be unreachable: while one
1547    /// function classified AND printed AND returned a code, a test could assert
1548    /// the code and nothing else.
1549    #[test]
1550    fn every_outcome_lands_in_the_right_bucket() {
1551        let checks: [&dyn Check; 5] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER, &BLOCKER];
1552        let got = classify(
1553            &checks,
1554            &[
1555                Outcome::Passed,
1556                Outcome::Unavailable,
1557                Outcome::Failed,
1558                Outcome::Failed,
1559                Outcome::Inert,
1560            ],
1561            &none(),
1562        );
1563        assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
1564        assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
1565        assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
1566        assert_eq!(got.passed, 1, "inert is not a pass: {got:?}");
1567    }
1568
1569    /// A clean stage concludes nothing at all — not an empty message, no
1570    /// message. Twenty checks that passed should print no roll-ups.
1571    ///
1572    /// `passed` is a tally, not a roll-up. It exists so that `amont.quiet` can
1573    /// say how many lines it swallowed, and it must never be the reason this
1574    /// report looks like it has something to announce.
1575    #[test]
1576    fn a_clean_stage_has_nothing_to_report() {
1577        let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
1578        let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
1579        assert!(
1580            got.fixed.is_empty()
1581                && got.blocked.is_empty()
1582                && got.downgraded.is_empty()
1583                && got.unavailable.is_empty(),
1584            "a clean stage found something to announce: {got:?}"
1585        );
1586        assert_eq!(got.passed, 1, "the pass was not tallied: {got:?}");
1587        assert_eq!(got.verdict(), Verdict::Proceed);
1588    }
1589
1590    #[test]
1591    fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
1592        let b: &dyn Check = &BLOCKER;
1593        let w: &dyn Check = &WARNER;
1594        assert_eq!(
1595            classify(&[b], &[Outcome::Failed], &none()).verdict(),
1596            Verdict::Block
1597        );
1598        assert_eq!(
1599            classify(&[b], &[Outcome::Passed], &none()).verdict(),
1600            Verdict::Proceed
1601        );
1602        // Every non-blocking shape, one at a time, so a regression cannot hide
1603        // behind a passing sibling.
1604        assert_eq!(
1605            classify(&[b], &[Outcome::Warned], &none()).verdict(),
1606            Verdict::Proceed
1607        );
1608        assert_eq!(
1609            classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
1610            Verdict::Proceed
1611        );
1612        assert_eq!(
1613            classify(&[w], &[Outcome::Failed], &none()).verdict(),
1614            Verdict::Proceed
1615        );
1616    }
1617
1618    #[test]
1619    fn one_blocking_failure_among_many_still_fails() {
1620        let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
1621        assert_eq!(
1622            classify(
1623                &checks,
1624                &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
1625                &none()
1626            )
1627            .verdict(),
1628            Verdict::Block
1629        );
1630        // Same shape, with the only *blocking* failure removed.
1631        assert_eq!(
1632            classify(
1633                &checks,
1634                &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
1635                &none()
1636            )
1637            .verdict(),
1638            Verdict::Proceed
1639        );
1640    }
1641
1642    /// The slot of a check whose thread died. Reading that as a pass is how a
1643    /// crash becomes a green commit.
1644    ///
1645    /// Asserted through the RUNNER, not through a `Default` impl: the rule
1646    /// belongs to this call site, and a test on `Outcome::default()` proved
1647    /// only that a trait impl existed, not that the runner used it.
1648    /// A check that PANICS must fail the commit, not pass it — and must not
1649    /// take the other checks down with it.
1650    ///
1651    /// Driven through the stage body rather than the runner, because the value
1652    /// that stands in for a dead check is chosen at the call site and the
1653    /// runner's own test cannot see that choice.
1654    #[test]
1655    fn a_panicking_check_blocks_the_commit() {
1656        static DIES: Builtin = Builtin {
1657            name: "stub-dies",
1658            stage: Stage::PreCommit,
1659            scope: Scope::ALWAYS,
1660            severity: Severity::Block,
1661            run: |_| panic!("this check died"),
1662            fix: crate::check::Fix::None,
1663            reach: crate::check::Reach::Convention,
1664        };
1665        let hook = std::panic::take_hook();
1666        std::panic::set_hook(Box::new(|_| {}));
1667        let push = crate::pushrefs::PushRefs::default();
1668        let manifest = crate::manifest::Manifest::default();
1669        let settings = crate::config::Settings::default();
1670        let ctx = Ctx {
1671            name: "pre-commit",
1672            args: &[],
1673            hooks_dir: std::path::Path::new("."),
1674            push: &push,
1675            manifest: &manifest,
1676            settings: &settings,
1677        };
1678        let verdict = run_stage(&[&DIES], &ctx, &none());
1679        std::panic::set_hook(hook);
1680        assert_eq!(
1681            verdict,
1682            Verdict::Block,
1683            "a check that died must not let the commit through"
1684        );
1685    }
1686
1687    #[test]
1688    fn a_thread_that_dies_leaves_a_failure_behind() {
1689        // The default hook would print a backtrace for the deliberate panic and
1690        // make a passing run look broken.
1691        let hook = std::panic::take_hook();
1692        std::panic::set_hook(Box::new(|_| {}));
1693        let items = ["a", "b", "c"];
1694        let out = run_concurrently(
1695            &items,
1696            |n: &&str| {
1697                if *n == "b" {
1698                    panic!("this check died");
1699                }
1700                Outcome::Passed
1701            },
1702            Outcome::Failed,
1703        );
1704        std::panic::set_hook(hook);
1705        assert_eq!(
1706            out,
1707            vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
1708            "a dead check must not read as one that passed, \
1709             and must not take the other checks down with it"
1710        );
1711    }
1712    use std::time::{Duration, Instant};
1713
1714    /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
1715    /// observe all the others arrive. Were the runner serial, the first task
1716    /// would wait alone, time out, and return non-zero — a failure, not a hang.
1717    #[test]
1718    fn run_concurrently_actually_overlaps() {
1719        static ARRIVED: AtomicUsize = AtomicUsize::new(0);
1720        ARRIVED.store(0, Ordering::SeqCst);
1721        let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
1722        let n = names.len();
1723
1724        let out = run_concurrently(
1725            &names,
1726            move |_: &&str| {
1727                ARRIVED.fetch_add(1, Ordering::SeqCst);
1728                let deadline = Instant::now() + Duration::from_secs(10);
1729                while ARRIVED.load(Ordering::SeqCst) < n {
1730                    if Instant::now() > deadline {
1731                        return 1; // never met the others — execution was serial
1732                    }
1733                    std::thread::yield_now();
1734                }
1735                0
1736            },
1737            1,
1738        );
1739        assert!(
1740            out.iter().all(|c| *c == 0),
1741            "tasks did not overlap: {out:?}"
1742        );
1743    }
1744
1745    #[test]
1746    fn results_come_back_in_input_order() {
1747        let names: Vec<&'static str> = vec!["first", "second", "third"];
1748        let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
1749        assert_eq!(out, vec![0, 7, 0], "results keep the input order");
1750    }
1751
1752    /// The filter calls the shared resolver rather than restating it. This test
1753    /// used to inline `n.contains(s)` — its own copy of the rule — and so went
1754    /// on passing after the rule changed underneath it.
1755    #[test]
1756    fn skips_are_filtered_by_the_shared_resolver() {
1757        let all = ["pre-commit-ruff", "pre-commit-prettier"];
1758        let skips = ["ruff".to_string()];
1759        let kept: Vec<_> = all
1760            .iter()
1761            .copied()
1762            .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
1763            .collect();
1764        assert_eq!(kept, vec!["pre-commit-prettier"]);
1765    }
1766
1767    /// The ordinary Rust push: source changed, `Cargo.toml` untouched.
1768    ///
1769    /// This test used to assert the OPPOSITE, and said so — it pinned
1770    /// `attestable` filtering on `Scope::matches`, which also asks whether
1771    /// the repository has opted in. Asking that of a push diff meant a
1772    /// `.rs`-only push, in a repository with a `Cargo.toml` sitting right
1773    /// there, attested nothing. Since that is what nearly every Rust push
1774    /// looks like, the feature was attesting almost nothing at all — quietly,
1775    /// while appearing to work.
1776    #[test]
1777    fn an_ordinary_source_push_is_vouched_for() {
1778        let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
1779        let checks: Vec<&dyn Check> = vec![&rust];
1780        let passed = vec!["pre-push-cargo-test".to_string()];
1781
1782        let changed = vec!["crates/amont/src/main.rs".to_string()];
1783        assert_eq!(
1784            attestable(&checks, &passed, &changed),
1785            vec!["pre-push-cargo-test".to_string()],
1786            "a push that changed Rust must vouch for the Rust gate"
1787        );
1788
1789        // And still when the marker IS in the diff — the opt-in file is not
1790        // required, but it is not disqualifying either.
1791        let changed = vec![
1792            "crates/amont/src/main.rs".to_string(),
1793            "Cargo.toml".to_string(),
1794        ];
1795        assert_eq!(
1796            attestable(&checks, &passed, &changed),
1797            vec!["pre-push-cargo-test".to_string()]
1798        );
1799    }
1800
1801    /// The over-claim the filter exists to stop, with an opt-in gate: a
1802    /// JS-only push must not vouch for the Rust suite, whatever files the
1803    /// repository contains.
1804    ///
1805    /// This is the half of the contract the fix above must not have broken,
1806    /// and it is the reason `touches` asks about EXTENSIONS rather than
1807    /// dropping the scope test altogether.
1808    #[test]
1809    fn an_opt_in_gate_is_not_vouched_for_by_a_push_in_another_language() {
1810        let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
1811        let checks: Vec<&dyn Check> = vec![&rust];
1812        let passed = vec!["pre-push-cargo-test".to_string()];
1813
1814        for changed in [
1815            vec!["app/routes/home.ts".to_string()],
1816            // Even the marker alone: editing Cargo.toml changes no Rust
1817            // source, so the suite has nothing new to have verified.
1818            vec!["Cargo.toml".to_string()],
1819            vec![],
1820        ] {
1821            assert!(
1822                attestable(&checks, &passed, &changed).is_empty(),
1823                "must not vouch for the Rust gate on {changed:?}"
1824            );
1825        }
1826    }
1827}