Skip to main content

agentmux_srv_core/backend/slug_migration/
running.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Whether an agent runs anywhere on this host, from what every instance
5//! leaves on disk: its lease (a pane holds one for its process's life, a
6//! turn for the turn), its registrations in the cross-channel registry, and
7//! each version's own registrations. Read from the files, never by asking an
8//! instance, so a channel that doesn't answer is still seen.
9
10use std::path::Path;
11
12use rusqlite::Connection;
13use serde_json::Value;
14
15use super::home::{fold, open_ro, place, Home, Install};
16use super::plan::Def;
17use crate::backend::reactive::registry::{pid_alive, AgentEntry};
18use crate::backend::rpc_types::ForkSlugRunning;
19use agentmux_common::slug::{agent_route_name, file_stem};
20
21/// A registration whose srv is alive, from `<dir>/<name>.json`.
22pub(super) fn registration(dir: &Path, name: &str) -> Option<AgentEntry> {
23    let entry: AgentEntry = serde_json::from_slice(&std::fs::read(dir.join(format!("{}.json", file_stem(name)))).ok()?).ok()?;
24    entry.srv_alive().then_some(entry)
25}
26
27/// The live entries filed under `name` in the cross-channel registry.
28pub(super) fn shared_entries(home: &Home, name: &str) -> Vec<AgentEntry> {
29    let dir = home.reactive().join(file_stem(name));
30    let Ok(files) = std::fs::read_dir(dir) else { return Vec::new() };
31    files
32        .flatten()
33        .filter(|f| f.path().extension().and_then(|e| e.to_str()) == Some("json"))
34        .filter_map(|f| serde_json::from_slice::<AgentEntry>(&std::fs::read(f.path()).ok()?).ok())
35        .filter(AgentEntry::srv_alive)
36        .collect()
37}
38
39/// The agent uid a block belongs to (`agentId`, else the legacy
40/// `agent:id`), from that version's own `objects.db`.
41pub(super) fn block_agent(conn: &Connection, block_id: &str) -> Option<String> {
42    if block_id.is_empty() {
43        return None;
44    }
45    let data: Vec<u8> = conn.query_row("SELECT data FROM db_block WHERE oid = ?1", [block_id], |r| r.get(0)).ok()?;
46    let block: Value = serde_json::from_slice(&data).ok()?;
47    let meta = block.get("meta")?;
48    ["agentId", "agent:id"].iter().find_map(|k| meta.get(*k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string))
49}
50
51/// The names an agent may be registered under: its slug, its former slugs
52/// and its display name's route name.
53fn names_of(def: &Def) -> Vec<String> {
54    let mut names = vec![fold(&def.slug), fold(&agent_route_name(&def.name))];
55    names.extend(def.former.iter().map(|f| fold(f)));
56    names.sort();
57    names.dedup();
58    names.retain(|n| !n.is_empty());
59    names
60}
61
62/// Where `def` runs now. A registration under one of its names counts unless
63/// it is provably another agent's pane; a lease counts while it is fresh and
64/// its holder isn't provably gone.
65pub(super) fn running(home: &Home, installs: &[Install], def: &Def) -> Result<Vec<ForkSlugRunning>, String> {
66    let mut out = Vec::new();
67    if let Some(lease) = live_lease(home, &def.uid) {
68        out.push(lease);
69    }
70    let names = names_of(def);
71    for name in &names {
72        for e in shared_entries(home, name) {
73            if e.uid.is_empty() || e.uid == def.uid {
74                out.push(ForkSlugRunning { block_id: e.block_id, channel: e.channel, how: format!("registered as {name}") });
75            }
76        }
77    }
78    for install in installs {
79        for version in &install.versions {
80            let mut conn: Option<Connection> = None;
81            for name in &names {
82                let Some(e) = registration(&version.registrations(), name) else { continue };
83                if conn.is_none() {
84                    conn = Some(open_ro(&version.objects_db())?);
85                }
86                let owner = conn.as_ref().and_then(|c| block_agent(c, &e.block_id));
87                if owner.is_none() || owner.as_deref() == Some(def.uid.as_str()) {
88                    out.push(ForkSlugRunning {
89                        block_id: e.block_id,
90                        channel: place(install, version),
91                        how: format!("registered as {name}"),
92                    });
93                }
94            }
95        }
96    }
97    let mut seen = std::collections::HashSet::new();
98    out.retain(|r| seen.insert((r.block_id.clone(), r.channel.clone(), r.how.clone())));
99    Ok(out)
100}
101
102/// The agent's lease, if live: renewed within its TTL, and its holder not
103/// provably gone (recorded on this host with a pid that is no longer
104/// running). An unreadable file that is still fresh counts, as the lease
105/// store itself fails closed.
106fn live_lease(home: &Home, uid: &str) -> Option<ForkSlugRunning> {
107    let path = home.leases().join(format!("{uid}.lease.json"));
108    let bytes = std::fs::read(&path).ok()?;
109    let ttl = crate::registry::LEASE_TTL_MS as i64;
110    let now = agentmux_common::time::now_ms();
111    let Ok(lease) = serde_json::from_slice::<Value>(&bytes) else {
112        let age = std::fs::metadata(&path).and_then(|m| m.modified()).ok()?.elapsed().ok()?.as_millis() as i64;
113        return (age <= ttl).then(|| ForkSlugRunning { block_id: String::new(), channel: String::new(), how: "an unreadable lease".into() });
114    };
115    let num = |k: &str| lease.get(k).and_then(Value::as_i64).unwrap_or(0);
116    let text = |k: &str| lease.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
117    if now - num("renewed_at_ms") > ttl {
118        return None;
119    }
120    let host = text("hostname");
121    let this_host = whoami::fallible::hostname().unwrap_or_default().trim().to_lowercase();
122    let pid = num("pid") as u32;
123    if !host.is_empty() && host == this_host && pid != 0 && !pid_alive(pid) {
124        return None;
125    }
126    Some(ForkSlugRunning { block_id: text("block_id"), channel: text("channel"), how: "holds its lease".into() })
127}