1use std::hash::{BuildHasher, Hasher};
16use std::io::Write;
17use std::path::Path;
18
19use serde::{Deserialize, Serialize};
20
21pub const FILE_NAME: &str = "incidents.jsonl";
23
24const KEEP_LINES: usize = 200;
26
27#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
29pub struct Incident {
30 pub id: String,
31 pub at_ms: u64,
32 pub kind: String,
37 pub what: String,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub cause: Option<String>,
42 #[serde(default)]
44 pub did: Vec<String>,
45 #[serde(default)]
47 pub lost: Vec<String>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub evidence: Option<String>,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub acknowledged_at_ms: Option<u64>,
54}
55
56impl Incident {
57 pub fn new(kind: &str, what: impl Into<String>, log: &str) -> Self {
60 let at_ms = crate::time::now_ms_u64();
61 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#[derive(Debug, Serialize, Deserialize)]
82#[serde(untagged)]
83enum Line {
84 Ack { ack: String, at_ms: u64 },
85 Interrupted { interrupted: u32, restart: String, at_ms: u64 },
88 Incident(Incident),
89}
90
91pub fn append(path: &Path, incident: &Incident) -> std::io::Result<()> {
93 write_line(path, &Line::Incident(incident.clone()))
94}
95
96pub 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
101pub 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
110pub const RESTART_ID_ENV: &str = "AGENTMUX_SRV_RESTART_ID";
113
114fn 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
122pub 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 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 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
164fn 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
180fn iso_utc(ms: u64) -> String {
182 let secs = ms / 1000;
183 let (days, rem) = ((secs / 86_400) as i64, secs % 86_400);
184 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 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 append_interrupted(&path, 3, &restart.id, restart.at_ms - 2_000).unwrap();
235 append(&path, &other).unwrap();
236 append(&path, &restart).unwrap();
237 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 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 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}