Skip to main content

oomtop_core/
attribution.rs

1//! Attribution (SPEC §7): group every process under the agent session, app, sandbox, model server, build
2//! daemon or system component that owns it. Pure: works over a [`Snapshot`], compiled rules and lineage data.
3//!
4//! ## Signals, in the order they are tried for each process
5//! 0. **oomtop itself** — its own process tree forms the `oomtop` group, except that an `oomtop mcp` child
6//!    stays inside the agent session that launched it (and is excluded from that session's reclaim gain).
7//! 1. **Adapter truth** — pids that adapters already mapped (`Snapshot::model_servers[].pids`,
8//!    `Snapshot::sandboxes[].host_pids`) when attribution runs after an adapter probe.
9//! 2. **cgroup path** (Linux) — container / VM scopes (docker, podman, containerd, CRI-O, kubepods, LXC,
10//!    libvirt/QEMU machines) form sandbox groups.
11//! 3. **Rule roots** — an identity match (`match.exe|name|script|cmdline|cwd|bundle|cgroup`, OR'd) makes the
12//!    process a group root, keyed by rule and root pid (`agent:<rule-id>:<pid>`). A root merges into a
13//!    same-rule parent (`ollama serve` → `ollama runner`, a `claude -p` started by a Claude Code session).
14//!    The id never depends on which descendants happen to be running: a root with `session_key` learns its
15//!    (hashed) session id from its marker-carrying descendants, but that id is only an *alias*
16//!    (`agent:<hash12>`) used to find the session — by markers below, and by journals written before ids
17//!    were pid-keyed.
18//! 4. **Session markers** — a process carrying an allowlisted marker (`CLAUDECODE`, hashed
19//!    `CLAUDE_CODE_SESSION_ID`) joins the live session with that id, even after being re-parented. The id
20//!    is read from the rule's own `session_key` (an agent started inside another agent carries both ids);
21//!    when several sessions match, the one the parent already belongs to wins, else the innermost (the
22//!    one with the youngest root).
23//! 5. **Responsible pid** (macOS) — XPC services / helpers join the app that is responsible for them (the
24//!    `com.apple.Virtualization.VirtualMachine` XPC → Claude.app). Ignored when the responsible process is a
25//!    terminal or the process was launched from a shell (macOS makes the terminal "responsible" for every
26//!    command typed into it).
27//! 6. **Ancestry** — the ppid chain. Terminals, interactive shells and `sudo`-style launchers are
28//!    *boundaries*: a command typed into a shell becomes its own root unless the shell itself belongs to a
29//!    rule-defined group (e.g. an agent session), so the terminal app does not swallow everything run in it;
30//!    terminal plumbing (`login`, interactive shells, `tmux`, `sudo`) stays in the terminal's group.
31//!    `launchd` / `systemd` / `init` are subreapers, never owners.
32//! 7. **Lineage journal** — a re-parented process (recorded ppid > 1, now 1 / a subreaper / a reused pid)
33//!    rejoins its recorded group while that group is alive; otherwise it becomes an **orphan root** whose
34//!    `owner_group` names the group that spawned it.
35//! 8. **Dead-session markers** — like 7 for marker carriers whose session root has exited.
36//! 9. **systemd unit / app scope** (Linux) — top-level processes of the same `.service` / `app-*.scope` share
37//!    a group.
38//! 10. **Heuristic** — the process is a top-level root: apps are keyed by bundle name (`app:google-chrome`),
39//!     system daemons by name, everything else by name + pid.
40//!
41//! Every process lands in exactly one group; groups are sorted by footprint desc; group ids are stable
42//! across samples for the same root. Identity is always `(pid, start_time)`: a parent whose start time is
43//! after its child's is a reused pid and is not treated as the parent.
44//!
45//! ## Rule semantics
46//! `[[group]]` in `rules.d/*.toml` (SPEC §15): within `match`, **fields are OR'd** (any identity field
47//! matching makes the process a group root) and values within a field are OR'd. `match.env` is not an
48//! identity match: it groups processes carrying those marker keys into the session (by `session_key`) of the
49//! rule's root. `exclude` vetoes a match. Higher `priority` wins; ties → first rule. Globs are case-sensitive;
50//! `match.exe` is tried against the executable path, its basename and argv[0] (self-updating CLIs such as
51//! Claude Code run from a versioned file, so argv[0] is the stable name).
52
53use crate::actions::{is_protected_process, ProtectContext};
54use crate::fingerprint;
55use crate::measured::{sum_bytes, sum_f64};
56use crate::model::{
57    AttributionSignal, Confidence, Group, GroupKind, GroupTotals, Member, ModelServerKind, ProcId, Process,
58    SandboxKind, Snapshot,
59};
60use globset::{Glob, GlobBuilder, GlobSet, GlobSetBuilder};
61use regex::Regex;
62use serde::{Deserialize, Serialize};
63use std::collections::{BTreeMap, HashMap, HashSet};
64use thiserror::Error;
65
66/// Group id of oomtop's own processes.
67pub const SELF_GROUP_ID: &str = "oomtop";
68/// Ancestry walks stop after this many hops (cycle / pathological-depth guard).
69const MAX_DEPTH: usize = 256;
70
71// ---------------------------------------------------------------------------------------------------------
72// Rules
73// ---------------------------------------------------------------------------------------------------------
74
75/// Identity match fields of a rule.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
77#[serde(default, deny_unknown_fields)]
78pub struct MatchSpec {
79    /// Globs against the executable path, its basename and argv[0] (e.g. "claude", "**/bin/sd-server").
80    pub exe: Vec<String>,
81    /// Globs against the short process name (comm).
82    pub name: Vec<String>,
83    /// Globs against any argv element after argv[0] (node/python scripts, java main classes).
84    pub script: Vec<String>,
85    /// Regexes against the space-joined command line.
86    pub cmdline: Vec<String>,
87    /// Marker keys (must be in the allowlist); groups carriers into the rule's session. Not an identity match.
88    pub env: Vec<String>,
89    /// Globs against cwd.
90    pub cwd: Vec<String>,
91    /// Globs against the macOS bundle id.
92    pub bundle: Vec<String>,
93    /// Globs against the Linux cgroup path.
94    pub cgroup: Vec<String>,
95}
96
97impl MatchSpec {
98    fn has_identity(&self) -> bool {
99        !(self.exe.is_empty()
100            && self.name.is_empty()
101            && self.script.is_empty()
102            && self.cmdline.is_empty()
103            && self.cwd.is_empty()
104            && self.bundle.is_empty()
105            && self.cgroup.is_empty())
106    }
107}
108
109/// One detection rule (TOML `[[group]]`).
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111#[serde(default, deny_unknown_fields)]
112pub struct Rule {
113    /// Optional stable id ("builtin:claude-code"); defaults to the label slug.
114    pub id: Option<String>,
115    pub kind: GroupKind,
116    pub label: String,
117    #[serde(rename = "match")]
118    pub matcher: MatchSpec,
119    pub exclude: Option<MatchSpec>,
120    /// "env:KEY" → one group per distinct (hashed) marker value.
121    pub session_key: Option<String>,
122    pub priority: i32,
123    /// Matching processes are protected (never offered for actions).
124    pub protected: bool,
125}
126
127impl Default for Rule {
128    fn default() -> Self {
129        Rule {
130            id: None,
131            kind: GroupKind::Other,
132            label: String::new(),
133            matcher: MatchSpec::default(),
134            exclude: None,
135            session_key: None,
136            priority: 0,
137            protected: false,
138        }
139    }
140}
141
142impl Rule {
143    pub fn rule_id(&self) -> String {
144        self.id.clone().unwrap_or_else(|| slug(&self.label))
145    }
146
147    /// The marker key named by `session_key = "env:KEY"`.
148    pub fn session_env_key(&self) -> Option<&str> {
149        self.session_key
150            .as_deref()
151            .and_then(|k| k.strip_prefix("env:"))
152            .map(str::trim)
153            .filter(|k| !k.is_empty())
154    }
155}
156
157/// An ordered rule set (built-in rules first, then user rules; user rules usually carry higher priority).
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
159#[serde(default, deny_unknown_fields)]
160pub struct RuleSet {
161    #[serde(rename = "group")]
162    pub rules: Vec<Rule>,
163}
164
165#[derive(Debug, Error, Clone, PartialEq, Eq)]
166pub enum RuleError {
167    #[error("rule {rule:?}: bad glob {pattern:?}: {msg}")]
168    Glob {
169        rule: String,
170        pattern: String,
171        msg: String,
172    },
173    #[error("rule {rule:?}: bad regex {pattern:?}: {msg}")]
174    Regex {
175        rule: String,
176        pattern: String,
177        msg: String,
178    },
179    #[error("rule {rule:?}: empty label")]
180    EmptyLabel { rule: String },
181    #[error("rule {rule:?}: session_key {key:?} must look like \"env:KEY\"")]
182    SessionKey { rule: String, key: String },
183}
184
185#[derive(Debug, Clone)]
186struct CompiledSpec {
187    exe: GlobSet,
188    name: GlobSet,
189    script: GlobSet,
190    cmdline: Vec<Regex>,
191    cwd: GlobSet,
192    bundle: GlobSet,
193    cgroup: GlobSet,
194    env: Vec<String>,
195    has_identity: bool,
196}
197
198#[derive(Debug, Clone)]
199struct CompiledRule {
200    rule: Rule,
201    id: String,
202    spec: CompiledSpec,
203    exclude: Option<CompiledSpec>,
204}
205
206/// All rules' globs for one field in a single [`GlobSet`] (glob index → rule index), so a process is
207/// matched once per field instead of once per rule.
208#[derive(Debug, Clone, Default)]
209struct GlobIndex {
210    set: GlobSet,
211    owner: Vec<usize>,
212}
213
214impl GlobIndex {
215    fn build(set: &RuleSet, pick: impl Fn(&MatchSpec) -> &Vec<String>) -> Result<Self, RuleError> {
216        let mut b = GlobSetBuilder::new();
217        let mut owner = Vec::new();
218        for (i, r) in set.rules.iter().enumerate() {
219            for pat in pick(&r.matcher) {
220                let g = GlobBuilder::new(pat)
221                    .case_insensitive(false)
222                    .literal_separator(false)
223                    .build()
224                    .map_err(|e| RuleError::Glob {
225                        rule: r.rule_id(),
226                        pattern: pat.clone(),
227                        msg: e.to_string(),
228                    })?;
229                b.add(g);
230                owner.push(i);
231            }
232        }
233        let set = b.build().map_err(|e| RuleError::Glob {
234            rule: "(all rules)".into(),
235            pattern: String::new(),
236            msg: e.to_string(),
237        })?;
238        Ok(GlobIndex { set, owner })
239    }
240
241    fn is_empty(&self) -> bool {
242        self.owner.is_empty()
243    }
244
245    fn hits(&self, value: &str, buf: &mut Vec<usize>, cand: &mut [bool]) {
246        if self.is_empty() || value.is_empty() {
247            return;
248        }
249        self.set.matches_into(value, buf);
250        for &g in buf.iter() {
251            cand[self.owner[g]] = true;
252        }
253    }
254}
255
256#[derive(Debug, Clone)]
257struct RegexIndex {
258    set: regex::RegexSet,
259    owner: Vec<usize>,
260}
261
262impl Default for RegexIndex {
263    fn default() -> Self {
264        RegexIndex {
265            set: regex::RegexSet::empty(),
266            owner: Vec::new(),
267        }
268    }
269}
270
271/// Most memo entries kept before the memo is reset (a long session sees many short-lived processes).
272const MEMO_CAP: usize = 16_384;
273
274/// Signature of the identity fields that rule matching and fingerprinting read (exe, name, argv, cwd,
275/// bundle id, cgroup). Equal signatures give equal results, so results are memoized by it.
276fn identity_sig(p: &Process) -> u64 {
277    use std::hash::{Hash, Hasher};
278    let mut h = std::collections::hash_map::DefaultHasher::new();
279    p.exe.hash(&mut h);
280    p.name.hash(&mut h);
281    p.cmdline.hash(&mut h);
282    p.cwd.hash(&mut h);
283    p.bundle_id.hash(&mut h);
284    p.cgroup.hash(&mut h);
285    h.finish()
286}
287
288/// Memo of pure per-process results — the root rule match and the group fingerprint — keyed by
289/// [`identity_sig`]. A process's identity rarely changes between samples, so re-matching ~700 processes
290/// against every glob and regex each refresh is wasted work (SPEC §14 CPU budget). Interior mutability
291/// keeps `match_root(&self)` unchanged; a poisoned lock just disables the memo.
292#[derive(Debug, Default)]
293struct Memo {
294    roots: HashMap<u64, Option<usize>>,
295    fingerprints: HashMap<(u64, GroupKind), String>,
296    /// [`heuristic_kind_label`] also reads the uid and pid.
297    heuristics: HashMap<(u64, Option<u32>, u32), (GroupKind, String)>,
298}
299
300#[derive(Debug, Default)]
301struct MemoCell(std::sync::Mutex<Memo>);
302
303impl Clone for MemoCell {
304    fn clone(&self) -> Self {
305        MemoCell::default()
306    }
307}
308
309/// Rules compiled for matching.
310#[derive(Debug, Clone, Default)]
311pub struct CompiledRules {
312    memo: MemoCell,
313    rules: Vec<CompiledRule>,
314    exe: GlobIndex,
315    name: GlobIndex,
316    script: GlobIndex,
317    cwd: GlobIndex,
318    bundle: GlobIndex,
319    cgroup: GlobIndex,
320    cmdline: RegexIndex,
321}
322
323fn glob_set(rule: &str, pats: &[String]) -> Result<GlobSet, RuleError> {
324    let mut b = GlobSetBuilder::new();
325    for p in pats {
326        let g: Glob = GlobBuilder::new(p)
327            .case_insensitive(false)
328            .literal_separator(false)
329            .build()
330            .map_err(|e| RuleError::Glob {
331                rule: rule.to_string(),
332                pattern: p.clone(),
333                msg: e.to_string(),
334            })?;
335        b.add(g);
336    }
337    b.build().map_err(|e| RuleError::Glob {
338        rule: rule.to_string(),
339        pattern: String::new(),
340        msg: e.to_string(),
341    })
342}
343
344fn compile_spec(rule: &str, s: &MatchSpec) -> Result<CompiledSpec, RuleError> {
345    let cmdline = s
346        .cmdline
347        .iter()
348        .map(|p| {
349            Regex::new(p).map_err(|e| RuleError::Regex {
350                rule: rule.to_string(),
351                pattern: p.clone(),
352                msg: e.to_string(),
353            })
354        })
355        .collect::<Result<Vec<_>, _>>()?;
356    Ok(CompiledSpec {
357        exe: glob_set(rule, &s.exe)?,
358        name: glob_set(rule, &s.name)?,
359        script: glob_set(rule, &s.script)?,
360        cmdline,
361        cwd: glob_set(rule, &s.cwd)?,
362        bundle: glob_set(rule, &s.bundle)?,
363        cgroup: glob_set(rule, &s.cgroup)?,
364        env: s.env.clone(),
365        has_identity: s.has_identity(),
366    })
367}
368
369fn basename(path: &str) -> &str {
370    let p = path.trim_end_matches('/');
371    p.rsplit('/').next().unwrap_or(p)
372}
373
374/// Per-process strings computed once for matching against every rule.
375struct ProcView<'a> {
376    p: &'a Process,
377    exe_base: &'a str,
378    argv0: Option<&'a str>,
379    joined: String,
380}
381
382impl<'a> ProcView<'a> {
383    fn new(p: &'a Process) -> Self {
384        ProcView {
385            p,
386            exe_base: basename(&p.exe),
387            argv0: p.cmdline.first().map(String::as_str).filter(|a| !a.is_empty()),
388            joined: p.cmdline.join(" "),
389        }
390    }
391}
392
393impl CompiledSpec {
394    fn identity_match(&self, v: &ProcView<'_>) -> bool {
395        if !self.has_identity {
396            return false;
397        }
398        let p = v.p;
399        if !self.exe.is_empty() {
400            if !p.exe.is_empty() && (self.exe.is_match(&p.exe) || self.exe.is_match(v.exe_base)) {
401                return true;
402            }
403            if let Some(a0) = v.argv0 {
404                if self.exe.is_match(a0) || self.exe.is_match(basename(a0)) {
405                    return true;
406                }
407            }
408        }
409        if !p.name.is_empty() && self.name.is_match(&p.name) {
410            return true;
411        }
412        if !self.script.is_empty() && p.cmdline.iter().skip(1).any(|a| self.script.is_match(a)) {
413            return true;
414        }
415        if !self.cmdline.is_empty() && self.cmdline.iter().any(|r| r.is_match(&v.joined)) {
416            return true;
417        }
418        if let Some(cwd) = &p.cwd {
419            if self.cwd.is_match(cwd) {
420                return true;
421            }
422        }
423        if let Some(b) = &p.bundle_id {
424            if self.bundle.is_match(b) {
425                return true;
426            }
427        }
428        if let Some(cg) = &p.cgroup {
429            if self.cgroup.is_match(cg) {
430                return true;
431            }
432        }
433        false
434    }
435
436    fn env_match(&self, p: &Process) -> bool {
437        !self.env.is_empty() && self.env.iter().any(|k| p.markers.keys.iter().any(|m| m == k))
438    }
439}
440
441/// A rule match for one process.
442#[derive(Debug, Clone, PartialEq)]
443pub struct RuleMatch<'a> {
444    pub index: usize,
445    pub rule: &'a Rule,
446}
447
448impl CompiledRules {
449    pub fn compile(set: &RuleSet) -> Result<CompiledRules, RuleError> {
450        let mut rules = Vec::with_capacity(set.rules.len());
451        for r in &set.rules {
452            let id = r.rule_id();
453            if r.label.trim().is_empty() {
454                return Err(RuleError::EmptyLabel { rule: id });
455            }
456            if let Some(k) = &r.session_key {
457                if r.session_env_key().is_none() {
458                    return Err(RuleError::SessionKey {
459                        rule: id,
460                        key: k.clone(),
461                    });
462                }
463            }
464            let spec = compile_spec(&id, &r.matcher)?;
465            let exclude = r.exclude.as_ref().map(|e| compile_spec(&id, e)).transpose()?;
466            rules.push(CompiledRule {
467                rule: r.clone(),
468                id,
469                spec,
470                exclude,
471            });
472        }
473        let mut pats = Vec::new();
474        let mut owner = Vec::new();
475        for (i, r) in set.rules.iter().enumerate() {
476            for p in &r.matcher.cmdline {
477                pats.push(p.clone());
478                owner.push(i);
479            }
480        }
481        let cmdline = RegexIndex {
482            set: regex::RegexSet::new(&pats).map_err(|e| RuleError::Regex {
483                rule: "(all rules)".into(),
484                pattern: String::new(),
485                msg: e.to_string(),
486            })?,
487            owner,
488        };
489        Ok(CompiledRules {
490            memo: MemoCell::default(),
491            rules,
492            exe: GlobIndex::build(set, |m| &m.exe)?,
493            name: GlobIndex::build(set, |m| &m.name)?,
494            script: GlobIndex::build(set, |m| &m.script)?,
495            cwd: GlobIndex::build(set, |m| &m.cwd)?,
496            bundle: GlobIndex::build(set, |m| &m.bundle)?,
497            cgroup: GlobIndex::build(set, |m| &m.cgroup)?,
498            cmdline,
499        })
500    }
501
502    /// Rules whose identity fields match (same semantics as matching each rule's spec in turn).
503    fn identity_candidates(&self, v: &ProcView<'_>) -> Vec<bool> {
504        let mut cand = vec![false; self.rules.len()];
505        let mut buf = Vec::new();
506        let p = v.p;
507        if !p.exe.is_empty() {
508            self.exe.hits(&p.exe, &mut buf, &mut cand);
509            self.exe.hits(v.exe_base, &mut buf, &mut cand);
510        }
511        if let Some(a0) = v.argv0 {
512            self.exe.hits(a0, &mut buf, &mut cand);
513            self.exe.hits(basename(a0), &mut buf, &mut cand);
514        }
515        self.name.hits(&p.name, &mut buf, &mut cand);
516        if !self.script.is_empty() {
517            for a in p.cmdline.iter().skip(1) {
518                self.script.hits(a, &mut buf, &mut cand);
519            }
520        }
521        if !self.cmdline.owner.is_empty() {
522            for i in self.cmdline.set.matches(&v.joined).iter() {
523                cand[self.cmdline.owner[i]] = true;
524            }
525        }
526        if let Some(c) = &p.cwd {
527            self.cwd.hits(c, &mut buf, &mut cand);
528        }
529        if let Some(b) = &p.bundle_id {
530            self.bundle.hits(b, &mut buf, &mut cand);
531        }
532        if let Some(c) = &p.cgroup {
533            self.cgroup.hits(c, &mut buf, &mut cand);
534        }
535        cand
536    }
537
538    pub fn len(&self) -> usize {
539        self.rules.len()
540    }
541
542    pub fn is_empty(&self) -> bool {
543        self.rules.is_empty()
544    }
545
546    /// The rule at `index` (as returned in [`RuleMatch::index`]).
547    pub fn rule(&self, index: usize) -> Option<&Rule> {
548        self.rules.get(index).map(|r| &r.rule)
549    }
550
551    fn best<'a>(
552        &'a self,
553        v: &ProcView<'_>,
554        f: impl Fn(&CompiledSpec, &ProcView<'_>) -> bool,
555        precomputed: Option<&[bool]>,
556    ) -> Option<RuleMatch<'a>> {
557        let mut best: Option<RuleMatch<'a>> = None;
558        for (i, r) in self.rules.iter().enumerate() {
559            let hit = match precomputed {
560                Some(c) => c[i] && r.spec.has_identity,
561                None => f(&r.spec, v),
562            };
563            if !hit {
564                continue;
565            }
566            if r.exclude.as_ref().map(|e| e.identity_match(v)).unwrap_or(false) {
567                continue;
568            }
569            if best
570                .as_ref()
571                .map(|b| r.rule.priority > b.rule.priority)
572                .unwrap_or(true)
573            {
574                best = Some(RuleMatch {
575                    index: i,
576                    rule: &r.rule,
577                });
578            }
579        }
580        best
581    }
582
583    /// Best identity match (process becomes a group root). Memoized by the process's identity fields.
584    pub fn match_root(&self, p: &Process) -> Option<RuleMatch<'_>> {
585        let sig = identity_sig(p);
586        if let Ok(m) = self.memo.0.lock() {
587            if let Some(hit) = m.roots.get(&sig) {
588                return hit.map(|index| RuleMatch {
589                    index,
590                    rule: &self.rules[index].rule,
591                });
592            }
593        }
594        let found = self.match_root_uncached(p);
595        if let Ok(mut m) = self.memo.0.lock() {
596            if m.roots.len() >= MEMO_CAP {
597                m.roots.clear();
598            }
599            m.roots.insert(sig, found.as_ref().map(|r| r.index));
600        }
601        found
602    }
603
604    fn match_root_uncached(&self, p: &Process) -> Option<RuleMatch<'_>> {
605        let v = ProcView::new(p);
606        let cand = self.identity_candidates(&v);
607        self.best(&v, |_, _| false, Some(&cand))
608    }
609
610    /// [`heuristic_kind_label`], memoized by the process's identity fields, uid and pid.
611    fn heuristic_kind_label(&self, p: &Process) -> (GroupKind, String) {
612        let key = (identity_sig(p), p.uid, p.id.pid);
613        if let Ok(m) = self.memo.0.lock() {
614            if let Some(v) = m.heuristics.get(&key) {
615                return v.clone();
616            }
617        }
618        let v = heuristic_kind_label(p);
619        if let Ok(mut m) = self.memo.0.lock() {
620            if m.heuristics.len() >= MEMO_CAP {
621                m.heuristics.clear();
622            }
623            m.heuristics.insert(key, v.clone());
624        }
625        v
626    }
627
628    /// [`fingerprint::group_fingerprint`], memoized by kind + the root's identity fields.
629    fn group_fingerprint(&self, kind: GroupKind, root: &Process) -> String {
630        let key = (identity_sig(root), kind);
631        if let Ok(m) = self.memo.0.lock() {
632            if let Some(fp) = m.fingerprints.get(&key) {
633                return fp.clone();
634            }
635        }
636        let fp = fingerprint::group_fingerprint(kind, root);
637        if let Ok(mut m) = self.memo.0.lock() {
638            if m.fingerprints.len() >= MEMO_CAP {
639                m.fingerprints.clear();
640            }
641            m.fingerprints.insert(key, fp.clone());
642        }
643        fp
644    }
645
646    /// Reference implementation of [`Self::match_root`] (one rule at a time), kept for equivalence tests.
647    #[cfg(test)]
648    fn match_root_naive(&self, p: &Process) -> Option<RuleMatch<'_>> {
649        self.best(&ProcView::new(p), |s, v| s.identity_match(v), None)
650    }
651
652    /// Best marker (env) match (process joins a session of the rule).
653    pub fn match_marker(&self, p: &Process) -> Option<RuleMatch<'_>> {
654        if p.markers.keys.is_empty() {
655            return None;
656        }
657        self.best(&ProcView::new(p), |s, v| s.env_match(v.p), None)
658    }
659
660    /// Every marker (env) match, best first (priority desc, then rule order).
661    fn match_markers(&self, p: &Process) -> Vec<usize> {
662        if p.markers.keys.is_empty() {
663            return Vec::new();
664        }
665        let v = ProcView::new(p);
666        let mut hits: Vec<usize> = self
667            .rules
668            .iter()
669            .enumerate()
670            .filter(|(_, r)| {
671                r.spec.env_match(p) && !r.exclude.as_ref().map(|e| e.identity_match(&v)).unwrap_or(false)
672            })
673            .map(|(i, _)| i)
674            .collect();
675        hits.sort_by_key(|&i| (std::cmp::Reverse(self.rules[i].rule.priority), i));
676        hits
677    }
678
679    fn is_protected_rule(&self, id: &str) -> bool {
680        self.rules.iter().any(|r| r.id == id && r.rule.protected)
681    }
682}
683
684// ---------------------------------------------------------------------------------------------------------
685// Lineage, context
686// ---------------------------------------------------------------------------------------------------------
687
688/// Lineage journal entry (SPEC §6.2), stored by `oomtop-state`.
689#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
690#[serde(default)]
691pub struct LineageEntry {
692    pub id: ProcId,
693    pub ppid: Option<u32>,
694    pub group_id: String,
695    pub group_kind: GroupKind,
696    pub group_label: String,
697    pub group_fingerprint: String,
698    /// Hashed session id.
699    pub session_id: Option<String>,
700    /// true if spawned (directly or transitively) by an agent session or tool.
701    pub spawned_by_agent: bool,
702    pub first_seen_ms: u64,
703    pub last_seen_ms: u64,
704    pub last_active_ms: u64,
705}
706
707/// Inputs besides the snapshot.
708#[derive(Debug, Clone, Copy)]
709pub struct AttributionContext<'a> {
710    pub rules: &'a CompiledRules,
711    pub lineage: &'a BTreeMap<ProcId, LineageEntry>,
712    pub protect: &'a ProtectContext,
713}
714
715/// Lower-case, dash-separated slug.
716pub fn slug(s: &str) -> String {
717    let mut out = String::new();
718    let mut dash = false;
719    for c in s.chars() {
720        if c.is_ascii_alphanumeric() {
721            out.push(c.to_ascii_lowercase());
722            dash = false;
723        } else if !dash && !out.is_empty() {
724            out.push('-');
725            dash = true;
726        }
727    }
728    while out.ends_with('-') {
729        out.pop();
730    }
731    out
732}
733
734// ---------------------------------------------------------------------------------------------------------
735// Process classification (terminals, shells, subreapers, app bundles)
736// ---------------------------------------------------------------------------------------------------------
737
738const SHELLS: &[&str] = &[
739    "sh", "bash", "zsh", "fish", "dash", "ksh", "mksh", "oksh", "loksh", "tcsh", "csh", "ash", "yash", "nu",
740    "elvish", "xonsh", "pwsh",
741];
742
743/// Terminal emulators, multiplexers and remote-login daemons (process / executable names).
744const TERMINALS: &[&str] = &[
745    "Terminal",
746    "iTerm2",
747    "iTerm",
748    "ghostty",
749    "Ghostty",
750    "kitty",
751    "alacritty",
752    "Alacritty",
753    "wezterm",
754    "wezterm-gui",
755    "wezterm-mux-server",
756    "WezTerm",
757    "Hyper",
758    "Tabby",
759    "rio",
760    "gnome-terminal-server",
761    "gnome-terminal-",
762    "gnome-terminal",
763    "kgx",
764    "ptyxis",
765    "ptyxis-agent",
766    "konsole",
767    "xterm",
768    "uxterm",
769    "urxvt",
770    "rxvt",
771    "foot",
772    "footclient",
773    "tilix",
774    "terminator",
775    "xfce4-terminal",
776    "lxterminal",
777    "mate-terminal",
778    "qterminal",
779    "st",
780    "contour",
781    "tmux",
782    "tmux: server",
783    "screen",
784    "SCREEN",
785    "zellij",
786    "dtach",
787    "abduco",
788    "sshd",
789    "sshd-session",
790    "login",
791    "mosh-server",
792];
793
794/// macOS terminal app bundle names (the part before `.app/`).
795const TERMINAL_APPS: &[&str] = &[
796    "Terminal",
797    "iTerm",
798    "iTerm2",
799    "Ghostty",
800    "kitty",
801    "Alacritty",
802    "WezTerm",
803    "Warp",
804    "Hyper",
805    "Tabby",
806    "Rio",
807];
808
809/// Launchers that exec a command and stay around as its parent.
810const TRANSPARENT: &[&str] = &[
811    "sudo",
812    "doas",
813    "su",
814    "caffeinate",
815    "script",
816    "nohup",
817    "timeout",
818    "nice",
819    "ionice",
820    "taskpolicy",
821];
822
823/// Process reapers: their children are top-level processes, never their members.
824const SUBREAPERS: &[&str] = &["launchd", "systemd", "init"];
825
826fn names_of(p: &Process) -> [&str; 3] {
827    [
828        p.name.trim_start_matches('-'),
829        basename(&p.exe),
830        p.cmdline
831            .first()
832            .map(|a| basename(a).trim_start_matches('-'))
833            .unwrap_or(""),
834    ]
835}
836
837fn name_in(p: &Process, list: &[&str]) -> bool {
838    names_of(p).iter().any(|n| !n.is_empty() && list.contains(n))
839}
840
841/// Bundle markers in an executable path. Chrome's updater runs the app from a temporary
842/// `…/code_sign_clone/…/Google Chrome.app.bundle/Contents/MacOS/Google Chrome` copy.
843const BUNDLE_MARKERS: [&str; 2] = [".app/", ".app.bundle/"];
844
845fn bundle_in(path: &str) -> Option<&str> {
846    let i = BUNDLE_MARKERS.iter().filter_map(|m| path.find(m)).min()?;
847    let name = basename(&path[..i]);
848    (!name.is_empty()).then_some(name)
849}
850
851/// The outermost `.app` bundle name of the executable (`Google Chrome` for a Chrome helper). Falls back
852/// to `argv[0]` when the executable runs from a non-bundle copy.
853pub fn app_bundle_name(p: &Process) -> Option<&str> {
854    bundle_in(&p.exe).or_else(|| p.cmdline.first().and_then(|a| bundle_in(a)))
855}
856
857/// True for the main executable of an app bundle (`X.app/Contents/MacOS/X`), not a nested helper.
858fn is_app_main(p: &Process) -> bool {
859    let n: usize = BUNDLE_MARKERS.iter().map(|m| p.exe.matches(m).count()).sum();
860    n == 1
861        && BUNDLE_MARKERS
862            .iter()
863            .any(|m| p.exe.contains(&format!("{m}Contents/MacOS/")))
864}
865
866/// Terminal emulators, multiplexers, sshd / login.
867pub fn is_terminal(p: &Process) -> bool {
868    name_in(p, TERMINALS)
869        || (is_app_main(p)
870            && app_bundle_name(p)
871                .map(|a| TERMINAL_APPS.contains(&a))
872                .unwrap_or(false))
873}
874
875/// Any shell process (interactive or not).
876pub fn is_shell(p: &Process) -> bool {
877    name_in(p, SHELLS)
878}
879
880/// A shell waiting for user commands: no `-c`, no script argument (only flags such as `-l`, `-i`).
881pub fn is_interactive_shell(p: &Process) -> bool {
882    if !is_shell(p) {
883        return false;
884    }
885    p.cmdline.iter().skip(1).all(|a| {
886        if a == "-c" || a == "-s" || !a.starts_with('-') {
887            return false;
888        }
889        // short flag clusters such as `-lc`
890        !(a.len() > 1 && !a.starts_with("--") && a[1..].contains('c'))
891    })
892}
893
894fn is_subreaper(p: &Process) -> bool {
895    p.id.pid <= 1 || name_in(p, SUBREAPERS)
896}
897
898/// A process whose children start their own groups (unless it sits in a rule-defined group).
899pub fn is_boundary(p: &Process) -> bool {
900    is_terminal(p) || is_interactive_shell(p) || name_in(p, TRANSPARENT)
901}
902
903/// Virtualization.framework guest processes: host footprint under-counts them (SPEC §5).
904pub fn is_vm_lower_bound(p: &Process) -> bool {
905    p.name.contains("com.apple.Virtualization.VirtualMachine")
906        || p.exe.contains("com.apple.Virtualization.VirtualMachine")
907}
908
909/// Heuristic kind + label for a top-level process with no rule.
910pub fn heuristic_kind_label(p: &Process) -> (GroupKind, String) {
911    if let Some(app) = app_bundle_name(p) {
912        return (GroupKind::App, app.to_string());
913    }
914    let exe = p.exe.as_str();
915    let system_prefixes = [
916        "/System/",
917        "/usr/libexec/",
918        "/usr/sbin/",
919        "/sbin/",
920        "/usr/lib/systemd/",
921        "/lib/systemd/",
922    ];
923    let short = if p.name.is_empty() {
924        basename(exe).to_string()
925    } else {
926        p.name.clone()
927    };
928    // Terminals are user apps even when installed under /usr/libexec (gnome-terminal-server): commands
929    // typed into them need a non-system owner.
930    let system_path = system_prefixes.iter().any(|pre| exe.starts_with(pre)) && !is_terminal(p);
931    if system_path || p.uid == Some(0) || p.id.pid <= 1 {
932        return (GroupKind::System, short);
933    }
934    // Interpreted programs are named after what they run ("studio.py", "@scope/pkg", "GradleDaemon").
935    let head = fingerprint::template_head(p);
936    let label = if head.is_empty() || head.starts_with('<') || head.contains(" -c") {
937        short
938    } else {
939        head
940    };
941    (
942        GroupKind::Other,
943        if label.is_empty() {
944            format!("pid {}", p.id.pid)
945        } else {
946            label
947        },
948    )
949}
950
951// ---------------------------------------------------------------------------------------------------------
952// cgroups (Linux)
953// ---------------------------------------------------------------------------------------------------------
954
955/// What a Linux cgroup v2 path says about a process's owner.
956#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
957#[serde(rename_all = "snake_case", tag = "type")]
958pub enum CgroupScope {
959    /// Container runtime scope (docker, podman, containerd, cri-o, kubepods, lxc, nspawn). `id` ≤ 12 chars.
960    Container { runtime: String, id: String },
961    /// libvirt / QEMU machine scope.
962    Vm { name: String },
963    /// A systemd service unit; `system` = under `system.slice`.
964    Service { unit: String, system: bool },
965    /// A desktop app scope (`app-gnome-firefox-1234.scope`, `snap.firefox.firefox-….scope`).
966    App { app: String },
967}
968
969fn unescape_systemd(s: &str) -> String {
970    s.replace("\\x2d", "-").replace("\\x20", " ")
971}
972
973fn is_hex_id(s: &str) -> bool {
974    s.len() >= 12 && s.bytes().all(|b| b.is_ascii_hexdigit())
975}
976
977fn short_id(s: &str) -> String {
978    s.chars().take(12).collect()
979}
980
981fn strip_instance_suffix(s: &str) -> &str {
982    // trailing "-<pid>" / "-<uuid>" / "-<hex>"
983    let mut cur = s;
984    loop {
985        let Some((head, tail)) = cur.rsplit_once('-') else {
986            return cur;
987        };
988        let instance = !tail.is_empty()
989            && tail.bytes().all(|b| b.is_ascii_hexdigit())
990            && (tail.bytes().any(|b| b.is_ascii_digit()));
991        if instance && !head.is_empty() {
992            cur = head;
993        } else {
994            return cur;
995        }
996    }
997}
998
999/// Parses a cgroup v2 path (as read from `/proc/<pid>/cgroup`, `0::` prefix optional).
1000pub fn parse_cgroup(path: &str) -> Option<CgroupScope> {
1001    let path = path.trim().trim_start_matches("0::");
1002    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
1003    // Containers and VMs anywhere in the path.
1004    for (i, seg) in segs.iter().enumerate() {
1005        let seg = *seg;
1006        let scope = seg.strip_suffix(".scope");
1007        if let Some(s) = scope {
1008            for (prefix, runtime) in [
1009                ("docker-", "docker"),
1010                ("libpod-conmon-", "podman"),
1011                ("libpod-", "podman"),
1012                ("cri-containerd-", "containerd"),
1013                ("crio-conmon-", "cri-o"),
1014                ("crio-", "cri-o"),
1015                ("containerd-", "containerd"),
1016            ] {
1017                if let Some(id) = s.strip_prefix(prefix) {
1018                    if is_hex_id(id) {
1019                        return Some(CgroupScope::Container {
1020                            runtime: runtime.into(),
1021                            id: short_id(id),
1022                        });
1023                    }
1024                }
1025            }
1026            if let Some(m) = s.strip_prefix("machine-") {
1027                let m = unescape_systemd(m);
1028                if let Some(rest) = m.strip_prefix("qemu-") {
1029                    // "qemu-<n>-<name>"
1030                    let name = rest.split_once('-').map(|(_, n)| n).unwrap_or(rest);
1031                    return Some(CgroupScope::Vm {
1032                        name: name.to_string(),
1033                    });
1034                }
1035                return Some(CgroupScope::Container {
1036                    runtime: "nspawn".into(),
1037                    id: m,
1038                });
1039            }
1040        }
1041        if let Some(name) = seg.strip_prefix("lxc.payload.") {
1042            return Some(CgroupScope::Container {
1043                runtime: "lxc".into(),
1044                id: name.to_string(),
1045            });
1046        }
1047        if (seg == "docker" || seg.starts_with("kubepods") || seg.starts_with("pod")) && i + 1 < segs.len() {
1048            let next = segs[i + 1];
1049            if is_hex_id(next) {
1050                let runtime = if seg == "docker" { "docker" } else { "kubernetes" };
1051                return Some(CgroupScope::Container {
1052                    runtime: runtime.into(),
1053                    id: short_id(next),
1054                });
1055            }
1056        }
1057    }
1058    let last = *segs.last()?;
1059    if last.ends_with("-spawn")
1060        || last.starts_with("vte-spawn-")
1061        || last.starts_with("tmux-spawn-")
1062        || last.starts_with("session-")
1063        || last == "init.scope"
1064    {
1065        return None;
1066    }
1067    if let Some(unit) = last.strip_suffix(".service") {
1068        if unit.starts_with("user@") || unit.is_empty() {
1069            return None;
1070        }
1071        let system = segs.first() == Some(&"system.slice");
1072        let unit = unescape_systemd(unit);
1073        let unit = unit.split('@').next().unwrap_or(&unit).to_string();
1074        return Some(CgroupScope::Service { unit, system });
1075    }
1076    let scope = last.strip_suffix(".scope")?;
1077    let raw = if let Some(rest) = scope.strip_prefix("app-") {
1078        let rest = unescape_systemd(rest);
1079        let rest = strip_instance_suffix(&rest).to_string();
1080        let rest = [
1081            "gnome-",
1082            "kde-",
1083            "xfce-",
1084            "flatpak-",
1085            "glib-",
1086            "dbus-:1.",
1087            "systemd-",
1088            "niri-",
1089            "sway-",
1090            "hyprland-",
1091        ]
1092        .iter()
1093        .find_map(|pre| rest.strip_prefix(pre).map(str::to_string))
1094        .unwrap_or(rest);
1095        rest
1096    } else {
1097        let rest = scope.strip_prefix("snap.")?;
1098        rest.split('.').next().unwrap_or(rest).to_string()
1099    };
1100    // reverse-DNS app ids → last component ("org.mozilla.firefox" → "firefox")
1101    let app = if raw.contains('.') && !raw.ends_with('.') {
1102        raw.rsplit('.').next().unwrap_or(&raw).to_string()
1103    } else {
1104        raw
1105    };
1106    if app.is_empty()
1107        || TERMINALS.contains(&app.as_str())
1108        || TERMINAL_APPS.contains(&app.as_str())
1109        || app.eq_ignore_ascii_case("terminal")
1110    {
1111        return None;
1112    }
1113    Some(CgroupScope::App { app })
1114}
1115
1116/// Kubernetes QoS class, as encoded in the kubelet's cgroup layout (and `status.qosClass`).
1117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
1118#[serde(rename_all = "snake_case")]
1119pub enum QosClass {
1120    /// Pod cgroup directly under `kubepods` (requests = limits for every container).
1121    Guaranteed,
1122    #[default]
1123    Burstable,
1124    BestEffort,
1125}
1126
1127impl QosClass {
1128    pub fn as_str(self) -> &'static str {
1129        match self {
1130            QosClass::Guaranteed => "Guaranteed",
1131            QosClass::Burstable => "Burstable",
1132            QosClass::BestEffort => "BestEffort",
1133        }
1134    }
1135
1136    /// `status.qosClass` spelling ("Guaranteed", "Burstable", "BestEffort"), case-insensitive.
1137    pub fn parse(s: &str) -> Option<QosClass> {
1138        match s.to_ascii_lowercase().as_str() {
1139            "guaranteed" => Some(QosClass::Guaranteed),
1140            "burstable" => Some(QosClass::Burstable),
1141            "besteffort" => Some(QosClass::BestEffort),
1142            _ => None,
1143        }
1144    }
1145}
1146
1147/// What a kubelet-managed cgroup path says (SPEC §11 "Local Kubernetes"): QoS class, pod UID and the
1148/// **full** container id, from the path alone. [`parse_cgroup`] keeps only a 12-character id for grouping;
1149/// this keeps everything the cluster tree needs.
1150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
1151pub struct KubeCgroup {
1152    pub qos: QosClass,
1153    /// Pod UID with dashes (`systemd` driver paths spell them `_`).
1154    pub pod_uid: String,
1155    /// Full container id (64 hex for containerd / CRI-O / docker), `None` for the pod-level cgroup.
1156    pub container_id: Option<String>,
1157    /// `containerd` | `cri-o` | `docker` from the scope prefix; `None` for cgroupfs-driver paths (bare id).
1158    pub runtime: Option<String>,
1159    /// CRI-O's `crio-conmon-<id>.scope` (the monitor, not the container itself).
1160    pub conmon: bool,
1161    /// Path of the pod cgroup (`…/kubepods-burstable-pod<uid>.slice` or `…/pod<uid>`).
1162    pub pod_cgroup: String,
1163    /// Path of the container cgroup, when the path goes below the pod.
1164    pub container_cgroup: Option<String>,
1165    /// Everything before the `kubepods` segment: empty on a node that is this host; a container scope
1166    /// (`/system.slice/docker-<id>.scope/kubelet.slice`) for kind / k3d / minikube nodes seen from the host.
1167    pub node_prefix: String,
1168}
1169
1170fn is_uid_like(s: &str) -> bool {
1171    (32..=40).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-' || b == b'_')
1172}
1173
1174/// `pod<uid>` / `kubepods[-<qos>]-pod<uid>.slice` / `kubelet-kubepods-<qos>-pod<uid>.slice` → uid.
1175fn pod_uid_of(seg: &str) -> Option<String> {
1176    let s = seg.strip_suffix(".slice").unwrap_or(seg);
1177    let idx = s.rfind("pod")?;
1178    let head = &s[..idx];
1179    if !(head.is_empty() || head.ends_with('-')) {
1180        return None;
1181    }
1182    let uid = &s[idx + 3..];
1183    is_uid_like(uid).then(|| uid.replace('_', "-"))
1184}
1185
1186/// QoS from a `kubepods…` segment: `burstable` / `besteffort` anywhere in it.
1187fn qos_of(seg: &str) -> Option<QosClass> {
1188    let s = seg.to_ascii_lowercase();
1189    if s.contains("besteffort") {
1190        Some(QosClass::BestEffort)
1191    } else if s.contains("burstable") {
1192        Some(QosClass::Burstable)
1193    } else {
1194        None
1195    }
1196}
1197
1198/// Container scope below a pod: `cri-containerd-<id>.scope`, `crio-<id>.scope`, `crio-conmon-<id>.scope`,
1199/// `docker-<id>.scope`, or a bare 64-hex id (cgroupfs driver). → (id, runtime, conmon)
1200fn container_of(seg: &str) -> Option<(String, Option<String>, bool)> {
1201    if let Some(s) = seg.strip_suffix(".scope") {
1202        for (prefix, runtime, conmon) in [
1203            ("cri-containerd-", "containerd", false),
1204            ("crio-conmon-", "cri-o", true),
1205            ("crio-", "cri-o", false),
1206            ("docker-", "docker", false),
1207            ("containerd-", "containerd", false),
1208        ] {
1209            if let Some(id) = s.strip_prefix(prefix) {
1210                return is_hex_id(id).then(|| (id.to_string(), Some(runtime.to_string()), conmon));
1211            }
1212        }
1213        return None;
1214    }
1215    // cgroupfs driver: the bare id; CRI-O cgroupfs writes "crio-<id>" without ".scope".
1216    if let Some(id) = seg.strip_prefix("crio-conmon-") {
1217        return is_hex_id(id).then(|| (id.to_string(), Some("cri-o".into()), true));
1218    }
1219    if let Some(id) = seg.strip_prefix("crio-") {
1220        return is_hex_id(id).then(|| (id.to_string(), Some("cri-o".into()), false));
1221    }
1222    is_hex_id(seg).then(|| (seg.to_string(), None, false))
1223}
1224
1225/// Parses a kubelet-managed cgroup v2 path (cgroupfs and systemd drivers; containerd, CRI-O and
1226/// cri-dockerd scopes; nodes nested in a container such as kind / k3d / minikube). `None` when the path
1227/// is not below a `kubepods` cgroup with a pod segment.
1228pub fn parse_kube_cgroup(path: &str) -> Option<KubeCgroup> {
1229    let path = path.trim().trim_start_matches("0::");
1230    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
1231    // The first segment naming kubepods (`kubepods`, `kubepods.slice`, `kubelet-kubepods.slice`).
1232    let start = segs.iter().position(|s| {
1233        let s = s.strip_suffix(".slice").unwrap_or(s);
1234        s == "kubepods" || s.ends_with("-kubepods") || s.starts_with("kubepods")
1235    })?;
1236    let mut qos = QosClass::Guaranteed;
1237    let mut i = start;
1238    let mut pod: Option<(usize, String)> = None;
1239    while i < segs.len() {
1240        let seg = segs[i];
1241        if let Some(uid) = pod_uid_of(seg) {
1242            if let Some(q) = qos_of(seg) {
1243                qos = q;
1244            }
1245            pod = Some((i, uid));
1246            break;
1247        }
1248        if let Some(q) = qos_of(seg) {
1249            qos = q;
1250        } else if i > start && !seg.contains("kubepods") {
1251            return None;
1252        }
1253        i += 1;
1254    }
1255    let (pi, pod_uid) = pod?;
1256    let join = |n: usize| format!("/{}", segs[..n].join("/"));
1257    let node_prefix = if start == 0 { String::new() } else { join(start) };
1258    let mut out = KubeCgroup {
1259        qos,
1260        pod_uid,
1261        pod_cgroup: join(pi + 1),
1262        node_prefix,
1263        ..Default::default()
1264    };
1265    if let Some(seg) = segs.get(pi + 1) {
1266        let (id, runtime, conmon) = container_of(seg)?;
1267        out.container_id = Some(id);
1268        out.runtime = runtime;
1269        out.conmon = conmon;
1270        out.container_cgroup = Some(join(pi + 2));
1271    }
1272    Some(out)
1273}
1274
1275// ---------------------------------------------------------------------------------------------------------
1276// Builder
1277// ---------------------------------------------------------------------------------------------------------
1278
1279#[derive(Debug, Clone, Copy)]
1280struct Slot {
1281    group: usize,
1282    via: AttributionSignal,
1283    confidence: Confidence,
1284}
1285
1286#[derive(Debug, Clone, Default)]
1287struct Meta {
1288    /// Rule/adapter/cgroup/self groups keep shell-launched descendants.
1289    sticky: bool,
1290    /// Root is a terminal: never a responsible-pid owner.
1291    launcher_root: bool,
1292}
1293
1294#[derive(Debug, Clone)]
1295struct AdapterHint {
1296    key: String,
1297    kind: GroupKind,
1298    label: String,
1299    matched_by: String,
1300}
1301
1302fn model_server_label(k: ModelServerKind) -> &'static str {
1303    match k {
1304        ModelServerKind::Ollama => "Ollama",
1305        ModelServerKind::LlamaCpp => "llama.cpp server",
1306        ModelServerKind::SdCpp => "sd-server",
1307        ModelServerKind::Vllm => "vLLM",
1308        ModelServerKind::LmStudio => "LM Studio",
1309        ModelServerKind::Mlx => "MLX-LM server",
1310        ModelServerKind::Generic => "model server",
1311    }
1312}
1313
1314/// Alias of a session: `<alias>:<first 12 hex of the hashed session id>`. It names the session in marker
1315/// lookups, in `owner_group` of orphans whose session is gone, and in journals written before session
1316/// groups were keyed by root pid; a live session's group id is `agent:<rule-id>:<root pid>`. A session id that is not
1317/// hash-shaped (e.g. from an old journal or a hand-made fixture) is hashed first, so a raw id never becomes
1318/// part of an exported id and slicing never splits a multi-byte character.
1319fn session_group_key(kind: GroupKind, sid: &str) -> String {
1320    let hashed = sid.len() >= 12 && sid.bytes().all(|b| b.is_ascii_hexdigit());
1321    let h: String = if hashed {
1322        sid.chars().take(12).collect()
1323    } else {
1324        crate::redact::hash_marker(sid).chars().take(12).collect()
1325    };
1326    format!("{}:{h}", kind.alias())
1327}
1328
1329struct Builder<'a> {
1330    snap: &'a Snapshot,
1331    rules: &'a CompiledRules,
1332    lineage: &'a BTreeMap<ProcId, LineageEntry>,
1333    by_pid: HashMap<u32, usize>,
1334    by_id: HashMap<ProcId, usize>,
1335    groups: Vec<Group>,
1336    meta: Vec<Meta>,
1337    key_to_group: HashMap<String, usize>,
1338    assigned: Vec<Option<Slot>>,
1339    visiting: Vec<bool>,
1340    root_rule: Vec<Option<usize>>,
1341    /// Session id of each session-keyed rule root.
1342    root_sid: Vec<Option<String>>,
1343    adapter: Vec<Option<AdapterHint>>,
1344    /// Session aliases ([`session_group_key`]) → index of the live rule root of that session.
1345    live_sessions: HashMap<String, usize>,
1346    /// oomtop's own uid: label-keyed app groups of other (non-root) users get a `@u<uid>` suffix, so
1347    /// another logged-in user's Chrome never merges with ours (fast user switching).
1348    self_uid: Option<u32>,
1349}
1350
1351impl<'a> Builder<'a> {
1352    /// `""`, or `@u<uid>` for a process of another non-root user.
1353    fn user_suffix(&self, p: &Process) -> String {
1354        match (p.uid, self.self_uid) {
1355            (Some(u), Some(me)) if u != me && u != 0 => format!("@u{u}"),
1356            _ => String::new(),
1357        }
1358    }
1359
1360    fn proc(&self, i: usize) -> &'a Process {
1361        &self.snap.processes[i]
1362    }
1363
1364    fn proc_by_id(&self, id: ProcId) -> Option<&'a Process> {
1365        self.by_id.get(&id).map(|&i| &self.snap.processes[i])
1366    }
1367
1368    fn ensure_group(&mut self, key: &str, kind: GroupKind, label: &str, root: Option<ProcId>) -> usize {
1369        if let Some(&i) = self.key_to_group.get(key) {
1370            if self.groups[i].root.is_none() {
1371                self.groups[i].root = root;
1372            }
1373            return i;
1374        }
1375        let i = self.groups.len();
1376        self.groups.push(Group {
1377            id: key.to_string(),
1378            kind,
1379            label: label.to_string(),
1380            root,
1381            ..Default::default()
1382        });
1383        self.meta.push(Meta::default());
1384        self.key_to_group.insert(key.to_string(), i);
1385        i
1386    }
1387
1388    fn set_root_meta(&mut self, g: usize) {
1389        let root = self.groups[g].root.and_then(|r| self.proc_by_id(r));
1390        self.meta[g].launcher_root = root.map(is_terminal).unwrap_or(false);
1391    }
1392
1393    /// Index of the live parent (not a subreaper, not a reused pid).
1394    fn parent_index(&self, i: usize) -> Option<usize> {
1395        let p = self.proc(i);
1396        let pp = p.ppid.filter(|&pp| pp > 1 && pp != p.id.pid)?;
1397        let pi = *self.by_pid.get(&pp)?;
1398        let parent = self.proc(pi);
1399        if pi == i || is_subreaper(parent) {
1400            return None;
1401        }
1402        if parent.id.start_time > 0 && p.id.start_time > 0 && parent.id.start_time > p.id.start_time {
1403            return None; // pid reused after our real parent exited
1404        }
1405        Some(pi)
1406    }
1407
1408    fn resolve(&mut self, i: usize, depth: usize) -> Option<usize> {
1409        if let Some(s) = self.assigned[i] {
1410            return Some(s.group);
1411        }
1412        if self.visiting[i] || depth > MAX_DEPTH {
1413            return None;
1414        }
1415        self.visiting[i] = true;
1416        let slot = self.decide(i, depth);
1417        self.visiting[i] = false;
1418        self.assigned[i] = Some(slot);
1419        Some(slot.group)
1420    }
1421
1422    /// Session aliases the process's markers name, best rule first: `(alias, rule index)` for every
1423    /// marker-matching rule with a `session_key` whose own id the process carries.
1424    fn marker_sessions(&self, i: usize) -> Vec<(String, usize)> {
1425        let p = self.proc(i);
1426        if p.markers.session_id.is_none() {
1427            return Vec::new();
1428        }
1429        self.rules
1430            .match_markers(p)
1431            .into_iter()
1432            .filter_map(|ri| {
1433                let rule = &self.rules.rules[ri].rule;
1434                let sid = crate::redact::session_id_for_key(&p.markers, rule.session_env_key()?)?;
1435                Some((session_group_key(rule.kind, sid), ri))
1436            })
1437            .collect()
1438    }
1439
1440    /// The group of the live session with this alias, if its root is in the snapshot.
1441    fn session_group(&mut self, alias: &str, depth: usize) -> Option<usize> {
1442        let root = *self.live_sessions.get(alias)?;
1443        self.resolve(root, depth + 1)
1444    }
1445
1446    fn decide(&mut self, i: usize, depth: usize) -> Slot {
1447        let p = self.proc(i);
1448
1449        // 0. oomtop itself
1450        if Some(p.id.pid) == self.snap.self_pid {
1451            if let Some(pg) = self.parent_index(i).and_then(|pi| self.resolve(pi, depth + 1)) {
1452                if self.groups[pg].kind == GroupKind::AgentSession {
1453                    return Slot {
1454                        group: pg,
1455                        via: AttributionSignal::Ancestry,
1456                        confidence: Confidence::High,
1457                    };
1458                }
1459            }
1460            let g = self.ensure_group(SELF_GROUP_ID, GroupKind::Other, "oomtop", Some(p.id));
1461            self.groups[g].matched_by = Some("self".into());
1462            self.meta[g].sticky = true;
1463            return Slot {
1464                group: g,
1465                via: AttributionSignal::Rule,
1466                confidence: Confidence::High,
1467            };
1468        }
1469
1470        // 1. adapter truth (rule roots keep their rule key so ids stay stable with/without adapter data)
1471        if self.root_rule[i].is_none() {
1472            if let Some(h) = self.adapter[i].clone() {
1473                let g = self.ensure_group(&h.key, h.kind, &h.label, Some(p.id));
1474                self.groups[g].matched_by.get_or_insert(h.matched_by);
1475                self.meta[g].sticky = true;
1476                return Slot {
1477                    group: g,
1478                    via: AttributionSignal::Adapter,
1479                    confidence: Confidence::High,
1480                };
1481            }
1482        }
1483
1484        // 2. container / VM cgroup
1485        if let Some(scope) = p.cgroup.as_deref().and_then(parse_cgroup) {
1486            let hit = match scope {
1487                CgroupScope::Container { runtime, id } => Some((
1488                    format!("sandbox:{runtime}-{}", slug(&id)),
1489                    format!("{runtime} {id}"),
1490                    format!("cgroup:{runtime}"),
1491                )),
1492                CgroupScope::Vm { name } => Some((
1493                    format!("sandbox:vm-{}", slug(&name)),
1494                    format!("VM {name}"),
1495                    "cgroup:machine".to_string(),
1496                )),
1497                _ => None,
1498            };
1499            if let Some((key, label, by)) = hit {
1500                let g = self.ensure_group(&key, GroupKind::Sandbox, &label, Some(p.id));
1501                self.groups[g].matched_by.get_or_insert(by);
1502                self.meta[g].sticky = true;
1503                return Slot {
1504                    group: g,
1505                    via: AttributionSignal::Cgroup,
1506                    confidence: Confidence::High,
1507                };
1508            }
1509        }
1510
1511        // 3. rule root
1512        if let Some(r) = self.root_rule[i] {
1513            return self.rule_root(i, r, depth);
1514        }
1515
1516        // 4. live session marker — unless the parent belongs to a different rule/adapter-defined group (a
1517        //    Gradle worker under its daemon, a model server's workers): those inherit the agent's env but
1518        //    are owned, and freed, by their own root.
1519        //    A process inside a nested agent carries the outer agent's id too: the session its parent
1520        //    already belongs to wins,
1521        let markers = self.marker_sessions(i);
1522        let mut marker: Option<String> = markers.first().map(|(k, _)| k.clone());
1523        if marker.is_some() {
1524            let parent = self.parent_index(i).and_then(|pi| self.resolve(pi, depth + 1));
1525            // …otherwise the innermost one: a nested session's root is younger than the outer one's.
1526            let mut session = None;
1527            let mut best_age = None;
1528            for (k, _) in &markers {
1529                let Some(root) = self.live_sessions.get(k).copied() else {
1530                    continue;
1531                };
1532                let Some(g) = self.session_group(k, depth) else {
1533                    continue;
1534                };
1535                let rp = self.proc(root);
1536                let age = (Some(g) == parent, rp.id.start_time, rp.id.pid);
1537                if best_age.is_none_or(|b| age > b) {
1538                    best_age = Some(age);
1539                    session = Some(g);
1540                    marker = Some(k.clone());
1541                }
1542            }
1543            let parent_group = parent.filter(|&pg| {
1544                let g = &self.groups[pg];
1545                self.meta[pg].sticky
1546                    && Some(pg) != session
1547                    && g.id != SELF_GROUP_ID
1548                    && g.kind != GroupKind::AgentSession
1549                    && g.kind != GroupKind::System
1550            });
1551            if let Some(pg) = parent_group {
1552                return Slot {
1553                    group: pg,
1554                    via: AttributionSignal::Ancestry,
1555                    confidence: Confidence::High,
1556                };
1557            }
1558            if let Some(g) = session {
1559                return Slot {
1560                    group: g,
1561                    via: AttributionSignal::Marker,
1562                    confidence: Confidence::High,
1563                };
1564            }
1565        }
1566
1567        // 5. responsible pid (macOS)
1568        if let Some(g) = self.responsible_group(i, depth) {
1569            return Slot {
1570                group: g,
1571                via: AttributionSignal::Responsible,
1572                confidence: Confidence::High,
1573            };
1574        }
1575
1576        // 6. ancestry
1577        if let Some(pi) = self.parent_index(i) {
1578            if let Some(pg) = self.resolve(pi, depth + 1) {
1579                let parent = self.proc(pi);
1580                // A command typed into a shell/terminal is its own root; terminal plumbing (login, shells,
1581                // tmux, sudo) stays with the terminal.
1582                if is_boundary(parent) && !self.meta[pg].sticky && !is_boundary(p) {
1583                    let owner =
1584                        (self.groups[pg].kind != GroupKind::System).then(|| self.groups[pg].id.clone());
1585                    return self.heuristic_root(i, owner);
1586                }
1587                let parent_high = self.assigned[pi]
1588                    .map(|s| s.confidence == Confidence::High)
1589                    .unwrap_or(false);
1590                return Slot {
1591                    group: pg,
1592                    via: AttributionSignal::Ancestry,
1593                    confidence: if parent_high {
1594                        Confidence::High
1595                    } else {
1596                        Confidence::Medium
1597                    },
1598                };
1599            }
1600        }
1601
1602        // --- top-level from here on (parent exited, is a subreaper, or unknown) ---
1603
1604        // 7. lineage journal
1605        if let Some(le) = self.lineage.get(&p.id).filter(|le| !le.group_id.is_empty()) {
1606            if reparented(p, le, self.snap, &self.by_pid) {
1607                // Once an orphan is its own root the journal records *that* group; its owner is then the
1608                // recorded session (or the marker's), never itself.
1609                let recorded_self = le.group_id == orphan_identity(p).2;
1610                let target = if recorded_self {
1611                    le.session_id
1612                        .as_deref()
1613                        .map(|sid| session_group_key(GroupKind::AgentSession, sid))
1614                        .or_else(|| marker.clone())
1615                } else {
1616                    Some(le.group_id.clone())
1617                };
1618                let agent = le.spawned_by_agent || p.markers.session_id.is_some();
1619                if let Some(t) = target {
1620                    // A session alias (old journals, `recorded_self`) resolves to the live session's group.
1621                    // A recorded group is alive only if its root predates this process (group keys contain
1622                    // pids; a younger root is a reused pid, not the group that spawned it).
1623                    // The recorded root may not have been resolved yet (`<alias>:<rule>:<pid>` names it).
1624                    let recorded_root = t
1625                        .rsplit_once(':')
1626                        .and_then(|(_, pid)| pid.parse::<u32>().ok())
1627                        .and_then(|pid| self.by_pid.get(&pid).copied())
1628                        .filter(|&k| k != i && self.root_rule[k].is_some());
1629                    if let Some(k) = recorded_root {
1630                        self.resolve(k, depth + 1);
1631                    }
1632                    let live = self.session_group(&t, depth).or_else(|| {
1633                        self.key_to_group.get(&t).copied().filter(|&g| {
1634                            self.groups[g]
1635                                .root
1636                                .and_then(|r| self.proc_by_id(r))
1637                                .map(|r| r.id.start_time <= p.id.start_time)
1638                                .unwrap_or(false)
1639                        })
1640                    });
1641                    if let Some(g) = live {
1642                        return Slot {
1643                            group: g,
1644                            via: AttributionSignal::Lineage,
1645                            confidence: Confidence::Medium,
1646                        };
1647                    }
1648                    return self.orphan_root(i, Some(t), AttributionSignal::Lineage, agent);
1649                }
1650                if agent {
1651                    return self.orphan_root(i, None, AttributionSignal::Lineage, true);
1652                }
1653            }
1654        }
1655
1656        // 8. marker of a session whose root has exited
1657        if let Some(key) = marker {
1658            return self.orphan_root(i, Some(key), AttributionSignal::Marker, true);
1659        }
1660
1661        // 9. systemd unit / desktop app scope
1662        if let Some(scope) = p.cgroup.as_deref().and_then(parse_cgroup) {
1663            let hit = match scope {
1664                CgroupScope::Service { unit, system } => {
1665                    let kind = if system || p.uid == Some(0) {
1666                        GroupKind::System
1667                    } else {
1668                        GroupKind::Other
1669                    };
1670                    Some((format!("{}:{}", kind.alias(), slug(&unit)), kind, unit))
1671                }
1672                CgroupScope::App { app } => Some((format!("app:{}", slug(&app)), GroupKind::App, app)),
1673                _ => None,
1674            };
1675            if let Some((key, kind, label)) = hit {
1676                let g = self.ensure_group(&key, kind, &label, Some(p.id));
1677                self.groups[g]
1678                    .matched_by
1679                    .get_or_insert_with(|| "cgroup:unit".into());
1680                self.set_root_meta(g);
1681                return Slot {
1682                    group: g,
1683                    via: AttributionSignal::Cgroup,
1684                    confidence: Confidence::Medium,
1685                };
1686            }
1687        }
1688
1689        // 10. heuristic top-level root
1690        self.heuristic_root(i, None)
1691    }
1692
1693    fn rule_root(&mut self, i: usize, r: usize, depth: usize) -> Slot {
1694        let p = self.proc(i);
1695        let cr = &self.rules.rules[r];
1696        let (kind, label, rid) = (cr.rule.kind, cr.rule.label.clone(), cr.id.clone());
1697        // The key never depends on the session id: a session is `agent:<rule>:<pid>` whether or not a
1698        // marker-carrying descendant is running right now (its id is stable for the life of the root).
1699        let key = match kind {
1700            // apps and system components are one group per label (all Firefox processes are "Firefox")
1701            GroupKind::App => format!("app:{}{}", slug(&label), self.user_suffix(p)),
1702            GroupKind::System => format!("{}:{}", kind.alias(), slug(&label)),
1703            _ => format!("{}:{}:{}", kind.alias(), rid, p.id.pid),
1704        };
1705        let via = if self.adapter[i].is_some() {
1706            AttributionSignal::Adapter
1707        } else {
1708            AttributionSignal::Rule
1709        };
1710        let pi = self.parent_index(i);
1711        let pg = pi.and_then(|pi| self.resolve(pi, depth + 1));
1712        if let Some(pg) = pg {
1713            let g = &self.groups[pg];
1714            // A same-rule root under a group of that rule is part of it (`ollama serve` → runner), unless
1715            // it is known to be a session of its own: a nested agent CLI whose children carry another id.
1716            let sid = self.root_sid[i].as_ref();
1717            let parent_sid = g
1718                .root
1719                .and_then(|r| self.by_id.get(&r))
1720                .and_then(|&ri| self.root_sid[ri].as_ref());
1721            if g.matched_by.as_deref() == Some(rid.as_str())
1722                && g.kind == kind
1723                && (sid.is_none() || sid == parent_sid)
1724            {
1725                return Slot {
1726                    group: pg,
1727                    via: AttributionSignal::Ancestry,
1728                    confidence: Confidence::High,
1729                };
1730            }
1731        }
1732        // A root that carries the id of a live session rooted elsewhere (an agent CLI the session started
1733        // and that was re-parented to launchd) is part of that session, like any other marker carrier.
1734        if let Some(sid) = &self.root_sid[i] {
1735            let alias = session_group_key(kind, sid);
1736            if self.live_sessions.get(&alias).is_some_and(|&j| j != i) {
1737                if let Some(sg) = self.session_group(&alias, depth) {
1738                    return Slot {
1739                        group: sg,
1740                        via: AttributionSignal::Marker,
1741                        confidence: Confidence::High,
1742                    };
1743                }
1744            }
1745        }
1746        let g = self.ensure_group(&key, kind, &label, Some(p.id));
1747        {
1748            let grp = &mut self.groups[g];
1749            grp.kind = kind;
1750            grp.label = label;
1751            grp.matched_by = Some(rid);
1752            if grp.root.is_none() {
1753                grp.root = Some(p.id);
1754            }
1755        }
1756        self.meta[g].sticky = true;
1757        self.set_root_meta(g);
1758        if self.groups[g].owner_group.is_none() {
1759            // the group it was launched from (a terminal, an IDE, another session) — never a system component
1760            let parent_owner = match pg {
1761                Some(pg) if pg != g && self.groups[pg].kind != GroupKind::System => {
1762                    Some(self.groups[pg].id.clone())
1763                }
1764                _ => None,
1765            };
1766            // the session whose marker it carries: the live session's group, else the (dead) session alias
1767            let marker_owner = match self.marker_sessions(i).into_iter().next() {
1768                Some((alias, _)) => match self.live_sessions.get(&alias).copied() {
1769                    Some(r) if r == i => None,
1770                    Some(_) => self
1771                        .session_group(&alias, depth)
1772                        .filter(|&og| og != g)
1773                        .map(|og| self.groups[og].id.clone()),
1774                    None => Some(alias),
1775                },
1776                None => None,
1777            };
1778            let owner = parent_owner.or(marker_owner).or_else(|| {
1779                self.lineage
1780                    .get(&p.id)
1781                    .map(|le| le.group_id.clone())
1782                    .filter(|id| !id.is_empty() && *id != key)
1783            });
1784            self.groups[g].owner_group = owner;
1785        }
1786        Slot {
1787            group: g,
1788            via,
1789            confidence: Confidence::High,
1790        }
1791    }
1792
1793    fn responsible_group(&mut self, i: usize, depth: usize) -> Option<usize> {
1794        let p = self.proc(i);
1795        let rp = p.responsible_pid.filter(|&rp| rp != p.id.pid && rp > 1)?;
1796        let ri = *self.by_pid.get(&rp)?;
1797        let resp = self.proc(ri);
1798        if ri == i || is_terminal(resp) || is_shell(resp) || is_subreaper(resp) {
1799            return None;
1800        }
1801        // Launched from a shell or terminal before reaching the responsible app? Then ancestry decides.
1802        let mut cur = self.parent_index(i);
1803        let mut hops = 0;
1804        while let Some(ci) = cur {
1805            if ci == ri {
1806                break;
1807            }
1808            if is_boundary(self.proc(ci)) || hops > 64 {
1809                return None;
1810            }
1811            hops += 1;
1812            cur = self.parent_index(ci);
1813        }
1814        let g = self.resolve(ri, depth + 1)?;
1815        (!self.meta[g].launcher_root).then_some(g)
1816    }
1817
1818    /// A top-level root for process `i` (apps merge by bundle name, system daemons by name).
1819    fn heuristic_root(&mut self, i: usize, owner: Option<String>) -> Slot {
1820        let p = self.proc(i);
1821        let (kind, base) = self.rules.heuristic_kind_label(p);
1822        let suffix = self.user_suffix(p);
1823        let label = if kind == GroupKind::App && !suffix.is_empty() {
1824            // Another user's copy of an app: say so. By uid, like the `@u<uid>` suffix of the id: it is always
1825            // known and ASCII (the name, when the OS gave one, is `Process.user` and is exported as it is).
1826            format!("{base} (uid {})", p.uid.unwrap_or_default())
1827        } else {
1828            base.clone()
1829        };
1830        let key = match kind {
1831            GroupKind::App => format!("app:{}{suffix}", slug(&base)),
1832            GroupKind::System => format!("system:{}", slug(&label)),
1833            _ => format!("{}:{}:{}", kind.alias(), slug(&label), p.id.pid),
1834        };
1835        let g = self.ensure_group(&key, kind, &label, Some(p.id));
1836        // Prefer the app's main executable as the root (actions quit the app, never a helper).
1837        if kind == GroupKind::App && is_app_main(p) {
1838            let cur = self.groups[g].root.and_then(|r| self.proc_by_id(r));
1839            if cur.map(|c| !is_app_main(c)).unwrap_or(true) {
1840                self.groups[g].root = Some(p.id);
1841            }
1842        }
1843        if self.groups[g].owner_group.is_none() {
1844            self.groups[g].owner_group = owner;
1845        }
1846        self.set_root_meta(g);
1847        Slot {
1848            group: g,
1849            via: AttributionSignal::Heuristic,
1850            confidence: Confidence::Low,
1851        }
1852    }
1853
1854    /// Orphan roots are their own groups (never merged into an app by name) owned by the exited group.
1855    /// `agent_spawned` sets the preliminary `orphan` flag (the age rule is applied by [`crate::idle`]).
1856    fn orphan_root(
1857        &mut self,
1858        i: usize,
1859        owner: Option<String>,
1860        via: AttributionSignal,
1861        agent_spawned: bool,
1862    ) -> Slot {
1863        let p = self.proc(i);
1864        let (kind, label, key) = orphan_identity(p);
1865        let g = self.ensure_group(&key, kind, &label, Some(p.id));
1866        self.groups[g].owner_group = owner.filter(|o| *o != key);
1867        self.groups[g].orphan = agent_spawned;
1868        self.meta[g].sticky = true;
1869        self.set_root_meta(g);
1870        Slot {
1871            group: g,
1872            via,
1873            confidence: Confidence::Medium,
1874        }
1875    }
1876}
1877
1878/// Kind, label and group key of a process that is (or would be) an orphan root: its own group, keyed by pid
1879/// (orphans are never merged into an app group by name).
1880fn orphan_identity(p: &Process) -> (GroupKind, String, String) {
1881    let (kind, label) = heuristic_kind_label(p);
1882    let kind = if kind == GroupKind::System {
1883        GroupKind::Other
1884    } else {
1885        kind
1886    };
1887    let key = format!("{}:{}:{}", kind.alias(), slug(&label), p.id.pid);
1888    (kind, label, key)
1889}
1890
1891/// True if a process was re-parented since the journal recorded it: its recorded parent (> 1) is gone
1892/// (the ppid changed to 1 / a subreaper, or the recorded pid now belongs to a younger process).
1893fn reparented(p: &Process, le: &LineageEntry, s: &Snapshot, by_pid: &HashMap<u32, usize>) -> bool {
1894    let Some(orig) = le.ppid.filter(|&pp| pp > 1) else {
1895        return false;
1896    };
1897    let parent = |pid: u32| by_pid.get(&pid).map(|&i| &s.processes[i]);
1898    let orig_alive = parent(orig)
1899        .map(|pp| pp.id.start_time <= p.id.start_time)
1900        .unwrap_or(false);
1901    if p.ppid == Some(orig) {
1902        return !orig_alive;
1903    }
1904    match p.ppid {
1905        None | Some(0) | Some(1) => true,
1906        Some(now) => parent(now).map(is_subreaper).unwrap_or(true),
1907    }
1908}
1909
1910/// Session ids for session-keyed rule roots: from the earliest marker-carrying descendant whose nearest
1911/// rule-root ancestor is this root, else the root's own marker when no ancestor runs the same rule (a
1912/// nested agent inherits its parent's marker, which is not its own session).
1913fn session_ids(
1914    s: &Snapshot,
1915    rules: &CompiledRules,
1916    root_rule: &[Option<usize>],
1917    by_pid: &HashMap<u32, usize>,
1918) -> Vec<Option<String>> {
1919    let n = s.processes.len();
1920    let mut best: Vec<Option<(u64, u32, String)>> = vec![None; n];
1921    let parent_of = |i: usize| -> Option<usize> {
1922        let p = &s.processes[i];
1923        let pp = p.ppid.filter(|&pp| pp > 1 && pp != p.id.pid)?;
1924        let pi = *by_pid.get(&pp)?;
1925        (pi != i && !is_subreaper(&s.processes[pi])).then_some(pi)
1926    };
1927    for (ci, c) in s.processes.iter().enumerate() {
1928        if c.markers.session_id.is_none() {
1929            continue;
1930        }
1931        let mut cur = parent_of(ci);
1932        let mut hops = 0;
1933        while let Some(k) = cur {
1934            if hops > 64 {
1935                break;
1936            }
1937            if let Some(r) = root_rule[k] {
1938                // the id of the rule's own key: a nested agent's children also carry the outer agent's id
1939                let sid = rules.rules[r]
1940                    .rule
1941                    .session_env_key()
1942                    .and_then(|key| crate::redact::session_id_for_key(&c.markers, key));
1943                {
1944                    if let Some(sid) = sid {
1945                        let cand = (c.id.start_time, c.id.pid, sid.to_string());
1946                        if best[k]
1947                            .as_ref()
1948                            .map(|b| (cand.0, cand.1) < (b.0, b.1))
1949                            .unwrap_or(true)
1950                        {
1951                            best[k] = Some(cand);
1952                        }
1953                    }
1954                }
1955                break;
1956            }
1957            hops += 1;
1958            cur = parent_of(k);
1959        }
1960    }
1961    (0..n)
1962        .map(|i| {
1963            let r = root_rule[i]?;
1964            let rule = &rules.rules[r].rule;
1965            let key = rule.session_env_key()?;
1966            if let Some((_, _, sid)) = &best[i] {
1967                return Some(sid.clone());
1968            }
1969            let p = &s.processes[i];
1970            let own = crate::redact::session_id_for_key(&p.markers, key)?.to_string();
1971            // nested under the same rule → the marker is the parent session's
1972            let mut cur = parent_of(i);
1973            let mut hops = 0;
1974            while let Some(k) = cur {
1975                if hops > 64 {
1976                    break;
1977                }
1978                if root_rule[k] == Some(r) {
1979                    return None;
1980                }
1981                hops += 1;
1982                cur = parent_of(k);
1983            }
1984            Some(own)
1985        })
1986        .collect()
1987}
1988
1989fn adapter_hints(s: &Snapshot) -> HashMap<ProcId, AdapterHint> {
1990    let mut out = HashMap::new();
1991    for ms in &s.model_servers {
1992        let label = model_server_label(ms.kind);
1993        let id = if ms.id.is_empty() {
1994            slug(label)
1995        } else {
1996            slug(&ms.id)
1997        };
1998        for pid in &ms.pids {
1999            out.entry(*pid).or_insert_with(|| AdapterHint {
2000                key: format!("model:{id}"),
2001                kind: GroupKind::ModelServer,
2002                label: label.to_string(),
2003                matched_by: format!("adapter:{}", ms.id),
2004            });
2005        }
2006    }
2007    for sb in &s.sandboxes {
2008        // App-owned VMs (Claude desktop, Docker Desktop) belong to their app via the responsible pid.
2009        if sb.kind == SandboxKind::Vm && sb.runtime.to_ascii_lowercase().contains("virtualization") {
2010            continue;
2011        }
2012        let label = if sb.label.is_empty() {
2013            sb.runtime.clone()
2014        } else {
2015            sb.label.clone()
2016        };
2017        for pid in &sb.host_pids {
2018            out.entry(*pid).or_insert_with(|| AdapterHint {
2019                key: format!("sandbox:{}", slug(&sb.id)),
2020                kind: GroupKind::Sandbox,
2021                label: label.clone(),
2022                matched_by: format!("adapter:{}", sb.runtime),
2023            });
2024        }
2025    }
2026    out
2027}
2028
2029/// oomtop's own pid plus all its descendants.
2030fn self_tree(s: &Snapshot) -> HashSet<ProcId> {
2031    let mut out = HashSet::new();
2032    let Some(me) = s.self_pid.and_then(|pid| s.process_by_pid(pid)) else {
2033        return out;
2034    };
2035    let mut children: HashMap<u32, Vec<&Process>> = HashMap::new();
2036    for p in &s.processes {
2037        if let Some(pp) = p.ppid {
2038            children.entry(pp).or_default().push(p);
2039        }
2040    }
2041    let mut stack = vec![me];
2042    while let Some(p) = stack.pop() {
2043        if !out.insert(p.id) || out.len() > 4096 {
2044            continue;
2045        }
2046        if let Some(kids) = children.get(&p.id.pid) {
2047            stack.extend(
2048                kids.iter()
2049                    .filter(|k| k.id.start_time >= p.id.start_time)
2050                    .copied(),
2051            );
2052        }
2053    }
2054    out
2055}
2056
2057/// Groups all processes of the snapshot. Totals, reclaim gain, fingerprint, protection, `lower_bound` and
2058/// `owner_group` are filled; `orphan` is a preliminary flag (agent-spawned root whose spawning group is gone)
2059/// that [`crate::idle::IdleTracker::apply`] re-decides with the age rule, together with `idle` / `idle_for_s`.
2060pub fn attribute(snapshot: &Snapshot, ctx: &AttributionContext<'_>) -> Vec<Group> {
2061    let n = snapshot.processes.len();
2062    // pid → index of the newest process with that pid (pid reuse inside one listing keeps both entries).
2063    let mut by_pid: HashMap<u32, usize> = HashMap::with_capacity(n);
2064    for (i, p) in snapshot.processes.iter().enumerate() {
2065        match by_pid.get(&p.id.pid) {
2066            Some(&j) if snapshot.processes[j].id.start_time >= p.id.start_time => {}
2067            _ => {
2068                by_pid.insert(p.id.pid, i);
2069            }
2070        }
2071    }
2072    let by_id: HashMap<ProcId, usize> = snapshot
2073        .processes
2074        .iter()
2075        .enumerate()
2076        .map(|(i, p)| (p.id, i))
2077        .collect();
2078    let root_rule: Vec<Option<usize>> = snapshot
2079        .processes
2080        .iter()
2081        .map(|p| ctx.rules.match_root(p).map(|m| m.index))
2082        .collect();
2083    let root_sid = session_ids(snapshot, ctx.rules, &root_rule, &by_pid);
2084    // Session alias → its root. When several roots share a session id (a nested same-rule root whose
2085    // children carry the id), the oldest one is the session.
2086    let mut live_sessions: HashMap<String, usize> = HashMap::new();
2087    for (i, (r, sid)) in root_rule.iter().zip(&root_sid).enumerate() {
2088        let (Some(r), Some(sid)) = (r, sid) else { continue };
2089        let alias = session_group_key(ctx.rules.rules[*r].rule.kind, sid);
2090        let age = |k: usize| (snapshot.processes[k].id.start_time, snapshot.processes[k].id.pid);
2091        match live_sessions.get(&alias) {
2092            Some(&j) if age(j) <= age(i) => {}
2093            _ => {
2094                live_sessions.insert(alias, i);
2095            }
2096        }
2097    }
2098    let hints = adapter_hints(snapshot);
2099    let adapter = snapshot
2100        .processes
2101        .iter()
2102        .map(|p| hints.get(&p.id).cloned())
2103        .collect();
2104    let mut b = Builder {
2105        snap: snapshot,
2106        rules: ctx.rules,
2107        lineage: ctx.lineage,
2108        by_pid,
2109        by_id: by_id.clone(),
2110        groups: Vec::new(),
2111        meta: Vec::new(),
2112        key_to_group: HashMap::new(),
2113        assigned: vec![None; n],
2114        visiting: vec![false; n],
2115        root_rule,
2116        root_sid,
2117        adapter,
2118        live_sessions,
2119        self_uid: ctx.protect.self_uid,
2120    };
2121    // Resolve in (start_time, pid) order so parents and group roots usually resolve first.
2122    let mut order: Vec<usize> = (0..n).collect();
2123    order.sort_by_key(|&i| (snapshot.processes[i].id.start_time, snapshot.processes[i].id.pid));
2124    for &i in &order {
2125        if b.resolve(i, 0).is_none() {
2126            // Unreachable in practice (resolve only fails inside a cycle); never leave a process out.
2127            let slot = b.heuristic_root(i, None);
2128            b.assigned[i] = Some(slot);
2129        }
2130    }
2131    let Builder {
2132        mut groups, assigned, ..
2133    } = b;
2134    for &i in &order {
2135        if let Some(s) = assigned[i] {
2136            groups[s.group].members.push(Member {
2137                id: snapshot.processes[i].id,
2138                confidence: s.confidence,
2139                via: s.via,
2140            });
2141        }
2142    }
2143    groups.retain(|g| !g.members.is_empty());
2144    let self_ids = self_tree(snapshot);
2145    for g in &mut groups {
2146        if g.root
2147            .map(|r| !g.members.iter().any(|m| m.id == r))
2148            .unwrap_or(true)
2149        {
2150            g.root = g.members.first().map(|m| m.id);
2151        }
2152        finish_group(g, snapshot, ctx, &self_ids, &by_id);
2153    }
2154    link_by_project(&mut groups, snapshot, &by_id);
2155    groups.sort_by(|a, b| {
2156        b.totals
2157            .footprint
2158            .value
2159            .unwrap_or(0)
2160            .cmp(&a.totals.footprint.value.unwrap_or(0))
2161            .then_with(|| a.id.cmp(&b.id))
2162    });
2163    groups
2164}
2165
2166/// The per-sample numbers of a group — totals, swap gain, reclaim gain — from its member processes.
2167fn group_numbers<'a>(
2168    g: &mut Group,
2169    members: &[&Process],
2170    self_ids: &HashSet<ProcId>,
2171    reclaim_model: &crate::headroom::ReclaimModel,
2172    lookup: impl Fn(ProcId) -> Option<&'a Process> + Copy,
2173) {
2174    let mut footprint = sum_bytes(
2175        members.iter().map(|p| &p.mem.footprint_or_pss),
2176        "Σ footprint_or_pss",
2177    );
2178    if g.lower_bound && footprint.value.is_some() {
2179        footprint = footprint.into_estimate();
2180        footprint.source = "Σ footprint_or_pss (lower bound: VM memory under-counted)".into();
2181    }
2182    g.totals = GroupTotals {
2183        footprint,
2184        resident: sum_bytes(members.iter().map(|p| &p.mem.resident), "Σ resident"),
2185        gpu: sum_bytes(members.iter().map(|p| &p.mem.gpu), "Σ gpu"),
2186        swapped: sum_bytes(members.iter().map(|p| &p.mem.swapped), "Σ swapped"),
2187        cpu_pct: sum_f64(members.iter().map(|p| &p.cpu_pct), "Σ cpu"),
2188        process_count: members.len() as u32,
2189    };
2190    g.swap_gain = g.totals.swapped.clone().into_estimate();
2191    // An `oomtop mcp` child inside an agent session is not part of what stopping that session frees.
2192    if !g.is_self && g.members.iter().any(|m| self_ids.contains(&m.id)) {
2193        let mut others = g.clone();
2194        others.members.retain(|m| !self_ids.contains(&m.id));
2195        g.reclaim_gain = crate::headroom::group_reclaim_gain_by(&others, reclaim_model, lookup);
2196    } else {
2197        g.reclaim_gain = crate::headroom::group_reclaim_gain_by(g, reclaim_model, lookup);
2198    }
2199}
2200
2201/// Signature of every input group **membership** depends on: each process's identity fields, parent,
2202/// responsible pid, uid and markers, the adapter truth (model servers, sandboxes), the lineage entries of
2203/// the listed processes (without their timestamps) and the protection context. Two samples with the same
2204/// signature attribute to the same groups; only the per-sample numbers differ (see [`refresh_numbers`]).
2205/// On a quiet machine the process set is unchanged between most refreshes, so a frontend can skip the
2206/// whole attribution (SPEC §14 CPU budget).
2207pub fn membership_signature(snapshot: &Snapshot, ctx: &AttributionContext<'_>) -> u64 {
2208    use std::hash::{Hash, Hasher};
2209    let mut h = std::collections::hash_map::DefaultHasher::new();
2210    snapshot.host.os.hash(&mut h);
2211    snapshot.self_pid.hash(&mut h);
2212    snapshot.processes.len().hash(&mut h);
2213    for p in &snapshot.processes {
2214        p.id.hash(&mut h);
2215        p.ppid.hash(&mut h);
2216        p.responsible_pid.hash(&mut h);
2217        p.uid.hash(&mut h);
2218        identity_sig(p).hash(&mut h);
2219        p.markers.session_id.hash(&mut h);
2220        p.markers.agent.hash(&mut h);
2221        p.markers.keys.hash(&mut h);
2222        if let Some(le) = ctx.lineage.get(&p.id) {
2223            le.ppid.hash(&mut h);
2224            le.group_id.hash(&mut h);
2225            le.group_kind.hash(&mut h);
2226            le.group_label.hash(&mut h);
2227            le.group_fingerprint.hash(&mut h);
2228            le.session_id.hash(&mut h);
2229            le.spawned_by_agent.hash(&mut h);
2230        } else {
2231            0u8.hash(&mut h);
2232        }
2233    }
2234    for m in &snapshot.model_servers {
2235        m.id.hash(&mut h);
2236        m.kind.hash(&mut h);
2237        m.pids.hash(&mut h);
2238    }
2239    for b in &snapshot.sandboxes {
2240        b.id.hash(&mut h);
2241        b.kind.hash(&mut h);
2242        b.runtime.hash(&mut h);
2243        b.label.hash(&mut h);
2244        b.host_pids.hash(&mut h);
2245        b.footprint_lower_bound.hash(&mut h);
2246        b.configured_mem.value.hash(&mut h);
2247    }
2248    let pc = ctx.protect;
2249    pc.self_pid.hash(&mut h);
2250    pc.self_uid.hash(&mut h);
2251    pc.ancestor_pids.hash(&mut h);
2252    pc.protected_names.hash(&mut h);
2253    pc.caller_group.hash(&mut h);
2254    h.finish()
2255}
2256
2257/// Recomputes the per-sample numbers (totals, swap gain, reclaim gain) of `groups` — the result of an
2258/// earlier [`attribute`] with the same [`membership_signature`] — from `snapshot`, and re-sorts them by
2259/// footprint like [`attribute`] does. Membership, ids, labels, fingerprints and flags are kept.
2260pub fn refresh_numbers(groups: &mut [Group], snapshot: &Snapshot) {
2261    let by_id: HashMap<ProcId, usize> = snapshot
2262        .processes
2263        .iter()
2264        .enumerate()
2265        .map(|(i, p)| (p.id, i))
2266        .collect();
2267    let lookup = |id: ProcId| by_id.get(&id).map(|&i| &snapshot.processes[i]);
2268    let self_ids = self_tree(snapshot);
2269    let model = crate::headroom::ReclaimModel::from_snapshot(snapshot);
2270    for g in groups.iter_mut() {
2271        let members: Vec<&Process> = g.members.iter().filter_map(|m| lookup(m.id)).collect();
2272        group_numbers(g, &members, &self_ids, &model, lookup);
2273    }
2274    groups.sort_by(|a, b| {
2275        b.totals
2276            .footprint
2277            .value
2278            .unwrap_or(0)
2279            .cmp(&a.totals.footprint.value.unwrap_or(0))
2280            .then_with(|| a.id.cmp(&b.id))
2281    });
2282}
2283
2284fn finish_group(
2285    g: &mut Group,
2286    snapshot: &Snapshot,
2287    ctx: &AttributionContext<'_>,
2288    self_ids: &HashSet<ProcId>,
2289    by_id: &HashMap<ProcId, usize>,
2290) {
2291    let lookup = |id: ProcId| by_id.get(&id).map(|&i| &snapshot.processes[i]);
2292    // root first, then by start time (members were pushed in (start_time, pid) order)
2293    if let Some(r) = g.root {
2294        if let Some(pos) = g.members.iter().position(|m| m.id == r) {
2295            let m = g.members.remove(pos);
2296            g.members.insert(0, m);
2297        }
2298    }
2299    let members: Vec<&Process> = g.members.iter().filter_map(|m| lookup(m.id)).collect();
2300    let root = g.root.and_then(lookup);
2301    let reclaim_model = crate::headroom::ReclaimModel::from_snapshot(snapshot);
2302
2303    // lower bound: Virtualization.framework guests, or an adapter-reported under-count
2304    let sandbox = snapshot
2305        .sandboxes
2306        .iter()
2307        .find(|sb| sb.footprint_lower_bound && g.members.iter().any(|m| sb.host_pids.contains(&m.id)));
2308    g.lower_bound = g.lower_bound || members.iter().any(|p| is_vm_lower_bound(p)) || sandbox.is_some();
2309    if g.configured_mem.is_none() {
2310        g.configured_mem = sandbox.and_then(|sb| sb.configured_mem.value);
2311    }
2312
2313    g.is_self = g.id == SELF_GROUP_ID;
2314    group_numbers(g, &members, self_ids, &reclaim_model, lookup);
2315
2316    // Group confidence = how sure we are about the root's identity.
2317    let root_member = g.root.and_then(|r| g.members.iter().find(|m| m.id == r));
2318    g.confidence = match root_member.map(|m| (m.via, m.confidence)) {
2319        Some((AttributionSignal::Heuristic, _)) if g.kind == GroupKind::App => Confidence::Medium,
2320        Some((_, c)) => c,
2321        None => g.members.iter().map(|m| m.confidence).max().unwrap_or_default(),
2322    };
2323    if g.matched_by.is_some()
2324        && g.confidence < Confidence::High
2325        && g.matched_by.as_deref() != Some("cgroup:unit")
2326    {
2327        g.confidence = Confidence::High;
2328    }
2329
2330    if let Some(r) = root {
2331        if g.fingerprint.is_empty() {
2332            g.fingerprint = ctx.rules.group_fingerprint(g.kind, r);
2333        }
2334    }
2335    let rule_protected = g
2336        .matched_by
2337        .as_deref()
2338        .map(|id| ctx.rules.is_protected_rule(id))
2339        .unwrap_or(false);
2340    g.protected = g.protected
2341        || rule_protected
2342        || g.is_self
2343        || g.kind == GroupKind::System
2344        || ctx.protect.caller_group.as_deref() == Some(g.id.as_str())
2345        || root
2346            .map(|r| is_protected_process(r, snapshot, ctx.protect))
2347            .unwrap_or(false);
2348}
2349
2350/// Rules & heuristics, lowest priority (SPEC §7): a user-launched root whose cwd is inside exactly one live
2351/// agent session's project is linked to it via `owner_group` (membership is not changed; an owner that is
2352/// merely the terminal it was typed into is replaced).
2353fn link_by_project(groups: &mut [Group], s: &Snapshot, by_id: &HashMap<ProcId, usize>) {
2354    let lookup = |id: ProcId| by_id.get(&id).map(|&i| &s.processes[i]);
2355    let sessions: Vec<(String, String)> = groups
2356        .iter()
2357        .filter(|g| g.kind == GroupKind::AgentSession)
2358        .filter_map(|g| {
2359            let root = lookup(g.root?)?;
2360            let cwd = fingerprint::project_root(root)?;
2361            Some((cwd.to_string(), g.id.clone()))
2362        })
2363        .collect();
2364    if sessions.is_empty() {
2365        return;
2366    }
2367    // groups rooted in a terminal / multiplexer: "launched from iTerm" is less informative than the project
2368    let launchers: HashSet<String> = groups
2369        .iter()
2370        .filter(|g| g.root.and_then(lookup).map(is_terminal).unwrap_or(false))
2371        .map(|g| g.id.clone())
2372        .collect();
2373    for g in groups.iter_mut() {
2374        let replaceable = g
2375            .owner_group
2376            .as_ref()
2377            .map(|o| launchers.contains(o))
2378            .unwrap_or(true);
2379        if g.kind != GroupKind::Other || !replaceable || g.matched_by.is_some() || g.orphan {
2380            continue;
2381        }
2382        let Some(cwd) = g.root.and_then(lookup).and_then(fingerprint::project_root) else {
2383            continue;
2384        };
2385        let mut hits: Vec<&(String, String)> = sessions
2386            .iter()
2387            .filter(|(root, _)| {
2388                cwd == root
2389                    || cwd
2390                        .strip_prefix(root.as_str())
2391                        .map(|r| r.starts_with('/'))
2392                        .unwrap_or(false)
2393            })
2394            .collect();
2395        hits.sort_by_key(|(root, _)| std::cmp::Reverse(root.len()));
2396        match hits.as_slice() {
2397            [only] => g.owner_group = Some(only.1.clone()),
2398            [a, b, ..] if a.0.len() > b.0.len() => g.owner_group = Some(a.1.clone()),
2399            _ => {}
2400        }
2401    }
2402}
2403
2404#[cfg(test)]
2405mod tests {
2406    use super::*;
2407    use crate::model::{Markers, Measured};
2408
2409    pub(crate) fn proc(pid: u32, ppid: u32, name: &str, exe: &str, fp: u64) -> Process {
2410        Process {
2411            id: ProcId::new(pid, 1000 + pid as u64),
2412            ppid: Some(ppid),
2413            name: name.into(),
2414            exe: exe.into(),
2415            cmdline: vec![exe.into()],
2416            uid: Some(501),
2417            mem: crate::model::MemBreakdown {
2418                footprint_or_pss: Measured::exact(fp, "t"),
2419                resident: Measured::exact(fp / 2, "t"),
2420                ..Default::default()
2421            },
2422            ..Default::default()
2423        }
2424    }
2425
2426    fn rules() -> CompiledRules {
2427        let set: RuleSet = RuleSet {
2428            rules: vec![
2429                Rule {
2430                    kind: GroupKind::AgentSession,
2431                    label: "Claude Code".into(),
2432                    matcher: MatchSpec {
2433                        exe: vec!["claude".into()],
2434                        env: vec!["CLAUDECODE".into()],
2435                        ..Default::default()
2436                    },
2437                    session_key: Some("env:CLAUDE_CODE_SESSION_ID".into()),
2438                    ..Default::default()
2439                },
2440                Rule {
2441                    kind: GroupKind::BuildDaemon,
2442                    label: "GradleDaemon".into(),
2443                    matcher: MatchSpec {
2444                        script: vec!["org.gradle.launcher.daemon.*".into()],
2445                        ..Default::default()
2446                    },
2447                    ..Default::default()
2448                },
2449            ],
2450        };
2451        CompiledRules::compile(&set).unwrap()
2452    }
2453
2454    fn run(s: &Snapshot, lineage: &BTreeMap<ProcId, LineageEntry>) -> Vec<Group> {
2455        let r = rules();
2456        let protect = ProtectContext::default();
2457        attribute(
2458            s,
2459            &AttributionContext {
2460                rules: &r,
2461                lineage,
2462                protect: &protect,
2463            },
2464        )
2465    }
2466
2467    fn sess(sid: &str) -> Markers {
2468        Markers {
2469            session_id: Some(sid.into()),
2470            agent: Some("claude-code".into()),
2471            keys: vec!["CLAUDECODE".into(), "CLAUDE_CODE_SESSION_ID".into()],
2472        }
2473    }
2474
2475    #[test]
2476    fn sessions_ancestry_and_markers() {
2477        let mut s = Snapshot::default();
2478        // The agent CLI itself carries no marker; only its children do.
2479        let claude = proc(100, 50, "claude", "/opt/bin/claude", 400);
2480        let desktop = proc(
2481            300,
2482            1,
2483            "Claude",
2484            "/Applications/Claude.app/Contents/MacOS/Claude",
2485            50,
2486        );
2487        let zsh = proc(50, 1, "zsh", "/bin/zsh", 10);
2488        let mut child = proc(101, 100, "node", "/usr/bin/node", 100);
2489        child.markers = sess("abcdef0123456789");
2490        // re-parented to launchd but still carries the marker
2491        let mut orphan = proc(102, 1, "chrome", "/x/chrome", 1000);
2492        orphan.markers = sess("abcdef0123456789");
2493        let mut gradle = proc(200, 1, "java", "/usr/bin/java", 3000);
2494        gradle.cmdline = vec![
2495            "java".into(),
2496            "org.gradle.launcher.daemon.bootstrap.GradleDaemon".into(),
2497        ];
2498        gradle.markers = sess("abcdef0123456789");
2499        s.processes = vec![zsh, claude, child, orphan, gradle, desktop];
2500        let groups = run(&s, &BTreeMap::new());
2501        let agent = groups.iter().find(|g| g.kind == GroupKind::AgentSession).unwrap();
2502        assert_eq!(agent.members.len(), 3, "{groups:#?}");
2503        assert_eq!(agent.totals.footprint.value, Some(1500));
2504        // keyed by rule and root pid, not by the session id its children happen to carry
2505        assert_eq!(agent.id, "agent:claude-code:100");
2506        assert_eq!(agent.root.map(|r| r.pid), Some(100));
2507        let daemon = groups.iter().find(|g| g.kind == GroupKind::BuildDaemon).unwrap();
2508        assert_eq!(daemon.members.len(), 1);
2509        assert_eq!(daemon.owner_group.as_deref(), Some("agent:claude-code:100"));
2510        assert!(!daemon.fingerprint.is_empty());
2511        let app = groups.iter().find(|g| g.label == "Claude").unwrap();
2512        assert_eq!(
2513            app.kind,
2514            GroupKind::App,
2515            "desktop app is not Claude Code (case-sensitive exe)"
2516        );
2517        let zsh_group = groups.iter().find(|g| g.label == "zsh").unwrap();
2518        assert_eq!(zsh_group.members.len(), 1);
2519        // largest first
2520        assert_eq!(groups[0].kind, GroupKind::BuildDaemon);
2521    }
2522
2523    #[test]
2524    fn lineage_rejoins_live_group_and_orphans_dead_one() {
2525        let mut s = Snapshot::default();
2526        let orphan = proc(500, 1, "chrome", "/x/chrome", 100);
2527        let stale = proc(
2528            600,
2529            1,
2530            "Claude",
2531            "/Applications/Claude.app/Contents/MacOS/Claude",
2532            100,
2533        );
2534        s.processes = vec![orphan.clone(), stale.clone()];
2535        let mut lineage = BTreeMap::new();
2536        let le = |id: ProcId, ppid: u32| LineageEntry {
2537            id,
2538            ppid: Some(ppid),
2539            group_id: "agent:abc".into(),
2540            group_kind: GroupKind::AgentSession,
2541            group_label: "Claude Code".into(),
2542            spawned_by_agent: true,
2543            ..Default::default()
2544        };
2545        lineage.insert(orphan.id, le(orphan.id, 77));
2546        lineage.insert(stale.id, le(stale.id, 1));
2547        let groups = run(&s, &lineage);
2548        // the session is gone → the re-parented process is its own (orphan) root owned by the session
2549        let g = groups.iter().find(|g| g.root == Some(orphan.id)).unwrap();
2550        assert_eq!(g.members[0].via, AttributionSignal::Lineage);
2551        assert_eq!(g.owner_group.as_deref(), Some("agent:abc"));
2552        assert_eq!(g.members.len(), 1);
2553        // ppid was already 1 when recorded → not re-parented → heuristic app
2554        assert!(groups
2555            .iter()
2556            .any(|g| g.label == "Claude" && g.kind == GroupKind::App));
2557    }
2558
2559    #[test]
2560    fn orphan_identity_is_stable_across_samples() {
2561        // sample 1: session gone, marker carrier → orphan root owned by the dead session
2562        let mut s = Snapshot::default();
2563        let mut o = proc(700, 1, "node", "/usr/bin/node", 100);
2564        o.markers = sess("feedfacefeedface");
2565        s.processes = vec![o.clone()];
2566        let g1 = run(&s, &BTreeMap::new());
2567        assert_eq!(g1[0].owner_group.as_deref(), Some("agent:feedfacefeed"));
2568        assert!(g1[0].orphan);
2569        // sample 2: the engine journaled the orphan's *own* group id (+ original ppid and session id)
2570        let mut lineage = BTreeMap::new();
2571        lineage.insert(
2572            o.id,
2573            LineageEntry {
2574                id: o.id,
2575                ppid: Some(650),
2576                group_id: g1[0].id.clone(),
2577                group_kind: g1[0].kind,
2578                session_id: Some("feedfacefeedface".into()),
2579                spawned_by_agent: true,
2580                ..Default::default()
2581            },
2582        );
2583        let g2 = run(&s, &lineage);
2584        assert_eq!(g2[0].id, g1[0].id);
2585        assert_eq!(
2586            g2[0].owner_group.as_deref(),
2587            Some("agent:feedfacefeed"),
2588            "never its own owner"
2589        );
2590        assert!(g2[0].orphan);
2591        // …and without the marker the journal alone still knows the session
2592        s.processes[0].markers = Markers::default();
2593        let g3 = run(&s, &lineage);
2594        assert_eq!(g3[0].id, g1[0].id);
2595        assert_eq!(g3[0].owner_group.as_deref(), Some("agent:feedfacefeed"));
2596        assert_eq!(g3[0].members[0].via, AttributionSignal::Lineage);
2597    }
2598
2599    /// Audit finding 2: the group id of a session must not depend on which marker-carrying descendants are
2600    /// alive in the sample (it used to flip between `agent:<rule>:<pid>` and `agent:<hash12>`).
2601    #[test]
2602    fn session_id_is_stable_while_marker_children_come_and_go() {
2603        let claude = proc(100, 50, "claude", "/opt/bin/claude", 400);
2604        let mut tool = proc(101, 100, "node", "/usr/bin/node", 50);
2605        tool.markers = sess("abcdef0123456789");
2606        let mut s = Snapshot {
2607            processes: vec![claude.clone()],
2608            ..Default::default()
2609        };
2610        let idle = run(&s, &BTreeMap::new());
2611        s.processes = vec![claude.clone(), tool.clone()];
2612        let busy = run(&s, &BTreeMap::new());
2613        s.processes = vec![claude];
2614        let idle_again = run(&s, &BTreeMap::new());
2615        let id = |g: &[Group]| {
2616            g.iter()
2617                .find(|g| g.kind == GroupKind::AgentSession)
2618                .map(|g| g.id.clone())
2619                .unwrap()
2620        };
2621        assert_eq!(id(&idle), "agent:claude-code:100");
2622        assert_eq!(id(&busy), id(&idle));
2623        assert_eq!(id(&idle_again), id(&idle));
2624    }
2625
2626    /// A journal entry names the session either by its group id or (journals written before ids were
2627    /// pid-keyed, and orphans that recorded themselves) by the hashed session id: both find the live group,
2628    /// whatever the order of the process table.
2629    #[test]
2630    fn lineage_finds_the_live_session_by_id_or_alias() {
2631        let claude = proc(900, 50, "claude", "/opt/bin/claude", 400);
2632        let mut tool = proc(901, 900, "node", "/usr/bin/node", 50);
2633        tool.markers = sess("abcdef0123456789");
2634        // spawned by the session with a scrubbed environment, re-parented to launchd; listed *before* the
2635        // session root, so the root is not resolved yet when the journal is consulted
2636        let mut watcher = proc(300, 1, "fswatch", "/usr/bin/fswatch", 20);
2637        watcher.id.start_time = claude.id.start_time + 1;
2638        let s = Snapshot {
2639            processes: vec![watcher.clone(), claude, tool],
2640            ..Default::default()
2641        };
2642        for recorded in ["agent:claude-code:900", "agent:abcdef012345"] {
2643            let mut lineage = BTreeMap::new();
2644            lineage.insert(
2645                watcher.id,
2646                LineageEntry {
2647                    id: watcher.id,
2648                    ppid: Some(901),
2649                    group_id: recorded.into(),
2650                    group_kind: GroupKind::AgentSession,
2651                    group_label: "Claude Code".into(),
2652                    spawned_by_agent: true,
2653                    ..Default::default()
2654                },
2655            );
2656            let groups = run(&s, &lineage);
2657            let a = groups.iter().find(|g| g.kind == GroupKind::AgentSession).unwrap();
2658            assert_eq!(a.id, "agent:claude-code:900", "{recorded}");
2659            let m = a.members.iter().find(|m| m.id.pid == 300);
2660            assert_eq!(
2661                m.map(|m| m.via),
2662                Some(AttributionSignal::Lineage),
2663                "{recorded}: {groups:#?}"
2664            );
2665        }
2666    }
2667
2668    /// Audit finding 5: a session id belongs to the marker key it came from. Codex started inside a Claude
2669    /// Code session inherits `CLAUDE_CODE_SESSION_ID`; its children must not be keyed (or labelled) by it.
2670    #[test]
2671    fn nested_agents_read_the_session_id_of_their_own_key() {
2672        let set = RuleSet {
2673            rules: vec![
2674                Rule {
2675                    kind: GroupKind::AgentSession,
2676                    label: "Claude Code".into(),
2677                    matcher: MatchSpec {
2678                        exe: vec!["claude".into()],
2679                        env: vec!["CLAUDECODE".into()],
2680                        ..Default::default()
2681                    },
2682                    session_key: Some("env:CLAUDE_CODE_SESSION_ID".into()),
2683                    ..Default::default()
2684                },
2685                Rule {
2686                    kind: GroupKind::AgentSession,
2687                    label: "Codex".into(),
2688                    matcher: MatchSpec {
2689                        exe: vec!["codex".into()],
2690                        env: vec!["CODEX_SESSION_ID".into()],
2691                        ..Default::default()
2692                    },
2693                    session_key: Some("env:CODEX_SESSION_ID".into()),
2694                    ..Default::default()
2695                },
2696            ],
2697        };
2698        let rules = CompiledRules::compile(&set).unwrap();
2699        let allow: Vec<String> = ["CLAUDECODE", "CLAUDE_CODE_SESSION_ID", "CODEX_SESSION_ID"]
2700            .iter()
2701            .map(|s| s.to_string())
2702            .collect();
2703        let claude_env = [("CLAUDECODE", "1"), ("CLAUDE_CODE_SESSION_ID", "outer-claude")];
2704        let both_env = [
2705            ("CLAUDECODE", "1"),
2706            ("CLAUDE_CODE_SESSION_ID", "outer-claude"),
2707            ("CODEX_SESSION_ID", "inner-codex"),
2708        ];
2709        let claude = proc(100, 50, "claude", "/opt/bin/claude", 400);
2710        let mut sh = proc(101, 100, "zsh", "/bin/zsh", 5);
2711        sh.markers = crate::redact::markers_from_env(claude_env, &allow);
2712        let mut codex = proc(110, 101, "codex", "/opt/bin/codex", 300);
2713        codex.markers = crate::redact::markers_from_env(claude_env, &allow);
2714        let mut tool = proc(111, 110, "node", "/usr/bin/node", 50);
2715        tool.markers = crate::redact::markers_from_env(both_env, &allow);
2716        // a Codex tool process re-parented to launchd: it carries both ids and belongs to Codex
2717        let mut orphan = proc(112, 1, "python3", "/usr/bin/python3", 70);
2718        orphan.markers = crate::redact::markers_from_env(both_env, &allow);
2719        // …and one of Claude's own, with only Claude's id
2720        let mut claude_orphan = proc(102, 1, "python3", "/usr/bin/python3", 70);
2721        claude_orphan.markers = crate::redact::markers_from_env(claude_env, &allow);
2722        let s = Snapshot {
2723            processes: vec![claude, sh, codex, tool, orphan, claude_orphan],
2724            ..Default::default()
2725        };
2726        let protect = ProtectContext::default();
2727        let groups = attribute(
2728            &s,
2729            &AttributionContext {
2730                rules: &rules,
2731                lineage: &BTreeMap::new(),
2732                protect: &protect,
2733            },
2734        );
2735        let pids = |label: &str| -> Vec<u32> {
2736            let g = groups.iter().find(|g| g.label == label).unwrap();
2737            let mut v: Vec<u32> = g.members.iter().map(|m| m.id.pid).collect();
2738            v.sort();
2739            v
2740        };
2741        assert_eq!(pids("Claude Code"), vec![100, 101, 102], "{groups:#?}");
2742        assert_eq!(pids("Codex"), vec![110, 111, 112], "{groups:#?}");
2743        let cx = groups.iter().find(|g| g.label == "Codex").unwrap();
2744        assert_eq!(cx.owner_group.as_deref(), Some("agent:claude-code:100"));
2745        assert_eq!(
2746            groups
2747                .iter()
2748                .filter(|g| g.kind == GroupKind::AgentSession)
2749                .count(),
2750            2
2751        );
2752    }
2753
2754    #[test]
2755    fn workers_of_a_rule_root_stay_with_it_despite_markers() {
2756        // `./gradlew build` in a session → daemon (ppid 1) → worker; both inherit the session env
2757        let mut s = Snapshot::default();
2758        let claude = proc(100, 50, "claude", "/opt/bin/claude", 400);
2759        let mut mcp = proc(101, 100, "node", "/usr/bin/node", 50);
2760        mcp.markers = sess("abcdef0123456789");
2761        let mut daemon = proc(200, 1, "java", "/usr/bin/java", 3000);
2762        daemon.cmdline = vec![
2763            "java".into(),
2764            "org.gradle.launcher.daemon.bootstrap.GradleDaemon".into(),
2765        ];
2766        daemon.markers = sess("abcdef0123456789");
2767        let mut worker = proc(201, 200, "java", "/usr/bin/java", 500);
2768        worker.markers = sess("abcdef0123456789");
2769        s.processes = vec![claude, mcp, daemon, worker];
2770        let groups = run(&s, &BTreeMap::new());
2771        let d = groups.iter().find(|g| g.kind == GroupKind::BuildDaemon).unwrap();
2772        let pids: Vec<u32> = d.members.iter().map(|m| m.id.pid).collect();
2773        assert_eq!(pids, vec![200, 201], "{groups:#?}");
2774        assert_eq!(d.members[1].via, AttributionSignal::Ancestry);
2775        assert_eq!(d.owner_group.as_deref(), Some("agent:claude-code:100"));
2776        let a = groups.iter().find(|g| g.kind == GroupKind::AgentSession).unwrap();
2777        assert_eq!(a.members.len(), 2);
2778    }
2779
2780    #[test]
2781    fn raw_or_non_ascii_session_ids_never_panic_or_leak() {
2782        let mut s = Snapshot::default();
2783        let claude = proc(100, 50, "claude", "/opt/bin/claude", 400);
2784        let mut child = proc(101, 100, "node", "/usr/bin/node", 50);
2785        // byte 12 falls inside 'ä' (a byte-index slice would panic)
2786        child.markers = sess("aääääääääää-raw");
2787        s.processes = vec![claude, child];
2788        let groups = run(&s, &BTreeMap::new());
2789        let a = groups.iter().find(|g| g.kind == GroupKind::AgentSession).unwrap();
2790        assert!(a.id.is_ascii() && !a.id.contains("raw"), "{}", a.id);
2791        assert_eq!(a.members.len(), 2);
2792        // …and the alias of a dead session (an orphan's owner) is a hash, never the raw id
2793        s.processes.remove(0);
2794        s.processes[0].ppid = Some(1);
2795        let groups = run(&s, &BTreeMap::new());
2796        let owner = groups[0].owner_group.clone().unwrap();
2797        assert!(owner.is_ascii() && !owner.contains("raw"), "{owner}");
2798        assert_eq!(owner.len(), "agent:".len() + 12);
2799        // a hashed id keeps its prefix (ids stay stable with the existing journal)
2800        assert_eq!(
2801            session_group_key(GroupKind::AgentSession, "abcdef0123456789"),
2802            "agent:abcdef012345"
2803        );
2804    }
2805
2806    #[test]
2807    fn lineage_never_rejoins_a_pid_reused_group() {
2808        // journal: pid 900 (started at 1900) was spawned by group "other:start-sh:800"; pid 800 now belongs
2809        // to a *younger* process with the same label → not the group that spawned it
2810        let mut s = Snapshot::default();
2811        let mut reused = proc(800, 1, "start.sh", "/bin/start.sh", 10);
2812        reused.id.start_time = 5000;
2813        let child = proc(900, 1, "node", "/usr/bin/node", 100);
2814        // an older XPC-style process that names the reused pid as responsible makes it resolve first
2815        let mut early = proc(850, 1, "helper", "/opt/helper", 1);
2816        early.responsible_pid = Some(800);
2817        s.processes = vec![reused.clone(), child.clone(), early];
2818        let groups = run(&s, &BTreeMap::new());
2819        let key = groups
2820            .iter()
2821            .find(|g| g.root == Some(reused.id))
2822            .unwrap()
2823            .id
2824            .clone();
2825        let mut lineage = BTreeMap::new();
2826        lineage.insert(
2827            child.id,
2828            LineageEntry {
2829                id: child.id,
2830                ppid: Some(800),
2831                group_id: key.clone(),
2832                group_kind: GroupKind::Other,
2833                group_label: "start.sh".into(),
2834                ..Default::default()
2835            },
2836        );
2837        let groups = run(&s, &lineage);
2838        let g = groups
2839            .iter()
2840            .find(|g| g.members.iter().any(|m| m.id == child.id))
2841            .unwrap();
2842        assert_ne!(g.id, key, "{groups:#?}");
2843        assert_eq!(g.root, Some(child.id));
2844        assert_eq!(g.owner_group.as_deref(), Some(key.as_str()));
2845    }
2846
2847    #[test]
2848    fn libexec_terminal_is_not_a_system_component() {
2849        let t = proc(
2850            600,
2851            400,
2852            "gnome-terminal-",
2853            "/usr/libexec/gnome-terminal-server",
2854            60,
2855        );
2856        assert_eq!(heuristic_kind_label(&t).0, GroupKind::Other);
2857        let d = proc(601, 1, "polkitd", "/usr/libexec/polkitd", 6);
2858        assert_eq!(heuristic_kind_label(&d).0, GroupKind::System);
2859    }
2860
2861    #[test]
2862    fn bad_rules_are_errors() {
2863        let set = RuleSet {
2864            rules: vec![Rule {
2865                label: "x".into(),
2866                matcher: MatchSpec {
2867                    cmdline: vec!["(".into()],
2868                    ..Default::default()
2869                },
2870                ..Default::default()
2871            }],
2872        };
2873        assert!(matches!(
2874            CompiledRules::compile(&set),
2875            Err(RuleError::Regex { .. })
2876        ));
2877        let set = RuleSet {
2878            rules: vec![Rule::default()],
2879        };
2880        assert!(matches!(
2881            CompiledRules::compile(&set),
2882            Err(RuleError::EmptyLabel { .. })
2883        ));
2884        let set = RuleSet {
2885            rules: vec![Rule {
2886                label: "x".into(),
2887                session_key: Some("CLAUDE_CODE_SESSION_ID".into()),
2888                ..Default::default()
2889            }],
2890        };
2891        assert!(matches!(
2892            CompiledRules::compile(&set),
2893            Err(RuleError::SessionKey { .. })
2894        ));
2895    }
2896
2897    /// Audit finding 9: a misspelled top-level table (`[[groups]]`, `[[rule]]`) is an error, not an
2898    /// empty rule set.
2899    #[test]
2900    fn unknown_top_level_keys_in_a_rule_set_are_errors() {
2901        let ok: RuleSet = serde_json::from_str(r#"{"group":[{"label":"x","match":{"exe":["x"]}}]}"#).unwrap();
2902        assert_eq!(ok.rules.len(), 1);
2903        assert_eq!(serde_json::from_str::<RuleSet>("{}").unwrap().rules.len(), 0);
2904        for bad in [
2905            r#"{"groups":[{"label":"x","match":{"exe":["x"]}}]}"#,
2906            r#"{"rule":[{"label":"x"}]}"#,
2907            r#"{"group":[],"version":2}"#,
2908        ] {
2909            let e = serde_json::from_str::<RuleSet>(bad).unwrap_err().to_string();
2910            assert!(e.contains("unknown field"), "{bad}: {e}");
2911        }
2912    }
2913
2914    #[test]
2915    fn slugs() {
2916        assert_eq!(slug("Claude Code"), "claude-code");
2917        assert_eq!(slug("  sd-server · qwen "), "sd-server-qwen");
2918    }
2919
2920    #[test]
2921    fn cgroups() {
2922        let c = |p: &str| parse_cgroup(p);
2923        assert_eq!(
2924            c("0::/system.slice/docker-3f2a9c01e2b4aabbccddeeff00112233445566778899aabbccddeeff00112233.scope"),
2925            Some(CgroupScope::Container {
2926                runtime: "docker".into(),
2927                id: "3f2a9c01e2b4".into()
2928            })
2929        );
2930        assert_eq!(
2931            c("/user.slice/user-1000.slice/user@1000.service/user.slice/libpod-0123456789abcdef0123.scope/container"),
2932            Some(CgroupScope::Container {
2933                runtime: "podman".into(),
2934                id: "0123456789ab".into()
2935            })
2936        );
2937        assert_eq!(
2938            c("/kubepods/burstable/pod1234-5678/0123456789abcdef0123456789abcdef"),
2939            Some(CgroupScope::Container {
2940                runtime: "kubernetes".into(),
2941                id: "0123456789ab".into()
2942            })
2943        );
2944        assert_eq!(
2945            c("/machine.slice/machine-qemu\\x2d1\\x2dubuntu.scope/libvirt/emulator"),
2946            Some(CgroupScope::Vm {
2947                name: "ubuntu".into()
2948            })
2949        );
2950        assert_eq!(
2951            c("/system.slice/ollama.service"),
2952            Some(CgroupScope::Service {
2953                unit: "ollama".into(),
2954                system: true
2955            })
2956        );
2957        assert_eq!(
2958            c("/user.slice/user-1000.slice/user@1000.service/app.slice/app-gnome-firefox-4242.scope"),
2959            Some(CgroupScope::App {
2960                app: "firefox".into()
2961            })
2962        );
2963        assert_eq!(
2964            c("/user.slice/user-1000.slice/user@1000.service/app.slice/app-flatpak-org.mozilla.firefox-4242.scope"),
2965            Some(CgroupScope::App { app: "firefox".into() })
2966        );
2967        assert_eq!(c("/user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/vte-spawn-1a2b.scope"), None);
2968        assert_eq!(
2969            c("/user.slice/user-1000.slice/user@1000.service/app.slice/app-kitty-4242.scope"),
2970            None
2971        );
2972        assert_eq!(c("/user.slice/user-1000.slice/session-2.scope"), None);
2973        assert_eq!(
2974            c("/user.slice/user-1000.slice/user@1000.service/init.scope"),
2975            None
2976        );
2977    }
2978
2979    /// Real-world kubelet cgroup layouts: cgroupfs and systemd drivers, every QoS class, containerd /
2980    /// CRI-O / cri-dockerd scopes, pod-level paths, nodes nested in kind / k3d containers, rootless k3s.
2981    #[test]
2982    fn kube_cgroups() {
2983        let cid = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
2984        let uid = "8f6c1c3e-3b5a-4b8e-9d55-0a1b2c3d4e5f";
2985        let uid_ = uid.replace('-', "_");
2986        let k = |p: &str| parse_kube_cgroup(p);
2987        // cgroupfs driver (containerd/k3s/microk8s default), burstable.
2988        let c = k(&format!("0::/kubepods/burstable/pod{uid}/{cid}")).unwrap();
2989        assert_eq!(c.qos, QosClass::Burstable);
2990        assert_eq!(c.pod_uid, uid);
2991        assert_eq!(c.container_id.as_deref(), Some(cid));
2992        assert_eq!(c.runtime, None);
2993        assert_eq!(c.pod_cgroup, format!("/kubepods/burstable/pod{uid}"));
2994        assert_eq!(
2995            c.container_cgroup,
2996            Some(format!("/kubepods/burstable/pod{uid}/{cid}"))
2997        );
2998        assert_eq!(c.node_prefix, "");
2999        // cgroupfs guaranteed (pod directly under kubepods) and besteffort.
3000        assert_eq!(
3001            k(&format!("/kubepods/pod{uid}/{cid}")).unwrap().qos,
3002            QosClass::Guaranteed
3003        );
3004        assert_eq!(
3005            k(&format!("/kubepods/besteffort/pod{uid}/{cid}")).unwrap().qos,
3006            QosClass::BestEffort
3007        );
3008        // systemd driver, containerd.
3009        let c = k(&format!(
3010            "/kubepods.slice/kubepods-burstable.slice/kubepods-burstable-pod{uid_}.slice/cri-containerd-{cid}.scope"
3011        ))
3012        .unwrap();
3013        assert_eq!((c.qos, c.pod_uid.as_str()), (QosClass::Burstable, uid));
3014        assert_eq!(c.runtime.as_deref(), Some("containerd"));
3015        assert_eq!(c.container_id.as_deref(), Some(cid));
3016        assert!(c
3017            .pod_cgroup
3018            .ends_with(&format!("kubepods-burstable-pod{uid_}.slice")));
3019        // systemd driver guaranteed + CRI-O, and its conmon scope.
3020        let c = k(&format!(
3021            "/kubepods.slice/kubepods-pod{uid_}.slice/crio-{cid}.scope"
3022        ))
3023        .unwrap();
3024        assert_eq!(
3025            (c.qos, c.runtime.as_deref(), c.conmon),
3026            (QosClass::Guaranteed, Some("cri-o"), false)
3027        );
3028        let c = k(&format!(
3029            "/kubepods.slice/kubepods-pod{uid_}.slice/crio-conmon-{cid}.scope"
3030        ))
3031        .unwrap();
3032        assert!(c.conmon);
3033        // cri-dockerd (Docker Desktop / minikube docker runtime).
3034        let c = k(&format!(
3035            "/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-pod{uid_}.slice/docker-{cid}.scope"
3036        ))
3037        .unwrap();
3038        assert_eq!(
3039            (c.qos, c.runtime.as_deref()),
3040            (QosClass::BestEffort, Some("docker"))
3041        );
3042        // Pod-level cgroup: no container.
3043        let c = k(&format!("/kubepods/burstable/pod{uid}")).unwrap();
3044        assert_eq!((c.container_id, c.container_cgroup), (None, None));
3045        // kind node (kubelet cgroup root /kubelet) seen from the host, inside the node's docker scope.
3046        let node = format!("/system.slice/docker-{cid}.scope");
3047        let c = k(&format!(
3048            "{node}/kubelet.slice/kubelet-kubepods.slice/kubelet-kubepods-burstable.slice/kubelet-kubepods-burstable-pod{uid_}.slice/cri-containerd-{cid}.scope"
3049        ))
3050        .unwrap();
3051        assert_eq!(c.node_prefix, format!("{node}/kubelet.slice"));
3052        assert_eq!((c.qos, c.pod_uid.as_str()), (QosClass::Burstable, uid));
3053        // k3d node (cgroupfs inside a docker container), rootless k3s under a user service.
3054        let c = k(&format!(
3055            "/system.slice/docker-{cid}.scope/kubepods/besteffort/pod{uid}/{cid}"
3056        ))
3057        .unwrap();
3058        assert_eq!(c.node_prefix, format!("/system.slice/docker-{cid}.scope"));
3059        let c = k(&format!(
3060            "/user.slice/user-1000.slice/user@1000.service/k3s-rootless.service/kubepods/burstable/pod{uid}/{cid}"
3061        ))
3062        .unwrap();
3063        assert_eq!(c.qos, QosClass::Burstable);
3064        // Not kubelet paths.
3065        for p in [
3066            "/system.slice/kubelet.service",
3067            "/kubepods.slice",
3068            "/kubepods/burstable",
3069            &format!("/system.slice/docker-{cid}.scope"),
3070            &format!("/kubepods/burstable/podnot-a-uid/{cid}"),
3071            &format!("/kubepods/burstable/pod{uid}/not-an-id"),
3072            &format!("/kubepods/burstable/extra/pod{uid}/{cid}"),
3073        ] {
3074            assert_eq!(k(p), None, "{p}");
3075        }
3076        // The grouping parser still keeps its 12-character id for the same paths.
3077        assert_eq!(
3078            parse_cgroup(&format!("/kubepods/burstable/pod{uid}/{cid}")),
3079            Some(CgroupScope::Container {
3080                runtime: "kubernetes".into(),
3081                id: cid[..12].into()
3082            })
3083        );
3084        assert_eq!(QosClass::parse("BestEffort"), Some(QosClass::BestEffort));
3085    }
3086
3087    #[test]
3088    fn indexed_matching_equals_rule_by_rule() {
3089        let set: RuleSet = serde_json::from_str(
3090            r#"{ "group": [
3091              { "id": "a", "kind": "agent_session", "label": "A", "match": { "exe": ["claude", "**/versions/*"], "name": ["claude"], "script": ["**/@anthropic-ai/claude-code/**"], "env": ["CLAUDECODE"] }, "session_key": "env:CLAUDE_CODE_SESSION_ID" },
3092              { "id": "b", "kind": "model_server", "label": "B", "match": { "cmdline": ["vllm\\s+serve", "mlx_lm[._]server"] } },
3093              { "id": "c", "kind": "app", "label": "C", "match": { "exe": ["firefox"] }, "exclude": { "exe": ["**/*.app/**"] } },
3094              { "id": "d", "kind": "other", "label": "D", "match": { "cwd": ["/srv/**"], "bundle": ["com.example.*"], "cgroup": ["/system.slice/x*.service"] } },
3095              { "id": "e", "kind": "build_daemon", "label": "E", "priority": 5, "match": { "script": ["*.js"] } },
3096              { "id": "f", "kind": "other", "label": "F only env", "match": { "env": ["CODEX_SANDBOX"] } }
3097            ] }"#,
3098        )
3099        .unwrap();
3100        let r = CompiledRules::compile(&set).unwrap();
3101        let mk = |exe: &str, argv: &[&str]| Process {
3102            exe: exe.into(),
3103            name: basename(exe).into(),
3104            cmdline: argv.iter().map(|s| s.to_string()).collect(),
3105            ..Default::default()
3106        };
3107        let mut cases = vec![
3108            mk("/opt/bin/claude", &["claude"]),
3109            mk("/u/.local/share/claude/versions/2.1.3", &["claude"]),
3110            mk("", &["claude", "-p", "x"]),
3111            mk(
3112                "/usr/bin/node",
3113                &["node", "/l/node_modules/@anthropic-ai/claude-code/cli.js"],
3114            ),
3115            mk("/usr/bin/python3", &["python3", "-m", "vllm", "serve", "m"]),
3116            mk("/usr/bin/python3", &["python", "-m", "mlx_lm.server"]),
3117            mk("/usr/lib/firefox/firefox", &["firefox"]),
3118            mk("/Applications/Firefox.app/Contents/MacOS/firefox", &["firefox"]),
3119            mk("/usr/bin/node", &["node", "server.js"]),
3120            mk("/bin/zsh", &["-zsh"]),
3121            mk("/x/tool", &[]),
3122        ];
3123        let mut d = mk("/x/y", &["y"]);
3124        d.cwd = Some("/srv/app".into());
3125        cases.push(d.clone());
3126        d.cwd = None;
3127        d.bundle_id = Some("com.example.tool".into());
3128        cases.push(d.clone());
3129        d.bundle_id = None;
3130        d.cgroup = Some("/system.slice/xyz.service".into());
3131        cases.push(d);
3132        for p in &cases {
3133            let a = r.match_root(p).map(|m| m.index);
3134            let b = r.match_root_naive(p).map(|m| m.index);
3135            assert_eq!(a, b, "{:?}", p.cmdline);
3136        }
3137        assert_eq!(
3138            r.match_root(&cases[3]).map(|m| m.index),
3139            Some(4),
3140            "priority 5 script rule wins"
3141        );
3142        assert_eq!(r.match_root(&cases[7]), None, "excluded .app");
3143        assert_eq!(r.match_root(&cases[11]).map(|m| m.rule.label.as_str()), Some("D"));
3144    }
3145
3146    #[test]
3147    fn shells_and_terminals() {
3148        let mut p = proc(1, 0, "zsh", "/bin/zsh", 0);
3149        assert!(is_interactive_shell(&p));
3150        p.cmdline = vec!["-zsh".into()];
3151        p.name = "-zsh".into();
3152        assert!(is_interactive_shell(&p));
3153        p.cmdline = vec!["/bin/zsh".into(), "-c".into(), "ls".into()];
3154        assert!(!is_interactive_shell(&p));
3155        p.cmdline = vec!["bash".into(), "-lc".into(), "ls".into()];
3156        assert!(!is_interactive_shell(&p));
3157        p.cmdline = vec!["bash".into(), "start.sh".into()];
3158        assert!(!is_interactive_shell(&p));
3159        let t = proc(2, 1, "iTerm2", "/Applications/iTerm.app/Contents/MacOS/iTerm2", 0);
3160        assert!(is_terminal(&t));
3161        let w = proc(3, 1, "stable", "/Applications/Warp.app/Contents/MacOS/stable", 0);
3162        assert!(is_terminal(&w));
3163        let c = proc(
3164            4,
3165            1,
3166            "Google Chrome",
3167            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
3168            0,
3169        );
3170        assert!(!is_terminal(&c));
3171    }
3172
3173    #[test]
3174    fn another_users_app_is_its_own_group() {
3175        // Fast user switching: a second logged-in user runs Chrome too (seen on the M5 Air).
3176        let exe = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
3177        let mine = proc(10, 1, "Google Chrome", exe, 100);
3178        let mut theirs = proc(20, 1, "Google Chrome", exe, 100);
3179        theirs.uid = Some(502);
3180        let s = Snapshot {
3181            processes: vec![mine, theirs],
3182            ..Default::default()
3183        };
3184        let r = rules();
3185        let protect = ProtectContext {
3186            self_uid: Some(501),
3187            ..Default::default()
3188        };
3189        let groups = attribute(
3190            &s,
3191            &AttributionContext {
3192                rules: &r,
3193                lineage: &BTreeMap::new(),
3194                protect: &protect,
3195            },
3196        );
3197        let ids: Vec<&str> = groups.iter().map(|g| g.id.as_str()).collect();
3198        assert!(ids.contains(&"app:google-chrome"), "{ids:?}");
3199        assert!(ids.contains(&"app:google-chrome@u502"), "{ids:?}");
3200        let mine = groups.iter().find(|g| g.id == "app:google-chrome").unwrap();
3201        assert!(!mine.protected, "our own Chrome stays actionable");
3202        // Without a known self uid (pure tests, fixtures) keys are unchanged.
3203        let groups = run(&s, &BTreeMap::new());
3204        assert_eq!(groups.len(), 1);
3205    }
3206
3207    #[test]
3208    fn chrome_code_sign_clone_is_still_the_app() {
3209        // Chrome's updater runs the browser from a temporary `.app.bundle` copy (seen on the M5 Air).
3210        let mut c = proc(
3211            5,
3212            1,
3213            "Google Chrome",
3214            "/private/var/folders/xx/X/com.google.Chrome.code_sign_clone/code_sign_clone.AbCd/Google Chrome.app.bundle/Contents/MacOS/Google Chrome",
3215            0,
3216        );
3217        assert_eq!(app_bundle_name(&c), Some("Google Chrome"));
3218        assert!(is_app_main(&c));
3219        assert_eq!(heuristic_kind_label(&c).0, GroupKind::App);
3220        // Unknown exe, argv[0] still names the bundle.
3221        c.exe = String::new();
3222        c.cmdline = vec!["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into()];
3223        assert_eq!(app_bundle_name(&c), Some("Google Chrome"));
3224    }
3225}