Skip to main content

agentmux_srv_core/backend/
record.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The record: AgentMux's own size over weeks, kept on this computer
5//! (docs/specs/SPEC_LONG_RUNNING_ZERO_DEGRADATION_2026_11_16.md ยง6, task #47820 phase 1).
6//!
7//! A leak that takes weeks to show can only be found from a record kept that
8//! long, and Tower's memory ledger (`tower::memory_ledger`) forgets after an
9//! hour and a restart. Every five minutes the sample Tower already takes for
10//! the ledger is also written here as one JSON line in a file for its day, with
11//! the machine's totals, AgentMux's parts and its largest rows. Raw days are
12//! kept for [`KEEP_DAYS`], oldest first out, and the whole record has a size
13//! budget ([`MAX_BYTES`]). Each finished hour is also folded into one rollup
14//! line (min, median, p95 and max of each figure) in a file for its month,
15//! kept for a year ([`ROLLUP_KEEP_DAYS`]) within its own budget
16//! ([`ROLLUP_MAX_BYTES`]): slow growth over months is read from those.
17//!
18//! Nothing leaves the computer, and a line holds numbers and stable keys only
19//! (`core`, `agent:<block>`, `np:claude.exe`, `renderer:window:<hash>`): no
20//! text, titles or paths. A renderer's own key is made of its window's or
21//! page's name, so a line keeps its kind and a hash of it instead.
22
23use std::path::{Path, PathBuf};
24use std::sync::Mutex;
25
26use serde::{Deserialize, Serialize};
27
28use crate::backend::rpc_types::{TowerMemory, TowerSnapshot};
29
30/// The gap between lines.
31pub const EVERY_MS: u64 = 5 * 60_000;
32/// How much early a sample still counts as the next line: a sample that ran long, or one Tower served from its
33/// 900 ms cache, must not make the following one look too soon and leave a ten-minute gap.
34const JITTER_MS: u64 = 30_000;
35const HOUR_MS: u64 = 3_600_000;
36/// Raw days kept.
37pub const KEEP_DAYS: i64 = 14;
38/// The record's own budget: past it, the oldest days go first (never today's).
39pub const MAX_BYTES: u64 = 28 * 1024 * 1024;
40/// Hourly rollups kept: a year, and a month's file goes whole.
41pub const ROLLUP_KEEP_DAYS: i64 = 366;
42/// The rollups' own budget (a year is about 10 MB), so the record as a whole stays under 40 MB.
43pub const ROLLUP_MAX_BYTES: u64 = 12 * 1024 * 1024;
44/// The rows an hour's rollup names, by their largest figure.
45const ROLLUP_ROWS: usize = 6;
46/// The windows an hour's rollup names, by their largest heap.
47const ROLLUP_PAGES: usize = 3;
48/// Windows a line names; a page that has not reported for this long has closed.
49const MAX_PAGES: usize = 8;
50const PAGE_FRESH_MS: u64 = 3 * EVERY_MS;
51const ROLLUP_PREFIX: &str = "rollup-";
52const MONTH_FORMAT: &str = "%Y-%m";
53/// The largest rows one line names; a runaway of differently named processes cannot grow a line.
54const MAX_ROWS: usize = 40;
55const DAY_FORMAT: &str = "%Y-%m-%d";
56const EXT: &str = "jsonl";
57
58/// The machine's totals at the time of a sample.
59#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
60pub struct MachineLine {
61    /// Fraction of one core, all processes; absent on a first sample.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub cpu: Option<f64>,
64    /// All processes' private memory, bytes.
65    pub mem: u64,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub mem_total: Option<u64>,
68    pub procs: u32,
69    /// Free and total bytes of the drive that holds this record.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub disk: Option<(u64, u64)>,
72}
73
74/// One of AgentMux's four parts, or one of its largest rows.
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76pub struct PartLine {
77    /// `core`, `panes`, `agents`, `not_placed`; a row's stable key.
78    pub k: String,
79    pub mem: u64,
80    pub n: u32,
81}
82
83/// AgentMux's own processes at the time of a sample.
84#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
85pub struct AgentMuxLine {
86    pub total: u64,
87    pub procs: u32,
88    /// Processes whose memory the OS would not give: not in `total`.
89    pub unreadable: u32,
90    pub parts: Vec<PartLine>,
91    /// Largest first, at most [`MAX_ROWS`].
92    pub rows: Vec<PartLine>,
93}
94
95/// What one window's page held when it last reported (`record.page`, every five minutes): numbers and the
96/// window's own label (`main`, `window-3`), never a title or a path.
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98pub struct PageLine {
99    /// The window's label.
100    pub w: String,
101    /// The JS heap in use and its limit, MB; absent where the engine does not say.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub heap: Option<u32>,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub heap_limit: Option<u32>,
106    /// Elements in the page.
107    pub dom: u32,
108    /// Agent panes mounted, their rows in all and in the largest, and how many have a find bar open.
109    pub panes: u32,
110    pub rows: u32,
111    pub max_rows: u32,
112    pub searches: u32,
113    /// What holds a recycle back, as a count.
114    pub blocked: u32,
115    /// Minutes since the page loaded.
116    pub up_min: u32,
117}
118
119fn pages_store() -> &'static Mutex<std::collections::BTreeMap<String, (u64, PageLine)>> {
120    static PAGES: Mutex<std::collections::BTreeMap<String, (u64, PageLine)>> = Mutex::new(std::collections::BTreeMap::new());
121    &PAGES
122}
123
124/// A window's page reported: kept until it reports again, and written into the next line of the record.
125/// A label is cut to what an id holds; a window that reports more than [`MAX_PAGES`] windows' worth is ignored.
126pub fn note_page(mut page: PageLine, now_ms: u64) {
127    page.w = page.w.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')).take(40).collect();
128    if page.w.is_empty() {
129        return;
130    }
131    let mut pages = pages_store().lock().unwrap_or_else(|e| e.into_inner());
132    pages.retain(|_, (t, _)| now_ms.saturating_sub(*t) <= PAGE_FRESH_MS);
133    if pages.len() < MAX_PAGES || pages.contains_key(&page.w) {
134        pages.insert(page.w.clone(), (now_ms, page));
135    }
136}
137
138/// The pages that reported in the last [`PAGE_FRESH_MS`], by label.
139pub fn pages_at(now_ms: u64) -> Vec<PageLine> {
140    let pages = pages_store().lock().unwrap_or_else(|e| e.into_inner());
141    pages.values().filter(|(t, _)| now_ms.saturating_sub(*t) <= PAGE_FRESH_MS).map(|(_, p)| p.clone()).collect()
142}
143
144/// One line of a day's file.
145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
146pub struct Sample {
147    /// When it was taken, ms since the epoch.
148    pub t: u64,
149    /// The version of srv that wrote it.
150    pub v: String,
151    /// Seconds srv had been running: the age a growth is read against.
152    pub up_s: u64,
153    pub os: String,
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub machine: Option<MachineLine>,
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub am: Option<AgentMuxLine>,
158    /// The windows' pages, as they last reported.
159    #[serde(default, skip_serializing_if = "Vec::is_empty")]
160    pub pages: Vec<PageLine>,
161}
162
163fn part_key(part: &impl Serialize) -> String {
164    serde_json::to_value(part).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default()
165}
166
167/// FNV-1a: the same hash on every run and platform (`DefaultHasher` makes no such promise).
168fn fnv(s: &str) -> u32 {
169    s.bytes().fold(0x811c_9dc5, |h, b| (h ^ b as u32).wrapping_mul(0x0100_0193))
170}
171
172/// A row's key as the record keeps it. A renderer's key is the slug of what it serves (a workspace's name, a page's
173/// host), so it is cut to its kind and a hash of itself: the same figure can be followed from line to line, and
174/// no name is written.
175fn persisted_key(key: &str) -> String {
176    let Some(rest) = key.strip_prefix("renderer:") else { return key.to_string() };
177    // Already cut (a line this version wrote): `<kind>:<8 hex>`.
178    if let Some((kind, hash)) = rest.split_once(':') {
179        if ["window", "browser", "pool", "other"].contains(&kind) && hash.len() == 8 && hash.bytes().all(|b| b.is_ascii_hexdigit()) {
180            return key.to_string();
181        }
182    }
183    let kind = if rest.contains("pool-window") {
184        "pool"
185    } else if rest.contains("browser-pane") {
186        "browser"
187    } else if rest.contains("window") {
188        "window"
189    } else {
190        "other"
191    };
192    format!("renderer:{kind}:{:08x}", fnv(rest))
193}
194
195fn agentmux_line(m: &TowerMemory) -> AgentMuxLine {
196    let parts = m.parts.iter().map(|p| PartLine { k: part_key(&p.part), mem: p.mem, n: p.processes }).collect();
197    let mut rows: Vec<PartLine> =
198        m.parts.iter().flat_map(|p| p.rows.iter()).map(|r| PartLine { k: persisted_key(&r.key), mem: r.mem, n: r.processes }).collect();
199    rows.sort_by(|a, b| b.mem.cmp(&a.mem).then_with(|| a.k.cmp(&b.k)));
200    rows.truncate(MAX_ROWS);
201    AgentMuxLine { total: m.total, procs: m.processes, unreadable: m.unreadable, parts, rows }
202}
203
204/// A snapshot as one line. `disk` is the record's drive; `up_s` how long srv has run.
205pub fn compact(snap: &TowerSnapshot, version: &str, up_s: u64, disk: Option<(u64, u64)>) -> Sample {
206    Sample {
207        t: snap.ts_ms,
208        v: version.to_string(),
209        up_s,
210        os: snap.os.clone(),
211        machine: snap.machine.as_ref().map(|m| MachineLine {
212            cpu: m.cpu,
213            mem: m.mem,
214            mem_total: m.mem_total,
215            procs: m.processes,
216            disk,
217        }),
218        am: snap.memory.as_ref().map(agentmux_line),
219        pages: Vec::new(),
220    }
221}
222
223/// `2026-11-16` for a time in ms since the epoch (UTC).
224pub fn day_of(t_ms: u64) -> String {
225    chrono::DateTime::from_timestamp_millis(t_ms as i64)
226        .map(|d| d.format(DAY_FORMAT).to_string())
227        .unwrap_or_else(|| "1970-01-01".to_string())
228}
229
230fn file_name(day: &str) -> String {
231    format!("{day}.{EXT}")
232}
233
234fn day_from_file(name: &str) -> Option<chrono::NaiveDate> {
235    let day = name.strip_suffix(&format!(".{EXT}"))?;
236    chrono::NaiveDate::parse_from_str(day, DAY_FORMAT).ok()
237}
238
239/// The day files to delete, given what is on disk as `(file name, bytes)`: those older than [`KEEP_DAYS`] before
240/// `today`, then the oldest of what is left while the total is over `max_bytes`. Today's file is never listed.
241pub fn files_to_remove(files: &[(String, u64)], today: &str, keep_days: i64, max_bytes: u64) -> Vec<String> {
242    let Ok(today_date) = chrono::NaiveDate::parse_from_str(today, DAY_FORMAT) else { return Vec::new() };
243    let mut dated: Vec<(chrono::NaiveDate, &String, u64)> =
244        files.iter().filter_map(|(name, size)| day_from_file(name).map(|d| (d, name, *size))).collect();
245    dated.sort_by_key(|(d, _, _)| *d);
246    let mut remove = Vec::new();
247    let mut total: u64 = dated.iter().map(|(_, _, s)| *s).sum();
248    for (date, name, size) in &dated {
249        if *date == today_date {
250            continue;
251        }
252        let too_old = (today_date - *date).num_days() > keep_days;
253        if too_old || total > max_bytes {
254            remove.push((*name).clone());
255            total = total.saturating_sub(*size);
256        }
257    }
258    remove
259}
260
261/// min, median, p95 and max of a figure over an hour.
262#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
263pub struct Stat(pub u64, pub u64, pub u64, pub u64);
264
265/// One finished hour of lines folded into one.
266#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
267pub struct Rollup {
268    /// The hour's start, ms since the epoch.
269    pub h: u64,
270    /// Lines in the hour.
271    pub n: u32,
272    /// The version and the uptime (seconds) of the hour's last line.
273    pub v: String,
274    pub up_s: u64,
275    /// Times srv started again inside the hour (its uptime went back).
276    pub restarts: u32,
277    /// When the hour's last line was taken (0 in a rollup from before this was written).
278    #[serde(default)]
279    pub last_t: u64,
280    /// All processes' CPU, thousandths of a core.
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub cpu: Option<Stat>,
283    #[serde(default, skip_serializing_if = "Option::is_none")]
284    pub mem: Option<Stat>,
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub disk_free: Option<Stat>,
287    /// AgentMux's total.
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub am: Option<Stat>,
290    pub parts: Vec<(String, Stat)>,
291    /// The [`ROLLUP_ROWS`] rows with the largest peak. A row missing from a line counts as 0 there.
292    pub rows: Vec<(String, Stat)>,
293    /// The [`ROLLUP_PAGES`] windows with the largest heap peak, over the lines that named them.
294    #[serde(default, skip_serializing_if = "Vec::is_empty")]
295    pub pages: Vec<PageRoll>,
296}
297
298/// One window's page over an hour: JS heap (MB), elements and mounted rows.
299#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
300pub struct PageRoll {
301    pub w: String,
302    #[serde(default, skip_serializing_if = "Option::is_none")]
303    pub heap: Option<Stat>,
304    pub dom: Stat,
305    pub rows: Stat,
306}
307
308fn stat(mut v: Vec<u64>) -> Option<Stat> {
309    if v.is_empty() {
310        return None;
311    }
312    v.sort_unstable();
313    let at = |p: f64| v[((p * v.len() as f64).ceil() as usize).clamp(1, v.len()) - 1];
314    Some(Stat(v[0], at(0.5), at(0.95), v[v.len() - 1]))
315}
316
317/// Each key's figure over the lines, by key, in the order first seen; a line without the key gives 0.
318fn series(samples: &[Sample], pick: impl Fn(&AgentMuxLine) -> &[PartLine]) -> Vec<(String, Vec<u64>)> {
319    let mut out: Vec<(String, Vec<u64>)> = Vec::new();
320    for (i, s) in samples.iter().enumerate() {
321        for row in s.am.as_ref().map(&pick).unwrap_or_default() {
322            // A line an older version wrote still has a renderer's name in its key.
323            let key = persisted_key(&row.k);
324            let at = match out.iter().position(|(k, _)| *k == key) {
325                Some(at) => at,
326                None => {
327                    out.push((key, vec![0; samples.len()]));
328                    out.len() - 1
329                }
330            };
331            out[at].1[i] = out[at].1[i].max(row.mem);
332        }
333    }
334    out
335}
336
337fn stats_of(series: Vec<(String, Vec<u64>)>) -> Vec<(String, Stat)> {
338    series.into_iter().filter_map(|(k, v)| stat(v).map(|s| (k, s))).collect()
339}
340
341/// The hour starting at `hour` as one line, from its lines (in time order). None for no lines.
342pub fn rollup(hour: u64, samples: &[Sample]) -> Option<Rollup> {
343    let last = samples.last()?;
344    let machine = || samples.iter().filter_map(|s| s.machine.as_ref());
345    let mut rows = stats_of(series(samples, |a| &a.rows));
346    rows.sort_by(|a, b| b.1 .3.cmp(&a.1 .3).then_with(|| a.0.cmp(&b.0)));
347    rows.truncate(ROLLUP_ROWS);
348    Some(Rollup {
349        last_t: last.t,
350        pages: page_rolls(samples),
351        h: hour,
352        n: samples.len() as u32,
353        v: last.v.clone(),
354        up_s: last.up_s,
355        restarts: samples.windows(2).filter(|w| w[1].up_s < w[0].up_s).count() as u32,
356        cpu: stat(machine().filter_map(|m| m.cpu).map(|c| (c * 1000.0).round() as u64).collect()),
357        mem: stat(machine().map(|m| m.mem).collect()),
358        disk_free: stat(machine().filter_map(|m| m.disk).map(|d| d.0).collect()),
359        am: stat(samples.iter().filter_map(|s| s.am.as_ref()).map(|a| a.total).collect()),
360        parts: stats_of(series(samples, |a| &a.parts)),
361        rows,
362    })
363}
364
365/// Each window's page over the hour, the [`ROLLUP_PAGES`] with the largest heap (then elements) first.
366fn page_rolls(samples: &[Sample]) -> Vec<PageRoll> {
367    let mut labels: Vec<&str> = samples.iter().flat_map(|s| s.pages.iter().map(|p| p.w.as_str())).collect();
368    labels.sort_unstable();
369    labels.dedup();
370    let mut out: Vec<PageRoll> = labels
371        .into_iter()
372        .filter_map(|w| {
373            let seen = || samples.iter().flat_map(|s| s.pages.iter()).filter(move |p| p.w == w);
374            Some(PageRoll {
375                w: w.to_string(),
376                heap: stat(seen().filter_map(|p| p.heap).map(u64::from).collect()),
377                dom: stat(seen().map(|p| u64::from(p.dom)).collect())?,
378                rows: stat(seen().map(|p| u64::from(p.rows)).collect())?,
379            })
380        })
381        .collect();
382    let peak = |p: &PageRoll| (p.heap.map_or(0, |h| h.3), p.dom.3);
383    out.sort_by(|a, b| peak(b).cmp(&peak(a)).then_with(|| a.w.cmp(&b.w)));
384    out.truncate(ROLLUP_PAGES);
385    out
386}
387
388fn rollup_file_name(hour: u64) -> String {
389    let month = chrono::DateTime::from_timestamp_millis(hour as i64).map(|d| d.format(MONTH_FORMAT).to_string());
390    format!("{ROLLUP_PREFIX}{}.{EXT}", month.unwrap_or_else(|| "1970-01".to_string()))
391}
392
393fn month_from_file(name: &str) -> Option<chrono::NaiveDate> {
394    let month = name.strip_prefix(ROLLUP_PREFIX)?.strip_suffix(&format!(".{EXT}"))?;
395    chrono::NaiveDate::parse_from_str(&format!("{month}-01"), "%Y-%m-%d").ok()
396}
397
398/// The rollup files to delete: a month that ended more than `keep_days` before `today`, then the oldest of what is
399/// left while the total is over `max_bytes`. The month of `today` is never listed.
400pub fn rollups_to_remove(files: &[(String, u64)], today: &str, keep_days: i64, max_bytes: u64) -> Vec<String> {
401    let Ok(today_date) = chrono::NaiveDate::parse_from_str(today, DAY_FORMAT) else { return Vec::new() };
402    let mut months: Vec<(chrono::NaiveDate, &String, u64)> =
403        files.iter().filter_map(|(name, size)| month_from_file(name).map(|d| (d, name, *size))).collect();
404    months.sort_by_key(|(d, _, _)| *d);
405    let mut total: u64 = months.iter().map(|(_, _, s)| *s).sum();
406    let mut remove = Vec::new();
407    for (start, name, size) in &months {
408        let end = start.checked_add_months(chrono::Months::new(1)).unwrap_or(*start);
409        if end > today_date {
410            continue;
411        }
412        if (today_date - end).num_days() > keep_days || total > max_bytes {
413            remove.push((*name).clone());
414            total = total.saturating_sub(*size);
415        }
416    }
417    remove
418}
419
420/// The hour of the last rollup written, from the newest month's file.
421fn last_rollup_hour(dir: &Path) -> Option<u64> {
422    let mut names: Vec<String> = std::fs::read_dir(dir)
423        .ok()?
424        .flatten()
425        .filter_map(|e| e.file_name().to_str().map(str::to_string))
426        .filter(|n| month_from_file(n).is_some())
427        .collect();
428    names.sort();
429    // Newest month first, until one has a whole line: a month whose first append failed is empty.
430    names.iter().rev().find_map(|name| {
431        let text = std::fs::read_to_string(dir.join(name)).ok()?;
432        text.lines().rev().find_map(|l| serde_json::from_str::<Rollup>(l).ok()).map(|r| r.h)
433    })
434}
435
436/// The raw lines of the days from `from_day` on, in time order.
437fn raw_since(dir: &Path, from_day: Option<&str>) -> Vec<Sample> {
438    let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
439    let from = from_day.and_then(|d| chrono::NaiveDate::parse_from_str(d, DAY_FORMAT).ok());
440    let mut days: Vec<(chrono::NaiveDate, PathBuf)> = entries
441        .flatten()
442        .filter_map(|e| Some((day_from_file(e.file_name().to_str()?)?, e.path())))
443        .filter(|(d, _)| from.is_none_or(|f| *d >= f))
444        .collect();
445    days.sort();
446    let mut out: Vec<Sample> = Vec::new();
447    for (_, path) in days {
448        let Ok(text) = std::fs::read_to_string(&path) else { continue };
449        out.extend(text.lines().filter_map(|l| serde_json::from_str::<Sample>(l).ok()));
450    }
451    out.sort_by_key(|s| s.t);
452    out
453}
454
455/// Fold every finished hour (before the one `now_ms` is in) that has no rollup yet into one, oldest first.
456fn roll_up(dir: &Path, now_ms: u64) {
457    use std::io::Write;
458    let current = now_ms / HOUR_MS * HOUR_MS;
459    let last = last_rollup_hour(dir);
460    let from_day = last.map(|h| day_of(h + HOUR_MS));
461    let mut hours: std::collections::BTreeMap<u64, Vec<Sample>> = std::collections::BTreeMap::new();
462    for s in raw_since(dir, from_day.as_deref()) {
463        let h = s.t / HOUR_MS * HOUR_MS;
464        if h < current && last.is_none_or(|l| h > l) {
465            hours.entry(h).or_default().push(s);
466        }
467    }
468    for (hour, samples) in hours {
469        let Some(line) = rollup(hour, &samples).and_then(|r| serde_json::to_string(&r).ok()) else { continue };
470        let written = std::fs::OpenOptions::new()
471            .create(true)
472            .append(true)
473            .open(dir.join(rollup_file_name(hour)))
474            .and_then(|mut f| f.write_all(format!("{line}\n").as_bytes()));
475        if let Err(e) = written {
476            tracing::warn!(error = %e, "[record] an hour could not be rolled up");
477            return;
478        }
479    }
480}
481
482struct Gate {
483    last_t: Option<u64>,
484    /// The hour rolled up last: once an hour is enough, and once at the first line.
485    rolled_hour: Option<u64>,
486    /// The day pruned last: once a day is enough, and once at the first line.
487    pruned_day: Option<String>,
488}
489
490/// Where the lines go, and when.
491pub struct Record {
492    dir: PathBuf,
493    version: String,
494    gate: Mutex<Gate>,
495    /// When this process started, by the wall clock: the uptime of a line is read from the same clock as its time,
496    /// so a suspend (which stops a monotonic clock) is part of the uptime and is not mistaken for a restart.
497    started_ms: u64,
498}
499
500impl Record {
501    pub fn new(dir: PathBuf, version: &str) -> Self {
502        Self {
503            dir,
504            version: version.to_string(),
505            gate: Mutex::new(Gate { last_t: None, rolled_hour: None, pruned_day: None }),
506            started_ms: agentmux_common::time::now_ms_u64(),
507        }
508    }
509
510    /// This is the process's record, in `dir` (the channel's `record` folder). Set once.
511    pub fn global(dir: impl FnOnce() -> Option<PathBuf>, version: &str) -> Option<&'static Record> {
512        static GLOBAL: std::sync::OnceLock<Option<Record>> = std::sync::OnceLock::new();
513        GLOBAL.get_or_init(|| dir().map(|d| Record::new(d, version))).as_ref()
514    }
515
516    /// Offer a sample Tower took: written when [`EVERY_MS`] (less [`JITTER_MS`]) have passed since the last line,
517    /// and the hours finished since the last rollup are folded when a new hour begins. BLOCKING (a file
518    /// append); call it where the sample is taken, off the async workers. A failure is logged and never
519    /// returned: the record is never a reason for a sample to fail. What comes back is what the rules found,
520    /// when this line began a new hour and they looked ([`super::record_flags::look`]).
521    pub fn note(&self, snap: &TowerSnapshot) -> Option<super::record_flags::Looked> {
522        if snap.memory.is_none() && snap.machine.is_none() {
523            return None;
524        }
525        {
526            let mut gate = self.gate.lock().unwrap_or_else(|e| e.into_inner());
527            if gate.last_t.is_some_and(|last| snap.ts_ms.saturating_sub(last) < EVERY_MS - JITTER_MS) {
528                return None;
529            }
530            gate.last_t = Some(snap.ts_ms);
531        }
532        let disk = agentmux_common::disk_space::volume_free_total_bytes(&self.dir_for_disk());
533        let mut sample = compact(snap, &self.version, snap.ts_ms.saturating_sub(self.started_ms) / 1000, disk);
534        sample.pages = pages_at(snap.ts_ms);
535        if let Err(e) = self.append(&sample) {
536            tracing::warn!(error = %e, "[record] a line could not be written");
537            return None;
538        }
539        let looked = self.roll_up_once_an_hour(snap.ts_ms);
540        self.prune_once_a_day(&day_of(snap.ts_ms));
541        looked
542    }
543
544    fn roll_up_once_an_hour(&self, now_ms: u64) -> Option<super::record_flags::Looked> {
545        let hour = now_ms / HOUR_MS;
546        {
547            let mut gate = self.gate.lock().unwrap_or_else(|e| e.into_inner());
548            if gate.rolled_hour == Some(hour) {
549                return None;
550            }
551            gate.rolled_hour = Some(hour);
552        }
553        roll_up(&self.dir, now_ms);
554        // The rules read the hour just folded, and what they find is written beside the stalls.
555        Some(super::record_flags::look(&self.dir, now_ms))
556    }
557
558    /// The nearest folder that exists, for the drive's free space (the record's own folder may not exist yet).
559    fn dir_for_disk(&self) -> PathBuf {
560        let mut p = self.dir.as_path();
561        while !p.exists() {
562            match p.parent() {
563                Some(parent) => p = parent,
564                None => break,
565            }
566        }
567        p.to_path_buf()
568    }
569
570    fn append(&self, sample: &Sample) -> std::io::Result<()> {
571        use std::io::Write;
572        std::fs::create_dir_all(&self.dir)?;
573        let mut line = serde_json::to_string(sample).map_err(std::io::Error::other)?;
574        line.push('\n');
575        let path = self.dir.join(file_name(&day_of(sample.t)));
576        let mut file = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
577        file.write_all(line.as_bytes())
578    }
579
580    fn prune_once_a_day(&self, today: &str) {
581        {
582            let mut gate = self.gate.lock().unwrap_or_else(|e| e.into_inner());
583            if gate.pruned_day.as_deref() == Some(today) {
584                return;
585            }
586            gate.pruned_day = Some(today.to_string());
587        }
588        prune(&self.dir, today);
589    }
590}
591
592/// Delete what [`files_to_remove`] says from `dir`.
593fn prune(dir: &Path, today: &str) {
594    let Ok(entries) = std::fs::read_dir(dir) else { return };
595    let files: Vec<(String, u64)> = entries
596        .flatten()
597        .filter_map(|e| Some((e.file_name().to_str()?.to_string(), e.metadata().ok()?.len())))
598        .collect();
599    let doomed = files_to_remove(&files, today, KEEP_DAYS, MAX_BYTES)
600        .into_iter()
601        .chain(rollups_to_remove(&files, today, ROLLUP_KEEP_DAYS, ROLLUP_MAX_BYTES))
602        .chain(events_to_remove(&files, today, ROLLUP_KEEP_DAYS));
603    for name in doomed {
604        if let Err(e) = std::fs::remove_file(dir.join(&name)) {
605            tracing::warn!(error = %e, file = %name, "[record] an old day could not be removed");
606        }
607    }
608}
609
610/// The events of the months that overlap `from_ms` to `to_ms` taken in that window, newest `limit` in time order,
611/// and how many the window holds. Each is the line as written: `t`, `kind` and numbers.
612pub fn read_events(dir: &Path, from_ms: u64, to_ms: u64, limit: usize) -> (usize, Vec<serde_json::Value>) {
613    let Ok(entries) = std::fs::read_dir(dir) else { return (0, Vec::new()) };
614    let mut files: Vec<(String, PathBuf)> = entries
615        .flatten()
616        .filter_map(|e| Some((agentmux_common::record_events::month_of_file(e.file_name().to_str()?)?.to_string(), e.path())))
617        .collect();
618    files.sort();
619    let mut out: Vec<(u64, serde_json::Value)> = Vec::new();
620    for (_, path) in files {
621        let Ok(text) = std::fs::read_to_string(&path) else { continue };
622        out.extend(
623            text.lines()
624                .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
625                .filter_map(|v| Some((v["t"].as_u64().filter(|t| *t >= from_ms && *t <= to_ms)?, v))),
626        );
627    }
628    out.sort_by_key(|(t, _)| *t);
629    let total = out.len();
630    out.drain(..total.saturating_sub(limit));
631    (total, out.into_iter().map(|(_, v)| v).collect())
632}
633
634/// The events files to delete: a month that ended more than `keep_days` before `today`.
635pub fn events_to_remove(files: &[(String, u64)], today: &str, keep_days: i64) -> Vec<String> {
636    let Ok(today_date) = chrono::NaiveDate::parse_from_str(today, DAY_FORMAT) else { return Vec::new() };
637    files
638        .iter()
639        .filter_map(|(name, _)| {
640            let start = chrono::NaiveDate::parse_from_str(&format!("{}-01", agentmux_common::record_events::month_of_file(name)?), DAY_FORMAT).ok()?;
641            let end = start.checked_add_months(chrono::Months::new(1))?;
642            ((today_date - end).num_days() > keep_days).then(|| name.clone())
643        })
644        .collect()
645}
646
647/// Where this AgentMux keeps its record: the `record` folder of its channel, which an upgrade keeps.
648pub fn default_dir() -> Option<PathBuf> {
649    agentmux_common::record_events::record_dir()
650}
651
652/// What the record holds on disk.
653#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
654pub struct Inventory {
655    pub raw_days: u32,
656    pub raw_bytes: u64,
657    /// The oldest day kept, `2026-11-02`.
658    #[serde(default, skip_serializing_if = "Option::is_none")]
659    pub raw_first_day: Option<String>,
660    pub rollup_months: u32,
661    pub rollup_bytes: u64,
662    /// Stall events kept (`agentmux_common::record_events`), in bytes.
663    #[serde(default)]
664    pub event_bytes: u64,
665    /// The oldest month kept, `2026-01`.
666    #[serde(default, skip_serializing_if = "Option::is_none")]
667    pub rollup_first_month: Option<String>,
668}
669
670/// The files of `dir`, counted and sized.
671pub fn inventory(dir: &Path) -> Inventory {
672    let mut inv = Inventory::default();
673    let Ok(entries) = std::fs::read_dir(dir) else { return inv };
674    let mut days: Vec<String> = Vec::new();
675    let mut months: Vec<String> = Vec::new();
676    for e in entries.flatten() {
677        let Some(name) = e.file_name().to_str().map(str::to_string) else { continue };
678        let size = e.metadata().map(|m| m.len()).unwrap_or(0);
679        if day_from_file(&name).is_some() {
680            inv.raw_bytes += size;
681            days.push(name.trim_end_matches(&format!(".{EXT}")).to_string());
682        } else if agentmux_common::record_events::month_of_file(&name).is_some() {
683            inv.event_bytes += size;
684        } else if month_from_file(&name).is_some() {
685            inv.rollup_bytes += size;
686            months.push(name.trim_start_matches(ROLLUP_PREFIX).trim_end_matches(&format!(".{EXT}")).to_string());
687        }
688    }
689    days.sort();
690    months.sort();
691    inv.raw_days = days.len() as u32;
692    inv.rollup_months = months.len() as u32;
693    inv.raw_first_day = days.into_iter().next();
694    inv.rollup_first_month = months.into_iter().next();
695    inv
696}
697
698/// The last `limit` lines taken from `from_ms` to `to_ms`, in time order, and how many lines the window holds in all.
699pub fn read_raw(dir: &Path, from_ms: u64, to_ms: u64, limit: usize) -> (usize, Vec<Sample>) {
700    let mut lines: Vec<Sample> = raw_since(dir, Some(&day_of(from_ms))).into_iter().filter(|s| s.t >= from_ms && s.t <= to_ms).collect();
701    let total = lines.len();
702    lines.drain(..total.saturating_sub(limit));
703    (total, lines)
704}
705
706/// The last `limit` hourly rollups of the hours that start from `from_ms` to `to_ms`, in time order, and how many
707/// the window holds in all.
708pub fn read_rollups(dir: &Path, from_ms: u64, to_ms: u64, limit: usize) -> (usize, Vec<Rollup>) {
709    let Ok(entries) = std::fs::read_dir(dir) else { return (0, Vec::new()) };
710    let mut files: Vec<(chrono::NaiveDate, PathBuf)> =
711        entries.flatten().filter_map(|e| Some((month_from_file(e.file_name().to_str()?)?, e.path()))).collect();
712    files.sort();
713    let mut out: Vec<Rollup> = Vec::new();
714    for (_, path) in files {
715        let Ok(text) = std::fs::read_to_string(&path) else { continue };
716        out.extend(text.lines().filter_map(|l| serde_json::from_str::<Rollup>(l).ok()).filter(|r| r.h >= from_ms && r.h <= to_ms));
717    }
718    out.sort_by_key(|r| r.h);
719    let total = out.len();
720    out.drain(..total.saturating_sub(limit));
721    (total, out)
722}
723
724#[cfg(test)]
725mod tests {
726    use super::*;
727    use crate::backend::rpc_types::{
728        TowerMachine, TowerMemoryPart, TowerMemoryPartId, TowerMemoryRow, TowerSnapshot,
729    };
730
731    fn row(key: &str, mem: u64) -> TowerMemoryRow {
732        TowerMemoryRow { key: key.into(), label: format!("label of {key}"), mem, processes: 2, kind: None, task: None, children: vec![] }
733    }
734
735    fn memory() -> TowerMemory {
736        TowerMemory {
737            total: 3_000,
738            processes: 9,
739            unreadable: 1,
740            parts: vec![
741                TowerMemoryPart { part: TowerMemoryPartId::Core, mem: 1_000, processes: 3, rows: vec![row("core:srv", 600), row("core:gpu", 400)] },
742                TowerMemoryPart { part: TowerMemoryPartId::Panes, mem: 1_500, processes: 4, rows: vec![row("pane:window:main", 1_500)] },
743                TowerMemoryPart { part: TowerMemoryPartId::Agents, mem: 500, processes: 2, rows: vec![row("agent:b1", 500)] },
744                TowerMemoryPart { part: TowerMemoryPartId::NotPlaced, mem: 0, processes: 0, rows: vec![] },
745            ],
746            other_instances: None,
747            metric: "private".into(),
748            growth: vec![],
749            history: None,
750        }
751    }
752
753    fn snapshot(t: u64) -> TowerSnapshot {
754        TowerSnapshot {
755            ts_ms: t,
756            hostname: "a-computer".into(),
757            os: "linux".into(),
758            cpu_count: 8,
759            memory_metric: "private".into(),
760            interval_ms: 2_000,
761            remote: false,
762            tasks: vec![],
763            machine: Some(TowerMachine { cpu: Some(0.5), mem: 9_000, processes: 300, mem_total: Some(32_000), agentmux_elsewhere: None }),
764            host: None,
765            panes: None,
766            memory: Some(memory()),
767        }
768    }
769
770    const DAY_MS: u64 = 86_400_000;
771    /// 2026-11-16 12:00 UTC.
772    const NOON: u64 = 1_794_830_400_000;
773
774    #[test]
775    fn a_line_holds_numbers_and_keys_but_no_labels_or_names() {
776        let line = compact(&snapshot(NOON), "0.60.30", 3_600, Some((10, 100)));
777        let json = serde_json::to_string(&line).unwrap();
778        assert!(!json.contains("label of"), "{json}");
779        assert!(!json.contains("a-computer"), "{json}");
780        let am = line.am.unwrap();
781        assert_eq!(am.parts.iter().map(|p| p.k.as_str()).collect::<Vec<_>>(), ["core", "panes", "agents", "not_placed"]);
782        assert_eq!(am.rows.iter().map(|r| r.k.as_str()).collect::<Vec<_>>(), ["pane:window:main", "core:srv", "agent:b1", "core:gpu"]);
783        assert_eq!(line.machine.unwrap().disk, Some((10, 100)));
784        assert_eq!((line.v.as_str(), line.up_s, line.t), ("0.60.30", 3_600, NOON));
785    }
786
787    #[test]
788    fn a_runaway_of_rows_is_cut_to_the_largest() {
789        let mut m = memory();
790        m.parts[0].rows = (0..200).map(|i| row(&format!("np:p{i}"), i)).collect();
791        let am = agentmux_line(&m);
792        assert_eq!(am.rows.len(), MAX_ROWS);
793        assert!(am.rows.windows(2).all(|w| w[0].mem >= w[1].mem));
794    }
795
796    #[test]
797    fn a_line_reads_back() {
798        let line = compact(&snapshot(NOON), "0.60.30", 5, None);
799        let back: Sample = serde_json::from_str(&serde_json::to_string(&line).unwrap()).unwrap();
800        assert_eq!(back, line);
801    }
802
803    #[test]
804    fn the_day_is_the_utc_day() {
805        assert_eq!(day_of(NOON), "2026-11-16");
806        assert_eq!(day_of(NOON + 12 * 3_600_000), "2026-11-17");
807    }
808
809    #[test]
810    fn old_days_and_then_the_oldest_over_budget_go_but_never_today() {
811        let f = |d: &str, size: u64| (format!("{d}.jsonl"), size);
812        let files = vec![f("2026-10-01", 10), f("2026-11-01", 10), f("2026-11-02", 10), f("2026-11-15", 10), f("2026-11-16", 10), ("notes.txt".into(), 99)];
813        // Fourteen days back from the 16th keeps the 2nd on; the 1st and October go.
814        assert_eq!(files_to_remove(&files, "2026-11-16", 14, 1_000), ["2026-10-01.jsonl", "2026-11-01.jsonl"]);
815        // A budget of 25 bytes takes the oldest of the rest until the total fits, and stops before today.
816        assert_eq!(
817            files_to_remove(&files, "2026-11-16", 14, 25),
818            ["2026-10-01.jsonl", "2026-11-01.jsonl", "2026-11-02.jsonl"]
819        );
820        assert_eq!(files_to_remove(&[f("2026-11-16", 9_999)], "2026-11-16", 14, 1), Vec::<String>::new());
821        assert_eq!(files_to_remove(&files, "not a day", 14, 1), Vec::<String>::new());
822    }
823
824    #[test]
825    fn a_line_is_written_each_five_minutes_to_the_file_of_its_day() {
826        let tmp = tempfile::tempdir().unwrap();
827        let record = Record::new(tmp.path().join("record"), "0.60.30");
828        record.note(&snapshot(NOON));
829        record.note(&snapshot(NOON + 2_000)); // a Tower sampling every 2 s: not a new line
830        record.note(&snapshot(NOON + EVERY_MS));
831        record.note(&snapshot(NOON + DAY_MS)); // the next day's file
832        let today = std::fs::read_to_string(tmp.path().join("record/2026-11-16.jsonl")).unwrap();
833        assert_eq!(today.lines().count(), 2);
834        let first: Sample = serde_json::from_str(today.lines().next().unwrap()).unwrap();
835        assert_eq!(first.t, NOON);
836        assert!(tmp.path().join("record/2026-11-17.jsonl").exists());
837    }
838
839    #[test]
840    fn a_renderer_key_keeps_its_kind_and_a_hash_but_never_the_name() {
841        let mut m = memory();
842        m.parts[1].rows = vec![
843            row("renderer:renderer-window-acme-payroll-q3", 900),
844            row("renderer:renderer-browser-pane-secret-bank-example", 800),
845            row("renderer:renderer-pool-window-idle", 700),
846            row("renderer:renderer", 600),
847            row("terminal:t1", 500),
848        ];
849        let am = agentmux_line(&m);
850        let keys: Vec<&str> = am.rows.iter().map(|r| r.k.as_str()).collect();
851        let json = serde_json::to_string(&am).unwrap();
852        for word in ["acme", "payroll", "secret", "bank", "example"] {
853            assert!(!json.contains(word), "{word} in {json}");
854        }
855        let has = |prefix: &str| keys.iter().filter(|k| k.starts_with(prefix)).count();
856        assert_eq!((has("renderer:window:"), has("renderer:browser:"), has("renderer:pool:"), has("renderer:other:")), (1, 1, 1, 1), "{keys:?}");
857        assert!(keys.contains(&"terminal:t1"), "{keys:?}");
858        assert_eq!(keys[0].len(), "renderer:window:".len() + 8, "{keys:?}");
859        // The same renderer gives the same key on the next line, and another one a different key.
860        assert_eq!(persisted_key("renderer:renderer-window-a"), persisted_key("renderer:renderer-window-a"));
861        assert_ne!(persisted_key("renderer:renderer-window-a"), persisted_key("renderer:renderer-window-b"));
862        // A key already cut stays as it is.
863        let cut = persisted_key("renderer:renderer-window-a");
864        assert_eq!(persisted_key(&cut), cut);
865    }
866
867    #[test]
868    fn a_rollup_of_lines_an_older_version_wrote_carries_no_names_either() {
869        let mut old = line(NOON, 1, 1, 10);
870        old.am.as_mut().unwrap().rows = vec![PartLine { k: "renderer:renderer-window-acme-payroll".into(), mem: 7, n: 1 }];
871        let json = serde_json::to_string(&rollup(NOON, &[old]).unwrap()).unwrap();
872        assert!(!json.contains("acme") && !json.contains("payroll"), "{json}");
873        assert!(json.contains("renderer:window:"), "{json}");
874    }
875
876    #[test]
877    fn a_sample_a_little_early_is_not_dropped_but_a_fast_sampler_still_is() {
878        let tmp = tempfile::tempdir().unwrap();
879        let record = Record::new(tmp.path().join("record"), "0.60.30");
880        record.note(&snapshot(NOON));
881        record.note(&snapshot(NOON + EVERY_MS - 1)); // the previous one ran long: still the next line
882        record.note(&snapshot(NOON + EVERY_MS - 1 + 60_000)); // not yet five minutes after the last
883        let today = std::fs::read_to_string(tmp.path().join("record/2026-11-16.jsonl")).unwrap();
884        assert_eq!(today.lines().count(), 2);
885    }
886
887    #[test]
888    fn a_sample_with_nothing_in_it_writes_nothing() {
889        let tmp = tempfile::tempdir().unwrap();
890        let record = Record::new(tmp.path().join("record"), "0.60.30");
891        let mut empty = snapshot(NOON);
892        empty.machine = None;
893        empty.memory = None;
894        record.note(&empty);
895        assert!(!tmp.path().join("record").exists());
896    }
897
898    #[test]
899    fn pruning_removes_old_days_from_the_folder_once_a_day() {
900        let tmp = tempfile::tempdir().unwrap();
901        let dir = tmp.path().join("record");
902        std::fs::create_dir_all(&dir).unwrap();
903        std::fs::write(dir.join("2026-09-01.jsonl"), "x\n").unwrap();
904        std::fs::write(dir.join("keep.txt"), "x\n").unwrap();
905        let record = Record::new(dir.clone(), "0.60.30");
906        record.note(&snapshot(NOON));
907        assert!(!dir.join("2026-09-01.jsonl").exists());
908        assert!(dir.join("keep.txt").exists());
909        assert!(dir.join("2026-11-16.jsonl").exists());
910    }
911
912    /// A line at `t` with AgentMux at `total` bytes, its renderer row at `win` and srv up for `up_s`.
913    fn line(t: u64, total: u64, win: u64, up_s: u64) -> Sample {
914        let mut snap = snapshot(t);
915        let m = snap.memory.as_mut().unwrap();
916        m.total = total;
917        m.parts[1].rows = vec![row("pane:window:main", win)];
918        compact(&snap, "0.60.30", up_s, Some((500, 1_000)))
919    }
920
921    #[test]
922    fn an_hour_is_min_median_p95_and_max() {
923        let samples: Vec<Sample> = (1..=12).map(|i| line(NOON + i * EVERY_MS, i * 100, i * 10, i * 300)).collect();
924        let r = rollup(NOON, &samples).unwrap();
925        assert_eq!((r.n, r.restarts, r.up_s), (12, 0, 3_600));
926        assert_eq!(r.am, Some(Stat(100, 600, 1_200, 1_200)));
927        assert_eq!(r.rows.iter().find(|(k, _)| k == "pane:window:main").unwrap().1, Stat(10, 60, 120, 120));
928        assert_eq!(r.disk_free, Some(Stat(500, 500, 500, 500)));
929        assert_eq!(r.cpu, Some(Stat(500, 500, 500, 500)));
930        assert_eq!(rollup(NOON, &[]), None);
931    }
932
933    #[test]
934    fn a_row_missing_from_some_lines_counts_as_zero_there_and_the_largest_rows_are_kept() {
935        let mut a = line(NOON, 1, 100, 10);
936        a.am.as_mut().unwrap().rows = (0..10).map(|i| PartLine { k: format!("np:p{i}"), mem: i + 1, n: 1 }).collect();
937        let mut b = line(NOON + EVERY_MS, 1, 100, 20);
938        b.am.as_mut().unwrap().rows = vec![PartLine { k: "np:p9".into(), mem: 50, n: 1 }];
939        let r = rollup(NOON, &[a, b]).unwrap();
940        assert_eq!(r.rows.len(), ROLLUP_ROWS);
941        assert_eq!(r.rows[0], ("np:p9".to_string(), Stat(10, 10, 50, 50)));
942        assert_eq!(r.rows[1].0, "np:p8");
943        assert_eq!(r.rows[1].1, Stat(0, 0, 9, 9));
944    }
945
946    #[test]
947    fn a_restart_inside_an_hour_is_counted_by_the_uptime_going_back() {
948        let samples = vec![line(NOON, 1, 1, 900), line(NOON + EVERY_MS, 1, 1, 1_200), line(NOON + 2 * EVERY_MS, 1, 1, 40)];
949        assert_eq!(rollup(NOON, &samples).unwrap().restarts, 1);
950    }
951
952    #[test]
953    fn finished_hours_are_rolled_up_once_each_and_the_current_hour_is_not() {
954        let tmp = tempfile::tempdir().unwrap();
955        let dir = tmp.path().join("record");
956        let record = Record::new(dir.clone(), "0.60.30");
957        // 12:00 to 14:59 in five-minute lines, then the first line of 15:00.
958        for i in 0..=36 {
959            record.note(&snapshot(NOON + i * EVERY_MS));
960        }
961        let text = std::fs::read_to_string(dir.join("rollup-2026-11.jsonl")).unwrap();
962        let rolls: Vec<Rollup> = text.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
963        assert_eq!(rolls.iter().map(|r| (r.h - NOON) / HOUR_MS).collect::<Vec<_>>(), [0, 1, 2]);
964        assert!(rolls.iter().all(|r| r.n == 12));
965        // A new process (srv restarted) finds where it left off and writes nothing twice.
966        let again = Record::new(dir.clone(), "0.60.30");
967        again.note(&snapshot(NOON + 37 * EVERY_MS));
968        assert_eq!(std::fs::read_to_string(dir.join("rollup-2026-11.jsonl")).unwrap().lines().count(), 3);
969        // An hour later the 15:00 hour is rolled up.
970        again.note(&snapshot(NOON + 49 * EVERY_MS));
971        assert_eq!(std::fs::read_to_string(dir.join("rollup-2026-11.jsonl")).unwrap().lines().count(), 4);
972    }
973
974    #[test]
975    fn the_uptime_of_a_line_follows_the_clock_of_its_time_so_a_sleep_is_not_a_restart() {
976        let tmp = tempfile::tempdir().unwrap();
977        let mut record = Record::new(tmp.path().join("record"), "0.60.30");
978        record.started_ms = NOON - 2 * HOUR_MS;
979        record.note(&snapshot(NOON));
980        // An hour later by the wall clock, whatever a monotonic clock counted in between (a suspend).
981        record.note(&snapshot(NOON + HOUR_MS));
982        let text = std::fs::read_to_string(tmp.path().join("record/2026-11-16.jsonl")).unwrap();
983        let ups: Vec<u64> = text.lines().map(|l| serde_json::from_str::<Sample>(l).unwrap().up_s).collect();
984        assert_eq!(ups, [7_200, 10_800]);
985    }
986
987    fn page(w: &str, heap: u32, dom: u32, rows: u32) -> PageLine {
988        PageLine { w: w.into(), heap: Some(heap), heap_limit: Some(4096), dom, panes: 3, rows, max_rows: rows / 2, searches: 1, blocked: 0, up_min: 90 }
989    }
990
991    #[test]
992    fn a_page_that_reported_is_in_the_next_line_until_it_stops_reporting() {
993        // An era of its own: the pages are the process's, and other tests write lines at NOON.
994        let t = 5_000_000_000_000u64;
995        note_page(page("window-9", 310, 18_000, 4_100), t);
996        note_page(page("Main <b>!</b>", 120, 5_000, 0), t + 1_000);
997        let tmp = tempfile::tempdir().unwrap();
998        let record = Record::new(tmp.path().join("record"), "0.60.30");
999        record.note(&snapshot(t + 2_000));
1000        let text = std::fs::read_to_string(tmp.path().join(format!("record/{}.jsonl", day_of(t)))).unwrap();
1001        let line: Sample = serde_json::from_str(text.lines().next().unwrap()).unwrap();
1002        // A label is cut to what an id holds.
1003        assert_eq!(line.pages.iter().map(|p| p.w.as_str()).collect::<Vec<_>>(), ["Mainbb", "window-9"]);
1004        assert_eq!(line.pages[1].dom, 18_000);
1005        // Fifteen minutes on, a page that never reported again has closed.
1006        assert!(pages_at(t + PAGE_FRESH_MS + 5_000).is_empty());
1007        // No page, no key in the line.
1008        let bare = serde_json::to_string(&compact(&snapshot(NOON), "0.60.30", 1, None)).unwrap();
1009        assert!(!bare.contains("pages"), "{bare}");
1010    }
1011
1012    #[test]
1013    fn an_hour_keeps_the_biggest_windows_pages_and_when_its_last_line_was() {
1014        let mut samples: Vec<Sample> = (0..12).map(|i| line(NOON + i * EVERY_MS, 1_000, 1, 1)).collect();
1015        for (i, s) in samples.iter_mut().enumerate() {
1016            let i = i as u32;
1017            s.pages = vec![page("main", 300 + i * 10, 10_000 + i * 100, 100 + i), page("a", 50, 100, 1), page("b", 60, 100, 1), page("c", 70, 100, 1)];
1018        }
1019        samples[11].pages.pop(); // c missed the last report
1020        let r = rollup(NOON, &samples).unwrap();
1021        assert_eq!(r.last_t, NOON + 11 * EVERY_MS);
1022        assert_eq!(r.pages.iter().map(|p| p.w.as_str()).collect::<Vec<_>>(), ["main", "c", "b"]);
1023        assert_eq!(r.pages[0].heap, Some(Stat(300, 350, 410, 410)));
1024        assert_eq!(r.pages[0].dom, Stat(10_000, 10_500, 11_100, 11_100));
1025        // An older rollup, from before any of it, still reads.
1026        let old: Rollup = serde_json::from_str(r#"{"h":1,"n":1,"v":"0.60.31","up_s":5,"restarts":0,"parts":[],"rows":[]}"#).unwrap();
1027        assert_eq!((old.last_t, old.pages.len()), (0, 0));
1028    }
1029
1030    #[test]
1031    fn a_rollup_is_a_small_line() {
1032        let mut samples: Vec<Sample> = (0..12).map(|i| line(NOON + i * EVERY_MS, 3_000_000_000, 1_500_000_000, 1_000_000)).collect();
1033        for s in samples.iter_mut() {
1034            s.pages = vec![page("main", 3_000, 200_000, 90_000), page("window-12", 2_000, 100_000, 5_000), page("window-13", 1_000, 90_000, 4_000)];
1035        }
1036        let json = serde_json::to_string(&rollup(NOON, &samples).unwrap()).unwrap();
1037        // A year of hours has to fit ROLLUP_MAX_BYTES with room to spare.
1038        assert!(json.len() as u64 * 24 * 366 < ROLLUP_MAX_BYTES, "{} bytes: {json}", json.len());
1039    }
1040
1041    #[test]
1042    fn an_empty_newest_month_does_not_reset_the_checkpoint() {
1043        let tmp = tempfile::tempdir().unwrap();
1044        let dir = tmp.path().join("record");
1045        let record = Record::new(dir.clone(), "0.60.30");
1046        for i in 0..=24 {
1047            record.note(&snapshot(NOON + i * EVERY_MS)); // 12:00 to 14:00: the 12:00 and 13:00 hours are rolled
1048        }
1049        let full = std::fs::read_to_string(dir.join("rollup-2026-11.jsonl")).unwrap().lines().count();
1050        assert_eq!(full, 2);
1051        // The next month's file exists but holds no whole line (a failed first append).
1052        std::fs::write(dir.join("rollup-2026-12.jsonl"), "{\"h\":").unwrap();
1053        assert_eq!(last_rollup_hour(&dir), Some(NOON + HOUR_MS));
1054        let again = Record::new(dir.clone(), "0.60.30");
1055        again.note(&snapshot(NOON + 25 * EVERY_MS));
1056        assert_eq!(std::fs::read_to_string(dir.join("rollup-2026-11.jsonl")).unwrap().lines().count(), full);
1057    }
1058
1059    #[test]
1060    fn the_record_is_read_back_by_window_and_counted() {
1061        let tmp = tempfile::tempdir().unwrap();
1062        let dir = tmp.path().join("record");
1063        let record = Record::new(dir.clone(), "0.60.30");
1064        for i in 0..=30 {
1065            record.note(&snapshot(NOON + i * EVERY_MS));
1066        }
1067        let (total, all) = read_raw(&dir, 0, u64::MAX, 1_000);
1068        assert_eq!((total, all.len()), (31, 31));
1069        // The newest lines of a window, in time order, and how many the window holds in all.
1070        let (total, last3) = read_raw(&dir, NOON + 10 * EVERY_MS, NOON + 20 * EVERY_MS, 3);
1071        assert_eq!(total, 11);
1072        assert_eq!(last3.iter().map(|s| s.t).collect::<Vec<_>>(), [NOON + 18 * EVERY_MS, NOON + 19 * EVERY_MS, NOON + 20 * EVERY_MS]);
1073        let (total, rolls) = read_rollups(&dir, 0, u64::MAX, 1);
1074        assert_eq!((total, rolls.iter().map(|r| r.h).collect::<Vec<_>>()), (2, vec![NOON + HOUR_MS]));
1075        let (_, rolls) = read_rollups(&dir, NOON + HOUR_MS, u64::MAX, 10);
1076        assert_eq!(rolls.iter().map(|r| r.h).collect::<Vec<_>>(), [NOON + HOUR_MS]);
1077        let inv = inventory(&dir);
1078        assert_eq!((inv.raw_days, inv.rollup_months), (1, 1));
1079        assert_eq!((inv.raw_first_day.as_deref(), inv.rollup_first_month.as_deref()), (Some("2026-11-16"), Some("2026-11")));
1080        assert!(inv.raw_bytes > 0 && inv.rollup_bytes > 0);
1081        assert_eq!(inventory(&tmp.path().join("nothing")), Inventory::default());
1082    }
1083
1084    #[test]
1085    fn events_are_read_back_by_window_and_counted_and_old_months_go() {
1086        let tmp = tempfile::tempdir().unwrap();
1087        let dir = tmp.path().join("record");
1088        for i in 0..5u64 {
1089            agentmux_common::record_events::append_event(&dir, NOON + i * 60_000, "ui_stall", serde_json::json!({ "ms": 1_000 * (i + 1) })).unwrap();
1090        }
1091        // The next month's file, and a line with no time that is not an event.
1092        agentmux_common::record_events::append_event(&dir, NOON + 30 * DAY_MS, "srv_stall", serde_json::json!({ "ms": 7 })).unwrap();
1093        std::fs::write(dir.join("events-2026-10.jsonl"), "{\"kind\":\"x\"}
1094not json
1095").unwrap();
1096        let (total, last2) = read_events(&dir, 0, NOON + 10 * DAY_MS, 2);
1097        assert_eq!(total, 5);
1098        assert_eq!(last2.iter().map(|e| e["ms"].as_u64().unwrap()).collect::<Vec<_>>(), [4_000, 5_000]);
1099        assert_eq!(read_events(&dir, 0, u64::MAX, 100).0, 6);
1100        assert_eq!(inventory(&dir).event_bytes > 0, true);
1101        let files: Vec<(String, u64)> = ["events-2025-09.jsonl", "events-2026-09.jsonl", "events-2026-11.jsonl", "2026-11-15.jsonl"].iter().map(|n| (n.to_string(), 10)).collect();
1102        assert_eq!(events_to_remove(&files, "2026-11-16", 366), ["events-2025-09.jsonl"]);
1103    }
1104
1105    #[test]
1106    fn rollup_months_go_after_a_year_or_over_budget_but_never_this_months() {
1107        let f = |m: &str, size: u64| (format!("rollup-{m}.jsonl"), size);
1108        let files = vec![f("2025-09", 10), f("2025-12", 10), f("2026-10", 10), f("2026-11", 10), ("2026-11-15.jsonl".into(), 10)];
1109        // A month that ended more than 366 days before the 16th of November 2026: September 2025 only.
1110        assert_eq!(rollups_to_remove(&files, "2026-11-16", 366, 1_000), ["rollup-2025-09.jsonl"]);
1111        assert_eq!(rollups_to_remove(&files, "2026-11-16", 366, 15), ["rollup-2025-09.jsonl", "rollup-2025-12.jsonl", "rollup-2026-10.jsonl"]);
1112        assert_eq!(rollups_to_remove(&[f("2026-11", 9_999)], "2026-11-16", 366, 1), Vec::<String>::new());
1113    }
1114}