Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

feat(composer): add canonical WorldDocumentV2 contract (#27)

Matthew Kissingerf8ea704a19b1
diff --git a/README.md b/README.md
index 9ac138e1..e789d5b1 100644
--- a/README.md
+++ b/README.md
@@ -61,7 +61,7 @@ The engine ships TypeScript source (Bun/tsx transpile on the fly); consume by su
| `@kiln/engine/prompt`, `/prompt-api`, `/list-primitives` | system-prompt generation + catalog |
| `@kiln/engine/metrics`, `/inspect` | instanceability grade + scene-structure analysis |
| `@kiln/engine/contracts` | browser-safe asset and integration contracts, including `IntegrationManifestV1` and the semantic role vocabulary (`KILN_SEMANTIC_ROLES`, `semanticRole`, `semanticRoleMatches`, `hasSemanticRole`) |
-| `@kiln/engine/composer`, `/composer/agent` | THREE-free scene-composition core (placement model, layout, overlap, DSL) + its Strands agent loop (`runKilnComposer`) |
+| `@kiln/engine/composer`, `/composer/agent` | THREE-free scene-composition core (canonical `WorldDocumentV2`, deterministic v1 migration/hash/projection, placement model, layout, overlap, DSL) + its Strands agent loop (`runKilnComposer`) |
Finished renders include `integrationManifest`, a versioned sidecar with the artifact
hash, metres/+Y-up axes, bounds, grounding offset, selected default scene, role, render
diff --git a/src/composer/index.ts b/src/composer/index.ts
index 30580a5e..3813039e 100644
--- a/src/composer/index.ts
+++ b/src/composer/index.ts
@@ -10,3 +10,4 @@ export * from './layout';
export * from './model';
export * from './overlap';
export * from './render-port';
+export * from './world-document';
diff --git a/src/composer/model.ts b/src/composer/model.ts
index c0a70d4d..75ef3759 100644
--- a/src/composer/model.ts
+++ b/src/composer/model.ts
@@ -480,8 +480,17 @@ export class PlacementModel {
if (m.scale != null) st.scale = m.scale;
const apply = (cur: Vec2): Vec2 =>
m.to ? [m.to[0], m.to[1]] : m.delta ? [cur[0] + m.delta[0], cur[1] + m.delta[1]] : cur;
- if (st.kind === 'place') st.at = apply(st.at);
- else if (st.kind === 'cluster') st.around = apply(st.around);
+ if (st.kind === 'place') {
+ if (st.exact) {
+ const next = apply([st.exact.pos[0], st.exact.pos[2]]);
+ // Exact is the evaluated authority for a look-preserving import. Keep its
+ // XZ in lockstep with the editable projection while preserving exact Y.
+ st.exact.pos = [next[0], st.exact.pos[1], next[1]];
+ st.at = [next[0], next[1]];
+ } else {
+ st.at = apply(st.at);
+ }
+ } else if (st.kind === 'cluster') st.around = apply(st.around);
else st.center = apply(st.center);
return { ok: true, alias: st.alias };
}
@@ -491,7 +500,12 @@ export class PlacementModel {
if (!st) return notFound(target);
if (st.kind === 'ring') st.faceOut = intent === 'out';
else if (st.kind === 'cluster') st.face = intent === 'out' ? 'out' : 'center';
- else st.face = intent;
+ else {
+ st.face = intent;
+ if (st.exact) {
+ st.exact.rotYDeg = facingToRotY(intent, [st.exact.pos[0], st.exact.pos[2]], SCENE_CENTER);
+ }
+ }
return { ok: true, alias: st.alias };
}
diff --git a/src/composer/world-document.test.ts b/src/composer/world-document.test.ts
new file mode 100644
index 00000000..73e5362e
--- /dev/null
+++ b/src/composer/world-document.test.ts
@@ -0,0 +1,499 @@
+import { createHash } from 'node:crypto';
+import { describe, expect, test } from 'bun:test';
+import { facingToRotY } from './layout';
+import type { SceneModelJSON } from './model';
+import { PlacementModel } from './model';
+import {
+ WORLD_DOCUMENT_V2_SCHEMA_VERSION,
+ canonicalWorldDocumentV2Json,
+ hashWorldDocumentV2,
+ migrateSceneModelV1ToWorldDocumentV2,
+ parseWorldDocumentV2,
+ reconcileWorldDocumentV2Objects,
+ safeParseWorldDocumentV2,
+ worldDocumentV2ToSceneModelJSON,
+} from './world-document';
+
+const HOUSE_SHA = '1'.repeat(64);
+const TREE_SHA = '2'.repeat(64);
+
+function v1Model(): SceneModelJSON {
+ return {
+ name: 'Exact legacy scene',
+ seed: 17,
+ catalog: [
+ {
+ generationId: 'house',
+ name: 'House',
+ bbox: { min: [-2, -0.25, -3], max: [4, 6, 3] },
+ role: 'building',
+ tier: 'B',
+ },
+ {
+ generationId: 'tree',
+ name: 'Tree',
+ bbox: { min: [-1, 0, -1], max: [1, 8, 1] },
+ tags: ['vegetation'],
+ role: 'fill',
+ },
+ ],
+ statements: [
+ {
+ kind: 'place',
+ stmtId: 's4',
+ alias: 'house_exact',
+ generationId: 'house',
+ role: 'hero',
+ scale: 1.125,
+ at: [12.3456789, -9.25],
+ face: -37.75,
+ exact: { pos: [12.3456789, 0.03125, -9.25], rotYDeg: -37.75 },
+ provenance: { sourcePrompt: 'Put the house on the ridge.' },
+ },
+ {
+ kind: 'ring',
+ stmtId: 's9',
+ alias: 'trees',
+ generationId: 'tree',
+ role: 'fill',
+ scale: 0.85,
+ center: [0, 0],
+ count: 3,
+ radius: 20,
+ faceOut: true,
+ group: 'grove',
+ },
+ ],
+ environment: 'edo',
+ backdrop: { kind: 'fuji', pos: [0, 0, -80], scale: 1.5 },
+ paint: [
+ {
+ kind: 'stone-path',
+ shape: { type: 'strip', axis: 'z', offset: 2, half: 1.5, from: -20, to: 20 },
+ },
+ ],
+ };
+}
+
+const migrationOptions = {
+ worldId: 'scene-123',
+ artifactSha256ByGenerationId: { house: HOUSE_SHA, tree: TREE_SHA },
+ lightingPresetId: 'legacy-scene-v1',
+} as const;
+
+describe('WorldDocumentV2 contract', () => {
+ test('migrates v1 deterministically and preserves every evaluated transform exactly', () => {
+ const source = v1Model();
+ const expected = PlacementModel.fromJSON(source).placements().placements;
+ const a = migrateSceneModelV1ToWorldDocumentV2(source, migrationOptions);
+ const b = migrateSceneModelV1ToWorldDocumentV2(source, migrationOptions);
+
+ expect(a).toEqual(b);
+ expect(a.schemaVersion).toBe(WORLD_DOCUMENT_V2_SCHEMA_VERSION);
+ expect(a.assets.map((asset) => [asset.generationId, asset.artifactSha256])).toEqual([
+ ['house', HOUSE_SHA],
+ ['tree', TREE_SHA],
+ ]);
+ expect(
+ a.objects.map((object) => ({
+ instanceId: object.id,
+ generationId: a.assets.find((asset) => asset.refId === object.assetRefId)!.generationId,
+ pos: object.transform.position,
+ rotYDeg: object.transform.rotationYDeg,
+ scale: object.transform.uniformScale,
+ stmtId: object.provenance.sourceStatementId,
+ })),
+ ).toEqual(expected);
+ expect(a.environment).toEqual({
+ presetId: 'edo',
+ lightingPresetId: 'legacy-scene-v1',
+ backdrop: source.backdrop,
+ groundPaint: source.paint!,
+ });
+ expect(a.terrain).toEqual({ kind: 'flat', height: 0 });
+ expect(a.authored).toEqual({ zones: [], paths: [], sockets: [] });
+ expect(a.collisionArtifacts).toEqual([]);
+ expect(a.spawns).toEqual([]);
+ });
+
+ test('projects canonical objects to exact v1 places for drift-free refine', () => {
+ const world = migrateSceneModelV1ToWorldDocumentV2(v1Model(), migrationOptions);
+ const projected = worldDocumentV2ToSceneModelJSON(world);
+ const placements = PlacementModel.fromJSON(projected).placements().placements;
+
+ expect(
+ placements.map(({ instanceId, generationId, pos, rotYDeg, scale }) => ({
+ instanceId,
+ generationId,
+ pos,
+ rotYDeg,
+ scale,
+ })),
+ ).toEqual(
+ world.objects.map((object) => ({
+ instanceId: object.id,
+ generationId: world.assets.find((asset) => asset.refId === object.assetRefId)!.generationId,
+ pos: object.transform.position,
+ rotYDeg: object.transform.rotationYDeg,
+ scale: object.transform.uniformScale,
+ })),
+ );
+ expect(
+ projected.statements.every((statement) => statement.kind === 'place' && statement.exact),
+ ).toBe(true);
+ expect(projected.environment).toBe('edo');
+ expect(projected.backdrop).toEqual(v1Model().backdrop);
+ expect(projected.paint).toEqual(v1Model().paint);
+ });
+
+ test('projected exact places remain editable through move, face, and group operations', () => {
+ const world = migrateSceneModelV1ToWorldDocumentV2(v1Model(), migrationOptions);
+ const model = PlacementModel.fromJSON(worldDocumentV2ToSceneModelJSON(world));
+ const before = new Map(
+ model.placements().placements.map((placement) => [placement.instanceId, placement]),
+ );
+
+ expect(model.move('house_exact', { delta: [7.25, -3.5], scale: 1.75 }).ok).toBe(true);
+ expect(model.face('house_exact', 42.125).ok).toBe(true);
+ const group = model.group(['trees#0', 'trees#1'], { name: 'moved-grove', delta: [4, -2] });
+ expect(group.ok).toBe(true);
+ expect(model.face('trees#0', 'center').ok).toBe(true);
+ expect(model.face('trees#1', [40, -10]).ok).toBe(true);
+
+ const after = new Map(
+ model.placements().placements.map((placement) => [placement.instanceId, placement]),
+ );
+ expect(after.get('house_exact')!.pos).toEqual([
+ before.get('house_exact')!.pos[0] + 7.25,
+ before.get('house_exact')!.pos[1],
+ before.get('house_exact')!.pos[2] - 3.5,
+ ]);
+ expect(after.get('house_exact')!.rotYDeg).toBe(42.125);
+ expect(after.get('house_exact')!.scale).toBe(1.75);
+
+ for (const id of ['trees#0', 'trees#1']) {
+ expect(after.get(id)!.pos).toEqual([
+ before.get(id)!.pos[0] + 4,
+ before.get(id)!.pos[1],
+ before.get(id)!.pos[2] - 2,
+ ]);
+ }
+ expect(after.get('trees#0')!.rotYDeg).toBe(
+ facingToRotY('center', [after.get('trees#0')!.pos[0], after.get('trees#0')!.pos[2]], [0, 0]),
+ );
+ expect(after.get('trees#1')!.rotYDeg).toBe(
+ facingToRotY([40, -10], [after.get('trees#1')!.pos[0], after.get('trees#1')!.pos[2]], [0, 0]),
+ );
+
+ const persisted = model.toJSON();
+ const house = persisted.statements.find((statement) => statement.alias === 'house_exact');
+ expect(house?.kind === 'place' && house.exact).toEqual({
+ pos: after.get('house_exact')!.pos,
+ rotYDeg: 42.125,
+ });
+ expect(
+ persisted.statements
+ .filter((statement) => statement.alias === 'trees#0' || statement.alias === 'trees#1')
+ .every((statement) => statement.group === 'moved-grove'),
+ ).toBe(true);
+ });
+
+ test('uses caller-supplied evaluated placements as the exact migration seam', () => {
+ const source = v1Model();
+ const placements = PlacementModel.fromJSON(source).placements().placements;
+ placements[0] = {
+ ...placements[0]!,
+ instanceId: 'host-authoritative-id',
+ pos: [1.234567890123, -2.5, 9.876543210987],
+ rotYDeg: 123.456789,
+ };
+ const world = migrateSceneModelV1ToWorldDocumentV2(source, {
+ ...migrationOptions,
+ placements,
+ });
+
+ expect(world.objects[0]).toMatchObject({
+ id: 'host-authoritative-id',
+ transform: {
+ position: [1.234567890123, -2.5, 9.876543210987],
+ rotationYDeg: 123.456789,
+ uniformScale: 1.125,
+ },
+ });
+ });
+
+ test('canonical JSON and SHA-256 are byte-stable and key-order independent', async () => {
+ const world = migrateSceneModelV1ToWorldDocumentV2(v1Model(), migrationOptions);
+ const reordered = JSON.parse(JSON.stringify(world)) as Record<string, unknown>;
+ const reversedTopLevel = Object.fromEntries(Object.entries(reordered).reverse());
+ const json = canonicalWorldDocumentV2Json(world);
+
+ expect(canonicalWorldDocumentV2Json(reversedTopLevel)).toBe(json);
+ expect(json.endsWith('\n')).toBe(false);
+ const expected = createHash('sha256').update(json).digest('hex');
+ expect(await hashWorldDocumentV2(world)).toBe(`sha256:${expected}`);
+ expect(await hashWorldDocumentV2(world)).toBe(await hashWorldDocumentV2(reversedTopLevel));
+
+ const changed = structuredClone(world);
+ changed.assets[0]!.artifactSha256 = 'a'.repeat(64);
+ expect(await hashWorldDocumentV2(changed)).not.toBe(await hashWorldDocumentV2(world));
+ });
+
+ test('fails closed on unknown versions, unknown keys, bad refs, duplicate ids, and non-finite numbers', () => {
+ const world = migrateSceneModelV1ToWorldDocumentV2(v1Model(), migrationOptions);
+ expect(() => parseWorldDocumentV2({ ...world, schemaVersion: 'kiln.world.v3' })).toThrow();
+ expect(() => parseWorldDocumentV2({ ...world, unexpected: true })).toThrow();
+
+ const badRef = structuredClone(world);
+ badRef.objects[0]!.assetRefId = 'missing';
+ expect(safeParseWorldDocumentV2(badRef).success).toBe(false);
+
+ const duplicate = structuredClone(world);
+ duplicate.objects[1]!.id = duplicate.objects[0]!.id;
+ expect(safeParseWorldDocumentV2(duplicate).success).toBe(false);
+
+ const infinite = structuredClone(world);
+ infinite.objects[0]!.transform.position[0] = Number.POSITIVE_INFINITY;
+ expect(safeParseWorldDocumentV2(infinite).success).toBe(false);
+ });
+
+ test('rejects unreferenced asset and collision artifacts', () => {
+ const world = migrateSceneModelV1ToWorldDocumentV2(v1Model(), migrationOptions);
+ const unusedAsset = structuredClone(world);
+ unusedAsset.assets.push({
+ ...structuredClone(unusedAsset.assets[0]!),
+ refId: 'asset:unused',
+ generationId: 'unused',
+ });
+ expect(safeParseWorldDocumentV2(unusedAsset).success).toBe(false);
+
+ const unusedCollision = structuredClone(world);
+ unusedCollision.collisionArtifacts.push({
+ refId: 'collision:unused',
+ artifact: {
+ uri: 'colliders/unused.glb',
+ sha256: 'b'.repeat(64),
+ mediaType: 'model/gltf-binary',
+ },
+ });
+ expect(safeParseWorldDocumentV2(unusedCollision).success).toBe(false);
+
+ const referencedCollision = structuredClone(unusedCollision);
+ referencedCollision.objects[0]!.collision = {
+ policy: 'artifact',
+ artifactRefId: 'collision:unused',
+ };
+ expect(safeParseWorldDocumentV2(referencedCollision).success).toBe(true);
+ });
+
+ test('accepts an empty world and exactly 200 objects, but rejects 201', () => {
+ const empty = migrateSceneModelV1ToWorldDocumentV2(
+ { name: 'Empty', seed: 1, catalog: [], statements: [] },
+ { worldId: 'empty', artifactSha256ByGenerationId: {} },
+ );
+ expect(empty.assets).toEqual([]);
+ expect(empty.objects).toEqual([]);
+
+ const base = migrateSceneModelV1ToWorldDocumentV2(v1Model(), migrationOptions);
+ const boundary = structuredClone(base);
+ boundary.objects = Array.from({ length: 200 }, (_, index) => ({
+ ...structuredClone(base.objects[0]!),
+ id: `object-${index}`,
+ }));
+ boundary.assets = [structuredClone(base.assets[0]!)];
+ expect(safeParseWorldDocumentV2(boundary).success).toBe(true);
+
+ boundary.objects.push({ ...structuredClone(base.objects[0]!), id: 'object-200' });
+ expect(safeParseWorldDocumentV2(boundary).success).toBe(false);
+ });
+
+ test('reconciles moved objects while preserving retained world-only fields', async () => {
+ const world = migrateSceneModelV1ToWorldDocumentV2(v1Model(), migrationOptions);
+ world.objects[0]!.collision = { policy: 'bounds' };
+ const beforeHash = await hashWorldDocumentV2(world);
+ const replacements = world.objects.map((object) => {
+ const asset = world.assets.find((candidate) => candidate.refId === object.assetRefId)!;
+ return {
+ id: object.id,
+ generationId: asset.generationId,
+ position: object.transform.position,
+ rotationYDeg: object.transform.rotationYDeg,
+ uniformScale: object.transform.uniformScale,
+ };
+ });
+ replacements[0] = {
+ ...replacements[0]!,
+ position: [99, 4, -33],
+ rotationYDeg: 77.5,
+ uniformScale: 2,
+ };
+ const reconciled = reconcileWorldDocumentV2Objects(world, { objects: replacements });
+
+ expect(reconciled.objects.find((object) => object.id === 'house_exact')).toEqual({
+ ...world.objects[0]!,
+ transform: { position: [99, 4, -33], rotationYDeg: 77.5, uniformScale: 2 },
+ });
+ expect(reconciled.environment).toEqual(world.environment);
+ expect(reconciled.terrain).toEqual(world.terrain);
+ expect(reconciled.authored).toEqual(world.authored);
+ expect(reconciled.provenance).toEqual(world.provenance);
+ expect(await hashWorldDocumentV2(reconciled)).not.toBe(beforeHash);
+ });
+
+ test('reconciles additions and removals with closed asset and collision references', () => {
+ const world = migrateSceneModelV1ToWorldDocumentV2(v1Model(), migrationOptions);
+ world.collisionArtifacts.push({
+ refId: 'collision:house',
+ artifact: { uri: 'collision/house.glb', sha256: 'c'.repeat(64) },
+ });
+ world.objects[0]!.collision = { policy: 'artifact', artifactRefId: 'collision:house' };
+
+ const reconciled = reconcileWorldDocumentV2Objects(world, {
+ objects: [
+ {
+ id: 'trees#0',
+ generationId: 'tree',
+ position: [20, 0, 0],
+ rotationYDeg: 0,
+ uniformScale: 0.85,
+ },
+ {
+ id: 'new-lantern',
+ generationId: 'lantern',
+ position: [3, 0, 4],
+ rotationYDeg: 15,
+ uniformScale: 1,
+ },
+ ],
+ assets: [
+ {
+ generationId: 'lantern',
+ artifactSha256: 'd'.repeat(64),
+ bounds: { min: [-0.5, 0, -0.5], max: [0.5, 2, 0.5] },
+ name: 'Lantern',
+ role: 'prop',
+ },
+ ],
+ environment: {
+ presetId: 'night',
+ lightingPresetId: 'night-v2',
+ groundPaint: [],
+ },
+ });
+
+ expect(reconciled.objects.map((object) => object.id)).toEqual(['new-lantern', 'trees#0']);
+ expect(reconciled.assets.map((asset) => asset.generationId)).toEqual(['lantern', 'tree']);
+ expect(reconciled.collisionArtifacts).toEqual([]);
+ expect(reconciled.environment).toEqual({
+ presetId: 'night',
+ lightingPresetId: 'night-v2',
+ groundPaint: [],
+ });
+ expect(reconciled.objects[0]).toMatchObject({
+ id: 'new-lantern',
+ role: 'support',
+ provenance: { sourceStatementId: 'manual:new-lantern' },
+ });
+ });
+
+ test('reconciliation is input-order independent and artifact-hash sensitive', async () => {
+ const world = migrateSceneModelV1ToWorldDocumentV2(v1Model(), migrationOptions);
+ const objects = world.objects.map((object) => ({
+ id: object.id,
+ generationId: world.assets.find((asset) => asset.refId === object.assetRefId)!.generationId,
+ position: object.transform.position,
+ rotationYDeg: object.transform.rotationYDeg,
+ uniformScale: object.transform.uniformScale,
+ }));
+ const ordered = reconcileWorldDocumentV2Objects(world, { objects });
+ const reversed = reconcileWorldDocumentV2Objects(world, { objects: [...objects].reverse() });
+ expect(reversed).toEqual(ordered);
+ expect(await hashWorldDocumentV2(reversed)).toBe(await hashWorldDocumentV2(ordered));
+
+ const house = world.assets.find((asset) => asset.generationId === 'house')!;
+ const changedHash = reconcileWorldDocumentV2Objects(world, {
+ objects,
+ assets: [
+ {
+ generationId: house.generationId,
+ artifactSha256: 'e'.repeat(64),
+ bounds: house.bounds,
+ ...(house.name ? { name: house.name } : {}),
+ ...(house.tags ? { tags: house.tags } : {}),
+ ...(house.role ? { role: house.role } : {}),
+ ...(house.tier ? { tier: house.tier } : {}),
+ },
+ ],
+ });
+ expect(await hashWorldDocumentV2(changedHash)).not.toBe(await hashWorldDocumentV2(ordered));
+ });
+
+ test('keeps only referenced assets and requires a real hash for each one', () => {
+ const withUnusedCatalogAsset = v1Model();
+ withUnusedCatalogAsset.catalog.push({
+ generationId: 'unused-prop',
+ bbox: { min: [-1, 0, -1], max: [1, 2, 1] },
+ role: 'prop',
+ });
+ const migrated = migrateSceneModelV1ToWorldDocumentV2(withUnusedCatalogAsset, migrationOptions);
+ expect(migrated.assets.map((asset) => asset.generationId)).toEqual(['house', 'tree']);
+
+ expect(() =>
+ migrateSceneModelV1ToWorldDocumentV2(v1Model(), {
+ worldId: 'scene-123',
+ artifactSha256ByGenerationId: { house: HOUSE_SHA },
+ }),
+ ).toThrow('missing artifact SHA-256 for generation "tree"');
+
+ expect(() =>
+ migrateSceneModelV1ToWorldDocumentV2(v1Model(), {
+ worldId: 'scene-123',
+ artifactSha256ByGenerationId: { house: 'not-a-hash', tree: TREE_SHA },
+ }),
+ ).toThrow();
+ });
+
+ test('rejects unknown and malformed persisted v1 model shapes before evaluation', () => {
+ expect(() =>
+ migrateSceneModelV1ToWorldDocumentV2(
+ { ...v1Model(), unknownRoot: true } as unknown as SceneModelJSON,
+ migrationOptions,
+ ),
+ ).toThrow();
+
+ const malformed = v1Model() as unknown as { statements: Array<Record<string, unknown>> };
+ malformed.statements[0]!.kind = 'unsupported';
+ expect(() =>
+ migrateSceneModelV1ToWorldDocumentV2(
+ malformed as unknown as SceneModelJSON,
+ migrationOptions,
+ ),
+ ).toThrow();
+
+ const nonFinite = v1Model();
+ nonFinite.statements[0]!.scale = Number.POSITIVE_INFINITY;
+ expect(() => migrateSceneModelV1ToWorldDocumentV2(nonFinite, migrationOptions)).toThrow();
+ });
+
+ test('rejects duplicate v1 ids and aliases plus dangling asset references', () => {
+ const duplicateGeneration = v1Model();
+ duplicateGeneration.catalog.push(structuredClone(duplicateGeneration.catalog[0]!));
+ expect(() =>
+ migrateSceneModelV1ToWorldDocumentV2(duplicateGeneration, migrationOptions),
+ ).toThrow();
+
+ const duplicateStatement = v1Model();
+ duplicateStatement.statements[1]!.stmtId = duplicateStatement.statements[0]!.stmtId;
+ expect(() =>
+ migrateSceneModelV1ToWorldDocumentV2(duplicateStatement, migrationOptions),
+ ).toThrow();
+
+ const duplicateAlias = v1Model();
+ duplicateAlias.statements[1]!.alias = duplicateAlias.statements[0]!.alias;
+ expect(() => migrateSceneModelV1ToWorldDocumentV2(duplicateAlias, migrationOptions)).toThrow();
+
+ const dangling = v1Model();
+ dangling.statements[0]!.generationId = 'missing-generation';
+ expect(() => migrateSceneModelV1ToWorldDocumentV2(dangling, migrationOptions)).toThrow();
+ });
+});
diff --git a/src/composer/world-document.ts b/src/composer/world-document.ts
new file mode 100644
index 00000000..9656e1c0
--- /dev/null
+++ b/src/composer/world-document.ts
@@ -0,0 +1,808 @@
+/**
+ * Canonical Composer V2 world contract.
+ *
+ * `WorldDocumentV2.objects` is the machine source of truth. The v1
+ * `SceneModelJSON` and readable composer program are projections used by the
+ * current authoring loop, never embedded parallel authorities. This module is
+ * pure and browser-safe: it performs no asset lookup, network access, or I/O.
+ */
+import { z } from 'zod';
+import type {
+ CatalogAssetRole,
+ CatalogTier,
+ Placement,
+ Role,
+ SceneModelJSON,
+ Statement,
+} from './model';
+import { placementRoleForAsset, PlacementModel } from './model';
+
+export const WORLD_DOCUMENT_V2_SCHEMA_VERSION = 'kiln.world.v2' as const;
+
+const finite = z.number().finite();
+const vec2 = z.tuple([finite, finite]);
+const vec3 = z.tuple([finite, finite, finite]);
+const sha256 = z.string().regex(/^[0-9a-f]{64}$/, 'expected 64 lowercase SHA-256 hex characters');
+const nonEmptyId = z.string().min(1).max(256);
+
+const boundsSchema = z
+ .object({ min: vec3, max: vec3 })
+ .strict()
+ .superRefine((bounds, ctx) => {
+ for (let axis = 0; axis < 3; axis++) {
+ if (bounds.min[axis]! > bounds.max[axis]!) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['min', axis],
+ message: 'bounds min must not exceed max',
+ });
+ }
+ }
+ });
+
+const roleSchema = z.enum(['hero', 'support', 'fill']);
+const assetRoleSchema = z.enum(['ground', 'building', 'wonder', 'poi', 'prop', 'fill', 'vehicle']);
+const assetTierSchema = z.enum(['A', 'B', 'C', 'D', 'F']);
+const groundThemeSchema = z.enum([
+ 'meadow',
+ 'desert',
+ 'egypt',
+ 'plaza',
+ 'snow',
+ 'arctic',
+ 'edo',
+ 'night',
+ 'studio',
+]);
+
+const backdropSchema = z
+ .object({
+ kind: z.enum(['mushroom-cloud', 'sun-disc', 'aurora', 'fuji']),
+ pos: vec3.optional(),
+ scale: finite.positive().optional(),
+ })
+ .strict();
+
+const paintShapeSchema = z.discriminatedUnion('type', [
+ z
+ .object({
+ type: z.literal('rect'),
+ x: finite,
+ z: finite,
+ hx: finite.positive(),
+ hz: finite.positive(),
+ })
+ .strict(),
+ z
+ .object({
+ type: z.literal('strip'),
+ axis: z.enum(['x', 'z']),
+ offset: finite,
+ half: finite.positive(),
+ from: finite,
+ to: finite,
+ })
+ .strict(),
+]);
+
+const paintZoneSchema = z
+ .object({
+ kind: z.enum([
+ 'grass',
+ 'concrete',
+ 'asphalt',
+ 'sand',
+ 'flagstone',
+ 'snow',
+ 'ice',
+ 'gravel',
+ 'stone-path',
+ ]),
+ shape: paintShapeSchema,
+ laneLine: z.boolean().optional(),
+ })
+ .strict();
+
+const artifactSchema = z
+ .object({
+ uri: z.string().min(1).max(2048),
+ sha256,
+ mediaType: z.string().min(1).max(128).optional(),
+ })
+ .strict();
+
+const assetSchema = z
+ .object({
+ refId: nonEmptyId,
+ generationId: nonEmptyId,
+ artifactSha256: sha256,
+ bounds: boundsSchema,
+ name: z.string().min(1).max(256).optional(),
+ tags: z.array(z.string().min(1).max(128)).max(128).optional(),
+ role: assetRoleSchema.optional(),
+ tier: assetTierSchema.optional(),
+ })
+ .strict();
+
+const objectSchema = z
+ .object({
+ id: nonEmptyId,
+ assetRefId: nonEmptyId,
+ transform: z
+ .object({
+ position: vec3,
+ rotationYDeg: finite,
+ uniformScale: finite.positive(),
+ })
+ .strict(),
+ role: roleSchema,
+ groupId: nonEmptyId.optional(),
+ collision: z
+ .discriminatedUnion('policy', [
+ z.object({ policy: z.literal('none') }).strict(),
+ z.object({ policy: z.literal('bounds') }).strict(),
+ z.object({ policy: z.literal('artifact'), artifactRefId: nonEmptyId }).strict(),
+ ])
+ .optional(),
+ provenance: z
+ .object({
+ sourceStatementId: nonEmptyId,
+ sourcePrompt: z.string().min(1).max(4000).optional(),
+ parentGenerationId: nonEmptyId.optional(),
+ })
+ .strict(),
+ })
+ .strict();
+
+const zoneSchema = z
+ .object({
+ id: nonEmptyId,
+ kind: z.enum(['reserved', 'portal-clearance', 'spawn-clearance']),
+ shape: z.discriminatedUnion('type', [
+ z.object({ type: z.literal('rect'), center: vec2, halfExtents: vec2 }).strict(),
+ z.object({ type: z.literal('circle'), center: vec2, radius: finite.positive() }).strict(),
+ ]),
+ })
+ .strict();
+
+const pathSchema = z
+ .object({
+ id: nonEmptyId,
+ points: z.array(vec3).min(2).max(4096),
+ halfWidth: finite.positive(),
+ })
+ .strict();
+
+const socketSchema = z
+ .object({
+ id: nonEmptyId,
+ position: vec3,
+ rotationYDeg: finite,
+ tags: z.array(z.string().min(1).max(128)).max(64),
+ })
+ .strict();
+
+const terrainSchema = z.discriminatedUnion('kind', [
+ z.object({ kind: z.literal('flat'), height: finite }).strict(),
+ z.object({ kind: z.literal('heightfield'), artifact: artifactSchema }).strict(),
+]);
+
+const collisionArtifactSchema = z
+ .object({
+ refId: nonEmptyId,
+ artifact: artifactSchema,
+ })
+ .strict();
+
+const spawnSchema = z
+ .object({
+ id: nonEmptyId,
+ position: vec3,
+ rotationYDeg: finite,
+ clearanceRadius: finite.positive(),
+ })
+ .strict();
+
+const worldEnvironmentSchema = z
+ .object({
+ presetId: groundThemeSchema.optional(),
+ lightingPresetId: nonEmptyId,
+ backdrop: backdropSchema.optional(),
+ groundPaint: z.array(paintZoneSchema).max(512),
+ })
+ .strict();
+
+const duplicateValues = (values: readonly string[]): string[] => {
+ const seen = new Set<string>();
+ const duplicates = new Set<string>();
+ for (const value of values) {
+ if (seen.has(value)) duplicates.add(value);
+ seen.add(value);
+ }
+ return [...duplicates].sort();
+};
+
+const v1ProvenanceSchema = z
+ .object({
+ sourcePrompt: z.string().min(1).max(4000).optional(),
+ parentGenerationId: nonEmptyId.optional(),
+ })
+ .strict();
+
+const v1StatementCommon = {
+ stmtId: nonEmptyId,
+ alias: nonEmptyId,
+ generationId: nonEmptyId,
+ role: roleSchema,
+ scale: finite.positive(),
+ group: nonEmptyId.optional(),
+ provenance: v1ProvenanceSchema.optional(),
+};
+
+const v1FacingSchema = z.union([z.enum(['center', 'out']), vec2, finite]);
+const v1StatementSchema = z.discriminatedUnion('kind', [
+ z
+ .object({
+ ...v1StatementCommon,
+ kind: z.literal('place'),
+ at: vec2,
+ y: finite.optional(),
+ face: v1FacingSchema,
+ exact: z
+ .object({
+ pos: vec3,
+ rotYDeg: finite,
+ })
+ .strict()
+ .optional(),
+ })
+ .strict(),
+ z
+ .object({
+ ...v1StatementCommon,
+ kind: z.literal('cluster'),
+ around: vec2,
+ count: z.number().int().min(1).max(200),
+ spread: finite.nonnegative(),
+ face: v1FacingSchema,
+ })
+ .strict(),
+ z
+ .object({
+ ...v1StatementCommon,
+ kind: z.literal('ring'),
+ center: vec2,
+ count: z.number().int().min(1).max(200),
+ radius: finite.nonnegative(),
+ faceOut: z.boolean(),
+ })
+ .strict(),
+]);
+
+/** Strict runtime schema for the unversioned v1 PlacementModel persistence shape. */
+export const SceneModelV1Schema = z
+ .object({
+ name: z.string().min(1).max(256),
+ seed: z.number().int().safe(),
+ catalog: z
+ .array(
+ z
+ .object({
+ generationId: nonEmptyId,
+ bbox: boundsSchema,
+ name: z.string().min(1).max(256).optional(),
+ tags: z.array(z.string().min(1).max(128)).max(128).optional(),
+ role: assetRoleSchema.optional(),
+ tier: assetTierSchema.optional(),
+ })
+ .strict(),
+ )
+ .max(200),
+ statements: z.array(v1StatementSchema).max(200),
+ environment: groundThemeSchema.optional(),
+ backdrop: backdropSchema.optional(),
+ paint: z.array(paintZoneSchema).max(512).optional(),
+ })
+ .strict()
+ .superRefine((model, ctx) => {
+ const unique = (values: readonly string[], path: 'catalog' | 'statements'): void => {
+ for (const duplicate of duplicateValues(values)) {
+ ctx.addIssue({ code: 'custom', path: [path], message: `duplicate id "${duplicate}"` });
+ }
+ };
+ unique(
+ model.catalog.map((entry) => entry.generationId),
+ 'catalog',
+ );
+ unique(
+ model.statements.map((statement) => statement.stmtId),
+ 'statements',
+ );
+ unique(
+ model.statements.map((statement) => statement.alias),
+ 'statements',
+ );
+
+ const generations = new Set(model.catalog.map((entry) => entry.generationId));
+ for (let index = 0; index < model.statements.length; index++) {
+ const statement = model.statements[index]!;
+ if (!generations.has(statement.generationId)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['statements', index, 'generationId'],
+ message: `unknown generation "${statement.generationId}"`,
+ });
+ }
+ }
+ });
+
+/** Strict schema for the canonical world. Every referenced artifact carries a SHA-256. */
+export const WorldDocumentV2Schema = z
+ .object({
+ schemaVersion: z.literal(WORLD_DOCUMENT_V2_SCHEMA_VERSION),
+ worldId: nonEmptyId,
+ name: z.string().min(1).max(256),
+ seed: z.number().int().safe(),
+ assets: z.array(assetSchema).max(200),
+ objects: z.array(objectSchema).max(200),
+ environment: worldEnvironmentSchema,
+ terrain: terrainSchema,
+ authored: z
+ .object({
+ zones: z.array(zoneSchema).max(512),
+ paths: z.array(pathSchema).max(512),
+ sockets: z.array(socketSchema).max(2048),
+ })
+ .strict(),
+ collisionArtifacts: z.array(collisionArtifactSchema).max(512),
+ spawns: z.array(spawnSchema).max(128),
+ runtimePolicy: z.object({ mode: z.literal('static-explore') }).strict(),
+ provenance: z
+ .object({
+ source: z.enum(['composer-v1', 'composer-v2', 'manual']),
+ sourcePrompt: z.string().min(1).max(4000).optional(),
+ parentWorldHash: z
+ .string()
+ .regex(/^sha256:[0-9a-f]{64}$/, 'expected sha256:<64 lowercase hex characters>')
+ .optional(),
+ })
+ .strict(),
+ })
+ .strict()
+ .superRefine((world, ctx) => {
+ const unique = (values: readonly string[], path: string): void => {
+ for (const duplicate of duplicateValues(values)) {
+ ctx.addIssue({ code: 'custom', path: [path], message: `duplicate id "${duplicate}"` });
+ }
+ };
+ unique(
+ world.assets.map((asset) => asset.refId),
+ 'assets',
+ );
+ unique(
+ world.assets.map((asset) => asset.generationId),
+ 'assets',
+ );
+ unique(
+ world.objects.map((object) => object.id),
+ 'objects',
+ );
+ unique(
+ world.authored.zones.map((zone) => zone.id),
+ 'authored',
+ );
+ unique(
+ world.authored.paths.map((path) => path.id),
+ 'authored',
+ );
+ unique(
+ world.authored.sockets.map((socket) => socket.id),
+ 'authored',
+ );
+ unique(
+ world.collisionArtifacts.map((artifact) => artifact.refId),
+ 'collisionArtifacts',
+ );
+ unique(
+ world.spawns.map((spawn) => spawn.id),
+ 'spawns',
+ );
+
+ const assetRefs = new Set(world.assets.map((asset) => asset.refId));
+ const collisionRefs = new Set(world.collisionArtifacts.map((artifact) => artifact.refId));
+ const referencedAssets = new Set<string>();
+ const referencedCollisions = new Set<string>();
+ for (let index = 0; index < world.objects.length; index++) {
+ const object = world.objects[index]!;
+ referencedAssets.add(object.assetRefId);
+ if (!assetRefs.has(object.assetRefId)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['objects', index, 'assetRefId'],
+ message: `unknown asset ref "${object.assetRefId}"`,
+ });
+ }
+ if (
+ object.collision?.policy === 'artifact' &&
+ !collisionRefs.has(object.collision.artifactRefId)
+ ) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['objects', index, 'collision', 'artifactRefId'],
+ message: `unknown collision artifact ref "${object.collision.artifactRefId}"`,
+ });
+ }
+ if (object.collision?.policy === 'artifact') {
+ referencedCollisions.add(object.collision.artifactRefId);
+ }
+ }
+ for (let index = 0; index < world.assets.length; index++) {
+ const asset = world.assets[index]!;
+ if (!referencedAssets.has(asset.refId)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['assets', index, 'refId'],
+ message: `unreferenced asset "${asset.refId}"`,
+ });
+ }
+ }
+ for (let index = 0; index < world.collisionArtifacts.length; index++) {
+ const artifact = world.collisionArtifacts[index]!;
+ if (!referencedCollisions.has(artifact.refId)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['collisionArtifacts', index, 'refId'],
+ message: `unreferenced collision artifact "${artifact.refId}"`,
+ });
+ }
+ }
+ });
+
+export type WorldDocumentV2 = z.infer<typeof WorldDocumentV2Schema>;
+export type WorldAssetRefV2 = WorldDocumentV2['assets'][number];
+export type WorldObjectV2 = WorldDocumentV2['objects'][number];
+
+/** Parse and clone current v1 persistence before it reaches PlacementModel.fromJSON. */
+export function parseSceneModelV1JSON(input: unknown): SceneModelJSON {
+ return SceneModelV1Schema.parse(input) as SceneModelJSON;
+}
+
+/** Parse and clone a v2 document. Unknown schema versions and unknown keys fail closed. */
+export function parseWorldDocumentV2(input: unknown): WorldDocumentV2 {
+ return WorldDocumentV2Schema.parse(input);
+}
+
+/** Non-throwing companion to `parseWorldDocumentV2`. */
+export function safeParseWorldDocumentV2(input: unknown) {
+ return WorldDocumentV2Schema.safeParse(input);
+}
+
+function canonicalJson(value: unknown): string {
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') {
+ return JSON.stringify(value);
+ }
+ if (typeof value === 'number') return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ if (typeof value === 'object') {
+ const record = value as Record<string, unknown>;
+ return `{${Object.keys(record)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)
+ .join(',')}}`;
+ }
+ throw new TypeError(`unsupported canonical JSON value: ${typeof value}`);
+}
+
+/** Validated RFC-8259 JSON with recursively sorted object keys and preserved array order. */
+export function canonicalWorldDocumentV2Json(input: unknown): string {
+ return canonicalJson(parseWorldDocumentV2(input));
+}
+
+/** Browser-safe SHA-256 over `canonicalWorldDocumentV2Json`. */
+export async function hashWorldDocumentV2(input: unknown): Promise<`sha256:${string}`> {
+ const bytes = new TextEncoder().encode(canonicalWorldDocumentV2Json(input));
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes));
+ const hex = [...digest].map((byte) => byte.toString(16).padStart(2, '0')).join('');
+ return `sha256:${hex}`;
+}
+
+const reconciliationSchema = z
+ .object({
+ objects: z
+ .array(
+ z
+ .object({
+ id: nonEmptyId,
+ generationId: nonEmptyId,
+ position: vec3,
+ rotationYDeg: finite,
+ uniformScale: finite.positive(),
+ })
+ .strict(),
+ )
+ .max(200),
+ assets: z
+ .array(
+ z
+ .object({
+ generationId: nonEmptyId,
+ artifactSha256: sha256,
+ bounds: boundsSchema,
+ name: z.string().min(1).max(256).optional(),
+ tags: z.array(z.string().min(1).max(128)).max(128).optional(),
+ role: assetRoleSchema.optional(),
+ tier: assetTierSchema.optional(),
+ })
+ .strict(),
+ )
+ .max(200)
+ .optional(),
+ /** Complete replacement when manual PUT changes presentation state. */
+ environment: worldEnvironmentSchema.optional(),
+ })
+ .strict()
+ .superRefine((input, ctx) => {
+ for (const duplicate of duplicateValues(input.objects.map((object) => object.id))) {
+ ctx.addIssue({ code: 'custom', path: ['objects'], message: `duplicate id "${duplicate}"` });
+ }
+ for (const duplicate of duplicateValues(
+ (input.assets ?? []).map((asset) => asset.generationId),
+ )) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['assets'],
+ message: `duplicate generation "${duplicate}"`,
+ });
+ }
+ const referencedGenerations = new Set(input.objects.map((object) => object.generationId));
+ for (let index = 0; index < (input.assets ?? []).length; index++) {
+ const asset = input.assets![index]!;
+ if (!referencedGenerations.has(asset.generationId)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['assets', index, 'generationId'],
+ message: `unreferenced asset metadata "${asset.generationId}"`,
+ });
+ }
+ }
+ });
+
+export type ReconcileWorldDocumentV2Input = z.infer<typeof reconciliationSchema>;
+
+/**
+ * Reconcile a host-authoritative complete placement set into an existing world.
+ * Retained object ids preserve role/group/collision/provenance, untouched world
+ * fields are carried through, removed references are pruned, and output arrays
+ * are sorted by stable ids so caller ordering cannot change the document hash.
+ */
+export function reconcileWorldDocumentV2Objects(
+ current: unknown,
+ replacement: unknown,
+): WorldDocumentV2 {
+ const world = parseWorldDocumentV2(current);
+ const input = reconciliationSchema.parse(replacement);
+ const existingObjects = new Map(world.objects.map((object) => [object.id, object]));
+ const existingAssets = new Map(world.assets.map((asset) => [asset.generationId, asset]));
+ const suppliedAssets = new Map((input.assets ?? []).map((asset) => [asset.generationId, asset]));
+ const compareId = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
+
+ const resolvedAssets = new Map<string, WorldAssetRefV2>();
+ const objects = [...input.objects]
+ .sort((a, b) => compareId(a.id, b.id))
+ .map((object) => {
+ const previous = existingObjects.get(object.id);
+ const existingAsset = existingAssets.get(object.generationId);
+ const suppliedAsset = suppliedAssets.get(object.generationId);
+ if (!existingAsset && !suppliedAsset) {
+ throw new Error(`missing asset metadata for generation "${object.generationId}"`);
+ }
+ const refId = existingAsset?.refId ?? assetRefId(object.generationId);
+ const asset = assetSchema.parse({
+ refId,
+ ...(suppliedAsset ?? existingAsset!),
+ });
+ resolvedAssets.set(asset.refId, asset);
+ return {
+ id: object.id,
+ assetRefId: asset.refId,
+ transform: {
+ position: object.position,
+ rotationYDeg: object.rotationYDeg,
+ uniformScale: object.uniformScale,
+ },
+ role: previous?.role ?? placementRoleForAsset(asset.role) ?? 'support',
+ provenance: previous?.provenance ?? {
+ sourceStatementId: `manual:${object.id}`.slice(0, 256),
+ },
+ ...(previous?.groupId ? { groupId: previous.groupId } : {}),
+ ...(previous?.collision ? { collision: previous.collision } : {}),
+ };
+ });
+
+ const referencedCollisions = new Set(
+ objects.flatMap((object) =>
+ object.collision?.policy === 'artifact' ? [object.collision.artifactRefId] : [],
+ ),
+ );
+ return parseWorldDocumentV2({
+ ...world,
+ assets: [...resolvedAssets.values()].sort((a, b) => compareId(a.refId, b.refId)),
+ objects,
+ collisionArtifacts: world.collisionArtifacts.filter((artifact) =>
+ referencedCollisions.has(artifact.refId),
+ ),
+ ...(input.environment ? { environment: input.environment } : {}),
+ });
+}
+
+export interface MigrateSceneModelV1Options {
+ /** Stable product-owned scene/world id. No random id is invented in the pure engine. */
+ worldId: string;
+ /** Existing GLB content hashes, resolved by the host before migration. */
+ artifactSha256ByGenerationId: Readonly<Record<string, string>>;
+ /** Host-authoritative evaluated transforms. Defaults to flat-ground v1 evaluation. */
+ placements?: readonly Placement[];
+ /** Presentation preset identity; does not change transforms. */
+ lightingPresetId?: string;
+ sourcePrompt?: string;
+ parentWorldHash?: `sha256:${string}`;
+}
+
+const assetRefId = (generationId: string): string => `asset:${generationId}`;
+
+/**
+ * Deterministically migrate the current PlacementModel JSON to canonical exact
+ * objects. Cluster/ring sugar is intentionally flattened: the evaluated
+ * instance transforms are the visual truth and survive reload bit-for-bit.
+ */
+export function migrateSceneModelV1ToWorldDocumentV2(
+ input: unknown,
+ options: MigrateSceneModelV1Options,
+): WorldDocumentV2 {
+ const modelJson = parseSceneModelV1JSON(input);
+ const evaluated = PlacementModel.fromJSON(modelJson).placements();
+ const placements = options.placements ?? evaluated.placements;
+ const statements = new Map(
+ modelJson.statements.map((statement) => [statement.stmtId, statement]),
+ );
+ const catalog = new Map(modelJson.catalog.map((entry) => [entry.generationId, entry]));
+ const referencedGenerations = new Set(placements.map((placement) => placement.generationId));
+
+ const assets = modelJson.catalog
+ .filter((entry) => referencedGenerations.has(entry.generationId))
+ .map((entry) => {
+ const artifactSha256 = options.artifactSha256ByGenerationId[entry.generationId];
+ if (!artifactSha256) {
+ throw new Error(`missing artifact SHA-256 for generation "${entry.generationId}"`);
+ }
+ return {
+ refId: assetRefId(entry.generationId),
+ generationId: entry.generationId,
+ artifactSha256,
+ bounds: entry.bbox,
+ ...(entry.name ? { name: entry.name } : {}),
+ ...(entry.tags ? { tags: entry.tags } : {}),
+ ...(entry.role ? { role: entry.role } : {}),
+ ...(entry.tier ? { tier: entry.tier } : {}),
+ };
+ });
+
+ const objects = placements.map((placement) => {
+ if (!catalog.has(placement.generationId)) {
+ throw new Error(
+ `placement "${placement.instanceId}" references unknown generation "${placement.generationId}"`,
+ );
+ }
+ const statement = statements.get(placement.stmtId);
+ if (!statement) {
+ throw new Error(
+ `placement "${placement.instanceId}" references unknown statement "${placement.stmtId}"`,
+ );
+ }
+ const evaluatedProvenance = evaluated.provenance[placement.instanceId];
+ const sourcePrompt = evaluatedProvenance?.sourcePrompt ?? statement.provenance?.sourcePrompt;
+ const parentGenerationId =
+ evaluatedProvenance?.parentGenerationId ?? statement.provenance?.parentGenerationId;
+ return {
+ id: placement.instanceId,
+ assetRefId: assetRefId(placement.generationId),
+ transform: {
+ position: [placement.pos[0], placement.pos[1], placement.pos[2]] as [
+ number,
+ number,
+ number,
+ ],
+ rotationYDeg: placement.rotYDeg,
+ uniformScale: placement.scale,
+ },
+ role: statement.role,
+ ...(statement.group ? { groupId: statement.group } : {}),
+ provenance: {
+ sourceStatementId: placement.stmtId,
+ ...(sourcePrompt ? { sourcePrompt } : {}),
+ ...(parentGenerationId ? { parentGenerationId } : {}),
+ },
+ };
+ });
+
+ return parseWorldDocumentV2({
+ schemaVersion: WORLD_DOCUMENT_V2_SCHEMA_VERSION,
+ worldId: options.worldId,
+ name: modelJson.name,
+ seed: modelJson.seed,
+ assets,
+ objects,
+ environment: {
+ ...(modelJson.environment ? { presetId: modelJson.environment } : {}),
+ lightingPresetId: options.lightingPresetId ?? 'legacy-scene-v1',
+ ...(modelJson.backdrop ? { backdrop: modelJson.backdrop } : {}),
+ groundPaint: modelJson.paint ?? [],
+ },
+ terrain: { kind: 'flat', height: 0 },
+ authored: { zones: [], paths: [], sockets: [] },
+ collisionArtifacts: [],
+ spawns: [],
+ runtimePolicy: { mode: 'static-explore' },
+ provenance: {
+ source: 'composer-v1',
+ ...(options.sourcePrompt ? { sourcePrompt: options.sourcePrompt } : {}),
+ ...(options.parentWorldHash ? { parentWorldHash: options.parentWorldHash } : {}),
+ },
+ });
+}
+
+/**
+ * Derive the current authoring model from canonical v2 exact objects. The
+ * projection deliberately uses one exact `place` statement per object so
+ * evaluation cannot recenter, reground, or reinterpret facing.
+ */
+export function worldDocumentV2ToSceneModelJSON(input: unknown): SceneModelJSON {
+ const world = parseWorldDocumentV2(input);
+ const assets = new Map(world.assets.map((asset) => [asset.refId, asset]));
+ const statements: Statement[] = world.objects.map((object, index) => {
+ const asset = assets.get(object.assetRefId)!;
+ const provenance = {
+ ...(object.provenance.sourcePrompt ? { sourcePrompt: object.provenance.sourcePrompt } : {}),
+ ...(object.provenance.parentGenerationId
+ ? { parentGenerationId: object.provenance.parentGenerationId }
+ : {}),
+ };
+ return {
+ kind: 'place',
+ stmtId: `s${index + 1}`,
+ alias: object.id,
+ generationId: asset.generationId,
+ role: object.role as Role,
+ scale: object.transform.uniformScale,
+ at: [object.transform.position[0], object.transform.position[2]],
+ face: object.transform.rotationYDeg,
+ exact: {
+ pos: [
+ object.transform.position[0],
+ object.transform.position[1],
+ object.transform.position[2],
+ ],
+ rotYDeg: object.transform.rotationYDeg,
+ },
+ ...(object.groupId ? { group: object.groupId } : {}),
+ ...(Object.keys(provenance).length ? { provenance } : {}),
+ };
+ });
+
+ return {
+ name: world.name,
+ seed: world.seed,
+ catalog: world.assets.map((asset) => ({
+ generationId: asset.generationId,
+ bbox: asset.bounds,
+ ...(asset.name ? { name: asset.name } : {}),
+ ...(asset.tags ? { tags: asset.tags } : {}),
+ ...(asset.role ? { role: asset.role as CatalogAssetRole } : {}),
+ ...(asset.tier ? { tier: asset.tier as CatalogTier } : {}),
+ })),
+ statements,
+ ...(world.environment.presetId ? { environment: world.environment.presetId } : {}),
+ ...(world.environment.backdrop ? { backdrop: world.environment.backdrop } : {}),
+ ...(world.environment.groundPaint.length ? { paint: world.environment.groundPaint } : {}),
+ };
+}