@jini-ai/db 0.6.19 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,851 @@
1
+ /**
2
+ * @file The core-mediated plugin dataModule engine (ADR-023 §2/§3/§4/§5/§6/§9).
3
+ *
4
+ * A plugin DECLARES its desired tables as data; CORE alone executes the DDL. A plugin never
5
+ * authors a migration and never holds a raw DB handle. The flow, in order:
6
+ * 1. validate the declaration (namespace `p_{pluginId}__*` §5, column shape, tier §3/T6) —
7
+ * before any I/O;
8
+ * 2. skip tables that already exist (idempotent, state-based reconciliation §2);
9
+ * 3. disk-headroom preflight (§3/T4) — fails closed before any file is touched;
10
+ * 4. namespace-adoption guard (§5/§6/T5) — fails closed on an unresolved provenance mismatch;
11
+ * 5. **snapshot the whole db FIRST** (§4) — the never-brick anchor;
12
+ * 6. open a durable phase-journal entry (§2/T3);
13
+ * 7. run all DDL, the post-DDL verification, AND the journal's own COMMITTED transition inside
14
+ * ONE transaction (see this file's POST-COMMIT DATA-LOSS WINDOW section for why verification
15
+ * and the journal write are in-transaction too, not just the DDL) so a failure rolls the live
16
+ * db AND the journal back together to a working, truthfully-recorded state (§9: recoverable,
17
+ * not zero-loss) — SQLite's own transaction rollback handles this same-process, non-crash
18
+ * case; the snapshot/journal exist for the CRASH case, recovered at next boot by
19
+ * `migration-recovery.ts` (see that file and `restore.ts` for why restore only ever runs
20
+ * there, never live).
21
+ *
22
+ * IN-MEMORY `dbPath` (BUG FIX, 2026-07-28): steps 3, 5, and 6 above are conditionally skipped for an
23
+ * in-memory (or SQLite's other non-file) `dbPath` — see `snapshot.ts`'s `isInMemoryDbPath`. Disk
24
+ * headroom (step 3, via `disk-headroom.ts`) and the whole snapshot/journal apparatus (steps 5-6)
25
+ * exist specifically to make "recovery at next boot" possible; for `:memory:` there IS no next
26
+ * boot — the database is discarded in full the instant the process ends, so "recoverable" and
27
+ * "not recoverable" are the same outcome regardless of whether a snapshot/journal entry exists.
28
+ * Skipping them for this case isn't a weakened guarantee, it's recognizing the guarantee doesn't
29
+ * apply. Step 7's same-process transaction rollback is UNAFFECTED and remains the full safety net
30
+ * for an in-memory db, because it is the only failure mode that can ever occur for one (there is no
31
+ * separate process to crash-and-restart into that could observe a different, corrupted state).
32
+ *
33
+ * COLUMN-LEVEL RECONCILIATION (BUG FIX, 2026-08-12): §2's own text is "Core diffs declared-state
34
+ * against live-state and executes the DDL itself" — but the first implementation of step 2 only
35
+ * diffed *table names*, not table *contents*. A plugin whose v2 manifest added a column to an
36
+ * already-existing table got `{ ok: true, created: [] }` back — the table-name presence check saw
37
+ * the table, concluded there was nothing to do, and took the early no-op path — and the new column
38
+ * silently never existed. The failure then surfaced far from its cause: at query time, against
39
+ * whatever repository call first touched the missing column, with no link back to the manifest
40
+ * that declared it. Step 2 now diffs declared columns against `PRAGMA table_info` for every table
41
+ * that already exists, not just the table's name. A declared-but-missing column on an existing
42
+ * table has three possible outcomes: (a) a plain nullable, non-PRIMARY-KEY column is safely
43
+ * addable via `ALTER TABLE ADD COLUMN` and gets queued as an alteration; (b) a `NOT NULL` column
44
+ * cannot — SQLite refuses `ADD COLUMN` with a `NOT NULL` constraint unless a non-NULL default is
45
+ * also supplied, and this declaration grammar (`ColumnDecl`) has no default field to supply one,
46
+ * so this fails closed with `COLUMN_ADD_NOT_NULL_WITHOUT_DEFAULT`; (c) a `PRIMARY KEY` column can
47
+ * never be added to an existing table via `ALTER TABLE` at all — SQLite has no such statement,
48
+ * only a full create-copy-drop-rename table rebuild, which is a materially larger and riskier
49
+ * change than this fix and stays explicitly out of scope — so this fails closed with
50
+ * `COLUMN_ADD_PRIMARY_KEY`. A live column whose type no longer matches its declaration also fails
51
+ * closed (`COLUMN_TYPE_MISMATCH`) for the same reason: a type change is a rebuild, not an `ALTER`.
52
+ *
53
+ * CONSTRAINT-LEVEL RECONCILIATION (BUG FIX, 2026-08-12): the reconciliation above diffed an
54
+ * existing column's `type` but not its `notNull`/`primaryKey` declarations — a plugin author
55
+ * tightening either constraint on an already-existing column (e.g. a v2 manifest marking a
56
+ * previously-nullable column `notNull: true`) got `{ ok: true, altered: [] }` back with the live
57
+ * column completely unchanged: the identical silent-non-enforcement bug class the type-mismatch
58
+ * fix above closed, just for two different fields on the same struct. `assertColumnNotNullMatches`
59
+ * and `assertColumnPrimaryKeyMatches` now run alongside `assertColumnTypeMatches` for every
60
+ * existing column a declaration mentions, each failing closed (`COLUMN_NOT_NULL_MISMATCH` /
61
+ * `COLUMN_PRIMARY_KEY_MISMATCH`) on disagreement, for the same reason as the type case: SQLite's
62
+ * `ALTER TABLE` cannot change either constraint on an existing column — no `ALTER COLUMN`, no way
63
+ * to add or drop a `NOT NULL` or `PRIMARY KEY` short of the same create-copy-drop-rename rebuild
64
+ * this file stays out of scope of everywhere else.
65
+ *
66
+ * Both checks are DIRECTION-AGNOSTIC — declared-stricter-than-live and declared-looser-than-live
67
+ * both fail closed — deliberately mirroring `COLUMN_TYPE_MISMATCH`'s own symmetric behavior rather
68
+ * than only catching the tightening direction the bug report above led with. The two directions
69
+ * are not equally *dangerous* (tightening risks silent bad data creeping in past a constraint the
70
+ * app believes SQLite is enforcing; loosening at most risks a write later hitting a live
71
+ * constraint the current manifest doesn't mention, which SQLite itself rejects loudly at write
72
+ * time, not silently) — but both are still a manifest that disagrees with the database it
73
+ * describes, and this module's whole job is to surface that disagreement at `declare()` time,
74
+ * next to the manifest, rather than let either direction surface later at some unrelated write
75
+ * site with no link back to the manifest. `COLUMN_TYPE_MISMATCH` never special-cased "safe"
76
+ * directions either (e.g. widening `INTEGER` to `REAL` isn't unsafe the way `TEXT`→`INTEGER` is)
77
+ * for the same underlying reason, so this stays consistent with the established fail-closed
78
+ * default rather than inventing a narrower rule for these two fields alone.
79
+ *
80
+ * `assertColumnPrimaryKeyMatches` compares against `getExistingColumns`'s already-boolean
81
+ * `primaryKey` field (`pk !== 0`, not `pk === 1`) so a column that is part of a *composite*
82
+ * primary key (`PRAGMA table_info`'s `pk` is an ordinal position, 1-based, not a 0/1 flag) is
83
+ * still read correctly as "is a primary key column" rather than only the first component
84
+ * matching. Whether that scenario can even arise given this engine's own DDL is a separate
85
+ * question: `ColumnDecl.primaryKey` is a single-column boolean with no table-level composite-key
86
+ * grammar, and `CREATE TABLE` with two columns each carrying a column-level `PRIMARY KEY`
87
+ * constraint is rejected by SQLite itself ("table has more than one primary key") before this
88
+ * code ever runs — so this engine cannot *create* a composite-PK table through its own DDL. A
89
+ * live table could still carry one from outside this engine's DDL entirely (the §0 access-control
90
+ * caveat below: a Tier-3 plugin holding a raw handle, or a table that predates this engine) — the
91
+ * ordinal-aware read guards against exactly that case rather than assuming it can't happen.
92
+ *
93
+ * A live column the CURRENT declaration no longer mentions is deliberately left alone rather than
94
+ * dropped — this engine never authors a `DROP COLUMN` on a plugin's behalf; an operator who rolled
95
+ * a plugin back to an older manifest, or a manifest that stopped mentioning a column on purpose,
96
+ * should not lose that column's data to a silent, unrequested `DROP`. When an existing table needs
97
+ * one or more columns added, the full snapshot/journal/single-transaction apparatus below still
98
+ * runs for it exactly as it does for a brand-new table — only the fully-reconciled no-op case
99
+ * (every declared table exists with every declared column already present and matching) skips it.
100
+ *
101
+ * INDEX-LEVEL RECONCILIATION (BUG FIX, 2026-08-12): the column-level reconciliation above still
102
+ * built `toAlter` from `columnsToAdd` alone — a declared `IndexDecl` on an already-existing table
103
+ * was reconciled only on the CREATE path (`table.indexes` was only ever walked inside the
104
+ * `plan.toCreate` loop), so a v2 manifest that added an index to an existing table got
105
+ * `{ ok: true, altered: [...] }` back (truthfully reporting the column work, if any) with the
106
+ * index itself silently never created — the identical bug class one level up. The kernel's `listIndexes`
107
+ * reads `fqTableName`'s live indexes via `PRAGMA index_list` + `PRAGMA index_info`, filtered to
108
+ * `origin: 'c'` rows only: SQLite also auto-creates an implicit index per `UNIQUE` column
109
+ * constraint (`origin: 'u'`) and one for most `PRIMARY KEY` shapes (`origin: 'pk'`, e.g.
110
+ * `sqlite_autoindex_*`), neither of which was ever declared through `IndexDecl` or created by this
111
+ * module's own `indexSql` — diffing against those would be comparing against something the
112
+ * declaration grammar can't even express. `planIndexReconciliation` then diffs declared indexes
113
+ * (matched by the SAME generated name `indexSql` already uses to create one) against that live
114
+ * set: a declared index missing live is queued in `indexesToAdd`, safely creatable via a plain
115
+ * `CREATE INDEX` — unlike the column NOT NULL/PRIMARY KEY cases above, an index carries no data
116
+ * for `ALTER` semantics to conflict with, so there is no "SQLite literally cannot express this"
117
+ * case here to fail closed on. A declared index whose live shape (column list, in order, or
118
+ * uniqueness) no longer matches is queued in `indexesToRecreate` (`DROP INDEX` then `CREATE INDEX`,
119
+ * both inside this call's single transaction, so a mid-way failure rolls back exactly like any
120
+ * other DDL here) — a deliberate choice, not an oversight: an index is pure derived structure with
121
+ * no data of its own, so dropping and rebuilding it risks nothing a rollback wouldn't already
122
+ * protect, in sharp contrast to a column whose type/constraint this file explicitly refuses to
123
+ * touch because doing so risks the column's actual data. The one way this CAN still fail is a
124
+ * `CREATE UNIQUE INDEX` rejected by genuine live duplicate values — that surfaces exactly like any
125
+ * other DDL failure in this transaction (rollback, `DDL_FAILED`, snapshot kept as the recovery
126
+ * point), needing no special-casing. A live index the CURRENT declaration no longer mentions is
127
+ * left alone, mirroring the column-drop policy directly above. `assertIdentifierFits` already
128
+ * covers every declared index's generated name unconditionally, for both the create and alter
129
+ * paths — `validate()` walks `table.indexes` for every table in the declaration up front, before
130
+ * reconciliation ever runs, so no separate length check is needed in this new path.
131
+ *
132
+ * POST-COMMIT JOURNAL INTEGRITY (BUG FIX, 2026-08-12): the catch block below used to write
133
+ * `ROLLED_BACK` unconditionally on ANY failure inside the DDL try block — but a failure can occur
134
+ * either BEFORE the `db.transaction()` call resolves (SQLite's own rollback truly undid every
135
+ * write; `ROLLED_BACK` is accurate) or AFTER it already committed (`verifyPostDdl` throwing, or
136
+ * even the `advancePhaseIfJournaled(..., "COMMITTED")` write itself throwing) — and for that second
137
+ * case, the DDL is live and durable, so `ROLLED_BACK` was a lie: the journal claimed a rollback
138
+ * that never happened. `migration-recovery.ts` only ever restores NON-terminal entries
139
+ * (`ROLLED_BACK`/`COMMITTED` are both terminal, see `migration-journal.ts`'s `TERMINAL_PHASES`), so
140
+ * a next-boot crash recovery would see this mislabeled entry, conclude there is nothing to do, and
141
+ * skip it — leaving the live db and the journal's account of it permanently disagreeing, with
142
+ * nothing left to ever reconcile them. `declareDataModule` now tracks `transactionCommitted`,
143
+ * flipped to `true` the instant `db.transaction(() => { ... })()` returns without throwing, and
144
+ * `recordFailurePhase` uses it to decide: pre-commit, write `ROLLED_BACK` as before (truthful,
145
+ * unchanged); post-commit, write NOTHING and leave the journal at whatever non-terminal phase it
146
+ * already reached (`VERIFYING`, set immediately after the transaction resolves, before either of
147
+ * the two post-commit throw sites) — non-terminal is exactly what makes next-boot recovery pick it
148
+ * up and restore from the pre-DDL snapshot. **CORRECTED below, same day**: leaving a non-terminal
149
+ * phase behind turned out to trade one bug for a worse one — see POST-COMMIT DATA-LOSS WINDOW
150
+ * immediately following this section for why "restore from the pre-DDL snapshot" is NOT the correct
151
+ * outcome for this case, and what replaced `transactionCommitted`/`recordFailurePhase` instead.
152
+ *
153
+ * POST-COMMIT DATA-LOSS WINDOW (BUG FIX, 2026-08-12, same-day follow-up to the fix immediately
154
+ * above): the fix above stopped LYING about a post-commit failure, but stopping the lie did not
155
+ * stop the underlying failure from existing. A post-commit `verifyPostDdl` failure correctly wrote
156
+ * nothing and left the entry at `VERIFYING` — but `VERIFYING` is non-terminal, and
157
+ * `migration-recovery.ts` treats every non-terminal entry as a crash-interrupted attempt requiring
158
+ * restore, indistinguishably from an actual process crash. The scenario this opened: DDL commits,
159
+ * verification fails (a normal, catchable, in-process failure — the process does NOT crash),
160
+ * `declareDataModule` returns `{ ok: false }`, and the site keeps running and serving traffic —
161
+ * nothing about a caught, in-process exception stops that. Every write the site accepts from that
162
+ * moment on, by ANY table, not just this plugin's, is exposed: the recovery snapshot is a
163
+ * WHOLE-FILE backup (§4), and `restoreFromSnapshot` (`restore.ts`) is a whole-file copy back over
164
+ * `dbPath`. The next time anything restarts the process — an operator's routine deploy, not a
165
+ * crash — boot-time `recoverIncompleteDataModuleMigrations` finds the still-`VERIFYING` entry,
166
+ * restores the whole db file to its pre-DDL state, and every write since is gone, with no crash and
167
+ * no operator warning to explain why. Direct reproduction (both as a fault-injected `:memory:` case
168
+ * and as a full write-after-failure/restart/verify-survival end-to-end case, see
169
+ * `data-module.test.ts`) confirmed both the live-column retention AND the eventual data loss on
170
+ * recovery; this was not a hypothetical.
171
+ *
172
+ * The root cause both this fix and the one above were reacting to is the same: `verifyPostDdl` ran
173
+ * AFTER `db.transaction()` had already committed, so there was always going to be SOME failure mode
174
+ * in that gap that a post-hoc phase label could describe accurately but never close. The actual fix
175
+ * is to remove the gap: `verifyPostDdl` now runs as the LAST statement INSIDE the same
176
+ * `db.transaction()` that runs the DDL, and a failure throws from inside that callback — the exact
177
+ * same mechanism `applyTableCreate`/`applyTableAlteration` already use to fail the transaction, so
178
+ * better-sqlite3's own automatic `ROLLBACK` undoes the DDL right along with it. There is no longer a
179
+ * state where the DDL is live but unverified; verified-and-committed and rolled-back-entirely are
180
+ * now the only two reachable outcomes. (Verification's own `PRAGMA table_info`/`index_list` reads
181
+ * are unaffected by running mid-transaction — a SQLite connection sees its own uncommitted writes
182
+ * within the same transaction exactly like committed ones, confirmed directly for this repo's
183
+ * better-sqlite3 build; it is not merely inferred from general SQL semantics.)
184
+ *
185
+ * The journal's own `COMMITTED` transition moves inside the same transaction too, via
186
+ * `migration-journal.ts`'s `stageJournalPhase` — a checkpoint-free write, because
187
+ * `advanceJournalPhase` CANNOT be reused here: it calls `PRAGMA wal_checkpoint(FULL)`, and a
188
+ * checkpoint issued by the SAME connection that holds an open write transaction throws `database
189
+ * table is locked` (confirmed directly, not assumed — SQLite's own docs do not call out
190
+ * same-connection mid-transaction checkpoint behavior at all, so this needed a real probe, not a
191
+ * reading). Writing `COMMITTED` inside the DDL transaction means a crash at the worst possible
192
+ * instant — literally between SQLite's internal commit and this function's `db.transaction()` call
193
+ * returning to JS — still leaves the journal reading `COMMITTED`, because that write committed WITH
194
+ * the DDL, as one indivisible unit; there is no instant at which live state and journal state can
195
+ * disagree. `stagePhaseIfJournaled` no-ops for the in-memory case exactly like
196
+ * `advancePhaseIfJournaled` does, matching this file's existing in-memory convention throughout.
197
+ *
198
+ * `declareDataModule`'s catch block goes back to unconditionally writing `ROLLED_BACK` — the
199
+ * `transactionCommitted` flag and `recordFailurePhase`'s pre/post-commit fork the previous fix
200
+ * introduced are gone, not because that reasoning was wrong but because it is now unreachable: with
201
+ * verification and the `COMMITTED` write both inside the transaction, `db.transaction()` throwing
202
+ * means SQLite really did roll everything back in every remaining case, so `ROLLED_BACK` is once
203
+ * again always truthful — the same simplicity the very first version of this file had, restored
204
+ * without reintroducing the bug that simplicity originally hid. The one sliver of risk that
205
+ * remains — the belt-and-suspenders `advancePhaseIfJournaled(db, journalId, "COMMITTED")` checkpoint
206
+ * call (re-writing the already-`COMMITTED` row purely to force its WAL merge), or
207
+ * `discardSnapshotIfFileBacked`, throwing AFTER the transaction has already committed everything
208
+ * that matters — is deliberately kept OUT of the catch path entirely: both calls run in their own
209
+ * swallow-all block after the transaction succeeds, because by that point the migration is already
210
+ * correct and durable, and reporting `{ ok: false }` for a housekeeping hiccup would itself be a lie
211
+ * in the other direction (the same principle `discardCommittedSnapshot` already documents: "must
212
+ * not turn a successful migration into a reported failure").
213
+ *
214
+ * T2 (§4's exclusive cross-process lock) is DELIBERATELY NOT acquired here — SPEC-033 correction
215
+ * (2026-07-16), superseding SPEC-032's original implementation. The ADR's own §4 text scopes T2's
216
+ * purpose narrowly: "The SQLite online backup API is safe under concurrent writers during
217
+ * snapshot creation — that step needs no change here. Restore is a different, less-safe
218
+ * operation" — the lock exists to guard RESTORE, not the live snapshot+DDL window. `restore.ts`'s
219
+ * own header already establishes that restore never runs live in this codebase's actual topology
220
+ * (single-process, single long-lived connection; restore only runs at boot-time recovery, before
221
+ * any other connection exists) — so T2's stated danger literally cannot occur here. Holding a
222
+ * real `PRAGMA locking_mode=EXCLUSIVE` during the live window instead caused a genuine,
223
+ * deterministic production bug: a live multi-boot smoke test against the real server found the
224
+ * store plugin's own separate `content.db` connection (`store-plugin.ts#bootstrapStore`) failing
225
+ * boot with "database is locked" every time, confirmed via A/B testing (disabling the lock calls
226
+ * made the failure disappear immediately) — the exact interleaving mechanism was not fully
227
+ * root-caused (multiple fire-and-forget dataModule declares and other writers share one
228
+ * long-lived connection in the real composition, unlike any isolated repro), but the causal link
229
+ * to `locking_mode=EXCLUSIVE` was empirically conclusive. Removing an unneeded lock whose own
230
+ * ADR-stated justification doesn't apply here, rather than debugging a specific interleaving
231
+ * further, is the correct call.
232
+ *
233
+ * ADR-023 is ACCEPTED (2026-07-11) after a 3-round external audit whose T1-T8 findings are now
234
+ * ALL reflected in code across this file, `migration-journal.ts`, `disk-headroom.ts`,
235
+ * `plugin-identity.ts`, `migration-recovery.ts`, and `restore.ts` — see SPEC-032/SPEC-033 for the
236
+ * full record of which finding lives where. This engine exists ahead of §12's "v1 ships seams
237
+ * only" schedule: §12's own last line permits shipping it early "against a concrete demand
238
+ * plugin," and Newsletter (`src/newsletter/data-module-manifest.ts`) is exactly that — a real
239
+ * production consumer already calling this engine before this file's safety mechanics existed.
240
+ *
241
+ * STORAGE KERNEL (2026-09-28, storage plan P1): the engine runs on the storage kernel, so the same
242
+ * declaration installs on SQLite, PGlite and Postgres. DDL text is unchanged on SQLite (column types
243
+ * via `columnTypeSql`; Postgres gets text/bigint/double precision/bytea); live state is read through
244
+ * the kernel's `listTables`/`listColumns`/`listIndexes` instead of `PRAGMA`s, with the same meaning.
245
+ * The snapshot, disk-headroom check and phase journal run only for a file-backed SQLite database
246
+ * (`recoverable` below): they exist for next-boot restore of a whole file. On Postgres/PGlite the DDL
247
+ * and its bookkeeping commit in one crash-safe transaction, so an interrupted attempt leaves nothing
248
+ * behind to restore — the same reasoning as the in-memory case above.
249
+ *
250
+ * NOTE (§0 access-control caveat): a Tier-3 in-process plugin could bypass this by opening the db
251
+ * file directly. The RECOVERABILITY guarantee here (who snapshots + who runs DDL = core) holds
252
+ * unconditionally for core-mediated DDL; the access-control framing is advisory until ADR-024 §4
253
+ * Rung 2 (capability sandbox) ships — see ADR-023 §0 for the full, precise wording.
254
+ */
255
+ import { statSync } from "node:fs";
256
+ import { sql } from "kysely";
257
+ import { autoIdColumnSql, columnTypeSql, listColumns, listIndexes, listTables, } from "../kernel/index.js";
258
+ import { checkDiskHeadroom } from "./disk-headroom.js";
259
+ import { advanceJournalPhase, beginJournalEntry, ensureMigrationJournal, stageJournalPhase } from "./migration-journal.js";
260
+ import { checkNamespaceAdoption } from "./plugin-identity.js";
261
+ import { pluginKernel } from "./plugin-store.js";
262
+ import { discardCommittedSnapshot, isInMemoryDbPath, snapshotDb } from "./snapshot.js";
263
+ const IDENT = /^[a-z][a-z0-9_]*$/;
264
+ const TYPES = new Set(["TEXT", "INTEGER", "REAL", "BLOB"]);
265
+ class DeclError extends Error {
266
+ code;
267
+ constructor(code, message) {
268
+ super(message);
269
+ this.code = code;
270
+ }
271
+ }
272
+ const fqName = (pluginId, name) => `p_${pluginId}__${name}`;
273
+ /** Validate the declaration entirely before any I/O (§5 namespace + column shape + §3/T6 tier). */
274
+ /**
275
+ * PostgreSQL's hard identifier ceiling (`NAMEDATALEN - 1`). SQLite has no limit at all, which is
276
+ * exactly why this needs checking here rather than being discovered later: nothing in a
277
+ * SQLite-only world ever fails, so a too-long name ships silently and only becomes a defect on a
278
+ * Postgres-backed site.
279
+ */
280
+ const MAX_IDENTIFIER_BYTES = 63;
281
+ /**
282
+ * Fails a declaration whose generated identifier would exceed what PostgreSQL accepts.
283
+ *
284
+ * Why reject rather than truncate: PostgreSQL truncates over-long identifiers *silently* — no
285
+ * error, no warning. The name in the catalog then differs from the name this module computed, so
286
+ * `existingTables`-style idempotency checks look for a name that is not there, conclude the object
287
+ * is missing, and try to create it again on every activation. Failing closed at declare time (like
288
+ * every other check in this function, all of which run before any I/O) turns a silent divergence on
289
+ * one backend into an install-time error the plugin author sees immediately.
290
+ *
291
+ * Measured headroom at the time this was added: the longest live identifier is 42 bytes
292
+ * (the comments plugin's moderation-queue index), so no existing plugin is affected. The budget a
293
+ * plugin author actually has is `pluginId + tableName + indexName <= 53` for an index, since the
294
+ * `idx_`, `p_`, and two `__` separators consume the other 10.
295
+ */
296
+ function assertIdentifierFits(identifier, what) {
297
+ if (Buffer.byteLength(identifier, "utf8") <= MAX_IDENTIFIER_BYTES)
298
+ return;
299
+ throw new DeclError("IDENTIFIER_TOO_LONG", `${what} generates the identifier "${identifier}" (${Buffer.byteLength(identifier, "utf8")} bytes), ` +
300
+ `which exceeds PostgreSQL's ${MAX_IDENTIFIER_BYTES}-byte limit and would be silently truncated. ` +
301
+ `Shorten the plugin id, table name, or index name.`);
302
+ }
303
+ /**
304
+ * Validates one table's columns and returns the set of names its indexes are allowed to reference.
305
+ *
306
+ * Returning the set rather than recomputing it in the index pass is what keeps the two loops
307
+ * independent — an index can only be checked against columns this same table declared, and pulling
308
+ * that dependency out into a return value is what allows both loops to be top-level functions
309
+ * rather than nested inside `validate`.
310
+ */
311
+ function validateColumns(table) {
312
+ if (table.columns.length === 0)
313
+ throw new DeclError("NO_COLUMNS", `table ${table.name} declares no columns`);
314
+ const declaredColumns = new Set();
315
+ for (const col of table.columns) {
316
+ if (!IDENT.test(col.name))
317
+ throw new DeclError("BAD_COLUMN", `invalid column name: ${col.name}`);
318
+ if (!TYPES.has(col.type))
319
+ throw new DeclError("BAD_TYPE", `unsupported column type for ${col.name}: ${col.type}`);
320
+ declaredColumns.add(col.name);
321
+ }
322
+ return declaredColumns;
323
+ }
324
+ /** Validates one index's declared columns against the table's actual columns — declared at TOP
325
+ * LEVEL (not a closure inside `validateIndexes`' loop) so it does not inherit that loop's own
326
+ * nesting; see `validate()`'s own doc above for why a nested closure would change nothing. */
327
+ function validateIndexColumns(idx, table, declaredColumns) {
328
+ if (idx.columns.length === 0)
329
+ throw new DeclError("EMPTY_INDEX", `index ${idx.name} on table ${table.name} declares no columns`);
330
+ for (const col of idx.columns) {
331
+ if (!declaredColumns.has(col)) {
332
+ throw new DeclError("INDEX_UNKNOWN_COLUMN", `index ${idx.name} on table ${table.name} references undeclared column: ${col}`);
333
+ }
334
+ }
335
+ }
336
+ /** Validates one table's index declarations against the columns that table actually declared. */
337
+ function validateIndexes(pluginId, table, declaredColumns) {
338
+ for (const idx of table.indexes ?? []) {
339
+ if (!IDENT.test(idx.name))
340
+ throw new DeclError("BAD_INDEX_NAME", `invalid index name: ${idx.name}`);
341
+ assertIdentifierFits(`idx_${fqName(pluginId, table.name)}__${idx.name}`, `index ${idx.name} on table ${table.name}`);
342
+ validateIndexColumns(idx, table, declaredColumns);
343
+ }
344
+ }
345
+ /** Validates one table declaration end to end: name, generated identifier length, columns, indexes. */
346
+ function validateTable(pluginId, table) {
347
+ if (!IDENT.test(table.name))
348
+ throw new DeclError("BAD_TABLE_NAME", `invalid table name: ${table.name}`);
349
+ assertIdentifierFits(fqName(pluginId, table.name), `table ${table.name}`);
350
+ validateIndexes(pluginId, table, validateColumns(table));
351
+ }
352
+ /**
353
+ * Every declaration check, run before any I/O so the whole engine fails closed on a bad manifest.
354
+ *
355
+ * Split into `validateTable`/`validateColumns`/`validateIndexes` rather than one nested triple
356
+ * loop: as a single function this measured cyclomatic 16 / cognitive 31 against this repo's
357
+ * ceiling of 10 for both. The nesting was the cognitive driver — SonarJS charges depth to every
358
+ * control-flow structure inside an enclosing loop, so extraction has to be to **top level** to pay
359
+ * off. A closure declared inside the loop body would inherit the loop's nesting and change nothing.
360
+ */
361
+ function validate(decl) {
362
+ if (!IDENT.test(decl.pluginId))
363
+ throw new DeclError("BAD_PLUGIN_ID", `invalid pluginId: ${decl.pluginId}`);
364
+ if (decl.pluginTier === "tier-1") {
365
+ throw new DeclError("TIER1_NOT_ALLOWED", "dataModule requires executable code (Tier-2 or Tier-3); Tier-1 plugins cannot request it");
366
+ }
367
+ if (decl.tables.length === 0)
368
+ throw new DeclError("EMPTY", "declaration lists no tables");
369
+ for (const table of decl.tables)
370
+ validateTable(decl.pluginId, table);
371
+ }
372
+ /**
373
+ * One column's DDL. Identifiers are validated (`IDENT`) before any DDL is built, so quoting them
374
+ * into the text is safe; the type is the dialect's spelling of the declared affinity (unchanged on
375
+ * SQLite). The same text is what `_plugin_migrations.ddl` records.
376
+ */
377
+ function columnSql(kernel, col) {
378
+ let ddl = `"${col.name}" ${columnTypeSql(kernel.dialect, col.type)}`;
379
+ if (col.primaryKey)
380
+ ddl += " PRIMARY KEY";
381
+ if (col.notNull)
382
+ ddl += " NOT NULL";
383
+ return ddl;
384
+ }
385
+ /** Runs one DDL statement this module built from validated identifiers. */
386
+ async function executeDdl(kernel, ddl) {
387
+ await kernel.execute(sql.raw(ddl));
388
+ }
389
+ function indexSql(fqTableName, idx) {
390
+ const indexName = `idx_${fqTableName}__${idx.name}`;
391
+ const unique = idx.unique ? "UNIQUE " : "";
392
+ const columns = idx.columns.map((c) => `"${c}"`).join(", ");
393
+ return { indexName, sql: `CREATE ${unique}INDEX "${indexName}" ON "${fqTableName}" (${columns})` };
394
+ }
395
+ /** Core's own migration timeline, extended to admit plugin entries later (ADR-023 §12). */
396
+ async function ensureJournal(kernel) {
397
+ const text = sql.raw(columnTypeSql(kernel.dialect, "TEXT"));
398
+ await kernel.execute(sql `CREATE TABLE IF NOT EXISTS _plugin_migrations (
399
+ id ${sql.raw(autoIdColumnSql(kernel.dialect))},
400
+ plugin_id ${text} NOT NULL,
401
+ table_name ${text} NOT NULL,
402
+ ddl ${text} NOT NULL,
403
+ snapshot_path ${text},
404
+ at ${sql.raw(columnTypeSql(kernel.dialect, "INTEGER"))} NOT NULL
405
+ )`);
406
+ }
407
+ async function existingTables(kernel, names) {
408
+ if (names.length === 0)
409
+ return new Set();
410
+ const wanted = new Set(names);
411
+ return new Set((await listTables(kernel)).filter((name) => wanted.has(name)));
412
+ }
413
+ /**
414
+ * Reads `fqTableName`'s live column shape through the kernel's `listColumns` (SQLite:
415
+ * `pragma_table_info`, whose ordinal `pk` it already reads as "is part of the primary key").
416
+ */
417
+ async function getExistingColumns(kernel, fqTableName) {
418
+ const columns = await listColumns(kernel, fqTableName);
419
+ return new Map(columns.map((c) => [c.name, { type: c.type, notNull: c.notNull, primaryKey: c.primaryKey }]));
420
+ }
421
+ /**
422
+ * Decides whether a declared-but-missing column on an already-existing table is safely addable
423
+ * via `ALTER TABLE ADD COLUMN`, throwing a fail-closed `DeclError` for the two cases SQLite
424
+ * cannot express as an `ADD COLUMN` at all (see this file's header comment for the full
425
+ * reasoning). Returns `col` unchanged when it is safe to add.
426
+ */
427
+ function planMissingColumn(tableName, col) {
428
+ if (col.primaryKey) {
429
+ throw new DeclError("COLUMN_ADD_PRIMARY_KEY", `table ${tableName} is missing declared column "${col.name}", which is a PRIMARY KEY. ` +
430
+ `SQLite's ALTER TABLE has no way to add a primary key to an existing table — only a full ` +
431
+ `table rebuild can, and this engine does not perform rebuilds. Ship "${col.name}" under a ` +
432
+ `new table name instead, or coordinate an explicit, out-of-band migration.`);
433
+ }
434
+ if (col.notNull) {
435
+ throw new DeclError("COLUMN_ADD_NOT_NULL_WITHOUT_DEFAULT", `table ${tableName} is missing declared column "${col.name}", declared NOT NULL. SQLite's ` +
436
+ `ALTER TABLE ADD COLUMN refuses a NOT NULL column unless a non-NULL default is also given, ` +
437
+ `and this declaration grammar (ColumnDecl) has no default field to supply one. Declare ` +
438
+ `"${col.name}" as nullable (omit notNull) so it can be added, and enforce NOT NULL at the ` +
439
+ `application layer, or backfill it before requiring the constraint here.`);
440
+ }
441
+ return col;
442
+ }
443
+ /**
444
+ * Fails closed when a column that already exists on the live table no longer matches its
445
+ * declared type. A type change (e.g. TEXT → INTEGER) needs a table rebuild, the same as the
446
+ * missing-column PRIMARY KEY case above — this module never attempts one.
447
+ */
448
+ function assertColumnTypeMatches(kernel, tableName, col, existingCol) {
449
+ // Type names compare case-insensitively (SQLite's own rule): `listColumns` reports lower case.
450
+ if (existingCol.type === columnTypeSql(kernel.dialect, col.type).toLowerCase())
451
+ return;
452
+ throw new DeclError("COLUMN_TYPE_MISMATCH", `table ${tableName} column "${col.name}" is declared ${col.type} but the live column is ` +
453
+ `${existingCol.type.toUpperCase()}. Changing a column's type needs a table rebuild, which this engine ` +
454
+ `does not perform.`);
455
+ }
456
+ /**
457
+ * Fails closed when a column that already exists on the live table no longer matches its
458
+ * declared `NOT NULL` constraint, in EITHER direction (see this file's header comment,
459
+ * CONSTRAINT-LEVEL RECONCILIATION, for why this is deliberately symmetric rather than only
460
+ * catching the tightening direction). SQLite's `ALTER TABLE` cannot flip `NOT NULL` on an
461
+ * existing column either way without a table rebuild, the same reason `assertColumnTypeMatches`
462
+ * fails closed on a type change.
463
+ */
464
+ function assertColumnNotNullMatches(kernel, tableName, col, existingCol) {
465
+ // Postgres makes every PRIMARY KEY column NOT NULL; SQLite does not (a legacy quirk it keeps).
466
+ const declaredNotNull = (col.notNull ?? false) || (kernel.dialect === "postgres" && col.primaryKey === true);
467
+ if (existingCol.notNull === declaredNotNull)
468
+ return;
469
+ throw new DeclError("COLUMN_NOT_NULL_MISMATCH", `table ${tableName} column "${col.name}" is declared ${declaredNotNull ? "NOT NULL" : "nullable"} but ` +
470
+ `the live column is ${existingCol.notNull ? "NOT NULL" : "nullable"}. Changing a column's NOT NULL ` +
471
+ `constraint needs a table rebuild, which this engine does not perform.`);
472
+ }
473
+ /**
474
+ * Fails closed when a column that already exists on the live table no longer matches its
475
+ * declared `PRIMARY KEY` membership, in EITHER direction (same symmetric reasoning as
476
+ * `assertColumnNotNullMatches`). Compares against `existingCol.primaryKey`, which
477
+ * `getExistingColumns` already normalizes from `PRAGMA table_info`'s ordinal `pk` column via
478
+ * `pk !== 0` — see this file's header comment for why that read is what keeps a composite primary
479
+ * key from producing a false positive here.
480
+ */
481
+ function assertColumnPrimaryKeyMatches(tableName, col, existingCol) {
482
+ const declaredPrimaryKey = col.primaryKey ?? false;
483
+ if (existingCol.primaryKey === declaredPrimaryKey)
484
+ return;
485
+ throw new DeclError("COLUMN_PRIMARY_KEY_MISMATCH", `table ${tableName} column "${col.name}" is declared ${declaredPrimaryKey ? "a PRIMARY KEY" : "not a PRIMARY KEY"} ` +
486
+ `but the live column ${existingCol.primaryKey ? "is" : "is not"} part of the table's primary key. SQLite's ` +
487
+ `ALTER TABLE cannot add or remove a primary key on an existing table — only a full table rebuild can, ` +
488
+ `and this engine does not perform rebuilds.`);
489
+ }
490
+ /**
491
+ * Diffs one already-existing table's declared columns against its live shape (§2's own text:
492
+ * "diffs declared-state against live-state"). A live column absent from `table.columns` is
493
+ * deliberately not inspected here at all — see this file's header comment for why that drift is
494
+ * left alone rather than dropped.
495
+ */
496
+ async function planColumnReconciliation(kernel, table, fqTableName) {
497
+ const existingColumns = await getExistingColumns(kernel, fqTableName);
498
+ const columnsToAdd = [];
499
+ for (const col of table.columns) {
500
+ const existingCol = existingColumns.get(col.name);
501
+ if (existingCol === undefined) {
502
+ columnsToAdd.push(planMissingColumn(table.name, col));
503
+ continue;
504
+ }
505
+ assertColumnTypeMatches(kernel, table.name, col, existingCol);
506
+ assertColumnNotNullMatches(kernel, table.name, col, existingCol);
507
+ assertColumnPrimaryKeyMatches(table.name, col, existingCol);
508
+ }
509
+ return columnsToAdd;
510
+ }
511
+ /** True when a declared index's shape (column list, in order, and uniqueness) matches its live index. */
512
+ function indexMatches(idx, existing) {
513
+ const declaredUnique = idx.unique ?? false;
514
+ if (existing.unique !== declaredUnique)
515
+ return false;
516
+ if (existing.columns.length !== idx.columns.length)
517
+ return false;
518
+ return existing.columns.every((col, i) => col === idx.columns[i]);
519
+ }
520
+ /**
521
+ * Diffs one already-existing table's declared indexes against its live shape (see this file's
522
+ * header comment, INDEX-LEVEL RECONCILIATION, for the full reasoning behind `indexesToAdd` vs.
523
+ * `indexesToRecreate` vs. leaving an undeclared live index alone).
524
+ *
525
+ * The kernel's `listIndexes` keys explicitly-authored indexes by their live names. Only
526
+ * `CREATE INDEX` indexes are listed — the implicit ones a `UNIQUE` column constraint or a
527
+ * `PRIMARY KEY` makes (SQLite origin `u`/`pk`, e.g. `sqlite_autoindex_*`; Postgres constraint-backed
528
+ * indexes) were never declared through `IndexDecl` or created by this module's own `indexSql`.
529
+ */
530
+ async function planIndexReconciliation(kernel, table, fqTableName) {
531
+ const existingIndexes = await listIndexes(kernel, fqTableName);
532
+ const indexesToAdd = [];
533
+ const indexesToRecreate = [];
534
+ for (const idx of table.indexes ?? []) {
535
+ const { indexName } = indexSql(fqTableName, idx);
536
+ const existing = existingIndexes.get(indexName);
537
+ if (existing === undefined) {
538
+ indexesToAdd.push(idx);
539
+ continue;
540
+ }
541
+ if (!indexMatches(idx, existing))
542
+ indexesToRecreate.push(idx);
543
+ }
544
+ return { indexesToAdd, indexesToRecreate };
545
+ }
546
+ /**
547
+ * Builds the full reconciliation plan for a validated declaration: which declared tables don't
548
+ * exist yet at all (`toCreate`, the pre-existing behavior) and which already-existing tables need
549
+ * one or more columns added and/or indexes added or recreated (`toAlter`). Throws a fail-closed
550
+ * `DeclError` if any existing table's live column shape can't be reconciled by a plain
551
+ * `ALTER TABLE ADD COLUMN` — index drift never throws here; see `planIndexReconciliation`.
552
+ */
553
+ async function planReconciliation(kernel, decl, existingTableNames) {
554
+ const toCreate = [];
555
+ const toAlter = [];
556
+ for (const table of decl.tables) {
557
+ const fqTableName = fqName(decl.pluginId, table.name);
558
+ if (!existingTableNames.has(fqTableName)) {
559
+ toCreate.push(table);
560
+ continue;
561
+ }
562
+ const columnsToAdd = await planColumnReconciliation(kernel, table, fqTableName);
563
+ const { indexesToAdd, indexesToRecreate } = await planIndexReconciliation(kernel, table, fqTableName);
564
+ if (columnsToAdd.length > 0 || indexesToAdd.length > 0 || indexesToRecreate.length > 0) {
565
+ toAlter.push({ fqTableName, columnsToAdd, indexesToAdd, indexesToRecreate });
566
+ }
567
+ }
568
+ return { toCreate, toAlter };
569
+ }
570
+ /** Records one applied DDL statement in the site-wide migration timeline (dedupes what was 3 inline call sites). */
571
+ async function recordMigration(kernel, pluginId, objectName, ddl, snapshotPath, at) {
572
+ await kernel.run((db) => db
573
+ .insertInto("_plugin_migrations")
574
+ .values({ plugin_id: pluginId, table_name: objectName, ddl, snapshot_path: snapshotPath, at })
575
+ .execute());
576
+ }
577
+ /**
578
+ * Re-reads one altered table's live indexes and reports any declared-added-or-recreated index
579
+ * (`indexesToAdd` or `indexesToRecreate`) not actually there under its generated name. Indexes on
580
+ * a brand-new table (`plan.toCreate`) are pre-existing, out-of-scope-for-this-fix behavior — this
581
+ * only covers the alter path this fix adds, matching `missingColumns`'s scope one level up.
582
+ */
583
+ async function verifyAlteredIndexes(kernel, alteration) {
584
+ const nowExistingIndexes = await listIndexes(kernel, alteration.fqTableName);
585
+ const declaredIndexes = [...alteration.indexesToAdd, ...alteration.indexesToRecreate];
586
+ return declaredIndexes
587
+ .map((idx) => indexSql(alteration.fqTableName, idx).indexName)
588
+ .filter((indexName) => !nowExistingIndexes.has(indexName))
589
+ .map((indexName) => `index ${indexName}`);
590
+ }
591
+ /**
592
+ * Post-DDL sanity check (§2): re-reads live state and returns a description of anything the DDL
593
+ * just run in this same transaction claims to have applied but that isn't actually there. Empty
594
+ * means the DDL is confirmed applied; a non-empty result makes the caller throw (see
595
+ * `declareDataModule`, POST-COMMIT DATA-LOSS WINDOW in this file's header) — called as the LAST
596
+ * statement inside the DDL transaction, so a non-empty result rolls the whole transaction back
597
+ * atomically with the DDL, even though SQLite itself reported no DDL error. `PRAGMA table_info` /
598
+ * `index_list` reads mid-transaction see this transaction's own uncommitted writes exactly like
599
+ * committed ones (same connection, standard SQLite read-your-writes semantics — confirmed directly,
600
+ * not merely assumed), so this check is exactly as sensitive to a real drift now as it was
601
+ * post-commit.
602
+ */
603
+ async function verifyPostDdl(kernel, decl, plan) {
604
+ const createdNames = plan.toCreate.map((t) => fqName(decl.pluginId, t.name));
605
+ const nowExistingTables = await existingTables(kernel, createdNames);
606
+ const missingTables = createdNames.filter((name) => !nowExistingTables.has(name));
607
+ const missingColumns = [];
608
+ const missingIndexes = [];
609
+ for (const alteration of plan.toAlter) {
610
+ const nowExisting = await getExistingColumns(kernel, alteration.fqTableName);
611
+ for (const c of alteration.columnsToAdd) {
612
+ if (!nowExisting.has(c.name))
613
+ missingColumns.push(`${alteration.fqTableName}.${c.name}`);
614
+ }
615
+ missingIndexes.push(...(await verifyAlteredIndexes(kernel, alteration)));
616
+ }
617
+ return [...missingTables, ...missingColumns, ...missingIndexes];
618
+ }
619
+ /** Namespace-adoption (§5/§6/T5) and disk-headroom (§3/T4) preflight, both fail-closed, before any snapshot/lock/DDL. */
620
+ async function runPreflightChecks(kernel, dbPath, decl, recoverable, checkHeadroom) {
621
+ const adoption = await checkNamespaceAdoption({ db: kernel, pluginId: decl.pluginId, provenance: decl.provenance });
622
+ if (!adoption.allowed) {
623
+ return { ok: false, error: { code: "IDENTITY_ADOPTION_REQUIRES_CONSENT", message: adoption.reason } };
624
+ }
625
+ // Headroom is for the snapshot file, so only a recoverable (file-backed SQLite) database needs it.
626
+ // `checkDiskHeadroom` itself also no-ops to `ok: true` for an in-memory `dbPath` (BUG FIX 2026-07-28).
627
+ if (!recoverable)
628
+ return { ok: true };
629
+ const headroom = checkHeadroom({ dbPath });
630
+ if (!headroom.ok) {
631
+ return {
632
+ ok: false,
633
+ error: {
634
+ code: "INSUFFICIENT_DISK_HEADROOM",
635
+ message: `dataModule declare refused: needs ~${headroom.requiredBytes} bytes free, only ${headroom.freeBytes ?? "unknown"} available`,
636
+ },
637
+ };
638
+ }
639
+ return { ok: true };
640
+ }
641
+ /**
642
+ * Opens the phase journal only when there's a real file behind `snapshotPath` to recover to — an
643
+ * in-memory db has no next boot to recover at (see this file's header comment), so `journalId`
644
+ * stays null and every phase transition below becomes a no-op for that case.
645
+ */
646
+ async function openJournalIfFileBacked(kernel, pluginId, snapshotPath) {
647
+ if (snapshotPath === null)
648
+ return null;
649
+ await ensureMigrationJournal({ store: kernel });
650
+ return beginJournalEntry({ db: kernel, pluginId, snapshotPath });
651
+ }
652
+ /** No-ops when there is no journal entry to advance (in-memory `dbPath` case). */
653
+ async function advancePhaseIfJournaled(kernel, journalId, phase) {
654
+ if (journalId === null)
655
+ return;
656
+ await advanceJournalPhase({ db: kernel, id: journalId, phase });
657
+ }
658
+ /**
659
+ * No-ops when there is no journal entry to advance (in-memory `dbPath` case, matching
660
+ * `advancePhaseIfJournaled`'s own guard) — but writes WITHOUT checkpointing, for use strictly
661
+ * inside an already-open kernel transaction on the same connection (see `migration-journal.ts`'s
662
+ * `stageJournalPhase` and this file's header comment, POST-COMMIT DATA-LOSS WINDOW, for why a
663
+ * checkpoint cannot run there).
664
+ */
665
+ async function stagePhaseIfJournaled(kernel, journalId, phase) {
666
+ if (journalId === null)
667
+ return;
668
+ await stageJournalPhase({ db: kernel, id: journalId, phase });
669
+ }
670
+ /** Runs one `CREATE INDEX` and records it. Shared by the create-table path and the add-index alter path. */
671
+ async function applyIndexAdd(kernel, pluginId, fqTableName, idx, snapshotPath, at) {
672
+ const { indexName, sql: createDdl } = indexSql(fqTableName, idx);
673
+ await executeDdl(kernel, createDdl);
674
+ await recordMigration(kernel, pluginId, indexName, createDdl, snapshotPath, at);
675
+ }
676
+ /**
677
+ * Drops then recreates one index whose live shape no longer matches its declaration (this file's
678
+ * header comment, INDEX-LEVEL RECONCILIATION) — two DDL statements, both recorded, both inside the
679
+ * caller's single transaction so either one failing rolls both back together with everything else.
680
+ */
681
+ async function applyIndexRecreate(kernel, pluginId, fqTableName, idx, snapshotPath, at) {
682
+ const { indexName } = indexSql(fqTableName, idx);
683
+ const dropDdl = `DROP INDEX "${indexName}"`;
684
+ await executeDdl(kernel, dropDdl);
685
+ await recordMigration(kernel, pluginId, indexName, dropDdl, snapshotPath, at);
686
+ await applyIndexAdd(kernel, pluginId, fqTableName, idx, snapshotPath, at);
687
+ }
688
+ /** Creates one brand-new table and its declared indexes, inside the caller's transaction. Returns the fully-qualified name created. */
689
+ async function applyTableCreate(kernel, pluginId, table, snapshotPath, at) {
690
+ const name = fqName(pluginId, table.name);
691
+ // No IF NOT EXISTS: a within-call duplicate is a malformed manifest → fail → roll back.
692
+ const ddl = `CREATE TABLE "${name}" (${table.columns.map((col) => columnSql(kernel, col)).join(", ")})`;
693
+ await executeDdl(kernel, ddl);
694
+ await recordMigration(kernel, pluginId, name, ddl, snapshotPath, at);
695
+ for (const idx of table.indexes ?? [])
696
+ await applyIndexAdd(kernel, pluginId, name, idx, snapshotPath, at);
697
+ return name;
698
+ }
699
+ /** Applies one already-existing table's queued column additions and index add/recreate, inside the caller's transaction. */
700
+ async function applyTableAlteration(kernel, pluginId, alteration, snapshotPath, at) {
701
+ for (const col of alteration.columnsToAdd) {
702
+ const ddl = `ALTER TABLE "${alteration.fqTableName}" ADD COLUMN ${columnSql(kernel, col)}`;
703
+ await executeDdl(kernel, ddl);
704
+ await recordMigration(kernel, pluginId, alteration.fqTableName, ddl, snapshotPath, at);
705
+ }
706
+ for (const idx of alteration.indexesToRecreate)
707
+ await applyIndexRecreate(kernel, pluginId, alteration.fqTableName, idx, snapshotPath, at);
708
+ for (const idx of alteration.indexesToAdd)
709
+ await applyIndexAdd(kernel, pluginId, alteration.fqTableName, idx, snapshotPath, at);
710
+ }
711
+ /** Completes housekeeping after the DDL and its COMMITTED journal marker are durable. */
712
+ async function finishCommittedMigration({ kernel, journalId, snapshotPath }, _optional = {}) {
713
+ // The transaction already committed the DDL AND the journal's "COMMITTED" marker
714
+ // atomically and durably (SQLite's own WAL commit) — recovery already reads this attempt
715
+ // correctly even if nothing below this line ever runs. What follows is housekeeping only:
716
+ // `advancePhaseIfJournaled` re-writes the (already correct) row purely to force the WAL→main-file
717
+ // checkpoint `stagePhaseIfJournaled` could not request from inside the open transaction (see
718
+ // migration-journal.ts); `discardCommittedSnapshot` deletes a snapshot the never-brick
719
+ // guarantee no longer needs (see the inline comment on `discardCommittedSnapshot`). Neither can
720
+ // undo a result that is already correct, so neither failing here is reported as a migration
721
+ // failure — matching `discardCommittedSnapshot`'s own "must not turn a successful migration into
722
+ // a reported failure" contract.
723
+ try {
724
+ await advancePhaseIfJournaled(kernel, journalId, "COMMITTED");
725
+ // No-ops when no snapshot file was ever written (in-memory `dbPath` case) — nothing to discard.
726
+ if (snapshotPath === null)
727
+ return;
728
+ await discardCommittedSnapshot({ snapshotPath });
729
+ }
730
+ catch {
731
+ // Best-effort only — see the comment above. The migration itself already succeeded.
732
+ }
733
+ }
734
+ /**
735
+ * Declare (reconcile) a plugin's tables. Core snapshots first, then runs the DDL transactionally.
736
+ *
737
+ * `db` is the storage kernel (or a SQLite connection, bridged to its kernel). `dbPath` names the
738
+ * SQLite file behind it, for the snapshot; it is ignored for a Postgres/PGlite kernel.
739
+ * `checkHeadroom` replaces only disk measurement; the existing disk-headroom adapter is the default.
740
+ *
741
+ * @agent-note `dbPath` must name the file behind `db`. `":memory:"`, `""` or a memory URI for a
742
+ * file-backed database skips the snapshot, journal and headroom check with no error. Another
743
+ * file's path still snapshots `db`, but beside that file, and sizes headroom from that file.
744
+ * `decl.provenance` is checked against the stored identity row; see {@link PluginProvenance}.
745
+ */
746
+ export async function declareDataModule(required, { checkHeadroom = ({ dbPath }, _optional = {}) => checkDiskHeadroom({ dbPath }) } = {}) {
747
+ const { dbPath, decl } = required;
748
+ const kernel = pluginKernel({ store: required.db });
749
+ let plan;
750
+ try {
751
+ // Validate entirely before any I/O (§5 namespace + column shape + §3/T6 tier), then diff
752
+ // declared-state against live-state (§2) — both table presence AND, for a table that already
753
+ // exists, its declared columns against its live columns (this file's header comment).
754
+ validate(decl);
755
+ kernel.require("transactionalDdl");
756
+ const fq = decl.tables.map((t) => fqName(decl.pluginId, t.name));
757
+ const existing = await existingTables(kernel, fq);
758
+ plan = await planReconciliation(kernel, decl, existing);
759
+ }
760
+ catch (err) {
761
+ const e = err;
762
+ return { ok: false, created: [], altered: [], snapshotPath: null, error: { code: e.code, message: e.message } };
763
+ }
764
+ if (plan.toCreate.length + plan.toAlter.length === 0) {
765
+ return { ok: true, created: [], altered: [], snapshotPath: null }; // idempotent no-op — nothing to snapshot
766
+ }
767
+ // Snapshot + journal exist for next-boot restore of a whole SQLite file (this file's header,
768
+ // STORAGE KERNEL): nothing to restore for an in-memory db or a Postgres/PGlite kernel.
769
+ // The snapshot, its boot restore and the headroom check bind to the file this connection has open,
770
+ // not to the named path. Identity is the filesystem's (dev, ino): two paths (a second bind mount,
771
+ // a hard link) can name one file. A path naming another file warns and never blocks the install.
772
+ let openDbPath = dbPath;
773
+ if (kernel.dialect === "sqlite" && !isInMemoryDbPath({ dbPath })) {
774
+ const [main] = await kernel.query(sql `SELECT file FROM pragma_database_list WHERE name = 'main'`);
775
+ openDbPath = main?.file || ":memory:";
776
+ const named = statSync(dbPath, { throwIfNoEntry: false });
777
+ const open = main?.file ? statSync(main.file, { throwIfNoEntry: false }) : undefined;
778
+ if (!named || !open || named.dev !== open.dev || named.ino !== open.ino) {
779
+ console.warn(`[data-module] ${decl.pluginId}: ${dbPath} is not the database this connection has open (${main?.file || "an in-memory database"}). Its tables are installed in the open database, and the safety snapshot and disk-space check use it too. Fix the configured database path.`);
780
+ }
781
+ }
782
+ const recoverable = kernel.dialect === "sqlite" && !isInMemoryDbPath({ dbPath: openDbPath });
783
+ const preflight = await runPreflightChecks(kernel, openDbPath, decl, recoverable, checkHeadroom);
784
+ if (!preflight.ok) {
785
+ return { ok: false, created: [], altered: [], snapshotPath: null, error: preflight.error };
786
+ }
787
+ // §4 — snapshot the WHOLE db BEFORE any DDL. This is the never-brick anchor.
788
+ // `snapshotDb` returns `null` for an in-memory `dbPath` (BUG FIX 2026-07-28, see `snapshot.ts`) —
789
+ // no file was ever written, so there is nothing to journal a recovery pointer to.
790
+ const snapshotPath = recoverable ? await snapshotDb({ db: kernel, dbPath: openDbPath, label: decl.pluginId }) : null;
791
+ // The phase-journal (§2/T3) exists solely to let `migration-recovery.ts` restore a crash-
792
+ // interrupted attempt at NEXT BOOT. An in-memory db has no next boot — the whole database
793
+ // vanishes with the process — so there is nothing for the journal to ever recover, and
794
+ // `_plugin_migration_journal.snapshot_path` is `NOT NULL` (see `migration-journal.ts`) and could
795
+ // not hold a null `snapshotPath` even if we tried. `journalId` stays `null` and every phase
796
+ // transition below is then a no-op for this case; the transaction's own same-process rollback
797
+ // (§9, the only failure mode a same-process in-memory db can ever hit) is unaffected and remains
798
+ // the complete safety net.
799
+ const journalId = await openJournalIfFileBacked(kernel, decl.pluginId, snapshotPath);
800
+ const created = [];
801
+ const altered = [];
802
+ try {
803
+ await advancePhaseIfJournaled(kernel, journalId, "DDL_IN_PROGRESS");
804
+ // One transaction for ALL DDL — new tables, column additions, and index add/recreate on
805
+ // existing tables — PLUS the post-DDL verification AND the journal's own COMMITTED write (this
806
+ // file's header comment, POST-COMMIT DATA-LOSS WINDOW). Folding all four into one atomic unit
807
+ // is what makes "the DDL committed" and "the journal says COMMITTED" the same fact: either this
808
+ // whole callback returns and every one of those things is durably true together, or it throws
809
+ // and the kernel rolls every one of them back together (§9).
810
+ await kernel.transaction(async () => {
811
+ await ensureJournal(kernel);
812
+ const at = Date.now();
813
+ for (const table of plan.toCreate)
814
+ created.push(await applyTableCreate(kernel, decl.pluginId, table, snapshotPath, at));
815
+ for (const alteration of plan.toAlter) {
816
+ await applyTableAlteration(kernel, decl.pluginId, alteration, snapshotPath, at);
817
+ altered.push(alteration.fqTableName);
818
+ }
819
+ const problems = await verifyPostDdl(kernel, decl, plan);
820
+ if (problems.length > 0) {
821
+ throw new Error(`post-DDL verification failed: ${problems.join(", ")} not found after DDL`);
822
+ }
823
+ await stagePhaseIfJournaled(kernel, journalId, "COMMITTED");
824
+ });
825
+ }
826
+ catch (err) {
827
+ // `kernel.transaction()` above threw — DDL, verification, and the in-transaction "COMMITTED" write
828
+ // are now one atomic unit, so the transaction's own rollback really did undo ALL of them; the
829
+ // live db is unchanged and working (same-process, catchable-failure case — no restore needed,
830
+ // restore only ever runs at next-boot recovery for a CRASH, see migration-recovery.ts).
831
+ // `ROLLED_BACK` is therefore always truthful here now (this file's header comment, POST-COMMIT
832
+ // DATA-LOSS WINDOW) — there is no remaining case where this catch fires with the DDL actually
833
+ // live. The snapshot remains as the named recovery point (§9) for operator forensics; for an
834
+ // in-memory db, `snapshotPath`/`journalId` are both null (see above) — the same-process
835
+ // rollback just performed IS the full recovery, no crash-recovery boot path can ever exist for
836
+ // `:memory:` to need one.
837
+ await advancePhaseIfJournaled(kernel, journalId, "ROLLED_BACK");
838
+ const e = err;
839
+ return {
840
+ ok: false,
841
+ created: [],
842
+ altered: [],
843
+ snapshotPath,
844
+ recoveryPoint: snapshotPath ?? undefined,
845
+ error: { code: "DDL_FAILED", message: e.message },
846
+ };
847
+ }
848
+ await finishCommittedMigration({ kernel, journalId, snapshotPath });
849
+ return { ok: true, created, altered, snapshotPath };
850
+ }
851
+ //# sourceMappingURL=data-module.js.map