Skip to main content

agentmux_srv_core/migrations/
prepare.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `agentmux-srv migrate --prepare`: everything a version's data needs
5//! before srv opens it, as one step a supervisor runs while srv is stopped.
6//!
7//! In order: copy the newest older version's databases forward when this
8//! version has none yet (`migrations/carry_forward.rs`), then the same locked
9//! batch the daemon runs (`runner::apply_pending`), whose backup leaves out
10//! `objects.db` after a copy-forward. Each part is reported on stderr in the
11//! `agentmux_common::srv_stderr` protocol (STEP and MIGRATION lines), so the
12//! launcher's native splash can show it; the NDJSON summary on stdout is the
13//! one plain `migrate` prints.
14//!
15//! The upgrade step of `docs/specs/SPEC_FAST_STARTUP_UPGRADE_OWNS_MIGRATIONS_AND_UPDATES_2026_09_15.md`
16//! ยง10. The launcher runs it (`srv_spawner::spawn_srv`) after srv exits with
17//! `AGENTMUXSRV-NEEDS-PREPARE`, its boot gate having found data that needs
18//! preparing (`migrations/gate.rs`).
19
20use std::path::Path;
21
22use super::runner::{apply_pending, emit_summary, write_error_log, STDERR_PROGRESS};
23use super::REGISTRY;
24
25pub(super) fn run(data_dir: &Path, home: &Path, shared_store_path: &Path) -> i32 {
26    let version = std::env::var("AGENTMUX_VERSION").unwrap_or_else(|_| env!("CARGO_PKG_VERSION").to_string());
27    run_for_version(data_dir, home, shared_store_path, &version)
28}
29
30/// [`run`] for an explicit version, so a test needn't set the environment.
31pub(super) fn run_for_version(data_dir: &Path, home: &Path, shared_store_path: &Path, version: &str) -> i32 {
32    // A copy that failed must not turn into a fresh start: that would start
33    // the new version without the user's data. Failing leaves this version
34    // without an objects.db, so the next start asks for preparation again.
35    if let Err(e) = crate::migrations::carry_forward::try_from_previous_version(&data_dir.join("db"), version) {
36        let msg = crate::migrations::carry_forward::stop_message(&e);
37        write_error_log(home, &msg);
38        eprintln!("{}", agentmux_common::srv_stderr::migration_failed_line(&msg));
39        return 1;
40    }
41    match apply_pending(REGISTRY, home, shared_store_path, data_dir, Some(&STDERR_PROGRESS)) {
42        Ok(outcome) => {
43            emit_summary(outcome.applied, outcome.skipped);
44            0
45        }
46        Err(msg) => {
47            write_error_log(home, &msg);
48            eprintln!("{}", agentmux_common::srv_stderr::migration_failed_line(&msg));
49            1
50        }
51    }
52}