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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/README.md +33 -17
  3. package/dist/core/index.d.ts +1 -2
  4. package/dist/core/index.js +0 -1
  5. package/dist/core/pg-types.d.ts +4 -1
  6. package/dist/core/pg-types.js +1 -1
  7. package/dist/core/row-values.d.ts +0 -30
  8. package/dist/core/row-values.js +1 -41
  9. package/dist/data-modules/data-module.d.ts +260 -4
  10. package/dist/data-modules/data-module.js +105 -83
  11. package/dist/data-modules/disk-headroom.js +1 -1
  12. package/dist/data-modules/index.d.ts +2 -2
  13. package/dist/data-modules/index.js +2 -2
  14. package/dist/data-modules/migration-journal.js +6 -6
  15. package/dist/data-modules/migration-recovery.js +2 -2
  16. package/dist/data-modules/plugin-identity.js +5 -5
  17. package/dist/data-modules/plugin-store.d.ts +4 -4
  18. package/dist/data-modules/restore.js +5 -5
  19. package/dist/data-modules/snapshot.d.ts +1 -1
  20. package/dist/data-modules/snapshot.js +3 -3
  21. package/dist/events/change-set-repo.sql.d.ts +70 -0
  22. package/dist/events/change-set-repo.sql.js +72 -0
  23. package/dist/events/index.d.ts +4 -0
  24. package/dist/events/index.js +3 -0
  25. package/dist/events/outbox-repo.sql.d.ts +91 -0
  26. package/dist/events/outbox-repo.sql.js +108 -0
  27. package/dist/events/repo.rows.d.ts +44 -0
  28. package/dist/events/repo.rows.js +59 -0
  29. package/dist/gated-mutations/index.d.ts +3 -0
  30. package/dist/gated-mutations/index.js +2 -0
  31. package/dist/gated-mutations/repo.rows.d.ts +19 -0
  32. package/dist/gated-mutations/repo.rows.js +23 -0
  33. package/dist/gated-mutations/repo.sql.d.ts +67 -0
  34. package/dist/gated-mutations/repo.sql.js +71 -0
  35. package/dist/kernel/dialect.d.ts +53 -31
  36. package/dist/kernel/dialect.js +14 -36
  37. package/dist/kernel/index.d.ts +2 -2
  38. package/dist/kernel/index.js +1 -7
  39. package/dist/kernel/kernel-core.d.ts +7 -3
  40. package/dist/kernel/kernel-core.js +75 -66
  41. package/dist/kernel/ops.d.ts +9 -3
  42. package/dist/kernel/ops.js +2 -2
  43. package/dist/kernel/owned-transaction.d.ts +7 -7
  44. package/dist/kernel/owned-transaction.js +2 -2
  45. package/dist/kernel/pglite/driver.d.ts +2 -2
  46. package/dist/kernel/pglite/driver.js +18 -18
  47. package/dist/kernel/pglite/ops.d.ts +8 -3
  48. package/dist/kernel/pglite/ops.js +5 -5
  49. package/dist/kernel/port.d.ts +9 -76
  50. package/dist/kernel/port.js +1 -10
  51. package/dist/kernel/postgres/driver.d.ts +4 -2
  52. package/dist/kernel/postgres/driver.js +17 -17
  53. package/dist/kernel/postgres/ops.d.ts +5 -3
  54. package/dist/kernel/postgres/ops.js +3 -3
  55. package/dist/kernel/postgres/pglite-socket.d.ts +2 -2
  56. package/dist/kernel/postgres/pglite-socket.js +13 -13
  57. package/dist/kernel/schema-scope.d.ts +5 -2
  58. package/dist/kernel/schema-scope.js +1 -1
  59. package/dist/kernel/schema-shape.d.ts +7 -3
  60. package/dist/kernel/schema-shape.js +2 -2
  61. package/dist/kernel/session-lock.d.ts +6 -6
  62. package/dist/kernel/sqlite/driver.d.ts +16 -8
  63. package/dist/kernel/sqlite/driver.js +38 -38
  64. package/dist/kernel/sqlite/index.d.ts +1 -0
  65. package/dist/kernel/sqlite/index.js +1 -0
  66. package/dist/kernel/sqlite/ops.d.ts +4 -2
  67. package/dist/kernel/sqlite/ops.js +3 -3
  68. package/dist/kernel/sqlite/sqlite-only.d.ts +81 -0
  69. package/dist/kernel/sqlite/sqlite-only.js +58 -0
  70. package/dist/kernel/store-copy.d.ts +7 -7
  71. package/dist/kernel/store-copy.js +22 -14
  72. package/dist/kernel/typegen.d.ts +5 -3
  73. package/dist/kernel/typegen.js +1 -1
  74. package/dist/migrate/checksum.d.ts +3 -1
  75. package/dist/migrate/checksum.js +1 -1
  76. package/dist/migrate/index.d.ts +1 -1
  77. package/dist/migrate/legacy-ledger.d.ts +4 -4
  78. package/dist/migrate/runner.d.ts +12 -7
  79. package/dist/migrate/runner.js +7 -6
  80. package/dist/migrate/step.d.ts +3 -28
  81. package/dist/migrate/step.js +3 -3
  82. package/dist/owner-store/index.d.ts +47 -1
  83. package/dist/owner-store/index.js +28 -1
  84. package/dist/owner-store/migrations/0000_owner_store.d.ts +3 -2
  85. package/dist/owner-store/migrations/index.d.ts +1 -1
  86. package/dist/pglite/owner.d.ts +12 -4
  87. package/dist/pglite/owner.js +33 -27
  88. package/dist/pglite/socket-server.d.ts +5 -1
  89. package/dist/pglite/socket-server.js +5 -4
  90. package/dist/recovery/deep-link.d.ts +3 -3
  91. package/dist/recovery/degraded-banners.d.ts +3 -3
  92. package/dist/recovery/degraded-banners.js +3 -3
  93. package/dist/recovery/disclosure.d.ts +6 -6
  94. package/dist/recovery/disclosure.js +6 -6
  95. package/dist/recovery/evaluate-boot-migration-policy.d.ts +5 -5
  96. package/dist/recovery/evaluate-boot-migration-policy.js +5 -5
  97. package/dist/recovery/lookup-adapters.d.ts +1 -1
  98. package/dist/recovery/lookup-adapters.js +1 -1
  99. package/dist/recovery/migrate-forward-execute.d.ts +1 -1
  100. package/dist/recovery/migrate-forward-execute.js +5 -5
  101. package/dist/recovery/migrate-forward-hooks.d.ts +6 -6
  102. package/dist/recovery/migrate-forward-hooks.js +5 -5
  103. package/dist/recovery/operation-lock.d.ts +11 -11
  104. package/dist/recovery/operation-lock.js +3 -3
  105. package/dist/recovery/reconcile-interrupted-migration.d.ts +7 -7
  106. package/dist/recovery/reconcile-interrupted-migration.js +7 -7
  107. package/dist/recovery/recovery-orchestrator.d.ts +21 -21
  108. package/dist/recovery/recovery-orchestrator.js +9 -9
  109. package/dist/recovery/restore-hooks.d.ts +8 -8
  110. package/dist/recovery/restore-hooks.js +7 -7
  111. package/dist/recovery/restore-point-create.d.ts +3 -3
  112. package/dist/secrets-vault/repo.sql.d.ts +3 -3
  113. package/dist/secrets-vault/repo.sql.js +5 -4
  114. package/dist/settings/index.d.ts +3 -0
  115. package/dist/settings/index.js +2 -0
  116. package/dist/settings/repo.rows.d.ts +117 -0
  117. package/dist/settings/repo.rows.js +106 -0
  118. package/dist/settings/repo.sql.d.ts +99 -0
  119. package/dist/settings/repo.sql.js +219 -0
  120. package/dist/sqlite/checked-client.d.ts +1 -1
  121. package/dist/sqlite/checked-state.d.ts +3 -3
  122. package/dist/sqlite/db-ops.d.ts +1 -1
  123. package/dist/sqlite/db-ops.js +1 -1
  124. package/dist/sqlite/index.d.ts +1 -3
  125. package/dist/sqlite/index.js +2 -0
  126. package/dist/sqlite/inspect.d.ts +2 -2
  127. package/dist/sqlite/inspect.js +1 -1
  128. package/dist/sqlite/open.d.ts +1 -2
  129. package/dist/sqlite/stopped.d.ts +46 -0
  130. package/dist/sqlite/stopped.js +86 -0
  131. package/dist/sqlite/transaction.d.ts +2 -2
  132. package/dist/tools/database-catalog.d.ts +2 -2
  133. package/dist/tools/database-catalog.js +13 -3
  134. package/dist/tools/read-tools.js +70 -59
  135. package/dist/tools/restore-points.d.ts +1 -1
  136. package/dist/tools/transfer-tools.d.ts +0 -1
  137. package/dist/tools/transfer-tools.js +5 -4
  138. package/dist/transfer/copy-engine.js +10 -10
  139. package/dist/transfer/copy-order.d.ts +47 -0
  140. package/dist/transfer/copy-order.js +103 -0
  141. package/dist/transfer/index.d.ts +1 -0
  142. package/dist/transfer/index.js +1 -0
  143. package/dist/transfer/internal-ddl.d.ts +28 -6
  144. package/dist/transfer/internal-ddl.js +15 -15
  145. package/dist/transfer/postgres-ddl.js +6 -6
  146. package/dist/transfer/sqlite-source.d.ts +2 -3
  147. package/dist/transfer/sqlite-source.js +1 -1
  148. package/dist/verified-origin/index.d.ts +4 -0
  149. package/dist/verified-origin/index.js +3 -0
  150. package/dist/verified-origin/register.d.ts +43 -0
  151. package/dist/verified-origin/register.js +51 -0
  152. package/dist/verified-origin/repo.rows.d.ts +42 -0
  153. package/dist/verified-origin/repo.rows.js +47 -0
  154. package/dist/verified-origin/repo.sql.d.ts +67 -0
  155. package/dist/verified-origin/repo.sql.js +34 -0
  156. package/package.json +38 -11
  157. package/dist/sqlite/restore-types.d.ts +0 -46
  158. package/dist/sqlite/restore-types.js +0 -2
  159. package/dist/sqlite/sync-types.d.ts +0 -34
  160. package/dist/sqlite/sync-types.js +0 -2
  161. package/dist/sqlite/types.d.ts +0 -37
  162. package/dist/sqlite/types.js +0 -8
