koota-kit 0.8.6 → 0.8.8

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.
@@ -0,0 +1,390 @@
1
+ import assert from "node:assert/strict";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
4
+ import { dirname, join, relative, sep } from "node:path";
5
+ import { performance } from "node:perf_hooks";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import { createProofCohort, PROOF_FRAME } from "./cohort.mjs";
8
+ import { loadFigureFixture } from "./fixture.mjs";
9
+ import { IDENTITY } from "./open-surface.mjs";
10
+ import { observeCommittedUpdate } from "./react-observer.mjs";
11
+
12
+ const [fixtureDirectory, consumerDirectory, output] = process.argv.slice(2);
13
+ if (!fixtureDirectory || !consumerDirectory)
14
+ throw new Error(
15
+ "Usage: node examples/coordination-proof/run.mjs <fixture-dir> <registry-consumer-dir> [receipt.json]",
16
+ );
17
+ const { registryImport: importInstalled, registryResolve } = await import(
18
+ pathToFileURL(join(consumerDirectory, "registry-import.mjs")).href
19
+ );
20
+ const importedFiles = new Map();
21
+ async function registryImport(specifier) {
22
+ const path = relative(consumerDirectory, fileURLToPath(registryResolve(specifier)));
23
+ assert.ok(
24
+ path.split(sep)[0] === "node_modules",
25
+ "registry import escaped the independent consumer",
26
+ );
27
+ const module = await importInstalled(specifier);
28
+ importedFiles.set(specifier, path);
29
+ return module;
30
+ }
31
+ const { createWorld, trait } = await registryImport("koota");
32
+ const { bindCoordination } = await registryImport("koota-kit/coordination");
33
+ const { queryPointClearance } = await registryImport("koota-kit/spatial");
34
+ const { AIBridge } = await registryImport("yuka-kit/koota");
35
+ const { Vehicle } = await registryImport("yuka");
36
+ const { createSeededTerrainField } = await registryImport("strata-procedural/terrain");
37
+ const React = await registryImport("react");
38
+ const { renderToStaticMarkup } = await registryImport("react-dom/server");
39
+ const { WorldProvider, useWorld } = await registryImport("koota/react");
40
+
41
+ const Position = trait({ x: 0, y: 0, z: 0 });
42
+ const Velocity = trait({ x: 0, y: 0, z: 0 });
43
+ const Intent = trait({ clearance: "unqueried", geometry: 0, topology: 0, pose: 0, transform: 0 });
44
+ const ModelKind = trait({ value: "" });
45
+ const world = createWorld();
46
+ const proceduralEntity = world.spawn(
47
+ Position,
48
+ Velocity,
49
+ Intent,
50
+ ModelKind({ value: "procedural" }),
51
+ );
52
+ const figureEntity = world.spawn(Position, Velocity, Intent, ModelKind({ value: "figure" }));
53
+ const unrelated = world.spawn(Position({ x: 123, y: 456, z: 789 }));
54
+ const coordination = bindCoordination(world);
55
+ assert.equal(coordination.world, world);
56
+ const figure = await loadFigureFixture(fixtureDirectory);
57
+ const field = createSeededTerrainField({
58
+ seed: "two-model-proof",
59
+ biomes: [{ type: "marsh", center: [0, 0], radius: 10 }],
60
+ });
61
+ const terrain = field.createHeightfield({ width: 5, depth: 5, cellSize: 0.5 });
62
+ // An application anchor on real published Strata geometry, not a claimed Strata anchor API.
63
+ const anchorVertex = 12 * 3;
64
+ const anchor = Object.freeze({
65
+ id: "caller-terrain-center",
66
+ x: terrain.positions[anchorVertex],
67
+ y: terrain.positions[anchorVertex + 1],
68
+ z: terrain.positions[anchorVertex + 2],
69
+ });
70
+ const specifications = [
71
+ {
72
+ id: "model-a",
73
+ entity: proceduralEntity,
74
+ sourceId: "strata-procedural@0.1.0",
75
+ instanceId: "terrain-a",
76
+ providerGeneration: 1,
77
+ },
78
+ {
79
+ id: "model-b",
80
+ entity: figureEntity,
81
+ sourceId: "copied-humanoid-fixture",
82
+ instanceId: "figure-b",
83
+ providerGeneration: 1,
84
+ },
85
+ ];
86
+ const cohort = createProofCohort(coordination, specifications);
87
+ const diagnostics = [];
88
+ const measurements = {
89
+ candidateSelectionMs: 0,
90
+ queryMs: 0,
91
+ exactOracleMs: 0,
92
+ queryExcludingOracleMs: 0,
93
+ oracleCalls: 0,
94
+ publicationMs: 0,
95
+ };
96
+ const selectionStart = performance.now();
97
+ assert.equal(world.query(ModelKind).length, 2);
98
+ measurements.candidateSelectionMs = performance.now() - selectionStart;
99
+ function publish(updates) {
100
+ const start = performance.now();
101
+ try {
102
+ return cohort.publish(updates);
103
+ } finally {
104
+ measurements.publicationMs += performance.now() - start;
105
+ }
106
+ }
107
+ function clearance(query) {
108
+ const capture = cohort.capture();
109
+ const start = performance.now();
110
+ let oracleMs = 0;
111
+ const oracle = {
112
+ nearest(request) {
113
+ const start = performance.now();
114
+ measurements.oracleCalls += 1;
115
+ try {
116
+ return capture.oracle.nearest(request);
117
+ } finally {
118
+ oracleMs += performance.now() - start;
119
+ }
120
+ },
121
+ };
122
+ try {
123
+ return queryPointClearance(capture.provider, oracle, query);
124
+ } finally {
125
+ const total = performance.now() - start;
126
+ measurements.queryMs += total;
127
+ measurements.exactOracleMs += oracleMs;
128
+ measurements.queryExcludingOracleMs += total - oracleMs;
129
+ diagnostics.push(...capture.getDiagnostics());
130
+ capture.release();
131
+ }
132
+ }
133
+ const partsForPose = (pose) =>
134
+ figure.parts.map((part) => ({
135
+ id: part.id,
136
+ positions: part.poses[pose].positions,
137
+ full: part.full,
138
+ visible: part.visible,
139
+ fullTopologyId: `${part.geometryHash}/full`,
140
+ visibleTopologyId: `${part.geometryHash}/visible`,
141
+ }));
142
+ let figureUpdate = {
143
+ id: "model-b",
144
+ revisions: { geometry: 0, topology: 0, pose: 0, transform: 0 },
145
+ toWorld: [...IDENTITY],
146
+ parts: partsForPose("relaxed"),
147
+ };
148
+ const terrainUpdate = {
149
+ id: "model-a",
150
+ revisions: { geometry: 0, topology: 0, pose: 0, transform: 0 },
151
+ toWorld: [...IDENTITY],
152
+ parts: [
153
+ {
154
+ id: "heightfield",
155
+ positions: terrain.positions,
156
+ full: terrain.indices,
157
+ visible: terrain.indices,
158
+ fullTopologyId: "seeded-heightfield/full",
159
+ visibleTopologyId: "seeded-heightfield/visible",
160
+ },
161
+ ],
162
+ };
163
+ const start = performance.now();
164
+ publish([terrainUpdate, figureUpdate]);
165
+ assert.equal(coordination.getEntity("model-a"), proceduralEntity);
166
+ assert.equal(coordination.getEntity("model-b"), figureEntity);
167
+ const base = cohort.getSnapshot();
168
+ const terrainStamp = base.records.find((record) => record.identity.instanceId === "terrain-a");
169
+ const query = {
170
+ point: { x: 0, y: 1, z: 0 },
171
+ frame: PROOF_FRAME,
172
+ minimumDistance: 3,
173
+ searchDistance: 10,
174
+ };
175
+ const oldLease = cohort.capture();
176
+ const first = clearance(query);
177
+ assert.equal(first.status, "violated");
178
+ assert.ok(first.witnesses.length > 0);
179
+ const trace = [];
180
+ const bridge = new AIBridge({ Position, Velocity });
181
+ const vehicle = new Vehicle();
182
+ figureEntity.set(Position, { x: 0, y: 1, z: 0 });
183
+ trace.push("caller-position");
184
+ bridge.syncFromKoota(vehicle, figureEntity);
185
+ trace.push("bridge-sync-from");
186
+ assert.equal(vehicle.position.y, 1);
187
+ const figureStamp = first.checked.find((stamp) => stamp.identity.instanceId === "figure-b");
188
+ figureEntity.set(Intent, { clearance: first.status, ...figureStamp.revisions });
189
+ trace.push("caller-stamped-intent");
190
+ // The caller behavior reads the same stamped surface predicate; this is not navigation.
191
+ const intent = figureEntity.get(Intent);
192
+ assert.deepEqual(
193
+ {
194
+ geometry: intent.geometry,
195
+ topology: intent.topology,
196
+ pose: intent.pose,
197
+ transform: intent.transform,
198
+ },
199
+ figureStamp.revisions,
200
+ );
201
+ vehicle.velocity.set(intent.clearance === "violated" ? -1 : 1, 0, 0);
202
+ trace.push("caller-ai-behavior");
203
+ bridge.syncToKoota(vehicle, figureEntity);
204
+ trace.push("bridge-sync-to");
205
+ assert.equal(figureEntity.get(Velocity).x, -1);
206
+ assert.equal(figureEntity.get(Position).y, 1);
207
+
208
+ const steps = [];
209
+ for (const epoch of ["pose", "transform", "topology", "geometry"]) {
210
+ const revisions = { ...figureUpdate.revisions, [epoch]: figureUpdate.revisions[epoch] + 1 };
211
+ // Topology affects geometry identity and is invalidated explicitly in both contracts.
212
+ if (epoch === "topology") revisions.geometry += 1;
213
+ figureUpdate = { ...figureUpdate, revisions };
214
+ if (epoch === "pose") figureUpdate.parts = partsForPose("overhead");
215
+ if (epoch === "transform") {
216
+ figureUpdate.toWorld = [...IDENTITY];
217
+ figureUpdate.toWorld[0] = 1.7;
218
+ figureUpdate.toWorld[5] = 0.8;
219
+ figureUpdate.toWorld[12] = 0.25;
220
+ }
221
+ if (epoch === "topology")
222
+ figureUpdate.parts = figureUpdate.parts.map((part) => ({
223
+ ...part,
224
+ visible: part.visible.subarray(0, part.visible.length - 3),
225
+ visibleTopologyId: `${part.visibleTopologyId}/mask-1`,
226
+ }));
227
+ publish([figureUpdate]);
228
+ const currentTerrain = cohort
229
+ .getSnapshot()
230
+ .records.find((record) => record.identity.instanceId === "terrain-a");
231
+ assert.equal(currentTerrain, terrainStamp);
232
+ const stale = clearance({
233
+ ...query,
234
+ expected: first.checked,
235
+ });
236
+ assert.equal(stale.status, "stale");
237
+ const fresh = clearance(query);
238
+ assert.equal(fresh.status, "violated");
239
+ steps.push({ epoch, revisions, stale: stale.status, fresh: fresh.status });
240
+ }
241
+ assert.deepEqual(queryPointClearance(oldLease.provider, oldLease.oracle, query), first);
242
+ oldLease.release();
243
+ const beforeFailed = cohort.getSnapshot();
244
+ assert.throws(() =>
245
+ cohort.publish([{ ...figureUpdate, revisions: { ...figureUpdate.revisions, pose: -1 } }]),
246
+ );
247
+ assert.equal(cohort.getSnapshot(), beforeFailed);
248
+ assert.equal(coordination.getSnapshot(), beforeFailed.coordination);
249
+ const disabled = {
250
+ ...figureUpdate,
251
+ revisions: { ...figureUpdate.revisions, geometry: figureUpdate.revisions.geometry + 1 },
252
+ parts: figureUpdate.parts.map((part) => ({ ...part, nearestSurface: false })),
253
+ };
254
+ publish([disabled]);
255
+ const exclusions = cohort
256
+ .getSnapshot()
257
+ .records.filter((record) => record.identity.instanceId === "terrain-a")
258
+ .map((record) => record.identity);
259
+ assert.equal(clearance({ ...query, exclusions }).status, "unsupported");
260
+ figureUpdate = {
261
+ ...figureUpdate,
262
+ revisions: { ...disabled.revisions, geometry: disabled.revisions.geometry + 1 },
263
+ };
264
+ publish([figureUpdate]);
265
+ const selectedRecords = cohort.getSnapshot().records;
266
+ const bodyRecord = selectedRecords.find(
267
+ (record) => record.identity.instanceId === "figure-b" && record.identity.partId === "body",
268
+ );
269
+ assert.ok(bodyRecord, "expected a body record for figure-b");
270
+ const bodyIdentity = bodyRecord.identity;
271
+ const partExclusion = clearance({ ...query, exclusions: [...exclusions, bodyIdentity] });
272
+ assert.equal(partExclusion.status, "violated");
273
+ assert.equal(partExclusion.checked.length, 1);
274
+ assert.equal(partExclusion.checked[0].identity.partId, figure.parts[1].id);
275
+ assert.ok(
276
+ partExclusion.witnesses.every(
277
+ (witness) => witness.consumed.identity.partId === figure.parts[1].id,
278
+ ),
279
+ );
280
+
281
+ let observedWorld;
282
+ function Inspector() {
283
+ observedWorld = useWorld();
284
+ const snapshot = React.useSyncExternalStore(
285
+ cohort.subscribe,
286
+ cohort.getSnapshot,
287
+ cohort.getSnapshot,
288
+ );
289
+ return React.createElement(
290
+ "output",
291
+ null,
292
+ snapshot.coordination.entries.map((entry) => entry.id).join(","),
293
+ );
294
+ }
295
+ const markup = renderToStaticMarkup(
296
+ React.createElement(WorldProvider, { world }, React.createElement(Inspector)),
297
+ );
298
+ assert.equal(observedWorld, world);
299
+ assert.equal(markup, "<output>model-a,model-b</output>");
300
+ figureUpdate = {
301
+ ...figureUpdate,
302
+ revisions: { ...figureUpdate.revisions, pose: figureUpdate.revisions.pose + 1 },
303
+ };
304
+ const mountedReact = await observeCommittedUpdate({
305
+ registryImport,
306
+ cohort,
307
+ world,
308
+ publish: () => publish([figureUpdate]),
309
+ });
310
+ assert.ok(diagnostics.every((witness) => witness.barycentric.length === 3));
311
+ const elapsedMs = performance.now() - start;
312
+ const retainedStamp = first.checked;
313
+ const disposalLease = cohort.capture();
314
+ cohort.dispose();
315
+ assert.throws(() => cohort.capture(), /disposed/);
316
+ assert.equal(
317
+ queryPointClearance(disposalLease.provider, disposalLease.oracle, {
318
+ ...query,
319
+ expected: retainedStamp,
320
+ }).status,
321
+ "stale",
322
+ );
323
+ disposalLease.release();
324
+ assert.ok(world.has(proceduralEntity) && world.has(figureEntity) && world.has(unrelated));
325
+ assert.equal(unrelated.get(Position).x, 123);
326
+ assert.ok(
327
+ figureEntity.has(Position) &&
328
+ figureEntity.has(Velocity) &&
329
+ figureEntity.has(Intent) &&
330
+ figureEntity.has(ModelKind),
331
+ );
332
+ coordination.dispose();
333
+ assert.ok(world.isInitialized);
334
+ const packages = JSON.parse(await readFile(join(consumerDirectory, "package.json"), "utf8"));
335
+ const lockBytes = await readFile(join(consumerDirectory, "package-lock.json"));
336
+ const lock = JSON.parse(lockBytes.toString("utf8"));
337
+ const installed = {};
338
+ for (const [name, version] of Object.entries(packages.dependencies)) {
339
+ const metadata = JSON.parse(
340
+ await readFile(join(consumerDirectory, "node_modules", name, "package.json"), "utf8"),
341
+ );
342
+ const entry = lock.packages[`node_modules/${name}`];
343
+ assert.equal(metadata.version, version);
344
+ assert.equal(entry.version, version);
345
+ assert.ok(entry.resolved.startsWith("https://registry.npmjs.org/"));
346
+ installed[name] = { version, integrity: entry.integrity, resolved: entry.resolved };
347
+ }
348
+ const report = {
349
+ scope:
350
+ "registry caller-composition proof; copied HK fixture only; open-surface clearance; mounted and server React observation, no GPU parity",
351
+ packages: packages.dependencies,
352
+ installed,
353
+ consumerLockSha256: createHash("sha256").update(lockBytes).digest("hex"),
354
+ imports: Object.fromEntries([...importedFiles.entries()].sort()),
355
+ node: process.version,
356
+ inputs: figure.inputs,
357
+ anchor,
358
+ trace,
359
+ steps,
360
+ first,
361
+ partExclusion,
362
+ witnessDiagnostics: diagnostics.slice(0, 3),
363
+ elapsedMs,
364
+ measurements,
365
+ mountedReact,
366
+ lifecyclePreserved: true,
367
+ sameRawWorldObserved: true,
368
+ };
369
+ if (output) {
370
+ await mkdir(dirname(output), { recursive: true });
371
+ await writeFile(output, `${JSON.stringify(report, null, 2)}\n`);
372
+ }
373
+ console.log(
374
+ JSON.stringify(
375
+ {
376
+ scope: report.scope,
377
+ packages: report.packages,
378
+ trace,
379
+ steps,
380
+ elapsedMs,
381
+ measurements,
382
+ mountedReact,
383
+ lifecyclePreserved: true,
384
+ sameRawWorldObserved: true,
385
+ },
386
+ null,
387
+ 2,
388
+ ),
389
+ );
390
+ world.destroy();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koota-kit",
3
- "version": "0.8.6",
3
+ "version": "0.8.8",
4
4
  "description": "Deterministic Koota simulation conventions: world lifecycle, dual RNG streams, safe object traits, and world-scoped event logs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -122,6 +122,7 @@
122
122
  "dist",
123
123
  "docs/API.md",
124
124
  "docs/ARCHITECTURE.md",
125
+ "docs/INTEGRATION_PROOF.md",
125
126
  "docs/assets",
126
127
  "examples"
127
128
  ],