amont-fleet 1.2.0

The amont fleet dashboard: see and repair hook coverage across many repositories
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! Walking a directory tree for git repositories, and counting everything.
//!
//! The counters are the point. `scripts/propagate.sh` printed scalars with no
//! denominator, and twice reported something that could not be true: 192
//! removals per hook across 96 repos holding one copy each, and
//! `0 copies / 0 distinct` from a `-maxdepth` that matched nothing. The second
//! is the dangerous one — a broken scan and a clean fleet produced identical
//! output.
//!
//! So this records how it arrived at its answer: directories visited, entries
//! it could not read, subtrees it deliberately skipped. A caller can then tell
//! "found nothing because there is nothing" from "found nothing because I
//! looked in the wrong place", which no scalar can express.

use std::path::{Path, PathBuf};
use std::process::Command;

use serde::Serialize;

use crate::severities::{self, SeverityOverride};
use crate::shim::{self, BakeState, ShimState, DISPATCHERS};
use crate::skips::{self, SkipEntry};

/// One `amont.conf` line, for display and for `--json`.
///
/// A SUM, like the `Line` it projects. Flattening it into `severity` +
/// `command` + `Option<broken>` would rebuild here exactly the shape the
/// runtime just stopped using: fields that mean nothing when the line is
/// unusable, and a renderer that has to remember which.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DeclaredCheck {
    pub name: String,
    pub stage: String,
    #[serde(flatten)]
    pub state: DeclaredState,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum DeclaredState {
    Usable {
        severity: String,
        /// Extensions that gate it. Empty means every change.
        exts: Vec<String>,
        command: String,
    },
    /// The check does not run, and saying so is the whole reason the dashboard
    /// reads these files.
    Unusable { why: String },
}

impl DeclaredCheck {
    pub fn is_unusable(&self) -> bool {
        matches!(self.state, DeclaredState::Unusable { .. })
    }
}

/// A projection rather than a re-parse: `manifest::read_lines` is the same
/// parser the dispatcher uses, so the dashboard cannot form its own opinion
/// about what a manifest means.
fn declared_checks(repo: &Path) -> Vec<DeclaredCheck> {
    amont_runtime::manifest::read_lines(repo)
        .into_iter()
        .map(|line| {
            let (name, stage, parsed) = line.into_parts();
            DeclaredCheck {
                name,
                stage: stage.as_str().to_string(),
                state: match parsed {
                    Ok(declared) => DeclaredState::Usable {
                        severity: declared.severity.as_str().to_string(),
                        command: declared.command(),
                        exts: declared.exts,
                    },
                    Err(why) => DeclaredState::Unusable { why },
                },
            }
        })
        .collect()
}

