Skip to main content

lean_ctx/ipc/
process.rs

1use anyhow::Result;
2use serde::{Deserialize, Serialize};
3
4/// Immutable OS-level process identity used to defend durable PID references
5/// against PID reuse. A PID may be recycled for an unrelated process after its
6/// original owner exits; the start marker makes that transition observable.
7#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
8pub struct ProcessIdentity {
9    pub start_marker: u64,
10    pub executable: String,
11}
12
13/// Run a command with a hard timeout, capturing its output.
14///
15/// Returns `Some(output)` if the child exits within `timeout`, or `None` if it
16/// had to be killed (timed out) or could not be spawned. This is the safe way
17/// to invoke external control tools (`launchctl`, `systemctl`, a freshly
18/// installed binary's `--version`, …) that must never be able to hang a
19/// `lean-ctx` command — a wedged `launchctl` previously forced users to reboot.
20///
21/// Note: intended for commands with small output. The child's stdout/stderr are
22/// piped; a process that writes more than the pipe buffer (~64 KiB) without
23/// exiting could block. All current callers emit at most a few lines.
24pub 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            // Process exited: pipes are at EOF, so reading output won't block.
42            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
56/// Spawn a long-lived background process (proxy, daemon) detached from the
57/// current process so it survives the parent's exit.
58///
59/// On Unix a child simply outlives its parent, so this is a plain spawn. On
60/// Windows the child inherits the parent's console and — crucially — its Job
61/// object. AI clients (OpenCode, Codex, Claude Code) run MCP servers inside
62/// kill-on-close Jobs; without detachment the auto-started proxy dies the
63/// moment the client recycles its MCP process, which users observe as
64/// "Cannot connect to API: The socket connection was closed unexpectedly"
65/// plus repeated proxy cold-starts (GL #545).
66///
67/// Strategy on Windows:
68///  1. `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB`
69///     — fully detached, escapes the parent's Job.
70///  2. If the Job denies breakaway, `CreateProcess` fails with
71///     `ERROR_ACCESS_DENIED`; retry without the breakaway flag (still
72///     console-detached, which covers non-Job parents).
73pub 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
97/// Check whether a process with the given PID is still running.
98pub fn is_alive(pid: u32) -> bool {
99    #[cfg(unix)]
100    {
101        // SAFETY: `kill` takes the PID and signal (0 = existence probe) by
102        // value; it dereferences no pointers and reports failure via its return
103        // value, so it cannot cause undefined behaviour.
104        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        // SAFETY: every Win32 call below takes integer args plus the local
114        // `exit_code` out-pointer; the handle is null-checked and closed on
115        // every return path, so no resource leaks or invalid pointers occur.
116        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
134/// Returns a PID-reuse-safe identity when the operating system exposes one.
135///
136/// Callers must treat `None` as "not proven alive" for security-sensitive
137/// ownership checks. The supported desktop targets use an immutable process
138/// creation marker plus executable path; unsupported targets deliberately
139/// fail closed rather than trusting a bare PID.
140pub 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
160/// True only when the live process still has the identity captured at
161/// registration. This is intentionally stricter than `is_alive(pid)`.
162pub 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    // SAFETY: `info` points to a suitably sized writable C-compatible buffer.
218    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    // SAFETY: `proc_pidinfo` returned the full structure size above.
231    let info = unsafe { info.assume_init() };
232    let mut path = [0_u8; libc::PATH_MAX as usize];
233    // SAFETY: `path` is a writable byte buffer of the length supplied.
234    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    // SAFETY: the returned handle is checked and closed on every path below.
280    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    // SAFETY: all output pointers refer to initialized local storage.
289    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    // SAFETY: `path` is a writable UTF-16 buffer and `path_len` describes it.
294    let path_ok =
295        unsafe { QueryFullProcessImageNameW(handle, 0, path.as_mut_ptr(), &mut path_len) != 0 };
296    // SAFETY: `handle` was returned by OpenProcess and has not been closed yet.
297    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
311/// Ask a process to terminate gracefully (SIGTERM on Unix, nothing on Windows
312/// since we prefer HTTP shutdown; the caller should have already tried that).
313pub fn terminate_gracefully(pid: u32) -> Result<()> {
314    #[cfg(unix)]
315    {
316        // SAFETY: `kill` takes the PID and signal by value; no pointer is
317        // dereferenced and errors surface via the return value.
318        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
333/// Unconditionally kill a process.
334pub fn force_kill(pid: u32) -> Result<()> {
335    #[cfg(unix)]
336    {
337        // SAFETY: `kill` takes the PID and signal by value; no pointer is
338        // dereferenced and errors surface via the return value.
339        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        // SAFETY: the Win32 calls take integer args only; the handle is
356        // null-checked and closed before returning on every path.
357        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
378/// PIDs this process must never signal: itself, its ancestor chain, and every
379/// member of its own process group.
380///
381/// The ancestor chain matters whenever `lean-ctx stop`/`dev-install` runs
382/// *under* lean-ctx itself — the shell hook routes commands through a
383/// `lean-ctx -c` wrapper, so the process tree is
384/// `lean-ctx -c … → sh → lean-ctx dev-install`. Excluding only `getpid()`
385/// SIGTERMed the wrapper parent, which took the whole pipeline down mid-run
386/// (exit 143) before autostart was re-enabled (#714).
387///
388/// The process *group* matters because agent harnesses (Cursor's shell) can
389/// reparent intermediaries to PID 1 mid-run — the `ps ppid` walk then stops
390/// before reaching the outer wrapper, but the wrapper still shares the
391/// foreground pgid; signalling it kills the pipeline all the same (#714
392/// follow-up, reproduced twice on the first fix).
393fn 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        // SAFETY: getpgrp() takes no arguments and cannot fail.
419        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
442/// Find all PIDs of processes whose executable name matches `name`.
443/// Excludes the current process and its ancestor chain (#714).
444pub 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        // Exact name match first
451        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        // Also find processes where the full command line contains the binary path
460        // (catches processes launched via absolute path, e.g. /Users/x/.local/bin/lean-ctx)
461        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
515/// Returns PIDs that are NOT MCP stdio servers (safe to kill during `lean-ctx stop`).
516/// MCP servers are child processes of the IDE and must not be killed — the IDE
517/// will immediately respawn them, causing a kill loop that requires a reboot.
518pub fn find_killable_pids(name: &str) -> Vec<u32> {
519    killable_excluding_mcp(find_pids_by_name(name), &find_mcp_server_pids(name))
520}
521
522/// Pure set-difference: every PID in `all` that is not an MCP server PID. Split
523/// out from [`find_killable_pids`] so the IDE-protection invariant — the
524/// MCP-stdio server is never returned as killable (#1036) — is unit-testable
525/// without spawning real processes.
526fn 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    // On Windows, check if the parent process is an IDE (Cursor, VS Code).
549    // Uses `wmic` which is available on all supported Windows versions.
550    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        // Direct child of IDE
574        if cmd_line.contains("cursor") || cmd_line.contains("code.exe") {
575            return true;
576        }
577
578        // Check parent process name
579        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        // MCP stdio server heuristic: lean-ctx.exe with no subcommand
599        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        // MCP stdio servers: bare `lean-ctx` with no subcommand (or just `mcp`)
642        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        // Hook observer/rewriter processes spawned by IDE
652        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
662/// Kill non-MCP processes matching `name` (SIGTERM then SIGKILL).
663/// Returns count of killed processes.
664pub 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        // #1036: the IDE-owned MCP stdio server PID must never be returned as
747        // killable, so `cmd_dev_install`'s force-kill cannot drop the editor's
748        // MCP connection.
749        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    /// #714 follow-up: agent harnesses reparent intermediaries to PID 1, so
762    /// the ppid walk alone misses the outer wrapper — the shared foreground
763    /// process group must be protected too.
764    #[cfg(unix)]
765    #[test]
766    fn protected_pids_cover_own_process_group() {
767        // SAFETY: getpgrp() takes no arguments and cannot fail.
768        let pgid = unsafe { libc::getpgrp() };
769        // Bracket `protected_self_pids` with two group snapshots. A single
770        // snapshot is racy under `cargo test` parallelism: sibling tests spawn
771        // short-lived subprocesses (git/ps/pgrep) that transiently join this
772        // foreground process group, so a member seen once may already be gone
773        // when `protected_self_pids` runs — or appear only afterwards. Only PIDs
774        // present in BOTH snapshots were alive across the whole window and must
775        // therefore be covered by the protected set.
776        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; // transient foreign subprocess from a parallel test
782            }
783            assert!(
784                protected.contains(&pid),
785                "stable group member {pid} missing from protected set"
786            );
787        }
788    }
789
790    /// #714: `stop`/`dev-install` running *under* a lean-ctx shell wrapper
791    /// (`lean-ctx -c … → sh → lean-ctx dev-install`) must not SIGTERM its own
792    /// ancestor chain — that killed the pipeline mid-run (exit 143) before
793    /// autostart was re-enabled.
794    #[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            // The direct parent (cargo's test runner) must be protected too.
801            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        // Regardless of what matches by name, the returned set must be
820        // disjoint from the protected self/ancestor set (#714).
821        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}