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/// Say out loud which checks did not run.
150///
151/// A skip is otherwise invisible at exactly the moment it matters. With
152/// `hook.skip = merge-conflict` set, a commit printed six green ticks and no
153/// hint that a seventh check had been disabled — the developer sees a clean run
154/// and concludes they are covered.
155///
156/// It is worse than it sounds, because one value can silence a whole stage:
157/// `hook.skip = pre-commit` suppresses all fifteen. That is now something
158/// somebody meant rather than the accident it once was — `e` used to cost
159/// twenty by substring reach — but a commit under it still looks exactly like a
160/// commit that had nothing to report.
161///
162/// One line, only when something was actually skipped, so a normal commit is
163/// unchanged. This reaches every skip however it was created — hand-edited
164/// config included — which no dashboard can claim.
165fn announce_skips(settings: &crate::config::Settings, dropped: &[&str]) {
166    if dropped.is_empty() {
167        return;
168    }
169    // Two lines, not one: "you decided this" (hook.skip on this machine)
170    // and "your team decided this" (a skip line in the committed
171    // amont.conf) are different things to be told — the same reason paused
172    // and held-back get their own sentences. A name both sources suppress
173    // is announced as the machine's: the local decision is the nearer one.
174    let (machine, _policy) = crate::skips_by_source(settings);
175    let (yours, theirs): (Vec<&&str>, Vec<&&str>) = dropped
176        .iter()
177        .partition(|name| machine.iter().any(|s| crate::skip_suppresses(name, s)));
178    let say = |names: &[&&str], via: &str| {
179        if names.is_empty() {
180            return;
181        }
182        let plural = if names.len() == 1 { "check" } else { "checks" };
183        println!(
184            "{} {} {plural} skipped by {}: {}",
185            warning_sign(),
186            names.len(),
187            highlight(via),
188            names.iter().map(|n| **n).collect::<Vec<_>>().join(", ")
189        );
190    };
191    say(&yours, "hook.skip");
192    say(&theirs, "amont.conf");
193}
194
195/// Say, once per stage, what the manifest's policy could not do — withheld
196/// behind trust, or aiming at names that exist nowhere. Policy that silently
197/// does not apply is a silent behaviour change, which is the one kind this
198/// codebase does not allow itself.
199fn announce_policy_state(settings: &crate::config::Settings, manifest: &crate::manifest::Manifest) {
200    if let Some(why) = manifest.policy_withheld {
201        println!(
202            "{} {} policy not applied: {why}",
203            warning_sign(),
204            highlight(crate::manifest::MANIFEST),
205        );
206    }
207    for note in &manifest.policy_notes {
208        println!("{} {}", warning_sign(), note);
209    }
210    // The version floor rides the same two call sites: once per stage,
211    // beside the other "this repository expects something you lack" lines.
212    crate::skew::announce_minimum(settings);
213}
214
215/// Run every item concurrently and collect `(name, code)` in the INPUT order.
216///
217/// Extracted so the concurrency itself can be tested with a rendezvous instead
218/// of a stopwatch — an earlier wall-clock test was flaky the moment the machine
219/// was busy, and a threshold that trips under load teaches you to ignore it.
220fn run_concurrently<T, R, F>(items: &[T], run: F, if_thread_died: R) -> Vec<R>
221where
222    T: Sync,
223    R: Send + Sync + Clone,
224    F: Fn(&T) -> R + Sync,
225{
226    let slots: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
227    std::thread::scope(|scope| {
228        for (item, slot) in items.iter().zip(&slots) {
229            let run = &run;
230            let died = &if_thread_died;
231            scope.spawn(move || {
232                // CAUGHT, not propagated. `thread::scope` re-raises a child
233                // panic in the parent, which would abort the whole hook with a
234                // backtrace and throw away the other nineteen checks' results —
235                // and would make `if_thread_died` unreachable, which is what it
236                // was until this test existed to notice.
237                let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(item)))
238                    .unwrap_or_else(|_| died.clone());
239                *slot.lock().expect("poisoned") = Some(outcome);
240            });
241        }
242    });
243    slots
244        .into_iter()
245        .map(|s| {
246            s.into_inner()
247                .expect("poisoned")
248                .unwrap_or_else(|| if_thread_died.clone())
249        })
250        .collect()
251}
252
253/// Take the index-fidelity hold, or say why the caller must stop.
254///
255/// Extracted from `pre_commit` so that `amont run` — which its own doc
256/// comment calls "a rehearsal of the hook" — can take exactly the same hold
257/// rather than judging the working tree while a real commit judges the index.
258///
259/// Around the WHOLE fan-out, not per check: twenty checks run concurrently and
260/// would fight over one working tree.
261fn hold_unstaged() -> Result<crate::staged_only::StagedOnly, Verdict> {
262    // BEFORE `enter()`, not after: `enter()` is what checks out the tree and
263    // parks the unstaged half, and a signal landing in the gap between that
264    // and the handler being armed would hit the default disposition — dead
265    // process, tree left checked out, nothing restored. The handler no-ops
266    // harmlessly on a signal that arrives before there is anything held.
267    crate::staged_only::install_signal_handler();
268    match crate::staged_only::StagedOnly::enter() {
269        Ok(guard) => Ok(guard),
270        Err(e) => {
271            // Refusing to check the wrong content is the safe direction; a
272            // check that read the tree would be answering about a commit
273            // nobody is making.
274            eprintln!("{e}");
275            Err(Verdict::Block)
276        }
277    }
278}
279
280pub fn pre_commit(ctx: &Ctx) -> Verdict {
281    let settings = ctx.settings;
282    // Before anything runs: a pinned tool at the wrong version makes every
283    // verdict below it suspect, and the warning costs one --version per pin.
284    crate::manifest::verify_tool_pins(&ctx.manifest.pins);
285    announce_policy_state(ctx.settings, ctx.manifest);
286    let in_progress = crate::git_states_in_progress();
287    let checks = selected_during(ctx.settings, Stage::PreCommit, &in_progress, ctx.manifest);
288
289    let held = match hold_unstaged() {
290        Ok(guard) => guard,
291        Err(verdict) => return verdict,
292    };
293
294    let severities = Overrides::read(settings);
295    let (verdict, outcomes) = run_stage_traced(settings, &checks, ctx, &severities);
296
297    // The shadow-mode ledger. Silent, best-effort, and never consulted by any
298    // verdict — see `crate::downgrade`.
299    crate::downgrade::note(
300        settings,
301        &downgraded_events(&checks, &outcomes, &severities),
302    );
303
304    // What post-commit will bind to the commit: the gate-declared checks
305    // that RAN clean, recorded while the index still is the commit's tree.
306    // Called on every verdict — an empty record clears any leftover marker,
307    // so a blocked attempt (or a repo with nothing declared) cannot leave an
308    // earlier attempt's marker to vouch for the next commit. `Unavailable`
309    // deliberately does not qualify: a check whose tool is missing judged
310    // nothing, and stamping it would be the paper promise this exists to
311    // replace.
312    // EVERY blocking declaration, not only the npm GATE names: a custom
313    // `pre-commit check … block …` earns its stamp the same way, and a
314    // same-named pre-push declaration defers to it (see `pair_verdict`).
315    let ran: Vec<String> = if matches!(verdict, Verdict::Block) {
316        Vec::new()
317    } else {
318        crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals)
319            .into_iter()
320            .filter(|d| {
321                checks
322                    .iter()
323                    .zip(&outcomes)
324                    .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Passed | Outcome::Fixed))
325            })
326            .map(|d| d.script)
327            .collect()
328    };
329    let ran: Vec<&str> = ran.iter().map(String::as_str).collect();
330    crate::gate_stamp::record(&ran);
331
332    drop(held);
333    verdict
334}
335
336/// The checks that FAILED without blocking, each with why — the shadow-mode
337/// signal [`crate::downgrade`] keeps.
338///
339/// Derived at the hook entry points and deliberately NOT inside
340/// [`run_stage_traced`], which is where `classify` already computes the same
341/// set. `run_all` reaches that function too, so recording there would let
342/// every `amont run` rehearsal inflate a ledger a lead is going to read as a
343/// count of real commits — and `run --all-files` over a dirty tree would add
344/// dozens of events for content nobody is committing.
345///
346/// A check that DECLARES `warn` is counted but is not evidence about a
347/// rollout: it was never going to block, so calling it "would have blocked"
348/// would inflate the one number the whole feature exists to produce. Only an
349/// override of a blocking check earns that.
350fn downgraded_events(
351    checks: &[&dyn Check],
352    outcomes: &[Outcome],
353    severities: &Overrides,
354) -> Vec<(String, crate::downgrade::Origin)> {
355    checks
356        .iter()
357        .zip(outcomes)
358        .filter(|(_, o)| matches!(o, Outcome::Failed))
359        .filter(|(c, _)| matches!(severities.of(**c), Severity::Warn))
360        .map(|(c, _)| (c.name().to_string(), downgrade_origin(*c, severities)))
361        .collect()
362}
363
364/// Why this check did not block. Shared, because `pre_push` fail-fasts and
365/// never builds an outcomes vector to hand to [`downgraded_events`].
366fn downgrade_origin(check: &dyn Check, severities: &Overrides) -> crate::downgrade::Origin {
367    use crate::downgrade::Origin;
368    use crate::registry::Source;
369    if matches!(check.severity(), Severity::Warn) {
370        return Origin::Declared;
371    }
372    match severities.applied_with_source(check.name()) {
373        Some((_, _, Source::Config)) => Origin::Config,
374        Some((_, _, Source::Policy)) => Origin::Policy,
375        // Declared `block`, resolved `warn`, and nothing claims to have
376        // overridden it: a contradiction. Count it, but not as evidence — the
377        // conservative direction for a number whose only failure mode is
378        // being too alarming.
379        None => Origin::Declared,
380    }
381}
382
383/// The pre-commit body, over the checks it is GIVEN.
384///
385/// A seam, so a test can hand it a check that panics. Without it the value
386/// standing in for a dead check was a literal at one call site that no test
387/// could reach — the rule was asserted on the runner and merely hoped for here.
388fn run_stage(checks: &[&dyn Check], ctx: &Ctx, severities: &Overrides) -> Verdict {
389    let settings = ctx.settings;
390    run_stage_traced(settings, checks, ctx, severities).0
391}
392
393/// [`run_stage`], keeping the per-check outcomes — index-aligned with
394/// `checks` — alive past the verdict. `pre_commit` needs them to know which
395/// gate-declared checks actually ran (`gate_stamp`); `Report` cannot answer
396/// that, because `classify` deliberately drops the names of `Passed`.
397fn run_stage_traced(
398    settings: &crate::config::Settings,
399    checks: &[&dyn Check],
400    ctx: &Ctx,
401    severities: &Overrides,
402) -> (Verdict, Vec<Outcome>) {
403    if checks.is_empty() {
404        return (Verdict::Proceed, Vec::new());
405    }
406    // One slot per check: everything a check says lands in its own buffer
407    // and reaches stdout as ONE block when it finishes — see `live`. Off
408    // (`amont.progress false`), no sink is ever installed and every print
409    // streams exactly as it always did.
410    let stage = crate::live::enabled(settings).then(|| {
411        let names: Vec<&str> = checks.iter().map(|c| c.name()).collect();
412        crate::live::Stage::begin(settings, &names)
413    });
414    let items: Vec<(usize, &&dyn Check)> = checks.iter().enumerate().collect();
415    let outcomes = run_concurrently(
416        &items,
417        |(idx, check)| {
418            let _sink = stage.as_ref().map(|s| s.enter(*idx));
419            // The block is emitted however the check leaves — a panicking
420            // check's partial output still reaches the reader, above the
421            // dead-check verdict `run_concurrently` fills in.
422            let _flush = stage
423                .as_ref()
424                .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, *idx));
425            let sub = Ctx {
426                name: check.name(),
427                args: ctx.args,
428                hooks_dir: ctx.hooks_dir,
429                push: ctx.push,
430                manifest: ctx.manifest,
431                settings: ctx.settings,
432            };
433            check.run(&sub)
434        },
435        // A check whose thread died has not passed. Stated here, where the slot
436        // is filled, rather than hidden in a `Default` impl that every future
437        // `#[derive(Default)]` would silently inherit.
438        Outcome::Failed,
439    );
440
441    let report = classify(checks, &outcomes, severities);
442    announce(settings, &report);
443    (report.verdict(), outcomes)
444}
445
446/// What a stage concluded, before anything is printed or exited.
447///
448/// A VALUE, so the classification can be asserted directly. While this was one
449/// function that classified, printed and returned an exit code, its tests could
450/// only check the code — whether the right thing was SAID went untested.
451#[derive(Debug, Default, PartialEq, Eq)]
452struct Report<'a> {
453    /// Repaired. The commit proceeds, but the author's files changed under
454    /// them and that must be said out loud.
455    fixed: Vec<&'a str>,
456    /// Failed, and the severity that applies blocks.
457    blocked: Vec<&'a str>,
458    /// Failed, but configured to warn. The check printed an error and meant it,
459    /// so somebody has to say it did not block.
460    downgraded: Vec<&'a str>,
461    /// Could not run. Distinct from "passed", which is the whole point.
462    unavailable: Vec<&'a str>,
463    /// How many passed outright. Only read when `amont.quiet` swallowed their
464    /// individual lines — a run that says nothing at all is indistinguishable
465    /// from a gate that never ran, and that is the one thing this crate will
466    /// not let a reader believe.
467    passed: usize,
468}
469
470impl Report<'_> {
471    fn verdict(&self) -> Verdict {
472        Verdict::blocking(!self.blocked.is_empty())
473    }
474}
475
476/// Pure: outcomes and severities in, a verdict out. No IO.
477fn classify<'a>(
478    checks: &[&'a dyn Check],
479    outcomes: &[Outcome],
480    severities: &Overrides,
481) -> Report<'a> {
482    let mut report = Report::default();
483    for (check, outcome) in checks.iter().zip(outcomes) {
484        match outcome {
485            Outcome::Passed => report.passed += 1,
486            // `Warned` needs nothing: a check that chose to warn has already
487            // said what it wanted to, and a roll-up would only repeat it.
488            Outcome::Warned => {}
489            Outcome::Fixed => report.fixed.push(check.name()),
490            Outcome::Unavailable => report.unavailable.push(check.name()),
491            Outcome::Failed => match severities.of(*check) {
492                Severity::Block => report.blocked.push(check.name()),
493                Severity::Warn => report.downgraded.push(check.name()),
494            },
495        }
496    }
497    report
498}
499
500/// Says what happened. Prints; decides nothing.
501fn announce(settings: &crate::config::Settings, report: &Report) {
502    if crate::live::quiet(settings) && report.passed > 0 {
503        println!("{} {} check(s) passed", valid_sign(), report.passed);
504    }
505    if !report.fixed.is_empty() {
506        // Louder than a pass, because files on disk are not what the author
507        // left them: they asked for the repair, but they did not watch it.
508        println!(
509            "{} {} check(s) fixed and re-staged: {}",
510            valid_sign(),
511            report.fixed.len(),
512            report.fixed.join(", ")
513        );
514    }
515    if !report.unavailable.is_empty() {
516        // Distinct from "passed". Silence here is how a repo looks verified
517        // when nothing actually ran — the trailing count is the one line
518        // guaranteed to be read, whatever the twenty blocks above said.
519        println!(
520            "{} {} check(s) could not run: {}",
521            warning_sign(),
522            report.unavailable.len(),
523            report.unavailable.join(", ")
524        );
525    }
526    if !report.downgraded.is_empty() {
527        println!(
528            "{} {} check(s) reported a problem but are set to warn: {}",
529            warning_sign(),
530            report.downgraded.len(),
531            report.downgraded.join(", ")
532        );
533    }
534    if report.blocked.is_empty() {
535        return;
536    }
537    println!("\n🚨  Error raised by:");
538    for name in &report.blocked {
539        println!("    - {}", highlight(name));
540    }
541}
542
543/// Point every check at `git ls-files` instead of the index.
544///
545/// THE definition, called from both entry points. There used to be two: this
546/// one, and a copy in `main.rs` built from a RAW `ls-files` — no `-z` — whose
547/// output git QUOTES for any unusual byte, so `é.json` arrived as the nine-byte
548/// literal `"\303\251.json"` and was handed to prettier and eslint as a path
549/// that does not exist. And because `override_file_set` writes a `OnceLock`,
550/// main's quoted list WON: whichever ran first was the one that counted, and
551/// main's ran first. `git.rs` documents this exact failure.
552pub fn enter_all_files_mode() {
553    crate::hooks::common::override_file_set(
554        crate::git::stdout_paths(&["ls-files"]).unwrap_or_default(),
555    );
556}
557
558/// `amont run` — every applicable check, on demand.
559///
560/// Two questions, and the mode says which it answers:
561///
562/// - **staged** (default) is "would my commit pass" — the same set a commit
563///   would check, so it is a rehearsal of the hook, and it takes the same
564///   index-fidelity hold the hook takes.
565/// - **`--all-files`** is "does my working tree pass". Deliberately NOT the same
566///   question: on a dirty tree it reports on content that is not committed and
567///   may never be. That is right for adopting a check into an existing
568///   repository, where `git add .` is not an acceptable way to measure the mess,
569///   and it is why `--all-files` takes no stash — there is no staged/unstaged
570///   distinction to protect when the answer is "all of it".
571pub fn run_all(ctx: &Ctx, all_files: bool) -> Verdict {
572    let settings = ctx.settings;
573    // ORDER: the override goes in FIRST. It is what tells `fixing_enabled` and
574    // `restage` that the file set is not the index, and both are consulted
575    // from inside the checks below.
576    if all_files {
577        enter_all_files_mode();
578        if crate::hooks::common::fixing_requested(settings) {
579            println!(
580                "{} {} is set, but fixing is off for {}: the input set is the \
581                 working tree, not the index",
582                warning_sign(),
583                highlight("amont.fix"),
584                highlight("--all-files")
585            );
586        }
587        // Stash-free, per decision 1 of docs/index-fidelity-and-run-modes.md:
588        // there is no staged/unstaged distinction to protect when the input
589        // set is `git ls-files`, so a hold would be surprising extra mutation
590        // with no correctness upside.
591        return run_stage(
592            &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
593            ctx,
594            &Overrides::read(settings),
595        );
596    }
597
598    // Staged mode IS a rehearsal of the commit, so it takes the same hold the
599    // commit does. Without it, `amont run` failed on garbage in the tree
600    // that `git commit` — which holds the unstaged half aside — passed, and
601    // vice versa: the two modes disagreed about the same repository, which is
602    // exactly what this mode exists not to do.
603    let held = match hold_unstaged() {
604        Ok(guard) => guard,
605        Err(verdict) => return verdict,
606    };
607    let verdict = run_stage(
608        &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
609        ctx,
610        &Overrides::read(settings),
611    );
612    // AFTER the report has been printed: dropping earlier would put the
613    // unstaged content back under a check that is still reading files.
614    drop(held);
615    verdict
616}
617
618/// `amont run <check>` — one check by name. `None` when there is no such
619/// check, which the caller turns into a usage error.
620///
621/// Lives here rather than in `main.rs` so `registry::lookup` stays inside the
622/// runtime, and so the hold decision is made once: a named check takes the
623/// index-fidelity hold only when it is a `Stage::PreCommit` check running in
624/// staged mode. A pre-push or commit-msg check invoked by name must never
625/// touch the working tree — nothing about a push is a staging operation.
626/// Resolve what `amont run <name>` means, exactly as `hook.skip` resolves a
627/// name — the rest of the tool taught `ban-terms`; making `run` demand the
628/// full id was a pointless second vocabulary. Ambiguity is an answer, not a
629/// guess: the two `branch-pattern` checks are different code at different
630/// stages.
631///
632/// Public because the CALLER needs the answer before anything else happens:
633/// main decides whether to synthesize push refs from the resolved name, and
634/// an ambiguous name must say so rather than fail on a missing upstream it
635/// was never going to use.
636pub fn resolve_check_name(name: &str, manifest: &crate::manifest::Manifest) -> Named2 {
637    if crate::registry::lookup(name, manifest).is_some() {
638        return Named2::Resolved(name.to_string());
639    }
640    let mut matches: Vec<String> = crate::registry::CHECKS
641        .iter()
642        .map(|c| c.name.to_string())
643        .chain(manifest.externals.iter().map(|e| e.id.clone()))
644        .filter(|id| crate::skip_suppresses(id, name))
645        .collect();
646    matches.dedup();
647    match matches.len() {
648        0 => Named2::Unknown,
649        1 => Named2::Resolved(matches.remove(0)),
650        _ => Named2::Ambiguous(matches),
651    }
652}
653
654/// How a run name resolved.
655pub enum Named2 {
656    Resolved(String),
657    Unknown,
658    Ambiguous(Vec<String>),
659}
660
661pub fn run_named(ctx: &Ctx, name: &str, all_files: bool) -> Named {
662    let full: String = match resolve_check_name(name, ctx.manifest) {
663        Named2::Resolved(id) => id,
664        Named2::Unknown => return Named::Unknown,
665        Named2::Ambiguous(ids) => return Named::Ambiguous(ids),
666    };
667    let name = full.as_str();
668    let Some(run_check) = crate::registry::lookup(name, ctx.manifest) else {
669        return Named::Unknown;
670    };
671    // The Ctx must carry the RESOLVED id: lookup's closure re-resolves
672    // through `ctx.name`, and handing it the short name back would panic on
673    // the very ambiguity this function just settled.
674    let ctx = &Ctx {
675        name,
676        args: ctx.args,
677        hooks_dir: ctx.hooks_dir,
678        push: ctx.push,
679        manifest: ctx.manifest,
680        settings: ctx.settings,
681    };
682    if all_files {
683        enter_all_files_mode();
684        return Named::Ran(run_check(ctx));
685    }
686    let is_pre_commit_check = crate::registry::one_named(name, ctx.manifest)
687        .is_some_and(|c| c.stage() == Stage::PreCommit);
688    if !is_pre_commit_check {
689        return Named::Ran(run_check(ctx));
690    }
691    let held = match hold_unstaged() {
692        Ok(guard) => guard,
693        Err(verdict) => return Named::Ran(verdict),
694    };
695    let verdict = run_check(ctx);
696    drop(held);
697    Named::Ran(verdict)
698}
699
700/// What `run_named` resolved a name to.
701pub enum Named {
702    Ran(Verdict),
703    /// Nothing matches — full id, short name, or entrypoint.
704    Unknown,
705    /// A short name that reaches more than one check; the caller lists them
706    /// so the user can pick a full id.
707    Ambiguous(Vec<String>),
708}
709
710pub fn pre_push(ctx: &Ctx) -> Verdict {
711    let settings = ctx.settings;
712    // The notes push `attest` makes re-enters this hook; its ref list is only
713    // ever the attest ref, so there is nothing to prove — and proving it
714    // would recurse.
715    if crate::attest::push_guard_active() {
716        return Verdict::Proceed;
717    }
718    crate::manifest::verify_tool_pins(&ctx.manifest.pins);
719    announce_policy_state(ctx.settings, ctx.manifest);
720    // NB: no CHERRY_PICK_HEAD check here — the zsh pre-push had none either.
721    let severities = Overrides::read(settings);
722    // pre-push had NO state guard at all, with a comment admitting it existed
723    // only because the zsh version had none. Now it asks the same question
724    // pre-commit does and each check answers for itself.
725    let in_progress = crate::git_states_in_progress();
726    let pre_push_checks = selected_during(ctx.settings, Stage::PrePush, &in_progress, ctx.manifest);
727    let stage = crate::live::enabled(settings).then(|| {
728        let names: Vec<&str> = pre_push_checks.iter().map(|c| c.name()).collect();
729        crate::live::Stage::begin(settings, &names)
730    });
731    // What actually PASSED, for the attestation at the bottom. `Warned` and
732    // `Unavailable` stay out — "could not run" is not "passed" — and a
733    // commit-time-gated pair counts, because its stamps say the check ran on
734    // every pushed tree.
735    let mut passed: Vec<String> = Vec::new();
736    // Accumulated rather than written per check: one append at the end costs a
737    // single file open, and the loop below can leave early.
738    let mut downgraded: Vec<(String, crate::downgrade::Origin)> = Vec::new();
739    // PUSH STAMPS. The tips being pushed, and what earlier runs of THIS gate
740    // recorded against their trees — an `amont run pre-push` rehearsal, or a
741    // push whose gate passed and whose transport then died. A scoped gate
742    // (a test suite: its verdict is a function of the tree alone) whose
743    // stamp sits on every tip is not run again; the unscoped ones
744    // (branch-protect, secrets — questions about the push, not the content)
745    // always run. `amont.pushStamps false` turns the reuse off.
746    //
747    // Reading `ctx.push` here may consume stdin, exactly as `attest` does
748    // below; every pre-push check reads it anyway.
749    let tips: Vec<String> = {
750        let mut t: Vec<String> = ctx
751            .push
752            .get()
753            .iter()
754            .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
755            .map(|r| r.local_oid.clone())
756            .collect();
757        t.dedup();
758        t
759    };
760    let reuse_stamps = crate::gate_stamp::push_stamps_enabled(settings);
761    // The working tree AS THE SUITE WILL BE HANDED IT, captured before any
762    // gate has run.
763    //
764    // Timing is the point. Asking afterwards means a gate that modifies a
765    // tracked file — a formatter, a suite that updates a snapshot fixture —
766    // disqualifies its OWN stamp. What a stamp needs to know is what the
767    // suite could READ, which is the state it was handed; a change the suite
768    // itself made was never an input to it.
769    //
770    // Tracked modifications only. `stamp_tips` argues that gap, which is a
771    // deliberate one.
772    let tree_at_start = if reuse_stamps {
773        crate::git::stdout(&["status", "--porcelain", "--untracked-files=no"]).unwrap_or_default()
774    } else {
775        String::new()
776    };
777    // A background rehearsal of one of these tips may be mid-suite right
778    // now. Waiting for it is strictly less work than starting over, and
779    // its stamp — read AFTER the wait, below — is the hand-off.
780    if reuse_stamps && !tips.is_empty() {
781        crate::rehearsal::await_for(settings, &tips);
782    }
783    let push_stamps = if reuse_stamps && !tips.is_empty() {
784        crate::gate_stamp::stamps_for(&tips)
785    } else {
786        Default::default()
787    };
788    // Inside a rehearsal snapshot only the content gates make sense: the
789    // unscoped checks ask about a PUSH — its branch name, its target, its
790    // secrets — and no push is happening. Said once, not per check.
791    let rehearsing = crate::rehearsal::in_snapshot();
792    if rehearsing {
793        crate::say!(
794            "rehearsal: running the test gates only — the push-shaped checks run at push time"
795        );
796    }
797    let stamped_on_every_tip = |name: &str| -> bool {
798        !tips.is_empty()
799            && tips.iter().all(|t| {
800                push_stamps
801                    .get(t)
802                    .is_some_and(|s| s.iter().any(|g| g == name))
803            })
804    };
805    // What actually RAN and passed here (as opposed to being vouched for by
806    // a stamp) — the set this run may stamp in turn.
807    let mut ran_and_passed: Vec<String> = Vec::new();
808    for (idx, check) in pre_push_checks.iter().enumerate() {
809        let _sink = stage.as_ref().map(|s| s.enter(idx));
810        let _flush = stage
811            .as_ref()
812            .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, idx));
813        // A declared pre-push external whose NAME is also declared at
814        // pre-commit (blocking) is a gate pair: the commit-time side earned
815        // per-commit stamps, and this side runs only for pushes carrying
816        // commits with no record of it — the same contract the npm gate has
817        // always had, for vocabularies npm never heard of (`cargo test`,
818        // `pytest`, anything). Messages mirror the npm gate's exactly;
819        // docs/checks.md quotes them.
820        // The push side of a pair is `(name, scope)`, from whichever of the
821        // two kinds of check this is. A declared pre-push external supplies
822        // its own; anything else is a BUILT-IN, and `pairing_name` plus the
823        // registry's scope say the same two things about it.
824        //
825        // The external is tried FIRST and its inputs are unchanged, so the
826        // declared path behaves exactly as before — that is what the
827        // untouched declared-pair tests prove.
828        if rehearsing && check.scope().is_unscoped() {
829            continue;
830        }
831        if !check.scope().is_unscoped() && stamped_on_every_tip(check.name()) {
832            crate::say!(
833                "{} {} passed on this exact tree earlier — not repeating it here",
834                valid_sign(),
835                highlight(check.name()),
836            );
837            passed.push(check.name().to_string());
838            continue;
839        }
840        let declared = ctx
841            .manifest
842            .externals
843            .iter()
844            .find(|e| e.stage == Stage::PrePush && e.id == check.name());
845        let builtin_scope = check.scope();
846        let pairing: Option<(&str, &crate::check::Scope)> = match declared {
847            Some(ext) => match &ext.kind {
848                crate::manifest::Kind::Runnable { scope, .. } => {
849                    Some((ext.short_name.as_str(), scope))
850                }
851                // A declared pre-push entry that runs nothing has no scope to
852                // judge with, and is not a built-in either. Nothing to pair.
853                _ => None,
854            },
855            None => Some((check.pairing_name(), &builtin_scope)),
856        };
857        if let Some((name, push_scope)) = pairing {
858            match crate::hooks::run_tests::pair_verdict(
859                ctx.settings,
860                name,
861                push_scope,
862                ctx.manifest,
863                ctx.push,
864            ) {
865                crate::hooks::run_tests::PairVerdict::Gated => {
866                    crate::say!(
867                        "{} {} gated at commit instead — not repeating it here",
868                        valid_sign(),
869                        highlight(name),
870                    );
871                    passed.push(check.name().to_string());
872                    continue;
873                }
874                crate::hooks::run_tests::PairVerdict::Unstamped(n) => {
875                    crate::say!(
876                        "{} {} is declared at commit time, but {n} pushed \
877                         commit{} carr{} no record of it — running it here",
878                        warning_sign(),
879                        name,
880                        if n == 1 { "" } else { "s" },
881                        if n == 1 { "ies" } else { "y" },
882                    );
883                }
884                crate::hooks::run_tests::PairVerdict::NotPaired => {}
885            }
886        }
887        let sub = Ctx {
888            name: check.name(),
889            args: ctx.args,
890            hooks_dir: ctx.hooks_dir,
891            push: ctx.push,
892            manifest: ctx.manifest,
893            settings: ctx.settings,
894        };
895        match check.run(&sub) {
896            Outcome::Passed => {
897                passed.push(check.name().to_string());
898                if !check.scope().is_unscoped() {
899                    ran_and_passed.push(check.name().to_string());
900                }
901            }
902            // Announced, never fatal: a check that could not run has not
903            // invalidated anything, and neither has a warning.
904            Outcome::Unavailable => {
905                println!(
906                    "{} {} could not run",
907                    warning_sign(),
908                    highlight(check.name())
909                )
910            }
911            Outcome::Warned => {}
912            // Cannot occur: `Fix::Rewrite` is refused on a pre-push
913            // declaration, so nothing here can repair anything.
914            Outcome::Fixed => {}
915            Outcome::Failed => match severities.of(*check) {
916                Severity::Warn => {
917                    downgraded.push((
918                        check.name().to_string(),
919                        downgrade_origin(*check, &severities),
920                    ));
921                    println!(
922                        "{} {} reported a problem (severity warn)",
923                        warning_sign(),
924                        highlight(check.name())
925                    );
926                }
927                // Fail-fast applies ONLY to Block: the later steps are
928                // expensive and their preconditions are gone.
929                Severity::Block => {
930                    // Record what already warned before leaving. Those checks
931                    // ran and reported; a later check blocking does not unmake
932                    // them, and dropping them here would make the ledger quietly
933                    // under-count every push that ended badly.
934                    crate::downgrade::note(settings, &downgraded);
935                    println!("\n🚨  Error raised by hook {}", highlight(check.name()));
936                    return Verdict::Block;
937                }
938            },
939        }
940    }
941    // Every block gate passed — stamp the tips with the scoped gates that
942    // RAN here, so the next push of this content (a retry after a dropped
943    // connection, or the real push after an `amont run pre-push` rehearsal)
944    // skips them. Only when what ran is what is being pushed: with
945    // `amont.testPushedTree` the suite ran on the tip itself — unless the
946    // snapshot could not be made, which `stamp_tips` asks about rather than
947    // assuming; otherwise it ran on the working tree, which vouches for the
948    // tip only when the two are the same content — HEAD, with nothing
949    // modified and nothing untracked.
950    // The same proxy `attestable` uses, for the same reason: a scoped gate
951    // whose files the push never touched returns `Passed` having run
952    // nothing, and a stamp for THAT would let a later push that does touch
953    // them skip a suite nobody ran.
954    if reuse_stamps && !ran_and_passed.is_empty() {
955        let changed = crate::pushrefs::changed_files(ctx.push.get());
956        let really_ran: Vec<String> = pre_push_checks
957            .iter()
958            .filter(|c| ran_and_passed.iter().any(|p| p == c.name()))
959            .filter(|c| c.scope().touches(&changed))
960            .map(|c| c.name().to_string())
961            .collect();
962        stamp_tips(settings, &tips, &really_ran, &tree_at_start);
963    }
964    // …and say so to CI, if this repository opted in.
965    // Gated behind `enabled()` HERE, not just inside `attest_push`: reading
966    // `ctx.push` may consume stdin, and a disabled repo should leave stdin
967    // exactly as it found it.
968    if !passed.is_empty() && crate::attest::enabled(settings) {
969        let remote = ctx
970            .args
971            .first()
972            .map(|a| a.to_string_lossy().into_owned())
973            .unwrap_or_default();
974        let changed = crate::pushrefs::changed_files(ctx.push.get());
975        let vouched = attestable(&pre_push_checks, &passed, &changed);
976        crate::attest::attest_push(ctx.settings, &remote, ctx.push.get(), &vouched);
977    }
978    crate::downgrade::note(settings, &downgraded);
979    Verdict::Proceed
980}
981
982/// The scoped pre-push gates — test suites — that have work to do for a
983/// push that changed `changed`: what a rehearsal would run, and therefore
984/// what its stamp would have to name before a push may skip anything.
985///
986/// The same two filters `pre_push` applies before stamping (selected here,
987/// and `scope().touches` the change), so the rehearsal's idea of "nothing to
988/// do" is the push's idea of "nothing to stamp".
989pub fn scoped_push_gates(
990    settings: &crate::config::Settings,
991    manifest: &crate::manifest::Manifest,
992    changed: &[String],
993) -> Vec<String> {
994    let in_progress = crate::git_states_in_progress();
995    selected_during(settings, Stage::PrePush, &in_progress, manifest)
996        .into_iter()
997        .filter(|c| !c.scope().is_unscoped() && c.scope().touches(changed))
998        .map(|c| c.name().to_string())
999        .collect()
1000}
1001
1002/// Push-stamp every tip whose content is what the gates actually tested.
1003///
1004/// See the comment at the call site for the two cases. Silent when nothing
1005/// qualifies — a dirty working tree is the ordinary state of a machine
1006/// mid-work, and a note on every push would teach people to ignore it.
1007fn stamp_tips(
1008    settings: &crate::config::Settings,
1009    tips: &[String],
1010    gates: &[String],
1011    tree_at_start: &str,
1012) {
1013    let pushed_tree_mode = crate::pushed_tree::enabled(settings);
1014    let head = crate::git::stdout(&["rev-parse", "HEAD"]);
1015    // TRACKED modifications only — a KNOWN gap, kept deliberately, and
1016    // spelled out because the comment that used to sit here argued it
1017    // backwards ("untracked files are not in any tree the suite could have
1018    // been asked about"). That is not the reason. The danger is not that the
1019    // tree lacks them, it is that the RUN had them: a new test file, a
1020    // fixture, a local `.env`, present while the suite ran and absent from
1021    // the tree the stamp vouches for.
1022    //
1023    // Counting them was tried, and is worse than the gap. Gates leave
1024    // artefacts — a log, a coverage directory, whatever a declared
1025    // `amont.conf` command writes — and nothing cleans them up, so a
1026    // repository using declared gates would stop earning stamps permanently
1027    // after its first commit. That does not merely lose an optimisation: it
1028    // puts the suite back INSIDE the push, which is the failure the whole
1029    // stamping mechanism exists to prevent. amont's own
1030    // `a_push_stamp_merges_with_a_commit_time_stamp` fixture is exactly that
1031    // shape, and CI is where it surfaced — a `*.log` line in one developer's
1032    // global gitignore had hidden it on the machine that wrote the change.
1033    //
1034    // `amont.testPushedTree true` closes the gap properly for anyone who
1035    // wants it closed: it runs the suite in a checkout of the commit, where
1036    // no untracked file exists to be read.
1037    //
1038    // `tree_at_start` — not a fresh `git status`. The gates have run by now
1039    // and may have written into the tree; what a stamp needs to know is what
1040    // the suite could READ, which is the state it was handed. See the
1041    // capture in `pre_push`.
1042    let worktree_clean = tree_at_start.trim().is_empty();
1043    let in_snapshot = crate::rehearsal::in_snapshot();
1044    let mut stamped: Vec<&str> = Vec::new();
1045    for tip in tips {
1046        // `pushed_tree_mode` is the CONFIG, not what happened. A snapshot
1047        // that could not be created falls back to the working tree and says
1048        // so, and stamping on the strength of the flag vouched for content
1049        // the suite never saw. `pushed_tree::fell_back` is what actually
1050        // happened.
1051        let snapshot_ran = pushed_tree_mode && !crate::pushed_tree::fell_back(tip);
1052        // Inside a rehearsal the working tree IS a checkout git made of this
1053        // commit, so it is the tip's content by construction — and whatever
1054        // `amont.snapshotPrepare` had to add to make it runnable (a
1055        // `node_modules`, a virtualenv) is not a reason to distrust it. That
1056        // is the same argument `snapshot_ran` makes for the pushed-tree mode.
1057        let is_head = head.as_deref() == Some(tip.as_str());
1058        let vouchable = snapshot_ran || (is_head && (in_snapshot || worktree_clean));
1059        if !vouchable {
1060            continue;
1061        }
1062        let spec = format!("{tip}^{{tree}}");
1063        let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
1064            continue;
1065        };
1066        if crate::gate_stamp::stamp_push(tip, &tree, gates) {
1067            stamped.push(tip);
1068        }
1069    }
1070    if !stamped.is_empty() {
1071        crate::say!(
1072            "{} stamped {} for this tree — the next push of it skips them ({})",
1073            valid_sign(),
1074            highlight(&gates.join(" ")),
1075            crate::gate_stamp::NOTES_REF,
1076        );
1077    }
1078}
1079
1080/// Of the checks that passed, the ones an attestation may actually VOUCH for.
1081///
1082/// A language gate whose scope the push never touched returns `Passed` having
1083/// run nothing — `cargo_test` walks its refs, finds no crate root, and falls
1084/// out of the loop green. That is right for a push gate (there was nothing to
1085/// object to) and wrong for an attestation: a JS-only push was minting
1086/// `gates … pre-push-cargo-test pre-push-go-test pre-push-pytest`, and in a
1087/// MIXED repository CI would then skip a suite that nobody ran on that tree.
1088///
1089/// The declared `scope` is the honest filter, and the same data `amont list`
1090/// already reports. Unscoped checks (`Scope::ALWAYS` — branch-protect,
1091/// secrets) match everything and are vouched for, which is accurate: they
1092/// really did run. An empty `changed` vouches for nothing scoped, which is
1093/// the safe direction — CI runs the suite.
1094///
1095/// [`Scope::touches`], NOT `Scope::matches`. `matches` also asks whether the
1096/// repository has opted in — whether a `Cargo.toml` exists — and asking that
1097/// of a push DIFF can only answer no unless the push happened to touch the
1098/// marker. So `pre-push-cargo-test` was vouched for by a push that edited
1099/// `Cargo.toml` and never by one that edited only `.rs` files, which is the
1100/// ordinary case and the one worth skipping CI for. The feature attested
1101/// almost nothing, silently, and looked like it worked.
1102///
1103/// WHAT THIS IS STILL A PROXY FOR, stated plainly because the trust path
1104/// deserves it: the honest question is "did this gate actually run", and no
1105/// gate reports that. `rust_tools::test` returns `Passed` whether it ran a
1106/// suite or found no crate root and fell out of its loop — the very thing
1107/// the first paragraph describes. Scope is the closest available stand-in.
1108/// It is now a good one: a gate is vouched for only if the push changed a
1109/// file its extensions cover.
1110///
1111/// The gap that remains is narrow and one-directional: a `.rs` file outside
1112/// every crate would be covered here while `cargo test` had nothing to say
1113/// about it. Closing it properly means an outcome that distinguishes "ran
1114/// and passed" from "found nothing to do", which is a change to every gate
1115/// and to `Outcome` itself — worth doing, not worth smuggling into this.
1116fn attestable(checks: &[&dyn Check], passed: &[String], changed: &[String]) -> Vec<String> {
1117    checks
1118        .iter()
1119        .filter(|c| passed.iter().any(|p| p == c.name()))
1120        .filter(|c| c.scope().touches(changed))
1121        .map(|c| c.name().to_string())
1122        .collect()
1123}
1124
1125#[cfg(test)]
1126mod tests {
1127    use super::*;
1128    use crate::check::{Builtin, Scope};
1129    use std::sync::atomic::{AtomicUsize, Ordering};
1130
1131    /// A check whose only job is to carry a name and a severity into `report`.
1132    /// Its `run` is never called — `report` is fed outcomes directly, which is
1133    /// what makes `Unavailable` testable at all: the real thing needs a missing
1134    /// binary, and a test that uninstalls the developer's toolchain is worse
1135    /// than no test.
1136    const fn stub(name: &'static str, severity: Severity) -> Builtin {
1137        Builtin {
1138            name,
1139            stage: Stage::PreCommit,
1140            scope: Scope::ALWAYS,
1141            severity,
1142            run: |_| Outcome::Passed,
1143            fix: crate::check::Fix::None,
1144            reach: crate::check::Reach::Convention,
1145        }
1146    }
1147
1148    /// A pre-push gate with an OPT-IN file, as the real Rust and Python
1149    /// gates have: `.rs` files, but only where a `Cargo.toml` exists.
1150    const fn opt_in(
1151        name: &'static str,
1152        exts: &'static [&'static str],
1153        names: &'static [&'static str],
1154    ) -> Builtin {
1155        Builtin {
1156            name,
1157            stage: Stage::PrePush,
1158            scope: Scope::new(exts, names),
1159            severity: Severity::Block,
1160            run: |_| Outcome::Passed,
1161            fix: crate::check::Fix::None,
1162            reach: crate::check::Reach::Convention,
1163        }
1164    }
1165
1166    /// A pre-push gate scoped to one language's files.
1167    const fn scoped(name: &'static str, exts: &'static [&'static str]) -> Builtin {
1168        Builtin {
1169            name,
1170            stage: Stage::PrePush,
1171            scope: Scope::new(exts, &[]),
1172            severity: Severity::Block,
1173            run: |_| Outcome::Passed,
1174            fix: crate::check::Fix::None,
1175            reach: crate::check::Reach::Convention,
1176        }
1177    }
1178
1179    /// The over-claim this filter exists to stop, caught in the wild: a
1180    /// JS-only push minted `gates … pre-push-cargo-test pre-push-go-test
1181    /// pre-push-pytest`, because each of those gates finds nothing of its
1182    /// language to do and returns `Passed` having run NOTHING. Harmless in a
1183    /// single-language repo, unsound in a mixed one — CI would skip a suite
1184    /// nobody ran on that tree.
1185    #[test]
1186    fn a_gate_whose_language_the_push_never_touched_is_not_vouched_for() {
1187        let js = scoped("pre-push-run-tests-js", &[".ts", ".js"]);
1188        let rust = scoped("pre-push-cargo-test", &[".rs"]);
1189        let py = scoped("pre-push-pytest", &[".py"]);
1190        let always = stub("pre-push-secrets", Severity::Block);
1191        let checks: Vec<&dyn Check> = vec![&js, &rust, &py, &always];
1192        let passed: Vec<String> = checks.iter().map(|c| c.name().to_string()).collect();
1193
1194        let changed = vec!["app/routes/home.ts".to_string()];
1195        let vouched = attestable(&checks, &passed, &changed);
1196        assert_eq!(
1197            vouched,
1198            vec![
1199                "pre-push-run-tests-js".to_string(),
1200                "pre-push-secrets".to_string()
1201            ],
1202            "only the gate that had work, plus the unscoped one that always runs"
1203        );
1204
1205        // Nothing computed about the push vouches for nothing scoped — the
1206        // safe direction, since CI then runs the suite.
1207        assert_eq!(
1208            attestable(&checks, &passed, &[]),
1209            vec!["pre-push-secrets".to_string()]
1210        );
1211
1212        // A check that did NOT pass is never vouched for, whatever its scope.
1213        let only_rust_passed = vec!["pre-push-cargo-test".to_string()];
1214        assert!(attestable(&checks, &only_rust_passed, &changed).is_empty());
1215    }
1216
1217    /// No overrides configured. `report` takes them as a VALUE now, so its
1218    /// tests need no repository and no git at all.
1219    fn none() -> Overrides {
1220        Overrides::default()
1221    }
1222
1223    static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
1224    static WARNER: Builtin = stub("stub-warner", Severity::Warn);
1225
1226    /// The unit tests hold `&dyn Check` for the same reason the dispatcher
1227    /// does: `report` must not be able to tell a built-in from an external.
1228    const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
1229        [cs[0], cs[1], cs[2]]
1230    }
1231
1232    /// The classification itself, which used to be unreachable: while one
1233    /// function classified AND printed AND returned a code, a test could assert
1234    /// the code and nothing else.
1235    #[test]
1236    fn every_outcome_lands_in_the_right_bucket() {
1237        let checks: [&dyn Check; 4] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER];
1238        let got = classify(
1239            &checks,
1240            &[
1241                Outcome::Passed,
1242                Outcome::Unavailable,
1243                Outcome::Failed,
1244                Outcome::Failed,
1245            ],
1246            &none(),
1247        );
1248        assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
1249        assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
1250        assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
1251    }
1252
1253    /// A clean stage concludes nothing at all — not an empty message, no
1254    /// message. Twenty checks that passed should print no roll-ups.
1255    ///
1256    /// `passed` is a tally, not a roll-up. It exists so that `amont.quiet` can
1257    /// say how many lines it swallowed, and it must never be the reason this
1258    /// report looks like it has something to announce.
1259    #[test]
1260    fn a_clean_stage_has_nothing_to_report() {
1261        let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
1262        let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
1263        assert!(
1264            got.fixed.is_empty()
1265                && got.blocked.is_empty()
1266                && got.downgraded.is_empty()
1267                && got.unavailable.is_empty(),
1268            "a clean stage found something to announce: {got:?}"
1269        );
1270        assert_eq!(got.passed, 1, "the pass was not tallied: {got:?}");
1271        assert_eq!(got.verdict(), Verdict::Proceed);
1272    }
1273
1274    #[test]
1275    fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
1276        let b: &dyn Check = &BLOCKER;
1277        let w: &dyn Check = &WARNER;
1278        assert_eq!(
1279            classify(&[b], &[Outcome::Failed], &none()).verdict(),
1280            Verdict::Block
1281        );
1282        assert_eq!(
1283            classify(&[b], &[Outcome::Passed], &none()).verdict(),
1284            Verdict::Proceed
1285        );
1286        // Every non-blocking shape, one at a time, so a regression cannot hide
1287        // behind a passing sibling.
1288        assert_eq!(
1289            classify(&[b], &[Outcome::Warned], &none()).verdict(),
1290            Verdict::Proceed
1291        );
1292        assert_eq!(
1293            classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
1294            Verdict::Proceed
1295        );
1296        assert_eq!(
1297            classify(&[w], &[Outcome::Failed], &none()).verdict(),
1298            Verdict::Proceed
1299        );
1300    }
1301
1302    #[test]
1303    fn one_blocking_failure_among_many_still_fails() {
1304        let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
1305        assert_eq!(
1306            classify(
1307                &checks,
1308                &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
1309                &none()
1310            )
1311            .verdict(),
1312            Verdict::Block
1313        );
1314        // Same shape, with the only *blocking* failure removed.
1315        assert_eq!(
1316            classify(
1317                &checks,
1318                &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
1319                &none()
1320            )
1321            .verdict(),
1322            Verdict::Proceed
1323        );
1324    }
1325
1326    /// The slot of a check whose thread died. Reading that as a pass is how a
1327    /// crash becomes a green commit.
1328    ///
1329    /// Asserted through the RUNNER, not through a `Default` impl: the rule
1330    /// belongs to this call site, and a test on `Outcome::default()` proved
1331    /// only that a trait impl existed, not that the runner used it.
1332    /// A check that PANICS must fail the commit, not pass it — and must not
1333    /// take the other checks down with it.
1334    ///
1335    /// Driven through the stage body rather than the runner, because the value
1336    /// that stands in for a dead check is chosen at the call site and the
1337    /// runner's own test cannot see that choice.
1338    #[test]
1339    fn a_panicking_check_blocks_the_commit() {
1340        static DIES: Builtin = Builtin {
1341            name: "stub-dies",
1342            stage: Stage::PreCommit,
1343            scope: Scope::ALWAYS,
1344            severity: Severity::Block,
1345            run: |_| panic!("this check died"),
1346            fix: crate::check::Fix::None,
1347            reach: crate::check::Reach::Convention,
1348        };
1349        let hook = std::panic::take_hook();
1350        std::panic::set_hook(Box::new(|_| {}));
1351        let push = crate::pushrefs::PushRefs::default();
1352        let manifest = crate::manifest::Manifest::default();
1353        let settings = crate::config::Settings::default();
1354        let ctx = Ctx {
1355            name: "pre-commit",
1356            args: &[],
1357            hooks_dir: std::path::Path::new("."),
1358            push: &push,
1359            manifest: &manifest,
1360            settings: &settings,
1361        };
1362        let verdict = run_stage(&[&DIES], &ctx, &none());
1363        std::panic::set_hook(hook);
1364        assert_eq!(
1365            verdict,
1366            Verdict::Block,
1367            "a check that died must not let the commit through"
1368        );
1369    }
1370
1371    #[test]
1372    fn a_thread_that_dies_leaves_a_failure_behind() {
1373        // The default hook would print a backtrace for the deliberate panic and
1374        // make a passing run look broken.
1375        let hook = std::panic::take_hook();
1376        std::panic::set_hook(Box::new(|_| {}));
1377        let items = ["a", "b", "c"];
1378        let out = run_concurrently(
1379            &items,
1380            |n: &&str| {
1381                if *n == "b" {
1382                    panic!("this check died");
1383                }
1384                Outcome::Passed
1385            },
1386            Outcome::Failed,
1387        );
1388        std::panic::set_hook(hook);
1389        assert_eq!(
1390            out,
1391            vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
1392            "a dead check must not read as one that passed, \
1393             and must not take the other checks down with it"
1394        );
1395    }
1396    use std::time::{Duration, Instant};
1397
1398    /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
1399    /// observe all the others arrive. Were the runner serial, the first task
1400    /// would wait alone, time out, and return non-zero — a failure, not a hang.
1401    #[test]
1402    fn run_concurrently_actually_overlaps() {
1403        static ARRIVED: AtomicUsize = AtomicUsize::new(0);
1404        ARRIVED.store(0, Ordering::SeqCst);
1405        let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
1406        let n = names.len();
1407
1408        let out = run_concurrently(
1409            &names,
1410            move |_: &&str| {
1411                ARRIVED.fetch_add(1, Ordering::SeqCst);
1412                let deadline = Instant::now() + Duration::from_secs(10);
1413                while ARRIVED.load(Ordering::SeqCst) < n {
1414                    if Instant::now() > deadline {
1415                        return 1; // never met the others — execution was serial
1416                    }
1417                    std::thread::yield_now();
1418                }
1419                0
1420            },
1421            1,
1422        );
1423        assert!(
1424            out.iter().all(|c| *c == 0),
1425            "tasks did not overlap: {out:?}"
1426        );
1427    }
1428
1429    #[test]
1430    fn results_come_back_in_input_order() {
1431        let names: Vec<&'static str> = vec!["first", "second", "third"];
1432        let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
1433        assert_eq!(out, vec![0, 7, 0], "results keep the input order");
1434    }
1435
1436    /// The filter calls the shared resolver rather than restating it. This test
1437    /// used to inline `n.contains(s)` — its own copy of the rule — and so went
1438    /// on passing after the rule changed underneath it.
1439    #[test]
1440    fn skips_are_filtered_by_the_shared_resolver() {
1441        let all = ["pre-commit-ruff", "pre-commit-prettier"];
1442        let skips = ["ruff".to_string()];
1443        let kept: Vec<_> = all
1444            .iter()
1445            .copied()
1446            .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
1447            .collect();
1448        assert_eq!(kept, vec!["pre-commit-prettier"]);
1449    }
1450
1451    /// The ordinary Rust push: source changed, `Cargo.toml` untouched.
1452    ///
1453    /// This test used to assert the OPPOSITE, and said so — it pinned
1454    /// `attestable` filtering on `Scope::matches`, which also asks whether
1455    /// the repository has opted in. Asking that of a push diff meant a
1456    /// `.rs`-only push, in a repository with a `Cargo.toml` sitting right
1457    /// there, attested nothing. Since that is what nearly every Rust push
1458    /// looks like, the feature was attesting almost nothing at all — quietly,
1459    /// while appearing to work.
1460    #[test]
1461    fn an_ordinary_source_push_is_vouched_for() {
1462        let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
1463        let checks: Vec<&dyn Check> = vec![&rust];
1464        let passed = vec!["pre-push-cargo-test".to_string()];
1465
1466        let changed = vec!["crates/amont/src/main.rs".to_string()];
1467        assert_eq!(
1468            attestable(&checks, &passed, &changed),
1469            vec!["pre-push-cargo-test".to_string()],
1470            "a push that changed Rust must vouch for the Rust gate"
1471        );
1472
1473        // And still when the marker IS in the diff — the opt-in file is not
1474        // required, but it is not disqualifying either.
1475        let changed = vec![
1476            "crates/amont/src/main.rs".to_string(),
1477            "Cargo.toml".to_string(),
1478        ];
1479        assert_eq!(
1480            attestable(&checks, &passed, &changed),
1481            vec!["pre-push-cargo-test".to_string()]
1482        );
1483    }
1484
1485    /// The over-claim the filter exists to stop, with an opt-in gate: a
1486    /// JS-only push must not vouch for the Rust suite, whatever files the
1487    /// repository contains.
1488    ///
1489    /// This is the half of the contract the fix above must not have broken,
1490    /// and it is the reason `touches` asks about EXTENSIONS rather than
1491    /// dropping the scope test altogether.
1492    #[test]
1493    fn an_opt_in_gate_is_not_vouched_for_by_a_push_in_another_language() {
1494        let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
1495        let checks: Vec<&dyn Check> = vec![&rust];
1496        let passed = vec!["pre-push-cargo-test".to_string()];
1497
1498        for changed in [
1499            vec!["app/routes/home.ts".to_string()],
1500            // Even the marker alone: editing Cargo.toml changes no Rust
1501            // source, so the suite has nothing new to have verified.
1502            vec!["Cargo.toml".to_string()],
1503            vec![],
1504        ] {
1505            assert!(
1506                attestable(&checks, &passed, &changed).is_empty(),
1507                "must not vouch for the Rust gate on {changed:?}"
1508            );
1509        }
1510    }
1511}