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

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 +39 -12
  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,99 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { StorageKernel } from "@jini-ai/core/contracts/storage";
3
+ import type { SettingDefinitionRecord, SettingRevisionRecord, SettingValueRecord, SettingsRepoPort } from "@jini-ai/core/settings";
4
+ /**
5
+ * @file THE `SettingsRepoPort` adapter (rule-of-two #2): one Kysely query body for every dialect
6
+ * the storage kernel drives (storage plan). Satisfies the same port as `@jini-ai/core/settings`'
7
+ * `InMemorySettingsRepo`; `repo.sqlite.ts` is the thin subclass the call sites build from the content db handle.
8
+ *
9
+ * `transaction` is the kernel's: `write-service.ts`'s chokepoint callback awaits repo calls inside it, which
10
+ * the kernel allows ("`BEGIN IMMEDIATE` -> ... -> COMMIT" on SQLite).
11
+ */
12
+ /** Host-owned table names. No schema or product table defaults live in the adapter. */
13
+ export interface SettingsTables {
14
+ definitions: string;
15
+ valuesGlobal: string;
16
+ valuesWorkspace: string;
17
+ valuesUser: string;
18
+ revisions: string;
19
+ }
20
+ export interface SettingsSqlRequired {
21
+ kernel: StorageKernel<Kysely<unknown>, unknown>;
22
+ tables: SettingsTables;
23
+ }
24
+ export declare class SqlSettingsRepo implements SettingsRepoPort {
25
+ protected readonly kernel: StorageKernel<Kysely<unknown>, unknown>;
26
+ protected readonly tables: SettingsTables;
27
+ constructor({ kernel, tables }: SettingsSqlRequired, _optional?: Record<string, never>);
28
+ findActiveDefinition(required: {
29
+ namespace: string;
30
+ key: string;
31
+ workspaceId: string | null;
32
+ }): Promise<SettingDefinitionRecord | null>;
33
+ findDefinitionBySettingId(required: {
34
+ settingId: string;
35
+ version?: number;
36
+ }): Promise<SettingDefinitionRecord | null>;
37
+ listActiveDefinitions(required: {
38
+ workspaceId: string | null;
39
+ }): Promise<SettingDefinitionRecord[]>;
40
+ saveDefinition(record: SettingDefinitionRecord): Promise<void>;
41
+ getGlobalValue(settingId: string): Promise<SettingValueRecord | null>;
42
+ getWorkspaceValue(required: {
43
+ workspaceId: string;
44
+ settingId: string;
45
+ }): Promise<SettingValueRecord | null>;
46
+ getUserValue(required: {
47
+ workspaceId: string;
48
+ principalId: string;
49
+ settingId: string;
50
+ }): Promise<SettingValueRecord | null>;
51
+ saveGlobalValue(record: SettingValueRecord): Promise<void>;
52
+ saveWorkspaceValue(record: SettingValueRecord): Promise<void>;
53
+ saveUserValue(record: SettingValueRecord): Promise<void>;
54
+ listWorkspaceValues(required: {
55
+ workspaceId: string;
56
+ }): Promise<SettingValueRecord[]>;
57
+ listUserValues(required: {
58
+ workspaceId: string;
59
+ principalId: string;
60
+ }): Promise<SettingValueRecord[]>;
61
+ listUserValuesByWorkspace(required: {
62
+ workspaceId: string;
63
+ }): Promise<SettingValueRecord[]>;
64
+ deleteWorkspaceValue(required: {
65
+ workspaceId: string;
66
+ settingId: string;
67
+ }): Promise<void>;
68
+ deleteUserValue(required: {
69
+ workspaceId: string;
70
+ principalId: string;
71
+ settingId: string;
72
+ }): Promise<void>;
73
+ /**
74
+ * Appends one revision and returns its `seq`. Takes `lockKey` on the revision stream inside the
75
+ * caller's transaction (or its own): `listRevisionsSince` subscribers page by `seq`, so a lower
76
+ * `seq` must never commit after a higher one — on Postgres, sequence values are handed out before
77
+ * commit, and without the lock two writers could commit out of order and a subscriber would skip
78
+ * the late one. SQLite's `BEGIN IMMEDIATE` already serializes writers.
79
+ */
80
+ appendRevision(record: Omit<SettingRevisionRecord, "seq">): Promise<number>;
81
+ listRevisions(required: {
82
+ settingId: string;
83
+ }): Promise<SettingRevisionRecord[]>;
84
+ listRevisionsSince(required: {
85
+ sinceSeq: number;
86
+ limit: number;
87
+ workspaceId: string;
88
+ }): Promise<SettingRevisionRecord[]>;
89
+ maxRevisionSeq(): Promise<number>;
90
+ /**
91
+ * Runs `fn` inside one kernel transaction. A call nested in the same async context joins the
92
+ * outer one; an unrelated caller (another request) waits its turn instead of landing inside it —
93
+ * the kernel tracks this per async context, so two independent root calls never merge (the defect
94
+ * an instance-level depth counter once had). A caller that needs several writes to commit together
95
+ * opens ONE transaction around them — see `resetNamespace`.
96
+ */
97
+ transaction<T>(fn: () => Promise<T>): Promise<T>;
98
+ }
99
+ //# sourceMappingURL=repo.sql.d.ts.map
@@ -0,0 +1,219 @@
1
+ import { toDefinitionRecord, toDefinitionRow, toDefinitionUpdate, toRevisionRecord, toValueRecord, valueColumns, } from "./repo.rows.js";
2
+ // Host-owned table names need an explicit column schema per table, as in the redirects adapter.
3
+ const definitionsOf = (db, tables) => db.withTables().selectFrom(tables.definitions);
4
+ const revisionsOf = (db, tables) => db.withTables().selectFrom(tables.revisions);
5
+ const globalOf = (db, tables) => db.withTables().selectFrom(tables.valuesGlobal);
6
+ const workspaceOf = (db, tables) => db.withTables().selectFrom(tables.valuesWorkspace);
7
+ const userOf = (db, tables) => db.withTables().selectFrom(tables.valuesUser);
8
+ export class SqlSettingsRepo {
9
+ kernel;
10
+ tables;
11
+ constructor({ kernel, tables }, _optional = {}) {
12
+ this.kernel = kernel;
13
+ this.tables = tables;
14
+ }
15
+ async findActiveDefinition(required) {
16
+ const row = await this.kernel.run((db) => definitionsOf(db, this.tables)
17
+ .selectAll()
18
+ .where("namespace", "=", required.namespace)
19
+ .where("key", "=", required.key)
20
+ .where("workspace_id", required.workspaceId === null ? "is" : "=", required.workspaceId)
21
+ .where("status", "in", ["active", "alias", "tombstone"])
22
+ .orderBy("version")
23
+ .limit(1)
24
+ .executeTakeFirst());
25
+ return row ? toDefinitionRecord(row) : null;
26
+ }
27
+ async findDefinitionBySettingId(required) {
28
+ const rows = await this.kernel.run((db) => definitionsOf(db, this.tables).selectAll().where("setting_id", "=", required.settingId).execute());
29
+ if (required.version != null) {
30
+ const row = rows.find((r) => r.version === required.version);
31
+ return row ? toDefinitionRecord(row) : null;
32
+ }
33
+ const active = rows.find((r) => r.status === "active");
34
+ if (active)
35
+ return toDefinitionRecord(active);
36
+ const latest = rows.sort((a, b) => b.version - a.version)[0];
37
+ return latest ? toDefinitionRecord(latest) : null;
38
+ }
39
+ async listActiveDefinitions(required) {
40
+ const rows = await this.kernel.run((db) => definitionsOf(db, this.tables)
41
+ .selectAll()
42
+ .where("workspace_id", required.workspaceId === null ? "is" : "=", required.workspaceId)
43
+ .where("status", "in", ["active", "alias"])
44
+ .orderBy("setting_id")
45
+ .orderBy("version")
46
+ .execute());
47
+ return rows.map(toDefinitionRecord);
48
+ }
49
+ async saveDefinition(record) {
50
+ const row = toDefinitionRow({ record });
51
+ const updatable = toDefinitionUpdate({ record });
52
+ await this.kernel.run((db) => db
53
+ .withTables()
54
+ .insertInto(this.tables.definitions)
55
+ .values(row)
56
+ .onConflict((oc) => oc.columns(["setting_id", "version"]).doUpdateSet(updatable))
57
+ .execute());
58
+ }
59
+ async getGlobalValue(settingId) {
60
+ const row = await this.kernel.run((db) => globalOf(db, this.tables).selectAll().where("setting_id", "=", settingId).limit(1).executeTakeFirst());
61
+ return row ? toValueRecord({ row, scope: "global", workspaceId: null, principalId: null }) : null;
62
+ }
63
+ async getWorkspaceValue(required) {
64
+ const row = await this.kernel.run((db) => workspaceOf(db, this.tables)
65
+ .selectAll()
66
+ .where("workspace_id", "=", required.workspaceId)
67
+ .where("setting_id", "=", required.settingId)
68
+ .limit(1)
69
+ .executeTakeFirst());
70
+ return row ? toValueRecord({ row, scope: "workspace", workspaceId: required.workspaceId, principalId: null }) : null;
71
+ }
72
+ async getUserValue(required) {
73
+ const row = await this.kernel.run((db) => userOf(db, this.tables)
74
+ .selectAll()
75
+ .where("workspace_id", "=", required.workspaceId)
76
+ .where("principal_id", "=", required.principalId)
77
+ .where("setting_id", "=", required.settingId)
78
+ .limit(1)
79
+ .executeTakeFirst());
80
+ return row ? toValueRecord({ row, scope: "user", workspaceId: required.workspaceId, principalId: required.principalId }) : null;
81
+ }
82
+ async saveGlobalValue(record) {
83
+ const columns = valueColumns({ record });
84
+ await this.kernel.run((db) => db
85
+ .withTables()
86
+ .insertInto(this.tables.valuesGlobal)
87
+ .values({ setting_id: record.settingId, ...columns })
88
+ .onConflict((oc) => oc.column("setting_id").doUpdateSet(columns))
89
+ .execute());
90
+ }
91
+ async saveWorkspaceValue(record) {
92
+ const workspaceId = record.workspaceId;
93
+ if (workspaceId == null)
94
+ throw new Error("saveWorkspaceValue requires workspaceId");
95
+ const columns = valueColumns({ record });
96
+ await this.kernel.run((db) => db
97
+ .withTables()
98
+ .insertInto(this.tables.valuesWorkspace)
99
+ .values({ setting_id: record.settingId, workspace_id: workspaceId, ...columns })
100
+ .onConflict((oc) => oc.columns(["workspace_id", "setting_id"]).doUpdateSet(columns))
101
+ .execute());
102
+ }
103
+ async saveUserValue(record) {
104
+ const { workspaceId, principalId } = record;
105
+ if (workspaceId == null || principalId == null) {
106
+ throw new Error("saveUserValue requires workspaceId and principalId");
107
+ }
108
+ const columns = valueColumns({ record });
109
+ await this.kernel.run((db) => db
110
+ .withTables()
111
+ .insertInto(this.tables.valuesUser)
112
+ .values({ setting_id: record.settingId, workspace_id: workspaceId, principal_id: principalId, ...columns })
113
+ .onConflict((oc) => oc.columns(["workspace_id", "principal_id", "setting_id"]).doUpdateSet(columns))
114
+ .execute());
115
+ }
116
+ async listWorkspaceValues(required) {
117
+ const rows = await this.kernel.run((db) => workspaceOf(db, this.tables).selectAll().where("workspace_id", "=", required.workspaceId).execute());
118
+ return rows.map((r) => toValueRecord({ row: r, scope: "workspace", workspaceId: required.workspaceId, principalId: null }));
119
+ }
120
+ async listUserValues(required) {
121
+ const rows = await this.kernel.run((db) => userOf(db, this.tables)
122
+ .selectAll()
123
+ .where("workspace_id", "=", required.workspaceId)
124
+ .where("principal_id", "=", required.principalId)
125
+ .execute());
126
+ return rows.map((r) => toValueRecord({ row: r, scope: "user", workspaceId: required.workspaceId, principalId: required.principalId }));
127
+ }
128
+ async listUserValuesByWorkspace(required) {
129
+ const rows = await this.kernel.run((db) => userOf(db, this.tables).selectAll().where("workspace_id", "=", required.workspaceId).execute());
130
+ return rows.map((r) => toValueRecord({ row: r, scope: "user", workspaceId: required.workspaceId, principalId: r.principal_id }));
131
+ }
132
+ // The two deletes below remove an override row (the value falls back to its default); they are the
133
+ // adapter's only deletes and the settings ledger (`revisions`) is never touched by them.
134
+ async deleteWorkspaceValue(required) {
135
+ await this.kernel.run((db) => db
136
+ .withTables()
137
+ .deleteFrom(this.tables.valuesWorkspace)
138
+ .where("workspace_id", "=", required.workspaceId)
139
+ .where("setting_id", "=", required.settingId)
140
+ .execute());
141
+ }
142
+ async deleteUserValue(required) {
143
+ await this.kernel.run((db) => db
144
+ .withTables()
145
+ .deleteFrom(this.tables.valuesUser)
146
+ .where("workspace_id", "=", required.workspaceId)
147
+ .where("principal_id", "=", required.principalId)
148
+ .where("setting_id", "=", required.settingId)
149
+ .execute());
150
+ }
151
+ /**
152
+ * Appends one revision and returns its `seq`. Takes `lockKey` on the revision stream inside the
153
+ * caller's transaction (or its own): `listRevisionsSince` subscribers page by `seq`, so a lower
154
+ * `seq` must never commit after a higher one — on Postgres, sequence values are handed out before
155
+ * commit, and without the lock two writers could commit out of order and a subscriber would skip
156
+ * the late one. SQLite's `BEGIN IMMEDIATE` already serializes writers.
157
+ */
158
+ async appendRevision(record) {
159
+ return this.kernel.transaction(async () => {
160
+ await this.kernel.lockKey("setting_revisions");
161
+ const inserted = await this.kernel.run((db) => db
162
+ .withTables()
163
+ .insertInto(this.tables.revisions)
164
+ .values({
165
+ entity_kind: record.entityKind,
166
+ setting_id: record.settingId,
167
+ scope: record.scope,
168
+ workspace_id: record.workspaceId,
169
+ principal_id: record.principalId,
170
+ op: record.op,
171
+ before_json: record.beforeJson == null ? null : JSON.stringify(record.beforeJson),
172
+ after_json: record.afterJson == null ? null : JSON.stringify(record.afterJson),
173
+ def_version: record.defVersion,
174
+ actor: record.actor,
175
+ origin_plugin_id: record.originPluginId,
176
+ change_set_id: record.changeSetId,
177
+ created_at: record.createdAt,
178
+ })
179
+ .returning("seq")
180
+ .executeTakeFirstOrThrow());
181
+ return Number(inserted.seq);
182
+ });
183
+ }
184
+ async listRevisions(required) {
185
+ const rows = await this.kernel.run((db) => revisionsOf(db, this.tables).selectAll().where("setting_id", "=", required.settingId).orderBy("seq").execute());
186
+ return rows.map(toRevisionRecord);
187
+ }
188
+ async listRevisionsSince(required) {
189
+ const rows = await this.kernel.run((db) => revisionsOf(db, this.tables)
190
+ .selectAll()
191
+ .where("seq", ">", required.sinceSeq)
192
+ // A NULL `workspace_id` is a platform definition or a `global`-scope value — resolved by
193
+ // every workspace, so every workspace must hear about it. Everything else belongs to one
194
+ // tenant. See the port's doc for why this is a page-sizing predicate rather than the
195
+ // disclosure check: it must stay a superset of `isRevisionVisibleTo`, which remains the
196
+ // only thing deciding what a subscriber is actually told.
197
+ .where((eb) => eb.or([eb("workspace_id", "is", null), eb("workspace_id", "=", required.workspaceId)]))
198
+ .orderBy("seq")
199
+ .limit(required.limit)
200
+ .execute());
201
+ return rows.map(toRevisionRecord);
202
+ }
203
+ async maxRevisionSeq() {
204
+ // `seq` is the auto-assigned primary key, so this is an index lookup rather than a scan.
205
+ const row = await this.kernel.run((db) => revisionsOf(db, this.tables).select("seq").orderBy("seq", "desc").limit(1).executeTakeFirst());
206
+ return row ? Number(row.seq) : 0;
207
+ }
208
+ /**
209
+ * Runs `fn` inside one kernel transaction. A call nested in the same async context joins the
210
+ * outer one; an unrelated caller (another request) waits its turn instead of landing inside it —
211
+ * the kernel tracks this per async context, so two independent root calls never merge (the defect
212
+ * an instance-level depth counter once had). A caller that needs several writes to commit together
213
+ * opens ONE transaction around them — see `resetNamespace`.
214
+ */
215
+ async transaction(fn) {
216
+ return this.kernel.transaction(fn);
217
+ }
218
+ }
219
+ //# sourceMappingURL=repo.sql.js.map
@@ -1,4 +1,4 @@
1
- import type { SqliteClient, SqliteStatement } from "./types.js";
1
+ import type { SqliteClient, SqliteStatement } from "@jini-ai/core/contracts/storage";
2
2
  export interface IntegerStatement extends SqliteStatement {
3
3
  safeIntegers(enabled: boolean): unknown;
4
4
  }
