Skip to main content

ljos_cli/
proc_tree.rs

1//! Processes above this one, each named by its pid and its start time, so
2//! a pid the kernel has since handed to another process is not taken for
3//! the one that was recorded. Read from `/proc` on Linux and `libproc` and
4//! `sysctl` on macOS; elsewhere every list is empty and nothing is alive.
5
6use std::path::{Path, PathBuf};
7
8/// One process: its pid, when it started (clock ticks after boot), and its
9/// name at the time it was read.
10#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
11pub struct Proc {
12    pub pid: u32,
13    pub start: u64,
14    #[serde(default, skip_serializing_if = "String::is_empty")]
15    pub comm: String,
16}
17
18impl Proc {
19    /// The same process: the name may change at exec, the start does not.
20    #[must_use]
21    pub fn same(&self, other: &Self) -> bool {
22        self.pid == other.pid && self.start == other.start
23    }
24}
25
26/// How far up a chain is read.
27const DEPTH: usize = 32;
28
29struct Stat {
30    comm: String,
31    dead: bool,
32    ppid: u32,
33    start: u64,
34}
35
36#[cfg(target_os = "linux")]
37fn stat(pid: u32) -> Option<Stat> {
38    let raw = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
39    let open = raw.find('(')?;
40    let close = raw.rfind(')')?;
41    let comm = raw.get(open + 1..close)?.to_string();
42    // After the name: state, ppid, ... and starttime, field 22 of stat(5).
43    let rest: Vec<&str> = raw.get(close + 1..)?.split_whitespace().collect();
44    Some(Stat {
45        comm,
46        dead: matches!(*rest.first()?, "Z" | "X" | "x"),
47        ppid: rest.get(1)?.parse().ok()?,
48        start: rest.get(19)?.parse().ok()?,
49    })
50}
51
52#[cfg(target_os = "macos")]
53fn stat(pid: u32) -> Option<Stat> {
54    let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
55    let size = libc::c_int::try_from(std::mem::size_of::<libc::proc_bsdinfo>()).ok()?;
56    // SAFETY: the buffer is a zeroed proc_bsdinfo of the size passed.
57    let n = unsafe {
58        libc::proc_pidinfo(
59            libc::c_int::try_from(pid).ok()?,
60            libc::PROC_PIDTBSDINFO,
61            0,
62            std::ptr::addr_of_mut!(info).cast(),
63            size,
64        )
65    };
66    if n != size {
67        return None;
68    }
69    let comm: Vec<u8> = info
70        .pbi_comm
71        .iter()
72        .take_while(|c| **c != 0)
73        .map(|c| c.to_ne_bytes()[0])
74        .collect();
75    let start = info
76        .pbi_start_tvsec
77        .saturating_mul(1_000_000)
78        .saturating_add(info.pbi_start_tvusec);
79    Some(Stat {
80        comm: String::from_utf8_lossy(&comm).into_owned(),
81        dead: info.pbi_status == libc::SZOMB,
82        ppid: info.pbi_ppid,
83        start,
84    })
85}
86
87#[cfg(not(any(target_os = "linux", target_os = "macos")))]
88fn stat(_pid: u32) -> Option<Stat> {
89    None
90}
91
92/// The process `pid` names now.
93#[must_use]
94pub fn of(pid: u32) -> Option<Proc> {
95    stat(pid).map(|s| Proc {
96        pid,
97        start: s.start,
98        comm: s.comm,
99    })
100}
101
102/// The processes above `pid`, nearest first, up to and including pid 1:
103/// in a container that may be the harness itself.
104#[must_use]
105pub fn above(pid: u32) -> Vec<Proc> {
106    let mut out = Vec::new();
107    let mut next = stat(pid).map(|s| s.ppid);
108    while let Some(p) = next.filter(|&p| p > 0 && out.len() < DEPTH) {
109        let Some(s) = stat(p) else {
110            break;
111        };
112        next = Some(s.ppid);
113        out.push(Proc {
114            pid: p,
115            start: s.start,
116            comm: s.comm,
117        });
118    }
119    out
120}
121
122/// The processes above this one, nearest first.
123#[must_use]
124pub fn ancestors() -> Vec<Proc> {
125    above(std::process::id())
126}
127
128/// `pid`'s parent and its own name.
129fn parent_and_name(pid: u32) -> Option<(u32, String)> {
130    stat(pid).map(|s| (s.ppid, s.comm))
131}
132
133fn split_environ(raw: &[u8]) -> Vec<(String, String)> {
134    raw.split(|b| *b == 0)
135        .filter_map(|kv| {
136            let kv = String::from_utf8_lossy(kv);
137            let (k, v) = kv.split_once('=')?;
138            Some((k.to_string(), v.to_string()))
139        })
140        .collect()
141}
142
143/// The environment `pid` was started with. A program it runs can set its
144/// own variables, but cannot change what its parent was started with.
145#[cfg(target_os = "linux")]
146#[must_use]
147pub fn environ(pid: u32) -> Option<Vec<(String, String)>> {
148    std::fs::read(format!("/proc/{pid}/environ"))
149        .ok()
150        .map(|raw| split_environ(&raw))
151}
152
153#[cfg(target_os = "macos")]
154fn procargs2_buf(pid: u32) -> Option<Vec<u8>> {
155    let mut mib = [
156        libc::CTL_KERN,
157        libc::KERN_PROCARGS2,
158        libc::c_int::try_from(pid).ok()?,
159    ];
160    let mut size: libc::size_t = 0;
161    // SAFETY: a null buffer asks sysctl for the size alone.
162    let asked = unsafe {
163        libc::sysctl(
164            mib.as_mut_ptr(),
165            3,
166            std::ptr::null_mut(),
167            &mut size,
168            std::ptr::null_mut(),
169            0,
170        )
171    };
172    if asked != 0 || size < 4 {
173        return None;
174    }
175    let mut buf = vec![0u8; size];
176    // SAFETY: buf holds the size sysctl reported.
177    let read = unsafe {
178        libc::sysctl(
179            mib.as_mut_ptr(),
180            3,
181            buf.as_mut_ptr().cast(),
182            &mut size,
183            std::ptr::null_mut(),
184            0,
185        )
186    };
187    if read != 0 {
188        return None;
189    }
190    buf.truncate(size);
191    Some(buf)
192}
193
194#[cfg(target_os = "macos")]
195#[must_use]
196pub fn environ(pid: u32) -> Option<Vec<(String, String)>> {
197    let buf = procargs2_buf(pid)?;
198    // argc, the executable path and its padding, argc words, then the
199    // environment up to an empty string.
200    let argc = usize::try_from(i32::from_ne_bytes(buf.get(..4)?.try_into().ok()?)).ok()?;
201    let mut words = buf[4..]
202        .split(|b| *b == 0)
203        .skip(1)
204        .skip_while(|w| w.is_empty());
205    for _ in 0..argc {
206        words.next()?;
207    }
208    let env: Vec<u8> = words
209        .take_while(|w| !w.is_empty())
210        .flat_map(|w| w.iter().copied().chain([0]))
211        .collect();
212    Some(split_environ(&env))
213}
214
215#[cfg(not(any(target_os = "linux", target_os = "macos")))]
216#[must_use]
217pub fn environ(_pid: u32) -> Option<Vec<(String, String)>> {
218    None
219}
220
221/// The command-line words of `pid`.
222#[cfg(target_os = "linux")]
223#[must_use]
224pub fn argv(pid: u32) -> Option<Vec<String>> {
225    let raw = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
226    let words: Vec<String> = raw
227        .split(|b| *b == 0)
228        .filter(|w| !w.is_empty())
229        .map(|w| String::from_utf8_lossy(w).into_owned())
230        .collect();
231    (!words.is_empty()).then_some(words)
232}
233
234#[cfg(target_os = "macos")]
235#[must_use]
236pub fn argv(pid: u32) -> Option<Vec<String>> {
237    let buf = procargs2_buf(pid)?;
238    let argc = usize::try_from(i32::from_ne_bytes(buf.get(..4)?.try_into().ok()?)).ok()?;
239    if argc == 0 {
240        return None;
241    }
242    let words: Vec<String> = buf[4..]
243        .split(|b| *b == 0)
244        .skip(1)
245        .skip_while(|w| w.is_empty())
246        .take(argc)
247        .filter(|w| !w.is_empty())
248        .map(|w| String::from_utf8_lossy(w).into_owned())
249        .collect();
250    (!words.is_empty()).then_some(words)
251}
252
253#[cfg(not(any(target_os = "linux", target_os = "macos")))]
254#[must_use]
255pub fn argv(_pid: u32) -> Option<Vec<String>> {
256    None
257}
258
259/// The executable path of `pid`.
260#[cfg(target_os = "linux")]
261#[must_use]
262pub fn exe(pid: u32) -> Option<PathBuf> {
263    std::fs::read_link(format!("/proc/{pid}/exe")).ok()
264}
265
266#[cfg(target_os = "macos")]
267#[must_use]
268pub fn exe(pid: u32) -> Option<PathBuf> {
269    use std::os::unix::ffi::OsStrExt as _;
270    let mut buf = [0u8; 4096];
271    // SAFETY: proc_pidpath writes at most `buf.len()` bytes into `buf`.
272    let len = unsafe {
273        libc::proc_pidpath(
274            libc::c_int::try_from(pid).ok()?,
275            buf.as_mut_ptr().cast(),
276            u32::try_from(buf.len()).ok()?,
277        )
278    };
279    let len = usize::try_from(len)
280        .ok()
281        .filter(|&n| n > 0 && n <= buf.len())?;
282    Some(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..len])))
283}
284
285#[cfg(not(any(target_os = "linux", target_os = "macos")))]
286#[must_use]
287pub fn exe(_pid: u32) -> Option<PathBuf> {
288    None
289}
290
291/// The working directory of `pid`.
292#[cfg(target_os = "linux")]
293#[must_use]
294pub fn cwd(pid: u32) -> Option<PathBuf> {
295    std::fs::read_link(format!("/proc/{pid}/cwd")).ok()
296}
297
298#[cfg(target_os = "macos")]
299#[must_use]
300pub fn cwd(pid: u32) -> Option<PathBuf> {
301    use std::os::unix::ffi::OsStrExt as _;
302    let mut info: libc::proc_vnodepathinfo = unsafe { std::mem::zeroed() };
303    let size = libc::c_int::try_from(std::mem::size_of::<libc::proc_vnodepathinfo>()).ok()?;
304    // SAFETY: the buffer is a zeroed proc_vnodepathinfo of the size passed.
305    let n = unsafe {
306        libc::proc_pidinfo(
307            libc::c_int::try_from(pid).ok()?,
308            libc::PROC_PIDVNODEPATHINFO,
309            0,
310            std::ptr::addr_of_mut!(info).cast(),
311            size,
312        )
313    };
314    if n != size {
315        return None;
316    }
317    let bytes: Vec<u8> = info
318        .pvi_cdir
319        .vip_path
320        .iter()
321        .flatten()
322        .take_while(|c| **c != 0)
323        .map(|c| c.to_ne_bytes()[0])
324        .collect();
325    (!bytes.is_empty()).then(|| PathBuf::from(std::ffi::OsStr::from_bytes(&bytes)))
326}
327
328#[cfg(not(any(target_os = "linux", target_os = "macos")))]
329#[must_use]
330pub fn cwd(_pid: u32) -> Option<PathBuf> {
331    None
332}
333
334/// The process the nearest runner on this process's chain started: the
335/// shell it opened for a tool call, or this process when the runner ran
336/// it directly. `None` when the chain reaches the person's session or the
337/// top without a runner.
338#[must_use]
339pub fn started_by_runner() -> Option<u32> {
340    let mut child = std::process::id();
341    for _ in 0..DEPTH {
342        let (ppid, _) = parent_and_name(child)?;
343        if ppid == 0 {
344            return None;
345        }
346        let (_, comm) = parent_and_name(ppid)?;
347        if crate::is_harness_process(ppid, &comm) {
348            return Some(child);
349        }
350        if crate::is_session(&comm) || ppid == 1 {
351            return None;
352        }
353        child = ppid;
354    }
355    None
356}
357
358/// Whether `p` still runs: the same pid with the same start, and not a
359/// zombie waiting to be reaped.
360#[must_use]
361pub fn alive(p: &Proc) -> bool {
362    stat(p.pid).is_some_and(|s| s.start == p.start && !s.dead)
363}
364
365/// This boot, so a process recorded before a reboot or on another machine
366/// never matches one here.
367#[must_use]
368pub fn boot() -> &'static str {
369    static BOOT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
370    BOOT.get_or_init(|| {
371        raw_boot_id()
372            .map(|s| {
373                s.trim()
374                    .chars()
375                    .filter(char::is_ascii_hexdigit)
376                    .take(12)
377                    .collect()
378            })
379            .filter(|s: &String| !s.is_empty())
380            .unwrap_or_else(|| "-".into())
381    })
382}
383
384#[cfg(target_os = "linux")]
385fn raw_boot_id() -> Option<String> {
386    std::fs::read_to_string("/proc/sys/kernel/random/boot_id").ok()
387}
388
389#[cfg(target_os = "macos")]
390fn raw_boot_id() -> Option<String> {
391    let mut buf = [0u8; 64];
392    let mut size = buf.len();
393    // SAFETY: buf holds `size` bytes, and sysctlbyname writes at most `size`.
394    let rc = unsafe {
395        libc::sysctlbyname(
396            c"kern.bootsessionuuid".as_ptr(),
397            buf.as_mut_ptr().cast(),
398            &mut size,
399            std::ptr::null_mut(),
400            0,
401        )
402    };
403    if rc != 0 || size == 0 {
404        return None;
405    }
406    let end = buf[..size].iter().position(|&b| b == 0).unwrap_or(size);
407    String::from_utf8(buf[..end].to_vec()).ok()
408}
409
410#[cfg(not(any(target_os = "linux", target_os = "macos")))]
411fn raw_boot_id() -> Option<String> {
412    None
413}
414
415/// `p` as one word that names it on this machine and boot.
416#[must_use]
417pub fn token(p: &Proc) -> String {
418    format!("{}:{}:{}", boot(), p.pid, p.start)
419}
420
421/// Whether the process a [`token`] names still runs here.
422#[must_use]
423pub fn token_alive(token: &str) -> bool {
424    let mut parts = token.splitn(3, ':');
425    let (Some(at), Some(pid), Some(start)) = (parts.next(), parts.next(), parts.next()) else {
426        return false;
427    };
428    let (Ok(pid), Ok(start)) = (pid.parse(), start.parse()) else {
429        return false;
430    };
431    at == boot()
432        && alive(&Proc {
433            pid,
434            start,
435            comm: String::new(),
436        })
437}
438
439const SHELLS: &[&str] = &[
440    "sh", "bash", "dash", "zsh", "ksh", "mksh", "ash", "yash", "fish", "tcsh", "csh", "busybox",
441];
442
443/// Programs that run a command and stand between it and the shell that
444/// asked for it.
445const WRAPPERS: &[&str] = &[
446    "env", "nice", "nohup", "timeout", "stdbuf", "setsid", "ionice", "chrt", "taskset", "time",
447    "flock", "sudo", "doas", "xargs",
448];
449
450fn is_shell(p: &Proc) -> bool {
451    SHELLS.contains(&p.comm.as_str())
452}
453
454fn is_wrapper(p: &Proc) -> bool {
455    WRAPPERS.contains(&p.comm.as_str())
456}
457
458fn is_harness(p: &Proc) -> bool {
459    crate::is_harness_process(p.pid, &p.comm)
460}
461
462/// The shell that ran the process whose ancestors are `chain`: past any
463/// wrappers, the outermost of the shells nested directly above it, so a
464/// script that starts a fresh `sh -c` per line is still one shell. `None`
465/// when a program other than a shell ran it.
466#[must_use]
467pub fn calling_shell(chain: &[Proc]) -> Option<&Proc> {
468    let mut rest = chain.iter().skip_while(|p| is_wrapper(p));
469    let mut top = rest.next().filter(|p| is_shell(p))?;
470    for p in rest {
471        if is_shell(p) {
472            top = p;
473        } else if !is_wrapper(p) {
474            break;
475        }
476    }
477    Some(top)
478}
479
480/// Where a chain stops being the hook's own: the person's session, a
481/// terminal or the init system ([`crate::is_session`]), or pid 1 unless
482/// it is a harness. Every sitting in that session shares it, and it
483/// outlives each of them.
484fn ends_the_walk(p: &Proc) -> bool {
485    crate::is_session(&p.comm) || (p.pid == 1 && !is_harness(p))
486}
487
488/// The program that ran the process whose ancestors are `chain`, read up
489/// to the session ([`ends_the_walk`]), which is never the program: the
490/// nearest harness ([`crate::is_harness_process`]), so a `uv`, `npx` or
491/// `node` that only started the hook and exits with it does not outrank
492/// the harness above it; else the nearest one that is neither a shell
493/// nor a wrapper, which keeps a harness that runs as plain `node`; else
494/// the outermost of the shells and wrappers below the session. `None`
495/// when the session ran the process itself.
496#[must_use]
497pub fn runner(chain: &[Proc]) -> Option<&Proc> {
498    let own = chain.iter().take_while(|p| !ends_the_walk(p));
499    own.clone()
500        .find(|p| is_harness(p))
501        .or_else(|| own.clone().find(|p| !is_shell(p) && !is_wrapper(p)))
502        .or_else(|| own.last())
503}
504
505/// The runners that spawn `ljos hook`, by the name of the program they
506/// are: `claude-code` is Claude Code's npm package.
507const HOOK_RUNNERS: &[(&str, &str)] = &[
508    ("claude", "claude"),
509    ("claude-code", "claude"),
510    ("codex", "codex"),
511    ("cursor-agent", "cursor-agent"),
512    ("cursor", "cursor"),
513    ("grok", "grok"),
514    ("opencode", "opencode"),
515    ("gemini", "gemini"),
516    ("agy", "agy"),
517    ("antigravity", "agy"),
518];
519
520/// Runtimes a runner may ship as: the program is the directory or script
521/// above them.
522const RUNTIMES: &[&str] = &["node", "nodejs", "bun", "deno"];
523
524/// The stem of a path component, so `cli.js` is the entry `cli`.
525fn component_stem(component: &str) -> &str {
526    component
527        .strip_suffix(".js")
528        .or_else(|| component.strip_suffix(".mjs"))
529        .or_else(|| component.strip_suffix(".cjs"))
530        .unwrap_or(component)
531}
532
533/// A path component that names where a runner is packed, not the runner.
534fn layout_component(component: &str) -> bool {
535    let name = component_stem(component);
536    crate::version_like(name)
537        || crate::PLACES.contains(&name)
538        || crate::ENTRY_STEMS.contains(&name)
539        || RUNTIMES.contains(&name)
540        || matches!(name, "vendor" | "share")
541        || name.starts_with('@')
542        || name.contains("unknown-linux")
543        || matches!(name, "x86_64" | "aarch64" | "arm64")
544        || name.starts_with("armv")
545}
546
547/// The runner a component names, after an architecture suffix is dropped.
548fn hook_name(component: &str) -> Option<&'static str> {
549    let name = component_stem(component);
550    let name = name.split_once("-x86_64").map_or(name, |(head, _)| head);
551    let name = name.split_once("-aarch64").map_or(name, |(head, _)| head);
552    HOOK_RUNNERS
553        .iter()
554        .find(|(n, _)| *n == name)
555        .map(|(_, runner)| *runner)
556}
557
558/// The home this user's passwd entry names. A tool call sets `HOME` for
559/// whatever it starts, but cannot change this.
560#[must_use]
561pub fn own_home() -> Option<std::path::PathBuf> {
562    use std::os::unix::ffi::OsStrExt as _;
563    let mut buf = vec![0u8; 1024];
564    loop {
565        // SAFETY: passwd is plain data, so all zeroes is a valid value.
566        let mut entry: libc::passwd = unsafe { std::mem::zeroed() };
567        let mut found: *mut libc::passwd = std::ptr::null_mut();
568        // SAFETY: getpwuid_r writes at most buf.len() bytes into buf and
569        // points entry's fields into it; buf outlives every read below.
570        let rc = unsafe {
571            libc::getpwuid_r(
572                libc::getuid(),
573                &mut entry,
574                buf.as_mut_ptr().cast(),
575                buf.len(),
576                &mut found,
577            )
578        };
579        if rc == libc::ERANGE && buf.len() < 1 << 20 {
580            buf.resize(buf.len() * 2, 0);
581            continue;
582        }
583        if rc != 0 || found.is_null() || entry.pw_dir.is_null() {
584            return None;
585        }
586        // SAFETY: pw_dir is a NUL-terminated string inside buf.
587        let dir = unsafe { std::ffi::CStr::from_ptr(entry.pw_dir) };
588        let home = std::path::PathBuf::from(std::ffi::OsStr::from_bytes(dir.to_bytes()));
589        return home.is_absolute().then_some(home);
590    }
591}
592
593/// Where a runner is installed under the person's home ([`own_home`]):
594/// a user `bin`, and the prefix npm's own guide gives a user for global
595/// packages. These are trusted because the person owns them, which
596/// also lets any process of the person's uid, a tool call among them,
597/// replace what they hold: the check keeps out other users and copies
598/// placed elsewhere, not the person's own account.
599const HOME_ROOTS: &[&str] = &[".local/bin", ".cargo/bin", ".npm-global"];
600
601/// Where a runner is installed for every user, and where npm keeps a
602/// global package.
603const SYSTEM_ROOTS: &[&str] = &[
604    "/usr/bin",
605    "/bin",
606    "/usr/local/bin",
607    "/opt/homebrew/bin",
608    "/usr/lib/node_modules",
609    "/usr/local/lib/node_modules",
610    "/opt/homebrew/lib/node_modules",
611];
612
613/// The directories a runner is installed below, for a person whose
614/// passwd home is `home`: the roots above, and an app directory of a
615/// runner's name under `~/.local/share` or `/usr/share`, where a native
616/// installer keeps the versions `~/.local/bin` links to.
617fn install_roots(home: Option<&Path>) -> Vec<PathBuf> {
618    let mut roots: Vec<PathBuf> = SYSTEM_ROOTS.iter().map(PathBuf::from).collect();
619    let mut shares = vec![PathBuf::from("/usr/share")];
620    if let Some(home) = home {
621        roots.extend(HOME_ROOTS.iter().map(|root| home.join(root)));
622        shares.push(home.join(".local/share"));
623    }
624    for share in shares {
625        roots.extend(HOOK_RUNNERS.iter().map(|(name, _)| share.join(name)));
626    }
627    roots
628}
629
630/// Where Nix keeps what it builds.
631const NIX_STORE: &str = "/nix/store";
632
633/// The `STORE/HASH-NAME` entry `path` sits in, STORE being Nix's store
634/// ([`NIX_STORE`]) and HASH 32 characters of Nix's base 32.
635fn nix_entry(path: &Path, store: &Path) -> Option<PathBuf> {
636    let name = path.strip_prefix(store).ok()?.iter().next()?.to_str()?;
637    let (hash, rest) = name.split_at_checked(32)?;
638    let hashed = hash
639        .chars()
640        .all(|c| "0123456789abcdfghijklmnpqrsvwxyz".contains(c));
641    (hashed && rest.len() > 1 && rest.starts_with('-')).then(|| store.join(name))
642}
643
644/// The runner `path` names when it sits below a root ([`root_below`]),
645/// and that root: the nearest component that is not packing layout
646/// ([`layout_component`]), read from the file up to the root's own name,
647/// so `share/claude/versions/2.1.3` is Claude Code.
648fn runner_below(path: &Path, roots: &[PathBuf], store: &Path) -> Option<(&'static str, PathBuf)> {
649    let root = root_below(path, roots, store)?;
650    let parts = root
651        .file_name()
652        .into_iter()
653        .chain(path.strip_prefix(&root).ok()?.iter())
654        .map(std::ffi::OsStr::to_str)
655        .collect::<Option<Vec<_>>>()?;
656    let name = parts.iter().rev().find(|part| !layout_component(part))?;
657    Some((hook_name(name)?, root))
658}
659
660/// The one of `roots`, or the entry of the Nix store `store`, that
661/// `path` sits strictly below. The path must be absolute and plain,
662/// since a `..` after the root would leave it. A path the kernel marks
663/// ` (deleted)` is not the file that was installed.
664fn root_below(path: &Path, roots: &[PathBuf], store: &Path) -> Option<PathBuf> {
665    let plain = path.is_absolute()
666        && path.components().all(|c| {
667            matches!(
668                c,
669                std::path::Component::RootDir | std::path::Component::Normal(_)
670            )
671        });
672    if !plain || path.to_str()?.contains(" (deleted)") {
673        return None;
674    }
675    roots
676        .iter()
677        .cloned()
678        .chain(nix_entry(path, store))
679        .find(|root| path != root.as_path() && path.starts_with(root))
680}
681
682/// A group as the group database lists it.
683struct GroupEntry {
684    name: std::ffi::OsString,
685    members: Vec<std::ffi::OsString>,
686}
687
688/// The account lookups [`group_is_private`] makes. `None` is a lookup
689/// that failed or that cannot be shown to be complete, which is never
690/// read as an empty answer.
691trait Accounts {
692    fn user_name(&self, uid: u32) -> Option<std::ffi::OsString>;
693    fn group(&self, gid: u32) -> Option<GroupEntry>;
694    /// The uid of every passwd entry whose primary group is `gid`.
695    fn primary_members(&self, gid: u32) -> Option<Vec<u32>>;
696}
697
698/// The passwd and group databases: a user's name through the C
699/// library, and a group and the accounts in it from `/etc/group` and
700/// `/etc/passwd` themselves ([`group_in_files`], [`primary_in_files`]),
701/// since a lookup by gid returns only the first line and enumerating
702/// NSS can stop short.
703struct SystemAccounts;
704
705/// Runs a `get*_r` lookup with a buffer that grows while it is too small.
706fn with_buf<T>(mut lookup: impl FnMut(&mut [u8]) -> Result<Option<T>, i32>) -> Option<T> {
707    let mut buf = vec![0u8; 1024];
708    loop {
709        match lookup(&mut buf) {
710            Err(libc::ERANGE) if buf.len() < 1 << 20 => buf.resize(buf.len() * 2, 0),
711            Ok(found) => return found,
712            Err(_) => return None,
713        }
714    }
715}
716
717/// # Safety
718/// `ptr` is a NUL-terminated string.
719unsafe fn os_string(ptr: *const libc::c_char) -> std::ffi::OsString {
720    use std::os::unix::ffi::OsStrExt as _;
721    // SAFETY: the caller's contract.
722    let bytes = unsafe { std::ffi::CStr::from_ptr(ptr) }.to_bytes();
723    std::ffi::OsStr::from_bytes(bytes).to_os_string()
724}
725
726impl Accounts for SystemAccounts {
727    fn user_name(&self, uid: u32) -> Option<std::ffi::OsString> {
728        with_buf(|buf| {
729            // SAFETY: passwd is plain data, so all zeroes is a valid value.
730            let mut entry: libc::passwd = unsafe { std::mem::zeroed() };
731            let mut found: *mut libc::passwd = std::ptr::null_mut();
732            // SAFETY: getpwuid_r writes at most buf.len() bytes into buf
733            // and points entry's fields into it.
734            let rc = unsafe {
735                libc::getpwuid_r(
736                    uid,
737                    &mut entry,
738                    buf.as_mut_ptr().cast(),
739                    buf.len(),
740                    &mut found,
741                )
742            };
743            if rc != 0 {
744                return Err(rc);
745            }
746            // SAFETY: a found entry's pw_name is a string inside buf.
747            Ok((!found.is_null() && !entry.pw_name.is_null())
748                .then(|| unsafe { os_string(entry.pw_name) }))
749        })
750    }
751
752    fn group(&self, gid: u32) -> Option<GroupEntry> {
753        group_in_files(Path::new(ETC), gid)
754    }
755
756    fn primary_members(&self, gid: u32) -> Option<Vec<u32>> {
757        primary_in_files(Path::new(ETC), gid)
758    }
759}
760
761/// Where the account files and `nsswitch.conf` are.
762const ETC: &str = "/etc";
763
764/// Whether `etc/nsswitch.conf` sends database `db` to `files` and
765/// nothing else, so the file under `etc` is all of it. A missing
766/// file, a missing or repeated line, or any other source, such as
767/// `systemd`, `sss`, `ldap` or `compat`, may add accounts that file
768/// does not list.
769fn files_only(etc: &Path, db: &str) -> bool {
770    let Ok(conf) = std::fs::read_to_string(etc.join("nsswitch.conf")) else {
771        return false;
772    };
773    let mut lines = conf
774        .lines()
775        .map(|line| line.split('#').next().unwrap_or_default())
776        .filter_map(|line| line.split_once(':'))
777        .filter(|(name, _)| name.trim() == db);
778    let (Some((_, sources)), None) = (lines.next(), lines.next()) else {
779        return false;
780    };
781    sources.split_whitespace().eq(["files"])
782}
783
784/// The one line of `etc/group` for `gid`, read only when group is
785/// that file alone ([`files_only`]). `None` when no line or more than
786/// one has that gid, since a lookup returns only the first and the
787/// members of the others still hold the group, and when the file
788/// cannot be read whole, as for `passwd` ([`primary_in_files`]).
789fn group_in_files(etc: &Path, gid: u32) -> Option<GroupEntry> {
790    if !files_only(etc, "group") {
791        return None;
792    }
793    let text = std::fs::read_to_string(etc.join("group")).ok()?;
794    let mut found = None;
795    for line in text.lines() {
796        if line.is_empty() || line.starts_with('#') {
797            continue;
798        }
799        if line.starts_with(['+', '-']) {
800            return None;
801        }
802        let fields: Vec<&str> = line.split(':').collect();
803        let [name, _, id, members] = fields[..] else {
804            return None;
805        };
806        if id.parse::<u32>().ok()? != gid {
807            continue;
808        }
809        if found.is_some() {
810            return None;
811        }
812        found = Some(GroupEntry {
813            name: name.into(),
814            members: members
815                .split(',')
816                .filter(|m| !m.is_empty())
817                .map(Into::into)
818                .collect(),
819        });
820    }
821    found
822}
823
824/// The uid of every line of `etc/passwd` whose primary group is `gid`,
825/// read only when passwd is that file alone ([`files_only`]). `None`
826/// when the file cannot be read whole: a line that is not seven fields
827/// with numeric ids, or a `+` or `-` line, which names accounts kept
828/// elsewhere.
829fn primary_in_files(etc: &Path, gid: u32) -> Option<Vec<u32>> {
830    if !files_only(etc, "passwd") {
831        return None;
832    }
833    let text = std::fs::read_to_string(etc.join("passwd")).ok()?;
834    let mut uids = Vec::new();
835    for line in text.lines() {
836        if line.is_empty() || line.starts_with('#') {
837            continue;
838        }
839        if line.starts_with(['+', '-']) {
840            return None;
841        }
842        let fields: Vec<&str> = line.split(':').collect();
843        let [_, _, uid, primary, _, _, _] = fields[..] else {
844            return None;
845        };
846        let (uid, primary) = (uid.parse::<u32>().ok()?, primary.parse::<u32>().ok()?);
847        if primary == gid {
848            uids.push(uid);
849        }
850    }
851    Some(uids)
852}
853
854/// Whether group `gid` holds no one but user `uid`: it bears the user's
855/// name, lists no other member, and is no other account's primary group.
856fn group_is_private(accounts: &dyn Accounts, uid: u32, gid: u32) -> bool {
857    let (Some(user), Some(group), Some(primary)) = (
858        accounts.user_name(uid),
859        accounts.group(gid),
860        accounts.primary_members(gid),
861    ) else {
862        return false;
863    };
864    group.name == user
865        && group.members.iter().all(|member| *member == user)
866        && primary.iter().all(|other| *other == uid)
867}
868
869/// Who [`person_keeps`] judges a file for: this process's user,
870/// primary group and supplementary groups (`None` when they could not
871/// be read), and whether the primary group is the user's alone, asked
872/// only when a file is group-writable.
873struct Person<'a> {
874    uid: u32,
875    gid: u32,
876    groups: Option<Vec<u32>>,
877    accounts: &'a dyn Accounts,
878    private_group: std::cell::OnceCell<bool>,
879}
880
881impl<'a> Person<'a> {
882    fn new(accounts: &'a dyn Accounts) -> Self {
883        // SAFETY: getuid and getgid take no arguments and only read the
884        // process identity.
885        let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
886        Person {
887            uid,
888            gid,
889            groups: supplementary_groups(),
890            accounts,
891            private_group: std::cell::OnceCell::new(),
892        }
893    }
894
895    /// Whether the person writes what group `gid` may write. Groups that
896    /// could not be read count as every group.
897    fn in_group(&self, gid: u32) -> bool {
898        gid == self.gid
899            || self
900                .groups
901                .as_ref()
902                .is_none_or(|groups| groups.contains(&gid))
903    }
904
905    fn private_group(&self) -> bool {
906        *self
907            .private_group
908            .get_or_init(|| group_is_private(self.accounts, self.uid, self.gid))
909    }
910}
911
912/// This process's supplementary groups.
913fn supplementary_groups() -> Option<Vec<u32>> {
914    // SAFETY: a size of zero asks only for the count and writes nothing.
915    let count = unsafe { libc::getgroups(0, std::ptr::null_mut()) };
916    let mut groups = vec![0; usize::try_from(count).ok()?];
917    // SAFETY: getgroups writes at most `count` ids into groups.
918    let got = unsafe { libc::getgroups(count, groups.as_mut_ptr()) };
919    groups.truncate(usize::try_from(got).ok()?);
920    Some(groups)
921}
922
923/// A file's owner, group and mode.
924#[derive(Clone, Copy)]
925struct Owner {
926    uid: u32,
927    gid: u32,
928    mode: u32,
929}
930
931impl From<&std::fs::Metadata> for Owner {
932    fn from(meta: &std::fs::Metadata) -> Self {
933        use std::os::unix::fs::MetadataExt as _;
934        Owner {
935            uid: meta.uid(),
936            gid: meta.gid(),
937            mode: meta.mode(),
938        }
939    }
940}
941
942/// The owner of `/` and of each directory below it down to `file`, and
943/// of `file`, each read from a descriptor opened beneath the one before
944/// without following a link, so a directory swapped for a link after
945/// `file` was resolved is not walked through. One swapped for another
946/// directory leads to another file than `expect`, the (device, inode)
947/// the caller holds for `file`. `None` unless every component above
948/// `file` is a directory and the file the walk ends on is a regular
949/// file that is `expect`.
950fn pinned_walk(file: &Path, expect: (u64, u64)) -> Option<Vec<Owner>> {
951    use std::os::fd::{AsRawFd as _, FromRawFd as _};
952    use std::os::unix::ffi::OsStrExt as _;
953    use std::os::unix::fs::MetadataExt as _;
954    #[cfg(target_os = "linux")]
955    let flags = libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC;
956    #[cfg(not(target_os = "linux"))]
957    let flags = libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
958    let open = |dir: libc::c_int, name: &std::ffi::CStr| {
959        // SAFETY: name is NUL-terminated, and openat only reads it.
960        let fd = unsafe { libc::openat(dir, name.as_ptr(), flags) };
961        // SAFETY: a descriptor openat returned is open and owned here.
962        (fd >= 0).then(|| std::fs::File::from(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) }))
963    };
964    let mut parts = file.components();
965    if parts.next() != Some(std::path::Component::RootDir) {
966        return None;
967    }
968    let mut at = open(libc::AT_FDCWD, c"/")?;
969    let mut meta = at.metadata().ok()?;
970    let mut owners = vec![Owner::from(&meta)];
971    for part in parts {
972        let std::path::Component::Normal(name) = part else {
973            return None;
974        };
975        if !meta.is_dir() {
976            return None;
977        }
978        at = open(
979            at.as_raw_fd(),
980            &std::ffi::CString::new(name.as_bytes()).ok()?,
981        )?;
982        meta = at.metadata().ok()?;
983        owners.push(Owner::from(&meta));
984    }
985    (meta.is_file() && expect == (meta.dev(), meta.ino())).then_some(owners)
986}
987
988/// Whether a Nix store and an entry in it are as Nix leaves them, so
989/// that only Nix can change what the entry holds. The store is root's,
990/// the person cannot write it, and it is sticky if its group or anyone
991/// may write it; the entry is then root's, as the daemon builds it. On
992/// a single-user install the store is the person's and no one else may
993/// write it, and the entry is the person's or root's. Such a store, like
994/// a home root ([`HOME_ROOTS`]), is writable by a tool call of the
995/// person's uid, and is trusted only because the person owns it.
996fn store_keeps(store: Owner, entry: Owner, person: &Person) -> bool {
997    let group = store.mode & 0o020 != 0;
998    let anyone = store.mode & 0o002 != 0;
999    if store.uid == 0 {
1000        let person_writes = anyone
1001            || (group && person.in_group(store.gid))
1002            || (person.uid == 0 && store.mode & 0o200 != 0);
1003        !person_writes && (!group || store.mode & 0o1000 != 0) && entry.uid == 0
1004    } else {
1005        store.uid == person.uid && !group && !anyone && (entry.uid == 0 || entry.uid == person.uid)
1006    }
1007}
1008
1009/// Whether root or `person` owns a file, and no one else can write it
1010/// but `person`'s primary group when that group is theirs alone.
1011fn person_keeps(file: Owner, person: &Person) -> bool {
1012    (file.uid == 0 || file.uid == person.uid)
1013        && file.mode & 0o002 == 0
1014        && (file.mode & 0o020 == 0 || (file.gid == person.gid && person.private_group()))
1015}
1016
1017/// The runner a program file is, when the file is an installed copy for
1018/// the person whose passwd home is `home` ([`runner_below`]).
1019/// `~/.local/share/claude/versions/2.1.3` is Claude Code, and so is
1020/// `/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js`. A bundled
1021/// runtime (`cursor-agent/versions/V/node`) is the runner it ships in.
1022/// The file and the roots are compared as the kernel resolves them, so a
1023/// link from `~/.local/bin` into `/tmp` is read in `/tmp`. A copy whose
1024/// name is the runner, in a temp directory, a project tree or a `.local`
1025/// of its own making, is not: the name alone is what a tool call can
1026/// choose. Nor is a file that someone other than the person could have
1027/// written, or swapped through a directory between it and its root, or
1028/// an entry of a Nix store `store` that Nix does not keep
1029/// ([`store_keeps`]). The directories and the file are judged as they
1030/// were opened ([`pinned_walk`]) from `path` resolved once, and the
1031/// file the walk ends on must be `expect`, the (device, inode) the
1032/// caller holds for the file it means.
1033fn runner_of_file(
1034    path: &Path,
1035    home: Option<&Path>,
1036    store: &Path,
1037    person: &Person,
1038    expect: (u64, u64),
1039) -> Option<&'static str> {
1040    runner_at(
1041        &std::fs::canonicalize(path).ok()?,
1042        home,
1043        store,
1044        person,
1045        expect,
1046    )
1047}
1048
1049/// [`runner_of_file`] for `file`, a path already resolved.
1050fn runner_at(
1051    file: &Path,
1052    home: Option<&Path>,
1053    store: &Path,
1054    person: &Person,
1055    expect: (u64, u64),
1056) -> Option<&'static str> {
1057    let (roots, store) = resolved_roots(home, store);
1058    let (runner, root) = runner_below(file, &roots, &store)?;
1059    kept_below(file, &root, &store, person, expect).then_some(runner)
1060}
1061
1062/// Whether `path` is a runtime ([`RUNTIMES`]) by its exact name, and
1063/// an installed copy kept as a runner file is ([`runner_of_file`]):
1064/// below an install root, left to the person, and the file `expect`.
1065fn runtime_of_file(
1066    path: &Path,
1067    home: Option<&Path>,
1068    store: &Path,
1069    person: &Person,
1070    expect: (u64, u64),
1071) -> bool {
1072    let Ok(file) = std::fs::canonicalize(path) else {
1073        return false;
1074    };
1075    let named = file
1076        .file_name()
1077        .and_then(std::ffi::OsStr::to_str)
1078        .is_some_and(|name| RUNTIMES.contains(&name));
1079    let (roots, store) = resolved_roots(home, store);
1080    named
1081        && root_below(&file, &roots, &store)
1082            .is_some_and(|root| kept_below(&file, &root, &store, person, expect))
1083}
1084
1085/// The install roots for `home` ([`install_roots`]) and the Nix store
1086/// `store`, resolved.
1087fn resolved_roots(home: Option<&Path>, store: &Path) -> (Vec<PathBuf>, PathBuf) {
1088    let roots = install_roots(home)
1089        .iter()
1090        .filter_map(|root| std::fs::canonicalize(root).ok())
1091        .collect();
1092    let store = std::fs::canonicalize(store).unwrap_or_else(|_| store.to_path_buf());
1093    (roots, store)
1094}
1095
1096/// Whether `file`, a resolved path below install root `root`, is the
1097/// file `expect` and left to the person ([`walk_kept`]) as the walk
1098/// reads it ([`pinned_walk`]). A file in a temp directory never is.
1099fn kept_below(file: &Path, root: &Path, store: &Path, person: &Person, expect: (u64, u64)) -> bool {
1100    if crate::bookkeep::resolved_path_is_temp(file) {
1101        return false;
1102    }
1103    let (Some(owners), Some(at)) = (
1104        pinned_walk(file, expect),
1105        root.components().count().checked_sub(1),
1106    ) else {
1107        return false;
1108    };
1109    walk_kept(&owners, at, root.parent() == Some(store), person)
1110}
1111
1112/// Whether the owners [`pinned_walk`] read leave a file to the person,
1113/// its install root being at `at`. The directory holding the root, the
1114/// root, and all below it are kept by the person ([`person_keeps`]),
1115/// since whoever may write the root's directory may rename the root.
1116/// For an entry of a Nix store, the store and the entry are as Nix keeps
1117/// them ([`store_keeps`]) instead.
1118fn walk_kept(owners: &[Owner], at: usize, in_store: bool, person: &Person) -> bool {
1119    let (Some(&above), Some(&root)) = (
1120        at.checked_sub(1).and_then(|above| owners.get(above)),
1121        owners.get(at),
1122    ) else {
1123        return false;
1124    };
1125    let top = if in_store {
1126        store_keeps(above, root, person)
1127    } else {
1128        person_keeps(above, person)
1129    };
1130    top && owners[at..].iter().all(|dir| person_keeps(*dir, person))
1131}
1132
1133#[cfg(target_os = "linux")]
1134fn running_exe(pid: u32) -> Option<(PathBuf, Option<(u64, u64)>)> {
1135    use std::os::unix::fs::MetadataExt as _;
1136    let path = format!("/proc/{pid}/exe");
1137    let exe = std::fs::read_link(&path).ok()?;
1138    let running = std::fs::metadata(&path)
1139        .ok()
1140        .map(|meta| (meta.dev(), meta.ino()));
1141    Some((exe, running))
1142}
1143
1144#[cfg(not(target_os = "linux"))]
1145fn running_exe(pid: u32) -> Option<(PathBuf, Option<(u64, u64)>)> {
1146    use std::os::unix::fs::MetadataExt as _;
1147    let exe = exe(pid)?;
1148    let running = std::fs::metadata(&exe)
1149        .ok()
1150        .map(|meta| (meta.dev(), meta.ino()));
1151    Some((exe, running))
1152}
1153
1154/// The runner `pid` is, from the file the kernel runs it from, never
1155/// from the name it gives itself. An installed runtime such as `node`
1156/// ([`runtime_of_file`]) is the runner whose script it runs, that
1157/// script's path resolved on disk and judged as a runner file is. The
1158/// script's path comes from the process's own arguments, so only a
1159/// runtime the person installed is believed about it.
1160#[must_use]
1161pub fn exe_runner(pid: u32) -> Option<&'static str> {
1162    let (exe, running) = running_exe(pid)?;
1163    let script = || {
1164        let words = argv(pid)?;
1165        let script = words
1166            .into_iter()
1167            .skip(1)
1168            .find(|a| !a.is_empty() && !a.starts_with('-'))?;
1169        let cwd = cwd(pid)?;
1170        Some(cwd.join(script))
1171    };
1172    let home = own_home();
1173    let person = Person::new(&SystemAccounts);
1174    runner_from(
1175        &exe,
1176        running,
1177        script,
1178        home.as_deref(),
1179        Path::new(NIX_STORE),
1180        &person,
1181    )
1182}
1183
1184/// [`exe_runner`] for a process run from `exe`, whose (device, inode)
1185/// the kernel reports as `running`, and that names `script` as the
1186/// script a runtime there runs. `None` when `running` could not be
1187/// read, since the path alone may name another file than the one the
1188/// process runs.
1189fn runner_from(
1190    exe: &Path,
1191    running: Option<(u64, u64)>,
1192    script: impl FnOnce() -> Option<PathBuf>,
1193    home: Option<&Path>,
1194    store: &Path,
1195    person: &Person,
1196) -> Option<&'static str> {
1197    use std::os::unix::fs::MetadataExt as _;
1198    let running = running?;
1199    if let Some(r) = runner_of_file(exe, home, store, person, running) {
1200        return Some(r);
1201    }
1202    if !runtime_of_file(exe, home, store, person, running) {
1203        return None;
1204    }
1205    let script = std::fs::canonicalize(script()?).ok()?;
1206    let meta = std::fs::metadata(&script).ok()?;
1207    runner_of_file(&script, home, store, person, (meta.dev(), meta.ino()))
1208}
1209
1210/// Editors and agents. A server whose chain still holds one of these is
1211/// not an orphan. Matched on the file name, without regard to case.
1212const EDITORS: &[&str] = &[
1213    "claude",
1214    "claude-code",
1215    "codex",
1216    "cursor",
1217    "cursor-agent",
1218    "opencode",
1219    "opencode-ai",
1220    "agy",
1221    "antigravity",
1222    "grok",
1223    "gemini",
1224    "copilot",
1225    "qwen",
1226    "droid",
1227    "crush",
1228    "kiro",
1229    "kiro-cli",
1230    "hermes",
1231    "omp",
1232    "cline",
1233    "aider",
1234    "code",
1235    "code-oss",
1236    "codium",
1237    "vscodium",
1238    "zed",
1239    "zed-editor",
1240    "windsurf",
1241    "goland",
1242    "idea",
1243    "pycharm",
1244    "webstorm",
1245    "rustrover",
1246    "sublime_text",
1247    "emacs",
1248    "nvim",
1249    "vim",
1250    "gvim",
1251    "helix",
1252    "lapce",
1253    "kate",
1254    "gedit",
1255    "cursor helper",
1256];
1257
1258/// Whether `name` is an editor or an agent. A path uses its file name.
1259#[must_use]
1260pub fn is_editor_name(name: &str) -> bool {
1261    let base = name.rsplit(['/', '\\']).next().unwrap_or(name).trim();
1262    EDITORS.iter().any(|item| base.eq_ignore_ascii_case(item))
1263}
1264
1265#[cfg(target_os = "linux")]
1266fn command_base(pid: u32) -> Option<String> {
1267    let raw = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
1268    let first = raw.split(|b| *b == 0).find(|word| !word.is_empty())?;
1269    let text = String::from_utf8_lossy(first);
1270    Some(text.rsplit(['/', '\\']).next().unwrap_or(&text).to_string())
1271}
1272
1273#[cfg(target_os = "macos")]
1274fn command_base(pid: u32) -> Option<String> {
1275    let mut mib = [
1276        libc::CTL_KERN,
1277        libc::KERN_PROCARGS2,
1278        libc::c_int::try_from(pid).ok()?,
1279    ];
1280    let mut size: libc::size_t = 0;
1281    // SAFETY: a null buffer asks sysctl for the size alone.
1282    let asked = unsafe {
1283        libc::sysctl(
1284            mib.as_mut_ptr(),
1285            3,
1286            std::ptr::null_mut(),
1287            &mut size,
1288            std::ptr::null_mut(),
1289            0,
1290        )
1291    };
1292    if asked != 0 || size < 4 {
1293        return None;
1294    }
1295    let mut buf = vec![0u8; size];
1296    // SAFETY: buf holds the size sysctl reported.
1297    let read = unsafe {
1298        libc::sysctl(
1299            mib.as_mut_ptr(),
1300            3,
1301            buf.as_mut_ptr().cast(),
1302            &mut size,
1303            std::ptr::null_mut(),
1304            0,
1305        )
1306    };
1307    if read != 0 {
1308        return None;
1309    }
1310    buf.truncate(size);
1311    let argc = usize::try_from(i32::from_ne_bytes(buf.get(..4)?.try_into().ok()?)).ok()?;
1312    if argc == 0 {
1313        return None;
1314    }
1315    let word = buf[4..]
1316        .split(|b| *b == 0)
1317        .skip(1)
1318        .find(|word| !word.is_empty())?;
1319    let text = String::from_utf8_lossy(word);
1320    Some(text.rsplit(['/', '\\']).next().unwrap_or(&text).to_string())
1321}
1322
1323/// Whether an editor or an agent is still above this process. Linux also
1324/// accepts the runner named by the file the process is running, so a
1325/// `node` that is only hosting an editor still counts.
1326#[cfg(target_os = "linux")]
1327#[must_use]
1328pub fn editor_above() -> bool {
1329    ancestors().into_iter().any(|proc| {
1330        is_editor_name(&proc.comm)
1331            || command_base(proc.pid).is_some_and(|name| is_editor_name(&name))
1332            || exe_runner(proc.pid).is_some_and(is_editor_name)
1333    })
1334}
1335
1336#[cfg(target_os = "macos")]
1337#[must_use]
1338pub fn editor_above() -> bool {
1339    // SAFETY: getppid has no preconditions.
1340    let mut pid = unsafe { libc::getppid() } as u32;
1341    for _ in 0..DEPTH {
1342        if pid <= 1 {
1343            return false;
1344        }
1345        let Some((ppid, comm)) = parent_and_name(pid) else {
1346            return false;
1347        };
1348        if is_editor_name(&comm) || command_base(pid).is_some_and(|name| is_editor_name(&name)) {
1349            return true;
1350        }
1351        if ppid == pid {
1352            return false;
1353        }
1354        pid = ppid;
1355    }
1356    false
1357}
1358
1359#[cfg(not(any(target_os = "linux", target_os = "macos")))]
1360#[must_use]
1361pub fn editor_above() -> bool {
1362    false
1363}
1364
1365/// Whether `cmd`, a shell's `-c` line, runs `ljos hook` and nothing else:
1366/// the program (`ljos`, a path to it, or the plugin launcher with `ljos`),
1367/// `hook`, and flags. `${NAME}` and double quotes are the runner's own
1368/// spelling of the launcher; a redirection, pipe or second command,
1369/// which a tool call needs to hand the hook a payload, is not.
1370fn bare_hook_command(cmd: &str) -> bool {
1371    let mut plain = String::new();
1372    let mut rest = cmd;
1373    while let Some(at) = rest.find("${") {
1374        plain.push_str(&rest[..at]);
1375        let Some(close) = rest[at..].find('}') else {
1376            return false;
1377        };
1378        let name = &rest[at + 2..at + close];
1379        if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
1380            return false;
1381        }
1382        plain.push_str("VAR");
1383        rest = &rest[at + close + 1..];
1384    }
1385    plain.push_str(rest);
1386    let plain = plain.replace('"', "");
1387    if plain.contains(|c: char| "<>|;&$`(){}\\'\n\r*?[]~#!".contains(c)) {
1388        return false;
1389    }
1390    let words: Vec<&str> = plain.split_whitespace().collect();
1391    let base = |w: &str| w.rsplit('/').next().unwrap_or(w).to_string();
1392    let at = match words.first().map(|w| base(w)).as_deref() {
1393        Some("ljos-plugin") if words.get(1) == Some(&"ljos") => 2,
1394        Some("ljos") => 1,
1395        _ => return false,
1396    };
1397    words.get(at) == Some(&"hook")
1398        && words[at + 1..].iter().all(|w| {
1399            w.starts_with("--")
1400                || w.chars()
1401                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
1402        })
1403}
1404
1405/// Whether `pid` is the shell a runner opens to run its configured hook
1406/// command: a shell by the file it runs from, started as `SHELL -c CMD`
1407/// with [`bare_hook_command`] for CMD. `dash` forks that command rather
1408/// than replacing itself with it.
1409fn hook_shell(pid: u32) -> bool {
1410    let Some(exe) = exe(pid) else {
1411        return false;
1412    };
1413    let shell = exe
1414        .file_name()
1415        .and_then(|f| f.to_str())
1416        .is_some_and(|f| SHELLS.contains(&f));
1417    let words = argv(pid).unwrap_or_default();
1418    shell && matches!(words.as_slice(), [_, c, cmd] if c == "-c" && bare_hook_command(cmd))
1419}
1420
1421/// The nearest process above this one that is a runner by the file the
1422/// kernel runs it from ([`exe_runner`]), and which runner it is.
1423#[must_use]
1424pub fn runner_above() -> Option<(Proc, &'static str)> {
1425    ancestors()
1426        .into_iter()
1427        .find_map(|p| exe_runner(p.pid).map(|r| (p, r)))
1428}
1429
1430/// Variables a runner gives the shell of a tool call. A runner started
1431/// with one runs inside another runner's tool call.
1432fn tool_call_stamp(env: &[(String, String)]) -> Option<&str> {
1433    env.iter()
1434        .find(|(k, v)| {
1435            matches!(
1436                k.as_str(),
1437                "CLAUDECODE" | "CURSOR_AGENT" | "CODEX_THREAD_ID"
1438            ) || (crate::runner_session_var(k, v) && !k.starts_with("LJOS_"))
1439        })
1440        .map(|(k, _)| k.as_str())
1441}
1442
1443/// One tool call the guard's `PreToolUse` saw: the session and cgroup it
1444/// could not shed, the start time of that hook (a later process is part
1445/// of the call), and the runner that spawned the hook.
1446struct ToolMark {
1447    sid: u32,
1448    at: u64,
1449    runner_pid: u32,
1450    runner_start: u64,
1451    shell_pid: u32,
1452    shell_start: u64,
1453    cgroup: String,
1454}
1455
1456/// The session and cgroup of this process. A child inherits both until
1457/// it calls `setsid` or migrates cgroup.
1458struct Here {
1459    sid: u32,
1460    cgroup: String,
1461}
1462
1463fn marks_path() -> std::path::PathBuf {
1464    crate::runtime_dir().join("tool-calls")
1465}
1466
1467fn broken_path() -> std::path::PathBuf {
1468    crate::runtime_dir().join("tool-calls.broken")
1469}
1470
1471/// The calling process's session id.
1472fn current_sid() -> Result<u32, String> {
1473    // SAFETY: getsid(0) reads the calling process's session id and writes
1474    // nothing the caller owns.
1475    let sid = unsafe { libc::getsid(0) };
1476    if sid < 0 {
1477        return Err(
1478            "the session id cannot be read, so a tool call cannot be told from the runner".into(),
1479        );
1480    }
1481    u32::try_from(sid).map_err(|_| "the session id does not fit".into())
1482}
1483
1484fn here_evidence() -> Result<Here, String> {
1485    let sid = current_sid()?;
1486    #[cfg(target_os = "linux")]
1487    let cgroup = std::fs::read_to_string("/proc/self/cgroup").map_err(|_| {
1488        "the cgroup cannot be read, so a tool call cannot be told from the runner".to_string()
1489    })?;
1490    #[cfg(not(target_os = "linux"))]
1491    let cgroup = format!("sid:{sid}");
1492    if cgroup.is_empty() {
1493        return Err("the cgroup is empty, so a tool call cannot be told from the runner".into());
1494    }
1495    Ok(Here { sid, cgroup })
1496}
1497
1498fn self_start() -> Result<u64, String> {
1499    stat(std::process::id())
1500        .map(|row| row.start)
1501        .ok_or_else(|| "this process's start time cannot be read".into())
1502}
1503
1504/// Remember that a tool-call record could not be written. A later read
1505/// then fails closed: a missing record means no tool call, and a failed
1506/// write must not look like that.
1507/// A tool call may have happened and its evidence could not be taken.
1508/// Later reads fail closed instead of looking like a quiet runtime.
1509pub fn seal_unreadable_tool_call() {
1510    mark_broken();
1511}
1512
1513fn mark_broken() {
1514    let dir = crate::runtime_dir();
1515    let _ = std::fs::create_dir_all(&dir);
1516    let mut options = std::fs::OpenOptions::new();
1517    options.create(true).write(true).truncate(true);
1518    #[cfg(unix)]
1519    {
1520        use std::os::unix::fs::OpenOptionsExt as _;
1521        options.mode(0o600);
1522    }
1523    let _ = options.open(broken_path());
1524}
1525
1526fn tool_marks() -> Result<Vec<ToolMark>, String> {
1527    if broken_path().exists() {
1528        return Err(
1529            "a tool-call record could not be written, so nothing is kept as the person's".into(),
1530        );
1531    }
1532    let text = match std::fs::read_to_string(marks_path()) {
1533        Ok(text) => text,
1534        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1535        Err(_) => {
1536            return Err(
1537                "the tool-call record cannot be read, so nothing is kept as the person's".into(),
1538            );
1539        }
1540    };
1541    let mut marks = Vec::new();
1542    for line in text.lines() {
1543        let fields: Vec<&str> = line.split('\t').collect();
1544        if fields.len() != 8 || fields[0] != "1" {
1545            return Err(
1546                "the tool-call record is corrupt, so nothing is kept as the person's".into(),
1547            );
1548        }
1549        let number = |index: usize, label: &str| -> Result<u64, String> {
1550            fields[index].parse().map_err(|_| {
1551                format!(
1552                    "the tool-call record has a bad {label}, so nothing is kept as the person's"
1553                )
1554            })
1555        };
1556        let cgroup = hex::decode(fields[7])
1557            .ok()
1558            .and_then(|bytes| String::from_utf8(bytes).ok())
1559            .ok_or("the tool-call record has a bad cgroup, so nothing is kept as the person's")?;
1560        let narrow = |value: u64, label: &str| -> Result<u32, String> {
1561            u32::try_from(value).map_err(|_| {
1562                format!(
1563                    "the tool-call record has a bad {label}, so nothing is kept as the person's"
1564                )
1565            })
1566        };
1567        marks.push(ToolMark {
1568            sid: narrow(number(1, "session")?, "session")?,
1569            at: number(2, "start")?,
1570            runner_pid: narrow(number(3, "runner")?, "runner")?,
1571            runner_start: number(4, "runner start")?,
1572            shell_pid: narrow(number(5, "shell")?, "shell")?,
1573            shell_start: number(6, "shell start")?,
1574            cgroup,
1575        });
1576    }
1577    Ok(marks)
1578}
1579
1580/// Record the tool call whose guard hook this is. The runner is `runner`,
1581/// the process that spawned the hook. The hook's own start time is the
1582/// watermark: a process started later, in this session or cgroup, is the
1583/// tool call even after it detaches.
1584///
1585/// # Errors
1586///
1587/// The session, cgroup or start time cannot be read, or the record cannot
1588/// be written. A failed write leaves a sentinel so later reads fail closed.
1589pub fn note_tool_call(runner: &Proc) -> Result<(), String> {
1590    // A tool call whose session, cgroup or start time cannot be read must
1591    // not look like a runtime that has seen no tool call.
1592    let here = match here_evidence() {
1593        Ok(here) => here,
1594        Err(why) => {
1595            mark_broken();
1596            return Err(why);
1597        }
1598    };
1599    let at = match self_start() {
1600        Ok(at) => at,
1601        Err(why) => {
1602            mark_broken();
1603            return Err(why);
1604        }
1605    };
1606    let dir = crate::runtime_dir();
1607    let mut builder = std::fs::DirBuilder::new();
1608    builder.recursive(true);
1609    #[cfg(unix)]
1610    {
1611        use std::os::unix::fs::DirBuilderExt as _;
1612        builder.mode(0o700);
1613    }
1614    if builder.create(&dir).is_err() {
1615        mark_broken();
1616        return Err("the tool-call record directory cannot be created".into());
1617    }
1618    // sid, watermark, runner pid and start, tool shell pid and start
1619    // (unset when the shell does not exist yet), cgroup text as hex.
1620    // One line stays under PIPE_BUF so the append is one write.
1621    let line = format!(
1622        "1\t{}\t{at}\t{}\t{}\t0\t0\t{}\n",
1623        here.sid,
1624        runner.pid,
1625        runner.start,
1626        hex::encode(here.cgroup.as_bytes())
1627    );
1628    if line.len() > 4096 {
1629        mark_broken();
1630        return Err("the tool-call record does not fit one write".into());
1631    }
1632    let mut options = std::fs::OpenOptions::new();
1633    options.create(true).append(true);
1634    #[cfg(unix)]
1635    {
1636        use std::os::unix::fs::OpenOptionsExt as _;
1637        options.mode(0o600);
1638    }
1639    let opened = options.open(marks_path());
1640    let mut file = match opened {
1641        Ok(file) => file,
1642        Err(_) => {
1643            mark_broken();
1644            return Err("the tool-call record cannot be written".into());
1645        }
1646    };
1647    use std::io::Write as _;
1648    if file.write_all(line.as_bytes()).is_err() {
1649        mark_broken();
1650        return Err("the tool-call record cannot be written".into());
1651    }
1652    Ok(())
1653}
1654
1655/// Whether `runner` is the runner a person started, rather than a process
1656/// a recorded tool call still owns. The same runner process that recorded
1657/// a mark is that opener. Any other process that shares the mark's cgroup
1658/// or session and is not older than the mark is the tool call. No marks
1659/// means the person has not made a tool call in this runtime yet.
1660fn confirm_runner(runner: &Proc) -> Result<(), String> {
1661    let here = here_evidence()?;
1662    let marks = tool_marks()?;
1663    let chain = ancestors();
1664    for mark in &marks {
1665        if mark.runner_pid == runner.pid && mark.runner_start == runner.start {
1666            continue;
1667        }
1668        if mark.shell_pid > 0
1669            && chain
1670                .iter()
1671                .any(|proc| proc.pid == mark.shell_pid && proc.start == mark.shell_start)
1672        {
1673            return Err(format!(
1674                "{} (pid {}) descends from a recorded tool call",
1675                runner.comm, runner.pid
1676            ));
1677        }
1678        let same_place = mark.sid == here.sid || mark.cgroup == here.cgroup;
1679        if same_place && runner.start >= mark.at {
1680            return Err(format!(
1681                "{} (pid {}) shares a recorded tool call's cgroup or session and is not older than that tool call",
1682                runner.comm, runner.pid
1683            ));
1684        }
1685    }
1686    Ok(())
1687}
1688
1689/// The installed runner above this process, checked against the tool-call
1690/// record ([`confirm_runner`]). Shells and wrappers are stepped over. The
1691/// first other program that is not an installed runner ends the walk, so
1692/// a copy named like a runner cannot hide behind a real one further up.
1693///
1694/// # Errors
1695///
1696/// No installed runner is above this process, or the one that is still
1697/// belongs to a recorded tool call.
1698pub fn placed_runner() -> Result<(), String> {
1699    for proc in ancestors() {
1700        if is_shell(&proc) || is_wrapper(&proc) {
1701            continue;
1702        }
1703        if ends_the_walk(&proc) {
1704            break;
1705        }
1706        if exe_runner(proc.pid).is_some() {
1707            return confirm_runner(&proc);
1708        }
1709        return Err(format!(
1710            "{} (pid {}) is not an installed runner, so this is not the person's runner",
1711            proc.comm, proc.pid
1712        ));
1713    }
1714    Err("no installed runner is above this process, so this is not the person's runner".into())
1715}
1716
1717/// The runner that spawned this `ljos hook` itself, or why none did: the
1718/// parent must be an installed runner ([`exe_runner`]), with no shell or
1719/// interpreter between them but the `sh -c` the runner runs its hook
1720/// command in ([`hook_shell`]). That runner must not run inside a tool
1721/// call, which a runner above it, a tool call's variables in the
1722/// environment it was started with, or the guard's tool-call record
1723/// ([`confirm_runner`]) would show. Only such a hook's prompt is the
1724/// person's. An environment that cannot be read hides the stamp, so it
1725/// is refused.
1726///
1727/// # Errors
1728///
1729/// Why the parent is not a runner the person started.
1730pub fn hook_runner() -> Result<(Proc, &'static str), String> {
1731    let mut chain = ancestors();
1732    let parent = chain.first().ok_or("it has no parent process")?;
1733    if exe_runner(parent.pid).is_none() && chain.len() > 1 && hook_shell(parent.pid) {
1734        chain.remove(0);
1735    }
1736    let parent = &chain[0];
1737    let Some(runner) = exe_runner(parent.pid) else {
1738        return Err(format!(
1739            "its parent, {} (pid {}), is not a runner's own program: a shell, an interpreter or ssh ran it, so a tool call may have",
1740            parent.comm, parent.pid
1741        ));
1742    };
1743    let env = environ(parent.pid).ok_or_else(|| {
1744        format!(
1745            "the environment {} (pid {}) was started with cannot be read, so a tool call's stamp would be hidden",
1746            parent.comm, parent.pid
1747        )
1748    })?;
1749    if let Some(key) = tool_call_stamp(&env) {
1750        return Err(format!(
1751            "{runner} (pid {}) was started with {key} set, inside another runner's tool call",
1752            parent.pid
1753        ));
1754    }
1755    // The Cursor app also hosts the person's own terminals; its agent's
1756    // shells carry `CURSOR_AGENT`, which the stamp above reads.
1757    let own = chain[1..].iter().take_while(|p| !ends_the_walk(p));
1758    if let Some((p, other)) = own
1759        .filter_map(|p| exe_runner(p.pid).map(|r| (p, r)))
1760        .find(|(_, r)| *r != "cursor")
1761    {
1762        return Err(format!(
1763            "{runner} (pid {}) runs under {other} (pid {}), inside a tool call",
1764            parent.pid, p.pid
1765        ));
1766    }
1767    confirm_runner(parent)?;
1768    Ok((parent.clone(), runner))
1769}
1770
1771#[cfg(test)]
1772mod tests {
1773    use super::*;
1774
1775    /// [`runner_of_file`] for the file `path` names now.
1776    #[cfg(target_os = "linux")]
1777    fn runner_here(
1778        path: &Path,
1779        home: Option<&Path>,
1780        store: &Path,
1781        person: &Person,
1782    ) -> Option<&'static str> {
1783        use std::os::unix::fs::MetadataExt as _;
1784        let meta = std::fs::metadata(path).ok()?;
1785        runner_of_file(path, home, store, person, (meta.dev(), meta.ino()))
1786    }
1787
1788    #[test]
1789    fn an_editor_name_matches_the_file_and_not_a_shell() {
1790        assert!(is_editor_name("Cursor"));
1791        assert!(is_editor_name("/Applications/Cursor Helper"));
1792        assert!(is_editor_name("cursor-agent"));
1793        assert!(!is_editor_name("bash"));
1794        assert!(!is_editor_name("python3"));
1795    }
1796
1797    #[test]
1798    fn a_runner_is_read_from_the_file_it_runs_from() {
1799        let roots = install_roots(Some(Path::new("/home/u")));
1800        for (path, want) in [
1801            ("/home/u/.local/share/claude/versions/2.1.3", Some("claude")),
1802            ("/home/u/.local/bin/claude", Some("claude")),
1803            (
1804                "/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js",
1805                Some("claude"),
1806            ),
1807            (
1808                "/usr/lib/node_modules/@openai/codex/vendor/x86_64-unknown-linux-musl/codex/codex",
1809                Some("codex"),
1810            ),
1811            (
1812                "/home/u/.local/share/cursor-agent/versions/2025.10.2-abc/node",
1813                Some("cursor-agent"),
1814            ),
1815            ("/usr/share/cursor/cursor", Some("cursor")),
1816            ("/usr/local/bin/codex", Some("codex")),
1817            ("/usr/bin/claude", Some("claude")),
1818            ("/bin/grok", Some("grok")),
1819            ("/home/u/.cargo/bin/codex", Some("codex")),
1820            (
1821                "/home/u/.npm-global/lib/node_modules/@anthropic-ai/claude-code/cli.js",
1822                Some("claude"),
1823            ),
1824            (
1825                "/nix/store/0c9yapqd0b8y4mj5xj7mrpmhy3l5ykh8-claude-code-2.0.1/bin/claude",
1826                Some("claude"),
1827            ),
1828            ("/usr/bin/node", None),
1829            ("/usr/bin/bash", None),
1830            ("/usr/bin/python3", None),
1831            ("/usr/bin/ssh", None),
1832            ("/home/u/.cargo/bin/ljos", None),
1833            ("/tmp/claude", None),
1834            ("/tmp/claude/versions/2.1.3", None),
1835            ("/home/u/runners/claude", None),
1836            ("/home/u/plant/grok", None),
1837            ("/home/u/plant/bin/claude", None),
1838            ("/home/u/.local/bin/claude (deleted)", None),
1839            ("/home/u/plant/.local/bin/claude", None),
1840            ("/tmp/.local/bin/claude", None),
1841            ("/tmp/project/node_modules/.bin/claude", None),
1842            ("/home/u/../other/.local/bin/claude", None),
1843            ("/home/uu/.local/bin/claude", None),
1844            ("/home/other/.local/bin/claude", None),
1845            ("/home/u/.local/binx/claude", None),
1846            ("/home/u/.local/bin/../../plant/claude", None),
1847            ("/home/u/.local/share/plant/claude", None),
1848            ("/home/u/.local/share/claude-plant/claude", None),
1849            ("/home/u/src/app/node_modules/.bin/claude", None),
1850            ("/usr/binx/claude", None),
1851            ("/usr/share/plant/claude", None),
1852            ("/usr/lib/node_modules/../../../tmp/claude", None),
1853            ("/opt/plant/claude", None),
1854            ("/var/tmp/.local/bin/claude", None),
1855            ("/dev/shm/node_modules/.bin/claude", None),
1856            ("/nix/store/claude/bin/claude", None),
1857            (
1858                "/nix/store/0c9yapqd0b8y4mj5xj7mrpmhy3l5ykh8/bin/claude",
1859                None,
1860            ),
1861            (
1862                "/nix/store/0c9yapqd0b8y4mj5xj7mrpmhy3l5ykhe-claude-code-2.0.1/bin/claude",
1863                None,
1864            ),
1865        ] {
1866            let got = runner_below(Path::new(path), &roots, Path::new(NIX_STORE))
1867                .map(|(runner, _)| runner);
1868            assert_eq!(got, want, "{path}");
1869        }
1870    }
1871
1872    /// A runner is read where the kernel resolves it. A link from the
1873    /// person's own `~/.local/bin` into `/tmp`, a path that climbs out of
1874    /// that home into another, and a file anyone may rewrite or reach
1875    /// through a directory anyone may write are not installed copies; the
1876    /// same file kept by the person is.
1877    #[cfg(target_os = "linux")]
1878    #[test]
1879    fn an_install_root_holds_only_what_resolves_inside_it() {
1880        use std::os::unix::fs::PermissionsExt as _;
1881        let base = tempfile::Builder::new()
1882            .prefix(".ljos-roots-")
1883            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
1884            .unwrap();
1885        let home = base.path().join("u");
1886        let person = Person::new(&SystemAccounts);
1887        let store = PathBuf::from(NIX_STORE);
1888        let program = |dir: &Path, name: &str| {
1889            std::fs::create_dir_all(dir).unwrap();
1890            let path = dir.join(name);
1891            std::fs::write(&path, "").unwrap();
1892            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
1893            path
1894        };
1895        let bin = home.join(".local/bin");
1896        let claude = program(&bin, "claude");
1897        assert_eq!(
1898            runner_here(&claude, Some(&home), &store, &person),
1899            Some("claude")
1900        );
1901
1902        let away = tempfile::tempdir().unwrap();
1903        std::os::unix::fs::symlink(program(away.path(), "codex"), bin.join("codex")).unwrap();
1904        assert_eq!(
1905            runner_here(&bin.join("codex"), Some(&home), &store, &person),
1906            None
1907        );
1908
1909        program(&base.path().join("other/.local/bin"), "claude");
1910        let climbed = home.join("../other/.local/bin/claude");
1911        assert_eq!(runner_here(&climbed, Some(&home), &store, &person), None);
1912
1913        std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o757)).unwrap();
1914        assert_eq!(runner_here(&claude, Some(&home), &store, &person), None);
1915
1916        let open = bin.join("open");
1917        let grok = program(&open, "grok");
1918        assert_eq!(
1919            runner_here(&grok, Some(&home), &store, &person),
1920            Some("grok")
1921        );
1922        std::fs::set_permissions(&open, std::fs::Permissions::from_mode(0o777)).unwrap();
1923        assert_eq!(runner_here(&grok, Some(&home), &store, &person), None);
1924    }
1925
1926    /// Whoever may write the directory an install root sits in may swap
1927    /// the root, so that directory is judged as the root is: each root
1928    /// under the person's home is refused once its own directory is
1929    /// writable by anyone or by a group the person shares.
1930    #[cfg(target_os = "linux")]
1931    #[test]
1932    fn a_root_in_a_directory_others_may_write_is_refused() {
1933        use std::os::unix::fs::PermissionsExt as _;
1934        let base = tempfile::Builder::new()
1935            .prefix(".ljos-above-")
1936            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
1937            .unwrap();
1938        let home = base.path().join("u");
1939        let store = PathBuf::from(NIX_STORE);
1940        let person = Person::new(&SystemAccounts);
1941        let staff = FakeAccounts {
1942            user: Some("u"),
1943            group: Some("staff"),
1944            members: &["u", "v"],
1945            primary: Some(vec![person.uid]),
1946        };
1947        let sharing = Person::new(&staff);
1948        let mut files: Vec<PathBuf> = vec![
1949            home.join(".local/bin/claude"),
1950            home.join(".cargo/bin/codex"),
1951            home.join(".npm-global/lib/node_modules/@anthropic-ai/claude-code/cli.js"),
1952        ];
1953        files.extend(
1954            HOOK_RUNNERS
1955                .iter()
1956                .map(|(name, _)| home.join(".local/share").join(name).join(name)),
1957        );
1958        for file in &files {
1959            std::fs::create_dir_all(file.parent().unwrap()).unwrap();
1960            std::fs::write(file, "").unwrap();
1961        }
1962        let set = |dir: &Path, mode| {
1963            std::fs::set_permissions(dir, std::fs::Permissions::from_mode(mode)).unwrap();
1964        };
1965        for root in install_roots(Some(&home))
1966            .iter()
1967            .filter(|r| r.starts_with(&home))
1968        {
1969            let file = files.iter().find(|f| f.starts_with(root)).unwrap();
1970            let above = root.parent().unwrap();
1971            let runner = |who| runner_here(file, Some(&home), &store, who);
1972            assert!(runner(&person).is_some(), "{}", root.display());
1973            set(above, 0o757);
1974            assert_eq!(runner(&person), None, "{}", root.display());
1975            set(above, 0o775);
1976            assert_eq!(runner(&sharing), None, "{}", root.display());
1977            set(above, 0o755);
1978        }
1979
1980        let uid = person.uid;
1981        let owner = |uid, mode| Owner {
1982            uid,
1983            gid: person.gid,
1984            mode,
1985        };
1986        let walk = |above| [owner(0, 0o755), above, owner(uid, 0o755), owner(uid, 0o755)];
1987        assert!(walk_kept(&walk(owner(uid, 0o755)), 2, false, &person));
1988        assert!(walk_kept(&walk(owner(0, 0o755)), 2, false, &person));
1989        assert!(!walk_kept(&walk(owner(uid + 1, 0o755)), 2, false, &person));
1990        assert!(!walk_kept(&walk(owner(uid, 0o757)), 2, false, &person));
1991        assert!(!walk_kept(&walk(owner(uid, 0o775)), 2, false, &sharing));
1992    }
1993
1994    /// The file judged is the one opened. A directory swapped after the
1995    /// path resolved, for a link or for another directory holding a file
1996    /// of the same name, is not walked through, and a file that is not
1997    /// the one the process runs is not its runner.
1998    #[cfg(target_os = "linux")]
1999    #[test]
2000    fn a_parent_swapped_after_the_path_resolved_is_refused() {
2001        use std::os::unix::fs::MetadataExt as _;
2002        let base = tempfile::Builder::new()
2003            .prefix(".ljos-swap-")
2004            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
2005            .unwrap();
2006        let home = std::fs::canonicalize(base.path()).unwrap().join("u");
2007        let person = Person::new(&SystemAccounts);
2008        let store = PathBuf::from(NIX_STORE);
2009        let versions = home.join(".local/share/claude/versions");
2010        let other = home.join("other");
2011        for dir in [&versions, &other] {
2012            std::fs::create_dir_all(dir).unwrap();
2013            std::fs::write(dir.join("2.1.3"), "").unwrap();
2014        }
2015        let id = |path: &Path| {
2016            let meta = std::fs::metadata(path).unwrap();
2017            (meta.dev(), meta.ino())
2018        };
2019        let file = versions.join("2.1.3");
2020        let (running, planted) = (id(&file), id(&other.join("2.1.3")));
2021        let runner = |expect| runner_at(&file, Some(&home), &store, &person, expect);
2022        assert_eq!(runner(running), Some("claude"));
2023
2024        std::fs::rename(&versions, home.join("held")).unwrap();
2025        std::os::unix::fs::symlink(&other, &versions).unwrap();
2026        assert_eq!(runner(running), None);
2027        assert_eq!(runner(planted), None);
2028
2029        std::fs::remove_file(&versions).unwrap();
2030        std::fs::rename(&other, &versions).unwrap();
2031        assert_eq!(runner(running), None);
2032    }
2033
2034    /// A process is its runner only through the (device, inode) the
2035    /// kernel reports for its executable. When that cannot be read, the
2036    /// path the link names is not trusted in its place.
2037    #[cfg(target_os = "linux")]
2038    #[test]
2039    fn an_executable_that_cannot_be_read_is_no_runner() {
2040        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
2041        let base = tempfile::Builder::new()
2042            .prefix(".ljos-exe-")
2043            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
2044            .unwrap();
2045        let home = base.path().join("u");
2046        let bin = home.join(".local/bin");
2047        std::fs::create_dir_all(&bin).unwrap();
2048        let claude = bin.join("claude");
2049        std::fs::write(&claude, "").unwrap();
2050        std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o755)).unwrap();
2051        let meta = std::fs::metadata(&claude).unwrap();
2052        let person = Person::new(&SystemAccounts);
2053        let store = PathBuf::from(NIX_STORE);
2054        let runner = |running| runner_from(&claude, running, || None, Some(&home), &store, &person);
2055        assert_eq!(runner(Some((meta.dev(), meta.ino()))), Some("claude"));
2056        assert_eq!(runner(None), None);
2057    }
2058
2059    /// A runtime's script names the runner only when the runtime is an
2060    /// installed copy of its exact name, kept as a runner file is and the
2061    /// file the process runs. A `node` of a tool call's own making, or a
2062    /// program whose name merely starts like one, may name any script.
2063    #[cfg(target_os = "linux")]
2064    #[test]
2065    fn a_script_names_the_runner_only_for_an_installed_runtime() {
2066        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
2067        let base = tempfile::Builder::new()
2068            .prefix(".ljos-runtime-")
2069            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
2070            .unwrap();
2071        let home = base.path().join("u");
2072        let away = tempfile::tempdir().unwrap();
2073        let program = |dir: &Path, name: &str| {
2074            std::fs::create_dir_all(dir).unwrap();
2075            let path = dir.join(name);
2076            std::fs::write(&path, "").unwrap();
2077            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
2078            path
2079        };
2080        let id = |path: &Path| {
2081            let meta = std::fs::metadata(path).unwrap();
2082            (meta.dev(), meta.ino())
2083        };
2084        let cli = program(
2085            &home.join(".npm-global/lib/node_modules/@anthropic-ai/claude-code"),
2086            "cli.js",
2087        );
2088        let bin = home.join(".local/bin");
2089        let node = program(&bin, "node");
2090        let person = Person::new(&SystemAccounts);
2091        let store = PathBuf::from(NIX_STORE);
2092        let runner = |exe: &Path, running| {
2093            runner_from(
2094                exe,
2095                Some(running),
2096                || Some(cli.clone()),
2097                Some(&home),
2098                &store,
2099                &person,
2100            )
2101        };
2102        assert_eq!(runner(&node, id(&node)), Some("claude"));
2103        assert_eq!(runner(&node, id(&cli)), None);
2104        for planted in [
2105            program(&bin, "node-v20"),
2106            program(&bin, "nodejs_modules"),
2107            program(away.path(), "node"),
2108        ] {
2109            assert_eq!(
2110                runner(&planted, id(&planted)),
2111                None,
2112                "{}",
2113                planted.display()
2114            );
2115        }
2116        std::fs::set_permissions(&node, std::fs::Permissions::from_mode(0o757)).unwrap();
2117        assert_eq!(runner(&node, id(&node)), None);
2118    }
2119
2120    /// A Nix store entry is a runner only while Nix alone keeps it. A
2121    /// store the person owns counts as a single-user install only while
2122    /// no one else may write it; a root's store must be closed to the
2123    /// person, sticky when its group may write it, and hold root's
2124    /// entries.
2125    #[cfg(target_os = "linux")]
2126    #[test]
2127    fn a_nix_entry_is_a_runner_only_in_a_store_nix_keeps() {
2128        use std::os::unix::fs::PermissionsExt as _;
2129        let base = tempfile::Builder::new()
2130            .prefix(".ljos-store-")
2131            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
2132            .unwrap();
2133        let store = base.path().join("store");
2134        let bin = store.join("0c9yapqd0b8y4mj5xj7mrpmhy3l5ykh8-claude-code-2.0.1/bin");
2135        std::fs::create_dir_all(&bin).unwrap();
2136        let claude = bin.join("claude");
2137        std::fs::write(&claude, "").unwrap();
2138        std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o755)).unwrap();
2139        let person = Person::new(&SystemAccounts);
2140        let set = |mode| {
2141            std::fs::set_permissions(&store, std::fs::Permissions::from_mode(mode)).unwrap();
2142        };
2143        let runner = || runner_here(&claude, None, &store, &person);
2144
2145        set(0o755);
2146        assert_eq!(runner(), Some("claude"));
2147        for mode in [0o775, 0o757, 0o777, 0o1775, 0o1777] {
2148            set(mode);
2149            assert_eq!(runner(), None, "{mode:o}");
2150        }
2151        set(0o755);
2152
2153        let uid = person.uid;
2154        let nixbld = person.gid + 1;
2155        let owner = |uid, gid, mode| Owner { uid, gid, mode };
2156        let outsider = Person {
2157            groups: Some(vec![]),
2158            ..Person::new(&SystemAccounts)
2159        };
2160        let builder = Person {
2161            groups: Some(vec![nixbld]),
2162            ..Person::new(&SystemAccounts)
2163        };
2164        let unread = Person {
2165            groups: None,
2166            ..Person::new(&SystemAccounts)
2167        };
2168        let root_entry = owner(0, 0, 0o555);
2169        let own_entry = owner(uid, uid, 0o555);
2170        for (store, entry, who, want) in [
2171            (owner(0, nixbld, 0o1775), root_entry, &outsider, true),
2172            (owner(0, 0, 0o755), root_entry, &outsider, true),
2173            (owner(0, nixbld, 0o1775), own_entry, &outsider, false),
2174            (owner(0, nixbld, 0o775), root_entry, &outsider, false),
2175            (owner(0, nixbld, 0o1775), root_entry, &builder, false),
2176            (owner(0, nixbld, 0o1775), root_entry, &unread, false),
2177            (owner(0, 0, 0o1777), root_entry, &outsider, false),
2178            (owner(uid, uid, 0o755), own_entry, &outsider, true),
2179            (owner(uid, uid, 0o755), root_entry, &outsider, true),
2180            (owner(uid, uid, 0o775), own_entry, &outsider, false),
2181            (owner(uid, uid, 0o1777), own_entry, &outsider, false),
2182            (
2183                owner(uid, uid, 0o755),
2184                owner(uid + 1, 0, 0o555),
2185                &outsider,
2186                false,
2187            ),
2188            (owner(uid + 1, 0, 0o755), own_entry, &outsider, false),
2189        ] {
2190            assert_eq!(
2191                store_keeps(store, entry, who),
2192                want,
2193                "{}:{} {:o}",
2194                store.uid,
2195                store.gid,
2196                store.mode
2197            );
2198        }
2199    }
2200
2201    /// One user `u`, the name and members of whatever group is asked
2202    /// for, and the uids whose primary group it is.
2203    #[cfg(target_os = "linux")]
2204    struct FakeAccounts {
2205        user: Option<&'static str>,
2206        group: Option<&'static str>,
2207        members: &'static [&'static str],
2208        primary: Option<Vec<u32>>,
2209    }
2210
2211    #[cfg(target_os = "linux")]
2212    impl Accounts for FakeAccounts {
2213        fn user_name(&self, _uid: u32) -> Option<std::ffi::OsString> {
2214            self.user.map(Into::into)
2215        }
2216
2217        fn group(&self, _gid: u32) -> Option<GroupEntry> {
2218            self.group.map(|name| GroupEntry {
2219                name: name.into(),
2220                members: self.members.iter().map(Into::into).collect(),
2221            })
2222        }
2223
2224        fn primary_members(&self, _gid: u32) -> Option<Vec<u32>> {
2225            self.primary.clone()
2226        }
2227    }
2228
2229    /// A runner file the person's primary group may write is theirs only
2230    /// when that group is: named for them, listing no one else, and no
2231    /// other account's primary group. An account lookup that fails is
2232    /// not such a group.
2233    #[cfg(target_os = "linux")]
2234    #[test]
2235    fn a_group_write_counts_only_from_a_group_the_person_has_alone() {
2236        use std::os::unix::fs::PermissionsExt as _;
2237        // SAFETY: getuid takes no arguments and only reads the process
2238        // identity.
2239        let uid = unsafe { libc::getuid() };
2240        let alone = |members, primary| FakeAccounts {
2241            user: Some("u"),
2242            group: Some("u"),
2243            members,
2244            primary: Some(primary),
2245        };
2246        let shared = [
2247            FakeAccounts {
2248                group: Some("staff"),
2249                ..alone(&[], vec![uid])
2250            },
2251            FakeAccounts {
2252                group: None,
2253                ..alone(&[], vec![uid])
2254            },
2255            alone(&["u", "v"], vec![uid]),
2256            alone(&["v"], vec![uid]),
2257            alone(&[], vec![uid, uid + 1]),
2258            FakeAccounts {
2259                user: None,
2260                ..alone(&[], vec![uid])
2261            },
2262            FakeAccounts {
2263                primary: None,
2264                ..alone(&[], vec![uid])
2265            },
2266        ];
2267
2268        let base = tempfile::Builder::new()
2269            .prefix(".ljos-group-")
2270            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
2271            .unwrap();
2272        let home = base.path().join("u");
2273        let bin = home.join(".local/bin");
2274        std::fs::create_dir_all(&bin).unwrap();
2275        let claude = bin.join("claude");
2276        std::fs::write(&claude, "").unwrap();
2277        std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o775)).unwrap();
2278        let store = PathBuf::from(NIX_STORE);
2279
2280        for accounts in [alone(&[], vec![uid]), alone(&["u"], vec![uid, uid])] {
2281            assert!(group_is_private(&accounts, uid, 0));
2282            let person = Person::new(&accounts);
2283            assert_eq!(
2284                runner_here(&claude, Some(&home), &store, &person),
2285                Some("claude")
2286            );
2287        }
2288        for accounts in &shared {
2289            assert!(!group_is_private(accounts, uid, 0));
2290            let person = Person::new(accounts);
2291            assert_eq!(runner_here(&claude, Some(&home), &store, &person), None);
2292        }
2293    }
2294
2295    /// The accounts in a group are read from `passwd` only when
2296    /// `nsswitch.conf` names that file alone, and a file that cannot be
2297    /// read whole lists no one rather than fewer.
2298    #[test]
2299    fn a_primary_group_is_listed_only_from_a_passwd_file_read_whole() {
2300        let etc = tempfile::tempdir().unwrap();
2301        let write = |name: &str, text: &str| std::fs::write(etc.path().join(name), text).unwrap();
2302        let passwd = "root:x:0:0::/root:/bin/sh\nu:x:1000:1000::/home/u:/bin/sh\n";
2303        write("passwd", passwd);
2304        assert_eq!(primary_in_files(etc.path(), 1000), None, "no nsswitch.conf");
2305        for conf in [
2306            "passwd: files systemd\n",
2307            "passwd: sss files\n",
2308            "passwd: compat\n",
2309            "passwd: files [NOTFOUND=return] ldap\n",
2310            "passwd: files\npasswd: files ldap\n",
2311            "group: files\n",
2312        ] {
2313            write("nsswitch.conf", conf);
2314            assert_eq!(primary_in_files(etc.path(), 1000), None, "{conf}");
2315        }
2316        write(
2317            "nsswitch.conf",
2318            "# local\npasswd:   files # only\ngroup: files\n",
2319        );
2320        assert_eq!(primary_in_files(etc.path(), 1000), Some(vec![1000]));
2321        assert_eq!(primary_in_files(etc.path(), 7), Some(vec![]));
2322        for extra in [
2323            "+@admins\n",
2324            "-v\n",
2325            "v:x:1001\n",
2326            "v:x:one:1000::/home/v:/bin/sh\n",
2327        ] {
2328            write("passwd", &format!("{passwd}{extra}"));
2329            assert_eq!(primary_in_files(etc.path(), 1000), None, "{extra}");
2330        }
2331        write(
2332            "passwd",
2333            &format!("{passwd}\n# kept\nv:x:1001:1000::/home/v:/bin/sh\n"),
2334        );
2335        assert_eq!(primary_in_files(etc.path(), 1000), Some(vec![1000, 1001]));
2336        std::fs::remove_file(etc.path().join("passwd")).unwrap();
2337        assert_eq!(primary_in_files(etc.path(), 1000), None);
2338    }
2339
2340    /// A group is read from `group` only when `nsswitch.conf` names that
2341    /// file alone, and only when one line has its gid: a second line's
2342    /// members hold the group as well, though a lookup returns the first.
2343    #[test]
2344    fn a_group_is_read_only_from_one_line_of_a_group_file_read_whole() {
2345        let etc = tempfile::tempdir().unwrap();
2346        let write = |name: &str, text: &str| std::fs::write(etc.path().join(name), text).unwrap();
2347        let group = "root:x:0:\nu:x:1000:\nstaff:x:50:u,v\n";
2348        write("group", group);
2349        let read = |gid| {
2350            group_in_files(etc.path(), gid).map(|g| {
2351                let members: Vec<String> = g
2352                    .members
2353                    .iter()
2354                    .map(|m| m.to_string_lossy().into_owned())
2355                    .collect();
2356                (g.name.to_string_lossy().into_owned(), members)
2357            })
2358        };
2359        assert_eq!(read(1000), None, "no nsswitch.conf");
2360        for conf in ["group: files systemd\n", "group: sss\n", "passwd: files\n"] {
2361            write("nsswitch.conf", conf);
2362            assert_eq!(read(1000), None, "{conf}");
2363        }
2364        write("nsswitch.conf", "passwd: files\ngroup: files\n");
2365        assert_eq!(read(1000), Some(("u".into(), vec![])));
2366        assert_eq!(
2367            read(50),
2368            Some(("staff".into(), vec!["u".into(), "v".into()]))
2369        );
2370        assert_eq!(read(7), None);
2371        for extra in ["shadow:x:1000:v\n", "+:::\n", "w:x:1000\n", "w:x:ten:\n"] {
2372            write("group", &format!("{group}{extra}"));
2373            assert_eq!(read(1000), None, "{extra}");
2374        }
2375    }
2376
2377    /// A process younger than a recorded tool call, in that call's cgroup
2378    /// or session, is still the tool call. The runner that recorded the
2379    /// mark is not. A missing record is not a tool call; a corrupt one
2380    /// refuses everything.
2381    #[test]
2382    fn a_young_runner_in_a_recorded_tool_call_is_refused() {
2383        let _guard = crate::test_env_lock();
2384        let opener = Proc {
2385            pid: 1,
2386            start: 1,
2387            comm: "claude".into(),
2388        };
2389        let young = Proc {
2390            pid: 999_999,
2391            start: u64::MAX,
2392            comm: "claude".into(),
2393        };
2394        let old = Proc {
2395            pid: 42,
2396            start: 0,
2397            comm: "claude".into(),
2398        };
2399        assert!(confirm_runner(&young).is_ok(), "no record yet");
2400        note_tool_call(&opener).unwrap();
2401        let why = confirm_runner(&young).unwrap_err();
2402        assert!(why.contains("tool call"), "{why}");
2403        assert!(confirm_runner(&opener).is_ok(), "the opener recorded it");
2404        assert!(confirm_runner(&old).is_ok(), "older than the record");
2405        std::fs::write(marks_path(), "nope\n").unwrap();
2406        let why = confirm_runner(&old).unwrap_err();
2407        assert!(why.contains("corrupt"), "{why}");
2408    }
2409
2410    #[test]
2411    fn a_tool_calls_variables_mark_a_runner_started_inside_one() {
2412        let env = |k: &str, v: &str| vec![(k.to_string(), v.to_string())];
2413        assert_eq!(tool_call_stamp(&env("CLAUDECODE", "1")), Some("CLAUDECODE"));
2414        assert_eq!(
2415            tool_call_stamp(&env("CURSOR_AGENT", "1")),
2416            Some("CURSOR_AGENT")
2417        );
2418        assert!(tool_call_stamp(&env("CURSOR_CONVERSATION_ID", "0199a1b2-c3d4")).is_some());
2419        assert_eq!(tool_call_stamp(&env("LJOS_SESSION_ID", "mine-0001")), None);
2420        assert_eq!(tool_call_stamp(&env("HOME", "/home/u")), None);
2421    }
2422
2423    #[test]
2424    fn only_a_bare_hook_command_is_the_runners_hook_shell() {
2425        for cmd in [
2426            "ljos hook",
2427            "/home/u/.cargo/bin/ljos hook --runner codex",
2428            "ljos hook --event SessionStart",
2429            "\"${CLAUDE_PLUGIN_ROOT}/bin/ljos-plugin\" ljos hook",
2430            "\"${CURSOR_PLUGIN_ROOT}/bin/ljos-plugin\" ljos hook",
2431        ] {
2432            assert!(bare_hook_command(cmd), "{cmd}");
2433        }
2434        for cmd in [
2435            "ljos hook < plant.json",
2436            "cat plant.json | ljos hook",
2437            "ljos hook <<'EOF'\n{}\nEOF",
2438            "ljos status; ljos hook",
2439            "ljos hook $(cat p)",
2440            "python3 plant.py",
2441            "ljos remember a b c d",
2442            "ljos-plugin hook",
2443            "bash -c 'ljos hook'",
2444        ] {
2445            assert!(!bare_hook_command(cmd), "{cmd}");
2446        }
2447    }
2448
2449    /// The test runner is no runner's program, so a hook it spawned is
2450    /// not the person's.
2451    #[test]
2452    fn a_hook_this_test_runs_has_no_runner() {
2453        let why = hook_runner().unwrap_err();
2454        assert!(why.contains("not a runner's own program"), "{why}");
2455    }
2456
2457    fn named(pid: u32, comm: &str) -> Proc {
2458        Proc {
2459            pid,
2460            start: u64::from(pid) * 10,
2461            comm: comm.into(),
2462        }
2463    }
2464
2465    #[test]
2466    fn this_process_has_live_ancestors_and_a_dead_pid_does_not_match() {
2467        let chain = ancestors();
2468        assert!(!chain.is_empty(), "the test runner is above this process");
2469        assert!(chain.iter().all(alive));
2470        let parent = &chain[0];
2471        assert!(token_alive(&token(parent)));
2472        let reused = Proc {
2473            start: parent.start + 1,
2474            ..parent.clone()
2475        };
2476        assert!(!alive(&reused));
2477        assert!(!token_alive(&format!(
2478            "other-boot:{}:{}",
2479            parent.pid, parent.start
2480        )));
2481    }
2482
2483    #[test]
2484    fn a_reaped_child_is_not_alive() {
2485        let mut child = std::process::Command::new("sleep")
2486            .arg("30")
2487            .spawn()
2488            .unwrap();
2489        let pid = child.id();
2490        let p = of(pid).unwrap();
2491        assert!(alive(&p));
2492        assert_eq!(above(pid).first().map(|q| q.pid), Some(std::process::id()));
2493        child.kill().unwrap();
2494        child.wait().unwrap();
2495        assert!(!alive(&p));
2496    }
2497
2498    #[test]
2499    fn a_child_is_read_with_the_environment_it_was_started_with() {
2500        let mut child = std::process::Command::new("sleep")
2501            .arg("30")
2502            .env("LJOS_PROC_TREE_PROBE", "started-with")
2503            .spawn()
2504            .unwrap();
2505        // Until the child has exec'd, its environment is the fork's.
2506        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2507        let env = loop {
2508            let env = environ(child.id()).unwrap_or_default();
2509            if env.iter().any(|(k, _)| k == "LJOS_PROC_TREE_PROBE")
2510                || std::time::Instant::now() > deadline
2511            {
2512                break env;
2513            }
2514            std::thread::sleep(std::time::Duration::from_millis(10));
2515        };
2516        child.kill().unwrap();
2517        child.wait().unwrap();
2518        assert!(
2519            env.iter()
2520                .any(|(k, v)| k == "LJOS_PROC_TREE_PROBE" && v == "started-with"),
2521            "{env:?}"
2522        );
2523    }
2524
2525    #[test]
2526    fn the_calling_shell_is_the_outermost_of_a_nested_run() {
2527        let harness = named(10, "claude");
2528        let chain = [
2529            named(3, "timeout"),
2530            named(4, "sh"),
2531            named(5, "bash"),
2532            harness.clone(),
2533        ];
2534        assert_eq!(calling_shell(&chain), Some(&chain[2]));
2535        let chain = [
2536            named(4, "sh"),
2537            named(6, "env"),
2538            named(5, "bash"),
2539            named(7, "node"),
2540            named(8, "bash"),
2541        ];
2542        assert_eq!(calling_shell(&chain), Some(&chain[2]));
2543        assert_eq!(calling_shell(&[harness.clone(), named(5, "bash")]), None);
2544        assert_eq!(calling_shell(&[named(3, "env"), harness]), None);
2545        assert_eq!(calling_shell(&[]), None);
2546    }
2547
2548    #[test]
2549    fn the_runner_is_above_the_shells_and_wrappers_it_started() {
2550        let chain = [
2551            named(4, "sh"),
2552            named(3, "timeout"),
2553            named(5, "bash"),
2554            named(10, "claude"),
2555            named(2, "tmux"),
2556        ];
2557        assert_eq!(runner(&chain).map(|p| p.pid), Some(10));
2558        assert_eq!(runner(&chain[3..]).map(|p| p.pid), Some(10));
2559        let shells = [named(4, "sh"), named(5, "bash")];
2560        assert_eq!(runner(&shells).map(|p| p.pid), Some(5));
2561        assert_eq!(runner(&[]), None);
2562    }
2563
2564    #[test]
2565    fn a_session_above_the_hook_is_never_its_runner() {
2566        for session in ["tmux", "tmux: server", "gnome-terminal-", "systemd", "sshd"] {
2567            let chain = [named(4, "sh"), named(5, "bash"), named(2, session)];
2568            assert_eq!(runner(&chain).map(|p| p.pid), Some(5), "{session}");
2569            let chain = [named(4, "sh"), named(2, session), named(10, "claude")];
2570            assert_eq!(runner(&chain).map(|p| p.pid), Some(4), "{session}");
2571            assert_eq!(runner(&[named(2, session), named(10, "claude")]), None);
2572        }
2573        let chain = [named(4, "sh"), named(7, "git"), named(2, "kitty")];
2574        assert_eq!(runner(&chain).map(|p| p.pid), Some(7));
2575    }
2576
2577    /// A process no kernel runs, so no `/proc` entry names it: pids stop
2578    /// below 2^22.
2579    fn fake(n: u32, comm: &str) -> Proc {
2580        named((1 << 22) + n, comm)
2581    }
2582
2583    #[test]
2584    fn a_harness_outranks_a_runtime_that_only_started_the_hook() {
2585        let chain = [
2586            fake(1, "sh"),
2587            fake(2, "uv"),
2588            fake(3, "uv"),
2589            fake(4, "claude"),
2590        ];
2591        assert_eq!(runner(&chain), Some(&chain[3]));
2592        let chain = [fake(1, "sh"), fake(2, "node"), fake(3, "claude")];
2593        assert_eq!(runner(&chain), Some(&chain[2]));
2594        let chain = [
2595            fake(1, "sh"),
2596            fake(2, "npx"),
2597            fake(3, "bash"),
2598            fake(4, "cursor-agent"),
2599            fake(5, "tmux"),
2600        ];
2601        assert_eq!(runner(&chain), Some(&chain[3]));
2602        let chain = [
2603            fake(1, "sh"),
2604            fake(2, "uv"),
2605            fake(3, "codex"),
2606            fake(4, "agy"),
2607        ];
2608        assert_eq!(runner(&chain), Some(&chain[2]), "the nearest harness");
2609    }
2610
2611    #[test]
2612    fn a_node_harness_with_no_known_harness_above_is_the_runner() {
2613        let chain = [
2614            fake(1, "sh"),
2615            fake(2, "node"),
2616            fake(3, "bash"),
2617            fake(4, "tmux"),
2618        ];
2619        assert_eq!(runner(&chain), Some(&chain[1]));
2620        assert_eq!(runner(&chain[..2]), Some(&chain[1]));
2621        // The walk stops at the session: a harness above it is not read.
2622        let chain = [
2623            fake(1, "sh"),
2624            fake(2, "node"),
2625            fake(3, "tmux"),
2626            fake(4, "claude"),
2627        ];
2628        assert_eq!(runner(&chain), Some(&chain[1]));
2629    }
2630
2631    #[test]
2632    fn pid_1_is_the_runner_only_as_a_harness() {
2633        let chain = [fake(1, "sh"), fake(2, "uv"), named(1, "claude")];
2634        assert_eq!(runner(&chain), Some(&chain[2]), "a container's harness");
2635        let chain = [fake(1, "sh"), fake(2, "bash"), named(1, "tini")];
2636        assert_eq!(runner(&chain), Some(&chain[1]), "an init is no runner");
2637        let chain = [fake(1, "sh"), fake(2, "node"), named(1, "dumb-init")];
2638        assert_eq!(runner(&chain), Some(&chain[1]));
2639        assert_eq!(runner(&[named(1, "tini")]), None);
2640    }
2641
2642    #[test]
2643    fn the_walk_reads_up_to_a_process_with_no_parent() {
2644        let chain = ancestors();
2645        let top = chain.last().expect("the test runner is above this process");
2646        assert!(
2647            chain.len() == DEPTH || stat(top.pid).is_some_and(|s| s.ppid == 0),
2648            "{chain:?}"
2649        );
2650    }
2651}