Skip to main content

agentmux_srv_core/migrations/
gate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! srv's boot gate: whether this version's data needs `agentmux-srv migrate
5//! --prepare` before srv may open it (S1c of
6//! `docs/specs/SPEC_FAST_STARTUP_UPGRADE_OWNS_MIGRATIONS_AND_UPDATES_2026_09_15.md` ยง10).
7//!
8//! Read-only, and fail-closed (invariants S1b and S1c there): it only opens
9//! stores read-only, creates nothing, and any doubt (a store it cannot read)
10//! counts as "needs preparing", so srv never boots onto data it couldn't
11//! check. A boot with nothing to prepare costs two read-only opens, in place
12//! of the read-write pending count it replaces.
13
14use std::path::Path;
15
16use super::runner::read_applied_ids;
17use super::{MigrationScope, REGISTRY};
18
19/// Why `data_dir` needs preparing, or `None` when srv can open it as it is.
20pub fn data_needs_preparing(data_dir: &Path, version: &str) -> Option<String> {
21    let db_dir = data_dir.join("db");
22    if let Some(source) = crate::migrations::carry_forward::source_for(&db_dir, version) {
23        return Some(format!("this version has no data yet; {} has data to copy forward", source.display()));
24    }
25    // No shared root (CI, a bare cargo run): nothing to migrate, as for
26    // `run_pending_migrations`.
27    let shared = crate::registry::resolve_shared_store_path()?;
28    let identity = crate::registry::resolve_identity_store_path()?;
29    // A dev build on the real home says why it won't touch the shared stores, ahead of the generic
30    // reason: `migrate --prepare` refuses with the same words.
31    if let Err(why) = refuse_on_real_home(REGISTRY, &shared, &identity) {
32        return Some(why);
33    }
34    pending_reason(REGISTRY, &shared, &db_dir.join("objects.db"), &identity)
35}
36
37/// Why the stores `migrate --prepare` opens need work: a schema older than
38/// this build's (its schema setup would change the file), a migration of
39/// `regs` not yet applied, or a store that can't be read. `None` when they need
40/// nothing. Read-only; `apply_pending` asks it too, to take its backup before
41/// anything opens the stores.
42///
43/// `identity-store.db` only counts when it is readable and behind: srv starts
44/// without it when it can't open it, and preparing couldn't repair it.
45pub(super) fn pending_reason(
46    regs: &[&(dyn super::Migration + Sync)],
47    shared_store: &Path,
48    objects_db: &Path,
49    identity_store: &Path,
50) -> Option<String> {
51    use crate::backend::storage::migrations::{
52        IDENTITY_STORE_SCHEMA_VERSION, OBJECT_SCHEMA_VERSION, SHARED_STORE_SCHEMA_VERSION,
53    };
54    let stores = [
55        (shared_store, SHARED_STORE_SCHEMA_VERSION, true),
56        (objects_db, OBJECT_SCHEMA_VERSION, true),
57        (identity_store, IDENTITY_STORE_SCHEMA_VERSION, false),
58    ];
59    for (path, current, required) in stores {
60        match schema_version(path) {
61            Ok(Some(found)) if found < current => {
62                return Some(format!("{} is at schema {found}, this build uses {current}", path.display()))
63            }
64            Err(e) if required => return Some(format!("{}'s schema version can't be read: {e}", path.display())),
65            _ => {}
66        }
67    }
68    let shared_applied = match read_applied_ids(shared_store) {
69        Ok(ids) => ids,
70        Err(e) => return Some(format!("the shared store's migrations can't be read: {e}")),
71    };
72    let channel_applied = match read_applied_ids(objects_db) {
73        Ok(ids) => ids,
74        Err(e) => return Some(format!("this version's migrations can't be read: {e}")),
75    };
76    let pending: Vec<&str> = regs
77        .iter()
78        .filter(|m| {
79            let applied = match m.scope() {
80                MigrationScope::Global => &shared_applied,
81                MigrationScope::Channel => &channel_applied,
82            };
83            !applied.contains(m.id())
84        })
85        .map(|m| m.id())
86        .collect();
87    let first = pending.first()?;
88    Some(format!("{} migration(s) pending, starting with {first}", pending.len()))
89}
90
91/// `task dev` sets this to `real` when it runs on the person's own `~/.agentmux`
92/// (`AGENTMUX_DEV_USE_REAL_HOME=1`), `isolated` otherwise.
93const DEV_HOME_MODE_ENV: &str = "AGENTMUX_DEV_HOME_MODE";
94
95/// How many pending migration ids the refusal names; the rest are counted.
96const MAX_IDS_SHOWN: usize = 5;
97
98#[cfg(any(test, feature = "test-support"))]
99thread_local! {
100    /// Lets a test act as a dev build on the real home without touching the process environment.
101    pub(super) static FORCE_REAL_HOME: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
102}
103
104/// Is this a dev build running on the real home?
105pub(super) fn dev_on_real_home() -> bool {
106    #[cfg(any(test, feature = "test-support"))]
107    if FORCE_REAL_HOME.with(|f| f.get()) {
108        return true;
109    }
110    std::env::var(DEV_HOME_MODE_ENV).as_deref() == Ok("real")
111}
112
113/// Refuses, before anything is locked, backed up or opened, when a dev build on
114/// the real home would move the stores every installed build shares ahead of
115/// them. Opening a store runs its schema setup and a Global migration rewrites
116/// the shared store, and the installed build can't read a store that is ahead of
117/// it. A channel-scoped migration only touches the dev build's own data, so it is
118/// no reason to refuse. Read-only; a no-op for any other build.
119pub(super) fn refuse_on_real_home(
120    regs: &[&(dyn super::Migration + Sync)],
121    shared_store: &Path,
122    identity_store: &Path,
123) -> Result<(), String> {
124    if !dev_on_real_home() {
125        return Ok(());
126    }
127    match real_home_would_move(regs, shared_store, identity_store) {
128        Some(what) => Err(format!(
129            "this dev build runs on your real AgentMux home and would move the shared stores ahead of the installed build: {what}. \
130             Either run it on an isolated home (`task dev` without AGENTMUX_DEV_USE_REAL_HOME=1), \
131             or start the installed AgentMux build first and let it migrate the shared stores."
132        )),
133        None => Ok(()),
134    }
135}
136
137/// [`refuse_on_real_home`] for the stores this process would open. Called before the startup
138/// count of pending migrations, which opens the shared store like any other writer.
139pub fn refuse_if_real_home_would_move() -> Result<(), String> {
140    let (Some(shared), Some(identity)) = (crate::registry::resolve_shared_store_path(), crate::registry::resolve_identity_store_path()) else {
141        return Ok(());
142    };
143    refuse_on_real_home(REGISTRY, &shared, &identity)
144}
145
146/// What a build of this version would change in the shared stores, or `None`.
147/// A store that doesn't exist yet has nobody to move ahead of.
148pub(super) fn real_home_would_move(
149    regs: &[&(dyn super::Migration + Sync)],
150    shared_store: &Path,
151    identity_store: &Path,
152) -> Option<String> {
153    use crate::backend::storage::migrations::{IDENTITY_STORE_SCHEMA_VERSION, SHARED_STORE_SCHEMA_VERSION};
154    let mut what = Vec::new();
155    for (path, current) in [(shared_store, SHARED_STORE_SCHEMA_VERSION), (identity_store, IDENTITY_STORE_SCHEMA_VERSION)] {
156        match schema_version(path) {
157            Ok(Some(found)) if found < current => {
158                what.push(format!("{} is at schema {found}, this build uses {current}", path.display()))
159            }
160            Err(e) => what.push(format!("{}'s schema version can't be read: {e}", path.display())),
161            _ => {}
162        }
163    }
164    if shared_store.exists() {
165        match read_applied_ids(shared_store) {
166            Ok(applied) => {
167                let ids: Vec<&str> = regs
168                    .iter()
169                    .filter(|m| m.scope() == MigrationScope::Global && !applied.contains(m.id()))
170                    .map(|m| m.id())
171                    .collect();
172                if !ids.is_empty() {
173                    let more = ids.len().saturating_sub(MAX_IDS_SHOWN);
174                    let more = if more > 0 { format!(" and {more} more") } else { String::new() };
175                    what.push(format!("shared-store migration(s) pending: {}{more}", ids[..ids.len().min(MAX_IDS_SHOWN)].join(", ")));
176                }
177            }
178            Err(e) => what.push(format!("the shared store's migrations can't be read: {e}")),
179        }
180    }
181    (!what.is_empty()).then(|| what.join("; "))
182}
183
184/// `PRAGMA user_version` of the database at `path`, read-only; `None` when
185/// the file doesn't exist yet.
186fn schema_version(path: &Path) -> Result<Option<i64>, String> {
187    let Some(conn) = super::runner::open_readonly(path)? else { return Ok(None) };
188    conn.query_row("PRAGMA user_version", [], |r| r.get(0)).map(Some).map_err(|e| e.to_string())
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::backend::storage::store::Store;
195
196    /// An identity store that doesn't exist: nothing to prepare for it.
197    fn no_identity(dir: &Path) -> std::path::PathBuf {
198        dir.join("identity-store.db")
199    }
200
201    /// Stores with every registered migration recorded as applied.
202    fn migrated(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
203        let shared = dir.join("store.db");
204        let objects = dir.join("objects.db");
205        let shared_store = Store::open_shared(&shared).unwrap();
206        let channel_store = Store::open(&objects).unwrap();
207        for m in REGISTRY.iter() {
208            let store = match m.scope() {
209                MigrationScope::Global => &shared_store,
210                MigrationScope::Channel => &channel_store,
211            };
212            store.migration_mark_applied(m.id(), m.scope().as_str(), 0).unwrap();
213        }
214        (shared, objects)
215    }
216
217    #[test]
218    fn fully_migrated_stores_need_nothing() {
219        let dir = tempfile::tempdir().unwrap();
220        let (shared, objects) = migrated(dir.path());
221        assert_eq!(pending_reason(REGISTRY, &shared, &objects, &no_identity(dir.path())), None);
222    }
223
224    #[test]
225    fn a_pending_migration_needs_preparing() {
226        let dir = tempfile::tempdir().unwrap();
227        let (shared, objects) = migrated(dir.path());
228        let last = REGISTRY.last().unwrap();
229        let path = match last.scope() {
230            MigrationScope::Global => &shared,
231            MigrationScope::Channel => &objects,
232        };
233        rusqlite::Connection::open(path).unwrap().execute("DELETE FROM db_migrations WHERE id = ?1", [last.id()]).unwrap();
234        let reason = pending_reason(REGISTRY, &shared, &objects, &no_identity(dir.path())).expect("one migration is pending");
235        assert!(reason.contains(last.id()), "{reason}");
236    }
237
238    #[test]
239    fn a_fresh_install_needs_preparing_and_the_check_creates_nothing() {
240        let dir = tempfile::tempdir().unwrap();
241        let (shared, objects) = (dir.path().join("store.db"), dir.path().join("objects.db"));
242        assert!(pending_reason(REGISTRY, &shared, &objects, &no_identity(dir.path())).is_some());
243        assert!(!shared.exists() && !objects.exists(), "the gate is read-only");
244    }
245
246    #[test]
247    fn a_store_it_cannot_read_needs_preparing() {
248        let dir = tempfile::tempdir().unwrap();
249        let (shared, objects) = migrated(dir.path());
250        std::fs::write(&objects, b"not a database").unwrap();
251        let _ = std::fs::remove_file(objects.with_extension("db-wal"));
252        assert!(pending_reason(REGISTRY, &shared, &objects, &no_identity(dir.path())).unwrap().contains("can't be read"));
253    }
254
255    /// A build that only raises the schema version (no new migration) still
256    /// goes through preparation, so its schema change gets a backup first.
257    #[test]
258    fn an_older_schema_version_needs_preparing() {
259        let dir = tempfile::tempdir().unwrap();
260        let (shared, objects) = migrated(dir.path());
261        rusqlite::Connection::open(&objects).unwrap().pragma_update(None, "user_version", 3).unwrap();
262        let reason = pending_reason(REGISTRY, &shared, &objects, &no_identity(dir.path())).expect("schema 3 is behind");
263        assert!(reason.contains("schema 3"), "{reason}");
264    }
265
266    /// The identity store has its own schema version; behind, it needs
267    /// preparing like the other two. Unreadable, it doesn't stop srv.
268    #[test]
269    fn an_older_identity_store_needs_preparing_and_an_unreadable_one_does_not() {
270        let dir = tempfile::tempdir().unwrap();
271        let (shared, objects) = migrated(dir.path());
272        let identity = dir.path().join("identity-store.db");
273        drop(Store::open_identity_store(&identity).unwrap());
274        assert_eq!(pending_reason(REGISTRY, &shared, &objects, &identity), None);
275        rusqlite::Connection::open(&identity).unwrap().pragma_update(None, "user_version", 2).unwrap();
276        let reason = pending_reason(REGISTRY, &shared, &objects, &identity).expect("schema 2 is behind");
277        assert!(reason.contains("identity-store.db"), "{reason}");
278        std::fs::write(&identity, b"not a database").unwrap();
279        let _ = std::fs::remove_file(identity.with_extension("db-wal"));
280        assert_eq!(pending_reason(REGISTRY, &shared, &objects, &identity), None);
281    }
282
283    #[test]
284    fn a_previous_version_to_copy_needs_preparing() {
285        let root = tempfile::tempdir().unwrap();
286        let versions = root.path().join("channels").join("stable").join("versions");
287        let old = versions.join("0.1.0").join("data").join("db");
288        std::fs::create_dir_all(&old).unwrap();
289        drop(Store::open(&old.join("objects.db")).unwrap());
290        let reason = data_needs_preparing(&versions.join("0.2.0").join("data"), "0.2.0").unwrap();
291        assert!(reason.contains("copy forward"), "{reason}");
292    }
293
294    // ---- A dev build on the real home must not move the shared stores ahead ----
295
296    use crate::migrations::{Migration, MigrationContext, MigrationError};
297
298    struct Fake {
299        id: &'static str,
300        scope: MigrationScope,
301    }
302    impl Migration for Fake {
303        fn id(&self) -> &'static str { self.id }
304        fn scope(&self) -> MigrationScope { self.scope }
305        fn description(&self) -> &'static str { "fake" }
306        fn up(&self, _ctx: &MigrationContext) -> Result<(), MigrationError> { Ok(()) }
307    }
308
309    /// Acts as a dev build on the real home for the length of the test.
310    struct OnRealHome;
311    impl OnRealHome {
312        fn enter() -> Self {
313            FORCE_REAL_HOME.with(|f| f.set(true));
314            Self
315        }
316    }
317    impl Drop for OnRealHome {
318        fn drop(&mut self) {
319            FORCE_REAL_HOME.with(|f| f.set(false));
320        }
321    }
322
323    /// A real home's shared and identity stores, current and with nothing pending.
324    fn real_home(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
325        let (shared, identity) = (dir.join("store.db"), dir.join("identity-store.db"));
326        drop(Store::open_shared(&shared).unwrap());
327        drop(Store::open_identity_store(&identity).unwrap());
328        (shared, identity)
329    }
330
331    /// The files in `dir` and their sizes, without the `-shm` and `-wal` files a read-only open of a WAL database leaves.
332    fn files(dir: &Path) -> Vec<(std::ffi::OsString, u64)> {
333        let mut v: Vec<_> = std::fs::read_dir(dir)
334            .unwrap()
335            .map(|e| e.unwrap())
336            .filter(|e| !e.file_name().to_string_lossy().ends_with("-shm") && !e.file_name().to_string_lossy().ends_with("-wal"))
337            .map(|e| (e.file_name(), e.metadata().unwrap().len()))
338            .collect();
339        v.sort();
340        v
341    }
342
343    #[test]
344    fn a_dev_build_on_the_real_home_refuses_a_pending_global_migration_and_names_the_ways_out() {
345        let dir = tempfile::tempdir().unwrap();
346        let (shared, identity) = real_home(dir.path());
347        let global = Fake { id: "9001_global_new", scope: MigrationScope::Global };
348        let regs: Vec<&(dyn Migration + Sync)> = vec![&global];
349        let _real = OnRealHome::enter();
350        let why = refuse_on_real_home(&regs, &shared, &identity).unwrap_err();
351        assert!(why.contains("9001_global_new"), "{why}");
352        assert!(why.contains("isolated home") && why.contains("installed AgentMux build"), "{why}");
353    }
354
355    #[test]
356    fn a_pending_channel_migration_is_no_reason_to_refuse() {
357        let dir = tempfile::tempdir().unwrap();
358        let (shared, identity) = real_home(dir.path());
359        let channel = Fake { id: "9002_channel_new", scope: MigrationScope::Channel };
360        let regs: Vec<&(dyn Migration + Sync)> = vec![&channel];
361        let _real = OnRealHome::enter();
362        assert_eq!(refuse_on_real_home(&regs, &shared, &identity), Ok(()));
363    }
364
365    #[test]
366    fn a_shared_or_identity_store_behind_this_builds_schema_is_refused() {
367        let _real = OnRealHome::enter();
368        let dir = tempfile::tempdir().unwrap();
369        let (shared, identity) = real_home(dir.path());
370        assert_eq!(refuse_on_real_home(&[], &shared, &identity), Ok(()));
371        rusqlite::Connection::open(&shared).unwrap().pragma_update(None, "user_version", 1).unwrap();
372        assert!(refuse_on_real_home(&[], &shared, &identity).unwrap_err().contains("store.db is at schema 1"));
373
374        let dir = tempfile::tempdir().unwrap();
375        let (shared, identity) = real_home(dir.path());
376        rusqlite::Connection::open(&identity).unwrap().pragma_update(None, "user_version", 1).unwrap();
377        assert!(refuse_on_real_home(&[], &shared, &identity).unwrap_err().contains("identity-store.db is at schema 1"));
378    }
379
380    #[test]
381    fn any_other_build_is_not_held_back_and_a_home_with_no_stores_yet_has_nobody_to_move_ahead_of() {
382        let dir = tempfile::tempdir().unwrap();
383        let (shared, identity) = real_home(dir.path());
384        let global = Fake { id: "9001_global_new", scope: MigrationScope::Global };
385        let regs: Vec<&(dyn Migration + Sync)> = vec![&global];
386        assert_eq!(refuse_on_real_home(&regs, &shared, &identity), Ok(()), "not a dev build on the real home");
387        let _real = OnRealHome::enter();
388        let none = tempfile::tempdir().unwrap();
389        assert_eq!(refuse_on_real_home(&regs, &none.path().join("store.db"), &none.path().join("identity-store.db")), Ok(()));
390    }
391
392    #[test]
393    fn the_boot_gate_and_the_migration_batch_refuse_before_touching_anything() {
394        let home = tempfile::tempdir().unwrap();
395        let shared_dir = home.path().join("shared");
396        std::fs::create_dir_all(&shared_dir).unwrap();
397        let (shared, _identity) = real_home(&shared_dir);
398        let data_dir = home.path().join("data");
399        let global = Fake { id: "9001_global_new", scope: MigrationScope::Global };
400        let regs: Vec<&(dyn Migration + Sync)> = vec![&global];
401        let before = (files(&shared_dir), data_dir.exists());
402        let _real = OnRealHome::enter();
403        let err = crate::migrations::runner::apply_pending(&regs, home.path(), &shared, &data_dir, None).unwrap_err();
404        assert!(err.contains("9001_global_new"), "{err}");
405        assert_eq!((files(&shared_dir), data_dir.exists()), before, "no lock, no backup, no store opened, nothing migrated");
406        let reason = pending_reason(&regs, &shared, &data_dir.join("db").join("objects.db"), &shared_dir.join("identity-store.db"));
407        assert!(reason.is_some(), "the gate still sends the launcher to prepare, which then refuses");
408    }
409}