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| hooks::run_tests::run(ctx.settings, ctx.push.get(), ctx.manifest, ctx.name),
548    },
549    Builtin {
550        name: "pre-push-cargo-test",
551        stage: Stage::PrePush,
552        scope: Scope::new(hooks::rust_tools::RUST_PATHS, &["Cargo.toml"])
553            .not_during(&[GitState::Bisect, GitState::Rebase]),
554        severity: Severity::Block,
555        fix: Fix::None,
556        reach: Reach::Convention,
557        run: |ctx| hooks::rust_tools::test(ctx.settings, ctx.push.get(), ctx.name),
558    },
559    Builtin {
560        name: "pre-push-go-test",
561        stage: Stage::PrePush,
562        scope: Scope::new(hooks::go_tools::GO_PATHS, &["go.mod"])
563            .not_during(&[GitState::Bisect, GitState::Rebase]),
564        severity: Severity::Block,
565        fix: Fix::None,
566        reach: Reach::Convention,
567        run: |ctx| hooks::go_tools::test(ctx.settings, ctx.push.get(), ctx.name),
568    },
569    Builtin {
570        name: "pre-push-pytest",
571        stage: Stage::PrePush,
572        scope: Scope::new(hooks::python_tools::EXTS, &["pytest.ini", "conftest.py"])
573            .not_during(&[GitState::Bisect, GitState::Rebase]),
574        severity: Severity::Block,
575        fix: Fix::None,
576        reach: Reach::Convention,
577        run: |ctx| hooks::python_tools::pytest(ctx.settings, ctx.push.get(), ctx.name),
578    },
579];
580
581/// A check's severity, after any per-repository override.
582///
583/// `git config amont.severity.<check> warn` downgrades a blocking check to a
584/// warning. Unlike `hook.skip` it keeps the signal: the check still runs and
585/// still reports, it just stops failing the commit.
586pub fn severity_of(settings: &crate::config::Settings, check: &dyn Check) -> Severity {
587    effective_override(settings, None, check.name()).unwrap_or_else(|| check.severity())
588}
589
590/// The config key a severity override lives under.
591pub fn severity_key(check: &str) -> String {
592    format!("amont.severity.{check}")
593}
594
595/// Every severity override visible here, resolved the way `--get` resolves it.
596///
597/// ONE subprocess for the whole stage, and — more importantly — a VALUE. The
598/// dispatcher used to call `severity_of` inside the loop that classifies
599/// outcomes, which put a `git` spawn in the middle of a fold and made the fold
600/// impossible to test without a repository.
601///
602/// `--get-regexp` emits entries in precedence order, so folding with overwrite
603/// lands on the same answer `--get` gives. That equivalence is not assumed:
604/// `the_batch_agrees_with_the_authority` pins it against `effective_override`.
605#[derive(Debug, Default, Clone)]
606pub struct Overrides(std::collections::BTreeMap<String, (Severity, Source)>);
607
608/// Where an override came from — machine config or the repository's
609/// committed policy. `amont list` reports it; nothing on the commit path
610/// consults it.
611#[derive(Debug, Clone, Copy, PartialEq, Eq)]
612pub enum Source {
613    Config,
614    Policy,
615}
616
617impl Source {
618    pub fn as_str(self) -> &'static str {
619        match self {
620            Source::Config => "config",
621            Source::Policy => "policy",
622        }
623    }
624}
625
626impl Overrides {
627    /// Machine config AND the installed repo policy, folded on the
628    /// specificity ladder: system < global < POLICY < local < worktree <
629    /// command. `--show-scope` labels each config line; on a git too old to
630    /// know the flag (exit 129 → `None`) this degrades, deliberately, to
631    /// "ALL git config beats policy" — the fail-safe direction, because the
632    /// alternative was an EMPTY override set silently discarding both.
633    pub fn read(settings: &crate::config::Settings) -> Overrides {
634        let policy = settings.policy();
635        match crate::git::stdout(&[
636            "config",
637            "--show-scope",
638            "--get-regexp",
639            r"^amont\.severity\.",
640        ]) {
641            Some(scoped) => Overrides::from_scoped(&scoped, policy),
642            // `--get-regexp` with no matches ALSO exits non-zero, so `None`
643            // here can mean "no keys" as well as "old git" — both fold the
644            // same way: nothing below, policy, nothing above.
645            None => Overrides::from_plain_with_policy_below(
646                crate::git::stdout(&["config", "--get-regexp", r"^amont\.severity\."]),
647                policy,
648            ),
649        }
650    }
651
652    /// Fold `--show-scope` output around the installed policy. Scope words
653    /// `system`/`global` fold BELOW policy; everything else — `local`,
654    /// `worktree`, `command`, and any word a future git invents — folds
655    /// ABOVE, because misreading a local as below would let a file pulled
656    /// from a remote silently override a person's explicit setting on their
657    /// own machine, and that is the worse direction to fail in.
658    pub fn from_scoped(scoped: &str, policy: &crate::policy::Policy) -> Overrides {
659        let mut below = String::new();
660        let mut above = String::new();
661        for line in scoped.lines() {
662            let Some((scope, rest)) = line.split_once('\t') else {
663                continue;
664            };
665            match scope {
666                "system" | "global" => {
667                    below.push_str(rest);
668                    below.push('\n');
669                }
670                _ => {
671                    above.push_str(rest);
672                    above.push('\n');
673                }
674            }
675        }
676        let mut o = Overrides::default();
677        o.fold_plain(&below, Source::Config);
678        o.fold_policy(policy);
679        o.fold_plain(&above, Source::Config);
680        o
681    }
682
683    /// The DEGRADED fold — policy below every config scope, i.e. all git
684    /// config beats policy — for a git that cannot label scopes. `pub`
685    /// because the fleet's severity column must degrade the same way the
686    /// dispatcher does, not invent a third opinion.
687    pub fn from_plain_with_policy_below(
688        plain: Option<String>,
689        policy: &crate::policy::Policy,
690    ) -> Overrides {
691        let mut o = Overrides::default();
692        o.fold_policy(policy);
693        o.fold_plain(plain.as_deref().unwrap_or_default(), Source::Config);
694        o
695    }
696
697    /// Policy entries are insert-only: a bad severity word was refused at
698    /// parse time and never reaches here.
699    fn fold_policy(&mut self, policy: &crate::policy::Policy) {
700        for (target, severity) in &policy.severities {
701            self.0.insert(target.clone(), (*severity, Source::Policy));
702        }
703    }
704
705    /// The original fold: later entries overwrite, an unrecognised value
706    /// CLEARS the key rather than shadowing a valid earlier one. Kept as the
707    /// single implementation both `from_config` and the ladder halves use.
708    fn fold_plain(&mut self, text: &str, source: Source) {
709        for line in text.lines() {
710            let Some((key, value)) = line.split_once(' ') else {
711                continue;
712            };
713            let Some(check) = key.strip_prefix("amont.severity.") else {
714                continue;
715            };
716            match Severity::parse(value.trim()) {
717                Some(sev) => {
718                    self.0.insert(check.to_string(), (sev, source));
719                }
720                None => {
721                    self.0.remove(check);
722                }
723            }
724        }
725    }
726
727    /// Built from `--get-regexp`-shaped text (`amont.severity.<check>
728    /// <value>` per line, in git's own precedence order — system, then
729    /// global, then local, then includes). `pub` so a reader that has
730    /// already fetched those lines for its own reasons (the fleet dashboard
731    /// needs the origin of each, which `Overrides` does not track) can still
732    /// ask this — the one place that must not get precedence wrong — rather
733    /// than re-deriving it from the lines by hand.
734    pub fn from_config(out: Option<String>) -> Overrides {
735        let mut o = Overrides::default();
736        o.fold_plain(out.as_deref().unwrap_or_default(), Source::Config);
737        o
738    }
739
740    /// The configured key that applies to `check`, and what it says.
741    ///
742    /// Several keys can name one check — `pre-commit` and `clippy` and
743    /// `pre-commit-clippy` all reach `pre-commit-clippy`. The most specific
744    /// wins, which is the rule anybody would guess and the only one that lets
745    /// you downgrade a whole trigger and then exempt one check from it.
746    pub fn applied_to(&self, check: &str) -> Option<(&str, Severity)> {
747        self.applied_with_source(check)
748            .map(|(pattern, severity, _)| (pattern, severity))
749    }
750
751    /// As `applied_to`, keeping WHERE the winning key came from — the one
752    /// reader (`amont list`) that reports provenance asks here rather than
753    /// re-deriving the answer a second way.
754    pub fn applied_with_source(&self, check: &str) -> Option<(&str, Severity, Source)> {
755        self.0
756            .iter()
757            .filter_map(|(pattern, (severity, source))| {
758                crate::names_check(check, pattern)
759                    .map(|m| (m, pattern.as_str(), *severity, *source))
760            })
761            .max_by_key(|(m, _, _, _)| *m)
762            .map(|(_, pattern, severity, source)| (pattern, severity, source))
763    }
764
765    /// The severity to apply to `check`, override or declared.
766    pub fn of(&self, check: &dyn Check) -> Severity {
767        self.applied_to(check.name())
768            .map(|(_, severity)| severity)
769            .unwrap_or_else(|| check.severity())
770    }
771}
772
773#[cfg(test)]
774mod precedence {
775    use super::{Overrides, Severity};
776
777    fn overrides(lines: &[&str]) -> Overrides {
778        let text = lines
779            .iter()
780            .map(|l| format!("amont.severity.{l}\n"))
781            .collect::<String>();
782        Overrides::from_config(Some(text))
783    }
784
785    /// The whole reason triggers and short names are allowed as keys: downgrade
786    /// a trigger wholesale, then say something different about one check. If the
787    /// broader key won instead, the exemption would be unwritable.
788    #[test]
789    fn the_more_specific_key_wins() {
790        let both = overrides(&["pre-commit warn", "pre-commit-clippy block"]);
791        assert_eq!(
792            both.applied_to("pre-commit-clippy"),
793            Some(("pre-commit-clippy", Severity::Block)),
794            "a full id beats its trigger"
795        );
796        assert_eq!(
797            both.applied_to("pre-commit-shellcheck"),
798            Some(("pre-commit", Severity::Warn)),
799            "and the trigger still governs every check it did not exempt"
800        );
801    }
802
803    /// Full id > short name > trigger, all three at once, so the ordering is
804    /// pinned end to end rather than one pair at a time.
805    #[test]
806    fn the_three_ways_to_name_a_check_are_ranked() {
807        let all = overrides(&["pre-commit warn", "clippy block", "pre-commit-clippy warn"]);
808        assert_eq!(
809            all.applied_to("pre-commit-clippy"),
810            Some(("pre-commit-clippy", Severity::Warn))
811        );
812
813        let no_full = overrides(&["pre-commit warn", "clippy block"]);
814        assert_eq!(
815            no_full.applied_to("pre-commit-clippy"),
816            Some(("clippy", Severity::Block)),
817            "a short name beats a trigger"
818        );
819    }
820
821    /// A key naming nothing must not become the answer by being the only one
822    /// there — that is how a repo believes it downgraded a check it never named.
823    #[test]
824    fn a_key_that_names_no_check_applies_to_nothing() {
825        let typo = overrides(&["clipy warn", "e warn", " warn"]);
826        assert_eq!(typo.applied_to("pre-commit-clippy"), None);
827    }
828}
829
830/// The override git would actually apply for `check`, or `None` if there is
831/// none (or the value is not one this understands).
832///
833/// `--get`, NOT `--get-regexp`: git returns the LAST value, so a local `block`
834/// beats a global `warn`. A reader that listed every entry instead and treated
835/// each as authoritative would report a downgrade that the dispatcher does not
836/// apply — which is exactly what the dashboard used to do.
837///
838/// `repo` is `None` for the current directory, which is where a hook runs.
839pub fn effective_override(
840    settings: &crate::config::Settings,
841    repo: Option<&Path>,
842    check: &str,
843) -> Option<Severity> {
844    overrides_in(settings, repo)
845        .applied_to(check)
846        .map(|(_, s)| s)
847}
848
849/// Which configured KEY applies to `check` here, if any.
850///
851/// The dashboard needs the key rather than the value: with three ways to name a
852/// check, "which of these lines is the one doing something" is the question a
853/// reader actually has.
854pub fn effective_key(
855    settings: &crate::config::Settings,
856    repo: Option<&Path>,
857    check: &str,
858) -> Option<String> {
859    overrides_in(settings, repo)
860        .applied_to(check)
861        .map(|(pattern, _)| pattern.to_string())
862}
863
864fn overrides_in(settings: &crate::config::Settings, repo: Option<&Path>) -> Overrides {
865    match repo {
866        // The current repository: same fold the dispatcher uses, policy
867        // included — `amont run <check>` resolves through here and must not
868        // disagree with the stage that would have run it.
869        None => Overrides::read(settings),
870        // Somebody ELSE's repository (the fleet's per-repo question): never
871        // this process's policy — the store belongs to the repo the process
872        // is standing in, and a scanner walks many.
873        Some(dir) => Overrides::from_config(crate::git::stdout_in(
874            dir,
875            &["config", "--get-regexp", r"^amont\.severity\."],
876        )),
877    }
878}
879
880/// Built-in checks for one stage, in declared order.
881pub fn stage_checks(stage: Stage) -> impl Iterator<Item = &'static Builtin> {
882    CHECKS.iter().filter(move |check| check.stage == stage)
883}
884
885/// The scope of the built-in pre-push gate that a commit-time declaration
886/// named `short` stands in for: the gate of that short name (`cargo-test`),
887/// or, for a script the npm push gate runs (`typecheck`, `test`), that gate's.
888/// `None` when no built-in gate is its twin. A declared pre-push twin is found
889/// by the manifest itself (`manifest::attach_twin_scopes`). Returns the gate's
890/// id with its scope, so a commit can say which gate reads the files it tests.
891pub fn push_twin_scope(short: &str) -> Option<(&'static str, Scope)> {
892    let mut push = stage_checks(Stage::PrePush);
893    let twin = push
894        .find(|check| check.pairing_name() == short)
895        .or_else(|| {
896            hooks::run_tests::is_gate_script(short)
897                .then(|| stage_checks(Stage::PrePush).find(|c| c.name() == "pre-push-run-tests-js"))
898                .flatten()
899        });
900    twin.map(|check| (check.name(), check.scope()))
901}
902
903/// Every check for one stage — built-ins first, then whatever this repository
904/// declares in `amont.conf`.
905///
906/// The order is not negotiable and not configurable. A third-party command must
907/// not be able to delay `pre-push-branch-protect`, and appending is the only
908/// arrangement in which it cannot.
909pub fn all_stage_checks<'a>(
910    stage: Stage,
911    manifest: &'a crate::manifest::Manifest,
912) -> Vec<&'a dyn Check> {
913    let mut out: Vec<&'a dyn Check> = stage_checks(stage)
914        .map(|check| check as &dyn Check)
915        .collect();
916    out.extend(
917        manifest
918            .externals
919            .iter()
920            .filter(|external| external.stage == stage)
921            .map(|external| external as &dyn Check),
922    );
923    out
924}
925
926pub fn lookup(name: &str, manifest: &crate::manifest::Manifest) -> Option<HookFn> {
927    if let Some((_, f)) = ENTRYPOINTS.iter().find(|(n, _)| *n == name) {
928        return Some(*f);
929    }
930    // A check invoked directly by name — how the tests drive individual checks,
931    // and how `amont <check>` works from a shell. Its Outcome collapses to an
932    // exit code here, honouring severity, so a `warn` check invoked directly
933    // reports without failing exactly as it does inside a dispatcher. The
934    // closure re-resolves through the Ctx it is handed — a plain fn pointer
935    // captures nothing, and the manifest travels ON the Ctx.
936    if CHECKS.iter().any(|check| check.name == name)
937        || manifest
938            .externals
939            .iter()
940            .any(|external| external.id == name)
941    {
942        return Some(|ctx: &Ctx| {
943            let check = one_named(ctx.name, ctx.manifest).expect("checked above");
944            // One check run by name queues for a host slot like it would
945            // inside its stage (ADR-0009).
946            let _slot = crate::host_slots::enter_check(check.name(), check.weight());
947            Verdict::blocking(matches!(
948                (check.run(ctx), severity_of(ctx.settings, check)),
949                (Outcome::Failed, Severity::Block)
950            ))
951        });
952    }
953    None
954}
955
956/// One check by name, whichever kind it is. Built-ins are searched first, which
957/// costs nothing because `manifest::parse` refuses a name a built-in already
958/// holds — the two guards together mean neither kind can shadow the other.
959pub fn one_named<'a>(name: &str, manifest: &'a crate::manifest::Manifest) -> Option<&'a dyn Check> {
960    if let Some(builtin) = CHECKS.iter().find(|check| check.name == name) {
961        return Some(builtin);
962    }
963    manifest
964        .externals
965        .iter()
966        .find(|external| external.id == name)
967        .map(|external| external as &dyn Check)
968}
969
970#[cfg(test)]
971mod tests {
972    use super::{lookup, Overrides, Reach, Severity, Stage, CHECKS, ENTRYPOINTS};
973    use crate::names::BIN;
974    use std::collections::BTreeSet;
975
976    /// The batch reader must land on the same answer as the authority.
977    ///
978    /// `Overrides` folds `--get-regexp` output with overwrite; `effective_override`
979    /// asks `--get`. They agree only because git emits entries in precedence
980    /// order — an assumption, so it is asserted against real git rather than
981    /// trusted.
982    #[test]
983    fn the_batch_agrees_with_the_authority() {
984        let d = std::env::temp_dir().join(format!("ov-{}", std::process::id()));
985        let _ = std::fs::remove_dir_all(&d);
986        std::fs::create_dir_all(&d).unwrap();
987        let git = |args: &[&str]| {
988            std::process::Command::new("git")
989                .args(args)
990                .current_dir(&d)
991                .output()
992                .expect("git");
993        };
994        git(&["init", "-q", "--template=", "."]);
995        let key = "amont.severity.pre-commit-merge-conflict";
996        git(&["config", "--add", key, "warn"]);
997        git(&["config", "--add", key, "block"]);
998
999        let raw = std::process::Command::new("git")
1000            .args(["config", "--get-regexp", r"^amont\.severity\."])
1001            .current_dir(&d)
1002            .output()
1003            .expect("git");
1004        let batch = Overrides::from_config(Some(
1005            String::from_utf8_lossy(&raw.stdout).trim().to_string(),
1006        ));
1007        let authority =
1008            crate::git::stdout_in(&d, &["config", "--get", key]).and_then(|v| Severity::parse(&v));
1009        let _ = std::fs::remove_dir_all(&d);
1010
1011        assert_eq!(
1012            authority,
1013            Some(Severity::Block),
1014            "git applies the last entry"
1015        );
1016        assert_eq!(
1017            batch.0.get("pre-commit-merge-conflict").map(|(s, _)| *s),
1018            authority,
1019            "the batch reader disagreed with `--get`"
1020        );
1021    }
1022
1023    /// An unrecognised value is not an override, and must not shadow a valid
1024    /// earlier one either — a typo would otherwise silently restore the
1025    /// declared severity in a way nobody could see.
1026    #[test]
1027    fn an_unrecognised_value_clears_rather_than_overrides() {
1028        let o = Overrides::from_config(Some(
1029            "amont.severity.a warn\namont.severity.a advisory\namont.severity.b warn".to_string(),
1030        ));
1031        assert_eq!(o.0.get("a"), None, "a typo must not leave `warn` standing");
1032        assert_eq!(o.0.get("b").map(|(s, _)| *s), Some(Severity::Warn));
1033    }
1034
1035    #[test]
1036    fn names_are_unique_across_entrypoints_and_checks() {
1037        let mut seen = BTreeSet::new();
1038        for n in ENTRYPOINTS
1039            .iter()
1040            .map(|(n, _)| *n)
1041            .chain(CHECKS.iter().map(|check| check.name))
1042        {
1043            assert!(seen.insert(n), "duplicate registration: {n}");
1044        }
1045    }
1046
1047    /// Only FIVE files ship, and they are exactly the hook names git invokes.
1048    #[test]
1049    fn the_shipped_shims_are_exactly_the_git_invoked_hooks() {
1050        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
1051        let mut shipped: Vec<String> = std::fs::read_dir(dir)
1052            .expect("templates/hooks")
1053            .flatten()
1054            .map(|entry| entry.file_name().to_string_lossy().into_owned())
1055            .collect();
1056        shipped.sort();
1057        assert_eq!(
1058            shipped,
1059            vec![
1060                "commit-msg",
1061                "post-commit",
1062                "post-rewrite",
1063                "pre-commit",
1064                "pre-push",
1065                "prepare-commit-msg"
1066            ]
1067        );
1068        let none = crate::manifest::Manifest::default();
1069        for name in &shipped {
1070            assert!(
1071                lookup(name, &none).is_some(),
1072                "shipped shim {name:?} has no handler"
1073            );
1074        }
1075    }
1076
1077    /// Every check is reachable by name, which is how a shell — and the tests —
1078    /// invoke one directly.
1079    #[test]
1080    fn every_check_is_reachable_by_name() {
1081        let none = crate::manifest::Manifest::default();
1082        for check in CHECKS {
1083            assert!(
1084                lookup(check.name, &none).is_some(),
1085                "{} not reachable",
1086                check.name
1087            );
1088        }
1089        assert!(lookup("pre-commit-not-a-check", &none).is_none());
1090    }
1091
1092    /// pre-push is serial and fail-fast, so declaration order IS cost order.
1093    #[test]
1094    fn pre_push_runs_cheapest_first() {
1095        let order: Vec<&str> = super::stage_checks(Stage::PrePush)
1096            .map(|check| check.name)
1097            .collect();
1098        assert_eq!(
1099            order,
1100            vec![
1101                "pre-push-branch-protect",
1102                "pre-push-branch-pattern",
1103                "pre-push-secrets",
1104                "pre-push-pull-rebase",
1105                "pre-push-audit-go",
1106                "pre-push-audit-js",
1107                "pre-push-audit-python",
1108                "pre-push-audit-rust",
1109                "pre-push-run-tests-js",
1110                "pre-push-cargo-test",
1111                "pre-push-go-test",
1112                "pre-push-pytest",
1113            ]
1114        );
1115    }
1116
1117    /// What a check actually looks at, as opposed to what it DECLARES.
1118    ///
1119    /// `All` is a check that reads every staged path regardless of the
1120    /// extensions in its scope (ban-terms greps them all); `Exts(e)` is a check
1121    /// that filters by suffix, and `e` is the list it filters WITH.
1122    enum Consumes {
1123        All,
1124        Exts(&'static [&'static str]),
1125    }
1126
1127    /// Every check, and the file set it consumes. The table exists so a NEW
1128    /// check cannot be added without somebody stating the answer.
1129    ///
1130    /// The incident: `pre-commit-lint-json-yaml` declared
1131    /// `[".json", ".yaml", ".yml"]` in the registry while `lint_json_yaml::run`
1132    /// asked `staged_files` for `[".yaml"]`. `amont list` reported the check
1133    /// as covering `.yml`, the fleet dashboard agreed, and a staged, broken
1134    /// `x.yml` returned `Outcome::Passed` with no output whatsoever. Nothing
1135    /// connected the two lists, so nothing could notice.
1136    ///
1137    /// Each entry now names the module constant the check itself filters with,
1138    /// which is the same constant the registry declares its scope from — so
1139    /// this table cannot silently agree with a stale copy.
1140    const CONSUMED: &[(&str, Consumes)] = &[
1141        (
1142            "pre-commit-argo-lint",
1143            Consumes::Exts(crate::hooks::k8s::EXTS),
1144        ),
1145        // Each term filters candidates against its own language's extensions,
1146        // and `EXTS` is pinned to be exactly their union — so this names the
1147        // module constant the check itself filters with.
1148        (
1149            "pre-commit-ban-terms",
1150            Consumes::Exts(crate::hooks::ban_terms::EXTS),
1151        ),
1152        (
1153            "pre-commit-cargo-fmt",
1154            Consumes::Exts(crate::hooks::rust_tools::EXTS),
1155        ),
1156        (
1157            "pre-commit-clippy",
1158            Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1159        ),
1160        (
1161            "pre-commit-go-vet",
1162            Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1163        ),
1164        (
1165            "pre-commit-gofmt",
1166            Consumes::Exts(crate::hooks::go_tools::EXTS),
1167        ),
1168        (
1169            "pre-commit-kube-linter",
1170            Consumes::Exts(crate::hooks::k8s::EXTS),
1171        ),
1172        (
1173            "pre-commit-kubeconform",
1174            Consumes::Exts(crate::hooks::k8s::EXTS),
1175        ),
1176        (
1177            "pre-commit-lint-js",
1178            Consumes::Exts(crate::hooks::lint_js::EXTS),
1179        ),
1180        (
1181            "pre-commit-lint-json-yaml",
1182            Consumes::Exts(crate::hooks::lint_json_yaml::EXTS),
1183        ),
1184        ("pre-commit-merge-conflict", Consumes::All),
1185        ("pre-commit-package-lock", Consumes::All),
1186        // Declares `files: &[]` — it is opt-in by CONFIG, not by file type —
1187        // while consuming seventeen extensions. The other reason the assertion
1188        // is a subset check rather than an equality.
1189        (
1190            "pre-commit-prettier",
1191            Consumes::Exts(crate::hooks::prettier::EXTS),
1192        ),
1193        (
1194            "pre-commit-pyright",
1195            Consumes::Exts(crate::hooks::python_tools::EXTS),
1196        ),
1197        (
1198            "pre-commit-ruff",
1199            Consumes::Exts(crate::hooks::python_tools::EXTS),
1200        ),
1201        ("pre-commit-usual-name", Consumes::All),
1202        (
1203            "pre-commit-yamllint",
1204            Consumes::Exts(crate::hooks::yamllint::EXTS),
1205        ),
1206        (
1207            "pre-commit-shellcheck",
1208            Consumes::Exts(crate::hooks::shellcheck::EXTS),
1209        ),
1210        (
1211            "pre-commit-hadolint",
1212            Consumes::Exts(crate::hooks::hadolint::NAMES),
1213        ),
1214        (
1215            "pre-commit-helm-lint",
1216            Consumes::Exts(crate::hooks::helm::EXTS),
1217        ),
1218        ("pre-commit-large-files", Consumes::All),
1219        ("pre-commit-secrets", Consumes::All),
1220        ("pre-push-secrets", Consumes::All),
1221        ("pre-push-branch-protect", Consumes::All),
1222        ("pre-push-branch-pattern", Consumes::All),
1223        ("pre-push-pull-rebase", Consumes::All),
1224        (
1225            "pre-push-run-tests-js",
1226            Consumes::Exts(crate::hooks::run_tests::JS_EXTS),
1227        ),
1228        (
1229            "pre-push-pytest",
1230            Consumes::Exts(crate::hooks::python_tools::EXTS),
1231        ),
1232        (
1233            "pre-push-cargo-test",
1234            Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1235        ),
1236        (
1237            "pre-push-go-test",
1238            Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1239        ),
1240        // Reads every workflow file, and amont.conf (a name, not an ext).
1241        (
1242            "pre-commit-tree-parity",
1243            Consumes::Exts(crate::hooks::k8s::EXTS),
1244        ),
1245    ];
1246
1247    /// A declared scope must never promise more than the check consumes.
1248    ///
1249    /// Two halves, and the first is the one that earns its keep: a check with a
1250    /// non-empty `scope.files` that nobody has entered in `CONSUMED` fails the
1251    /// build, so adding a check forces somebody to state what it actually
1252    /// reads. The second half then pins that `scope.files ⊆ consumed`.
1253    ///
1254    /// SUBSET, not equality, deliberately: `prettier` declares `files: &[]` —
1255    /// it is opt-in by CONFIG, not by file type — while consuming seventeen
1256    /// extensions. Equality would forbid it.
1257    #[test]
1258    fn no_check_declares_a_file_type_it_does_not_consume() {
1259        for (name, _) in CONSUMED {
1260            assert!(
1261                CHECKS.iter().any(|check| check.name == *name),
1262                "CONSUMED names {name:?}, which is not a check"
1263            );
1264        }
1265        for check in CHECKS {
1266            let entry = CONSUMED.iter().find(|(name, _)| *name == check.name);
1267            if check.scope.files.is_empty() && entry.is_none() {
1268                continue;
1269            }
1270            let Some((_, consumes)) = entry else {
1271                panic!(
1272                    "{} declares scope.files {:?} but is missing from CONSUMED — \
1273                     say what it actually reads",
1274                    check.name, check.scope.files
1275                );
1276            };
1277            let Consumes::Exts(consumed) = consumes else {
1278                continue; // `All` consumes everything, so any declaration fits
1279            };
1280            for ext in check.scope.files {
1281                assert!(
1282                    consumed.contains(ext),
1283                    "{} declares {ext:?} in its scope but never asks for it — \
1284                     `{BIN} list` would report a coverage the check does not have",
1285                    check.name
1286                );
1287            }
1288        }
1289    }
1290
1291    /// A push suite must declare EVERY path it consumes, the converse of the
1292    /// test above, because the declaration is what the rest of the push
1293    /// reads: rehearsal picks its gates by `scope.touches`, pairing judges
1294    /// coverage by it, and `stamp_tips` stamps only a gate whose scope the
1295    /// push touched.
1296    ///
1297    /// The incident: `pre-push-cargo-test` declared `.rs` while
1298    /// `rust_tools::test` ran for `Cargo.toml` and `Cargo.lock` too. A
1299    /// release commit (version bump only) got "nothing to rehearse", then
1300    /// the push ran the full suite (557 s for relais 0.22.0), and the pass
1301    /// was never stamped, so every such push ran it again.
1302    #[test]
1303    fn a_push_suite_declares_every_path_it_consumes() {
1304        for name in ["pre-push-cargo-test", "pre-push-go-test", "pre-push-pytest"] {
1305            let check = CHECKS.iter().find(|c| c.name == name).expect(name);
1306            let Some((_, Consumes::Exts(consumed))) = CONSUMED.iter().find(|(n, _)| *n == name)
1307            else {
1308                panic!("{name} must consume an explicit file set");
1309            };
1310            for path in *consumed {
1311                assert!(
1312                    check.scope.files.contains(path),
1313                    "{name} runs for {path:?} but does not declare it: a push \
1314                     touching only {path:?} would be rehearsed as nothing to do, \
1315                     run at push time, and never stamped"
1316                );
1317            }
1318        }
1319    }
1320
1321    /// Which checks contain code that repairs and re-stages, stated by hand.
1322    ///
1323    /// `pre-commit-cargo-fmt` and `pre-commit-ruff` both declared
1324    /// `Fix::Rewrite` with NO fixing code anywhere — only `prettier.rs` and
1325    /// `manifest.rs` ever called `restage`/`fixing_enabled`. `amont list
1326    /// --json` reported `"fix":"rewrite"` for them regardless, and `agents_md`
1327    /// explicitly directs agents to trust that JSON, so an agent would set
1328    /// `amont.fix true` and wait for a repair that could never arrive.
1329    const HAS_FIXING_CODE: &[(&str, bool)] = &[
1330        ("pre-commit-agents-md", true),
1331        ("pre-commit-argo-lint", false),
1332        ("pre-commit-ban-terms", false),
1333        ("pre-commit-branch-pattern", false),
1334        ("pre-commit-branch-protect", false),
1335        ("pre-commit-cargo-fmt", true),
1336        ("pre-commit-clippy", false),
1337        ("pre-commit-go-vet", false),
1338        ("pre-commit-gofmt", true),
1339        ("pre-commit-kube-linter", false),
1340        ("pre-commit-kubeconform", false),
1341        ("pre-commit-lint-js", false),
1342        ("pre-commit-lint-json-yaml", false),
1343        ("pre-commit-manifest-trust", false),
1344        ("pre-commit-merge-conflict", false),
1345        ("pre-commit-package-lock", false),
1346        ("pre-commit-prettier", true),
1347        ("pre-commit-pyright", false),
1348        ("pre-commit-ruff", true),
1349        ("pre-commit-tree-parity", false),
1350        ("pre-commit-usual-name", false),
1351        ("pre-commit-yamllint", false),
1352        ("pre-commit-shellcheck", false),
1353        ("pre-commit-hadolint", false),
1354        ("pre-commit-helm-lint", false),
1355        ("pre-commit-large-files", false),
1356        ("pre-commit-secrets", false),
1357        ("pre-push-secrets", false),
1358        ("pre-push-branch-protect", false),
1359        ("pre-push-branch-pattern", false),
1360        ("pre-push-pull-rebase", false),
1361        ("pre-push-audit-go", false),
1362        ("pre-push-audit-js", false),
1363        ("pre-push-audit-python", false),
1364        ("pre-push-audit-rust", false),
1365        ("pre-push-run-tests-js", false),
1366        ("pre-push-cargo-test", false),
1367        ("pre-push-go-test", false),
1368        ("pre-push-pytest", false),
1369    ];
1370
1371    /// A `Fix::Rewrite` declaration is a PROMISE, and the set of checks that
1372    /// keep it must equal the set that make it.
1373    #[test]
1374    fn every_rewrite_declaration_has_a_fixer() {
1375        let declared: BTreeSet<&str> = CHECKS
1376            .iter()
1377            .filter(|check| check.fix == super::Fix::Rewrite)
1378            .map(|check| check.name)
1379            .collect();
1380        let implemented: BTreeSet<&str> = HAS_FIXING_CODE
1381            .iter()
1382            .filter(|(_, has)| *has)
1383            .map(|(name, _)| *name)
1384            .collect();
1385        assert_eq!(
1386            declared, implemented,
1387            "a check declaring Fix::Rewrite with no fixer lies to `{BIN} list --json`, \
1388             and a check with a fixer that does not declare it can never be reached"
1389        );
1390
1391        // …and the table must cover every check, so a new one cannot be added
1392        // without somebody answering the question.
1393        let listed: BTreeSet<&str> = HAS_FIXING_CODE.iter().map(|(name, _)| *name).collect();
1394        let all: BTreeSet<&str> = CHECKS.iter().map(|check| check.name).collect();
1395        assert_eq!(listed, all, "HAS_FIXING_CODE does not cover CHECKS");
1396    }
1397
1398    /// The reconciliation tests that used to live here are gone, and that is
1399    /// the point of the refactor: there is no second table to disagree with.
1400    /// The safety net is exactly the checks whose findings are mistakes in
1401    /// ANY codebase, with near-zero false positives — a conflict marker, an
1402    /// oversized blob, a leaked credential, a debug leftover in YOUR diff.
1403    /// Everything else is a house rule, and a house rule must not fire in a
1404    /// repository that never subscribed. Growing this list is a decision,
1405    /// not a default: lint-json-yaml stays OUT because Helm templates are
1406    /// invalid YAML and blocking a contribution to somebody else's chart
1407    /// repo is exactly the false positive this split exists to prevent.
1408    #[test]
1409    fn the_safety_net_is_exactly_the_low_false_positive_set() {
1410        let safety: Vec<&str> = CHECKS
1411            .iter()
1412            .filter(|c| c.reach == Reach::Safety)
1413            .map(|c| c.name)
1414            .collect();
1415        assert_eq!(
1416            safety,
1417            vec![
1418                "pre-commit-ban-terms",
1419                "pre-commit-large-files",
1420                "pre-commit-manifest-trust",
1421                "pre-commit-merge-conflict",
1422                "pre-commit-secrets",
1423                "pre-push-secrets",
1424            ]
1425        );
1426    }
1427
1428    #[test]
1429    fn every_check_declares_a_stage_and_a_scope() {
1430        assert_eq!(CHECKS.len(), 39);
1431        let pre_commit = super::stage_checks(Stage::PreCommit).count();
1432        let pre_push = super::stage_checks(Stage::PrePush).count();
1433        assert_eq!(
1434            pre_commit + pre_push,
1435            CHECKS.len(),
1436            "every check has a stage"
1437        );
1438    }
1439}