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