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

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 (88) hide show
  1. package/README.md +46 -1
  2. package/dist/core/ports.d.ts +2 -2
  3. package/dist/core/ports.js +2 -2
  4. package/dist/data-modules/data-module.d.ts +2 -46
  5. package/dist/data-modules/plugin-identity.d.ts +2 -11
  6. package/dist/data-modules/snapshot.d.ts +5 -3
  7. package/dist/data-modules/snapshot.js +5 -3
  8. package/dist/events/change-set-repo.sql.d.ts +18 -5
  9. package/dist/events/change-set-repo.sql.js +25 -8
  10. package/dist/events/index.d.ts +1 -1
  11. package/dist/events/outbox-repo.sql.d.ts +26 -1
  12. package/dist/events/outbox-repo.sql.js +36 -2
  13. package/dist/events/repo.rows.d.ts +22 -4
  14. package/dist/events/repo.rows.js +32 -4
  15. package/dist/kernel/idle-turn.d.ts +62 -0
  16. package/dist/kernel/idle-turn.js +32 -0
  17. package/dist/kernel/index.d.ts +1 -0
  18. package/dist/kernel/index.js +1 -0
  19. package/dist/kernel/kernel-core.js +28 -0
  20. package/dist/kernel/schema-scope.js +2 -0
  21. package/dist/kernel/sqlite/driver.js +2 -0
  22. package/dist/kernel/turn-lock.d.ts +2 -0
  23. package/dist/kernel/turn-lock.js +7 -0
  24. package/dist/pglite/copy-source.d.ts +45 -0
  25. package/dist/pglite/copy-source.js +36 -0
  26. package/dist/pglite/index.d.ts +1 -0
  27. package/dist/pglite/index.js +1 -0
  28. package/dist/react/recovery/Recovery.d.ts +205 -0
  29. package/dist/react/recovery/Recovery.js +141 -0
  30. package/dist/react/recovery/Recovery.restore-steps.d.ts +10 -0
  31. package/dist/react/recovery/Recovery.restore-steps.js +71 -0
  32. package/dist/recovery/agent-tools.d.ts +33 -0
  33. package/dist/recovery/agent-tools.js +166 -0
  34. package/dist/recovery/drift.d.ts +47 -0
  35. package/dist/recovery/drift.js +51 -0
  36. package/dist/recovery/journal-kernel.d.ts +80 -0
  37. package/dist/recovery/journal-kernel.js +40 -0
  38. package/dist/recovery/journal-repo.sql.d.ts +154 -0
  39. package/dist/recovery/journal-repo.sql.js +303 -0
  40. package/dist/recovery/journal-schema.d.ts +37 -0
  41. package/dist/recovery/journal-schema.js +110 -0
  42. package/dist/recovery/migrate-forward-hooks.d.ts +2 -1
  43. package/dist/recovery/migrate-forward-hooks.js +3 -3
  44. package/dist/recovery/operation-lock.d.ts +2 -17
  45. package/dist/recovery/reconcile-interrupted-migration.d.ts +2 -5
  46. package/dist/recovery/reconcile-interrupted-migration.js +0 -30
  47. package/dist/recovery/restore-hooks.d.ts +4 -0
  48. package/dist/recovery/restore-hooks.js +1 -1
  49. package/dist/recovery/tool-registrations.d.ts +175 -0
  50. package/dist/recovery/tool-registrations.js +295 -0
  51. package/dist/site/repo.memory.d.ts +149 -0
  52. package/dist/site/repo.memory.js +162 -0
  53. package/dist/site/tool-registrations.d.ts +130 -0
  54. package/dist/site/tool-registrations.js +185 -0
  55. package/dist/sqlite/backup-policy.d.ts +14 -0
  56. package/dist/sqlite/backup-policy.js +47 -3
  57. package/dist/sqlite/compaction-steps.d.ts +43 -0
  58. package/dist/sqlite/compaction-steps.js +73 -0
  59. package/dist/sqlite/compaction.d.ts +63 -0
  60. package/dist/sqlite/compaction.js +263 -0
  61. package/dist/sqlite/index.d.ts +2 -1
  62. package/dist/sqlite/index.js +2 -1
  63. package/dist/tools/index.d.ts +2 -0
  64. package/dist/tools/index.js +2 -0
  65. package/dist/tools/plan-store.d.ts +1 -1
  66. package/dist/tools/plan-store.js +10 -6
  67. package/dist/tools/site-db-messages.d.ts +10 -0
  68. package/dist/tools/site-db-messages.js +23 -0
  69. package/dist/tools/site-transfer-messages.d.ts +9 -0
  70. package/dist/tools/site-transfer-messages.js +20 -0
  71. package/dist/transfer/confirmation-ui.d.ts +19 -0
  72. package/dist/transfer/confirmation-ui.js +39 -0
  73. package/dist/transfer/copy-engine.js +11 -11
  74. package/dist/transfer/destination-store.d.ts +69 -0
  75. package/dist/transfer/destination-store.js +75 -0
  76. package/dist/transfer/index.d.ts +2 -0
  77. package/dist/transfer/index.js +2 -0
  78. package/dist/transfer/internal-ddl.d.ts +6 -2
  79. package/dist/transfer/internal-ddl.js +15 -15
  80. package/dist/transfer/postgres-ddl.js +2 -2
  81. package/dist/transfer/schema-catalog.d.ts +148 -0
  82. package/dist/transfer/schema-catalog.js +141 -0
  83. package/dist/transfer/sqlite-backup.d.ts +27 -0
  84. package/dist/transfer/sqlite-backup.js +31 -0
  85. package/dist/transfer/table-catalog.js +1 -0
  86. package/dist/watermark/kernel.d.ts +64 -0
  87. package/dist/watermark/kernel.js +45 -0
  88. package/package.json +104 -9
