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, &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(not(any(target_os = "macos", target_os = "linux", windows)))]
154 {
155 let _ = pid;
156 None
157 }
158}
159
160pub fn matches_identity(pid: u32, expected: &ProcessIdentity) -> bool {
163 identity(pid).as_ref() == Some(expected)
164}
165
166#[cfg(target_os = "macos")]
167#[repr(C)]
168struct ProcBsdInfo {
169 pbi_flags: u32,
170 pbi_status: u32,
171 pbi_xstatus: u32,
172 pbi_pid: u32,
173 pbi_ppid: u32,
174 pbi_uid: u32,
175 pbi_gid: u32,
176 pbi_ruid: u32,
177 pbi_rgid: u32,
178 pbi_svuid: u32,
179 pbi_svgid: u32,
180 rfu_1: u32,
181 pbi_comm: [std::ffi::c_char; 16],
182 pbi_name: [std::ffi::c_char; 32],
183 pbi_nfiles: u32,
184 pbi_pgid: u32,
185 pbi_pjobc: u32,
186 e_tdev: u32,
187 e_tpgid: u32,
188 pbi_nice: i32,
189 pbi_start_tvsec: u64,
190 pbi_start_tvusec: u64,
191}
192
193#[cfg(target_os = "macos")]
194const PROC_PIDTBSDINFO: std::ffi::c_int = 3;
195
196#[cfg(target_os = "macos")]
197#[link(name = "proc")]
198unsafe extern "C" {
199 fn proc_pidinfo(
200 pid: std::ffi::c_int,
201 flavor: std::ffi::c_int,
202 arg: u64,
203 buffer: *mut std::ffi::c_void,
204 buffersize: std::ffi::c_int,
205 ) -> std::ffi::c_int;
206 fn proc_pidpath(
207 pid: std::ffi::c_int,
208 buffer: *mut std::ffi::c_void,
209 buffersize: u32,
210 ) -> std::ffi::c_int;
211}
212
213#[cfg(target_os = "macos")]
214fn macos_process_identity(pid: u32) -> Option<ProcessIdentity> {
215 let mut info = std::mem::MaybeUninit::<ProcBsdInfo>::zeroed();
216 let size = i32::try_from(std::mem::size_of::<ProcBsdInfo>()).ok()?;
217 let read = unsafe {
219 proc_pidinfo(
220 i32::try_from(pid).ok()?,
221 PROC_PIDTBSDINFO,
222 0,
223 info.as_mut_ptr().cast(),
224 size,
225 )
226 };
227 if read != size {
228 return None;
229 }
230 let info = unsafe { info.assume_init() };
232 let mut path = [0_u8; libc::PATH_MAX as usize];
233 let path_len = unsafe {
235 proc_pidpath(
236 i32::try_from(pid).ok()?,
237 path.as_mut_ptr().cast(),
238 u32::try_from(path.len()).ok()?,
239 )
240 };
241 if path_len <= 0 {
242 return None;
243 }
244 let path_len = usize::try_from(path_len).ok()?;
245 let executable = String::from_utf8_lossy(path.get(..path_len)?).into_owned();
246 let start_marker = info
247 .pbi_start_tvsec
248 .checked_mul(1_000_000)?
249 .checked_add(info.pbi_start_tvusec)?;
250 Some(ProcessIdentity {
251 start_marker,
252 executable,
253 })
254}
255
256#[cfg(target_os = "linux")]
257fn linux_process_identity(pid: u32) -> Option<ProcessIdentity> {
258 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
259 let (_, fields) = stat.rsplit_once(')')?;
260 let start_marker = fields.split_whitespace().nth(19)?.parse().ok()?;
261 let executable = std::fs::read_link(format!("/proc/{pid}/exe"))
262 .ok()?
263 .to_string_lossy()
264 .into_owned();
265 Some(ProcessIdentity {
266 start_marker,
267 executable,
268 })
269}
270
271#[cfg(windows)]
272fn windows_process_identity(pid: u32) -> Option<ProcessIdentity> {
273 use std::os::windows::ffi::OsStringExt;
274 use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
275 use windows_sys::Win32::System::Threading::{
276 GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
277 };
278
279 let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
281 if handle.is_null() {
282 return None;
283 }
284 let mut created = FILETIME::default();
285 let mut exited = FILETIME::default();
286 let mut kernel = FILETIME::default();
287 let mut user = FILETIME::default();
288 let times_ok =
290 unsafe { GetProcessTimes(handle, &mut created, &mut exited, &mut kernel, &mut user) } != 0;
291 let mut path = vec![0_u16; 32_768];
292 let mut path_len = u32::try_from(path.len()).ok()?;
293 let path_ok =
295 unsafe { QueryFullProcessImageNameW(handle, 0, path.as_mut_ptr(), &mut path_len) != 0 };
296 unsafe { CloseHandle(handle) };
298 if !times_ok || !path_ok {
299 return None;
300 }
301 let executable = std::ffi::OsString::from_wide(path.get(..usize::try_from(path_len).ok()?)?)
302 .to_string_lossy()
303 .into_owned();
304 let start_marker = (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime);
305 Some(ProcessIdentity {
306 start_marker,
307 executable,
308 })
309}
310
311pub fn terminate_gracefully(pid: u32) -> Result<()> {
314 #[cfg(unix)]
315 {
316 let ret = unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) };
319 if ret != 0 {
320 anyhow::bail!(
321 "Failed to send SIGTERM to PID {pid}: {}",
322 std::io::Error::last_os_error()
323 );
324 }
325 Ok(())
326 }
327 #[cfg(windows)]
328 {
329 force_kill(pid)
330 }
331}
332
333pub fn force_kill(pid: u32) -> Result<()> {
335 #[cfg(unix)]
336 {
337 let ret = unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
340 if ret != 0 {
341 anyhow::bail!(
342 "Failed to send SIGKILL to PID {pid}: {}",
343 std::io::Error::last_os_error()
344 );
345 }
346 Ok(())
347 }
348 #[cfg(windows)]
349 {
350 use windows_sys::Win32::Foundation::CloseHandle;
351 use windows_sys::Win32::System::Threading::{
352 OpenProcess, PROCESS_TERMINATE, TerminateProcess,
353 };
354
355 unsafe {
358 let handle = OpenProcess(PROCESS_TERMINATE, 0, pid);
359 if handle.is_null() {
360 anyhow::bail!(
361 "Failed to open PID {pid} for termination: {}",
362 std::io::Error::last_os_error()
363 );
364 }
365 let ok = TerminateProcess(handle, 1);
366 CloseHandle(handle);
367 if ok == 0 {
368 anyhow::bail!(
369 "Failed to terminate PID {pid}: {}",
370 std::io::Error::last_os_error()
371 );
372 }
373 Ok(())
374 }
375 }
376}
377
378fn protected_self_pids() -> std::collections::HashSet<u32> {
394 let mut protected = std::collections::HashSet::new();
395 protected.insert(std::process::id());
396 #[cfg(unix)]
397 {
398 let mut pid = std::process::id();
399 for _ in 0..16 {
400 let Ok(output) = std::process::Command::new("ps")
401 .args(["-o", "ppid=", "-p", &pid.to_string()])
402 .output()
403 else {
404 break;
405 };
406 let Ok(ppid) = String::from_utf8_lossy(&output.stdout)
407 .trim()
408 .parse::<u32>()
409 else {
410 break;
411 };
412 if ppid <= 1 || !protected.insert(ppid) {
413 break;
414 }
415 pid = ppid;
416 }
417
418 let own_pgid = unsafe { libc::getpgrp() };
420 if own_pgid > 0 {
421 protected.extend(process_group_pids(own_pgid));
422 }
423 }
424 protected
425}
426
427#[cfg(unix)]
428fn process_group_pids(pgid: libc::pid_t) -> Vec<u32> {
429 std::process::Command::new("pgrep")
430 .args(["-g", &pgid.to_string()])
431 .output()
432 .ok()
433 .map(|output| {
434 String::from_utf8_lossy(&output.stdout)
435 .lines()
436 .filter_map(|line| line.trim().parse::<u32>().ok())
437 .collect()
438 })
439 .unwrap_or_default()
440}
441
442pub fn find_pids_by_name(name: &str) -> Vec<u32> {
445 let protected = protected_self_pids();
446 let mut pids = Vec::new();
447
448 #[cfg(unix)]
449 {
450 if let Ok(output) = std::process::Command::new("pgrep")
452 .arg("-x")
453 .arg(name)
454 .output()
455 {
456 collect_pids(&output.stdout, &protected, &mut pids);
457 }
458
459 if let Ok(output) = std::process::Command::new("pgrep")
462 .arg("-f")
463 .arg(format!("/{name}(\\s|$)"))
464 .output()
465 {
466 collect_pids(&output.stdout, &protected, &mut pids);
467 }
468
469 pids.sort_unstable();
470 pids.dedup();
471 }
472
473 #[cfg(windows)]
474 {
475 if let Ok(output) = std::process::Command::new("tasklist")
476 .args([
477 "/FI",
478 &format!("IMAGENAME eq {name}.exe"),
479 "/FO",
480 "CSV",
481 "/NH",
482 ])
483 .output()
484 {
485 let stdout = String::from_utf8_lossy(&output.stdout);
486 for line in stdout.lines() {
487 let parts: Vec<&str> = line.split(',').collect();
488 if parts.len() >= 2 {
489 let pid_str = parts[1].trim().trim_matches('"');
490 if let Ok(pid) = pid_str.parse::<u32>() {
491 if !protected.contains(&pid) {
492 pids.push(pid);
493 }
494 }
495 }
496 }
497 }
498 }
499
500 pids
501}
502
503#[cfg(unix)]
504fn collect_pids(stdout: &[u8], protected: &std::collections::HashSet<u32>, out: &mut Vec<u32>) {
505 let text = String::from_utf8_lossy(stdout);
506 for line in text.lines() {
507 if let Ok(pid) = line.trim().parse::<u32>()
508 && !protected.contains(&pid)
509 {
510 out.push(pid);
511 }
512 }
513}
514
515pub fn find_killable_pids(name: &str) -> Vec<u32> {
519 killable_excluding_mcp(find_pids_by_name(name), &find_mcp_server_pids(name))
520}
521
522fn killable_excluding_mcp(all: Vec<u32>, mcp: &[u32]) -> Vec<u32> {
527 all.into_iter().filter(|p| !mcp.contains(p)).collect()
528}
529
530#[cfg(unix)]
531fn find_mcp_server_pids(name: &str) -> Vec<u32> {
532 find_pids_by_name(name)
533 .into_iter()
534 .filter(|&pid| is_mcp_stdio_process(pid))
535 .collect()
536}
537
538#[cfg(windows)]
539fn find_mcp_server_pids(name: &str) -> Vec<u32> {
540 find_pids_by_name(name)
541 .into_iter()
542 .filter(|&pid| is_mcp_stdio_process_win(pid))
543 .collect()
544}
545
546#[cfg(windows)]
547fn is_mcp_stdio_process_win(pid: u32) -> bool {
548 let Ok(output) = std::process::Command::new("wmic")
551 .args([
552 "process",
553 "where",
554 &format!("ProcessId={pid}"),
555 "get",
556 "ParentProcessId,CommandLine",
557 "/FORMAT:CSV",
558 ])
559 .output()
560 else {
561 return false;
562 };
563
564 let text = String::from_utf8_lossy(&output.stdout);
565 for line in text.lines() {
566 let parts: Vec<&str> = line.split(',').collect();
567 if parts.len() < 3 {
568 continue;
569 }
570 let cmd_line = parts[1].to_lowercase();
571 let ppid_str = parts.last().unwrap_or(&"").trim();
572
573 if cmd_line.contains("cursor") || cmd_line.contains("code.exe") {
575 return true;
576 }
577
578 if let Ok(ppid) = ppid_str.parse::<u32>() {
580 if let Ok(pp_out) = std::process::Command::new("wmic")
581 .args([
582 "process",
583 "where",
584 &format!("ProcessId={ppid}"),
585 "get",
586 "Name",
587 "/FORMAT:CSV",
588 ])
589 .output()
590 {
591 let pp_text = String::from_utf8_lossy(&pp_out.stdout).to_lowercase();
592 if pp_text.contains("cursor") || pp_text.contains("code.exe") {
593 return true;
594 }
595 }
596 }
597
598 if (cmd_line.ends_with("lean-ctx.exe") || cmd_line.ends_with("lean-ctx.exe\""))
600 && !cmd_line.contains("proxy")
601 && !cmd_line.contains("dashboard")
602 && !cmd_line.contains("daemon")
603 && !cmd_line.contains("stop")
604 && !cmd_line.contains("hook")
605 {
606 return true;
607 }
608 }
609 false
610}
611
612#[cfg(not(any(unix, windows)))]
613fn find_mcp_server_pids(_name: &str) -> Vec<u32> {
614 Vec::new()
615}
616
617#[cfg(unix)]
618fn is_mcp_stdio_process(pid: u32) -> bool {
619 if let Ok(output) = std::process::Command::new("ps")
620 .args(["-o", "ppid=,command=", "-p", &pid.to_string()])
621 .output()
622 {
623 let text = String::from_utf8_lossy(&output.stdout);
624 let t = text.trim();
625 if t.contains("Cursor") || t.contains("cursor") || t.contains("code") {
626 return true;
627 }
628 let parts: Vec<&str> = t.split_whitespace().collect();
629 if let Some(ppid_str) = parts.first()
630 && let Ok(ppid) = ppid_str.parse::<u32>()
631 && let Ok(pp_out) = std::process::Command::new("ps")
632 .args(["-o", "command=", "-p", &ppid.to_string()])
633 .output()
634 {
635 let pp_cmd = String::from_utf8_lossy(&pp_out.stdout);
636 if pp_cmd.contains("Cursor") || pp_cmd.contains("cursor") || pp_cmd.contains("code") {
637 return true;
638 }
639 }
640 let cmd_part = parts.get(1..).map(|p| p.join(" ")).unwrap_or_default();
641 if (cmd_part.ends_with("/lean-ctx") || cmd_part == "lean-ctx")
643 && !cmd_part.contains("proxy")
644 && !cmd_part.contains("dashboard")
645 && !cmd_part.contains("daemon")
646 && !cmd_part.contains("stop")
647 && !cmd_part.contains("hook")
648 {
649 return true;
650 }
651 if cmd_part.contains("hook observe")
653 || cmd_part.contains("hook rewrite")
654 || cmd_part.contains("hook redirect")
655 {
656 return true;
657 }
658 }
659 false
660}
661
662pub fn kill_all_by_name(name: &str) -> usize {
665 let pids = find_killable_pids(name);
666 if pids.is_empty() {
667 return 0;
668 }
669
670 for &pid in &pids {
671 let _ = terminate_gracefully(pid);
672 }
673
674 std::thread::sleep(std::time::Duration::from_millis(500));
675
676 let mut killed = 0;
677 for &pid in &pids {
678 if is_alive(pid) {
679 let _ = force_kill(pid);
680 }
681 killed += 1;
682 }
683
684 std::thread::sleep(std::time::Duration::from_millis(200));
685
686 killed
687}
688
689#[cfg(test)]
690mod tests {
691 use super::*;
692
693 #[test]
694 fn current_process_is_alive() {
695 assert!(is_alive(std::process::id()));
696 }
697
698 #[test]
699 fn current_process_identity_is_stable_and_matches() {
700 let pid = std::process::id();
701 let identity = identity(pid).expect("supported platform exposes process identity");
702 assert!(!identity.executable.is_empty());
703 assert!(matches_identity(pid, &identity));
704 }
705
706 #[test]
707 fn killable_pids_exclude_active_mcp_stdio_servers() {
708 assert_eq!(
709 killable_excluding_mcp(vec![11, 17, 23], &[11, 23]),
710 vec![17]
711 );
712 }
713
714 #[test]
715 fn bogus_pid_is_not_alive() {
716 assert!(!is_alive(u32::MAX - 42));
717 }
718
719 #[cfg(unix)]
720 #[test]
721 fn run_with_timeout_returns_output_for_fast_command() {
722 let mut cmd = std::process::Command::new("echo");
723 cmd.arg("hello");
724 let out = run_with_timeout(cmd, std::time::Duration::from_secs(5))
725 .expect("fast command should complete");
726 assert!(out.status.success());
727 assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hello");
728 }
729
730 #[cfg(unix)]
731 #[test]
732 fn run_with_timeout_kills_slow_command() {
733 let mut cmd = std::process::Command::new("sleep");
734 cmd.arg("30");
735 let start = std::time::Instant::now();
736 let result = run_with_timeout(cmd, std::time::Duration::from_millis(300));
737 assert!(result.is_none(), "slow command must time out");
738 assert!(
739 start.elapsed() < std::time::Duration::from_secs(5),
740 "timeout must not wait for the full command"
741 );
742 }
743
744 #[test]
745 fn killable_excludes_mcp_pids() {
746 let killable = killable_excluding_mcp(vec![1, 2, 3, 4], &[2, 4]);
750 assert_eq!(killable, vec![1, 3]);
751 assert!(!killable.contains(&2));
752 assert!(!killable.contains(&4));
753 }
754
755 #[test]
756 fn killable_with_no_mcp_returns_all() {
757 let all = vec![10, 20, 30];
758 assert_eq!(killable_excluding_mcp(all.clone(), &[]), all);
759 }
760
761 #[cfg(unix)]
765 #[test]
766 fn protected_pids_cover_own_process_group() {
767 let pgid = unsafe { libc::getpgrp() };
769 let members_before = process_group_pids(pgid);
777 let protected = protected_self_pids();
778 let members_after = process_group_pids(pgid);
779 for pid in members_before {
780 if !members_after.contains(&pid) {
781 continue; }
783 assert!(
784 protected.contains(&pid),
785 "stable group member {pid} missing from protected set"
786 );
787 }
788 }
789
790 #[test]
795 fn protected_pids_cover_self_and_ancestors() {
796 let protected = protected_self_pids();
797 assert!(protected.contains(&std::process::id()));
798 #[cfg(unix)]
799 {
800 let out = std::process::Command::new("ps")
802 .args(["-o", "ppid=", "-p", &std::process::id().to_string()])
803 .output()
804 .expect("ps runs");
805 if let Ok(ppid) = String::from_utf8_lossy(&out.stdout).trim().parse::<u32>()
806 && ppid > 1
807 {
808 assert!(
809 protected.contains(&ppid),
810 "parent {ppid} missing from {protected:?}"
811 );
812 }
813 }
814 }
815
816 #[cfg(unix)]
817 #[test]
818 fn find_pids_never_reports_own_process_tree() {
819 let protected = protected_self_pids();
822 for pid in find_pids_by_name("lean-ctx") {
823 assert!(!protected.contains(&pid), "own tree pid {pid} reported");
824 }
825 }
826}