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                    // `amont.unstampedPush refuse`: never run a suite with
984                    // the remote's connection held open — say how to earn
985                    // the stamp instead. Not inside a rehearsal snapshot:
986                    // running there is how the stamp is earned.
987                    if !rehearsing && crate::rehearsal::refuse_unstamped(ctx.settings) {
988                        crate::say!(
989                            "{} {} is declared at commit time, but {n} pushed \
990                             commit{} carr{} no record of it (rewritten by a \
991                             rebase or amend, or made without the hooks) — \
992                             refusing the push",
993                            warning_sign(),
994                            name,
995                            if n == 1 { "" } else { "s" },
996                            if n == 1 { "ies" } else { "y" },
997                        );
998                        crate::say!(
999                            "    Test this tree first, with no push waiting on it: {} — then push again",
1000                            highlight("amont rehearse --wait"),
1001                        );
1002                        crate::downgrade::note(settings, &downgraded);
1003                        record_evidence(&tips, &evidence);
1004                        println!("\n🚨  Error raised by hook {}", highlight(check.name()));
1005                        return Verdict::Block;
1006                    }
1007                    crate::say!(
1008                        "{} {} is declared at commit time, but {n} pushed \
1009                         commit{} carr{} no record of it — running it here",
1010                        warning_sign(),
1011                        name,
1012                        if n == 1 { "" } else { "s" },
1013                        if n == 1 { "ies" } else { "y" },
1014                    );
1015                }
1016                crate::hooks::run_tests::PairVerdict::NotPaired => {}
1017            }
1018        }
1019        let sub = Ctx {
1020            name: check.name(),
1021            args: ctx.args,
1022            hooks_dir: ctx.hooks_dir,
1023            push: ctx.push,
1024            manifest: ctx.manifest,
1025            settings: ctx.settings,
1026        };
1027        // Wall clock around the check itself, not around the hook: the number
1028        // that catches a suite which stopped finding tests is how long THAT
1029        // gate took, and everything outside this call is bookkeeping.
1030        let started = std::time::Instant::now();
1031        let outcome = check.run(&sub);
1032        evidence.push(crate::gate_stamp::Run {
1033            at: crate::gate_evidence::now(),
1034            gate: check.name().to_string(),
1035            outcome: run_outcome(outcome),
1036            ms: started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
1037        });
1038        match outcome {
1039            Outcome::Passed => {
1040                passed.push(check.name().to_string());
1041                if !check.scope().is_unscoped() {
1042                    ran_and_passed.push(check.name().to_string());
1043                }
1044            }
1045            // Announced, never fatal: a check that could not run has not
1046            // invalidated anything, and neither has a warning.
1047            Outcome::Unavailable => {
1048                println!(
1049                    "{} {} could not run",
1050                    warning_sign(),
1051                    highlight(check.name())
1052                )
1053            }
1054            Outcome::Warned => {}
1055            // Nothing to judge: not passed (nothing to stamp or attest), not
1056            // a gap (nothing is missing). The dispatcher asked the registry's
1057            // opt-in question above; this is a check answering it for itself.
1058            Outcome::Inert => {}
1059            // Cannot occur: `Fix::Rewrite` is refused on a pre-push
1060            // declaration, so nothing here can repair anything.
1061            Outcome::Fixed => {}
1062            Outcome::Failed => match severities.of(*check) {
1063                Severity::Warn => {
1064                    downgraded.push((
1065                        check.name().to_string(),
1066                        downgrade_origin(*check, &severities),
1067                    ));
1068                    println!(
1069                        "{} {} reported a problem (severity warn)",
1070                        warning_sign(),
1071                        highlight(check.name())
1072                    );
1073                }
1074                // Fail-fast applies ONLY to Block: the later steps are
1075                // expensive and their preconditions are gone.
1076                Severity::Block => {
1077                    // Record what already warned before leaving. Those checks
1078                    // ran and reported; a later check blocking does not unmake
1079                    // them, and dropping them here would make the ledger quietly
1080                    // under-count every push that ended badly.
1081                    crate::downgrade::note(settings, &downgraded);
1082                    // The same argument for the evidence, and it matters more
1083                    // here: this is the path a FAILURE leaves by, and a record
1084                    // written only on the way out of a successful push would
1085                    // be a dataset of passes calling itself a dataset of runs.
1086                    record_evidence(&tips, &evidence);
1087                    println!("\n🚨  Error raised by hook {}", highlight(check.name()));
1088                    return Verdict::Block;
1089                }
1090            },
1091        }
1092    }
1093    // Every block gate passed — stamp the tips with the scoped gates that
1094    // RAN here, so the next push of this content (a retry after a dropped
1095    // connection, or the real push after an `amont run pre-push` rehearsal)
1096    // skips them. Only when what ran is what is being pushed: with
1097    // `amont.testPushedTree` the suite ran on the tip itself — unless the
1098    // snapshot could not be made, which `stamp_tips` asks about rather than
1099    // assuming; otherwise it ran on the working tree, which vouches for the
1100    // tip only when the two are the same content — HEAD, with nothing
1101    // modified and nothing untracked.
1102    // The same proxy `attestable` uses, for the same reason: a scoped gate
1103    // whose files the push never touched returns `Passed` having run
1104    // nothing, and a stamp for THAT would let a later push that does touch
1105    // them skip a suite nobody ran.
1106    if reuse_stamps && !ran_and_passed.is_empty() {
1107        let changed = crate::pushrefs::changed_files(ctx.push.get());
1108        let really_ran: Vec<String> = pre_push_checks
1109            .iter()
1110            .filter(|c| ran_and_passed.iter().any(|p| p == c.name()))
1111            .filter(|c| c.scope().touches(&changed))
1112            .map(|c| c.name().to_string())
1113            .collect();
1114        stamp_tips(&tips, &really_ran, &tree_at_start);
1115    }
1116    // …and say so to CI, if this repository opted in.
1117    // Gated behind `enabled()` HERE, not just inside `attest_push`: reading
1118    // `ctx.push` may consume stdin, and a disabled repo should leave stdin
1119    // exactly as it found it.
1120    if !passed.is_empty() && crate::attest::enabled(settings) {
1121        let remote = ctx
1122            .args
1123            .first()
1124            .map(|a| a.to_string_lossy().into_owned())
1125            .unwrap_or_default();
1126        let changed = crate::pushrefs::changed_files(ctx.push.get());
1127        let vouched = attestable(&pre_push_checks, &passed, &changed);
1128        crate::attest::attest_push(ctx.settings, &remote, ctx.push.get(), &vouched);
1129    }
1130    crate::downgrade::note(settings, &downgraded);
1131    record_evidence(&tips, &evidence);
1132    Verdict::Proceed
1133}
1134
1135/// What one check's outcome is called in the record.
1136fn run_outcome(outcome: Outcome) -> crate::gate_stamp::RunOutcome {
1137    use crate::gate_stamp::RunOutcome as R;
1138    match outcome {
1139        Outcome::Passed => R::Passed,
1140        Outcome::Failed => R::Failed,
1141        Outcome::Warned => R::Warned,
1142        Outcome::Fixed => R::Fixed,
1143        Outcome::Unavailable => R::Unavailable,
1144        Outcome::Inert => R::Inert,
1145    }
1146}
1147
1148/// File this push's runs under the content they judged.
1149///
1150/// ONE key, not one per tip: a push of two branches ran each gate once, and
1151/// writing the same run onto both trees would make a report count it twice.
1152/// The first tip's tree is that key, falling back to `HEAD` — and to nothing
1153/// at all when git will not name either, which costs a row in a report and
1154/// never a verdict.
1155fn record_evidence(tips: &[String], runs: &[crate::gate_stamp::Run]) {
1156    if runs.is_empty() {
1157        return;
1158    }
1159    let tree = tips
1160        .first()
1161        .and_then(|tip| crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]))
1162        .or_else(|| crate::git::stdout(&["rev-parse", "HEAD^{tree}"]));
1163    if let Some(tree) = tree {
1164        crate::gate_stamp::record_runs(&tree, runs);
1165    }
1166}
1167
1168/// The scoped pre-push gates — test suites — that have work to do for a
1169/// push that changed `changed`: what a rehearsal would run, and therefore
1170/// what its stamp would have to name before a push may skip anything.
1171///
1172/// The same two filters `pre_push` applies before stamping (selected here,
1173/// and `scope().touches` the change), so the rehearsal's idea of "nothing to
1174/// do" is the push's idea of "nothing to stamp".
1175pub fn scoped_push_gates(
1176    settings: &crate::config::Settings,
1177    manifest: &crate::manifest::Manifest,
1178    changed: &[String],
1179) -> Vec<String> {
1180    let in_progress = crate::git_states_in_progress();
1181    let tracked = crate::tracked_paths();
1182    selected_during(settings, Stage::PrePush, &in_progress, manifest)
1183        .into_iter()
1184        .filter(|c| !c.scope().is_unscoped() && c.scope().touches(changed))
1185        // The same opt-in gate `pre_push` applies: a suite the repository
1186        // never turned on is not work a rehearsal owes a stamp for.
1187        .filter(|c| c.scope().opted_in(&tracked))
1188        .map(|c| c.name().to_string())
1189        .collect()
1190}
1191
1192/// Push-stamp every tip whose content is what the gates actually tested.
1193///
1194/// See the comment at the call site for the two cases. Silent when nothing
1195/// qualifies — a dirty working tree is the ordinary state of a machine
1196/// mid-work, and a note on every push would teach people to ignore it.
1197fn stamp_tips(tips: &[String], gates: &[String], tree_at_start: &str) {
1198    let head = crate::git::stdout(&["rev-parse", "HEAD"]);
1199    // TRACKED modifications only — a KNOWN gap, kept deliberately, and
1200    // spelled out because the comment that used to sit here argued it
1201    // backwards ("untracked files are not in any tree the suite could have
1202    // been asked about"). That is not the reason. The danger is not that the
1203    // tree lacks them, it is that the RUN had them: a new test file, a
1204    // fixture, a local `.env`, present while the suite ran and absent from
1205    // the tree the stamp vouches for.
1206    //
1207    // Counting them was tried, and is worse than the gap. Gates leave
1208    // artefacts — a log, a coverage directory, whatever a declared
1209    // `amont.conf` command writes — and nothing cleans them up, so a
1210    // repository using declared gates would stop earning stamps permanently
1211    // after its first commit. That does not merely lose an optimisation: it
1212    // puts the suite back INSIDE the push, which is the failure the whole
1213    // stamping mechanism exists to prevent. amont's own
1214    // `a_push_stamp_merges_with_a_commit_time_stamp` fixture is exactly that
1215    // shape, and CI is where it surfaced — a `*.log` line in one developer's
1216    // global gitignore had hidden it on the machine that wrote the change.
1217    //
1218    // `amont.testPushedTree true` closes the gap properly for anyone who
1219    // wants it closed: it runs the suite in a checkout of the commit, where
1220    // no untracked file exists to be read.
1221    //
1222    // `tree_at_start` — not a fresh `git status`. The gates have run by now
1223    // and may have written into the tree; what a stamp needs to know is what
1224    // the suite could READ, which is the state it was handed. See the
1225    // capture in `pre_push`.
1226    let worktree_clean = tree_at_start.trim().is_empty();
1227    let in_snapshot = crate::rehearsal::in_snapshot();
1228    let mut stamped: Vec<String> = Vec::new();
1229    for tip in tips {
1230        // Inside a rehearsal the working tree IS a checkout git made of this
1231        // commit, so it is the tip's content by construction — and whatever
1232        // `amont.snapshotPrepare` had to add to make it runnable (a
1233        // `node_modules`, a virtualenv) is not a reason to distrust it. That
1234        // is the same argument a pushed-tree snapshot makes.
1235        let is_head = head.as_deref() == Some(tip.as_str());
1236        let tree_is_tip = is_head && (in_snapshot || worktree_clean);
1237        // PER GATE, from what each one actually did — not from the config.
1238        // `amont.testPushedTree` is a request; `pushed_tree::ran_on_tip` is
1239        // the record of which gates were handed a checkout of this tip. A
1240        // gate that ran somewhere else (a snapshot that could not be made,
1241        // or a check that ran in the working tree) may vouch for the tip
1242        // only when the working tree WAS the tip. Deciding from the flag
1243        // stamped every passing gate onto a tip that one of them had never
1244        // seen.
1245        let vouched: Vec<String> = gates
1246            .iter()
1247            .filter(|g| tree_is_tip || crate::pushed_tree::ran_on_tip(g, tip))
1248            .cloned()
1249            .collect();
1250        if vouched.is_empty() {
1251            continue;
1252        }
1253        let spec = format!("{tip}^{{tree}}");
1254        let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
1255            continue;
1256        };
1257        if crate::gate_stamp::stamp_push(tip, &tree, &vouched) {
1258            for g in vouched {
1259                if !stamped.contains(&g) {
1260                    stamped.push(g);
1261                }
1262            }
1263        }
1264    }
1265    if !stamped.is_empty() {
1266        crate::say!(
1267            "{} stamped {} for this tree — the next push of it skips them ({})",
1268            valid_sign(),
1269            highlight(&stamped.join(" ")),
1270            crate::gate_stamp::NOTES_REF,
1271        );
1272    }
1273}
1274
1275/// Of the checks that passed, the ones an attestation may actually VOUCH for.
1276///
1277/// A language gate whose scope the push never touched returns `Passed` having
1278/// run nothing — `cargo_test` walks its refs, finds no crate root, and falls
1279/// out of the loop green. That is right for a push gate (there was nothing to
1280/// object to) and wrong for an attestation: a JS-only push was minting
1281/// `gates … pre-push-cargo-test pre-push-go-test pre-push-pytest`, and in a
1282/// MIXED repository CI would then skip a suite that nobody ran on that tree.
1283///
1284/// The declared `scope` is the honest filter, and the same data `amont list`
1285/// already reports. Unscoped checks (`Scope::ALWAYS` — branch-protect,
1286/// secrets) match everything and are vouched for, which is accurate: they
1287/// really did run. An empty `changed` vouches for nothing scoped, which is
1288/// the safe direction — CI runs the suite.
1289///
1290/// [`Scope::touches`], NOT `Scope::matches`. `matches` also asks whether the
1291/// repository has opted in — whether a `Cargo.toml` exists — and asking that
1292/// of a push DIFF can only answer no unless the push happened to touch the
1293/// marker. So `pre-push-cargo-test` was vouched for by a push that edited
1294/// `Cargo.toml` and never by one that edited only `.rs` files, which is the
1295/// ordinary case and the one worth skipping CI for. The feature attested
1296/// almost nothing, silently, and looked like it worked.
1297///
1298/// WHAT THIS IS STILL A PROXY FOR, stated plainly because the trust path
1299/// deserves it: the honest question is "did this gate actually run", and no
1300/// gate reports that. `rust_tools::test` returns `Passed` whether it ran a
1301/// suite or found no crate root and fell out of its loop — the very thing
1302/// the first paragraph describes. Scope is the closest available stand-in.
1303/// It is now a good one: a gate is vouched for only if the push changed a
1304/// file its extensions cover.
1305///
1306/// The gap that remains is narrow and one-directional: a `.rs` file outside
1307/// every crate would be covered here while `cargo test` had nothing to say
1308/// about it. Closing it properly means an outcome that distinguishes "ran
1309/// and passed" from "found nothing to do", which is a change to every gate
1310/// and to `Outcome` itself — worth doing, not worth smuggling into this.
1311fn attestable(checks: &[&dyn Check], passed: &[String], changed: &[String]) -> Vec<String> {
1312    checks
1313        .iter()
1314        .filter(|c| passed.iter().any(|p| p == c.name()))
1315        .filter(|c| c.scope().touches(changed))
1316        .map(|c| c.name().to_string())
1317        .collect()
1318}
1319
1320#[cfg(test)]
1321mod tests {
1322    use super::*;
1323    use crate::check::{Builtin, Scope};
1324    use std::sync::atomic::{AtomicUsize, Ordering};
1325
1326    /// A check whose only job is to carry a name and a severity into `report`.
1327    /// Its `run` is never called — `report` is fed outcomes directly, which is
1328    /// what makes `Unavailable` testable at all: the real thing needs a missing
1329    /// binary, and a test that uninstalls the developer's toolchain is worse
1330    /// than no test.
1331    const fn stub(name: &'static str, severity: Severity) -> Builtin {
1332        Builtin {
1333            name,
1334            stage: Stage::PreCommit,
1335            scope: Scope::ALWAYS,
1336            severity,
1337            run: |_| Outcome::Passed,
1338            fix: crate::check::Fix::None,
1339            reach: crate::check::Reach::Convention,
1340        }
1341    }
1342
1343    /// A pre-push gate with an OPT-IN file, as the real Rust and Python
1344    /// gates have: `.rs` files, but only where a `Cargo.toml` exists.
1345    const fn opt_in(
1346        name: &'static str,
1347        exts: &'static [&'static str],
1348        names: &'static [&'static str],
1349    ) -> Builtin {
1350        Builtin {
1351            name,
1352            stage: Stage::PrePush,
1353            scope: Scope::new(exts, names),
1354            severity: Severity::Block,
1355            run: |_| Outcome::Passed,
1356            fix: crate::check::Fix::None,
1357            reach: crate::check::Reach::Convention,
1358        }
1359    }
1360
1361    /// A pre-push gate scoped to one language's files.
1362    const fn scoped(name: &'static str, exts: &'static [&'static str]) -> Builtin {
1363        Builtin {
1364            name,
1365            stage: Stage::PrePush,
1366            scope: Scope::new(exts, &[]),
1367            severity: Severity::Block,
1368            run: |_| Outcome::Passed,
1369            fix: crate::check::Fix::None,
1370            reach: crate::check::Reach::Convention,
1371        }
1372    }
1373
1374    /// The over-claim this filter exists to stop, caught in the wild: a
1375    /// JS-only push minted `gates … pre-push-cargo-test pre-push-go-test
1376    /// pre-push-pytest`, because each of those gates finds nothing of its
1377    /// language to do and returns `Passed` having run NOTHING. Harmless in a
1378    /// single-language repo, unsound in a mixed one — CI would skip a suite
1379    /// nobody ran on that tree.
1380    #[test]
1381    fn a_gate_whose_language_the_push_never_touched_is_not_vouched_for() {
1382        let js = scoped("pre-push-run-tests-js", &[".ts", ".js"]);
1383        let rust = scoped("pre-push-cargo-test", &[".rs"]);
1384        let py = scoped("pre-push-pytest", &[".py"]);
1385        let always = stub("pre-push-secrets", Severity::Block);
1386        let checks: Vec<&dyn Check> = vec![&js, &rust, &py, &always];
1387        let passed: Vec<String> = checks.iter().map(|c| c.name().to_string()).collect();
1388
1389        let changed = vec!["app/routes/home.ts".to_string()];
1390        let vouched = attestable(&checks, &passed, &changed);
1391        assert_eq!(
1392            vouched,
1393            vec![
1394                "pre-push-run-tests-js".to_string(),
1395                "pre-push-secrets".to_string()
1396            ],
1397            "only the gate that had work, plus the unscoped one that always runs"
1398        );
1399
1400        // Nothing computed about the push vouches for nothing scoped — the
1401        // safe direction, since CI then runs the suite.
1402        assert_eq!(
1403            attestable(&checks, &passed, &[]),
1404            vec!["pre-push-secrets".to_string()]
1405        );
1406
1407        // A check that did NOT pass is never vouched for, whatever its scope.
1408        let only_rust_passed = vec!["pre-push-cargo-test".to_string()];
1409        assert!(attestable(&checks, &only_rust_passed, &changed).is_empty());
1410    }
1411
1412    /// No overrides configured. `report` takes them as a VALUE now, so its
1413    /// tests need no repository and no git at all.
1414    fn none() -> Overrides {
1415        Overrides::default()
1416    }
1417
1418    static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
1419    static WARNER: Builtin = stub("stub-warner", Severity::Warn);
1420
1421    /// The unit tests hold `&dyn Check` for the same reason the dispatcher
1422    /// does: `report` must not be able to tell a built-in from an external.
1423    const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
1424        [cs[0], cs[1], cs[2]]
1425    }
1426
1427    /// The classification itself, which used to be unreachable: while one
1428    /// function classified AND printed AND returned a code, a test could assert
1429    /// the code and nothing else.
1430    #[test]
1431    fn every_outcome_lands_in_the_right_bucket() {
1432        let checks: [&dyn Check; 5] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER, &BLOCKER];
1433        let got = classify(
1434            &checks,
1435            &[
1436                Outcome::Passed,
1437                Outcome::Unavailable,
1438                Outcome::Failed,
1439                Outcome::Failed,
1440                Outcome::Inert,
1441            ],
1442            &none(),
1443        );
1444        assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
1445        assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
1446        assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
1447        assert_eq!(got.passed, 1, "inert is not a pass: {got:?}");
1448    }
1449
1450    /// A clean stage concludes nothing at all — not an empty message, no
1451    /// message. Twenty checks that passed should print no roll-ups.
1452    ///
1453    /// `passed` is a tally, not a roll-up. It exists so that `amont.quiet` can
1454    /// say how many lines it swallowed, and it must never be the reason this
1455    /// report looks like it has something to announce.
1456    #[test]
1457    fn a_clean_stage_has_nothing_to_report() {
1458        let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
1459        let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
1460        assert!(
1461            got.fixed.is_empty()
1462                && got.blocked.is_empty()
1463                && got.downgraded.is_empty()
1464                && got.unavailable.is_empty(),
1465            "a clean stage found something to announce: {got:?}"
1466        );
1467        assert_eq!(got.passed, 1, "the pass was not tallied: {got:?}");
1468        assert_eq!(got.verdict(), Verdict::Proceed);
1469    }
1470
1471    #[test]
1472    fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
1473        let b: &dyn Check = &BLOCKER;
1474        let w: &dyn Check = &WARNER;
1475        assert_eq!(
1476            classify(&[b], &[Outcome::Failed], &none()).verdict(),
1477            Verdict::Block
1478        );
1479        assert_eq!(
1480            classify(&[b], &[Outcome::Passed], &none()).verdict(),
1481            Verdict::Proceed
1482        );
1483        // Every non-blocking shape, one at a time, so a regression cannot hide
1484        // behind a passing sibling.
1485        assert_eq!(
1486            classify(&[b], &[Outcome::Warned], &none()).verdict(),
1487            Verdict::Proceed
1488        );
1489        assert_eq!(
1490            classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
1491            Verdict::Proceed
1492        );
1493        assert_eq!(
1494            classify(&[w], &[Outcome::Failed], &none()).verdict(),
1495            Verdict::Proceed
1496        );
1497    }
1498
1499    #[test]
1500    fn one_blocking_failure_among_many_still_fails() {
1501        let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
1502        assert_eq!(
1503            classify(
1504                &checks,
1505                &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
1506                &none()
1507            )
1508            .verdict(),
1509            Verdict::Block
1510        );
1511        // Same shape, with the only *blocking* failure removed.
1512        assert_eq!(
1513            classify(
1514                &checks,
1515                &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
1516                &none()
1517            )
1518            .verdict(),
1519            Verdict::Proceed
1520        );
1521    }
1522
1523    /// The slot of a check whose thread died. Reading that as a pass is how a
1524    /// crash becomes a green commit.
1525    ///
1526    /// Asserted through the RUNNER, not through a `Default` impl: the rule
1527    /// belongs to this call site, and a test on `Outcome::default()` proved
1528    /// only that a trait impl existed, not that the runner used it.
1529    /// A check that PANICS must fail the commit, not pass it — and must not
1530    /// take the other checks down with it.
1531    ///
1532    /// Driven through the stage body rather than the runner, because the value
1533    /// that stands in for a dead check is chosen at the call site and the
1534    /// runner's own test cannot see that choice.
1535    #[test]
1536    fn a_panicking_check_blocks_the_commit() {
1537        static DIES: Builtin = Builtin {
1538            name: "stub-dies",
1539            stage: Stage::PreCommit,
1540            scope: Scope::ALWAYS,
1541            severity: Severity::Block,
1542            run: |_| panic!("this check died"),
1543            fix: crate::check::Fix::None,
1544            reach: crate::check::Reach::Convention,
1545        };
1546        let hook = std::panic::take_hook();
1547        std::panic::set_hook(Box::new(|_| {}));
1548        let push = crate::pushrefs::PushRefs::default();
1549        let manifest = crate::manifest::Manifest::default();
1550        let settings = crate::config::Settings::default();
1551        let ctx = Ctx {
1552            name: "pre-commit",
1553            args: &[],
1554            hooks_dir: std::path::Path::new("."),
1555            push: &push,
1556            manifest: &manifest,
1557            settings: &settings,
1558        };
1559        let verdict = run_stage(&[&DIES], &ctx, &none());
1560        std::panic::set_hook(hook);
1561        assert_eq!(
1562            verdict,
1563            Verdict::Block,
1564            "a check that died must not let the commit through"
1565        );
1566    }
1567
1568    #[test]
1569    fn a_thread_that_dies_leaves_a_failure_behind() {
1570        // The default hook would print a backtrace for the deliberate panic and
1571        // make a passing run look broken.
1572        let hook = std::panic::take_hook();
1573        std::panic::set_hook(Box::new(|_| {}));
1574        let items = ["a", "b", "c"];
1575        let out = run_concurrently(
1576            &items,
1577            |n: &&str| {
1578                if *n == "b" {
1579                    panic!("this check died");
1580                }
1581                Outcome::Passed
1582            },
1583            Outcome::Failed,
1584        );
1585        std::panic::set_hook(hook);
1586        assert_eq!(
1587            out,
1588            vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
1589            "a dead check must not read as one that passed, \
1590             and must not take the other checks down with it"
1591        );
1592    }
1593    use std::time::{Duration, Instant};
1594
1595    /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
1596    /// observe all the others arrive. Were the runner serial, the first task
1597    /// would wait alone, time out, and return non-zero — a failure, not a hang.
1598    #[test]
1599    fn run_concurrently_actually_overlaps() {
1600        static ARRIVED: AtomicUsize = AtomicUsize::new(0);
1601        ARRIVED.store(0, Ordering::SeqCst);
1602        let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
1603        let n = names.len();
1604
1605        let out = run_concurrently(
1606            &names,
1607            move |_: &&str| {
1608                ARRIVED.fetch_add(1, Ordering::SeqCst);
1609                let deadline = Instant::now() + Duration::from_secs(10);
1610                while ARRIVED.load(Ordering::SeqCst) < n {
1611                    if Instant::now() > deadline {
1612                        return 1; // never met the others — execution was serial
1613                    }
1614                    std::thread::yield_now();
1615                }
1616                0
1617            },
1618            1,
1619        );
1620        assert!(
1621            out.iter().all(|c| *c == 0),
1622            "tasks did not overlap: {out:?}"
1623        );
1624    }
1625
1626    #[test]
1627    fn results_come_back_in_input_order() {
1628        let names: Vec<&'static str> = vec!["first", "second", "third"];
1629        let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
1630        assert_eq!(out, vec![0, 7, 0], "results keep the input order");
1631    }
1632
1633    /// The filter calls the shared resolver rather than restating it. This test
1634    /// used to inline `n.contains(s)` — its own copy of the rule — and so went
1635    /// on passing after the rule changed underneath it.
1636    #[test]
1637    fn skips_are_filtered_by_the_shared_resolver() {
1638        let all = ["pre-commit-ruff", "pre-commit-prettier"];
1639        let skips = ["ruff".to_string()];
1640        let kept: Vec<_> = all
1641            .iter()
1642            .copied()
1643            .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
1644            .collect();
1645        assert_eq!(kept, vec!["pre-commit-prettier"]);
1646    }
1647
1648    /// The ordinary Rust push: source changed, `Cargo.toml` untouched.
1649    ///
1650    /// This test used to assert the OPPOSITE, and said so — it pinned
1651    /// `attestable` filtering on `Scope::matches`, which also asks whether
1652    /// the repository has opted in. Asking that of a push diff meant a
1653    /// `.rs`-only push, in a repository with a `Cargo.toml` sitting right
1654    /// there, attested nothing. Since that is what nearly every Rust push
1655    /// looks like, the feature was attesting almost nothing at all — quietly,
1656    /// while appearing to work.
1657    #[test]
1658    fn an_ordinary_source_push_is_vouched_for() {
1659        let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
1660        let checks: Vec<&dyn Check> = vec![&rust];
1661        let passed = vec!["pre-push-cargo-test".to_string()];
1662
1663        let changed = vec!["crates/amont/src/main.rs".to_string()];
1664        assert_eq!(
1665            attestable(&checks, &passed, &changed),
1666            vec!["pre-push-cargo-test".to_string()],
1667            "a push that changed Rust must vouch for the Rust gate"
1668        );
1669
1670        // And still when the marker IS in the diff — the opt-in file is not
1671        // required, but it is not disqualifying either.
1672        let changed = vec![
1673            "crates/amont/src/main.rs".to_string(),
1674            "Cargo.toml".to_string(),
1675        ];
1676        assert_eq!(
1677            attestable(&checks, &passed, &changed),
1678            vec!["pre-push-cargo-test".to_string()]
1679        );
1680    }
1681
1682    /// The over-claim the filter exists to stop, with an opt-in gate: a
1683    /// JS-only push must not vouch for the Rust suite, whatever files the
1684    /// repository contains.
1685    ///
1686    /// This is the half of the contract the fix above must not have broken,
1687    /// and it is the reason `touches` asks about EXTENSIONS rather than
1688    /// dropping the scope test altogether.
1689    #[test]
1690    fn an_opt_in_gate_is_not_vouched_for_by_a_push_in_another_language() {
1691        let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
1692        let checks: Vec<&dyn Check> = vec![&rust];
1693        let passed = vec!["pre-push-cargo-test".to_string()];
1694
1695        for changed in [
1696            vec!["app/routes/home.ts".to_string()],
1697            // Even the marker alone: editing Cargo.toml changes no Rust
1698            // source, so the suite has nothing new to have verified.
1699            vec!["Cargo.toml".to_string()],
1700            vec![],
1701        ] {
1702            assert!(
1703                attestable(&checks, &passed, &changed).is_empty(),
1704                "must not vouch for the Rust gate on {changed:?}"
1705            );
1706        }
1707    }
1708}