Skip to main content

agentmux_srv_core/migrations/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Data migration framework.
5//!
6//! Migrations are versioned steps that run once, either via `agentmux-srv migrate`
7//! or in-process at startup via `run_pending_migrations` (called unconditionally;
8//! fast-paths to `Ok(0)` when already current). The in-process path runs before
9//! any store is opened for normal operation so that `id_store` always binds to a
10//! fully-backfilled shared store.
11//!
12//! Adding a migration: implement [`Migration`], add it to [`REGISTRY`], add a
13//! file under this module. The ID must be unique and lexicographically ordered
14//! (use the `NNNN_slug` convention). Retiring old migrations: remove from
15//! [`REGISTRY`] once the minimum supported upgrade path passes the migration's
16//! origin version — the `db_migrations` row stays as a permanent record. That
17//! path is the repo's `UPGRADE_FLOOR`: raise it past the migration's origin
18//! version first, so an install older than that is told to install the floor
19//! version before upgrading (`backend::update::check::upgrade_floor`).
20//!
21//! # A Global migration is additive
22//!
23//! Every AgentMux on the computer opens the shared stores at once, whatever its
24//! version or channel, so a `MigrationScope::Global` migration may only add:
25//! new tables, columns and rows. No drop, rename or delete until an
26//! `UPGRADE_FLOOR` raise has retired the old shape (expand now, remove later;
27//! decision D1 of `REPORT_STARTUP_ARCHITECTURE_AND_MIGRATIONS_AUDIT_2026_10_20`).
28//! Start its doc comment with a `//! Shared store: additive, ...` line saying
29//! what it adds. `additive_guard_tests` fails a Global migration with no such
30//! line, or one that declares itself additive and writes destructive SQL. A
31//! reviewer still has to read what a store helper does: the test cannot.
32//!
33//! # No private marker files
34//!
35//! `db_migrations` (plus a [`Migration::verify`] post-condition) is the sole
36//! source of truth for "has this run" — SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03
37//! Phase 2. A new migration must not introduce its own flag file, and no
38//! migration may treat the mere *existence* of a marker as proof of
39//! completion: that is the shape that left `0007`'s target table empty
40//! while its flag said "done" (§1.2, F1). The three legacy markers that
41//! remain are evidence only — `0007`'s and `0002`'s helpers decide from the
42//! data (`consolidate_looks_incomplete`, `block_zones_look_incomplete`) and
43//! are content-idempotent, `0003`'s helper ignores its marker and re-asserts
44//! its invariant every run. The bootstrap that stamped a pre-framework
45//! install from them, and the migrations older than the upgrade floor (0.55.0),
46//! are retired: an install that old is told to install the floor first.
47//!
48//! # Migrations freeze copies of live logic on purpose
49//!
50//! Some migrations carry verbatim copies of helpers that also exist in live
51//! code: `m0020_agent_color_backfill` and
52//! `m0021_backfill_agent_bundles` mirror 25–30 lines each of
53//! `backend/storage/mcp_servers.rs` and `def_registry_mirror.rs`. That is
54//! deliberate, not accidental duplication. A migration must produce the same
55//! rows on every machine it ever runs on, so it cannot call a live helper
56//! whose behaviour a later release may change; the copy pins the logic as it
57//! was at the migration's origin version. Do not "deduplicate" a migration
58//! against live code. When you copy logic into a new migration, say so next
59//! to the copy — `// frozen copy of <path>::<fn> as of <version>` — so the
60//! next reader can tell a freeze from a drift.
61
62pub mod carry_forward;
63pub mod m0002_block_zones_v1;
64pub mod m0003_template_sessions_v1;
65pub mod m0007_agents_consolidate;
66pub mod m0011_shared_store_backfill;
67pub mod m0016_seed_starter_mcp_servers;
68pub mod m0020_agent_color_backfill;
69pub mod m0021_backfill_agent_bundles;
70pub mod m0022_identity_store_links_backfill;
71pub mod m0023_native_memory_versions_backfill;
72pub mod m0024_native_memory_backfill_from_fs;
73pub mod m0025_agents_launch_state_backfill;
74pub mod m0026_registry_agent_id_rekey;
75pub mod m0027_agents_workspace_backfill;
76pub mod m0028_agent_child_tables_repoint_fk;
77pub mod m0029_drop_legacy_agent_tables;
78pub mod m0030_backfill_bundle_component_refs;
79pub mod m0031_carry_skills_and_mcp_servers_to_identity_store;
80pub mod m0032_drop_catalog_fk_from_ref_tables;
81pub mod m0033_narrow_skill_global_uniqueness_index;
82pub mod m0034_identity_history_backfill;
83pub mod m0035_agent_owns_its_provider;
84pub mod m0036_drop_bundle_mcp;
85pub mod m0037_retire_old_pane_names;
86pub mod m0038_drop_drone_runs_definition_fk;
87pub mod m0039_vault_into_warden;
88pub mod m0040_cron_jobs_to_db_jobs;
89pub mod m0041_retire_untouched_starter_skills;
90pub mod m0042_supervisor_modes_reset;
91pub mod m0043_rotate_container_agent_keys;
92pub mod m0044_warden_split;
93pub mod m0045_palette_snap;
94pub mod m0046_remove_empty_agent_bundles;
95pub mod m0047_agents_drop_own_bundle;
96pub mod m0048_seed_grok_muse_accounts;
97pub mod m0049_drone_versions;
98pub mod m0050_drone_checkpoints;
99pub mod m0051_palette_12_snap;
100pub mod m0052_drone_access;
101pub mod m0053_history_into_audit;
102pub mod m0054_rotate_host_agent_keys;
103pub mod backup;
104pub mod gate;
105pub mod prepare;
106pub mod runner;
107pub mod schema_probe;
108#[cfg(test)]
109mod additive_guard_tests;
110#[cfg(test)]
111mod phase5_tests;
112
113pub(crate) use schema_probe::table_exists;
114
115pub use gate::data_needs_preparing;
116pub use gate::refuse_if_real_home_would_move;
117pub use runner::count_pending_migrations;
118pub use runner::doctor_report_for_instance;
119pub use runner::run_migrate_command;
120pub use runner::run_pending_migrations;
121pub use runner::try_count_pending_migrations;
122pub use runner::PendingCountError;
123
124use std::path::PathBuf;
125
126// ── Public types ─────────────────────────────────────────────────────────────
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum MigrationScope {
130    /// Touches `~/.agentmux/shared/` — runs once regardless of channel.
131    Global,
132    /// Touches the current channel's data dir.
133    Channel,
134}
135
136impl MigrationScope {
137    pub fn as_str(self) -> &'static str {
138        match self {
139            Self::Global => "global",
140            Self::Channel => "channel",
141        }
142    }
143}
144
145/// Context passed to every migration's `up()` call.
146pub struct MigrationContext {
147    /// `~/.agentmux` (or wherever AGENTMUX_SHARED_DIR's parent lives).
148    pub home: PathBuf,
149    /// Current channel's data directory (passed via `--wavedata`).
150    pub data_dir: PathBuf,
151    /// Path to the shared store (`~/.agentmux/shared/store.db`).
152    pub shared_store_path: PathBuf,
153    /// Path to the channel store (`<data_dir>/db/objects.db`).
154    pub channel_store_path: PathBuf,
155}
156
157#[derive(Debug)]
158pub struct MigrationError(pub String);
159
160impl std::fmt::Display for MigrationError {
161    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162        write!(f, "{}", self.0)
163    }
164}
165
166impl From<String> for MigrationError {
167    fn from(s: String) -> Self {
168        Self(s)
169    }
170}
171
172impl From<&str> for MigrationError {
173    fn from(s: &str) -> Self {
174        Self(s.to_owned())
175    }
176}
177
178/// Result of an applied migration's post-condition check
179/// (`agentmux-srv migrate --verify`, SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03
180/// Phase 1). `db_migrations` records only that `up()` returned `Ok` — never
181/// that it wrote what it was meant to. A migration that can state its own
182/// effect as a cheap query implements [`Migration::verify`]; the rest report
183/// `NotVerifiable` and the doctor pass says so rather than guessing.
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum VerifyOutcome {
186    /// The migration declares no checkable post-condition (the default).
187    NotVerifiable,
188    /// The post-condition holds. The string is the evidence (counts, paths).
189    Ok(String),
190    /// Recorded applied, but the effect is not there — the F1/F2 "marker
191    /// present, wrote nothing" shape the spec was written about.
192    Mismatch(String),
193    /// The check itself could not run (store unreadable, etc.). Treated
194    /// like a mismatch for exit-code purposes: an unverifiable applied
195    /// migration is not a passing one.
196    Error(String),
197}
198
199impl VerifyOutcome {
200    /// `true` for `Mismatch` and `Error` — the two outcomes that fail the pass.
201    pub fn is_failure(&self) -> bool {
202        matches!(self, Self::Mismatch(_) | Self::Error(_))
203    }
204
205    /// Short status word for CLI / NDJSON output.
206    pub fn label(&self) -> &'static str {
207        match self {
208            Self::NotVerifiable => "n/a",
209            Self::Ok(_) => "ok",
210            Self::Mismatch(_) => "MISMATCH",
211            Self::Error(_) => "error",
212        }
213    }
214
215    /// The detail string, if any.
216    pub fn detail(&self) -> &str {
217        match self {
218            Self::NotVerifiable => "",
219            Self::Ok(s) | Self::Mismatch(s) | Self::Error(s) => s,
220        }
221    }
222}
223
224pub trait Migration: Send + Sync {
225    fn id(&self) -> &'static str;
226    fn scope(&self) -> MigrationScope;
227    fn description(&self) -> &'static str;
228    fn up(&self, ctx: &MigrationContext) -> Result<(), MigrationError>;
229
230    /// Post-condition check for an APPLIED migration. Must be read-only and
231    /// cheap (a handful of queries / `exists()` calls) — it runs from a CLI
232    /// doctor pass, never from startup. Default: nothing checkable. Override
233    /// where the effect can be stated as a query; see `m0007` for the
234    /// row-count shape and `m0002` for the marker-file shape.
235    fn verify(&self, _ctx: &MigrationContext) -> VerifyOutcome {
236        VerifyOutcome::NotVerifiable
237    }
238}
239
240// ── Registry ─────────────────────────────────────────────────────────────────
241//
242// Ordered list of all migrations. Applied in order; each runs at most once
243// (guarded by `db_migrations` in the shared store). Add new migrations at the
244// end. Do NOT reorder or remove applied migrations — removals belong in a
245// separate "retire" pass once the minimum supported upgrade path clears them.
246
247static REGISTRY: &[&(dyn Migration + Sync)] = &[
248    &m0002_block_zones_v1::M0002BlockZonesV1,
249    &m0003_template_sessions_v1::M0003TemplateSessionsV1,
250    &m0007_agents_consolidate::M0007AgentsConsolidate,
251    &m0011_shared_store_backfill::M0011SharedStoreBackfill,
252    &m0016_seed_starter_mcp_servers::M0016SeedStarterMcpServers,
253    &m0020_agent_color_backfill::M0020AgentColorBackfill,
254    &m0021_backfill_agent_bundles::M0021BackfillAgentBundles,
255    &m0022_identity_store_links_backfill::M0022IdentityStoreLinksBackfill,
256    &m0023_native_memory_versions_backfill::M0023NativeMemoryVersionsBackfill,
257    &m0024_native_memory_backfill_from_fs::M0024NativeMemoryBackfillFromFs,
258    &m0025_agents_launch_state_backfill::M0025AgentsLaunchStateBackfill,
259    &m0026_registry_agent_id_rekey::M0026RegistryAgentIdRekey,
260    &m0027_agents_workspace_backfill::M0027AgentsWorkspaceBackfill,
261    &m0028_agent_child_tables_repoint_fk::M0028AgentChildTablesRepointFk,
262    &m0029_drop_legacy_agent_tables::M0029DropLegacyAgentTables,
263    &m0030_backfill_bundle_component_refs::M0030BackfillBundleComponentRefs,
264    &m0031_carry_skills_and_mcp_servers_to_identity_store::M0031CarrySkillsAndMcpServersToIdentityStore,
265    &m0032_drop_catalog_fk_from_ref_tables::M0032DropCatalogFkFromRefTables,
266    &m0033_narrow_skill_global_uniqueness_index::M0033NarrowSkillGlobalUniquenessIndex,
267    &m0034_identity_history_backfill::M0034IdentityHistoryBackfill,
268    &m0035_agent_owns_its_provider::M0035AgentOwnsItsProvider,
269    &m0036_drop_bundle_mcp::M0036DropBundleMcp,
270    &m0037_retire_old_pane_names::M0037RetireOldPaneNames,
271    &m0038_drop_drone_runs_definition_fk::M0038DropDroneRunsDefinitionFk,
272    &m0039_vault_into_warden::M0039VaultIntoWarden,
273    &m0040_cron_jobs_to_db_jobs::M0040CronJobsToDbJobs,
274    &m0041_retire_untouched_starter_skills::M0041RetireUntouchedStarterSkills,
275    &m0042_supervisor_modes_reset::M0042SupervisorModesReset,
276    &m0043_rotate_container_agent_keys::M0043RotateContainerAgentKeys,
277    &m0044_warden_split::M0044WardenSplit,
278    &m0045_palette_snap::M0045PaletteSnap,
279    &m0046_remove_empty_agent_bundles::M0046RemoveEmptyAgentBundles,
280    &m0047_agents_drop_own_bundle::M0047AgentsDropOwnBundle,
281    &m0048_seed_grok_muse_accounts::M0048SeedGrokMuseAccounts,
282    &m0049_drone_versions::M0049DroneVersions,
283    &m0050_drone_checkpoints::M0050DroneCheckpoints,
284    &m0051_palette_12_snap::M0051Palette12Snap,
285    &m0052_drone_access::M0052DroneAccess,
286    &m0053_history_into_audit::M0053HistoryIntoAudit,
287    &m0054_rotate_host_agent_keys::M0054RotateHostAgentKeys,
288];