Skip to main content

agentmux_common/
record_events.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Events for the record AgentMux keeps on this computer
5//! (docs/specs/SPEC_LONG_RUNNING_ZERO_DEGRADATION_2026_11_16.md ยง6, task #47820): a stall of the host's UI thread
6//! or of srv's runtime, written as one JSON line in a file for its month, `events-YYYY-MM.jsonl`, next to the
7//! record's days. srv reads them back (`backend::record`); the window host, a process of its own, writes the
8//! ones it sees from here, so the writer is in this crate.
9//!
10//! A line is `{"t": ms, "kind": "ui_stall", ...numbers}`: numbers and stable names only, never a title or a path.
11
12use std::io::Write;
13use std::path::{Path, PathBuf};
14use std::sync::Mutex;
15
16const PREFIX: &str = "events-";
17const EXT: &str = "jsonl";
18/// A line longer than this is not written: an event is a few numbers.
19const MAX_LINE_BYTES: usize = 2_048;
20
21/// Where this AgentMux keeps its record: the `record` folder of its channel (of a dev build's own folder). Not
22/// the data folder: an installed AgentMux has one of those per version, and the record must outlast an upgrade.
23pub fn record_dir() -> Option<PathBuf> {
24    crate::data_paths::DataPaths::from_env().map(|p| record_dir_in(&p))
25}
26
27/// [`record_dir`] for the folders in `paths`.
28pub fn record_dir_in(paths: &crate::data_paths::DataPaths) -> PathBuf {
29    paths.instance_dir.join("record")
30}
31
32/// `(year, month)` of a time in ms since the epoch, UTC.
33fn year_month(t_ms: u64) -> (i64, u32) {
34    // Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm).
35    let z = (t_ms / 86_400_000) as i64 + 719_468;
36    let era = z.div_euclid(146_097);
37    let doe = z.rem_euclid(146_097);
38    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
39    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
40    let mp = (5 * doy + 2) / 153;
41    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
42    let year = yoe + era * 400 + i64::from(month <= 2);
43    (year, month)
44}
45
46/// The file for the month of `t_ms`: `events-2026-11.jsonl`.
47pub fn file_name(t_ms: u64) -> String {
48    let (y, m) = year_month(t_ms);
49    format!("{PREFIX}{y:04}-{m:02}.{EXT}")
50}
51
52/// Whether `name` is an events file, and the month it holds as `2026-11`.
53pub fn month_of_file(name: &str) -> Option<&str> {
54    let month = name.strip_prefix(PREFIX)?.strip_suffix(&format!(".{EXT}"))?;
55    let (y, m) = month.split_once('-')?;
56    (y.len() == 4 && m.len() == 2 && y.bytes().all(|b| b.is_ascii_digit()) && m.bytes().all(|b| b.is_ascii_digit())).then_some(month)
57}
58
59/// One process writes its lines whole, one at a time; a line is one `write` in append mode, so two processes (srv
60/// and the window host) do not cut each other's lines.
61static WRITE: Mutex<()> = Mutex::new(());
62
63/// Append an event of `kind` at `t_ms` to `dir`'s file for the month. `fields` is a JSON object of numbers and
64/// short names; `t` and `kind` are added to it. BLOCKING (a file append). Errors are the caller's to log; an event
65/// is never a reason for anything else to fail.
66pub fn append_event(dir: &Path, t_ms: u64, kind: &str, fields: serde_json::Value) -> std::io::Result<()> {
67    let serde_json::Value::Object(mut line) = fields else {
68        return Err(std::io::Error::other("an event's fields are an object"));
69    };
70    line.insert("t".into(), t_ms.into());
71    line.insert("kind".into(), kind.into());
72    let mut text = serde_json::Value::Object(line).to_string();
73    if text.len() >= MAX_LINE_BYTES {
74        return Err(std::io::Error::other("an event is a few numbers"));
75    }
76    text.push('\n');
77    let _guard = WRITE.lock().unwrap_or_else(|e| e.into_inner());
78    std::fs::create_dir_all(dir)?;
79    let mut file = std::fs::OpenOptions::new().create(true).append(true).open(dir.join(file_name(t_ms)))?;
80    file.write_all(text.as_bytes())
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use serde_json::json;
87
88    #[test]
89    fn the_month_is_the_utc_month_of_the_time() {
90        assert_eq!(file_name(0), "events-1970-01.jsonl");
91        assert_eq!(file_name(1_794_830_400_000), "events-2026-11.jsonl");
92        // 2000-02-29 00:00 UTC, and the last millisecond of 2026-12-31.
93        assert_eq!(file_name(951_782_400_000), "events-2000-02.jsonl");
94        assert_eq!(file_name(1_798_761_599_999), "events-2026-12.jsonl");
95        assert_eq!(file_name(1_798_761_600_000), "events-2027-01.jsonl");
96    }
97
98    #[test]
99    fn the_record_is_in_the_channels_folder_so_an_upgrade_keeps_it() {
100        let channel = PathBuf::from("home").join("channels").join("stable");
101        let version = channel.join("versions").join("0.60.35");
102        let paths = crate::data_paths::DataPaths {
103            home_dir: PathBuf::from("home"),
104            instance_dir: channel.clone(),
105            channel: "stable".to_string(),
106            data_dir: version.join("data"),
107            config_dir: channel.join("config"),
108            logs_dir: version.join("logs"),
109            cef_cache_dir: version.join("cef-cache"),
110            agents_dir: channel.join("agents"),
111            instance_runtime_dir: version.join("runtime"),
112            shared_dir: PathBuf::from("home").join("shared"),
113            mode: crate::RuntimeMode::Installed,
114        };
115        let dir = record_dir_in(&paths);
116        assert_eq!(dir, channel.join("record"));
117        assert!(!dir.starts_with(&version));
118    }
119
120    #[test]
121    fn only_an_events_file_is_one() {
122        assert_eq!(month_of_file("events-2026-11.jsonl"), Some("2026-11"));
123        for other in ["2026-11-16.jsonl", "rollup-2026-11.jsonl", "events-2026-1.jsonl", "events-26-11.jsonl", "events-2026-11.txt", "events-abcd-ef.jsonl"] {
124            assert_eq!(month_of_file(other), None, "{other}");
125        }
126    }
127
128    #[test]
129    fn an_event_is_one_line_with_its_time_and_kind() {
130        let tmp = tempfile::tempdir().unwrap();
131        let dir = tmp.path().join("record");
132        append_event(&dir, 1_794_830_400_000, "ui_stall", json!({ "ms": 55_000, "host_mb": 310 })).unwrap();
133        append_event(&dir, 1_794_830_460_000, "srv_stall", json!({ "ms": 5_300 })).unwrap();
134        let text = std::fs::read_to_string(dir.join("events-2026-11.jsonl")).unwrap();
135        let lines: Vec<serde_json::Value> = text.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
136        assert_eq!(lines[0], json!({ "t": 1_794_830_400_000u64, "kind": "ui_stall", "ms": 55_000, "host_mb": 310 }));
137        assert_eq!(lines[1]["kind"], "srv_stall");
138        // What is not an object, or is more than a few numbers, is refused.
139        assert!(append_event(&dir, 1, "x", json!([1])).is_err());
140        assert!(append_event(&dir, 1, "x", json!({ "text": "x".repeat(3_000) })).is_err());
141        assert_eq!(std::fs::read_to_string(dir.join("events-2026-11.jsonl")).unwrap().lines().count(), 2);
142    }
143}