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