/// Subtrees never worth descending. Matches the exclusions the shell sweep
/// used, so the two agree about what "the fleet" means.
pub const EXCLUDED: [&str; 6] = ["node_modules", "target", "dist", "build", ".venv", "vendor"];

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct Repo {
    /// Path relative to the scan root, which is what a human recognises.
    pub path: PathBuf,
    /// At least one file in `.git/hooks` dispatches to the binary.
    pub managed: bool,
    /// One entry per git-invoked hook, in `DISPATCHERS` order.
    pub shims: Vec<ShimState>,
    pub baked: BakeState,
    /// Our files that we no longer ship — the 16 per-check shims retired when
    /// checks moved in-process, and anything else removed upstream.
    pub stale_ours: Vec<String>,
    /// Hand-written `pre-commit-*` / `pre-push-*` sub-hooks. Nothing dispatches
    /// these any more, so they LOOK installed and never run.
    pub foreign_subs: Vec<String>,
    /// The node-era `package.json` that forced CommonJS. No hook is node now.
    pub hook_pkgjson: bool,
    /// Manifests present at the repo root. Display only — the LANG column.
    pub languages: Vec<String>,
    /// Checks that would ever fire here, from each check's own `Scope`
    /// evaluated against this repo's tracked files. Not inferred by this crate:
    /// a fourth copy of that rule was what `LANGUAGES` used to be.
    pub applicable: Vec<String>,
    /// `hook.skip` entries, resolved: what each one suppresses and where it
    /// came from. Bare strings hid both — a value need not be a check id (a
    /// trigger silences fifteen), and local/global are indistinguishable once
    /// merged.
    pub skips: Vec<SkipEntry>,
    /// `amont.severity.*` entries. A downgraded check still runs and still
    /// prints its failure, so unlike a skip it leaves no trace on screen — a
    /// repo that enforces nothing reads exactly like one that enforces
    /// everything unless this column says otherwise.
    pub severities: Vec<SeverityOverride>,
    /// Checks this repo declares in `amont.conf`. Invisible to the fleet
    /// view until now: a repo could be running a command on every commit that
    /// no dashboard column mentioned, and a manifest line nobody can parse is a
    /// check that silently is not running.
    pub declared: Vec<DeclaredCheck>,
    /// Whether this repo's `amont.conf` is trusted here. `None` when there
    /// is no manifest — which is almost every repo, and must read differently
    /// from "declared something and it is not running".
    pub trusted: Option<bool>,
    /// Whether `AGENTS.md` carries an up-to-date pointer at this check's own
    /// generated block, and if not, why.
    pub agents_md: AgentsMdState,
    /// Where this repo's hooks resolve to, and whether that is inside it.
    pub hooks_dir: HooksDir,
    /// Set when another repository already seen in this scan shares this one's
    /// hooks directory, naming that repository.
    ///
    /// Recognising `.git` FILES created this problem the same day it fixed the
    /// bigger one: a submodule and a linked worktree keep their hooks in the
    /// superproject/main repo, so one hooks directory became reachable from two
    /// entries in `repos`. Without this, `fix --apply` would write the same four
    /// files twice and count them twice, and the dashboard would report a repo
    /// as needing an install it had already received through its sibling.
    ///
    /// The first repository encountered in the walk's (stable, sorted) order
    /// owns the directory; every later one points at it.
    pub shares_hooks_with: Option<PathBuf>,
}

/// A local wrapper around `amont_runtime::agents_md::CheckResult`: that
/// type lives in the dependency-free crate and cannot derive `Serialize`
/// itself, the same reason `severities::Level` wraps
/// `amont_runtime::check::Severity` rather than re-exporting it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AgentsMdState {
    UpToDate,
    Missing,
    Drifted,
    /// An unpaired marker — not something this crate, any more than the
    /// dependency-free one, tries to guess its way out of.
    Malformed,
}

fn agents_md_state(repo: &Path) -> AgentsMdState {
    use amont_runtime::agents_md::CheckResult;
    match amont_runtime::agents_md::check(&repo.join("AGENTS.md")) {
        Ok(CheckResult::MatchesGenerated) => AgentsMdState::UpToDate,
        Ok(CheckResult::NotPresent) => AgentsMdState::Missing,
        Ok(CheckResult::Drifted) => AgentsMdState::Drifted,
        Err(_) => AgentsMdState::Malformed,
    }
}

/// A whole scan, including how it was performed.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct FleetScan {
    pub root: PathBuf,
    pub depth: usize,
    pub git_dirs_found: usize,
    pub hook_dirs_seen: usize,
    pub managed_seen: usize,
    pub unmanaged_seen: usize,
    /// Paths that exist but could not be read. Never silently dropped: an
    /// unreadable repo is not an absent one.
    pub unreadable: Vec<PathBuf>,
    /// Repositories whose hooks resolve somewhere this tool will not touch —
    /// outside the repository, or nowhere git would name. Counted rather than
    /// merely listed per-repo, because the number that matters to a reader is
    /// "how much of this fleet did I decline to act on".
    pub hooks_outside_seen: usize,
    pub excluded_dirs: usize,
    pub dirs_visited: usize,
    pub repos: Vec<Repo>,
}

impl FleetScan {
    /// True when the scan looked at essentially nothing. The caller is expected
    /// to render this as a FAILURE rather than as an empty success — the single
    /// rule this whole tool exists to enforce.
    pub fn looks_like_a_failed_scan(&self) -> bool {
        self.git_dirs_found == 0
    }
}

