Skip to main content

agentmux_common/
incidents.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The incident record: what went wrong and what AgentMux did about it, kept
5//! for the user (docs/specs/SPEC_RECOVERY_NOTICES_AND_TOASTS_2026_10_16.md
6//! §4.1). The host writes the cases it handles (`agentmux-cef`
7//! `commands::incidents`), the launcher the ones only it sees (a restart);
8//! the frontend shows each one the user hasn't closed.
9//!
10//! An append-only JSON-lines file in the instance's data folder: an incident
11//! is one line, closing its notice appends an acknowledgement line. Written
12//! synchronously, since the writers are recovery paths that may be about to
13//! exit; incidents are rare, and each write is one small append.
14
15use std::hash::{BuildHasher, Hasher};
16use std::io::Write;
17use std::path::Path;
18
19use serde::{Deserialize, Serialize};
20
21/// The file's name in the data folder.
22pub const FILE_NAME: &str = "incidents.jsonl";
23
24/// The file keeps about this many lines; past twice that it is cut back.
25const KEEP_LINES: usize = 200;
26
27/// One incident, as the user is told about it.
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
29pub struct Incident {
30    pub id: String,
31    pub at_ms: u64,
32    /// A closed set (spec §4.4): `renderer_crashed`, `renderer_oom`,
33    /// `renderer_hung`, `quit_no_window`, `host_restarted`,
34    /// `host_restarted_safe_mode`, `srv_restarted`, `memory_give_up`,
35    /// `host_give_up`.
36    pub kind: String,
37    /// What happened, in plain words.
38    pub what: String,
39    /// Why, when it is known; never guessed.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub cause: Option<String>,
42    /// What AgentMux did that keeps the user's work: only what this path did.
43    #[serde(default)]
44    pub did: Vec<String>,
45    /// What may not have survived, when this path knows.
46    #[serde(default)]
47    pub lost: Vec<String>,
48    /// Which log has the details, and when, for a bug report.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub evidence: Option<String>,
51    /// Set by `read` from the acknowledgement lines.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub acknowledged_at_ms: Option<u64>,
54}
55
56impl Incident {
57    /// A new incident now; `log` names the log with the details ("host",
58    /// "launcher").
59    pub fn new(kind: &str, what: impl Into<String>, log: &str) -> Self {
60        let at_ms = crate::time::now_ms_u64();
61        // Unique enough for a handful of records: the time, and a hash seeded
62        // per process at random.
63        let mut h = std::collections::hash_map::RandomState::new().build_hasher();
64        h.write_u64(at_ms);
65        h.write_u32(std::process::id());
66        Incident {
67            id: format!("{at_ms}-{:08x}", h.finish() as u32),
68            at_ms,
69            kind: kind.to_string(),
70            what: what.into(),
71            cause: None,
72            did: Vec::new(),
73            lost: Vec::new(),
74            evidence: Some(format!("{log} log, {}", iso_utc(at_ms))),
75            acknowledged_at_ms: None,
76        }
77    }
78}
79
80/// One line of the file.
81#[derive(Debug, Serialize, Deserialize)]
82#[serde(untagged)]
83enum Line {
84    Ack { ack: String, at_ms: u64 },
85    /// srv's start-up pass found `interrupted` agents whose process was running
86    /// when the previous srv died, as the launcher's respawn `restart` started it.
87    Interrupted { interrupted: u32, restart: String, at_ms: u64 },
88    Incident(Incident),
89}
90
91/// Append `incident` to the file at `path`.
92pub fn append(path: &Path, incident: &Incident) -> std::io::Result<()> {
93    write_line(path, &Line::Incident(incident.clone()))
94}
95
96/// Append the acknowledgement of incident `id`.
97pub fn append_ack(path: &Path, id: &str, at_ms: u64) -> std::io::Result<()> {
98    write_line(path, &Line::Ack { ack: id.to_string(), at_ms })
99}
100
101/// Append what srv found at start-up: `agents` agent processes were running
102/// when the previous srv died (`session_recovery::scan_orphans`). `restart` is
103/// the id of the `srv_restarted` incident whose respawn started this srv (the
104/// launcher passes it in `RESTART_ID_ENV`; a cold start has none and writes
105/// nothing). The two are written by different processes, in either order.
106pub fn append_interrupted(path: &Path, agents: u32, restart: &str, at_ms: u64) -> std::io::Result<()> {
107    write_line(path, &Line::Interrupted { interrupted: agents, restart: restart.to_string(), at_ms })
108}
109
110/// The environment variable the launcher starts a respawned srv with: the id
111/// of the incident it records for the restart.
112pub const RESTART_ID_ENV: &str = "AGENTMUX_SRV_RESTART_ID";
113
114/// What the notice says of `agents` agents stopped with srv.
115fn interrupted_did(agents: u32) -> String {
116    match agents {
117        1 => "1 running agent was stopped with the service; it resumes from its saved conversation when you open it.".to_string(),
118        n => format!("{n} running agents were stopped with the service; each resumes from its saved conversation when you open it."),
119    }
120}
121
122/// The newest `max` incidents at `path`, newest first, each with its
123/// acknowledgement. A missing file is no incidents.
124pub fn read(path: &Path, max: usize) -> Vec<Incident> {
125    let Ok(text) = std::fs::read_to_string(path) else {
126        return Vec::new();
127    };
128    let mut incidents: Vec<Incident> = Vec::new();
129    let mut acks: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
130    let mut interrupted: Vec<(u32, String)> = Vec::new();
131    // A torn last line (a crash mid-append) costs only itself.
132    for line in text.lines().filter_map(|l| serde_json::from_str::<Line>(l).ok()) {
133        match line {
134            Line::Ack { ack, at_ms } => {
135                acks.insert(ack, at_ms);
136            }
137            Line::Interrupted { interrupted: n, restart, .. } => interrupted.push((n, restart)),
138            Line::Incident(i) => incidents.push(i),
139        }
140    }
141    for i in &mut incidents {
142        i.acknowledged_at_ms = acks.get(&i.id).copied();
143    }
144    // srv's count belongs to the restart that started that srv, by id.
145    for (n, restart) in interrupted {
146        if let Some(i) = incidents.iter_mut().find(|i| i.kind == "srv_restarted" && i.id == restart) {
147            i.did.retain(|d| !d.contains("running agent"));
148            i.did.push(interrupted_did(n));
149            i.lost = vec![if n == 1 { "Whatever it had under way in its current turn." } else { "Whatever each had under way in its current turn." }.to_string()];
150        }
151    }
152    incidents.reverse();
153    incidents.truncate(max);
154    incidents
155}
156
157fn write_line(path: &Path, line: &Line) -> std::io::Result<()> {
158    let json = serde_json::to_string(line).map_err(std::io::Error::other)?;
159    std::fs::OpenOptions::new().create(true).append(true).open(path).and_then(|mut f| writeln!(f, "{json}"))?;
160    compact(path);
161    Ok(())
162}
163
164/// Keep the last `KEEP_LINES` lines once the file is past twice that.
165fn compact(path: &Path) {
166    let Ok(text) = std::fs::read_to_string(path) else {
167        return;
168    };
169    let lines: Vec<&str> = text.lines().collect();
170    if lines.len() <= KEEP_LINES * 2 {
171        return;
172    }
173    let kept = lines[lines.len() - KEEP_LINES..].join("\n") + "\n";
174    let tmp = path.with_extension("jsonl.tmp");
175    if std::fs::write(&tmp, kept).is_ok() {
176        let _ = std::fs::rename(&tmp, path);
177    }
178}
179
180/// `ms` since the epoch as `YYYY-MM-DDTHH:MM:SSZ`.
181fn iso_utc(ms: u64) -> String {
182    let secs = ms / 1000;
183    let (days, rem) = ((secs / 86_400) as i64, secs % 86_400);
184    // Days to a civil date (Howard Hinnant's algorithm).
185    let z = days + 719_468;
186    let era = z.div_euclid(146_097);
187    let doe = z - era * 146_097;
188    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
189    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
190    let mp = (5 * doy + 2) / 153;
191    let day = doy - (153 * mp + 2) / 5 + 1;
192    let month = if mp < 10 { mp + 3 } else { mp - 9 };
193    let year = yoe + era * 400 + i64::from(month <= 2);
194    format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60)
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn incidents_read_back_newest_first_with_their_acknowledgements() {
203        let dir = tempfile::tempdir().unwrap();
204        let path = dir.path().join(FILE_NAME);
205        let mut a = Incident::new("renderer_crashed", "A window crashed and was reloaded", "host");
206        a.did = vec!["Every agent kept running".into()];
207        let b = Incident::new("host_restarted", "AgentMux restarted", "launcher");
208        append(&path, &a).unwrap();
209        append(&path, &b).unwrap();
210        append_ack(&path, &a.id, 99).unwrap();
211        // A torn last line costs only itself.
212        std::fs::OpenOptions::new().append(true).open(&path).unwrap().write_all(b"{\"id\":\"torn").unwrap();
213        let got = read(&path, 50);
214        assert_eq!(got.iter().map(|i| i.kind.as_str()).collect::<Vec<_>>(), vec!["host_restarted", "renderer_crashed"]);
215        assert_eq!(got[1].acknowledged_at_ms, Some(99));
216        assert_eq!(got[0].acknowledged_at_ms, None);
217        assert_eq!(got[1].did, vec!["Every agent kept running".to_string()]);
218        assert_ne!(a.id, b.id);
219        assert!(b.evidence.as_deref().unwrap().starts_with("launcher log, "));
220        assert!(read(&dir.path().join("none.jsonl"), 50).is_empty());
221    }
222
223    #[test]
224    fn srvs_count_lands_on_the_restart_that_started_that_srv_in_either_order() {
225        let dir = tempfile::tempdir().unwrap();
226        let path = dir.path().join(FILE_NAME);
227        let mut restart = Incident::new("srv_restarted", "AgentMux's background service restarted", "launcher");
228        restart.did = vec!["AgentMux started the service again.".into()];
229        restart.lost = vec!["An agent's turn that was under way may have been cut off.".into()];
230        let mut later = restart.clone();
231        later.id = "later-restart".into();
232        let other = Incident::new("host_restarted", "AgentMux restarted its window", "launcher");
233        // srv writes its count first (it finishes starting before the launcher records), then the launcher.
234        append_interrupted(&path, 3, &restart.id, restart.at_ms - 2_000).unwrap();
235        append(&path, &other).unwrap();
236        append(&path, &restart).unwrap();
237        // A second restart a minute later: the first srv's count is not its.
238        append(&path, &later).unwrap();
239        let got = read(&path, 10);
240        let r = got.iter().find(|i| i.id == restart.id).unwrap();
241        assert_eq!(r.did.last().unwrap(), "3 running agents were stopped with the service; each resumes from its saved conversation when you open it.");
242        assert_eq!(r.lost, vec!["Whatever each had under way in its current turn.".to_string()]);
243        let l = got.iter().find(|i| i.id == "later-restart").unwrap();
244        assert_eq!(l.did, vec!["AgentMux started the service again.".to_string()], "the neighbouring restart gets none");
245        let h = got.iter().find(|i| i.kind == "host_restarted").unwrap();
246        assert!(h.did.is_empty() && h.lost.is_empty());
247        // The other order, one agent; a count for an id that isn't there lands nowhere.
248        let path2 = dir.path().join("two.jsonl");
249        append(&path2, &restart).unwrap();
250        append_interrupted(&path2, 1, &restart.id, restart.at_ms + 5_000).unwrap();
251        append_interrupted(&path2, 9, "no-such-restart", restart.at_ms + 6_000).unwrap();
252        let r = read(&path2, 10).remove(0);
253        assert_eq!(r.did.iter().filter(|d| d.contains("running agent")).count(), 1);
254        assert!(r.did.last().unwrap().starts_with("1 running agent was stopped"));
255        assert_eq!(r.lost, vec!["Whatever it had under way in its current turn.".to_string()]);
256        // No count: the launcher's own words stand.
257        let path3 = dir.path().join("three.jsonl");
258        append(&path3, &restart).unwrap();
259        assert_eq!(read(&path3, 10)[0].lost, vec!["An agent's turn that was under way may have been cut off.".to_string()]);
260    }
261
262    #[test]
263    fn the_file_is_cut_back_to_its_last_lines() {
264        let dir = tempfile::tempdir().unwrap();
265        let path = dir.path().join(FILE_NAME);
266        for n in 0..(KEEP_LINES * 2 + 1) {
267            append(&path, &Incident::new("renderer_crashed", format!("n{n}"), "host")).unwrap();
268        }
269        assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), KEEP_LINES);
270        assert_eq!(read(&path, 1).first().map(|i| i.what.as_str()), Some(format!("n{}", KEEP_LINES * 2).as_str()));
271    }
272
273    #[test]
274    fn times_are_written_as_utc() {
275        assert_eq!(iso_utc(0), "1970-01-01T00:00:00Z");
276        assert_eq!(iso_utc(1_792_186_299_395), "2026-10-16T21:31:39Z");
277        assert_eq!(iso_utc(951_782_400_000), "2000-02-29T00:00:00Z");
278    }
279}