@jini-ai/db 0.7.3-next.2 → 0.7.4

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.
Files changed (101) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +66 -2
  3. package/dist/core/ports.d.ts +2 -2
  4. package/dist/core/ports.js +2 -2
  5. package/dist/data-modules/data-module.d.ts +2 -46
  6. package/dist/data-modules/plugin-identity.d.ts +2 -11
  7. package/dist/data-modules/snapshot.d.ts +5 -3
  8. package/dist/data-modules/snapshot.js +5 -3
  9. package/dist/events/change-set-repo.sql.d.ts +18 -5
  10. package/dist/events/change-set-repo.sql.js +25 -8
  11. package/dist/events/index.d.ts +1 -1
  12. package/dist/events/outbox-repo.sql.d.ts +26 -1
  13. package/dist/events/outbox-repo.sql.js +36 -2
  14. package/dist/events/repo.rows.d.ts +22 -4
  15. package/dist/events/repo.rows.js +32 -4
  16. package/dist/kernel/idle-turn.d.ts +62 -0
  17. package/dist/kernel/idle-turn.js +32 -0
  18. package/dist/kernel/index.d.ts +1 -0
  19. package/dist/kernel/index.js +1 -0
  20. package/dist/kernel/kernel-core.js +28 -0
  21. package/dist/kernel/schema-scope.js +2 -0
  22. package/dist/kernel/sqlite/driver.js +2 -0
  23. package/dist/kernel/sqlite/index.d.ts +1 -1
  24. package/dist/kernel/sqlite/index.js +1 -1
  25. package/dist/kernel/sqlite/ops.d.ts +61 -0
  26. package/dist/kernel/sqlite/ops.js +82 -0
  27. package/dist/kernel/turn-lock.d.ts +2 -0
  28. package/dist/kernel/turn-lock.js +7 -0
  29. package/dist/migrate/runner.d.ts +3 -3
  30. package/dist/migrate/runner.js +4 -1
  31. package/dist/owner-store/index.js +1 -1
  32. package/dist/pglite/copy-source.d.ts +45 -0
  33. package/dist/pglite/copy-source.js +36 -0
  34. package/dist/pglite/index.d.ts +1 -0
  35. package/dist/pglite/index.js +1 -0
  36. package/dist/react/recovery/Recovery.d.ts +205 -0
  37. package/dist/react/recovery/Recovery.js +141 -0
  38. package/dist/react/recovery/Recovery.restore-steps.d.ts +10 -0
  39. package/dist/react/recovery/Recovery.restore-steps.js +71 -0
  40. package/dist/recovery/agent-tools.d.ts +33 -0
  41. package/dist/recovery/agent-tools.js +166 -0
  42. package/dist/recovery/drift.d.ts +47 -0
  43. package/dist/recovery/drift.js +51 -0
  44. package/dist/recovery/journal-kernel.d.ts +80 -0
  45. package/dist/recovery/journal-kernel.js +40 -0
  46. package/dist/recovery/journal-repo.sql.d.ts +154 -0
  47. package/dist/recovery/journal-repo.sql.js +303 -0
  48. package/dist/recovery/journal-schema.d.ts +37 -0
  49. package/dist/recovery/journal-schema.js +110 -0
  50. package/dist/recovery/migrate-forward-hooks.d.ts +2 -1
  51. package/dist/recovery/migrate-forward-hooks.js +3 -3
  52. package/dist/recovery/operation-lock.d.ts +2 -17
  53. package/dist/recovery/reconcile-interrupted-migration.d.ts +2 -5
  54. package/dist/recovery/reconcile-interrupted-migration.js +0 -30
  55. package/dist/recovery/restore-hooks.d.ts +4 -0
  56. package/dist/recovery/restore-hooks.js +1 -1
  57. package/dist/recovery/tool-registrations.d.ts +175 -0
  58. package/dist/recovery/tool-registrations.js +295 -0
  59. package/dist/site/repo.memory.d.ts +149 -0
  60. package/dist/site/repo.memory.js +162 -0
  61. package/dist/site/tool-registrations.d.ts +130 -0
  62. package/dist/site/tool-registrations.js +184 -0
  63. package/dist/sqlite/backup-policy.d.ts +14 -0
  64. package/dist/sqlite/backup-policy.js +47 -3
  65. package/dist/sqlite/compaction-steps.d.ts +43 -0
  66. package/dist/sqlite/compaction-steps.js +74 -0
  67. package/dist/sqlite/compaction.d.ts +63 -0
  68. package/dist/sqlite/compaction.js +263 -0
  69. package/dist/sqlite/db-ops.js +10 -11
  70. package/dist/sqlite/index.d.ts +2 -1
  71. package/dist/sqlite/index.js +2 -1
  72. package/dist/sqlite/open.d.ts +2 -1
  73. package/dist/sqlite/open.js +14 -4
  74. package/dist/tools/index.d.ts +2 -0
  75. package/dist/tools/index.js +2 -0
  76. package/dist/tools/plan-store.d.ts +1 -1
  77. package/dist/tools/plan-store.js +10 -6
  78. package/dist/tools/read-tools.d.ts +1 -1
  79. package/dist/tools/site-db-messages.d.ts +10 -0
  80. package/dist/tools/site-db-messages.js +23 -0
  81. package/dist/tools/site-transfer-messages.d.ts +9 -0
  82. package/dist/tools/site-transfer-messages.js +20 -0
  83. package/dist/transfer/confirmation-ui.d.ts +19 -0
  84. package/dist/transfer/confirmation-ui.js +39 -0
  85. package/dist/transfer/copy-engine.js +11 -11
  86. package/dist/transfer/copy-order.js +1 -3
  87. package/dist/transfer/destination-store.d.ts +83 -0
  88. package/dist/transfer/destination-store.js +82 -0
  89. package/dist/transfer/index.d.ts +2 -0
  90. package/dist/transfer/index.js +2 -0
  91. package/dist/transfer/internal-ddl.d.ts +6 -2
  92. package/dist/transfer/internal-ddl.js +15 -15
  93. package/dist/transfer/postgres-ddl.js +2 -2
  94. package/dist/transfer/schema-catalog.d.ts +148 -0
  95. package/dist/transfer/schema-catalog.js +141 -0
  96. package/dist/transfer/sqlite-backup.d.ts +27 -0
  97. package/dist/transfer/sqlite-backup.js +31 -0
  98. package/dist/transfer/table-catalog.js +1 -0
  99. package/dist/watermark/kernel.d.ts +64 -0
  100. package/dist/watermark/kernel.js +45 -0
  101. package/package.json +107 -9
