1use anyhow::Result;
2use serde::{Deserialize, Serialize};
3
4#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
8pub struct ProcessIdentity {
9 pub start_marker: u64,
10 pub executable: String,
11}
12
13pub fn run_with_timeout(
25 mut cmd: std::process::Command,
26 timeout: std::time::Duration,
27) -> Option<std::process::Output> {
28 use std::process::Stdio;
29 use std::time::Instant;
30
31 let mut child = cmd
32 .stdin(Stdio::null())
33 .stdout(Stdio::piped())
34 .stderr(Stdio::piped())
35 .spawn()
36 .ok()?;
37
38 let start = Instant::now();
39 loop {
40 match child.try_wait() {
41 Ok(Some(_)) => return child.wait_with_output().ok(),
43 Ok(None) => {
44 if start.elapsed() >= timeout {
45 let _ = child.kill();
46 let _ = child.wait();
47 return None;
48 }
49 std::thread::sleep(std::time::Duration::from_millis(50));
50 }
51 Err(_) => return None,
52 }
53 }
54}
55
56pub fn spawn_detached(cmd: &mut std::process::Command) -> std::io::Result<std::process::Child> {
74 #[cfg(windows)]
75 {
76 use std::os::windows::process::CommandExt;
77
78 const DETACHED_PROCESS: u32 = 0x0000_0008;
79 const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
80 const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
81
82 let detached = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
83 match cmd
84 .creation_flags(detached | CREATE_BREAKAWAY_FROM_JOB)
85 .spawn()
86 {
87 Ok(child) => Ok(child),
88 Err(_) => cmd.creation_flags(detached).spawn(),
89 }
90 }
91 #[cfg(not(windows))]
92 {
93 cmd.spawn()
94 }
95}
96
97pub fn is_alive(pid: u32) -> bool {
99 #[cfg(unix)]
100 {
101 unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
105 }
106 #[cfg(windows)]
107 {
108 use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE, WAIT_TIMEOUT};
109 use windows_sys::Win32::System::Threading::{
110 GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, WaitForSingleObject,
111 };
112
113 unsafe {
117 let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
118 if handle.is_null() {
119 return false;
120 }
121 let wait = WaitForSingleObject(handle, 0);
122 if wait == WAIT_TIMEOUT {
123 CloseHandle(handle);
124 return true;
125 }
126 let mut exit_code: u32 = 0;
127 GetExitCodeProcess(handle, &raw mut exit_code);
128 CloseHandle(handle);
129 exit_code == STILL_ACTIVE as u32
130 }
131 }
132}
133
134pub fn identity(pid: u32) -> Option<ProcessIdentity> {
141 #[cfg(target_os = "macos")]
142 {
143 macos_process_identity(pid)
144 }
145 #[cfg(target_os = "linux")]
146 {
147 linux_process_identity(pid)
148 }
149 #[cfg(windows)]
150 {
151 windows_process_identity(pid)
152 }
153 #[cfg(target_os = "freebsd")]
154 {
155 freebsd_process_identity(pid)
156 }
157 #[cfg(not(any(
158 target_os = "macos",
159 target_os = "linux",
160 target_os = "freebsd",
161 windows
162 )))]
163 {
164 let _ = pid;
165 None
166 }
167}
168
169#[cfg(target_os = "freebsd")]
174fn freebsd_process_identity(pid: u32) -> Option<ProcessIdentity> {
175 let pid = libc::c_int::try_from(pid).ok()?;
176
177 let mut info = std::mem::MaybeUninit::<libc::kinfo_proc>::zeroed();
178 let mut info_len = std::mem::size_of::<libc::kinfo_proc>();
179 let mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_PID, pid];
180 let rc = unsafe {
183 libc::sysctl(
184 mib.as_ptr(),
185 4,
186 info.as_mut_ptr().cast(),
187 &mut info_len,
188 std::ptr::null(),
189 0,
190 )
191 };
192 if rc != 0 || info_len != std::mem::size_of::<libc::kinfo_proc>() {
193 return None;
194 }
195 let info = unsafe { info.assume_init() };
197 if info.ki_pid != pid {
198 return None;
199 }
200 let start_marker = u64::try_from(info.ki_start.tv_sec)
201 .ok()?
202 .checked_mul(1_000_000)?
203 .checked_add(u64::try_from(info.ki_start.tv_usec).ok()?)?;
204
205 let mut path = [0_u8; libc::PATH_MAX as usize];
206 let mut path_len = path.len();
207 let mib = [
208 libc::CTL_KERN,
209 libc::KERN_PROC,
210 libc::KERN_PROC_PATHNAME,
211 pid,
212 ];
213 let rc = unsafe {
215 libc::sysctl(
216 mib.as_ptr(),
217 4,
218 path.as_mut_ptr().cast(),
219 &mut path_len,
220 std::ptr::null(),
221 0,
222 )
223 };
224 if rc != 0 || path_len == 0 {
225 return None;
226 }
227 let bytes = path.get(..path_len)?;
229 let bytes = bytes.strip_suffix(&[0]).unwrap_or(bytes);
230 if bytes.is_empty() {
231 return None;
232 }
233 Some(ProcessIdentity {
234 start_marker,
235 executable: String::from_utf8_lossy(bytes).into_owned(),
236 })
237}
238
239pub fn matches_identity(pid: u32, expected: &ProcessIdentity) -> bool {
242 identity(pid).as_ref() == Some(expected)
243}
244
245#[cfg(target_os = "macos")]
246#[repr(C)]
247struct ProcBsdInfo {
248 pbi_flags: u32,
249 pbi_status: u32,
250 pbi_xstatus: u32,
251 pbi_pid: u32,
252 pbi_ppid: u32,
253 pbi_uid: u32,
254 pbi_gid: u32,
255 pbi_ruid: u32,
256 pbi_rgid: u32,
257 pbi_svuid: u32,
258 pbi_svgid: u32,
259 rfu_1: u32,
260 pbi_comm: [std::ffi::c_char; 16],
261 pbi_name: [std::ffi::c_char; 32],
262 pbi_nfiles: u32,
263 pbi_pgid: u32,
264 pbi_pjobc: u32,
265 e_tdev: u32,
266 e_tpgid: u32,
267 pbi_nice: i32,
268 pbi_start_tvsec: u64,
269 pbi_start_tvusec: u64,
270}
271
272#[cfg(target_os = "macos")]
273const PROC_PIDTBSDINFO: std::ffi::c_int = 3;
274
275#[cfg(target_os = "macos")]
276#[link(name = "proc")]
277unsafe extern "C" {
278 fn proc_pidinfo(
279 pid: std::ffi::c_int,
280 flavor: std::ffi::c_int,
281 arg: u64,
282 buffer: *mut std::ffi::c_void,
283 buffersize: std::ffi::c_int,
284 ) -> std::ffi::c_int;
285 fn proc_pidpath(
286 pid: std::ffi::c_int,
287 buffer: *mut std::ffi::c_void,
288 buffersize: u32,
289 ) -> std::ffi::c_int;
290}
291
292#[cfg(target_os = "macos")]
293fn macos_process_identity(pid: u32) -> Option<ProcessIdentity> {
294 let mut info = std::mem::MaybeUninit::<ProcBsdInfo>::zeroed();
295 let size = i32::try_from(std::mem::size_of::<ProcBsdInfo>()).ok()?;
296 let read = unsafe {
298 proc_pidinfo(
299 i32::try_from(pid).ok()?,
300 PROC_PIDTBSDINFO,
301 0,
302 info.as_mut_ptr().cast(),
303 size,
304 )
305 };
306 if read != size {
307 return None;
308 }
309 let info = unsafe { info.assume_init() };
311 let mut path = [0_u8; libc::PATH_MAX as usize];
312 let path_len = unsafe {
314 proc_pidpath(
315 i32::try_from(pid).ok()?,
316 path.as_mut_ptr().cast(),
317 u32::try_from(path.len()).ok()?,
318 )
319 };
320 if path_len <= 0 {
321 return None;
322 }
323 let path_len = usize::try_from(path_len).ok()?;
324 let executable = String::from_utf8_lossy(path.get(..path_len)?).into_owned();
325 let start_marker = info
326 .pbi_start_tvsec
327 .checked_mul(1_000_000)?
328 .checked_add(info.pbi_start_tvusec)?;
329 Some(ProcessIdentity {
330 start_marker,
331 executable,
332 })
333}
334
335#[cfg(target_os = "linux")]
336fn linux_process_identity(pid: u32) -> Option<ProcessIdentity> {
337 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
338 let (_, fields) = stat.rsplit_once(')')?;
339 let start_marker = fields.split_whitespace().nth(19)?.parse().ok()?;
340 let executable = std::fs::read_link(format!("/proc/{pid}/exe"))
341 .ok()?
342 .to_string_lossy()
343 .into_owned();
344 Some(ProcessIdentity {
345 start_marker,
346 executable,
347 })
348}
349
350#[cfg(windows)]
351fn windows_process_identity(pid: u32) -> Option<ProcessIdentity> {
352 use std::os::windows::ffi::OsStringExt;
353 use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
354 use windows_sys::Win32::System::Threading::{
355 GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
356 };
357
358 let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
360 if handle.is_null() {
361 return None;
362 }
363 let mut created = FILETIME::default();
364 let mut exited = FILETIME::default();
365 let mut kernel = FILETIME::default();
366 let mut user = FILETIME::default();
367 let times_ok = unsafe {
369 GetProcessTimes(
370 handle,
371 &raw mut created,
372 &raw mut exited,
373 &raw mut kernel,
374 &raw mut user,
375 )
376 } != 0;
377 let mut path = vec![0_u16; 32_768];
378 let mut path_len = u32::try_from(path.len()).ok()?;
379 let path_ok =
381 unsafe { QueryFullProcessImageNameW(handle, 0, path.as_mut_ptr(), &raw mut path_len) != 0 };
382 unsafe { CloseHandle(handle) };
384 if !times_ok || !path_ok {
385 return None;
386 }
387 let executable = std::ffi::OsString::from_wide(path.get(..usize::try_from(path_len).ok()?)?)
388 .to_string_lossy()
389 .into_owned();
390 let start_marker = (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime);
391 Some(ProcessIdentity {
392 start_marker,
393 executable,
394 })
395}
396
397pub fn terminate_gracefully(pid: u32) -> Result<()> {
400 #[cfg(unix)]
401 {
402 let ret = unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) };
405 if ret != 0 {
406 anyhow::bail!(
407 "Failed to send SIGTERM to PID {pid}: {}",
408 std::io::Error::last_os_error()
409 );
410 }
411 Ok(())
412 }
413 #[cfg(windows)]
414 {
415 force_kill(pid)
416 }
417}
418
419pub fn force_kill(pid: u32) -> Result<()> {
421 #[cfg(unix)]
422 {
423 let ret = unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
426 if ret != 0 {
427 anyhow::bail!(
428 "Failed to send SIGKILL to PID {pid}: {}",
429 std::io::Error::last_os_error()
430 );
431 }
432 Ok(())
433 }
434 #[cfg(windows)]
435 {
436 use windows_sys::Win32::Foundation::CloseHandle;
437 use windows_sys::Win32::System::Threading::{
438 OpenProcess, PROCESS_TERMINATE, TerminateProcess,
439 };
440
441 unsafe {
444 let handle = OpenProcess(PROCESS_TERMINATE, 0, pid);
445 if handle.is_null() {
446 anyhow::bail!(
447 "Failed to open PID {pid} for termination: {}",
448 std::io::Error::last_os_error()
449 );
450 }
451 let ok = TerminateProcess(handle, 1);
452 CloseHandle(handle);
453 if ok == 0 {
454 anyhow::bail!(
455 "Failed to terminate PID {pid}: {}",
456 std::io::Error::last_os_error()
457 );
458 }
459 Ok(())
460 }
461 }
462}
463
464fn protected_self_pids() -> std::collections::HashSet<u32> {
480 let mut protected = std::collections::HashSet::new();
481 protected.insert(std::process::id());
482 #[cfg(unix)]
483 {
484 let mut pid = std::process::id();
485 for _ in 0..16 {
486 let Ok(output) = std::process::Command::new("ps")
487 .args(["-o", "ppid=", "-p", &pid.to_string()])
488 .output()
489 else {
490 break;
491 };
492 let Ok(ppid) = String::from_utf8_lossy(&output.stdout)
493 .trim()
494 .parse::<u32>()
495 else {
496 break;
497 };
498 if ppid <= 1 || !protected.insert(ppid) {
499 break;
500 }
501 pid = ppid;
502 }
503
504 let own_pgid = unsafe { libc::getpgrp() };
506 if own_pgid > 0 {
507 protected.extend(process_group_pids(own_pgid));
508 }
509 }
510 protected
511}
512
513#[cfg(unix)]
514fn process_group_pids(pgid: libc::pid_t) -> Vec<u32> {
515 std::process::Command::new("pgrep")
516 .args(["-g", &pgid.to_string()])
517 .output()
518 .ok()
519 .map(|output| {
520 String::from_utf8_lossy(&output.stdout)
521 .lines()
522 .filter_map(|line| line.trim().parse::<u32>().ok())
523 .collect()
524 })
525 .unwrap_or_default()
526}
527
528pub fn find_pids_by_name(name: &str) -> Vec<u32> {
531 let protected = protected_self_pids();
532 let mut pids = Vec::new();
533
534 #[cfg(unix)]
535 {
536 if let Ok(output) = std::process::Command::new("pgrep")
538 .arg("-x")
539 .arg(name)
540 .output()
541 {
542 collect_pids(&output.stdout, &protected, &mut pids);
543 }
544
545 if let Ok(output) = std::process::Command::new("pgrep")
548 .arg("-f")
549 .arg(format!("/{name}(\\s|$)"))
550 .output()
551 {
552 collect_pids(&output.stdout, &protected, &mut pids);
553 }
554
555 pids.sort_unstable();
556 pids.dedup();
557 }
558
559 #[cfg(windows)]
560 {
561 if let Ok(output) = std::process::Command::new("tasklist")
562 .args([
563 "/FI",
564 &format!("IMAGENAME eq {name}.exe"),
565 "/FO",
566 "CSV",
567 "/NH",
568 ])
569 .output()
570 {
571 let stdout = String::from_utf8_lossy(&output.stdout);
572 for line in stdout.lines() {
573 let parts: Vec<&str> = line.split(',').collect();
574 if parts.len() >= 2 {
575 let pid_str = parts[1].trim().trim_matches('"');
576 if let Ok(pid) = pid_str.parse::<u32>() {
577 if !protected.contains(&pid) {
578 pids.push(pid);
579 }
580 }
581 }
582 }
583 }
584 }
585
586 pids
587}
588
589#[cfg(unix)]
590fn collect_pids(stdout: &[u8], protected: &std::collections::HashSet<u32>, out: &mut Vec<u32>) {
591 let text = String::from_utf8_lossy(stdout);
592 for line in text.lines() {
593 if let Ok(pid) = line.trim().parse::<u32>()
594 && !protected.contains(&pid)
595 {
596 out.push(pid);
597 }
598 }
599}
600
601pub fn find_killable_pids(name: &str) -> Vec<u32> {
611 let mut protected = find_mcp_server_pids(name);
612 protected.extend(find_command_runner_pids(name));
613 killable_excluding_mcp(find_pids_by_name(name), &protected)
614}
615
616fn killable_excluding_mcp(all: Vec<u32>, protected: &[u32]) -> Vec<u32> {
621 all.into_iter().filter(|p| !protected.contains(p)).collect()
622}
623
624#[cfg(unix)]
626fn find_command_runner_pids(name: &str) -> Vec<u32> {
627 find_pids_by_name(name)
628 .into_iter()
629 .filter(|&pid| {
630 std::process::Command::new("ps")
631 .args(["-o", "command=", "-p", &pid.to_string()])
632 .output()
633 .is_ok_and(|out| is_command_runner_cmdline(&String::from_utf8_lossy(&out.stdout)))
634 })
635 .collect()
636}
637
638#[cfg(not(unix))]
641fn find_command_runner_pids(_name: &str) -> Vec<u32> {
642 Vec::new()
643}
644
645#[cfg_attr(not(unix), allow(dead_code))]
650fn is_command_runner_cmdline(command: &str) -> bool {
651 let mut words = command.split_whitespace();
652 let Some(argv0) = words.next() else {
653 return false;
654 };
655 if argv0 != "lean-ctx" && !argv0.ends_with("/lean-ctx") {
656 return false;
657 }
658 matches!(words.next(), Some("-c" | "exec" | "-t" | "--track"))
659}
660
661#[cfg(unix)]
662fn find_mcp_server_pids(name: &str) -> Vec<u32> {
663 find_pids_by_name(name)
664 .into_iter()
665 .filter(|&pid| is_mcp_stdio_process(pid))
666 .collect()
667}
668
669#[cfg(windows)]
670fn find_mcp_server_pids(name: &str) -> Vec<u32> {
671 find_pids_by_name(name)
672 .into_iter()
673 .filter(|&pid| is_mcp_stdio_process_win(pid))
674 .collect()
675}
676
677#[cfg(windows)]
678fn is_mcp_stdio_process_win(pid: u32) -> bool {
679 let Ok(output) = std::process::Command::new("wmic")
682 .args([
683 "process",
684 "where",
685 &format!("ProcessId={pid}"),
686 "get",
687 "ParentProcessId,CommandLine",
688 "/FORMAT:CSV",
689 ])
690 .output()
691 else {
692 return false;
693 };
694
695 let text = String::from_utf8_lossy(&output.stdout);
696 for line in text.lines() {
697 let parts: Vec<&str> = line.split(',').collect();
698 if parts.len() < 3 {
699 continue;
700 }
701 let cmd_line = parts[1].to_lowercase();
702 let ppid_str = parts.last().unwrap_or(&"").trim();
703
704 if cmd_line.contains("cursor") || cmd_line.contains("code.exe") {
706 return true;
707 }
708
709 if let Ok(ppid) = ppid_str.parse::<u32>() {
711 if let Ok(pp_out) = std::process::Command::new("wmic")
712 .args([
713 "process",
714 "where",
715 &format!("ProcessId={ppid}"),
716 "get",
717 "Name",
718 "/FORMAT:CSV",
719 ])
720 .output()
721 {
722 let pp_text = String::from_utf8_lossy(&pp_out.stdout).to_lowercase();
723 if pp_text.contains("cursor") || pp_text.contains("code.exe") {
724 return true;
725 }
726 }
727 }
728
729 if (cmd_line.ends_with("lean-ctx.exe") || cmd_line.ends_with("lean-ctx.exe\""))
731 && !cmd_line.contains("proxy")
732 && !cmd_line.contains("dashboard")
733 && !cmd_line.contains("daemon")
734 && !cmd_line.contains("stop")
735 && !cmd_line.contains("hook")
736 {
737 return true;
738 }
739 }
740 false
741}
742
743#[cfg(not(any(unix, windows)))]
744fn find_mcp_server_pids(_name: &str) -> Vec<u32> {
745 Vec::new()
746}
747
748#[cfg(unix)]
749fn is_mcp_stdio_process(pid: u32) -> bool {
750 if let Ok(output) = std::process::Command::new("ps")
751 .args(["-o", "ppid=,command=", "-p", &pid.to_string()])
752 .output()
753 {
754 let text = String::from_utf8_lossy(&output.stdout);
755 let t = text.trim();
756 if t.contains("Cursor") || t.contains("cursor") || t.contains("code") {
757 return true;
758 }
759 let parts: Vec<&str> = t.split_whitespace().collect();
760 if let Some(ppid_str) = parts.first()
761 && let Ok(ppid) = ppid_str.parse::<u32>()
762 && let Ok(pp_out) = std::process::Command::new("ps")
763 .args(["-o", "command=", "-p", &ppid.to_string()])
764 .output()
765 {
766 let pp_cmd = String::from_utf8_lossy(&pp_out.stdout);
767 if pp_cmd.contains("Cursor") || pp_cmd.contains("cursor") || pp_cmd.contains("code") {
768 return true;
769 }
770 }
771 let cmd_part = parts.get(1..).map(|p| p.join(" ")).unwrap_or_default();
772 if (cmd_part.ends_with("/lean-ctx") || cmd_part == "lean-ctx")
774 && !cmd_part.contains("proxy")
775 && !cmd_part.contains("dashboard")
776 && !cmd_part.contains("daemon")
777 && !cmd_part.contains("stop")
778 && !cmd_part.contains("hook")
779 {
780 return true;
781 }
782 if cmd_part.contains("hook observe")
784 || cmd_part.contains("hook rewrite")
785 || cmd_part.contains("hook redirect")
786 {
787 return true;
788 }
789 }
790 false
791}
792
793pub fn kill_all_by_name(name: &str) -> usize {
796 let pids = find_killable_pids(name);
797 if pids.is_empty() {
798 return 0;
799 }
800
801 for &pid in &pids {
802 let _ = terminate_gracefully(pid);
803 }
804
805 std::thread::sleep(std::time::Duration::from_millis(500));
806
807 let mut killed = 0;
808 for &pid in &pids {
809 if is_alive(pid) {
810 let _ = force_kill(pid);
811 }
812 killed += 1;
813 }
814
815 std::thread::sleep(std::time::Duration::from_millis(200));
816
817 killed
818}
819
820#[cfg(test)]
821mod tests {
822 use super::*;
823
824 #[test]
825 fn current_process_is_alive() {
826 assert!(is_alive(std::process::id()));
827 }
828
829 #[test]
830 fn current_process_identity_is_stable_and_matches() {
831 let pid = std::process::id();
832 let identity = identity(pid).expect("supported platform exposes process identity");
833 assert!(!identity.executable.is_empty());
834 assert!(matches_identity(pid, &identity));
835 }
836
837 #[test]
838 fn killable_pids_exclude_active_mcp_stdio_servers() {
839 assert_eq!(
840 killable_excluding_mcp(vec![11, 17, 23], &[11, 23]),
841 vec![17]
842 );
843 }
844
845 #[test]
849 fn in_flight_command_runners_are_never_killable() {
850 for runner in [
851 "lean-ctx -c cargo test --lib",
852 "/Users/me/.local/bin/lean-ctx -c git commit -m x",
853 "/usr/local/bin/lean-ctx exec make",
854 "lean-ctx --track npm test",
855 "lean-ctx -t pytest",
856 ] {
857 assert!(
858 is_command_runner_cmdline(runner),
859 "must be protected: {runner}"
860 );
861 }
862 for stoppable in [
863 "lean-ctx serve --_foreground-daemon",
864 "/Users/me/.local/bin/lean-ctx proxy start --port 4444",
865 "lean-ctx dashboard",
866 "lean-ctx",
867 "/usr/bin/grep -c lean-ctx",
868 "",
869 ] {
870 assert!(
871 !is_command_runner_cmdline(stoppable),
872 "must stay stoppable: {stoppable}"
873 );
874 }
875 }
876
877 #[test]
878 fn bogus_pid_is_not_alive() {
879 assert!(!is_alive(u32::MAX - 42));
880 }
881
882 #[cfg(unix)]
883 #[test]
884 fn run_with_timeout_returns_output_for_fast_command() {
885 let mut cmd = std::process::Command::new("echo");
886 cmd.arg("hello");
887 let out = run_with_timeout(cmd, std::time::Duration::from_secs(5))
888 .expect("fast command should complete");
889 assert!(out.status.success());
890 assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hello");
891 }
892
893 #[cfg(unix)]
894 #[test]
895 fn run_with_timeout_kills_slow_command() {
896 let mut cmd = std::process::Command::new("sleep");
897 cmd.arg("30");
898 let start = std::time::Instant::now();
899 let result = run_with_timeout(cmd, std::time::Duration::from_millis(300));
900 assert!(result.is_none(), "slow command must time out");
901 assert!(
902 start.elapsed() < std::time::Duration::from_secs(5),
903 "timeout must not wait for the full command"
904 );
905 }
906
907 #[test]
908 fn killable_excludes_mcp_pids() {
909 let killable = killable_excluding_mcp(vec![1, 2, 3, 4], &[2, 4]);
913 assert_eq!(killable, vec![1, 3]);
914 assert!(!killable.contains(&2));
915 assert!(!killable.contains(&4));
916 }
917
918 #[test]
919 fn killable_with_no_mcp_returns_all() {
920 let all = vec![10, 20, 30];
921 assert_eq!(killable_excluding_mcp(all.clone(), &[]), all);
922 }
923
924 #[cfg(unix)]
928 #[test]
929 fn protected_pids_cover_own_process_group() {
930 let pgid = unsafe { libc::getpgrp() };
932 let members_before = process_group_pids(pgid);
940 let protected = protected_self_pids();
941 let members_after = process_group_pids(pgid);
942 for pid in members_before {
943 if !members_after.contains(&pid) {
944 continue; }
946 assert!(
947 protected.contains(&pid),
948 "stable group member {pid} missing from protected set"
949 );
950 }
951 }
952
953 #[test]
958 fn protected_pids_cover_self_and_ancestors() {
959 let protected = protected_self_pids();
960 assert!(protected.contains(&std::process::id()));
961 #[cfg(unix)]
962 {
963 let out = std::process::Command::new("ps")
965 .args(["-o", "ppid=", "-p", &std::process::id().to_string()])
966 .output()
967 .expect("ps runs");
968 if let Ok(ppid) = String::from_utf8_lossy(&out.stdout).trim().parse::<u32>()
969 && ppid > 1
970 {
971 assert!(
972 protected.contains(&ppid),
973 "parent {ppid} missing from {protected:?}"
974 );
975 }
976 }
977 }
978
979 #[cfg(unix)]
980 #[test]
981 fn find_pids_never_reports_own_process_tree() {
982 let protected = protected_self_pids();
985 for pid in find_pids_by_name("lean-ctx") {
986 assert!(!protected.contains(&pid), "own tree pid {pid} reported");
987 }
988 }
989}