@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
package/dist/index.js ADDED
@@ -0,0 +1,1988 @@
1
+ // @bun
2
+ // src/canonical.ts
3
+ import { createHash, randomBytes } from "crypto";
4
+
5
+ class OhValidationError extends Error {
6
+ code;
7
+ path;
8
+ constructor(code, path, message) {
9
+ super(`${path}: ${message}`);
10
+ this.name = "OhValidationError";
11
+ this.code = code;
12
+ this.path = path;
13
+ }
14
+ }
15
+ function isPlainRecord(value) {
16
+ if (typeof value !== "object" || value === null || Array.isArray(value))
17
+ return false;
18
+ const prototype = Object.getPrototypeOf(value);
19
+ return prototype === Object.prototype || prototype === null;
20
+ }
21
+ function hasExactKeys(value, keys) {
22
+ const actual = Object.keys(value);
23
+ return actual.length === keys.length && keys.every((key) => Object.hasOwn(value, key));
24
+ }
25
+ function assertUnicodeScalarString(value, path) {
26
+ for (let index = 0;index < value.length; index += 1) {
27
+ const code = value.charCodeAt(index);
28
+ if (code >= 55296 && code <= 56319) {
29
+ const next = value.charCodeAt(index + 1);
30
+ if (!(next >= 56320 && next <= 57343)) {
31
+ throw new OhValidationError("invalid-unicode", path, "contains an unpaired surrogate");
32
+ }
33
+ index += 1;
34
+ } else if (code >= 56320 && code <= 57343) {
35
+ throw new OhValidationError("invalid-unicode", path, "contains an unpaired surrogate");
36
+ }
37
+ }
38
+ }
39
+ function encodeCanonical(value, path, ancestors) {
40
+ if (value === null || typeof value === "boolean")
41
+ return JSON.stringify(value);
42
+ if (typeof value === "string") {
43
+ assertUnicodeScalarString(value, path);
44
+ return JSON.stringify(value);
45
+ }
46
+ if (typeof value === "number") {
47
+ if (!Number.isFinite(value)) {
48
+ throw new OhValidationError("non-json-number", path, "must be finite");
49
+ }
50
+ if (Object.is(value, -0)) {
51
+ throw new OhValidationError("noncanonical-number", path, "negative zero is not canonical");
52
+ }
53
+ return JSON.stringify(value);
54
+ }
55
+ if (typeof value !== "object" || value === null) {
56
+ throw new OhValidationError("non-json-value", path, `cannot encode ${typeof value}`);
57
+ }
58
+ if (ancestors.has(value)) {
59
+ throw new OhValidationError("cycle", path, "contains a cycle");
60
+ }
61
+ ancestors.add(value);
62
+ try {
63
+ if (Array.isArray(value)) {
64
+ const encoded = [];
65
+ for (let index = 0;index < value.length; index += 1) {
66
+ if (!Object.hasOwn(value, index)) {
67
+ throw new OhValidationError("sparse-array", `${path}[${index}]`, "must not contain holes");
68
+ }
69
+ encoded.push(encodeCanonical(value[index], `${path}[${index}]`, ancestors));
70
+ }
71
+ const extraKeys = Reflect.ownKeys(value).filter((key) => key !== "length" && (typeof key !== "string" || !/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= value.length));
72
+ if (extraKeys.length > 0) {
73
+ throw new OhValidationError("non-json-property", path, "array has non-index properties");
74
+ }
75
+ return `[${encoded.join(",")}]`;
76
+ }
77
+ if (!isPlainRecord(value)) {
78
+ throw new OhValidationError("non-plain-object", path, "must be a plain object");
79
+ }
80
+ const ownKeys = Reflect.ownKeys(value);
81
+ if (ownKeys.some((key) => typeof key !== "string")) {
82
+ throw new OhValidationError("non-json-property", path, "object has a symbol property");
83
+ }
84
+ const keys = ownKeys;
85
+ for (const key of keys) {
86
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
87
+ if (descriptor === undefined || !descriptor.enumerable || descriptor.get !== undefined || descriptor.set !== undefined) {
88
+ throw new OhValidationError("non-json-property", `${path}.${key}`, "must be an enumerable data property");
89
+ }
90
+ }
91
+ keys.sort();
92
+ const entries = keys.map((key) => {
93
+ assertUnicodeScalarString(key, `${path}.<key>`);
94
+ return `${JSON.stringify(key)}:${encodeCanonical(value[key], `${path}.${key}`, ancestors)}`;
95
+ });
96
+ return `{${entries.join(",")}}`;
97
+ } finally {
98
+ ancestors.delete(value);
99
+ }
100
+ }
101
+ function canonicalJson(value) {
102
+ return encodeCanonical(value, "$", new Set);
103
+ }
104
+ function parseCanonicalJson(text, maximumBytes = 16 * 1024 * 1024) {
105
+ if (utf8ByteLength(text) > maximumBytes) {
106
+ throw new OhValidationError("limit-exceeded", "$", "canonical JSON exceeds its byte limit");
107
+ }
108
+ let value;
109
+ try {
110
+ value = JSON.parse(text);
111
+ } catch {
112
+ throw new OhValidationError("invalid-json", "$", "is not valid JSON");
113
+ }
114
+ if (canonicalJson(value) !== text) {
115
+ throw new OhValidationError("noncanonical-json", "$", "keys or values are not canonical");
116
+ }
117
+ return value;
118
+ }
119
+ function utf8ByteLength(value) {
120
+ return Buffer.byteLength(value, "utf8");
121
+ }
122
+ function sha256Hex(value) {
123
+ return createHash("sha256").update(value).digest("hex");
124
+ }
125
+ function canonicalSha256(value) {
126
+ return sha256Hex(canonicalJson(value));
127
+ }
128
+ function parseSha256Hex(value) {
129
+ return typeof value === "string" && /^[a-f0-9]{64}$/u.test(value) ? value : null;
130
+ }
131
+ function parseCanonicalInstantV1(value) {
132
+ if (typeof value !== "string" || !/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d\.\d{3}Z$/u.test(value)) {
133
+ return null;
134
+ }
135
+ const timestamp = Date.parse(value);
136
+ return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value ? value : null;
137
+ }
138
+ function canonicalNow() {
139
+ return new Date().toISOString();
140
+ }
141
+ function opaqueId(prefix) {
142
+ if (!/^[a-z][a-z0-9_]{1,15}$/u.test(prefix)) {
143
+ throw new OhValidationError("invalid-prefix", "prefix", "must be a short lowercase code");
144
+ }
145
+ return `${prefix}${randomBytes(12).toString("hex")}`;
146
+ }
147
+ function safeCode(value, maximumLength = 128) {
148
+ return typeof value === "string" && value.length <= maximumLength && /^[a-z][a-z0-9]*(?:[._:/-][a-z0-9]+)*$/u.test(value) ? value : null;
149
+ }
150
+ function boundedText(value, maximumBytes = 64 * 1024) {
151
+ if (typeof value !== "string" || value.length === 0 || value.normalize("NFC") !== value || utf8ByteLength(value) > maximumBytes)
152
+ return null;
153
+ try {
154
+ assertUnicodeScalarString(value, "$text");
155
+ } catch {
156
+ return null;
157
+ }
158
+ for (const character of value) {
159
+ const code = character.codePointAt(0) ?? 0;
160
+ if (code <= 8 || code >= 11 && code <= 12 || code >= 14 && code <= 31 || code >= 127 && code <= 159)
161
+ return null;
162
+ }
163
+ return value;
164
+ }
165
+ function orderedUnique(values, key) {
166
+ return values.every((value, index) => index === 0 || key(values[index - 1]) < key(value));
167
+ }
168
+ function sortUnique(values, key) {
169
+ const sorted = [...values].sort((left, right) => {
170
+ const leftKey = key(left);
171
+ const rightKey = key(right);
172
+ return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;
173
+ });
174
+ if (!orderedUnique(sorted, key)) {
175
+ throw new OhValidationError("duplicate", "$", "contains duplicate canonical values");
176
+ }
177
+ return sorted;
178
+ }
179
+
180
+ // src/graph.ts
181
+ var OH_GRAPH_FORMAT_VERSION_V1 = 1;
182
+ var OH_GRAPH_LIMITS_V1 = Object.freeze({
183
+ changesPerOperation: 8192,
184
+ dependenciesPerRecord: 4096,
185
+ recordBytes: 1024 * 1024,
186
+ recordsPerSnapshot: 65536
187
+ });
188
+ var OH_KNOWLEDGE_GRAPH_RECORD_KINDS_V1 = [
189
+ "activity",
190
+ "assertion",
191
+ "context",
192
+ "dependency-manifest",
193
+ "edition",
194
+ "entity",
195
+ "evidence",
196
+ "identity-operation",
197
+ "inquiry",
198
+ "inquiry-event",
199
+ "review-decision",
200
+ "rights-decision",
201
+ "schema",
202
+ "shape",
203
+ "statement",
204
+ "type-membership",
205
+ "view",
206
+ "vocabulary"
207
+ ];
208
+ function recordKey(value) {
209
+ return typeof value === "string" && value.length <= 512 && /^[a-z][a-z0-9]*(?:[._:/-][a-z0-9]+)*$/u.test(value) ? value : null;
210
+ }
211
+ function createKnowledgeGraphRecordV1(input) {
212
+ if (!isPlainRecord(input) || !hasExactKeys(input, ["dependencies", "key", "kind", "v", "value"]) || input.v !== 1 || !Array.isArray(input.dependencies))
213
+ throw new TypeError("Invalid graph record input.");
214
+ const key = recordKey(input.key);
215
+ const kind = OH_KNOWLEDGE_GRAPH_RECORD_KINDS_V1.find((candidate) => candidate === input.kind);
216
+ if (key === null || kind === undefined || input.dependencies.length > OH_GRAPH_LIMITS_V1.dependenciesPerRecord)
217
+ throw new TypeError("Invalid graph record identity.");
218
+ const dependencies = input.dependencies.map(recordKey);
219
+ if (dependencies.some((dependency) => dependency === null) || !orderedUnique(dependencies, String) || dependencies.includes(key)) {
220
+ throw new TypeError("Graph dependencies must be ordered, unique, and non-reflexive.");
221
+ }
222
+ const valueJson = canonicalJson(input.value);
223
+ if (Buffer.byteLength(valueJson, "utf8") > OH_GRAPH_LIMITS_V1.recordBytes) {
224
+ throw new RangeError("Graph record value exceeds its canonical byte limit.");
225
+ }
226
+ const payload = { dependencies, key, kind, v: 1, value: input.value };
227
+ return { ...payload, recordSha256: canonicalSha256(payload) };
228
+ }
229
+ function parseKnowledgeGraphRecordV1(value) {
230
+ if (!isPlainRecord(value) || !Object.hasOwn(value, "recordSha256"))
231
+ return null;
232
+ const recordSha256 = parseSha256Hex(value.recordSha256);
233
+ const { recordSha256: _digest, ...input } = value;
234
+ try {
235
+ const created = createKnowledgeGraphRecordV1(input);
236
+ return recordSha256 !== null && created.recordSha256 === recordSha256 ? { ...created, recordSha256 } : null;
237
+ } catch {
238
+ return null;
239
+ }
240
+ }
241
+ function knowledgeGraphRecordRefV1(record) {
242
+ return {
243
+ dependencies: record.dependencies,
244
+ key: record.key,
245
+ kind: record.kind,
246
+ sha256: record.recordSha256,
247
+ v: 1
248
+ };
249
+ }
250
+ function changeKey(change) {
251
+ return change.kind === "put" ? change.record.key : change.key;
252
+ }
253
+ function canonicalKnowledgeGraphChangesV1(changes) {
254
+ const normalized = [];
255
+ for (const change of changes) {
256
+ if (!isPlainRecord(change) || change.v !== 1)
257
+ throw new TypeError("Invalid graph change.");
258
+ if (change.kind === "put") {
259
+ const record = parseKnowledgeGraphRecordV1(change.record);
260
+ if (record === null)
261
+ throw new TypeError("Invalid graph record in change.");
262
+ normalized.push({ kind: "put", record, v: 1 });
263
+ } else if (change.kind === "tombstone") {
264
+ const key = recordKey(change.key);
265
+ const priorSha256 = parseSha256Hex(change.priorSha256);
266
+ if (key === null || priorSha256 === null)
267
+ throw new TypeError("Invalid graph tombstone.");
268
+ normalized.push({ key, kind: "tombstone", priorSha256, v: 1 });
269
+ } else
270
+ throw new TypeError("Unknown graph change kind.");
271
+ }
272
+ return sortUnique(normalized, changeKey);
273
+ }
274
+ function graphRevisionSha256V1(input) {
275
+ const changes = canonicalKnowledgeGraphChangesV1(input.changes);
276
+ const operationId = safeCode(input.operationId);
277
+ const parentGraphRevisionSha256 = input.parentGraphRevisionSha256 === null ? null : parseSha256Hex(input.parentGraphRevisionSha256);
278
+ const recordsSha256 = parseSha256Hex(input.recordsSha256);
279
+ const revision = Number.isSafeInteger(input.revision) && input.revision > 0 ? input.revision : null;
280
+ if (changes.length === 0 || changes.length > OH_GRAPH_LIMITS_V1.changesPerOperation || operationId === null || recordsSha256 === null || revision === null || input.parentGraphRevisionSha256 !== null && parentGraphRevisionSha256 === null || revision === 1 !== (parentGraphRevisionSha256 === null)) {
281
+ throw new TypeError("Invalid graph revision digest input.");
282
+ }
283
+ return canonicalSha256({ changes, operationId, parentGraphRevisionSha256, recordsSha256, revision, v: 1 });
284
+ }
285
+ function createKnowledgeGraphRevisionV1(input) {
286
+ if (input.parent !== null && parseKnowledgeGraphRevisionV1(input.parent) === null) {
287
+ throw new TypeError("Invalid parent graph revision.");
288
+ }
289
+ const operationId = safeCode(input.operationId);
290
+ const changes = canonicalKnowledgeGraphChangesV1(input.changes);
291
+ if (operationId === null || changes.length === 0 || changes.length > OH_GRAPH_LIMITS_V1.changesPerOperation)
292
+ throw new TypeError("Invalid graph revision.");
293
+ const byKey = new Map((input.parent?.recordRefs ?? []).map((ref) => [ref.key, ref]));
294
+ for (const change of changes) {
295
+ if (change.kind === "put") {
296
+ for (const dependency of change.record.dependencies) {
297
+ if (!byKey.has(dependency) && !changes.some((candidate) => candidate.kind === "put" && candidate.record.key === dependency)) {
298
+ throw new TypeError(`Missing graph dependency: ${dependency}`);
299
+ }
300
+ }
301
+ byKey.set(change.record.key, knowledgeGraphRecordRefV1(change.record));
302
+ } else {
303
+ const prior = byKey.get(change.key);
304
+ if (prior === undefined || prior.sha256 !== change.priorSha256)
305
+ throw new TypeError("Tombstone prior digest does not match.");
306
+ byKey.delete(change.key);
307
+ }
308
+ }
309
+ if (byKey.size > OH_GRAPH_LIMITS_V1.recordsPerSnapshot) {
310
+ throw new RangeError("Graph revision exceeds its record snapshot limit.");
311
+ }
312
+ for (const ref of byKey.values()) {
313
+ if (ref.dependencies.some((dependency) => !byKey.has(dependency))) {
314
+ throw new TypeError(`Missing graph dependency after revision: ${ref.key}`);
315
+ }
316
+ }
317
+ const recordRefs = [...byKey.values()].sort((left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0);
318
+ const recordsSha256 = canonicalSha256(recordRefs);
319
+ const payload = {
320
+ changes,
321
+ operationId,
322
+ parentGraphRevisionSha256: input.parent?.graphRevisionSha256 ?? null,
323
+ recordRefs,
324
+ recordsSha256,
325
+ revision: (input.parent?.revision ?? 0) + 1,
326
+ v: 1
327
+ };
328
+ return { ...payload, graphRevisionSha256: graphRevisionSha256V1(payload) };
329
+ }
330
+ function parseKnowledgeGraphRevisionV1(value) {
331
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
332
+ "changes",
333
+ "graphRevisionSha256",
334
+ "operationId",
335
+ "parentGraphRevisionSha256",
336
+ "recordRefs",
337
+ "recordsSha256",
338
+ "revision",
339
+ "v"
340
+ ]) || value.v !== 1 || !Array.isArray(value.changes) || !Array.isArray(value.recordRefs) || value.recordRefs.length > OH_GRAPH_LIMITS_V1.recordsPerSnapshot)
341
+ return null;
342
+ const graphRevisionSha256 = parseSha256Hex(value.graphRevisionSha256);
343
+ const recordsSha256 = parseSha256Hex(value.recordsSha256);
344
+ const parentGraphRevisionSha256 = value.parentGraphRevisionSha256 === null ? null : parseSha256Hex(value.parentGraphRevisionSha256);
345
+ const operationId = safeCode(value.operationId);
346
+ const revision = Number.isSafeInteger(value.revision) && value.revision > 0 ? value.revision : null;
347
+ let changes;
348
+ try {
349
+ changes = canonicalKnowledgeGraphChangesV1(value.changes);
350
+ } catch {
351
+ return null;
352
+ }
353
+ const refs = [];
354
+ for (const item of value.recordRefs) {
355
+ if (!isPlainRecord(item) || !hasExactKeys(item, ["dependencies", "key", "kind", "sha256", "v"]) || item.v !== 1 || !Array.isArray(item.dependencies))
356
+ return null;
357
+ const dependencies = item.dependencies.map(recordKey);
358
+ const key = recordKey(item.key);
359
+ const kind = OH_KNOWLEDGE_GRAPH_RECORD_KINDS_V1.find((candidate) => candidate === item.kind);
360
+ const sha256 = parseSha256Hex(item.sha256);
361
+ if (key === null || kind === undefined || sha256 === null || dependencies.some((dependency) => dependency === null) || dependencies.length > OH_GRAPH_LIMITS_V1.dependenciesPerRecord || !orderedUnique(dependencies, String) || dependencies.includes(key))
362
+ return null;
363
+ refs.push({ dependencies, key, kind, sha256, v: 1 });
364
+ }
365
+ if (graphRevisionSha256 === null || recordsSha256 === null || operationId === null || revision === null || value.parentGraphRevisionSha256 !== null && parentGraphRevisionSha256 === null || !orderedUnique(refs, (ref) => ref.key) || canonicalSha256(refs) !== recordsSha256)
366
+ return null;
367
+ const keys = new Set(refs.map((ref) => ref.key));
368
+ if (refs.some((ref) => ref.dependencies.some((dependency) => !keys.has(dependency))))
369
+ return null;
370
+ const payload = {
371
+ changes,
372
+ operationId,
373
+ parentGraphRevisionSha256,
374
+ recordRefs: refs,
375
+ recordsSha256,
376
+ revision,
377
+ v: 1
378
+ };
379
+ try {
380
+ return graphRevisionSha256V1(payload) === graphRevisionSha256 ? { ...payload, graphRevisionSha256 } : null;
381
+ } catch {
382
+ return null;
383
+ }
384
+ }
385
+ function reduceKnowledgeGraphRevisionsV1(revisions) {
386
+ if (revisions.length === 0 || revisions.length > 65536)
387
+ return null;
388
+ const ordered = [...revisions].sort((left, right) => left.revision - right.revision);
389
+ let parent = null;
390
+ const operationIds = new Set;
391
+ for (const candidate of ordered) {
392
+ const current = parseKnowledgeGraphRevisionV1(candidate);
393
+ if (current === null || current.revision !== (parent?.revision ?? 0) + 1 || current.parentGraphRevisionSha256 !== (parent?.graphRevisionSha256 ?? null) || operationIds.has(current.operationId))
394
+ return null;
395
+ try {
396
+ const rebuilt = createKnowledgeGraphRevisionV1({ changes: current.changes, operationId: current.operationId, parent });
397
+ if (rebuilt.graphRevisionSha256 !== current.graphRevisionSha256)
398
+ return null;
399
+ } catch {
400
+ return null;
401
+ }
402
+ operationIds.add(current.operationId);
403
+ parent = current;
404
+ }
405
+ return parent;
406
+ }
407
+
408
+ // src/ontology.ts
409
+ var OH_ONTOLOGY_VERSION_V1 = "1.0.0";
410
+ var OH_CONTRACT_ID_V1 = "oh.ontology.v1";
411
+ var OH_KNOWLEDGE_LIMITS_V1 = Object.freeze({
412
+ dimensions: 64,
413
+ listValues: 256,
414
+ qualifiers: 128,
415
+ statementBytes: 256 * 1024,
416
+ textBytes: 64 * 1024
417
+ });
418
+ var OH_KNOWLEDGE_KERNEL_CONCEPTS_V1 = [
419
+ { code: "entity", description: "A stable identity anchor for something that can be referred to.", label: "Entity" },
420
+ { code: "statement", description: "An immutable proposition with a subject, predicate, object, and qualifiers.", label: "Statement" },
421
+ { code: "assertion", description: "An attributable stance toward a statement.", label: "Assertion" },
422
+ { code: "evidence", description: "A typed account of how an observation bears on an assertion.", label: "Evidence" },
423
+ { code: "context", description: "The scenario and dimensions in which knowledge applies.", label: "Context" },
424
+ { code: "inquiry", description: "A question and its durable investigation trail.", label: "Inquiry" },
425
+ { code: "projection", description: "A reproducible view derived from exact knowledge.", label: "Projection" }
426
+ ];
427
+ function success(value) {
428
+ return { ok: true, value };
429
+ }
430
+ function failure(field, code = "invalid-input") {
431
+ return { error: { code, field }, ok: false };
432
+ }
433
+ function parseOpaqueId(value, prefix) {
434
+ return typeof value === "string" && new RegExp(`^${prefix}[a-z0-9]{24}$`, "u").test(value) ? value : null;
435
+ }
436
+ function parseKnowledgeEntityId(value) {
437
+ return parseOpaqueId(value, "kent_");
438
+ }
439
+ function parseKnowledgeAssertionId(value) {
440
+ return parseOpaqueId(value, "kast_");
441
+ }
442
+ function parseKnowledgeEvidenceId(value) {
443
+ return parseOpaqueId(value, "kevd_");
444
+ }
445
+ function parseKnowledgeInquiryId(value) {
446
+ return parseOpaqueId(value, "kinq_");
447
+ }
448
+ var OH_KNOWLEDGE_ENTITY_STATES_V1 = ["active", "quarantined", "redirected", "tombstoned"];
449
+ function parseKnowledgeEntityV1(value) {
450
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
451
+ "entityId",
452
+ "identityOperationId",
453
+ "identityRevision",
454
+ "redirectEntityId",
455
+ "state",
456
+ "v"
457
+ ]) || value.v !== 1)
458
+ return failure("entity");
459
+ const entityId = parseKnowledgeEntityId(value.entityId);
460
+ const identityOperationId = safeCode(value.identityOperationId);
461
+ const identityRevision = Number.isSafeInteger(value.identityRevision) && value.identityRevision > 0 ? value.identityRevision : null;
462
+ const redirectEntityId = value.redirectEntityId === null ? null : parseKnowledgeEntityId(value.redirectEntityId);
463
+ const state = OH_KNOWLEDGE_ENTITY_STATES_V1.find((candidate) => candidate === value.state);
464
+ return entityId !== null && identityOperationId !== null && identityRevision !== null && (value.redirectEntityId === null || redirectEntityId !== null) && state !== undefined && state === "redirected" === (redirectEntityId !== null) && redirectEntityId !== entityId ? success({ entityId, identityOperationId, identityRevision, redirectEntityId, state, v: 1 }) : failure("entity");
465
+ }
466
+ function parseKnowledgeSchemaRefV1(value) {
467
+ if (!isPlainRecord(value) || !hasExactKeys(value, ["code", "namespace", "revision", "schemaSha256", "v"]) || value.v !== 1)
468
+ return failure("schemaRef");
469
+ const code = safeCode(value.code);
470
+ const namespace = safeCode(value.namespace);
471
+ const revision = Number.isSafeInteger(value.revision) && value.revision > 0 ? value.revision : null;
472
+ const schemaSha256 = parseSha256Hex(value.schemaSha256);
473
+ return code !== null && namespace !== null && revision !== null && schemaSha256 !== null ? success({ code, namespace, revision, schemaSha256, v: 1 }) : failure("schemaRef");
474
+ }
475
+ var INTEGER = /^(?:0|-[1-9][0-9]*|[1-9][0-9]*)$/u;
476
+ var DECIMAL = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*[1-9])?$/u;
477
+ function parseKnowledgeValueInternal(value, depth) {
478
+ if (!isPlainRecord(value) || value.v !== 1 || depth > 8)
479
+ return null;
480
+ switch (value.kind) {
481
+ case "entity": {
482
+ if (!hasExactKeys(value, ["entityId", "kind", "v"]))
483
+ return null;
484
+ const entityId = parseKnowledgeEntityId(value.entityId);
485
+ return entityId === null ? null : { entityId, kind: "entity", v: 1 };
486
+ }
487
+ case "text": {
488
+ if (!hasExactKeys(value, ["kind", "language", "text", "v"]))
489
+ return null;
490
+ const language = typeof value.language === "string" && /^(?:und|[a-z]{2,3}(?:-[a-z0-9]{2,8})*)$/u.test(value.language) ? value.language : null;
491
+ const text = boundedText(value.text);
492
+ return language !== null && text !== null ? { kind: "text", language, text, v: 1 } : null;
493
+ }
494
+ case "string": {
495
+ const parsed = boundedText(value.value);
496
+ return hasExactKeys(value, ["kind", "v", "value"]) && parsed !== null ? { kind: "string", v: 1, value: parsed } : null;
497
+ }
498
+ case "boolean":
499
+ return hasExactKeys(value, ["kind", "v", "value"]) && typeof value.value === "boolean" ? { kind: "boolean", v: 1, value: value.value } : null;
500
+ case "integer":
501
+ case "decimal": {
502
+ const valid = typeof value.value === "string" && value.value.length <= 1024 && (value.kind === "integer" ? INTEGER.test(value.value) : DECIMAL.test(value.value) && value.value !== "-0");
503
+ return hasExactKeys(value, ["kind", "v", "value"]) && valid ? { kind: value.kind, v: 1, value: value.value } : null;
504
+ }
505
+ case "uri": {
506
+ if (!hasExactKeys(value, ["kind", "uri", "v"]) || typeof value.uri !== "string" || value.uri.length > 4096)
507
+ return null;
508
+ try {
509
+ const url = new URL(value.uri);
510
+ return url.href === value.uri && url.username === "" && url.password === "" && !["data:", "file:", "javascript:"].includes(url.protocol) ? { kind: "uri", uri: value.uri, v: 1 } : null;
511
+ } catch {
512
+ return null;
513
+ }
514
+ }
515
+ case "list":
516
+ case "set": {
517
+ if (!hasExactKeys(value, ["kind", "v", "values"]) || !Array.isArray(value.values) || value.values.length > OH_KNOWLEDGE_LIMITS_V1.listValues)
518
+ return null;
519
+ const values = [];
520
+ for (const item of value.values) {
521
+ const parsed = parseKnowledgeValueInternal(item, depth + 1);
522
+ if (parsed === null)
523
+ return null;
524
+ values.push(parsed);
525
+ }
526
+ if (value.kind === "set" && !orderedUnique(values, canonicalJson))
527
+ return null;
528
+ return { kind: value.kind, v: 1, values };
529
+ }
530
+ case "extension": {
531
+ if (!hasExactKeys(value, ["canonicalizerSha256", "canonicalValue", "kind", "mediaType", "schema", "v", "valueSha256"]))
532
+ return null;
533
+ const canonicalizerSha256 = parseSha256Hex(value.canonicalizerSha256);
534
+ const canonicalValue = boundedText(value.canonicalValue, 64 * 1024);
535
+ const mediaType = typeof value.mediaType === "string" && /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/u.test(value.mediaType) ? value.mediaType : null;
536
+ const schema = parseKnowledgeSchemaRefV1(value.schema);
537
+ const valueSha256 = parseSha256Hex(value.valueSha256);
538
+ return canonicalizerSha256 !== null && canonicalValue !== null && mediaType !== null && schema.ok && valueSha256 !== null ? { canonicalizerSha256, canonicalValue, kind: "extension", mediaType, schema: schema.value, v: 1, valueSha256 } : null;
539
+ }
540
+ default:
541
+ return null;
542
+ }
543
+ }
544
+ function parseKnowledgeValueV1(value) {
545
+ const parsed = parseKnowledgeValueInternal(value, 0);
546
+ return parsed === null ? failure("value") : success(parsed);
547
+ }
548
+ function verifyKnowledgeValueV1(value) {
549
+ const parsed = parseKnowledgeValueV1(value);
550
+ if (!parsed.ok)
551
+ return parsed;
552
+ if (parsed.value.kind === "extension" && sha256Hex(parsed.value.canonicalValue) !== parsed.value.valueSha256) {
553
+ return failure("valueSha256", "digest-mismatch");
554
+ }
555
+ if (parsed.value.kind === "list" || parsed.value.kind === "set") {
556
+ for (const child of parsed.value.values) {
557
+ const verified = verifyKnowledgeValueV1(child);
558
+ if (!verified.ok)
559
+ return verified;
560
+ }
561
+ }
562
+ return success(parsed.value);
563
+ }
564
+ function parseDimension(value) {
565
+ if (!isPlainRecord(value) || !hasExactKeys(value, ["predicate", "v", "value"]) || value.v !== 1)
566
+ return null;
567
+ const predicate = parseKnowledgeSchemaRefV1(value.predicate);
568
+ const parsedValue = parseKnowledgeValueV1(value.value);
569
+ return predicate.ok && parsedValue.ok ? { predicate: predicate.value, v: 1, value: parsedValue.value } : null;
570
+ }
571
+ function createKnowledgeContextV1(input) {
572
+ if (!isPlainRecord(input) || input.v !== 1 || !Array.isArray(input.dimensions) || input.dimensions.length > OH_KNOWLEDGE_LIMITS_V1.dimensions || !["actual", "counterfactual", "hypothetical", "planned"].includes(input.scenario))
573
+ return failure("context");
574
+ const dimensions = [];
575
+ for (const item of input.dimensions) {
576
+ const parsed = parseDimension(item);
577
+ if (parsed === null)
578
+ return failure("dimensions");
579
+ const verified = verifyKnowledgeValueV1(parsed.value);
580
+ if (!verified.ok)
581
+ return verified;
582
+ dimensions.push(parsed);
583
+ }
584
+ let canonicalDimensions;
585
+ try {
586
+ canonicalDimensions = sortUnique(dimensions, canonicalJson);
587
+ } catch {
588
+ return failure("dimensions", "noncanonical-input");
589
+ }
590
+ const payload = { dimensions: canonicalDimensions, scenario: input.scenario, v: 1 };
591
+ return success({ ...payload, contextSha256: canonicalSha256(payload) });
592
+ }
593
+ function parseKnowledgeContextV1(value) {
594
+ if (!isPlainRecord(value) || !hasExactKeys(value, ["contextSha256", "dimensions", "scenario", "v"]))
595
+ return failure("context");
596
+ const digest = parseSha256Hex(value.contextSha256);
597
+ if (digest === null)
598
+ return failure("contextSha256");
599
+ const created = createKnowledgeContextV1({ dimensions: value.dimensions, scenario: value.scenario, v: value.v });
600
+ return created.ok && created.value.contextSha256 === digest && canonicalJson(created.value.dimensions) === canonicalJson(value.dimensions) ? success({ ...created.value, contextSha256: digest }) : failure("contextSha256", "digest-mismatch");
601
+ }
602
+ function createKnowledgeStatementV1(input) {
603
+ const object = parseKnowledgeValueV1(input.object);
604
+ const predicate = parseKnowledgeSchemaRefV1(input.predicate);
605
+ const subject = parseKnowledgeEntityId(input.subject);
606
+ if (input.v !== 1 || !object.ok || !predicate.ok || subject === null || !Array.isArray(input.qualifiers) || input.qualifiers.length > OH_KNOWLEDGE_LIMITS_V1.qualifiers)
607
+ return failure("statement");
608
+ const verifiedObject = verifyKnowledgeValueV1(object.value);
609
+ if (!verifiedObject.ok)
610
+ return verifiedObject;
611
+ const qualifiers = [];
612
+ for (const item of input.qualifiers) {
613
+ const parsed = parseDimension(item);
614
+ if (parsed === null)
615
+ return failure("qualifiers");
616
+ const verified = verifyKnowledgeValueV1(parsed.value);
617
+ if (!verified.ok)
618
+ return verified;
619
+ qualifiers.push(parsed);
620
+ }
621
+ let canonicalQualifiers;
622
+ try {
623
+ canonicalQualifiers = sortUnique(qualifiers, canonicalJson);
624
+ } catch {
625
+ return failure("qualifiers", "noncanonical-input");
626
+ }
627
+ const payload = { object: object.value, predicate: predicate.value, qualifiers: canonicalQualifiers, subject, v: 1 };
628
+ if (Buffer.byteLength(canonicalJson(payload), "utf8") > OH_KNOWLEDGE_LIMITS_V1.statementBytes)
629
+ return failure("statement", "limit-exceeded");
630
+ return success({ ...payload, statementSha256: canonicalSha256(payload) });
631
+ }
632
+ function parseKnowledgeStatementV1(value) {
633
+ if (!isPlainRecord(value) || !hasExactKeys(value, ["object", "predicate", "qualifiers", "statementSha256", "subject", "v"]))
634
+ return failure("statement");
635
+ const digest = parseSha256Hex(value.statementSha256);
636
+ const created = createKnowledgeStatementV1(value);
637
+ return digest !== null && created.ok && created.value.statementSha256 === digest && canonicalJson(created.value.qualifiers) === canonicalJson(value.qualifiers) ? success({ ...created.value, statementSha256: digest }) : failure("statementSha256", "digest-mismatch");
638
+ }
639
+ function parseKnowledgeAgentRefV1(value) {
640
+ if (!isPlainRecord(value) || value.v !== 1)
641
+ return null;
642
+ if (value.kind === "entity" && hasExactKeys(value, ["entityId", "kind", "v"])) {
643
+ const entityId = parseKnowledgeEntityId(value.entityId);
644
+ return entityId === null ? null : { entityId, kind: "entity", v: 1 };
645
+ }
646
+ if (value.kind === "model" && hasExactKeys(value, ["kind", "model", "receiptSha256", "v"])) {
647
+ const model = parseKnowledgeSchemaRefV1(value.model);
648
+ const receiptSha256 = parseSha256Hex(value.receiptSha256);
649
+ return model.ok && receiptSha256 !== null ? { kind: "model", model: model.value, receiptSha256, v: 1 } : null;
650
+ }
651
+ if (value.kind === "system" && hasExactKeys(value, ["authority", "kind", "receiptSha256", "v"])) {
652
+ const authority = parseKnowledgeSchemaRefV1(value.authority);
653
+ const receiptSha256 = parseSha256Hex(value.receiptSha256);
654
+ return authority.ok && receiptSha256 !== null ? { authority: authority.value, kind: "system", receiptSha256, v: 1 } : null;
655
+ }
656
+ return null;
657
+ }
658
+ function parseDigestArray(value, maximum = 2048) {
659
+ if (!Array.isArray(value) || value.length > maximum)
660
+ return null;
661
+ const digests = value.map(parseSha256Hex);
662
+ return digests.every((digest) => digest !== null) && orderedUnique(digests, String) ? digests : null;
663
+ }
664
+ var OH_KNOWLEDGE_ACTIVITY_KINDS_V1 = [
665
+ "extraction",
666
+ "human-entry",
667
+ "human-review",
668
+ "import",
669
+ "model-proposal",
670
+ "normalization",
671
+ "publication",
672
+ "resolution",
673
+ "transformation"
674
+ ];
675
+ function parseActivityInput(value) {
676
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
677
+ "actor",
678
+ "inputSha256s",
679
+ "kind",
680
+ "occurredAt",
681
+ "outputSha256s",
682
+ "policySha256",
683
+ "tool",
684
+ "v"
685
+ ]) || value.v !== 1)
686
+ return null;
687
+ const actor = parseKnowledgeAgentRefV1(value.actor);
688
+ const inputSha256s = parseDigestArray(value.inputSha256s);
689
+ const kind = OH_KNOWLEDGE_ACTIVITY_KINDS_V1.find((candidate) => candidate === value.kind);
690
+ const occurredAt = parseCanonicalInstantV1(value.occurredAt);
691
+ const outputSha256s = parseDigestArray(value.outputSha256s);
692
+ const policySha256 = parseSha256Hex(value.policySha256);
693
+ const tool = value.tool === null ? null : parseKnowledgeSchemaRefV1(value.tool);
694
+ const parsedTool = tool === null ? null : tool.ok ? tool.value : null;
695
+ return actor !== null && inputSha256s !== null && kind !== undefined && occurredAt !== null && outputSha256s !== null && policySha256 !== null && (value.tool === null || parsedTool !== null) ? { actor, inputSha256s, kind, occurredAt, outputSha256s, policySha256, tool: parsedTool, v: 1 } : null;
696
+ }
697
+ function createKnowledgeActivityV1(input) {
698
+ const parsed = parseActivityInput(input);
699
+ return parsed === null ? failure("activity") : success({ ...parsed, activitySha256: canonicalSha256(parsed) });
700
+ }
701
+ function parseKnowledgeActivityV1(value) {
702
+ if (!isPlainRecord(value) || !Object.hasOwn(value, "activitySha256"))
703
+ return failure("activity");
704
+ const activitySha256 = parseSha256Hex(value.activitySha256);
705
+ const { activitySha256: _digest, ...input } = value;
706
+ const parsed = parseActivityInput(input);
707
+ return activitySha256 !== null && parsed !== null && canonicalSha256(parsed) === activitySha256 ? success({ ...parsed, activitySha256 }) : failure("activitySha256", "digest-mismatch");
708
+ }
709
+ var OH_KNOWLEDGE_ASSERTION_STANCES_V1 = ["questions", "refutes", "reports", "supports", "undetermined"];
710
+ var OH_KNOWLEDGE_ASSERTION_STATES_V1 = [
711
+ "accepted-for-purpose",
712
+ "disputed",
713
+ "proposed",
714
+ "reviewed",
715
+ "superseded",
716
+ "withdrawn"
717
+ ];
718
+ function parseStringCodes(value, maximum) {
719
+ if (!Array.isArray(value) || value.length > maximum)
720
+ return null;
721
+ const codes = value.map((item) => safeCode(item));
722
+ return codes.every((code) => code !== null) && orderedUnique(codes, String) ? codes : null;
723
+ }
724
+ function parseAssertionInput(value) {
725
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
726
+ "acceptedPurposes",
727
+ "assertionId",
728
+ "assertor",
729
+ "confidence",
730
+ "contextSha256",
731
+ "provenanceActivitySha256",
732
+ "reviewActivitySha256",
733
+ "stance",
734
+ "state",
735
+ "statementSha256",
736
+ "v"
737
+ ]) || value.v !== 1)
738
+ return null;
739
+ const acceptedPurposes = parseStringCodes(value.acceptedPurposes, 32);
740
+ const assertionId = parseKnowledgeAssertionId(value.assertionId);
741
+ const assertor = parseKnowledgeAgentRefV1(value.assertor);
742
+ const confidence = value.confidence === null ? null : parseKnowledgeSchemaRefV1(value.confidence);
743
+ const parsedConfidence = confidence === null ? null : confidence.ok ? confidence.value : null;
744
+ const contextSha256 = value.contextSha256 === null ? null : parseSha256Hex(value.contextSha256);
745
+ const provenanceActivitySha256 = parseSha256Hex(value.provenanceActivitySha256);
746
+ const reviewActivitySha256 = value.reviewActivitySha256 === null ? null : parseSha256Hex(value.reviewActivitySha256);
747
+ const stance = OH_KNOWLEDGE_ASSERTION_STANCES_V1.find((candidate) => candidate === value.stance);
748
+ const state = OH_KNOWLEDGE_ASSERTION_STATES_V1.find((candidate) => candidate === value.state);
749
+ const statementSha256 = parseSha256Hex(value.statementSha256);
750
+ if (acceptedPurposes === null || assertionId === null || assertor === null || value.confidence !== null && parsedConfidence === null || value.contextSha256 !== null && contextSha256 === null || provenanceActivitySha256 === null || value.reviewActivitySha256 !== null && reviewActivitySha256 === null || stance === undefined || state === undefined || statementSha256 === null)
751
+ return null;
752
+ if (assertor.kind === "model" && (state !== "proposed" || acceptedPurposes.length !== 0 || reviewActivitySha256 !== null))
753
+ return null;
754
+ if (state === "accepted-for-purpose" !== acceptedPurposes.length > 0 || state !== "proposed" && reviewActivitySha256 === null)
755
+ return null;
756
+ return {
757
+ acceptedPurposes,
758
+ assertionId,
759
+ assertor,
760
+ confidence: parsedConfidence,
761
+ contextSha256,
762
+ provenanceActivitySha256,
763
+ reviewActivitySha256,
764
+ stance,
765
+ state,
766
+ statementSha256,
767
+ v: 1
768
+ };
769
+ }
770
+ function createKnowledgeAssertionV1(input) {
771
+ const parsed = parseAssertionInput(input);
772
+ return parsed === null ? failure("assertion") : success({ ...parsed, assertionSha256: canonicalSha256(parsed) });
773
+ }
774
+ function parseKnowledgeAssertionV1(value) {
775
+ if (!isPlainRecord(value) || !Object.hasOwn(value, "assertionSha256"))
776
+ return failure("assertion");
777
+ const assertionSha256 = parseSha256Hex(value.assertionSha256);
778
+ const { assertionSha256: _digest, ...input } = value;
779
+ const parsed = parseAssertionInput(input);
780
+ return assertionSha256 !== null && parsed !== null && canonicalSha256(parsed) === assertionSha256 ? success({ ...parsed, assertionSha256 }) : failure("assertionSha256", "digest-mismatch");
781
+ }
782
+ var OH_KNOWLEDGE_EVIDENCE_BEARINGS_V1 = [
783
+ "background",
784
+ "contradicts",
785
+ "corroborates",
786
+ "direct-observation",
787
+ "method",
788
+ "quotation",
789
+ "registry-record",
790
+ "supports"
791
+ ];
792
+ function parseEvidenceInput(value) {
793
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
794
+ "assertionSha256",
795
+ "bearing",
796
+ "disclosure",
797
+ "evidenceId",
798
+ "observationSha256",
799
+ "provenanceActivitySha256",
800
+ "selector",
801
+ "sourceEntityId",
802
+ "v"
803
+ ]) || value.v !== 1)
804
+ return null;
805
+ const assertionSha256 = parseSha256Hex(value.assertionSha256);
806
+ const bearing = OH_KNOWLEDGE_EVIDENCE_BEARINGS_V1.find((candidate) => candidate === value.bearing);
807
+ const evidenceId = parseKnowledgeEvidenceId(value.evidenceId);
808
+ const observationSha256 = value.observationSha256 === null ? null : parseSha256Hex(value.observationSha256);
809
+ const provenanceActivitySha256 = parseSha256Hex(value.provenanceActivitySha256);
810
+ const selector = value.selector === null ? null : boundedText(value.selector, 8192);
811
+ const sourceEntityId = value.sourceEntityId === null ? null : parseKnowledgeEntityId(value.sourceEntityId);
812
+ return assertionSha256 !== null && bearing !== undefined && (value.disclosure === "private" || value.disclosure === "public" || value.disclosure === "shared") && evidenceId !== null && (value.observationSha256 === null || observationSha256 !== null) && provenanceActivitySha256 !== null && (value.selector === null || selector !== null) && (value.sourceEntityId === null || sourceEntityId !== null) && (observationSha256 !== null || sourceEntityId !== null) ? {
813
+ assertionSha256,
814
+ bearing,
815
+ disclosure: value.disclosure,
816
+ evidenceId,
817
+ observationSha256,
818
+ provenanceActivitySha256,
819
+ selector,
820
+ sourceEntityId,
821
+ v: 1
822
+ } : null;
823
+ }
824
+ function createKnowledgeEvidenceLinkV1(input) {
825
+ const parsed = parseEvidenceInput(input);
826
+ return parsed === null ? failure("evidence") : success({ ...parsed, evidenceSha256: canonicalSha256(parsed) });
827
+ }
828
+ function parseKnowledgeEvidenceLinkV1(value) {
829
+ if (!isPlainRecord(value) || !Object.hasOwn(value, "evidenceSha256"))
830
+ return failure("evidence");
831
+ const evidenceSha256 = parseSha256Hex(value.evidenceSha256);
832
+ const { evidenceSha256: _digest, ...input } = value;
833
+ const parsed = parseEvidenceInput(input);
834
+ return evidenceSha256 !== null && parsed !== null && canonicalSha256(parsed) === evidenceSha256 ? success({ ...parsed, evidenceSha256 }) : failure("evidenceSha256", "digest-mismatch");
835
+ }
836
+ function createKnowledgeInquiryV1(input) {
837
+ const answerForm = safeCode(input.answerForm);
838
+ const authorEntityId = parseKnowledgeEntityId(input.authorEntityId);
839
+ const contextSha256 = input.contextSha256 === null ? null : parseSha256Hex(input.contextSha256);
840
+ const createdAt = parseCanonicalInstantV1(input.createdAt);
841
+ const inquiryId = parseKnowledgeInquiryId(input.inquiryId);
842
+ const language = typeof input.language === "string" && /^(?:und|[a-z]{2,3}(?:-[a-z0-9]{2,8})*)$/u.test(input.language) ? input.language : null;
843
+ const parents = Array.isArray(input.parentInquiryIds) ? input.parentInquiryIds.map(parseKnowledgeInquiryId) : null;
844
+ const question = boundedText(input.question, 16384);
845
+ if (input.v !== 1 || answerForm === null || authorEntityId === null || input.contextSha256 !== null && contextSha256 === null || createdAt === null || inquiryId === null || language === null || parents === null || parents.some((item) => item === null) || !orderedUnique(parents, String) || !["private", "public", "shared"].includes(input.privacy) || question === null || !["abandoned", "open", "paused", "resolved"].includes(input.status))
846
+ return failure("inquiry");
847
+ const payload = {
848
+ answerForm,
849
+ authorEntityId,
850
+ contextSha256,
851
+ createdAt,
852
+ inquiryId,
853
+ language,
854
+ parentInquiryIds: parents,
855
+ privacy: input.privacy,
856
+ question,
857
+ status: input.status,
858
+ v: 1
859
+ };
860
+ return success({ ...payload, inquirySha256: canonicalSha256(payload) });
861
+ }
862
+ function parseKnowledgeInquiryV1(value) {
863
+ if (!isPlainRecord(value) || !Object.hasOwn(value, "inquirySha256"))
864
+ return failure("inquiry");
865
+ const digest = parseSha256Hex(value.inquirySha256);
866
+ const { inquirySha256: _digest, ...input } = value;
867
+ const created = createKnowledgeInquiryV1(input);
868
+ return digest !== null && created.ok && created.value.inquirySha256 === digest ? success({ ...created.value, inquirySha256: digest }) : failure("inquirySha256", "digest-mismatch");
869
+ }
870
+
871
+ // src/schema.ts
872
+ var OH_SCHEMA_FORMAT_VERSION_V1 = 1;
873
+ var OH_SCHEMA_KINDS_V1 = ["concept", "mapping", "predicate", "shape", "unit", "vocabulary"];
874
+ function parseLocalizedTexts(value) {
875
+ if (!Array.isArray(value) || value.length === 0 || value.length > 128)
876
+ return null;
877
+ const output = [];
878
+ for (const item of value) {
879
+ if (!isPlainRecord(item) || !hasExactKeys(item, ["language", "text", "v"]) || item.v !== 1)
880
+ return null;
881
+ const language = typeof item.language === "string" && /^(?:und|[a-z]{2,3}(?:-[a-z0-9]{2,8})*)$/u.test(item.language) ? item.language : null;
882
+ const text = boundedText(item.text, 16384);
883
+ if (language === null || text === null)
884
+ return null;
885
+ output.push({ language, text, v: 1 });
886
+ }
887
+ return orderedUnique(output, canonicalJson) ? output : null;
888
+ }
889
+ function parseSchemaInput(value) {
890
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
891
+ "body",
892
+ "code",
893
+ "compatibility",
894
+ "description",
895
+ "kind",
896
+ "labels",
897
+ "namespace",
898
+ "previousSchemaSha256",
899
+ "revision",
900
+ "v"
901
+ ]) || value.v !== 1 || !isPlainRecord(value.body))
902
+ return null;
903
+ try {
904
+ canonicalJson(value.body);
905
+ } catch {
906
+ return null;
907
+ }
908
+ const code = safeCode(value.code);
909
+ const namespace = safeCode(value.namespace);
910
+ const kind = OH_SCHEMA_KINDS_V1.find((candidate) => candidate === value.kind);
911
+ const labels = parseLocalizedTexts(value.labels);
912
+ const description = parseLocalizedTexts(value.description);
913
+ const previousSchemaSha256 = value.previousSchemaSha256 === null ? null : parseSha256Hex(value.previousSchemaSha256);
914
+ const revision = Number.isSafeInteger(value.revision) && value.revision > 0 ? value.revision : null;
915
+ const compatibility = value.compatibility === "additive" || value.compatibility === "breaking" ? value.compatibility : null;
916
+ return code !== null && namespace !== null && kind !== undefined && labels !== null && description !== null && (value.previousSchemaSha256 === null || previousSchemaSha256 !== null) && revision !== null && compatibility !== null && revision === 1 === (previousSchemaSha256 === null) && (revision !== 1 || compatibility === "additive") ? {
917
+ body: value.body,
918
+ code,
919
+ compatibility,
920
+ description,
921
+ kind,
922
+ labels,
923
+ namespace,
924
+ previousSchemaSha256,
925
+ revision,
926
+ v: 1
927
+ } : null;
928
+ }
929
+ function createKnowledgeSchemaRevisionV1(input) {
930
+ const parsed = parseSchemaInput(input);
931
+ if (parsed === null)
932
+ throw new TypeError("Invalid schema revision input.");
933
+ return { ...parsed, schemaSha256: canonicalSha256(parsed) };
934
+ }
935
+ function parseKnowledgeSchemaRevisionV1(value) {
936
+ if (!isPlainRecord(value) || !Object.hasOwn(value, "schemaSha256"))
937
+ return null;
938
+ const schemaSha256 = parseSha256Hex(value.schemaSha256);
939
+ const { schemaSha256: _digest, ...input } = value;
940
+ const parsed = parseSchemaInput(input);
941
+ return schemaSha256 !== null && parsed !== null && canonicalSha256(parsed) === schemaSha256 ? { ...parsed, schemaSha256 } : null;
942
+ }
943
+ function knowledgeSchemaRefV1(schema) {
944
+ return {
945
+ code: schema.code,
946
+ namespace: schema.namespace,
947
+ revision: schema.revision,
948
+ schemaSha256: schema.schemaSha256,
949
+ v: 1
950
+ };
951
+ }
952
+ function additiveBodyRetainsPrior(prior, next) {
953
+ return Object.entries(prior).every(([key, value]) => Object.hasOwn(next, key) && canonicalJson(next[key]) === canonicalJson(value));
954
+ }
955
+ function verifyKnowledgeSchemaEvolutionV1(prior, next) {
956
+ if (parseKnowledgeSchemaRevisionV1(prior) === null || parseKnowledgeSchemaRevisionV1(next) === null) {
957
+ return { ok: false, reason: "invalid-schema" };
958
+ }
959
+ if (prior.namespace !== next.namespace || prior.code !== next.code || prior.kind !== next.kind) {
960
+ return { ok: false, reason: "identity-changed" };
961
+ }
962
+ if (next.revision !== prior.revision + 1 || next.previousSchemaSha256 !== prior.schemaSha256) {
963
+ return { ok: false, reason: "chain-broken" };
964
+ }
965
+ if (next.compatibility === "additive" && !additiveBodyRetainsPrior(prior.body, next.body)) {
966
+ return { ok: false, reason: "false-additive-claim" };
967
+ }
968
+ return { ok: true };
969
+ }
970
+ function createKnowledgeVocabularyRevisionV1(input) {
971
+ const namespace = safeCode(input.namespace);
972
+ if (namespace === null || input.v !== 1 || !Number.isSafeInteger(input.revision) || input.revision < 1 || !Array.isArray(input.schemaRefs) || input.schemaRefs.length > 65536) {
973
+ throw new TypeError("Invalid vocabulary revision input.");
974
+ }
975
+ const refs = [];
976
+ for (const candidate of input.schemaRefs) {
977
+ const parsed = parseKnowledgeSchemaRefV1(candidate);
978
+ if (!parsed.ok || parsed.value.namespace !== namespace)
979
+ throw new TypeError("Invalid vocabulary schema reference.");
980
+ refs.push(parsed.value);
981
+ }
982
+ if (!orderedUnique(refs, canonicalJson))
983
+ throw new TypeError("Vocabulary schema references must be ordered and unique.");
984
+ const payload = { namespace, revision: input.revision, schemaRefs: refs, v: 1 };
985
+ return { ...payload, vocabularySha256: canonicalSha256(payload) };
986
+ }
987
+ function parseKnowledgeVocabularyRevisionV1(value) {
988
+ if (!isPlainRecord(value) || !hasExactKeys(value, ["namespace", "revision", "schemaRefs", "v", "vocabularySha256"]))
989
+ return null;
990
+ const digest = parseSha256Hex(value.vocabularySha256);
991
+ try {
992
+ const created = createKnowledgeVocabularyRevisionV1({
993
+ namespace: value.namespace,
994
+ revision: value.revision,
995
+ schemaRefs: value.schemaRefs,
996
+ v: value.v
997
+ });
998
+ return digest !== null && created.vocabularySha256 === digest ? { ...created, vocabularySha256: digest } : null;
999
+ } catch {
1000
+ return null;
1001
+ }
1002
+ }
1003
+
1004
+ // src/contract.ts
1005
+ var manifestPayload = Object.freeze({
1006
+ contractId: OH_CONTRACT_ID_V1,
1007
+ graphFormatVersion: OH_GRAPH_FORMAT_VERSION_V1,
1008
+ ontologyVersion: OH_ONTOLOGY_VERSION_V1,
1009
+ recordKinds: OH_KNOWLEDGE_GRAPH_RECORD_KINDS_V1,
1010
+ schemaFormatVersion: OH_SCHEMA_FORMAT_VERSION_V1,
1011
+ v: 1
1012
+ });
1013
+ var OH_CONTRACT_MANIFEST_V1 = Object.freeze({
1014
+ ...manifestPayload,
1015
+ contractSha256: canonicalSha256(manifestPayload)
1016
+ });
1017
+ function parseOhContractManifestV1(value) {
1018
+ try {
1019
+ return canonicalJson(value) === canonicalJson(OH_CONTRACT_MANIFEST_V1) ? OH_CONTRACT_MANIFEST_V1 : null;
1020
+ } catch {
1021
+ return null;
1022
+ }
1023
+ }
1024
+
1025
+ class OhRecordCodecRegistry {
1026
+ #codecs = new Map;
1027
+ #sealed = false;
1028
+ register(codec) {
1029
+ if (this.#sealed)
1030
+ throw new TypeError("The codec registry is sealed.");
1031
+ if (this.#codecs.has(codec.kind))
1032
+ throw new TypeError(`A codec is already registered for ${codec.kind}.`);
1033
+ this.#codecs.set(codec.kind, Object.freeze({ kind: codec.kind, parse: codec.parse }));
1034
+ return this;
1035
+ }
1036
+ parse(kind, value) {
1037
+ const codec = this.#codecs.get(kind);
1038
+ if (codec !== undefined)
1039
+ return codec.parse(value);
1040
+ try {
1041
+ canonicalJson(value);
1042
+ return value;
1043
+ } catch {
1044
+ return null;
1045
+ }
1046
+ }
1047
+ has(kind) {
1048
+ return this.#codecs.has(kind);
1049
+ }
1050
+ parseRequired(kind, value) {
1051
+ const codec = this.#codecs.get(kind);
1052
+ if (codec === undefined)
1053
+ return null;
1054
+ try {
1055
+ const parsed = codec.parse(value);
1056
+ if (parsed === null)
1057
+ return null;
1058
+ canonicalJson(parsed);
1059
+ return parsed;
1060
+ } catch {
1061
+ return null;
1062
+ }
1063
+ }
1064
+ seal() {
1065
+ this.#sealed = true;
1066
+ return this;
1067
+ }
1068
+ get sealed() {
1069
+ return this.#sealed;
1070
+ }
1071
+ }
1072
+
1073
+ // src/operation.ts
1074
+ var OH_OPERATION_MAX_BYTES_V1 = 64 * 1024 * 1024;
1075
+ function parsePayload(value) {
1076
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
1077
+ "actorId",
1078
+ "changes",
1079
+ "contractId",
1080
+ "graphRevisionSha256",
1081
+ "instant",
1082
+ "operationId",
1083
+ "parentOperationSha256",
1084
+ "recordsSha256",
1085
+ "sequence",
1086
+ "spaceId",
1087
+ "v"
1088
+ ]) || value.v !== 1 || value.contractId !== OH_CONTRACT_ID_V1 || !Array.isArray(value.changes))
1089
+ return null;
1090
+ const actorId = safeCode(value.actorId);
1091
+ const operationId = safeCode(value.operationId);
1092
+ const spaceId = safeCode(value.spaceId);
1093
+ const graphRevisionSha256 = parseSha256Hex(value.graphRevisionSha256);
1094
+ const parentOperationSha256 = value.parentOperationSha256 === null ? null : parseSha256Hex(value.parentOperationSha256);
1095
+ const recordsSha256 = parseSha256Hex(value.recordsSha256);
1096
+ const instant = parseCanonicalInstantV1(value.instant);
1097
+ const sequence = Number.isSafeInteger(value.sequence) && value.sequence > 0 ? value.sequence : null;
1098
+ let changes;
1099
+ try {
1100
+ changes = canonicalKnowledgeGraphChangesV1(value.changes);
1101
+ } catch {
1102
+ return null;
1103
+ }
1104
+ if (changes.length === 0 || changes.length > OH_GRAPH_LIMITS_V1.changesPerOperation)
1105
+ return null;
1106
+ return actorId !== null && operationId !== null && spaceId !== null && graphRevisionSha256 !== null && recordsSha256 !== null && instant !== null && sequence !== null && (value.parentOperationSha256 === null || parentOperationSha256 !== null) && sequence === 1 === (parentOperationSha256 === null) ? {
1107
+ actorId,
1108
+ changes,
1109
+ contractId: OH_CONTRACT_ID_V1,
1110
+ graphRevisionSha256,
1111
+ instant,
1112
+ operationId,
1113
+ parentOperationSha256,
1114
+ recordsSha256,
1115
+ sequence,
1116
+ spaceId,
1117
+ v: 1
1118
+ } : null;
1119
+ }
1120
+ function createOhOperationV1(input) {
1121
+ const payload = parsePayload(input);
1122
+ if (payload === null)
1123
+ throw new TypeError("Invalid Oh operation payload.");
1124
+ const operation = { ...payload, operationSha256: canonicalSha256(payload) };
1125
+ if (Buffer.byteLength(canonicalJson(operation), "utf8") > OH_OPERATION_MAX_BYTES_V1) {
1126
+ throw new RangeError("Oh operation exceeds its canonical byte limit.");
1127
+ }
1128
+ return operation;
1129
+ }
1130
+ function parseOhOperationV1(value) {
1131
+ if (!isPlainRecord(value) || !Object.hasOwn(value, "operationSha256"))
1132
+ return null;
1133
+ const operationSha256 = parseSha256Hex(value.operationSha256);
1134
+ const { operationSha256: _digest, ...input } = value;
1135
+ const payload = parsePayload(input);
1136
+ return operationSha256 !== null && payload !== null && Buffer.byteLength(canonicalJson({ ...payload, operationSha256 }), "utf8") <= OH_OPERATION_MAX_BYTES_V1 && canonicalSha256(payload) === operationSha256 ? { ...payload, operationSha256 } : null;
1137
+ }
1138
+
1139
+ // src/sync.ts
1140
+ var OH_SYNC_PROTOCOL_V1 = "oh.sync.v1";
1141
+ function createOhSyncBundleV1(spaceId, operations) {
1142
+ const parsedSpaceId = safeCode(spaceId);
1143
+ if (parsedSpaceId === null || operations.length > 1000)
1144
+ throw new TypeError("Invalid sync bundle.");
1145
+ let priorSequence = null;
1146
+ let priorSha256 = null;
1147
+ const parsed = [];
1148
+ for (const candidate of operations) {
1149
+ const operation = parseOhOperationV1(candidate);
1150
+ if (operation === null || operation.spaceId !== parsedSpaceId || priorSequence !== null && operation.sequence !== priorSequence + 1 || priorSequence !== null && operation.parentOperationSha256 !== priorSha256) {
1151
+ throw new TypeError("Sync operations must form one ordered chain.");
1152
+ }
1153
+ parsed.push(operation);
1154
+ priorSequence = operation.sequence;
1155
+ priorSha256 = operation.operationSha256;
1156
+ }
1157
+ const payload = {
1158
+ contractSha256: OH_CONTRACT_MANIFEST_V1.contractSha256,
1159
+ operations: parsed,
1160
+ protocol: OH_SYNC_PROTOCOL_V1,
1161
+ spaceId: parsedSpaceId,
1162
+ v: 1
1163
+ };
1164
+ return { ...payload, bundleSha256: canonicalSha256(payload) };
1165
+ }
1166
+ function parseOhSyncBundleV1(value) {
1167
+ if (!isPlainRecord(value) || !hasExactKeys(value, ["bundleSha256", "contractSha256", "operations", "protocol", "spaceId", "v"]) || value.protocol !== OH_SYNC_PROTOCOL_V1 || value.v !== 1 || !Array.isArray(value.operations))
1168
+ return null;
1169
+ const bundleSha256 = parseSha256Hex(value.bundleSha256);
1170
+ const contractSha256 = parseSha256Hex(value.contractSha256);
1171
+ if (bundleSha256 === null || contractSha256 !== OH_CONTRACT_MANIFEST_V1.contractSha256)
1172
+ return null;
1173
+ try {
1174
+ const created = createOhSyncBundleV1(value.spaceId, value.operations);
1175
+ return created.bundleSha256 === bundleSha256 ? { ...created, bundleSha256 } : null;
1176
+ } catch {
1177
+ return null;
1178
+ }
1179
+ }
1180
+ async function synchronizeOhStoreV1(store, transport, options = {}) {
1181
+ const batchSize = options.batchSize ?? 100;
1182
+ const maximumRounds = options.maximumRounds ?? 100;
1183
+ const remoteId = safeCode(options.remoteId ?? "default");
1184
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1000 || !Number.isSafeInteger(maximumRounds) || maximumRounds < 1 || maximumRounds > 1e4 || remoteId === null)
1185
+ throw new TypeError("Invalid sync options.");
1186
+ await transport.handshake(OH_CONTRACT_MANIFEST_V1);
1187
+ let pulled = 0;
1188
+ let pushed = 0;
1189
+ for (let round = 1;round <= maximumRounds; round += 1) {
1190
+ const local = store.head();
1191
+ const remote = await transport.head(store.spaceId);
1192
+ if (local.sequence === remote.sequence) {
1193
+ if (local.operationSha256 !== remote.operationSha256) {
1194
+ throw new Error("Sync conflict: equal sequence numbers have different heads.");
1195
+ }
1196
+ store.updateSyncState(remoteId, {
1197
+ pulledSequence: local.sequence,
1198
+ pushedSequence: local.sequence,
1199
+ remoteHeadSha256: remote.operationSha256
1200
+ });
1201
+ return { head: remote, pulled, pushed, rounds: round, v: 1 };
1202
+ }
1203
+ if (local.sequence < remote.sequence) {
1204
+ const bundle = parseOhSyncBundleV1(await transport.pull(store.spaceId, local.sequence, batchSize));
1205
+ if (bundle === null || bundle.operations.length === 0 || bundle.operations[0]?.sequence !== local.sequence + 1 || bundle.operations[0]?.parentOperationSha256 !== local.operationSha256) {
1206
+ throw new Error("Sync conflict: remote history does not extend the local head.");
1207
+ }
1208
+ for (const operation of bundle.operations) {
1209
+ store.importOperation(operation);
1210
+ pulled += 1;
1211
+ }
1212
+ } else {
1213
+ const operations = store.exportOperations(remote.sequence, batchSize);
1214
+ if (operations.length === 0 || operations[0]?.sequence !== remote.sequence + 1 || operations[0]?.parentOperationSha256 !== remote.operationSha256) {
1215
+ throw new Error("Sync conflict: local history does not extend the remote head.");
1216
+ }
1217
+ const head = await transport.push(createOhSyncBundleV1(store.spaceId, operations));
1218
+ if (head.sequence !== operations.at(-1)?.sequence || head.operationSha256 !== operations.at(-1)?.operationSha256) {
1219
+ throw new Error("The sync transport acknowledged a different head.");
1220
+ }
1221
+ pushed += operations.length;
1222
+ }
1223
+ }
1224
+ throw new Error("Sync did not settle within maximumRounds.");
1225
+ }
1226
+ function rowValue(row, key, index) {
1227
+ return Array.isArray(row) ? row[index] : row[key];
1228
+ }
1229
+ function createLibSqlOperationSyncTransportV1(client) {
1230
+ let ready = null;
1231
+ const setup = async (manifest) => {
1232
+ if (parseOhContractManifestV1(manifest) === null)
1233
+ throw new Error("Unsupported contract manifest.");
1234
+ await client.batch([
1235
+ { sql: `CREATE TABLE IF NOT EXISTS oh_sync_contracts (
1236
+ contract_id TEXT PRIMARY KEY, contract_sha256 TEXT NOT NULL, manifest_json TEXT NOT NULL
1237
+ ) STRICT` },
1238
+ { sql: `CREATE TABLE IF NOT EXISTS oh_sync_operations (
1239
+ space_id TEXT NOT NULL, sequence INTEGER NOT NULL, operation_sha256 TEXT NOT NULL UNIQUE,
1240
+ operation_json TEXT NOT NULL, PRIMARY KEY(space_id, sequence)
1241
+ ) STRICT` },
1242
+ {
1243
+ sql: "INSERT INTO oh_sync_contracts(contract_id, contract_sha256, manifest_json) VALUES (?, ?, ?) ON CONFLICT(contract_id) DO NOTHING",
1244
+ args: [manifest.contractId, manifest.contractSha256, canonicalJson(manifest)]
1245
+ }
1246
+ ], "write");
1247
+ const result = await client.execute({
1248
+ sql: "SELECT contract_sha256, manifest_json FROM oh_sync_contracts WHERE contract_id = ?",
1249
+ args: [manifest.contractId]
1250
+ });
1251
+ const row = result.rows[0];
1252
+ if (row === undefined || rowValue(row, "contract_sha256", 0) !== manifest.contractSha256 || rowValue(row, "manifest_json", 1) !== canonicalJson(manifest)) {
1253
+ throw new Error("Remote contract manifest mismatch.");
1254
+ }
1255
+ };
1256
+ const ensure = (manifest = OH_CONTRACT_MANIFEST_V1) => {
1257
+ ready ??= setup(manifest).catch((error) => {
1258
+ ready = null;
1259
+ throw error;
1260
+ });
1261
+ return ready;
1262
+ };
1263
+ const head = async (spaceId) => {
1264
+ await ensure();
1265
+ const result = await client.execute({ sql: `SELECT sequence, operation_sha256 FROM oh_sync_operations
1266
+ WHERE space_id = ? ORDER BY sequence DESC LIMIT 1`, args: [spaceId] });
1267
+ const row = result.rows[0];
1268
+ if (row === undefined)
1269
+ return { operationSha256: null, sequence: 0, v: 1 };
1270
+ const sequence = Number(rowValue(row, "sequence", 0));
1271
+ const operationSha256 = parseSha256Hex(rowValue(row, "operation_sha256", 1));
1272
+ if (!Number.isSafeInteger(sequence) || sequence < 1 || operationSha256 === null)
1273
+ throw new Error("Invalid remote head.");
1274
+ return { operationSha256, sequence, v: 1 };
1275
+ };
1276
+ return {
1277
+ handshake: async (manifest) => {
1278
+ const parsed = parseOhContractManifestV1(manifest);
1279
+ if (parsed === null)
1280
+ throw new Error("Unsupported contract manifest.");
1281
+ await ensure(parsed);
1282
+ },
1283
+ head,
1284
+ pull: async (spaceId, afterSequence, limit) => {
1285
+ await ensure();
1286
+ const result = await client.execute({ sql: `SELECT operation_json FROM oh_sync_operations
1287
+ WHERE space_id = ? AND sequence > ? ORDER BY sequence LIMIT ?`, args: [spaceId, afterSequence, limit] });
1288
+ const operations = result.rows.map((row) => {
1289
+ const json = rowValue(row, "operation_json", 0);
1290
+ if (typeof json !== "string")
1291
+ throw new Error("Invalid remote operation JSON.");
1292
+ const operation = parseOhOperationV1(JSON.parse(json));
1293
+ if (operation === null || canonicalJson(operation) !== json)
1294
+ throw new Error("Invalid remote operation.");
1295
+ return operation;
1296
+ });
1297
+ return createOhSyncBundleV1(spaceId, operations);
1298
+ },
1299
+ push: async (value) => {
1300
+ await ensure();
1301
+ const bundle = parseOhSyncBundleV1(value);
1302
+ if (bundle === null)
1303
+ throw new Error("Invalid outgoing sync bundle.");
1304
+ if (bundle.operations.length === 0)
1305
+ return head(bundle.spaceId);
1306
+ const remote = await head(bundle.spaceId);
1307
+ const first = bundle.operations[0];
1308
+ const last = bundle.operations.at(-1);
1309
+ if (remote.sequence === last.sequence && remote.operationSha256 === last.operationSha256)
1310
+ return remote;
1311
+ if (first.sequence !== remote.sequence + 1 || first.parentOperationSha256 !== remote.operationSha256) {
1312
+ throw new Error("Sync conflict: pushed history does not extend the remote head.");
1313
+ }
1314
+ await client.batch(bundle.operations.map((operation) => ({
1315
+ sql: "INSERT INTO oh_sync_operations(space_id, sequence, operation_sha256, operation_json) VALUES (?, ?, ?, ?)",
1316
+ args: [bundle.spaceId, operation.sequence, operation.operationSha256, canonicalJson(operation)]
1317
+ })), "write");
1318
+ return { operationSha256: last.operationSha256, sequence: last.sequence, v: 1 };
1319
+ }
1320
+ };
1321
+ }
1322
+ // src/store.ts
1323
+ class OhConflictError extends Error {
1324
+ constructor(message) {
1325
+ super(message);
1326
+ this.name = "OhConflictError";
1327
+ }
1328
+ }
1329
+
1330
+ class OhIntegrityError extends Error {
1331
+ constructor(message) {
1332
+ super(message);
1333
+ this.name = "OhIntegrityError";
1334
+ }
1335
+ }
1336
+
1337
+ class OhDependencyError extends Error {
1338
+ constructor(message) {
1339
+ super(message);
1340
+ this.name = "OhDependencyError";
1341
+ }
1342
+ }
1343
+
1344
+ class OhProfileError extends Error {
1345
+ constructor(message) {
1346
+ super(message);
1347
+ this.name = "OhProfileError";
1348
+ }
1349
+ }
1350
+ var OH_CANONICAL_STORE_PROFILE_V1 = createOhStoreProfileV1({
1351
+ applicationProfileSha256: null,
1352
+ capabilities: {
1353
+ changesSince: true,
1354
+ dependencyClosureExport: true,
1355
+ exactSnapshots: true,
1356
+ operationReplication: true,
1357
+ semanticBundleCommit: true,
1358
+ v: 1,
1359
+ wholeSpacePurge: false
1360
+ },
1361
+ profileId: "oh.store.canonical.v1",
1362
+ profileKind: "canonical",
1363
+ v: 1
1364
+ });
1365
+ var OH_WORKING_STORE_PROFILE_V1 = createOhStoreProfileV1({
1366
+ applicationProfileSha256: null,
1367
+ capabilities: {
1368
+ changesSince: true,
1369
+ dependencyClosureExport: true,
1370
+ exactSnapshots: true,
1371
+ operationReplication: false,
1372
+ semanticBundleCommit: true,
1373
+ v: 1,
1374
+ wholeSpacePurge: true
1375
+ },
1376
+ profileId: "oh.store.working.v1",
1377
+ profileKind: "working",
1378
+ v: 1
1379
+ });
1380
+ var OH_DEPENDENCY_CLOSURE_LIMITS_V1 = Object.freeze({
1381
+ bytes: 64 * 1024 * 1024,
1382
+ records: 8192,
1383
+ roots: 1024
1384
+ });
1385
+
1386
+ class OhPurgedSpaceError extends Error {
1387
+ receipt;
1388
+ constructor(receipt) {
1389
+ super(`Oh space ${receipt.spaceId} was purged at ${receipt.purgedAt}.`);
1390
+ this.name = "OhPurgedSpaceError";
1391
+ this.receipt = receipt;
1392
+ }
1393
+ }
1394
+ var EMPTY_RECORDS_SHA256 = canonicalSha256([]);
1395
+ function emptyOhHeadV1() {
1396
+ return {
1397
+ generation: 0,
1398
+ graphRevisionSha256: null,
1399
+ operationSha256: null,
1400
+ recordsSha256: EMPTY_RECORDS_SHA256,
1401
+ sequence: 0,
1402
+ v: 1
1403
+ };
1404
+ }
1405
+ function parseOhHeadV1(value) {
1406
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
1407
+ "generation",
1408
+ "graphRevisionSha256",
1409
+ "operationSha256",
1410
+ "recordsSha256",
1411
+ "sequence",
1412
+ "v"
1413
+ ]) || value.v !== 1)
1414
+ return null;
1415
+ const graphRevisionSha256 = value.graphRevisionSha256 === null ? null : parseSha256Hex(value.graphRevisionSha256);
1416
+ const operationSha256 = value.operationSha256 === null ? null : parseSha256Hex(value.operationSha256);
1417
+ const recordsSha256 = parseSha256Hex(value.recordsSha256);
1418
+ const generation = Number.isSafeInteger(value.generation) && value.generation >= 0 ? value.generation : null;
1419
+ const sequence = Number.isSafeInteger(value.sequence) && value.sequence >= 0 ? value.sequence : null;
1420
+ return generation !== null && sequence !== null && generation === sequence && recordsSha256 !== null && (value.graphRevisionSha256 === null || graphRevisionSha256 !== null) && (value.operationSha256 === null || operationSha256 !== null) && sequence === 0 === (operationSha256 === null) && sequence === 0 === (graphRevisionSha256 === null) ? { generation, graphRevisionSha256, operationSha256, recordsSha256, sequence, v: 1 } : null;
1421
+ }
1422
+ function parseOhHeadRefV1(value) {
1423
+ const complete = parseOhHeadV1(value);
1424
+ if (complete !== null) {
1425
+ return { operationSha256: complete.operationSha256, sequence: complete.sequence };
1426
+ }
1427
+ if (!isPlainRecord(value) || !hasExactKeys(value, ["operationSha256", "sequence"]))
1428
+ return null;
1429
+ const operationSha256 = value.operationSha256 === null ? null : parseSha256Hex(value.operationSha256);
1430
+ const sequence = Number.isSafeInteger(value.sequence) && value.sequence >= 0 ? value.sequence : null;
1431
+ return sequence !== null && (value.operationSha256 === null || operationSha256 !== null) && sequence === 0 === (operationSha256 === null) ? { operationSha256, sequence } : null;
1432
+ }
1433
+ function parseCapabilities(value) {
1434
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
1435
+ "changesSince",
1436
+ "dependencyClosureExport",
1437
+ "exactSnapshots",
1438
+ "operationReplication",
1439
+ "semanticBundleCommit",
1440
+ "v",
1441
+ "wholeSpacePurge"
1442
+ ]) || value.changesSince !== true || value.dependencyClosureExport !== true || value.exactSnapshots !== true || typeof value.operationReplication !== "boolean" || value.semanticBundleCommit !== true || value.v !== 1 || typeof value.wholeSpacePurge !== "boolean")
1443
+ return null;
1444
+ return {
1445
+ changesSince: true,
1446
+ dependencyClosureExport: true,
1447
+ exactSnapshots: true,
1448
+ operationReplication: value.operationReplication,
1449
+ semanticBundleCommit: true,
1450
+ v: 1,
1451
+ wholeSpacePurge: value.wholeSpacePurge
1452
+ };
1453
+ }
1454
+ function createOhStoreProfileV1(input) {
1455
+ if (!isPlainRecord(input) || !hasExactKeys(input, [
1456
+ "applicationProfileSha256",
1457
+ "capabilities",
1458
+ "profileId",
1459
+ "profileKind",
1460
+ "v"
1461
+ ]) || input.v !== 1)
1462
+ throw new TypeError("Invalid Oh store profile input.");
1463
+ const profileId = safeCode(input.profileId);
1464
+ const applicationProfileSha256 = input.applicationProfileSha256 === null ? null : parseSha256Hex(input.applicationProfileSha256);
1465
+ const capabilities = parseCapabilities(input.capabilities);
1466
+ if (profileId === null || capabilities === null || input.applicationProfileSha256 !== null && applicationProfileSha256 === null || input.profileKind !== "canonical" && input.profileKind !== "working") {
1467
+ throw new TypeError("Invalid Oh store profile input.");
1468
+ }
1469
+ if (input.profileKind === "working" && (capabilities.operationReplication || !capabilities.wholeSpacePurge)) {
1470
+ throw new OhProfileError("A working profile must disable operation replication and permit whole-space purge.");
1471
+ }
1472
+ if (input.profileKind === "canonical" && capabilities.wholeSpacePurge) {
1473
+ throw new OhProfileError("A canonical profile cannot permit whole-space purge.");
1474
+ }
1475
+ const payload = {
1476
+ applicationProfileSha256,
1477
+ capabilities: Object.freeze(capabilities),
1478
+ profileId,
1479
+ profileKind: input.profileKind,
1480
+ v: 1
1481
+ };
1482
+ return Object.freeze({ ...payload, profileSha256: canonicalSha256(payload) });
1483
+ }
1484
+ function parseOhStoreProfileV1(value) {
1485
+ if (!isPlainRecord(value) || !Object.hasOwn(value, "profileSha256"))
1486
+ return null;
1487
+ const digest = parseSha256Hex(value.profileSha256);
1488
+ const { profileSha256: _profileSha256, ...input } = value;
1489
+ try {
1490
+ const created = createOhStoreProfileV1(input);
1491
+ return digest !== null && created.profileSha256 === digest ? created : null;
1492
+ } catch {
1493
+ return null;
1494
+ }
1495
+ }
1496
+ function createOhStoreBindingV1(input) {
1497
+ const profile = parseOhStoreProfileV1(input.profile);
1498
+ const realmId = safeCode(input.realmId);
1499
+ const spaceId = safeCode(input.spaceId);
1500
+ if (input.v !== 1 || profile === null || realmId === null || spaceId === null) {
1501
+ throw new TypeError("Invalid Oh store binding input.");
1502
+ }
1503
+ const payload = {
1504
+ contractSha256: OH_CONTRACT_MANIFEST_V1.contractSha256,
1505
+ profile,
1506
+ realmId,
1507
+ spaceId,
1508
+ v: 1
1509
+ };
1510
+ return Object.freeze({ ...payload, bindingSha256: canonicalSha256(payload) });
1511
+ }
1512
+ function parseOhStoreBindingV1(value) {
1513
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
1514
+ "bindingSha256",
1515
+ "contractSha256",
1516
+ "profile",
1517
+ "realmId",
1518
+ "spaceId",
1519
+ "v"
1520
+ ]) || value.v !== 1 || value.contractSha256 !== OH_CONTRACT_MANIFEST_V1.contractSha256)
1521
+ return null;
1522
+ const bindingSha256 = parseSha256Hex(value.bindingSha256);
1523
+ const profile = parseOhStoreProfileV1(value.profile);
1524
+ try {
1525
+ if (bindingSha256 === null || profile === null)
1526
+ return null;
1527
+ const created = createOhStoreBindingV1({
1528
+ profile,
1529
+ realmId: value.realmId,
1530
+ spaceId: value.spaceId,
1531
+ v: 1
1532
+ });
1533
+ return created.bindingSha256 === bindingSha256 ? created : null;
1534
+ } catch {
1535
+ return null;
1536
+ }
1537
+ }
1538
+ function sortedRecords(records) {
1539
+ return [...records].sort((left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0);
1540
+ }
1541
+ function verifyDependencies(records) {
1542
+ for (const record of records.values()) {
1543
+ for (const dependency of record.dependencies) {
1544
+ if (!records.has(dependency))
1545
+ throw new OhDependencyError(`Missing dependency ${dependency} for ${record.key}.`);
1546
+ }
1547
+ }
1548
+ }
1549
+ function replayOhOperationsV1(spaceId, values, maximumRecords = OH_GRAPH_LIMITS_V1.recordsPerSnapshot) {
1550
+ const parsedSpaceId = safeCode(spaceId);
1551
+ if (parsedSpaceId === null || !Number.isSafeInteger(maximumRecords) || maximumRecords < 1 || maximumRecords > OH_GRAPH_LIMITS_V1.recordsPerSnapshot) {
1552
+ throw new TypeError("Invalid operation replay input.");
1553
+ }
1554
+ const records = new Map;
1555
+ const operationIds = new Set;
1556
+ let head = emptyOhHeadV1();
1557
+ for (const value of values) {
1558
+ const operation = parseOhOperationV1(value);
1559
+ if (operation === null || operation.spaceId !== parsedSpaceId || operation.sequence !== head.sequence + 1 || operation.parentOperationSha256 !== head.operationSha256 || operationIds.has(operation.operationId)) {
1560
+ throw new OhIntegrityError("Operation replay chain is broken.");
1561
+ }
1562
+ operationIds.add(operation.operationId);
1563
+ for (const change of operation.changes) {
1564
+ if (change.kind === "put")
1565
+ records.set(change.record.key, change.record);
1566
+ else {
1567
+ const prior = records.get(change.key);
1568
+ if (prior?.recordSha256 !== change.priorSha256) {
1569
+ throw new OhIntegrityError("Replay tombstone does not match its prior record.");
1570
+ }
1571
+ records.delete(change.key);
1572
+ }
1573
+ }
1574
+ if (records.size > maximumRecords)
1575
+ throw new RangeError("Operation replay exceeds its record bound.");
1576
+ verifyDependencies(records);
1577
+ const refs = sortedRecords(records.values()).map(knowledgeGraphRecordRefV1);
1578
+ const recordsSha256 = canonicalSha256(refs);
1579
+ const graphRevisionSha256 = graphRevisionSha256V1({
1580
+ changes: operation.changes,
1581
+ operationId: operation.operationId,
1582
+ parentGraphRevisionSha256: head.graphRevisionSha256,
1583
+ recordsSha256,
1584
+ revision: operation.sequence
1585
+ });
1586
+ if (recordsSha256 !== operation.recordsSha256 || graphRevisionSha256 !== operation.graphRevisionSha256) {
1587
+ throw new OhIntegrityError("Replay does not reproduce an operation head.");
1588
+ }
1589
+ head = {
1590
+ generation: operation.sequence,
1591
+ graphRevisionSha256,
1592
+ operationSha256: operation.operationSha256,
1593
+ recordsSha256,
1594
+ sequence: operation.sequence,
1595
+ v: 1
1596
+ };
1597
+ }
1598
+ return { head, records: sortedRecords(records.values()), v: 1 };
1599
+ }
1600
+ function transitionOhSnapshotV1(input) {
1601
+ const actorId = safeCode(input.actorId);
1602
+ const operationId = safeCode(input.operationId);
1603
+ const spaceId = safeCode(input.spaceId);
1604
+ const instant = parseCanonicalInstantV1(input.instant);
1605
+ const changes = canonicalKnowledgeGraphChangesV1(input.changes);
1606
+ if (actorId === null || operationId === null || spaceId === null || instant === null || changes.length === 0 || changes.length > OH_GRAPH_LIMITS_V1.changesPerOperation) {
1607
+ throw new TypeError("Invalid graph transition input.");
1608
+ }
1609
+ const head = parseOhHeadV1(input.snapshot.head);
1610
+ if (input.snapshot.v !== 1 || head === null || !Array.isArray(input.snapshot.records)) {
1611
+ throw new OhIntegrityError("The transition snapshot is invalid.");
1612
+ }
1613
+ const records = new Map;
1614
+ for (const value of input.snapshot.records) {
1615
+ const record = parseKnowledgeGraphRecordV1(value);
1616
+ if (record === null || records.has(record.key)) {
1617
+ throw new OhIntegrityError("The transition snapshot contains an invalid record.");
1618
+ }
1619
+ records.set(record.key, record);
1620
+ }
1621
+ verifyDependencies(records);
1622
+ const priorRecordsSha256 = canonicalSha256(sortedRecords(records.values()).map(knowledgeGraphRecordRefV1));
1623
+ if (priorRecordsSha256 !== head.recordsSha256) {
1624
+ throw new OhIntegrityError("The transition snapshot does not reproduce its head.");
1625
+ }
1626
+ for (const change of changes) {
1627
+ if (change.kind === "put")
1628
+ records.set(change.record.key, change.record);
1629
+ else {
1630
+ const prior = records.get(change.key);
1631
+ if (prior === undefined || prior.recordSha256 !== change.priorSha256) {
1632
+ throw new OhConflictError(`The prior digest for ${change.key} does not match the snapshot.`);
1633
+ }
1634
+ records.delete(change.key);
1635
+ }
1636
+ }
1637
+ if (records.size > OH_GRAPH_LIMITS_V1.recordsPerSnapshot) {
1638
+ throw new RangeError("Graph transition exceeds its record snapshot limit.");
1639
+ }
1640
+ verifyDependencies(records);
1641
+ const nextRecords = sortedRecords(records.values());
1642
+ const recordsSha256 = canonicalSha256(nextRecords.map(knowledgeGraphRecordRefV1));
1643
+ const graphRevisionSha256 = graphRevisionSha256V1({
1644
+ changes,
1645
+ operationId,
1646
+ parentGraphRevisionSha256: head.graphRevisionSha256,
1647
+ recordsSha256,
1648
+ revision: head.sequence + 1
1649
+ });
1650
+ const operation = createOhOperationV1({
1651
+ actorId,
1652
+ changes,
1653
+ contractId: OH_CONTRACT_MANIFEST_V1.contractId,
1654
+ graphRevisionSha256,
1655
+ instant,
1656
+ operationId,
1657
+ parentOperationSha256: head.operationSha256,
1658
+ recordsSha256,
1659
+ sequence: head.sequence + 1,
1660
+ spaceId,
1661
+ v: 1
1662
+ });
1663
+ const nextHead = {
1664
+ generation: operation.sequence,
1665
+ graphRevisionSha256,
1666
+ operationSha256: operation.operationSha256,
1667
+ recordsSha256,
1668
+ sequence: operation.sequence,
1669
+ v: 1
1670
+ };
1671
+ return { operation, snapshot: { head: nextHead, records: nextRecords, v: 1 } };
1672
+ }
1673
+ function normalizeRoots(values) {
1674
+ if (!Array.isArray(values) || values.length < 1 || values.length > OH_DEPENDENCY_CLOSURE_LIMITS_V1.roots) {
1675
+ throw new RangeError(`A dependency closure needs 1 through ${OH_DEPENDENCY_CLOSURE_LIMITS_V1.roots} roots.`);
1676
+ }
1677
+ const roots = values.map((value) => safeCode(value, 512));
1678
+ if (roots.some((value) => value === null))
1679
+ throw new TypeError("Invalid dependency closure root.");
1680
+ const sorted = [...roots].sort();
1681
+ if (sorted.some((value, index) => index > 0 && sorted[index - 1] === value)) {
1682
+ throw new TypeError("Dependency closure roots must be unique.");
1683
+ }
1684
+ return sorted;
1685
+ }
1686
+ function closureRecords(available, roots, maximumRecords, maximumBytes = OH_DEPENDENCY_CLOSURE_LIMITS_V1.bytes - 64 * 1024) {
1687
+ const selected = new Map;
1688
+ const pending = [...roots];
1689
+ let selectedBytes = 0;
1690
+ while (pending.length > 0) {
1691
+ const key = pending.pop();
1692
+ if (selected.has(key))
1693
+ continue;
1694
+ const record = available.get(key);
1695
+ if (record === undefined)
1696
+ throw new OhDependencyError(`Dependency closure record ${key} is missing.`);
1697
+ selectedBytes += Buffer.byteLength(canonicalJson(record), "utf8") + 1;
1698
+ if (selectedBytes > maximumBytes)
1699
+ throw new RangeError("Dependency closure exceeds its canonical byte bound.");
1700
+ selected.set(key, record);
1701
+ if (selected.size > maximumRecords)
1702
+ throw new RangeError("Dependency closure exceeds its record bound.");
1703
+ pending.push(...record.dependencies);
1704
+ }
1705
+ return sortedRecords(selected.values());
1706
+ }
1707
+ function createOhDependencyClosureV1(input) {
1708
+ const binding = parseOhStoreBindingV1(input.binding);
1709
+ const head = parseOhHeadV1(input.snapshot.head);
1710
+ const maximumRecords = input.maximumRecords ?? OH_DEPENDENCY_CLOSURE_LIMITS_V1.records;
1711
+ if (binding === null || head === null || !Number.isSafeInteger(maximumRecords) || maximumRecords < 1 || maximumRecords > OH_DEPENDENCY_CLOSURE_LIMITS_V1.records) {
1712
+ throw new TypeError("Invalid dependency closure input.");
1713
+ }
1714
+ const roots = normalizeRoots(input.roots);
1715
+ const available = new Map;
1716
+ for (const value of input.snapshot.records) {
1717
+ const record = parseKnowledgeGraphRecordV1(value);
1718
+ if (record === null || available.has(record.key))
1719
+ throw new OhIntegrityError("Snapshot contains an invalid record.");
1720
+ available.set(record.key, record);
1721
+ }
1722
+ const recordsSha256 = canonicalSha256(sortedRecords(available.values()).map(knowledgeGraphRecordRefV1));
1723
+ if (recordsSha256 !== head.recordsSha256)
1724
+ throw new OhIntegrityError("Snapshot records do not reproduce its head.");
1725
+ const records = closureRecords(available, roots, maximumRecords);
1726
+ const payload = { binding, head, records, roots, v: 1 };
1727
+ const closure = { ...payload, closureSha256: canonicalSha256(payload) };
1728
+ if (Buffer.byteLength(canonicalJson(closure), "utf8") > OH_DEPENDENCY_CLOSURE_LIMITS_V1.bytes) {
1729
+ throw new RangeError("Dependency closure exceeds its canonical byte bound.");
1730
+ }
1731
+ return Object.freeze(closure);
1732
+ }
1733
+ function parseOhDependencyClosureV1(value) {
1734
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
1735
+ "binding",
1736
+ "closureSha256",
1737
+ "head",
1738
+ "records",
1739
+ "roots",
1740
+ "v"
1741
+ ]) || value.v !== 1 || !Array.isArray(value.records) || !Array.isArray(value.roots) || value.records.length > OH_DEPENDENCY_CLOSURE_LIMITS_V1.records)
1742
+ return null;
1743
+ const binding = parseOhStoreBindingV1(value.binding);
1744
+ const head = parseOhHeadV1(value.head);
1745
+ const closureSha256 = parseSha256Hex(value.closureSha256);
1746
+ if (binding === null || head === null || closureSha256 === null)
1747
+ return null;
1748
+ const records = new Map;
1749
+ for (const item of value.records) {
1750
+ const record = parseKnowledgeGraphRecordV1(item);
1751
+ if (record === null || records.has(record.key))
1752
+ return null;
1753
+ records.set(record.key, record);
1754
+ }
1755
+ try {
1756
+ const roots = normalizeRoots(value.roots);
1757
+ if (canonicalJson(roots) !== canonicalJson(value.roots))
1758
+ return null;
1759
+ const exact = closureRecords(records, roots, OH_DEPENDENCY_CLOSURE_LIMITS_V1.records);
1760
+ if (canonicalJson(exact) !== canonicalJson(value.records))
1761
+ return null;
1762
+ const payload = { binding, head, records: exact, roots, v: 1 };
1763
+ const parsed = { ...payload, closureSha256 };
1764
+ return canonicalSha256(payload) === closureSha256 && Buffer.byteLength(canonicalJson(parsed), "utf8") <= OH_DEPENDENCY_CLOSURE_LIMITS_V1.bytes ? Object.freeze(parsed) : null;
1765
+ } catch {
1766
+ return null;
1767
+ }
1768
+ }
1769
+ function verifyOhDependencyClosureV1(value) {
1770
+ const closure = parseOhDependencyClosureV1(value);
1771
+ return closure === null ? { ok: false, reason: "invalid-closure" } : { closure, ok: true };
1772
+ }
1773
+ function verifyOhDependencyClosureAgainstV1(value, expected) {
1774
+ const binding = parseOhStoreBindingV1(expected.binding);
1775
+ const head = parseOhHeadV1(expected.head);
1776
+ if (binding === null || head === null)
1777
+ return { ok: false, reason: "invalid-expectation" };
1778
+ const closure = parseOhDependencyClosureV1(value);
1779
+ if (closure === null)
1780
+ return { ok: false, reason: "invalid-closure" };
1781
+ if (closure.binding.bindingSha256 !== binding.bindingSha256)
1782
+ return { ok: false, reason: "binding-mismatch" };
1783
+ if (canonicalJson(closure.head) !== canonicalJson(head))
1784
+ return { ok: false, reason: "head-mismatch" };
1785
+ return { closure, ok: true, verification: "expected-authority-and-head" };
1786
+ }
1787
+ function createOhSpacePurgeReceiptV1(input) {
1788
+ const binding = parseOhStoreBindingV1(input.binding);
1789
+ const priorHead = parseOhHeadV1(input.priorHead);
1790
+ const purgedAt = parseCanonicalInstantV1(input.purgedAt);
1791
+ if (binding === null || priorHead === null || purgedAt === null || binding.profile.profileKind !== "working" || !binding.profile.capabilities.wholeSpacePurge) {
1792
+ throw new OhProfileError("Only a bound working realm can produce a purge receipt.");
1793
+ }
1794
+ const payload = {
1795
+ bindingSha256: binding.bindingSha256,
1796
+ priorHead,
1797
+ purgedAt,
1798
+ spaceId: binding.spaceId,
1799
+ v: 1
1800
+ };
1801
+ return Object.freeze({ ...payload, receiptSha256: canonicalSha256(payload) });
1802
+ }
1803
+ function parseOhSpacePurgeReceiptV1(value) {
1804
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
1805
+ "bindingSha256",
1806
+ "priorHead",
1807
+ "purgedAt",
1808
+ "receiptSha256",
1809
+ "spaceId",
1810
+ "v"
1811
+ ]) || value.v !== 1)
1812
+ return null;
1813
+ const bindingSha256 = parseSha256Hex(value.bindingSha256);
1814
+ const priorHead = parseOhHeadV1(value.priorHead);
1815
+ const purgedAt = parseCanonicalInstantV1(value.purgedAt);
1816
+ const receiptSha256 = parseSha256Hex(value.receiptSha256);
1817
+ const spaceId = safeCode(value.spaceId);
1818
+ if (bindingSha256 === null || priorHead === null || purgedAt === null || receiptSha256 === null || spaceId === null)
1819
+ return null;
1820
+ const payload = { bindingSha256, priorHead, purgedAt, spaceId, v: 1 };
1821
+ return canonicalSha256(payload) === receiptSha256 ? Object.freeze({ ...payload, receiptSha256 }) : null;
1822
+ }
1823
+
1824
+ class OhSemanticBundleIngressV1 {
1825
+ #codecs;
1826
+ #store;
1827
+ constructor(store, codecs) {
1828
+ this.#store = store;
1829
+ this.#codecs = codecs.seal();
1830
+ }
1831
+ async commit(value) {
1832
+ if (!isPlainRecord(value) || !hasExactKeys(value, [
1833
+ "actorId",
1834
+ "expectedHead",
1835
+ "instant",
1836
+ "operationId",
1837
+ "puts",
1838
+ "tombstones",
1839
+ "v"
1840
+ ]) || value.v !== 1 || !Array.isArray(value.puts) || !Array.isArray(value.tombstones) || value.puts.length + value.tombstones.length < 1 || value.puts.length + value.tombstones.length > OH_GRAPH_LIMITS_V1.changesPerOperation) {
1841
+ throw new TypeError("Invalid semantic bundle.");
1842
+ }
1843
+ const actorId = safeCode(value.actorId);
1844
+ const operationId = safeCode(value.operationId);
1845
+ const expected = value.expectedHead;
1846
+ const instant = value.instant === null ? undefined : parseCanonicalInstantV1(value.instant);
1847
+ if (actorId === null || operationId === null || !isPlainRecord(expected) || !hasExactKeys(expected, ["generation", "operationSha256"]) || !Number.isSafeInteger(expected.generation) || expected.generation < 0 || expected.operationSha256 !== null && parseSha256Hex(expected.operationSha256) === null || expected.generation === 0 !== (expected.operationSha256 === null) || value.instant !== null && instant === null)
1848
+ throw new TypeError("Invalid semantic bundle identity.");
1849
+ const changes = [];
1850
+ for (const item of value.puts) {
1851
+ if (!isPlainRecord(item) || !hasExactKeys(item, ["dependencies", "key", "kind", "v", "value"]) || item.v !== 1 || !Array.isArray(item.dependencies) || !OH_KNOWLEDGE_GRAPH_RECORD_KINDS_V1.some((kind) => kind === item.kind)) {
1852
+ throw new TypeError("Invalid semantic bundle put.");
1853
+ }
1854
+ const parsed = this.#codecs.parseRequired(item.kind, item.value);
1855
+ if (parsed === null)
1856
+ throw new TypeError(`The ${String(item.kind)} codec rejected a semantic value.`);
1857
+ const record = createKnowledgeGraphRecordV1({
1858
+ dependencies: item.dependencies,
1859
+ key: item.key,
1860
+ kind: item.kind,
1861
+ v: 1,
1862
+ value: parsed
1863
+ });
1864
+ changes.push({ kind: "put", record, v: 1 });
1865
+ }
1866
+ for (const item of value.tombstones) {
1867
+ if (!isPlainRecord(item) || !hasExactKeys(item, ["key", "priorSha256", "v"]) || item.v !== 1) {
1868
+ throw new TypeError("Invalid semantic bundle tombstone.");
1869
+ }
1870
+ const priorSha256 = parseSha256Hex(item.priorSha256);
1871
+ if (typeof item.key !== "string" || priorSha256 === null)
1872
+ throw new TypeError("Invalid semantic bundle tombstone.");
1873
+ changes.push({ key: item.key, kind: "tombstone", priorSha256, v: 1 });
1874
+ }
1875
+ const canonical = canonicalKnowledgeGraphChangesV1(changes);
1876
+ return await this.#store.commit({
1877
+ actorId,
1878
+ changes: canonical,
1879
+ expectedHead: {
1880
+ generation: expected.generation,
1881
+ operationSha256: expected.operationSha256
1882
+ },
1883
+ ...typeof instant === "string" ? { instant } : {},
1884
+ operationId
1885
+ });
1886
+ }
1887
+ }
1888
+ export {
1889
+ verifyOhDependencyClosureV1,
1890
+ verifyOhDependencyClosureAgainstV1,
1891
+ verifyKnowledgeValueV1,
1892
+ verifyKnowledgeSchemaEvolutionV1,
1893
+ utf8ByteLength,
1894
+ transitionOhSnapshotV1,
1895
+ synchronizeOhStoreV1,
1896
+ sortUnique,
1897
+ sha256Hex,
1898
+ safeCode,
1899
+ replayOhOperationsV1,
1900
+ reduceKnowledgeGraphRevisionsV1,
1901
+ parseSha256Hex,
1902
+ parseOhSyncBundleV1,
1903
+ parseOhStoreProfileV1,
1904
+ parseOhStoreBindingV1,
1905
+ parseOhSpacePurgeReceiptV1,
1906
+ parseOhOperationV1,
1907
+ parseOhHeadV1,
1908
+ parseOhHeadRefV1,
1909
+ parseOhDependencyClosureV1,
1910
+ parseOhContractManifestV1,
1911
+ parseKnowledgeVocabularyRevisionV1,
1912
+ parseKnowledgeValueV1,
1913
+ parseKnowledgeStatementV1,
1914
+ parseKnowledgeSchemaRevisionV1,
1915
+ parseKnowledgeSchemaRefV1,
1916
+ parseKnowledgeInquiryV1,
1917
+ parseKnowledgeInquiryId,
1918
+ parseKnowledgeGraphRevisionV1,
1919
+ parseKnowledgeGraphRecordV1,
1920
+ parseKnowledgeEvidenceLinkV1,
1921
+ parseKnowledgeEvidenceId,
1922
+ parseKnowledgeEntityV1,
1923
+ parseKnowledgeEntityId,
1924
+ parseKnowledgeContextV1,
1925
+ parseKnowledgeAssertionV1,
1926
+ parseKnowledgeAssertionId,
1927
+ parseKnowledgeActivityV1,
1928
+ parseCanonicalJson,
1929
+ parseCanonicalInstantV1,
1930
+ orderedUnique,
1931
+ opaqueId,
1932
+ knowledgeSchemaRefV1,
1933
+ knowledgeGraphRecordRefV1,
1934
+ isPlainRecord,
1935
+ hasExactKeys,
1936
+ graphRevisionSha256V1,
1937
+ emptyOhHeadV1,
1938
+ createOhSyncBundleV1,
1939
+ createOhStoreProfileV1,
1940
+ createOhStoreBindingV1,
1941
+ createOhSpacePurgeReceiptV1,
1942
+ createOhOperationV1,
1943
+ createOhDependencyClosureV1,
1944
+ createLibSqlOperationSyncTransportV1,
1945
+ createKnowledgeVocabularyRevisionV1,
1946
+ createKnowledgeStatementV1,
1947
+ createKnowledgeSchemaRevisionV1,
1948
+ createKnowledgeInquiryV1,
1949
+ createKnowledgeGraphRevisionV1,
1950
+ createKnowledgeGraphRecordV1,
1951
+ createKnowledgeEvidenceLinkV1,
1952
+ createKnowledgeContextV1,
1953
+ createKnowledgeAssertionV1,
1954
+ createKnowledgeActivityV1,
1955
+ canonicalSha256,
1956
+ canonicalNow,
1957
+ canonicalKnowledgeGraphChangesV1,
1958
+ canonicalJson,
1959
+ boundedText,
1960
+ OhValidationError,
1961
+ OhSemanticBundleIngressV1,
1962
+ OhRecordCodecRegistry,
1963
+ OhPurgedSpaceError,
1964
+ OhProfileError,
1965
+ OhIntegrityError,
1966
+ OhDependencyError,
1967
+ OhConflictError,
1968
+ OH_WORKING_STORE_PROFILE_V1,
1969
+ OH_SYNC_PROTOCOL_V1,
1970
+ OH_SCHEMA_KINDS_V1,
1971
+ OH_SCHEMA_FORMAT_VERSION_V1,
1972
+ OH_OPERATION_MAX_BYTES_V1,
1973
+ OH_ONTOLOGY_VERSION_V1,
1974
+ OH_KNOWLEDGE_LIMITS_V1,
1975
+ OH_KNOWLEDGE_KERNEL_CONCEPTS_V1,
1976
+ OH_KNOWLEDGE_GRAPH_RECORD_KINDS_V1,
1977
+ OH_KNOWLEDGE_EVIDENCE_BEARINGS_V1,
1978
+ OH_KNOWLEDGE_ENTITY_STATES_V1,
1979
+ OH_KNOWLEDGE_ASSERTION_STATES_V1,
1980
+ OH_KNOWLEDGE_ASSERTION_STANCES_V1,
1981
+ OH_KNOWLEDGE_ACTIVITY_KINDS_V1,
1982
+ OH_GRAPH_LIMITS_V1,
1983
+ OH_GRAPH_FORMAT_VERSION_V1,
1984
+ OH_DEPENDENCY_CLOSURE_LIMITS_V1,
1985
+ OH_CONTRACT_MANIFEST_V1,
1986
+ OH_CONTRACT_ID_V1,
1987
+ OH_CANONICAL_STORE_PROFILE_V1
1988
+ };