@jini-ai/db 0.7.1 → 0.7.3-next.1

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 (162) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/README.md +33 -17
  3. package/dist/core/index.d.ts +1 -2
  4. package/dist/core/index.js +0 -1
  5. package/dist/core/pg-types.d.ts +4 -1
  6. package/dist/core/pg-types.js +1 -1
  7. package/dist/core/row-values.d.ts +0 -30
  8. package/dist/core/row-values.js +1 -41
  9. package/dist/data-modules/data-module.d.ts +260 -4
  10. package/dist/data-modules/data-module.js +105 -83
  11. package/dist/data-modules/disk-headroom.js +1 -1
  12. package/dist/data-modules/index.d.ts +2 -2
  13. package/dist/data-modules/index.js +2 -2
  14. package/dist/data-modules/migration-journal.js +6 -6
  15. package/dist/data-modules/migration-recovery.js +2 -2
  16. package/dist/data-modules/plugin-identity.js +5 -5
  17. package/dist/data-modules/plugin-store.d.ts +4 -4
  18. package/dist/data-modules/restore.js +5 -5
  19. package/dist/data-modules/snapshot.d.ts +1 -1
  20. package/dist/data-modules/snapshot.js +3 -3
  21. package/dist/events/change-set-repo.sql.d.ts +70 -0
  22. package/dist/events/change-set-repo.sql.js +72 -0
  23. package/dist/events/index.d.ts +4 -0
  24. package/dist/events/index.js +3 -0
  25. package/dist/events/outbox-repo.sql.d.ts +91 -0
  26. package/dist/events/outbox-repo.sql.js +108 -0
  27. package/dist/events/repo.rows.d.ts +44 -0
  28. package/dist/events/repo.rows.js +59 -0
  29. package/dist/gated-mutations/index.d.ts +3 -0
  30. package/dist/gated-mutations/index.js +2 -0
  31. package/dist/gated-mutations/repo.rows.d.ts +19 -0
  32. package/dist/gated-mutations/repo.rows.js +23 -0
  33. package/dist/gated-mutations/repo.sql.d.ts +67 -0
  34. package/dist/gated-mutations/repo.sql.js +71 -0
  35. package/dist/kernel/dialect.d.ts +53 -31
  36. package/dist/kernel/dialect.js +14 -36
  37. package/dist/kernel/index.d.ts +2 -2
  38. package/dist/kernel/index.js +1 -7
  39. package/dist/kernel/kernel-core.d.ts +7 -3
  40. package/dist/kernel/kernel-core.js +75 -66
  41. package/dist/kernel/ops.d.ts +9 -3
  42. package/dist/kernel/ops.js +2 -2
  43. package/dist/kernel/owned-transaction.d.ts +7 -7
  44. package/dist/kernel/owned-transaction.js +2 -2
  45. package/dist/kernel/pglite/driver.d.ts +2 -2
  46. package/dist/kernel/pglite/driver.js +18 -18
  47. package/dist/kernel/pglite/ops.d.ts +8 -3
  48. package/dist/kernel/pglite/ops.js +5 -5
  49. package/dist/kernel/port.d.ts +9 -76
  50. package/dist/kernel/port.js +1 -10
  51. package/dist/kernel/postgres/driver.d.ts +4 -2
  52. package/dist/kernel/postgres/driver.js +17 -17
  53. package/dist/kernel/postgres/ops.d.ts +5 -3
  54. package/dist/kernel/postgres/ops.js +3 -3
  55. package/dist/kernel/postgres/pglite-socket.d.ts +2 -2
  56. package/dist/kernel/postgres/pglite-socket.js +13 -13
  57. package/dist/kernel/schema-scope.d.ts +5 -2
  58. package/dist/kernel/schema-scope.js +1 -1
  59. package/dist/kernel/schema-shape.d.ts +7 -3
  60. package/dist/kernel/schema-shape.js +2 -2
  61. package/dist/kernel/session-lock.d.ts +6 -6
  62. package/dist/kernel/sqlite/driver.d.ts +16 -8
  63. package/dist/kernel/sqlite/driver.js +38 -38
  64. package/dist/kernel/sqlite/index.d.ts +1 -0
  65. package/dist/kernel/sqlite/index.js +1 -0
  66. package/dist/kernel/sqlite/ops.d.ts +4 -2
  67. package/dist/kernel/sqlite/ops.js +3 -3
  68. package/dist/kernel/sqlite/sqlite-only.d.ts +81 -0
  69. package/dist/kernel/sqlite/sqlite-only.js +58 -0
  70. package/dist/kernel/store-copy.d.ts +7 -7
  71. package/dist/kernel/store-copy.js +22 -14
  72. package/dist/kernel/typegen.d.ts +5 -3
  73. package/dist/kernel/typegen.js +1 -1
  74. package/dist/migrate/checksum.d.ts +3 -1
  75. package/dist/migrate/checksum.js +1 -1
  76. package/dist/migrate/index.d.ts +1 -1
  77. package/dist/migrate/legacy-ledger.d.ts +4 -4
  78. package/dist/migrate/runner.d.ts +12 -7
  79. package/dist/migrate/runner.js +7 -6
  80. package/dist/migrate/step.d.ts +3 -28
  81. package/dist/migrate/step.js +3 -3
  82. package/dist/owner-store/index.d.ts +47 -1
  83. package/dist/owner-store/index.js +28 -1
  84. package/dist/owner-store/migrations/0000_owner_store.d.ts +3 -2
  85. package/dist/owner-store/migrations/index.d.ts +1 -1
  86. package/dist/pglite/owner.d.ts +12 -4
  87. package/dist/pglite/owner.js +33 -27
  88. package/dist/pglite/socket-server.d.ts +5 -1
  89. package/dist/pglite/socket-server.js +5 -4
  90. package/dist/recovery/deep-link.d.ts +3 -3
  91. package/dist/recovery/degraded-banners.d.ts +3 -3
  92. package/dist/recovery/degraded-banners.js +3 -3
  93. package/dist/recovery/disclosure.d.ts +6 -6
  94. package/dist/recovery/disclosure.js +6 -6
  95. package/dist/recovery/evaluate-boot-migration-policy.d.ts +5 -5
  96. package/dist/recovery/evaluate-boot-migration-policy.js +5 -5
  97. package/dist/recovery/lookup-adapters.d.ts +1 -1
  98. package/dist/recovery/lookup-adapters.js +1 -1
  99. package/dist/recovery/migrate-forward-execute.d.ts +1 -1
  100. package/dist/recovery/migrate-forward-execute.js +5 -5
  101. package/dist/recovery/migrate-forward-hooks.d.ts +6 -6
  102. package/dist/recovery/migrate-forward-hooks.js +5 -5
  103. package/dist/recovery/operation-lock.d.ts +11 -11
  104. package/dist/recovery/operation-lock.js +3 -3
  105. package/dist/recovery/reconcile-interrupted-migration.d.ts +7 -7
  106. package/dist/recovery/reconcile-interrupted-migration.js +7 -7
  107. package/dist/recovery/recovery-orchestrator.d.ts +21 -21
  108. package/dist/recovery/recovery-orchestrator.js +9 -9
  109. package/dist/recovery/restore-hooks.d.ts +8 -8
  110. package/dist/recovery/restore-hooks.js +7 -7
  111. package/dist/recovery/restore-point-create.d.ts +3 -3
  112. package/dist/secrets-vault/repo.sql.d.ts +3 -3
  113. package/dist/secrets-vault/repo.sql.js +5 -4
  114. package/dist/settings/index.d.ts +3 -0
  115. package/dist/settings/index.js +2 -0
  116. package/dist/settings/repo.rows.d.ts +117 -0
  117. package/dist/settings/repo.rows.js +106 -0
  118. package/dist/settings/repo.sql.d.ts +99 -0
  119. package/dist/settings/repo.sql.js +219 -0
  120. package/dist/sqlite/checked-client.d.ts +1 -1
  121. package/dist/sqlite/checked-state.d.ts +3 -3
  122. package/dist/sqlite/db-ops.d.ts +1 -1
  123. package/dist/sqlite/db-ops.js +1 -1
  124. package/dist/sqlite/index.d.ts +1 -3
  125. package/dist/sqlite/index.js +2 -0
  126. package/dist/sqlite/inspect.d.ts +2 -2
  127. package/dist/sqlite/inspect.js +1 -1
  128. package/dist/sqlite/open.d.ts +1 -2
  129. package/dist/sqlite/stopped.d.ts +46 -0
  130. package/dist/sqlite/stopped.js +86 -0
  131. package/dist/sqlite/transaction.d.ts +2 -2
  132. package/dist/tools/database-catalog.d.ts +2 -2
  133. package/dist/tools/database-catalog.js +13 -3
  134. package/dist/tools/read-tools.js +70 -59
  135. package/dist/tools/restore-points.d.ts +1 -1
  136. package/dist/tools/transfer-tools.d.ts +0 -1
  137. package/dist/tools/transfer-tools.js +5 -4
  138. package/dist/transfer/copy-engine.js +10 -10
  139. package/dist/transfer/copy-order.d.ts +47 -0
  140. package/dist/transfer/copy-order.js +103 -0
  141. package/dist/transfer/index.d.ts +1 -0
  142. package/dist/transfer/index.js +1 -0
  143. package/dist/transfer/internal-ddl.d.ts +28 -6
  144. package/dist/transfer/internal-ddl.js +15 -15
  145. package/dist/transfer/postgres-ddl.js +6 -6
  146. package/dist/transfer/sqlite-source.d.ts +2 -3
  147. package/dist/transfer/sqlite-source.js +1 -1
  148. package/dist/verified-origin/index.d.ts +4 -0
  149. package/dist/verified-origin/index.js +3 -0
  150. package/dist/verified-origin/register.d.ts +43 -0
  151. package/dist/verified-origin/register.js +51 -0
  152. package/dist/verified-origin/repo.rows.d.ts +42 -0
  153. package/dist/verified-origin/repo.rows.js +47 -0
  154. package/dist/verified-origin/repo.sql.d.ts +67 -0
  155. package/dist/verified-origin/repo.sql.js +34 -0
  156. package/package.json +38 -11
  157. package/dist/sqlite/restore-types.d.ts +0 -46
  158. package/dist/sqlite/restore-types.js +0 -2
  159. package/dist/sqlite/sync-types.d.ts +0 -34
  160. package/dist/sqlite/sync-types.js +0 -2
  161. package/dist/sqlite/types.d.ts +0 -37
  162. package/dist/sqlite/types.js +0 -8
