@wazootech/worlds-sdk 0.0.0-stage → 0.11.3-rc.0

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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +288 -2
  3. package/THIRD_PARTY_NOTICES.md +279 -0
  4. package/dist/ai-sdk.d.ts +27 -0
  5. package/dist/ai-sdk.js +28 -0
  6. package/dist/build-search-result-id-qxdmXp0V.js +12 -0
  7. package/dist/chunk-and-embed-0crm0xLl.js +75 -0
  8. package/dist/client-BJ45zmXU.d.ts +74 -0
  9. package/dist/client-BWh0UAM0.js +45 -0
  10. package/dist/embedding-service-DebRMVmn.d.ts +15 -0
  11. package/dist/embedding-service.d.ts +3 -0
  12. package/dist/embedding-service.js +19 -0
  13. package/dist/index.d.ts +8 -0
  14. package/dist/index.js +9 -0
  15. package/dist/memory.d.ts +26 -0
  16. package/dist/memory.js +29 -0
  17. package/dist/mod-8Zh1f9vW.d.ts +24 -0
  18. package/dist/mod-BuF_B_xU.d.ts +362 -0
  19. package/dist/mod-CHiiyEER.d.ts +79 -0
  20. package/dist/mod-ClDFMN-C.d.ts +625 -0
  21. package/dist/mod-Dmrdrb03.d.ts +13 -0
  22. package/dist/quad-chunker.d.ts +2 -0
  23. package/dist/quad-chunker.js +1 -0
  24. package/dist/quad-store-BGCOUBxK.js +851 -0
  25. package/dist/quad-store.d.ts +2 -0
  26. package/dist/quad-store.js +3 -0
  27. package/dist/rdf-formats-BkGt5RDB.js +93 -0
  28. package/dist/rdfjs-BNVjLSNL.js +190 -0
  29. package/dist/rdfjs.d.ts +79 -0
  30. package/dist/rdfjs.js +1 -0
  31. package/dist/search-index.d.ts +2 -0
  32. package/dist/search-index.js +219 -0
  33. package/dist/sparql-engine.d.ts +2 -0
  34. package/dist/sparql-engine.js +0 -0
  35. package/dist/testing.d.ts +301 -0
  36. package/dist/testing.js +786 -0
  37. package/dist/tfjs-use.d.ts +42 -0
  38. package/dist/tfjs-use.js +315 -0
  39. package/dist/wazoo.d.ts +86 -0
  40. package/dist/wazoo.js +347 -0
  41. package/package.json +119 -4