@@ -0,0 +1,74 @@
1
+ /**
2
+ * WAL-consistent copy (`VACUUM INTO`) to `<target>.partial`, checked, then durably renamed into place.
3
+ * A copy that fails its check is removed (it was never published) and the error propagates.
4
+ * @complexity O(database bytes).
5
+ */
6
+ export async function copySqliteFile({ db, targetPath, io, open }) {
7
+ const partial = `${targetPath}.partial`;
8
+ await io.removeOwn(partial);
9
+ try {
10
+ // Same statement as kernel/sqlite/ops.ts `copySqliteInto`, which this connection-only entry must
11
+ // not import (it loads the kernel). Bound, so a quote in a folder name never becomes SQL.
12
+ db.prepare('VACUUM INTO ?').run(partial);
13
+ verifyCopy({ copyPath: partial, open });
14
+ }
15
+ catch (error) {
16
+ await io.removeOwn(partial);
17
+ throw error;
18
+ }
19
+ await io.publish(partial, targetPath);
20
+ }
21
+ /** Opens the copy read-only and requires `integrity_check` = ok. @throws when the copy is not whole. */
22
+ export function verifyCopy({ copyPath, open }) {
23
+ if (!copyIsWhole({ copyPath, open }))
24
+ throw new Error('The recovery copy made before compaction did not pass its check; nothing was changed.');
25
+ }
26
+ /**
27
+ * True only when the copy opens read-only and `integrity_check` answers ok. A file that is not a database
28
+ * at all (a torn or foreign file) answers false rather than throwing; anything else propagates.
29
+ */
30
+ export function copyIsWhole({ copyPath, open }) {
31
+ let copy;
32
+ try {
33
+ copy = open(copyPath, { readonly: true, fileMustExist: true });
34
+ const [result] = copy.pragma('integrity_check');
35
+ return result?.integrity_check === 'ok';
36
+ }
37
+ catch (error) {
38
+ if (isNotADatabase(error))
39
+ return false;
40
+ throw error;
41
+ }
42
+ finally {
43
+ copy?.close();
44
+ }
45
+ }
46
+ function isNotADatabase(error) {
47
+ const code = error?.code;
48
+ return code === 'SQLITE_NOTADB' || code === 'SQLITE_CORRUPT';
49
+ }
50
+ /**
51
+ * The rewrite and its check, in `compactAndVerify`'s order: VACUUM, WAL switch, TRUNCATE checkpoint
52
+ * (busy must be 0), then integrity_check, then `auto_vacuum` must read back as 2.
53
+ * @returns undefined when verified; otherwise the plain reason recorded in the marker.
54
+ */
55
+ export function verifyRewrite({ db, alreadyConverted }) {
56
+ if (!alreadyConverted) {
57
+ // auto_vacuum only changes through a full VACUUM, and not while the file is in WAL mode.
58
+ db.exec('PRAGMA journal_mode = DELETE; PRAGMA auto_vacuum = INCREMENTAL; VACUUM;');
59
+ }
60
+ // WAL switch and checkpoint BEFORE integrity_check (see kernel/sqlite/ops.ts: the reverse order left a lock).
61
+ db.pragma('journal_mode = WAL');
62
+ const [checkpoint] = db.pragma('wal_checkpoint(TRUNCATE)');
63
+ if (checkpoint === undefined || checkpoint.busy !== 0)
64
+ return `final WAL checkpoint reported busy=${checkpoint?.busy}`;
65
+ // SQLite integrity_check returns at least one row: "ok" or corruption details.
66
+ const [{ integrity_check: integrity }] = db.pragma('integrity_check');
67
+ if (integrity !== 'ok')
68
+ return `integrity_check: ${integrity}`;
69
+ const mode = db.pragma('auto_vacuum', { simple: true });
70
+ if (mode !== 2)
71
+ return `auto_vacuum reads ${String(mode)} after the rewrite`;
72
+ return undefined;
73
+ }
74
+ //# sourceMappingURL=compaction-steps.js.map
@@ -0,0 +1,63 @@
1
+ import type { SqliteCompactionFs, SqliteCompactionMarkerStore, SqliteConversionOutcome, SqliteDb, SqliteVacuumStepOutcome } from '@jini-ai/core/contracts/storage';
2
+ import type { StoppedSqliteOpener } from './stopped.js';
3
+ export declare const COMPACTION_MESSAGES: {
4
+ readonly running: "This website is running; compaction needs it stopped.";
5
+ readonly busy: "This website's database is busy; compaction will try again later.";
6
+ readonly needsAttention: "This website's database did not pass its check after compaction. The copy made before compaction was kept; nothing was deleted.";
7
+ readonly notConverted: "This website's database has not been prepared for compaction yet.";
8
+ readonly nothingToReclaim: "This website's database has little free space to reclaim.";
9
+ };
10
+ /** `pre-compact-<db name>-<ms>.db` beside the database: apart from `pre-migrations-*` rotation and per DB. */
11
+ export declare function compactionRecoveryCopyPath({ filePath, now }: {
12
+ filePath: string;
13
+ now: number;
14
+ }, _optional?: Record<string, never>): string;
15
+ type ConvertRequired = {
16
+ filePath: string;
17
+ open: StoppedSqliteOpener;
18
+ marker: SqliteCompactionMarkerStore;
19
+ holdsRunningLease: () => boolean;
20
+ fs: SqliteCompactionFs;
21
+ now: () => number;
22
+ };
23
+ type ConvertOptional = {
24
+ recoveryCopyPath?: string;
25
+ reserveBytes?: number;
26
+ };
27
+ /**
28
+ * One-time conversion of a stopped database file to `auto_vacuum = INCREMENTAL`.
29
+ * Every refusal before the rewrite leaves the file byte-for-byte unchanged. A failed check after the
30
+ * rewrite is recorded as `needs-attention` and is never retried automatically.
31
+ * @param required.holdsRunningLease the host's running-lease probe (the same lease `serve` takes); asked at
32
+ * entry, after admission and before the rewrite, so a lease lost mid-run stops before any rewrite.
33
+ * @param required.fs the host's filesystem port, including the folder SQLite builds its temp database in.
34
+ * @param _optional.reserveBytes headroom per filesystem on top of the copy, journal and temp budgets (64 MiB).
35
+ * @throws on a handle already inside a transaction; a recovery copy path that is the database or an
36
+ * existing file; marker-store and fs errors.
37
+ * @complexity O(database bytes): one copy, one rewrite, two integrity checks.
38
+ */
39
+ export declare function convertToIncrementalVacuum(required: ConvertRequired, _optional?: ConvertOptional): Promise<SqliteConversionOutcome>;
40
+ type StepRequired = {
41
+ db: SqliteDb;
42
+ filePath: string;
43
+ marker: SqliteCompactionMarkerStore;
44
+ fs: SqliteCompactionFs;
45
+ mono: () => number;
46
+ };
47
+ type StepOptional = {
48
+ maxPages?: number;
49
+ minFreeRatio?: number;
50
+ minFreeBytes?: number;
51
+ busyTimeoutMs?: number;
52
+ };
53
+ /**
54
+ * One bounded `incremental_vacuum(maxPages)` on the host's coordinated handle. Runs only for a file
55
+ * converted under its current identity; skips when free space is below BOTH thresholds; a busy or
56
+ * locked database defers to the next pass. The handle's own busy timeout is restored afterwards.
57
+ * @param required.mono the host's monotonic clock, for `elapsedMs`.
58
+ * @throws when called inside a transaction (incremental_vacuum would join it).
59
+ * @complexity O(maxPages) page moves; two metadata reads before and after.
60
+ */
61
+ export declare function incrementalVacuumStep(required: StepRequired, _optional?: StepOptional): Promise<SqliteVacuumStepOutcome>;
62
+ export {};
63
+ //# sourceMappingURL=compaction.d.ts.map
@@ -0,0 +1,263 @@
1
+ /**
2
+ * @module compaction
3
+ *
4
+ * Reclaiming SQLite free pages without a serving-time `VACUUM`, in two separate operations:
5
+ *
6
+ * 1. `convertToIncrementalVacuum` — once per file, on a STOPPED database. Never a migration: the
7
+ * migration runner wraps each step in a transaction and `VACUUM` cannot run inside one. Order:
8
+ * running lease → SQLite exclusive admission (proves no other connection, before any byte changes)
9
+ * → lease again → disk budget → `copying` marker → verified, durably published recovery copy →
10
+ * `copied` → lease again → `rewriting` → rewrite → check → `converted(dev:ino)`.
11
+ * 2. `incrementalVacuumStep` — the bounded daily step on the host's own coordinated handle; it runs
12
+ * only for a file whose marker says it was converted AND whose `auto_vacuum` reads 2.
13
+ *
14
+ * The host owns the marker store, the clocks and every filesystem call (ports from
15
+ * `@jini-ai/core/contracts/storage`); this module ships no Node filesystem default. The `./sqlite` entry
16
+ * stays connection-only (no Kysely), so the rewrite check mirrors `kernel/sqlite/ops.ts`'s
17
+ * `compactAndVerify` order instead of building a kernel to call it.
18
+ */
19
+ import path from 'node:path';
20
+ import { copyIsWhole, copySqliteFile, verifyCopy, verifyRewrite } from './compaction-steps.js';
21
+ const MiB = 1024 * 1024;
22
+ const AUTO_VACUUM_INCREMENTAL = 2;
23
+ export const COMPACTION_MESSAGES = {
24
+ running: 'This website is running; compaction needs it stopped.',
25
+ busy: "This website's database is busy; compaction will try again later.",
26
+ needsAttention: "This website's database did not pass its check after compaction. The copy made before compaction was kept; nothing was deleted.",
27
+ notConverted: "This website's database has not been prepared for compaction yet.",
28
+ nothingToReclaim: "This website's database has little free space to reclaim.",
29
+ };
30
+ const IN_TRANSACTION = 'Compaction must run on its own connection, outside any migration or transaction.';
31
+ /** `pre-compact-<db name>-<ms>.db` beside the database: apart from `pre-migrations-*` rotation and per DB. */
32
+ export function compactionRecoveryCopyPath({ filePath, now }, _optional = {}) {
33
+ const name = path.basename(filePath, path.extname(filePath));
34
+ return path.join(path.dirname(filePath), `pre-compact-${name}-${now}.db`);
35
+ }
36
+ const deferredRunning = () => ({ status: 'deferred', reason: 'running', message: COMPACTION_MESSAGES.running });
37
+ /**
38
+ * One-time conversion of a stopped database file to `auto_vacuum = INCREMENTAL`.
39
+ * Every refusal before the rewrite leaves the file byte-for-byte unchanged. A failed check after the
40
+ * rewrite is recorded as `needs-attention` and is never retried automatically.
41
+ * @param required.holdsRunningLease the host's running-lease probe (the same lease `serve` takes); asked at
42
+ * entry, after admission and before the rewrite, so a lease lost mid-run stops before any rewrite.
43
+ * @param required.fs the host's filesystem port, including the folder SQLite builds its temp database in.
44
+ * @param _optional.reserveBytes headroom per filesystem on top of the copy, journal and temp budgets (64 MiB).
45
+ * @throws on a handle already inside a transaction; a recovery copy path that is the database or an
46
+ * existing file; marker-store and fs errors.
47
+ * @complexity O(database bytes): one copy, one rewrite, two integrity checks.
48
+ */
49
+ export async function convertToIncrementalVacuum(required, _optional = {}) {
50
+ const { reserveBytes = 64 * MiB } = _optional;
51
+ if (!required.holdsRunningLease())
52
+ return deferredRunning();
53
+ const prior = await required.marker.read();
54
+ if (prior?.state === 'needs-attention')
55
+ return { status: 'deferred', reason: 'needs-attention', message: COMPACTION_MESSAGES.needsAttention, recoveryCopyPath: prior.recoveryCopyPath };
56
+ const recoveryCopyPath = await pickRecoveryCopy({ filePath: required.filePath, prior, requested: _optional.recoveryCopyPath, io: required.fs, now: required.now });
57
+ const db = admit({ filePath: required.filePath, open: required.open });
58
+ if (db === undefined)
59
+ return { status: 'deferred', reason: 'busy', message: COMPACTION_MESSAGES.busy };
60
+ try {
61
+ if (!required.holdsRunningLease())
62
+ return deferredRunning();
63
+ return await convertAdmitted({ ...required, db, prior, recoveryCopyPath, reserveBytes });
64
+ }
65
+ finally {
66
+ db.close();
67
+ }
68
+ }
69
+ /**
70
+ * Why BOTH a verified copy and exclusive admission: admission proves no other connection (a server, a
71
+ * reader pinning the WAL, a writer) can see or change the file while it is rewritten, so the copy and the
72
+ * rewrite describe the same bytes; the verified, published copy is the way back if the rewrite itself is
73
+ * damaged by a crash or a bug. Admission without a copy leaves no way back; a copy without admission can
74
+ * miss a concurrent writer's commit, so restoring it would silently lose data.
75
+ */
76
+ async function convertAdmitted(job) {
77
+ if (await isAlreadyConverted(job))
78
+ return { status: 'already-converted', message: "This website's database is already prepared for compaction." };
79
+ const before = await measure({ db: job.db, filePath: job.filePath, io: job.fs });
80
+ const shortfall = await budget({ ...job, bytes: before.mainBytes + before.walBytes });
81
+ if (shortfall !== undefined)
82
+ return { status: 'deferred', reason: 'low-disk', message: shortfall };
83
+ await copy(job);
84
+ if (!job.holdsRunningLease())
85
+ return deferredRunning();
86
+ const failure = await rewrite(job);
87
+ if (failure !== undefined)
88
+ return { status: 'deferred', reason: 'needs-attention', message: COMPACTION_MESSAGES.needsAttention, recoveryCopyPath: job.recoveryCopyPath };
89
+ return mark(job, before);
90
+ }
91
+ async function isAlreadyConverted({ db, prior, filePath, fs }) {
92
+ if (db.pragma('auto_vacuum', { simple: true }) !== AUTO_VACUUM_INCREMENTAL || prior?.state !== 'converted')
93
+ return false;
94
+ return prior.identity === await fs.identity(filePath);
95
+ }
96
+ /** Reuse the copy an interrupted attempt named (a `copying` path even if not yet written); otherwise a new, unused path. */
97
+ async function pickRecoveryCopy({ filePath, prior, requested, io, now }) {
98
+ if (prior?.state === 'copying')
99
+ return prior.recoveryCopyPath;
100
+ if (prior !== undefined && prior.state !== 'converted' && await io.exists(prior.recoveryCopyPath))
101
+ return prior.recoveryCopyPath;
102
+ const chosen = requested ?? compactionRecoveryCopyPath({ filePath, now: now() });
103
+ if (path.resolve(chosen) === path.resolve(filePath) || await io.exists(chosen)) {
104
+ throw new Error('The recovery copy must be a new file next to the database, not the database itself or an existing file.');
105
+ }
106
+ return chosen;
107
+ }
108
+ /**
109
+ * SQLite's exclusive lock is the admission proof: in WAL mode every open connection (an idle one, a
110
+ * reader pinning the WAL, a writer) holds a shared lock, so `BEGIN EXCLUSIVE` under EXCLUSIVE locking
111
+ * mode fails at once with SQLITE_BUSY. Once taken, the lock is held until close, fencing out every
112
+ * other connection for the whole copy + rewrite. Nothing has been written when this refuses.
113
+ * A handle already inside a transaction is a shared one (a migration's): it is refused untouched and NOT
114
+ * closed, because closing it would roll back its owner's transaction.
115
+ */
116
+ function admit({ filePath, open }) {
117
+ const db = open(filePath, { fileMustExist: true, timeout: 0 });
118
+ if (db.inTransaction)
119
+ throw new Error(IN_TRANSACTION);
120
+ try {
121
+ db.exec('PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; ROLLBACK;');
122
+ return db;
123
+ }
124
+ catch (error) {
125
+ db.close();
126
+ if (isBusy(error))
127
+ return undefined;
128
+ throw error;
129
+ }
130
+ }
131
+ function isBusy(error) {
132
+ const code = error?.code;
133
+ return typeof code === 'string' && (code.startsWith('SQLITE_BUSY') || code.startsWith('SQLITE_LOCKED'));
134
+ }
135
+ /**
136
+ * Peak space per distinct filesystem: the new copy (only when none is reusable), the DELETE-mode rollback
137
+ * journal beside the database (up to 1×), and SQLite's temp database for `VACUUM` (1×, in the host's temp
138
+ * folder). Each filesystem touched also keeps `reserveBytes` free.
139
+ */
140
+ async function budget({ filePath, recoveryCopyPath, bytes, reserveBytes, fs: io }) {
141
+ const needs = new Map();
142
+ const add = async (dir, amount) => {
143
+ const device = await io.deviceOf(dir);
144
+ const entry = needs.get(device) ?? { dir, need: reserveBytes };
145
+ needs.set(device, { dir: entry.dir, need: entry.need + amount });
146
+ };
147
+ await add(path.dirname(filePath), bytes);
148
+ await add(path.dirname(recoveryCopyPath), (await io.exists(recoveryCopyPath)) ? 0 : bytes);
149
+ await add(io.tempDirectory(), bytes);
150
+ for (const { dir, need } of needs.values()) {
151
+ const free = await io.freeBytes(dir);
152
+ if (free < need) {
153
+ return `There is not enough free disk space to compact this website's database (needs ${Math.ceil(need / MiB)} MB, ${Math.floor(free / MiB)} MB free). Nothing was changed.`;
154
+ }
155
+ }
156
+ return undefined;
157
+ }
158
+ /**
159
+ * Write-ahead `copying` marker, then `VACUUM INTO` → check → publish, then `copied`. A copy already
160
+ * published under `copied`/`rewriting` must still verify (else throw: nothing is rewritten). One left under
161
+ * `copying` (crash after publish, before `copied`) is reused when whole, otherwise redone at the same path.
162
+ */
163
+ async function copy({ db, prior, recoveryCopyPath, marker, fs: io, open, now }) {
164
+ const named = prior?.recoveryCopyPath === recoveryCopyPath && await io.exists(recoveryCopyPath);
165
+ if (named && prior?.state !== 'copying') {
166
+ verifyCopy({ copyPath: recoveryCopyPath, open });
167
+ return;
168
+ }
169
+ if (named && copyIsWhole({ copyPath: recoveryCopyPath, open })) {
170
+ await marker.write({ state: 'copied', recoveryCopyPath, at: now() });
171
+ return;
172
+ }
173
+ if (named)
174
+ await io.removeOwn(recoveryCopyPath);
175
+ await marker.write({ state: 'copying', recoveryCopyPath, at: now() });
176
+ await copySqliteFile({ db, targetPath: recoveryCopyPath, io, open });
177
+ await marker.write({ state: 'copied', recoveryCopyPath, at: now() });
178
+ }
179
+ /** Records `rewriting`, rewrites and checks. A failed check records `needs-attention` (copy kept) and returns why. */
180
+ async function rewrite({ db, recoveryCopyPath, marker, now }) {
181
+ await marker.write({ state: 'rewriting', recoveryCopyPath, at: now() });
182
+ const failure = verifyRewrite({ db, alreadyConverted: db.pragma('auto_vacuum', { simple: true }) === AUTO_VACUUM_INCREMENTAL });
183
+ if (failure !== undefined)
184
+ await marker.write({ state: 'needs-attention', recoveryCopyPath, at: now(), reason: failure });
185
+ return failure;
186
+ }
187
+ /** Only after `verifyRewrite` passed (integrity ok, `auto_vacuum` reads 2): `converted`, scoped to this file's identity. */
188
+ async function mark({ db, filePath, recoveryCopyPath, marker, fs: io, now }, before) {
189
+ await marker.write({ state: 'converted', recoveryCopyPath, at: now(), identity: await io.identity(filePath) });
190
+ return { status: 'converted', recoveryCopyPath, before, after: await measure({ db, filePath, io }), message: "This website's database is now prepared for compaction." };
191
+ }
192
+ async function measure({ db, filePath, io }) {
193
+ return {
194
+ mainBytes: await io.size(filePath),
195
+ walBytes: await io.size(`${filePath}-wal`),
196
+ freePages: Number(db.pragma('freelist_count', { simple: true })),
197
+ pageSize: Number(db.pragma('page_size', { simple: true })),
198
+ };
199
+ }
200
+ /**
201
+ * One bounded `incremental_vacuum(maxPages)` on the host's coordinated handle. Runs only for a file
202
+ * converted under its current identity; skips when free space is below BOTH thresholds; a busy or
203
+ * locked database defers to the next pass. The handle's own busy timeout is restored afterwards.
204
+ * @param required.mono the host's monotonic clock, for `elapsedMs`.
205
+ * @throws when called inside a transaction (incremental_vacuum would join it).
206
+ * @complexity O(maxPages) page moves; two metadata reads before and after.
207
+ */
208
+ export async function incrementalVacuumStep(required, _optional = {}) {
209
+ const { db, filePath, marker, fs: io, mono } = required;
210
+ if (db.inTransaction)
211
+ throw new Error('incrementalVacuumStep must run outside a transaction.');
212
+ if (!(await isConvertedHere({ db, filePath, marker, io }))) {
213
+ return { status: 'skipped', reason: 'not-converted', message: COMPACTION_MESSAGES.notConverted };
214
+ }
215
+ const before = await measure({ db, filePath, io });
216
+ if (!worthReclaiming({ db, before, ..._optional })) {
217
+ return { status: 'skipped', reason: 'nothing-to-reclaim', message: COMPACTION_MESSAGES.nothingToReclaim, before };
218
+ }
219
+ // The awaits above leave a gap in which a foreign `BEGIN` can open on the shared handle; the
220
+ // vacuum would then join that transaction. Re-check with no await before the pragma.
221
+ if (db.inTransaction)
222
+ return { status: 'skipped', reason: 'busy', message: COMPACTION_MESSAGES.busy, before };
223
+ const started = mono();
224
+ if (!runBoundedVacuum({ db, ..._optional }))
225
+ return { status: 'skipped', reason: 'busy', message: COMPACTION_MESSAGES.busy, before };
226
+ const after = await measure({ db, filePath, io });
227
+ return {
228
+ status: 'reclaimed', before, after, elapsedMs: mono() - started,
229
+ message: `Reclaimed ${before.freePages - after.freePages} free pages. The file shrinks on disk at the next checkpoint; a long-running reader can delay that.`,
230
+ };
231
+ }
232
+ /** Converted under THIS file's identity (a restored or replaced file does not inherit it) and `auto_vacuum` reads 2. */
233
+ async function isConvertedHere({ db, filePath, marker, io }) {
234
+ const recorded = await marker.read();
235
+ if (recorded?.state !== 'converted' || recorded.identity !== await io.identity(filePath))
236
+ return false;
237
+ return db.pragma('auto_vacuum', { simple: true }) === AUTO_VACUUM_INCREMENTAL;
238
+ }
239
+ /** False when there are no free pages, or free space is below BOTH the byte and the ratio threshold. */
240
+ function worthReclaiming({ db, before, minFreeRatio = 0.2, minFreeBytes = 8 * MiB }) {
241
+ if (before.freePages === 0)
242
+ return false;
243
+ const pageCount = Number(db.pragma('page_count', { simple: true }));
244
+ return before.freePages * before.pageSize >= minFreeBytes || before.freePages / pageCount >= minFreeRatio;
245
+ }
246
+ /** False when SQLite reported busy/locked. The handle's prior busy timeout is restored either way. */
247
+ function runBoundedVacuum({ db, maxPages = 2048, busyTimeoutMs = 250 }) {
248
+ const previousTimeout = db.pragma('busy_timeout', { simple: true });
249
+ db.pragma(`busy_timeout = ${Math.max(0, Math.floor(busyTimeoutMs))}`);
250
+ try {
251
+ db.pragma(`incremental_vacuum(${Math.max(1, Math.floor(maxPages))})`);
252
+ return true;
253
+ }
254
+ catch (error) {
255
+ if (!isBusy(error))
256
+ throw error;
257
+ return false;
258
+ }
259
+ finally {
260
+ db.pragma(`busy_timeout = ${Number(previousTimeout)}`);
261
+ }
262
+ }
263
+ //# sourceMappingURL=compaction.js.map
@@ -96,18 +96,17 @@ export class SqliteDbOpsAdapter {
96
96
  * @complexity O(c) metadata operations for c collisions; no database bytes are copied here.
97
97
  */
98
98
  async function reserveRestorePoint(required, _options = {}) {
99
- for (let timestamp = required.timestamp;; timestamp++) {
100
- const artifactRef = path.join(required.targetDir, restorePointFilename({ ...required, timestamp }));
101
- try {
102
- const reservation = await fs.open(artifactRef, 'wx', 0o600);
103
- await reservation.close();
104
- return artifactRef;
105
- }
106
- catch (error) {
107
- if (error instanceof Error && 'code' in error && error.code === 'EEXIST')
108
- continue;
109
- throw error;
99
+ const artifactRef = path.join(required.targetDir, restorePointFilename(required));
100
+ try {
101
+ const reservation = await fs.open(artifactRef, 'wx', 0o600);
102
+ await reservation.close();
103
+ return artifactRef;
104
+ }
105
+ catch (error) {
106
+ if (error instanceof Error && 'code' in error && error.code === 'EEXIST') {
107
+ return reserveRestorePoint({ ...required, timestamp: required.timestamp + 1 });
110
108
  }
109
+ throw error;
111
110
  }
112
111
  }
113
112
  //# sourceMappingURL=db-ops.js.map
@@ -4,7 +4,8 @@ export { SqliteClientError } from "./checked-state.js";
4
4
  export { withSqliteTransaction, type TransactionSession, type Work } from "./transaction.js";
5
5
  export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
6
6
  export { SqliteDbOpsAdapter, type SqliteDbOpsAdapterDeps } from "./db-ops.js";
7
- export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies, type DatabaseCopy } from "./backup-policy.js";
7
+ export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies, selectDatabaseCopiesToPrune, type DatabaseCopy } from "./backup-policy.js";
8
+ export { COMPACTION_MESSAGES, compactionRecoveryCopyPath, convertToIncrementalVacuum, incrementalVacuumStep } from "./compaction.js";
8
9
  export { inspectSqliteDatabase, verifySqliteIntegrity } from "./inspect.js";
9
10
  export { assertSqliteStopped, checkpointStoppedSqliteWal, inspectStoppedSqlite, type StoppedSqliteOpener } from "./stopped.js";
10
11
  export type { DaemonDbTableInfo, DaemonDbStatusReport, DbIntegrityIssueKind, DbIntegrityIssue, DbIntegrityReport, VerifyDbOptions } from "./inspect.js";
@@ -4,7 +4,8 @@ export { SqliteClientError } from "./checked-state.js";
4
4
  export { withSqliteTransaction } from "./transaction.js";
5
5
  export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
6
6
  export { SqliteDbOpsAdapter } from "./db-ops.js";
7
- export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies } from "./backup-policy.js";
7
+ export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies, selectDatabaseCopiesToPrune } from "./backup-policy.js";
8
+ export { COMPACTION_MESSAGES, compactionRecoveryCopyPath, convertToIncrementalVacuum, incrementalVacuumStep } from "./compaction.js";
8
9
  export { inspectSqliteDatabase, verifySqliteIntegrity } from "./inspect.js";