package/README.md CHANGED
@@ -15,7 +15,7 @@ subpaths as deprecated re-export shims for one release; import db directly in ne
15
15
  | `./kernel/pglite` | `openPgliteKernel`, `PgKernel`, `PgliteDialect`, `pgliteOps`, served-data copy and restore types | `kysely` |
16
16
  | `./kernel/postgres` | `openPostgresKernel`, `openPgliteSocketKernel`, `postgresOps` | `kysely` |
17
17
  | `./migrate` | `runMigrations`, `assertValidSteps`, `hasLedger`, `sourceChecksum`, step/error types | `kysely` |
18
- | `./transfer` | Snapshot sources, completeness, DDL and transactional psql COPY | Nothing |
18
+ | `./transfer` | Snapshot sources, completeness, DDL, transactional psql COPY and the ORM-neutral schema catalog (`CatalogIntrospection` injected by the host) | Nothing |
19
19
  | `./kernel/store-copy` | Scope-selected Postgres store copy over borrowed kernels | `kysely` |
20
20
  | `./tools` | DB catalogs, portable read/restore-point/transfer handlers and injected ports | `@jini-ai/core` |
21
21
 
@@ -210,6 +210,42 @@ builds the same four definitions for catalog inspection; its display-only defaul
210
210
  `app_`. `databaseTransferAgentToolCatalog` remains the neutral default display catalog.
211
211
 
212
212
 
213
+ ## Wiring
214
+
215
+ ### Site wording profile (`@jini-ai/db/tools`)
216
+
217
+ `SITE_DATABASE_MESSAGES` and `SITE_TRANSFER_MESSAGES` are a ready-made "this site" wording
218
+ profile for a host that serves one site. They change prose only: tool ids, permissions, side
219
+ effects and input schemas are identical to the neutral catalog. The profile carries no
220
+ specification ids; a host that cites its own documents spreads the profile and overrides those
221
+ fields. The host injects:
222
+
223
+ - `messages: SITE_DATABASE_MESSAGES` (or its spread override) into
224
+ `getDatabaseAgentToolCatalog({}, { messages })`, `createDatabaseReadTools(ports, { messages })`
225
+ and any other `DbMessages` consumer when it wants the site wording;
226
+ - `messages: SITE_TRANSFER_MESSAGES` plus its own persisted `TransferNaming` into
227
+ `getDatabaseTransferAgentToolCatalog({}, { naming, messages })`,
228
+ `createDatabaseTransferTools(ports, { messages })`, `countSourceRows` and `runCopy`;
229
+ - its own `applicationName` into `createPsqlPostgresTarget({ connectionString }, { applicationName })`
230
+ (the default is `database-transfer`);
231
+ - one `new DatabaseTransferPlanStore()` per process as `plans`, so a planId minted by the plan
232
+ tool is redeemable by the run tool.
233
+
234
+ Product names, schema names, marker tables and table-exclusion policy stay host inputs.
235
+
236
+ ### Recovery agent-tool catalog (`@jini-ai/db/recovery/agent-tools`)
237
+
238
+ `createRecoveryAgentToolCatalog({ backupWorkflowGuidance, restorePointIdSource })` returns the seven
239
+ recovery tool definitions. Ids, permissions, side effects, the actor-class rule on
240
+ `backup_execute_restore` and every input schema are fixed by the engine. The host injects:
241
+
242
+ - `backupWorkflowGuidance`: the sentences inside `backup_get_capabilities` that name its own
243
+ repository-backup tools and its portable export path / admin screen;
244
+ - `restorePointIdSource`: the read tool(s) that return a restore point id, named in the
245
+ `restorePointId` field description of `backup_plan_restore` and `backup_execute_restore`.
246
+
247
+ Bind it once at the host's recovery registration site and reuse that one array everywhere.
248
+
213
249
  ## Design decisions
214
250
 
215
251
  - [Operational history is a bounded read surface](docs/decisions/DR-001-bounded-operational-timeline.md).
@@ -306,3 +342,12 @@ lives in `@jini-ai/server/owner-store`.
306
342
  with the same names from `'@jini-ai/server/owner-store'`, and add `@jini-ai/server` (same version as
307
343
  `@jini-ai/db`) to the host's dependencies. `OWNER_STORE_LEDGER`, `ownerStoreMigrations`, `ownerStoreDdl`
308
344
  and `ownerStoreMigration` stay here.
345
+
346
+ ## Wiring (transfer: SQLite online backup)
347
+
348
+ `captureSqliteBackupBytes` (`@jini-ai/db/transfer`): the host passes its open, structural SQLite handle
349
+ (`backupTo`) and its own `tempDirPrefix` for the short-lived backup directory.
350
+
351
+ - `@jini-ai/db/pglite`: `copyPgliteSourceTo({ sourceDataDir, targetDataDir, ports })` owns the served-versus-stopped
352
+ copy and owner-lock lifecycle of a PGlite data dir. The host supplies `runningOwner`, `copyServed`,
353
+ `acquireOwnerLock` (mapping a refused lock to its own error), `openStopped` and `copyStopped`.
@@ -7,8 +7,8 @@
7
7
  * module contributes zero bytes and zero `require()` calls to a consumer's runtime graph.
8
8
  *
9
9
  * How it relates to the package:
10
- * `db/core` is the half of `@jini-ai/infra` that must stay installable with no native module
11
- * present — a host running Supabase/Postgres pulls `@jini-ai/infra/db/core` and never compiles
10
+ * `db/core` is the half of `@jini-ai/db` that must stay installable with no native module
11
+ * present — a host running Supabase/Postgres imports `@jini-ai/db/core` and never compiles
12
12
  * `better-sqlite3`. That property is not a convention here, it is enforced: `pnpm guard`'s
