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