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 = "__GREENGATE_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. `$GREENGATE_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 `$GREENGATE_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/// `$GREENGATE_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/// `$GREENGATE_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 `$GREENGATE_BIN_DIR`.
250pub fn bin_dir() -> PathBuf {
251    if let Some(d) = std::env::var_os("GREENGATE_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 `greengate.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", "greengate.conventions", word]) {
616                return Err(
617                    "could not write greengate.conventions to the global git config".into(),
618                );
619            }
620            eprintln!(
621                "{} greengate.conventions = {} (global)",
622                valid_sign(),
623                highlight(word)
624            );
625            if word == "declared" {
626                eprintln!("    House rules run only in repositories that commit a greengate.conf;");
627                eprintln!("    the safety net (conflicts, secrets, size, debug leftovers) runs");
628                eprintln!("    everywhere.");
629            }
630        }
631        None => {
632            eprintln!(
633                "{} conventions currently apply everywhere. On a machine that also",
634                warning_sign()
635            );
636            eprintln!("    clones other people's projects, consider:");
637            eprintln!(
638                "        {}",
639                highlight(concat!(crate::bin!(), " enroll --conventions declared"))
640            );
641        }
642    }
643
644    eprintln!();
645    eprintln!("Enrolled. Every future `git clone` and `git init` gets the hooks.");
646    eprintln!("Repositories cloned before now are untouched — wire them with");
647    eprintln!(
648        "    {}   (one repository)",
649        highlight(concat!(crate::bin!(), " init"))
650    );
651    eprintln!(
652        "    {}   (every repository under a root)",
653        highlight(concat!(crate::fleet_bin!(), " install --root <dir>"))
654    );
655    eprintln!(
656        "Undo with {}.",
657        highlight("git config --global --unset init.templateDir")
658    );
659    Ok(())
660}
661
662/// Point `init.templateDir` at `templates` — or refuse, loudly, when it
663/// already points somewhere else. Overwriting it would silently disable
664/// whatever the user's OTHER template dir was installing, which is the exact
665/// shape of failure the husky refusal exists to prevent, one level up.
666fn point_template_dir_at(templates: &std::path::Path) -> Result<(), String> {
667    let want = templates.to_string_lossy().into_owned();
668    let current = crate::git::stdout(&["config", "--global", "--get", "init.templateDir"])
669        .filter(|s| !s.is_empty());
670    match current {
671        None => {
672            if !crate::git::succeeds(&["config", "--global", "init.templateDir", &want]) {
673                return Err("could not write init.templateDir to the global git config".into());
674            }
675            eprintln!(
676                "{} init.templateDir = {} (global)",
677                valid_sign(),
678                highlight(&want)
679            );
680            Ok(())
681        }
682        Some(existing) if same_dir(&existing, &want) => {
683            eprintln!(
684                "{} init.templateDir already points here ({})",
685                valid_sign(),
686                highlight(&existing)
687            );
688            Ok(())
689        }
690        Some(existing) => Err(format!(
691            "init.templateDir is already set to {existing} — something else installs
692             hooks on this machine. Overwriting it would silently disable that.
693             Decide which one wins, then either unset it
694             (git config --global --unset init.templateDir) and re-run
695             `{BIN} enroll`, or leave enrollment to it."
696        )),
697    }
698}
699
700/// The same directory, spelled two ways: canonicalize both when possible so
701/// a symlinked config dir still counts as "already ours".
702fn same_dir(a: &str, b: &str) -> bool {
703    if a == b {
704        return true;
705    }
706    match (
707        std::path::Path::new(a).canonicalize(),
708        std::path::Path::new(b).canonicalize(),
709    ) {
710        (Ok(x), Ok(y)) => x == y,
711        _ => false,
712    }
713}
714
715/// `amont init` — wire up THIS repository, and touch nothing else.
716///
717/// The verb a package manager can call. `"prepare": "amont init"` in a
718/// `package.json` means a teammate who clones and runs `npm install` gets the
719/// hooks, which is the ergonomic husky has and this project did not.
720///
721/// ## Why `install` could not be that verb
722///
723/// Every one of its three extra steps is wrong for something that runs on every
724/// teammate's install, and the third is a hang:
725///
726///   * `install_binary` copies into `~/.local/bin` — a machine-level write from
727///     `npm install`;
728///   * `populate_template_dir` writes `~/.config/git/git-templates`, so a
729///     package manager would be arranging for every FUTURE clone to get hooks;
730///   * `offer_trust` calls `trust::confirm`, which opens `/dev/tty`. In a
731///     terminal that succeeds and BLOCKS, so `npm install` would stop dead on a
732///     prompt about a manifest the user has not read.
733///
734/// So this does one thing: bake four shims into the repository's own hooks
735/// directory.
736///
737/// ## What it bakes, and why not the PATH hit
738///
739/// `current_exe()`, always — never [`install_binary`]'s "is it already on
740/// `PATH`?" branch. Under npm the answer to that question is
741/// `node_modules/.bin/amont`, which is the **JS wrapper**: baking it would put a
742/// node process in front of every single commit, on a tool whose start-up cost
743/// is a stated feature. `current_exe()` is the native binary inside the platform
744/// package, which is what should run.
745///
746/// ## Silence, and its limits
747///
748/// Outside a git repository this reports nothing and exits 0. `npm install`
749/// legitimately runs where there is no `.git` — from a tarball, inside a Docker
750/// build, in CI — and failing there would make the package uninstallable in all
751/// three. It stays LOUD about everything else: a redirect, an unwritable
752/// directory, a foreign hook, and a repository git REFUSES to answer about
753/// (dubious ownership in a container bind mount, an unreadable `.git/config`)
754/// all still fail, because those are repositories where somebody believes they
755/// have hooks and does not. The silence is git's verdict, never git's absence.
756///
757/// ## Inside a push snapshot, it stands down
758///
759/// A push snapshot is a linked worktree, so it SHARES this repository's hooks
760/// directory — and its dependency install runs `prepare`, which runs this.
761/// Baking there pointed every hook at a binary inside a temp directory that
762/// is deleted minutes later. The snapshot marks itself in its own git admin
763/// dir ([`crate::pushed_tree::in_push_snapshot`]); when the mark is there,
764/// nothing is written. When it cannot be TOLD whether the mark is there, it
765/// fails rather than guess: a wrong guess is exactly the bake this prevents.
766pub fn init() -> Result<(), String> {
767    init_with(
768        std::env::current_exe(),
769        Path::new("."),
770        &crate::pushed_tree::in_push_snapshot,
771    )
772}
773
774/// [`init`] with what it would otherwise read from the process — the binary
775/// to bake, the directory to ask about, and the snapshot probe — passed in,
776/// so a test can reach every branch without `set_current_dir`.
777fn init_with(
778    me: std::io::Result<PathBuf>,
779    dir: &Path,
780    in_snapshot: &dyn Fn(&Path) -> std::io::Result<bool>,
781) -> Result<(), String> {
782    let rh = repo_hooks_in(dir);
783    // The one silent exit, and the only one: git itself said this is not a
784    // repository.
785    if matches!(rh, RepoHooks::Nowhere) {
786        return Ok(());
787    }
788    // BEFORE the redirect and `Unanswerable` arms: a snapshot's install must
789    // never fail `prepare` over hook config it is not going to touch anyway.
790    match in_snapshot(dir) {
791        Ok(true) => {
792            eprintln!(
793                "{BIN} init: inside a {BIN} push snapshot — the repository's hooks are left as they are"
794            );
795            return Ok(());
796        }
797        Ok(false) => {}
798        // git would not answer either question: its own reason, below, says
799        // more than ours would. Still a failure — nothing is written.
800        Err(_) if matches!(rh, RepoHooks::Unanswerable { .. }) => {}
801        Err(e) => {
802            return Err(format!(
803                "{} cannot tell whether this is a {BIN} push snapshot — {e}\n    \
804                 Hooks were NOT installed.",
805                error_sign()
806            ))
807        }
808    }
809    let hooks = match rh {
810        RepoHooks::Own(dir) => dir,
811        RepoHooks::Redirected { to, own } if redirect_is_hostile(&to, &own) => {
812            return Err(redirected_message(&to, &own))
813        }
814        RepoHooks::Redirected { to, .. } => to,
815        RepoHooks::Nowhere => return Ok(()),
816        RepoHooks::Unanswerable { why } => {
817            return Err(format!(
818                "{} git would not say where this repository's hooks live —\n    {}\n    \
819                 Hooks were NOT installed.",
820                error_sign(),
821                crate::ui::sanitize(&why)
822            ))
823        }
824    };
825
826    let me = me.map_err(|e| format!("cannot locate the running binary: {e}"))?;
827    // `absolute` rather than `canonicalize`: the shim needs an absolute path
828    // and nothing more, so there is no reason to touch the filesystem again.
829    //
830    // It does NOT keep us off pnpm's `.pnpm/<pkg>@<version>/…` store path, and
831    // an earlier version of this comment claimed it did. By the time this runs,
832    // the JS wrapper has already resolved the binary through `require.resolve`,
833    // which returns the REAL path — and `current_exe()` resolves symlinks
834    // besides. A pnpm install bakes the versioned store path, verified.
835    //
836    // Which is fine, and worth saying why rather than leaving the next reader
837    // to worry about it: `prepare` runs on every install, so a version bump
838    // re-bakes before anything can dispatch against the old path — and if one
839    // ever does go missing, the shim's resolution order falls through to
840    // `~/.local/bin` and then `PATH`, and fails LOUDLY rather than skipping a
841    // check, which is the property that actually matters.
842    let binary = absolute(&me);
843    let binary = binary.to_string_lossy().into_owned();
844    if !is_bakeable(&binary) {
845        return Err(format!(
846            "{} cannot bake {binary:?} — the shim takes an absolute path only",
847            error_sign()
848        ));
849    }
850
851    std::fs::create_dir_all(&hooks)
852        .map_err(|e| format!("cannot create {}: {e}", hooks.display()))?;
853
854    // `force: false`. A hook somebody else wrote is theirs, and `init` runs
855    // unattended — there is no one at the keyboard to have decided otherwise.
856    let written = write_shims(&hooks, &binary, false)
857        .map_err(|e| format!("cannot write shims to {}: {e}", hooks.display()))?;
858    eprintln!(
859        "{} {BIN}: {} hooks in {}",
860        valid_sign(),
861        written.len(),
862        hooks.display()
863    );
864    Ok(())
865}
866
867/// Name the commit-style settings, once, at the moment somebody acquires them.
868///
869/// A PRINT, never a prompt. `install` has to remain answerable by nobody: it
870/// runs under `amont-fleet install --root`, in provisioning scripts, and not
871/// at all for the `init.templateDir` users whose hooks arrive with a clone. A
872/// third question would break all three; a line of output breaks none of them,
873/// and it puts the dial in front of the one person guaranteed to be reading.
874fn point_at_setup(settings: &crate::config::Settings) {
875    let s = crate::commit_style::Style::resolve(settings);
876    eprintln!(
877        "  commit style: gitmoji {}, subject ≤{}, description ≤{} — `{BIN} setup` to change",
878        s.gitmoji.as_str(),
879        s.subject_max,
880        s.description_max
881    );
882}
883
884/// Ask about the manifest, once, at the moment somebody is already deciding
885/// about this repository.
886///
887/// `direnv` has to ask lazily on `cd` because it has no install step to hang
888/// the question from. We have one — so this is a single question, shown with
889/// the declarations in view, and declining still leaves the built-ins working.
890///
891/// Never blocks and never fails the install: a repository that declares nothing
892/// says nothing, and a non-interactive install simply reports the state.
893fn offer_trust() {
894    // No repository, no manifest to ask about. `repo_root()` answered "." and
895    // this went looking for `./amont.conf` in whatever directory the
896    // install was run from — a file it would then have offered to trust ON
897    // BEHALF of a repository that does not exist.
898    let Ok(root) = crate::hooks::common::repo_root_checked() else {
899        return;
900    };
901    let root = Path::new(&root);
902    let state = crate::trust::state(root);
903    if matches!(
904        state,
905        crate::trust::State::NoManifest | crate::trust::State::Trusted
906    ) {
907        return;
908    }
909
910    eprintln!();
911    eprintln!(
912        "{} {} declares checks and policy that would apply to your commits:",
913        warning_sign(),
914        crate::manifest::manifest_name(root)
915    );
916    // Read ONCE, then show and fingerprint that same buffer. `confirm()` blocks
917    // on a keypress, sometimes for several seconds, and a file rewritten in
918    // that window must not be trusted under the guise of the content that was
919    // displayed — `record_verified` re-checks this fingerprint once the answer
920    // is in. Reading separately to show and to hash would leave the same gap
921    // one step earlier: the listing approved need not be the one recorded.
922    let manifest_file = crate::manifest::manifest_name(root);
923    let manifest = root.join(manifest_file);
924    let Ok(source) = std::fs::read(&manifest) else {
925        eprintln!("{} could not read {manifest_file}", warning_sign());
926        return;
927    };
928    eprint!(
929        "{}",
930        crate::trust::describe_source(&String::from_utf8_lossy(&source))
931    );
932    let Some(fp) = crate::trust::fingerprint_bytes(root, &source) else {
933        eprintln!("{} could not hash {manifest_file}", warning_sign());
934        return;
935    };
936    if crate::trust::confirm("    Trust them? (y/N) ") {
937        match crate::trust::record_verified(root, &fp) {
938            Ok(()) => eprintln!("{} trusted ({fp})", valid_sign()),
939            Err(e) => eprintln!("{} {e}", warning_sign()),
940        }
941    } else {
942        eprintln!("    Left untrusted. The built-ins still run; these do not.");
943        eprintln!("    Change your mind with `{BIN} trust`.");
944    }
945}
946
947/// Ask about `AGENTS.md`, once, right where `offer_trust` asks about the
948/// manifest — same reasoning, same shape: a single question with an install
949/// step to hang it from, and declining changes nothing about how the hooks
950/// themselves run.
951///
952/// This is the first thing `install` would write to TRACKED repo content —
953/// everything else here lives in `.git/hooks` (never tracked) or a
954/// machine-local path (`~/.local/bin`, the XDG template dir). That is exactly
955/// why it is a confirm, not a silent write: `crate::agents_md::write` is
956/// marker-scoped and safe to re-run, but "safe to overwrite" is not the same
957/// promise as "yours to write unasked."
958///
959/// Never blocks and never fails the install: skips silently when there is
960/// nothing to offer, and a non-interactive install simply leaves the
961/// question unanswered — `trust::confirm` already treats no tty as "no".
962fn offer_agents_md(settings: &crate::config::Settings) {
963    // Same reason as `offer_trust`: with `repo_root()`'s "." fallback, an
964    // install run outside a repository offered to write an AGENTS.md into the
965    // current directory — the one thing `install` writes to TRACKED content,
966    // aimed at a directory nobody said was a project.
967    let Ok(root) = crate::hooks::common::repo_root_checked() else {
968        return;
969    };
970    let path = Path::new(&root).join("AGENTS.md");
971    match crate::agents_md::check(settings, &path) {
972        Ok(crate::agents_md::CheckResult::MatchesGenerated) => return,
973        Ok(_) => {}
974        // Malformed markers: nothing this prompt can safely offer to fix.
975        Err(_) => return,
976    }
977
978    eprintln!();
979    eprintln!(
980        "{} AGENTS.md can point coding agents at `greengate list --json` \
981         instead of leaving them to discover these checks the hard way:",
982        warning_sign()
983    );
984    if crate::trust::confirm("    Add it? (y/N) ") {
985        match crate::agents_md::write(settings, &path) {
986            Ok(()) => eprintln!("{} wrote {}", valid_sign(), path.display()),
987            Err(e) => eprintln!("{} {e}", warning_sign()),
988        }
989    } else {
990        eprintln!("    Left as-is. Change your mind with `{BIN} agents-md`.");
991    }
992}
993
994/// Where this binary can already be found on `PATH`, if it can.
995///
996/// Returns the path as `PATH` exposes it — deliberately NOT the resolved one.
997/// Homebrew's `/usr/local/bin/amont` is a symlink into
998/// `/usr/local/Cellar/amont/<version>/bin/`, and that Cellar path is
999/// version-specific and removed on upgrade. Baking it would pin every repo to a
1000/// version that is about to be deleted, which is worse than the copy this
1001/// function exists to avoid. The same is true of any versioned store — nix,
1002/// asdf, mise.
1003///
1004/// So the comparison is canonical (to recognise ourselves through the symlink)
1005/// while the value returned is the entry that led here. That also makes the
1006/// answer correct whichever way `current_exe()` behaves: it resolves symlinks
1007/// on some platforms and libcs and not others, and this never has to care.
1008fn on_path_already(me: &Path) -> Option<PathBuf> {
1009    let me_real = me.canonicalize().ok()?;
1010    let name = installed_name();
1011    let path = std::env::var_os("PATH")?;
1012    std::env::split_paths(&path)
1013        .map(|dir| dir.join(&name))
1014        .filter(|cand| !in_a_build_dir(cand))
1015        .find(|cand| cand.canonicalize().is_ok_and(|real| real == me_real))
1016        .map(|cand| absolute(&cand))
1017        .filter(|abs| is_bakeable(&abs.to_string_lossy()))
1018}
1019
1020/// Whether `p` sits inside a cargo build directory.
1021///
1022/// "On PATH" alone is not the question — the question is whether the path will
1023/// still be there tomorrow, and a build directory is precisely the one that
1024/// will not. `cargo clean`, or any rebuild, and the shims baked against it
1025/// resolve nothing.
1026///
1027/// This is not hypothetical and it is not only about `cargo run`: **cargo
1028/// prepends the build directory to PATH when it runs tests on Windows**, so
1029/// `target/debug` genuinely appears there. That took out four existing install
1030/// tests on the Windows runner and nowhere else, which is a fair description of
1031/// how the loose predicate would have failed a user, too.
1032///
1033/// `CACHEDIR.TAG` is cargo's own marker for the directory, written since 1.55
1034/// and standardised for exactly this — "a program wrote this, do not treat it
1035/// as durable". Asking for it beats matching on the name `target`, which is
1036/// configurable and is also an ordinary word for a directory. Bounded to a few
1037/// levels so a stray tag high up somebody's home directory cannot disqualify
1038/// every path on the system.
1039fn in_a_build_dir(p: &Path) -> bool {
1040    p.ancestors()
1041        .skip(1)
1042        .take(4)
1043        .any(|dir| dir.join("CACHEDIR.TAG").is_file())
1044}
1045
1046/// Copy the running binary to a stable location, and return where it now lives.
1047fn install_binary() -> Result<String, String> {
1048    let me =
1049        std::env::current_exe().map_err(|e| format!("cannot locate the running binary: {e}"))?;
1050
1051    // A binary a package manager already put on PATH is not ours to copy.
1052    //
1053    // The copy below exists for `./target/release/amont install`, where the
1054    // binary sits in a directory `cargo clean` will delete — baking that path
1055    // would install hooks that stop resolving the next time somebody builds.
1056    // For `brew install`, `cargo install` or a distro package, the opposite is
1057    // true: the binary is already somewhere stable, and copying it produces a
1058    // SECOND, unmanaged copy that the package manager will never update again.
1059    //
1060    // That is not hypothetical. It is what this machine was in: `brew upgrade`
1061    // would have refreshed /usr/local/bin while every repo stayed baked to a
1062    // frozen copy in ~/.local/bin — the same staleness the copy is meant to
1063    // prevent, arrived at from the other direction.
1064    //
1065    // `$GREENGATE_BIN_DIR` is checked first because setting it IS the request to
1066    // put the binary somewhere specific, and honouring it costs nothing.
1067    if std::env::var_os("GREENGATE_BIN_DIR").is_none() {
1068        if let Some(stable) = on_path_already(&me) {
1069            let shown = stable.to_string_lossy().into_owned();
1070            eprintln!("{} using {}", valid_sign(), highlight(&shown));
1071            eprintln!("    already on PATH, so nothing was copied — an upgrade there");
1072            eprintln!("    reaches every repository without reinstalling.");
1073            return Ok(shown);
1074        }
1075    }
1076
1077    let dir = bin_dir();
1078    std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
1079
1080    // Absolute from here on: this path is what gets baked into every shim, and
1081    // `bin_dir()` honours `$GREENGATE_BIN_DIR`, which may be relative.
1082    let target = absolute(&dir.join(installed_name()));
1083    // Copying a running binary over ITSELF fails on some platforms and is
1084    // pointless on all of them.
1085    //
1086    // `me.canonicalize().ok() == target.canonicalize().ok()` is the version
1087    // this replaces, and it was wrong in the one case that matters: when the
1088    // TARGET does not exist yet — a first install, the whole point of the
1089    // step — `canonicalize` returns `Err`, both sides are `None`, `None ==
1090    // None` is true, and the copy was skipped. The binary was never installed,
1091    // and `install` printed "installed <path>" for a file that was not there.
1092    // Every shim then baked that path and resolved nothing. Two `Ok`s that
1093    // agree is the only thing that means "same file".
1094    let already_there = matches!(
1095        (me.canonicalize(), target.canonicalize()),
1096        (Ok(a), Ok(b)) if a == b
1097    );
1098    sweep_install_leftovers(&dir);
1099    if !already_there {
1100        replace_atomically(&me, &target)
1101            .map_err(|e| format!("cannot install to {}: {e}", target.display()))?;
1102    }
1103    let aliases = write_aliases(&target)?;
1104    let installed = target.to_string_lossy().into_owned();
1105    eprintln!("{} installed {}", valid_sign(), highlight(&installed));
1106    if !aliases.is_empty() {
1107        eprintln!(
1108            "    also as {}: hooks baked to the old name keep working",
1109            aliases.join(" and ")
1110        );
1111    }
1112    Ok(installed)
1113}
1114
1115/// Write the shims into the template directory — unless doing so would delete
1116/// somebody's source.
1117///
1118/// REFUSING is not an error: on a machine where the template dir is the
1119/// checkout, there is nothing to install and the install has succeeded. FAILING
1120/// to write one it was allowed to write is, though — reporting success after a
1121/// step did not happen is the thing this whole codebase is arranged against.
1122fn populate_template_dir(binary: &str, force: bool) -> Result<(), String> {
1123    let dir = template_hooks_dir();
1124    let _ = std::fs::create_dir_all(&dir);
1125    // Report the RESOLVED path. "It is the checkout" is only useful with the
1126    // checkout named, and the configured path is usually the symlink that hides
1127    // exactly that.
1128    let shown = dir.canonicalize().unwrap_or_else(|_| dir.clone());
1129    let shown = shown.display();
1130
1131    match classify_dir(&dir) {
1132        TemplateDir::IsCheckout => {
1133            eprintln!(
1134                "{} template dir IS the checkout ({shown}) — nothing to install.",
1135                warning_sign()
1136            );
1137            eprintln!("    Its shims keep the placeholder deliberately and resolve");
1138            eprintln!("    {binary} at run time. This is the intended setup.");
1139            // …as long as run-time resolution can actually reach the binary,
1140            // which the sentence above used to assert unconditionally.
1141            warn_if_unbaked_cannot_resolve(binary);
1142        }
1143        TemplateDir::InsideCheckout => {
1144            eprintln!(
1145                "{} {shown} is inside a git checkout — leaving it alone.",
1146                warning_sign()
1147            );
1148            warn_if_unbaked_cannot_resolve(binary);
1149        }
1150        TemplateDir::NoGit => eprintln!(
1151            "{} git is not on PATH — refusing to delete anything.",
1152            warning_sign()
1153        ),
1154        TemplateDir::Unresolvable => {
1155            eprintln!("{} cannot resolve {shown} — skipping.", warning_sign())
1156        }
1157        TemplateDir::Safe => {
1158            let written = write_shims(&dir, binary, force)
1159                .map_err(|e| format!("cannot write shims to {shown}: {e}"))?;
1160            eprintln!("{} wrote {} shims to {shown}", valid_sign(), written.len());
1161            report_overwrites(&written);
1162        }
1163    }
1164    Ok(())
1165}
1166
1167/// Say what each write took, for the writes that took something.
1168///
1169/// `install --force` used to print `baked 4 shims` and stop. `--force` is
1170/// typed precisely because a file is in the way, so the one fact the output
1171/// omitted is the only fact the user needed: which files, and what they were.
1172/// A hook replaced with no record of what it was is unrecoverable — `.git` is
1173/// not tracked, so there is nothing to `git checkout` it back from.
1174fn report_overwrites(written: &[Written]) {
1175    for w in written {
1176        if matches!(w.replaced, HookFile::Absent | HookFile::Ours) {
1177            continue;
1178        }
1179        eprintln!(
1180            "{} overwrote {} — it was {}",
1181            warning_sign(),
1182            w.path.display(),
1183            w.replaced.describe()
1184        );
1185    }
1186}
1187
1188/// Where git dispatches hooks from, and whether that is this repository's OWN
1189/// hooks directory or somewhere `core.hooksPath` sent it.
1190///
1191/// This replaces a bare `repo_hooks_dir()` that returned only the dispatch path.
1192/// `--git-path hooks` is still the right question — never `--git-dir` plus
1193/// `join("hooks")`, because hooks are explicitly SHARED across worktrees while a
1194/// linked worktree's `--git-dir` is its own PRIVATE gitdir, so joining "hooks"
1195/// onto it names a directory git never dispatches from. The addition is asking
1196/// `--git-common-dir` alongside it, so the answer can be compared against the
1197/// directory that would be ours.
1198///
1199/// The distinction did not exist and its absence was silent. `--git-path hooks`
1200/// honours `core.hooksPath`, so in a repository running husky it answers
1201/// `.husky/_` — inside the repo, plausible, and wrong. `install` wrote four
1202/// shims there, husky's own `prepare` regenerated the directory on the next
1203/// `npm install`, and the repository went back to having no checks with nothing
1204/// to show for it. Every guarantee this tool makes was off in those repositories
1205/// and the fleet reported them as merely "drifted".
1206#[derive(Debug, Clone, PartialEq, Eq)]
1207pub enum RepoHooks {
1208    /// `<git-common-dir>/hooks`. Git dispatches from here and it is ours to write.
1209    Own(PathBuf),
1210    /// `core.hooksPath` points somewhere else. Another tool owns dispatch here,
1211    /// and writing to `own` would install shims git never runs.
1212    Redirected { to: PathBuf, own: PathBuf },
1213    /// Not in a repository — git itself said "not a git repository".
1214    Nowhere,
1215    /// git failed for any OTHER reason: dubious ownership, an unreadable
1216    /// `.git/config`, a corrupt gitfile. There is plausibly a repository here;
1217    /// git would not talk about it. Split from [`RepoHooks::Nowhere`] because
1218    /// the two demand opposite behaviour from `init` — outside a repository,
1219    /// silence is correct; a repository git refuses to answer about is one
1220    /// where somebody believes they are getting hooks and is not, which is the
1221    /// failure this whole tool is arranged against.
1222    Unanswerable { why: String },
1223}
1224
1225/// Ask git both questions at once — what it dispatches from, and what this
1226/// repository's own hooks directory is — then compare.
1227///
1228/// Lexical comparison via [`crate::hookfile::resolve_lexical`], not
1229/// `canonicalize`: neither directory is guaranteed to exist yet (a fresh clone
1230/// has no `.git/hooks` until something writes one), and `canonicalize` cannot be
1231/// asked about a path that does not. Same reason `is_within` is lexical.
1232pub fn repo_hooks() -> RepoHooks {
1233    repo_hooks_in(Path::new("."))
1234}
1235
1236/// [`repo_hooks`] for the repository at `dir`, so a test can aim it at a
1237/// fixture without moving the process.
1238pub fn repo_hooks_in(dir: &Path) -> RepoHooks {
1239    // `git::output`, not `git::stdout`: the latter collapses every non-zero
1240    // exit to `None` with stderr discarded, which folded "not in a repository"
1241    // (silence is right) and "git refused to answer" (silence hid a container
1242    // checkout getting no hooks from `prepare`, with exit 0) into one arm.
1243    let Some(out) = crate::git::output_in(
1244        dir,
1245        &[
1246            "rev-parse",
1247            "--path-format=absolute",
1248            "--git-path",
1249            "hooks",
1250            "--git-common-dir",
1251        ],
1252    ) else {
1253        return RepoHooks::Unanswerable {
1254            why: "could not run git".to_string(),
1255        };
1256    };
1257    if out.code != 0 {
1258        // git's own verdict draws the line — the same phrase
1259        // `amont-fleet::scan::hooks_dir_for` keys on.
1260        if out.stderr.contains("not a git repository") {
1261            return RepoHooks::Nowhere;
1262        }
1263        let why = out
1264            .stderr
1265            .lines()
1266            .find(|l| l.starts_with("fatal:"))
1267            .or_else(|| out.stderr.lines().find(|l| !l.trim().is_empty()))
1268            .unwrap_or("git gave no reason")
1269            .to_string();
1270        return RepoHooks::Unanswerable { why };
1271    }
1272    let mut lines = out.stdout.lines();
1273    let (Some(dispatched), Some(common)) = (lines.next(), lines.next()) else {
1274        return RepoHooks::Nowhere;
1275    };
1276    let dispatched = PathBuf::from(dispatched);
1277    let own = PathBuf::from(common).join("hooks");
1278    if crate::hookfile::resolve_lexical(&dispatched) == crate::hookfile::resolve_lexical(&own) {
1279        RepoHooks::Own(own)
1280    } else {
1281        RepoHooks::Redirected {
1282            to: dispatched,
1283            own,
1284        }
1285    }
1286}
1287
1288/// Name the tool behind a `core.hooksPath`, when the path gives it away.
1289///
1290/// A short list on purpose. It is half of [`redirect_is_hostile`]'s evidence,
1291/// not a general classifier, and a name guessed wrong is worse than none.
1292pub fn redirect_culprit(to: &Path) -> Option<&'static str> {
1293    let s = to.to_string_lossy().replace('\\', "/");
1294    if s.contains("/.husky") {
1295        return Some("husky");
1296    }
1297    if s.contains("/.lefthook") || s.contains("lefthook") {
1298        return Some("lefthook");
1299    }
1300    None
1301}
1302
1303/// Whether any of our four shims sits in `dir`.
1304///
1305/// The runtime's own copy of the question `amont-fleet::scan::is_managed`
1306/// answers, because the guard that needs it runs in the commit-path crate and
1307/// cannot depend on the dashboard.
1308pub fn holds_our_shims(dir: &Path) -> bool {
1309    DISPATCHERS
1310        .iter()
1311        .any(|name| matches!(hookfile::classify(&dir.join(name)), HookFile::Ours))
1312}
1313
1314/// Whether a redirect must be REFUSED rather than followed.
1315///
1316/// Not every `core.hooksPath` is a problem, and the first cut of this refused
1317/// them all — which would have broken a repository that deliberately keeps its
1318/// hooks in `tooling/hooks` under version control. That is a setup this project
1319/// has always honoured and `plan_finds_shims_at_a_redirected_hooks_path` pins.
1320///
1321/// So the refusal rests on evidence, not on the mere presence of the setting.
1322/// Either is enough:
1323///
1324///   * **the destination belongs to a hook manager we recognise** — husky and
1325///     lefthook both REGENERATE their directory on install, so anything we wrote
1326///     there is gone by the next `npm install` and the repository silently stops
1327///     being checked;
1328///   * **our shims sit in the repository's own hooks directory and NOT at the
1329///     destination** — amont was installed here and something later took
1330///     dispatch away. Whatever the destination is, this repository is not
1331///     running the checks it believes it is, and that is worth stopping for
1332///     whether or not we can name the culprit.
1333///
1334/// The second signal needs both halves. A repository whose shims sit at the
1335/// destination too moved its hooks there deliberately — amont IS running, from
1336/// the directory the repository chose — and whatever lingers in
1337/// `<git-common-dir>/hooks` is leftovers from before the move, not evidence of
1338/// a takeover. Refusing on the leftovers alone locked such a repository out of
1339/// `install` (and of `amont init` from npm's `prepare`, failing every
1340/// `npm install`) with a remedy that would have broken the deliberate setup.
1341///
1342/// A repository with neither signal keeps the old behaviour exactly.
1343pub fn redirect_is_hostile(to: &Path, own: &Path) -> bool {
1344    redirect_culprit(to).is_some() || (holds_our_shims(own) && !holds_our_shims(to))
1345}
1346
1347/// The refusal both `install` and `init` give when another tool owns dispatch.
1348///
1349/// One function, so the two cannot drift into saying different things about the
1350/// same situation — and so the remedy is spelled exactly once.
1351pub fn redirected_message(to: &Path, own: &Path) -> String {
1352    let mut msg = format!(
1353        "{} git dispatches hooks from {}, not {}",
1354        error_sign(),
1355        highlight(&to.display().to_string()),
1356        own.display()
1357    );
1358    match redirect_culprit(to) {
1359        Some(tool) => msg.push_str(&format!(
1360            "\n    `core.hooksPath` is set, so {tool} owns the hooks here. Shims\n    \
1361             written to either directory would be overwritten or never run."
1362        )),
1363        None => msg.push_str(
1364            "\n    `core.hooksPath` is set, so another tool owns the hooks here.\n    \
1365             Shims written to either directory would be overwritten or never run.",
1366        ),
1367    }
1368    msg.push_str(&format!(
1369        "\n    Hand dispatch back first: {}",
1370        highlight("git config --unset core.hooksPath")
1371    ));
1372    // Stranded shims are the evidence when no culprit is named — say how to
1373    // clear them, because "unset core.hooksPath" is the WRONG remedy for a
1374    // repository whose redirect is deliberate and merely predates a cleanup.
1375    if redirect_culprit(to).is_none() && holds_our_shims(own) {
1376        msg.push_str(&format!(
1377            "\n    Or, if the redirect is deliberate, clear our stale shims from {}\n    \
1378             first: {}",
1379            own.display(),
1380            highlight(concat!(crate::bin!(), " uninstall"))
1381        ));
1382    }
1383    msg
1384}
1385
1386/// Bake the shims into the repository we are standing in, if we are in one.
1387///
1388/// The tracked guard is inherited from `hookfile::guard_write` rather than
1389/// written here, and that inheritance closes a verified bug: with
1390/// `.git/hooks/pre-commit` a symlink to a TRACKED `devhooks/pre-commit`,
1391/// `install --force` rewrote the tracked source file. Every guard this function
1392/// had was about the LINK path — untracked, inside `.git`, unremarkable — while
1393/// `fs::write` followed the link and landed in the working tree. Both halves
1394/// are fixed at once: the symlink is refused by name, and `--force` replaces
1395/// the link by rename instead of writing through it.
1396fn bake_repo_hooks(binary: &str, force: bool) -> Result<(), String> {
1397    let hooks = match repo_hooks() {
1398        RepoHooks::Own(dir) => dir,
1399        // A hostile redirect is refused, and `--force` does not move it.
1400        // `--force` means "that file is mine to replace"; it has never meant
1401        // "write where git does not look". Writing `own` would leave four shims
1402        // git never dispatches, and writing `to` would hand our files to the
1403        // tool that regenerates that directory.
1404        //
1405        // A redirect that is merely a redirect is followed, as it always was —
1406        // see `redirect_is_hostile` for where the line is.
1407        RepoHooks::Redirected { to, own } if redirect_is_hostile(&to, &own) => {
1408            return Err(redirected_message(&to, &own))
1409        }
1410        RepoHooks::Redirected { to, .. } => to,
1411        RepoHooks::Nowhere => {
1412            eprintln!(
1413                "{} not inside a git repository — no repo hooks written.",
1414                warning_sign()
1415            );
1416            return Ok(());
1417        }
1418        RepoHooks::Unanswerable { why } => {
1419            return Err(format!(
1420                "{} git would not say where this repository's hooks live —\n    {}",
1421                error_sign(),
1422                crate::ui::sanitize(&why)
1423            ))
1424        }
1425    };
1426    let _ = std::fs::create_dir_all(&hooks);
1427
1428    // Asked here, ahead of the guard, only so the message can offer `--force`.
1429    // The guard inside `write_shims` is the one that decides, and it refuses
1430    // things `--force` will not move (a tracked path, a path git cannot answer
1431    // for) which this pre-check deliberately says nothing about.
1432    let foreign = foreign_hooks(&hooks);
1433    if !foreign.is_empty() && !force {
1434        let mut msg = format!(
1435            "{} {} already has hooks that are not ours:",
1436            error_sign(),
1437            hooks.display()
1438        );
1439        for (name, what) in &foreign {
1440            msg.push_str(&format!("\n    {name} — {}", what.describe()));
1441        }
1442        msg.push_str(concat!(
1443            "\n    Look at them first, then `",
1444            crate::bin!(),
1445            " install --force`."
1446        ));
1447        return Err(msg);
1448    }
1449
1450    let written = write_shims(&hooks, binary, force)
1451        .map_err(|e| format!("cannot write shims to {}: {e}", hooks.display()))?;
1452    eprintln!(
1453        "{} baked {} shims into {}",
1454        valid_sign(),
1455        written.len(),
1456        hooks.display()
1457    );
1458    report_overwrites(&written);
1459    Ok(())
1460}
1461
1462/// Take the shims out of the repository we are standing in.
1463///
1464/// Deliberately narrow. It removes files that are OURS and nothing else:
1465///
1466/// - a hook we did not write is left alone and named, because somebody wrote it
1467///   on purpose;
1468/// - `hook.skip` and `greengate.severity` are never touched — those are the
1469///   user's statements about their own repository, not our artefacts, and a
1470///   reinstall should not silently forget that they disabled a check;
1471/// - the binary goes only when asked, because other repositories are using it.
1472pub fn uninstall(remove_binary: bool) -> Result<(), String> {
1473    // The template directory FIRST, and unconditionally, because it is the only
1474    // part of an install that keeps working when you are not standing in a
1475    // repository — and because `uninstall` returning early with "not inside a
1476    // git repository" is how the standing grant survived every attempt to
1477    // revoke it.
1478    uninstall_template_dir()?;
1479    uninstall_repo_hooks()?;
1480
1481    if remove_binary {
1482        // The binary and the alias of its old name: an uninstall that left
1483        // `amont` behind would leave every 2.x shim still running it.
1484        let me = std::env::current_exe().unwrap_or_else(|_| PathBuf::from(BIN));
1485        for name in [BIN, OLD_BIN] {
1486            let target = bin_dir().join(name_for(&me, name));
1487            match std::fs::remove_file(&target) {
1488                Ok(()) => eprintln!(
1489                    "{} removed {}",
1490                    valid_sign(),
1491                    highlight(&target.to_string_lossy())
1492                ),
1493                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1494                Err(e) => return Err(format!("cannot remove {}: {e}", target.display())),
1495            }
1496        }
1497    }
1498
1499    report_global_template_dir();
1500
1501    // Said out loud, because a user who uninstalls and reinstalls should not be
1502    // surprised that a check they disabled is still disabled.
1503    eprintln!("    hook.skip and greengate.severity were not touched.");
1504    Ok(())
1505}
1506
1507/// `amont uninstall --repo`: this repository's shims and bookkeeping, and
1508/// nothing else. The template dir, `init.templateDir` and the binary are
1509/// machine state, which an installer that armed one repository must leave
1510/// exactly as it found them.
1511pub fn uninstall_repo() -> Result<(), String> {
1512    uninstall_repo_hooks()
1513}
1514
1515/// How much of amont is in a hooks directory.
1516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1517pub enum InstalledState {
1518    /// All six shims.
1519    Present,
1520    /// None, and every hook could be read.
1521    Absent,
1522    Partial,
1523    /// A hook could not be read, or git would not answer: never "absent".
1524    Unknown,
1525}
1526
1527impl InstalledState {
1528    pub fn as_str(self) -> &'static str {
1529        match self {
1530            InstalledState::Present => "present",
1531            InstalledState::Absent => "absent",
1532            InstalledState::Partial => "partial",
1533            InstalledState::Unknown => "unknown",
1534        }
1535    }
1536}
1537
1538/// Whether our shims are in a hooks directory, and the binary each bakes.
1539#[derive(Debug, PartialEq, Eq)]
1540pub struct Installed {
1541    pub state: InstalledState,
1542    pub hooks_dir: Option<PathBuf>,
1543    /// `(hook name, baked binary path)` for each shim of ours.
1544    pub shims: Vec<(&'static str, Option<String>)>,
1545}
1546
1547impl Installed {
1548    fn unknown() -> Installed {
1549        Installed {
1550            state: InstalledState::Unknown,
1551            hooks_dir: None,
1552            shims: Vec::new(),
1553        }
1554    }
1555
1556    pub fn to_json(&self) -> String {
1557        let shims: Vec<String> = self
1558            .shims
1559            .iter()
1560            .map(|(name, bin)| {
1561                crate::json::object(&[
1562                    crate::json::string_field("name", name),
1563                    crate::json::opt_string_field("binary", bin.as_deref()),
1564                ])
1565            })
1566            .collect();
1567        let dir = self.hooks_dir.as_ref().map(|d| d.display().to_string());
1568        crate::json::object(&[
1569            crate::json::string_field("state", self.state.as_str()),
1570            crate::json::opt_string_field("hooks_dir", dir.as_deref()),
1571            format!("\"shims\":{}", crate::json::array(&shims)),
1572        ])
1573    }
1574}
1575
1576/// Read the shims in `dir` from the files themselves, never from the list of
1577/// checks: what is installed is what is on disk.
1578pub fn installed_in(dir: &Path) -> Installed {
1579    let mut shims = Vec::new();
1580    let mut unreadable = false;
1581    for name in DISPATCHERS {
1582        let path = dir.join(name);
1583        match hookfile::classify(&path) {
1584            HookFile::Ours => shims.push((name, baked_binary(&path))),
1585            HookFile::Unknown { .. }
1586            | HookFile::Foreign(hookfile::ForeignWhy::Unreadable { .. }) => unreadable = true,
1587            HookFile::Absent
1588            | HookFile::Symlink { .. }
1589            | HookFile::NotARegularFile
1590            | HookFile::Foreign(
1591                hookfile::ForeignWhy::HandWritten | hookfile::ForeignWhy::NotUtf8,
1592            ) => {}
1593            // Unix only: the variant does not exist on Windows.
1594            #[cfg(unix)]
1595            HookFile::Foreign(hookfile::ForeignWhy::MultiplyLinked { .. }) => {}
1596        }
1597    }
1598    let state = match (shims.len(), unreadable) {
1599        (n, _) if n == DISPATCHERS.len() => InstalledState::Present,
1600        (_, true) => InstalledState::Unknown,
1601        (0, false) => InstalledState::Absent,
1602        _ => InstalledState::Partial,
1603    };
1604    Installed {
1605        state,
1606        hooks_dir: Some(dir.to_path_buf()),
1607        shims,
1608    }
1609}
1610
1611/// The repository's hooks, where git dispatches from.
1612pub fn installed_here() -> Installed {
1613    match repo_hooks() {
1614        RepoHooks::Own(dir) | RepoHooks::Redirected { to: dir, .. } => installed_in(&dir),
1615        RepoHooks::Nowhere | RepoHooks::Unanswerable { .. } => Installed::unknown(),
1616    }
1617}
1618
1619/// The machine's template dir, which every `git clone` copies hooks from.
1620pub fn installed_in_template_dir() -> Installed {
1621    installed_in(&template_hooks_dir())
1622}
1623
1624/// The absolute path `install` baked into a shim (`BAKED="…"`), if any.
1625fn baked_binary(path: &Path) -> Option<String> {
1626    let text = std::fs::read_to_string(path).ok()?;
1627    text.lines().find_map(|l| {
1628        let v = l.strip_prefix("BAKED=\"")?.strip_suffix('"')?;
1629        (!v.is_empty() && v != PLACEHOLDER).then(|| v.to_string())
1630    })
1631}
1632
1633/// Everything this tool ever wrote into ONE repository, forgotten — the
1634/// single list, so the two uninstall paths cannot drift apart.
1635///
1636/// `amont uninstall` swept its own repository and the fleet's `uninstall`
1637/// swept none of them: it removed shims from 200 repositories and left 200
1638/// ledgers, stamp refs and trust records behind, each one a statement about
1639/// hooks that are no longer there. Both now call this.
1640///
1641/// **Trust is revoked here, and that is a deliberate reversal.** The record
1642/// is keyed on the manifest's content, so keeping it would re-honour the
1643/// consent automatically on a reinstall — for bytes somebody reviewed once,
1644/// possibly a year ago, in a repository they since asked amont to stop
1645/// running in. Consent defaults to no everywhere else in this codebase
1646/// (untrusted manifests are inert, policy is withheld); it defaults to no
1647/// here too. Re-granting is one `amont trust`, which shows the file again.
1648///
1649/// **What is never touched**: `hook.skip` and `greengate.severity` (the user's
1650/// statements about their repository, not ours), and above all the held
1651/// store — `$GIT_DIR/greengate-held` and `greengate-preserved` hold UNCOMMITTED
1652/// WORK. An uninstall that deletes those loses the very thing the parking
1653/// machinery exists to protect; `amont restore` must keep working after the
1654/// hooks are gone.
1655pub fn forget_bookkeeping_in(repo: &Path) -> Vec<&'static str> {
1656    let mut gone = Vec::new();
1657    if crate::gate_stamp::forget_in(repo) {
1658        gone.push("gate stamps");
1659    }
1660    if crate::attest::forget_in(repo) {
1661        gone.push("attestations");
1662    }
1663    if crate::bypass::forget_in(repo) {
1664        gone.push("bypass ledger");
1665    }
1666    if crate::downgrade::forget_in(repo) {
1667        gone.push("downgrade ledger");
1668    }
1669    if crate::skew::forget_in(repo) {
1670        gone.push("version-skew marker");
1671    }
1672    // `--unset-all` exits 5 when the key is absent; that is not a removal.
1673    if crate::git::succeeds_in(repo, &["config", "--unset-all", "greengate.knownIdentity"]) {
1674        gone.push("known-identity memo");
1675    }
1676    if !crate::trust::recorded(repo).is_empty() && crate::trust::revoke(repo).is_ok() {
1677        gone.push("greengate.conf trust");
1678    }
1679    gone
1680}
1681
1682/// Remove our shims from the repository we are standing in, naming everything
1683/// we did not take and why.
1684///
1685/// Every non-removal is now NAMED. The loop this replaces matched
1686/// `Err(_) => {}` on `read_to_string`, so a hook that could not be read at all
1687/// — a compiled one, or one whose permissions we lack — was passed over in
1688/// total silence: not removed, not counted, not mentioned. The README's promise
1689/// that a foreign hook is "left alone and named" was true only for hooks that
1690/// happened to be valid UTF-8.
1691///
1692/// Not being in a repository is a warning rather than an error. It used to
1693/// return `Err`, which was defensible on its own but became wrong once
1694/// `uninstall_template_dir` existed: the early return meant that running
1695/// `amont uninstall` from a plain directory did nothing AND said nothing,
1696/// while `init.templateDir` quietly went on installing hooks into every future
1697/// clone. Refusing is not failing — the same rule `populate_template_dir`
1698/// already states.
1699fn uninstall_repo_hooks() -> Result<(), String> {
1700    // BOTH directories, where they differ. Uninstall is the one path that must
1701    // not inherit `install`'s new refusal: versions before it wrote shims into
1702    // whatever `core.hooksPath` named, so a repository can be carrying our files
1703    // in `.husky/_` right now — and refusing to look there would leave the only
1704    // command that removes them unable to find them. Removal is safe in a way
1705    // writing is not; `guard_remove` still decides file by file.
1706    let dirs: Vec<PathBuf> = match repo_hooks() {
1707        RepoHooks::Own(dir) => vec![dir],
1708        RepoHooks::Redirected { to, own } => vec![to, own],
1709        RepoHooks::Nowhere => {
1710            eprintln!(
1711                "{} not inside a git repository — no repo hooks removed.",
1712                warning_sign()
1713            );
1714            return Ok(());
1715        }
1716        // Removal stays forgiving where writing does not: failing here would
1717        // leave `uninstall --binary` unable to finish its cleanup. Loud, and Ok.
1718        RepoHooks::Unanswerable { why } => {
1719            eprintln!(
1720                "{} git would not answer here — no repo hooks removed ({})",
1721                warning_sign(),
1722                crate::ui::sanitize(&why)
1723            );
1724            return Ok(());
1725        }
1726    };
1727
1728    for hooks in &dirs {
1729        let mut removed = 0usize;
1730        let mut left: Vec<String> = Vec::new();
1731        for name in DISPATCHERS {
1732            let path = hooks.join(name);
1733            match hookfile::classify(&path) {
1734                HookFile::Absent => {}
1735                HookFile::Ours => match hookfile::guard_remove(&path, true) {
1736                    Ok(()) => {
1737                        hookfile::remove_regular(&path)
1738                            .map_err(|e| format!("cannot remove {}: {e}", path.display()))?;
1739                        removed += 1;
1740                    }
1741                    // Ours by marker, and still not ours to delete: a tracked
1742                    // path, or one git could not answer for.
1743                    Err(r) => left.push(r.explain()),
1744                },
1745                what => left.push(format!("{name} — {}", what.describe())),
1746            }
1747        }
1748        // The second directory is usually empty of ours and saying so every time
1749        // would be noise. Report it only when it held something.
1750        if removed > 0 || !left.is_empty() || dirs.len() == 1 {
1751            eprintln!(
1752                "{} removed {removed} shims from {}",
1753                valid_sign(),
1754                hooks.display()
1755            );
1756        }
1757        for reason in &left {
1758            eprintln!("{} left alone: {reason}", warning_sign());
1759        }
1760    }
1761    // Our bookkeeping only ever says "amont checked this" (or "didn't"),
1762    // which stops being true of anything the moment the hooks are gone. One
1763    // list, shared with the fleet — see `forget_bookkeeping_in` for what is
1764    // deliberately NOT taken.
1765    if let Ok(root) = crate::hooks::common::repo_root_checked() {
1766        let gone = forget_bookkeeping_in(Path::new(&root));
1767        if !gone.is_empty() {
1768            eprintln!("{} forgot {}", valid_sign(), gone.join(", "));
1769        }
1770    }
1771    Ok(())
1772}
1773
1774/// Take our shims back out of the template directory.
1775///
1776/// `install` writes there; `uninstall` did not, which meant uninstall did not
1777/// undo install. Combined with `init.templateDir`, that is the failure worth
1778/// spelling out: the user runs `amont uninstall`, sees "removed 4 shims",
1779/// believes they are done — and every `git clone` and `git init` from then on
1780/// copies the template directory into the new repository's `.git/hooks` and
1781/// installs the hooks again. They uninstalled a repository, not a machine.
1782///
1783/// The same classification `install` uses decides what may happen here, for the
1784/// same reason and with the sharper stake: `~/.config/git/git-templates` is
1785/// commonly a SYMLINK to a checkout of this repository, and "uninstalling"
1786/// there means `rm` on tracked source. That is not a hypothetical; it is the
1787/// two incidents this module exists because of, and a delete has no `--force`.
1788fn uninstall_template_dir() -> Result<(), String> {
1789    let dir = template_hooks_dir();
1790    // The RESOLVED path, because the configured one is usually the symlink that
1791    // hides exactly what we are about to explain.
1792    let shown = dir.canonicalize().unwrap_or_else(|_| dir.clone());
1793    let shown = shown.display();
1794
1795    match classify_dir(&dir) {
1796        TemplateDir::IsCheckout | TemplateDir::InsideCheckout => {
1797            eprintln!(
1798                "{} template dir is a git checkout ({shown}) — deleting NOTHING there.",
1799                warning_sign()
1800            );
1801            eprintln!("    Those shims are tracked files belonging to that checkout,");
1802            eprintln!("    not something this install put there. Remove them with git,");
1803            eprintln!("    or point init.templateDir somewhere else.");
1804        }
1805        TemplateDir::NoGit => eprintln!(
1806            "{} git is not on PATH — cannot tell whether {shown} is a checkout, deleting nothing.",
1807            warning_sign()
1808        ),
1809        TemplateDir::Unresolvable => eprintln!(
1810            "{} no template dir at {shown} — nothing to remove.",
1811            warning_sign()
1812        ),
1813        TemplateDir::Safe => {
1814            let mut removed = 0usize;
1815            let mut left: Vec<String> = Vec::new();
1816            for name in DISPATCHERS {
1817                let path = dir.join(name);
1818                match hookfile::classify(&path) {
1819                    HookFile::Absent => {}
1820                    HookFile::Ours => match hookfile::guard_remove(&path, true) {
1821                        Ok(()) => {
1822                            hookfile::remove_regular(&path)
1823                                .map_err(|e| format!("cannot remove {}: {e}", path.display()))?;
1824                            removed += 1;
1825                        }
1826                        Err(r) => left.push(r.explain()),
1827                    },
1828                    what => left.push(format!("{name} — {}", what.describe())),
1829                }
1830            }
1831            eprintln!("{} removed {removed} shims from {shown}", valid_sign());
1832            for reason in &left {
1833                eprintln!("{} left alone: {reason}", warning_sign());
1834            }
1835        }
1836    }
1837    Ok(())
1838}
1839
1840/// Say, every time, whether `init.templateDir` is still pointing at us.
1841///
1842/// UNCONDITIONAL, including when the template dir was a checkout we refused to
1843/// touch and when there was no template dir at all — because the config setting
1844/// is what actually installs hooks into new repositories, and it survives every
1845/// file this command removes. An uninstall that leaves it set has not
1846/// uninstalled anything durable: the next `git clone` re-installs.
1847///
1848/// Printed rather than unset. `git config --global` is the user's file, holding
1849/// their identity and their aliases, and reaching into it uninvited is a larger
1850/// claim than removing files this tool wrote. The command to run is given
1851/// verbatim so it is a copy rather than a lookup.
1852fn report_global_template_dir() {
1853    let Some(configured) = crate::git::stdout(&["config", "--global", "--get", "init.templateDir"])
1854        .filter(|s| !s.is_empty())
1855    else {
1856        return;
1857    };
1858    eprintln!();
1859    eprintln!(
1860        "{} init.templateDir is still set: {}",
1861        warning_sign(),
1862        highlight(&configured)
1863    );
1864    eprintln!("    Every `git clone` and `git init` still copies hooks from there");
1865    eprintln!("    into the new repository. Uninstalling this repo did not change that.");
1866    eprintln!("    Undo it with:");
1867    eprintln!(
1868        "        {}",
1869        highlight("git config --global --unset init.templateDir")
1870    );
1871}
1872
1873#[cfg(test)]
1874mod tests {
1875    use super::*;
1876
1877    fn tmp(name: &str) -> PathBuf {
1878        let d = std::env::temp_dir().join(format!("gh-install-{name}-{}", std::process::id()));
1879        let _ = std::fs::remove_dir_all(&d);
1880        std::fs::create_dir_all(&d).expect("mkdir");
1881        d
1882    }
1883
1884    fn git(dir: &Path, args: &[&str]) {
1885        Command::new("git")
1886            .arg("-C")
1887            .arg(dir)
1888            .args(args)
1889            .output()
1890            .expect("git");
1891    }
1892
1893    /// The embedded shim must be the shim that ships. `include_str!` takes one
1894    /// of the four; if they ever diverge, the installer would write a file
1895    /// nobody reviewed.
1896    #[test]
1897    fn shims_on_disk_match_the_embedded_one() {
1898        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
1899        // Absent when this crate is built from its PUBLISHED tarball, which
1900        // contains this directory and nothing above it. There is no drift to
1901        // catch in that situation — the only shim present is the one compiled
1902        // in — so say so rather than fail a test about a file that is not
1903        // supposed to be there.
1904        if !Path::new(dir).is_dir() {
1905            println!(
1906                "! no repository checkout here — nothing to compare the embedded shim against"
1907            );
1908            return;
1909        }
1910        for name in DISPATCHERS {
1911            let disk = std::fs::read_to_string(Path::new(dir).join(name))
1912                .unwrap_or_else(|e| panic!("read {name}: {e}"));
1913            assert_eq!(disk, SHIM, "{name} differs from the embedded shim");
1914        }
1915    }
1916
1917    /// The bytes that SHIP carry no carriage return.
1918    ///
1919    /// `SHIM` is an `include_str!`, so it is whatever the build host's
1920    /// checkout held — and with no `.gitattributes` that was CRLF on
1921    /// Windows, whose git defaults `core.autocrlf` to true. v1.14.0's
1922    /// `amont.exe` embedded `#!/bin/sh\r\n` and its archive shipped an
1923    /// 82-CR `pre-commit`, so every install there wrote a shell script with
1924    /// a carriage return in the shebang. This asserts the fix from the only
1925    /// side that matters — the compiled-in bytes — rather than trusting the
1926    /// attributes file to keep working. It runs on the Windows job, which is
1927    /// the checkout that could regress.
1928    #[test]
1929    fn the_embedded_shim_carries_no_carriage_return() {
1930        assert!(
1931            !SHIM.contains('\r'),
1932            "the embedded shim has CRLF line endings: this binary would \
1933             install `#!/bin/sh\\r` as a POSIX sh hook. `.gitattributes` \
1934             declares templates/hooks/* as eol=lf — has it been removed, or \
1935             is this checkout stale?"
1936        );
1937    }
1938
1939    /// The whole point of the module. A directory holding tracked files is the
1940    /// source checkout reached through a symlink, and emptying it destroys work.
1941    #[test]
1942    fn a_directory_holding_tracked_files_is_never_safe() {
1943        let d = tmp("tracked");
1944        git(&d, &["init", "-q", "--template=", "."]);
1945        git(&d, &["config", "user.email", "t@t.test"]);
1946        git(&d, &["config", "user.name", "t"]);
1947        std::fs::write(d.join("kept.txt"), "precious\n").expect("write");
1948        git(&d, &["add", "-A"]);
1949        git(&d, &["commit", "-qm", "seed"]);
1950
1951        assert_eq!(classify_dir(&d), TemplateDir::IsCheckout);
1952        let _ = std::fs::remove_dir_all(&d);
1953    }
1954
1955    /// A path comparison against the source tree passes here and is WRONG: a
1956    /// worktree is a different path holding the same tracked files. This is the
1957    /// case that caused the second incident.
1958    #[test]
1959    fn a_worktree_is_recognised_even_though_its_path_differs() {
1960        let d = tmp("wt-main");
1961        git(&d, &["init", "-q", "--template=", "."]);
1962        git(&d, &["config", "user.email", "t@t.test"]);
1963        git(&d, &["config", "user.name", "t"]);
1964        std::fs::write(d.join("kept.txt"), "precious\n").expect("write");
1965        git(&d, &["add", "-A"]);
1966        git(&d, &["commit", "-qm", "seed"]);
1967
1968        let wt = d.with_extension("wt");
1969        let _ = std::fs::remove_dir_all(&wt);
1970        git(&d, &["worktree", "add", "-q", wt.to_str().unwrap()]);
1971        assert!(
1972            wt.join("kept.txt").is_file(),
1973            "worktree did not materialise"
1974        );
1975        assert_ne!(d.canonicalize().ok(), wt.canonicalize().ok());
1976        assert_eq!(
1977            classify_dir(&wt),
1978            TemplateDir::IsCheckout,
1979            "a worktree must be refused exactly like the main checkout"
1980        );
1981        let _ = std::fs::remove_dir_all(&wt);
1982        let _ = std::fs::remove_dir_all(&d);
1983    }
1984
1985    /// Inside a checkout but tracking nothing here — still not ours to empty.
1986    #[test]
1987    fn an_untracked_directory_inside_a_checkout_is_refused() {
1988        let d = tmp("inside");
1989        git(&d, &["init", "-q", "--template=", "."]);
1990        let sub = d.join("scratch");
1991        std::fs::create_dir_all(&sub).expect("mkdir");
1992        assert_eq!(classify_dir(&sub), TemplateDir::InsideCheckout);
1993        let _ = std::fs::remove_dir_all(&d);
1994    }
1995
1996    #[test]
1997    fn an_ordinary_directory_is_safe() {
1998        let d = tmp("plain");
1999        assert_eq!(classify_dir(&d), TemplateDir::Safe);
2000        let _ = std::fs::remove_dir_all(&d);
2001    }
2002
2003    #[test]
2004    fn a_missing_directory_is_unresolvable_not_safe() {
2005        assert_eq!(
2006            classify_dir(Path::new("/nonexistent-install-c8f2/hooks")),
2007            TemplateDir::Unresolvable
2008        );
2009    }
2010
2011    /// Baking replaces every occurrence and is idempotent.
2012    #[test]
2013    fn baking_is_total_and_idempotent() {
2014        let once = bake(SHIM, "/opt/amont");
2015        assert!(!once.contains(PLACEHOLDER), "a token survived baking");
2016        assert!(once.contains("/opt/amont"));
2017        assert_eq!(bake(&once, "/other"), once, "re-baking must be a no-op");
2018    }
2019
2020    /// The shim's comment must not spell the token out, or a global replace
2021    /// turns the explanation into a machine path — which it did, in every shim
2022    /// baked before this module existed.
2023    #[test]
2024    fn baking_does_not_rewrite_the_comment_explaining_it() {
2025        for line in bake(SHIM, "/opt/amont").lines() {
2026            if line.trim_start().starts_with('#') {
2027                assert!(
2028                    !line.contains("/opt/amont"),
2029                    "baking rewrote a comment: {line}"
2030                );
2031            }
2032        }
2033    }
2034
2035    /// Only an absolute path may be baked.
2036    ///
2037    /// A relative one is resolved by the shim against the WORKING TREE, so a
2038    /// repository shipping an executable by that name would be running it on
2039    /// the first commit after clone.
2040    #[test]
2041    fn only_an_absolute_path_is_bakeable() {
2042        for good in [
2043            "/opt/amont",
2044            "/home/u/.local/bin/amont",
2045            "C:/Users/u/amont.exe",
2046            "C:\\Users\\u\\amont.exe",
2047        ] {
2048            assert!(is_bakeable(good), "{good} should be bakeable");
2049        }
2050        for bad in [
2051            "",
2052            PLACEHOLDER,
2053            "amont",
2054            "./amont",
2055            "../amont",
2056            "target/debug/amont",
2057            "C:amont.exe",
2058        ] {
2059            assert!(!is_bakeable(bad), "{bad:?} must not be bakeable");
2060        }
2061    }
2062
2063    /// The shim must never hand the unsubstituted token to `[ -x ]`: that is a
2064    /// filesystem question asked in the repository's own directory.
2065    #[test]
2066    fn the_shim_never_tests_the_placeholder_as_a_path() {
2067        assert!(
2068            !SHIM.contains(&format!("[ -x \"{PLACEHOLDER}\" ]")),
2069            "the shim tests the raw token as a path"
2070        );
2071        assert!(
2072            SHIM.contains("case \"$BAKED\" in"),
2073            "the shim lost its absoluteness guard"
2074        );
2075    }
2076
2077    /// Refusing beats writing four hooks that cannot resolve their binary.
2078    #[test]
2079    fn write_shims_refuses_a_relative_binary_path() {
2080        let d = tmp("relative");
2081        let err = write_shims(&d, "target/debug/amont", false).expect_err("must refuse");
2082        assert!(err.to_string().contains("absolute"), "{err}");
2083        for name in DISPATCHERS {
2084            assert!(!d.join(name).exists(), "{name} was written anyway");
2085        }
2086        let _ = std::fs::remove_dir_all(&d);
2087    }
2088
2089    /// Every hook git invokes gets a file, and each is the baked shim.
2090    #[test]
2091    fn writing_shims_covers_every_dispatcher() {
2092        let d = tmp("write");
2093        let written = write_shims(&d, "/opt/amont", false).expect("write");
2094        assert_eq!(written.len(), DISPATCHERS.len());
2095        for name in DISPATCHERS {
2096            let got = std::fs::read_to_string(d.join(name)).expect("read");
2097            assert!(!got.contains(PLACEHOLDER), "{name} was written unbaked");
2098            assert!(got.contains("/opt/amont"), "{name} has no path");
2099        }
2100        let _ = std::fs::remove_dir_all(&d);
2101    }
2102
2103    /// The whole-repository posture, at the level of the function that owes it:
2104    /// ONE unwritable path and nothing at all is written. `bake_repo_hooks` has
2105    /// claimed this in a comment since it was written, over a loop that checked
2106    /// one file then wrote it, four times over — so a refusal on the third hook
2107    /// arrived after two were already gone.
2108    #[test]
2109    fn one_refusal_writes_nothing_at_all() {
2110        let d = tmp("all-or-nothing");
2111        // `prepare-commit-msg` sorts last among the dispatchers, so under the
2112        // old check-then-write loop the first three would already be on disk by
2113        // the time this one refused.
2114        let theirs = d.join("prepare-commit-msg");
2115        std::fs::write(&theirs, "#!/bin/sh\necho MINE\n").expect("write");
2116
2117        let err = write_shims(&d, "/opt/amont", false).expect_err("must refuse");
2118        assert!(
2119            matches!(err, ShimWriteError::Refused(ref rs) if rs.len() == 1),
2120            "{err}"
2121        );
2122        for name in ["commit-msg", "pre-commit", "pre-push"] {
2123            assert!(
2124                !d.join(name).exists(),
2125                "{name} was written despite a refusal elsewhere"
2126            );
2127        }
2128        assert_eq!(
2129            std::fs::read_to_string(&theirs).expect("read"),
2130            "#!/bin/sh\necho MINE\n"
2131        );
2132        let _ = std::fs::remove_dir_all(&d);
2133    }
2134
2135    /// A refusal has to say WHAT was in the way, not only that something was.
2136    /// The old predicate could not: it read the file as a string, so the one
2137    /// case worth naming — a compiled hook — came back as "not foreign" and was
2138    /// overwritten in silence.
2139    #[test]
2140    fn a_refusal_names_the_reason_for_each_hook() {
2141        let d = tmp("named");
2142        std::fs::write(d.join("commit-msg"), [0x7f, b'E', b'L', b'F', 0xff]).expect("write");
2143        std::fs::write(d.join("pre-commit"), "#!/bin/sh\necho mine\n").expect("write");
2144
2145        let err = write_shims(&d, "/opt/amont", false).expect_err("must refuse");
2146        let text = err.to_string();
2147        assert!(text.contains("not valid UTF-8"), "{text}");
2148        assert!(text.contains("commit-msg"), "{text}");
2149        assert!(text.contains("pre-commit"), "{text}");
2150
2151        // And `foreign_hooks` — which is what phrases the `--force` offer —
2152        // agrees about both.
2153        let foreign = foreign_hooks(&d);
2154        assert_eq!(foreign.len(), 2, "{foreign:?}");
2155        assert!(foreign
2156            .iter()
2157            .any(|(n, w)| *n == "commit-msg" && matches!(w, HookFile::Foreign(_))));
2158        let _ = std::fs::remove_dir_all(&d);
2159    }
2160
2161    /// `--force` says what it took, per file, with what it was. Without this
2162    /// the output was "baked 4 shims" — a receipt with the transaction left
2163    /// off, for the one operation whose purpose is to destroy something.
2164    #[test]
2165    fn force_reports_what_each_write_replaced() {
2166        let d = tmp("force-report");
2167        std::fs::write(d.join("commit-msg"), "#!/bin/sh\necho mine\n").expect("write");
2168        let written = write_shims(&d, "/opt/amont", true).expect("force must write");
2169        let replaced: Vec<_> = written
2170            .iter()
2171            .filter(|w| !matches!(w.replaced, HookFile::Absent))
2172            .collect();
2173        assert_eq!(replaced.len(), 1, "{written:?}");
2174        assert!(replaced[0].path.ends_with("commit-msg"));
2175        assert!(matches!(replaced[0].replaced, HookFile::Foreign(_)));
2176        let _ = std::fs::remove_dir_all(&d);
2177    }
2178
2179    /// Windows builds amont.exe, and a shim testing `[ -x .../amont ]` is
2180    /// false for it — so the installed name has to keep the suffix. Asserted
2181    /// against explicit paths, because a `cfg!(windows)` branch is vacuous on
2182    /// the platform this is usually run on.
2183    #[test]
2184    fn the_installed_name_keeps_the_platform_suffix() {
2185        assert_eq!(
2186            name_for(Path::new("/w/target/release/greengate.exe"), BIN),
2187            "greengate.exe"
2188        );
2189        assert_eq!(
2190            name_for(Path::new("/w/target/release/greengate.exe"), OLD_BIN),
2191            "amont.exe"
2192        );
2193        assert_eq!(
2194            name_for(Path::new("/u/target/release/greengate"), BIN),
2195            "greengate"
2196        );
2197        // A path that happens to contain a dot elsewhere is not an extension.
2198        assert_eq!(name_for(Path::new("/some.dir/greengate"), OLD_BIN), "amont");
2199    }
2200
2201    #[cfg(unix)]
2202    #[test]
2203    fn an_install_replaces_by_rename_and_writes_the_alias_as_a_copy() {
2204        use std::os::unix::fs::MetadataExt;
2205        struct Cleanup(PathBuf);
2206        impl Drop for Cleanup {
2207            fn drop(&mut self) {
2208                let _ = std::fs::remove_dir_all(&self.0); // a leftover temp dir is harmless
2209            }
2210        }
2211        let dir = std::env::temp_dir().join(format!("greengate-install-{}", std::process::id()));
2212        let _cleanup = Cleanup(dir.clone());
2213        std::fs::create_dir_all(&dir).unwrap();
2214        let src = dir.join("built");
2215        std::fs::write(&src, "new build").unwrap();
2216        let target = dir.join(BIN);
2217        std::fs::write(&target, "old build").unwrap();
2218        let before = std::fs::metadata(&target).unwrap().ino();
2219        // A stale temporary, a young one (another install, running now),
2220        // and an old alias from a 2.x install.
2221        let stale = dir.join(format!(".{BIN}.tmp.1"));
2222        std::fs::write(&stale, "x").unwrap();
2223        let aged = std::process::Command::new("touch")
2224            .args(["-t", "200001010000"])
2225            .arg(&stale)
2226            .status()
2227            .unwrap();
2228        assert!(aged.success(), "touch -t could not age the leftover");
2229        // The young one staged through the same copy an install makes, from
2230        // a source that is itself old (the running binary usually is).
2231        let old_source = dir.join("old-source");
2232        std::fs::write(&old_source, "y").unwrap();
2233        std::process::Command::new("touch")
2234            .args(["-t", "200001010000"])
2235            .arg(&old_source)
2236            .status()
2237            .unwrap();
2238        let young = dir.join(format!(".{BIN}.tmp.2"));
2239        stage_copy(&old_source, &young).unwrap();
2240        std::fs::write(dir.join(OLD_BIN), "2.x binary").unwrap();
2241
2242        sweep_install_leftovers(&dir);
2243        replace_atomically(&src, &target).unwrap();
2244        assert_eq!(write_aliases(&target).unwrap(), vec![OLD_BIN]);
2245
2246        assert_eq!(std::fs::read_to_string(&target).unwrap(), "new build");
2247        // A new inode: the old file was replaced by rename, never written in place.
2248        assert_ne!(std::fs::metadata(&target).unwrap().ino(), before);
2249        let alias = dir.join(OLD_BIN);
2250        assert_eq!(std::fs::read_to_string(&alias).unwrap(), "new build");
2251        assert!(!std::fs::symlink_metadata(&alias)
2252            .unwrap()
2253            .file_type()
2254            .is_symlink());
2255        assert_ne!(
2256            std::fs::metadata(&alias).unwrap().ino(),
2257            std::fs::metadata(&target).unwrap().ino(),
2258            "the alias is a copy, not a hard link"
2259        );
2260        assert!(!stale.exists(), "a stale leftover was not swept");
2261        assert!(
2262            young.exists(),
2263            "a young temporary, maybe another install's, was swept"
2264        );
2265        // No fleet binary beside it, so no fleet alias either.
2266        assert!(!dir.join(OLD_FLEET_BIN).exists());
2267        // A 2.x `amont install` copying onto its target replaces only the alias.
2268        std::fs::write(&alias, "2.3.1 overwrite").unwrap();
2269        assert_eq!(std::fs::read_to_string(&target).unwrap(), "new build");
2270    }
2271
2272    fn hook_bytes(dir: &Path) -> Vec<(String, Vec<u8>)> {
2273        let mut v: Vec<_> = std::fs::read_dir(dir)
2274            .expect("hooks dir")
2275            .filter_map(|e| e.ok())
2276            .map(|e| {
2277                (
2278                    e.file_name().to_string_lossy().into_owned(),
2279                    std::fs::read(e.path()).unwrap_or_default(),
2280                )
2281            })
2282            .collect();
2283        v.sort();
2284        v
2285    }
2286
2287    /// A snapshot probe that cannot answer is NOT "not a snapshot": that
2288    /// answer is the one that bakes, and baking from a snapshot is the bug.
2289    /// The shims sit at sentinel A and the binary offered is B, so a re-bake
2290    /// would show — and the control at the end proves it does show.
2291    #[test]
2292    fn init_fails_closed_when_the_snapshot_probe_cannot_answer() {
2293        let d = tmp("probe-err");
2294        git(&d, &["init", "-q", "--template=", "."]);
2295        let hooks = d.join(".git").join("hooks");
2296        std::fs::create_dir_all(&hooks).expect("mkdir");
2297        write_shims(&hooks, "/sentinel/A/amont", false).expect("seed");
2298        let before = hook_bytes(&hooks);
2299        let b = || Ok(PathBuf::from("/sentinel/B/amont"));
2300
2301        let got = init_with(b(), &d, &|_| Err(std::io::Error::other("probe broke")));
2302        let why = got.expect_err("a probe that cannot answer must fail init");
2303        assert!(why.contains("cannot tell"), "{why}");
2304        assert_eq!(before, hook_bytes(&hooks), "init wrote on doubt");
2305
2306        init_with(b(), &d, &|_| Ok(false)).expect("not a snapshot: bakes");
2307        assert_ne!(before, hook_bytes(&hooks), "the control could not fail");
2308        let _ = std::fs::remove_dir_all(&d);
2309    }
2310}