Skip to main content

agentmux_srv_core/backend/
name_resolution.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The one place a typed agent name is interpreted (identity M3,
5//! `docs/specs/SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md` §5).
6//!
7//! **Callable only from surfaces where a human or a model typed the name** —
8//! today the `POST /agentmux/agents/resolve` endpoint the MCP server calls
9//! before it enqueues work or schedules a cron job. No internal code path may
10//! call this: `scripts/check-name-resolver-callers.sh` is the CI grep gate
11//! that enforces it (§9.3), so §2 rule 1 is mechanical rather than a
12//! convention that erodes.
13//!
14//! **Ambiguity is surfaced, never guessed** (§5.2). A name held by two agents
15//! is returned as `Ambiguous` with enough about each candidate for a model to
16//! retry by UID and for a human to act on. This is deliberately the opposite
17//! of `agent_resolve::resolve_agent_id`, which collapses "several" into
18//! "none" because its callers are internal and have nobody to ask.
19//!
20//! **What is consulted, in order.** (1) A typed value that *is* a UID. (2) The
21//! live registry, by name — every registered block whose display or stable
22//! name matches, with its UID when it has one. (3) The store, by slug and by
23//! display name (`name`, `instance_name`, case-insensitively) over
24//! non-template, non-hidden rows — the agents that exist but are not running
25//! right now — and, when none of those match, by a slug an agent was renamed
26//! from (`Store::agents_matching_name`; `SPEC_FORK_SLUG_MIGRATION_2026_10_22.md`
27//! Phase 1), so a task or cron job addressed to an old id still reaches its
28//! agent. Live and stored candidates that share a UID are one candidate.
29//!
30//! Spec §1.1 measured that a display name never resolves through the
31//! exact-case slug tier. That finding is about a resolver that has to *pick*;
32//! this one *lists*, so it can afford to match display names: a single match
33//! resolves, a collision is refused with the candidates, and nothing is ever
34//! misrouted.
35
36use serde::Serialize;
37
38use crate::backend::reactive::handler::{LookupOutcome, ReactiveHandler};
39use crate::backend::storage::store::Store;
40
41/// One agent that a typed name could mean.
42#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
43pub struct AgentCandidate {
44    /// `db_agents.id` when the agent has a row; `None` for a live block with
45    /// no row (a quick-launch pane, a PTY shell) — addressable by name only.
46    pub uid: Option<String>,
47    /// What a human would recognise it by.
48    pub name: String,
49    #[serde(skip_serializing_if = "String::is_empty")]
50    pub slug: String,
51    /// Set when the candidate is registered right now.
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub block_id: Option<String>,
54    pub live: bool,
55}
56
57/// The answer to "which agent did they mean?" (§5.1).
58#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
59#[serde(tag = "resolution", rename_all = "snake_case")]
60pub enum NameResolution {
61    /// Exactly one agent matches, and it has a UID.
62    One {
63        uid: String,
64        candidate: AgentCandidate,
65    },
66    /// Several do. Carries enough to ask the human which.
67    Ambiguous {
68        candidates: Vec<AgentCandidate>,
69    },
70    /// Exactly one agent matches, but it has no UID (no `db_agents` row):
71    /// reachable by name, not storable as an identity. Not in the spec's
72    /// three-variant enum — added because such agents exist (M0's finding)
73    /// and collapsing them into `None` would tell the caller the agent does
74    /// not exist when it does.
75    Unidentified {
76        candidate: AgentCandidate,
77    },
78    None,
79}
80
81/// Resolve `typed` to a UID, or to the reasons it cannot be resolved.
82///
83/// `registry` is the live in-memory registry (`get_global_handler()` in
84/// production; a fresh `ReactiveHandler` in tests). `store` is the
85/// per-channel object store that holds `db_agents`.
86///
87/// `Err` means the store could not be read, and the caller must refuse
88/// rather than proceed: `None` would send the bare name on, and a
89/// same-named live agent could then take work or a cron fire meant for a
90/// stored agent the fault hid (Codex P1 on #3563).
91pub fn resolve_name_to_uid(
92    store: &Store,
93    registry: &ReactiveHandler,
94    typed: &str,
95) -> Result<NameResolution, String> {
96    let typed = typed.trim();
97    if typed.is_empty() {
98        return Ok(NameResolution::None);
99    }
100
101    // (1) The typed value is itself a UID.
102    let as_uid = store
103        .agent_def_get_strict(typed)
104        .map_err(|e| store_fault(typed, e))?;
105    if let Some(def) = as_uid {
106        if def.is_seeded == 0 {
107            let candidate = AgentCandidate {
108                uid: Some(def.id.clone()),
109                name: if def.name.is_empty() {
110                    def.slug.clone()
111                } else {
112                    def.name.clone()
113                },
114                slug: def.slug.clone(),
115                block_id: registry.get_agent(typed).map(|r| r.block_id),
116                live: registry.get_agent(typed).is_some(),
117            };
118            return Ok(NameResolution::One {
119                uid: def.id,
120                candidate,
121            });
122        }
123    }
124
125    let mut candidates: Vec<AgentCandidate> = Vec::new();
126
127    // (2) Live registry, by name (a former slug too: this picks a target).
128    let live: Vec<crate::backend::reactive::AgentRegistration> =
129        match registry.lookup_delivery_target(typed) {
130            LookupOutcome::One(reg) => vec![reg],
131            LookupOutcome::Ambiguous(regs) => regs,
132            LookupOutcome::NotFound => Vec::new(),
133        };
134    for reg in live {
135        // A registration made before its row existed carries no UID (spec
136        // Q1); take the one on its block's row, so the agent and its own row
137        // are one candidate — not an ambiguity with itself (review on #3563).
138        // Identity by block, not by name.
139        let uid = reg
140            .uid
141            .clone()
142            .or_else(|| crate::backend::agent_resolve::uid_for_block(store, &reg.block_id));
143        candidates.push(AgentCandidate {
144            uid,
145            name: reg.agent_id.clone(),
146            slug: String::new(),
147            block_id: Some(reg.block_id.clone()),
148            live: true,
149        });
150    }
151
152    // (3) The store, by slug and by display name.
153    let rows = store
154        .agents_matching_name(typed)
155        .map_err(|e| store_fault(typed, e))?;
156    for row in rows {
157        if let Some(existing) = candidates
158            .iter_mut()
159            .find(|c| c.uid.as_deref() == Some(row.id.as_str()))
160        {
161            // Same agent, seen live already: enrich, don't duplicate.
162            if existing.slug.is_empty() {
163                existing.slug = row.slug.clone();
164            }
165            continue;
166        }
167        candidates.push(AgentCandidate {
168            uid: Some(row.id),
169            name: if row.instance_name.is_empty() {
170                row.name
171            } else {
172                row.instance_name
173            },
174            slug: row.slug,
175            block_id: None,
176            live: false,
177        });
178    }
179
180    // (4) Nothing here by that name: every channel's definitions, by slug,
181    // by the route form of the title an agent goes by ("Naki-2" for
182    // "Naki #2", the form agents sign with), or by a former name. An agent
183    // defined or running in another channel on this computer has no row in
184    // this channel's store until it is opened here, and the task queue is
185    // shared by every channel, so a task filed for it by name alone could
186    // never be claimed (#1257).
187    if candidates.is_empty() {
188        for def in shared_defs_answering_to(store, typed).map_err(|e| store_fault(typed, e))? {
189            candidates.push(AgentCandidate {
190                uid: Some(def.id.clone()),
191                name: current_title(&def).to_string(),
192                slug: def.slug,
193                block_id: None,
194                live: false,
195            });
196        }
197    }
198
199    match candidates.len() {
200        // Only the outcomes that leave a row on the name path are counted
201        // (§9.2 reads these as "must reach zero"); `One`, `None` and
202        // `Ambiguous` are answers, not fallbacks.
203        0 => Ok(NameResolution::None),
204        1 => {
205            let candidate = candidates.remove(0);
206            match candidate.uid.clone() {
207                Some(uid) => Ok(NameResolution::One { uid, candidate }),
208                None => {
209                    record("resolve.unidentified");
210                    Ok(NameResolution::Unidentified { candidate })
211                }
212            }
213        }
214        _ => Ok(NameResolution::Ambiguous { candidates }),
215    }
216}
217
218/// How many ids a refusal offers.
219const MOST_SUGGESTIONS: usize = 3;
220
221/// Edits (insert, delete, change one letter, swap two neighbours) between two short strings.
222fn edit_distance(a: &str, b: &str) -> usize {
223    let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
224    let mut d = vec![vec![0usize; b.len() + 1]; a.len() + 1];
225    for (i, row) in d.iter_mut().enumerate() {
226        row[0] = i;
227    }
228    for j in 0..=b.len() {
229        d[0][j] = j;
230    }
231    for i in 1..=a.len() {
232        for j in 1..=b.len() {
233            let same = usize::from(a[i - 1] != b[j - 1]);
234            d[i][j] = (d[i - 1][j - 1] + same).min(d[i - 1][j] + 1).min(d[i][j - 1] + 1);
235            if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
236                d[i][j] = d[i][j].min(d[i - 2][j - 2] + 1);
237            }
238        }
239    }
240    d[a.len()][b.len()]
241}
242
243/// Which of `ids` a typed name nobody answers to most likely meant, best first, at most three: the id it
244/// starts with (an agent's workspace folder is its id and a suffix, "agent2-0630f" for `agent2`), the id that
245/// starts with it (a name cut short), or one a typo or two away. Case and a leading `@` do not count.
246pub fn closest_ids(typed: &str, ids: &[String]) -> Vec<String> {
247    let typed = typed.trim().trim_start_matches('@').to_lowercase();
248    if typed.len() < 2 {
249        return Vec::new();
250    }
251    let mut scored: Vec<(usize, &String)> = ids
252        .iter()
253        .filter_map(|id| {
254            let low = id.to_lowercase();
255            let rank = if low == typed {
256                0
257            } else if typed.starts_with(&format!("{low}-")) || typed.starts_with(&format!("{low}_")) {
258                1
259            } else if low.starts_with(&typed) && typed.len() >= 3 {
260                2
261            } else {
262                let d = edit_distance(&typed, &low);
263                if d <= (typed.len().min(low.len()) / 4).max(1) { 2 + d } else { return None }
264            };
265            Some((rank, id))
266        })
267        .collect();
268    scored.sort();
269    scored.dedup_by(|a, b| a.1 == b.1);
270    scored.into_iter().take(MOST_SUGGESTIONS).map(|(_, id)| id.clone()).collect()
271}
272
273/// The ids (the names an agent is addressed by) of the agents this computer knows, running or not: the ones a
274/// name that nobody answers to is offered back from. Only agents a name may mean, as `agents_matching_name` holds.
275pub fn known_agent_ids(store: &Store, registry: &ReactiveHandler) -> Vec<String> {
276    let mut ids: Vec<String> = store
277        .agent_def_list()
278        .map(|defs| defs.into_iter().filter(|d| d.is_seeded == 0 && d.user_hidden == 0).map(|d| d.slug).collect())
279        .unwrap_or_default();
280    ids.extend(registry.list_agents().into_iter().map(|r| r.agent_id));
281    ids.retain(|id| !id.is_empty());
282    ids.sort();
283    ids.dedup();
284    ids
285}
286
287/// The definitions, in any channel, that `typed` names: the one whose slug
288/// it is, else every one whose current title routes to it, else the one it
289/// is a former name of. Only agents a name may mean: never a template, never
290/// one the user forgot (`user_hidden`), as `agents_matching_name` holds; they
291/// are left out before matching, so a template's slug can't shadow an
292/// agent's title.
293fn shared_defs_answering_to(
294    store: &Store,
295    typed: &str,
296) -> Result<Vec<crate::backend::storage::agents::AgentDefinition>, crate::backend::storage::StoreError> {
297    let fold = |s: &str| s.trim().to_lowercase();
298    let target = fold(typed);
299    let route = fold(&agentmux_common::slug::agent_route_name(typed));
300    let defs: Vec<_> = store
301        .agent_def_list()?
302        .into_iter()
303        .filter(|d| d.is_seeded == 0 && d.user_hidden == 0)
304        .collect();
305    if let Some(def) = defs.iter().find(|d| fold(&d.slug) == target) {
306        return Ok(vec![def.clone()]);
307    }
308    let by_title: Vec<_> = defs
309        .iter()
310        .filter(|d| fold(&agentmux_common::slug::agent_route_name(current_title(d))) == route)
311        .cloned()
312        .collect();
313    if !by_title.is_empty() {
314        return Ok(by_title);
315    }
316    let Some(owner) = store.former_name_owner(typed)? else {
317        return Ok(Vec::new());
318    };
319    Ok(defs.into_iter().filter(|d| d.id == owner.uid).collect())
320}
321
322/// The title an agent goes by now: a fork's is its `branch_label`, which a
323/// rename updates while `name` keeps the title it was forked with; a root's
324/// is its `name`.
325fn current_title(d: &crate::backend::storage::agents::AgentDefinition) -> &str {
326    if d.parent_id.trim().is_empty() || d.branch_label.trim().is_empty() {
327        if d.name.is_empty() { &d.slug } else { &d.name }
328    } else {
329        &d.branch_label
330    }
331}
332
333fn store_fault(typed: &str, e: impl std::fmt::Display) -> String {
334    tracing::warn!(name = %typed, error = %e, "resolve_name_to_uid: store read failed — refusing to resolve");
335    record("resolve.store_error");
336    format!("agent store unavailable: {e}")
337}
338
339fn record(site: &'static str) {
340    crate::backend::agent_resolve::record_uid_fallback(site);
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346    use crate::backend::storage::agents::test_agent_def;
347
348    const UID_Y: &str = "4f3c0000-0000-4000-8000-000000000a91";
349    const UID_UP: &str = "9b2e0000-0000-4000-8000-0000000007d4";
350
351    fn store_with(rows: &[(&str, &str, &str)]) -> Store {
352        let store = Store::open_in_memory().unwrap();
353        for (id, name, slug) in rows {
354            let mut def = test_agent_def(id, name, "claude", "agent", 1, "");
355            def.slug = slug.to_string();
356            store.agent_def_insert(&mut def).unwrap();
357        }
358        store
359    }
360
361    fn registry() -> ReactiveHandler {
362        ReactiveHandler::new()
363    }
364
365    #[test]
366    fn a_name_nobody_answers_to_is_offered_the_closest_ids() {
367        let ids: Vec<String> = ["agent2", "agent20", "agenty", "wren", "loap-3", "Naki-2"].iter().map(|s| s.to_string()).collect();
368        // The workspace folder's form: the id and a suffix.
369        assert_eq!(closest_ids("agent2-0630f", &ids), ["agent2"]);
370        // Case and a leading @.
371        assert_eq!(closest_ids("@WREN", &ids), ["wren"]);
372        // A name cut short, and a typo.
373        assert_eq!(closest_ids("loap", &ids), ["loap-3"]);
374        assert_eq!(closest_ids("wern", &ids), ["wren"]);
375        assert_eq!(closest_ids("agentx", &ids), ["agent2", "agenty"]);
376        // Nobody is close: no suggestion rather than a bad one.
377        assert!(closest_ids("zzzzzz", &ids).is_empty());
378        assert!(closest_ids("a", &ids).is_empty());
379    }
380
381    #[test]
382    fn the_known_ids_feed_the_suggestions() {
383        let store = store_with(&[(UID_Y, "AgentY", "agenty")]);
384        let reg = registry();
385        let ids = known_agent_ids(&store, &reg);
386        assert!(ids.contains(&"agenty".to_string()));
387        assert_eq!(closest_ids("agenty-77aa1", &ids), ["agenty"]);
388    }
389
390    #[test]
391    fn a_uid_resolves_to_itself() {
392        let store = store_with(&[(UID_Y, "AgentY", "agenty")]);
393        let r = resolve_name_to_uid(&store, &registry(), UID_Y).unwrap();
394        assert!(
395            matches!(r, NameResolution::One { ref uid, .. } if uid == UID_Y),
396            "{r:?}"
397        );
398    }
399
400    /// The §1.1 finding, inverted for a resolver that LISTS: a display name
401    /// that the exact-case slug tier could never resolve resolves here when
402    /// exactly one agent bears it, because there is nothing to misroute.
403    #[test]
404    fn a_unique_display_name_resolves_to_the_rows_uid() {
405        let store = store_with(&[(UID_Y, "AgentY", "agenty")]);
406        for typed in ["AgentY", "agenty", "AGENTY"] {
407            let r = resolve_name_to_uid(&store, &registry(), typed).unwrap();
408            assert!(
409                matches!(r, NameResolution::One { ref uid, .. } if uid == UID_Y),
410                "{typed}: {r:?}"
411            );
412        }
413    }
414
415    /// Two agents whose names collide are refused WITH both candidates.
416    #[test]
417    fn colliding_names_are_ambiguous_with_both_candidates_listed() {
418        let store = store_with(&[(UID_Y, "AgentY", "agenty"), (UID_UP, "AGENTY", "agenty-2")]);
419        let r = resolve_name_to_uid(&store, &registry(), "agenty").unwrap();
420        let NameResolution::Ambiguous { candidates } = r else {
421            panic!("expected Ambiguous, got {r:?}");
422        };
423        let uids: Vec<&str> = candidates.iter().filter_map(|c| c.uid.as_deref()).collect();
424        assert!(
425            uids.contains(&UID_Y) && uids.contains(&UID_UP),
426            "{candidates:?}"
427        );
428        // …while the collision-resolved slug alone is exact.
429        let r = resolve_name_to_uid(&store, &registry(), "agenty-2").unwrap();
430        assert!(
431            matches!(r, NameResolution::One { ref uid, .. } if uid == UID_UP),
432            "{r:?}"
433        );
434    }
435
436    /// A live registration and its stored row are ONE candidate, marked live
437    /// with its block — not two.
438    #[test]
439    fn a_live_agent_and_its_row_merge_into_one_live_candidate() {
440        let store = store_with(&[(UID_Y, "AgentY", "agenty")]);
441        let reg = registry();
442        reg.register_agent_full("AgentY", "block-y", None, 0, None, Some(UID_Y), "test.m3")
443            .unwrap();
444        let r = resolve_name_to_uid(&store, &reg, "AgentY").unwrap();
445        let NameResolution::One { uid, candidate } = r else {
446            panic!("expected One, got {r:?}");
447        };
448        assert_eq!(uid, UID_Y);
449        assert!(candidate.live);
450        assert_eq!(candidate.block_id.as_deref(), Some("block-y"));
451        assert_eq!(candidate.slug, "agenty");
452    }
453
454    fn bind_block(store: &Store, block_id: &str, agent_uid: &str) {
455        let mut block = crate::backend::obj::Block {
456            oid: block_id.to_string(),
457            parentoref: String::new(),
458            version: 0,
459            runtimeopts: None,
460            stickers: None,
461            meta: {
462                let mut m = crate::backend::obj::MetaMapType::new();
463                m.insert("view".to_string(), serde_json::json!("agent"));
464                m.insert("agentId".to_string(), serde_json::json!(agent_uid));
465                m
466            },
467            subblockids: None,
468        };
469        store.insert(&mut block).unwrap();
470    }
471
472    /// An agent that registered before its row existed carries no UID (spec
473    /// Q1). It must still be ONE candidate with its own row — its UID taken
474    /// from the row on its block — not ambiguous with itself (review on
475    /// #3563: an agent scheduling cron to itself by name was refused).
476    #[test]
477    fn a_live_agent_registered_without_a_uid_merges_with_its_own_row_by_block() {
478        let store = store_with(&[(UID_Y, "AgentY", "agenty")]);
479        bind_block(&store, "block-y", UID_Y);
480        let reg = registry();
481        reg.register_agent_full("AgentY", "block-y", None, 0, None, None, "test.m3")
482            .unwrap();
483        let r = resolve_name_to_uid(&store, &reg, "AgentY").unwrap();
484        let NameResolution::One { uid, candidate } = r else {
485            panic!("expected One, got {r:?}");
486        };
487        assert_eq!(uid, UID_Y);
488        assert!(candidate.live);
489        assert_eq!(candidate.block_id.as_deref(), Some("block-y"));
490    }
491
492    /// …but a uid-less live block that is NOT that row's block (a
493    /// quick-launch pane that happens to share the name) stays a separate
494    /// candidate: the merge is by block identity, never by name.
495    #[test]
496    fn a_same_named_pane_on_another_block_is_still_ambiguous_with_the_row() {
497        let store = store_with(&[(UID_Y, "AgentY", "agenty")]);
498        let reg = registry();
499        reg.register_agent_full("AgentY", "block-pane", None, 0, None, None, "test.m3")
500            .unwrap();
501        let r = resolve_name_to_uid(&store, &reg, "AgentY").unwrap();
502        let NameResolution::Ambiguous { candidates } = r else {
503            panic!("expected Ambiguous, got {r:?}");
504        };
505        assert_eq!(candidates.len(), 2, "{candidates:?}");
506    }
507
508    /// A live block with no row (quick-launch pane) is `Unidentified`: it
509    /// exists and is reachable by name, but has no UID to store.
510    #[test]
511    fn a_live_block_without_a_row_is_unidentified_not_none() {
512        let store = store_with(&[]);
513        let reg = registry();
514        reg.register_agent_full("Scratch", "block-s", None, 0, None, None, "test.m3")
515            .unwrap();
516        let r = resolve_name_to_uid(&store, &reg, "scratch").unwrap();
517        assert!(
518            matches!(r, NameResolution::Unidentified { ref candidate } if candidate.block_id.as_deref() == Some("block-s")),
519            "{r:?}"
520        );
521    }
522
523    #[test]
524    fn unknown_and_empty_names_are_none() {
525        let store = store_with(&[(UID_Y, "AgentY", "agenty")]);
526        assert_eq!(
527            resolve_name_to_uid(&store, &registry(), "nobody").unwrap(),
528            NameResolution::None
529        );
530        assert_eq!(
531            resolve_name_to_uid(&store, &registry(), "   ").unwrap(),
532            NameResolution::None
533        );
534    }
535
536    /// A store fault is an error, never `None`: `None` would send the bare
537    /// name on, and a same-named live agent could take what was meant for
538    /// the stored agent the fault hid (Codex P1 on #3563).
539    #[test]
540    fn a_store_fault_is_refused_not_answered_as_none() {
541        let store = store_with(&[(UID_Y, "AgentY", "agenty")]);
542        let reg = registry();
543        reg.register_agent_full("AgentY", "block-other", None, 0, None, None, "test.m3")
544            .unwrap();
545        store.test_break_agents_table().unwrap();
546        for typed in ["AgentY", UID_Y] {
547            let r = resolve_name_to_uid(&store, &reg, typed);
548            assert!(r.is_err(), "{typed}: {r:?}");
549        }
550    }
551
552    /// A typed UID whose cross-channel definition cannot be read is refused
553    /// too — "not found" there would send the UID string on as a name, and
554    /// the work could never be claimed (Codex P2 on #3568).
555    #[test]
556    fn an_unreadable_global_definition_is_refused_not_answered_as_none() {
557        let store = store_with(&[]);
558        let tmp = tempfile::tempdir().unwrap();
559        let defs = crate::registry::DefinitionStore::open(tmp.path().to_path_buf()).unwrap();
560        std::fs::write(tmp.path().join(format!("{UID_UP}.json")), b"{ not json").unwrap();
561        store.set_def_registry(std::sync::Arc::new(defs));
562        let r = resolve_name_to_uid(&store, &registry(), UID_UP);
563        assert!(r.is_err(), "{r:?}");
564    }
565
566    /// A slug an agent was renamed from resolves to it, stored or live: the
567    /// endpoint `WorkEnqueue` and `CronCreate` call, so a task or a cron job
568    /// addressed to the old id stores the agent's UID (fork slug migration
569    /// Phase 1). Live and stored are one candidate.
570    #[test]
571    fn a_former_slug_resolves_to_its_agent_stored_or_live() {
572        let store = std::sync::Arc::new(store_with(&[(UID_Y, "Loap #2", "loap-loap-2")]));
573        store.test_rename_slug(UID_Y, "loap-2", 1);
574        let r = resolve_name_to_uid(&store, &registry(), "loap-loap-2").unwrap();
575        let NameResolution::One { uid, candidate } = r else {
576            panic!("expected One, got {r:?}");
577        };
578        assert_eq!((uid.as_str(), candidate.slug.as_str(), candidate.live), (UID_Y, "loap-2", false));
579
580        let reg = registry();
581        let resolver_store = store.clone();
582        reg.set_former_slug_resolver(std::sync::Arc::new(move |n: &str| {
583            resolver_store.former_slug_owner(n).ok().flatten().map(|o| o.uid)
584        }));
585        reg.register_agent_full("Loap-2", "block-l", None, 0, Some("loap-2"), Some(UID_Y), "test.m3").unwrap();
586        let r = resolve_name_to_uid(&store, &reg, "loap-loap-2").unwrap();
587        assert!(
588            matches!(&r, NameResolution::One { uid, candidate } if uid == UID_Y && candidate.live),
589            "{r:?}"
590        );
591    }
592
593    #[test]
594    fn a_display_names_route_form_resolves_to_its_agent() {
595        // "Naki #2" signs and is addressed as "Naki-2" (#1257).
596        let store = store_with(&[(UID_Y, "Naki #2", "naki-naki-2")]);
597        for typed in ["Naki-2", "naki-2", " NAKI-2 "] {
598            let r = resolve_name_to_uid(&store, &registry(), typed).unwrap();
599            assert!(matches!(r, NameResolution::One { ref uid, .. } if uid == UID_Y), "{typed}: {r:?}");
600        }
601    }
602
603    #[test]
604    fn two_display_names_with_one_route_form_are_ambiguous() {
605        let store = store_with(&[(UID_Y, "Naki #2", "naki-naki-2"), (UID_UP, "Naki 2", "naki-2-b")]);
606        let r = resolve_name_to_uid(&store, &registry(), "Naki-2").unwrap();
607        let NameResolution::Ambiguous { candidates } = r else { panic!("{r:?}") };
608        let mut uids: Vec<_> = candidates.iter().filter_map(|c| c.uid.clone()).collect();
609        uids.sort();
610        assert_eq!(uids, vec![UID_Y.to_string(), UID_UP.to_string()]);
611    }
612
613    #[test]
614    fn a_route_form_of_nothing_is_still_none() {
615        let store = store_with(&[(UID_Y, "Naki #2", "naki-naki-2")]);
616        assert_eq!(resolve_name_to_uid(&store, &registry(), "Naki-3").unwrap(), NameResolution::None);
617    }
618
619    /// A local template's slug doesn't shadow an agent whose
620    /// title routes to the same name; a forgotten agent is never a target; a
621    /// renamed fork is found by its current title.
622    #[test]
623    fn templates_and_forgotten_agents_never_shadow_or_answer() {
624        let store = store_with(&[]);
625        let mut tpl = test_agent_def("tpl-claude", "Claude", "claude", "agent", 1, "");
626        tpl.slug = "claude".into();
627        tpl.is_seeded = 1;
628        store.agent_def_insert(&mut tpl).unwrap();
629        let mut root = test_agent_def(UID_Y, "Claude", "claude", "agent", 2, "");
630        root.slug = "claude-2".into();
631        store.agent_def_insert(&mut root).unwrap();
632        // "claude" is the template's slug, and the user agent's title.
633        let r = resolve_name_to_uid(&store, &registry(), "claude").unwrap();
634        assert!(matches!(r, NameResolution::One { ref uid, .. } if uid == UID_Y), "{r:?}");
635
636        let mut gone = test_agent_def(UID_UP, "Gone #1", "claude", "agent", 3, "");
637        gone.slug = "gone-gone-1".into();
638        gone.user_hidden = 1;
639        store.agent_def_insert(&mut gone).unwrap();
640        for typed in ["Gone-1", "gone-gone-1"] {
641            assert_eq!(resolve_name_to_uid(&store, &registry(), typed).unwrap(), NameResolution::None, "{typed}");
642        }
643
644        let mut fork = test_agent_def("uid-fork-1257", "Loap", "claude", "agent", 4, "");
645        fork.slug = "loap-loap-3".into();
646        fork.parent_id = "uid-root".into();
647        fork.branch_label = "Loap Renamed".into();
648        store.agent_def_insert(&mut fork).unwrap();
649        let r = resolve_name_to_uid(&store, &registry(), "Loap-Renamed").unwrap();
650        assert!(matches!(r, NameResolution::One { ref uid, .. } if uid == "uid-fork-1257"), "{r:?}");
651    }
652
653    /// Templates are prototypes, never targets (spec §1.2): a provider key
654    /// typed as a name must not resolve to the template row.
655    #[test]
656    fn a_template_row_is_not_a_candidate() {
657        let store = Store::open_in_memory().unwrap();
658        let mut tpl = test_agent_def("claude", "Claude", "claude", "agent", 1, "");
659        tpl.is_seeded = 1;
660        store.agent_def_insert(&mut tpl).unwrap();
661        assert_eq!(
662            resolve_name_to_uid(&store, &registry(), "claude").unwrap(),
663            NameResolution::None
664        );
665    }
666}