Skip to main content

amont_runtime/hooks/
common.rs

1//! Shared plumbing for the linter-orchestration hooks.
2//!
3//! Nine of them do the same four things: collect staged files of some kind,
4//! bail out if there are none, resolve a tool, run it. In shell that was ~65
5//! lines apiece, mostly duplicated; here it is a handful of helpers and each
6//! hook keeps only what is actually specific to it.
7
8use crate::git;
9use crate::ui::{error_sign, valid_sign, warning_sign};
10use std::path::Path;
11use std::process::{Command, Stdio};
12use std::sync::OnceLock;
13
14/// Staged files, deletions excluded, whose name ends with one of `exts`.
15/// The file set every check asks about, when it is not the staged one.
16///
17/// Set at most once, before any check runs, by `amont run --all-files`. A
18/// process-level override rather than a parameter because a check's signature
19/// is `(&[OsString])` — it never sees a `Ctx` — and threading a file set
20/// through twenty of them to serve one mode would be a worse trade than a
21/// value that is written once and read many times.
22///
23/// Same shape as `PushRefs`: read once, lent to every check that asks.
24static OVERRIDE: OnceLock<Vec<String>> = OnceLock::new();
25
26/// Set once the file set stops being the index.
27///
28/// `restage`'s own doc says what makes re-staging safe: the pre-commit stage
29/// holds the unstaged changes aside, so the tree contains the staged content
30/// and nothing else, and anything a formatter touched is by definition part of
31/// this commit. `amont run --all-files` replaces the file set with every
32/// tracked path — which is that precondition being FALSE.
33///
34/// With `amont.fix true`, every fixer's `restage(&files)` would then `git
35/// add` everything in the working tree that differs from the index, turning a
36/// read-only "does my tree pass" query into `git add .`. That is the hazard §2
37/// of docs/index-fidelity-and-run-modes.md names.
38///
39/// The gate hangs off the OVERRIDE rather than off a flag threaded through
40/// twenty check signatures, because the override IS the fact that matters. It
41/// therefore covers built-ins and `manifest::External::run` (which consults
42/// `fixing_enabled` in two places) in one change, and a future check cannot
43/// forget it.
44static NOT_THE_INDEX: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
45
46/// Make every subsequent `staged_files` answer from `files` instead of the
47/// index. Only the first call counts.
48pub fn override_file_set(files: Vec<String>) {
49    // Set unconditionally, even if a set already won the `OnceLock`: the
50    // statement "the file set is not the index" is true from the first call
51    // onwards regardless of which one supplied the paths.
52    NOT_THE_INDEX.store(true, std::sync::atomic::Ordering::SeqCst);
53    let _ = OVERRIDE.set(files);
54}
55
56/// Whether the file set every check sees is something other than the index.
57pub fn not_the_index() -> bool {
58    NOT_THE_INDEX.load(std::sync::atomic::Ordering::SeqCst)
59}
60
61/// Extensions a commit may edit without running `docs-skip` checks. `.txt` is
62/// left out on purpose: `requirements.txt` is a dependency manifest, and a
63/// dependency change must never skip the gate that judges it.
64const DOC_EXTS: &[&str] = &[".md", ".mdx", ".rst", ".adoc"];
65
66/// Whether the staged change is ONLY edits to existing documentation: every
67/// path a modification (an added, deleted or renamed file can break a citation
68/// in either direction, so it is never skipped) with a documentation
69/// extension, outside the decision registry's `adr/`, whose records the
70/// decision graph is built from. False when the file set is not the index,
71/// when git would not say, and for an empty change.
72pub fn staged_docs_only() -> bool {
73    if not_the_index() {
74        return false;
75    }
76    let Some(raw) = git::stdout_paths(&["diff", "--cached", "--no-renames", "--name-status"])
77    else {
78        return false;
79    };
80    !raw.is_empty()
81        && raw.len() % 2 == 0
82        && raw.chunks(2).all(|pair| {
83            pair[0] == "M"
84                && !pair[1].starts_with("adr/")
85                && DOC_EXTS.iter().any(|e| pair[1].ends_with(e))
86        })
87}
88
89/// An empty `exts` returns them all.
90///
91/// The UNFILTERED list is read from git ONCE per process and lent to every
92/// caller — the per-stage snapshot. Eleven of the pre-commit checks ask this
93/// question, concurrently, and each used to pay its own `git diff` spawn for
94/// an answer that cannot change while the stage runs: the index-fidelity
95/// hold pins the tree, and a fixer's `restage()` re-adds only paths already
96/// on this list. `PushRefs` ("read once and lent") and `Overrides` ("ONE
97/// subprocess for the whole stage") are the same pattern; this was the last
98/// hot question still answered per asker.
99pub fn staged_files(exts: &[&str]) -> Vec<String> {
100    if let Some(all) = OVERRIDE.get() {
101        return all
102            .iter()
103            .filter(|f| exts.is_empty() || exts.iter().any(|e| f.ends_with(e)))
104            .cloned()
105            .collect();
106    }
107    static INDEX: OnceLock<Vec<String>> = OnceLock::new();
108    INDEX
109        .get_or_init(|| {
110            match git::stdout_paths(&["diff", "--diff-filter=d", "--cached", "--name-only"]) {
111                Some(files) => files,
112                // The third member of a bug family (`repo_hooks`, the push
113                // gates): git FAILING is not git answering "empty", and a
114                // stage that judges an empty set on a git failure reports
115                // clean having verified nothing. Say so — once, this cache
116                // being the once — and still fail open: pre-commit's job is
117                // never to block a commit over its own plumbing.
118                None => {
119                    warn(
120                        "git would not list the staged files — the checks are judging \
121                         an EMPTY set, not a verified one",
122                    );
123                    Vec::new()
124                }
125            }
126        })
127        .iter()
128        .filter(|f| exts.is_empty() || exts.iter().any(|e| f.ends_with(e)))
129        .cloned()
130        .collect()
131}
132
133/// Every path the index holds — what the repository CARRIES, as opposed to
134/// what the current change touches.
135///
136/// The one honest source for a [`Scope`](crate::check::Scope) opt-in marker.
137/// [`staged_files`] answers a different question, and answering the opt-in one
138/// with it makes a `+marker` row fire only when the marker itself is in the
139/// change — which is never, in ordinary work.
140///
141/// `ls-files` reads the INDEX, not `HEAD`, so a marker being added by this very
142/// commit already counts. A marker sitting untracked on disk does not, which is
143/// the same rule the manifest itself lives by: commit it, or it is not real.
144///
145/// Fails OPEN, unlike `staged_files`, and the asymmetry is deliberate. There,
146/// an empty list means the checks judge nothing and say so. Here, an empty list
147/// would silently switch every gated check OFF — a check that has quietly never
148/// run is the one failure this design is arranged against — so a git failure
149/// reports the check as opted in and lets the command itself be the judge. A
150/// command that then finds no project fails to spawn, which is `Unavailable`:
151/// a warning, never a block.
152/// `None` when git would not answer — which is NOT the same as an empty
153/// repository, and the caller must not flatten the two. An empty `Vec` opts
154/// every gated check OUT; `None` means "unverified", and the gate opts them IN.
155pub fn tracked_files() -> Option<Vec<String>> {
156    static TRACKED: OnceLock<Option<Vec<String>>> = OnceLock::new();
157    TRACKED
158        .get_or_init(|| match git::stdout_paths(&["ls-files"]) {
159            Some(files) => Some(files),
160            None => {
161                warn(
162                    "git would not list the repository's files — opt-in gated checks \
163                     will run rather than be skipped on an unverified answer",
164                );
165                None
166            }
167        })
168        .clone()
169}
170
171/// Repo root, or "." when git cannot say.
172///
173/// **For CHECK BODIES ONLY.** The fallback is safe there and nowhere else: git
174/// invokes a hook with the working tree as the current directory, so a check
175/// that reaches this line is already standing in the repository, and "." is the
176/// right answer rather than a guess.
177///
178/// Anything a user types — `amont agents-md`, `install`, `trust`, `restore`
179/// — can be typed from any directory on the machine, and there the fallback is
180/// not a fallback but a wrong answer that reads as a right one. Use
181/// [`repo_root_checked`] at every command entry point.
182pub fn repo_root() -> String {
183    // Cached: the answer is a property of the process's repository, and
184    // every check asked it through its own subprocess.
185    static ROOT: OnceLock<String> = OnceLock::new();
186    ROOT.get_or_init(|| {
187        git::stdout(&["rev-parse", "--show-toplevel"]).unwrap_or_else(|| ".".into())
188    })
189    .clone()
190}
191
192/// Repo root, or an error naming the problem.
193///
194/// The same question as [`repo_root`] without the "." — because "." is a
195/// PLAUSIBLE root, and that is what made it dangerous. `amont agents-md`
196/// run outside a repository did not fail; it resolved the root to the current
197/// directory and wrote `./AGENTS.md` into whatever directory the user happened
198/// to be standing in, then printed `wrote ./AGENTS.md` as if that were the
199/// answer. Same shape in `install`'s two prompts, in `trust` (which then
200/// looked for a manifest, and would have recorded trust, under `.`) and in
201/// `restore`.
202///
203/// Every one of those is a command somebody types, and a command somebody
204/// types is a command they can type from `~`. There is no correct behaviour
205/// available to this function when git cannot answer, so it does not invent
206/// one.
207pub fn repo_root_checked() -> Result<String, String> {
208    git::stdout(&["rev-parse", "--show-toplevel"])
209        .filter(|s| !s.is_empty())
210        .ok_or_else(|| "not inside a git repository".to_string())
211}
212
213/// Resolve a tool, preferring the repo's PINNED copy so the hook matches CI.
214///
215///
216/// Order: `<root>/node_modules/.bin/<tool>`, then the MAIN worktree's (a linked
217/// worktree has no node_modules of its own — this is why the shell version
218/// consulted the git common dir), then PATH.
219pub fn resolve_tool(root: &str, tool: &str) -> Option<Vec<String>> {
220    // Same extension problem as `which`: an npm-installed binary is `eslint.cmd`
221    // on Windows, so the bare name misses the repo's PINNED copy and the hook
222    // silently falls through to an ambient one.
223    if let Some(p) = in_bin_dir(&format!("{root}/node_modules/.bin"), tool) {
224        return Some(vec![p]);
225    }
226    if let Some(common) = git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])
227    {
228        if let Some(main) = Path::new(&common).parent() {
229            if let Some(p) = in_bin_dir(&main.join("node_modules/.bin").to_string_lossy(), tool) {
230                return Some(vec![p]);
231            }
232        }
233    }
234    if let Some(full) = which(tool) {
235        return Some(vec![full]);
236    }
237    // `npx --no-install`: never silently download a random latest version — a
238    // hook that quietly pulls a different linter than CI uses is worse than one
239    // that skips.
240    if which("npx").is_some()
241        && Command::new(program("npx"))
242            .args(["--no-install", tool, "--version"])
243            .current_dir(root)
244            .stdin(Stdio::null())
245            .stdout(Stdio::null())
246            .stderr(Stdio::null())
247            .status()
248            .map(|s| s.success())
249            .unwrap_or(false)
250    {
251        return Some(vec![
252            program("npx"),
253            "--no-install".to_string(),
254            tool.to_string(),
255        ]);
256    }
257    None
258}
259
260/// First match for `tool` on PATH.
261///
262/// Windows executables carry an extension — `git` is `git.exe`, an npm-installed
263/// `eslint` is `eslint.cmd` — so the bare name finds nothing there. PATHEXT is
264/// the OS's own list of what counts as executable; fall back to the usual set
265/// when it is unset. Found by the Windows CI job on its first run, where
266/// `which("git")` returned None on a machine that plainly has git.
267pub fn which(tool: &str) -> Option<String> {
268    which_on(&std::env::var_os("PATH")?, tool)
269}
270
271/// [`which`] against an EXPLICIT path list — the seam its own test needs.
272///
273/// The test that pins the Windows extension order used to `set_var("PATH")`
274/// around the call, which is process-global: for the length of that call
275/// every OTHER test in the binary — 340 of them, running in parallel, many
276/// spawning git — had a PATH containing one fake tool and nothing else. A
277/// git spawned in that window fails with "not found", which is not a
278/// transient `git::retrying` may retry (correctly: it is a hard error), so
279/// the caller reads it as git's ANSWER. In `gate_stamp` that answer is
280/// "nothing is stamped". Passing the path in deletes the shared state
281/// rather than guarding it — a lock only protects the callers who remember
282/// to take it, and every future test here would have to remember.
283pub fn which_on(path: &std::ffi::OsStr, tool: &str) -> Option<String> {
284    let exts: Vec<String> = if cfg!(windows) {
285        std::env::var("PATHEXT")
286            .unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into())
287            .split(';')
288            .filter(|e| !e.is_empty())
289            .map(|e| e.to_lowercase())
290            .collect()
291    } else {
292        Vec::new()
293    };
294    for dir in std::env::split_paths(path) {
295        // On Windows the EXTENSION forms come first. A node install ships both
296        // `npm` (an extensionless shell script, for MSYS) and `npm.cmd` in the
297        // same directory; preferring the bare name hands CreateProcess a shell
298        // script it cannot execute — "%1 is not a valid Win32 application" —
299        // and the hook reports an installed tool as broken.
300        for e in &exts {
301            let c = dir.join(format!("{tool}{e}"));
302            if c.is_file() {
303                return Some(c.to_string_lossy().into_owned());
304            }
305        }
306        let bare = dir.join(tool);
307        if bare.is_file() {
308            return Some(bare.to_string_lossy().into_owned());
309        }
310    }
311    None
312}
313
314/// `<dir>/<tool>`, trying the Windows executable extensions too.
315fn in_bin_dir(dir: &str, tool: &str) -> Option<String> {
316    let bare = Path::new(dir).join(tool);
317    if bare.is_file() {
318        return Some(bare.to_string_lossy().into_owned());
319    }
320    if cfg!(windows) {
321        for e in [".cmd", ".exe", ".bat", ".ps1"] {
322            let c = Path::new(dir).join(format!("{tool}{e}"));
323            if c.is_file() {
324                return Some(c.to_string_lossy().into_owned());
325            }
326        }
327    }
328    None
329}
330
331/// Resolve a tool name to a full path for spawning.
332///
333/// `Command::new("npm")` cannot execute `npm.cmd`: Rust does no PATHEXT
334/// resolution, so on Windows every bare-name spawn fails with "program not
335/// found" and the hook reports the tool as broken rather than absent. Found by
336/// the Windows job on its first FULL-suite run — the smoke never spawned a
337/// tool, so it could not have surfaced this.
338///
339/// Falls back to the name unchanged, so a caller still gets a sensible error.
340pub fn program(name: &str) -> String {
341    which(name).unwrap_or_else(|| name.to_string())
342}
343
344/// The first of `names` that exists at the repo root — how these hooks decide
345/// a repo has opted into a tool.
346pub fn first_existing(root: &str, names: &[&str]) -> Option<String> {
347    names
348        .iter()
349        .find(|n| Path::new(root).join(n).exists())
350        .map(|n| (*n).to_string())
351}
352
353/// Strip git's own environment before handing a Command to another tool.
354///
355/// git exports GIT_DIR, GIT_INDEX_FILE, GIT_WORK_TREE and friends to every
356/// hook. Those OVERRIDE the working directory, so any tool that shells out to
357/// git operates on the hook's repository no matter where it was launched.
358///
359/// That is not hypothetical: `pre-push-cargo-test` runs a project's test suite,
360/// and this repo's own suite creates throwaway repos and commits to them. With
361/// GIT_DIR inherited, `git commit` in a test wrote into the REAL repository —
362/// an actual stray commit, authored by the test fixture, pushed to a branch.
363///
364/// A test suite should behave exactly as it does when run by hand, which means
365/// seeing no git environment at all.
366pub fn strip_git_env(cmd: &mut Command) {
367    for (k, _) in std::env::vars_os() {
368        let key = k.to_string_lossy();
369        if key.starts_with("GIT_") {
370            cmd.env_remove(&k);
371        }
372    }
373}
374
375/// The wall-clock CEILING for one check's spawned command, in seconds.
376///
377/// `amont.timeout`, default 3600. This used to be 600 and to be the only
378/// clock, which made it answer two different questions with one number: "is
379/// this tool stuck?" and "is this suite slow?". A stuck tool is silent, and
380/// [`idle_timeout`] catches it in minutes; what is left for the ceiling is
381/// the tool that keeps printing and never finishes, which is rare enough to
382/// afford an hour. `0` disables. Read once per process: twenty concurrent
383/// checks must not each spawn a `git config` to learn the same number.
384pub fn check_timeout(settings: &crate::config::Settings) -> u64 {
385    *settings.timeout.get_or_init(|| {
386        crate::config::integer_or(settings, "amont.timeout", 3600, 0..=86_400) as u64
387    })
388}
389
390/// The SILENCE budget: how long a spawned command may go without writing a
391/// byte before it is judged stuck, in seconds.
392///
393/// `amont.idleTimeout`, default 120. A hang is silent; a slow test suite
394/// talks — `cargo test` prints a line per test. Not every one does (vitest
395/// without a terminal prints only its summary), so where CPU can be measured
396/// the budget counts silence AND an idle process tree — see [`Activity`] and
397/// ADR-0008. Killing on silence catches
398/// the captive portal, the deadlocked lock file and the tool waiting on a
399/// prompt nobody will answer FASTER than a ten-minute wall clock did, while
400/// letting a chatty twenty-five-minute suite finish. Only applies where the
401/// output is observed (the captured runners); a command inheriting the
402/// terminal directly answers to the ceiling alone. `0` disables.
403pub fn idle_timeout(settings: &crate::config::Settings) -> u64 {
404    *settings.idle.get_or_init(|| {
405        crate::config::integer_or(settings, "amont.idleTimeout", 120, 0..=86_400) as u64
406    })
407}
408
409/// Whether a silent check that is measurably working on CPU is kept alive
410/// past the silence budget — `amont.idleCpuCredit`, default true (ADR-0008,
411/// `hooks.liveness`). `false` restores the silence-only rule everywhere.
412/// Read once per `Settings`, like the two clocks.
413pub fn idle_cpu_credit(settings: &crate::config::Settings) -> bool {
414    *settings
415        .idle_cpu
416        .get_or_init(|| crate::config::boolean_or(settings, "amont.idleCpuCredit", true))
417}
418
419/// How long a command may sit in a DECLARED wait — a line that says it is
420/// blocked on a lock ([`crate::hooks::wait::marker`]) — before it is killed,
421/// in seconds. `amont.lockWait`, default 600; `0` means until the ceiling.
422/// The silence clock does not run during such a wait: the tool has said
423/// what it is doing, and a lock held by another cargo for a minute on a
424/// loaded machine is not a hang (ADR-0009). Read once per `Settings`.
425pub fn lock_wait(settings: &crate::config::Settings) -> LockWait {
426    match *settings.lock_wait.get_or_init(|| {
427        crate::config::integer_or(settings, "amont.lockWait", 600, 0..=86_400) as u64
428    }) {
429        0 => LockWait::UntilCeiling,
430        s => LockWait::Secs(s),
431    }
432}
433
434/// The budget for a declared wait, as [`lock_wait`] reads it.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436pub enum LockWait {
437    Secs(u64),
438    /// `amont.lockWait 0`: the ceiling alone bounds a declared wait — and
439    /// when the ceiling is off too, the extended silence budget does, so
440    /// nothing is ever unbounded.
441    UntilCeiling,
442}
443
444/// `secs` as people read it: `12s`, `8m12s`, `1h02m`.
445pub fn human_secs(secs: u64) -> String {
446    match secs {
447        s if s < 60 => format!("{s}s"),
448        s if s < 3600 => format!("{}m{:02}s", s / 60, s % 60),
449        s => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
450    }
451}
452
453/// How much of a tool's last stderr line a message may quote.
454pub const LAST_LINE_CHARS: usize = 200;
455
456/// A work window of at least this many thousandths of one core counts as the
457/// tree doing something (ADR-0008): 0.1 core. A hang — a prompt, a lock, a
458/// dead network — sits near zero; a test suite runs at whole cores.
459pub const BUSY_MILLI_CORES: u32 = 100;
460
461/// What the CPU side of [`Activity`] knows. Stored as a `u8`.
462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
463pub enum CpuState {
464    /// Not sampled: `amont.idleCpuCredit false`, no silence budget, or a
465    /// platform that cannot measure. The silence-only rule applies.
466    Off = 0,
467    /// Sampling, but nothing measured yet (the check has not been quiet
468    /// long enough, or it has only a baseline).
469    Waiting = 1,
470    /// Consecutive complete snapshots are being compared.
471    Measuring = 2,
472    /// The last snapshot was incomplete; the next complete one re-baselines.
473    Unavailable = 3,
474}
475
476/// What a spawned command has been doing, shared between the reader threads
477/// that see its bytes, the CPU sampler, the wait loop that judges it, and the
478/// progress displays. Every field is an atomic offset from `base`, so the
479/// 80 ms repaint and the 25 ms wait loop read it without a lock.
480///
481/// Two clocks, kept apart on purpose: `last_out` is when it last WROTE (what
482/// the messages report as "last output"), `last_busy` is the start of the
483/// last window in which its process tree did measurable CPU work. The kill
484/// decision uses the later of the two ([`Activity::still_for`]).
485pub struct Activity {
486    base: std::time::Instant,
487    last_out: std::sync::atomic::AtomicU64,
488    last_busy: std::sync::atomic::AtomicU64,
489    /// Offset + 1 of the start of the current unbroken run of complete
490    /// measurements; 0 when there is none.
491    measured_since: std::sync::atomic::AtomicU64,
492    /// Offset + 1 of the end of the last complete window; 0 when none.
493    last_measured: std::sync::atomic::AtomicU64,
494    rate_milli: std::sync::atomic::AtomicU32,
495    interval_ms: std::sync::atomic::AtomicU32,
496    cpu: std::sync::atomic::AtomicU8,
497    /// Offset + 1 of the start of the current declared wait (ADR-0009); 0
498    /// when the last stderr line was not a wait marker.
499    wait_since: std::sync::atomic::AtomicU64,
500    /// [`crate::hooks::wait::WaitKind::code`] of that wait; 0 when none.
501    wait_kind: std::sync::atomic::AtomicU8,
502    /// Nanoseconds spent in declared waits that have ENDED — what the note
503    /// after a slow-but-passing check reports.
504    waited_ns: std::sync::atomic::AtomicU64,
505    /// The code of the most recent wait, kept after it ends, so the note can
506    /// name what was waited for.
507    last_wait_kind: std::sync::atomic::AtomicU8,
508    /// The silence budget the wait loop is applying right now, in seconds,
509    /// after the host's load stretched it; 0 while it is the configured one
510    /// (ADR-0009). What the displays count toward.
511    budget_secs: std::sync::atomic::AtomicU32,
512    /// The load that stretched it: average × 1000, cores, factor × 1000.
513    load_avg_milli: std::sync::atomic::AtomicU32,
514    load_cores: std::sync::atomic::AtomicU32,
515    load_factor_milli: std::sync::atomic::AtomicU32,
516    /// The last complete, non-empty stderr line, colour stripped and
517    /// clipped: what a kill message may quote, and what decides a retry.
518    last_line: std::sync::Mutex<String>,
519}
520
521impl Activity {
522    pub fn new() -> std::sync::Arc<Activity> {
523        std::sync::Arc::new(Activity {
524            base: std::time::Instant::now(),
525            last_out: Default::default(),
526            last_busy: Default::default(),
527            measured_since: Default::default(),
528            last_measured: Default::default(),
529            rate_milli: Default::default(),
530            interval_ms: Default::default(),
531            cpu: std::sync::atomic::AtomicU8::new(CpuState::Off as u8),
532            wait_since: Default::default(),
533            wait_kind: Default::default(),
534            waited_ns: Default::default(),
535            last_wait_kind: Default::default(),
536            budget_secs: Default::default(),
537            load_avg_milli: Default::default(),
538            load_cores: Default::default(),
539            load_factor_milli: Default::default(),
540            last_line: std::sync::Mutex::new(String::new()),
541        })
542    }
543
544    /// What the most recent declared wait, ended or not, was for.
545    pub fn last_wait_kind(&self) -> Option<crate::hooks::wait::WaitKind> {
546        crate::hooks::wait::WaitKind::from_code(
547            self.last_wait_kind
548                .load(std::sync::atomic::Ordering::Relaxed),
549        )
550    }
551
552    /// One complete stderr line arrived. A wait marker starts a declared
553    /// wait, or continues the one in progress (cargo prints `package cache`
554    /// and then `build directory`; the budget covers the run of them, not
555    /// each); any other line ends it. The line is kept for the messages.
556    pub fn stderr_line(&self, raw: &str) {
557        use std::sync::atomic::Ordering::Relaxed;
558        let line = crate::hooks::wait::strip_csi(raw);
559        if !line.trim().is_empty() {
560            let mut keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
561            keep.clear();
562            keep.extend(line.trim().chars().take(LAST_LINE_CHARS));
563        }
564        match crate::hooks::wait::marker(&line) {
565            Some(kind) => {
566                self.wait_kind.store(kind.code(), Relaxed);
567                self.last_wait_kind.store(kind.code(), Relaxed);
568                // `compare_exchange` from 0: a second marker keeps the
569                // original start.
570                let _ = self
571                    .wait_since
572                    .compare_exchange(0, self.now() + 1, Relaxed, Relaxed);
573            }
574            None => self.end_wait(),
575        }
576    }
577
578    /// The tool wrote something that is not a wait marker: whatever wait
579    /// was in progress is over, and its length is banked for the note.
580    pub fn end_wait(&self) {
581        use std::sync::atomic::Ordering::Relaxed;
582        let since = self.wait_since.swap(0, Relaxed);
583        if since != 0 {
584            let spent = self.now().saturating_sub(since - 1);
585            self.waited_ns.fetch_add(spent, Relaxed);
586        }
587        self.wait_kind.store(0, Relaxed);
588    }
589
590    /// The declared wait in progress, and how long it has lasted.
591    pub fn waiting(&self) -> Option<(crate::hooks::wait::WaitKind, std::time::Duration)> {
592        use std::sync::atomic::Ordering::Relaxed;
593        let since = self.wait_since.load(Relaxed);
594        if since == 0 {
595            return None;
596        }
597        let kind = crate::hooks::wait::WaitKind::from_code(self.wait_kind.load(Relaxed))?;
598        Some((kind, self.since(since - 1)))
599    }
600
601    /// Time spent in declared waits that have ended, plus the one in
602    /// progress: what a passing check waited for in total.
603    pub fn waited_total(&self) -> std::time::Duration {
604        use std::sync::atomic::Ordering::Relaxed;
605        let banked = std::time::Duration::from_nanos(self.waited_ns.load(Relaxed));
606        banked + self.waiting().map_or(std::time::Duration::ZERO, |(_, d)| d)
607    }
608
609    /// The last non-empty stderr line, if any.
610    pub fn last_line(&self) -> Option<String> {
611        let keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
612        (!keep.is_empty()).then(|| keep.clone())
613    }
614
615    /// The wait loop read the host's load and is applying `budget_secs`.
616    pub fn set_load(&self, budget_secs: u64, load: crate::load::Load, factor_milli: u32) {
617        use std::sync::atomic::Ordering::Relaxed;
618        self.budget_secs
619            .store(u32::try_from(budget_secs).unwrap_or(u32::MAX), Relaxed);
620        self.load_avg_milli.store(load.avg1_milli, Relaxed);
621        self.load_cores.store(load.cores, Relaxed);
622        self.load_factor_milli.store(factor_milli, Relaxed);
623    }
624
625    /// The load-stretched budget in force, with the load behind it, when
626    /// the host's load stretched it at all.
627    pub fn load_scale(&self) -> Option<(u64, crate::load::Load, u32)> {
628        use std::sync::atomic::Ordering::Relaxed;
629        let factor = self.load_factor_milli.load(Relaxed);
630        if factor <= 1000 {
631            return None;
632        }
633        Some((
634            u64::from(self.budget_secs.load(Relaxed)),
635            crate::load::Load {
636                avg1_milli: self.load_avg_milli.load(Relaxed),
637                cores: self.load_cores.load(Relaxed),
638            },
639            factor,
640        ))
641    }
642    fn offset(&self, at: std::time::Instant) -> u64 {
643        u64::try_from(at.saturating_duration_since(self.base).as_nanos()).unwrap_or(u64::MAX)
644    }
645    fn now(&self) -> u64 {
646        self.offset(std::time::Instant::now())
647    }
648    fn since(&self, offset: u64) -> std::time::Duration {
649        std::time::Duration::from_nanos(self.now().saturating_sub(offset))
650    }
651    /// It wrote something.
652    pub fn touch(&self) {
653        self.last_out
654            .fetch_max(self.now(), std::sync::atomic::Ordering::Relaxed);
655    }
656    /// How long since it last wrote a byte — the true output silence, what
657    /// the displays report as "last output".
658    pub fn quiet_for(&self) -> std::time::Duration {
659        self.since(self.last_out.load(std::sync::atomic::Ordering::Relaxed))
660    }
661    /// The silence the clock counts: zero while the command is in a
662    /// declared wait (it has said what it is doing), the output silence
663    /// otherwise. What [`Activity::still_for`] and the sampler's start gate
664    /// read; the displays keep [`Activity::quiet_for`].
665    pub fn silence_for(&self) -> std::time::Duration {
666        if self.waiting().is_some() {
667            std::time::Duration::ZERO
668        } else {
669            self.quiet_for()
670        }
671    }
672    /// How long it has been BOTH silent and idle on CPU — the number the
673    /// silence budget is judged against. Equals [`Activity::silence_for`]
674    /// whenever CPU is not sampled.
675    pub fn still_for(&self) -> std::time::Duration {
676        let busy = self.last_busy.load(std::sync::atomic::Ordering::Relaxed);
677        self.silence_for().min(self.since(busy))
678    }
679    pub fn cpu_state(&self) -> CpuState {
680        match self.cpu.load(std::sync::atomic::Ordering::Relaxed) {
681            1 => CpuState::Waiting,
682            2 => CpuState::Measuring,
683            3 => CpuState::Unavailable,
684            _ => CpuState::Off,
685        }
686    }
687    fn set_cpu_state(&self, s: CpuState) {
688        self.cpu
689            .store(s as u8, std::sync::atomic::Ordering::Relaxed);
690    }
691    /// The last measured rate in thousandths of a core, while it is fresh:
692    /// `None` once two sampling intervals have passed without a complete
693    /// window, so a display never keeps showing "busy" on stale data.
694    pub fn fresh_rate(&self) -> Option<u32> {
695        if self.cpu_state() != CpuState::Measuring {
696            return None;
697        }
698        let end = self
699            .last_measured
700            .load(std::sync::atomic::Ordering::Relaxed);
701        if end == 0 {
702            return None;
703        }
704        let every = u64::from(self.interval_ms.load(std::sync::atomic::Ordering::Relaxed));
705        let stale = std::time::Duration::from_millis(2 * every.max(1));
706        (self.since(end - 1) <= stale)
707            .then(|| self.rate_milli.load(std::sync::atomic::Ordering::Relaxed))
708    }
709    /// What the CPU side can honestly say at a kill. "Measured idle" names
710    /// the unbroken span of complete measurements it rests on — sampling
711    /// starts only after a stretch of silence, so that span is always shorter
712    /// than the silence itself, and nothing is claimed about the rest.
713    pub fn verdict(&self) -> CpuVerdict {
714        match self.cpu_state() {
715            CpuState::Off => return CpuVerdict::NotSampled,
716            CpuState::Waiting | CpuState::Unavailable => return CpuVerdict::Unmeasured,
717            CpuState::Measuring => {}
718        }
719        if let Some(rate) = self.fresh_rate().filter(|r| *r >= BUSY_MILLI_CORES) {
720            return CpuVerdict::BusyAtKill(rate);
721        }
722        let since = self
723            .measured_since
724            .load(std::sync::atomic::Ordering::Relaxed);
725        match (since, self.fresh_rate()) {
726            (s, Some(_)) if s != 0 => CpuVerdict::MeasuredIdle(self.since(s - 1).as_secs()),
727            _ => CpuVerdict::Unmeasured,
728        }
729    }
730    /// Feed one sampler observation in. `interval` is the sampling period,
731    /// kept so displays can tell a fresh rate from a stale one.
732    pub fn record(
733        &self,
734        obs: crate::proctree::Observation,
735        at: std::time::Instant,
736        interval: std::time::Duration,
737    ) {
738        use std::sync::atomic::Ordering::Relaxed;
739        self.interval_ms.store(
740            u32::try_from(interval.as_millis()).unwrap_or(u32::MAX),
741            Relaxed,
742        );
743        match obs {
744            crate::proctree::Observation::Baseline => {
745                self.measured_since.store(self.offset(at) + 1, Relaxed);
746                self.set_cpu_state(CpuState::Waiting);
747            }
748            crate::proctree::Observation::Window(w) => {
749                let milli = w.milli_cores();
750                self.rate_milli.store(milli, Relaxed);
751                self.last_measured.store(self.offset(w.end) + 1, Relaxed);
752                if milli >= BUSY_MILLI_CORES {
753                    // The window's START: a burst buys one window, not a
754                    // whole new budget.
755                    self.last_busy.fetch_max(self.offset(w.start), Relaxed);
756                }
757                if w.gapped {
758                    // Busy is still busy, but a gap is not a measurement:
759                    // the measured-idle span starts over at the gap's end,
760                    // so the claim never covers what was not seen.
761                    self.measured_since.store(self.offset(w.end) + 1, Relaxed);
762                }
763                self.set_cpu_state(CpuState::Measuring);
764            }
765            // A skipped sample changes nothing: the rate ages and goes
766            // stale on its own if the next complete one is late.
767            crate::proctree::Observation::Skipped => {}
768            crate::proctree::Observation::Unmeasured => {
769                self.measured_since.store(0, Relaxed);
770                self.set_cpu_state(CpuState::Unavailable);
771            }
772        }
773    }
774    /// Sampling is on for this command.
775    pub fn enable_cpu(&self) {
776        self.set_cpu_state(CpuState::Waiting);
777    }
778    /// Which silence budget applies right now, from what the sampler can
779    /// claim: see [`CpuGate`].
780    pub fn gate(&self) -> CpuGate {
781        match self.verdict() {
782            CpuVerdict::NotSampled => CpuGate::NotSampled,
783            CpuVerdict::MeasuredIdle(_) | CpuVerdict::BusyAtKill(_) => CpuGate::Measured,
784            CpuVerdict::Unmeasured => CpuGate::Unmeasured,
785        }
786    }
787}
788
789/// What the kill decision may rest on from the CPU side (ADR-0009). Not
790/// sampled at all: the silence-only rule, as ever. Measured: the silence
791/// budget, because "silent and idle" was actually observed. Unmeasured —
792/// sampling is on but the last sample was late, partial, or has not come
793/// yet: the EXTENDED budget, `amont.idleTimeout × amont.idleLoadScale`,
794/// which is bounded even when the ceiling is off, and never the bare
795/// silence budget, because that would kill on a measurement nobody made.
796#[derive(Debug, Clone, Copy, PartialEq, Eq)]
797pub enum CpuGate {
798    NotSampled,
799    Measured,
800    Unmeasured,
801}
802
803/// What the CPU sampler could say when a command was killed.
804#[derive(Debug, Clone, Copy, PartialEq, Eq)]
805pub enum CpuVerdict {
806    /// Not sampled here (knob off, no budget, platform): silence alone.
807    NotSampled,
808    /// An unbroken run of complete measurements, this many seconds long and
809    /// ending at the kill, all under [`BUSY_MILLI_CORES`].
810    MeasuredIdle(u64),
811    /// Sampling was on but could not measure the whole budget.
812    Unmeasured,
813    /// Its tree was measurably busy at the kill, at this many thousandths
814    /// of a core.
815    BusyAtKill(u32),
816}
817
818/// `milli` thousandths of a core as people read it: `~3.9 cores`.
819pub fn cores(milli: u32) -> String {
820    format!("~{}.{} cores", milli / 1000, (milli % 1000) / 100)
821}
822
823/// The deadline for a network PROBE — an `ls-remote` asked before the real
824/// work, not the work itself. Capped at 30s below [`check_timeout`]: a
825/// probe answers in a second or two when the network is there at all, and
826/// a healthy `amont.timeout` of ten minutes is sized for a test suite, not
827/// for deciding whether the remote is reachable. Shrinking `amont.timeout`
828/// below the cap shrinks this too, and `0` keeps meaning no deadline —
829/// somebody who disabled the clock disabled all of it.
830pub fn network_probe_budget(settings: &crate::config::Settings) -> u64 {
831    match check_timeout(settings) {
832        0 => 0,
833        t => t.min(30),
834    }
835}
836
837/// Which clock killed a command.
838#[derive(Debug, Clone, Copy, PartialEq, Eq)]
839pub enum Why {
840    /// The wall-clock ceiling, `amont.timeout`, in seconds.
841    Ceiling(u64),
842    /// The silence budget, `amont.idleTimeout`, in seconds.
843    Silence(u64),
844    /// A declared wait outlived `amont.lockWait` (or, with that at 0 and
845    /// the ceiling off, the extended silence budget), in seconds.
846    Waited(crate::hooks::wait::WaitKind, u64),
847}
848
849/// A command killed by a clock — what happened, said with enough to tell
850/// "slow" from "stuck", which is the whole reason there are two clocks.
851#[derive(Debug, Clone)]
852pub struct Killed {
853    pub why: Why,
854    /// How long it had been running.
855    pub ran_secs: u64,
856    /// How long since its last output; `None` when the output was not ours
857    /// to observe (inherited stdio).
858    pub quiet_secs: Option<u64>,
859    /// What its CPU was doing, as far as it was measured.
860    pub cpu: CpuVerdict,
861    /// The silence budget it ran under, in seconds (0 = off). With
862    /// `quiet_secs` it says whether CPU work is what kept a silent command
863    /// alive past that budget.
864    pub idle_secs: u64,
865    /// The declared wait it was in at the kill, and for how long.
866    pub waiting: Option<(crate::hooks::wait::WaitKind, u64)>,
867    /// Its last non-empty stderr line, colour stripped and clipped to
868    /// [`LAST_LINE_CHARS`]: what decides a retry, and what the message may
869    /// quote.
870    pub last_line: Option<String>,
871    /// The host's load at the kill, with the factor it stretched the
872    /// silence budget by, when it stretched it at all.
873    pub load: Option<(crate::load::Load, u32)>,
874}
875
876/// The budgets one wait is judged under — the inputs to [`judge`] that do
877/// not move while the command runs.
878#[derive(Debug, Clone, Copy, PartialEq, Eq)]
879pub struct Clocks {
880    /// `amont.timeout`; `None` when off.
881    pub ceiling: Option<u64>,
882    /// `amont.idleTimeout`; `None` when off or when nobody watches the
883    /// output.
884    pub silence: Option<u64>,
885    /// `amont.lockWait`.
886    pub lock_wait: LockWait,
887    /// The bound a declared wait falls back to when `lock_wait` says "until
888    /// the ceiling" and the ceiling is off: the extended silence budget,
889    /// `None` when silence is off too.
890    pub extended: Option<u64>,
891    /// `amont.idleLoadScale`: how far the host's load may stretch
892    /// `silence`; 1 means not at all.
893    pub scale: u64,
894}
895
896impl Clocks {
897    /// The ceiling alone: inherited stdio, where nobody sees the bytes.
898    pub fn ceiling_only(wall_secs: u64) -> Clocks {
899        Clocks {
900            ceiling: (wall_secs > 0).then_some(wall_secs),
901            silence: None,
902            lock_wait: LockWait::UntilCeiling,
903            extended: None,
904            scale: 1,
905        }
906    }
907
908    /// Every clock, from the settings. `idle_secs` is the silence budget
909    /// the caller resolved (0 = off).
910    pub fn from_settings(settings: &crate::config::Settings, idle_secs: u64) -> Clocks {
911        let wall = check_timeout(settings);
912        let scale = idle_load_scale(settings);
913        Clocks {
914            ceiling: (wall > 0).then_some(wall),
915            silence: (idle_secs > 0).then_some(idle_secs),
916            lock_wait: lock_wait(settings),
917            extended: (idle_secs > 0).then(|| idle_secs.saturating_mul(scale)),
918            scale,
919        }
920    }
921}
922
923/// How often the wait loop re-reads the host's load.
924const LOAD_EVERY: std::time::Duration = std::time::Duration::from_secs(5);
925
926/// `amont.idleLoadScale`: how far the silence budget may stretch, as a
927/// factor — under load (ADR-0009, the load-scaled budget) and whenever the
928/// CPU could not be measured (the extended budget, `idleTimeout × this`).
929/// Default 4, `1` disables the stretch, range 1..=16. A HOST key: read from
930/// global or system config only, never from a repository, because it
931/// describes the machine and two repositories must not disagree about it.
932pub fn idle_load_scale(settings: &crate::config::Settings) -> u64 {
933    *settings.idle_load_scale.get_or_init(|| {
934        crate::config::host_integer_or(settings, "amont.idleLoadScale", 4, 1..=16) as u64
935    })
936}
937
938/// What became of a command run under the deadline.
939pub enum Ran {
940    Status(std::process::ExitStatus),
941    /// Killed by a clock; see [`Killed`].
942    TimedOut(Killed),
943}
944
945/// `cmd.status()`, bounded by [`check_timeout`].
946///
947/// Without a bound, one hung tool — a linter deadlocked on a lock file, a
948/// plugin doing network I/O — blocked the commit FOREVER, and it hung inside
949/// the index-fidelity hold: the user's unstaged changes parked in `$GIT_DIR`,
950/// their tree showing staged content only, for as long as they were willing
951/// to wait. The learned response to that is `--no-verify`, permanently —
952/// which disarms every check to escape one.
953///
954/// The kill reaches the direct child only. A grandchild that detached
955/// survives, orphaned — but the COMMIT is no longer hostage to it, which is
956/// the property that matters.
957pub fn status_within(
958    settings: &crate::config::Settings,
959    cmd: &mut Command,
960) -> std::io::Result<Ran> {
961    // The same host-slot wait as the observed runners: a check run without
962    // a live stage (one check by name, `amont.progress false`) still queues.
963    if crate::host_slots::before_spawn(settings) {
964        cmd.env(crate::host_slots::HELD_ENV, "held");
965    }
966    status_within_secs(cmd, check_timeout(settings))
967}
968
969/// [`status_within`] with an explicit ceiling — the testable seam. The
970/// output is inherited, so nobody sees the bytes and the silence budget
971/// cannot apply; the ceiling is the only clock.
972pub fn status_within_secs(cmd: &mut Command, budget_secs: u64) -> std::io::Result<Ran> {
973    if budget_secs == 0 {
974        return cmd.status().map(Ran::Status);
975    }
976    let mut child = cmd.spawn()?;
977    wait_within(&mut child, Clocks::ceiling_only(budget_secs), None)
978}
979
980/// Spawn `cmd` with both streams piped, hand every chunk to `on_output` as
981/// it arrives, and wait under BOTH clocks — the reader threads are what
982/// make the silence budget observable. The shared runner behind the
983/// streamed, captured and discarded variants.
984fn run_observed(
985    settings: &crate::config::Settings,
986    cmd: &mut Command,
987    on_output: impl Fn(&[u8]) + Send + Sync + 'static,
988    ceiling_left: Option<u64>,
989) -> std::io::Result<Ran> {
990    // A heavy check's first tool waits here for a host slot (ADR-0009);
991    // its clocks start at the spawn below, after the wait.
992    if crate::host_slots::before_spawn(settings) {
993        cmd.env(crate::host_slots::HELD_ENV, "held");
994    }
995    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
996    let activity = Activity::new();
997    let on_output = std::sync::Arc::new(on_output);
998    let mut child = cmd.spawn()?;
999    // The silence is the CHILD's, so its clock starts when the child does:
1000    // a spawn that itself took a second on a loaded machine is not a
1001    // second the tool spent saying nothing.
1002    activity.touch();
1003    let mut readers = Vec::new();
1004    // stderr is where cargo and uv print their status, so only its lines
1005    // are read for wait markers: a test that prints the words on stdout
1006    // must not pause its own clock. A stdout chunk still ENDS a wait — the
1007    // tool is visibly alive.
1008    let pipes = [
1009        (
1010            child
1011                .stdout
1012                .take()
1013                .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
1014            false,
1015        ),
1016        (
1017            child
1018                .stderr
1019                .take()
1020                .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
1021            true,
1022        ),
1023    ];
1024    for (pipe, is_stderr) in pipes {
1025        let Some(pipe) = pipe else { continue };
1026        let activity = std::sync::Arc::clone(&activity);
1027        let on_output = std::sync::Arc::clone(&on_output);
1028        readers.push(std::thread::spawn(move || {
1029            let mut pipe = pipe;
1030            let mut chunk = [0u8; 4096];
1031            let mut framer = crate::hooks::wait::LineFramer::default();
1032            loop {
1033                match std::io::Read::read(&mut pipe, &mut chunk) {
1034                    Ok(0) | Err(_) => break,
1035                    Ok(n) => {
1036                        activity.touch();
1037                        if is_stderr {
1038                            for line in framer.feed(&chunk[..n]) {
1039                                activity.stderr_line(&line);
1040                            }
1041                        } else {
1042                            activity.end_wait();
1043                        }
1044                        on_output(&chunk[..n]);
1045                    }
1046                }
1047            }
1048        }));
1049    }
1050    // The displays read the same clocks the kill decision does.
1051    let _attached = crate::live::current_sink()
1052        .map(|(stage, idx)| stage.attach(idx, std::sync::Arc::clone(&activity)));
1053    let idle = idle_timeout(settings);
1054    let sampler = (idle > 0 && idle_cpu_credit(settings) && crate::proctree::SUPPORTED)
1055        .then(|| CpuSampler::start(child.id(), std::sync::Arc::clone(&activity), idle));
1056    let mut clocks = Clocks::from_settings(settings, idle);
1057    if let Some(left) = ceiling_left {
1058        // A retry runs under what the first attempt left of the ceiling:
1059        // both attempts together answer to one `amont.timeout`.
1060        clocks.ceiling = Some(left.max(1));
1061    }
1062    let ran = wait_within(&mut child, clocks, Some(&activity));
1063    if let Some(s) = sampler {
1064        s.stop();
1065    }
1066    for r in readers {
1067        let _ = r.join();
1068    }
1069    // A check that passed after sitting on a lock says so once: the
1070    // reader of a slow commit learns where the minutes went, and a run that
1071    // would once have been killed leaves a trace of why it no longer is.
1072    if let Ok(Ran::Status(_)) = &ran {
1073        let waited = activity.waited_total();
1074        if waited >= std::time::Duration::from_secs(1) {
1075            let what = activity
1076                .last_wait_kind()
1077                .map_or("a lock", crate::hooks::wait::WaitKind::describe);
1078            say(&format!(
1079                "  (waited {} for {what})",
1080                human_secs(waited.as_secs())
1081            ));
1082        }
1083    }
1084    ran
1085}
1086
1087/// The CPU half of the silence budget (ADR-0008): a thread that, while the
1088/// command is silent, snapshots its process tree and records whether it is
1089/// doing measurable work. It runs BESIDE the wait loop, never inside it —
1090/// the loop only reads what this publishes — so nothing a snapshot does can
1091/// delay the ceiling.
1092struct CpuSampler {
1093    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
1094    handle: std::thread::JoinHandle<()>,
1095}
1096
1097impl CpuSampler {
1098    fn start(pid: u32, activity: std::sync::Arc<Activity>, idle_secs: u64) -> CpuSampler {
1099        activity.enable_cpu();
1100        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1101        let flag = std::sync::Arc::clone(&stop);
1102        let handle = std::thread::Builder::new()
1103            .name("amont-cpu".into())
1104            .spawn(move || sample_loop(pid, &activity, idle_secs, &flag))
1105            .expect("spawn the CPU sampler thread");
1106        CpuSampler { stop, handle }
1107    }
1108
1109    /// Ask it to stop and wait a bounded second for it. A snapshot is itself
1110    /// bounded, so it always stops sooner; if it somehow did not, it is left
1111    /// to finish on its own rather than holding the check.
1112    fn stop(self) {
1113        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
1114        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
1115        while !self.handle.is_finished() && std::time::Instant::now() < deadline {
1116            std::thread::sleep(std::time::Duration::from_millis(10));
1117        }
1118        if self.handle.is_finished() {
1119            let _ = self.handle.join();
1120        }
1121    }
1122}
1123
1124/// When sampling starts and how often it repeats, from the silence budget:
1125/// quiet for `max(250 ms, min(30 s, budget/3))`, then every
1126/// `clamp(budget/4, 250 ms, 10 s)` — so even a one-second budget is sampled
1127/// several times before it runs out.
1128pub fn sampling_schedule(idle_secs: u64) -> (std::time::Duration, std::time::Duration) {
1129    let ms = std::time::Duration::from_millis;
1130    let budget = std::time::Duration::from_secs(idle_secs);
1131    let first = (budget / 3)
1132        .min(std::time::Duration::from_secs(30))
1133        .max(ms(250));
1134    let every = (budget / 4).clamp(ms(250), std::time::Duration::from_secs(10));
1135    (first, every)
1136}
1137
1138fn sample_loop(
1139    pid: u32,
1140    activity: &Activity,
1141    idle_secs: u64,
1142    stop: &std::sync::atomic::AtomicBool,
1143) {
1144    use std::sync::atomic::Ordering::Relaxed;
1145    let (first, every) = sampling_schedule(idle_secs);
1146    let mut limits = crate::proctree::Limits::default();
1147    // A diagnostic, and the seam the timing tests use to force a partial
1148    // snapshot: cap the walk at this many processes.
1149    if let Some(n) = std::env::var("AMONT_CPU_MAX_PROCS")
1150        .ok()
1151        .and_then(|v| v.trim().parse::<usize>().ok())
1152    {
1153        limits.max_procs = n;
1154    }
1155    let trace = std::env::var_os("AMONT_CPU_TRACE");
1156    let mut tracker = crate::proctree::Tracker::default();
1157    let nap = |d: std::time::Duration| {
1158        let until = std::time::Instant::now() + d;
1159        while !stop.load(Relaxed) && std::time::Instant::now() < until {
1160            std::thread::sleep(std::time::Duration::from_millis(50));
1161        }
1162    };
1163    while !stop.load(Relaxed) {
1164        // The silence the clock counts, not the raw output silence: during
1165        // a declared wait there is nothing to prove, and no CPU is sampled.
1166        if activity.silence_for() < first {
1167            // Talking: nothing to prove, and the next quiet stretch starts
1168            // from a fresh baseline rather than a stale one.
1169            tracker = crate::proctree::Tracker::default();
1170            nap(std::time::Duration::from_millis(100));
1171            continue;
1172        }
1173        let snap = crate::proctree::snapshot(pid, &tracker.seen(), &limits);
1174        let at = std::time::Instant::now();
1175        let traced = trace.as_ref().map(|_| match &snap {
1176            crate::proctree::Snapshot::Complete(procs) => procs.clone(),
1177            _ => Vec::new(),
1178        });
1179        let obs = tracker.observe(at, snap);
1180        if let (Some(path), Some(procs)) = (&trace, traced) {
1181            trace_sample(path, pid, &procs, &obs);
1182        }
1183        activity.record(obs, at, every);
1184        nap(every);
1185    }
1186}
1187
1188/// `AMONT_CPU_TRACE=<file>`: append what each sample saw — one
1189/// `pid start ppid cpu_ns` line per process of a complete snapshot, then a
1190/// `# root <pid> <observation>` line. A diagnostic, and the seam the timing
1191/// tests use to know a worker was seen before they orphan it (they match
1192/// the leading pid).
1193fn trace_sample(
1194    path: &std::ffi::OsStr,
1195    root: u32,
1196    procs: &[crate::proctree::Proc],
1197    obs: &crate::proctree::Observation,
1198) {
1199    use std::io::Write;
1200    let Ok(mut f) = std::fs::OpenOptions::new()
1201        .create(true)
1202        .append(true)
1203        .open(path)
1204    else {
1205        return;
1206    };
1207    let mut text = String::new();
1208    for p in procs {
1209        text.push_str(&format!(
1210            "{} {} {} {}\n",
1211            p.id.pid, p.id.start, p.ppid, p.cpu_ns
1212        ));
1213    }
1214    let obs = match obs {
1215        crate::proctree::Observation::Window(w) => {
1216            format!("window {} milli-cores", w.milli_cores())
1217        }
1218        other => format!("{other:?}").to_lowercase(),
1219    };
1220    text.push_str(&format!("# root {root} {obs}\n"));
1221    let _ = f.write_all(text.as_bytes());
1222}
1223
1224/// [`status_within`], with the child's stdout and stderr CAPTURED into the
1225/// calling check's slot instead of inherited — the other half of one-check-
1226/// one-block: a linter's twelve lines used to land on the shared terminal
1227/// between two other checks' lines. Falls back to plain [`status_within`]
1228/// when no slot is installed on this thread (`amont.progress false`, or a
1229/// spawn outside a stage), which is byte-for-byte the old behaviour.
1230///
1231/// stdout and stderr merge in ARRIVAL order inside the block, which is what
1232/// the terminal showed before. The readers are threads, not processes, and
1233/// they are joined before the status is returned so a block can never grow
1234/// after its check finished.
1235pub fn status_streamed(
1236    settings: &crate::config::Settings,
1237    cmd: &mut Command,
1238    retry: Retry,
1239) -> std::io::Result<Ran> {
1240    let Some((stage, idx)) = crate::live::current_sink() else {
1241        return status_within(settings, cmd);
1242    };
1243    if crate::live::watching() {
1244        // The block lands on a real terminal but the tool sees a pipe and
1245        // would strip its colors; the big three opt-in knobs put them back.
1246        cmd.env("FORCE_COLOR", "1")
1247            .env("CLICOLOR_FORCE", "1")
1248            .env("CARGO_TERM_COLOR", "always");
1249    }
1250    let first = run_observed(
1251        settings,
1252        cmd,
1253        {
1254            let stage = std::sync::Arc::clone(&stage);
1255            move |bytes| stage.append_raw(idx, bytes)
1256        },
1257        None,
1258    );
1259    let Ok(Ran::TimedOut(k)) = &first else {
1260        return first;
1261    };
1262    let Some(left) = retry_budget(retry, k, check_timeout(settings)) else {
1263        return first;
1264    };
1265    // The check's name (`clippy`), which is what the reader knows; the
1266    // program (`cargo`) only when no check is running on this thread.
1267    let what = crate::host_slots::current_check()
1268        .unwrap_or_else(|| cmd.get_program().to_string_lossy().into_owned());
1269    say(&format!(
1270        "{} was killed while it looked like it was waiting ({}); retrying once{}.",
1271        hl(&what),
1272        k.last_line.as_deref().unwrap_or(""),
1273        match left {
1274            Some(s) => format!(" with {} left", human_secs(s)),
1275            None => String::new(),
1276        }
1277    ));
1278    run_observed(
1279        settings,
1280        cmd,
1281        move |bytes| stage.append_raw(idx, bytes),
1282        left,
1283    )
1284}
1285
1286/// Whether a check's tool may be run once more after a kill (ADR-0009).
1287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1288pub enum Retry {
1289    /// A built-in check: its tools are safe to run twice.
1290    Once,
1291    /// A declared external: a user's command may not be safe to run twice.
1292    Never,
1293}
1294
1295/// Whether a kill earns the one retry, and with how much ceiling left
1296/// (`Some(None)`: the ceiling is off). Only after a SILENCE kill whose last
1297/// line reads like a wait — never after a declared wait outlived its own
1298/// budget, nor at the ceiling — and only while the ceiling has at least one
1299/// silence budget left. Pure.
1300pub fn retry_budget(retry: Retry, k: &Killed, ceiling: u64) -> Option<Option<u64>> {
1301    if retry == Retry::Never || !matches!(k.why, Why::Silence(_)) {
1302        return None;
1303    }
1304    if !k
1305        .last_line
1306        .as_deref()
1307        .is_some_and(crate::hooks::wait::looks_like_wait)
1308    {
1309        return None;
1310    }
1311    if ceiling == 0 {
1312        return Some(None);
1313    }
1314    let left = ceiling.saturating_sub(k.ran_secs);
1315    (left >= k.idle_secs.max(1)).then_some(Some(left))
1316}
1317
1318/// Run to completion under the `amont.timeout` deadline with stdout and
1319/// stderr CAPTURED into a string the caller can parse — what the audit
1320/// checks need: their verdict lives in the tool's output, not its exit
1321/// code alone. Arrival-ordered merge of both streams, like
1322/// [`status_streamed`]'s blocks. `None` when the child cannot be spawned.
1323pub fn capture_within(
1324    settings: &crate::config::Settings,
1325    cmd: &mut Command,
1326) -> Option<(Ran, String)> {
1327    let text = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
1328    let sink = std::sync::Arc::clone(&text);
1329    let ran = run_observed(
1330        settings,
1331        cmd,
1332        move |bytes| {
1333            sink.lock()
1334                .unwrap_or_else(|p| p.into_inner())
1335                .push_str(&String::from_utf8_lossy(bytes));
1336        },
1337        None,
1338    )
1339    .ok()?;
1340    let text = std::sync::Arc::try_unwrap(text)
1341        .map(|m| m.into_inner().unwrap_or_else(|p| p.into_inner()))
1342        .unwrap_or_default();
1343    Some((ran, text))
1344}
1345
1346/// The wait over an already-spawned child — shared by every runner. The
1347/// silence budget in `clocks` applies only when there is an [`Activity`] to
1348/// consult (piped output); with inherited stdio the ceiling is the only
1349/// clock, and with that off too the child is simply waited for.
1350pub(crate) fn wait_within(
1351    child: &mut std::process::Child,
1352    clocks: Clocks,
1353    activity: Option<&Activity>,
1354) -> std::io::Result<Ran> {
1355    let started = std::time::Instant::now();
1356    let clocks = match activity {
1357        Some(_) => clocks,
1358        None => Clocks {
1359            silence: None,
1360            extended: None,
1361            ..clocks
1362        },
1363    };
1364    if clocks.ceiling.is_none() && clocks.silence.is_none() {
1365        return child.wait().map(Ran::Status);
1366    }
1367    // The clocks as judged: `silence` stretched by the host's load, re-read
1368    // every few seconds. The configured value stays in `clocks` for the
1369    // message.
1370    let mut live = clocks;
1371    let mut load: Option<(crate::load::Load, u32)> = None;
1372    let mut next_load = started;
1373    loop {
1374        if let Some(status) = child.try_wait()? {
1375            return Ok(Ran::Status(status));
1376        }
1377        let now = std::time::Instant::now();
1378        if let (Some(idle), Some(a)) = (clocks.silence, activity) {
1379            if clocks.scale > 1 && now >= next_load {
1380                next_load = now + LOAD_EVERY;
1381                if let Some(l) = crate::load::read() {
1382                    let factor = l.factor_milli(clocks.scale);
1383                    let applied = crate::load::scaled_budget(idle, l, clocks.scale, clocks.ceiling);
1384                    live.silence = Some(applied);
1385                    a.set_load(applied, l, factor);
1386                    load = (factor > 1000).then_some((l, factor));
1387                }
1388            }
1389        }
1390        // Judged on "silent AND idle on CPU"; equal to plain silence when CPU
1391        // is not sampled, and zero during a declared wait.
1392        let quiet = activity.map(|a| a.still_for());
1393        let waiting = activity.and_then(Activity::waiting);
1394        let gate = activity.map_or(CpuGate::NotSampled, Activity::gate);
1395        let why = judge(now.duration_since(started), quiet, waiting, gate, &live);
1396        if let Some(why) = why {
1397            let _ = child.kill();
1398            let _ = child.wait();
1399            return Ok(Ran::TimedOut(Killed {
1400                why,
1401                ran_secs: now.duration_since(started).as_secs(),
1402                // The true OUTPUT silence, for the message — not the
1403                // still-time the verdict was judged on.
1404                quiet_secs: activity.map(|a| a.quiet_for().as_secs()),
1405                cpu: activity.map_or(CpuVerdict::NotSampled, Activity::verdict),
1406                idle_secs: clocks.silence.unwrap_or(0),
1407                waiting: waiting.map(|(k, d)| (k, d.as_secs())),
1408                last_line: activity.and_then(Activity::last_line),
1409                load,
1410            }));
1411        }
1412        std::thread::sleep(std::time::Duration::from_millis(25));
1413    }
1414}
1415
1416/// Which clock, if any, has fired — the decision, with no process or
1417/// clock of its own so it can be tested to the second.
1418///
1419/// `ran` is how long the command has been running; `quiet` how long it has
1420/// been silent (and idle, where CPU is sampled), `None` when nobody is
1421/// watching its output; `waiting` the declared wait in progress, with its
1422/// length. The ceiling wins when several have fired: it is the larger
1423/// claim, and the message for it carries the other figures anyway. A
1424/// declared wait answers to `lock_wait`, never to the silence budget — the
1425/// tool has said what it is doing — and with `lock_wait` deferring to a
1426/// ceiling that is off, to the extended silence budget, so that nothing is
1427/// unbounded. `cpu` picks which silence budget applies: the plain one when
1428/// idleness was measured or is not sampled at all, the extended one while
1429/// the sampler cannot say ([`CpuGate`]).
1430pub fn judge(
1431    ran: std::time::Duration,
1432    quiet: Option<std::time::Duration>,
1433    waiting: Option<(crate::hooks::wait::WaitKind, std::time::Duration)>,
1434    cpu: CpuGate,
1435    clocks: &Clocks,
1436) -> Option<Why> {
1437    if let Some(wall) = clocks.ceiling {
1438        if ran >= std::time::Duration::from_secs(wall) {
1439            return Some(Why::Ceiling(wall));
1440        }
1441    }
1442    if let Some((kind, waited)) = waiting {
1443        let budget = match clocks.lock_wait {
1444            LockWait::Secs(s) => Some(s),
1445            LockWait::UntilCeiling if clocks.ceiling.is_some() => None,
1446            LockWait::UntilCeiling => clocks.extended,
1447        };
1448        return match budget {
1449            Some(b) if waited >= std::time::Duration::from_secs(b) => Some(Why::Waited(kind, b)),
1450            _ => None,
1451        };
1452    }
1453    let budget = match cpu {
1454        CpuGate::NotSampled | CpuGate::Measured => clocks.silence,
1455        CpuGate::Unmeasured => clocks.extended.or(clocks.silence),
1456    };
1457    if let (Some(idle), Some(q)) = (budget, quiet) {
1458        if q >= std::time::Duration::from_secs(idle) {
1459            return Some(Why::Silence(idle));
1460        }
1461    }
1462    None
1463}
1464
1465/// Say a command was killed, by which clock, and what that tells you.
1466///
1467/// The two clocks exist to answer two different questions, so the message
1468/// answers the one that was asked: silence means stuck — look at the tool;
1469/// the ceiling with recent output means slow — raise the ceiling.
1470pub fn say_timed_out(what: &str, k: Killed) {
1471    match k.why {
1472        Why::Silence(budget) => {
1473            // Why the budget is not the configured one, when it is not:
1474            // the extended budget while CPU could not be measured, or the
1475            // configured one stretched by the host's load.
1476            let stretched = match (k.cpu, k.load) {
1477                _ if budget == k.idle_secs => String::new(),
1478                (CpuVerdict::Unmeasured, _) => format!(
1479                    " (the extended budget, {} × {}: its CPU could not be measured)",
1480                    human_secs(k.idle_secs),
1481                    hl("amont.idleLoadScale")
1482                ),
1483                (_, Some((load, factor))) => format!(
1484                    " ({} stretched {} by a load average of {} on {} cores — {})",
1485                    human_secs(k.idle_secs),
1486                    crate::load::factor_text(factor),
1487                    load.avg1_text(),
1488                    load.cores,
1489                    hl("amont.idleLoadScale")
1490                ),
1491                _ => String::new(),
1492            };
1493            fail(&match k.cpu {
1494                CpuVerdict::MeasuredIdle(covered) => format!(
1495                    "{} printed nothing for {}{stretched} and did no measurable CPU work \
1496                     (< 0.1 core) in the last {} of it; killed after {} — a tool this idle \
1497                     is stuck, not slow. {} raises the silence budget (0 disables)",
1498                    hl(what),
1499                    human_secs(budget),
1500                    human_secs(covered.max(1)),
1501                    human_secs(k.ran_secs),
1502                    hl("git config amont.idleTimeout <secs>")
1503                ),
1504                _ => format!(
1505                    "{} printed nothing for {}{stretched}{} and was killed after {} — a tool \
1506                     this quiet is usually stuck, not slow. {} raises the silence budget (0 \
1507                     disables)",
1508                    hl(what),
1509                    human_secs(budget),
1510                    if k.cpu == CpuVerdict::Unmeasured && stretched.is_empty() {
1511                        " (CPU not measured)"
1512                    } else {
1513                        ""
1514                    },
1515                    human_secs(k.ran_secs),
1516                    hl("git config amont.idleTimeout <secs>")
1517                ),
1518            })
1519        }
1520        Why::Waited(kind, budget) => fail(&format!(
1521            "{} waited {} for {} and was killed after {} — {}. {} raises the wait budget \
1522             (0: until the ceiling)",
1523            hl(what),
1524            human_secs(budget),
1525            kind.describe(),
1526            human_secs(k.ran_secs),
1527            kind.holders(),
1528            hl("git config amont.lockWait <secs>")
1529        )),
1530        Why::Ceiling(budget) => {
1531            let verdict = match (k.quiet_secs, k.cpu) {
1532                (_, _) if k.waiting.is_some() => {
1533                    let (kind, w) = k.waiting.expect("checked");
1534                    format!(
1535                        " It was waiting for {} for the last {} — {}.",
1536                        kind.describe(),
1537                        human_secs(w),
1538                        kind.holders()
1539                    )
1540                }
1541                (Some(q), CpuVerdict::BusyAtKill(m)) if k.idle_secs > 0 && q >= k.idle_secs => {
1542                    format!(
1543                        " It printed nothing for the last {} but kept its CPU busy ({}), so the \
1544                     silence budget did not stop it: a busy loop, or a tool that prints only \
1545                     at the end (give it a per-file reporter). {} kills quiet runs at the \
1546                     silence budget whatever their CPU.",
1547                        human_secs(q),
1548                        cores(m),
1549                        hl("git config amont.idleCpuCredit false")
1550                    )
1551                }
1552                (Some(q), CpuVerdict::Unmeasured) if k.idle_secs > 0 && q >= k.idle_secs => {
1553                    format!(
1554                        " It printed nothing for the last {} and its CPU could not be measured, \
1555                         so only the extended silence budget applied. {} kills quiet runs at \
1556                         the silence budget whatever their CPU.",
1557                        human_secs(q),
1558                        hl("git config amont.idleCpuCredit false")
1559                    )
1560                }
1561                (Some(q), _) if q < 30 => format!(
1562                    " It was still printing ({} since its last line): slow, not stuck.",
1563                    human_secs(q)
1564                ),
1565                (Some(q), _) => format!(" Its last output was {} ago.", human_secs(q)),
1566                (None, _) => String::new(),
1567            };
1568            fail(&format!(
1569                "{} timed out: ran for {} and was killed at the ceiling. {} raises it \
1570                 (0 disables).{verdict}",
1571                hl(what),
1572                human_secs(budget),
1573                hl("git config amont.timeout <secs>")
1574            ))
1575        }
1576    }
1577}
1578
1579/// [`status_within`], collapsed to "did it exit 0" — the shape the one-shot
1580/// tool spawns want. A timeout says so, names `what`, and reads as failure.
1581pub fn bounded_success(settings: &crate::config::Settings, cmd: &mut Command, what: &str) -> bool {
1582    match status_streamed(settings, cmd, Retry::Once) {
1583        Ok(Ran::Status(s)) => s.success(),
1584        Ok(Ran::TimedOut(b)) => {
1585            say_timed_out(what, b);
1586            false
1587        }
1588        Err(_) => false,
1589    }
1590}
1591
1592/// Run `argv` from `root`, inheriting stdio. True when it exits 0.
1593pub fn run(
1594    settings: &crate::config::Settings,
1595    root: &str,
1596    argv: &[String],
1597    extra: &[String],
1598) -> bool {
1599    let Some((program, rest)) = argv.split_first() else {
1600        return true;
1601    };
1602    let mut cmd = Command::new(program);
1603    cmd.args(rest)
1604        .args(extra)
1605        .current_dir(root)
1606        .stdin(Stdio::null());
1607    strip_git_env(&mut cmd);
1608    bounded_success(settings, &mut cmd, program)
1609}
1610
1611/// As [`run`], but with the tool's own output discarded.
1612///
1613/// For a pass whose only job is to decide something — prettier's `--check`,
1614/// ruff's `--fix` sweep — where the offenders are printed once, by the pass
1615/// that reports them, rather than twice.
1616pub fn run_quiet(
1617    settings: &crate::config::Settings,
1618    root: &str,
1619    argv: &[String],
1620    extra: &[String],
1621) -> bool {
1622    let Some((program, rest)) = argv.split_first() else {
1623        return true;
1624    };
1625    let mut cmd = Command::new(program);
1626    cmd.args(rest)
1627        .args(extra)
1628        .current_dir(root)
1629        .stdin(Stdio::null());
1630    strip_git_env(&mut cmd);
1631    // Deliberately NOT the streamed runner: this helper's contract is that
1632    // the output is discarded, and capture would resurrect it into the
1633    // block. Observed and dropped instead of `/dev/null`, so the silence
1634    // clock still sees whether the tool is alive.
1635    match run_observed(settings, &mut cmd, |_| {}, None) {
1636        Ok(Ran::Status(s)) => s.success(),
1637        Ok(Ran::TimedOut(b)) => {
1638            say_timed_out(program, b);
1639            false
1640        }
1641        Err(_) => false,
1642    }
1643}
1644
1645/// Whether the user asked for checks to repair what they find.
1646///
1647/// OFF by default. `git config amont.fix true` turns it on, per repository,
1648/// because a hook that edits your files without being asked is a larger
1649/// surprise than one that complains — and because with index fidelity in place
1650/// the repair lands in the commit you are making, which is a bigger claim to
1651/// make on somebody's behalf than printing an error.
1652pub fn fixing_enabled(settings: &crate::config::Settings) -> bool {
1653    // Never while the file set is not the index — see `NOT_THE_INDEX`.
1654    !not_the_index() && fixing_requested(settings)
1655}
1656
1657/// What the CONFIG says, ignoring whether the current run may act on it.
1658///
1659/// Split out so `run_all` can tell the difference between "fixing is off" and
1660/// "you asked for fixing and this mode will not do it", and say the second out
1661/// loud instead of silently ignoring the key.
1662pub fn fixing_requested(settings: &crate::config::Settings) -> bool {
1663    *settings
1664        .fixing
1665        .get_or_init(|| crate::config::boolean_or(settings, "amont.fix", false))
1666}
1667
1668/// What a re-stage actually did. THREE answers, because the old `bool`
1669/// conflated two of them and the conflation shipped unformatted code.
1670///
1671/// `prettier.rs` read `if run_quiet(write) && restage(&files) { … Fixed }`. When
1672/// `git add` FAILED, `restage` returned `false` — indistinguishable from
1673/// "nothing needed staging" — so control fell through to a second `--check`
1674/// pass, which inspected the NOW-FORMATTED WORKING TREE, passed, printed
1675/// "Prettier passed" and returned `Outcome::Passed`. The index still held the
1676/// unformatted content, so the commit contained unformatted code and the hook
1677/// said it had passed. `manifest.rs` had the same shape.
1678#[derive(Debug, Clone, PartialEq, Eq)]
1679pub enum Restaged {
1680    /// No path differed from the index — nothing to do, and nothing wrong.
1681    Nothing,
1682    /// `git add` succeeded; the index now holds the repair.
1683    Staged,
1684    /// `git add` failed, carrying the paths it could not stage. The index
1685    /// holds content the fixer has already replaced on disk, so this MUST be
1686    /// loud at every call site — and naming the files is the difference
1687    /// between a message somebody can act on and one they cannot.
1688    Failed(Vec<String>),
1689}
1690
1691/// Serialises this process's own `git add` calls.
1692///
1693/// pre-commit runs its checks concurrently (`dispatch.rs`), and up to three of
1694/// them can re-stage. git takes `$GIT_DIR/index.lock` exclusively, so two
1695/// concurrent `git add`s in the same repository make one of them fail — which,
1696/// before `Restaged`, was silently read as "nothing moved". Holding this across
1697/// the `git add` removes self-contention entirely; the retry below is only for
1698/// OTHER processes.
1699static INDEX_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1700
1701/// Re-stage exactly the paths a fixer rewrote, and say what happened.
1702///
1703/// Safe ONLY because the pre-commit stage holds unstaged changes aside: the
1704/// tree contains the staged content and nothing else, so anything a formatter
1705/// touched is by definition part of this commit. Without that, re-staging would
1706/// sweep in work the author deliberately kept back.
1707pub fn restage(paths: &[String]) -> Restaged {
1708    // Belt and braces alongside `fixing_enabled`: a future fixer that forgets
1709    // the gate still cannot turn `amont run --all-files` into `git add .`.
1710    if not_the_index() {
1711        return Restaged::Nothing;
1712    }
1713    let changed: Vec<String> = paths
1714        .iter()
1715        .filter(|p| !git::succeeds(&["diff", "--quiet", "--", p]))
1716        .cloned()
1717        .collect();
1718    if changed.is_empty() {
1719        return Restaged::Nothing;
1720    }
1721    let mut args = vec!["add", "--"];
1722    args.extend(changed.iter().map(String::as_str));
1723
1724    let _serialised = INDEX_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1725    // Another PROCESS can hold `index.lock` — a `git status` from an editor, a
1726    // second hook in a linked worktree. Back off and retry rather than
1727    // reporting a transient collision as a failed repair. `git add` of the same
1728    // paths is idempotent: it records the paths' current worktree content, so
1729    // running it twice records the same thing twice and cannot double-stage.
1730    const BACKOFF_MS: [u64; 3] = [50, 150, 400];
1731    if git::succeeds(&args) {
1732        return Restaged::Staged;
1733    }
1734    for wait in BACKOFF_MS {
1735        std::thread::sleep(std::time::Duration::from_millis(wait));
1736        if git::succeeds(&args) {
1737            return Restaged::Staged;
1738        }
1739    }
1740    Restaged::Failed(changed)
1741}
1742
1743/// A check passed. THE funnel for every success line, which is what lets
1744/// `amont.quiet` swallow them in one place — see [`crate::live::quiet`].
1745pub fn ok(settings: &crate::config::Settings, msg: &str) {
1746    if crate::live::quiet(settings) {
1747        return;
1748    }
1749    crate::live::say(&format!("{} {msg}", valid_sign()));
1750}
1751pub fn fail(msg: &str) {
1752    crate::live::say(&format!("{} {msg}", error_sign()));
1753}
1754pub fn warn(msg: &str) {
1755    crate::live::say(&format!("{} {msg}", warning_sign()));
1756}
1757/// A line with no sign of its own — what a check's direct `println!` becomes,
1758/// so it lands in the check's block instead of interleaving. See `live::say`.
1759pub fn say(msg: &str) {
1760    crate::live::say(msg);
1761}
1762
1763/// Orange, for the fragments these hooks highlight.
1764pub fn hl(s: &str) -> String {
1765    crate::ui::highlight(s)
1766}
1767
1768#[cfg(test)]
1769mod tests {
1770
1771    /// A window of `milli` thousandths of a core between `start` and `end`
1772    /// (a zero-length window still reports `milli`: `milli_cores` floors the
1773    /// wall time at 1 ns).
1774    fn window(
1775        start: std::time::Instant,
1776        end: std::time::Instant,
1777        milli: u64,
1778    ) -> crate::proctree::Observation {
1779        let wall = u64::try_from(end.duration_since(start).as_nanos())
1780            .unwrap_or(u64::MAX)
1781            .max(1);
1782        let gain = wall * milli / 1000;
1783        crate::proctree::Observation::Window(crate::proctree::Window {
1784            start,
1785            end,
1786            gain_ns: gain,
1787            gapped: false,
1788        })
1789    }
1790
1791    /// A gapped window resets the measured-idle span to its own end: the
1792    /// claim never covers the gap, while a busy gapped window still counts
1793    /// as busy.
1794    #[test]
1795    fn a_gapped_window_is_never_claimed_as_measured_idle() {
1796        use super::{Activity, CpuVerdict};
1797        use crate::proctree::{Observation, Window};
1798        let s = std::time::Duration::from_secs;
1799        let every = s(10);
1800        let a = Activity::new();
1801        a.enable_cpu();
1802        let t0 = std::time::Instant::now() - s(30);
1803        a.record(Observation::Baseline, t0, every);
1804        a.record(Observation::Skipped, t0 + s(10), every);
1805        let gap_end = std::time::Instant::now();
1806        a.record(
1807            Observation::Window(Window {
1808                start: t0,
1809                end: gap_end,
1810                gain_ns: 0,
1811                gapped: true,
1812            }),
1813            gap_end,
1814            every,
1815        );
1816        // Idle, but the span rests only on what followed the gap: 0 s.
1817        assert_eq!(a.verdict(), CpuVerdict::MeasuredIdle(0));
1818        assert_eq!(a.gate(), super::CpuGate::Measured);
1819
1820        let busy = Activity::new();
1821        busy.enable_cpu();
1822        busy.record(Observation::Baseline, t0, every);
1823        busy.record(Observation::Skipped, t0 + s(10), every);
1824        let now = std::time::Instant::now();
1825        busy.record(window_gapped(t0, now, 3000), now, every);
1826        assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3000));
1827        assert!(busy.still_for() < s(1));
1828    }
1829
1830    fn window_gapped(
1831        start: std::time::Instant,
1832        end: std::time::Instant,
1833        milli: u64,
1834    ) -> crate::proctree::Observation {
1835        match window(start, end, milli) {
1836            crate::proctree::Observation::Window(w) => {
1837                crate::proctree::Observation::Window(crate::proctree::Window { gapped: true, ..w })
1838            }
1839            o => o,
1840        }
1841    }
1842
1843    /// Even the shortest budget is sampled several times before it runs out,
1844    /// and the default one starts at 30 s and repeats every 10 s.
1845    #[test]
1846    fn the_sampling_schedule_follows_the_budget_within_floors() {
1847        use super::sampling_schedule;
1848        let ms = std::time::Duration::from_millis;
1849        let third = |secs: u64| std::time::Duration::from_secs(secs) / 3;
1850        assert_eq!(sampling_schedule(1), (third(1), ms(250)));
1851        assert_eq!(sampling_schedule(2), (third(2), ms(500)));
1852        assert_eq!(sampling_schedule(120), (ms(30_000), ms(10_000)));
1853        assert_eq!(sampling_schedule(0), (ms(250), ms(250)));
1854    }
1855
1856    /// Without CPU data the still-time IS the silence; a busy window pulls it
1857    /// back to the window's start, and the output clock is left alone.
1858    #[test]
1859    fn busy_work_resets_the_still_time_but_not_the_output_silence() {
1860        use super::Activity;
1861        let a = Activity::new();
1862        a.touch();
1863        std::thread::sleep(std::time::Duration::from_millis(60));
1864        let quiet = a.quiet_for();
1865        assert!(a.still_for() >= quiet.saturating_sub(std::time::Duration::from_millis(5)));
1866        a.enable_cpu();
1867        let now = std::time::Instant::now();
1868        a.record(
1869            window(now - std::time::Duration::from_millis(10), now, 2000),
1870            now,
1871            std::time::Duration::from_secs(1),
1872        );
1873        assert!(a.still_for() < std::time::Duration::from_millis(40));
1874        assert!(a.quiet_for() >= std::time::Duration::from_millis(60));
1875    }
1876
1877    /// What the kill message may claim. "Measured idle" names the unbroken
1878    /// span of complete measurements behind it; a broken run is unmeasured;
1879    /// a fresh busy window is reported as busy; no sampling says nothing.
1880    #[test]
1881    fn the_cpu_verdict_claims_only_what_was_measured() {
1882        use super::{Activity, CpuVerdict};
1883        use crate::proctree::Observation;
1884        let s = std::time::Duration::from_secs;
1885        let every = s(10);
1886
1887        let off = Activity::new();
1888        assert_eq!(off.verdict(), CpuVerdict::NotSampled);
1889
1890        let waiting = Activity::new();
1891        waiting.enable_cpu();
1892        assert_eq!(waiting.verdict(), CpuVerdict::Unmeasured);
1893
1894        let now = std::time::Instant::now();
1895        let before = now - s(1);
1896        // A real second of complete, idle measurement: the claim names it.
1897        let idle = Activity::new();
1898        idle.enable_cpu();
1899        let t0 = std::time::Instant::now();
1900        idle.record(Observation::Baseline, t0, every);
1901        std::thread::sleep(std::time::Duration::from_millis(1050));
1902        let t1 = std::time::Instant::now();
1903        idle.record(window(t0, t1, 20), t1, every);
1904        assert_eq!(idle.verdict(), CpuVerdict::MeasuredIdle(1));
1905
1906        let busy = Activity::new();
1907        busy.enable_cpu();
1908        busy.record(Observation::Baseline, before, every);
1909        busy.record(window(before, now, 3900), now, every);
1910        assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3900));
1911
1912        let broken = Activity::new();
1913        broken.enable_cpu();
1914        broken.record(Observation::Baseline, before, every);
1915        broken.record(window(before, now, 20), now, every);
1916        broken.record(Observation::Unmeasured, now, every);
1917        assert_eq!(broken.verdict(), CpuVerdict::Unmeasured);
1918        assert_eq!(broken.gate(), super::CpuGate::Unmeasured);
1919        assert_eq!(off.gate(), super::CpuGate::NotSampled);
1920        assert_eq!(idle.gate(), super::CpuGate::Measured);
1921        assert_eq!(busy.gate(), super::CpuGate::Measured);
1922    }
1923
1924    /// A rate older than two sampling intervals is not shown, and cannot
1925    /// back a "busy" or "idle" claim.
1926    #[test]
1927    fn a_stale_rate_expires() {
1928        use super::{Activity, CpuVerdict};
1929        use crate::proctree::Observation;
1930        let a = Activity::new();
1931        a.enable_cpu();
1932        let then = std::time::Instant::now();
1933        let tick = std::time::Duration::from_millis(5);
1934        let earlier = then - std::time::Duration::from_secs(1);
1935        a.record(Observation::Baseline, earlier, tick);
1936        a.record(window(earlier, then, 3000), then, tick);
1937        std::thread::sleep(std::time::Duration::from_millis(40));
1938        assert_eq!(a.fresh_rate(), None);
1939        assert_eq!(a.verdict(), CpuVerdict::Unmeasured);
1940    }
1941
1942    #[test]
1943    fn cores_read_as_one_decimal() {
1944        assert_eq!(super::cores(3900), "~3.9 cores");
1945        assert_eq!(super::cores(420), "~0.4 cores");
1946        assert_eq!(super::cores(100), "~0.1 cores");
1947    }
1948
1949    /// The two clocks, decided to the second. A chatty command outlives any
1950    /// silence budget however long it runs; a silent one dies at the budget
1951    /// however short; a command nobody watches answers to the ceiling only.
1952    #[test]
1953    fn the_clocks_judge_silence_and_ceiling_separately() {
1954        use super::{judge, CpuGate, Why};
1955        use std::time::Duration as D;
1956        let s = D::from_secs;
1957        let c = |ceiling: Option<u64>, silence: Option<u64>| super::Clocks {
1958            ceiling,
1959            silence,
1960            lock_wait: super::LockWait::Secs(600),
1961            extended: silence,
1962            scale: 1,
1963        };
1964        // Chatty and long: past a five-second silence budget, still fine.
1965        assert_eq!(
1966            judge(
1967                s(900),
1968                Some(s(0)),
1969                None,
1970                CpuGate::NotSampled,
1971                &c(Some(3600), Some(5))
1972            ),
1973            None
1974        );
1975        assert_eq!(
1976            judge(
1977                s(900),
1978                Some(s(4)),
1979                None,
1980                CpuGate::NotSampled,
1981                &c(Some(3600), Some(5))
1982            ),
1983            None
1984        );
1985        // Silent for the budget: killed, and the silence is blamed.
1986        assert_eq!(
1987            judge(
1988                s(30),
1989                Some(s(5)),
1990                None,
1991                CpuGate::NotSampled,
1992                &c(Some(3600), Some(5))
1993            ),
1994            Some(Why::Silence(5))
1995        );
1996        // Unobserved output: the silence clock cannot run at all.
1997        assert_eq!(
1998            judge(
1999                s(900),
2000                None,
2001                None,
2002                CpuGate::NotSampled,
2003                &c(Some(3600), Some(5))
2004            ),
2005            None
2006        );
2007        // The ceiling fires on elapsed time whatever the output is doing.
2008        assert_eq!(
2009            judge(
2010                s(3600),
2011                Some(s(0)),
2012                None,
2013                CpuGate::NotSampled,
2014                &c(Some(3600), Some(120))
2015            ),
2016            Some(Why::Ceiling(3600))
2017        );
2018        // Both fired at once: the ceiling is the answer.
2019        assert_eq!(
2020            judge(
2021                s(3600),
2022                Some(s(600)),
2023                None,
2024                CpuGate::NotSampled,
2025                &c(Some(3600), Some(120))
2026            ),
2027            Some(Why::Ceiling(3600))
2028        );
2029        // Both off: nothing ever fires.
2030        assert_eq!(
2031            judge(
2032                s(86_400),
2033                Some(s(86_400)),
2034                None,
2035                CpuGate::NotSampled,
2036                &c(None, None)
2037            ),
2038            None
2039        );
2040        // Only silence on: no ceiling, however long it runs.
2041        assert_eq!(
2042            judge(
2043                s(86_400),
2044                Some(s(1)),
2045                None,
2046                CpuGate::NotSampled,
2047                &c(None, Some(120))
2048            ),
2049            None
2050        );
2051    }
2052
2053    /// A declared wait answers to `amont.lockWait` and never to the silence
2054    /// budget; at 0 it answers to the ceiling, and with the ceiling off too,
2055    /// to the extended silence budget — never to nothing.
2056    #[test]
2057    fn a_declared_wait_answers_to_its_own_budget() {
2058        use super::{judge, Clocks, CpuGate, LockWait, Why};
2059        use crate::hooks::wait::{CargoLockWhat, WaitKind};
2060        use std::time::Duration as D;
2061        let s = D::from_secs;
2062        let kind = WaitKind::CargoLock(CargoLockWhat::BuildDirectory);
2063        let clocks = Clocks {
2064            ceiling: Some(3600),
2065            silence: Some(120),
2066            lock_wait: LockWait::Secs(600),
2067            extended: Some(480),
2068            scale: 4,
2069        };
2070        // Silent for ten times the budget, but in a declared wait: fine.
2071        assert_eq!(
2072            judge(
2073                s(1300),
2074                Some(s(0)),
2075                Some((kind, s(599))),
2076                CpuGate::Measured,
2077                &clocks
2078            ),
2079            None
2080        );
2081        // The wait outlives its budget: killed, and the wait is blamed.
2082        assert_eq!(
2083            judge(
2084                s(1300),
2085                Some(s(0)),
2086                Some((kind, s(600))),
2087                CpuGate::Measured,
2088                &clocks
2089            ),
2090            Some(Why::Waited(kind, 600))
2091        );
2092        // The ceiling still wins.
2093        assert_eq!(
2094            judge(
2095                s(3600),
2096                Some(s(0)),
2097                Some((kind, s(3000))),
2098                CpuGate::Measured,
2099                &clocks
2100            ),
2101            Some(Why::Ceiling(3600))
2102        );
2103        // lockWait 0 with a ceiling: the ceiling alone bounds the wait.
2104        let until = Clocks {
2105            lock_wait: LockWait::UntilCeiling,
2106            ..clocks
2107        };
2108        assert_eq!(
2109            judge(
2110                s(3000),
2111                Some(s(0)),
2112                Some((kind, s(2900))),
2113                CpuGate::Measured,
2114                &until
2115            ),
2116            None
2117        );
2118        // lockWait 0 and no ceiling: the extended budget bounds it.
2119        let open = Clocks {
2120            ceiling: None,
2121            ..until
2122        };
2123        assert_eq!(
2124            judge(
2125                s(3000),
2126                Some(s(0)),
2127                Some((kind, s(479))),
2128                CpuGate::Measured,
2129                &open
2130            ),
2131            None
2132        );
2133        assert_eq!(
2134            judge(
2135                s(3000),
2136                Some(s(0)),
2137                Some((kind, s(480))),
2138                CpuGate::Measured,
2139                &open
2140            ),
2141            Some(Why::Waited(kind, 480))
2142        );
2143    }
2144
2145    /// One retry, only after a silence kill whose last line reads like a
2146    /// wait, only for a built-in, only with a silence budget of ceiling
2147    /// left, and under what is left.
2148    #[test]
2149    fn a_wait_like_silence_kill_earns_one_retry_under_the_remaining_ceiling() {
2150        use super::{retry_budget, CpuVerdict, Killed, Retry, Why};
2151        use crate::hooks::wait::{CargoLockWhat, WaitKind};
2152        let k = |why: Why, line: &str, ran: u64| Killed {
2153            why,
2154            ran_secs: ran,
2155            quiet_secs: Some(ran),
2156            cpu: CpuVerdict::MeasuredIdle(1),
2157            idle_secs: 120,
2158            waiting: None,
2159            last_line: Some(line.to_string()),
2160            load: None,
2161        };
2162        let wait = "waiting for lock on x";
2163        assert_eq!(
2164            retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 3600),
2165            Some(Some(3480))
2166        );
2167        assert_eq!(
2168            retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 0),
2169            Some(None)
2170        );
2171        assert_eq!(
2172            retry_budget(Retry::Never, &k(Why::Silence(120), wait, 120), 3600),
2173            None
2174        );
2175        assert_eq!(
2176            retry_budget(
2177                Retry::Once,
2178                &k(Why::Silence(120), "test_lock.py::x", 120),
2179                3600
2180            ),
2181            None
2182        );
2183        assert_eq!(
2184            retry_budget(Retry::Once, &k(Why::Ceiling(3600), wait, 3600), 3600),
2185            None
2186        );
2187        let waited = Why::Waited(WaitKind::CargoLock(CargoLockWhat::BuildDirectory), 600);
2188        assert_eq!(retry_budget(Retry::Once, &k(waited, wait, 700), 3600), None);
2189        // Less than one silence budget of ceiling left: no retry.
2190        assert_eq!(
2191            retry_budget(Retry::Once, &k(Why::Silence(120), wait, 3500), 3600),
2192            None
2193        );
2194    }
2195
2196    /// While the CPU is unmeasured the silence budget is the extended one:
2197    /// no kill before `idle × scale`, a kill at it even with the ceiling
2198    /// off; measured and not-sampled keep the plain budget.
2199    #[test]
2200    fn an_unmeasured_cpu_answers_to_the_extended_budget() {
2201        use super::{judge, Clocks, CpuGate, LockWait, Why};
2202        use std::time::Duration as D;
2203        let s = D::from_secs;
2204        let clocks = Clocks {
2205            ceiling: None,
2206            silence: Some(120),
2207            lock_wait: LockWait::Secs(600),
2208            extended: Some(480),
2209            scale: 4,
2210        };
2211        assert_eq!(
2212            judge(s(500), Some(s(300)), None, CpuGate::Unmeasured, &clocks),
2213            None
2214        );
2215        assert_eq!(
2216            judge(s(500), Some(s(479)), None, CpuGate::Unmeasured, &clocks),
2217            None
2218        );
2219        assert_eq!(
2220            judge(s(500), Some(s(480)), None, CpuGate::Unmeasured, &clocks),
2221            Some(Why::Silence(480))
2222        );
2223        assert_eq!(
2224            judge(s(500), Some(s(120)), None, CpuGate::Measured, &clocks),
2225            Some(Why::Silence(120))
2226        );
2227        assert_eq!(
2228            judge(s(500), Some(s(120)), None, CpuGate::NotSampled, &clocks),
2229            Some(Why::Silence(120))
2230        );
2231        // No extended budget configured (silence off): nothing fires.
2232        let off = Clocks {
2233            silence: None,
2234            extended: None,
2235            ..clocks
2236        };
2237        assert_eq!(
2238            judge(s(86_400), Some(s(86_400)), None, CpuGate::Unmeasured, &off),
2239            None
2240        );
2241    }
2242
2243    /// A marker line starts a wait that a second marker continues and any
2244    /// other line ends; the silence the clock counts is zero meanwhile, the
2245    /// output silence is not, and the time is banked for the note.
2246    #[test]
2247    fn a_marker_line_pauses_the_silence_clock_until_another_line() {
2248        use super::Activity;
2249        use crate::hooks::wait::{CargoLockWhat, WaitKind};
2250        let a = Activity::new();
2251        a.touch();
2252        assert_eq!(a.waiting(), None);
2253        a.stderr_line("    Blocking waiting for file lock on package cache");
2254        std::thread::sleep(std::time::Duration::from_millis(30));
2255        let (kind, waited) = a.waiting().expect("a wait is in progress");
2256        assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::PackageCache));
2257        assert!(waited >= std::time::Duration::from_millis(30));
2258        assert_eq!(a.silence_for(), std::time::Duration::ZERO);
2259        assert_eq!(a.still_for(), std::time::Duration::ZERO);
2260        assert!(a.quiet_for() >= std::time::Duration::from_millis(30));
2261        // A second marker keeps the original start, and names the new lock.
2262        a.stderr_line("\u{1b}[1m    Blocking\u{1b}[0m waiting for file lock on build directory");
2263        let (kind, again) = a.waiting().expect("still waiting");
2264        assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::BuildDirectory));
2265        assert!(again >= waited);
2266        // Any other line ends it, and the time spent is banked. The reader
2267        // touches the output clock before it frames, as here.
2268        a.touch();
2269        a.stderr_line("    Checking foo v0.1.0");
2270        assert_eq!(a.waiting(), None);
2271        assert!(a.waited_total() >= std::time::Duration::from_millis(30));
2272        assert_eq!(a.last_wait_kind(), Some(kind));
2273        assert_eq!(a.last_line().as_deref(), Some("Checking foo v0.1.0"));
2274        assert!(a.silence_for() < std::time::Duration::from_millis(20));
2275        // A stdout chunk ends a wait too.
2276        a.stderr_line("Waiting to acquire write lock for `x`");
2277        assert!(a.waiting().is_some());
2278        a.end_wait();
2279        assert_eq!(a.waiting(), None);
2280    }
2281
2282    /// The deadline kills what outlives it and reports what finished.
2283    #[cfg(unix)]
2284    #[test]
2285    fn the_deadline_kills_a_sleeper_and_spares_a_finisher() {
2286        let started = std::time::Instant::now();
2287        let mut slow = Command::new(program("sleep"));
2288        slow.arg("300").stdin(Stdio::null());
2289        match status_within_secs(&mut slow, 1) {
2290            Ok(Ran::TimedOut(Killed {
2291                why: Why::Ceiling(1),
2292                quiet_secs: None,
2293                ..
2294            })) => {}
2295            other => panic!("expected TimedOut(1), got {:?}", other.map(|_| "ran")),
2296        }
2297        assert!(
2298            started.elapsed() < std::time::Duration::from_secs(60),
2299            "the kill did not happen at the deadline"
2300        );
2301
2302        let mut quick = Command::new(program("true"));
2303        quick.stdin(Stdio::null());
2304        match status_within_secs(&mut quick, 60) {
2305            Ok(Ran::Status(s)) => assert!(s.success()),
2306            other => panic!("expected a clean exit, got {:?}", other.map(|_| "?")),
2307        }
2308    }
2309
2310    use super::*;
2311
2312    #[test]
2313    fn which_finds_a_real_binary_and_not_a_fake_one() {
2314        assert!(which("git").is_some());
2315        assert!(which("definitely-not-a-real-binary-xyz").is_none());
2316    }
2317
2318    /// On Windows a tool can exist BOTH as an extensionless shell script and as
2319    /// a .cmd/.exe in the same directory; only the latter is executable by
2320    /// CreateProcess, so the extension forms must win.
2321    #[test]
2322    #[cfg(windows)]
2323    fn windows_prefers_an_executable_extension_over_a_bare_file() {
2324        let dir = std::env::temp_dir().join("amont-which-order");
2325        let _ = std::fs::create_dir_all(&dir);
2326        std::fs::write(dir.join("faketool"), "#!/bin/sh\n").unwrap();
2327        std::fs::write(dir.join("faketool.cmd"), "@echo off\n").unwrap();
2328        // The path is PASSED, never installed into this process: see
2329        // `which_on`. The old spelling swapped the real PATH out from under
2330        // every other test in this binary for the length of the call.
2331        let found = which_on(dir.as_os_str(), "faketool").unwrap();
2332        assert!(found.ends_with(".cmd"), "got {found}");
2333        let _ = std::fs::remove_dir_all(&dir);
2334    }
2335
2336    /// "Nothing moved" and "`git add` FAILED" are different answers, and the
2337    /// old `bool` gave the same one for both.
2338    ///
2339    /// That conflation is what shipped unformatted code: `prettier.rs` read
2340    /// `if wrote && restage(&files)`, so a failed `git add` fell through to a
2341    /// second `--check` against the now-formatted WORKING TREE, which passed —
2342    /// while the INDEX still held the unformatted content the commit would
2343    /// carry.
2344    ///
2345    /// An absolute path outside any repository is a `git add` git will always
2346    /// refuse, which is the only way to reach the failing branch without
2347    /// sabotaging a real index.
2348    #[test]
2349    fn restage_distinguishes_nothing_from_failure() {
2350        // `restage` runs `git add` in the PROCESS cwd, so this test depends
2351        // on that cwd as surely as one that moves it — see `crate::TEST_CWD`.
2352        // Without the lock it ran inside whatever fixture `gate_stamp` had
2353        // moved into, and took that repository's index.lock out from under
2354        // its own commit.
2355        let _cwd = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
2356        let outside = std::env::temp_dir()
2357            .join("amont-restage-outside-any-repo")
2358            .to_string_lossy()
2359            .into_owned();
2360        assert_eq!(
2361            restage(std::slice::from_ref(&outside)),
2362            Restaged::Failed(vec![outside]),
2363            "a `git add` git refuses must report Failed, never Nothing"
2364        );
2365        assert_eq!(
2366            restage(&[]),
2367            Restaged::Nothing,
2368            "no paths is nothing to do, and nothing wrong"
2369        );
2370    }
2371
2372    /// No check may hand `Command` a bare program name.
2373    ///
2374    /// `Command::new` does NO PATHEXT resolution, so `Command::new("npm")`
2375    /// cannot execute `npm.cmd` and `Command::new("uvx")` cannot execute
2376    /// `uvx.exe`: the spawn fails with "program not found" and a
2377    /// `Severity::Block` check reports an installed tool as broken. That is the
2378    /// incident `program()` exists for, and it kept recurring — `yamllint` and
2379    /// three sites in `python_tools` were still doing it, THREE OF THEM after
2380    /// `which()` had already succeeded and discarded the answer.
2381    ///
2382    /// A source scan rather than a runtime assertion because the failure only
2383    /// reproduces on Windows, and the whole point is to catch the next one on
2384    /// every platform. Comment lines are skipped: `program()`'s own doc quotes
2385    /// the offending call. The needle is assembled from two pieces so this
2386    /// module — which the scan also reads — does not match itself.
2387    #[test]
2388    fn no_hook_spawns_a_bare_program_name() {
2389        let needle = concat!("Command", "::new(");
2390        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src/hooks");
2391        let mut scanned = 0usize;
2392        for entry in std::fs::read_dir(dir).expect("hooks dir").flatten() {
2393            let path = entry.path();
2394            if path.extension().and_then(|e| e.to_str()) != Some("rs") {
2395                continue;
2396            }
2397            scanned += 1;
2398            let src = std::fs::read_to_string(&path).expect("read a hook module");
2399            for (n, line) in src.lines().enumerate() {
2400                if line.trim_start().starts_with("//") {
2401                    continue;
2402                }
2403                let Some(after) = line.split_once(needle) else {
2404                    continue;
2405                };
2406                assert!(
2407                    !after.1.starts_with('"'),
2408                    "{}:{} spawns a bare name — route it through `program()` or \
2409                     the path `which()` already resolved: {}",
2410                    path.display(),
2411                    n + 1,
2412                    line.trim()
2413                );
2414            }
2415        }
2416        assert!(
2417            scanned > 10,
2418            "the scan found almost nothing: {scanned} files"
2419        );
2420    }
2421
2422    #[test]
2423    fn first_existing_picks_the_earliest_present_name() {
2424        let dir = std::env::temp_dir().join("amont-first-existing-test");
2425        let _ = std::fs::create_dir_all(&dir);
2426        let root = dir.to_string_lossy().into_owned();
2427        let _ = std::fs::write(dir.join("second"), "x");
2428        assert_eq!(
2429            first_existing(&root, &["first", "second", "third"]).as_deref(),
2430            Some("second")
2431        );
2432        assert_eq!(first_existing(&root, &["nope"]), None);
2433        let _ = std::fs::remove_dir_all(&dir);
2434    }
2435}