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