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, &raw 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(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/// #1947: `kern.proc.pid.<pid>` carries the process start time (`ki_start`),
170/// which a reused PID cannot share, and `kern.proc.pathname.<pid>` the
171/// executable. Without this FreeBSD fell into the fail-closed branch above,
172/// and agent-bus registration refused every tool call.
173#[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    // SAFETY: `mib` holds four valid ints, `info` is a writable buffer of
181    // `info_len` bytes, and no new value is written.
182    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    // SAFETY: sysctl filled the full structure (checked above).
196    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    // SAFETY: `path` is a writable buffer of `path_len` bytes.
214    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    // The returned length includes the trailing NUL.
228    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
239/// True only when the live process still has the identity captured at
240/// registration. This is intentionally stricter than `is_alive(pid)`.
241pub 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    // SAFETY: `info` points to a suitably sized writable C-compatible buffer.
297    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    // SAFETY: `proc_pidinfo` returned the full structure size above.
310    let info = unsafe { info.assume_init() };
311    let mut path = [0_u8; libc::PATH_MAX as usize];
312    // SAFETY: `path` is a writable byte buffer of the length supplied.
313    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    // SAFETY: the returned handle is checked and closed on every path below.
359    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    // SAFETY: all output pointers refer to initialized local storage.
368    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    // SAFETY: `path` is a writable UTF-16 buffer and `path_len` describes it.
380    let path_ok =
381        unsafe { QueryFullProcessImageNameW(handle, 0, path.as_mut_ptr(), &raw mut path_len) != 0 };
382    // SAFETY: `handle` was returned by OpenProcess and has not been closed yet.
383    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
397/// Ask a process to terminate gracefully (SIGTERM on Unix, nothing on Windows
398/// since we prefer HTTP shutdown; the caller should have already tried that).
399pub fn terminate_gracefully(pid: u32) -> Result<()> {
400    #[cfg(unix)]
401    {
402        // SAFETY: `kill` takes the PID and signal by value; no pointer is
403        // dereferenced and errors surface via the return value.
404        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
419/// Unconditionally kill a process.
420pub fn force_kill(pid: u32) -> Result<()> {
421    #[cfg(unix)]
422    {
423        // SAFETY: `kill` takes the PID and signal by value; no pointer is
424        // dereferenced and errors surface via the return value.
425        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        // SAFETY: the Win32 calls take integer args only; the handle is
442        // null-checked and closed before returning on every path.
443        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
464/// PIDs this process must never signal: itself, its ancestor chain, and every
465/// member of its own process group.
466///
467/// The ancestor chain matters whenever `lean-ctx stop`/`dev-install` runs
468/// *under* lean-ctx itself — the shell hook routes commands through a
469/// `lean-ctx -c` wrapper, so the process tree is
470/// `lean-ctx -c … → sh → lean-ctx dev-install`. Excluding only `getpid()`
471/// SIGTERMed the wrapper parent, which took the whole pipeline down mid-run
472/// (exit 143) before autostart was re-enabled (#714).
473///
474/// The process *group* matters because agent harnesses (Cursor's shell) can
475/// reparent intermediaries to PID 1 mid-run — the `ps ppid` walk then stops
476/// before reaching the outer wrapper, but the wrapper still shares the
477/// foreground pgid; signalling it kills the pipeline all the same (#714
478/// follow-up, reproduced twice on the first fix).
479fn 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        // SAFETY: getpgrp() takes no arguments and cannot fail.
505        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
528/// Find all PIDs of processes whose executable name matches `name`.
529/// Excludes the current process and its ancestor chain (#714).
530pub 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        // Exact name match first
537        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        // Also find processes where the full command line contains the binary path
546        // (catches processes launched via absolute path, e.g. /Users/x/.local/bin/lean-ctx)
547        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
601/// Returns PIDs that are safe to kill during `lean-ctx stop`: neither MCP stdio
602/// servers nor in-flight command runners.
603///
604/// MCP servers are child processes of the IDE and must not be killed — the IDE
605/// will immediately respawn them, causing a kill loop that requires a reboot.
606/// Command runners (`lean-ctx -c <cmd>`, `exec`, `--track`) are executing
607/// someone's command right now — another agent's `cargo test`, a commit hook.
608/// Killing one ends that work with SIGTERM/SIGKILL and holds nothing lean-ctx
609/// owns, so even a deliberate "stop everything" leaves them to finish (#1292).
610pub 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
616/// Pure set-difference: every PID in `all` that is not a protected PID (MCP
617/// server or command runner). Split out from [`find_killable_pids`] so the
618/// protection invariant — a protected process is never returned as killable
619/// (#1036, #1292) — is unit-testable without spawning real processes.
620fn killable_excluding_mcp(all: Vec<u32>, protected: &[u32]) -> Vec<u32> {
621    all.into_iter().filter(|p| !protected.contains(p)).collect()
622}
623
624/// `lean-ctx` processes that are running a user's command (#1292).
625#[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/// Windows keeps the running `.exe` locked, so `dev-install` and `uninstall`
639/// must still be able to stop a runner there before replacing the binary.
640#[cfg(not(unix))]
641fn find_command_runner_pids(_name: &str) -> Vec<u32> {
642    Vec::new()
643}
644
645/// True when `command` is a `lean-ctx` invocation that runs a user command:
646/// `-c`/`exec` (the shell wrapper) or `-t`/`--track`.
647// Only the Unix runner lookup calls this; the unit test runs on every target,
648// so the function is not gated, only its dead-code lint off Unix.
649#[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    // On Windows, check if the parent process is an IDE (Cursor, VS Code).
680    // Uses `wmic` which is available on all supported Windows versions.
681    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        // Direct child of IDE
705        if cmd_line.contains("cursor") || cmd_line.contains("code.exe") {
706            return true;
707        }
708
709        // Check parent process name
710        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        // MCP stdio server heuristic: lean-ctx.exe with no subcommand
730        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        // MCP stdio servers: bare `lean-ctx` with no subcommand (or just `mcp`)
773        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        // Hook observer/rewriter processes spawned by IDE
783        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
793/// Kill non-MCP processes matching `name` (SIGTERM then SIGKILL).
794/// Returns count of killed processes.
795pub 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    /// #1292: `lean-ctx stop` SIGKILLed other agents' in-flight commands
846    /// (`lean-ctx -c "cargo test"`, a commit hook) as "orphans". A command
847    /// runner is never killable; daemons, proxies and dashboards still are.
848    #[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        // #1036: the IDE-owned MCP stdio server PID must never be returned as
910        // killable, so `cmd_dev_install`'s force-kill cannot drop the editor's
911        // MCP connection.
912        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    /// #714 follow-up: agent harnesses reparent intermediaries to PID 1, so
925    /// the ppid walk alone misses the outer wrapper — the shared foreground
926    /// process group must be protected too.
927    #[cfg(unix)]
928    #[test]
929    fn protected_pids_cover_own_process_group() {
930        // SAFETY: getpgrp() takes no arguments and cannot fail.
931        let pgid = unsafe { libc::getpgrp() };
932        // Bracket `protected_self_pids` with two group snapshots. A single
933        // snapshot is racy under `cargo test` parallelism: sibling tests spawn
934        // short-lived subprocesses (git/ps/pgrep) that transiently join this
935        // foreground process group, so a member seen once may already be gone
936        // when `protected_self_pids` runs — or appear only afterwards. Only PIDs
937        // present in BOTH snapshots were alive across the whole window and must
938        // therefore be covered by the protected set.
939        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; // transient foreign subprocess from a parallel test
945            }
946            assert!(
947                protected.contains(&pid),
948                "stable group member {pid} missing from protected set"
949            );
950        }
951    }
952
953    /// #714: `stop`/`dev-install` running *under* a lean-ctx shell wrapper
954    /// (`lean-ctx -c … → sh → lean-ctx dev-install`) must not SIGTERM its own
955    /// ancestor chain — that killed the pipeline mid-run (exit 143) before
956    /// autostart was re-enabled.
957    #[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            // The direct parent (cargo's test runner) must be protected too.
964            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        // Regardless of what matches by name, the returned set must be
983        // disjoint from the protected self/ancestor set (#714).
984        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}