agentmux_srv_core/backend/
agent_resolve.rs1use crate::backend::agent_registry_lookup::find_active_record_by_slug;
24use crate::backend::storage::store::Store;
25
26pub 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 match store.instance_get_by_slug(slug_or_id) {
56 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
82static UID_FALLBACK_COUNTS: std::sync::OnceLock<
86 std::sync::Mutex<std::collections::HashMap<&'static str, u64>>,
87> = std::sync::OnceLock::new();
88
89pub 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
106pub 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
115pub 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
125pub(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
138pub(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
146pub 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 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 #[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 #[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 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 #[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}