@hraness/oh 0.2.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 (126) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +598 -0
  3. package/dist/canonical.d.ts +32 -0
  4. package/dist/canonical.d.ts.map +1 -0
  5. package/dist/cli.d.ts +4 -0
  6. package/dist/cli.d.ts.map +1 -0
  7. package/dist/cli.js +3419 -0
  8. package/dist/contract.d.ts +33 -0
  9. package/dist/contract.d.ts.map +1 -0
  10. package/dist/graph.d.ts +67 -0
  11. package/dist/graph.d.ts.map +1 -0
  12. package/dist/index.d.ts +9 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +1988 -0
  15. package/dist/libsql.d.ts +57 -0
  16. package/dist/libsql.d.ts.map +1 -0
  17. package/dist/libsql.js +2662 -0
  18. package/dist/memory.d.ts +366 -0
  19. package/dist/memory.d.ts.map +1 -0
  20. package/dist/memory.js +3650 -0
  21. package/dist/ontology.d.ts +242 -0
  22. package/dist/ontology.d.ts.map +1 -0
  23. package/dist/operation.d.ts +24 -0
  24. package/dist/operation.d.ts.map +1 -0
  25. package/dist/projection-public.d.ts +59 -0
  26. package/dist/projection-public.d.ts.map +1 -0
  27. package/dist/projection-public.js +1682 -0
  28. package/dist/projection-suss.d.ts +17 -0
  29. package/dist/projection-suss.d.ts.map +1 -0
  30. package/dist/projection-suss.js +1721 -0
  31. package/dist/projection.d.ts +315 -0
  32. package/dist/projection.d.ts.map +1 -0
  33. package/dist/schema.d.ts +45 -0
  34. package/dist/schema.d.ts.map +1 -0
  35. package/dist/sdk.d.ts +51 -0
  36. package/dist/sdk.d.ts.map +1 -0
  37. package/dist/sdk.js +3072 -0
  38. package/dist/search.d.ts +34 -0
  39. package/dist/search.d.ts.map +1 -0
  40. package/dist/semantic.d.ts +83 -0
  41. package/dist/semantic.d.ts.map +1 -0
  42. package/dist/semantic.js +706 -0
  43. package/dist/sqlite/driver.d.ts +6 -0
  44. package/dist/sqlite/driver.d.ts.map +1 -0
  45. package/dist/sqlite/index.d.ts +5 -0
  46. package/dist/sqlite/index.d.ts.map +1 -0
  47. package/dist/sqlite/index.js +2840 -0
  48. package/dist/sqlite/migrations.d.ts +10 -0
  49. package/dist/sqlite/migrations.d.ts.map +1 -0
  50. package/dist/sqlite/port.d.ts +40 -0
  51. package/dist/sqlite/port.d.ts.map +1 -0
  52. package/dist/sqlite/runtime.d.ts +23 -0
  53. package/dist/sqlite/runtime.d.ts.map +1 -0
  54. package/dist/sqlite/store.d.ts +85 -0
  55. package/dist/sqlite/store.d.ts.map +1 -0
  56. package/dist/store.d.ts +236 -0
  57. package/dist/store.d.ts.map +1 -0
  58. package/dist/store.js +996 -0
  59. package/dist/sync.d.ts +57 -0
  60. package/dist/sync.d.ts.map +1 -0
  61. package/dist/sync.js +1328 -0
  62. package/package.json +121 -0
  63. package/skills/oh/SKILL.md +206 -0
  64. package/skills/oh/agents/openai.yaml +4 -0
  65. package/spec/README.md +74 -0
  66. package/spec/manifest.json +41 -0
  67. package/spec/v1/canonical-json.md +59 -0
  68. package/spec/v1/contract.json +28 -0
  69. package/spec/v1/contract.schema.json +58 -0
  70. package/spec/v1/embedding-profile.json +11 -0
  71. package/spec/v1/embedding.md +56 -0
  72. package/spec/v1/graph.md +87 -0
  73. package/spec/v1/memory.md +193 -0
  74. package/spec/v1/migration.md +92 -0
  75. package/spec/v1/ontology.json +55 -0
  76. package/spec/v1/ontology.md +80 -0
  77. package/spec/v1/operation.schema.json +138 -0
  78. package/spec/v1/projection-identity.schema.json +58 -0
  79. package/spec/v1/projection-query.schema.json +60 -0
  80. package/spec/v1/projection-result.schema.json +452 -0
  81. package/spec/v1/projection-rule-pack.schema.json +182 -0
  82. package/spec/v1/projection.md +165 -0
  83. package/spec/v1/record.schema.json +95 -0
  84. package/spec/v1/schema-evolution.md +51 -0
  85. package/spec/v1/schema-revision.schema.json +178 -0
  86. package/spec/v1/storage.md +88 -0
  87. package/spec/v1/store.md +131 -0
  88. package/spec/v1/sync-bundle.schema.json +51 -0
  89. package/spec/v1/sync.md +67 -0
  90. package/src/canonical.test.ts +46 -0
  91. package/src/canonical.ts +203 -0
  92. package/src/cli.test.ts +103 -0
  93. package/src/cli.ts +308 -0
  94. package/src/contract.ts +87 -0
  95. package/src/contracts.test.ts +147 -0
  96. package/src/graph.ts +248 -0
  97. package/src/index.ts +8 -0
  98. package/src/libsql.test.ts +657 -0
  99. package/src/libsql.ts +1687 -0
  100. package/src/memory.test.ts +783 -0
  101. package/src/memory.ts +1684 -0
  102. package/src/ontology.ts +573 -0
  103. package/src/operation.ts +80 -0
  104. package/src/projection-public.ts +53 -0
  105. package/src/projection-suss.ts +129 -0
  106. package/src/projection.test.ts +418 -0
  107. package/src/projection.ts +1457 -0
  108. package/src/schema.ts +156 -0
  109. package/src/sdk.ts +96 -0
  110. package/src/search.ts +66 -0
  111. package/src/semantic.test.ts +480 -0
  112. package/src/semantic.ts +333 -0
  113. package/src/sqlite/driver.ts +47 -0
  114. package/src/sqlite/index.ts +4 -0
  115. package/src/sqlite/migrations.test.ts +44 -0
  116. package/src/sqlite/migrations.ts +178 -0
  117. package/src/sqlite/port.test.ts +127 -0
  118. package/src/sqlite/port.ts +120 -0
  119. package/src/sqlite/runtime.test.ts +68 -0
  120. package/src/sqlite/runtime.ts +53 -0
  121. package/src/sqlite/store.test.ts +295 -0
  122. package/src/sqlite/store.ts +988 -0
  123. package/src/store.test.ts +121 -0
  124. package/src/store.ts +701 -0
  125. package/src/sync.test.ts +117 -0
  126. package/src/sync.ts +227 -0
