Skip to main content

agentmux_srv_core/registry/
def_migrate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Global migration: backfill user-agent DEFINITIONS (with their content +
5//! skills) from every channel's per-version `objects.db` — and every `dev/`
6//! branch DB — into the GLOBAL definition store, so EXISTING agents become
7//! cross-channel without waiting for the next edit. Read-only on every scanned
8//! SQLite.
9//!
10//! **Version-gated, re-runnable marker** (not strictly one-shot): the
11//! `.migrated_definitions` marker in the store root records the
12//! [`MIGRATION_VERSION`] that last ran. A marker older than the current version
13//! — including the legacy `migrated` text, which parses as version 0 — re-runs
14//! the scan ONCE, so users whose earlier pass was incomplete recover
15//! automatically on the next launch. Bump [`MIGRATION_VERSION`] whenever the
16//! scan logic changes to trigger a one-time re-run for everyone.
17//!
18//! On a re-run, an agent already in the global store is refreshed only when the
19//! scanned copy is strictly fresher than the global record (so a broken earlier
20//! pass's stale/content-less copy is corrected) — never downgraded below what
21//! the live write-mirror has since advanced, and never resurrected if
22//! tombstoned. (codex P1 / reagent P2 #1391.)
23//!
24//! Cross-channel agent persistence, P0.2d
25//! (`docs/specs/SPEC_CROSS_CHANNEL_AGENT_PERSISTENCE_2026-06-13.md`).
26//!
27//! Resilience mirrors `scripts/import-agents.sh`: a single unreadable / locked
28//! / old-schema `objects.db` is skipped with a warning, never aborting the
29//! pass. The marker is written after a pass even if some DBs were skipped — a
30//! transiently-skipped DB's agents still go global on their next edit via the
31//! live write-mirror (P0.2b), and a future [`MIGRATION_VERSION`] bump re-scans
32//! everything — so nothing is permanently lost and the migration never loops
33//! forever on a permanent old-schema failure.
34
35use std::collections::{HashMap, HashSet};
36use std::path::{Path, PathBuf};
37
38use rusqlite::{Connection, OpenFlags};
39
40use super::def_schema::{
41    DefContentBlob, DefSkillBlob, DefinitionRecord, DefinitionRecordV1, DEF_MAX_SUPPORTED_SCHEMA,
42};
43use super::def_store::{DefStoreError, DefinitionStore};
44
45const MARKER: &str = ".migrated_definitions";
46
47/// Migration-logic version. Bump whenever the scan changes (new roots, schema
48/// handling, etc.) so existing users re-run the migration ONCE: the marker
49/// stores this number; a marker older than this re-runs. The pre-v2 marker
50/// held the literal text `migrated`, which parses as version 0 → re-runs,
51/// recovering everyone whose first pass was incomplete.
52///
53/// v2 — schema-resilient column handling (missing columns no longer skip a
54/// whole DB), scans `dev/` branches too, and a recoverable versioned marker.
55/// See `docs/analysis/ANALYSIS_CROSS_CHANNEL_AGENT_RETENTION_2026_06_13.md`.
56const MIGRATION_VERSION: u32 = 2;
57
58/// `db_agent_definitions` columns in the order the row mapper expects, paired
59/// with a default SQL literal used when a column is absent on an older DB.
60/// Substituting `<default> AS <col>` keeps the SELECT's column count + order
61/// fixed (so index-based `row.get` stays valid) while tolerating schema drift.
62const DEF_COLUMNS: &[(&str, &str)] = &[
63    ("id", "''"),
64    ("slug", "''"),
65    ("name", "''"),
66    ("icon", "''"),
67    ("provider", "''"),
68    ("description", "''"),
69    ("working_directory", "''"),
70    ("shell", "''"),
71    ("provider_flags", "''"),
72    ("auto_start", "0"),
73    ("restart_on_crash", "0"),
74    ("idle_timeout_minutes", "0"),
75    ("created_at", "0"),
76    ("agent_type", "'host'"),
77    ("environment", "''"),
78    ("agent_bus_id", "''"),
79    ("is_seeded", "0"),
80    ("accounts", "''"),
81    ("parent_id", "''"),
82    ("branch_label", "''"),
83    ("updated_at", "0"),
84    ("user_hidden", "0"),
85    ("container_image", "''"),
86    ("container_volumes", "'[]'"),
87    ("container_name", "''"),
88    ("use_ambient_login", "0"),
89];
90
91/// Outcome stats — surfaced in the srv log.
92#[derive(Debug, Default, Clone, Copy)]
93pub struct DefMigrateStats {
94    pub dbs_scanned: usize,
95    pub dbs_skipped: usize,
96    pub rows_seen: usize,
97    pub records_written: usize,
98    pub records_skipped_existing: usize,
99    /// Agents whose slug another agent already held: not published.
100    pub records_skipped_slug_taken: usize,
101}
102
103/// Scan every channel AND dev-branch `objects.db` under `home` for user agents
104/// and backfill them into the global definition `store`. Re-runs once per
105/// [`MIGRATION_VERSION`] bump (marker in `store.root()`); read-only on every
106/// scanned SQLite, and tolerant of older schemas (missing columns).
107pub fn migrate_definitions_global_once(
108    home: &Path,
109    store: &DefinitionStore,
110) -> Result<DefMigrateStats, DefStoreError> {
111    let mut stats = DefMigrateStats::default();
112    let marker = store.root().join(MARKER);
113    if marker_version(&marker) >= MIGRATION_VERSION {
114        return Ok(stats);
115    }
116
117    // Dedup across channels/versions/dev-branches: keep the copy with the
118    // highest FRESHNESS = max(def.updated_at, content.updated_at,
119    // skill.created_at). `agent_content_set` bumps the content row's timestamp
120    // without touching the definition row, so comparing definition timestamps
121    // alone could keep a stale content/skills snapshot. (codex P1.)
122    let mut best: HashMap<String, (DefinitionRecord, i64)> = HashMap::new();
123    for db in collect_scan_dbs(home) {
124        stats.dbs_scanned += 1;
125        match read_user_definitions(&db) {
126            Ok(recs) => {
127                for (rec, freshness) in recs {
128                    stats.rows_seen += 1;
129                    let id = rec.data.id.clone();
130                    let keep = match best.get(&id) {
131                        Some((_, f)) => freshness > *f,
132                        None => true,
133                    };
134                    if keep {
135                        best.insert(id, (rec, freshness));
136                    }
137                }
138            }
139            Err(e) => {
140                stats.dbs_skipped += 1;
141                tracing::warn!(
142                    db = %db.display(),
143                    error = %e,
144                    "def migrate: skipping unreadable/incompatible objects.db"
145                );
146            }
147        }
148    }
149    // One slug, one published agent: two channels can each hold a different
150    // agent under one slug (`claude-2` beside the `claude` template). The
151    // oldest keeps it; a later one stays its channel's alone, and the plan
152    // reports it.
153    let _allocating = match store.lock_slug_allocation() {
154        Ok(lock) => Some(lock),
155        Err(e) => {
156            tracing::warn!(error = %e, "def migrate: slug allocation lock not taken; checking slugs without it");
157            None
158        }
159    };
160    // The strict index, as every allocation reads: a newer-schema record's
161    // slugs count. When a record can't be read, no slug is known to be free,
162    // so this pass publishes none (`None`); the agents it holds back go global
163    // on their next edit, through the live allocation. A failed migration
164    // stops srv starting, so one bad file mustn't fail it.
165    let mut holders: Option<HashMap<String, String>> = match store.slug_index_strict() {
166        Ok(index) => {
167            let mut held = HashMap::new();
168            for (uid, names) in index {
169                for s in std::iter::once(&names.slug).chain(&names.former) {
170                    let folded = s.trim().to_lowercase();
171                    if !folded.is_empty() {
172                        held.entry(folded).or_insert_with(|| uid.clone());
173                    }
174                }
175            }
176            Some(held)
177        }
178        Err(e) => {
179            tracing::warn!(error = %e, "def migrate: a definition can't be read; publishing no new slug this pass");
180            None
181        }
182    };
183    let mut ordered: Vec<(String, (DefinitionRecord, i64))> = best.into_iter().collect();
184    ordered.sort_by(|(a_id, (a, _)), (b_id, (b, _))| a.data.created_at.cmp(&b.data.created_at).then_with(|| a_id.cmp(b_id)));
185    for (id, (mut rec, freshness)) in ordered {
186        // Decide whether to write based on freshness vs any existing global
187        // record:
188        //   - absent              → backfill (new agent).
189        //   - present & OLDER      → refresh. A broken earlier pass may have
190        //     written a stale or content-less copy globally while a fresher
191        //     channel/dev DB holds the real one; the recovery re-run must
192        //     correct it. (codex P1.)
193        //   - present & not-older  → skip. The live write-mirror advances the
194        //     global record without touching any channel's SQLite, so a
195        //     channel-DB copy can be staler than what's already global — never
196        //     downgrade it. (reagent P2.)
197        // `upsert` additionally refuses to resurrect a tombstoned id.
198        //
199        // Freshness comparison: the scanned side is max(def, content, skill)
200        // timestamps; the in-memory global record only carries `updated_at`
201        // (its content/skill blobs are timestamp-less), so we compare against
202        // that. The asymmetry biases toward refreshing on a recovery run, which
203        // is the safe direction, and still never downgrades a genuinely-newer
204        // global `updated_at`.
205        let existing_slug = match store.get(&id) {
206            Ok(Some(existing)) => {
207                if freshness <= existing.data.updated_at {
208                    stats.records_skipped_existing += 1;
209                    continue;
210                }
211                // else: scanned copy is strictly fresher → fall through to upsert.
212                Some(existing.data.slug)
213            }
214            Ok(None) => None,
215            Err(e) => {
216                tracing::warn!(def_id = %id, error = %e, "def migrate: get failed; skipping");
217                continue;
218            }
219        };
220        // `upsert` keeps a record's slug; only one without a slug takes this.
221        let folded = rec.data.slug.trim().to_lowercase();
222        let publishes = existing_slug.as_ref().is_none_or(|s| s.trim().is_empty()) && !folded.is_empty();
223        let holder = match &holders {
224            Some(held) => held.get(&folded).filter(|h| h.as_str() != id).cloned(),
225            None => Some("(unknown: a definition can't be read)".to_string()),
226        };
227        if let Some(holder) = holder.filter(|_| publishes) {
228            tracing::warn!(
229                def_id = %id,
230                slug = %rec.data.slug,
231                holder = %holder,
232                "def migrate: another agent holds this slug; not publishing it"
233            );
234            stats.records_skipped_slug_taken += 1;
235            if existing_slug.is_none() {
236                continue;
237            }
238            rec.data.slug.clear();
239        }
240        match store.upsert(&rec) {
241            Ok(()) => {
242                stats.records_written += 1;
243                if let Some(held) = holders.as_mut().filter(|_| publishes && !rec.data.slug.is_empty()) {
244                    held.entry(folded).or_insert_with(|| id.clone());
245                }
246            }
247            Err(e) => {
248                tracing::warn!(error = %e, "def migrate: upsert into global store failed")
249            }
250        }
251    }
252
253    // Record the migration version. A DB skipped this pass (genuinely
254    // corrupt/locked — now rare since v2 tolerates schema drift) still goes
255    // global on its next edit via the live write-mirror (P0.2b), and a future
256    // MIGRATION_VERSION bump re-scans everything — so nothing is permanently
257    // lost and we never loop on a permanent failure.
258    write_marker(&marker, MIGRATION_VERSION)?;
259    Ok(stats)
260}
261
262/// Migration version recorded in the marker; `0` when absent or unparseable
263/// (the legacy `migrated` text → 0 → re-run).
264fn marker_version(marker: &Path) -> u32 {
265    std::fs::read_to_string(marker)
266        .ok()
267        .and_then(|s| s.trim().parse::<u32>().ok())
268        .unwrap_or(0)
269}
270
271/// Every `…/data/db/objects.db` under `home/channels/*/versions/*` AND
272/// `home/dev/<branch>[/<sub>]`. The instance migration scans both
273/// (`migrate.rs::enumerate_sources`); the definition migration must too, or
274/// dev-branch agents (e.g. agents created via `task dev`) never go global.
275fn collect_scan_dbs(home: &Path) -> Vec<PathBuf> {
276    let mut dbs = Vec::new();
277    let mut add = |dir: &Path| {
278        let db = dir.join("data").join("db").join("objects.db");
279        if db.is_file() {
280            dbs.push(db);
281        }
282    };
283    // Installed/portable: channels/<ch>/versions/<v>/data/db/objects.db
284    for ch in dir_subdirs(&home.join("channels")) {
285        for v in dir_subdirs(&ch.join("versions")) {
286            add(&v);
287        }
288    }
289    // Dev: dev/<branch>[/<sub>]/data/db/objects.db (both layouts).
290    for br in dir_subdirs(&home.join("dev")) {
291        add(&br);
292        for sub in dir_subdirs(&br) {
293            add(&sub);
294        }
295    }
296    dbs
297}
298
299/// Read all `is_seeded=0` definitions from `db` with their content + skills,
300/// each paired with a freshness timestamp for cross-copy winner selection.
301fn read_user_definitions(db: &Path) -> Result<Vec<(DefinitionRecord, i64)>, rusqlite::Error> {
302    let conn = Connection::open_with_flags(db, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
303    // Schema-resilient: introspect the columns present and substitute a default
304    // literal for any absent on an older DB, so a missing column degrades a
305    // single field rather than skipping the whole DB (the original bug — older
306    // DBs lacked `container_image`/`_volumes`/`_name`). The column order/count
307    // stays fixed, so the index-based row mapper below remains valid.
308    let present = present_columns(&conn, "db_agent_definitions")?;
309    if present.is_empty() {
310        // No db_agent_definitions table here → no user definitions.
311        return Ok(Vec::new());
312    }
313    let select_list = DEF_COLUMNS
314        .iter()
315        .map(|(name, default)| {
316            if present.contains(*name) {
317                (*name).to_string()
318            } else {
319                format!("{default} AS {name}")
320            }
321        })
322        .collect::<Vec<_>>()
323        .join(", ");
324    // Filter seeded templates only when the column exists (pre-seeded-template
325    // DBs have no templates, so every row is a user agent).
326    let where_clause = if present.contains("is_seeded") {
327        " WHERE is_seeded = 0"
328    } else {
329        ""
330    };
331    let sql = format!("SELECT {select_list} FROM db_agent_definitions{where_clause}");
332    let defs: Vec<DefinitionRecordV1> = {
333        let mut stmt = conn.prepare(&sql)?;
334        let rows = stmt.query_map([], |row| {
335            Ok(DefinitionRecordV1 {
336                id: row.get(0)?,
337                slug: row.get(1)?,
338                name: row.get(2)?,
339                icon: row.get(3)?,
340                provider: row.get(4)?,
341                description: row.get(5)?,
342                working_directory: row.get(6)?,
343                shell: row.get(7)?,
344                provider_flags: row.get(8)?,
345                auto_start: row.get(9)?,
346                restart_on_crash: row.get(10)?,
347                idle_timeout_minutes: row.get(11)?,
348                created_at: row.get(12)?,
349                agent_type: row.get(13)?,
350                environment: row.get(14)?,
351                agent_bus_id: row.get(15)?,
352                is_seeded: row.get(16)?,
353                accounts: row.get(17)?,
354                parent_id: row.get(18)?,
355                branch_label: row.get(19)?,
356                updated_at: row.get(20)?,
357                user_hidden: row.get(21)?,
358                container_image: row.get(22)?,
359                container_volumes: row.get(23)?,
360                container_name: row.get(24)?,
361                use_ambient_login: row.get(25)?,
362                former_slugs: Vec::new(),
363                seat: None,
364                handover: None,
365                content: Vec::new(),
366                skills: Vec::new(),
367            })
368        })?;
369        rows.collect::<Result<Vec<_>, _>>()?
370    };
371
372    let mut out = Vec::with_capacity(defs.len());
373    for mut d in defs {
374        // Content/skills tables are absent on pre-v2 DBs — tolerate THAT, but
375        // propagate a genuine error (lock/corrupt) so the whole DB is skipped
376        // rather than silently writing an instruction-less record. (codex P2.)
377        d.content = tolerate_missing_table(read_content(&conn, &d.id))?;
378        d.skills = tolerate_missing_table(read_skills(&conn, &d.id))?;
379        let content_max = max_ts(
380            &conn,
381            "SELECT MAX(updated_at) FROM db_agent_content WHERE agent_id = ?1",
382            &d.id,
383        )?;
384        let skill_max = max_ts(
385            &conn,
386            "SELECT MAX(created_at) FROM db_agent_skills WHERE agent_id = ?1",
387            &d.id,
388        )?;
389        let freshness = d.updated_at.max(content_max).max(skill_max);
390        out.push((
391            DefinitionRecord {
392                schema_version: DEF_MAX_SUPPORTED_SCHEMA,
393                data: d,
394            },
395            freshness,
396        ));
397    }
398    Ok(out)
399}
400
401/// True iff the error is SQLite "no such table" (a pre-v2 DB missing
402/// db_agent_content / db_agent_skills) — the only failure we treat as "no
403/// rows" rather than a reason to skip the DB.
404fn is_missing_table(e: &rusqlite::Error) -> bool {
405    matches!(e, rusqlite::Error::SqliteFailure(_, Some(msg)) if msg.contains("no such table"))
406}
407
408fn tolerate_missing_table<T: Default>(r: Result<T, rusqlite::Error>) -> Result<T, rusqlite::Error> {
409    match r {
410        Ok(v) => Ok(v),
411        Err(ref e) if is_missing_table(e) => Ok(T::default()),
412        Err(e) => Err(e),
413    }
414}
415
416/// `MAX(col)` over a per-agent table; `0` when the table is missing (pre-v2)
417/// or there are no rows. Other errors propagate (→ DB skipped).
418fn max_ts(conn: &Connection, sql: &str, agent_id: &str) -> Result<i64, rusqlite::Error> {
419    match conn.query_row(sql, [agent_id], |row| row.get::<_, Option<i64>>(0)) {
420        Ok(v) => Ok(v.unwrap_or(0)),
421        Err(ref e) if is_missing_table(e) => Ok(0),
422        Err(e) => Err(e),
423    }
424}
425
426fn read_content(conn: &Connection, agent_id: &str) -> Result<Vec<DefContentBlob>, rusqlite::Error> {
427    let mut stmt =
428        conn.prepare("SELECT content_type, content FROM db_agent_content WHERE agent_id = ?1")?;
429    let rows = stmt.query_map([agent_id], |row| {
430        Ok(DefContentBlob {
431            content_type: row.get(0)?,
432            content: row.get(1)?,
433        })
434    })?;
435    rows.collect()
436}
437
438fn read_skills(conn: &Connection, agent_id: &str) -> Result<Vec<DefSkillBlob>, rusqlite::Error> {
439    let mut stmt = conn.prepare(
440        "SELECT id, name, trigger, skill_type, description, content
441         FROM db_agent_skills WHERE agent_id = ?1",
442    )?;
443    let rows = stmt.query_map([agent_id], |row| {
444        Ok(DefSkillBlob {
445            id: row.get(0)?,
446            name: row.get(1)?,
447            trigger: row.get(2)?,
448            skill_type: row.get(3)?,
449            description: row.get(4)?,
450            content: row.get(5)?,
451        })
452    })?;
453    rows.collect()
454}
455
456fn dir_subdirs(dir: &Path) -> Vec<PathBuf> {
457    let Ok(rd) = std::fs::read_dir(dir) else {
458        return Vec::new();
459    };
460    rd.flatten()
461        .map(|e| e.path())
462        .filter(|p| p.is_dir())
463        .collect()
464}
465
466fn write_marker(path: &Path, version: u32) -> Result<(), DefStoreError> {
467    std::fs::write(path, version.to_string().as_bytes())?;
468    Ok(())
469}
470
471/// Column names present in `table` (empty set if the table doesn't exist —
472/// `PRAGMA table_info` on a missing table yields no rows, not an error).
473fn present_columns(conn: &Connection, table: &str) -> Result<HashSet<String>, rusqlite::Error> {
474    let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
475    let rows = stmt.query_map([], |row| row.get::<_, String>(1))?;
476    rows.collect()
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482    use rusqlite::params;
483
484    /// Create the current (v2) schema at `db`.
485    fn create_full_schema(db: &Path) {
486        let conn = Connection::open(db).unwrap();
487        conn.execute_batch(
488            "CREATE TABLE db_agent_definitions (
489                id TEXT, slug TEXT, name TEXT, icon TEXT, provider TEXT, description TEXT,
490                working_directory TEXT, shell TEXT, provider_flags TEXT, auto_start INTEGER,
491                restart_on_crash INTEGER, idle_timeout_minutes INTEGER, created_at INTEGER,
492                agent_type TEXT, environment TEXT, agent_bus_id TEXT, is_seeded INTEGER,
493                accounts TEXT, parent_id TEXT, branch_label TEXT, updated_at INTEGER,
494                user_hidden INTEGER, container_image TEXT, container_volumes TEXT, container_name TEXT);
495             CREATE TABLE db_agent_content (agent_id TEXT, content_type TEXT, content TEXT, updated_at INTEGER);
496             CREATE TABLE db_agent_skills (id TEXT, agent_id TEXT, name TEXT, trigger TEXT, skill_type TEXT, description TEXT, content TEXT, created_at INTEGER);",
497        )
498        .unwrap();
499    }
500
501    fn db_at(dir: PathBuf) -> PathBuf {
502        std::fs::create_dir_all(&dir).unwrap();
503        let db = dir.join("objects.db");
504        create_full_schema(&db);
505        db
506    }
507
508    fn make_channel_db(home: &Path, channel: &str, version: &str) -> PathBuf {
509        db_at(home
510            .join("channels")
511            .join(channel)
512            .join("versions")
513            .join(version)
514            .join("data")
515            .join("db"))
516    }
517
518    fn insert_user_agent(db: &Path, id: &str, name: &str, updated_at: i64) {
519        let conn = Connection::open(db).unwrap();
520        conn.execute(
521            "INSERT INTO db_agent_definitions (id, slug, name, icon, provider, description,
522                working_directory, shell, provider_flags, auto_start, restart_on_crash,
523                idle_timeout_minutes, created_at, agent_type, environment, agent_bus_id, is_seeded,
524                accounts, parent_id, branch_label, updated_at, user_hidden, container_image,
525                container_volumes, container_name)
526             VALUES (?1, ?1, ?2, '✦', 'claude', '', '', '', '', 0, 0, 0, 1, 'host', '', '', 0,
527                     '', '', '', ?3, 0, '', '[]', '')",
528            params![id, name, updated_at],
529        )
530        .unwrap();
531        conn.execute(
532            "INSERT INTO db_agent_content (agent_id, content_type, content, updated_at)
533             VALUES (?1, 'agentmd', 'instructions', 1)",
534            params![id],
535        )
536        .unwrap();
537        conn.execute(
538            "INSERT INTO db_agent_skills (id, agent_id, name, trigger, skill_type, description, content, created_at)
539             VALUES ('sk1', ?1, 'greet', '', 'prompt', '', '', 1)",
540            params![id],
541        )
542        .unwrap();
543    }
544
545    fn store_at(home: &Path) -> DefinitionStore {
546        DefinitionStore::open(home.join("shared").join("agents").join("definitions")).unwrap()
547    }
548
549    #[test]
550    fn migrates_user_agents_with_content_and_skills_and_is_idempotent() {
551        let tmp = tempfile::tempdir().unwrap();
552        let home = tmp.path();
553        let db = make_channel_db(home, "local-a-aaa", "0.44.1");
554        insert_user_agent(&db, "agent-1", "Maks", 100);
555        let store = store_at(home);
556
557        let stats = migrate_definitions_global_once(home, &store).unwrap();
558        assert_eq!(stats.records_written, 1);
559        let rec = store.get("agent-1").unwrap().unwrap();
560        assert_eq!(rec.data.name, "Maks");
561        assert_eq!(rec.data.content.len(), 1, "content backfilled");
562        assert_eq!(rec.data.skills.len(), 1, "skills backfilled");
563
564        // Second run is a no-op (marker present).
565        let stats2 = migrate_definitions_global_once(home, &store).unwrap();
566        assert_eq!(stats2.dbs_scanned, 0);
567        assert_eq!(stats2.records_written, 0);
568    }
569
570    #[test]
571    fn skips_seeded_and_dedups_by_latest_freshness() {
572        let tmp = tempfile::tempdir().unwrap();
573        let home = tmp.path();
574        // Same id in two channels with different updated_at → freshest wins.
575        let db_a = make_channel_db(home, "ch-a", "0.44.1");
576        insert_user_agent(&db_a, "dup", "Old", 100);
577        let db_b = make_channel_db(home, "ch-b", "0.44.1");
578        insert_user_agent(&db_b, "dup", "New", 200);
579        // A seeded template — must NOT migrate.
580        Connection::open(&db_a)
581            .unwrap()
582            .execute(
583                "INSERT INTO db_agent_definitions (id, slug, name, provider, is_seeded, container_volumes)
584                 VALUES ('tpl', 'tpl', 'Claude', 'claude', 1, '[]')",
585                [],
586            )
587            .unwrap();
588
589        let store = store_at(home);
590        let stats = migrate_definitions_global_once(home, &store).unwrap();
591        assert_eq!(
592            store.get("dup").unwrap().unwrap().data.name,
593            "New",
594            "latest freshness wins across channels"
595        );
596        assert!(store.get("tpl").unwrap().is_none(), "seeded template not migrated");
597        assert_eq!(stats.records_written, 1);
598    }
599
600    #[test]
601    fn does_not_downgrade_an_existing_global_record() {
602        let tmp = tempfile::tempdir().unwrap();
603        let home = tmp.path();
604        // The channel DB has the OLD copy.
605        let db = make_channel_db(home, "ch-a", "0.44.1");
606        insert_user_agent(&db, "dup", "OldName", 100);
607        let store = store_at(home);
608        // The global store already has a NEWER copy (e.g. the live mirror
609        // advanced it via a cross-channel edit that never touched the DB).
610        store
611            .upsert(&DefinitionRecord {
612                schema_version: DEF_MAX_SUPPORTED_SCHEMA,
613                data: DefinitionRecordV1 {
614                    id: "dup".to_string(),
615                    name: "NewName".to_string(),
616                    provider: "claude".to_string(),
617                    updated_at: 500,
618                    ..Default::default()
619                },
620            })
621            .unwrap();
622
623        let stats = migrate_definitions_global_once(home, &store).unwrap();
624        assert_eq!(
625            store.get("dup").unwrap().unwrap().data.name,
626            "NewName",
627            "migration must NOT downgrade the newer global record"
628        );
629        assert_eq!(stats.records_written, 0);
630        assert_eq!(stats.records_skipped_existing, 1);
631    }
632
633    #[test]
634    fn refreshes_a_stale_global_record_on_rerun() {
635        let tmp = tempfile::tempdir().unwrap();
636        let home = tmp.path();
637        // The channel DB holds a FRESHER copy (updated_at=300).
638        let db = make_channel_db(home, "ch-a", "0.44.1");
639        insert_user_agent(&db, "dup", "FreshName", 300);
640        let store = store_at(home);
641        // The global store holds a STALE copy a broken earlier pass wrote
642        // (older updated_at, e.g. content-less). The recovery re-run must
643        // REFRESH it from the fresher scan rather than skip it. (codex P1.)
644        store
645            .upsert(&DefinitionRecord {
646                schema_version: DEF_MAX_SUPPORTED_SCHEMA,
647                data: DefinitionRecordV1 {
648                    id: "dup".to_string(),
649                    name: "StaleName".to_string(),
650                    provider: "claude".to_string(),
651                    updated_at: 50,
652                    ..Default::default()
653                },
654            })
655            .unwrap();
656
657        let stats = migrate_definitions_global_once(home, &store).unwrap();
658        let rec = store.get("dup").unwrap().unwrap();
659        assert_eq!(rec.data.name, "FreshName", "stale global record must be refreshed from the fresher scan");
660        assert_eq!(rec.data.content.len(), 1, "content backfilled on refresh");
661        assert_eq!(stats.records_written, 1);
662        assert_eq!(stats.records_skipped_existing, 0);
663    }
664
665    #[test]
666    fn winner_selection_includes_content_freshness() {
667        let tmp = tempfile::tempdir().unwrap();
668        let home = tmp.path();
669        // Copy A: newer DEFINITION timestamp, old content.
670        let db_a = make_channel_db(home, "ch-a", "0.44.2");
671        insert_user_agent(&db_a, "dup", "FromA", 300);
672        // Copy B: older definition timestamp, but content edited later
673        // (agent_content_set bumps content.updated_at, not the def row).
674        let db_b = make_channel_db(home, "ch-b", "0.44.1");
675        insert_user_agent(&db_b, "dup", "FromB", 200);
676        Connection::open(&db_b)
677            .unwrap()
678            .execute(
679                "UPDATE db_agent_content SET content = 'fresh', updated_at = 900 WHERE agent_id = 'dup'",
680                [],
681            )
682            .unwrap();
683
684        let store = store_at(home);
685        migrate_definitions_global_once(home, &store).unwrap();
686        let rec = store.get("dup").unwrap().unwrap();
687        assert_eq!(rec.data.name, "FromB", "copy with freshest content wins");
688        assert_eq!(rec.data.content[0].content, "fresh");
689    }
690
691    #[test]
692    fn migrates_db_missing_container_columns() {
693        // F1: an older DB without container_image/_volumes/_name (and without
694        // the content/skills tables) must NOT be skipped — the missing columns
695        // degrade to defaults.
696        let tmp = tempfile::tempdir().unwrap();
697        let home = tmp.path();
698        let db_dir = home
699            .join("channels")
700            .join("old-ch")
701            .join("versions")
702            .join("0.40.0")
703            .join("data")
704            .join("db");
705        std::fs::create_dir_all(&db_dir).unwrap();
706        let db = db_dir.join("objects.db");
707        let conn = Connection::open(&db).unwrap();
708        conn.execute_batch(
709            "CREATE TABLE db_agent_definitions (
710                id TEXT, slug TEXT, name TEXT, icon TEXT, provider TEXT, description TEXT,
711                working_directory TEXT, shell TEXT, provider_flags TEXT, auto_start INTEGER,
712                restart_on_crash INTEGER, idle_timeout_minutes INTEGER, created_at INTEGER,
713                agent_type TEXT, environment TEXT, agent_bus_id TEXT, is_seeded INTEGER,
714                accounts TEXT, parent_id TEXT, branch_label TEXT, updated_at INTEGER,
715                user_hidden INTEGER);",
716        )
717        .unwrap();
718        // All 22 present columns populated (real old DBs are NOT NULL); only
719        // the container_* columns are absent from the schema entirely.
720        conn.execute(
721            "INSERT INTO db_agent_definitions VALUES
722             ('old-1','old-1','OldAgent','✦','claude','','','','',0,0,0,1,
723              'host','','',0,'','','',50,0)",
724            [],
725        )
726        .unwrap();
727        drop(conn);
728
729        let store = store_at(home);
730        let stats = migrate_definitions_global_once(home, &store).unwrap();
731        assert_eq!(stats.dbs_skipped, 0, "old-schema DB must not be skipped");
732        assert_eq!(stats.records_written, 1, "old-schema agent migrated");
733        let rec = store.get("old-1").unwrap().unwrap();
734        assert_eq!(rec.data.name, "OldAgent");
735        assert_eq!(rec.data.container_volumes, "[]", "missing column defaulted");
736    }
737
738    #[test]
739    fn scans_dev_branch_agents() {
740        // F2: agents in dev/<branch>/<sub>/ must be migrated too.
741        let tmp = tempfile::tempdir().unwrap();
742        let home = tmp.path();
743        let db = db_at(
744            home.join("dev")
745                .join("main")
746                .join("abc123")
747                .join("data")
748                .join("db"),
749        );
750        insert_user_agent(&db, "dev-1", "DevAgent", 100);
751
752        let store = store_at(home);
753        let stats = migrate_definitions_global_once(home, &store).unwrap();
754        assert_eq!(stats.records_written, 1, "dev-branch agent migrated");
755        assert_eq!(store.get("dev-1").unwrap().unwrap().data.name, "DevAgent");
756    }
757
758    /// A user agent row with its own slug and creation time.
759    fn insert_slugged(db: &Path, id: &str, slug: &str, created_at: i64) {
760        insert_user_agent(db, id, "Claude", created_at);
761        Connection::open(db)
762            .unwrap()
763            .execute("UPDATE db_agent_definitions SET slug = ?2, created_at = ?3 WHERE id = ?1", params![id, slug, created_at])
764            .unwrap();
765    }
766
767    /// Two channels each holding a different agent under one slug (each
768    /// unique in its own database): the oldest is published with it, the
769    /// later isn't published at all, and neither is a slug an existing
770    /// record holds as its slug or a former slug. Case doesn't make a slug
771    /// another.
772    #[test]
773    fn a_slug_two_channels_hold_is_published_once() {
774        let tmp = tempfile::tempdir().unwrap();
775        let home = tmp.path();
776        let db_a = make_channel_db(home, "ch-a", "0.44.1");
777        let db_b = make_channel_db(home, "ch-b", "0.44.1");
778        insert_slugged(&db_b, "u-later", "Claude-2", 200);
779        insert_slugged(&db_a, "u-oldest", "claude-2", 100);
780        insert_slugged(&db_a, "u-taken", "kept", 50);
781        insert_slugged(&db_b, "u-retired-name", "old-name", 60);
782        let store = store_at(home);
783        store
784            .upsert(&DefinitionRecord {
785                schema_version: DEF_MAX_SUPPORTED_SCHEMA,
786                data: DefinitionRecordV1 {
787                    id: "u-holder".to_string(),
788                    slug: "kept".to_string(),
789                    name: "Holder".to_string(),
790                    provider: "claude".to_string(),
791                    former_slugs: vec![crate::registry::FormerSlug { slug: "old-name".to_string(), retired_at: 1 }],
792                    ..Default::default()
793                },
794            })
795            .unwrap();
796
797        let stats = migrate_definitions_global_once(home, &store).unwrap();
798        assert_eq!(store.get("u-oldest").unwrap().unwrap().data.slug, "claude-2");
799        for id in ["u-later", "u-taken", "u-retired-name"] {
800            assert!(store.get(id).unwrap().is_none(), "{id} isn't published");
801        }
802        assert_eq!(store.get("u-holder").unwrap().unwrap().data.slug, "kept");
803        assert_eq!((stats.records_written, stats.records_skipped_slug_taken), (1, 3));
804    }
805
806    /// A slug a newer version's record holds is taken, and a definition that
807    /// can't be read stops the pass publishing any slug without failing it
808    /// (a failed migration stops srv starting).
809    #[test]
810    fn newer_and_unreadable_records_keep_slugs_from_the_backfill() {
811        let tmp = tempfile::tempdir().unwrap();
812        let home = tmp.path();
813        let db = make_channel_db(home, "ch-a", "0.44.1");
814        insert_slugged(&db, "u-new", "future-held", 100);
815        let store = store_at(home);
816        let future = r#"{"schema_version":99,"data":{"id":"u-future","slug":"future-held"}}"#;
817        std::fs::write(store.root().join("u-future.json"), future).unwrap();
818
819        let stats = migrate_definitions_global_once(home, &store).unwrap();
820        assert!(store.get("u-new").unwrap().is_none(), "a newer record's slug is held");
821        assert_eq!((stats.records_written, stats.records_skipped_slug_taken), (0, 1));
822
823        let tmp = tempfile::tempdir().unwrap();
824        let home = tmp.path();
825        let db = make_channel_db(home, "ch-a", "0.44.1");
826        insert_slugged(&db, "u-free", "free-slug", 100);
827        let store = store_at(home);
828        std::fs::write(store.root().join("u-broken.json"), "{").unwrap();
829
830        let stats = migrate_definitions_global_once(home, &store).unwrap();
831        assert!(store.get("u-free").unwrap().is_none(), "no slug is known free");
832        assert_eq!((stats.records_written, stats.records_skipped_slug_taken), (0, 1));
833    }
834
835    #[test]
836    fn legacy_text_marker_triggers_rerun_then_settles() {
837        // F3/F4: the pre-v2 marker (literal "migrated") parses as version 0 →
838        // re-runs once; afterward the versioned marker makes it idempotent.
839        let tmp = tempfile::tempdir().unwrap();
840        let home = tmp.path();
841        let db = make_channel_db(home, "ch", "0.44.1");
842        insert_user_agent(&db, "a1", "A", 100);
843        let store = store_at(home);
844        std::fs::write(store.root().join(MARKER), b"migrated\n").unwrap();
845
846        let stats = migrate_definitions_global_once(home, &store).unwrap();
847        assert_eq!(stats.records_written, 1, "legacy text marker must re-run");
848        assert!(store.get("a1").unwrap().is_some());
849
850        let stats2 = migrate_definitions_global_once(home, &store).unwrap();
851        assert_eq!(stats2.dbs_scanned, 0, "versioned marker → idempotent after");
852    }
853}