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