/// A file is ours only if it carries our shim marker AND is an ordinary file we
/// could actually read.
///
/// Asked once, via [`amont_runtime::hookfile::classify`], rather than
/// re-tested here. This answer feeds `stale_ours`, which `fix::plan` turns
/// straight into a REMOVAL list, and `is_managed`, which decides whether the
/// tool will act on a repository at all — so both halves of a wrong answer are
/// expensive:
///
/// - The body was once `s.contains("--hooks-dir")`, matched by a hand-written
///   hook that merely mentions the flag in a comment or forwards it to another
///   tool. That claimed somebody else's file as ours to delete.
/// - Then it was `read_to_string(..).map(is_our_shim).unwrap_or(false)`, which
///   FOLLOWS SYMLINKS: a dispatcher that is a link to a shim in the working tree
///   read as ours, so the repo counted as managed and `fix --apply` wrote
///   through the link. `hookfile::classify` reports the link as a link.
fn is_ours(path: &Path) -> bool {
    matches!(
        amont_runtime::hookfile::classify(path),
        amont_runtime::hookfile::HookFile::Ours
    )
}

/// Where a scanned repository's hooks live — and whether that is somewhere this
/// tool is willing to touch.
///
/// The `Outside` variant is the whole reason this is a sum type rather than a
/// `PathBuf`. `core.hooksPath` may be an ABSOLUTE path anywhere on the disk, and
/// `Intent::Activate` used to `create_dir_all` whatever came back and write four
/// 0o755 files into it. Nothing canonicalised, nothing compared it against the
/// repository — so a repo could name `/etc/amont`, or another checkout's
/// working tree, and a fleet-wide `install` would create it and populate it.
///
/// **The asymmetry with per-repo `amont install` is deliberate.** That
/// command keeps honouring its own repository's `core.hooksPath`, absolute or
/// not: you are standing in that repository and you configured it yourself, so
/// the redirect is your instruction. The fleet refuses, because it is walking
/// ninety-six repositories it did not configure and a redirect there is a fact
/// about somebody else's checkout, not an instruction to this tool.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "where", rename_all = "snake_case")]
pub enum HooksDir {
    /// Inside the repository's own working tree, or inside its git common
    /// directory. Both count: a submodule's and a linked worktree's hooks live
    /// in the superproject/main repo's common dir and are perfectly legitimate,
    /// and a repo redirecting `core.hooksPath` to `tooling/hooks` within itself
    /// is redirecting within itself.
    In { path: PathBuf },
    /// Resolved to a directory that is neither. Reported, never created, never
    /// written to, never deleted from.
    Outside { path: PathBuf },
    /// git would not say. Not a guess-worthy state: the old code fell back to
    /// `repo.join(".git/hooks")`, which for a repository whose `.git` is a FILE
    /// (a submodule, a linked worktree) is not a fallback but a wrong answer.
    Unknown { why: String },
}

impl HooksDir {
    /// The directory, when it is one we may act on. `None` is the refusal.
    pub fn inside(&self) -> Option<&Path> {
        match self {
            HooksDir::In { path } => Some(path),
            _ => None,
        }
    }

    /// A fragment for the middle of a sentence: "the hooks directory is {}".
    pub fn describe(&self) -> String {
        match self {
            HooksDir::In { path } => path.display().to_string(),
            HooksDir::Outside { path } => {
                format!("{} — OUTSIDE the repository", path.display())
            }
            HooksDir::Unknown { why } => format!("unresolvable ({why})"),
        }
    }
}

