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 let uid = unsafe { libc::getuid() }.to_string();
540
541 if let Ok(output) = std::process::Command::new("pgrep")
543 .args(["-U", &uid, "-x", name])
544 .output()
545 {
546 collect_pids(&output.stdout, &protected, &mut pids);
547 }
548
549 if let Ok(output) = std::process::Command::new("pgrep")
552 .args(["-U", &uid])
553 .arg("-f")
554 .arg(format!("/{name}(\\s|$)"))
555 .output()
556 {
557 collect_pids(&output.stdout, &protected, &mut pids);
558 }
559
560 pids.sort_unstable();
561 pids.dedup();
562 }
563
564 #[cfg(windows)]
565 {
566 if let Ok(output) = std::process::Command::new("tasklist")
567 .args([
568 "/FI",
569 &format!("IMAGENAME eq {name}.exe"),
570 "/FO",
571 "CSV",
572 "/NH",
573 ])
574 .output()
575 {
576 let stdout = String::from_utf8_lossy(&output.stdout);
577 for line in stdout.lines() {
578 let parts: Vec<&str> = line.split(',').collect();
579 if parts.len() >= 2 {
580 let pid_str = parts[1].trim().trim_matches('"');
581 if let Ok(pid) = pid_str.parse::<u32>() {
582 if !protected.contains(&pid) {
583 pids.push(pid);
584 }
585 }
586 }
587 }
588 }
589 }
590
591 pids
592}
593
594#[cfg(unix)]
595fn collect_pids(stdout: &[u8], protected: &std::collections::HashSet<u32>, out: &mut Vec<u32>) {
596 let text = String::from_utf8_lossy(stdout);
597 for line in text.lines() {
598 if let Ok(pid) = line.trim().parse::<u32>()
599 && !protected.contains(&pid)
600 {
601 out.push(pid);
602 }
603 }
604}
605
606pub fn find_killable_pids(name: &str) -> Vec<u32> {
616 let mut protected = find_mcp_server_pids(name);
617 protected.extend(find_command_runner_pids(name));
618 killable_excluding_mcp(find_pids_by_name(name), &protected)
619}
620
621fn killable_excluding_mcp(all: Vec<u32>, protected: &[u32]) -> Vec<u32> {
626 all.into_iter().filter(|p| !protected.contains(p)).collect()
627}
628
629#[cfg(unix)]
631fn find_command_runner_pids(name: &str) -> Vec<u32> {
632 find_pids_by_name(name)
633 .into_iter()
634 .filter(|&pid| {
635 std::process::Command::new("ps")
636 .args(["-o", "command=", "-p", &pid.to_string()])
637 .output()
638 .is_ok_and(|out| is_command_runner_cmdline(&String::from_utf8_lossy(&out.stdout)))
639 })
640 .collect()
641}
642
643#[cfg(not(unix))]
646fn find_command_runner_pids(_name: &str) -> Vec<u32> {
647 Vec::new()
648}
649
650#[cfg_attr(not(unix), allow(dead_code))]
655fn is_command_runner_cmdline(command: &str) -> bool {
656 let mut words = command.split_whitespace();
657 let Some(argv0) = words.next() else {
658 return false;
659 };
660 if argv0 != "lean-ctx" && !argv0.ends_with("/lean-ctx") {
661 return false;
662 }
663 matches!(words.next(), Some("-c" | "exec" | "-t" | "--track"))
664}
665
666#[cfg(unix)]
667fn find_mcp_server_pids(name: &str) -> Vec<u32> {
668 find_pids_by_name(name)
669 .into_iter()
670 .filter(|&pid| is_mcp_stdio_process(pid))
671 .collect()
672}
673
674#[cfg(windows)]
675fn find_mcp_server_pids(name: &str) -> Vec<u32> {
676 find_pids_by_name(name)
677 .into_iter()
678 .filter(|&pid| is_mcp_stdio_process_win(pid))
679 .collect()
680}
681
682#[cfg(windows)]
683fn is_mcp_stdio_process_win(pid: u32) -> bool {
684 let Ok(output) = std::process::Command::new("wmic")
687 .args([
688 "process",
689 "where",
690 &format!("ProcessId={pid}"),
691 "get",
692 "ParentProcessId,CommandLine",
693 "/FORMAT:CSV",
694 ])
695 .output()
696 else {
697 return false;
698 };
699
700 let text = String::from_utf8_lossy(&output.stdout);
701 for line in text.lines() {
702 let parts: Vec<&str> = line.split(',').collect();
703 if parts.len() < 3 {
704 continue;
705 }
706 let cmd_line = parts[1].to_lowercase();
707 let ppid_str = parts.last().unwrap_or(&"").trim();
708
709 if cmd_line.contains("cursor") || cmd_line.contains("code.exe") {
711 return true;
712 }
713
714 if let Ok(ppid) = ppid_str.parse::<u32>() {
716 if let Ok(pp_out) = std::process::Command::new("wmic")
717 .args([
718 "process",
719 "where",
720 &format!("ProcessId={ppid}"),
721 "get",
722 "Name",
723 "/FORMAT:CSV",
724 ])
725 .output()
726 {
727 let pp_text = String::from_utf8_lossy(&pp_out.stdout).to_lowercase();
728 if pp_text.contains("cursor") || pp_text.contains("code.exe") {
729 return true;
730 }
731 }
732 }
733
734 if (cmd_line.ends_with("lean-ctx.exe") || cmd_line.ends_with("lean-ctx.exe\""))
736 && !cmd_line.contains("proxy")
737 && !cmd_line.contains("dashboard")
738 && !cmd_line.contains("daemon")
739 && !cmd_line.contains("stop")
740 && !cmd_line.contains("hook")
741 {
742 return true;
743 }
744 }
745 false
746}
747
748#[cfg(not(any(unix, windows)))]
749fn find_mcp_server_pids(_name: &str) -> Vec<u32> {
750 Vec::new()
751}
752
753#[cfg(unix)]
754fn is_mcp_stdio_process(pid: u32) -> bool {
755 if let Ok(output) = std::process::Command::new("ps")
756 .args(["-o", "ppid=,command=", "-p", &pid.to_string()])
757 .output()
758 {
759 let text = String::from_utf8_lossy(&output.stdout);
760 let t = text.trim();
761 if t.contains("Cursor") || t.contains("cursor") || t.contains("code") {
762 return true;
763 }
764 let parts: Vec<&str> = t.split_whitespace().collect();
765 if let Some(ppid_str) = parts.first()
766 && let Ok(ppid) = ppid_str.parse::<u32>()
767 && let Ok(pp_out) = std::process::Command::new("ps")
768 .args(["-o", "command=", "-p", &ppid.to_string()])
769 .output()
770 {
771 let pp_cmd = String::from_utf8_lossy(&pp_out.stdout);
772 if pp_cmd.contains("Cursor") || pp_cmd.contains("cursor") || pp_cmd.contains("code") {
773 return true;
774 }
775 }
776 let cmd_part = parts.get(1..).map(|p| p.join(" ")).unwrap_or_default();
777 if (cmd_part.ends_with("/lean-ctx") || cmd_part == "lean-ctx")
779 && !cmd_part.contains("proxy")
780 && !cmd_part.contains("dashboard")
781 && !cmd_part.contains("daemon")
782 && !cmd_part.contains("stop")
783 && !cmd_part.contains("hook")
784 {
785 return true;
786 }
787 if cmd_part.contains("hook observe")
789 || cmd_part.contains("hook rewrite")
790 || cmd_part.contains("hook redirect")
791 {
792 return true;
793 }
794 }
795 false
796}
797
798pub fn kill_all_by_name(name: &str) -> usize {
801 let pids = find_killable_pids(name);
802 if pids.is_empty() {
803 return 0;
804 }
805
806 for &pid in &pids {
807 let _ = terminate_gracefully(pid);
808 }
809
810 std::thread::sleep(std::time::Duration::from_millis(500));
811
812 let mut killed = 0;
813 for &pid in &pids {
814 if is_alive(pid) {
815 let _ = force_kill(pid);
816 }
817 killed += 1;
818 }
819
820 std::thread::sleep(std::time::Duration::from_millis(200));
821
822 killed
823}
824
825#[cfg(test)]
826mod tests {
827 use super::*;
828
829 #[test]
830 fn current_process_is_alive() {
831 assert!(is_alive(std::process::id()));
832 }
833
834 #[cfg(target_os = "macos")]
837 #[test]
838 fn name_lookup_is_scoped_to_this_user() {
839 if unsafe { libc::getuid() } == 0 {
841 return;
842 }
843 assert!(!find_pids_by_name("launchd").contains(&1));
844 }
845
846 #[test]
847 fn current_process_identity_is_stable_and_matches() {
848 let pid = std::process::id();
849 let identity = identity(pid).expect("supported platform exposes process identity");
850 assert!(
851 !identity.executable.is_empty(),
852 "`identity.executable` is empty"
853 );
854 assert!(matches_identity(pid, &identity));
855 }
856
857 #[test]
858 fn killable_pids_exclude_active_mcp_stdio_servers() {
859 assert_eq!(
860 killable_excluding_mcp(vec![11, 17, 23], &[11, 23]),
861 vec![17]
862 );
863 }
864
865 #[test]
869 fn in_flight_command_runners_are_never_killable() {
870 for runner in [
871 "lean-ctx -c cargo test --lib",
872 "/Users/me/.local/bin/lean-ctx -c git commit -m x",
873 "/usr/local/bin/lean-ctx exec make",
874 "lean-ctx --track npm test",
875 "lean-ctx -t pytest",
876 ] {
877 assert!(
878 is_command_runner_cmdline(runner),
879 "must be protected: {runner}"
880 );
881 }
882 for stoppable in [
883 "lean-ctx serve --_foreground-daemon",
884 "/Users/me/.local/bin/lean-ctx proxy start --port 4444",
885 "lean-ctx dashboard",
886 "lean-ctx",
887 "/usr/bin/grep -c lean-ctx",
888 "",
889 ] {
890 assert!(
891 !is_command_runner_cmdline(stoppable),
892 "must stay stoppable: {stoppable}"
893 );
894 }
895 }
896
897 #[test]
898 fn bogus_pid_is_not_alive() {
899 assert!(!is_alive(u32::MAX - 42));
900 }
901
902 #[cfg(unix)]
903 #[test]
904 fn run_with_timeout_returns_output_for_fast_command() {
905 let mut cmd = std::process::Command::new("echo");
906 cmd.arg("hello");
907 let out = run_with_timeout(cmd, std::time::Duration::from_secs(5))
908 .expect("fast command should complete");
909 assert!(out.status.success());
910 assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hello");
911 }
912
913 #[cfg(unix)]
914 #[test]
915 fn run_with_timeout_kills_slow_command() {
916 let mut cmd = std::process::Command::new("sleep");
917 cmd.arg("30");
918 let start = std::time::Instant::now();
919 let result = run_with_timeout(cmd, std::time::Duration::from_millis(300));
920 assert!(result.is_none(), "slow command must time out");
921 assert!(
922 start.elapsed() < std::time::Duration::from_secs(5),
923 "timeout must not wait for the full command"
924 );
925 }
926
927 #[test]
928 fn killable_excludes_mcp_pids() {
929 let killable = killable_excluding_mcp(vec![1, 2, 3, 4], &[2, 4]);
933 assert_eq!(killable, vec![1, 3]);
934 assert!(!killable.contains(&2));
935 assert!(!killable.contains(&4));
936 }
937
938 #[test]
939 fn killable_with_no_mcp_returns_all() {
940 let all = vec![10, 20, 30];
941 assert_eq!(killable_excluding_mcp(all.clone(), &[]), all);
942 }
943
944 #[cfg(unix)]
948 #[test]
949 fn protected_pids_cover_own_process_group() {
950 let pgid = unsafe { libc::getpgrp() };
952 let members_before = process_group_pids(pgid);
960 let protected = protected_self_pids();
961 let members_after = process_group_pids(pgid);
962 for pid in members_before {
963 if !members_after.contains(&pid) {
964 continue; }
966 assert!(
967 protected.contains(&pid),
968 "stable group member {pid} missing from protected set"
969 );
970 }
971 }
972
973 #[test]
978 fn protected_pids_cover_self_and_ancestors() {
979 let protected = protected_self_pids();
980 assert!(protected.contains(&std::process::id()));
981 #[cfg(unix)]
982 {
983 let out = std::process::Command::new("ps")
985 .args(["-o", "ppid=", "-p", &std::process::id().to_string()])
986 .output()
987 .expect("ps runs");
988 if let Ok(ppid) = String::from_utf8_lossy(&out.stdout).trim().parse::<u32>()
989 && ppid > 1
990 {
991 assert!(
992 protected.contains(&ppid),
993 "parent {ppid} missing from {protected:?}"
994 );
995 }
996 }
997 }
998
999 #[cfg(unix)]
1000 #[test]
1001 fn find_pids_never_reports_own_process_tree() {
1002 let protected = protected_self_pids();
1005 for pid in find_pids_by_name("lean-ctx") {
1006 assert!(!protected.contains(&pid), "own tree pid {pid} reported");
1007 }
1008 }
1009}