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