agentmux_srv_core/backend/agent_registry_lookup.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Slug-based lookup into the global named-agent registry.
5//!
6//! **One implementation, deliberately.** This matching is subtle — the caller
7//! holds a routing slug (`AGENTMUX_AGENT_ID`, e.g. `"agenty"`) while a record
8//! stores the display-cased `instance_name` (e.g. `"AgentY"`), so both sides
9//! have to be normalized through [`derive_slug`] rather than compared
10//! directly. Raw string equality here was a real bug (reagentx, PR #2428).
11//!
12//! It lived in `server::native_memory_handlers` and was then re-implemented in
13//! `backend::history`; reagentx P2 on PR #3480 flagged the copy, citing this
14//! codebase's own history of exactly that drift — *"a future collision/matching
15//! fix applied to one copy will silently miss the other."*
16//!
17//! It lives in `backend/` rather than `registry/` on purpose: `registry/` has
18//! no dependency on `crate::backend` at all today, and [`derive_slug`] is a
19//! `backend::storage` function — homing this there would have added a
20//! registry→backend edge to a module that is currently self-contained.
21
22use crate::backend::storage::store::derive_slug;
23use crate::registry::NamedAgentRecord;
24
25/// Every active registry record whose `instance_name` normalizes to the same
26/// slug as `agent_id`. Usually zero or one; more than one means a collision.
27fn active_records_matching_slug(agent_id: &str) -> Option<Vec<NamedAgentRecord>> {
28 let registry_dir = crate::registry::resolve_shared_registry_dir()?;
29 let registry = crate::registry::Registry::open(registry_dir).ok()?;
30 let queried_slug = derive_slug(agent_id);
31 Some(
32 registry
33 .list_active()
34 .ok()?
35 .into_iter()
36 .filter(|r| derive_slug(&r.data.instance_name) == queried_slug)
37 .collect(),
38 )
39}
40
41/// The active registry record whose `instance_name` normalizes to the same
42/// slug as `agent_id` — **only if it names one agent**.
43///
44/// One record matching is one agent. Several records that all name one
45/// non-empty `definition_id` are also one agent, recorded more than once (the
46/// move to definition-id keys left the old record beside the new): the
47/// preferred record answers (see [`preferred`]).
48///
49/// `None` when the registry is unavailable, unreadable, nothing matches, or
50/// **records of different definitions match**. Callers treat the first three
51/// the same way (fall back to another source), so they are not distinguished.
52///
53/// **Why ambiguity returns `None` rather than the first match** (reagentx P1,
54/// PR #3480): registry records are keyed by `instance_id`, and nothing
55/// enforces a unique `instance_name` across them — `derive_slug("AgentY")` and
56/// `derive_slug("AGENTY")` are both `agenty`, which two agents on two hosts
57/// can easily produce. This function used to return whichever matched first in
58/// `list_active()` order, handing that record's `definition_id` and
59/// `working_dir` to the caller. Callers use those to resolve an agent's
60/// *conversation history* and *memory directory*, so guessing wrong does not
61/// degrade gracefully — it discloses one agent's data to another. A slug
62/// simply does not identify an agent when it collides, so the honest answer
63/// is "unknown". Same collision class as Codex P1 on #2901 and reagentx on
64/// #2428.
65///
66/// If you hold a `definition_id`, prefer
67/// [`find_active_record_by_slug_and_definition`] — it resolves the collision
68/// instead of refusing it.
69pub(crate) fn find_active_record_by_slug(agent_id: &str) -> Option<NamedAgentRecord> {
70 let mut matches = active_records_matching_slug(agent_id)?;
71 // Records that all name one definition are one agent recorded more than once (an upgrade across the move to
72 // definition-id keys left the old record beside the new): not a collision, and the live one answers.
73 if matches.len() > 1 && same_definition(&matches) {
74 return Some(preferred(matches));
75 }
76 match matches.len() {
77 1 => matches.pop(),
78 0 => None,
79 n => {
80 tracing::warn!(
81 slug = %derive_slug(agent_id),
82 matches = n,
83 "registry slug collision: refusing to resolve an agent by slug alone"
84 );
85 None
86 }
87 }
88}
89
90/// The active registry record matching both `agent_id`'s slug and an exact
91/// `definition_id`.
92///
93/// For callers that already know which agent they mean. Unlike
94/// [`find_active_record_by_slug`] this stays correct under a slug collision,
95/// because `definition_id` is the disambiguator the slug lacks — so it returns
96/// a record in cases where the slug-only lookup must give up.
97pub fn find_active_record_by_slug_and_definition(
98 agent_id: &str,
99 definition_id: &str,
100) -> Option<NamedAgentRecord> {
101 let of_definition: Vec<_> = active_records_matching_slug(agent_id)?.into_iter().filter(|r| r.data.definition_id == definition_id).collect();
102 (!of_definition.is_empty()).then(|| preferred(of_definition))
103}
104
105/// Whether every record names one non-empty definition that is a user agent: they are one agent, recorded more than
106/// once. A user agent's own record is keyed by its agent id, which is its definition id, so that is the mark of one. A
107/// template's launches share the template's id but are each their own agent, keyed by their own launch ids, and no
108/// record is keyed by the template: they are a collision, and the lookup refuses them (as the migration that re-keys the
109/// registry treats them, `m0026_registry_agent_id_rekey.rs`).
110fn same_definition(records: &[NamedAgentRecord]) -> bool {
111 let first = &records[0].data.definition_id;
112 !first.is_empty()
113 && records.iter().all(|r| &r.data.definition_id == first)
114 && records.iter().any(|r| &r.data.instance_id == first)
115}
116
117/// The record to go by among several for one agent: the one whose instance holds a live lease, else the one launched
118/// last, else the newest made, else the lowest instance id (so the answer is the same on every call). `records` is not
119/// empty. One record is the answer as it stands: the lease store is opened (its folder made, its lock taken) only to
120/// choose between several, so the lookups that only read, history and memory among them, write nothing in the
121/// normal case.
122fn preferred(mut records: Vec<NamedAgentRecord>) -> NamedAgentRecord {
123 if records.len() == 1 {
124 return records.remove(0);
125 }
126 let leases = crate::registry::resolve_shared_registry_dir().and_then(|dir| crate::registry::LeaseStore::open(&dir).ok());
127 // Read once per record: each read takes the instance's lease lock.
128 let live = |r: &NamedAgentRecord| {
129 leases.as_ref().is_some_and(|l| l.live_holder_other_than(&r.data.instance_id, "").ok().flatten().is_some())
130 };
131 records
132 .into_iter()
133 .map(|r| (live(&r), r))
134 .max_by(|(live_a, a), (live_b, b)| {
135 live_a
136 .cmp(live_b)
137 .then(a.data.last_launched_at_ms.cmp(&b.data.last_launched_at_ms))
138 .then(a.data.created_at_ms.cmp(&b.data.created_at_ms))
139 .then(b.data.instance_id.cmp(&a.data.instance_id))
140 })
141 .map(|(_, r)| r)
142 .expect("records is not empty")
143}
144
145/// Reconstruct an agent's absolute working directory from its registry record.
146///
147/// `source_agents_base` joined with the relative `working_dir`, with legacy
148/// (v1/v2) records lacking a base falling back to the current channel's agents
149/// dir, matching the registry's own pre-P0.4 reconstruction rule.
150pub(crate) fn working_dir_from_record(rec: &NamedAgentRecord) -> Option<String> {
151 let base = rec
152 .data
153 .source_agents_base
154 .clone()
155 .or_else(|| std::env::var("AGENTMUX_AGENTS_DIR").ok())?;
156 Some(
157 std::path::Path::new(&base)
158 .join(&rec.data.working_dir)
159 .to_string_lossy()
160 .to_string(),
161 )
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167 use crate::registry::{NamedAgentRecordV1, Registry, MAX_SUPPORTED_SCHEMA};
168
169 // These tests drive the real registry through `resolve_shared_registry_dir`,
170 // which reads the process-global `AGENTMUX_HOME_OVERRIDE`. Left unset it
171 // would resolve the developer's own `~/.agentmux` and merge in every real
172 // agent on the machine. Uses the CRATE-WIDE lock every other consumer of
173 // this env var already takes — a module-local mutex does not stop the
174 // races these tests would otherwise have with the migration test modules.
175 use crate::test_support::ISOLATED_AUTH_ENV_LOCK as ENV_GUARD;
176
177 fn with_registry<T>(records: &[(&str, &str)], f: impl FnOnce() -> T) -> T {
178 let _guard = ENV_GUARD.lock().unwrap_or_else(|e| e.into_inner());
179 let home = tempfile::tempdir().unwrap();
180 std::env::set_var("AGENTMUX_HOME_OVERRIDE", home.path().to_str().unwrap());
181
182 let dir = crate::registry::resolve_shared_registry_dir().unwrap();
183 std::fs::create_dir_all(&dir).unwrap();
184 let registry = Registry::open(dir).unwrap();
185 for (instance_id, instance_name) in records {
186 registry.upsert(&record(instance_id, instance_name)).unwrap();
187 }
188
189 let out = f();
190 std::env::remove_var("AGENTMUX_HOME_OVERRIDE");
191 out
192 }
193
194 fn record(instance_id: &str, instance_name: &str) -> NamedAgentRecord {
195 NamedAgentRecord {
196 schema_version: MAX_SUPPORTED_SCHEMA,
197 data: NamedAgentRecordV1 {
198 instance_id: instance_id.to_string(),
199 instance_name: instance_name.to_string(),
200 definition_id: format!("def-{instance_id}"),
201 identity_id: None,
202 memory_id: None,
203 session_id: None,
204 working_dir: format!("{instance_id}-dir"),
205 source_agents_base: Some("/agents".to_string()),
206 created_at_ms: 1,
207 last_launched_at_ms: 1,
208 created_by_version: "test".to_string(),
209 last_launched_by_version: "test".to_string(),
210 },
211 }
212 }
213
214 #[test]
215 fn resolves_the_single_record_whose_name_normalizes_to_the_slug() {
216 with_registry(&[("i1", "AgentY")], || {
217 let found = find_active_record_by_slug("agenty").expect("one match resolves");
218 assert_eq!(found.data.instance_id, "i1");
219 });
220 }
221
222 // The module's whole reason for existing: the caller holds a routing slug
223 // while the record stores a display-cased `instance_name`, so both sides
224 // must go through `derive_slug`. Raw string equality here was a real bug
225 // (reagentx, PR #2428).
226 #[test]
227 fn matches_through_derive_slug_on_both_sides_not_raw_equality() {
228 with_registry(&[("i1", "AgentY")], || {
229 assert!(find_active_record_by_slug("AgentY").is_some(), "display casing");
230 assert!(find_active_record_by_slug("AGENTY").is_some(), "upper casing");
231 assert!(find_active_record_by_slug("agenty").is_some(), "already a slug");
232 });
233 }
234
235 #[test]
236 fn returns_none_when_nothing_matches() {
237 with_registry(&[("i1", "AgentY")], || {
238 assert!(find_active_record_by_slug("someone-else").is_none());
239 });
240 }
241
242 // The guard PR #3480 added and #3497 §2.5.3 flagged as never verified.
243 // `derive_slug` lowercases, so "AgentY" and "AGENTY" are two agents with
244 // one slug — nothing enforces a unique `instance_name` across records.
245 // Returning either one hands its `definition_id`/`working_dir` to a caller
246 // resolving conversation history or a memory directory, so the wrong pick
247 // discloses one agent's data to another.
248 #[test]
249 fn refuses_to_resolve_a_slug_two_active_records_share() {
250 with_registry(&[("i1", "AgentY"), ("i2", "AGENTY")], || {
251 assert!(
252 find_active_record_by_slug("agenty").is_none(),
253 "an ambiguous slug must resolve to nothing, never to an arbitrary winner"
254 );
255 });
256 }
257
258 // The disambiguated sibling stays correct exactly where the slug-only
259 // lookup must give up — otherwise refusing the collision would leave
260 // callers that DO know which agent they mean with no way through.
261 #[test]
262 fn definition_scoped_lookup_resolves_a_collision_the_slug_alone_cannot() {
263 with_registry(&[("i1", "AgentY"), ("i2", "AGENTY")], || {
264 let found = find_active_record_by_slug_and_definition("agenty", "def-i2")
265 .expect("definition_id disambiguates");
266 assert_eq!(found.data.instance_id, "i2");
267 assert!(
268 find_active_record_by_slug_and_definition("agenty", "def-nope").is_none(),
269 "an unmatched definition must not fall back to a slug-only guess"
270 );
271 });
272 }
273 /// Two records of one definition (an agent recorded twice across the move to definition-id keys): its old launch
274 /// record, `a-launch`, and the record keyed by the agent id, `def-manpo`. `launched` is each record's
275 /// `last_launched_at_ms`.
276 fn with_pair<T>(launched: [i64; 2], f: impl FnOnce(&Registry) -> T) -> T {
277 with_registry(&[], || {
278 let registry = Registry::open(crate::registry::resolve_shared_registry_dir().unwrap()).unwrap();
279 for (i, at) in launched.into_iter().enumerate() {
280 let id = if i == 0 { "a-launch" } else { "def-manpo" };
281 let mut r = record(id, "Manpo");
282 r.data.definition_id = "def-manpo".to_string();
283 r.data.last_launched_at_ms = at;
284 registry.upsert(&r).unwrap();
285 }
286 f(®istry)
287 })
288 }
289
290 // The upgrade to 0.60.22 logged "registry slug collision ... matches 2" for an agent that was one: its old record
291 // and its new one named the same definition.
292 #[test]
293 fn two_records_of_one_definition_are_one_agent_and_the_one_launched_last_answers() {
294 with_pair([100, 200], |_| {
295 let found = find_active_record_by_slug("manpo").expect("one agent, not a collision");
296 assert_eq!(found.data.instance_id, "def-manpo");
297 let scoped = find_active_record_by_slug_and_definition("manpo", "def-manpo").unwrap();
298 assert_eq!(scoped.data.instance_id, "def-manpo", "the definition-scoped lookup picks the same record");
299 });
300 with_pair([200, 100], |_| {
301 assert_eq!(find_active_record_by_slug("manpo").unwrap().data.instance_id, "a-launch");
302 });
303 with_pair([100, 100], |_| {
304 assert_eq!(find_active_record_by_slug("manpo").unwrap().data.instance_id, "a-launch", "a tie is decided the same way every time");
305 });
306 }
307
308 // A lookup that finds one record only reads: opening the lease store makes its folder and takes a lock file in the
309 // registry shared by every instance, on every history and memory lookup (#46577).
310 #[test]
311 fn one_matching_record_is_returned_without_opening_the_lease_store() {
312 with_registry(&[("i1", "AgentY")], || {
313 let leases = crate::registry::resolve_shared_registry_dir().unwrap().join("leases");
314 assert!(!leases.exists(), "nothing has opened the lease store yet");
315 assert_eq!(find_active_record_by_slug("agenty").unwrap().data.instance_id, "i1");
316 assert_eq!(find_active_record_by_slug_and_definition("agenty", "def-i1").unwrap().data.instance_id, "i1");
317 assert!(!leases.exists(), "a single match leaves no lease folder or lock file behind");
318 });
319 }
320
321 #[test]
322 fn the_record_whose_instance_holds_a_live_lease_answers_before_the_one_launched_last() {
323 with_pair([100, 200], |registry| {
324 let leases = crate::registry::LeaseStore::open(registry.root()).unwrap();
325 let boot: std::sync::Arc<str> = std::sync::Arc::from("boot-live");
326 let _held = leases.claim("a-launch", &boot, "block-1", None).unwrap();
327 assert_eq!(find_active_record_by_slug("manpo").unwrap().data.instance_id, "a-launch", "the live one, though the other was launched later");
328 });
329 }
330
331 // On a channel that has not upgraded, two launches of one template share the template's id as their definition and
332 // each is its own agent, keyed by its launch id; no record is keyed by the template. Collapsing them would answer
333 // for one agent with the other's memory or history (#46578).
334 #[test]
335 fn two_launches_of_one_template_are_still_a_collision() {
336 with_registry(&[("launch-1", "Manpo"), ("launch-2", "MANPO")], || {
337 let records = crate::registry::Registry::open(crate::registry::resolve_shared_registry_dir().unwrap()).unwrap();
338 for id in ["launch-1", "launch-2"] {
339 let mut r = record(id, if id == "launch-1" { "Manpo" } else { "MANPO" });
340 r.data.definition_id = "template-9".to_string();
341 records.upsert(&r).unwrap();
342 }
343 assert!(find_active_record_by_slug("manpo").is_none(), "two template launches are two agents: refused");
344 });
345 }
346
347 // Different definitions are different agents: collapsing them would hand one agent's history to another.
348 #[test]
349 fn records_of_different_definitions_are_still_a_collision() {
350 with_registry(&[("i1", "Manpo"), ("i2", "MANPO")], || {
351 assert!(find_active_record_by_slug("manpo").is_none());
352 });
353 }
354}