Skip to main content

greengate_runtime/
manifest.rs

1//! `amont.conf` — checks a repository declares for itself.
2//!
3//! A third party cannot add a Rust module without rebuilding this binary, so
4//! extension means declared commands.
5//!
6//! The manifest is **committed at the repository root**, and that is the point.
7//! `.git/hooks` is not committed, so under the old filename-prefix mechanism a
8//! team could never actually share a custom hook — every member had to install
9//! it by hand, and nothing told them when it changed. That flaw mattered more
10//! than the lexicographic ordering usually cited against prefixes.
11//!
12//! ```text
13//! # stage       name        scope   severity  command
14//! pre-commit    lint-shell  *.sh    block     scripts/lint-shell.sh
15//! pre-push      smoke       *       warn      make smoke
16//! ```
17//!
18//! Whitespace-delimited, in file order. TOML would be nicer to write and costs a
19//! dependency tree that would then run on every commit in ninety-six
20//! repositories; for four fields and a command, the twenty lines of parsing win.
21//! See `scripts/check-no-deps.sh` for why that trade is the default here.
22//!
23//! ## No shell
24//!
25//! The command is split on whitespace and executed directly. There is no shell,
26//! so no pipes, no redirection, no globbing and no quoting. Two reasons, and the
27//! second is the one that decided it: Windows has no `sh`, and every emulation
28//! of one this project has tried has been a source of bugs; and a manifest line
29//! that silently gained shell semantics would be a much larger thing to have
30//! introduced than it looks. A pipeline belongs in a script the line invokes.
31//!
32//! ## A line that cannot be understood is not skipped
33//!
34//! A malformed line means a check the repository asked for is not running, which
35//! is precisely the "looks verified, enforced nothing" failure `Outcome` exists
36//! to name. So a broken line still produces a check — one that runs to
37//! `Unavailable` and says why. It appears in the dispatcher's "could not run"
38//! roll-up like any other gap, rather than needing a mechanism of its own.
39
40use std::path::Path;
41use std::process::{Command, Stdio};
42
43use crate::check::{Check, Fix, Outcome, Scope, Severity, Stage};
44use crate::hooks::common::Restaged;
45use crate::registry::{Ctx, CHECKS, ENTRYPOINTS};
46
47pub const MANIFEST: &str = "amont.conf";
48
49/// Why a line could not be used.
50///
51/// A type rather than a `String`: the prose belongs in `Display`, and a caller
52/// that wants to ask "was this a duplicate?" should not have to grep for the
53/// word. The tests used to assert on substrings, which coupled them to wording
54/// and would have kept passing if the wording stayed while the meaning changed.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum ParseError {
57    MissingFields,
58    MissingName,
59    /// Names a check compiled into the binary.
60    NameTaken(String),
61    /// The name is a trigger, or carries one as a prefix.
62    ///
63    /// `pre-commit  pre-commit-clippy  …` would declare a check whose SHORT
64    /// name is another check's full id, so `hook.skip pre-commit-clippy` would
65    /// mean two things at once. The stage column supplies the trigger; writing
66    /// it again in the name is the one way to make an id ambiguous.
67    TriggerInName(String),
68    /// A second USABLE line claiming a name already claimed ON THE SAME
69    /// TRIGGER. The same name on both triggers is two checks, not a clash.
70    Duplicate(String),
71    BadStage(String),
72    BadScope(String),
73    BadSeverity(String),
74    /// A `tool` line with the wrong shape.
75    BadTool,
76    /// A `severity`/`skip`/`set` line with the wrong shape; carries the usage.
77    BadPolicyLine(&'static str),
78    /// A `set` line naming a key policy may not reach.
79    UnsettableKey(String),
80    /// `set planExempt` with a value other than `on`/`off`, or a second one.
81    /// attest's verifiers read this one line from the committed bytes with a
82    /// tolerant reading that matches only exactly `set planExempt off`, so any
83    /// other shape would silently mean "on" to them: it is loud here instead.
84    BadPlanExempt(String),
85    /// `set onBusy` other than `wait`/`defer`, `set slotWait` or
86    /// `set warnSlotWait` other than a whole number of seconds in 1..=3600, or
87    /// any of them set twice. Strict
88    /// like `planExempt`: a busy policy that silently meant something else
89    /// would move a gate to CI, or keep it here, without saying so.
90    BadBusyPolicy {
91        key: &'static str,
92        why: String,
93    },
94    /// `set rootRunsMembers` other than a comma-separated list of the npm
95    /// gate's script names or `none`, or set twice. Strict like the busy
96    /// policy: a list that silently meant something else would skip a member's
97    /// tests that nothing ran.
98    BadRootRunsMembers(String),
99    /// A `pre-push` line asked to rewrite files.
100    ///
101    /// Refused HERE, beside `NameTaken` and `Duplicate`, rather than as a
102    /// runtime "contract violation" at push time: same fact, discovered
103    /// earlier, by more people, at the moment it is cheapest to fix. A pre-push
104    /// hook must not modify the worktree or index — the pushed commit would
105    /// then differ from the tree the developer is looking at.
106    FixOnPrePush,
107    /// `platform=any` beside `fix`: the cluster proves only passes, and a
108    /// rewrite made in a pod never reaches the index (ADR-0016).
109    PlatformAnyWithFix,
110    /// `platform=any` beside `files`: the pod is not handed the matched set
111    /// (`AMONT_FILES`), so a pass would be over the wrong files (ADR-0016).
112    PlatformAnyWithFiles,
113    /// `platform=<word>` other than `any`. Loud rather than read as the
114    /// program name, which is what an older amont does with it.
115    BadPlatform(String),
116    /// `set executor` other than `cluster`/`local`, or `set executor` /
117    /// `set clusterPrepare` twice. Strict like `onBusy`: where a gate runs
118    /// must never silently mean something else.
119    BadClusterSetting {
120        key: &'static str,
121        why: String,
122    },
123    /// `docs-skip` on a pre-push line: a push has no staged change to judge as docs.
124    DocsSkipOnPrePush,
125    /// `index` on a pre-push line: a push has no index being committed.
126    IndexOnPrePush,
127    /// `index` beside `platform=any`: a pod cannot read this machine's index.
128    PlatformAnyWithIndex,
129    /// A `tree` line with the wrong shape; carries what was wrong.
130    BadTreeLine(&'static str),
131    /// A `tree` line naming a tool amont does not know how to attest.
132    BadTreeTool(String),
133    /// A `tree` gate name that cannot become a note's gate token.
134    BadTreeName(String),
135    /// A `tree` option amont does not know, or one whose value is unsafe.
136    BadTreeOption(String),
137    /// `{cache}` on a tool that has no cache, or more than once.
138    BadTreeCache,
139}
140
141impl std::fmt::Display for ParseError {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        match self {
144            ParseError::MissingFields => {
145                write!(f, "expected 5 fields: stage name scope severity command")
146            }
147            ParseError::MissingName => write!(f, "missing name"),
148            ParseError::NameTaken(n) => write!(f, "{n:?} already names a check"),
149            ParseError::TriggerInName(n) => write!(
150                f,
151                "{n:?} must not be a trigger or start with one — the stage column says which"
152            ),
153            ParseError::Duplicate(n) => write!(f, "{n:?} is declared twice on one trigger"),
154            ParseError::BadStage(t) => {
155                write!(f, "stage {t:?} must be `pre-commit` or `pre-push`")
156            }
157            ParseError::BadScope(t) => write!(
158                f,
159                "scope {t:?} must be `*`, `*.<ext>`, or a bare filename (no `/`), \
160                 optionally followed by `+<file>` the repository must carry"
161            ),
162            ParseError::BadTool => write!(
163                f,
164                "a tool pin is exactly `tool <program> <version-substring>`"
165            ),
166            ParseError::BadPolicyLine(usage) => write!(f, "a policy line is `{usage}`"),
167            ParseError::BadPlanExempt(why) => write!(f, "set planExempt: {why}"),
168            ParseError::BadBusyPolicy { key, why } => write!(f, "set {key}: {why}"),
169            ParseError::BadRootRunsMembers(why) => write!(f, "set rootRunsMembers: {why}"),
170            ParseError::UnsettableKey(k) => write!(
171                f,
172                "set {k:?} is not a policy-settable key — see docs/custom-checks.md"
173            ),
174            ParseError::BadTreeLine(what) => write!(
175                f,
176                "a tree gate is `tree <name> <tool> <scope> attest [cwd=<dir>] \
177                 [inputs=<path>,...] <command>` — {what}"
178            ),
179            ParseError::BadTreeTool(t) => write!(
180                f,
181                "tree tool {t:?} must be one of: {}",
182                TreeTool::ALL
183                    .iter()
184                    .map(|t| t.as_str())
185                    .collect::<Vec<_>>()
186                    .join(", ")
187            ),
188            ParseError::BadTreeName(n) => write!(
189                f,
190                "tree gate name {n:?} must match [A-Za-z0-9][A-Za-z0-9._-]{{0,58}}"
191            ),
192            ParseError::BadTreeOption(o) => write!(
193                f,
194                "tree option {o:?}: only `cwd=<relative dir>` and \
195                 `inputs=<path>,...` (literal paths, no globs, no `..`)"
196            ),
197            ParseError::BadTreeCache => write!(
198                f,
199                "`{{cache}}` may appear once, and only for eslint or prettier"
200            ),
201            ParseError::FixOnPrePush => write!(
202                f,
203                "`fix` is only for pre-commit — a pre-push hook must not rewrite files"
204            ),
205            ParseError::PlatformAnyWithFix => write!(
206                f,
207                "`platform=any` cannot be combined with `fix` — the cluster proves passes, \
208                 it never rewrites files"
209            ),
210            ParseError::PlatformAnyWithFiles => write!(
211                f,
212                "`platform=any` cannot be combined with `files` — the cluster is not handed \
213                 the matched file set"
214            ),
215            ParseError::BadPlatform(word) => {
216                write!(f, "{word:?}: the only platform marker is `platform=any`")
217            }
218            ParseError::BadClusterSetting { key, why } => write!(f, "set {key}: {why}"),
219            ParseError::DocsSkipOnPrePush => write!(
220                f,
221                "`docs-skip` is only for pre-commit — a push has no staged change to judge"
222            ),
223            ParseError::IndexOnPrePush => write!(
224                f,
225                "`index` is only for pre-commit — a push has no index being committed"
226            ),
227            ParseError::PlatformAnyWithIndex => write!(
228                f,
229                "`platform=any` cannot be combined with `index` — the cluster cannot read \
230                 this machine's index"
231            ),
232            ParseError::BadSeverity(t) => {
233                write!(f, "severity {t:?} must be `block` or `warn`")
234            }
235        }
236    }
237}
238
239/// A line that parsed. Every field means something.
240///
241/// `program` and `args` rather than one `argv`: a runnable check must have a
242/// command, and splitting the head off makes that structural instead of a
243/// `split_first` guard that can only ever be dead code.
244#[derive(Debug, Clone, PartialEq, Eq)]
245pub struct Declared {
246    /// `Fix::Rewrite` when the command column began `fix `.
247    pub fix: Fix,
248    /// The command column carried the `files` marker.
249    pub files: bool,
250    /// The command column began `docs-skip ` — do not run on a commit whose
251    /// staged change only edits existing documentation (`staged_docs_only`).
252    pub docs_skip: bool,
253    /// The command column carried the `heavy` marker: the check compiles or
254    /// executes the product and takes a host slot (ADR-0013).
255    pub heavy: bool,
256    /// Where the command may run, and what it may read there: see [`RunsOn`].
257    pub runs_on: RunsOn,
258    /// The 1-based line of the manifest that declares it, for a message that
259    /// sends a person to the line to edit.
260    pub lineno: usize,
261    pub name: String,
262    pub stage: Stage,
263    pub severity: Severity,
264    /// Extensions that gate it. Empty means any change — the `*` scope.
265    pub exts: Vec<String>,
266    /// Exact filenames that gate it — the scope column's bare tokens.
267    pub names: Vec<String>,
268    /// Directory triggers, each `dir/**/*.ext` — see `parse_scope`.
269    pub dirs: Vec<String>,
270    /// Files the REPOSITORY must carry for this check to apply at all — the
271    /// scope column's `+` half. Empty means always applicable, which is what
272    /// every declaration meant before `amont add` made a line something you
273    /// could acquire rather than write.
274    pub opt_in: Vec<String>,
275    pub program: String,
276    pub args: Vec<String>,
277}
278
279impl Declared {
280    /// `<trigger>-<name>`, the same shape a built-in has.
281    ///
282    /// This is what `hook.skip` and `amont.severity.<key>` resolve against,
283    /// so a declared check answers to its trigger and its short name exactly as
284    /// a compiled-in one does. Before it had an id, `hook.skip pre-commit`
285    /// silenced fifteen built-ins and left every declared check running.
286    pub fn id(&self) -> String {
287        format!("{}-{}", self.stage.as_str(), self.name)
288    }
289
290    /// The command as written, for display.
291    pub fn command(&self) -> String {
292        std::iter::once(self.program.as_str())
293            .chain(self.args.iter().map(String::as_str))
294            .collect::<Vec<_>>()
295            .join(" ")
296    }
297}
298
299/// One manifest line: usable, or not.
300///
301/// A SUM, not a struct with an `Option<why>` beside the fields. The struct
302/// form let a broken line carry a severity, a scope and an argv that meant
303/// nothing — and it produced a wrong diagnosis: because broken and usable
304/// entries shared one list, a valid line was rejected as "declared twice" for
305/// colliding with a line that could not run. Dedup now sees only `Usable`.
306///
307/// Separate from `External` because the fleet reads ninety-six manifests and may
308/// re-read them on every refresh, while `External` holds a `Scope` whose
309/// `&'static` slices are LEAKED.
310/// `tool <program> <version-substring>` — a version this repository expects
311/// of a tool its checks drive, so cross-machine skew is a printed fact
312/// instead of "the hook is flaky here". Verified once per hook run, warn-only.
313#[derive(Debug, Clone, PartialEq, Eq)]
314pub struct ToolPin {
315    pub program: String,
316    /// A substring `<program> --version`'s first line must contain — `0.6.`
317    /// pins a minor, `0.6.3` pins a patch. Substring, not semver: the point
318    /// is agreement between machines, not range arithmetic.
319    pub want: String,
320}
321
322/// The tools a `tree` gate may name. The tool is declared, never guessed from
323/// the command: `npm run lint` says nothing about what it runs, and amont needs
324/// to know what `{cache}` expands to and how to read the version the gate
325/// actually executes (ADR-0024, `ci.skip-needs-the-same-command`).
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327pub enum TreeTool {
328    Eslint,
329    Prettier,
330    Ruff,
331    Pyright,
332    Gofmt,
333}
334
335impl TreeTool {
336    pub const ALL: &'static [TreeTool] = &[
337        TreeTool::Eslint,
338        TreeTool::Prettier,
339        TreeTool::Ruff,
340        TreeTool::Pyright,
341        TreeTool::Gofmt,
342    ];
343
344    pub fn parse(token: &str) -> Option<TreeTool> {
345        TreeTool::ALL.iter().copied().find(|t| t.as_str() == token)
346    }
347
348    pub fn as_str(self) -> &'static str {
349        match self {
350            TreeTool::Eslint => "eslint",
351            TreeTool::Prettier => "prettier",
352            TreeTool::Ruff => "ruff",
353            TreeTool::Pyright => "pyright",
354            TreeTool::Gofmt => "gofmt",
355        }
356    }
357
358    /// Whether the tool has an on-disk cache `{cache}` can point at. Ruff has
359    /// one too, but it manages it itself and a whole-tree run is already
360    /// sub-second; pyright and gofmt have none.
361    pub fn has_cache(self) -> bool {
362        matches!(self, TreeTool::Eslint | TreeTool::Prettier)
363    }
364}
365
366/// `tree <name> <tool> <scope> attest [cwd=<dir>] [inputs=<path>,...] <command>`
367/// — a whole-tree check whose pass may be ATTESTED so CI skips the step that
368/// runs the same command (ADR-0024).
369///
370/// The declaration IS the CI command. `normalized()` is what the workflow
371/// step's `run:` must equal, character for character; `{cache}` is the only
372/// thing amont may add, and it never changes a verdict. A tree gate never
373/// decides a commit: it is not a pre-commit or pre-push check, so it has no
374/// severity column — `attest` stands where the severity would be, saying what
375/// the line is for.
376#[derive(Debug, Clone, PartialEq, Eq)]
377pub struct TreeGate {
378    pub name: String,
379    pub tool: TreeTool,
380    pub exts: Vec<String>,
381    pub names: Vec<String>,
382    pub dirs: Vec<String>,
383    pub opt_in: Vec<String>,
384    /// The directory the command runs in, relative to the repository root.
385    pub cwd: Option<String>,
386    /// Extra paths that belong to the gate's cache namespace.
387    pub inputs: Vec<String>,
388    /// The command as declared, `{cache}` and all.
389    pub command: String,
390    pub lineno: usize,
391}
392
393/// The placeholder a `tree` command may carry for the tool's cache flags.
394pub const CACHE_PLACEHOLDER: &str = "{cache}";
395
396impl TreeGate {
397    /// The gate token in the attestation note — what CI's `if:` names.
398    pub fn id(&self) -> String {
399        format!("tree-{}", self.name)
400    }
401
402    /// The key a tree proof is stamped under. Distinct from every commit-stamp
403    /// token (short names like `cargo-test`) by its `:`, so no per-commit
404    /// reader can mistake a staged-only pass for a whole-tree one.
405    pub fn stamp_key(&self) -> String {
406        format!("tree:{}", self.name)
407    }
408
409    /// The command CI must run: `{cache}` removed, then a dangling trailing
410    /// `--` (left behind by `npm run lint -- {cache}`), then whitespace
411    /// collapsed.
412    pub fn normalized(&self) -> String {
413        normalize_command(&self.command)
414    }
415}
416
417/// See [`TreeGate::normalized`]. Free so `tree-parity` can normalize a
418/// workflow's `run:` the same way.
419pub fn normalize_command(command: &str) -> String {
420    let mut words: Vec<&str> = command
421        .split_whitespace()
422        .filter(|w| *w != CACHE_PLACEHOLDER)
423        .collect();
424    if words.last() == Some(&"--") {
425        words.pop();
426    }
427    words.join(" ")
428}
429
430/// A committed policy statement about a BUILT-IN (or declared) check — the
431/// team's decision, shipped with the repository, trust-gated like everything
432/// else the manifest says. See `policy`.
433#[derive(Debug, Clone, PartialEq, Eq)]
434pub enum PolicyLine {
435    /// `severity <check|short-name|trigger> warn|block`
436    Severity { target: String, severity: Severity },
437    /// `skip <check|short-name|trigger>`
438    Skip { target: String },
439    /// `set <key> <value>` — a committed default for an allowlisted
440    /// `amont.*` config key. `key` is the FULL git key (`amont.timeout`),
441    /// canonicalised from whatever case the file used, because git keys are
442    /// case-insensitive and a policy file stricter than git is a trap.
443    Set { key: String, value: String },
444}
445
446/// The scripts the npm push gate (`pre-push-run-tests-js`) runs, cheapest
447/// first. Defined here, where `set rootRunsMembers` validates against it, so the
448/// manifest does not depend on a hook; the gate reads it back from here.
449pub const NPM_GATE_SCRIPTS: [&str; 3] = ["typecheck", "test:unit", "test"];
450
451/// The keys `set` may reach, in canonical spelling. Deliberately absent:
452/// `fix` (a committed file must not change what already-trusted commands may
453/// DO to your working tree — a different consent than "I read these
454/// commands"), `trusted`, `conventions`, `recordBypasses`, `progress`,
455/// `knownIdentity`, and the `severity.*` family (its own line kind).
456pub const SETTABLE: &[&str] = &[
457    "largeFileWarn",
458    "largeFileBlock",
459    "commit.gitmoji",
460    "commit.subjectMax",
461    "commit.descriptionMax",
462    "commit.bodyWrap",
463    "autoRebase",
464    "timeout",
465    // How long a tool may sit in a declared lock wait (ADR-0009). A property
466    // of the project's build — a workspace whose cold check holds the cargo
467    // lock for ten minutes is the project's to know — and, like `timeout`,
468    // only ever lengthens or shortens a wait; it enforces nothing.
469    "lockWait",
470    "testPushedTree",
471    "minVersion",
472    // A snapshot is not a workspace. `testPushedTree` is settable here, so a
473    // repository can say "run the gate on a checkout of the commit" — and
474    // before this it could not say how to make that checkout runnable, which
475    // for a pnpm or npm workspace means an install. The repository is what
476    // knows; requiring every clone to discover `git config
477    // amont.snapshotPrepare` by hand made the declarable half useless.
478    //
479    // Safe on the same terms as a declared check: policy is populated ONLY
480    // when the manifest is trusted, `PolicyLine::describe` puts the command
481    // in front of the person consenting, and any edit revokes that consent.
482    // A local `git config` still outranks it (see `policy`'s ladder), so a
483    // developer can override without touching the file.
484    "snapshotPrepare",
485    // The two halves of making a snapshot runnable that amont does itself.
486    // `snapshotDeps` picks how dependencies arrive (`install`, `reuse`,
487    // `off`); `snapshotCarry` names untracked files copied in from the
488    // working tree — never over tracked content, which is refused. Both are
489    // properties of the project, and trust-gated like `snapshotPrepare`.
490    "snapshotDeps",
491    "snapshotCarry",
492    // Ordering only. `amont.order evidence` permutes the push gates a
493    // repository already runs, using that machine's own record of them; it
494    // adds nothing, removes nothing and skips nothing, so it grants a
495    // committed file no power over what is enforced — which is the line
496    // `fix` and the `severity.*` family are kept on the other side of. Which
497    // ORDER a team's suites are attempted in is a property of the project
498    // (the four-minute suite, the five-second audit), so the project is the
499    // right place to be able to say it; a local `git config` still wins.
500    "order",
501    // Tree gates (ADR-0024). Whether they run, how long they may add to a
502    // commit after its checks, and which ignored paths are the repository's
503    // reproducible outputs rather than inputs a linter could import. None of
504    // them decides a commit; they only decide whether a stamp is earned.
505    "treeLint",
506    "treeLintSlack",
507    "treeLintWait",
508    "treeLintRehearsalTimeout",
509    "snapshotPrepareOutputs",
510    // Whether a closing plan commit may reuse a gate's result (attest 1.5.0,
511    // "Canonical tree"). `off` for a repository whose gate reads the contents
512    // of a plan. It only ever narrows, so attest's verifiers and every producer
513    // read the committed line itself, trusted or not, and the line is strict:
514    // exactly `on` or `off`, once.
515    "planExempt",
516    // What a Heavy check does when no host slot frees (ADR-0013). `defer`
517    // moves the gate to CI, so a repository says it only where its CI runs
518    // that gate; strict like `planExempt`: exactly `wait` or `defer`, and a
519    // whole number of seconds for `slotWait`, each once.
520    "onBusy",
521    // Which of the npm gate's scripts a repository's ROOT package already runs
522    // for every workspace member, so the push does not run them again in each
523    // changed member. Policy, strict and set once; a comma-separated list of
524    // the gate's script names, or `none`. A local `git config` may only remove
525    // names from it, never add one (`hooks::run_tests::root_declaration`).
526    "rootRunsMembers",
527    "slotWait",
528    // How long a heavy `warn` gate of land's pre-stage waits for a slot
529    // before it runs unqueued (ADR-0013): a whole number of seconds, once.
530    "warnSlotWait",
531    // Whether pre-commit's Heavy checks wait for its Light ones and are
532    // skipped when one blocks (ADR-0020). On by default; `false` runs every
533    // check at once, as before 2.1. A local `git config` outranks it, and
534    // `AMONT_FAIL_FAST` outranks both for one run.
535    "failFast",
536    // Where a `platform=any` gate runs (ADR-0016): `cluster` sends it to the
537    // homelab as one Kubernetes Job, `local` (the default) keeps it here, and
538    // `clusterPrepare` is the shell command the Job's `prepare` container
539    // runs before the gate. Policy, so effective only from a trusted
540    // manifest; strict and set once, like `onBusy`. A local `git config
541    // amont.executor local` may turn it off, never on.
542    "executor",
543    "clusterPrepare",
544];
545
546impl PolicyLine {
547    /// The one-line rendering the trust prompt shows — consent must see the
548    /// policy it is granting.
549    pub fn describe(&self) -> String {
550        match self {
551            PolicyLine::Severity { target, severity } => {
552                format!("severity  {target}  {}", severity.as_str())
553            }
554            PolicyLine::Skip { target } => format!("skip      {target}"),
555            PolicyLine::Set { key, value } => format!("set       {key}  {value}"),
556        }
557    }
558}
559
560#[derive(Debug, Clone, PartialEq, Eq)]
561pub enum Line {
562    Usable(Declared),
563    /// A tool version pin — carries no check.
564    Tool(ToolPin),
565    /// A policy statement — carries no check either. The line number rides
566    /// along because a "names no check here" note must point somewhere.
567    Policy {
568        what: PolicyLine,
569        lineno: usize,
570    },
571    /// A whole-tree gate that may be attested — carries no check: it never
572    /// decides a commit or a push (ADR-0024).
573    Tree(TreeGate),
574    Broken {
575        /// The declared name, or `<file>:<lineno>` when the line has none — a
576        /// gap has to be nameable to be reportable.
577        name: String,
578        /// Broken lines land on pre-commit unless the stage token parsed: seen
579        /// on every commit beats seen on every push.
580        stage: Stage,
581        lineno: usize,
582        why: ParseError,
583    },
584}
585
586impl Line {
587    pub fn name(&self) -> &str {
588        match self {
589            Line::Usable(d) => &d.name,
590            Line::Tool(pin) => &pin.program,
591            Line::Policy {
592                what: PolicyLine::Severity { target, .. } | PolicyLine::Skip { target },
593                ..
594            } => target,
595            Line::Policy {
596                what: PolicyLine::Set { key, .. },
597                ..
598            } => key,
599            Line::Tree(gate) => &gate.name,
600            Line::Broken { name, .. } => name,
601        }
602    }
603
604    /// Does this line declare a CHECK? `Tool` and `Policy` lines do not, and
605    /// every consumer that projects lines into checks — `parse`, the trust
606    /// prompt, the fleet's declared column — must filter on this rather than
607    /// pattern-match variants it will forget to extend. A `Broken` line IS a
608    /// check (one that runs to Unavailable and says why).
609    pub fn is_check(&self) -> bool {
610        matches!(self, Line::Usable(_) | Line::Broken { .. })
611    }
612    pub fn stage(&self) -> Stage {
613        match self {
614            Line::Usable(d) => d.stage,
615            // A pin has no stage; it is verified at both. The value only
616            // feeds displays that will not ask a pin for one. Policy lines
617            // likewise — `is_check()` keeps both out of anything that would.
618            Line::Tool(_) | Line::Policy { .. } | Line::Tree(_) => Stage::PreCommit,
619            Line::Broken { stage, .. } => *stage,
620        }
621    }
622    /// `Some(reason)` when this line declares a check that cannot run.
623    pub fn broken(&self) -> Option<String> {
624        match self {
625            Line::Usable(_) | Line::Tool(_) | Line::Policy { .. } | Line::Tree(_) => None,
626            Line::Broken { lineno, why, .. } => Some(format!("line {lineno}: {why}")),
627        }
628    }
629
630    /// `<trigger>-<name>`, matching `Declared::id` and `External::id`. A broken
631    /// line has one too: `hook.skip pre-commit` should silence its nag exactly
632    /// as it silences the checks that do run.
633    pub fn id(&self) -> String {
634        format!("{}-{}", self.stage().as_str(), self.name())
635    }
636
637    /// Consume into the identity every line has, and either the declaration or
638    /// the reason there is none.
639    ///
640    /// Both consumers — `External::from` and the fleet's projection — used to
641    /// destructure this by hand, and both carried an arm for a combination the
642    /// type forbids, because they computed the reason BEFORE matching. Written
643    /// once, that arm has nowhere to appear.
644    pub fn into_parts(self) -> (String, Stage, Result<Declared, String>) {
645        let name = self.name().to_string();
646        let stage = self.stage();
647        let parsed = match self {
648            Line::Usable(d) => Ok(d),
649            // Reachable only through a consumer that skipped `is_check()` —
650            // kept total so the type stays honest, worded so a leak is
651            // recognisable in whatever display it lands in.
652            Line::Tool(pin) => Err(format!("tool pin: {} {}", pin.program, pin.want)),
653            Line::Policy { what, .. } => Err(format!("policy: {}", what.describe())),
654            Line::Tree(gate) => Err(format!("tree gate: {} {}", gate.name, gate.command)),
655            Line::Broken { lineno, why, .. } => Err(format!("line {lineno}: {why}")),
656        };
657        (name, stage, parsed)
658    }
659}
660
661/// What a pre-commit declaration fires on once its push twins' files count
662/// too, and which twins those are: the scope, and the id and scope of each
663/// gate whose reach it borrowed (`pre-push-cargo-test`), so a commit can say
664/// which gate reads the file it is testing.
665#[derive(Debug, Clone, PartialEq, Eq)]
666pub struct Trigger {
667    pub scope: Scope,
668    /// Every push gate whose files it covers: a declared `pre-push` line
669    /// before the built-in gate, each with the scope it acts on.
670    pub twins: Vec<(String, Scope)>,
671}
672
673impl Trigger {
674    /// The id of the first twin that acts on `path`; the first twin when none
675    /// does, which cannot happen for a path the trigger covers beyond the
676    /// declaration's own scope.
677    pub fn twin_for(&self, path: &str) -> &str {
678        self.twins
679            .iter()
680            .find(|(_, twin)| twin.covers(path))
681            .or(self.twins.first())
682            .map_or("its push twin", |(id, _)| id.as_str())
683    }
684
685    /// Every twin's id, in order, for a row that lists them.
686    pub fn twin_ids(&self) -> Vec<&str> {
687        self.twins.iter().map(|(id, _)| id.as_str()).collect()
688    }
689}
690
691/// A check a repository declares, rather than one compiled in.
692pub struct External {
693    /// `<trigger>-<name>` — what `hook.skip` and `amont.severity.<key>`
694    /// resolve against, and what `Check::name` returns. Built-ins have had this
695    /// shape all along; declared checks answering to a bare name were invisible
696    /// to `hook.skip pre-commit`.
697    pub id: String,
698    /// The name as written in the manifest — the "short name" of the vocabulary
699    /// — used for messages. A line too malformed to name itself falls back to
700    /// its position, and reading `pre-commit-amont.conf:3` back to somebody
701    /// helps nobody.
702    pub short_name: String,
703    pub stage: Stage,
704    pub kind: Kind,
705    /// The 1-based line of the manifest that declares it, `None` for a line
706    /// that carries no position: what a message names when it sends a person
707    /// to the line to edit.
708    pub lineno: Option<usize>,
709}
710
711/// Where a declared command runs, and what it reads there. One value, so the
712/// combination nothing can honour — a pod reading this machine's index —
713/// cannot be built.
714#[derive(Debug, Clone, Copy, PartialEq, Eq)]
715pub enum RunsOn {
716    /// On this machine. `reads_index`: the command column carried `index`,
717    /// so the command reads the index `git commit` is sealing through git
718    /// itself (`git diff --cached`) and is handed `GIT_INDEX_FILE`, the one
719    /// git variable a declared command keeps (see `External::execute`).
720    Here { reads_index: bool },
721    /// The command column carried `platform=any`: the verdict does not depend
722    /// on the platform, so a trusted repository with `set executor cluster`
723    /// may run it as a Kubernetes Job (ADR-0016).
724    AnyPlatform,
725}
726
727/// The two things an external can be. `Scope` and `Severity` live only on the
728/// runnable side, so a broken external cannot carry a severity nobody applies.
729pub enum Kind {
730    Runnable {
731        scope: Scope,
732        severity: Severity,
733        program: String,
734        args: Vec<String>,
735        fix: Fix,
736        /// The command column began `files ` — append the matched paths to
737        /// the argv, the way a builtin hands its tool the staged list.
738        files: bool,
739        /// The command column began `docs-skip ` — see `Declared::docs_skip`.
740        docs_skip: bool,
741        /// The command column carried `heavy` — see `Declared::heavy`.
742        heavy: bool,
743        /// See [`RunsOn`]. A `Runnable` exists only for a trusted manifest
744        /// (`gate`), so `AnyPlatform` is always the trusted declaration.
745        runs_on: RunsOn,
746        /// What this pre-commit declaration would fire on if its push twin's
747        /// files counted too: its own scope united with the twin's. Computed
748        /// at load (`attach_twin_scopes`), and NOT applied until
749        /// [`Manifest::resolve_triggers`] has judged the declaration blocking:
750        /// until then [`External::effective_scope`] is the declaration's own,
751        /// so a caller that forgets the resolve behaves as before the twin
752        /// existed — narrow, and the push runs the suite.
753        pending_trigger: Option<Box<Trigger>>,
754        /// The pending trigger, once resolved for a declaration that blocks.
755        /// What the declaration fires on at commit and is judged on at push.
756        /// Boxed, like the pending one: most declarations carry neither, and
757        /// two inline scopes made this variant several times the size of
758        /// `Unusable`.
759        trigger: Option<Box<Trigger>>,
760    },
761    Unusable {
762        why: String,
763        /// The severity the line declares, when it parsed and only trust is
764        /// withheld: kept for `amont list` to report, never applied. `None`
765        /// for a line that did not parse.
766        declared: Option<Severity>,
767    },
768}
769
770/// The scripts already vouched for against the staged tree, read once per
771/// hook process — a stage's externals run concurrently, and each asking git
772/// itself would be two spawns per check for one answer.
773fn vouched_for_staged_tree() -> &'static std::collections::HashSet<String> {
774    static VOUCHED: std::sync::OnceLock<std::collections::HashSet<String>> =
775        std::sync::OnceLock::new();
776    VOUCHED.get_or_init(crate::gate_stamp::vouched_for_staged_tree)
777}
778
779/// What a pre-commit command is told about the index being committed.
780#[derive(Debug, PartialEq, Eq)]
781enum IndexEnv {
782    /// These variables, in this order.
783    Set(Vec<(&'static str, std::path::PathBuf)>),
784    /// No index to read: refused, never run blind. An unmarked gate may read
785    /// `$AMONT_INDEX_FILE` and fall back to the default index, so it is
786    /// refused too: a blind pass would be stamped onto the committed tree.
787    Refuse(String),
788}
789
790/// The variables `lookup` gives a pre-commit command that runs as `runs_on`
791/// says, or why it gets none. Not knowing the index is the original bug,
792/// said out loud.
793fn index_env(
794    lookup: Result<&crate::hooks::common::CommitIndex, &crate::hooks::common::IndexLookupError>,
795    runs_on: RunsOn,
796    gate: &str,
797) -> IndexEnv {
798    let reads_index = runs_on == RunsOn::Here { reads_index: true };
799    match lookup {
800        Ok(index) => {
801            let mut vars = vec![
802                (crate::hooks::common::INDEX_ENV, index.file.clone()),
803                (
804                    crate::hooks::common::INDEX_GIT_DIR_ENV,
805                    index.git_dir.clone(),
806                ),
807            ];
808            if reads_index {
809                vars.push(("GIT_INDEX_FILE", index.file.clone()));
810            }
811            IndexEnv::Set(vars)
812        }
813        Err(why) => IndexEnv::Refuse(format!(
814            "{gate}: cannot locate the index being committed ({why}); {} cannot be set",
815            crate::hooks::common::INDEX_ENV
816        )),
817    }
818}
819
820impl External {
821    /// The scope this declaration fires on and is judged on: its resolved
822    /// trigger when it has one (its own scope united with its push twin's),
823    /// else the scope as written. `Scope::ALWAYS` for an unusable one.
824    pub fn effective_scope(&self) -> Scope {
825        match &self.kind {
826            Kind::Runnable {
827                trigger: Some(t), ..
828            } => t.scope,
829            Kind::Runnable { scope, .. } => *scope,
830            Kind::Unusable { .. } => Scope::ALWAYS,
831        }
832    }
833
834    /// Whether this is a commit-time declaration that blocks and is not
835    /// switched off: the ones whose runs earn stamps. The ONE predicate
836    /// `blocking_commit_decls` and [`Manifest::resolve_triggers`] share, so the
837    /// two cannot disagree about which declarations count, and it lives on the
838    /// type it judges, not in a hook that depends on this module.
839    pub fn blocks_at_commit(
840        &self,
841        severities: &crate::registry::Overrides,
842        skips: &[String],
843    ) -> bool {
844        matches!(self.kind, Kind::Runnable { .. })
845            && self.stage == Stage::PreCommit
846            && severities.of(self) == Severity::Block
847            && !skips
848                .iter()
849                .any(|skip| crate::skip_suppresses(&self.id, skip))
850    }
851
852    /// The first staged path this declaration tests only because its push
853    /// twin reads it, with that twin's id; `None` when its own scope touches
854    /// the staged set (or it was not widened).
855    fn twin_only_path<'a>(&'a self, staged: &'a [String]) -> Option<(&'a str, &'a str)> {
856        let Kind::Runnable {
857            scope,
858            trigger: Some(trigger),
859            ..
860        } = &self.kind
861        else {
862            return None;
863        };
864        if scope.touches(staged) {
865            return None;
866        }
867        staged
868            .iter()
869            .find(|path| trigger.scope.covers(path))
870            .map(|path| (path.as_str(), trigger.twin_for(path)))
871    }
872
873    /// What the `amont.conf` line declares, trusted or not: reading the file
874    /// applies nothing, so a reader may be told what it says. `None` for a
875    /// line that did not parse.
876    pub fn manifest_severity(&self) -> Option<Severity> {
877        match &self.kind {
878            Kind::Runnable { severity, .. } => Some(*severity),
879            Kind::Unusable { declared, .. } => *declared,
880        }
881    }
882}
883
884impl Check for External {
885    fn name(&self) -> &str {
886        &self.id
887    }
888    fn stage(&self) -> Stage {
889        self.stage
890    }
891    /// Derived for an unusable check rather than stored: it never runs, so its
892    /// scope is a question with no answer, and computing one here keeps the
893    /// DATA from carrying a value that means nothing.
894    fn scope(&self) -> Scope {
895        self.effective_scope()
896    }
897    fn severity(&self) -> Severity {
898        match &self.kind {
899            Kind::Runnable { severity, .. } => *severity,
900            // Never consulted: an unusable check reports `Unavailable`, which
901            // no severity can turn into a block.
902            Kind::Unusable { .. } => Severity::Warn,
903        }
904    }
905
906    /// Heavy when the line says `heavy`, or when it MOVES a built-in Heavy
907    /// gate: `pre-commit cargo-test` runs the suite `pre-push-cargo-test`
908    /// would, and must queue as that gate does (ADR-0013).
909    fn weight(&self) -> crate::host_slots::Weight {
910        let moved = crate::host_slots::HEAVY
911            .iter()
912            .any(|h| crate::short_name(h) == self.short_name);
913        match &self.kind {
914            Kind::Runnable { heavy: true, .. } => crate::host_slots::Weight::Heavy,
915            Kind::Runnable { .. } if moved => crate::host_slots::Weight::Heavy,
916            Kind::Runnable { .. } | Kind::Unusable { .. } => crate::host_slots::Weight::Light,
917        }
918    }
919
920    fn run(&self, ctx: &Ctx) -> Outcome {
921        let settings = ctx.settings;
922        let effective = self.effective_scope();
923        let (scope, program, args, fix, files, docs_skip, runs_on) = match &self.kind {
924            Kind::Runnable {
925                program,
926                args,
927                fix,
928                files,
929                docs_skip,
930                runs_on,
931                ..
932            } => (
933                &effective, program, args, *fix, *files, *docs_skip, *runs_on,
934            ),
935            Kind::Unusable { why, .. } => {
936                crate::hooks::common::warn(&format!(
937                    "{MANIFEST}: {} — {}",
938                    crate::ui::highlight(&self.short_name),
939                    // Carries repo tokens: `BadStage("…")` quotes the manifest.
940                    crate::ui::sanitize(why)
941                ));
942                return Outcome::Unavailable;
943            }
944        };
945
946        // The scope gate lives HERE, unlike a built-in's, which enforces its own
947        // in its first three lines. A declared command has no way to know what
948        // was staged, so if this did not gate it, `*.sh` would run on every
949        // commit and the column would be decoration.
950        //
951        // Which files to test against depends on the stage: what is staged for
952        // a commit, what is being pushed for a push. `*` short-circuits before
953        // either is computed, which is the common case.
954        // A check whose whole job is to rewrite has nothing to say when nobody
955        // asked for rewriting — so it does not RUN, rather than running and
956        // having its result discarded. Gating only the re-staging let the
957        // command edit files with `amont.fix` off, which is precisely the
958        // surprise the gate exists to prevent.
959        //
960        // `Unavailable`, not `Passed`. `check.rs` defines `Unavailable` as
961        // "COULD NOT RUN — a tool is missing, or the opt-in config is absent",
962        // which is exactly this; `Passed` is the one verdict it must not
963        // report, because the dispatcher's roll-up and the fleet dashboard
964        // then show a check that never executed as clean. With a message,
965        // because every other `Unavailable` in this codebase says what was
966        // missing and an unexplained count on every commit is worse than none.
967        if fix == Fix::Rewrite && !crate::hooks::common::fixing_enabled(settings) {
968            crate::hooks::common::warn(&format!(
969                "{}: declares fix, and {} is off — not run",
970                crate::ui::highlight(&self.short_name),
971                crate::ui::highlight("amont.fix")
972            ));
973            return Outcome::Unavailable;
974        }
975
976        // Two questions, two path lists. `touches` asks what the CHANGE
977        // contains; `opted_in` asks what the REPOSITORY carries, and answering
978        // the second from the change set made a `+marker` row fire only when
979        // the marker itself was staged — so a pack that followed our own
980        // advice to gate every row was a pack that never ran. `tracked_files`
981        // returning `None` means git would not say, and an unverified answer
982        // must not silently switch a check off: run it, and let the command
983        // judge.
984        let opted_in =
985            crate::hooks::common::tracked_files().map_or(true, |tracked| scope.opted_in(&tracked));
986        if !opted_in {
987            return Outcome::Passed;
988        }
989        let root = crate::hooks::common::repo_root();
990        match self.stage {
991            Stage::PreCommit => {
992                let staged = crate::hooks::common::staged_files(&[]);
993                // The declaration's own bet is that an edit to existing
994                // documentation does not change what this gate judges. Said
995                // out loud, like every other skip that is a decision and not a
996                // missing tool.
997                //
998                // `Inert`, not `Passed`: a bet is not a verdict. `Passed` is
999                // what the stamp and the push-side pairing read as "this gate
1000                // ran clean on this tree", and a stamp for a run that never
1001                // happened would let a same-named `pre-push` declaration defer
1002                // to it, or an attestation tell CI the gate is covered. Left
1003                // unstamped, the push gate runs it as it would have.
1004                if docs_skip && crate::hooks::common::staged_docs_only() {
1005                    crate::say!(
1006                        "{} {} skipped — the commit only edits existing documentation",
1007                        crate::ui::valid_sign(),
1008                        crate::ui::highlight(&self.short_name),
1009                    );
1010                    return Outcome::Inert;
1011                }
1012                // Nothing staged is in scope: the gate judged nothing, so it
1013                // is `Inert` for the reason docs-skip is above. `Passed` here
1014                // stamped a plan-only commit `gate@…` on its tree and on its
1015                // canonical key, which ignores `docs/plans/` content — so a
1016                // deferred commit beneath it inherited the token, and the
1017                // push attested a suite that ran nowhere (decisions
1018                // programme one-verdict-per-tree, t07).
1019                let Some(matched) = files_to_judge(scope, files, &staged) else {
1020                    return Outcome::Inert;
1021                };
1022                // Fired only through the files its push twin reads: say so,
1023                // so a lockfile commit that starts testing is not a mystery.
1024                // The basename only: the line stays within 80 columns.
1025                if let Some((path, twin)) = self.twin_only_path(&staged) {
1026                    crate::say!(
1027                        "{}: {} is read by {} — running it at commit",
1028                        crate::ui::highlight(&self.short_name),
1029                        crate::ui::sanitize(path.rsplit('/').next().unwrap_or(path)),
1030                        crate::ui::sanitize(twin),
1031                    );
1032                }
1033                // A blocking gate that already ran clean against exactly this
1034                // staged tree is not run again: the attempt that ran it never
1035                // reached post-commit (commit-msg refused the subject, the
1036                // editor was closed on the message) or the same tree is
1037                // being re-committed. Said out loud, in the push gate's
1038                // words, and answered as `Passed` so pre-commit records the
1039                // marker again and post-commit binds it as usual. What can
1040                // and cannot be vouched for: `gate_stamp::vouched_for_staged_tree`.
1041                if self.severity() == Severity::Block
1042                    && crate::gate_stamp::commit_stamps_enabled(settings)
1043                    && crate::gate_identity::external_token(self, &self.short_name)
1044                        .is_some_and(|t| vouched_for_staged_tree().contains(&t))
1045                {
1046                    crate::say!(
1047                        "{} {} passed on this exact tree earlier — not repeating it here",
1048                        crate::ui::valid_sign(),
1049                        crate::ui::highlight(&self.short_name),
1050                    );
1051                    return Outcome::Passed;
1052                }
1053                // The cluster's record, beside the local one and not inside
1054                // it: a cluster token needs no program on this machine
1055                // (ADR-0016). Only a trusted `platform=any` gate asks.
1056                let judged = crate::cluster::Judged::Index;
1057                if self.severity() == Severity::Block
1058                    && crate::gate_stamp::commit_stamps_enabled(settings)
1059                    && crate::cluster::vouched(settings, self, judged)
1060                {
1061                    crate::say!(
1062                        "{} {} passed on the cluster on this exact tree earlier — not repeating it here",
1063                        crate::ui::valid_sign(),
1064                        crate::ui::highlight(&self.short_name),
1065                    );
1066                    return Outcome::Passed;
1067                }
1068                if crate::cluster::try_run(settings, self, program, args, judged) {
1069                    return Outcome::Passed;
1070                }
1071                self.execute(
1072                    settings,
1073                    program,
1074                    args,
1075                    fix,
1076                    files,
1077                    runs_on,
1078                    &matched,
1079                    Path::new(&root),
1080                )
1081            }
1082            // PER REF, and — when `amont.testPushedTree` asks for it — in a
1083            // checkout of that ref's tip, exactly as the built-in suites do
1084            // and for the same reason: a declared `test *.rs block cargo
1085            // test` line used to run once, in the working tree, whatever the
1086            // flag said. It passed on an uncommitted fix, and `stamp_tips`
1087            // then read the flag and stamped it onto the tip as though it had
1088            // run there, so the next push of that tip skipped it. The flag is
1089            // a promise about what a push gate tests; a declared gate is a
1090            // push gate.
1091            Stage::PrePush => {
1092                let zero = crate::git::stdout(&["hash-object", "--stdin"])
1093                    .map(|h| "0".repeat(h.len()))
1094                    .unwrap_or_else(|| "0".repeat(40));
1095                for r in ctx.push.get() {
1096                    if r.local_oid == zero {
1097                        continue; // deleting a ref pushes no code
1098                    }
1099                    let changed = crate::pushrefs::changed_files_for(r, &zero);
1100                    let Some(matched) = files_to_judge(scope, files, &changed) else {
1101                        continue;
1102                    };
1103                    // The cluster first, on exactly this tip's tree: a local
1104                    // checkout is made only when the gate falls back here.
1105                    let judged = crate::cluster::Judged::Commit(&r.local_oid);
1106                    if crate::cluster::try_run(settings, self, program, args, judged) {
1107                        continue;
1108                    }
1109                    // `_guard` owns the checkout for the length of this ref's
1110                    // run; dropping it removes the worktree before the next
1111                    // ref's begins. `self.id`, because that is what a stamp
1112                    // names and what `stamp_tips` asks `ran_on_tip` about.
1113                    let (run_in, _guard) =
1114                        crate::pushed_tree::where_to_run(settings, &r.local_oid, &root, &self.id);
1115                    match self.execute(
1116                        settings, program, args, fix, files, runs_on, &matched, &run_in,
1117                    ) {
1118                        Outcome::Passed => {}
1119                        other => return other,
1120                    }
1121                }
1122                Outcome::Passed
1123            }
1124        }
1125    }
1126}
1127
1128/// The paths a declared check is handed for `in_scope`, or `None` when it
1129/// has nothing to judge and must not run.
1130///
1131/// No `is_unscoped()` guard: `touches` already answers true for an unscoped
1132/// trigger, so the gate reduces to the opt-in the caller has already
1133/// settled — which is what a row with nothing on the left (`+Gemfile`: "any
1134/// change, in a repository that carries a Gemfile") means. Guarding on it
1135/// here skipped the opt-in for exactly those rows.
1136///
1137/// The paths are what the declaration's scope actually matched — what a
1138/// builtin would be handed. A files-taking command with no files has
1139/// nothing to judge — running it bare would make most linters error on an
1140/// empty argv, blocking a commit over nothing. The builtin convention,
1141/// applied here.
1142fn files_to_judge(scope: &Scope, files: bool, in_scope: &[String]) -> Option<Vec<String>> {
1143    if !scope.touches(in_scope) {
1144        return None;
1145    }
1146    let matched = scoped(scope, in_scope);
1147    if files && matched.is_empty() {
1148        return None;
1149    }
1150    Some(matched)
1151}
1152
1153impl External {
1154    /// Spawn the declared command over `matched`, in `run_in`, and judge it.
1155    ///
1156    /// `matched` reaches the command two ways: `$AMONT_FILES` always
1157    /// (newline-separated, so a wrapper script never re-derives `git diff
1158    /// --cached` and diverges from the set this gate judged — `amont run
1159    /// --all-files` overrides the set in-process, invisibly to any child that
1160    /// asks git itself), and appended to the argv when the declaration
1161    /// carries the `files` marker.
1162    #[allow(clippy::too_many_arguments)]
1163    fn execute(
1164        &self,
1165        settings: &crate::config::Settings,
1166        program: &str,
1167        args: &[String],
1168        fix: Fix,
1169        files: bool,
1170        runs_on: RunsOn,
1171        matched: &[String],
1172        run_in: &Path,
1173    ) -> Outcome {
1174        // Through `program()`, exactly like every builtin: on Windows,
1175        // `Command::new("npx")` cannot start `npx.cmd`, and an external that
1176        // fails to SPAWN reports Unavailable — warn, never block — so the
1177        // check would silently never run. The guard test that enforces this
1178        // for builtins scans only `src/hooks/`; this call is the manifest's
1179        // half of the same rule.
1180        let mut cmd = Command::new(crate::hooks::common::program(program));
1181        cmd.args(args).current_dir(run_in).stdin(Stdio::null());
1182        // Env, not only argv: newline-separated so ordinary shell loops can
1183        // read it. A path with a newline in its name would split wrong — the
1184        // list is repo-controlled and such a path is already hostile input —
1185        // and a change set too large for an environment variable (rare, but
1186        // E2BIG kills the spawn outright) travels as an empty variable
1187        // instead, which a wrapper treats exactly like "derive it yourself".
1188        let joined = matched.join("\n");
1189        cmd.env(
1190            "AMONT_FILES",
1191            if joined.len() <= 100_000 {
1192                joined.as_str()
1193            } else {
1194                ""
1195            },
1196        );
1197        if files {
1198            cmd.args(matched);
1199        }
1200        crate::hooks::common::strip_git_env(&mut cmd);
1201        // The one thing the strip above must not take from a commit-time
1202        // gate: WHICH index is being committed. `git commit -a` and `git
1203        // commit <paths>` seal a temporary index git names only in
1204        // `GIT_INDEX_FILE`; stripped, a gate that reads the index judged the
1205        // old one, passed on nothing, and its pass was stamped onto the tree
1206        // that was actually committed. Every pre-commit command is told the
1207        // index, and the repository it belongs to, in variables git never
1208        // reads, so a suite's fixture repositories can neither write into it
1209        // nor, honouring the git-dir binding, read it by mistake; a command
1210        // declared `index` reads it through git, as `GIT_INDEX_FILE`. Any
1211        // value this process inherited is already gone: `strip_git_env`
1212        // drops it, so a push gate never sees one.
1213        if self.stage == Stage::PreCommit {
1214            // Asked per gate, a few milliseconds of `git rev-parse`: no
1215            // process-wide cache to reason about. A `platform=any` gate asks
1216            // too: it reaches here only when the cluster did not take it, and
1217            // then it runs on this machine, where the index is readable.
1218            let lookup = crate::hooks::common::commit_index();
1219            match index_env(lookup.as_ref(), runs_on, &self.short_name) {
1220                IndexEnv::Set(vars) => {
1221                    for (key, value) in vars {
1222                        cmd.env(key, value);
1223                    }
1224                }
1225                IndexEnv::Refuse(why) => {
1226                    crate::hooks::common::fail(&crate::ui::sanitize(&why));
1227                    return Outcome::Failed;
1228                }
1229            }
1230        }
1231        // Under the deadline: repo-authored code that outlives the budget is
1232        // killed and FAILS — "hung" must not read as "passed", and pre-push
1233        // runs these serially where one hang stalls the entire push.
1234        let status = match crate::hooks::common::status_streamed(
1235            settings,
1236            &mut cmd,
1237            crate::hooks::common::Retry::Never,
1238        ) {
1239            Ok(crate::hooks::common::Ran::Status(s)) => Ok(s),
1240            Ok(crate::hooks::common::Ran::TimedOut(budget)) => {
1241                crate::hooks::common::say_timed_out(&self.short_name, budget);
1242                return Outcome::Failed;
1243            }
1244            Err(e) => Err(e),
1245        };
1246        match status {
1247            // A command that could not be STARTED has not judged anything. This
1248            // is the distinction `Outcome` was added for: reporting a missing
1249            // `shellcheck` as a lint failure sends someone hunting for a lint
1250            // error that does not exist.
1251            Err(e) => {
1252                crate::hooks::common::warn(&format!(
1253                    "{MANIFEST}: {} could not run {} — {}",
1254                    crate::ui::highlight(&self.short_name),
1255                    crate::ui::highlight(program),
1256                    // The io error's text embeds the program name it tried.
1257                    crate::ui::sanitize(&e.to_string())
1258                ));
1259                Outcome::Unavailable
1260            }
1261            Ok(s) if s.success() => {
1262                // A declared fixer that ran clean may still have rewritten
1263                // something; re-stage exactly what moved. Only its own scope,
1264                // so it cannot stage a file it never looked at.
1265                if fix == Fix::Rewrite && crate::hooks::common::fixing_enabled(settings) {
1266                    match crate::hooks::common::restage(matched) {
1267                        Restaged::Staged => {
1268                            crate::hooks::common::ok(
1269                                settings,
1270                                &format!(
1271                                    "{} fixed and re-staged",
1272                                    crate::ui::highlight(&self.short_name)
1273                                ),
1274                            );
1275                            return Outcome::Fixed;
1276                        }
1277                        // `git add` failed, so the index still holds whatever
1278                        // the command has already replaced on disk. This used
1279                        // to be indistinguishable from "nothing moved" and was
1280                        // reported as a pass.
1281                        Restaged::Failed(stuck) => {
1282                            crate::hooks::common::fail(&format!(
1283                                "{} rewrote files but {} failed — the index still holds the \
1284                                 OLD content: {}",
1285                                crate::ui::highlight(&self.short_name),
1286                                crate::ui::highlight("git add"),
1287                                crate::ui::sanitize(&stuck.join(", "))
1288                            ));
1289                            return Outcome::Failed;
1290                        }
1291                        Restaged::Nothing => {}
1292                    }
1293                }
1294                Outcome::Passed
1295            }
1296            Ok(_) => {
1297                crate::hooks::common::fail(&format!(
1298                    "{} failed (output above)",
1299                    crate::ui::highlight(&self.short_name)
1300                ));
1301                Outcome::Failed
1302            }
1303        }
1304    }
1305}
1306
1307/// The paths this check's scope actually covers.
1308fn scoped(scope: &Scope, paths: &[String]) -> Vec<String> {
1309    if scope.is_unscoped() {
1310        return paths.to_vec();
1311    }
1312    paths.iter().filter(|p| scope.covers(p)).cloned().collect()
1313}
1314
1315/// `Scope` holds `&'static` slices so a built-in can be a `const`. A parsed
1316/// manifest has neither, so its extension list is leaked.
1317///
1318/// This is bounded and deliberate: the manifest is read at most once per
1319/// process, holds a handful of short strings, and the process is a git hook that
1320/// exits in milliseconds. The alternative — a lifetime on `Scope` — would
1321/// propagate through the trait, both dispatchers and the fleet crate to buy back
1322/// a few hundred bytes that the kernel reclaims moments later.
1323fn leak(exts: Vec<String>) -> &'static [&'static str] {
1324    let refs: Vec<&'static str> = exts
1325        .into_iter()
1326        .map(|s| &*Box::leak(s.into_boxed_str()))
1327        .collect();
1328    Box::leak(refs.into_boxed_slice())
1329}
1330
1331/// `*` means any change; `*.sh` or `*.sh,*.bash` gate on extensions; and
1332/// `<triggers>+<opt-ins>` adds the repository condition a builtin has.
1333///
1334/// # `+`, and why there is now an opt-in at all
1335///
1336/// This used to read: *"No `opt_in` counterpart, because the manifest IS the
1337/// opt-in: a repository that does not want the check deletes the line."* That
1338/// was true while every line was one somebody typed. `amont add` ended it — a
1339/// vendored line is in your manifest because you took a whole PACK, not
1340/// because you chose that tool, so a packaged `rubocop` fired on every `.rb`
1341/// in a repository with no rubocop config and simply errored. That is the
1342/// "ninety-five nags" `hooks::yamllint` documents avoiding, which is a
1343/// courtesy every builtin has had and no declaration could express.
1344///
1345/// The separator is `+` because that is what `amont list` already PRINTS
1346/// between the two halves — `inert here — needs .rs + Cargo.toml`. What you
1347/// read in the listing is what you write in the file. No spaces: the column
1348/// grammar splits on whitespace.
1349///
1350/// Both sides are comma-separated, and each side is an OR — any trigger, and
1351/// any one opt-in. Between the sides it is an AND, matching `Scope`'s own
1352/// semantics.
1353///
1354/// Splitting on the FIRST `+` means a filename containing one is not
1355/// expressible. It is stated in `docs/custom-checks.md` rather than worked
1356/// around with quoting this grammar deliberately does not have.
1357///
1358/// Returns owned strings rather than a `Scope`, so validating a manifest
1359/// costs nothing permanent. Only `External::from` turns these into the
1360/// `&'static` form `Scope` requires.
1361#[derive(Debug, Default, PartialEq, Eq)]
1362struct ParsedScope {
1363    exts: Vec<String>,
1364    names: Vec<String>,
1365    dirs: Vec<String>,
1366    opt_in: Vec<String>,
1367}
1368
1369/// A directory trigger: `dir/**/*.ext`. The directory is whole segments with no
1370/// glob characters, so `claude-plugin/**/*.md` is in and `claude-*/**/*.md`,
1371/// `/abs/**/*.md`, `a//b/**/*.md` and `../x/**/*.md` are out. The extension is
1372/// a plain suffix. Nothing else in the grammar gets a `/` or a glob.
1373fn is_dir_token(part: &str) -> bool {
1374    let Some((dir, ext)) = part.split_once("/**/*") else {
1375        return false;
1376    };
1377    !dir.is_empty()
1378        && dir.split('/').all(|seg| {
1379            !seg.is_empty() && seg != "." && seg != ".." && !seg.contains(['*', '?', '['])
1380        })
1381        && ext.len() > 1
1382        && ext.starts_with('.')
1383        && !ext.contains(['*', '?', '[', '/'])
1384}
1385
1386fn parse_scope(token: &str) -> Result<ParsedScope, ParseError> {
1387    let (triggers, opt_in) = match token.split_once('+') {
1388        None => (token, Vec::new()),
1389        Some((left, right)) => {
1390            // `*.rb+` promises a condition and states none. Refused rather
1391            // than read as "no condition", which is the opposite of what the
1392            // author was reaching for.
1393            let opts: Vec<String> = right
1394                .split(',')
1395                .filter(|p| !p.is_empty())
1396                .map(str::to_string)
1397                .collect();
1398            if opts.is_empty() || right.contains('+') {
1399                return Err(ParseError::BadScope(token.to_string()));
1400            }
1401            for o in &opts {
1402                if o.contains(['*', '?', '[', '/']) {
1403                    return Err(ParseError::BadScope(o.clone()));
1404                }
1405            }
1406            // `+cfg` with nothing on the left is "any change, if this repo has
1407            // cfg" — a real shape, and `*` is how the trigger half spells
1408            // "anything".
1409            (if left.is_empty() { "*" } else { left }, opts)
1410        }
1411    };
1412    if triggers == "*" {
1413        return Ok(ParsedScope {
1414            opt_in,
1415            ..ParsedScope::default()
1416        });
1417    }
1418    let mut exts = Vec::new();
1419    let mut names = Vec::new();
1420    let mut dirs = Vec::new();
1421    for part in triggers.split(',') {
1422        if let Some(ext) = part.strip_prefix('*').filter(|ext| ext.starts_with('.')) {
1423            exts.push(ext.to_string());
1424            continue;
1425        }
1426        if part.contains("/**/*") {
1427            if is_dir_token(part) {
1428                dirs.push(part.to_string());
1429                continue;
1430            }
1431            return Err(ParseError::BadScope(part.to_string()));
1432        }
1433        // A bare token is an exact FILENAME — `package.json`, `Dockerfile`,
1434        // `.prettierrc` — matched against the basename. A directory is only
1435        // ever `dir/**/*.ext`, handled above; any other `/`, and anything that
1436        // LOOKS like a glob (`*`, `?`, `[`), is refused as the typo it almost
1437        // certainly is — this grammar has no globs to mis-guess.
1438        if !part.is_empty() && !part.contains(['*', '?', '[', '/']) {
1439            names.push(part.to_string());
1440            continue;
1441        }
1442        return Err(ParseError::BadScope(part.to_string()));
1443    }
1444    Ok(ParsedScope {
1445        exts,
1446        names,
1447        dirs,
1448        opt_in,
1449    })
1450}
1451
1452fn parse_stage(token: &str) -> Option<Stage> {
1453    match token {
1454        "pre-commit" => Some(Stage::PreCommit),
1455        "pre-push" => Some(Stage::PrePush),
1456        _ => None,
1457    }
1458}
1459
1460/// An identity already spoken for. An external must not be able to shadow
1461/// `pre-push-branch-protect` — nor silently lose to it, which is what a
1462/// first-match lookup would do without this.
1463///
1464/// Judged on the ID, which is why `clippy` on `pre-push` is now legal: it is
1465/// `pre-push-clippy`, a different check from `pre-commit-clippy`. Judged on the
1466/// bare name, as it was, the two collided and the second was refused.
1467///
1468fn name_is_taken(id: &str) -> bool {
1469    CHECKS.iter().any(|c| c.name == id) || ENTRYPOINTS.iter().any(|(n, _)| *n == id)
1470}
1471
1472/// A short name that says its own trigger — either by being one, or by starting
1473/// with one.
1474///
1475/// Both make an id ambiguous rather than merely ugly. `pre-commit` as a name
1476/// gives `hook.skip pre-commit` two readings; `pre-commit-clippy` as a name
1477/// gives a check whose SHORT name is the built-in's FULL id, so one skip
1478/// silences both. The stage column already says which trigger this is.
1479fn name_says_its_trigger(name: &str) -> bool {
1480    crate::TRIGGERS
1481        .iter()
1482        .any(|t| name == *t || name.starts_with(&format!("{t}-")))
1483}
1484
1485/// The four leading tokens and the untouched remainder, or `None` when the line
1486/// does not have them.
1487///
1488/// The arity is in the TYPE. Returning a `Vec` made "four or it is malformed"
1489/// a rule every caller had to remember and none could be checked against.
1490///
1491/// NOT `splitn(5, char::is_whitespace)`: that splits at the FIRST whitespace
1492/// character every time, so a file aligned into columns — which is how the
1493/// format invites you to write it — yields empty fields for every run of
1494/// spaces after the first.
1495fn tokenise(line: &str) -> Option<([&str; 4], &str)> {
1496    let mut fields: [&str; 4] = [""; 4];
1497    let mut rest = line;
1498    for slot in fields.iter_mut() {
1499        rest = rest.trim_start();
1500        let i = rest.find(char::is_whitespace)?;
1501        *slot = &rest[..i];
1502        rest = &rest[i..];
1503    }
1504    let command = rest.trim();
1505    (!command.is_empty()).then_some((fields, command))
1506}
1507
1508pub fn parse_lines(text: &str) -> Vec<Line> {
1509    let mut out: Vec<Line> = Vec::new();
1510    for (i, raw) in text.lines().enumerate() {
1511        let line = raw.trim();
1512        if line.is_empty() || line.starts_with('#') {
1513            continue;
1514        }
1515        let lineno = i + 1;
1516        let mut parsed = parse_line(lineno, line, &out);
1517        // `trim` and `is_whitespace` are Unicode; attest's verifiers read the
1518        // raw line with ASCII blanks only. A line this parser takes for
1519        // `planExempt off` that they would read as "on" (a form feed, a
1520        // non-breaking space) is loud here, never a silent opt-out that is not.
1521        if matches!(&parsed, Line::Policy { what: PolicyLine::Set { key, value }, .. }
1522            if key == "amont.planExempt" && value.eq_ignore_ascii_case("off"))
1523            && !crate::attest_inputs::conf_says_plan_exempt_off(raw.as_bytes())
1524        {
1525            parsed = broken_at(
1526                lineno,
1527                format!("{MANIFEST}:{lineno}"),
1528                None,
1529                ParseError::BadPlanExempt("write it with plain spaces or tabs".to_string()),
1530            );
1531        }
1532        out.push(parsed);
1533    }
1534    out
1535}
1536
1537/// One line, given the lines already accepted.
1538///
1539/// `earlier` is read ONLY for the duplicate check, and only its `Usable`
1540/// entries — a line that cannot run does not reserve its name. Before this, a
1541/// valid declaration was rejected as "declared twice" for colliding with a
1542/// broken one, which pointed the reader at the wrong line entirely.
1543fn parse_line(lineno: usize, line: &str, earlier: &[Line]) -> Line {
1544    // `tool` was never a valid stage, so claiming it as a keyword breaks no
1545    // manifest that ever parsed. Handled before `tokenise`, whose five-column
1546    // shape a three-token pin does not have.
1547    if line == "tool" || line.starts_with("tool ") || line.starts_with("tool\t") {
1548        let mut it = line.split_whitespace().skip(1);
1549        return match (it.next(), it.next(), it.next()) {
1550            (Some(program), Some(want), None) => Line::Tool(ToolPin {
1551                program: program.to_string(),
1552                want: want.to_string(),
1553            }),
1554            _ => broken_at(
1555                lineno,
1556                format!("{MANIFEST}:{lineno}"),
1557                None,
1558                ParseError::BadTool,
1559            ),
1560        };
1561    }
1562    // `severity` and `skip` were never valid stages either — the same
1563    // keyword claim `tool` made. Fixed arity; anything else is a positional
1564    // gap, never a phantom check named after its target (a broken
1565    // `severity clippy loud` must not mint `pre-commit-clippy`).
1566    if line == "severity" || line.starts_with("severity ") || line.starts_with("severity\t") {
1567        let mut it = line.split_whitespace().skip(1);
1568        return match (it.next(), it.next(), it.next()) {
1569            (Some(target), Some(word), None) => match Severity::parse(word) {
1570                Some(severity) => Line::Policy {
1571                    what: PolicyLine::Severity {
1572                        target: target.to_string(),
1573                        severity,
1574                    },
1575                    lineno,
1576                },
1577                None => broken_at(
1578                    lineno,
1579                    format!("{MANIFEST}:{lineno}"),
1580                    None,
1581                    ParseError::BadSeverity(word.to_string()),
1582                ),
1583            },
1584            _ => broken_at(
1585                lineno,
1586                format!("{MANIFEST}:{lineno}"),
1587                None,
1588                ParseError::BadPolicyLine("severity <check> warn|block"),
1589            ),
1590        };
1591    }
1592    if line == "skip" || line.starts_with("skip ") || line.starts_with("skip\t") {
1593        let mut it = line.split_whitespace().skip(1);
1594        return match (it.next(), it.next()) {
1595            (Some(target), None) => Line::Policy {
1596                what: PolicyLine::Skip {
1597                    target: target.to_string(),
1598                },
1599                lineno,
1600            },
1601            _ => broken_at(
1602                lineno,
1603                format!("{MANIFEST}:{lineno}"),
1604                None,
1605                ParseError::BadPolicyLine("skip <check>"),
1606            ),
1607        };
1608    }
1609    // `tree` was never a valid stage either. Its own shape: it carries a
1610    // command but decides nothing, so it gets no severity column.
1611    if line == "tree" || line.starts_with("tree ") || line.starts_with("tree\t") {
1612        return parse_tree_line(lineno, line, earlier);
1613    }
1614    if line == "set" || line.starts_with("set ") || line.starts_with("set\t") {
1615        // The value is the REST of the line, not a third token. Every key
1616        // settable before this took a single word — `true`, `72`, a version —
1617        // so splitting on whitespace was indistinguishable from splitting
1618        // once. `snapshotPrepare` is a shell command, and a rule that only
1619        // ever admits one-word values cannot express it.
1620        //
1621        // A trailing `#` stays part of the value, exactly as it does in a
1622        // check's command: comments here are whole-line only (see the caller).
1623        let rest = line[3..].trim();
1624        let split = rest
1625            .split_once(char::is_whitespace)
1626            .map(|(k, v)| (k, v.trim()))
1627            .filter(|(_, v)| !v.is_empty());
1628        return match split {
1629            Some((key, value)) => {
1630                // Case-insensitive against the allowlist, canonical spelling
1631                // stored — `set commit.subjectmax 72` must work, because git
1632                // would have accepted the key in any case.
1633                match SETTABLE.iter().find(|k| k.eq_ignore_ascii_case(key)) {
1634                    Some(canonical) if *canonical == "planExempt" => {
1635                        if !(value.eq_ignore_ascii_case("on") || value.eq_ignore_ascii_case("off"))
1636                        {
1637                            broken_at(
1638                                lineno,
1639                                format!("{MANIFEST}:{lineno}"),
1640                                None,
1641                                ParseError::BadPlanExempt(format!(
1642                                    "the value is `on` or `off`, not {value:?}"
1643                                )),
1644                            )
1645                        } else if earlier.iter().any(|l| {
1646                            matches!(l, Line::Policy { what: PolicyLine::Set { key, .. }, .. }
1647                                if key == "amont.planExempt")
1648                        }) {
1649                            broken_at(
1650                                lineno,
1651                                format!("{MANIFEST}:{lineno}"),
1652                                None,
1653                                ParseError::BadPlanExempt("it is set twice".to_string()),
1654                            )
1655                        } else {
1656                            Line::Policy {
1657                                what: PolicyLine::Set {
1658                                    key: format!("amont.{canonical}"),
1659                                    value: value.to_string(),
1660                                },
1661                                lineno,
1662                            }
1663                        }
1664                    }
1665                    Some(canonical)
1666                        if *canonical == "onBusy"
1667                            || *canonical == "slotWait"
1668                            || *canonical == "warnSlotWait" =>
1669                    {
1670                        let canonical: &'static str = canonical;
1671                        let bad = if canonical == "onBusy" {
1672                            (!(value.eq_ignore_ascii_case("wait")
1673                                || value.eq_ignore_ascii_case("defer")))
1674                            .then(|| format!("the value is `wait` or `defer`, not {value:?}"))
1675                        } else {
1676                            match value.parse::<u64>() {
1677                                Ok(1..=3600) => None,
1678                                _ => Some(format!(
1679                                    "the value is a whole number of seconds from 1 to 3600, not {value:?}"
1680                                )),
1681                            }
1682                        };
1683                        let full = format!("amont.{canonical}");
1684                        let twice = earlier.iter().any(|l| {
1685                            matches!(l, Line::Policy { what: PolicyLine::Set { key, .. }, .. }
1686                                if *key == full)
1687                        });
1688                        match (bad, twice) {
1689                            (Some(why), _) => broken_at(
1690                                lineno,
1691                                format!("{MANIFEST}:{lineno}"),
1692                                None,
1693                                ParseError::BadBusyPolicy {
1694                                    key: canonical,
1695                                    why,
1696                                },
1697                            ),
1698                            (None, true) => broken_at(
1699                                lineno,
1700                                format!("{MANIFEST}:{lineno}"),
1701                                None,
1702                                ParseError::BadBusyPolicy {
1703                                    key: canonical,
1704                                    why: "it is set twice".to_string(),
1705                                },
1706                            ),
1707                            (None, false) => Line::Policy {
1708                                what: PolicyLine::Set {
1709                                    key: full,
1710                                    value: value.to_ascii_lowercase(),
1711                                },
1712                                lineno,
1713                            },
1714                        }
1715                    }
1716                    Some(canonical)
1717                        if *canonical == "executor" || *canonical == "clusterPrepare" =>
1718                    {
1719                        parse_cluster_setting(lineno, canonical, value, earlier)
1720                    }
1721                    Some(canonical) if *canonical == "rootRunsMembers" => {
1722                        parse_root_runs_members(lineno, value, earlier)
1723                    }
1724                    Some(canonical) => Line::Policy {
1725                        what: PolicyLine::Set {
1726                            key: format!("amont.{canonical}"),
1727                            value: value.to_string(),
1728                        },
1729                        lineno,
1730                    },
1731                    None => broken_at(
1732                        lineno,
1733                        format!("{MANIFEST}:{lineno}"),
1734                        None,
1735                        ParseError::UnsettableKey(key.to_string()),
1736                    ),
1737                }
1738            }
1739            None => broken_at(
1740                lineno,
1741                format!("{MANIFEST}:{lineno}"),
1742                None,
1743                ParseError::BadPolicyLine("set <key> <value>"),
1744            ),
1745        };
1746    }
1747    let (fields, command) = match tokenise(line) {
1748        Some(t) => t,
1749        // No name to report: fall back to the position, which is the only
1750        // handle a reader has on a line this malformed.
1751        None => {
1752            return broken_at(
1753                lineno,
1754                name_or_position(tokenise(line).map(|(f, _)| f[1]).unwrap_or(""), lineno),
1755                None,
1756                ParseError::MissingFields,
1757            )
1758        }
1759    };
1760    let [stage_tok, declared, scope_tok, severity_tok] = fields;
1761    let stage = parse_stage(stage_tok);
1762    let name = name_or_position(declared, lineno);
1763    let fail = |why| broken_at(lineno, name.clone(), stage, why);
1764
1765    if declared.is_empty() {
1766        return fail(ParseError::MissingName);
1767    }
1768    // The stage is settled BEFORE the name is judged, because the identity
1769    // being judged is `<trigger>-<name>` and there is no such thing without a
1770    // trigger. Ordered the other way, a line with an unusable stage was refused
1771    // for a name clash that could not be assessed yet.
1772    let Some(stage) = stage else {
1773        return fail(ParseError::BadStage(stage_tok.to_string()));
1774    };
1775    if name_says_its_trigger(declared) {
1776        return fail(ParseError::TriggerInName(declared.to_string()));
1777    }
1778    let id = format!("{}-{}", stage.as_str(), declared);
1779    if name_is_taken(&id) {
1780        return fail(ParseError::NameTaken(declared.to_string()));
1781    }
1782    if earlier
1783        .iter()
1784        .any(|l| matches!(l, Line::Usable(d) if d.id() == id))
1785    {
1786        return fail(ParseError::Duplicate(declared.to_string()));
1787    }
1788    let ParsedScope {
1789        exts,
1790        names,
1791        dirs,
1792        opt_in,
1793    } = match parse_scope(scope_tok) {
1794        Ok(e) => e,
1795        Err(why) => return fail(why),
1796    };
1797    let Some(severity) = Severity::parse(severity_tok) else {
1798        return fail(ParseError::BadSeverity(severity_tok.to_string()));
1799    };
1800    // `fix` and `files` are leading markers on the command column rather
1801    // than extra fields, so every manifest written before them still parses.
1802    // A loop, so `fix files cmd` and `files fix cmd` both work — two markers
1803    // whose order carries no meaning must not be order-sensitive.
1804    let mut command = command;
1805    let mut wants_fix = false;
1806    let mut wants_files = false;
1807    let mut wants_docs_skip = false;
1808    let mut wants_heavy = false;
1809    let mut wants_index = false;
1810    let mut wants_platform_any = false;
1811    loop {
1812        if let Some(rest) = command.strip_prefix("fix ") {
1813            command = rest.trim_start();
1814            wants_fix = true;
1815            continue;
1816        }
1817        if let Some(rest) = command.strip_prefix("files ") {
1818            command = rest.trim_start();
1819            wants_files = true;
1820            continue;
1821        }
1822        if let Some(rest) = command.strip_prefix("docs-skip ") {
1823            command = rest.trim_start();
1824            wants_docs_skip = true;
1825            continue;
1826        }
1827        if let Some(rest) = command.strip_prefix("heavy ") {
1828            command = rest.trim_start();
1829            wants_heavy = true;
1830            continue;
1831        }
1832        if let Some(rest) = command.strip_prefix("index ") {
1833            command = rest.trim_start();
1834            wants_index = true;
1835            continue;
1836        }
1837        if let Some(rest) = command.strip_prefix("platform=") {
1838            let (word, rest) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
1839            if word != "any" {
1840                return fail(ParseError::BadPlatform(format!("platform={word}")));
1841            }
1842            command = rest.trim_start();
1843            wants_platform_any = true;
1844            continue;
1845        }
1846        break;
1847    }
1848    if wants_platform_any && wants_fix {
1849        return fail(ParseError::PlatformAnyWithFix);
1850    }
1851    if wants_platform_any && wants_files {
1852        return fail(ParseError::PlatformAnyWithFiles);
1853    }
1854    if wants_fix && stage == Stage::PrePush {
1855        return fail(ParseError::FixOnPrePush);
1856    }
1857    if wants_docs_skip && stage == Stage::PrePush {
1858        return fail(ParseError::DocsSkipOnPrePush);
1859    }
1860    if wants_index && stage == Stage::PrePush {
1861        return fail(ParseError::IndexOnPrePush);
1862    }
1863    if wants_index && wants_platform_any {
1864        return fail(ParseError::PlatformAnyWithIndex);
1865    }
1866    // `tokenise` guarantees a non-empty command, so the split cannot fail.
1867    let mut argv = command.split_whitespace().map(str::to_owned);
1868    let Some(program) = argv.next() else {
1869        return fail(ParseError::MissingFields);
1870    };
1871    Line::Usable(Declared {
1872        fix: if wants_fix { Fix::Rewrite } else { Fix::None },
1873        files: wants_files,
1874        docs_skip: wants_docs_skip,
1875        heavy: wants_heavy,
1876        runs_on: if wants_platform_any {
1877            RunsOn::AnyPlatform
1878        } else {
1879            RunsOn::Here {
1880                reads_index: wants_index,
1881            }
1882        },
1883        lineno,
1884        name: declared.to_string(),
1885        stage,
1886        severity,
1887        exts,
1888        names,
1889        dirs,
1890        opt_in,
1891        program,
1892        args: argv.collect(),
1893    })
1894}
1895
1896/// The key `set rootRunsMembers` stores its value under: the parser, the
1897/// hook and the tests name it from here.
1898pub(crate) const ROOT_RUNS_KEY: &str = "amont.rootRunsMembers";
1899
1900/// `set rootRunsMembers test,typecheck` or `set rootRunsMembers none`: strict
1901/// and set once. The value is a comma-separated list of the npm gate's script
1902/// names ([`NPM_GATE_SCRIPTS`]), or `none` standing alone; it is stored with
1903/// `none` lowercased and the names as written.
1904fn parse_root_runs_members(lineno: usize, raw_scripts: &str, earlier: &[Line]) -> Line {
1905    const KEY: &str = ROOT_RUNS_KEY;
1906    let broken = |why: String| {
1907        broken_at(
1908            lineno,
1909            format!("{MANIFEST}:{lineno}"),
1910            None,
1911            ParseError::BadRootRunsMembers(why),
1912        )
1913    };
1914    let twice = earlier
1915        .iter()
1916        .any(|l| matches!(l, Line::Policy { what: PolicyLine::Set { key, .. }, .. } if key == KEY));
1917    if twice {
1918        return broken("it is set twice".to_string());
1919    }
1920    let items: Vec<&str> = raw_scripts.split(',').map(str::trim).collect();
1921    if items.iter().any(|item| item.is_empty()) {
1922        return broken(
1923            "the value is script names separated by commas, or `none`; an empty name is neither"
1924                .to_string(),
1925        );
1926    }
1927    if items.iter().any(|item| item.eq_ignore_ascii_case("none")) {
1928        return if items.len() == 1 {
1929            Line::Policy {
1930                what: PolicyLine::Set {
1931                    key: KEY.to_string(),
1932                    value: "none".to_string(),
1933                },
1934                lineno,
1935            }
1936        } else {
1937            broken("`none` stands alone, not beside script names".to_string())
1938        };
1939    }
1940    if let Some(unknown) = items.iter().find(|item| !NPM_GATE_SCRIPTS.contains(item)) {
1941        return broken(format!(
1942            "{unknown:?} is not a script the gate runs ({})",
1943            NPM_GATE_SCRIPTS.join(", ")
1944        ));
1945    }
1946    Line::Policy {
1947        what: PolicyLine::Set {
1948            key: KEY.to_string(),
1949            value: items.join(","),
1950        },
1951        lineno,
1952    }
1953}
1954
1955/// `set executor cluster|local` or `set clusterPrepare <command>`: strict and
1956/// set once (ADR-0016). The executor is stored lowercased; the prepare command
1957/// verbatim, since it is a shell command.
1958fn parse_cluster_setting(
1959    lineno: usize,
1960    canonical: &'static str,
1961    value: &str,
1962    earlier: &[Line],
1963) -> Line {
1964    let full = format!("amont.{canonical}");
1965    let bad = |why: String| {
1966        broken_at(
1967            lineno,
1968            format!("{MANIFEST}:{lineno}"),
1969            None,
1970            ParseError::BadClusterSetting {
1971                key: canonical,
1972                why,
1973            },
1974        )
1975    };
1976    let is_executor = canonical == "executor";
1977    if is_executor
1978        && !(value.eq_ignore_ascii_case("cluster") || value.eq_ignore_ascii_case("local"))
1979    {
1980        return bad(format!("the value is `cluster` or `local`, not {value:?}"));
1981    }
1982    let twice = earlier.iter().any(
1983        |l| matches!(l, Line::Policy { what: PolicyLine::Set { key, .. }, .. } if *key == full),
1984    );
1985    if twice {
1986        return bad("it is set twice".to_string());
1987    }
1988    Line::Policy {
1989        what: PolicyLine::Set {
1990            key: full,
1991            value: if is_executor {
1992                value.to_ascii_lowercase()
1993            } else {
1994                value.to_string()
1995            },
1996        },
1997        lineno,
1998    }
1999}
2000
2001/// The first whitespace-separated token of `s`, and what follows it untouched.
2002fn split_token(s: &str) -> Option<(&str, &str)> {
2003    let s = s.trim_start();
2004    if s.is_empty() {
2005        return None;
2006    }
2007    let end = s.find(char::is_whitespace).unwrap_or(s.len());
2008    Some((&s[..end], &s[end..]))
2009}
2010
2011/// A gate name the attestation note can carry: the note's token grammar is
2012/// `[A-Za-z0-9][A-Za-z0-9._-]{0,63}` and `tree-` spends five of it.
2013fn tree_name_valid(name: &str) -> bool {
2014    let mut chars = name.chars();
2015    matches!(chars.next(), Some(c) if c.is_ascii_alphanumeric())
2016        && name.len() <= 59
2017        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
2018}
2019
2020/// A path a `cwd=` or `inputs=` may name: relative, literal, inside the tree.
2021fn tree_path_safe(path: &str) -> bool {
2022    !path.is_empty()
2023        && !path.starts_with('/')
2024        && !path.contains(['*', '?', '[', '\\'])
2025        && !path.split('/').any(|seg| seg == "..")
2026}
2027
2028fn parse_tree_line(lineno: usize, line: &str, earlier: &[Line]) -> Line {
2029    let position = format!("{MANIFEST}:{lineno}");
2030    let fail = |name: &str, why| {
2031        broken_at(
2032            lineno,
2033            if name.is_empty() {
2034                position.clone()
2035            } else {
2036                name.to_string()
2037            },
2038            None,
2039            why,
2040        )
2041    };
2042    let rest = &line[4..];
2043    let Some((name, rest)) = split_token(rest) else {
2044        return fail("", ParseError::BadTreeLine("missing name"));
2045    };
2046    if !tree_name_valid(name) {
2047        return fail(name, ParseError::BadTreeName(name.to_string()));
2048    }
2049    if name_says_its_trigger(name) {
2050        return fail(name, ParseError::TriggerInName(name.to_string()));
2051    }
2052    if earlier
2053        .iter()
2054        .any(|l| matches!(l, Line::Tree(g) if g.name == name))
2055    {
2056        return fail(name, ParseError::Duplicate(name.to_string()));
2057    }
2058    let Some((tool_tok, rest)) = split_token(rest) else {
2059        return fail(name, ParseError::BadTreeLine("missing tool"));
2060    };
2061    let Some(tool) = TreeTool::parse(tool_tok) else {
2062        return fail(name, ParseError::BadTreeTool(tool_tok.to_string()));
2063    };
2064    let Some((scope_tok, rest)) = split_token(rest) else {
2065        return fail(name, ParseError::BadTreeLine("missing scope"));
2066    };
2067    let ParsedScope {
2068        exts,
2069        names,
2070        dirs,
2071        opt_in,
2072    } = match parse_scope(scope_tok) {
2073        Ok(s) => s,
2074        Err(why) => return fail(name, why),
2075    };
2076    match split_token(rest) {
2077        Some(("attest", _)) => {}
2078        _ => {
2079            return fail(
2080                name,
2081                ParseError::BadTreeLine("the fifth column must be `attest`"),
2082            )
2083        }
2084    }
2085    let mut rest = split_token(rest).map(|(_, r)| r).unwrap_or("");
2086    let mut cwd = None;
2087    let mut inputs = Vec::new();
2088    // Options are LOWERCASE `key=value` tokens. An uppercase one
2089    // (`NODE_OPTIONS=… npm run lint`) is an environment assignment that begins
2090    // the command, so an env-prefixed command stays expressible.
2091    while let Some((tok, after)) = split_token(rest) {
2092        let Some((key, value)) = tok.split_once('=') else {
2093            break;
2094        };
2095        if key.is_empty() || !key.chars().all(|c| c.is_ascii_lowercase()) {
2096            break;
2097        }
2098        match key {
2099            "cwd" if cwd.is_none() && tree_path_safe(value) => {
2100                cwd = Some(value.trim_end_matches('/').to_string());
2101            }
2102            "inputs" if inputs.is_empty() => {
2103                let paths: Vec<String> = value.split(',').map(str::to_string).collect();
2104                if !paths.iter().all(|p| tree_path_safe(p)) {
2105                    return fail(name, ParseError::BadTreeOption(tok.to_string()));
2106                }
2107                inputs = paths;
2108            }
2109            _ => return fail(name, ParseError::BadTreeOption(tok.to_string())),
2110        }
2111        rest = after;
2112    }
2113    let command = rest.trim();
2114    if command.is_empty() {
2115        return fail(name, ParseError::BadTreeLine("missing command"));
2116    }
2117    let placeholders = command
2118        .split_whitespace()
2119        .filter(|w| *w == CACHE_PLACEHOLDER)
2120        .count();
2121    if placeholders > 1 || (placeholders == 1 && !tool.has_cache()) {
2122        return fail(name, ParseError::BadTreeCache);
2123    }
2124    if normalize_command(command).is_empty() {
2125        return fail(name, ParseError::BadTreeLine("missing command"));
2126    }
2127    Line::Tree(TreeGate {
2128        name: name.to_string(),
2129        tool,
2130        exts,
2131        names,
2132        dirs,
2133        opt_in,
2134        cwd,
2135        inputs,
2136        command: command.to_string(),
2137        lineno,
2138    })
2139}
2140
2141/// The usable tree gates a manifest text declares — untrusted, for readers
2142/// that execute nothing (`tree-parity` compares text with text). Anything that
2143/// RUNS a gate reads [`Manifest::tree`], which is trust-gated.
2144pub fn tree_gates(text: &str) -> Vec<TreeGate> {
2145    parse_lines(text)
2146        .into_iter()
2147        .filter_map(|l| match l {
2148            Line::Tree(g) => Some(g),
2149            _ => None,
2150        })
2151        .collect()
2152}
2153
2154fn name_or_position(declared: &str, lineno: usize) -> String {
2155    if declared.is_empty() {
2156        format!("{MANIFEST}:{lineno}")
2157    } else {
2158        declared.to_string()
2159    }
2160}
2161
2162fn broken_at(lineno: usize, name: String, stage: Option<Stage>, why: ParseError) -> Line {
2163    Line::Broken {
2164        name,
2165        stage: stage.unwrap_or(Stage::PreCommit),
2166        lineno,
2167        why,
2168    }
2169}
2170
2171impl From<Line> for External {
2172    fn from(l: Line) -> External {
2173        let lineno = match &l {
2174            Line::Usable(declared) => Some(declared.lineno),
2175            Line::Broken { lineno, .. } | Line::Policy { lineno, .. } => Some(*lineno),
2176            Line::Tool(_) | Line::Tree(_) => None,
2177        };
2178        let (name, stage, parsed) = l.into_parts();
2179        let kind = match parsed {
2180            Ok(d) => Kind::Runnable {
2181                // `ALWAYS` only when NOTHING narrows it. An opt-in alone is a
2182                // narrowing — `+Gemfile` means "any change, in a Ruby
2183                // repository" — and collapsing that to `ALWAYS` would run the
2184                // check everywhere, which is the exact bug this field exists
2185                // to prevent.
2186                scope: if d.exts.is_empty()
2187                    && d.names.is_empty()
2188                    && d.dirs.is_empty()
2189                    && d.opt_in.is_empty()
2190                {
2191                    Scope::ALWAYS
2192                } else {
2193                    Scope {
2194                        files: leak(d.exts),
2195                        names: leak(d.names),
2196                        dirs: leak(d.dirs),
2197                        opt_in: leak(d.opt_in),
2198                        not_during: &[],
2199                    }
2200                },
2201                severity: d.severity,
2202                program: d.program,
2203                args: d.args,
2204                fix: d.fix,
2205                files: d.files,
2206                docs_skip: d.docs_skip,
2207                heavy: d.heavy,
2208                runs_on: d.runs_on,
2209                pending_trigger: None,
2210                trigger: None,
2211            },
2212            Err(why) => Kind::Unusable {
2213                why,
2214                declared: None,
2215            },
2216        };
2217        let id = format!("{}-{}", stage.as_str(), name);
2218        External {
2219            id,
2220            short_name: name,
2221            stage,
2222            kind,
2223            lineno,
2224        }
2225    }
2226}
2227
2228pub fn parse(text: &str) -> Vec<External> {
2229    parse_lines(text)
2230        .into_iter()
2231        .filter(Line::is_check)
2232        .map(External::from)
2233        .collect()
2234}
2235
2236/// The manifest for `root`, or an empty list. Read once per process.
2237pub fn read(root: &Path) -> Vec<External> {
2238    std::fs::read_to_string(root.join(MANIFEST))
2239        .map(|t| parse(&t))
2240        .unwrap_or_default()
2241}
2242
2243/// The same file, without building the `Scope`s — for a reader that inspects
2244/// many repositories and must not leak once per manifest per refresh.
2245pub fn read_lines(root: &Path) -> Vec<Line> {
2246    std::fs::read_to_string(root.join(MANIFEST))
2247        .map(|t| parse_lines(&t))
2248        .unwrap_or_default()
2249}
2250
2251/// Everything one repository's manifest declares, parsed and trust-gated
2252/// ONCE, owned by the entrypoint that loaded it and lent down through `Ctx`.
2253///
2254/// This replaced two process-global `OnceLock`s keyed on the working
2255/// directory at first call — safe in a hook, which handles one repository
2256/// and exits, and a trap for anything that walks many. Owned data has no
2257/// first-call: the caller says which repository it means, every time.
2258#[derive(Default)]
2259pub struct Manifest {
2260    /// Declared checks — untrusted ones present but `Unusable`, so the
2261    /// decision waiting on the reader stays visible. See [`gate`].
2262    pub externals: Vec<External>,
2263    /// Tool version pins — DROPPED entirely when untrusted, because verifying
2264    /// one executes `<program> --version` for a name the repository chose,
2265    /// which is exactly the consent the trust model exists to collect.
2266    pub pins: Vec<ToolPin>,
2267    /// Tree gates — DROPPED entirely when untrusted, like the pins: running
2268    /// one executes a command the repository chose.
2269    pub tree: Vec<TreeGate>,
2270    /// Whether an `amont.conf` EXISTS in this repository — the committed
2271    /// declaration that this project subscribes to amont's conventions.
2272    /// Presence, not content: an empty file declares, and declaring executes
2273    /// nothing, so this is safe to read before any trust decision. What the
2274    /// file SAYS stays trust-gated above.
2275    pub declared: bool,
2276    /// Committed `severity`/`skip` policy — POPULATED ONLY WHEN TRUSTED,
2277    /// like the pins: applying a repository's opinion about your safety net
2278    /// is exactly the consent the trust model collects. See `policy`.
2279    pub policy: crate::policy::Policy,
2280    /// `trust::why(state)` when policy lines exist but the manifest is not
2281    /// trusted — the dispatchers say it once per stage, because policy that
2282    /// silently does not apply is a silent behaviour change.
2283    pub policy_withheld: Option<&'static str>,
2284    /// `severity`/`skip` targets that name no check here, with positions —
2285    /// a typo in committed policy must be loud, not a phantom check.
2286    pub policy_notes: Vec<String>,
2287}
2288
2289/// Read and trust-gate `root`'s manifest.
2290///
2291/// ONE read. The bytes that get PARSED and the bytes that get HASHED are the
2292/// same bytes: an earlier shape `read(root)`-ed and then let `trust::state`
2293/// open the file a second time, so anything that changed it in between — a
2294/// `git checkout`, a watcher, a `make` target already running — produced a
2295/// trust decision about content that is not the content about to be
2296/// executed.
2297///
2298/// Each call leaks the `Scope` slices it builds (see [`leak`]) — pennies for
2299/// the hook path, which loads once per process, and the reason the fleet
2300/// keeps reading [`read_lines`] instead: a scanner must not leak once per
2301/// repository per refresh.
2302pub fn load(root: &Path) -> Manifest {
2303    // Non-UTF-8 yields nothing, as it always has: `parse` takes a `&str`,
2304    // and a manifest we cannot read as text is one we cannot act on. Not
2305    // lossy — that would invent a manifest nobody wrote.
2306    let declared = root.join(MANIFEST).exists();
2307    let Ok(bytes) = std::fs::read(root.join(MANIFEST)) else {
2308        return Manifest {
2309            declared,
2310            ..Manifest::default()
2311        };
2312    };
2313    let Ok(text) = String::from_utf8(bytes.clone()) else {
2314        return Manifest {
2315            declared,
2316            ..Manifest::default()
2317        };
2318    };
2319    let state = crate::trust::state_of(root, &bytes);
2320    let lines = parse_lines(&text);
2321    let externals = gate(
2322        lines
2323            .iter()
2324            .filter(|l| l.is_check())
2325            .cloned()
2326            .map(External::from)
2327            .collect(),
2328        state,
2329    );
2330    let externals = attach_twin_scopes(externals);
2331    let trusted = state == crate::trust::State::Trusted;
2332    let pins = if trusted {
2333        lines
2334            .iter()
2335            .filter_map(|l| match l {
2336                Line::Tool(pin) => Some(pin.clone()),
2337                _ => None,
2338            })
2339            .collect()
2340    } else {
2341        Vec::new()
2342    };
2343    let tree = if trusted {
2344        lines
2345            .iter()
2346            .filter_map(|l| match l {
2347                Line::Tree(gate) => Some(gate.clone()),
2348                _ => None,
2349            })
2350            .collect()
2351    } else {
2352        Vec::new()
2353    };
2354    let has_policy = lines.iter().any(|l| matches!(l, Line::Policy { .. }));
2355    let (policy, policy_notes) = if trusted {
2356        crate::policy::Policy::from_lines(&lines)
2357    } else {
2358        (crate::policy::Policy::default(), Vec::new())
2359    };
2360    // NOTE: load() computes but never INSTALLS the policy — the entrypoints
2361    // do, immediately after this returns and before any config read. A
2362    // multi-repo walker (the fleet) reads `read_lines` and must never seed
2363    // the process-global store.
2364    let policy_withheld = if has_policy && !trusted {
2365        crate::trust::why(state)
2366    } else {
2367        None
2368    };
2369    Manifest {
2370        externals,
2371        pins,
2372        tree,
2373        declared,
2374        policy,
2375        policy_withheld,
2376        policy_notes,
2377    }
2378}
2379
2380/// Give each pre-commit declaration its push twin's reach, as a PENDING
2381/// trigger: what it would fire on if the files its twin acts on counted too.
2382///
2383/// A commit-time declaration stands in for a push gate of the same short name
2384/// (`pre-commit cargo-test *.rs` for the built-in `pre-push-cargo-test`), but
2385/// its own patterns are usually narrower than the twin's: a commit changing
2386/// only `Cargo.lock` fired neither, earned no stamp, and the push ran the whole
2387/// suite again, silently. The twin is a declared `pre-push` line of the same
2388/// name (the manifest's own, so one later in the file counts too), else the
2389/// built-in gate ([`crate::registry::push_twin_scope`]).
2390///
2391/// Left alone: a `files` declaration (its command is handed the matched paths,
2392/// and handing a linter `Cargo.lock` is wrong), a twin with no patterns (it
2393/// acts on every change, and widening to that would run the suite on every
2394/// docs commit), and a declaration the twin adds nothing to.
2395fn attach_twin_scopes(mut externals: Vec<External>) -> Vec<External> {
2396    let declared: Vec<(String, String, Scope)> = externals
2397        .iter()
2398        .filter_map(|ext| match &ext.kind {
2399            Kind::Runnable { scope, .. } if ext.stage == Stage::PrePush => {
2400                Some((ext.short_name.clone(), ext.id.clone(), *scope))
2401            }
2402            Kind::Runnable { .. } | Kind::Unusable { .. } => None,
2403        })
2404        .collect();
2405    for ext in externals.iter_mut().filter(|e| e.stage == Stage::PreCommit) {
2406        let External {
2407            short_name, kind, ..
2408        } = ext;
2409        let Kind::Runnable {
2410            scope,
2411            files: false,
2412            pending_trigger,
2413            ..
2414        } = kind
2415        else {
2416            continue;
2417        };
2418        // Every twin it stands in for: a declared `pre-push` line of its name
2419        // and the built-in gate of that name can both be in play, and the
2420        // commit-time line must cover what either acts on. A twin that acts on
2421        // every change is not followed.
2422        let mut twins: Vec<(String, Scope)> = declared
2423            .iter()
2424            .filter(|(name, _, _)| name.as_str() == short_name.as_str())
2425            .map(|(_, id, twin)| (id.clone(), *twin))
2426            .collect();
2427        if let Some((id, twin)) = crate::registry::push_twin_scope(short_name) {
2428            twins.push((id.to_string(), twin));
2429        }
2430        twins.retain(|(_, twin)| !twin.is_unscoped());
2431        let widened = twins
2432            .iter()
2433            .fold(*scope, |reach, (_, twin)| reach.union(twin));
2434        if widened != *scope && !twins.is_empty() {
2435            *pending_trigger = Some(Box::new(Trigger {
2436                scope: widened,
2437                twins,
2438            }));
2439        }
2440    }
2441    externals
2442}
2443
2444impl Manifest {
2445    /// Apply each pending trigger to the declarations that block: the ones
2446    /// [`External::blocks_at_commit`] says earn stamps,
2447    /// settings, overrides and `hook.skip` included. A warn declaration
2448    /// vouches for nothing, so it is never widened.
2449    ///
2450    /// `load` has no settings, so every entrypoint that builds checks calls
2451    /// this once, right after it builds its [`crate::config::Settings`]. A
2452    /// caller that forgets leaves every trigger pending, which is the
2453    /// declaration's own scope: the narrow side, where the worst outcome is a
2454    /// suite run at push, never a stamp for work that did not run.
2455    pub fn resolve_triggers(&mut self, settings: &crate::config::Settings) {
2456        let any_pending = self.externals.iter().any(|ext| {
2457            matches!(
2458                ext.kind,
2459                Kind::Runnable {
2460                    pending_trigger: Some(_),
2461                    ..
2462                }
2463            )
2464        });
2465        if !any_pending {
2466            return;
2467        }
2468        let skips = crate::configured_skips(settings);
2469        let severities = crate::registry::Overrides::read(settings);
2470        for ext in &mut self.externals {
2471            let blocks = ext.blocks_at_commit(&severities, &skips);
2472            if let Kind::Runnable {
2473                pending_trigger,
2474                trigger,
2475                ..
2476            } = &mut ext.kind
2477            {
2478                *trigger = if blocks {
2479                    pending_trigger.clone()
2480                } else {
2481                    None
2482                };
2483            }
2484        }
2485    }
2486}
2487
2488/// [`load`], then the [`crate::config::Settings`] built from its policy, then
2489/// the triggers resolved: the three steps every entrypoint that BUILDS checks
2490/// takes, once, in the one order that is right. A caller that only reads the
2491/// manifest's pins or tree gates, or its policy, calls [`load`] and says it
2492/// builds no check.
2493pub fn load_resolved(root: &Path) -> (Manifest, crate::config::Settings) {
2494    let mut manifest = load(root);
2495    let settings = crate::config::Settings::new(manifest.policy.clone());
2496    manifest.resolve_triggers(&settings);
2497    (manifest, settings)
2498}
2499
2500/// Check every trusted pin against the tool actually on this machine, and say
2501/// what disagrees. Warn-only, once per hook run, at BOTH stages: skew never
2502/// blocks a commit — its cost is a check disagreeing with CI, and the fix is
2503/// a human decision — but it stops being invisible, which is the whole point.
2504pub fn verify_tool_pins(pins: &[ToolPin]) {
2505    for pin in pins {
2506        match version_of(&pin.program) {
2507            None => crate::hooks::common::warn(&format!(
2508                "{} is pinned to {} in {MANIFEST}, but `{} --version` would not run",
2509                crate::ui::highlight(&pin.program),
2510                crate::ui::sanitize(&pin.want),
2511                crate::ui::sanitize(&pin.program),
2512            )),
2513            Some(v) if !v.contains(&pin.want) => crate::hooks::common::warn(&format!(
2514                "{} reports {} — {MANIFEST} pins {}; this machine may disagree with CI",
2515                crate::ui::highlight(&pin.program),
2516                crate::ui::sanitize(&v),
2517                crate::ui::sanitize(&pin.want),
2518            )),
2519            _ => {}
2520        }
2521    }
2522}
2523
2524/// First line of `<program> --version`, resolved the way every check resolves
2525/// a tool. A version probe answers in milliseconds or not at all, so it is
2526/// deliberately not under the check deadline.
2527fn version_of(program: &str) -> Option<String> {
2528    let out = Command::new(crate::hooks::common::program(program))
2529        .arg("--version")
2530        .stdin(Stdio::null())
2531        .output()
2532        .ok()?;
2533    if !out.status.success() {
2534        return None;
2535    }
2536    let text = String::from_utf8_lossy(&out.stdout);
2537    let line = text.lines().next().unwrap_or("").trim();
2538    if line.is_empty() {
2539        return None;
2540    }
2541    Some(line.to_string())
2542}
2543
2544/// Apply a trust verdict to what the manifest declared.
2545///
2546/// Untrusted declarations are kept and DISABLED, not dropped. The names stay
2547/// visible in `amont list`, in the dashboard and in the "could not run"
2548/// roll-up, because a repository quietly declaring checks that never run is the
2549/// failure this project is arranged against — and the reader needs to know
2550/// there is a decision waiting for them.
2551///
2552/// Split out of [`load`] so the rule can be asserted without a repository on
2553/// disk — and kept split even now that `load` takes an explicit root, because
2554/// a trust verdict is one input among several there and this is the part with
2555/// the rule in it.
2556pub(crate) fn gate(declared: Vec<External>, state: crate::trust::State) -> Vec<External> {
2557    match crate::trust::why(state) {
2558        None => declared,
2559        Some(reason) => declared
2560            .into_iter()
2561            .map(|external| External {
2562                kind: Kind::Unusable {
2563                    why: reason.to_string(),
2564                    declared: external.manifest_severity(),
2565                },
2566                ..external
2567            })
2568            .collect(),
2569    }
2570}
2571
2572#[cfg(test)]
2573mod tests {
2574    use super::*;
2575
2576    fn one(text: &str) -> Line {
2577        let mut v = parse_lines(text);
2578        assert_eq!(v.len(), 1, "expected one entry from {text:?}");
2579        v.pop().expect("one")
2580    }
2581
2582    /// The error a line produced, as a VALUE. Tests used to match on the prose,
2583    /// which coupled them to wording and would have kept passing if the wording
2584    /// stayed while the meaning changed.
2585    fn why(l: &Line) -> ParseError {
2586        match l {
2587            Line::Broken { why, .. } => why.clone(),
2588            Line::Usable(d) => panic!("{} parsed when it should not have", d.name),
2589            Line::Tool(pin) => panic!("{} parsed as a pin, not a broken line", pin.program),
2590            Line::Policy { what, .. } => {
2591                panic!("{} parsed as policy, not a broken line", what.describe())
2592            }
2593            Line::Tree(g) => panic!("{} parsed as a tree gate, not a broken line", g.name),
2594        }
2595    }
2596
2597    fn usable(l: &Line) -> &Declared {
2598        match l {
2599            Line::Usable(d) => d,
2600            Line::Broken { name, why, .. } => panic!("{name} failed to parse: {why}"),
2601            Line::Tool(pin) => panic!("{} is a tool pin, not a declaration", pin.program),
2602            Line::Policy { what, .. } => {
2603                panic!("{} is policy, not a declaration", what.describe())
2604            }
2605            Line::Tree(g) => panic!("{} is a tree gate, not a declaration", g.name),
2606        }
2607    }
2608
2609    fn tree(l: &Line) -> &TreeGate {
2610        match l {
2611            Line::Tree(g) => g,
2612            Line::Broken { name, why, .. } => panic!("{name} failed to parse: {why}"),
2613            other => panic!("{} is not a tree gate", other.name()),
2614        }
2615    }
2616
2617    #[test]
2618    fn tree_full_line_parses_with_options() {
2619        let l = one("tree  eslint  eslint  *.ts,*.tsx  attest  cwd=web/ inputs=tsconfig.json,.eslintignore  npm run lint -- {cache}");
2620        let g = tree(&l);
2621        assert_eq!(g.name, "eslint");
2622        assert_eq!(g.tool, TreeTool::Eslint);
2623        assert_eq!(g.exts, vec![".ts".to_string(), ".tsx".to_string()]);
2624        assert_eq!(g.cwd.as_deref(), Some("web"));
2625        assert_eq!(
2626            g.inputs,
2627            vec!["tsconfig.json".to_string(), ".eslintignore".to_string()]
2628        );
2629        assert_eq!(g.command, "npm run lint -- {cache}");
2630        assert_eq!(g.id(), "tree-eslint");
2631        assert_eq!(g.stamp_key(), "tree:eslint");
2632        assert!(!l.is_check());
2633    }
2634
2635    #[test]
2636    fn tree_normalizes_cache_dangling_dashes_and_whitespace() {
2637        assert_eq!(normalize_command("npm run lint -- {cache}"), "npm run lint");
2638        assert_eq!(normalize_command("npx eslint . {cache}"), "npx eslint .");
2639        assert_eq!(
2640            normalize_command("uvx ruff@0.16.0   check packages"),
2641            "uvx ruff@0.16.0 check packages"
2642        );
2643        // A `--` that is NOT trailing is the command's own and stays.
2644        assert_eq!(
2645            normalize_command("npm run lint -- --quiet"),
2646            "npm run lint -- --quiet"
2647        );
2648    }
2649
2650    #[test]
2651    fn tree_env_assignment_begins_the_command() {
2652        let l =
2653            one("tree eslint eslint * attest NODE_OPTIONS=--max-old-space-size=4096 npm run lint");
2654        let g = tree(&l);
2655        assert_eq!(g.cwd, None);
2656        assert_eq!(
2657            g.command,
2658            "NODE_OPTIONS=--max-old-space-size=4096 npm run lint"
2659        );
2660    }
2661
2662    /// `dir/**/*.ext` is the one trigger with a `/` in it: a whole directory
2663    /// prefix and a plain suffix. Everything else with a slash, a glob or an
2664    /// empty segment is refused, so the grammar cannot grow a glob by accident.
2665    #[test]
2666    fn a_directory_token_is_a_trigger_and_nothing_else_with_a_slash_is() {
2667        let Line::Usable(d) = one("pre-commit  plugin  claude-plugin/**/*.md  block  true\n")
2668        else {
2669            panic!("a directory trigger should parse");
2670        };
2671        assert_eq!(d.dirs, ["claude-plugin/**/*.md"]);
2672        assert!(d.exts.is_empty() && d.names.is_empty());
2673
2674        let Line::Usable(d) = one("pre-commit  plugin  docs/x/**/*.md+Cargo.toml  block  true\n")
2675        else {
2676            panic!("a directory trigger with an opt-in should parse");
2677        };
2678        assert_eq!(d.dirs, ["docs/x/**/*.md"]);
2679        assert_eq!(d.opt_in, ["Cargo.toml"]);
2680
2681        for bad in [
2682            "claude-*/**/*.md",
2683            "/abs/**/*.md",
2684            "a//b/**/*.md",
2685            "../x/**/*.md",
2686            "a/./**/*.md",
2687            "x/**/*",
2688            "claude-plugin/*.md",
2689            "claude-plugin/**/*.md/x",
2690        ] {
2691            let l = one(&format!("pre-commit  plugin  {bad}  block  true\n"));
2692            assert!(
2693                matches!(why(&l), ParseError::BadScope(_)),
2694                "{bad} must be refused"
2695            );
2696        }
2697    }
2698
2699    /// `docs-skip` is a leading marker like `fix` and `files`, and it means
2700    /// something only where there is a staged change to judge.
2701    #[test]
2702    fn docs_skip_is_a_marker_and_refused_on_pre_push() {
2703        let Line::Usable(d) = one("pre-commit  adr  *+.adr.yaml  block  docs-skip aval check\n")
2704        else {
2705            panic!("docs-skip should parse on pre-commit");
2706        };
2707        assert!(d.docs_skip);
2708        assert_eq!(d.program, "aval");
2709        assert_eq!(
2710            why(&one("pre-push  adr  *  block  docs-skip aval check\n")),
2711            ParseError::DocsSkipOnPrePush
2712        );
2713    }
2714
2715    /// No index to read refuses every pre-commit gate, never runs one blind,
2716    /// and says git's own reason.
2717    #[test]
2718    fn an_index_that_cannot_be_located_refuses_every_gate() {
2719        let lost = crate::hooks::common::IndexLookupError::Git {
2720            args: "rev-parse --absolute-git-dir".into(),
2721            why: "fatal: detected dubious ownership".into(),
2722        };
2723        assert!(
2724            matches!(index_env(Err(&lost), RunsOn::Here { reads_index: true }, "staged"), IndexEnv::Refuse(w) if w.contains("staged") && w.contains("dubious ownership"))
2725        );
2726        assert!(
2727            matches!(index_env(Err(&lost), RunsOn::Here { reads_index: false }, "lint"), IndexEnv::Refuse(w) if w.contains("AMONT_INDEX_FILE"))
2728        );
2729        let found = crate::hooks::common::CommitIndex {
2730            file: "/r/.git/index.lock".into(),
2731            git_dir: "/r/.git".into(),
2732        };
2733        let found = Ok(&found);
2734        let IndexEnv::Set(plain) = index_env(found, RunsOn::Here { reads_index: false }, "lint")
2735        else {
2736            panic!("an index that was found is set");
2737        };
2738        assert_eq!(
2739            plain.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
2740            ["AMONT_INDEX_FILE", "AMONT_INDEX_GIT_DIR"]
2741        );
2742        let IndexEnv::Set(marked) = index_env(found, RunsOn::Here { reads_index: true }, "staged")
2743        else {
2744            panic!("an index that was found is set");
2745        };
2746        assert!(marked.contains(&("GIT_INDEX_FILE", "/r/.git/index.lock".into())));
2747    }
2748
2749    /// `index` is a leading marker too, meaningful only where an index is
2750    /// being committed, and never beside a pod that cannot read it.
2751    #[test]
2752    fn index_is_a_marker_refused_on_pre_push_and_beside_platform_any() {
2753        let Line::Usable(d) = one("pre-commit  staged  *.rs  block  heavy index my-lint --x\n")
2754        else {
2755            panic!("index should parse on pre-commit");
2756        };
2757        assert_eq!(d.runs_on, RunsOn::Here { reads_index: true });
2758        assert!(d.heavy);
2759        assert_eq!(d.program, "my-lint");
2760        assert_eq!(
2761            why(&one("pre-push  staged  *.rs  block  index my-lint\n")),
2762            ParseError::IndexOnPrePush
2763        );
2764        assert_eq!(
2765            why(&one(
2766                "pre-commit  staged  *.rs  block  index platform=any my-lint\n"
2767            )),
2768            ParseError::PlatformAnyWithIndex
2769        );
2770    }
2771
2772    /// Each malformed tree line is refused, and says why.
2773    #[test]
2774    fn a_malformed_tree_line_is_refused_with_its_reason() {
2775        for (line, expected) in [
2776            ("tree", ParseError::BadTreeLine("missing name")),
2777            ("tree eslint", ParseError::BadTreeLine("missing tool")),
2778            (
2779                "tree eslint eslint",
2780                ParseError::BadTreeLine("missing scope"),
2781            ),
2782            (
2783                "tree eslint eslint * block npx eslint .",
2784                ParseError::BadTreeLine("the fifth column must be `attest`"),
2785            ),
2786            (
2787                "tree eslint eslint * attest",
2788                ParseError::BadTreeLine("missing command"),
2789            ),
2790            // `{cache}` only for a tool that has one, and only once
2791            (
2792                "tree ruff-check ruff * attest uvx ruff@0.16.0 check packages {cache}",
2793                ParseError::BadTreeCache,
2794            ),
2795            (
2796                "tree eslint eslint * attest npx eslint {cache} . {cache}",
2797                ParseError::BadTreeCache,
2798            ),
2799            (
2800                "tree lint biome * attest npx biome check .",
2801                ParseError::BadTreeTool("biome".into()),
2802            ),
2803            // `cwd` stays inside the repository; `inputs` names paths, not globs
2804            (
2805                "tree eslint eslint * attest cwd=/etc npx eslint .",
2806                ParseError::BadTreeOption("cwd=/etc".into()),
2807            ),
2808            (
2809                "tree eslint eslint * attest cwd=web/../.. npx eslint .",
2810                ParseError::BadTreeOption("cwd=web/../..".into()),
2811            ),
2812            (
2813                "tree eslint eslint * attest inputs=src/*.json npx eslint .",
2814                ParseError::BadTreeOption("inputs=src/*.json".into()),
2815            ),
2816            (
2817                "tree eslint eslint * attest shell=bash npx eslint .",
2818                ParseError::BadTreeOption("shell=bash".into()),
2819            ),
2820            (
2821                "tree pre-commit-lint eslint * attest npx eslint .",
2822                ParseError::TriggerInName("pre-commit-lint".into()),
2823            ),
2824            (
2825                "tree -lint eslint * attest npx eslint .",
2826                ParseError::BadTreeName("-lint".into()),
2827            ),
2828        ] {
2829            assert_eq!(why(&one(line)), expected, "{line}");
2830        }
2831    }
2832
2833    #[test]
2834    fn tree_duplicate_name_refused() {
2835        let v = parse_lines(
2836            "tree eslint eslint * attest npx eslint .\ntree eslint eslint * attest npx eslint src",
2837        );
2838        assert_eq!(v.len(), 2);
2839        tree(&v[0]);
2840        assert_eq!(why(&v[1]), ParseError::Duplicate("eslint".into()));
2841    }
2842
2843    #[test]
2844    fn tree_gates_are_not_runnable_checks() {
2845        let text = "tree eslint eslint * attest npx eslint .\npre-commit smoke * block true";
2846        let checks = parse(text);
2847        assert_eq!(checks.len(), 1);
2848        assert_eq!(checks[0].id, "pre-commit-smoke");
2849        let gates = tree_gates(text);
2850        assert_eq!(gates.len(), 1);
2851        assert_eq!(gates[0].normalized(), "npx eslint .");
2852    }
2853
2854    /// The scope column's bare tokens are exact filenames — basename-matched,
2855    /// so `package.json` cannot be counterfeited by `not-package.json` — and
2856    /// they mix freely with extensions. Directories and free `*` stay refused.
2857    #[test]
2858    fn a_bare_scope_token_is_an_exact_filename() {
2859        let line = one("pre-commit  lockcheck  package.json  block  ./check.sh\n");
2860        let d = usable(&line);
2861        assert!(d.exts.is_empty());
2862        assert_eq!(d.names, ["package.json"]);
2863
2864        let line = one("pre-commit  x  *.ts,package.json,.prettierrc  block  ./x\n");
2865        let d = usable(&line);
2866        assert_eq!(d.exts, [".ts"]);
2867        assert_eq!(d.names, ["package.json", ".prettierrc"]);
2868
2869        assert_eq!(
2870            why(&one("pre-commit  x  src/package.json  block  ./x\n")),
2871            ParseError::BadScope("src/package.json".into())
2872        );
2873        assert_eq!(
2874            why(&one("pre-commit  x  pkg*  block  ./x\n")),
2875            ParseError::BadScope("pkg*".into())
2876        );
2877    }
2878
2879    /// `+` adds the repository condition a builtin has always had.
2880    ///
2881    /// The separator is the one `amont list` already prints between the two
2882    /// halves (`needs .rs + Cargo.toml`), so what a reader sees in the listing
2883    /// is what they write in the file.
2884    #[test]
2885    fn a_scope_can_name_what_the_repository_must_carry() {
2886        let line = one("pre-commit  rubocop  *.rb+.rubocop.yml  block  rubocop\n");
2887        let d = usable(&line);
2888        assert_eq!(d.exts, [".rb"]);
2889        assert!(d.names.is_empty());
2890        assert_eq!(d.opt_in, [".rubocop.yml"]);
2891
2892        // Both sides comma-separated: any trigger, and any ONE opt-in.
2893        let line = one("pre-commit  x  *.rb,Rakefile+.rubocop.yml,.rubocop_todo.yml  block  ./x\n");
2894        let d = usable(&line);
2895        assert_eq!(d.exts, [".rb"]);
2896        assert_eq!(d.names, ["Rakefile"]);
2897        assert_eq!(d.opt_in, [".rubocop.yml", ".rubocop_todo.yml"]);
2898
2899        // No trigger half: "any change, in a repository that carries this".
2900        let line = one("pre-commit  x  +Gemfile  block  ./x\n");
2901        let d = usable(&line);
2902        assert!(d.exts.is_empty() && d.names.is_empty());
2903        assert_eq!(d.opt_in, ["Gemfile"]);
2904    }
2905
2906    /// Every declaration written before `+` existed keeps its meaning: no
2907    /// opt-in is the old behaviour, which is "applies wherever it triggers".
2908    #[test]
2909    fn a_scope_without_a_plus_is_unchanged() {
2910        let line = one("pre-commit  x  *.ts,package.json  block  ./x\n");
2911        let d = usable(&line);
2912        assert!(d.opt_in.is_empty());
2913        let line = one("pre-commit  x  *  block  ./x\n");
2914        let d = usable(&line);
2915        assert!(d.opt_in.is_empty() && d.exts.is_empty() && d.names.is_empty());
2916    }
2917
2918    /// A `+` that promises a condition and names none is refused, rather than
2919    /// read as "no condition" — which is the opposite of what was reached for.
2920    #[test]
2921    fn a_malformed_opt_in_half_is_refused() {
2922        for bad in [
2923            "*.rb+",            // promised, not given
2924            "*.rb+,",           // still nothing
2925            "*.rb+a+b",         // a second separator is not a filename
2926            "*.rb+sub/dir.yml", // directories are inexpressible, as on the left
2927            "*.rb+*.yml",       // this grammar has no globs to mis-guess
2928        ] {
2929            let line = one(&format!("pre-commit  x  {bad}  block  ./x\n"));
2930            assert!(
2931                matches!(line, Line::Broken { .. }),
2932                "{bad} should be refused, got {line:?}"
2933            );
2934        }
2935    }
2936
2937    /// The pin grammar: exactly three tokens, claimed from a first token that
2938    /// was never a valid stage — no manifest that ever parsed changes meaning.
2939    #[test]
2940    fn a_tool_pin_parses_and_a_malformed_one_is_broken() {
2941        let line = one("tool  ruff  0.6.\n");
2942        assert_eq!(
2943            line,
2944            Line::Tool(ToolPin {
2945                program: "ruff".into(),
2946                want: "0.6.".into()
2947            })
2948        );
2949        assert_eq!(why(&one("tool ruff\n")), ParseError::BadTool);
2950        assert_eq!(why(&one("tool ruff 0.6. extra\n")), ParseError::BadTool);
2951        // `tool` is only a keyword in column one — a check NAMED tool still
2952        // parses as the check it always was.
2953        let line = one("pre-commit  tool  *  block  make tool\n");
2954        assert_eq!(usable(&line).name, "tool");
2955    }
2956
2957    #[test]
2958    fn parses_the_documented_example() {
2959        let v = parse_lines(
2960            "# stage       name        scope   severity  command\n\
2961             pre-commit    lint-shell  *.sh    block     scripts/lint-shell.sh\n\
2962             pre-push      smoke       *       warn      make smoke\n",
2963        );
2964        assert_eq!(v.len(), 2);
2965
2966        let a = usable(&v[0]);
2967        assert_eq!(a.name, "lint-shell");
2968        assert_eq!(a.stage, Stage::PreCommit);
2969        assert_eq!(a.severity, Severity::Block);
2970        assert_eq!(a.program, "scripts/lint-shell.sh");
2971        assert!(a.args.is_empty());
2972        assert_eq!(a.exts, [".sh"]);
2973
2974        let b = usable(&v[1]);
2975        assert_eq!(b.stage, Stage::PrePush);
2976        assert_eq!(b.severity, Severity::Warn);
2977        // A command with arguments is split, not handed to a shell.
2978        assert_eq!(b.program, "make");
2979        assert_eq!(b.args, ["smoke"]);
2980        assert!(b.exts.is_empty(), "`*` gates on nothing");
2981    }
2982
2983    /// Blank lines and comments are not entries, and must not become broken
2984    /// ones — a file that is mostly documentation would otherwise report a
2985    /// dozen gaps.
2986    #[test]
2987    fn comments_and_blank_lines_produce_nothing() {
2988        assert!(parse_lines("\n  \n# just a comment\n\t# indented\n").is_empty());
2989    }
2990
2991    /// The rule the module commits to: a line that cannot be understood still
2992    /// yields a check, so its absence is visible. Matched by VARIANT.
2993    #[test]
2994    fn a_malformed_line_becomes_a_visible_gap() {
2995        let cases: [(&str, ParseError); 4] = [
2996            (
2997                "pre-commit lint-shell *.sh block\n",
2998                ParseError::MissingFields,
2999            ),
3000            (
3001                "nonsense lint-shell *.sh block x\n",
3002                ParseError::BadStage("nonsense".into()),
3003            ),
3004            (
3005                "pre-commit lint-shell ?.sh block x\n",
3006                ParseError::BadScope("?.sh".into()),
3007            ),
3008            (
3009                "pre-commit lint-shell *.sh loud x\n",
3010                ParseError::BadSeverity("loud".into()),
3011            ),
3012        ];
3013        for (text, expected) in cases {
3014            assert_eq!(why(&one(text)), expected, "for {text:?}");
3015        }
3016    }
3017
3018    /// The prose still has to locate the line, even though the tests no longer
3019    /// depend on its wording.
3020    #[test]
3021    fn a_gap_reports_where_it_is() {
3022        let l = one("pre-commit lint-shell *.sh loud x\n");
3023        let said = l.broken().expect("broken");
3024        assert!(said.contains("line 1"), "{said}");
3025        assert!(said.contains("severity"), "{said}");
3026    }
3027
3028    /// `fix` on a pre-push line is refused where every other bad declaration is
3029    /// refused — on every commit, named and located — rather than as a runtime
3030    /// "contract violation" discovered later at push time by fewer people.
3031    #[test]
3032    fn fix_is_refused_on_a_pre_push_line() {
3033        assert_eq!(
3034            why(&one("pre-push  smoke  *  block  fix make smoke\n")),
3035            ParseError::FixOnPrePush
3036        );
3037        // …and accepted on pre-commit.
3038        let line = one("pre-commit  fmt  *  block  fix make format\n");
3039        let declared = usable(&line);
3040        assert_eq!(declared.fix, Fix::Rewrite);
3041        assert_eq!(declared.program, "make");
3042        assert_eq!(declared.args, ["format"]);
3043    }
3044
3045    /// Every manifest written before `fix` existed must still parse the same.
3046    #[test]
3047    fn a_command_that_merely_starts_with_fix_is_not_a_marker() {
3048        let line = one("pre-commit  x  *  block  fixup-tool --check\n");
3049        let declared = usable(&line);
3050        assert_eq!(declared.fix, Fix::None);
3051        assert_eq!(declared.program, "fixup-tool");
3052    }
3053
3054    /// The `files` marker, alone and stacked with `fix` in either order —
3055    /// two markers whose order carries no meaning must not be
3056    /// order-sensitive.
3057    #[test]
3058    fn the_files_marker_parses_alone_and_in_either_order_with_fix() {
3059        let line = one("pre-commit  sc  *.sh  block  files shellcheck\n");
3060        let declared = usable(&line);
3061        assert!(declared.files);
3062        assert_eq!(declared.fix, Fix::None);
3063        assert_eq!(declared.program, "shellcheck");
3064
3065        for text in [
3066            "pre-commit  fmt  *  block  fix files prettier --write\n",
3067            "pre-commit  fmt  *  block  files fix prettier --write\n",
3068        ] {
3069            let line = one(text);
3070            let declared = usable(&line);
3071            assert!(declared.files, "for {text:?}");
3072            assert_eq!(declared.fix, Fix::Rewrite, "for {text:?}");
3073            assert_eq!(declared.program, "prettier", "for {text:?}");
3074            assert_eq!(declared.args, ["--write"], "for {text:?}");
3075        }
3076    }
3077
3078    /// A command that merely starts with `files` keeps its name, exactly as
3079    /// `fixup-tool` keeps its own.
3080    #[test]
3081    fn a_command_that_merely_starts_with_files_is_not_a_marker() {
3082        let line = one("pre-commit  x  *  block  files-checker --strict\n");
3083        let declared = usable(&line);
3084        assert!(!declared.files);
3085        assert_eq!(declared.program, "files-checker");
3086    }
3087
3088    /// A gap with no name cannot be reported, and a line this broken has none.
3089    #[test]
3090    fn a_nameless_line_is_named_after_its_position() {
3091        let l = one("pre-commit\n");
3092        assert_eq!(l.name(), "amont.conf:1");
3093        assert_eq!(why(&l), ParseError::MissingFields);
3094    }
3095
3096    /// An external must not be able to take a built-in's id — it would either
3097    /// shadow `pre-push-branch-protect` or silently lose to it, and neither is
3098    /// something a repository should be able to do by editing a text file.
3099    ///
3100    /// Judged on the id, so the same declaration is refused on one trigger and
3101    /// accepted on the other. That is not a loophole: `pre-push-clippy` is a
3102    /// different check from `pre-commit-clippy`, and nothing is shadowed.
3103    #[test]
3104    fn a_built_in_id_is_refused() {
3105        assert_eq!(
3106            why(&one("pre-commit clippy *.rs block x\n")),
3107            ParseError::NameTaken("clippy".into())
3108        );
3109        assert!(matches!(
3110            one("pre-push clippy *.rs block x\n"),
3111            Line::Usable(_)
3112        ));
3113        // And a pre-push built-in is protected on pre-push, not on pre-commit,
3114        // for the same reason.
3115        assert_eq!(
3116            why(&one("pre-push pull-rebase * block x\n")),
3117            ParseError::NameTaken("pull-rebase".into())
3118        );
3119        assert!(matches!(
3120            one("pre-commit pull-rebase * block x\n"),
3121            Line::Usable(_)
3122        ));
3123    }
3124
3125    /// The stage column says which trigger a line is for. Saying it again in
3126    /// the name is the one way to make an id ambiguous: `pre-commit-clippy` as
3127    /// a NAME is a check whose short name is the built-in's full id, so one
3128    /// `hook.skip` would silence both.
3129    #[test]
3130    fn a_name_that_says_its_own_trigger_is_refused() {
3131        for name in ["pre-commit", "pre-push", "pre-commit-clippy", "pre-push-x"] {
3132            assert_eq!(
3133                why(&one(&format!("pre-commit {name} * block x\n"))),
3134                ParseError::TriggerInName(name.into()),
3135                "{name}"
3136            );
3137        }
3138        // A name that merely begins with the same letters is fine — the trigger
3139        // has to be followed by the separator to count.
3140        assert!(matches!(
3141            one("pre-commit pre-commitish * block x\n"),
3142            Line::Usable(_)
3143        ));
3144    }
3145
3146    /// Two USABLE lines with one ID: the second cannot be addressed by
3147    /// `hook.skip` or by a severity override, so it is refused.
3148    #[test]
3149    fn a_duplicate_id_is_refused() {
3150        let v = parse_lines(
3151            "pre-commit smoke * block a\n\
3152             pre-commit smoke * block b\n",
3153        );
3154        assert_eq!(v.len(), 2);
3155        assert_eq!(usable(&v[0]).id(), "pre-commit-smoke");
3156        assert_eq!(why(&v[1]), ParseError::Duplicate("smoke".into()));
3157    }
3158
3159    /// The same name on both triggers is TWO checks, and this used to refuse
3160    /// the second. Somebody wanting a `show-unicorn` on commit and on push had
3161    /// no way to write it, and no way to skip or downgrade one without the
3162    /// other — the bare name could not tell them apart.
3163    #[test]
3164    fn the_same_name_on_two_triggers_is_allowed() {
3165        let v = parse_lines(
3166            "pre-commit show-unicorn * block a\n\
3167             pre-push   show-unicorn * block b\n",
3168        );
3169        assert_eq!(v.len(), 2);
3170        assert_eq!(usable(&v[0]).id(), "pre-commit-show-unicorn");
3171        assert_eq!(usable(&v[1]).id(), "pre-push-show-unicorn");
3172
3173        // And each is separately addressable, while the short name takes both —
3174        // which is the whole vocabulary, applied to declared checks.
3175        for (id, only) in [
3176            ("pre-commit-show-unicorn", "pre-push-show-unicorn"),
3177            ("pre-push-show-unicorn", "pre-commit-show-unicorn"),
3178        ] {
3179            assert!(crate::skip_suppresses(id, id));
3180            assert!(!crate::skip_suppresses(only, id));
3181        }
3182        assert!(crate::skip_suppresses(
3183            "pre-commit-show-unicorn",
3184            "show-unicorn"
3185        ));
3186        assert!(crate::skip_suppresses(
3187            "pre-push-show-unicorn",
3188            "show-unicorn"
3189        ));
3190        assert!(crate::skip_suppresses(
3191            "pre-commit-show-unicorn",
3192            "pre-commit"
3193        ));
3194        assert!(!crate::skip_suppresses(
3195            "pre-push-show-unicorn",
3196            "pre-commit"
3197        ));
3198    }
3199
3200    /// A line that cannot run does not RESERVE its name.
3201    ///
3202    /// It used to: broken and usable entries shared one list, so a valid
3203    /// declaration was rejected as "declared twice" for colliding with a line
3204    /// that could never execute — pointing the reader at the wrong line, and
3205    /// forcing them to fix the first before the second would work at all.
3206    #[test]
3207    fn a_broken_line_does_not_reserve_its_name() {
3208        let v = parse_lines(
3209            "pre-commit smoke * LOUD   make a\n\
3210             pre-commit smoke * block  make b\n",
3211        );
3212        assert_eq!(v.len(), 2);
3213        assert_eq!(why(&v[0]), ParseError::BadSeverity("LOUD".into()));
3214        let good = usable(&v[1]);
3215        assert_eq!(good.name, "smoke");
3216        assert_eq!(good.program, "make");
3217    }
3218
3219    /// Alignment is cosmetic. A file someone has lined up with tabs, or not
3220    /// lined up at all, must parse identically.
3221    #[test]
3222    fn field_alignment_does_not_matter() {
3223        let spaced = one("pre-commit      lint-shell    *.sh      block     make lint\n");
3224        let tabbed = one("pre-commit\tlint-shell\t*.sh\tblock\tmake lint\n");
3225        assert_eq!(usable(&spaced), usable(&tabbed));
3226        assert_eq!(usable(&spaced).args, ["lint"]);
3227    }
3228
3229    #[test]
3230    fn several_extensions_can_gate_one_check() {
3231        let e = External::from(one("pre-commit shell *.sh,*.bash block make lint\n"));
3232        assert!(e.scope().matches(&["a.bash".into()]));
3233        assert!(e.scope().matches(&["a.sh".into()]));
3234        assert!(!e.scope().matches(&["a.zsh".into()]));
3235    }
3236
3237    /// `tokenise` states its arity in the type, so "four tokens then a command"
3238    /// is checked rather than remembered.
3239    #[test]
3240    fn tokenise_wants_four_fields_and_a_command() {
3241        assert!(tokenise("a b c").is_none(), "too few fields");
3242        assert!(tokenise("a b c d").is_none(), "four fields, no command");
3243        // Trailing whitespace reaches the four fields but still leaves nothing
3244        // to run — the case the `?` on the last field cannot catch.
3245        assert!(
3246            tokenise("a b c d   ").is_none(),
3247            "command is all whitespace"
3248        );
3249        assert!(tokenise("a b c d\t").is_none(), "command is a tab");
3250        let (fields, cmd) = tokenise("a  b\tc   d   run it").expect("four and a command");
3251        assert_eq!(fields, ["a", "b", "c", "d"]);
3252        assert_eq!(cmd, "run it");
3253    }
3254
3255    /// An unusable line carries no command at all — the type has nowhere to put
3256    /// one, which is the point of the split.
3257    #[test]
3258    fn an_unusable_external_holds_no_command() {
3259        let e = External::from(one("pre-commit lint-shell *.sh loud echo hi\n"));
3260        assert!(matches!(e.kind, Kind::Unusable { .. }));
3261        // And it can never block, whatever severity anyone configures.
3262        assert_eq!(e.severity(), Severity::Warn);
3263    }
3264
3265    /// A missing manifest is the normal case and must not be an error.
3266    #[test]
3267    fn a_repository_with_no_manifest_declares_nothing() {
3268        assert!(read(Path::new("/nonexistent-c8f2")).is_empty());
3269        assert!(read_lines(Path::new("/nonexistent-c8f2")).is_empty());
3270    }
3271
3272    /// `Line` exists to spare the dashboard a leak, not to become a second
3273    /// opinion about what a manifest says.
3274    #[test]
3275    fn the_leaking_and_non_leaking_parsers_agree() {
3276        let text = "pre-commit  lint-shell  *.sh,*.bash  block  make lint\n\
3277                    pre-push    smoke       *            warn   make smoke\n\
3278                    pre-commit  broken      ?            block  x\n";
3279        let lines = parse_lines(text);
3280        let externals = parse(text);
3281        assert_eq!(lines.len(), externals.len());
3282        for (l, e) in lines.iter().zip(&externals) {
3283            assert_eq!(l.id(), e.name(), "the id is what a check answers to");
3284            assert_eq!(
3285                l.name(),
3286                e.short_name,
3287                "and the short name is what it is called"
3288            );
3289            assert_eq!(l.stage(), e.stage());
3290            assert_eq!(
3291                l.broken().is_some(),
3292                matches!(e.kind, Kind::Unusable { .. })
3293            );
3294            if let Line::Usable(d) = l {
3295                assert_eq!(d.severity, e.severity());
3296                // The scope the dashboard would DESCRIBE is the scope the
3297                // dispatcher would ENFORCE.
3298                assert_eq!(d.exts, e.scope().files);
3299            }
3300        }
3301    }
3302
3303    /// `heavy` is a marker, not part of the command, in any order with the
3304    /// others; a declared check is Heavy by it, or by moving a built-in
3305    /// Heavy gate (ADR-0013), and Light otherwise.
3306    #[test]
3307    fn heavy_is_a_marker_and_a_moved_gate_is_heavy() {
3308        use crate::check::Check;
3309        use crate::host_slots::Weight;
3310        let parsed =
3311            usable(&parse_lines("pre-commit plugin-test *.ts block heavy files make plugin")[0])
3312                .clone();
3313        assert!(parsed.heavy && parsed.files);
3314        assert_eq!(parsed.program, "make");
3315        assert_eq!(parsed.args, vec!["plugin".to_string()]);
3316        let externals = parse(
3317            "pre-commit plugin-test *.ts block heavy make plugin\n\
3318             pre-commit cargo-test *.rs block cargo test --locked\n\
3319             pre-commit lint *.sh block shellcheck\n",
3320        );
3321        let weight = |name: &str| {
3322            externals
3323                .iter()
3324                .find(|e| e.short_name == name)
3325                .map(|e| e.weight())
3326                .unwrap()
3327        };
3328        assert_eq!(weight("plugin-test"), Weight::Heavy);
3329        assert_eq!(
3330            weight("cargo-test"),
3331            Weight::Heavy,
3332            "moves pre-push-cargo-test"
3333        );
3334        assert_eq!(weight("lint"), Weight::Light);
3335    }
3336
3337    /// `platform=any` is a marker in any order with `heavy` and `docs-skip`,
3338    /// refused beside `fix` or `files`, and the only `platform=` word.
3339    #[test]
3340    fn platform_any_is_a_marker_refused_with_fix_or_files() {
3341        let line = one("pre-commit lint *.ts block heavy platform=any make lint");
3342        let d = usable(&line);
3343        assert!(d.runs_on == RunsOn::AnyPlatform && d.heavy);
3344        assert_eq!(d.program, "make");
3345        let line = one("pre-commit lint *.ts block platform=any docs-skip make lint");
3346        assert!(usable(&line).runs_on == RunsOn::AnyPlatform && usable(&line).docs_skip);
3347        assert_eq!(
3348            usable(&one("pre-commit lint * block make lint")).runs_on,
3349            RunsOn::Here { reads_index: false }
3350        );
3351        assert_eq!(
3352            why(&one("pre-commit lint * block platform=any fix make fmt")),
3353            ParseError::PlatformAnyWithFix
3354        );
3355        assert_eq!(
3356            why(&one("pre-commit lint * block files platform=any eslint")),
3357            ParseError::PlatformAnyWithFiles
3358        );
3359        assert_eq!(
3360            why(&one("pre-commit lint * block platform=linux make")),
3361            ParseError::BadPlatform("platform=linux".into())
3362        );
3363    }
3364
3365    /// `set executor` is exactly `cluster` or `local`; it and
3366    /// `set clusterPrepare` are each set once.
3367    #[test]
3368    fn the_cluster_settings_are_strict_and_set_once() {
3369        let lines = parse_lines("set executor CLUSTER\nset clusterPrepare pnpm i && pnpm build\n");
3370        assert!(
3371            matches!(&lines[0], Line::Policy { what: PolicyLine::Set { key, value }, .. }
3372            if key == "amont.executor" && value == "cluster")
3373        );
3374        assert!(
3375            matches!(&lines[1], Line::Policy { what: PolicyLine::Set { key, value }, .. }
3376            if key == "amont.clusterPrepare" && value == "pnpm i && pnpm build")
3377        );
3378        for text in [
3379            "set executor remote\n",
3380            "set executor cluster\nset executor local\n",
3381            "set clusterPrepare a\nset clusterPrepare b\n",
3382        ] {
3383            let last = parse_lines(text).pop().expect("a line");
3384            assert!(
3385                matches!(why(&last), ParseError::BadClusterSetting { .. }),
3386                "{text:?}"
3387            );
3388        }
3389    }
3390
3391    /// `onBusy` is exactly `wait` or `defer`, `slotWait` a whole number of
3392    /// seconds in 1..=3600, each once; anything else is a broken line.
3393    #[test]
3394    fn the_busy_policy_keys_are_strict_and_set_once() {
3395        let set = |line: &Line| {
3396            let Line::Policy {
3397                what: PolicyLine::Set { key, value },
3398                ..
3399            } = line
3400            else {
3401                return None;
3402            };
3403            Some((key.clone(), value.clone()))
3404        };
3405        let lines = parse_lines("set onBusy DEFER\nset slotWait 90\nset warnSlotWait 120\n");
3406        assert_eq!(
3407            set(&lines[0]),
3408            Some(("amont.onBusy".into(), "defer".into()))
3409        );
3410        assert_eq!(set(&lines[1]), Some(("amont.slotWait".into(), "90".into())));
3411        assert_eq!(
3412            set(&lines[2]),
3413            Some(("amont.warnSlotWait".into(), "120".into()))
3414        );
3415        for bad in [
3416            "set onBusy later",
3417            "set onBusy defer # busy",
3418            "set slotWait 0",
3419            "set slotWait 3601",
3420            "set slotWait 1m",
3421            "set warnSlotWait 0",
3422            "set warnSlotWait 3601",
3423            "set warnSlotWait 10m",
3424        ] {
3425            let lines = parse_lines(bad);
3426            assert!(set(&lines[0]).is_none(), "{bad:?} must not be a policy");
3427            assert!(
3428                matches!(why(&lines[0]), ParseError::BadBusyPolicy { .. }),
3429                "{bad:?}"
3430            );
3431        }
3432        let lines = parse_lines("set onBusy defer\nset onBusy wait\n");
3433        assert!(set(&lines[0]).is_some());
3434        assert!(matches!(
3435            why(&lines[1]),
3436            ParseError::BadBusyPolicy { key: "onBusy", .. }
3437        ));
3438        let lines = parse_lines("set warnSlotWait 5\nset warnSlotWait 6\n");
3439        assert!(set(&lines[0]).is_some());
3440        assert!(matches!(
3441            why(&lines[1]),
3442            ParseError::BadBusyPolicy {
3443                key: "warnSlotWait",
3444                ..
3445            }
3446        ));
3447    }
3448
3449    #[test]
3450    fn plan_exempt_is_exactly_on_or_off_and_set_once() {
3451        let policy = |l: &Line| match l {
3452            Line::Policy {
3453                what: PolicyLine::Set { key, value },
3454                ..
3455            } => Some((key.clone(), value.clone())),
3456            _ => None,
3457        };
3458        for ok in [
3459            "set planExempt off",
3460            "set PLANEXEMPT On",
3461            "  set\tplanExempt\toff  ",
3462        ] {
3463            let v = parse_lines(ok);
3464            assert!(policy(&v[0]).is_some(), "{ok:?} should parse");
3465            assert_eq!(policy(&v[0]).unwrap().0, "amont.planExempt");
3466        }
3467        // attest's verifiers match only exactly `set planExempt off`, so any
3468        // other shape would silently mean "on" to them: loud here instead.
3469        for bad in [
3470            "set planExempt off # because",
3471            "set planExempt false",
3472            "set planExempt off off",
3473            "set planExempt",
3474        ] {
3475            let v = parse_lines(bad);
3476            assert!(policy(&v[0]).is_none(), "{bad:?} must not be a policy");
3477        }
3478        let v = parse_lines("set planExempt off # because");
3479        assert!(matches!(why(&v[0]), ParseError::BadPlanExempt(_)));
3480        let v = parse_lines("set planExempt off\nset planExempt on\n");
3481        assert!(policy(&v[0]).is_some());
3482        assert!(matches!(why(&v[1]), ParseError::BadPlanExempt(_)));
3483        let v = parse_lines("set planExempt on\nset planExempt off\n");
3484        assert!(matches!(why(&v[1]), ParseError::BadPlanExempt(_)));
3485        for odd in [
3486            "set planExempt off\u{c}",
3487            "\u{b}set planExempt off",
3488            "set planExempt\u{a0}off",
3489        ] {
3490            let v = parse_lines(odd);
3491            assert!(
3492                matches!(why(&v[0]), ParseError::BadPlanExempt(_)),
3493                "{odd:?} must be loud"
3494            );
3495        }
3496    }
3497
3498    fn widened(text: &str) -> Vec<External> {
3499        attach_twin_scopes(parse(text))
3500    }
3501
3502    fn pending(ext: &External) -> Option<&Trigger> {
3503        match &ext.kind {
3504            Kind::Runnable {
3505                pending_trigger, ..
3506            } => pending_trigger.as_deref(),
3507            Kind::Unusable { .. } => None,
3508        }
3509    }
3510
3511    /// A declaration named for a built-in push gate borrows that gate's reach,
3512    /// pending until `resolve_triggers` has judged it blocking: until then its
3513    /// effective scope is the one it wrote.
3514    #[test]
3515    fn a_declaration_borrows_its_builtin_twins_reach_once_resolved_not_before() {
3516        let externals = widened("pre-commit  cargo-test  *.rs  block  cargo test\n");
3517        let trigger = pending(&externals[0]).expect("widened to pre-push-cargo-test's reach");
3518        assert!(trigger.scope.covers("Cargo.lock") && trigger.scope.covers("src/a.rs"));
3519        assert_eq!(trigger.twin_ids(), ["pre-push-cargo-test"]);
3520        let before = externals[0].effective_scope();
3521        assert!(
3522            !before.covers("Cargo.lock"),
3523            "pending is not applied: the narrow side"
3524        );
3525    }
3526
3527    /// The command of a `files` declaration is handed the matched paths, so
3528    /// widening it would hand a linter `Cargo.lock`.
3529    #[test]
3530    fn a_files_declaration_is_never_widened() {
3531        let externals = widened("pre-commit  cargo-test  *.rs  block  files cargo test\n");
3532        assert!(pending(&externals[0]).is_none());
3533    }
3534
3535    /// A twin that acts on every change would turn the commit-time gate into
3536    /// one that runs the suite on every docs commit.
3537    #[test]
3538    fn an_unscoped_twin_does_not_widen() {
3539        let externals = widened(
3540            "pre-commit  check  *.rs  block  make check\n\
3541             pre-push    check  *  block  make check\n",
3542        );
3543        assert!(pending(&externals[0]).is_none());
3544    }
3545
3546    #[test]
3547    fn a_twin_that_adds_nothing_leaves_no_trigger() {
3548        let externals = widened(
3549            "pre-commit  check  *.rs  block  make check\n\
3550             pre-push    check  *.rs  block  make check\n",
3551        );
3552        assert!(pending(&externals[0]).is_none());
3553    }
3554
3555    /// The order of the lines is not the pairing's business.
3556    #[test]
3557    fn a_declared_twin_is_found_before_or_after_the_commit_line() {
3558        for text in [
3559            "pre-commit  check  *.txt  block  x\npre-push  check  *.txt,*.md  block  x\n",
3560            "pre-push  check  *.txt,*.md  block  x\npre-commit  check  *.txt  block  x\n",
3561        ] {
3562            let externals = widened(text);
3563            let commit = externals
3564                .iter()
3565                .find(|e| e.stage == Stage::PreCommit)
3566                .unwrap();
3567            let trigger = pending(commit).expect("widened to the declared twin");
3568            assert!(trigger.scope.covers("notes.md"), "{text}");
3569            assert_eq!(trigger.twin_ids(), ["pre-push-check"]);
3570        }
3571    }
3572
3573    /// A declared `pre-push` line of the same name does not replace the
3574    /// built-in gate that also runs: the commit-time line covers what either
3575    /// acts on, so a `.vue` push is not left to a gap nobody can explain.
3576    #[test]
3577    fn a_declared_twin_and_the_builtin_gate_both_count() {
3578        let externals = widened(
3579            "pre-commit  test  *.ts  block  pnpm test\n\
3580             pre-push    test  *.ts  block  pnpm test\n",
3581        );
3582        let commit = externals
3583            .iter()
3584            .find(|e| e.stage == Stage::PreCommit)
3585            .unwrap();
3586        let trigger = pending(commit).expect("widened to the JS gate's reach");
3587        assert!(trigger.scope.covers("App.vue"), "the built-in gate's files");
3588        assert_eq!(
3589            trigger.twin_ids(),
3590            ["pre-push-test", "pre-push-run-tests-js"],
3591            "the declared twin first, then the built-in gate"
3592        );
3593        assert_eq!(
3594            trigger.twin_for("App.vue"),
3595            "pre-push-run-tests-js",
3596            "a file only the built-in gate reads names that gate"
3597        );
3598    }
3599
3600    /// The npm push gate runs the scripts it names, whatever the repository
3601    /// calls the commit-time line that stands in for one.
3602    #[test]
3603    fn a_gate_script_pairs_with_the_js_push_gate() {
3604        let externals = widened("pre-commit  typecheck  *.ts  block  pnpm typecheck\n");
3605        let trigger = pending(&externals[0]).expect("widened to the JS gate's reach");
3606        assert!(trigger.scope.covers("App.vue") && trigger.scope.covers("a.js"));
3607        assert_eq!(trigger.twin_ids(), ["pre-push-run-tests-js"]);
3608        let unrelated = widened("pre-commit  shellcheck  *.sh  block  shellcheck\n");
3609        assert!(pending(&unrelated[0]).is_none(), "no push twin, no trigger");
3610    }
3611
3612    fn root_runs_members(text: &str) -> Result<String, ParseError> {
3613        let lines = parse_lines(text);
3614        match lines.last().expect("a line") {
3615            Line::Policy {
3616                what: PolicyLine::Set { key, value },
3617                ..
3618            } => {
3619                assert_eq!(key, "amont.rootRunsMembers");
3620                Ok(value.clone())
3621            }
3622            broken => Err(why(broken)),
3623        }
3624    }
3625
3626    /// The scripts a root declares it runs for every member: the npm gate's
3627    /// names, comma-separated, or `none`; nothing else, and once.
3628    #[test]
3629    fn root_runs_members_is_strict_and_set_once() {
3630        assert_eq!(
3631            root_runs_members("set rootRunsMembers test, typecheck\n"),
3632            Ok("test,typecheck".to_string())
3633        );
3634        assert_eq!(
3635            root_runs_members("set rootRunsMembers test:unit\n"),
3636            Ok("test:unit".to_string())
3637        );
3638        assert_eq!(
3639            root_runs_members("set rootRunsMembers NONE\n"),
3640            Ok("none".to_string())
3641        );
3642        for bad in [
3643            "set rootRunsMembers tests",
3644            "set rootRunsMembers lint",
3645            "set rootRunsMembers none,test",
3646            "set rootRunsMembers test,",
3647            "set rootRunsMembers test,,typecheck",
3648        ] {
3649            assert!(
3650                matches!(
3651                    root_runs_members(bad),
3652                    Err(ParseError::BadRootRunsMembers(_))
3653                ),
3654                "{bad:?} must be loud"
3655            );
3656        }
3657        let twice = parse_lines("set rootRunsMembers test\nset rootRunsMembers none\n");
3658        assert!(
3659            matches!(why(&twice[1]), ParseError::BadRootRunsMembers(why) if why == "it is set twice")
3660        );
3661    }
3662}