/// Where `repo`'s hooks actually live, resolved by git and then contained.
///
/// `git rev-parse` is the authority for the resolution: relative
/// `core.hooksPath`, `~` expansion, `.git`-file indirection and worktree
/// indirection are git's rules to get right, not ours to reimplement. This used
/// to skip the call unless `.git/config`'s own bytes mentioned `hooksPath`, on
/// the theory that a config file which does not mention it cannot have set it —
/// true of THAT FILE, but the value can just as well come from global or system
/// config, or from a file `.git/config` merely `include`s. One `git` call per
/// repo, always.
///
/// Three paths come back from one invocation, and all three are needed:
///
/// | asked | used for |
/// |---|---|
/// | `--git-path hooks` | where the hooks are |
/// | `--git-common-dir` | a submodule's / linked worktree's hooks live here |
/// | `--show-toplevel`  | an in-repo `core.hooksPath` redirect lives here |
///
/// Containment is tested against EITHER of the last two, and compares
/// git-reported paths only — never a git-reported path against one this process
/// built — because git resolves symlinks in what it prints (`/tmp` comes back as
/// `/private/tmp` on macOS) and a lexical comparison across that boundary would
/// report every repository under a symlinked root as `Outside`.
///
/// Having compared in git's spelling, the answer is returned in the CALLER's
/// wherever it can be: hooks under the toplevel come back re-anchored onto
/// `repo`. Everything downstream — the removal list, the write list, the
/// root-relative paths the report and the parity gate compare — is built from
/// this, and handing back `/private/var/…` for a `--root` of `/var/…` would make
/// every one of those paths fail to relativise against the root the user typed.
/// A submodule's or linked worktree's hooks live outside the toplevel by
/// definition and keep git's absolute answer, which is the only true one there.
///
/// ## The one fallback, and its guard
///
/// `fatal: not a git repository` with a `.git` that IS a directory falls back to
/// `<repo>/.git/hooks` as `In`. That is not the old guess wearing a hat: a
/// directory git does not recognise as a repository cannot have a
/// `core.hooksPath`, so there is nothing to resolve and exactly one place the
/// walk could have meant. It is also load-bearing for the test suites — the
/// fixtures throughout this crate build `<name>/.git/hooks` in a bare temp dir,
/// and refusing those would fail every one of them for a reason unrelated to
/// what it tests, the same accommodation `hookfile::tracked` makes and for the
/// same reason. The `.git`-is-a-DIRECTORY guard is what keeps it honest: when
/// `.git` is a FILE and git will not resolve the pointer inside it, we do not
/// know where the hooks are, and `Unknown` says so.
pub fn hooks_dir_for(repo: &Path) -> HooksDir {
    let out = match Command::new("git")
        .arg("-C")
        .arg(repo)
        .args([
            "rev-parse",
            "--path-format=absolute",
            "--git-path",
            "hooks",
            "--git-common-dir",
            "--show-toplevel",
        ])
        .output()
    {
        Ok(o) => o,
        Err(e) => {
            return HooksDir::Unknown {
                why: format!("could not run git: {e}"),
            }
        }
    };
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        if stderr.to_lowercase().contains("not a git repository") && repo.join(".git").is_dir() {
            return HooksDir::In {
                path: repo.join(".git").join("hooks"),
            };
        }
        return HooksDir::Unknown {
            why: first_line(&stderr),
        };
    }
    let stdout = String::from_utf8_lossy(&out.stdout);
    let mut lines = stdout.lines();
    let (Some(hooks), Some(common), Some(top)) = (lines.next(), lines.next(), lines.next()) else {
        return HooksDir::Unknown {
            why: "git rev-parse answered with fewer paths than it was asked for".to_string(),
        };
    };
    let hooks = PathBuf::from(hooks);
    if let Ok(rel) = amont_runtime::hookfile::resolve_lexical(&hooks)
        .strip_prefix(amont_runtime::hookfile::resolve_lexical(Path::new(top)))
    {
        return HooksDir::In {
            path: repo.join(rel),
        };
    }
    if amont_runtime::hookfile::is_within(&hooks, Path::new(common)) {
        HooksDir::In { path: hooks }
    } else {
        HooksDir::Outside { path: hooks }
    }
}

/// The git common directory, which is what two "repositories" sharing one hooks
/// directory have in common — a linked worktree and its main repo report the
/// same one. `None` when git would not say, in which case no sharing can be
/// established and none is claimed.
fn common_dir_for(repo: &Path) -> Option<PathBuf> {
    amont_runtime::git::stdout_in(
        repo,
        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
    )
    .map(PathBuf::from)
}