9
10
  export { assertSqliteStopped, checkpointStoppedSqliteWal, inspectStoppedSqlite } from "./stopped.js";
10
11
  //# sourceMappingURL=index.js.map
@@ -49,7 +49,8 @@ export declare const DEFAULT_PRAGMAS: readonly string[];
49
49
  * Opens (or creates) a SQLite database and applies pragmas.
50
50
  *
51
51
  * Returns the exact handle supplied by the injected `open`, preserving its structural type.
52
- * Recovery runs before opening; pragma policy runs immediately afterwards.
52
+ * Recovery runs before opening; pragma policy runs immediately afterwards. A pragma failure
53
+ * closes the partially configured handle; successful calls transfer ownership to the caller.
53
54
  * @throws Any error from the recovery hook, opener, or pragma application.
54
55
  * @complexity O(p) calls for p pragmas; storage costs belong to the injected driver.
55
56
  */
@@ -28,16 +28,26 @@ export const DEFAULT_PRAGMAS = [
28
28
  * Opens (or creates) a SQLite database and applies pragmas.
29
29
  *
30
30
  * Returns the exact handle supplied by the injected `open`, preserving its structural type.
31
- * Recovery runs before opening; pragma policy runs immediately afterwards.
31
+ * Recovery runs before opening; pragma policy runs immediately afterwards. A pragma failure
32
+ * closes the partially configured handle; successful calls transfer ownership to the caller.
32
33
  * @throws Any error from the recovery hook, opener, or pragma application.
33
34
  * @complexity O(p) calls for p pragmas; storage costs belong to the injected driver.
34
35
  */
35
36
  export function openSqliteConnection(required, options = {}) {
36
37
  options.recover?.({ filePath: required.filePath }, {});
37
38
  const connection = required.open({ filePath: required.filePath }, {});
38
- for (const pragma of options.pragmas ?? DEFAULT_PRAGMAS) {
39
- connection.pragma(pragma);
39
+ try {
40
+ for (const pragma of options.pragmas ?? DEFAULT_PRAGMAS)
41
+ connection.pragma(pragma);
42
+ return connection;
43
+ }
44
+ catch (error) {
45
+ // Preserve the setup failure even if cleanup also fails; the caller never received this handle.
46
+ try {
47
+ connection.close();
48
+ }
49
+ catch { /* Best effort: the original setup failure remains actionable. */ }
50
+ throw error;
40
51
  }
41
- return connection;
42
52
  }
43
53
  //# sourceMappingURL=open.js.map
@@ -8,6 +8,8 @@ export * from "./timeline.js";
8
8
  export * from "./restore-points.js";
9
9
  export * from "./plan-store.js";
10
10
  export * from "./destination-port.js";
11
+ export { SITE_DATABASE_MESSAGES } from "./site-db-messages.js";
12
+ export { SITE_TRANSFER_MESSAGES } from "./site-transfer-messages.js";
11
13
  export type { InputReaders } from "./registration.js";
12
14
  export type { TransferSurfacePorts, SurfaceExchange, SurfaceMessage } from "./surface-port.js";
13
15
  //# sourceMappingURL=index.d.ts.map
@@ -8,4 +8,6 @@ export * from "./timeline.js";
8
8
  export * from "./restore-points.js";
9
9
  export * from "./plan-store.js";
10
10
  export * from "./destination-port.js";
11
+ export { SITE_DATABASE_MESSAGES } from "./site-db-messages.js";
12
+ export { SITE_TRANSFER_MESSAGES } from "./site-transfer-messages.js";
11
13
  //# sourceMappingURL=index.js.map
@@ -45,7 +45,7 @@ export declare class DatabaseTransferPlanStore {
45
45
  constructor(_required?: Record<string, never>, optional?: {
46
46
  now?: () => number;
47
47
  });
48
- /** @complexity O(plans held), at most {@link DEFAULT_MAX_PLANS}. */
48
+ /** @complexity O(plans held): at most {@link DEFAULT_MAX_PLANS} per principal, expired ones pruned first. */
49
49
  save(input: {
50
50
  principalId: string;
51
51
  workspaceId: string;
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  const DEFAULT_PLAN_TTL_MS = 10 * 60 * 1000;
3
- /** Each plan holds a whole database snapshot, so only a couple are kept. */
3
+ /** Each plan holds a whole database snapshot, so only a couple are kept per principal. */
4
4
  const DEFAULT_MAX_PLANS = 2;
5
5
  export class DatabaseTransferPlanStore {
6
6
  plans = new Map();
@@ -8,19 +8,23 @@ export class DatabaseTransferPlanStore {
8
8
  constructor(_required = {}, optional = {}) {
9
9
  this.now = optional.now ?? Date.now;
10
10
  }
11
- /** @complexity O(plans held), at most {@link DEFAULT_MAX_PLANS}. */
11
+ /** @complexity O(plans held): at most {@link DEFAULT_MAX_PLANS} per principal, expired ones pruned first. */
12
12
  save(input, _optional = {}) {
13
13
  const nowMs = this.now();
14
14
  for (const [id, plan] of this.plans) {
15
15
  if (plan.expiresAtMs <= nowMs)
16
16
  this.plans.delete(id);
17
17
  }
18
- // Evict oldest-first (a Map iterates in insertion order) until there is room for this plan. The
19
- // former `oldest === undefined` guard is gone: iterating the keys themselves cannot yield a missing one.
20
- for (const id of this.plans.keys()) {
21
- if (this.plans.size < DEFAULT_MAX_PLANS)
18
+ // Evict this principal's own oldest plans first (a Map iterates in insertion order) until there is
19
+ // room. The cap is per principal (B166): a global cap let one user's new plan evict another's.
20
+ let held = [...this.plans.values()].filter(plan => plan.principalId === input.principalId).length;
21
+ for (const [id, plan] of this.plans) {
22
+ if (held < DEFAULT_MAX_PLANS)
22
23
  break;
24
+ if (plan.principalId !== input.principalId)
25
+ continue;
23
26
  this.plans.delete(id);
27
+ held -= 1;
24
28
  }
25
29
  const plan = { ...input.content, planId: randomUUID(), principalId: input.principalId, workspaceId: input.workspaceId, expiresAtMs: nowMs + DEFAULT_PLAN_TTL_MS };
26
30
  this.plans.set(plan.planId, plan);
@@ -12,7 +12,7 @@ export interface DatabasePermissionRequest {
12
12
  }
13
13
  export interface DatabaseReadToolPorts {
14
14
  workspaceId: string;
15
- readers: InputReaders;
15
+ readers: Pick<InputReaders, "isRecord" | "noInput" | "optionalString" | "optionalBoolean"> & Partial<InputReaders>;
16
16
  requirePermission(request: DatabasePermissionRequest): Promise<void>;
17
17
  introspection: {
18
18
  getHealth(): Promise<unknown>;
@@ -0,0 +1,10 @@
1
+ import { type DbMessages } from "../core/messages.js";
2
+ /**
3
+ * @file Site wording for the `@jini-ai/db/tools` database tools. The package defaults speak of "the
4
+ * source"; a host that serves one site has its tools say "this site", and their descriptions are the
5
+ * bytes the host's descriptor snapshot pins from the pre-extraction catalog. The transfer tools' copy
6
+ * lives in `site-transfer-messages.ts`. Specification references (requirement or decision ids) are
7
+ * not part of this profile: a host that cites its own documents in this copy overrides those fields.
8
+ */
9
+ export declare const SITE_DATABASE_MESSAGES: DbMessages;
10
+ //# sourceMappingURL=site-db-messages.d.ts.map
@@ -0,0 +1,23 @@
1
+ import { defaultDbMessages } from "../core/messages.js";
2
+ /**
3
+ * @file Site wording for the `@jini-ai/db/tools` database tools. The package defaults speak of "the
4
+ * source"; a host that serves one site has its tools say "this site", and their descriptions are the
5
+ * bytes the host's descriptor snapshot pins from the pre-extraction catalog. The transfer tools' copy
6
+ * lives in `site-transfer-messages.ts`. Specification references (requirement or decision ids) are
7
+ * not part of this profile: a host that cites its own documents in this copy overrides those fields.
8
+ */
9
+ export const SITE_DATABASE_MESSAGES = {
10
+ ...defaultDbMessages,
11
+ restorePointUnavailable: "no restore-point mechanism is available for this site; the in-product migrate is refused with no attestation override",
12
+ restorePointCostAck: "Explicit cost acknowledgment. Required (must be true) only when this site's restore-point cost class is 'expensive'; ignored when 'cheap'. The call is refused with no override at all when cost class is 'unavailable' (no attestation override).",
13
+ databaseHealth: "Reports a summary of this site's database health (connectivity, disk headroom, pending-migration/interrupted-migration state).",
14
+ databaseSchemaState: "Reports this site's schema drift status (in-sync/ahead/diverged/behind) between its persisted schema snapshot and the runtime's current schema.",
15
+ databasePendingMigrations: "Lists migrations pending against this site that have not yet been applied.",
16
+ databaseRestorePoints: "Lists every restore point recorded for this site, newest first, with its trigger, cost class, and capture time.",
17
+ databasePlanMigrate: "Previews what forward-migrating this site's schema would do — cost class and a plan hash — without applying anything.",
18
+ databaseExecuteMigrate: "Moves this site's database forward to the current schema. Shows the user a confirm dialog first and only runs if they " +
19
+ "confirm. A restore point is taken first. Call database_plan_migrate_forward first to see the cost class.",
20
+ databaseCreateRestorePoint: "Mints a new restore point for this site independent of any migration, subject to the site's cost-acknowledgment rule.",
21
+ databaseRestoreGuidance: "Returns a deep-link routing envelope pointing at the Recovery surface for restoring this site to an earlier snapshot. Never itself a restore lever.",
22
+ };
23
+ //# sourceMappingURL=site-db-messages.js.map
@@ -0,0 +1,9 @@
1
+ import type { DbMessages, DbTransferMessages } from "../core/messages.js";
2
+ /**
3
+ * @file Site wording for the `@jini-ai/db/tools` transfer tools. The package defaults speak of "the
4
+ * source"; a host that serves one site has its transfer tools say "this site", and the four
5
+ * descriptions are the bytes the host's descriptor snapshot pins from the pre-extraction catalog.
6
+ * `plan` names the real schemas from the host's `TransferNaming` (its default schema and per-site prefix).
7
+ */
8
+ export declare const SITE_TRANSFER_MESSAGES: DbTransferMessages & Pick<DbMessages, "privateAreasTaken" | "noDestination" | "uncheckedLinks" | "destinationSaved" | "missingSourceTable" | "missingSourceColumn">;
9
+ //# sourceMappingURL=site-transfer-messages.d.ts.map