Skip to main content

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