Skip to main content

agentmux_srv_core/backend/storage/
agents_consolidate.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Phase 3a — one-shot backfill from `db_agent_definitions` +
5//! `db_agent_instances` into the new consolidated `db_agents` table.
6//!
7//! See `docs/specs/SPEC_AGENT_CONCEPT_CONSOLIDATION_2026_05_24.md`.
8//!
9//! Phase 3a is **write-only**: this migration populates `db_agents` so
10//! a later Phase 3b PR can flip readers over with full confidence the
11//! data is there. Phase 3c drops the old tables.
12//!
13//! Marker-file gated (`<data_dir>/migration_agents_consolidate_v1.flag`)
14//! so the backfill only runs once per data dir. Idempotent on second
15//! run (marker check short-circuits).
16//!
17//! Algorithm (per spec §"What `db_agent_instances` rows become"):
18//!
19//! 1. For each `db_agent_definitions WHERE is_seeded = 1`: INSERT a
20//!    template projection (`is_template = 1`, bindings empty).
21//!
22//! 2. For each `db_agent_definitions WHERE is_seeded = 0`: INSERT a
23//!    user-clone projection (`is_template = 0`, `parent_template_id =
24//!    parent_id`).
25//!
26//! 3. For each `db_agent_instances` row whose `definition_id` points at
27//!    a TEMPLATE: INSERT a new user-clone projection keyed by
28//!    `instance.id`, `parent_template_id = definition_id`, name +
29//!    bindings from the instance.
30//!
31//! 4. For each `db_agent_instances` row whose `definition_id` points at
32//!    an already-user-cloned definition: UPDATE the existing
33//!    user-clone projection (keyed by the definition id from pass 2) to
34//!    fold in the instance's bindings. If multiple instances point at
35//!    the same user-clone, the most-recent (`created_at` DESC) wins
36//!    and a warning is logged.
37//!
38//! Continuation rows (`parent_instance_id` non-empty) are skipped — the
39//! consolidated model has no place for them; they were the
40//! pre-Option-E continuation chain.
41
42use std::path::Path;
43
44use rusqlite::Connection;
45
46use super::error::StoreError;
47
48#[path = "agents_consolidate_steps.rs"]
49pub mod steps;
50
51/// Marker filename. Lives in the data dir (one level above the `db/`
52/// subdir that holds `objects.db`).
53pub const CONSOLIDATE_MARKER: &str = "migration_agents_consolidate_v1.flag";
54
55/// Backfill statistics — useful for logs + tests.
56#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
57pub struct ConsolidateStats {
58    pub templates_inserted: usize,
59    pub user_defs_inserted: usize,
60    pub instances_as_clone_inserted: usize,
61    pub instances_folded_into_def: usize,
62    pub instances_skipped_continuation: usize,
63    pub instances_skipped_no_definition: usize,
64    pub instances_collision_warned: usize,
65    pub already_done: bool,
66}
67
68/// True when the backfill's source tables have data but its target
69/// (`db_agents`) doesn't — i.e. a marker (or a `db_migrations` stamp) claims
70/// this migration ran, but the data it's supposed to have produced isn't
71/// there. Used to stop trusting marker/stamp *existence* as proof of
72/// *effect* (see `docs/specs/SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03.md`
73/// Phase 0a/0b) — a stale marker (rebuilt/restored `objects.db` sitting next
74/// to an old flag file, or a bootstrap stamping from a copied flag file with
75/// no matching data) is now detectable instead of silently trusted.
76///
77/// Cheap: up to three `COUNT(*)` queries, safe to call on every startup.
78///
79/// Tolerates either source table being physically absent (Phase 3e,
80/// `SPEC_AGENT_ARCHITECTURE_2026_05_27.md` — `db_agent_definitions`/
81/// `db_agent_instances` are dropped by `m0029_drop_legacy_agent_tables`):
82/// an absent table categorically has no rows, so it can never be the
83/// "source has rows but the target doesn't" shape this function detects.
84/// Load-bearing, not defensive-only — a fresh (v32+) channel is stamped
85/// `0007_agents_consolidate` applied via its own early-return no-op
86/// (`m0007_agents_consolidate.rs::up`'s `channel_store_path.exists()`
87/// guard, for a channel created before migrations ever ran), and a later
88/// `muxspect migrations --verify` doctor pass calls `m0007`'s `verify()` —
89/// which calls this — against that channel once it has real, ordinarily-
90/// populated `db_agents` data. Without this guard that doctor pass would
91/// error on "no such table" for every fresh install, not just an upgraded
92/// one that genuinely went through the old table pair.
93pub fn consolidate_looks_incomplete(conn: &Connection) -> Result<bool, StoreError> {
94    let defs = table_row_count_if_exists(conn, "db_agent_definitions")?;
95    let insts = table_row_count_if_exists(conn, "db_agent_instances")?;
96    let agents: i64 = conn.query_row("SELECT COUNT(*) FROM db_agents", [], |r| r.get(0))?;
97    Ok((defs > 0 || insts > 0) && agents == 0)
98}
99
100/// `SELECT COUNT(*) FROM <table>`, or `0` if the table doesn't exist at
101/// all — distinct from a genuinely empty table, which also counts as `0`
102/// here on purpose (both mean "no source rows to backfill").
103fn table_row_count_if_exists(conn: &Connection, table: &str) -> Result<i64, StoreError> {
104    if !crate::migrations::table_exists(conn, table)? {
105        return Ok(0);
106    }
107    Ok(conn.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0))?)
108}
109
110/// Run the one-shot consolidation backfill, gated by the marker file.
111///
112/// `data_dir` is the directory that holds the marker file (typically
113/// the parent of the `db/` directory). Pass `None` to skip marker
114/// gating — only intended for tests + in-memory stores.
115///
116/// Returns `Ok(stats)` on success (incl. the marker-already-present
117/// short-circuit). Failures roll back the active transaction and
118/// return the underlying SQLite error; the marker is NOT written.
119pub fn run_consolidate_migration(
120    conn: &mut Connection,
121    data_dir: Option<&Path>,
122) -> Result<ConsolidateStats, StoreError> {
123    if steps::marker_says_done(conn, data_dir)? {
124        return Ok(ConsolidateStats {
125            already_done: true,
126            ..Default::default()
127        });
128    }
129
130    // Nothing to consolidate FROM if neither source table exists — a fresh
131    // (v32+) channel, or one already past `m0029_drop_legacy_agent_tables`.
132    // `up()`'s own `channel_store_path.exists()` guard already keeps this
133    // from firing for a channel created after this shipped (see
134    // `consolidate_looks_incomplete`'s doc comment for the doctor-pass path
135    // that reaches this function on an EXISTING, already-migrated channel
136    // instead).
137    if !steps::definitions_table_exists(conn)? {
138        return Ok(ConsolidateStats::default());
139    }
140
141    // The backfill runs inside a transaction so a mid-flight failure
142    // leaves db_agents empty rather than half-populated. The dual-
143    // write call sites tolerate empty + idempotently upsert on the
144    // next mutation, so partial backfill state is recoverable.
145    let tx = conn.transaction()?;
146
147    let mut stats = ConsolidateStats::default();
148
149    steps::backfill_definitions(&tx, &mut stats)?;
150    let inst_rows = steps::load_instances(&tx)?;
151    steps::project_instances(&tx, &inst_rows, &mut stats)?;
152
153    tx.commit()?;
154
155    // Marker written AFTER successful commit so a crash mid-backfill
156    // leaves the marker absent → next start retries from scratch.
157    if let Some(dir) = data_dir {
158        steps::write_marker(dir);
159    }
160
161    steps::log_completed(&stats);
162    Ok(stats)
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use crate::backend::storage::migrations::run_object_schema;
169    use rusqlite::params;
170
171    /// `db_agent_definitions`/`db_agent_instances` are gone from the flat
172    /// schema as of v32 (`OBJECT_SCHEMA_VERSION`'s v32 doc comment,
173    /// `SPEC_AGENT_ARCHITECTURE_2026_05_27.md` Phase 3e) — this fixture
174    /// stands up the pre-drop legacy shape by hand, since `run_object_schema`
175    /// no longer will. Every column `insert_def`/`insert_instance` write is
176    /// present; the FK matches what the tables actually had before the
177    /// drop, so cascade behavior this module's own logic depends on
178    /// (`run_consolidate_migration` reads both, unrelated to cascades) still
179    /// matches production history.
180    fn fresh_conn() -> Connection {
181        let conn = Connection::open_in_memory().unwrap();
182        conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
183        run_object_schema(&conn).unwrap();
184        conn.execute_batch(
185            "CREATE TABLE db_agent_definitions (
186                id                   TEXT PRIMARY KEY,
187                slug                 TEXT NOT NULL DEFAULT '',
188                name                 TEXT NOT NULL,
189                icon                 TEXT NOT NULL DEFAULT '✦',
190                provider             TEXT NOT NULL,
191                description          TEXT NOT NULL DEFAULT '',
192                working_directory    TEXT NOT NULL DEFAULT '',
193                shell                TEXT NOT NULL DEFAULT '',
194                provider_flags       TEXT NOT NULL DEFAULT '',
195                auto_start           INTEGER NOT NULL DEFAULT 0,
196                restart_on_crash     INTEGER NOT NULL DEFAULT 0,
197                idle_timeout_minutes INTEGER NOT NULL DEFAULT 0,
198                agent_type           TEXT NOT NULL DEFAULT 'standalone',
199                environment          TEXT NOT NULL DEFAULT '',
200                agent_bus_id         TEXT NOT NULL DEFAULT '',
201                is_seeded            INTEGER NOT NULL DEFAULT 0,
202                accounts             TEXT NOT NULL DEFAULT '',
203                parent_id            TEXT NOT NULL DEFAULT '',
204                branch_label         TEXT NOT NULL DEFAULT '',
205                created_at           INTEGER NOT NULL DEFAULT 0,
206                updated_at           INTEGER NOT NULL DEFAULT 0,
207                user_hidden          INTEGER NOT NULL DEFAULT 0
208             );
209             CREATE TABLE db_agent_instances (
210                id                 TEXT PRIMARY KEY,
211                definition_id      TEXT NOT NULL,
212                parent_instance_id TEXT NOT NULL DEFAULT '',
213                block_id           TEXT NOT NULL DEFAULT '',
214                session_id         TEXT NOT NULL DEFAULT '',
215                status             TEXT NOT NULL DEFAULT 'running',
216                github_context     TEXT NOT NULL DEFAULT '',
217                identity_id        TEXT NOT NULL DEFAULT '',
218                memory_id          TEXT NOT NULL DEFAULT '',
219                instance_name      TEXT NOT NULL DEFAULT '',
220                working_directory  TEXT NOT NULL DEFAULT '',
221                display_hidden     INTEGER NOT NULL DEFAULT 0,
222                started_at         INTEGER NOT NULL DEFAULT 0,
223                ended_at           INTEGER NOT NULL DEFAULT 0,
224                created_at         INTEGER NOT NULL DEFAULT 0,
225                FOREIGN KEY (definition_id) REFERENCES db_agent_definitions(id) ON DELETE CASCADE
226             );",
227        )
228        .unwrap();
229        conn
230    }
231
232    fn insert_def(
233        conn: &Connection,
234        id: &str,
235        name: &str,
236        is_seeded: i64,
237        parent_id: &str,
238    ) {
239        conn.execute(
240            "INSERT INTO db_agent_definitions
241                (id, slug, name, icon, provider, description, working_directory, shell,
242                 provider_flags, auto_start, restart_on_crash, idle_timeout_minutes,
243                 created_at, agent_type, environment, agent_bus_id, is_seeded, accounts,
244                 parent_id, branch_label, updated_at)
245             VALUES (?1, ?2, ?3, '✦', 'claude', 'desc', '', 'bash',
246                     '', 0, 0, 0,
247                     ?4, 'standalone', '', '', ?5, '',
248                     ?6, '', ?4)",
249            params![id, id, name, 1000_i64, is_seeded, parent_id],
250        )
251        .unwrap();
252    }
253
254    fn insert_instance(
255        conn: &Connection,
256        id: &str,
257        definition_id: &str,
258        instance_name: &str,
259        identity_id: &str,
260        memory_id: &str,
261        working_directory: &str,
262        created_at: i64,
263        display_hidden: bool,
264    ) {
265        conn.execute(
266            "INSERT INTO db_agent_instances
267                (id, definition_id, parent_instance_id, block_id, session_id, status,
268                 github_context, started_at, ended_at, created_at, identity_id, memory_id,
269                 instance_name, working_directory, display_hidden)
270             VALUES (?1, ?2, '', '', '', 'running', '', ?3, 0, ?3, ?4, ?5, ?6, ?7, ?8)",
271            params![
272                id,
273                definition_id,
274                created_at,
275                identity_id,
276                memory_id,
277                instance_name,
278                working_directory,
279                if display_hidden { 1_i64 } else { 0_i64 },
280            ],
281        )
282        .unwrap();
283    }
284
285    fn count_agents(conn: &Connection, where_clause: &str) -> i64 {
286        let sql = format!("SELECT COUNT(*) FROM db_agents WHERE {where_clause}");
287        conn.query_row(&sql, [], |row| row.get(0)).unwrap()
288    }
289
290    #[test]
291    fn round_trip_template_user_clone_and_instance_lifecycle() {
292        let mut conn = fresh_conn();
293
294        // 2 templates, 1 user-cloned definition (from template tpl-1),
295        // 3 instances:
296        //   - inst-A on template tpl-1 (named "Maks")
297        //   - inst-B on template tpl-2 (unnamed)
298        //   - inst-C on user-clone-def def-u1 (named "Custom")
299        insert_def(&conn, "tpl-1", "Coder", 1, "");
300        insert_def(&conn, "tpl-2", "Reviewer", 1, "");
301        insert_def(&conn, "def-u1", "Maks-the-Coder", 0, "tpl-1");
302        insert_instance(&conn, "inst-A", "tpl-1", "Maks", "id-1", "mem-1", "/wd/a", 100, false);
303        insert_instance(&conn, "inst-B", "tpl-2", "", "", "", "/wd/b", 200, false);
304        insert_instance(&conn, "inst-C", "def-u1", "Custom", "id-2", "mem-2", "/wd/c", 300, false);
305
306        let stats = run_consolidate_migration(&mut conn, None).unwrap();
307        assert_eq!(stats.templates_inserted, 2);
308        assert_eq!(stats.user_defs_inserted, 1);
309        assert_eq!(stats.instances_as_clone_inserted, 2);
310        assert_eq!(stats.instances_folded_into_def, 1);
311        assert_eq!(stats.instances_skipped_continuation, 0);
312
313        // Templates present, is_template=1, parent_template_id empty.
314        assert_eq!(count_agents(&conn, "is_template = 1"), 2);
315        for tpl in &["tpl-1", "tpl-2"] {
316            let parent: String = conn
317                .query_row(
318                    "SELECT parent_template_id FROM db_agents WHERE id = ?1",
319                    params![tpl],
320                    |r| r.get(0),
321                )
322                .unwrap();
323            assert_eq!(parent, "");
324        }
325
326        // 3 user-clone rows: def-u1 (folded from inst-C), inst-A, inst-B.
327        assert_eq!(count_agents(&conn, "is_template = 0"), 3);
328
329        // inst-A → parent_template_id = tpl-1, name = "Maks".
330        let (parent, name, identity): (String, String, String) = conn
331            .query_row(
332                "SELECT parent_template_id, name, identity_id FROM db_agents WHERE id = 'inst-A'",
333                [],
334                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
335            )
336            .unwrap();
337        assert_eq!(parent, "tpl-1");
338        assert_eq!(name, "Maks");
339        assert_eq!(identity, "id-1");
340
341        // inst-B (unnamed) → name falls back to template name "Reviewer".
342        let name: String = conn
343            .query_row(
344                "SELECT name FROM db_agents WHERE id = 'inst-B'",
345                [],
346                |r| r.get(0),
347            )
348            .unwrap();
349        assert_eq!(name, "Reviewer");
350
351        // def-u1 (user-clone) folded inst-C's bindings.
352        let (name, identity, memory): (String, String, String) = conn
353            .query_row(
354                "SELECT name, identity_id, memory_id FROM db_agents WHERE id = 'def-u1'",
355                [],
356                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
357            )
358            .unwrap();
359        assert_eq!(name, "Custom"); // instance_name overrode def name
360        assert_eq!(identity, "id-2");
361        assert_eq!(memory, "mem-2");
362    }
363
364    #[test]
365    fn multiple_instances_on_one_user_clone_keeps_most_recent_bindings() {
366        let mut conn = fresh_conn();
367        insert_def(&conn, "tpl-1", "Coder", 1, "");
368        insert_def(&conn, "def-u1", "User Coder", 0, "tpl-1");
369        // Two instances on def-u1; most recent has id-RECENT.
370        insert_instance(&conn, "inst-old", "def-u1", "Old", "id-OLD", "mem-OLD", "/wd/old", 100, false);
371        insert_instance(&conn, "inst-new", "def-u1", "New", "id-RECENT", "mem-RECENT", "/wd/new", 999, false);
372
373        let stats = run_consolidate_migration(&mut conn, None).unwrap();
374        assert_eq!(stats.instances_collision_warned, 1);
375
376        let identity: String = conn
377            .query_row(
378                "SELECT identity_id FROM db_agents WHERE id = 'def-u1'",
379                [],
380                |r| r.get(0),
381            )
382            .unwrap();
383        assert_eq!(identity, "id-RECENT", "most-recent instance's bindings must win");
384    }
385
386    #[test]
387    fn fold_into_user_clone_stamps_updated_at_from_instance_created_at() {
388        // Codex P2 on PR #1110: ordering `db_agents` by `updated_at`
389        // would misbehave on migrated stores if the fold UPDATE
390        // didn't write `updated_at`. After the fix, the folded
391        // user-clone row's `updated_at` equals the most-recent
392        // instance's `created_at` (the launch moment), not the def's
393        // edit time — matching what the live launch write
394        // (`Store::instance_create`) stamps for new
395        // launches.
396        let mut conn = fresh_conn();
397        // Def created at t=1000 (insert_def uses ?4 for both
398        // created_at and updated_at).
399        insert_def(&conn, "tpl-1", "Coder", 1, "");
400        insert_def(&conn, "def-u1", "User Coder", 0, "tpl-1");
401        // Instance launched at t=5000 — later than the def.
402        insert_instance(
403            &conn, "inst-1", "def-u1", "Maks", "id-1", "mem-1", "/wd/m", 5000, false,
404        );
405
406        run_consolidate_migration(&mut conn, None).unwrap();
407
408        let updated_at: i64 = conn
409            .query_row(
410                "SELECT updated_at FROM db_agents WHERE id = 'def-u1'",
411                [],
412                |r| r.get(0),
413            )
414            .unwrap();
415        assert_eq!(
416            updated_at, 5000,
417            "folded user-clone row's updated_at must reflect the instance's launch time, \
418             not the def's edit time, so ORDER BY updated_at picks the right row"
419        );
420    }
421
422    #[test]
423    fn fold_into_user_clone_keeps_higher_updated_at() {
424        // MAX(updated_at, ?) semantics: if the def was edited AFTER
425        // the instance launched, the def's edit time should stay as
426        // updated_at (the def edit IS the most-recent touch).
427        let mut conn = fresh_conn();
428        insert_def(&conn, "tpl-1", "Coder", 1, "");
429        // Def edited at t=8000.
430        conn.execute(
431            "UPDATE db_agent_definitions SET updated_at = 8000 WHERE id = 'tpl-1'",
432            [],
433        )
434        .unwrap();
435        insert_def(&conn, "def-u1", "User Coder", 0, "tpl-1");
436        conn.execute(
437            "UPDATE db_agent_definitions SET updated_at = 8000 WHERE id = 'def-u1'",
438            [],
439        )
440        .unwrap();
441        // Now insert an OLDER instance.
442        insert_instance(
443            &conn, "inst-1", "def-u1", "Maks", "id-1", "mem-1", "/wd/m", 3000, false,
444        );
445
446        run_consolidate_migration(&mut conn, None).unwrap();
447
448        let updated_at: i64 = conn
449            .query_row(
450                "SELECT updated_at FROM db_agents WHERE id = 'def-u1'",
451                [],
452                |r| r.get(0),
453            )
454            .unwrap();
455        assert_eq!(
456            updated_at, 8000,
457            "later def edit beats older instance launch — MAX(updated_at, inst.created_at)"
458        );
459    }
460
461    #[test]
462    fn marker_short_circuits_second_run() {
463        let mut conn = fresh_conn();
464        insert_def(&conn, "tpl-1", "Coder", 1, "");
465        let tmp = tempfile::tempdir().unwrap();
466
467        let stats1 = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
468        assert_eq!(stats1.templates_inserted, 1);
469        assert!(!stats1.already_done);
470        assert!(tmp.path().join(CONSOLIDATE_MARKER).exists());
471
472        // Insert a NEW row after the marker; second call must NOT see
473        // it.
474        insert_def(&conn, "tpl-2", "Reviewer", 1, "");
475        let stats2 = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
476        assert!(stats2.already_done);
477        assert_eq!(stats2.templates_inserted, 0);
478        // db_agents only has tpl-1 — the post-marker insert is the
479        // dual-write hook's problem, not the backfill's.
480        assert_eq!(count_agents(&conn, "is_template = 1"), 1);
481    }
482
483    #[test]
484    fn skips_continuation_rows() {
485        let mut conn = fresh_conn();
486        insert_def(&conn, "tpl-1", "Coder", 1, "");
487        insert_instance(&conn, "inst-A", "tpl-1", "Original", "", "", "/wd/a", 100, false);
488        // Continuation row (parent_instance_id = inst-A).
489        conn.execute(
490            "INSERT INTO db_agent_instances
491                (id, definition_id, parent_instance_id, block_id, session_id, status,
492                 github_context, started_at, ended_at, created_at, identity_id, memory_id,
493                 instance_name, working_directory, display_hidden)
494             VALUES ('inst-cont', 'tpl-1', 'inst-A', '', '', 'running', '', 200, 0, 200,
495                     '', '', 'Original', '/wd/a', 0)",
496            [],
497        )
498        .unwrap();
499
500        let stats = run_consolidate_migration(&mut conn, None).unwrap();
501        assert_eq!(stats.instances_skipped_continuation, 1);
502        // Only inst-A and the template made it into db_agents.
503        assert_eq!(count_agents(&conn, "1 = 1"), 2);
504        assert_eq!(count_agents(&conn, "id = 'inst-cont'"), 0);
505    }
506
507    #[test]
508    fn empty_database_is_clean_noop() {
509        let mut conn = fresh_conn();
510        let stats = run_consolidate_migration(&mut conn, None).unwrap();
511        assert_eq!(stats, ConsolidateStats::default());
512        assert_eq!(count_agents(&conn, "1 = 1"), 0);
513    }
514
515    #[test]
516    fn preserves_hidden_flag_into_user_hidden() {
517        let mut conn = fresh_conn();
518        insert_def(&conn, "tpl-1", "Coder", 1, "");
519        insert_instance(&conn, "inst-H", "tpl-1", "Hidden", "", "", "/wd/h", 100, true);
520        run_consolidate_migration(&mut conn, None).unwrap();
521        let hidden: i64 = conn
522            .query_row(
523                "SELECT user_hidden FROM db_agents WHERE id = 'inst-H'",
524                [],
525                |r| r.get(0),
526            )
527            .unwrap();
528        assert_eq!(hidden, 1);
529    }
530
531    #[test]
532    fn definition_working_directory_survives_the_pass_1_2_backfill() {
533        // Regression: the Pass 1/2 INSERT (templates + user-cloned
534        // definitions with no instance to fold) used to hardcode
535        // working_directory as '' instead of binding def.working_directory,
536        // silently discarding it during consolidation — audit finding,
537        // docs/reports/REPORT_REPO_HEALTH_AUDIT_2026_07_20.md §1.2. A
538        // definition that was never instantiated (no db_agent_instances
539        // row) only ever goes through this path — Pass 3/4 (instances)
540        // never touches it — so this case wasn't covered by any existing
541        // test here.
542        let mut conn = fresh_conn();
543        conn.execute(
544            "INSERT INTO db_agent_definitions
545                (id, slug, name, icon, provider, description, working_directory, shell,
546                 provider_flags, auto_start, restart_on_crash, idle_timeout_minutes,
547                 created_at, agent_type, environment, agent_bus_id, is_seeded, accounts,
548                 parent_id, branch_label, updated_at)
549             VALUES ('tpl-wd', 'tpl-wd', 'Coder', '✦', 'claude', 'desc',
550                     '/home/user/my-project', 'bash',
551                     '', 0, 0, 0,
552                     1000, 'standalone', '', '', 1, '',
553                     '', '', 1000)",
554            [],
555        )
556        .unwrap();
557
558        run_consolidate_migration(&mut conn, None).unwrap();
559
560        let working_directory: String = conn
561            .query_row(
562                "SELECT working_directory FROM db_agents WHERE id = 'tpl-wd'",
563                [],
564                |r| r.get(0),
565            )
566            .unwrap();
567        assert_eq!(
568            working_directory, "/home/user/my-project",
569            "a definition's working_directory must survive Pass 1/2 consolidation \
570             even when it was never instantiated (no instance row to fold bindings from)"
571        );
572    }
573
574    // ── Phase 0 hardening (SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03) ──────
575
576    #[test]
577    fn consolidate_looks_incomplete_is_false_on_a_fresh_db() {
578        let conn = fresh_conn();
579        // No source rows, no db_agents rows — nothing to backfill, not "incomplete".
580        assert!(!consolidate_looks_incomplete(&conn).unwrap());
581    }
582
583    /// The scenario `consolidate_looks_incomplete`'s own doc comment names:
584    /// a genuinely v32+ channel, born without either legacy table at all
585    /// (not just empty — physically absent, unlike `fresh_conn`'s fixture
586    /// above, which stands them up empty for the OTHER tests in this file
587    /// that still need to insert legacy rows). Must not error.
588    #[test]
589    fn consolidate_looks_incomplete_tolerates_both_tables_being_physically_absent() {
590        let conn = Connection::open_in_memory().unwrap();
591        conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
592        run_object_schema(&conn).unwrap();
593        assert!(!consolidate_looks_incomplete(&conn).unwrap());
594    }
595
596    /// Same scenario, through `run_consolidate_migration` directly (not
597    /// just its `consolidate_looks_incomplete` sub-check) — the doctor-pass
598    /// path this guards against calls `verify()`, which only reads via
599    /// `consolidate_looks_incomplete`, but `run_consolidate_migration`
600    /// itself must also tolerate this shape rather than erroring on the
601    /// first `SELECT ... FROM db_agent_definitions` if anything ever calls
602    /// it directly against a table-less store.
603    #[test]
604    fn run_consolidate_migration_tolerates_both_tables_being_physically_absent() {
605        let mut conn = Connection::open_in_memory().unwrap();
606        conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
607        run_object_schema(&conn).unwrap();
608        let stats = run_consolidate_migration(&mut conn, None).unwrap();
609        assert_eq!(stats, ConsolidateStats::default());
610    }
611
612    #[test]
613    fn consolidate_looks_incomplete_is_false_once_backfilled() {
614        let mut conn = fresh_conn();
615        insert_def(&conn, "tpl-1", "Coder", 1, "");
616        run_consolidate_migration(&mut conn, None).unwrap();
617        assert!(!consolidate_looks_incomplete(&conn).unwrap());
618    }
619
620    #[test]
621    fn consolidate_looks_incomplete_is_true_when_source_has_rows_but_db_agents_is_empty() {
622        let conn = fresh_conn();
623        // Source rows present, but db_agents was never populated (the exact
624        // shape a stale/orphaned marker file produces).
625        insert_def(&conn, "tpl-1", "Coder", 1, "");
626        assert!(consolidate_looks_incomplete(&conn).unwrap());
627    }
628
629    #[test]
630    fn stale_marker_does_not_block_a_real_backfill() {
631        // Acceptance test for Phase 0a/0b: a data dir with a marker file
632        // present but an empty db_agents table (simulating a rebuilt/restored
633        // objects.db sitting next to a stale flag file) must NOT be trusted
634        // as "already done" — the migration must detect this and actually
635        // run the backfill instead of silently no-op'ing.
636        let tmp = tempfile::TempDir::new().unwrap();
637        std::fs::write(tmp.path().join(CONSOLIDATE_MARKER), b"phase3a").unwrap();
638
639        let mut conn = fresh_conn();
640        insert_def(&conn, "tpl-1", "Coder", 1, "");
641        assert_eq!(count_agents(&conn, "1=1"), 0, "db_agents must start empty for this test to be meaningful");
642
643        let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
644        assert!(!stats.already_done, "a stale marker must not short-circuit as already_done");
645        assert_eq!(stats.templates_inserted, 1);
646        assert_eq!(count_agents(&conn, "1=1"), 1, "db_agents must actually get populated, not silently skipped");
647    }
648
649    #[test]
650    fn genuinely_completed_marker_still_short_circuits() {
651        // The flip side: once db_agents is correctly populated, a present
652        // marker SHOULD short-circuit (already_done=true) — Phase 0's fix
653        // must not make every run pay the full backfill cost forever.
654        let tmp = tempfile::TempDir::new().unwrap();
655        std::fs::write(tmp.path().join(CONSOLIDATE_MARKER), b"phase3a").unwrap();
656
657        let mut conn = fresh_conn();
658        insert_def(&conn, "tpl-1", "Coder", 1, "");
659        run_consolidate_migration(&mut conn, None).unwrap(); // populate db_agents directly
660        assert_eq!(count_agents(&conn, "1=1"), 1);
661
662        let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
663        assert!(stats.already_done, "a marker backed by real data must still short-circuit");
664        assert_eq!(count_agents(&conn, "1=1"), 1, "must not double-insert");
665    }
666
667    // ── Row-level characterisation of every pass ────────────────────────────
668
669    const AGENT_COLUMNS: &str = "id, name, icon, description, is_template, parent_template_id, \
670        provider, provider_flags, shell, environment, agent_type, agent_bus_id, accounts, \
671        auto_start, restart_on_crash, idle_timeout_minutes, slug, branch_label, \
672        identity_id, memory_id, working_directory, github_context, instance_name, \
673        created_at, updated_at, is_seeded, user_hidden";
674
675    /// One `db_agents` row as `|`-joined text, columns in `AGENT_COLUMNS` order.
676    fn row_of(conn: &Connection, id: &str) -> String {
677        let cols: Vec<String> = AGENT_COLUMNS
678            .split(',')
679            .map(|c| format!("CAST({} AS TEXT)", c.trim()))
680            .collect();
681        let sql = format!("SELECT {} FROM db_agents WHERE id = ?1", cols.join(", "));
682        conn.query_row(&sql, params![id], |r| {
683            let mut parts = Vec::new();
684            for i in 0..27 {
685                parts.push(r.get::<_, String>(i)?);
686            }
687            Ok(parts.join("|"))
688        })
689        .unwrap()
690    }
691
692    /// A definition with a distinct value in every column.
693    fn rich_def(conn: &Connection, id: &str, name: &str, is_seeded: i64, parent_id: &str) {
694        conn.execute(
695            "INSERT INTO db_agent_definitions
696                (id, slug, name, icon, provider, description, working_directory, shell,
697                 provider_flags, auto_start, restart_on_crash, idle_timeout_minutes,
698                 created_at, agent_type, environment, agent_bus_id, is_seeded, accounts,
699                 parent_id, branch_label, updated_at)
700             VALUES (?1, ?1, ?2, 'ic', 'prov', 'descr', '/def/wd', 'zsh',
701                     '--fl', 1, 1, 7,
702                     111, 'sub', 'K=V', 'bus-9', ?3, 'acct-1',
703                     ?4, 'br-1', 222)",
704            params![id, name, is_seeded, parent_id],
705        )
706        .unwrap();
707    }
708
709    /// An instance with a distinct value in every column the backfill copies.
710    fn rich_instance(
711        conn: &Connection,
712        id: &str,
713        definition_id: &str,
714        parent_instance_id: &str,
715        instance_name: &str,
716        created_at: i64,
717        display_hidden: bool,
718    ) {
719        conn.execute(
720            "INSERT INTO db_agent_instances
721                (id, definition_id, parent_instance_id, block_id, session_id, status,
722                 github_context, started_at, ended_at, created_at, identity_id, memory_id,
723                 instance_name, working_directory, display_hidden)
724             VALUES (?1, ?2, ?3, 'blk', 'sess', 'running', 'ghc', 1, 0, ?4, 'idn', 'mem',
725                     ?5, '/inst/wd', ?6)",
726            params![id, definition_id, parent_instance_id, created_at, instance_name, display_hidden as i64],
727        )
728        .unwrap();
729    }
730
731    #[test]
732    fn a_seeded_definition_becomes_a_template_carrying_every_column() {
733        let mut conn = fresh_conn();
734        // The parent id is set on purpose: a template ignores it.
735        rich_def(&conn, "tpl", "Tpl", 1, "ignored-parent");
736        run_consolidate_migration(&mut conn, None).unwrap();
737        assert_eq!(
738            row_of(&conn, "tpl"),
739            "tpl|Tpl|ic|descr|1||prov|--fl|zsh|K=V|sub|bus-9|acct-1|1|1|7|tpl|br-1|||/def/wd|||111|222|1|0"
740        );
741    }
742
743    #[test]
744    fn an_unseeded_definition_becomes_a_user_clone_of_its_parent() {
745        let mut conn = fresh_conn();
746        rich_def(&conn, "tpl", "Tpl", 1, "");
747        rich_def(&conn, "usr", "Usr", 0, "tpl");
748        run_consolidate_migration(&mut conn, None).unwrap();
749        assert_eq!(
750            row_of(&conn, "usr"),
751            "usr|Usr|ic|descr|0|tpl|prov|--fl|zsh|K=V|sub|bus-9|acct-1|1|1|7|usr|br-1|||/def/wd|||111|222|0|0"
752        );
753    }
754
755    #[test]
756    fn an_instance_of_a_template_becomes_a_user_clone_keyed_by_the_instance() {
757        let mut conn = fresh_conn();
758        rich_def(&conn, "tpl", "Tpl", 1, "");
759        rich_instance(&conn, "i1", "tpl", "", "Inst", 555, true);
760        let stats = run_consolidate_migration(&mut conn, None).unwrap();
761        assert_eq!(stats.instances_as_clone_inserted, 1);
762        // Definition fields from the template, bindings and timestamps from the
763        // instance; the clone is never seeded even though its template is.
764        assert_eq!(
765            row_of(&conn, "i1"),
766            "i1|Inst|ic|descr|0|tpl|prov|--fl|zsh|K=V|sub|bus-9|acct-1|1|1|7|tpl|br-1|idn|mem|/inst/wd|ghc|Inst|555|555|0|1"
767        );
768    }
769
770    #[test]
771    fn two_instances_of_one_template_each_get_their_own_clone() {
772        let mut conn = fresh_conn();
773        rich_def(&conn, "tpl", "Tpl", 1, "");
774        rich_instance(&conn, "i1", "tpl", "", "One", 100, false);
775        rich_instance(&conn, "i2", "tpl", "", "Two", 200, false);
776        let stats = run_consolidate_migration(&mut conn, None).unwrap();
777        assert_eq!(stats.instances_as_clone_inserted, 2);
778        assert_eq!(stats.instances_collision_warned, 0);
779        assert_eq!(count_agents(&conn, "is_template = 0"), 2);
780    }
781
782    #[test]
783    fn folding_an_instance_into_a_user_clone_rewrites_only_the_binding_columns() {
784        let mut conn = fresh_conn();
785        rich_def(&conn, "tpl", "Tpl", 1, "");
786        rich_def(&conn, "usr", "Usr", 0, "tpl");
787        // Launched after the definition was last edited (222).
788        rich_instance(&conn, "i2", "usr", "", "Folded", 333, false);
789        let stats = run_consolidate_migration(&mut conn, None).unwrap();
790        assert_eq!(stats.instances_folded_into_def, 1);
791        assert_eq!(
792            row_of(&conn, "usr"),
793            "usr|Folded|ic|descr|0|tpl|prov|--fl|zsh|K=V|sub|bus-9|acct-1|1|1|7|usr|br-1|idn|mem|/inst/wd|ghc|Folded|111|333|0|0"
794        );
795        // No row is keyed by the folded instance.
796        assert_eq!(count_agents(&conn, "id = 'i2'"), 0);
797    }
798
799    #[test]
800    fn an_unnamed_instance_folds_in_under_its_definitions_name() {
801        let mut conn = fresh_conn();
802        rich_def(&conn, "tpl", "Tpl", 1, "");
803        rich_def(&conn, "usr", "Usr", 0, "tpl");
804        rich_instance(&conn, "i2", "usr", "", "", 333, true);
805        run_consolidate_migration(&mut conn, None).unwrap();
806        assert_eq!(
807            row_of(&conn, "usr"),
808            "usr|Usr|ic|descr|0|tpl|prov|--fl|zsh|K=V|sub|bus-9|acct-1|1|1|7|usr|br-1|idn|mem|/inst/wd|ghc||111|333|0|1"
809        );
810    }
811
812    #[test]
813    fn three_instances_on_one_user_clone_fold_the_newest_and_warn_twice() {
814        let mut conn = fresh_conn();
815        rich_def(&conn, "tpl", "Tpl", 1, "");
816        rich_def(&conn, "usr", "Usr", 0, "tpl");
817        rich_instance(&conn, "old", "usr", "", "Old", 100, false);
818        rich_instance(&conn, "mid", "usr", "", "Mid", 200, false);
819        rich_instance(&conn, "new", "usr", "", "New", 300, false);
820        let stats = run_consolidate_migration(&mut conn, None).unwrap();
821        assert_eq!(stats.instances_folded_into_def, 1);
822        assert_eq!(stats.instances_collision_warned, 2);
823        assert_eq!(row_of(&conn, "usr").split('|').nth(22), Some("New"));
824    }
825
826    #[test]
827    fn a_newer_continuation_row_does_not_use_up_the_fold_slot() {
828        let mut conn = fresh_conn();
829        rich_def(&conn, "tpl", "Tpl", 1, "");
830        rich_def(&conn, "usr", "Usr", 0, "tpl");
831        rich_instance(&conn, "real", "usr", "", "Real", 100, false);
832        rich_instance(&conn, "cont", "usr", "real", "Cont", 900, false);
833        let stats = run_consolidate_migration(&mut conn, None).unwrap();
834        assert_eq!(stats.instances_skipped_continuation, 1);
835        assert_eq!(stats.instances_collision_warned, 0);
836        assert_eq!(stats.instances_folded_into_def, 1);
837        assert_eq!(row_of(&conn, "usr").split('|').nth(22), Some("Real"));
838    }
839
840    #[test]
841    fn an_instance_with_no_definition_is_skipped_and_counted() {
842        let mut conn = fresh_conn();
843        // The cascade would have removed this row; switch the key check off to
844        // get one that survived.
845        conn.execute_batch("PRAGMA foreign_keys=OFF;").unwrap();
846        rich_def(&conn, "tpl", "Tpl", 1, "");
847        rich_instance(&conn, "orphan", "ghost", "", "Orphan", 100, false);
848        let stats = run_consolidate_migration(&mut conn, None).unwrap();
849        assert_eq!(stats.instances_skipped_no_definition, 1);
850        assert_eq!(stats.instances_skipped_continuation, 0);
851        assert_eq!(stats.instances_as_clone_inserted, 0);
852        assert_eq!(count_agents(&conn, "1 = 1"), 1);
853    }
854
855    #[test]
856    fn an_orphaned_continuation_row_counts_as_a_continuation_not_an_orphan() {
857        let mut conn = fresh_conn();
858        conn.execute_batch("PRAGMA foreign_keys=OFF;").unwrap();
859        rich_instance(&conn, "cont", "ghost", "parent", "Cont", 100, false);
860        // No definitions at all: the table exists but is empty, so the pass runs.
861        let stats = run_consolidate_migration(&mut conn, None).unwrap();
862        assert_eq!(stats.instances_skipped_continuation, 1);
863        assert_eq!(stats.instances_skipped_no_definition, 0);
864    }
865
866    #[test]
867    fn a_missing_instances_table_still_backfills_the_definitions() {
868        let mut conn = fresh_conn();
869        conn.execute_batch("DROP TABLE db_agent_instances;").unwrap();
870        rich_def(&conn, "tpl", "Tpl", 1, "");
871        rich_def(&conn, "usr", "Usr", 0, "tpl");
872        let tmp = tempfile::tempdir().unwrap();
873        let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
874        assert_eq!(stats.templates_inserted, 1);
875        assert_eq!(stats.user_defs_inserted, 1);
876        assert_eq!(stats.instances_as_clone_inserted, 0);
877        assert_eq!(count_agents(&conn, "1 = 1"), 2);
878        assert!(tmp.path().join(CONSOLIDATE_MARKER).exists());
879    }
880
881    #[test]
882    fn a_missing_definitions_table_returns_empty_stats_and_writes_no_marker() {
883        let mut conn = Connection::open_in_memory().unwrap();
884        run_object_schema(&conn).unwrap();
885        conn.execute_batch("CREATE TABLE db_agent_instances (id TEXT PRIMARY KEY);").unwrap();
886        let tmp = tempfile::tempdir().unwrap();
887        let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
888        assert_eq!(stats, ConsolidateStats::default());
889        assert!(!tmp.path().join(CONSOLIDATE_MARKER).exists());
890    }
891
892    #[test]
893    fn a_completed_run_writes_the_marker_even_with_nothing_to_move() {
894        let mut conn = fresh_conn();
895        let tmp = tempfile::tempdir().unwrap();
896        let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
897        assert_eq!(stats, ConsolidateStats::default());
898        assert_eq!(std::fs::read(tmp.path().join(CONSOLIDATE_MARKER)).unwrap(), b"phase3a");
899    }
900
901    #[test]
902    fn a_marker_that_cannot_be_written_does_not_fail_the_run() {
903        let mut conn = fresh_conn();
904        rich_def(&conn, "tpl", "Tpl", 1, "");
905        let tmp = tempfile::tempdir().unwrap();
906        let missing = tmp.path().join("no-such-dir");
907        let stats = run_consolidate_migration(&mut conn, Some(&missing)).unwrap();
908        assert_eq!(stats.templates_inserted, 1);
909        assert_eq!(count_agents(&conn, "1 = 1"), 1);
910        assert!(!missing.exists());
911    }
912
913    #[test]
914    fn a_failure_part_way_rolls_everything_back_and_leaves_no_marker() {
915        let mut conn = fresh_conn();
916        rich_def(&conn, "tpl", "Tpl", 1, "");
917        rich_instance(&conn, "i1", "tpl", "", "Inst", 100, false);
918        // The template inserts fine; the clone for the instance is refused.
919        conn.execute_batch(
920            "CREATE TRIGGER refuse_clone BEFORE INSERT ON db_agents
921             WHEN NEW.id = 'i1'
922             BEGIN SELECT RAISE(ABORT, 'refused'); END;",
923        )
924        .unwrap();
925        let tmp = tempfile::tempdir().unwrap();
926        assert!(run_consolidate_migration(&mut conn, Some(tmp.path())).is_err());
927        assert_eq!(count_agents(&conn, "1 = 1"), 0, "the template insert must roll back too");
928        assert!(!tmp.path().join(CONSOLIDATE_MARKER).exists());
929
930        // The next start retries from scratch.
931        conn.execute_batch("DROP TRIGGER refuse_clone;").unwrap();
932        let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
933        assert_eq!(stats.templates_inserted, 1);
934        assert_eq!(stats.instances_as_clone_inserted, 1);
935        assert_eq!(count_agents(&conn, "1 = 1"), 2);
936        assert!(tmp.path().join(CONSOLIDATE_MARKER).exists());
937    }
938
939    #[test]
940    fn running_twice_without_a_marker_replaces_rows_instead_of_failing() {
941        let mut conn = fresh_conn();
942        rich_def(&conn, "tpl", "Tpl", 1, "");
943        rich_def(&conn, "usr", "Usr", 0, "tpl");
944        rich_instance(&conn, "i1", "tpl", "", "Inst", 100, false);
945        rich_instance(&conn, "i2", "usr", "", "Folded", 333, false);
946        let first = run_consolidate_migration(&mut conn, None).unwrap();
947        let rows_after_first: Vec<String> =
948            ["tpl", "usr", "i1"].iter().map(|id| row_of(&conn, id)).collect();
949        let second = run_consolidate_migration(&mut conn, None).unwrap();
950        assert_eq!(first, second);
951        let rows_after_second: Vec<String> =
952            ["tpl", "usr", "i1"].iter().map(|id| row_of(&conn, id)).collect();
953        assert_eq!(rows_after_first, rows_after_second);
954        assert_eq!(count_agents(&conn, "1 = 1"), 3);
955    }
956}