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