use anyhow::Result;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProcessIdentity {
pub start_marker: u64,
pub executable: String,
}
pub fn run_with_timeout(
mut cmd: std::process::Command,
timeout: std::time::Duration,
) -> Option<std::process::Output> {
use std::process::Stdio;
use std::time::Instant;
let mut child = cmd
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.ok()?;
let start = Instant::now();
loop {
match child.try_wait() {
Ok(Some(_)) => return child.wait_with_output().ok(),
Ok(None) => {
if start.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait();
return None;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
Err(_) => return None,
}
}
}
pub fn spawn_detached(cmd: &mut std::process::Command) -> std::io::Result<std::process::Child> {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const DETACHED_PROCESS: u32 = 0x0000_0008;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
let detached = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
match cmd
.creation_flags(detached | CREATE_BREAKAWAY_FROM_JOB)
.spawn()
{
Ok(child) => Ok(child),
Err(_) => cmd.creation_flags(detached).spawn(),
}
}
#[cfg(not(windows))]
{
cmd.spawn()
}
}
pub fn is_alive(pid: u32) -> bool {
#[cfg(unix)]
{
unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
}
#[cfg(windows)]
{
use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE, WAIT_TIMEOUT};
use windows_sys::Win32::System::Threading::{
GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, WaitForSingleObject,
};
unsafe {
let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
if handle.is_null() {
return false;
}
let wait = WaitForSingleObject(handle, 0);
if wait == WAIT_TIMEOUT {
CloseHandle(handle);
return true;
}
let mut exit_code: u32 = 0;
GetExitCodeProcess(handle, &raw mut exit_code);
CloseHandle(handle);
exit_code == STILL_ACTIVE as u32
}
}
}
pub fn identity(pid: u32) -> Option<ProcessIdentity> {
#[cfg(target_os = "macos")]
{
macos_process_identity(pid)
}
#[cfg(target_os = "linux")]
{
linux_process_identity(pid)
}
#[cfg(windows)]
{
windows_process_identity(pid)
}
#[cfg(target_os = "freebsd")]
{
freebsd_process_identity(pid)
}
#[cfg(not(any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
windows
)))]
{
let _ = pid;
None
}
}
#[cfg(target_os = "freebsd")]
fn freebsd_process_identity(pid: u32) -> Option<ProcessIdentity> {
let pid = libc::c_int::try_from(pid).ok()?;
let mut info = std::mem::MaybeUninit::<libc::kinfo_proc>::zeroed();
let mut info_len = std::mem::size_of::<libc::kinfo_proc>();
let mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_PID, pid];
let rc = unsafe {
libc::sysctl(
mib.as_ptr(),
4,
info.as_mut_ptr().cast(),
&mut info_len,
std::ptr::null(),
0,
)
};
if rc != 0 || info_len != std::mem::size_of::<libc::kinfo_proc>() {
return None;
}
let info = unsafe { info.assume_init() };
if info.ki_pid != pid {
return None;
}
let start_marker = u64::try_from(info.ki_start.tv_sec)
.ok()?
.checked_mul(1_000_000)?
.checked_add(u64::try_from(info.ki_start.tv_usec).ok()?)?;
let mut path = [0_u8; libc::PATH_MAX as usize];
let mut path_len = path.len();
let mib = [
libc::CTL_KERN,
libc::KERN_PROC,
libc::KERN_PROC_PATHNAME,
pid,
];
let rc = unsafe {
libc::sysctl(
mib.as_ptr(),
4,
path.as_mut_ptr().cast(),
&mut path_len,
std::ptr::null(),
0,
)
};
if rc != 0 || path_len == 0 {
return None;
}
let bytes = path.get(..path_len)?;
let bytes = bytes.strip_suffix(&[0]).unwrap_or(bytes);
if bytes.is_empty() {
return None;
}
Some(ProcessIdentity {
start_marker,
executable: String::from_utf8_lossy(bytes).into_owned(),
})
}
pub fn matches_identity(pid: u32, expected: &ProcessIdentity) -> bool {
identity(pid).as_ref() == Some(expected)
}
#[cfg(target_os = "macos")]
#[repr(C)]
struct ProcBsdInfo {
pbi_flags: u32,
pbi_status: u32,
pbi_xstatus: u32,
pbi_pid: u32,
pbi_ppid: u32,
pbi_uid: u32,
pbi_gid: u32,
pbi_ruid: u32,
pbi_rgid: u32,
pbi_svuid: u32,
pbi_svgid: u32,
rfu_1: u32,
pbi_comm: [std::ffi::c_char; 16],
pbi_name: [std::ffi::c_char; 32],
pbi_nfiles: u32,
pbi_pgid: u32,
pbi_pjobc: u32,
e_tdev: u32,
e_tpgid: u32,
pbi_nice: i32,
pbi_start_tvsec: u64,
pbi_start_tvusec: u64,
}
#[cfg(target_os = "macos")]
const PROC_PIDTBSDINFO: std::ffi::c_int = 3;
#[cfg(target_os = "macos")]
#[link(name = "proc")]
unsafe extern "C" {
fn proc_pidinfo(
pid: std::ffi::c_int,
flavor: std::ffi::c_int,
arg: u64,
buffer: *mut std::ffi::c_void,
buffersize: std::ffi::c_int,
) -> std::ffi::c_int;
fn proc_pidpath(
pid: std::ffi::c_int,
buffer: *mut std::ffi::c_void,
buffersize: u32,
) -> std::ffi::c_int;
}
#[cfg(target_os = "macos")]
fn macos_process_identity(pid: u32) -> Option<ProcessIdentity> {
let mut info = std::mem::MaybeUninit::<ProcBsdInfo>::zeroed();
let size = i32::try_from(std::mem::size_of::<ProcBsdInfo>()).ok()?;
let read = unsafe {
proc_pidinfo(
i32::try_from(pid).ok()?,
PROC_PIDTBSDINFO,
0,
info.as_mut_ptr().cast(),
size,
)
};
if read != size {
return None;
}
let info = unsafe { info.assume_init() };
let mut path = [0_u8; libc::PATH_MAX as usize];
let path_len = unsafe {
proc_pidpath(
i32::try_from(pid).ok()?,
path.as_mut_ptr().cast(),
u32::try_from(path.len()).ok()?,
)
};
if path_len <= 0 {
return None;
}
let path_len = usize::try_from(path_len).ok()?;
let executable = String::from_utf8_lossy(path.get(..path_len)?).into_owned();
let start_marker = info
.pbi_start_tvsec
.checked_mul(1_000_000)?
.checked_add(info.pbi_start_tvusec)?;
Some(ProcessIdentity {
start_marker,
executable,
})
}
#[cfg(target_os = "linux")]
fn linux_process_identity(pid: u32) -> Option<ProcessIdentity> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let (_, fields) = stat.rsplit_once(')')?;
let start_marker = fields.split_whitespace().nth(19)?.parse().ok()?;
let executable = std::fs::read_link(format!("/proc/{pid}/exe"))
.ok()?
.to_string_lossy()
.into_owned();
Some(ProcessIdentity {
start_marker,
executable,
})
}
#[cfg(windows)]
fn windows_process_identity(pid: u32) -> Option<ProcessIdentity> {
use std::os::windows::ffi::OsStringExt;
use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
use windows_sys::Win32::System::Threading::{
GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
};
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
if handle.is_null() {
return None;
}
let mut created = FILETIME::default();
let mut exited = FILETIME::default();
let mut kernel = FILETIME::default();
let mut user = FILETIME::default();
let times_ok = unsafe {
GetProcessTimes(
handle,
&raw mut created,
&raw mut exited,
&raw mut kernel,
&raw mut user,
)
} != 0;
let mut path = vec![0_u16; 32_768];
let mut path_len = u32::try_from(path.len()).ok()?;
let path_ok =
unsafe { QueryFullProcessImageNameW(handle, 0, path.as_mut_ptr(), &raw mut path_len) != 0 };
unsafe { CloseHandle(handle) };
if !times_ok || !path_ok {
return None;
}
let executable = std::ffi::OsString::from_wide(path.get(..usize::try_from(path_len).ok()?)?)
.to_string_lossy()
.into_owned();
let start_marker = (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime);
Some(ProcessIdentity {
start_marker,
executable,
})
}
pub fn terminate_gracefully(pid: u32) -> Result<()> {
#[cfg(unix)]
{
let ret = unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) };
if ret != 0 {
anyhow::bail!(
"Failed to send SIGTERM to PID {pid}: {}",
std::io::Error::last_os_error()
);
}
Ok(())
}
#[cfg(windows)]
{
force_kill(pid)
}
}
pub fn force_kill(pid: u32) -> Result<()> {
#[cfg(unix)]
{
let ret = unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
if ret != 0 {
anyhow::bail!(
"Failed to send SIGKILL to PID {pid}: {}",
std::io::Error::last_os_error()
);
}
Ok(())
}
#[cfg(windows)]
{
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::{
OpenProcess, PROCESS_TERMINATE, TerminateProcess,
};
unsafe {
let handle = OpenProcess(PROCESS_TERMINATE, 0, pid);
if handle.is_null() {
anyhow::bail!(
"Failed to open PID {pid} for termination: {}",
std::io::Error::last_os_error()
);
}
let ok = TerminateProcess(handle, 1);
CloseHandle(handle);
if ok == 0 {
anyhow::bail!(
"Failed to terminate PID {pid}: {}",
std::io::Error::last_os_error()
);
}
Ok(())
}
}
}
fn protected_self_pids() -> std::collections::HashSet<u32> {
let mut protected = std::collections::HashSet::new();
protected.insert(std::process::id());
#[cfg(unix)]
{
let mut pid = std::process::id();
for _ in 0..16 {
let Ok(output) = std::process::Command::new("ps")
.args(["-o", "ppid=", "-p", &pid.to_string()])
.output()
else {
break;
};
let Ok(ppid) = String::from_utf8_lossy(&output.stdout)
.trim()
.parse::<u32>()
else {
break;
};
if ppid <= 1 || !protected.insert(ppid) {
break;
}
pid = ppid;
}
let own_pgid = unsafe { libc::getpgrp() };
if own_pgid > 0 {
protected.extend(process_group_pids(own_pgid));
}
}
protected
}
#[cfg(unix)]
fn process_group_pids(pgid: libc::pid_t) -> Vec<u32> {
std::process::Command::new("pgrep")
.args(["-g", &pgid.to_string()])
.output()
.ok()
.map(|output| {
String::from_utf8_lossy(&output.stdout)
.lines()
.filter_map(|line| line.trim().parse::<u32>().ok())
.collect()
})
.unwrap_or_default()
}
pub fn find_pids_by_name(name: &str) -> Vec<u32> {
let protected = protected_self_pids();
let mut pids = Vec::new();
#[cfg(unix)]
{
let uid = unsafe { libc::getuid() }.to_string();
if let Ok(output) = std::process::Command::new("pgrep")
.args(["-U", &uid, "-x", name])
.output()
{
collect_pids(&output.stdout, &protected, &mut pids);
}
if let Ok(output) = std::process::Command::new("pgrep")
.args(["-U", &uid])
.arg("-f")
.arg(format!("/{name}(\\s|$)"))
.output()
{
collect_pids(&output.stdout, &protected, &mut pids);
}
pids.sort_unstable();
pids.dedup();
}
#[cfg(windows)]
{
if let Ok(output) = std::process::Command::new("tasklist")
.args([
"/FI",
&format!("IMAGENAME eq {name}.exe"),
"/FO",
"CSV",
"/NH",
])
.output()
{
let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() {
let parts: Vec<&str> = line.split(',').collect();
if parts.len() >= 2 {
let pid_str = parts[1].trim().trim_matches('"');
if let Ok(pid) = pid_str.parse::<u32>() {
if !protected.contains(&pid) {
pids.push(pid);
}
}
}
}
}
}
pids
}
#[cfg(unix)]
fn collect_pids(stdout: &[u8], protected: &std::collections::HashSet<u32>, out: &mut Vec<u32>) {
let text = String::from_utf8_lossy(stdout);
for line in text.lines() {
if let Ok(pid) = line.trim().parse::<u32>()
&& !protected.contains(&pid)
{
out.push(pid);
}
}
}
pub fn find_killable_pids(name: &str) -> Vec<u32> {
let mut protected = find_mcp_server_pids(name);
protected.extend(find_command_runner_pids(name));
killable_excluding_mcp(find_pids_by_name(name), &protected)
}
fn killable_excluding_mcp(all: Vec<u32>, protected: &[u32]) -> Vec<u32> {
all.into_iter().filter(|p| !protected.contains(p)).collect()
}
#[cfg(unix)]
fn find_command_runner_pids(name: &str) -> Vec<u32> {
find_pids_by_name(name)
.into_iter()
.filter(|&pid| {
std::process::Command::new("ps")
.args(["-o", "command=", "-p", &pid.to_string()])
.output()
.is_ok_and(|out| is_command_runner_cmdline(&String::from_utf8_lossy(&out.stdout)))
})
.collect()
}
#[cfg(not(unix))]
fn find_command_runner_pids(_name: &str) -> Vec<u32> {
Vec::new()
}
#[cfg_attr(not(unix), allow(dead_code))]
fn is_command_runner_cmdline(command: &str) -> bool {
let mut words = command.split_whitespace();
let Some(argv0) = words.next() else {
return false;
};
if argv0 != "lean-ctx" && !argv0.ends_with("/lean-ctx") {
return false;
}
matches!(words.next(), Some("-c" | "exec" | "-t" | "--track"))
}
#[cfg(unix)]
fn find_mcp_server_pids(name: &str) -> Vec<u32> {
find_pids_by_name(name)
.into_iter()
.filter(|&pid| is_mcp_stdio_process(pid))
.collect()
}
#[cfg(windows)]
fn find_mcp_server_pids(name: &str) -> Vec<u32> {
find_pids_by_name(name)
.into_iter()
.filter(|&pid| is_mcp_stdio_process_win(pid))
.collect()
}
#[cfg(windows)]
fn is_mcp_stdio_process_win(pid: u32) -> bool {
let Ok(output) = std::process::Command::new("wmic")
.args([
"process",
"where",
&format!("ProcessId={pid}"),
"get",
"ParentProcessId,CommandLine",
"/FORMAT:CSV",
])
.output()
else {
return false;
};
let text = String::from_utf8_lossy(&output.stdout);
for line in text.lines() {
let parts: Vec<&str> = line.split(',').collect();
if parts.len() < 3 {
continue;
}
let cmd_line = parts[1].to_lowercase();
let ppid_str = parts.last().unwrap_or(&"").trim();
if cmd_line.contains("cursor") || cmd_line.contains("code.exe") {
return true;
}
if let Ok(ppid) = ppid_str.parse::<u32>() {
if let Ok(pp_out) = std::process::Command::new("wmic")
.args([
"process",
"where",
&format!("ProcessId={ppid}"),
"get",
"Name",
"/FORMAT:CSV",
])
.output()
{
let pp_text = String::from_utf8_lossy(&pp_out.stdout).to_lowercase();
if pp_text.contains("cursor") || pp_text.contains("code.exe") {
return true;
}
}
}
if (cmd_line.ends_with("lean-ctx.exe") || cmd_line.ends_with("lean-ctx.exe\""))
&& !cmd_line.contains("proxy")
&& !cmd_line.contains("dashboard")
&& !cmd_line.contains("daemon")
&& !cmd_line.contains("stop")
&& !cmd_line.contains("hook")
{
return true;
}
}
false
}
#[cfg(not(any(unix, windows)))]
fn find_mcp_server_pids(_name: &str) -> Vec<u32> {
Vec::new()
}
#[cfg(unix)]
fn is_mcp_stdio_process(pid: u32) -> bool {
if let Ok(output) = std::process::Command::new("ps")
.args(["-o", "ppid=,command=", "-p", &pid.to_string()])
.output()
{
let text = String::from_utf8_lossy(&output.stdout);
let t = text.trim();
if t.contains("Cursor") || t.contains("cursor") || t.contains("code") {
return true;
}
let parts: Vec<&str> = t.split_whitespace().collect();
if let Some(ppid_str) = parts.first()
&& let Ok(ppid) = ppid_str.parse::<u32>()
&& let Ok(pp_out) = std::process::Command::new("ps")
.args(["-o", "command=", "-p", &ppid.to_string()])
.output()
{
let pp_cmd = String::from_utf8_lossy(&pp_out.stdout);
if pp_cmd.contains("Cursor") || pp_cmd.contains("cursor") || pp_cmd.contains("code") {
return true;
}
}
let cmd_part = parts.get(1..).map(|p| p.join(" ")).unwrap_or_default();
if (cmd_part.ends_with("/lean-ctx") || cmd_part == "lean-ctx")
&& !cmd_part.contains("proxy")
&& !cmd_part.contains("dashboard")
&& !cmd_part.contains("daemon")
&& !cmd_part.contains("stop")
&& !cmd_part.contains("hook")
{
return true;
}
if cmd_part.contains("hook observe")
|| cmd_part.contains("hook rewrite")
|| cmd_part.contains("hook redirect")
{
return true;
}
}
false
}
pub fn kill_all_by_name(name: &str) -> usize {
let pids = find_killable_pids(name);
if pids.is_empty() {
return 0;
}
for &pid in &pids {
let _ = terminate_gracefully(pid);
}
std::thread::sleep(std::time::Duration::from_millis(500));
let mut killed = 0;
for &pid in &pids {
if is_alive(pid) {
let _ = force_kill(pid);
}
killed += 1;
}
std::thread::sleep(std::time::Duration::from_millis(200));
killed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn current_process_is_alive() {
assert!(is_alive(std::process::id()));
}
#[cfg(target_os = "macos")]
#[test]
fn name_lookup_is_scoped_to_this_user() {
if unsafe { libc::getuid() } == 0 {
return;
}
assert!(!find_pids_by_name("launchd").contains(&1));
}
#[test]
fn current_process_identity_is_stable_and_matches() {
let pid = std::process::id();
let identity = identity(pid).expect("supported platform exposes process identity");
assert!(
!identity.executable.is_empty(),
"`identity.executable` is empty"
);
assert!(matches_identity(pid, &identity));
}
#[test]
fn killable_pids_exclude_active_mcp_stdio_servers() {
assert_eq!(
killable_excluding_mcp(vec![11, 17, 23], &[11, 23]),
vec![17]
);
}
#[test]
fn in_flight_command_runners_are_never_killable() {
for runner in [
"lean-ctx -c cargo test --lib",
"/Users/me/.local/bin/lean-ctx -c git commit -m x",
"/usr/local/bin/lean-ctx exec make",
"lean-ctx --track npm test",
"lean-ctx -t pytest",
] {
assert!(
is_command_runner_cmdline(runner),
"must be protected: {runner}"
);
}
for stoppable in [
"lean-ctx serve --_foreground-daemon",
"/Users/me/.local/bin/lean-ctx proxy start --port 4444",
"lean-ctx dashboard",
"lean-ctx",
"/usr/bin/grep -c lean-ctx",
"",
] {
assert!(
!is_command_runner_cmdline(stoppable),
"must stay stoppable: {stoppable}"
);
}
}
#[test]
fn bogus_pid_is_not_alive() {
assert!(!is_alive(u32::MAX - 42));
}
#[cfg(unix)]
#[test]
fn run_with_timeout_returns_output_for_fast_command() {
let mut cmd = std::process::Command::new("echo");
cmd.arg("hello");
let out = run_with_timeout(cmd, std::time::Duration::from_secs(5))
.expect("fast command should complete");
assert!(out.status.success());
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hello");
}
#[cfg(unix)]
#[test]
fn run_with_timeout_kills_slow_command() {
let mut cmd = std::process::Command::new("sleep");
cmd.arg("30");
let start = std::time::Instant::now();
let result = run_with_timeout(cmd, std::time::Duration::from_millis(300));
assert!(result.is_none(), "slow command must time out");
assert!(
start.elapsed() < std::time::Duration::from_secs(5),
"timeout must not wait for the full command"
);
}
#[test]
fn killable_excludes_mcp_pids() {
let killable = killable_excluding_mcp(vec![1, 2, 3, 4], &[2, 4]);
assert_eq!(killable, vec![1, 3]);
assert!(!killable.contains(&2));
assert!(!killable.contains(&4));
}
#[test]
fn killable_with_no_mcp_returns_all() {
let all = vec![10, 20, 30];
assert_eq!(killable_excluding_mcp(all.clone(), &[]), all);
}
#[cfg(unix)]
#[test]
fn protected_pids_cover_own_process_group() {
let pgid = unsafe { libc::getpgrp() };
let members_before = process_group_pids(pgid);
let protected = protected_self_pids();
let members_after = process_group_pids(pgid);
for pid in members_before {
if !members_after.contains(&pid) {
continue; }
assert!(
protected.contains(&pid),
"stable group member {pid} missing from protected set"
);
}
}
#[test]
fn protected_pids_cover_self_and_ancestors() {
let protected = protected_self_pids();
assert!(protected.contains(&std::process::id()));
#[cfg(unix)]
{
let out = std::process::Command::new("ps")
.args(["-o", "ppid=", "-p", &std::process::id().to_string()])
.output()
.expect("ps runs");
if let Ok(ppid) = String::from_utf8_lossy(&out.stdout).trim().parse::<u32>()
&& ppid > 1
{
assert!(
protected.contains(&ppid),
"parent {ppid} missing from {protected:?}"
);
}
}
}
#[cfg(unix)]
#[test]
fn find_pids_never_reports_own_process_tree() {
let protected = protected_self_pids();
for pid in find_pids_by_name("lean-ctx") {
assert!(!protected.contains(&pid), "own tree pid {pid} reported");
}
}
}