Skip to main content

agentmux_srv_core/backend/slug_migration/
verify.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! ยง4 Phase 2 step 5: re-read every location after an agent's steps and say
5//! what is wrong, if anything. The new slug everywhere; the old one only as a
6//! former slug; no signing key under the old name; and both names resolve to
7//! the uid, by the same rule message delivery uses (`Store::former_name_owner`,
8//! which resolves former slugs and former display names alike).
9
10use std::path::Path;
11use std::sync::Arc;
12
13use rusqlite::OptionalExtension;
14use serde_json::Value;
15
16use super::home::{fold, open_ro, table_exists};
17use super::steps::{Agent, Ctx};
18use super::{steps_db, steps_files};
19
20/// Every problem found for `a`; empty when it verifies.
21pub(super) fn verify(ctx: &Ctx, a: &Agent) -> Result<Vec<String>, String> {
22    let mut problems = Vec::new();
23    let def_path = steps_files::def_path(ctx.home, &a.uid);
24    let def: Value = serde_json::from_slice(&std::fs::read(&def_path).map_err(|e| format!("{}: {e}", def_path.display()))?)
25        .map_err(|e| e.to_string())?;
26    if def.pointer("/data/slug").and_then(Value::as_str) != Some(a.new.as_str()) {
27        problems.push(format!("the shared definition's slug isn't {}", a.new));
28    }
29    let former = def.pointer("/data/former_slugs").and_then(Value::as_array).cloned().unwrap_or_default();
30    if !former.iter().any(|f| f.get("slug").and_then(Value::as_str).is_some_and(|s| fold(s) == fold(&a.old))) {
31        problems.push(format!("the shared definition doesn't list {} as a former slug", a.old));
32    }
33    let defs_store = Arc::new(crate::registry::DefinitionStore::open(ctx.home.definitions()).map_err(|e| e.to_string())?);
34    for db in ctx.objects_dbs() {
35        problems.extend(verify_objects_db(&db, &defs_store, a)?);
36    }
37    for db in ctx.wan_dbs() {
38        let conn = open_ro(&db)?;
39        if table_exists(&conn, "wan_agent_keys") {
40            let left: Option<String> = conn
41                .query_row("SELECT agent_id FROM wan_agent_keys WHERE agent_id = ?1 COLLATE NOCASE", [fold(&a.old)], |r| r.get(0))
42                .optional()
43                .map_err(|e| e.to_string())?;
44            if left.is_some() {
45                problems.push(format!("{}: a WAN key is still filed under {}", db.display(), a.old));
46            }
47        }
48    }
49    let leftover = steps_files::stale_registrations(ctx, a);
50    if !leftover.is_empty() {
51        problems.push(format!("{} registration(s) under {} remain", leftover.len(), a.old));
52    }
53    if !steps_files::mcp_files(ctx, a)?.is_empty() {
54        problems.push(format!("a workspace .mcp.json still signs as {}", a.old));
55    }
56    let name_only = steps_db::s6_before(ctx, a)?;
57    let left = ["updates", "grants"].iter().map(|k| name_only[*k].as_array().map_or(0, Vec::len)).sum::<usize>();
58    if left > 0 {
59        problems.push(format!("{left} cron job, queue item or trust grant row(s) still name {} without its uid", a.old));
60    }
61    Ok(problems)
62}
63
64fn verify_objects_db(db: &Path, defs: &Arc<crate::registry::DefinitionStore>, a: &Agent) -> Result<Vec<String>, String> {
65    let mut problems = Vec::new();
66    let place = db.display().to_string();
67    {
68        let conn = open_ro(db)?;
69        let row: Option<Option<String>> = if super::home::has_agent_slugs(&conn) {
70            conn.query_row("SELECT slug FROM db_agents WHERE id = ?1", [&a.uid], |r| r.get(0))
71                .optional()
72                .map_err(|e| e.to_string())?
73        } else {
74            None
75        };
76        if let Some(slug) = &row {
77            if slug.as_deref() != Some(a.new.as_str()) {
78                problems.push(format!("{place}: db_agents.slug is {:?}, not {}", slug.as_deref().unwrap_or(""), a.new));
79            }
80            let recorded = table_exists(&conn, "db_agent_former_slugs")
81                && conn
82                    .query_row("SELECT 1 FROM db_agent_former_slugs WHERE agent_uid = ?1 AND slug = ?2", [&a.uid, &fold(&a.old)], |_| Ok(()))
83                    .optional()
84                    .map_err(|e| e.to_string())?
85                    .is_some();
86            if !recorded {
87                problems.push(format!("{place}: {} isn't recorded as a former slug", a.old));
88            }
89        }
90        for table in ["db_agent_jekt_keys", "db_agent_lan_keys", "db_agent_wan_keys"].iter().filter(|t| table_exists(&conn, t)) {
91            let left: Option<String> = conn
92                .query_row(&format!("SELECT agent_id FROM {table} WHERE agent_id = ?1 COLLATE NOCASE"), [fold(&a.old)], |r| r.get(0))
93                .optional()
94                .map_err(|e| e.to_string())?;
95            if left.is_some() {
96                problems.push(format!("{place}: a signing key is still filed under {} in {table}", a.old));
97            }
98        }
99        if row.is_none() {
100            return Ok(problems);
101        }
102    }
103    if !steps_db::s7_rows(db, a)?.is_empty() {
104        problems.push(format!("{place}: a pane's persisted identity still names {}", a.old));
105    }
106    // Resolution, by srv's own rule, on this database as it is.
107    let store = crate::backend::storage::store::Store::open_source_readonly(db).map_err(|e| e.to_string())?;
108    store.set_def_registry(defs.clone());
109    match store.former_name_owner(&a.old) {
110        Ok(Some(owner)) if owner.uid == a.uid && owner.slug == a.new => {}
111        Ok(other) => problems.push(format!("{place}: {} resolves to {other:?}, not to {}", a.old, a.uid)),
112        Err(e) if too_old(&e) => {}
113        Err(e) => problems.push(format!("{place}: resolving {} failed: {e}", a.old)),
114    }
115    match store.agent_ids_for_slug_folded(&a.new) {
116        Ok(ids) if ids == [a.uid.clone()] => {}
117        Ok(ids) => problems.push(format!("{place}: {} resolves to {ids:?}, not only to {}", a.new, a.uid)),
118        Err(e) if too_old(&e) => {}
119        Err(e) => problems.push(format!("{place}: resolving {} failed: {e}", a.new)),
120    }
121    Ok(problems)
122}
123
124/// A database from a version too old for srv's resolver to query: nothing
125/// running reads it with that rule, and its rows were checked above.
126fn too_old(e: &crate::backend::storage::error::StoreError) -> bool {
127    e.to_string().contains("no such")
128}