13
13
  * R12 check walks this directory's transitive import closure and fails if it reaches a driver
14
14
  * folder or a driver package. See `scripts/check-driver-isolation.ts`.
@@ -7,8 +7,8 @@
7
7
  * module contributes zero bytes and zero `require()` calls to a consumer's runtime graph.
8
8
  *
9
9
  * How it relates to the package:
10
- * `db/core` is the half of `@jini-ai/infra` that must stay installable with no native module
11
- * present — a host running Supabase/Postgres pulls `@jini-ai/infra/db/core` and never compiles
10
+ * `db/core` is the half of `@jini-ai/db` that must stay installable with no native module
11
+ * present — a host running Supabase/Postgres imports `@jini-ai/db/core` and never compiles
12
12
  * `better-sqlite3`. That property is not a convention here, it is enforced: `pnpm guard`'s
13
13
  * R12 check walks this directory's transitive import closure and fails if it reaches a driver
14
14
  * folder or a driver package. See `scripts/check-driver-isolation.ts`.
@@ -254,53 +254,9 @@
254
254
  */
255
255
  import { type Logger } from "@jini-ai/core/primitives";
256
256
  import { type HeadroomCheck } from "./disk-headroom.js";
257
- import { type PluginProvenance } from "./plugin-identity.js";
258
257
  import { type PluginStore } from "./plugin-store.js";
