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