Skip to main content

greengate_runtime/
tree_lint.rs

1//! Tree gates at commit time: run beside the commit's checks, never decide it,
2//! stamp the tree when they prove it (ADR-0024).
3//!
4//! The commit's verdict is untouched: it comes from the checks it always came
5//! from. A tree gate adds at most `amont.treeLintSlack` after those finish, and
6//! a pass is recorded as the token `tree:<name>` in the commit's gate stamp
7//! (`gate_stamp::record`), which post-commit binds to both the commit and its
8//! tree. The push reads the tree's note, so a reword keeps the proof.
9//!
10//! No stamp, and the gates do not even start, when the tree they would lint is
11//! not exactly the commit's tree:
12//!
13//! - tracked files had unstaged edits (captured BEFORE the staged-only hold
14//!   parks them — after, the working tree always looks clean);
15//! - untracked, non-ignored files exist;
16//! - ignored files exist outside the allow-list (`snapshotPrepareOutputs`,
17//!   plus tool caches by default) — a gitignored generated module can make a
18//!   linter pass here and fail in CI;
19//! - a merge, rebase, cherry-pick or revert is in progress.
20
21use crate::names::BIN;
22use std::path::{Path, PathBuf};
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::sync::Arc;
25use std::thread::JoinHandle;
26use std::time::{Duration, Instant};
27
28use crate::hooks::common::{hl, ok, say};
29use crate::manifest::{TreeGate, CACHE_PLACEHOLDER};
30use crate::tree_run::TreeRun;
31
32pub const TOGGLE: &str = "amont.treeLint";
33pub const SLACK: &str = "amont.treeLintSlack";
34pub const OUTPUTS: &str = "amont.snapshotPrepareOutputs";
35
36/// Seconds tree gates may run after the commit's own checks have finished.
37const DEFAULT_SLACK: i64 = 2;
38
39/// The ceiling for one tree gate at commit, whatever the slack: a gate is
40/// cancelled at `slack` after the checks anyway, this only bounds a commit
41/// whose checks themselves run long.
42const CEILING: Duration = Duration::from_secs(600);
43
44/// Ignored paths that are tool caches or dependency trees CI recreates, and
45/// never a module a linter could import in place of a committed one.
46pub const DEFAULT_OUTPUTS: &[&str] = &[
47    "node_modules/",
48    ".venv/",
49    "venv/",
50    "__pycache__/",
51    ".ruff_cache/",
52    ".pytest_cache/",
53    ".mypy_cache/",
54    ".hypothesis/",
55    ".eslintcache",
56    ".prettiercache",
57    ".DS_Store",
58];
59
60/// Whether tree gates run here. On by default where attestation is on:
61/// a stamp nobody signs is paid for and never used.
62pub fn enabled(settings: &crate::config::Settings) -> bool {
63    crate::config::boolean_or(settings, TOGGLE, crate::attest::enabled(settings))
64}
65
66fn slack_ms(settings: &crate::config::Settings) -> u64 {
67    u64::try_from(slack(settings).as_millis()).unwrap_or(u64::MAX)
68}
69
70fn slack(settings: &crate::config::Settings) -> Duration {
71    let secs = crate::config::integer_or(settings, SLACK, DEFAULT_SLACK, 0..=600);
72    crate::clock::scaled(Duration::from_secs(u64::try_from(secs).unwrap_or(0)))
73}
74
75/// The allow-list: the defaults plus `snapshotPrepareOutputs`.
76pub fn outputs(settings: &crate::config::Settings) -> Vec<String> {
77    let mut out: Vec<String> = DEFAULT_OUTPUTS.iter().map(|s| s.to_string()).collect();
78    if let Some(v) = crate::config::string_value(settings, OUTPUTS) {
79        out.extend(v.split_whitespace().map(str::to_string));
80    }
81    out
82}
83
84/// Whether an ignored entry (as `git ls-files -o -i --directory` prints it:
85/// directories end in `/`) is covered by an allow-list pattern.
86///
87/// A pattern ending in `/` names a directory, anywhere in the tree
88/// (`__pycache__/` matches `pkg/__pycache__/`). Any other pattern names a
89/// file by basename, with `*` as the only wildcard (`*.log`).
90pub fn allowed(entry: &str, patterns: &[String]) -> bool {
91    patterns.iter().any(|p| {
92        if let Some(dir) = p.strip_suffix('/') {
93            let dir = dir.trim_start_matches("./");
94            entry == format!("{dir}/")
95                || entry.starts_with(&format!("{dir}/"))
96                || entry.contains(&format!("/{dir}/"))
97        } else {
98            let base = entry
99                .trim_end_matches('/')
100                .rsplit('/')
101                .next()
102                .unwrap_or(entry);
103            glob_basename(p, base)
104        }
105    })
106}
107
108/// `*` matches any run of characters; nothing else is special.
109fn glob_basename(pattern: &str, name: &str) -> bool {
110    let parts: Vec<&str> = pattern.split('*').collect();
111    if parts.len() == 1 {
112        return pattern == name;
113    }
114    let mut rest = name;
115    for (i, part) in parts.iter().enumerate() {
116        if i == 0 {
117            let Some(r) = rest.strip_prefix(part) else {
118                return false;
119            };
120            rest = r;
121        } else if i == parts.len() - 1 {
122            return rest.ends_with(part);
123        } else {
124            let Some(at) = rest.find(part) else {
125                return false;
126            };
127            rest = &rest[at + part.len()..];
128        }
129    }
130    true
131}
132
133/// Why this commit's tree cannot be proven, or `None` when it can. Runs
134/// BEFORE the staged-only hold: only then can unstaged edits be seen.
135pub fn guard(settings: &crate::config::Settings) -> Option<String> {
136    if !crate::git_states_in_progress().is_empty() {
137        return Some("a merge, rebase, cherry-pick or revert is in progress".into());
138    }
139    if !crate::git::succeeds(&["diff", "--quiet"]) {
140        return Some("tracked files have unstaged edits (the tree is not the commit's)".into());
141    }
142    content_guard(Path::new(&crate::hooks::common::repo_root()), settings)
143}
144
145/// Untracked files, and ignored ones outside the allow-list, under `dir`.
146fn content_guard(dir: &Path, settings: &crate::config::Settings) -> Option<String> {
147    // A git that cannot answer proves nothing: withhold, never read "none".
148    let Some(untracked) = crate::git::stdout_in(
149        dir,
150        &["ls-files", "--others", "--exclude-standard", "--directory"],
151    ) else {
152        return Some("git could not list untracked files".into());
153    };
154    if let Some(first) = untracked.lines().find(|l| !l.trim().is_empty()) {
155        return Some(format!("an untracked file is present ({first})"));
156    }
157    let Some(ignored) = crate::git::stdout_in(
158        dir,
159        &[
160            "ls-files",
161            "--others",
162            "--ignored",
163            "--exclude-standard",
164            "--directory",
165        ],
166    ) else {
167        return Some("git could not list ignored files".into());
168    };
169    let allow = outputs(settings);
170    if let Some(first) = ignored
171        .lines()
172        .map(str::trim)
173        .find(|l| !l.is_empty() && !allowed(l, &allow))
174    {
175        return Some(format!(
176            "an ignored file outside {} is present ({first})",
177            hl("snapshotPrepareOutputs")
178        ));
179    }
180    None
181}
182
183/// The argv a gate runs: its command through `sh -c`, as a CI `run:` line
184/// runs through a shell, with `{cache}` expanded to `cache_flags`.
185pub fn argv(gate: &TreeGate, cache_flags: &str) -> Vec<String> {
186    if cache_flags.trim().is_empty() {
187        // Exactly what CI runs: no dangling `--`.
188        return vec!["sh".into(), "-c".into(), gate.normalized()];
189    }
190    let command: Vec<&str> = gate
191        .command
192        .split_whitespace()
193        .flat_map(|w| {
194            if w == CACHE_PLACEHOLDER {
195                cache_flags.split_whitespace().collect::<Vec<_>>()
196            } else {
197                vec![w]
198            }
199        })
200        .collect();
201    vec!["sh".into(), "-c".into(), command.join(" ")]
202}
203
204/// What one gate's thread decided, and did.
205enum Decision {
206    /// It ran: how it ended, and how long it took.
207    Ran(TreeRun, u64),
208    /// The tool it would run is not the one CI resolves.
209    Skew(String),
210    /// Its version could not be read before the deadline or the cancel.
211    NoVersion,
212    /// No completed run in its current namespace.
213    Cold,
214    /// Another run held its cache lock.
215    Busy,
216    /// Its last run (ms) would not fit this commit's cover plus the slack.
217    Slow(u64),
218}
219
220type InFlight = (String, JoinHandle<Decision>);
221
222/// Tree gates in flight.
223pub struct SideCar {
224    cancel: Arc<AtomicBool>,
225    running: Vec<InFlight>,
226}
227
228/// This hook run's tree-gate outcomes, for `gate_evidence`: proven, failed,
229/// cold, busy, skew, withheld, cancelled — the hit rate, and why it missed.
230static EVIDENCE: std::sync::Mutex<Vec<crate::gate_stamp::Run>> = std::sync::Mutex::new(Vec::new());
231
232fn note(name: &str, outcome: crate::gate_stamp::RunOutcome, ms: u64) {
233    let at = std::time::SystemTime::now()
234        .duration_since(std::time::UNIX_EPOCH)
235        .map(|d| d.as_secs())
236        .unwrap_or(0);
237    if let Ok(mut e) = EVIDENCE.lock() {
238        e.push(crate::gate_stamp::Run {
239            at,
240            gate: format!("tree-{name}"),
241            outcome,
242            ms,
243        });
244    }
245}
246
247/// Every gate withheld for the same reason (the guard fired).
248pub fn note_withheld(gates: &[TreeGate]) {
249    for g in gates {
250        note(&g.name, crate::gate_stamp::RunOutcome::Withheld, 0);
251    }
252}
253
254/// Write this run's tree-gate evidence against `tree`'s gate note, and
255/// clear it. Best-effort, like every evidence writer.
256pub fn flush_evidence(tree: &str) {
257    let runs = EVIDENCE
258        .lock()
259        .map(|mut e| std::mem::take(&mut *e))
260        .unwrap_or_default();
261    if !runs.is_empty() {
262        crate::gate_stamp::record_runs(tree, &runs);
263    }
264}
265
266fn cwd_of(root: &Path, gate: &TreeGate) -> PathBuf {
267    match &gate.cwd {
268        Some(dir) => root.join(dir),
269        None => root.to_path_buf(),
270    }
271}
272
273/// Start one thread per gate against the working tree, which the staged-only
274/// hold has made the commit's tree. EVERYTHING a gate needs to decide runs in
275/// its own thread, so none of it delays the commit's checks: the version
276/// probe (bounded and cancellable — a wrapper may reach the network), the
277/// skew check, the namespace, the warm and fit tests, the lock, the run.
278/// `cover_ms` is how long this commit's own declared checks are expected to
279/// run. Returns `None` when nothing starts.
280pub fn start(
281    settings: &crate::config::Settings,
282    root: &Path,
283    gates: &[TreeGate],
284    pins: &[crate::manifest::ToolPin],
285    cover_ms: u64,
286) -> Option<SideCar> {
287    if gates.is_empty() {
288        return None;
289    }
290    if cfg!(not(unix)) {
291        say("  tree gates need a Unix shell and do not run here — CI will lint");
292        return None;
293    }
294    let cancel = Arc::new(AtomicBool::new(false));
295    let deadline = Instant::now() + CEILING;
296    let budget_ms = cover_ms.saturating_add(slack_ms(settings));
297    let running = gates
298        .iter()
299        .map(|g| {
300            let gate = g.clone();
301            let pins = pins.to_vec();
302            let cwd = cwd_of(root, g);
303            let flag = Arc::clone(&cancel);
304            let handle = std::thread::spawn(move || {
305                decide_and_run(&gate, &cwd, &pins, budget_ms, deadline, &flag)
306            });
307            (g.name.clone(), handle)
308        })
309        .collect();
310    Some(SideCar { cancel, running })
311}
312
313fn decide_and_run(
314    g: &TreeGate,
315    cwd: &Path,
316    pins: &[crate::manifest::ToolPin],
317    budget_ms: u64,
318    deadline: Instant,
319    cancel: &AtomicBool,
320) -> Decision {
321    // Would it fit? Its last run against this commit's cover plus the slack,
322    // asked FIRST so a gate that cannot fit costs nothing. Unknown runs once,
323    // to learn.
324    if let Some(ms) = crate::tree_cache::gate_last_ms(g).filter(|ms| *ms > budget_ms) {
325        return Decision::Slow(ms);
326    }
327    let Some(version) = crate::tree_cache::tool_version(cwd, g, deadline, cancel) else {
328        return Decision::NoVersion;
329    };
330    if let Some(why) = crate::tree_skew::skew(cwd, g, pins, &version) {
331        return Decision::Skew(why);
332    }
333    let Some(ns) =
334        crate::tree_cache::namespace(g, &version).filter(|ns| crate::tree_cache::is_warm(g, ns))
335    else {
336        return Decision::Cold;
337    };
338    let Some(ns_dir) = crate::tree_cache::gate_dir(g).map(|d| d.join(&ns)) else {
339        return Decision::Cold;
340    };
341    let Some(lock) = crate::tree_cache::try_lock(g) else {
342        return Decision::Busy;
343    };
344    let argv = argv(
345        g,
346        &crate::tree_cache::cache_flags(cwd, g, &ns_dir, deadline, cancel),
347    );
348    let began = Instant::now();
349    let run = crate::tree_run::run(&argv, cwd, deadline, cancel);
350    let ms = u64::try_from(began.elapsed().as_millis()).unwrap_or(u64::MAX);
351    // Only now: the runner killed the whole group before returning, so
352    // nothing that could still write the cache is alive.
353    drop(lock);
354    Decision::Ran(run, ms)
355}
356
357/// Which declared tree gates every pushed tip's TREE proves, as note gate
358/// ids (`tree-<name>`), and which it does not, by name. A tip whose tree git
359/// cannot name proves nothing.
360pub fn tree_verdict(gates: &[TreeGate], tips: &[String]) -> (Vec<String>, Vec<String>) {
361    let trees: Vec<Option<String>> = tips
362        .iter()
363        .map(|t| crate::git::stdout(&["rev-parse", &format!("{t}^{{tree}}")]))
364        .collect();
365    let tokens: Vec<Vec<String>> = trees
366        .iter()
367        .map(|t| {
368            t.as_deref()
369                .map(crate::gate_stamp::tree_tokens)
370                .unwrap_or_default()
371        })
372        .collect();
373    let mut proven = Vec::new();
374    let mut unproven = Vec::new();
375    for g in gates {
376        let key = g.stamp_key();
377        if !tips.is_empty() && tokens.iter().all(|toks| toks.iter().any(|t| t == &key)) {
378            proven.push(g.id());
379        } else {
380            unproven.push(g.name.clone());
381        }
382    }
383    (proven, unproven)
384}
385
386pub const REHEARSAL_TIMEOUT: &str = "amont.treeLintRehearsalTimeout";
387pub const WAIT: &str = "amont.treeLintWait";
388
389/// Whether a snapshot is still exactly its tree once `snapshotPrepare` (and
390/// `snapshotCarry`) ran: tracked content unchanged, nothing untracked, and
391/// nothing ignored outside the allow-list. Prepare runs arbitrary commands,
392/// so this is what keeps it from forging the tree a stamp names.
393pub fn prepare_guard(snapshot: &Path, settings: &crate::config::Settings) -> Option<String> {
394    if !crate::git::succeeds_in(snapshot, &["diff", "--quiet", "HEAD"]) {
395        return Some("snapshotPrepare changed tracked content".into());
396    }
397    content_guard(snapshot, settings)
398}
399
400/// The rehearsal's half (ADR-0024): prove `gates` on the snapshot of `tree`,
401/// uncached (every snapshot sits at a new path) and bounded by
402/// `amont.treeLintRehearsalTimeout`, and stamp the TREE. Runs before the
403/// rehearsal's test gates, so a push waiting on lint does not wait on tests.
404pub fn rehearse(
405    settings: &crate::config::Settings,
406    snapshot: &Path,
407    tree: &str,
408    gates: &[TreeGate],
409) -> Vec<String> {
410    if gates.is_empty() || cfg!(not(unix)) {
411        return Vec::new();
412    }
413    if let Some(why) = prepare_guard(snapshot, settings) {
414        println!("tree lint not proven in the snapshot: {why}");
415        note_withheld(gates);
416        flush_evidence(tree);
417        return Vec::new();
418    }
419    let budget = crate::config::integer_or(settings, REHEARSAL_TIMEOUT, 120, 1..=3600);
420    let budget = Duration::from_secs(u64::try_from(budget).unwrap_or(120));
421    let mut tokens = Vec::new();
422    let pins = crate::manifest::load(snapshot).pins;
423    for g in gates {
424        let cwd = cwd_of(snapshot, g);
425        let Some(version) = crate::tree_cache::tool_version(
426            &cwd,
427            g,
428            Instant::now() + budget,
429            &AtomicBool::new(false),
430        ) else {
431            note(&g.name, crate::gate_stamp::RunOutcome::Skew, 0);
432            println!(
433                "tree lint not proven: {} — its tool's version could not be read",
434                g.name
435            );
436            continue;
437        };
438        if let Some(why) = crate::tree_skew::skew(&cwd, g, &pins, &version) {
439            note(&g.name, crate::gate_stamp::RunOutcome::Skew, 0);
440            println!("tree lint not proven: {} — {why}", g.name);
441            continue;
442        }
443        let started = Instant::now();
444        let run = crate::tree_run::run(
445            &argv(g, ""),
446            &cwd,
447            started + budget,
448            &AtomicBool::new(false),
449        );
450        let ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
451        match run {
452            TreeRun::Passed => {
453                note(&g.name, crate::gate_stamp::RunOutcome::Passed, ms);
454                println!(
455                    "tree lint proven: {} ({:.1}s)",
456                    g.name,
457                    started.elapsed().as_secs_f32()
458                );
459                tokens.push(g.stamp_key());
460            }
461            other => {
462                let outcome = match other {
463                    TreeRun::Failed(_) => crate::gate_stamp::RunOutcome::Failed,
464                    TreeRun::TimedOut | TreeRun::Cancelled => {
465                        crate::gate_stamp::RunOutcome::Cancelled
466                    }
467                    TreeRun::Spawn(_) => crate::gate_stamp::RunOutcome::Unavailable,
468                    TreeRun::Passed => unreachable!("matched above"),
469                };
470                note(&g.name, outcome, ms);
471                println!("tree lint not proven: {} — {other:?}", g.name);
472            }
473        }
474    }
475    flush_evidence(tree);
476    if !tokens.is_empty() && !crate::gate_stamp::stamp_tree(tree, &tokens) {
477        println!("git refused the tree note — nothing stamped");
478        return Vec::new();
479    }
480    tokens
481}
482
483/// [`tree_verdict`], waiting — at most `amont.treeLintWait` counted from
484/// `started` (the start of pre-push), as ONE deadline for every gate — for a
485/// rehearsal running on the tree of one of `tips` to stamp its tree gates.
486/// Independent of `amont.rehearsalWait`: it neither uses nor extends it.
487pub fn await_verdict(
488    settings: &crate::config::Settings,
489    gates: &[TreeGate],
490    tips: &[String],
491    started: Instant,
492) -> (Vec<String>, Vec<String>) {
493    let secs = crate::config::integer_or(settings, WAIT, 30, 0..=3600);
494    let until =
495        started + crate::clock::scaled(Duration::from_secs(u64::try_from(secs).unwrap_or(30)));
496    let trees: Vec<String> = tips
497        .iter()
498        .filter_map(|t| crate::git::stdout(&["rev-parse", &format!("{t}^{{tree}}")]))
499        .collect();
500    loop {
501        let verdict = tree_verdict(gates, tips);
502        let rehearsing =
503            crate::rehearsal::read().is_some_and(|s| s.alive() && trees.contains(&s.tree));
504        if verdict.1.is_empty() || !rehearsing || Instant::now() >= until {
505            return verdict;
506        }
507        std::thread::sleep(Duration::from_millis(250));
508    }
509}
510
511/// `prefix + body + suffix`, with `body` cut (and an ellipsis added) so the
512/// whole line fits 80 columns. The body carries a tool's own summary line,
513/// whose length nothing bounds.
514pub fn fit_line(prefix: &str, body: &str, suffix: &str) -> String {
515    const COLUMNS: usize = 80;
516    let room = COLUMNS.saturating_sub(prefix.chars().count() + suffix.chars().count());
517    let body = if body.chars().count() > room && room > 1 {
518        let cut: String = body.chars().take(room - 1).collect();
519        format!("{cut}…")
520    } else {
521        body.to_string()
522    };
523    format!("{prefix}{body}{suffix}")
524}
525
526/// Where the background warm-up writes: its own log, never the rehearsal's.
527#[cfg(unix)]
528fn warm_log() -> Option<PathBuf> {
529    crate::git::stdout(&["rev-parse", "--absolute-git-dir"])
530        .map(|d| PathBuf::from(d).join("amont-warm.log"))
531}
532
533/// Start the background warm-up for the cold gates, and say so once — under
534/// every `amont.quiet` setting: a cold gate is why this commit carries no
535/// `tree:` stamp, and quiet only swallows success lines.
536fn warm_later(cold: &[String]) {
537    #[cfg(unix)]
538    {
539        let Some(log) = warm_log() else { return };
540        match crate::rehearsal::spawn_amont(&["warm", "--worker"], &log) {
541            Ok(_) => say(&fit_line(
542                "  tree lint cold: ",
543                &cold.join(" "),
544                " — warming ($GIT_DIR/amont-warm.log)",
545            )),
546            Err(e) => say(&format!(
547                "  tree lint cold: {} — could not start the warm-up ({e}); run {}",
548                cold.join(" "),
549                hl(&format!("{BIN} warm"))
550            )),
551        }
552    }
553    #[cfg(not(unix))]
554    {
555        let _ = cold;
556    }
557}
558
559/// `amont warm` — fill every cold tree gate's cache in its current
560/// namespace: a full run with `{cache}`, then the completion marker. Old
561/// namespaces are deleted first, under the gate's lock. A gate whose lock is
562/// held is left to whoever holds it. Exit 0 whatever the lint found: a
563/// warm-up proves nothing, it only makes the next commit's run cheap.
564pub fn warm(root: &Path) -> i32 {
565    let manifest = crate::manifest::load(root);
566    if manifest.tree.is_empty() {
567        eprintln!("{BIN} warm: no trusted tree gate here");
568        return 0;
569    }
570    for g in &manifest.tree {
571        let cwd = cwd_of(root, g);
572        let Some(version) = crate::tree_cache::tool_version(
573            &cwd,
574            g,
575            Instant::now() + Duration::from_secs(60),
576            &AtomicBool::new(false),
577        ) else {
578            println!("{}: its tool's version could not be read — skipped", g.name);
579            continue;
580        };
581        let Some(ns) = crate::tree_cache::namespace(g, &version) else {
582            println!("{}: git could not name the namespace — skipped", g.name);
583            continue;
584        };
585        if crate::tree_cache::is_warm(g, &ns) {
586            println!("{}: already warm", g.name);
587            continue;
588        }
589        let Some(_lock) = crate::tree_cache::try_lock(g) else {
590            println!("{}: another run holds the cache — skipped", g.name);
591            continue;
592        };
593        let Some(ns_dir) = crate::tree_cache::enter_namespace(g, &ns) else {
594            println!("{}: cannot create the cache directory — skipped", g.name);
595            continue;
596        };
597        let argv = argv(
598            g,
599            &crate::tree_cache::cache_flags(
600                &cwd,
601                g,
602                &ns_dir,
603                Instant::now() + CEILING,
604                &AtomicBool::new(false),
605            ),
606        );
607        let started = Instant::now();
608        let run = crate::tree_run::run(&argv, &cwd, started + CEILING, &AtomicBool::new(false));
609        let secs = started.elapsed().as_secs_f32();
610        match run {
611            TreeRun::Passed | TreeRun::Failed(_) => {
612                crate::tree_cache::mark_complete(&ns_dir);
613                println!("{}: warm ({secs:.1}s)", g.name);
614            }
615            other => println!("{}: not warmed — {other:?}", g.name),
616        }
617    }
618    0
619}
620
621/// Wait at most `amont.treeLintSlack` for the gates still running, cancel the
622/// rest, and return the stamp tokens of the gates that proved the tree.
623/// `stampable` is false when the commit is blocked or a check rewrote files:
624/// then nothing is waited for and nothing is stamped. Cold gates go to the
625/// background warm-up.
626pub fn finish(settings: &crate::config::Settings, car: SideCar, stampable: bool) -> Vec<String> {
627    use crate::gate_stamp::RunOutcome;
628    let until = Instant::now()
629        + if stampable {
630            slack(settings)
631        } else {
632            Duration::ZERO
633        };
634    while Instant::now() < until && car.running.iter().any(|(_, h)| !h.is_finished()) {
635        std::thread::sleep(Duration::from_millis(20));
636    }
637    car.cancel.store(true, Ordering::SeqCst);
638    let mut proven = Vec::new();
639    // (gate, why): every gate this commit did not prove, one reason each.
640    let mut unproven: Vec<(String, String, bool)> = Vec::new();
641    let mut cold = Vec::new();
642    for (name, handle) in car.running {
643        let decision = handle
644            .join()
645            .unwrap_or(Decision::Ran(TreeRun::Spawn("thread died".into()), 0));
646        match decision {
647            Decision::Ran(run, ms) => {
648                // A completed run's time, or a cancelled one's lower bound:
649                // what the next commit's fit test reads.
650                if !matches!(run, TreeRun::Spawn(_)) {
651                    crate::tree_cache::record_gate_last_ms(&name, ms);
652                }
653                match run {
654                    TreeRun::Passed if stampable => {
655                        note(&name, RunOutcome::Passed, ms);
656                        proven.push(name);
657                    }
658                    TreeRun::Passed => note(&name, RunOutcome::Withheld, ms),
659                    TreeRun::Failed(summary) => {
660                        note(&name, RunOutcome::Failed, ms);
661                        unproven.push((name, summary, false));
662                    }
663                    TreeRun::TimedOut | TreeRun::Cancelled => {
664                        note(&name, RunOutcome::Cancelled, ms);
665                        unproven.push((
666                            name,
667                            "still running when the commit was ready".into(),
668                            false,
669                        ));
670                    }
671                    TreeRun::Spawn(e) => {
672                        note(&name, RunOutcome::Unavailable, ms);
673                        unproven.push((name, format!("could not start ({e})"), false));
674                    }
675                }
676            }
677            Decision::Skew(why) => {
678                note(&name, RunOutcome::Skew, 0);
679                unproven.push((name, why, false));
680            }
681            Decision::NoVersion => {
682                note(&name, RunOutcome::Skew, 0);
683                unproven.push((
684                    name,
685                    "its tool's version could not be read in time".into(),
686                    false,
687                ));
688            }
689            Decision::Cold => {
690                note(&name, RunOutcome::Cold, 0);
691                cold.push(name);
692            }
693            Decision::Busy => {
694                note(&name, RunOutcome::Busy, 0);
695                unproven.push((name, "a warm-up holds its cache".into(), false));
696            }
697            Decision::Slow(ms) => {
698                note(&name, RunOutcome::Slow, 0);
699                unproven.push((
700                    name,
701                    format!(
702                        "skipped: needs ~{:.1}s, more than this commit leaves",
703                        ms as f64 / 1000.0
704                    ),
705                    true,
706                ));
707            }
708        }
709    }
710    // The gates linted the working tree the staged-only hold made the index.
711    // If it moved while they ran (an editor autosave, a gate that writes), the
712    // proof is about another tree: withhold it.
713    if stampable && !proven.is_empty() {
714        let moved = if crate::git::succeeds(&["diff", "--quiet"]) {
715            content_guard(Path::new(&crate::hooks::common::repo_root()), settings)
716        } else {
717            Some("tracked files changed while it ran".into())
718        };
719        if let Some(why) = moved {
720            for name in proven.drain(..) {
721                note(&name, RunOutcome::Withheld, 0);
722                unproven.push((name, format!("the tree moved while it ran ({why})"), false));
723            }
724        }
725    }
726    if !proven.is_empty() {
727        ok(settings, &format!("tree lint proven: {}", proven.join(" ")));
728    }
729    // One header naming the consequence once, then one line per gate, each
730    // fitted to 80 columns (a tool's own summary is unbounded).
731    let quiet = crate::live::quiet(settings);
732    let unproven: Vec<(String, String, bool)> = unproven
733        .into_iter()
734        .filter(|(_, _, skipped)| !(quiet && *skipped))
735        .collect();
736    if stampable && !unproven.is_empty() {
737        say("  tree lint not proven — CI will lint:");
738        for (name, why, _) in &unproven {
739            say(&fit_line(
740                &format!("    {} — ", crate::ui::sanitize(name)),
741                &crate::ui::sanitize(why),
742                "",
743            ));
744        }
745    }
746    if !cold.is_empty() {
747        warm_later(&cold);
748    }
749    proven.iter().map(|n| format!("tree:{n}")).collect()
750}
751
752#[cfg(test)]
753mod tests {
754    use super::*;
755
756    fn pats(extra: &[&str]) -> Vec<String> {
757        DEFAULT_OUTPUTS
758            .iter()
759            .chain(extra)
760            .map(|s| s.to_string())
761            .collect()
762    }
763
764    #[test]
765    fn tree_lint_allows_tool_caches_anywhere() {
766        let p = pats(&[]);
767        assert!(allowed("node_modules/", &p));
768        assert!(allowed("packages/api/__pycache__/", &p));
769        assert!(allowed(".venv/", &p));
770        assert!(allowed("web/.DS_Store", &p));
771    }
772
773    #[test]
774    fn tree_lint_refuses_an_ignored_module() {
775        let p = pats(&[]);
776        assert!(!allowed("src/generated/types.ts", &p));
777        assert!(!allowed(".react-router/", &p));
778        assert!(!allowed("build/", &p));
779    }
780
781    #[test]
782    fn tree_lint_repo_patterns_extend_the_list() {
783        let p = pats(&["build/", ".react-router/", "*.db", "*.db-wal"]);
784        assert!(allowed("build/", &p));
785        assert!(allowed(".react-router/", &p));
786        assert!(allowed("landscape.db", &p));
787        assert!(allowed("landscape.db-wal", &p));
788        assert!(!allowed("landscape.sqlite", &p));
789    }
790
791    #[test]
792    fn tree_lint_fit_line_cuts_the_body_to_eighty_columns() {
793        let l = fit_line(
794            "  tree lint not proven: ",
795            "eslint — 12 problems (12 errors, 0 warnings) and some more words",
796            " — CI will lint",
797        );
798        assert_eq!(l.chars().count(), 80, "{l}");
799        assert!(l.ends_with("… — CI will lint"), "{l}");
800        let body = fit_line("    eslint — ", &"x".repeat(200), "");
801        assert_eq!(body.chars().count(), 80);
802        let short = fit_line("a", "b", "c");
803        assert_eq!(short, "abc");
804    }
805
806    #[test]
807    fn tree_lint_argv_runs_through_sh_with_cache_expanded() {
808        let g = crate::manifest::tree_gates("tree eslint eslint * attest npm run lint -- {cache}")
809            .remove(0);
810        assert_eq!(
811            argv(&g, "--cache --cache-location /x"),
812            vec!["sh", "-c", "npm run lint -- --cache --cache-location /x"]
813        );
814        assert_eq!(argv(&g, ""), vec!["sh", "-c", "npm run lint"]);
815    }
816}