Skip to main content

agentmux_srv/bootstrap/
stores.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Split out of the single-file bootstrap module unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.3).
5
6use super::*;
7use super::store_attach::*;
8use super::store_boot::*;
9
10/// Step 2: Parse CLI args and build config. Dispatches the `migrate`
11/// subcommand (and exits) before touching AUTH_KEY-gated config.
12pub fn load_config() -> config::Config {
13    let args = CliArgs::parse();
14
15    // Dispatch migrate subcommand before loading config (no AUTH_KEY needed).
16    if let Some(config::SrvCommand::Migrate { dry_run, list, verify, prepare }) = &args.command {
17        // Same precedence as `Config::from_env_and_args`: the CLI flag, then
18        // the canonical `AGENTMUX_DATA_DIR` the launcher exports. Without
19        // that fallback a launcher-spawned `migrate --verify` opened a
20        // different objects.db than the daemon's and could "verify" the
21        // wrong channel and exit 0 (codex P1 on #3058). The retired
22        // `AGENTMUX_DATA_HOME` and the bare default stay last for the
23        // standalone / pre-unification shapes.
24        let data_dir: std::path::PathBuf = args.wavedata
25            .clone()
26            .or_else(|| std::env::var_os("AGENTMUX_DATA_DIR").filter(|s| !s.is_empty()).map(std::path::PathBuf::from))
27            .or_else(|| std::env::var_os("AGENTMUX_DATA_HOME").map(std::path::PathBuf::from))
28            .unwrap_or_else(|| std::path::PathBuf::from(base::get_mux_data_dir()));
29        let data_dir = migrate_data_dir(data_dir);
30        let code = migrations::run_migrate_command(&data_dir, *dry_run, *list, *verify, *prepare);
31        std::process::exit(code);
32    }
33
34    if let Some(config::SrvCommand::MigrateForkSlugs { plan: _, apply, rollback, restore }) = &args.command {
35        use crate::backend::rpc_types::ForkSlugMigrationMode as Mode;
36        let (mode, journal) = match (apply, rollback, restore) {
37            (true, _, _) => (Mode::Apply, None),
38            (_, Some(j), _) => (Mode::Rollback, Some(j.as_str())),
39            (_, _, Some(j)) => (Mode::Restore, Some(j.as_str())),
40            _ => (Mode::Plan, None),
41        };
42        std::process::exit(crate::backend::slug_migration::run_cli(mode, journal));
43    }
44
45    let config = config::Config::from_env_and_args(&args).unwrap_or_else(|e| {
46        tracing::error!("Failed to load config: {}", e);
47        std::process::exit(1);
48    });
49
50    // Make the per-launch auth_key available to the cross-instance agent
51    // registry writer. Peers performing an HTTP forward of a missed inject
52    // use this to authenticate against the writing instance's sidecar.
53    // Must happen after Config::from_env_and_args (which removes
54    // AGENTMUX_AUTH_KEY from the process env) but before anything calls
55    // `agent_registry::write`.
56    crate::backend::reactive::registry::init_local_auth_key(&config.auth_key);
57
58    config
59}
60
61/// The data folder `migrate` works on: the one the daemon opens given the same
62/// environment. The daemon turns its data folder into `AGENTMUX_DATA_HOME` and
63/// opens `base::get_mux_db_dir()`, which resolves through `agentmux_root()`,
64/// where `AGENTMUX_HOME_OVERRIDE` comes first, except for a data folder inside
65/// it (an isolated instance's version folder, task #3569). Without the same
66/// resolution, the launcher's `migrate --prepare` under a home override
67/// migrated the version's folder while srv's boot check read `<override>/db`,
68/// and srv never started (Korp@narko, after #5252).
69fn migrate_data_dir(requested: std::path::PathBuf) -> std::path::PathBuf {
70    if !requested.as_os_str().is_empty() {
71        std::env::set_var("AGENTMUX_DATA_HOME", &requested);
72    }
73    base::get_mux_data_dir()
74}
75
76/// Output of [`open_stores_and_migrate`] — every store/log handle the rest
77/// of bootstrap and `AppState` need.
78pub struct Stores {
79    pub mstore: Arc<Store>,
80    pub filestore: Arc<FileStore>,
81    pub global_transcript_store: Option<Arc<FileStore>>,
82    pub shared_store: Option<Arc<Store>>,
83    pub id_store: Arc<Store>,
84    /// Permanently-global identity store (agent→account links, memory
85    /// bundles, drone definitions, muxbus/agent M2M credentials, native
86    /// memory, cron jobs) — see
87    /// `docs/specs/SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md`. Distinct from
88    /// `id_store`: never redirected by `isolated_auth_enabled()`. Falls
89    /// back to `mstore` (never `None`) on the same best-effort terms as
90    /// `id_store`'s own fallback, so a resolution/open failure degrades to
91    /// today's per-channel behavior instead of panicking.
92    pub identity_store: Arc<Store>,
93    /// Where the Kanban queue, Presence claims, coordination posts and the
94    /// Jobs run ledger live: `identity_store`, unless this is a `task dev` build
95    /// (or `AGENTMUX_ISOLATED_WORK=1`), which has a `work-store.db` of its own
96    /// (`crate::registry::work_store`).
97    pub work_store: Arc<Store>,
98    /// Where scheduled jobs live: `shared_store` (`None` when it can't be
99    /// resolved), or `work_store` in a build that has its own.
100    pub cron_store: Option<Arc<Store>>,
101    pub saga_log: Arc<crate::sagas::log::SagaLog>,
102    pub saga_id_seed: u64,
103}
104
105/// Step 4: Initialize backend (matching Go cmd/server/main-server.go:374-590).
106/// Sets up the data directory, runs in-process migrations, opens every
107/// SQLite-backed store, attaches the shared/global registries, and performs
108/// the various one-time startup seed/repair passes.
109pub fn open_stores_and_migrate(config: &config::Config, version: &str, build_time: &str) -> Stores {
110    base::set_version(version);
111    base::set_build_time(build_time);
112
113    prepare_data_dir(config, version);
114    let mux_data_dir = base::get_mux_data_dir();
115    let db_dir = base::get_mux_db_dir();
116    gate_or_prepare_data(&mux_data_dir, &db_dir);
117
118    let mstore_raw = open_objects_db(&db_dir);
119    attach_agent_registry(&mstore_raw);
120    let backfill_def_ids = attach_definition_store(&mstore_raw);
121    reconcile_registries(&mstore_raw);
122    attach_token_index_and_wan_identity(&mstore_raw);
123    let mstore = Arc::new(mstore_raw);
124    // Identity M4a: lets spawn sites tell a row-backed block from a row-less
125    // one when the environment carries no UID.
126    backend::identity_spawn::attach_row_store(mstore.clone());
127    let filestore = open_filestore(&db_dir);
128    let global_transcript_store = open_global_transcripts();
129    let shared_store = open_shared_store();
130    let id_store = pick_id_store(&shared_store, &mstore);
131    adopt_earlier_auth(&shared_store, &id_store);
132    let identity_store = open_identity_store(&mstore);
133    // Every key stored for an agent is withheld from transcripts from the start, whether or not its agent launches.
134    let withheld_keys = crate::boot_timing::time("withhold_stored_keys", || mstore.withhold_stored_keys());
135    tracing::info!(withheld_keys, "withhold: the stored agent keys are registered");
136    let (work_store, cron_store) = open_work_store(&identity_store, shared_store.clone(), &db_dir);
137    backend::work_store_handle::attach(work_store.clone());
138    // Which folders a container agent can write is read from the panes here: named before anything asks.
139    backend::fs_ops::container_folders::install(&mstore);
140    // #3603: memory resolution finds the account an agent is linked to (the
141    // directory its spawn runs Claude in) through these, read-only.
142    crate::server::native_memory_handlers::attach_identity_stores(
143        id_store.clone(),
144        identity_store.clone(),
145    );
146    // Which agents get GitHub tokens from AgentMux Cloud's broker is decided by the accounts here.
147    crate::identity::github_tokens::attach_store(id_store.clone());
148    let global_memory_recorder =
149        attach_global_memory(&id_store, &global_transcript_store, &backfill_def_ids);
150    // A fork made before its mark said where the copied history came from gets that fact, signed (idempotent).
151    if let Some(fs) = &global_transcript_store {
152        let sealed = crate::boot_timing::time("fork_marks_seal", || backend::agent_session::fork_history::seal_existing_forks(fs, &mstore));
153        if sealed > 0 {
154            tracing::info!(sealed, "forks: the mark of each now says which runtime its copied history came from");
155        }
156    }
157    let (saga_log, saga_id_seed) = open_saga_log(&db_dir);
158    ensure_initial_data(&mstore);
159    recover_and_seed(&mstore, &id_store, &identity_store, &global_memory_recorder);
160    install_key_resolvers(&mstore);
161
162    Stores {
163        mstore,
164        filestore,
165        global_transcript_store,
166        shared_store,
167        id_store,
168        identity_store,
169        work_store,
170        cron_store,
171        saga_log,
172        saga_id_seed,
173    }
174}
175
176/// After a repair of the shared store (`filestore::repair`): put back, from the per-channel copies of
177/// it, the conversation of each agent whose zone lost rows. Runs inside the repair, before the store
178/// is opened for use.
179pub(super) fn restore_repaired_history(fs: &FileStore, zones: &[String]) {
180    let Some(home) = registry::resolve_global_shared_root().and_then(|shared| shared.parent().map(std::path::Path::to_path_buf)) else { return };
181    let stats = crate::backend::transcript_backfill::restore_damaged(&home, fs, zones);
182    tracing::info!(?stats, "history repair: conversations put back from the per-channel copies");
183}
184
185/// The stores the work queue and scheduled jobs use. Installed and `task
186/// package` builds share the host's (the identity store and the shared store,
187/// as before); a `task dev` build gets a `work-store.db` of its own, so it never
188/// reads or changes the operator's real queue or jobs. If that store can't be
189/// opened srv exits, as it does for `objects.db`: falling back to the host's
190/// files would be the leak this exists to close.
191fn open_work_store(
192    identity_store: &Arc<Store>,
193    shared_store: Option<Arc<Store>>,
194    db_dir: &std::path::Path,
195) -> (Arc<Store>, Option<Arc<Store>>) {
196    let Some(path) = registry::resolve_isolated_work_store_path(db_dir) else {
197        return (identity_store.clone(), shared_store);
198    };
199    let opened = path
200        .parent()
201        .map_or(Ok(()), std::fs::create_dir_all)
202        .map_err(|e| e.to_string())
203        .and_then(|()| Store::open_identity_store(&path).map_err(|e| e.to_string()));
204    let store = Arc::new(opened.unwrap_or_else(|e| {
205        tracing::error!(path = %path.display(), "Failed to open the channel's work store: {}", e);
206        std::process::exit(1);
207    }));
208    let reason = crate::registry::work_store::isolated_work_reason();
209    tracing::info!(path = %path.display(), reason = reason.as_str(), "work store: attached (channel-scoped)");
210    (store.clone(), Some(store))
211}
212
213/// The copy-forward of the previous version's data before this version's first start: `Ok(true)` when it was copied, `Ok(false)`
214/// when there was nothing to copy (a first start, or this version already has data: a fresh start on purpose), and `Err` with the
215/// message to stop with when an older version has data and copying it failed.
216fn carry_forward_or_stop(db_dir: &std::path::Path, code_version: &str) -> Result<bool, String> {
217    match super::carry_forward::try_from_previous_version(db_dir, code_version) {
218        Ok(from) => Ok(from.is_some()),
219        Err(e) => Err(super::carry_forward::stop_message(&e)),
220    }
221}
222
223/// [`carry_forward_or_stop`] for the start path: a copy that failed while an older version has data is NOT a fresh start. With no
224/// launcher to show a dialog (this path is the headless and hosted one), the person would see an empty workspace while the previous
225/// version's folder still holds their data. srv stops, says why, and leaves that folder as it was.
226fn carry_forward_or_exit(db_dir: &std::path::Path, code_version: &str) -> bool {
227    match carry_forward_or_stop(db_dir, code_version) {
228        Ok(carried) => carried,
229        Err(message) => {
230            tracing::error!("startup: refusing to start: {}", message);
231            eprintln!("{}", agentmux_common::srv_stderr::migration_failed_line(&message));
232            std::process::exit(1);
233        }
234    }
235}
236
237/// What an unsupervised srv does before opening its stores: copy a previous
238/// version's data forward, snapshot, and run pending migrations (the same
239/// work `agentmux-srv migrate --prepare` does for the launcher).
240pub(super) fn prepare_in_process(mux_data_dir: &std::path::Path, db_dir: &std::path::Path, code_version: &str) {
241    // Before the pending-migration count below, which opens the shared store and so runs its schema setup.
242    if let Err(e) = migrations::refuse_if_real_home_would_move() {
243        tracing::error!("startup: refusing to start: {}", e);
244        eprintln!("{}", agentmux_common::srv_stderr::migration_failed_line(&e));
245        std::process::exit(1);
246    }
247    // Pre-migration snapshot (Increment B.2 lean cut from
248    // SPEC_DATA_CHANNELS §3.4). Run BEFORE Store::open AND before
249    // count_pending_migrations/run_pending_migrations — both open
250    // objects.db via Store::open which runs DDL/schema setup, mutating
251    // the file. The snapshot must capture the pre-DDL state so it is a
252    // valid rollback aid for a buggy forward migration.
253    //
254    // Failures are logged and ignored — refusing to boot when the
255    // snapshot can't be written would be worse than booting without a
256    // backup (the safety lock still prevents downgrade corruption).
257    let channel = std::env::var("AGENTMUX_CHANNEL").unwrap_or_else(|_| "stable".to_string());
258    // Snapshots live in this version's own data directory, `<data>/snapshots/`:
259    // `get_mux_data_dir()` answers with the data directory once
260    // AGENTMUX_DATA_HOME is set above (#3372). They sit beside the databases
261    // they copy, and pruning keeps 5 there. AGENTMUX_HOME_OVERRIDE wins in
262    // tests. (Before #3372 they went to `~/.agentmux/snapshots/`; older
263    // snapshots stay there.)
264    let snapshots_dir = std::env::var_os("AGENTMUX_HOME_OVERRIDE")
265        .filter(|s| !s.is_empty())
266        .map(std::path::PathBuf::from)
267        .unwrap_or_else(base::get_mux_data_dir)
268        .join("snapshots");
269    // A new version's first start begins from the previous version's data,
270    // then migrates it like any upgrade (carry_forward.rs). No snapshot after
271    // a copy-forward: the previous version's folder is that data, untouched.
272    let carried = carry_forward_or_exit(&db_dir, &code_version);
273    let snapshot = if carried {
274        Ok(None)
275    } else {
276        maybe_snapshot_pre_migration(&db_dir, &snapshots_dir, &channel, &code_version, OBJECT_SCHEMA_VERSION)
277    };
278    match snapshot {
279        Ok(Some(path)) => tracing::info!(snapshot = %path.display(), "pre-migration snapshot written"),
280        Ok(None) => {}
281        Err(e) => tracing::warn!("pre-migration snapshot failed (continuing without backup): {}", e),
282    }
283
284    // Run in-process migrations AFTER snapshot so the rollback aid captures
285    // the pre-DDL state. count_pending_migrations emits AGENTMUXSRV-MIGRATING
286    // first so the launcher/sidecar extend their ESTART deadline before the
287    // (potentially slow) migration work begins.
288    // Strict check, lenient reaction: this runs only when no supervisor
289    // prepares data (headless srv, `task dev:standalone`), where the line
290    // only sizes the ESTART deadline and the migration batch runs right below
291    // anyway, so an unreadable store costs nothing here beyond a less precise
292    // hint — `readable_pending()` reproduces exactly the number this call site
293    // used before. Under the launcher the same question is the fail-closed
294    // boot gate instead (`migrations/gate.rs`, invariant S1b of
295    // `SPEC_FAST_STARTUP_UPGRADE_OWNS_MIGRATIONS_AND_UPDATES_2026_09_15.md`).
296    let pre_migration_count = match migrations::try_count_pending_migrations(&mux_data_dir) {
297        Ok(n) => n,
298        Err(e) => {
299            let fallback = e.readable_pending();
300            // Distinguished because they mean different things to whoever
301            // reads the log: one store was readable and the count is
302            // partial, versus nothing was readable and the count is a
303            // placeholder.
304            match &e {
305                migrations::PendingCountError::ChannelStoreUnreadable { .. } => tracing::warn!(
306                    "startup: channel-scoped migrations could not be counted: {} — sizing the ESTART deadline with {} global",
307                    e,
308                    fallback
309                ),
310                _ => tracing::warn!(
311                    "startup: no pending-migration count available: {} — sizing the ESTART deadline as if none were pending",
312                    e
313                ),
314            }
315            fallback
316        }
317    };
318    if pre_migration_count > 0 {
319        eprintln!("{}", agentmux_common::srv_stderr::migrating_line("migrations", pre_migration_count));
320    }
321    match migrations::run_pending_migrations(&mux_data_dir) {
322        Ok(0) => {}
323        Ok(n) => tracing::info!(applied = n, "startup: applied pending migrations"),
324        Err(e) => {
325            // SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03 Phase 1 (F4): a failed
326            // migration is fatal. This used to be a `warn!` and the server
327            // booted anyway against a store in an unknown state, which turned
328            // any migration bug into a silent one. Note the asymmetry it left:
329            // failing to OPEN the store (just below) always exited 1; failing
330            // to MIGRATE it did not.
331            //
332            // The tagged stderr line lets the launcher / CEF host fail fast
333            // with the real reason instead of timing out on ESTART 30s later
334            // (crates/common/src/srv_stderr.rs). Exit code 1 is what
335            // docs/exe-return-codes.md already documented for this case.
336            tracing::error!("startup: migration failed — refusing to start: {}", e);
337            eprintln!("{}", agentmux_common::srv_stderr::migration_failed_line(&e));
338            std::process::exit(1);
339        }
340    }
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    /// Sets env vars for one test and puts them back after.
348    struct EnvRestore(Vec<(&'static str, Option<std::ffi::OsString>)>);
349    impl EnvRestore {
350        fn set(vars: &[(&'static str, Option<&std::path::Path>)]) -> Self {
351            let saved = vars.iter().map(|(k, _)| (*k, std::env::var_os(k))).collect();
352            for (k, v) in vars {
353                match v {
354                    Some(v) => std::env::set_var(k, v),
355                    None => std::env::remove_var(k),
356                }
357            }
358            EnvRestore(saved)
359        }
360    }
361    impl Drop for EnvRestore {
362        fn drop(&mut self) {
363            for (k, v) in &self.0 {
364                match v {
365                    Some(v) => std::env::set_var(k, v),
366                    None => std::env::remove_var(k),
367                }
368            }
369        }
370    }
371
372    /// `migrate` works on the folder whose `db/` the daemon opens, so the
373    /// launcher's `migrate --prepare` prepares what srv's boot check reads.
374    #[test]
375    fn migrate_works_on_the_daemons_data_folder_with_and_without_a_home_override() {
376        let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
377        let root = tempfile::tempdir().unwrap();
378        let version_dir = root.path().join("channels").join("x").join("versions").join("1.0.0").join("data");
379
380        // No override: the folder asked for, as before.
381        let _env = EnvRestore::set(&[("AGENTMUX_HOME_OVERRIDE", None), ("AGENTMUX_DATA_HOME", None)]);
382        assert_eq!(migrate_data_dir(version_dir.clone()), version_dir);
383        assert_eq!(base::get_mux_db_dir(), version_dir.join("db"), "the daemon's db folder");
384
385        // A home override and a version folder inside it (an isolated
386        // instance): the versioned layout, as without an override.
387        let _env = EnvRestore::set(&[("AGENTMUX_HOME_OVERRIDE", Some(root.path())), ("AGENTMUX_DATA_HOME", None)]);
388        assert_eq!(migrate_data_dir(version_dir.clone()), version_dir);
389        assert_eq!(base::get_mux_db_dir(), version_dir.join("db"));
390
391        // A folder outside the override isn't the instance's: the override's own, as before.
392        let elsewhere = tempfile::tempdir().unwrap();
393        let _env = EnvRestore::set(&[("AGENTMUX_HOME_OVERRIDE", Some(root.path())), ("AGENTMUX_DATA_HOME", None)]);
394        assert_eq!(migrate_data_dir(elsewhere.path().to_path_buf()), root.path());
395        assert_eq!(migrate_data_dir(elsewhere.path().to_path_buf()).join("db"), base::get_mux_db_dir());
396    }
397
398    /// Task #3569: under a root override each version gets its own folder and
399    /// the next one starts from the previous one's data, so an upgrade's data
400    /// can be tested in isolation.
401    #[test]
402    fn an_isolated_instance_carries_its_data_forward_between_versions() {
403        let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
404        let root = tempfile::tempdir().unwrap();
405        let versions = root.path().join("channels").join("x").join("versions");
406        let (old, new) = (versions.join("1.0.0").join("data"), versions.join("1.1.0").join("data"));
407        std::fs::create_dir_all(old.join("db")).unwrap();
408        let conn = rusqlite::Connection::open(old.join("db").join("objects.db")).unwrap();
409        conn.execute_batch("CREATE TABLE t(v TEXT); INSERT INTO t VALUES ('from 1.0.0');").unwrap();
410        drop(conn);
411
412        let _env = EnvRestore::set(&[("AGENTMUX_HOME_OVERRIDE", Some(root.path())), ("AGENTMUX_DATA_HOME", None)]);
413        std::env::set_var("AGENTMUX_DATA_HOME", &new); // what open_stores_and_migrate does with the launcher's folder
414        let db_dir = base::get_mux_db_dir();
415        assert_eq!(db_dir, new.join("db"), "not <override>/db, which every version would share");
416        std::fs::create_dir_all(&db_dir).unwrap();
417        let from = super::carry_forward::from_previous_version(&db_dir, "1.1.0").expect("carried from 1.0.0");
418        assert!(from.starts_with(&versions.join("1.0.0")), "carried from {from:?}");
419        let conn = rusqlite::Connection::open(db_dir.join("objects.db")).unwrap();
420        let v: String = conn.query_row("SELECT v FROM t", [], |r| r.get(0)).unwrap();
421        assert_eq!(v, "from 1.0.0");
422    }
423
424    /// A start whose carry-forward fails while an older version has data stops with a message; a first start does not.
425    #[test]
426    fn a_failed_carry_forward_stops_instead_of_starting_empty() {
427        let root = tempfile::tempdir().unwrap();
428        let versions = root.path().join("channels").join("x").join("versions");
429        let old = versions.join("1.0.0").join("data").join("db");
430        std::fs::create_dir_all(&old).unwrap();
431        std::fs::write(old.join("objects.db"), b"not a database").unwrap();
432        let new = versions.join("1.1.0").join("data").join("db");
433        let message = super::carry_forward_or_stop(&new, "1.1.0").expect_err("an older version has data that could not be copied");
434        assert!(message.contains("could not be read") && message.contains("untouched"), "{message}");
435        assert_eq!(std::fs::read(old.join("objects.db")).unwrap(), b"not a database");
436        assert!(!new.join("objects.db").exists(), "no empty database was started in its place");
437
438        let first = root.path().join("channels").join("y").join("versions").join("1.0.0").join("data").join("db");
439        assert_eq!(super::carry_forward_or_stop(&first, "1.0.0"), Ok(false), "a first start with no older version starts fresh");
440    }
441}