Skip to main content

agentmux_srv_core/backend/
instance_registry.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The AgentMux instances running on this machine, one record each, so a tool in one instance can
5//! name another (`muxspect instances`, `muxspect --channel <name> ...`;
6//! `docs/specs/SPEC_MUXSPECT_CROSS_TIER_INSTANCE_INSPECTION_2026_09_02.md` ยง2, Phase 2a).
7//!
8//! One `<channel>-<hash>.json` per running srv under `registry::resolve_shared_instances_dir()`,
9//! written when srv starts, rewritten every [`HEARTBEAT_INTERVAL`] and removed when it exits. The
10//! agent registry cannot answer this: it has one file per agent, so a channel with no agent
11//! registered has no file at all. A record carries the instance's `auth_key` (the way the agent
12//! registry's entries do) so a request can be forwarded to it; the file is readable by its owner
13//! only, and `muxspect instances` never prints the key.
14//!
15//! A record is listed only while its srv is alive: a fresh `updated_at` AND a process that started
16//! no later than that write (`reactive::registry::pid_alive_since`, so a recycled pid does not keep
17//! a dead instance listed). A record whose process is gone is removed by whoever reads it.
18
19use std::path::{Path, PathBuf};
20use std::time::Duration;
21
22use serde::{Deserialize, Serialize};
23
24/// How often a running instance rewrites its record.
25pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(20);
26/// A record not rewritten for this long (three missed beats) is not listed.
27pub const STALE_AFTER_MS: u64 = 60_000;
28/// Records looked at per read: a directory full of junk must not stall a request.
29const MAX_FILES_SCANNED: usize = 64;
30/// A real record is a few hundred bytes.
31const MAX_FILE_BYTES: u64 = 8192;
32const MAX_FIELD_LEN: usize = 256;
33const MAX_CHANNEL_LEN: usize = 64;
34
35/// One instance's record, as stored on disk.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub struct InstanceRecord {
38    pub channel: String,
39    pub version: String,
40    pub pid: u32,
41    /// `http://127.0.0.1:<port>`: where a same-host caller reaches this instance.
42    pub local_url: String,
43    pub auth_key: String,
44    pub started_at: u64,
45    pub updated_at: u64,
46    pub agent_count: u32,
47}
48
49impl InstanceRecord {
50    /// The record without its key: what `muxspect instances` returns.
51    pub fn listing(&self, own_pid: u32, now_ms: u64) -> serde_json::Value {
52        serde_json::json!({
53            "channel": self.channel,
54            "version": self.version,
55            "pid": self.pid,
56            "local_url": self.local_url,
57            "started_at": self.started_at,
58            "updated_at": self.updated_at,
59            "uptime_ms": now_ms.saturating_sub(self.started_at),
60            "agent_count": self.agent_count,
61            "self": self.pid == own_pid,
62        })
63    }
64}
65
66/// The file a channel's record lives in: a readable stem (reduced to `[a-z0-9_-]` and capped, so it
67/// can never name a path outside the directory) and 8 hex chars of a SHA-256 of the exact channel
68/// name, because the stem alone is lossy (`Foo` and `foo bar` / `foo_bar` would share one file).
69pub fn record_file_name(channel: &str) -> String {
70    use sha2::{Digest, Sha256};
71    let stem: String = agentmux_common::slug::file_stem(channel).chars().take(MAX_CHANNEL_LEN).collect();
72    let stem = if stem.is_empty() { "_".to_string() } else { stem };
73    let digest = Sha256::digest(channel.as_bytes());
74    let tag: String = digest[..4].iter().map(|b| format!("{b:02x}")).collect();
75    format!("{stem}-{tag}.json")
76}
77
78/// Write `record` atomically (temp file in the same folder, then rename). The temp file is created
79/// owner-only on Unix; on Windows the folder inherits the user's own profile ACL.
80pub fn write_record(dir: &Path, record: &InstanceRecord) -> std::io::Result<()> {
81    use std::io::Write;
82    std::fs::create_dir_all(dir)?;
83    let json = serde_json::to_vec(record).map_err(std::io::Error::other)?;
84    let mut tmp = tempfile::Builder::new().prefix(".instance-").suffix(".tmp").tempfile_in(dir)?;
85    tmp.as_file_mut().write_all(&json)?;
86    tmp.persist(dir.join(record_file_name(&record.channel))).map_err(|e| e.error)?;
87    Ok(())
88}
89
90/// Remove `channel`'s record if it is the one process `pid` wrote. Another process on the same
91/// channel name owns its own record and keeps it.
92pub fn remove_own_record(dir: &Path, channel: &str, pid: u32) {
93    let path = dir.join(record_file_name(channel));
94    if read_record(&path).is_some_and(|r| r.pid == pid) {
95        let _ = std::fs::remove_file(&path);
96    }
97}
98
99/// Read one record, refusing an oversized file, out-of-bounds fields, or a `local_url` that is not
100/// this machine's loopback (a record is a file any local process can write; a request is never
101/// forwarded to an address it names unless it is loopback).
102fn read_record(path: &Path) -> Option<InstanceRecord> {
103    if std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES {
104        return None;
105    }
106    let record: InstanceRecord = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
107    let in_bounds = !record.channel.is_empty()
108        && record.channel.len() <= MAX_CHANNEL_LEN
109        && record.version.len() <= MAX_FIELD_LEN
110        && record.auth_key.len() <= MAX_FIELD_LEN
111        && is_loopback_url(&record.local_url);
112    in_bounds.then_some(record)
113}
114
115/// `http://127.0.0.1:<port>` and nothing else (no path, no userinfo, no other host).
116fn is_loopback_url(url: &str) -> bool {
117    url.strip_prefix("http://127.0.0.1:")
118        .is_some_and(|port| !port.is_empty() && port.len() <= 5 && port.bytes().all(|b| b.is_ascii_digit()))
119}
120
121/// The live instances in `dir`, sorted by channel. `pid_alive(pid, updated_at)` says whether the
122/// process that wrote a record at that time still runs. A record whose process is gone is deleted;
123/// one that is merely stale (a live process that stopped beating) is skipped and left.
124pub fn read_live(dir: &Path, now_ms: u64, pid_alive: impl Fn(u32, u64) -> bool) -> Vec<InstanceRecord> {
125    let Ok(entries) = std::fs::read_dir(dir) else {
126        return Vec::new();
127    };
128    let mut found: Vec<InstanceRecord> = Vec::new();
129    for path in entries
130        .flatten()
131        .map(|e| e.path())
132        .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("json"))
133        .take(MAX_FILES_SCANNED)
134    {
135        let Some(record) = read_record(&path) else {
136            continue;
137        };
138        if !pid_alive(record.pid, record.updated_at) {
139            let _ = std::fs::remove_file(&path);
140            continue;
141        }
142        // A timestamp far in the future is as untrustworthy as an old one.
143        if now_ms.abs_diff(record.updated_at) <= STALE_AFTER_MS {
144            found.push(record);
145        }
146    }
147    found.sort_by(|a, b| a.channel.to_lowercase().cmp(&b.channel.to_lowercase()).then_with(|| a.channel.cmp(&b.channel)));
148    found
149}
150
151/// [`read_live`] against the real process table.
152pub fn live_instances(dir: &Path) -> Vec<InstanceRecord> {
153    read_live(dir, agentmux_common::time::now_ms_u64(), super::reactive::registry::pid_alive_since)
154}
155
156/// What this srv knows about itself; the rest of its record is read fresh on each beat.
157#[derive(Clone)]
158pub struct Identity {
159    pub version: String,
160    pub local_url: String,
161    pub auth_key: String,
162    pub started_at: u64,
163}
164
165fn own_record(id: &Identity) -> InstanceRecord {
166    InstanceRecord {
167        channel: super::reactive::registry::local_channel_id(),
168        version: id.version.clone(),
169        pid: std::process::id(),
170        local_url: id.local_url.clone(),
171        auth_key: id.auth_key.clone(),
172        started_at: id.started_at,
173        updated_at: agentmux_common::time::now_ms_u64(),
174        agent_count: u32::try_from(crate::backend::reactive::get_global_handler().list_agents().len()).unwrap_or(u32::MAX),
175    }
176}
177
178/// Where records go: `None` when the shared root can't be resolved, and always `None` under
179/// `cargo test`, whose srv instances must not write into a developer's real folder. Tests that
180/// exercise the files pass a temp directory.
181fn instances_dir() -> Option<PathBuf> {
182    if cfg!(any(test, feature = "test-support")) {
183        return None;
184    }
185    crate::registry::resolve_shared_instances_dir()
186}
187
188/// Publish this instance's record now and again every [`HEARTBEAT_INTERVAL`] for as long as srv runs.
189pub fn spawn(id: Identity) {
190    let Some(dir) = instances_dir() else {
191        return;
192    };
193    tokio::spawn(async move {
194        let mut tick = tokio::time::interval(HEARTBEAT_INTERVAL);
195        loop {
196            tick.tick().await;
197            let (dir, id) = (dir.clone(), id.clone());
198            // The write is a few small file operations; keep them off the async workers.
199            let _ = tokio::task::spawn_blocking(move || {
200                if let Err(e) = write_record(&dir, &own_record(&id)) {
201                    tracing::debug!(error = %e, "instance record not written");
202                }
203            })
204            .await;
205        }
206    });
207}
208
209/// Remove this instance's record at a clean exit. A crash leaves it; the next reader removes it
210/// because its process is gone.
211pub fn withdraw() {
212    if let Some(dir) = instances_dir() {
213        remove_own_record(&dir, &super::reactive::registry::local_channel_id(), std::process::id());
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    const NOW: u64 = 1_000_000_000;
222
223    fn record(channel: &str, pid: u32, updated_at: u64) -> InstanceRecord {
224        InstanceRecord {
225            channel: channel.to_string(),
226            version: "0.60.27".to_string(),
227            pid,
228            local_url: "http://127.0.0.1:29700".to_string(),
229            auth_key: format!("key-{channel}"),
230            started_at: updated_at - 5_000,
231            updated_at,
232            agent_count: 2,
233        }
234    }
235
236    fn channels(dir: &Path, alive: impl Fn(u32, u64) -> bool) -> Vec<String> {
237        read_live(dir, NOW, alive).into_iter().map(|r| r.channel).collect()
238    }
239
240    #[test]
241    fn a_written_record_reads_back_and_leaves_no_temp_file() {
242        let dir = tempfile::tempdir().unwrap();
243        let r = record("stable", 42, NOW);
244        write_record(dir.path(), &r).unwrap();
245        assert_eq!(read_live(dir.path(), NOW, |_, _| true), vec![r]);
246        let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap().flatten().map(|e| e.file_name()).collect();
247        assert_eq!(names, vec![std::ffi::OsString::from(record_file_name("stable"))]);
248    }
249
250    #[test]
251    fn instances_are_listed_by_channel_and_a_rewrite_replaces_the_record() {
252        let dir = tempfile::tempdir().unwrap();
253        write_record(dir.path(), &record("zeta", 1, NOW)).unwrap();
254        write_record(dir.path(), &record("alpha", 2, NOW)).unwrap();
255        write_record(dir.path(), &record("alpha", 2, NOW + 1)).unwrap();
256        assert_eq!(channels(dir.path(), |_, _| true), vec!["alpha", "zeta"]);
257        assert_eq!(read_live(dir.path(), NOW, |_, _| true)[0].updated_at, NOW + 1);
258    }
259
260    #[test]
261    fn a_record_whose_process_is_gone_is_evicted() {
262        let dir = tempfile::tempdir().unwrap();
263        write_record(dir.path(), &record("live", 1, NOW)).unwrap();
264        write_record(dir.path(), &record("dead", 2, NOW)).unwrap();
265        assert_eq!(channels(dir.path(), |pid, _| pid == 1), vec!["live"]);
266        assert!(!dir.path().join(record_file_name("dead")).exists(), "the dead record's file is deleted");
267        assert!(dir.path().join(record_file_name("live")).exists());
268    }
269
270    #[test]
271    fn a_live_process_that_stopped_beating_is_skipped_but_kept() {
272        let dir = tempfile::tempdir().unwrap();
273        write_record(dir.path(), &record("hung", 1, NOW - STALE_AFTER_MS - 1)).unwrap();
274        write_record(dir.path(), &record("future", 2, NOW + STALE_AFTER_MS + 1)).unwrap();
275        write_record(dir.path(), &record("edge", 3, NOW - STALE_AFTER_MS)).unwrap();
276        assert_eq!(channels(dir.path(), |_, _| true), vec!["edge"]);
277        assert!(dir.path().join(record_file_name("hung")).exists());
278    }
279
280    #[test]
281    fn the_pid_check_gets_the_write_time_so_a_recycled_pid_is_not_alive() {
282        let dir = tempfile::tempdir().unwrap();
283        write_record(dir.path(), &record("stable", 7, NOW)).unwrap();
284        let seen = std::cell::Cell::new(None);
285        read_live(dir.path(), NOW, |pid, written| {
286            seen.set(Some((pid, written)));
287            true
288        });
289        assert_eq!(seen.get(), Some((7, NOW)));
290    }
291
292    #[test]
293    fn channels_that_slug_alike_keep_their_own_files() {
294        let (a, b) = (record_file_name("foo bar"), record_file_name("foo_bar"));
295        assert_ne!(a, b);
296        assert!(!record_file_name("../../etc").contains('/') && !record_file_name("../../etc").contains(".."));
297    }
298
299    #[test]
300    fn remove_own_record_leaves_another_process_record_alone() {
301        let dir = tempfile::tempdir().unwrap();
302        write_record(dir.path(), &record("stable", 5, NOW)).unwrap();
303        remove_own_record(dir.path(), "stable", 6);
304        assert!(dir.path().join(record_file_name("stable")).exists());
305        remove_own_record(dir.path(), "stable", 5);
306        assert!(!dir.path().join(record_file_name("stable")).exists());
307    }
308
309    #[test]
310    fn a_record_naming_a_non_loopback_address_or_a_huge_file_is_ignored() {
311        let dir = tempfile::tempdir().unwrap();
312        for (i, url) in ["http://203.0.113.9:80", "http://127.0.0.1:80@203.0.113.9:80", "http://127.0.0.1:", "https://127.0.0.1:80", "http://127.0.0.1:80/x"]
313            .iter()
314            .enumerate()
315        {
316            let mut r = record(&format!("bad{i}"), 1, NOW);
317            r.local_url = (*url).to_string();
318            write_record(dir.path(), &r).unwrap();
319        }
320        std::fs::write(dir.path().join("big.json"), vec![b' '; (MAX_FILE_BYTES + 1) as usize]).unwrap();
321        std::fs::write(dir.path().join("junk.json"), b"not json").unwrap();
322        assert!(channels(dir.path(), |_, _| true).is_empty());
323    }
324
325    #[test]
326    fn the_listing_never_carries_the_key_and_marks_the_caller() {
327        let r = record("stable", 42, NOW);
328        let listing = r.listing(42, NOW + 7_000);
329        assert!(listing.get("auth_key").is_none());
330        assert_eq!(listing["self"], true);
331        assert_eq!(listing["uptime_ms"], 12_000);
332        assert_eq!(r.listing(1, NOW)["self"], false);
333    }
334}