Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(server): ordered schema migrations, stamped and swap-aware (#524)

Myriad-Dreamin3fcfca60a0de
diff --git a/changelog/unreleased/2026-08-27-schema-migrations.md b/changelog/unreleased/2026-08-27-schema-migrations.md
new file mode 100644
index 00000000..a4ccb992
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-schema-migrations.md
@@ -0,0 +1,19 @@
+# Schema changes are migrations now, and travel with the platform
+
+- **Date:** 2026-08-27
+- **Type:** feature
+- **Scope:** `server`
+- **PR:** [#383](https://github.com/Prism-Shadow/penguin-harness/pull/383)
+
+[中文版](2026-08-27-schema-migrations.zh.md)
+
+`schema.ts` declares the shape a fresh database is created with; it cannot express a change. Re-running `CREATE TABLE IF NOT EXISTS` converges a database toward the current declaration without knowing which state it came from, so no build could tell a 0.2.4 database from a 0.2.7 one and every change had to be additive to be safe at all. Schema changes are ordered migrations now, each stamped into `PRAGMA user_version`, and a pushed platform carries its own — which is how a table reaches a runtime older than the feature that needs it.
+
+## Details
+
+- A migration spells out its own frozen DDL and never imports `SCHEMA_SQL`: referring to the live declaration would make an old migration mean something new every time the schema moves. Versions are contiguous from 1 and are never renumbered or edited once released, so a stamp names an unambiguous state.
+- Each migration and its version stamp commit in one transaction, so an interrupted run leaves the database at the last version that fully applied — never half-migrated.
+- `swapSafe` is the axis hot updates require. A pushed platform boots against a live database and is rolled back to its predecessor if it fails, leaving that predecessor on whatever the migration already did. Additive work survives; narrowing work does not. The runtime's own open may apply anything, while a booting platform applies only `swapSafe` migrations and refuses the rest **whole**, before touching the database, with `RestartRequiredError`.
+- Two migrations so far, both additive: 0.2.4 → 0.2.7 adds the `messaging_bindings` table and three indexes, and 0.2.7 → 0.2.8 adds that table's `final_reply_only` and `render_markdown` columns. A 0.2.4 database that has run them holds the same schema a current build creates from scratch — the same tables, columns, types, constraints and indexes. Column *order* can differ, because `ALTER TABLE ADD COLUMN` appends while a fresh database gets the column where the declaration puts it; matching it would mean rebuilding the table, which is not additive.
+- Every migration declares a `down`, or declares `null` to state that it has none — required rather than optional, so "there is no undo" is something the author says rather than forgets. `rollbackTo` applies them newest-first and refuses **whole** if anything in range is irreversible. It is an operator's tool and a destructive one (undoing "add a table" drops that table with its rows in it), and it is deliberately **not** the hot-update rollback: a failed platform boot reverts the platform, never the schema. Undoing DDL inside a process whose boot just failed would run destructive statements against a half-known state, and `swapSafe` exists precisely so that not undoing is safe.
+- Databases formed before migrations existed all read version 0 while sitting in genuinely different shapes, so a migration must tolerate finding its work already done. That is not only a version-1 concern: `schema.ts` still declares the current shape in full and `openDatabase` still runs its `ensureColumn` list, so a database can reach any migration with that migration's work already applied by the declarative track. Every migration stays idempotent until `SCHEMA_SQL` is frozen to a baseline.
diff --git a/changelog/unreleased/2026-08-27-schema-migrations.zh.md b/changelog/unreleased/2026-08-27-schema-migrations.zh.md
new file mode 100644
index 00000000..fe2e69ef
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-schema-migrations.zh.md
@@ -0,0 +1,19 @@
+# schema 变更改由迁移表达,并随 platform 一同送达
+
+- **Date:** 2026-08-27
+- **Type:** feature
+- **Scope:** `server`
+- **PR:** [#383](https://github.com/Prism-Shadow/penguin-harness/pull/383)
+
+[English](2026-08-27-schema-migrations.md)
+
+`schema.ts` 声明的是一个全新数据库被创建时的形状,它无法表达一次变更。反复执行 `CREATE TABLE IF NOT EXISTS` 只会让数据库朝当前声明收敛,却始终不知道它从哪个状态而来,因此没有任何构建能区分 0.2.4 与 0.2.7 的库,也因此每次变更都必须是加性的才谈得上安全。现在 schema 变更是有序迁移,各自记入 `PRAGMA user_version`;推送的 platform 携带自己的迁移——一张表正是这样抵达一个比它所属功能更旧的运行时。
+
+## 详情
+
+- 迁移写明自己那份冻结的 DDL,绝不引用 `SCHEMA_SQL`:引用活动声明会让一条旧迁移在每次 schema 变动后悄悄改变含义。版本号自 1 起连续,发布后既不重编号也不再修改,因此一个版本戳指向的状态毫不含糊。
+- 迁移与其版本戳在同一个事务中提交,因此中断的执行只会停在最后一个完整应用的版本上——绝不会出现迁移到一半的数据库。
+- `swapSafe` 是热更新所要求的那个维度。推送的 platform 在活动数据库上启动,失败即回滚到前一个 platform,而后者要面对迁移已经造成的既成事实。加性变更能被它安然容纳,收窄性的则不能。运行时自身的打开过程可以应用任何迁移;而正在启动的 platform 只应用 `swapSafe` 的迁移,遇到其余的则在触碰数据库之前**整体拒绝**,抛出 `RestartRequiredError`。
+- 目前有两条迁移,均为加性:0.2.4 → 0.2.7 新增 `messaging_bindings` 表与三个索引,0.2.7 → 0.2.8 为该表新增 `final_reply_only` 与 `render_markdown` 两列。一个 0.2.4 的库执行完它们之后,其 schema 与当前构建从零创建出来的一致——表、列、类型、约束与索引都相同。列的*顺序*可能不同,因为 `ALTER TABLE ADD COLUMN` 追加在末尾,而全新库中该列位于声明所在的位置;要让顺序一致就得重建表,那不是加性操作。
+- 每条迁移都声明 `down`,或声明为 `null` 以表明它没有回退——这是必填而非可选,因此"没有回退"是作者明确说出的,而不是遗漏掉的。`rollbackTo` 从最新一条开始倒序执行,若范围内存在不可逆的迁移则**整体拒绝**。它是运维工具,且具有破坏性(撤销"新增一张表"会连同表中的行一起删除);它刻意**不是**热更新的回滚机制:platform 启动失败回滚的是 platform,而非 schema。在一个刚刚启动失败的进程里撤销 DDL,等于对一个只知道一半的状态执行破坏性语句,而 `swapSafe` 的存在正是为了让"不撤销"本身就是安全的。
+- 在迁移机制出现之前形成的数据库,版本号一律读作 0,实际形状却各不相同,因此迁移必须容忍"要做的事已经做过"。这不只是第 1 条迁移的问题:`schema.ts` 仍然完整声明当前形状,`openDatabase` 仍然执行它那份 `ensureColumn` 列表,因此一个数据库到达任何一条迁移时,该迁移的工作都可能已由声明式那条轨道完成。在 `SCHEMA_SQL` 被冻结为 baseline 之前,这里的每条迁移都保持幂等。
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 55f90bf4..f2918861 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -42,6 +42,7 @@ import {
} from "./hmr/capabilities.js";
import type { ProxyControl } from "./hmr/capabilities.js";
import { openDatabase } from "./db/database.js";
+import { migrate } from "./db/migrations.js";
import { ErrorsRepo } from "./db/repos/errors.js";
import { MessagingBindingsRepo } from "./db/repos/messaging-bindings.js";
import { GoalsRepo } from "./db/repos/goals.js";
@@ -669,6 +670,12 @@ export function buildAppDeps(
const { config, db, authState, channels, hmr } = caps;
const log = overrides.log ?? ((line: string) => console.log(line));
+ // A pushed platform carries its own migrations, which is the only way the tables its
+ // business needs can reach a runtime older than they are — that runtime will never grow
+ // them by restarting, because it does not have them. swapPath: this boot can be rolled
+ // back, so a restart-only migration is refused here instead of being left behind.
+ migrate(db, { swapPath: true });
+
const usersRepo = new UsersRepo(db);
const projectsRepo = new ProjectsRepo(db);
const membersRepo = new MembersRepo(db);
diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.ts
index cfe06dbb..2e47ae63 100644
--- a/packages/server/src/db/database.ts
+++ b/packages/server/src/db/database.ts
@@ -8,6 +8,7 @@
import { mkdirSync } from "node:fs";
import path from "node:path";
import type { DatabaseSync } from "node:sqlite";
+import { migrate } from "./migrations.js";
import { SCHEMA_SQL } from "./schema.js";
// Fetch the runtime module via process.getBuiltinModule (node >=22.3): avoids static
@@ -78,6 +79,9 @@ export function openDatabase(dbPath: string): DatabaseSync {
// exist, so a downgrade after two Sessions saved the same bot needs those rows removed.
db.exec("DROP INDEX IF EXISTS idx_messaging_account");
upgradeLastActiveAt(db);
+ // The runtime's own open is the ONLY place a restart-only migration may be applied: it
+ // owns the process, so there is no boot to roll back out from under it.
+ migrate(db);
return db;
}
@@ -114,7 +118,12 @@ function upgradeLastActiveAt(db: DatabaseSync): void {
* Returns whether this call actually ALTERed the table (false = the column was already
* there), so a caller can gate one-time backfill work on it.
*/
-function ensureColumn(db: DatabaseSync, table: string, column: string, ddl: string): boolean {
+export function ensureColumn(
+ db: DatabaseSync,
+ table: string,
+ column: string,
+ ddl: string,
+): boolean {
const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];
if (cols.some((c) => c.name === column)) return false;
db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`);
diff --git a/packages/server/src/db/migrations.ts b/packages/server/src/db/migrations.ts
new file mode 100644
index 00000000..53215fed
--- /dev/null
+++ b/packages/server/src/db/migrations.ts
@@ -0,0 +1,256 @@
+/**
+ * Ordered, versioned schema migrations.
+ *
+ * `schema.ts` declares the shape a FRESH database is created with. It cannot express a
+ * CHANGE — `CREATE TABLE IF NOT EXISTS` only ever says "should exist", so re-running it
+ * converges a database toward the current declaration without ever knowing, or recording,
+ * which state it came from. That is why a build could not tell a 0.2.4 database from a
+ * 0.2.7 one, and why the only safe change was an additive one.
+ *
+ * A migration says what CHANGED, runs once, and leaves the database stamped with how far
+ * it has come (`PRAGMA user_version`). Two rules make that stamp trustworthy:
+ *
+ * FROZEN DDL. A migration spells out its own SQL and never imports SCHEMA_SQL. Referring
+ * to the live declaration would make an old migration silently mean something new every
+ * time the schema moves, which is the property that makes migrations auditable at all.
+ *
+ * ONE WAY, IN ORDER. Versions are contiguous from 1 and never renumbered or rewritten
+ * once released — a database that already stamped version N will never run N again, so
+ * editing N only changes what NEW databases get, and silently forks the two.
+ *
+ * `swapSafe` is this codebase's extra axis, and it exists because of hot updates. A
+ * pushed platform boots against a live database and is ROLLED BACK to its predecessor if
+ * it fails; the predecessor then runs on whatever the migration already did. Additive
+ * work survives that (the older build does not know the new table, so it never touches
+ * it) — narrowing work does not. Anything that drops, retypes, constrains, or reshapes
+ * is `swapSafe: false` and must be refused on the swap path rather than half-applied
+ * (see `migrate`'s `swapPath` option).
+ *
+ * DOWN, AND WHO DOES NOT CALL IT. Every migration declares an undo — or declares `null`
+ * to say it has none, which is a decision the author has to make rather than omit. What
+ * `down` is NOT is the hot-update rollback mechanism. When a pushed platform fails to boot
+ * the runtime reverts to its PREDECESSOR and the schema stays where the migration left it:
+ * undoing DDL inside a process whose boot just failed would run destructive statements
+ * against a half-known state, and `swapSafe` exists precisely so that not undoing is safe —
+ * the predecessor does not know the new table or column, so it never touches it. `down` is
+ * an operator's tool, called deliberately (`rollbackTo`), never by the swap.
+ *
+ * It is also LOSSY by nature: undoing "add a table" drops that table with its rows in it.
+ * Each `down` below names what its rows were.
+ *
+ * ADOPTION. Databases created before this file existed are all stamped 0 while sitting in
+ * genuinely different shapes, so a migration must tolerate finding its work already done.
+ * That is not only a version-1 concern: `schema.ts` still DECLARES the current shape in
+ * full and `openDatabase` still runs its ensureColumn list, so a database can arrive at a
+ * migration with that migration's work already applied by the declarative track. Until
+ * SCHEMA_SQL is frozen to a baseline and every later change is a migration, every
+ * migration here stays idempotent — `IF NOT EXISTS`, or the same `ensureColumn` guard the
+ * declarative track uses. Once that double track is gone, a bare `CREATE TABLE` that
+ * fails loudly becomes the point.
+ */
+import type { DatabaseSync } from "node:sqlite";
+import { ensureColumn } from "./database.js";
+
+export interface Migration {
+ /** Contiguous from 1. Never renumbered, never edited once released. */
+ version: number;
+ /** Kebab-case, names the change — read in logs and in the stamp's history. */
+ name: string;
+ /**
+ * May this run while a pushed platform boots? True only for strictly additive work,
+ * which a rollback to the previous platform survives. See the module doc.
+ */
+ swapSafe: boolean;
+ /** Applied inside a transaction; throw to abort and leave the version unchanged. */
+ up: (db: DatabaseSync) => void;
+ /**
+ * Undoes `up`, or null when this migration cannot be undone — required, not optional, so
+ * "there is no undo" is something the author states rather than forgets.
+ *
+ * Never called by the swap path (see the module doc): a failed boot reverts the platform,
+ * not the schema. Reached only through `rollbackTo`, and destructive by nature — dropping
+ * a table takes its rows with it.
+ */
+ down: ((db: DatabaseSync) => void) | null;
+}
+
+export const MIGRATIONS: readonly Migration[] = [
+ {
+ version: 1,
+ name: "messaging-bindings",
+ // Purely additive: one new table plus three indexes, no column of any existing table
+ // touched. A platform that rolls back to a predecessor without messaging simply never
+ // queries them.
+ swapSafe: true,
+ up(db) {
+ // 0.2.4 → 0.2.7. Frozen copy of the DDL as of 0.2.7; do not re-derive from schema.ts.
+ // IF NOT EXISTS only because version 1 adopts unstamped databases, which may already
+ // be at 0.2.7 (see the module doc's ADOPTION note).
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS messaging_bindings (
+ session_id TEXT NOT NULL,
+ channel TEXT NOT NULL,
+ account_id TEXT NOT NULL,
+ config_json TEXT NOT NULL,
+ enabled INTEGER NOT NULL DEFAULT 0,
+ line_per_message INTEGER NOT NULL DEFAULT 0,
+ last_chat_id TEXT,
+ last_chat_is_direct INTEGER NOT NULL DEFAULT 1,
+ last_inbound_message_id TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (session_id, channel)
+ );
+ CREATE INDEX IF NOT EXISTS idx_messaging_by_account ON messaging_bindings(channel, account_id);
+ CREATE INDEX IF NOT EXISTS idx_auth_sessions_expires ON auth_sessions(expires_at);
+ CREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(user_id);
+ `);
+ },
+ // LOSES every messaging binding: the channel credentials, the enabled flag and the
+ // last-chat memory all live in the table this drops. The auth_sessions indexes are
+ // derived and cost nothing to lose.
+ down(db) {
+ db.exec(`
+ DROP INDEX IF EXISTS idx_auth_sessions_user;
+ DROP INDEX IF EXISTS idx_auth_sessions_expires;
+ DROP INDEX IF EXISTS idx_messaging_by_account;
+ DROP TABLE IF EXISTS messaging_bindings;
+ `);
+ },
+ },
+ {
+ version: 2,
+ name: "messaging-delivery-flags",
+ // Two columns with defaults on an existing table: a rollback to a predecessor that
+ // does not know them leaves them at their defaults and reads nothing.
+ swapSafe: true,
+ up(db) {
+ // 0.2.7 → 0.2.8. ensureColumn rather than a bare ALTER because the declarative
+ // track may already have added these (see the module doc's ADOPTION note).
+ ensureColumn(db, "messaging_bindings", "final_reply_only", "INTEGER NOT NULL DEFAULT 0");
+ ensureColumn(db, "messaging_bindings", "render_markdown", "INTEGER NOT NULL DEFAULT 1");
+ },
+ // LOSES both delivery preferences on every binding; the bindings themselves survive.
+ // Dropped in reverse order for symmetry with `up`. Neither column is indexed, which is
+ // what lets SQLite drop them at all.
+ down(db) {
+ db.exec("ALTER TABLE messaging_bindings DROP COLUMN render_markdown");
+ db.exec("ALTER TABLE messaging_bindings DROP COLUMN final_reply_only");
+ },
+ },
+];
+
+/** The highest version this build knows how to reach. */
+export const LATEST_VERSION: number = MIGRATIONS.reduce((n, m) => Math.max(n, m.version), 0);
+
+/** How far this database has been migrated. Unstamped (pre-migrations) databases read 0. */
+export function schemaVersion(db: DatabaseSync): number {
+ const row = db.prepare("PRAGMA user_version").get() as { user_version: number } | undefined;
+ return row?.user_version ?? 0;
+}
+
+export class IrreversibleMigrationError extends Error {
+ constructor(readonly migration: Migration) {
+ super(
+ `migration ${migration.version} (${migration.name}) declares no down and cannot be rolled back. ` +
+ `Restore the database from a backup taken before it was applied.`,
+ );
+ this.name = "IrreversibleMigrationError";
+ }
+}
+
+export class RestartRequiredError extends Error {
+ constructor(readonly migration: Migration) {
+ super(
+ `migration ${migration.version} (${migration.name}) is restart-only and cannot be applied ` +
+ `while a pushed platform boots: it is not safe to leave behind if this boot is rolled back. ` +
+ `Restart the runtime on a build that carries it, then push again.`,
+ );
+ this.name = "RestartRequiredError";
+ }
+}
+
+/**
+ * Applies every migration this database has not reached yet, in order.
+ *
+ * Each migration and its version stamp commit together, so an interrupted run leaves the
+ * database at the last version that fully applied — never half-migrated. Already-current
+ * databases do no work and touch nothing.
+ *
+ * `swapPath` marks the caller as a booting pushed platform: the first pending migration
+ * that is not `swapSafe` throws RestartRequiredError BEFORE anything is applied, so the
+ * push is refused whole rather than partially landed.
+ */
+export function migrate(
+ db: DatabaseSync,
+ { swapPath = false }: { swapPath?: boolean } = {},
+): { from: number; to: number; applied: readonly string[] } {
+ const from = schemaVersion(db);
+ const pending = [...MIGRATIONS]
+ .sort((a, b) => a.version - b.version)
+ .filter((m) => m.version > from);
+ if (swapPath) {
+ const blocked = pending.find((m) => !m.swapSafe);
+ if (blocked) throw new RestartRequiredError(blocked);
+ }
+ const applied: string[] = [];
+ for (const m of pending) {
+ db.exec("BEGIN");
+ try {
+ m.up(db);
+ // PRAGMA takes no bound parameter; the value is this file's own integer literal.
+ db.exec(`PRAGMA user_version = ${m.version}`);
+ db.exec("COMMIT");
+ } catch (err) {
+ db.exec("ROLLBACK");
+ throw new Error(`migration ${m.version} (${m.name}) failed: ${String(err)}`, { cause: err });
+ }
+ applied.push(m.name);
+ }
+ return { from, to: schemaVersion(db), applied };
+}
+
+/**
+ * Reverts the database DOWN to `targetVersion`, newest migration first.
+ *
+ * An operator's tool, and a destructive one — see each migration's `down` for what its rows
+ * were. Deliberately not reachable from the swap path: a failed platform boot reverts the
+ * PLATFORM, never the schema (module doc).
+ *
+ * Refused whole, before anything runs, if any migration in range declares no `down`: a
+ * partial rollback would leave the database at a version whose meaning nobody wrote down.
+ * Each `down` commits with its version stamp, so an interrupted run stops at a real version.
+ */
+export function rollbackTo(
+ db: DatabaseSync,
+ targetVersion: number,
+): { from: number; to: number; reverted: readonly string[] } {
+ const from = schemaVersion(db);
+ if (targetVersion < 0) throw new Error(`target version ${targetVersion} is negative`);
+ if (targetVersion > from) {
+ throw new Error(`database is at version ${from}, which is already below ${targetVersion}`);
+ }
+ const toRevert = [...MIGRATIONS]
+ .filter((m) => m.version > targetVersion && m.version <= from)
+ .sort((a, b) => b.version - a.version);
+ const blocked = toRevert.find((m) => m.down === null);
+ if (blocked) throw new IrreversibleMigrationError(blocked);
+
+ const reverted: string[] = [];
+ for (const m of toRevert) {
+ db.exec("BEGIN");
+ try {
+ m.down!(db);
+ // Versions are contiguous, so the predecessor of `m` is exactly m.version - 1.
+ db.exec(`PRAGMA user_version = ${m.version - 1}`);
+ db.exec("COMMIT");
+ } catch (err) {
+ db.exec("ROLLBACK");
+ throw new Error(`rollback of migration ${m.version} (${m.name}) failed: ${String(err)}`, {
+ cause: err,
+ });
+ }
+ reverted.push(m.name);
+ }
+ return { from, to: schemaVersion(db), reverted };
+}
diff --git a/packages/server/test/db-migrations.test.ts b/packages/server/test/db-migrations.test.ts
new file mode 100644
index 00000000..d9c0605c
--- /dev/null
+++ b/packages/server/test/db-migrations.test.ts
@@ -0,0 +1,350 @@
+/**
+ * The ordered-migration mechanism, and the 0.2.4 → 0.2.7 migration that is its first entry.
+ *
+ * Two properties carry everything else: a real 0.2.4 database reaches exactly the shape a
+ * fresh one is created with (so a runtime older than the platform pushed onto it becomes
+ * usable), and the version stamp commits with the migration (so an interrupted run is never
+ * half-applied). The swapPath suite pins the rule that keeps a hot push honest.
+ */
+import { describe, expect, it } from "vitest";
+import type { DatabaseSync } from "node:sqlite";
+import {
+ IrreversibleMigrationError,
+ LATEST_VERSION,
+ MIGRATIONS,
+ RestartRequiredError,
+ migrate,
+ rollbackTo,
+ schemaVersion,
+} from "../src/db/migrations.js";
+import { SCHEMA_SQL } from "../src/db/schema.js";
+
+const sqlite = process.getBuiltinModule("node:sqlite");
+
+/**
+ * The v0.2.4 schema, as a frozen excerpt: today's declaration minus exactly what 0.2.4
+ * lacked. Derived by removing, not by hand-copying 15 tables that would fork from reality.
+ */
+function open024(): DatabaseSync {
+ const db = new sqlite.DatabaseSync(":memory:");
+ db.exec(SCHEMA_SQL);
+ db.exec("DROP TABLE messaging_bindings");
+ db.exec("DROP INDEX IF EXISTS idx_auth_sessions_expires");
+ db.exec("DROP INDEX IF EXISTS idx_auth_sessions_user");
+ return db;
+}
+
+/**
+ * Every schema object, in a form two databases can be compared by — columns keyed by NAME,
+ * with ordinal position (`cid`) excluded.
+ *
+ * Column ORDER is deliberately not compared. `ALTER TABLE ADD COLUMN` appends, while a
+ * fresh database gets the column wherever SCHEMA_SQL declares it, so a migrated database
+ * and a freshly created one hold the same columns in a different order — and always have:
+ * openDatabase's own ensureColumn list has appended columns to released databases since
+ * long before migrations existed. Making the orders match would mean rebuilding the table,
+ * which is not additive and would take the rollback guarantee with it. What order actually
+ * costs is the column order of `SELECT *`, and every read here maps rows by name.
+ *
+ * Index column order IS compared: for a composite index it is the index.
+ */
+function shape(db: DatabaseSync): string {
+ const objs = db
+ .prepare(
+ "SELECT type, name, tbl_name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name",
+ )
+ .all() as { type: string; name: string; tbl_name: string }[];
+ const dropCid = (rows: unknown[]): Record<string, unknown>[] =>
+ rows.map((r) => {
+ const { cid: _cid, ...rest } = r as Record<string, unknown>;
+ return rest;
+ });
+ return JSON.stringify(
+ objs.map((o) => ({
+ ...o,
+ detail:
+ o.type === "table"
+ ? dropCid(db.prepare(`PRAGMA table_info(${o.name})`).all()).sort((a, b) =>
+ String(a.name) < String(b.name) ? -1 : String(a.name) > String(b.name) ? 1 : 0,
+ )
+ : dropCid(db.prepare(`PRAGMA index_info(${o.name})`).all()),
+ unique:
+ o.type === "index"
+ ? (
+ db.prepare(`PRAGMA index_list(${o.tbl_name})`).all() as {
+ name: string;
+ unique: number;
+ }[]
+ ).find((i) => i.name === o.name)?.unique
+ : undefined,
+ })),
+ );
+}
+
+describe("migration mechanism", () => {
+ it("versions are contiguous from 1, so a stamp names an unambiguous state", () => {
+ expect(MIGRATIONS.map((m) => m.version)).toEqual(MIGRATIONS.map((_, i) => i + 1));
+ expect(LATEST_VERSION).toBe(MIGRATIONS.length);
+ });
+
+ it("stamps the database with how far it has come", () => {
+ const db = open024();
+ try {
+ expect(schemaVersion(db)).toBe(0);
+ const r = migrate(db);
+ expect(r.from).toBe(0);
+ expect(r.to).toBe(LATEST_VERSION);
+ expect(r.applied).toEqual(["messaging-bindings", "messaging-delivery-flags"]);
+ expect(schemaVersion(db)).toBe(LATEST_VERSION);
+ } finally {
+ db.close();
+ }
+ });
+
+ it("runs once: an already-current database does no work", () => {
+ const db = open024();
+ try {
+ migrate(db);
+ const before = shape(db);
+ const again = migrate(db);
+ expect(again.applied).toEqual([]);
+ expect(again.from).toBe(LATEST_VERSION);
+ expect(shape(db)).toBe(before);
+ } finally {
+ db.close();
+ }
+ });
+
+ it("a failing migration leaves the version untouched, never half-applied", () => {
+ const db = open024();
+ try {
+ const boom = {
+ version: LATEST_VERSION + 1,
+ name: "explodes",
+ swapSafe: true,
+ up(d: DatabaseSync) {
+ d.exec("CREATE TABLE scratch_marker (x TEXT)");
+ throw new Error("boom");
+ },
+ };
+ migrate(db);
+ const at = schemaVersion(db);
+ const shapeBefore = shape(db);
+ (MIGRATIONS as unknown as (typeof boom)[]).push(boom);
+ try {
+ expect(() => migrate(db)).toThrow(/explodes.*failed/s);
+ expect(schemaVersion(db)).toBe(at);
+ // The table its `up` created is gone with the rolled-back transaction.
+ expect(shape(db)).toBe(shapeBefore);
+ } finally {
+ (MIGRATIONS as unknown as (typeof boom)[]).pop();
+ }
+ } finally {
+ db.close();
+ }
+ });
+});
+
+describe("the swap path refuses what a rollback could not survive", () => {
+ it("applies swap-safe migrations while a pushed platform boots", () => {
+ const db = open024();
+ try {
+ expect(migrate(db, { swapPath: true }).applied).toEqual([
+ "messaging-bindings",
+ "messaging-delivery-flags",
+ ]);
+ } finally {
+ db.close();
+ }
+ });
+
+ it("refuses a restart-only migration whole, applying nothing", () => {
+ const db = open024();
+ try {
+ const narrowing = {
+ version: LATEST_VERSION + 1,
+ name: "narrows-something",
+ swapSafe: false,
+ up(d: DatabaseSync) {
+ d.exec("CREATE TABLE should_not_exist (x TEXT)");
+ },
+ };
+ (MIGRATIONS as unknown as (typeof narrowing)[]).push(narrowing);
+ try {
+ const before = shape(db);
+ expect(() => migrate(db, { swapPath: true })).toThrow(RestartRequiredError);
+ // Not even the swap-safe migration ahead of it ran: the push is refused whole.
+ expect(shape(db)).toBe(before);
+ expect(schemaVersion(db)).toBe(0);
+ // The runtime's own open, which owns the process, may apply it.
+ expect(migrate(db).applied).toEqual([
+ "messaging-bindings",
+ "messaging-delivery-flags",
+ "narrows-something",
+ ]);
+ } finally {
+ (MIGRATIONS as unknown as (typeof narrowing)[]).pop();
+ }
+ } finally {
+ db.close();
+ }
+ });
+});
+
+describe("0.2.4 → current", () => {
+ /** The whole point: an older runtime's database becomes what a current build creates. */
+ it("brings a 0.2.4 database to the shape a fresh one is created with", () => {
+ const old = open024();
+ const fresh = new sqlite.DatabaseSync(":memory:");
+ try {
+ fresh.exec(SCHEMA_SQL);
+ expect(shape(old)).not.toBe(shape(fresh));
+
+ migrate(old);
+
+ expect(shape(old)).toBe(shape(fresh));
+ } finally {
+ old.close();
+ fresh.close();
+ }
+ });
+
+ it("the messaging table it creates is writable, which is what the boot needed", () => {
+ const db = open024();
+ try {
+ migrate(db);
+ db.exec(
+ "INSERT INTO messaging_bindings (session_id, channel, account_id, config_json, created_at, updated_at)" +
+ " VALUES ('s1', 'telegram', 'a1', '{}', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')",
+ );
+ expect(db.prepare("SELECT COUNT(*) AS n FROM messaging_bindings").get()).toEqual({ n: 1 });
+ } finally {
+ db.close();
+ }
+ });
+
+ it("leaves existing rows alone", () => {
+ const db = open024();
+ try {
+ db.exec(
+ "INSERT INTO users (user_id, password_hash, is_admin, created_at) VALUES ('admin', 'h', 1, '2026-01-01T00:00:00Z')",
+ );
+ migrate(db);
+ expect(db.prepare("SELECT user_id FROM users").all()).toEqual([{ user_id: "admin" }]);
+ } finally {
+ db.close();
+ }
+ });
+});
+
+describe("rollbackTo", () => {
+ /** Every migration states an undo or states that it has none — never leaves it unsaid. */
+ it("every migration declares its down, one way or the other", () => {
+ for (const m of MIGRATIONS) {
+ expect(m, `${m.name} must declare down (a function or null)`).toHaveProperty("down");
+ expect(typeof m.down === "function" || m.down === null).toBe(true);
+ }
+ });
+
+ it("undoes a migration and moves the stamp back with it", () => {
+ const db = open024();
+ try {
+ migrate(db);
+ expect(schemaVersion(db)).toBe(LATEST_VERSION);
+
+ const r = rollbackTo(db, LATEST_VERSION - 1);
+ expect(r.from).toBe(LATEST_VERSION);
+ expect(r.to).toBe(LATEST_VERSION - 1);
+ expect(r.reverted).toEqual(["messaging-delivery-flags"]);
+ const cols = (
+ db.prepare("PRAGMA table_info(messaging_bindings)").all() as { name: string }[]
+ ).map((c) => c.name);
+ expect(cols).not.toContain("render_markdown");
+ expect(cols).not.toContain("final_reply_only");
+ } finally {
+ db.close();
+ }
+ });
+
+ /** The property that makes an undo an undo: up ∘ down ∘ up leaves the same schema as up. */
+ it("round-trips: up, down, up again lands on the same shape", () => {
+ const db = open024();
+ try {
+ migrate(db);
+ const afterUp = shape(db);
+
+ rollbackTo(db, 0);
+ expect(schemaVersion(db)).toBe(0);
+ expect(shape(db)).not.toBe(afterUp);
+
+ migrate(db);
+ expect(schemaVersion(db)).toBe(LATEST_VERSION);
+ expect(shape(db)).toBe(afterUp);
+ } finally {
+ db.close();
+ }
+ });
+
+ it("reverts newest first, so a multi-step rollback is ordered", () => {
+ const db = open024();
+ try {
+ migrate(db);
+ const r = rollbackTo(db, 0);
+ expect(r.reverted).toEqual(["messaging-delivery-flags", "messaging-bindings"]);
+ expect(
+ db
+ .prepare(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messaging_bindings'",
+ )
+ .get(),
+ ).toBeUndefined();
+ } finally {
+ db.close();
+ }
+ });
+
+ it("refuses whole when anything in range has no down, applying nothing", () => {
+ const db = open024();
+ try {
+ migrate(db);
+ const at = schemaVersion(db);
+ const before = shape(db);
+ const oneWay = {
+ version: LATEST_VERSION + 1,
+ name: "one-way",
+ swapSafe: true,
+ up(d: DatabaseSync) {
+ d.exec("CREATE TABLE one_way (x TEXT)");
+ },
+ down: null,
+ };
+ (MIGRATIONS as unknown as (typeof oneWay)[]).push(oneWay);
+ try {
+ migrate(db);
+ // Rolling back past the irreversible one is refused before anything is undone —
+ // including the reversible migrations sitting above it.
+ expect(() => rollbackTo(db, 0)).toThrow(IrreversibleMigrationError);
+ expect(schemaVersion(db)).toBe(at + 1);
+ } finally {
+ (MIGRATIONS as unknown as (typeof oneWay)[]).pop();
+ // Leave the fixture database as the other cases expect it.
+ db.exec("DROP TABLE IF EXISTS one_way");
+ db.exec(`PRAGMA user_version = ${at}`);
+ expect(shape(db)).toBe(before);
+ }
+ } finally {
+ db.close();
+ }
+ });
+
+ it("will not roll forward, and rejects a negative target", () => {
+ const db = open024();
+ try {
+ migrate(db);
+ expect(() => rollbackTo(db, LATEST_VERSION + 5)).toThrow(/already below/);
+ expect(() => rollbackTo(db, -1)).toThrow(/negative/);
+ } finally {
+ db.close();
+ }
+ });
+});