@@ -1,6 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import type { SqliteClient } from "./types.js";
3
- import type { StorageKernel } from "../kernel/port.js";
2
+ import type { SqliteClient } from "@jini-ai/core/contracts/storage";
3
+ import type { KyselyKernel } from "../kernel/port.js";
4
4
  export interface SqliteLease {
5
5
  active: boolean;
6
6
  acquired: boolean;
@@ -15,7 +15,7 @@ export declare const checkedStates: WeakMap<SqliteClient, CheckedState>;
15
15
  export declare const checkedClients: WeakSet<SqliteClient>;
16
16
  export declare const rawKernelClients: WeakSet<SqliteClient>;
17
17
  /** The reverse of the driver's kernel cache, plus the owning kernels openSqliteFileKernel returns. */
18
- export declare const connectionsByKernel: WeakMap<StorageKernel<unknown>, SqliteClient>;
18
+ export declare const connectionsByKernel: WeakMap<KyselyKernel<unknown>, SqliteClient>;
19
19
  /** A typed failure from the opt-in checked client; the native failure remains its cause. */
20
20
  export declare class SqliteClientError extends Error {
21
21
  readonly code: "unsafe_integer" | "commit_failed" | "rollback_failed" | "quarantined" | "session_expired" | "transaction_busy";
@@ -1,5 +1,5 @@
1
1
  import type { DbOpsPort, RestoreCapability, RestorePoint, WatermarkReader } from '../core/ports.js';
2
- import type { SqliteBackupSource } from './restore-types.js';
2
+ import type { SqliteBackupSource } from '@jini-ai/core/contracts/storage';
3
3
  export interface SqliteDbOpsAdapterDeps {
4
4
  /**
5
5
  * The raw driver handle, not an ORM wrapper. This adapter needs `backup` and nothing else, so a
@@ -7,7 +7,7 @@
7
7
  * unconditionally, and why a networked driver implementing the same port would not.
8
8
  *
9
9
  * The watermark is injected (`readWatermark`) rather than read from a table this package would
10
- * have to know the name of — see `WatermarkReader` in `db/core/ports.ts`.
10
+ * have to know the name of — see `WatermarkReader` in `packages/db/src/core/ports.ts`.
11
11
  */
12
12
  import { randomBytes } from 'node:crypto';
13
13
  import fs from 'node:fs/promises';
@@ -1,13 +1,11 @@
1
1
  /** SQLite connection policy and restore operations; inject the consumer's opener. */
2
- export type { SqliteClient, SqliteOpener, SqliteOpenOptions, SqliteStatement } from "./types.js";
3
2
  export { createCheckedSqliteClient, type CheckedSqliteClient, type IntegerSource, type IntegerStatement } from "./checked-client.js";
4
3
  export { SqliteClientError } from "./checked-state.js";
5
4
  export { withSqliteTransaction, type TransactionSession, type Work } from "./transaction.js";
6
5
  export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
7
6
  export { SqliteDbOpsAdapter, type SqliteDbOpsAdapterDeps } from "./db-ops.js";
8
7
  export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies, type DatabaseCopy } from "./backup-policy.js";
9
- export type { SqliteBackupSource, SqliteRecoveryHook, OpenSqliteConnectionOptions } from "./restore-types.js";
10
- export type { SqliteSyncClient, SqliteSyncStatement, SqliteSyncTransaction, SqliteSyncOpener, SqliteDb } from "./sync-types.js";
11
8
  export { inspectSqliteDatabase, verifySqliteIntegrity } from "./inspect.js";
9
+ export { assertSqliteStopped, checkpointStoppedSqliteWal, inspectStoppedSqlite, type StoppedSqliteOpener } from "./stopped.js";
12
10
  export type { DaemonDbTableInfo, DaemonDbStatusReport, DbIntegrityIssueKind, DbIntegrityIssue, DbIntegrityReport, VerifyDbOptions } from "./inspect.js";
13
11
  //# sourceMappingURL=index.d.ts.map
@@ -1,3 +1,4 @@
1
+ /** SQLite connection policy and restore operations; inject the consumer's opener. */
1
2
  export { createCheckedSqliteClient } from "./checked-client.js";
2
3
  export { SqliteClientError } from "./checked-state.js";
3
4
  export { withSqliteTransaction } from "./transaction.js";
@@ -5,4 +6,5 @@ export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
5
6
  export { SqliteDbOpsAdapter } from "./db-ops.js";
6
7
  export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies } from "./backup-policy.js";
7
8
  export { inspectSqliteDatabase, verifySqliteIntegrity } from "./inspect.js";
9
+ export { assertSqliteStopped, checkpointStoppedSqliteWal, inspectStoppedSqlite } from "./stopped.js";
8
10
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import type { SqliteDb } from './sync-types.js';
1
+ import type { SqliteDb } from '@jini-ai/core/contracts/storage';
2
2
  export interface DaemonDbTableInfo {
3
3
  name: string;
4
4
  rowCount: number;
@@ -28,7 +28,7 @@ export interface DaemonDbStatusReport {
28
28
  export declare function inspectSqliteDatabase(input: {
29
29
  db: SqliteDb;
30
30
  file: string;
31
- }): Promise<DaemonDbStatusReport>;
31
+ }, _optional?: Record<string, never>): Promise<DaemonDbStatusReport>;
32
32
  export type DbIntegrityIssueKind = 'integrity' | 'foreign_key';
33
33
  export interface DbIntegrityIssue {
34
34
  kind: DbIntegrityIssueKind;
@@ -25,7 +25,7 @@ function isSystemTable(name) {
25
25
  * @returns The status report. Never throws — schema-read and per-table failures
26
26
  * degrade to `null`/`0`/an empty list rather than failing the whole report.
27
27
  */
28
- export async function inspectSqliteDatabase(input) {
28
+ export async function inspectSqliteDatabase(input, _optional = {}) {
29
29
  const { db, file } = input;
30
30
  // 1. Schema version (user_version pragma).
31
31
  let schemaVersion = null;
@@ -22,8 +22,7 @@
22
22
  * (`drizzle(conn, { schema })`) and runs its own migrator; migrations are product schema, and this
23
23
  * package has no business knowing a host's tables.
24
24
  */
25
- import type { SqliteClient } from './types.js';
26
- import type { OpenSqliteConnectionOptions } from './restore-types.js';
25
+ import type { SqliteClient, OpenSqliteConnectionOptions } from '@jini-ai/core/contracts/storage';
27
26
  /**
28
27
  * Applied when a caller passes no `pragmas`.
29
28
  *
@@ -0,0 +1,46 @@
1
+ import { verifySqliteIntegrity } from './inspect.js';
2
+ import type { SqliteDb } from '@jini-ai/core/contracts/storage';
3
+ /** The host's native opener: `(file, options) => new Database(file, options)`. */
4
+ export type StoppedSqliteOpener = (file: string, options: {
5
+ readonly?: boolean;
6
+ fileMustExist?: boolean;
7
+ timeout?: number;
8
+ }) => SqliteDb;
9
+ /** Fold an unclean stop's committed WAL frames into the main file; never read rows.
10
+ * The caller must hold SQLite's exclusive lock on this connection until it closes, so a
11
+ * leftover journal belongs to the stopped database rather than a concurrent writer.
12
+ * @param input - The locked connection and its database file path.
13
+ * @returns Nothing once an absent or fully truncated WAL is safe for relocation.
14
+ * @throws The mover's checkpoint error if SQLite reports busy or the WAL remains non-empty;
15
+ * native SQLite/filesystem errors propagate to the caller's existing admission handling.
16
+ * @example checkpointStoppedSqliteWal({ db, path: file });
17
+ * @complexity O(1) file probes plus checkpointing the leftover WAL; no rows are read.
18
+ */
19
+ export declare function checkpointStoppedSqliteWal({ db, path: file }: {
20
+ db: Pick<SqliteDb, 'pragma'>;
21
+ path: string;
22
+ }, _options?: {}): void;
23
+ /** Released hosts have no lease. SQLite's exclusive lock is the admission proof. Never copy a live SQLite inode.
24
+ * A WAL/SHM that survives while this probe holds that lock was left by an unclean stop (no process has the DB):
25
+ * its committed frames are checkpointed into the main file, exactly as the site's next open would, and the
26
+ * stale SHM is removed under the lock; close deletes the emptied WAL. Any journal still present afterwards refuses.
27
+ * @complexity O(1) probes per DB, plus one checkpoint of a leftover WAL; no rows are read.
28
+ */
29
+ export declare function assertSqliteStopped({ path: file, open }: {
30
+ path: string;
31
+ open: StoppedSqliteOpener;
32
+ }, _options?: {}): void;
33
+ /** Read-only verification of every user table plus SQLite's full integrity check through Jini's
34
+ * existing SQLite inspector. It now supports strict counts; its diagnostics mode still reports
35
+ * partial results. No process is signalled: a recycled PID is not permission to stop another app.
36
+ * Row counts include tables with unusual quoted names and distinguish identical totals per table.
37
+ * @param options.verifyIntegrity - Integrity/row-count inspector; defaults to `verifySqliteIntegrity`.
38
+ * @complexity O(database pages + all table rows), one stopped connection per verification.
39
+ */
40
+ export declare function inspectStoppedSqlite({ path: file, open }: {
41
+ path: string;
42
+ open: StoppedSqliteOpener;
43
+ }, { verifyIntegrity }?: {
44
+ verifyIntegrity?: typeof verifySqliteIntegrity;
45
+ }): string;
46
+ //# sourceMappingURL=stopped.d.ts.map
@@ -0,0 +1,86 @@
1
+ /**
2
+ * @module stopped
3
+ *
4
+ * Native stopped-database admission and verification. SQLite's exclusive lock is the admission
5
+ * proof; nothing is copied while any process still holds the database. The host passes its own
6
+ * opener (its copy of better-sqlite3), so this module never loads a driver.
7
+ */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { verifySqliteIntegrity } from './inspect.js';
11
+ /** Fold an unclean stop's committed WAL frames into the main file; never read rows.
12
+ * The caller must hold SQLite's exclusive lock on this connection until it closes, so a
13
+ * leftover journal belongs to the stopped database rather than a concurrent writer.
14
+ * @param input - The locked connection and its database file path.
15
+ * @returns Nothing once an absent or fully truncated WAL is safe for relocation.
16
+ * @throws The mover's checkpoint error if SQLite reports busy or the WAL remains non-empty;
17
+ * native SQLite/filesystem errors propagate to the caller's existing admission handling.
18
+ * @example checkpointStoppedSqliteWal({ db, path: file });
19
+ * @complexity O(1) file probes plus checkpointing the leftover WAL; no rows are read.
20
+ */
21
+ export function checkpointStoppedSqliteWal({ db, path: file }, _options = {}) {
22
+ if (fs.existsSync(file + "-wal")) {
23
+ const [result] = db.pragma("wal_checkpoint(TRUNCATE)");
24
+ if (result?.busy || fs.statSync(file + "-wal").size !== 0)
25
+ throw new Error(`Database journal could not be checkpointed: ${file}-wal. Open and stop the site, then retry.`);
26
+ }
27
+ }
28
+ /** Released hosts have no lease. SQLite's exclusive lock is the admission proof. Never copy a live SQLite inode.
29
+ * A WAL/SHM that survives while this probe holds that lock was left by an unclean stop (no process has the DB):
30
+ * its committed frames are checkpointed into the main file, exactly as the site's next open would, and the
31
+ * stale SHM is removed under the lock; close deletes the emptied WAL. Any journal still present afterwards refuses.
32
+ * @complexity O(1) probes per DB, plus one checkpoint of a leftover WAL; no rows are read.
33
+ */
34
+ export function assertSqliteStopped({ path: file, open }, _options = {}) {
35
+ const db = open(file, { fileMustExist: true, timeout: 0 });
36
+ try {
37
+ // EXCLUSIVE locking mode keeps the lock until close and uses a heap wal-index, never the stale SHM.
38
+ db.exec("PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; ROLLBACK;");
39
+ checkpointStoppedSqliteWal({ db, path: file });
40
+ fs.rmSync(file + "-shm", { force: true });
41
+ }
42
+ catch (error) {
43
+ if (error.code?.startsWith("SQLITE_BUSY"))
44
+ throw new Error(`Database is open in another process: ${file}. Stop it before moving it.`);
45
+ throw error;
46
+ }
47
+ finally {
48
+ db.close();
49
+ }
50
+ for (const suffix of ["-wal", "-shm"]) {
51
+ if (fs.existsSync(file + suffix))
52
+ throw new Error(`Database journal exists: ${file + suffix}. Stop the site and close/checkpoint its database before moving it.`);
53
+ }
54
+ }
55
+ /** Read-only verification of every user table plus SQLite's full integrity check through Jini's
56
+ * existing SQLite inspector. It now supports strict counts; its diagnostics mode still reports
57
+ * partial results. No process is signalled: a recycled PID is not permission to stop another app.
58
+ * Row counts include tables with unusual quoted names and distinguish identical totals per table.
59
+ * @param options.verifyIntegrity - Integrity/row-count inspector; defaults to `verifySqliteIntegrity`.
60
+ * @complexity O(database pages + all table rows), one stopped connection per verification.
61
+ */
62
+ export function inspectStoppedSqlite({ path: file, open }, { verifyIntegrity = verifySqliteIntegrity } = {}) {
63
+ // SQLite can create WAL/SHM even for a readonly connection. Remember exactly what existed;
64
+ // only this inspection's artifacts may be removed, never a pre-existing journal.
65
+ const absentSidecars = ["-wal", "-shm"].map((suffix) => file + suffix).filter((sidecar) => !fs.existsSync(sidecar));
66
+ let db;
67
+ try {
68
+ db = open(file, { readonly: true, fileMustExist: true });
69
+ const checked = verifyIntegrity({ db }, { includeRowCounts: true });
70
+ if (!checked.ok)
71
+ throw new Error(`SQLite integrity_check failed for ${path.basename(file)}: ${checked.issues.map((issue) => issue.message).join('; ')}`);
72
+ if (!checked.rowCounts)
73
+ throw new Error("Build @jini-ai/db before running the stopped-site database mover.");
74
+ return JSON.stringify(checked.rowCounts);
75
+ }
76
+ finally {
77
+ try {
78
+ db?.close();
79
+ }
80
+ finally {
81
+ for (const sidecar of absentSidecars)
82
+ fs.rmSync(sidecar, { force: true });
83
+ }
84
+ }
85
+ }
86
+ //# sourceMappingURL=stopped.js.map
@@ -1,4 +1,4 @@
1
- import type { RawBuilder, StorageKernel } from "../kernel/port.js";
1
+ import type { KyselyKernel, RawBuilder } from "../kernel/port.js";
2
2
  import type { CheckedSqliteClient } from "./checked-client.js";
3
3
  export type Work<T> = (input: {
4
4
  session: TransactionSession;
@@ -21,7 +21,7 @@ export interface TransactionSession {
21
21
  */
22
22
  export declare function withSqliteTransaction<T>(required: {
23
23
  client: CheckedSqliteClient;
24
- kernel: StorageKernel<unknown>;
24
+ kernel: KyselyKernel<unknown>;
25
25
  work: Work<T>;
26
26
  }, optional?: {
27
27
  rollbackOnFailedOutcome?: boolean;
@@ -14,7 +14,7 @@
14
14
  * `inputSchema` — this file previously declared id/sideEffects/authorization only, one layer short
15
15
  * of what `tool-registrations.ts` requires to actually publish a tool to the model (mirrors
16
16
  * core's `AgentToolDefinition` shape; `inputSchema` stays OPTIONAL, as in
17
- * `features/content-types/agent-tools.ts`, because 1 of these 9 entries is still declared but
17
+ * `packages/cms/src/content-types/agent-tools.ts`, because 1 of these 9 entries is still declared but
18
18
  * deliberately never wired — see `tool-registrations.ts`'s `UNWIRED_DATABASE_TOOL_IDS`:
19
19
  * `database_get_restore_guidance` has no envelope-minting function to compose (only the RECEIVING
20
20
  * side, `recovery/deep-link.ts`'s `resolveDeepLinkContext`, exists — building one would mean
@@ -23,7 +23,7 @@
23
23
  * read-only introspection adapter below).
24
24
  *
25
25
  * A later dispatch built `features/database/adapter.sqlite.ts` (`DatabaseIntrospectionPort`,
26
- * composed into `RouteDeps` as `databaseIntrospection` in both `server/deps.ts` and `server/app.ts`)
26
+ * composed into `RouteDeps` as `databaseIntrospection` in both a host module and a host module)
27
27
  * and wired `database_get_health`/`database_get_schema_state`/`content_read.database_pending_migration`
28
28
  * against it — see each entry's own comment below and `tool-registrations.ts`'s handlers.
29
29
  *
@@ -14,7 +14,7 @@
14
14
  * `inputSchema` — this file previously declared id/sideEffects/authorization only, one layer short
15
15
  * of what `tool-registrations.ts` requires to actually publish a tool to the model (mirrors
16
16
  * core's `AgentToolDefinition` shape; `inputSchema` stays OPTIONAL, as in
17
- * `features/content-types/agent-tools.ts`, because 1 of these 9 entries is still declared but
17
+ * `packages/cms/src/content-types/agent-tools.ts`, because 1 of these 9 entries is still declared but
18
18
  * deliberately never wired — see `tool-registrations.ts`'s `UNWIRED_DATABASE_TOOL_IDS`:
19
19
  * `database_get_restore_guidance` has no envelope-minting function to compose (only the RECEIVING
20
20
  * side, `recovery/deep-link.ts`'s `resolveDeepLinkContext`, exists — building one would mean
@@ -23,7 +23,7 @@
23
23
  * read-only introspection adapter below).
24
24
  *
25
25
  * A later dispatch built `features/database/adapter.sqlite.ts` (`DatabaseIntrospectionPort`,
26
- * composed into `RouteDeps` as `databaseIntrospection` in both `server/deps.ts` and `server/app.ts`)
26
+ * composed into `RouteDeps` as `databaseIntrospection` in both a host module and a host module)
27
27
  * and wired `database_get_health`/`database_get_schema_state`/`content_read.database_pending_migration`
28
28
  * against it — see each entry's own comment below and `tool-registrations.ts`'s handlers.
29
29
  *
@@ -54,7 +54,7 @@ const NO_INPUT_SCHEMA = {
54
54
  required: [],
55
55
  properties: {},
56
56
  };
57
- /** `database_query_timeline`'s filter — mirrors `features/database/timeline.ts`'s `getTimeline` filter shape and `routes/admin/database/timeline.ts`'s query-string parsing 1:1. */
57
+ /** `database_query_timeline`'s filter — mirrors `features/database/timeline.ts`'s `getTimeline` filter shape and a host module's query-string parsing 1:1. */
58
58
  const TIMELINE_QUERY_SCHEMA = {
59
59
  type: "object",
60
60
  additionalProperties: false,
@@ -96,6 +96,12 @@ export function getDatabaseAgentToolCatalog(_required = {}, _optional = {}) {
96
96
  },
97
97
  },
98
98
  };
99
+ return [
100
+ ...createDatabaseReadCatalog(messages),
101
+ ...createDatabaseWorkflowCatalog(messages, CREATE_RESTORE_POINT_SCHEMA),
102
+ ];
103
+ }
104
+ function createDatabaseReadCatalog(messages) {
99
105
  return [
100
106
  {
101
107
  // WIRED (tool-registrations.ts) against `adapter.sqlite.ts`'s `DatabaseIntrospectionPort.getHealth()`
@@ -140,6 +146,10 @@ export function getDatabaseAgentToolCatalog(_required = {}, _optional = {}) {
140
146
  authorization: { permission: DATABASE_READ_PERMISSION },
141
147
  inputSchema: TIMELINE_QUERY_SCHEMA,
142
148
  },
149
+ ];
150
+ }
151
+ function createDatabaseWorkflowCatalog(messages, CREATE_RESTORE_POINT_SCHEMA) {
152
+ return [
143
153
  {
144
154
  name: "database_list_restore_points",
145
155
  description: messages.databaseRestorePoints,