Skip to main content

agentmux_srv_core/backend/
sysinfo.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Sysinfo data collection loop: collects CPU, memory, and network metrics
5//! and publishes them via the MPS broker. Sampling interval is configurable
6//! via the `telemetry:interval` setting (0.1s–2.0s, default 1.0s).
7
8use std::collections::{HashMap, HashSet};
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::Arc;
11use std::time::{Duration, Instant};
12
13use crate::backend::net_counters::NetCounters;
14use sysinfo::{DiskRefreshKind, Disks, MemoryRefreshKind, Pid, ProcessRefreshKind, ProcessesToUpdate};
15
16use crate::backend::blockcontroller::pidregistry;
17use crate::backend::blockcontroller::process_tree;
18#[cfg(target_os = "windows")]
19use crate::backend::own_instance;
20use crate::backend::rpc_types::TimeSeriesData;
21use crate::backend::wconfig::ConfigState;
22use crate::backend::mps::Broker;
23use crate::backend::sampler::{Scheduler, SourceId, SourceSpec};
24
25const BYTES_PER_GB: f64 = 1_073_741_824.0;
26const BYTES_PER_MB: f64 = 1_048_576.0;
27const PERSIST_COUNT: usize = 1024;
28/// The sample's key for the milliseconds its rates average over (the chart reads it).
29pub const SAMPLE_WINDOW_KEY: &str = "sample:window_ms";
30const DEFAULT_INTERVAL_SECS: f64 = 1.0;
31const MIN_INTERVAL_SECS: f64 = 0.2;
32const MAX_INTERVAL_SECS: f64 = 2.0;
33/// How often the disk list and each volume's capacity/free space are
34/// re-read. Every tick only refreshes I/O counters (the read/write rates need
35/// a delta per tick). A full refresh re-lists every mounted volume and, on
36/// macOS, asks each for its "available for important usage" capacity, which
37/// goes through CacheDelete: with a few DMGs mounted that was thousands of
38/// system calls and log lines a minute, for numbers that move slowly.
39const DISK_FULL_REFRESH: Duration = Duration::from_secs(30);
40
41/// Sources due within this much of each other run in one pass.
42const SCHEDULER_COALESCE_MS: u64 = 50;
43/// How often the panes' processes are scanned with no badge watching: enough to
44/// evict a pane whose shell exited without normal cleanup.
45const PANE_JANITOR_MS: u64 = 30_000;
46/// A budget no run exceeds: the source keeps its interval whatever a run costs.
47const NEVER_STRETCHED: u64 = u64::MAX / 4;
48const HOLDER_TELEMETRY: &str = "telemetry";
49const HOLDER_JANITOR: &str = "pane-janitor";
50const HOLDER_BADGES: &str = "pane-badges";
51
52// ── Commit (pagefile) attribution ────────────────────────────────────────
53// docs/retro/retro-subagent-backfill-storm-oom-2026-07-17.md: a live OOM
54// crash left no forensic trail of WHICH processes were consuming commit —
55// only the system-wide total (`get_commit_data`) was ever logged. This
56// section adds periodic + urgent-on-pressure attribution, bucketing every
57// process on the machine into "agentmux" (this app's own process family —
58// host, srv, launcher, CEF helper processes), "panes" (every registered
59// block's shell process tree — agent CLI subprocesses, terminal shells,
60// etc.; exact PID-tree membership via `pidregistry` + `process_tree`, not
61// name-guessing), and "other" (everything else, top-N by commit kept for
62// visibility — Chrome, VS Code, Docker, Windows itself, ...).
63
64/// Milliseconds from a SUSPEND-AWARE monotonic clock — one that keeps counting
65/// while the machine is asleep, and can never move backwards.
66///
67/// Uptime needs both properties, and no single obvious clock has them:
68///
69/// - Wall clock (`SystemTime`/`chrono::Utc::now()`) counts suspend but moves
70///   backwards on an NTP correction, a manual set, or a VM resume. That was
71///   the original bug: on 0.55.26 the app started while the machine's clock
72///   read 2081-02-05, the clock was later corrected to 2026-08-29 with no
73///   restart, and the status bar rendered `-59:0-14`.
74/// - `std::time::Instant` can't move backwards, but it STOPS while the machine
75///   is suspended (`CLOCK_MONOTONIC` on Linux, `mach_absolute_time` on macOS,
76///   QPC on Windows). Using it would silently under-report by the whole
77///   suspend interval on every laptop lid-close — a regression against the
78///   wall-clock behaviour it replaced (codex P2 on PR #2831).
79///
80/// So each platform's suspend-aware counter is used directly:
81///
82/// | Platform | Source | Counts suspend |
83/// |---|---|---|
84/// | Linux/Android | `CLOCK_BOOTTIME` | yes (`CLOCK_MONOTONIC` does not) |
85/// | macOS/BSD | `CLOCK_MONOTONIC` | yes — Darwin's continues across sleep, unlike `CLOCK_UPTIME_RAW` and unlike the `mach_absolute_time` behind `Instant` |
86/// | Windows | `GetTickCount64` | yes (`QueryUnbiasedInterruptTime` does not) |
87///
88/// All three count from system boot, not process start, so `mark_process_start`
89/// takes a baseline and `uptime_secs` subtracts it.
90#[cfg(windows)]
91fn suspend_aware_now_ms() -> u64 {
92    // SAFETY: no arguments, no pointers, always succeeds.
93    unsafe { windows_sys::Win32::System::SystemInformation::GetTickCount64() }
94}
95
96#[cfg(not(windows))]
97fn suspend_aware_now_ms() -> u64 {
98    #[cfg(any(target_os = "linux", target_os = "android"))]
99    const CLOCK: libc::clockid_t = libc::CLOCK_BOOTTIME;
100    #[cfg(not(any(target_os = "linux", target_os = "android")))]
101    const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC;
102
103    let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
104    // SAFETY: `ts` is a valid, initialized, exclusively-borrowed timespec.
105    if unsafe { libc::clock_gettime(CLOCK, &mut ts) } != 0 {
106        // Reporting 0 makes uptime read 0 — visibly wrong but harmless and
107        // never negative. Preferable to substituting a clock with different
108        // properties partway through the process's life.
109        return 0;
110    }
111    (ts.tv_sec as u64) * 1_000 + (ts.tv_nsec as u64) / 1_000_000
112}
113
114/// Baseline reading of `suspend_aware_now_ms` captured at process start by
115/// `mark_process_start` (`main.rs`).
116static PROCESS_START_MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
117
118/// Record this process's start for uptime reporting. Idempotent; the first
119/// call wins, so a stray second call can't restart the clock.
120pub fn mark_process_start() {
121    let _ = PROCESS_START_MS.set(suspend_aware_now_ms());
122}
123
124/// Seconds since `mark_process_start`. Falls back to initializing on first
125/// read, so a caller that never marked startup reports a truthful (if
126/// late-based) 0 rather than a wrong number or a panic. `saturating_sub`
127/// makes a decrease structurally impossible even if a platform counter ever
128/// misbehaved.
129pub fn uptime_secs() -> u64 {
130    let start = *PROCESS_START_MS.get_or_init(suspend_aware_now_ms);
131    suspend_aware_now_ms().saturating_sub(start) / 1_000
132}
133
134/// How often to log a full attribution snapshot in the steady state.
135#[cfg(target_os = "windows")]
136const ATTRIBUTION_INTERVAL: Duration = Duration::from_secs(30);
137/// Re-snapshot immediately (bypassing `ATTRIBUTION_INTERVAL`) once available
138/// commit drops below this — a snapshot taken seconds before a crash is far
139/// more useful than one from up to 30s earlier.
140#[cfg(target_os = "windows")]
141const ATTRIBUTION_URGENT_THRESHOLD_GB: f64 = 2.0;
142/// Debounce for the urgent trigger so a sustained low-commit period doesn't
143/// log every single tick.
144#[cfg(target_os = "windows")]
145const ATTRIBUTION_URGENT_COOLDOWN: Duration = Duration::from_secs(10);
146/// How many "other" processes to name individually in the log line.
147#[cfg(target_os = "windows")]
148const ATTRIBUTION_OTHER_TOP_N: usize = 5;
149/// Per-block descendant-PID cap for the attribution walk — deliberately its
150/// OWN, much larger constant, not `process_tree::MAX_PIDS_PER_BLOCK` (64).
151/// That cap is sized for the Sysinfo pane's small per-block CPU/mem display;
152/// reusing it here silently dropped overflow into the "other" bucket
153/// instead of "panes" in exactly the storm scenario this feature exists to
154/// diagnose (a single block's descendant tree exceeding 64 processes) —
155/// reagent P1 on PR #2207. `collect_descendants` gives no truncation signal
156/// beyond "returned exactly `max_pids` results," so that's what
157/// `log_memory_attribution` checks to log a truncation warning rather than
158/// silently under-counting (no silent caps).
159#[cfg(target_os = "windows")]
160const ATTRIBUTION_MAX_PIDS_PER_BLOCK: usize = 4096;
161
162/// One process's classification input — commit charge, not working set:
163/// what actually exhausts the pagefile. (sysinfo's `virtual_memory()` on
164/// Windows is `PROCESS_MEMORY_COUNTERS_EX::PrivateUsage` — a misleading
165/// name from sysinfo's cross-platform API, but the right number: the
166/// process's private/committed bytes.)
167#[cfg(target_os = "windows")]
168struct ProcSample {
169    pid: u32,
170    name: String,
171    commit_mb: f64,
172    /// Whether this process belongs to THIS instance (the launcher's tree that
173    /// srv is in, `own_instance::own_instance_pids`), not just whether it is
174    /// named `agentmux*`: a stable install beside a dev build both have
175    /// `agentmux*` processes, and only this instance's belong in `agentmux_mb`.
176    own: bool,
177}
178
179#[cfg(target_os = "windows")]
180struct AttributionResult {
181    agentmux_mb: f64,
182    panes_mb: f64,
183    other_mb: f64,
184    /// Top `top_n` "other" processes by commit, descending.
185    other_top: Vec<(String, f64)>,
186}
187
188/// Pure classification, factored out for unit testing without a real
189/// process table (mirrors `resolve_pagefile_watch_target` above).
190/// `pane_pids` is the exact PID set `pidregistry`'s block trees computed —
191/// membership, not a name guess, so this bucket can never miscount a
192/// same-named-but-unrelated process. Aggregates "other" by process name
193/// before ranking the top-N — a multi-process app (Chrome, VS Code) would
194/// otherwise get split across many small per-PID entries that individually
195/// miss the cutoff while collectively dominating `other_mb`, hiding the
196/// true top contributor (reagent P1 on PR #2207).
197#[cfg(target_os = "windows")]
198fn classify_commit_attribution(
199    samples: &[ProcSample],
200    pane_pids: &HashSet<u32>,
201    top_n: usize,
202) -> AttributionResult {
203    let mut agentmux_mb = 0.0;
204    let mut panes_mb = 0.0;
205    let mut other_by_name: HashMap<String, f64> = HashMap::new();
206    for s in samples {
207        if s.own && s.name.to_ascii_lowercase().starts_with("agentmux") {
208            agentmux_mb += s.commit_mb;
209        } else if pane_pids.contains(&s.pid) {
210            panes_mb += s.commit_mb;
211        } else {
212            *other_by_name.entry(s.name.clone()).or_insert(0.0) += s.commit_mb;
213        }
214    }
215    let mut other: Vec<(String, f64)> = other_by_name.into_iter().collect();
216    other.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
217    let other_mb: f64 = other.iter().map(|(_, mb)| mb).sum();
218    other.truncate(top_n);
219    AttributionResult {
220        agentmux_mb,
221        panes_mb,
222        other_mb,
223        other_top: other,
224    }
225}
226
227/// Handle-count anomaly thresholds. Both real incidents this detects were
228/// found manually with Sysinternals Handle after weeks of commit growth
229/// (docs/status/STATUS_PF_COMMIT_GROWTH_INVESTIGATION_2026_07_24.md §16:
230/// Audiosrv at ~85K handles ≈ 18GB of leaked pagefile-backed Sections;
231/// docs/status/STATUS_SRV_SECTION_HANDLE_LEAK_2026_08_08.md: agentmux-srv
232/// itself at ~215K, 99.5% Sections). A leaking process crosses these within
233/// hours of a healthy baseline (both incidents' healthy baselines were
234/// under 1K handles), while legitimately handle-heavy processes
235/// (System/svchost/browsers) sit well below the external threshold —
236/// 24,797 was the highest non-leaking count observed on the 08-08
237/// machine snapshot.
238#[cfg(target_os = "windows")]
239const HANDLE_WARN_AGENTMUX: u32 = 20_000;
240#[cfg(target_os = "windows")]
241const HANDLE_WARN_EXTERNAL: u32 = 50_000;
242#[cfg(target_os = "windows")]
243const HANDLE_TOP_N: usize = 3;
244/// Minimum gap between repeat WARNs for the SAME still-anomalous PID. The
245/// first live run of this detector (2026-08-09) re-warned every 30s
246/// attribution cycle — and more under the urgent-on-pressure path — for
247/// two persisting Vite-process anomalies, drowning the log. One warn per
248/// PID per this window keeps the signal (a persisting anomaly still
249/// re-surfaces regularly, and the info line's `handles_top` carries the
250/// count every cycle regardless) without the spam. A PID that drops below
251/// threshold and re-crosses later warns immediately again (its entry is
252/// pruned while healthy).
253#[cfg(target_os = "windows")]
254const HANDLE_WARN_COOLDOWN: Duration = Duration::from_secs(600);
255
256/// One process's handle-count sample for anomaly classification.
257#[cfg(target_os = "windows")]
258struct HandleSample {
259    pid: u32,
260    name: String,
261    handles: u32,
262}
263
264#[cfg(target_os = "windows")]
265struct HandleAnomaly {
266    pid: u32,
267    name: String,
268    handles: u32,
269    /// True → one of our own processes (leak in AgentMux code, actionable
270    /// by us); false → an external process (Audiosrv-class OS leak — the
271    /// remediation is restarting *that* service, not AgentMux).
272    is_agentmux: bool,
273}
274
275/// Pure anomaly classification, factored out for unit testing like
276/// `classify_commit_attribution` above. AgentMux's own processes get the
277/// lower threshold (we know their healthy baseline is well under 1K); any
278/// other process only trips the higher one.
279#[cfg(target_os = "windows")]
280fn classify_handle_anomalies(samples: &[HandleSample]) -> Vec<HandleAnomaly> {
281    let mut anomalies: Vec<HandleAnomaly> = samples
282        .iter()
283        .filter_map(|s| {
284            let is_agentmux = s.name.to_ascii_lowercase().starts_with("agentmux");
285            let threshold = if is_agentmux { HANDLE_WARN_AGENTMUX } else { HANDLE_WARN_EXTERNAL };
286            (s.handles >= threshold).then(|| HandleAnomaly {
287                pid: s.pid,
288                name: s.name.clone(),
289                handles: s.handles,
290                is_agentmux,
291            })
292        })
293        .collect();
294    anomalies.sort_by(|a, b| b.handles.cmp(&a.handles));
295    anomalies
296}
297
298/// Pure cooldown gate for anomaly WARNs, factored out for unit testing.
299/// Returns the indices (into `anomalies`) that should warn THIS cycle, and
300/// updates `last_warned` accordingly. Entries for PIDs that are no longer
301/// anomalous are pruned first — both so the map can't grow unbounded across
302/// process churn, and so a process that recovers and later re-crosses the
303/// threshold warns immediately rather than being silently inside a stale
304/// cooldown window.
305#[cfg(target_os = "windows")]
306fn filter_anomalies_for_warn(
307    anomalies: &[HandleAnomaly],
308    last_warned: &mut HashMap<u32, Instant>,
309    now: Instant,
310    cooldown: Duration,
311) -> Vec<usize> {
312    let current: HashSet<u32> = anomalies.iter().map(|a| a.pid).collect();
313    last_warned.retain(|pid, _| current.contains(pid));
314
315    let mut warn = Vec::new();
316    for (i, anomaly) in anomalies.iter().enumerate() {
317        let due = match last_warned.get(&anomaly.pid) {
318            Some(&at) => now.duration_since(at) >= cooldown,
319            None => true,
320        };
321        if due {
322            last_warned.insert(anomaly.pid, now);
323            warn.push(i);
324        }
325    }
326    warn
327}
328
329/// Process-lifetime state for the cooldown above. A plain static rather
330/// than threading it through the loop: `log_memory_attribution` is only
331/// ever called from the single sysinfo loop task, so contention is nil.
332#[cfg(target_os = "windows")]
333static LAST_HANDLE_WARN: std::sync::OnceLock<std::sync::Mutex<HashMap<u32, Instant>>> =
334    std::sync::OnceLock::new();
335
336/// Open-query-close a process's total handle count. Returns `None` for
337/// PIDs we can't open (protected/system processes) — expected, skipped
338/// silently. The handle opened here is closed unconditionally on both the
339/// success and failure path; leaking handles from the handle-leak detector
340/// would be a bit much.
341#[cfg(target_os = "windows")]
342pub(crate) fn process_handle_count(pid: u32) -> Option<u32> {
343    use windows_sys::Win32::Foundation::CloseHandle;
344    use windows_sys::Win32::System::Threading::{
345        GetProcessHandleCount, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
346    };
347    unsafe {
348        let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
349        if h.is_null() {
350            return None;
351        }
352        let mut count: u32 = 0;
353        let ok = GetProcessHandleCount(h, &mut count);
354        CloseHandle(h);
355        (ok != 0).then_some(count)
356    }
357}
358
359/// Full-system commit snapshot: refresh every process (heavier than the
360/// per-block passes above, but only ever called on the attribution
361/// cadence — every 30s in steady state, or debounced-urgent under
362/// pressure), classify, and log one line. Independent of the per-tick
363/// block-stats pass above — it does its own PID-tree collection so it
364/// can't be affected by that pass's ordering.
365///
366/// `commit_used_gb`/`commit_total_gb` come from the caller's already-computed
367/// `get_commit_data` values rather than re-querying `GlobalMemoryStatusEx`
368/// here — this function is on the same tick as that call.
369#[cfg(target_os = "windows")]
370fn log_memory_attribution(sys: &mut sysinfo::System, commit_used_gb: f64, commit_total_gb: f64) {
371    // Only name()/parent()/virtual_memory() are read below — parent() and
372    // name() are always populated regardless of refresh kind, so only
373    // memory needs to be requested. The per-pane pass a few lines below
374    // (targeted `ProcessesToUpdate::Some`) uses the same restraint; this is
375    // the whole-machine equivalent, so it's the one call where skipping
376    // CPU deltas/disk I/O/exe/cmdline/environ actually matters.
377    sys.refresh_processes_specifics(
378        ProcessesToUpdate::All,
379        true, // remove dead processes — keep this bounded to what's live
380        ProcessRefreshKind::nothing().with_memory(),
381    );
382
383    let mut pane_pids: HashSet<u32> = HashSet::new();
384    for (block_id, pid) in pidregistry::get_all() {
385        let tree = process_tree::collect_descendants(
386            sys,
387            Pid::from(pid as usize),
388            ATTRIBUTION_MAX_PIDS_PER_BLOCK,
389        );
390        if tree.len() == ATTRIBUTION_MAX_PIDS_PER_BLOCK {
391            tracing::warn!(
392                block_id = %block_id,
393                cap = ATTRIBUTION_MAX_PIDS_PER_BLOCK,
394                "log_memory_attribution: block's descendant PID tree hit the cap — \
395                 some processes may be misclassified into \"other\" instead of \"panes\""
396            );
397        }
398        pane_pids.extend(tree.into_iter().map(|pid| pid.as_u32()));
399    }
400
401    // This instance's own processes, so a second AgentMux on the machine (a
402    // stable install beside a dev build, another channel) is counted under
403    // "other" by name, not folded into `agentmux_mb`.
404    let nodes: Vec<own_instance::ProcNode> = sys
405        .processes()
406        .iter()
407        .map(|(pid, proc)| own_instance::ProcNode {
408            pid: pid.as_u32(),
409            parent: proc.parent().map(|p| p.as_u32()),
410            is_agentmux: proc.name().to_string_lossy().to_ascii_lowercase().starts_with("agentmux"),
411            started_at_ms: Some(proc.start_time().saturating_mul(1000)),
412        })
413        .collect();
414    let own_pids = own_instance::own_instance_pids(&nodes, std::process::id());
415    let samples: Vec<ProcSample> = sys
416        .processes()
417        .iter()
418        .map(|(pid, proc)| ProcSample {
419            pid: pid.as_u32(),
420            name: proc.name().to_string_lossy().into_owned(),
421            commit_mb: proc.virtual_memory() as f64 / BYTES_PER_MB,
422            own: own_pids.contains(&pid.as_u32()),
423        })
424        .collect();
425
426    let result = classify_commit_attribution(&samples, &pane_pids, ATTRIBUTION_OTHER_TOP_N);
427
428    let other_top_str = result
429        .other_top
430        .iter()
431        .map(|(name, mb)| format!("{}:{:.0}MB", name, mb))
432        .collect::<Vec<_>>()
433        .join(", ");
434
435    // The two diagnostics both prior pagefile-exhaustion incidents needed
436    // (and had to gather manually with Sysinternals — see the doc refs on
437    // HANDLE_WARN_AGENTMUX above): the *unattributed* commit gap, and
438    // per-process handle counts. Process-private buckets alone are blind to
439    // exactly the leak class that caused both incidents: pagefile-backed
440    // Section objects held via leaked handles are charged to system commit
441    // but to no process's private bytes, so `agentmux_mb + panes_mb +
442    // other_mb` stays flat while `commit_used_gb` climbs — the gap IS the
443    // signal. Handle counts then attribute the gap to the owning process
444    // (which the commit numbers can't), the way the manual handle.exe sweep
445    // did both times.
446    let attributed_gb = (result.agentmux_mb + result.panes_mb + result.other_mb) / 1024.0;
447    let unattributed_gb = (commit_used_gb - attributed_gb).max(0.0);
448
449    // One OpenProcess/GetProcessHandleCount/CloseHandle triplet per live
450    // process, on the same 30s cadence as the rest of this function —
451    // microseconds each, no handles retained (see process_handle_count).
452    let handle_samples: Vec<HandleSample> = samples
453        .iter()
454        .filter_map(|s| {
455            process_handle_count(s.pid).map(|handles| HandleSample {
456                pid: s.pid,
457                name: s.name.clone(),
458                handles,
459            })
460        })
461        .collect();
462    let mut top_handles: Vec<&HandleSample> = handle_samples.iter().collect();
463    top_handles.sort_by(|a, b| b.handles.cmp(&a.handles));
464    let handles_top_str = top_handles
465        .iter()
466        .take(HANDLE_TOP_N)
467        .map(|s| format!("{}:{}:{}", s.name, s.pid, s.handles))
468        .collect::<Vec<_>>()
469        .join(", ");
470
471    let anomalies = classify_handle_anomalies(&handle_samples);
472    let warn_indices = {
473        let mut last = LAST_HANDLE_WARN
474            .get_or_init(|| std::sync::Mutex::new(HashMap::new()))
475            .lock()
476            .unwrap();
477        filter_anomalies_for_warn(&anomalies, &mut last, Instant::now(), HANDLE_WARN_COOLDOWN)
478    };
479    for i in warn_indices {
480        let anomaly = &anomalies[i];
481        if anomaly.is_agentmux {
482            tracing::warn!(
483                target: "mem_attribution",
484                pid = anomaly.pid,
485                name = %anomaly.name,
486                handles = anomaly.handles,
487                "possible handle leak in an AgentMux process — a healthy baseline is under ~1K; \
488                 run `handle64 -s -p <pid>` for the type breakdown (a huge Section count is the \
489                 known leak signature, docs/status/STATUS_SRV_SECTION_HANDLE_LEAK_2026_08_08.md)"
490            );
491        } else {
492            tracing::warn!(
493                target: "mem_attribution",
494                pid = anomaly.pid,
495                name = %anomaly.name,
496                handles = anomaly.handles,
497                "external process handle-count anomaly (Audiosrv-class OS leak?) — if commit is \
498                 also climbing unattributed, restarting that process/service reclaims it \
499                 (docs/status/STATUS_PF_COMMIT_GROWTH_INVESTIGATION_2026_07_24.md §16)"
500            );
501        }
502    }
503
504    // Subsystem counters alongside the memory numbers, same log line/target
505    // so `muxlog srv grep mem_attribution` correlates them for free — added
506    // while investigating a newly-reported leak (2026-09-20) that turned out
507    // not to match either previously-fixed Section-handle mechanism
508    // (#2666/#2722, both already in this build): a block/PID count that
509    // climbs without bound, or reaper candidates that never resolve to
510    // `reaped`, point at these two newer subsystems specifically rather than
511    // requiring a repeat of the manual handle64 archaeology those fixes needed.
512    let (tracker_blocks, tracker_pids) = crate::backend::process_tracker::registry::global()
513        .map(|r| r.stats())
514        .unwrap_or((0, 0));
515    let (reaper_candidates, reaper_first_seen, reaper_reaped_cumulative) =
516        crate::backend::sweep_stats::last_sweep_stats();
517
518    tracing::info!(
519        target: "mem_attribution",
520        commit_used_gb = format!("{:.2}", commit_used_gb),
521        commit_total_gb = format!("{:.2}", commit_total_gb),
522        agentmux_mb = format!("{:.0}", result.agentmux_mb),
523        panes_mb = format!("{:.0}", result.panes_mb),
524        other_mb = format!("{:.0}", result.other_mb),
525        other_top = %other_top_str,
526        unattributed_gb = format!("{:.2}", unattributed_gb),
527        handles_top = %handles_top_str,
528        process_count = samples.len(),
529        tracker_blocks = tracker_blocks,
530        tracker_pids = tracker_pids,
531        reaper_candidates = reaper_candidates,
532        reaper_first_seen = reaper_first_seen,
533        reaper_reaped_cumulative = reaper_reaped_cumulative,
534        "commit attribution"
535    );
536}
537
538/// Collect CPU usage (total + per-core).
539fn get_cpu_data(sys: &sysinfo::System, values: &mut HashMap<String, f64>) {
540    let cpus = sys.cpus();
541    if cpus.is_empty() {
542        return;
543    }
544    // Total CPU usage (average across all cores)
545    let total: f64 = cpus.iter().map(|c| c.cpu_usage() as f64).sum::<f64>() / cpus.len() as f64;
546    values.insert("cpu".to_string(), total);
547    // Per-core usage
548    for (idx, cpu) in cpus.iter().enumerate() {
549        values.insert(format!("cpu:{}", idx), cpu.cpu_usage() as f64);
550    }
551}
552
553/// Collect memory metrics (in GB).
554fn get_mem_data(sys: &sysinfo::System, values: &mut HashMap<String, f64>) {
555    let total = sys.total_memory() as f64 / BYTES_PER_GB;
556    let used = sys.used_memory() as f64 / BYTES_PER_GB;
557    let available = sys.available_memory() as f64 / BYTES_PER_GB;
558    let free = sys.free_memory() as f64 / BYTES_PER_GB;
559    values.insert("mem:total".to_string(), total);
560    values.insert("mem:used".to_string(), used);
561    values.insert("mem:available".to_string(), available);
562    values.insert("mem:free".to_string(), free);
563}
564
565/// Read the Windows commit budget via `GlobalMemoryStatusEx`.
566/// Emits `mem:commit:used` and `mem:commit:total` (in GB).
567/// No-op on non-Windows — keys are simply absent from the payload.
568fn get_commit_data(_values: &mut HashMap<String, f64>) {
569    #[cfg(target_os = "windows")]
570    {
571        use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
572        let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
573        mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
574        if unsafe { GlobalMemoryStatusEx(&mut mem) } != 0 {
575            let total_gb = mem.ullTotalPageFile as f64 / BYTES_PER_GB;
576            let avail_gb = mem.ullAvailPageFile as f64 / BYTES_PER_GB;
577            _values.insert("mem:commit:used".to_string(), total_gb - avail_gb);
578            _values.insert("mem:commit:total".to_string(), total_gb);
579        }
580    }
581}
582
583/// Available system commit headroom in GB (Windows: `GlobalMemoryStatusEx`
584/// → `ullAvailPageFile`). Returns `None` where there's no cheap commit figure
585/// (non-Windows) or the read fails — callers treat `None` as "no limit / admit".
586/// This is the admission-control signal for Pillar 3 (commit-aware agent spawn):
587/// see `agents::runner::admit_spawn` and `SPEC_WIN10_PAGEFILE_OOM_CRASH`.
588pub fn available_commit_gb() -> Option<f64> {
589    #[cfg(target_os = "windows")]
590    {
591        use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
592        let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
593        mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
594        if unsafe { GlobalMemoryStatusEx(&mut mem) } != 0 {
595            return Some(mem.ullAvailPageFile as f64 / BYTES_PER_GB);
596        }
597    }
598    None
599}
600
601// ── SPEC_WIN10_PAGEFILE_OOM_CRASH_2026_06_29 §5.2 P0 ──────────────────────────────────
602// "Track free disk on the pagefile volume, not just avail_page_gb. Warn when
603// free disk < ~15% and page file is system-managed." The existing commit
604// gauge above only sees the SYMPTOM (commit near limit); it is blind to the
605// CAUSE this spec found: a system-managed page file wants to grow toward
606// min(3×RAM, ⅛ volume) but silently cannot if the volume it lives on doesn't
607// have the free space, pinning the commit ceiling well below what every
608// other gauge assumes. This makes the cause itself visible.
609//
610// The registry-parsing + disk-free logic itself now lives in
611// `agentmux_common::pagefile` (extracted by
612// SPEC_RAM_PAGEFILE_PRESSURE_SPLIT_2026_08_07 §4) so `agentmux-cef`'s
613// low-memory banner can consume the identical implementation instead of a
614// second, independently-drifting copy — this file just wires it into the
615// StatusBar telemetry payload.
616
617/// Windows watch volume: the drive backing the page file. Emits the
618/// platform-neutral `disk:watch:free_gb` / `:total_gb` / `:free_pct`, plus
619/// `disk:pagefile_system_managed` (1.0/0.0), which stays Windows-named
620/// because it is a page-file fact and its ABSENCE is what tells the status
621/// bar it is not on Windows (see the colour tri-state in
622/// SPEC_STATUSBAR_DISK_PILL_CROSS_PLATFORM_2026_09_18 §3.3).
623///
624/// No-op (keys absent) on non-Windows or any read failure — matches
625/// `get_commit_data`'s fail-open convention. The Unix half of the same
626/// concept is `get_watch_volume_data` below.
627fn get_pagefile_volume_data(_values: &mut HashMap<String, f64>) {
628    #[cfg(target_os = "windows")]
629    {
630        let (drive, system_managed) = agentmux_common::pagefile::pagefile_watch_target();
631        if let Some((free_gb, total_gb)) = agentmux_common::pagefile::drive_free_total_gb(drive) {
632            _values.insert("disk:watch:free_gb".to_string(), free_gb);
633            _values.insert("disk:watch:total_gb".to_string(), total_gb);
634            if total_gb > 0.0 {
635                _values.insert(
636                    "disk:watch:free_pct".to_string(),
637                    (free_gb / total_gb) * 100.0,
638                );
639            }
640            _values.insert(
641                "disk:pagefile_system_managed".to_string(),
642                if system_managed { 1.0 } else { 0.0 },
643            );
644            // Marks which disk:vol:<mount>:* volume (get_disk_data) the
645            // pagefile-volume gauge above refers to, so the status bar can
646            // name the drive ("C:") in its Disk readout without a separate
647            // string channel — the values map is f64-only, so the letter
648            // rides in the key. Mount format matches sysinfo's Windows
649            // mount_point() ("C:\").
650            _values.insert(format!("disk:vol:{}:\\:watch", drive), 1.0);
651            // Whether the watched (page-file) volume is also the OS's own
652            // system drive -- usually true, but a custom PagingFiles entry
653            // can point the page file at a different volume than
654            // %SystemDrive% (e.g. `E:\pagefile.sys 0 0` with SystemDrive=C).
655            // Lets the status-bar tooltip say "system drive (C:)" only when
656            // that's actually true, rather than mislabeling a page-file-only
657            // volume as the system drive (reagent finding on #2479).
658            let is_system_drive = std::env::var("SystemDrive")
659                .ok()
660                .and_then(|s| s.chars().next())
661                .map(|c| c.to_ascii_uppercase() == drive)
662                .unwrap_or(false);
663            _values.insert(
664                format!("disk:vol:{}:\\:is_system_drive", drive),
665                if is_system_drive { 1.0 } else { 0.0 },
666            );
667        }
668    }
669}
670
671#[cfg(all(test, target_os = "windows"))]
672mod handle_anomaly_tests {
673    use super::*;
674
675    fn hsample(pid: u32, name: &str, handles: u32) -> HandleSample {
676        HandleSample { pid, name: name.to_string(), handles }
677    }
678
679    #[test]
680    fn healthy_baselines_trip_nothing() {
681        let samples = vec![
682            hsample(1, "agentmux-srv.exe", 950),
683            hsample(2, "svchost.exe", 3_000),
684            hsample(3, "chrome.exe", 11_000),
685        ];
686        assert!(classify_handle_anomalies(&samples).is_empty());
687    }
688
689    #[test]
690    fn agentmux_process_trips_at_the_lower_threshold() {
691        // The real 08-08 incident profile: an agentmux process far above
692        // its healthy baseline but an external process (chrome-scale) that
693        // is high-but-normal must not be flagged alongside it.
694        let samples = vec![
695            hsample(1, "agentmux-srv-0.54.10-windows.x64.exe", HANDLE_WARN_AGENTMUX),
696            hsample(2, "chrome.exe", HANDLE_WARN_AGENTMUX + 5_000),
697        ];
698        let anomalies = classify_handle_anomalies(&samples);
699        assert_eq!(anomalies.len(), 1);
700        assert!(anomalies[0].is_agentmux);
701        assert_eq!(anomalies[0].pid, 1);
702    }
703
704    #[test]
705    fn external_process_trips_only_at_the_higher_threshold() {
706        // The real 07-24 incident profile: Audiosrv's svchost at ~85K.
707        let samples = vec![hsample(9, "svchost.exe", 85_000)];
708        let anomalies = classify_handle_anomalies(&samples);
709        assert_eq!(anomalies.len(), 1);
710        assert!(!anomalies[0].is_agentmux);
711    }
712
713    #[test]
714    fn anomalies_are_sorted_worst_first() {
715        let samples = vec![
716            hsample(1, "agentmux-srv.exe", 25_000),
717            hsample(2, "svchost.exe", 85_000),
718        ];
719        let anomalies = classify_handle_anomalies(&samples);
720        assert_eq!(anomalies[0].pid, 2);
721        assert_eq!(anomalies[1].pid, 1);
722    }
723
724    #[test]
725    fn own_process_handle_count_is_queryable_and_nonzero() {
726        // Live smoke test of the winapi wrapper against this test process
727        // itself — a running process always has at least a few handles.
728        let count = process_handle_count(std::process::id());
729        assert!(count.is_some_and(|c| c > 0), "got {count:?}");
730    }
731
732    /// Regression test for the `sysinfo` v0.34.2 `CreateToolhelp32Snapshot`
733    /// handle leak (docs/status/STATUS_SRV_SECTION_HANDLE_LEAK_2026_08_08.md,
734    /// docs/status/STATUS_SRV_SECTION_HANDLE_LEAK_LIVE_RECURRENCE_2026_08_19.md).
735    /// That version's Windows `refresh_processes_specifics` never closed the
736    /// handle it got from `CreateToolhelp32Snapshot`, leaking one `Section`
737    /// object (kernel-charged, pagefile-backed) per call — invisible to this
738    /// process's own working-set/private-bytes, only visible as a climbing
739    /// `GetProcessHandleCount`. Repeats the exact call pattern
740    /// `run_sysinfo_loop` makes per tick (`ProcessesToUpdate::All`, the light
741    /// refresh kind used for the parent-link pass) many times and asserts
742    /// this process's own handle count does NOT grow linearly with call
743    /// count — a fixed `sysinfo` leaks ~0 handles/call; the broken 0.34.2
744    /// leaked exactly 1/call, so 500 calls would have shown +500, not "a
745    /// small bounded amount from unrelated one-time OS/runtime activity."
746    ///
747    /// The tests of one `cargo test` run share this process, so another test's
748    /// handles can inflate a window (nextest isolates them). A leak grows every
749    /// window, noise only some: it passes on the first window under the bar.
750    #[test]
751    fn refresh_processes_specifics_does_not_leak_a_handle_per_call() {
752        let pid = std::process::id();
753        let mut sys = sysinfo::System::new();
754        let mut refresh = |n: u32| {
755            for _ in 0..n {
756                sys.refresh_processes_specifics(ProcessesToUpdate::All, false, ProcessRefreshKind::nothing());
757            }
758        };
759        // Warm up: first call(s) can allocate one-time bookkeeping (e.g. the
760        // process list's initial capacity) that isn't part of the per-call
761        // leak this test is checking for.
762        refresh(5);
763        // A leak is one handle per call in every window; the count is the whole process's, so other tests add noise to some
764        // windows: many short ones, and one quiet one shows there is no leak.
765        const CALLS: u32 = 100; const WINDOWS: usize = 20;
766        let mut growth = Vec::new();
767        for _ in 0..WINDOWS {
768            let before = process_handle_count(pid).expect("own handle count must be queryable");
769            refresh(CALLS);
770            let after = process_handle_count(pid).expect("own handle count must be queryable");
771            let grew_by = after.saturating_sub(before);
772            if grew_by < CALLS / 2 {
773                return;
774            }
775            growth.push(grew_by);
776        }
777        panic!("handle count grew by {growth:?} over {WINDOWS} windows of {CALLS} refresh_processes_specifics calls: a per-call handle leak (the CreateToolhelp32Snapshot bug fixed in sysinfo 0.35.0 leaked a handle per call)");
778    }
779
780    fn anomaly(pid: u32) -> HandleAnomaly {
781        HandleAnomaly { pid, name: format!("proc{pid}.exe"), handles: 99_999, is_agentmux: false }
782    }
783
784    #[test]
785    fn cooldown_warns_immediately_on_first_sight_then_suppresses() {
786        let mut last = HashMap::new();
787        let t0 = Instant::now();
788        let cooldown = Duration::from_secs(600);
789        let anomalies = vec![anomaly(1)];
790
791        assert_eq!(filter_anomalies_for_warn(&anomalies, &mut last, t0, cooldown), vec![0]);
792        // Same anomaly, next 30s cycle — suppressed.
793        let t1 = t0 + Duration::from_secs(30);
794        assert!(filter_anomalies_for_warn(&anomalies, &mut last, t1, cooldown).is_empty());
795        // Past the cooldown — warns again.
796        let t2 = t0 + cooldown;
797        assert_eq!(filter_anomalies_for_warn(&anomalies, &mut last, t2, cooldown), vec![0]);
798    }
799
800    #[test]
801    fn cooldown_is_per_pid_not_global() {
802        let mut last = HashMap::new();
803        let t0 = Instant::now();
804        let cooldown = Duration::from_secs(600);
805
806        assert_eq!(filter_anomalies_for_warn(&[anomaly(1)], &mut last, t0, cooldown), vec![0]);
807        // A DIFFERENT pid appearing 30s later warns immediately, even though
808        // pid 1 is mid-cooldown.
809        let t1 = t0 + Duration::from_secs(30);
810        let both = vec![anomaly(1), anomaly(2)];
811        assert_eq!(filter_anomalies_for_warn(&both, &mut last, t1, cooldown), vec![1]);
812    }
813
814    #[test]
815    fn recovered_pid_recrossing_the_threshold_warns_immediately() {
816        let mut last = HashMap::new();
817        let t0 = Instant::now();
818        let cooldown = Duration::from_secs(600);
819
820        assert_eq!(filter_anomalies_for_warn(&[anomaly(1)], &mut last, t0, cooldown), vec![0]);
821        // pid 1 drops below threshold (absent from anomalies) — its entry is
822        // pruned...
823        let t1 = t0 + Duration::from_secs(30);
824        assert!(filter_anomalies_for_warn(&[], &mut last, t1, cooldown).is_empty());
825        assert!(last.is_empty(), "healthy pid's entry must be pruned");
826        // ...so re-crossing 30s later (well inside what would have been the
827        // old cooldown window) warns immediately.
828        let t2 = t0 + Duration::from_secs(60);
829        assert_eq!(filter_anomalies_for_warn(&[anomaly(1)], &mut last, t2, cooldown), vec![0]);
830    }
831}
832
833#[cfg(all(test, target_os = "windows"))]
834mod commit_attribution_tests {
835    use super::*;
836
837    fn sample(pid: u32, name: &str, commit_mb: f64) -> ProcSample {
838        ProcSample { pid, name: name.to_string(), commit_mb, own: true }
839    }
840
841    fn foreign(pid: u32, name: &str, commit_mb: f64) -> ProcSample {
842        ProcSample { pid, name: name.to_string(), commit_mb, own: false }
843    }
844
845    #[test]
846    fn another_instances_agentmux_processes_are_other_not_ours() {
847        // A stable install running beside this dev build: its agentmux*
848        // processes are named the same but are not this instance's.
849        let samples = vec![
850            sample(201, "agentmux-srv-0.59.31-windows.x64.exe", 90.0),
851            sample(202, "agentmux-cef.exe", 300.0),
852            foreign(101, "agentmux-srv-0.59.30-windows.x64.exe", 120.0),
853            foreign(102, "agentmux-cef.exe", 900.0),
854        ];
855        let result = classify_commit_attribution(&samples, &HashSet::new(), 5);
856        assert_eq!(result.agentmux_mb, 390.0, "only this instance's processes");
857        assert_eq!(result.other_mb, 1020.0, "the other instance is counted, under other");
858        assert_eq!(result.panes_mb, 0.0);
859    }
860
861    #[test]
862    fn buckets_agentmux_by_name_regardless_of_pane_membership() {
863        // Name match wins even if (hypothetically) a PID also showed up in
864        // a pane's descendant tree — AgentMux's own processes are never
865        // "pane" work, no matter how the tree walk found them.
866        let samples = vec![sample(100, "agentmux-cef.exe", 500.0)];
867        let mut pane_pids = HashSet::new();
868        pane_pids.insert(100);
869        let result = classify_commit_attribution(&samples, &pane_pids, 5);
870        assert_eq!(result.agentmux_mb, 500.0);
871        assert_eq!(result.panes_mb, 0.0);
872    }
873
874    #[test]
875    fn buckets_pane_pids_by_membership_not_name() {
876        // A pane's process tree (e.g. node.exe running Claude Code) is
877        // classified by exact PID membership, not by guessing its name.
878        let samples = vec![sample(200, "node.exe", 300.0), sample(201, "conhost.exe", 10.0)];
879        let mut pane_pids = HashSet::new();
880        pane_pids.insert(200);
881        pane_pids.insert(201);
882        let result = classify_commit_attribution(&samples, &pane_pids, 5);
883        assert_eq!(result.panes_mb, 310.0);
884        assert_eq!(result.agentmux_mb, 0.0);
885        assert!(result.other_top.is_empty());
886    }
887
888    #[test]
889    fn everything_else_falls_to_other_ranked_and_capped() {
890        let samples = vec![
891            sample(1, "chrome.exe", 800.0),
892            sample(2, "Code.exe", 600.0),
893            sample(3, "Docker Desktop.exe", 1200.0),
894            sample(4, "explorer.exe", 150.0),
895        ];
896        let result = classify_commit_attribution(&samples, &HashSet::new(), 2);
897        // Total is preserved even though the printed list is capped.
898        assert_eq!(result.other_mb, 800.0 + 600.0 + 1200.0 + 150.0);
899        // Only the top 2 (by commit) are kept for the log line, descending.
900        assert_eq!(result.other_top.len(), 2);
901        assert_eq!(result.other_top[0].0, "Docker Desktop.exe");
902        assert_eq!(result.other_top[1].0, "chrome.exe");
903    }
904
905    #[test]
906    fn aggregates_other_by_name_before_ranking_so_a_multi_process_app_is_not_split_below_the_cutoff() {
907        // A multi-process app (Chrome, VS Code) spread across many small
908        // per-PID entries must still rank by its TOTAL commit, not have each
909        // PID compete individually against single-process apps — otherwise
910        // the true top contributor can be missing from other_top even
911        // though other_mb (the sum) correctly reflects it. reagent P1 on
912        // PR #2207.
913        let samples = vec![
914            sample(1, "chrome.exe", 100.0),
915            sample(2, "chrome.exe", 100.0),
916            sample(3, "chrome.exe", 100.0),
917            sample(4, "chrome.exe", 100.0),
918            sample(5, "single_app.exe", 250.0),
919        ];
920        let result = classify_commit_attribution(&samples, &HashSet::new(), 1);
921        assert_eq!(result.other_mb, 650.0);
922        assert_eq!(result.other_top.len(), 1);
923        assert_eq!(result.other_top[0], ("chrome.exe".to_string(), 400.0));
924    }
925
926    #[test]
927    fn name_match_is_case_insensitive() {
928        let samples = vec![sample(1, "AgentMux-Srv.exe", 42.0)];
929        let result = classify_commit_attribution(&samples, &HashSet::new(), 5);
930        assert_eq!(result.agentmux_mb, 42.0);
931    }
932
933    #[test]
934    fn empty_process_list_yields_zeroed_result() {
935        let result = classify_commit_attribution(&[], &HashSet::new(), 5);
936        assert_eq!(result.agentmux_mb, 0.0);
937        assert_eq!(result.panes_mb, 0.0);
938        assert_eq!(result.other_mb, 0.0);
939        assert!(result.other_top.is_empty());
940    }
941
942    /// Runs the real Win32 process-enumeration path against this machine's
943    /// actual process table — the synthetic-data tests above cover
944    /// classification logic but can't catch a bad Win32 API call, an
945    /// access-denied edge case, or a panic on a real process's field
946    /// values. This test's own process is guaranteed to exist in the table
947    /// with a real name and non-zero commit, so a classification bucket is
948    /// exercised end-to-end for real.
949    #[test]
950    fn log_memory_attribution_runs_against_the_real_process_table_without_panicking() {
951        let mut sys = sysinfo::System::new_all();
952        log_memory_attribution(&mut sys, 0.0, 0.0); // must not panic
953        assert!(
954            sys.processes().len() > 1,
955            "expected the real process table to have picked up more than just this test binary"
956        );
957    }
958}
959
960/// Network I/O tracking state for rate calculations.
961pub(crate) struct NetState {
962    prev_sent: u64,
963    prev_recv: u64,
964    prev_time: Option<Instant>,
965}
966
967impl NetState {
968    pub(crate) fn new() -> Self {
969        Self {
970            prev_sent: 0,
971            prev_recv: 0,
972            prev_time: None,
973        }
974    }
975
976    /// Collect network I/O rates (in MB/s).
977    fn get_net_data(&mut self, totals: (u64, u64), values: &mut HashMap<String, f64>) {
978        self.get_net_data_at(Instant::now(), totals, values);
979    }
980
981    /// The rates over the real time since the last read, so a late tick gives the
982    /// average over its longer interval, not a spike or a hole.
983    pub(crate) fn get_net_data_at(&mut self, now: Instant, (total_sent, total_recv): (u64, u64), values: &mut HashMap<String, f64>) {
984        if let Some(prev_time) = self.prev_time {
985            let elapsed = now.duration_since(prev_time).as_secs_f64();
986            if elapsed > 0.0 {
987                let sent_rate = (total_sent.saturating_sub(self.prev_sent)) as f64 / elapsed / BYTES_PER_MB;
988                let recv_rate = (total_recv.saturating_sub(self.prev_recv)) as f64 / elapsed / BYTES_PER_MB;
989                values.insert("net:bytessent".to_string(), sent_rate);
990                values.insert("net:bytesrecv".to_string(), recv_rate);
991                values.insert("net:bytestotal".to_string(), sent_rate + recv_rate);
992            }
993        }
994
995        self.prev_sent = total_sent;
996        self.prev_recv = total_recv;
997        self.prev_time = Some(now);
998    }
999}
1000
1001/// Collect disk I/O rates (in MB/s).
1002/// sysinfo Disk::usage() returns deltas (bytes since last refresh) so we
1003/// divide by elapsed time to get rates.
1004fn get_disk_data(disks: &Disks, elapsed_secs: f64, values: &mut HashMap<String, f64>) {
1005    // Per-volume capacity/free, keyed by mount point:
1006    //   disk:vol:<mount>:free_gb / disk:vol:<mount>:total_gb
1007    // (e.g. `disk:vol:C:\:free_gb` — the mount's own colons/backslashes are
1008    // fine inside the key; consumers anchor on the `disk:vol:` prefix and the
1009    // known suffix). Feeds the status bar's Disk popover (per-drive free
1010    // space). Deduped by mount point — sysinfo can list one volume once per
1011    // physical disk it spans — and zero-capacity entries (empty card
1012    // readers, unformatted media) are skipped rather than shown as "0G".
1013    let mut seen_mounts: HashSet<&std::path::Path> = HashSet::new();
1014    for disk in disks.list() {
1015        let mount = disk.mount_point();
1016        if !seen_mounts.insert(mount) {
1017            continue;
1018        }
1019        let total = disk.total_space();
1020        if total == 0 {
1021            continue;
1022        }
1023        let mount_str = mount.to_string_lossy();
1024        values.insert(
1025            format!("disk:vol:{}:free_gb", mount_str),
1026            disk.available_space() as f64 / BYTES_PER_GB,
1027        );
1028        values.insert(
1029            format!("disk:vol:{}:total_gb", mount_str),
1030            total as f64 / BYTES_PER_GB,
1031        );
1032    }
1033
1034    if elapsed_secs <= 0.0 {
1035        return;
1036    }
1037    let (total_read, total_write) = disks.list().iter().fold((0u64, 0u64), |(r, w), disk| {
1038        let u = disk.usage();
1039        (r + u.read_bytes, w + u.written_bytes)
1040    });
1041    let read_rate = total_read as f64 / elapsed_secs / BYTES_PER_MB;
1042    let write_rate = total_write as f64 / elapsed_secs / BYTES_PER_MB;
1043    values.insert("disk:read".to_string(), read_rate);
1044    values.insert("disk:write".to_string(), write_rate);
1045    values.insert("disk:total".to_string(), read_rate + write_rate);
1046}
1047
1048/// Pick the mount whose path is the longest prefix of `target`.
1049///
1050/// Pure, and separated from `Disks` so it is testable without a real
1051/// filesystem. Longest-prefix rather than first-match because several mounts
1052/// legitimately prefix one path (`/` and `/home` both prefix
1053/// `/home/yas/.agentmux`) and the most specific one is the filesystem whose
1054/// free space actually constrains a write there.
1055#[cfg(not(target_os = "windows"))]
1056fn pick_watch_mount<'a>(mounts: &[&'a std::path::Path], target: &std::path::Path) -> Option<&'a std::path::Path> {
1057    mounts
1058        .iter()
1059        .filter(|m| target.starts_with(m))
1060        .max_by_key(|m| m.as_os_str().len())
1061        .copied()
1062}
1063
1064/// Unix watch volume: the mount backing AgentMux's data dir — where the
1065/// store, logs and packaged builds land, so it is the volume whose filling up
1066/// actually breaks this app.
1067///
1068/// Emits the same `disk:watch:*` summary and `disk:vol:<mount>:watch` /
1069/// `:is_system_drive` markers the Windows path emits, so the status bar is
1070/// platform-agnostic. Costs no syscall: it reads the `Disks` list already
1071/// refreshed this tick, and reuses the free/total `get_disk_data` just
1072/// computed rather than re-reading them.
1073#[cfg(not(target_os = "windows"))]
1074fn get_watch_volume_data(disks: &Disks, values: &mut HashMap<String, f64>) {
1075    let data_dir = crate::backend::base::get_mux_data_dir();
1076    let mounts: Vec<&std::path::Path> = disks.list().iter().map(|d| d.mount_point()).collect();
1077    let root = std::path::Path::new("/");
1078    let watch = pick_watch_mount(&mounts, &data_dir).unwrap_or(root);
1079
1080    write_watch_summary(watch, watch == root, values);
1081}
1082
1083/// Summarise one already-collected volume as the watch target.
1084///
1085/// Reads the `disk:vol:<mount>:*` figures `get_disk_data` wrote rather than
1086/// re-deriving them, which keeps the pill and the popover row arithmetically
1087/// identical by construction. Pure w.r.t. the map, so the partial-tick
1088/// behaviour below is testable.
1089///
1090/// A mount `get_disk_data` skipped (zero capacity, torn tick) has no figures
1091/// to summarise: emit nothing rather than a fabricated 0, matching
1092/// `parseDiskVolumes`, which drops partial volumes for the same reason.
1093#[cfg(not(target_os = "windows"))]
1094fn write_watch_summary(mount: &std::path::Path, is_system_drive: bool, values: &mut HashMap<String, f64>) {
1095    let mount_str = mount.to_string_lossy();
1096    let (Some(free_gb), Some(total_gb)) = (
1097        values.get(&format!("disk:vol:{mount_str}:free_gb")).copied(),
1098        values.get(&format!("disk:vol:{mount_str}:total_gb")).copied(),
1099    ) else {
1100        return;
1101    };
1102    if total_gb <= 0.0 {
1103        return;
1104    }
1105
1106    values.insert("disk:watch:free_gb".to_string(), free_gb);
1107    values.insert("disk:watch:total_gb".to_string(), total_gb);
1108    values.insert("disk:watch:free_pct".to_string(), (free_gb / total_gb) * 100.0);
1109    values.insert(format!("disk:vol:{mount_str}:watch"), 1.0);
1110    values.insert(
1111        format!("disk:vol:{mount_str}:is_system_drive"),
1112        if is_system_drive { 1.0 } else { 0.0 },
1113    );
1114}
1115
1116/// Read the telemetry interval from config, clamped to [MIN, MAX].
1117fn get_interval_secs(config_watcher: &ConfigState) -> f64 {
1118    let val = config_watcher.get_settings().telemetry_interval;
1119    if val <= 0.0 {
1120        return DEFAULT_INTERVAL_SECS;
1121    }
1122    val.clamp(MIN_INTERVAL_SECS, MAX_INTERVAL_SECS)
1123}
1124
1125/// Run the sysinfo collection loop until `stop` is set. It must run on a runtime
1126/// of its own (`sampler::thread`), not srv's: every read below blocks its thread,
1127/// and a sampler that waits for a free worker in the runtime it measures is late
1128/// exactly when the machine is busiest. The interval is re-read from config each
1129/// tick.
1130pub async fn run_sysinfo_loop(
1131    broker: Arc<Broker>,
1132    config_watcher: Arc<ConfigState>,
1133    conn_name: String,
1134    panes: crate::backend::sampler::panes::PaneSampler,
1135    stop: Arc<AtomicBool>,
1136) {
1137    // CPU and memory only: `new_all()` also kept a full snapshot of every process.
1138    let kind = sysinfo::RefreshKind::everything().without_processes();
1139    let mut sys = sysinfo::System::new_with_specifics(kind);
1140    let mut networks = NetCounters::new();
1141    let mut net_state = NetState::new();
1142    let mut disks = Disks::new_with_refreshed_list();
1143    let mut last_disk_full_refresh = Instant::now();
1144    let mut last_tick = Instant::now();
1145    // Commit-attribution cadence (see "Commit (pagefile) attribution" above): starts due-now-minus-interval, so the
1146    // first snapshot sets a baseline soon after startup. Windows-only, like the loop body below.
1147    #[cfg(target_os = "windows")]
1148    let mut last_attribution = Instant::now()
1149        .checked_sub(ATTRIBUTION_INTERVAL)
1150        .unwrap_or_else(Instant::now);
1151    #[cfg(target_os = "windows")]
1152    let mut last_urgent_attribution: Option<Instant> = None;
1153
1154    // Each pane badge's highest memory, for its tooltip.
1155    let mut peaks = crate::backend::blockstats_detail::Peaks::default();
1156
1157    // What to measure and how often: a source runs only while something holds a
1158    // lease on it (backend/sampler). The machine's counters are the baseline. The
1159    // panes' processes run at the telemetry rate only while a pane badge is
1160    // subscribed, and otherwise just often enough to evict a pane whose shell has
1161    // died. docs/reports/REPORT_SYSINFO_REWRITE_AND_MODERN_MONITOR_2026_10_13.md
1162    // section 5.5.
1163    let epoch = Instant::now();
1164    let since_epoch = |t: Instant| t.duration_since(epoch).as_millis() as u64;
1165    let min_interval_ms = (MIN_INTERVAL_SECS * 1000.0) as u64;
1166    let mut sched = Scheduler::new(
1167        vec![
1168            // Never stretched: the machine's counters are what the CPU chart shows,
1169            // and a busy machine is exactly when they must keep coming. Only the
1170            // costly pane scan slows down under load.
1171            SourceSpec { id: SourceId::Machine, min_interval_ms, budget_ms: NEVER_STRETCHED, needs: &[] },
1172            SourceSpec { id: SourceId::Panes, min_interval_ms, budget_ms: 400, needs: &[] },
1173        ],
1174        SCHEDULER_COALESCE_MS,
1175    );
1176    let mut watched = false;
1177    let mut late_ticks = crate::backend::sampler::late_tick::LateTickLog::default();
1178    let mut current_interval = get_interval_secs(&config_watcher);
1179    sched.lease(HOLDER_TELEMETRY, SourceId::Machine, (current_interval * 1000.0) as u64, None, 0);
1180    sched.lease(HOLDER_JANITOR, SourceId::Panes, PANE_JANITOR_MS, None, 0);
1181    // Both start one interval in: the CPU counters need two reads to mean anything.
1182    sched.finished(SourceId::Machine, 0, 0);
1183    sched.finished(SourceId::Panes, 0, 0);
1184
1185    tracing::info!("sysinfo loop started for conn:{}", conn_name);
1186
1187    while !stop.load(Ordering::Relaxed) {
1188        let now_ms = since_epoch(Instant::now());
1189        let new_interval = get_interval_secs(&config_watcher);
1190        if (new_interval - current_interval).abs() > 0.001 {
1191            current_interval = new_interval;
1192            tracing::info!("sysinfo interval changed to {}s", current_interval);
1193        }
1194        let interval_ms = (current_interval * 1000.0) as u64;
1195        sched.lease(HOLDER_TELEMETRY, SourceId::Machine, interval_ms, None, now_ms);
1196        let has_viewers = broker.has_subscribers(crate::backend::mps::EVENT_BLOCK_STATS);
1197        if has_viewers {
1198            sched.lease(HOLDER_BADGES, SourceId::Panes, interval_ms, None, now_ms);
1199        } else {
1200            sched.release_source(HOLDER_BADGES, SourceId::Panes, now_ms);
1201        }
1202        if has_viewers != watched {
1203            watched = has_viewers;
1204            tracing::debug!(watched, "sysinfo: pane stats {}", if watched { "have a viewer" } else { "have no viewer" });
1205        }
1206        let planned = sched.planned_wakeup(now_ms).unwrap_or(now_ms + interval_ms);
1207        let wake = sched.next_wakeup(now_ms).unwrap_or(now_ms + interval_ms);
1208        if wake > now_ms {
1209            tokio::time::sleep_until(tokio::time::Instant::from_std(epoch + Duration::from_millis(wake))).await;
1210        }
1211        let woke_ms = since_epoch(Instant::now());
1212        if let Some(late) = late_ticks.check(planned, woke_ms) {
1213            tracing::warn!(late_ms = late.late_ms, also_late = late.also, "sysinfo: a tick ran late; a chart breaks after 3 s without a sample");
1214        }
1215        let due = sched.due(woke_ms);
1216
1217        if due.contains(&SourceId::Machine) {
1218            let run_started = Instant::now();
1219            // Refresh all metrics: synchronous reads of the OS's counters, on the sampler's own
1220            // thread, so blocking holds nothing else up (`get_pagefile_volume_data` is a disk syscall).
1221            let mut pagefile_values = HashMap::new();
1222            sys.refresh_cpu_usage();
1223            // RAM only: the swap figures cost a whole-system query and nothing reads them.
1224            sys.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
1225            let net_totals = networks.totals();
1226            if last_disk_full_refresh.elapsed() >= DISK_FULL_REFRESH {
1227                disks.refresh(true);
1228                last_disk_full_refresh = Instant::now();
1229            } else {
1230                for disk in disks.list_mut() {
1231                    disk.refresh_specifics(DiskRefreshKind::nothing().with_io_usage());
1232                }
1233            }
1234            get_pagefile_volume_data(&mut pagefile_values);
1235
1236            let now_instant = Instant::now();
1237            let elapsed_secs = now_instant.duration_since(last_tick).as_secs_f64();
1238            last_tick = now_instant;
1239
1240            let mut values = pagefile_values;
1241            // What the rates below average over: a late tick's is long, and the chart draws it as a step.
1242            values.insert(SAMPLE_WINDOW_KEY.to_string(), elapsed_secs * 1000.0);
1243            get_cpu_data(&sys, &mut values);
1244            crate::backend::sampler::own_processes::sample_into(sys.cpus().len(), &mut values);
1245            get_mem_data(&sys, &mut values);
1246            get_commit_data(&mut values);
1247            net_state.get_net_data(net_totals, &mut values);
1248            get_disk_data(&disks, elapsed_secs, &mut values);
1249            crate::backend::gpu::add_compact_values(&mut values);
1250            // Must follow get_disk_data: it summarises the per-volume figures that
1251            // call just wrote. The Windows equivalent already ran with the
1252            // machine reads above (it makes a real syscall); this one does not.
1253            #[cfg(not(target_os = "windows"))]
1254            get_watch_volume_data(&disks, &mut values);
1255
1256            // Commit attribution: periodic in the steady state, or immediately
1257            // (debounced) when commit heads toward exhaustion — see
1258            // docs/retro/retro-subagent-backfill-storm-oom-2026-07-17.md. Reuses
1259            // the commit numbers just computed above rather than re-querying.
1260            // Windows-only like every other commit/pagefile helper in this file
1261            // (get_commit_data, available_commit_gb, get_pagefile_volume_data) —
1262            // its rationale (pagefile/commit exhaustion) doesn't apply elsewhere,
1263            // and off-Windows `mem:commit:*` are never populated, so this would
1264            // otherwise pay a full process-table refresh every tick just to log
1265            // a permanently-zero commit_used_gb/commit_total_gb.
1266            #[cfg(target_os = "windows")]
1267            {
1268                let commit_avail_gb = match (values.get("mem:commit:total"), values.get("mem:commit:used")) {
1269                    (Some(total), Some(used)) => Some(total - used),
1270                    _ => None,
1271                };
1272                let due_periodic = now_instant.duration_since(last_attribution) >= ATTRIBUTION_INTERVAL;
1273                let due_urgent = commit_avail_gb.is_some_and(|gb| gb < ATTRIBUTION_URGENT_THRESHOLD_GB)
1274                    && last_urgent_attribution
1275                        .is_none_or(|t| now_instant.duration_since(t) >= ATTRIBUTION_URGENT_COOLDOWN);
1276                if due_periodic || due_urgent {
1277                    let commit_used_gb = *values.get("mem:commit:used").unwrap_or(&0.0);
1278                    let commit_total_gb = *values.get("mem:commit:total").unwrap_or(&0.0);
1279                    log_memory_attribution(&mut sys, commit_used_gb, commit_total_gb);
1280                    last_attribution = now_instant;
1281                    if due_urgent {
1282                        last_urgent_attribution = Some(now_instant);
1283                    }
1284                }
1285            }
1286
1287            let now = agentmux_common::time::now_ms();
1288
1289            let ts_data = TimeSeriesData { ts: now, values, uptime_secs: Some(uptime_secs()) };
1290
1291            broker.publish_event::<crate::backend::mps_events::SysInfo>(&ts_data, vec![conn_name.clone()], PERSIST_COUNT);
1292            sched.finished(SourceId::Machine, since_epoch(run_started), run_started.elapsed().as_millis() as u64);
1293        }
1294
1295        if due.contains(&SourceId::Panes) {
1296            let run_started = Instant::now();
1297            let now = agentmux_common::time::now_ms();
1298            // Each pane's processes as Tower groups them (its Job Object or cgroup,
1299            // else its shell's tree), from Tower's own sample, so the badge, its
1300            // detail and Tower count the same processes (`sampler::panes`).
1301            // Read before the sample: a shell registered after it was read can't be
1302            // judged by it.
1303            let registered = pidregistry::get_all();
1304            let asked = Instant::now();
1305            match panes() {
1306                Ok(stats) => {
1307                    peaks.retain(|id| stats.iter().any(|s| s.block_id == id));
1308                    for s in &stats {
1309                        let mut values = HashMap::new();
1310                        if let Some(cpu) = s.cpu_pct {
1311                            values.insert("cpu".to_string(), cpu);
1312                        }
1313                        values.insert("mem".to_string(), s.mem as f64);
1314                        values.insert("pids".to_string(), f64::from(s.pids));
1315                        let peak = peaks.observe(&s.block_id, s.shell, s.mem);
1316                        values.insert("mem:peak".to_string(), peak as f64);
1317                        // Per-block process stats, not the backend's own uptime.
1318                        let block_ts = TimeSeriesData { ts: now, values, uptime_secs: None };
1319                        broker.publish_event::<crate::backend::mps_events::BlockStats>(
1320                            &block_ts,
1321                            vec![format!("block:{}", s.block_id)],
1322                            0,
1323                        );
1324                    }
1325                }
1326                Err(e) => tracing::debug!(error = %e, "sysinfo: pane stats sample failed"),
1327            }
1328            // Last-resort cleanup for a shell that exited without the normal
1329            // teardown (killed by the OS, a crash, a stop() race): its PID is
1330            // missing from a process table read after it was registered. Only a
1331            // sample taken in this pass counts; a reused or failed one is skipped,
1332            // and the next pass decides.
1333            if let Some(live) = crate::backend::tower::sampler::Tower::global().live_pids_since(asked) {
1334                for (block_id, pid) in registered {
1335                    if !live.contains(&pid) {
1336                        pidregistry::unregister(&block_id);
1337                        tracing::warn!(
1338                            block_id = %block_id,
1339                            "sysinfo: evicted dead root PID — process exited without normal cleanup"
1340                        );
1341                    }
1342                }
1343            }
1344            sched.finished(SourceId::Panes, since_epoch(run_started), run_started.elapsed().as_millis() as u64);
1345        }
1346    }
1347}
1348
1349#[cfg(test)]
1350mod uptime_tests {
1351    use super::*;
1352
1353    /// Neither property this fix depends on — immunity to a clock step, and
1354    /// counting across suspend — can be asserted in a unit test: the platform
1355    /// counters are deliberately unsettable, and suspending the machine isn't
1356    /// something a test can do. What IS assertable: the marker is idempotent
1357    /// (a stray second call can't restart the clock) and the value never runs
1358    /// backwards. The `u64` return type is itself part of the fix — the old
1359    /// wall-clock subtraction was signed and reached about -1.7e9.
1360    #[test]
1361    fn uptime_is_monotonic_and_the_start_marker_is_idempotent() {
1362        mark_process_start();
1363        let first = uptime_secs();
1364        mark_process_start();
1365        let second = uptime_secs();
1366        assert!(second >= first, "uptime went backwards: {second} < {first}");
1367    }
1368
1369    /// The suspend-aware counter must be a sane, forward-running millisecond
1370    /// source on whatever platform this is built for — a `clock_gettime`
1371    /// failure returning 0, or a units mix-up, would show up here.
1372    #[test]
1373    fn suspend_aware_clock_is_nonzero_and_never_decreases() {
1374        let a = suspend_aware_now_ms();
1375        let b = suspend_aware_now_ms();
1376        assert!(a > 0, "suspend-aware clock returned 0 — clock_gettime failed?");
1377        assert!(b >= a, "suspend-aware clock went backwards: {b} < {a}");
1378        // Sanity on units: a machine that booted more than ~10 years ago is a
1379        // units error (ns or µs mistaken for ms), not a real uptime.
1380        assert!(a < 10 * 365 * 24 * 60 * 60 * 1_000, "implausible ms reading: {a}");
1381    }
1382
1383    /// The frontend's fallback path keys off this field's ABSENCE, and the
1384    /// per-block stats / CPU-stream payloads must keep their exact prior
1385    /// shape — so `skip_serializing_if` is a wire contract, not a style choice.
1386    #[test]
1387    fn uptime_secs_is_emitted_when_present_and_omitted_when_absent() {
1388        let with = TimeSeriesData { ts: 5, values: HashMap::new(), uptime_secs: Some(42) };
1389        let v = serde_json::to_value(&with).expect("serialize");
1390        assert_eq!(v["uptime_secs"], serde_json::json!(42));
1391
1392        let without = TimeSeriesData { ts: 5, values: HashMap::new(), uptime_secs: None };
1393        let v = serde_json::to_value(&without).expect("serialize");
1394        assert!(
1395            v.get("uptime_secs").is_none(),
1396            "block-stats/CPU-stream payload shape must be byte-for-byte unchanged"
1397        );
1398    }
1399
1400    /// A payload produced before this field existed (e.g. replayed from the
1401    /// sysinfo persist ring across an upgrade) must still deserialize.
1402    #[test]
1403    fn payload_without_uptime_still_deserializes() {
1404        let json = serde_json::json!({ "ts": 7, "values": { "cpu": 1.5 } });
1405        let parsed: TimeSeriesData = serde_json::from_value(json).expect("deserialize");
1406        assert_eq!(parsed.ts, 7);
1407        assert_eq!(parsed.uptime_secs, None);
1408    }
1409}
1410
1411#[cfg(all(test, not(target_os = "windows")))]
1412mod watch_volume_tests {
1413    use super::*;
1414    use std::path::Path;
1415
1416    /// The case that motivated longest-prefix: `/` also prefixes the data
1417    /// dir, and picking it would report free space on the wrong filesystem
1418    /// whenever `/home` is separately mounted.
1419    #[test]
1420    fn longest_prefix_wins_over_root() {
1421        let mounts = [Path::new("/"), Path::new("/home"), Path::new("/boot")];
1422        let got = pick_watch_mount(&mounts, Path::new("/home/yas/.agentmux"));
1423        assert_eq!(got, Some(Path::new("/home")));
1424    }
1425
1426    #[test]
1427    fn falls_back_to_root_when_nothing_more_specific_matches() {
1428        let mounts = [Path::new("/"), Path::new("/boot")];
1429        let got = pick_watch_mount(&mounts, Path::new("/home/yas/.agentmux"));
1430        assert_eq!(got, Some(Path::new("/")));
1431    }
1432
1433    #[test]
1434    fn exact_mount_matches_itself() {
1435        let mounts = [Path::new("/"), Path::new("/data")];
1436        assert_eq!(pick_watch_mount(&mounts, Path::new("/data")), Some(Path::new("/data")));
1437    }
1438
1439    /// A sibling must never match: `/home2` is not a prefix of `/home/yas`,
1440    /// and a naive string `starts_with` would say it is.
1441    #[test]
1442    fn sibling_mount_is_not_a_prefix() {
1443        let mounts = [Path::new("/home2")];
1444        assert_eq!(pick_watch_mount(&mounts, Path::new("/home/yas")), None);
1445    }
1446
1447    #[test]
1448    fn empty_mount_list_yields_none() {
1449        assert_eq!(pick_watch_mount(&[], Path::new("/home/yas")), None);
1450    }
1451
1452    /// Summary keys are derived from what `get_disk_data` already wrote, so a
1453    /// volume it skipped (zero capacity, torn tick) summarises to nothing
1454    /// rather than a fabricated zero.
1455    #[test]
1456    fn partial_volume_emits_no_summary() {
1457        let mut values: HashMap<String, f64> = HashMap::new();
1458        // total_gb present, free_gb missing — a torn tick.
1459        values.insert("disk:vol:/:total_gb".to_string(), 100.0);
1460        write_watch_summary(Path::new("/"), true, &mut values);
1461        assert!(!values.keys().any(|k| k.starts_with("disk:watch:")));
1462    }
1463
1464    #[test]
1465    fn zero_capacity_volume_emits_no_summary() {
1466        let mut values: HashMap<String, f64> = HashMap::new();
1467        values.insert("disk:vol:/:free_gb".to_string(), 0.0);
1468        values.insert("disk:vol:/:total_gb".to_string(), 0.0);
1469        write_watch_summary(Path::new("/"), true, &mut values);
1470        assert!(!values.keys().any(|k| k.starts_with("disk:watch:")));
1471    }
1472
1473    /// The percentage must be derived from the same figures the popover row
1474    /// shows, or the pill and the row can disagree about the same drive.
1475    #[test]
1476    fn summary_matches_the_per_volume_figures() {
1477        let mut values: HashMap<String, f64> = HashMap::new();
1478        values.insert("disk:vol:/home:free_gb".to_string(), 35.0);
1479        values.insert("disk:vol:/home:total_gb".to_string(), 350.0);
1480        write_watch_summary(Path::new("/home"), false, &mut values);
1481
1482        assert_eq!(values["disk:watch:free_gb"], 35.0);
1483        assert_eq!(values["disk:watch:total_gb"], 350.0);
1484        assert!((values["disk:watch:free_pct"] - 10.0).abs() < 1e-9);
1485        assert_eq!(values["disk:vol:/home:watch"], 1.0);
1486        assert_eq!(values["disk:vol:/home:is_system_drive"], 0.0);
1487    }
1488
1489    #[test]
1490    fn root_watch_volume_is_marked_as_the_system_drive() {
1491        let mut values: HashMap<String, f64> = HashMap::new();
1492        values.insert("disk:vol:/:free_gb".to_string(), 1.9);
1493        values.insert("disk:vol:/:total_gb".to_string(), 345.0);
1494        write_watch_summary(Path::new("/"), true, &mut values);
1495        assert_eq!(values["disk:vol:/:is_system_drive"], 1.0);
1496        // The night this spec was written: 0.55% free, and nothing said so.
1497        assert!(values["disk:watch:free_pct"] < 1.0);
1498    }
1499}