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