Skip to main content

greengate_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/// A copy the machine had, and what its `--version` probe said.
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub(crate) enum Ambient {
216    /// The first match on PATH, at this path.
217    Path { path: String, version: Version },
218    /// A copy `npx --no-install` already had; its probe printed this version
219    /// (npx with no copy, or a probe that failed, is no candidate at all).
220    Npx { version: String },
221}
222
223/// What a `--version` probe of an ambient tool answered.
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub(crate) enum Version {
226    Known(String),
227    /// It exited non-zero, or printed nothing shaped like a version.
228    Unknown,
229    /// It did not answer within [`PROBE_DEADLINE`].
230    TimedOut,
231}
232
233/// How long a `--version` probe may take. A probe runs before the check
234/// itself, so a tool that hangs on `--version` must not hold the commit for
235/// `amont.timeout` (an hour by default): five seconds, then its whole process
236/// group is killed (`tree_run::run_output`).
237pub(crate) const PROBE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(5);
238
239/// The repo's own copy: `<root>/node_modules/.bin`, then the main worktree's —
240/// preferred so the hook runs what CI runs (a linked worktree has no
241/// node_modules of its own, hence the git common dir).
242pub(crate) fn pinned_tool(root: &str, tool: &str) -> Option<String> {
243    // Same extension problem as `which`: an npm-installed binary is `eslint.cmd`
244    // on Windows, so the bare name misses the repo's PINNED copy and the hook
245    // silently falls through to an ambient one.
246    if let Some(p) = in_bin_dir(&format!("{root}/node_modules/.bin"), tool) {
247        return Some(p);
248    }
249    let common = git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
250    let main = Path::new(&common).parent()?;
251    in_bin_dir(&main.join("node_modules/.bin").to_string_lossy(), tool)
252}
253
254/// What the machine offered for a tool.
255enum Found {
256    Tool(Vec<String>, Ambient),
257    /// npx is there, but its `--version` probe did not answer in time.
258    NpxHung,
259    Nothing,
260}
261
262/// A copy the machine has: PATH, then one `npx --no-install` already cached.
263/// Its version is probed here, so reporting it later starts nothing.
264fn ambient_tool(root: &str, tool: &str) -> Found {
265    if let Some(path) = which(tool) {
266        let argv = vec![path.clone()];
267        let version = probe_version(&argv, root);
268        return Found::Tool(argv, Ambient::Path { path, version });
269    }
270    // `npx --no-install`: never silently download a random latest version — a
271    // hook that quietly pulls a different linter than CI uses is worse than one
272    // that skips. The probe's own output is the version, so naming it later
273    // costs no second npx.
274    if which("npx").is_none() {
275        return Found::Nothing;
276    }
277    let npx = vec![program("npx"), "--no-install".to_string(), tool.to_string()];
278    match probe_version(&npx, root) {
279        Version::Known(version) => Found::Tool(npx, Ambient::Npx { version }),
280        Version::TimedOut => Found::NpxHung,
281        // npx has no copy to offer.
282        Version::Unknown => Found::Nothing,
283    }
284}
285
286/// `<argv> --version`, bounded by [`PROBE_DEADLINE`] and run in its own
287/// process group, so a hung tool (or a child it left holding the pipe) is
288/// killed with everything it started.
289fn probe_version(argv: &[String], root: &str) -> Version {
290    static NEVER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
291    let mut probe = argv.to_vec();
292    probe.push("--version".to_string());
293    // Not `clock::scaled`: the bound is the behaviour under test, and a scaled
294    // one is shorter than a shell takes to start on a loaded machine.
295    let deadline = std::time::Instant::now() + PROBE_DEADLINE;
296    match crate::tree_run::run_output(&probe, Path::new(root), deadline, &NEVER) {
297        Ok(out) => version_in(&out).map_or(Version::Unknown, Version::Known),
298        Err(crate::tree_run::TreeRun::TimedOut) => Version::TimedOut,
299        Err(_) => Version::Unknown,
300    }
301}
302
303/// The first line of `out` that starts with a version (`v9.14.0`, `3.9.10`),
304/// without its leading `v` and cut at the first character a version does not
305/// use. Never simply the first line: the probe's stdout and stderr share one
306/// pipe, so an `npm warn …` or a node warning can come first.
307fn version_in(out: &str) -> Option<String> {
308    out.lines().find_map(|line| {
309        let word = line.trim_start();
310        let word = word.strip_prefix('v').unwrap_or(word);
311        let end = word
312            .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+')))
313            .unwrap_or(word.len());
314        let v = &word[..end];
315        let mut parts = v.splitn(3, '.');
316        let whole = |p: Option<&str>| {
317            p.is_some_and(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
318        };
319        let (major, minor) = (parts.next(), parts.next());
320        let patch_starts = parts
321            .next()
322            .is_some_and(|s| s.starts_with(|c: char| c.is_ascii_digit()));
323        (whole(major) && whole(minor) && patch_starts).then(|| v.to_string())
324    })
325}
326
327/// A JS tool as a check should treat it, from the package.json of the
328/// checkout being committed and where the binary was found (ADR-0019: a
329/// repository pins its tools, never the machine's PATH).
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub(crate) enum JsTool {
332    /// The repo's own `node_modules/.bin` copy.
333    Pinned(Vec<String>),
334    /// Not declared, and taken from PATH or npx's cache: it runs, and the
335    /// check says so with [`JsUse::warn_ambient`].
336    Ambient { argv: Vec<String>, ambient: Ambient },
337    /// Declared, but no `node_modules/.bin` has it: nothing runs, because
338    /// PATH's copy is not the version the repository asked for.
339    NotInstalled,
340    /// npx might have a copy, but its probe did not answer in time.
341    NpxHung,
342    /// Not declared and not found anywhere.
343    Missing,
344}
345
346/// A resolved JS tool and what the checkout says about installing it — the
347/// package.json read once, for both.
348pub(crate) struct JsUse {
349    pub(crate) tool: JsTool,
350    name: &'static str,
351    manager: crate::snapshot_prep::Manager,
352}
353
354/// Resolve `name` for a check. Only the root package.json of THIS checkout
355/// decides whether it is declared; the main worktree may lend a binary, never
356/// its manifest. A declared tool is looked up in `node_modules/.bin` only.
357pub(crate) fn resolve_js_tool(root: &str, name: &'static str) -> JsUse {
358    let manifest = std::fs::read_to_string(Path::new(root).join("package.json")).ok();
359    let manager = manifest
360        .as_deref()
361        .and_then(crate::snapshot_prep::declared_manager)
362        .or_else(|| crate::snapshot_prep::Manager::from_root_lockfile(Path::new(root)))
363        .unwrap_or(crate::snapshot_prep::Manager::Npm);
364    let tool = if let Some(p) = pinned_tool(root, name) {
365        JsTool::Pinned(vec![p])
366    } else if manifest
367        .as_deref()
368        .is_some_and(|text| package_json_declares(text, name))
369    {
370        JsTool::NotInstalled
371    } else {
372        match ambient_tool(root, name) {
373            Found::Tool(argv, ambient) => JsTool::Ambient { argv, ambient },
374            Found::NpxHung => JsTool::NpxHung,
375            Found::Nothing => JsTool::Missing,
376        }
377    };
378    JsUse {
379        tool,
380        name,
381        manager,
382    }
383}
384
385impl JsUse {
386    /// The two lines for an undeclared tool taken from the machine: what ran,
387    /// and the command that pins it. Kept under 80 columns for a typical
388    /// path; the root-only rule is in the docs and the CHANGELOG.
389    pub(crate) fn warn_ambient(&self, ambient: &Ambient) {
390        let name = self.name;
391        let (from, version) = match ambient {
392            Ambient::Npx { version } => {
393                ("npx's cache".to_string(), Version::Known(version.clone()))
394            }
395            Ambient::Path { path, version } => (path.clone(), version.clone()),
396        };
397        let secs = PROBE_DEADLINE.as_secs();
398        let (named, pin, note) = match &version {
399            Version::Known(v) => (format!("{name} {v}"), format!("{name}@{v}"), ""),
400            Version::Unknown => (
401                format!("{name} (unknown version)"),
402                name.to_string(),
403                " (latest, not necessarily this one)",
404            ),
405            Version::TimedOut => (
406                format!("{name} (no --version in {secs} s)"),
407                name.to_string(),
408                " (latest, not necessarily this one)",
409            ),
410        };
411        warn(&format!(
412            "{} from {} is not in the root package.json",
413            crate::ui::sanitize(&named),
414            crate::ui::sanitize(&from)
415        ));
416        warn(&format!(
417            "Pin it: {}{note}",
418            hl(&self.manager.add_dev_command(&pin))
419        ));
420    }
421
422    /// The line for a check that could not run, by why it could not; nothing
423    /// for a tool that runs.
424    pub(crate) fn warn_unavailable(&self) {
425        let name = self.name;
426        match &self.tool {
427            JsTool::NotInstalled => warn(&format!(
428                "{name} is in package.json but not installed: run {}",
429                hl(&format!("{} install", self.manager.tool()))
430            )),
431            JsTool::NpxHung => warn(&format!(
432                "npx --no-install {name} --version did not answer in {} s. Pin it: {}",
433                PROBE_DEADLINE.as_secs(),
434                hl(&self.manager.add_dev_command(name))
435            )),
436            // Installing never brings in a tool package.json does not list:
437            // the command that adds it is the one that helps.
438            JsTool::Missing => warn(&format!(
439                "{name} config found but no {name} binary. Run {}",
440                hl(&self.manager.add_dev_command(name))
441            )),
442            JsTool::Pinned(_) | JsTool::Ambient { .. } => {}
443        }
444    }
445}
446
447/// Whether a package.json declares `tool` under `dependencies` or
448/// `devDependencies`, both direct members of the root object. A top-level
449/// `"prettier": {…}` config, a nested `metadata.devDependencies`, a peer or
450/// optional dependency, an override or a script do not count, and a file
451/// that does not parse counts as not declared.
452///
453/// A targeted walk, not a JSON parser: the crate has none on purpose (see
454/// `snapshot_prep`'s module doc), and these two keys are all it needs.
455fn package_json_declares(text: &str, tool: &str) -> bool {
456    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
457    let mut p = JsonWalk {
458        b: text.as_bytes(),
459        i: 0,
460        depth: 0,
461    };
462    p.declares(tool).unwrap_or(false)
463}
464
465/// How deep a package.json may nest before the walk gives up (as "not
466/// declared"): the file is the repository's, and recursion must not be a way
467/// to overflow the hook's stack.
468const MAX_JSON_DEPTH: u16 = 128;
469
470struct JsonWalk<'a> {
471    b: &'a [u8],
472    i: usize,
473    depth: u16,
474}
475
476impl JsonWalk<'_> {
477    fn ws(&mut self) {
478        while self.b.get(self.i).is_some_and(u8::is_ascii_whitespace) {
479            self.i += 1;
480        }
481    }
482
483    fn eat(&mut self, c: u8) -> Option<()> {
484        self.ws();
485        (self.b.get(self.i) == Some(&c)).then(|| self.i += 1)
486    }
487
488    /// A string's raw content (escapes kept as written).
489    fn string(&mut self) -> Option<&[u8]> {
490        self.eat(b'"')?;
491        let start = self.i;
492        loop {
493            match *self.b.get(self.i)? {
494                b'\\' => self.i += 2,
495                b'"' => {
496                    self.i += 1;
497                    return self.b.get(start..self.i - 1);
498                }
499                _ => self.i += 1,
500            }
501        }
502    }
503
504    fn value(&mut self) -> Option<()> {
505        self.ws();
506        match *self.b.get(self.i)? {
507            b'"' => self.string().map(|_| ()),
508            b'{' => self.nested(|w| w.object(|_, w| w.value())),
509            b'[' => self.nested(|w| {
510                w.i += 1;
511                if w.eat(b']').is_some() {
512                    return Some(());
513                }
514                loop {
515                    w.value()?;
516                    if w.eat(b',').is_none() {
517                        return w.eat(b']');
518                    }
519                }
520            }),
521            _ => {
522                let start = self.i;
523                while self
524                    .b
525                    .get(self.i)
526                    .is_some_and(|c| !matches!(c, b',' | b'}' | b']') && !c.is_ascii_whitespace())
527                {
528                    self.i += 1;
529                }
530                (self.i > start).then_some(())
531            }
532        }
533    }
534
535    /// One level deeper, refused past [`MAX_JSON_DEPTH`].
536    fn nested(&mut self, f: impl FnOnce(&mut Self) -> Option<()>) -> Option<()> {
537        if self.depth >= MAX_JSON_DEPTH {
538            return None;
539        }
540        self.depth += 1;
541        let r = f(self);
542        self.depth -= 1;
543        r
544    }
545
546    /// Walk an object, handing each member's key to `member`, which must
547    /// consume the value. `None` when the object is malformed or cut off.
548    fn object(&mut self, mut member: impl FnMut(&[u8], &mut Self) -> Option<()>) -> Option<()> {
549        self.eat(b'{')?;
550        if self.eat(b'}').is_some() {
551            return Some(());
552        }
553        loop {
554            let key = self.string()?.to_vec();
555            self.eat(b':')?;
556            member(&key, self)?;
557            if self.eat(b',').is_none() {
558                return self.eat(b'}');
559            }
560        }
561    }
562
563    fn declares(&mut self, tool: &str) -> Option<bool> {
564        let mut found = false;
565        self.object(|key, w| {
566            if key == b"dependencies" || key == b"devDependencies" {
567                w.ws();
568                if w.b.get(w.i) == Some(&b'{') {
569                    return w.object(|dep, w2| {
570                        found |= dep == tool.as_bytes();
571                        w2.value()
572                    });
573                }
574            }
575            w.value()
576        })?;
577        self.ws();
578        // Anything after the root object means this is not one JSON document.
579        (self.i == self.b.len()).then_some(found)
580    }
581}
582
583/// First match for `tool` on PATH.
584///
585/// Windows executables carry an extension — `git` is `git.exe`, an npm-installed
586/// `eslint` is `eslint.cmd` — so the bare name finds nothing there. PATHEXT is
587/// the OS's own list of what counts as executable; fall back to the usual set
588/// when it is unset. Found by the Windows CI job on its first run, where
589/// `which("git")` returned None on a machine that plainly has git.
590pub fn which(tool: &str) -> Option<String> {
591    which_on(&std::env::var_os("PATH")?, tool)
592}
593
594/// [`which`] against an EXPLICIT path list — the seam its own test needs.
595///
596/// The test that pins the Windows extension order used to `set_var("PATH")`
597/// around the call, which is process-global: for the length of that call
598/// every OTHER test in the binary — 340 of them, running in parallel, many
599/// spawning git — had a PATH containing one fake tool and nothing else. A
600/// git spawned in that window fails with "not found", which is not a
601/// transient `git::retrying` may retry (correctly: it is a hard error), so
602/// the caller reads it as git's ANSWER. In `gate_stamp` that answer is
603/// "nothing is stamped". Passing the path in deletes the shared state
604/// rather than guarding it — a lock only protects the callers who remember
605/// to take it, and every future test here would have to remember.
606pub fn which_on(path: &std::ffi::OsStr, tool: &str) -> Option<String> {
607    let exts: Vec<String> = if cfg!(windows) {
608        std::env::var("PATHEXT")
609            .unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into())
610            .split(';')
611            .filter(|e| !e.is_empty())
612            .map(|e| e.to_lowercase())
613            .collect()
614    } else {
615        Vec::new()
616    };
617    for dir in std::env::split_paths(path) {
618        // On Windows the EXTENSION forms come first. A node install ships both
619        // `npm` (an extensionless shell script, for MSYS) and `npm.cmd` in the
620        // same directory; preferring the bare name hands CreateProcess a shell
621        // script it cannot execute — "%1 is not a valid Win32 application" —
622        // and the hook reports an installed tool as broken.
623        for e in &exts {
624            let c = dir.join(format!("{tool}{e}"));
625            if c.is_file() {
626                return Some(c.to_string_lossy().into_owned());
627            }
628        }
629        let bare = dir.join(tool);
630        if bare.is_file() {
631            return Some(bare.to_string_lossy().into_owned());
632        }
633    }
634    None
635}
636
637/// `<dir>/<tool>`, trying the Windows executable extensions too.
638fn in_bin_dir(dir: &str, tool: &str) -> Option<String> {
639    let bare = Path::new(dir).join(tool);
640    if bare.is_file() {
641        return Some(bare.to_string_lossy().into_owned());
642    }
643    if cfg!(windows) {
644        for e in [".cmd", ".exe", ".bat", ".ps1"] {
645            let c = Path::new(dir).join(format!("{tool}{e}"));
646            if c.is_file() {
647                return Some(c.to_string_lossy().into_owned());
648            }
649        }
650    }
651    None
652}
653
654/// Resolve a tool name to a full path for spawning.
655///
656/// `Command::new("npm")` cannot execute `npm.cmd`: Rust does no PATHEXT
657/// resolution, so on Windows every bare-name spawn fails with "program not
658/// found" and the hook reports the tool as broken rather than absent. Found by
659/// the Windows job on its first FULL-suite run — the smoke never spawned a
660/// tool, so it could not have surfaced this.
661///
662/// Falls back to the name unchanged, so a caller still gets a sensible error.
663pub fn program(name: &str) -> String {
664    which(name).unwrap_or_else(|| name.to_string())
665}
666
667/// The first of `names` that exists at the repo root — how these hooks decide
668/// a repo has opted into a tool.
669pub fn first_existing(root: &str, names: &[&str]) -> Option<String> {
670    names
671        .iter()
672        .find(|n| Path::new(root).join(n).exists())
673        .map(|n| (*n).to_string())
674}
675
676/// Strip git's own environment before handing a Command to another tool.
677///
678/// git exports GIT_DIR, GIT_INDEX_FILE, GIT_WORK_TREE and friends to every
679/// hook. Those OVERRIDE the working directory, so any tool that shells out to
680/// git operates on the hook's repository no matter where it was launched.
681///
682/// That is not hypothetical: `pre-push-cargo-test` runs a project's test suite,
683/// and this repo's own suite creates throwaway repos and commits to them. With
684/// GIT_DIR inherited, `git commit` in a test wrote into the REAL repository —
685/// an actual stray commit, authored by the test fixture, pushed to a branch.
686///
687/// A test suite should behave exactly as it does when run by hand, which means
688/// seeing no git environment at all.
689pub fn strip_git_env(cmd: &mut Command) {
690    for (k, _) in std::env::vars_os() {
691        let key = k.to_string_lossy();
692        if key.starts_with("GIT_") {
693            cmd.env_remove(&k);
694        }
695    }
696    // The index hints name the index of a commit this process may be inside
697    // (amont started from a pre-commit gate's fixture): a child never inherits
698    // them. `External::execute` sets them again for a pre-commit gate.
699    cmd.env_remove(INDEX_ENV);
700    cmd.env_remove(INDEX_GIT_DIR_ENV);
701}
702
703/// The variable a pre-commit command is told the index being committed in:
704/// see [`commit_index`].
705pub const INDEX_ENV: &str = "AMONT_INDEX_FILE";
706/// The absolute git dir of the repository that index belongs to: a consumer
707/// honours [`INDEX_ENV`] only where its own `git rev-parse --absolute-git-dir`
708/// is this, so a suite's fixture repository never reads the outer index.
709pub const INDEX_GIT_DIR_ENV: &str = "AMONT_INDEX_GIT_DIR";
710
711/// The index `git commit` is sealing, and the repository it belongs to.
712#[derive(Debug, Clone, PartialEq, Eq)]
713pub struct CommitIndex {
714    pub file: std::path::PathBuf,
715    pub git_dir: std::path::PathBuf,
716}
717
718/// Why [`commit_index`] could not locate the index.
719#[derive(Debug, Clone, PartialEq, Eq)]
720pub enum IndexLookupError {
721    /// This process's directory could not be read.
722    CurrentDir(String),
723    /// A `git rev-parse` failed; `why` is git's own stderr.
724    Git { args: String, why: String },
725}
726
727impl std::fmt::Display for IndexLookupError {
728    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
729        match self {
730            Self::CurrentDir(e) => write!(f, "current directory: {e}"),
731            Self::Git { args, why } => write!(f, "git {args} failed: {why}"),
732        }
733    }
734}
735
736/// The index `git commit` is sealing, as an absolute path: git's own
737/// `GIT_INDEX_FILE` when it handed the hook one (the temporary index of
738/// `commit -a` or `commit <paths>`), else the repository's index. Relative
739/// paths are resolved against this process's directory, where git ran the
740/// hook. Paths are kept as bytes, so a non-UTF-8 one survives. The error
741/// names the step that failed, with git's own reason.
742pub fn commit_index() -> Result<CommitIndex, IndexLookupError> {
743    let here = std::env::current_dir().map_err(|e| IndexLookupError::CurrentDir(e.to_string()))?;
744    let absolute = |p: std::path::PathBuf| if p.is_absolute() { p } else { here.join(p) };
745    let git_path = |args: &[&str]| -> Result<std::path::PathBuf, IndexLookupError> {
746        let out = crate::git::stdout_raw_or_why(args).map_err(|why| IndexLookupError::Git {
747            args: args.join(" "),
748            why,
749        })?;
750        Ok(path_from_bytes(strip_one_newline(out)))
751    };
752    let file = match std::env::var_os("GIT_INDEX_FILE").filter(|v| !v.is_empty()) {
753        Some(named) => std::path::PathBuf::from(named),
754        None => git_path(&["rev-parse", "--git-path", "index"])?,
755    };
756    let git_dir = git_path(&["rev-parse", "--absolute-git-dir"])?;
757    Ok(CommitIndex {
758        file: absolute(file),
759        git_dir,
760    })
761}
762
763/// Git ends a path with exactly one `\n`; anything before it, a `\r`
764/// included, is part of the name.
765fn strip_one_newline(mut out: Vec<u8>) -> Vec<u8> {
766    if out.last() == Some(&b'\n') {
767        out.pop();
768    }
769    out
770}
771
772#[cfg(unix)]
773fn path_from_bytes(bytes: Vec<u8>) -> std::path::PathBuf {
774    use std::os::unix::ffi::OsStringExt;
775    std::path::PathBuf::from(std::ffi::OsString::from_vec(bytes))
776}
777
778#[cfg(not(unix))]
779fn path_from_bytes(bytes: Vec<u8>) -> std::path::PathBuf {
780    std::path::PathBuf::from(String::from_utf8_lossy(&bytes).into_owned())
781}
782
783/// The wall-clock CEILING for one check's spawned command, in seconds.
784///
785/// `amont.timeout`, default 3600. This used to be 600 and to be the only
786/// clock, which made it answer two different questions with one number: "is
787/// this tool stuck?" and "is this suite slow?". A stuck tool is silent, and
788/// [`idle_timeout`] catches it in minutes; what is left for the ceiling is
789/// the tool that keeps printing and never finishes, which is rare enough to
790/// afford an hour. `0` disables. Read once per process: twenty concurrent
791/// checks must not each spawn a `git config` to learn the same number.
792pub fn check_timeout(settings: &crate::config::Settings) -> u64 {
793    *settings.timeout.get_or_init(|| {
794        crate::config::integer_or(settings, "amont.timeout", 3600, 0..=86_400) as u64
795    })
796}
797
798/// The SILENCE budget: how long a spawned command may go without writing a
799/// byte before it is judged stuck, in seconds.
800///
801/// `amont.idleTimeout`, default 120. A hang is silent; a slow test suite
802/// talks — `cargo test` prints a line per test. Not every one does (vitest
803/// without a terminal prints only its summary), so where CPU can be measured
804/// the budget counts silence AND an idle process tree — see [`Activity`] and
805/// ADR-0008. Killing on silence catches
806/// the captive portal, the deadlocked lock file and the tool waiting on a
807/// prompt nobody will answer FASTER than a ten-minute wall clock did, while
808/// letting a chatty twenty-five-minute suite finish. Only applies where the
809/// output is observed (the captured runners); a command inheriting the
810/// terminal directly answers to the ceiling alone. `0` disables.
811pub fn idle_timeout(settings: &crate::config::Settings) -> u64 {
812    *settings.idle.get_or_init(|| {
813        crate::config::integer_or(settings, "amont.idleTimeout", 120, 0..=86_400) as u64
814    })
815}
816
817/// Whether a silent check that is measurably working on CPU is kept alive
818/// past the silence budget — `amont.idleCpuCredit`, default true (ADR-0008,
819/// `hooks.liveness`). `false` restores the silence-only rule everywhere.
820/// Read once per `Settings`, like the two clocks.
821pub fn idle_cpu_credit(settings: &crate::config::Settings) -> bool {
822    *settings
823        .idle_cpu
824        .get_or_init(|| crate::config::boolean_or(settings, "amont.idleCpuCredit", true))
825}
826
827/// How long a command may sit in a DECLARED wait — a line that says it is
828/// blocked on a lock ([`crate::hooks::wait::marker`]) — before it is killed,
829/// in seconds. `amont.lockWait`, default 600; `0` means until the ceiling.
830/// The silence clock does not run during such a wait: the tool has said
831/// what it is doing, and a lock held by another cargo for a minute on a
832/// loaded machine is not a hang (ADR-0009). Read once per `Settings`.
833pub fn lock_wait(settings: &crate::config::Settings) -> LockWait {
834    match *settings.lock_wait.get_or_init(|| {
835        crate::config::integer_or(settings, "amont.lockWait", 600, 0..=86_400) as u64
836    }) {
837        0 => LockWait::UntilCeiling,
838        s => LockWait::Secs(s),
839    }
840}
841
842/// The budget for a declared wait, as [`lock_wait`] reads it.
843#[derive(Debug, Clone, Copy, PartialEq, Eq)]
844pub enum LockWait {
845    Secs(u64),
846    /// `amont.lockWait 0`: the ceiling alone bounds a declared wait — and
847    /// when the ceiling is off too, the extended silence budget does, so
848    /// nothing is ever unbounded.
849    UntilCeiling,
850}
851
852/// `secs` as people read it: `12s`, `8m12s`, `1h02m`.
853pub fn human_secs(secs: u64) -> String {
854    match secs {
855        s if s < 60 => format!("{s}s"),
856        s if s < 3600 => format!("{}m{:02}s", s / 60, s % 60),
857        s => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
858    }
859}
860
861/// How much of a tool's last stderr line a message may quote.
862pub const LAST_LINE_CHARS: usize = 200;
863
864/// A work window of at least this many thousandths of one core counts as the
865/// tree doing something (ADR-0008): 0.1 core. A hang — a prompt, a lock, a
866/// dead network — sits near zero; a test suite runs at whole cores.
867pub const BUSY_MILLI_CORES: u32 = 100;
868
869/// What the CPU side of [`Activity`] knows. Stored as a `u8`.
870#[derive(Debug, Clone, Copy, PartialEq, Eq)]
871pub enum CpuState {
872    /// Not sampled: `amont.idleCpuCredit false`, no silence budget, or a
873    /// platform that cannot measure. The silence-only rule applies.
874    Off = 0,
875    /// Sampling, but nothing measured yet (the check has not been quiet
876    /// long enough, or it has only a baseline).
877    Waiting = 1,
878    /// Consecutive complete snapshots are being compared.
879    Measuring = 2,
880    /// The last snapshot was incomplete; the next complete one re-baselines.
881    Unavailable = 3,
882}
883
884/// What a spawned command has been doing, shared between the reader threads
885/// that see its bytes, the CPU sampler, the wait loop that judges it, and the
886/// progress displays. Every field is an atomic offset from `base`, so the
887/// 80 ms repaint and the 25 ms wait loop read it without a lock.
888///
889/// Two clocks, kept apart on purpose: `last_out` is when it last WROTE (what
890/// the messages report as "last output"), `last_busy` is the start of the
891/// last window in which its process tree did measurable CPU work. The kill
892/// decision uses the later of the two ([`Activity::still_for`]).
893pub struct Activity {
894    base: std::time::Instant,
895    last_out: std::sync::atomic::AtomicU64,
896    last_busy: std::sync::atomic::AtomicU64,
897    /// Offset + 1 of the start of the current unbroken run of complete
898    /// measurements; 0 when there is none.
899    measured_since: std::sync::atomic::AtomicU64,
900    /// Offset + 1 of the end of the last complete window; 0 when none.
901    last_measured: std::sync::atomic::AtomicU64,
902    rate_milli: std::sync::atomic::AtomicU32,
903    interval_ms: std::sync::atomic::AtomicU32,
904    cpu: std::sync::atomic::AtomicU8,
905    /// Offset + 1 of the start of the current declared wait (ADR-0009); 0
906    /// when the last stderr line was not a wait marker.
907    wait_since: std::sync::atomic::AtomicU64,
908    /// [`crate::hooks::wait::WaitKind::code`] of that wait; 0 when none.
909    wait_kind: std::sync::atomic::AtomicU8,
910    /// Nanoseconds spent in declared waits that have ENDED — what the note
911    /// after a slow-but-passing check reports.
912    waited_ns: std::sync::atomic::AtomicU64,
913    /// The code of the most recent wait, kept after it ends, so the note can
914    /// name what was waited for.
915    last_wait_kind: std::sync::atomic::AtomicU8,
916    /// The silence budget the wait loop is applying right now, in seconds,
917    /// after the host's load stretched it; 0 while it is the configured one
918    /// (ADR-0009). What the displays count toward.
919    budget_secs: std::sync::atomic::AtomicU32,
920    /// The load that stretched it: average × 1000, cores, factor × 1000.
921    load_avg_milli: std::sync::atomic::AtomicU32,
922    load_cores: std::sync::atomic::AtomicU32,
923    load_factor_milli: std::sync::atomic::AtomicU32,
924    /// The last complete, non-empty stderr line, colour stripped and
925    /// clipped: what a kill message may quote, and what decides a retry.
926    last_line: std::sync::Mutex<String>,
927}
928
929impl Activity {
930    pub fn new() -> std::sync::Arc<Activity> {
931        std::sync::Arc::new(Activity {
932            base: std::time::Instant::now(),
933            last_out: Default::default(),
934            last_busy: Default::default(),
935            measured_since: Default::default(),
936            last_measured: Default::default(),
937            rate_milli: Default::default(),
938            interval_ms: Default::default(),
939            cpu: std::sync::atomic::AtomicU8::new(CpuState::Off as u8),
940            wait_since: Default::default(),
941            wait_kind: Default::default(),
942            waited_ns: Default::default(),
943            last_wait_kind: Default::default(),
944            budget_secs: Default::default(),
945            load_avg_milli: Default::default(),
946            load_cores: Default::default(),
947            load_factor_milli: Default::default(),
948            last_line: std::sync::Mutex::new(String::new()),
949        })
950    }
951
952    /// What the most recent declared wait, ended or not, was for.
953    pub fn last_wait_kind(&self) -> Option<crate::hooks::wait::WaitKind> {
954        crate::hooks::wait::WaitKind::from_code(
955            self.last_wait_kind
956                .load(std::sync::atomic::Ordering::Relaxed),
957        )
958    }
959
960    /// One complete stderr line arrived. A wait marker starts a declared
961    /// wait, or continues the one in progress (cargo prints `package cache`
962    /// and then `build directory`; the budget covers the run of them, not
963    /// each); any other line ends it. The line is kept for the messages.
964    pub fn stderr_line(&self, raw: &str) {
965        use std::sync::atomic::Ordering::Relaxed;
966        let line = crate::hooks::wait::strip_csi(raw);
967        if !line.trim().is_empty() {
968            let mut keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
969            keep.clear();
970            keep.extend(line.trim().chars().take(LAST_LINE_CHARS));
971        }
972        match crate::hooks::wait::marker(&line) {
973            Some(kind) => {
974                self.wait_kind.store(kind.code(), Relaxed);
975                self.last_wait_kind.store(kind.code(), Relaxed);
976                // `compare_exchange` from 0: a second marker keeps the
977                // original start.
978                let _ = self
979                    .wait_since
980                    .compare_exchange(0, self.now() + 1, Relaxed, Relaxed);
981            }
982            None => self.end_wait(),
983        }
984    }
985
986    /// The tool wrote something that is not a wait marker: whatever wait
987    /// was in progress is over, and its length is banked for the note.
988    pub fn end_wait(&self) {
989        use std::sync::atomic::Ordering::Relaxed;
990        let since = self.wait_since.swap(0, Relaxed);
991        if since != 0 {
992            let spent = self.now().saturating_sub(since - 1);
993            self.waited_ns.fetch_add(spent, Relaxed);
994        }
995        self.wait_kind.store(0, Relaxed);
996    }
997
998    /// The declared wait in progress, and how long it has lasted.
999    pub fn waiting(&self) -> Option<(crate::hooks::wait::WaitKind, std::time::Duration)> {
1000        use std::sync::atomic::Ordering::Relaxed;
1001        let since = self.wait_since.load(Relaxed);
1002        if since == 0 {
1003            return None;
1004        }
1005        let kind = crate::hooks::wait::WaitKind::from_code(self.wait_kind.load(Relaxed))?;
1006        Some((kind, self.since(since - 1)))
1007    }
1008
1009    /// Time spent in declared waits that have ended, plus the one in
1010    /// progress: what a passing check waited for in total.
1011    pub fn waited_total(&self) -> std::time::Duration {
1012        use std::sync::atomic::Ordering::Relaxed;
1013        let banked = std::time::Duration::from_nanos(self.waited_ns.load(Relaxed));
1014        banked + self.waiting().map_or(std::time::Duration::ZERO, |(_, d)| d)
1015    }
1016
1017    /// The last non-empty stderr line, if any.
1018    pub fn last_line(&self) -> Option<String> {
1019        let keep = self.last_line.lock().unwrap_or_else(|p| p.into_inner());
1020        (!keep.is_empty()).then(|| keep.clone())
1021    }
1022
1023    /// The wait loop read the host's load and is applying `budget_secs`.
1024    pub fn set_load(&self, budget_secs: u64, load: crate::load::Load, factor_milli: u32) {
1025        use std::sync::atomic::Ordering::Relaxed;
1026        self.budget_secs
1027            .store(u32::try_from(budget_secs).unwrap_or(u32::MAX), Relaxed);
1028        self.load_avg_milli.store(load.avg1_milli, Relaxed);
1029        self.load_cores.store(load.cores, Relaxed);
1030        self.load_factor_milli.store(factor_milli, Relaxed);
1031    }
1032
1033    /// The load-stretched budget in force, with the load behind it, when
1034    /// the host's load stretched it at all.
1035    pub fn load_scale(&self) -> Option<(u64, crate::load::Load, u32)> {
1036        use std::sync::atomic::Ordering::Relaxed;
1037        let factor = self.load_factor_milli.load(Relaxed);
1038        if factor <= 1000 {
1039            return None;
1040        }
1041        Some((
1042            u64::from(self.budget_secs.load(Relaxed)),
1043            crate::load::Load {
1044                avg1_milli: self.load_avg_milli.load(Relaxed),
1045                cores: self.load_cores.load(Relaxed),
1046            },
1047            factor,
1048        ))
1049    }
1050    fn offset(&self, at: std::time::Instant) -> u64 {
1051        u64::try_from(at.saturating_duration_since(self.base).as_nanos()).unwrap_or(u64::MAX)
1052    }
1053    fn now(&self) -> u64 {
1054        self.offset(std::time::Instant::now())
1055    }
1056    fn since(&self, offset: u64) -> std::time::Duration {
1057        std::time::Duration::from_nanos(self.now().saturating_sub(offset))
1058    }
1059    /// It wrote something.
1060    pub fn touch(&self) {
1061        self.last_out
1062            .fetch_max(self.now(), std::sync::atomic::Ordering::Relaxed);
1063    }
1064    /// How long since it last wrote a byte — the true output silence, what
1065    /// the displays report as "last output".
1066    pub fn quiet_for(&self) -> std::time::Duration {
1067        self.since(self.last_out.load(std::sync::atomic::Ordering::Relaxed))
1068    }
1069    /// The silence the clock counts: zero while the command is in a
1070    /// declared wait (it has said what it is doing), the output silence
1071    /// otherwise. What [`Activity::still_for`] and the sampler's start gate
1072    /// read; the displays keep [`Activity::quiet_for`].
1073    pub fn silence_for(&self) -> std::time::Duration {
1074        if self.waiting().is_some() {
1075            std::time::Duration::ZERO
1076        } else {
1077            self.quiet_for()
1078        }
1079    }
1080    /// How long it has been BOTH silent and idle on CPU — the number the
1081    /// silence budget is judged against. Equals [`Activity::silence_for`]
1082    /// whenever CPU is not sampled.
1083    pub fn still_for(&self) -> std::time::Duration {
1084        let busy = self.last_busy.load(std::sync::atomic::Ordering::Relaxed);
1085        self.silence_for().min(self.since(busy))
1086    }
1087    pub fn cpu_state(&self) -> CpuState {
1088        match self.cpu.load(std::sync::atomic::Ordering::Relaxed) {
1089            1 => CpuState::Waiting,
1090            2 => CpuState::Measuring,
1091            3 => CpuState::Unavailable,
1092            _ => CpuState::Off,
1093        }
1094    }
1095    fn set_cpu_state(&self, s: CpuState) {
1096        self.cpu
1097            .store(s as u8, std::sync::atomic::Ordering::Relaxed);
1098    }
1099    /// The last measured rate in thousandths of a core, while it is fresh:
1100    /// `None` once two sampling intervals have passed without a complete
1101    /// window, so a display never keeps showing "busy" on stale data.
1102    pub fn fresh_rate(&self) -> Option<u32> {
1103        if self.cpu_state() != CpuState::Measuring {
1104            return None;
1105        }
1106        let end = self
1107            .last_measured
1108            .load(std::sync::atomic::Ordering::Relaxed);
1109        if end == 0 {
1110            return None;
1111        }
1112        let every = u64::from(self.interval_ms.load(std::sync::atomic::Ordering::Relaxed));
1113        let stale = std::time::Duration::from_millis(2 * every.max(1));
1114        (self.since(end - 1) <= stale)
1115            .then(|| self.rate_milli.load(std::sync::atomic::Ordering::Relaxed))
1116    }
1117    /// What the CPU side can honestly say at a kill. "Measured idle" names
1118    /// the unbroken span of complete measurements it rests on — sampling
1119    /// starts only after a stretch of silence, so that span is always shorter
1120    /// than the silence itself, and nothing is claimed about the rest.
1121    pub fn verdict(&self) -> CpuVerdict {
1122        match self.cpu_state() {
1123            CpuState::Off => return CpuVerdict::NotSampled,
1124            CpuState::Waiting | CpuState::Unavailable => return CpuVerdict::Unmeasured,
1125            CpuState::Measuring => {}
1126        }
1127        if let Some(rate) = self.fresh_rate().filter(|r| *r >= BUSY_MILLI_CORES) {
1128            return CpuVerdict::BusyAtKill(rate);
1129        }
1130        let since = self
1131            .measured_since
1132            .load(std::sync::atomic::Ordering::Relaxed);
1133        match (since, self.fresh_rate()) {
1134            (s, Some(_)) if s != 0 => CpuVerdict::MeasuredIdle(self.since(s - 1).as_secs()),
1135            _ => CpuVerdict::Unmeasured,
1136        }
1137    }
1138    /// Feed one sampler observation in. `interval` is the sampling period,
1139    /// kept so displays can tell a fresh rate from a stale one.
1140    pub fn record(
1141        &self,
1142        obs: crate::proctree::Observation,
1143        at: std::time::Instant,
1144        interval: std::time::Duration,
1145    ) {
1146        use std::sync::atomic::Ordering::Relaxed;
1147        self.interval_ms.store(
1148            u32::try_from(interval.as_millis()).unwrap_or(u32::MAX),
1149            Relaxed,
1150        );
1151        match obs {
1152            crate::proctree::Observation::Baseline => {
1153                self.measured_since.store(self.offset(at) + 1, Relaxed);
1154                self.set_cpu_state(CpuState::Waiting);
1155            }
1156            crate::proctree::Observation::Window(w) => {
1157                let milli = w.milli_cores();
1158                self.rate_milli.store(milli, Relaxed);
1159                self.last_measured.store(self.offset(w.end) + 1, Relaxed);
1160                if milli >= BUSY_MILLI_CORES {
1161                    // The window's START: a burst buys one window, not a
1162                    // whole new budget.
1163                    self.last_busy.fetch_max(self.offset(w.start), Relaxed);
1164                }
1165                if w.gapped {
1166                    // Busy is still busy, but a gap is not a measurement:
1167                    // the measured-idle span starts over at the gap's end,
1168                    // so the claim never covers what was not seen.
1169                    self.measured_since.store(self.offset(w.end) + 1, Relaxed);
1170                }
1171                self.set_cpu_state(CpuState::Measuring);
1172            }
1173            // A skipped sample changes nothing: the rate ages and goes
1174            // stale on its own if the next complete one is late.
1175            crate::proctree::Observation::Skipped => {}
1176            crate::proctree::Observation::Unmeasured => {
1177                self.measured_since.store(0, Relaxed);
1178                self.set_cpu_state(CpuState::Unavailable);
1179            }
1180        }
1181    }
1182    /// Sampling is on for this command.
1183    pub fn enable_cpu(&self) {
1184        self.set_cpu_state(CpuState::Waiting);
1185    }
1186    /// Which silence budget applies right now, from what the sampler can
1187    /// claim: see [`CpuGate`].
1188    pub fn gate(&self) -> CpuGate {
1189        match self.verdict() {
1190            CpuVerdict::NotSampled => CpuGate::NotSampled,
1191            CpuVerdict::MeasuredIdle(_) | CpuVerdict::BusyAtKill(_) => CpuGate::Measured,
1192            CpuVerdict::Unmeasured => CpuGate::Unmeasured,
1193        }
1194    }
1195}
1196
1197/// What the kill decision may rest on from the CPU side (ADR-0009). Not
1198/// sampled at all: the silence-only rule, as ever. Measured: the silence
1199/// budget, because "silent and idle" was actually observed. Unmeasured —
1200/// sampling is on but the last sample was late, partial, or has not come
1201/// yet: the EXTENDED budget, `amont.idleTimeout × amont.idleLoadScale`,
1202/// which is bounded even when the ceiling is off, and never the bare
1203/// silence budget, because that would kill on a measurement nobody made.
1204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1205pub enum CpuGate {
1206    NotSampled,
1207    Measured,
1208    Unmeasured,
1209}
1210
1211/// What the CPU sampler could say when a command was killed.
1212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1213pub enum CpuVerdict {
1214    /// Not sampled here (knob off, no budget, platform): silence alone.
1215    NotSampled,
1216    /// An unbroken run of complete measurements, this many seconds long and
1217    /// ending at the kill, all under [`BUSY_MILLI_CORES`].
1218    MeasuredIdle(u64),
1219    /// Sampling was on but could not measure the whole budget.
1220    Unmeasured,
1221    /// Its tree was measurably busy at the kill, at this many thousandths
1222    /// of a core.
1223    BusyAtKill(u32),
1224}
1225
1226/// `milli` thousandths of a core as people read it: `~3.9 cores`.
1227pub fn cores(milli: u32) -> String {
1228    format!("~{}.{} cores", milli / 1000, (milli % 1000) / 100)
1229}
1230
1231/// The deadline for a network PROBE — an `ls-remote` asked before the real
1232/// work, not the work itself. Capped at 30s below [`check_timeout`]: a
1233/// probe answers in a second or two when the network is there at all, and
1234/// a healthy `amont.timeout` of ten minutes is sized for a test suite, not
1235/// for deciding whether the remote is reachable. Shrinking `amont.timeout`
1236/// below the cap shrinks this too, and `0` keeps meaning no deadline —
1237/// somebody who disabled the clock disabled all of it.
1238pub fn network_probe_budget(settings: &crate::config::Settings) -> u64 {
1239    match check_timeout(settings) {
1240        0 => 0,
1241        t => t.min(30),
1242    }
1243}
1244
1245/// Which clock killed a command.
1246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1247pub enum Why {
1248    /// The wall-clock ceiling, `amont.timeout`, in seconds.
1249    Ceiling(u64),
1250    /// The silence budget, `amont.idleTimeout`, in seconds.
1251    Silence(u64),
1252    /// A declared wait outlived `amont.lockWait` (or, with that at 0 and
1253    /// the ceiling off, the extended silence budget), in seconds.
1254    Waited(crate::hooks::wait::WaitKind, u64),
1255}
1256
1257/// A command killed by a clock — what happened, said with enough to tell
1258/// "slow" from "stuck", which is the whole reason there are two clocks.
1259#[derive(Debug, Clone)]
1260pub struct Killed {
1261    pub why: Why,
1262    /// How long it had been running.
1263    pub ran_secs: u64,
1264    /// How long since its last output; `None` when the output was not ours
1265    /// to observe (inherited stdio).
1266    pub quiet_secs: Option<u64>,
1267    /// What its CPU was doing, as far as it was measured.
1268    pub cpu: CpuVerdict,
1269    /// The silence budget it ran under, in seconds (0 = off). With
1270    /// `quiet_secs` it says whether CPU work is what kept a silent command
1271    /// alive past that budget.
1272    pub idle_secs: u64,
1273    /// The declared wait it was in at the kill, and for how long.
1274    pub waiting: Option<(crate::hooks::wait::WaitKind, u64)>,
1275    /// Its last non-empty stderr line, colour stripped and clipped to
1276    /// [`LAST_LINE_CHARS`]: what decides a retry, and what the message may
1277    /// quote.
1278    pub last_line: Option<String>,
1279    /// The host's load at the kill, with the factor it stretched the
1280    /// silence budget by, when it stretched it at all.
1281    pub load: Option<(crate::load::Load, u32)>,
1282}
1283
1284/// The budgets one wait is judged under — the inputs to [`judge`] that do
1285/// not move while the command runs.
1286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1287pub struct Clocks {
1288    /// `amont.timeout`; `None` when off.
1289    pub ceiling: Option<u64>,
1290    /// `amont.idleTimeout`; `None` when off or when nobody watches the
1291    /// output.
1292    pub silence: Option<u64>,
1293    /// `amont.lockWait`.
1294    pub lock_wait: LockWait,
1295    /// The bound a declared wait falls back to when `lock_wait` says "until
1296    /// the ceiling" and the ceiling is off: the extended silence budget,
1297    /// `None` when silence is off too.
1298    pub extended: Option<u64>,
1299    /// `amont.idleLoadScale`: how far the host's load may stretch
1300    /// `silence`; 1 means not at all.
1301    pub scale: u64,
1302}
1303
1304impl Clocks {
1305    /// The ceiling alone: inherited stdio, where nobody sees the bytes.
1306    pub fn ceiling_only(wall_secs: u64) -> Clocks {
1307        Clocks {
1308            ceiling: (wall_secs > 0).then_some(wall_secs),
1309            silence: None,
1310            lock_wait: LockWait::UntilCeiling,
1311            extended: None,
1312            scale: 1,
1313        }
1314    }
1315
1316    /// Every clock, from the settings. `idle_secs` is the silence budget
1317    /// the caller resolved (0 = off).
1318    pub fn from_settings(settings: &crate::config::Settings, idle_secs: u64) -> Clocks {
1319        let wall = check_timeout(settings);
1320        let scale = idle_load_scale(settings);
1321        Clocks {
1322            ceiling: (wall > 0).then_some(wall),
1323            silence: (idle_secs > 0).then_some(idle_secs),
1324            lock_wait: lock_wait(settings),
1325            extended: (idle_secs > 0).then(|| idle_secs.saturating_mul(scale)),
1326            scale,
1327        }
1328    }
1329}
1330
1331/// How often the wait loop re-reads the host's load.
1332const LOAD_EVERY: std::time::Duration = std::time::Duration::from_secs(5);
1333
1334/// `amont.idleLoadScale`: how far the silence budget may stretch, as a
1335/// factor — under load (ADR-0009, the load-scaled budget) and whenever the
1336/// CPU could not be measured (the extended budget, `idleTimeout × this`).
1337/// Default 4, `1` disables the stretch, range 1..=16. A HOST key: read from
1338/// global or system config only, never from a repository, because it
1339/// describes the machine and two repositories must not disagree about it.
1340pub fn idle_load_scale(settings: &crate::config::Settings) -> u64 {
1341    *settings.idle_load_scale.get_or_init(|| {
1342        crate::config::host_integer_or(settings, "amont.idleLoadScale", 4, 1..=16) as u64
1343    })
1344}
1345
1346/// What became of a command run under the deadline.
1347pub enum Ran {
1348    Status(std::process::ExitStatus),
1349    /// Killed by a clock; see [`Killed`].
1350    TimedOut(Killed),
1351}
1352
1353/// `cmd.status()`, bounded by [`check_timeout`].
1354///
1355/// Without a bound, one hung tool — a linter deadlocked on a lock file, a
1356/// plugin doing network I/O — blocked the commit FOREVER, and it hung inside
1357/// the index-fidelity hold: the user's unstaged changes parked in `$GIT_DIR`,
1358/// their tree showing staged content only, for as long as they were willing
1359/// to wait. The learned response to that is `--no-verify`, permanently —
1360/// which disarms every check to escape one.
1361///
1362/// The kill reaches the direct child only. A grandchild that detached
1363/// survives, orphaned — but the COMMIT is no longer hostage to it, which is
1364/// the property that matters.
1365pub fn status_within(
1366    settings: &crate::config::Settings,
1367    cmd: &mut Command,
1368) -> std::io::Result<Ran> {
1369    // The same host-slot wait as the observed runners: a check run without
1370    // a live stage (one check by name, `amont.progress false`) still queues.
1371    if crate::host_slots::before_spawn(settings)? {
1372        cmd.env(crate::host_slots::HELD_ENV, "held");
1373    }
1374    crate::host_slots::bound(cmd);
1375    status_within_secs(cmd, check_timeout(settings))
1376}
1377
1378/// [`status_within`] with an explicit ceiling — the testable seam. The
1379/// output is inherited, so nobody sees the bytes and the silence budget
1380/// cannot apply; the ceiling is the only clock.
1381pub fn status_within_secs(cmd: &mut Command, budget_secs: u64) -> std::io::Result<Ran> {
1382    if budget_secs == 0 {
1383        return cmd.status().map(Ran::Status);
1384    }
1385    let mut child = cmd.spawn()?;
1386    wait_within(&mut child, Clocks::ceiling_only(budget_secs), None)
1387}
1388
1389/// Spawn `cmd` with both streams piped, hand every chunk to `on_output` as
1390/// it arrives, and wait under BOTH clocks — the reader threads are what
1391/// make the silence budget observable. The shared runner behind the
1392/// streamed, captured and discarded variants.
1393fn run_observed(
1394    settings: &crate::config::Settings,
1395    cmd: &mut Command,
1396    on_output: impl Fn(&[u8]) + Send + Sync + 'static,
1397    ceiling_left: Option<u64>,
1398) -> std::io::Result<Ran> {
1399    // A heavy check's first tool waits here for a host slot (ADR-0009);
1400    // its clocks start at the spawn below, after the wait.
1401    if crate::host_slots::before_spawn(settings)? {
1402        cmd.env(crate::host_slots::HELD_ENV, "held");
1403    }
1404    crate::host_slots::bound(cmd);
1405    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
1406    let activity = Activity::new();
1407    let on_output = std::sync::Arc::new(on_output);
1408    let mut child = cmd.spawn()?;
1409    // The silence is the CHILD's, so its clock starts when the child does:
1410    // a spawn that itself took a second on a loaded machine is not a
1411    // second the tool spent saying nothing.
1412    activity.touch();
1413    let mut readers = Vec::new();
1414    // stderr is where cargo and uv print their status, so only its lines
1415    // are read for wait markers: a test that prints the words on stdout
1416    // must not pause its own clock. A stdout chunk still ENDS a wait — the
1417    // tool is visibly alive.
1418    let pipes = [
1419        (
1420            child
1421                .stdout
1422                .take()
1423                .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
1424            false,
1425        ),
1426        (
1427            child
1428                .stderr
1429                .take()
1430                .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
1431            true,
1432        ),
1433    ];
1434    for (pipe, is_stderr) in pipes {
1435        let Some(pipe) = pipe else { continue };
1436        let activity = std::sync::Arc::clone(&activity);
1437        let on_output = std::sync::Arc::clone(&on_output);
1438        readers.push(std::thread::spawn(move || {
1439            let mut pipe = pipe;
1440            let mut chunk = [0u8; 4096];
1441            let mut framer = crate::hooks::wait::LineFramer::default();
1442            // Whole lines only: stdout and stderr are two pipes with a reader
1443            // each, and handing on raw chunks let one stream's chunk land in
1444            // the middle of the other's line — cargo writes a panic to stderr
1445            // and `test result:` to stdout, and the quiet excerpt (and the
1446            // log) read the splice. The two now merge at line boundaries.
1447            let mut pending: Vec<u8> = Vec::new();
1448            loop {
1449                match std::io::Read::read(&mut pipe, &mut chunk) {
1450                    Ok(0) | Err(_) => break,
1451                    Ok(n) => {
1452                        activity.touch();
1453                        if is_stderr {
1454                            for line in framer.feed(&chunk[..n]) {
1455                                activity.stderr_line(&line);
1456                            }
1457                        } else {
1458                            activity.end_wait();
1459                        }
1460                        pending.extend_from_slice(&chunk[..n]);
1461                        if let Some(end) = whole_lines(&pending) {
1462                            on_output(&pending[..end]);
1463                            pending.drain(..end);
1464                        }
1465                    }
1466                }
1467            }
1468            if !pending.is_empty() {
1469                on_output(&pending);
1470            }
1471        }));
1472    }
1473    // The displays read the same clocks the kill decision does.
1474    let _attached = crate::live::current_sink()
1475        .map(|(stage, idx)| stage.attach(idx, std::sync::Arc::clone(&activity)));
1476    let idle = idle_timeout(settings);
1477    let sampler = (idle > 0 && idle_cpu_credit(settings) && crate::proctree::SUPPORTED)
1478        .then(|| CpuSampler::start(child.id(), std::sync::Arc::clone(&activity), idle));
1479    let mut clocks = Clocks::from_settings(settings, idle);
1480    if let Some(left) = ceiling_left {
1481        // A retry runs under what the first attempt left of the ceiling:
1482        // both attempts together answer to one `amont.timeout`.
1483        clocks.ceiling = Some(left.max(1));
1484    }
1485    let ran = wait_within(&mut child, clocks, Some(&activity));
1486    if let Some(s) = sampler {
1487        s.stop();
1488    }
1489    for r in readers {
1490        let _ = r.join();
1491    }
1492    // A check that passed after sitting on a lock says so once: the
1493    // reader of a slow commit learns where the minutes went, and a run that
1494    // would once have been killed leaves a trace of why it no longer is.
1495    if let Ok(Ran::Status(_)) = &ran {
1496        let waited = activity.waited_total();
1497        if waited >= std::time::Duration::from_secs(1) {
1498            let what = activity
1499                .last_wait_kind()
1500                .map_or("a lock", crate::hooks::wait::WaitKind::describe);
1501            say(&format!(
1502                "  (waited {} for {what})",
1503                human_secs(waited.as_secs())
1504            ));
1505        }
1506    }
1507    ran
1508}
1509
1510/// The CPU half of the silence budget (ADR-0008): a thread that, while the
1511/// command is silent, snapshots its process tree and records whether it is
1512/// doing measurable work. It runs BESIDE the wait loop, never inside it —
1513/// the loop only reads what this publishes — so nothing a snapshot does can
1514/// delay the ceiling.
1515struct CpuSampler {
1516    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
1517    handle: std::thread::JoinHandle<()>,
1518}
1519
1520impl CpuSampler {
1521    fn start(pid: u32, activity: std::sync::Arc<Activity>, idle_secs: u64) -> CpuSampler {
1522        activity.enable_cpu();
1523        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1524        let flag = std::sync::Arc::clone(&stop);
1525        let handle = std::thread::Builder::new()
1526            .name("amont-cpu".into())
1527            .spawn(move || sample_loop(pid, &activity, idle_secs, &flag))
1528            .expect("spawn the CPU sampler thread");
1529        CpuSampler { stop, handle }
1530    }
1531
1532    /// Ask it to stop and wait a bounded second for it. A snapshot is itself
1533    /// bounded, so it always stops sooner; if it somehow did not, it is left
1534    /// to finish on its own rather than holding the check.
1535    fn stop(self) {
1536        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
1537        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
1538        while !self.handle.is_finished() && std::time::Instant::now() < deadline {
1539            std::thread::sleep(std::time::Duration::from_millis(10));
1540        }
1541        if self.handle.is_finished() {
1542            let _ = self.handle.join();
1543        }
1544    }
1545}
1546
1547/// When sampling starts and how often it repeats, from the silence budget:
1548/// quiet for `max(250 ms, min(30 s, budget/3))`, then every
1549/// `clamp(budget/4, 250 ms, 10 s)` — so even a one-second budget is sampled
1550/// several times before it runs out.
1551pub fn sampling_schedule(idle_secs: u64) -> (std::time::Duration, std::time::Duration) {
1552    let ms = std::time::Duration::from_millis;
1553    let budget = std::time::Duration::from_secs(idle_secs);
1554    let first = (budget / 3)
1555        .min(std::time::Duration::from_secs(30))
1556        .max(ms(250));
1557    let every = (budget / 4).clamp(ms(250), std::time::Duration::from_secs(10));
1558    (first, every)
1559}
1560
1561fn sample_loop(
1562    pid: u32,
1563    activity: &Activity,
1564    idle_secs: u64,
1565    stop: &std::sync::atomic::AtomicBool,
1566) {
1567    use std::sync::atomic::Ordering::Relaxed;
1568    let (first, every) = sampling_schedule(idle_secs);
1569    let mut limits = crate::proctree::Limits::default();
1570    // A diagnostic, and the seam the timing tests use to force a partial
1571    // snapshot: cap the walk at this many processes.
1572    if let Some(n) = std::env::var("AMONT_CPU_MAX_PROCS")
1573        .ok()
1574        .and_then(|v| v.trim().parse::<usize>().ok())
1575    {
1576        limits.max_procs = n;
1577    }
1578    let trace = std::env::var_os("AMONT_CPU_TRACE");
1579    let mut tracker = crate::proctree::Tracker::default();
1580    let nap = |d: std::time::Duration| {
1581        let until = std::time::Instant::now() + d;
1582        while !stop.load(Relaxed) && std::time::Instant::now() < until {
1583            std::thread::sleep(std::time::Duration::from_millis(50));
1584        }
1585    };
1586    while !stop.load(Relaxed) {
1587        // The silence the clock counts, not the raw output silence: during
1588        // a declared wait there is nothing to prove, and no CPU is sampled.
1589        if activity.silence_for() < first {
1590            // Talking: nothing to prove, and the next quiet stretch starts
1591            // from a fresh baseline rather than a stale one.
1592            tracker = crate::proctree::Tracker::default();
1593            nap(std::time::Duration::from_millis(100));
1594            continue;
1595        }
1596        let snap = crate::proctree::snapshot(pid, &tracker.seen(), &limits);
1597        let at = std::time::Instant::now();
1598        let traced = trace.as_ref().map(|_| match &snap {
1599            crate::proctree::Snapshot::Complete(procs) => procs.clone(),
1600            _ => Vec::new(),
1601        });
1602        let obs = tracker.observe(at, snap);
1603        if let (Some(path), Some(procs)) = (&trace, traced) {
1604            trace_sample(path, pid, &procs, &obs);
1605        }
1606        activity.record(obs, at, every);
1607        nap(every);
1608    }
1609}
1610
1611/// `AMONT_CPU_TRACE=<file>`: append what each sample saw — one
1612/// `pid start ppid cpu_ns` line per process of a complete snapshot, then a
1613/// `# root <pid> <observation>` line. A diagnostic, and the seam the timing
1614/// tests use to know a worker was seen before they orphan it (they match
1615/// the leading pid).
1616fn trace_sample(
1617    path: &std::ffi::OsStr,
1618    root: u32,
1619    procs: &[crate::proctree::Proc],
1620    obs: &crate::proctree::Observation,
1621) {
1622    use std::io::Write;
1623    let Ok(mut f) = std::fs::OpenOptions::new()
1624        .create(true)
1625        .append(true)
1626        .open(path)
1627    else {
1628        return;
1629    };
1630    let mut text = String::new();
1631    for p in procs {
1632        text.push_str(&format!(
1633            "{} {} {} {}\n",
1634            p.id.pid, p.id.start, p.ppid, p.cpu_ns
1635        ));
1636    }
1637    let obs = match obs {
1638        crate::proctree::Observation::Window(w) => {
1639            format!("window {} milli-cores", w.milli_cores())
1640        }
1641        other => format!("{other:?}").to_lowercase(),
1642    };
1643    text.push_str(&format!("# root {root} {obs}\n"));
1644    let _ = f.write_all(text.as_bytes());
1645}
1646
1647/// [`status_within`], with the child's stdout and stderr CAPTURED into the
1648/// calling check's slot instead of inherited — the other half of one-check-
1649/// one-block: a linter's twelve lines used to land on the shared terminal
1650/// between two other checks' lines. Falls back to plain [`status_within`]
1651/// when no slot is installed on this thread (`amont.progress false`, or a
1652/// spawn outside a stage), which is byte-for-byte the old behaviour.
1653///
1654/// stdout and stderr merge in ARRIVAL order inside the block, which is what
1655/// the terminal showed before. The readers are threads, not processes, and
1656/// they are joined before the status is returned so a block can never grow
1657/// after its check finished.
1658pub fn status_streamed(
1659    settings: &crate::config::Settings,
1660    cmd: &mut Command,
1661    retry: Retry,
1662) -> std::io::Result<Ran> {
1663    let Some((stage, idx)) = crate::live::current_sink() else {
1664        return status_within(settings, cmd);
1665    };
1666    if crate::live::watching() {
1667        // The block lands on a real terminal but the tool sees a pipe and
1668        // would strip its colors; the big three opt-in knobs put them back.
1669        cmd.env("FORCE_COLOR", "1")
1670            .env("CLICOLOR_FORCE", "1")
1671            .env("CARGO_TERM_COLOR", "always");
1672    }
1673    let first = run_observed(
1674        settings,
1675        cmd,
1676        {
1677            let stage = std::sync::Arc::clone(&stage);
1678            move |bytes| stage.append_raw(idx, bytes)
1679        },
1680        None,
1681    );
1682    stage.runner_exit(idx, exit_of(&first));
1683    let Ok(Ran::TimedOut(k)) = &first else {
1684        return first;
1685    };
1686    let Some(left) = retry_budget(retry, k, check_timeout(settings)) else {
1687        return first;
1688    };
1689    // The check's name (`clippy`), which is what the reader knows; the
1690    // program (`cargo`) only when no check is running on this thread.
1691    let what = crate::host_slots::current_check()
1692        .unwrap_or_else(|| cmd.get_program().to_string_lossy().into_owned());
1693    say(&format!(
1694        "{} was killed while it looked like it was waiting ({}); retrying once{}.",
1695        hl(&what),
1696        k.last_line.as_deref().unwrap_or(""),
1697        match left {
1698            Some(s) => format!(" with {} left", human_secs(s)),
1699            None => String::new(),
1700        }
1701    ));
1702    let second = run_observed(
1703        settings,
1704        cmd,
1705        {
1706            let stage = std::sync::Arc::clone(&stage);
1707            move |bytes| stage.append_raw(idx, bytes)
1708        },
1709        left,
1710    );
1711    stage.runner_exit(idx, exit_of(&second));
1712    second
1713}
1714
1715/// How much of `pending` to hand on: up to and including its last newline,
1716/// or all of it once it holds [`LINE_HOLD`] bytes with none — a progress bar
1717/// redrawing with `\r` must not grow without bound.
1718fn whole_lines(pending: &[u8]) -> Option<usize> {
1719    match pending.iter().rposition(|&b| b == b'\n') {
1720        Some(i) => Some(i + 1),
1721        None if pending.len() >= LINE_HOLD => Some(pending.len()),
1722        None => None,
1723    }
1724}
1725
1726const LINE_HOLD: usize = 64 * 1024;
1727
1728/// The tool's exit code, for a quiet slot's failure line; `None` when it was
1729/// killed or never ran.
1730fn exit_of(ran: &std::io::Result<Ran>) -> Option<i32> {
1731    match ran {
1732        Ok(Ran::Status(s)) => s.code(),
1733        _ => None,
1734    }
1735}
1736
1737/// Whether a check's tool may be run once more after a kill (ADR-0009).
1738#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1739pub enum Retry {
1740    /// A built-in check: its tools are safe to run twice.
1741    Once,
1742    /// A declared external: a user's command may not be safe to run twice.
1743    Never,
1744}
1745
1746/// Whether a kill earns the one retry, and with how much ceiling left
1747/// (`Some(None)`: the ceiling is off). Only after a SILENCE kill whose last
1748/// line reads like a wait — never after a declared wait outlived its own
1749/// budget, nor at the ceiling — and only while the ceiling has at least one
1750/// silence budget left. Pure.
1751pub fn retry_budget(retry: Retry, k: &Killed, ceiling: u64) -> Option<Option<u64>> {
1752    if retry == Retry::Never || !matches!(k.why, Why::Silence(_)) {
1753        return None;
1754    }
1755    if !k
1756        .last_line
1757        .as_deref()
1758        .is_some_and(crate::hooks::wait::looks_like_wait)
1759    {
1760        return None;
1761    }
1762    if ceiling == 0 {
1763        return Some(None);
1764    }
1765    let left = ceiling.saturating_sub(k.ran_secs);
1766    (left >= k.idle_secs.max(1)).then_some(Some(left))
1767}
1768
1769/// Run to completion under the `amont.timeout` deadline with stdout and
1770/// stderr CAPTURED into a string the caller can parse — what the audit
1771/// checks need: their verdict lives in the tool's output, not its exit
1772/// code alone. Arrival-ordered merge of both streams, like
1773/// [`status_streamed`]'s blocks. `None` when the child cannot be spawned.
1774pub fn capture_within(
1775    settings: &crate::config::Settings,
1776    cmd: &mut Command,
1777) -> Option<(Ran, String)> {
1778    let text = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
1779    let sink = std::sync::Arc::clone(&text);
1780    let ran = run_observed(
1781        settings,
1782        cmd,
1783        move |bytes| {
1784            sink.lock()
1785                .unwrap_or_else(|p| p.into_inner())
1786                .push_str(&String::from_utf8_lossy(bytes));
1787        },
1788        None,
1789    )
1790    .ok()?;
1791    let text = std::sync::Arc::try_unwrap(text)
1792        .map(|m| m.into_inner().unwrap_or_else(|p| p.into_inner()))
1793        .unwrap_or_default();
1794    Some((ran, text))
1795}
1796
1797/// The wait over an already-spawned child — shared by every runner. The
1798/// silence budget in `clocks` applies only when there is an [`Activity`] to
1799/// consult (piped output); with inherited stdio the ceiling is the only
1800/// clock, and with that off too the child is simply waited for.
1801pub(crate) fn wait_within(
1802    child: &mut std::process::Child,
1803    clocks: Clocks,
1804    activity: Option<&Activity>,
1805) -> std::io::Result<Ran> {
1806    let started = std::time::Instant::now();
1807    let clocks = match activity {
1808        Some(_) => clocks,
1809        None => Clocks {
1810            silence: None,
1811            extended: None,
1812            ..clocks
1813        },
1814    };
1815    if clocks.ceiling.is_none() && clocks.silence.is_none() {
1816        return child.wait().map(Ran::Status);
1817    }
1818    // The clocks as judged: `silence` stretched by the host's load, re-read
1819    // every few seconds. The configured value stays in `clocks` for the
1820    // message.
1821    let mut live = clocks;
1822    let mut load: Option<(crate::load::Load, u32)> = None;
1823    let mut next_load = started;
1824    loop {
1825        if let Some(status) = child.try_wait()? {
1826            return Ok(Ran::Status(status));
1827        }
1828        let now = std::time::Instant::now();
1829        if let (Some(idle), Some(a)) = (clocks.silence, activity) {
1830            if clocks.scale > 1 && now >= next_load {
1831                next_load = now + LOAD_EVERY;
1832                if let Some(l) = crate::load::read() {
1833                    let factor = l.factor_milli(clocks.scale);
1834                    let applied = crate::load::scaled_budget(idle, l, clocks.scale, clocks.ceiling);
1835                    live.silence = Some(applied);
1836                    a.set_load(applied, l, factor);
1837                    load = (factor > 1000).then_some((l, factor));
1838                }
1839            }
1840        }
1841        // Judged on "silent AND idle on CPU"; equal to plain silence when CPU
1842        // is not sampled, and zero during a declared wait.
1843        let quiet = activity.map(|a| a.still_for());
1844        let waiting = activity.and_then(Activity::waiting);
1845        let gate = activity.map_or(CpuGate::NotSampled, Activity::gate);
1846        let why = judge(now.duration_since(started), quiet, waiting, gate, &live);
1847        if let Some(why) = why {
1848            let _ = child.kill();
1849            let _ = child.wait();
1850            return Ok(Ran::TimedOut(Killed {
1851                why,
1852                ran_secs: now.duration_since(started).as_secs(),
1853                // The true OUTPUT silence, for the message — not the
1854                // still-time the verdict was judged on.
1855                quiet_secs: activity.map(|a| a.quiet_for().as_secs()),
1856                cpu: activity.map_or(CpuVerdict::NotSampled, Activity::verdict),
1857                idle_secs: clocks.silence.unwrap_or(0),
1858                waiting: waiting.map(|(k, d)| (k, d.as_secs())),
1859                last_line: activity.and_then(Activity::last_line),
1860                load,
1861            }));
1862        }
1863        std::thread::sleep(std::time::Duration::from_millis(25));
1864    }
1865}
1866
1867/// Which clock, if any, has fired — the decision, with no process or
1868/// clock of its own so it can be tested to the second.
1869///
1870/// `ran` is how long the command has been running; `quiet` how long it has
1871/// been silent (and idle, where CPU is sampled), `None` when nobody is
1872/// watching its output; `waiting` the declared wait in progress, with its
1873/// length. The ceiling wins when several have fired: it is the larger
1874/// claim, and the message for it carries the other figures anyway. A
1875/// declared wait answers to `lock_wait`, never to the silence budget — the
1876/// tool has said what it is doing — and with `lock_wait` deferring to a
1877/// ceiling that is off, to the extended silence budget, so that nothing is
1878/// unbounded. `cpu` picks which silence budget applies: the plain one when
1879/// idleness was measured or is not sampled at all, the extended one while
1880/// the sampler cannot say ([`CpuGate`]).
1881pub fn judge(
1882    ran: std::time::Duration,
1883    quiet: Option<std::time::Duration>,
1884    waiting: Option<(crate::hooks::wait::WaitKind, std::time::Duration)>,
1885    cpu: CpuGate,
1886    clocks: &Clocks,
1887) -> Option<Why> {
1888    if let Some(wall) = clocks.ceiling {
1889        if ran >= std::time::Duration::from_secs(wall) {
1890            return Some(Why::Ceiling(wall));
1891        }
1892    }
1893    if let Some((kind, waited)) = waiting {
1894        let budget = match clocks.lock_wait {
1895            LockWait::Secs(s) => Some(s),
1896            LockWait::UntilCeiling if clocks.ceiling.is_some() => None,
1897            LockWait::UntilCeiling => clocks.extended,
1898        };
1899        return match budget {
1900            Some(b) if waited >= std::time::Duration::from_secs(b) => Some(Why::Waited(kind, b)),
1901            _ => None,
1902        };
1903    }
1904    let budget = match cpu {
1905        CpuGate::NotSampled | CpuGate::Measured => clocks.silence,
1906        CpuGate::Unmeasured => clocks.extended.or(clocks.silence),
1907    };
1908    if let (Some(idle), Some(q)) = (budget, quiet) {
1909        if q >= std::time::Duration::from_secs(idle) {
1910            return Some(Why::Silence(idle));
1911        }
1912    }
1913    None
1914}
1915
1916/// Say a command was killed, by which clock, and what that tells you.
1917///
1918/// The two clocks exist to answer two different questions, so the message
1919/// answers the one that was asked: silence means stuck — look at the tool;
1920/// the ceiling with recent output means slow — raise the ceiling.
1921pub fn say_timed_out(what: &str, k: Killed) {
1922    match k.why {
1923        Why::Silence(budget) => {
1924            // Why the budget is not the configured one, when it is not:
1925            // the extended budget while CPU could not be measured, or the
1926            // configured one stretched by the host's load.
1927            let stretched = match (k.cpu, k.load) {
1928                _ if budget == k.idle_secs => String::new(),
1929                (CpuVerdict::Unmeasured, _) => format!(
1930                    " (the extended budget, {} × {}: its CPU could not be measured)",
1931                    human_secs(k.idle_secs),
1932                    hl("amont.idleLoadScale")
1933                ),
1934                (_, Some((load, factor))) => format!(
1935                    " ({} stretched {} by a load average of {} on {} cores — {})",
1936                    human_secs(k.idle_secs),
1937                    crate::load::factor_text(factor),
1938                    load.avg1_text(),
1939                    load.cores,
1940                    hl("amont.idleLoadScale")
1941                ),
1942                _ => String::new(),
1943            };
1944            fail(&match k.cpu {
1945                CpuVerdict::MeasuredIdle(covered) => format!(
1946                    "{} printed nothing for {}{stretched} and did no measurable CPU work \
1947                     (< 0.1 core) in the last {} of it; killed after {} — a tool this idle \
1948                     is stuck, not slow. {} raises the silence budget (0 disables)",
1949                    hl(what),
1950                    human_secs(budget),
1951                    human_secs(covered.max(1)),
1952                    human_secs(k.ran_secs),
1953                    hl("git config amont.idleTimeout <secs>")
1954                ),
1955                _ => format!(
1956                    "{} printed nothing for {}{stretched}{} and was killed after {} — a tool \
1957                     this quiet is usually stuck, not slow. {} raises the silence budget (0 \
1958                     disables)",
1959                    hl(what),
1960                    human_secs(budget),
1961                    if k.cpu == CpuVerdict::Unmeasured && stretched.is_empty() {
1962                        " (CPU not measured)"
1963                    } else {
1964                        ""
1965                    },
1966                    human_secs(k.ran_secs),
1967                    hl("git config amont.idleTimeout <secs>")
1968                ),
1969            })
1970        }
1971        Why::Waited(kind, budget) => fail(&format!(
1972            "{} waited {} for {} and was killed after {} — {}. {} raises the wait budget \
1973             (0: until the ceiling)",
1974            hl(what),
1975            human_secs(budget),
1976            kind.describe(),
1977            human_secs(k.ran_secs),
1978            kind.holders(),
1979            hl("git config amont.lockWait <secs>")
1980        )),
1981        Why::Ceiling(budget) => {
1982            let verdict = match (k.quiet_secs, k.cpu) {
1983                (_, _) if k.waiting.is_some() => {
1984                    let (kind, w) = k.waiting.expect("checked");
1985                    format!(
1986                        " It was waiting for {} for the last {} — {}.",
1987                        kind.describe(),
1988                        human_secs(w),
1989                        kind.holders()
1990                    )
1991                }
1992                (Some(q), CpuVerdict::BusyAtKill(m)) if k.idle_secs > 0 && q >= k.idle_secs => {
1993                    format!(
1994                        " It printed nothing for the last {} but kept its CPU busy ({}), so the \
1995                     silence budget did not stop it: a busy loop, or a tool that prints only \
1996                     at the end (give it a per-file reporter). {} kills quiet runs at the \
1997                     silence budget whatever their CPU.",
1998                        human_secs(q),
1999                        cores(m),
2000                        hl("git config amont.idleCpuCredit false")
2001                    )
2002                }
2003                (Some(q), CpuVerdict::Unmeasured) if k.idle_secs > 0 && q >= k.idle_secs => {
2004                    format!(
2005                        " It printed nothing for the last {} and its CPU could not be measured, \
2006                         so only the extended silence budget applied. {} kills quiet runs at \
2007                         the silence budget whatever their CPU.",
2008                        human_secs(q),
2009                        hl("git config amont.idleCpuCredit false")
2010                    )
2011                }
2012                (Some(q), _) if q < 30 => format!(
2013                    " It was still printing ({} since its last line): slow, not stuck.",
2014                    human_secs(q)
2015                ),
2016                (Some(q), _) => format!(" Its last output was {} ago.", human_secs(q)),
2017                (None, _) => String::new(),
2018            };
2019            fail(&format!(
2020                "{} timed out: ran for {} and was killed at the ceiling. {} raises it \
2021                 (0 disables).{verdict}",
2022                hl(what),
2023                human_secs(budget),
2024                hl("git config amont.timeout <secs>")
2025            ))
2026        }
2027    }
2028}
2029
2030/// [`status_within`], collapsed to "did it exit 0" — the shape the one-shot
2031/// tool spawns want. A timeout says so, names `what`, and reads as failure.
2032pub fn bounded_success(settings: &crate::config::Settings, cmd: &mut Command, what: &str) -> bool {
2033    match status_streamed(settings, cmd, Retry::Once) {
2034        Ok(Ran::Status(s)) => s.success(),
2035        Ok(Ran::TimedOut(b)) => {
2036            say_timed_out(what, b);
2037            false
2038        }
2039        Err(_) => false,
2040    }
2041}
2042
2043/// Run `argv` from `root`, inheriting stdio. True when it exits 0.
2044pub fn run(
2045    settings: &crate::config::Settings,
2046    root: &str,
2047    argv: &[String],
2048    extra: &[String],
2049) -> bool {
2050    let Some((program, rest)) = argv.split_first() else {
2051        return true;
2052    };
2053    let mut cmd = Command::new(program);
2054    cmd.args(rest)
2055        .args(extra)
2056        .current_dir(root)
2057        .stdin(Stdio::null());
2058    strip_git_env(&mut cmd);
2059    bounded_success(settings, &mut cmd, program)
2060}
2061
2062/// As [`run`], but with the tool's own output discarded.
2063///
2064/// For a pass whose only job is to decide something — prettier's `--check`,
2065/// ruff's `--fix` sweep — where the offenders are printed once, by the pass
2066/// that reports them, rather than twice.
2067pub fn run_quiet(
2068    settings: &crate::config::Settings,
2069    root: &str,
2070    argv: &[String],
2071    extra: &[String],
2072) -> bool {
2073    let Some((program, rest)) = argv.split_first() else {
2074        return true;
2075    };
2076    let mut cmd = Command::new(program);
2077    cmd.args(rest)
2078        .args(extra)
2079        .current_dir(root)
2080        .stdin(Stdio::null());
2081    strip_git_env(&mut cmd);
2082    // Deliberately NOT the streamed runner: this helper's contract is that
2083    // the output is discarded, and capture would resurrect it into the
2084    // block. Observed and dropped instead of `/dev/null`, so the silence
2085    // clock still sees whether the tool is alive.
2086    match run_observed(settings, &mut cmd, |_| {}, None) {
2087        Ok(Ran::Status(s)) => s.success(),
2088        Ok(Ran::TimedOut(b)) => {
2089            say_timed_out(program, b);
2090            false
2091        }
2092        Err(_) => false,
2093    }
2094}
2095
2096/// Whether the user asked for checks to repair what they find.
2097///
2098/// OFF by default. `git config amont.fix true` turns it on, per repository,
2099/// because a hook that edits your files without being asked is a larger
2100/// surprise than one that complains — and because with index fidelity in place
2101/// the repair lands in the commit you are making, which is a bigger claim to
2102/// make on somebody's behalf than printing an error.
2103pub fn fixing_enabled(settings: &crate::config::Settings) -> bool {
2104    // Never while the file set is not the index — see `NOT_THE_INDEX`.
2105    !not_the_index() && fixing_requested(settings)
2106}
2107
2108/// What the CONFIG says, ignoring whether the current run may act on it.
2109///
2110/// Split out so `run_all` can tell the difference between "fixing is off" and
2111/// "you asked for fixing and this mode will not do it", and say the second out
2112/// loud instead of silently ignoring the key.
2113pub fn fixing_requested(settings: &crate::config::Settings) -> bool {
2114    *settings
2115        .fixing
2116        .get_or_init(|| crate::config::boolean_or(settings, "amont.fix", false))
2117}
2118
2119/// What a re-stage actually did. THREE answers, because the old `bool`
2120/// conflated two of them and the conflation shipped unformatted code.
2121///
2122/// `prettier.rs` read `if run_quiet(write) && restage(&files) { … Fixed }`. When
2123/// `git add` FAILED, `restage` returned `false` — indistinguishable from
2124/// "nothing needed staging" — so control fell through to a second `--check`
2125/// pass, which inspected the NOW-FORMATTED WORKING TREE, passed, printed
2126/// "Prettier passed" and returned `Outcome::Passed`. The index still held the
2127/// unformatted content, so the commit contained unformatted code and the hook
2128/// said it had passed. `manifest.rs` had the same shape.
2129#[derive(Debug, Clone, PartialEq, Eq)]
2130pub enum Restaged {
2131    /// No path differed from the index — nothing to do, and nothing wrong.
2132    Nothing,
2133    /// `git add` succeeded; the index now holds the repair.
2134    Staged,
2135    /// `git add` failed, carrying the paths it could not stage. The index
2136    /// holds content the fixer has already replaced on disk, so this MUST be
2137    /// loud at every call site — and naming the files is the difference
2138    /// between a message somebody can act on and one they cannot.
2139    Failed(Vec<String>),
2140}
2141
2142/// Serialises this process's own `git add` calls.
2143///
2144/// pre-commit runs its checks concurrently (`dispatch.rs`), and up to three of
2145/// them can re-stage. git takes `$GIT_DIR/index.lock` exclusively, so two
2146/// concurrent `git add`s in the same repository make one of them fail — which,
2147/// before `Restaged`, was silently read as "nothing moved". Holding this across
2148/// the `git add` removes self-contention entirely; the retry below is only for
2149/// OTHER processes.
2150static INDEX_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2151
2152/// Re-stage exactly the paths a fixer rewrote, and say what happened.
2153///
2154/// Safe ONLY because the pre-commit stage holds unstaged changes aside: the
2155/// tree contains the staged content and nothing else, so anything a formatter
2156/// touched is by definition part of this commit. Without that, re-staging would
2157/// sweep in work the author deliberately kept back.
2158pub fn restage(paths: &[String]) -> Restaged {
2159    // Belt and braces alongside `fixing_enabled`: a future fixer that forgets
2160    // the gate still cannot turn `amont run --all-files` into `git add .`.
2161    if not_the_index() {
2162        return Restaged::Nothing;
2163    }
2164    let changed: Vec<String> = paths
2165        .iter()
2166        .filter(|p| !git::succeeds(&["diff", "--quiet", "--", p]))
2167        .cloned()
2168        .collect();
2169    if changed.is_empty() {
2170        return Restaged::Nothing;
2171    }
2172    let mut args = vec!["add", "--"];
2173    args.extend(changed.iter().map(String::as_str));
2174
2175    let _serialised = INDEX_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2176    // Another PROCESS can hold `index.lock` — a `git status` from an editor, a
2177    // second hook in a linked worktree. Back off and retry rather than
2178    // reporting a transient collision as a failed repair. `git add` of the same
2179    // paths is idempotent: it records the paths' current worktree content, so
2180    // running it twice records the same thing twice and cannot double-stage.
2181    const BACKOFF_MS: [u64; 3] = [50, 150, 400];
2182    if git::succeeds(&args) {
2183        return Restaged::Staged;
2184    }
2185    for wait in BACKOFF_MS {
2186        std::thread::sleep(std::time::Duration::from_millis(wait));
2187        if git::succeeds(&args) {
2188            return Restaged::Staged;
2189        }
2190    }
2191    Restaged::Failed(changed)
2192}
2193
2194/// A check passed. THE funnel for every success line, which is what lets
2195/// `amont.quiet` swallow them in one place — see [`crate::live::quiet`].
2196pub fn ok(settings: &crate::config::Settings, msg: &str) {
2197    if crate::live::quiet(settings) {
2198        return;
2199    }
2200    crate::live::say(&format!("{} {msg}", valid_sign()));
2201}
2202pub fn fail(msg: &str) {
2203    // As for `warn` below: a deferred check's refused spawn is not a failure,
2204    // and saying "Clippy warnings" or "tests failed. Push aborted." before
2205    // the deferral line contradicts it (ADR-0013).
2206    if crate::host_slots::deferred_here() {
2207        return;
2208    }
2209    crate::live::say(&format!("{} {msg}", error_sign()));
2210}
2211pub fn warn(msg: &str) {
2212    // A check the busy policy deferred has its spawn refused, and whatever
2213    // it then says about that ("could not run …") is not a finding: the
2214    // dispatcher's deferral line is the one thing to say (ADR-0013).
2215    if crate::host_slots::deferred_here() {
2216        return;
2217    }
2218    crate::live::say(&format!("{} {msg}", warning_sign()));
2219}
2220/// A line with no sign of its own — what a check's direct `println!` becomes,
2221/// so it lands in the check's block instead of interleaving. See `live::say`.
2222pub fn say(msg: &str) {
2223    crate::live::say(msg);
2224}
2225
2226/// Orange, for the fragments these hooks highlight.
2227pub fn hl(s: &str) -> String {
2228    crate::ui::highlight(s)
2229}
2230
2231#[cfg(test)]
2232mod tests {
2233
2234    /// Git ends a path with one `\n`; a `\r` before it is part of the name.
2235    #[test]
2236    fn only_the_one_newline_git_prints_is_stripped() {
2237        assert_eq!(super::strip_one_newline(b"/r/.git\n".to_vec()), b"/r/.git");
2238        assert_eq!(super::strip_one_newline(b"/r/x\r\n".to_vec()), b"/r/x\r");
2239        assert_eq!(super::strip_one_newline(b"/r/x".to_vec()), b"/r/x");
2240    }
2241
2242    /// Runs on every platform, so the non-unix `path_from_bytes` is covered
2243    /// on Windows CI too.
2244    #[test]
2245    fn a_git_path_becomes_the_same_path() {
2246        assert_eq!(
2247            super::path_from_bytes(b"/r/.git/index".to_vec()),
2248            std::path::PathBuf::from("/r/.git/index")
2249        );
2250    }
2251
2252    #[test]
2253    fn a_lookup_error_says_git_s_reason() {
2254        let e = super::IndexLookupError::Git {
2255            args: "rev-parse --git-path index".into(),
2256            why: "fatal: not a git repository".into(),
2257        };
2258        assert_eq!(
2259            e.to_string(),
2260            "git rev-parse --git-path index failed: fatal: not a git repository"
2261        );
2262    }
2263
2264    /// A window of `milli` thousandths of a core between `start` and `end`
2265    /// (a zero-length window still reports `milli`: `milli_cores` floors the
2266    /// wall time at 1 ns).
2267    fn window(
2268        start: std::time::Instant,
2269        end: std::time::Instant,
2270        milli: u64,
2271    ) -> crate::proctree::Observation {
2272        let wall = u64::try_from(end.duration_since(start).as_nanos())
2273            .unwrap_or(u64::MAX)
2274            .max(1);
2275        let gain = wall * milli / 1000;
2276        crate::proctree::Observation::Window(crate::proctree::Window {
2277            start,
2278            end,
2279            gain_ns: gain,
2280            gapped: false,
2281        })
2282    }
2283
2284    /// A gapped window resets the measured-idle span to its own end: the
2285    /// claim never covers the gap, while a busy gapped window still counts
2286    /// as busy.
2287    #[test]
2288    fn a_gapped_window_is_never_claimed_as_measured_idle() {
2289        use super::{Activity, CpuVerdict};
2290        use crate::proctree::{Observation, Window};
2291        let s = std::time::Duration::from_secs;
2292        let every = s(10);
2293        let a = Activity::new();
2294        a.enable_cpu();
2295        let t0 = std::time::Instant::now() - s(30);
2296        a.record(Observation::Baseline, t0, every);
2297        a.record(Observation::Skipped, t0 + s(10), every);
2298        let gap_end = std::time::Instant::now();
2299        a.record(
2300            Observation::Window(Window {
2301                start: t0,
2302                end: gap_end,
2303                gain_ns: 0,
2304                gapped: true,
2305            }),
2306            gap_end,
2307            every,
2308        );
2309        // Idle, but the span rests only on what followed the gap: 0 s.
2310        assert_eq!(a.verdict(), CpuVerdict::MeasuredIdle(0));
2311        assert_eq!(a.gate(), super::CpuGate::Measured);
2312
2313        let busy = Activity::new();
2314        busy.enable_cpu();
2315        busy.record(Observation::Baseline, t0, every);
2316        busy.record(Observation::Skipped, t0 + s(10), every);
2317        let now = std::time::Instant::now();
2318        busy.record(window_gapped(t0, now, 3000), now, every);
2319        assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3000));
2320        assert!(busy.still_for() < s(1));
2321    }
2322
2323    fn window_gapped(
2324        start: std::time::Instant,
2325        end: std::time::Instant,
2326        milli: u64,
2327    ) -> crate::proctree::Observation {
2328        match window(start, end, milli) {
2329            crate::proctree::Observation::Window(w) => {
2330                crate::proctree::Observation::Window(crate::proctree::Window { gapped: true, ..w })
2331            }
2332            o => o,
2333        }
2334    }
2335
2336    /// Even the shortest budget is sampled several times before it runs out,
2337    /// and the default one starts at 30 s and repeats every 10 s.
2338    #[test]
2339    fn the_sampling_schedule_follows_the_budget_within_floors() {
2340        use super::sampling_schedule;
2341        let ms = std::time::Duration::from_millis;
2342        let third = |secs: u64| std::time::Duration::from_secs(secs) / 3;
2343        assert_eq!(sampling_schedule(1), (third(1), ms(250)));
2344        assert_eq!(sampling_schedule(2), (third(2), ms(500)));
2345        assert_eq!(sampling_schedule(120), (ms(30_000), ms(10_000)));
2346        assert_eq!(sampling_schedule(0), (ms(250), ms(250)));
2347    }
2348
2349    /// Without CPU data the still-time IS the silence; a busy window pulls it
2350    /// back to the window's start, and the output clock is left alone.
2351    #[test]
2352    fn busy_work_resets_the_still_time_but_not_the_output_silence() {
2353        use super::Activity;
2354        let a = Activity::new();
2355        a.touch();
2356        std::thread::sleep(std::time::Duration::from_millis(60));
2357        let quiet = a.quiet_for();
2358        assert!(a.still_for() >= quiet.saturating_sub(std::time::Duration::from_millis(5)));
2359        a.enable_cpu();
2360        let now = std::time::Instant::now();
2361        a.record(
2362            window(now - std::time::Duration::from_millis(10), now, 2000),
2363            now,
2364            std::time::Duration::from_secs(1),
2365        );
2366        assert!(a.still_for() < std::time::Duration::from_millis(40));
2367        assert!(a.quiet_for() >= std::time::Duration::from_millis(60));
2368    }
2369
2370    /// What the kill message may claim. "Measured idle" names the unbroken
2371    /// span of complete measurements behind it; a broken run is unmeasured;
2372    /// a fresh busy window is reported as busy; no sampling says nothing.
2373    #[test]
2374    fn the_cpu_verdict_claims_only_what_was_measured() {
2375        use super::{Activity, CpuVerdict};
2376        use crate::proctree::Observation;
2377        let s = std::time::Duration::from_secs;
2378        let every = s(10);
2379
2380        let off = Activity::new();
2381        assert_eq!(off.verdict(), CpuVerdict::NotSampled);
2382
2383        let waiting = Activity::new();
2384        waiting.enable_cpu();
2385        assert_eq!(waiting.verdict(), CpuVerdict::Unmeasured);
2386
2387        let now = std::time::Instant::now();
2388        let before = now - s(1);
2389        // A real second of complete, idle measurement: the claim names it.
2390        let idle = Activity::new();
2391        idle.enable_cpu();
2392        let t0 = std::time::Instant::now();
2393        idle.record(Observation::Baseline, t0, every);
2394        std::thread::sleep(std::time::Duration::from_millis(1050));
2395        let t1 = std::time::Instant::now();
2396        idle.record(window(t0, t1, 20), t1, every);
2397        assert_eq!(idle.verdict(), CpuVerdict::MeasuredIdle(1));
2398
2399        let busy = Activity::new();
2400        busy.enable_cpu();
2401        busy.record(Observation::Baseline, before, every);
2402        busy.record(window(before, now, 3900), now, every);
2403        assert_eq!(busy.verdict(), CpuVerdict::BusyAtKill(3900));
2404
2405        let broken = Activity::new();
2406        broken.enable_cpu();
2407        broken.record(Observation::Baseline, before, every);
2408        broken.record(window(before, now, 20), now, every);
2409        broken.record(Observation::Unmeasured, now, every);
2410        assert_eq!(broken.verdict(), CpuVerdict::Unmeasured);
2411        assert_eq!(broken.gate(), super::CpuGate::Unmeasured);
2412        assert_eq!(off.gate(), super::CpuGate::NotSampled);
2413        assert_eq!(idle.gate(), super::CpuGate::Measured);
2414        assert_eq!(busy.gate(), super::CpuGate::Measured);
2415    }
2416
2417    /// A rate older than two sampling intervals is not shown, and cannot
2418    /// back a "busy" or "idle" claim.
2419    #[test]
2420    fn a_stale_rate_expires() {
2421        use super::{Activity, CpuVerdict};
2422        use crate::proctree::Observation;
2423        let a = Activity::new();
2424        a.enable_cpu();
2425        let then = std::time::Instant::now();
2426        let tick = std::time::Duration::from_millis(5);
2427        let earlier = then - std::time::Duration::from_secs(1);
2428        a.record(Observation::Baseline, earlier, tick);
2429        a.record(window(earlier, then, 3000), then, tick);
2430        std::thread::sleep(std::time::Duration::from_millis(40));
2431        assert_eq!(a.fresh_rate(), None);
2432        assert_eq!(a.verdict(), CpuVerdict::Unmeasured);
2433    }
2434
2435    #[test]
2436    fn cores_read_as_one_decimal() {
2437        assert_eq!(super::cores(3900), "~3.9 cores");
2438        assert_eq!(super::cores(420), "~0.4 cores");
2439        assert_eq!(super::cores(100), "~0.1 cores");
2440    }
2441
2442    /// The two clocks, decided to the second. A chatty command outlives any
2443    /// silence budget however long it runs; a silent one dies at the budget
2444    /// however short; a command nobody watches answers to the ceiling only.
2445    #[test]
2446    fn the_clocks_judge_silence_and_ceiling_separately() {
2447        use super::{judge, CpuGate, Why};
2448        use std::time::Duration as D;
2449        let s = D::from_secs;
2450        let c = |ceiling: Option<u64>, silence: Option<u64>| super::Clocks {
2451            ceiling,
2452            silence,
2453            lock_wait: super::LockWait::Secs(600),
2454            extended: silence,
2455            scale: 1,
2456        };
2457        // Chatty and long: past a five-second silence budget, still fine.
2458        assert_eq!(
2459            judge(
2460                s(900),
2461                Some(s(0)),
2462                None,
2463                CpuGate::NotSampled,
2464                &c(Some(3600), Some(5))
2465            ),
2466            None
2467        );
2468        assert_eq!(
2469            judge(
2470                s(900),
2471                Some(s(4)),
2472                None,
2473                CpuGate::NotSampled,
2474                &c(Some(3600), Some(5))
2475            ),
2476            None
2477        );
2478        // Silent for the budget: killed, and the silence is blamed.
2479        assert_eq!(
2480            judge(
2481                s(30),
2482                Some(s(5)),
2483                None,
2484                CpuGate::NotSampled,
2485                &c(Some(3600), Some(5))
2486            ),
2487            Some(Why::Silence(5))
2488        );
2489        // Unobserved output: the silence clock cannot run at all.
2490        assert_eq!(
2491            judge(
2492                s(900),
2493                None,
2494                None,
2495                CpuGate::NotSampled,
2496                &c(Some(3600), Some(5))
2497            ),
2498            None
2499        );
2500        // The ceiling fires on elapsed time whatever the output is doing.
2501        assert_eq!(
2502            judge(
2503                s(3600),
2504                Some(s(0)),
2505                None,
2506                CpuGate::NotSampled,
2507                &c(Some(3600), Some(120))
2508            ),
2509            Some(Why::Ceiling(3600))
2510        );
2511        // Both fired at once: the ceiling is the answer.
2512        assert_eq!(
2513            judge(
2514                s(3600),
2515                Some(s(600)),
2516                None,
2517                CpuGate::NotSampled,
2518                &c(Some(3600), Some(120))
2519            ),
2520            Some(Why::Ceiling(3600))
2521        );
2522        // Both off: nothing ever fires.
2523        assert_eq!(
2524            judge(
2525                s(86_400),
2526                Some(s(86_400)),
2527                None,
2528                CpuGate::NotSampled,
2529                &c(None, None)
2530            ),
2531            None
2532        );
2533        // Only silence on: no ceiling, however long it runs.
2534        assert_eq!(
2535            judge(
2536                s(86_400),
2537                Some(s(1)),
2538                None,
2539                CpuGate::NotSampled,
2540                &c(None, Some(120))
2541            ),
2542            None
2543        );
2544    }
2545
2546    /// A declared wait answers to `amont.lockWait` and never to the silence
2547    /// budget; at 0 it answers to the ceiling, and with the ceiling off too,
2548    /// to the extended silence budget — never to nothing.
2549    #[test]
2550    fn a_declared_wait_answers_to_its_own_budget() {
2551        use super::{judge, Clocks, CpuGate, LockWait, Why};
2552        use crate::hooks::wait::{CargoLockWhat, WaitKind};
2553        use std::time::Duration as D;
2554        let s = D::from_secs;
2555        let kind = WaitKind::CargoLock(CargoLockWhat::BuildDirectory);
2556        let clocks = Clocks {
2557            ceiling: Some(3600),
2558            silence: Some(120),
2559            lock_wait: LockWait::Secs(600),
2560            extended: Some(480),
2561            scale: 4,
2562        };
2563        // Silent for ten times the budget, but in a declared wait: fine.
2564        assert_eq!(
2565            judge(
2566                s(1300),
2567                Some(s(0)),
2568                Some((kind, s(599))),
2569                CpuGate::Measured,
2570                &clocks
2571            ),
2572            None
2573        );
2574        // The wait outlives its budget: killed, and the wait is blamed.
2575        assert_eq!(
2576            judge(
2577                s(1300),
2578                Some(s(0)),
2579                Some((kind, s(600))),
2580                CpuGate::Measured,
2581                &clocks
2582            ),
2583            Some(Why::Waited(kind, 600))
2584        );
2585        // The ceiling still wins.
2586        assert_eq!(
2587            judge(
2588                s(3600),
2589                Some(s(0)),
2590                Some((kind, s(3000))),
2591                CpuGate::Measured,
2592                &clocks
2593            ),
2594            Some(Why::Ceiling(3600))
2595        );
2596        // lockWait 0 with a ceiling: the ceiling alone bounds the wait.
2597        let until = Clocks {
2598            lock_wait: LockWait::UntilCeiling,
2599            ..clocks
2600        };
2601        assert_eq!(
2602            judge(
2603                s(3000),
2604                Some(s(0)),
2605                Some((kind, s(2900))),
2606                CpuGate::Measured,
2607                &until
2608            ),
2609            None
2610        );
2611        // lockWait 0 and no ceiling: the extended budget bounds it.
2612        let open = Clocks {
2613            ceiling: None,
2614            ..until
2615        };
2616        assert_eq!(
2617            judge(
2618                s(3000),
2619                Some(s(0)),
2620                Some((kind, s(479))),
2621                CpuGate::Measured,
2622                &open
2623            ),
2624            None
2625        );
2626        assert_eq!(
2627            judge(
2628                s(3000),
2629                Some(s(0)),
2630                Some((kind, s(480))),
2631                CpuGate::Measured,
2632                &open
2633            ),
2634            Some(Why::Waited(kind, 480))
2635        );
2636    }
2637
2638    /// One retry, only after a silence kill whose last line reads like a
2639    /// wait, only for a built-in, only with a silence budget of ceiling
2640    /// left, and under what is left.
2641    #[test]
2642    fn a_wait_like_silence_kill_earns_one_retry_under_the_remaining_ceiling() {
2643        use super::{retry_budget, CpuVerdict, Killed, Retry, Why};
2644        use crate::hooks::wait::{CargoLockWhat, WaitKind};
2645        let k = |why: Why, line: &str, ran: u64| Killed {
2646            why,
2647            ran_secs: ran,
2648            quiet_secs: Some(ran),
2649            cpu: CpuVerdict::MeasuredIdle(1),
2650            idle_secs: 120,
2651            waiting: None,
2652            last_line: Some(line.to_string()),
2653            load: None,
2654        };
2655        let wait = "waiting for lock on x";
2656        assert_eq!(
2657            retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 3600),
2658            Some(Some(3480))
2659        );
2660        assert_eq!(
2661            retry_budget(Retry::Once, &k(Why::Silence(120), wait, 120), 0),
2662            Some(None)
2663        );
2664        assert_eq!(
2665            retry_budget(Retry::Never, &k(Why::Silence(120), wait, 120), 3600),
2666            None
2667        );
2668        assert_eq!(
2669            retry_budget(
2670                Retry::Once,
2671                &k(Why::Silence(120), "test_lock.py::x", 120),
2672                3600
2673            ),
2674            None
2675        );
2676        assert_eq!(
2677            retry_budget(Retry::Once, &k(Why::Ceiling(3600), wait, 3600), 3600),
2678            None
2679        );
2680        let waited = Why::Waited(WaitKind::CargoLock(CargoLockWhat::BuildDirectory), 600);
2681        assert_eq!(retry_budget(Retry::Once, &k(waited, wait, 700), 3600), None);
2682        // Less than one silence budget of ceiling left: no retry.
2683        assert_eq!(
2684            retry_budget(Retry::Once, &k(Why::Silence(120), wait, 3500), 3600),
2685            None
2686        );
2687    }
2688
2689    /// While the CPU is unmeasured the silence budget is the extended one:
2690    /// no kill before `idle × scale`, a kill at it even with the ceiling
2691    /// off; measured and not-sampled keep the plain budget.
2692    #[test]
2693    fn an_unmeasured_cpu_answers_to_the_extended_budget() {
2694        use super::{judge, Clocks, CpuGate, LockWait, Why};
2695        use std::time::Duration as D;
2696        let s = D::from_secs;
2697        let clocks = Clocks {
2698            ceiling: None,
2699            silence: Some(120),
2700            lock_wait: LockWait::Secs(600),
2701            extended: Some(480),
2702            scale: 4,
2703        };
2704        assert_eq!(
2705            judge(s(500), Some(s(300)), None, CpuGate::Unmeasured, &clocks),
2706            None
2707        );
2708        assert_eq!(
2709            judge(s(500), Some(s(479)), None, CpuGate::Unmeasured, &clocks),
2710            None
2711        );
2712        assert_eq!(
2713            judge(s(500), Some(s(480)), None, CpuGate::Unmeasured, &clocks),
2714            Some(Why::Silence(480))
2715        );
2716        assert_eq!(
2717            judge(s(500), Some(s(120)), None, CpuGate::Measured, &clocks),
2718            Some(Why::Silence(120))
2719        );
2720        assert_eq!(
2721            judge(s(500), Some(s(120)), None, CpuGate::NotSampled, &clocks),
2722            Some(Why::Silence(120))
2723        );
2724        // No extended budget configured (silence off): nothing fires.
2725        let off = Clocks {
2726            silence: None,
2727            extended: None,
2728            ..clocks
2729        };
2730        assert_eq!(
2731            judge(s(86_400), Some(s(86_400)), None, CpuGate::Unmeasured, &off),
2732            None
2733        );
2734    }
2735
2736    /// A marker line starts a wait that a second marker continues and any
2737    /// other line ends; the silence the clock counts is zero meanwhile, the
2738    /// output silence is not, and the time is banked for the note.
2739    #[test]
2740    fn a_marker_line_pauses_the_silence_clock_until_another_line() {
2741        use super::Activity;
2742        use crate::hooks::wait::{CargoLockWhat, WaitKind};
2743        let a = Activity::new();
2744        a.touch();
2745        assert_eq!(a.waiting(), None);
2746        a.stderr_line("    Blocking waiting for file lock on package cache");
2747        std::thread::sleep(std::time::Duration::from_millis(30));
2748        let (kind, waited) = a.waiting().expect("a wait is in progress");
2749        assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::PackageCache));
2750        assert!(waited >= std::time::Duration::from_millis(30));
2751        assert_eq!(a.silence_for(), std::time::Duration::ZERO);
2752        assert_eq!(a.still_for(), std::time::Duration::ZERO);
2753        assert!(a.quiet_for() >= std::time::Duration::from_millis(30));
2754        // A second marker keeps the original start, and names the new lock.
2755        a.stderr_line("\u{1b}[1m    Blocking\u{1b}[0m waiting for file lock on build directory");
2756        let (kind, again) = a.waiting().expect("still waiting");
2757        assert_eq!(kind, WaitKind::CargoLock(CargoLockWhat::BuildDirectory));
2758        assert!(again >= waited);
2759        // Any other line ends it, and the time spent is banked. The reader
2760        // touches the output clock before it frames, as here.
2761        a.touch();
2762        a.stderr_line("    Checking foo v0.1.0");
2763        assert_eq!(a.waiting(), None);
2764        assert!(a.waited_total() >= std::time::Duration::from_millis(30));
2765        assert_eq!(a.last_wait_kind(), Some(kind));
2766        assert_eq!(a.last_line().as_deref(), Some("Checking foo v0.1.0"));
2767        assert!(a.silence_for() < std::time::Duration::from_millis(20));
2768        // A stdout chunk ends a wait too.
2769        a.stderr_line("Waiting to acquire write lock for `x`");
2770        assert!(a.waiting().is_some());
2771        a.end_wait();
2772        assert_eq!(a.waiting(), None);
2773    }
2774
2775    /// The deadline kills what outlives it and reports what finished.
2776    #[cfg(unix)]
2777    #[test]
2778    fn the_deadline_kills_a_sleeper_and_spares_a_finisher() {
2779        let started = std::time::Instant::now();
2780        let mut slow = Command::new(program("sleep"));
2781        slow.arg("300").stdin(Stdio::null());
2782        match status_within_secs(&mut slow, 1) {
2783            Ok(Ran::TimedOut(Killed {
2784                why: Why::Ceiling(1),
2785                quiet_secs: None,
2786                ..
2787            })) => {}
2788            other => panic!("expected TimedOut(1), got {:?}", other.map(|_| "ran")),
2789        }
2790        assert!(
2791            started.elapsed() < std::time::Duration::from_secs(60),
2792            "the kill did not happen at the deadline"
2793        );
2794
2795        let mut quick = Command::new(program("true"));
2796        quick.stdin(Stdio::null());
2797        match status_within_secs(&mut quick, 60) {
2798            Ok(Ran::Status(s)) => assert!(s.success()),
2799            other => panic!("expected a clean exit, got {:?}", other.map(|_| "?")),
2800        }
2801    }
2802
2803    use super::*;
2804
2805    #[test]
2806    fn which_finds_a_real_binary_and_not_a_fake_one() {
2807        assert!(which("git").is_some());
2808        assert!(which("definitely-not-a-real-binary-xyz").is_none());
2809    }
2810
2811    /// On Windows a tool can exist BOTH as an extensionless shell script and as
2812    /// a .cmd/.exe in the same directory; only the latter is executable by
2813    /// CreateProcess, so the extension forms must win.
2814    #[test]
2815    #[cfg(windows)]
2816    fn windows_prefers_an_executable_extension_over_a_bare_file() {
2817        let dir = std::env::temp_dir().join("amont-which-order");
2818        let _ = std::fs::create_dir_all(&dir);
2819        std::fs::write(dir.join("faketool"), "#!/bin/sh\n").unwrap();
2820        std::fs::write(dir.join("faketool.cmd"), "@echo off\n").unwrap();
2821        // The path is PASSED, never installed into this process: see
2822        // `which_on`. The old spelling swapped the real PATH out from under
2823        // every other test in this binary for the length of the call.
2824        let found = which_on(dir.as_os_str(), "faketool").unwrap();
2825        assert!(found.ends_with(".cmd"), "got {found}");
2826        let _ = std::fs::remove_dir_all(&dir);
2827    }
2828
2829    /// "Nothing moved" and "`git add` FAILED" are different answers, and the
2830    /// old `bool` gave the same one for both.
2831    ///
2832    /// That conflation is what shipped unformatted code: `prettier.rs` read
2833    /// `if wrote && restage(&files)`, so a failed `git add` fell through to a
2834    /// second `--check` against the now-formatted WORKING TREE, which passed —
2835    /// while the INDEX still held the unformatted content the commit would
2836    /// carry.
2837    ///
2838    /// An absolute path outside any repository is a `git add` git will always
2839    /// refuse, which is the only way to reach the failing branch without
2840    /// sabotaging a real index.
2841    #[test]
2842    fn restage_distinguishes_nothing_from_failure() {
2843        // `restage` runs `git add` in the PROCESS cwd, so this test depends
2844        // on that cwd as surely as one that moves it — see `crate::TEST_CWD`.
2845        // Without the lock it ran inside whatever fixture `gate_stamp` had
2846        // moved into, and took that repository's index.lock out from under
2847        // its own commit.
2848        let _cwd = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
2849        let outside = std::env::temp_dir()
2850            .join("amont-restage-outside-any-repo")
2851            .to_string_lossy()
2852            .into_owned();
2853        assert_eq!(
2854            restage(std::slice::from_ref(&outside)),
2855            Restaged::Failed(vec![outside]),
2856            "a `git add` git refuses must report Failed, never Nothing"
2857        );
2858        assert_eq!(
2859            restage(&[]),
2860            Restaged::Nothing,
2861            "no paths is nothing to do, and nothing wrong"
2862        );
2863    }
2864
2865    /// No check may hand `Command` a bare program name.
2866    ///
2867    /// `Command::new` does NO PATHEXT resolution, so `Command::new("npm")`
2868    /// cannot execute `npm.cmd` and `Command::new("uvx")` cannot execute
2869    /// `uvx.exe`: the spawn fails with "program not found" and a
2870    /// `Severity::Block` check reports an installed tool as broken. That is the
2871    /// incident `program()` exists for, and it kept recurring — `yamllint` and
2872    /// three sites in `python_tools` were still doing it, THREE OF THEM after
2873    /// `which()` had already succeeded and discarded the answer.
2874    ///
2875    /// A source scan rather than a runtime assertion because the failure only
2876    /// reproduces on Windows, and the whole point is to catch the next one on
2877    /// every platform. Comment lines are skipped: `program()`'s own doc quotes
2878    /// the offending call. The needle is assembled from two pieces so this
2879    /// module — which the scan also reads — does not match itself.
2880    #[test]
2881    fn no_hook_spawns_a_bare_program_name() {
2882        let needle = concat!("Command", "::new(");
2883        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src/hooks");
2884        let mut scanned = 0usize;
2885        for entry in std::fs::read_dir(dir).expect("hooks dir").flatten() {
2886            let path = entry.path();
2887            if path.extension().and_then(|e| e.to_str()) != Some("rs") {
2888                continue;
2889            }
2890            scanned += 1;
2891            let src = std::fs::read_to_string(&path).expect("read a hook module");
2892            for (n, line) in src.lines().enumerate() {
2893                if line.trim_start().starts_with("//") {
2894                    continue;
2895                }
2896                let Some(after) = line.split_once(needle) else {
2897                    continue;
2898                };
2899                assert!(
2900                    !after.1.starts_with('"'),
2901                    "{}:{} spawns a bare name — route it through `program()` or \
2902                     the path `which()` already resolved: {}",
2903                    path.display(),
2904                    n + 1,
2905                    line.trim()
2906                );
2907            }
2908        }
2909        assert!(
2910            scanned > 10,
2911            "the scan found almost nothing: {scanned} files"
2912        );
2913    }
2914
2915    #[test]
2916    fn first_existing_picks_the_earliest_present_name() {
2917        let dir = std::env::temp_dir().join("amont-first-existing-test");
2918        let _ = std::fs::create_dir_all(&dir);
2919        let root = dir.to_string_lossy().into_owned();
2920        let _ = std::fs::write(dir.join("second"), "x");
2921        assert_eq!(
2922            first_existing(&root, &["first", "second", "third"]).as_deref(),
2923            Some("second")
2924        );
2925        assert_eq!(first_existing(&root, &["nope"]), None);
2926        let _ = std::fs::remove_dir_all(&dir);
2927    }
2928}
2929
2930#[cfg(test)]
2931mod js_tool_tests {
2932    use super::{package_json_declares, version_in};
2933
2934    #[test]
2935    fn package_json_declares_a_dev_dependency() {
2936        assert!(package_json_declares(
2937            r#"{"devDependencies":{"prettier":"3.9.10"}}"#,
2938            "prettier"
2939        ));
2940        assert!(package_json_declares(
2941            "{\n  \"name\": \"x\",\n  \"dependencies\": { \"eslint\": \"9.1.0\" }\n}\n",
2942            "eslint"
2943        ));
2944        // A byte-order mark does not hide a declaration.
2945        assert!(package_json_declares(
2946            "\u{feff}{\"devDependencies\":{\"prettier\":\"3.9.10\"}}",
2947            "prettier"
2948        ));
2949    }
2950
2951    /// Nesting past the limit is "not declared", never a stack overflow.
2952    #[test]
2953    fn package_json_declares_gives_up_on_deep_nesting() {
2954        let deep = format!(
2955            "{{\"x\":{}{},\"devDependencies\":{{\"prettier\":\"3\"}}}}",
2956            "[".repeat(100_000),
2957            "]".repeat(100_000)
2958        );
2959        assert!(!package_json_declares(&deep, "prettier"));
2960        let fine = format!(
2961            "{{\"x\":{}{},\"devDependencies\":{{\"prettier\":\"3\"}}}}",
2962            "[".repeat(50),
2963            "]".repeat(50)
2964        );
2965        assert!(package_json_declares(&fine, "prettier"));
2966    }
2967
2968    #[test]
2969    fn package_json_declares_nothing_else() {
2970        let not = |text: &str| assert!(!package_json_declares(text, "prettier"), "{text}");
2971        // A top-level config key is not a dependency.
2972        not(r#"{"prettier":{"semi":false}}"#);
2973        // A plugin whose name starts with the tool's.
2974        not(r#"{"devDependencies":{"prettier-plugin-x":"1.0.0"}}"#);
2975        // Peer, optional, overrides, scripts.
2976        not(r#"{"peerDependencies":{"prettier":"3"}}"#);
2977        not(r#"{"optionalDependencies":{"prettier":"3"}}"#);
2978        not(r#"{"pnpm":{"overrides":{"prettier":"3"}}}"#);
2979        not(r#"{"scripts":{"prettier":"prettier --check ."}}"#);
2980        // Dependency objects that are not root members.
2981        not(r#"{"metadata":{"devDependencies":{"prettier":"3"}}}"#);
2982        not(r#"{"list":[{"dependencies":{"prettier":"3"}}]}"#);
2983        // A quote, a brace and the key's name inside string values.
2984        not(r#"{"description":"say \"devDependencies\": {\"prettier\": 1}"}"#);
2985        // Cut off, or not one JSON document.
2986        not(r#"{"devDependencies":{"prettier":"3.9.10""#);
2987        not(r#"{"devDependencies":{"prettier":"3.9.10"}} trailing"#);
2988        not("");
2989    }
2990
2991    #[test]
2992    fn package_json_declares_past_escapes_and_nesting() {
2993        assert!(package_json_declares(
2994            r#"{"description":"a \"quoted\" {brace}","x":[1,{"y":null}],"devDependencies":{"a":"1","prettier":"^3"}}"#,
2995            "prettier"
2996        ));
2997    }
2998
2999    #[test]
3000    fn version_in_skips_warnings_and_strips_v() {
3001        assert_eq!(version_in("3.9.10\n").as_deref(), Some("3.9.10"));
3002        assert_eq!(version_in("v9.14.0").as_deref(), Some("9.14.0"));
3003        assert_eq!(
3004            version_in("npm warn exec The following package was not found\n3.9.10").as_deref(),
3005            Some("3.9.10")
3006        );
3007        assert_eq!(
3008            version_in("(node:1) Warning: x\n3.0.0-beta.1").as_deref(),
3009            Some("3.0.0-beta.1")
3010        );
3011        assert_eq!(version_in("3.9.10\u{1b}[2J").as_deref(), Some("3.9.10"));
3012        assert_eq!(version_in("no version here\n1.2"), None);
3013        assert_eq!(version_in(""), None);
3014    }
3015}