Skip to main content

sysprims_proc/
lib.rs

1//! sysprims-proc: Process inspection and enumeration utilities
2//!
3//! This crate provides cross-platform process inspection capabilities with a stable
4//! JSON schema for automation. It supports listing all processes, filtering by various
5//! criteria, and getting details for a specific PID.
6//!
7//! ## Features
8//!
9//! - **Process enumeration**: List all running processes
10//! - **Process inspection**: Get details for a single process by PID
11//! - **Filtering**: Filter by name, state, CPU, memory, user
12//! - **Stable JSON output**: Schema-versioned output for automation
13//!
14//! ## Platform Support
15//!
16//! | Feature | Linux | macOS | Windows |
17//! |---------|-------|-------|---------|
18//! | PID enumeration | /proc | proc_listpids | Toolhelp32 |
19//! | Process info | /proc/[pid]/* | proc_pidinfo | OpenProcess |
20//! | CPU usage | /proc/[pid]/stat | proc_pidinfo | GetProcessTimes |
21//! | Memory usage | /proc/[pid]/statm | proc_pidinfo | GetProcessMemoryInfo |
22//!
23//! ## Examples
24//!
25//! ```rust,no_run
26//! use sysprims_proc::{snapshot, get_process, ProcessFilter};
27//!
28//! // Get all processes
29//! let snap = snapshot().unwrap();
30//! println!("Found {} processes", snap.processes.len());
31//!
32//! // Get current process
33//! let self_info = get_process(std::process::id()).unwrap();
34//! println!("Current process: {} (PID {})", self_info.name, self_info.pid);
35//!
36//! // Filter processes by name
37//! let filter = ProcessFilter {
38//!     name_contains: Some("rust".into()),
39//!     ..Default::default()
40//! };
41//! let filtered = sysprims_proc::snapshot_filtered(&filter).unwrap();
42//! ```
43
44use serde::{Deserialize, Serialize};
45use std::collections::{BTreeMap, HashMap, HashSet};
46use std::net::IpAddr;
47use std::sync::Arc;
48use std::time::Duration;
49use sysprims_core::schema::{
50    ANCESTORS_RESULT_V1, DESCENDANTS_RESULT_SAMPLED_V1, DESCENDANTS_RESULT_V1, FD_SNAPSHOT_V1,
51    GUARD_EVENT_V1, PORT_BINDINGS_V1, PORT_FILTER_V1, PROCESS_INFO_SAMPLED_V1, PROCESS_INFO_V1,
52    WAIT_PID_RESULT_V1,
53};
54use sysprims_core::time::now_rfc3339;
55use sysprims_core::{get_platform, guard_signals, time, SysprimsError, SysprimsResult};
56
57// Platform-specific implementations
58#[cfg(target_os = "linux")]
59mod linux;
60#[cfg(target_os = "macos")]
61mod macos;
62#[cfg(windows)]
63mod windows;
64
65/// Read-only `native-process-observation:v0` OS collectors and continuity handles.
66pub mod observation;
67
68/// Re-exported process-bound signal and exit-watch handle (`ProcessHandle`) from `sysprims-signal`.
69pub use sysprims_signal::{
70    open_process_handle, open_process_handle_verified, ProcessHandle, SignalBinding,
71};
72
73// Re-export the platform implementation
74#[cfg(target_os = "linux")]
75use linux as platform;
76#[cfg(target_os = "macos")]
77use macos as platform;
78#[cfg(windows)]
79use windows as platform;
80
81// ============================================================================
82// Core Types
83// ============================================================================
84
85/// Snapshot of all processes at a point in time.
86///
87/// Contains a list of process information with a timestamp and schema identifier.
88#[derive(Debug, Clone, Serialize)]
89pub struct ProcessSnapshot {
90    /// Schema identifier for version detection.
91    pub schema_id: &'static str,
92
93    /// Timestamp of snapshot (ISO 8601).
94    pub timestamp: String,
95
96    /// List of processes.
97    pub processes: Vec<ProcessInfo>,
98}
99
100/// Result of waiting for a PID to exit.
101///
102/// Best-effort cross-platform semantics:
103/// - On Unix, this uses a polling strategy (we are not necessarily the parent).
104/// - On Windows, this uses process wait APIs when available.
105#[derive(Debug, Clone, Serialize)]
106pub struct WaitPidResult {
107    /// Schema identifier for version detection.
108    pub schema_id: &'static str,
109
110    /// Timestamp of result creation (ISO 8601).
111    pub timestamp: String,
112
113    /// Current platform (e.g., "linux", "macos", "windows").
114    pub platform: &'static str,
115
116    /// PID waited on.
117    pub pid: u32,
118
119    /// True if the process was observed to have exited.
120    pub exited: bool,
121
122    /// True if the wait timed out before exit was observed.
123    pub timed_out: bool,
124
125    /// Exit code when available.
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub exit_code: Option<i32>,
128
129    /// Warnings about degraded visibility.
130    pub warnings: Vec<String>,
131}
132
133/// Snapshot of listening ports at a point in time.
134#[derive(Debug, Clone, Serialize)]
135pub struct PortBindingsSnapshot {
136    /// Schema identifier for version detection.
137    pub schema_id: &'static str,
138
139    /// Timestamp of snapshot (ISO 8601).
140    pub timestamp: String,
141
142    /// Current platform (e.g., "linux", "macos", "windows").
143    pub platform: &'static str,
144
145    /// List of socket bindings.
146    pub bindings: Vec<PortBinding>,
147
148    /// Warnings about partial visibility or skipped entries.
149    pub warnings: Vec<String>,
150}
151
152/// Listening socket binding information.
153#[derive(Debug, Clone, Serialize)]
154pub struct PortBinding {
155    /// Protocol for the socket.
156    pub protocol: Protocol,
157
158    /// Local address (None if unknown).
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub local_addr: Option<IpAddr>,
161
162    /// Local port for the socket.
163    pub local_port: u16,
164
165    /// Socket state (e.g., "listen" for TCP).
166    #[serde(skip_serializing_if = "Option::is_none")]
167    pub state: Option<String>,
168
169    /// Owning process ID (None if attribution not available).
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub pid: Option<u32>,
172
173    /// Owning process info (best-effort).
174    #[serde(skip_serializing_if = "Option::is_none")]
175    pub process: Option<ProcessInfo>,
176
177    /// Socket inode when available (Linux-only).
178    #[serde(skip)]
179    pub inode: Option<u64>,
180}
181
182/// Protocol for a socket binding.
183#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
184#[serde(rename_all = "snake_case")]
185pub enum Protocol {
186    Tcp,
187    Udp,
188}
189
190/// Filter for port queries.
191#[derive(Debug, Clone, Default, Deserialize)]
192#[serde(deny_unknown_fields)]
193pub struct PortFilter {
194    /// Filter by protocol (tcp/udp).
195    pub protocol: Option<Protocol>,
196
197    /// Filter by local port.
198    pub local_port: Option<u16>,
199}
200
201/// File descriptor kind.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(rename_all = "snake_case")]
204pub enum FdKind {
205    File,
206    Socket,
207    Pipe,
208    Unknown,
209}
210
211/// Filter for fd queries.
212#[derive(Debug, Clone, Default, Deserialize)]
213#[serde(deny_unknown_fields)]
214pub struct FdFilter {
215    /// Filter by fd kind.
216    pub kind: Option<FdKind>,
217}
218
219impl FdFilter {
220    pub fn validate(&self) -> SysprimsResult<()> {
221        // No numeric ranges for now.
222        Ok(())
223    }
224}
225
226/// Information about a single file descriptor.
227#[derive(Debug, Clone, Serialize)]
228pub struct FdInfo {
229    /// File descriptor number.
230    pub fd: u32,
231
232    /// Best-effort fd classification.
233    pub kind: FdKind,
234
235    /// Best-effort resolved path/target.
236    #[serde(skip_serializing_if = "Option::is_none")]
237    pub path: Option<String>,
238}
239
240/// Snapshot of open file descriptors for a process.
241#[derive(Debug, Clone, Serialize)]
242pub struct FdSnapshot {
243    /// Schema identifier for version detection.
244    pub schema_id: &'static str,
245
246    /// Timestamp of snapshot (ISO 8601).
247    pub timestamp: String,
248
249    /// Current platform (e.g., "linux", "macos", "windows").
250    pub platform: &'static str,
251
252    /// Target PID.
253    pub pid: u32,
254
255    /// List of open file descriptors.
256    pub fds: Vec<FdInfo>,
257
258    /// Warnings about partial visibility.
259    pub warnings: Vec<String>,
260}
261
262/// Options controlling optional process detail collection.
263///
264/// These options are additive and opt-in. Existing APIs default to both values
265/// disabled to avoid extra syscall/parse overhead.
266#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
267#[serde(default, deny_unknown_fields)]
268pub struct ProcessOptions {
269    /// Include environment variables in `ProcessInfo.env`.
270    ///
271    /// Platform notes:
272    /// - Linux/macOS: best-effort for visible processes.
273    /// - Windows: currently unsupported in v0.1.14 (`env` remains `None`).
274    pub include_env: bool,
275
276    /// Include thread count in `ProcessInfo.thread_count`.
277    pub include_threads: bool,
278}
279
280impl ProcessOptions {
281    /// Enable environment variable collection.
282    pub fn with_env(mut self) -> Self {
283        self.include_env = true;
284        self
285    }
286
287    /// Enable thread count collection.
288    pub fn with_threads(mut self) -> Self {
289        self.include_threads = true;
290        self
291    }
292}
293
294/// Safety caps for environment collection when proc_ext is enabled.
295#[cfg(all(feature = "proc_ext", unix))]
296pub(crate) const MAX_ENV_ENTRIES: usize = 1024;
297#[cfg(all(feature = "proc_ext", unix))]
298pub(crate) const MAX_ENV_KEY_BYTES: usize = 1024;
299#[cfg(all(feature = "proc_ext", unix))]
300pub(crate) const MAX_ENV_VALUE_BYTES: usize = 4096;
301#[cfg(all(feature = "proc_ext", unix))]
302pub(crate) const MAX_ENV_TOTAL_BYTES: usize = 1_048_576;
303
304/// Information about a single process.
305///
306/// All fields are populated on a best-effort basis. Fields that cannot be read
307/// (e.g., due to permissions) are set to default values or `None`.
308#[derive(Debug, Clone, Serialize)]
309pub struct ProcessInfo {
310    /// Process ID.
311    pub pid: u32,
312
313    /// Parent process ID.
314    pub ppid: u32,
315
316    /// Process name (executable name, max 255 chars).
317    pub name: String,
318
319    /// Owner username (None if unavailable due to permissions).
320    #[serde(skip_serializing_if = "Option::is_none")]
321    pub user: Option<String>,
322
323    /// CPU usage normalized 0-100 across all cores.
324    ///
325    /// Note: This is an instantaneous value and may be 0 for short-lived
326    /// processes or processes that were just started.
327    pub cpu_percent: f64,
328
329    /// Memory usage in kilobytes.
330    pub memory_kb: u64,
331
332    /// Seconds since process start.
333    pub elapsed_seconds: u64,
334
335    /// Process start time (Unix epoch milliseconds), when available.
336    ///
337    /// Best-effort: omitted if the platform cannot provide it or access is denied.
338    #[serde(skip_serializing_if = "Option::is_none")]
339    pub start_time_unix_ms: Option<u64>,
340
341    /// Executable path (absolute), when available.
342    ///
343    /// Best-effort: omitted if the platform cannot provide it or access is denied.
344    #[serde(skip_serializing_if = "Option::is_none")]
345    pub exe_path: Option<String>,
346
347    /// Process state.
348    pub state: ProcessState,
349
350    /// Command line arguments.
351    ///
352    /// May be empty if command line cannot be read (permissions, zombie process).
353    pub cmdline: Vec<String>,
354
355    /// Process environment variables (best-effort, opt-in via `ProcessOptions`).
356    #[serde(skip_serializing_if = "Option::is_none")]
357    pub env: Option<BTreeMap<String, String>>,
358
359    /// Thread count (best-effort, opt-in via `ProcessOptions`).
360    #[serde(skip_serializing_if = "Option::is_none")]
361    pub thread_count: Option<u32>,
362}
363
364/// Process state.
365///
366/// Maps platform-specific states to a common enum.
367#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
368#[serde(rename_all = "snake_case")]
369pub enum ProcessState {
370    /// Process is running or runnable.
371    Running,
372    /// Process is sleeping (interruptible or uninterruptible).
373    Sleeping,
374    /// Process is stopped (e.g., by a signal).
375    Stopped,
376    /// Process is a zombie (terminated but not reaped).
377    Zombie,
378    /// Process state could not be determined.
379    Unknown,
380}
381
382/// Liveness classification of a PID.
383///
384/// Internal to the crate; the public surface is the [`is_live`] / [`is_fully_gone`]
385/// predicates. Kept as a three-state enum so a zombie is distinguishable from a
386/// fully-reaped process on platforms where that distinction is observable.
387///
388/// `Zombie` has no analogue on Windows (a PID is either live or gone), so the
389/// Windows probe never constructs it; `allow(dead_code)` there keeps the shared
390/// enum intact without tripping `-D warnings`.
391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
392#[cfg_attr(windows, allow(dead_code))]
393pub(crate) enum Liveness {
394    /// The process exists and is in a live (non-zombie) state.
395    Live,
396    /// The process has exited but has not yet been reaped (Unix zombie).
397    Zombie,
398    /// No process record exists for the PID (never existed, or fully reaped).
399    Gone,
400}
401
402/// Filter for process queries.
403///
404/// All fields are optional. Processes must match ALL specified criteria (AND logic).
405/// Unknown fields in JSON input will result in `InvalidArgument` error.
406#[derive(Debug, Clone, Default, Deserialize)]
407#[serde(deny_unknown_fields)]
408pub struct ProcessFilter {
409    /// Filter by process name substring (case-insensitive).
410    pub name_contains: Option<String>,
411
412    /// Filter by exact process name (case-sensitive).
413    pub name_equals: Option<String>,
414
415    /// Filter by owner username (exact match).
416    pub user_equals: Option<String>,
417
418    /// Filter to specific PIDs.
419    pub pid_in: Option<Vec<u32>>,
420
421    /// Filter by parent PID.
422    pub ppid: Option<u32>,
423
424    /// Filter by process state.
425    pub state_in: Option<Vec<ProcessState>>,
426
427    /// Filter by minimum CPU usage (0-100).
428    pub cpu_above: Option<f64>,
429
430    /// Filter by minimum memory usage in KB.
431    pub memory_above_kb: Option<u64>,
432
433    /// Filter by minimum process age in seconds.
434    ///
435    /// Uses `elapsed_seconds` (best-effort, already cross-platform).
436    pub running_for_at_least_secs: Option<u64>,
437}
438
439impl ProcessFilter {
440    /// Validate filter values.
441    ///
442    /// Returns an error if any values are out of range.
443    pub fn validate(&self) -> SysprimsResult<()> {
444        if let Some(cpu) = self.cpu_above {
445            if !(0.0..=100.0).contains(&cpu) {
446                return Err(SysprimsError::invalid_argument(
447                    "cpu_above must be between 0 and 100",
448                ));
449            }
450        }
451        Ok(())
452    }
453}
454
455fn validate_process_options(options: &ProcessOptions) -> SysprimsResult<()> {
456    #[cfg(feature = "proc_ext")]
457    {
458        let _ = options;
459    }
460
461    #[cfg(not(feature = "proc_ext"))]
462    {
463        if options.include_env || options.include_threads {
464            return Err(SysprimsError::invalid_argument(
465                "include_env/include_threads require the proc_ext feature",
466            ));
467        }
468    }
469
470    Ok(())
471}
472
473impl PortFilter {
474    /// Validate filter values.
475    pub fn validate(&self) -> SysprimsResult<()> {
476        if let Some(port) = self.local_port {
477            if port == 0 {
478                return Err(SysprimsError::invalid_argument(
479                    "local_port must be between 1 and 65535",
480                ));
481            }
482        }
483        Ok(())
484    }
485
486    pub fn schema_id() -> &'static str {
487        PORT_FILTER_V1
488    }
489}
490
491impl FdInfo {
492    fn matches(&self, filter: &FdFilter) -> bool {
493        if let Some(kind) = filter.kind {
494            if self.kind != kind {
495                return false;
496            }
497        }
498
499        true
500    }
501}
502
503impl PortBinding {
504    fn matches(&self, filter: &PortFilter) -> bool {
505        if let Some(protocol) = filter.protocol {
506            if self.protocol != protocol {
507                return false;
508            }
509        }
510
511        if let Some(port) = filter.local_port {
512            if self.local_port != port {
513                return false;
514            }
515        }
516
517        true
518    }
519}
520
521impl ProcessFilter {
522    /// Check if a process matches this filter.
523    fn matches(&self, proc: &ProcessInfo) -> bool {
524        // Name contains (case-insensitive)
525        if let Some(ref pattern) = self.name_contains {
526            if !proc.name.to_lowercase().contains(&pattern.to_lowercase()) {
527                return false;
528            }
529        }
530
531        // Name equals (exact)
532        if let Some(ref name) = self.name_equals {
533            if proc.name != *name {
534                return false;
535            }
536        }
537
538        // User equals
539        if let Some(ref user) = self.user_equals {
540            match &proc.user {
541                Some(proc_user) if proc_user == user => {}
542                _ => return false,
543            }
544        }
545
546        // PID in list
547        if let Some(ref pids) = self.pid_in {
548            if !pids.contains(&proc.pid) {
549                return false;
550            }
551        }
552
553        // Parent PID
554        if let Some(ppid) = self.ppid {
555            if proc.ppid != ppid {
556                return false;
557            }
558        }
559
560        // State in list
561        if let Some(ref states) = self.state_in {
562            if !states.contains(&proc.state) {
563                return false;
564            }
565        }
566
567        // CPU above threshold
568        if let Some(threshold) = self.cpu_above {
569            if proc.cpu_percent < threshold {
570                return false;
571            }
572        }
573
574        // Memory above threshold
575        if let Some(threshold) = self.memory_above_kb {
576            if proc.memory_kb < threshold {
577                return false;
578            }
579        }
580
581        // Process age (minimum elapsed seconds)
582        if let Some(min_secs) = self.running_for_at_least_secs {
583            if proc.elapsed_seconds < min_secs {
584                return false;
585            }
586        }
587
588        true
589    }
590}
591
592// ============================================================================
593// Public API
594// ============================================================================
595
596/// Get a snapshot of all processes.
597///
598/// Returns a list of all processes visible to the current user. Processes that
599/// cannot be read (e.g., due to permissions) are silently skipped.
600///
601/// # Examples
602///
603/// ```rust,no_run
604/// // Replaces: ps -eo pid,comm
605/// let snap = sysprims_proc::snapshot().unwrap();
606/// for proc in &snap.processes {
607///     println!("{}: {}", proc.pid, proc.name);
608/// }
609/// ```
610pub fn snapshot() -> SysprimsResult<ProcessSnapshot> {
611    snapshot_with_options(ProcessOptions::default())
612}
613
614/// Get a snapshot of all processes with optional extended fields.
615///
616/// # Examples
617///
618/// ```rust,no_run
619/// use sysprims_proc::ProcessOptions;
620///
621/// // Replaces: ps -M -p <pid> plus line counting
622/// let snap = sysprims_proc::snapshot_with_options(ProcessOptions::default().with_threads()).unwrap();
623/// println!("{} processes", snap.processes.len());
624/// ```
625pub fn snapshot_with_options(options: ProcessOptions) -> SysprimsResult<ProcessSnapshot> {
626    validate_process_options(&options)?;
627    platform::snapshot_impl(&options)
628}
629
630/// Get total CPU time consumed by a process (kernel + user) in nanoseconds.
631///
632/// This is a best-effort value used for sampling-based CPU calculations.
633///
634/// Notes:
635/// - The existing `ProcessInfo.cpu_percent` is a lifetime-average estimate.
636/// - For near-instant CPU usage, callers should sample this value twice and
637///   compute a rate over an interval.
638///
639/// # Examples
640///
641/// ```rust,no_run
642/// let pid = std::process::id();
643/// // Replaces: parsing top/ps CPU time columns
644/// let total_ns = sysprims_proc::cpu_total_time_ns(pid).unwrap();
645/// println!("cpu total ns: {}", total_ns);
646/// ```
647pub fn cpu_total_time_ns(pid: u32) -> SysprimsResult<u64> {
648    const MAX_SAFE_PID: u32 = i32::MAX as u32;
649
650    if pid == 0 {
651        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
652    }
653    if pid > MAX_SAFE_PID {
654        return Err(SysprimsError::invalid_argument(format!(
655            "PID {} exceeds maximum safe value {}",
656            pid, MAX_SAFE_PID
657        )));
658    }
659    platform::cpu_total_time_ns_impl(pid)
660}
661
662/// Get a snapshot of listening ports.
663///
664/// # Examples
665///
666/// ```rust,no_run
667/// use sysprims_proc::{listening_ports, PortFilter, Protocol};
668///
669/// // Replaces: lsof -nP -iTCP -sTCP:LISTEN
670/// let filter = PortFilter {
671///     protocol: Some(Protocol::Tcp),
672///     local_port: Some(8080),
673/// };
674/// let snap = listening_ports(Some(&filter)).unwrap();
675/// println!("bindings: {}", snap.bindings.len());
676/// ```
677pub fn listening_ports(filter: Option<&PortFilter>) -> SysprimsResult<PortBindingsSnapshot> {
678    let filter = filter.cloned().unwrap_or_default();
679    filter.validate()?;
680
681    let mut snapshot = platform::listening_ports_impl()?;
682    if filter.protocol.is_some() || filter.local_port.is_some() {
683        snapshot.bindings.retain(|binding| binding.matches(&filter));
684    }
685
686    if snapshot.bindings.is_empty() && snapshot.warnings.is_empty() {
687        let platform = get_platform();
688        return Err(SysprimsError::not_supported("port bindings", platform));
689    }
690
691    Ok(snapshot)
692}
693
694/// List open file descriptors for a PID.
695///
696/// Best-effort cross-platform behavior:
697/// - Linux: enumerates `/proc/<pid>/fd` symlinks.
698/// - macOS: enumerates via libproc (`proc_pidinfo(PROC_PIDLISTFDS)`) and attempts path recovery.
699/// - Windows: returns NotSupported.
700///
701/// # Examples
702///
703/// ```rust,no_run
704/// let pid = std::process::id();
705/// // Replaces: lsof -p <pid>
706/// let snap = sysprims_proc::list_fds(pid, None).unwrap();
707/// println!("fd count: {}", snap.fds.len());
708/// ```
709pub fn list_fds(pid: u32, filter: Option<&FdFilter>) -> SysprimsResult<FdSnapshot> {
710    // Safety: avoid negative pid_t casting semantics on Unix.
711    const MAX_SAFE_PID: u32 = i32::MAX as u32;
712    if pid == 0 {
713        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
714    }
715    if pid > MAX_SAFE_PID {
716        return Err(SysprimsError::invalid_argument(format!(
717            "PID {} exceeds maximum safe value {}",
718            pid, MAX_SAFE_PID
719        )));
720    }
721
722    let filter = filter.cloned().unwrap_or_default();
723    filter.validate()?;
724
725    let (mut fds, mut warnings) = platform::list_fds_impl(pid)?;
726    if filter.kind.is_some() {
727        fds.retain(|fd| fd.matches(&filter));
728    }
729
730    // Best-effort: provide a helpful warning if nothing visible.
731    if fds.is_empty() {
732        warnings.push("No file descriptors visible".to_string());
733    }
734
735    Ok(make_fd_snapshot(pid, fds, warnings))
736}
737
738/// Resolve a process by port and protocol.
739///
740/// # Examples
741///
742/// ```rust,no_run
743/// use sysprims_proc::Protocol;
744///
745/// // Replaces: lsof -nP -iTCP:8080 -sTCP:LISTEN
746/// let proc = sysprims_proc::process_by_port(8080, Protocol::Tcp).unwrap();
747/// println!("{} {}", proc.pid, proc.name);
748/// ```
749pub fn process_by_port(port: u16, protocol: Protocol) -> SysprimsResult<ProcessInfo> {
750    if port == 0 {
751        return Err(SysprimsError::invalid_argument(
752            "port must be between 1 and 65535",
753        ));
754    }
755
756    let filter = PortFilter {
757        protocol: Some(protocol),
758        local_port: Some(port),
759    };
760    let snapshot = listening_ports(Some(&filter))?;
761    let binding = snapshot
762        .bindings
763        .into_iter()
764        .find(|binding| binding.pid.is_some())
765        .ok_or_else(|| SysprimsError::not_found(port as u32))?;
766
767    match binding.process {
768        Some(process) => Ok(process),
769        None => binding
770            .pid
771            .map(get_process)
772            .unwrap_or_else(|| Err(SysprimsError::not_found(port as u32))),
773    }
774}
775
776#[cfg(unix)]
777fn aggregate_permission_warning(skipped: usize, label: &str) -> Option<String> {
778    if skipped == 0 {
779        None
780    } else {
781        Some(format!(
782            "Skipped {} {} due to permission errors",
783            skipped, label
784        ))
785    }
786}
787
788fn aggregate_error_warning(skipped: usize, label: &str) -> Option<String> {
789    if skipped == 0 {
790        None
791    } else {
792        Some(format!("Skipped {} {} due to read errors", skipped, label))
793    }
794}
795
796/// Get a snapshot with filter applied.
797///
798/// Filters are applied after enumeration. All filter criteria must match (AND logic).
799///
800/// # Examples
801///
802/// ```rust,no_run
803/// use sysprims_proc::ProcessFilter;
804///
805/// // Replaces: ps output grep/awk pipelines
806/// let filter = ProcessFilter {
807///     name_contains: Some("nginx".into()),
808///     cpu_above: Some(1.0),
809///     ..Default::default()
810/// };
811/// let snap = sysprims_proc::snapshot_filtered(&filter).unwrap();
812/// ```
813pub fn snapshot_filtered(filter: &ProcessFilter) -> SysprimsResult<ProcessSnapshot> {
814    snapshot_filtered_with_options(filter, ProcessOptions::default())
815}
816
817/// Get a snapshot with filter applied and optional extended fields.
818///
819/// # Examples
820///
821/// ```rust,no_run
822/// use sysprims_proc::{ProcessFilter, ProcessOptions};
823///
824/// // Replaces: ps filters that require brittle grep/awk chains
825/// let filter = ProcessFilter {
826///     name_contains: Some("worker".into()),
827///     ..Default::default()
828/// };
829/// let snap = sysprims_proc::snapshot_filtered_with_options(
830///     &filter,
831///     ProcessOptions::default().with_threads(),
832/// )
833/// .unwrap();
834/// println!("{}", snap.processes.len());
835/// ```
836pub fn snapshot_filtered_with_options(
837    filter: &ProcessFilter,
838    options: ProcessOptions,
839) -> SysprimsResult<ProcessSnapshot> {
840    filter.validate()?;
841    validate_process_options(&options)?;
842
843    let mut snap = snapshot_with_options(options)?;
844    snap.processes.retain(|p| filter.matches(p));
845    Ok(snap)
846}
847
848/// Get information for a single process.
849///
850/// # Errors
851///
852/// Returns `NotFound` if the process does not exist.
853/// Returns `PermissionDenied` if the process cannot be read.
854///
855/// # Liveness and zombies (cross-platform note)
856///
857/// This function reports a process's *record*, not a normalized liveness answer,
858/// and the two platforms diverge for an exited-but-unreaped child. On Linux the
859/// kernel keeps the PID in the process table with state
860/// [`ProcessState::Zombie`] until the parent reaps it, so `get_process` returns
861/// `Ok(_)` with `state == Zombie`. On macOS the same PID typically becomes
862/// unreadable almost immediately, so `get_process` returns `Err(NotFound)`.
863///
864/// Treating `Ok(_)` as "alive" is therefore not portable. When you need "is this
865/// process actually still running?" use [`is_live`] (returns `false` for zombies
866/// on every platform); for "is every trace of it gone?" use [`is_fully_gone`]; to
867/// block until exit, use [`wait_pid`]. If you keep using `get_process`, inspect
868/// [`ProcessInfo::state`] and treat [`ProcessState::Zombie`] as not-running.
869///
870/// # Examples
871///
872/// ```rust,no_run
873/// // Replaces: ps -p <pid> -o ... plus parsing
874/// let self_info = sysprims_proc::get_process(std::process::id()).unwrap();
875/// println!("Current process: {}", self_info.name);
876/// ```
877pub fn get_process(pid: u32) -> SysprimsResult<ProcessInfo> {
878    get_process_with_options(pid, ProcessOptions::default())
879}
880
881/// Get information for a single process with optional extended fields.
882///
883/// # Examples
884///
885/// ```rust,no_run
886/// use sysprims_proc::ProcessOptions;
887///
888/// // Replaces: ps eww -p <pid> when you need env/threads
889/// let pid = std::process::id();
890/// let proc = sysprims_proc::get_process_with_options(pid, ProcessOptions::default().with_threads()).unwrap();
891/// println!("threads: {:?}", proc.thread_count);
892/// ```
893pub fn get_process_with_options(pid: u32, options: ProcessOptions) -> SysprimsResult<ProcessInfo> {
894    const MAX_SAFE_PID: u32 = i32::MAX as u32;
895
896    if pid == 0 {
897        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
898    }
899    if pid > MAX_SAFE_PID {
900        return Err(SysprimsError::invalid_argument(format!(
901            "PID {} exceeds maximum safe value {}",
902            pid, MAX_SAFE_PID
903        )));
904    }
905    validate_process_options(&options)?;
906    platform::get_process_impl(pid, &options)
907}
908
909// ============================================================================
910// Descendants API
911// ============================================================================
912
913/// A single level in a descendants result.
914#[derive(Debug, Clone, Serialize)]
915pub struct DescendantsLevel {
916    /// Depth level (1 = direct children, 2 = grandchildren, etc.).
917    pub level: u32,
918
919    /// Processes at this level.
920    pub processes: Vec<ProcessInfo>,
921}
922
923/// Result of a descendants traversal.
924#[derive(Debug, Clone, Serialize)]
925pub struct DescendantsResult {
926    /// Schema identifier for version detection.
927    pub schema_id: &'static str,
928
929    /// Root PID that was traversed from.
930    pub root_pid: u32,
931
932    /// Maximum depth that was requested.
933    pub max_levels: u32,
934
935    /// Processes grouped by depth level.
936    pub levels: Vec<DescendantsLevel>,
937
938    /// Total number of descendant processes found (before filtering).
939    pub total_found: usize,
940
941    /// Number of processes matching the filter (after filtering).
942    pub matched_by_filter: usize,
943
944    /// Timestamp (ISO 8601).
945    pub timestamp: String,
946
947    /// Platform identifier.
948    pub platform: &'static str,
949}
950
951/// CPU measurement mode for descendants traversal.
952#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
953#[serde(rename_all = "snake_case")]
954pub enum CpuMode {
955    /// Lifetime-average CPU usage (best-effort), normalized to 0-100.
956    #[default]
957    Lifetime,
958
959    /// Sampled CPU usage over an interval (Activity Monitor / top style).
960    ///
961    /// Sampled values may exceed 100 when a process uses multiple cores.
962    Monitor,
963}
964
965/// Configuration for descendants traversal.
966#[derive(Debug, Clone)]
967pub struct DescendantsConfig {
968    /// PID to start traversal from.
969    pub root_pid: u32,
970
971    /// Maximum depth (1 = children only). `None` means traverse all levels.
972    pub max_levels: Option<u32>,
973
974    /// Optional process filter applied after traversal.
975    pub filter: Option<ProcessFilter>,
976
977    /// CPU measurement mode used before applying `cpu_above` filters.
978    pub cpu_mode: CpuMode,
979
980    /// Optional sample interval used when `cpu_mode = Monitor`.
981    ///
982    /// Defaults to 1 second when omitted.
983    pub sample_duration: Option<Duration>,
984}
985
986/// Get descendants of a process using BFS traversal.
987///
988/// Performs a single snapshot and builds a parent→children map, then traverses
989/// from `root_pid` up to `max_levels` deep. An optional filter is applied to
990/// the results after traversal.
991///
992/// # Arguments
993///
994/// * `root_pid` - PID to start traversal from (must exist).
995/// * `max_levels` - Maximum depth (1 = children only, u32::MAX = all).
996/// * `filter` - Optional filter applied to descendant processes.
997///
998/// # Safety
999///
1000/// Validates `root_pid` against ADR-0011 forbidden values (0, > i32::MAX).
1001///
1002/// # Examples
1003///
1004/// ```rust,no_run
1005/// // Replaces: pstree/ps --ppid traversal and text parsing
1006/// let root = std::process::id();
1007/// let result = sysprims_proc::descendants(root, 1, None).unwrap();
1008/// println!("matched: {}", result.matched_by_filter);
1009/// ```
1010pub fn descendants(
1011    root_pid: u32,
1012    max_levels: u32,
1013    filter: Option<&ProcessFilter>,
1014) -> SysprimsResult<DescendantsResult> {
1015    descendants_with_options(root_pid, max_levels, filter, ProcessOptions::default())
1016}
1017
1018/// Get descendants of a process using BFS traversal with optional extended fields.
1019///
1020/// # Examples
1021///
1022/// ```rust,no_run
1023/// use sysprims_proc::{ProcessOptions, ProcessFilter};
1024///
1025/// // Replaces: pstree + ad hoc enrichment for thread/env fields
1026/// let root = std::process::id();
1027/// let filter = ProcessFilter {
1028///     cpu_above: Some(1.0),
1029///     ..Default::default()
1030/// };
1031/// let result = sysprims_proc::descendants_with_options(
1032///     root,
1033///     2,
1034///     Some(&filter),
1035///     ProcessOptions::default().with_threads(),
1036/// )
1037/// .unwrap();
1038/// println!("levels: {}", result.levels.len());
1039/// ```
1040pub fn descendants_with_options(
1041    root_pid: u32,
1042    max_levels: u32,
1043    filter: Option<&ProcessFilter>,
1044    options: ProcessOptions,
1045) -> SysprimsResult<DescendantsResult> {
1046    descendants_with_config_and_options(
1047        DescendantsConfig {
1048            root_pid,
1049            max_levels: Some(max_levels),
1050            filter: filter.cloned(),
1051            cpu_mode: CpuMode::Lifetime,
1052            sample_duration: None,
1053        },
1054        options,
1055    )
1056}
1057
1058/// Get descendants using explicit traversal configuration.
1059///
1060/// # Examples
1061///
1062/// ```rust,no_run
1063/// use std::time::Duration;
1064/// use sysprims_proc::{CpuMode, DescendantsConfig};
1065///
1066/// // Replaces: repeated ps sampling loops for active CPU trees
1067/// let result = sysprims_proc::descendants_with_config(DescendantsConfig {
1068///     root_pid: std::process::id(),
1069///     max_levels: Some(2),
1070///     filter: None,
1071///     cpu_mode: CpuMode::Monitor,
1072///     sample_duration: Some(Duration::from_millis(500)),
1073/// })
1074/// .unwrap();
1075/// println!("total: {}", result.total_found);
1076/// ```
1077pub fn descendants_with_config(config: DescendantsConfig) -> SysprimsResult<DescendantsResult> {
1078    descendants_with_config_and_options(config, ProcessOptions::default())
1079}
1080
1081/// Select descendant target PIDs from a traversal result.
1082///
1083/// This helper is intended for remediation workflows (for example,
1084/// `kill-descendants` and `guard_step`) that need to compute a deterministic
1085/// target set from one traversal snapshot.
1086///
1087/// When `cascade` is `false`, the result contains only matched descendant PIDs.
1088/// When `cascade` is `true`, each matched PID is expanded to include its
1089/// descendants within the already traversed tree.
1090///
1091/// Returned PIDs are sorted, deduplicated, and never include `root_pid`.
1092pub fn select_descendant_targets(
1093    result: &DescendantsResult,
1094    filter: Option<&ProcessFilter>,
1095    cascade: bool,
1096) -> Vec<u32> {
1097    let all_procs: Vec<&ProcessInfo> = result
1098        .levels
1099        .iter()
1100        .flat_map(|l| l.processes.iter())
1101        .collect();
1102
1103    let matched_roots: Vec<u32> = all_procs
1104        .iter()
1105        .filter(|p| filter.map(|f| f.matches(p)).unwrap_or(true))
1106        .map(|p| p.pid)
1107        .collect();
1108
1109    if !cascade {
1110        let mut out = matched_roots;
1111        out.sort_unstable();
1112        out.dedup();
1113        out.retain(|&pid| pid != result.root_pid);
1114        return out;
1115    }
1116
1117    let mut children_map: HashMap<u32, Vec<u32>> = HashMap::new();
1118    for proc in all_procs {
1119        children_map.entry(proc.ppid).or_default().push(proc.pid);
1120    }
1121
1122    let mut expanded: HashSet<u32> = HashSet::new();
1123    for root in matched_roots {
1124        let mut stack = vec![root];
1125        while let Some(pid) = stack.pop() {
1126            if !expanded.insert(pid) {
1127                continue;
1128            }
1129            if let Some(children) = children_map.get(&pid) {
1130                stack.extend(children.iter().copied());
1131            }
1132        }
1133    }
1134
1135    let mut out: Vec<u32> = expanded.into_iter().collect();
1136    out.sort_unstable();
1137    out.retain(|&pid| pid != result.root_pid);
1138    out
1139}
1140
1141/// Rule configuration for one guard evaluation cycle.
1142#[derive(Debug, Clone)]
1143pub struct GuardRule {
1144    /// Root PID used for descendants traversal.
1145    pub root_pid: u32,
1146
1147    /// Maximum descendants traversal depth.
1148    pub max_levels: u32,
1149
1150    /// Optional descendants filter.
1151    pub filter: Option<ProcessFilter>,
1152
1153    /// CPU measurement mode used for `cpu_above` filtering.
1154    pub cpu_mode: CpuMode,
1155
1156    /// Optional sampling interval used when `cpu_mode = Monitor`.
1157    pub sample_duration: Option<Duration>,
1158}
1159
1160/// Action configuration for one guard evaluation cycle.
1161#[derive(Debug, Clone)]
1162pub enum GuardAction {
1163    /// Kill descendant processes matching the rule.
1164    KillDescendants {
1165        /// Signal number to send.
1166        signal: i32,
1167        /// Expand each matched PID to include its descendant subtree.
1168        cascade: bool,
1169    },
1170}
1171
1172/// Configuration for one guard evaluation cycle.
1173#[derive(Debug, Clone)]
1174pub struct GuardConfig {
1175    /// Rule used to evaluate descendants.
1176    pub rule: GuardRule,
1177    /// Action to run after evaluation.
1178    pub action: GuardAction,
1179    /// Explicit action gate. Defaults should be false at call sites.
1180    pub action_enabled: bool,
1181    /// Hard cap on number of signaled targets when action is enabled.
1182    pub max_targets: u32,
1183}
1184
1185/// Structured output for one guard evaluation cycle.
1186#[derive(Debug, Clone, Serialize)]
1187pub struct GuardEvent {
1188    /// Schema identifier for version detection.
1189    pub schema_id: &'static str,
1190    /// Event timestamp (ISO 8601).
1191    pub timestamp: String,
1192    /// Platform identifier.
1193    pub platform: &'static str,
1194    /// Number of descendants matching the rule filter.
1195    pub matched: u32,
1196    /// Number of targets selected for action after safety/cap checks.
1197    pub targeted: u32,
1198    /// Number of successful kills in this cycle.
1199    pub killed: u32,
1200    /// Number of failed kills in this cycle.
1201    pub failed: u32,
1202    /// Number of targets skipped by safety exclusions.
1203    pub skipped_safety: u32,
1204    /// Non-fatal warnings.
1205    pub warnings: Vec<String>,
1206}
1207
1208/// Execute one guard evaluation cycle.
1209///
1210/// This function performs descendants evaluation and optional remediation behind
1211/// an explicit action gate (`action_enabled`).
1212pub fn guard_step(config: GuardConfig) -> SysprimsResult<GuardEvent> {
1213    const MAX_SAFE_PID: u32 = i32::MAX as u32;
1214
1215    if config.rule.root_pid == 0 {
1216        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
1217    }
1218    if config.rule.root_pid > MAX_SAFE_PID {
1219        return Err(SysprimsError::invalid_argument(format!(
1220            "PID {} exceeds maximum safe value {}",
1221            config.rule.root_pid, MAX_SAFE_PID
1222        )));
1223    }
1224    if config.max_targets == 0 {
1225        return Err(SysprimsError::invalid_argument("max_targets must be >= 1"));
1226    }
1227    if let Some(f) = config.rule.filter.as_ref() {
1228        f.validate()?;
1229    }
1230
1231    let desc = descendants_with_config_and_options(
1232        DescendantsConfig {
1233            root_pid: config.rule.root_pid,
1234            max_levels: Some(config.rule.max_levels),
1235            filter: None,
1236            cpu_mode: config.rule.cpu_mode,
1237            sample_duration: config.rule.sample_duration,
1238        },
1239        ProcessOptions::default(),
1240    )?;
1241
1242    let matched_pids = select_descendant_targets(&desc, config.rule.filter.as_ref(), false);
1243    let matched = matched_pids.len() as u32;
1244
1245    let (signal, cascade) = match config.action {
1246        GuardAction::KillDescendants { signal, cascade } => (signal, cascade),
1247    };
1248
1249    let mut warnings = Vec::new();
1250    if !config.action_enabled {
1251        warnings.push("action disabled; no signals sent".to_string());
1252        return Ok(GuardEvent {
1253            schema_id: GUARD_EVENT_V1,
1254            timestamp: now_rfc3339(),
1255            platform: get_platform(),
1256            matched,
1257            targeted: 0,
1258            killed: 0,
1259            failed: 0,
1260            skipped_safety: 0,
1261            warnings,
1262        });
1263    }
1264
1265    let mut target_pids = select_descendant_targets(&desc, config.rule.filter.as_ref(), cascade);
1266
1267    if target_pids.len() > config.max_targets as usize {
1268        target_pids.truncate(config.max_targets as usize);
1269        warnings.push(format!(
1270            "target count capped at max_targets={} for this cycle",
1271            config.max_targets
1272        ));
1273    }
1274
1275    let self_pid = std::process::id();
1276    let parent_pid = get_process(self_pid).ok().map(|p| p.ppid);
1277
1278    let before = target_pids.len();
1279    target_pids.retain(|&pid| pid != self_pid && pid != 1 && pid != config.rule.root_pid);
1280    if let Some(ppid) = parent_pid {
1281        target_pids.retain(|&pid| pid != ppid);
1282    }
1283    let skipped_safety = before.saturating_sub(target_pids.len()) as u32;
1284    if skipped_safety > 0 {
1285        warnings.push(format!(
1286            "skipped {} unsafe target(s) (self/PID1/parent/root)",
1287            skipped_safety
1288        ));
1289    }
1290
1291    if target_pids.is_empty() {
1292        return Ok(GuardEvent {
1293            schema_id: GUARD_EVENT_V1,
1294            timestamp: now_rfc3339(),
1295            platform: get_platform(),
1296            matched,
1297            targeted: 0,
1298            killed: 0,
1299            failed: 0,
1300            skipped_safety,
1301            warnings,
1302        });
1303    }
1304
1305    let batch = sysprims_signal::kill_many(&target_pids, signal)?;
1306
1307    Ok(GuardEvent {
1308        schema_id: GUARD_EVENT_V1,
1309        timestamp: now_rfc3339(),
1310        platform: get_platform(),
1311        matched,
1312        targeted: target_pids.len() as u32,
1313        killed: batch.succeeded.len() as u32,
1314        failed: batch.failed.len() as u32,
1315        skipped_safety,
1316        warnings,
1317    })
1318}
1319
1320#[cfg(any(test, target_os = "linux", target_os = "macos"))]
1321fn is_sysprims_binary_name(name: &str) -> bool {
1322    name == "sysprims" || name.starts_with("sysprims-")
1323}
1324
1325#[cfg(any(test, target_os = "linux", target_os = "macos"))]
1326fn guard_discovery_name(cmdline: &[String], fallback_name: &str) -> Option<String> {
1327    let binary = cmdline.first()?.rsplit('/').next().unwrap_or(fallback_name);
1328    if !is_sysprims_binary_name(binary) {
1329        return None;
1330    }
1331
1332    let guard_index = cmdline.iter().position(|arg| arg == "guard")?;
1333    let root_pid = cmdline.get(guard_index + 1)?;
1334    if root_pid.parse::<u32>().ok()? == 0 {
1335        return None;
1336    }
1337
1338    Some(format!("sysprims-guard:{root_pid}"))
1339}
1340
1341#[cfg(target_os = "linux")]
1342fn set_guard_process_title(root_pid: u32) {
1343    let title = format!("sysprims-guard:{root_pid}");
1344    let truncated = title.bytes().take(15).collect::<Vec<_>>();
1345    if let Ok(c_title) = std::ffi::CString::new(truncated) {
1346        unsafe {
1347            libc::prctl(
1348                libc::PR_SET_NAME,
1349                c_title.as_ptr() as libc::c_ulong,
1350                0,
1351                0,
1352                0,
1353            );
1354        }
1355    }
1356}
1357
1358#[cfg(target_os = "macos")]
1359fn set_guard_process_title(root_pid: u32) {
1360    unsafe extern "C" {
1361        fn pthread_setname_np(name: *const libc::c_char) -> libc::c_int;
1362    }
1363
1364    let title = format!("sysprims-guard:{root_pid}");
1365    let thread_title = std::ffi::CString::new(title.bytes().take(63).collect::<Vec<_>>()).ok();
1366
1367    unsafe {
1368        if let Some(name) = thread_title.as_ref() {
1369            let _ = pthread_setname_np(name.as_ptr());
1370        }
1371    }
1372}
1373
1374#[cfg(not(any(target_os = "linux", target_os = "macos")))]
1375fn set_guard_process_title(_root_pid: u32) {}
1376
1377// ============================================================================
1378// GuardRunner: Managed Guard Loop
1379// ============================================================================
1380
1381/// Preset configurations for common guard use cases.
1382///
1383/// Presets provide sensible defaults for interval and sample duration.
1384/// Explicit values always override preset defaults.
1385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1386pub enum GuardPreset {
1387    /// Short interval for interactive debugging (3s interval, 2s sample).
1388    Interactive,
1389    /// Moderate interval for background monitoring (3m interval, 3s sample).
1390    Background,
1391    /// Long interval for lightweight watchdog (5m interval, 5s sample).
1392    Watchdog,
1393}
1394
1395impl GuardPreset {
1396    /// Default tick interval for this preset.
1397    pub fn interval(&self) -> Duration {
1398        match self {
1399            Self::Interactive => Duration::from_secs(3),
1400            Self::Background => Duration::from_secs(180),
1401            Self::Watchdog => Duration::from_secs(300),
1402        }
1403    }
1404
1405    /// Default CPU sample duration for this preset.
1406    pub fn sample_duration(&self) -> Duration {
1407        match self {
1408            Self::Interactive => Duration::from_secs(2),
1409            Self::Background => Duration::from_secs(3),
1410            Self::Watchdog => Duration::from_secs(5),
1411        }
1412    }
1413}
1414
1415/// Configuration for a managed guard loop.
1416#[derive(Debug, Clone)]
1417pub struct GuardRunnerConfig {
1418    /// Per-tick evaluation configuration.
1419    pub guard: GuardConfig,
1420    /// Tick interval between evaluations.
1421    pub interval: Duration,
1422    /// Maximum number of ticks before auto-stop (None = unlimited).
1423    pub max_iterations: Option<u64>,
1424}
1425
1426/// Summary returned after a guard loop completes.
1427#[derive(Debug, Clone)]
1428pub struct GuardRunnerSummary {
1429    /// Total number of ticks executed.
1430    pub ticks: u64,
1431    /// Reason the loop stopped.
1432    pub stop_reason: StopReason,
1433}
1434
1435/// Why the guard loop stopped.
1436#[derive(Debug, Clone, PartialEq, Eq)]
1437pub enum StopReason {
1438    /// Received SIGINT or SIGTERM.
1439    Signal,
1440    /// Reached max_iterations limit.
1441    MaxIterations,
1442    /// Stopped via [`GuardStopHandle::stop()`].
1443    Requested,
1444}
1445
1446/// Cloneable, thread-safe handle for stopping a running guard loop.
1447///
1448/// Obtain via [`GuardRunner::stop_handle()`] before calling [`GuardRunner::run()`].
1449/// Can be sent to another thread, stored in a signal handler, or used from
1450/// an async runtime to request graceful shutdown.
1451///
1452/// # Example
1453///
1454/// ```no_run
1455/// use std::time::Duration;
1456/// use sysprims_proc::{
1457///     GuardRunnerConfig, GuardRunner, GuardConfig, GuardRule, GuardAction,
1458///     CpuMode,
1459/// };
1460///
1461/// let config = GuardRunnerConfig {
1462///     guard: GuardConfig {
1463///         rule: GuardRule {
1464///             root_pid: 12345,
1465///             max_levels: u32::MAX,
1466///             filter: None,
1467///             cpu_mode: CpuMode::Lifetime,
1468///             sample_duration: None,
1469///         },
1470///         action: GuardAction::KillDescendants { signal: 15, cascade: false },
1471///         action_enabled: false,
1472///         max_targets: 8,
1473///     },
1474///     interval: Duration::from_secs(5),
1475///     max_iterations: None,
1476/// };
1477///
1478/// let mut runner = GuardRunner::new(config).unwrap();
1479/// let handle = runner.stop_handle();
1480///
1481/// // Stop from another thread after 30 seconds
1482/// std::thread::spawn(move || {
1483///     std::thread::sleep(Duration::from_secs(30));
1484///     handle.stop();
1485/// });
1486///
1487/// let summary = runner.run(|event| {
1488///     println!("matched={}", event.matched);
1489/// }, |_tick, err| {
1490///     eprintln!("error: {err}");
1491/// }).unwrap();
1492/// // summary.stop_reason == StopReason::Requested
1493/// ```
1494#[derive(Clone)]
1495pub struct GuardStopHandle {
1496    /// Programmatic stop flag — set by stop(), distinct from signal flag.
1497    requested: Arc<std::sync::atomic::AtomicBool>,
1498    /// Write-only handle to GuardSignals' stop flag.
1499    signals_flag: guard_signals::StopFlagHandle,
1500    /// Clone of SignalManager — calling stop() unblocks listen().
1501    manager: guard_signals::SignalManager,
1502}
1503
1504impl GuardStopHandle {
1505    /// Request the guard loop to stop gracefully.
1506    ///
1507    /// The loop will finish the current tick and then exit with
1508    /// [`StopReason::Requested`].
1509    pub fn stop(&self) {
1510        self.requested
1511            .store(true, std::sync::atomic::Ordering::SeqCst);
1512        // Set the GuardSignals stop flag so should_stop() returns true
1513        self.signals_flag.set();
1514        // Unblock the signal listener thread
1515        self.manager.stop();
1516    }
1517}
1518
1519impl std::fmt::Debug for GuardStopHandle {
1520    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1521        f.debug_struct("GuardStopHandle")
1522            .field(
1523                "requested",
1524                &self.requested.load(std::sync::atomic::Ordering::SeqCst),
1525            )
1526            .finish()
1527    }
1528}
1529
1530/// Managed guard loop with signal handling and drift-free scheduling.
1531///
1532/// `GuardRunner` wraps `guard_step()` in a tick loop with `GuardSignals`
1533/// for clean shutdown and `Tick` for drift-free scheduling.
1534///
1535/// # Usage
1536///
1537/// 1. Create with [`GuardRunner::new()`]
1538/// 2. Obtain a [`GuardStopHandle`] via [`stop_handle()`](Self::stop_handle)
1539///    (optional — only needed for programmatic stop from another thread)
1540/// 3. Call [`run()`](Self::run) — blocks until signal, max_iterations, or stop handle
1541///
1542/// # Example
1543///
1544/// ```no_run
1545/// use std::time::Duration;
1546/// use sysprims_proc::{
1547///     GuardRunnerConfig, GuardRunner, GuardConfig, GuardRule, GuardAction,
1548///     CpuMode,
1549/// };
1550///
1551/// let config = GuardRunnerConfig {
1552///     guard: GuardConfig {
1553///         rule: GuardRule {
1554///             root_pid: 12345,
1555///             max_levels: u32::MAX,
1556///             filter: None,
1557///             cpu_mode: CpuMode::Lifetime,
1558///             sample_duration: None,
1559///         },
1560///         action: GuardAction::KillDescendants { signal: 15, cascade: false },
1561///         action_enabled: false,
1562///         max_targets: 8,
1563///     },
1564///     interval: Duration::from_secs(60),
1565///     max_iterations: Some(10),
1566/// };
1567///
1568/// let mut runner = GuardRunner::new(config).unwrap();
1569/// let summary = runner.run(|event| {
1570///     println!("matched={}", event.matched);
1571/// }, |_tick, err| {
1572///     eprintln!("error: {err}");
1573/// }).unwrap();
1574/// println!("stopped after {} ticks: {:?}", summary.ticks, summary.stop_reason);
1575/// ```
1576pub struct GuardRunner {
1577    config: GuardRunnerConfig,
1578    signals: guard_signals::GuardSignals,
1579    tick: time::Tick,
1580    /// Tracks whether stop was requested programmatically (vs signal).
1581    stop_requested: Arc<std::sync::atomic::AtomicBool>,
1582}
1583
1584impl GuardRunner {
1585    /// Create a new runner. Sets up signal handlers and tick scheduler.
1586    ///
1587    /// Does not start the loop — call [`run()`](Self::run) to begin.
1588    pub fn new(config: GuardRunnerConfig) -> SysprimsResult<Self> {
1589        let signals = guard_signals::GuardSignals::start()?;
1590        let tick = time::Tick::new(config.interval)?;
1591        Ok(Self {
1592            config,
1593            signals,
1594            tick,
1595            stop_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
1596        })
1597    }
1598
1599    /// Get a cloneable stop handle for this runner.
1600    ///
1601    /// The handle can be sent to another thread and used to request
1602    /// graceful shutdown while [`run()`](Self::run) is active.
1603    pub fn stop_handle(&self) -> GuardStopHandle {
1604        GuardStopHandle {
1605            requested: Arc::clone(&self.stop_requested),
1606            signals_flag: self.signals.stop_flag_handle(),
1607            manager: self.signals.manager().clone(),
1608        }
1609    }
1610
1611    /// Run the guard loop, calling `on_event` after each tick.
1612    ///
1613    /// Blocks until a shutdown signal, `max_iterations`, or
1614    /// [`GuardStopHandle::stop()`].
1615    ///
1616    /// Errors from individual `guard_step()` calls are passed to `on_error`;
1617    /// the loop continues unless stopped.
1618    pub fn run<F, E>(
1619        &mut self,
1620        mut on_event: F,
1621        mut on_error: E,
1622    ) -> SysprimsResult<GuardRunnerSummary>
1623    where
1624        F: FnMut(&GuardEvent),
1625        E: FnMut(u64, &SysprimsError),
1626    {
1627        let mut tick_count: u64 = 0;
1628
1629        set_guard_process_title(self.config.guard.rule.root_pid);
1630
1631        while !self.signals.should_stop() {
1632            match guard_step(self.config.guard.clone()) {
1633                Ok(event) => {
1634                    tick_count += 1;
1635                    on_event(&event);
1636                }
1637                Err(e) => {
1638                    tick_count += 1;
1639                    on_error(tick_count, &e);
1640                }
1641            }
1642
1643            // Check max_iterations
1644            if let Some(max) = self.config.max_iterations {
1645                if tick_count >= max {
1646                    return Ok(GuardRunnerSummary {
1647                        ticks: tick_count,
1648                        stop_reason: StopReason::MaxIterations,
1649                    });
1650                }
1651            }
1652
1653            // Check stop flag before sleeping (signal may arrive during tick)
1654            if self.signals.should_stop() {
1655                break;
1656            }
1657
1658            self.tick.sleep_until_next();
1659        }
1660
1661        let reason = if self
1662            .stop_requested
1663            .load(std::sync::atomic::Ordering::SeqCst)
1664        {
1665            StopReason::Requested
1666        } else {
1667            StopReason::Signal
1668        };
1669
1670        Ok(GuardRunnerSummary {
1671            ticks: tick_count,
1672            stop_reason: reason,
1673        })
1674    }
1675
1676    /// Access the underlying signal controller (for testing).
1677    pub fn signals(&self) -> &guard_signals::GuardSignals {
1678        &self.signals
1679    }
1680}
1681
1682// ============================================================================
1683// Ancestors API
1684// ============================================================================
1685
1686/// Result of an ancestors traversal.
1687#[derive(Debug, Clone, Serialize)]
1688pub struct AncestorsResult {
1689    /// Schema identifier for version detection.
1690    pub schema_id: &'static str,
1691
1692    /// ISO 8601 timestamp.
1693    pub timestamp: String,
1694
1695    /// Platform identifier.
1696    pub platform: &'static str,
1697
1698    /// Starting PID that was queried.
1699    pub pid: u32,
1700
1701    /// Ancestor chain from the starting PID upward (pid -> parent -> grandparent -> ...).
1702    pub chain: Vec<ProcessInfo>,
1703
1704    /// Non-fatal warnings (loop detected, permission denied, etc.).
1705    pub warnings: Vec<String>,
1706}
1707
1708/// Walk the parent chain from `pid` upward, collecting process info at each step.
1709///
1710/// Stops when:
1711/// - PID becomes 0 or 1 (init/launchd)
1712/// - `max_depth` is reached
1713/// - A process is not found or permission is denied (recorded as warning)
1714/// - A loop is detected (PID repeats)
1715///
1716/// The starting PID itself is included as the first element of the chain.
1717///
1718/// # Errors
1719///
1720/// - `InvalidArgument` if `pid` is 0 or exceeds `i32::MAX`
1721/// - `NotFound` if the starting PID does not exist
1722///
1723/// # Examples
1724///
1725/// ```rust,no_run
1726/// use sysprims_proc::{ancestors, ProcessOptions};
1727///
1728/// let result = sysprims_proc::ancestors(std::process::id(), 10, ProcessOptions::default()).unwrap();
1729/// for p in &result.chain {
1730///     println!("PID {} ({})", p.pid, p.name);
1731/// }
1732/// ```
1733pub fn ancestors(
1734    pid: u32,
1735    max_depth: u32,
1736    options: ProcessOptions,
1737) -> SysprimsResult<AncestorsResult> {
1738    const MAX_SAFE_PID: u32 = i32::MAX as u32;
1739
1740    if pid == 0 {
1741        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
1742    }
1743    if pid > MAX_SAFE_PID {
1744        return Err(SysprimsError::invalid_argument(format!(
1745            "PID {} exceeds maximum safe value {}",
1746            pid, MAX_SAFE_PID
1747        )));
1748    }
1749    validate_process_options(&options)?;
1750
1751    let mut chain = Vec::new();
1752    let mut warnings = Vec::new();
1753    let mut seen = HashSet::new();
1754    let mut current_pid = pid;
1755
1756    for depth in 0..=max_depth {
1757        if !seen.insert(current_pid) {
1758            warnings.push(format!(
1759                "loop detected: PID {} already visited at depth {}",
1760                current_pid, depth
1761            ));
1762            break;
1763        }
1764
1765        match get_process_with_options(current_pid, options) {
1766            Ok(info) => {
1767                let next_pid = info.ppid;
1768                chain.push(info);
1769
1770                // Stop at init/launchd (PID 0 or 1) or if ppid == self (root process)
1771                if next_pid == 0 || next_pid == 1 || next_pid == current_pid {
1772                    // Include PID 1 in chain if we can read it
1773                    if next_pid == 1 && current_pid != 1 {
1774                        match get_process_with_options(1, options) {
1775                            Ok(init_info) => chain.push(init_info),
1776                            Err(_) => {
1777                                warnings.push("could not read init/launchd (PID 1)".to_string());
1778                            }
1779                        }
1780                    }
1781                    break;
1782                }
1783
1784                current_pid = next_pid;
1785            }
1786            Err(e) => {
1787                if depth == 0 {
1788                    // Starting PID must exist
1789                    return Err(e);
1790                }
1791                warnings.push(format!(
1792                    "ancestor walk stopped at PID {}: {}",
1793                    current_pid, e
1794                ));
1795                break;
1796            }
1797        }
1798    }
1799
1800    Ok(AncestorsResult {
1801        schema_id: ANCESTORS_RESULT_V1,
1802        timestamp: now_rfc3339(),
1803        platform: get_platform(),
1804        pid,
1805        chain,
1806        warnings,
1807    })
1808}
1809
1810/// Get descendants using explicit traversal configuration and optional extended fields.
1811///
1812/// # Examples
1813///
1814/// ```rust,no_run
1815/// use sysprims_proc::{CpuMode, DescendantsConfig, ProcessOptions};
1816///
1817/// // Replaces: custom parent-child map logic plus ps parsing
1818/// let result = sysprims_proc::descendants_with_config_and_options(
1819///     DescendantsConfig {
1820///         root_pid: std::process::id(),
1821///         max_levels: Some(1),
1822///         filter: None,
1823///         cpu_mode: CpuMode::Lifetime,
1824///         sample_duration: None,
1825///     },
1826///     ProcessOptions::default().with_threads(),
1827/// )
1828/// .unwrap();
1829/// println!("{}", result.matched_by_filter);
1830/// ```
1831pub fn descendants_with_config_and_options(
1832    config: DescendantsConfig,
1833    options: ProcessOptions,
1834) -> SysprimsResult<DescendantsResult> {
1835    const MAX_SAFE_PID: u32 = i32::MAX as u32;
1836
1837    if config.root_pid == 0 {
1838        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
1839    }
1840    if config.root_pid > MAX_SAFE_PID {
1841        return Err(SysprimsError::invalid_argument(format!(
1842            "PID {} exceeds maximum safe value {}",
1843            config.root_pid, MAX_SAFE_PID
1844        )));
1845    }
1846
1847    validate_process_options(&options)?;
1848
1849    if let Some(f) = config.filter.as_ref() {
1850        f.validate()?;
1851    }
1852
1853    // Verify root exists before any traversal/sampling work.
1854    let _ = get_process_with_options(config.root_pid, options)?;
1855
1856    // Snapshot for consistent traversal; monitor mode samples at the snapshot level.
1857    let snap = snapshot_for_descendants(options, config.cpu_mode, config.sample_duration)?;
1858
1859    // Build parent → children map.
1860    let mut children_map: HashMap<u32, Vec<ProcessInfo>> = HashMap::new();
1861    for proc in snap.processes {
1862        children_map.entry(proc.ppid).or_default().push(proc);
1863    }
1864
1865    // BFS traversal.
1866    let mut levels: Vec<DescendantsLevel> = Vec::new();
1867    let mut current_pids = vec![config.root_pid];
1868    let mut total_found: usize = 0;
1869    let max_levels = config.max_levels.unwrap_or(u32::MAX);
1870
1871    for depth in 1..=max_levels {
1872        let mut level_procs = Vec::new();
1873        let mut next_pids = Vec::new();
1874
1875        for &pid in &current_pids {
1876            if let Some(children) = children_map.get(&pid) {
1877                for child in children {
1878                    level_procs.push(child.clone());
1879                    next_pids.push(child.pid);
1880                }
1881            }
1882        }
1883
1884        if level_procs.is_empty() {
1885            break;
1886        }
1887
1888        total_found += level_procs.len();
1889        levels.push(DescendantsLevel {
1890            level: depth,
1891            processes: level_procs,
1892        });
1893        current_pids = next_pids;
1894    }
1895
1896    // Apply filter if provided.
1897    let mut matched_by_filter = total_found;
1898    if let Some(f) = config.filter.as_ref() {
1899        for level in &mut levels {
1900            level.processes.retain(|p| f.matches(p));
1901        }
1902        matched_by_filter = levels.iter().map(|l| l.processes.len()).sum();
1903        // Remove empty levels after filtering.
1904        levels.retain(|l| !l.processes.is_empty());
1905    }
1906
1907    Ok(DescendantsResult {
1908        schema_id: match config.cpu_mode {
1909            CpuMode::Lifetime => DESCENDANTS_RESULT_V1,
1910            CpuMode::Monitor => DESCENDANTS_RESULT_SAMPLED_V1,
1911        },
1912        root_pid: config.root_pid,
1913        max_levels,
1914        levels,
1915        total_found,
1916        matched_by_filter,
1917        timestamp: now_rfc3339(),
1918        platform: get_platform(),
1919    })
1920}
1921
1922fn snapshot_for_descendants(
1923    options: ProcessOptions,
1924    cpu_mode: CpuMode,
1925    sample_duration: Option<Duration>,
1926) -> SysprimsResult<ProcessSnapshot> {
1927    match cpu_mode {
1928        CpuMode::Lifetime => snapshot_with_options(options),
1929        CpuMode::Monitor => {
1930            let sample = sample_duration.unwrap_or_else(|| Duration::from_secs(1));
1931            snapshot_with_sampled_cpu(options, sample)
1932        }
1933    }
1934}
1935
1936fn snapshot_with_sampled_cpu(
1937    options: ProcessOptions,
1938    sample_duration: Duration,
1939) -> SysprimsResult<ProcessSnapshot> {
1940    if sample_duration.is_zero() {
1941        return Err(SysprimsError::invalid_argument(
1942            "sample duration must be > 0",
1943        ));
1944    }
1945
1946    let snap0 = snapshot_with_options(options)?;
1947    let mut t0 = HashMap::<u32, (Option<u64>, u64)>::new();
1948    for p in &snap0.processes {
1949        if let Ok(cpu_ns) = cpu_total_time_ns(p.pid) {
1950            t0.insert(p.pid, (p.start_time_unix_ms, cpu_ns));
1951        }
1952    }
1953
1954    std::thread::sleep(sample_duration);
1955
1956    let mut snap1 = snapshot_with_options(options)?;
1957    let dt_ns = sample_duration.as_nanos() as f64;
1958    if dt_ns > 0.0 {
1959        for p in &mut snap1.processes {
1960            if let Some((start0, cpu0)) = t0.get(&p.pid) {
1961                // PID reuse guard: only compute if start time matches.
1962                if start0.is_some()
1963                    && p.start_time_unix_ms.is_some()
1964                    && start0 != &p.start_time_unix_ms
1965                {
1966                    continue;
1967                }
1968
1969                if let Ok(cpu1) = cpu_total_time_ns(p.pid) {
1970                    let delta = cpu1.saturating_sub(*cpu0) as f64;
1971                    p.cpu_percent = (delta / dt_ns) * 100.0;
1972                }
1973            }
1974        }
1975    }
1976
1977    // Sampled CPU semantics can exceed 100 on multi-core.
1978    snap1.schema_id = PROCESS_INFO_SAMPLED_V1;
1979    Ok(snap1)
1980}
1981
1982/// Wait for a PID to exit, up to the provided timeout.
1983///
1984/// Returns:
1985/// - `Ok` with `timed_out=true` if the process did not exit in time.
1986/// - `Ok` with `exited=true` if the process was observed to have exited.
1987/// - `Err(NotFound)` if the PID does not exist at the time of the first check.
1988/// - `Err(PermissionDenied)` if the platform forbids even querying liveness.
1989///
1990/// # Examples
1991///
1992/// ```rust,no_run
1993/// use std::time::Duration;
1994///
1995/// // Replaces: while kill -0 <pid>; do sleep ...; done
1996/// let res = sysprims_proc::wait_pid(std::process::id(), Duration::from_millis(1)).unwrap();
1997/// println!("timed_out: {}", res.timed_out);
1998/// ```
1999pub fn wait_pid(pid: u32, timeout: Duration) -> SysprimsResult<WaitPidResult> {
2000    const MAX_SAFE_PID: u32 = i32::MAX as u32;
2001
2002    if pid == 0 {
2003        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
2004    }
2005    if pid > MAX_SAFE_PID {
2006        return Err(SysprimsError::invalid_argument(format!(
2007            "PID {} exceeds maximum safe value {}",
2008            pid, MAX_SAFE_PID
2009        )));
2010    }
2011    platform::wait_pid_impl(pid, timeout)
2012}
2013
2014/// Report whether a PID refers to a live (non-zombie) process.
2015///
2016/// This is the portable answer to "did the process I just signalled actually
2017/// stop running?". It normalizes a divergence that [`get_process`] exposes: an
2018/// exited-but-unreaped child is a *zombie* still present in the process table on
2019/// Linux but is typically already unreadable on macOS. `is_live` returns `false`
2020/// for a zombie on every platform. Windows has no Unix-style zombie, so a PID is
2021/// simply live or gone.
2022///
2023/// To keep that answer portable, this predicate treats a present-but-unreadable
2024/// PID (the state a killed-but-unreaped child reaches on macOS) as *not live*.
2025/// That is a deliberate liveness bias for the kill-then-check pattern, not a
2026/// diagnostic: when you need a process's full record, use [`get_process`] and
2027/// inspect [`ProcessInfo::state`] directly.
2028///
2029/// This is a single-shot probe (no waiting). To block until exit, use
2030/// [`wait_pid`]; for "is every trace of the process gone?" use [`is_fully_gone`].
2031///
2032/// This answers liveness at a PID *slot*, not process *identity*: PIDs are
2033/// reused, so this is not a security or identity boundary. It is safe for the
2034/// "did the child I just signalled stop?" pattern because the parent holds the
2035/// unreaped slot until it reaps, so the PID cannot recycle underneath the check.
2036///
2037/// # Errors
2038///
2039/// - `InvalidArgument` for PID 0 or a PID above `i32::MAX` (rejected before any
2040///   platform probe, per the PID-safety rule in ADR-0011).
2041/// - `PermissionDenied` if the platform forbids querying the PID. This is rare
2042///   for caller-owned children (the primary use case), which are always
2043///   queryable by their parent.
2044///
2045/// # Examples
2046///
2047/// ```rust,no_run
2048/// // Replaces: kill -0 <pid> plus a zombie-state check
2049/// assert!(sysprims_proc::is_live(std::process::id()).unwrap());
2050/// ```
2051pub fn is_live(pid: u32) -> SysprimsResult<bool> {
2052    const MAX_SAFE_PID: u32 = i32::MAX as u32;
2053
2054    if pid == 0 {
2055        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
2056    }
2057    if pid > MAX_SAFE_PID {
2058        return Err(SysprimsError::invalid_argument(format!(
2059            "PID {} exceeds maximum safe value {}",
2060            pid, MAX_SAFE_PID
2061        )));
2062    }
2063    Ok(platform::liveness_impl(pid)? == Liveness::Live)
2064}
2065
2066/// Report whether a PID has no observable process record (fully gone).
2067///
2068/// Unlike [`is_live`], this distinguishes a *zombie* (exited but not yet reaped)
2069/// from a *fully reaped* process: a zombie is neither live nor fully gone, so
2070/// `is_fully_gone` returns `false` for it. Use this when a test or supervisor
2071/// needs to assert that cleanup has completed and the PID slot is free.
2072///
2073/// This is a single-shot probe (no waiting).
2074///
2075/// # Errors
2076///
2077/// - `InvalidArgument` for PID 0 or a PID above `i32::MAX` (rejected before any
2078///   platform probe, per the PID-safety rule in ADR-0011).
2079/// - `PermissionDenied` if the platform forbids querying the PID (the process
2080///   exists but cannot be classified).
2081///
2082/// # Examples
2083///
2084/// ```rust,no_run
2085/// let pid = std::process::id();
2086/// assert!(!sysprims_proc::is_fully_gone(pid).unwrap());
2087/// ```
2088pub fn is_fully_gone(pid: u32) -> SysprimsResult<bool> {
2089    const MAX_SAFE_PID: u32 = i32::MAX as u32;
2090
2091    if pid == 0 {
2092        return Err(SysprimsError::invalid_argument("PID 0 is not valid"));
2093    }
2094    if pid > MAX_SAFE_PID {
2095        return Err(SysprimsError::invalid_argument(format!(
2096            "PID {} exceeds maximum safe value {}",
2097            pid, MAX_SAFE_PID
2098        )));
2099    }
2100    Ok(platform::liveness_impl(pid)? == Liveness::Gone)
2101}
2102
2103// ============================================================================
2104// Helpers
2105// ============================================================================
2106
2107fn make_port_snapshot(bindings: Vec<PortBinding>, warnings: Vec<String>) -> PortBindingsSnapshot {
2108    let mut warnings = warnings;
2109    if bindings.is_empty() {
2110        warnings.push("No listening ports found".to_string());
2111    }
2112
2113    PortBindingsSnapshot {
2114        schema_id: PORT_BINDINGS_V1,
2115        timestamp: now_rfc3339(),
2116        platform: get_platform(),
2117        bindings,
2118        warnings,
2119    }
2120}
2121
2122fn make_fd_snapshot(pid: u32, fds: Vec<FdInfo>, warnings: Vec<String>) -> FdSnapshot {
2123    FdSnapshot {
2124        schema_id: FD_SNAPSHOT_V1,
2125        timestamp: now_rfc3339(),
2126        platform: get_platform(),
2127        pid,
2128        fds,
2129        warnings,
2130    }
2131}
2132
2133// Timestamp generation consolidated in sysprims_core::time::now_rfc3339()
2134
2135/// Create a ProcessSnapshot with the standard schema ID.
2136fn make_snapshot(processes: Vec<ProcessInfo>) -> ProcessSnapshot {
2137    ProcessSnapshot {
2138        schema_id: PROCESS_INFO_V1,
2139        timestamp: now_rfc3339(),
2140        processes,
2141    }
2142}
2143
2144fn make_wait_pid_result(
2145    pid: u32,
2146    exited: bool,
2147    timed_out: bool,
2148    exit_code: Option<i32>,
2149    warnings: Vec<String>,
2150) -> WaitPidResult {
2151    WaitPidResult {
2152        schema_id: WAIT_PID_RESULT_V1,
2153        timestamp: now_rfc3339(),
2154        platform: get_platform(),
2155        pid,
2156        exited,
2157        timed_out,
2158        exit_code,
2159        warnings,
2160    }
2161}
2162
2163// ============================================================================
2164// Tests
2165// ============================================================================
2166
2167#[cfg(test)]
2168mod tests {
2169    use super::*;
2170    use std::process::{Child, Command, Stdio};
2171    use std::thread;
2172
2173    #[test]
2174    fn test_snapshot_not_empty() {
2175        let snap = snapshot().unwrap();
2176        assert!(
2177            !snap.processes.is_empty(),
2178            "Snapshot should contain processes"
2179        );
2180    }
2181
2182    #[test]
2183    fn test_snapshot_has_schema_id() {
2184        let snap = snapshot().unwrap();
2185        assert_eq!(snap.schema_id, PROCESS_INFO_V1);
2186        assert!(snap.schema_id.contains("process-info"));
2187    }
2188
2189    #[test]
2190    fn test_snapshot_has_timestamp() {
2191        let snap = snapshot().unwrap();
2192        assert!(!snap.timestamp.is_empty());
2193        // Should be RFC3339 format
2194        assert!(snap.timestamp.contains('T'));
2195        assert!(snap.timestamp.contains('Z') || snap.timestamp.contains('+'));
2196    }
2197
2198    #[test]
2199    #[cfg(unix)]
2200    fn test_snapshot_has_processes() {
2201        // On macOS with SIP, we may only see user-owned processes
2202        // On Linux without root, we may also be restricted
2203        // Just verify we get a reasonable number of processes
2204        let snap = snapshot().unwrap();
2205
2206        // We should at least see our own process
2207        let own_pid = std::process::id();
2208        let has_self = snap.processes.iter().any(|p| p.pid == own_pid);
2209        assert!(has_self, "Snapshot should include our own process");
2210
2211        // We should see at least a few processes
2212        assert!(
2213            snap.processes.len() >= 3,
2214            "Should have at least a few visible processes, got {}",
2215            snap.processes.len()
2216        );
2217    }
2218
2219    #[test]
2220    fn test_get_self() {
2221        let pid = std::process::id();
2222        let info = get_process(pid).unwrap();
2223        assert_eq!(info.pid, pid);
2224        assert!(!info.name.is_empty(), "Process should have a name");
2225    }
2226
2227    #[test]
2228    #[cfg(target_os = "macos")]
2229    fn test_own_process_has_cmdline() {
2230        let snap = snapshot().unwrap();
2231        let own_pid = std::process::id();
2232        let own_proc = snap
2233            .processes
2234            .iter()
2235            .find(|p| p.pid == own_pid)
2236            .expect("Should find own process in snapshot");
2237        assert!(
2238            !own_proc.cmdline.is_empty(),
2239            "Own process should have cmdline, got empty"
2240        );
2241    }
2242
2243    #[test]
2244    fn test_get_self_has_valid_fields() {
2245        let pid = std::process::id();
2246        let info = get_process(pid).unwrap();
2247
2248        // CPU percent should be in valid range
2249        assert!(info.cpu_percent >= 0.0);
2250        assert!(info.cpu_percent <= 100.0);
2251
2252        // Memory should be non-zero for running process
2253        // Note: Don't require this as some systems may report 0
2254        assert!(info.memory_kb < u64::MAX);
2255
2256        // Identity fields are best-effort; if present, they should be reasonable.
2257        if let Some(ms) = info.start_time_unix_ms {
2258            assert!(ms > 0);
2259        }
2260        if let Some(ref exe) = info.exe_path {
2261            assert!(!exe.is_empty());
2262        }
2263
2264        // State should be running (we're executing)
2265        // Note: Windows reports Unknown as it doesn't expose process state simply
2266        assert!(
2267            info.state == ProcessState::Running
2268                || info.state == ProcessState::Sleeping
2269                || info.state == ProcessState::Unknown,
2270            "Test process should be running, sleeping, or unknown (Windows)"
2271        );
2272    }
2273
2274    #[test]
2275    fn test_wait_pid_self_times_out() {
2276        let pid = std::process::id();
2277        let r = wait_pid(pid, Duration::from_millis(1)).unwrap();
2278        assert_eq!(r.pid, pid);
2279        assert!(r.timed_out);
2280        assert!(!r.exited);
2281    }
2282
2283    /// ADR-0011: every public pid-taking entrypoint must reject PID 0 and PIDs
2284    /// above `i32::MAX` *before* any `pid as pid_t` cast could produce a
2285    /// negative/broadcast PID. These inputs must never reach a syscall.
2286    #[test]
2287    fn pid_taking_entrypoints_reject_unsafe_pids() {
2288        let over_max = (i32::MAX as u32) + 1;
2289        for &pid in &[0u32, over_max, u32::MAX] {
2290            assert!(
2291                matches!(get_process(pid), Err(SysprimsError::InvalidArgument { .. })),
2292                "get_process must reject unsafe PID {pid}"
2293            );
2294            assert!(
2295                matches!(
2296                    wait_pid(pid, Duration::from_millis(1)),
2297                    Err(SysprimsError::InvalidArgument { .. })
2298                ),
2299                "wait_pid must reject unsafe PID {pid}"
2300            );
2301            assert!(
2302                matches!(
2303                    cpu_total_time_ns(pid),
2304                    Err(SysprimsError::InvalidArgument { .. })
2305                ),
2306                "cpu_total_time_ns must reject unsafe PID {pid}"
2307            );
2308        }
2309    }
2310
2311    #[test]
2312    fn test_filter_by_name_contains() {
2313        // Filter for our own test process
2314        let filter = ProcessFilter {
2315            name_contains: Some("sysprims".into()),
2316            ..Default::default()
2317        };
2318        let snap = snapshot_filtered(&filter).unwrap();
2319
2320        for proc in &snap.processes {
2321            assert!(
2322                proc.name.to_lowercase().contains("sysprims"),
2323                "Filtered process '{}' should contain 'sysprims'",
2324                proc.name
2325            );
2326        }
2327    }
2328
2329    #[test]
2330    fn test_guard_discovery_name_matches_guard_cmdline() {
2331        let cmdline = vec![
2332            "/usr/local/bin/sysprims".to_string(),
2333            "guard".to_string(),
2334            "27776".to_string(),
2335            "--preset".to_string(),
2336            "watchdog".to_string(),
2337        ];
2338
2339        assert_eq!(
2340            guard_discovery_name(&cmdline, "sysprims"),
2341            Some("sysprims-guard:27776".to_string())
2342        );
2343    }
2344
2345    #[test]
2346    fn test_guard_discovery_name_ignores_non_guard_cmdline() {
2347        let cmdline = vec![
2348            "/usr/local/bin/sysprims".to_string(),
2349            "pstat".to_string(),
2350            "--json".to_string(),
2351        ];
2352
2353        assert_eq!(guard_discovery_name(&cmdline, "sysprims"), None);
2354    }
2355
2356    #[test]
2357    fn test_guard_discovery_name_rejects_invalid_root_pid() {
2358        let cmdline = vec![
2359            "/usr/local/bin/sysprims".to_string(),
2360            "guard".to_string(),
2361            "not-a-pid".to_string(),
2362        ];
2363
2364        assert_eq!(guard_discovery_name(&cmdline, "sysprims"), None);
2365    }
2366
2367    #[test]
2368    fn test_filter_by_pid() {
2369        let my_pid = std::process::id();
2370        let filter = ProcessFilter {
2371            pid_in: Some(vec![my_pid]),
2372            ..Default::default()
2373        };
2374        let snap = snapshot_filtered(&filter).unwrap();
2375
2376        assert_eq!(snap.processes.len(), 1);
2377        assert_eq!(snap.processes[0].pid, my_pid);
2378    }
2379
2380    #[test]
2381    fn test_filter_validation_cpu_range() {
2382        let filter = ProcessFilter {
2383            cpu_above: Some(150.0),
2384            ..Default::default()
2385        };
2386        let result = filter.validate();
2387        assert!(result.is_err());
2388
2389        let filter = ProcessFilter {
2390            cpu_above: Some(-1.0),
2391            ..Default::default()
2392        };
2393        let result = filter.validate();
2394        assert!(result.is_err());
2395
2396        let filter = ProcessFilter {
2397            cpu_above: Some(50.0),
2398            ..Default::default()
2399        };
2400        let result = filter.validate();
2401        assert!(result.is_ok());
2402    }
2403
2404    #[test]
2405    fn test_nonexistent_pid() {
2406        // Use a very high PID that shouldn't exist
2407        let result = get_process(99999999);
2408        assert!(
2409            matches!(result, Err(SysprimsError::NotFound { .. })),
2410            "Should return NotFound for nonexistent PID"
2411        );
2412    }
2413
2414    #[test]
2415    fn test_invalid_pid_zero() {
2416        let result = get_process(0);
2417        assert!(
2418            matches!(result, Err(SysprimsError::InvalidArgument { .. })),
2419            "PID 0 should be invalid"
2420        );
2421    }
2422
2423    #[test]
2424    fn test_cpu_normalized() {
2425        let snap = snapshot().unwrap();
2426        for proc in &snap.processes {
2427            assert!(
2428                proc.cpu_percent >= 0.0,
2429                "CPU percent for PID {} should be >= 0",
2430                proc.pid
2431            );
2432            assert!(
2433                proc.cpu_percent <= 100.0,
2434                "CPU percent for PID {} should be <= 100, got {}",
2435                proc.pid,
2436                proc.cpu_percent
2437            );
2438        }
2439    }
2440
2441    #[test]
2442    fn test_process_state_serialization() {
2443        // Test that states serialize to snake_case
2444        let json = serde_json::to_string(&ProcessState::Running).unwrap();
2445        assert_eq!(json, "\"running\"");
2446
2447        let json = serde_json::to_string(&ProcessState::Sleeping).unwrap();
2448        assert_eq!(json, "\"sleeping\"");
2449
2450        let json = serde_json::to_string(&ProcessState::Zombie).unwrap();
2451        assert_eq!(json, "\"zombie\"");
2452    }
2453
2454    #[test]
2455    fn test_filter_deserialization() {
2456        let json = r#"{"name_contains": "test", "cpu_above": 5.0}"#;
2457        let filter: ProcessFilter = serde_json::from_str(json).unwrap();
2458        assert_eq!(filter.name_contains, Some("test".to_string()));
2459        assert_eq!(filter.cpu_above, Some(5.0));
2460    }
2461
2462    #[test]
2463    fn test_filter_unknown_field_rejected() {
2464        let json = r#"{"unknown_field": "value"}"#;
2465        let result: Result<ProcessFilter, _> = serde_json::from_str(json);
2466        assert!(result.is_err(), "Unknown fields should be rejected");
2467    }
2468
2469    #[test]
2470    fn test_port_filter_unknown_field_rejected() {
2471        let json = r#"{"unknown_field": true}"#;
2472        let result: Result<PortFilter, _> = serde_json::from_str(json);
2473        assert!(result.is_err(), "Unknown fields should be rejected");
2474    }
2475
2476    #[test]
2477    fn test_port_filter_schema_id() {
2478        assert!(PortFilter::schema_id().contains("port-filter"));
2479    }
2480
2481    #[test]
2482    fn test_process_options_builder() {
2483        let opts = ProcessOptions::default();
2484        assert!(!opts.include_env);
2485        assert!(!opts.include_threads);
2486
2487        let opts = ProcessOptions::default().with_env().with_threads();
2488        assert!(opts.include_env);
2489        assert!(opts.include_threads);
2490    }
2491
2492    #[test]
2493    fn test_get_process_with_default_options_has_no_proc_ext_fields() {
2494        let pid = std::process::id();
2495        let info = get_process_with_options(pid, ProcessOptions::default()).unwrap();
2496        assert!(info.env.is_none());
2497        assert!(info.thread_count.is_none());
2498    }
2499
2500    #[test]
2501    #[cfg(feature = "proc_ext")]
2502    fn test_get_process_with_threads_populates_thread_count() {
2503        let pid = std::process::id();
2504        let info = get_process_with_options(pid, ProcessOptions::default().with_threads()).unwrap();
2505        assert!(info.thread_count.is_some());
2506    }
2507
2508    #[test]
2509    #[cfg(all(feature = "proc_ext", unix))]
2510    fn test_get_process_with_env_populates_env_map() {
2511        let pid = std::process::id();
2512        let info = get_process_with_options(pid, ProcessOptions::default().with_env()).unwrap();
2513        assert!(info.env.is_some());
2514    }
2515
2516    #[test]
2517    #[cfg(not(feature = "proc_ext"))]
2518    fn test_proc_ext_options_rejected_when_feature_disabled() {
2519        let pid = std::process::id();
2520        let err = get_process_with_options(pid, ProcessOptions::default().with_env()).unwrap_err();
2521        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2522    }
2523
2524    #[test]
2525    fn test_descendants_with_config_lifetime_self() {
2526        let pid = std::process::id();
2527        let config = DescendantsConfig {
2528            root_pid: pid,
2529            max_levels: Some(1),
2530            filter: None,
2531            cpu_mode: CpuMode::Lifetime,
2532            sample_duration: None,
2533        };
2534
2535        let result = descendants_with_config(config).unwrap();
2536        assert_eq!(result.root_pid, pid);
2537        assert_eq!(result.max_levels, 1);
2538    }
2539
2540    #[test]
2541    fn test_descendants_with_config_monitor_self() {
2542        let pid = std::process::id();
2543        let config = DescendantsConfig {
2544            root_pid: pid,
2545            max_levels: Some(1),
2546            filter: None,
2547            cpu_mode: CpuMode::Monitor,
2548            sample_duration: Some(Duration::from_millis(1)),
2549        };
2550
2551        let result = descendants_with_config(config).unwrap();
2552        assert_eq!(result.schema_id, DESCENDANTS_RESULT_SAMPLED_V1);
2553        assert_eq!(result.root_pid, pid);
2554        assert_eq!(result.max_levels, 1);
2555    }
2556
2557    #[test]
2558    fn test_descendants_with_config_monitor_zero_sample_rejected() {
2559        let config = DescendantsConfig {
2560            root_pid: std::process::id(),
2561            max_levels: Some(1),
2562            filter: None,
2563            cpu_mode: CpuMode::Monitor,
2564            sample_duration: Some(Duration::ZERO),
2565        };
2566
2567        let err = descendants_with_config(config).unwrap_err();
2568        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2569    }
2570
2571    #[test]
2572    fn test_descendants_with_config_invalid_pid_zero_rejected_before_sampling() {
2573        let config = DescendantsConfig {
2574            root_pid: 0,
2575            max_levels: Some(1),
2576            filter: None,
2577            cpu_mode: CpuMode::Monitor,
2578            sample_duration: Some(Duration::from_secs(1)),
2579        };
2580
2581        let err = descendants_with_config(config).unwrap_err();
2582        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2583    }
2584
2585    #[test]
2586    fn test_snapshot_json_output() {
2587        let snap = snapshot().unwrap();
2588        let json = serde_json::to_string_pretty(&snap).unwrap();
2589
2590        // Verify JSON structure
2591        assert!(json.contains("\"schema_id\""));
2592        assert!(json.contains("\"timestamp\""));
2593        assert!(json.contains("\"processes\""));
2594        assert!(json.contains(PROCESS_INFO_V1));
2595    }
2596
2597    fn test_process(pid: u32, ppid: u32, name: &str) -> ProcessInfo {
2598        ProcessInfo {
2599            pid,
2600            ppid,
2601            name: name.to_string(),
2602            user: None,
2603            cpu_percent: 0.0,
2604            memory_kb: 0,
2605            elapsed_seconds: 0,
2606            start_time_unix_ms: None,
2607            exe_path: None,
2608            state: ProcessState::Running,
2609            cmdline: vec![],
2610            env: None,
2611            thread_count: None,
2612        }
2613    }
2614
2615    fn test_descendants_tree() -> DescendantsResult {
2616        DescendantsResult {
2617            schema_id: DESCENDANTS_RESULT_V1,
2618            root_pid: 10,
2619            max_levels: 10,
2620            levels: vec![
2621                DescendantsLevel {
2622                    level: 1,
2623                    processes: vec![test_process(11, 10, "helper"), test_process(12, 10, "db")],
2624                },
2625                DescendantsLevel {
2626                    level: 2,
2627                    processes: vec![
2628                        test_process(13, 11, "child-a"),
2629                        test_process(14, 12, "child-b"),
2630                    ],
2631                },
2632            ],
2633            total_found: 4,
2634            matched_by_filter: 4,
2635            timestamp: "1970-01-01T00:00:00Z".to_string(),
2636            platform: get_platform(),
2637        }
2638    }
2639
2640    fn spawn_sleep_child() -> Child {
2641        #[cfg(unix)]
2642        {
2643            Command::new("sleep")
2644                .arg("30")
2645                .stdin(Stdio::null())
2646                .stdout(Stdio::null())
2647                .stderr(Stdio::null())
2648                .spawn()
2649                .expect("spawn sleep child")
2650        }
2651
2652        #[cfg(windows)]
2653        {
2654            Command::new("cmd")
2655                .args(["/C", "ping -n 60 127.0.0.1 >NUL"])
2656                .stdin(Stdio::null())
2657                .stdout(Stdio::null())
2658                .stderr(Stdio::null())
2659                .spawn()
2660                .expect("spawn ping child")
2661        }
2662    }
2663
2664    fn guard_step_retry(config: &GuardConfig, attempts: usize, delay_ms: u64) -> GuardEvent {
2665        let mut last = None;
2666        for attempt in 0..attempts {
2667            let event = guard_step(config.clone()).expect("guard_step should succeed");
2668            let ready = if config.action_enabled {
2669                event.targeted > 0 && (event.killed > 0 || event.failed > 0)
2670            } else {
2671                true
2672            };
2673            if ready {
2674                return event;
2675            }
2676            last = Some(event);
2677            if attempt + 1 < attempts {
2678                thread::sleep(Duration::from_millis(delay_ms));
2679            }
2680        }
2681        last.expect("guard_step retry should record an event")
2682    }
2683
2684    #[test]
2685    fn test_select_descendant_targets_non_cascade() {
2686        let result = test_descendants_tree();
2687        let filter = ProcessFilter {
2688            name_contains: Some("helper".to_string()),
2689            ..Default::default()
2690        };
2691
2692        let targets = select_descendant_targets(&result, Some(&filter), false);
2693        assert_eq!(targets, vec![11]);
2694    }
2695
2696    #[test]
2697    fn test_select_descendant_targets_cascade() {
2698        let result = test_descendants_tree();
2699        let filter = ProcessFilter {
2700            name_contains: Some("helper".to_string()),
2701            ..Default::default()
2702        };
2703
2704        let targets = select_descendant_targets(&result, Some(&filter), true);
2705        assert_eq!(targets, vec![11, 13]);
2706    }
2707
2708    #[test]
2709    fn test_guard_step_action_disabled_emits_event() {
2710        let cfg = GuardConfig {
2711            rule: GuardRule {
2712                root_pid: std::process::id(),
2713                max_levels: 1,
2714                filter: None,
2715                cpu_mode: CpuMode::Lifetime,
2716                sample_duration: None,
2717            },
2718            action: GuardAction::KillDescendants {
2719                signal: 15,
2720                cascade: false,
2721            },
2722            action_enabled: false,
2723            max_targets: 32,
2724        };
2725
2726        let event = guard_step(cfg).unwrap();
2727        assert_eq!(event.schema_id, GUARD_EVENT_V1);
2728        assert_eq!(event.targeted, 0);
2729        assert_eq!(event.killed, 0);
2730        assert_eq!(event.failed, 0);
2731        assert!(event.warnings.iter().any(|w| w.contains("action disabled")));
2732    }
2733
2734    #[test]
2735    fn test_guard_step_rejects_zero_max_targets() {
2736        let cfg = GuardConfig {
2737            rule: GuardRule {
2738                root_pid: std::process::id(),
2739                max_levels: 1,
2740                filter: None,
2741                cpu_mode: CpuMode::Lifetime,
2742                sample_duration: None,
2743            },
2744            action: GuardAction::KillDescendants {
2745                signal: 15,
2746                cascade: false,
2747            },
2748            action_enabled: false,
2749            max_targets: 0,
2750        };
2751
2752        let err = guard_step(cfg).unwrap_err();
2753        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2754    }
2755
2756    #[test]
2757    fn test_guard_step_action_enabled_kills_targeted_child() {
2758        let mut child = spawn_sleep_child();
2759        let child_pid = child.id();
2760
2761        let mut child_visible = false;
2762        for _ in 0..20 {
2763            let desc = descendants_with_config(DescendantsConfig {
2764                root_pid: std::process::id(),
2765                max_levels: Some(1),
2766                filter: Some(ProcessFilter {
2767                    pid_in: Some(vec![child_pid]),
2768                    ..Default::default()
2769                }),
2770                cpu_mode: CpuMode::Lifetime,
2771                sample_duration: None,
2772            })
2773            .unwrap();
2774            if desc.matched_by_filter >= 1 {
2775                child_visible = true;
2776                break;
2777            }
2778            thread::sleep(Duration::from_millis(50));
2779        }
2780        assert!(child_visible, "expected spawned child to be visible");
2781
2782        let cfg = GuardConfig {
2783            rule: GuardRule {
2784                root_pid: std::process::id(),
2785                max_levels: 1,
2786                filter: Some(ProcessFilter {
2787                    pid_in: Some(vec![child_pid]),
2788                    ..Default::default()
2789                }),
2790                cpu_mode: CpuMode::Lifetime,
2791                sample_duration: None,
2792            },
2793            action: GuardAction::KillDescendants {
2794                signal: 15,
2795                cascade: false,
2796            },
2797            action_enabled: true,
2798            max_targets: 8,
2799        };
2800
2801        let event = guard_step_retry(&cfg, 10, 100);
2802        assert_eq!(event.targeted, 1);
2803        assert_eq!(event.killed, 1);
2804        assert_eq!(event.failed, 0);
2805
2806        let mut exited = false;
2807        for _ in 0..20 {
2808            if let Some(_status) = child.try_wait().expect("poll child exit") {
2809                exited = true;
2810                break;
2811            }
2812            thread::sleep(Duration::from_millis(100));
2813        }
2814        if !exited {
2815            let _ = child.kill();
2816            let _ = child.wait();
2817        }
2818        assert!(exited, "guard_step should terminate targeted child");
2819    }
2820
2821    #[test]
2822    fn test_guard_step_action_enabled_applies_max_targets_cap() {
2823        let mut child_a = spawn_sleep_child();
2824        let mut child_b = spawn_sleep_child();
2825        let pids = vec![child_a.id(), child_b.id()];
2826
2827        // Wait until both children are discoverable as direct descendants.
2828        let mut both_visible = false;
2829        for _ in 0..20 {
2830            let desc = descendants_with_config(DescendantsConfig {
2831                root_pid: std::process::id(),
2832                max_levels: Some(1),
2833                filter: Some(ProcessFilter {
2834                    pid_in: Some(pids.clone()),
2835                    ..Default::default()
2836                }),
2837                cpu_mode: CpuMode::Lifetime,
2838                sample_duration: None,
2839            })
2840            .unwrap();
2841            if desc.matched_by_filter >= 2 {
2842                both_visible = true;
2843                break;
2844            }
2845            thread::sleep(Duration::from_millis(50));
2846        }
2847        assert!(both_visible, "expected both spawned children to be visible");
2848
2849        let cfg = GuardConfig {
2850            rule: GuardRule {
2851                root_pid: std::process::id(),
2852                max_levels: 1,
2853                filter: Some(ProcessFilter {
2854                    pid_in: Some(pids.clone()),
2855                    ..Default::default()
2856                }),
2857                cpu_mode: CpuMode::Lifetime,
2858                sample_duration: None,
2859            },
2860            action: GuardAction::KillDescendants {
2861                signal: 15,
2862                cascade: false,
2863            },
2864            action_enabled: true,
2865            max_targets: 1,
2866        };
2867
2868        let event = guard_step_retry(&cfg, 10, 100);
2869
2870        assert_eq!(event.matched, 2);
2871        assert_eq!(event.targeted, 1);
2872        assert_eq!(event.killed, 1);
2873        assert_eq!(event.failed, 0);
2874        assert!(
2875            event
2876                .warnings
2877                .iter()
2878                .any(|w| w.contains("target count capped at max_targets=1")),
2879            "expected max_targets cap warning, got: {:?}",
2880            event.warnings
2881        );
2882
2883        // Exactly one process should exit quickly; the other remains until cleanup.
2884        let mut exited_count = 0;
2885        for _ in 0..20 {
2886            exited_count = 0;
2887            if child_a.try_wait().expect("poll child A").is_some() {
2888                exited_count += 1;
2889            }
2890            if child_b.try_wait().expect("poll child B").is_some() {
2891                exited_count += 1;
2892            }
2893            if exited_count >= 1 {
2894                break;
2895            }
2896            thread::sleep(Duration::from_millis(100));
2897        }
2898        assert!(
2899            exited_count >= 1,
2900            "expected at least one child to exit after capped guard_step kill"
2901        );
2902
2903        for child in [&mut child_a, &mut child_b] {
2904            if child.try_wait().expect("final poll").is_none() {
2905                let _ = child.kill();
2906                let _ = child.wait();
2907            }
2908        }
2909    }
2910
2911    #[test]
2912    fn test_ancestors_self() {
2913        let pid = std::process::id();
2914        let result = ancestors(pid, 64, ProcessOptions::default()).unwrap();
2915
2916        assert_eq!(result.schema_id, ANCESTORS_RESULT_V1);
2917        assert_eq!(result.pid, pid);
2918        assert!(
2919            !result.chain.is_empty(),
2920            "chain should include at least self"
2921        );
2922        assert_eq!(
2923            result.chain[0].pid, pid,
2924            "first element should be starting PID"
2925        );
2926
2927        // Chain should have at least 2 elements (self + parent)
2928        assert!(
2929            result.chain.len() >= 2,
2930            "chain should include at least self and parent, got {}",
2931            result.chain.len()
2932        );
2933    }
2934
2935    #[test]
2936    fn test_ancestors_rejects_pid_zero() {
2937        let err = ancestors(0, 10, ProcessOptions::default()).unwrap_err();
2938        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
2939    }
2940
2941    #[test]
2942    fn test_ancestors_nonexistent_pid() {
2943        let err = ancestors(99999999, 10, ProcessOptions::default()).unwrap_err();
2944        assert!(matches!(err, SysprimsError::NotFound { .. }));
2945    }
2946
2947    #[test]
2948    fn test_ancestors_max_depth_zero() {
2949        let pid = std::process::id();
2950        let result = ancestors(pid, 0, ProcessOptions::default()).unwrap();
2951
2952        // max_depth=0 means just the starting PID
2953        assert_eq!(result.chain.len(), 1);
2954        assert_eq!(result.chain[0].pid, pid);
2955    }
2956}