@jini-ai/db 0.6.11 → 0.6.15-rc.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 (35) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +76 -0
  3. package/dist/kernel/kernel-core.js +22 -4
  4. package/dist/kernel/owned-transaction.d.ts +15 -0
  5. package/dist/kernel/owned-transaction.js +9 -0
  6. package/dist/kernel/port.d.ts +1 -0
  7. package/dist/kernel/schema-scope.js +6 -1
  8. package/dist/kernel/sqlite/driver.js +20 -3
  9. package/dist/migrate/ddl.d.ts +11 -0
  10. package/dist/migrate/ddl.js +13 -0
  11. package/dist/migrate/index.d.ts +3 -1
  12. package/dist/migrate/index.js +2 -1
  13. package/dist/migrate/legacy-ledger.d.ts +39 -0
  14. package/dist/migrate/legacy-ledger.js +67 -0
  15. package/dist/migrate/runner.d.ts +58 -0
  16. package/dist/migrate/runner.js +79 -9
  17. package/dist/migrate/step.d.ts +1 -1
  18. package/dist/migrate/step.js +1 -1
  19. package/dist/owner-store/index.d.ts +4 -0
  20. package/dist/owner-store/index.js +4 -0
  21. package/dist/owner-store/migrations/0000_owner_store.d.ts +6 -0
  22. package/dist/owner-store/migrations/0000_owner_store.js +36 -0
  23. package/dist/owner-store/migrations/index.d.ts +6 -0
  24. package/dist/owner-store/migrations/index.js +7 -0
  25. package/dist/secrets-vault/repo.sql.d.ts +3 -4
  26. package/dist/secrets-vault/repo.sql.js +12 -2
  27. package/dist/sqlite/checked-client.d.ts +19 -0
  28. package/dist/sqlite/checked-client.js +117 -0
  29. package/dist/sqlite/checked-state.d.ts +32 -0
  30. package/dist/sqlite/checked-state.js +26 -0
  31. package/dist/sqlite/index.d.ts +3 -0
  32. package/dist/sqlite/index.js +3 -0
  33. package/dist/sqlite/transaction.d.ts +29 -0
  34. package/dist/sqlite/transaction.js +80 -0
  35. package/package.json +16 -6
package/CHANGELOG.md CHANGED
@@ -1,3 +1,39 @@
1
+ ## 0.6.13
2
+
3
+ ### Patch Changes
4
+
5
+ - 9138c3b: Leased SQLite transactions release their lease before the next queued kernel transaction takes its turn, so it no longer fails with `transaction_busy`. Checked clients quarantine only uncertain outcomes: a failed COMMIT followed by a successful ROLLBACK, or a stray ROLLBACK with nothing open, leaves the handle usable.
6
+ - aa8de3d: Add opt-in checked SQLite clients and leased transaction sessions, plus batch migration atomicity,
7
+ ordered-prefix history checks, injected clocks and explicit legacy ledger mappings. Existing raw
8
+ clients, transaction signatures and default per-step migration behavior are unchanged.
9
+ - 03dec0a: Preserve credential hint metadata across owner-store backup restores and reject database/key path aliases on Windows and macOS.
10
+ - 506196f: BREAKING (host import path): the owner-store composition moved from `@jini-ai/db/owner-store` to the new
11
+ `@jini-ai/server/owner-store` entry, so `@jini-ai/db` no longer reaches `@jini-ai/platform` or its own
12
+ sibling domains (guard L1 / SI-domain). Moved: `openOwnerStore`, `OwnerStoreRecoveryError`, `OwnerStoreService`,
13
+ `OWNER_WORKSPACE_ID`, `ownerContext`, `exportOwnerStore`, `restoreOwnerStore`, `OwnerStoreBackupError` and the
14
+ `OpenOwnerStore*` / `OwnerStoreDatabase` / `OwnerGrant` / `OwnerPutInput` / `OwnerSyncTarget` types. Behaviour is
15
+ unchanged. `@jini-ai/db/owner-store` keeps `OWNER_STORE_LEDGER`, `ownerStoreMigrations`, `ownerStoreDdl` and
16
+ `ownerStoreMigration`.
17
+
18
+ Migration: import those names from `@jini-ai/server/owner-store` and add `@jini-ai/server` (same version as
19
+ `@jini-ai/db`) to the host's dependencies; that entry uses the optional `@jini-ai/db`, `@jini-ai/platform`
20
+ and `kysely` peers. `OwnerStoreService` additionally accepts an optional `repo`; existing kernel-only
21
+ constructions still work.
22
+
23
+ - Updated dependencies [7479159]
24
+ - Updated dependencies [c31264d]
25
+ - Updated dependencies [0728914]
26
+ - Updated dependencies [6ecbdb2]
27
+ - Updated dependencies [63bacc5]
28
+ - @jini-ai/core@0.6.13
29
+
30
+ ## 0.6.12
31
+
32
+ ### Patch Changes
33
+
34
+ - db: new `@jini-ai/db/owner-store` entry — owner-only SQLite vault with grants, copy-to-site sync and passphrase-sealed backup (uses the optional `better-sqlite3` peer or an injected opener).
35
+ - @jini-ai/core@0.6.12
36
+
1
37
  ## 0.6.11
2
38
 
3
39
  ### Patch Changes
package/README.md CHANGED
@@ -201,6 +201,72 @@ builds the same four definitions for catalog inspection; its display-only defaul
201
201
  - [Unavailable restore mechanisms have no attestation override](docs/decisions/DR-002-restore-point-precondition.md).
202
202
  - [Storage copying takes its schemas from the host](docs/decisions/DR-003-host-owned-schema-copy.md).
203
203
 
204
+ ### Optional checked SQLite transactions and migration policies
205
+
206
+ `@jini-ai/db/sqlite` adds the following object-input APIs:
207
+
208
+ ```ts
209
+ declare function createCheckedSqliteClient(
210
+ required: { database: IntegerSource }, optional?: {}
211
+ ): CheckedSqliteClient;
212
+ declare function withSqliteTransaction<T>(
213
+ required: { client: CheckedSqliteClient; kernel: StorageKernel<unknown>; work: Work<T> },
214
+ optional?: { rollbackOnFailedOutcome?: boolean }
215
+ ): Promise<T>;
216
+ ```
217
+
218
+ The host's `database` must support `statement.safeIntegers(true)`. The factory memoizes one
219
+ borrowed wrapper per handle; `sqliteKernel(client)` supplies its matching kernel. Safe bigint
220
+ cells and write metadata become numbers; overflow throws `SqliteClientError` with code
221
+ `unsafe_integer`. Blobs and floats retain their values. Iteration decodes one row at a time.
222
+ The wrapper's `close()` does nothing. Mixing raw and checked kernel ownership is refused.
223
+ Connection-only imports still load no runtime Kysely dependency; sessions use the supplied kernel.
224
+
225
+ `work({ session })` receives `TransactionSession` with `query({ statement }, {})`,
226
+ `execute({ statement }, {})` and `transaction({ work }, {})`. Statements are Kysely
227
+ `RawBuilder`s. Nested work joins; only the root return value decides whether the optional
228
+ failed-Outcome policy rolls back. Omission or `false` commits resolved values, including
229
+ `{ ok: false }`; `true` rolls that result back and returns the identical object after successful
230
+ cleanup. Thrown errors roll back. Retained sessions, overlapping helpers and entry into existing
231
+ transactions are refused. Uncertain outcomes (a COMMIT that may have applied, or a transaction a
232
+ failed ROLLBACK left open) quarantine the shared wrapper; queued and future SQL fails. A failed
233
+ COMMIT followed by a successful ROLLBACK, or a stray ROLLBACK with nothing open, is not quarantined. Native control errors remain causes of typed `commit_failed` /
234
+ `rollback_failed` errors; combined failures use `AggregateError`. Other codes are `quarantined`,
235
+ `session_expired` and `transaction_busy`. The host retains responsibility for the native handle.
236
+ The exported error constructor is `new SqliteClientError({ code }, { cause })`; its second object
237
+ is optional.
238
+
239
+ `@jini-ai/db/migrate` adds `migrate({ kernel, steps, ledgerTable }, options = {})`, which
240
+ delegates to `runMigrations`. Both accept these optional `MigrationOptions` fields:
241
+
242
+ ```ts
243
+ declare function migrate(
244
+ required: { kernel: StorageKernel<unknown>; steps: readonly MigrationStep[]; ledgerTable: string },
245
+ optional?: Omit<MigrationOptions, "ledgerTable">
246
+ ): Promise<MigrationReport>;
247
+
248
+ interface MigrationExtensions {
249
+ atomicity?: "step" | "batch";
250
+ historyCheck?: "known" | "ordered-prefix";
251
+ clock?: Clock; // @jini-ai/core/primitives, nowMs()
252
+ legacyLedger?: LegacyLedgerMapping;
253
+ }
254
+ interface LegacyLedgerMapping {
255
+ columns: { version: string; name: string; checksum: string; appliedAt: string };
256
+ identities: Readonly<Record<string, { version: number; name: string }>>;
257
+ timestamps?: "database-default" | "iso";
258
+ }
259
+ ```
260
+
261
+ Batch mode requires a kernel-owned transaction and transactional DDL, refuses pending `prepare`
262
+ hooks, backs up outside the transaction and verifies history again under the ledger lock.
263
+ Ordered-prefix checks reject holes before pending work and repeat under that lock. ISO clocks
264
+ are sampled once per inserted row. Legacy mappings require complete, unique positive-safe-integer
265
+ versions ascending in step order and unique nonempty names; identifiers are quoted and history is read by numeric version.
266
+ Existing rows are never rewritten. Mapped timestamps use the database default unless `iso` is
267
+ explicit; supplying a clock with database-default timestamps is refused. The default runner
268
+ retains its standard ledger, known-ID checks and per-step commits.
269
+
204
270
  ### Host database prose
