Skip to main content

mur_common/
lock_file.rs

1//! Canonical `running.lock` reader + 3-state agent status classifier.
2//!
3//! Used by:
4//! - `mur agent list/status` (CLI) — see `mur-core/src/cmd/agent.rs`
5//! - `/api/v1/agents/*` (HTTP) — see `mur-core/src/server_agents/`
6//! - `mur-agent-runtime` supervisor — see `mur-agent-runtime/src/lock_file.rs`
7//!   (the runtime additionally uses `flock`; that check stays local)
8
9use crate::LockFile;
10use serde::Serialize;
11use std::path::{Path, PathBuf};
12
13/// Three-state classification of an agent's runtime state.
14#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq)]
15#[serde(rename_all = "snake_case")]
16pub enum AgentStatusKind {
17    /// Lock present and the recorded pid is alive.
18    Running,
19    /// Lock present but the pid is not alive (crash/kill — orphan lock).
20    Stale,
21    /// No lock file.
22    Stopped,
23}
24
25impl AgentStatusKind {
26    /// Stable visual marker for this status — the single source of truth for
27    /// the status→emoji mapping used by `mur agent list` and the agent card.
28    /// Exhaustive match: adding a variant is a compile error here by design.
29    pub fn emoji(&self) -> &'static str {
30        match self {
31            AgentStatusKind::Running => "🟢",
32            AgentStatusKind::Stale => "🟡",
33            AgentStatusKind::Stopped => "⚪",
34        }
35    }
36}
37
38/// Result of classifying an agent's lock state.
39#[derive(Debug, Clone, Copy)]
40pub struct AgentStatus {
41    pub kind: AgentStatusKind,
42    /// PID from the lock file. `None` when no lock or unparseable lock.
43    pub pid: Option<u32>,
44}
45
46/// Read and JSON-parse `<home>/running.lock`. Returns:
47/// - `Ok(None)` if the file does not exist (agent stopped).
48/// - `Ok(Some(_))` if the file exists and parses successfully.
49/// - `Err(_)` if the file exists but I/O fails or JSON is malformed.
50pub fn read(lock_path: &Path) -> std::io::Result<Option<LockFile>> {
51    let bytes = match std::fs::read(lock_path) {
52        Ok(b) => b,
53        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
54        Err(e) => return Err(e),
55    };
56    serde_json::from_slice(&bytes)
57        .map(Some)
58        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
59}
60
61/// Is the given pid currently a live process the calling user can signal?
62///
63/// On Unix uses `kill(pid, 0)` — signal 0 is a no-op probe that checks
64/// process existence and permission without delivering any signal.
65///
66/// On Windows uses `OpenProcess` with `PROCESS_QUERY_LIMITED_INFORMATION`,
67/// then `GetExitCodeProcess` — an openable handle is NOT proof of life.
68///
69/// On other platforms returns `true` (optimistically treat any present lock
70/// as live, since P0a agents are not supported there).
71#[cfg(unix)]
72pub fn pid_alive(pid: u32) -> bool {
73    // SAFETY: kill(2) with signal 0 delivers no signal; it only checks
74    // process existence and our permission to signal it. Always safe to call.
75    unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
76}
77
78#[cfg(windows)]
79pub fn pid_alive(pid: u32) -> bool {
80    use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
81    use windows_sys::Win32::System::Threading::{
82        GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
83    };
84    // SAFETY: OpenProcess/GetExitCodeProcess/CloseHandle are safe to call with
85    // any pid; the handle is closed on every path out.
86    unsafe {
87        let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
88        if h.is_null() {
89            return false;
90        }
91        // A terminated process stays openable until the last handle to it is
92        // closed — Windows' equivalent of a zombie. Treating a non-null handle
93        // as "alive" therefore reports a just-crashed agent as running, and
94        // `clear_runtime_state` then refuses to clear its stale lock. Ask for
95        // the exit code instead: only STILL_ACTIVE means running. (Known
96        // Windows caveat: a process that exits with code 259 is
97        // indistinguishable from a running one. Our runtimes never exit 259,
98        // and the failure direction is the conservative one — a lock kept, not
99        // a live process's lock deleted.)
100        let mut code: u32 = 0;
101        let queried = GetExitCodeProcess(h, &mut code);
102        CloseHandle(h);
103        // If the query itself fails we cannot tell, so claim alive: keeping a
104        // dead process's lock costs the user one manual clear, while deleting
105        // a live one's lock lets a second supervisor run against the same agent
106        // home (#790).
107        queried == 0 || code == STILL_ACTIVE as u32
108    }
109}
110
111#[cfg(not(any(unix, windows)))]
112pub fn pid_alive(_pid: u32) -> bool {
113    true
114}
115
116/// Classify the agent's running state by inspecting `<home>/running.lock`.
117///
118/// - No lock → `Stopped`
119/// - Lock present, parses, pid alive → `Running`
120/// - Lock present but pid not alive (crash / SIGKILL / OOM) → `Stale`
121/// - Lock present but unparseable / unreadable → `Stale` with `pid: None`
122///   (treat as stale rather than running so dashboards don't paint dead
123///   agents green)
124pub fn classify(lock_path: &Path) -> AgentStatus {
125    match read(lock_path) {
126        Ok(None) => AgentStatus {
127            kind: AgentStatusKind::Stopped,
128            pid: None,
129        },
130        Err(_) => AgentStatus {
131            kind: AgentStatusKind::Stale,
132            pid: None,
133        },
134        Ok(Some(lock)) => {
135            let kind = if pid_alive(lock.pid) {
136                AgentStatusKind::Running
137            } else {
138                AgentStatusKind::Stale
139            };
140            AgentStatus {
141                kind,
142                pid: Some(lock.pid),
143            }
144        }
145    }
146}
147
148/// The runtime's startup exclusion file in an agent's directory. A booting
149/// runtime holds its flock for the whole seal, before `running.lock` exists.
150pub const SENTINEL_FILE: &str = "running.sentinel";
151
152/// The flock sentinel beside a runtime lock file (`running.lock` →
153/// `running.sentinel`).
154///
155/// A separate file on purpose: `running.lock` is written by temp-file +
156/// rename, which swaps its inode. A flock on the JSON file itself would be
157/// left on an inode nobody can see; the sentinel is never renamed, so its
158/// inode is the one every holder and every probe meets on.
159pub fn sentinel_path(lock: &Path) -> PathBuf {
160    lock.with_extension("sentinel")
161}
162
163/// What [`probe_sentinel`] found on an agent's `running.sentinel`.
164#[derive(Debug)]
165pub enum SentinelProbe {
166    /// The agent directory does not exist, so there is nothing to clear.
167    NoAgentDir,
168    /// A live process owns it — or the probe could not tell, which counts
169    /// the same: keeping a dead runtime's files costs one manual clear,
170    /// deleting a live one's state is #790.
171    Owned,
172    /// The caller now holds its flock and it names no live pid. The handle
173    /// keeps the flock until dropped; the dead pid it recorded is erased.
174    Free(std::fs::File),
175}
176
177/// Take the `running.sentinel` flock if nobody owns it, creating the file
178/// when it is missing (the same open the runtime does, so both always meet
179/// on one inode).
180///
181/// The pid the runtime writes into the sentinel is a fallback for a
182/// filesystem where the flock probe cannot see a holder. It is erased once
183/// the sentinel is judged free, so a later process reusing that pid cannot
184/// make a long-dead runtime look alive forever.
185///
186/// The sentinel itself is never unlinked, by anyone: its existence means
187/// nothing, only the flock does, and every unlink is a chance for a holder
188/// to end up locking an inode the next opener cannot see. Hold a `Free`
189/// handle across any clear of the agent's other files, so a runtime racing
190/// the clear fails its own `try_lock_exclusive` and exits as a duplicate —
191/// and drop it before launching a runtime, for the same reason.
192pub fn probe_sentinel(agent_dir: &Path) -> SentinelProbe {
193    use fs2::FileExt;
194    use std::io::Read;
195
196    let mut file = match std::fs::OpenOptions::new()
197        .create(true)
198        .read(true)
199        .write(true)
200        .truncate(false)
201        .open(agent_dir.join(SENTINEL_FILE))
202    {
203        Ok(f) => f,
204        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return SentinelProbe::NoAgentDir,
205        Err(_) => return SentinelProbe::Owned,
206    };
207    if file.try_lock_exclusive().is_err() {
208        return SentinelProbe::Owned;
209    }
210    let mut pid = String::new();
211    if file.read_to_string(&mut pid).is_err() {
212        return SentinelProbe::Owned;
213    }
214    if pid.trim().parse::<u32>().is_ok_and(pid_alive) {
215        return SentinelProbe::Owned;
216    }
217    let _ = file.set_len(0);
218    SentinelProbe::Free(file)
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use crate::agent::LockTransports;
225
226    #[test]
227    fn status_emoji_mapping_is_stable() {
228        assert_eq!(AgentStatusKind::Running.emoji(), "🟢");
229        assert_eq!(AgentStatusKind::Stale.emoji(), "🟡");
230        assert_eq!(AgentStatusKind::Stopped.emoji(), "⚪");
231    }
232
233    fn make_lock(pid: u32) -> LockFile {
234        LockFile {
235            schema: 1,
236            uuid: "01JQX4TM8Y9K7VQH6B2N3R5DPE".into(),
237            name: "agent_a".into(),
238            pid,
239            ppid: 1,
240            started_at: "2026-04-22T08:00:00Z".into(),
241            binary_version: "mur-agent-runtime 0.1.0".into(),
242            transports: LockTransports {
243                stdio: false,
244                unix_socket: Some("/tmp/x.sock".into()),
245                tcp: None,
246                webhook: None,
247            },
248            card_digest: "sha256:abc".into(),
249            capabilities: vec!["a2a.message.send".into()],
250            build_sha: String::new(),
251            proto_version: 0,
252            sandbox: None,
253            startup_override: None,
254            override_rejected: None,
255        }
256    }
257
258    fn write_lock_file(dir: &std::path::Path, pid: u32) -> std::path::PathBuf {
259        let path = dir.join("running.lock");
260        let lock = make_lock(pid);
261        std::fs::write(&path, serde_json::to_vec_pretty(&lock).unwrap()).unwrap();
262        path
263    }
264
265    #[test]
266    fn classify_returns_stopped_when_no_lock() {
267        let tmp = tempfile::tempdir().unwrap();
268        let lock_path = tmp.path().join("running.lock");
269        let status = classify(&lock_path);
270        assert_eq!(status.kind, AgentStatusKind::Stopped);
271        assert_eq!(status.pid, None);
272    }
273
274    #[cfg(unix)]
275    #[test]
276    fn classify_returns_running_when_pid_alive() {
277        let tmp = tempfile::tempdir().unwrap();
278        let lock_path = write_lock_file(tmp.path(), std::process::id());
279        let status = classify(&lock_path);
280        assert_eq!(status.kind, AgentStatusKind::Running);
281        assert_eq!(status.pid, Some(std::process::id()));
282    }
283
284    #[cfg(unix)]
285    #[test]
286    fn classify_returns_stale_when_pid_dead() {
287        let tmp = tempfile::tempdir().unwrap();
288        let dead_pid: u32 = 999_999;
289        let lock_path = write_lock_file(tmp.path(), dead_pid);
290        let status = classify(&lock_path);
291        assert_eq!(status.kind, AgentStatusKind::Stale);
292        assert_eq!(status.pid, Some(dead_pid));
293    }
294
295    #[test]
296    fn classify_returns_stale_when_lock_malformed() {
297        let tmp = tempfile::tempdir().unwrap();
298        let lock_path = tmp.path().join("running.lock");
299        std::fs::write(&lock_path, b"not json").unwrap();
300        let status = classify(&lock_path);
301        assert_eq!(status.kind, AgentStatusKind::Stale);
302        assert_eq!(status.pid, None);
303    }
304
305    #[test]
306    fn read_returns_none_for_missing_file() {
307        let tmp = tempfile::tempdir().unwrap();
308        let lock_path = tmp.path().join("running.lock");
309        let result = read(&lock_path).unwrap();
310        assert!(result.is_none());
311    }
312
313    #[test]
314    fn read_returns_ok_for_valid_lock() {
315        let tmp = tempfile::tempdir().unwrap();
316        let lock_path = write_lock_file(tmp.path(), 42);
317        let result = read(&lock_path).unwrap();
318        assert!(result.is_some());
319        assert_eq!(result.unwrap().pid, 42);
320    }
321
322    #[test]
323    fn read_returns_err_for_malformed_json() {
324        let tmp = tempfile::tempdir().unwrap();
325        let lock_path = tmp.path().join("running.lock");
326        std::fs::write(&lock_path, b"not json").unwrap();
327        let result = read(&lock_path);
328        assert!(result.is_err());
329    }
330
331    #[cfg(unix)]
332    #[test]
333    fn pid_alive_returns_true_for_self() {
334        assert!(pid_alive(std::process::id()));
335    }
336
337    #[cfg(unix)]
338    #[test]
339    fn pid_alive_returns_false_for_dead_pid() {
340        assert!(!pid_alive(999_999));
341    }
342
343    #[test]
344    fn sentinel_path_sits_beside_the_lock() {
345        let dir = Path::new("/x/agents/a");
346        assert_eq!(
347            sentinel_path(&dir.join("running.lock")),
348            dir.join(SENTINEL_FILE)
349        );
350    }
351
352    /// Every verdict the probe can reach. Each `Free` handle is dropped
353    /// before the next directory is looked at.
354    #[test]
355    fn probe_sentinel_verdicts() {
356        use fs2::FileExt;
357
358        #[derive(Debug, PartialEq)]
359        enum V {
360            NoDir,
361            Owned,
362            Free,
363        }
364        let verdict = |dir: &Path| match probe_sentinel(dir) {
365            SentinelProbe::NoAgentDir => V::NoDir,
366            SentinelProbe::Owned => V::Owned,
367            SentinelProbe::Free(_) => V::Free,
368        };
369
370        let tmp = tempfile::tempdir().unwrap();
371        let missing = tmp.path().join("missing");
372        let fresh = tmp.path().join("fresh");
373        let dead = tmp.path().join("dead");
374        let live = tmp.path().join("live");
375        let held = tmp.path().join("held");
376        for d in [&fresh, &dead, &live, &held] {
377            std::fs::create_dir_all(d).unwrap();
378        }
379        std::fs::write(dead.join(SENTINEL_FILE), b"999999").unwrap();
380        std::fs::write(live.join(SENTINEL_FILE), std::process::id().to_string()).unwrap();
381        std::fs::write(held.join(SENTINEL_FILE), b"").unwrap();
382        let flock = std::fs::File::open(held.join(SENTINEL_FILE)).unwrap();
383        flock.try_lock_exclusive().unwrap();
384
385        for (dir, want) in [
386            (&missing, V::NoDir),
387            (&fresh, V::Free),
388            (&dead, V::Free),
389            (&live, V::Owned),
390            (&held, V::Owned),
391        ] {
392            assert_eq!(verdict(dir), want, "{}", dir.display());
393        }
394        assert!(!missing.exists(), "a probe must not create the agent dir");
395        assert_eq!(
396            std::fs::read_to_string(dead.join(SENTINEL_FILE)).unwrap(),
397            "",
398            "a free sentinel's dead pid is erased"
399        );
400        drop(flock);
401    }
402}