agentmux_srv_core/backend/storage/migrations.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! SQL schema setup for Store, FileStore, and the saga log.
5//!
6//! `objects.db` uses a **flat schema**: `run_object_schema` defines the
7//! final table set directly in one idempotent `CREATE TABLE IF NOT EXISTS`
8//! batch. It replaced an 11-step incremental migration chain
9//! (`run_forge_v1` … `run_forge_v11`) — see
10//! `docs/specs/SPEC_SCHEMA_FLATTENING_2026_05_19.md`. The chain was pure
11//! historical accretion: per-version data dirs mean every new version is
12//! born with a fresh `objects.db` and ran the whole chain top-to-bottom
13//! anyway, so the intermediate states were never reachable in production.
14//!
15//! `filestore.db` and `sagas.db` were already single-DDL stores; they keep
16//! their existing schema functions and gain only the `user_version`
17//! tripwire (`check_schema_compat` + `stamp_version`).
18
19use rusqlite::Connection;
20use tracing::warn;
21
22use super::error::StoreError;
23
24pub mod object_schema;
25pub mod store_schema;
26
27pub(in crate::backend::storage) use object_schema::apply_additive_columns;
28
29/// `user_version` stamped into `~/.agentmux/shared/store.db` after `run_shared_store_schema`.
30/// Versioned independently from `objects.db`. What each version (v1 to v12) added:
31/// docs/architecture/STORAGE_SCHEMA_VERSION_HISTORY.md, "Shared store".
32pub const SHARED_STORE_SCHEMA_VERSION: i64 = 12;
33
34/// `user_version` stamped into `objects.db` after `run_object_schema`. The flat schema reset the
35/// counter to 1 (the pre-flatten chain never set `user_version`, so legacy files read 0). Bumped
36/// per additive migration; `check_schema_compat` makes an older binary refuse a file stamped
37/// newer than it. What each version (v1 to v45) added:
38/// docs/architecture/STORAGE_SCHEMA_VERSION_HISTORY.md, "Objects store".
39pub const OBJECT_SCHEMA_VERSION: i64 = 45;
40/// `user_version` value stamped into `filestore.db`.
41pub const FILESTORE_SCHEMA_VERSION: i64 = 1;
42/// `user_version` value stamped into `sagas.db`.
43pub const SAGA_LOG_SCHEMA_VERSION: i64 = 1;
44
45/// Object type table names matching the `db_<otype>` convention.
46const WSTORE_OTYPES: &[&str] = &[
47 "client",
48 "window",
49 "workspace",
50 "tab",
51 "layout",
52 "block",
53 "temp",
54];
55
56/// Legacy `objects.db` table names retired by the de-forge rename, paired
57/// with their replacement. `adopt_legacy_table_names` renames any of these
58/// it finds — the single surviving piece of the old migration chain (it
59/// also subsumes the v11 `db_memories` rename).
60const LEGACY_TABLE_RENAMES: &[(&str, &str)] = &[
61 ("db_forge_agents", "db_agent_definitions"),
62 ("db_forge_content", "db_agent_content"),
63 ("db_forge_skills", "db_agent_skills"),
64 ("db_forge_history", "db_agent_history"),
65 ("db_forge_agent_identities", "db_agent_identity_links"),
66 ("db_memories", "db_memory_bundles"),
67 // Phase 4 of SPEC_PRESET_TO_BUNDLE_REFACTOR_2026_07_02.md — the
68 // "bundle" naming collision fix (SPEC_ARMORY_PHASE4_STORAGE_RENAME_COMPLETION_2026_07_12.md).
69 // Order matters: this entry runs AFTER the `db_memories` rename above
70 // in the same pass, so a database old enough to still have `db_memories`
71 // chains straight through to `db_bundles` in one migration run instead
72 // of stopping at the intermediate name.
73 ("db_identity_accounts", "db_accounts"),
74 ("db_memory_bundles", "db_bundles"),
75];
76
77/// Legacy index names that must be dropped after their table is renamed —
78/// `ALTER TABLE … RENAME` keeps indexes attached but under their old names,
79/// which would collide with the flat DDL's `CREATE INDEX`. The flat DDL
80/// recreates each under the new name.
81const LEGACY_INDEX_DROPS: &[&str] = &[
82 "idx_forge_agents_slug",
83 "idx_forge_history_agent_date",
84 "idx_forge_agent_identities_account",
85 "idx_memories_is_blank",
86 // Phase 4 rename (see LEGACY_TABLE_RENAMES above) — objects.db names,
87 // then the shared store.db names (`idx_ss_*` prefix, see
88 // run_shared_store_schema).
89 "idx_identity_accounts_provider",
90 "idx_memory_bundles_is_blank",
91 "idx_ss_identity_accounts_provider",
92 "idx_ss_memory_bundles_is_blank",
93];
94
95/// Tables retained by the old chain only for a downgrade path the flatten
96/// abandons. Dropped from any legacy DB by the adopt step; never created
97/// by the flat schema. `db_workflow_*` data was already copied into
98/// `db_drone_*` by the old v10 migration, so dropping loses nothing.
99///
100/// `db_identities` (the pre-v11 name), `db_identity_bundles`, and
101/// `db_identity_bindings` were dropped outright rather than renamed
102/// forward in Phase 4c of SPEC_PRESET_TO_BUNDLE_REFACTOR_2026_07_02.md —
103/// `db_agent_identity_links`/`db_accounts` is the sole credential-
104/// resolution path (`identity/resolver/inject.rs::resolve_bindings_for_instance`),
105/// confirmed by the direct-link backfill migrations, since retired
106/// (see SPEC_ARMORY_PHASE4_STORAGE_RENAME_COMPLETION_2026_07_12.md §6/§8a).
107const DEAD_TABLE_DROPS: &[&str] = &[
108 "db_workflow_definitions",
109 "db_workflow_runs",
110 "db_v10_migrated_legacy_defs",
111 "db_v10_migrated_legacy_runs",
112 "db_identities",
113 "db_identity_bundles",
114 "db_identity_bindings",
115];
116
117/// Initialize (or re-validate) the full `objects.db` schema.
118///
119/// Idempotent — safe on every srv startup. Steps:
120///
121/// 1. `adopt_legacy_table_names` — renames any pre-flatten forge/bundle
122/// tables found (protects dev databases created before the flatten;
123/// see the spec §3/§7) and drops the dead workflow/sentinel tables.
124/// 2. The flat `CREATE TABLE IF NOT EXISTS` batch — the canonical schema.
125/// 3. Seeds the blank Bundle singleton row.
126///
127/// A database stuck at a pre-v11 intermediate schema cannot be fully
128/// adopted (its tables predate later columns). The adopt step still
129/// renames what it finds; the first query referencing a missing column
130/// then fails loudly with `no such column` — a hard error, not silent
131/// empty state, with the data preserved on disk. Per-version data dirs
132/// make that case unreachable for released builds.
133pub fn run_object_schema(conn: &Connection) -> Result<(), StoreError> {
134 adopt_legacy_table_names(conn)?;
135
136 object_schema::create_generic_tables(conn)?;
137 object_schema::create_input_history_tables(conn)?;
138 conn.execute_batch(object_schema::OBJECT_TABLES_SQL)?;
139 object_schema::add_object_columns(conn)?;
140 object_schema::add_legacy_definition_columns(conn)?;
141 object_schema::add_agent_columns(conn)?;
142 object_schema::seed_blank_bundle(conn)?;
143 object_schema::create_channel_migrations(conn)?;
144
145 Ok(())
146}
147
148/// Rename any pre-flatten `objects.db` tables to their de-forged names and
149/// drop the dead workflow/sentinel tables. Idempotent — on a fresh or
150/// already-flat database every check is a no-op.
151///
152/// This is the single surviving fragment of the old v1–v11 chain: it
153/// exists only to carry a developer's pre-flatten `objects.db` (always at
154/// the post-v11 schema, since v11 is merged) forward without data loss.
155/// SQLite ≥ 3.25 auto-updates foreign-key references in child tables when
156/// a parent table is renamed, so the agent/identity cascades survive.
157fn adopt_legacy_table_names(conn: &Connection) -> Result<(), StoreError> {
158 for (legacy, current) in LEGACY_TABLE_RENAMES {
159 if !crate::migrations::table_exists(conn, legacy)? {
160 continue;
161 }
162 if crate::migrations::table_exists(conn, current)? {
163 // Both present — only reachable on a deliberate
164 // downgrade-roundtrip dev DB (flat build → pre-flatten build,
165 // which re-creates the legacy name → flat build again). The
166 // flatten abandons the downgrade path, but the legacy table
167 // may hold rows the downgraded build wrote. Do NOT drop it —
168 // that would be silent data loss (the bug class behind PR
169 // #933's Codex P1). Leave it on disk and warn loudly so the
170 // developer can recover or delete it manually.
171 warn!(
172 legacy_table = *legacy,
173 current_table = *current,
174 "objects.db has both a legacy table and its de-forged \
175 replacement — this only happens after a downgrade to a \
176 pre-flatten build; the legacy table is left untouched \
177 for manual recovery and is otherwise unused",
178 );
179 } else {
180 conn.execute_batch(&format!("ALTER TABLE {legacy} RENAME TO {current};"))?;
181 }
182 }
183
184 // Drop indexes orphaned by the renames — the flat DDL recreates them
185 // under the new names.
186 for idx in LEGACY_INDEX_DROPS {
187 conn.execute_batch(&format!("DROP INDEX IF EXISTS {idx};"))?;
188 }
189
190 // Drop tables retained only for the abandoned downgrade path.
191 for table in DEAD_TABLE_DROPS {
192 conn.execute_batch(&format!("DROP TABLE IF EXISTS {table};"))?;
193 }
194
195 Ok(())
196}
197
198/// Initialize (or re-validate) the `~/.agentmux/shared/store.db` schema.
199///
200/// Contains only the durable user content that must survive across
201/// channels/versions: identity accounts, agent→account links, memory
202/// bundles, drone definitions, and muxbus credentials. Session state
203/// (`db_block`, `db_tab`, etc.) and drone run history stay in the
204/// per-channel `objects.db`.
205///
206/// `db_agent_identity_links` drops the FK to `db_agent_definitions` here
207/// (cross-DB FK enforcement is impossible in SQLite); application code
208/// enforces referential integrity instead.
209///
210/// Idempotent — safe to call on every startup.
211pub fn run_shared_store_schema(conn: &Connection) -> Result<(), StoreError> {
212 // Rename any legacy table names (including the Phase 4 accounts/bundles
213 // rename — LEGACY_TABLE_RENAMES entries that don't apply to this
214 // connection's tables are safely skipped) before the idempotent
215 // CREATE TABLE IF NOT EXISTS batch below, same as run_object_schema.
216 adopt_legacy_table_names(conn)?;
217
218 conn.execute_batch(store_schema::SHARED_STORE_TABLES_SQL)?;
219 store_schema::seed_shared_blank_bundle(conn)?;
220 store_schema::add_shared_store_columns(conn)?;
221
222 Ok(())
223}
224
225/// `user_version` stamped into the permanently-global `~/.agentmux/shared/identity-store.db` (a
226/// different file from `store.db`; see [`run_identity_store_schema`]). Independent counter from
227/// `SHARED_STORE_SCHEMA_VERSION`. What each version (v1 to v11) added:
228/// docs/architecture/STORAGE_SCHEMA_VERSION_HISTORY.md, "Identity store".
229///
230/// Added WITHOUT a bump: `db_mcp_server_reach` (OBJECT_SCHEMA_VERSION v44
231/// has the same table). The catalog's reach switches live with the catalog,
232/// here, so they survive an upgrade where an agent bind
233/// (`db_agent_mcp_ref`, in `objects.db`) does not. This store is one file
234/// shared by every AgentMux on the computer, installed and dev builds alike,
235/// and `check_schema_compat` makes any build that speaks an older version
236/// refuse it. So a bump here locks every older AgentMux on the computer out
237/// as soon as one newer build starts: a dev build of a branch with a bump
238/// did exactly that on 2026-10-11. A table an older build never reads needs
239/// no lock: an older build ignores it, a newer one creates it if missing.
240/// Bump only for a change an older build would misread or corrupt.
241/// `SPEC_CONNECTORS_MCP_WHAT_AGENTS_RUN_2026_10_10.md` §2.1.
242pub const IDENTITY_STORE_SCHEMA_VERSION: i64 = 11;
243
244/// Initialize (or re-validate) the `~/.agentmux/shared/identity-store.db` schema: the
245/// permanently-global store from docs/specs/SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md, which
246/// fixes conversation continuity across a version switch
247/// (docs/specs/REPORT_HISTORY_CONTINUITY_ACROSS_VERSION_UPGRADE_2026_08_17.md).
248///
249/// A **near-superset** of [`run_shared_store_schema`]'s tables (v2), including `db_accounts`,
250/// but there it is a read-through FALLBACK MIRROR, not the authoritative write path. Accounts
251/// have one intentional isolation need (Armory's disposable delete-account testing flow) and
252/// the per-account creation-time scope split (SPEC §3.2) hasn't shipped, so `id_store` /
253/// `resolve_shared_store_path()` stays the primary read/write path for accounts. This copy
254/// exists only so a link resolved here (always global) doesn't dead-end on an account row stuck
255/// in a fresh, per-channel `id_store`: see `identity::resolver::inject`'s account resolution
256/// (falls back to this store's `identity_get` only when `id_store`'s lookup misses) and
257/// `migrations::m0022_identity_store_links_backfill`, which backfills the mirror as it does
258/// links. `db_agent_identity_links.account_id` has NO foreign key here, as
259/// `run_shared_store_schema` does for `db_agent_definitions`: cross-database FKs can't be
260/// enforced in SQLite and the mirror isn't guaranteed complete, so application code enforces
261/// integrity and tolerates a miss.
262///
263/// A dedicated store, not a subset of the shared store reached by a new always-global path, is
264/// deliberate: "can this table ever be reached from a per-channel-isolated codepath" becomes a
265/// structural fact (a separate file and connection) rather than a convention a later call site
266/// of `resolve_shared_store_path()` could violate, the failure mode
267/// docs/specs/CHECKLIST_AGENT_DATA_SCOPE_ROUTING_2026_08_17.md items 2-4 record as having
268/// bitten more than once.
269///
270/// Idempotent — safe to call on every startup.
271pub fn run_identity_store_schema(conn: &Connection) -> Result<(), StoreError> {
272 conn.execute_batch(store_schema::IDENTITY_STORE_TABLES_SQL)?;
273 conn.execute_batch(super::vault::VAULT_SCHEMA)?; // The Vault's tables, no version bump: storage/vault.rs.
274 conn.execute_batch(super::vault_sync::SCHEMA)?; // What a shared Vault keeps besides: storage/vault_sync.rs.
275 conn.execute_batch(super::vault_changes::SCHEMA)?; // What agents changed that the person has not seen: storage/vault_changes.rs.
276 apply_additive_columns(conn, super::vault_changes::COLUMNS)?;
277 store_schema::seed_identity_blank_bundle(conn)?;
278 store_schema::add_identity_store_columns(conn)?;
279
280 Ok(())
281}
282
283/// Initialize the FileStore schema. Creates the wave_file and file_data
284/// tables. Already a flat single-DDL store — unaffected by the
285/// `objects.db` flattening.
286pub fn run_filestore_migrations(conn: &Connection) -> Result<(), StoreError> {
287 conn.execute_batch(
288 "CREATE TABLE IF NOT EXISTS db_wave_file (
289 zoneid TEXT NOT NULL,
290 name TEXT NOT NULL,
291 size INTEGER NOT NULL DEFAULT 0,
292 createdts INTEGER NOT NULL DEFAULT 0,
293 modts INTEGER NOT NULL DEFAULT 0,
294 opts TEXT NOT NULL DEFAULT '{}',
295 meta TEXT NOT NULL DEFAULT '{}',
296 PRIMARY KEY (zoneid, name)
297 );
298
299 CREATE TABLE IF NOT EXISTS db_file_data (
300 zoneid TEXT NOT NULL,
301 name TEXT NOT NULL,
302 partidx INTEGER NOT NULL,
303 data BLOB NOT NULL,
304 PRIMARY KEY (zoneid, name, partidx)
305 );",
306 )?;
307 // Line counter (Phase 5a-2, SPEC_AGENT_PANE_BOUNDED_LIVE_WINDOW_MIGRATION_
308 // 2026_09_23.md §6.3.7; see `filestore/counter.rs`). Additive and
309 // nullable, and deliberately WITHOUT a FILESTORE_SCHEMA_VERSION bump: the
310 // global transcript store is shared by every srv instance on the machine,
311 // and a bump would make older builds refuse to open it. Older builds
312 // insert rows without these columns (NULL = not counted) and write
313 // without maintaining them, which the counter detects. "duplicate
314 // column" is expected when another instance added them first.
315 apply_additive_columns(conn, [
316 "ALTER TABLE db_wave_file ADD COLUMN gen TEXT",
317 "ALTER TABLE db_wave_file ADD COLUMN lines INTEGER",
318 "ALTER TABLE db_wave_file ADD COLUMN lines_size INTEGER",
319 "ALTER TABLE db_wave_file ADD COLUMN lines_tail INTEGER",
320 "ALTER TABLE db_wave_file ADD COLUMN lines_modts INTEGER",
321 // Bumped (by the triggers below) by every write that changes bytes
322 // already in the file — not by appends — and the value an epoch was
323 // counted at. An epoch is valid only while they are equal.
324 "ALTER TABLE db_wave_file ADD COLUMN rev INTEGER",
325 "ALTER TABLE db_wave_file ADD COLUMN lines_rev INTEGER",
326 // A random identity per row, set by the insert trigger below: a file
327 // deleted and re-created is a different incarnation even if every
328 // other column (and the creation millisecond) comes out the same.
329 "ALTER TABLE db_wave_file ADD COLUMN incarnation BLOB",
330 ])?;
331 // `rev` is maintained by triggers, not by this code's writes, because
332 // triggers are part of the database: they fire for every connection,
333 // including older builds that know nothing about the counter. Any write
334 // that changes existing bytes bumps it:
335 // - a part deleted (write_file's replace, a delete);
336 // - a part written over with bytes that aren't a pure extension of it
337 // (REPLACE INTO / UPDATE). Appending extends the last part, which
338 // keeps it a prefix, so appends — ours or an older build's — don't.
339 // REPLACE INTO doesn't fire DELETE triggers (recursive_triggers is off,
340 // SQLite's default; nothing here enables it), so an append can't reach
341 // the delete trigger. A trigger on a deleted row's parts finds no row.
342 conn.execute_batch(
343 "-- Versioned name: CREATE TRIGGER IF NOT EXISTS never updates an
344 -- existing definition, so a changed rule gets a new name and the
345 -- old one is dropped.
346 DROP TRIGGER IF EXISTS db_file_data_rev_insert;
347 CREATE TRIGGER IF NOT EXISTS db_file_data_rev_insert_v2
348 BEFORE INSERT ON db_file_data
349 WHEN EXISTS (
350 SELECT 1 FROM db_file_data d
351 WHERE d.zoneid = NEW.zoneid AND d.name = NEW.name AND d.partidx = NEW.partidx
352 AND substr(NEW.data, 1, length(d.data)) IS NOT d.data
353 )
354 -- A NEW part inside the range the file already claims: bytes the
355 -- file declared (and a reader may have read as missing) are being
356 -- filled in, not appended. Every writer inserts appended parts
357 -- before raising `size`, so an append's new parts always start at
358 -- or past it. Older builds' write_file raises `size` first and
359 -- inserts after (Codex on #3631). 65536 is PART_DATA_SIZE.
360 OR (
361 NOT EXISTS (
362 SELECT 1 FROM db_file_data d
363 WHERE d.zoneid = NEW.zoneid AND d.name = NEW.name AND d.partidx = NEW.partidx
364 )
365 AND NEW.partidx * 65536 < (
366 SELECT COALESCE(MAX(w.size), 0) FROM db_wave_file w
367 WHERE w.zoneid = NEW.zoneid AND w.name = NEW.name
368 )
369 )
370 BEGIN
371 UPDATE db_wave_file SET rev = COALESCE(rev, 0) + 1
372 WHERE zoneid = NEW.zoneid AND name = NEW.name;
373 END;
374
375 CREATE TRIGGER IF NOT EXISTS db_file_data_rev_update
376 BEFORE UPDATE OF data ON db_file_data
377 WHEN substr(NEW.data, 1, length(OLD.data)) IS NOT OLD.data
378 BEGIN
379 UPDATE db_wave_file SET rev = COALESCE(rev, 0) + 1
380 WHERE zoneid = OLD.zoneid AND name = OLD.name;
381 END;
382
383 CREATE TRIGGER IF NOT EXISTS db_file_data_rev_delete
384 AFTER DELETE ON db_file_data
385 BEGIN
386 UPDATE db_wave_file SET rev = COALESCE(rev, 0) + 1
387 WHERE zoneid = OLD.zoneid AND name = OLD.name;
388 END;
389
390 -- Every row, whoever inserts it (older builds included), gets 64
391 -- random bits of identity. A delete + re-create in the same
392 -- millisecond with the same size and bytes is still a different
393 -- incarnation (Codex on #3631).
394 CREATE TRIGGER IF NOT EXISTS db_wave_file_incarnation
395 AFTER INSERT ON db_wave_file
396 BEGIN
397 UPDATE db_wave_file SET incarnation = randomblob(8)
398 WHERE zoneid = NEW.zoneid AND name = NEW.name;
399 END;
400
401 UPDATE db_wave_file SET incarnation = randomblob(8) WHERE incarnation IS NULL;",
402 )?;
403 Ok(())
404}
405
406/// Initialize the saga durability schema (`saga` + `saga_step` tables and
407/// their indexes). See `docs/specs/SPEC_SAGA_DURABILITY_2026-05-01.md` §2.2.
408/// Already a flat single-DDL store.
409pub fn run_saga_log_migrations(conn: &Connection) -> Result<(), StoreError> {
410 conn.execute_batch(
411 "CREATE TABLE IF NOT EXISTS saga (
412 saga_id INTEGER PRIMARY KEY,
413 name TEXT NOT NULL,
414 state TEXT NOT NULL,
415 started_at INTEGER NOT NULL,
416 terminal_at INTEGER,
417 failure_reason TEXT,
418 input_json TEXT NOT NULL
419 );
420
421 CREATE TABLE IF NOT EXISTS saga_step (
422 saga_id INTEGER NOT NULL REFERENCES saga(saga_id),
423 step_index INTEGER NOT NULL,
424 name TEXT NOT NULL,
425 state TEXT NOT NULL,
426 cmd_json TEXT NOT NULL,
427 output_json TEXT,
428 started_at INTEGER NOT NULL,
429 ended_at INTEGER,
430 PRIMARY KEY (saga_id, step_index)
431 );
432
433 CREATE INDEX IF NOT EXISTS saga_state_idx
434 ON saga(state) WHERE state IN ('running', 'compensating');
435 CREATE INDEX IF NOT EXISTS saga_terminal_idx
436 ON saga(terminal_at);",
437 )?;
438 Ok(())
439}
440
441/// `PRAGMA user_version` tripwire (AUDIT_SQLITE_SYSTEMS §8.5): compare the file's
442/// `user_version` to `current` and refuse to open a database written by a NEWER binary. This is
443/// the forward-compat safety lock of the channels design (`SPEC_DATA_CHANNELS_2026_05_24.md`
444/// §3.3): within a channel several released AgentMux versions share one data dir, and the lock
445/// keeps an older binary from writing into a schema a newer one laid down (as Chrome's
446/// profile-too-new check and Postgres's catalog version mismatch do).
447///
448/// **Must be called BEFORE `run_*_schema` / `run_*_migrations`.** Those include mutating steps
449/// (legacy-table renames, seed inserts, `CREATE TABLE` for tables the older binary doesn't
450/// have), so checking afterwards would let a downgraded binary alter a newer database before
451/// the error fires, breaking the "reject without touching disk" invariant (#1029).
452///
453/// Read-only: only a `PRAGMA user_version` query. [`stamp_version`] does the corresponding
454/// write AFTER migrations succeed.
455///
456/// On `SchemaTooNew` the user upgrades AgentMux to a version ≥ `found`, or sets
457/// `AGENTMUX_CHANNEL=<other>` to land in a different channel dir; the data on disk is preserved
458/// either way, since this function never modifies the database on the rejected path.
459pub fn check_schema_compat(
460 conn: &Connection,
461 current: i64,
462 db_label: &str,
463) -> Result<(), StoreError> {
464 let found: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
465 if found > current {
466 warn!(
467 db = db_label,
468 found, expected = current,
469 "database user_version is newer than this build — refusing \
470 to open. Upgrade AgentMux or switch channels.",
471 );
472 return Err(StoreError::SchemaTooNew {
473 db: db_label.to_string(),
474 found,
475 expected: current,
476 });
477 }
478 Ok(())
479}
480
481/// Stamp the database's `user_version` PRAGMA to `current`. Called
482/// AFTER `run_*_schema` succeeds, paired with a prior
483/// [`check_schema_compat`] that gated the migrations on the
484/// caller-binary speaking a compatible (or newer) schema version.
485///
486/// Splitting the read from the write makes the safety-lock order
487/// explicit at every call site:
488///
489/// ```ignore
490/// check_schema_compat(&conn, OBJECT_SCHEMA_VERSION, "objects.db")?;
491/// run_object_schema(&conn)?;
492/// stamp_version(&conn, OBJECT_SCHEMA_VERSION)?;
493/// ```
494pub fn stamp_version(conn: &Connection, current: i64) -> Result<(), StoreError> {
495 conn.execute_batch(&format!("PRAGMA user_version = {current};"))?;
496 Ok(())
497}
498
499#[cfg(test)]
500#[path = "migrations_tests.rs"]
501mod tests;