205
271
 
206
272
  `defaultDbMessages` and `DbMessages` are exported from `@jini-ai/db/tools`.
@@ -214,3 +280,13 @@ message replacements remain supported; unspecified runtime fields retain neutral
214
280
  missing-source-table/column formatter subset. Messages never select a schema or rewrite SQL.
215
281
  Persisted `TransferNaming` remains required with no fallback; its display-only catalog
216
282
  examples still default to `app` / `app_`. Keep each host's existing wire names explicit.
283
+
284
+ `@jini-ai/db/owner-store` exports the independent owner schema and pinned migration history.
285
+ The concrete owner-vault assembly moved to `@jini-ai/server/owner-store`; use that entry for
286
+ `openOwnerStore`, `OwnerStoreService` and encrypted backup operations.
287
+
288
+ **Migration (breaking, next release):** replace
289
+ `import { openOwnerStore, OwnerStoreService, exportOwnerStore, restoreOwnerStore, OwnerStoreBackupError, OwnerStoreRecoveryError } from '@jini-ai/db/owner-store'`
290
+ with the same names from `'@jini-ai/server/owner-store'`, and add `@jini-ai/server` (same version as
291
+ `@jini-ai/db`) to the host's dependencies. `OWNER_STORE_LEDGER`, `ownerStoreMigrations`, `ownerStoreDdl`
292
+ and `ownerStoreMigration` stay here.
@@ -1,6 +1,7 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { UnsupportedCapabilityError, } from "./port.js";
3
3
  import { TurnLock } from "./turn-lock.js";
4
+ import { ownedTransactions } from "./owned-transaction.js";
4
5
  /** The turn locks the caller's async context holds, across every kernel in the process. */
5
6
  const heldLocks = new AsyncLocalStorage();
6
7
  /**
@@ -40,9 +41,16 @@ export function buildKernel(driver) {
40
41
  return fn(driver.base);
41
42
  return takingTurn(lock, "shared", async () => scope.run({ kind: "run", db: driver.base }, () => fn(driver.base)));
42
43
  }
43
- async function transaction(fn) {
44
+ function assertOwnedAvailable() {
45
+ if (scope.getStore() !== undefined || joinsForeign()) {
46
+ throw new Error("an owned transaction cannot join an existing run or foreign transaction");
47
+ }
48
+ }
49
+ async function transaction(fn, owned) {
44
50
  require("interactiveTransactions");
45
51
  await driver.ready;
52
+ if (owned !== undefined)
53
+ assertOwnedAvailable();
46
54
  const current = scope.getStore();
47
55
  if (current?.kind === "transaction")
48
56
  return fn();
@@ -50,14 +58,18 @@ export function buildKernel(driver) {
50
58
  throw new Error("transaction() was called inside a run() body; start the transaction first and call run() inside it");
51
59
  }
52
60
  if (joinsForeign())
53
- return fn();
61
+ return scope.run({ kind: "transaction", db: driver.base }, fn);
54
62
  return takingTurn(lock, "exclusive", async () => {
63
+ if (owned !== undefined)
64
+ assertOwnedAvailable();
55
65
  ownTransactions += 1;
56
66
  try {
57
67
  return await driver.begin((tx) => scope.run({ kind: "transaction", db: tx }, fn));
58
68
  }
59
69
  finally {
60
70
  ownTransactions -= 1;
71
+ // Still inside the turn: the next queued caller must not see this owner's state.
72
+ owned?.onSettled?.();
61
73
  }
62
74
  });
63
75
  }
@@ -69,7 +81,7 @@ export function buildKernel(driver) {
69
81
  }
70
82
  await driver.lockKey(current?.db ?? driver.base, key);
71
83
  }
72
- return {
84
+ const kernel = {
73
85
  dialect: driver.dialect,
74
86
  transport: driver.transport,
75
87
  capabilities: driver.capabilities,
@@ -90,9 +102,15 @@ export function buildKernel(driver) {
90
102
  if (scope.getStore()?.kind === "transaction")
91
103
  throw new Error("backupTo() must be called outside a transaction");
92
104
  await driver.ready;
93
- await driver.backup(destPath);
105
+ // A copy must wait for unrelated work to commit or roll back on the shared connection.
106
+ await takingTurn(lock, "exclusive", () => driver.backup(destPath));
94
107
  },
95
108
  close: () => driver.close(),
96
109
  };
110
+ ownedTransactions.set(kernel, {
111
+ assertAvailable: assertOwnedAvailable,
112
+ transaction: (work, optional = {}) => transaction(work, optional),
113
+ });
114
+ return kernel;
97
115
  }
98
116
  //# sourceMappingURL=kernel-core.js.map
@@ -0,0 +1,15 @@
1
+ import type { StorageKernel } from "./port.js";
2
+ /** Private access to the kernel's scope checks; public transactions retain their join semantics. */
3
+ export interface OwnedTransactionControl {
4
+ assertAvailable(): void;
5
+ /** `onSettled` runs after commit/rollback but before the turn lock is released. */
6
+ transaction<T>(work: () => Promise<T>, optional?: {
7
+ onSettled?: () => void;
8
+ }): Promise<T>;
9
+ }
10
+ export declare const ownedTransactions: WeakMap<StorageKernel<unknown>, OwnedTransactionControl>;
11
+ /** Refuse unknown kernels rather than promising atomicity over an executor we do not own. */
12
+ export declare function ownedTransactionOf({ kernel }: {
13
+ kernel: StorageKernel<unknown>;
14
+ }, _optional?: {}): OwnedTransactionControl;
15
+ //# sourceMappingURL=owned-transaction.d.ts.map
@@ -0,0 +1,9 @@
1
+ export const ownedTransactions = new WeakMap();
2
+ /** Refuse unknown kernels rather than promising atomicity over an executor we do not own. */
3
+ export function ownedTransactionOf({ kernel }, _optional = {}) {
4
+ const control = ownedTransactions.get(kernel);
5
+ if (control === undefined)
6
+ throw new Error("an owned transaction requires a kernel built by buildKernel");
7
+ return control;
8
+ }
9
+ //# sourceMappingURL=owned-transaction.js.map
@@ -1,4 +1,5 @@
1
1
  import type { Kysely, RawBuilder } from "kysely";
2
+ export type { RawBuilder } from "kysely";
2
3
  /**
3
4
  * @file The storage kernel port: the ONE async way a repo reaches its database, on every driver.
4
5
  * Package: `@jini-ai/db/kernel` (no driver is imported here; each driver lives in its own subpath).
@@ -1,3 +1,4 @@
1
+ import { ownedTransactions } from "./owned-transaction.js";
1
2
  /**
2
3
  * @file A kernel whose query-builder statements address one Postgres schema: every `run()` body gets
3
4
  * `db.withSchema(schema)` (Kysely's own plugin prefixes each table it names). Used when one
@@ -12,9 +13,13 @@
12
13
  export function scopeToSchema(kernel, schema) {
13
14
  if (kernel.dialect !== "postgres")
14
15
  throw new Error(`schema '${schema}' needs a Postgres kernel, not ${kernel.dialect}`);
15
- return {
16
+ const scoped = {
16
17
  ...kernel,
17
18
  run: (fn) => kernel.run((db) => fn(db.withSchema(schema))),
18
19
  };
20
+ const control = ownedTransactions.get(kernel);
21
+ if (control !== undefined)
22
+ ownedTransactions.set(scoped, control);
23
+ return scoped;
19
24
  }
20
25
  //# sourceMappingURL=schema-scope.js.map
@@ -1,9 +1,9 @@
1
1
  import path from "node:path";
2
2
  import { Kysely, SqliteDialect } from "kysely";
3
3
  import { buildKernel, TurnLock } from "../index.js";
4
+ import { checkedClients, checkedStates, connectionsByKernel, rawKernelClients } from "../../sqlite/checked-state.js";
5
+ import { ownedTransactions } from "../owned-transaction.js";
4
6
  const kernels = new WeakMap();
5
- /** The reverse of `kernels`, plus the owning kernels {@link openSqliteFileKernel} hands out. */
6
- const connectionsByKernel = new WeakMap();
7
7
  /** One turn lock per database FILE, shared by every connection to it in this process. */