@@ -0,0 +1,786 @@
1
+ import { h as hashQuad } from "./quad-store-BGCOUBxK.js";
2
+ import { o as materializeImportQuads } from "./rdf-formats-BkGt5RDB.js";
3
+ import { DataFactory } from "n3";
4
+ import { FakeEmbeddingService } from "./embedding-service.js";
5
+ // src/testing/parity-fixtures.ts
6
+ const XSD = "http://www.w3.org/2001/XMLSchema#";
7
+ /**
8
+ * multiGraphWorld exercises the one-world-many-graphs guarantee
9
+ * (wazootech/workspace#71): default-graph quads plus named public and private
10
+ * graphs with overlapping subjects, searchable and queryable per graph.
11
+ */
12
+ const multiGraphWorld = {
13
+ name: "multiGraphWorld",
14
+ nquads: [
15
+ "<urn:alice> <urn:likes> \"sailing\"@en .",
16
+ "<urn:alice> <urn:age> \"42\"^^<" + XSD + "integer> .",
17
+ "<urn:alice> <urn:posted> \"alice wrote a public note\" <urn:graph:public> .",
18
+ "<urn:bob> <urn:posted> \"bob is public too\" <urn:graph:public> .",
19
+ "<urn:alice> <urn:stores> \"confidential key material for alice\" <urn:graph:private> ."
20
+ ].join("\n"),
21
+ totalQuads: 5,
22
+ graphSizes: {
23
+ "": 2,
24
+ "urn:graph:public": 2,
25
+ "urn:graph:private": 1
26
+ },
27
+ search: [
28
+ {
29
+ name: "alice across graphs",
30
+ request: {
31
+ query: "alice",
32
+ topK: 10
33
+ }
34
+ },
35
+ {
36
+ name: "confidential hits the private graph only",
37
+ request: {
38
+ query: "confidential",
39
+ topK: 10
40
+ }
41
+ },
42
+ {
43
+ name: "public scoped to the public graph via QuadFilter",
44
+ request: {
45
+ query: "public",
46
+ topK: 10,
47
+ include: { graphs: ["urn:graph:public"] }
48
+ }
49
+ }
50
+ ],
51
+ sparql: [
52
+ {
53
+ name: "private-graph subjects",
54
+ query: "SELECT ?s WHERE { GRAPH <urn:graph:private> { ?s ?p ?o } }",
55
+ expected: {
56
+ kind: "select",
57
+ bindings: [{ s: {
58
+ type: "uri",
59
+ value: "urn:alice"
60
+ } }]
61
+ }
62
+ },
63
+ {
64
+ name: "ask a public-graph fact",
65
+ query: "ASK WHERE { GRAPH <urn:graph:public> { <urn:bob> ?p ?o } }",
66
+ expected: {
67
+ kind: "ask",
68
+ boolean: true
69
+ }
70
+ },
71
+ {
72
+ name: "cross-graph join narrows to alice",
73
+ query: "SELECT ?s WHERE { GRAPH <urn:graph:public> { ?s <urn:posted> ?o } . GRAPH <urn:graph:private> { ?s <urn:stores> ?x } }",
74
+ expected: {
75
+ kind: "select",
76
+ bindings: [{ s: {
77
+ type: "uri",
78
+ value: "urn:alice"
79
+ } }]
80
+ }
81
+ },
82
+ {
83
+ name: "total quad count across all graphs",
84
+ query: "SELECT (COUNT(*) AS ?c) WHERE { { ?s ?p ?o } UNION { GRAPH ?g { ?s ?p ?o } } }",
85
+ expected: {
86
+ kind: "select",
87
+ bindings: [{ c: {
88
+ type: "literal",
89
+ value: "5",
90
+ datatype: XSD + "integer"
91
+ } }]
92
+ }
93
+ }
94
+ ]
95
+ };
96
+ /**
97
+ * typedLiteralsWorld covers the literal type surface: plain (xsd:string),
98
+ * language-tagged (en/es/ar incl. RTL unicode), and typed literals
99
+ * (integer, double, date, boolean).
100
+ */
101
+ const typedLiteralsWorld = {
102
+ name: "typedLiteralsWorld",
103
+ nquads: [
104
+ "<urn:item1> <urn:label> \"Widget\" .",
105
+ "<urn:item1> <urn:greeting> \"Hello\"@en .",
106
+ "<urn:item1> <urn:greeting> \"Hola\"@es .",
107
+ "<urn:item1> <urn:greeting> \"مرحبا\"@ar .",
108
+ "<urn:item1> <urn:count> \"42\"^^<" + XSD + "integer> .",
109
+ "<urn:item1> <urn:ratio> \"3.14\"^^<" + XSD + "double> .",
110
+ "<urn:item1> <urn:born> \"2000-01-01\"^^<" + XSD + "date> .",
111
+ "<urn:item1> <urn:active> \"true\"^^<" + XSD + "boolean> ."
112
+ ].join("\n"),
113
+ totalQuads: 8,
114
+ graphSizes: { "": 8 },
115
+ search: [
116
+ {
117
+ name: "widget label",
118
+ request: {
119
+ query: "Widget",
120
+ topK: 10
121
+ }
122
+ },
123
+ {
124
+ name: "arabic greeting (unicode)",
125
+ request: {
126
+ query: "مرحبا",
127
+ topK: 10
128
+ }
129
+ },
130
+ {
131
+ name: "english greeting",
132
+ request: {
133
+ query: "Hello",
134
+ topK: 10
135
+ }
136
+ }
137
+ ],
138
+ sparql: [
139
+ {
140
+ name: "lang-filtered greeting returns the arabic literal",
141
+ query: "SELECT ?o WHERE { <urn:item1> <urn:greeting> ?o FILTER (LANG(?o) = \"ar\") }",
142
+ expected: {
143
+ kind: "select",
144
+ bindings: [{ o: {
145
+ type: "literal",
146
+ value: "مرحبا",
147
+ "xml:lang": "ar"
148
+ } }]
149
+ }
150
+ },
151
+ {
152
+ name: "typed integer literal round-trips its datatype",
153
+ query: "SELECT ?o WHERE { <urn:item1> <urn:count> ?o }",
154
+ expected: {
155
+ kind: "select",
156
+ bindings: [{ o: {
157
+ type: "literal",
158
+ value: "42",
159
+ datatype: XSD + "integer"
160
+ } }]
161
+ }
162
+ },
163
+ {
164
+ name: "boolean literal matches SPARQL true",
165
+ query: "ASK WHERE { <urn:item1> <urn:active> true }",
166
+ expected: {
167
+ kind: "ask",
168
+ boolean: true
169
+ }
170
+ }
171
+ ]
172
+ };
173
+ /**
174
+ * rdfStarWorld declares the RDF-star corpus category (RDF 1.2 quoted-triple
175
+ * syntax). Under RDF 1.2 occurrence semantics, the quoted-triple subject
176
+ * statement expands to a reification quad (an anonymous reifier with
177
+ * rdf:reifies) plus the claim, so the world holds 3 quads. The SPARQL engine
178
+ * models quoted triples, but the durable reference cannot store them yet
179
+ * (the backend-neutral Term layer throws on Quad terms), so this fixture is
180
+ * gated "declared": it runs and is reported, but does not fail the suite
181
+ * until the reference lands RDF-star storage.
182
+ */
183
+ const rdfStarWorld = {
184
+ name: "rdfStarWorld",
185
+ nquads: ["<< <urn:alice> <urn:likes> <urn:sailing> >> <urn:claims> \"yes\" .", "<urn:alice> <urn:notes> \"alice keeps a journal\" ."].join("\n"),
186
+ totalQuads: 3,
187
+ graphSizes: { "": 3 },
188
+ gate: "declared",
189
+ sparql: [{
190
+ name: "quoted-triple pattern matches the RDF-star fact",
191
+ query: "SELECT ?o WHERE { << <urn:alice> <urn:likes> <urn:sailing> >> <urn:claims> ?o }",
192
+ expected: {
193
+ kind: "select",
194
+ bindings: [{ o: {
195
+ type: "literal",
196
+ value: "yes"
197
+ } }]
198
+ }
199
+ }]
200
+ };
201
+ /**
202
+ * chunkBoundaryWorld exercises the search chunker with a literal far longer
203
+ * than the reference's default 1000-char chunk size, plus a short needle
204
+ * literal. Both Sdks must produce identical chunk-derived search result ids.
205
+ */
206
+ const chunkBoundaryWorld = {
207
+ name: "chunkBoundaryWorld",
208
+ nquads: ["<urn:long> <urn:body> \"" + longParagraph() + "\" .", "<urn:long> <urn:tag> \"needle\" ."].join("\n"),
209
+ totalQuads: 2,
210
+ graphSizes: { "": 2 },
211
+ search: [{
212
+ name: "turquoise hits the long chunk",
213
+ request: {
214
+ query: "turquoise",
215
+ topK: 10
216
+ }
217
+ }, {
218
+ name: "needle short literal",
219
+ request: {
220
+ query: "needle",
221
+ topK: 5
222
+ }
223
+ }]
224
+ };
225
+ /** emptyWorld verifies zero-quad behavior end to end. */
226
+ const emptyWorld = {
227
+ name: "emptyWorld",
228
+ nquads: "",
229
+ totalQuads: 0,
230
+ graphSizes: { "": 0 },
231
+ search: [{
232
+ name: "empty search",
233
+ request: {
234
+ query: "anything",
235
+ topK: 10
236
+ }
237
+ }],
238
+ sparql: [{
239
+ name: "ask is false on the empty world",
240
+ query: "ASK WHERE { ?s ?p ?o }",
241
+ expected: {
242
+ kind: "ask",
243
+ boolean: false
244
+ }
245
+ }]
246
+ };
247
+ /**
248
+ * replaceModeCase exercises replace-mode import: the second import must fully
249
+ * wipe the first (the reference's commit-patch replace-mode contract).
250
+ */
251
+ const replaceModeCase = {
252
+ name: "replaceModeCase",
253
+ first: ["<urn:a> <urn:p> \"one\" .", "<urn:b> <urn:p> \"two\" ."].join("\n"),
254
+ second: "<urn:c> <urn:p> \"three\" .",
255
+ resultCount: 1
256
+ };
257
+ /** parityCorpus is the full registry run by runParitySuite by default. */
258
+ const parityCorpus = {
259
+ fixtures: [
260
+ multiGraphWorld,
261
+ typedLiteralsWorld,
262
+ rdfStarWorld,
263
+ chunkBoundaryWorld,
264
+ emptyWorld
265
+ ],
266
+ replaceCases: [replaceModeCase]
267
+ };
268
+ /**
269
+ * longParagraph returns a deterministic English paragraph of roughly 1,400
270
+ * characters (well past the reference's default 1000-char chunk size) with
271
+ * repeated "turquoise" tokens so the long chunk is searchable.
272
+ */
273
+ function longParagraph() {
274
+ return "The turquoise ribbon drifted over the harbor while a lone gull circled the mast and the evening tide carried the fishing boats home one by one. ".repeat(14).slice(0, 1400);
275
+ }
276
+ // src/testing/parity-helpers.ts
277
+ const NQUADS = "application/n-quads";
278
+ const XSD_STRING = "http://www.w3.org/2001/XMLSchema#string";
279
+ async function exportQuads(sdk) {
280
+ const response = await sdk.export({ format: { kind: "quads" } });
281
+ if (response.kind !== "quads") throw new Error("export did not return quads");
282
+ return response.quads;
283
+ }
284
+ async function exportSerialized(sdk) {
285
+ const response = await sdk.export({ format: {
286
+ kind: "serialized",
287
+ contentType: NQUADS
288
+ } });
289
+ if (response.kind !== "serialized") throw new Error("export did not return serialized data");
290
+ return {
291
+ data: response.data,
292
+ contentType: response.contentType
293
+ };
294
+ }
295
+ async function importNquads(sdk, nquads, mode = "merge") {
296
+ await sdk.import({
297
+ mode,
298
+ source: {
299
+ kind: "serialized",
300
+ data: nquads,
301
+ contentType: NQUADS
302
+ }
303
+ });
304
+ }
305
+ async function countNquads(nquads) {
306
+ return (await materializeImportQuads({
307
+ kind: "serialized",
308
+ data: nquads,
309
+ contentType: NQUADS
310
+ })).length;
311
+ }
312
+ function searchResultKey(result) {
313
+ return JSON.stringify({
314
+ id: result.id,
315
+ subject: result.subject,
316
+ predicate: result.predicate,
317
+ graph: result.graph,
318
+ text: result.text
319
+ });
320
+ }
321
+ /** bindingKey canonicalizes a SPARQL binding (order-insensitive key comparison). */
322
+ function bindingKey(binding) {
323
+ return `{${Object.keys(binding).sort().map((variable) => {
324
+ return `${variable}=${valueKey(binding[variable])}`;
325
+ }).join(", ")}}`;
326
+ }
327
+ function valueKey(value) {
328
+ switch (value.type) {
329
+ case "uri":
330
+ case "bnode": return `${value.type}:${value.value}`;
331
+ case "literal": {
332
+ let key = `literal:${value.value}`;
333
+ if (value["xml:lang"]) key += `@${value["xml:lang"]}`;
334
+ if (value.datatype && value.datatype !== XSD_STRING) key += `^^${value.datatype}`;
335
+ if (value["its:dir"]) key += `[${value["its:dir"]}]`;
336
+ return key;
337
+ }
338
+ case "triple": return `triple(${valueKey(value.value.subject)}, ${valueKey(value.value.predicate)}, ${valueKey(value.value.object)})`;
339
+ }
340
+ }
341
+ function sequenceEqual(a, b) {
342
+ return a.length === b.length && a.every((value, index) => value === b[index]);
343
+ }
344
+ function multisetEqual(a, b) {
345
+ if (a.length !== b.length) return false;
346
+ const counts = /* @__PURE__ */ new Map();
347
+ for (const value of a) counts.set(value, (counts.get(value) ?? 0) + 1);
348
+ for (const value of b) {
349
+ const remaining = (counts.get(value) ?? 0) - 1;
350
+ if (remaining < 0) return false;
351
+ counts.set(value, remaining);
352
+ }
353
+ return true;
354
+ }
355
+ // src/testing/parity-checks.ts
356
+ async function checkQuadCounts(fixtureName, ref, cand, expected, failures) {
357
+ for (const [label, sdk] of [["reference", ref], ["candidate", cand]]) {
358
+ const quads = await exportQuads(sdk);
359
+ if (quads.length !== expected) failures.push(`[${fixtureName}] ${label} quad count ${quads.length} != expected ${expected}`);
360
+ }
361
+ }
362
+ async function checkGraphSizes(fixtureName, sdk, expected, failures) {
363
+ if (!expected) return;
364
+ const quads = await exportQuads(sdk);
365
+ const sizes = /* @__PURE__ */ new Map();
366
+ for (const quad of quads) {
367
+ const graph = quad.graph.value;
368
+ sizes.set(graph, (sizes.get(graph) ?? 0) + 1);
369
+ }
370
+ for (const [graph, count] of Object.entries(expected)) if ((sizes.get(graph) ?? 0) !== count) failures.push(`[${fixtureName}] candidate graph ${JSON.stringify(graph)} has ${sizes.get(graph) ?? 0} quads != expected ${count}`);
371
+ }
372
+ /**
373
+ * checkRoundTrip verifies that exporting a world and re-importing the
374
+ * exported serialization yields byte-identical serializations (idempotent
375
+ * round-trip) on the candidate's own engine.
376
+ */
377
+ async function checkRoundTrip(fixtureName, candidateFactory, nquads, failures) {
378
+ const sdk1 = await candidateFactory();
379
+ await importNquads(sdk1, nquads);
380
+ const out1 = await exportSerialized(sdk1);
381
+ const sdk2 = await candidateFactory();
382
+ await importNquads(sdk2, out1.data);
383
+ const out2 = await exportSerialized(sdk2);
384
+ if (out1.data !== out2.data) failures.push(`[${fixtureName}] candidate serialized export is not round-trip idempotent`);
385
+ }
386
+ async function checkSearchCase(fixtureName, options, nquads, searchCase, strictOrder, failures) {
387
+ const ref = await options.reference();
388
+ const cand = await options.candidate();
389
+ await importNquads(ref, nquads);
390
+ await importNquads(cand, nquads);
391
+ const refResults = (await ref.search(searchCase.request)).results ?? [];
392
+ const candResults = (await cand.search(searchCase.request)).results ?? [];
393
+ const refKeys = refResults.map(searchResultKey);
394
+ const candKeys = candResults.map(searchResultKey);
395
+ if (!(strictOrder ? sequenceEqual(refKeys, candKeys) : multisetEqual(refKeys, candKeys))) failures.push(`[${fixtureName}] search case "${searchCase.name}": candidate results differ from reference (query=${JSON.stringify(searchCase.request.query)})`);
396
+ }
397
+ // src/testing/parity-sparql.ts
398
+ async function checkSparqlCase(fixtureName, options, nquads, sparqlCase, failures) {
399
+ const ref = await options.reference();
400
+ const cand = await options.candidate();
401
+ await importNquads(ref, nquads);
402
+ await importNquads(cand, nquads);
403
+ const refResponse = await ref.sparql({ query: sparqlCase.query });
404
+ const candResponse = await cand.sparql({ query: sparqlCase.query });
405
+ checkSparqlAgainstExpectation(fixtureName, sparqlCase.name, "reference", refResponse, sparqlCase.expected, failures);
406
+ checkSparqlAgainstExpectation(fixtureName, sparqlCase.name, "candidate", candResponse, sparqlCase.expected, failures);
407
+ checkSparqlEquivalence(fixtureName, sparqlCase.name, refResponse, candResponse, failures);
408
+ }
409
+ function checkSparqlAgainstExpectation(fixtureName, caseName, label, response, expected, failures) {
410
+ if (expected.kind === "ask") {
411
+ if (response.kind !== "ask") {
412
+ failures.push(`[${fixtureName}] SPARQL "${caseName}" (${label}): expected ask, got ${response.kind}`);
413
+ return;
414
+ }
415
+ if (response.data.boolean !== expected.boolean) failures.push(`[${fixtureName}] SPARQL "${caseName}" (${label}): ask ${response.data.boolean} != expected ${expected.boolean}`);
416
+ return;
417
+ }
418
+ if (expected.kind === "select") {
419
+ if (response.kind !== "select") {
420
+ failures.push(`[${fixtureName}] SPARQL "${caseName}" (${label}): expected select, got ${response.kind}`);
421
+ return;
422
+ }
423
+ if (!sequenceEqual(response.data.results.bindings.map(bindingKey).sort(), expected.bindings.map(bindingKey).sort())) failures.push(`[${fixtureName}] SPARQL "${caseName}" (${label}): bindings differ from expected (query=${JSON.stringify(caseName)})`);
424
+ }
425
+ }
426
+ function checkSparqlEquivalence(fixtureName, caseName, refResponse, candResponse, failures) {
427
+ if (refResponse.kind !== candResponse.kind) {
428
+ failures.push(`[${fixtureName}] SPARQL "${caseName}": response kinds differ (${refResponse.kind} vs ${candResponse.kind})`);
429
+ return;
430
+ }
431
+ if (refResponse.kind === "ask" && candResponse.kind === "ask") {
432
+ if (refResponse.data.boolean !== candResponse.data.boolean) failures.push(`[${fixtureName}] SPARQL "${caseName}": ask results differ between reference and candidate`);
433
+ return;
434
+ }
435
+ if (refResponse.kind === "select" && candResponse.kind === "select") {
436
+ if (!sequenceEqual(refResponse.data.results.bindings.map(bindingKey).sort(), candResponse.data.results.bindings.map(bindingKey).sort())) failures.push(`[${fixtureName}] SPARQL "${caseName}": bindings differ between reference and candidate`);
437
+ }
438
+ }
439
+ // src/testing/parity-cases.ts
440
+ async function runFixtureCase(options, fixture) {
441
+ const failures = [];
442
+ const notes = [];
443
+ try {
444
+ const ref = await options.reference();
445
+ const cand = await options.candidate();
446
+ await importNquads(ref, fixture.nquads);
447
+ await importNquads(cand, fixture.nquads);
448
+ await checkQuadCounts(fixture.name, ref, cand, fixture.totalQuads, failures);
449
+ await checkGraphSizes(fixture.name, cand, fixture.graphSizes, failures);
450
+ await checkRoundTrip(fixture.name, options.candidate, fixture.nquads, failures);
451
+ for (const searchCase of fixture.search ?? []) await checkSearchCase(fixture.name, options, fixture.nquads, searchCase, options.strictSearchOrder ?? true, failures);
452
+ for (const sparqlCase of fixture.sparql ?? []) await checkSparqlCase(fixture.name, options, fixture.nquads, sparqlCase, failures);
453
+ } catch (error) {
454
+ const message = error instanceof Error ? error.message : String(error);
455
+ failures.push(`threw: ${message}`);
456
+ }
457
+ if (fixture.gate === "declared") {
458
+ if (failures.length > 0) {
459
+ notes.push(...failures);
460
+ failures.length = 0;
461
+ }
462
+ }
463
+ return {
464
+ name: fixture.name,
465
+ ok: failures.length === 0,
466
+ failures,
467
+ notes: notes.length > 0 ? notes : void 0
468
+ };
469
+ }
470
+ async function runReplaceCase(options, replaceCase) {
471
+ const failures = [];
472
+ try {
473
+ const firstCount = await countNquads(replaceCase.first);
474
+ for (const [label, factory] of [["reference", options.reference], ["candidate", options.candidate]]) {
475
+ const sdk = await factory();
476
+ await importNquads(sdk, replaceCase.first, "replace");
477
+ const afterFirst = await exportQuads(sdk);
478
+ if (afterFirst.length !== firstCount) failures.push(`[${replaceCase.name}] ${label} after first replace: ${afterFirst.length} quads != expected ${firstCount}`);
479
+ await importNquads(sdk, replaceCase.second, "replace");
480
+ const afterSecond = await exportQuads(sdk);
481
+ if (afterSecond.length !== replaceCase.resultCount) failures.push(`[${replaceCase.name}] ${label} after second replace: ${afterSecond.length} quads != expected ${replaceCase.resultCount}`);
482
+ }
483
+ } catch (error) {
484
+ const message = error instanceof Error ? error.message : String(error);
485
+ failures.push(`threw: ${message}`);
486
+ }
487
+ return {
488
+ name: replaceCase.name,
489
+ ok: failures.length === 0,
490
+ failures
491
+ };
492
+ }
493
+ // src/testing/run-parity-suite.ts
494
+ /**
495
+ * runParitySuite verifies a candidate durable backend against a reference
496
+ * WorldsSdk on the shared fixture corpus. Every fixture is imported into a fresh
497
+ * pair of WorldsSdks, then checked for: exact quad counts, per-graph counts,
498
+ * idempotent serialized export round-trips, SPARQL results against
499
+ * hand-authored expectations (both WorldsSdks), and search results compared to the
500
+ * reference (order-sensitive by default). See the shared parity/benchmark
501
+ * suite definition (wazootech/workspace#72).
502
+ */
503
+ async function runParitySuite(options) {
504
+ const fixtures = options.fixtures ?? parityCorpus.fixtures;
505
+ const replaceCases = options.replaceCases ?? parityCorpus.replaceCases;
506
+ const results = [];
507
+ for (const fixture of fixtures) results.push(await runFixtureCase(options, fixture));
508
+ for (const replaceCase of replaceCases) results.push(await runReplaceCase(options, replaceCase));
509
+ return {
510
+ ok: results.every((result) => result.ok),
511
+ results
512
+ };
513
+ }
514
+ // src/testing/commit-conformance-support.ts
515
+ const { quad, namedNode, literal } = DataFactory;
516
+ const g = namedNode("urn:conformance:g");
517
+ const p = namedNode("urn:conformance:p");
518
+ /** The fixture quads: three textual quads and one with an IRI object (never chunked). */
519
+ const fixtureQuads = {
520
+ base: quad(namedNode("urn:conformance:base"), p, literal("base text"), g),
521
+ one: quad(namedNode("urn:conformance:one"), p, literal("first text"), g),
522
+ two: quad(namedNode("urn:conformance:two"), p, literal("second text"), g),
523
+ three: quad(namedNode("urn:conformance:three"), p, literal("third text"), g),
524
+ link: quad(namedNode("urn:conformance:link"), p, namedNode("urn:x"), g)
525
+ };
526
+ /** workingEmbeddings returns a valid 32-dimension vector for every text. */
527
+ const workingEmbeddings = new FakeEmbeddingService();
528
+ /** failingEmbeddings rejects every call. */
529
+ const failingEmbeddings = { embed: () => Promise.reject(/* @__PURE__ */ new Error("embedding service unavailable")) };
530
+ /** ids returns the content hash of each quad, sorted for set comparison. */
531
+ function sortedIds(quads) {
532
+ return quads.map(hashQuad).sort();
533
+ }
534
+ /** storedIds returns the sorted hashes of the quads a subject stores. */
535
+ async function storedIds(subject) {
536
+ return sortedIds(await subject.storedQuads());
537
+ }
538
+ /** sameSet reports whether two sorted id lists are equal. */
539
+ function sameIds(a, b) {
540
+ return a.length === b.length && a.every((id, index) => id === b[index]);
541
+ }
542
+ /** insertPatch is a patch that inserts the given quads. */
543
+ function insertPatch(...quads) {
544
+ return {
545
+ insertions: quads,
546
+ deletions: []
547
+ };
548
+ }
549
+ /** mergeImport is the context of a merge-mode import. */
550
+ const mergeImport = { importMode: "merge" };
551
+ /** replaceImport is the context of a replace-mode import. */
552
+ const replaceImport = { importMode: "replace" };
553
+ /** rejects reports whether `run` rejected, without letting the error escape. */
554
+ async function rejects(run) {
555
+ try {
556
+ await run();
557
+ return false;
558
+ } catch {
559
+ return true;
560
+ }
561
+ }
562
+ // src/testing/commit-conformance-failure-cases.ts
563
+ /** an embedding failure rejects the commit and writes nothing. */
564
+ async function embeddingFailureCase(ctx) {
565
+ const subject = await ctx.create({
566
+ searchIndexOnImport: "incremental",
567
+ embeddingService: failingEmbeddings
568
+ });
569
+ const failed = await rejects(() => subject.commit(insertPatch(fixtureQuads.one), mergeImport));
570
+ const stored = (await subject.storedQuads()).length;
571
+ const chunks = (await subject.chunkedQuadIds()).length;
572
+ if (!failed) ctx.fail("embedding failure: expected the commit to reject");
573
+ if (stored !== 0 || chunks !== 0) ctx.fail(`embedding failure: nothing may be written, found ${stored} quads and ${chunks} chunks`);
574
+ }
575
+ /** a failed write leaves no orphan chunks, and nothing new at all when atomic. */
576
+ async function writeFailureCase(ctx) {
577
+ const subject = await ctx.create({
578
+ searchIndexOnImport: "incremental",
579
+ embeddingService: workingEmbeddings
580
+ });
581
+ await subject.commit(insertPatch(fixtureQuads.base), mergeImport);
582
+ subject.failNextWrite();
583
+ if (!await rejects(() => subject.commit(insertPatch(fixtureQuads.one, fixtureQuads.two), mergeImport))) ctx.fail("write failure: expected the commit to reject");
584
+ const stored = await storedIds(subject);
585
+ const chunked = [...new Set(await subject.chunkedQuadIds())].sort();
586
+ if (!stored.includes(sortedIds([fixtureQuads.base])[0])) ctx.fail("write failure: the previously committed quad must survive");
587
+ if (ctx.contract.atomic) {
588
+ if (!sameIds(stored, sortedIds([fixtureQuads.base])) || !sameIds(chunked, sortedIds([fixtureQuads.base]))) ctx.fail("write failure: an atomic backend must leave exactly the prior state");
589
+ } else if (chunked.some((id) => !stored.includes(id))) ctx.fail("write failure: a chunk row refers to a quad that is not stored");
590
+ }
591
+ /** a failed replace import leaves the old graph or an empty one, as declared, never orphans. */
592
+ async function replaceFailureCase(ctx) {
593
+ const subject = await ctx.create({
594
+ searchIndexOnImport: "incremental",
595
+ embeddingService: workingEmbeddings
596
+ });
597
+ await subject.commit(insertPatch(fixtureQuads.base, fixtureQuads.three), mergeImport);
598
+ subject.failNextWrite();
599
+ if (!await rejects(() => subject.commit(insertPatch(fixtureQuads.one), replaceImport))) ctx.fail("replace failure: expected the import to reject");
600
+ const stored = await storedIds(subject);
601
+ const chunked = [...new Set(await subject.chunkedQuadIds())].sort();
602
+ const expected = ctx.contract.replaceImportFailure === "keeps-old-graph" ? sortedIds([fixtureQuads.base, fixtureQuads.three]) : [];
603
+ if (!sameIds(stored, expected) || !sameIds(chunked, expected)) ctx.fail(`replace failure: declared "${ctx.contract.replaceImportFailure}" expects ${expected.length} quads and chunks, found ${stored.length} quads and ${chunked.length} chunked`);
604
+ }
605
+ /** a quad deleted and re-inserted in one patch stays stored, with its chunk. */
606
+ async function deleteAndReinsertCase(ctx) {
607
+ const subject = await ctx.create({
608
+ searchIndexOnImport: "incremental",
609
+ embeddingService: workingEmbeddings
610
+ });
611
+ await subject.commit(insertPatch(fixtureQuads.base), mergeImport);
612
+ await subject.commit({
613
+ insertions: [fixtureQuads.base],
614
+ deletions: [fixtureQuads.base]
615
+ });
616
+ if (!sameIds(await storedIds(subject), sortedIds([fixtureQuads.base]))) ctx.fail("delete + re-insert: the quad must remain stored exactly once");
617
+ if (!(await subject.chunkedQuadIds()).includes(sortedIds([fixtureQuads.base])[0])) ctx.fail("delete + re-insert: the quad must keep a chunk row");
618
+ }
619
+ // src/testing/commit-conformance-mode-cases.ts
620
+ const textual = [fixtureQuads.one, fixtureQuads.two];
621
+ /** importAll merges the fixture import into a fresh subject under `mode`. */
622
+ async function importAll(ctx, mode) {
623
+ const subject = await ctx.create({
624
+ searchIndexOnImport: mode,
625
+ embeddingService: workingEmbeddings
626
+ });
627
+ await subject.commit(insertPatch(fixtureQuads.one, fixtureQuads.two, fixtureQuads.link), mergeImport);
628
+ return subject;
629
+ }
630
+ /** expectStoredAll fails unless the import wrote all three fixture quads. */
631
+ async function expectStoredAll(ctx, subject) {
632
+ if (!sameIds(await storedIds(subject), sortedIds([
633
+ fixtureQuads.one,
634
+ fixtureQuads.two,
635
+ fixtureQuads.link
636
+ ]))) ctx.fail("an import must store every inserted quad");
637
+ }
638
+ /** incremental projects chunks for textual quads during the import itself. */
639
+ async function incrementalCase(ctx) {
640
+ const subject = await importAll(ctx, "incremental");
641
+ await expectStoredAll(ctx, subject);
642
+ if (!sameIds((await subject.chunkedQuadIds()).sort(), sortedIds(textual))) ctx.fail("incremental: expected one chunk per textual quad and none for IRI objects");
643
+ if (subject.fullRebuildCount() !== 0) ctx.fail("incremental: must not run a full rebuild");
644
+ }
645
+ /** disabled stores quads and writes no chunks, even for ordinary commits. */
646
+ async function disabledCase(ctx) {
647
+ const subject = await importAll(ctx, "disabled");
648
+ await expectStoredAll(ctx, subject);
649
+ await subject.commit(insertPatch(fixtureQuads.three));
650
+ if ((await subject.chunkedQuadIds()).length !== 0) ctx.fail("disabled: no chunk rows may be written, for imports or ordinary commits");
651
+ if (subject.fullRebuildCount() !== 0) ctx.fail("disabled: must not run a full rebuild");
652
+ }
653
+ /** deferred rebuilds once after an import and projects ordinary commits directly. */
654
+ async function deferredCase(ctx) {
655
+ const subject = await importAll(ctx, "deferred");
656
+ await expectStoredAll(ctx, subject);
657
+ if (subject.fullRebuildCount() !== 1) ctx.fail("deferred: an import must trigger exactly one full rebuild");
658
+ if (!sameIds((await subject.chunkedQuadIds()).sort(), sortedIds(textual))) ctx.fail("deferred: the rebuild must leave one chunk per textual quad");
659
+ await subject.commit(insertPatch(fixtureQuads.three));
660
+ if (subject.fullRebuildCount() !== 1) ctx.fail("deferred: an ordinary commit must not trigger a rebuild");
661
+ if (!(await subject.chunkedQuadIds()).includes(sortedIds([fixtureQuads.three])[0])) ctx.fail("deferred: an ordinary commit must project its own chunks");
662
+ }
663
+ /** the default mode (option unset) behaves as the contract declares. */
664
+ async function defaultModeCase(ctx) {
665
+ const declared = ctx.contract.defaultSearchIndexOnImport;
666
+ const subject = await importAll(ctx, void 0);
667
+ const chunked = (await subject.chunkedQuadIds()).length;
668
+ const rebuilds = subject.fullRebuildCount();
669
+ const expected = {
670
+ incremental: {
671
+ chunked: textual.length,
672
+ rebuilds: 0
673
+ },
674
+ deferred: {
675
+ chunked: textual.length,
676
+ rebuilds: 1
677
+ },
678
+ disabled: {
679
+ chunked: 0,
680
+ rebuilds: 0
681
+ }
682
+ }[declared];
683
+ if (chunked !== expected.chunked || rebuilds !== expected.rebuilds) ctx.fail(`default mode: declared "${declared}" expects ${expected.chunked} chunks and ${expected.rebuilds} rebuilds, got ${chunked} and ${rebuilds}`);
684
+ }
685
+ /** writing a stored quad again changes nothing. */
686
+ async function idempotentCase(ctx) {
687
+ const subject = await ctx.create({
688
+ searchIndexOnImport: "incremental",
689
+ embeddingService: workingEmbeddings
690
+ });
691
+ await subject.commit(insertPatch(fixtureQuads.one), mergeImport);
692
+ const before = (await subject.chunkedQuadIds()).length;
693
+ await subject.commit(insertPatch(fixtureQuads.one), mergeImport);
694
+ if (!sameIds(await storedIds(subject), sortedIds([fixtureQuads.one]))) ctx.fail("re-inserting a stored quad must leave it stored exactly once");
695
+ if ((await subject.chunkedQuadIds()).length !== before) ctx.fail("re-inserting a stored quad must not duplicate its chunk rows");
696
+ }
697
+ // src/testing/commit-conformance-later-write-case.ts
698
+ /**
699
+ * a failure in a write after the quad writes either rolls the quads back
700
+ * (atomic) or is cleaned up, as declared. Skipped without `failLaterWrite`.
701
+ */
702
+ async function laterWriteFailureCase(ctx) {
703
+ const subject = await ctx.create({
704
+ searchIndexOnImport: "incremental",
705
+ embeddingService: workingEmbeddings
706
+ });
707
+ if (!subject.failLaterWrite) {
708
+ ctx.skip("later-write failure: skipped, the subject does not implement failLaterWrite");
709
+ return;
710
+ }
711
+ await subject.commit(insertPatch(fixtureQuads.base), mergeImport);
712
+ subject.failLaterWrite();
713
+ if (!await rejects(() => subject.commit(insertPatch(fixtureQuads.one, fixtureQuads.two), mergeImport))) ctx.fail("later-write failure: expected the commit to reject");
714
+ const stored = await storedIds(subject);
715
+ const chunked = [...new Set(await subject.chunkedQuadIds())].sort();
716
+ const prior = sortedIds([fixtureQuads.base]);
717
+ const keeps = !ctx.contract.atomic && ctx.contract.laterWriteFailure === "keeps-written-quads";
718
+ if (!stored.includes(prior[0])) ctx.fail("later-write failure: the previously committed quad must survive");
719
+ if (!keeps && (!sameIds(stored, prior) || !sameIds(chunked, prior))) ctx.fail(`later-write failure: expected exactly the prior state (${ctx.contract.atomic ? "atomic backends roll back" : "cleanup removes"} the failed commit), found ${stored.length} quads and ${chunked.length} chunked`);
720
+ else if (chunked.some((id) => !stored.includes(id))) ctx.fail("later-write failure: a chunk row refers to a quad that is not stored");
721
+ await subject.commit(insertPatch(fixtureQuads.one), mergeImport);
722
+ const after = await storedIds(subject);
723
+ if (![fixtureQuads.base, fixtureQuads.one].every((quad) => after.includes(sortedIds([quad])[0]))) ctx.fail("later-write failure: the store must accept a commit afterwards");
724
+ }
725
+ // src/testing/run-commit-conformance.ts
726
+ /** conformanceCases lists every case; the key is the name reported on failure. */
727
+ const conformanceCases = [
728
+ ["incremental import projects chunks", incrementalCase],
729
+ ["disabled import writes no chunks", disabledCase],
730
+ ["deferred import rebuilds once", deferredCase],
731
+ ["default mode matches the contract", defaultModeCase],
732
+ ["re-writing a stored quad is idempotent", idempotentCase],
733
+ ["delete and re-insert keeps the quad", deleteAndReinsertCase],
734
+ ["embedding failure follows the contract", embeddingFailureCase],
735
+ ["write failure leaves no orphan chunks", writeFailureCase],
736
+ ["replace-import failure follows the contract", replaceFailureCase],
737
+ ["later-write failure follows the contract", laterWriteFailureCase]
738
+ ];
739
+ /**
740
+ * runCommitConformanceSuite checks one backend's commit and search-projection
741
+ * behavior against the shared contract: the `searchIndexOnImport` modes, the
742
+ * default mode, idempotent and delete-then-re-add writes, and what an embedding
743
+ * failure, a failed write, a failed replace import, and a failed later write
744
+ * (after the quad writes) leave behind.
745
+ *
746
+ * The later-write case needs the optional subject hook `failLaterWrite`. A
747
+ * subject without it keeps all other cases unchanged: the case is left out of
748
+ * `results` and the reason is added to `report.notes`.
749
+ *
750
+ * Each case runs on a fresh subject from `options.create`. The result has the
751
+ * same shape as `runParitySuite`'s report: assert `report.ok`, and print
752
+ * `failures` per case when it is false. A case that throws unexpectedly fails.
753
+ */
754
+ async function runCommitConformanceSuite(options) {
755
+ const results = [];
756
+ const notes = [];
757
+ for (const [name, run] of conformanceCases) {
758
+ const failures = [];
759
+ const skipped = [];
760
+ const ctx = {
761
+ ...options,
762
+ fail: (m) => failures.push(m),
763
+ skip: (note) => skipped.push(note)
764
+ };
765
+ try {
766
+ await run(ctx);
767
+ } catch (error) {
768
+ failures.push(`threw unexpectedly: ${error?.message ?? error}`);
769
+ }
770
+ if (skipped.length > 0 && failures.length === 0) {
771
+ notes.push(...skipped.map((note) => `${name}: ${note}`));
772
+ continue;
773
+ }
774
+ results.push({
775
+ name,
776
+ ok: failures.length === 0,
777
+ failures
778
+ });
779
+ }
780
+ return {
781
+ ok: results.every((r) => r.ok),
782
+ results,
783
+ ...notes.length && { notes }
784
+ };
785
+ }
786
+ export { chunkBoundaryWorld, emptyWorld, multiGraphWorld, parityCorpus, rdfStarWorld, replaceModeCase, runCommitConformanceSuite, runParitySuite, typedLiteralsWorld };