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