Skip to main content

amont_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 [`crate::active`]). `None` when it could not be written.
77    entry: Option<crate::active::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(PathBuf::from(git_dir).join("amont").join("logs"))
97}
98
99impl Capture {
100    /// Open `<dir>/<check>.<pid>.log.tmp`. A failure is remembered, not
101    /// returned: the excerpt still works without a file.
102    pub fn open(dir: Option<PathBuf>, check: &str) -> Capture {
103        #[cfg(feature = "test-hooks")]
104        let fail_after = std::env::var("AMONT_TEST_LOG_FAIL_AFTER")
105            .ok()
106            .and_then(|v| v.parse().ok());
107        #[cfg(not(feature = "test-hooks"))]
108        let fail_after = None;
109        Capture::open_failing_after(dir, check, fail_after)
110    }
111
112    /// [`Capture::open`], with the write failure the tests inject passed in
113    /// (only honoured under the `test-hooks` feature).
114    pub fn open_failing_after(
115        dir: Option<PathBuf>,
116        check: &str,
117        #[cfg_attr(not(feature = "test-hooks"), allow(unused_variables))] fail_after: Option<u64>,
118    ) -> Capture {
119        let name = file_name(check);
120        let pid = std::process::id();
121        let (tmp, done, file, err) = match dir {
122            None => (
123                PathBuf::new(),
124                PathBuf::new(),
125                None,
126                Some("not inside a git repository".to_string()),
127            ),
128            Some(dir) => {
129                let done = dir.join(format!("{name}.{pid}.log"));
130                let tmp = dir.join(format!("{name}.{pid}.log.tmp"));
131                match create(&dir, &tmp) {
132                    Ok(f) => (tmp, done, Some(f), None),
133                    Err(e) => (tmp, done, None, Some(format!("cannot create the log: {e}"))),
134                }
135            }
136        };
137        // Only a log that exists can be tailed.
138        let entry = file
139            .as_ref()
140            .and_then(|_| crate::active::Entry::start(&crate::active::dir()?, check, repo, &tmp));
141        Capture {
142            tmp,
143            done,
144            file,
145            err,
146            written: 0,
147            seen: 0,
148            #[cfg(feature = "test-hooks")]
149            fail_after,
150            acc: Accumulator::new(crate::excerpt::DEFAULT_BOUND),
151            entry,
152        }
153    }
154
155    /// End the active-run entry: `exit` is the check's result (`Some(0)` for
156    /// anything but a failure, `None` when the check died), and `log` where
157    /// the log now is. A capture dropped without this ends with no exit.
158    pub fn end_entry(&mut self, exit: Option<i32>, log: Option<&Path>) {
159        if let Some(entry) = self.entry.as_mut() {
160            entry.end(exit, log);
161        }
162    }
163
164    /// Whether a log file is being written.
165    pub fn writing(&self) -> bool {
166        self.file.is_some()
167    }
168
169    pub fn take(&mut self, bytes: &[u8]) {
170        self.seen += bytes.len() as u64;
171        self.acc.feed(bytes);
172        let (chunk, injected) = self.clip(bytes);
173        let Some(file) = self.file.as_mut() else {
174            return;
175        };
176        match file.write_all(chunk) {
177            Ok(()) => self.written += chunk.len() as u64,
178            Err(e) => self.err = Some(format!("write failed: {e}")),
179        }
180        if injected && self.err.is_none() {
181            self.err = Some(format!(
182                "injected write failure after {} bytes",
183                self.written
184            ));
185        }
186        if self.err.is_some() {
187            // Stop writing; the accumulator keeps being fed.
188            self.file = None;
189        }
190    }
191
192    #[cfg(feature = "test-hooks")]
193    fn clip<'a>(&self, bytes: &'a [u8]) -> (&'a [u8], bool) {
194        match self.fail_after {
195            Some(limit) => {
196                let left = limit.saturating_sub(self.written) as usize;
197                if left < bytes.len() {
198                    (&bytes[..left], true)
199                } else {
200                    (bytes, false)
201                }
202            }
203            None => (bytes, false),
204        }
205    }
206
207    #[cfg(not(feature = "test-hooks"))]
208    fn clip<'a>(&self, bytes: &'a [u8]) -> (&'a [u8], bool) {
209        (bytes, false)
210    }
211
212    /// Close the file and move it into place.
213    pub fn finish(&mut self) -> Stored {
214        let file = self.file.take();
215        drop(file);
216        if let Some(why) = self.err.take() {
217            // A prefix of the run is not the run: do not leave it looking
218            // like a log.
219            if !self.tmp.as_os_str().is_empty() {
220                let _ = fs::remove_file(&self.tmp);
221            }
222            return Stored::NotWritten(why);
223        }
224        match fs::rename(&self.tmp, &self.done) {
225            Ok(()) => {
226                if let Some(dir) = self.done.parent() {
227                    prune(dir, &self.done);
228                }
229                Stored::Saved(self.done.clone())
230            }
231            Err(_) => Stored::RenameFailed(self.tmp.clone()),
232        }
233    }
234}
235
236fn create(dir: &Path, tmp: &Path) -> std::io::Result<File> {
237    fs::create_dir_all(dir)?;
238    let mut open = OpenOptions::new();
239    open.write(true).create(true).truncate(true);
240    #[cfg(unix)]
241    {
242        use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
243        let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o700));
244        open.mode(0o600);
245    }
246    open.open(tmp)
247}
248
249/// A check name as a file name: `[A-Za-z0-9._-]`, everything else `_`.
250fn file_name(check: &str) -> String {
251    let clean: String = check
252        .chars()
253        .map(|c| {
254            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
255                c
256            } else {
257                '_'
258            }
259        })
260        .take(60)
261        .collect();
262    if clean.is_empty() {
263        "check".into()
264    } else {
265        clean
266    }
267}
268
269/// Keep the newest [`KEEP`] finished logs of the check `done` belongs to.
270/// Best-effort: a log that cannot be listed or removed is left for the next
271/// run, and nothing this run prints depends on it.
272fn prune(dir: &Path, done: &Path) {
273    let Some(name) = done.file_name().and_then(|n| n.to_str()) else {
274        return;
275    };
276    // `<check>.<pid>.log` → `<check>.`
277    let Some(stem) = name.strip_suffix(".log").and_then(|s| s.rsplit_once('.')) else {
278        return;
279    };
280    let prefix = format!("{}.", stem.0);
281    let Ok(read) = fs::read_dir(dir) else { return };
282    let mut logs: Vec<(std::time::SystemTime, PathBuf)> = read
283        .filter_map(|e| e.ok())
284        .filter(|e| {
285            let n = e.file_name();
286            let n = n.to_string_lossy();
287            n.starts_with(&prefix)
288                && n.ends_with(".log")
289                && n[prefix.len()..n.len() - 4]
290                    .bytes()
291                    .all(|b| b.is_ascii_digit())
292        })
293        .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
294        .collect();
295    logs.sort();
296    let excess = logs.len().saturating_sub(KEEP);
297    for (_, old) in logs.into_iter().take(excess) {
298        let _ = fs::remove_file(old);
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305
306    fn scratch(tag: &str) -> PathBuf {
307        let d = std::env::temp_dir().join(format!("amont-capture-{tag}-{}", std::process::id()));
308        let _ = fs::remove_dir_all(&d);
309        d
310    }
311
312    #[test]
313    fn a_tmp_is_renamed_on_finish() {
314        let dir = scratch("rename");
315        let mut c = Capture::open(Some(dir.clone()), "pre-push-cargo-test");
316        assert!(c.tmp.exists());
317        c.take(b"hello\n");
318        let stored = c.finish();
319        let path = stored.path().unwrap().to_path_buf();
320        assert!(path.exists() && !c.tmp.exists());
321        assert_eq!(fs::read_to_string(path).unwrap(), "hello\n");
322        assert!(stored.note().is_none());
323    }
324
325    #[test]
326    fn no_directory_still_gives_an_excerpt() {
327        let mut c = Capture::open(None, "x");
328        c.take(b"thread 'a' panicked at src/a.rs:1:1:\nboom\n");
329        let stored = c.finish();
330        assert!(stored.note().unwrap().starts_with("log not written:"));
331        assert!(c.acc.finish("-").contains("panicked at"));
332    }
333
334    #[test]
335    fn pruning_keeps_ten_and_never_a_tmp_or_another_check() {
336        let dir = scratch("prune");
337        fs::create_dir_all(&dir).unwrap();
338        for i in 0..15 {
339            fs::write(dir.join(format!("clippy.{}.log", 1000 + i)), "x").unwrap();
340            std::thread::sleep(std::time::Duration::from_millis(5));
341        }
342        fs::write(dir.join("clippy.1.log.tmp"), "x").unwrap();
343        fs::write(dir.join("clippy-extra.5.log"), "x").unwrap();
344        let mut c = Capture::open(Some(dir.clone()), "clippy");
345        c.finish();
346        let names: Vec<String> = fs::read_dir(&dir)
347            .unwrap()
348            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
349            .collect();
350        let clippy = names
351            .iter()
352            .filter(|n| n.starts_with("clippy.") && n.ends_with(".log"))
353            .count();
354        assert_eq!(clippy, KEEP, "{names:?}");
355        assert!(names.iter().any(|n| n == "clippy.1.log.tmp"));
356        assert!(names.iter().any(|n| n == "clippy-extra.5.log"));
357    }
358
359    #[cfg(unix)]
360    #[test]
361    fn the_log_is_private() {
362        use std::os::unix::fs::PermissionsExt;
363        let dir = scratch("mode");
364        let c = Capture::open(Some(dir), "x");
365        let mode = fs::metadata(&c.tmp).unwrap().permissions().mode() & 0o777;
366        assert_eq!(mode, 0o600);
367    }
368
369    #[cfg(feature = "test-hooks")]
370    #[test]
371    fn a_failed_write_keeps_the_excerpt() {
372        let dir = scratch("inject");
373        let mut c = Capture::open_failing_after(Some(dir), "x", Some(10));
374        c.take(b"0123456789abcdef\nthread 'a' panicked at src/a.rs:1:1:\n");
375        let stored = c.finish();
376        assert!(stored.note().unwrap().contains("injected write failure"));
377        assert!(!c.tmp.exists());
378        assert!(c.acc.finish("-").contains("panicked at"));
379    }
380
381    #[test]
382    fn fifty_megabytes_keep_the_accumulator_bounded() {
383        let mut c = Capture::open(None, "x");
384        let chunk: String = (0..1000).map(|i| format!("line {i} ok\n")).collect();
385        let mut fed = 0u64;
386        while fed < 50 * 1024 * 1024 {
387            c.take(chunk.as_bytes());
388            fed += chunk.len() as u64;
389        }
390        assert!(c.acc.held() <= 64 * 1024, "{}", c.acc.held());
391        assert_eq!(c.seen, fed);
392    }
393}