8
8
  const fileTurnLocks = new Map();
9
9
  function turnLockFor(client) {
@@ -40,6 +40,11 @@ function bindingShim(client) {
40
40
  }
41
41
  export function sqliteKernel(source) {
42
42
  const client = sqliteClientOf(source);
43
+ const checked = checkedClients.has(client);
44
+ if (checkedStates.has(client) && !checked)
45
+ throw new Error("cannot mix raw and checked SQLite kernel ownership");
46
+ if (!checked)
47
+ rawKernelClients.add(client);
43
48
  const known = kernels.get(client);
44
49
  if (known !== undefined)
45
50
  return known;
@@ -60,7 +65,16 @@ export function sqliteKernel(source) {
60
65
  return result;
61
66
  }
62
67
  catch (error) {
63
- if (client.inTransaction)
68
+ if (checked) {
69
+ try {
70
+ if (client.inTransaction)
71
+ client.exec("ROLLBACK");
72
+ }
73
+ catch (cleanup) {
74
+ throw new AggregateError([error, cleanup], "SQLite transaction and rollback failed");
75
+ }
76
+ }
77
+ else if (client.inTransaction)
64
78
  client.exec("ROLLBACK");
65
79
  throw error;
66
80
  }
@@ -113,6 +127,9 @@ export function openSqliteFileKernel(required, optional = {}) {
113
127
  close: async () => closeSqliteConnection(client),
114
128
  };
115
129
  connectionsByKernel.set(owned, client);
130
+ const control = ownedTransactions.get(kernel);
131
+ if (control !== undefined)
132
+ ownedTransactions.set(owned, control);
116
133
  return owned;
117
134
  }
118
135
  /**
@@ -0,0 +1,11 @@
1
+ import type { StorageKernel } from "../kernel/index.js";
2
+ /**
3
+ * Runs a `;`-separated DDL script one statement at a time; the runner owns the encompassing
4
+ * transaction. Lives here so migration steps outside kernel/migrate need no Kysely import.
5
+ * @complexity O(statements).
6
+ */
7
+ export declare function executeDdl({ kernel, ddl }: {
8
+ kernel: StorageKernel<unknown>;
9
+ ddl: string;
10
+ }, _options?: {}): Promise<void>;
11
+ //# sourceMappingURL=ddl.d.ts.map
@@ -0,0 +1,13 @@
1
+ import { sql } from "kysely";
2
+ /**
3
+ * Runs a `;`-separated DDL script one statement at a time; the runner owns the encompassing
4
+ * transaction. Lives here so migration steps outside kernel/migrate need no Kysely import.
5
+ * @complexity O(statements).
6
+ */
7
+ export async function executeDdl({ kernel, ddl }, _options = {}) {
8
+ // Kysely executes one SQLite statement at a time.
9
+ for (const statement of ddl.split(";").filter(part => part.trim())) {
10
+ await kernel.execute(sql.raw(statement));
11
+ }
12
+ }
13
+ //# sourceMappingURL=ddl.js.map
@@ -2,7 +2,9 @@
2
2
  * @file `@jini-ai/db/migrate`: one migration runner for every dialect. The consumer owns its steps,
3
3
  * their pinned checksums and the ledger table's name (required, no default).
4
4
  */
5
- export { assertValidSteps, hasLedger, type MigrationOptions, type MigrationReport, runMigrations } from "./runner.js";
5
+ export { assertValidSteps, hasLedger, migrate, type MigrationOptions, type MigrationReport, runMigrations } from "./runner.js";
6
+ export type { LegacyLedgerMapping } from "./legacy-ledger.js";
6
7
  export { MIGRATION_ID, MigrationChecksumError, type MigrationContext, type MigrationStep, UnknownAppliedMigrationError, } from "./step.js";
7
8
  export { sourceChecksum } from "./checksum.js";
9
+ export { executeDdl } from "./ddl.js";
8
10
  //# sourceMappingURL=index.d.ts.map
@@ -2,7 +2,8 @@
2
2
  * @file `@jini-ai/db/migrate`: one migration runner for every dialect. The consumer owns its steps,
3
3
  * their pinned checksums and the ledger table's name (required, no default).
4
4
  */
5
- export { assertValidSteps, hasLedger, runMigrations } from "./runner.js";
5
+ export { assertValidSteps, hasLedger, migrate, runMigrations } from "./runner.js";
6
6
  export { MIGRATION_ID, MigrationChecksumError, UnknownAppliedMigrationError, } from "./step.js";
7
7
  export { sourceChecksum } from "./checksum.js";
8
+ export { executeDdl } from "./ddl.js";
8
9
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,39 @@
1
+ import type { MigrationStep } from "./step.js";
2
+ import type { Ledger, LedgerRow } from "./runner.js";
3
+ import type { StorageDialect } from "../kernel/port.js";
4
+ /** Persisted identities remain host-owned; no existing row is rewritten. */
5
+ export interface LegacyLedgerMapping {
6
+ columns: {
7
+ version: string;
8
+ name: string;
9
+ checksum: string;
10
+ appliedAt: string;
11
+ };
12
+ identities: Readonly<Record<string, {
13
+ version: number;
14
+ name: string;
15
+ }>>;
16
+ timestamps?: "database-default" | "iso";
17
+ }
18
+ /** Validate the whole map before backups, DDL or migration work. O(steps + identities). */
19
+ export declare function validateLegacyMapping({ mapping, steps }: {
20
+ mapping: LegacyLedgerMapping;
21
+ steps: readonly MigrationStep[];
22
+ }, _optional?: {}): void;
23
+ export declare function ensureLegacyLedger({ ledger, mapping, dialect }: {
24
+ ledger: Ledger;
25
+ mapping: LegacyLedgerMapping;
26
+ dialect: StorageDialect;
27
+ }, _optional?: {}): Promise<void>;
28
+ /** Read in numeric version order, matching both parts of each persisted identity. */
29
+ export declare function readLegacyLedger({ ledger, mapping }: {
30
+ ledger: Ledger;
31
+ mapping: LegacyLedgerMapping;
32
+ }, _optional?: {}): Promise<LedgerRow[]>;
33
+ export declare function insertLegacyRow({ ledger, mapping, step, timestamp }: {
34
+ ledger: Ledger;
35
+ mapping: LegacyLedgerMapping;
36
+ step: MigrationStep;
37
+ timestamp: () => string;
38
+ }, _optional?: {}): Promise<void>;
39
+ //# sourceMappingURL=legacy-ledger.d.ts.map
@@ -0,0 +1,67 @@
1
+ import { sql } from "kysely";
2
+ /** Validate the whole map before backups, DDL or migration work. O(steps + identities). */
3
+ export function validateLegacyMapping({ mapping, steps }, _optional = {}) {
4
+ const columns = Object.values(mapping.columns);
5
+ if (columns.some((column) => typeof column !== "string" || column.length === 0) || new Set(columns).size !== 4) {
6
+ throw new Error("legacy ledger columns must be four distinct nonempty identifiers");
7
+ }
8
+ let previous = 0;
9
+ const names = new Set();
10
+ for (const step of steps) {
11
+ const identity = mapping.identities[step.id];
12
+ if (!Object.hasOwn(mapping.identities, step.id) || identity === undefined)
13
+ throw new Error(`missing legacy identity for ${step.id}`);
14
+ validateIdentity({ identity });
15
+ // Rows are read back in version order, so versions must ascend with the steps for an ordered-prefix check.
16
+ if (identity.version <= previous || names.has(identity.name))
17
+ throw new Error("legacy identities must be unique with versions ascending in step order");
18
+ previous = identity.version;
19
+ names.add(identity.name);
20
+ }
21
+ if (Object.keys(mapping.identities).length !== steps.length)
22
+ throw new Error("legacy identities must match the supplied steps");
23
+ }
24
+ function validateIdentity({ identity }, _optional = {}) {
25
+ if (!Number.isSafeInteger(identity.version) || identity.version <= 0)
26
+ throw new Error("legacy versions must be positive safe integers");
27
+ if (typeof identity.name !== "string" || identity.name.length === 0)
28
+ throw new Error("legacy names must be nonempty strings");
29
+ }
30
+ export async function ensureLegacyLedger({ ledger, mapping, dialect }, _optional = {}) {
31
+ const c = mapping.columns;
32
+ // Postgres integer is only 32-bit; mapped versions accept the full safe JS integer range.
33
+ const versionType = dialect === "sqlite" ? "integer" : "bigint";
34
+ await ledger.run((db) => db.schema.createTable(ledger.table).ifNotExists()
35
+ .addColumn(c.version, versionType, (column) => column.primaryKey())
36
+ .addColumn(c.name, "text", (column) => column.notNull())
37
+ .addColumn(c.checksum, "text", (column) => column.notNull())
38
+ .addColumn(c.appliedAt, "text", (column) => column.notNull().defaultTo(sql `CURRENT_TIMESTAMP`))
39
+ .execute());
40
+ }
41
+ /** Read in numeric version order, matching both parts of each persisted identity. */
42
+ export async function readLegacyLedger({ ledger, mapping }, _optional = {}) {
43
+ const c = mapping.columns;
44
+ const byVersion = new Map(Object.entries(mapping.identities).map(([id, identity]) => [identity.version, { id, ...identity }]));
45
+ const rows = await ledger.run((db) => db.selectFrom(ledger.table).select([
46
+ sql `${sql.id(c.version)}`.as("version"),
47
+ sql `${sql.id(c.name)}`.as("name"),
48
+ sql `${sql.id(c.checksum)}`.as("checksum"),
49
+ sql `${sql.id(c.appliedAt)}`.as("applied_at"),
50
+ ]).orderBy(sql.id(c.version)).execute());
51
+ return rows.map((row) => {
52
+ const identity = byVersion.get(row.version);
53
+ if (identity !== undefined && identity.name !== row.name)
54
+ throw new Error(`legacy migration name drift at version ${row.version}`);
55
+ return { id: identity?.id ?? `legacy:${row.version}:${row.name}`, checksum: row.checksum, applied_at: row.applied_at };
56
+ });
57
+ }
58
+ export async function insertLegacyRow({ ledger, mapping, step, timestamp }, _optional = {}) {
59
+ const c = mapping.columns;
60
+ const identity = mapping.identities[step.id];
61
+ const row = { [c.version]: identity.version, [c.name]: identity.name, [c.checksum]: step.checksum };
62
+ if (mapping.timestamps === "iso")
63
+ row[c.appliedAt] = timestamp();
64
+ // The builder (not raw SQL) so the ledger's `withSchema` also places this insert.
65
+ await ledger.run((db) => db.insertInto(ledger.table).values(row).execute());
66
+ }
67
+ //# sourceMappingURL=legacy-ledger.js.map
@@ -1,14 +1,65 @@
1
+ import { type Kysely } from "kysely";
2
+ import { type Clock } from "@jini-ai/core/primitives";
1
3
  import { type StorageKernel } from "../kernel/index.js";
4
+ import { type LegacyLedgerMapping } from "./legacy-ledger.js";
2
5
  import { type MigrationStep } from "./step.js";
6
+ /**
7
+ * @file The migration runner: applies an ordered list of {@link MigrationStep}s to one database on
8
+ * any dialect and records each in a ledger table the consumer names (required, no default: this
9
+ * package ships no tables, so no name of its own can leak into a consumer's database).
10
+ *
11
+ * - Default ledger `<ledgerTable>(id, checksum, applied_at)`, created by the runner inside the first step's
12
+ * transaction (so a step's pre-change backup has no trace of the runner), same on every dialect.
13
+ * - Before anything is applied, every recorded id must be one this runtime knows
14
+ * (unless an additive history opts into `allowUnknownApplied`)
15
+ * ({@link UnknownAppliedMigrationError}) with the checksum this runtime has
16
+ * ({@link MigrationChecksumError}). Nothing is applied on a mismatch.
17
+ * - Serialized: by default each pending step runs in ONE kernel transaction that first takes
18
+ * `lockKey(<ledgerTable>)` (Postgres advisory lock; SQLite's `BEGIN IMMEDIATE` write lock) and
19
+ * re-reads and verifies the full ledger, so two processes starting at once apply a step exactly once
20
+ * and an older runtime refuses history committed by a newer one while it was waiting.
21
+ * - A kernel without interactive transactions is refused (`require`), never downgraded.
22
+ * - Given {@link MigrationOptions.backupPath}, a database that already holds tables is copied there
23
+ * once, outside any transaction, before the first pending step (ledger absent or behind). Nothing
24
+ * pending, an empty database or a driver without `backup` (Postgres): no copy.
25
+ * - One runner, several histories: each history names its own ledger
26
+ * ({@link MigrationOptions.ledgerTable}) and, on Postgres, may name the schema that ledger lives in
27
+ * ({@link MigrationOptions.schema}). Ledger statements
28
+ * go through Kysely `withSchema`, never `SET search_path` (no session state on a shared PGlite).
29
+ */
30
+ export interface LedgerRow {
31
+ id: string;
32
+ checksum: string;
33
+ applied_at: string;
34
+ }
35
+ type LedgerDb = Record<string, LedgerRow>;
3
36
  export interface MigrationOptions {
4
37
  /** The ledger table (REQUIRED, no default); also the migration lock's key. */
5
38
  ledgerTable: string;
39
+ /** Additive host histories may be opened by an older runtime; known checksums still must match. */
40
+ allowUnknownApplied?: boolean;
6
41
  /** Where to copy an existing database before the first pending step changes it (see the file header). */
7
42
  backupPath?: string;
8
43
  /** Postgres only: the schema holding the ledger, created with it when missing. */
9
44
  schema?: string;
10
45
  /** Names the newer runtime in {@link UnknownAppliedMigrationError}'s message (default "version"). */
11
46
  appName?: string;
47
+ /** Opt in to one owned transaction for the entire pending batch. Default: per-step commits. */
48
+ atomicity?: "step" | "batch";
49
+ /** Opt in to requiring recorded history to be an exact prefix of the supplied steps. */
50
+ historyCheck?: "known" | "ordered-prefix";
51
+ /** Sampled once for each inserted ISO timestamp, never for already-recorded rows. */
52
+ clock?: Clock;
53
+ /** Explicit persisted identities and column names for an existing version/name ledger. */
54
+ legacyLedger?: LegacyLedgerMapping;
55
+ }
56
+ /** Where one history's ledger lives, resolved from {@link MigrationOptions}. */
57
+ export interface Ledger {
58
+ readonly table: string;
59
+ readonly schema: string | undefined;
60
+ readonly lockKey: string;
61
+ readonly mapping: LegacyLedgerMapping | undefined;
62
+ run<T>(fn: (db: Kysely<LedgerDb>) => Promise<T>): Promise<T>;
12
63
  }
13
64
  export interface MigrationReport {
14
65
  /** Steps this call applied, in order. */
@@ -19,6 +70,12 @@ export interface MigrationReport {
19
70
  }
20
71
  /** Throws on duplicate, unordered or malformed ids and on a checksum that is not sha256 hex. */
21
72
  export declare function assertValidSteps(steps: readonly MigrationStep[]): void;
73
+ /** Object-input facade over the existing runner; all extensions remain opt-in. */
74
+ export declare function migrate(required: {
75
+ kernel: StorageKernel<unknown>;
76
+ steps: readonly MigrationStep[];
77
+ ledgerTable: string;
78
+ }, optional?: Omit<MigrationOptions, "ledgerTable">): Promise<MigrationReport>;
22
79
  /**
23
80
  * Applies every pending step of `steps`, in order, to `kernel`'s database.
24
81
  *
@@ -30,4 +87,5 @@ export declare function assertValidSteps(steps: readonly MigrationStep[]): void;
30
87
  export declare function runMigrations(kernel: StorageKernel<unknown>, steps: readonly MigrationStep[], options: MigrationOptions): Promise<MigrationReport>;
31
88
  /** True when `kernel`'s database has the ledger `ledgerTable` (it has been through {@link runMigrations}). */
32
89
  export declare function hasLedger(kernel: StorageKernel<unknown>, ledgerTable: string): Promise<boolean>;
90
+ export {};
33
91
  //# sourceMappingURL=runner.d.ts.map
@@ -1,7 +1,10 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { sql } from "kysely";
4
+ import { nowIso } from "@jini-ai/core/primitives";
4
5
  import { listTables, tableExists } from "../kernel/index.js";
6
+ import { ownedTransactionOf } from "../kernel/owned-transaction.js";
7
+ import { ensureLegacyLedger, insertLegacyRow, readLegacyLedger, validateLegacyMapping } from "./legacy-ledger.js";
5
8
  import { MIGRATION_ID, MigrationChecksumError, UnknownAppliedMigrationError, } from "./step.js";
6
9
  function ledgerFor(kernel, options) {
7
10
  const table = options.ledgerTable;
@@ -15,6 +18,7 @@ function ledgerFor(kernel, options) {
15
18
  table,
16
19
  schema,
17
20
  lockKey: schema === undefined ? table : `${schema}.${table}`,
21
+ mapping: options.legacyLedger,
18
22
  run: (fn) => store.run((db) => fn(schema === undefined ? db : db.withSchema(schema))),
19
23
  };
20
24
  }
@@ -37,6 +41,8 @@ export function assertValidSteps(steps) {
37
41
  async function ensureLedger(kernel, ledger) {
38
42
  if (ledger.schema !== undefined)
39
43
  await kernel.run((db) => db.schema.createSchema(ledger.schema).ifNotExists().execute());
44
+ if (ledger.mapping !== undefined)
45
+ return ensureLegacyLedger({ ledger, mapping: ledger.mapping, dialect: kernel.dialect });
40
46
  await ledger.run((db) => db.schema
41
47
  .createTable(ledger.table)
42
48
  .ifNotExists()
@@ -46,18 +52,80 @@ async function ensureLedger(kernel, ledger) {
46
52
  .execute());
47
53
  }
48
54
  async function readLedger(ledger) {
55
+ if (ledger.mapping !== undefined)
56
+ return readLegacyLedger({ ledger, mapping: ledger.mapping });
49
57
  return ledger.run((db) => db.selectFrom(ledger.table).selectAll().orderBy("id").execute());
50
58
  }
51
- function verifyRecorded(rows, steps, appName) {
59
+ function verifyRecorded(rows, steps, options) {
52
60
  const known = new Map(steps.map((step) => [step.id, step]));
53
61
  const unknown = rows.filter((row) => !known.has(row.id)).map((row) => row.id);
54
- if (unknown.length > 0)
55
- throw new UnknownAppliedMigrationError(unknown, appName);
62
+ if (unknown.length > 0 && !options.allowUnknownApplied)
63
+ throw new UnknownAppliedMigrationError(unknown, options.appName);
56
64
  for (const row of rows) {
57
65
  const step = known.get(row.id);
66
+ if (!step)
67
+ continue;
58
68
  if (row.checksum !== step.checksum)
59
69
  throw new MigrationChecksumError(row.id, row.checksum, step.checksum);
60
70
  }
71
+ if (options.historyCheck === "ordered-prefix" && rows.some((row, index) => row.id !== steps[index]?.id)) {
72
+ throw new Error("recorded migration history is not an ordered prefix");
73
+ }
74
+ }
75
+ async function insertRow({ ledger, step, options }, _optional = {}) {
76
+ const timestamp = () => options.clock === undefined ? new Date().toISOString() : nowIso({ clock: options.clock });
77
+ if (ledger.mapping !== undefined)
78
+ return insertLegacyRow({ ledger, mapping: ledger.mapping, step, timestamp });
79
+ await ledger.run((db) => db.insertInto(ledger.table).values({ id: step.id, checksum: step.checksum, applied_at: timestamp() }).execute());
80
+ }
81
+ async function recordedStep({ ledger, step, steps, options }, _optional = {}) {
82
+ const rows = await readLedger(ledger);
83
+ verifyRecorded(rows, steps, options);
84
+ return rows.some((row) => row.id === step.id);
85
+ }
86
+ function validateExtensions({ options, steps }, _optional = {}) {
87
+ if (options.legacyLedger === undefined)
88
+ return;
89
+ validateLegacyMapping({ mapping: options.legacyLedger, steps });
90
+ if (options.clock !== undefined && options.legacyLedger.timestamps !== "iso") {
91
+ throw new Error("a migration clock requires ISO legacy ledger timestamps");
92
+ }
93
+ }
94
+ function assertBatchSteps({ steps, done }, _optional = {}) {
95
+ if (steps.some((step) => !done.has(step.id) && step.prepare !== undefined))
96
+ throw new Error("batch migrations cannot run pending prepare hooks");
97
+ }
98
+ async function applyBatch({ kernel, ledger, steps, options, context, report }, _optional = {}) {
99
+ const control = ownedTransactionOf({ kernel });
100
+ kernel.require("transactionalDdl");
101
+ control.assertAvailable();
102
+ const initiallyDone = new Set(report.alreadyApplied);
103
+ const pending = steps.filter((step) => !initiallyDone.has(step.id));
104
+ assertBatchSteps({ steps, done: initiallyDone });
105
+ if (pending.length === 0)
106
+ return report;
107
+ await backUpBeforeChange(kernel, context);
108
+ return control.transaction(async () => {
109
+ await kernel.lockKey(ledger.lockKey);
110
+ await ensureLedger(kernel, ledger);
111
+ const rows = await readLedger(ledger);
112
+ verifyRecorded(rows, steps, options);
113
+ const done = new Set(rows.map((row) => row.id));
114
+ assertBatchSteps({ steps, done });
115
+ report.alreadyApplied = [...done];
116
+ for (const step of steps) {
117
+ if (done.has(step.id))
118
+ continue;
119
+ await step.up(kernel, context);
120
+ await insertRow({ ledger, step, options });
121
+ report.applied.push(step.id);
122
+ }
123
+ return report;
124
+ });
125
+ }
126
+ /** Object-input facade over the existing runner; all extensions remain opt-in. */
127
+ export function migrate(required, optional = {}) {
128
+ return runMigrations(required.kernel, required.steps, { ...optional, ledgerTable: required.ledgerTable });
61
129
  }
62
130
  /**
63
131
  * Applies every pending step of `steps`, in order, to `kernel`'s database.
@@ -70,14 +138,19 @@ function verifyRecorded(rows, steps, appName) {
70
138
  export async function runMigrations(kernel, steps, options) {
71
139
  assertValidSteps(steps);
72
140
  kernel.require("interactiveTransactions");
141
+ validateExtensions({ options, steps });
142
+ if (options.atomicity === "batch")
143
+ ownedTransactionOf({ kernel }).assertAvailable();
73
144
  const ledger = ledgerFor(kernel, options);
74
145
  const recorded = (await ledgerExists(kernel, ledger)) ? await readLedger(ledger) : [];
75
- verifyRecorded(recorded, steps, options.appName);
146
+ verifyRecorded(recorded, steps, options);
76
147
  const report = { applied: [], alreadyApplied: recorded.map((row) => row.id), notes: [] };
77
148
  const note = (message) => {
78
149
  report.notes.push(message);
79
150
  };
80
151
  const context = options.backupPath === undefined ? { note } : { backupPath: options.backupPath, note };
152
+ if (options.atomicity === "batch")
153
+ return applyBatch({ kernel, ledger, steps, options, context, report });
81
154
  const done = new Set(report.alreadyApplied);
82
155
  let backedUp = false;
83
156
  for (const step of steps) {
@@ -90,13 +163,10 @@ export async function runMigrations(kernel, steps, options) {
90
163
  const applied = await kernel.transaction(async () => {
91
164
  await kernel.lockKey(ledger.lockKey);
92
165
  await ensureLedger(kernel, ledger);
93
- const row = await ledger.run((db) => db.selectFrom(ledger.table).selectAll().where("id", "=", step.id).executeTakeFirst());
94
- if (row !== undefined) {
95
- verifyRecorded([row], steps, options.appName);
166
+ if (await recordedStep({ ledger, step, steps, options }))
96
167
  return false;
97
- }
98
168
  await step.up(kernel, context);
99
- await ledger.run((db) => db.insertInto(ledger.table).values({ id: step.id, checksum: step.checksum, applied_at: new Date().toISOString() }).execute());
169
+ await insertRow({ ledger, step, options });
100
170
  return true;
101
171
  });
102
172
  (applied ? report.applied : report.alreadyApplied).push(step.id);
@@ -1,7 +1,7 @@
1
1
  import type { StorageKernel } from "../kernel/index.js";
2
2
  /**
3
3
  * @file What a migration step is. Steps form ONE ordered history for every dialect; the runner
4
- * (`runner.ts`) applies each pending one in its own transaction and records it in the consumer's
4
+ * (`runner.ts`) by default applies each pending one in its own transaction and records it in the consumer's
5
5
  * ledger table.
6
6
  */
7
7
  /** `NNNN_snake_name`. Ordered by the number; never renamed or reused once shipped. */
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @file What a migration step is. Steps form ONE ordered history for every dialect; the runner
3
- * (`runner.ts`) applies each pending one in its own transaction and records it in the consumer's
3
+ * (`runner.ts`) by default applies each pending one in its own transaction and records it in the consumer's
4
4
  * ledger table.
5
5
  */
6
6
  /** `NNNN_snake_name`. Ordered by the number; never renamed or reused once shipped. */
@@ -0,0 +1,4 @@
1
+ /** Legacy owner database schema history; the read-only reader lives in @jini-ai/server/owner-store. */
2
+ export { OWNER_STORE_LEDGER, ownerStoreMigrations } from "./migrations/index.js";
3
+ export { ownerStoreDdl, ownerStoreMigration } from "./migrations/0000_owner_store.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,4 @@
1
+ /** Legacy owner database schema history; the read-only reader lives in @jini-ai/server/owner-store. */
2
+ export { OWNER_STORE_LEDGER, ownerStoreMigrations } from "./migrations/index.js";
3
+ export { ownerStoreDdl, ownerStoreMigration } from "./migrations/0000_owner_store.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ import type { MigrationStep } from "../../migrate/step.js";
2
+ /** Owner-only history: no site tables or foreign workspace records are required. */
3
+ 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
+ /** Pin is checked against the DDL in tests; never edit this step after publication. */
5
+ export declare const ownerStoreMigration: MigrationStep;
6
+ //# sourceMappingURL=0000_owner_store.d.ts.map
@@ -0,0 +1,36 @@
1
+ import { executeDdl } from "../../migrate/ddl.js";
2
+ /** Owner-only history: no site tables or foreign workspace records are required. */
3
+ export const ownerStoreDdl = `
4
+ CREATE TABLE secrets_vault (
5
+ workspace_id TEXT NOT NULL, id TEXT NOT NULL UNIQUE, kind TEXT NOT NULL, owner_key TEXT NOT NULL,
6
+ principal_id TEXT, binding TEXT, provider TEXT, label TEXT NOT NULL, is_default INTEGER NOT NULL,
7
+ revision INTEGER NOT NULL, sealed_key_id TEXT, sealed_ciphertext TEXT, sealed_nonce TEXT, sealed_alg TEXT,
8
+ last4 TEXT, token_length INTEGER, meta TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
9
+ PRIMARY KEY (workspace_id, id)
10
+ );
11
+ CREATE UNIQUE INDEX owner_vault_default ON secrets_vault
12
+ (workspace_id, kind, owner_key, (principal_id IS NULL), coalesce(principal_id, ''),
13
+ (provider IS NULL), coalesce(provider, '')) WHERE is_default = 1;
14
+ CREATE UNIQUE INDEX owner_vault_label ON secrets_vault
15
+ (workspace_id, kind, owner_key, (principal_id IS NULL), coalesce(principal_id, ''),
16
+ (provider IS NULL), coalesce(provider, ''), label);
17
+ CREATE INDEX owner_vault_lookup ON secrets_vault
18
+ (workspace_id, kind, owner_key, principal_id, provider, is_default);
19
+ CREATE INDEX owner_vault_promotion ON secrets_vault
20
+ (workspace_id, kind, owner_key, principal_id, provider, updated_at DESC, id COLLATE BINARY DESC);
21
+ CREATE TABLE owner_grants (
22
+ entry_id TEXT NOT NULL REFERENCES secrets_vault(id) ON DELETE CASCADE,
23
+ consumer_id TEXT NOT NULL, created_at TEXT NOT NULL,
24
+ PRIMARY KEY (entry_id, consumer_id)
25
+ );
26
+ CREATE INDEX owner_grants_consumer ON owner_grants (consumer_id, entry_id);
27
+ `;
28
+ /** Pin is checked against the DDL in tests; never edit this step after publication. */
29
+ export const ownerStoreMigration = {
30
+ id: "0000_owner_store",
31
+ checksum: "ea2c33cf1835f6b1db0f52a4de3419aaf8c1a2e2edeece1e2b3240c517592446",
32
+ async up(kernel) {
33
+ await executeDdl({ kernel, ddl: ownerStoreDdl });
34
+ },
35
+ };
36
+ //# sourceMappingURL=0000_owner_store.js.map
@@ -0,0 +1,6 @@
1
+ /** Independent history: a site migration ledger must never govern this database. Read-only now:
2
+ * no host opens an owner store for writing, so this history only describes legacy files.
3
+ */
4
+ export declare const OWNER_STORE_LEDGER = "owner_migrations";
5
+ export declare const ownerStoreMigrations: readonly [import("../../migrate/step.js").MigrationStep];
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,7 @@
1
+ import { ownerStoreMigration } from "./0000_owner_store.js";
2
+ /** Independent history: a site migration ledger must never govern this database. Read-only now:
3
+ * no host opens an owner store for writing, so this history only describes legacy files.
4
+ */
5
+ export const OWNER_STORE_LEDGER = "owner_migrations";
6
+ export const ownerStoreMigrations = [ownerStoreMigration];
7
+ //# sourceMappingURL=index.js.map
@@ -64,10 +64,9 @@ export declare class SqlSecretsVaultRepo implements VaultRepoPort {
64
64
  findDefault(input: VaultDefaultQuery, _options?: VaultOptions): Promise<VaultRecord | null>;
65
65
  list(input: VaultQuery, _options?: VaultOptions): Promise<VaultRecord[]>;
66
66
  private assertLabelAvailable;
67
- put(input: {
68
- record: VaultRecord;
69
- expectedRevision: number | null;
70
- }, _options?: VaultOptions): Promise<VaultRecord>;
67
+ /** One bounded existence query only when the caller leaves default placement unspecified. */
68
+ private defaultForPut;
69
+ put(input: Parameters<VaultRepoPort["put"]>[0], _options?: VaultOptions): Promise<VaultRecord>;
71
70
  /** Top-level targeted JSON writes preserve ciphertext/default fields; caller validates merged meta. */
72
71
  patchMeta(input: {
73
72
  workspaceId: string;
@@ -111,6 +111,15 @@ export class SqlSecretsVaultRepo {
111
111
  throw new VaultError({ code: "conflict" });
112
112
  }
113
113
  }
114
+ /** One bounded existence query only when the caller leaves default placement unspecified. */
115
+ async defaultForPut({ record, existing, moved }, _options = {}) {
116
+ if (record.isDefault !== undefined)
117
+ return record.isDefault;
118
+ if (existing !== null && !moved)
119
+ return false;
120
+ return !await this.kernel.run(db => this.scoped({ db, input: this.group(record) })
121
+ .select("id").limit(1).executeTakeFirst());
122
+ }
114
123
  async put(input, _options = {}) {
115
124
  return this.write(input.record.workspaceId, async () => {
116
125
  const existing = await this.find(input.record);
@@ -118,8 +127,9 @@ export class SqlSecretsVaultRepo {
118
127
  const scope = this.group(input.record);
119
128
  const moved = existing !== null && existing.provider !== input.record.provider;
120
129
  await this.assertLabelAvailable({ record: input.record, existing, moved, scope });
121
- const hasGroup = (existing !== null && !moved) || input.record.isDefault || Boolean(await this.kernel.run(db => this.scoped({ db, input: scope }).select("id").limit(1).executeTakeFirst()));
122
- const saved = { ...input.record, isDefault: input.record.isDefault || !hasGroup };
130
+ // Auto-select the first row so an ordinary save is usable without a separate default action.
131
+ // Explicit false opts out, keeping unattached project keys from becoming vendor defaults.
132
+ const saved = { ...input.record, isDefault: await this.defaultForPut({ record: input.record, existing, moved }) };
123
133
  // Clear before insert/update so a partial UNIQUE default index never sees two defaults.
124
134
  if (saved.isDefault)
125
135
  await this.kernel.run(db => db.updateTable("secrets_vault")
@@ -0,0 +1,19 @@
1
+ import type { SqliteClient, SqliteStatement } from "./types.js";
2
+ export interface IntegerStatement extends SqliteStatement {
3
+ safeIntegers(enabled: boolean): unknown;
4
+ }
5
+ export type IntegerSource = Omit<SqliteClient, "prepare"> & {
6
+ prepare(source: string): IntegerStatement;
7
+ };
8
+ export interface CheckedSqliteClient extends SqliteClient {
9
+ readonly checked: true;
10
+ }
11
+ /**
12
+ * Borrow a native handle with exact integer decoding and shared quarantine/lease state.
13
+ * Memoized by handle; refuses handles already owned by a raw kernel. Does not close the host handle.
14
+ * @complexity O(cells) per result, O(1) additional rows for lazy iteration.
15
+ */
16
+ export declare function createCheckedSqliteClient(required: {
17
+ database: IntegerSource;
18
+ }, _optional?: {}): CheckedSqliteClient;
19
+ //# sourceMappingURL=checked-client.d.ts.map
@@ -0,0 +1,117 @@
1
+ import { assertCheckedAvailable, checkedClients, checkedStates, rawKernelClients, SqliteClientError } from "./checked-state.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ const clients = new WeakMap();
4
+ function numberCell({ value }, _optional = {}) {
5
+ if (typeof value !== "bigint")
6
+ return value;
7
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
8
+ throw new SqliteClientError({ code: "unsafe_integer" });
9
+ }
10
+ return Number(value);
11
+ }
12
+ /** Decode cells only, preserving blobs and other non-integer values by identity. */
13
+ function decodeRow({ row }, _optional = {}) {
14
+ if (Array.isArray(row))
15
+ return row.map((value) => numberCell({ value }));
16
+ if (row === null || typeof row !== "object" || ArrayBuffer.isView(row))
17
+ return numberCell({ value: row });
18
+ return Object.fromEntries(Object.entries(row).map(([key, value]) => [key, numberCell({ value })]));
19
+ }
20
+ function checkedStatement({ statement, state }, _optional = {}) {
21
+ statement.safeIntegers(true);
22
+ return {
23
+ get reader() { return statement.reader; },
24
+ all(...parameters) {
25
+ assertCheckedAvailable({ state });
26
+ return statement.all(...parameters).map((row) => decodeRow({ row }));
27
+ },
28
+ run(...parameters) {
29
+ assertCheckedAvailable({ state });
30
+ const result = statement.run(...parameters);
31
+ return { changes: numberCell({ value: result.changes }), lastInsertRowid: numberCell({ value: result.lastInsertRowid }) };
32
+ },
33
+ *iterate(...parameters) {
34
+ assertCheckedAvailable({ state });
35
+ const iterator = statement.iterate(...parameters);
36
+ try {
37
+ while (true) {
38
+ assertCheckedAvailable({ state });
39
+ const next = iterator.next();
40
+ if (next.done)
41
+ return;
42
+ yield decodeRow({ row: next.value });
43
+ }
44
+ }
45
+ finally {
46
+ iterator.return?.();
47
+ }
48
+ },
49
+ };
50
+ }
51
+ /** Quarantine only an uncertain outcome: a transaction still open, or a COMMIT that may have applied. */
52
+ function controlFailure({ database, state, command, cause }, _optional = {}) {
53
+ const open = database.inTransaction;
54
+ if (command === "COMMIT") {
55
+ state.quarantined = true;
56
+ // Still open: nothing applied yet, so a following ROLLBACK can settle it and lift the quarantine.
57
+ state.cleanupAllowed = open;
58
+ return new SqliteClientError({ code: "commit_failed" }, { cause });
59
+ }
60
+ state.quarantined = open;
61
+ return new SqliteClientError({ code: "rollback_failed" }, { cause });
62
+ }
63
+ function execChecked({ database, state, source }, _optional = {}) {
64
+ const command = source.trim().replace(/;$/, "").toUpperCase();
65
+ const cleanup = command === "ROLLBACK" && state.cleanupAllowed;
66
+ // Cleanup must remain possible after a failed COMMIT quarantines the handle.
67
+ if (!cleanup)
68
+ assertCheckedAvailable({ state });
69
+ if (command === "ROLLBACK")
70
+ state.cleanupAllowed = false;
71
+ try {
72
+ const result = database.exec(source);
73
+ if (cleanup)
74
+ state.quarantined = false;
75
+ return result;
76
+ }
77
+ catch (cause) {
78
+ if (command !== "COMMIT" && command !== "ROLLBACK")
79
+ throw cause;
80
+ throw controlFailure({ database, state, command, cause });
81
+ }
82
+ }
83
+ /**
84
+ * Borrow a native handle with exact integer decoding and shared quarantine/lease state.
85
+ * Memoized by handle; refuses handles already owned by a raw kernel. Does not close the host handle.
86
+ * @complexity O(cells) per result, O(1) additional rows for lazy iteration.
87
+ */
88
+ export function createCheckedSqliteClient(required, _optional = {}) {
89
+ const { database } = required;
90
+ const known = clients.get(database);
91
+ if (known !== undefined)
92
+ return known;
93
+ if (rawKernelClients.has(database))
94
+ throw new Error("cannot mix raw and checked SQLite kernel ownership");
95
+ const state = { context: new AsyncLocalStorage(), quarantined: false, cleanupAllowed: false };
96
+ const client = {
97
+ checked: true,
98
+ get memory() { return database.memory; },
99
+ get name() { return database.name; },
100
+ get inTransaction() { return database.inTransaction; },
101
+ exec: (source) => execChecked({ database, state, source }),
102
+ prepare(source) {
103
+ assertCheckedAvailable({ state });
104
+ return checkedStatement({ statement: database.prepare(source), state });
105
+ },
106
+ pragma(source) { assertCheckedAvailable({ state }); return database.pragma(source); },
107
+ backup(destination) { assertCheckedAvailable({ state }); return database.backup(destination); },
108
+ close() { },
109
+ };
110
+ clients.set(database, client);
111
+ clients.set(client, client);
112
+ checkedStates.set(database, state);
113
+ checkedStates.set(client, state);
114
+ checkedClients.add(client);
115
+ return client;
116
+ }
117
+ //# sourceMappingURL=checked-client.js.map
@@ -0,0 +1,32 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { SqliteClient } from "./types.js";
3
+ import type { StorageKernel } from "../kernel/port.js";
4
+ export interface SqliteLease {
5
+ active: boolean;
6
+ acquired: boolean;
7
+ }
8
+ export interface CheckedState {
9
+ context: AsyncLocalStorage<SqliteLease>;
10
+ lease?: SqliteLease;
11
+ quarantined: boolean;
12
+ cleanupAllowed: boolean;
13
+ }
14
+ export declare const checkedStates: WeakMap<SqliteClient, CheckedState>;
15
+ export declare const checkedClients: WeakSet<SqliteClient>;
16
+ export declare const rawKernelClients: WeakSet<SqliteClient>;
17
+ /** The reverse of the driver's kernel cache, plus the owning kernels openSqliteFileKernel returns. */
18
+ export declare const connectionsByKernel: WeakMap<StorageKernel<unknown>, SqliteClient>;
19
+ /** A typed failure from the opt-in checked client; the native failure remains its cause. */
20
+ export declare class SqliteClientError extends Error {
21
+ readonly code: "unsafe_integer" | "commit_failed" | "rollback_failed" | "quarantined" | "session_expired" | "transaction_busy";
22
+ constructor(required: {
23
+ code: SqliteClientError["code"];
24
+ }, optional?: {
25
+ cause?: unknown;
26
+ });
27
+ }
28
+ /** Checks both queued work's lifetime and the shared native handle's health. */
29
+ export declare function assertCheckedAvailable({ state }: {
30
+ state: CheckedState;
31
+ }, _optional?: {}): void;
32
+ //# sourceMappingURL=checked-state.d.ts.map
@@ -0,0 +1,26 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ export const checkedStates = new WeakMap();
3
+ export const checkedClients = new WeakSet();
4
+ export const rawKernelClients = new WeakSet();
5
+ /** The reverse of the driver's kernel cache, plus the owning kernels openSqliteFileKernel returns. */
6
+ export const connectionsByKernel = new WeakMap();
7
+ /** A typed failure from the opt-in checked client; the native failure remains its cause. */
8
+ export class SqliteClientError extends Error {
9
+ code;
10
+ constructor(required, optional = {}) {
11
+ super(required.code, { cause: optional.cause });
12
+ this.code = required.code;
13
+ this.name = "SqliteClientError";
14
+ }
15
+ }
16
+ /** Checks both queued work's lifetime and the shared native handle's health. */
17
+ export function assertCheckedAvailable({ state }, _optional = {}) {
18
+ if (state.quarantined)
19
+ throw new SqliteClientError({ code: "quarantined" });
20
+ const current = state.context.getStore();
21
+ if (current?.active === false)
22
+ throw new SqliteClientError({ code: "session_expired" });
23
+ if (state.lease?.acquired === true && current !== state.lease)
24
+ throw new SqliteClientError({ code: "transaction_busy" });
25
+ }
26
+ //# sourceMappingURL=checked-state.js.map
@@ -1,5 +1,8 @@
1
1
  /** SQLite connection policy and restore operations; inject the consumer's opener. */
2
2
  export type { SqliteClient, SqliteOpener, SqliteOpenOptions, SqliteStatement } from "./types.js";
3
+ export { createCheckedSqliteClient, type CheckedSqliteClient, type IntegerSource, type IntegerStatement } from "./checked-client.js";
4
+ export { SqliteClientError } from "./checked-state.js";
5
+ export { withSqliteTransaction, type TransactionSession, type Work } from "./transaction.js";
3
6
  export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
4
7
  export { SqliteDbOpsAdapter, type SqliteDbOpsAdapterDeps } from "./db-ops.js";
5
8
  export type { SqliteBackupSource, SqliteRecoveryHook, OpenSqliteConnectionOptions } from "./restore-types.js";
@@ -1,3 +1,6 @@
1
+ export { createCheckedSqliteClient } from "./checked-client.js";
2
+ export { SqliteClientError } from "./checked-state.js";
3
+ export { withSqliteTransaction } from "./transaction.js";
1
4
  export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
2
5
  export { SqliteDbOpsAdapter } from "./db-ops.js";
3
6
  export { inspectSqliteDatabase, verifySqliteIntegrity } from "./inspect.js";
@@ -0,0 +1,29 @@
1
+ import type { RawBuilder, StorageKernel } from "../kernel/port.js";
2
+ import type { CheckedSqliteClient } from "./checked-client.js";
3
+ export type Work<T> = (input: {
4
+ session: TransactionSession;
5
+ }) => Promise<T>;
6
+ export interface TransactionSession {
7
+ query<R>(required: {
8
+ statement: RawBuilder<R>;
9
+ }, optional?: {}): Promise<R[]>;
10
+ execute(required: {
11
+ statement: RawBuilder<unknown>;
12
+ }, optional?: {}): Promise<void>;
13
+ transaction<T>(required: {
14
+ work: Work<T>;
15
+ }, optional?: {}): Promise<T>;
16
+ }
17
+ /**
18
+ * Exclusively lease a matching checked kernel. Nested session work joins; only the root result
19
+ * decides optional failed-Outcome rollback. A session is revoked even when cleanup fails.
20
+ * @throws SqliteClientError or the original body error; AggregateError preserves cleanup failures.
21
+ */
22
+ export declare function withSqliteTransaction<T>(required: {
23
+ client: CheckedSqliteClient;
24
+ kernel: StorageKernel<unknown>;
25
+ work: Work<T>;
26
+ }, optional?: {
27
+ rollbackOnFailedOutcome?: boolean;
28
+ }): Promise<T>;
29
+ //# sourceMappingURL=transaction.d.ts.map
@@ -0,0 +1,80 @@
1
+ import { ownedTransactionOf } from "../kernel/owned-transaction.js";
2
+ import { assertCheckedAvailable, checkedClients, checkedStates, connectionsByKernel, SqliteClientError } from "./checked-state.js";
3
+ class FailedOutcome extends Error {
4
+ outcome;
5
+ constructor({ outcome }, _optional = {}) {
6
+ super("returned failed outcome", { cause: outcome });
7
+ this.outcome = outcome;
8
+ }
9
+ }
10
+ function sessionFor({ kernel, state, lease }, _optional = {}) {
11
+ const check = () => {
12
+ if (!lease.active)
13
+ throw new SqliteClientError({ code: "session_expired" });
14
+ assertCheckedAvailable({ state });
15
+ };
16
+ const session = {
17
+ async query({ statement }, _optional = {}) {
18
+ check();
19
+ return kernel.run(async (db) => { check(); return (await statement.execute(db)).rows; });
20
+ },
21
+ async execute({ statement }, _optional = {}) {
22
+ check();
23
+ await kernel.run(async (db) => { check(); await statement.execute(db); });
24
+ },
25
+ async transaction({ work }, _optional = {}) { check(); return work({ session }); },
26
+ };
27
+ return session;
28
+ }
29
+ /**
30
+ * Exclusively lease a matching checked kernel. Nested session work joins; only the root result
31
+ * decides optional failed-Outcome rollback. A session is revoked even when cleanup fails.
32
+ * @throws SqliteClientError or the original body error; AggregateError preserves cleanup failures.
33
+ */
34
+ export async function withSqliteTransaction(required, optional = {}) {
35
+ const { client, kernel, work } = required;
36
+ const state = checkedStates.get(client);
37
+ if (!checkedClients.has(client) || state === undefined || connectionsByKernel.get(kernel) !== client)
38
+ throw new Error("a matching checked SQLite client and kernel are required");
39
+ assertCheckedAvailable({ state });
40
+ if (state.lease !== undefined)
41
+ throw new SqliteClientError({ code: "transaction_busy" });
42
+ if (client.inTransaction)
43
+ throw new Error("an owned transaction cannot join an existing or foreign transaction");
44
+ const control = ownedTransactionOf({ kernel });
45
+ control.assertAvailable();
46
+ const lease = { active: true, acquired: false };
47
+ state.lease = lease;
48
+ const session = sessionFor({ kernel, state, lease });
49
+ const revoke = () => {
50
+ lease.active = false;
51
+ if (state.lease === lease)
52
+ delete state.lease;
53
+ };
54
+ try {
55
+ return await state.context.run(lease, () => control.transaction(async () => {
56
+ // Reserve first to reject overlaps, but let earlier shared runs finish before taking control.
57
+ lease.acquired = true;
58
+ const result = await work({ session });
59
+ if (optional.rollbackOnFailedOutcome === true && isFailedOutcome({ value: result }))
60
+ throw new FailedOutcome({ outcome: result });
61
+ return result;
62
+ }, { onSettled: revoke }));
63
+ }
64
+ catch (error) {
65
+ if (error instanceof FailedOutcome)
66
+ return error.outcome;
67
+ if (error instanceof AggregateError) {
68
+ throw new AggregateError(error.errors.map((part) => part instanceof FailedOutcome ? part.outcome : part), error.message);
69
+ }
70
+ throw error;
71
+ }
72
+ finally {
73
+ // Backstop for failures before the turn was taken; normally revoked inside the turn.
74
+ revoke();
75
+ }
76
+ }
77
+ function isFailedOutcome({ value }, _optional = {}) {
78
+ return value !== null && typeof value === "object" && "ok" in value && value.ok === false;
79
+ }
80
+ //# sourceMappingURL=transaction.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/db",
3
- "version": "0.6.11",
3
+ "version": "0.6.15-rc.1",
4
4
  "description": "Database ports, connection helpers, ownership, isolated Kysely kernels and migrations. All peers are optional; drivers are injected.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -24,13 +24,15 @@
24
24
  "src/kernel/index.ts",
25
25
  "src/kernel/kernel-core.ts",
26
26
  "src/kernel/ops.ts",
27
+ "src/kernel/owned-transaction.ts",
27
28
  "src/kernel/port.ts",
28
29
  "src/kernel/postgres-lock.ts",
29
30
  "src/kernel/schema-scope.ts",
30
31
  "src/kernel/schema-shape.ts",
31
32
  "src/kernel/store-copy.ts",
32
33
  "src/kernel/turn-lock.ts",
33
- "src/kernel/typegen.ts"
34
+ "src/kernel/typegen.ts",
35
+ "src/sqlite/checked-state.ts"
34
36
  ]
35
37
  }
36
38
  },
@@ -113,6 +115,11 @@
113
115
  "import": "./dist/recovery/index.js",
114
116
  "default": "./dist/recovery/index.js"
115
117
  },
118
+ "./owner-store": {
119
+ "types": "./dist/owner-store/index.d.ts",
120
+ "import": "./dist/owner-store/index.js",
121
+ "default": "./dist/owner-store/index.js"
122
+ },
116
123
  "./secrets-vault": {
117
124
  "types": "./dist/secrets-vault/index.d.ts",
118
125
  "import": "./dist/secrets-vault/index.js",
@@ -169,6 +176,9 @@
169
176
  "recovery": [
170
177
  "./dist/recovery/index.d.ts"
171
178
  ],
179
+ "owner-store": [
180
+ "./dist/owner-store/index.d.ts"
181
+ ],
172
182
  "secrets-vault": [
173
183
  "./dist/secrets-vault/index.d.ts"
174
184
  ]
@@ -192,14 +202,14 @@
192
202
  "registry": "https://registry.npmjs.org"
193
203
  },
194
204
  "dependencies": {
195
- "@jini-ai/core": "^0.6.11"
205
+ "@jini-ai/core": "^0.6.15-rc.1"
196
206
  },
197
207
  "peerDependencies": {
198
208
  "kysely": "^0.29.6",
199
209
  "better-sqlite3": "^13.0.0",
200
210
  "@electric-sql/pglite": "0.5.8",
201
211
  "pg": "^8.23.0",
202
- "@jini-ai/platform": "^0.6.10"
212
+ "@jini-ai/platform": "^0.6.15-rc.1"
203
213
  },
204
214
  "peerDependenciesMeta": {
205
215
  "better-sqlite3": {
@@ -226,8 +236,8 @@
226
236
  "better-sqlite3": "13.0.3",
227
237
  "kysely": "0.29.6",
228
238
  "pg": "8.23.0",
229
- "@jini-ai/platform": "0.6.11",
230
- "@jini-ai/core": "0.6.11"
239
+ "@jini-ai/core": "0.6.15-rc.1",
240
+ "@jini-ai/platform": "0.6.15-rc.1"
231
241
  },
232
242
  "scripts": {
233
243
  "build": "tsc -p tsconfig.build.json",