1use crate::LockFile;
10use serde::Serialize;
11use std::path::{Path, PathBuf};
12
13#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq)]
15#[serde(rename_all = "snake_case")]
16pub enum AgentStatusKind {
17 Running,
19 Stale,
21 Stopped,
23}
24
25impl AgentStatusKind {
26 pub fn emoji(&self) -> &'static str {
30 match self {
31 AgentStatusKind::Running => "🟢",
32 AgentStatusKind::Stale => "🟡",
33 AgentStatusKind::Stopped => "⚪",
34 }
35 }
36}
37
38#[derive(Debug, Clone, Copy)]
40pub struct AgentStatus {
41 pub kind: AgentStatusKind,
42 pub pid: Option<u32>,
44}
45
46pub 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#[cfg(unix)]
72pub fn pid_alive(pid: u32) -> bool {
73 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 unsafe {
87 let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
88 if h.is_null() {
89 return false;
90 }
91 let mut code: u32 = 0;
101 let queried = GetExitCodeProcess(h, &mut code);
102 CloseHandle(h);
103 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
116pub 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
148pub const SENTINEL_FILE: &str = "running.sentinel";
151
152pub fn sentinel_path(lock: &Path) -> PathBuf {
160 lock.with_extension("sentinel")
161}
162
163#[derive(Debug)]
165pub enum SentinelProbe {
166 NoAgentDir,
168 Owned,
172 Free(std::fs::File),
175}
176
177pub 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 #[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}