Skip to main content

greengate_runtime/
live.rs

1//! One check, one block — and while it runs, one line: per-check output
2//! capture plus a live progress region for the concurrent stage.
3//!
4//! Twenty checks used to print straight to inherited stdio from their own
5//! threads, so two failing linters shuffled their lines together and the
6//! reader un-shuffled them by hand — the dispatcher's roll-up existed partly
7//! to apologise for it. Now every check writes into its own slot, and a
8//! completed check's output reaches stdout as ONE locked write: contiguous,
9//! whatever the other nineteen were doing.
10//!
11//! Three writers feed a slot:
12//!
13//! 1. The check's own thread, through [`say`] — which is what
14//!    `common::ok/fail/warn` call. A thread with no slot installed (commit-msg,
15//!    `amont install`, the dispatcher itself) prints directly, exactly as
16//!    before; nothing outside a stage changes.
17//! 2. A captured child's reader threads, through [`Stage::append_raw`] —
18//!    they are not the check's thread, so the thread-local cannot carry the
19//!    routing; the `Arc` is captured before the spawn instead.
20//! 3. Nobody else. The dispatcher's own lines (skips, pins, the roll-up)
21//!    happen strictly before or after the fan-out and stay direct.
22//!
23//! Order across checks is COMPLETION order — deterministic per block, not
24//! per stage, which is the same nondeterminism the interleaved version had
25//! without the shuffling. `greengate.progress false` switches the whole
26//! mechanism off and restores raw streaming for anyone who wants to watch a
27//! tool write in real time.
28//!
29//! # The region
30//!
31//! When stderr is a real terminal ([`watching`]) the stage also paints a
32//! live region UNDER the finished blocks: one line per running check —
33//! braille spinner, name, elapsed — repainted every 80ms by a ticker
34//! thread, shrinking as checks finish, gone without a trace when the stage
35//! ends. Blocks go to stdout, the region to stderr; both feed one tty, and
36//! every write to either happens under the same [`Stage::out`] lock, so a
37//! block never tears a repaint in half. Piped, redirected, `TERM=dumb`, or
38//! CI: [`watching`] is false, no ticker starts, and the region costs
39//! nothing — which is also why the test suite (piped stdio throughout)
40//! exercises capture but never the paint.
41
42use std::cell::RefCell;
43use std::io::{IsTerminal, Write};
44use std::sync::atomic::{AtomicBool, Ordering};
45use std::sync::{Arc, Mutex, Weak};
46use std::time::Instant;
47
48/// The fleet spinner's frames (progress.rs) — cycled by elapsed time, so a
49/// frame needs no state beyond the clock.
50const FRAMES: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
51
52/// The region never grows past this many check lines; the rest fold into
53/// one `… and N more`. Twelve is the whole default fleet on one screen.
54const MAX_LINES: usize = 12;
55
56/// One check's place in the stage.
57struct Slot {
58    /// Sanitised at [`Stage::begin`]: a manifest-declared name is
59    /// repo-derived text and the region writes it to a live terminal.
60    name: String,
61    /// Restamped by [`Stage::enter`], so a serial stage (pre-push) times
62    /// each check from its own start, not the stage's.
63    started: Instant,
64    /// The last byte or line that landed in `buf` — what the region's
65    /// `quiet` figure and the heartbeat's `last output` read.
66    last_output: Instant,
67    /// Elapsed seconds at which the non-tty heartbeat next speaks.
68    next_beat: u64,
69    buf: Vec<u8>,
70    /// Entered and not yet finished — the region shows exactly these.
71    running: bool,
72    done: bool,
73    /// The command this check is waiting on, while it runs: its output
74    /// clock and what its CPU is doing — the same object the kill decision
75    /// reads, so the displays can never disagree with it (ADR-0008).
76    activity: Option<Arc<crate::hooks::common::Activity>>,
77    /// Waiting for a host slot since, and how many slots there are
78    /// (ADR-0009).
79    queued: Option<(Instant, u64)>,
80    /// Under quiet: where the tool's output goes instead of `buf` (the whole
81    /// of it to a log, a bounded excerpt in memory). `buf` keeps the check's
82    /// own messages. See [`crate::capture`].
83    capture: Option<crate::capture::Capture>,
84    /// The exit code of the last tool the check ran, for the failure line.
85    runner_exit: Option<i32>,
86    /// The `running <check>, log <path>` line has been printed.
87    announced: bool,
88}
89
90/// A quiet run says where its log is only once it has taken this long, so a
91/// quick pass is exactly one line even under `2>&1`.
92const ANNOUNCE_SECS: u64 = 5;
93
94/// A running stage: the slots, and the one lock every terminal write inside
95/// the stage goes through.
96pub struct Stage {
97    slots: Mutex<Vec<Slot>>,
98    /// Serialises block emission and region repaints; the value is how many
99    /// region lines are currently painted (what an erase must remove).
100    out: Mutex<usize>,
101    /// Painting at all? [`enabled`] && [`watching`], decided once at begin.
102    live: bool,
103    /// Is this the PUSH stage? Read by the heartbeat, which has something to
104    /// say about a long gate there and nothing to say about one at commit
105    /// time — see [`beat_line`]. Derived from the names, which already
106    /// carry the trigger.
107    on_push: bool,
108    /// Whether the queued heartbeat offers the way out, decided once beside
109    /// `on_push`: a land rehearsal forces `onBusy wait` on its snapshot.
110    way_out: WayOut,
111    /// [`quiet`], decided once at begin: tool output is captured to a log and
112    /// a passing check prints one line.
113    quiet: bool,
114    log_dir: Option<std::path::PathBuf>,
115    /// A check run by name (`amont run <check>`): its pass is one `ok` line.
116    /// Inside a stage a pass prints nothing, like every other success line
117    /// under quiet — the stage's tally speaks for it — and its log stays.
118    named: AtomicBool,
119    stop: AtomicBool,
120}
121
122thread_local! {
123    /// Where [`say`] routes on THIS thread: a stage and a slot index.
124    static SINK: RefCell<Option<(Arc<Stage>, usize)>> = const { RefCell::new(None) };
125}
126
127impl Stage {
128    /// A stage over `names`, in dispatch order. Does nothing visible until
129    /// checks start entering (the region) or finishing (the blocks).
130    pub fn begin(settings: &crate::config::Settings, names: &[&str]) -> Arc<Stage> {
131        let now = Instant::now();
132        let stage = Arc::new(Stage {
133            slots: Mutex::new(
134                names
135                    .iter()
136                    .map(|n| Slot {
137                        // Every name in a stage carries the stage's own
138                        // prefix ("pre-commit-clippy"); the region drops it
139                        // — twelve identical prefixes say nothing.
140                        name: crate::ui::sanitize(
141                            n.strip_prefix("pre-commit-")
142                                .or_else(|| n.strip_prefix("pre-push-"))
143                                .unwrap_or(n),
144                        ),
145                        started: now,
146                        last_output: now,
147                        next_beat: HEARTBEAT_SECS,
148                        buf: Vec::new(),
149                        running: false,
150                        done: false,
151                        activity: None,
152                        queued: None,
153                        capture: None,
154                        runner_exit: None,
155                        announced: false,
156                    })
157                    .collect(),
158            ),
159            out: Mutex::new(0),
160            live: enabled(settings) && watching(),
161            // The names arrive fully qualified and the loop above has
162            // already had to strip the trigger to display them, so the
163            // stage can answer this without dispatch passing anything in.
164            on_push: holds_a_push_connection(names, crate::rehearsal::in_snapshot()),
165            way_out: WayOut::for_snapshot(crate::rehearsal::in_snapshot()),
166            quiet: quiet(settings),
167            named: AtomicBool::new(false),
168            log_dir: if quiet(settings) {
169                crate::capture::log_dir()
170            } else {
171                None
172            },
173            stop: AtomicBool::new(false),
174        });
175        if stage.live {
176            // The ticker holds a Weak: the stage dropping is what ends it,
177            // so a paint can never outlive the region's owner.
178            let weak = Arc::downgrade(&stage);
179            let own = settings.for_thread();
180            let _ = std::thread::Builder::new()
181                .name("greengate-live".into())
182                .spawn(move || tick(own, weak));
183        } else if enabled(settings) || stage.quiet {
184            // Nobody is watching a terminal — an agent, CI, a pipe — and a
185            // captured check shows nothing until it finishes. The heartbeat
186            // is the one line a minute that says it is alive, which is the
187            // difference between "wait" and "kill it" for whoever is on the
188            // other end of the pipe.
189            let weak = Arc::downgrade(&stage);
190            let own = settings.for_thread();
191            let _ = std::thread::Builder::new()
192                .name("greengate-heartbeat".into())
193                .spawn(move || heartbeat(own, weak));
194        }
195        stage
196    }
197
198    /// Route this thread's [`say`] calls into slot `idx` until the guard
199    /// drops. Installed by the dispatcher around each `check.run`. Also
200    /// starts the slot's clock and puts it in the region.
201    pub fn enter(self: &Arc<Stage>, idx: usize) -> SinkGuard {
202        {
203            let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
204            if let Some(slot) = slots.get_mut(idx) {
205                slot.running = true;
206                slot.started = Instant::now();
207                slot.last_output = slot.started;
208                slot.next_beat = HEARTBEAT_SECS;
209                if self.quiet {
210                    slot.capture = Some(crate::capture::Capture::open(
211                        self.log_dir.clone(),
212                        &slot.name,
213                    ));
214                }
215            }
216        }
217        SINK.with(|s| *s.borrow_mut() = Some((Arc::clone(self), idx)));
218        SinkGuard
219    }
220
221    /// Slot `idx` is waiting for a host slot (`Some`), or no longer is.
222    pub fn queue(&self, idx: usize, since: Option<(Instant, u64)>) {
223        let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
224        if let Some(slot) = slots.get_mut(idx) {
225            slot.queued = since;
226        }
227    }
228
229    /// Show slot `idx`'s spawned command in the displays while the returned
230    /// guard lives. A check that runs several commands in turn attaches each
231    /// one; between them the slot falls back to its own output clock.
232    pub fn attach(
233        self: &Arc<Stage>,
234        idx: usize,
235        activity: Arc<crate::hooks::common::Activity>,
236    ) -> AttachGuard {
237        let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
238        if let Some(slot) = slots.get_mut(idx) {
239            slot.activity = Some(activity);
240        }
241        AttachGuard {
242            stage: Arc::clone(self),
243            idx,
244        }
245    }
246
247    /// Append raw bytes (a captured child's output) to slot `idx`.
248    pub fn append_raw(&self, idx: usize, bytes: &[u8]) {
249        let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
250        if let Some(slot) = slots.get_mut(idx) {
251            if !slot.done {
252                match slot.capture.as_mut() {
253                    Some(capture) => capture.take(bytes),
254                    None => slot.buf.extend_from_slice(bytes),
255                }
256                slot.last_output = Instant::now();
257            }
258        }
259    }
260
261    /// This stage is one check run by name: its pass prints an `ok` line.
262    pub fn named(&self) {
263        self.named.store(true, Ordering::Relaxed);
264    }
265
266    /// The exit code of the tool slot `idx` just ran (`None`: killed).
267    pub fn runner_exit(&self, idx: usize, code: Option<i32>) {
268        let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
269        if let Some(slot) = slots.get_mut(idx) {
270            slot.runner_exit = code;
271        }
272    }
273
274    fn append_line(&self, idx: usize, line: &str) {
275        let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
276        if let Some(slot) = slots.get_mut(idx) {
277            if !slot.done {
278                slot.buf.extend_from_slice(line.as_bytes());
279                slot.buf.push(b'\n');
280                slot.last_output = Instant::now();
281            }
282        }
283    }
284
285    /// The check is over: emit everything it said as ONE contiguous write,
286    /// with the region lifted out of the way first and repainted after —
287    /// blocks pile up above, spinners stay below.
288    ///
289    /// Called by the dispatcher after `check.run` returns (still on the
290    /// check's thread, so a torn-down thread cannot strand a buffer — the
291    /// same `catch_unwind` that feeds the dead-check outcome runs first).
292    ///
293    /// `outcome` is the check's, when it returned one; `None` is a check
294    /// whose thread died, which has not passed. Only a quiet slot reads it.
295    pub fn finish(
296        &self,
297        settings: &crate::config::Settings,
298        idx: usize,
299        outcome: Option<crate::check::Outcome>,
300    ) {
301        let block = {
302            let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
303            let Some(slot) = slots.get_mut(idx) else {
304                return;
305            };
306            slot.done = true;
307            slot.running = false;
308            let said = std::mem::take(&mut slot.buf);
309            match slot.capture.take() {
310                None => QuietOut::plain(said),
311                Some(capture) => quiet_block(QuietEnd {
312                    name: &slot.name,
313                    secs: slot.started.elapsed().as_secs_f64(),
314                    outcome,
315                    said,
316                    capture,
317                    runner_exit: slot.runner_exit,
318                    ci: in_ci(),
319                    ok_line: self.named.load(Ordering::Relaxed),
320                }),
321            }
322        };
323        if block.is_empty() && !self.live {
324            return;
325        }
326        let mut drawn = self.out.lock().unwrap_or_else(|p| p.into_inner());
327        if !block.is_empty() {
328            if *drawn > 0 {
329                let mut err = std::io::stderr().lock();
330                let _ = write!(err, "\x1b[{}A\x1b[J", *drawn);
331                let _ = err.flush();
332                *drawn = 0;
333            }
334            let stdout = std::io::stdout();
335            let mut handle = stdout.lock();
336            block.write(&mut handle);
337            let _ = handle.flush();
338        }
339        self.repaint(settings, &mut drawn);
340    }
341
342    /// Erase and redraw the region in one stderr write. Lock order is
343    /// `out` → `slots`, everywhere — never the reverse.
344    fn repaint(&self, settings: &crate::config::Settings, drawn: &mut usize) {
345        if !self.live {
346            return;
347        }
348        let entries: Vec<Row> = {
349            let slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
350            let now = Instant::now();
351            slots
352                .iter()
353                .filter(|s| s.running && !s.done)
354                .map(|s| row_of(s, now, now.duration_since(s.started).as_secs_f64()))
355                .collect()
356        };
357        let text = region(&entries, term_width(), budgets(settings));
358        let mut paint = String::new();
359        if *drawn > 0 {
360            paint.push_str(&format!("\x1b[{}A\x1b[J", *drawn));
361        }
362        paint.push_str(&text);
363        if paint.is_empty() {
364            return;
365        }
366        let mut err = std::io::stderr().lock();
367        let _ = err.write_all(paint.as_bytes());
368        let _ = err.flush();
369        *drawn = text.matches('\n').count();
370    }
371}
372
373impl Drop for Stage {
374    /// The stage's end erases whatever the region still shows — a Block
375    /// verdict, a panic on the dispatcher path, anything: no spinner junk
376    /// above the roll-up. (`get_mut`: dropping proves no other thread holds
377    /// the stage, so the locks are free.)
378    fn drop(&mut self) {
379        self.stop.store(true, Ordering::Relaxed);
380        if !self.live {
381            return;
382        }
383        let drawn = self.out.get_mut().unwrap_or_else(|p| p.into_inner());
384        if *drawn > 0 {
385            let mut err = std::io::stderr().lock();
386            let _ = write!(err, "\x1b[{}A\x1b[J", *drawn);
387            let _ = err.flush();
388            *drawn = 0;
389        }
390    }
391}
392
393/// The ticker: repaint every 80ms until the stage drops or tells it to
394/// stop. Holds only a `Weak`, so it can never keep a finished stage alive.
395/// Owns its `Settings` (see [`crate::config::Settings::for_thread`]): a
396/// spawned thread is `'static`, and the budgets must be read lazily, not
397/// pre-resolved at the spawn.
398fn tick(settings: crate::config::Settings, weak: Weak<Stage>) {
399    loop {
400        std::thread::sleep(std::time::Duration::from_millis(80));
401        let Some(stage) = weak.upgrade() else { return };
402        if stage.stop.load(Ordering::Relaxed) {
403            return;
404        }
405        let mut drawn = stage.out.lock().unwrap_or_else(|p| p.into_inner());
406        stage.repaint(&settings, &mut drawn);
407    }
408}
409
410/// One running check, as the region and the heartbeat see it.
411#[derive(Debug, Clone)]
412pub struct Row {
413    pub name: String,
414    /// Seconds since the check entered.
415    pub elapsed: f64,
416    /// Seconds since it last wrote anything.
417    pub quiet: f64,
418    /// Seconds it has been silent AND idle on CPU — what the silence budget
419    /// is judged against. Equal to `quiet` when CPU is not sampled.
420    pub still: f64,
421    pub cpu: RowCpu,
422    /// The declared lock wait it is in, and for how many seconds
423    /// (ADR-0009): shown instead of the silence countdown, which does not
424    /// run meanwhile.
425    pub wait: Option<(crate::hooks::wait::WaitKind, f64)>,
426    /// The silence budget the kill decision is applying, stretched by the
427    /// host's load, with the load and the factor; `None` while it is the
428    /// configured one (ADR-0009).
429    pub load: Option<(u64, crate::load::Load, u32)>,
430    /// Waiting for a host slot: for how many seconds, out of how many
431    /// slots.
432    pub queued: Option<(f64, u64)>,
433}
434
435/// What a running check's CPU is doing, as far as the displays may say.
436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
437pub enum RowCpu {
438    /// No spawned command is attached (an in-process check, or between two
439    /// commands): nothing to say.
440    None,
441    /// A command is attached but its CPU is not sampled here
442    /// (`greengate.idleCpuCredit false`, no silence budget, or the platform):
443    /// silence alone counts.
444    NotSampled,
445    /// Sampled, but nothing fresh to report (not quiet long enough yet, or
446    /// the last snapshot was incomplete).
447    Unmeasured,
448    /// Measurably working, at this many thousandths of a core.
449    Busy(u32),
450    /// Measured under the busy threshold.
451    Idle,
452}
453
454/// A slot as a [`Row`], reading its attached command's clocks when there is
455/// one. The quiet figure is the more recent of the slot's own lines and the
456/// command's bytes (a captured command writes to one and not the other).
457fn row_of(s: &Slot, now: Instant, elapsed: f64) -> Row {
458    use crate::hooks::common::{CpuState, BUSY_MILLI_CORES};
459    let slot_quiet = now.duration_since(s.last_output).as_secs_f64();
460    let (quiet, still, cpu, wait, load) = match &s.activity {
461        None => (slot_quiet, slot_quiet, RowCpu::None, None, None),
462        Some(a) => {
463            let quiet = slot_quiet.min(a.quiet_for().as_secs_f64());
464            let still = quiet.min(a.still_for().as_secs_f64());
465            let cpu = match (a.cpu_state(), a.fresh_rate()) {
466                (CpuState::Off, _) => RowCpu::NotSampled,
467                (_, Some(r)) if r >= BUSY_MILLI_CORES => RowCpu::Busy(r),
468                (_, Some(_)) => RowCpu::Idle,
469                (_, None) => RowCpu::Unmeasured,
470            };
471            let wait = a.waiting().map(|(k, d)| (k, d.as_secs_f64()));
472            (quiet, still, cpu, wait, a.load_scale())
473        }
474    };
475    Row {
476        name: s.name.clone(),
477        elapsed,
478        quiet,
479        still,
480        cpu,
481        wait,
482        load,
483        queued: s
484            .queued
485            .map(|(since, n)| (now.duration_since(since).as_secs_f64(), n)),
486    }
487}
488
489impl Row {
490    /// The silence budget this row counts toward: the load-stretched one
491    /// when the host stretched it, else the configured one.
492    fn applied_idle(&self, budgets: Budgets) -> u64 {
493        match self.load {
494            Some((applied, _, _)) if applied > 0 => applied,
495            _ => budgets.idle,
496        }
497    }
498}
499
500/// The clocks, as the region annotates them, in seconds: `idle` and
501/// `ceiling` with `0` for off; `lock_wait` with `0` for "until the
502/// ceiling".
503#[derive(Debug, Clone, Copy)]
504pub struct Budgets {
505    pub idle: u64,
506    pub ceiling: u64,
507    pub lock_wait: u64,
508    /// The extended silence budget, `idle × greengate.idleLoadScale`: what a
509    /// check answers to while its CPU cannot be measured.
510    pub extended: u64,
511}
512
513fn budgets(settings: &crate::config::Settings) -> Budgets {
514    let idle = crate::hooks::common::idle_timeout(settings);
515    Budgets {
516        idle,
517        extended: idle.saturating_mul(crate::hooks::common::idle_load_scale(settings)),
518        ceiling: crate::hooks::common::check_timeout(settings),
519        lock_wait: match crate::hooks::common::lock_wait(settings) {
520            crate::hooks::common::LockWait::Secs(s) => s,
521            crate::hooks::common::LockWait::UntilCeiling => 0,
522        },
523    }
524}
525
526/// How long a check must be quiet before the region says so. A test suite
527/// pauses this long between crates without anything being wrong; past it,
528/// the reader wants to know the silence is being counted.
529const QUIET_NOTE_SECS: f64 = 30.0;
530
531/// The non-tty heartbeat's period: one line a minute per running check.
532const HEARTBEAT_SECS: u64 = 60;
533
534/// Elapsed time in a fixed six-column figure: `  3.2s` under a minute,
535/// `8m12s` and `1h02m` above, so the column stays aligned as the suite
536/// crosses the minute.
537fn elapsed_column(secs: f64) -> String {
538    if secs < 60.0 {
539        format!("{secs:>5.1}s")
540    } else {
541        format!("{:>6}", crate::hooks::common::human_secs(secs as u64))
542    }
543}
544
545/// The region's text: one `⠹ name  12.3s` line per running check, capped at
546/// [`MAX_LINES`] plus a `… and N more` overflow line. Pure — the ticker is
547/// a thin shell around this, and the tests drive it directly.
548///
549/// Two annotations, each only when it carries news: `· quiet 45s/2m` once
550/// a check has been silent past [`QUIET_NOTE_SECS`] (with the silence
551/// budget it is counting toward, when there is one), and `· 48m/60m` once
552/// elapsed passes 80% of the ceiling — the cliff, shown before the fall.
553fn region(entries: &[Row], width: usize, budgets: Budgets) -> String {
554    if entries.is_empty() {
555        return String::new();
556    }
557    let pad = entries
558        .iter()
559        .take(MAX_LINES)
560        .map(|r| r.name.chars().count())
561        .max()
562        .unwrap_or(0);
563    let mut out = String::new();
564    for row in entries.iter().take(MAX_LINES) {
565        let frame = FRAMES[((row.elapsed * 10.0) as usize) % FRAMES.len()];
566        let name = &row.name;
567        let mut line = format!("{frame} {name:<pad$} {}", elapsed_column(row.elapsed));
568        if let Some((secs, n)) = row.queued {
569            line.push_str(&format!(
570                " · queued {} (slots {n}/{n})",
571                crate::hooks::common::human_secs(secs as u64)
572            ));
573        } else if let Some((kind, waited)) = row.wait {
574            // A declared wait: no silence countdown runs, so the row says
575            // what is being waited for and against which budget.
576            line.push_str(&format!(
577                " · {} {}",
578                kind.short(),
579                crate::hooks::common::human_secs(waited as u64)
580            ));
581            if budgets.lock_wait > 0 {
582                line.push_str(&format!(
583                    "/{}",
584                    crate::hooks::common::human_secs(budgets.lock_wait)
585                ));
586            }
587        } else if row.quiet >= QUIET_NOTE_SECS {
588            let quiet = crate::hooks::common::human_secs(row.quiet as u64);
589            match row.cpu {
590                // Working: no countdown — no kill is coming — just how hard.
591                RowCpu::Busy(m) => line.push_str(&format!(
592                    " · quiet {quiet} · {}",
593                    crate::hooks::common::cores(m)
594                )),
595                _ if budgets.idle == 0 => line.push_str(&format!(" · quiet {quiet}")),
596                // The countdown counts what the kill decision counts: the
597                // still-time, which only differs from the silence once CPU
598                // work has pushed it back.
599                // Unmeasured: the extended budget is the one that counts,
600                // and the row says why the figure is not the usual one.
601                RowCpu::Unmeasured => line.push_str(&format!(
602                    " · quiet {quiet}/{} (CPU unmeasured)",
603                    crate::hooks::common::human_secs(budgets.extended.max(budgets.idle))
604                )),
605                RowCpu::Idle if row.quiet - row.still >= 1.0 => line.push_str(&format!(
606                    " · quiet {quiet} · idle {}/{}",
607                    crate::hooks::common::human_secs(row.still as u64),
608                    crate::hooks::common::human_secs(row.applied_idle(budgets))
609                )),
610                _ => line.push_str(&format!(
611                    " · quiet {quiet}/{}",
612                    crate::hooks::common::human_secs(row.applied_idle(budgets))
613                )),
614            }
615            if let (Some((_, _, factor)), false) = (row.load, row.cpu == RowCpu::Unmeasured) {
616                line.push_str(&format!(" (load {})", crate::load::factor_text(factor)));
617            }
618        }
619        if budgets.ceiling > 0 && row.elapsed >= 0.8 * budgets.ceiling as f64 {
620            line.push_str(&format!(
621                " · {}/{}",
622                crate::hooks::common::human_secs(row.elapsed as u64),
623                crate::hooks::common::human_secs(budgets.ceiling)
624            ));
625        }
626        if line.chars().count() > width {
627            out.extend(line.chars().take(width));
628        } else {
629            out.push_str(&line);
630        }
631        out.push('\n');
632    }
633    if entries.len() > MAX_LINES {
634        out.push_str(&format!("… and {} more\n", entries.len() - MAX_LINES));
635    }
636    out
637}
638
639/// The heartbeat: once a minute, for each check still running, one plain
640/// line on stderr — elapsed, and how long since it last said anything.
641/// Not a region: nothing is erased or repainted, because nobody is looking
642/// at a cursor; whoever reads this reads a log.
643///
644/// The first beat for a check also names the two budgets, once, so the
645/// reader can tell how far it is from being killed without opening the
646/// docs. Written under the same `out` lock as the blocks, so a beat never
647/// lands inside one.
648/// Owns its `Settings` for the same reason [`tick`] does.
649/// What a quiet slot knows when its check ends.
650struct QuietEnd<'a> {
651    name: &'a str,
652    secs: f64,
653    outcome: Option<crate::check::Outcome>,
654    /// The check's own messages, as today.
655    said: Vec<u8>,
656    capture: crate::capture::Capture,
657    runner_exit: Option<i32>,
658    ci: bool,
659    /// Print `ok <check> …` on a pass (a check run by name).
660    ok_line: bool,
661}
662
663/// `CI` set to anything but empty, `false` or `0`. Under CI a failure prints
664/// its whole log: the log file goes away with the runner.
665fn in_ci() -> bool {
666    std::env::var("CI").is_ok_and(|v| !v.is_empty() && v != "false" && v != "0")
667}
668
669/// A quiet slot's block: one line for a pass; for anything else the check's
670/// own messages, then each failure block of the tool's output in full and
671/// the log's path. Pure but for the log file it closes and renames.
672fn quiet_block(mut end: QuietEnd) -> QuietOut {
673    let stored = end.capture.finish();
674    let failed = is_failure(end.outcome);
675    // The active-run entry carries the check's result, not the tool's: a
676    // failure with a runner exit of 0 is still a failure in relais's pane.
677    let exit = match (end.outcome, failed) {
678        (None, _) => None,
679        (Some(_), true) => Some(end.runner_exit.filter(|c| *c != 0).unwrap_or(1)),
680        (Some(_), false) => Some(0),
681    };
682    end.capture.end_entry(exit, stored.path());
683    let passed = end.outcome == Some(crate::check::Outcome::Passed);
684    if end.capture.seen == 0 {
685        // No tool output: a check that runs no tool (ban-terms, secrets), or
686        // one the push stage skipped before it ran. Exactly what it printed
687        // before quiet captured anything — under quiet, nothing on a pass —
688        // and no empty log left behind. A tool that ran and printed nothing
689        // on a failure says so.
690        if let Some(p) = stored.path() {
691            let _ = std::fs::remove_file(p);
692        }
693        let mut head = end.said;
694        if failed && end.runner_exit.is_some() {
695            head.extend_from_slice(b"(no output)\n");
696            if let Some(code) = end.runner_exit.filter(|c| *c != 0) {
697                head.extend_from_slice(
698                    format!("{} failed, runner exit {code}\n", end.name).as_bytes(),
699                );
700            }
701        }
702        return QuietOut::plain(head);
703    }
704    if passed && !end.ok_line {
705        // In a stage: silent, like every passing check under quiet; the log
706        // stays on disk for whoever wants it.
707        return QuietOut::plain(end.said);
708    }
709    let path = stored.path().map(|p| p.display().to_string());
710    if passed {
711        let mut out = format!("ok {} {:.1}s", end.name, end.secs);
712        if let (crate::capture::Stored::Saved(_), Some(p)) = (&stored, &path) {
713            out.push_str(&format!(" log={p}"));
714        }
715        out.push('\n');
716        if let Some(note) = stored.note() {
717            out.push_str(&note);
718            out.push('\n');
719        }
720        return QuietOut::plain(out.into_bytes());
721    }
722    let excerpt = end.capture.acc.finish(path.as_deref().unwrap_or("-"));
723    let mut tail = String::new();
724    if failed {
725        if let Some(code) = end.runner_exit.filter(|c| *c != 0) {
726            tail.push_str(&format!("{} failed, runner exit {code}\n", end.name));
727        }
728    }
729    if let Some(p) = &path {
730        tail.push_str(&format!("full log: {p}\n"));
731    }
732    if let Some(note) = stored.note() {
733        tail.push_str(&note);
734        tail.push('\n');
735    }
736    // Under CI a failure prints its whole log, copied from the file when the
737    // block is written: the file goes away with the runner. The excerpt is
738    // what prints if the copy cannot be made.
739    match (&stored, end.ci && failed) {
740        (crate::capture::Stored::Saved(p), true) => QuietOut {
741            head: end.said,
742            stream: Some((p.clone(), excerpt)),
743            tail: tail.into_bytes(),
744        },
745        _ => {
746            let mut head = end.said;
747            head.extend_from_slice(excerpt.as_bytes());
748            QuietOut {
749                head,
750                stream: None,
751                tail: tail.into_bytes(),
752            }
753        }
754    }
755}
756
757/// A finished slot's block: `head`, then a log file copied out whole (with
758/// the excerpt to print if the copy fails), then `tail`.
759struct QuietOut {
760    head: Vec<u8>,
761    stream: Option<(std::path::PathBuf, String)>,
762    tail: Vec<u8>,
763}
764
765impl QuietOut {
766    fn plain(head: Vec<u8>) -> QuietOut {
767        QuietOut {
768            head,
769            stream: None,
770            tail: Vec::new(),
771        }
772    }
773
774    fn is_empty(&self) -> bool {
775        self.head.is_empty() && self.stream.is_none() && self.tail.is_empty()
776    }
777
778    fn write(self, to: &mut impl Write) {
779        let _ = to.write_all(&self.head);
780        if let Some((path, excerpt)) = self.stream {
781            let copied = std::fs::File::open(&path).and_then(|mut f| std::io::copy(&mut f, to));
782            if let Err(e) = copied {
783                let _ = to.write_all(excerpt.as_bytes());
784                let _ = writeln!(to, "log not read: {e}");
785            }
786        }
787        let _ = to.write_all(&self.tail);
788    }
789}
790
791/// Whether an outcome is a failure for the quiet block: the failure line
792/// and, under CI, the whole log. A check whose thread died (`None`) has not
793/// passed. Every variant named, so a new one is a compile error here.
794fn is_failure(outcome: Option<crate::check::Outcome>) -> bool {
795    use crate::check::Outcome;
796    match outcome {
797        None => true,
798        Some(Outcome::Failed) => true,
799        Some(
800            Outcome::Passed
801            | Outcome::Warned
802            | Outcome::Fixed
803            | Outcome::Unavailable
804            | Outcome::Inert
805            | Outcome::Deferred
806            | Outcome::Skipped,
807        ) => false,
808    }
809}
810
811fn heartbeat(settings: crate::config::Settings, weak: Weak<Stage>) {
812    loop {
813        std::thread::sleep(crate::clock::scaled(std::time::Duration::from_secs(1)));
814        let Some(stage) = weak.upgrade() else { return };
815        if stage.stop.load(Ordering::Relaxed) {
816            return;
817        }
818        let mut announce: Vec<String> = Vec::new();
819        let due: Vec<(Row, bool)> = {
820            let mut slots = stage.slots.lock().unwrap_or_else(|p| p.into_inner());
821            let now = Instant::now();
822            let mut due = Vec::new();
823            for s in slots.iter_mut().filter(|s| s.running && !s.done) {
824                let ran = now.duration_since(s.started);
825                let elapsed = ran.as_secs();
826                // Only a log the tool has written to: a check that prints
827                // nothing keeps no log, and the line would point at nothing.
828                if !s.announced
829                    && ran >= crate::clock::scaled(std::time::Duration::from_secs(ANNOUNCE_SECS))
830                {
831                    if let Some(c) = s.capture.as_ref().filter(|c| c.writing() && c.seen > 0) {
832                        s.announced = true;
833                        announce.push(format!("running {}, log {}\n", s.name, c.tmp.display()));
834                    }
835                }
836                if elapsed >= s.next_beat {
837                    let first = s.next_beat == HEARTBEAT_SECS;
838                    s.next_beat += HEARTBEAT_SECS;
839                    due.push((row_of(s, now, elapsed as f64), first));
840                }
841            }
842            due
843        };
844        if due.is_empty() && announce.is_empty() {
845            continue;
846        }
847        let text: String = announce.concat()
848            + &due
849                .iter()
850                .map(|(row, first)| {
851                    beat_line(
852                        row,
853                        *first,
854                        budgets(&settings),
855                        stage.on_push,
856                        stage.way_out,
857                    )
858                })
859                .collect::<String>();
860        let _guard = stage.out.lock().unwrap_or_else(|p| p.into_inner());
861        let mut err = std::io::stderr().lock();
862        let _ = err.write_all(text.as_bytes());
863        let _ = err.flush();
864    }
865}
866
867/// One heartbeat line. Pure, for the tests.
868///
869/// On the FIRST beat of a PUSH gate it also names something no other part of
870/// the system is placed to explain. `git push` opens its connection to the
871/// remote, reads the remote refs — which is where the `pre-push` hook's own
872/// stdin comes from — and only then calls the hook. The connection is
873/// therefore already open and goes idle for exactly as long as the gate
874/// runs, and a remote may close it before the gate finishes. git then
875/// reports `Connection reset by peer`, which reads as a network fault and
876/// says nothing about the seven minutes that caused it.
877///
878/// The note does NOT recommend ssh keepalive, and that omission is
879/// deliberate: `ServerAliveInterval 60` was already in force on the machine
880/// where this was diagnosed, and GitHub reset the connection anyway.
881/// Whatever the remote is measuring, it is not packets. Recommending it
882/// would be a confident instruction to change a setting that is probably
883/// already on and cannot help, so the note says so and points at the thing
884/// that does work.
885///
886/// Only on a first beat, so it is said once; only on a push, so a commit
887/// gate never hears it. A first beat is a check that has already run a full
888/// minute, which is the population at risk — no threshold to invent.
889///
890/// `way_out` is decided once per stage (see [`Stage`]), not read here.
891fn beat_line(row: &Row, first: bool, budgets: Budgets, on_push: bool, way_out: WayOut) -> String {
892    use crate::hooks::common::human_secs;
893    // The prefix is byte-for-byte what it always was: log readers grep it.
894    // What CPU sampling adds goes after it.
895    let mut line = format!(
896        "  … {} still running: {}, last output {} ago",
897        row.name,
898        human_secs(row.elapsed as u64),
899        human_secs(row.quiet as u64)
900    );
901    if let Some((secs, n)) = row.queued {
902        line.push_str(&queued_note(secs, n, budgets.ceiling));
903    } else if let Some((kind, waited)) = row.wait {
904        line.push_str(&format!(
905            ", waiting for {} {}",
906            kind.describe(),
907            human_secs(waited as u64)
908        ));
909        match budgets.lock_wait {
910            0 => line.push_str(" (greengate.lockWait 0: until the ceiling)"),
911            s => line.push_str(&format!(" (greengate.lockWait {})", human_secs(s))),
912        }
913    } else {
914        match row.cpu {
915            RowCpu::Busy(m) => line.push_str(&format!(", busy {}", crate::hooks::common::cores(m))),
916            RowCpu::Idle => line.push_str(&format!(", CPU idle {}", human_secs(row.still as u64))),
917            RowCpu::Unmeasured if budgets.idle > 0 => line.push_str(&format!(
918                ", CPU unmeasured — extended budget {}",
919                human_secs(budgets.extended.max(budgets.idle))
920            )),
921            RowCpu::Unmeasured => line.push_str(", CPU unmeasured"),
922            RowCpu::None | RowCpu::NotSampled => {}
923        }
924        if let (Some((applied, load, factor)), false) = (row.load, row.cpu == RowCpu::Unmeasured) {
925            line.push_str(&format!(
926                ", budget {} (load avg {} on {} cores, {} — greengate.idleLoadScale)",
927                human_secs(applied),
928                load.avg1_text(),
929                load.cores,
930                crate::load::factor_text(factor)
931            ));
932        }
933    }
934    if first {
935        let idle = match row.applied_idle(budgets) {
936            0 => "off".to_string(),
937            s => human_secs(s),
938        };
939        let ceiling = match budgets.ceiling {
940            0 => "off".to_string(),
941            s => human_secs(s),
942        };
943        match row.cpu {
944            // In a declared wait the silence clock is not running: the rule
945            // in force is the wait's own budget.
946            _ if row.wait.is_some() => line.push_str(&format!(
947                " (killed after {} in the wait, or {ceiling} in total — greengate.lockWait / \
948                 greengate.timeout)",
949                match budgets.lock_wait {
950                    0 => ceiling.clone(),
951                    s => human_secs(s),
952                }
953            )),
954            // The budget that applies to THIS check, not the configured
955            // one: while CPU is unmeasured that is the extended budget.
956            RowCpu::Unmeasured if budgets.idle > 0 => line.push_str(&format!(
957                " (killed after {} with no output while its CPU is unmeasured, or {ceiling} \
958                 in total — greengate.idleTimeout × greengate.idleLoadScale / greengate.timeout)",
959                human_secs(budgets.extended.max(budgets.idle))
960            )),
961            RowCpu::Busy(_) | RowCpu::Idle if budgets.idle > 0 => line.push_str(&format!(
962                " (killed after {idle} with no output and under 0.1 core of CPU, or \
963                 {ceiling} in total — greengate.idleTimeout / greengate.timeout)"
964            )),
965            _ => line.push_str(&format!(
966                " (killed after {idle} of silence or {ceiling} in total — greengate.idleTimeout / greengate.timeout)"
967            )),
968        }
969        if row.cpu == RowCpu::NotSampled && budgets.idle > 0 {
970            line.push_str("; CPU not sampled here, silence alone counts");
971        }
972        // The way out is the last words of the line, after the kill rule, so
973        // that nothing reads as part of what to type; the push note below
974        // starts a new line.
975        line.push_str(&skip_clause(row, way_out));
976        if on_push {
977            // `concat!`, not a `\`-continued literal: a continuation keeps
978            // the next line's indentation, which turns the message into runs
979            // of spaces. Each line is its own literal and the newlines are
980            // written down, so what is here is what a reader sees.
981            line.push_str(concat!(
982                "\n    git opened its connection to the remote before calling this",
983                "\n    gate, and it stays idle until the gate finishes. A remote may",
984                "\n    close it first — GitHub does — and the push then fails with",
985                "\n    \"Connection reset by peer\", naming the network rather than the",
986                "\n    wait. ssh keepalive does not prevent this.",
987                "\n    Declaring this check at pre-commit moves it off the push path —",
988                "\n    see \"Moving a gate entry earlier\" in the docs.",
989            ));
990        }
991    }
992    if !first {
993        line.push_str(&skip_clause(row, way_out));
994    }
995    line.push('\n');
996    line
997}
998
999/// Whether the heartbeat offers the way out: a land rehearsal forces
1000/// `onBusy wait` on its snapshot, so there the variable would not skip.
1001#[derive(Clone, Copy)]
1002enum WayOut {
1003    Offered,
1004    Withheld,
1005}
1006
1007impl WayOut {
1008    fn for_snapshot(in_snapshot: bool) -> Self {
1009        if in_snapshot {
1010            WayOut::Withheld
1011        } else {
1012            WayOut::Offered
1013        }
1014    }
1015}
1016
1017/// What the heartbeat says of a check waiting in line for a host slot: how
1018/// long, and what the wait ends at. The end is at most what is left of
1019/// `greengate.timeout` (an `onBusy defer` or `warn` check ends sooner); a hook
1020/// check defers to CI there. Plain text: this is a log line.
1021fn queued_note(secs: f64, slots: u64, timeout: u64) -> String {
1022    use crate::hooks::common::human_secs;
1023    let left = crate::host_slots::wait_ceiling_secs(timeout).saturating_sub(secs as u64);
1024    format!(
1025        ", queued {} for a host slot (greengate.hostSlots {slots}), defers to CI \
1026         in at most {} (greengate.timeout)",
1027        human_secs(secs as u64),
1028        human_secs(left)
1029    )
1030}
1031
1032/// The way out of a queued check's wait: the variable only, because `on_push`
1033/// cannot name the command that was run. A land rehearsal sets
1034/// `GREENGATE_ON_BUSY=wait` for its snapshot, so there the variable is no way
1035/// out and the clause is left out. Empty for a row that is not queued.
1036fn skip_clause(row: &Row, way_out: WayOut) -> String {
1037    match (row.queued, way_out) {
1038        (Some(_), WayOut::Offered) => format!("; skip the queue: rerun with {SKIP_QUEUE}"),
1039        (Some(_), WayOut::Withheld) | (None, _) => String::new(),
1040    }
1041}
1042
1043/// The variable that skips the queue for one run (ADR-0022).
1044const SKIP_QUEUE: &str = "GREENGATE_ON_BUSY=now";
1045
1046/// Whether a stage of these checks runs while git holds a connection to the
1047/// remote open: a push stage, unless it runs inside a rehearsal snapshot
1048/// (land's pre-stage included), where nothing is connected, so the beat's
1049/// connection note would be false. The names arrive fully qualified.
1050fn holds_a_push_connection(names: &[&str], in_snapshot: bool) -> bool {
1051    names.iter().any(|n| n.starts_with("pre-push-")) && !in_snapshot
1052}
1053
1054/// `$COLUMNS` when it is exported and sane, else a conservative 80 — the
1055/// region's lines are short and an ioctl is not worth its portability. 80,
1056/// not wider: shells rarely export `COLUMNS`, and a region line longer than
1057/// the real terminal wraps, which breaks the erase arithmetic.
1058///
1059/// `pub` is now wider than it needs to be — the out-of-crate caller that
1060/// justified it, `amont-agent`, is its own project and carries its own copy.
1061/// Left public rather than narrowed in the same change that removed it.
1062pub fn term_width() -> usize {
1063    std::env::var("COLUMNS")
1064        .ok()
1065        .and_then(|c| c.parse::<usize>().ok())
1066        .filter(|w| *w >= 20)
1067        .unwrap_or(80)
1068}
1069
1070/// Emits slot `idx`'s block when dropped — however the check's closure
1071/// exits, a panic included: the partial output of a check that died still
1072/// reaches the reader, above the dead-check verdict the runner fills in.
1073pub struct FinishOnDrop<'a> {
1074    stage: &'a Stage,
1075    idx: usize,
1076    /// The check's outcome once it has one; `None` when its thread died.
1077    outcome: std::cell::Cell<Option<crate::check::Outcome>>,
1078    /// Carried, because `Drop` takes no arguments and the finish paint
1079    /// needs the budgets. Same lifetime as the stage it belongs to.
1080    settings: &'a crate::config::Settings,
1081}
1082
1083impl<'a> FinishOnDrop<'a> {
1084    pub fn new(
1085        settings: &'a crate::config::Settings,
1086        stage: &'a Stage,
1087        idx: usize,
1088    ) -> FinishOnDrop<'a> {
1089        FinishOnDrop {
1090            stage,
1091            idx,
1092            outcome: std::cell::Cell::new(None),
1093            settings,
1094        }
1095    }
1096
1097    /// Record what the check returned, for the quiet block.
1098    pub fn outcome(&self, outcome: crate::check::Outcome) {
1099        self.outcome.set(Some(outcome));
1100    }
1101}
1102
1103impl Drop for FinishOnDrop<'_> {
1104    fn drop(&mut self) {
1105        self.stage
1106            .finish(self.settings, self.idx, self.outcome.get());
1107    }
1108}
1109
1110/// Uninstalls the thread's sink on drop, whatever path the check took out.
1111pub struct SinkGuard;
1112
1113impl Drop for SinkGuard {
1114    fn drop(&mut self) {
1115        SINK.with(|s| *s.borrow_mut() = None);
1116    }
1117}
1118
1119/// Detaches a command from its slot's displays when dropped. See
1120/// [`Stage::attach`].
1121pub struct AttachGuard {
1122    stage: Arc<Stage>,
1123    idx: usize,
1124}
1125
1126impl Drop for AttachGuard {
1127    fn drop(&mut self) {
1128        let mut slots = self.stage.slots.lock().unwrap_or_else(|p| p.into_inner());
1129        if let Some(slot) = slots.get_mut(self.idx) {
1130            slot.activity = None;
1131        }
1132    }
1133}
1134
1135/// The sink installed on THIS thread, if any — how a child-capture helper on
1136/// the check's own thread learns where the reader threads should append.
1137pub fn current_sink() -> Option<(Arc<Stage>, usize)> {
1138    SINK.with(|s| s.borrow().clone())
1139}
1140
1141/// One line of check output, wherever it should go.
1142///
1143/// THE funnel: `common::ok/fail/warn` call this, so a check's helper prints
1144/// land in its slot during a stage and on stdout everywhere else. `line` is
1145/// taken without a trailing newline, exactly like `println!`.
1146pub fn say(line: &str) {
1147    let routed = SINK.with(|s| {
1148        s.borrow().as_ref().map(|(stage, idx)| {
1149            stage.append_line(*idx, line);
1150        })
1151    });
1152    if routed.is_none() {
1153        println!("{line}");
1154    }
1155}
1156
1157/// `println!`, stage-aware: formats and routes through [`say`]. What every
1158/// direct print inside a CHECK BODY becomes — a line printed raw from a
1159/// check thread bypasses the slot and interleaves, which is the bug this
1160/// module exists to close.
1161#[macro_export]
1162macro_rules! say {
1163    ($($arg:tt)*) => {
1164        $crate::live::say(&format!($($arg)*))
1165    };
1166}
1167
1168/// Should a check's SUCCESS line be swallowed?
1169///
1170/// A hook that passes says one line per check, and on a clean run that is the
1171/// entire output: fourteen lines to say nothing happened. At a terminal those
1172/// lines are the reassurance that the gate ran. Captured — an agent's tool
1173/// result, a CI log — they are re-read on every later turn of the session and
1174/// say no more the tenth time than the first.
1175///
1176/// So the setting names WHO is reading, not how loud to be:
1177///
1178/// - `auto` (default) — quiet when nobody is watching, verbose at a terminal.
1179/// - `never` — every check says it passed, whoever is reading.
1180/// - `always` — quiet everywhere.
1181///
1182/// `auto` is the default because the reader it costs nothing is the one at a
1183/// terminal: `watching()` is true there, so a person sees exactly what they
1184/// saw before. The reader it saves is the one who cannot skim — a captured
1185/// log, an agent's tool result — and that reader was paying for fourteen
1186/// lines of nothing on every turn of a session. A default that is free for
1187/// one audience and compounding for the other is not a neutral default.
1188///
1189/// Only the success lines go. A failure, a warning, a check that could not
1190/// run, a repaired file, and the blocked summary are printed under every
1191/// setting: quiet is about the uneventful path, and nothing else.
1192pub fn quiet(settings: &crate::config::Settings) -> bool {
1193    *settings.quiet.get_or_init(|| {
1194        decide(
1195            crate::config::enumerated_or(settings, "greengate.quiet", QUIET_VALUES, "auto"),
1196            watching(),
1197        )
1198    })
1199}
1200
1201pub const QUIET_VALUES: &[&str] = &["never", "auto", "always"];
1202
1203/// Pure, so the three-way decision is testable without a terminal or a config.
1204fn decide(setting: &str, watching: bool) -> bool {
1205    match setting {
1206        "always" => true,
1207        "auto" => !watching,
1208        // `never`. A value `enumerated_or` rejected never reaches here — it
1209        // complains and hands back the default, which is now `auto`.
1210        _ => false,
1211    }
1212}
1213
1214/// Whether the capture mechanism is on at all. `greengate.progress false` is the
1215/// escape hatch back to raw streaming — one knob, read once.
1216pub fn enabled(settings: &crate::config::Settings) -> bool {
1217    *settings
1218        .progress
1219        .get_or_init(|| crate::config::boolean_or(settings, "greengate.progress", true))
1220}
1221
1222/// Is anyone watching? True only when stderr is a real terminal that speaks
1223/// VT: not piped, not redirected, not `TERM=dumb` — and on Windows only
1224/// with `TERM` actually set, because bare conhost may not interpret the
1225/// cursor codes the region depends on. This is the paint gate; capture
1226/// ([`enabled`]) does not consult it.
1227pub fn watching() -> bool {
1228    static WATCHING: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1229    *WATCHING.get_or_init(|| {
1230        if !std::io::stderr().is_terminal() {
1231            return false;
1232        }
1233        match std::env::var("TERM") {
1234            Ok(term) => term != "dumb",
1235            Err(_) => !cfg!(windows),
1236        }
1237    })
1238}
1239
1240#[cfg(test)]
1241mod tests {
1242    use super::*;
1243
1244    fn test_settings() -> crate::config::Settings {
1245        crate::config::Settings::default()
1246    }
1247
1248    #[test]
1249    fn quiet_asks_who_is_reading() {
1250        assert!(!decide("never", true));
1251        assert!(!decide("never", false));
1252        assert!(always_and_auto_agree_at_a_terminal());
1253        assert!(decide("auto", false), "captured: nobody is watching");
1254        assert!(decide("always", true));
1255        assert!(decide("always", false));
1256        // An unreadable value has already been reported by `enumerated_or`,
1257        // which hands back the default; silence is never assumed.
1258        assert!(!decide("shhh", false));
1259    }
1260
1261    fn always_and_auto_agree_at_a_terminal() -> bool {
1262        !decide("auto", true) && decide("always", true)
1263    }
1264
1265    /// The atomicity contract at the unit level: two threads writing
1266    /// interleaved lines into their own slots come out as two contiguous
1267    /// buffers, whatever the scheduler did.
1268    #[test]
1269    fn slots_do_not_share_a_buffer() {
1270        let stage = Stage::begin(&test_settings(), &["a", "b"]);
1271        std::thread::scope(|scope| {
1272            for idx in 0..2 {
1273                let stage = Arc::clone(&stage);
1274                scope.spawn(move || {
1275                    let _guard = stage.enter(idx);
1276                    for i in 0..50 {
1277                        say(&format!("check-{idx} line-{i}"));
1278                        std::thread::yield_now();
1279                    }
1280                });
1281            }
1282        });
1283        let slots = stage.slots.lock().unwrap();
1284        for idx in 0..2 {
1285            let text = String::from_utf8(slots[idx].buf.clone()).unwrap();
1286            assert_eq!(text.lines().count(), 50);
1287            assert!(
1288                text.lines()
1289                    .all(|l| l.starts_with(&format!("check-{idx} "))),
1290                "a foreign line landed in slot {idx}"
1291            );
1292        }
1293    }
1294
1295    /// A thread with no sink prints; its lines never land in anyone's slot.
1296    #[test]
1297    fn no_sink_means_no_capture() {
1298        let stage = Stage::begin(&test_settings(), &["a"]);
1299        say("goes to stdout, not to a slot");
1300        let slots = stage.slots.lock().unwrap();
1301        assert!(slots[0].buf.is_empty());
1302    }
1303
1304    /// After finish, late writes are dropped rather than stranded — a child
1305    /// reader thread that outlives its check must not corrupt a later block.
1306    #[test]
1307    fn a_finished_slot_takes_no_more_writes() {
1308        let stage = Stage::begin(&test_settings(), &["a"]);
1309        stage.append_raw(0, b"before\n");
1310        stage.finish(&test_settings(), 0, None);
1311        stage.append_raw(0, b"after\n");
1312        let slots = stage.slots.lock().unwrap();
1313        assert!(slots[0].buf.is_empty(), "a write landed after finish");
1314    }
1315
1316    /// A repo-derived check name cannot smuggle control bytes onto a live
1317    /// terminal: sanitised at begin, once, for every later paint.
1318    #[test]
1319    fn a_slot_name_is_sanitised_at_begin() {
1320        let stage = Stage::begin(&test_settings(), &["evil\u{1b}[2Jname\rhere"]);
1321        let slots = stage.slots.lock().unwrap();
1322        assert!(!slots[0].name.contains('\u{1b}'), "{:?}", slots[0].name);
1323        assert!(!slots[0].name.contains('\r'), "{:?}", slots[0].name);
1324    }
1325
1326    /// Region names drop the stage's own prefix — it is the same twelve
1327    /// characters on every line.
1328    #[test]
1329    fn a_slot_name_drops_the_stage_prefix() {
1330        let stage = Stage::begin(
1331            &test_settings(),
1332            &["pre-commit-clippy", "pre-push-run-tests", "bare"],
1333        );
1334        let slots = stage.slots.lock().unwrap();
1335        assert_eq!(slots[0].name, "clippy");
1336        assert_eq!(slots[1].name, "run-tests");
1337        assert_eq!(slots[2].name, "bare");
1338    }
1339
1340    fn row(name: &str, elapsed: f64) -> Row {
1341        Row {
1342            name: name.into(),
1343            elapsed,
1344            quiet: 0.0,
1345            still: 0.0,
1346            cpu: RowCpu::None,
1347            wait: None,
1348            load: None,
1349            queued: None,
1350        }
1351    }
1352
1353    /// A check waiting for a host slot says so in the region, within 80
1354    /// columns, and in the heartbeat after its unchanged prefix.
1355    #[test]
1356    fn a_queued_check_says_it_waits_for_a_host_slot() {
1357        let mut r = row("pre-push-run-tests-js", 42.0);
1358        r.queued = Some((42.0, 2));
1359        let text = region(&[r.clone()], 80, B);
1360        assert!(text.contains("· queued 42s (slots 2/2)"), "{text:?}");
1361        assert!(text.lines().all(|l| l.chars().count() <= 80), "{text:?}");
1362        r.elapsed = 60.0;
1363        r.quiet = 60.0;
1364        r.queued = Some((60.0, 2));
1365        let beat = beat_line(&r, false, B, false, WayOut::Offered);
1366        assert_eq!(
1367            beat,
1368            "  … pre-push-run-tests-js still running: 1m00s, last output 1m00s ago, \
1369             queued 1m00s for a host slot (greengate.hostSlots 2), defers to CI in \
1370             at most 59m00s (greengate.timeout); \
1371             skip the queue: rerun with GREENGATE_ON_BUSY=now\n"
1372        );
1373    }
1374
1375    /// What is left of the ceiling is counted down from the time in line, is
1376    /// never negative, and a disabled `greengate.timeout` (0) still ends at
1377    /// the queue's own 3600 s. The text is plain: no escape bytes.
1378    #[test]
1379    fn a_queued_note_counts_down_to_the_ceiling() {
1380        assert!(queued_note(3590.0, 2, 3600).contains("in at most 10s (greengate.timeout)"));
1381        assert!(queued_note(7200.0, 2, 3600).contains("in at most 0s (greengate.timeout)"));
1382        assert!(queued_note(60.0, 2, 0).contains("in at most 59m00s (greengate.timeout)"));
1383        assert!(!queued_note(60.0, 2, 3600).contains('\x1b'));
1384    }
1385
1386    /// The way out ends the line, after a first beat's kill rule, so nothing
1387    /// reads as part of what to type. A land rehearsal sets `onBusy wait`
1388    /// itself, so there the heartbeat leaves the way out out. The same words
1389    /// whatever `on_push` says: it cannot name the command that was run.
1390    #[test]
1391    fn the_way_out_of_a_queue_ends_the_line_and_is_withheld_in_a_land() {
1392        let mut queued_row = row("pre-push-run-tests-js", 60.0);
1393        queued_row.queued = Some((60.0, 2));
1394        let skip = "skip the queue: rerun with GREENGATE_ON_BUSY=now";
1395        let offered = |first, on_push| beat_line(&queued_row, first, B, on_push, WayOut::Offered);
1396        let first = offered(true, false);
1397        assert!(first.contains("(killed after"), "{first:?}");
1398        assert!(first.ends_with(&format!("; {skip}\n")), "{first:?}");
1399        assert!(!first.contains("\x1b"), "{first:?}");
1400        assert_eq!(offered(false, true), offered(false, false));
1401        let pushing = offered(true, true);
1402        let way_out_at = pushing.find(skip).expect("the way out");
1403        assert!(pushing.find("git opened its connection").unwrap() > way_out_at);
1404        for first_beat in [true, false] {
1405            let withheld = beat_line(&queued_row, first_beat, B, false, WayOut::Withheld);
1406            assert!(!withheld.contains("GREENGATE_ON_BUSY"), "{withheld:?}");
1407            assert!(
1408                withheld.contains("defers to CI in at most 59m00s"),
1409                "{withheld:?}"
1410            );
1411        }
1412    }
1413
1414    /// Under load the region counts toward the stretched budget and says
1415    /// so; the heartbeat names the budget, the load and the key; the first
1416    /// beat states the stretched figure.
1417    #[test]
1418    fn a_load_stretched_budget_is_shown_with_its_load() {
1419        let mut r = row("pre-push-run-tests-js", 240.0);
1420        r.quiet = 130.0;
1421        r.still = 130.0;
1422        r.cpu = RowCpu::Idle;
1423        r.load = Some((
1424            468,
1425            crate::load::Load {
1426                avg1_milli: 31_200,
1427                cores: 8,
1428            },
1429            3900,
1430        ));
1431        let text = region(&[r.clone()], 80, B);
1432        assert!(text.contains("· quiet 2m10s/7m48s (load ×3.9)"), "{text:?}");
1433        assert!(text.lines().all(|l| l.chars().count() <= 80), "{text:?}");
1434        let beat = beat_line(&r, false, B, false, WayOut::Offered);
1435        assert!(
1436            beat.ends_with(
1437                ", CPU idle 2m10s, budget 7m48s (load avg 31.2 on 8 cores, ×3.9 — greengate.idleLoadScale)\n"
1438            ),
1439            "{beat:?}"
1440        );
1441        let first = flat(&beat_line(&r, true, B, false, WayOut::Offered));
1442        assert!(
1443            first.contains("killed after 7m48s with no output and under 0.1 core of CPU"),
1444            "{first:?}"
1445        );
1446    }
1447
1448    const B: Budgets = Budgets {
1449        idle: 120,
1450        ceiling: 3600,
1451        lock_wait: 600,
1452        extended: 480,
1453    };
1454
1455    /// While CPU is unmeasured the extended budget is the one that counts:
1456    /// the region counts toward it and says why, the heartbeat names it,
1457    /// and the first beat states that rule rather than the configured one.
1458    #[test]
1459    fn an_unmeasured_check_is_shown_against_the_extended_budget() {
1460        let mut r = row("pre-push-run-tests-js", 240.0);
1461        r.quiet = 130.0;
1462        r.still = 130.0;
1463        r.cpu = RowCpu::Unmeasured;
1464        let text = region(&[r.clone()], 80, B);
1465        assert!(
1466            text.contains("· quiet 2m10s/8m00s (CPU unmeasured)"),
1467            "{text:?}"
1468        );
1469        assert!(text.lines().all(|l| l.chars().count() <= 80), "{text:?}");
1470        let beat = beat_line(&r, false, B, false, WayOut::Offered);
1471        assert!(
1472            beat.ends_with(", CPU unmeasured — extended budget 8m00s\n"),
1473            "{beat:?}"
1474        );
1475        let first = flat(&beat_line(&r, true, B, false, WayOut::Offered));
1476        assert!(
1477            first.contains(
1478                "killed after 8m00s with no output while its CPU is unmeasured, or 1h00m in total"
1479            ),
1480            "{first:?}"
1481        );
1482        assert!(first.contains("greengate.idleLoadScale"), "{first:?}");
1483    }
1484
1485    /// A declared wait replaces the silence countdown in the region and
1486    /// rides after the heartbeat's unchanged prefix, naming its budget; both
1487    /// fit 80 columns with the longest built-in name.
1488    #[test]
1489    fn a_declared_wait_is_shown_against_its_own_budget() {
1490        use crate::hooks::wait::{CargoLockWhat, WaitKind};
1491        let mut r = row("pre-push-run-tests-js", 240.0);
1492        r.quiet = 130.0;
1493        r.still = 0.0;
1494        r.cpu = RowCpu::Unmeasured;
1495        r.wait = Some((WaitKind::CargoLock(CargoLockWhat::BuildDirectory), 90.0));
1496        let text = region(&[r.clone()], 80, B);
1497        assert!(text.contains("· cargo lock 1m30s/10m00s"), "{text:?}");
1498        assert!(!text.contains("quiet"), "no silence countdown: {text:?}");
1499        assert!(text.lines().all(|l| l.chars().count() <= 80), "{text:?}");
1500        let until = Budgets { lock_wait: 0, ..B };
1501        let text = region(&[r.clone()], 80, until);
1502        assert!(
1503            text.contains("· cargo lock 1m30s") && !text.contains("1m30s/"),
1504            "{text:?}"
1505        );
1506
1507        let beat = beat_line(&r, false, B, false, WayOut::Offered);
1508        assert_eq!(
1509            beat,
1510            "  … pre-push-run-tests-js still running: 4m00s, last output 2m10s ago, \
1511             waiting for the cargo lock on the build directory 1m30s (greengate.lockWait 10m00s)\n"
1512        );
1513        let beat = beat_line(&r, false, until, false, WayOut::Offered);
1514        assert!(
1515            beat.contains("(greengate.lockWait 0: until the ceiling)"),
1516            "{beat:?}"
1517        );
1518        // The first beat states the wait's rule, not the CPU one: the
1519        // silence clock is not running.
1520        let first = flat(&beat_line(&r, true, B, false, WayOut::Offered));
1521        assert!(
1522            first.contains(
1523                "(killed after 10m00s in the wait, or 1h00m in total — greengate.lockWait"
1524            ),
1525            "{first:?}"
1526        );
1527        assert!(!first.contains("unmeasured"), "{first:?}");
1528    }
1529
1530    /// The spinner frame comes from the clock: different elapsed, different
1531    /// frame; same elapsed, same frame.
1532    #[test]
1533    fn frames_advance_with_time() {
1534        let a = region(&[row("clippy", 0.0)], 80, B);
1535        let b = region(&[row("clippy", 0.1)], 80, B);
1536        let c = region(&[row("clippy", 1.0)], 80, B);
1537        assert_ne!(a.chars().next(), b.chars().next());
1538        assert_eq!(a.chars().next(), c.chars().next(), "10 frames per second");
1539    }
1540
1541    /// Names pad to a column so the elapsed figures align — across the
1542    /// minute mark too, where the figure changes shape.
1543    #[test]
1544    fn region_lines_align() {
1545        let text = region(&[row("a", 0.0), row("longer-name", 0.0)], 80, B);
1546        let widths: Vec<usize> = text.lines().map(|l| l.chars().count()).collect();
1547        assert_eq!(widths[0], widths[1], "{text:?}");
1548        let text = region(&[row("a", 3.2), row("b", 492.0)], 80, B);
1549        let widths: Vec<usize> = text.lines().map(|l| l.chars().count()).collect();
1550        assert_eq!(widths[0], widths[1], "{text:?}");
1551        assert!(text.contains("8m12s"), "{text:?}");
1552    }
1553
1554    /// Thirteen running checks paint as twelve lines and one overflow.
1555    #[test]
1556    fn region_caps_and_counts_the_rest() {
1557        let entries: Vec<Row> = (0..13).map(|i| row(&format!("check-{i}"), 0.0)).collect();
1558        let text = region(&entries, 80, B);
1559        assert_eq!(text.lines().count(), MAX_LINES + 1);
1560        assert!(text.ends_with("… and 1 more\n"), "{text:?}");
1561    }
1562
1563    /// A narrow terminal truncates rather than wraps — a wrapped region
1564    /// line would break the erase arithmetic.
1565    #[test]
1566    fn region_respects_width() {
1567        let text = region(&[row("a-name-much-longer-than-the-terminal", 0.0)], 20, B);
1568        assert!(text.lines().all(|l| l.chars().count() <= 20), "{text:?}");
1569    }
1570
1571    /// No running checks, no region — not even a blank line.
1572    #[test]
1573    fn an_empty_region_is_empty() {
1574        assert_eq!(region(&[], 80, B), "");
1575    }
1576
1577    /// Silence is annotated only once it is news, and names the budget it
1578    /// counts toward — a check that just paused between crates says
1579    /// nothing extra.
1580    #[test]
1581    fn a_quiet_check_shows_its_silence_against_the_budget() {
1582        let mut r = row("cargo-test", 300.0);
1583        r.quiet = 5.0;
1584        assert!(!region(&[r.clone()], 80, B).contains("quiet"));
1585        r.quiet = 45.0;
1586        let text = region(&[r.clone()], 80, B);
1587        assert!(text.contains("quiet 45s/2m00s"), "{text:?}");
1588        let off = Budgets { idle: 0, ..B };
1589        let text = region(&[r], 80, off);
1590        assert!(
1591            text.contains("quiet 45s") && !text.contains('/'),
1592            "{text:?}"
1593        );
1594    }
1595
1596    /// A silent check that is working shows how hard, with no countdown —
1597    /// no kill is coming; one whose CPU work pushed the still-time back
1598    /// counts down the still-time, which is what the kill decision uses.
1599    /// Both fit an 80-column terminal with a longish name.
1600    #[test]
1601    fn a_quiet_busy_check_shows_cores_and_an_idle_one_counts_down_the_still_time() {
1602        let mut r = row("vitest-workspace", 240.0);
1603        r.quiet = 130.0;
1604        r.still = 130.0;
1605        r.cpu = RowCpu::Busy(3900);
1606        let busy = region(&[r.clone()], 80, B);
1607        assert!(busy.contains("· quiet 2m10s · ~3.9 cores"), "{busy:?}");
1608        assert!(
1609            !busy.contains("/2m00s"),
1610            "no countdown while busy: {busy:?}"
1611        );
1612
1613        r.cpu = RowCpu::Idle;
1614        r.still = 40.0;
1615        let idle = region(&[r.clone()], 80, B);
1616        assert!(idle.contains("· quiet 2m10s · idle 40s/2m00s"), "{idle:?}");
1617
1618        r.cpu = RowCpu::Unmeasured;
1619        r.still = 130.0;
1620        let plain = region(&[r], 80, B);
1621        assert!(
1622            plain.contains("· quiet 2m10s/8m00s (CPU unmeasured)"),
1623            "{plain:?}"
1624        );
1625
1626        for text in [busy, idle, plain] {
1627            assert!(text.lines().all(|l| l.chars().count() <= 80), "{text:?}");
1628        }
1629    }
1630
1631    /// The heartbeat's prefix is unchanged — log readers grep it — and the
1632    /// CPU state rides after it.
1633    #[test]
1634    fn a_heartbeat_appends_the_cpu_state_after_an_unchanged_prefix() {
1635        let mut r = row("vitest", 240.0);
1636        r.quiet = 130.0;
1637        r.still = 40.0;
1638        let prefix = "  … vitest still running: 4m00s, last output 2m10s ago";
1639        for (cpu, suffix) in [
1640            (RowCpu::Busy(3900), ", busy ~3.9 cores\n"),
1641            (RowCpu::Idle, ", CPU idle 40s\n"),
1642            (
1643                RowCpu::Unmeasured,
1644                ", CPU unmeasured — extended budget 8m00s\n",
1645            ),
1646            (RowCpu::None, "\n"),
1647            (RowCpu::NotSampled, "\n"),
1648        ] {
1649            r.cpu = cpu;
1650            assert_eq!(
1651                beat_line(&r, false, B, false, WayOut::Offered),
1652                format!("{prefix}{suffix}")
1653            );
1654        }
1655    }
1656
1657    /// The first beat states the rule that actually applies to this check.
1658    #[test]
1659    fn the_first_beat_states_the_rule_in_force() {
1660        let mut r = row("vitest", 60.0);
1661        r.cpu = RowCpu::Idle;
1662        let sampled = beat_line(&r, true, B, false, WayOut::Offered);
1663        assert!(
1664            flat(&sampled).contains(
1665                "killed after 2m00s with no output and under 0.1 core of CPU, or 1h00m in total"
1666            ),
1667            "{sampled:?}"
1668        );
1669        r.cpu = RowCpu::NotSampled;
1670        let not = beat_line(&r, true, B, false, WayOut::Offered);
1671        assert!(
1672            not.contains("2m00s of silence or 1h00m in total"),
1673            "{not:?}"
1674        );
1675        assert!(
1676            not.contains("CPU not sampled here, silence alone counts"),
1677            "{not:?}"
1678        );
1679    }
1680
1681    /// The ceiling appears once a check is 80% of the way to it — the cliff,
1682    /// shown before the fall — and never for a disabled ceiling.
1683    #[test]
1684    fn the_ceiling_shows_only_when_it_is_near() {
1685        assert!(!region(&[row("cargo-test", 1000.0)], 80, B).contains("/1h00m"));
1686        let text = region(&[row("cargo-test", 3000.0)], 80, B);
1687        assert!(text.contains("50m00s/1h00m"), "{text:?}");
1688        let off = Budgets { ceiling: 0, ..B };
1689        assert!(!region(&[row("cargo-test", 3000.0)], 80, off).contains("/"));
1690    }
1691
1692    /// The heartbeat says how long, how quiet, and — the first time — the
1693    /// budgets, so a reader at the far end of a pipe can tell "wait" from
1694    /// "kill it" without the docs.
1695    #[test]
1696    fn a_heartbeat_names_the_budgets_once() {
1697        let mut r = row("cargo-test", 60.0);
1698        r.quiet = 2.0;
1699        let first = beat_line(&r, true, B, false, WayOut::Offered);
1700        assert!(
1701            first.contains("cargo-test still running: 1m00s"),
1702            "{first:?}"
1703        );
1704        assert!(first.contains("last output 2s ago"), "{first:?}");
1705        assert!(
1706            first.contains("2m00s of silence or 1h00m in total"),
1707            "{first:?}"
1708        );
1709        assert!(first.contains("greengate.idleTimeout"), "{first:?}");
1710        let later = beat_line(&r, false, B, false, WayOut::Offered);
1711        assert!(!later.contains("greengate.idleTimeout"), "{later:?}");
1712        let off = beat_line(
1713            &r,
1714            true,
1715            Budgets {
1716                idle: 0,
1717                ceiling: 0,
1718                lock_wait: 0,
1719                extended: 0,
1720            },
1721            false,
1722            WayOut::Offered,
1723        );
1724        assert!(off.contains("off of silence or off in total"), "{off:?}");
1725    }
1726
1727    /// The message, with newlines and indentation flattened.
1728    ///
1729    /// The note is wrapped for a terminal, so a literal substring can fall
1730    /// across a line break — asserting on `"may close it first"` failed for
1731    /// no better reason than that `may` ended a line. These tests are about
1732    /// what the message SAYS; re-wrapping it should not break them.
1733    fn flat(line: &str) -> String {
1734        line.split_whitespace().collect::<Vec<_>>().join(" ")
1735    }
1736
1737    /// A long PUSH gate is told what it is sitting on; a commit gate is not.
1738    ///
1739    /// The three negatives matter as much as the positive. Said on every
1740    /// beat it would be nagging; said at commit time it would be false —
1741    /// there is no connection open — and a future refactor that wires
1742    /// `on_push` to a constant would show up here and nowhere else.
1743    #[test]
1744    fn a_long_push_gate_is_told_what_it_is_sitting_on() {
1745        let r = row("cargo-test", 60.0);
1746
1747        let pushing = flat(&beat_line(&r, true, B, true, WayOut::Offered));
1748        assert!(
1749            pushing.contains("A remote may close it first"),
1750            "{pushing:?}"
1751        );
1752        assert!(pushing.contains("Connection reset by peer"), "{pushing:?}");
1753        assert!(
1754            pushing.contains("Moving a gate entry earlier"),
1755            "{pushing:?}"
1756        );
1757
1758        // Once, not every minute.
1759        let later = flat(&beat_line(&r, false, B, true, WayOut::Offered));
1760        assert!(!later.contains("close it first"), "{later:?}");
1761
1762        // Never at commit time: nothing is waiting on a socket there.
1763        let committing = flat(&beat_line(&r, true, B, false, WayOut::Offered));
1764        assert!(!committing.contains("close it first"), "{committing:?}");
1765    }
1766
1767    /// amont #431: inside a rehearsal snapshot a push gate may now queue past
1768    /// its first beat, and the stage must not believe git holds a
1769    /// connection there (none is open), else the beat warns of a reset that
1770    /// cannot happen.
1771    #[test]
1772    fn a_push_stage_in_a_snapshot_holds_no_connection() {
1773        let push = ["pre-push-greenspotter-cli-probe"];
1774        assert!(holds_a_push_connection(&push, false));
1775        assert!(!holds_a_push_connection(&push, true));
1776        assert!(!holds_a_push_connection(&["pre-commit-clippy"], false));
1777    }
1778
1779    /// The advice that does NOT appear, and must not come back.
1780    ///
1781    /// `ServerAliveInterval 60` is the obvious suggestion and it is wrong:
1782    /// it was already in force on the machine where this failure was
1783    /// diagnosed, and the remote reset the connection regardless. Telling
1784    /// every amont user to set it would be confident, actionable and
1785    /// useless. This test exists so that a future reader who has the same
1786    /// obvious idea meets an argument instead of a blank.
1787    #[test]
1788    fn the_push_note_does_not_recommend_ssh_keepalive() {
1789        let r = row("cargo-test", 60.0);
1790        let pushing = flat(&beat_line(&r, true, B, true, WayOut::Offered));
1791        assert!(
1792            !pushing.contains("ServerAlive"),
1793            "keepalive was already on when this failed; recommending it \
1794             would be useless advice: {pushing:?}"
1795        );
1796        assert!(
1797            pushing.contains("ssh keepalive does not prevent this"),
1798            "say so, rather than leaving the reader to try it: {pushing:?}"
1799        );
1800    }
1801}