259
- export type ColumnType = "TEXT" | "INTEGER" | "REAL" | "BLOB";
260
- export type PluginTier = "tier-1" | "tier-2" | "tier-3";
261
- export interface ColumnDecl {
262
- readonly name: string;
263
- readonly type: ColumnType;
264
- readonly notNull?: boolean;
265
- readonly primaryKey?: boolean;
266
- }
267
- /**
268
- * Declared FKs / the SDK stress-test finding — the dataModule seam's
269
- * declared-index grammar. Comments' moderation-queue query pattern
270
- * (`workspace_id, entry_id, status`) is the concrete demand this grows the seam against, per
271
- * OQ-1's own instruction not to silently work around the gap. Deliberately NOT a foreign-key
272
- * declaration seam too — the original design says referential integrity to `entries`/parent
273
- * comments is "chokepoint-validated, not FK-enforced (v1)", so only indexes are the real,
274
- * load-bearing need; adding FK-declaration grammar with no consumer would be speculative.
275
- */
276
- export interface IndexDecl {
277
- /** SHORT name; core prefixes it the same way tables are (`idx_p_{pluginId}__{name}`). */
278
- readonly name: string;
279
- readonly columns: readonly string[];
280
- readonly unique?: boolean;
281
- }
282
- export interface TableDecl {
283
- /** SHORT name; core prefixes it with the reserved `p_{pluginId}__` namespace. */
284
- readonly name: string;
285
- readonly columns: readonly ColumnDecl[];
286
- readonly indexes?: readonly IndexDecl[];
287
- /** Share policy belongs to the table owner. Missing declarations still refuse nonempty data.
288
- * Portable columns are explicit so later personal fields cannot silently enter an archive. */
289
- readonly portability?: {
290
- readonly kind: "private";
291
- } | {
292
- readonly kind: "portable";
293
- readonly columns: readonly string[];
294
- };
295
- }
296
- export interface DataModuleDecl {
297
- readonly pluginId: string;
298
- /** §3/T6: `dataModule` is scoped to Tier-2/Tier-3 only — a Tier-1 declaration is rejected. */
299
- readonly pluginTier: PluginTier;
300
- readonly tables: readonly TableDecl[];
301
- /** §5/§6/T5 — used by the namespace-adoption guard. */
302
- readonly provenance: PluginProvenance;
303
- }
258
+ import type { DataModuleDecl } from "@jini-ai/core/contracts/site/db-data-modules";
259
+ export type { ColumnType, PluginTier, ColumnDecl, IndexDecl, TableDecl, DataModuleDecl } from "@jini-ai/core/contracts/site/db-data-modules";
304
260
  export interface DeclareResult {
305
261
  readonly ok: boolean;
306
262
  /** Fully-qualified names of tables created this call. */
@@ -1,15 +1,6 @@
1
1
  import { type PluginStore } from "./plugin-store.js";
2
- /**
3
- * @agent-note Saved format. The first declare that applies DDL stores these fields in
4
- * `_plugin_identity`; they are never updated. Later declares compare all three with strict string
5
- * equality, so a renamed publisher or moved URL is refused as `consent-required` the next time
6
- * that plugin has DDL to apply, unless both sides carry the same `signature`.
7
- */
8
- export interface PluginProvenance {
9
- sourceUrl: string;
10
- publisher: string;
11
- signature?: string;
12
- }
2
+ import type { PluginProvenance } from "@jini-ai/core/contracts/site/db-data-modules";
3
+ export type { PluginProvenance } from "@jini-ai/core/contracts/site/db-data-modules";
13
4
  export interface PluginIdentityRecord {
14
5
  pluginId: string;
15
6
  provenance: PluginProvenance;
@@ -43,9 +43,11 @@ export declare function snapshotDb(required: {
43
43
  * it there removes zero recovery capability: the never-brick guarantee covers the window between
44
44
  * "snapshot taken" and "DDL committed", and that window has closed.
45
45
  *
46
- * **A failed migration keeps its snapshot**, deliberately — the catch path leaves the entry
47
- * non-terminal precisely so the next boot can restore from it, and §9 also wants it retained for
48
- * operator forensics.
46
+ * **A failed migration keeps its snapshot**, deliberately — the catch path marks the entry
47
+ * `ROLLED_BACK` (terminal; see `recordFailurePhase` in `data-module.ts`, which writes `COMMITTED`
48
+ * instead when the DDL had already committed) and never deletes the snapshot file, so §9's
49
+ * operator forensics still has it. The next boot does not restore from it: a terminal entry is not
50
+ * an incomplete journal entry.
49
51
  *
50
52
  * `_plugin_migrations.snapshot_path` still records which snapshot guarded each committed DDL. That
51
53
  * row is history — it says what protected the change at the time, which stays true — so a path
@@ -80,9 +80,11 @@ export async function snapshotDb(required, _optional = {}) {
80
80
  * it there removes zero recovery capability: the never-brick guarantee covers the window between
81
81
  * "snapshot taken" and "DDL committed", and that window has closed.
82
82
  *
83
- * **A failed migration keeps its snapshot**, deliberately — the catch path leaves the entry
84
- * non-terminal precisely so the next boot can restore from it, and §9 also wants it retained for
85
- * operator forensics.
83
+ * **A failed migration keeps its snapshot**, deliberately — the catch path marks the entry
84
+ * `ROLLED_BACK` (terminal; see `recordFailurePhase` in `data-module.ts`, which writes `COMMITTED`
85
+ * instead when the DDL had already committed) and never deletes the snapshot file, so §9's
86
+ * operator forensics still has it. The next boot does not restore from it: a terminal entry is not
87
+ * an incomplete journal entry.
86
88
  *
87
89
  * `_plugin_migrations.snapshot_path` still records which snapshot guarded each committed DDL. That
88
90
  * row is history — it says what protected the change at the time, which stays true — so a path
@@ -1,6 +1,8 @@
1
1
  import type { Kysely } from "kysely";
2
2
  import type { StorageKernel } from "@jini-ai/core/contracts/storage";
3
- import type { DomainEvent, ChangeSetItemRecord, ChangeSetRecord, ChangeSetRepoPort, ChangeSetWithItems } from "@jini-ai/core/contracts/events";
3
+ import type { AttributedDomainEvent, NewChangeSetRecord, ChangeSetItemRecord, ChangeSetRecord, ChangeSetRepoPort, ChangeSetWithItems } from "@jini-ai/core/contracts/events";
4
+ import { type OutboxEventPreparation } from "./outbox-repo.sql.js";
5
+ import { type ActorKindColumn } from "./repo.rows.js";
4
6
  /**
5
7
  * @file Phase 1 — THE `ChangeSetRepoPort` adapter: one Kysely query body for every
6
8
  * dialect (storage plan). Rule-of-two "second adapter" half;
@@ -38,21 +40,32 @@ export interface ChangeSetSqlRequired {
38
40
  kernel: StorageKernel<Kysely<unknown>, unknown>;
39
41
  tables: ChangeSetTables;
40
42
  }
41
- export type ChangeSetSqlOptional = Record<string, never>;
43
+ /**
44
+ * `actorKindColumn` (default off): set it only once the host schema has `change_sets.actor_kind`,
45
+ * so a rolling host never selects or inserts a column its database does not have yet.
46
+ */
47
+ export type ChangeSetSqlOptional = ActorKindColumn;
42
48
  export declare class SqlChangeSetRepo implements ChangeSetRepoPort {
43
49
  protected readonly kernel: StorageKernel<Kysely<unknown>, unknown>;
44
50
  protected readonly tables: ChangeSetTables;
45
- constructor({ kernel, tables }: ChangeSetSqlRequired, _optional?: ChangeSetSqlOptional);
51
+ private readonly preparation;
52
+ private readonly columns;
53
+ /**
54
+ * @param optional.actorKindColumn read/write `change_sets.actor_kind` (see `ChangeSetSqlOptional`).
55
+ * @param optional.prepareOutboxEvent host hook preparing the co-persisted event for this repo's one transaction.
56
+ */
57
+ constructor({ kernel, tables }: ChangeSetSqlRequired, { actorKindColumn, ...preparation }?: ChangeSetSqlOptional & OutboxEventPreparation);
58
+ private read;
46
59
  private sets;
47
60
  private items;
48
61
  /** Header + items + (when supplied) the outbox event land as one atomic transaction — never a
49
62
  * partial write (the "transaction participation" requirement, and the
50
63
  * resolution for the outbox event specifically; see this file's header). */
51
64
  insert({ record, items }: {
52
- record: ChangeSetRecord;
65
+ record: NewChangeSetRecord;
53
66
  items: ChangeSetItemRecord[];
54
67
  }, { event }?: {
55
- event?: DomainEvent;
68
+ event?: AttributedDomainEvent | undefined;
56
69
  }): Promise<void>;
57
70
  findById(required: {
58
71
  workspaceId: string;
@@ -1,11 +1,22 @@
1
- import { outboxEventValues } from "./outbox-repo.sql.js";
1
+ import { outboxEventValues, preparedOutboxEvent } from "./outbox-repo.sql.js";
2
2
  import { toItemRecord, toItemRow, toRecord, toRow, } from "./repo.rows.js";
3
3
  export class SqlChangeSetRepo {
4
4
  kernel;
5
5
  tables;
6
- constructor({ kernel, tables }, _optional = {}) {
6
+ preparation;
7
+ columns;
8
+ /**
9
+ * @param optional.actorKindColumn read/write `change_sets.actor_kind` (see `ChangeSetSqlOptional`).
10
+ * @param optional.prepareOutboxEvent host hook preparing the co-persisted event for this repo's one transaction.
11
+ */
12
+ constructor({ kernel, tables }, { actorKindColumn = false, ...preparation } = {}) {
7
13
  this.kernel = kernel;
8
14
  this.tables = tables;
15
+ this.preparation = preparation;
16
+ this.columns = { actorKindColumn };
17
+ }
18
+ read(row) {
19
+ return toRecord(row, this.columns);
9
20
  }
10
21
  // Host-owned table names need an explicit column schema, as in the settings adapter.
11
22
  sets(db) {
@@ -18,12 +29,18 @@ export class SqlChangeSetRepo {
18
29
  * partial write (the "transaction participation" requirement, and the
19
30
  * resolution for the outbox event specifically; see this file's header). */
20
31
  async insert({ record, items }, { event } = {}) {
32
+ // Build every row first so conflicting attribution is refused before the transaction opens.
33
+ if (event && (record.actor.id !== event.actor.id || record.actor.kind !== event.actor.kind || record.actorId !== event.actorId))
34
+ throw new Error("Change-set and event actor attribution must match.");
35
+ const header = toRow(record, this.columns);
36
+ // Preparation preserves the writer's actor while preparing the envelope that is actually stored.
37
+ const eventRow = event ? outboxEventValues(preparedOutboxEvent({ event }, this.preparation)) : undefined;
21
38
  await this.kernel.transaction(async () => this.kernel.run(async (db) => {
22
- await this.sets(db).insertInto(this.tables.changeSets).values(toRow(record)).execute();
39
+ await this.sets(db).insertInto(this.tables.changeSets).values(header).execute();
23
40
  for (const item of items)
24
41
  await this.items(db).insertInto(this.tables.changeSetItems).values(toItemRow(item)).execute();
25
- if (event)
26
- await db.withTables().insertInto(this.tables.outboxEvents).values(outboxEventValues(event)).execute();
42
+ if (eventRow)
43
+ await db.withTables().insertInto(this.tables.outboxEvents).values(eventRow).execute();
27
44
  }));
28
45
  }
29
46
  async findById(required, _optional = {}) {
@@ -43,7 +60,7 @@ export class SqlChangeSetRepo {
43
60
  .where("change_set_id", "=", row.id)
44
61
  .orderBy("position")
45
62
  .execute();
46
- return { changeSet: toRecord(row), items: itemRows.map(toItemRecord) };
63
+ return { changeSet: this.read(row), items: itemRows.map(toItemRecord) };
47
64
  });
48
65
  }
49
66
  async findByIdempotencyKey(required, _optional = {}) {
@@ -54,11 +71,11 @@ export class SqlChangeSetRepo {
54
71
  .where("idempotency_key", "=", required.idempotencyKey)
55
72
  .limit(1)
56
73
  .executeTakeFirst());
57
- return row ? toRecord(row) : null;
74
+ return row ? this.read(row) : null;
58
75
  }
59
76
  async listByWorkspace(required, _optional = {}) {
60
77
  const rows = await this.kernel.run((db) => this.sets(db).selectFrom(this.tables.changeSets).selectAll().where("workspace_id", "=", required.workspaceId).orderBy("created_at").execute());
61
- return rows.map(toRecord);
78
+ return rows.map((row) => this.read(row));
62
79
  }
63
80
  async save(record) {
64
81
  await this.kernel.run((db) => this.sets(db)
@@ -1,4 +1,4 @@
1
1
  export { SqlChangeSetRepo, type ChangeSetSqlOptional, type ChangeSetSqlRequired, type ChangeSetTables } from "./change-set-repo.sql.js";
2
- export { SqlOutboxAdapter, outboxEventValues, type OutboxSqlOptional, type OutboxSqlRequired, type OutboxTables } from "./outbox-repo.sql.js";
2
+ export { SqlOutboxAdapter, outboxEventValues, type OutboxEventPreparation, type OutboxSqlOptional, type PrepareOutboxEvent, type OutboxSqlRequired, type OutboxTables } from "./outbox-repo.sql.js";
3
3
  export type { ChangeSetItemsTable, ChangeSetsTable, OutboxEventsTable } from "./repo.rows.js";
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -33,6 +33,15 @@ export interface OutboxSqlRequired {
33
33
  claimLeaseMs: number;
34
34
  }
35
35
  export type OutboxSqlOptional = Record<string, never>;
36
+ /** Host hook returning the envelope to persist (for example with producer trace context in
37
+ * `metadata`). It must return a new envelope rather than modify the one it is given. */
38
+ export type PrepareOutboxEvent = (required: {
39
+ event: DomainEvent;
40
+ }, _optional?: Record<string, never>) => DomainEvent;
41
+ /** Constructor options shared by both outbox writers: the direct enqueue and the co-persisted change-set write. */
42
+ export interface OutboxEventPreparation {
43
+ prepareOutboxEvent?: PrepareOutboxEvent;
44
+ }
36
45
  /** The `outbox_events` row for a freshly-produced event (snake_case). Shared by enqueue
37
46
  * and transactional callers so an audit event can be inserted atomically with its domain
38
47
  * writes, using the identical row shape rather than a copy or an independent enqueue.
@@ -46,16 +55,32 @@ export declare function outboxEventValues(event: DomainEvent<object>): {
46
55
  next_attempt_at: string;
47
56
  created_at: string;
48
57
  };
58
+ /**
59
+ * The envelope an outbox writer serializes, prepared inside the caller's existing write. Correlation
60
+ * is captured here, while the producer is still running, because the asynchronous delivery cannot
61
+ * inherit the producer's request-local state and must not depend on when this transaction commits.
62
+ * The prepared envelope keeps the original's id, workspace and occurrence time, so the dedupe key
63
+ * (`ON CONFLICT (id)`) and the first due time cannot move. A failing or malformed preparation
64
+ * persists the original envelope and the write still succeeds: losing correlation is preferable to
65
+ * losing the event or rolling back the domain write it belongs to.
66
+ * @example const stored = preparedOutboxEvent({ event }, { prepareOutboxEvent });
67
+ * @complexity O(1) beyond the injected hook.
68
+ */
69
+ export declare function preparedOutboxEvent(required: {
70
+ event: DomainEvent;
71
+ }, optional?: OutboxEventPreparation): DomainEvent;
49
72
  export declare class SqlOutboxAdapter implements OutboxPort {
50
73
  protected readonly kernel: StorageKernel<Kysely<unknown>, unknown>;
51
74
  protected readonly tables: OutboxTables;
52
75
  private readonly claimLeaseMs;
76
+ private readonly preparation;
53
77
  /**
54
78
  * @param required.kernel the database holding the outbox table.
55
79
  * @param required.tables.outboxEvents the host's outbox table name.
56
80
  * @param required.claimLeaseMs claim lease length.
81
+ * @param optional.prepareOutboxEvent host hook preparing each envelope inside the enqueue write.
57
82
  */
58
- constructor({ kernel, tables, claimLeaseMs }: OutboxSqlRequired, _optional?: OutboxSqlOptional);
83
+ constructor({ kernel, tables, claimLeaseMs }: OutboxSqlRequired, optional?: OutboxEventPreparation);
59
84
  /** Host-owned table name needs an explicit column schema, as in the settings adapter. */
60
85
  private table;
61
86
  /** A repeated `event.id` is a no-op, never a primary-key error: ids are deterministic per event
@@ -1,3 +1,4 @@
1
+ import { assertConsistentActor } from "./repo.rows.js";
1
2
  function toRecord(row) {
2
3
  return {
3
4
  id: row.id,
@@ -24,6 +25,8 @@ const UNSETTLED_STATUSES = ["pending", "processing"];
24
25
  * writes, using the identical row shape rather than a copy or an independent enqueue.
25
26
  */
26
27
  export function outboxEventValues(event) {
28
+ // The actor (id and kind) rides inside the existing `event_json`, so no outbox column is added.
29
+ assertConsistentActor(event);
27
30
  return {
28
31
  id: event.id,
29
32
  workspace_id: event.workspaceId,
@@ -34,19 +37,50 @@ export function outboxEventValues(event) {
34
37
  created_at: event.occurredAt,
35
38
  };
36
39
  }
40
+ /**
41
+ * The envelope an outbox writer serializes, prepared inside the caller's existing write. Correlation
42
+ * is captured here, while the producer is still running, because the asynchronous delivery cannot
43
+ * inherit the producer's request-local state and must not depend on when this transaction commits.
44
+ * The prepared envelope keeps the original's id, workspace and occurrence time, so the dedupe key
45
+ * (`ON CONFLICT (id)`) and the first due time cannot move. A failing or malformed preparation
46
+ * persists the original envelope and the write still succeeds: losing correlation is preferable to
47
+ * losing the event or rolling back the domain write it belongs to.
48
+ * @example const stored = preparedOutboxEvent({ event }, { prepareOutboxEvent });
49
+ * @complexity O(1) beyond the injected hook.
50
+ */
51
+ export function preparedOutboxEvent(required, optional = {}) {
52
+ const { event } = required;
53
+ if (!optional.prepareOutboxEvent)
54
+ return event;
55
+ const { id, workspaceId, occurredAt, actorId } = event;
56
+ const actor = event.actor === undefined ? undefined : { ...event.actor };
57
+ try {
58
+ const prepared = optional.prepareOutboxEvent({ event: { ...event, ...(actor === undefined ? {} : { actor: { ...actor } }) } });
59
+ if (typeof prepared !== "object" || prepared === null)
60
+ return event;
61
+ const { actor: _preparedActor, actorId: _preparedActorId, ...envelope } = prepared;
62
+ return { ...envelope, id, workspaceId, occurredAt, ...(actor === undefined ? {} : { actor }), ...(actorId === undefined ? {} : { actorId }) };
63
+ }
64
+ catch {
65
+ return event;
66
+ }
67
+ }
37
68
  export class SqlOutboxAdapter {
38
69
  kernel;
39
70
  tables;
40
71
  claimLeaseMs;
72
+ preparation;
41
73
  /**
42
74
  * @param required.kernel the database holding the outbox table.
43
75
  * @param required.tables.outboxEvents the host's outbox table name.
44
76
  * @param required.claimLeaseMs claim lease length.
77
+ * @param optional.prepareOutboxEvent host hook preparing each envelope inside the enqueue write.
45
78
  */
46
- constructor({ kernel, tables, claimLeaseMs }, _optional = {}) {
79
+ constructor({ kernel, tables, claimLeaseMs }, optional = {}) {
47
80
  this.kernel = kernel;
48
81
  this.tables = tables;
49
82
  this.claimLeaseMs = claimLeaseMs;
83
+ this.preparation = optional;
50
84
  }
51
85
  /** Host-owned table name needs an explicit column schema, as in the settings adapter. */
52
86
  table(db) {
@@ -57,7 +91,7 @@ export class SqlOutboxAdapter {
57
91
  * scheduled go-live), so the same id is the same event, and the post go-live sweep
58
92
  * (`features/post/go-live.ts`) relies on this to announce each go-live exactly once. */
59
93
  async enqueue(event) {
60
- await this.kernel.run((db) => this.table(db).insertInto(this.tables.outboxEvents).values(outboxEventValues(event)).onConflict((oc) => oc.column("id").doNothing()).execute());
94
+ await this.kernel.run((db) => this.table(db).insertInto(this.tables.outboxEvents).values(outboxEventValues(preparedOutboxEvent({ event }, this.preparation))).onConflict((oc) => oc.column("id").doNothing()).execute());
61
95
  }
62
96
  /** Selects due rows (pending, or processing under an expired claim lease) and marks them
63
97
  * `processing` under a fresh lease in one kernel transaction — the select-then-update is never
@@ -1,5 +1,5 @@
1
1
  import type { Generated, Insertable, Selectable } from "kysely";
2
- import type { ChangeSetItemRecord, ChangeSetRecord } from "@jini-ai/core/contracts/events";
2
+ import type { ChangeSetItemRecord, ChangeSetRecord, MutationActor } from "@jini-ai/core/contracts/events";
3
3
  /** Stored column shapes, copied without schema changes; the table names are host-owned (see `ChangeSetTables`, `OutboxTables`). */
4
4
  export interface ChangeSetItemsTable {
5
5
  id: string;
@@ -17,6 +17,8 @@ export interface ChangeSetsTable {
17
17
  id: string;
18
18
  workspace_id: string;
19
19
  actor_id: string | null;
20
+ /** Present only once the host has migrated; read and written only under `ActorKindColumn`. */
21
+ actor_kind?: string | null;
20
22
  status: string;
21
23
  summary: string;
22
24
  idempotency_key: string | null;
@@ -35,10 +37,26 @@ export interface OutboxEventsTable {
35
37
  last_error: string | null;
36
38
  created_at: string;
37
39
  }
38
- export declare function toRecord(row: Selectable<ChangeSetsTable>): ChangeSetRecord;
40
+ /** Whether the host's `change_sets` table has the `actor_kind` column yet; off means it is never named. */
41
+ export interface ActorKindColumn {
42
+ actorKindColumn?: boolean;
43
+ }
44
+ /**
45
+ * Refuses a record or event whose compatibility `actorId` names someone other than its `actor`,
46
+ * so the two attribution fields can never be persisted disagreeing.
47
+ *
48
+ * @param required - The record or event's `actorId` and `actor`.
49
+ * @throws {Error} When both are present and the ids differ.
50
+ * @complexity O(1).
51
+ */
52
+ export declare function assertConsistentActor({ actorId, actor }: {
53
+ actorId?: string | undefined;
54
+ actor?: MutationActor | undefined;
55
+ }, _optional?: Record<string, never>): void;
56
+ export declare function toRecord(row: Selectable<ChangeSetsTable>, options?: ActorKindColumn): ChangeSetRecord;
39
57
  export declare function toItemRecord(row: Selectable<ChangeSetItemsTable>): ChangeSetItemRecord;
40
- /** `toRecord`'s inverse: every absent optional field is written as SQL NULL. */
41
- export declare function toRow(record: ChangeSetRecord): Insertable<ChangeSetsTable>;
58
+ /** `toRecord`'s inverse: every absent optional field is written as SQL NULL; `actor_kind` only under `ActorKindColumn`. */
59
+ export declare function toRow(record: ChangeSetRecord, options?: ActorKindColumn): Insertable<ChangeSetsTable>;
42
60
  /** `toItemRecord`'s inverse: absent optionals as SQL NULL, the inverse payload as JSON text. */
43
61
  export declare function toItemRow(item: ChangeSetItemRecord): Insertable<ChangeSetItemsTable>;
44
62
  //# sourceMappingURL=repo.rows.d.ts.map
@@ -1,5 +1,27 @@
1
- export function toRecord(row) {
1
+ const ACTOR_KINDS = new Set(["user", "agent", "system"]);
2
+ /**
3
+ * Refuses a record or event whose compatibility `actorId` names someone other than its `actor`,
4
+ * so the two attribution fields can never be persisted disagreeing.
5
+ *
6
+ * @param required - The record or event's `actorId` and `actor`.
7
+ * @throws {Error} When both are present and the ids differ.
8
+ * @complexity O(1).
9
+ */
10
+ export function assertConsistentActor({ actorId, actor }, _optional = {}) {
11
+ if (actor && actorId !== undefined && actorId !== actor.id) {
12
+ throw new Error("The actor id does not match the recorded actor; refusing to write conflicting attribution.");
13
+ }
14
+ }
15
+ /** The stored provenance as an actor, or nothing: a missing or unrecognised kind is unknown, never guessed. */
16
+ function storedActor(row, { actorKindColumn = false }) {
17
+ const kind = actorKindColumn ? row.actor_kind : null;
18
+ if (!row.actor_id || !kind || !ACTOR_KINDS.has(kind))
19
+ return {};
20
+ return { actor: { id: row.actor_id, kind: kind } };
21
+ }
22
+ export function toRecord(row, options = {}) {
2
23
  return {
24
+ ...storedActor(row, options),
3
25
  id: row.id,
4
26
  workspaceId: row.workspace_id,
5
27
  actorId: row.actor_id ?? undefined,
@@ -26,12 +48,18 @@ export function toItemRecord(row) {
26
48
  position: row.position,
27
49
  };
28
50
  }
29
- /** `toRecord`'s inverse: every absent optional field is written as SQL NULL. */
30
- export function toRow(record) {
51
+ /** The attribution columns of a record, refusing conflicting ids; `actor_kind` is named only under `ActorKindColumn`. */
52
+ function actorColumns(record, { actorKindColumn = false }) {
53
+ assertConsistentActor(record);
54
+ const actorId = record.actorId ?? record.actor?.id ?? null;
55
+ return actorKindColumn ? { actor_id: actorId, actor_kind: record.actor?.kind ?? null } : { actor_id: actorId };
56
+ }
57
+ /** `toRecord`'s inverse: every absent optional field is written as SQL NULL; `actor_kind` only under `ActorKindColumn`. */
58
+ export function toRow(record, options = {}) {
31
59
  return {
60
+ ...actorColumns(record, options),
32
61
  id: record.id,
33
62
  workspace_id: record.workspaceId,
34
- actor_id: record.actorId ?? null,
35
63
  status: record.status,
36
64
  summary: record.summary,
37
65
  idempotency_key: record.idempotencyKey ?? null,
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @file `withIdleTurn`: an exclusive, NON-queuing turn on a one-connection kernel (better-sqlite3,
3
+ * PGlite), taken only while the kernel is idle.
4
+ *
5
+ * Why: every caller of such a kernel shares ONE connection, and a kernel transaction is just a
6
+ * `BEGIN` on it. Maintenance that must not land inside someone else's transaction (a bounded
7
+ * `PRAGMA incremental_vacuum`, for instance) needs the file's turn lock to itself — but serving
8
+ * traffic must never queue behind maintenance, so admission refuses instead of waiting.
9
+ *
10
+ * Invariants: the body runs only while this process holds the file's turn lock exclusively (I1);
11
+ * admission never waits and never overtakes a queued caller (I2); it refuses inside a kernel scope,
12
+ * with a foreign transaction open, or on a kernel without a turn lock (I3); kernel calls on the same
13
+ * file inside the body throw (I4); the lock is released even when the body throws, and the body's
14
+ * error is never caught (I5). Never call it from a migration: the runner's transaction scope makes
15
+ * it refuse with "in-scope" (I6).
16
+ */
17
+ import type { KyselyKernel } from "./port.js";
18
+ /**
19
+ * Why a turn was not taken. "busy": kernel work holds or waits for the lock — it clears by itself.
20
+ * "in-scope": the caller is inside a kernel run/transaction (or holds the lock through another
21
+ * kernel). "transaction-open": the shared connection is in a transaction the kernel does not own.
22
+ * "unsupported": a multi-connection kernel, or one not built by `buildKernel`.
23
+ */
24
+ export type IdleTurnRefusal = "busy" | "in-scope" | "transaction-open" | "unsupported";
25
+ export type IdleTurnResult<T> = {
26
+ readonly ran: true;
27
+ readonly value: T;
28
+ } | {
29
+ readonly ran: false;
30
+ readonly reason: IdleTurnRefusal;
31
+ };
32
+ /** Private per-kernel control, registered by `buildKernel` (the same pattern as `registerOwnedTransaction`). */
33
+ export interface IdleTurnControl {
34
+ /** Synchronous admission plus exclusive take: the release function, or the refusal. */
35
+ tryTake(): {
36
+ readonly release: () => void;
37
+ } | {
38
+ readonly refusal: IdleTurnRefusal;
39
+ };
40
+ /** Runs `body` with the lock marked held for this async chain, so nested kernel calls throw (I4). */
41
+ runHeld<T>(body: () => Promise<T>): Promise<T>;
42
+ }
43
+ /** Records the control of a kernel built by `buildKernel`. Not exported from the package. */
44
+ export declare function registerIdleTurn({ kernel, control }: {
45
+ kernel: KyselyKernel<unknown>;
46
+ control: IdleTurnControl;
47
+ }, _optional?: Record<string, never>): void;
48
+ /** A wrapper kernel (schema-scoped, owned connection) shares its source's lock and control. */
49
+ export declare function inheritIdleTurn({ from, to }: {
50
+ from: KyselyKernel<unknown>;
51
+ to: KyselyKernel<unknown>;
52
+ }, _optional?: Record<string, never>): void;
53
+ /**
54
+ * Run `body` in an exclusive turn on a one-connection kernel, only if the kernel is idle right now.
55
+ * Never queues (I2), never joins a transaction (I3), always releases (I5).
56
+ * @complexity O(1) admission plus the body.
57
+ */
58
+ export declare function withIdleTurn<T, DB = unknown>({ kernel, body }: {
59
+ kernel: KyselyKernel<DB>;
60
+ body: () => Promise<T>;
61
+ }, _optional?: Record<string, never>): Promise<IdleTurnResult<T>>;
62
+ //# sourceMappingURL=idle-turn.d.ts.map
@@ -0,0 +1,32 @@
1
+ const controls = new WeakMap();
2
+ /** Records the control of a kernel built by `buildKernel`. Not exported from the package. */
3
+ export function registerIdleTurn({ kernel, control }, _optional = {}) {
4
+ controls.set(kernel, control);
5
+ }
6
+ /** A wrapper kernel (schema-scoped, owned connection) shares its source's lock and control. */
7
+ export function inheritIdleTurn({ from, to }, _optional = {}) {
8
+ const control = controls.get(from);
9
+ if (control !== undefined)
10
+ controls.set(to, control);
11
+ }
12
+ /**
13
+ * Run `body` in an exclusive turn on a one-connection kernel, only if the kernel is idle right now.
14
+ * Never queues (I2), never joins a transaction (I3), always releases (I5).
15
+ * @complexity O(1) admission plus the body.
16
+ */
17
+ export async function withIdleTurn({ kernel, body }, _optional = {}) {
18
+ const control = controls.get(kernel);
19
+ if (control === undefined)
20
+ return { ran: false, reason: "unsupported" };
21
+ await kernel.ready;
22
+ const taken = control.tryTake();
23
+ if ("refusal" in taken)
24
+ return { ran: false, reason: taken.refusal };
25
+ try {
26
+ return { ran: true, value: await control.runHeld(body) };
27
+ }
28
+ finally {
29
+ taken.release();
30
+ }
31
+ }
32
+ //# sourceMappingURL=idle-turn.js.map