@@ -0,0 +1,657 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { Database, type SQLQueryBindings } from "bun:sqlite";
3
+
4
+ import { canonicalJson } from "./canonical";
5
+ import { createKnowledgeGraphRecordV1 } from "./graph";
6
+ import {
7
+ bootstrapOhLibSqlAuthorityV1,
8
+ createOhLibSqlStoreAuthorityV1,
9
+ OH_LIBSQL_STORE_LIMITS_V1,
10
+ openExistingOhLibSqlStoreAuthorityV1,
11
+ purgeOhLibSqlWorkingSpaceV1,
12
+ type OhLibSqlClientV1,
13
+ type OhLibSqlResultV1,
14
+ type OhLibSqlStatementV1,
15
+ } from "./libsql";
16
+ import {
17
+ OH_CANONICAL_STORE_PROFILE_V1,
18
+ OH_WORKING_STORE_PROFILE_V1,
19
+ OhConflictError,
20
+ OhIntegrityError,
21
+ OhProfileError,
22
+ OhPurgedSpaceError,
23
+ } from "./store";
24
+
25
+ class SqliteCompatibleLibSqlClient implements OhLibSqlClientV1 {
26
+ readonly database = new Database(":memory:", { strict: true });
27
+ lastBatchResponseBytes = 0;
28
+
29
+ #execute(statement: OhLibSqlStatementV1 | string): OhLibSqlResultV1 {
30
+ const sql = typeof statement === "string" ? statement : statement.sql;
31
+ const args = typeof statement === "string" ? [] : statement.args ?? [];
32
+ const bindings: SQLQueryBindings[] = args.map((value) => value instanceof Date
33
+ ? value.toISOString() : value instanceof ArrayBuffer ? new Uint8Array(value) : value);
34
+ if (/^\s*(?:SELECT|PRAGMA)\b/iu.test(sql)) {
35
+ return { rows: this.database.query<Record<string, unknown>, SQLQueryBindings[]>(sql).all(...bindings) };
36
+ }
37
+ const result = this.database.query<never, SQLQueryBindings[]>(sql).run(...bindings);
38
+ return { rows: [], rowsAffected: result.changes };
39
+ }
40
+
41
+ async execute(statement: OhLibSqlStatementV1 | string): Promise<OhLibSqlResultV1> {
42
+ return this.#execute(statement);
43
+ }
44
+
45
+ async batch(
46
+ statements: readonly OhLibSqlStatementV1[],
47
+ _mode?: "deferred" | "read" | "write",
48
+ ): Promise<readonly OhLibSqlResultV1[]> {
49
+ const results = this.database.transaction((items: readonly OhLibSqlStatementV1[]) =>
50
+ items.map((statement) => this.#execute(statement)))(statements);
51
+ this.lastBatchResponseBytes = Buffer.byteLength(JSON.stringify(results), "utf8");
52
+ return results;
53
+ }
54
+
55
+ close(): void { this.database.close(); }
56
+ }
57
+
58
+ const entity = (key: string, name: string, dependencies: readonly string[] = []) =>
59
+ createKnowledgeGraphRecordV1({ dependencies, key, kind: "entity", v: 1, value: { name } });
60
+
61
+ async function bootstrappedClient(): Promise<SqliteCompatibleLibSqlClient> {
62
+ const client = new SqliteCompatibleLibSqlClient();
63
+ expect(await bootstrapOhLibSqlAuthorityV1(client)).toMatchObject({ schemaVersion: 1, v: 1 });
64
+ return client;
65
+ }
66
+
67
+ describe("direct libSQL Oh authority", () => {
68
+ test("refuses to bless preexisting or drifted authority schema objects", async () => {
69
+ const malformed = new SqliteCompatibleLibSqlClient();
70
+ malformed.database.exec("CREATE TABLE oh_authority_commit_guards(value TEXT)");
71
+ await expect(bootstrapOhLibSqlAuthorityV1(malformed)).rejects.toThrow(OhIntegrityError);
72
+ malformed.close();
73
+
74
+ const drifted = await bootstrappedClient();
75
+ drifted.database.exec(`CREATE TRIGGER unexpected_authority_trigger
76
+ BEFORE INSERT ON oh_authority_records BEGIN SELECT 1; END`);
77
+ await expect(createOhLibSqlStoreAuthorityV1(drifted, {
78
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:drift", spaceId: "drift",
79
+ })).rejects.toThrow(OhIntegrityError);
80
+ drifted.close();
81
+ });
82
+
83
+ test("does not bootstrap schema as a side effect of the runtime open", async () => {
84
+ const client = new SqliteCompatibleLibSqlClient();
85
+ await expect(createOhLibSqlStoreAuthorityV1(client, {
86
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:missing", spaceId: "missing",
87
+ })).rejects.toThrow();
88
+ expect(client.database.query<{ count: number }, []>(`SELECT count(*) AS count FROM sqlite_schema
89
+ WHERE name LIKE 'oh_authority_%'`).get()?.count).toBe(0);
90
+ client.close();
91
+ });
92
+
93
+ test("opens with a data-only runtime client after one explicit schema bootstrap", async () => {
94
+ const schemaClient = await bootstrappedClient();
95
+ const rejectDdl = (statement: OhLibSqlStatementV1 | string): void => {
96
+ const sql = typeof statement === "string" ? statement : statement.sql;
97
+ if (/^\s*(?:ALTER|CREATE|DROP|REINDEX|VACUUM)\b/iu.test(sql)) {
98
+ throw new Error("runtime credential cannot execute schema DDL");
99
+ }
100
+ };
101
+ const runtimeClient: OhLibSqlClientV1 = {
102
+ execute: async (statement) => {
103
+ rejectDdl(statement);
104
+ return await schemaClient.execute(statement);
105
+ },
106
+ batch: async (statements, mode) => {
107
+ statements.forEach(rejectDdl);
108
+ return await schemaClient.batch(statements, mode);
109
+ },
110
+ };
111
+ const authority = await createOhLibSqlStoreAuthorityV1(runtimeClient, {
112
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:data-only", spaceId: "data-only",
113
+ });
114
+ expect((await authority.store.head()).sequence).toBe(0);
115
+ await authority.store.close();
116
+ schemaClient.close();
117
+ });
118
+
119
+ test("opens existing purge custody without acquiring space-creation authority", async () => {
120
+ const provider = await bootstrappedClient();
121
+ const created = await createOhLibSqlStoreAuthorityV1(provider, {
122
+ profile: OH_WORKING_STORE_PROFILE_V1,
123
+ realmId: "realm:existing-only",
124
+ spaceId: "existing-only",
125
+ });
126
+ await created.store.commit({
127
+ actorId: "host.existing-only",
128
+ changes: [{ kind: "put", record: entity("entity:private", "Private"), v: 1 }],
129
+ expectedHead: await created.store.head(),
130
+ operationId: "op_existing_only",
131
+ });
132
+ await created.store.close();
133
+
134
+ const observed: string[] = [];
135
+ const forbidCreation = (statement: OhLibSqlStatementV1 | string): void => {
136
+ const sql = typeof statement === "string" ? statement : statement.sql;
137
+ observed.push(sql);
138
+ if (/\bINSERT\s+INTO\s+oh_authority_(?:spaces|bindings)\b/iu.test(sql)) {
139
+ throw new Error("existing-only credential cannot create a space or binding");
140
+ }
141
+ };
142
+ const existingOnlyClient: OhLibSqlClientV1 = {
143
+ execute: async (statement) => {
144
+ forbidCreation(statement);
145
+ return await provider.execute(statement);
146
+ },
147
+ batch: async (statements, mode) => {
148
+ statements.forEach(forbidCreation);
149
+ return await provider.batch(statements, mode);
150
+ },
151
+ };
152
+
153
+ await expect(openExistingOhLibSqlStoreAuthorityV1(existingOnlyClient, {
154
+ profile: OH_WORKING_STORE_PROFILE_V1,
155
+ realmId: "realm:missing-existing-only",
156
+ spaceId: "missing-existing-only",
157
+ })).rejects.toThrow(OhIntegrityError);
158
+ await expect(openExistingOhLibSqlStoreAuthorityV1(existingOnlyClient, {
159
+ profile: OH_WORKING_STORE_PROFILE_V1,
160
+ realmId: "realm:different",
161
+ spaceId: "existing-only",
162
+ })).rejects.toThrow(OhProfileError);
163
+
164
+ observed.length = 0;
165
+ const authority = await openExistingOhLibSqlStoreAuthorityV1(existingOnlyClient, {
166
+ profile: OH_WORKING_STORE_PROFILE_V1,
167
+ realmId: "realm:existing-only",
168
+ spaceId: "existing-only",
169
+ });
170
+ expect((await authority.store.head()).sequence).toBe(1);
171
+ expect(observed.every((sql) => /^\s*SELECT\b/iu.test(sql))).toBe(true);
172
+ await authority.host.purgeWorkingSpace({ purgedAt: "2026-08-30T01:00:00.000Z" });
173
+ expect(observed.some((sql) => /\bINSERT\s+INTO\s+oh_authority_purges\b/iu.test(sql)))
174
+ .toBe(true);
175
+ expect(observed.some((sql) =>
176
+ /\bINSERT\s+INTO\s+oh_authority_(?:spaces|bindings)\b/iu.test(sql))).toBe(false);
177
+ await authority.store.close();
178
+ provider.close();
179
+ });
180
+
181
+ test("fences an authority that was abandoned before creation without creating it", async () => {
182
+ const provider = await bootstrappedClient();
183
+ const observed: string[] = [];
184
+ const purgeOnlyClient: OhLibSqlClientV1 = {
185
+ execute: async (statement) => {
186
+ const sql = typeof statement === "string" ? statement : statement.sql;
187
+ observed.push(sql);
188
+ if (/\bINSERT\s+INTO\s+oh_authority_(?:spaces|bindings)\b/iu.test(sql)) {
189
+ throw new Error("purge custody cannot create a space or binding");
190
+ }
191
+ return await provider.execute(statement);
192
+ },
193
+ batch: async (statements, mode) => {
194
+ for (const statement of statements) {
195
+ observed.push(statement.sql);
196
+ if (/\bINSERT\s+INTO\s+oh_authority_(?:spaces|bindings)\b/iu.test(statement.sql)) {
197
+ throw new Error("purge custody cannot create a space or binding");
198
+ }
199
+ }
200
+ return await provider.batch(statements, mode);
201
+ },
202
+ };
203
+ const options = {
204
+ profile: OH_WORKING_STORE_PROFILE_V1,
205
+ realmId: "realm:abandoned-before-create",
206
+ spaceId: "abandoned-before-create",
207
+ } as const;
208
+ const receipt = await purgeOhLibSqlWorkingSpaceV1(purgeOnlyClient, {
209
+ ...options,
210
+ purgedAt: "2026-08-30T02:30:00.000Z",
211
+ });
212
+ expect(receipt.priorHead.sequence).toBe(0);
213
+ expect(observed.some((sql) => /\bINSERT\s+INTO\s+oh_authority_purges\b/iu.test(sql))).toBe(true);
214
+ expect(observed.some((sql) => /\bINSERT\s+INTO\s+oh_authority_(?:spaces|bindings)\b/iu.test(sql)))
215
+ .toBe(false);
216
+ expect(await purgeOhLibSqlWorkingSpaceV1(purgeOnlyClient, {
217
+ ...options,
218
+ purgedAt: "2026-08-30T02:31:00.000Z",
219
+ })).toEqual(receipt);
220
+ await expect(createOhLibSqlStoreAuthorityV1(provider, options)).rejects.toMatchObject({
221
+ receipt,
222
+ });
223
+ provider.close();
224
+ });
225
+
226
+ test("arbitrates a concurrent late creator into a complete purge", async () => {
227
+ const provider = await bootstrappedClient();
228
+ const options = {
229
+ profile: OH_WORKING_STORE_PROFILE_V1,
230
+ realmId: "realm:late-creator",
231
+ spaceId: "late-creator",
232
+ } as const;
233
+ let raced = false;
234
+ const racingPurgeClient: OhLibSqlClientV1 = {
235
+ execute: async (statement) => await provider.execute(statement),
236
+ batch: async (statements, mode) => {
237
+ if (!raced && statements.some((statement) =>
238
+ /\bINSERT\s+INTO\s+oh_authority_purges\b/iu.test(statement.sql))) {
239
+ raced = true;
240
+ const created = await createOhLibSqlStoreAuthorityV1(provider, options);
241
+ await created.store.close();
242
+ }
243
+ return await provider.batch(statements, mode);
244
+ },
245
+ };
246
+ const receipt = await purgeOhLibSqlWorkingSpaceV1(racingPurgeClient, {
247
+ ...options,
248
+ purgedAt: "2026-08-30T02:32:00.000Z",
249
+ });
250
+ expect(raced).toBe(true);
251
+ expect(receipt.priorHead.sequence).toBe(0);
252
+ await expect(openExistingOhLibSqlStoreAuthorityV1(provider, options))
253
+ .rejects.toBeInstanceOf(OhPurgedSpaceError);
254
+ expect(provider.database.query<{ count: number }, [string]>(`SELECT count(*) AS count
255
+ FROM oh_authority_spaces WHERE space_id = ?`).get(options.spaceId)?.count).toBe(0);
256
+ provider.close();
257
+ });
258
+
259
+ test("recovers from a failed fence with one atomic concurrent-purge proof", async () => {
260
+ const provider = await bootstrappedClient();
261
+ const options = {
262
+ profile: OH_WORKING_STORE_PROFILE_V1,
263
+ realmId: "realm:concurrent-purge-recovery",
264
+ spaceId: "concurrent-purge-recovery",
265
+ } as const;
266
+ let writeFailed = false;
267
+ let concurrentReceipt: Awaited<ReturnType<typeof purgeOhLibSqlWorkingSpaceV1>> | null = null;
268
+ const racingPurgeClient: OhLibSqlClientV1 = {
269
+ execute: async (statement) => await provider.execute(statement),
270
+ batch: async (statements, mode) => {
271
+ if (mode === "write" && !writeFailed) {
272
+ writeFailed = true;
273
+ throw new Error("simulated concurrent guard failure");
274
+ }
275
+ if (mode === "read" && writeFailed && concurrentReceipt === null
276
+ && statements.some((statement) => /FROM oh_authority_bindings WHERE space_id = \?/u
277
+ .test(statement.sql))) {
278
+ concurrentReceipt = await purgeOhLibSqlWorkingSpaceV1(provider, {
279
+ ...options,
280
+ purgedAt: "2026-08-30T02:33:00.000Z",
281
+ });
282
+ }
283
+ return await provider.batch(statements, mode);
284
+ },
285
+ };
286
+ const receipt = await purgeOhLibSqlWorkingSpaceV1(racingPurgeClient, options);
287
+ expect(writeFailed).toBe(true);
288
+ if (concurrentReceipt === null) throw new Error("The concurrent purge did not run.");
289
+ expect(receipt).toEqual(concurrentReceipt);
290
+ provider.close();
291
+ });
292
+
293
+ test("rolls an absent-space fence back when orphaned payload prevents a complete purge", async () => {
294
+ const provider = await bootstrappedClient();
295
+ const spaceId = "corrupt-before-create";
296
+ provider.database.query(`INSERT INTO oh_authority_records(space_id, record_key, kind,
297
+ record_sha256, record_json, operation_sha256, sequence) VALUES (?, ?, ?, ?, ?, ?, ?)`)
298
+ .run(spaceId, "entity:orphan", "entity", "a".repeat(64), "{}", "b".repeat(64), 1);
299
+ await expect(purgeOhLibSqlWorkingSpaceV1(provider, {
300
+ profile: OH_WORKING_STORE_PROFILE_V1,
301
+ realmId: `realm:${spaceId}`,
302
+ spaceId,
303
+ })).rejects.toThrow();
304
+ expect(provider.database.query<{ count: number }, [string]>(`SELECT count(*) AS count
305
+ FROM oh_authority_purges WHERE space_id = ?`).get(spaceId)?.count).toBe(0);
306
+ expect(provider.database.query<{ count: number }, [string]>(`SELECT count(*) AS count
307
+ FROM oh_authority_records WHERE space_id = ?`).get(spaceId)?.count).toBe(1);
308
+ provider.close();
309
+ });
310
+
311
+ test("is an async authoritative store rather than an operation-sync cache", async () => {
312
+ const client = await bootstrappedClient();
313
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
314
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:remote", spaceId: "remote",
315
+ });
316
+ const parent = entity("entity:parent", "Parent");
317
+ const child = entity("entity:child", "Child", [parent.key]);
318
+ const first = await authority.store.commit({ actorId: "agent.remote", changes: [
319
+ { kind: "put", record: parent, v: 1 }, { kind: "put", record: child, v: 1 },
320
+ ], expectedHead: await authority.store.head(), instant: "2026-08-29T12:00:00.000Z",
321
+ operationId: "op_remote_one" });
322
+ await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
323
+ record: entity("entity:later", "Later"), v: 1 }], expectedHead: await authority.store.head(),
324
+ instant: "2026-08-29T12:01:00.000Z", operationId: "op_remote_two" });
325
+
326
+ expect((await authority.store.snapshot({ head: {
327
+ operationSha256: first.operationSha256, sequence: first.sequence } })).records)
328
+ .toEqual([child, parent].sort((left, right) => left.key.localeCompare(right.key)));
329
+ expect(await authority.store.snapshot({ head: { operationSha256: null, sequence: 0 } }))
330
+ .toMatchObject({ head: { operationSha256: null, sequence: 0 }, records: [] });
331
+ expect((await authority.store.exportDependencyClosure({ roots: [child.key] })).records)
332
+ .toEqual([child, parent].sort((left, right) => left.key.localeCompare(right.key)));
333
+ expect(await authority.store.verify()).toMatchObject({ integrity: "verified", operations: 2, records: 3 });
334
+
335
+ const reopened = await createOhLibSqlStoreAuthorityV1(client, {
336
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:remote", spaceId: "remote",
337
+ });
338
+ expect((await reopened.store.head()).operationSha256).toBe((await authority.store.head()).operationSha256);
339
+ await reopened.store.close();
340
+ await authority.store.close();
341
+ client.close();
342
+ });
343
+
344
+ test("uses compare-and-swap guards to leave no partial remote mutation", async () => {
345
+ const client = await bootstrappedClient();
346
+ const first = await createOhLibSqlStoreAuthorityV1(client, {
347
+ profile: OH_CANONICAL_STORE_PROFILE_V1, realmId: "realm:cas", spaceId: "cas",
348
+ });
349
+ const second = await createOhLibSqlStoreAuthorityV1(client, {
350
+ profile: OH_CANONICAL_STORE_PROFILE_V1, realmId: "realm:cas", spaceId: "cas",
351
+ });
352
+ const stale = await second.store.head();
353
+ await first.store.commit({ actorId: "agent.one", changes: [{ kind: "put",
354
+ record: entity("entity:first", "First"), v: 1 }], expectedHead: stale,
355
+ operationId: "op_first" });
356
+ await expect(second.store.commit({ actorId: "agent.two", changes: [{ kind: "put",
357
+ record: entity("entity:stale", "Stale"), v: 1 }], expectedHead: stale,
358
+ operationId: "op_stale" })).rejects.toThrow(OhConflictError);
359
+ expect((await first.store.snapshot()).records.map(({ key }) => key)).toEqual(["entity:first"]);
360
+ expect(client.database.query<{ count: number }, []>(`SELECT count(*) AS count
361
+ FROM oh_authority_operations WHERE operation_id = 'op_stale'`).get()?.count).toBe(0);
362
+ await first.store.close(); await second.store.close(); client.close();
363
+ });
364
+
365
+ test("rejects orphaned idempotency rows and duplicated binding-column drift", async () => {
366
+ const sourceClient = await bootstrappedClient();
367
+ const source = await createOhLibSqlStoreAuthorityV1(sourceClient, {
368
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:remote-orphan", spaceId: "remote-orphan",
369
+ });
370
+ const changes = [{ kind: "put" as const, record: entity("entity:orphan", "Orphan"), v: 1 as const }];
371
+ const operation = await source.store.commit({ actorId: "agent.remote", changes,
372
+ expectedHead: await source.store.head(), operationId: "op_remote_orphan" });
373
+
374
+ const targetClient = await bootstrappedClient();
375
+ const target = await createOhLibSqlStoreAuthorityV1(targetClient, {
376
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:remote-orphan", spaceId: "remote-orphan",
377
+ });
378
+ targetClient.database.query(`INSERT INTO oh_authority_operations(operation_sha256, space_id,
379
+ sequence, operation_id, parent_operation_sha256, graph_revision_sha256, records_sha256,
380
+ operation_json, instant) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
381
+ operation.operationSha256, operation.spaceId, operation.sequence, operation.operationId,
382
+ operation.parentOperationSha256, operation.graphRevisionSha256, operation.recordsSha256,
383
+ canonicalJson(operation), operation.instant,
384
+ );
385
+ await expect(target.store.commit({ actorId: operation.actorId, changes,
386
+ expectedHead: await target.store.head(), operationId: operation.operationId }))
387
+ .rejects.toThrow(OhIntegrityError);
388
+ expect((await target.store.head()).sequence).toBe(0);
389
+ targetClient.database.query("UPDATE oh_authority_bindings SET realm_id = ? WHERE space_id = ?")
390
+ .run("realm:alien", "remote-orphan");
391
+ await expect(createOhLibSqlStoreAuthorityV1(targetClient, {
392
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:remote-orphan", spaceId: "remote-orphan",
393
+ })).rejects.toThrow(OhIntegrityError);
394
+ await target.store.close(); await source.store.close(); targetClient.close(); sourceClient.close();
395
+ });
396
+
397
+ test("refuses snapshots and commits when the current head drifts from its operation", async () => {
398
+ const client = await bootstrappedClient();
399
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
400
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:head-drift", spaceId: "head-drift",
401
+ });
402
+ await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
403
+ record: entity("entity:one", "One"), v: 1 }], expectedHead: await authority.store.head(),
404
+ operationId: "op_head_one" });
405
+ client.database.query("UPDATE oh_authority_spaces SET graph_revision_sha256 = ? WHERE space_id = ?")
406
+ .run("f".repeat(64), "head-drift");
407
+ const drifted = await authority.store.head();
408
+ await expect(authority.store.snapshot()).rejects.toThrow(OhIntegrityError);
409
+ await expect(authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
410
+ record: entity("entity:two", "Two"), v: 1 }], expectedHead: drifted,
411
+ operationId: "op_head_two" })).rejects.toThrow(OhIntegrityError);
412
+ expect((await authority.store.head()).sequence).toBe(1);
413
+ await authority.store.close(); client.close();
414
+ });
415
+
416
+ test("detects record-column and operation-record tampering before advancing authority", async () => {
417
+ const client = await bootstrappedClient();
418
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
419
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:tamper", spaceId: "tamper",
420
+ });
421
+ const record = entity("entity:tamper", "Tamper");
422
+ await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put", record, v: 1 }],
423
+ expectedHead: await authority.store.head(), operationId: "op_tamper" });
424
+ const head = await authority.store.head();
425
+ client.database.query(`UPDATE oh_authority_records SET record_sha256 = ?
426
+ WHERE space_id = ? AND record_key = ?`).run("f".repeat(64), "tamper", record.key);
427
+ await expect(authority.store.verify()).rejects.toThrow(OhIntegrityError);
428
+ await expect(authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "tombstone",
429
+ key: record.key, priorSha256: record.recordSha256, v: 1 }], expectedHead: head,
430
+ operationId: "op_after_tamper" })).rejects.toThrow(OhIntegrityError);
431
+ expect((await authority.store.head()).sequence).toBe(1);
432
+ client.database.query(`UPDATE oh_authority_records SET record_sha256 = ?
433
+ WHERE space_id = ? AND record_key = ?`).run(record.recordSha256, "tamper", record.key);
434
+ expect(() => client.database.query("DELETE FROM oh_authority_operation_records WHERE space_id = ?")
435
+ .run("tamper")).toThrow("require a purge receipt");
436
+ client.database.exec("DROP TRIGGER oh_authority_operation_records_guard_delete");
437
+ client.database.query("DELETE FROM oh_authority_operation_records WHERE space_id = ?").run("tamper");
438
+ await expect(authority.store.verify()).rejects.toThrow(OhIntegrityError);
439
+ await authority.store.close(); client.close();
440
+ });
441
+
442
+ test("refuses to extend noncanonical current-record provenance", async () => {
443
+ const client = await bootstrappedClient();
444
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
445
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:provenance", spaceId: "provenance",
446
+ });
447
+ await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
448
+ record: entity("entity:first", "First"), v: 1 }], expectedHead: await authority.store.head(),
449
+ operationId: "op_provenance_one" });
450
+ await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
451
+ record: entity("entity:second", "Second"), v: 1 }], expectedHead: await authority.store.head(),
452
+ operationId: "op_provenance_two" });
453
+ const row = client.database.query<{ operation_json: string }, []>(`SELECT operation_json
454
+ FROM oh_authority_operations WHERE operation_id = 'op_provenance_one'`).get();
455
+ expect(row).not.toBeNull();
456
+ const noncanonical = JSON.stringify(JSON.parse(row?.operation_json ?? "null"), null, 2);
457
+ expect(() => client.database.query(`UPDATE oh_authority_operations SET operation_json = ?
458
+ WHERE operation_id = 'op_provenance_one'`).run(noncanonical)).toThrow("immutable");
459
+ client.database.exec("DROP TRIGGER oh_authority_operations_no_update");
460
+ client.database.query(`UPDATE oh_authority_operations SET operation_json = ?
461
+ WHERE operation_id = 'op_provenance_one'`).run(noncanonical);
462
+ const head = await authority.store.head();
463
+ await expect(authority.store.snapshot()).rejects.toThrow(OhIntegrityError);
464
+ await expect(authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
465
+ record: entity("entity:third", "Third"), v: 1 }], expectedHead: head,
466
+ operationId: "op_provenance_three" })).rejects.toThrow(OhIntegrityError);
467
+ expect((await authority.store.head()).sequence).toBe(2);
468
+ await authority.store.close(); client.close();
469
+ });
470
+
471
+ test("never reports a remote feed that omits its tail or hides a bad sentinel", async () => {
472
+ const client = await bootstrappedClient();
473
+ const populate = async (spaceId: string) => {
474
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
475
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: `realm:${spaceId}`, spaceId,
476
+ });
477
+ for (let index = 1; index <= 3; index += 1) {
478
+ await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
479
+ record: entity(`entity:${spaceId}-${index}`, `${spaceId} ${index}`), v: 1 }],
480
+ expectedHead: await authority.store.head(), operationId: `op_${spaceId}_${index}` });
481
+ }
482
+ return authority;
483
+ };
484
+ const tail = await populate("feed-tail");
485
+ const sentinel = await populate("feed-sentinel");
486
+ client.database.exec("DROP TRIGGER oh_authority_operations_guard_delete");
487
+ client.database.query("DELETE FROM oh_authority_operations WHERE space_id = ? AND sequence = 3")
488
+ .run("feed-tail");
489
+ await expect(tail.store.changesSince({ operationSha256: null, sequence: 0 }, { limit: 3 }))
490
+ .rejects.toThrow(OhIntegrityError);
491
+ client.database.query("DELETE FROM oh_authority_operations WHERE space_id = ? AND sequence = 2")
492
+ .run("feed-sentinel");
493
+ await expect(sentinel.store.changesSince({ operationSha256: null, sequence: 0 }, { limit: 1 }))
494
+ .rejects.toThrow(OhIntegrityError);
495
+ await tail.store.close(); await sentinel.store.close(); client.close();
496
+ });
497
+
498
+ test("enforces provider-safe operation, feed, and snapshot response bounds", async () => {
499
+ const client = await bootstrappedClient();
500
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
501
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:provider-bounds", spaceId: "provider-bounds",
502
+ });
503
+ await expect(authority.store.changesSince({ operationSha256: null, sequence: 0 }, { limit: 16 }))
504
+ .rejects.toThrow(RangeError);
505
+ const oversized = entity("entity:oversized", "x".repeat(600_000));
506
+ await expect(authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
507
+ record: oversized, v: 1 }], expectedHead: await authority.store.head(),
508
+ operationId: "op_oversized" })).rejects.toThrow("canonical byte bound");
509
+ expect((await authority.store.head()).sequence).toBe(0);
510
+
511
+ await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
512
+ record: entity("entity:bounded", "Bounded"), v: 1 }], expectedHead: await authority.store.head(),
513
+ operationId: "op_bounded" });
514
+ client.database.query(`UPDATE oh_authority_records
515
+ SET record_json = json_object('blob', hex(zeroblob(2200000))) WHERE space_id = ?`)
516
+ .run("provider-bounds");
517
+ await expect(authority.store.snapshot()).rejects.toThrow("provider-safe response bounds");
518
+ await authority.store.close(); client.close();
519
+ });
520
+
521
+ test("keeps escape-heavy feeds and accepted history below the libSQL response ceiling", async () => {
522
+ const client = await bootstrappedClient();
523
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
524
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:response-ceiling",
525
+ spaceId: "response-ceiling",
526
+ });
527
+ const escaped = "\\\"\n".repeat(50_000);
528
+ const heads = [];
529
+ for (let index = 1; index <= 14; index += 1) {
530
+ const operation = await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
531
+ record: entity("entity:response-ceiling", `${String(index).padStart(2, "0")}:${escaped}`), v: 1 }],
532
+ expectedHead: await authority.store.head(), operationId: `op_response_ceiling_${index}` });
533
+ heads.push({ operationSha256: operation.operationSha256, sequence: operation.sequence });
534
+ }
535
+ expect(OH_LIBSQL_STORE_LIMITS_V1.changeFeedLimit).toBe(7);
536
+ const page = await authority.store.changesSince({ operationSha256: null, sequence: 0 });
537
+ expect(page.operations).toHaveLength(7);
538
+ expect(page.hasMore).toBe(true);
539
+ expect(client.lastBatchResponseBytes).toBeLessThan(10_000_000);
540
+
541
+ const historical = await authority.store.snapshot({ head: heads[12]! });
542
+ expect(historical.head.sequence).toBe(13);
543
+ expect(client.lastBatchResponseBytes).toBeLessThan(10_000_000);
544
+ await authority.store.close(); client.close();
545
+ });
546
+
547
+ test("rejects profile drift and permanently purges a working realm with a receipt", async () => {
548
+ const client = await bootstrappedClient();
549
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
550
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:purge", spaceId: "purge",
551
+ });
552
+ await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
553
+ record: entity("entity:private", "Private"), v: 1 }], expectedHead: await authority.store.head(),
554
+ operationId: "op_private" });
555
+ await expect(createOhLibSqlStoreAuthorityV1(client, {
556
+ profile: OH_CANONICAL_STORE_PROFILE_V1, realmId: "realm:other", spaceId: "purge",
557
+ })).rejects.toThrow(OhProfileError);
558
+
559
+ const receipt = await authority.host.purgeWorkingSpace({ purgedAt: "2026-08-29T13:00:00.000Z" });
560
+ expect(receipt.priorHead.sequence).toBe(1);
561
+ expect("purgeWorkingSpace" in authority.store).toBe(false);
562
+ for (const table of ["oh_authority_spaces", "oh_authority_bindings", "oh_authority_operations",
563
+ "oh_authority_operation_records", "oh_authority_records", "oh_authority_dependencies"]) {
564
+ const count = client.database.query<{ count: number }, []>(`SELECT count(*) AS count FROM ${table}`).get()?.count;
565
+ expect(count, table).toBe(0);
566
+ }
567
+ expect(client.database.query<{ count: number }, []>(
568
+ "SELECT count(*) AS count FROM oh_authority_purges WHERE space_id = 'purge'",
569
+ ).get()?.count).toBe(1);
570
+ await expect(createOhLibSqlStoreAuthorityV1(client, {
571
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:purge", spaceId: "purge",
572
+ })).rejects.toThrow(OhPurgedSpaceError);
573
+ client.close();
574
+ });
575
+
576
+ test("rejects new cross-space operation records and cleans legacy mismatches by owner", async () => {
577
+ const client = await bootstrappedClient();
578
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
579
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:owner-purge", spaceId: "owner-purge",
580
+ });
581
+ const operation = await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
582
+ record: entity("entity:private", "Private"), v: 1 }], expectedHead: await authority.store.head(),
583
+ operationId: "op_owner_private" });
584
+ const insertMismatch = () => client.database.query(`INSERT INTO oh_authority_operation_records(
585
+ space_id, operation_sha256, ordinal, record_key, change_kind, record_sha256)
586
+ VALUES (?, ?, 1, ?, 'put', ?)`).run("alien-space", operation.operationSha256,
587
+ "entity:alien", "f".repeat(64));
588
+ expect(insertMismatch).toThrow("no owning operation");
589
+ client.database.exec("DROP TRIGGER oh_authority_operation_records_guard_insert");
590
+ insertMismatch();
591
+ await authority.host.purgeWorkingSpace({ purgedAt: "2026-08-29T13:00:00.000Z" });
592
+ expect(client.database.query<{ count: number }, []>(`SELECT count(*) AS count
593
+ FROM oh_authority_operation_records`).get()?.count).toBe(0);
594
+ await authority.store.close(); client.close();
595
+ });
596
+
597
+ test("cannot resurrect a space purged between open preflight and creation batch", async () => {
598
+ const client = await bootstrappedClient();
599
+ const original = await createOhLibSqlStoreAuthorityV1(client, {
600
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:open-purge-race", spaceId: "open-purge-race",
601
+ });
602
+ let interleaved = false;
603
+ const racingClient: OhLibSqlClientV1 = {
604
+ execute: async (statement) => {
605
+ const result = await client.execute(statement);
606
+ const sql = typeof statement === "string" ? statement : statement.sql;
607
+ const firstArgument = typeof statement === "string" ? undefined : statement.args?.[0];
608
+ if (!interleaved && firstArgument === "open-purge-race"
609
+ && sql.includes("FROM oh_authority_purges WHERE space_id = ?")) {
610
+ interleaved = true;
611
+ await original.host.purgeWorkingSpace({ purgedAt: "2026-08-29T13:00:00.000Z" });
612
+ }
613
+ return result;
614
+ },
615
+ batch: async (statements, mode) => await client.batch(statements, mode),
616
+ };
617
+ await expect(createOhLibSqlStoreAuthorityV1(racingClient, {
618
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:open-purge-race", spaceId: "open-purge-race",
619
+ })).rejects.toThrow(OhPurgedSpaceError);
620
+ expect(interleaved).toBe(true);
621
+ expect(client.database.query<{ count: number }, []>(`SELECT count(*) AS count
622
+ FROM oh_authority_spaces WHERE space_id = 'open-purge-race'`).get()?.count).toBe(0);
623
+ expect(client.database.query<{ count: number }, []>(`SELECT count(*) AS count
624
+ FROM oh_authority_purges WHERE space_id = 'open-purge-race'`).get()?.count).toBe(1);
625
+ client.close();
626
+ });
627
+
628
+ test("rolls purge back when any private payload row resists deletion", async () => {
629
+ const client = await bootstrappedClient();
630
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
631
+ profile: OH_WORKING_STORE_PROFILE_V1, realmId: "realm:blocked-purge", spaceId: "blocked-purge",
632
+ });
633
+ await authority.store.commit({ actorId: "agent.remote", changes: [{ kind: "put",
634
+ record: entity("entity:private", "Private"), v: 1 }], expectedHead: await authority.store.head(),
635
+ operationId: "op_blocked_private" });
636
+ client.database.exec(`CREATE TRIGGER block_record_delete BEFORE DELETE ON oh_authority_records
637
+ BEGIN SELECT RAISE(IGNORE); END`);
638
+ await expect(authority.host.purgeWorkingSpace({ purgedAt: "2026-08-29T13:00:00.000Z" }))
639
+ .rejects.toThrow();
640
+ expect(client.database.query<{ count: number }, []>(`SELECT count(*) AS count
641
+ FROM oh_authority_purges WHERE space_id = 'blocked-purge'`).get()?.count).toBe(0);
642
+ expect(client.database.query<{ count: number }, []>(`SELECT count(*) AS count
643
+ FROM oh_authority_records WHERE space_id = 'blocked-purge'`).get()?.count).toBe(1);
644
+ expect(client.database.query<{ count: number }, []>(`SELECT count(*) AS count
645
+ FROM oh_authority_spaces WHERE space_id = 'blocked-purge'`).get()?.count).toBe(1);
646
+ await authority.store.close(); client.close();
647
+ });
648
+
649
+ test("does not grant canonical stores a purge path", async () => {
650
+ const client = await bootstrappedClient();
651
+ const authority = await createOhLibSqlStoreAuthorityV1(client, {
652
+ profile: OH_CANONICAL_STORE_PROFILE_V1, realmId: "realm:canonical", spaceId: "canonical",
653
+ });
654
+ await expect(authority.host.purgeWorkingSpace({})).rejects.toThrow(OhProfileError);
655
+ await authority.store.close(); client.close();
656
+ });
657
+ });