Skip to main content

agentmux_srv_core/backend/
agent_resolve.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The one place a human-readable agent slug becomes a canonical
5//! `db_agents.id`.
6//!
7//! **Why this exists.** `AGENTMUX_AGENT_ID` is a model-and-human-chosen slug,
8//! not a key: `db_agents.slug` carries no `UNIQUE` constraint, deliberately
9//! (`storage::migrations` declines the index because template launches copy
10//! their template's slug). Treating it as a primary key has produced the same
11//! defect four times — Codex P1 on #2901, reagentx on #2428, reagentx on
12//! #3480, and `instance_get_by_slug` itself on #3500 — each found and fixed
13//! separately because the resolution logic existed in three places that drifted
14//! apart.
15//!
16//! Phase 0 of `SPEC_CANONICAL_AGENT_ID_MIGRATION_2026_09_21.md`. Later phases
17//! call this instead of inventing a fourth resolver.
18//!
19//! **Resolve once, at the trust boundary.** Callers pass the slug they already
20//! have — MCP arguments, audit-log display and agent-facing docs keep the
21//! readable name. Everything downstream of this function uses the id.
22
23use crate::backend::agent_registry_lookup::find_active_record_by_slug;
24use crate::backend::storage::store::Store;
25
26/// Resolve `slug_or_id` to a canonical `db_agents.id`.
27///
28/// Tried in order, first hit wins:
29///
30/// 1. **`db_agents` by slug** — the persisted row. Fails closed when two rows
31///    share the slug (#3500), so an ambiguous slug falls through rather than
32///    resolving to an arbitrary winner.
33/// 2. **`db_agents` by id** — idempotent passthrough. Phases land in sequence,
34///    so a caller may hold a value that is already resolved; requiring each one
35///    to know which it has would defeat the point of a shared resolver.
36/// 3. **The named-agent registry** — a live agent with no `db_agents` row yet,
37///    which is the common case (launching an agent does not create one). Also
38///    fails closed on a colliding slug (#3480).
39///
40/// `Err` means "no agent" *or* "more than one agent". They are deliberately
41/// not distinguished yet: both of the underlying lookups already collapse
42/// ambiguity into "not found", and surfacing `Ambiguous` separately is a
43/// user-facing error-message decision the spec (§4) flags as needing UX input
44/// rather than a choice to make here. Nothing about this function's shape
45/// prevents adding it later.
46pub fn resolve_agent_id(store: &Store, slug_or_id: &str) -> Result<String, String> {
47    if slug_or_id.is_empty() {
48        return Err("cannot resolve an empty agent id".to_string());
49    }
50
51    // A store error is reported, not swallowed. `resolve_agent_uuid` already
52    // propagated it; `resolve_agent_definition_id` silently treated it as "not
53    // this tier" and tried the registry, which turns a database fault into a
54    // confident "unknown agent". The stricter of the two behaviors wins.
55    match store.instance_get_by_slug(slug_or_id) {
56        // `map_instance_row` populates `definition_id` from the same column as
57        // `id` — in the consolidated `db_agents` table they are the same value,
58        // which is why the three resolvers this replaces could return either
59        // and still agree here.
60        Ok(Some(instance)) if !instance.id.is_empty() => return Ok(instance.id),
61        Ok(_) => {}
62        Err(e) => return Err(format!("resolve_agent_id: store: {e}")),
63    }
64
65    match store.agent_def_get(slug_or_id) {
66        Ok(Some(_)) => return Ok(slug_or_id.to_string()),
67        Ok(None) => {}
68        Err(e) => return Err(format!("resolve_agent_id: store: {e}")),
69    }
70
71    if let Some(rec) = find_active_record_by_slug(slug_or_id) {
72        if !rec.data.definition_id.is_empty() {
73            return Ok(rec.data.definition_id);
74        }
75    }
76
77    Err(format!(
78        "unknown agent '{slug_or_id}': no agent row, definition or active registry record resolves it"
79    ))
80}
81
82/// Process-wide fallback counters, keyed by call site (spec §9.2). In-memory
83/// only, same lifecycle as the reactive handler's audit log; a phase's exit
84/// criterion is read from these, not assumed.
85static UID_FALLBACK_COUNTS: std::sync::OnceLock<
86    std::sync::Mutex<std::collections::HashMap<&'static str, u64>>,
87> = std::sync::OnceLock::new();
88
89/// The agent UID (`db_agents.id`) for the agent shown on `block_id`, if it
90/// has a row — the same block → row resolution `build_persistent_spawn_env`
91/// uses, without minting a token. For the frontend presence path
92/// (`handle_reactive_register`), which does not trust the name it is sent
93/// (spec §0.1) and resolves identity by block instead. A synchronous store
94/// read: call it on `spawn_blocking` from async handlers.
95pub fn uid_for_block(store: &Store, block_id: &str) -> Option<String> {
96    match store.instance_get_active_for_block(block_id) {
97        Ok(Some(instance)) if !instance.id.trim().is_empty() => Some(instance.id),
98        Ok(_) => None,
99        Err(e) => {
100            tracing::warn!(block_id, error = %e, "uid_for_block: store read failed — registering without a uid");
101            None
102        }
103    }
104}
105
106/// Bump the counter for `site` (spec §9.2). Shared by the resolver's
107/// dual-write misses and, since identity M2, the registry's own
108/// registration/delivery/lookup counters — one snapshot for all of them.
109pub fn record_uid_fallback(site: &'static str) {
110    let counts = UID_FALLBACK_COUNTS.get_or_init(Default::default);
111    let mut guard = counts.lock().unwrap_or_else(|e| e.into_inner());
112    *guard.entry(site).or_insert(0) += 1;
113}
114
115/// Snapshot of every fallback counter, for the exit-criterion check (spec
116/// §9.2). Sorted by site so output is stable.
117pub fn uid_fallback_counts() -> Vec<(&'static str, u64)> {
118    let counts = UID_FALLBACK_COUNTS.get_or_init(Default::default);
119    let guard = counts.lock().unwrap_or_else(|e| e.into_inner());
120    let mut out: Vec<(&'static str, u64)> = guard.iter().map(|(k, v)| (*k, *v)).collect();
121    out.sort();
122    out
123}
124
125/// Identity M4d-3's own gate signal (spec §6.5.10, "Gating per step"): a
126/// config written with an `AGENTMUX_AGENT_ID` that is not exactly its row's
127/// slug. Such an agent signs under a name its row doesn't have (a
128/// collision-suffixed backfill, a #3573 stub), so the keys
129/// `/agentmux/agents/self/keys` serves are not its keys, and its config must
130/// keep carrying them. Counting only: nothing here changes what is written.
131/// `row_slug` is `None` when no single row could be matched.
132pub(crate) fn record_config_id_drift(site: &'static str, written_id: &str, row_slug: Option<&str>) {
133    if row_slug.map(str::trim) != Some(written_id) {
134        record_uid_fallback(site);
135    }
136}
137
138/// The one row whose slug equals `name` folded (trimmed, case-insensitive),
139/// or `None` when none or several do. `WriteAgentConfig` has no `Caller` and
140/// names its agent only by the id in the content.
141pub(crate) fn single_row_slug_folded(mstore: &Store, name: &str) -> Option<String> {
142    let mut slugs = mstore.agent_slugs_folded(name).ok()?;
143    (slugs.len() == 1).then(|| slugs.remove(0))
144}
145
146/// [`resolve_agent_id`], and where that finds nothing, an agent named as a person writes it: its display name or
147/// its slug in any letter case, when exactly one agent on this machine has it. A name two agents share is refused,
148/// with their ids, not guessed. `Agents transcript` reads names this way; `Agents watch` and the lifecycle actions
149/// refused a display name ("Korp" for the slug "korp") and wanted the uid.
150pub fn resolve_agent_named(store: &Store, named: &str) -> Result<String, String> {
151    let err = match resolve_agent_id(store, named) {
152        Ok(id) => return Ok(id),
153        Err(e) => e,
154    };
155    let defs = store.agent_def_list().map_err(|e| format!("resolve_agent_named: store: {e}"))?;
156    let same: Vec<&crate::backend::storage::agents::AgentDefinition> = defs
157        .iter()
158        .filter(|d| d.is_seeded != 1 && (d.name.eq_ignore_ascii_case(named) || d.slug.eq_ignore_ascii_case(named)))
159        .collect();
160    match same.as_slice() {
161        [one] => Ok(one.id.clone()),
162        [] => Err(format!("{err}; give an agent's id or slug (Agents list)")),
163        many => {
164            let ids: Vec<&str> = many.iter().map(|d| d.id.as_str()).collect();
165            Err(format!("more than one agent is named '{named}' (ids {}): give an id (Agents list)", ids.join(", ")))
166        }
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173    use crate::backend::storage::agents::{test_agent_def, AgentInstance};
174
175    // Tier 3 reads the global registry via `resolve_shared_registry_dir`, which
176    // resolves the developer's real `~/.agentmux` unless `AGENTMUX_HOME_OVERRIDE`
177    // is set — so a not-found assertion would depend on whichever agents happen
178    // to be running on the machine. Every test here runs against an isolated
179    // empty home, under the crate-wide lock that env var's other consumers take.
180    use crate::test_support::ISOLATED_AUTH_ENV_LOCK as ENV_GUARD;
181
182    fn with_isolated_home<T>(f: impl FnOnce() -> T) -> T {
183        let _guard = ENV_GUARD.lock().unwrap_or_else(|e| e.into_inner());
184        let home = tempfile::tempdir().unwrap();
185        std::env::set_var("AGENTMUX_HOME_OVERRIDE", home.path().to_str().unwrap());
186        let out = f();
187        std::env::remove_var("AGENTMUX_HOME_OVERRIDE");
188        out
189    }
190
191    fn instance(id: &str, definition_id: &str, name: &str) -> AgentInstance {
192        AgentInstance {
193            status: "init".to_string(),
194            instance_name: name.to_string(),
195            ..crate::backend::storage::agents::test_agent_instance(id, definition_id, "", 1)
196        }
197    }
198
199    #[test]
200    fn resolves_a_slug_to_the_agents_canonical_id() {
201        with_isolated_home(|| {
202            let store = Store::open_in_memory().unwrap();
203            let mut def = test_agent_def("def-1", "Solo Agent", "claude", "agent", 1, "");
204            def.slug = "solo".to_string();
205            store.agent_def_insert(&mut def).unwrap();
206
207            assert_eq!(resolve_agent_id(&store, "solo").unwrap(), "def-1");
208        });
209    }
210
211    // Idempotency (spec §4): phases land in sequence, so a caller may already
212    // hold a resolved id. Tier 1 misses here because the id is not the slug —
213    // it is tier 2 that answers.
214    #[test]
215    fn passes_through_an_id_that_is_already_canonical() {
216        with_isolated_home(|| {
217            let store = Store::open_in_memory().unwrap();
218            let mut def = test_agent_def("def-1", "Solo Agent", "claude", "agent", 1, "");
219            def.slug = "solo".to_string();
220            store.agent_def_insert(&mut def).unwrap();
221
222            assert_eq!(resolve_agent_id(&store, "def-1").unwrap(), "def-1");
223        });
224    }
225
226    #[test]
227    fn errors_for_an_agent_that_exists_nowhere() {
228        with_isolated_home(|| {
229            let store = Store::open_in_memory().unwrap();
230            assert!(resolve_agent_id(&store, "nobody").is_err());
231        });
232    }
233
234    #[test]
235    fn a_display_name_in_any_case_resolves_when_one_agent_has_it() {
236        with_isolated_home(|| {
237            let store = Store::open_in_memory().unwrap();
238            let mut def = test_agent_def("def-1", "Solo Agent", "claude", "agent", 1, "");
239            def.slug = "solo".to_string();
240            store.agent_def_insert(&mut def).unwrap();
241            assert!(resolve_agent_id(&store, "solo agent").is_err(), "the strict resolver wants a slug or an id");
242            assert_eq!(resolve_agent_named(&store, "solo agent").unwrap(), "def-1");
243            assert_eq!(resolve_agent_named(&store, "SOLO").unwrap(), "def-1");
244            assert_eq!(resolve_agent_named(&store, "def-1").unwrap(), "def-1");
245            assert!(resolve_agent_named(&store, "nobody").unwrap_err().contains("Agents list"));
246        });
247    }
248
249    #[test]
250    fn a_display_name_two_agents_share_is_refused_with_their_ids() {
251        with_isolated_home(|| {
252            let store = Store::open_in_memory().unwrap();
253            for id in ["def-a", "def-b"] {
254                let mut def = test_agent_def(id, "Twin", "claude", "agent", 1, "");
255                store.agent_def_insert(&mut def).unwrap();
256            }
257            let err = resolve_agent_named(&store, "twin").unwrap_err();
258            assert!(err.contains("more than one agent") && err.contains("def-a") && err.contains("def-b"), "{err}");
259        });
260    }
261
262    #[test]
263    fn errors_on_an_empty_id_without_touching_the_store() {
264        with_isolated_home(|| {
265            let store = Store::open_in_memory().unwrap();
266            assert!(resolve_agent_id(&store, "").is_err());
267        });
268    }
269
270    // The §7 case the spec calls out as having no coverage anywhere.
271    //
272    // The duplicate is forced rather than launched: both write paths
273    // suffix-resolve since #3497 §4, so two `instance_create` calls no longer
274    // collide. Forcing it one row at a time keeps the assertion honest — the
275    // single-row case must RESOLVE, so the refusal below is caused by the
276    // second row and not by the slug matching nothing.
277    //
278    // Tier 1 fails closed (#3500), tier 2 misses because a slug is not an id,
279    // tier 3 finds nothing in the isolated registry — so the whole resolver
280    // refuses rather than naming an arbitrary winner.
281    #[test]
282    fn refuses_a_slug_two_rows_share() {
283        with_isolated_home(|| {
284            let store = Store::open_in_memory().unwrap();
285            let mut tmpl = test_agent_def("tmpl-1", "Shared Template", "claude", "agent", 1, "");
286            tmpl.slug = "shared-template".to_string();
287            tmpl.is_seeded = 1;
288            store.agent_def_insert(&mut tmpl).unwrap();
289
290            store.instance_create(&instance("launch-a", "tmpl-1", "Launch A")).unwrap();
291            store.instance_create(&instance("launch-b", "tmpl-1", "Launch B")).unwrap();
292
293            // Both write paths suffix-resolve now (§4), so force the duplicate.
294            // One row first: resolving it proves the fixture is live, so the
295            // refusal below is the second row's doing and not "nothing matched".
296            store.test_force_slug("launch-a", "collide-me").unwrap();
297            assert_eq!(
298                resolve_agent_id(&store, "collide-me").unwrap(),
299                "launch-a",
300                "one row with the slug must resolve — otherwise the check below is vacuous"
301            );
302
303            store.test_force_slug("launch-b", "collide-me").unwrap();
304            assert!(
305                resolve_agent_id(&store, "collide-me").is_err(),
306                "adding a second row with the same slug must flip resolve to refusal"
307            );
308        });
309    }
310
311    /// The §9.2 counters are per site and read back sorted. Site names are
312    /// unique to this test: the counters are process-wide and tests run in
313    /// parallel.
314    #[test]
315    fn fallback_counters_are_recorded_per_site() {
316        let count = |site: &str| {
317            uid_fallback_counts()
318                .into_iter()
319                .find(|(s, _)| *s == site)
320                .map_or(0, |(_, n)| n)
321        };
322        let before = count("test.counters.b");
323        record_uid_fallback("test.counters.b");
324        record_uid_fallback("test.counters.b");
325        record_uid_fallback("test.counters.a");
326        assert_eq!(count("test.counters.b"), before + 2);
327        let sites: Vec<&str> = uid_fallback_counts().into_iter().map(|(s, _)| s).collect();
328        let mut sorted = sites.clone();
329        sorted.sort();
330        assert_eq!(sites, sorted);
331    }
332
333    fn store_with_slug(uid: &str, slug: &str) -> Store {
334        let store = Store::open_in_memory().unwrap();
335        let mut def = test_agent_def(uid, slug, "claude", "agent", agentmux_common::time::now_ms(), "");
336        def.slug = slug.to_string();
337        store.agent_def_insert(&mut def).unwrap();
338        store
339    }
340
341    #[test]
342    fn a_config_s_id_matches_one_row_only_when_one_slug_folds_to_it() {
343        let store = store_with_slug("uid-a", "Aria");
344        assert_eq!(single_row_slug_folded(&store, "aria").as_deref(), Some("Aria"));
345        let mut def = test_agent_def("uid-b", "ä", "claude", "agent", 1, "");
346        def.slug = "Ä".into();
347        store.agent_def_insert(&mut def).unwrap();
348        let mut def = test_agent_def("uid-c", "ä", "claude", "agent", 1, "");
349        def.slug = "ä".into();
350        store.agent_def_insert(&mut def).unwrap();
351        assert_eq!(single_row_slug_folded(&store, "ä"), None, "Ä and ä fold together: ambiguous");
352        assert_eq!(single_row_slug_folded(&store, "nobody"), None);
353    }
354
355    #[test]
356    fn drift_is_counted_when_the_written_id_is_not_exactly_the_row_s_slug() {
357        let count = || {
358            uid_fallback_counts()
359                .into_iter()
360                .find(|(site, _)| *site == "m4d.config_id_drift.test")
361                .map_or(0, |(_, n)| n)
362        };
363        let before = count();
364        record_config_id_drift("m4d.config_id_drift.test", "aria", Some("aria"));
365        assert_eq!(count(), before, "exact match: no drift");
366        record_config_id_drift("m4d.config_id_drift.test", "aria", Some("aria-2"));
367        record_config_id_drift("m4d.config_id_drift.test", "Aria", Some("aria"));
368        record_config_id_drift("m4d.config_id_drift.test", "aria", None);
369        assert_eq!(count(), before + 3);
370    }
371}