Skip to main content

agentmux_srv_core/backend/slug_migration/
plan.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The plan: which agents are candidates (§5.1), what each would be renamed
5//! to, whether that id is free everywhere it could be held, and every place
6//! the old one is stored. Reads only; nothing here writes.
7
8use std::collections::{BTreeMap, HashSet};
9use std::path::{Path, PathBuf};
10
11use serde_json::Value;
12
13use super::home::{fold, has_agent_slugs, has_column, open_ro, place, table_exists, Home, Install};
14use crate::backend::rpc_types::{
15    ForkSlugBlocker, ForkSlugBlockerKind, ForkSlugCandidate, ForkSlugChoice, ForkSlugDuplicate, ForkSlugPlan, ForkSlugSkipped,
16};
17use agentmux_common::slug::{agent_route_name, definition_slug, fork_slug, is_agent_id};
18use rusqlite::OptionalExtension;
19
20/// One shared definition, as the plan needs it.
21#[derive(Debug, Clone, Default)]
22pub(super) struct Def {
23    pub uid: String,
24    pub name: String,
25    pub slug: String,
26    pub former: Vec<String>,
27    pub parent_id: String,
28    pub branch_label: String,
29    pub created_at: i64,
30    pub path: PathBuf,
31}
32
33/// Every active shared definition, and the files that can't be read. A
34/// file whose slug can't be read leaves the collision check incomplete, so
35/// it blocks the run.
36pub(super) fn load_defs(home: &Home) -> Result<(Vec<Def>, Vec<String>), String> {
37    let dir = home.definitions();
38    let entries = match std::fs::read_dir(&dir) {
39        Ok(e) => e,
40        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((Vec::new(), Vec::new())),
41        Err(e) => return Err(format!("{} can't be listed: {e}", dir.display())),
42    };
43    let mut defs = Vec::new();
44    let mut unreadable = Vec::new();
45    for entry in entries {
46        let path = entry.map_err(|e| format!("{} can't be listed: {e}", dir.display()))?.path();
47        if path.extension().and_then(|e| e.to_str()) != Some("json") || !path.is_file() {
48            continue;
49        }
50        let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or_default().to_string();
51        match std::fs::read(&path).map_err(|e| e.to_string()).and_then(|b| parse_def(&stem, &b, &path)) {
52            Ok(def) => defs.push(def),
53            Err(why) => unreadable.push(format!("{}: {why}", path.display())),
54        }
55    }
56    defs.sort_by(|a, b| a.uid.cmp(&b.uid));
57    Ok((defs, unreadable))
58}
59
60fn parse_def(stem: &str, bytes: &[u8], path: &Path) -> Result<Def, String> {
61    let json: Value = serde_json::from_slice(bytes).map_err(|e| format!("not JSON ({e})"))?;
62    let data = json.get("data").and_then(Value::as_object).ok_or("no `data` object")?;
63    let text = |k: &str| data.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
64    if text("id") != stem {
65        return Err("its `data.id` doesn't name this file".into());
66    }
67    let former = match data.get("former_slugs") {
68        None | Some(Value::Null) => Vec::new(),
69        Some(Value::Array(list)) => list
70            .iter()
71            .map(|f| f.get("slug").and_then(Value::as_str).map(str::to_string))
72            .collect::<Option<Vec<_>>>()
73            .ok_or("a `former_slugs` entry has no slug")?,
74        Some(_) => return Err("`former_slugs` isn't a list".into()),
75    };
76    Ok(Def {
77        uid: stem.to_string(),
78        name: text("name"),
79        slug: text("slug"),
80        former,
81        parent_id: text("parent_id"),
82        branch_label: text("branch_label"),
83        created_at: data.get("created_at").and_then(Value::as_i64).unwrap_or(0),
84        path: path.to_path_buf(),
85    })
86}
87
88/// A candidate before its collision check and locations.
89#[derive(Debug, Clone)]
90pub(super) struct Found {
91    pub def: Def,
92    pub new_slug: String,
93    pub depth: usize,
94}
95
96/// §5.1: a fork whose slug is its parent's slug, `-`, and its label's slug
97/// (the rule before #4746), and differs from `fork_slug` of its lineage root.
98/// The parent's former slugs count as its slug: a parent migrated first (or in
99/// an earlier, interrupted run) no longer has the slug the child chained.
100pub(super) fn find_candidates(defs: &[Def]) -> (Vec<Found>, Vec<ForkSlugSkipped>) {
101    let by_id: BTreeMap<&str, &Def> = defs.iter().map(|d| (d.uid.as_str(), d)).collect();
102    let mut found = Vec::new();
103    let mut skipped = Vec::new();
104    // Only forks: an agent without a branch label is a lineage root, whatever
105    // its `parent_id` says (one made from a template keeps the template's id
106    // there), as `fork_lineage_root_id` reads it.
107    for def in defs.iter().filter(|d| !d.parent_id.trim().is_empty() && !d.branch_label.is_empty()) {
108        let skip = |reason: &str| ForkSlugSkipped {
109            uid: def.uid.clone(),
110            name: def.name.clone(),
111            slug: def.slug.clone(),
112            reason: reason.to_string(),
113        };
114        let Some(parent) = by_id.get(def.parent_id.as_str()) else {
115            skipped.push(skip("its parent is missing, so the old rule can't be recomputed"));
116            continue;
117        };
118        let Some((root, depth)) = lineage_root(&by_id, def) else {
119            skipped.push(skip("its lineage root is missing"));
120            continue;
121        };
122        if root.slug.trim().is_empty() {
123            skipped.push(skip("its lineage root has no slug"));
124            continue;
125        }
126        let new_slug = fork_slug(&root.slug, &root.name, &def.branch_label);
127        if fold(&def.slug) == fold(&new_slug) {
128            continue;
129        }
130        let label = definition_slug(&def.branch_label);
131        let chained = std::iter::once(&parent.slug).chain(&parent.former).any(|p| {
132            let old_rule = format!("{p}-{label}");
133            fold(&def.slug) == fold(&old_rule) || fold(&def.slug) == definition_slug(&old_rule)
134        });
135        if !chained {
136            skipped.push(skip("not a pre-fix chain: its slug isn't its parent's plus its label"));
137            continue;
138        }
139        if !is_agent_id(&new_slug) {
140            skipped.push(skip(&format!("its new id {new_slug:?} isn't a valid agent id")));
141            continue;
142        }
143        found.push(Found { def: def.clone(), new_slug, depth });
144    }
145    // Parent first (§5.2): by generation, then by name.
146    found.sort_by(|a, b| a.depth.cmp(&b.depth).then_with(|| a.def.name.cmp(&b.def.name)));
147    (found, skipped)
148}
149
150/// The lineage root of `def` and how many generations below it `def` is:
151/// `parent_id` is followed only while the agent is a fork (it has a branch
152/// label), so the root is the first agent without one, and a template in
153/// its `parent_id` ends the walk there (template.rs `fork_lineage_root_id`).
154/// `None` if a fork's parent is missing or the links loop.
155fn lineage_root<'a>(by_id: &BTreeMap<&str, &'a Def>, def: &'a Def) -> Option<(&'a Def, usize)> {
156    let mut seen = HashSet::new();
157    let mut cur = def;
158    let mut depth = 0;
159    // Exactly `fork_lineage_root_id`'s test: a whitespace-only label still
160    // makes a fork (#5366).
161    while !cur.branch_label.is_empty() && !cur.parent_id.is_empty() {
162        if !seen.insert(cur.uid.as_str()) {
163            return None;
164        }
165        cur = by_id.get(cur.parent_id.as_str())?;
166        depth += 1;
167    }
168    Some((cur, depth))
169}
170
171/// Whether a display or instance name routes to `folded`, as a message's
172/// target does (`agent_route_name`, case-insensitive).
173fn routes_to(name: &str, folded: &str) -> bool {
174    !name.trim().is_empty() && fold(&agent_route_name(name)) == folded
175}
176
177/// Who holds `target` other than `uid`, if anyone: a shared definition's
178/// slug, former slug or display route; a row's slug, former slug, display or
179/// instance route, or former display name's route (which still addresses
180/// its agent, as `resolve_slug_collision` keeps it) in any `objects.db` on
181/// disk; another candidate's new id; a
182/// live cross-channel registration; or a live per-version registration of
183/// another agent's pane. A display route counts because a message to the
184/// target would otherwise reach whichever agent holds it as its slug, and
185/// the agent it was meant for would never see it. Held only by `uid` itself
186/// (its own display binding) is free. An `Err` is a store that can't be
187/// read: the answer isn't known.
188pub(super) fn holder_of(
189    home: &Home,
190    installs: &[Install],
191    defs: &[Def],
192    taken: &BTreeMap<String, String>,
193    uid: &str,
194    target: &str,
195) -> Result<Option<String>, String> {
196    let t = fold(target);
197    for d in defs.iter().filter(|d| d.uid != uid) {
198        if fold(&d.slug) == t {
199            return Ok(Some(format!("agent {} ({}) has it as its id", d.name, d.uid)));
200        }
201        if d.former.iter().any(|f| fold(f) == t) {
202            return Ok(Some(format!("agent {} ({}) was renamed from it, and it stays reserved", d.name, d.uid)));
203        }
204        if routes_to(&d.name, &t) {
205            return Ok(Some(format!("messages to it reach agent {} ({}), whose name routes there", d.name, d.uid)));
206        }
207        // A fork's name is its branch label, and messages reach it too.
208        if routes_to(&d.branch_label, &t) {
209            return Ok(Some(format!("messages to it reach agent {} ({}), whose branch label routes there", d.name, d.uid)));
210        }
211    }
212    if let Some(other) = taken.get(&t).filter(|o| o.as_str() != uid) {
213        return Ok(Some(format!("this run renames agent {other} to it")));
214    }
215    for install in installs {
216        for version in &install.versions {
217            let db = version.objects_db();
218            let failed = |e: rusqlite::Error| format!("{} can't be read: {e}", db.display());
219            let conn = open_ro(&db)?;
220            let slugs = has_agent_slugs(&conn);
221            let row: Option<String> = if slugs {
222                conn.query_row("SELECT id FROM db_agents WHERE slug = ?1 COLLATE NOCASE AND id != ?2 LIMIT 1", [&t, uid], |r| r.get(0))
223                    .optional()
224                    .map_err(failed)?
225            } else {
226                None
227            };
228            if let Some(id) = row {
229                return Ok(Some(format!("agent {id} has it in {}", place(install, version))));
230            }
231            let routed: Option<(String, String)> = if !slugs {
232                None
233            } else {
234                // An older db_agents may lack a route column: it routes nothing.
235                let col = |c: &str| if has_column(&conn, "db_agents", c) { format!("COALESCE({c}, '')") } else { "''".to_string() };
236                let (name, instance, label) = (col("name"), col("instance_name"), col("branch_label"));
237                let mut stmt = conn
238                    .prepare(&format!("SELECT id, {name}, {instance}, {label} FROM db_agents WHERE id != ?1"))
239                    .map_err(failed)?;
240                let rows = stmt
241                    .query_map([uid], |r| {
242                        Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?))
243                    })
244                    .map_err(failed)?;
245                let mut hit = None;
246                for row in rows {
247                    let (id, name, instance, branch_label) = row.map_err(failed)?;
248                    if let Some(route) = [name, instance, branch_label].into_iter().find(|n| routes_to(n, &t)) {
249                        hit = Some((id, route));
250                        break;
251                    }
252                }
253                hit
254            };
255            if let Some((id, name)) = routed {
256                return Ok(Some(format!("messages to it reach agent {id} in {}, whose name {name:?} routes there", place(install, version))));
257            }
258            if table_exists(&conn, "db_agent_former_slugs") {
259                let former: Option<String> = conn
260                    .query_row(
261                        "SELECT agent_uid FROM db_agent_former_slugs WHERE slug = ?1 COLLATE NOCASE AND agent_uid != ?2 LIMIT 1",
262                        [&t, uid],
263                        |r| r.get(0),
264                    )
265                    .optional()
266                    .map_err(failed)?;
267                if let Some(id) = former {
268                    return Ok(Some(format!("agent {id} was renamed from it in {}", place(install, version))));
269                }
270            }
271            if table_exists(&conn, "db_agent_former_names") {
272                let mut stmt = conn.prepare("SELECT agent_id, name FROM db_agent_former_names WHERE agent_id != ?1").map_err(failed)?;
273                let rows = stmt.query_map([uid], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(failed)?;
274                for row in rows {
275                    let (id, name) = row.map_err(failed)?;
276                    if routes_to(&name, &t) {
277                        return Ok(Some(format!(
278                            "agent {id} was called {name:?} in {}, and messages to that name still reach it",
279                            place(install, version)
280                        )));
281                    }
282                }
283            }
284            if let Some(entry) = super::running::registration(&version.registrations(), &t) {
285                let owner = super::running::block_agent(&conn, &entry.block_id);
286                if owner.as_deref() != Some(uid) {
287                    return Ok(Some(format!("a running pane is registered as it in {}", place(install, version))));
288                }
289            }
290        }
291    }
292    for entry in super::running::shared_entries(home, &t) {
293        if entry.uid != uid {
294            return Ok(Some(format!("a running pane in channel {} is registered as it", entry.channel)));
295        }
296    }
297    Ok(None)
298}
299
300/// The plan: candidates, each refused or not, with its locations and where
301/// it runs; the forks left alone; and what would block an apply now.
302/// `quick` stops after finding the candidates.
303pub fn plan(home: &Home, quick: bool) -> Result<ForkSlugPlan, String> {
304    plan_with(home, quick, true, &[])
305}
306
307/// [`plan`] with ids the user picked for some agents.
308pub fn plan_choosing(home: &Home, quick: bool, choices: &[ForkSlugChoice]) -> Result<ForkSlugPlan, String> {
309    plan_with(home, quick, true, choices)
310}
311
312/// Give each chosen agent the id the user picked in place of the computed one. The pick goes
313/// through the same collision check as any other new id (an agent whose pick is taken is
314/// refused again, with the new reason), so a choice can't claim an id something holds.
315/// An error for a pick that can't be an id for that agent at all.
316fn apply_choices(found: &mut [Found], choices: &[ForkSlugChoice]) -> Result<(), String> {
317    for choice in choices {
318        let slug = choice.new_slug.trim();
319        let Some(f) = found.iter_mut().find(|f| f.def.uid == choice.uid) else {
320            return Err(format!("{} isn't an agent with an outdated id", choice.uid));
321        };
322        if !is_agent_id(slug) {
323            return Err(format!("{slug:?} isn't a valid agent id"));
324        }
325        if fold(slug) == fold(&f.def.slug) {
326            return Err(format!("{} already has the id {slug}", f.def.name));
327        }
328        f.new_slug = slug.to_string();
329    }
330    Ok(())
331}
332
333/// [`plan`]; a run that holds the migration lock itself passes `false`
334/// for `check_lock`. `choices` give agents an id of the user's picking.
335pub(super) fn plan_with(home: &Home, quick: bool, check_lock: bool, choices: &[ForkSlugChoice]) -> Result<ForkSlugPlan, String> {
336    let (defs, unreadable) = load_defs(home)?;
337    let (mut found, skipped) = find_candidates(&defs);
338    if !quick {
339        apply_choices(&mut found, choices)?;
340    }
341    if quick {
342        let candidates = found.into_iter().map(|f| bare(&f)).collect::<Vec<_>>();
343        let summary = summary(&candidates, &skipped, &[], &[]);
344        return Ok(ForkSlugPlan { candidates, skipped, blockers: Vec::new(), summary, last_run: last_run(home), duplicates: Vec::new() });
345    }
346    let installs = home.installs()?;
347    let mut blockers: Vec<ForkSlugBlocker> = unreadable
348        .iter()
349        .map(|u| ForkSlugBlocker::new(ForkSlugBlockerKind::Unreadable, format!("A shared definition can't be read, so no new id can be checked: {u}")))
350        .collect();
351    blockers.extend(unreadable_stores(home, &installs).into_iter().map(|u| {
352        ForkSlugBlocker::new(ForkSlugBlockerKind::Unreadable, format!("A database can't be read, so no new id can be checked: {u}"))
353    }));
354    if !blockers.is_empty() {
355        // Nothing past this point can be trusted: a store that can't be read
356        // may hold any target. Every candidate waits, none is "free".
357        let candidates: Vec<ForkSlugCandidate> = found
358            .iter()
359            .map(|f| ForkSlugCandidate { refused: Some("not every store can be read, so its new id can't be checked".into()), ..bare(f) })
360            .collect();
361        // The shared definitions alone: a store that can't be read may hold
362        // more, and no proposal can be checked.
363        let duplicates = super::duplicates::duplicates(home, &installs, &defs, &BTreeMap::new(), false);
364        let summary = summary(&candidates, &skipped, &blockers, &duplicates);
365        return Ok(ForkSlugPlan { candidates, skipped, blockers, summary, last_run: last_run(home), duplicates });
366    }
367    let mut taken: BTreeMap<String, String> = BTreeMap::new();
368    let mut candidates = Vec::new();
369    for f in &found {
370        let mut c = bare(f);
371        match holder_of(home, &installs, &defs, &taken, &f.def.uid, &f.new_slug) {
372            Ok(Some(holder)) => {
373                c.refused = Some(format!("{} is taken: {holder}", f.new_slug));
374                c.suggestion = suggest(home, &installs, &defs, &taken, &f.def.uid, &f.new_slug).unwrap_or(None);
375            }
376            Ok(None) => {
377                taken.insert(fold(&f.new_slug), f.def.uid.clone());
378            }
379            Err(e) => {
380                c.refused = Some("its new id can't be checked".into());
381                blockers.push(ForkSlugBlocker::new(ForkSlugBlockerKind::Unreadable, format!("A database can't be read, so no new id can be checked: {e}")));
382                candidates.push(c);
383                continue;
384            }
385        }
386        c.locations = super::locations::locations(home, &installs, &f.def, &f.new_slug)?;
387        c.running = super::running::running(home, &installs, &f.def)?;
388        candidates.push(c);
389    }
390    if candidates.iter().any(|c| c.refused.is_none()) {
391        blockers.extend(super::preconditions::blockers(home, &installs, &candidates, check_lock));
392    }
393    let duplicates = super::duplicates::duplicates(home, &installs, &defs, &taken, true);
394    let summary = summary(&candidates, &skipped, &blockers, &duplicates);
395    Ok(ForkSlugPlan { candidates, skipped, blockers, summary, last_run: last_run(home), duplicates })
396}
397
398/// The latest run, unless it was rolled back. A journal that can't be read
399/// counts as no run: the plan still shows, and an apply reports the error.
400fn last_run(home: &Home) -> Option<crate::backend::rpc_types::ForkSlugLastRun> {
401    let (path, journal) = super::journal::journals(&home.backups())
402        .into_iter()
403        .find_map(|p| super::journal::Journal::read(&p).ok().map(|j| (p, j)))?;
404    if journal.rolled_back() {
405        return None;
406    }
407    Some(crate::backend::rpc_types::ForkSlugLastRun {
408        journal: path.display().to_string(),
409        finished: journal.finished().is_some(),
410        failed: journal.last_failure(),
411    })
412}
413
414/// Every database a run reads or writes that can't be read now, by path
415/// and why: a corrupt or incompatible `objects.db` (its agents), `wan.db` or
416/// host store. A query that finds no row is not a failure; one that can't
417/// run is.
418pub(super) fn unreadable_stores(home: &Home, installs: &[Install]) -> Vec<String> {
419    let mut out = Vec::new();
420    let probe = |db: &Path, sql: &str, out: &mut Vec<String>| {
421        let result = open_ro(db).and_then(|c| {
422            c.query_row(sql, [], |_| Ok(())).optional().map(|_| ()).map_err(|e| e.to_string())
423        });
424        if let Err(e) = result {
425            out.push(format!("{} ({e})", db.display()));
426        }
427    };
428    for install in installs {
429        for version in &install.versions {
430            // An objects.db older than `db_agents.slug` holds no slug: only a
431            // database that can't be read at all blocks (#5342).
432            probe(&version.objects_db(), "SELECT name FROM sqlite_master LIMIT 1", &mut out);
433        }
434        if let Some(wan) = install.wan_db() {
435            probe(&wan, "SELECT name FROM sqlite_master LIMIT 1", &mut out);
436        }
437    }
438    for db in home.host_stores(installs) {
439        probe(&db, "SELECT name FROM sqlite_master LIMIT 1", &mut out);
440    }
441    out
442}
443
444fn bare(f: &Found) -> ForkSlugCandidate {
445    ForkSlugCandidate {
446        uid: f.def.uid.clone(),
447        name: f.def.name.clone(),
448        old_slug: f.def.slug.clone(),
449        new_slug: f.new_slug.clone(),
450        refused: None,
451        suggestion: None,
452        locations: Vec::new(),
453        running: Vec::new(),
454    }
455}
456
457/// The first of `target-2`, `target-3`, … nobody holds. Suggested, never
458/// taken: a collision suffix is the user's choice (§5.1).
459fn suggest(
460    home: &Home,
461    installs: &[Install],
462    defs: &[Def],
463    taken: &BTreeMap<String, String>,
464    uid: &str,
465    target: &str,
466) -> Result<Option<String>, String> {
467    for n in 2..100 {
468        let next = format!("{target}-{n}");
469        if is_agent_id(&next) && holder_of(home, installs, defs, taken, uid, &next)?.is_none() {
470            return Ok(Some(next));
471        }
472    }
473    Ok(None)
474}
475
476fn summary(candidates: &[ForkSlugCandidate], skipped: &[ForkSlugSkipped], blockers: &[ForkSlugBlocker], duplicates: &[ForkSlugDuplicate]) -> String {
477    let ready = candidates.iter().filter(|c| c.refused.is_none()).count();
478    let mut lines = Vec::new();
479    if candidates.is_empty() {
480        lines.push("No agent has an outdated id.".to_string());
481    } else {
482        lines.push(format!(
483            "{} agent{} {} an outdated id; {ready} can be updated now.",
484            candidates.len(),
485            if candidates.len() == 1 { "" } else { "s" },
486            if candidates.len() == 1 { "has" } else { "have" },
487        ));
488    }
489    for c in candidates {
490        match &c.refused {
491            None => lines.push(format!("  {} : {} -> {}", c.name, c.old_slug, c.new_slug)),
492            Some(why) => lines.push(format!("  {} : {} -> {} refused: {why}", c.name, c.old_slug, c.new_slug)),
493        }
494    }
495    if !skipped.is_empty() {
496        lines.push(format!("{} fork{} left alone (not a pre-fix chain).", skipped.len(), if skipped.len() == 1 { "" } else { "s" }));
497    }
498    for b in blockers {
499        lines.push(format!("Blocked: {}", b.message));
500    }
501    for d in duplicates {
502        lines.push(format!("{} agents share the id {} (an update doesn't change it):", d.holders.len(), d.slug));
503        for (i, h) in d.holders.iter().enumerate() {
504            let what = match (i, &h.proposed) {
505                (0, _) => "keeps it, as the oldest".to_string(),
506                (_, Some(p)) => format!("could be renamed to {p}"),
507                (_, None) => "needs a new id".to_string(),
508            };
509            lines.push(format!("  {} ({}, {}): {what}", h.name, h.uid, h.place));
510        }
511    }
512    lines.join("\n")
513}