Skip to main content

agentmux_srv_core/backend/slug_migration/
duplicates.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The plan's report of slugs more than one agent holds (two uids, one
5//! slug). New agents can't get one any more (`HostSlugs` and the shared
6//! definitions are checked under the slug allocation lock), but builds before
7//! that left some: an agent made in each of two channels picked the same slug,
8//! unique in its own `objects.db`, and both were published. Reported, with
9//! the id a rename could give each holder after the oldest; nothing here
10//! renames anything.
11
12use std::collections::{BTreeMap, HashSet};
13
14use super::home::{fold, has_agent_slugs, has_column, open_ro, place, Home, Install};
15use super::plan::{holder_of, Def};
16use crate::backend::rpc_types::{ForkSlugDuplicate, ForkSlugDuplicateHolder};
17use agentmux_common::slug::is_agent_id;
18
19/// Every slug held by more than one agent: each agent's slug is its shared
20/// definition's (the one every reader gives), else its row's for an agent
21/// never published. With `read_stores`, every `objects.db` is read for those
22/// rows and each later holder gets a proposed id, checked by `holder_of`
23/// against everything a run checks and against `taken` (ids this plan already
24/// gives); without it, only the shared definitions are compared.
25pub(super) fn duplicates(
26    home: &Home,
27    installs: &[Install],
28    defs: &[Def],
29    taken: &BTreeMap<String, String>,
30    read_stores: bool,
31) -> Vec<ForkSlugDuplicate> {
32    let mut by_slug: BTreeMap<String, Vec<ForkSlugDuplicateHolder>> = BTreeMap::new();
33    let mut add = |slug: &str, holder: ForkSlugDuplicateHolder| {
34        let holders = by_slug.entry(fold(slug)).or_default();
35        if !holders.iter().any(|h| h.uid == holder.uid) {
36            holders.push(holder);
37        }
38    };
39    for d in defs.iter().filter(|d| !d.slug.trim().is_empty()) {
40        add(&d.slug, holder(&d.uid, &d.name, d.created_at, "the shared definitions"));
41    }
42    if read_stores {
43        let published: HashSet<&str> = defs.iter().map(|d| d.uid.as_str()).collect();
44        let retired = home.definitions().join("retired");
45        for install in installs {
46            for version in &install.versions {
47                for (uid, name, slug, created_at) in unpublished_rows(&version.objects_db()) {
48                    // A row of a deleted agent another channel kept isn't an agent.
49                    if published.contains(uid.as_str()) || retired.join(format!("{uid}.json")).exists() {
50                        continue;
51                    }
52                    add(&slug, holder(&uid, &name, created_at, &place(install, version)));
53                }
54            }
55        }
56    }
57    let mut taken = taken.clone();
58    let mut out = Vec::new();
59    for (slug, mut holders) in by_slug.into_iter().filter(|(_, h)| h.len() > 1) {
60        holders.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.uid.cmp(&b.uid)));
61        if read_stores {
62            for h in holders.iter_mut().skip(1) {
63                h.proposed = propose(home, installs, defs, &taken, &h.uid, &slug);
64                if let Some(p) = &h.proposed {
65                    taken.insert(fold(p), h.uid.clone());
66                }
67            }
68        }
69        out.push(ForkSlugDuplicate { slug, holders });
70    }
71    out
72}
73
74fn holder(uid: &str, name: &str, created_at: i64, place: &str) -> ForkSlugDuplicateHolder {
75    ForkSlugDuplicateHolder {
76        uid: uid.to_string(),
77        name: name.to_string(),
78        created_at,
79        place: place.to_string(),
80        proposed: None,
81    }
82}
83
84/// `(uid, name, slug, created_at)` of every row with a slug in `db`. A store
85/// that can't be read gives none: the plan already blocks on it.
86fn unpublished_rows(db: &std::path::Path) -> Vec<(String, String, String, i64)> {
87    let Ok(conn) = open_ro(db) else { return Vec::new() };
88    if !has_agent_slugs(&conn) {
89        return Vec::new();
90    }
91    let col = |c: &str, default: &str| if has_column(&conn, "db_agents", c) { c.to_string() } else { default.to_string() };
92    let sql = format!(
93        "SELECT id, COALESCE({}, ''), slug, COALESCE({}, 0) FROM db_agents WHERE slug IS NOT NULL AND trim(slug) <> ''",
94        col("name", "''"),
95        col("created_at", "0"),
96    );
97    let Ok(mut stmt) = conn.prepare(&sql) else { return Vec::new() };
98    let Ok(rows) = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))) else { return Vec::new() };
99    rows.flatten().collect()
100}
101
102/// The first free id after `slug` for `uid`: `claude-2` → `claude-3`,
103/// `forklead` → `forklead-2`.
104fn propose(
105    home: &Home,
106    installs: &[Install],
107    defs: &[Def],
108    taken: &BTreeMap<String, String>,
109    uid: &str,
110    slug: &str,
111) -> Option<String> {
112    let (stem, first) = match slug.rsplit_once('-') {
113        Some((stem, n)) if !stem.is_empty() && !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => {
114            (stem, n.parse::<u32>().ok()?.checked_add(1)?)
115        }
116        _ => (slug, 2),
117    };
118    (first..first + 100)
119        .map(|n| format!("{stem}-{n}"))
120        .filter(|c| is_agent_id(c))
121        .find(|c| matches!(holder_of(home, installs, defs, taken, uid, c), Ok(None)))
122}