fn first_line(s: &str) -> String {
    s.lines()
        .find(|l| !l.trim().is_empty())
        .unwrap_or("no output")
        .trim()
        .to_string()
}

pub fn is_managed(hooks: &Path) -> bool {
    let Ok(entries) = std::fs::read_dir(hooks) else {
        return false;
    };
    entries.flatten().any(|e| is_ours(&e.path()))
}

/// Progress emitted while walking, so a caller can paint rows as they are
/// found rather than after 7 seconds of nothing. Visibility of system status is
/// the first usability heuristic, and this scan is well past the ~400ms at
/// which an interface stops feeling immediate.
pub enum Progress<'a> {
    Visited(usize),
    Found(&'a Repo),
}

pub fn scan(root: &Path, depth: usize, installed_binary: &str) -> FleetScan {
    scan_with(root, depth, installed_binary, &mut |_| {})
}

pub fn scan_with(
    root: &Path,
    depth: usize,
    installed_binary: &str,
    on: &mut dyn FnMut(Progress),
) -> FleetScan {
    let mut w = Walk {
        root: root.to_path_buf(),
        installed_binary: installed_binary.to_string(),
        seen_common: std::collections::HashMap::new(),
        scan: FleetScan {
            root: root.to_path_buf(),
            depth,
            git_dirs_found: 0,
            hook_dirs_seen: 0,
            managed_seen: 0,
            unmanaged_seen: 0,
            unreadable: Vec::new(),
            hooks_outside_seen: 0,
            excluded_dirs: 0,
            dirs_visited: 0,
            repos: Vec::new(),
        },
    };
    walk(&mut w, root, depth, on);
    w.scan.repos.sort_by(|a, b| a.path.cmp(&b.path));
    w.scan
}

/// State the walk carries that is not part of the reported scan.
///
/// `seen_common` is the one that earns the struct: answering "have I already
/// scanned something that shares this hooks directory?" needs a memory that
/// outlives one directory's recursion, and threading a seventh `&mut` argument
/// through `walk` was how the previous shape started to go wrong.
struct Walk {
    root: PathBuf,
    installed_binary: String,
    seen_common: std::collections::HashMap<PathBuf, PathBuf>,
    scan: FleetScan,
}

/// Walks `dir`, following symlinks — DELIBERATELY, not merely because
/// `Path::is_dir` happens to. `~/.config/git/git-templates` is commonly a
/// symlink to a checkout (see `install::TemplateDir`), and a linked worktree
/// reaches its repository the same way; either can sit inside `--root`, and a
/// scan that refused to follow them would silently under-report the fleet —
/// exactly the "0 copies / 0 distinct" failure this module's own doc warns
/// about.
///
/// The `depth` budget bounds the cost, but a symlink can still walk the scan
/// to a directory outside `--root` that a filesystem path comparison would
/// not expect. That is not this function's problem to solve: `fix`/`apply`
/// never trust a path scan reported — every removal and write is re-verified
/// through `hookfile`'s guards at the moment of action — so a symlink reaching
/// tracked source changes what gets REPORTED here, never what a later `--apply`
/// is willing to touch.
///
/// ## `.git` is not always a directory
///
/// The entry test used to be `path.is_dir()` before the name was even looked
/// at, so a repository whose `.git` is a FILE holding `gitdir: …` — every
/// SUBMODULE, and every linked WORKTREE — was invisible. Not scanned, not
/// installed into, and not counted as uncovered: the dashboard reported a clean
/// fleet while commits inside a submodule ran no checks at all. That is the
/// exact failure mode this crate's module doc opens with, one file type along.
///
/// The pointer inside a `.git` file is never parsed here. `git rev-parse`
/// resolves it (see [`hooks_dir_for`]), because the format has grown relative
/// gitdirs, worktree indirection and `commondir` files, and a hand-rolled
/// reader of it would be a fourth place that can disagree with git.
///
/// Entries are SORTED before they are acted on. Ordering used to be whatever
/// `read_dir` returned, which was fine while every repo was independent; it
/// stopped being fine when a linked worktree and its main repo can both claim
/// the same hooks directory and exactly one of them must be recorded as the
/// owner. An unstable order there means an unstable `shares_hooks_with`.
fn walk(w: &mut Walk, dir: &Path, budget: usize, on: &mut dyn FnMut(Progress)) {
    w.scan.dirs_visited += 1;
    on(Progress::Visited(w.scan.dirs_visited));
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => {
            w.scan.unreadable.push(dir.to_path_buf());
            return;
        }
    };

    let mut repos = Vec::new();
    let mut subdirs = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().into_owned();

        // Name first, TYPE SECOND: a `.git` file is a repository just as much as
        // a `.git` directory is.
        if name == ".git" {
            repos.push(path.parent().unwrap_or(&path).to_path_buf());
            continue;
        }
        if !path.is_dir() {
            continue;
        }
        if EXCLUDED.contains(&name.as_str()) {
            w.scan.excluded_dirs += 1;
            continue;
        }
        subdirs.push(path);
    }
    repos.sort();
    subdirs.sort();

    for repo in repos {
        let found = found_repo(w, &repo);
        on(Progress::Found(&found));
        w.scan.repos.push(found);
    }

    if budget == 0 {
        return;
    }
    for subdir in subdirs {
        walk(w, &subdir, budget - 1, on);
    }
}

