Skip to main content

agentmux_launcher/
logging.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4/// Rotation cap for `agentmux-launcher.log` (SPEC_WIN10_PAGEFILE_OOM_CRASH_
5/// 2026_06_29 P1). This file mirrors the srv subprocess's entire stderr
6/// stream verbatim, forever, with no rotation of its own — left unbounded
7/// it grew to 406 MB across 69 days on a real machine, directly tightening
8/// the page-file ceiling the pagefile-OOM spec is about. 50 MB per file ×
9/// 3 rotated files + the live file ≈ 200 MB worst case, versus unbounded.
10const MAX_LOG_BYTES: u64 = 50 * 1024 * 1024;
11const MAX_ROTATED_FILES: u32 = 3;
12
13/// Append a timestamped line to ~/.agentmux/logs/agentmux-launcher.log.
14/// Best-effort — silently no-ops if the log dir doesn't exist yet.
15pub(crate) fn log(msg: &str) {
16    let log_dir = dirs_fallback_home().join(".agentmux").join("logs");
17    let _ = std::fs::create_dir_all(&log_dir);
18    let path = log_dir.join("agentmux-launcher.log");
19    rotate_if_oversized(&path);
20    if let Ok(mut f) = std::fs::OpenOptions::new()
21        .create(true)
22        .append(true)
23        .open(&path)
24    {
25        use std::io::Write;
26        let secs = agentmux_common::time::now_secs_u64();
27        let _ = writeln!(f, "[{}] v{} {}", secs, env!("CARGO_PKG_VERSION"), msg);
28    }
29}
30
31/// Longest panic message written to the log. Panic payloads are usually one
32/// line, but `unwrap()` on an error can embed a whole `Debug` dump.
33const MAX_PANIC_MSG_CHARS: usize = 600;
34
35/// One log line describing a panic. Kept single-line (the log is read with
36/// `grep`) and bounded, and free of any std panic types so it can be tested.
37fn panic_line(thread: Option<&str>, location: Option<(&str, u32, u32)>, payload: &str) -> String {
38    let mut msg: String = payload
39        .chars()
40        .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
41        .take(MAX_PANIC_MSG_CHARS)
42        .collect();
43    if payload.chars().count() > MAX_PANIC_MSG_CHARS {
44        msg.push_str("...");
45    }
46    let thread = thread.unwrap_or("<unnamed>");
47    match location {
48        Some((file, line, col)) => format!("PANIC thread={thread} at {file}:{line}:{col}: {msg}"),
49        None => format!("PANIC thread={thread}: {msg}"),
50    }
51}
52
53/// Record every panic in `agentmux-launcher.log`, then run whatever hook was
54/// installed before (the default one, which prints to stderr).
55///
56/// The launcher spawns dozens of tokio tasks and threads. A panic in a task
57/// is caught by tokio and the task just ends; the launcher keeps running and
58/// nothing, anywhere, says it happened. The launcher's own stderr goes nowhere
59/// useful, so even a panic that does end the process left no trace in this
60/// log. With this hook either case leaves a line naming the thread and the
61/// source location, which is what is needed to tell how often it happens
62/// before deciding whether the launcher can afford `panic = "abort"`.
63///
64/// Call once, first thing in `main`.
65pub(crate) fn install_panic_hook() {
66    install_panic_hook_with(log);
67}
68
69fn install_panic_hook_with(sink: fn(&str)) {
70    let previous = std::panic::take_hook();
71    std::panic::set_hook(Box::new(move |info| {
72        let payload = info.payload();
73        let text = payload
74            .downcast_ref::<&str>()
75            .copied()
76            .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
77            .unwrap_or("<non-string panic payload>");
78        let location = info.location().map(|l| (l.file(), l.line(), l.column()));
79        let thread = std::thread::current();
80        sink(&panic_line(thread.name(), location, text));
81        previous(info);
82    }));
83}
84
85fn rotated_path(path: &std::path::Path, n: u32) -> std::path::PathBuf {
86    path.with_extension(format!("log.{n}"))
87}
88
89/// Size-based rotation: `agentmux-launcher.log` -> `.log.1` -> `.log.2` ->
90/// `.log.3` (oldest dropped), run once per `log()` call before appending.
91/// A `metadata()` stat per call is cheap relative to the disk write that
92/// follows; simplicity here matters more than shaving a syscall. Best-effort
93/// like `log()` itself — any failure (permissions, concurrent access) just
94/// leaves the current file growing past the cap rather than losing log data
95/// or panicking.
96fn rotate_if_oversized(path: &std::path::Path) {
97    let Ok(meta) = std::fs::metadata(path) else {
98        return;
99    };
100    if meta.len() < MAX_LOG_BYTES {
101        return;
102    }
103    let _ = std::fs::remove_file(rotated_path(path, MAX_ROTATED_FILES));
104    for i in (1..MAX_ROTATED_FILES).rev() {
105        let _ = std::fs::rename(rotated_path(path, i), rotated_path(path, i + 1));
106    }
107    let _ = std::fs::rename(path, rotated_path(path, 1));
108}
109
110/// Home dir without depending on `dirs` for THIS specific lookup.
111/// Kept to avoid a dirs dep cycle from log() — log() is called from
112/// data_dir::resolve_paths via failure paths, and we want it to work
113/// even if `dirs` itself is mid-failure.
114pub(crate) fn dirs_fallback_home() -> std::path::PathBuf {
115    std::env::var("USERPROFILE")
116        .or_else(|_| std::env::var("HOME"))
117        .map(std::path::PathBuf::from)
118        .unwrap_or_else(|_| std::path::PathBuf::from("."))
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124    use tempfile::tempdir;
125
126    #[test]
127    fn rotate_if_oversized_is_a_noop_below_the_cap() {
128        let tmp = tempdir().unwrap();
129        let path = tmp.path().join("agentmux-launcher.log");
130        std::fs::write(&path, vec![b'x'; 1024]).unwrap();
131
132        rotate_if_oversized(&path);
133
134        assert!(path.exists());
135        assert_eq!(std::fs::metadata(&path).unwrap().len(), 1024);
136        assert!(!rotated_path(&path, 1).exists());
137    }
138
139    #[test]
140    fn rotate_if_oversized_rotates_the_live_file_to_dot_1() {
141        let tmp = tempdir().unwrap();
142        let path = tmp.path().join("agentmux-launcher.log");
143        std::fs::write(&path, vec![b'x'; MAX_LOG_BYTES as usize]).unwrap();
144
145        rotate_if_oversized(&path);
146
147        assert!(!path.exists(), "oversized live file should be rotated away");
148        assert!(rotated_path(&path, 1).exists());
149        assert_eq!(
150            std::fs::metadata(rotated_path(&path, 1)).unwrap().len(),
151            MAX_LOG_BYTES
152        );
153    }
154
155    #[test]
156    fn rotate_if_oversized_shifts_the_whole_chain_and_drops_the_oldest() {
157        let tmp = tempdir().unwrap();
158        let path = tmp.path().join("agentmux-launcher.log");
159        std::fs::write(&path, vec![b'x'; MAX_LOG_BYTES as usize]).unwrap();
160        std::fs::write(rotated_path(&path, 1), b"gen1").unwrap();
161        std::fs::write(rotated_path(&path, 2), b"gen2").unwrap();
162        std::fs::write(rotated_path(&path, 3), b"gen3-oldest-should-be-dropped").unwrap();
163
164        rotate_if_oversized(&path);
165
166        assert!(!path.exists());
167        assert_eq!(std::fs::read(rotated_path(&path, 1)).unwrap(), vec![b'x'; MAX_LOG_BYTES as usize]);
168        assert_eq!(std::fs::read(rotated_path(&path, 2)).unwrap(), b"gen1");
169        assert_eq!(std::fs::read(rotated_path(&path, 3)).unwrap(), b"gen2");
170    }
171
172    #[test]
173    fn panic_line_names_thread_and_location() {
174        let line = panic_line(Some("tokio-runtime-worker"), Some(("src/x.rs", 12, 5)), "boom");
175        assert_eq!(line, "PANIC thread=tokio-runtime-worker at src/x.rs:12:5: boom");
176    }
177
178    #[test]
179    fn panic_line_copes_with_a_missing_thread_name_and_location() {
180        assert_eq!(panic_line(None, None, "boom"), "PANIC thread=<unnamed>: boom");
181    }
182
183    #[test]
184    fn panic_line_is_one_bounded_line() {
185        let line = panic_line(Some("t"), None, &format!("a\nb\r\nc{}", "x".repeat(2000)));
186        assert!(!line.contains('\n') && !line.contains('\r'));
187        assert!(line.starts_with("PANIC thread=t: a b  c"));
188        assert!(line.ends_with("..."));
189        assert!(line.chars().count() < "PANIC thread=t: ".len() + MAX_PANIC_MSG_CHARS + 4);
190        // Exactly at the limit is not truncated.
191        let exact = panic_line(None, None, &"y".repeat(MAX_PANIC_MSG_CHARS));
192        assert!(!exact.ends_with("..."));
193    }
194
195    static SEEN: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
196
197    fn collect(line: &str) {
198        SEEN.lock().unwrap().push(line.to_string());
199    }
200
201    #[test]
202    fn the_hook_logs_a_contained_panic_and_keeps_the_previous_hook() {
203        // Another test may panic on purpose while this hook is installed, so
204        // look for our own marker rather than counting lines.
205        let before = std::panic::take_hook();
206        let chained = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
207        let flag = chained.clone();
208        std::panic::set_hook(Box::new(move |_| {
209            flag.store(true, std::sync::atomic::Ordering::SeqCst);
210        }));
211        install_panic_hook_with(collect);
212
213        let r = std::panic::catch_unwind(|| {
214            panic!("hook-test-marker-7f3a");
215        });
216        std::panic::set_hook(before);
217
218        assert!(r.is_err());
219        let seen = SEEN.lock().unwrap();
220        let line = seen.iter().find(|l| l.contains("hook-test-marker-7f3a")).expect("panic was logged");
221        assert!(line.starts_with("PANIC thread="), "{line}");
222        assert!(line.contains("logging.rs:"), "location is recorded: {line}");
223        assert!(chained.load(std::sync::atomic::Ordering::SeqCst), "previous hook still runs");
224    }
225}