@@ -1,4 +1,5 @@
1
1
  /** Kysely's SQLite binding and kernel storage operations. */
2
2
  export { sqliteKernel, openSqliteFileKernel, openMemorySqliteKernel, closeSqliteConnection, sqliteClientOf, sqliteConnectionOf, type SqliteConnectionSource, type SqliteKernel } from "./driver.js";
3
3
  export { sqliteOps, copySqliteInto } from "./ops.js";
4
+ export { sqliteForeignKeyCheckedTransaction, sqliteSchemaObjects, sqliteTableExtendedInfo, sqliteTableInfo, type SqliteExtendedTableColumn, type SqliteForeignKeyViolation, type SqliteSchemaObject, type SqliteTableColumn } from "./sqlite-only.js";
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,5 @@
1
1
  /** Kysely's SQLite binding and kernel storage operations. */
2
2
  export { sqliteKernel, openSqliteFileKernel, openMemorySqliteKernel, closeSqliteConnection, sqliteClientOf, sqliteConnectionOf } from "./driver.js";
3
3
  export { sqliteOps, copySqliteInto } from "./ops.js";
4
+ export { sqliteForeignKeyCheckedTransaction, sqliteSchemaObjects, sqliteTableExtendedInfo, sqliteTableInfo } from "./sqlite-only.js";
4
5
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { type StorageKernel, type StorageOps } from "../index.js";
1
+ import { type KyselyKernel, type StorageOps } from "../index.js";
2
2
  /** Synchronous WAL-safe snapshot for admission code that must commit under a synchronous lock.
3
3
  * Accepts either the host's SQLite client or Node's built-in DatabaseSync; the caller owns it.
4
4
  * @throws SQLite errors, including an existing destination or an active transaction.
@@ -21,5 +21,7 @@ export declare function copySqliteInto({ source, targetPath }: {
21
21
  * a transaction.
22
22
  * @complexity each op is one full pass over the database file, O(size).
23
23
  */