@@ -0,0 +1,72 @@
1
+ import { outboxEventValues } from "./outbox-repo.sql.js";
2
+ import { toItemRecord, toItemRow, toRecord, toRow, } from "./repo.rows.js";
3
+ export class SqlChangeSetRepo {
4
+ kernel;
5
+ tables;
6
+ constructor({ kernel, tables }, _optional = {}) {
7
+ this.kernel = kernel;
8
+ this.tables = tables;
9
+ }
10
+ // Host-owned table names need an explicit column schema, as in the settings adapter.
11
+ sets(db) {
12
+ return db.withTables();
13
+ }
14
+ items(db) {
15
+ return db.withTables();
16
+ }
17
+ /** Header + items + (when supplied) the outbox event land as one atomic transaction — never a
18
+ * partial write (the "transaction participation" requirement, and the
19
+ * resolution for the outbox event specifically; see this file's header). */
20
+ async insert({ record, items }, { event } = {}) {
21
+ await this.kernel.transaction(async () => this.kernel.run(async (db) => {
22
+ await this.sets(db).insertInto(this.tables.changeSets).values(toRow(record)).execute();
23
+ for (const item of items)
24
+ 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();
27
+ }));
28
+ }
29
+ async findById(required, _optional = {}) {
30
+ return this.kernel.run(async (db) => {
31
+ const row = await this.sets(db)
32
+ .selectFrom(this.tables.changeSets)
33
+ .selectAll()
34
+ .where("workspace_id", "=", required.workspaceId)
35
+ .where("id", "=", required.id)
36
+ .limit(1)
37
+ .executeTakeFirst();
38
+ if (!row)
39
+ return null;
40
+ const itemRows = await this.items(db)
41
+ .selectFrom(this.tables.changeSetItems)
42
+ .selectAll()
43
+ .where("change_set_id", "=", row.id)
44
+ .orderBy("position")
45
+ .execute();
46
+ return { changeSet: toRecord(row), items: itemRows.map(toItemRecord) };
47
+ });
48
+ }
49
+ async findByIdempotencyKey(required, _optional = {}) {
50
+ const row = await this.kernel.run((db) => this.sets(db)
51
+ .selectFrom(this.tables.changeSets)
52
+ .selectAll()
53
+ .where("workspace_id", "=", required.workspaceId)
54
+ .where("idempotency_key", "=", required.idempotencyKey)
55
+ .limit(1)
56
+ .executeTakeFirst());
57
+ return row ? toRecord(row) : null;
58
+ }
59
+ async listByWorkspace(required, _optional = {}) {
60
+ 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);
62
+ }
63
+ async save(record) {
64
+ await this.kernel.run((db) => this.sets(db)
65
+ .updateTable(this.tables.changeSets)
66
+ .set({ status: record.status, applied_at: record.appliedAt ?? null, reverted_at: record.revertedAt ?? null })
67
+ .where("workspace_id", "=", record.workspaceId)
68
+ .where("id", "=", record.id)
69
+ .execute());
70
+ }
71
+ }
72
+ //# sourceMappingURL=change-set-repo.sql.js.map
@@ -0,0 +1,4 @@
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";
3
+ export type { ChangeSetItemsTable, ChangeSetsTable, OutboxEventsTable } from "./repo.rows.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { SqlChangeSetRepo } from "./change-set-repo.sql.js";
2
+ export { SqlOutboxAdapter, outboxEventValues } from "./outbox-repo.sql.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,91 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { StorageKernel } from "@jini-ai/core/contracts/storage";
3
+ import type { ISODateTime, UUID } from "@jini-ai/core/primitives";
4
+ import type { DomainEvent, OutboxPort, OutboxRecord } from "@jini-ai/core/contracts/events";
5
+ /**
6
+ * @file THE `OutboxPort` adapter over `outbox_events` (Phase 1): one Kysely query body for
7
+ * every dialect (storage plan). Rule-of-two "second adapter" half;
8
+ * `core/events/memory-bus.ts`'s `InMemoryOutbox` is the first. The host's binding is the thin class that
9
+ * builds it from the content db handle: its kernel, its table name and its claim lease.
10
+ *
11
+ * Events enqueued by `executeCommand()` (via `ChangeSetRepoPort.insert()`'s co-persisted write) and
12
+ * by direct `OutboxPort.enqueue()` callers survive a restart. `enqueue()` is the plain single-row
13
+ * path for callers outside `executeCommand()`.
14
+ *
15
+ * `claimPending()` selects and marks rows `processing` inside one kernel transaction under
16
+ * `lockKey("outbox_events:claim")` ("claim rows atomically"): two concurrent claims can
17
+ * never both walk away with the same row — on Postgres too, where a transaction alone would not
18
+ * serialize the select-then-update.
19
+ *
20
+ * A claim is a lease (2026-09-14). The claim stores its expiry in `next_attempt_at`, and a
21
+ * `processing` row past that expiry is claimable again, so a process that dies mid-drain no longer
22
+ * strands its rows forever; delivery is at-least-once. `idx_outbox_events_claim` (status,
23
+ * next_attempt_at) covers the query.
24
+ */
25
+ /** Host-owned table name. No schema or product table default lives in the adapter. */
26
+ export interface OutboxTables {
27
+ outboxEvents: string;
28
+ }
29
+ export interface OutboxSqlRequired {
30
+ kernel: StorageKernel<Kysely<unknown>, unknown>;
31
+ tables: OutboxTables;
32
+ /** How long a claim holds a row before another claimer may take it; the host owns the number. */
33
+ claimLeaseMs: number;
34
+ }
35
+ export type OutboxSqlOptional = Record<string, never>;
36
+ /** The `outbox_events` row for a freshly-produced event (snake_case). Shared by enqueue
37
+ * and transactional callers so an audit event can be inserted atomically with its domain
38
+ * writes, using the identical row shape rather than a copy or an independent enqueue.
39
+ */
40
+ export declare function outboxEventValues(event: DomainEvent<object>): {
41
+ id: string;
42
+ workspace_id: string;
43
+ event_json: string;
44
+ status: string;
45
+ attempts: number;
46
+ next_attempt_at: string;
47
+ created_at: string;
48
+ };
49
+ export declare class SqlOutboxAdapter implements OutboxPort {
50
+ protected readonly kernel: StorageKernel<Kysely<unknown>, unknown>;
51
+ protected readonly tables: OutboxTables;
52
+ private readonly claimLeaseMs;
53
+ /**
54
+ * @param required.kernel the database holding the outbox table.
55
+ * @param required.tables.outboxEvents the host's outbox table name.
56
+ * @param required.claimLeaseMs claim lease length.
57
+ */
58
+ constructor({ kernel, tables, claimLeaseMs }: OutboxSqlRequired, _optional?: OutboxSqlOptional);
59
+ /** Host-owned table name needs an explicit column schema, as in the settings adapter. */
60
+ private table;
61
+ /** A repeated `event.id` is a no-op, never a primary-key error: ids are deterministic per event
62
+ * (`${aggregate}-${name}-${version}`, or `${aggregate}-entry.published-at-${publishAt}` for a
63
+ * scheduled go-live), so the same id is the same event, and the post go-live sweep
64
+ * (`features/post/go-live.ts`) relies on this to announce each go-live exactly once. */
65
+ enqueue(event: DomainEvent): Promise<void>;
66
+ /** Selects due rows (pending, or processing under an expired claim lease) and marks them
67
+ * `processing` under a fresh lease in one kernel transaction — the select-then-update is never
68
+ * observable as two separate steps to a concurrent claimer. Returned records keep the due time
69
+ * they were claimed at. */
70
+ claimPending({ batchSize, nowIso }: {
71
+ batchSize: number;
72
+ nowIso: ISODateTime;
73
+ }, _optional?: OutboxSqlOptional): Promise<OutboxRecord[]>;
74
+ /** Settles a claimed row as delivered; a row already settled (see {@link UNSETTLED_STATUSES}) is left as it is. */
75
+ markDelivered({ id }: {
76
+ id: UUID;
77
+ }, _optional?: OutboxSqlOptional): Promise<void>;
78
+ /**
79
+ * Marks a claimed row failed and persists whichever `nextStatus` the caller decided (the retry-cap
80
+ * decision lives with the worker — `contracts/core/events/outbox-worker.ts`'s header doc). A
81
+ * single UPDATE, same shape as `markDelivered`: the caller already had every value it needed.
82
+ * A row already settled (see {@link UNSETTLED_STATUSES}) is left as it is.
83
+ */
84
+ markFailed({ id, error, nextAttemptAt, nextStatus }: {
85
+ id: UUID;
86
+ error: string;
87
+ nextAttemptAt: ISODateTime;
88
+ nextStatus: Extract<OutboxRecord["status"], "pending" | "failed">;
89
+ }, _optional?: OutboxSqlOptional): Promise<void>;
90
+ }
91
+ //# sourceMappingURL=outbox-repo.sql.d.ts.map
@@ -0,0 +1,108 @@
1
+ function toRecord(row) {
2
+ return {
3
+ id: row.id,
4
+ event: JSON.parse(row.event_json),
5
+ status: row.status,
6
+ attempts: row.attempts,
7
+ nextAttemptAt: row.next_attempt_at,
8
+ lastError: row.last_error ?? undefined,
9
+ createdAt: row.created_at,
10
+ };
11
+ }
12
+ /** Statuses `claimPending` may take: never claimed, or claimed under a lease that may have expired. */
13
+ const CLAIMABLE_STATUSES = ["pending", "processing"];
14
+ /**
15
+ * Statuses an attempt's outcome may still overwrite (F9C, 2026-10-20). `delivered` and `failed` are
16
+ * settled: a purge fails a job whose attempt may still be in flight (`form-delivery-repo.ts`
17
+ * `scrubPurged`), and that attempt's outcome must not revive it, or the retry would send the
18
+ * blanked answers. `pending` stays writable because a timeout records `pending` while its handler
19
+ * keeps running, and Jini's `recordOverrun` then lets the late outcome replace that record.
20
+ */
21
+ const UNSETTLED_STATUSES = ["pending", "processing"];
22
+ /** The `outbox_events` row for a freshly-produced event (snake_case). Shared by enqueue
23
+ * and transactional callers so an audit event can be inserted atomically with its domain
24
+ * writes, using the identical row shape rather than a copy or an independent enqueue.
25
+ */
26
+ export function outboxEventValues(event) {
27
+ return {
28
+ id: event.id,
29
+ workspace_id: event.workspaceId,
30
+ event_json: JSON.stringify(event),
31
+ status: "pending",
32
+ attempts: 0,
33
+ next_attempt_at: event.occurredAt,
34
+ created_at: event.occurredAt,
35
+ };
36
+ }
37
+ export class SqlOutboxAdapter {
38
+ kernel;
39
+ tables;
40
+ claimLeaseMs;
41
+ /**
42
+ * @param required.kernel the database holding the outbox table.
43
+ * @param required.tables.outboxEvents the host's outbox table name.
44
+ * @param required.claimLeaseMs claim lease length.
45
+ */
46
+ constructor({ kernel, tables, claimLeaseMs }, _optional = {}) {
47
+ this.kernel = kernel;
48
+ this.tables = tables;
49
+ this.claimLeaseMs = claimLeaseMs;
50
+ }
51
+ /** Host-owned table name needs an explicit column schema, as in the settings adapter. */
52
+ table(db) {
53
+ return db.withTables();
54
+ }
55
+ /** A repeated `event.id` is a no-op, never a primary-key error: ids are deterministic per event
56
+ * (`${aggregate}-${name}-${version}`, or `${aggregate}-entry.published-at-${publishAt}` for a
57
+ * scheduled go-live), so the same id is the same event, and the post go-live sweep
58
+ * (`features/post/go-live.ts`) relies on this to announce each go-live exactly once. */
59
+ 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());
61
+ }
62
+ /** Selects due rows (pending, or processing under an expired claim lease) and marks them
63
+ * `processing` under a fresh lease in one kernel transaction — the select-then-update is never
64
+ * observable as two separate steps to a concurrent claimer. Returned records keep the due time
65
+ * they were claimed at. */
66
+ async claimPending({ batchSize, nowIso }, _optional = {}) {
67
+ const leaseExpiresAt = new Date(Date.parse(nowIso) + this.claimLeaseMs).toISOString();
68
+ return this.kernel.transaction(async () => {
69
+ await this.kernel.lockKey("outbox_events:claim");
70
+ const eligible = await this.kernel.run((db) => this.table(db)
71
+ .selectFrom(this.tables.outboxEvents)
72
+ .selectAll()
73
+ .where("status", "in", CLAIMABLE_STATUSES)
74
+ .where("next_attempt_at", "<=", nowIso)
75
+ .orderBy("next_attempt_at", "asc")
76
+ .limit(batchSize)
77
+ .execute());
78
+ for (const row of eligible) {
79
+ await this.kernel.run((db) => this.table(db)
80
+ .updateTable(this.tables.outboxEvents)
81
+ .set({ status: "processing", attempts: row.attempts + 1, next_attempt_at: leaseExpiresAt })
82
+ .where("id", "=", row.id)
83
+ .execute());
84
+ }
85
+ return eligible.map((row) => toRecord({ ...row, status: "processing", attempts: row.attempts + 1 }));
86
+ });
87
+ }
88
+ /** Settles a claimed row as delivered; a row already settled (see {@link UNSETTLED_STATUSES}) is left as it is. */
89
+ async markDelivered({ id }, _optional = {}) {
90
+ await this.kernel.run((db) => this.table(db).updateTable(this.tables.outboxEvents).set({ status: "delivered" }).where("id", "=", id)
91
+ .where("status", "in", UNSETTLED_STATUSES).execute());
92
+ }
93
+ /**
94
+ * Marks a claimed row failed and persists whichever `nextStatus` the caller decided (the retry-cap
95
+ * decision lives with the worker — `contracts/core/events/outbox-worker.ts`'s header doc). A
96
+ * single UPDATE, same shape as `markDelivered`: the caller already had every value it needed.
97
+ * A row already settled (see {@link UNSETTLED_STATUSES}) is left as it is.
98
+ */
99
+ async markFailed({ id, error, nextAttemptAt, nextStatus }, _optional = {}) {
100
+ await this.kernel.run((db) => this.table(db)
101
+ .updateTable(this.tables.outboxEvents)
102
+ .set({ status: nextStatus, last_error: error, next_attempt_at: nextAttemptAt })
103
+ .where("id", "=", id)
104
+ .where("status", "in", UNSETTLED_STATUSES)
105
+ .execute());
106
+ }
107
+ }
108
+ //# sourceMappingURL=outbox-repo.sql.js.map
@@ -0,0 +1,44 @@
1
+ import type { Generated, Insertable, Selectable } from "kysely";
2
+ import type { ChangeSetItemRecord, ChangeSetRecord } from "@jini-ai/core/contracts/events";
3
+ /** Stored column shapes, copied without schema changes; the table names are host-owned (see `ChangeSetTables`, `OutboxTables`). */
4
+ export interface ChangeSetItemsTable {
5
+ id: string;
6
+ change_set_id: string;
7
+ entity_type: string;
8
+ entity_id: string;
9
+ operation: string;
10
+ before_revision_id: string | null;
11
+ after_revision_id: string | null;
12
+ inverse_payload_json: string | null;
13
+ entity_version_at_apply: number | null;
14
+ position: number;
15
+ }
16
+ export interface ChangeSetsTable {
17
+ id: string;
18
+ workspace_id: string;
19
+ actor_id: string | null;
20
+ status: string;
21
+ summary: string;
22
+ idempotency_key: string | null;
23
+ intent_ref: string | null;
24
+ created_at: string;
25
+ applied_at: string | null;
26
+ reverted_at: string | null;
27
+ }
28
+ export interface OutboxEventsTable {
29
+ id: string;
30
+ workspace_id: string;
31
+ event_json: string;
32
+ status: string;
33
+ attempts: Generated<number>;
34
+ next_attempt_at: string;
35
+ last_error: string | null;
36
+ created_at: string;
37
+ }
38
+ export declare function toRecord(row: Selectable<ChangeSetsTable>): ChangeSetRecord;
39
+ 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>;
42
+ /** `toItemRecord`'s inverse: absent optionals as SQL NULL, the inverse payload as JSON text. */
43
+ export declare function toItemRow(item: ChangeSetItemRecord): Insertable<ChangeSetItemsTable>;
44
+ //# sourceMappingURL=repo.rows.d.ts.map
@@ -0,0 +1,59 @@
1
+ export function toRecord(row) {
2
+ return {
3
+ id: row.id,
4
+ workspaceId: row.workspace_id,
5
+ actorId: row.actor_id ?? undefined,
6
+ status: row.status,
7
+ summary: row.summary,
8
+ idempotencyKey: row.idempotency_key ?? undefined,
9
+ intentRef: row.intent_ref ?? undefined,
10
+ createdAt: row.created_at,
11
+ appliedAt: row.applied_at ?? undefined,
12
+ revertedAt: row.reverted_at ?? undefined,
13
+ };
14
+ }
15
+ export function toItemRecord(row) {
16
+ return {
17
+ id: row.id,
18
+ changeSetId: row.change_set_id,
19
+ entityType: row.entity_type,
20
+ entityId: row.entity_id,
21
+ operation: row.operation,
22
+ beforeRevisionId: row.before_revision_id ?? undefined,
23
+ afterRevisionId: row.after_revision_id ?? undefined,
24
+ inversePayload: row.inverse_payload_json == null ? undefined : JSON.parse(row.inverse_payload_json),
25
+ entityVersionAtApply: row.entity_version_at_apply ?? undefined,
26
+ position: row.position,
27
+ };
28
+ }
29
+ /** `toRecord`'s inverse: every absent optional field is written as SQL NULL. */
30
+ export function toRow(record) {
31
+ return {
32
+ id: record.id,
33
+ workspace_id: record.workspaceId,
34
+ actor_id: record.actorId ?? null,
35
+ status: record.status,
36
+ summary: record.summary,
37
+ idempotency_key: record.idempotencyKey ?? null,
38
+ intent_ref: record.intentRef ?? null,
39
+ created_at: record.createdAt,
40
+ applied_at: record.appliedAt ?? null,
41
+ reverted_at: record.revertedAt ?? null,
42
+ };
43
+ }
44
+ /** `toItemRecord`'s inverse: absent optionals as SQL NULL, the inverse payload as JSON text. */
45
+ export function toItemRow(item) {
46
+ return {
47
+ id: item.id,
48
+ change_set_id: item.changeSetId,
49
+ entity_type: item.entityType,
50
+ entity_id: item.entityId,
51
+ operation: item.operation,
52
+ before_revision_id: item.beforeRevisionId ?? null,
53
+ after_revision_id: item.afterRevisionId ?? null,
54
+ inverse_payload_json: item.inversePayload === undefined ? null : JSON.stringify(item.inversePayload),
55
+ entity_version_at_apply: item.entityVersionAtApply ?? null,
56
+ position: item.position,
57
+ };
58
+ }
59
+ //# sourceMappingURL=repo.rows.js.map
@@ -0,0 +1,3 @@
1
+ export { SqlTokenStore, type TokenStoreSqlRequired, type TokenStoreTables } from "./repo.sql.js";
2
+ export type { GatedMutationTokensTable } from "./repo.rows.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,2 @@
1
+ export { SqlTokenStore } from "./repo.sql.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,19 @@
1
+ import type { Insertable, Selectable } from "kysely";
2
+ import type { ConfirmationTokenRecord } from "@jini-ai/core/gated-mutations";
3
+ /** Stored column shape, copied without schema changes; the table name is host-owned (see `TokenStoreTables`). */
4
+ export interface GatedMutationTokensTable {
5
+ confirmation_token: string;
6
+ plan_hash: string;
7
+ scope_id: string;
8
+ confirmer_principal_id: string;
9
+ status: string;
10
+ created_at: string;
11
+ expires_at: string;
12
+ }
13
+ export declare function toRecord({ row }: {
14
+ row: Selectable<GatedMutationTokensTable>;
15
+ }, _optional?: Record<string, never>): ConfirmationTokenRecord;
16
+ export declare function toRow({ record }: {
17
+ record: ConfirmationTokenRecord;
18
+ }, _optional?: Record<string, never>): Insertable<GatedMutationTokensTable>;
19
+ //# sourceMappingURL=repo.rows.d.ts.map
@@ -0,0 +1,23 @@
1
+ export function toRecord({ row }, _optional = {}) {
2
+ return {
3
+ confirmationToken: row.confirmation_token,
4
+ planHash: row.plan_hash,
5
+ scopeId: row.scope_id,
6
+ confirmerPrincipalId: row.confirmer_principal_id,
7
+ status: row.status,
8
+ createdAt: row.created_at,
9
+ expiresAt: row.expires_at,
10
+ };
11
+ }
12
+ export function toRow({ record }, _optional = {}) {
13
+ return {
14
+ confirmation_token: record.confirmationToken,
15
+ plan_hash: record.planHash,
16
+ scope_id: record.scopeId,
17
+ confirmer_principal_id: record.confirmerPrincipalId,
18
+ status: record.status,
19
+ created_at: record.createdAt,
20
+ expires_at: record.expiresAt,
21
+ };
22
+ }
23
+ //# sourceMappingURL=repo.rows.js.map
@@ -0,0 +1,67 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { StorageKernel } from "@jini-ai/core/contracts/storage";
3
+ import { type ConfirmationTokenRecord, type TokenStorePort } from "@jini-ai/core/gated-mutations";
4
+ /**
5
+ * @file Durability fix — THE durable `TokenStorePort` adapter: one Kysely query body for
6
+ * every dialect (storage plan). `sqlite/gated-mutation-token-repo.sqlite.ts` is the
7
+ * thin subclass the composition root builds from the content db handle.
8
+ *
9
+ * Purpose:
10
+ * `core/gated-mutations/token.ts`'s own file header disclosed that a durable token store "is not
11
+ * required by this test slice" and shipped only `InMemoryTokenStore`. That made the
12
+ * `gated-mutations` capability-inventory entry `hasDurableAdapter: false` — a `classification:
13
+ * "production"` capability with no durable adapter, which `production-readiness-gate.ts`'s
14
+ * `collectDurabilityFailures` unconditionally fails on. This adapter closes that gap: confirmation
15
+ * tokens survive a process restart via the `gated_mutation_tokens` table (migration `0052`).
16
+ *
17
+ * `tryRedeem` is single-use on every dialect: the read, the `isRedeemable` check and the
18
+ * conditional write run inside one kernel transaction holding `lockKey` on the token, so no other
19
+ * redemption of the same token can interleave (SQLite: `BEGIN IMMEDIATE` holds the write lock;
20
+ * Postgres: a transaction advisory lock — READ COMMITTED alone would let two redeems both read
21
+ * `minted`). The update is also conditioned on the status it read, so a missed lock could never
22
+ * turn into a second redemption.
23
+ *
24
+ * Architectural role:
25
+ * Infrastructure adapter. `core/gated-mutations` never imports this file — it depends only on
26
+ * `TokenStorePort`; composition roots bind the concrete class.
27
+ */
28
+ /** Host-owned table name. No schema or product table default lives in the adapter. */
29
+ export interface TokenStoreTables {
30
+ tokens: string;
31
+ }
32
+ export interface TokenStoreSqlRequired {
33
+ kernel: StorageKernel<Kysely<unknown>, unknown>;
34
+ tables: TokenStoreTables;
35
+ }
36
+ export declare class SqlTokenStore implements TokenStorePort {
37
+ protected readonly kernel: StorageKernel<Kysely<unknown>, unknown>;
38
+ protected readonly tables: TokenStoreTables;
39
+ constructor({ kernel, tables }: TokenStoreSqlRequired, _optional?: Record<string, never>);
40
+ private from;
41
+ save({ record }: {
42
+ record: ConfirmationTokenRecord;
43
+ }, _optional?: Record<string, never>): Promise<void>;
44
+ findByToken({ token }: {
45
+ token: string;
46
+ }, _optional?: Record<string, never>): Promise<ConfirmationTokenRecord | null>;
47
+ /** See this file's own header for what makes this single-use on every dialect. */
48
+ tryRedeem(params: {
49
+ token: string;
50
+ now: string;
51
+ }, _optional?: Record<string, never>): Promise<{
52
+ redeemed: boolean;
53
+ record: ConfirmationTokenRecord | null;
54
+ }>;
55
+ /**
56
+ * Atomically revokes only a minted token; a concurrent redemption remains terminal.
57
+ * @param required.token The credential to revoke.
58
+ * @returns Resolves after one conditional UPDATE, including when no minted row exists.
59
+ * @complexity One indexed UPDATE; O(1) application time and space.
60
+ */
61
+ expire({ token }: {
62
+ token: string;
63
+ }, _optional?: Record<string, never>): Promise<void>;
64
+ /** Not part of the core port: the host's legacy token store contract still reads it. */
65
+ count(): Promise<number>;
66
+ }
67
+ //# sourceMappingURL=repo.sql.d.ts.map
@@ -0,0 +1,71 @@
1
+ import { isRedeemable } from "@jini-ai/core/gated-mutations";
2
+ import { toRecord, toRow } from "./repo.rows.js";
3
+ export class SqlTokenStore {
4
+ kernel;
5
+ tables;
6
+ constructor({ kernel, tables }, _optional = {}) {
7
+ this.kernel = kernel;
8
+ this.tables = tables;
9
+ }
10
+ // Host-owned table names need an explicit column schema, as in the settings adapter.
11
+ from(db) {
12
+ return db.withTables().selectFrom(this.tables.tokens);
13
+ }
14
+ async save({ record }, _optional = {}) {
15
+ const row = toRow({ record });
16
+ await this.kernel.run((db) => db
17
+ .withTables()
18
+ .insertInto(this.tables.tokens)
19
+ .values(row)
20
+ .onConflict((oc) => oc.column("confirmation_token").doUpdateSet(row))
21
+ .execute());
22
+ }
23
+ async findByToken({ token }, _optional = {}) {
24
+ const row = await this.kernel.run((db) => this.from(db).selectAll().where("confirmation_token", "=", token).executeTakeFirst());
25
+ return row ? toRecord({ row }) : null;
26
+ }
27
+ /** See this file's own header for what makes this single-use on every dialect. */
28
+ async tryRedeem(params, _optional = {}) {
29
+ return this.kernel.transaction(async () => {
30
+ await this.kernel.lockKey(`gated_mutation_tokens:${params.token}`);
31
+ const row = await this.kernel.run((db) => this.from(db).selectAll().where("confirmation_token", "=", params.token).executeTakeFirst());
32
+ if (!row)
33
+ return { redeemed: false, record: null };
34
+ const record = toRecord({ row });
35
+ if (!isRedeemable({ record, now: params.now }))
36
+ return { redeemed: false, record };
37
+ const result = await this.kernel.run((db) => db
38
+ .withTables()
39
+ .updateTable(this.tables.tokens)
40
+ .set({ status: "redeemed" })
41
+ .where("confirmation_token", "=", params.token)
42
+ .where("status", "=", row.status)
43
+ .executeTakeFirst());
44
+ if (Number(result.numUpdatedRows) === 0)
45
+ return { redeemed: false, record };
46
+ return { redeemed: true, record: { ...record, status: "redeemed" } };
47
+ });
48
+ }
49
+ /**
50
+ * Atomically revokes only a minted token; a concurrent redemption remains terminal.
51
+ * @param required.token The credential to revoke.
52
+ * @returns Resolves after one conditional UPDATE, including when no minted row exists.
53
+ * @complexity One indexed UPDATE; O(1) application time and space.
54
+ */
55
+ async expire({ token }, _optional = {}) {
56
+ await this.kernel.run((db) => db
57
+ .withTables()
58
+ .updateTable(this.tables.tokens)
59
+ .set({ status: "expired" })
60
+ .where("confirmation_token", "=", token)
61
+ .where("status", "=", "minted")
62
+ .execute());
63
+ }
64
+ /** Not part of the core port: the host's legacy token store contract still reads it. */
65
+ async count() {
66
+ // An ungrouped COUNT(*) always yields exactly one non-null row, so no empty-result fallback exists.
67
+ const row = await this.kernel.run((db) => this.from(db).select((eb) => eb.fn.countAll().as("value")).executeTakeFirstOrThrow());
68
+ return Number(row.value);
69
+ }
70
+ }
71
+ //# sourceMappingURL=repo.sql.js.map