Skip to main content

greengate_runtime/
install.rs

1//! `amont install` — put the binary somewhere stable and wire up the shims.
2//!
3//! Everything this module prints is a report for a person (what was
4//! installed, wired, trusted or left alone), so all of it goes to stderr, in
5//! one stream and in order; stdout stays free for data.
6//!
7//! This was a Makefile recipe. It moved here for one reason: the guard below
8//! decides whether a directory is safe to delete, it has been got wrong TWICE —
9//! both times overwriting tracked source files with machine-specific paths — and
10//! shell that runs on one platform cannot be tested on three.
11//!
12//! Everything here is `std`. The commit path's dependency posture
13//! (`scripts/check-no-deps.sh`) is unchanged: this adds code, not crates.
14//!
15//! ## Why it is a subcommand and not a script
16//!
17//! A `.ps1` for Windows plus a Makefile for Unix would be two implementations of
18//! that guard, in two languages, one of them untested — for a routine whose
19//! failure mode is deleting your work. And `make` is not the Unix-only detail it
20//! looks like: Git for Windows ships `bash`, `sh` and coreutils but NOT `make`,
21//! so the dependency was the problem rather than the shell.
22//!
23//! The shim text is embedded with `include_str!`, so an installed binary carries
24//! its own shims and can install from any directory.
25
26use std::path::{Path, PathBuf};
27use std::process::Command;
28
29use crate::hookfile::{self, HookFile, Refuse, Staged, SwapFailure};
30use crate::names::{BIN, FLEET_BIN, OLD_BIN, OLD_FLEET_BIN};
31use crate::ui::{error_sign, highlight, valid_sign, warning_sign};
32
33/// The token every shim carries until it is baked.
34pub const PLACEHOLDER: &str = "__AMONT_BIN__";
35
36/// The one shim. All four git-invoked hooks are the same file — it passes its
37/// own filename through — and `shims_on_disk_match_the_embedded_one` keeps the
38/// repository's `templates/hooks/` honest against this copy.
39///
40/// The canonical text lives INSIDE this crate, and that is a packaging
41/// constraint rather than a preference. It used to be
42/// `include_str!("../../../templates/hooks/pre-commit")`, reaching up to the
43/// repository root — which works in a checkout and cannot work in a published
44/// crate, because `cargo package` tars up this directory and nothing above it.
45/// The tarball compiled nowhere: `couldn't read src/../../../templates/hooks/
46/// pre-commit`. crates.io is immutable, so that would have been a broken
47/// release that could only be yanked, never fixed in place.
48///
49/// The repository's `templates/hooks/` still holds the four installable copies
50/// — that directory IS the product for anyone pointing `init.templateDir` at a
51/// clone, and it has to be real files rather than symlinks because Git for
52/// Windows materialises those as text files containing a path.
53pub const SHIM: &str = include_str!("../templates/hooks/pre-commit");
54
55/// The ownership question, and every other "may we touch this file?" answer,
56/// now live in [`crate::hookfile`] — one implementation that fails closed,
57/// rather than the three `unwrap_or(false)` one-liners that used to answer it
58/// here, in `fleet::scan` and in `fleet::fix`.
59///
60/// Re-exported rather than moved outright because both fleet call sites and the
61/// dashboard's `shim` module name them through this path, and a rename would be
62/// churn in files this change has no business editing.
63pub use crate::hookfile::{is_our_shim, SHIM_MARKER};
64
65/// The hook names git actually invokes, and so the only files we install.
66pub const DISPATCHERS: [&str; 6] = [
67    "commit-msg",
68    "post-commit",
69    "post-rewrite",
70    "pre-commit",
71    "pre-push",
72    "prepare-commit-msg",
73];
74
75/// What may be done with a candidate template directory.
76///
77/// `~/.config/git/git-templates` is commonly a SYMLINK to a checkout of this
78/// repository, in which case "installing" there means deleting and overwriting
79/// TRACKED files.
80///
81/// Comparing the path against the source tree is NOT enough, and that is the
82/// mistake that caused both incidents: run the install from a git worktree and
83/// the two resolve to different paths — a different checkout of the same repo —
84/// so a path comparison says "not the source" and clobbers the main checkout.
85/// Asking git is the reliable test whatever route the symlink took.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum TemplateDir {
88    /// The path does not exist and could not be created.
89    Unresolvable,
90    /// No git to ask. Refuse rather than guess.
91    NoGit,
92    /// It holds tracked files: it IS a checkout. Nothing to install — `git init`
93    /// already reads its templates from there, and the shims keep their
94    /// placeholder and resolve the binary at run time.
95    IsCheckout,
96    /// Inside a checkout but tracking nothing here. Still not ours to empty.
97    InsideCheckout,
98    /// An ordinary directory. Safe to populate.
99    Safe,
100}
101
102fn git_ok(dir: &Path, args: &[&str]) -> bool {
103    Command::new("git")
104        .arg("-C")
105        .arg(dir)
106        .args(args)
107        .stdout(std::process::Stdio::null())
108        .stderr(std::process::Stdio::null())
109        .status()
110        .map(|s| s.success())
111        .unwrap_or(false)
112}
113
114/// Decide what may be done with `dir`. Never mutates anything.
115pub fn classify_dir(dir: &Path) -> TemplateDir {
116    let Ok(real) = dir.canonicalize() else {
117        return TemplateDir::Unresolvable;
118    };
119    if Command::new("git").arg("--version").output().is_err() {
120        return TemplateDir::NoGit;
121    }
122    // `ls-files --error-unmatch .` is the question that matters: does git track
123    // anything HERE? A directory can be inside a checkout and still be
124    // untracked scratch space, which the next test separates.
125    if git_ok(&real, &["ls-files", "--error-unmatch", "."]) {
126        return TemplateDir::IsCheckout;
127    }
128    if git_ok(&real, &["rev-parse", "--git-dir"]) {
129        return TemplateDir::InsideCheckout;
130    }
131    TemplateDir::Safe
132}
133
134/// Write the absolute binary path into a shim.
135///
136/// A plain global replace, which is why the shim's own comment must not spell
137/// the token out — it did, and every baked shim carried an "explanation" whose
138/// text was a machine path. Idempotent: re-baking a baked shim is a no-op
139/// because the token is gone.
140pub fn bake(shim: &str, bin: &str) -> String {
141    shim.replace(PLACEHOLDER, bin)
142}
143
144/// Whether the shim will accept `bin` as its baked path.
145///
146/// The shim rejects anything relative before it ever touches the filesystem,
147/// and this is the same rule stated where the value is produced. Git runs a
148/// hook with the working tree as the current directory, so a relative baked
149/// path is a question asked of the REPOSITORY — and a clone that ships a file
150/// by that name gets to answer it. Baking one would install a hook that either
151/// cannot resolve its binary or resolves it to somebody else's, so refuse here
152/// too, where the message can say which path was wrong.
153///
154/// Absolute means POSIX `/…` or a Windows drive path (`C:\…`, `C:/…`).
155pub fn is_bakeable(bin: &str) -> bool {
156    if bin.is_empty() || bin == PLACEHOLDER {
157        return false;
158    }
159    let b = bin.as_bytes();
160    if b[0] == b'/' {
161        return true;
162    }
163    b.len() > 2 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'/' || b[2] == b'\\')
164}
165
166/// An absolute form of `p`, for baking.
167///
168/// NOT `canonicalize`: that returns an extended-length path (`\\?\C:\…`) on
169/// Windows, which `sh` cannot test, and it fails outright on a path that does
170/// not exist yet. `$AMONT_BIN_DIR` may be relative, which is the route by
171/// which a relative path could reach a shim at all.
172fn absolute(p: &Path) -> PathBuf {
173    if p.is_absolute() {
174        return p.to_path_buf();
175    }
176    match std::env::current_dir() {
177        Ok(cwd) => cwd.join(p),
178        Err(_) => p.to_path_buf(),
179    }
180}
181
182/// The one directory an UNBAKED shim looks in, hardcoded in the shim itself.
183///
184/// Deliberately NOT `bin_dir()`, and the difference is the whole point of
185/// `warn_if_unbaked_cannot_resolve`. `bin_dir()` answers "where should install
186/// PUT the binary?" and honours `$AMONT_BIN_DIR`. This answers "where will a
187/// shim that never got a path baked into it LOOK?", which is a constant in a
188/// POSIX sh file and cannot be configured at all.
189///
190/// `$AMONT_BIN_DIR` is deliberately not wired into the shim to close that
191/// gap. It is an install-time question answered in the shell where `amont
192/// install` ran; the shim runs inside git's environment during a commit, where
193/// that variable is almost never set — so honouring it there would ship a knob
194/// that looks like it works and silently does not. The runtime override already
195/// exists and is `$GIT_HOOKS_BIN`; a second variable able to redirect which
196/// binary executes on every commit would double that surface for nothing.
197///
198/// Not "XDG", either: the XDG Base Directory spec defines no binary directory.
199/// `~/.local/bin` is simply the widely-observed convention.
200fn unbaked_lookup_dir() -> PathBuf {
201    home().join(".local").join("bin")
202}
203
204/// Say so when the binary went somewhere an unbaked shim will never look.
205///
206/// Two supported choices stop composing when made together. A template dir that
207/// IS the checkout keeps the placeholder on purpose — those shims resolve the
208/// binary at run time from [`unbaked_lookup_dir`]. Install to a custom
209/// `$AMONT_BIN_DIR` as well and nothing baked a path, while the one path the
210/// shim knows is not where the binary went.
211///
212/// Nothing is silently skipped — the shim prints what it looked at and exits 1,
213/// which fails the commit loudly. But it fails at somebody's next commit, in a
214/// repository they have not thought about since, and the cause is a decision
215/// made here. So it is said here.
216fn warn_if_unbaked_cannot_resolve(binary: &str) {
217    let looked = unbaked_lookup_dir();
218    let placed = Path::new(binary).parent();
219
220    // Compare RESOLVED paths, and require both to resolve. `a.ok() == b.ok()`
221    // would read `None == None` as "the same directory" — the shape of a bug
222    // this module has already had once, in `already_there`.
223    let reachable = placed.is_some_and(|p| {
224        matches!(
225            (p.canonicalize(), looked.canonicalize()),
226            (Ok(a), Ok(b)) if a == b
227        )
228    });
229    if reachable {
230        return;
231    }
232
233    eprintln!();
234    eprintln!(
235        "{} the binary is at {}, which an unbaked shim will not find.",
236        warning_sign(),
237        highlight(binary)
238    );
239    eprintln!(
240        "    Shims here keep the placeholder, and they look only in {}.",
241        looked.display()
242    );
243    eprintln!("    Either link it where they look:");
244    eprintln!("      ln -s {} {}", binary, looked.join(BIN).display());
245    eprintln!("    or set GIT_HOOKS_BIN in the environment git runs hooks with:");
246    eprintln!("      export GIT_HOOKS_BIN={binary}");
247}
248
249/// `~/.local/bin`, or `$AMONT_BIN_DIR`.
250pub fn bin_dir() -> PathBuf {
251    if let Some(d) = std::env::var_os("AMONT_BIN_DIR") {
252        return PathBuf::from(d);
253    }
254    home().join(".local").join("bin")
255}
256
257/// `$XDG_CONFIG_HOME/git/git-templates/templates/hooks`.
258pub fn template_hooks_dir() -> PathBuf {
259    let base = std::env::var_os("XDG_CONFIG_HOME")
260        .map(PathBuf::from)
261        .unwrap_or_else(|| home().join(".config"));
262    base.join("git")
263        .join("git-templates")
264        .join("templates")
265        .join("hooks")
266}
267
268fn home() -> PathBuf {
269    std::env::var_os("HOME")
270        .or_else(|| std::env::var_os("USERPROFILE"))
271        .map(PathBuf::from)
272        .unwrap_or_else(|| PathBuf::from("."))
273}
274
275/// The name to install under. Windows builds `greengate.exe`, and a shim
276/// testing `[ -x .../greengate ]` is false for it.
277fn installed_name() -> String {
278    match std::env::current_exe() {
279        Ok(p) => name_for(&p, BIN),
280        Err(_) => BIN.to_string(),
281    }
282}
283
284/// `name` with the running binary's platform suffix: `greengate`, or the old
285/// name `amont` an alias is written under, each `.exe` on Windows.
286///
287/// Split from `installed_name` so it can be tested on every platform rather
288/// than only the one that produces a `.exe`. A `cfg!(windows)` assertion is
289/// vacuous on the machine most of this is written on.
290fn name_for(exe: &Path, name: &str) -> String {
291    match exe.extension().and_then(|e| e.to_str()) {
292        Some(e) if !e.is_empty() => format!("{name}.{e}"),
293        _ => name.to_string(),
294    }
295}
296
297/// Write `from`'s bytes to `target` so that `target` is never missing or
298/// half-written: copied to a temporary name in the same directory, made
299/// executable, then `rename(2)`d over the target. A commit that runs a shim
300/// baked to `target` during the install finds the old binary or the new one,
301/// never neither. On Windows a running `.exe` cannot be replaced by rename,
302/// so the existing one is first renamed aside to `<name>.old.exe` (swept on
303/// the next install).
304fn replace_atomically(from: &Path, target: &Path) -> std::io::Result<()> {
305    let dir = target.parent().unwrap_or_else(|| Path::new("."));
306    let file = target
307        .file_name()
308        .map(|f| f.to_string_lossy().into_owned())
309        .unwrap_or_default();
310    let staged_copy = dir.join(format!(".{file}.tmp.{}", std::process::id()));
311    if let Err(e) = stage_copy(from, &staged_copy) {
312        let _ = std::fs::remove_file(&staged_copy); // the error being returned says what failed
313        return Err(e);
314    }
315    if cfg!(windows) && target.exists() {
316        let aside = target.with_extension("old.exe");
317        let _ = std::fs::remove_file(&aside); // a leftover from an earlier install
318        if let Err(e) = std::fs::rename(target, &aside) {
319            let _ = std::fs::remove_file(&staged_copy); // the error being returned says what failed
320            return Err(e);
321        }
322    }
323    let renamed = std::fs::rename(&staged_copy, target);
324    if renamed.is_err() {
325        let _ = std::fs::remove_file(&staged_copy); // the error being returned says what failed
326        if cfg!(windows) {
327            // Put the old binary back rather than leave no target at all.
328            let _ = std::fs::rename(target.with_extension("old.exe"), target); // best effort; the error below is the report
329        }
330    }
331    renamed
332}
333
334/// Write `from`'s bytes to `staged`, executable and flushed to disk.
335///
336/// Flushed before the caller's rename: after a power loss the target must be
337/// the old binary or the whole new one, never an empty file every shim points
338/// at. Copied by hand, not `fs::copy`: on macOS that clones the file and the
339/// clone keeps the running binary's old mtime, so a leftover sweep would take
340/// this live temporary for a stale one. A file this writes is new.
341fn stage_copy(from: &Path, staged: &Path) -> std::io::Result<()> {
342    let mut source = std::fs::File::open(from)?;
343    let mut file = std::fs::File::create(staged)?;
344    std::io::copy(&mut source, &mut file)?;
345    // For the installed binary only: shims get their mode from
346    // `hookfile::stage`, before a hook could be dispatched from them.
347    // The mode through the open handle, BEFORE the flush, so the flush covers
348    // it: after a power loss the target is never the whole binary at 0644.
349    #[cfg(unix)]
350    {
351        use std::os::unix::fs::PermissionsExt;
352        file.set_permissions(std::fs::Permissions::from_mode(0o755))?;
353    }
354    // `sync_all` needs a handle open for writing on Windows, which this is.
355    file.sync_all()
356}
357
358/// How long a leftover must be untouched before an install sweeps it.
359const LEFTOVER_AGE: std::time::Duration = std::time::Duration::from_secs(600);
360
361/// Remove what an interrupted [`replace_atomically`] can leave in `dir`:
362/// `.greengate*.tmp.*` and `.amont*.tmp.*` temporaries, and `*.old.exe` files
363/// renamed aside on Windows. Best effort: a file still in use stays for the
364/// next install. Only files untouched for [`LEFTOVER_AGE`]: a temporary that
365/// young may be another install's, running now, whose rename would then fail.
366fn sweep_install_leftovers(dir: &Path) {
367    let Ok(entries) = std::fs::read_dir(dir) else {
368        return;
369    };
370    for entry in entries.flatten() {
371        let name = entry.file_name().to_string_lossy().into_owned();
372        let ours = [BIN, OLD_BIN]
373            .iter()
374            .any(|n| name.starts_with(&format!(".{n}")) && name.contains(".tmp."));
375        let aside = [BIN, FLEET_BIN, OLD_BIN, OLD_FLEET_BIN]
376            .iter()
377            .any(|n| name == format!("{n}.old.exe"));
378        let stale = entry
379            .metadata()
380            .and_then(|m| m.modified())
381            .ok()
382            .and_then(|t| t.elapsed().ok())
383            .is_some_and(|age| age >= LEFTOVER_AGE);
384        if (ours || aside) && stale {
385            let _ = std::fs::remove_file(entry.path()); // best effort, see above
386        }
387    }
388}
389
390/// The old names written beside the binaries as copies (plan "amont ships as
391/// greengate"): `amont` from `greengate`, and `amont-fleet` from
392/// `greengate-fleet` when that sits in the same directory. Copies, not links:
393/// a 2.x `amont install` copies onto its target, and through a link it would
394/// overwrite greengate itself.
395///
396/// Returns the old names it wrote, for the install's own report.
397fn write_aliases(binary: &Path) -> Result<Vec<&'static str>, String> {
398    let dir = binary.parent().unwrap_or_else(|| Path::new("."));
399    let pairs = [(BIN, OLD_BIN), (FLEET_BIN, OLD_FLEET_BIN)];
400    let mut written = Vec::new();
401    for (new, old) in pairs {
402        let from = dir.join(name_for(binary, new));
403        if !from.is_file() {
404            continue;
405        }
406        let alias = dir.join(name_for(binary, old));
407        replace_atomically(&from, &alias).map_err(|e| {
408            format!(
409                "installed {}, but cannot write its old name {}: {e}\n    hooks baked to the old name keep running the build that was there;\n    run `{BIN} install` again, or delete {}",
410                from.display(),
411                alias.display(),
412                alias.display()
413            )
414        })?;
415        written.push(old);
416    }
417    Ok(written)
418}
419
420/// Hook files in `dir` that exist and are NOT ours, each with its reason.
421///
422/// `install` used to write all four unconditionally, which silently destroyed a
423/// `commit-msg` somebody had written themselves. That is the same failure as the
424/// two that overwrote tracked files, one directory along, and it had no guard at
425/// all — the fleet's `fix` planner has one and the per-repo installer never did.
426///
427/// It carries the [`HookFile`] rather than only the name because "commit-msg is
428/// not ours" sends somebody to diff a file against a shim they have never seen,
429/// while "commit-msg is not valid UTF-8 — a compiled hook, probably" ends the
430/// question. The old version could not have said either: it read the file as a
431/// string, and a file it could not read came back as NOT foreign.
432fn foreign_hooks(dir: &Path) -> Vec<(&'static str, HookFile)> {
433    DISPATCHERS
434        .into_iter()
435        .map(|name| (name, hookfile::classify(&dir.join(name))))
436        .filter(|(_, what)| !matches!(what, HookFile::Absent | HookFile::Ours))
437        .collect()
438}
439
440/// One dispatcher that landed, and what stood at that path before it.
441///
442/// `replaced` exists so `--force` can say what it took. It printed
443/// "baked 4 shims" and nothing else, which is a receipt for an act whose whole
444/// point is that it destroys something — the user typed `--force` precisely
445/// because there was a file there, and the one thing the output never said was
446/// which files or what they were.
447#[derive(Debug)]
448pub struct Written {
449    pub path: PathBuf,
450    pub replaced: HookFile,
451}
452
453/// Why a set of shims was not written.
454#[derive(Debug)]
455pub enum ShimWriteError {
456    /// One or more paths are not ours to write. Every refusal is carried, not
457    /// just the first: somebody about to run `--force` should see all four.
458    Refused(Vec<Refuse>),
459    /// A failure before any destination was touched — an unbakeable path, or a
460    /// staging write that could not happen (no space, no permission).
461    Preflight { at: PathBuf, error: std::io::Error },
462    /// Staging succeeded and a rename did not. The only failure mode that can
463    /// leave a directory partly written, which is why it carries the lists.
464    Swap(SwapFailure),
465}
466
467impl std::fmt::Display for ShimWriteError {
468    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
469        match self {
470            ShimWriteError::Refused(refusals) => {
471                writeln!(f, "refusing to write {} hooks:", refusals.len())?;
472                for (i, r) in refusals.iter().enumerate() {
473                    if i > 0 {
474                        writeln!(f)?;
475                    }
476                    write!(f, "    {}", r.explain())?;
477                }
478                Ok(())
479            }
480            ShimWriteError::Preflight { at, error } => {
481                write!(f, "cannot prepare {}: {error}", at.display())
482            }
483            ShimWriteError::Swap(s) => write!(f, "{s}"),
484        }
485    }
486}
487
488/// Write the four dispatchers into `dir`: guard ALL, stage ALL, then swap.
489///
490/// Three phases, in that order, because the posture `bake_repo_hooks` has
491/// claimed since it was written — "fail closed, and for the whole repository
492/// rather than per file: a partial install is how a repo ends up with two of
493/// four hooks and no way to tell" — was a comment over a loop that checked one
494/// file and then wrote it, four times. A refusal on the third hook came after
495/// two had already been overwritten.
496///
497/// Now: every path is guarded before any body is written, and every body is
498/// written before any destination is touched. A refusal anywhere means nothing
499/// at all was written; a staging failure likewise. Only the swap can leave a
500/// directory partly done, and that is reported as exactly which files landed
501/// and which did not (see [`SwapFailure`]) rather than as a count.
502///
503/// Returns what was written and what each write replaced, so `--force` can name
504/// what it took.
505fn write_shims(dir: &Path, bin: &str, force: bool) -> Result<Vec<Written>, ShimWriteError> {
506    // Fail closed rather than write four hooks that resolve to nothing — or, if
507    // the repository happens to hold a file by that name, to something.
508    if !is_bakeable(bin) {
509        return Err(ShimWriteError::Preflight {
510            at: dir.to_path_buf(),
511            error: std::io::Error::other(format!(
512                "refusing to bake {bin:?}: the shim takes an absolute path only"
513            )),
514        });
515    }
516    let baked = bake(SHIM, bin);
517
518    // Phase 1 — guard every path. Nothing has been written and nothing will be
519    // if a single one of these refuses.
520    let mut allowed: Vec<(PathBuf, HookFile)> = Vec::new();
521    let mut refusals: Vec<Refuse> = Vec::new();
522    for name in DISPATCHERS {
523        let path = dir.join(name);
524        match hookfile::guard_write(&path, force) {
525            Ok(what) => allowed.push((path, what)),
526            Err(r) => refusals.push(r),
527        }
528    }
529    if !refusals.is_empty() {
530        return Err(ShimWriteError::Refused(refusals));
531    }
532
533    // Phase 2 — stage every body. A `Staged` that never lands removes its own
534    // temporary on drop, so an error here leaves the directory as it was.
535    let mut staged: Vec<Staged> = Vec::new();
536    for (path, _) in &allowed {
537        match hookfile::stage(path, &baked, true) {
538            Ok(s) => staged.push(s),
539            Err(error) => {
540                return Err(ShimWriteError::Preflight {
541                    at: path.clone(),
542                    error,
543                });
544            }
545        }
546    }
547
548    // Phase 3 — swap. Renames, so a symlinked destination is REPLACED rather
549    // than written through.
550    hookfile::commit_all(staged).map_err(ShimWriteError::Swap)?;
551    Ok(allowed
552        .into_iter()
553        .map(|(path, replaced)| Written { path, replaced })
554        .collect())
555}
556
557/// Install: copy this binary somewhere stable, populate the template directory
558/// if that is safe, and bake the current repository's hooks.
559///
560/// Three steps, three functions. This was one 88-line body whose own comments
561/// numbered its sections — which is the tell that the sections wanted to be
562/// functions.
563pub fn run(settings: &crate::config::Settings, force: bool) -> Result<(), String> {
564    let binary = install_binary()?;
565    populate_template_dir(&binary, force)?;
566    bake_repo_hooks(&binary, force)?;
567    offer_trust();
568    offer_agents_md(settings);
569    point_at_setup(settings);
570    Ok(())
571}
572
573/// `amont enroll` — the machine-level standing grant, made one command.
574///
575/// The team-rollout problem in one sentence: hooks only protect the machines
576/// that installed them, and only npm repositories can self-install on clone.
577/// `enroll` is the other half — run ONCE per machine, it arranges for every
578/// FUTURE `git clone` and `git init` to arrive with the shims already baked:
579///
580///   1. the binary lands somewhere stable (`install_binary`'s rules);
581///   2. the template dir is populated (`populate_template_dir`'s guards);
582///   3. `init.templateDir` is pointed at it — the one write `install` always
583///      left to the user, because a standing grant should be typed, not
584///      inherited. `enroll` IS that typing.
585///
586/// With `--conventions declared` it also writes `amont.conventions`, so the
587/// grant is safe on a machine that clones other people's projects: those get
588/// the safety net only, and the house rules wait for a committed
589/// `amont.conf`. See `dispatch::conventions_apply`.
590///
591/// Existing clones are deliberately untouched — a standing grant reaches
592/// forward, not backward. The output names the two remedies.
593pub fn enroll(conventions: Option<&str>) -> Result<(), String> {
594    // Validate the flag BEFORE writing anything: an enroll that half-runs
595    // and then rejects its own argument has still changed global state.
596    match conventions {
597        None | Some("declared") | Some("everywhere") => {}
598        Some(other) => {
599            return Err(format!(
600                "{BIN} enroll --conventions takes `declared` or `everywhere`, not {other:?}"
601            ));
602        }
603    }
604    let binary = install_binary()?;
605    populate_template_dir(&binary, false)?;
606    let hooks = template_hooks_dir();
607    let templates = hooks
608        .parent()
609        .ok_or_else(|| "template hooks dir has no parent".to_string())?
610        .to_path_buf();
611    point_template_dir_at(&templates)?;
612
613    match conventions {
614        Some(word) => {
615            if !crate::git::succeeds(&["config", "--global", "amont.conventions", word]) {
616                return Err("could not write amont.conventions to the global git config".into());
617            }
618            eprintln!(
619                "{} amont.conventions = {} (global)",
620                valid_sign(),
621                highlight(word)
622            );
623            if word == "declared" {
624                eprintln!("    House rules run only in repositories that commit an amont.conf;");
625                eprintln!("    the safety net (conflicts, secrets, size, debug leftovers) runs");
626                eprintln!("    everywhere.");
627            }
628        }
629        None => {
630            eprintln!(
631                "{} conventions currently apply everywhere. On a machine that also",
632                warning_sign()
633            );
634            eprintln!("    clones other people's projects, consider:");
635            eprintln!(
636                "        {}",
637                highlight(concat!(crate::bin!(), " enroll --conventions declared"))
638            );
639        }
640    }
641
642    eprintln!();
643    eprintln!("Enrolled. Every future `git clone` and `git init` gets the hooks.");
644    eprintln!("Repositories cloned before now are untouched — wire them with");
645    eprintln!(
646        "    {}   (one repository)",
647        highlight(concat!(crate::bin!(), " init"))
648    );
649    eprintln!(
650        "    {}   (every repository under a root)",
651        highlight(concat!(crate::fleet_bin!(), " install --root <dir>"))
652    );
653    eprintln!(
654        "Undo with {}.",
655        highlight("git config --global --unset init.templateDir")
656    );
657    Ok(())
658}
659
660/// Point `init.templateDir` at `templates` — or refuse, loudly, when it
661/// already points somewhere else. Overwriting it would silently disable
662/// whatever the user's OTHER template dir was installing, which is the exact
663/// shape of failure the husky refusal exists to prevent, one level up.
664fn point_template_dir_at(templates: &std::path::Path) -> Result<(), String> {
665    let want = templates.to_string_lossy().into_owned();
666    let current = crate::git::stdout(&["config", "--global", "--get", "init.templateDir"])
667        .filter(|s| !s.is_empty());
668    match current {
669        None => {
670            if !crate::git::succeeds(&["config", "--global", "init.templateDir", &want]) {
671                return Err("could not write init.templateDir to the global git config".into());
672            }
673            eprintln!(
674                "{} init.templateDir = {} (global)",
675                valid_sign(),
676                highlight(&want)
677            );
678            Ok(())
679        }
680        Some(existing) if same_dir(&existing, &want) => {
681            eprintln!(
682                "{} init.templateDir already points here ({})",
683                valid_sign(),
684                highlight(&existing)
685            );
686            Ok(())
687        }
688        Some(existing) => Err(format!(
689            "init.templateDir is already set to {existing} — something else installs
690             hooks on this machine. Overwriting it would silently disable that.
691             Decide which one wins, then either unset it
692             (git config --global --unset init.templateDir) and re-run
693             `{BIN} enroll`, or leave enrollment to it."
694        )),
695    }
696}
697
698/// The same directory, spelled two ways: canonicalize both when possible so
699/// a symlinked config dir still counts as "already ours".
700fn same_dir(a: &str, b: &str) -> bool {
701    if a == b {
702        return true;
703    }
704    match (
705        std::path::Path::new(a).canonicalize(),
706        std::path::Path::new(b).canonicalize(),
707    ) {
708        (Ok(x), Ok(y)) => x == y,
709        _ => false,
710    }
711}
712
713/// `amont init` — wire up THIS repository, and touch nothing else.
714///
715/// The verb a package manager can call. `"prepare": "amont init"` in a
716/// `package.json` means a teammate who clones and runs `npm install` gets the
717/// hooks, which is the ergonomic husky has and this project did not.
718///
719/// ## Why `install` could not be that verb
720///
721/// Every one of its three extra steps is wrong for something that runs on every
722/// teammate's install, and the third is a hang:
723///
724///   * `install_binary` copies into `~/.local/bin` — a machine-level write from
725///     `npm install`;
726///   * `populate_template_dir` writes `~/.config/git/git-templates`, so a
727///     package manager would be arranging for every FUTURE clone to get hooks;
728///   * `offer_trust` calls `trust::confirm`, which opens `/dev/tty`. In a
729///     terminal that succeeds and BLOCKS, so `npm install` would stop dead on a
730///     prompt about a manifest the user has not read.
731///
732/// So this does one thing: bake four shims into the repository's own hooks
733/// directory.
734///
735/// ## What it bakes, and why not the PATH hit
736///
737/// `current_exe()`, always — never [`install_binary`]'s "is it already on
738/// `PATH`?" branch. Under npm the answer to that question is
739/// `node_modules/.bin/amont`, which is the **JS wrapper**: baking it would put a
740/// node process in front of every single commit, on a tool whose start-up cost
741/// is a stated feature. `current_exe()` is the native binary inside the platform
742/// package, which is what should run.
743///
744/// ## Silence, and its limits
745///
746/// Outside a git repository this reports nothing and exits 0. `npm install`
747/// legitimately runs where there is no `.git` — from a tarball, inside a Docker
748/// build, in CI — and failing there would make the package uninstallable in all
749/// three. It stays LOUD about everything else: a redirect, an unwritable
750/// directory, a foreign hook, and a repository git REFUSES to answer about
751/// (dubious ownership in a container bind mount, an unreadable `.git/config`)
752/// all still fail, because those are repositories where somebody believes they
753/// have hooks and does not. The silence is git's verdict, never git's absence.
754///
755/// ## Inside a push snapshot, it stands down
756///
757/// A push snapshot is a linked worktree, so it SHARES this repository's hooks
758/// directory — and its dependency install runs `prepare`, which runs this.
759/// Baking there pointed every hook at a binary inside a temp directory that
760/// is deleted minutes later. The snapshot marks itself in its own git admin
761/// dir ([`crate::pushed_tree::in_push_snapshot`]); when the mark is there,
762/// nothing is written. When it cannot be TOLD whether the mark is there, it
763/// fails rather than guess: a wrong guess is exactly the bake this prevents.
764pub fn init() -> Result<(), String> {
765    init_with(
766        std::env::current_exe(),
767        Path::new("."),
768        &crate::pushed_tree::in_push_snapshot,
769    )
770}
771
772/// [`init`] with what it would otherwise read from the process — the binary
773/// to bake, the directory to ask about, and the snapshot probe — passed in,
774/// so a test can reach every branch without `set_current_dir`.
775fn init_with(
776    me: std::io::Result<PathBuf>,
777    dir: &Path,
778    in_snapshot: &dyn Fn(&Path) -> std::io::Result<bool>,
779) -> Result<(), String> {
780    let rh = repo_hooks_in(dir);
781    // The one silent exit, and the only one: git itself said this is not a
782    // repository.
783    if matches!(rh, RepoHooks::Nowhere) {
784        return Ok(());
785    }
786    // BEFORE the redirect and `Unanswerable` arms: a snapshot's install must
787    // never fail `prepare` over hook config it is not going to touch anyway.
788    match in_snapshot(dir) {
789        Ok(true) => {
790            eprintln!(
791                "{BIN} init: inside a {BIN} push snapshot — the repository's hooks are left as they are"
792            );
793            return Ok(());
794        }
795        Ok(false) => {}
796        // git would not answer either question: its own reason, below, says
797        // more than ours would. Still a failure — nothing is written.
798        Err(_) if matches!(rh, RepoHooks::Unanswerable { .. }) => {}
799        Err(e) => {
800            return Err(format!(
801                "{} cannot tell whether this is a {BIN} push snapshot — {e}\n    \
802                 Hooks were NOT installed.",
803                error_sign()
804            ))
805        }
806    }
807    let hooks = match rh {
808        RepoHooks::Own(dir) => dir,
809        RepoHooks::Redirected { to, own } if redirect_is_hostile(&to, &own) => {
810            return Err(redirected_message(&to, &own))
811        }
812        RepoHooks::Redirected { to, .. } => to,
813        RepoHooks::Nowhere => return Ok(()),
814        RepoHooks::Unanswerable { why } => {
815            return Err(format!(
816                "{} git would not say where this repository's hooks live —\n    {}\n    \
817                 Hooks were NOT installed.",
818                error_sign(),
819                crate::ui::sanitize(&why)
820            ))
821        }
822    };
823
824    let me = me.map_err(|e| format!("cannot locate the running binary: {e}"))?;
825    // `absolute` rather than `canonicalize`: the shim needs an absolute path
826    // and nothing more, so there is no reason to touch the filesystem again.
827    //
828    // It does NOT keep us off pnpm's `.pnpm/<pkg>@<version>/…` store path, and
829    // an earlier version of this comment claimed it did. By the time this runs,
830    // the JS wrapper has already resolved the binary through `require.resolve`,
831    // which returns the REAL path — and `current_exe()` resolves symlinks
832    // besides. A pnpm install bakes the versioned store path, verified.
833    //
834    // Which is fine, and worth saying why rather than leaving the next reader
835    // to worry about it: `prepare` runs on every install, so a version bump
836    // re-bakes before anything can dispatch against the old path — and if one
837    // ever does go missing, the shim's resolution order falls through to
838    // `~/.local/bin` and then `PATH`, and fails LOUDLY rather than skipping a
839    // check, which is the property that actually matters.
840    let binary = absolute(&me);
841    let binary = binary.to_string_lossy().into_owned();
842    if !is_bakeable(&binary) {
843        return Err(format!(
844            "{} cannot bake {binary:?} — the shim takes an absolute path only",
845            error_sign()
846        ));
847    }
848
849    std::fs::create_dir_all(&hooks)
850        .map_err(|e| format!("cannot create {}: {e}", hooks.display()))?;
851
852    // `force: false`. A hook somebody else wrote is theirs, and `init` runs
853    // unattended — there is no one at the keyboard to have decided otherwise.
854    let written = write_shims(&hooks, &binary, false)
855        .map_err(|e| format!("cannot write shims to {}: {e}", hooks.display()))?;
856    eprintln!(
857        "{} {BIN}: {} hooks in {}",
858        valid_sign(),
859        written.len(),
860        hooks.display()
861    );
862    Ok(())
863}
864
865/// Name the commit-style settings, once, at the moment somebody acquires them.
866///
867/// A PRINT, never a prompt. `install` has to remain answerable by nobody: it
868/// runs under `amont-fleet install --root`, in provisioning scripts, and not
869/// at all for the `init.templateDir` users whose hooks arrive with a clone. A
870/// third question would break all three; a line of output breaks none of them,
871/// and it puts the dial in front of the one person guaranteed to be reading.
872fn point_at_setup(settings: &crate::config::Settings) {
873    let s = crate::commit_style::Style::resolve(settings);
874    eprintln!(
875        "  commit style: gitmoji {}, subject ≤{}, description ≤{} — `{BIN} setup` to change",
876        s.gitmoji.as_str(),
877        s.subject_max,
878        s.description_max
879    );
880}
881
882/// Ask about the manifest, once, at the moment somebody is already deciding
883/// about this repository.
884///
885/// `direnv` has to ask lazily on `cd` because it has no install step to hang
886/// the question from. We have one — so this is a single question, shown with
887/// the declarations in view, and declining still leaves the built-ins working.
888///
889/// Never blocks and never fails the install: a repository that declares nothing
890/// says nothing, and a non-interactive install simply reports the state.
891fn offer_trust() {
892    // No repository, no manifest to ask about. `repo_root()` answered "." and
893    // this went looking for `./amont.conf` in whatever directory the
894    // install was run from — a file it would then have offered to trust ON
895    // BEHALF of a repository that does not exist.
896    let Ok(root) = crate::hooks::common::repo_root_checked() else {
897        return;
898    };
899    let root = Path::new(&root);
900    let state = crate::trust::state(root);
901    if matches!(
902        state,
903        crate::trust::State::NoManifest | crate::trust::State::Trusted
904    ) {
905        return;
906    }
907
908    eprintln!();
909    eprintln!(
910        "{} {} declares checks and policy that would apply to your commits:",
911        warning_sign(),
912        crate::manifest::MANIFEST
913    );
914    // Read ONCE, then show and fingerprint that same buffer. `confirm()` blocks
915    // on a keypress, sometimes for several seconds, and a file rewritten in
916    // that window must not be trusted under the guise of the content that was
917    // displayed — `record_verified` re-checks this fingerprint once the answer
918    // is in. Reading separately to show and to hash would leave the same gap
919    // one step earlier: the listing approved need not be the one recorded.
920    let manifest = root.join(crate::manifest::MANIFEST);
921    let Ok(source) = std::fs::read(&manifest) else {
922        eprintln!(
923            "{} could not read {}",
924            warning_sign(),
925            crate::manifest::MANIFEST
926        );
927        return;
928    };
929    eprint!(
930        "{}",
931        crate::trust::describe_source(&String::from_utf8_lossy(&source))
932    );
933    let Some(fp) = crate::trust::fingerprint_bytes(root, &source) else {
934        eprintln!(
935            "{} could not hash {}",
936            warning_sign(),
937            crate::manifest::MANIFEST
938        );
939        return;
940    };
941    if crate::trust::confirm("    Trust them? (y/N) ") {
942        match crate::trust::record_verified(root, &fp) {
943            Ok(()) => eprintln!("{} trusted ({fp})", valid_sign()),
944            Err(e) => eprintln!("{} {e}", warning_sign()),
945        }
946    } else {
947        eprintln!("    Left untrusted. The built-ins still run; these do not.");
948        eprintln!("    Change your mind with `{BIN} trust`.");
949    }
950}
951
952/// Ask about `AGENTS.md`, once, right where `offer_trust` asks about the
953/// manifest — same reasoning, same shape: a single question with an install
954/// step to hang it from, and declining changes nothing about how the hooks
955/// themselves run.
956///
957/// This is the first thing `install` would write to TRACKED repo content —
958/// everything else here lives in `.git/hooks` (never tracked) or a
959/// machine-local path (`~/.local/bin`, the XDG template dir). That is exactly
960/// why it is a confirm, not a silent write: `crate::agents_md::write` is
961/// marker-scoped and safe to re-run, but "safe to overwrite" is not the same
962/// promise as "yours to write unasked."
963///
964/// Never blocks and never fails the install: skips silently when there is
965/// nothing to offer, and a non-interactive install simply leaves the
966/// question unanswered — `trust::confirm` already treats no tty as "no".
967fn offer_agents_md(settings: &crate::config::Settings) {
968    // Same reason as `offer_trust`: with `repo_root()`'s "." fallback, an
969    // install run outside a repository offered to write an AGENTS.md into the
970    // current directory — the one thing `install` writes to TRACKED content,
971    // aimed at a directory nobody said was a project.
972    let Ok(root) = crate::hooks::common::repo_root_checked() else {
973        return;
974    };
975    let path = Path::new(&root).join("AGENTS.md");
976    match crate::agents_md::check(settings, &path) {
977        Ok(crate::agents_md::CheckResult::MatchesGenerated) => return,
978        Ok(_) => {}
979        // Malformed markers: nothing this prompt can safely offer to fix.
980        Err(_) => return,
981    }
982
983    eprintln!();
984    eprintln!(
985        "{} AGENTS.md can point coding agents at `amont list --json` \
986         instead of leaving them to discover these checks the hard way:",
987        warning_sign()
988    );
989    if crate::trust::confirm("    Add it? (y/N) ") {
990        match crate::agents_md::write(settings, &path) {
991            Ok(()) => eprintln!("{} wrote {}", valid_sign(), path.display()),
992            Err(e) => eprintln!("{} {e}", warning_sign()),
993        }
994    } else {
995        eprintln!("    Left as-is. Change your mind with `{BIN} agents-md`.");
996    }
997}
998
999/// Where this binary can already be found on `PATH`, if it can.
1000///
1001/// Returns the path as `PATH` exposes it — deliberately NOT the resolved one.
1002/// Homebrew's `/usr/local/bin/amont` is a symlink into
1003/// `/usr/local/Cellar/amont/<version>/bin/`, and that Cellar path is
1004/// version-specific and removed on upgrade. Baking it would pin every repo to a
1005/// version that is about to be deleted, which is worse than the copy this
1006/// function exists to avoid. The same is true of any versioned store — nix,
1007/// asdf, mise.
1008///
1009/// So the comparison is canonical (to recognise ourselves through the symlink)
1010/// while the value returned is the entry that led here. That also makes the
1011/// answer correct whichever way `current_exe()` behaves: it resolves symlinks
1012/// on some platforms and libcs and not others, and this never has to care.
1013fn on_path_already(me: &Path) -> Option<PathBuf> {
1014    let me_real = me.canonicalize().ok()?;
1015    let name = installed_name();
1016    let path = std::env::var_os("PATH")?;
1017    std::env::split_paths(&path)
1018        .map(|dir| dir.join(&name))
1019        .filter(|cand| !in_a_build_dir(cand))
1020        .find(|cand| cand.canonicalize().is_ok_and(|real| real == me_real))
1021        .map(|cand| absolute(&cand))
1022        .filter(|abs| is_bakeable(&abs.to_string_lossy()))
1023}
1024
1025/// Whether `p` sits inside a cargo build directory.
1026///
1027/// "On PATH" alone is not the question — the question is whether the path will
1028/// still be there tomorrow, and a build directory is precisely the one that
1029/// will not. `cargo clean`, or any rebuild, and the shims baked against it
1030/// resolve nothing.
1031///
1032/// This is not hypothetical and it is not only about `cargo run`: **cargo
1033/// prepends the build directory to PATH when it runs tests on Windows**, so
1034/// `target/debug` genuinely appears there. That took out four existing install
1035/// tests on the Windows runner and nowhere else, which is a fair description of
1036/// how the loose predicate would have failed a user, too.
1037///
1038/// `CACHEDIR.TAG` is cargo's own marker for the directory, written since 1.55
1039/// and standardised for exactly this — "a program wrote this, do not treat it
1040/// as durable". Asking for it beats matching on the name `target`, which is
1041/// configurable and is also an ordinary word for a directory. Bounded to a few
1042/// levels so a stray tag high up somebody's home directory cannot disqualify
1043/// every path on the system.
1044fn in_a_build_dir(p: &Path) -> bool {
1045    p.ancestors()
1046        .skip(1)
1047        .take(4)
1048        .any(|dir| dir.join("CACHEDIR.TAG").is_file())
1049}
1050
1051/// Copy the running binary to a stable location, and return where it now lives.
1052fn install_binary() -> Result<String, String> {
1053    let me =
1054        std::env::current_exe().map_err(|e| format!("cannot locate the running binary: {e}"))?;
1055
1056    // A binary a package manager already put on PATH is not ours to copy.
1057    //
1058    // The copy below exists for `./target/release/amont install`, where the
1059    // binary sits in a directory `cargo clean` will delete — baking that path
1060    // would install hooks that stop resolving the next time somebody builds.
1061    // For `brew install`, `cargo install` or a distro package, the opposite is
1062    // true: the binary is already somewhere stable, and copying it produces a
1063    // SECOND, unmanaged copy that the package manager will never update again.
1064    //
1065    // That is not hypothetical. It is what this machine was in: `brew upgrade`
1066    // would have refreshed /usr/local/bin while every repo stayed baked to a
1067    // frozen copy in ~/.local/bin — the same staleness the copy is meant to
1068    // prevent, arrived at from the other direction.
1069    //
1070    // `$AMONT_BIN_DIR` is checked first because setting it IS the request to
1071    // put the binary somewhere specific, and honouring it costs nothing.
1072    if std::env::var_os("AMONT_BIN_DIR").is_none() {
1073        if let Some(stable) = on_path_already(&me) {
1074            let shown = stable.to_string_lossy().into_owned();
1075            eprintln!("{} using {}", valid_sign(), highlight(&shown));
1076            eprintln!("    already on PATH, so nothing was copied — an upgrade there");
1077            eprintln!("    reaches every repository without reinstalling.");
1078            return Ok(shown);
1079        }
1080    }
1081
1082    let dir = bin_dir();
1083    std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
1084
1085    // Absolute from here on: this path is what gets baked into every shim, and
1086    // `bin_dir()` honours `$AMONT_BIN_DIR`, which may be relative.
1087    let target = absolute(&dir.join(installed_name()));
1088    // Copying a running binary over ITSELF fails on some platforms and is
1089    // pointless on all of them.
1090    //
1091    // `me.canonicalize().ok() == target.canonicalize().ok()` is the version
1092    // this replaces, and it was wrong in the one case that matters: when the
1093    // TARGET does not exist yet — a first install, the whole point of the
1094    // step — `canonicalize` returns `Err`, both sides are `None`, `None ==
1095    // None` is true, and the copy was skipped. The binary was never installed,
1096    // and `install` printed "installed <path>" for a file that was not there.
1097    // Every shim then baked that path and resolved nothing. Two `Ok`s that
1098    // agree is the only thing that means "same file".
1099    let already_there = matches!(
1100        (me.canonicalize(), target.canonicalize()),
1101        (Ok(a), Ok(b)) if a == b
1102    );
1103    sweep_install_leftovers(&dir);
1104    if !already_there {
1105        replace_atomically(&me, &target)
1106            .map_err(|e| format!("cannot install to {}: {e}", target.display()))?;
1107    }
1108    let aliases = write_aliases(&target)?;
1109    let installed = target.to_string_lossy().into_owned();
1110    eprintln!("{} installed {}", valid_sign(), highlight(&installed));
1111    if !aliases.is_empty() {
1112        eprintln!(
1113            "    also as {}: hooks baked to the old name keep working",
1114            aliases.join(" and ")
1115        );
1116    }
1117    Ok(installed)
1118}
1119
1120/// Write the shims into the template directory — unless doing so would delete
1121/// somebody's source.
1122///
1123/// REFUSING is not an error: on a machine where the template dir is the
1124/// checkout, there is nothing to install and the install has succeeded. FAILING
1125/// to write one it was allowed to write is, though — reporting success after a
1126/// step did not happen is the thing this whole codebase is arranged against.
1127fn populate_template_dir(binary: &str, force: bool) -> Result<(), String> {
1128    let dir = template_hooks_dir();
1129    let _ = std::fs::create_dir_all(&dir);
1130    // Report the RESOLVED path. "It is the checkout" is only useful with the
1131    // checkout named, and the configured path is usually the symlink that hides
1132    // exactly that.
1133    let shown = dir.canonicalize().unwrap_or_else(|_| dir.clone());
1134    let shown = shown.display();
1135
1136    match classify_dir(&dir) {
1137        TemplateDir::IsCheckout => {
1138            eprintln!(
1139                "{} template dir IS the checkout ({shown}) — nothing to install.",
1140                warning_sign()
1141            );
1142            eprintln!("    Its shims keep the placeholder deliberately and resolve");
1143            eprintln!("    {binary} at run time. This is the intended setup.");
1144            // …as long as run-time resolution can actually reach the binary,
1145            // which the sentence above used to assert unconditionally.
1146            warn_if_unbaked_cannot_resolve(binary);
1147        }
1148        TemplateDir::InsideCheckout => {
1149            eprintln!(
1150                "{} {shown} is inside a git checkout — leaving it alone.",
1151                warning_sign()
1152            );
1153            warn_if_unbaked_cannot_resolve(binary);
1154        }
1155        TemplateDir::NoGit => eprintln!(
1156            "{} git is not on PATH — refusing to delete anything.",
1157            warning_sign()
1158        ),
1159        TemplateDir::Unresolvable => {
1160            eprintln!("{} cannot resolve {shown} — skipping.", warning_sign())
1161        }
1162        TemplateDir::Safe => {
1163            let written = write_shims(&dir, binary, force)
1164                .map_err(|e| format!("cannot write shims to {shown}: {e}"))?;
1165            eprintln!("{} wrote {} shims to {shown}", valid_sign(), written.len());
1166            report_overwrites(&written);
1167        }
1168    }
1169    Ok(())
1170}
1171
1172/// Say what each write took, for the writes that took something.
1173///
1174/// `install --force` used to print `baked 4 shims` and stop. `--force` is
1175/// typed precisely because a file is in the way, so the one fact the output
1176/// omitted is the only fact the user needed: which files, and what they were.
1177/// A hook replaced with no record of what it was is unrecoverable — `.git` is
1178/// not tracked, so there is nothing to `git checkout` it back from.
1179fn report_overwrites(written: &[Written]) {
1180    for w in written {
1181        if matches!(w.replaced, HookFile::Absent | HookFile::Ours) {
1182            continue;
1183        }
1184        eprintln!(
1185            "{} overwrote {} — it was {}",
1186            warning_sign(),
1187            w.path.display(),
1188            w.replaced.describe()
1189        );
1190    }
1191}
1192
1193/// Where git dispatches hooks from, and whether that is this repository's OWN
1194/// hooks directory or somewhere `core.hooksPath` sent it.
1195///
1196/// This replaces a bare `repo_hooks_dir()` that returned only the dispatch path.
1197/// `--git-path hooks` is still the right question — never `--git-dir` plus
1198/// `join("hooks")`, because hooks are explicitly SHARED across worktrees while a
1199/// linked worktree's `--git-dir` is its own PRIVATE gitdir, so joining "hooks"
1200/// onto it names a directory git never dispatches from. The addition is asking
1201/// `--git-common-dir` alongside it, so the answer can be compared against the
1202/// directory that would be ours.
1203///
1204/// The distinction did not exist and its absence was silent. `--git-path hooks`
1205/// honours `core.hooksPath`, so in a repository running husky it answers
1206/// `.husky/_` — inside the repo, plausible, and wrong. `install` wrote four
1207/// shims there, husky's own `prepare` regenerated the directory on the next
1208/// `npm install`, and the repository went back to having no checks with nothing
1209/// to show for it. Every guarantee this tool makes was off in those repositories
1210/// and the fleet reported them as merely "drifted".
1211#[derive(Debug, Clone, PartialEq, Eq)]
1212pub enum RepoHooks {
1213    /// `<git-common-dir>/hooks`. Git dispatches from here and it is ours to write.
1214    Own(PathBuf),
1215    /// `core.hooksPath` points somewhere else. Another tool owns dispatch here,
1216    /// and writing to `own` would install shims git never runs.
1217    Redirected { to: PathBuf, own: PathBuf },
1218    /// Not in a repository — git itself said "not a git repository".
1219    Nowhere,
1220    /// git failed for any OTHER reason: dubious ownership, an unreadable
1221    /// `.git/config`, a corrupt gitfile. There is plausibly a repository here;
1222    /// git would not talk about it. Split from [`RepoHooks::Nowhere`] because
1223    /// the two demand opposite behaviour from `init` — outside a repository,
1224    /// silence is correct; a repository git refuses to answer about is one
1225    /// where somebody believes they are getting hooks and is not, which is the
1226    /// failure this whole tool is arranged against.
1227    Unanswerable { why: String },
1228}
1229
1230/// Ask git both questions at once — what it dispatches from, and what this
1231/// repository's own hooks directory is — then compare.
1232///
1233/// Lexical comparison via [`crate::hookfile::resolve_lexical`], not
1234/// `canonicalize`: neither directory is guaranteed to exist yet (a fresh clone
1235/// has no `.git/hooks` until something writes one), and `canonicalize` cannot be
1236/// asked about a path that does not. Same reason `is_within` is lexical.
1237pub fn repo_hooks() -> RepoHooks {
1238    repo_hooks_in(Path::new("."))
1239}
1240
1241/// [`repo_hooks`] for the repository at `dir`, so a test can aim it at a
1242/// fixture without moving the process.
1243pub fn repo_hooks_in(dir: &Path) -> RepoHooks {
1244    // `git::output`, not `git::stdout`: the latter collapses every non-zero
1245    // exit to `None` with stderr discarded, which folded "not in a repository"
1246    // (silence is right) and "git refused to answer" (silence hid a container
1247    // checkout getting no hooks from `prepare`, with exit 0) into one arm.
1248    let Some(out) = crate::git::output_in(
1249        dir,
1250        &[
1251            "rev-parse",
1252            "--path-format=absolute",
1253            "--git-path",
1254            "hooks",
1255            "--git-common-dir",
1256        ],
1257    ) else {
1258        return RepoHooks::Unanswerable {
1259            why: "could not run git".to_string(),
1260        };
1261    };
1262    if out.code != 0 {
1263        // git's own verdict draws the line — the same phrase
1264        // `amont-fleet::scan::hooks_dir_for` keys on.
1265        if out.stderr.contains("not a git repository") {
1266            return RepoHooks::Nowhere;
1267        }
1268        let why = out
1269            .stderr
1270            .lines()
1271            .find(|l| l.starts_with("fatal:"))
1272            .or_else(|| out.stderr.lines().find(|l| !l.trim().is_empty()))
1273            .unwrap_or("git gave no reason")
1274            .to_string();
1275        return RepoHooks::Unanswerable { why };
1276    }
1277    let mut lines = out.stdout.lines();
1278    let (Some(dispatched), Some(common)) = (lines.next(), lines.next()) else {
1279        return RepoHooks::Nowhere;
1280    };
1281    let dispatched = PathBuf::from(dispatched);
1282    let own = PathBuf::from(common).join("hooks");
1283    if crate::hookfile::resolve_lexical(&dispatched) == crate::hookfile::resolve_lexical(&own) {
1284        RepoHooks::Own(own)
1285    } else {
1286        RepoHooks::Redirected {
1287            to: dispatched,
1288            own,
1289        }
1290    }
1291}
1292
1293/// Name the tool behind a `core.hooksPath`, when the path gives it away.
1294///
1295/// A short list on purpose. It is half of [`redirect_is_hostile`]'s evidence,
1296/// not a general classifier, and a name guessed wrong is worse than none.
1297pub fn redirect_culprit(to: &Path) -> Option<&'static str> {
1298    let s = to.to_string_lossy().replace('\\', "/");
1299    if s.contains("/.husky") {
1300        return Some("husky");
1301    }
1302    if s.contains("/.lefthook") || s.contains("lefthook") {
1303        return Some("lefthook");
1304    }
1305    None
1306}
1307
1308/// Whether any of our four shims sits in `dir`.
1309///
1310/// The runtime's own copy of the question `amont-fleet::scan::is_managed`
1311/// answers, because the guard that needs it runs in the commit-path crate and
1312/// cannot depend on the dashboard.
1313pub fn holds_our_shims(dir: &Path) -> bool {
1314    DISPATCHERS
1315        .iter()
1316        .any(|name| matches!(hookfile::classify(&dir.join(name)), HookFile::Ours))
1317}
1318
1319/// Whether a redirect must be REFUSED rather than followed.
1320///
1321/// Not every `core.hooksPath` is a problem, and the first cut of this refused
1322/// them all — which would have broken a repository that deliberately keeps its
1323/// hooks in `tooling/hooks` under version control. That is a setup this project
1324/// has always honoured and `plan_finds_shims_at_a_redirected_hooks_path` pins.
1325///
1326/// So the refusal rests on evidence, not on the mere presence of the setting.
1327/// Either is enough:
1328///
1329///   * **the destination belongs to a hook manager we recognise** — husky and
1330///     lefthook both REGENERATE their directory on install, so anything we wrote
1331///     there is gone by the next `npm install` and the repository silently stops
1332///     being checked;
1333///   * **our shims sit in the repository's own hooks directory and NOT at the
1334///     destination** — amont was installed here and something later took
1335///     dispatch away. Whatever the destination is, this repository is not
1336///     running the checks it believes it is, and that is worth stopping for
1337///     whether or not we can name the culprit.
1338///
1339/// The second signal needs both halves. A repository whose shims sit at the
1340/// destination too moved its hooks there deliberately — amont IS running, from
1341/// the directory the repository chose — and whatever lingers in
1342/// `<git-common-dir>/hooks` is leftovers from before the move, not evidence of
1343/// a takeover. Refusing on the leftovers alone locked such a repository out of
1344/// `install` (and of `amont init` from npm's `prepare`, failing every
1345/// `npm install`) with a remedy that would have broken the deliberate setup.
1346///
1347/// A repository with neither signal keeps the old behaviour exactly.
1348pub fn redirect_is_hostile(to: &Path, own: &Path) -> bool {
1349    redirect_culprit(to).is_some() || (holds_our_shims(own) && !holds_our_shims(to))
1350}
1351
1352/// The refusal both `install` and `init` give when another tool owns dispatch.
1353///
1354/// One function, so the two cannot drift into saying different things about the
1355/// same situation — and so the remedy is spelled exactly once.
1356pub fn redirected_message(to: &Path, own: &Path) -> String {
1357    let mut msg = format!(
1358        "{} git dispatches hooks from {}, not {}",
1359        error_sign(),
1360        highlight(&to.display().to_string()),
1361        own.display()
1362    );
1363    match redirect_culprit(to) {
1364        Some(tool) => msg.push_str(&format!(
1365            "\n    `core.hooksPath` is set, so {tool} owns the hooks here. Shims\n    \
1366             written to either directory would be overwritten or never run."
1367        )),
1368        None => msg.push_str(
1369            "\n    `core.hooksPath` is set, so another tool owns the hooks here.\n    \
1370             Shims written to either directory would be overwritten or never run.",
1371        ),
1372    }
1373    msg.push_str(&format!(
1374        "\n    Hand dispatch back first: {}",
1375        highlight("git config --unset core.hooksPath")
1376    ));
1377    // Stranded shims are the evidence when no culprit is named — say how to
1378    // clear them, because "unset core.hooksPath" is the WRONG remedy for a
1379    // repository whose redirect is deliberate and merely predates a cleanup.
1380    if redirect_culprit(to).is_none() && holds_our_shims(own) {
1381        msg.push_str(&format!(
1382            "\n    Or, if the redirect is deliberate, clear our stale shims from {}\n    \
1383             first: {}",
1384            own.display(),
1385            highlight(concat!(crate::bin!(), " uninstall"))
1386        ));
1387    }
1388    msg
1389}
1390
1391/// Bake the shims into the repository we are standing in, if we are in one.
1392///
1393/// The tracked guard is inherited from `hookfile::guard_write` rather than
1394/// written here, and that inheritance closes a verified bug: with
1395/// `.git/hooks/pre-commit` a symlink to a TRACKED `devhooks/pre-commit`,
1396/// `install --force` rewrote the tracked source file. Every guard this function
1397/// had was about the LINK path — untracked, inside `.git`, unremarkable — while
1398/// `fs::write` followed the link and landed in the working tree. Both halves
1399/// are fixed at once: the symlink is refused by name, and `--force` replaces
1400/// the link by rename instead of writing through it.
1401fn bake_repo_hooks(binary: &str, force: bool) -> Result<(), String> {
1402    let hooks = match repo_hooks() {
1403        RepoHooks::Own(dir) => dir,
1404        // A hostile redirect is refused, and `--force` does not move it.
1405        // `--force` means "that file is mine to replace"; it has never meant
1406        // "write where git does not look". Writing `own` would leave four shims
1407        // git never dispatches, and writing `to` would hand our files to the
1408        // tool that regenerates that directory.
1409        //
1410        // A redirect that is merely a redirect is followed, as it always was —
1411        // see `redirect_is_hostile` for where the line is.
1412        RepoHooks::Redirected { to, own } if redirect_is_hostile(&to, &own) => {
1413            return Err(redirected_message(&to, &own))
1414        }
1415        RepoHooks::Redirected { to, .. } => to,
1416        RepoHooks::Nowhere => {
1417            eprintln!(
1418                "{} not inside a git repository — no repo hooks written.",
1419                warning_sign()
1420            );
1421            return Ok(());
1422        }
1423        RepoHooks::Unanswerable { why } => {
1424            return Err(format!(
1425                "{} git would not say where this repository's hooks live —\n    {}",
1426                error_sign(),
1427                crate::ui::sanitize(&why)
1428            ))
1429        }
1430    };
1431    let _ = std::fs::create_dir_all(&hooks);
1432
1433    // Asked here, ahead of the guard, only so the message can offer `--force`.
1434    // The guard inside `write_shims` is the one that decides, and it refuses
1435    // things `--force` will not move (a tracked path, a path git cannot answer
1436    // for) which this pre-check deliberately says nothing about.
1437    let foreign = foreign_hooks(&hooks);
1438    if !foreign.is_empty() && !force {
1439        let mut msg = format!(
1440            "{} {} already has hooks that are not ours:",
1441            error_sign(),
1442            hooks.display()
1443        );
1444        for (name, what) in &foreign {
1445            msg.push_str(&format!("\n    {name} — {}", what.describe()));
1446        }
1447        msg.push_str(concat!(
1448            "\n    Look at them first, then `",
1449            crate::bin!(),
1450            " install --force`."
1451        ));
1452        return Err(msg);
1453    }
1454
1455    let written = write_shims(&hooks, binary, force)
1456        .map_err(|e| format!("cannot write shims to {}: {e}", hooks.display()))?;
1457    eprintln!(
1458        "{} baked {} shims into {}",
1459        valid_sign(),
1460        written.len(),
1461        hooks.display()
1462    );
1463    report_overwrites(&written);
1464    Ok(())
1465}
1466
1467/// Take the shims out of the repository we are standing in.
1468///
1469/// Deliberately narrow. It removes files that are OURS and nothing else:
1470///
1471/// - a hook we did not write is left alone and named, because somebody wrote it
1472///   on purpose;
1473/// - `hook.skip` and `amont.severity` are never touched — those are the
1474///   user's statements about their own repository, not our artefacts, and a
1475///   reinstall should not silently forget that they disabled a check;
1476/// - the binary goes only when asked, because other repositories are using it.
1477pub fn uninstall(remove_binary: bool) -> Result<(), String> {
1478    // The template directory FIRST, and unconditionally, because it is the only
1479    // part of an install that keeps working when you are not standing in a
1480    // repository — and because `uninstall` returning early with "not inside a
1481    // git repository" is how the standing grant survived every attempt to
1482    // revoke it.
1483    uninstall_template_dir()?;
1484    uninstall_repo_hooks()?;
1485
1486    if remove_binary {
1487        // The binary and the alias of its old name: an uninstall that left
1488        // `amont` behind would leave every 2.x shim still running it.
1489        let me = std::env::current_exe().unwrap_or_else(|_| PathBuf::from(BIN));
1490        for name in [BIN, OLD_BIN] {
1491            let target = bin_dir().join(name_for(&me, name));
1492            match std::fs::remove_file(&target) {
1493                Ok(()) => eprintln!(
1494                    "{} removed {}",
1495                    valid_sign(),
1496                    highlight(&target.to_string_lossy())
1497                ),
1498                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1499                Err(e) => return Err(format!("cannot remove {}: {e}", target.display())),
1500            }
1501        }
1502    }
1503
1504    report_global_template_dir();
1505
1506    // Said out loud, because a user who uninstalls and reinstalls should not be
1507    // surprised that a check they disabled is still disabled.
1508    eprintln!("    hook.skip and amont.severity were not touched.");
1509    Ok(())
1510}
1511
1512/// `amont uninstall --repo`: this repository's shims and bookkeeping, and
1513/// nothing else. The template dir, `init.templateDir` and the binary are
1514/// machine state, which an installer that armed one repository must leave
1515/// exactly as it found them.
1516pub fn uninstall_repo() -> Result<(), String> {
1517    uninstall_repo_hooks()
1518}
1519
1520/// How much of amont is in a hooks directory.
1521#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1522pub enum InstalledState {
1523    /// All six shims.
1524    Present,
1525    /// None, and every hook could be read.
1526    Absent,
1527    Partial,
1528    /// A hook could not be read, or git would not answer: never "absent".
1529    Unknown,
1530}
1531
1532impl InstalledState {
1533    pub fn as_str(self) -> &'static str {
1534        match self {
1535            InstalledState::Present => "present",
1536            InstalledState::Absent => "absent",
1537            InstalledState::Partial => "partial",
1538            InstalledState::Unknown => "unknown",
1539        }
1540    }
1541}
1542
1543/// Whether our shims are in a hooks directory, and the binary each bakes.
1544#[derive(Debug, PartialEq, Eq)]
1545pub struct Installed {
1546    pub state: InstalledState,
1547    pub hooks_dir: Option<PathBuf>,
1548    /// `(hook name, baked binary path)` for each shim of ours.
1549    pub shims: Vec<(&'static str, Option<String>)>,
1550}
1551
1552impl Installed {
1553    fn unknown() -> Installed {
1554        Installed {
1555            state: InstalledState::Unknown,
1556            hooks_dir: None,
1557            shims: Vec::new(),
1558        }
1559    }
1560
1561    pub fn to_json(&self) -> String {
1562        let shims: Vec<String> = self
1563            .shims
1564            .iter()
1565            .map(|(name, bin)| {
1566                crate::json::object(&[
1567                    crate::json::string_field("name", name),
1568                    crate::json::opt_string_field("binary", bin.as_deref()),
1569                ])
1570            })
1571            .collect();
1572        let dir = self.hooks_dir.as_ref().map(|d| d.display().to_string());
1573        crate::json::object(&[
1574            crate::json::string_field("state", self.state.as_str()),
1575            crate::json::opt_string_field("hooks_dir", dir.as_deref()),
1576            format!("\"shims\":{}", crate::json::array(&shims)),
1577        ])
1578    }
1579}
1580
1581/// Read the shims in `dir` from the files themselves, never from the list of
1582/// checks: what is installed is what is on disk.
1583pub fn installed_in(dir: &Path) -> Installed {
1584    let mut shims = Vec::new();
1585    let mut unreadable = false;
1586    for name in DISPATCHERS {
1587        let path = dir.join(name);
1588        match hookfile::classify(&path) {
1589            HookFile::Ours => shims.push((name, baked_binary(&path))),
1590            HookFile::Unknown { .. }
1591            | HookFile::Foreign(hookfile::ForeignWhy::Unreadable { .. }) => unreadable = true,
1592            HookFile::Absent
1593            | HookFile::Symlink { .. }
1594            | HookFile::NotARegularFile
1595            | HookFile::Foreign(
1596                hookfile::ForeignWhy::HandWritten | hookfile::ForeignWhy::NotUtf8,
1597            ) => {}
1598            // Unix only: the variant does not exist on Windows.
1599            #[cfg(unix)]
1600            HookFile::Foreign(hookfile::ForeignWhy::MultiplyLinked { .. }) => {}
1601        }
1602    }
1603    let state = match (shims.len(), unreadable) {
1604        (n, _) if n == DISPATCHERS.len() => InstalledState::Present,
1605        (_, true) => InstalledState::Unknown,
1606        (0, false) => InstalledState::Absent,
1607        _ => InstalledState::Partial,
1608    };
1609    Installed {
1610        state,
1611        hooks_dir: Some(dir.to_path_buf()),
1612        shims,
1613    }
1614}
1615
1616/// The repository's hooks, where git dispatches from.
1617pub fn installed_here() -> Installed {
1618    match repo_hooks() {
1619        RepoHooks::Own(dir) | RepoHooks::Redirected { to: dir, .. } => installed_in(&dir),
1620        RepoHooks::Nowhere | RepoHooks::Unanswerable { .. } => Installed::unknown(),
1621    }
1622}
1623
1624/// The machine's template dir, which every `git clone` copies hooks from.
1625pub fn installed_in_template_dir() -> Installed {
1626    installed_in(&template_hooks_dir())
1627}
1628
1629/// The absolute path `install` baked into a shim (`BAKED="…"`), if any.
1630fn baked_binary(path: &Path) -> Option<String> {
1631    let text = std::fs::read_to_string(path).ok()?;
1632    text.lines().find_map(|l| {
1633        let v = l.strip_prefix("BAKED=\"")?.strip_suffix('"')?;
1634        (!v.is_empty() && v != PLACEHOLDER).then(|| v.to_string())
1635    })
1636}
1637
1638/// Everything this tool ever wrote into ONE repository, forgotten — the
1639/// single list, so the two uninstall paths cannot drift apart.
1640///
1641/// `amont uninstall` swept its own repository and the fleet's `uninstall`
1642/// swept none of them: it removed shims from 200 repositories and left 200
1643/// ledgers, stamp refs and trust records behind, each one a statement about
1644/// hooks that are no longer there. Both now call this.
1645///
1646/// **Trust is revoked here, and that is a deliberate reversal.** The record
1647/// is keyed on the manifest's content, so keeping it would re-honour the
1648/// consent automatically on a reinstall — for bytes somebody reviewed once,
1649/// possibly a year ago, in a repository they since asked amont to stop
1650/// running in. Consent defaults to no everywhere else in this codebase
1651/// (untrusted manifests are inert, policy is withheld); it defaults to no
1652/// here too. Re-granting is one `amont trust`, which shows the file again.
1653///
1654/// **What is never touched**: `hook.skip` and `amont.severity` (the user's
1655/// statements about their repository, not ours), and above all the held
1656/// store — `$GIT_DIR/amont-held` and `amont-preserved` hold UNCOMMITTED
1657/// WORK. An uninstall that deletes those loses the very thing the parking
1658/// machinery exists to protect; `amont restore` must keep working after the
1659/// hooks are gone.
1660pub fn forget_bookkeeping_in(repo: &Path) -> Vec<&'static str> {
1661    let mut gone = Vec::new();
1662    if crate::gate_stamp::forget_in(repo) {
1663        gone.push("gate stamps");
1664    }
1665    if crate::attest::forget_in(repo) {
1666        gone.push("attestations");
1667    }
1668    if crate::bypass::forget_in(repo) {
1669        gone.push("bypass ledger");
1670    }
1671    if crate::downgrade::forget_in(repo) {
1672        gone.push("downgrade ledger");
1673    }
1674    if crate::skew::forget_in(repo) {
1675        gone.push("version-skew marker");
1676    }
1677    // `--unset-all` exits 5 when the key is absent; that is not a removal.
1678    if crate::git::succeeds_in(repo, &["config", "--unset-all", "amont.knownIdentity"]) {
1679        gone.push("known-identity memo");
1680    }
1681    if !crate::trust::recorded(repo).is_empty() && crate::trust::revoke(repo).is_ok() {
1682        gone.push("amont.conf trust");
1683    }
1684    gone
1685}
1686
1687/// Remove our shims from the repository we are standing in, naming everything
1688/// we did not take and why.
1689///
1690/// Every non-removal is now NAMED. The loop this replaces matched
1691/// `Err(_) => {}` on `read_to_string`, so a hook that could not be read at all
1692/// — a compiled one, or one whose permissions we lack — was passed over in
1693/// total silence: not removed, not counted, not mentioned. The README's promise
1694/// that a foreign hook is "left alone and named" was true only for hooks that
1695/// happened to be valid UTF-8.
1696///
1697/// Not being in a repository is a warning rather than an error. It used to
1698/// return `Err`, which was defensible on its own but became wrong once
1699/// `uninstall_template_dir` existed: the early return meant that running
1700/// `amont uninstall` from a plain directory did nothing AND said nothing,
1701/// while `init.templateDir` quietly went on installing hooks into every future
1702/// clone. Refusing is not failing — the same rule `populate_template_dir`
1703/// already states.
1704fn uninstall_repo_hooks() -> Result<(), String> {
1705    // BOTH directories, where they differ. Uninstall is the one path that must
1706    // not inherit `install`'s new refusal: versions before it wrote shims into
1707    // whatever `core.hooksPath` named, so a repository can be carrying our files
1708    // in `.husky/_` right now — and refusing to look there would leave the only
1709    // command that removes them unable to find them. Removal is safe in a way
1710    // writing is not; `guard_remove` still decides file by file.
1711    let dirs: Vec<PathBuf> = match repo_hooks() {
1712        RepoHooks::Own(dir) => vec![dir],
1713        RepoHooks::Redirected { to, own } => vec![to, own],
1714        RepoHooks::Nowhere => {
1715            eprintln!(
1716                "{} not inside a git repository — no repo hooks removed.",
1717                warning_sign()
1718            );
1719            return Ok(());
1720        }
1721        // Removal stays forgiving where writing does not: failing here would
1722        // leave `uninstall --binary` unable to finish its cleanup. Loud, and Ok.
1723        RepoHooks::Unanswerable { why } => {
1724            eprintln!(
1725                "{} git would not answer here — no repo hooks removed ({})",
1726                warning_sign(),
1727                crate::ui::sanitize(&why)
1728            );
1729            return Ok(());
1730        }
1731    };
1732
1733    for hooks in &dirs {
1734        let mut removed = 0usize;
1735        let mut left: Vec<String> = Vec::new();
1736        for name in DISPATCHERS {
1737            let path = hooks.join(name);
1738            match hookfile::classify(&path) {
1739                HookFile::Absent => {}
1740                HookFile::Ours => match hookfile::guard_remove(&path, true) {
1741                    Ok(()) => {
1742                        hookfile::remove_regular(&path)
1743                            .map_err(|e| format!("cannot remove {}: {e}", path.display()))?;
1744                        removed += 1;
1745                    }
1746                    // Ours by marker, and still not ours to delete: a tracked
1747                    // path, or one git could not answer for.
1748                    Err(r) => left.push(r.explain()),
1749                },
1750                what => left.push(format!("{name} — {}", what.describe())),
1751            }
1752        }
1753        // The second directory is usually empty of ours and saying so every time
1754        // would be noise. Report it only when it held something.
1755        if removed > 0 || !left.is_empty() || dirs.len() == 1 {
1756            eprintln!(
1757                "{} removed {removed} shims from {}",
1758                valid_sign(),
1759                hooks.display()
1760            );
1761        }
1762        for reason in &left {
1763            eprintln!("{} left alone: {reason}", warning_sign());
1764        }
1765    }
1766    // Our bookkeeping only ever says "amont checked this" (or "didn't"),
1767    // which stops being true of anything the moment the hooks are gone. One
1768    // list, shared with the fleet — see `forget_bookkeeping_in` for what is
1769    // deliberately NOT taken.
1770    if let Ok(root) = crate::hooks::common::repo_root_checked() {
1771        let gone = forget_bookkeeping_in(Path::new(&root));
1772        if !gone.is_empty() {
1773            eprintln!("{} forgot {}", valid_sign(), gone.join(", "));
1774        }
1775    }
1776    Ok(())
1777}
1778
1779/// Take our shims back out of the template directory.
1780///
1781/// `install` writes there; `uninstall` did not, which meant uninstall did not
1782/// undo install. Combined with `init.templateDir`, that is the failure worth
1783/// spelling out: the user runs `amont uninstall`, sees "removed 4 shims",
1784/// believes they are done — and every `git clone` and `git init` from then on
1785/// copies the template directory into the new repository's `.git/hooks` and
1786/// installs the hooks again. They uninstalled a repository, not a machine.
1787///
1788/// The same classification `install` uses decides what may happen here, for the
1789/// same reason and with the sharper stake: `~/.config/git/git-templates` is
1790/// commonly a SYMLINK to a checkout of this repository, and "uninstalling"
1791/// there means `rm` on tracked source. That is not a hypothetical; it is the
1792/// two incidents this module exists because of, and a delete has no `--force`.
1793fn uninstall_template_dir() -> Result<(), String> {
1794    let dir = template_hooks_dir();
1795    // The RESOLVED path, because the configured one is usually the symlink that
1796    // hides exactly what we are about to explain.
1797    let shown = dir.canonicalize().unwrap_or_else(|_| dir.clone());
1798    let shown = shown.display();
1799
1800    match classify_dir(&dir) {
1801        TemplateDir::IsCheckout | TemplateDir::InsideCheckout => {
1802            eprintln!(
1803                "{} template dir is a git checkout ({shown}) — deleting NOTHING there.",
1804                warning_sign()
1805            );
1806            eprintln!("    Those shims are tracked files belonging to that checkout,");
1807            eprintln!("    not something this install put there. Remove them with git,");
1808            eprintln!("    or point init.templateDir somewhere else.");
1809        }
1810        TemplateDir::NoGit => eprintln!(
1811            "{} git is not on PATH — cannot tell whether {shown} is a checkout, deleting nothing.",
1812            warning_sign()
1813        ),
1814        TemplateDir::Unresolvable => eprintln!(
1815            "{} no template dir at {shown} — nothing to remove.",
1816            warning_sign()
1817        ),
1818        TemplateDir::Safe => {
1819            let mut removed = 0usize;
1820            let mut left: Vec<String> = Vec::new();
1821            for name in DISPATCHERS {
1822                let path = dir.join(name);
1823                match hookfile::classify(&path) {
1824                    HookFile::Absent => {}
1825                    HookFile::Ours => match hookfile::guard_remove(&path, true) {
1826                        Ok(()) => {
1827                            hookfile::remove_regular(&path)
1828                                .map_err(|e| format!("cannot remove {}: {e}", path.display()))?;
1829                            removed += 1;
1830                        }
1831                        Err(r) => left.push(r.explain()),
1832                    },
1833                    what => left.push(format!("{name} — {}", what.describe())),
1834                }
1835            }
1836            eprintln!("{} removed {removed} shims from {shown}", valid_sign());
1837            for reason in &left {
1838                eprintln!("{} left alone: {reason}", warning_sign());
1839            }
1840        }
1841    }
1842    Ok(())
1843}
1844
1845/// Say, every time, whether `init.templateDir` is still pointing at us.
1846///
1847/// UNCONDITIONAL, including when the template dir was a checkout we refused to
1848/// touch and when there was no template dir at all — because the config setting
1849/// is what actually installs hooks into new repositories, and it survives every
1850/// file this command removes. An uninstall that leaves it set has not
1851/// uninstalled anything durable: the next `git clone` re-installs.
1852///
1853/// Printed rather than unset. `git config --global` is the user's file, holding
1854/// their identity and their aliases, and reaching into it uninvited is a larger
1855/// claim than removing files this tool wrote. The command to run is given
1856/// verbatim so it is a copy rather than a lookup.
1857fn report_global_template_dir() {
1858    let Some(configured) = crate::git::stdout(&["config", "--global", "--get", "init.templateDir"])
1859        .filter(|s| !s.is_empty())
1860    else {
1861        return;
1862    };
1863    eprintln!();
1864    eprintln!(
1865        "{} init.templateDir is still set: {}",
1866        warning_sign(),
1867        highlight(&configured)
1868    );
1869    eprintln!("    Every `git clone` and `git init` still copies hooks from there");
1870    eprintln!("    into the new repository. Uninstalling this repo did not change that.");
1871    eprintln!("    Undo it with:");
1872    eprintln!(
1873        "        {}",
1874        highlight("git config --global --unset init.templateDir")
1875    );
1876}
1877
1878#[cfg(test)]
1879mod tests {
1880    use super::*;
1881
1882    fn tmp(name: &str) -> PathBuf {
1883        let d = std::env::temp_dir().join(format!("gh-install-{name}-{}", std::process::id()));
1884        let _ = std::fs::remove_dir_all(&d);
1885        std::fs::create_dir_all(&d).expect("mkdir");
1886        d
1887    }
1888
1889    fn git(dir: &Path, args: &[&str]) {
1890        Command::new("git")
1891            .arg("-C")
1892            .arg(dir)
1893            .args(args)
1894            .output()
1895            .expect("git");
1896    }
1897
1898    /// The embedded shim must be the shim that ships. `include_str!` takes one
1899    /// of the four; if they ever diverge, the installer would write a file
1900    /// nobody reviewed.
1901    #[test]
1902    fn shims_on_disk_match_the_embedded_one() {
1903        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
1904        // Absent when this crate is built from its PUBLISHED tarball, which
1905        // contains this directory and nothing above it. There is no drift to
1906        // catch in that situation — the only shim present is the one compiled
1907        // in — so say so rather than fail a test about a file that is not
1908        // supposed to be there.
1909        if !Path::new(dir).is_dir() {
1910            println!(
1911                "! no repository checkout here — nothing to compare the embedded shim against"
1912            );
1913            return;
1914        }
1915        for name in DISPATCHERS {
1916            let disk = std::fs::read_to_string(Path::new(dir).join(name))
1917                .unwrap_or_else(|e| panic!("read {name}: {e}"));
1918            assert_eq!(disk, SHIM, "{name} differs from the embedded shim");
1919        }
1920    }
1921
1922    /// The bytes that SHIP carry no carriage return.
1923    ///
1924    /// `SHIM` is an `include_str!`, so it is whatever the build host's
1925    /// checkout held — and with no `.gitattributes` that was CRLF on
1926    /// Windows, whose git defaults `core.autocrlf` to true. v1.14.0's
1927    /// `amont.exe` embedded `#!/bin/sh\r\n` and its archive shipped an
1928    /// 82-CR `pre-commit`, so every install there wrote a shell script with
1929    /// a carriage return in the shebang. This asserts the fix from the only
1930    /// side that matters — the compiled-in bytes — rather than trusting the
1931    /// attributes file to keep working. It runs on the Windows job, which is
1932    /// the checkout that could regress.
1933    #[test]
1934    fn the_embedded_shim_carries_no_carriage_return() {
1935        assert!(
1936            !SHIM.contains('\r'),
1937            "the embedded shim has CRLF line endings: this binary would \
1938             install `#!/bin/sh\\r` as a POSIX sh hook. `.gitattributes` \
1939             declares templates/hooks/* as eol=lf — has it been removed, or \
1940             is this checkout stale?"
1941        );
1942    }
1943
1944    /// The whole point of the module. A directory holding tracked files is the
1945    /// source checkout reached through a symlink, and emptying it destroys work.
1946    #[test]
1947    fn a_directory_holding_tracked_files_is_never_safe() {
1948        let d = tmp("tracked");
1949        git(&d, &["init", "-q", "--template=", "."]);
1950        git(&d, &["config", "user.email", "t@t.test"]);
1951        git(&d, &["config", "user.name", "t"]);
1952        std::fs::write(d.join("kept.txt"), "precious\n").expect("write");
1953        git(&d, &["add", "-A"]);
1954        git(&d, &["commit", "-qm", "seed"]);
1955
1956        assert_eq!(classify_dir(&d), TemplateDir::IsCheckout);
1957        let _ = std::fs::remove_dir_all(&d);
1958    }
1959
1960    /// A path comparison against the source tree passes here and is WRONG: a
1961    /// worktree is a different path holding the same tracked files. This is the
1962    /// case that caused the second incident.
1963    #[test]
1964    fn a_worktree_is_recognised_even_though_its_path_differs() {
1965        let d = tmp("wt-main");
1966        git(&d, &["init", "-q", "--template=", "."]);
1967        git(&d, &["config", "user.email", "t@t.test"]);
1968        git(&d, &["config", "user.name", "t"]);
1969        std::fs::write(d.join("kept.txt"), "precious\n").expect("write");
1970        git(&d, &["add", "-A"]);
1971        git(&d, &["commit", "-qm", "seed"]);
1972
1973        let wt = d.with_extension("wt");
1974        let _ = std::fs::remove_dir_all(&wt);
1975        git(&d, &["worktree", "add", "-q", wt.to_str().unwrap()]);
1976        assert!(
1977            wt.join("kept.txt").is_file(),
1978            "worktree did not materialise"
1979        );
1980        assert_ne!(d.canonicalize().ok(), wt.canonicalize().ok());
1981        assert_eq!(
1982            classify_dir(&wt),
1983            TemplateDir::IsCheckout,
1984            "a worktree must be refused exactly like the main checkout"
1985        );
1986        let _ = std::fs::remove_dir_all(&wt);
1987        let _ = std::fs::remove_dir_all(&d);
1988    }
1989
1990    /// Inside a checkout but tracking nothing here — still not ours to empty.
1991    #[test]
1992    fn an_untracked_directory_inside_a_checkout_is_refused() {
1993        let d = tmp("inside");
1994        git(&d, &["init", "-q", "--template=", "."]);
1995        let sub = d.join("scratch");
1996        std::fs::create_dir_all(&sub).expect("mkdir");
1997        assert_eq!(classify_dir(&sub), TemplateDir::InsideCheckout);
1998        let _ = std::fs::remove_dir_all(&d);
1999    }
2000
2001    #[test]
2002    fn an_ordinary_directory_is_safe() {
2003        let d = tmp("plain");
2004        assert_eq!(classify_dir(&d), TemplateDir::Safe);
2005        let _ = std::fs::remove_dir_all(&d);
2006    }
2007
2008    #[test]
2009    fn a_missing_directory_is_unresolvable_not_safe() {
2010        assert_eq!(
2011            classify_dir(Path::new("/nonexistent-install-c8f2/hooks")),
2012            TemplateDir::Unresolvable
2013        );
2014    }
2015
2016    /// Baking replaces every occurrence and is idempotent.
2017    #[test]
2018    fn baking_is_total_and_idempotent() {
2019        let once = bake(SHIM, "/opt/amont");
2020        assert!(!once.contains(PLACEHOLDER), "a token survived baking");
2021        assert!(once.contains("/opt/amont"));
2022        assert_eq!(bake(&once, "/other"), once, "re-baking must be a no-op");
2023    }
2024
2025    /// The shim's comment must not spell the token out, or a global replace
2026    /// turns the explanation into a machine path — which it did, in every shim
2027    /// baked before this module existed.
2028    #[test]
2029    fn baking_does_not_rewrite_the_comment_explaining_it() {
2030        for line in bake(SHIM, "/opt/amont").lines() {
2031            if line.trim_start().starts_with('#') {
2032                assert!(
2033                    !line.contains("/opt/amont"),
2034                    "baking rewrote a comment: {line}"
2035                );
2036            }
2037        }
2038    }
2039
2040    /// Only an absolute path may be baked.
2041    ///
2042    /// A relative one is resolved by the shim against the WORKING TREE, so a
2043    /// repository shipping an executable by that name would be running it on
2044    /// the first commit after clone.
2045    #[test]
2046    fn only_an_absolute_path_is_bakeable() {
2047        for good in [
2048            "/opt/amont",
2049            "/home/u/.local/bin/amont",
2050            "C:/Users/u/amont.exe",
2051            "C:\\Users\\u\\amont.exe",
2052        ] {
2053            assert!(is_bakeable(good), "{good} should be bakeable");
2054        }
2055        for bad in [
2056            "",
2057            PLACEHOLDER,
2058            "amont",
2059            "./amont",
2060            "../amont",
2061            "target/debug/amont",
2062            "C:amont.exe",
2063        ] {
2064            assert!(!is_bakeable(bad), "{bad:?} must not be bakeable");
2065        }
2066    }
2067
2068    /// The shim must never hand the unsubstituted token to `[ -x ]`: that is a
2069    /// filesystem question asked in the repository's own directory.
2070    #[test]
2071    fn the_shim_never_tests_the_placeholder_as_a_path() {
2072        assert!(
2073            !SHIM.contains(&format!("[ -x \"{PLACEHOLDER}\" ]")),
2074            "the shim tests the raw token as a path"
2075        );
2076        assert!(
2077            SHIM.contains("case \"$BAKED\" in"),
2078            "the shim lost its absoluteness guard"
2079        );
2080    }
2081
2082    /// Refusing beats writing four hooks that cannot resolve their binary.
2083    #[test]
2084    fn write_shims_refuses_a_relative_binary_path() {
2085        let d = tmp("relative");
2086        let err = write_shims(&d, "target/debug/amont", false).expect_err("must refuse");
2087        assert!(err.to_string().contains("absolute"), "{err}");
2088        for name in DISPATCHERS {
2089            assert!(!d.join(name).exists(), "{name} was written anyway");
2090        }
2091        let _ = std::fs::remove_dir_all(&d);
2092    }
2093
2094    /// Every hook git invokes gets a file, and each is the baked shim.
2095    #[test]
2096    fn writing_shims_covers_every_dispatcher() {
2097        let d = tmp("write");
2098        let written = write_shims(&d, "/opt/amont", false).expect("write");
2099        assert_eq!(written.len(), DISPATCHERS.len());
2100        for name in DISPATCHERS {
2101            let got = std::fs::read_to_string(d.join(name)).expect("read");
2102            assert!(!got.contains(PLACEHOLDER), "{name} was written unbaked");
2103            assert!(got.contains("/opt/amont"), "{name} has no path");
2104        }
2105        let _ = std::fs::remove_dir_all(&d);
2106    }
2107
2108    /// The whole-repository posture, at the level of the function that owes it:
2109    /// ONE unwritable path and nothing at all is written. `bake_repo_hooks` has
2110    /// claimed this in a comment since it was written, over a loop that checked
2111    /// one file then wrote it, four times over — so a refusal on the third hook
2112    /// arrived after two were already gone.
2113    #[test]
2114    fn one_refusal_writes_nothing_at_all() {
2115        let d = tmp("all-or-nothing");
2116        // `prepare-commit-msg` sorts last among the dispatchers, so under the
2117        // old check-then-write loop the first three would already be on disk by
2118        // the time this one refused.
2119        let theirs = d.join("prepare-commit-msg");
2120        std::fs::write(&theirs, "#!/bin/sh\necho MINE\n").expect("write");
2121
2122        let err = write_shims(&d, "/opt/amont", false).expect_err("must refuse");
2123        assert!(
2124            matches!(err, ShimWriteError::Refused(ref rs) if rs.len() == 1),
2125            "{err}"
2126        );
2127        for name in ["commit-msg", "pre-commit", "pre-push"] {
2128            assert!(
2129                !d.join(name).exists(),
2130                "{name} was written despite a refusal elsewhere"
2131            );
2132        }
2133        assert_eq!(
2134            std::fs::read_to_string(&theirs).expect("read"),
2135            "#!/bin/sh\necho MINE\n"
2136        );
2137        let _ = std::fs::remove_dir_all(&d);
2138    }
2139
2140    /// A refusal has to say WHAT was in the way, not only that something was.
2141    /// The old predicate could not: it read the file as a string, so the one
2142    /// case worth naming — a compiled hook — came back as "not foreign" and was
2143    /// overwritten in silence.
2144    #[test]
2145    fn a_refusal_names_the_reason_for_each_hook() {
2146        let d = tmp("named");
2147        std::fs::write(d.join("commit-msg"), [0x7f, b'E', b'L', b'F', 0xff]).expect("write");
2148        std::fs::write(d.join("pre-commit"), "#!/bin/sh\necho mine\n").expect("write");
2149
2150        let err = write_shims(&d, "/opt/amont", false).expect_err("must refuse");
2151        let text = err.to_string();
2152        assert!(text.contains("not valid UTF-8"), "{text}");
2153        assert!(text.contains("commit-msg"), "{text}");
2154        assert!(text.contains("pre-commit"), "{text}");
2155
2156        // And `foreign_hooks` — which is what phrases the `--force` offer —
2157        // agrees about both.
2158        let foreign = foreign_hooks(&d);
2159        assert_eq!(foreign.len(), 2, "{foreign:?}");
2160        assert!(foreign
2161            .iter()
2162            .any(|(n, w)| *n == "commit-msg" && matches!(w, HookFile::Foreign(_))));
2163        let _ = std::fs::remove_dir_all(&d);
2164    }
2165
2166    /// `--force` says what it took, per file, with what it was. Without this
2167    /// the output was "baked 4 shims" — a receipt with the transaction left
2168    /// off, for the one operation whose purpose is to destroy something.
2169    #[test]
2170    fn force_reports_what_each_write_replaced() {
2171        let d = tmp("force-report");
2172        std::fs::write(d.join("commit-msg"), "#!/bin/sh\necho mine\n").expect("write");
2173        let written = write_shims(&d, "/opt/amont", true).expect("force must write");
2174        let replaced: Vec<_> = written
2175            .iter()
2176            .filter(|w| !matches!(w.replaced, HookFile::Absent))
2177            .collect();
2178        assert_eq!(replaced.len(), 1, "{written:?}");
2179        assert!(replaced[0].path.ends_with("commit-msg"));
2180        assert!(matches!(replaced[0].replaced, HookFile::Foreign(_)));
2181        let _ = std::fs::remove_dir_all(&d);
2182    }
2183
2184    /// Windows builds amont.exe, and a shim testing `[ -x .../amont ]` is
2185    /// false for it — so the installed name has to keep the suffix. Asserted
2186    /// against explicit paths, because a `cfg!(windows)` branch is vacuous on
2187    /// the platform this is usually run on.
2188    #[test]
2189    fn the_installed_name_keeps_the_platform_suffix() {
2190        assert_eq!(
2191            name_for(Path::new("/w/target/release/greengate.exe"), BIN),
2192            "greengate.exe"
2193        );
2194        assert_eq!(
2195            name_for(Path::new("/w/target/release/greengate.exe"), OLD_BIN),
2196            "amont.exe"
2197        );
2198        assert_eq!(
2199            name_for(Path::new("/u/target/release/greengate"), BIN),
2200            "greengate"
2201        );
2202        // A path that happens to contain a dot elsewhere is not an extension.
2203        assert_eq!(name_for(Path::new("/some.dir/greengate"), OLD_BIN), "amont");
2204    }
2205
2206    #[cfg(unix)]
2207    #[test]
2208    fn an_install_replaces_by_rename_and_writes_the_alias_as_a_copy() {
2209        use std::os::unix::fs::MetadataExt;
2210        struct Cleanup(PathBuf);
2211        impl Drop for Cleanup {
2212            fn drop(&mut self) {
2213                let _ = std::fs::remove_dir_all(&self.0); // a leftover temp dir is harmless
2214            }
2215        }
2216        let dir = std::env::temp_dir().join(format!("greengate-install-{}", std::process::id()));
2217        let _cleanup = Cleanup(dir.clone());
2218        std::fs::create_dir_all(&dir).unwrap();
2219        let src = dir.join("built");
2220        std::fs::write(&src, "new build").unwrap();
2221        let target = dir.join(BIN);
2222        std::fs::write(&target, "old build").unwrap();
2223        let before = std::fs::metadata(&target).unwrap().ino();
2224        // A stale temporary, a young one (another install, running now),
2225        // and an old alias from a 2.x install.
2226        let stale = dir.join(format!(".{BIN}.tmp.1"));
2227        std::fs::write(&stale, "x").unwrap();
2228        let aged = std::process::Command::new("touch")
2229            .args(["-t", "200001010000"])
2230            .arg(&stale)
2231            .status()
2232            .unwrap();
2233        assert!(aged.success(), "touch -t could not age the leftover");
2234        // The young one staged through the same copy an install makes, from
2235        // a source that is itself old (the running binary usually is).
2236        let old_source = dir.join("old-source");
2237        std::fs::write(&old_source, "y").unwrap();
2238        std::process::Command::new("touch")
2239            .args(["-t", "200001010000"])
2240            .arg(&old_source)
2241            .status()
2242            .unwrap();
2243        let young = dir.join(format!(".{BIN}.tmp.2"));
2244        stage_copy(&old_source, &young).unwrap();
2245        std::fs::write(dir.join(OLD_BIN), "2.x binary").unwrap();
2246
2247        sweep_install_leftovers(&dir);
2248        replace_atomically(&src, &target).unwrap();
2249        assert_eq!(write_aliases(&target).unwrap(), vec![OLD_BIN]);
2250
2251        assert_eq!(std::fs::read_to_string(&target).unwrap(), "new build");
2252        // A new inode: the old file was replaced by rename, never written in place.
2253        assert_ne!(std::fs::metadata(&target).unwrap().ino(), before);
2254        let alias = dir.join(OLD_BIN);
2255        assert_eq!(std::fs::read_to_string(&alias).unwrap(), "new build");
2256        assert!(!std::fs::symlink_metadata(&alias)
2257            .unwrap()
2258            .file_type()
2259            .is_symlink());
2260        assert_ne!(
2261            std::fs::metadata(&alias).unwrap().ino(),
2262            std::fs::metadata(&target).unwrap().ino(),
2263            "the alias is a copy, not a hard link"
2264        );
2265        assert!(!stale.exists(), "a stale leftover was not swept");
2266        assert!(
2267            young.exists(),
2268            "a young temporary, maybe another install's, was swept"
2269        );
2270        // No fleet binary beside it, so no fleet alias either.
2271        assert!(!dir.join(OLD_FLEET_BIN).exists());
2272        // A 2.x `amont install` copying onto its target replaces only the alias.
2273        std::fs::write(&alias, "2.3.1 overwrite").unwrap();
2274        assert_eq!(std::fs::read_to_string(&target).unwrap(), "new build");
2275    }
2276
2277    fn hook_bytes(dir: &Path) -> Vec<(String, Vec<u8>)> {
2278        let mut v: Vec<_> = std::fs::read_dir(dir)
2279            .expect("hooks dir")
2280            .filter_map(|e| e.ok())
2281            .map(|e| {
2282                (
2283                    e.file_name().to_string_lossy().into_owned(),
2284                    std::fs::read(e.path()).unwrap_or_default(),
2285                )
2286            })
2287            .collect();
2288        v.sort();
2289        v
2290    }
2291
2292    /// A snapshot probe that cannot answer is NOT "not a snapshot": that
2293    /// answer is the one that bakes, and baking from a snapshot is the bug.
2294    /// The shims sit at sentinel A and the binary offered is B, so a re-bake
2295    /// would show — and the control at the end proves it does show.
2296    #[test]
2297    fn init_fails_closed_when_the_snapshot_probe_cannot_answer() {
2298        let d = tmp("probe-err");
2299        git(&d, &["init", "-q", "--template=", "."]);
2300        let hooks = d.join(".git").join("hooks");
2301        std::fs::create_dir_all(&hooks).expect("mkdir");
2302        write_shims(&hooks, "/sentinel/A/amont", false).expect("seed");
2303        let before = hook_bytes(&hooks);
2304        let b = || Ok(PathBuf::from("/sentinel/B/amont"));
2305
2306        let got = init_with(b(), &d, &|_| Err(std::io::Error::other("probe broke")));
2307        let why = got.expect_err("a probe that cannot answer must fail init");
2308        assert!(why.contains("cannot tell"), "{why}");
2309        assert_eq!(before, hook_bytes(&hooks), "init wrote on doubt");
2310
2311        init_with(b(), &d, &|_| Ok(false)).expect("not a snapshot: bakes");
2312        assert_ne!(before, hook_bytes(&hooks), "the control could not fail");
2313        let _ = std::fs::remove_dir_all(&d);
2314    }
2315}