24
- export declare function sqliteOps<DB>(kernel: StorageKernel<DB>): StorageOps;
24
+ export declare function sqliteOps<DB>({ kernel }: {
25
+ kernel: KyselyKernel<DB>;
26
+ }, _optional?: Record<string, never>): StorageOps;
25
27
  //# sourceMappingURL=ops.d.ts.map
@@ -18,11 +18,11 @@ export function copySqliteInto({ source, targetPath }, _options = {}) {
18
18
  * a transaction.
19
19
  * @complexity each op is one full pass over the database file, O(size).
20
20
  */
21
- export function sqliteOps(kernel) {
22
- const client = sqliteConnectionOf(kernel);
21
+ export function sqliteOps({ kernel }, _optional = {}) {
22
+ const client = sqliteConnectionOf({ kernel });
23
23
  if (client === undefined)
24
24
  throw new Error("sqliteOps: this SQLite kernel was not built by the sqlite driver");
25
- const outsideTransaction = outsideTransactionOf(kernel);
25
+ const outsideTransaction = outsideTransactionOf({ kernel: kernel });
26
26
  return {
27
27
  async copyTo(targetPath) {
28
28
  outsideTransaction("copyTo");
@@ -0,0 +1,81 @@
1
+ import type { KyselyKernel } from "../port.js";
2
+ /**
3
+ * @file SQLite-only primitives with no portable equivalent, spelled once at the kernel boundary.
4
+ *
5
+ * Why these are not `listColumns`/`tableExists` (`dialect.ts`): their callers need SQLite's OWN
6
+ * answer, byte for byte. A peer that ships a table's `PRAGMA table_info` shape to another peer,
7
+ * which compares it to its own and hashes it into a row's content hash, needs the declared type to
8
+ * keep its case and `pk` to keep its key ordinal. `listColumns` lower-cases the type and folds `pk`
9
+ * to a boolean, which would make an upgraded peer disagree with an older one about the same table.
10
+ * The deferred foreign-key check is SQLite's `defer_foreign_keys` + `foreign_key_check` pair;
11
+ * Postgres has no statement-level equivalent.
12
+ */
13
+ /** One `PRAGMA table_info` row, as the SQLite catalog reports it. */
14
+ export interface SqliteTableColumn {
15
+ readonly name: string;
16
+ /** The declared type, case preserved. */
17
+ readonly type: string;
18
+ /** 0 for a non-key column, else the column's 1-based position in the primary key. */
19
+ readonly pk: number;
20
+ readonly notnull: number;
21
+ }
22
+ /** Exact table_xinfo metadata; generated and virtual-table columns must not disappear in archive validation. */
23
+ export interface SqliteExtendedTableColumn extends SqliteTableColumn {
24
+ readonly cid: number;
25
+ readonly dflt_value: string | null;
26
+ readonly hidden: number;
27
+ }
28
+ /** One `PRAGMA foreign_key_check` row. */
29
+ export interface SqliteForeignKeyViolation {
30
+ readonly table: string;
31
+ readonly rowid: number;
32
+ readonly parent: string;
33
+ }
34
+ /** Exact native schema entry, including SQLite's internal indexes and original DDL bytes. */
35
+ export interface SqliteSchemaObject {
36
+ type: string;
37
+ name: string;
38
+ tbl_name: string;
39
+ sql: string | null;
40
+ }
41
+ /** Read exact archive column metadata through the existing SQLite boundary, including hidden columns.
42
+ * @throws {Error} On another dialect or a failed read. No writes; table names are bound values.
43
+ * @complexity O(columns) time and space.
44
+ */
45
+ export declare function sqliteTableExtendedInfo<DB>({ kernel, table }: {
46
+ kernel: KyselyKernel<DB>;
47
+ table: string;
48
+ }, _options?: {}): Promise<SqliteExtendedTableColumn[]>;
49
+ /**
50
+ * Read every native schema object without normalizing its SQL. Unlike readSchemaShape, this
51
+ * preserves internal objects and exact DDL for callers that must reject untrusted substitutions.
52
+ * @throws {Error} On a non-SQLite kernel or a failed catalog read. No writes.
53
+ * @complexity O(s log s) database ordering and O(s + DDL bytes) memory for s schema objects.
54
+ */
55
+ export declare function sqliteSchemaObjects<DB>({ kernel }: {
56
+ kernel: KyselyKernel<DB>;
57
+ }, _options?: {}): Promise<SqliteSchemaObject[]>;
58
+ /**
59
+ * The columns of the ordinary table `table` (views excluded), in declaration order, exactly as
60
+ * `PRAGMA table_info` reports them; `null` when no such table exists. The name is bound, never
61
+ * spliced, so it needs no identifier quoting.
62
+ * @throws {Error} On a non-SQLite kernel.
63
+ */
64
+ export declare function sqliteTableInfo<DB>(required: {
65
+ kernel: KyselyKernel<DB>;
66
+ table: string;
67
+ }, _optional?: {}): Promise<SqliteTableColumn[] | null>;
68
+ /**
69
+ * Runs `work` in one kernel transaction with foreign keys deferred, then checks every foreign key
70
+ * before commit. A violation throws `onViolation({ violation: first })` INSIDE the transaction, so the
71
+ * whole of `work` rolls back.
72
+ * @throws {Error} On a non-SQLite kernel.
73
+ */
74
+ export declare function sqliteForeignKeyCheckedTransaction<DB, T>(required: {
75
+ kernel: KyselyKernel<DB>;
76
+ work: () => Promise<T>;
77
+ onViolation: (required: {
78
+ violation: SqliteForeignKeyViolation;
79
+ }, optional?: Record<string, never>) => Error;
80
+ }, _optional?: {}): Promise<T>;
81
+ //# sourceMappingURL=sqlite-only.d.ts.map
@@ -0,0 +1,58 @@
1
+ import { sql } from "kysely";
2
+ function requireSqlite({ kernel, operation }, _optional = {}) {
3
+ if (kernel.dialect !== "sqlite") {
4
+ throw new Error(`${operation} is SQLite-only; this kernel is ${kernel.dialect}`);
5
+ }
6
+ }
7
+ /** Read exact archive column metadata through the existing SQLite boundary, including hidden columns.
8
+ * @throws {Error} On another dialect or a failed read. No writes; table names are bound values.
9
+ * @complexity O(columns) time and space.
10
+ */
11
+ export async function sqliteTableExtendedInfo({ kernel, table }, _options = {}) {
12
+ requireSqlite({ kernel, operation: "sqliteTableExtendedInfo" });
13
+ return kernel.query(sql `SELECT * FROM pragma_table_xinfo(${table}) ORDER BY cid`);
14
+ }
15
+ /**
16
+ * Read every native schema object without normalizing its SQL. Unlike readSchemaShape, this
17
+ * preserves internal objects and exact DDL for callers that must reject untrusted substitutions.
18
+ * @throws {Error} On a non-SQLite kernel or a failed catalog read. No writes.
19
+ * @complexity O(s log s) database ordering and O(s + DDL bytes) memory for s schema objects.
20
+ */
21
+ export async function sqliteSchemaObjects({ kernel }, _options = {}) {
22
+ requireSqlite({ kernel, operation: "sqliteSchemaObjects" });
23
+ return kernel.query(sql `SELECT type,name,tbl_name,sql FROM sqlite_schema ORDER BY type,name`);
24
+ }
25
+ /**
26
+ * The columns of the ordinary table `table` (views excluded), in declaration order, exactly as
27
+ * `PRAGMA table_info` reports them; `null` when no such table exists. The name is bound, never
28
+ * spliced, so it needs no identifier quoting.
29
+ * @throws {Error} On a non-SQLite kernel.
30
+ */
31
+ export async function sqliteTableInfo(required, _optional = {}) {
32
+ const { kernel, table } = required;
33
+ requireSqlite({ kernel, operation: "sqliteTableInfo" });
34
+ const found = await kernel.query(sql `SELECT name FROM sqlite_schema WHERE type='table' AND name=${table}`);
35
+ if (found.length === 0)
36
+ return null;
37
+ const rows = await kernel.query(sql `SELECT name, type, pk, "notnull" FROM pragma_table_info(${table}) ORDER BY cid`);
38
+ return rows.map(({ name, type, pk, notnull }) => ({ name, type, pk, notnull }));
39
+ }
40
+ /**
41
+ * Runs `work` in one kernel transaction with foreign keys deferred, then checks every foreign key
42
+ * before commit. A violation throws `onViolation({ violation: first })` INSIDE the transaction, so the
43
+ * whole of `work` rolls back.
44
+ * @throws {Error} On a non-SQLite kernel.
45
+ */
46
+ export async function sqliteForeignKeyCheckedTransaction(required, _optional = {}) {
47
+ const { kernel, work, onViolation } = required;
48
+ requireSqlite({ kernel, operation: "sqliteForeignKeyCheckedTransaction" });
49
+ return kernel.transaction(async () => {
50
+ await kernel.execute(sql `PRAGMA defer_foreign_keys = ON`);
51
+ const result = await work();
52
+ const [first] = await kernel.query(sql `PRAGMA foreign_key_check`);
53
+ if (first)
54
+ throw onViolation({ violation: first });
55
+ return result;
56
+ });
57
+ }
58
+ //# sourceMappingURL=sqlite-only.js.map
@@ -1,4 +1,4 @@
1
- import type { StorageKernel } from "./port.js";
1
+ import type { KyselyKernel } from "./port.js";
2
2
  /**
3
3
  * @file A Postgres-to-Postgres copy of a site's whole store (R1g, the host storage move command): every table
4
4
  * in the host-supplied schemas (content and AI chat), row for row, from a PGlite
@@ -65,21 +65,21 @@ export declare class StoreCopyError extends Error {
65
65
  }
66
66
  /** Public copy API: required host scope and borrowed kernels; no new kernel is opened. */
67
67
  export declare function readCatalog({ kernel, scope }: {
68
- kernel: StorageKernel<unknown>;
68
+ kernel: KyselyKernel<unknown>;
69
69
  scope: StoreCopyScope;
70
70
  }, _optional?: {}): Promise<CatalogTable[]>;
71
71
  export declare function nonEmptyTables({ kernel, scope }: {
72
- kernel: StorageKernel<unknown>;
72
+ kernel: KyselyKernel<unknown>;
73
73
  scope: StoreCopyScope;
74
74
  }, _optional?: {}): Promise<string[]>;
75
75
  export declare function assertLedgersAgree({ source, target, scope }: {
76
- source: StorageKernel<unknown>;
77
- target: StorageKernel<unknown>;
76
+ source: KyselyKernel<unknown>;
77
+ target: KyselyKernel<unknown>;
78
78
  scope: StoreCopyScope;
79
79
  }, _optional?: {}): Promise<void>;
80
80
  export declare function copyPgStore({ source, target, scope }: {
81
- source: StorageKernel<unknown>;
82
- target: StorageKernel<unknown>;
81
+ source: KyselyKernel<unknown>;
82
+ target: KyselyKernel<unknown>;
83
83
  scope: StoreCopyScope;
84
84
  }, optional?: {
85
85
  onCopied?: () => Promise<void>;
@@ -180,6 +180,26 @@ async function advanceIdentityCounters({ target, tables }, _optional = {}) {
180
180
  }
181
181
  }
182
182
  }
183
+ /** A table present on both sides must have identical columns; copying into a different shape would corrupt rows. */
184
+ function assertSharedTableShapesAgree({ sourceTables, targetTables }) {
185
+ for (const table of sourceTables) {
186
+ const other = targetTables.get(qualified(table));
187
+ if (other === undefined)
188
+ continue;
189
+ const shape = (t) => t.columns.map((c) => `${c.name} ${c.type}`).join(", ");
190
+ if (shape(table) !== shape(other)) {
191
+ throw new StoreCopyError(`table ${qualified(table)} differs: source (${shape(table)}), target (${shape(other)})`);
192
+ }
193
+ }
194
+ }
195
+ /** Every copied table must hash identically on both sides, or the copy is rolled back. */
196
+ async function verifyFingerprints({ source, target, tables }) {
197
+ for (const table of tables) {
198
+ const [a, b] = [await fingerprint(source, table), await fingerprint(target, table)];
199
+ if (a !== b)
200
+ throw new StoreCopyError(`table ${qualified(table)} did not verify after the copy: source ${a}, target ${b}`);
201
+ }
202
+ }
183
203
  /**
184
204
  * Copies every table of `source` into `target` (see this file's header). Call it with both at head
185
205
  * and the target empty ({@link nonEmptyTables}); the ledgers are checked here first.
@@ -194,15 +214,7 @@ async function copyPgStoreInternal(source, target, scope, optional = {}) {
194
214
  await assertLedgersAgreeInternal(source, target, scope);
195
215
  const sourceTables = (await readCatalogInternal(source, scope)).filter((t) => !isLedger(t, scope));
196
216
  const targetTables = new Map((await readCatalogInternal(target, scope)).map((t) => [qualified(t), t]));
197
- for (const table of sourceTables) {
198
- const other = targetTables.get(qualified(table));
199
- if (other === undefined)
200
- continue;
201
- const shape = (t) => t.columns.map((c) => `${c.name} ${c.type}`).join(", ");
202
- if (shape(table) !== shape(other)) {
203
- throw new StoreCopyError(`table ${qualified(table)} differs: source (${shape(table)}), target (${shape(other)})`);
204
- }
205
- }
217
+ assertSharedTableShapesAgree({ sourceTables, targetTables });
206
218
  const created = sourceTables.filter((t) => !targetTables.has(qualified(t)));
207
219
  const createdIds = new Set(created.map(qualified));
208
220
  const sourceConstraints = await readConstraints(source, scope);
@@ -236,11 +248,7 @@ async function copyPgStoreInternal(source, target, scope, optional = {}) {
236
248
  }
237
249
  await addConstraints({ target, constraints: [...foreignKeys, ...createdConstraints.filter((c) => c.type === "f")] });
238
250
  await advanceIdentityCounters({ target, tables: sourceTables });
239
- for (const table of sourceTables) {
240
- const [a, b] = [await fingerprint(source, table), await fingerprint(target, table)];
241
- if (a !== b)
242
- throw new StoreCopyError(`table ${qualified(table)} did not verify after the copy: source ${a}, target ${b}`);
243
- }
251
+ await verifyFingerprints({ source, target, tables: sourceTables });
244
252
  await optional.onCopied?.();
245
253
  return report;
246
254
  });
@@ -1,13 +1,15 @@
1
- import type { StorageKernel } from "./port.js";
1
+ import type { KyselyKernel } from "./port.js";
2
2
  /**
3
3
  * The `.ts` source of a Kysely database interface for every table in the kernel's current schema.
4
4
  *
5
5
  * @param required.interfaceName e.g. `ContentDatabase`.
6
6
  * @param required.source one line naming where the reference database came from (printed in the header).
7
7
  */
8
- export declare function renderDatabaseTypes(kernel: StorageKernel<unknown>, required: {
8
+ export declare function renderDatabaseTypes({ kernel, ...required }: {
9
+ kernel: KyselyKernel<unknown>;
10
+ } & {
9
11
  interfaceName: string;
10
12
  source: string;
11
13
  regenerate: string;
12
- }): Promise<string>;
14
+ }, _optional?: Record<string, never>): Promise<string>;
13
15
  //# sourceMappingURL=typegen.d.ts.map
@@ -40,7 +40,7 @@ function columnType(column) {
40
40
  * @param required.interfaceName e.g. `ContentDatabase`.
41
41
  * @param required.source one line naming where the reference database came from (printed in the header).
42
42
  */
43
- export async function renderDatabaseTypes(kernel, required) {
43
+ export async function renderDatabaseTypes({ kernel, ...required }, _optional = {}) {
44
44
  if (kernel.dialect !== "postgres")
45
45
  throw new Error("typegen reads a Postgres reference database");
46
46
  const rows = await kernel.query(sql `SELECT table_name, column_name, data_type, is_nullable, column_default, is_identity
@@ -7,5 +7,7 @@
7
7
  *
8
8
  * @complexity O(length of `text`).
9
9
  */
10
- export declare function sourceChecksum(text: string): string;
10
+ export declare function sourceChecksum({ text }: {
11
+ text: string;
12
+ }, _optional?: Record<string, never>): string;
11
13
  //# sourceMappingURL=checksum.d.ts.map
@@ -8,7 +8,7 @@ import { createHash } from "node:crypto";
8
8
  *
9
9
  * @complexity O(length of `text`).
10
10
  */
11
- export function sourceChecksum(text) {
11
+ export function sourceChecksum({ text }, _optional = {}) {
12
12
  return createHash("sha256").update(text, "utf8").digest("hex");
13
13
  }
14
14
  //# sourceMappingURL=checksum.js.map
@@ -4,7 +4,7 @@
4
4
  */
5
5
  export { assertValidSteps, hasLedger, migrate, type MigrationOptions, type MigrationReport, runMigrations } from "./runner.js";
6
6
  export type { LegacyLedgerMapping } from "./legacy-ledger.js";
7
- export { MIGRATION_ID, MigrationChecksumError, type MigrationContext, type MigrationStep, UnknownAppliedMigrationError, } from "./step.js";
7
+ export { MIGRATION_ID, MigrationChecksumError, UnknownAppliedMigrationError, } from "./step.js";
8
8
  export { sourceChecksum } from "./checksum.js";
9
9
  export { executeDdl } from "./ddl.js";
10
10
  //# sourceMappingURL=index.d.ts.map
@@ -1,11 +1,11 @@
1
- import type { MigrationStep } from "./step.js";
1
+ import type { MigrationStep, StorageDialect } from "@jini-ai/core/contracts/storage";
2
2
  import type { Ledger, LedgerRow, LegacyLedgerMapping } from "./ledger-contracts.js";
3
3
  export type { LegacyLedgerMapping } from "./ledger-contracts.js";
4
- import type { StorageDialect } from "../kernel/port.js";
4
+ import type { KyselyKernel } from "../kernel/index.js";
5
5
  /** Validate the whole map before backups, DDL or migration work. O(steps + identities). */
6
6
  export declare function validateLegacyMapping({ mapping, steps }: {
7
7
  mapping: LegacyLedgerMapping;
8
- steps: readonly MigrationStep[];
8
+ steps: readonly MigrationStep<KyselyKernel<unknown>>[];
9
9
  }, _optional?: {}): void;
10
10
  export declare function ensureLegacyLedger({ ledger, mapping, dialect }: {
11
11
  ledger: Ledger;
@@ -20,7 +20,7 @@ export declare function readLegacyLedger({ ledger, mapping }: {
20
20
  export declare function insertLegacyRow({ ledger, mapping, step, timestamp }: {
21
21
  ledger: Ledger;
22
22
  mapping: LegacyLedgerMapping;
23
- step: MigrationStep;
23
+ step: MigrationStep<KyselyKernel<unknown>>;
24
24
  timestamp: () => string;
25
25
  }, _optional?: {}): Promise<void>;
26
26
  //# sourceMappingURL=legacy-ledger.d.ts.map
@@ -1,8 +1,8 @@
1
1
  import { type Clock } from "@jini-ai/core/primitives";
2
- import { type StorageKernel } from "../kernel/index.js";
2
+ import { type KyselyKernel } from "../kernel/index.js";
3
3
  import { type LegacyLedgerMapping } from "./legacy-ledger.js";
4
4
  export type { Ledger, LedgerRow } from "./ledger-contracts.js";
5
- import { type MigrationContext, type MigrationStep } from "./step.js";
5
+ import { type MigrationContext, type MigrationStep } from "@jini-ai/core/contracts/storage";
6
6
  export interface MigrationOptions {
7
7
  /** The ledger table (REQUIRED, no default); also the migration lock's key. */
8
8
  ledgerTable: string;
@@ -35,11 +35,13 @@ export interface MigrationReport {
35
35
  notes: string[];
36
36
  }
37
37
  /** Throws on duplicate, unordered or malformed ids and on a checksum that is not sha256 hex. */
38
- export declare function assertValidSteps(steps: readonly MigrationStep[]): void;
38
+ export declare function assertValidSteps({ steps }: {
39
+ steps: readonly MigrationStep<KyselyKernel<unknown>>[];
40
+ }, _optional?: Record<string, never>): void;
39
41
  /** Object-input facade over the existing runner; all extensions remain opt-in. */
40
42
  export declare function migrate(required: {
41
- kernel: StorageKernel<unknown>;
42
- steps: readonly MigrationStep[];
43
+ kernel: KyselyKernel<unknown>;
44
+ steps: readonly MigrationStep<KyselyKernel<unknown>>[];
43
45
  ledgerTable: string;
44
46
  }, optional?: Omit<MigrationOptions, "ledgerTable">): Promise<MigrationReport>;
45
47
  /**
@@ -50,7 +52,10 @@ export declare function migrate(required: {
50
52
  * @throws UnknownAppliedMigrationError / MigrationChecksumError before applying anything; whatever a
51
53
  * step throws (its transaction is rolled back, later steps are not attempted).
52
54
  */
53
- export declare function runMigrations(kernel: StorageKernel<unknown>, steps: readonly MigrationStep[], options: MigrationOptions): Promise<MigrationReport>;
55
+ export declare function runMigrations(kernel: KyselyKernel<unknown>, steps: readonly MigrationStep<KyselyKernel<unknown>>[], options: MigrationOptions): Promise<MigrationReport>;
54
56
  /** True when `kernel`'s database has the ledger `ledgerTable` (it has been through {@link runMigrations}). */
55
- export declare function hasLedger(kernel: StorageKernel<unknown>, ledgerTable: string): Promise<boolean>;
57
+ export declare function hasLedger({ kernel, ledgerTable }: {
58
+ kernel: KyselyKernel<unknown>;
59
+ ledgerTable: string;
60
+ }, _optional?: Record<string, never>): Promise<boolean>;
56
61
  //# sourceMappingURL=runner.d.ts.map
@@ -6,6 +6,7 @@ import { listTables, tableExists } from "../kernel/index.js";
6
6
  import { ownedTransactionOf } from "../kernel/owned-transaction.js";
7
7
  import { ensureLegacyLedger, insertLegacyRow, readLegacyLedger, validateLegacyMapping } from "./legacy-ledger.js";
8
8
  import { MIGRATION_ID, MigrationChecksumError, UnknownAppliedMigrationError, } from "./step.js";
9
+ import {} from "@jini-ai/core/contracts/storage";
9
10
  function ledgerFor(kernel, options) {
10
11
  const table = options.ledgerTable;
11
12
  if (typeof table !== "string" || table.length === 0)
@@ -23,7 +24,7 @@ function ledgerFor(kernel, options) {
23
24
  };
24
25
  }
25
26
  /** Throws on duplicate, unordered or malformed ids and on a checksum that is not sha256 hex. */
26
- export function assertValidSteps(steps) {
27
+ export function assertValidSteps({ steps }, _optional = {}) {
27
28
  let previous = "";
28
29
  for (const step of steps) {
29
30
  if (!MIGRATION_ID.test(step.id))
@@ -140,7 +141,7 @@ export function migrate(required, optional = {}) {
140
141
  * step throws (its transaction is rolled back, later steps are not attempted).
141
142
  */
142
143
  export async function runMigrations(kernel, steps, options) {
143
- assertValidSteps(steps);
144
+ assertValidSteps({ steps });
144
145
  kernel.require("interactiveTransactions");
145
146
  validateExtensions({ options, steps });
146
147
  if (options.atomicity === "batch")
@@ -193,7 +194,7 @@ async function preparePendingStep({ kernel, context, step, backedUp }) {
193
194
  /** The pre-change copy (see the file header). Outside any transaction: a backup cannot run inside one. */
194
195
  async function backUpBeforeChange(kernel, context) {
195
196
  const target = context.backupPath;
196
- if (target === undefined || !kernel.capabilities.backup || (await listTables(kernel)).length === 0)
197
+ if (target === undefined || !kernel.capabilities.backup || (await listTables({ kernel })).length === 0)
197
198
  return;
198
199
  // The folder is made only when a copy is taken, so a run with nothing to copy leaves none behind.
199
200
  fs.mkdirSync(path.dirname(path.resolve(target)), { recursive: true });
@@ -211,12 +212,12 @@ async function backUpBeforeChange(kernel, context) {
211
212
  }
212
213
  async function ledgerExists(kernel, ledger) {
213
214
  if (ledger.schema === undefined)
214
- return tableExists(kernel, ledger.table);
215
+ return tableExists({ kernel, table: ledger.table });
215
216
  const [row] = await kernel.query(sql `SELECT to_regclass(${ledger.schema + "." + ledger.table})::text AS found`);
216
217
  return row?.found != null;
217
218
  }
218
219
  /** True when `kernel`'s database has the ledger `ledgerTable` (it has been through {@link runMigrations}). */
219
- export async function hasLedger(kernel, ledgerTable) {
220
- return tableExists(kernel, ledgerTable);
220
+ export async function hasLedger({ kernel, ledgerTable }, _optional = {}) {
221
+ return tableExists({ kernel, table: ledgerTable });
221
222
  }
222
223
  //# sourceMappingURL=runner.js.map
@@ -1,35 +1,10 @@
1
- import type { StorageKernel } from "../kernel/index.js";
2
1
  /**
3
- * @file What a migration step is. Steps form ONE ordered history for every dialect; the runner
4
- * (`runner.ts`) by default applies each pending one in its own transaction and records it in the consumer's
5
- * ledger table.
2
+ * @file The migration identity rule and the runner's errors. The step contract itself
3
+ * (`MigrationStep`, `MigrationContext`) is `@jini-ai/core/contracts/storage`; the runner (`runner.ts`) by default
4
+ * applies each pending step in its own transaction and records it in the consumer's ledger table.
6
5
  */
7
6
  /** `NNNN_snake_name`. Ordered by the number; never renamed or reused once shipped. */
8
7
  export declare const MIGRATION_ID: RegExp;
9
- export interface MigrationContext {
10
- /** Where the runner copied (or would copy) the database before the first pending step; the caller decides. */
11
- readonly backupPath?: string;
12
- /** A host may explicitly continue after selected backup failures; throwing preserves refusal. */
13
- readonly onBackupError?: (input: {
14
- error: unknown;
15
- backupPath: string;
16
- }) => void;
17
- /** Runs only after the copy succeeds, before any step changes the source database. */
18
- readonly onBackupComplete?: (input: {
19
- backupPath: string;
20
- }) => Promise<void>;
21
- /** Something worth telling the operator (a backup taken, a legacy tail applied). */
22
- note(message: string): void;
23
- }
24
- export interface MigrationStep {
25
- readonly id: string;
26
- /** sha256 hex of what the step does, pinned by the consumer (a test re-derives it with `sourceChecksum`). */
27
- readonly checksum: string;
28
- /** Runs OUTSIDE the transaction, only when the step is pending (backups: they cannot run inside one). */
29
- prepare?(kernel: StorageKernel<unknown>, context: MigrationContext): Promise<void>;
30
- /** Runs inside the step's transaction, after the runner holds the migration lock. */
31
- up(kernel: StorageKernel<unknown>, context: MigrationContext): Promise<void>;
32
- }
33
8
  /** An applied step's recorded checksum differs from this runtime's: the step was edited after shipping. */
34
9
  export declare class MigrationChecksumError extends Error {
35
10
  readonly id: string;
@@ -1,7 +1,7 @@
1
1
  /**
2
- * @file What a migration step is. Steps form ONE ordered history for every dialect; the runner
3
- * (`runner.ts`) by default applies each pending one in its own transaction and records it in the consumer's
4
- * ledger table.
2
+ * @file The migration identity rule and the runner's errors. The step contract itself
3
+ * (`MigrationStep`, `MigrationContext`) is `@jini-ai/core/contracts/storage`; the runner (`runner.ts`) by default
4
+ * applies each pending step in its own transaction and records it in the consumer's ledger table.
5
5
  */
6
6
  /** `NNNN_snake_name`. Ordered by the number; never renamed or reused once shipped. */
7
7
  export const MIGRATION_ID = /^\d{4}_[a-z0-9_]+$/;
@@ -1,4 +1,50 @@
1
- /** Legacy owner database schema history; the read-only reader lives in @jini-ai/server/owner-store. */
1
+ /** Legacy owner database schema history and its read-only row queries; decryption lives in @jini-ai/platform/secrets/legacy-owner, the file wiring in @jini-ai/server/owner-store. */
2
+ import type { VaultKind } from "@jini-ai/core/contracts/vault";
3
+ import type { KyselyKernel } from "../kernel/port.js";
4
+ import type { SecretsVaultDatabase } from "../secrets-vault/index.js";
2
5
  export { OWNER_STORE_LEDGER, ownerStoreMigrations } from "./migrations/index.js";
3
6
  export { ownerStoreDdl, ownerStoreMigration } from "./migrations/0000_owner_store.js";
7
+ export interface LegacyOwnerDatabase extends SecretsVaultDatabase {
8
+ owner_grants: {
9
+ entry_id: string;
10
+ consumer_id: string;
11
+ created_at: string;
12
+ };
13
+ owner_revocations: {
14
+ entry_id: string;
15
+ consumer_id: string;
16
+ };
17
+ }
18
+ /** Count entries and grants without any key, so a caller can tell an empty store from a used one.
19
+ * @throws Whatever the kernel throws (not a database, locked).
20
+ * @complexity O(1) queries over indexed tables.
21
+ * @example const { entries, grants } = await countOwnerStoreRows({ kernel });
22
+ */
23
+ export declare function countOwnerStoreRows({ kernel }: {
24
+ kernel: KyselyKernel<LegacyOwnerDatabase>;
25
+ }, _options?: {}): Promise<{
26
+ entries: number;
27
+ grants: number;
28
+ }>;
29
+ /** The sealed entries of one workspace, in id order. The caller passes the legacy owner workspace.
30
+ * @complexity O(n) for n rows of that workspace.
31
+ * @example const rows = await listOwnerEntryRows({ kernel, workspaceId: "owner" });
32
+ */
33
+ export declare function listOwnerEntryRows({ kernel, workspaceId }: {
34
+ kernel: KyselyKernel<LegacyOwnerDatabase>;
35
+ workspaceId: string;
36
+ }, _options?: {}): Promise<{
37
+ id: string;
38
+ kind: VaultKind;
39
+ ownerKey: string;
40
+ binding: string | null;
41
+ }[]>;
42
+ /** owner_revocations exists only past the unpublished 0001 step; a 0000 store has none. */
43
+ export declare function listOwnerDestinations({ kernel, table }: {
44
+ kernel: KyselyKernel<LegacyOwnerDatabase>;
45
+ table: "owner_grants" | "owner_revocations";
46
+ }, _options?: {}): Promise<{
47
+ entryId: string;
48
+ consumerId: string;
49
+ }[]>;
4
50
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,31 @@
1
- /** Legacy owner database schema history; the read-only reader lives in @jini-ai/server/owner-store. */
1
+ // No runtime kysely import here: this entry must load without the optional kysely peer, so the reads
2
+ // below use the kernel's own query builder (db.selectFrom, db.introspection) rather than the `sql` tag.
2
3
  export { OWNER_STORE_LEDGER, ownerStoreMigrations } from "./migrations/index.js";
3
4
  export { ownerStoreDdl, ownerStoreMigration } from "./migrations/0000_owner_store.js";
5
+ /** Count entries and grants without any key, so a caller can tell an empty store from a used one.
6
+ * @throws Whatever the kernel throws (not a database, locked).
7
+ * @complexity O(1) queries over indexed tables.
8
+ * @example const { entries, grants } = await countOwnerStoreRows({ kernel });
9
+ */
10
+ export async function countOwnerStoreRows({ kernel }, _options = {}) {
11
+ const count = (table) => kernel.run(async (db) => Number((await db.selectFrom(table).select(eb => eb.fn.countAll().as("n")).executeTakeFirst())?.n ?? 0));
12
+ return { entries: await count("secrets_vault"), grants: await count("owner_grants") };
13
+ }
14
+ /** The sealed entries of one workspace, in id order. The caller passes the legacy owner workspace.
15
+ * @complexity O(n) for n rows of that workspace.
16
+ * @example const rows = await listOwnerEntryRows({ kernel, workspaceId: "owner" });
17
+ */
18
+ export async function listOwnerEntryRows({ kernel, workspaceId }, _options = {}) {
19
+ const rows = await kernel.run(db => db.selectFrom("secrets_vault").select(["id", "kind", "owner_key", "binding"])
20
+ .where("workspace_id", "=", workspaceId).orderBy("id").execute());
21
+ return rows.map(row => ({ id: row.id, kind: row.kind, ownerKey: row.owner_key, binding: row.binding }));
22
+ }
23
+ /** owner_revocations exists only past the unpublished 0001 step; a 0000 store has none. */
24
+ export async function listOwnerDestinations({ kernel, table }, _options = {}) {
25
+ const present = (await kernel.run(db => db.introspection.getTables())).some(candidate => candidate.name === table);
26
+ if (!present)
27
+ return [];
28
+ const rows = await kernel.run(db => db.selectFrom(table).select(["entry_id", "consumer_id"]).orderBy("entry_id").orderBy("consumer_id").execute());
29
+ return rows.map(row => ({ entryId: row.entry_id, consumerId: row.consumer_id }));
30
+ }
4
31
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,7 @@
1
- import type { MigrationStep } from "../../migrate/step.js";
1
+ import type { MigrationStep } from "@jini-ai/core/contracts/storage";
2
+ import type { KyselyKernel } from "../../kernel/index.js";
2
3
  /** Owner-only history: no site tables or foreign workspace records are required. */
3
4
  export declare const ownerStoreDdl = "\nCREATE TABLE secrets_vault (\n workspace_id TEXT NOT NULL, id TEXT NOT NULL UNIQUE, kind TEXT NOT NULL, owner_key TEXT NOT NULL,\n principal_id TEXT, binding TEXT, provider TEXT, label TEXT NOT NULL, is_default INTEGER NOT NULL,\n revision INTEGER NOT NULL, sealed_key_id TEXT, sealed_ciphertext TEXT, sealed_nonce TEXT, sealed_alg TEXT,\n last4 TEXT, token_length INTEGER, meta TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,\n PRIMARY KEY (workspace_id, id)\n);\nCREATE UNIQUE INDEX owner_vault_default ON secrets_vault\n (workspace_id, kind, owner_key, (principal_id IS NULL), coalesce(principal_id, ''),\n (provider IS NULL), coalesce(provider, '')) WHERE is_default = 1;\nCREATE UNIQUE INDEX owner_vault_label ON secrets_vault\n (workspace_id, kind, owner_key, (principal_id IS NULL), coalesce(principal_id, ''),\n (provider IS NULL), coalesce(provider, ''), label);\nCREATE INDEX owner_vault_lookup ON secrets_vault\n (workspace_id, kind, owner_key, principal_id, provider, is_default);\nCREATE INDEX owner_vault_promotion ON secrets_vault\n (workspace_id, kind, owner_key, principal_id, provider, updated_at DESC, id COLLATE BINARY DESC);\nCREATE TABLE owner_grants (\n entry_id TEXT NOT NULL REFERENCES secrets_vault(id) ON DELETE CASCADE,\n consumer_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (entry_id, consumer_id)\n);\nCREATE INDEX owner_grants_consumer ON owner_grants (consumer_id, entry_id);\n";
4
5
  /** Pin is checked against the DDL in tests; never edit this step after publication. */
5
- export declare const ownerStoreMigration: MigrationStep;
6
+ export declare const ownerStoreMigration: MigrationStep<KyselyKernel<unknown>>;
6
7
  //# sourceMappingURL=0000_owner_store.d.ts.map
@@ -2,5 +2,5 @@
2
2
  * no host opens an owner store for writing, so this history only describes legacy files.
3
3
  */
4
4
  export declare const OWNER_STORE_LEDGER = "owner_migrations";
5
- export declare const ownerStoreMigrations: readonly [import("../../migrate/step.js").MigrationStep];
5
+ export declare const ownerStoreMigrations: readonly [import("@jini-ai/core/contracts/storage").MigrationStep<import("../../kernel/port.js").KyselyKernel<unknown>>];
6
6
  //# sourceMappingURL=index.d.ts.map