/// One repository, counted and inspected. Split out of [`walk`] only because
/// the counting is now five decisions rather than two, and burying them inside
/// a loop over directory entries is how `hook_dirs_seen` came to be incremented
/// for a directory nobody had established was a hooks directory.
fn found_repo(w: &mut Walk, repo: &Path) -> Repo {
    w.scan.git_dirs_found += 1;
    let hooks_dir = hooks_dir_for(repo);

    // Sharing is established from the git COMMON directory, not from the hooks
    // path: two repos can legitimately be told to use one `core.hooksPath`
    // without being the same repository, and it is the repository identity that
    // decides whether writing twice is writing the same file twice.
    let shares_hooks_with = common_dir_for(repo).and_then(|common| {
        use std::collections::hash_map::Entry;
        let rel = repo.strip_prefix(&w.root).unwrap_or(repo).to_path_buf();
        match w.seen_common.entry(common) {
            // The FIRST repository to claim a common directory keeps it, so a
            // third sharer points at the same owner as the second rather than
            // at the second itself.
            Entry::Occupied(e) => Some(e.get().clone()),
            Entry::Vacant(e) => {
                e.insert(rel);
                None
            }
        }
    });

    match &hooks_dir {
        HooksDir::In { path } => {
            if path.is_dir() {
                w.scan.hook_dirs_seen += 1;
            }
        }
        _ => w.scan.hooks_outside_seen += 1,
    }

    // A repository we will not look inside is never "managed": claiming so would
    // put it in the population `fix` acts on, which is the one thing an
    // unresolvable or out-of-repo hooks directory must not do.
    let managed = hooks_dir.inside().is_some_and(is_managed);
    if managed {
        w.scan.managed_seen += 1;
    } else {
        w.scan.unmanaged_seen += 1;
    }
    inspect(
        &w.root,
        repo,
        hooks_dir,
        managed,
        shares_hooks_with,
        &w.installed_binary,
    )
}

