Skip to main content

amont_runtime/
registry.rs

1//! The hook registry — one table, one signature.
2//!
3//! Before this, dispatch was a 20-arm `match` in main.rs and handlers had four
4//! different signatures (`run(&args)`, `run(&hook, &args)`, `argo_lint(&args)`,
5//! …). Two costs, one of them real:
6//!
7//!   - adding a hook meant touching a match arm, a module, and remembering
8//!     which signature that one used;
9//!   - the hook NAME was written twice — in the arm and as the shim's filename
10//!     — with nothing checking they agree. A shim the binary does not recognise
11//!     exits 2 and blocks the commit; a handler with no shim is dead code. The
12//!     consistency test below turns that pairing into something enforced.
13
14use std::ffi::OsString;
15use std::path::Path;
16
17use crate::check::{Builtin, Check, Fix, GitState, Outcome, Scope, Severity, Stage, Verdict};
18use crate::pushrefs::PushRefs;
19use crate::{dispatch, hooks};
20
21/// Everything a hook is given. One shape for all of them, so a handler that
22/// needs the invoked name (ban-terms excludes its own source by it) or the
23/// hooks directory (the dispatchers glob it) does not need its own signature.
24pub struct Ctx<'a> {
25    /// The hook name as invoked.
26    pub name: &'a str,
27    /// Arguments git passed the hook.
28    pub args: &'a [OsString],
29    /// Directory the shim lives in. Only foreign sub-hooks are found here now;
30    /// our own checks are functions in this binary.
31    pub hooks_dir: &'a Path,
32    /// The pre-push ref list, read from stdin at most once and lent to every
33    /// check that asks. See `pushrefs`.
34    pub push: &'a PushRefs,
35    /// What this repository's manifest declares — parsed and trust-gated once
36    /// by the entrypoint, lent to everything downstream. The same shape as
37    /// `push`: read once, owned high, borrowed everywhere.
38    pub manifest: &'a crate::manifest::Manifest,
39}
40
41pub type HookFn = fn(&Ctx) -> Verdict;
42
43/// name → handler. The single place a hook is registered.
44/// The five hook names git itself invokes. Everything else is a `Check`.
45pub const ENTRYPOINTS: &[(&str, HookFn)] = &[
46    ("pre-commit", dispatch::pre_commit),
47    ("pre-push", dispatch::pre_push),
48    ("commit-msg", |ctx| hooks::commit_msg::run(ctx.args)),
49    ("prepare-commit-msg", |ctx| {
50        hooks::prepare_commit_msg::run(ctx.args)
51    }),
52    ("post-commit", |ctx| hooks::post_commit::run(ctx)),
53];
54
55/// Every check, in the order its stage runs them.
56///
57/// ONE declaration each: name, stage, scope and function together. This
58/// replaced `REGISTRY` plus `PRE_COMMIT_CHECKS` plus `PRE_PUSH_CHECKS` plus the
59/// fleet crate's `LANGUAGES` — four tables keyed by the same string, kept in
60/// step by reconciliation tests that are now unnecessary rather than passing.
61///
62/// pre-push order is the cost order: refuse a forbidden push before validating
63/// a name, and validate everything structural before paying for a test suite.
64/// Operations during which a content check cannot say anything useful: half the
65/// tree is somebody else's work, and you cannot fix it from inside the
66/// operation anyway.
67///
68/// NOT applied to `merge-conflict` or `ban-terms`. Those are exactly the checks
69/// you want during a resolution commit — leaving a conflict marker in the
70/// commit that RESOLVES a merge is the bug, and importing a banned term from
71/// the other branch is the other one. The old behaviour skipped the whole
72/// pre-commit stage during a cherry-pick, which silenced both.
73const MID_OPERATION: &[GitState] = &[
74    GitState::Merge,
75    GitState::Rebase,
76    GitState::CherryPick,
77    GitState::Revert,
78];
79
80pub const CHECKS: &[Builtin] = &[
81    // ---- pre-commit ----
82    Builtin {
83        name: "pre-commit-argo-lint",
84        stage: Stage::PreCommit,
85        scope: Scope::new(
86            hooks::k8s::EXTS,
87            &["kustomization.yaml", "kustomization.yml"],
88        )
89        .not_during(MID_OPERATION),
90        severity: Severity::Block,
91        fix: Fix::None,
92        run: |ctx| hooks::k8s::argo_lint(ctx.args),
93    },
94    Builtin {
95        name: "pre-commit-ban-terms",
96        stage: Stage::PreCommit,
97        scope: Scope::files(&[".js", ".jsx", ".ts", ".tsx", ".vue"]),
98        severity: Severity::Block,
99        fix: Fix::None,
100        run: |ctx| hooks::ban_terms::run(ctx.name, ctx.args),
101    },
102    // The push-time contract, said at the first commit — when renaming the
103    // branch costs one command and zero rework. Same short name as the
104    // pre-push check on purpose: `hook.skip branch-pattern` silences the
105    // rule, not one of its two voices.
106    Builtin {
107        name: "pre-commit-branch-pattern",
108        stage: Stage::PreCommit,
109        scope: Scope::ALWAYS,
110        severity: Severity::Warn,
111        fix: Fix::None,
112        run: |_ctx| hooks::branch_pattern::early(),
113    },
114    Builtin {
115        name: "pre-commit-cargo-fmt",
116        stage: Stage::PreCommit,
117        scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"]).not_during(MID_OPERATION),
118        severity: Severity::Block,
119        fix: Fix::Rewrite,
120        run: |ctx| hooks::rust_tools::fmt(ctx.args),
121    },
122    Builtin {
123        name: "pre-commit-clippy",
124        stage: Stage::PreCommit,
125        scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"]).not_during(MID_OPERATION),
126        severity: Severity::Block,
127        fix: Fix::None,
128        run: |ctx| hooks::rust_tools::clippy(ctx.args),
129    },
130    Builtin {
131        name: "pre-commit-kube-linter",
132        stage: Stage::PreCommit,
133        scope: Scope::new(
134            hooks::k8s::EXTS,
135            &[".kube-linter*.yaml", ".kube-linter*.yml"],
136        )
137        .not_during(MID_OPERATION),
138        severity: Severity::Block,
139        fix: Fix::None,
140        run: |ctx| hooks::k8s::kube_linter(ctx.args),
141    },
142    Builtin {
143        name: "pre-commit-kubeconform",
144        stage: Stage::PreCommit,
145        scope: Scope::new(
146            hooks::k8s::EXTS,
147            &["kustomization.yaml", "kustomization.yml"],
148        )
149        .not_during(MID_OPERATION),
150        severity: Severity::Block,
151        fix: Fix::None,
152        run: |ctx| hooks::k8s::kubeconform(ctx.args),
153    },
154    Builtin {
155        name: "pre-commit-lint-js",
156        stage: Stage::PreCommit,
157        scope: Scope::new(hooks::lint_js::EXTS, &["package.json"]).not_during(MID_OPERATION),
158        severity: Severity::Block,
159        fix: Fix::None,
160        run: |ctx| hooks::lint_js::run(ctx.args),
161    },
162    Builtin {
163        name: "pre-commit-lint-json-yaml",
164        stage: Stage::PreCommit,
165        scope: Scope::files(hooks::lint_json_yaml::EXTS).not_during(MID_OPERATION),
166        severity: Severity::Block,
167        fix: Fix::None,
168        run: |ctx| hooks::lint_json_yaml::run(ctx.args),
169    },
170    Builtin {
171        name: "pre-commit-merge-conflict",
172        stage: Stage::PreCommit,
173        scope: Scope::ALWAYS,
174        severity: Severity::Block,
175        fix: Fix::None,
176        run: |ctx| hooks::merge_conflict::run(ctx.name, ctx.args),
177    },
178    Builtin {
179        name: "pre-commit-package-lock",
180        stage: Stage::PreCommit,
181        scope: Scope::new(&[], &["package.json"]),
182        severity: Severity::Block,
183        fix: Fix::None,
184        run: |ctx| hooks::package_lock::run(ctx.args),
185    },
186    Builtin {
187        name: "pre-commit-prettier",
188        stage: Stage::PreCommit,
189        scope: Scope::new(
190            &[],
191            &[
192                ".prettierrc",
193                ".prettierrc.json",
194                ".prettierrc.yml",
195                ".prettierrc.yaml",
196                ".prettierrc.js",
197                "prettier.config.js",
198            ],
199        )
200        .not_during(MID_OPERATION),
201        severity: Severity::Block,
202        fix: Fix::Rewrite,
203        run: |ctx| hooks::prettier::run(ctx.args),
204    },
205    Builtin {
206        name: "pre-commit-pyright",
207        stage: Stage::PreCommit,
208        scope: Scope::new(
209            hooks::python_tools::EXTS,
210            &[
211                "pyrightconfig.json",
212                "pyrightconfig.jsonc",
213                "pyproject.toml",
214            ],
215        )
216        .not_during(MID_OPERATION),
217        severity: Severity::Block,
218        fix: Fix::None,
219        run: |ctx| hooks::python_tools::pyright(ctx.args),
220    },
221    Builtin {
222        name: "pre-commit-ruff",
223        stage: Stage::PreCommit,
224        scope: Scope::new(
225            hooks::python_tools::EXTS,
226            &["ruff.toml", ".ruff.toml", "pyproject.toml"],
227        )
228        .not_during(MID_OPERATION),
229        severity: Severity::Block,
230        fix: Fix::Rewrite,
231        run: |ctx| hooks::python_tools::ruff(ctx.args),
232    },
233    Builtin {
234        name: "pre-commit-usual-name",
235        stage: Stage::PreCommit,
236        scope: Scope::ALWAYS,
237        severity: Severity::Block,
238        fix: Fix::None,
239        run: |ctx| hooks::usual_name::run(ctx.args),
240    },
241    Builtin {
242        name: "pre-commit-yamllint",
243        stage: Stage::PreCommit,
244        scope: Scope::new(
245            hooks::yamllint::EXTS,
246            &[".yamllint.yaml", ".yamllint.yml", ".yamllint"],
247        )
248        .not_during(MID_OPERATION),
249        severity: Severity::Block,
250        fix: Fix::None,
251        run: |ctx| hooks::yamllint::run(ctx.args),
252    },
253    // ---- pre-push, cheapest and most decisive first ----
254    Builtin {
255        name: "pre-push-branch-protect",
256        stage: Stage::PrePush,
257        scope: Scope::ALWAYS,
258        severity: Severity::Block,
259        fix: Fix::None,
260        run: |ctx| hooks::branch_protect::run(ctx.push.get()),
261    },
262    Builtin {
263        name: "pre-push-branch-pattern",
264        stage: Stage::PrePush,
265        scope: Scope::ALWAYS,
266        severity: Severity::Block,
267        fix: Fix::None,
268        run: |ctx| hooks::branch_pattern::run(ctx.push.get(), ctx.args),
269    },
270    Builtin {
271        name: "pre-push-pull-rebase",
272        stage: Stage::PrePush,
273        scope: Scope::ALWAYS.not_during(&[GitState::Rebase, GitState::Merge]),
274        severity: Severity::Block,
275        fix: Fix::None,
276        run: |ctx| hooks::pull_rebase::run(ctx.args),
277    },
278    // The three dependency audits sit between the structural checks and the
279    // test suites: network-bound but seconds, where a suite is minutes —
280    // and when a v* tag is in the push, failing here saves the suite's
281    // whole cost. Each opts in by the LOCKFILE its tool audits: an audit
282    // without a resolved tree audits a guess. On a branch push they only
283    // warn; the blocking case is the release tag — see `hooks::audit`.
284    Builtin {
285        name: "pre-push-audit-js",
286        stage: Stage::PrePush,
287        scope: Scope::new(&[], &["package-lock.json"]),
288        severity: Severity::Block,
289        fix: Fix::None,
290        run: |ctx| hooks::audit::js(ctx.push.get()),
291    },
292    Builtin {
293        name: "pre-push-audit-python",
294        stage: Stage::PrePush,
295        scope: Scope::new(&[], &["requirements.txt"]),
296        severity: Severity::Block,
297        fix: Fix::None,
298        run: |ctx| hooks::audit::python(ctx.push.get()),
299    },
300    Builtin {
301        name: "pre-push-audit-rust",
302        stage: Stage::PrePush,
303        scope: Scope::new(&[], &["Cargo.lock"]),
304        severity: Severity::Block,
305        fix: Fix::None,
306        run: |ctx| hooks::audit::rust(ctx.push.get()),
307    },
308    Builtin {
309        name: "pre-push-run-tests-js",
310        stage: Stage::PrePush,
311        scope: Scope::new(hooks::run_tests::JS_EXTS, &["package.json"])
312            .not_during(&[GitState::Bisect, GitState::Rebase]),
313        severity: Severity::Block,
314        fix: Fix::None,
315        run: |ctx| hooks::run_tests::run(ctx.push.get(), &ctx.manifest.externals),
316    },
317    Builtin {
318        name: "pre-push-cargo-test",
319        stage: Stage::PrePush,
320        scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"])
321            .not_during(&[GitState::Bisect, GitState::Rebase]),
322        severity: Severity::Block,
323        fix: Fix::None,
324        run: |ctx| hooks::rust_tools::test(ctx.push.get()),
325    },
326];
327
328/// A check's severity, after any per-repository override.
329///
330/// `git config amont.severity.<check> warn` downgrades a blocking check to a
331/// warning. Unlike `hook.skip` it keeps the signal: the check still runs and
332/// still reports, it just stops failing the commit.
333pub fn severity_of(check: &dyn Check) -> Severity {
334    effective_override(None, check.name()).unwrap_or_else(|| check.severity())
335}
336
337/// The config key a severity override lives under.
338pub fn severity_key(check: &str) -> String {
339    format!("amont.severity.{check}")
340}
341
342/// Every severity override visible here, resolved the way `--get` resolves it.
343///
344/// ONE subprocess for the whole stage, and — more importantly — a VALUE. The
345/// dispatcher used to call `severity_of` inside the loop that classifies
346/// outcomes, which put a `git` spawn in the middle of a fold and made the fold
347/// impossible to test without a repository.
348///
349/// `--get-regexp` emits entries in precedence order, so folding with overwrite
350/// lands on the same answer `--get` gives. That equivalence is not assumed:
351/// `the_batch_agrees_with_the_authority` pins it against `effective_override`.
352#[derive(Debug, Default, Clone)]
353pub struct Overrides(std::collections::BTreeMap<String, Severity>);
354
355impl Overrides {
356    pub fn read() -> Overrides {
357        Overrides::from_config(crate::git::stdout(&[
358            "config",
359            "--get-regexp",
360            r"^amont\.severity\.",
361        ]))
362    }
363
364    /// Built from `--get-regexp`-shaped text (`amont.severity.<check>
365    /// <value>` per line, in git's own precedence order — system, then
366    /// global, then local, then includes). `pub` so a reader that has
367    /// already fetched those lines for its own reasons (the fleet dashboard
368    /// needs the origin of each, which `Overrides` does not track) can still
369    /// ask this — the one place that must not get precedence wrong — rather
370    /// than re-deriving it from the lines by hand.
371    pub fn from_config(out: Option<String>) -> Overrides {
372        let mut map = std::collections::BTreeMap::new();
373        for line in out.as_deref().unwrap_or_default().lines() {
374            let Some((key, value)) = line.split_once(' ') else {
375                continue;
376            };
377            let Some(check) = key.strip_prefix("amont.severity.") else {
378                continue;
379            };
380            // Later entries overwrite earlier ones — git's own precedence,
381            // observed rather than reimplemented.
382            match Severity::parse(value.trim()) {
383                Some(s) => {
384                    map.insert(check.to_string(), s);
385                }
386                // An unrecognised value is not an override at all, and must not
387                // shadow a valid earlier one either.
388                None => {
389                    map.remove(check);
390                }
391            }
392        }
393        Overrides(map)
394    }
395
396    /// The configured key that applies to `check`, and what it says.
397    ///
398    /// Several keys can name one check — `pre-commit` and `clippy` and
399    /// `pre-commit-clippy` all reach `pre-commit-clippy`. The most specific
400    /// wins, which is the rule anybody would guess and the only one that lets
401    /// you downgrade a whole trigger and then exempt one check from it.
402    pub fn applied_to(&self, check: &str) -> Option<(&str, Severity)> {
403        self.0
404            .iter()
405            .filter_map(|(pattern, severity)| {
406                crate::names_check(check, pattern).map(|m| (m, pattern.as_str(), *severity))
407            })
408            .max_by_key(|(m, _, _)| *m)
409            .map(|(_, pattern, severity)| (pattern, severity))
410    }
411
412    /// The severity to apply to `check`, override or declared.
413    pub fn of(&self, check: &dyn Check) -> Severity {
414        self.applied_to(check.name())
415            .map(|(_, severity)| severity)
416            .unwrap_or_else(|| check.severity())
417    }
418}
419
420#[cfg(test)]
421mod precedence {
422    use super::{Overrides, Severity};
423
424    fn overrides(lines: &[&str]) -> Overrides {
425        let text = lines
426            .iter()
427            .map(|l| format!("amont.severity.{l}\n"))
428            .collect::<String>();
429        Overrides::from_config(Some(text))
430    }
431
432    /// The whole reason triggers and short names are allowed as keys: downgrade
433    /// a trigger wholesale, then say something different about one check. If the
434    /// broader key won instead, the exemption would be unwritable.
435    #[test]
436    fn the_more_specific_key_wins() {
437        let both = overrides(&["pre-commit warn", "pre-commit-clippy block"]);
438        assert_eq!(
439            both.applied_to("pre-commit-clippy"),
440            Some(("pre-commit-clippy", Severity::Block)),
441            "a full id beats its trigger"
442        );
443        assert_eq!(
444            both.applied_to("pre-commit-shellcheck"),
445            Some(("pre-commit", Severity::Warn)),
446            "and the trigger still governs every check it did not exempt"
447        );
448    }
449
450    /// Full id > short name > trigger, all three at once, so the ordering is
451    /// pinned end to end rather than one pair at a time.
452    #[test]
453    fn the_three_ways_to_name_a_check_are_ranked() {
454        let all = overrides(&["pre-commit warn", "clippy block", "pre-commit-clippy warn"]);
455        assert_eq!(
456            all.applied_to("pre-commit-clippy"),
457            Some(("pre-commit-clippy", Severity::Warn))
458        );
459
460        let no_full = overrides(&["pre-commit warn", "clippy block"]);
461        assert_eq!(
462            no_full.applied_to("pre-commit-clippy"),
463            Some(("clippy", Severity::Block)),
464            "a short name beats a trigger"
465        );
466    }
467
468    /// A key naming nothing must not become the answer by being the only one
469    /// there — that is how a repo believes it downgraded a check it never named.
470    #[test]
471    fn a_key_that_names_no_check_applies_to_nothing() {
472        let typo = overrides(&["clipy warn", "e warn", " warn"]);
473        assert_eq!(typo.applied_to("pre-commit-clippy"), None);
474    }
475}
476
477/// The override git would actually apply for `check`, or `None` if there is
478/// none (or the value is not one this understands).
479///
480/// `--get`, NOT `--get-regexp`: git returns the LAST value, so a local `block`
481/// beats a global `warn`. A reader that listed every entry instead and treated
482/// each as authoritative would report a downgrade that the dispatcher does not
483/// apply — which is exactly what the dashboard used to do.
484///
485/// `repo` is `None` for the current directory, which is where a hook runs.
486pub fn effective_override(repo: Option<&Path>, check: &str) -> Option<Severity> {
487    overrides_in(repo).applied_to(check).map(|(_, s)| s)
488}
489
490/// Which configured KEY applies to `check` here, if any.
491///
492/// The dashboard needs the key rather than the value: with three ways to name a
493/// check, "which of these lines is the one doing something" is the question a
494/// reader actually has.
495pub fn effective_key(repo: Option<&Path>, check: &str) -> Option<String> {
496    overrides_in(repo)
497        .applied_to(check)
498        .map(|(pattern, _)| pattern.to_string())
499}
500
501fn overrides_in(repo: Option<&Path>) -> Overrides {
502    let args = ["config", "--get-regexp", r"^amont\.severity\."];
503    Overrides::from_config(match repo {
504        None => crate::git::stdout(&args),
505        Some(dir) => crate::git::stdout_in(dir, &args),
506    })
507}
508
509/// Built-in checks for one stage, in declared order.
510pub fn stage_checks(stage: Stage) -> impl Iterator<Item = &'static Builtin> {
511    CHECKS.iter().filter(move |check| check.stage == stage)
512}
513
514/// Every check for one stage — built-ins first, then whatever this repository
515/// declares in `amont.conf`.
516///
517/// The order is not negotiable and not configurable. A third-party command must
518/// not be able to delay `pre-push-branch-protect`, and appending is the only
519/// arrangement in which it cannot.
520pub fn all_stage_checks<'a>(
521    stage: Stage,
522    manifest: &'a crate::manifest::Manifest,
523) -> Vec<&'a dyn Check> {
524    let mut out: Vec<&'a dyn Check> = stage_checks(stage)
525        .map(|check| check as &dyn Check)
526        .collect();
527    out.extend(
528        manifest
529            .externals
530            .iter()
531            .filter(|external| external.stage == stage)
532            .map(|external| external as &dyn Check),
533    );
534    out
535}
536
537pub fn lookup(name: &str, manifest: &crate::manifest::Manifest) -> Option<HookFn> {
538    if let Some((_, f)) = ENTRYPOINTS.iter().find(|(n, _)| *n == name) {
539        return Some(*f);
540    }
541    // A check invoked directly by name — how the tests drive individual checks,
542    // and how `amont <check>` works from a shell. Its Outcome collapses to an
543    // exit code here, honouring severity, so a `warn` check invoked directly
544    // reports without failing exactly as it does inside a dispatcher. The
545    // closure re-resolves through the Ctx it is handed — a plain fn pointer
546    // captures nothing, and the manifest travels ON the Ctx.
547    if CHECKS.iter().any(|check| check.name == name)
548        || manifest
549            .externals
550            .iter()
551            .any(|external| external.id == name)
552    {
553        return Some(|ctx: &Ctx| {
554            let check = one_named(ctx.name, ctx.manifest).expect("checked above");
555            Verdict::blocking(matches!(
556                (check.run(ctx), severity_of(check)),
557                (Outcome::Failed, Severity::Block)
558            ))
559        });
560    }
561    None
562}
563
564/// One check by name, whichever kind it is. Built-ins are searched first, which
565/// costs nothing because `manifest::parse` refuses a name a built-in already
566/// holds — the two guards together mean neither kind can shadow the other.
567pub fn one_named<'a>(name: &str, manifest: &'a crate::manifest::Manifest) -> Option<&'a dyn Check> {
568    if let Some(builtin) = CHECKS.iter().find(|check| check.name == name) {
569        return Some(builtin);
570    }
571    manifest
572        .externals
573        .iter()
574        .find(|external| external.id == name)
575        .map(|external| external as &dyn Check)
576}
577
578#[cfg(test)]
579mod tests {
580    use super::{lookup, Overrides, Severity, Stage, CHECKS, ENTRYPOINTS};
581    use std::collections::BTreeSet;
582
583    /// The batch reader must land on the same answer as the authority.
584    ///
585    /// `Overrides` folds `--get-regexp` output with overwrite; `effective_override`
586    /// asks `--get`. They agree only because git emits entries in precedence
587    /// order — an assumption, so it is asserted against real git rather than
588    /// trusted.
589    #[test]
590    fn the_batch_agrees_with_the_authority() {
591        let d = std::env::temp_dir().join(format!("ov-{}", std::process::id()));
592        let _ = std::fs::remove_dir_all(&d);
593        std::fs::create_dir_all(&d).unwrap();
594        let git = |args: &[&str]| {
595            std::process::Command::new("git")
596                .args(args)
597                .current_dir(&d)
598                .output()
599                .expect("git");
600        };
601        git(&["init", "-q", "--template=", "."]);
602        let key = "amont.severity.pre-commit-merge-conflict";
603        git(&["config", "--add", key, "warn"]);
604        git(&["config", "--add", key, "block"]);
605
606        let raw = std::process::Command::new("git")
607            .args(["config", "--get-regexp", r"^amont\.severity\."])
608            .current_dir(&d)
609            .output()
610            .expect("git");
611        let batch = Overrides::from_config(Some(
612            String::from_utf8_lossy(&raw.stdout).trim().to_string(),
613        ));
614        let authority =
615            crate::git::stdout_in(&d, &["config", "--get", key]).and_then(|v| Severity::parse(&v));
616        let _ = std::fs::remove_dir_all(&d);
617
618        assert_eq!(
619            authority,
620            Some(Severity::Block),
621            "git applies the last entry"
622        );
623        assert_eq!(
624            batch.0.get("pre-commit-merge-conflict").copied(),
625            authority,
626            "the batch reader disagreed with `--get`"
627        );
628    }
629
630    /// An unrecognised value is not an override, and must not shadow a valid
631    /// earlier one either — a typo would otherwise silently restore the
632    /// declared severity in a way nobody could see.
633    #[test]
634    fn an_unrecognised_value_clears_rather_than_overrides() {
635        let o = Overrides::from_config(Some(
636            "amont.severity.a warn\namont.severity.a advisory\namont.severity.b warn".to_string(),
637        ));
638        assert_eq!(o.0.get("a"), None, "a typo must not leave `warn` standing");
639        assert_eq!(o.0.get("b").copied(), Some(Severity::Warn));
640    }
641
642    #[test]
643    fn names_are_unique_across_entrypoints_and_checks() {
644        let mut seen = BTreeSet::new();
645        for n in ENTRYPOINTS
646            .iter()
647            .map(|(n, _)| *n)
648            .chain(CHECKS.iter().map(|check| check.name))
649        {
650            assert!(seen.insert(n), "duplicate registration: {n}");
651        }
652    }
653
654    /// Only FIVE files ship, and they are exactly the hook names git invokes.
655    #[test]
656    fn the_shipped_shims_are_exactly_the_git_invoked_hooks() {
657        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
658        let mut shipped: Vec<String> = std::fs::read_dir(dir)
659            .expect("templates/hooks")
660            .flatten()
661            .map(|entry| entry.file_name().to_string_lossy().into_owned())
662            .collect();
663        shipped.sort();
664        assert_eq!(
665            shipped,
666            vec![
667                "commit-msg",
668                "post-commit",
669                "pre-commit",
670                "pre-push",
671                "prepare-commit-msg"
672            ]
673        );
674        let none = crate::manifest::Manifest::default();
675        for name in &shipped {
676            assert!(
677                lookup(name, &none).is_some(),
678                "shipped shim {name:?} has no handler"
679            );
680        }
681    }
682
683    /// Every check is reachable by name, which is how a shell — and the tests —
684    /// invoke one directly.
685    #[test]
686    fn every_check_is_reachable_by_name() {
687        let none = crate::manifest::Manifest::default();
688        for check in CHECKS {
689            assert!(
690                lookup(check.name, &none).is_some(),
691                "{} not reachable",
692                check.name
693            );
694        }
695        assert!(lookup("pre-commit-not-a-check", &none).is_none());
696    }
697
698    /// pre-push is serial and fail-fast, so declaration order IS cost order.
699    #[test]
700    fn pre_push_runs_cheapest_first() {
701        let order: Vec<&str> = super::stage_checks(Stage::PrePush)
702            .map(|check| check.name)
703            .collect();
704        assert_eq!(
705            order,
706            vec![
707                "pre-push-branch-protect",
708                "pre-push-branch-pattern",
709                "pre-push-pull-rebase",
710                "pre-push-audit-js",
711                "pre-push-audit-python",
712                "pre-push-audit-rust",
713                "pre-push-run-tests-js",
714                "pre-push-cargo-test",
715            ]
716        );
717    }
718
719    /// What a check actually looks at, as opposed to what it DECLARES.
720    ///
721    /// `All` is a check that reads every staged path regardless of the
722    /// extensions in its scope (ban-terms greps them all); `Exts(e)` is a check
723    /// that filters by suffix, and `e` is the list it filters WITH.
724    enum Consumes {
725        All,
726        Exts(&'static [&'static str]),
727    }
728
729    /// Every check, and the file set it consumes. The table exists so a NEW
730    /// check cannot be added without somebody stating the answer.
731    ///
732    /// The incident: `pre-commit-lint-json-yaml` declared
733    /// `[".json", ".yaml", ".yml"]` in the registry while `lint_json_yaml::run`
734    /// asked `staged_files` for `[".yaml"]`. `amont list` reported the check
735    /// as covering `.yml`, the fleet dashboard agreed, and a staged, broken
736    /// `x.yml` returned `Outcome::Passed` with no output whatsoever. Nothing
737    /// connected the two lists, so nothing could notice.
738    ///
739    /// Each entry now names the module constant the check itself filters with,
740    /// which is the same constant the registry declares its scope from — so
741    /// this table cannot silently agree with a stale copy.
742    const CONSUMED: &[(&str, Consumes)] = &[
743        (
744            "pre-commit-argo-lint",
745            Consumes::Exts(crate::hooks::k8s::EXTS),
746        ),
747        // Declares JS extensions so the dashboard can say what it is FOR, but
748        // greps every staged path — a banned term in a `.md` is still a banned
749        // term. This is why the assertion below is a SUBSET check.
750        ("pre-commit-ban-terms", Consumes::All),
751        (
752            "pre-commit-cargo-fmt",
753            Consumes::Exts(crate::hooks::rust_tools::EXTS),
754        ),
755        (
756            "pre-commit-clippy",
757            Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
758        ),
759        (
760            "pre-commit-kube-linter",
761            Consumes::Exts(crate::hooks::k8s::EXTS),
762        ),
763        (
764            "pre-commit-kubeconform",
765            Consumes::Exts(crate::hooks::k8s::EXTS),
766        ),
767        (
768            "pre-commit-lint-js",
769            Consumes::Exts(crate::hooks::lint_js::EXTS),
770        ),
771        (
772            "pre-commit-lint-json-yaml",
773            Consumes::Exts(crate::hooks::lint_json_yaml::EXTS),
774        ),
775        ("pre-commit-merge-conflict", Consumes::All),
776        ("pre-commit-package-lock", Consumes::All),
777        // Declares `files: &[]` — it is opt-in by CONFIG, not by file type —
778        // while consuming seventeen extensions. The other reason the assertion
779        // is a subset check rather than an equality.
780        (
781            "pre-commit-prettier",
782            Consumes::Exts(crate::hooks::prettier::EXTS),
783        ),
784        (
785            "pre-commit-pyright",
786            Consumes::Exts(crate::hooks::python_tools::EXTS),
787        ),
788        (
789            "pre-commit-ruff",
790            Consumes::Exts(crate::hooks::python_tools::EXTS),
791        ),
792        ("pre-commit-usual-name", Consumes::All),
793        (
794            "pre-commit-yamllint",
795            Consumes::Exts(crate::hooks::yamllint::EXTS),
796        ),
797        ("pre-push-branch-protect", Consumes::All),
798        ("pre-push-branch-pattern", Consumes::All),
799        ("pre-push-pull-rebase", Consumes::All),
800        (
801            "pre-push-run-tests-js",
802            Consumes::Exts(crate::hooks::run_tests::JS_EXTS),
803        ),
804        (
805            "pre-push-cargo-test",
806            Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
807        ),
808    ];
809
810    /// A declared scope must never promise more than the check consumes.
811    ///
812    /// Two halves, and the first is the one that earns its keep: a check with a
813    /// non-empty `scope.files` that nobody has entered in `CONSUMED` fails the
814    /// build, so adding a check forces somebody to state what it actually
815    /// reads. The second half then pins that `scope.files ⊆ consumed`.
816    ///
817    /// SUBSET, not equality, deliberately: `ban-terms` declares JS extensions
818    /// and greps every staged path, and `prettier` declares `files: &[]` while
819    /// consuming seventeen extensions. Equality would forbid both.
820    #[test]
821    fn no_check_declares_a_file_type_it_does_not_consume() {
822        for (name, _) in CONSUMED {
823            assert!(
824                CHECKS.iter().any(|check| check.name == *name),
825                "CONSUMED names {name:?}, which is not a check"
826            );
827        }
828        for check in CHECKS {
829            let entry = CONSUMED.iter().find(|(name, _)| *name == check.name);
830            if check.scope.files.is_empty() && entry.is_none() {
831                continue;
832            }
833            let Some((_, consumes)) = entry else {
834                panic!(
835                    "{} declares scope.files {:?} but is missing from CONSUMED — \
836                     say what it actually reads",
837                    check.name, check.scope.files
838                );
839            };
840            let Consumes::Exts(consumed) = consumes else {
841                continue; // `All` consumes everything, so any declaration fits
842            };
843            for ext in check.scope.files {
844                assert!(
845                    consumed.contains(ext),
846                    "{} declares {ext:?} in its scope but never asks for it — \
847                     `amont list` would report a coverage the check does not have",
848                    check.name
849                );
850            }
851        }
852    }
853
854    /// Which checks contain code that repairs and re-stages, stated by hand.
855    ///
856    /// `pre-commit-cargo-fmt` and `pre-commit-ruff` both declared
857    /// `Fix::Rewrite` with NO fixing code anywhere — only `prettier.rs` and
858    /// `manifest.rs` ever called `restage`/`fixing_enabled`. `amont list
859    /// --json` reported `"fix":"rewrite"` for them regardless, and `agents_md`
860    /// explicitly directs agents to trust that JSON, so an agent would set
861    /// `amont.fix true` and wait for a repair that could never arrive.
862    const HAS_FIXING_CODE: &[(&str, bool)] = &[
863        ("pre-commit-argo-lint", false),
864        ("pre-commit-ban-terms", false),
865        ("pre-commit-branch-pattern", false),
866        ("pre-commit-cargo-fmt", true),
867        ("pre-commit-clippy", false),
868        ("pre-commit-kube-linter", false),
869        ("pre-commit-kubeconform", false),
870        ("pre-commit-lint-js", false),
871        ("pre-commit-lint-json-yaml", false),
872        ("pre-commit-merge-conflict", false),
873        ("pre-commit-package-lock", false),
874        ("pre-commit-prettier", true),
875        ("pre-commit-pyright", false),
876        ("pre-commit-ruff", true),
877        ("pre-commit-usual-name", false),
878        ("pre-commit-yamllint", false),
879        ("pre-push-branch-protect", false),
880        ("pre-push-branch-pattern", false),
881        ("pre-push-pull-rebase", false),
882        ("pre-push-audit-js", false),
883        ("pre-push-audit-python", false),
884        ("pre-push-audit-rust", false),
885        ("pre-push-run-tests-js", false),
886        ("pre-push-cargo-test", false),
887    ];
888
889    /// A `Fix::Rewrite` declaration is a PROMISE, and the set of checks that
890    /// keep it must equal the set that make it.
891    #[test]
892    fn every_rewrite_declaration_has_a_fixer() {
893        let declared: BTreeSet<&str> = CHECKS
894            .iter()
895            .filter(|check| check.fix == super::Fix::Rewrite)
896            .map(|check| check.name)
897            .collect();
898        let implemented: BTreeSet<&str> = HAS_FIXING_CODE
899            .iter()
900            .filter(|(_, has)| *has)
901            .map(|(name, _)| *name)
902            .collect();
903        assert_eq!(
904            declared, implemented,
905            "a check declaring Fix::Rewrite with no fixer lies to `amont list --json`, \
906             and a check with a fixer that does not declare it can never be reached"
907        );
908
909        // …and the table must cover every check, so a new one cannot be added
910        // without somebody answering the question.
911        let listed: BTreeSet<&str> = HAS_FIXING_CODE.iter().map(|(name, _)| *name).collect();
912        let all: BTreeSet<&str> = CHECKS.iter().map(|check| check.name).collect();
913        assert_eq!(listed, all, "HAS_FIXING_CODE does not cover CHECKS");
914    }
915
916    /// The reconciliation tests that used to live here are gone, and that is
917    /// the point of the refactor: there is no second table to disagree with.
918    #[test]
919    fn every_check_declares_a_stage_and_a_scope() {
920        assert_eq!(CHECKS.len(), 24);
921        let pre_commit = super::stage_checks(Stage::PreCommit).count();
922        let pre_push = super::stage_checks(Stage::PrePush).count();
923        assert_eq!(
924            pre_commit + pre_push,
925            CHECKS.len(),
926            "every check has a stage"
927        );
928    }
929}