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        // Only this user's processes: `stop` and `uninstall` act for the caller
537        // and never reach another account's lean-ctx, even when run as root.
538        // SAFETY: getuid has no preconditions and cannot fail.
539        let uid = unsafe { libc::getuid() }.to_string();
540
541        // Exact name match first
542        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        // Also find processes where the full command line contains the binary path
550        // (catches processes launched via absolute path, e.g. /Users/x/.local/bin/lean-ctx)
551        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
606/// Returns PIDs that are safe to kill during `lean-ctx stop`: neither MCP stdio
607/// servers nor in-flight command runners.
608///
609/// MCP servers are child processes of the IDE and must not be killed — the IDE
610/// will immediately respawn them, causing a kill loop that requires a reboot.
611/// Command runners (`lean-ctx -c <cmd>`, `exec`, `--track`) are executing
612/// someone's command right now — another agent's `cargo test`, a commit hook.
613/// Killing one ends that work with SIGTERM/SIGKILL and holds nothing lean-ctx
614/// owns, so even a deliberate "stop everything" leaves them to finish (#1292).
615pub 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
621/// Pure set-difference: every PID in `all` that is not a protected PID (MCP
622/// server or command runner). Split out from [`find_killable_pids`] so the
623/// protection invariant — a protected process is never returned as killable
624/// (#1036, #1292) — is unit-testable without spawning real processes.
625fn killable_excluding_mcp(all: Vec<u32>, protected: &[u32]) -> Vec<u32> {
626    all.into_iter().filter(|p| !protected.contains(p)).collect()
627}
628
629/// `lean-ctx` processes that are running a user's command (#1292).
630#[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/// Windows keeps the running `.exe` locked, so `dev-install` and `uninstall`
644/// must still be able to stop a runner there before replacing the binary.
645#[cfg(not(unix))]
646fn find_command_runner_pids(_name: &str) -> Vec<u32> {
647    Vec::new()
648}
649
650/// True when `command` is a `lean-ctx` invocation that runs a user command:
651/// `-c`/`exec` (the shell wrapper) or `-t`/`--track`.
652// Only the Unix runner lookup calls this; the unit test runs on every target,
653// so the function is not gated, only its dead-code lint off Unix.
654#[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    // On Windows, check if the parent process is an IDE (Cursor, VS Code).
685    // Uses `wmic` which is available on all supported Windows versions.
686    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        // Direct child of IDE
710        if cmd_line.contains("cursor") || cmd_line.contains("code.exe") {
711            return true;
712        }
713
714        // Check parent process name
715        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        // MCP stdio server heuristic: lean-ctx.exe with no subcommand
735        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        // MCP stdio servers: bare `lean-ctx` with no subcommand (or just `mcp`)
778        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        // Hook observer/rewriter processes spawned by IDE
788        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
798/// Kill non-MCP processes matching `name` (SIGTERM then SIGKILL).
799/// Returns count of killed processes.
800pub 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    /// `stop`/`uninstall` never reach another account's processes: root's
835    /// launchd (PID 1) is not a candidate for an ordinary user.
836    #[cfg(target_os = "macos")]
837    #[test]
838    fn name_lookup_is_scoped_to_this_user() {
839        // SAFETY: getuid has no preconditions and cannot fail.
840        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    /// #1292: `lean-ctx stop` SIGKILLed other agents' in-flight commands
866    /// (`lean-ctx -c "cargo test"`, a commit hook) as "orphans". A command
867    /// runner is never killable; daemons, proxies and dashboards still are.
868    #[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        // #1036: the IDE-owned MCP stdio server PID must never be returned as
930        // killable, so `cmd_dev_install`'s force-kill cannot drop the editor's
931        // MCP connection.
932        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    /// #714 follow-up: agent harnesses reparent intermediaries to PID 1, so
945    /// the ppid walk alone misses the outer wrapper — the shared foreground
946    /// process group must be protected too.
947    #[cfg(unix)]
948    #[test]
949    fn protected_pids_cover_own_process_group() {
950        // SAFETY: getpgrp() takes no arguments and cannot fail.
951        let pgid = unsafe { libc::getpgrp() };
952        // Bracket `protected_self_pids` with two group snapshots. A single
953        // snapshot is racy under `cargo test` parallelism: sibling tests spawn
954        // short-lived subprocesses (git/ps/pgrep) that transiently join this
955        // foreground process group, so a member seen once may already be gone
956        // when `protected_self_pids` runs — or appear only afterwards. Only PIDs
957        // present in BOTH snapshots were alive across the whole window and must
958        // therefore be covered by the protected set.
959        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; // transient foreign subprocess from a parallel test
965            }
966            assert!(
967                protected.contains(&pid),
968                "stable group member {pid} missing from protected set"
969            );
970        }
971    }
972
973    /// #714: `stop`/`dev-install` running *under* a lean-ctx shell wrapper
974    /// (`lean-ctx -c … → sh → lean-ctx dev-install`) must not SIGTERM its own
975    /// ancestor chain — that killed the pipeline mid-run (exit 143) before
976    /// autostart was re-enabled.
977    #[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            // The direct parent (cargo's test runner) must be protected too.
984            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        // Regardless of what matches by name, the returned set must be
1003        // disjoint from the protected self/ancestor set (#714).
1004        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}