@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.
- package/LICENSE +21 -0
- package/README.md +598 -0
- package/dist/canonical.d.ts +32 -0
- package/dist/canonical.d.ts.map +1 -0
- package/dist/cli.d.ts +4 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +3419 -0
- package/dist/contract.d.ts +33 -0
- package/dist/contract.d.ts.map +1 -0
- package/dist/graph.d.ts +67 -0
- package/dist/graph.d.ts.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1988 -0
- package/dist/libsql.d.ts +57 -0
- package/dist/libsql.d.ts.map +1 -0
- package/dist/libsql.js +2662 -0
- package/dist/memory.d.ts +366 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/memory.js +3650 -0
- package/dist/ontology.d.ts +242 -0
- package/dist/ontology.d.ts.map +1 -0
- package/dist/operation.d.ts +24 -0
- package/dist/operation.d.ts.map +1 -0
- package/dist/projection-public.d.ts +59 -0
- package/dist/projection-public.d.ts.map +1 -0
- package/dist/projection-public.js +1682 -0
- package/dist/projection-suss.d.ts +17 -0
- package/dist/projection-suss.d.ts.map +1 -0
- package/dist/projection-suss.js +1721 -0
- package/dist/projection.d.ts +315 -0
- package/dist/projection.d.ts.map +1 -0
- package/dist/schema.d.ts +45 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/sdk.d.ts +51 -0
- package/dist/sdk.d.ts.map +1 -0
- package/dist/sdk.js +3072 -0
- package/dist/search.d.ts +34 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/semantic.d.ts +83 -0
- package/dist/semantic.d.ts.map +1 -0
- package/dist/semantic.js +706 -0
- package/dist/sqlite/driver.d.ts +6 -0
- package/dist/sqlite/driver.d.ts.map +1 -0
- package/dist/sqlite/index.d.ts +5 -0
- package/dist/sqlite/index.d.ts.map +1 -0
- package/dist/sqlite/index.js +2840 -0
- package/dist/sqlite/migrations.d.ts +10 -0
- package/dist/sqlite/migrations.d.ts.map +1 -0
- package/dist/sqlite/port.d.ts +40 -0
- package/dist/sqlite/port.d.ts.map +1 -0
- package/dist/sqlite/runtime.d.ts +23 -0
- package/dist/sqlite/runtime.d.ts.map +1 -0
- package/dist/sqlite/store.d.ts +85 -0
- package/dist/sqlite/store.d.ts.map +1 -0
- package/dist/store.d.ts +236 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +996 -0
- package/dist/sync.d.ts +57 -0
- package/dist/sync.d.ts.map +1 -0
- package/dist/sync.js +1328 -0
- package/package.json +121 -0
- package/skills/oh/SKILL.md +206 -0
- package/skills/oh/agents/openai.yaml +4 -0
- package/spec/README.md +74 -0
- package/spec/manifest.json +41 -0
- package/spec/v1/canonical-json.md +59 -0
- package/spec/v1/contract.json +28 -0
- package/spec/v1/contract.schema.json +58 -0
- package/spec/v1/embedding-profile.json +11 -0
- package/spec/v1/embedding.md +56 -0
- package/spec/v1/graph.md +87 -0
- package/spec/v1/memory.md +193 -0
- package/spec/v1/migration.md +92 -0
- package/spec/v1/ontology.json +55 -0
- package/spec/v1/ontology.md +80 -0
- package/spec/v1/operation.schema.json +138 -0
- package/spec/v1/projection-identity.schema.json +58 -0
- package/spec/v1/projection-query.schema.json +60 -0
- package/spec/v1/projection-result.schema.json +452 -0
- package/spec/v1/projection-rule-pack.schema.json +182 -0
- package/spec/v1/projection.md +165 -0
- package/spec/v1/record.schema.json +95 -0
- package/spec/v1/schema-evolution.md +51 -0
- package/spec/v1/schema-revision.schema.json +178 -0
- package/spec/v1/storage.md +88 -0
- package/spec/v1/store.md +131 -0
- package/spec/v1/sync-bundle.schema.json +51 -0
- package/spec/v1/sync.md +67 -0
- package/src/canonical.test.ts +46 -0
- package/src/canonical.ts +203 -0
- package/src/cli.test.ts +103 -0
- package/src/cli.ts +308 -0
- package/src/contract.ts +87 -0
- package/src/contracts.test.ts +147 -0
- package/src/graph.ts +248 -0
- package/src/index.ts +8 -0
- package/src/libsql.test.ts +657 -0
- package/src/libsql.ts +1687 -0
- package/src/memory.test.ts +783 -0
- package/src/memory.ts +1684 -0
- package/src/ontology.ts +573 -0
- package/src/operation.ts +80 -0
- package/src/projection-public.ts +53 -0
- package/src/projection-suss.ts +129 -0
- package/src/projection.test.ts +418 -0
- package/src/projection.ts +1457 -0
- package/src/schema.ts +156 -0
- package/src/sdk.ts +96 -0
- package/src/search.ts +66 -0
- package/src/semantic.test.ts +480 -0
- package/src/semantic.ts +333 -0
- package/src/sqlite/driver.ts +47 -0
- package/src/sqlite/index.ts +4 -0
- package/src/sqlite/migrations.test.ts +44 -0
- package/src/sqlite/migrations.ts +178 -0
- package/src/sqlite/port.test.ts +127 -0
- package/src/sqlite/port.ts +120 -0
- package/src/sqlite/runtime.test.ts +68 -0
- package/src/sqlite/runtime.ts +53 -0
- package/src/sqlite/store.test.ts +295 -0
- package/src/sqlite/store.ts +988 -0
- package/src/store.test.ts +121 -0
- package/src/store.ts +701 -0
- package/src/sync.test.ts +117 -0
- package/src/sync.ts +227 -0
package/dist/sync.js
ADDED
|
@@ -0,0 +1,1328 @@
|
|
|
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
|
+
export {
|
|
1323
|
+
synchronizeOhStoreV1,
|
|
1324
|
+
parseOhSyncBundleV1,
|
|
1325
|
+
createOhSyncBundleV1,
|
|
1326
|
+
createLibSqlOperationSyncTransportV1,
|
|
1327
|
+
OH_SYNC_PROTOCOL_V1
|
|
1328
|
+
};
|