Skip to main content

agentmux_srv_core/backend/reactive/
registry.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! File-based cross-instance agent registry.
5//!
6//! Each AgentMux instance writes agent registrations to
7//! `{data_dir}/agents/{agent_id}.json`. When a local inject fails with
8//! "agent not found", the inject handler looks up this registry and
9//! HTTP-forwards the request to the owning instance.
10//!
11//! Lifecycle:
12//! - Register: write file (on HTTP register endpoint + shell auto-register)
13//! - Unregister: delete file (on HTTP unregister endpoint + process exit)
14//! - Cleanup: TTL-based removal of stale files at startup
15
16use serde::{Deserialize, Serialize};
17use std::path::{Path, PathBuf};
18use std::sync::OnceLock;
19
20use super::now_unix_millis;
21
22/// One entry per registered agent in the shared data dir.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct AgentEntry {
25    pub agent_id: String,
26    /// Local HTTP URL of the owning AgentMux instance (e.g. http://127.0.0.1:PORT).
27    pub local_url: String,
28    pub block_id: String,
29    /// OS PID of the owning agentmux-srv process.
30    pub pid: u32,
31    /// Unix milliseconds of last update.
32    pub updated_at: u64,
33    /// Per-launch auth key of the owning instance. Required by peers
34    /// performing cross-instance HTTP forward of `/agentmux/reactive/inject`
35    /// after the route moved under auth_middleware. Optional in the
36    /// struct (serde default) so older on-disk entries still deserialize;
37    /// a missing or empty value means a forward to this entry will be
38    /// rejected by the peer's auth layer (graceful — falls back to cloud
39    /// muxbus).
40    #[serde(default)]
41    pub auth_key: String,
42    /// The writing instance's channel id (`AGENTMUX_CHANNEL`, default
43    /// "stable"). Empty for entries in the per-channel registry (where a
44    /// channel tag is redundant — the whole file is already channel-
45    /// scoped by its directory); populated for entries in the host-global
46    /// shared registry (§ below), where multiple channels' entries for
47    /// the same agent name coexist and need distinguishing. MuxBus Tier 2b
48    /// same-host cross-channel delivery, issue #1916.
49    ///
50    /// (This previously cited a `SPEC_MUXBUS_CROSS_CHANNEL_DELIVERY` spec dated
51    /// 2026-07-02 that has never existed in any commit — `check-spec-citations`
52    /// flags it the moment this file is touched. Repointed at the issue rather
53    /// than at a plausible-looking neighbour, since the similarly-named
54    /// duplicate-delivery spec is a different document about duplicate
55    /// suppression, not this registry's shape. `registry/paths.rs` carries the
56    /// same dead pointer and is deliberately left alone here: it is unchanged
57    /// by this PR so the gate does not see it, and widening a security PR to
58    /// sweep unrelated files is its own risk. Worth a follow-up.)
59    #[serde(default)]
60    pub channel: String,
61    /// Process-wide unique nonce of the persistent-controller spawn this
62    /// entry was written for; 0 = not recorded (HTTP register handler,
63    /// PTY shell auto-register, pre-existing entries). Real nonces are
64    /// always ≥ 1, drawn from a single srv-wide counter — NOT the
65    /// controller-local spawn generation, which restarts for a
66    /// replacement controller and could collide across controller
67    /// instances (codex P1 on PR #2500). Lets an exit-handler's cleanup
68    /// compare-and-remove ([`remove_if_nonce`]) instead of deleting a
69    /// fallback respawn's fresh entry (issue #2363).
70    #[serde(default)]
71    pub registration_nonce: u64,
72    /// Base64 Ed25519 **public** key for this agent, for cross-channel jekt
73    /// signature verification —
74    /// `docs/specs/SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md` §D1.
75    ///
76    /// The public half only. That is what makes publishing it here safe, and
77    /// is the whole reason this tier uses the agent's asymmetric LAN keypair
78    /// rather than its symmetric host-tier HMAC key: a shared file containing
79    /// HMAC secrets would let every channel on the machine *mint* signatures
80    /// for every agent (spec §5).
81    ///
82    /// Empty for entries written before this shipped, and for an agent whose
83    /// LAN keypair has not been minted yet. **An empty value means "cannot
84    /// check," never "failed the check"** — the verifier must map it to
85    /// `None`, not `Some(false)`, or every pre-upgrade sender on a
86    /// mixed-version machine gets escalated (spec §6).
87    #[serde(default)]
88    pub jekt_public_key: String,
89    /// Identity M4d-5 (`SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md`
90    /// §6.5.10): the registered block's agent UID, and that UID's own public
91    /// key (M4d-2), published beside the name-keyed `jekt_public_key`, which
92    /// is unchanged so v1 verification is the same for every peer. M4d-6
93    /// verifies v2 signatures (`source_uid`) against it, by UID. Empty for an
94    /// entry written before this shipped or for a block with no agent row;
95    /// like `jekt_public_key`, empty means "cannot check".
96    #[serde(default, skip_serializing_if = "String::is_empty")]
97    pub uid: String,
98    #[serde(default, skip_serializing_if = "String::is_empty")]
99    pub uid_public_key: String,
100    /// What the writing instance can receive beyond plain jekts, e.g.
101    /// `files-v1` (`SPEC_JEKT_FILE_TRANSFER_2026_10_05.md` §3.4). Empty for
102    /// an entry an older build wrote: a sender attaches nothing for it.
103    #[serde(default, skip_serializing_if = "Vec::is_empty")]
104    pub jekt_features: Vec<String>,
105}
106
107/// Serializes this process's own read-compare-remove sequences
108/// ([`remove_if_nonce`] / [`remove_shared_if_nonce`]) against
109/// its own writes. Both the racing writer (a fallback respawn's
110/// re-registration) and the racing remover (the dying spawn's
111/// exit-handler) live in this same agentmux-srv process — each per-agent
112/// registry file has exactly one writing instance — so a process-local
113/// mutex is sufficient to make the compare-and-remove atomic; no file
114/// locking needed. Plain removes/writes for other controller types don't
115/// need the guard but take it anyway for uniformity (it's uncontended).
116static REGISTRY_OP_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
117
118/// Process-wide auth key for the local AgentMux instance.
119///
120/// Initialised once by `main.rs` after `Config::from_env_and_args` reads
121/// `AGENTMUX_AUTH_KEY` and removes it from the env. The registry write
122/// path reads this to populate `AgentEntry::auth_key`, which lets peers
123/// authenticate cross-instance inject forwards.
124///
125/// Tests and the `register` HTTP handler (which has `state.auth_key`)
126/// can both pre-set this safely — the first `set` wins.
127static LOCAL_AUTH_KEY: OnceLock<String> = OnceLock::new();
128
129/// Initialise the process's local auth key. Idempotent — first call wins.
130pub fn init_local_auth_key(key: impl Into<String>) {
131    let _ = LOCAL_AUTH_KEY.set(key.into());
132}
133
134fn local_auth_key() -> &'static str {
135    LOCAL_AUTH_KEY.get().map(String::as_str).unwrap_or("")
136}
137
138/// Resolves an agent's published Ed25519 public key for
139/// [`AgentEntry::jekt_public_key`].
140///
141/// Indirection rather than a `Store` handle because this module is
142/// deliberately pure filesystem — it is called from PTY auto-register,
143/// persistent-controller auto-register, and the HTTP register handler, none of
144/// which share a `Store` argument. Mirrors [`LOCAL_AUTH_KEY`]'s
145/// set-once-from-bootstrap pattern, except the value is per-agent so it has to
146/// be a lookup rather than a constant.
147type PubkeyResolver = Box<dyn Fn(&str) -> Option<String> + Send + Sync>;
148static JEKT_PUBLIC_KEY_RESOLVER: OnceLock<PubkeyResolver> = OnceLock::new();
149
150/// Resolves a registered block's agent UID and that UID's public key, for
151/// [`AgentEntry::uid`] / [`AgentEntry::uid_public_key`] (identity M4d-5). By
152/// block, because the block is what every registration path has. A load,
153/// never a mint, like [`jekt_public_key_for`]: M4d-2 mints the key at spawn.
154type UidKeyResolver = Box<dyn Fn(&str) -> Option<(String, String)> + Send + Sync>;
155static UID_KEY_RESOLVER: OnceLock<UidKeyResolver> = OnceLock::new();
156
157/// Install the process's block → (UID, UID public key) resolver. First call
158/// wins. Until it is called, entries are written without a UID.
159pub fn init_uid_key_resolver<F>(resolver: F)
160where
161    F: Fn(&str) -> Option<(String, String)> + Send + Sync + 'static,
162{
163    let _ = UID_KEY_RESOLVER.set(Box::new(resolver));
164}
165
166fn uid_key_for_block(block_id: &str) -> (String, String) {
167    UID_KEY_RESOLVER.get().and_then(|resolve| resolve(block_id)).unwrap_or_default()
168}
169
170/// Install the process's agent-public-key resolver. Idempotent — first call
171/// wins, same contract as [`init_local_auth_key`].
172///
173/// Called from bootstrap once the Store is open. Until it is called (and for
174/// any agent with no LAN keypair minted yet) entries are written with an empty
175/// `jekt_public_key`, which readers treat as "cannot check" — see that field's
176/// doc comment.
177pub fn init_jekt_public_key_resolver<F>(resolver: F)
178where
179    F: Fn(&str) -> Option<String> + Send + Sync + 'static,
180{
181    let _ = JEKT_PUBLIC_KEY_RESOLVER.set(Box::new(resolver));
182}
183
184/// The agent's published public key, or empty if unavailable.
185///
186/// Deliberately a *load*, never an ensure/mint: registry writes happen on
187/// every registration and re-registration, and minting key material as a side
188/// effect of a bookkeeping write would be a surprising place to put it. Key
189/// creation stays where it already is, at config-injection time
190/// (`agent_config::inject_jekt_signing_keys_into_mcp_json`).
191fn jekt_public_key_for(agent_id: &str) -> String {
192    JEKT_PUBLIC_KEY_RESOLVER
193        .get()
194        .and_then(|resolve| resolve(agent_id))
195        .unwrap_or_default()
196}
197
198fn agents_dir(data_dir: &Path) -> PathBuf {
199    data_dir.join("agents")
200}
201
202fn agent_path(data_dir: &Path, agent_id: &str) -> PathBuf {
203    // Lowercase first so this matches `ReactiveHandler`'s own
204    // `agent_id.to_lowercase()` key convention (backend/reactive/handler.rs)
205    // — every other muxbus identity path is already case-insensitive, and a
206    // channel registering "AgentX" vs. a peer injecting to "agentx" must
207    // land on the same file, not two different ones (reagent P1 on #2350,
208    // caught in Tier 2b but pre-existing here for Tier 2a too).
209    // Sanitize: only allow alphanumeric, dash, underscore to prevent path traversal.
210    let safe = agentmux_common::slug::file_stem(agent_id);
211    agents_dir(data_dir).join(format!("{}.json", safe))
212}
213
214/// Write (create or update) an agent entry in the shared registry.
215///
216/// The entry includes the writing instance's auth_key (from
217/// `LOCAL_AUTH_KEY`) so a peer performing an HTTP forward of a missed
218/// inject can authenticate. On Unix the file is created with mode 0600
219/// **at open time** (not write-then-chmod, which would briefly expose
220/// the file at the default umask — same security boundary as the
221/// existing `authkey.dev` file). On Windows, default ACLs inherit
222/// user-only on user-owned directories.
223pub fn write(data_dir: &Path, agent_id: &str, local_url: &str, block_id: &str) {
224    write_with_nonce(data_dir, agent_id, local_url, block_id, 0);
225}
226
227/// [`write`], recording the registering persistent-controller spawn's
228/// registration nonce — see `AgentEntry::registration_nonce` / issue #2363.
229pub fn write_with_nonce(
230    data_dir: &Path,
231    agent_id: &str,
232    local_url: &str,
233    block_id: &str,
234    registration_nonce: u64,
235) {
236    let _guard = REGISTRY_OP_LOCK.lock().unwrap();
237    let dir = agents_dir(data_dir);
238    let _ = std::fs::create_dir_all(&dir);
239    let entry = AgentEntry {
240        agent_id: agent_id.to_string(),
241        local_url: local_url.to_string(),
242        block_id: block_id.to_string(),
243        pid: std::process::id(),
244        updated_at: now_unix_millis(),
245        auth_key: local_auth_key().to_string(),
246        // Empty for entries in the per-channel registry — see the field's
247        // doc comment on `AgentEntry`.
248        channel: String::new(),
249        registration_nonce,
250        // Deliberately EMPTY in the per-channel registry. Only the shared
251        // registry's copy is load-bearing — a same-instance sender is verified
252        // by the host-tier HMAC path, which never consults this file — so
253        // resolving it here would mean a synchronous SQLite lookup, held under
254        // `REGISTRY_OP_LOCK`, on every local agent registration and
255        // re-registration, for a value nothing reads (reagent P2 on PR #2959).
256        jekt_public_key: String::new(),
257        uid: String::new(),
258        uid_public_key: String::new(),
259        jekt_features: vec![agentmux_common::jekt_files::FEATURE.to_string()],
260    };
261    let path = agent_path(data_dir, agent_id);
262    let Ok(json) = serde_json::to_string(&entry) else { return };
263
264    let mut opts = std::fs::OpenOptions::new();
265    opts.write(true).create(true).truncate(true);
266    #[cfg(unix)]
267    {
268        use std::os::unix::fs::OpenOptionsExt;
269        opts.mode(0o600);
270    }
271    if let Ok(mut f) = opts.open(&path) {
272        use std::io::Write;
273        let _ = f.write_all(json.as_bytes());
274    }
275}
276
277/// Remove an agent entry from the shared registry.
278pub fn remove(data_dir: &Path, agent_id: &str) {
279    let _guard = REGISTRY_OP_LOCK.lock().unwrap();
280    let _ = std::fs::remove_file(agent_path(data_dir, agent_id));
281}
282
283/// Remove an agent entry **only if** it was written by the spawn with
284/// `expected_nonce` — compare-and-remove for persistent-controller
285/// exit-handlers (issue #2363; nonce is process-wide unique, so the
286/// guard holds across controller replacement too — codex P1 on PR
287/// #2500). An entry with no recorded nonce
288/// (0) is never removed by this variant: leaving a stale file to the
289/// TTL sweep ([`cleanup_stale`]) is strictly safer than deleting a live
290/// registration. Atomic w.r.t. this process's own writes via
291/// [`REGISTRY_OP_LOCK`].
292pub fn remove_if_nonce(data_dir: &Path, agent_id: &str, expected_nonce: u64) {
293    let _guard = REGISTRY_OP_LOCK.lock().unwrap();
294    let matches = lookup(data_dir, agent_id)
295        .is_some_and(|e| expected_nonce != 0 && e.registration_nonce == expected_nonce);
296    if !matches {
297        tracing::info!(
298            agent_id = %agent_id,
299            expected_nonce = expected_nonce,
300            "registry: entry changed hands since this spawn registered — skipping remove"
301        );
302        return;
303    }
304    let _ = std::fs::remove_file(agent_path(data_dir, agent_id));
305}
306
307/// Look up an agent entry. Returns None if not found or file is malformed.
308pub fn lookup(data_dir: &Path, agent_id: &str) -> Option<AgentEntry> {
309    let content = std::fs::read_to_string(agent_path(data_dir, agent_id)).ok()?;
310    serde_json::from_str(&content).ok()
311}
312
313/// Remove stale entries at startup.
314///
315/// An entry is considered stale if `updated_at` is older than `max_age_ms`.
316/// The default is 4 hours — well beyond any reasonable agent session.
317/// Entries are also removed if their JSON is malformed, or if the srv that
318/// wrote them is gone (its pid dead, or reused by another program).
319pub fn cleanup_stale(data_dir: &Path, max_age_ms: u64) {
320    let dir = agents_dir(data_dir);
321    let Ok(entries) = std::fs::read_dir(&dir) else { return };
322    let cutoff = now_unix_millis().saturating_sub(max_age_ms);
323    for entry in entries.flatten() {
324        let path = entry.path();
325        if path.extension().and_then(|e| e.to_str()) != Some("json") {
326            continue;
327        }
328        let Ok(content) = std::fs::read_to_string(&path) else {
329            let _ = std::fs::remove_file(&path);
330            continue;
331        };
332        match serde_json::from_str::<AgentEntry>(&content) {
333            // Fresh, and the srv that wrote it is still running: a pid reused by another program
334            // would otherwise keep a stopped agent's entry alive.
335            Ok(agent) if agent.updated_at >= cutoff && agent.srv_alive() => {}
336            _ => {
337                let _ = std::fs::remove_file(&path);
338            }
339        }
340    }
341}
342
343// ---------------------------------------------------------------------
344// Host-global shared registry (MuxBus Tier 2b — same-host, cross-channel
345// delivery). Sibling API to the per-channel functions above, rooted at a
346// DIFFERENT directory (`registry::resolve_shared_reactive_dir()`, passed
347// in by the caller rather than resolved here to keep this module free of
348// a dependency on the `registry` crate module).
349//
350// Layout: `<shared_dir>/<agent_name>/<channel>.json` (`shared_dir` here is
351// already `resolve_shared_reactive_dir()`'s output, i.e.
352// `~/.agentmux/shared/agents/reactive/`, so the full real path is
353// `~/.agentmux/shared/agents/reactive/<agent_name>/<channel>.json`), one
354// file per (agent, channel) pair — NOT a single JSON array shared across
355// channels.
356// Each channel only ever reads/writes its OWN file, so two channels
357// registering the same agent name concurrently never contend on the same
358// file: no read-modify-write race is possible by construction, and no
359// locking is needed (reagent P1 on PR #2350 — the earlier one-array-per-
360// name design let a concurrent register/unregister from a different
361// channel silently clobber this channel's entry, since two writers could
362// each read the pre-write array before either wrote back, with no
363// periodic repair since a channel only ever writes once at agent spawn).
364// §4.2 of the cross-channel delivery spec.
365// ---------------------------------------------------------------------
366
367/// Lowercase + sanitize a single path component (agent name or channel
368/// id) to alphanumeric/dash/underscore only, preventing path traversal
369/// and matching `ReactiveHandler`'s lowercase key convention.
370fn sanitize_path_component(raw: &str) -> String {
371    agentmux_common::slug::file_stem(raw)
372}
373
374/// Directory holding one file per channel currently registering
375/// `agent_id` in the host-global shared registry.
376///
377/// Deliberately does NOT go through `agents_dir()` (which appends an
378/// `agents` segment for the per-channel registry, where the caller passes
379/// a bare data dir) — `shared_dir` here is already
380/// `registry::resolve_shared_reactive_dir()`'s output
381/// (`.../shared/agents/reactive`), so entries land at
382/// `.../shared/agents/reactive/<agent>/<channel>.json` as documented,
383/// not double-nested under an extra `agents/` (reagent P2 on #2350 —
384/// harmless since read/write agreed internally, but contradicted the
385/// documented layout).
386fn shared_agent_dir(shared_dir: &Path, agent_id: &str) -> PathBuf {
387    shared_dir.join(sanitize_path_component(agent_id))
388}
389
390/// Path to one (agent, channel) pair's entry file.
391fn shared_channel_path(shared_dir: &Path, agent_id: &str, channel: &str) -> PathBuf {
392    shared_agent_dir(shared_dir, agent_id).join(format!("{}.json", sanitize_path_component(channel)))
393}
394
395/// True if a process with this PID is currently running on this host.
396/// Meaningful here specifically because the shared registry is always
397/// same-host by construction (a local file only readable by local
398/// processes) — unlike a LAN/cloud registry, PID-liveness is an
399/// authoritative staleness signal, not just a heuristic.
400pub fn pid_alive(pid: u32) -> bool {
401    let target = sysinfo::Pid::from(pid as usize);
402    let mut sys = sysinfo::System::new();
403    // Targeted refresh, no CPU/memory/exe/cmdline needed — existence alone
404    // is what matters. `true` = drop entries for since-exited PIDs, same
405    // as the whole-machine attribution pass in backend/sysinfo.rs.
406    sys.refresh_processes_specifics(
407        sysinfo::ProcessesToUpdate::Some(&[target]),
408        true,
409        sysinfo::ProcessRefreshKind::nothing(),
410    );
411    sys.process(target).is_some()
412}
413
414/// Whether the srv that wrote an entry at `written_ms` is still running. A live pid alone proves
415/// nothing: once the srv exits, any program can be given its pid, and a record left behind then
416/// reads as "running". The process must also have started no later than the entry was last
417/// written (the same rule `process_identity::srv_alive` applies to claims).
418pub(crate) fn pid_alive_since(pid: u32, written_ms: u64) -> bool {
419    let target = sysinfo::Pid::from(pid as usize);
420    let mut sys = sysinfo::System::new();
421    sys.refresh_processes_specifics(
422        sysinfo::ProcessesToUpdate::Some(&[target]),
423        true,
424        sysinfo::ProcessRefreshKind::nothing(),
425    );
426    sys.process(target).is_some_and(|p| started_no_later_than(p.start_time(), written_ms))
427}
428
429/// A process that started at `started_secs` can be the one that wrote at `written_ms`: it began no
430/// later than the write, give or take the two clocks' rounding.
431pub(crate) fn started_no_later_than(started_secs: u64, written_ms: u64) -> bool {
432    started_secs <= written_ms / 1000 + crate::backend::process_identity::START_SLACK_SECS
433}
434
435impl AgentEntry {
436    /// Whether the srv that wrote this entry is still running (see [`pid_alive_since`]).
437    pub fn srv_alive(&self) -> bool {
438        pid_alive_since(self.pid, self.updated_at)
439    }
440}
441
442/// Grace period during which a forward failure against a live-process entry
443/// is presumed transient rather than proof the specific agent is gone — see
444/// [`should_evict_on_forward_failure`]. `pub(crate)` so `muxspect_handlers`'s
445/// `verify-sender` route can reuse the same real, already-tested staleness
446/// judgment for shared-registry entries instead of inventing its own
447/// threshold (see that module's own doc comment for why).
448pub const FORWARD_FAILURE_GRACE_MS: u64 = 60_000;
449
450/// Should `server/reactive.rs`'s evict-on-forward-failure sites remove this
451/// entry after a failed forward (`success:false` or a connection error)?
452///
453/// `entry.pid` identifies the OWNING SRV PROCESS (`AgentEntry::pid`'s own
454/// doc comment: "OS PID of the owning agentmux-srv process"), not the
455/// individual agent — every agent registered under the same channel/srv
456/// shares one `pid` value. A first version of this function (PR #2640,
457/// reagent P1 round 2) checked ONLY `pid_alive(entry.pid)`: alive process ⇒
458/// never evict. That over-corrects — it can only ever prove "the whole
459/// process died," never "this ONE agent's controller died while its srv
460/// process kept running for other agents," which is at least as common a
461/// failure mode as a whole-process death on a host running multiple agents
462/// under one shared srv (the default topology — see the retro). Under that
463/// version, a genuinely-dead individual agent's entry would linger in the
464/// shared registry forever as long as ANY other agent kept that same srv
465/// process alive, with no self-healing path short of a full srv restart —
466/// strictly worse than the pre-PR-2640 behavior (unconditional eviction) for
467/// that case.
468///
469/// Evict when EITHER signal indicates death:
470/// - the owning process is confirmed dead (definitive), OR
471/// - the entry is older than [`FORWARD_FAILURE_GRACE_MS`] — a fresh entry
472///   gets one grace window to account for the specific race PR #2640 fixes
473///   (the registering agent's controller hasn't finished its own
474///   registration yet, even though its srv process and this file both
475///   already exist); anything older that still fails a forward is presumed
476///   genuinely gone, matching pre-PR-2640 behavior for everything but a
477///   just-registered entry.
478///
479/// See docs/retro/retro-cross-channel-jekt-eviction-2026-08-17.md.
480pub fn should_evict_on_forward_failure(entry: &AgentEntry) -> bool {
481    if !pid_alive(entry.pid) {
482        return true;
483    }
484    let age_ms = now_unix_millis().saturating_sub(entry.updated_at);
485    age_ms > FORWARD_FAILURE_GRACE_MS
486}
487
488/// Write (create or update) this channel's entry for `agent_id` in the
489/// host-global shared registry. Writes only this channel's own file
490/// (`shared_channel_path`) — never touches another channel's file, so
491/// concurrent writers for different channels of the same agent name
492/// cannot race or clobber each other.
493pub fn write_shared(shared_dir: &Path, agent_id: &str, local_url: &str, block_id: &str, channel: &str) {
494    write_shared_with_nonce(shared_dir, agent_id, local_url, block_id, channel, 0);
495}
496
497/// [`write_shared`], recording the registering persistent-controller
498/// spawn's registration nonce — see `AgentEntry::registration_nonce` / issue #2363.
499pub fn write_shared_with_nonce(
500    shared_dir: &Path,
501    agent_id: &str,
502    local_url: &str,
503    block_id: &str,
504    channel: &str,
505    registration_nonce: u64,
506) {
507    // Resolved BEFORE taking the guard. This is a synchronous SQLite read
508    // serialized on the store's single `Mutex<Connection>`, and it can itself
509    // queue behind an unrelated slow store operation. Holding the process-wide
510    // REGISTRY_OP_LOCK across it would block every other registry file
511    // operation for every agent in the process — writes, removes, and the
512    // nonce compare-and-remove — behind a DB query (reagent P1 on PR #2959).
513    //
514    // Safe to hoist: the key depends only on `agent_id`, not on anything
515    // REGISTRY_OP_LOCK protects. The lock serialises this process's own
516    // read-compare-remove sequences against its own writes; a stale key here
517    // would be no worse than the entry being rewritten a moment later, which
518    // re-registration does anyway.
519    let jekt_public_key = jekt_public_key_for(agent_id);
520    // Same hoisting, same reason: a store read, kept out of the guard.
521    let (uid, uid_public_key) = uid_key_for_block(block_id);
522
523    let _guard = REGISTRY_OP_LOCK.lock().unwrap();
524    let dir = shared_agent_dir(shared_dir, agent_id);
525    let _ = std::fs::create_dir_all(&dir);
526    let path = shared_channel_path(shared_dir, agent_id, channel);
527    let entry = AgentEntry {
528        agent_id: agent_id.to_string(),
529        local_url: local_url.to_string(),
530        block_id: block_id.to_string(),
531        pid: std::process::id(),
532        updated_at: now_unix_millis(),
533        auth_key: local_auth_key().to_string(),
534        channel: channel.to_string(),
535        registration_nonce,
536        jekt_public_key,
537        uid,
538        uid_public_key,
539        jekt_features: vec![agentmux_common::jekt_files::FEATURE.to_string()],
540    };
541    write_entry_file(&path, &entry);
542}
543
544/// Remove this channel's entry for `agent_id` from the shared registry.
545/// Best-effort removes the now-possibly-empty agent directory too (a
546/// concurrent writer recreating it a moment later is harmless — the next
547/// write just re-creates the directory via `create_dir_all`).
548pub fn remove_shared(shared_dir: &Path, agent_id: &str, channel: &str) {
549    let _guard = REGISTRY_OP_LOCK.lock().unwrap();
550    let path = shared_channel_path(shared_dir, agent_id, channel);
551    let _ = std::fs::remove_file(&path);
552    let _ = std::fs::remove_dir(shared_agent_dir(shared_dir, agent_id));
553}
554
555/// [`remove_shared`] **only if** this channel's entry was written by the
556/// spawn with `expected_nonce` — see [`remove_if_nonce`]
557/// (issue #2363). Cross-channel note: only this channel's own file is
558/// read and removed, matching [`write_shared`]'s single-writer contract,
559/// so the process-local [`REGISTRY_OP_LOCK`] still suffices.
560pub fn remove_shared_if_nonce(
561    shared_dir: &Path,
562    agent_id: &str,
563    channel: &str,
564    expected_nonce: u64,
565) {
566    let _guard = REGISTRY_OP_LOCK.lock().unwrap();
567    let path = shared_channel_path(shared_dir, agent_id, channel);
568    let matches = std::fs::read_to_string(&path)
569        .ok()
570        .and_then(|content| serde_json::from_str::<AgentEntry>(&content).ok())
571        .is_some_and(|e| expected_nonce != 0 && e.registration_nonce == expected_nonce);
572    if !matches {
573        tracing::info!(
574            agent_id = %agent_id,
575            channel = %channel,
576            expected_nonce = expected_nonce,
577            "registry: shared entry changed hands since this spawn registered — skipping remove"
578        );
579        return;
580    }
581    let _ = std::fs::remove_file(&path);
582    let _ = std::fs::remove_dir(shared_agent_dir(shared_dir, agent_id));
583}
584
585/// This process's own channel id — `AGENTMUX_CHANNEL`, default `"stable"`.
586///
587/// The single source of the `channel` string written into every shared
588/// registry entry ([`write_shared_from_env`] and siblings), and — as of
589/// `SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md` Phase B — the string
590/// injected into each agent's MCP env as `AGENTMUX_CHANNEL` so the
591/// `source_channel` a sender binds into its cross-channel signature (§D5)
592/// is byte-identical to the `channel` a receiver finds on the entry it
593/// verifies against. Two independent reads of the env var would agree
594/// today; one function guarantees they keep agreeing.
595pub fn local_channel_id() -> String {
596    std::env::var("AGENTMUX_CHANNEL").unwrap_or_else(|_| "stable".to_string())
597}
598
599/// This machine's host label — the `hostname` half of an agent's WAN instance
600/// identity, paired with
601/// [`local_channel_id`] to identify *which* AgentMux instance under an account
602/// owns a given agent's WAN keypair.
603///
604/// Lowercased and trimmed so the value a sender binds into its signature and
605/// the value an instance publishes alongside its public key can't differ by
606/// case alone — the same normalization discipline `agent_id` already has, and
607/// for the same reason: a mismatch here doesn't fail loudly, it selects a
608/// different key and renders a valid message as an active forgery.
609///
610/// Falls back to `"unknown"` exactly as `bootstrap/network.rs` already does for
611/// the LAN advertisement, rather than erroring — an unresolvable hostname must
612/// not block spawning an agent.
613pub fn local_host_label() -> String {
614    whoami::fallible::hostname()
615        .unwrap_or_else(|_| "unknown".to_string())
616        .trim()
617        .to_lowercase()
618}
619
620/// Convenience wrapper over [`write_shared`]: resolves the shared dir and
621/// this process's channel itself, no-op if the shared root can't be
622/// resolved. Exists so call sites outside `server/reactive.rs`'s explicit
623/// register/unregister handlers (PTY shell auto-register, persistent
624/// stream-json controller auto-register — both call the per-channel
625/// `write`/`remove` directly, not through the HTTP handler) don't each
626/// repeat the same resolve-dir-then-read-env dance.
627pub fn write_shared_from_env(agent_id: &str, local_url: &str, block_id: &str) {
628    if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
629        let channel = local_channel_id();
630        write_shared(&shared_dir, agent_id, local_url, block_id, &channel);
631    }
632}
633
634/// Convenience wrapper over [`remove_shared`] — see [`write_shared_from_env`].
635pub fn remove_shared_from_env(agent_id: &str) {
636    if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
637        let channel = local_channel_id();
638        remove_shared(&shared_dir, agent_id, &channel);
639    }
640}
641
642/// Convenience wrapper over [`write_shared_with_nonce`] — see
643/// [`write_shared_from_env`].
644pub fn write_shared_from_env_with_nonce(
645    agent_id: &str,
646    local_url: &str,
647    block_id: &str,
648    registration_nonce: u64,
649) {
650    if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
651        let channel = local_channel_id();
652        write_shared_with_nonce(&shared_dir, agent_id, local_url, block_id, &channel, registration_nonce);
653    }
654}
655
656/// Convenience wrapper over [`remove_shared_if_nonce`] — see
657/// [`write_shared_from_env`].
658pub fn remove_shared_from_env_if_nonce(agent_id: &str, expected_nonce: u64) {
659    if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
660        let channel = local_channel_id();
661        remove_shared_if_nonce(&shared_dir, agent_id, &channel, expected_nonce);
662    }
663}
664
665/// Whether `entry` is one this srv wrote for `block_id` that a stopping spawn may remove: any entry
666/// of the block, whatever name it is filed under, unless a newer spawn wrote it (a nonce that is
667/// neither 0, "not recorded", nor `only_nonce`). `None` removes whatever nonce it has.
668fn block_entry_is_removable(entry: &AgentEntry, block_id: &str, only_nonce: Option<u64>) -> bool {
669    entry.block_id == block_id
670        && entry.pid == std::process::id()
671        && only_nonce.is_none_or(|n| entry.registration_nonce == 0 || entry.registration_nonce == n)
672}
673
674/// Remove every per-channel entry registered for `block_id`, under any name: the agent's slug, a
675/// former slug, or its display name's route (an entry written during a turn is filed under the
676/// block's current name, not the one its spawn registered). A removal keyed on one name leaves the
677/// others behind, and a stopped agent then reads as running. Returns how many files it removed.
678pub fn remove_for_block(data_dir: &Path, block_id: &str, only_nonce: Option<u64>) -> usize {
679    let _guard = REGISTRY_OP_LOCK.lock().unwrap();
680    remove_matching_in(&agents_dir(data_dir), block_id, only_nonce)
681}
682
683/// [`remove_for_block`] for this channel's entries in the host-global shared registry, which files
684/// them `<shared_dir>/<name>/<channel>.json`.
685pub fn remove_shared_for_block(shared_dir: &Path, block_id: &str, channel: &str, only_nonce: Option<u64>) -> usize {
686    let _guard = REGISTRY_OP_LOCK.lock().unwrap();
687    let Ok(dirs) = std::fs::read_dir(shared_dir) else { return 0 };
688    let mut removed = 0;
689    for dir in dirs.flatten().filter(|d| d.path().is_dir()) {
690        let path = dir.path().join(format!("{}.json", sanitize_path_component(channel)));
691        if read_entry_file(&path).is_some_and(|e| block_entry_is_removable(&e, block_id, only_nonce)) {
692            removed += usize::from(std::fs::remove_file(&path).is_ok());
693            let _ = std::fs::remove_dir(dir.path());
694        }
695    }
696    removed
697}
698
699/// Convenience wrapper over [`remove_shared_for_block`] — see [`write_shared_from_env`].
700pub fn remove_shared_for_block_from_env(block_id: &str, only_nonce: Option<u64>) -> usize {
701    crate::registry::resolve_shared_reactive_dir()
702        .map_or(0, |shared_dir| remove_shared_for_block(&shared_dir, block_id, &local_channel_id(), only_nonce))
703}
704
705fn remove_matching_in(dir: &Path, block_id: &str, only_nonce: Option<u64>) -> usize {
706    let Ok(files) = std::fs::read_dir(dir) else { return 0 };
707    let mut removed = 0;
708    for file in files.flatten() {
709        let path = file.path();
710        if path.extension().and_then(|e| e.to_str()) != Some("json") {
711            continue;
712        }
713        if read_entry_file(&path).is_some_and(|e| block_entry_is_removable(&e, block_id, only_nonce)) {
714            removed += usize::from(std::fs::remove_file(&path).is_ok());
715        }
716    }
717    removed
718}
719
720/// Every channel's shared entry that published a key for `uid` (identity
721/// M4d-6). Scans the whole registry: entries are filed by name, and one UID
722/// live in several channels has an entry, and a key, in each.
723pub fn lookup_shared_by_uid(shared_dir: &Path, uid: &str) -> Vec<AgentEntry> {
724    let Ok(dirs) = std::fs::read_dir(shared_dir) else { return Vec::new() };
725    dirs.flatten()
726        .filter(|d| d.path().is_dir())
727        .flat_map(|d| read_entry_files_in_dir(&d.path()))
728        .filter(|e| e.uid == uid && !e.uid_public_key.is_empty())
729        .collect()
730}
731
732/// Return every live candidate for `agent_id` across all channels,
733/// freshest-first (§4.3: Tier 2b prefers the freshest candidate). Does
734/// NOT filter by staleness/pid-liveness — callers needing that should use
735/// [`cleanup_stale_shared`] (startup sweep) plus the existing
736/// evict-on-forward-failure pattern already used by Tier 2a/3 in
737/// `server/reactive.rs`, matching how this codebase already handles
738/// registry staleness elsewhere rather than re-validating on every read.
739pub fn lookup_all_shared(shared_dir: &Path, agent_id: &str) -> Vec<AgentEntry> {
740    let dir = shared_agent_dir(shared_dir, agent_id);
741    let mut list = read_entry_files_in_dir(&dir);
742    list.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
743    list
744}
745
746/// List every entry currently in the host-global shared registry, across
747/// every agent name and channel. Used by the `/agentmux/discovery` endpoint
748/// to populate `host.cross_channel[]` (§4.5 of the cross-channel delivery
749/// spec) — unlike [`lookup_all_shared`], which targets one known agent
750/// name, this enumerates the whole directory.
751pub fn list_all_shared(shared_dir: &Path) -> Vec<AgentEntry> {
752    // Not agents_dir(shared_dir) -- see shared_agent_dir's doc comment.
753    let Ok(entries) = std::fs::read_dir(shared_dir) else {
754        return Vec::new();
755    };
756    let mut out = Vec::new();
757    for entry in entries.flatten() {
758        let path = entry.path();
759        if !path.is_dir() {
760            continue;
761        }
762        out.extend(read_entry_files_in_dir(&path));
763    }
764    out
765}
766
767/// Startup sweep over the host-global registry: remove any entry whose
768/// `updated_at` is past `max_age_ms` OR whose `pid` is no longer alive on
769/// this host (§4.4) — the dead-`Agent3` case from the spec's problem
770/// statement, where per-channel TTL cleanup never reached an entry
771/// belonging to a channel that hadn't restarted.
772pub fn cleanup_stale_shared(shared_dir: &Path, max_age_ms: u64) {
773    // Not agents_dir(shared_dir) -- see shared_agent_dir's doc comment.
774    let Ok(agent_dirs) = std::fs::read_dir(shared_dir) else { return };
775    let cutoff = now_unix_millis().saturating_sub(max_age_ms);
776    for agent_dir_entry in agent_dirs.flatten() {
777        let agent_dir_path = agent_dir_entry.path();
778        if !agent_dir_path.is_dir() {
779            continue;
780        }
781        let Ok(channel_files) = std::fs::read_dir(&agent_dir_path) else { continue };
782        for channel_entry in channel_files.flatten() {
783            let channel_path = channel_entry.path();
784            if channel_path.extension().and_then(|e| e.to_str()) != Some("json") {
785                continue;
786            }
787            let keep = read_entry_file(&channel_path)
788                .map(|e| e.updated_at >= cutoff && e.srv_alive())
789                .unwrap_or(false);
790            if !keep {
791                let _ = std::fs::remove_file(&channel_path);
792            }
793        }
794        // Best-effort: only actually removes the directory if it's now
795        // empty (every channel file was stale) — a concurrent writer
796        // recreating it right after is harmless, same as `remove_shared`.
797        let _ = std::fs::remove_dir(&agent_dir_path);
798    }
799}
800
801/// Best-effort read of one (agent, channel) entry file. Missing,
802/// unreadable, or malformed files are treated as absent — same
803/// graceful-degradation posture as the per-channel `lookup`.
804fn read_entry_file(path: &Path) -> Option<AgentEntry> {
805    let content = std::fs::read_to_string(path).ok()?;
806    serde_json::from_str(&content).ok()
807}
808
809/// Read every valid `.json` entry file directly inside `dir` (one level,
810/// not recursive) — used for both `lookup_all_shared` (one agent's
811/// per-channel dir) and `list_all_shared` (one agent-name dir at a time).
812fn read_entry_files_in_dir(dir: &Path) -> Vec<AgentEntry> {
813    let Ok(entries) = std::fs::read_dir(dir) else {
814        return Vec::new();
815    };
816    entries
817        .flatten()
818        .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("json"))
819        .filter_map(|e| read_entry_file(&e.path()))
820        .collect()
821}
822
823/// Write one (agent, channel) entry file, atomically (temp file + rename)
824/// so a concurrent reader never observes a partially-written file. Mode
825/// 0600 on Unix at open time — same auth_key exposure boundary as the
826/// per-channel registry (§5 of the cross-channel spec: same-user trust
827/// boundary, not cross-user).
828fn write_entry_file(path: &Path, entry: &AgentEntry) {
829    let Ok(json) = serde_json::to_string(entry) else { return };
830    let tmp_path = path.with_extension("json.tmp");
831
832    let mut opts = std::fs::OpenOptions::new();
833    opts.write(true).create(true).truncate(true);
834    #[cfg(unix)]
835    {
836        use std::os::unix::fs::OpenOptionsExt;
837        opts.mode(0o600);
838    }
839    let Ok(mut f) = opts.open(&tmp_path) else { return };
840    use std::io::Write;
841    if f.write_all(json.as_bytes()).is_err() {
842        let _ = std::fs::remove_file(&tmp_path);
843        return;
844    }
845    drop(f);
846    let _ = std::fs::rename(&tmp_path, path);
847}
848
849/// Write a fully-specified shared-registry entry, bypassing the
850/// process-global pubkey resolver and `local_auth_key()`. For tests that
851/// need a deterministic `jekt_public_key` regardless of which other test in
852/// the binary happened to install the `OnceLock` resolver first
853/// (`server/reactive.rs`'s cross-channel verification tests).
854#[cfg(any(test, feature = "test-support"))]
855pub fn write_shared_entry_for_test(shared_dir: &Path, entry: &AgentEntry) {
856    let _guard = REGISTRY_OP_LOCK.lock().unwrap();
857    let _ = std::fs::create_dir_all(shared_agent_dir(shared_dir, &entry.agent_id));
858    write_entry_file(&shared_channel_path(shared_dir, &entry.agent_id, &entry.channel), entry);
859}
860
861#[cfg(test)]
862mod shared_tests {
863    use super::*;
864
865    #[test]
866    fn write_then_lookup_round_trip() {
867        let dir = tempfile::tempdir().unwrap();
868        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
869        let found = lookup_all_shared(dir.path(), "agentx");
870        assert_eq!(found.len(), 1);
871        assert_eq!(found[0].channel, "dev-a");
872        assert_eq!(found[0].local_url, "http://127.0.0.1:9001");
873        assert_eq!(found[0].block_id, "block1");
874    }
875
876    #[test]
877    fn write_and_lookup_are_case_insensitive() {
878        let dir = tempfile::tempdir().unwrap();
879        write_shared(dir.path(), "AgentX", "http://127.0.0.1:9001", "block1", "dev-a");
880        // A peer looking up the lowercase form (as ReactiveHandler's
881        // Tier-1 in-memory map always does) must land on the same entry —
882        // reagent P1 on #2350.
883        let found = lookup_all_shared(dir.path(), "agentx");
884        assert_eq!(found.len(), 1);
885        assert_eq!(found[0].local_url, "http://127.0.0.1:9001");
886
887        // And a second write under a different-cased spelling of the same
888        // name must overwrite, not create a sibling file.
889        write_shared(dir.path(), "AGENTX", "http://127.0.0.1:9099", "block9", "dev-a");
890        let found = lookup_all_shared(dir.path(), "agentx");
891        assert_eq!(found.len(), 1);
892        assert_eq!(found[0].local_url, "http://127.0.0.1:9099");
893    }
894
895    #[test]
896    fn multiple_channels_coexist_for_same_name() {
897        let dir = tempfile::tempdir().unwrap();
898        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
899        write_shared(dir.path(), "agentx", "http://127.0.0.1:9002", "block2", "dev-b");
900        let found = lookup_all_shared(dir.path(), "agentx");
901        assert_eq!(found.len(), 2);
902        let channels: std::collections::HashSet<_> =
903            found.iter().map(|e| e.channel.clone()).collect();
904        assert_eq!(
905            channels,
906            ["dev-a", "dev-b"].into_iter().map(String::from).collect()
907        );
908    }
909
910    #[test]
911    fn write_same_channel_twice_replaces_not_duplicates() {
912        let dir = tempfile::tempdir().unwrap();
913        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
914        write_shared(dir.path(), "agentx", "http://127.0.0.1:9099", "block9", "dev-a");
915        let found = lookup_all_shared(dir.path(), "agentx");
916        assert_eq!(found.len(), 1);
917        assert_eq!(found[0].local_url, "http://127.0.0.1:9099");
918    }
919
920    // ---- identity M4d-5: the UID and its key published beside the name's ----
921
922    #[test]
923    fn a_shared_entry_publishes_the_block_s_uid_and_its_public_key() {
924        // The resolver is a process-wide OnceLock: this one test owns it. The
925        // key is a real M4d-2 key from a real store row; only the block→UID
926        // step is a fixed map here (bootstrap reads the block's active
927        // instance).
928        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
929        let mut def = crate::backend::storage::agents::test_agent_def("uid-x", "agentx", "claude", "agent", 1, "");
930        def.slug = "agentx".into();
931        store.agent_def_insert(&mut def).unwrap();
932        let (keys, _) = store.agent_uid_keys_ensure("uid-x").unwrap().unwrap();
933        let public = keys.lan.public_key.clone();
934        init_uid_key_resolver(move |block_id| {
935            (block_id == "block-uid").then(|| ("uid-x".to_string(), store.agent_uid_lan_public_key_load("uid-x").ok().flatten())).and_then(|(u, k)| Some((u, k?)))
936        });
937
938        let dir = tempfile::tempdir().unwrap();
939        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block-uid", "dev-a");
940        write_shared(dir.path(), "agenty", "http://127.0.0.1:9001", "block-none", "dev-a");
941        let x = &lookup_all_shared(dir.path(), "agentx")[0];
942        assert_eq!((x.uid.as_str(), x.uid_public_key.as_str()), ("uid-x", public.as_str()));
943        assert_ne!(x.uid_public_key, keys.lan.private_key, "never the private half");
944        let y = &lookup_all_shared(dir.path(), "agenty")[0];
945        assert_eq!((y.uid.as_str(), y.uid_public_key.as_str()), ("", ""), "no row: nothing to check against");
946        let raw = std::fs::read_to_string(shared_channel_path(dir.path(), "agenty", "dev-a")).unwrap();
947        assert!(!raw.contains("uid"), "empty fields stay off the wire for older readers");
948    }
949
950    // ---- jekt_public_key publication (SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md §D1) ----
951
952    #[test]
953    fn a_shared_entry_publishes_the_agents_real_store_public_key() {
954        // Store-backed, not a stub: the closure installed here is the SAME
955        // shape bootstrap/stores.rs installs, so this exercises the real
956        // resolver → Store → entry wiring rather than just the plumbing
957        // around it. That distinction matters — the last time a jekt key
958        // feature shipped, the code was correct and the real call path simply
959        // never ran it (REPORT_JEKT_SIGNING_KEY_INJECTION_GAP_2026_08_16.md).
960        //
961        // The resolver is a process-wide OnceLock, so this one test owns it
962        // for the whole test binary — hence both the resolvable and the
963        // unresolvable agent are covered here rather than in two tests that
964        // would race to set it.
965        // In memory: the resolver keeps the store for the process's life,
966        // so a file-backed one would outlive its temp file and leave its
967        // -wal/-shm behind (#3815).
968        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
969        let minted = store.agent_lan_key_ensure("agentx").unwrap();
970
971        init_jekt_public_key_resolver(move |agent_id| {
972            store.agent_lan_public_key_load(agent_id).ok().flatten()
973        });
974
975        let dir = tempfile::tempdir().unwrap();
976        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
977        let found = lookup_all_shared(dir.path(), "agentx");
978        assert_eq!(found.len(), 1);
979        assert_eq!(
980            found[0].jekt_public_key, minted.public_key,
981            "the shared entry must publish the agent's real public key from the store"
982        );
983        assert_ne!(
984            found[0].jekt_public_key, minted.private_key,
985            "the PRIVATE half must never reach the shared registry"
986        );
987
988        // Case-insensitivity: registry ids are lowercased on the path, the
989        // store lowercases on lookup — a display-cased name must still resolve.
990        write_shared(dir.path(), "AgentX", "http://127.0.0.1:9001", "block1", "dev-b");
991        let cased = lookup_all_shared(dir.path(), "agentx");
992        assert!(cased.iter().all(|e| e.jekt_public_key == minted.public_key));
993
994        // An agent with no LAN keypair minted yet publishes an empty key
995        // rather than failing the write. Empty means "cannot check" (§6) —
996        // the registry write itself must stay infallible.
997        write_shared(dir.path(), "agenty", "http://127.0.0.1:9002", "block2", "dev-a");
998        let other = lookup_all_shared(dir.path(), "agenty");
999        assert_eq!(other.len(), 1);
1000        assert!(other[0].jekt_public_key.is_empty());
1001    }
1002
1003    #[test]
1004    fn an_entry_written_before_this_shipped_still_deserializes_with_an_empty_key() {
1005        // §6 backward compatibility: a pre-upgrade file has no
1006        // `jekt_public_key` member at all. It must load (not error), and it
1007        // must load as EMPTY — which the verifier maps to "cannot check",
1008        // never to "failed the check". Getting this wrong escalates every
1009        // sender on a mixed-version machine.
1010        let dir = tempfile::tempdir().unwrap();
1011        let agent_dir = shared_agent_dir(dir.path(), "agentz");
1012        std::fs::create_dir_all(&agent_dir).unwrap();
1013        let legacy = r#"{"agent_id":"agentz","local_url":"http://127.0.0.1:9003",
1014            "block_id":"b3","pid":1,"updated_at":1,"auth_key":"k","channel":"dev-a",
1015            "registration_nonce":0}"#;
1016        std::fs::write(shared_channel_path(dir.path(), "agentz", "dev-a"), legacy).unwrap();
1017
1018        let found = lookup_all_shared(dir.path(), "agentz");
1019        assert_eq!(found.len(), 1, "a pre-upgrade entry must still deserialize");
1020        assert!(found[0].jekt_public_key.is_empty());
1021        assert_eq!(found[0].auth_key, "k", "the other fields must survive intact");
1022    }
1023
1024    #[test]
1025    fn lookup_all_shared_sorts_freshest_first() {
1026        let dir = tempfile::tempdir().unwrap();
1027        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
1028        write_shared(dir.path(), "agentx", "http://127.0.0.1:9002", "block2", "dev-b");
1029        // Directly bump dev-b's own file's updated_at so it's unambiguously
1030        // freshest, independent of how fast the two writes above happened
1031        // to run. Only touches dev-b's own file -- exactly the point of
1032        // the one-file-per-channel layout.
1033        let path = shared_channel_path(dir.path(), "agentx", "dev-b");
1034        let mut entry = read_entry_file(&path).unwrap();
1035        entry.updated_at += 10_000;
1036        write_entry_file(&path, &entry);
1037
1038        let found = lookup_all_shared(dir.path(), "agentx");
1039        assert_eq!(found[0].channel, "dev-b");
1040        assert_eq!(found[1].channel, "dev-a");
1041    }
1042
1043    /// A turn files an entry under the block's current name with no nonce; a spawn's own removal is keyed on
1044    /// the name and nonce it registered by. A stop must still leave nothing for the block.
1045    #[test]
1046    fn remove_for_block_clears_every_name_but_a_newer_spawns() {
1047        let dir = tempfile::tempdir().unwrap();
1048        let url = "http://127.0.0.1:9001";
1049        write_with_nonce(dir.path(), "loap-loap-2-loap-3", url, "blk", 7);
1050        write_with_nonce(dir.path(), "Loap-3", url, "blk", 0);
1051        write_with_nonce(dir.path(), "newer", url, "blk", 9);
1052        write_with_nonce(dir.path(), "other", url, "blk2", 0);
1053        assert_eq!(remove_for_block(dir.path(), "blk", Some(7)), 2);
1054        assert!(lookup(dir.path(), "loap-loap-2-loap-3").is_none());
1055        assert!(lookup(dir.path(), "loap-3").is_none());
1056        assert!(lookup(dir.path(), "newer").is_some(), "a newer spawn's entry survives");
1057        assert!(lookup(dir.path(), "other").is_some(), "another block's entry survives");
1058        assert_eq!(remove_for_block(dir.path(), "blk", None), 1, "an unconditional removal takes it too");
1059        assert!(lookup(dir.path(), "other").is_some());
1060    }
1061
1062    #[test]
1063    fn remove_for_block_leaves_an_entry_another_srv_wrote() {
1064        let dir = tempfile::tempdir().unwrap();
1065        write_with_nonce(dir.path(), "peer", "http://127.0.0.1:9001", "blk", 0);
1066        let mut entry = lookup(dir.path(), "peer").unwrap();
1067        entry.pid = u32::MAX;
1068        write_entry_file(&agent_path(dir.path(), "peer"), &entry);
1069        assert_eq!(remove_for_block(dir.path(), "blk", None), 0);
1070        assert!(lookup(dir.path(), "peer").is_some());
1071    }
1072
1073    #[test]
1074    fn remove_shared_for_block_clears_every_name_in_this_channel_only() {
1075        let dir = tempfile::tempdir().unwrap();
1076        let url = "http://127.0.0.1:9001";
1077        write_shared_with_nonce(dir.path(), "loap-loap-2-loap-3", url, "blk", "stable", 7);
1078        write_shared_with_nonce(dir.path(), "Loap-3", url, "blk", "stable", 0);
1079        write_shared_with_nonce(dir.path(), "loap-3", url, "blk", "dev-a", 0);
1080        write_shared_with_nonce(dir.path(), "other", url, "blk2", "stable", 0);
1081        assert_eq!(remove_shared_for_block(dir.path(), "blk", "stable", Some(7)), 2);
1082        assert!(lookup_all_shared(dir.path(), "loap-loap-2-loap-3").is_empty());
1083        assert_eq!(lookup_all_shared(dir.path(), "loap-3").len(), 1, "the other channel's entry survives");
1084        assert_eq!(lookup_all_shared(dir.path(), "other").len(), 1);
1085        assert!(!shared_agent_dir(dir.path(), "loap-loap-2-loap-3").exists(), "its emptied directory goes too");
1086    }
1087
1088    #[test]
1089    fn a_pid_a_program_took_after_the_srv_exited_is_not_that_srv() {
1090        // Rounding either way is allowed; a start well after the write is another process.
1091        assert!(started_no_later_than(100, 100_000));
1092        assert!(started_no_later_than(103, 100_000));
1093        assert!(!started_no_later_than(200, 100_000));
1094        // This process is alive now, so an entry it wrote just now is its own, and one written an hour ago
1095        // (before it started) is a pid it has since been given.
1096        let now = now_unix_millis();
1097        assert!(pid_alive_since(std::process::id(), now));
1098        assert!(!pid_alive_since(std::process::id(), now - 3_600_000));
1099        assert!(!pid_alive_since(u32::MAX, now));
1100    }
1101
1102    #[test]
1103    fn cleanup_stale_drops_an_entry_whose_pid_was_reused() {
1104        let dir = tempfile::tempdir().unwrap();
1105        write(dir.path(), "kept", "http://127.0.0.1:9001", "b1");
1106        write(dir.path(), "reused", "http://127.0.0.1:9002", "b2");
1107        let mut reused = lookup(dir.path(), "reused").unwrap();
1108        reused.updated_at = now_unix_millis() - 3_600_000;
1109        write_entry_file(&agent_path(dir.path(), "reused"), &reused);
1110        cleanup_stale(dir.path(), 4 * 60 * 60 * 1000);
1111        assert!(lookup(dir.path(), "kept").is_some());
1112        assert!(lookup(dir.path(), "reused").is_none());
1113    }
1114
1115    #[test]
1116    fn remove_shared_drops_only_that_channel() {
1117        let dir = tempfile::tempdir().unwrap();
1118        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
1119        write_shared(dir.path(), "agentx", "http://127.0.0.1:9002", "block2", "dev-b");
1120        remove_shared(dir.path(), "agentx", "dev-a");
1121        let found = lookup_all_shared(dir.path(), "agentx");
1122        assert_eq!(found.len(), 1);
1123        assert_eq!(found[0].channel, "dev-b");
1124    }
1125
1126    #[test]
1127    fn remove_shared_last_channel_deletes_file_and_dir() {
1128        let dir = tempfile::tempdir().unwrap();
1129        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
1130        remove_shared(dir.path(), "agentx", "dev-a");
1131        assert!(lookup_all_shared(dir.path(), "agentx").is_empty());
1132        assert!(!shared_channel_path(dir.path(), "agentx", "dev-a").exists());
1133        assert!(!shared_agent_dir(dir.path(), "agentx").exists());
1134    }
1135
1136    #[test]
1137    fn list_all_shared_covers_multiple_agent_names() {
1138        let dir = tempfile::tempdir().unwrap();
1139        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
1140        write_shared(dir.path(), "agenty", "http://127.0.0.1:9002", "block2", "dev-b");
1141        let all = list_all_shared(dir.path());
1142        assert_eq!(all.len(), 2);
1143        let names: std::collections::HashSet<_> =
1144            all.iter().map(|e| e.agent_id.clone()).collect();
1145        assert_eq!(
1146            names,
1147            ["agentx", "agenty"].into_iter().map(String::from).collect()
1148        );
1149    }
1150
1151    #[test]
1152    fn cleanup_stale_shared_evicts_by_ttl() {
1153        let dir = tempfile::tempdir().unwrap();
1154        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
1155        // Backdate updated_at well past the TTL, but keep pid as our own
1156        // (alive) so only the TTL check can be responsible for eviction.
1157        let path = shared_channel_path(dir.path(), "agentx", "dev-a");
1158        let mut entry = read_entry_file(&path).unwrap();
1159        entry.updated_at = 0;
1160        entry.pid = std::process::id();
1161        write_entry_file(&path, &entry);
1162
1163        cleanup_stale_shared(dir.path(), 4 * 60 * 60 * 1000);
1164        assert!(lookup_all_shared(dir.path(), "agentx").is_empty());
1165    }
1166
1167    #[test]
1168    fn cleanup_stale_shared_evicts_dead_pid_even_if_fresh() {
1169        let dir = tempfile::tempdir().unwrap();
1170        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
1171        // Fresh updated_at, but a PID essentially guaranteed not to exist —
1172        // exercises the dead-channel-that-never-restarted case from the
1173        // spec's problem statement, which TTL alone wouldn't catch for
1174        // another 4 hours.
1175        let path = shared_channel_path(dir.path(), "agentx", "dev-a");
1176        let mut entry = read_entry_file(&path).unwrap();
1177        entry.pid = u32::MAX;
1178        write_entry_file(&path, &entry);
1179
1180        cleanup_stale_shared(dir.path(), 4 * 60 * 60 * 1000);
1181        assert!(lookup_all_shared(dir.path(), "agentx").is_empty());
1182    }
1183
1184    #[test]
1185    fn cleanup_stale_shared_keeps_fresh_live_entries() {
1186        let dir = tempfile::tempdir().unwrap();
1187        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
1188        let path = shared_channel_path(dir.path(), "agentx", "dev-a");
1189        let mut entry = read_entry_file(&path).unwrap();
1190        entry.pid = std::process::id();
1191        write_entry_file(&path, &entry);
1192
1193        cleanup_stale_shared(dir.path(), 4 * 60 * 60 * 1000);
1194        assert_eq!(lookup_all_shared(dir.path(), "agentx").len(), 1);
1195    }
1196
1197    #[test]
1198    fn cleanup_stale_shared_evicts_one_channel_keeps_sibling() {
1199        // The whole point of the redesign: cleanup for one channel's
1200        // stale/dead entry must not disturb a sibling channel's live one,
1201        // since they're now genuinely separate files, not shared array
1202        // elements.
1203        let dir = tempfile::tempdir().unwrap();
1204        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "dev-a");
1205        write_shared(dir.path(), "agentx", "http://127.0.0.1:9002", "block2", "dev-b");
1206        let stale_path = shared_channel_path(dir.path(), "agentx", "dev-a");
1207        let mut stale = read_entry_file(&stale_path).unwrap();
1208        stale.pid = u32::MAX;
1209        write_entry_file(&stale_path, &stale);
1210
1211        cleanup_stale_shared(dir.path(), 4 * 60 * 60 * 1000);
1212        let found = lookup_all_shared(dir.path(), "agentx");
1213        assert_eq!(found.len(), 1);
1214        assert_eq!(found[0].channel, "dev-b");
1215    }
1216
1217    #[test]
1218    fn agent_id_path_traversal_is_sanitized() {
1219        let dir = tempfile::tempdir().unwrap();
1220        write_shared(dir.path(), "../../evil", "http://127.0.0.1:9001", "block1", "dev-a");
1221        // Sanitization (shared_agent_dir) must keep the write confined to
1222        // the shared registry root — no directory with `.` path segments
1223        // should escape it. Reading `dir.path()` directly (not
1224        // `agents_dir(dir.path())`) since shared_agent_dir no longer nests
1225        // under an extra `agents/` level.
1226        for entry in std::fs::read_dir(dir.path()).unwrap() {
1227            let name = entry.unwrap().file_name();
1228            assert!(!name.to_string_lossy().contains(".."));
1229        }
1230    }
1231
1232    #[test]
1233    fn channel_path_traversal_is_sanitized() {
1234        let dir = tempfile::tempdir().unwrap();
1235        write_shared(dir.path(), "agentx", "http://127.0.0.1:9001", "block1", "../../evil");
1236        // Sanitization must apply to the CHANNEL component too, not just
1237        // the agent name — a channel string is caller-controlled the same
1238        // way an agent_id is.
1239        let agent_dir = shared_agent_dir(dir.path(), "agentx");
1240        for entry in std::fs::read_dir(&agent_dir).unwrap() {
1241            let name = entry.unwrap().file_name();
1242            assert!(!name.to_string_lossy().contains(".."));
1243        }
1244    }
1245
1246    #[test]
1247    fn concurrent_writes_from_different_channels_never_clobber() {
1248        // Direct regression test for reagent's P1 on PR #2350: the old
1249        // one-array-per-agent-name design let two channels' concurrent
1250        // writes race (each reads the pre-write array, second writer's
1251        // save clobbers the first). Spawns real OS threads hammering
1252        // write_shared for N distinct channels of the same agent name
1253        // concurrently and asserts every single one survives.
1254        let dir = tempfile::tempdir().unwrap();
1255        let shared_dir = dir.path().to_path_buf();
1256        const N: usize = 16;
1257
1258        let handles: Vec<_> = (0..N)
1259            .map(|i| {
1260                let shared_dir = shared_dir.clone();
1261                std::thread::spawn(move || {
1262                    let channel = format!("dev-{i}");
1263                    for _ in 0..5 {
1264                        write_shared(
1265                            &shared_dir,
1266                            "agentx",
1267                            &format!("http://127.0.0.1:{}", 9000 + i),
1268                            "block1",
1269                            &channel,
1270                        );
1271                    }
1272                })
1273            })
1274            .collect();
1275        for h in handles {
1276            h.join().unwrap();
1277        }
1278
1279        let found = lookup_all_shared(&shared_dir, "agentx");
1280        assert_eq!(found.len(), N, "every channel's entry must survive concurrent writes");
1281        let channels: std::collections::HashSet<_> = found.iter().map(|e| e.channel.clone()).collect();
1282        assert_eq!(channels.len(), N);
1283    }
1284
1285    #[test]
1286    fn pid_alive_true_for_self() {
1287        assert!(pid_alive(std::process::id()));
1288    }
1289
1290    #[test]
1291    fn pid_alive_false_for_max_pid() {
1292        assert!(!pid_alive(u32::MAX));
1293    }
1294
1295    fn entry_with(pid: u32, updated_at: u64) -> AgentEntry {
1296        AgentEntry {
1297            agent_id: "agentx".to_string(),
1298            local_url: "http://127.0.0.1:9001".to_string(),
1299            block_id: "block1".to_string(),
1300            pid,
1301            updated_at,
1302            auth_key: String::new(),
1303            channel: "dev-a".to_string(),
1304            registration_nonce: 0,
1305            jekt_public_key: String::new(),
1306            uid: String::new(),
1307            uid_public_key: String::new(),
1308            jekt_features: Vec::new(),
1309        }
1310    }
1311
1312    #[test]
1313    fn should_evict_on_forward_failure_true_for_dead_pid_even_when_fresh() {
1314        // Dead process is definitive regardless of age — the original,
1315        // pre-PR-2640 case this whole mechanism exists for.
1316        let entry = entry_with(u32::MAX, now_unix_millis());
1317        assert!(should_evict_on_forward_failure(&entry));
1318    }
1319
1320    #[test]
1321    fn should_evict_on_forward_failure_false_for_alive_pid_and_fresh_entry() {
1322        // The race PR #2640 actually fixes: owning srv process is alive, the
1323        // entry was JUST written (this agent's own registration is still
1324        // settling) — a forward failure right now is presumed transient.
1325        let entry = entry_with(std::process::id(), now_unix_millis());
1326        assert!(!should_evict_on_forward_failure(&entry));
1327    }
1328
1329    #[test]
1330    fn should_evict_on_forward_failure_true_for_alive_pid_but_old_entry() {
1331        // reagent P1 round 2 on PR #2640: a genuinely-dead INDIVIDUAL agent
1332        // whose srv process stays alive for other agents (the shared-srv
1333        // topology this host actually runs) must still be evictable once
1334        // the entry is old enough that a startup race is no longer a
1335        // plausible explanation — pid-liveness alone would wrongly protect
1336        // this forever.
1337        let stale_updated_at = now_unix_millis().saturating_sub(FORWARD_FAILURE_GRACE_MS + 1_000);
1338        let entry = entry_with(std::process::id(), stale_updated_at);
1339        assert!(should_evict_on_forward_failure(&entry));
1340    }
1341}