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(stage: Stage, manifest: &crate::manifest::Manifest) -> Vec<&dyn Check> {
40    selected_during(stage, &[], manifest)
41}
42
43/// Do this repository's hooks apply the CONVENTIONS, or only the safety net?
44///
45/// `git config amont.conventions declared` (usually `--global`, set by
46/// `amont enroll`) scopes the house rules to repositories that commit an
47/// `amont.conf` — the standing grant of `init.templateDir` then becomes safe
48/// to hand a whole team: a clone of somebody else's project gets conflict,
49/// secret, size and debug-leftover protection, and none of this team's
50/// opinions about commit subjects or branch names. The default,
51/// `everywhere`, keeps today's behaviour exactly.
52///
53/// Presence of the manifest is the declaration; its CONTENT stays
54/// trust-gated. Reading presence executes nothing, so no consent is needed.
55pub fn conventions_apply(manifest: &crate::manifest::Manifest) -> bool {
56    manifest.declared || !declared_mode()
57}
58
59/// One config read per process — this sits on the hook path of every commit.
60fn declared_mode() -> bool {
61    static MODE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
62    *MODE.get_or_init(|| {
63        crate::config::enumerated_or(
64            "amont.conventions",
65            &["everywhere", "declared"],
66            "everywhere",
67        ) == "declared"
68    })
69}
70
71/// The checks for a stage, minus `hook.skip` and minus anything that declares
72/// it does not run during an operation currently in progress.
73fn selected_during<'a>(
74    stage: Stage,
75    in_progress: &[crate::check::GitState],
76    manifest: &'a crate::manifest::Manifest,
77) -> Vec<&'a dyn Check> {
78    let skips = configured_skips();
79    // Externals are included here, so `hook.skip` and the severity override
80    // govern a declared command exactly as they govern a built-in. A repository
81    // that can add a check it cannot disable would be a worse deal than not
82    // being able to add one.
83    let (kept, dropped): (Vec<_>, Vec<_>) = all_stage_checks(stage, manifest)
84        .into_iter()
85        .partition(|c| !skips.iter().any(|s| crate::skip_suppresses(c.name(), s)));
86    let names: Vec<&str> = dropped.iter().map(|c| c.name()).collect();
87    announce_skips(&names);
88
89    // Announced separately from `hook.skip`, and with the operation named: "not
90    // during a rebase" is a property of the moment and will be true again in a
91    // minute, which is a different thing to tell a reader than "you disabled
92    // this".
93    let (kept, paused): (Vec<_>, Vec<_>) = kept.into_iter().partition(|check| {
94        !check
95            .scope()
96            .not_during
97            .iter()
98            .any(|state| in_progress.contains(state))
99    });
100    if !paused.is_empty() {
101        let what = in_progress
102            .iter()
103            .map(|s| s.as_str())
104            .collect::<Vec<_>>()
105            .join(" and ");
106        println!(
107            "{} {} check(s) paused during {what}: {}",
108            warning_sign(),
109            paused.len(),
110            paused
111                .iter()
112                .map(|c| c.name())
113                .collect::<Vec<_>>()
114                .join(", ")
115        );
116    }
117
118    // The conventions split, last: a held-back check was neither skipped (a
119    // choice about THIS repository) nor paused (a property of the moment) —
120    // this repository simply never subscribed. One line, count not names:
121    // in the clone-of-somebody-else's-project case this prints on every
122    // commit, and fifteen names every time is how a safety message becomes
123    // scroll-past noise.
124    if conventions_apply(manifest) {
125        return kept;
126    }
127    let (kept, held): (Vec<_>, Vec<_>) = kept
128        .into_iter()
129        .partition(|check| check.reach() == crate::check::Reach::Safety);
130    if !held.is_empty() {
131        println!(
132            "{} {} convention check(s) held back — no amont.conf here and \
133             amont.conventions is `declared`; the safety net still runs",
134            warning_sign(),
135            held.len(),
136        );
137    }
138    kept
139}
140
141/// Say out loud which checks did not run.
142///
143/// A skip is otherwise invisible at exactly the moment it matters. With
144/// `hook.skip = merge-conflict` set, a commit printed six green ticks and no
145/// hint that a seventh check had been disabled — the developer sees a clean run
146/// and concludes they are covered.
147///
148/// It is worse than it sounds, because one value can silence a whole stage:
149/// `hook.skip = pre-commit` suppresses all fifteen. That is now something
150/// somebody meant rather than the accident it once was — `e` used to cost
151/// twenty by substring reach — but a commit under it still looks exactly like a
152/// commit that had nothing to report.
153///
154/// One line, only when something was actually skipped, so a normal commit is
155/// unchanged. This reaches every skip however it was created — hand-edited
156/// config included — which no dashboard can claim.
157fn announce_skips(dropped: &[&str]) {
158    if dropped.is_empty() {
159        return;
160    }
161    // Two lines, not one: "you decided this" (hook.skip on this machine)
162    // and "your team decided this" (a skip line in the committed
163    // amont.conf) are different things to be told — the same reason paused
164    // and held-back get their own sentences. A name both sources suppress
165    // is announced as the machine's: the local decision is the nearer one.
166    let (machine, _policy) = crate::skips_by_source();
167    let (yours, theirs): (Vec<&&str>, Vec<&&str>) = dropped
168        .iter()
169        .partition(|name| machine.iter().any(|s| crate::skip_suppresses(name, s)));
170    let say = |names: &[&&str], via: &str| {
171        if names.is_empty() {
172            return;
173        }
174        let plural = if names.len() == 1 { "check" } else { "checks" };
175        println!(
176            "{} {} {plural} skipped by {}: {}",
177            warning_sign(),
178            names.len(),
179            highlight(via),
180            names.iter().map(|n| **n).collect::<Vec<_>>().join(", ")
181        );
182    };
183    say(&yours, "hook.skip");
184    say(&theirs, "amont.conf");
185}
186
187/// Say, once per stage, what the manifest's policy could not do — withheld
188/// behind trust, or aiming at names that exist nowhere. Policy that silently
189/// does not apply is a silent behaviour change, which is the one kind this
190/// codebase does not allow itself.
191fn announce_policy_state(manifest: &crate::manifest::Manifest) {
192    if let Some(why) = manifest.policy_withheld {
193        println!(
194            "{} {} policy not applied: {why}",
195            warning_sign(),
196            highlight(crate::manifest::MANIFEST),
197        );
198    }
199    for note in &manifest.policy_notes {
200        println!("{} {}", warning_sign(), note);
201    }
202    // The version floor rides the same two call sites: once per stage,
203    // beside the other "this repository expects something you lack" lines.
204    crate::skew::announce_minimum();
205}
206
207/// Run every item concurrently and collect `(name, code)` in the INPUT order.
208///
209/// Extracted so the concurrency itself can be tested with a rendezvous instead
210/// of a stopwatch — an earlier wall-clock test was flaky the moment the machine
211/// was busy, and a threshold that trips under load teaches you to ignore it.
212fn run_concurrently<T, R, F>(items: &[T], run: F, if_thread_died: R) -> Vec<R>
213where
214    T: Sync,
215    R: Send + Sync + Clone,
216    F: Fn(&T) -> R + Sync,
217{
218    let slots: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
219    std::thread::scope(|scope| {
220        for (item, slot) in items.iter().zip(&slots) {
221            let run = &run;
222            let died = &if_thread_died;
223            scope.spawn(move || {
224                // CAUGHT, not propagated. `thread::scope` re-raises a child
225                // panic in the parent, which would abort the whole hook with a
226                // backtrace and throw away the other nineteen checks' results —
227                // and would make `if_thread_died` unreachable, which is what it
228                // was until this test existed to notice.
229                let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(item)))
230                    .unwrap_or_else(|_| died.clone());
231                *slot.lock().expect("poisoned") = Some(outcome);
232            });
233        }
234    });
235    slots
236        .into_iter()
237        .map(|s| {
238            s.into_inner()
239                .expect("poisoned")
240                .unwrap_or_else(|| if_thread_died.clone())
241        })
242        .collect()
243}
244
245/// Take the index-fidelity hold, or say why the caller must stop.
246///
247/// Extracted from `pre_commit` so that `amont run` — which its own doc
248/// comment calls "a rehearsal of the hook" — can take exactly the same hold
249/// rather than judging the working tree while a real commit judges the index.
250///
251/// Around the WHOLE fan-out, not per check: twenty checks run concurrently and
252/// would fight over one working tree.
253fn hold_unstaged() -> Result<crate::staged_only::StagedOnly, Verdict> {
254    // BEFORE `enter()`, not after: `enter()` is what checks out the tree and
255    // parks the unstaged half, and a signal landing in the gap between that
256    // and the handler being armed would hit the default disposition — dead
257    // process, tree left checked out, nothing restored. The handler no-ops
258    // harmlessly on a signal that arrives before there is anything held.
259    crate::staged_only::install_signal_handler();
260    match crate::staged_only::StagedOnly::enter() {
261        Ok(guard) => Ok(guard),
262        Err(e) => {
263            // Refusing to check the wrong content is the safe direction; a
264            // check that read the tree would be answering about a commit
265            // nobody is making.
266            eprintln!("{e}");
267            Err(Verdict::Block)
268        }
269    }
270}
271
272pub fn pre_commit(ctx: &Ctx) -> Verdict {
273    // Before anything runs: a pinned tool at the wrong version makes every
274    // verdict below it suspect, and the warning costs one --version per pin.
275    crate::manifest::verify_tool_pins(&ctx.manifest.pins);
276    announce_policy_state(ctx.manifest);
277    let in_progress = crate::git_states_in_progress();
278    let checks = selected_during(Stage::PreCommit, &in_progress, ctx.manifest);
279
280    let held = match hold_unstaged() {
281        Ok(guard) => guard,
282        Err(verdict) => return verdict,
283    };
284
285    let (verdict, outcomes) = run_stage_traced(&checks, ctx, &Overrides::read());
286
287    // What post-commit will bind to the commit: the gate-declared checks
288    // that RAN clean, recorded while the index still is the commit's tree.
289    // Called on every verdict — an empty record clears any leftover marker,
290    // so a blocked attempt (or a repo with nothing declared) cannot leave an
291    // earlier attempt's marker to vouch for the next commit. `Unavailable`
292    // deliberately does not qualify: a check whose tool is missing judged
293    // nothing, and stamping it would be the paper promise this exists to
294    // replace.
295    // EVERY blocking declaration, not only the npm GATE names: a custom
296    // `pre-commit check … block …` earns its stamp the same way, and a
297    // same-named pre-push declaration defers to it (see `pair_verdict`).
298    let ran: Vec<String> = if matches!(verdict, Verdict::Block) {
299        Vec::new()
300    } else {
301        crate::hooks::run_tests::blocking_commit_decls(&ctx.manifest.externals)
302            .into_iter()
303            .filter(|d| {
304                checks
305                    .iter()
306                    .zip(&outcomes)
307                    .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Passed | Outcome::Fixed))
308            })
309            .map(|d| d.script)
310            .collect()
311    };
312    let ran: Vec<&str> = ran.iter().map(String::as_str).collect();
313    crate::gate_stamp::record(&ran);
314
315    drop(held);
316    verdict
317}
318
319/// The pre-commit body, over the checks it is GIVEN.
320///
321/// A seam, so a test can hand it a check that panics. Without it the value
322/// standing in for a dead check was a literal at one call site that no test
323/// could reach — the rule was asserted on the runner and merely hoped for here.
324fn run_stage(checks: &[&dyn Check], ctx: &Ctx, severities: &Overrides) -> Verdict {
325    run_stage_traced(checks, ctx, severities).0
326}
327
328/// [`run_stage`], keeping the per-check outcomes — index-aligned with
329/// `checks` — alive past the verdict. `pre_commit` needs them to know which
330/// gate-declared checks actually ran (`gate_stamp`); `Report` cannot answer
331/// that, because `classify` deliberately drops the names of `Passed`.
332fn run_stage_traced(
333    checks: &[&dyn Check],
334    ctx: &Ctx,
335    severities: &Overrides,
336) -> (Verdict, Vec<Outcome>) {
337    if checks.is_empty() {
338        return (Verdict::Proceed, Vec::new());
339    }
340    // One slot per check: everything a check says lands in its own buffer
341    // and reaches stdout as ONE block when it finishes — see `live`. Off
342    // (`amont.progress false`), no sink is ever installed and every print
343    // streams exactly as it always did.
344    let stage = crate::live::enabled().then(|| {
345        let names: Vec<&str> = checks.iter().map(|c| c.name()).collect();
346        crate::live::Stage::begin(&names)
347    });
348    let items: Vec<(usize, &&dyn Check)> = checks.iter().enumerate().collect();
349    let outcomes = run_concurrently(
350        &items,
351        |(idx, check)| {
352            let _sink = stage.as_ref().map(|s| s.enter(*idx));
353            // The block is emitted however the check leaves — a panicking
354            // check's partial output still reaches the reader, above the
355            // dead-check verdict `run_concurrently` fills in.
356            let _flush = stage
357                .as_ref()
358                .map(|s| crate::live::FinishOnDrop::new(s, *idx));
359            let sub = Ctx {
360                name: check.name(),
361                args: ctx.args,
362                hooks_dir: ctx.hooks_dir,
363                push: ctx.push,
364                manifest: ctx.manifest,
365            };
366            check.run(&sub)
367        },
368        // A check whose thread died has not passed. Stated here, where the slot
369        // is filled, rather than hidden in a `Default` impl that every future
370        // `#[derive(Default)]` would silently inherit.
371        Outcome::Failed,
372    );
373
374    let report = classify(checks, &outcomes, severities);
375    announce(&report);
376    (report.verdict(), outcomes)
377}
378
379/// What a stage concluded, before anything is printed or exited.
380///
381/// A VALUE, so the classification can be asserted directly. While this was one
382/// function that classified, printed and returned an exit code, its tests could
383/// only check the code — whether the right thing was SAID went untested.
384#[derive(Debug, Default, PartialEq, Eq)]
385struct Report<'a> {
386    /// Repaired. The commit proceeds, but the author's files changed under
387    /// them and that must be said out loud.
388    fixed: Vec<&'a str>,
389    /// Failed, and the severity that applies blocks.
390    blocked: Vec<&'a str>,
391    /// Failed, but configured to warn. The check printed an error and meant it,
392    /// so somebody has to say it did not block.
393    downgraded: Vec<&'a str>,
394    /// Could not run. Distinct from "passed", which is the whole point.
395    unavailable: Vec<&'a str>,
396}
397
398impl Report<'_> {
399    fn verdict(&self) -> Verdict {
400        Verdict::blocking(!self.blocked.is_empty())
401    }
402}
403
404/// Pure: outcomes and severities in, a verdict out. No IO.
405fn classify<'a>(
406    checks: &[&'a dyn Check],
407    outcomes: &[Outcome],
408    severities: &Overrides,
409) -> Report<'a> {
410    let mut report = Report::default();
411    for (check, outcome) in checks.iter().zip(outcomes) {
412        match outcome {
413            // `Warned` needs nothing: a check that chose to warn has already
414            // said what it wanted to, and a roll-up would only repeat it.
415            Outcome::Passed | Outcome::Warned => {}
416            Outcome::Fixed => report.fixed.push(check.name()),
417            Outcome::Unavailable => report.unavailable.push(check.name()),
418            Outcome::Failed => match severities.of(*check) {
419                Severity::Block => report.blocked.push(check.name()),
420                Severity::Warn => report.downgraded.push(check.name()),
421            },
422        }
423    }
424    report
425}
426
427/// Says what happened. Prints; decides nothing.
428fn announce(report: &Report) {
429    if !report.fixed.is_empty() {
430        // Louder than a pass, because files on disk are not what the author
431        // left them: they asked for the repair, but they did not watch it.
432        println!(
433            "{} {} check(s) fixed and re-staged: {}",
434            valid_sign(),
435            report.fixed.len(),
436            report.fixed.join(", ")
437        );
438    }
439    if !report.unavailable.is_empty() {
440        // Distinct from "passed". Silence here is how a repo looks verified
441        // when nothing actually ran — the trailing count is the one line
442        // guaranteed to be read, whatever the twenty blocks above said.
443        println!(
444            "{} {} check(s) could not run: {}",
445            warning_sign(),
446            report.unavailable.len(),
447            report.unavailable.join(", ")
448        );
449    }
450    if !report.downgraded.is_empty() {
451        println!(
452            "{} {} check(s) reported a problem but are set to warn: {}",
453            warning_sign(),
454            report.downgraded.len(),
455            report.downgraded.join(", ")
456        );
457    }
458    if report.blocked.is_empty() {
459        return;
460    }
461    println!("\n🚨  Error raised by:");
462    for name in &report.blocked {
463        println!("    - {}", highlight(name));
464    }
465}
466
467/// Point every check at `git ls-files` instead of the index.
468///
469/// THE definition, called from both entry points. There used to be two: this
470/// one, and a copy in `main.rs` built from a RAW `ls-files` — no `-z` — whose
471/// output git QUOTES for any unusual byte, so `é.json` arrived as the nine-byte
472/// literal `"\303\251.json"` and was handed to prettier and eslint as a path
473/// that does not exist. And because `override_file_set` writes a `OnceLock`,
474/// main's quoted list WON: whichever ran first was the one that counted, and
475/// main's ran first. `git.rs` documents this exact failure.
476pub fn enter_all_files_mode() {
477    crate::hooks::common::override_file_set(
478        crate::git::stdout_paths(&["ls-files"]).unwrap_or_default(),
479    );
480}
481
482/// `amont run` — every applicable check, on demand.
483///
484/// Two questions, and the mode says which it answers:
485///
486/// - **staged** (default) is "would my commit pass" — the same set a commit
487///   would check, so it is a rehearsal of the hook, and it takes the same
488///   index-fidelity hold the hook takes.
489/// - **`--all-files`** is "does my working tree pass". Deliberately NOT the same
490///   question: on a dirty tree it reports on content that is not committed and
491///   may never be. That is right for adopting a check into an existing
492///   repository, where `git add .` is not an acceptable way to measure the mess,
493///   and it is why `--all-files` takes no stash — there is no staged/unstaged
494///   distinction to protect when the answer is "all of it".
495pub fn run_all(ctx: &Ctx, all_files: bool) -> Verdict {
496    // ORDER: the override goes in FIRST. It is what tells `fixing_enabled` and
497    // `restage` that the file set is not the index, and both are consulted
498    // from inside the checks below.
499    if all_files {
500        enter_all_files_mode();
501        if crate::hooks::common::fixing_requested() {
502            println!(
503                "{} {} is set, but fixing is off for {}: the input set is the \
504                 working tree, not the index",
505                warning_sign(),
506                highlight("amont.fix"),
507                highlight("--all-files")
508            );
509        }
510        // Stash-free, per decision 1 of docs/index-fidelity-and-run-modes.md:
511        // there is no staged/unstaged distinction to protect when the input
512        // set is `git ls-files`, so a hold would be surprising extra mutation
513        // with no correctness upside.
514        return run_stage(
515            &selected(Stage::PreCommit, ctx.manifest),
516            ctx,
517            &Overrides::read(),
518        );
519    }
520
521    // Staged mode IS a rehearsal of the commit, so it takes the same hold the
522    // commit does. Without it, `amont run` failed on garbage in the tree
523    // that `git commit` — which holds the unstaged half aside — passed, and
524    // vice versa: the two modes disagreed about the same repository, which is
525    // exactly what this mode exists not to do.
526    let held = match hold_unstaged() {
527        Ok(guard) => guard,
528        Err(verdict) => return verdict,
529    };
530    let verdict = run_stage(
531        &selected(Stage::PreCommit, ctx.manifest),
532        ctx,
533        &Overrides::read(),
534    );
535    // AFTER the report has been printed: dropping earlier would put the
536    // unstaged content back under a check that is still reading files.
537    drop(held);
538    verdict
539}
540
541/// `amont run <check>` — one check by name. `None` when there is no such
542/// check, which the caller turns into a usage error.
543///
544/// Lives here rather than in `main.rs` so `registry::lookup` stays inside the
545/// runtime, and so the hold decision is made once: a named check takes the
546/// index-fidelity hold only when it is a `Stage::PreCommit` check running in
547/// staged mode. A pre-push or commit-msg check invoked by name must never
548/// touch the working tree — nothing about a push is a staging operation.
549/// Resolve what `amont run <name>` means, exactly as `hook.skip` resolves a
550/// name — the rest of the tool taught `ban-terms`; making `run` demand the
551/// full id was a pointless second vocabulary. Ambiguity is an answer, not a
552/// guess: the two `branch-pattern` checks are different code at different
553/// stages.
554///
555/// Public because the CALLER needs the answer before anything else happens:
556/// main decides whether to synthesize push refs from the resolved name, and
557/// an ambiguous name must say so rather than fail on a missing upstream it
558/// was never going to use.
559pub fn resolve_check_name(name: &str, manifest: &crate::manifest::Manifest) -> Named2 {
560    if crate::registry::lookup(name, manifest).is_some() {
561        return Named2::Resolved(name.to_string());
562    }
563    let mut matches: Vec<String> = crate::registry::CHECKS
564        .iter()
565        .map(|c| c.name.to_string())
566        .chain(manifest.externals.iter().map(|e| e.id.clone()))
567        .filter(|id| crate::skip_suppresses(id, name))
568        .collect();
569    matches.dedup();
570    match matches.len() {
571        0 => Named2::Unknown,
572        1 => Named2::Resolved(matches.remove(0)),
573        _ => Named2::Ambiguous(matches),
574    }
575}
576
577/// How a run name resolved.
578pub enum Named2 {
579    Resolved(String),
580    Unknown,
581    Ambiguous(Vec<String>),
582}
583
584pub fn run_named(ctx: &Ctx, name: &str, all_files: bool) -> Named {
585    let full: String = match resolve_check_name(name, ctx.manifest) {
586        Named2::Resolved(id) => id,
587        Named2::Unknown => return Named::Unknown,
588        Named2::Ambiguous(ids) => return Named::Ambiguous(ids),
589    };
590    let name = full.as_str();
591    let Some(run_check) = crate::registry::lookup(name, ctx.manifest) else {
592        return Named::Unknown;
593    };
594    // The Ctx must carry the RESOLVED id: lookup's closure re-resolves
595    // through `ctx.name`, and handing it the short name back would panic on
596    // the very ambiguity this function just settled.
597    let ctx = &Ctx {
598        name,
599        args: ctx.args,
600        hooks_dir: ctx.hooks_dir,
601        push: ctx.push,
602        manifest: ctx.manifest,
603    };
604    if all_files {
605        enter_all_files_mode();
606        return Named::Ran(run_check(ctx));
607    }
608    let is_pre_commit_check = crate::registry::one_named(name, ctx.manifest)
609        .is_some_and(|c| c.stage() == Stage::PreCommit);
610    if !is_pre_commit_check {
611        return Named::Ran(run_check(ctx));
612    }
613    let held = match hold_unstaged() {
614        Ok(guard) => guard,
615        Err(verdict) => return Named::Ran(verdict),
616    };
617    let verdict = run_check(ctx);
618    drop(held);
619    Named::Ran(verdict)
620}
621
622/// What `run_named` resolved a name to.
623pub enum Named {
624    Ran(Verdict),
625    /// Nothing matches — full id, short name, or entrypoint.
626    Unknown,
627    /// A short name that reaches more than one check; the caller lists them
628    /// so the user can pick a full id.
629    Ambiguous(Vec<String>),
630}
631
632pub fn pre_push(ctx: &Ctx) -> Verdict {
633    // The notes push `attest` makes re-enters this hook; its ref list is only
634    // ever the attest ref, so there is nothing to prove — and proving it
635    // would recurse.
636    if crate::attest::push_guard_active() {
637        return Verdict::Proceed;
638    }
639    crate::manifest::verify_tool_pins(&ctx.manifest.pins);
640    announce_policy_state(ctx.manifest);
641    // NB: no CHERRY_PICK_HEAD check here — the zsh pre-push had none either.
642    let severities = Overrides::read();
643    // pre-push had NO state guard at all, with a comment admitting it existed
644    // only because the zsh version had none. Now it asks the same question
645    // pre-commit does and each check answers for itself.
646    let in_progress = crate::git_states_in_progress();
647    let pre_push_checks = selected_during(Stage::PrePush, &in_progress, ctx.manifest);
648    let stage = crate::live::enabled().then(|| {
649        let names: Vec<&str> = pre_push_checks.iter().map(|c| c.name()).collect();
650        crate::live::Stage::begin(&names)
651    });
652    // What actually PASSED, for the attestation at the bottom. `Warned` and
653    // `Unavailable` stay out — "could not run" is not "passed" — and a
654    // commit-time-gated pair counts, because its stamps say the check ran on
655    // every pushed tree.
656    let mut passed: Vec<String> = Vec::new();
657    for (idx, check) in pre_push_checks.iter().enumerate() {
658        let _sink = stage.as_ref().map(|s| s.enter(idx));
659        let _flush = stage
660            .as_ref()
661            .map(|s| crate::live::FinishOnDrop::new(s, idx));
662        // A declared pre-push external whose NAME is also declared at
663        // pre-commit (blocking) is a gate pair: the commit-time side earned
664        // per-commit stamps, and this side runs only for pushes carrying
665        // commits with no record of it — the same contract the npm gate has
666        // always had, for vocabularies npm never heard of (`cargo test`,
667        // `pytest`, anything). Messages mirror the npm gate's exactly;
668        // docs/checks.md quotes them.
669        if let Some(ext) = ctx
670            .manifest
671            .externals
672            .iter()
673            .find(|e| e.stage == Stage::PrePush && e.id == check.name())
674        {
675            match crate::hooks::run_tests::pair_verdict(ext, ctx.manifest, ctx.push) {
676                crate::hooks::run_tests::PairVerdict::Gated => {
677                    crate::say!(
678                        "{} {} gated at commit instead — not repeating it here",
679                        valid_sign(),
680                        highlight(&ext.short_name),
681                    );
682                    passed.push(check.name().to_string());
683                    continue;
684                }
685                crate::hooks::run_tests::PairVerdict::Unstamped(n) => {
686                    crate::say!(
687                        "{} {} is declared at commit time, but {n} pushed \
688                         commit{} carr{} no record of it — running it here",
689                        warning_sign(),
690                        ext.short_name,
691                        if n == 1 { "" } else { "s" },
692                        if n == 1 { "ies" } else { "y" },
693                    );
694                }
695                crate::hooks::run_tests::PairVerdict::NotPaired => {}
696            }
697        }
698        let sub = Ctx {
699            name: check.name(),
700            args: ctx.args,
701            hooks_dir: ctx.hooks_dir,
702            push: ctx.push,
703            manifest: ctx.manifest,
704        };
705        match check.run(&sub) {
706            Outcome::Passed => passed.push(check.name().to_string()),
707            // Announced, never fatal: a check that could not run has not
708            // invalidated anything, and neither has a warning.
709            Outcome::Unavailable => {
710                println!(
711                    "{} {} could not run",
712                    warning_sign(),
713                    highlight(check.name())
714                )
715            }
716            Outcome::Warned => {}
717            // Cannot occur: `Fix::Rewrite` is refused on a pre-push
718            // declaration, so nothing here can repair anything.
719            Outcome::Fixed => {}
720            Outcome::Failed => match severities.of(*check) {
721                Severity::Warn => println!(
722                    "{} {} reported a problem (severity warn)",
723                    warning_sign(),
724                    highlight(check.name())
725                ),
726                // Fail-fast applies ONLY to Block: the later steps are
727                // expensive and their preconditions are gone.
728                Severity::Block => {
729                    println!("\n🚨  Error raised by hook {}", highlight(check.name()));
730                    return Verdict::Block;
731                }
732            },
733        }
734    }
735    // Every block gate passed — say so to CI, if this repository opted in.
736    // Gated behind `enabled()` HERE, not just inside `attest_push`: reading
737    // `ctx.push` may consume stdin, and a disabled repo should leave stdin
738    // exactly as it found it.
739    if !passed.is_empty() && crate::attest::enabled() {
740        let remote = ctx
741            .args
742            .first()
743            .map(|a| a.to_string_lossy().into_owned())
744            .unwrap_or_default();
745        let changed = crate::pushrefs::changed_files(ctx.push.get());
746        let vouched = attestable(&pre_push_checks, &passed, &changed);
747        crate::attest::attest_push(&remote, ctx.push.get(), &vouched);
748    }
749    Verdict::Proceed
750}
751
752/// Of the checks that passed, the ones an attestation may actually VOUCH for.
753///
754/// A language gate whose scope the push never touched returns `Passed` having
755/// run nothing — `cargo_test` walks its refs, finds no crate root, and falls
756/// out of the loop green. That is right for a push gate (there was nothing to
757/// object to) and wrong for an attestation: a JS-only push was minting
758/// `gates … pre-push-cargo-test pre-push-go-test pre-push-pytest`, and in a
759/// MIXED repository CI would then skip a suite that nobody ran on that tree.
760///
761/// The declared `scope` is the honest filter, and the same data `amont list`
762/// already reports. Unscoped checks (`Scope::ALWAYS` — branch-protect,
763/// secrets) match everything and are vouched for, which is accurate: they
764/// really did run. An empty `changed` vouches for nothing scoped, which is
765/// the safe direction — CI runs the suite.
766fn attestable(checks: &[&dyn Check], passed: &[String], changed: &[String]) -> Vec<String> {
767    checks
768        .iter()
769        .filter(|c| passed.iter().any(|p| p == c.name()))
770        .filter(|c| c.scope().matches(changed))
771        .map(|c| c.name().to_string())
772        .collect()
773}
774
775#[cfg(test)]
776mod tests {
777    use super::*;
778    use crate::check::{Builtin, Scope};
779    use std::sync::atomic::{AtomicUsize, Ordering};
780
781    /// A check whose only job is to carry a name and a severity into `report`.
782    /// Its `run` is never called — `report` is fed outcomes directly, which is
783    /// what makes `Unavailable` testable at all: the real thing needs a missing
784    /// binary, and a test that uninstalls the developer's toolchain is worse
785    /// than no test.
786    const fn stub(name: &'static str, severity: Severity) -> Builtin {
787        Builtin {
788            name,
789            stage: Stage::PreCommit,
790            scope: Scope::ALWAYS,
791            severity,
792            run: |_| Outcome::Passed,
793            fix: crate::check::Fix::None,
794            reach: crate::check::Reach::Convention,
795        }
796    }
797
798    /// A pre-push gate scoped to one language's files.
799    const fn scoped(name: &'static str, exts: &'static [&'static str]) -> Builtin {
800        Builtin {
801            name,
802            stage: Stage::PrePush,
803            scope: Scope::new(exts, &[]),
804            severity: Severity::Block,
805            run: |_| Outcome::Passed,
806            fix: crate::check::Fix::None,
807            reach: crate::check::Reach::Convention,
808        }
809    }
810
811    /// The over-claim this filter exists to stop, caught in the wild: a
812    /// JS-only push minted `gates … pre-push-cargo-test pre-push-go-test
813    /// pre-push-pytest`, because each of those gates finds nothing of its
814    /// language to do and returns `Passed` having run NOTHING. Harmless in a
815    /// single-language repo, unsound in a mixed one — CI would skip a suite
816    /// nobody ran on that tree.
817    #[test]
818    fn a_gate_whose_language_the_push_never_touched_is_not_vouched_for() {
819        let js = scoped("pre-push-run-tests-js", &[".ts", ".js"]);
820        let rust = scoped("pre-push-cargo-test", &[".rs"]);
821        let py = scoped("pre-push-pytest", &[".py"]);
822        let always = stub("pre-push-secrets", Severity::Block);
823        let checks: Vec<&dyn Check> = vec![&js, &rust, &py, &always];
824        let passed: Vec<String> = checks.iter().map(|c| c.name().to_string()).collect();
825
826        let changed = vec!["app/routes/home.ts".to_string()];
827        let vouched = attestable(&checks, &passed, &changed);
828        assert_eq!(
829            vouched,
830            vec![
831                "pre-push-run-tests-js".to_string(),
832                "pre-push-secrets".to_string()
833            ],
834            "only the gate that had work, plus the unscoped one that always runs"
835        );
836
837        // Nothing computed about the push vouches for nothing scoped — the
838        // safe direction, since CI then runs the suite.
839        assert_eq!(
840            attestable(&checks, &passed, &[]),
841            vec!["pre-push-secrets".to_string()]
842        );
843
844        // A check that did NOT pass is never vouched for, whatever its scope.
845        let only_rust_passed = vec!["pre-push-cargo-test".to_string()];
846        assert!(attestable(&checks, &only_rust_passed, &changed).is_empty());
847    }
848
849    /// No overrides configured. `report` takes them as a VALUE now, so its
850    /// tests need no repository and no git at all.
851    fn none() -> Overrides {
852        Overrides::default()
853    }
854
855    static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
856    static WARNER: Builtin = stub("stub-warner", Severity::Warn);
857
858    /// The unit tests hold `&dyn Check` for the same reason the dispatcher
859    /// does: `report` must not be able to tell a built-in from an external.
860    const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
861        [cs[0], cs[1], cs[2]]
862    }
863
864    /// The classification itself, which used to be unreachable: while one
865    /// function classified AND printed AND returned a code, a test could assert
866    /// the code and nothing else.
867    #[test]
868    fn every_outcome_lands_in_the_right_bucket() {
869        let checks: [&dyn Check; 4] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER];
870        let got = classify(
871            &checks,
872            &[
873                Outcome::Passed,
874                Outcome::Unavailable,
875                Outcome::Failed,
876                Outcome::Failed,
877            ],
878            &none(),
879        );
880        assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
881        assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
882        assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
883    }
884
885    /// A clean stage concludes nothing at all — not an empty message, no
886    /// message. Twenty checks that passed should print no roll-ups.
887    #[test]
888    fn a_clean_stage_has_nothing_to_report() {
889        let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
890        let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
891        assert_eq!(got, Report::default());
892        assert_eq!(got.verdict(), Verdict::Proceed);
893    }
894
895    #[test]
896    fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
897        let b: &dyn Check = &BLOCKER;
898        let w: &dyn Check = &WARNER;
899        assert_eq!(
900            classify(&[b], &[Outcome::Failed], &none()).verdict(),
901            Verdict::Block
902        );
903        assert_eq!(
904            classify(&[b], &[Outcome::Passed], &none()).verdict(),
905            Verdict::Proceed
906        );
907        // Every non-blocking shape, one at a time, so a regression cannot hide
908        // behind a passing sibling.
909        assert_eq!(
910            classify(&[b], &[Outcome::Warned], &none()).verdict(),
911            Verdict::Proceed
912        );
913        assert_eq!(
914            classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
915            Verdict::Proceed
916        );
917        assert_eq!(
918            classify(&[w], &[Outcome::Failed], &none()).verdict(),
919            Verdict::Proceed
920        );
921    }
922
923    #[test]
924    fn one_blocking_failure_among_many_still_fails() {
925        let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
926        assert_eq!(
927            classify(
928                &checks,
929                &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
930                &none()
931            )
932            .verdict(),
933            Verdict::Block
934        );
935        // Same shape, with the only *blocking* failure removed.
936        assert_eq!(
937            classify(
938                &checks,
939                &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
940                &none()
941            )
942            .verdict(),
943            Verdict::Proceed
944        );
945    }
946
947    /// The slot of a check whose thread died. Reading that as a pass is how a
948    /// crash becomes a green commit.
949    ///
950    /// Asserted through the RUNNER, not through a `Default` impl: the rule
951    /// belongs to this call site, and a test on `Outcome::default()` proved
952    /// only that a trait impl existed, not that the runner used it.
953    /// A check that PANICS must fail the commit, not pass it — and must not
954    /// take the other checks down with it.
955    ///
956    /// Driven through the stage body rather than the runner, because the value
957    /// that stands in for a dead check is chosen at the call site and the
958    /// runner's own test cannot see that choice.
959    #[test]
960    fn a_panicking_check_blocks_the_commit() {
961        static DIES: Builtin = Builtin {
962            name: "stub-dies",
963            stage: Stage::PreCommit,
964            scope: Scope::ALWAYS,
965            severity: Severity::Block,
966            run: |_| panic!("this check died"),
967            fix: crate::check::Fix::None,
968            reach: crate::check::Reach::Convention,
969        };
970        let hook = std::panic::take_hook();
971        std::panic::set_hook(Box::new(|_| {}));
972        let push = crate::pushrefs::PushRefs::default();
973        let manifest = crate::manifest::Manifest::default();
974        let ctx = Ctx {
975            name: "pre-commit",
976            args: &[],
977            hooks_dir: std::path::Path::new("."),
978            push: &push,
979            manifest: &manifest,
980        };
981        let verdict = run_stage(&[&DIES], &ctx, &none());
982        std::panic::set_hook(hook);
983        assert_eq!(
984            verdict,
985            Verdict::Block,
986            "a check that died must not let the commit through"
987        );
988    }
989
990    #[test]
991    fn a_thread_that_dies_leaves_a_failure_behind() {
992        // The default hook would print a backtrace for the deliberate panic and
993        // make a passing run look broken.
994        let hook = std::panic::take_hook();
995        std::panic::set_hook(Box::new(|_| {}));
996        let items = ["a", "b", "c"];
997        let out = run_concurrently(
998            &items,
999            |n: &&str| {
1000                if *n == "b" {
1001                    panic!("this check died");
1002                }
1003                Outcome::Passed
1004            },
1005            Outcome::Failed,
1006        );
1007        std::panic::set_hook(hook);
1008        assert_eq!(
1009            out,
1010            vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
1011            "a dead check must not read as one that passed, \
1012             and must not take the other checks down with it"
1013        );
1014    }
1015    use std::time::{Duration, Instant};
1016
1017    /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
1018    /// observe all the others arrive. Were the runner serial, the first task
1019    /// would wait alone, time out, and return non-zero — a failure, not a hang.
1020    #[test]
1021    fn run_concurrently_actually_overlaps() {
1022        static ARRIVED: AtomicUsize = AtomicUsize::new(0);
1023        ARRIVED.store(0, Ordering::SeqCst);
1024        let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
1025        let n = names.len();
1026
1027        let out = run_concurrently(
1028            &names,
1029            move |_: &&str| {
1030                ARRIVED.fetch_add(1, Ordering::SeqCst);
1031                let deadline = Instant::now() + Duration::from_secs(10);
1032                while ARRIVED.load(Ordering::SeqCst) < n {
1033                    if Instant::now() > deadline {
1034                        return 1; // never met the others — execution was serial
1035                    }
1036                    std::thread::yield_now();
1037                }
1038                0
1039            },
1040            1,
1041        );
1042        assert!(
1043            out.iter().all(|c| *c == 0),
1044            "tasks did not overlap: {out:?}"
1045        );
1046    }
1047
1048    #[test]
1049    fn results_come_back_in_input_order() {
1050        let names: Vec<&'static str> = vec!["first", "second", "third"];
1051        let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
1052        assert_eq!(out, vec![0, 7, 0], "results keep the input order");
1053    }
1054
1055    /// The filter calls the shared resolver rather than restating it. This test
1056    /// used to inline `n.contains(s)` — its own copy of the rule — and so went
1057    /// on passing after the rule changed underneath it.
1058    #[test]
1059    fn skips_are_filtered_by_the_shared_resolver() {
1060        let all = ["pre-commit-ruff", "pre-commit-prettier"];
1061        let skips = ["ruff".to_string()];
1062        let kept: Vec<_> = all
1063            .iter()
1064            .copied()
1065            .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
1066            .collect();
1067        assert_eq!(kept, vec!["pre-commit-prettier"]);
1068    }
1069}