Skip to main content

greengate_runtime/
lib.rs

1//! The git-templates hook logic: registry, dispatchers and every check.
2//!
3//! This is a library so that more than one binary can hold the same truth about
4//! what a hook IS. `amont` (the commit path) executes the checks;
5//! `amont-fleet` reports on how they are installed across the fleet. Before
6//! the split there was no lib target at all, which is why `cargo test --lib`
7//! failed outright.
8//!
9//! **This crate gains no third-party dependency.** The hook binary depends on
10//! it, so anything added here reaches every commit transitively. The one
11//! crate it links is `git-attest`, attest's std-only implementation of the
12//! attestation format (decisions ADR-0037), argued in Cargo.toml and checked
13//! by `scripts/check-no-deps.sh`. ratatui and friends belong in `amont-fleet`.
14//!
15//! Hooks are invoked through a thin `sh` shim at each hook path, which passes
16//! the hooks directory it lives in:
17//!
18//! ```text
19//! amont --hooks-dir <dir> pre-commit [args…]
20//! ```
21
22/// Serialises every test that moves the process cwd **or depends on it**.
23///
24/// The second half of that sentence was missing, and it cost a day. The
25/// lock started as "movers only" — `gate_stamp` and `attest`, which both
26/// talk to "the repository at cwd" and each carried its own mutex, so each
27/// was serialised against itself and raced against the other. But a mover
28/// is only half the hazard: a test that READS the ambient cwd is just as
29/// exposed, because production code spawns git without `-C`. While
30/// `gate_stamp` held cwd inside its fixture, `restage_distinguishes_
31/// nothing_from_failure` ran `git add` — landing in that fixture and
32/// taking its `.git/index.lock`, so the fixture's own `git commit` failed
33/// 128 and the panic surfaced three lines later as a missing gate stamp.
34/// Roughly one run in forty, and unreadable until the fixtures started
35/// reporting git's exit status.
36///
37/// So: if a test moves the cwd, or calls anything that spawns git without
38/// naming a directory, it takes this lock.
39#[cfg(test)]
40pub(crate) static TEST_CWD: std::sync::Mutex<()> = std::sync::Mutex::new(());
41
42pub mod agents_md;
43pub mod attest;
44pub mod attest_inputs;
45pub mod bypass;
46pub mod capture;
47pub mod check;
48pub mod clock;
49pub mod cluster;
50pub mod commit_style;
51pub mod config;
52pub mod content;
53pub mod dispatch;
54pub mod downgrade;
55pub mod excerpt;
56pub mod finding;
57pub mod gate_evidence;
58pub mod gate_identity;
59pub mod gate_stamp;
60pub mod git;
61pub mod hookfile;
62pub mod hooks;
63pub mod host_slots;
64pub mod install;
65pub mod json;
66pub mod json_read;
67pub mod land;
68pub mod live;
69pub mod load;
70pub mod manifest;
71pub mod names;
72pub mod pack;
73pub mod policy;
74pub mod proctree;
75pub mod pushed_tree;
76pub mod pushrefs;
77pub mod registry;
78pub mod rehearsal;
79pub mod run_stamp;
80pub mod setup;
81pub mod skew;
82pub mod slot_cmd;
83pub mod snapshot_prep;
84pub mod staged_only;
85pub mod tree_cache;
86pub mod tree_lint;
87pub mod tree_run;
88pub mod tree_skew;
89pub mod trust;
90pub mod ui;
91pub mod vocabulary;
92pub(crate) mod waves;
93
94use crate::names::BIN;
95use std::path::Path;
96use std::process::{Command, Stdio};
97
98/// `git config --get-all hook.skip`, or empty when unset/unavailable.
99/// The two triggers a check can be attached to, as they are spelled in config.
100///
101/// Deliberately the same strings as `Stage::as_str`, and
102/// `every_id_agrees_with_its_declared_stage` keeps them that way.
103pub const TRIGGERS: [&str; 2] = ["pre-commit", "pre-push"];
104
105/// How specifically a configured value names a check.
106///
107/// Ordered, so that when several keys match one check the most specific wins —
108/// which only matters for `amont.severity`, since a skip is a boolean.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
110pub enum Match {
111    /// `pre-commit` — every check on that trigger.
112    Trigger,
113    /// `clippy` — that check, whichever trigger it is on.
114    ShortName,
115    /// `pre-commit-clippy` — this check and no other.
116    FullId,
117}
118
119/// A check's id without its trigger — `pre-commit-clippy` → `clippy`.
120///
121/// For DISPLAY only, wherever the trigger is already established by a heading
122/// or a neighbouring column. Under a `pre-commit` heading, printing
123/// `pre-commit-clippy` on every row spends eleven columns restating what the
124/// heading said. Never write this to config or compare against it: two checks
125/// can share a short name, and telling them apart is what the id is for.
126pub fn short_name(check: &str) -> &str {
127    for trigger in TRIGGERS {
128        if let Some(short) = check
129            .strip_prefix(trigger)
130            .and_then(|rest| rest.strip_prefix('-'))
131        {
132            return short;
133        }
134    }
135    check
136}
137
138/// Does `pattern`, as written in `hook.skip` or `amont.severity.<pattern>`,
139/// name `check`?
140///
141/// A check's id is `<trigger>-<name>`, and exactly three things name it:
142///
143/// | written | means |
144/// |---|---|
145/// | `pre-commit-clippy` | that one check |
146/// | `pre-commit`        | every check on that trigger |
147/// | `clippy`            | that check, on any trigger |
148///
149/// Three exact comparisons. **No substring.** The previous rule was
150/// `check.contains(skip)`, which made `hook.skip = clippy` work by accident of
151/// reach — and `hook.skip = e` disable all twenty checks by the same accident,
152/// and `lint-js` silently also suppress `lint-json-yaml`. Naming the three
153/// things a user actually means keeps every useful case and removes every
154/// sharp edge, including the one the old doc comment called "not a bug".
155///
156/// This reads the trigger out of the ID, which is not the same as deriving a
157/// check's stage: `Stage` remains a declared field and is what the dispatcher
158/// obeys. Here we are parsing an identifier a human typed.
159///
160/// Defined ONCE because four callers need it — the dispatcher decides what
161/// runs, the severity resolver decides what blocks, the fleet view reports
162/// where a check applies, and the skip resolver computes reach. A
163/// reimplementation that disagreed would have the dashboard claim a check is
164/// active while the dispatcher skips it.
165pub fn names_check(check: &str, pattern: &str) -> Option<Match> {
166    if check == pattern {
167        return Some(Match::FullId);
168    }
169    for trigger in TRIGGERS {
170        let Some(short) = check
171            .strip_prefix(trigger)
172            .and_then(|rest| rest.strip_prefix('-'))
173        else {
174            continue;
175        };
176        // An id carries one trigger, so the first that matches is the answer.
177        if pattern == trigger {
178            return Some(Match::Trigger);
179        }
180        if pattern == short {
181            return Some(Match::ShortName);
182        }
183        return None;
184    }
185    None
186}
187
188/// Does `skip`, as configured in `hook.skip`, suppress `check`?
189pub fn skip_suppresses(check: &str, skip: &str) -> bool {
190    names_check(check, skip).is_some()
191}
192
193/// One check, as reported by `amont list`.
194///
195/// Deliberately flat — this is what gets rendered as text or serialised to
196/// JSON, and a reader (human or agent) parsing the latter should not have to
197/// chase nested objects for a yes/no question.
198#[derive(Debug, Clone)]
199pub struct CheckListing {
200    /// `<trigger>-<name>` — what `hook.skip` and `amont.severity.<key>`
201    /// resolve against.
202    pub id: String,
203    pub short_name: String,
204    pub stage: check::Stage,
205    pub source: Source,
206    /// What the check (or manifest line) declared.
207    pub declared_severity: check::Severity,
208    /// For a declared check, what its `amont.conf` line says, trusted or
209    /// not: `declared_severity` reads `warn` for a check that cannot run,
210    /// an untrusted one included, and a reader asking what the repository
211    /// declares needs the line's own word. `None` for a builtin and for a
212    /// line that did not parse.
213    pub manifest_severity: Option<check::Severity>,
214    /// What `registry::Overrides::of` would actually apply — NOT the same as
215    /// `declared_severity` once `amont.severity.*` is configured. This is
216    /// the one thing the old text-only `list_checks` never reported, and the
217    /// exact "declared vs. effective" gap that caused a real bug in the
218    /// fleet's own severity column (see `greengate-fleet/src/severities.rs`).
219    pub effective_severity: check::Severity,
220    pub severity_overridden: bool,
221    /// Where the winning override came from, only when one applies —
222    /// strictly additive next to `severity_overridden`, whose meaning is
223    /// unchanged.
224    pub severity_source: Option<registry::Source>,
225    pub fix: check::Fix,
226    pub status: Status,
227    /// Empty when `status == Status::Runs`; the same prose the text output
228    /// always showed for the other three states.
229    pub reason: String,
230    pub scope_files: Vec<String>,
231    pub scope_opt_in: Vec<String>,
232    /// `Some` only for a declared, `Runnable` external — a builtin has no
233    /// command to show, and an `Unusable` external never got far enough to
234    /// have one.
235    pub command: Option<String>,
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239pub enum Source {
240    Builtin,
241    Declared,
242}
243
244/// The four states the text output's glyphs already named. Not called
245/// `Outcome` — that type means what a check concluded when it RAN; this means
246/// whether it would run at all, the same question `Scope::matches` answers.
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
248pub enum Status {
249    Runs,
250    Inert,
251    Skipped,
252    Unusable,
253}
254
255pub struct ListOptions {
256    pub json: bool,
257    pub stage: Option<check::Stage>,
258    pub pushed: bool,
259    /// Print the inert checks too, one row each, as this always did.
260    pub all: bool,
261}
262
263/// Every check that would be considered for `stage_filter` (or both stages,
264/// when `None`), evaluated against `paths`.
265///
266/// Reads `hook.skip` and `amont.severity.*` from the current repo's git
267/// config, same as the original `list_checks` did — this is why it is not
268/// unit-tested in isolation; see `hooks/pull_rebase.rs`'s own split between
269/// pure helpers (unit-tested) and config-dependent behaviour (integration
270/// tested) for the precedent.
271pub fn gather_checks(
272    settings: &crate::config::Settings,
273    stage_filter: Option<check::Stage>,
274    paths: &[String],
275    manifest: &manifest::Manifest,
276) -> Vec<CheckListing> {
277    use crate::check::Stage;
278    let stages: Vec<Stage> = match stage_filter {
279        Some(s) => vec![s],
280        None => vec![Stage::PreCommit, Stage::PrePush],
281    };
282    let skips = configured_skips(settings);
283    let overrides = registry::Overrides::read(settings);
284    let externals_by_id: std::collections::BTreeMap<&str, &manifest::External> = manifest
285        .externals
286        .iter()
287        .map(|e| (e.id.as_str(), e))
288        .collect();
289
290    let mut out = Vec::new();
291    for stage in stages {
292        // Externals are listed here too, and marked, because the question
293        // this command answers — "would this run here?" — is asked most
294        // often about the check somebody just added to `amont.conf`.
295        for check in registry::all_stage_checks(stage, manifest) {
296            let name = check.name();
297            let external = externals_by_id.get(name).copied();
298            let skipped = skips.iter().any(|s| skip_suppresses(name, s));
299            let applies = check.scope().matches(paths);
300
301            let unusable_why = external.and_then(|e| match &e.kind {
302                manifest::Kind::Unusable { why, .. } => Some(why.as_str()),
303                manifest::Kind::Runnable { .. } => None,
304            });
305            // Four states: a check that is correctly silent must never look
306            // like one that is disabled, and neither must look like one
307            // whose declaration could not be read.
308            let (status, reason) = if let Some(w) = unusable_why {
309                (Status::Unusable, format!("{} {w}", manifest::MANIFEST))
310            } else if skipped {
311                // Which source? Policy skips read differently from machine
312                // skips — the legend and the fleet detail pane echo this
313                // wording, so the three move together.
314                let via = if settings
315                    .policy()
316                    .skips
317                    .iter()
318                    .any(|s| skip_suppresses(name, s))
319                {
320                    "skipped via amont.conf"
321                } else {
322                    "skipped via hook.skip"
323                };
324                (Status::Skipped, via.to_string())
325            } else if applies {
326                (Status::Runs, String::new())
327            } else {
328                (
329                    Status::Inert,
330                    format!("inert here — needs {}", describe(check.scope())),
331                )
332            };
333
334            let command = external.and_then(|e| match &e.kind {
335                manifest::Kind::Runnable { program, args, .. } => Some(
336                    std::iter::once(program.as_str())
337                        .chain(args.iter().map(String::as_str))
338                        .collect::<Vec<_>>()
339                        .join(" "),
340                ),
341                manifest::Kind::Unusable { .. } => None,
342            });
343
344            let declared_severity = check.severity();
345            let effective_severity = overrides.of(check);
346            let severity_source = overrides
347                .applied_with_source(name)
348                .map(|(_, _, src)| src)
349                .filter(|_| declared_severity != effective_severity);
350            out.push(CheckListing {
351                id: name.to_string(),
352                short_name: short_name(name).to_string(),
353                stage,
354                source: if external.is_some() {
355                    Source::Declared
356                } else {
357                    Source::Builtin
358                },
359                declared_severity,
360                manifest_severity: external.and_then(manifest::External::manifest_severity),
361                effective_severity,
362                severity_overridden: declared_severity != effective_severity,
363                severity_source,
364                fix: check.fix(),
365                status,
366                reason,
367                scope_files: {
368                    let scope = check.scope();
369                    scope
370                        .files
371                        .iter()
372                        .chain(scope.names.iter())
373                        .map(|s| s.to_string())
374                        .collect()
375                },
376                scope_opt_in: check.scope().opt_in.iter().map(|s| s.to_string()).collect(),
377                command,
378            });
379        }
380    }
381    out
382}
383
384/// BYTE-IDENTICAL to what `list_checks` printed before it grew `--json`.
385/// `listings` is already stage-grouped (`gather_checks` iterates stage by
386/// stage), so a heading prints exactly once per stage encountered, in the
387/// same order.
388/// The ecosystem a scope token belongs to, for the inert summary.
389///
390/// Presentational and deliberately incomplete: a token nobody has mapped
391/// simply does not get named, and its check is still counted. The alternative
392/// — a `family` field on every `Builtin` — is thirty-seven places for a label
393/// to drift out of step with the scope that actually decides anything.
394///
395/// Generic tokens (`.yaml`, `.json`) are absent on purpose. Four checks want
396/// `.yaml` for four different reasons, so naming YAML here would tell a reader
397/// their repository is "missing YAML checks" when what it is missing is
398/// Kubernetes.
399fn ecosystem(token: &str) -> Option<&'static str> {
400    Some(match token {
401        ".rs" | "Cargo.toml" | "Cargo.lock" => "Rust",
402        ".go" | "go.mod" | "go.sum" => "Go",
403        ".py"
404        | ".pyi"
405        | "requirements.txt"
406        | "pyproject.toml"
407        | "ruff.toml"
408        | ".ruff.toml"
409        | "pytest.ini"
410        | "conftest.py"
411        | "pyrightconfig.json"
412        | "pyrightconfig.jsonc" => "Python",
413        ".js" | ".jsx" | ".ts" | ".tsx" | ".vue" | "package.json" | "package-lock.json" => {
414            "JavaScript"
415        }
416        "kustomization.yaml" | "kustomization.yml" => "Kubernetes",
417        t if t.starts_with(".kube-linter") => "Kubernetes",
418        t if t.starts_with(".prettierrc") || t == "prettier.config.js" => "JavaScript",
419        _ => return None,
420    })
421}
422
423/// Every check that would run here, and one line for the ones that would not.
424///
425/// The default used to print all thirty-odd rows interleaved alphabetically.
426/// In a repository amont serves well that is about half inert; in one built on
427/// a stack it does not cover yet it is two thirds — and every one of those rows
428/// names somebody else's language. Read top to bottom it says "this tool is for
429/// other people", which is the opposite of true: the checks that DO run are
430/// `secrets`, `large-files` and `merge-conflict`, the ones that prevent
431/// incidents in any repository at all.
432///
433/// So the inert rows collapse to a count and the ecosystems they belong to.
434/// `--all` brings them back, because "why is clippy not running" is a real
435/// question with a real answer already written.
436///
437/// **Skipped and unusable rows are never collapsed.** `⊘` means somebody
438/// silenced a check and `✗` means a declaration is broken; both are things the
439/// reader has to act on, and both would be lost in a count.
440pub fn print_text(listings: &[CheckListing], all: bool) {
441    let shown: Vec<&CheckListing> = listings
442        .iter()
443        .filter(|l| all || l.status != Status::Inert)
444        .collect();
445
446    let mut current: Option<check::Stage> = None;
447    for l in &shown {
448        if current != Some(l.stage) {
449            println!("{}", ui::highlight(l.stage.as_str()));
450            current = Some(l.stage);
451        }
452        let glyph = match l.status {
453            Status::Unusable => '✗',
454            Status::Skipped => '⊘',
455            Status::Runs => '●',
456            Status::Inert => '○',
457        };
458        // The SHORT name: this loop is already inside a `pre-commit` /
459        // `pre-push` heading, so printing the trigger on all twenty rows
460        // restates the heading twenty times and pushes the reason — the part
461        // that differs per row — eleven columns to the right.
462        //
463        // Where a check CAME FROM belongs next to its name, not appended
464        // after a reason that is often empty. A reader scanning this list
465        // wants to know which of these their repository added.
466        // A declared check's name and its reason both come from the
467        // repository's manifest, and `amont list` is read at least as often
468        // as the trust prompt. Sanitised before padding, so the column width is
469        // computed on what is printed — see `ui::sanitize`.
470        let short_name = ui::sanitize(&l.short_name);
471        let label = match l.source {
472            Source::Declared => format!("{short_name} (declared)"),
473            Source::Builtin => short_name,
474        };
475        println!("  {glyph} {label:<26} {}", ui::sanitize(&l.reason));
476    }
477
478    let runs = listings.iter().filter(|l| l.status == Status::Runs).count();
479    let inert: Vec<&CheckListing> = listings
480        .iter()
481        .filter(|l| l.status == Status::Inert)
482        .collect();
483
484    println!();
485    if inert.is_empty() {
486        println!("  {runs} active here.");
487    } else if all {
488        println!("  {runs} active here, {} inert.", inert.len());
489    } else {
490        let mut families: Vec<&str> = inert
491            .iter()
492            .flat_map(|l| l.scope_files.iter().chain(l.scope_opt_in.iter()))
493            .filter_map(|t| ecosystem(t))
494            .collect();
495        families.sort_unstable();
496        families.dedup();
497        let named = if families.is_empty() {
498            String::new()
499        } else {
500            format!(" ({})", families.join(", "))
501        };
502        println!(
503            "  {runs} active here.  {} inert{named} — {BIN} list --all",
504            inert.len()
505        );
506    }
507    println!("  ● runs here   ○ inert   ⊘ skipped via hook.skip   ✗ declaration unusable");
508}
509
510/// What `commit-msg` will enforce here, and where each answer came from.
511///
512/// Printed **always**, not only when something has been configured. The
513/// defaults are the divisive part — a gitmoji in every subject, a 50-character
514/// description — and somebody who wants them changed has no reason to guess
515/// that four keys exist. `amont list` is where they are already looking, so
516/// it is where the dial belongs.
517///
518/// The source column appears only for a value somebody set: repeating
519/// "default" on four rows spends a column restating the line underneath.
520pub fn print_commit_style(style: &commit_style::Style, rows: &[commit_style::Setting]) {
521    println!();
522    println!("{}", ui::highlight("commit style"));
523    for r in rows {
524        let origin = if r.set_here {
525            format!("{} ({})", r.key, r.scope.as_str())
526        } else {
527            String::new()
528        };
529        println!("  {:<18} {:<10} {origin}", r.label, r.value);
530    }
531    println!();
532    for w in style.warnings() {
533        println!("  {} {w}", ui::warning_sign().trim());
534    }
535    println!("  `{BIN} setup` to change any of these");
536}
537
538/// The commit-style block as JSON: the effective value, the shipped default,
539/// whether they differ and where the answer came from — the same
540/// declared-vs-effective shape `CheckListing` uses for severity.
541fn commit_style_json(style: &commit_style::Style, rows: &[commit_style::Setting]) -> String {
542    let setting = |r: &commit_style::Setting, value: String, default: String| {
543        json::object(&[
544            format!("\"value\":{value}"),
545            format!("\"default\":{default}"),
546            json::bool_field("overridden", r.overridden),
547            json::bool_field("set_here", r.set_here),
548            json::string_field("source", r.scope.as_str()),
549            json::string_field("key", r.key),
550        ])
551    };
552    let d = commit_style::Style::default();
553    // `rows` is built in this order by `commit_style::describe`, and the
554    // numbers are emitted as numbers so a reader can compare them.
555    let quoted = |s: &str| format!("\"{}\"", json::escape(s));
556    let fields: Vec<String> = rows
557        .iter()
558        .map(|r| {
559            let (value, default) = match r.key {
560                commit_style::KEY_GITMOJI => {
561                    (quoted(style.gitmoji.as_str()), quoted(d.gitmoji.as_str()))
562                }
563                commit_style::KEY_SUBJECT_MAX => {
564                    (style.subject_max.to_string(), d.subject_max.to_string())
565                }
566                commit_style::KEY_DESCRIPTION_MAX => (
567                    style.description_max.to_string(),
568                    d.description_max.to_string(),
569                ),
570                _ => (style.body_wrap.to_string(), d.body_wrap.to_string()),
571            };
572            let name = r.key.rsplit('.').next().unwrap_or(r.key);
573            format!("\"{}\":{}", json::escape(name), setting(r, value, default))
574        })
575        .collect();
576
577    let warnings: Vec<String> = style.warnings();
578    let mut all = fields;
579    all.push(json::string_array_field("warnings", &warnings));
580    json::object(&all)
581}
582
583/// The format id this document declares, as its first field.
584///
585/// Every other machine-readable thing this tool writes carries one and
586/// REFUSES what it does not recognise — `amont-gate-v1`, `amont-held-v1`,
587/// `amont-skew-v1`, `amont-bypasses-v1`, and `amont-attest-v2`, whose bump
588/// exists precisely so a v1 verifier reads a v2 note as no note rather than
589/// misreading it. This document, the most public machine surface of the
590/// three, carried none: a reader had no way to state which contract it was
591/// written against, so a rename here would land as a silently different
592/// answer rather than a failure. Bump the version when a field's MEANING
593/// changes or one is removed; adding a field keeps it, which is what the
594/// object shape below was already for.
595pub const LIST_FORMAT: &str = "amont-list-v1";
596
597/// `{"format": "amont-list-v1", "stage_filter": ..., "checks": [...]}` — an
598/// object, not a bare array, so a field can be added later without changing
599/// the top-level shape.
600pub fn print_json(
601    settings: &crate::config::Settings,
602    stage_filter: Option<check::Stage>,
603    pushed: bool,
604    listings: &[CheckListing],
605    bypasses: &bypass::Ledger,
606    downgrades: &downgrade::Ledger,
607    conventions_apply: bool,
608) {
609    let checks: Vec<String> = listings
610        .iter()
611        .map(|l| {
612            json::object(&[
613                json::string_field("id", &l.id),
614                json::string_field("short_name", &l.short_name),
615                json::string_field("stage", l.stage.as_str()),
616                json::string_field(
617                    "source",
618                    match l.source {
619                        Source::Builtin => "builtin",
620                        Source::Declared => "declared",
621                    },
622                ),
623                json::string_field("declared_severity", l.declared_severity.as_str()),
624                json::opt_string_field(
625                    "manifest_severity",
626                    l.manifest_severity.map(check::Severity::as_str),
627                ),
628                json::string_field("effective_severity", l.effective_severity.as_str()),
629                json::bool_field("severity_overridden", l.severity_overridden),
630                json::opt_string_field(
631                    "severity_source",
632                    l.severity_source.map(registry::Source::as_str),
633                ),
634                json::string_field("fix", l.fix.as_str()),
635                json::string_field(
636                    "status",
637                    match l.status {
638                        Status::Runs => "runs",
639                        Status::Inert => "inert",
640                        Status::Skipped => "skipped",
641                        Status::Unusable => "unusable",
642                    },
643                ),
644                json::string_field("reason", &l.reason),
645                json::string_array_field("scope_files", &l.scope_files),
646                json::string_array_field("scope_opt_in", &l.scope_opt_in),
647                json::opt_string_field("command", l.command.as_deref()),
648            ])
649        })
650        .collect();
651
652    let (style, rows) = commit_style::describe(settings);
653    println!(
654        "{}",
655        json::object(&[
656            json::string_field("format", LIST_FORMAT),
657            json::opt_string_field("stage_filter", stage_filter.map(check::Stage::as_str)),
658            json::bool_field("pushed", pushed),
659            format!("\"checks\":{}", json::array(&checks)),
660            format!("\"commit_style\":{}", commit_style_json(&style, &rows)),
661            format!("\"branch_style\":{}", branch_style_json()),
662            format!("\"bypasses\":{}", bypasses_json(bypasses)),
663            format!("\"downgrades\":{}", downgrades_json(downgrades)),
664            json::bool_field("conventions_apply", conventions_apply),
665            format!("\"installed\":{}", install::installed_here().to_json()),
666            format!(
667                "\"template_dir\":{}",
668                install::installed_in_template_dir().to_json()
669            ),
670        ])
671    );
672}
673
674/// `{"total": N, "last": <epoch|null>, "by_script": [...]}` — the ledger of
675/// unverified commits, so a parsing reader (the fleet, an agent) sees the
676/// same numbers `amont list` prints.
677fn downgrades_json(l: &downgrade::Ledger) -> String {
678    let by_check: Vec<String> = l
679        .by_check
680        .iter()
681        .map(|c| {
682            json::object(&[
683                json::string_field("check", &c.check),
684                json::int_field("count", c.count as i64),
685                json::int_field("would_block", c.would_block as i64),
686                json::int_field("last", c.last as i64),
687            ])
688        })
689        .collect();
690    json::object(&[
691        json::int_field("total", l.total as i64),
692        json::int_field("would_block", l.would_block as i64),
693        json::int_field("commits", l.commits as i64),
694        json::opt_int_field("first", l.first.map(|v| v as i64)),
695        json::opt_int_field("last", l.last.map(|v| v as i64)),
696        format!("\"by_check\":{}", json::array(&by_check)),
697    ])
698}
699
700fn bypasses_json(l: &bypass::Ledger) -> String {
701    let by_script: Vec<String> = l
702        .by_script
703        .iter()
704        .map(|s| {
705            json::object(&[
706                json::string_field("script", &s.script),
707                json::int_field("count", s.count as i64),
708                json::int_field("last", s.last as i64),
709            ])
710        })
711        .collect();
712    json::object(&[
713        json::int_field("total", l.total as i64),
714        json::opt_int_field("last", l.last.map(|v| v as i64)),
715        format!("\"by_script\":{}", json::array(&by_script)),
716    ])
717}
718
719/// The branch contract, in the same document agents are told to consult — so
720/// the pattern is knowable BEFORE a branch is created rather than discovered
721/// at push time. Rendered from `vocabulary::BRANCH_PREFIXES`, the same table
722/// `pre-push-branch-pattern` enforces: there is no second copy to drift.
723fn branch_style_json() -> String {
724    let prefixes: Vec<String> = vocabulary::BRANCH_PREFIXES
725        .iter()
726        .map(|p| p.name.to_string())
727        .collect();
728    json::object(&[
729        json::string_field("shape", "<prefix>/<name>"),
730        json::string_field("pattern", &vocabulary::branch_contract()),
731        json::string_array_field("prefixes", &prefixes),
732    ])
733}
734
735/// `git ls-files` — every check's default scope evaluation, unchanged from
736/// what `list_checks` always did.
737///
738/// Through `git::stdout_paths`, i.e. with `-z`. A raw `ls-files` QUOTES any
739/// path holding an unusual byte: `é.json` comes back as the nine-byte literal
740/// `"\303\251.json"`, which ends with a quote rather than an extension, so
741/// `Scope::matches` reports a check as irrelevant to a repository it plainly
742/// covers. Cosmetic here (this only decides what `list` prints) and not
743/// cosmetic in `dispatch::enter_all_files_mode`, which is the same bug — so
744/// both ask the same way.
745pub(crate) fn tracked_paths() -> Vec<String> {
746    git::stdout_paths(&["ls-files"]).unwrap_or_default()
747}
748
749/// The pushed-range file list, computed standalone rather than from a real
750/// pre-push invocation's stdin.
751///
752/// Reuses `pushrefs::changed_files`, which already handles zero-oid deletes,
753/// merge commits and the `--stdin` trailing-newline edge case — this only
754/// SYNTHESISES the one `PushRef` a standalone invocation has no other way to
755/// obtain.
756fn pushed_paths() -> Result<Vec<String>, String> {
757    let synthetic = pushrefs::synthetic_from_upstream()?;
758    Ok(pushrefs::changed_files(&[synthetic]))
759}
760
761/// `amont list`: what would run here, and why — as prose, or as
762/// `--json` for a reader that wants to parse it.
763pub fn list_checks(opts: ListOptions) -> i32 {
764    let paths = if opts.pushed {
765        match pushed_paths() {
766            Ok(p) => p,
767            Err(msg) => {
768                if opts.json {
769                    println!("{}", json::object(&[json::string_field("error", &msg)]));
770                } else {
771                    eprintln!("{BIN}: {msg}");
772                }
773                return 2;
774            }
775        }
776    } else {
777        tracked_paths()
778    };
779    // Loaded HERE, with the repository this command is standing in — the
780    // owned-manifest shape every entrypoint now follows. See manifest::load.
781    let manifest = manifest::load(std::path::Path::new(&hooks::common::repo_root()));
782    // The policy is OWNED here and borrowed downstream. The invariant that
783    // used to be a comment — install immediately after load, before any
784    // config read — is now the borrow checker's: nothing downstream can read
785    // configuration without being handed this.
786    let settings = crate::config::Settings::new(manifest.policy.clone());
787    let listings = gather_checks(&settings, opts.stage, &paths, &manifest);
788    let bypasses = bypass::read();
789    let downgrades = downgrade::read();
790    let conventions_apply = dispatch::conventions_apply(&settings, &manifest);
791    if opts.json {
792        print_json(
793            &settings,
794            opts.stage,
795            opts.pushed,
796            &listings,
797            &bypasses,
798            &downgrades,
799            conventions_apply,
800        );
801    } else {
802        print_text(&listings, opts.all);
803        // Not filtered by `--stage`: commit style belongs to no stage, and
804        // suppressing it for `--stage pre-push` would only hide it from the
805        // reader who narrowed their question.
806        let (style, rows) = commit_style::describe(&settings);
807        print_commit_style(&style, &rows);
808        print_bypasses(&bypasses);
809        print_downgrades(&downgrades);
810        if !conventions_apply {
811            println!(
812                "\n  ! conventions held back — no amont.conf here and amont.conventions \
813                 is `declared`; only the safety net runs"
814            );
815        }
816    }
817    0
818}
819
820/// The shadow-mode worksheet, only when there is one — a repository that has
821/// never warned about anything keeps its old output byte-for-byte.
822///
823/// This is what a fortnight of `amont.severity.pre-commit warn` is FOR: the
824/// counts are the argument, and the footer carries the one action a reader
825/// takes afterwards. Repeating a config line per row would bury it.
826fn print_downgrades(l: &downgrade::Ledger) {
827    if l.total == 0 {
828        return;
829    }
830    let now = std::time::SystemTime::now()
831        .duration_since(std::time::UNIX_EPOCH)
832        .map(|d| d.as_secs())
833        .unwrap_or_default();
834    println!("\nproblems that did not block");
835    let pad = l
836        .by_check
837        .iter()
838        .map(|c| ui::sanitize(&c.check).chars().count())
839        .max()
840        .unwrap_or(0);
841    for c in &l.by_check {
842        // A check that declares `warn` itself was never going to block, and
843        // saying so inline stops it being read as rollout evidence.
844        let advisory = if c.would_block == 0 {
845            "  (advisory)"
846        } else {
847            ""
848        };
849        println!(
850            "  {:<pad$}  {:>3}   last {}{}",
851            ui::sanitize(&c.check),
852            c.count,
853            bypass::age(now, c.last),
854            advisory
855        );
856    }
857    // Events and commits are different facts: forty commits each tripping a
858    // check once is a check the team disagrees with, while one commit tripping
859    // it forty times is one person losing an afternoon.
860    let since = l
861        .first
862        .map(|f| format!(", since {}", bypass::age(now, f)))
863        .unwrap_or_default();
864    println!(
865        "  {} event{} over {} commit{}{since}",
866        l.total,
867        if l.total == 1 { "" } else { "s" },
868        l.commits,
869        if l.commits == 1 { "" } else { "s" },
870    );
871    if l.would_block > 0 {
872        println!(
873            "  {} of them would have blocked — set amont.severity.<check> to keep one \
874             advisory when you go back to block",
875            l.would_block
876        );
877    }
878}
879
880/// The unverified-commit tally, only when there is one — a clean repository's
881/// `amont list` output stays byte-identical to what it always was.
882fn print_bypasses(l: &bypass::Ledger) {
883    if l.total == 0 {
884        return;
885    }
886    let now = std::time::SystemTime::now()
887        .duration_since(std::time::UNIX_EPOCH)
888        .map(|d| d.as_secs())
889        .unwrap_or_default();
890    println!("\nunverified commits");
891    let pad = l
892        .by_script
893        .iter()
894        .map(|s| ui::sanitize(&s.script).chars().count())
895        .max()
896        .unwrap_or(0);
897    for s in &l.by_script {
898        println!(
899            "  {:<pad$}  {:>3}   last {}",
900            ui::sanitize(&s.script),
901            s.count,
902            bypass::age(now, s.last)
903        );
904    }
905    println!(
906        "  these commits carry no record that their commit-time gate ran — the push gate ran it instead"
907    );
908}
909
910fn describe(s: crate::check::Scope) -> String {
911    let files = if s.is_unscoped() {
912        String::new()
913    } else {
914        s.files
915            .iter()
916            .chain(s.names.iter())
917            .chain(s.dirs.iter())
918            .copied()
919            .collect::<Vec<_>>()
920            .join(" ")
921    };
922    let opt = s.opt_in.join(" | ");
923    match (files.is_empty(), opt.is_empty()) {
924        (false, false) => format!("{files} + {opt}"),
925        (false, true) => files,
926        (true, false) => opt,
927        (true, true) => "nothing".into(),
928    }
929}
930
931/// The machine's `hook.skip` entries PLUS the trusted policy's `skip`
932/// lines — the union every resolution site sees. Callers that must tell the
933/// two apart (the dispatcher announces them separately) use
934/// [`skips_by_source`].
935pub fn configured_skips(settings: &config::Settings) -> Vec<String> {
936    policy::union_skips(machine_skips(), settings.policy())
937}
938
939/// `(machine, policy)` — the split the announcements need: "you decided
940/// this" and "your team decided this" are different things to be told.
941pub fn skips_by_source(settings: &config::Settings) -> (Vec<String>, Vec<String>) {
942    (machine_skips(), settings.policy().skips.clone())
943}
944
945/// The check names one `hook.skip` value carries. A value may join several
946/// with commas (`-c hook.skip=clippy,prettier`), which is the same as one
947/// `hook.skip` per name. A check id is letters, digits, `.`, `_` and `-`, so a
948/// comma can never be part of a name and the split is never ambiguous. Names
949/// are matched exactly afterwards, as ever: joining never turns one into a glob.
950pub fn skip_names(value: &str) -> impl Iterator<Item = &str> {
951    value
952        .split(',')
953        .map(str::trim)
954        .filter(|name| !name.is_empty())
955}
956
957fn machine_skips() -> Vec<String> {
958    let Ok(out) = Command::new("git")
959        .args(["config", "--get-all", "hook.skip"])
960        .stderr(Stdio::null())
961        .output()
962    else {
963        return Vec::new();
964    };
965    String::from_utf8_lossy(&out.stdout)
966        .lines()
967        .flat_map(skip_names)
968        .map(str::to_owned)
969        .collect()
970}
971
972/// Which git operations are part-way through, from the markers in `$GIT_DIR`.
973///
974/// Asks git directly rather than deriving a path from `hooks_dir`. That used
975/// to be `hooks_dir.parent()` — correct for the main worktree, where hooks
976/// live in `.git/hooks` and `.git` IS `$GIT_DIR`, but wrong for a LINKED
977/// worktree: hooks dispatch from the COMMON directory's `hooks/`, shared
978/// across every worktree, while `MERGE_HEAD`/`CHERRY_PICK_HEAD`/etc. live in
979/// each worktree's own PRIVATE gitdir under `.git/worktrees/<name>`.
980/// Conflating the two silently disabled this guard for every linked
981/// worktree — the same mistake `staged_only`'s store path made, which lost
982/// unstaged work outright; see its module doc.
983pub fn git_states_in_progress() -> Vec<crate::check::GitState> {
984    let Some(git_dir) = crate::git::stdout(&["rev-parse", "--git-dir"]) else {
985        return Vec::new();
986    };
987    let git_dir = Path::new(&git_dir);
988    crate::check::GitState::ALL
989        .into_iter()
990        .filter(|state| {
991            state
992                .markers()
993                .iter()
994                .any(|marker| git_dir.join(marker).exists())
995        })
996        .collect()
997}
998
999/// True during a cherry-pick, where the zsh `pre-commit` exited 0 immediately.
1000/// Superseded internally by [`git_states_in_progress`]; kept for whatever
1001/// still calls it directly. See that function for why this asks git rather
1002/// than deriving a path from `hooks_dir`.
1003pub fn cherry_pick_in_progress() -> bool {
1004    crate::git::stdout(&["rev-parse", "--git-dir"])
1005        .map(|d| Path::new(&d).join("CHERRY_PICK_HEAD").exists())
1006        .unwrap_or(false)
1007}
1008
1009#[cfg(test)]
1010mod naming {
1011    use super::*;
1012
1013    /// A joined value is the same as one skip per name; spaces, empty pieces
1014    /// and a trailing comma change nothing, and a lone name is untouched.
1015    #[test]
1016    fn a_comma_joined_skip_is_one_skip_per_name() {
1017        fn names(v: &str) -> Vec<&str> {
1018            skip_names(v).collect()
1019        }
1020        assert_eq!(names("clippy"), ["clippy"]);
1021        assert_eq!(
1022            names("pre-commit-cargo-test,pre-commit-plugin-test"),
1023            ["pre-commit-cargo-test", "pre-commit-plugin-test"]
1024        );
1025        assert_eq!(names(" a , b ,,c, "), ["a", "b", "c"]);
1026        assert!(names(" , ").is_empty());
1027    }
1028
1029    /// Joining never widens a name: each piece is matched exactly, as a
1030    /// separate `hook.skip` would be, so `e,clippy` still reaches nothing by `e`.
1031    #[test]
1032    fn joining_names_does_not_turn_them_into_globs() {
1033        assert!(!skip_suppresses("pre-commit-clippy", "e"));
1034        assert!(skip_names("e,clippy").any(|n| skip_suppresses("pre-commit-clippy", n)));
1035        assert!(!skip_names("e,lint").any(|n| skip_suppresses("pre-commit-clippy", n)));
1036    }
1037
1038    /// The three things a user can write, and what each reaches.
1039    #[test]
1040    fn three_ways_to_name_a_check() {
1041        assert_eq!(
1042            names_check("pre-commit-clippy", "pre-commit-clippy"),
1043            Some(Match::FullId)
1044        );
1045        assert_eq!(
1046            names_check("pre-commit-clippy", "pre-commit"),
1047            Some(Match::Trigger)
1048        );
1049        assert_eq!(
1050            names_check("pre-commit-clippy", "clippy"),
1051            Some(Match::ShortName)
1052        );
1053    }
1054
1055    /// The hazards the old substring rule created, all gone by construction.
1056    #[test]
1057    fn nothing_matches_by_accident() {
1058        // `hook.skip = e` disabled all twenty checks. It now reaches nothing.
1059        for pattern in ["e", "t", "i", ""] {
1060            assert_eq!(
1061                names_check("pre-commit-clippy", pattern),
1062                None,
1063                "{pattern:?}"
1064            );
1065        }
1066        // A partial word is not a name.
1067        assert_eq!(names_check("pre-commit-clippy", "clip"), None);
1068        assert_eq!(names_check("pre-commit-clippy", "lint"), None);
1069        // The wrong trigger reaches nothing.
1070        assert_eq!(names_check("pre-commit-clippy", "pre-push"), None);
1071        // And the empty string names nothing, rather than everything — git
1072        // stores `hook.skip` with no value as exactly this.
1073        assert_eq!(names_check("pre-commit-clippy", ""), None);
1074    }
1075
1076    /// The coupling `docs/hook-skip-management.md` warned about: `lint-js` is a
1077    /// substring of `lint-json-yaml`, so skipping one used to skip both.
1078    #[test]
1079    fn a_short_name_does_not_reach_a_longer_one() {
1080        assert!(names_check("pre-commit-lint-json-yaml", "lint-js").is_none());
1081        assert_eq!(
1082            names_check("pre-commit-lint-js", "lint-js"),
1083            Some(Match::ShortName)
1084        );
1085        assert_eq!(
1086            names_check("pre-commit-lint-json-yaml", "lint-json-yaml"),
1087            Some(Match::ShortName)
1088        );
1089    }
1090
1091    /// The one value that exists in the real fleet.
1092    #[test]
1093    fn the_fleets_only_skip_still_resolves() {
1094        assert_eq!(
1095            names_check("pre-push-run-tests-js", "run-tests-js"),
1096            Some(Match::ShortName)
1097        );
1098    }
1099
1100    /// A trigger reaches every check on it and none on the other.
1101    #[test]
1102    fn a_trigger_reaches_its_own_stage_only() {
1103        let pre_commit = registry::CHECKS
1104            .iter()
1105            .filter(|c| names_check(c.name, "pre-commit").is_some())
1106            .count();
1107        let pre_push = registry::CHECKS
1108            .iter()
1109            .filter(|c| names_check(c.name, "pre-push").is_some())
1110            .count();
1111        assert_eq!(pre_commit + pre_push, registry::CHECKS.len());
1112        assert!(pre_commit > 0 && pre_push > 0);
1113    }
1114
1115    /// Specificity ordering, which decides severity when several keys apply.
1116    #[test]
1117    fn a_full_id_outranks_a_short_name_outranks_a_trigger() {
1118        assert!(Match::FullId > Match::ShortName);
1119        assert!(Match::ShortName > Match::Trigger);
1120    }
1121
1122    /// The resolver reads the trigger out of the ID. That is only sound while
1123    /// every ID agrees with the stage its check actually declares — so it is
1124    /// checked rather than assumed.
1125    #[test]
1126    fn every_id_agrees_with_its_declared_stage() {
1127        for check in registry::CHECKS {
1128            assert_eq!(
1129                names_check(check.name, check.stage.as_str()),
1130                Some(Match::Trigger),
1131                "{} declares {:?} but its id says otherwise",
1132                check.name,
1133                check.stage
1134            );
1135        }
1136    }
1137}
1138
1139#[cfg(test)]
1140mod listing {
1141    use super::*;
1142
1143    /// The summary names ecosystems so the inert count reads as "other
1144    /// people's stacks" rather than "twenty-two things are broken".
1145    #[test]
1146    fn scope_tokens_map_to_the_ecosystem_a_reader_would_name() {
1147        assert_eq!(ecosystem(".rs"), Some("Rust"));
1148        assert_eq!(ecosystem("Cargo.lock"), Some("Rust"));
1149        assert_eq!(ecosystem("go.sum"), Some("Go"));
1150        assert_eq!(ecosystem("pyproject.toml"), Some("Python"));
1151        assert_eq!(ecosystem(".tsx"), Some("JavaScript"));
1152        assert_eq!(ecosystem(".prettierrc.json"), Some("JavaScript"));
1153        assert_eq!(ecosystem("kustomization.yaml"), Some("Kubernetes"));
1154        assert_eq!(ecosystem(".kube-linter.yaml"), Some("Kubernetes"));
1155    }
1156
1157    /// The generic tokens are unmapped ON PURPOSE. Four checks want `.yaml`
1158    /// for four unrelated reasons, so naming YAML would tell a reader their
1159    /// repository is missing "YAML checks" when what it is missing is
1160    /// Kubernetes. An unmapped token is still COUNTED — it just goes unnamed,
1161    /// which is the honest failure mode for a presentational map.
1162    #[test]
1163    fn generic_tokens_are_deliberately_unnamed() {
1164        for t in [".yaml", ".yml", ".json", ".md", ".sh", "unknown-thing"] {
1165            assert_eq!(ecosystem(t), None, "{t} should not name an ecosystem");
1166        }
1167    }
1168}