Skip to main content

oomtop_core/
model.rs

1//! The oomtop data model (SPEC §5). **FROZEN**: additive changes only.
2//!
3//! New fields must be `Option<_>` or carry a serde default (every struct here is `#[serde(default)]` and
4//! implements `Default`), so older JSON keeps deserializing and older consumers ignore new fields.
5//!
6//! Invariants:
7//! - Every *measured* number is a [`Measured<T>`] carrying `source` and `quality`; an unavailable value is
8//!   `value: None` + `Quality::Unavailable(reason)` and is never rendered as zero.
9//! - Bytes are `u64`, times are milliseconds since the Unix epoch (`*_ms`) or seconds (`*_s`).
10//! - Process identity is always [`ProcId`] `(pid, start_time)`, so pid reuse never merges two processes.
11//! - Command lines held in a live `Snapshot` are raw (needed for rule matching and adapter argv parsing);
12//!   every export path (json, ndjson, serve, MCP) must pass through [`crate::redact::redact_snapshot`].
13//! - Environments are never stored: only [`Markers`] derived from allowlisted keys, with values hashed.
14
15use serde::{Deserialize, Serialize};
16use std::collections::BTreeMap;
17
18/// Output schema version for `json`, `ndjson`, `serve` and MCP (SPEC §6.2).
19pub const SCHEMA_VERSION: u32 = 1;
20
21/// Byte counts are always integers.
22pub type Bytes = u64;
23
24// ---------------------------------------------------------------------------------------------------------
25// Measured<T>
26// ---------------------------------------------------------------------------------------------------------
27
28/// How much a measured value can be trusted.
29#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
30#[serde(rename_all = "snake_case")]
31pub enum Quality {
32    /// Read directly from an authoritative OS source.
33    Exact,
34    /// Derived, interpolated between expensive reads, or a heuristic / lower bound.
35    Estimate,
36    /// Not available; the string says why (e.g. "needs root", "not supported on this OS").
37    Unavailable(String),
38}
39
40impl Default for Quality {
41    fn default() -> Self {
42        Quality::Unavailable("not collected".to_string())
43    }
44}
45
46/// A measured value with its provenance (SPEC §5). Helpers live in [`crate::measured`].
47#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
48#[serde(default)]
49pub struct Measured<T> {
50    /// `None` whenever `quality` is `Unavailable`.
51    pub value: Option<T>,
52    /// Where the value came from, e.g. `"proc_pid_rusage.ri_phys_footprint"`, `"/proc/meminfo:MemAvailable"`.
53    pub source: String,
54    pub quality: Quality,
55}
56
57impl<T> Default for Measured<T> {
58    fn default() -> Self {
59        Measured {
60            value: None,
61            source: String::new(),
62            quality: Quality::default(),
63        }
64    }
65}
66
67/// Availability of one data source for the current snapshot (SPEC §6.1).
68#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
69#[serde(rename_all = "snake_case")]
70pub enum SourceStatus {
71    #[default]
72    Available,
73    Partial(String),
74    Unavailable(String),
75}
76
77// ---------------------------------------------------------------------------------------------------------
78// Host
79// ---------------------------------------------------------------------------------------------------------
80
81#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
82#[serde(rename_all = "snake_case")]
83pub enum OsKind {
84    Macos,
85    Linux,
86    #[default]
87    Other,
88}
89
90/// Static-ish facts about the machine.
91#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
92#[serde(default)]
93pub struct HostInfo {
94    pub hostname: String,
95    pub os: OsKind,
96    /// e.g. "macOS 26.6", "Linux 6.8.0".
97    pub os_version: String,
98    /// e.g. "aarch64", "x86_64".
99    pub arch: String,
100    /// Hardware model, e.g. "Mac17,3".
101    pub model: Option<String>,
102    /// e.g. "Apple M5".
103    pub cpu_brand: Option<String>,
104    pub cores_logical: u32,
105    pub cores_performance: Option<u32>,
106    pub cores_efficiency: Option<u32>,
107    pub mem_total: Bytes,
108    /// Unified memory (Apple Silicon) vs discrete VRAM.
109    pub unified_memory: bool,
110    /// `Some(true)` for fanless machines (thermal-prone), `None` if unknown.
111    pub fanless: Option<bool>,
112    pub page_size: u64,
113    pub boot_time_ms: Option<u64>,
114}
115
116/// Host memory pressure level (macOS memorystatus / Linux derived from PSI).
117#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
118#[serde(rename_all = "snake_case")]
119pub enum PressureLevel {
120    #[default]
121    Normal,
122    Warn,
123    Critical,
124}
125
126/// Linux PSI (`/proc/pressure/memory`), percentages 0..100.
127#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Default)]
128#[serde(default)]
129pub struct Psi {
130    pub some_avg10: f64,
131    pub some_avg60: f64,
132    pub some_avg300: f64,
133    pub full_avg10: f64,
134    pub full_avg60: f64,
135    pub full_avg300: f64,
136}
137
138/// Host memory (SPEC §5, §8.1).
139#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
140#[serde(default)]
141pub struct HostMemory {
142    pub total: Measured<Bytes>,
143    /// Headroom input `available_now` (SPEC §8.1). macOS: `(free − speculative) + external/file-backed
144    /// (⊇ speculative) + purgeable` — speculative pages counted once; anonymous inactive pages are NOT
145    /// counted. Linux: MemAvailable (capped by own cgroup when set).
146    pub available: Measured<Bytes>,
147    pub free: Measured<Bytes>,
148    pub cached: Measured<Bytes>,
149    pub wired: Measured<Bytes>,
150    /// Physical memory occupied by the compressor (macOS) / zswap+zram pool (Linux).
151    pub compressed: Measured<Bytes>,
152    /// Logical (uncompressed) bytes held in the compressor; `compressed / compressed_logical` = ratio.
153    pub compressed_logical: Measured<Bytes>,
154    /// Anonymous "app" memory (macOS Activity Monitor "App Memory"; Linux AnonPages).
155    pub app: Measured<Bytes>,
156    pub swap_used: Measured<Bytes>,
157    pub swap_total: Measured<Bytes>,
158    /// Swap-ins per minute (pages→bytes), from deltas (SPEC §9 swap storm).
159    pub swap_in_per_min: Measured<Bytes>,
160    pub swap_out_per_min: Measured<Bytes>,
161    pub pressure: Measured<PressureLevel>,
162    /// macOS `kern.memorystatus_level` (% available), 0..100.
163    pub memorystatus_level: Measured<u8>,
164    pub psi: Measured<Psi>,
165    /// Linux: `memory.max` of oomtop's own cgroup when set.
166    pub own_cgroup_limit: Measured<Bytes>,
167    /// macOS: how far swap can grow before jetsam runs out of swap space — swap used + free space on the
168    /// swap volume (`/System/Volumes/VM`), an estimate. macOS adds swap files on demand, so `swap_total` is
169    /// not a limit there. Unavailable on Linux (fixed-size swap: `swap_total` is the limit).
170    #[serde(default)]
171    pub swap_limit: Measured<Bytes>,
172}
173
174/// Host CPU.
175#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
176#[serde(default)]
177pub struct HostCpu {
178    /// Whole-machine utilization, 0..100 (100 = all cores busy).
179    pub total_pct: Measured<f64>,
180    pub load_avg_1: Measured<f64>,
181    pub load_avg_5: Measured<f64>,
182    pub load_avg_15: Measured<f64>,
183    /// Per-logical-core utilization, 0..100 each, in OS core order (htop-style meters). Empty until two samples
184    /// exist or when the source is unavailable.
185    pub per_core_pct: Vec<f64>,
186    /// Kind of each core, parallel to `per_core_pct` when known (Apple Silicon P/E clusters); empty if unknown.
187    pub core_kinds: Vec<CoreKind>,
188    /// Process / thread counts for the header "Tasks" line.
189    pub tasks: TaskCounts,
190}
191
192/// Core class on heterogeneous CPUs.
193#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
194#[serde(rename_all = "snake_case")]
195pub enum CoreKind {
196    Performance,
197    Efficiency,
198    #[default]
199    Unknown,
200}
201
202/// Counts shown in the htop-style header ("Tasks: 867, 1625 thr; 1 running").
203#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)]
204#[serde(default)]
205pub struct TaskCounts {
206    pub processes: u32,
207    /// Sum of per-process thread counts where readable; `None` when no process reported threads.
208    pub threads: Option<u32>,
209    pub running: u32,
210}
211
212// ---------------------------------------------------------------------------------------------------------
213// OOM (SPEC §8.3)
214// ---------------------------------------------------------------------------------------------------------
215
216#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
217#[serde(rename_all = "snake_case")]
218pub enum OomKiller {
219    /// Linux kernel OOM killer (always applies on Linux).
220    #[default]
221    Kernel,
222    SystemdOomd,
223    Earlyoom,
224    /// macOS memorystatus / jetsam.
225    Jetsam,
226}
227
228#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
229#[serde(rename_all = "snake_case")]
230pub enum ThresholdMetric {
231    /// Swap used as % of swap total.
232    #[default]
233    SwapUsedPct,
234    /// Memory pressure %: the forecast evaluates it on PSI `some avg10` (SPEC §21, the conservative
235    /// series: `some ≥ full`).
236    MemPressurePct,
237    /// Available memory in bytes.
238    AvailableBytes,
239    /// Available memory as % of total.
240    AvailablePct,
241}
242
243/// A threshold at which a killer acts, e.g. systemd-oomd "swap used > 90 %".
244#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
245#[serde(default)]
246pub struct OomThreshold {
247    pub killer: OomKiller,
248    pub metric: ThresholdMetric,
249    pub value: f64,
250    /// Sustained duration required, if any (oomd: 30 s).
251    pub duration_s: Option<u32>,
252    /// Where the threshold came from ("oomd.conf", "earlyoom argv", "default").
253    pub source: String,
254}
255
256#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
257#[serde(rename_all = "snake_case")]
258pub enum ForecastTarget {
259    /// Swap used reaches swap total.
260    #[default]
261    SwapExhaustion,
262    /// Available memory reaches zero (after which the killer acts).
263    AvailableExhaustion,
264    /// A killer threshold (see `Oom::thresholds`) is crossed.
265    KillerThreshold,
266}
267
268/// OOM forecast. Present only when the trend is consistent (R² ≥ 0.6) and ETA < 30 min (SPEC §8.3).
269#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
270#[serde(default)]
271pub struct Forecast {
272    pub target: ForecastTarget,
273    /// Which killer acts at the target.
274    pub killer: Option<OomKiller>,
275    pub eta_s: u64,
276    /// 0..1, the R² of the linear fit.
277    pub confidence: f64,
278    /// Trend rate in bytes per minute (positive = growing towards the target).
279    pub rate_per_min: f64,
280    /// Window used for the fit, seconds.
281    pub window_s: u64,
282}
283
284/// Who the OOM killer would likely pick.
285#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
286#[serde(default)]
287pub struct Victim {
288    pub id: ProcId,
289    pub name: String,
290    pub group_id: Option<String>,
291    /// e.g. "highest oom_score (812)" or "largest background app (heuristic)".
292    pub reason: String,
293    /// true on macOS (jetsam bands unreadable without root).
294    pub heuristic: bool,
295}
296
297#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
298#[serde(default)]
299pub struct OomKill {
300    pub at_ms: Option<u64>,
301    pub killer: OomKiller,
302    pub victim_name: Option<String>,
303    pub victim_pid: Option<u32>,
304    /// e.g. "memory.events:oom_kill", "JetsamEvent-2026-09-29-101010.ips".
305    pub source: String,
306}
307
308#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
309#[serde(default)]
310pub struct Oom {
311    /// The nearest applicable killer.
312    pub killer: OomKiller,
313    /// All killers that apply on this host (kernel is always present on Linux).
314    pub killers: Vec<OomKiller>,
315    pub thresholds: Vec<OomThreshold>,
316    /// `None` = stable / not enough data.
317    pub forecast: Option<Forecast>,
318    pub likely_victim: Option<Victim>,
319    pub recent_kills: Vec<OomKill>,
320}
321
322// ---------------------------------------------------------------------------------------------------------
323// Accelerators & thermal (SPEC §5, §9)
324// ---------------------------------------------------------------------------------------------------------
325
326#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
327#[serde(rename_all = "snake_case")]
328pub enum GpuVendor {
329    Apple,
330    Nvidia,
331    Amd,
332    Intel,
333    #[default]
334    Other,
335}
336
337#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
338#[serde(default)]
339pub struct Accelerator {
340    /// Stable id within the host, e.g. "gpu0".
341    pub id: String,
342    pub vendor: GpuVendor,
343    pub name: String,
344    /// Shares host RAM (Apple Silicon, iGPUs).
345    pub unified: bool,
346    pub util_pct: Measured<f64>,
347    pub mem_used: Measured<Bytes>,
348    pub mem_total: Measured<Bytes>,
349    /// Metal working-set limit (`recommendedMaxWorkingSetSize` / `iogpu.wired_limit_mb`) (SPEC §8.1).
350    pub gpu_budget: Measured<Bytes>,
351    pub power_w: Measured<f64>,
352    pub temp_c: Measured<f64>,
353    pub clock_mhz: Measured<f64>,
354    pub max_clock_mhz: Measured<f64>,
355    /// e.g. "SW power cap", "HW slowdown", "thermal".
356    pub throttle_reasons: Vec<String>,
357}
358
359/// Thermal pressure levels (macOS `OSThermalNotification.h`; Linux derived from trip points).
360#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
361#[serde(rename_all = "snake_case")]
362pub enum ThermalPressure {
363    #[default]
364    Nominal,
365    Moderate,
366    Heavy,
367    Trapping,
368    Sleeping,
369}
370
371/// Frequency/residency of one CPU cluster or GPU (input for the throttle factor, SPEC §9).
372#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
373#[serde(default)]
374pub struct ClusterFreq {
375    /// e.g. "P-cluster", "E-cluster", "cpu0", "gpu".
376    pub name: String,
377    pub cur_mhz: f64,
378    pub max_mhz: f64,
379    /// Active residency 0..100.
380    pub active_pct: f64,
381}
382
383#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
384#[serde(default)]
385pub struct TempSensor {
386    pub name: String,
387    pub celsius: f64,
388}
389
390#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
391#[serde(default)]
392pub struct Thermal {
393    pub pressure: Measured<ThermalPressure>,
394    /// 0..1 = observed ÷ max frequency, only while busy; `Unavailable("idle")` otherwise (SPEC §9).
395    pub throttle_factor: Measured<f64>,
396    pub low_power_mode: Measured<bool>,
397    pub on_battery: Measured<bool>,
398    /// 0..100.
399    pub battery_pct: Measured<f64>,
400    pub adapter_watts: Measured<f64>,
401    pub package_power_w: Measured<f64>,
402    pub clusters: Vec<ClusterFreq>,
403    pub temps: Vec<TempSensor>,
404    /// Linux: a thermal trip point was hit.
405    pub trip_point_hit: Measured<bool>,
406}
407
408// ---------------------------------------------------------------------------------------------------------
409// Processes
410// ---------------------------------------------------------------------------------------------------------
411
412/// Process identity: `(pid, start_time)`. `start_time` is milliseconds since the Unix epoch
413/// (Linux: btime + starttime/CLK_TCK; macOS: `pbi_start_tvsec/usec`). Used for identity only.
414#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
415pub struct ProcId {
416    pub pid: u32,
417    pub start_time: u64,
418}
419
420impl ProcId {
421    pub fn new(pid: u32, start_time: u64) -> Self {
422        ProcId { pid, start_time }
423    }
424}
425
426/// Per-process memory (SPEC §5 memory taxonomy).
427#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
428#[serde(default)]
429pub struct MemBreakdown {
430    pub resident: Measured<Bytes>,
431    /// macOS `ri_phys_footprint`; Linux `Pss` (estimate `RSS − Shared` between smaps reads).
432    pub footprint_or_pss: Measured<Bytes>,
433    pub gpu: Measured<Bytes>,
434    pub compressed: Measured<Bytes>,
435    pub swapped: Measured<Bytes>,
436    /// macOS: `max(0, footprint − resident)`, "compressed or swapped (est.)".
437    pub non_resident_est: Measured<Bytes>,
438}
439
440#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
441#[serde(default)]
442pub struct DiskIo {
443    /// Cumulative bytes read/written since process start.
444    pub read_bytes: Measured<Bytes>,
445    pub write_bytes: Measured<Bytes>,
446    /// Bytes per second over the last interval.
447    pub read_rate: Measured<f64>,
448    pub write_rate: Measured<f64>,
449}
450
451#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
452#[serde(rename_all = "snake_case")]
453pub enum ProcState {
454    Running,
455    Sleeping,
456    Idle,
457    Stopped,
458    Zombie,
459    #[default]
460    Unknown,
461}
462
463/// Session markers derived from allowlisted environment keys (SPEC §7.4). Values are never stored raw.
464#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
465#[serde(default)]
466pub struct Markers {
467    /// Hashed session id (e.g. of `CLAUDE_CODE_SESSION_ID`), see [`crate::redact::hash_marker`].
468    pub session_id: Option<String>,
469    /// Agent name inferred from marker keys, e.g. "claude-code".
470    pub agent: Option<String>,
471    /// Allowlisted marker keys that were present (keys only, no values).
472    pub keys: Vec<String>,
473}
474
475#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
476#[serde(default)]
477pub struct Process {
478    pub id: ProcId,
479    pub ppid: Option<u32>,
480    /// macOS responsible pid (helpers/XPC → launching app).
481    pub responsible_pid: Option<u32>,
482    /// Short name (comm / basename).
483    pub name: String,
484    /// Executable path (may be empty when unreadable).
485    pub exe: String,
486    /// argv. Raw in a live snapshot; redacted in every export.
487    pub cmdline: Vec<String>,
488    pub cwd: Option<String>,
489    pub uid: Option<u32>,
490    pub user: Option<String>,
491    /// Per-core percent (100 = one core busy); needs two samples.
492    pub cpu_pct: Measured<f64>,
493    pub mem: MemBreakdown,
494    pub disk_io: DiskIo,
495    pub state: ProcState,
496    pub threads: Option<u32>,
497    /// Seconds idle; `Estimate` quality means "≥ observed window" (no lineage data).
498    pub idle_for_s: Measured<u64>,
499    pub markers: Markers,
500    /// Linux cgroup v2 path.
501    pub cgroup: Option<String>,
502    /// Linux `/proc/<pid>/oom_score`.
503    pub oom_score: Option<i32>,
504    /// macOS bundle id of the owning app, when known.
505    pub bundle_id: Option<String>,
506    /// Model weight files mapped/open (`*.gguf`, `*.safetensors`), when known.
507    pub model_files: Vec<String>,
508    // --- time and staleness (SPEC §5 "Time and staleness"; filled by the decoders and
509    // `crate::staleness::apply`; left out of JSON until computed) ---
510    /// Seconds since the process started (now − start time).
511    #[serde(skip_serializing_if = "crate::staleness::not_collected")]
512    pub age_s: Measured<u64>,
513    /// Total CPU time (user + system) since the process started, seconds.
514    #[serde(skip_serializing_if = "crate::staleness::not_collected")]
515    pub cpu_time_s: Measured<f64>,
516    /// Duty cycle: CPU time ÷ age, in percent of one core (100 = one core busy for its whole life).
517    #[serde(skip_serializing_if = "crate::staleness::not_collected")]
518    pub duty_pct: Measured<f64>,
519    /// Idle rent: GiB-hours of footprint held while idle (footprint × idle time); always an estimate.
520    #[serde(skip_serializing_if = "crate::staleness::not_collected")]
521    pub idle_rent_gib_h: Measured<f64>,
522    /// `Some(true)`: the working directory no longer exists; `None`: not checked / not readable.
523    #[serde(skip_serializing_if = "Option::is_none")]
524    pub cwd_missing: Option<bool>,
525    /// The executable was deleted or replaced since the process started; `None`: unchanged or unknown.
526    #[serde(skip_serializing_if = "Option::is_none")]
527    pub exe_change: Option<crate::staleness::ExeChange>,
528    /// Project directory: git root of the cwd when known, else the cwd.
529    #[serde(skip_serializing_if = "Option::is_none")]
530    pub project: Option<String>,
531    /// Agent session roots: modification time (ms since the epoch) of the session's transcript file. The
532    /// file's content is never read.
533    #[serde(skip_serializing_if = "crate::staleness::not_collected")]
534    pub transcript_mtime_ms: Measured<u64>,
535    /// **Reserved for network data** (not collected yet): `Some(true)` when the process listens on a port
536    /// and has no clients. Feeds the `listening_no_clients` staleness signal.
537    #[serde(skip_serializing_if = "Option::is_none")]
538    pub listening_no_clients: Option<bool>,
539    /// Linux namespace identities (`/proc/<pid>/ns/*`, own processes only); `None` = not read or not Linux
540    /// (SPEC §11 "Namespaces", `crate::namespaces`).
541    #[serde(skip_serializing_if = "Option::is_none")]
542    pub ns: Option<crate::namespaces::NsIds>,
543}
544
545// ---------------------------------------------------------------------------------------------------------
546// Groups (SPEC §5, §7)
547// ---------------------------------------------------------------------------------------------------------
548
549/// Group kinds with short aliases used in queries, themes and rules.
550#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
551#[serde(rename_all = "snake_case")]
552pub enum GroupKind {
553    #[serde(alias = "agent")]
554    AgentSession,
555    App,
556    #[serde(alias = "model")]
557    ModelServer,
558    Sandbox,
559    #[serde(alias = "daemon")]
560    BuildDaemon,
561    System,
562    #[default]
563    Other,
564}
565
566impl GroupKind {
567    pub const ALL: [GroupKind; 7] = [
568        GroupKind::AgentSession,
569        GroupKind::App,
570        GroupKind::ModelServer,
571        GroupKind::Sandbox,
572        GroupKind::BuildDaemon,
573        GroupKind::System,
574        GroupKind::Other,
575    ];
576
577    /// Short alias: agent | app | model | sandbox | daemon | system | other.
578    pub fn alias(self) -> &'static str {
579        match self {
580            GroupKind::AgentSession => "agent",
581            GroupKind::App => "app",
582            GroupKind::ModelServer => "model",
583            GroupKind::Sandbox => "sandbox",
584            GroupKind::BuildDaemon => "daemon",
585            GroupKind::System => "system",
586            GroupKind::Other => "other",
587        }
588    }
589
590    /// Canonical serde name: agent_session | app | model_server | sandbox | build_daemon | system | other.
591    pub fn as_str(self) -> &'static str {
592        match self {
593            GroupKind::AgentSession => "agent_session",
594            GroupKind::App => "app",
595            GroupKind::ModelServer => "model_server",
596            GroupKind::Sandbox => "sandbox",
597            GroupKind::BuildDaemon => "build_daemon",
598            GroupKind::System => "system",
599            GroupKind::Other => "other",
600        }
601    }
602
603    /// Parses either the canonical name or the short alias (case-insensitive).
604    pub fn parse(s: &str) -> Option<GroupKind> {
605        let s = s.trim().to_ascii_lowercase();
606        GroupKind::ALL
607            .into_iter()
608            .find(|k| k.alias() == s || k.as_str() == s)
609    }
610}
611
612#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
613#[serde(rename_all = "snake_case")]
614pub enum Confidence {
615    #[default]
616    Low,
617    Medium,
618    High,
619}
620
621/// Which attribution signal placed a process in its group (SPEC §7, strongest first).
622#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
623#[serde(rename_all = "snake_case")]
624pub enum AttributionSignal {
625    Adapter,
626    Cgroup,
627    Responsible,
628    Marker,
629    Ancestry,
630    Lineage,
631    Rule,
632    #[default]
633    Heuristic,
634}
635
636#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
637#[serde(default)]
638pub struct Member {
639    pub id: ProcId,
640    pub confidence: Confidence,
641    pub via: AttributionSignal,
642}
643
644#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
645#[serde(default)]
646pub struct GroupTotals {
647    /// Σ `footprint_or_pss` of members.
648    pub footprint: Measured<Bytes>,
649    pub resident: Measured<Bytes>,
650    pub gpu: Measured<Bytes>,
651    pub swapped: Measured<Bytes>,
652    /// Σ per-core CPU % of members.
653    pub cpu_pct: Measured<f64>,
654    pub process_count: u32,
655}
656
657#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
658#[serde(default)]
659pub struct Group {
660    /// Unique within a snapshot and stable across samples for the same root, e.g. "agent:3f2a9c01".
661    pub id: String,
662    pub kind: GroupKind,
663    pub label: String,
664    /// Entity fingerprint (UX §4), hex.
665    pub fingerprint: String,
666    pub root: Option<ProcId>,
667    pub members: Vec<Member>,
668    pub totals: GroupTotals,
669    /// RAM freed if stopped (SPEC §8.1); always `Estimate`.
670    pub reclaim_gain: Measured<Bytes>,
671    /// Swap freed if stopped, reported separately (SPEC §8.1).
672    pub swap_gain: Measured<Bytes>,
673    pub confidence: Confidence,
674    /// Group that started/owns this one (e.g. sandbox started by an agent session).
675    pub owner_group: Option<String>,
676    pub orphan: bool,
677    pub idle: bool,
678    pub idle_for_s: Option<u64>,
679    /// Protected groups are never offered for actions (SPEC §13).
680    pub protected: bool,
681    /// oomtop's own processes.
682    pub is_self: bool,
683    /// Footprint is a lower bound (Virtualization.framework VMs, SPEC §5).
684    pub lower_bound: bool,
685    /// Configured VM memory for sandbox groups.
686    pub configured_mem: Option<Bytes>,
687    /// Rule/adapter that defined this group, for "why" explanations.
688    pub matched_by: Option<String>,
689    // --- time and staleness (filled by `crate::staleness::apply`; left out of JSON until computed) ---
690    /// Age of the root process, else of the oldest member (the source says which), seconds.
691    #[serde(skip_serializing_if = "crate::staleness::not_collected")]
692    pub age_s: Measured<u64>,
693    /// Σ CPU time of the live members, seconds.
694    #[serde(skip_serializing_if = "crate::staleness::not_collected")]
695    pub cpu_time_s: Measured<f64>,
696    /// Duty cycle: `cpu_time_s ÷ age_s`, percent of one core.
697    #[serde(skip_serializing_if = "crate::staleness::not_collected")]
698    pub duty_pct: Measured<f64>,
699    /// Idle time of the longest-idle member (`idle_for_s` is the shortest: the whole group's).
700    #[serde(skip_serializing_if = "Option::is_none")]
701    pub longest_idle_s: Option<u64>,
702    /// The longest-idle member.
703    #[serde(skip_serializing_if = "Option::is_none")]
704    pub longest_idle: Option<ProcId>,
705    /// Idle rent: Σ GiB-hours held by idle members; always an estimate.
706    #[serde(skip_serializing_if = "crate::staleness::not_collected")]
707    pub idle_rent_gib_h: Measured<f64>,
708    /// Staleness score (0..1) and the ordered evidence behind it.
709    #[serde(skip_serializing_if = "crate::staleness::no_staleness")]
710    pub staleness: crate::staleness::Staleness,
711    /// Project directory of the root, else the most common among the members.
712    #[serde(skip_serializing_if = "Option::is_none")]
713    pub project: Option<String>,
714    /// Id of the [`crate::staleness::Cohort`] this group belongs to: the agent session that left it has
715    /// ended.
716    #[serde(skip_serializing_if = "Option::is_none")]
717    pub cohort: Option<String>,
718}
719
720// ---------------------------------------------------------------------------------------------------------
721// Model servers (SPEC §10) and sandboxes (SPEC §11)
722// ---------------------------------------------------------------------------------------------------------
723
724#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
725#[serde(rename_all = "snake_case")]
726pub enum ModelServerKind {
727    Ollama,
728    LlamaCpp,
729    SdCpp,
730    Vllm,
731    LmStudio,
732    Mlx,
733    #[default]
734    Generic,
735}
736
737#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
738#[serde(rename_all = "snake_case")]
739pub enum Device {
740    Gpu,
741    Cpu,
742    Mixed,
743    #[default]
744    Unknown,
745}
746
747#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
748#[serde(default)]
749pub struct LoadedModel {
750    pub name: String,
751    pub file: Option<String>,
752    pub weights_bytes: Measured<Bytes>,
753    pub kv_bytes: Measured<Bytes>,
754    pub device: Device,
755}
756
757#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
758#[serde(default)]
759pub struct JobProgress {
760    pub done: u32,
761    pub total: u32,
762    /// Human label, e.g. "generating".
763    pub label: String,
764}
765
766#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
767#[serde(default)]
768pub struct ModelServer {
769    pub id: String,
770    pub kind: ModelServerKind,
771    /// Always a loopback URL, e.g. "http://127.0.0.1:11434".
772    pub endpoint: Option<String>,
773    pub pids: Vec<ProcId>,
774    pub group_id: Option<String>,
775    pub models: Vec<LoadedModel>,
776    pub tok_s: Measured<f64>,
777    pub s_per_step: Measured<f64>,
778    pub queue: Measured<u32>,
779    pub busy: Measured<bool>,
780    pub progress: Option<JobProgress>,
781    pub status: SourceStatus,
782}
783
784#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
785#[serde(rename_all = "snake_case")]
786pub enum SandboxKind {
787    Container,
788    Vm,
789    MicroVm,
790    #[default]
791    ProcessSandbox,
792}
793
794#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
795#[serde(default)]
796pub struct SandboxLimits {
797    pub mem_max: Option<Bytes>,
798    pub cpus: Option<f64>,
799}
800
801#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
802#[serde(default)]
803pub struct Sandbox {
804    pub id: String,
805    pub kind: SandboxKind,
806    /// e.g. "docker", "podman", "virtualization.framework", "firecracker", "bwrap".
807    pub runtime: String,
808    pub label: String,
809    pub host_pids: Vec<ProcId>,
810    pub configured_mem: Measured<Bytes>,
811    pub guest_mem: Measured<Bytes>,
812    pub limits: SandboxLimits,
813    pub started_by_group: Option<String>,
814    /// Host footprint under-counts this sandbox (SPEC §5).
815    pub footprint_lower_bound: bool,
816}
817
818// ---------------------------------------------------------------------------------------------------------
819// Snapshot
820// ---------------------------------------------------------------------------------------------------------
821
822/// One consistent view of the machine. Output of the sampler + attribution + adapters.
823#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
824#[serde(default)]
825pub struct Snapshot {
826    /// Always [`SCHEMA_VERSION`].
827    pub schema_version: u32,
828    pub taken_at_ms: u64,
829    pub host: HostInfo,
830    pub memory: HostMemory,
831    pub cpu: HostCpu,
832    pub oom: Oom,
833    pub accelerators: Vec<Accelerator>,
834    pub thermal: Thermal,
835    pub processes: Vec<Process>,
836    pub groups: Vec<Group>,
837    pub model_servers: Vec<ModelServer>,
838    pub sandboxes: Vec<Sandbox>,
839    /// Per source name (e.g. "macos.procs", "linux.meminfo", "adapter.ollama").
840    pub source_status: BTreeMap<String, SourceStatus>,
841    /// pid of the oomtop process that produced this snapshot.
842    pub self_pid: Option<u32>,
843    /// Leftovers bucketed by the agent session that ended (`crate::staleness::cohorts`).
844    #[serde(skip_serializing_if = "Vec::is_empty")]
845    pub cohorts: Vec<crate::staleness::Cohort>,
846    /// More than one live instance of one fingerprint in one project (`crate::staleness::duplicates`).
847    #[serde(skip_serializing_if = "Vec::is_empty")]
848    pub duplicates: Vec<crate::staleness::DuplicateSet>,
849    /// Ports and "who talks to whom" (`crate::net`): sockets from the socket source, listeners, links and
850    /// findings computed by `crate::net::analyze`. Left out of JSON when no socket source ran.
851    #[serde(skip_serializing_if = "crate::net::Net::is_empty")]
852    pub net: crate::net::Net,
853    /// Linux cgroup v2 memory accounting of container / pod cgroups and of every cgroup with a memory limit
854    /// (SPEC §8.3 per-limit forecast, §11).
855    #[serde(skip_serializing_if = "Vec::is_empty")]
856    pub cgroups: Vec<crate::limits::CgroupMem>,
857    /// Containers, local Kubernetes clusters, per-limit forecasts, VM slack, namespace sets and stale
858    /// containers (SPEC §8.3, §11; `crate::cluster`).
859    #[serde(skip_serializing_if = "crate::cluster::Isolation::is_empty")]
860    pub isolation: crate::cluster::Isolation,
861}
862
863impl Default for Snapshot {
864    fn default() -> Self {
865        Snapshot {
866            schema_version: SCHEMA_VERSION,
867            taken_at_ms: 0,
868            host: HostInfo::default(),
869            memory: HostMemory::default(),
870            cpu: HostCpu::default(),
871            oom: Oom::default(),
872            accelerators: Vec::new(),
873            thermal: Thermal::default(),
874            processes: Vec::new(),
875            groups: Vec::new(),
876            model_servers: Vec::new(),
877            sandboxes: Vec::new(),
878            source_status: BTreeMap::new(),
879            self_pid: None,
880            cohorts: Vec::new(),
881            duplicates: Vec::new(),
882            net: crate::net::Net::default(),
883            cgroups: Vec::new(),
884            isolation: Default::default(),
885        }
886    }
887}
888
889impl Snapshot {
890    /// Finds a process by identity.
891    pub fn process(&self, id: ProcId) -> Option<&Process> {
892        self.processes.iter().find(|p| p.id == id)
893    }
894
895    /// Finds a process by pid only (for ppid/responsible lookups inside one snapshot).
896    pub fn process_by_pid(&self, pid: u32) -> Option<&Process> {
897        self.processes.iter().find(|p| p.id.pid == pid)
898    }
899
900    pub fn group(&self, id: &str) -> Option<&Group> {
901        self.groups.iter().find(|g| g.id == id)
902    }
903
904    /// The group containing a process, if attributed.
905    pub fn group_of(&self, id: ProcId) -> Option<&Group> {
906        self.groups.iter().find(|g| g.members.iter().any(|m| m.id == id))
907    }
908}
909
910#[cfg(test)]
911mod tests {
912    use super::*;
913
914    #[test]
915    fn default_snapshot_roundtrips_and_has_schema_version() {
916        let s = Snapshot::default();
917        assert_eq!(s.schema_version, SCHEMA_VERSION);
918        let json = serde_json::to_string(&s).unwrap();
919        let back: Snapshot = serde_json::from_str(&json).unwrap();
920        assert_eq!(back, s);
921    }
922
923    #[test]
924    fn missing_fields_deserialize_with_defaults() {
925        let back: Snapshot = serde_json::from_str(r#"{"taken_at_ms": 5}"#).unwrap();
926        assert_eq!(back.taken_at_ms, 5);
927        assert_eq!(back.schema_version, SCHEMA_VERSION);
928        assert!(back.memory.total.value.is_none());
929    }
930
931    #[test]
932    fn group_kind_aliases() {
933        for k in GroupKind::ALL {
934            assert_eq!(GroupKind::parse(k.alias()), Some(k));
935            assert_eq!(GroupKind::parse(k.as_str()), Some(k));
936        }
937        let k: GroupKind = serde_json::from_str("\"daemon\"").unwrap();
938        assert_eq!(k, GroupKind::BuildDaemon);
939        assert_eq!(
940            serde_json::to_string(&GroupKind::ModelServer).unwrap(),
941            "\"model_server\""
942        );
943    }
944
945    #[test]
946    fn quality_serde_shape() {
947        assert_eq!(serde_json::to_string(&Quality::Exact).unwrap(), "\"exact\"");
948        assert_eq!(
949            serde_json::to_string(&Quality::Unavailable("needs root".into())).unwrap(),
950            r#"{"unavailable":"needs root"}"#
951        );
952    }
953}