Skip to main content

agentmux_srv_core/migrations/
runner.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Migration runner — invoked by `agentmux-srv migrate` (a CLI subcommand;
5//! the launcher runs `migrate --prepare` through `srv_spawner::run_prepare`
6//! when srv's boot gate asks for it) and, separately, in-process at boot via
7//! `run_pending_migrations`, only when no supervisor prepares data (headless
8//! srv, `task dev:standalone`).
9//!
10//! `--prepare` and the in-process path report per-migration progress as
11//! `agentmux_common::srv_stderr`'s `AGENTMUXSRV-MIGRATION-BEGIN`/`-END` lines
12//! on stderr (`STDERR_PROGRESS`), which the launcher's splash shows as
13//! sub-rows. Plain `migrate` (no flags) prints newline-delimited JSON on
14//! stdout instead, for scripts and operators running it by hand.
15//! Failures are written to `<home>/logs/migration-error.log`; the
16//! process exits non-zero so the launcher can surface the error rather than
17//! booting with a half-migrated data dir.
18
19use std::collections::HashSet;
20use std::path::{Path, PathBuf};
21use std::time::Instant;
22
23use crate::backend::storage::store::Store;
24use crate::registry::{resolve_global_shared_root, resolve_shared_store_path};
25
26use super::{MigrationContext, MigrationScope, REGISTRY};
27
28// ── Progress events (newline-delimited JSON → launcher reads these) ───────────
29
30fn emit(event: &str, id: &str, extra: &str) {
31    if extra.is_empty() {
32        println!("{{\"event\":\"{}\",\"id\":\"{}\"}}", event, id);
33    } else {
34        println!("{{\"event\":\"{}\",\"id\":\"{}\",{}}}", event, id, extra);
35    }
36}
37
38pub(super) fn emit_summary(applied: usize, skipped: usize) {
39    println!(
40        "{{\"event\":\"complete\",\"applied\":{},\"skipped\":{}}}",
41        applied, skipped
42    );
43}
44
45/// The true, unconditional `~/.agentmux` root — `MigrationContext.home`.
46///
47/// Deliberately NOT derived from `resolve_shared_store_path()` (which
48/// varies under isolated-auth mode, resolving to a channel-scoped path
49/// instead of the global one) — nearly every registered migration builds
50/// paths directly off `ctx.home` (registry/definitions/transcripts dirs),
51/// and `backup::backup_stores`/`write_error_log` use it too. All of those
52/// must stay anchored to the real global root regardless of isolation;
53/// only `ctx.shared_store_path` itself is meant to vary. A single shared
54/// helper (not one inline derivation per call site) so the two can't
55/// drift apart. See `registry::resolve_global_shared_root`'s doc comment
56/// and `docs/specs/SPEC_ISOLATED_AUTH_DEV_TESTING_2026_07_27.md`.
57fn resolve_home() -> Option<PathBuf> {
58    resolve_global_shared_root().and_then(|p| p.parent().map(Path::to_path_buf))
59}
60
61// ── Entry point ───────────────────────────────────────────────────────────────
62
63/// Exit code of `migrate --verify` when at least one applied migration's
64/// post-condition is a mismatch or its check errored. Distinct from 1 (a
65/// migration RUN failed) so a caller can tell "your data is inconsistent"
66/// from "the migrate command itself broke", and from 2, which clap uses for
67/// a CLI usage error (a typoed flag must not read as a data finding —
68/// reagent P2 on #3058). See docs/exe-return-codes.md.
69pub const VERIFY_FAILED_EXIT_CODE: i32 = 3;
70
71/// Called from `main.rs` when the `migrate` subcommand is active.
72/// Returns the exit code (0 = success, 1 = failure, 3 = `--verify` found a
73/// mismatch — see `VERIFY_FAILED_EXIT_CODE`).
74pub fn run_migrate_command(data_dir: &Path, dry_run: bool, list: bool, verify: bool, prepare: bool) -> i32 {
75    // Unresolvable shared store path means we're in CI or an unusual env that
76    // has no AGENTMUX_SHARED_DIR. Mirror the daemon's behaviour: treat as a
77    // no-op and exit 0 so the launcher proceeds normally.
78    let Some(shared_store_path) = resolve_shared_store_path() else {
79        emit_summary(0, 0);
80        return 0;
81    };
82
83    let Some(home) = resolve_home() else {
84        emit_summary(0, 0);
85        return 0;
86    };
87
88    // `--verify` is read-only by contract, so it dispatches BEFORE the store
89    // opens below: `Store::open*` run schema setup, WAL configuration and
90    // legacy-table adoption, and create the database file when it is missing
91    // (codex P2 on #3058). A doctor must not do any of that — least of all
92    // turn a typoed data dir into a fresh empty store that then "verifies".
93    if verify {
94        return cmd_verify(data_dir, &home, &shared_store_path);
95    }
96
97    // Ensure the shared/ directory exists — on a fresh install it has not been
98    // created yet (the daemon does create_dir_all at startup, but migrate runs
99    // before the daemon). SQLite cannot create parent directories itself.
100    if let Some(parent) = shared_store_path.parent() {
101        if let Err(e) = std::fs::create_dir_all(parent) {
102            eprintln!("migration: failed to create shared dir {}: {}", parent.display(), e);
103            return 1;
104        }
105    }
106
107    if prepare || !(list || dry_run) {
108        if let Some(code) = crate::registry::shared_guard::claim_for_migrate(data_dir) {
109            return code;
110        }
111    }
112
113    if prepare {
114        return super::prepare::run(data_dir, &home, &shared_store_path);
115    }
116
117    // `--list` and `--dry-run` are read-only previews and deliberately do NOT
118    // take the migration lock: an operator uses them precisely while another
119    // process may be mid-migration, and a 30-minute wait would defeat that
120    // (reagent P1 on #3062). They open the stores the ordinary way (schema
121    // setup and all — the same thing the daemon does on every boot).
122    if list || dry_run {
123        let (shared_store, channel_store) = match open_stores_for_preview(&shared_store_path, data_dir) {
124            Ok(pair) => pair,
125            Err(msg) => {
126                eprintln!("migration: {}", msg);
127                return 1;
128            }
129        };
130        if list {
131            return cmd_list(&shared_store, channel_store.as_ref());
132        }
133        let pending = pending_of(REGISTRY, &shared_store, channel_store.as_ref());
134        if pending.is_empty() {
135            emit_summary(0, REGISTRY.len());
136        }
137        for m in &pending {
138            println!("pending: {} — {}", m.id(), m.description());
139        }
140        return 0;
141    }
142
143    // Apply: the SAME locked batch the daemon runs (`apply_pending`), so the
144    // CLI can never race a booting srv — and the lock is taken before the
145    // stores are opened, so a daemon holding a write transaction longer than
146    // `Store::open*`'s own 5 s busy timeout waits on the lock instead of
147    // failing with a spurious "database is locked" (reagent P1 on #3062).
148    // The only CLI-specific parts are the NDJSON progress lines on stdout
149    // (for a person or script running `migrate`) and the error log file.
150    let progress = ApplyProgress {
151        on_start: &|id, description| {
152            emit("migration_start", id, &format!("\"description\":\"{}\"", description));
153        },
154        on_done: &|id, ms| emit("migration_done", id, &format!("\"duration_ms\":{}", ms)),
155    };
156    match apply_pending(REGISTRY, &home, &shared_store_path, data_dir, Some(&progress)) {
157        Ok(outcome) => {
158            emit_summary(outcome.applied, outcome.skipped);
159            0
160        }
161        Err(msg) => {
162            write_error_log(&home, &msg);
163            eprintln!("{}", msg);
164            1
165        }
166    }
167}
168
169/// Return the store that tracks applied state for a migration of the given scope.
170/// Global migrations → shared store; Channel migrations → channel store.
171fn tracking_store<'a>(
172    scope: super::MigrationScope,
173    shared: &'a Store,
174    channel: Option<&'a Store>,
175) -> Option<&'a Store> {
176    match scope {
177        super::MigrationScope::Global => Some(shared),
178        super::MigrationScope::Channel => channel,
179    }
180}
181
182fn cmd_list(shared_store: &Store, channel_store: Option<&Store>) -> i32 {
183    let shared_applied = shared_store.migrations_list_applied().unwrap_or_default();
184    let channel_applied = channel_store
185        .and_then(|s| s.migrations_list_applied().ok())
186        .unwrap_or_default();
187    for m in REGISTRY.iter() {
188        let applied_ids = match m.scope() {
189            super::MigrationScope::Global => &shared_applied,
190            super::MigrationScope::Channel => &channel_applied,
191        };
192        let status = if applied_ids.contains(&m.id().to_string()) { "applied" } else { "pending" };
193        println!("{} [{}] [{}] — {}", m.id(), m.scope().as_str(), status, m.description());
194    }
195    0
196}
197
198// ── In-process migration runner (migrate --prepare; unsupervised srv) ────────
199
200/// Apply all pending migrations in-process before srv opens its stores.
201///
202/// Under the launcher, srv never calls this at boot: its gate exits 4 and the
203/// launcher runs `migrate --prepare`. A srv without a supervisor (headless,
204/// `task dev:standalone`) calls it from `prepare_in_process` before `id_store`
205/// binds to the shared store. Returns `Ok(0)` when nothing is pending.
206///
207/// Unlike `run_migrate_command` this writes progress via `tracing` rather than
208/// stdout JSON and is meant to be called from within the daemon process rather
209/// than a subprocess. Returns the number of migrations applied. On error, returns
210/// `Err` — callers should fall back to the per-channel store rather than binding
211/// `id_store` to an un-backfilled shared store.
212///
213/// `data_dir` must be the wave data dir (parent of `db/`), not the db dir.
214pub fn run_pending_migrations(data_dir: &Path) -> Result<usize, String> {
215    let shared_store_path = match resolve_shared_store_path() {
216        Some(p) => p,
217        None => {
218            tracing::info!("run_pending_migrations: shared store path unresolvable — nothing to do");
219            return Ok(0);
220        }
221    };
222
223    let home = match resolve_home() {
224        Some(p) => p,
225        None => return Err("run_pending_migrations: cannot resolve global shared root".to_string()),
226    };
227
228    // Per-migration BEGIN/END stderr lines, inside the AGENTMUXSRV-MIGRATING
229    // window `bootstrap/stores.rs` already opens. Without this, srv's launcher-
230    // supervised splash shows a bare, silently-running "Backend startup"
231    // clock for the whole migration batch — up to 30 minutes
232    // (MIGRATION_LOCK_WAIT) — with no indication anything unusual is
233    // happening inside it. See
234    // docs/reports/REPORT_SPLASH_SCREEN_ARCHITECTURE_RETHINK_2026_09_14.md
235    // §2.1. Unlike `run_migrate_command`'s stdout JSON (only logged), this
236    // goes to STDERR — the channel every daemon-boot marker (ESTART,
237    // MIGRATING, MIGRATION-FAILED) uses — via `agentmux_common::srv_stderr`.
238    // The launcher's `run_prepare` (`srv_spawner.rs`) reads these lines from
239    // `migrate --prepare` and shows them as splash rows; a supervisor that
240    // doesn't parse them (the CEF host sidecar today) just logs them.
241    apply_pending(REGISTRY, &home, &shared_store_path, data_dir, Some(&STDERR_PROGRESS)).map(|o| o.applied)
242}
243
244// ── Cross-process migration lock (Phase 3, F6) ────────────────────────────────
245//
246// Two `agentmux-srv` processes against the same data dir (a crash-restart
247// race, or a misconfigured channel) could both see a migration as pending
248// and both run `up()`: SQLite's own locking serializes individual statements,
249// not the runner's check → run → mark-applied sequence (classic TOCTOU).
250//
251// The lock is a dedicated one-table SQLite file next to the shared store
252// with `BEGIN IMMEDIATE` held for the whole batch. That IS a cross-process
253// advisory lock — SQLite takes an OS-level file lock — with three properties
254// a hand-rolled lockfile does not get for free: it blocks (busy_timeout)
255// instead of failing, it is released by the OS when the holder dies (no
256// stale-lockfile cleanup), and it is portable to Windows. It is NOT taken on
257// the real stores because migrations open their own connections to those
258// (m0007 opens the channel store itself); a transaction held there would
259// deadlock them.
260
261/// File name of the lock database, created beside the shared store.
262pub(super) const MIGRATION_LOCK_FILE: &str = "migrations.lock.db";
263
264/// How long a second runner waits for the first to finish before giving up.
265/// Matches the launcher's extended ESTART deadline for a long migration
266/// batch (`srv_spawner.rs` / `sidecar.rs`: 30 minutes).
267const MIGRATION_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(30 * 60);
268
269/// Held for the duration of a migration batch. Dropping it releases the lock.
270pub(super) struct MigrationLock {
271    _conn: rusqlite::Connection,
272}
273
274impl MigrationLock {
275    /// Acquire the batch lock at `path`, waiting up to `wait` for another
276    /// holder. `Err` only if the lock database cannot be opened or the wait
277    /// expires — both fatal for a migration run, by design.
278    pub(super) fn acquire(path: &Path, wait: std::time::Duration) -> Result<Self, String> {
279        let conn = rusqlite::Connection::open(path)
280            .map_err(|e| format!("open migration lock {}: {}", path.display(), e))?;
281        conn.busy_timeout(wait)
282            .map_err(|e| format!("migration lock busy_timeout: {}", e))?;
283        // The table exists only so the file is a well-formed database on
284        // first use; the lock is the RESERVED lock BEGIN IMMEDIATE takes.
285        conn.execute_batch("CREATE TABLE IF NOT EXISTS lock (id INTEGER PRIMARY KEY); BEGIN IMMEDIATE;")
286            .map_err(|e| format!("acquire migration lock {} (another runner may still hold it): {}", path.display(), e))?;
287        Ok(Self { _conn: conn })
288    }
289}
290
291/// Open the shared + channel stores the way every writer does (creating the
292/// channel dir/db on a fresh install — see the comment inside). Shared by the
293/// locked batch and the lock-free `--list`/`--dry-run` previews.
294fn open_stores_for_preview(shared_store_path: &Path, data_dir: &Path) -> Result<(Store, Option<Store>), String> {
295    let shared_store = Store::open_shared(shared_store_path)
296        .map_err(|e| format!("open shared store: {}", e))?;
297    let channel_store_path = data_dir.join("db").join("objects.db");
298    if let Some(parent) = channel_store_path.parent() {
299        std::fs::create_dir_all(parent).map_err(|e| format!("create channel db dir: {}", e))?;
300    }
301    // Channel store (objects.db) tracks channel-scoped migrations independently
302    // per channel — MigrationScope::Channel migrations record here, not in shared.
303    // Always open/create it so that seed migrations (e.g.
304    // m0016_seed_starter_mcp_servers) run on fresh install. Skipping it on a fresh install once left the
305    // Channel-scoped migrations (0002/0003/0007) out of the pending list, so
306    // they were never marked applied; when mstore then created objects.db,
307    // count_pending_migrations at ESTART reported them pending and fired the
308    // "Migration failed" UI warning on every fresh first launch.
309    // Data-transformation migrations guard themselves with
310    // `if !ctx.channel_store_path.exists()` and are no-ops on an empty db.
311    let channel_store = Store::open(&channel_store_path)
312        .map(Some)
313        .map_err(|e| format!("open channel store: {}", e))?;
314    Ok((shared_store, channel_store))
315}
316
317/// The migrations in `regs` whose tracking store does not record them applied.
318fn pending_of<'r>(
319    regs: &'r [&'r (dyn super::Migration + Sync)],
320    shared: &Store,
321    channel: Option<&Store>,
322) -> Vec<&'r (dyn super::Migration + Sync)> {
323    regs.iter()
324        .copied()
325        .filter(|m| {
326            tracking_store(m.scope(), shared, channel).map_or(false, |s| !s.migration_is_applied(m.id()))
327        })
328        .collect()
329}
330
331/// Per-migration progress hooks. Two real implementations: the CLI's NDJSON
332/// stdout lines (`run_migrate_command`), and — since this PR —
333/// `run_pending_migrations`'s `AGENTMUXSRV-MIGRATION-BEGIN`/`-END` stderr
334/// lines, which the launcher turns into live splash sub-rows. Both also
335/// still get the unconditional `tracing` lines `apply_pending` emits
336/// regardless of whether a progress hook is passed at all.
337pub(super) struct ApplyProgress<'a> {
338    pub on_start: &'a dyn Fn(&str, &str),
339    pub on_done: &'a dyn Fn(&str, u64),
340}
341
342/// Per-migration BEGIN/END lines on stderr (`agentmux_common::srv_stderr`),
343/// which the launcher shows as splash sub-rows: the daemon's batch and
344/// `migrate --prepare` report the same way.
345pub(super) const STDERR_PROGRESS: ApplyProgress<'static> = ApplyProgress {
346    on_start: &|id, description| eprintln!("{}", agentmux_common::srv_stderr::migration_begin_line(id, description)),
347    on_done: &|id, ms| eprintln!("{}", agentmux_common::srv_stderr::migration_end_line(id, ms)),
348};
349
350/// What a batch did. `skipped` = already applied at the time of the run.
351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352pub(super) struct ApplyOutcome {
353    pub applied: usize,
354    pub skipped: usize,
355}
356
357/// The locked migration batch — the ONE apply path, used by the daemon
358/// (`run_pending_migrations`) and by `agentmux-srv migrate`. Generic over the
359/// registry so the concurrency contract can be tested with a fake migration.
360///
361/// Order matters and is the point of Phase 3: the cross-process lock is
362/// taken FIRST, before the stores are even opened, so that check → run →
363/// mark is one critical section and a second runner blocks on the lock
364/// (30 min) rather than tripping `Store::open*`'s 5 s busy timeout against
365/// a migrating peer.
366pub(super) fn apply_pending(
367    regs: &[&(dyn super::Migration + Sync)],
368    home: &Path,
369    shared_store_path: &Path,
370    data_dir: &Path,
371    progress: Option<&ApplyProgress<'_>>,
372) -> Result<ApplyOutcome, String> {
373    super::gate::refuse_on_real_home(regs, shared_store_path, &home.join("shared").join("identity-store.db"))?;
374    if let Some(parent) = shared_store_path.parent() {
375        if let Err(e) = std::fs::create_dir_all(parent) {
376            return Err(format!("run_pending_migrations: create shared dir: {}", e));
377        }
378    }
379
380    // Two locks, one beside each store this batch can write, always in the
381    // same order (shared, then channel) so two runners can never deadlock
382    // on each other. One lock beside the shared store is not enough: two
383    // processes can share a `data_dir` (hence the same `objects.db`) while
384    // resolving DIFFERENT shared stores — isolated-auth instances with
385    // different `AGENTMUX_INSTANCE_DIR`s do exactly that — and would then
386    // hold different shared-side locks while racing on the same
387    // channel-scoped migrations (codex P1 on #3062).
388    let shared_lock_path = shared_store_path
389        .parent()
390        .map(|p| p.join(MIGRATION_LOCK_FILE))
391        .unwrap_or_else(|| PathBuf::from(MIGRATION_LOCK_FILE));
392    let channel_db_dir = data_dir.join("db");
393    // A splash row once the wait passes 250 ms, while it is still waiting.
394    let (_shared_lock, _channel_lock) =
395        crate::boot_timing::step_if_slow("migration_lock", "Waiting for other AgentMux", || {
396            let shared = MigrationLock::acquire(&shared_lock_path, MIGRATION_LOCK_WAIT)
397                .map_err(|e| format!("run_pending_migrations: {}", e))?;
398            std::fs::create_dir_all(&channel_db_dir)
399                .map_err(|e| format!("run_pending_migrations: create channel db dir: {}", e))?;
400            let channel = MigrationLock::acquire(&channel_db_dir.join(MIGRATION_LOCK_FILE), MIGRATION_LOCK_WAIT)
401                .map_err(|e| format!("run_pending_migrations: {}", e))?;
402            Ok::<_, String>((shared, channel))
403        })?;
404
405    // Back up BEFORE the stores are opened: opening runs schema setup, which
406    // changes the files. The decision is the boot gate's read-only check.
407    let channel_store_path = channel_db_dir.join("objects.db");
408    let identity_store_path = home.join("shared").join("identity-store.db");
409    if super::gate::pending_reason(regs, shared_store_path, &channel_store_path, &identity_store_path).is_some() {
410        super::backup::backup_stores(home, shared_store_path, data_dir)
411            .map_err(|e| format!("run_pending_migrations: backup failed: {}", e))?;
412    }
413    let (shared_store, channel_store) = open_stores_for_preview(shared_store_path, data_dir)
414        .map_err(|e| format!("run_pending_migrations: {}", e))?;
415    // Its schema setup too, here under the backup rather than in srv's startup.
416    if identity_store_path.exists() {
417        if let Err(e) = Store::open_identity_store(&identity_store_path) {
418            tracing::warn!(error = %e, "run_pending_migrations: identity store not opened");
419        }
420    }
421
422    let pending = pending_of(regs, &shared_store, channel_store.as_ref());
423    if pending.is_empty() {
424        return Ok(ApplyOutcome { applied: 0, skipped: regs.len() });
425    }
426    let skipped = regs.len() - pending.len();
427
428    let ctx = super::MigrationContext {
429        home: home.to_path_buf(),
430        data_dir: data_dir.to_path_buf(),
431        shared_store_path: shared_store_path.to_path_buf(),
432        channel_store_path: channel_store_path.clone(),
433    };
434
435    let mut applied = 0;
436    for m in &pending {
437        let t = Instant::now();
438        tracing::info!(id = m.id(), description = m.description(), "run_pending_migrations: applying");
439        if let Some(p) = progress {
440            (p.on_start)(m.id(), m.description());
441        }
442        match m.up(&ctx) {
443            Ok(()) => {
444                let ms = t.elapsed().as_millis() as u64;
445                let scope = m.scope().as_str();
446                let tracking = tracking_store(m.scope(), &shared_store, channel_store.as_ref())
447                    .ok_or_else(|| format!("run_pending_migrations: no tracking store for {} (channel store missing)", m.id()))?;
448                if let Err(e) = tracking.migration_mark_applied(m.id(), scope, ms) {
449                    return Err(format!("run_pending_migrations: failed to record {} as applied: {}", m.id(), e));
450                }
451                tracing::info!(id = m.id(), duration_ms = ms, "run_pending_migrations: applied");
452                if let Some(p) = progress {
453                    (p.on_done)(m.id(), ms);
454                }
455                applied += 1;
456            }
457            Err(e) => {
458                return Err(format!("run_pending_migrations: migration {} failed: {}", m.id(), e));
459            }
460        }
461    }
462
463    Ok(ApplyOutcome { applied, skipped })
464}
465
466// ── Pending count (used by srv startup before migration and for ESTART) ──────
467
468/// Why a pending count could not be determined. Distinguished from "zero
469/// pending" on purpose: a caller deciding whether the schema is current
470/// must be able to tell "nothing to do" from "I could not tell", because
471/// the safe reaction to each is opposite.
472#[derive(Debug)]
473pub enum PendingCountError {
474    /// No shared store path resolves (CI, or an env with no
475    /// `AGENTMUX_SHARED_DIR`). Global-scope migrations cannot be counted.
476    SharedStoreUnresolvable,
477    /// The shared store exists but would not open.
478    SharedStoreUnreadable { path: PathBuf, error: String },
479    /// The channel store would not open. Channel-scoped migrations cannot be
480    /// counted. Carries the global-scope count that WAS readable, so the
481    /// lenient wrapper can keep reporting it — but it is still an error,
482    /// because a partial count must not be mistaken for a complete one.
483    ChannelStoreUnreadable { path: PathBuf, error: String, global_pending: usize },
484}
485
486impl PendingCountError {
487    /// The pending count that WAS readable despite this error — the
488    /// global-scope half when only the channel store failed, otherwise none
489    /// at all.
490    ///
491    /// For callers that must not block on an unreadable store (the
492    /// `AGENTMUXSRV-MIGRATING` hint, which only sizes a timeout, and the
493    /// `ESTART` report, which runs after the migration batch). A caller
494    /// *deciding* anything on the count must handle the error instead — see
495    /// [`try_count_pending_migrations`].
496    pub fn readable_pending(&self) -> usize {
497        match self {
498            Self::ChannelStoreUnreadable { global_pending, .. } => *global_pending,
499            Self::SharedStoreUnresolvable | Self::SharedStoreUnreadable { .. } => 0,
500        }
501    }
502}
503
504impl std::fmt::Display for PendingCountError {
505    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
506        match self {
507            Self::SharedStoreUnresolvable => write!(f, "could not resolve the shared store path"),
508            Self::SharedStoreUnreadable { path, error } => {
509                write!(f, "failed to open the shared store at {}: {}", path.display(), error)
510            }
511            Self::ChannelStoreUnreadable { path, error, .. } => {
512                write!(f, "failed to open the channel store at {}: {}", path.display(), error)
513            }
514        }
515    }
516}
517
518/// Number of REGISTRY migrations not yet applied, or why that could not be
519/// determined.
520///
521/// Opens stores read-write (SQLite has no read-only open for WAL mode); this
522/// may create `objects.db` if it does not exist. `data_dir` must be the wave
523/// data dir (parent of `db/`), not the db dir itself.
524///
525/// WHY THIS EXISTS ALONGSIDE [`count_pending_migrations`]. That function
526/// reports `0` on every error, which is the right default for its caller:
527/// the migration run is still ahead of it, so a bad count costs nothing.
528/// It is the wrong default for a caller using the count to decide whether
529/// the schema is current — there, a transient open failure reading as
530/// "nothing pending" means proceeding against a store that may be one or
531/// many migrations behind. `SPEC_FAST_STARTUP_UPGRADE_OWNS_MIGRATIONS_AND_UPDATES_2026_09_15.md`
532/// §4.1 (invariant S1b) requires that gate to fail closed, which it cannot
533/// do without a fallible check to fail closed *on*.
534pub fn try_count_pending_migrations(data_dir: &Path) -> Result<usize, PendingCountError> {
535    let shared_store_path =
536        resolve_shared_store_path().ok_or(PendingCountError::SharedStoreUnresolvable)?;
537    let shared_store = Store::open_shared(&shared_store_path).map_err(|e| {
538        PendingCountError::SharedStoreUnreadable {
539            path: shared_store_path.clone(),
540            error: e.to_string(),
541        }
542    })?;
543    let pending_in = |channel: Option<&Store>| pending_of(REGISTRY, &shared_store, channel).len();
544    let channel_store_path = data_dir.join("db").join("objects.db");
545    let channel_store = Store::open(&channel_store_path).map_err(|e| {
546        PendingCountError::ChannelStoreUnreadable {
547            path: channel_store_path.clone(),
548            error: e.to_string(),
549            // Global-scope migrations track in the shared store, which opened
550            // fine — that half of the count is still valid.
551            global_pending: pending_in(None),
552        }
553    })?;
554    Ok(pending_in(Some(&channel_store)))
555}
556
557/// Return the number of REGISTRY migrations that have not yet been applied,
558/// reporting 0 on any error so startup is never blocked.
559///
560/// **A `0` from this function does not mean the schema is current** — it may
561/// equally mean the stores could not be read. Callers that need to tell those
562/// apart must use [`try_count_pending_migrations`]; this one exists for the
563/// reporting path (`AGENTMUXSRV-ESTART`'s `pending_migrations:` field) where
564/// the migration run has already happened and an unreadable store is not a
565/// decision point. `data_dir` must be the wave data dir (parent of `db/`),
566/// not the db dir itself.
567pub fn count_pending_migrations(data_dir: &Path) -> usize {
568    match try_count_pending_migrations(data_dir) {
569        Ok(n) => n,
570        Err(e) => {
571            // Unchanged from before this function grew a fallible sibling:
572            // an unreadable channel store still reports the global-scope
573            // count rather than dropping to 0.
574            let fallback = e.readable_pending();
575            tracing::warn!("count_pending_migrations: {} — reporting {}", e, fallback);
576            fallback
577        }
578    }
579}
580
581// ── Error log ─────────────────────────────────────────────────────────────────
582
583pub(super) fn write_error_log(home: &Path, msg: &str) {
584    let log_dir = home.join("logs");
585    let _ = std::fs::create_dir_all(&log_dir);
586    let path = log_dir.join("migration-error.log");
587    let content = format!("{}\n", msg);
588    let _ = std::fs::write(path, content);
589}
590
591// ── Verify (doctor pass) ──────────────────────────────────────────────────────
592//
593// SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03 Phase 1, second bullet: "applied"
594// in `db_migrations` means `up()` returned Ok — nothing re-checks that it
595// wrote anything. `migrate --verify` asks each APPLIED migration for its own
596// post-condition (`Migration::verify`) and reports per migration. Unapplied
597// migrations are skipped: there is nothing to verify yet, and `--list`
598// already shows them.
599//
600// Read-only by contract (codex P2 on #3058): nothing on this path calls
601// `Store::open*`. Those run schema setup, WAL configuration and legacy-table
602// adoption, and create the file when missing. This path opens plain SQLite
603// connections with SQLITE_OPEN_READ_ONLY, so a typoed data dir yields "no
604// store here", never a freshly created empty database that then "verifies".
605
606/// One line of the verify report.
607#[derive(Debug, Clone, PartialEq, Eq)]
608pub struct VerifyRecord {
609    pub id: &'static str,
610    pub scope: &'static str,
611    pub outcome: super::VerifyOutcome,
612}
613
614/// Which migration ids each tracking store records as applied, read through
615/// a FALLIBLE path. `Err` means the store exists but its tracking state
616/// could not be read (not a database, malformed table, locked): every
617/// migration of that scope then reports `VerifyOutcome::Error` instead of
618/// being silently skipped as "unapplied" and letting the pass exit 0 —
619/// codex P1 on #3058, which `Store::migration_is_applied`'s
620/// `unwrap_or(false)` would have caused. A store file that does not exist,
621/// or one predating the `db_migrations` table, has nothing recorded and is
622/// `Ok(empty)`.
623pub struct AppliedIds {
624    pub global: Result<HashSet<String>, String>,
625    pub channel: Result<HashSet<String>, String>,
626}
627
628impl AppliedIds {
629    fn for_scope(&self, scope: MigrationScope) -> &Result<HashSet<String>, String> {
630        match scope {
631            MigrationScope::Global => &self.global,
632            MigrationScope::Channel => &self.channel,
633        }
634    }
635}
636
637/// Open an existing SQLite file read-only. `Ok(None)` when the file is
638/// absent — never creates one (the whole point of this path).
639pub(super) fn open_readonly(path: &Path) -> Result<Option<rusqlite::Connection>, String> {
640    if !path.exists() {
641        return Ok(None);
642    }
643    rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
644        .map(Some)
645        .map_err(|e| format!("open {} read-only: {}", path.display(), e))
646}
647
648/// `SELECT id FROM db_migrations` through a read-only connection. A missing
649/// file or a missing table is `Ok(empty)` — nothing was ever recorded there.
650/// Any other failure is `Err`, which `verify_applied` turns into an
651/// `Error` outcome for every migration of that scope.
652pub(super) fn read_applied_ids(path: &Path) -> Result<HashSet<String>, String> {
653    let Some(conn) = open_readonly(path)? else {
654        return Ok(HashSet::new());
655    };
656    let mut stmt = match conn.prepare("SELECT id FROM db_migrations") {
657        Ok(s) => s,
658        Err(rusqlite::Error::SqliteFailure(_, Some(msg))) if msg.contains("no such table") => {
659            return Ok(HashSet::new());
660        }
661        Err(e) => return Err(format!("read db_migrations in {}: {}", path.display(), e)),
662    };
663    stmt.query_map([], |row| row.get::<_, String>(0))
664        .and_then(|rows| rows.collect::<Result<HashSet<String>, _>>())
665        .map_err(|e| format!("read db_migrations in {}: {}", path.display(), e))
666}
667
668/// Run `verify()` for every migration in `regs` whose tracking store records
669/// it as applied. Generic over the registry slice so the harness can be
670/// tested with fakes; production passes `REGISTRY`.
671pub fn verify_applied(
672    regs: &[&(dyn super::Migration + Sync)],
673    ctx: &MigrationContext,
674    applied: &AppliedIds,
675) -> Vec<VerifyRecord> {
676    let mut out = Vec::new();
677    for m in regs {
678        let outcome = match applied.for_scope(m.scope()) {
679            Err(e) => super::VerifyOutcome::Error(format!("cannot read applied state: {}", e)),
680            Ok(ids) if ids.contains(m.id()) => m.verify(ctx),
681            Ok(_) => continue,
682        };
683        out.push(VerifyRecord { id: m.id(), scope: m.scope().as_str(), outcome });
684    }
685    out
686}
687
688/// Exit code for a verify report: 0 unless any record is a mismatch or an
689/// error. `NotVerifiable` is not a failure — it is the honest default.
690pub fn verify_exit_code(records: &[VerifyRecord]) -> i32 {
691    if records.iter().any(|r| r.outcome.is_failure()) {
692        VERIFY_FAILED_EXIT_CODE
693    } else {
694        0
695    }
696}
697
698/// One `migration_verify` NDJSON line. `detail` goes through serde_json so
699/// control characters (a multi-line SQLite error, say) cannot break the
700/// line-delimited stream a consumer tails (reagent P2 on #3058).
701fn verify_event_line(r: &VerifyRecord) -> String {
702    let detail = serde_json::to_string(r.outcome.detail()).unwrap_or_else(|_| "\"\"".to_string());
703    format!(
704        "{{\"event\":\"migration_verify\",\"id\":\"{}\",\"scope\":\"{}\",\"status\":\"{}\",\"detail\":{}}}",
705        r.id,
706        r.scope,
707        r.outcome.label(),
708        detail
709    )
710}
711
712// ── Doctor report ─────────────────────────────────────────────────────────────
713//
714// SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03.md Phase 1c: the `--verify` pass
715// and the applied/pending listing, as ONE machine-readable structure that both
716// `agentmux-srv migrate --verify` (printed below) and the live instance's
717// `GET /api/v1/muxspect/migrations` (JSON) are built from. One producer, so
718// the CLI you run against a stopped install and the `muxspect migrations`
719// you run from inside a running one can never disagree about what
720// "verified" means. Read-only end to end — same `open_readonly` path as
721// `--verify`, never opens a `Store`, never creates a file.
722
723/// The complete migration doctor report for one data dir.
724#[derive(Debug, Clone, serde::Serialize)]
725pub struct DoctorReport {
726    pub data_dir: String,
727    pub shared_store: String,
728    pub channel_store: String,
729    /// One entry per tracking store whose `db_migrations` could not be read
730    /// (not a database, malformed, locked). Every migration of that scope
731    /// reads `unknown` / `error` below; this names the cause once.
732    pub tracking_errors: Vec<String>,
733    pub migrations: Vec<DoctorRow>,
734    pub summary: DoctorSummary,
735    /// What `migrate --verify` exits with for this state: `0`, or
736    /// [`VERIFY_FAILED_EXIT_CODE`] when any check is a mismatch or error.
737    pub exit_code: i32,
738}
739
740/// One registry migration, in registry order.
741#[derive(Debug, Clone, serde::Serialize)]
742pub struct DoctorRow {
743    pub id: &'static str,
744    pub scope: &'static str,
745    pub description: &'static str,
746    /// `applied` | `pending` | `unknown` — the last when the scope's
747    /// tracking store could not be read (see `tracking_errors`).
748    pub state: &'static str,
749    /// [`super::VerifyOutcome::label`] for an applied migration: `ok` |
750    /// `MISMATCH` | `error` | `n/a`. Absent for a pending one — there is no
751    /// post-condition to check until it has run.
752    #[serde(skip_serializing_if = "Option::is_none")]
753    pub verify: Option<&'static str>,
754    /// The verdict's evidence or reason (counts, the SQLite error, …).
755    #[serde(skip_serializing_if = "String::is_empty")]
756    pub detail: String,
757}
758
759#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
760pub struct DoctorSummary {
761    pub total: usize,
762    pub applied: usize,
763    pub pending: usize,
764    pub unknown: usize,
765    /// Applied migrations whose `verify()` ran — equals `applied` unless a
766    /// tracking store was unreadable.
767    pub checked: usize,
768    pub ok: usize,
769    pub mismatch: usize,
770    pub error: usize,
771    pub not_verifiable: usize,
772}
773
774/// Paths and tracking state the doctor works from. Reads both tracking
775/// stores through the fallible read-only path; never opens a `Store`.
776fn doctor_inputs(data_dir: &Path, home: &Path, shared_store_path: &Path) -> (MigrationContext, AppliedIds) {
777    let channel_store_path = data_dir.join("db").join("objects.db");
778    let ctx = MigrationContext {
779        home: home.to_path_buf(),
780        data_dir: data_dir.to_path_buf(),
781        shared_store_path: shared_store_path.to_path_buf(),
782        channel_store_path: channel_store_path.clone(),
783    };
784    let applied = AppliedIds {
785        global: read_applied_ids(shared_store_path),
786        channel: read_applied_ids(&channel_store_path),
787    };
788    (ctx, applied)
789}
790
791/// Assemble the report from an already-run verify pass, so `cmd_verify` can
792/// print the per-record NDJSON lines from the same `records` the report
793/// summarises rather than verifying twice.
794fn build_doctor_report(
795    regs: &[&(dyn super::Migration + Sync)],
796    ctx: &MigrationContext,
797    applied: &AppliedIds,
798    records: &[VerifyRecord],
799) -> DoctorReport {
800    let mut summary = DoctorSummary { total: regs.len(), ..Default::default() };
801    let mut migrations = Vec::with_capacity(regs.len());
802    for m in regs {
803        let record = records.iter().find(|r| r.id == m.id());
804        let state = match applied.for_scope(m.scope()) {
805            Err(_) => "unknown",
806            Ok(ids) if ids.contains(m.id()) => "applied",
807            Ok(_) => "pending",
808        };
809        match state {
810            "applied" => summary.applied += 1,
811            "pending" => summary.pending += 1,
812            _ => summary.unknown += 1,
813        }
814        let (verify, detail) = match record {
815            Some(r) => {
816                summary.checked += 1;
817                match r.outcome {
818                    super::VerifyOutcome::Ok(_) => summary.ok += 1,
819                    super::VerifyOutcome::Mismatch(_) => summary.mismatch += 1,
820                    super::VerifyOutcome::Error(_) => summary.error += 1,
821                    super::VerifyOutcome::NotVerifiable => summary.not_verifiable += 1,
822                }
823                (Some(r.outcome.label()), r.outcome.detail().to_string())
824            }
825            None => (None, String::new()),
826        };
827        migrations.push(DoctorRow {
828            id: m.id(),
829            scope: m.scope().as_str(),
830            description: m.description(),
831            state,
832            verify,
833            detail,
834        });
835    }
836    let tracking_errors = [&applied.global, &applied.channel]
837        .into_iter()
838        .filter_map(|r| r.as_ref().err().cloned())
839        .collect();
840    DoctorReport {
841        data_dir: ctx.data_dir.display().to_string(),
842        shared_store: ctx.shared_store_path.display().to_string(),
843        channel_store: ctx.channel_store_path.display().to_string(),
844        tracking_errors,
845        migrations,
846        summary,
847        exit_code: verify_exit_code(records),
848    }
849}
850
851/// The doctor report for `data_dir`, against an explicit registry (tests
852/// pass fakes; production passes `REGISTRY`). Read-only.
853pub fn doctor_report(
854    regs: &[&(dyn super::Migration + Sync)],
855    data_dir: &Path,
856    home: &Path,
857    shared_store_path: &Path,
858) -> DoctorReport {
859    let (ctx, applied) = doctor_inputs(data_dir, home, shared_store_path);
860    let records = verify_applied(regs, &ctx, &applied);
861    build_doctor_report(regs, &ctx, &applied, &records)
862}
863
864/// [`doctor_report`] for the running instance's own registry and resolved
865/// shared store / home — what `GET /api/v1/muxspect/migrations` serves.
866/// `Err` when the shared root can't be resolved at all (no
867/// `AGENTMUX_SHARED_DIR`, CI), the same condition under which
868/// `run_migrate_command` treats migrations as a no-op.
869pub fn doctor_report_for_instance(data_dir: &Path) -> Result<DoctorReport, String> {
870    let shared_store_path = resolve_shared_store_path()
871        .ok_or_else(|| "shared store path is unresolvable (AGENTMUX_SHARED_DIR / home not set)".to_string())?;
872    let home = resolve_home().ok_or_else(|| "AgentMux home is unresolvable".to_string())?;
873    Ok(doctor_report(REGISTRY, data_dir, &home, &shared_store_path))
874}
875
876fn cmd_verify(data_dir: &Path, home: &Path, shared_store_path: &Path) -> i32 {
877    let (ctx, applied) = doctor_inputs(data_dir, home, shared_store_path);
878    let records = verify_applied(REGISTRY, &ctx, &applied);
879    for r in &records {
880        let detail = r.outcome.detail();
881        if detail.is_empty() {
882            println!("verify: {} [{}] [{}]", r.id, r.scope, r.outcome.label());
883        } else {
884            println!("verify: {} [{}] [{}] — {}", r.id, r.scope, r.outcome.label(), detail);
885        }
886        println!("{}", verify_event_line(r));
887    }
888    let report = build_doctor_report(REGISTRY, &ctx, &applied, &records);
889    let s = &report.summary;
890    println!(
891        "verify: {} applied checked — {} ok, {} mismatch, {} error, {} not verifiable (data dir {})",
892        s.checked,
893        s.ok,
894        s.mismatch,
895        s.error,
896        s.not_verifiable,
897        data_dir.display()
898    );
899    println!(
900        "{{\"event\":\"verify_complete\",\"checked\":{},\"ok\":{},\"mismatch\":{},\"error\":{},\"not_verifiable\":{}}}",
901        s.checked, s.ok, s.mismatch, s.error, s.not_verifiable
902    );
903    report.exit_code
904}
905
906/// `SELECT COUNT(*) FROM <table>` on a (read-only) connection, treating a
907/// missing table as 0 rows — a store from before the table existed has
908/// nothing in it, which is exactly the answer a post-condition wants. Any
909/// other SQLite error is surfaced. `table` must be a literal identifier from
910/// the calling migration, never user input (it is interpolated, not bound).
911pub(super) fn table_count(conn: &rusqlite::Connection, table: &str) -> Result<i64, String> {
912    match conn.query_row(&format!("SELECT COUNT(*) FROM {}", table), [], |row| row.get::<_, i64>(0)) {
913        Ok(n) => Ok(n),
914        Err(rusqlite::Error::SqliteFailure(_, Some(msg))) if msg.contains("no such table") => Ok(0),
915        Err(e) => Err(format!("count {}: {}", table, e)),
916    }
917}
918
919#[cfg(test)]
920mod lock_tests {
921    use super::*;
922    use crate::migrations::{Migration, MigrationError};
923    use std::sync::atomic::{AtomicUsize, Ordering};
924
925    #[test]
926    fn lock_is_exclusive_across_connections_and_released_on_drop() {
927        let dir = tempfile::tempdir().unwrap();
928        let path = dir.path().join(MIGRATION_LOCK_FILE);
929        let first = MigrationLock::acquire(&path, std::time::Duration::from_millis(100)).expect("first holder");
930        // A second acquirer waits out its budget and fails while the first holds.
931        let err = MigrationLock::acquire(&path, std::time::Duration::from_millis(200))
932            .err()
933            .expect("second acquire must fail while the first is held");
934        assert!(err.contains("another runner may still hold it"), "{}", err);
935        drop(first);
936        MigrationLock::acquire(&path, std::time::Duration::from_millis(100)).expect("free after drop");
937    }
938
939    /// A Global migration that records how many times `up()` ran and is slow
940    /// enough that two runners started together both pass the "is it
941    /// pending?" check before either can mark it applied — unless the
942    /// critical section holds.
943    static UP_RUNS: AtomicUsize = AtomicUsize::new(0);
944    struct SlowOnce;
945    impl Migration for SlowOnce {
946        fn id(&self) -> &'static str { "9900_slow_once" }
947        fn scope(&self) -> MigrationScope { MigrationScope::Global }
948        fn description(&self) -> &'static str { "counts its own runs" }
949        fn up(&self, _ctx: &MigrationContext) -> Result<(), MigrationError> {
950            UP_RUNS.fetch_add(1, Ordering::SeqCst);
951            std::thread::sleep(std::time::Duration::from_millis(300));
952            Ok(())
953        }
954    }
955    static SLOW_ONCE: SlowOnce = SlowOnce;
956
957    /// Channel-scoped twin of `SlowOnce`, for the different-shared-store case.
958    static CHANNEL_UP_RUNS: AtomicUsize = AtomicUsize::new(0);
959    struct SlowOnceChannel;
960    impl Migration for SlowOnceChannel {
961        fn id(&self) -> &'static str { "9901_slow_once_channel" }
962        fn scope(&self) -> MigrationScope { MigrationScope::Channel }
963        fn description(&self) -> &'static str { "counts its own runs (channel scope)" }
964        fn up(&self, _ctx: &MigrationContext) -> Result<(), MigrationError> {
965            CHANNEL_UP_RUNS.fetch_add(1, Ordering::SeqCst);
966            std::thread::sleep(std::time::Duration::from_millis(300));
967            Ok(())
968        }
969    }
970    static SLOW_ONCE_CHANNEL: SlowOnceChannel = SlowOnceChannel;
971
972    #[test]
973    fn runners_with_different_shared_stores_but_one_data_dir_still_serialize() {
974        // codex P1 on #3062: isolated-auth instances resolve different shared
975        // stores yet can share a data dir, i.e. the same objects.db and the
976        // same channel-scoped migrations. The shared-side lock alone would let
977        // both through; the channel-side lock must catch it.
978        let dir = tempfile::tempdir().unwrap();
979        let home = dir.path().to_path_buf();
980        let data_dir = home.join("data");
981        let shared_a = home.join("iso-a").join("shared").join("store.db");
982        let shared_b = home.join("iso-b").join("shared").join("store.db");
983        CHANNEL_UP_RUNS.store(0, Ordering::SeqCst);
984
985        let results: Vec<Result<ApplyOutcome, String>> = std::thread::scope(|s| {
986            let handles: Vec<_> = [shared_a.clone(), shared_b.clone()]
987                .into_iter()
988                .map(|shared| {
989                    let (home, data_dir) = (home.clone(), data_dir.clone());
990                    s.spawn(move || {
991                        let regs: Vec<&(dyn Migration + Sync)> = vec![&SLOW_ONCE_CHANNEL];
992                        apply_pending(&regs, &home, &shared, &data_dir, None)
993                    })
994                })
995                .collect();
996            handles.into_iter().map(|h| h.join().expect("runner thread")).collect()
997        });
998
999        for r in &results {
1000            assert!(r.is_ok(), "both runners must succeed: {:?}", results);
1001        }
1002        let applied: usize = results.iter().map(|r| r.as_ref().unwrap().applied).sum();
1003        assert_eq!(applied, 1, "exactly one runner applied it: {:?}", results);
1004        assert_eq!(CHANNEL_UP_RUNS.load(Ordering::SeqCst), 1, "channel-scoped up() ran once despite two shared stores");
1005    }
1006
1007    #[test]
1008    fn previews_do_not_wait_on_the_migration_lock() {
1009        // reagent P1 on #3062: `--list` / `--dry-run` must stay usable while
1010        // another process is mid-migration. Hold the lock, then take the same
1011        // read path the previews use and require it to come back at once.
1012        let dir = tempfile::tempdir().unwrap();
1013        let shared = dir.path().join("shared").join("store.db");
1014        std::fs::create_dir_all(shared.parent().unwrap()).unwrap();
1015        let data_dir = dir.path().join("data");
1016        let _held = MigrationLock::acquire(&shared.parent().unwrap().join(MIGRATION_LOCK_FILE), std::time::Duration::from_millis(100))
1017            .expect("hold the lock");
1018
1019        let before = UP_RUNS.load(Ordering::SeqCst);
1020        let started = std::time::Instant::now();
1021        let (shared_store, channel_store) = open_stores_for_preview(&shared, &data_dir).expect("preview opens stores");
1022        let regs: Vec<&(dyn Migration + Sync)> = vec![&SLOW_ONCE];
1023        let pending = pending_of(&regs, &shared_store, channel_store.as_ref());
1024        assert_eq!(pending.len(), 1, "nothing applied yet, so the fake is pending");
1025        assert!(started.elapsed() < std::time::Duration::from_secs(5), "preview must not block on the lock");
1026        assert_eq!(UP_RUNS.load(Ordering::SeqCst), before, "preview never runs up()");
1027    }
1028
1029    #[test]
1030    fn two_concurrent_runners_on_one_data_dir_apply_a_migration_exactly_once() {
1031        // Phase 3 acceptance (SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03):
1032        // "two concurrent run_pending_migrations calls against the same
1033        // fresh data dir; assert the migration's up() body executes exactly
1034        // once." Both runners must also succeed: the loser sees the winner's
1035        // db_migrations row once it gets the lock and applies nothing.
1036        let dir = tempfile::tempdir().unwrap();
1037        let home = dir.path().to_path_buf();
1038        let shared = home.join("shared").join("store.db");
1039        let data_dir = home.join("data");
1040        UP_RUNS.store(0, Ordering::SeqCst);
1041
1042        let results: Vec<Result<usize, String>> = std::thread::scope(|s| {
1043            let handles: Vec<_> = (0..2)
1044                .map(|_| {
1045                    let (home, shared, data_dir) = (home.clone(), shared.clone(), data_dir.clone());
1046                    s.spawn(move || {
1047                        let regs: Vec<&(dyn Migration + Sync)> = vec![&SLOW_ONCE];
1048                        apply_pending(&regs, &home, &shared, &data_dir, None).map(|o| o.applied)
1049                    })
1050                })
1051                .collect();
1052            handles.into_iter().map(|h| h.join().expect("runner thread")).collect()
1053        });
1054
1055        for r in &results {
1056            assert!(r.is_ok(), "both runners must succeed: {:?}", results);
1057        }
1058        let applied: usize = results.iter().map(|r| *r.as_ref().unwrap()).sum();
1059        assert_eq!(applied, 1, "exactly one runner applied it: {:?}", results);
1060        assert_eq!(UP_RUNS.load(Ordering::SeqCst), 1, "up() body must execute exactly once");
1061
1062        // And the record is durable: a third run has nothing to do.
1063        let regs: Vec<&(dyn Migration + Sync)> = vec![&SLOW_ONCE];
1064        assert_eq!(apply_pending(&regs, &home, &shared, &data_dir, None).map(|o| o.applied).unwrap(), 0);
1065        assert_eq!(UP_RUNS.load(Ordering::SeqCst), 1);
1066    }
1067}
1068
1069#[cfg(test)]
1070mod verify_tests {
1071    use super::*;
1072    use crate::migrations::{Migration, MigrationError, VerifyOutcome};
1073
1074    /// A migration whose `verify()` returns a canned outcome. `up()` is never
1075    /// called by the verify harness.
1076    struct Fake {
1077        id: &'static str,
1078        scope: MigrationScope,
1079        outcome: VerifyOutcome,
1080    }
1081    impl Migration for Fake {
1082        fn id(&self) -> &'static str { self.id }
1083        fn scope(&self) -> MigrationScope { self.scope }
1084        fn description(&self) -> &'static str { "fake" }
1085        fn up(&self, _ctx: &MigrationContext) -> Result<(), MigrationError> { Ok(()) }
1086        fn verify(&self, _ctx: &MigrationContext) -> VerifyOutcome { self.outcome.clone() }
1087    }
1088
1089    /// Default `verify()` — a migration that never opted in.
1090    struct Silent;
1091    impl Migration for Silent {
1092        fn id(&self) -> &'static str { "9998_silent" }
1093        fn scope(&self) -> MigrationScope { MigrationScope::Global }
1094        fn description(&self) -> &'static str { "no verify impl" }
1095        fn up(&self, _ctx: &MigrationContext) -> Result<(), MigrationError> { Ok(()) }
1096    }
1097
1098    fn ctx_in(dir: &tempfile::TempDir) -> MigrationContext {
1099        MigrationContext {
1100            home: dir.path().to_path_buf(),
1101            data_dir: dir.path().join("data"),
1102            shared_store_path: dir.path().join("shared").join("store.db"),
1103            channel_store_path: dir.path().join("data").join("db").join("objects.db"),
1104        }
1105    }
1106
1107    fn ids(list: &[&str]) -> Result<HashSet<String>, String> {
1108        Ok(list.iter().map(|s| s.to_string()).collect())
1109    }
1110
1111    #[test]
1112    fn only_applied_migrations_are_verified_and_unapplied_are_skipped() {
1113        let dir = tempfile::tempdir().unwrap();
1114        let applied = Fake { id: "9001_applied", scope: MigrationScope::Global, outcome: VerifyOutcome::Ok("fine".into()) };
1115        let pending = Fake { id: "9002_pending", scope: MigrationScope::Global, outcome: VerifyOutcome::Mismatch("would fail".into()) };
1116        let state = AppliedIds { global: ids(&["9001_applied"]), channel: ids(&[]) };
1117
1118        let regs: Vec<&(dyn Migration + Sync)> = vec![&applied, &pending];
1119        let records = verify_applied(&regs, &ctx_in(&dir), &state);
1120        assert_eq!(records.len(), 1, "the pending one has nothing to verify yet");
1121        assert_eq!(records[0].id, "9001_applied");
1122        assert_eq!(records[0].outcome, VerifyOutcome::Ok("fine".into()));
1123        assert_eq!(verify_exit_code(&records), 0);
1124    }
1125
1126    #[test]
1127    fn channel_scoped_migrations_consult_the_channel_state_not_the_global_one() {
1128        let dir = tempfile::tempdir().unwrap();
1129        let m = Fake { id: "9003_channel", scope: MigrationScope::Channel, outcome: VerifyOutcome::Ok("ok".into()) };
1130        let regs: Vec<&(dyn Migration + Sync)> = vec![&m];
1131        // Recorded in the GLOBAL set only: wrong tracking store for a Channel
1132        // migration, so it must read as unapplied.
1133        let wrong = AppliedIds { global: ids(&["9003_channel"]), channel: ids(&[]) };
1134        assert!(verify_applied(&regs, &ctx_in(&dir), &wrong).is_empty());
1135        let right = AppliedIds { global: ids(&[]), channel: ids(&["9003_channel"]) };
1136        assert_eq!(verify_applied(&regs, &ctx_in(&dir), &right).len(), 1);
1137    }
1138
1139    #[test]
1140    fn unreadable_tracking_state_is_an_error_for_every_migration_of_that_scope() {
1141        // codex P1 on #3058: a broken db_migrations must not read as "nothing
1142        // applied" and let the pass exit 0.
1143        let dir = tempfile::tempdir().unwrap();
1144        let g = Fake { id: "9004_global", scope: MigrationScope::Global, outcome: VerifyOutcome::Ok("never reached".into()) };
1145        let c = Fake { id: "9005_channel", scope: MigrationScope::Channel, outcome: VerifyOutcome::Ok("fine".into()) };
1146        let regs: Vec<&(dyn Migration + Sync)> = vec![&g, &c];
1147        let state = AppliedIds { global: Err("file is not a database".into()), channel: ids(&["9005_channel"]) };
1148        let records = verify_applied(&regs, &ctx_in(&dir), &state);
1149        assert_eq!(records.len(), 2);
1150        assert!(matches!(&records[0].outcome, VerifyOutcome::Error(e) if e.contains("not a database")));
1151        assert_eq!(records[1].outcome, VerifyOutcome::Ok("fine".into()));
1152        assert_eq!(verify_exit_code(&records), VERIFY_FAILED_EXIT_CODE);
1153    }
1154
1155    #[test]
1156    fn a_migration_without_a_verify_impl_reports_not_verifiable_and_passes() {
1157        let dir = tempfile::tempdir().unwrap();
1158        let regs: Vec<&(dyn Migration + Sync)> = vec![&Silent];
1159        let state = AppliedIds { global: ids(&["9998_silent"]), channel: ids(&[]) };
1160        let records = verify_applied(&regs, &ctx_in(&dir), &state);
1161        assert_eq!(records[0].outcome, VerifyOutcome::NotVerifiable);
1162        assert_eq!(verify_exit_code(&records), 0, "not verifiable is honest, not a failure");
1163    }
1164
1165    #[test]
1166    fn mismatch_or_error_fails_the_pass_with_a_code_distinct_from_run_failure_and_clap() {
1167        let mk = |o: VerifyOutcome| VerifyRecord { id: "x", scope: "global", outcome: o };
1168        assert_eq!(verify_exit_code(&[mk(VerifyOutcome::Ok("a".into())), mk(VerifyOutcome::NotVerifiable)]), 0);
1169        assert_eq!(verify_exit_code(&[mk(VerifyOutcome::Ok("a".into())), mk(VerifyOutcome::Mismatch("gone".into()))]), VERIFY_FAILED_EXIT_CODE);
1170        assert_eq!(verify_exit_code(&[mk(VerifyOutcome::Error("locked".into()))]), VERIFY_FAILED_EXIT_CODE);
1171        assert_ne!(VERIFY_FAILED_EXIT_CODE, 1, "1 = a migration run failed");
1172        assert_ne!(VERIFY_FAILED_EXIT_CODE, 2, "2 = clap usage error (bad flag)");
1173    }
1174
1175    #[test]
1176    fn read_applied_ids_reads_real_tracking_state_and_never_creates_a_store() {
1177        let dir = tempfile::tempdir().unwrap();
1178        let path = dir.path().join("shared").join("store.db");
1179        // Absent file: nothing recorded, and still absent afterwards.
1180        assert_eq!(read_applied_ids(&path).unwrap(), HashSet::new());
1181        assert!(!path.exists(), "verify must never create a database");
1182
1183        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1184        let store = Store::open_shared(&path).expect("open shared");
1185        store.migration_mark_applied("9010_a", "global", 1).unwrap();
1186        store.migration_mark_applied("9011_b", "global", 1).unwrap();
1187        drop(store);
1188        let got = read_applied_ids(&path).unwrap();
1189        assert!(got.contains("9010_a") && got.contains("9011_b"));
1190        assert_eq!(got.len(), 2);
1191    }
1192
1193    #[test]
1194    fn read_applied_ids_errors_on_a_file_that_is_not_a_database() {
1195        let dir = tempfile::tempdir().unwrap();
1196        let path = dir.path().join("objects.db");
1197        std::fs::write(&path, b"definitely not sqlite\n").unwrap();
1198        let err = read_applied_ids(&path).unwrap_err();
1199        assert!(err.contains("objects.db"), "names the store: {}", err);
1200    }
1201
1202    #[test]
1203    fn table_count_treats_a_missing_table_as_zero_rows() {
1204        let dir = tempfile::tempdir().unwrap();
1205        let path = dir.path().join("objects.db");
1206        drop(Store::open(&path).expect("create channel store"));
1207        let conn = open_readonly(&path).unwrap().expect("exists");
1208        assert_eq!(table_count(&conn, "db_table_that_never_existed").unwrap(), 0);
1209        assert!(table_count(&conn, "db_migrations").is_ok());
1210    }
1211
1212    // ---- Doctor report (Phase 1c — the producer `muxspect migrations` serves) ----
1213
1214    #[test]
1215    fn doctor_report_on_a_fresh_data_dir_lists_everything_pending_and_creates_nothing() {
1216        let dir = tempfile::tempdir().unwrap();
1217        let data_dir = dir.path().join("data");
1218        let shared = dir.path().join("shared").join("store.db");
1219        let report = doctor_report(REGISTRY, &data_dir, dir.path(), &shared);
1220
1221        assert_eq!(report.migrations.len(), REGISTRY.len());
1222        assert!(report.migrations.iter().all(|r| r.state == "pending" && r.verify.is_none()));
1223        assert_eq!(report.summary.total, REGISTRY.len());
1224        assert_eq!(report.summary.pending, REGISTRY.len());
1225        assert_eq!(report.summary.checked, 0);
1226        assert!(report.tracking_errors.is_empty());
1227        assert_eq!(report.exit_code, 0);
1228        // Read-only, like --verify: a doctor must never conjure a store.
1229        assert!(!shared.exists() && !data_dir.exists(), "doctor created files");
1230        // Serialises — the handler returns this as JSON.
1231        let json = serde_json::to_value(&report).unwrap();
1232        assert_eq!(json["summary"]["pending"], REGISTRY.len());
1233        assert!(json["migrations"][0].get("verify").is_none(), "pending rows omit `verify`");
1234    }
1235
1236    #[test]
1237    fn doctor_report_reports_applied_rows_with_their_verdict_and_counts_them() {
1238        let dir = tempfile::tempdir().unwrap();
1239        let data_dir = dir.path().join("data");
1240        let channel = data_dir.join("db").join("objects.db");
1241        std::fs::create_dir_all(channel.parent().unwrap()).unwrap();
1242        let shared = dir.path().join("shared").join("store.db");
1243        {
1244            // A fresh channel store with 0007 recorded applied: no legacy
1245            // rows, empty target — consistent, so the verdict is `ok`.
1246            let store = Store::open(&channel).expect("create channel store");
1247            store.migration_mark_applied("0007_agents_consolidate", "channel", 1).unwrap();
1248        }
1249        let report = doctor_report(REGISTRY, &data_dir, dir.path(), &shared);
1250        let row = report.migrations.iter().find(|r| r.id == "0007_agents_consolidate").unwrap();
1251        assert_eq!(row.state, "applied");
1252        assert_eq!(row.verify, Some("ok"));
1253        assert!(row.detail.contains("no legacy rows"), "{}", row.detail);
1254        assert_eq!(report.summary.applied, 1);
1255        assert_eq!(report.summary.checked, 1);
1256        assert_eq!(report.summary.ok, 1);
1257        assert_eq!(report.summary.pending, REGISTRY.len() - 1);
1258        assert_eq!(report.exit_code, 0);
1259    }
1260
1261    #[test]
1262    fn doctor_report_marks_a_scope_unknown_when_its_tracking_store_is_unreadable_and_exits_3() {
1263        let dir = tempfile::tempdir().unwrap();
1264        let data_dir = dir.path().join("data");
1265        let shared = dir.path().join("shared").join("store.db");
1266        std::fs::create_dir_all(shared.parent().unwrap()).unwrap();
1267        std::fs::write(&shared, b"definitely not sqlite\n").unwrap();
1268        let report = doctor_report(REGISTRY, &data_dir, dir.path(), &shared);
1269
1270        let global_rows: Vec<_> = report.migrations.iter().filter(|r| r.scope == "global").collect();
1271        assert!(!global_rows.is_empty());
1272        assert!(global_rows.iter().all(|r| r.state == "unknown" && r.verify == Some("error")));
1273        assert!(report.migrations.iter().filter(|r| r.scope == "channel").all(|r| r.state == "pending"));
1274        assert_eq!(report.summary.unknown, global_rows.len());
1275        assert_eq!(report.summary.error, global_rows.len());
1276        // The cause is named once, not once per migration.
1277        assert_eq!(report.tracking_errors.len(), 1, "{:?}", report.tracking_errors);
1278        assert!(report.tracking_errors[0].contains("store.db"));
1279        assert_eq!(report.exit_code, VERIFY_FAILED_EXIT_CODE);
1280    }
1281
1282    #[test]
1283    fn verify_event_line_is_valid_json_even_with_control_characters_in_detail() {
1284        let r = VerifyRecord {
1285            id: "9020_x",
1286            scope: "channel",
1287            outcome: VerifyOutcome::Error("line one\nline \"two\"\t\\end".into()),
1288        };
1289        let line = verify_event_line(&r);
1290        let parsed: serde_json::Value = serde_json::from_str(&line).expect("one JSON object per line");
1291        assert_eq!(parsed["event"], "migration_verify");
1292        assert_eq!(parsed["status"], "error");
1293        assert_eq!(parsed["detail"], "line one\nline \"two\"\t\\end");
1294        assert!(!line.contains('\n'), "must stay on one line");
1295    }
1296}
1297
1298#[cfg(test)]
1299mod tests {
1300    use super::*;
1301
1302    // Process-global env access — shared with registry::paths and
1303    // migrations::m0011_shared_store_backfill's tests, which mutate the SAME
1304    // AGENTMUX_ISOLATED_AUTH/AGENTMUX_INSTANCE_DIR vars. A module-local lock
1305    // only serializes tests within this file; Cargo runs a crate's tests in
1306    // one multi-threaded process, so a local-only lock still let this
1307    // module's tests race against those two (reagent/codex on PR #2318).
1308    use crate::test_support::ISOLATED_AUTH_ENV_LOCK as ENV_LOCK;
1309
1310    fn clear() {
1311        std::env::remove_var("AGENTMUX_HOME_OVERRIDE");
1312        std::env::remove_var("AGENTMUX_SHARED_DIR");
1313        std::env::remove_var("AGENTMUX_ISOLATED_AUTH");
1314        std::env::remove_var("AGENTMUX_INSTANCE_DIR");
1315        std::env::remove_var("AGENTMUX_CHANNEL");
1316    }
1317
1318    // ── Pending count: lenient vs. fail-closed ───────────────────────────
1319
1320    #[test]
1321    fn an_unreadable_shared_store_is_an_error_not_a_zero() {
1322        // The trap this pair of functions exists to separate: a caller
1323        // deciding whether the schema is current cannot act on `0`, because
1324        // `0` is also what an unreadable store produces.
1325        // SPEC_FAST_STARTUP_UPGRADE_OWNS_MIGRATIONS_AND_UPDATES_2026_09_15 S1b.
1326        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1327        clear();
1328        // A home with no `shared/` directory: SQLite will not create the
1329        // parent, so the shared store cannot be opened.
1330        let home = tempfile::tempdir().expect("tempdir");
1331        std::env::set_var("AGENTMUX_HOME_OVERRIDE", home.path());
1332        let data_dir = home.path().join("data");
1333
1334        let strict = try_count_pending_migrations(&data_dir);
1335        let lenient = count_pending_migrations(&data_dir);
1336        clear();
1337
1338        match strict {
1339            Err(PendingCountError::SharedStoreUnreadable { .. }) => {}
1340            Err(other) => panic!("expected SharedStoreUnreadable, got {other}"),
1341            Ok(n) => panic!("an unreadable shared store must not read as {n} pending"),
1342        }
1343        assert_eq!(lenient, 0, "the lenient wrapper still reports 0, as it always did");
1344    }
1345
1346    #[test]
1347    fn the_lenient_wrapper_keeps_reporting_the_global_half_it_could_read() {
1348        // An unreadable CHANNEL store is the partial case: global-scope
1349        // migrations track in the shared store, which opened fine. The
1350        // fallible check still refuses to answer (the total is incomplete);
1351        // the lenient one reports the half it could read, exactly as it did
1352        // before it grew a fallible sibling.
1353        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1354        clear();
1355        let home = tempfile::tempdir().expect("tempdir");
1356        std::fs::create_dir_all(home.path().join("shared")).expect("shared dir");
1357        std::env::set_var("AGENTMUX_HOME_OVERRIDE", home.path());
1358        // No `db/` under it, so the channel store cannot open.
1359        let data_dir = home.path().join("no-such-data-dir");
1360
1361        let strict = try_count_pending_migrations(&data_dir);
1362        let lenient = count_pending_migrations(&data_dir);
1363        let global_pending = match &strict {
1364            Err(PendingCountError::ChannelStoreUnreadable { global_pending, .. }) => *global_pending,
1365            other => {
1366                let msg = format!("precondition: expected ChannelStoreUnreadable, got {other:?}");
1367                clear();
1368                panic!("{msg}");
1369            }
1370        };
1371        clear();
1372
1373        assert_eq!(
1374            lenient, global_pending,
1375            "the lenient wrapper must keep reporting the readable global-scope count"
1376        );
1377    }
1378
1379    #[test]
1380    fn readable_pending_keeps_the_global_half_but_claims_nothing_otherwise() {
1381        // What the non-blocking callers fall back to. A shared-store failure
1382        // has no readable half at all — reporting anything but 0 there would
1383        // be inventing a number.
1384        assert_eq!(
1385            PendingCountError::ChannelStoreUnreadable {
1386                path: std::path::PathBuf::from("/tmp/objects.db"),
1387                error: "locked".into(),
1388                global_pending: 3,
1389            }
1390            .readable_pending(),
1391            3
1392        );
1393        assert_eq!(PendingCountError::SharedStoreUnresolvable.readable_pending(), 0);
1394        assert_eq!(
1395            PendingCountError::SharedStoreUnreadable {
1396                path: std::path::PathBuf::from("/tmp/store.db"),
1397                error: "locked".into(),
1398            }
1399            .readable_pending(),
1400            0
1401        );
1402    }
1403
1404    #[test]
1405    fn a_pending_count_error_says_which_store_and_why() {
1406        // The blocking upgrade state shows this text to a human, so it has to
1407        // name the store and carry the underlying reason rather than being a
1408        // bare "could not count".
1409        let e = PendingCountError::SharedStoreUnreadable {
1410            path: std::path::PathBuf::from("/tmp/store.db"),
1411            error: "disk I/O error".to_string(),
1412        };
1413        let msg = e.to_string();
1414        assert!(msg.contains("store.db"), "{msg}");
1415        assert!(msg.contains("disk I/O error"), "{msg}");
1416    }
1417
1418    /// The regression test that would have caught the `ctx.home` /
1419    /// `shared_store_path` coupling bug before it shipped: `resolve_home()`
1420    /// must return the SAME value whether or not isolated-auth is active,
1421    /// even though `resolve_shared_store_path()` itself deliberately
1422    /// returns a DIFFERENT (channel-scoped) path under isolation. Every
1423    /// other Global migration, plus backups and the error log, anchor to
1424    /// `home` and must never silently move just because one channel opted
1425    /// into isolated auth.
1426    #[test]
1427    fn home_is_invariant_to_isolated_auth() {
1428        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1429        clear();
1430        std::env::set_var("AGENTMUX_HOME_OVERRIDE", "/tmp/test-home");
1431
1432        let home_default = resolve_home().unwrap();
1433        assert_eq!(home_default, PathBuf::from("/tmp/test-home"));
1434
1435        let shared_store_path_default = resolve_shared_store_path().unwrap();
1436
1437        std::env::set_var("AGENTMUX_ISOLATED_AUTH", "1");
1438        std::env::set_var("AGENTMUX_INSTANCE_DIR", "/tmp/test-home/dev/some-branch");
1439        let home_isolated = resolve_home().unwrap();
1440        let shared_store_path_isolated = resolve_shared_store_path().unwrap();
1441
1442        assert_eq!(
1443            home_default, home_isolated,
1444            "resolve_home() must be invariant to AGENTMUX_ISOLATED_AUTH/AGENTMUX_INSTANCE_DIR"
1445        );
1446        // Meanwhile resolve_shared_store_path() DOES vary — confirms the two
1447        // functions have genuinely diverged as designed, not that isolation
1448        // silently does nothing.
1449        assert_ne!(
1450            shared_store_path_default, shared_store_path_isolated,
1451            "resolve_shared_store_path() must actually change under isolation"
1452        );
1453
1454        clear();
1455    }
1456
1457    /// Same invariant as `home_is_invariant_to_isolated_auth`, with a
1458    /// non-"stable" channel and an instance dir present. Auth is shared by
1459    /// default on every channel now (SPEC_SHARED_AUTH_ACROSS_CHANNELS_2026_10_03.md),
1460    /// so the channel alone changes nothing: neither the home nor the store path.
1461    #[test]
1462    fn home_and_store_are_invariant_to_the_channel_when_auth_is_shared() {
1463        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1464        clear();
1465        std::env::set_var("AGENTMUX_HOME_OVERRIDE", "/tmp/test-home");
1466
1467        let home_default = resolve_home().unwrap();
1468        let shared_store_path_default = resolve_shared_store_path().unwrap();
1469
1470        // No AGENTMUX_ISOLATED_AUTH set at all — only a non-"stable" channel.
1471        std::env::set_var("AGENTMUX_CHANNEL", "dev-some-branch");
1472        std::env::set_var("AGENTMUX_INSTANCE_DIR", "/tmp/test-home/dev/some-branch");
1473        let home_isolated = resolve_home().unwrap();
1474        let shared_store_path_isolated = resolve_shared_store_path().unwrap();
1475
1476        assert_eq!(
1477            home_default, home_isolated,
1478            "resolve_home() must not depend on the channel"
1479        );
1480        assert_eq!(
1481            shared_store_path_default, shared_store_path_isolated,
1482            "a non-stable channel alone must not move the shared store"
1483        );
1484
1485        // An explicit opt-in still isolates, and still leaves the home alone.
1486        std::env::set_var("AGENTMUX_ISOLATED_AUTH", "1");
1487        assert_eq!(resolve_home().unwrap(), home_default);
1488        assert_ne!(resolve_shared_store_path().unwrap(), shared_store_path_default);
1489
1490        clear();
1491    }
1492}