Skip to main content

oomtop_core/
staleness.rs

1//! "How long, how stale" (SPEC §5 time fields, §7 staleness). Pure: everything here is a function of one
2//! [`Snapshot`], a [`StalenessConfig`] and what the caller knows about ended agent sessions.
3//!
4//! [`apply`] fills, in this order:
5//! - per process: `age_s` (now − start), `duty_pct` (CPU time ÷ age) and `idle_rent_gib_h`;
6//! - per group: `age_s` (root, else oldest member), `cpu_time_s`, `duty_pct`, `longest_idle_s` /
7//!   `longest_idle`, `idle_rent_gib_h`, `project`, `cohort` and `staleness` (score + ordered evidence);
8//! - on the snapshot: `cohorts` (leftovers bucketed by the agent session that ended) and `duplicates`
9//!   (more than one live instance of one fingerprint in one project).
10//!
11//! The decoders provide the per-process inputs (`cpu_time_s`, `cwd_missing`, `exe_change`, `project`,
12//! `transcript_mtime_ms`); this module never touches the filesystem.
13//!
14//! **Score.** Every piece of evidence has a weight in 0..1; the score is the noisy-OR of the weights,
15//! `1 − Π(1 − wᵢ)`, so independent signals add up without ever exceeding 1 and one strong signal is enough.
16//! A group is flagged `stale` when the score reaches [`StalenessConfig::stale_score`] and the group is at
17//! least [`StalenessConfig::min_age_s`] old. Protected groups, oomtop itself and system groups are never
18//! scored (score 0, no evidence): nothing about them is actionable.
19
20use crate::measured::sum_f64;
21use crate::model::{Bytes, Group, GroupKind, Measured, ProcId, ProcState, Process, Quality, Snapshot};
22use crate::units::format_duration;
23use serde::{Deserialize, Serialize};
24use std::collections::{BTreeMap, HashMap};
25
26const GIB: f64 = (1u64 << 30) as f64;
27
28/// Source label of process and group ages.
29pub const SOURCE_AGE: &str = "now − start time";
30/// Source label of duty cycles.
31pub const SOURCE_DUTY: &str = "CPU time ÷ age";
32/// Source label of idle rent.
33pub const SOURCE_RENT: &str = "footprint now × idle time (footprint assumed constant while idle)";
34
35// ---------------------------------------------------------------------------------------------------------
36// Types stored in the snapshot (referenced from `model.rs`)
37// ---------------------------------------------------------------------------------------------------------
38
39/// What happened to a process's executable file since the process started.
40#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
41#[serde(rename_all = "snake_case")]
42pub enum ExeChange {
43    /// The file is gone (Linux: the `exe` link ends in " (deleted)"; macOS: the path no longer exists).
44    Deleted,
45    /// The file at that path is newer than the process (macOS: mtime later than the start time): the
46    /// process still runs the old version.
47    Replaced,
48}
49
50/// One kind of staleness evidence. Serialized in snake_case (`cwd_missing`, `exe_deleted`, …).
51#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
52#[serde(rename_all = "snake_case")]
53pub enum StaleSignal {
54    /// The working directory no longer exists.
55    CwdMissing,
56    /// The executable was deleted since the process started.
57    ExeDeleted,
58    /// The executable was replaced since the process started.
59    ExeReplaced,
60    /// The process is stopped / suspended (state T).
61    Stopped,
62    /// Orphaned: started by an agent session or tool that is gone.
63    Orphaned,
64    /// Idle for longer than `thresholds.stale_idle_s`.
65    #[default]
66    IdleLong,
67    /// The agent session's transcript was not modified for `thresholds.stale_transcript_s`.
68    TranscriptQuiet,
69    /// Listening on a port with no clients. **Reserved slot**: produced only when a collector fills
70    /// `Process::listening_no_clients` (network data; not collected by this module's inputs yet).
71    ListeningNoClients,
72}
73
74impl StaleSignal {
75    pub const ALL: [StaleSignal; 8] = [
76        StaleSignal::CwdMissing,
77        StaleSignal::ExeDeleted,
78        StaleSignal::ExeReplaced,
79        StaleSignal::Stopped,
80        StaleSignal::Orphaned,
81        StaleSignal::IdleLong,
82        StaleSignal::TranscriptQuiet,
83        StaleSignal::ListeningNoClients,
84    ];
85
86    pub fn as_str(self) -> &'static str {
87        match self {
88            StaleSignal::CwdMissing => "cwd_missing",
89            StaleSignal::ExeDeleted => "exe_deleted",
90            StaleSignal::ExeReplaced => "exe_replaced",
91            StaleSignal::Stopped => "stopped",
92            StaleSignal::Orphaned => "orphaned",
93            StaleSignal::IdleLong => "idle_long",
94            StaleSignal::TranscriptQuiet => "transcript_quiet",
95            StaleSignal::ListeningNoClients => "listening_no_clients",
96        }
97    }
98
99    /// Weight of the signal when it applies fully (see the module docs for how weights combine).
100    pub fn base_weight(self) -> f64 {
101        match self {
102            StaleSignal::CwdMissing => 0.6,
103            StaleSignal::Orphaned => 0.6,
104            StaleSignal::Stopped => 0.5,
105            StaleSignal::ExeDeleted => 0.45,
106            StaleSignal::TranscriptQuiet => 0.4,
107            StaleSignal::ExeReplaced => 0.35,
108            StaleSignal::IdleLong => 0.3,
109            StaleSignal::ListeningNoClients => 0.3,
110        }
111    }
112}
113
114/// One typed piece of evidence with its human sentence.
115#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
116#[serde(default)]
117pub struct StaleEvidence {
118    pub signal: StaleSignal,
119    /// Contribution to the score, 0..1.
120    pub weight: f64,
121    /// One plain sentence without a trailing period, e.g. "idle for 5h 12m (threshold 4h)".
122    pub sentence: String,
123    /// The member the evidence is about, when it is about one process.
124    pub pid: Option<u32>,
125    /// How many members show the signal (1 for group-level signals).
126    pub members: u32,
127}
128
129/// Staleness of one group: a score and the evidence behind it, strongest first.
130#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
131#[serde(default)]
132pub struct Staleness {
133    /// 0..1, noisy-OR of the evidence weights. Always an estimate (a heuristic).
134    pub score: f64,
135    /// `score ≥ thresholds.stale_score` and the group is at least `thresholds.stale_min_age_s` old.
136    pub stale: bool,
137    /// Strongest first; ties in [`StaleSignal`] declaration order.
138    pub evidence: Vec<StaleEvidence>,
139}
140
141impl Staleness {
142    pub fn has(&self, signal: StaleSignal) -> bool {
143        self.evidence.iter().any(|e| e.signal == signal)
144    }
145}
146
147/// Groups left behind by one agent session that has ended.
148#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
149#[serde(default)]
150pub struct Cohort {
151    /// The dead session's key as it appears in `Group::owner_group` (`agent:<hash12>` or the session's
152    /// former group id).
153    pub id: String,
154    /// The session's label when known (lineage journal), else "agent session".
155    pub label: String,
156    /// When the session was last seen alive by oomtop (an estimate: it ended at or after this time);
157    /// unavailable without journal data.
158    pub ended_at_ms: Measured<u64>,
159    /// Groups it left, largest footprint first.
160    pub group_ids: Vec<String>,
161    /// Σ footprint of those groups.
162    pub footprint: Measured<Bytes>,
163    pub process_count: u32,
164    /// "left by the Claude Code session that ended 3h ago".
165    pub sentence: String,
166}
167
168/// More than one live instance of the same fingerprint in the same project directory.
169#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
170#[serde(default)]
171pub struct DuplicateSet {
172    pub fingerprint: String,
173    pub kind: GroupKind,
174    pub label: String,
175    pub project: String,
176    /// Instances, oldest first (the first one is the likely keeper).
177    pub group_ids: Vec<String>,
178    /// Σ footprint of all instances.
179    pub footprint: Measured<Bytes>,
180    /// Σ footprint of every instance but the largest: what stopping the extras would give back at most.
181    pub extra_footprint: Measured<Bytes>,
182}
183
184// ---------------------------------------------------------------------------------------------------------
185// Inputs
186// ---------------------------------------------------------------------------------------------------------
187
188/// Thresholds (config section `thresholds`, see `oomtop config init`).
189#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
190#[serde(default)]
191pub struct StalenessConfig {
192    /// A group idle for at least this long shows `idle_long` evidence (default 4 h).
193    pub idle_s: u64,
194    /// An agent session whose transcript was not modified for this long shows `transcript_quiet`
195    /// (default 12 h).
196    pub transcript_s: u64,
197    /// Score at or above which a group is flagged stale (default 0.5).
198    pub stale_score: f64,
199    /// Groups younger than this are never flagged stale (default 600 s).
200    pub min_age_s: u64,
201    /// Idle rent accrues for processes idle at least this long (`thresholds.idle_after_s`, default 1800).
202    pub rent_after_s: u64,
203}
204
205impl Default for StalenessConfig {
206    fn default() -> Self {
207        StalenessConfig {
208            idle_s: 4 * 3600,
209            transcript_s: 12 * 3600,
210            stale_score: 0.5,
211            min_age_s: 600,
212            rent_after_s: 1800,
213        }
214    }
215}
216
217/// What is known about an agent session that is no longer running (from the lineage journal or from
218/// having watched it disappear).
219#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
220#[serde(default)]
221pub struct EndedSession {
222    pub label: String,
223    /// Last time the session was seen alive, ms since the epoch.
224    pub last_seen_ms: Option<u64>,
225}
226
227// ---------------------------------------------------------------------------------------------------------
228// serde helpers: fields that were never computed are left out, so snapshots that did not go through
229// `apply` (raw decoder output, older fixtures) serialize exactly as before.
230// ---------------------------------------------------------------------------------------------------------
231
232/// `skip_serializing_if` for `Measured` fields that were never filled in.
233pub fn not_collected<T>(m: &Measured<T>) -> bool {
234    m.value.is_none() && m.source.is_empty() && m.quality == Quality::default()
235}
236
237/// `skip_serializing_if` for a [`Staleness`] that was never computed.
238pub fn no_staleness(s: &Staleness) -> bool {
239    s.score == 0.0 && !s.stale && s.evidence.is_empty()
240}
241
242// ---------------------------------------------------------------------------------------------------------
243// Per-process times
244// ---------------------------------------------------------------------------------------------------------
245
246/// Age of a process at `now_ms`. Exact when the start time is known.
247pub fn age_of(id: ProcId, now_ms: u64) -> Measured<u64> {
248    if id.start_time == 0 {
249        return Measured::unavailable(SOURCE_AGE, "start time unknown");
250    }
251    Measured::exact(now_ms.saturating_sub(id.start_time) / 1000, SOURCE_AGE)
252}
253
254/// Duty cycle in percent of one core: `cpu_time ÷ age × 100` (100 = one core busy for its whole life).
255/// Exact when both inputs are; unavailable for processes younger than a second.
256pub fn duty_pct(cpu_time_s: &Measured<f64>, age_s: &Measured<u64>) -> Measured<f64> {
257    let (Some(cpu), Some(age)) = (cpu_time_s.value, age_s.value) else {
258        let why = if cpu_time_s.unavailable_reason().is_some() {
259            cpu_time_s.reason_or("")
260        } else {
261            age_s.reason_or("CPU time or age unavailable")
262        };
263        return Measured::unavailable(SOURCE_DUTY, why);
264    };
265    if age == 0 {
266        return Measured::unavailable(SOURCE_DUTY, "younger than a second");
267    }
268    let v = (cpu / age as f64 * 100.0).max(0.0);
269    if cpu_time_s.quality == Quality::Exact && age_s.quality == Quality::Exact {
270        Measured::exact(v, SOURCE_DUTY)
271    } else {
272        Measured::estimate(v, SOURCE_DUTY)
273    }
274}
275
276/// Idle rent in GiB-hours: footprint × idle time, counted once the process has been idle for
277/// `rent_after_s`. Always an estimate (the footprint is today's, the idle time is sampled).
278pub fn idle_rent(
279    footprint: &Measured<Bytes>,
280    idle_for_s: &Measured<u64>,
281    rent_after_s: u64,
282) -> Measured<f64> {
283    let Some(idle) = idle_for_s.value else {
284        return Measured::unavailable(SOURCE_RENT, idle_for_s.reason_or("idle time unknown"));
285    };
286    if idle < rent_after_s {
287        return Measured::estimate(0.0, SOURCE_RENT);
288    }
289    match footprint.value {
290        Some(b) => Measured::estimate(b as f64 / GIB * idle as f64 / 3600.0, SOURCE_RENT),
291        None => Measured::unavailable(SOURCE_RENT, footprint.reason_or("footprint unavailable")),
292    }
293}
294
295// ---------------------------------------------------------------------------------------------------------
296// Scoring
297// ---------------------------------------------------------------------------------------------------------
298
299/// Weight growth of a duration signal: the base weight at the threshold, twice that at 8× the threshold
300/// (log scale), never more.
301fn duration_weight(base: f64, value_s: u64, threshold_s: u64) -> f64 {
302    let ratio = value_s as f64 / threshold_s.max(1) as f64;
303    let grow = (ratio.max(1.0).log2() / 3.0).clamp(0.0, 1.0);
304    base * (1.0 + grow)
305}
306
307/// Weight of a per-member signal seen on `n` of `m` members: full when the root shows it or every member
308/// does, otherwise scaled by the share (at least half).
309fn member_weight(base: f64, n: usize, m: usize, root_hit: bool) -> f64 {
310    if root_hit || n >= m {
311        base
312    } else {
313        base * (n as f64 / m.max(1) as f64).max(0.5)
314    }
315}
316
317/// Evidence for a signal that individual members show. `one`: sentence tail for a single process
318/// ("runs in a working directory that no longer exists"); `many`: tail after "N of M processes".
319fn member_evidence(
320    signal: StaleSignal,
321    hits: &[&Process],
322    total: usize,
323    root: Option<ProcId>,
324    one: &str,
325    many: &str,
326) -> Option<StaleEvidence> {
327    let first = hits.first()?;
328    let root_hit = root.is_some_and(|r| hits.iter().any(|p| p.id == r));
329    let subject = root
330        .and_then(|r| hits.iter().find(|p| p.id == r))
331        .unwrap_or(first);
332    let sentence = if hits.len() == 1 || total == 1 {
333        format!("{} (pid {}) {one}", subject.name, subject.id.pid)
334    } else {
335        format!("{} of {total} processes {many}", hits.len())
336    };
337    Some(StaleEvidence {
338        signal,
339        weight: member_weight(signal.base_weight(), hits.len(), total, root_hit),
340        sentence,
341        pid: (hits.len() == 1).then_some(subject.id.pid),
342        members: hits.len() as u32,
343    })
344}
345
346/// Score and evidence for one group. `members`: the group's processes that are in the snapshot;
347/// `cohort`: the ended session that left it, when known. Deterministic: same inputs, same output.
348/// Executables installed by the OS itself (macOS sealed system volume, Linux system daemons).
349fn is_os_path(exe: &str) -> bool {
350    [
351        "/System/",
352        "/usr/libexec/",
353        "/usr/sbin/",
354        "/sbin/",
355        "/usr/lib/systemd/",
356        "/lib/systemd/",
357    ]
358    .iter()
359    .any(|pre| exe.starts_with(pre))
360}
361
362pub fn score_group(
363    g: &Group,
364    members: &[&Process],
365    now_ms: u64,
366    cfg: &StalenessConfig,
367    cohort: Option<&Cohort>,
368) -> Staleness {
369    if g.protected || g.is_self || g.kind == GroupKind::System || members.is_empty() {
370        return Staleness::default();
371    }
372    // Apps the OS ships (Spotlight, ControlCenter, Siri: bundles under /System) sit idle for days by design
373    // and are not the user's to stop; calling them stale is noise. Same paths attribution treats as system.
374    let root = g
375        .root
376        .and_then(|r| members.iter().find(|p| p.id == r))
377        .or(members.first());
378    if root.is_some_and(|p| is_os_path(&p.exe)) {
379        return Staleness::default();
380    }
381    let total = members.len();
382    let mut ev: Vec<StaleEvidence> = Vec::new();
383    let pick = |f: &dyn Fn(&Process) -> bool| -> Vec<&Process> {
384        members.iter().copied().filter(|p| f(p)).collect()
385    };
386
387    let hits = pick(&|p| p.cwd_missing == Some(true));
388    ev.extend(member_evidence(
389        StaleSignal::CwdMissing,
390        &hits,
391        total,
392        g.root,
393        "runs in a working directory that no longer exists",
394        "run in a working directory that no longer exists",
395    ));
396    let hits = pick(&|p| p.exe_change == Some(ExeChange::Deleted));
397    ev.extend(member_evidence(
398        StaleSignal::ExeDeleted,
399        &hits,
400        total,
401        g.root,
402        "runs an executable that was deleted after it started",
403        "run an executable that was deleted after they started",
404    ));
405    let hits = pick(&|p| p.exe_change == Some(ExeChange::Replaced));
406    ev.extend(member_evidence(
407        StaleSignal::ExeReplaced,
408        &hits,
409        total,
410        g.root,
411        "runs an executable that was replaced after it started (still the old version)",
412        "run an executable that was replaced after they started (still the old version)",
413    ));
414    let hits = pick(&|p| p.state == ProcState::Stopped);
415    ev.extend(member_evidence(
416        StaleSignal::Stopped,
417        &hits,
418        total,
419        g.root,
420        "is stopped (suspended, state T)",
421        "are stopped (suspended, state T)",
422    ));
423    // A listener with no clients is normal for apps (AirPlay receivers), agent sessions (IDE / MCP ports),
424    // sandboxes and the OS's own services: it only says "forgotten" for things that exist to be connected
425    // to — model servers, build daemons, loose dev servers — or for anything already orphaned.
426    let listening_matters = g.orphan
427        || matches!(
428            g.kind,
429            GroupKind::ModelServer | GroupKind::BuildDaemon | GroupKind::Other
430        );
431    let hits = if listening_matters {
432        pick(&|p| p.listening_no_clients == Some(true))
433    } else {
434        Vec::new()
435    };
436    ev.extend(member_evidence(
437        StaleSignal::ListeningNoClients,
438        &hits,
439        total,
440        g.root,
441        "listens on a port with no clients",
442        "listen on a port with no clients",
443    ));
444
445    if g.orphan {
446        let sentence = match cohort {
447            Some(c) => format!("orphaned: {}", c.sentence),
448            None => "orphaned: the agent session or tool that started it is gone".to_string(),
449        };
450        ev.push(StaleEvidence {
451            signal: StaleSignal::Orphaned,
452            weight: StaleSignal::Orphaned.base_weight(),
453            sentence,
454            pid: None,
455            members: 1,
456        });
457    }
458
459    if let Some(idle) = g.idle_for_s.filter(|i| *i >= cfg.idle_s && cfg.idle_s > 0) {
460        ev.push(StaleEvidence {
461            signal: StaleSignal::IdleLong,
462            weight: duration_weight(StaleSignal::IdleLong.base_weight(), idle, cfg.idle_s),
463            sentence: format!(
464                "idle for {} (threshold {})",
465                format_duration(idle),
466                format_duration(cfg.idle_s)
467            ),
468            pid: None,
469            members: 1,
470        });
471    }
472
473    if g.kind == GroupKind::AgentSession && cfg.transcript_s > 0 {
474        // The newest transcript any member reports (the session root carries it).
475        let newest = members
476            .iter()
477            .filter_map(|p| p.transcript_mtime_ms.value.map(|t| (t, p.id.pid)))
478            .max();
479        if let Some((mtime, pid)) = newest {
480            let quiet = now_ms.saturating_sub(mtime) / 1000;
481            if quiet >= cfg.transcript_s {
482                ev.push(StaleEvidence {
483                    signal: StaleSignal::TranscriptQuiet,
484                    weight: duration_weight(
485                        StaleSignal::TranscriptQuiet.base_weight(),
486                        quiet,
487                        cfg.transcript_s,
488                    ),
489                    sentence: format!(
490                        "session transcript not modified for {} (threshold {})",
491                        format_duration(quiet),
492                        format_duration(cfg.transcript_s)
493                    ),
494                    pid: Some(pid),
495                    members: 1,
496                });
497            }
498        }
499    }
500
501    for e in &mut ev {
502        e.weight = e.weight.clamp(0.0, 1.0);
503    }
504    ev.sort_by(|a, b| {
505        b.weight
506            .partial_cmp(&a.weight)
507            .unwrap_or(std::cmp::Ordering::Equal)
508            .then(a.signal.cmp(&b.signal))
509    });
510    let score = 1.0 - ev.iter().map(|e| 1.0 - e.weight).product::<f64>();
511    let old_enough = g.age_s.value.is_none_or(|a| a >= cfg.min_age_s);
512    Staleness {
513        score,
514        stale: !ev.is_empty() && score >= cfg.stale_score && old_enough,
515        evidence: ev,
516    }
517}
518
519// ---------------------------------------------------------------------------------------------------------
520// Cohorts and duplicates
521// ---------------------------------------------------------------------------------------------------------
522
523/// The dead agent session a group was left by: its `owner_group` names an agent session that is not a
524/// live group. `live`: ids of the groups in the snapshot.
525pub fn cohort_key<'a>(g: &'a Group, live: &HashMap<&str, GroupKind>) -> Option<&'a str> {
526    let o = g.owner_group.as_deref()?;
527    if o == g.id || live.contains_key(o) || !o.starts_with("agent:") {
528        return None;
529    }
530    Some(o)
531}
532
533fn cohort_sentence(label: &str, ended_ms: Option<u64>, now_ms: u64) -> String {
534    let who = if label.is_empty() || label == "agent session" {
535        "an agent session".to_string()
536    } else {
537        format!("the {label} session")
538    };
539    match ended_ms {
540        Some(t) => format!(
541            "left by {who} that ended {} ago",
542            format_duration(now_ms.saturating_sub(t) / 1000)
543        ),
544        None => format!("left by {who} that has ended"),
545    }
546}
547
548/// Buckets the groups whose owning agent session has ended by that session. Newest ended session first;
549/// sessions whose end time is unknown last, by id.
550pub fn cohorts(s: &Snapshot, ended: &BTreeMap<String, EndedSession>) -> Vec<Cohort> {
551    let live: HashMap<&str, GroupKind> = s.groups.iter().map(|g| (g.id.as_str(), g.kind)).collect();
552    let mut by_key: BTreeMap<&str, Vec<&Group>> = BTreeMap::new();
553    for g in &s.groups {
554        if let Some(k) = cohort_key(g, &live) {
555            by_key.entry(k).or_default().push(g);
556        }
557    }
558    let mut out: Vec<Cohort> = by_key
559        .into_iter()
560        .map(|(key, mut groups)| {
561            groups.sort_by(|a, b| {
562                b.totals
563                    .footprint
564                    .value
565                    .unwrap_or(0)
566                    .cmp(&a.totals.footprint.value.unwrap_or(0))
567                    .then(a.id.cmp(&b.id))
568            });
569            let known = ended.get(key);
570            let label = known
571                .map(|e| e.label.clone())
572                .filter(|l| !l.is_empty())
573                .unwrap_or_else(|| "agent session".to_string());
574            let ended_ms = known.and_then(|e| e.last_seen_ms).map(|t| t.min(s.taken_at_ms));
575            Cohort {
576                id: key.to_string(),
577                sentence: cohort_sentence(&label, ended_ms, s.taken_at_ms),
578                label,
579                ended_at_ms: match ended_ms {
580                    Some(t) => Measured::estimate(t, "lineage journal: session last seen"),
581                    None => Measured::unavailable(
582                        "lineage journal",
583                        "the session was never recorded (no journal data)",
584                    ),
585                },
586                group_ids: groups.iter().map(|g| g.id.clone()).collect(),
587                footprint: crate::measured::sum_bytes(
588                    groups.iter().map(|g| &g.totals.footprint),
589                    "Σ group footprint",
590                ),
591                process_count: groups.iter().map(|g| g.totals.process_count).sum(),
592            }
593        })
594        .collect();
595    out.sort_by(|a, b| {
596        b.ended_at_ms
597            .value
598            .cmp(&a.ended_at_ms.value)
599            .then(a.id.cmp(&b.id))
600    });
601    out
602}
603
604/// More than one live group with the same fingerprint in the same project. Protected, system and oomtop's
605/// own groups are left out. Largest total footprint first.
606pub fn duplicates(s: &Snapshot) -> Vec<DuplicateSet> {
607    let start: HashMap<ProcId, u64> = s.processes.iter().map(|p| (p.id, p.id.start_time)).collect();
608    let born = |g: &Group| -> u64 {
609        g.root
610            .and_then(|r| start.get(&r).copied())
611            .or_else(|| g.members.iter().filter_map(|m| start.get(&m.id).copied()).min())
612            .unwrap_or(u64::MAX)
613    };
614    let mut sets: BTreeMap<(&str, &str), Vec<&Group>> = BTreeMap::new();
615    for g in &s.groups {
616        if g.protected || g.is_self || g.kind == GroupKind::System || g.fingerprint.is_empty() {
617            continue;
618        }
619        let Some(project) = g.project.as_deref().filter(|p| !p.is_empty()) else {
620            continue;
621        };
622        sets.entry((g.fingerprint.as_str(), project)).or_default().push(g);
623    }
624    let mut out: Vec<DuplicateSet> = sets
625        .into_iter()
626        .filter(|(_, gs)| gs.len() > 1)
627        .map(|((fp, project), mut gs)| {
628            gs.sort_by(|a, b| born(a).cmp(&born(b)).then(a.id.cmp(&b.id)));
629            let footprint =
630                crate::measured::sum_bytes(gs.iter().map(|g| &g.totals.footprint), "Σ group footprint");
631            let largest = gs.iter().filter_map(|g| g.totals.footprint.value).max();
632            let extra_footprint = match (footprint.value, largest) {
633                (Some(sum), Some(max)) => {
634                    Measured::estimate(sum.saturating_sub(max), "Σ footprint − largest instance")
635                }
636                _ => Measured::unavailable("Σ footprint − largest instance", "footprint unavailable"),
637            };
638            DuplicateSet {
639                fingerprint: fp.to_string(),
640                kind: gs[0].kind,
641                label: gs[0].label.clone(),
642                project: project.to_string(),
643                group_ids: gs.iter().map(|g| g.id.clone()).collect(),
644                footprint,
645                extra_footprint,
646            }
647        })
648        .collect();
649    out.sort_by(|a, b| {
650        b.footprint
651            .value
652            .unwrap_or(0)
653            .cmp(&a.footprint.value.unwrap_or(0))
654            .then(a.fingerprint.cmp(&b.fingerprint))
655            .then(a.project.cmp(&b.project))
656    });
657    out
658}
659
660// ---------------------------------------------------------------------------------------------------------
661// apply
662// ---------------------------------------------------------------------------------------------------------
663
664/// The project of a group: its root's, else the most common among its members (ties: smallest path).
665fn group_project(root: Option<&Process>, members: &[&Process]) -> Option<String> {
666    if let Some(p) = root.and_then(|r| r.project.clone()).filter(|p| !p.is_empty()) {
667        return Some(p);
668    }
669    let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
670    for p in members {
671        if let Some(pr) = p.project.as_deref().filter(|p| !p.is_empty()) {
672            *counts.entry(pr).or_default() += 1;
673        }
674    }
675    counts
676        .into_iter()
677        .max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(a.0)))
678        .map(|(p, _)| p.to_string())
679}
680
681/// Fills every time and staleness field of the snapshot (see the module docs). Call after attribution and
682/// [`crate::idle::IdleTracker::apply`]; calling it again recomputes everything.
683pub fn apply(s: &mut Snapshot, cfg: &StalenessConfig, ended: &BTreeMap<String, EndedSession>) {
684    let now = s.taken_at_ms;
685    for p in &mut s.processes {
686        p.age_s = age_of(p.id, now);
687        // An idle time cannot exceed the age (a journal seeded from a reused pid would claim it).
688        if let (Some(idle), Some(age)) = (p.idle_for_s.value, p.age_s.value) {
689            if idle > age {
690                p.idle_for_s.value = Some(age);
691            }
692        }
693        if not_collected(&p.cpu_time_s) {
694            p.cpu_time_s = Measured::unavailable("cpu time", "not reported by this source");
695        }
696        p.duty_pct = duty_pct(&p.cpu_time_s, &p.age_s);
697        p.idle_rent_gib_h = idle_rent(&p.mem.footprint_or_pss, &p.idle_for_s, cfg.rent_after_s);
698        if not_collected(&p.transcript_mtime_ms) {
699            p.transcript_mtime_ms = Measured::unavailable("agent transcript", "not an agent session root");
700        }
701    }
702
703    // Groups: everything but staleness (which wants the cohorts, which want `project`-free groups only).
704    struct Times {
705        age_s: Measured<u64>,
706        cpu_time_s: Measured<f64>,
707        duty_pct: Measured<f64>,
708        longest_idle: Option<(u64, ProcId)>,
709        rent: Measured<f64>,
710        project: Option<String>,
711    }
712    let by_id: HashMap<ProcId, &Process> = s.processes.iter().map(|p| (p.id, p)).collect();
713    let live: HashMap<&str, GroupKind> = s.groups.iter().map(|g| (g.id.as_str(), g.kind)).collect();
714    let mut times: Vec<Times> = Vec::with_capacity(s.groups.len());
715    let mut cohort_keys: Vec<Option<String>> = Vec::with_capacity(s.groups.len());
716    for g in &s.groups {
717        let members: Vec<&Process> = g
718            .members
719            .iter()
720            .filter_map(|m| by_id.get(&m.id).copied())
721            .collect();
722        let root = g.root.and_then(|r| by_id.get(&r).copied());
723        let age_s = match root.filter(|r| r.age_s.value.is_some()) {
724            Some(r) => Measured {
725                source: format!("root process: {SOURCE_AGE}").into(),
726                ..r.age_s.clone()
727            },
728            None => match members.iter().filter_map(|p| p.age_s.value).max() {
729                Some(a) => Measured::exact(a, format!("oldest member: {SOURCE_AGE}")),
730                None => Measured::unavailable(SOURCE_AGE, "start time unknown"),
731            },
732        };
733        let cpu_time_s = sum_f64(members.iter().map(|p| &p.cpu_time_s), "Σ member CPU time");
734        let duty = duty_pct(&cpu_time_s, &age_s);
735        let longest_idle = members
736            .iter()
737            .filter_map(|p| p.idle_for_s.value.map(|i| (i, p.id)))
738            .max_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
739        let rent = {
740            let mut m = sum_f64(members.iter().map(|p| &p.idle_rent_gib_h), SOURCE_RENT);
741            if m.value.is_some() {
742                m.quality = Quality::Estimate;
743            }
744            m
745        };
746        times.push(Times {
747            age_s,
748            cpu_time_s,
749            duty_pct: duty,
750            longest_idle,
751            rent,
752            project: group_project(root, &members),
753        });
754        cohort_keys.push(cohort_key(g, &live).map(str::to_string));
755    }
756    drop(by_id);
757    drop(live);
758    for ((g, t), c) in s.groups.iter_mut().zip(times).zip(cohort_keys) {
759        g.age_s = t.age_s;
760        g.cpu_time_s = t.cpu_time_s;
761        g.duty_pct = t.duty_pct;
762        g.longest_idle_s = t.longest_idle.map(|x| x.0);
763        g.longest_idle = t.longest_idle.map(|x| x.1);
764        g.idle_rent_gib_h = t.rent;
765        g.project = t.project;
766        g.cohort = c;
767    }
768
769    s.cohorts = cohorts(s, ended);
770    s.duplicates = duplicates(s);
771
772    let by_id: HashMap<ProcId, &Process> = s.processes.iter().map(|p| (p.id, p)).collect();
773    let cohort_of: HashMap<&str, &Cohort> = s.cohorts.iter().map(|c| (c.id.as_str(), c)).collect();
774    let scores: Vec<Staleness> = s
775        .groups
776        .iter()
777        .map(|g| {
778            let members: Vec<&Process> = g
779                .members
780                .iter()
781                .filter_map(|m| by_id.get(&m.id).copied())
782                .collect();
783            let cohort = g.cohort.as_deref().and_then(|c| cohort_of.get(c).copied());
784            score_group(g, &members, now, cfg, cohort)
785        })
786        .collect();
787    for (g, st) in s.groups.iter_mut().zip(scores) {
788        g.staleness = st;
789    }
790}
791
792/// Groups worth showing in a "stale" list: those with any evidence, most stale first (score, then idle
793/// rent, then footprint, then id — fully deterministic).
794pub fn ranked(s: &Snapshot) -> Vec<&Group> {
795    let mut v: Vec<&Group> = s
796        .groups
797        .iter()
798        .filter(|g| !g.staleness.evidence.is_empty())
799        .collect();
800    v.sort_by(|a, b| {
801        b.staleness
802            .stale
803            .cmp(&a.staleness.stale)
804            .then(
805                b.staleness
806                    .score
807                    .partial_cmp(&a.staleness.score)
808                    .unwrap_or(std::cmp::Ordering::Equal),
809            )
810            .then(
811                b.idle_rent_gib_h
812                    .value
813                    .unwrap_or(0.0)
814                    .partial_cmp(&a.idle_rent_gib_h.value.unwrap_or(0.0))
815                    .unwrap_or(std::cmp::Ordering::Equal),
816            )
817            .then(
818                b.totals
819                    .footprint
820                    .value
821                    .unwrap_or(0)
822                    .cmp(&a.totals.footprint.value.unwrap_or(0)),
823            )
824            .then(a.id.cmp(&b.id))
825    });
826    v
827}
828
829#[cfg(test)]
830mod tests {
831    use super::*;
832    use crate::model::Member;
833
834    const NOW: u64 = 2_000_000_000_000;
835    const H: u64 = 3600;
836
837    fn proc(pid: u32, age_s: u64) -> Process {
838        Process {
839            id: ProcId::new(pid, NOW - age_s * 1000),
840            name: format!("p{pid}"),
841            mem: crate::model::MemBreakdown {
842                footprint_or_pss: Measured::exact(2 << 30, "test"),
843                ..Default::default()
844            },
845            cpu_time_s: Measured::exact(36.0, "test"),
846            idle_for_s: Measured::estimate(0, "test"),
847            ..Default::default()
848        }
849    }
850
851    fn group(id: &str, kind: GroupKind, procs: &[&Process]) -> Group {
852        Group {
853            id: id.into(),
854            kind,
855            label: id.into(),
856            fingerprint: format!("fp-{id}"),
857            root: procs.first().map(|p| p.id),
858            members: procs
859                .iter()
860                .map(|p| Member {
861                    id: p.id,
862                    ..Default::default()
863                })
864                .collect(),
865            totals: crate::model::GroupTotals {
866                footprint: Measured::exact(
867                    procs.iter().filter_map(|p| p.mem.footprint_or_pss.value).sum(),
868                    "test",
869                ),
870                process_count: procs.len() as u32,
871                ..Default::default()
872            },
873            ..Default::default()
874        }
875    }
876
877    fn snap(procs: Vec<Process>, groups: Vec<Group>) -> Snapshot {
878        Snapshot {
879            taken_at_ms: NOW,
880            processes: procs,
881            groups,
882            ..Default::default()
883        }
884    }
885
886    fn one(p: Process, kind: GroupKind, edit: impl FnOnce(&mut Group)) -> Snapshot {
887        let mut g = group("g", kind, &[&p]);
888        edit(&mut g);
889        let mut s = snap(vec![p], vec![g]);
890        apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
891        s
892    }
893
894    #[test]
895    fn age_cpu_time_and_duty_per_process_and_group() {
896        let a = proc(1, 3600);
897        let mut b = proc(2, 600);
898        b.cpu_time_s = Measured::exact(60.0, "test");
899        let g = group("g", GroupKind::Other, &[&a, &b]);
900        let mut s = snap(vec![a, b], vec![g]);
901        apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
902        let p = &s.processes[0];
903        assert_eq!(p.age_s.value, Some(3600));
904        assert_eq!(p.age_s.quality, Quality::Exact);
905        assert_eq!(
906            p.duty_pct.value,
907            Some(1.0),
908            "36 s of CPU in 3600 s = 1 % of one core"
909        );
910        assert_eq!(p.duty_pct.quality, Quality::Exact);
911        assert_eq!(s.processes[1].duty_pct.value, Some(10.0));
912        let g = &s.groups[0];
913        assert_eq!(g.age_s.value, Some(3600), "the root's age");
914        assert!(g.age_s.source.starts_with("root process"));
915        assert_eq!(g.cpu_time_s.value, Some(96.0));
916        assert!((g.duty_pct.value.unwrap() - 96.0 / 3600.0 * 100.0).abs() < 1e-9);
917    }
918
919    #[test]
920    fn unknown_inputs_stay_unavailable_never_zero() {
921        let mut p = proc(1, 100);
922        p.id.start_time = 0;
923        p.cpu_time_s = Measured::default();
924        p.idle_for_s = Measured::unavailable("idle tracker", "no CPU data");
925        let s = one(p, GroupKind::Other, |_| {});
926        let p = &s.processes[0];
927        assert_eq!(p.age_s.value, None);
928        assert_eq!(p.age_s.unavailable_reason(), Some("start time unknown"));
929        assert_eq!(
930            p.cpu_time_s.unavailable_reason(),
931            Some("not reported by this source")
932        );
933        assert_eq!(p.duty_pct.value, None);
934        assert_eq!(p.idle_rent_gib_h.value, None);
935        assert_eq!(p.idle_rent_gib_h.unavailable_reason(), Some("no CPU data"));
936        let g = &s.groups[0];
937        assert_eq!(
938            (g.age_s.value, g.cpu_time_s.value, g.duty_pct.value),
939            (None, None, None)
940        );
941        assert_eq!(g.idle_rent_gib_h.value, None);
942    }
943
944    #[test]
945    fn group_age_falls_back_to_the_oldest_member() {
946        let a = proc(1, 100);
947        let b = proc(2, 900);
948        let mut g = group("g", GroupKind::Other, &[&a, &b]);
949        g.root = None;
950        let mut s = snap(vec![a, b], vec![g]);
951        apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
952        assert_eq!(s.groups[0].age_s.value, Some(900));
953        assert!(s.groups[0].age_s.source.starts_with("oldest member"));
954    }
955
956    #[test]
957    fn idle_rent_is_gib_hours_and_an_estimate() {
958        // 2 GiB idle for 5 h = 10 GiB·h; a member idle for less than the rent threshold adds nothing.
959        let mut a = proc(1, 10 * H);
960        a.idle_for_s = Measured::estimate(5 * H, "test");
961        let mut b = proc(2, 10 * H);
962        b.idle_for_s = Measured::estimate(60, "test");
963        let g = group("g", GroupKind::Other, &[&a, &b]);
964        let mut s = snap(vec![a, b], vec![g]);
965        apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
966        assert_eq!(s.processes[0].idle_rent_gib_h.value, Some(10.0));
967        assert_eq!(s.processes[0].idle_rent_gib_h.quality, Quality::Estimate);
968        assert_eq!(s.processes[1].idle_rent_gib_h.value, Some(0.0));
969        let g = &s.groups[0];
970        assert_eq!(g.idle_rent_gib_h.value, Some(10.0));
971        assert_eq!(g.idle_rent_gib_h.quality, Quality::Estimate);
972        assert_eq!(g.longest_idle_s, Some(5 * H));
973        assert_eq!(g.longest_idle.map(|p| p.pid), Some(1));
974    }
975
976    #[test]
977    fn idle_time_is_capped_by_age() {
978        let mut p = proc(1, 100);
979        p.idle_for_s = Measured::estimate(5_000, "test");
980        let s = one(p, GroupKind::Other, |_| {});
981        assert_eq!(s.processes[0].idle_for_s.value, Some(100));
982    }
983
984    /// One row per signal: the evidence it produces, its weight and whether it alone makes a group stale.
985    #[test]
986    fn signal_table() {
987        type Edit = fn(&mut Process, &mut Group);
988        let rows: [(StaleSignal, Edit, f64, bool, &str); 8] = [
989            (
990                StaleSignal::CwdMissing,
991                |p, _| p.cwd_missing = Some(true),
992                0.6,
993                true,
994                "p1 (pid 1) runs in a working directory that no longer exists",
995            ),
996            (
997                StaleSignal::ExeDeleted,
998                |p, _| p.exe_change = Some(ExeChange::Deleted),
999                0.45,
1000                false,
1001                "p1 (pid 1) runs an executable that was deleted after it started",
1002            ),
1003            (
1004                StaleSignal::ExeReplaced,
1005                |p, _| p.exe_change = Some(ExeChange::Replaced),
1006                0.35,
1007                false,
1008                "p1 (pid 1) runs an executable that was replaced after it started (still the old version)",
1009            ),
1010            (
1011                StaleSignal::Stopped,
1012                |p, _| p.state = ProcState::Stopped,
1013                0.5,
1014                true,
1015                "p1 (pid 1) is stopped (suspended, state T)",
1016            ),
1017            (
1018                StaleSignal::Orphaned,
1019                |_, g| g.orphan = true,
1020                0.6,
1021                true,
1022                "orphaned: the agent session or tool that started it is gone",
1023            ),
1024            (
1025                StaleSignal::IdleLong,
1026                |_, g| g.idle_for_s = Some(4 * H),
1027                0.3,
1028                false,
1029                "idle for 4h (threshold 4h)",
1030            ),
1031            (
1032                StaleSignal::TranscriptQuiet,
1033                |p, g| {
1034                    g.kind = GroupKind::AgentSession;
1035                    p.transcript_mtime_ms = Measured::exact(NOW - 12 * H * 1000, "test");
1036                },
1037                0.4,
1038                false,
1039                "session transcript not modified for 12h (threshold 12h)",
1040            ),
1041            (
1042                StaleSignal::ListeningNoClients,
1043                |p, _| p.listening_no_clients = Some(true),
1044                0.3,
1045                false,
1046                "p1 (pid 1) listens on a port with no clients",
1047            ),
1048        ];
1049        for (signal, edit, weight, stale, sentence) in rows {
1050            let mut p = proc(1, 100 * H);
1051            let mut g = group("g", GroupKind::Other, &[&p]);
1052            edit(&mut p, &mut g);
1053            let mut s = snap(vec![p], vec![g]);
1054            apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
1055            let st = &s.groups[0].staleness;
1056            assert_eq!(st.evidence.len(), 1, "{signal:?}: {st:?}");
1057            let e = &st.evidence[0];
1058            assert_eq!(e.signal, signal);
1059            assert!(
1060                (e.weight - weight).abs() < 1e-9,
1061                "{signal:?}: weight {}",
1062                e.weight
1063            );
1064            assert!((st.score - weight).abs() < 1e-9, "{signal:?}: score {}", st.score);
1065            assert_eq!(st.stale, stale, "{signal:?}");
1066            assert_eq!(e.sentence, sentence);
1067        }
1068    }
1069
1070    #[test]
1071    fn no_evidence_means_score_zero_and_not_stale() {
1072        let s = one(proc(1, 100 * H), GroupKind::Other, |_| {});
1073        assert_eq!(s.groups[0].staleness, Staleness::default());
1074        assert!(ranked(&s).is_empty());
1075    }
1076
1077    #[test]
1078    fn evidence_combines_as_noisy_or_strongest_first() {
1079        let mut p = proc(1, 100 * H);
1080        p.exe_change = Some(ExeChange::Replaced);
1081        p.cwd_missing = Some(true);
1082        let s = one(p, GroupKind::Other, |g| g.idle_for_s = Some(4 * H));
1083        let st = &s.groups[0].staleness;
1084        let signals: Vec<StaleSignal> = st.evidence.iter().map(|e| e.signal).collect();
1085        assert_eq!(
1086            signals,
1087            vec![
1088                StaleSignal::CwdMissing,
1089                StaleSignal::ExeReplaced,
1090                StaleSignal::IdleLong
1091            ]
1092        );
1093        let want = 1.0 - 0.4 * 0.65 * 0.7;
1094        assert!((st.score - want).abs() < 1e-9);
1095        assert!(st.stale);
1096        assert!(st.score < 1.0);
1097    }
1098
1099    #[test]
1100    fn duration_signals_grow_with_the_duration_up_to_twice_the_base() {
1101        for (idle_h, want) in [(4, 0.3), (8, 0.4), (16, 0.5), (32, 0.6), (1000, 0.6)] {
1102            let s = one(proc(1, 2000 * H), GroupKind::Other, |g| {
1103                g.idle_for_s = Some(idle_h * H)
1104            });
1105            let w = s.groups[0].staleness.evidence[0].weight;
1106            assert!((w - want).abs() < 1e-9, "{idle_h} h: {w}");
1107        }
1108        // below the threshold: no evidence at all
1109        let s = one(proc(1, 2000 * H), GroupKind::Other, |g| {
1110            g.idle_for_s = Some(4 * H - 1)
1111        });
1112        assert!(s.groups[0].staleness.evidence.is_empty());
1113        // 32 h idle alone is enough to be stale
1114        let s = one(proc(1, 2000 * H), GroupKind::Other, |g| {
1115            g.idle_for_s = Some(32 * H)
1116        });
1117        assert!(s.groups[0].staleness.stale);
1118    }
1119
1120    #[test]
1121    fn thresholds_come_from_the_config() {
1122        let p = proc(1, 100 * H);
1123        let mut g = group("g", GroupKind::Other, &[&p]);
1124        g.idle_for_s = Some(H);
1125        let mut s = snap(vec![p], vec![g]);
1126        let cfg = StalenessConfig {
1127            idle_s: H,
1128            stale_score: 0.25,
1129            ..Default::default()
1130        };
1131        apply(&mut s, &cfg, &BTreeMap::new());
1132        let st = &s.groups[0].staleness;
1133        assert_eq!(st.evidence[0].sentence, "idle for 1h (threshold 1h)");
1134        assert!(st.stale, "0.3 ≥ 0.25");
1135        // idle_s = 0 turns the signal off
1136        let cfg = StalenessConfig {
1137            idle_s: 0,
1138            ..Default::default()
1139        };
1140        apply(&mut s, &cfg, &BTreeMap::new());
1141        assert!(s.groups[0].staleness.evidence.is_empty());
1142    }
1143
1144    #[test]
1145    fn young_groups_are_scored_but_never_flagged() {
1146        let mut p = proc(1, 60);
1147        p.cwd_missing = Some(true);
1148        let s = one(p, GroupKind::Other, |_| {});
1149        let st = &s.groups[0].staleness;
1150        assert!((st.score - 0.6).abs() < 1e-9);
1151        assert!(!st.stale, "younger than min_age_s");
1152    }
1153
1154    #[test]
1155    fn protected_system_and_self_groups_are_never_scored() {
1156        for edit in [
1157            (|g: &mut Group| g.protected = true) as fn(&mut Group),
1158            |g| g.is_self = true,
1159            |g| g.kind = GroupKind::System,
1160        ] {
1161            let mut p = proc(1, 100 * H);
1162            p.cwd_missing = Some(true);
1163            p.state = ProcState::Stopped;
1164            let s = one(p, GroupKind::Other, |g| {
1165                g.orphan = true;
1166                edit(g)
1167            });
1168            assert_eq!(s.groups[0].staleness, Staleness::default());
1169        }
1170    }
1171
1172    #[test]
1173    fn member_signals_count_members_and_weigh_by_share() {
1174        let root = proc(1, 100 * H);
1175        let mut a = proc(2, 100 * H);
1176        a.state = ProcState::Stopped;
1177        let b = proc(3, 100 * H);
1178        let c = proc(4, 100 * H);
1179        let g = group("g", GroupKind::Other, &[&root, &a, &b, &c]);
1180        let mut s = snap(vec![root, a, b, c], vec![g]);
1181        apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
1182        let e = &s.groups[0].staleness.evidence[0];
1183        // 1 of 4 members, not the root: half the base weight (the floor)
1184        assert!((e.weight - 0.25).abs() < 1e-9);
1185        assert_eq!(e.sentence, "p2 (pid 2) is stopped (suspended, state T)");
1186        assert_eq!((e.pid, e.members), (Some(2), 1));
1187
1188        // three of four, including the root: full weight, counted sentence
1189        for p in s.processes.iter_mut().take(3) {
1190            p.state = ProcState::Stopped;
1191        }
1192        apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
1193        let e = &s.groups[0].staleness.evidence[0];
1194        assert!((e.weight - 0.5).abs() < 1e-9);
1195        assert_eq!(e.sentence, "3 of 4 processes are stopped (suspended, state T)");
1196        assert_eq!((e.pid, e.members), (None, 3));
1197    }
1198
1199    #[test]
1200    fn transcript_signal_is_for_agent_sessions_only() {
1201        let mut p = proc(1, 100 * H);
1202        p.transcript_mtime_ms = Measured::exact(NOW - 20 * H * 1000, "test");
1203        let s = one(p.clone(), GroupKind::App, |_| {});
1204        assert!(s.groups[0].staleness.evidence.is_empty());
1205        let s = one(p, GroupKind::AgentSession, |_| {});
1206        assert_eq!(
1207            s.groups[0].staleness.evidence[0].signal,
1208            StaleSignal::TranscriptQuiet
1209        );
1210        // a process without a transcript gets a reason, not a zero
1211        let s = one(proc(1, 100), GroupKind::AgentSession, |_| {});
1212        assert_eq!(
1213            s.processes[0].transcript_mtime_ms.unavailable_reason(),
1214            Some("not an agent session root")
1215        );
1216    }
1217
1218    fn leftovers() -> Snapshot {
1219        let live_root = proc(1, 10 * H);
1220        let a = proc(2, 9 * H);
1221        let mut b = proc(3, 8 * H);
1222        b.mem.footprint_or_pss = Measured::exact(5 << 30, "test");
1223        let c = proc(4, 7 * H);
1224        let d = proc(5, 7 * H);
1225        let live = group("agent:claude-code:1", GroupKind::AgentSession, &[&live_root]);
1226        let mut ga = group("daemon:a:2", GroupKind::BuildDaemon, &[&a]);
1227        ga.owner_group = Some("agent:deadbeef0001".into());
1228        ga.orphan = true;
1229        let mut gb = group("other:b:3", GroupKind::Other, &[&b]);
1230        gb.owner_group = Some("agent:deadbeef0001".into());
1231        let mut gc = group("other:c:4", GroupKind::Other, &[&c]);
1232        gc.owner_group = Some("agent:feedface0002".into());
1233        // owned by a live session: not a cohort
1234        let mut gd = group("other:d:5", GroupKind::Other, &[&d]);
1235        gd.owner_group = Some("agent:claude-code:1".into());
1236        snap(vec![live_root, a, b, c, d], vec![live, ga, gb, gc, gd])
1237    }
1238
1239    #[test]
1240    fn cohorts_bucket_leftovers_by_the_session_that_ended() {
1241        let mut s = leftovers();
1242        let mut ended = BTreeMap::new();
1243        ended.insert(
1244            "agent:deadbeef0001".to_string(),
1245            EndedSession {
1246                label: "Claude Code".into(),
1247                last_seen_ms: Some(NOW - 3 * H * 1000),
1248            },
1249        );
1250        apply(&mut s, &StalenessConfig::default(), &ended);
1251        assert_eq!(s.cohorts.len(), 2);
1252        let c = &s.cohorts[0];
1253        assert_eq!(c.id, "agent:deadbeef0001");
1254        assert_eq!(c.label, "Claude Code");
1255        assert_eq!(c.ended_at_ms.value, Some(NOW - 3 * H * 1000));
1256        assert_eq!(c.ended_at_ms.quality, Quality::Estimate);
1257        assert_eq!(c.group_ids, vec!["other:b:3", "daemon:a:2"], "largest first");
1258        assert_eq!(c.footprint.value, Some(7 << 30));
1259        assert_eq!(c.process_count, 2);
1260        assert_eq!(c.sentence, "left by the Claude Code session that ended 3h ago");
1261        // no journal data: still a cohort, the end time is unavailable with a reason
1262        let c = &s.cohorts[1];
1263        assert_eq!(c.id, "agent:feedface0002");
1264        assert_eq!(c.ended_at_ms.value, None);
1265        assert!(c.ended_at_ms.unavailable_reason().is_some());
1266        assert_eq!(c.sentence, "left by an agent session that has ended");
1267        // groups carry their cohort; the live session's child does not
1268        let cohort = |id: &str| s.group(id).unwrap().cohort.clone();
1269        assert_eq!(cohort("daemon:a:2").as_deref(), Some("agent:deadbeef0001"));
1270        assert_eq!(cohort("other:d:5"), None);
1271        assert_eq!(cohort("agent:claude-code:1"), None);
1272        // the orphan's evidence names the session
1273        let ev = &s.group("daemon:a:2").unwrap().staleness.evidence[0];
1274        assert_eq!(
1275            ev.sentence,
1276            "orphaned: left by the Claude Code session that ended 3h ago"
1277        );
1278    }
1279
1280    #[test]
1281    fn duplicates_are_same_fingerprint_in_the_same_project() {
1282        let mut procs = Vec::new();
1283        let mut groups = Vec::new();
1284        for (pid, age, project, fp) in [
1285            (1u32, 500, Some("/w/app"), "gradle"),
1286            (2, 900, Some("/w/app"), "gradle"),
1287            (3, 100, Some("/w/app"), "gradle"),
1288            (4, 100, Some("/w/other"), "gradle"),
1289            (5, 100, Some("/w/app"), "tsserver"),
1290            (6, 100, None, "nop"),
1291            (7, 100, None, "nop"),
1292        ] {
1293            let mut p = proc(pid, age);
1294            p.project = project.map(str::to_string);
1295            let mut g = group(&format!("g{pid}"), GroupKind::BuildDaemon, &[&p]);
1296            g.fingerprint = fp.into();
1297            procs.push(p);
1298            groups.push(g);
1299        }
1300        let mut s = snap(procs, groups);
1301        apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
1302        assert_eq!(s.duplicates.len(), 1, "{:?}", s.duplicates);
1303        let d = &s.duplicates[0];
1304        assert_eq!((d.fingerprint.as_str(), d.project.as_str()), ("gradle", "/w/app"));
1305        assert_eq!(d.group_ids, vec!["g2", "g1", "g3"], "oldest first");
1306        assert_eq!(d.footprint.value, Some(6 << 30));
1307        assert_eq!(d.extra_footprint.value, Some(4 << 30));
1308        assert_eq!(d.extra_footprint.quality, Quality::Estimate);
1309        assert_eq!(s.group("g1").unwrap().project.as_deref(), Some("/w/app"));
1310    }
1311
1312    #[test]
1313    fn group_project_prefers_the_root_then_the_majority() {
1314        let mut root = proc(1, 100);
1315        let mut a = proc(2, 100);
1316        let mut b = proc(3, 100);
1317        a.project = Some("/w/x".into());
1318        b.project = Some("/w/x".into());
1319        let g = group("g", GroupKind::Other, &[&root, &a, &b]);
1320        let mut s = snap(vec![root.clone(), a.clone(), b.clone()], vec![g]);
1321        apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
1322        assert_eq!(s.groups[0].project.as_deref(), Some("/w/x"));
1323        root.project = Some("/w/root".into());
1324        let g = group("g", GroupKind::Other, &[&root, &a, &b]);
1325        let mut s = snap(vec![root, a, b], vec![g]);
1326        apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
1327        assert_eq!(s.groups[0].project.as_deref(), Some("/w/root"));
1328    }
1329
1330    #[test]
1331    fn ranking_is_deterministic_and_stale_first() {
1332        let mut a = proc(1, 100 * H);
1333        a.cwd_missing = Some(true);
1334        let mut b = proc(2, 100 * H);
1335        b.exe_change = Some(ExeChange::Replaced);
1336        let mut c = proc(3, 100 * H);
1337        c.cwd_missing = Some(true);
1338        c.mem.footprint_or_pss = Measured::exact(9 << 30, "test");
1339        let quiet = proc(4, 100 * H);
1340        let groups = vec![
1341            group("a", GroupKind::Other, &[&a]),
1342            group("b", GroupKind::Other, &[&b]),
1343            group("c", GroupKind::Other, &[&c]),
1344            group("quiet", GroupKind::Other, &[&quiet]),
1345        ];
1346        let mut s = snap(vec![a, b, c, quiet], groups);
1347        apply(&mut s, &StalenessConfig::default(), &BTreeMap::new());
1348        let ids: Vec<&str> = ranked(&s).iter().map(|g| g.id.as_str()).collect();
1349        assert_eq!(ids, vec!["c", "a", "b"], "same score: larger footprint first");
1350        let again = {
1351            let mut t = s.clone();
1352            apply(&mut t, &StalenessConfig::default(), &BTreeMap::new());
1353            t
1354        };
1355        assert_eq!(again, s, "apply is idempotent");
1356    }
1357
1358    #[test]
1359    fn uncomputed_fields_are_not_serialized() {
1360        let s = snap(vec![proc(1, 100)], vec![group("g", GroupKind::Other, &[])]);
1361        let mut p = s.processes[0].clone();
1362        p.cpu_time_s = Measured::default();
1363        let j = serde_json::to_value(&p).unwrap();
1364        for k in [
1365            "age_s",
1366            "cpu_time_s",
1367            "duty_pct",
1368            "idle_rent_gib_h",
1369            "cwd_missing",
1370            "project",
1371        ] {
1372            assert!(j.get(k).is_none(), "{k} serialized before apply");
1373        }
1374        let j = serde_json::to_value(&s.groups[0]).unwrap();
1375        for k in [
1376            "age_s",
1377            "staleness",
1378            "cohort",
1379            "idle_rent_gib_h",
1380            "longest_idle_s",
1381        ] {
1382            assert!(j.get(k).is_none(), "{k} serialized before apply");
1383        }
1384        let j = serde_json::to_value(&s).unwrap();
1385        assert!(j.get("cohorts").is_none() && j.get("duplicates").is_none());
1386        // …and after apply they are there and round-trip
1387        let mut t = s.clone();
1388        apply(&mut t, &StalenessConfig::default(), &BTreeMap::new());
1389        let j = serde_json::to_string(&t).unwrap();
1390        assert!(j.contains("\"age_s\"") && j.contains("\"duty_pct\""));
1391        let back: Snapshot = serde_json::from_str(&j).unwrap();
1392        assert_eq!(back, t);
1393    }
1394}