Skip to main content

greengate_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::{
18    Builtin, Check, Fix, GitState, Outcome, Reach, Scope, Severity, Stage, Verdict,
19};
20use crate::pushrefs::PushRefs;
21use crate::{dispatch, hooks};
22
23/// Everything a hook is given. One shape for all of them, so a handler that
24/// needs the invoked name (ban-terms excludes its own source by it) or the
25/// hooks directory (the dispatchers glob it) does not need its own signature.
26pub struct Ctx<'a> {
27    /// The hook name as invoked.
28    pub name: &'a str,
29    /// Arguments git passed the hook.
30    pub args: &'a [OsString],
31    /// Directory the shim lives in. Only foreign sub-hooks are found here now;
32    /// our own checks are functions in this binary.
33    pub hooks_dir: &'a Path,
34    /// The pre-push ref list, read from stdin at most once and lent to every
35    /// check that asks. See `pushrefs`.
36    pub push: &'a PushRefs,
37    /// What this repository's manifest declares — parsed and trust-gated once
38    /// by the entrypoint, lent to everything downstream. The same shape as
39    /// `push`: read once, owned high, borrowed everywhere.
40    pub manifest: &'a crate::manifest::Manifest,
41    /// Configuration resolved once for this process: the manifest's trusted
42    /// policy plus the reads memoised over it. Joins `manifest` and `push` in
43    /// the read-once-borrow-everywhere shape, and replaces the process-global
44    /// policy store — see [`crate::config::Settings`].
45    pub settings: &'a crate::config::Settings,
46    /// The gates the rehearsal that made this pre-push snapshot handed to the
47    /// cluster (ADR-0017), parsed once in `main` with the rest of the
48    /// environment it removes; empty everywhere else.
49    pub handed_to_cluster: &'a [String],
50    /// What `amont land` set on its own push (ADR-0018), parsed once in
51    /// `main` with the rest of the environment it removes.
52    pub land: &'a crate::rehearsal::LandEnv,
53    /// This push's dependency-audit records and memos (ADR-0018): owned by
54    /// whoever starts the hook, lent to each audit.
55    pub audits: &'a crate::hooks::audit::Ledger,
56    /// The working tree a rehearsal snapshot was taken from, inside one
57    /// (`AMONT_SOURCE_WORKTREE`, read once in `main`); `None` elsewhere.
58    pub source_worktree: Option<&'a std::path::Path>,
59}
60
61pub type HookFn = fn(&Ctx) -> Verdict;
62
63/// name → handler. The single place a hook is registered.
64/// The six hook names git itself invokes. Everything else is a `Check`.
65pub const ENTRYPOINTS: &[(&str, HookFn)] = &[
66    ("pre-commit", dispatch::pre_commit),
67    ("pre-push", dispatch::pre_push),
68    // The message hooks are pure convention — a subject shape and a decoration
69    // — so under `amont.conventions declared` they quietly stand down in a
70    // repository that never subscribed. Quietly: the pre-commit stage has
71    // already said, once, that the conventions are held back here; a second
72    // and third line every commit would be the noise that gets amont
73    // uninstalled. post-commit stays: it records, never opines.
74    ("commit-msg", |ctx| {
75        if !dispatch::conventions_apply(ctx.settings, ctx.manifest) {
76            return Verdict::Proceed;
77        }
78        hooks::commit_msg::run(ctx.settings, ctx.args)
79    }),
80    ("prepare-commit-msg", |ctx| {
81        if !dispatch::conventions_apply(ctx.settings, ctx.manifest) {
82            return Verdict::Proceed;
83        }
84        hooks::prepare_commit_msg::run(ctx.args)
85    }),
86    ("post-commit", |ctx| {
87        hooks::post_commit::run(ctx.settings, ctx)
88    }),
89    // A rebase rewrote the branch: its stamps no longer vouch for it, so
90    // rehearse again. Like post-commit it records, never opines.
91    ("post-rewrite", |ctx| {
92        hooks::post_rewrite::run(ctx.settings, ctx)
93    }),
94];
95
96/// Every check, in the order its stage runs them.
97///
98/// ONE declaration each: name, stage, scope and function together. This
99/// replaced `REGISTRY` plus `PRE_COMMIT_CHECKS` plus `PRE_PUSH_CHECKS` plus the
100/// fleet crate's `LANGUAGES` — four tables keyed by the same string, kept in
101/// step by reconciliation tests that are now unnecessary rather than passing.
102///
103/// pre-push order is the cost order: refuse a forbidden push before validating
104/// a name, and validate everything structural before paying for a test suite.
105/// Operations during which a content check cannot say anything useful: half the
106/// tree is somebody else's work, and you cannot fix it from inside the
107/// operation anyway.
108///
109/// NOT applied to `merge-conflict` or `ban-terms`. Those are exactly the checks
110/// you want during a resolution commit — leaving a conflict marker in the
111/// commit that RESOLVES a merge is the bug, and importing a banned term from
112/// the other branch is the other one. The old behaviour skipped the whole
113/// pre-commit stage during a cherry-pick, which silenced both.
114const MID_OPERATION: &[GitState] = &[
115    GitState::Merge,
116    GitState::Rebase,
117    GitState::CherryPick,
118    GitState::Revert,
119];
120
121pub const CHECKS: &[Builtin] = &[
122    // ---- pre-commit ----
123    // The generated guidance block, checked against the binary that would
124    // generate it now. Not during a rebase: stepping through old commits
125    // would warn on every one of them about a file the step did not touch.
126    Builtin {
127        name: "pre-commit-agents-md",
128        stage: Stage::PreCommit,
129        scope: Scope::ALWAYS.not_during(MID_OPERATION),
130        severity: Severity::Warn,
131        fix: Fix::Rewrite,
132        reach: Reach::Convention,
133        run: |ctx| hooks::agents_md_drift::run(ctx.settings),
134    },
135    Builtin {
136        name: "pre-commit-argo-lint",
137        stage: Stage::PreCommit,
138        scope: Scope::new(
139            hooks::k8s::EXTS,
140            &["kustomization.yaml", "kustomization.yml"],
141        )
142        .not_during(MID_OPERATION),
143        severity: Severity::Block,
144        fix: Fix::None,
145        reach: Reach::Convention,
146        run: |ctx| hooks::k8s::argo_lint(ctx.settings, ctx.args),
147    },
148    Builtin {
149        name: "pre-commit-ban-terms",
150        stage: Stage::PreCommit,
151        scope: Scope::files(hooks::ban_terms::EXTS),
152        severity: Severity::Block,
153        fix: Fix::None,
154        reach: Reach::Safety,
155        run: |ctx| hooks::ban_terms::run(ctx.settings, ctx.name, ctx.args),
156    },
157    // The push-time contract, said at the first commit — when renaming the
158    // branch costs one command and zero rework. Same short name as the
159    // pre-push check on purpose: `hook.skip branch-pattern` silences the
160    // rule, not one of its two voices.
161    Builtin {
162        name: "pre-commit-branch-pattern",
163        stage: Stage::PreCommit,
164        scope: Scope::ALWAYS,
165        severity: Severity::Warn,
166        fix: Fix::None,
167        reach: Reach::Convention,
168        run: |ctx| hooks::branch_pattern::early(ctx.settings),
169    },
170    // Same device for the other push-time refusal: a commit landing on
171    // `main` will be refused at push, and the commit is the moment moving
172    // it costs one command. Same short name as the pre-push check, so
173    // `hook.skip branch-protect` silences the rule, not one voice.
174    Builtin {
175        name: "pre-commit-branch-protect",
176        stage: Stage::PreCommit,
177        scope: Scope::ALWAYS,
178        severity: Severity::Warn,
179        fix: Fix::None,
180        reach: Reach::Convention,
181        run: |ctx| hooks::branch_protect::early(ctx.settings),
182    },
183    Builtin {
184        name: "pre-commit-cargo-fmt",
185        stage: Stage::PreCommit,
186        scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"]).not_during(MID_OPERATION),
187        severity: Severity::Block,
188        fix: Fix::Rewrite,
189        reach: Reach::Convention,
190        run: |ctx| hooks::rust_tools::fmt(ctx.settings, ctx.args),
191    },
192    Builtin {
193        name: "pre-commit-clippy",
194        stage: Stage::PreCommit,
195        // holds-until: a commit that changes only a manifest or a toolchain
196        // pin needs linting. Clippy consumes `RUST_PATHS` but declares `.rs`,
197        // so such a commit skips it here; the push suite (`RUST_PATHS`) still
198        // builds it. Widen this scope when that gap is shown to matter.
199        scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"]).not_during(MID_OPERATION),
200        severity: Severity::Block,
201        fix: Fix::None,
202        reach: Reach::Convention,
203        run: |ctx| hooks::rust_tools::clippy(ctx.settings, ctx.args),
204    },
205    Builtin {
206        name: "pre-commit-go-vet",
207        stage: Stage::PreCommit,
208        scope: Scope::new(hooks::go_tools::EXTS, &["go.mod"]).not_during(MID_OPERATION),
209        severity: Severity::Block,
210        fix: Fix::None,
211        reach: Reach::Convention,
212        run: |ctx| hooks::go_tools::vet(ctx.settings, ctx.args),
213    },
214    Builtin {
215        name: "pre-commit-gofmt",
216        stage: Stage::PreCommit,
217        scope: Scope::new(hooks::go_tools::EXTS, &["go.mod"]).not_during(MID_OPERATION),
218        severity: Severity::Block,
219        fix: Fix::Rewrite,
220        reach: Reach::Convention,
221        run: |ctx| hooks::go_tools::fmt(ctx.settings, ctx.args),
222    },
223    Builtin {
224        name: "pre-commit-kube-linter",
225        stage: Stage::PreCommit,
226        scope: Scope::new(
227            hooks::k8s::EXTS,
228            &[".kube-linter*.yaml", ".kube-linter*.yml"],
229        )
230        .not_during(MID_OPERATION),
231        severity: Severity::Block,
232        fix: Fix::None,
233        reach: Reach::Convention,
234        run: |ctx| hooks::k8s::kube_linter(ctx.settings, ctx.args),
235    },
236    Builtin {
237        name: "pre-commit-kubeconform",
238        stage: Stage::PreCommit,
239        scope: Scope::new(
240            hooks::k8s::EXTS,
241            &["kustomization.yaml", "kustomization.yml"],
242        )
243        .not_during(MID_OPERATION),
244        severity: Severity::Block,
245        fix: Fix::None,
246        reach: Reach::Convention,
247        run: |ctx| hooks::k8s::kubeconform(ctx.settings, ctx.args),
248    },
249    Builtin {
250        name: "pre-commit-large-files",
251        stage: Stage::PreCommit,
252        scope: Scope::ALWAYS,
253        severity: Severity::Block,
254        fix: Fix::None,
255        reach: Reach::Safety,
256        run: |ctx| hooks::large_files::staged(ctx.settings),
257    },
258    Builtin {
259        name: "pre-commit-lint-js",
260        stage: Stage::PreCommit,
261        scope: Scope::new(hooks::lint_js::EXTS, &["package.json"]).not_during(MID_OPERATION),
262        severity: Severity::Block,
263        fix: Fix::None,
264        reach: Reach::Convention,
265        run: |ctx| hooks::lint_js::run(ctx.settings, ctx.args),
266    },
267    Builtin {
268        name: "pre-commit-lint-json-yaml",
269        stage: Stage::PreCommit,
270        scope: Scope::files(hooks::lint_json_yaml::EXTS).not_during(MID_OPERATION),
271        severity: Severity::Block,
272        fix: Fix::None,
273        reach: Reach::Convention,
274        run: |ctx| hooks::lint_json_yaml::run(ctx.settings, ctx.args),
275    },
276    // A commit that changes amont.conf would otherwise go through with every
277    // check that file declares standing down as "could not run" — trust is
278    // keyed on content, and the author has not re-trusted their own edit yet.
279    // Not mid-operation: a manifest arriving from another branch is the
280    // pulled case, which stays a gap by design (docs/trust.md).
281    Builtin {
282        name: "pre-commit-manifest-trust",
283        stage: Stage::PreCommit,
284        scope: Scope::named(&[crate::manifest::MANIFEST]).not_during(MID_OPERATION),
285        severity: Severity::Block,
286        fix: Fix::None,
287        reach: Reach::Safety,
288        run: |ctx| hooks::manifest_trust::run(ctx.settings, ctx.manifest),
289    },
290    Builtin {
291        name: "pre-commit-merge-conflict",
292        stage: Stage::PreCommit,
293        scope: Scope::ALWAYS,
294        severity: Severity::Block,
295        fix: Fix::None,
296        reach: Reach::Safety,
297        run: |ctx| hooks::merge_conflict::run(ctx.settings, ctx.name, ctx.args),
298    },
299    Builtin {
300        name: "pre-commit-package-lock",
301        stage: Stage::PreCommit,
302        scope: Scope::new(&[], &["package.json"]),
303        severity: Severity::Block,
304        fix: Fix::None,
305        reach: Reach::Convention,
306        run: |ctx| hooks::package_lock::run(ctx.settings, ctx.args),
307    },
308    Builtin {
309        name: "pre-commit-prettier",
310        stage: Stage::PreCommit,
311        scope: Scope::new(
312            &[],
313            // The same markers `hooks::prettier::has_config` reads, so
314            // `amont list` and the gate agree (#307).
315            &[
316                ".prettierrc",
317                ".prettierrc.json",
318                ".prettierrc.yml",
319                ".prettierrc.yaml",
320                ".prettierrc.js",
321                ".prettierrc.cjs",
322                ".prettierrc.mjs",
323                ".prettierrc.toml",
324                "prettier.config.js",
325                "prettier.config.mjs",
326                "prettier.config.cjs",
327            ],
328        )
329        .not_during(MID_OPERATION),
330        severity: Severity::Block,
331        fix: Fix::Rewrite,
332        reach: Reach::Convention,
333        run: |ctx| hooks::prettier::run(ctx.settings, ctx.args),
334    },
335    Builtin {
336        name: "pre-commit-pyright",
337        stage: Stage::PreCommit,
338        scope: Scope::new(
339            hooks::python_tools::EXTS,
340            &[
341                "pyrightconfig.json",
342                "pyrightconfig.jsonc",
343                "pyproject.toml",
344            ],
345        )
346        .not_during(MID_OPERATION),
347        severity: Severity::Block,
348        fix: Fix::None,
349        reach: Reach::Convention,
350        run: |ctx| hooks::python_tools::pyright(ctx.settings, ctx.args),
351    },
352    Builtin {
353        name: "pre-commit-ruff",
354        stage: Stage::PreCommit,
355        scope: Scope::new(
356            hooks::python_tools::EXTS,
357            &["ruff.toml", ".ruff.toml", "pyproject.toml"],
358        )
359        .not_during(MID_OPERATION),
360        severity: Severity::Block,
361        fix: Fix::Rewrite,
362        reach: Reach::Convention,
363        run: |ctx| hooks::python_tools::ruff(ctx.settings, ctx.args),
364    },
365    // A staged credential is a ten-second fix; a pushed one is an
366    // incident. Both halves of that sentence are checks — see
367    // `hooks::secrets` for why the push half exists at all.
368    Builtin {
369        name: "pre-commit-secrets",
370        stage: Stage::PreCommit,
371        scope: Scope::ALWAYS,
372        severity: Severity::Block,
373        fix: Fix::None,
374        reach: Reach::Safety,
375        run: |ctx| hooks::secrets::staged(ctx.settings),
376    },
377    // A CI step skipped on `tree-<name>` must run exactly that gate's
378    // command (ADR-0024). Text against text — it executes nothing, so it
379    // needs no trust. Blocking: a drifted step is a skip nobody proved. A
380    // step skipped on a BUILT-IN test gate is compared too, and its drift
381    // only warns (#288): the check reports `Warned` for it.
382    Builtin {
383        name: "pre-commit-tree-parity",
384        stage: Stage::PreCommit,
385        scope: Scope {
386            files: hooks::k8s::EXTS,
387            names: &[crate::manifest::MANIFEST],
388            dirs: &[],
389            opt_in: &[crate::manifest::MANIFEST],
390            not_during: MID_OPERATION,
391        },
392        severity: Severity::Block,
393        fix: Fix::None,
394        reach: Reach::Convention,
395        run: |ctx| hooks::tree_parity::run(ctx.settings),
396    },
397    Builtin {
398        name: "pre-commit-usual-name",
399        stage: Stage::PreCommit,
400        scope: Scope::ALWAYS,
401        severity: Severity::Block,
402        fix: Fix::None,
403        reach: Reach::Convention,
404        run: |ctx| hooks::usual_name::run(ctx.args),
405    },
406    Builtin {
407        name: "pre-commit-shellcheck",
408        stage: Stage::PreCommit,
409        // No opt-in: shellcheck's defaults are the reason to run it, unlike
410        // `yamllint`, whose stock rules gate on a repo-local config.
411        scope: Scope::files(hooks::shellcheck::EXTS).not_during(MID_OPERATION),
412        severity: Severity::Block,
413        fix: Fix::None,
414        reach: Reach::Convention,
415        run: |ctx| hooks::shellcheck::run(ctx.settings, ctx.args),
416    },
417    Builtin {
418        name: "pre-commit-hadolint",
419        stage: Stage::PreCommit,
420        // A `Dockerfile` in the diff already says everything a marker would.
421        // `names`, not `files`: an extension list cannot say "Dockerfile"
422        // without also matching `my-Dockerfile`.
423        scope: Scope::named(hooks::hadolint::NAMES).not_during(MID_OPERATION),
424        severity: Severity::Block,
425        fix: Fix::None,
426        reach: Reach::Convention,
427        run: |ctx| hooks::hadolint::run(ctx.settings, ctx.args),
428    },
429    Builtin {
430        name: "pre-commit-helm-lint",
431        stage: Stage::PreCommit,
432        // `Chart.yaml` is the marker that says this repository has charts at
433        // all — the same shape `kubeconform` uses for `kustomization.yaml`.
434        scope: Scope::new(hooks::helm::EXTS, hooks::helm::MARKERS).not_during(MID_OPERATION),
435        severity: Severity::Block,
436        fix: Fix::None,
437        reach: Reach::Convention,
438        run: |ctx| hooks::helm::run(ctx.settings, ctx.args),
439    },
440    Builtin {
441        name: "pre-commit-yamllint",
442        stage: Stage::PreCommit,
443        scope: Scope::new(
444            hooks::yamllint::EXTS,
445            &[".yamllint.yaml", ".yamllint.yml", ".yamllint"],
446        )
447        .not_during(MID_OPERATION),
448        severity: Severity::Block,
449        fix: Fix::None,
450        reach: Reach::Convention,
451        run: |ctx| hooks::yamllint::run(ctx.settings, ctx.args),
452    },
453    // ---- pre-push, cheapest and most decisive first ----
454    Builtin {
455        name: "pre-push-branch-protect",
456        stage: Stage::PrePush,
457        scope: Scope::ALWAYS,
458        severity: Severity::Block,
459        fix: Fix::None,
460        reach: Reach::Convention,
461        run: |ctx| hooks::branch_protect::run(ctx.settings, ctx.push.get()),
462    },
463    Builtin {
464        name: "pre-push-branch-pattern",
465        stage: Stage::PrePush,
466        scope: Scope::ALWAYS,
467        severity: Severity::Block,
468        fix: Fix::None,
469        reach: Reach::Convention,
470        run: |ctx| hooks::branch_pattern::run(ctx.settings, ctx.push.get(), ctx.args),
471    },
472    Builtin {
473        name: "pre-push-secrets",
474        stage: Stage::PrePush,
475        scope: Scope::ALWAYS,
476        severity: Severity::Block,
477        fix: Fix::None,
478        reach: Reach::Safety,
479        run: |ctx| hooks::secrets::pushed(ctx.settings, ctx.push.get()),
480    },
481    Builtin {
482        name: "pre-push-pull-rebase",
483        stage: Stage::PrePush,
484        scope: Scope::ALWAYS.not_during(&[GitState::Rebase, GitState::Merge]),
485        severity: Severity::Block,
486        fix: Fix::None,
487        reach: Reach::Convention,
488        run: |ctx| hooks::pull_rebase::run(ctx.settings, ctx.push.get(), ctx.args),
489    },
490    // The four dependency audits sit between the structural checks and the
491    // test suites: network-bound but seconds, where a suite is minutes —
492    // and when a v* tag is in the push, failing here saves the suite's
493    // whole cost. Each opts in by the LOCKFILE its tool audits: an audit
494    // without a resolved tree audits a guess. On a branch push they only
495    // warn; the blocking case is the release tag — see `hooks::audit`.
496    Builtin {
497        name: "pre-push-audit-go",
498        stage: Stage::PrePush,
499        scope: Scope::new(&[], &["go.sum"]),
500        severity: Severity::Block,
501        fix: Fix::None,
502        reach: Reach::Convention,
503        run: |ctx| hooks::audit::go(ctx),
504    },
505    // `pnpm-lock.yaml` too: a pnpm workspace has no package-lock.json, and
506    // without it here the dispatcher's opt-in gate silenced the audit for
507    // every pnpm repository — `hooks::audit::js` runs `pnpm audit` there.
508    Builtin {
509        name: "pre-push-audit-js",
510        stage: Stage::PrePush,
511        scope: Scope::new(&[], &["package-lock.json", "pnpm-lock.yaml"]),
512        severity: Severity::Block,
513        fix: Fix::None,
514        reach: Reach::Convention,
515        run: |ctx| hooks::audit::js(ctx),
516    },
517    // `pyproject.toml` too: a uv/PEP-621 project has no requirements.txt
518    // and the runner audits its virtualenv instead — the registry must
519    // say so, or the dispatcher's opt-in gate would silence the audit
520    // exactly where `hooks::audit::python` learned to work.
521    Builtin {
522        name: "pre-push-audit-python",
523        stage: Stage::PrePush,
524        scope: Scope::new(&[], &["requirements.txt", "pyproject.toml"]),
525        severity: Severity::Block,
526        fix: Fix::None,
527        reach: Reach::Convention,
528        run: |ctx| hooks::audit::python(ctx),
529    },
530    Builtin {
531        name: "pre-push-audit-rust",
532        stage: Stage::PrePush,
533        scope: Scope::new(&[], &["Cargo.lock"]),
534        severity: Severity::Block,
535        fix: Fix::None,
536        reach: Reach::Convention,
537        run: |ctx| hooks::audit::rust(ctx),
538    },
539    Builtin {
540        name: "pre-push-run-tests-js",
541        stage: Stage::PrePush,
542        scope: Scope::new(hooks::run_tests::JS_EXTS, &["package.json"])
543            .not_during(&[GitState::Bisect, GitState::Rebase]),
544        severity: Severity::Block,
545        fix: Fix::None,
546        reach: Reach::Convention,
547        run: |ctx| {
548            hooks::run_tests::run(
549                ctx.settings,
550                ctx.push.get(),
551                &ctx.manifest.externals,
552                ctx.name,
553            )
554        },
555    },
556    Builtin {
557        name: "pre-push-cargo-test",
558        stage: Stage::PrePush,
559        scope: Scope::new(hooks::rust_tools::RUST_PATHS, &["Cargo.toml"])
560            .not_during(&[GitState::Bisect, GitState::Rebase]),
561        severity: Severity::Block,
562        fix: Fix::None,
563        reach: Reach::Convention,
564        run: |ctx| hooks::rust_tools::test(ctx.settings, ctx.push.get(), ctx.name),
565    },
566    Builtin {
567        name: "pre-push-go-test",
568        stage: Stage::PrePush,
569        scope: Scope::new(hooks::go_tools::GO_PATHS, &["go.mod"])
570            .not_during(&[GitState::Bisect, GitState::Rebase]),
571        severity: Severity::Block,
572        fix: Fix::None,
573        reach: Reach::Convention,
574        run: |ctx| hooks::go_tools::test(ctx.settings, ctx.push.get(), ctx.name),
575    },
576    Builtin {
577        name: "pre-push-pytest",
578        stage: Stage::PrePush,
579        scope: Scope::new(hooks::python_tools::EXTS, &["pytest.ini", "conftest.py"])
580            .not_during(&[GitState::Bisect, GitState::Rebase]),
581        severity: Severity::Block,
582        fix: Fix::None,
583        reach: Reach::Convention,
584        run: |ctx| hooks::python_tools::pytest(ctx.settings, ctx.push.get(), ctx.name),
585    },
586];
587
588/// A check's severity, after any per-repository override.
589///
590/// `git config amont.severity.<check> warn` downgrades a blocking check to a
591/// warning. Unlike `hook.skip` it keeps the signal: the check still runs and
592/// still reports, it just stops failing the commit.
593pub fn severity_of(settings: &crate::config::Settings, check: &dyn Check) -> Severity {
594    effective_override(settings, None, check.name()).unwrap_or_else(|| check.severity())
595}
596
597/// The config key a severity override lives under.
598pub fn severity_key(check: &str) -> String {
599    format!("amont.severity.{check}")
600}
601
602/// Every severity override visible here, resolved the way `--get` resolves it.
603///
604/// ONE subprocess for the whole stage, and — more importantly — a VALUE. The
605/// dispatcher used to call `severity_of` inside the loop that classifies
606/// outcomes, which put a `git` spawn in the middle of a fold and made the fold
607/// impossible to test without a repository.
608///
609/// `--get-regexp` emits entries in precedence order, so folding with overwrite
610/// lands on the same answer `--get` gives. That equivalence is not assumed:
611/// `the_batch_agrees_with_the_authority` pins it against `effective_override`.
612#[derive(Debug, Default, Clone)]
613pub struct Overrides(std::collections::BTreeMap<String, (Severity, Source)>);
614
615/// Where an override came from — machine config or the repository's
616/// committed policy. `amont list` reports it; nothing on the commit path
617/// consults it.
618#[derive(Debug, Clone, Copy, PartialEq, Eq)]
619pub enum Source {
620    Config,
621    Policy,
622}
623
624impl Source {
625    pub fn as_str(self) -> &'static str {
626        match self {
627            Source::Config => "config",
628            Source::Policy => "policy",
629        }
630    }
631}
632
633impl Overrides {
634    /// Machine config AND the installed repo policy, folded on the
635    /// specificity ladder: system < global < POLICY < local < worktree <
636    /// command. `--show-scope` labels each config line; on a git too old to
637    /// know the flag (exit 129 → `None`) this degrades, deliberately, to
638    /// "ALL git config beats policy" — the fail-safe direction, because the
639    /// alternative was an EMPTY override set silently discarding both.
640    pub fn read(settings: &crate::config::Settings) -> Overrides {
641        let policy = settings.policy();
642        match crate::git::stdout(&[
643            "config",
644            "--show-scope",
645            "--get-regexp",
646            r"^amont\.severity\.",
647        ]) {
648            Some(scoped) => Overrides::from_scoped(&scoped, policy),
649            // `--get-regexp` with no matches ALSO exits non-zero, so `None`
650            // here can mean "no keys" as well as "old git" — both fold the
651            // same way: nothing below, policy, nothing above.
652            None => Overrides::from_plain_with_policy_below(
653                crate::git::stdout(&["config", "--get-regexp", r"^amont\.severity\."]),
654                policy,
655            ),
656        }
657    }
658
659    /// Fold `--show-scope` output around the installed policy. Scope words
660    /// `system`/`global` fold BELOW policy; everything else — `local`,
661    /// `worktree`, `command`, and any word a future git invents — folds
662    /// ABOVE, because misreading a local as below would let a file pulled
663    /// from a remote silently override a person's explicit setting on their
664    /// own machine, and that is the worse direction to fail in.
665    pub fn from_scoped(scoped: &str, policy: &crate::policy::Policy) -> Overrides {
666        let mut below = String::new();
667        let mut above = String::new();
668        for line in scoped.lines() {
669            let Some((scope, rest)) = line.split_once('\t') else {
670                continue;
671            };
672            match scope {
673                "system" | "global" => {
674                    below.push_str(rest);
675                    below.push('\n');
676                }
677                _ => {
678                    above.push_str(rest);
679                    above.push('\n');
680                }
681            }
682        }
683        let mut o = Overrides::default();
684        o.fold_plain(&below, Source::Config);
685        o.fold_policy(policy);
686        o.fold_plain(&above, Source::Config);
687        o
688    }
689
690    /// The DEGRADED fold — policy below every config scope, i.e. all git
691    /// config beats policy — for a git that cannot label scopes. `pub`
692    /// because the fleet's severity column must degrade the same way the
693    /// dispatcher does, not invent a third opinion.
694    pub fn from_plain_with_policy_below(
695        plain: Option<String>,
696        policy: &crate::policy::Policy,
697    ) -> Overrides {
698        let mut o = Overrides::default();
699        o.fold_policy(policy);
700        o.fold_plain(plain.as_deref().unwrap_or_default(), Source::Config);
701        o
702    }
703
704    /// Policy entries are insert-only: a bad severity word was refused at
705    /// parse time and never reaches here.
706    fn fold_policy(&mut self, policy: &crate::policy::Policy) {
707        for (target, severity) in &policy.severities {
708            self.0.insert(target.clone(), (*severity, Source::Policy));
709        }
710    }
711
712    /// The original fold: later entries overwrite, an unrecognised value
713    /// CLEARS the key rather than shadowing a valid earlier one. Kept as the
714    /// single implementation both `from_config` and the ladder halves use.
715    fn fold_plain(&mut self, text: &str, source: Source) {
716        for line in text.lines() {
717            let Some((key, value)) = line.split_once(' ') else {
718                continue;
719            };
720            let Some(check) = key.strip_prefix("amont.severity.") else {
721                continue;
722            };
723            match Severity::parse(value.trim()) {
724                Some(sev) => {
725                    self.0.insert(check.to_string(), (sev, source));
726                }
727                None => {
728                    self.0.remove(check);
729                }
730            }
731        }
732    }
733
734    /// Built from `--get-regexp`-shaped text (`amont.severity.<check>
735    /// <value>` per line, in git's own precedence order — system, then
736    /// global, then local, then includes). `pub` so a reader that has
737    /// already fetched those lines for its own reasons (the fleet dashboard
738    /// needs the origin of each, which `Overrides` does not track) can still
739    /// ask this — the one place that must not get precedence wrong — rather
740    /// than re-deriving it from the lines by hand.
741    pub fn from_config(out: Option<String>) -> Overrides {
742        let mut o = Overrides::default();
743        o.fold_plain(out.as_deref().unwrap_or_default(), Source::Config);
744        o
745    }
746
747    /// The configured key that applies to `check`, and what it says.
748    ///
749    /// Several keys can name one check — `pre-commit` and `clippy` and
750    /// `pre-commit-clippy` all reach `pre-commit-clippy`. The most specific
751    /// wins, which is the rule anybody would guess and the only one that lets
752    /// you downgrade a whole trigger and then exempt one check from it.
753    pub fn applied_to(&self, check: &str) -> Option<(&str, Severity)> {
754        self.applied_with_source(check)
755            .map(|(pattern, severity, _)| (pattern, severity))
756    }
757
758    /// As `applied_to`, keeping WHERE the winning key came from — the one
759    /// reader (`amont list`) that reports provenance asks here rather than
760    /// re-deriving the answer a second way.
761    pub fn applied_with_source(&self, check: &str) -> Option<(&str, Severity, Source)> {
762        self.0
763            .iter()
764            .filter_map(|(pattern, (severity, source))| {
765                crate::names_check(check, pattern)
766                    .map(|m| (m, pattern.as_str(), *severity, *source))
767            })
768            .max_by_key(|(m, _, _, _)| *m)
769            .map(|(_, pattern, severity, source)| (pattern, severity, source))
770    }
771
772    /// The severity to apply to `check`, override or declared.
773    pub fn of(&self, check: &dyn Check) -> Severity {
774        self.applied_to(check.name())
775            .map(|(_, severity)| severity)
776            .unwrap_or_else(|| check.severity())
777    }
778}
779
780#[cfg(test)]
781mod precedence {
782    use super::{Overrides, Severity};
783
784    fn overrides(lines: &[&str]) -> Overrides {
785        let text = lines
786            .iter()
787            .map(|l| format!("amont.severity.{l}\n"))
788            .collect::<String>();
789        Overrides::from_config(Some(text))
790    }
791
792    /// The whole reason triggers and short names are allowed as keys: downgrade
793    /// a trigger wholesale, then say something different about one check. If the
794    /// broader key won instead, the exemption would be unwritable.
795    #[test]
796    fn the_more_specific_key_wins() {
797        let both = overrides(&["pre-commit warn", "pre-commit-clippy block"]);
798        assert_eq!(
799            both.applied_to("pre-commit-clippy"),
800            Some(("pre-commit-clippy", Severity::Block)),
801            "a full id beats its trigger"
802        );
803        assert_eq!(
804            both.applied_to("pre-commit-shellcheck"),
805            Some(("pre-commit", Severity::Warn)),
806            "and the trigger still governs every check it did not exempt"
807        );
808    }
809
810    /// Full id > short name > trigger, all three at once, so the ordering is
811    /// pinned end to end rather than one pair at a time.
812    #[test]
813    fn the_three_ways_to_name_a_check_are_ranked() {
814        let all = overrides(&["pre-commit warn", "clippy block", "pre-commit-clippy warn"]);
815        assert_eq!(
816            all.applied_to("pre-commit-clippy"),
817            Some(("pre-commit-clippy", Severity::Warn))
818        );
819
820        let no_full = overrides(&["pre-commit warn", "clippy block"]);
821        assert_eq!(
822            no_full.applied_to("pre-commit-clippy"),
823            Some(("clippy", Severity::Block)),
824            "a short name beats a trigger"
825        );
826    }
827
828    /// A key naming nothing must not become the answer by being the only one
829    /// there — that is how a repo believes it downgraded a check it never named.
830    #[test]
831    fn a_key_that_names_no_check_applies_to_nothing() {
832        let typo = overrides(&["clipy warn", "e warn", " warn"]);
833        assert_eq!(typo.applied_to("pre-commit-clippy"), None);
834    }
835}
836
837/// The override git would actually apply for `check`, or `None` if there is
838/// none (or the value is not one this understands).
839///
840/// `--get`, NOT `--get-regexp`: git returns the LAST value, so a local `block`
841/// beats a global `warn`. A reader that listed every entry instead and treated
842/// each as authoritative would report a downgrade that the dispatcher does not
843/// apply — which is exactly what the dashboard used to do.
844///
845/// `repo` is `None` for the current directory, which is where a hook runs.
846pub fn effective_override(
847    settings: &crate::config::Settings,
848    repo: Option<&Path>,
849    check: &str,
850) -> Option<Severity> {
851    overrides_in(settings, repo)
852        .applied_to(check)
853        .map(|(_, s)| s)
854}
855
856/// Which configured KEY applies to `check` here, if any.
857///
858/// The dashboard needs the key rather than the value: with three ways to name a
859/// check, "which of these lines is the one doing something" is the question a
860/// reader actually has.
861pub fn effective_key(
862    settings: &crate::config::Settings,
863    repo: Option<&Path>,
864    check: &str,
865) -> Option<String> {
866    overrides_in(settings, repo)
867        .applied_to(check)
868        .map(|(pattern, _)| pattern.to_string())
869}
870
871fn overrides_in(settings: &crate::config::Settings, repo: Option<&Path>) -> Overrides {
872    match repo {
873        // The current repository: same fold the dispatcher uses, policy
874        // included — `amont run <check>` resolves through here and must not
875        // disagree with the stage that would have run it.
876        None => Overrides::read(settings),
877        // Somebody ELSE's repository (the fleet's per-repo question): never
878        // this process's policy — the store belongs to the repo the process
879        // is standing in, and a scanner walks many.
880        Some(dir) => Overrides::from_config(crate::git::stdout_in(
881            dir,
882            &["config", "--get-regexp", r"^amont\.severity\."],
883        )),
884    }
885}
886
887/// Built-in checks for one stage, in declared order.
888pub fn stage_checks(stage: Stage) -> impl Iterator<Item = &'static Builtin> {
889    CHECKS.iter().filter(move |check| check.stage == stage)
890}
891
892/// The scope of the built-in pre-push gate that a commit-time declaration
893/// named `short` stands in for: the gate of that short name (`cargo-test`),
894/// or, for a script the npm push gate runs (`typecheck`, `test`), that gate's.
895/// `None` when no built-in gate is its twin. A declared pre-push twin is found
896/// by the manifest itself (`manifest::attach_twin_scopes`). Returns the gate's
897/// id with its scope, so a commit can say which gate reads the files it tests.
898pub fn push_twin_scope(short: &str) -> Option<(&'static str, Scope)> {
899    let mut push = stage_checks(Stage::PrePush);
900    let twin = push
901        .find(|check| check.pairing_name() == short)
902        .or_else(|| {
903            hooks::run_tests::is_gate_script(short)
904                .then(|| stage_checks(Stage::PrePush).find(|c| c.name() == "pre-push-run-tests-js"))
905                .flatten()
906        });
907    twin.map(|check| (check.name(), check.scope()))
908}
909
910/// Every check for one stage — built-ins first, then whatever this repository
911/// declares in `amont.conf`.
912///
913/// The order is not negotiable and not configurable. A third-party command must
914/// not be able to delay `pre-push-branch-protect`, and appending is the only
915/// arrangement in which it cannot.
916pub fn all_stage_checks<'a>(
917    stage: Stage,
918    manifest: &'a crate::manifest::Manifest,
919) -> Vec<&'a dyn Check> {
920    let mut out: Vec<&'a dyn Check> = stage_checks(stage)
921        .map(|check| check as &dyn Check)
922        .collect();
923    out.extend(
924        manifest
925            .externals
926            .iter()
927            .filter(|external| external.stage == stage)
928            .map(|external| external as &dyn Check),
929    );
930    out
931}
932
933pub fn lookup(name: &str, manifest: &crate::manifest::Manifest) -> Option<HookFn> {
934    if let Some((_, f)) = ENTRYPOINTS.iter().find(|(n, _)| *n == name) {
935        return Some(*f);
936    }
937    // A check invoked directly by name — how the tests drive individual checks,
938    // and how `amont <check>` works from a shell. Its Outcome collapses to an
939    // exit code here, honouring severity, so a `warn` check invoked directly
940    // reports without failing exactly as it does inside a dispatcher. The
941    // closure re-resolves through the Ctx it is handed — a plain fn pointer
942    // captures nothing, and the manifest travels ON the Ctx.
943    if CHECKS.iter().any(|check| check.name == name)
944        || manifest
945            .externals
946            .iter()
947            .any(|external| external.id == name)
948    {
949        return Some(|ctx: &Ctx| {
950            let check = one_named(ctx.name, ctx.manifest).expect("checked above");
951            // One check run by name queues for a host slot like it would
952            // inside its stage (ADR-0009).
953            let _slot = crate::host_slots::enter_check(check.name(), check.weight());
954            Verdict::blocking(matches!(
955                (check.run(ctx), severity_of(ctx.settings, check)),
956                (Outcome::Failed, Severity::Block)
957            ))
958        });
959    }
960    None
961}
962
963/// One check by name, whichever kind it is. Built-ins are searched first, which
964/// costs nothing because `manifest::parse` refuses a name a built-in already
965/// holds — the two guards together mean neither kind can shadow the other.
966pub fn one_named<'a>(name: &str, manifest: &'a crate::manifest::Manifest) -> Option<&'a dyn Check> {
967    if let Some(builtin) = CHECKS.iter().find(|check| check.name == name) {
968        return Some(builtin);
969    }
970    manifest
971        .externals
972        .iter()
973        .find(|external| external.id == name)
974        .map(|external| external as &dyn Check)
975}
976
977#[cfg(test)]
978mod tests {
979    use super::{lookup, Overrides, Reach, Severity, Stage, CHECKS, ENTRYPOINTS};
980    use crate::names::BIN;
981    use std::collections::BTreeSet;
982
983    /// The batch reader must land on the same answer as the authority.
984    ///
985    /// `Overrides` folds `--get-regexp` output with overwrite; `effective_override`
986    /// asks `--get`. They agree only because git emits entries in precedence
987    /// order — an assumption, so it is asserted against real git rather than
988    /// trusted.
989    #[test]
990    fn the_batch_agrees_with_the_authority() {
991        let d = std::env::temp_dir().join(format!("ov-{}", std::process::id()));
992        let _ = std::fs::remove_dir_all(&d);
993        std::fs::create_dir_all(&d).unwrap();
994        let git = |args: &[&str]| {
995            std::process::Command::new("git")
996                .args(args)
997                .current_dir(&d)
998                .output()
999                .expect("git");
1000        };
1001        git(&["init", "-q", "--template=", "."]);
1002        let key = "amont.severity.pre-commit-merge-conflict";
1003        git(&["config", "--add", key, "warn"]);
1004        git(&["config", "--add", key, "block"]);
1005
1006        let raw = std::process::Command::new("git")
1007            .args(["config", "--get-regexp", r"^amont\.severity\."])
1008            .current_dir(&d)
1009            .output()
1010            .expect("git");
1011        let batch = Overrides::from_config(Some(
1012            String::from_utf8_lossy(&raw.stdout).trim().to_string(),
1013        ));
1014        let authority =
1015            crate::git::stdout_in(&d, &["config", "--get", key]).and_then(|v| Severity::parse(&v));
1016        let _ = std::fs::remove_dir_all(&d);
1017
1018        assert_eq!(
1019            authority,
1020            Some(Severity::Block),
1021            "git applies the last entry"
1022        );
1023        assert_eq!(
1024            batch.0.get("pre-commit-merge-conflict").map(|(s, _)| *s),
1025            authority,
1026            "the batch reader disagreed with `--get`"
1027        );
1028    }
1029
1030    /// An unrecognised value is not an override, and must not shadow a valid
1031    /// earlier one either — a typo would otherwise silently restore the
1032    /// declared severity in a way nobody could see.
1033    #[test]
1034    fn an_unrecognised_value_clears_rather_than_overrides() {
1035        let o = Overrides::from_config(Some(
1036            "amont.severity.a warn\namont.severity.a advisory\namont.severity.b warn".to_string(),
1037        ));
1038        assert_eq!(o.0.get("a"), None, "a typo must not leave `warn` standing");
1039        assert_eq!(o.0.get("b").map(|(s, _)| *s), Some(Severity::Warn));
1040    }
1041
1042    #[test]
1043    fn names_are_unique_across_entrypoints_and_checks() {
1044        let mut seen = BTreeSet::new();
1045        for n in ENTRYPOINTS
1046            .iter()
1047            .map(|(n, _)| *n)
1048            .chain(CHECKS.iter().map(|check| check.name))
1049        {
1050            assert!(seen.insert(n), "duplicate registration: {n}");
1051        }
1052    }
1053
1054    /// Only FIVE files ship, and they are exactly the hook names git invokes.
1055    #[test]
1056    fn the_shipped_shims_are_exactly_the_git_invoked_hooks() {
1057        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
1058        let mut shipped: Vec<String> = std::fs::read_dir(dir)
1059            .expect("templates/hooks")
1060            .flatten()
1061            .map(|entry| entry.file_name().to_string_lossy().into_owned())
1062            .collect();
1063        shipped.sort();
1064        assert_eq!(
1065            shipped,
1066            vec![
1067                "commit-msg",
1068                "post-commit",
1069                "post-rewrite",
1070                "pre-commit",
1071                "pre-push",
1072                "prepare-commit-msg"
1073            ]
1074        );
1075        let none = crate::manifest::Manifest::default();
1076        for name in &shipped {
1077            assert!(
1078                lookup(name, &none).is_some(),
1079                "shipped shim {name:?} has no handler"
1080            );
1081        }
1082    }
1083
1084    /// Every check is reachable by name, which is how a shell — and the tests —
1085    /// invoke one directly.
1086    #[test]
1087    fn every_check_is_reachable_by_name() {
1088        let none = crate::manifest::Manifest::default();
1089        for check in CHECKS {
1090            assert!(
1091                lookup(check.name, &none).is_some(),
1092                "{} not reachable",
1093                check.name
1094            );
1095        }
1096        assert!(lookup("pre-commit-not-a-check", &none).is_none());
1097    }
1098
1099    /// pre-push is serial and fail-fast, so declaration order IS cost order.
1100    #[test]
1101    fn pre_push_runs_cheapest_first() {
1102        let order: Vec<&str> = super::stage_checks(Stage::PrePush)
1103            .map(|check| check.name)
1104            .collect();
1105        assert_eq!(
1106            order,
1107            vec![
1108                "pre-push-branch-protect",
1109                "pre-push-branch-pattern",
1110                "pre-push-secrets",
1111                "pre-push-pull-rebase",
1112                "pre-push-audit-go",
1113                "pre-push-audit-js",
1114                "pre-push-audit-python",
1115                "pre-push-audit-rust",
1116                "pre-push-run-tests-js",
1117                "pre-push-cargo-test",
1118                "pre-push-go-test",
1119                "pre-push-pytest",
1120            ]
1121        );
1122    }
1123
1124    /// What a check actually looks at, as opposed to what it DECLARES.
1125    ///
1126    /// `All` is a check that reads every staged path regardless of the
1127    /// extensions in its scope (ban-terms greps them all); `Exts(e)` is a check
1128    /// that filters by suffix, and `e` is the list it filters WITH.
1129    enum Consumes {
1130        All,
1131        Exts(&'static [&'static str]),
1132    }
1133
1134    /// Every check, and the file set it consumes. The table exists so a NEW
1135    /// check cannot be added without somebody stating the answer.
1136    ///
1137    /// The incident: `pre-commit-lint-json-yaml` declared
1138    /// `[".json", ".yaml", ".yml"]` in the registry while `lint_json_yaml::run`
1139    /// asked `staged_files` for `[".yaml"]`. `amont list` reported the check
1140    /// as covering `.yml`, the fleet dashboard agreed, and a staged, broken
1141    /// `x.yml` returned `Outcome::Passed` with no output whatsoever. Nothing
1142    /// connected the two lists, so nothing could notice.
1143    ///
1144    /// Each entry now names the module constant the check itself filters with,
1145    /// which is the same constant the registry declares its scope from — so
1146    /// this table cannot silently agree with a stale copy.
1147    const CONSUMED: &[(&str, Consumes)] = &[
1148        (
1149            "pre-commit-argo-lint",
1150            Consumes::Exts(crate::hooks::k8s::EXTS),
1151        ),
1152        // Each term filters candidates against its own language's extensions,
1153        // and `EXTS` is pinned to be exactly their union — so this names the
1154        // module constant the check itself filters with.
1155        (
1156            "pre-commit-ban-terms",
1157            Consumes::Exts(crate::hooks::ban_terms::EXTS),
1158        ),
1159        (
1160            "pre-commit-cargo-fmt",
1161            Consumes::Exts(crate::hooks::rust_tools::EXTS),
1162        ),
1163        (
1164            "pre-commit-clippy",
1165            Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1166        ),
1167        (
1168            "pre-commit-go-vet",
1169            Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1170        ),
1171        (
1172            "pre-commit-gofmt",
1173            Consumes::Exts(crate::hooks::go_tools::EXTS),
1174        ),
1175        (
1176            "pre-commit-kube-linter",
1177            Consumes::Exts(crate::hooks::k8s::EXTS),
1178        ),
1179        (
1180            "pre-commit-kubeconform",
1181            Consumes::Exts(crate::hooks::k8s::EXTS),
1182        ),
1183        (
1184            "pre-commit-lint-js",
1185            Consumes::Exts(crate::hooks::lint_js::EXTS),
1186        ),
1187        (
1188            "pre-commit-lint-json-yaml",
1189            Consumes::Exts(crate::hooks::lint_json_yaml::EXTS),
1190        ),
1191        ("pre-commit-merge-conflict", Consumes::All),
1192        ("pre-commit-package-lock", Consumes::All),
1193        // Declares `files: &[]` — it is opt-in by CONFIG, not by file type —
1194        // while consuming seventeen extensions. The other reason the assertion
1195        // is a subset check rather than an equality.
1196        (
1197            "pre-commit-prettier",
1198            Consumes::Exts(crate::hooks::prettier::EXTS),
1199        ),
1200        (
1201            "pre-commit-pyright",
1202            Consumes::Exts(crate::hooks::python_tools::EXTS),
1203        ),
1204        (
1205            "pre-commit-ruff",
1206            Consumes::Exts(crate::hooks::python_tools::EXTS),
1207        ),
1208        ("pre-commit-usual-name", Consumes::All),
1209        (
1210            "pre-commit-yamllint",
1211            Consumes::Exts(crate::hooks::yamllint::EXTS),
1212        ),
1213        (
1214            "pre-commit-shellcheck",
1215            Consumes::Exts(crate::hooks::shellcheck::EXTS),
1216        ),
1217        (
1218            "pre-commit-hadolint",
1219            Consumes::Exts(crate::hooks::hadolint::NAMES),
1220        ),
1221        (
1222            "pre-commit-helm-lint",
1223            Consumes::Exts(crate::hooks::helm::EXTS),
1224        ),
1225        ("pre-commit-large-files", Consumes::All),
1226        ("pre-commit-secrets", Consumes::All),
1227        ("pre-push-secrets", Consumes::All),
1228        ("pre-push-branch-protect", Consumes::All),
1229        ("pre-push-branch-pattern", Consumes::All),
1230        ("pre-push-pull-rebase", Consumes::All),
1231        (
1232            "pre-push-run-tests-js",
1233            Consumes::Exts(crate::hooks::run_tests::JS_EXTS),
1234        ),
1235        (
1236            "pre-push-pytest",
1237            Consumes::Exts(crate::hooks::python_tools::EXTS),
1238        ),
1239        (
1240            "pre-push-cargo-test",
1241            Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1242        ),
1243        (
1244            "pre-push-go-test",
1245            Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1246        ),
1247        // Reads every workflow file, and amont.conf (a name, not an ext).
1248        (
1249            "pre-commit-tree-parity",
1250            Consumes::Exts(crate::hooks::k8s::EXTS),
1251        ),
1252    ];
1253
1254    /// A declared scope must never promise more than the check consumes.
1255    ///
1256    /// Two halves, and the first is the one that earns its keep: a check with a
1257    /// non-empty `scope.files` that nobody has entered in `CONSUMED` fails the
1258    /// build, so adding a check forces somebody to state what it actually
1259    /// reads. The second half then pins that `scope.files ⊆ consumed`.
1260    ///
1261    /// SUBSET, not equality, deliberately: `prettier` declares `files: &[]` —
1262    /// it is opt-in by CONFIG, not by file type — while consuming seventeen
1263    /// extensions. Equality would forbid it.
1264    #[test]
1265    fn no_check_declares_a_file_type_it_does_not_consume() {
1266        for (name, _) in CONSUMED {
1267            assert!(
1268                CHECKS.iter().any(|check| check.name == *name),
1269                "CONSUMED names {name:?}, which is not a check"
1270            );
1271        }
1272        for check in CHECKS {
1273            let entry = CONSUMED.iter().find(|(name, _)| *name == check.name);
1274            if check.scope.files.is_empty() && entry.is_none() {
1275                continue;
1276            }
1277            let Some((_, consumes)) = entry else {
1278                panic!(
1279                    "{} declares scope.files {:?} but is missing from CONSUMED — \
1280                     say what it actually reads",
1281                    check.name, check.scope.files
1282                );
1283            };
1284            let Consumes::Exts(consumed) = consumes else {
1285                continue; // `All` consumes everything, so any declaration fits
1286            };
1287            for ext in check.scope.files {
1288                assert!(
1289                    consumed.contains(ext),
1290                    "{} declares {ext:?} in its scope but never asks for it — \
1291                     `{BIN} list` would report a coverage the check does not have",
1292                    check.name
1293                );
1294            }
1295        }
1296    }
1297
1298    /// A push suite must declare EVERY path it consumes, the converse of the
1299    /// test above, because the declaration is what the rest of the push
1300    /// reads: rehearsal picks its gates by `scope.touches`, pairing judges
1301    /// coverage by it, and `stamp_tips` stamps only a gate whose scope the
1302    /// push touched.
1303    ///
1304    /// The incident: `pre-push-cargo-test` declared `.rs` while
1305    /// `rust_tools::test` ran for `Cargo.toml` and `Cargo.lock` too. A
1306    /// release commit (version bump only) got "nothing to rehearse", then
1307    /// the push ran the full suite (557 s for relais 0.22.0), and the pass
1308    /// was never stamped, so every such push ran it again.
1309    #[test]
1310    fn a_push_suite_declares_every_path_it_consumes() {
1311        for name in ["pre-push-cargo-test", "pre-push-go-test", "pre-push-pytest"] {
1312            let check = CHECKS.iter().find(|c| c.name == name).expect(name);
1313            let Some((_, Consumes::Exts(consumed))) = CONSUMED.iter().find(|(n, _)| *n == name)
1314            else {
1315                panic!("{name} must consume an explicit file set");
1316            };
1317            for path in *consumed {
1318                assert!(
1319                    check.scope.files.contains(path),
1320                    "{name} runs for {path:?} but does not declare it: a push \
1321                     touching only {path:?} would be rehearsed as nothing to do, \
1322                     run at push time, and never stamped"
1323                );
1324            }
1325        }
1326    }
1327
1328    /// Which checks contain code that repairs and re-stages, stated by hand.
1329    ///
1330    /// `pre-commit-cargo-fmt` and `pre-commit-ruff` both declared
1331    /// `Fix::Rewrite` with NO fixing code anywhere — only `prettier.rs` and
1332    /// `manifest.rs` ever called `restage`/`fixing_enabled`. `amont list
1333    /// --json` reported `"fix":"rewrite"` for them regardless, and `agents_md`
1334    /// explicitly directs agents to trust that JSON, so an agent would set
1335    /// `amont.fix true` and wait for a repair that could never arrive.
1336    const HAS_FIXING_CODE: &[(&str, bool)] = &[
1337        ("pre-commit-agents-md", true),
1338        ("pre-commit-argo-lint", false),
1339        ("pre-commit-ban-terms", false),
1340        ("pre-commit-branch-pattern", false),
1341        ("pre-commit-branch-protect", false),
1342        ("pre-commit-cargo-fmt", true),
1343        ("pre-commit-clippy", false),
1344        ("pre-commit-go-vet", false),
1345        ("pre-commit-gofmt", true),
1346        ("pre-commit-kube-linter", false),
1347        ("pre-commit-kubeconform", false),
1348        ("pre-commit-lint-js", false),
1349        ("pre-commit-lint-json-yaml", false),
1350        ("pre-commit-manifest-trust", false),
1351        ("pre-commit-merge-conflict", false),
1352        ("pre-commit-package-lock", false),
1353        ("pre-commit-prettier", true),
1354        ("pre-commit-pyright", false),
1355        ("pre-commit-ruff", true),
1356        ("pre-commit-tree-parity", false),
1357        ("pre-commit-usual-name", false),
1358        ("pre-commit-yamllint", false),
1359        ("pre-commit-shellcheck", false),
1360        ("pre-commit-hadolint", false),
1361        ("pre-commit-helm-lint", false),
1362        ("pre-commit-large-files", false),
1363        ("pre-commit-secrets", false),
1364        ("pre-push-secrets", false),
1365        ("pre-push-branch-protect", false),
1366        ("pre-push-branch-pattern", false),
1367        ("pre-push-pull-rebase", false),
1368        ("pre-push-audit-go", false),
1369        ("pre-push-audit-js", false),
1370        ("pre-push-audit-python", false),
1371        ("pre-push-audit-rust", false),
1372        ("pre-push-run-tests-js", false),
1373        ("pre-push-cargo-test", false),
1374        ("pre-push-go-test", false),
1375        ("pre-push-pytest", false),
1376    ];
1377
1378    /// A `Fix::Rewrite` declaration is a PROMISE, and the set of checks that
1379    /// keep it must equal the set that make it.
1380    #[test]
1381    fn every_rewrite_declaration_has_a_fixer() {
1382        let declared: BTreeSet<&str> = CHECKS
1383            .iter()
1384            .filter(|check| check.fix == super::Fix::Rewrite)
1385            .map(|check| check.name)
1386            .collect();
1387        let implemented: BTreeSet<&str> = HAS_FIXING_CODE
1388            .iter()
1389            .filter(|(_, has)| *has)
1390            .map(|(name, _)| *name)
1391            .collect();
1392        assert_eq!(
1393            declared, implemented,
1394            "a check declaring Fix::Rewrite with no fixer lies to `{BIN} list --json`, \
1395             and a check with a fixer that does not declare it can never be reached"
1396        );
1397
1398        // …and the table must cover every check, so a new one cannot be added
1399        // without somebody answering the question.
1400        let listed: BTreeSet<&str> = HAS_FIXING_CODE.iter().map(|(name, _)| *name).collect();
1401        let all: BTreeSet<&str> = CHECKS.iter().map(|check| check.name).collect();
1402        assert_eq!(listed, all, "HAS_FIXING_CODE does not cover CHECKS");
1403    }
1404
1405    /// The reconciliation tests that used to live here are gone, and that is
1406    /// the point of the refactor: there is no second table to disagree with.
1407    /// The safety net is exactly the checks whose findings are mistakes in
1408    /// ANY codebase, with near-zero false positives — a conflict marker, an
1409    /// oversized blob, a leaked credential, a debug leftover in YOUR diff.
1410    /// Everything else is a house rule, and a house rule must not fire in a
1411    /// repository that never subscribed. Growing this list is a decision,
1412    /// not a default: lint-json-yaml stays OUT because Helm templates are
1413    /// invalid YAML and blocking a contribution to somebody else's chart
1414    /// repo is exactly the false positive this split exists to prevent.
1415    #[test]
1416    fn the_safety_net_is_exactly_the_low_false_positive_set() {
1417        let safety: Vec<&str> = CHECKS
1418            .iter()
1419            .filter(|c| c.reach == Reach::Safety)
1420            .map(|c| c.name)
1421            .collect();
1422        assert_eq!(
1423            safety,
1424            vec![
1425                "pre-commit-ban-terms",
1426                "pre-commit-large-files",
1427                "pre-commit-manifest-trust",
1428                "pre-commit-merge-conflict",
1429                "pre-commit-secrets",
1430                "pre-push-secrets",
1431            ]
1432        );
1433    }
1434
1435    #[test]
1436    fn every_check_declares_a_stage_and_a_scope() {
1437        assert_eq!(CHECKS.len(), 39);
1438        let pre_commit = super::stage_checks(Stage::PreCommit).count();
1439        let pre_push = super::stage_checks(Stage::PrePush).count();
1440        assert_eq!(
1441            pre_commit + pre_push,
1442            CHECKS.len(),
1443            "every check has a stage"
1444        );
1445    }
1446}