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/// Every check for one stage — built-ins first, then whatever this repository
893/// declares in `amont.conf`.
894///
895/// The order is not negotiable and not configurable. A third-party command must
896/// not be able to delay `pre-push-branch-protect`, and appending is the only
897/// arrangement in which it cannot.
898pub fn all_stage_checks<'a>(
899    stage: Stage,
900    manifest: &'a crate::manifest::Manifest,
901) -> Vec<&'a dyn Check> {
902    let mut out: Vec<&'a dyn Check> = stage_checks(stage)
903        .map(|check| check as &dyn Check)
904        .collect();
905    out.extend(
906        manifest
907            .externals
908            .iter()
909            .filter(|external| external.stage == stage)
910            .map(|external| external as &dyn Check),
911    );
912    out
913}
914
915pub fn lookup(name: &str, manifest: &crate::manifest::Manifest) -> Option<HookFn> {
916    if let Some((_, f)) = ENTRYPOINTS.iter().find(|(n, _)| *n == name) {
917        return Some(*f);
918    }
919    // A check invoked directly by name — how the tests drive individual checks,
920    // and how `amont <check>` works from a shell. Its Outcome collapses to an
921    // exit code here, honouring severity, so a `warn` check invoked directly
922    // reports without failing exactly as it does inside a dispatcher. The
923    // closure re-resolves through the Ctx it is handed — a plain fn pointer
924    // captures nothing, and the manifest travels ON the Ctx.
925    if CHECKS.iter().any(|check| check.name == name)
926        || manifest
927            .externals
928            .iter()
929            .any(|external| external.id == name)
930    {
931        return Some(|ctx: &Ctx| {
932            let check = one_named(ctx.name, ctx.manifest).expect("checked above");
933            // One check run by name queues for a host slot like it would
934            // inside its stage (ADR-0009).
935            let _slot = crate::host_slots::enter_check(check.name(), check.weight());
936            Verdict::blocking(matches!(
937                (check.run(ctx), severity_of(ctx.settings, check)),
938                (Outcome::Failed, Severity::Block)
939            ))
940        });
941    }
942    None
943}
944
945/// One check by name, whichever kind it is. Built-ins are searched first, which
946/// costs nothing because `manifest::parse` refuses a name a built-in already
947/// holds — the two guards together mean neither kind can shadow the other.
948pub fn one_named<'a>(name: &str, manifest: &'a crate::manifest::Manifest) -> Option<&'a dyn Check> {
949    if let Some(builtin) = CHECKS.iter().find(|check| check.name == name) {
950        return Some(builtin);
951    }
952    manifest
953        .externals
954        .iter()
955        .find(|external| external.id == name)
956        .map(|external| external as &dyn Check)
957}
958
959#[cfg(test)]
960mod tests {
961    use super::{lookup, Overrides, Reach, Severity, Stage, CHECKS, ENTRYPOINTS};
962    use crate::names::BIN;
963    use std::collections::BTreeSet;
964
965    /// The batch reader must land on the same answer as the authority.
966    ///
967    /// `Overrides` folds `--get-regexp` output with overwrite; `effective_override`
968    /// asks `--get`. They agree only because git emits entries in precedence
969    /// order — an assumption, so it is asserted against real git rather than
970    /// trusted.
971    #[test]
972    fn the_batch_agrees_with_the_authority() {
973        let d = std::env::temp_dir().join(format!("ov-{}", std::process::id()));
974        let _ = std::fs::remove_dir_all(&d);
975        std::fs::create_dir_all(&d).unwrap();
976        let git = |args: &[&str]| {
977            std::process::Command::new("git")
978                .args(args)
979                .current_dir(&d)
980                .output()
981                .expect("git");
982        };
983        git(&["init", "-q", "--template=", "."]);
984        let key = "amont.severity.pre-commit-merge-conflict";
985        git(&["config", "--add", key, "warn"]);
986        git(&["config", "--add", key, "block"]);
987
988        let raw = std::process::Command::new("git")
989            .args(["config", "--get-regexp", r"^amont\.severity\."])
990            .current_dir(&d)
991            .output()
992            .expect("git");
993        let batch = Overrides::from_config(Some(
994            String::from_utf8_lossy(&raw.stdout).trim().to_string(),
995        ));
996        let authority =
997            crate::git::stdout_in(&d, &["config", "--get", key]).and_then(|v| Severity::parse(&v));
998        let _ = std::fs::remove_dir_all(&d);
999
1000        assert_eq!(
1001            authority,
1002            Some(Severity::Block),
1003            "git applies the last entry"
1004        );
1005        assert_eq!(
1006            batch.0.get("pre-commit-merge-conflict").map(|(s, _)| *s),
1007            authority,
1008            "the batch reader disagreed with `--get`"
1009        );
1010    }
1011
1012    /// An unrecognised value is not an override, and must not shadow a valid
1013    /// earlier one either — a typo would otherwise silently restore the
1014    /// declared severity in a way nobody could see.
1015    #[test]
1016    fn an_unrecognised_value_clears_rather_than_overrides() {
1017        let o = Overrides::from_config(Some(
1018            "amont.severity.a warn\namont.severity.a advisory\namont.severity.b warn".to_string(),
1019        ));
1020        assert_eq!(o.0.get("a"), None, "a typo must not leave `warn` standing");
1021        assert_eq!(o.0.get("b").map(|(s, _)| *s), Some(Severity::Warn));
1022    }
1023
1024    #[test]
1025    fn names_are_unique_across_entrypoints_and_checks() {
1026        let mut seen = BTreeSet::new();
1027        for n in ENTRYPOINTS
1028            .iter()
1029            .map(|(n, _)| *n)
1030            .chain(CHECKS.iter().map(|check| check.name))
1031        {
1032            assert!(seen.insert(n), "duplicate registration: {n}");
1033        }
1034    }
1035
1036    /// Only FIVE files ship, and they are exactly the hook names git invokes.
1037    #[test]
1038    fn the_shipped_shims_are_exactly_the_git_invoked_hooks() {
1039        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
1040        let mut shipped: Vec<String> = std::fs::read_dir(dir)
1041            .expect("templates/hooks")
1042            .flatten()
1043            .map(|entry| entry.file_name().to_string_lossy().into_owned())
1044            .collect();
1045        shipped.sort();
1046        assert_eq!(
1047            shipped,
1048            vec![
1049                "commit-msg",
1050                "post-commit",
1051                "post-rewrite",
1052                "pre-commit",
1053                "pre-push",
1054                "prepare-commit-msg"
1055            ]
1056        );
1057        let none = crate::manifest::Manifest::default();
1058        for name in &shipped {
1059            assert!(
1060                lookup(name, &none).is_some(),
1061                "shipped shim {name:?} has no handler"
1062            );
1063        }
1064    }
1065
1066    /// Every check is reachable by name, which is how a shell — and the tests —
1067    /// invoke one directly.
1068    #[test]
1069    fn every_check_is_reachable_by_name() {
1070        let none = crate::manifest::Manifest::default();
1071        for check in CHECKS {
1072            assert!(
1073                lookup(check.name, &none).is_some(),
1074                "{} not reachable",
1075                check.name
1076            );
1077        }
1078        assert!(lookup("pre-commit-not-a-check", &none).is_none());
1079    }
1080
1081    /// pre-push is serial and fail-fast, so declaration order IS cost order.
1082    #[test]
1083    fn pre_push_runs_cheapest_first() {
1084        let order: Vec<&str> = super::stage_checks(Stage::PrePush)
1085            .map(|check| check.name)
1086            .collect();
1087        assert_eq!(
1088            order,
1089            vec![
1090                "pre-push-branch-protect",
1091                "pre-push-branch-pattern",
1092                "pre-push-secrets",
1093                "pre-push-pull-rebase",
1094                "pre-push-audit-go",
1095                "pre-push-audit-js",
1096                "pre-push-audit-python",
1097                "pre-push-audit-rust",
1098                "pre-push-run-tests-js",
1099                "pre-push-cargo-test",
1100                "pre-push-go-test",
1101                "pre-push-pytest",
1102            ]
1103        );
1104    }
1105
1106    /// What a check actually looks at, as opposed to what it DECLARES.
1107    ///
1108    /// `All` is a check that reads every staged path regardless of the
1109    /// extensions in its scope (ban-terms greps them all); `Exts(e)` is a check
1110    /// that filters by suffix, and `e` is the list it filters WITH.
1111    enum Consumes {
1112        All,
1113        Exts(&'static [&'static str]),
1114    }
1115
1116    /// Every check, and the file set it consumes. The table exists so a NEW
1117    /// check cannot be added without somebody stating the answer.
1118    ///
1119    /// The incident: `pre-commit-lint-json-yaml` declared
1120    /// `[".json", ".yaml", ".yml"]` in the registry while `lint_json_yaml::run`
1121    /// asked `staged_files` for `[".yaml"]`. `amont list` reported the check
1122    /// as covering `.yml`, the fleet dashboard agreed, and a staged, broken
1123    /// `x.yml` returned `Outcome::Passed` with no output whatsoever. Nothing
1124    /// connected the two lists, so nothing could notice.
1125    ///
1126    /// Each entry now names the module constant the check itself filters with,
1127    /// which is the same constant the registry declares its scope from — so
1128    /// this table cannot silently agree with a stale copy.
1129    const CONSUMED: &[(&str, Consumes)] = &[
1130        (
1131            "pre-commit-argo-lint",
1132            Consumes::Exts(crate::hooks::k8s::EXTS),
1133        ),
1134        // Each term filters candidates against its own language's extensions,
1135        // and `EXTS` is pinned to be exactly their union — so this names the
1136        // module constant the check itself filters with.
1137        (
1138            "pre-commit-ban-terms",
1139            Consumes::Exts(crate::hooks::ban_terms::EXTS),
1140        ),
1141        (
1142            "pre-commit-cargo-fmt",
1143            Consumes::Exts(crate::hooks::rust_tools::EXTS),
1144        ),
1145        (
1146            "pre-commit-clippy",
1147            Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1148        ),
1149        (
1150            "pre-commit-go-vet",
1151            Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1152        ),
1153        (
1154            "pre-commit-gofmt",
1155            Consumes::Exts(crate::hooks::go_tools::EXTS),
1156        ),
1157        (
1158            "pre-commit-kube-linter",
1159            Consumes::Exts(crate::hooks::k8s::EXTS),
1160        ),
1161        (
1162            "pre-commit-kubeconform",
1163            Consumes::Exts(crate::hooks::k8s::EXTS),
1164        ),
1165        (
1166            "pre-commit-lint-js",
1167            Consumes::Exts(crate::hooks::lint_js::EXTS),
1168        ),
1169        (
1170            "pre-commit-lint-json-yaml",
1171            Consumes::Exts(crate::hooks::lint_json_yaml::EXTS),
1172        ),
1173        ("pre-commit-merge-conflict", Consumes::All),
1174        ("pre-commit-package-lock", Consumes::All),
1175        // Declares `files: &[]` — it is opt-in by CONFIG, not by file type —
1176        // while consuming seventeen extensions. The other reason the assertion
1177        // is a subset check rather than an equality.
1178        (
1179            "pre-commit-prettier",
1180            Consumes::Exts(crate::hooks::prettier::EXTS),
1181        ),
1182        (
1183            "pre-commit-pyright",
1184            Consumes::Exts(crate::hooks::python_tools::EXTS),
1185        ),
1186        (
1187            "pre-commit-ruff",
1188            Consumes::Exts(crate::hooks::python_tools::EXTS),
1189        ),
1190        ("pre-commit-usual-name", Consumes::All),
1191        (
1192            "pre-commit-yamllint",
1193            Consumes::Exts(crate::hooks::yamllint::EXTS),
1194        ),
1195        (
1196            "pre-commit-shellcheck",
1197            Consumes::Exts(crate::hooks::shellcheck::EXTS),
1198        ),
1199        (
1200            "pre-commit-hadolint",
1201            Consumes::Exts(crate::hooks::hadolint::NAMES),
1202        ),
1203        (
1204            "pre-commit-helm-lint",
1205            Consumes::Exts(crate::hooks::helm::EXTS),
1206        ),
1207        ("pre-commit-large-files", Consumes::All),
1208        ("pre-commit-secrets", Consumes::All),
1209        ("pre-push-secrets", Consumes::All),
1210        ("pre-push-branch-protect", Consumes::All),
1211        ("pre-push-branch-pattern", Consumes::All),
1212        ("pre-push-pull-rebase", Consumes::All),
1213        (
1214            "pre-push-run-tests-js",
1215            Consumes::Exts(crate::hooks::run_tests::JS_EXTS),
1216        ),
1217        (
1218            "pre-push-pytest",
1219            Consumes::Exts(crate::hooks::python_tools::EXTS),
1220        ),
1221        (
1222            "pre-push-cargo-test",
1223            Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1224        ),
1225        (
1226            "pre-push-go-test",
1227            Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1228        ),
1229        // Reads every workflow file, and amont.conf (a name, not an ext).
1230        (
1231            "pre-commit-tree-parity",
1232            Consumes::Exts(crate::hooks::k8s::EXTS),
1233        ),
1234    ];
1235
1236    /// A declared scope must never promise more than the check consumes.
1237    ///
1238    /// Two halves, and the first is the one that earns its keep: a check with a
1239    /// non-empty `scope.files` that nobody has entered in `CONSUMED` fails the
1240    /// build, so adding a check forces somebody to state what it actually
1241    /// reads. The second half then pins that `scope.files ⊆ consumed`.
1242    ///
1243    /// SUBSET, not equality, deliberately: `prettier` declares `files: &[]` —
1244    /// it is opt-in by CONFIG, not by file type — while consuming seventeen
1245    /// extensions. Equality would forbid it.
1246    #[test]
1247    fn no_check_declares_a_file_type_it_does_not_consume() {
1248        for (name, _) in CONSUMED {
1249            assert!(
1250                CHECKS.iter().any(|check| check.name == *name),
1251                "CONSUMED names {name:?}, which is not a check"
1252            );
1253        }
1254        for check in CHECKS {
1255            let entry = CONSUMED.iter().find(|(name, _)| *name == check.name);
1256            if check.scope.files.is_empty() && entry.is_none() {
1257                continue;
1258            }
1259            let Some((_, consumes)) = entry else {
1260                panic!(
1261                    "{} declares scope.files {:?} but is missing from CONSUMED — \
1262                     say what it actually reads",
1263                    check.name, check.scope.files
1264                );
1265            };
1266            let Consumes::Exts(consumed) = consumes else {
1267                continue; // `All` consumes everything, so any declaration fits
1268            };
1269            for ext in check.scope.files {
1270                assert!(
1271                    consumed.contains(ext),
1272                    "{} declares {ext:?} in its scope but never asks for it — \
1273                     `{BIN} list` would report a coverage the check does not have",
1274                    check.name
1275                );
1276            }
1277        }
1278    }
1279
1280    /// A push suite must declare EVERY path it consumes, the converse of the
1281    /// test above, because the declaration is what the rest of the push
1282    /// reads: rehearsal picks its gates by `scope.touches`, pairing judges
1283    /// coverage by it, and `stamp_tips` stamps only a gate whose scope the
1284    /// push touched.
1285    ///
1286    /// The incident: `pre-push-cargo-test` declared `.rs` while
1287    /// `rust_tools::test` ran for `Cargo.toml` and `Cargo.lock` too. A
1288    /// release commit (version bump only) got "nothing to rehearse", then
1289    /// the push ran the full suite (557 s for relais 0.22.0), and the pass
1290    /// was never stamped, so every such push ran it again.
1291    #[test]
1292    fn a_push_suite_declares_every_path_it_consumes() {
1293        for name in ["pre-push-cargo-test", "pre-push-go-test", "pre-push-pytest"] {
1294            let check = CHECKS.iter().find(|c| c.name == name).expect(name);
1295            let Some((_, Consumes::Exts(consumed))) = CONSUMED.iter().find(|(n, _)| *n == name)
1296            else {
1297                panic!("{name} must consume an explicit file set");
1298            };
1299            for path in *consumed {
1300                assert!(
1301                    check.scope.files.contains(path),
1302                    "{name} runs for {path:?} but does not declare it: a push \
1303                     touching only {path:?} would be rehearsed as nothing to do, \
1304                     run at push time, and never stamped"
1305                );
1306            }
1307        }
1308    }
1309
1310    /// Which checks contain code that repairs and re-stages, stated by hand.
1311    ///
1312    /// `pre-commit-cargo-fmt` and `pre-commit-ruff` both declared
1313    /// `Fix::Rewrite` with NO fixing code anywhere — only `prettier.rs` and
1314    /// `manifest.rs` ever called `restage`/`fixing_enabled`. `amont list
1315    /// --json` reported `"fix":"rewrite"` for them regardless, and `agents_md`
1316    /// explicitly directs agents to trust that JSON, so an agent would set
1317    /// `amont.fix true` and wait for a repair that could never arrive.
1318    const HAS_FIXING_CODE: &[(&str, bool)] = &[
1319        ("pre-commit-agents-md", true),
1320        ("pre-commit-argo-lint", false),
1321        ("pre-commit-ban-terms", false),
1322        ("pre-commit-branch-pattern", false),
1323        ("pre-commit-branch-protect", false),
1324        ("pre-commit-cargo-fmt", true),
1325        ("pre-commit-clippy", false),
1326        ("pre-commit-go-vet", false),
1327        ("pre-commit-gofmt", true),
1328        ("pre-commit-kube-linter", false),
1329        ("pre-commit-kubeconform", false),
1330        ("pre-commit-lint-js", false),
1331        ("pre-commit-lint-json-yaml", false),
1332        ("pre-commit-manifest-trust", false),
1333        ("pre-commit-merge-conflict", false),
1334        ("pre-commit-package-lock", false),
1335        ("pre-commit-prettier", true),
1336        ("pre-commit-pyright", false),
1337        ("pre-commit-ruff", true),
1338        ("pre-commit-tree-parity", false),
1339        ("pre-commit-usual-name", false),
1340        ("pre-commit-yamllint", false),
1341        ("pre-commit-shellcheck", false),
1342        ("pre-commit-hadolint", false),
1343        ("pre-commit-helm-lint", false),
1344        ("pre-commit-large-files", false),
1345        ("pre-commit-secrets", false),
1346        ("pre-push-secrets", false),
1347        ("pre-push-branch-protect", false),
1348        ("pre-push-branch-pattern", false),
1349        ("pre-push-pull-rebase", false),
1350        ("pre-push-audit-go", false),
1351        ("pre-push-audit-js", false),
1352        ("pre-push-audit-python", false),
1353        ("pre-push-audit-rust", false),
1354        ("pre-push-run-tests-js", false),
1355        ("pre-push-cargo-test", false),
1356        ("pre-push-go-test", false),
1357        ("pre-push-pytest", false),
1358    ];
1359
1360    /// A `Fix::Rewrite` declaration is a PROMISE, and the set of checks that
1361    /// keep it must equal the set that make it.
1362    #[test]
1363    fn every_rewrite_declaration_has_a_fixer() {
1364        let declared: BTreeSet<&str> = CHECKS
1365            .iter()
1366            .filter(|check| check.fix == super::Fix::Rewrite)
1367            .map(|check| check.name)
1368            .collect();
1369        let implemented: BTreeSet<&str> = HAS_FIXING_CODE
1370            .iter()
1371            .filter(|(_, has)| *has)
1372            .map(|(name, _)| *name)
1373            .collect();
1374        assert_eq!(
1375            declared, implemented,
1376            "a check declaring Fix::Rewrite with no fixer lies to `{BIN} list --json`, \
1377             and a check with a fixer that does not declare it can never be reached"
1378        );
1379
1380        // …and the table must cover every check, so a new one cannot be added
1381        // without somebody answering the question.
1382        let listed: BTreeSet<&str> = HAS_FIXING_CODE.iter().map(|(name, _)| *name).collect();
1383        let all: BTreeSet<&str> = CHECKS.iter().map(|check| check.name).collect();
1384        assert_eq!(listed, all, "HAS_FIXING_CODE does not cover CHECKS");
1385    }
1386
1387    /// The reconciliation tests that used to live here are gone, and that is
1388    /// the point of the refactor: there is no second table to disagree with.
1389    /// The safety net is exactly the checks whose findings are mistakes in
1390    /// ANY codebase, with near-zero false positives — a conflict marker, an
1391    /// oversized blob, a leaked credential, a debug leftover in YOUR diff.
1392    /// Everything else is a house rule, and a house rule must not fire in a
1393    /// repository that never subscribed. Growing this list is a decision,
1394    /// not a default: lint-json-yaml stays OUT because Helm templates are
1395    /// invalid YAML and blocking a contribution to somebody else's chart
1396    /// repo is exactly the false positive this split exists to prevent.
1397    #[test]
1398    fn the_safety_net_is_exactly_the_low_false_positive_set() {
1399        let safety: Vec<&str> = CHECKS
1400            .iter()
1401            .filter(|c| c.reach == Reach::Safety)
1402            .map(|c| c.name)
1403            .collect();
1404        assert_eq!(
1405            safety,
1406            vec![
1407                "pre-commit-ban-terms",
1408                "pre-commit-large-files",
1409                "pre-commit-manifest-trust",
1410                "pre-commit-merge-conflict",
1411                "pre-commit-secrets",
1412                "pre-push-secrets",
1413            ]
1414        );
1415    }
1416
1417    #[test]
1418    fn every_check_declares_a_stage_and_a_scope() {
1419        assert_eq!(CHECKS.len(), 39);
1420        let pre_commit = super::stage_checks(Stage::PreCommit).count();
1421        let pre_push = super::stage_checks(Stage::PrePush).count();
1422        assert_eq!(
1423            pre_commit + pre_push,
1424            CHECKS.len(),
1425            "every check has a stage"
1426        );
1427    }
1428}