Skip to main content

agentmux_srv_core/backend/
process_identity.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Whether a pid another srv recorded still belongs to that srv. A recorded
5//! pid can belong to any program by now (chrome.exe, conhost.exe), so a live
6//! pid alone says nothing (#1270, #5367): the process must be an
7//! `agentmux-srv` binary that started no later than its claim was written.
8//! Used by the slug migration's stale-lock check and by a cron run another
9//! channel follows (#1988).
10
11use std::time::SystemTime;
12
13/// How long after a claim was written its srv may still have started: the
14/// claim's time and the process's start time come from different clocks'
15/// rounding.
16pub const START_SLACK_SECS: u64 = 5;
17
18/// Whether `pid` is still an srv, and, given when its claim was `written`,
19/// the one that wrote it. The name rule is the launcher's (`stale_srv.rs`).
20pub fn srv_alive(pid: u32, written: Option<SystemTime>) -> bool {
21    #[cfg(any(test, feature = "test-support"))]
22    if let Some(srv) = test_srv::is_srv(pid) {
23        return srv && crate::backend::reactive::registry::pid_alive(pid);
24    }
25    let target = sysinfo::Pid::from(pid as usize);
26    let mut sys = sysinfo::System::new();
27    sys.refresh_processes_specifics(sysinfo::ProcessesToUpdate::Some(&[target]), true, sysinfo::ProcessRefreshKind::nothing());
28    let Some(process) = sys.process(target) else { return false };
29    let written_secs = written.and_then(|w| w.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs());
30    is_srv_that_wrote(&process.name().to_string_lossy(), process.start_time(), written_secs)
31}
32
33/// [`srv_alive`]'s rule on a process's executable `name` and start time: an
34/// `agentmux-srv` binary started no later than its claim was written.
35pub fn is_srv_that_wrote(name: &str, started_secs: u64, written_secs: Option<u64>) -> bool {
36    name.to_ascii_lowercase().starts_with("agentmux-srv") && written_secs.is_none_or(|w| started_secs <= w + START_SLACK_SECS)
37}
38
39/// Tests stand in for an srv with their own process, which isn't one by
40/// name: each test thread says which pids count.
41#[cfg(any(test, feature = "test-support"))]
42pub mod test_srv {
43    use std::cell::RefCell;
44    use std::collections::HashSet;
45
46    thread_local!(static SRV: RefCell<Option<HashSet<u32>>> = const { RefCell::new(None) });
47
48    /// From now on, on this thread, exactly `pids` are srv processes.
49    pub fn treat_as_srv(pids: &[u32]) {
50        SRV.with(|s| *s.borrow_mut() = Some(pids.iter().copied().collect()));
51    }
52
53    pub(super) fn is_srv(pid: u32) -> Option<bool> {
54        SRV.with(|s| s.borrow().as_ref().map(|set| set.contains(&pid)))
55    }
56}