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