Skip to main content

greengate_runtime/
capture.rs

1//! A quiet check's output: the whole of it on disk, a bounded excerpt in
2//! memory (fleet plan 2026-10-11 "test output keeps its status", shared
3//! rules).
4//!
5//! A captured check used to grow `slot.buf` with every byte its tool
6//! printed and pour it all out at the end — a passing clippy was 3.4 KB of
7//! download lines in an agent's context. Under quiet, the bytes go to
8//! `<git-dir>/amont/logs/<check>.<pid>.log.tmp` as they arrive (tailable
9//! while the check runs), and through the excerpt accumulator, which holds
10//! at most 64 KB whatever the tool prints. When the check ends the file is
11//! renamed to `.log`, and the slot prints one line on a pass or the
12//! failure blocks on anything else.
13//!
14//! Storage is never allowed to change the verdict: a log that cannot be
15//! created, written or renamed stops being written, the accumulator keeps
16//! being fed, and the result says where the log is not.
17//!
18//! holds-until: amont installs no SIGINT/SIGTERM handler of its own for
19//! this. `staged_only` already does, to bring back the user's parked
20//! unstaged changes during the index-fidelity hold, and a second handler on
21//! the commit path would compete with it. So an interrupted run leaves its
22//! `<check>.<pid>.log.tmp` — complete up to the interrupt, and named by the
23//! running line — and pruning never removes a `.tmp`. Revisit when amont
24//! has one signal path that both can register with. (`cluster sign --watch`
25//! installs a handler of its own, a flag on the first signal and the
26//! default death on the second, in a process that never runs a check; the raw calls both handlers use live in `posix_signal`, but there
27//! is still no shared registration.)
28
29use std::fs::{self, File, OpenOptions};
30use std::io::Write;
31use std::path::{Path, PathBuf};
32
33use crate::excerpt::Accumulator;
34
35/// Finished logs kept per check. `*.tmp` (a run in flight, or one a killed
36/// process left) are never pruned.
37const KEEP: usize = 10;
38
39/// Where a check's log ended up.
40pub enum Stored {
41    Saved(PathBuf),
42    /// The run is complete in the `.tmp`; only the rename failed.
43    RenameFailed(PathBuf),
44    NotWritten(String),
45}
46
47impl Stored {
48    /// The line to print after the result, when the log is not where the
49    /// result says it is.
50    pub fn note(&self) -> Option<String> {
51        match self {
52            Stored::Saved(_) => None,
53            Stored::RenameFailed(tmp) => Some(format!("log left at {}", tmp.display())),
54            Stored::NotWritten(why) => Some(format!("log not written: {why}")),
55        }
56    }
57
58    /// The path a reader can open, if any.
59    pub fn path(&self) -> Option<&Path> {
60        match self {
61            Stored::Saved(p) | Stored::RenameFailed(p) => Some(p),
62            Stored::NotWritten(_) => None,
63        }
64    }
65}
66
67pub struct Capture {
68    pub tmp: PathBuf,
69    done: PathBuf,
70    file: Option<File>,
71    err: Option<String>,
72    written: u64,
73    /// Bytes the tool printed, whether or not the file kept them.
74    pub seen: u64,
75    #[cfg(feature = "test-hooks")]
76    fail_after: Option<u64>,
77    pub acc: Accumulator,
78    /// The active-run entry relais's pane tails this log from, while the run
79    /// is live (see [`greenharness_quiet`]). `None` when it could not be written.
80    entry: Option<greenharness_quiet::Entry>,
81}
82
83/// The repository's top level, asked of git once per process: an entry is
84/// written per check, and a pre-commit runs twenty of them.
85fn repo() -> &'static str {
86    static TOP: std::sync::OnceLock<String> = std::sync::OnceLock::new();
87    TOP.get_or_init(|| {
88        crate::git::stdout(&["rev-parse", "--show-toplevel"]).unwrap_or_else(|| {
89            std::env::current_dir()
90                .map(|d| d.display().to_string())
91                .unwrap_or_default()
92        })
93    })
94}
95
96/// `<git-dir>/amont/logs`, created 0700. `None` outside a repository.
97pub fn log_dir() -> Option<PathBuf> {
98    let git_dir = crate::git::stdout(&["rev-parse", "--absolute-git-dir"])?;
99    Some(
100        PathBuf::from(git_dir)
101            .join(crate::names::STATE_DIR)
102            .join("logs"),
103    )
104}
105
106impl Capture {
107    /// Open `<dir>/<check>.<pid>.log.tmp`. A failure is remembered, not
108    /// returned: the excerpt still works without a file.
109    pub fn open(dir: Option<PathBuf>, check: &str) -> Capture {
110        #[cfg(feature = "test-hooks")]
111        let fail_after = std::env::var("GREENGATE_TEST_LOG_FAIL_AFTER")
112            .ok()
113            .and_then(|v| v.parse().ok());
114        #[cfg(not(feature = "test-hooks"))]
115        let fail_after = None;
116        Capture::open_failing_after(dir, check, fail_after)
117    }
118
119    /// [`Capture::open`], with the write failure the tests inject passed in
120    /// (only honoured under the `test-hooks` feature).
121    pub fn open_failing_after(
122        dir: Option<PathBuf>,
123        check: &str,
124        #[cfg_attr(not(feature = "test-hooks"), allow(unused_variables))] fail_after: Option<u64>,
125    ) -> Capture {
126        let name = file_name(check);
127        let pid = std::process::id();
128        let (tmp, done, file, err) = match dir {
129            None => (
130                PathBuf::new(),
131                PathBuf::new(),
132                None,
133                Some("not inside a git repository".to_string()),
134            ),
135            Some(dir) => {
136                let done = dir.join(format!("{name}.{pid}.log"));
137                let tmp = dir.join(format!("{name}.{pid}.log.tmp"));
138                match create(&dir, &tmp) {
139                    Ok(f) => (tmp, done, Some(f), None),
140                    Err(e) => (tmp, done, None, Some(format!("cannot create the log: {e}"))),
141                }
142            }
143        };
144        // Only a log that exists can be tailed.
145        let session = std::env::var("CLAUDE_CODE_SESSION_ID").unwrap_or_default();
146        let entry = file.as_ref().and_then(|_| {
147            greenharness_quiet::Entry::start(
148                &greenharness_quiet::dir_from_env()?,
149                crate::names::SLOT_HOLDER,
150                &session,
151                check,
152                repo,
153                &tmp,
154            )
155        });
156        Capture {
157            tmp,
158            done,
159            file,
160            err,
161            written: 0,
162            seen: 0,
163            #[cfg(feature = "test-hooks")]
164            fail_after,
165            acc: Accumulator::new(crate::excerpt::DEFAULT_BOUND),
166            entry,
167        }
168    }
169
170    /// End the active-run entry: `exit` is the check's result (`Some(0)` for
171    /// anything but a failure, `None` when the check died), and `log` where
172    /// the log now is. A capture dropped without this ends with no exit.
173    pub fn end_entry(&mut self, exit: Option<i32>, log: Option<&Path>) {
174        if let Some(entry) = self.entry.as_mut() {
175            entry.end(exit, log);
176        }
177    }
178
179    /// Whether a log file is being written.
180    pub fn writing(&self) -> bool {
181        self.file.is_some()
182    }
183
184    pub fn take(&mut self, bytes: &[u8]) {
185        self.seen += bytes.len() as u64;
186        self.acc.feed(bytes);
187        let (chunk, injected) = self.clip(bytes);
188        let Some(file) = self.file.as_mut() else {
189            return;
190        };
191        match file.write_all(chunk) {
192            Ok(()) => self.written += chunk.len() as u64,
193            Err(e) => self.err = Some(format!("write failed: {e}")),
194        }
195        if injected && self.err.is_none() {
196            self.err = Some(format!(
197                "injected write failure after {} bytes",
198                self.written
199            ));
200        }
201        if self.err.is_some() {
202            // Stop writing; the accumulator keeps being fed.
203            self.file = None;
204        }
205    }
206
207    #[cfg(feature = "test-hooks")]
208    fn clip<'a>(&self, bytes: &'a [u8]) -> (&'a [u8], bool) {
209        match self.fail_after {
210            Some(limit) => {
211                let left = limit.saturating_sub(self.written) as usize;
212                if left < bytes.len() {
213                    (&bytes[..left], true)
214                } else {
215                    (bytes, false)
216                }
217            }
218            None => (bytes, false),
219        }
220    }
221
222    #[cfg(not(feature = "test-hooks"))]
223    fn clip<'a>(&self, bytes: &'a [u8]) -> (&'a [u8], bool) {
224        (bytes, false)
225    }
226
227    /// Close the file and move it into place.
228    pub fn finish(&mut self) -> Stored {
229        let file = self.file.take();
230        drop(file);
231        if let Some(why) = self.err.take() {
232            // A prefix of the run is not the run: do not leave it looking
233            // like a log.
234            if !self.tmp.as_os_str().is_empty() {
235                let _ = fs::remove_file(&self.tmp);
236            }
237            return Stored::NotWritten(why);
238        }
239        match fs::rename(&self.tmp, &self.done) {
240            Ok(()) => {
241                if let Some(dir) = self.done.parent() {
242                    prune(dir, &self.done);
243                }
244                Stored::Saved(self.done.clone())
245            }
246            Err(_) => Stored::RenameFailed(self.tmp.clone()),
247        }
248    }
249}
250
251fn create(dir: &Path, tmp: &Path) -> std::io::Result<File> {
252    fs::create_dir_all(dir)?;
253    let mut open = OpenOptions::new();
254    open.write(true).create(true).truncate(true);
255    #[cfg(unix)]
256    {
257        use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
258        let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o700));
259        open.mode(0o600);
260    }
261    open.open(tmp)
262}
263
264/// A check name as a file name: `[A-Za-z0-9._-]`, everything else `_`.
265fn file_name(check: &str) -> String {
266    let clean: String = check
267        .chars()
268        .map(|c| {
269            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
270                c
271            } else {
272                '_'
273            }
274        })
275        .take(60)
276        .collect();
277    if clean.is_empty() {
278        "check".into()
279    } else {
280        clean
281    }
282}
283
284/// Keep the newest [`KEEP`] finished logs of the check `done` belongs to.
285/// Best-effort: a log that cannot be listed or removed is left for the next
286/// run, and nothing this run prints depends on it.
287fn prune(dir: &Path, done: &Path) {
288    let Some(name) = done.file_name().and_then(|n| n.to_str()) else {
289        return;
290    };
291    // `<check>.<pid>.log` → `<check>.`
292    let Some(stem) = name.strip_suffix(".log").and_then(|s| s.rsplit_once('.')) else {
293        return;
294    };
295    let prefix = format!("{}.", stem.0);
296    let Ok(read) = fs::read_dir(dir) else { return };
297    let mut logs: Vec<(std::time::SystemTime, PathBuf)> = read
298        .filter_map(|e| e.ok())
299        .filter(|e| {
300            let n = e.file_name();
301            let n = n.to_string_lossy();
302            n.starts_with(&prefix)
303                && n.ends_with(".log")
304                && n[prefix.len()..n.len() - 4]
305                    .bytes()
306                    .all(|b| b.is_ascii_digit())
307        })
308        .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
309        .collect();
310    logs.sort();
311    let excess = logs.len().saturating_sub(KEEP);
312    for (_, old) in logs.into_iter().take(excess) {
313        let _ = fs::remove_file(old);
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    #[test]
322    fn quiet_entries_never_reach_the_real_state_dir() {
323        // .cargo/config.toml: an agent running this suite must not put its
324        // fixtures in the person's live relais pane.
325        assert_eq!(std::env::var("CLAUDE_CODE_SESSION_ID").as_deref(), Ok(""));
326        assert!(std::env::var("QUIET_ACTIVE_DIR").is_ok_and(|d| d.contains("target")));
327    }
328
329    fn scratch(tag: &str) -> PathBuf {
330        let scratch_dir =
331            std::env::temp_dir().join(format!("greengate-capture-{tag}-{}", std::process::id()));
332        let _ = fs::remove_dir_all(&scratch_dir); // best-effort: a scratch path; absent or left behind is harmless
333        scratch_dir
334    }
335
336    #[test]
337    fn a_tmp_is_renamed_on_finish() {
338        let dir = scratch("rename");
339        let mut c = Capture::open(Some(dir.clone()), "pre-push-cargo-test");
340        assert!(c.tmp.exists());
341        c.take(b"hello\n");
342        let stored = c.finish();
343        let path = stored.path().unwrap().to_path_buf();
344        assert!(path.exists() && !c.tmp.exists());
345        assert_eq!(fs::read_to_string(path).unwrap(), "hello\n");
346        assert!(stored.note().is_none());
347    }
348
349    #[test]
350    fn no_directory_still_gives_an_excerpt() {
351        let mut c = Capture::open(None, "x");
352        c.take(b"thread 'a' panicked at src/a.rs:1:1:\nboom\n");
353        let stored = c.finish();
354        assert!(stored.note().unwrap().starts_with("log not written:"));
355        assert!(c.acc.finish("-").contains("panicked at"));
356    }
357
358    #[test]
359    fn pruning_keeps_ten_and_never_a_tmp_or_another_check() {
360        let dir = scratch("prune");
361        fs::create_dir_all(&dir).unwrap();
362        for i in 0..15 {
363            fs::write(dir.join(format!("clippy.{}.log", 1000 + i)), "x").unwrap();
364            std::thread::sleep(std::time::Duration::from_millis(5));
365        }
366        fs::write(dir.join("clippy.1.log.tmp"), "x").unwrap();
367        fs::write(dir.join("clippy-extra.5.log"), "x").unwrap();
368        let mut c = Capture::open(Some(dir.clone()), "clippy");
369        c.finish();
370        let names: Vec<String> = fs::read_dir(&dir)
371            .unwrap()
372            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
373            .collect();
374        let clippy = names
375            .iter()
376            .filter(|n| n.starts_with("clippy.") && n.ends_with(".log"))
377            .count();
378        assert_eq!(clippy, KEEP, "{names:?}");
379        assert!(names.iter().any(|n| n == "clippy.1.log.tmp"));
380        assert!(names.iter().any(|n| n == "clippy-extra.5.log"));
381    }
382
383    #[cfg(unix)]
384    #[test]
385    fn the_log_is_private() {
386        use std::os::unix::fs::PermissionsExt;
387        let dir = scratch("mode");
388        let c = Capture::open(Some(dir), "x");
389        let mode = fs::metadata(&c.tmp).unwrap().permissions().mode() & 0o777;
390        assert_eq!(mode, 0o600);
391    }
392
393    #[cfg(feature = "test-hooks")]
394    #[test]
395    fn a_failed_write_keeps_the_excerpt() {
396        let dir = scratch("inject");
397        let mut c = Capture::open_failing_after(Some(dir), "x", Some(10));
398        c.take(b"0123456789abcdef\nthread 'a' panicked at src/a.rs:1:1:\n");
399        let stored = c.finish();
400        assert!(stored.note().unwrap().contains("injected write failure"));
401        assert!(!c.tmp.exists());
402        assert!(c.acc.finish("-").contains("panicked at"));
403    }
404
405    #[test]
406    /// Bounded, not merely small at the end: the holding never passes 64 KiB
407    /// at any point of a run 64 times that long. (It fed 50 MiB, checked
408    /// once, and was the slowest unit test by 6 s.)
409    fn a_long_run_keeps_the_accumulator_bounded() {
410        let mut c = Capture::open(None, "x");
411        let chunk: String = (0..1000).map(|i| format!("line {i} ok\n")).collect();
412        let mut fed = 0u64;
413        while fed < 4 * 1024 * 1024 {
414            c.take(chunk.as_bytes());
415            fed += chunk.len() as u64;
416            assert!(c.acc.held() <= 64 * 1024, "{} after {fed}", c.acc.held());
417        }
418        assert_eq!(c.seen, fed);
419    }
420}