Skip to main content

amont_runtime/
dispatch.rs

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