/// Everything we can learn about one repository from its hooks directory.
///
/// When `hooks_dir` is not [`HooksDir::In`] this reads NOTHING from it — not
/// even to report what is there. That is a deliberate refusal to look rather
/// than an inability: a repository can point `core.hooksPath` at any directory
/// on the disk, and enumerating it would put somebody else's filenames into this
/// tool's output (and into `stale_ours`, which is a removal list). The four
/// dispatchers come back as `Unreadable`, naming why, which is honest and — the
/// part that matters — is not `Missing`, the state that makes `fix` write.
fn inspect(
    root: &Path,
    repo: &Path,
    hooks_dir: HooksDir,
    managed: bool,
    shares_hooks_with: Option<PathBuf>,
    installed_binary: &str,
) -> Repo {
    let (mut stale_ours, mut foreign_subs) = (Vec::new(), Vec::new());
    let mut hook_pkgjson = false;
    let shims: Vec<ShimState> = match hooks_dir.inside() {
        None => vec![
            ShimState::Unreadable {
                why: format!("hooks directory {}", hooks_dir.describe()),
            };
            DISPATCHERS.len()
        ],
        Some(hooks) => {
            if let Ok(entries) = std::fs::read_dir(hooks) {
                for entry in entries.flatten() {
                    let p = entry.path();
                    let name = entry.file_name().to_string_lossy().into_owned();
                    if name.ends_with(".sample") || DISPATCHERS.contains(&name.as_str()) {
                        continue;
                    }
                    if name == "package.json" {
                        hook_pkgjson = std::fs::read_to_string(&p)
                            .map(|c| c.contains("Forces Node"))
                            .unwrap_or(false);
                        continue;
                    }
                    if is_ours(&p) {
                        stale_ours.push(name);
                    } else if name.starts_with("pre-commit-") || name.starts_with("pre-push-") {
                        foreign_subs.push(name);
                    }
                }
            }
            DISPATCHERS
                .iter()
                .map(|n| shim::classify(&hooks.join(n)))
                .collect()
        }
    };
    stale_ours.sort();
    foreign_subs.sort();

    Repo {
        path: repo.strip_prefix(root).unwrap_or(repo).to_path_buf(),
        managed,
        baked: shim::bake_state(&shims, installed_binary),
        shims,
        stale_ours,
        foreign_subs,
        hook_pkgjson,
        languages: languages(repo),
        applicable: applicable_checks(repo),
        skips: skips::read(repo),
        severities: severities::read(repo),
        declared: declared_checks(repo),
        trusted: match amont_runtime::trust::state(repo) {
            amont_runtime::trust::State::NoManifest => None,
            amont_runtime::trust::State::Trusted => Some(true),
            _ => Some(false),
        },
        agents_md: agents_md_state(repo),
        hooks_dir,
        shares_hooks_with,
    }
}

/// Root-level manifests only. Deliberately an approximation: the hooks
/// themselves resolve the NEAREST manifest, so a repo can hold Rust in a
/// subdirectory and show no `rust` here. It drives a display column, never a
/// verdict.
fn languages(repo: &Path) -> Vec<String> {
    let mut out = Vec::new();
    let has = |f: &str| repo.join(f).is_file();
    if has("Cargo.toml") {
        out.push("rust".into());
    }
    if has("package.json") {
        out.push("js".into());
    }
    if has("pyproject.toml") || has("requirements.txt") || has("setup.py") {
        out.push("python".into());
    }
    if has("kustomization.yaml") || has("kustomization.yml") || repo.join("k8s").is_dir() {
        out.push("k8s".into());
    }
    out
}

/// Which checks could ever fire in this repository.
///
/// One `git ls-files` per repo, evaluated against each check's declared
/// `Scope`. Coarser than what a check enforces at commit time — `cargo-fmt`
/// resolves the NEAREST ancestor `Cargo.toml` while this asks whether the repo
/// contains one at all — and deliberately so: the dispatcher answers "does this
/// apply to these staged files", and this answers "would it ever fire here".
/// Over-approximating is the safe direction; the alternative was a table in
/// this crate guessing at rules the checks already own.
fn applicable_checks(repo: &Path) -> Vec<String> {
    let Ok(out) = Command::new("git")
        .args(["ls-files"])
        .current_dir(repo)
        .output()
    else {
        return Vec::new();
    };
    let paths: Vec<String> = String::from_utf8_lossy(&out.stdout)
        .lines()
        .map(str::to_owned)
        .collect();
    applicable_from_paths(&paths)
}

/// The pure half: which checks could ever fire in a repository containing these
/// paths.
///
/// Split out because the rollup's fixtures used to recompute this filter
/// themselves. A test that builds its own answer cannot fail when the answer is
/// wrong — the fixtures call this now.
pub fn applicable_from_paths(paths: &[String]) -> Vec<String> {
    amont_runtime::registry::CHECKS
        .iter()
        .filter(|c| c.scope.matches(paths))
        .map(|c| c.name.to_string())
        .collect()
}