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.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat(composer): add deterministic world integration phase (#28)
Matthew Kissinger58b6d1921785
diff --git a/README.md b/README.mdindex e789d5b1..72444e12 100644--- a/README.md+++ b/README.md@@ -61,7 +61,20 @@ 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 (canonical `WorldDocumentV2`, deterministic v1 migration/hash/projection, placement model, layout, overlap, DSL) + its Strands agent loop (`runKilnComposer`) |+| `@kiln/engine/composer`, `/composer/agent` | THREE-free scene-composition core (canonical `WorldDocumentV2`, strict reconciliation, sockets/zones/paths/spawns, deterministic terrain, layout/overlap/DSL) + bounded compose and post-compose integration loops (`runKilnComposer`, `runKilnWorldIntegration`) |+| `@kiln/engine/world-runtime` | dependency-free browser-safe heightfield V1 parser/codec/hash/sampler/mesh projection; Studio `sync:engine` may copy this exact leaf and stamp its source SHA so frontend/Play run the Engine-owned implementation without importing the Engine package |++Composer V2 uses one canonical-world authority. For a fresh scene, run the ordinary composer,+migrate its evaluated candidate with `migrateSceneModelV1ToWorldDocumentV2`, then pass that world to+`runKilnWorldIntegration`. For refine, merge the migrated candidate into the parent with+`reconcileWorldDocumentV2Candidate` first; that preserves terrain/authored/runtime state and applies+locked asset-swap semantics. The bounded integration loop renders and finalizes the same world state+its `scene_world_*` tools mutate. Pass one `generationCallBudget` through both `runKilnComposer` and+`runKilnWorldIntegration` so the host settles one aggregate allowance; the integration stage otherwise+requires an explicit positive `maxSteps`, with no hidden second-stage call allowance.+Heightfield artifact SHA-256 binds the exact bytes from+`encodeHeightfieldArtifactV1`; portable asset paths remain the additive package contract+`models/<generationId>.glb`.Finished renders include `integrationManifest`, a versioned sidecar with the artifacthash, metres/+Y-up axes, bounds, grounding offset, selected default scene, role, renderdiff --git a/package.json b/package.jsonindex 96216a0e..55862ab9 100644--- a/package.json+++ b/package.json@@ -38,7 +38,8 @@"./contracts": "./src/contracts/index.ts","./qa": "./src/qa/index.ts","./composer": "./src/composer/index.ts",- "./composer/agent": "./src/composer/agent/index.ts"+ "./composer/agent": "./src/composer/agent/index.ts",+ "./world-runtime": "./src/composer/terrain-runtime.ts"},"files": ["src/**/*.ts",diff --git a/src/__tests__/composer-world-run.test.ts b/src/__tests__/composer-world-run.test.tsnew file mode 100644index 00000000..30c5379b--- /dev/null+++ b/src/__tests__/composer-world-run.test.ts@@ -0,0 +1,136 @@+import { describe, expect, test } from 'bun:test';+import type { Message, ModelStreamEvent, StreamOptions } from '@strands-agents/sdk';+import type { SceneModelJSON, SceneRenderPort } from '../composer';+import { migrateSceneModelV1ToWorldDocumentV2 } from '../composer';+import { createGenerationCallBudget } from '../agent/call-budget';+import {+ runKilnComposer,+ runKilnWorldIntegration,+ WORLD_INTEGRATION_PROMPT_V2,+} from '../composer/agent';+import { ScriptedModel } from '../agent/__tests__/scripted-model';++class ToolCapturingModel extends ScriptedModel {+ toolNames: string[][] = [];+ override async *stream(+ messages: Message[],+ options?: StreamOptions,+ ): AsyncIterable<ModelStreamEvent> {+ this.toolNames.push((options?.toolSpecs ?? []).map(({ name }) => name));+ yield* super.stream(messages, options);+ }+}++function world() {+ const scene: SceneModelJSON = {+ name: 'World',+ seed: 2,+ catalog: [+ { generationId: 'crate', bbox: { min: [-1, 0, -1], max: [1, 2, 1] }, tags: ['cargo'] },+ ],+ statements: [+ {+ kind: 'place',+ stmtId: 's1',+ alias: 'crate',+ generationId: 'crate',+ role: 'support',+ scale: 1,+ at: [5, 5],+ face: 0,+ exact: { pos: [5, 0, 5], rotYDeg: 0 },+ },+ ],+ };+ return migrateSceneModelV1ToWorldDocumentV2(scene, {+ worldId: 'world',+ artifactSha256ByGenerationId: { crate: 'a'.repeat(64) },+ });+}++describe('runKilnWorldIntegration', () => {+ test('mutates, renders, and finalizes one canonical world authority', async () => {+ const model = new ToolCapturingModel([+ {+ toolCalls: [+ {+ name: 'scene_world_set_sockets',+ input: {+ sockets: [+ {+ id: 'slot',+ kind: 'anchor',+ position: [0, 0, 0],+ rotationYDeg: 90,+ compatibilityTags: ['cargo'],+ capacity: 1,+ },+ ],+ },+ },+ ],+ },+ { toolCalls: [{ name: 'scene_world_snap', input: { objectId: 'crate', socketId: 'slot' } }] },+ { toolCalls: [{ name: 'scene_world_render' }] },+ { toolCalls: [{ name: 'scene_world_finalize' }] },+ { text: 'done' },+ ]);+ const calls: Parameters<SceneRenderPort>[0][] = [];+ const render: SceneRenderPort = async (request) => {+ calls.push(request);+ return { ok: true, pngBase64: Buffer.from('png').toString('base64') };+ };+ const result = await runKilnWorldIntegration({+ model,+ prompt: 'add a cargo anchor',+ world: world(),+ render,+ maxSteps: 8,+ });+ expect(result.error).toBeUndefined();+ expect(result.finalized).toBe(true);+ expect(result.world.objects[0]).toMatchObject({+ socketId: 'slot',+ transform: { position: [0, 0, 0], rotationYDeg: 90 },+ });+ expect(result.placements[0]).toMatchObject({ pos: [0, 0, 0], rotYDeg: 90 });+ expect(calls).toHaveLength(1);+ expect(calls[0]!.worldHash).toBe(result.worldHash);+ expect(calls[0]!.worldDocument).toEqual(result.world);+ expect(model.toolNames[0]).toEqual(+ expect.arrayContaining(['scene_world_snap', 'scene_world_render', 'scene_world_finalize']),+ );+ expect(String(model.seenSystemPrompts[0])).toContain(WORLD_INTEGRATION_PROMPT_V2.slice(0, 30));+ });++ test('shares one aggregate model-call allowance across compose and integration', async () => {+ const budget = createGenerationCallBudget(1);+ const render: SceneRenderPort = async () => ({ ok: true });+ const composed = await runKilnComposer({+ model: new ScriptedModel([{ text: 'first stage done' }]),+ prompt: 'compose a crate',+ catalog: [+ {+ generationId: 'crate',+ bbox: { min: [-1, 0, -1], max: [1, 2, 1] },+ tags: ['cargo'],+ },+ ],+ render,+ maxSteps: 8,+ generationCallBudget: budget,+ });+ expect(composed.callBudget).toMatchObject({ consumed: 1, remaining: 0, denied: 0 });++ const integrated = await runKilnWorldIntegration({+ model: new ScriptedModel([{ text: 'must not dispatch' }]),+ prompt: 'add integration',+ world: world(),+ render,+ generationCallBudget: budget,+ });+ expect(integrated.capped).toBe(true);+ expect(integrated.callBudget).toMatchObject({ consumed: 1, remaining: 0, denied: 1 });+ expect(budget.receipt()).toEqual(integrated.callBudget!);+ });+});diff --git a/src/__tests__/composer-world-tools.test.ts b/src/__tests__/composer-world-tools.test.tsnew file mode 100644index 00000000..cac93115--- /dev/null+++ b/src/__tests__/composer-world-tools.test.ts@@ -0,0 +1,112 @@+import { describe, expect, test } from 'bun:test';+import type { Tool } from '@strands-agents/sdk';+import type { SceneModelJSON } from '../composer';+import { migrateSceneModelV1ToWorldDocumentV2 } from '../composer';+import { makeWorldIntegrationToolsV2, type WorldIntegrationToolState } from '../composer/agent';++function state(): WorldIntegrationToolState {+ const model: SceneModelJSON = {+ name: 'Tools',+ seed: 1,+ catalog: [+ { generationId: 'crate', bbox: { min: [-1, 0, -1], max: [1, 2, 1] }, tags: ['cargo'] },+ ],+ statements: [+ {+ kind: 'place',+ stmtId: 's1',+ alias: 'crate',+ generationId: 'crate',+ role: 'support',+ scale: 1,+ at: [5, 5],+ face: 0,+ exact: { pos: [5, 0, 5], rotYDeg: 0 },+ },+ ],+ };+ return {+ world: migrateSceneModelV1ToWorldDocumentV2(model, {+ worldId: 'tools',+ artifactSha256ByGenerationId: { crate: 'a'.repeat(64) },+ }),+ };+}++interface Invokable {+ name: string;+ invoke(input: unknown): Promise<unknown>;+}+const call = (tools: Tool[], name: string, input: unknown) =>+ (tools.find((tool) => tool.name === name) as unknown as Invokable).invoke(input) as Promise<+ Record<string, unknown>+ >;++describe('Composer V2 world tools', () => {+ test('exposes a bounded seven-tool integration surface and authors canonical state', async () => {+ const target = state();+ const tools = makeWorldIntegrationToolsV2({ state: target });+ expect(tools.map(({ name }) => name).sort()).toEqual(+ [+ 'scene_world_set_heightfield',+ 'scene_world_set_paths',+ 'scene_world_set_sockets',+ 'scene_world_set_spawns',+ 'scene_world_set_zones',+ 'scene_world_snap',+ 'scene_world_fill_path',+ ].sort(),+ );+ expect(+ (+ await call(tools, 'scene_world_set_sockets', {+ sockets: [+ {+ id: 'slot',+ kind: 'anchor',+ position: [0, 0, 0],+ rotationYDeg: 90,+ compatibilityTags: ['cargo'],+ capacity: 1,+ },+ ],+ })+ ).ok,+ ).toBe(true);+ expect(+ (await call(tools, 'scene_world_snap', { objectId: 'crate', socketId: 'slot' })).ok,+ ).toBe(true);+ expect(target.world.objects[0]).toMatchObject({+ socketId: 'slot',+ transform: { position: [0, 0, 0], rotationYDeg: 90 },+ });+ });++ test('publishes the exact heightfield bytes and binds the returned URI/hash', async () => {+ const target = state();+ let published: Uint8Array | undefined;+ const tools = makeWorldIntegrationToolsV2({+ state: target,+ publishHeightfieldArtifact: async (_artifact, bytes) => {+ published = bytes;+ return { uri: 'terrain/generated.heightfield.json' };+ },+ });+ const result = await call(tools, 'scene_world_set_heightfield', {+ origin: [-2, -2],+ cellSize: 1,+ width: 5,+ height: 5,+ baseHeight: 0,+ amplitude: 2,+ frequency: 0.2,+ stamps: [],+ });+ expect(result.ok).toBe(true);+ expect(published!.byteLength).toBeGreaterThan(0);+ expect(target.world.terrain).toMatchObject({+ kind: 'heightfield',+ artifact: { uri: 'terrain/generated.heightfield.json' },+ });+ });+});diff --git a/src/composer/agent/index.ts b/src/composer/agent/index.tsindex f2ceaae1..0da97cd9 100644--- a/src/composer/agent/index.ts+++ b/src/composer/agent/index.ts@@ -17,8 +17,24 @@ export type { RunKilnComposerOptions, RunKilnComposerResult } from './run';export { makeSceneComposerTools } from './tools';export type { ComposerSink, MakeComposerToolsOptions, SceneRenderCandidate } from './tools';-export { buildComposerUserPrompt, COMPOSER_SYSTEM_PROMPT } from './prompt';+export {+ buildComposerUserPrompt,+ COMPOSER_SYSTEM_PROMPT,+ WORLD_INTEGRATION_PROMPT_V2,+} from './prompt';export type { BuildComposerPromptOptions } from './prompt';+export { makeWorldIntegrationToolsV2 } from './world-tools';+export type {+ MakeWorldIntegrationToolsV2Options,+ WorldIntegrationToolState,+} from './world-tools';++export { runKilnWorldIntegration } from './world-run';+export type {+ RunKilnWorldIntegrationOptions,+ RunKilnWorldIntegrationResult,+} from './world-run';+export { SceneCompactionManager } from './compaction';export type { SceneCompactionConfig, SceneCompactionInfo } from './compaction';diff --git a/src/composer/agent/prompt.ts b/src/composer/agent/prompt.tsindex 6415f52b..89bf877a 100644--- a/src/composer/agent/prompt.ts+++ b/src/composer/agent/prompt.ts@@ -57,6 +57,14 @@ Every cluster / ring instance and every laid-out asset counts toward a hard 200-4. Refine with a HANDFUL of targeted edits, not a fresh placement per asset: scene_move / scene_face / scene_group the heroes, and build one or two deliberate clusters or rings for the spaces that matter (a courtyard, a motor-court, a row). Then scene_paint the ground to match (an avenue strip + a plaza). scene_validate for overlaps (move by the mtv). Re-render once to confirm.5. Call scene_finalize once, before the budget runs out. A laid-out, lightly-refined, overlap-free scene that is FINALIZED beats a half-hand-placed one that never finishes.`;+/** Optional Phase 1 addendum for hosts exposing the bounded `scene_world_*` tools. */+export const WORLD_INTEGRATION_PROMPT_V2 = `## World integration+Honor the user's complete world intent; do not narrow the scene into a terrain-only or socket-only task. Use scene_world_* only after the main composition reads well.+- Reserve intentional negative space and keep player spawns and portals clear.+- Author a small number of meaningful paths, anchors, and portals. Compatibility tags must match asset tags; snap only when the relationship is intentional.+- Use one bounded seeded heightfield when terrain materially helps the request. Road/path/pad stamps shape traversable space; keep them inside the generated grid.+- Re-check the composed world after integration. Never trade readable composition for procedural complexity.`;+export interface BuildComposerPromptOptions {/** Natural-language description of the scene to compose. */prompt: string;diff --git a/src/composer/agent/run.ts b/src/composer/agent/run.tsindex 0a07857e..97afc8e8 100644--- a/src/composer/agent/run.ts+++ b/src/composer/agent/run.ts@@ -16,6 +16,7 @@import { Agent, type Message, type Tool } from '@strands-agents/sdk';import { unifiedDiff } from '../../agent/diff';+import type { GenerationCallBudget, GenerationCallBudgetReceipt } from '../../agent/call-budget';import { type AgentUsage, type KilnAgentEvent, MetricsCollector } from '../../agent/hooks';import { toCachedSystemPrompt } from '../../agent/providers';import { SceneCompactionManager } from './compaction';@@ -67,6 +68,10 @@ export interface RunKilnComposerOptions {onCandidate?: (c: SceneRenderCandidate) => void;/** Extra tools to expose (e.g. a Strands McpClient). */extraTools?: unknown[];+ /** Explicit first-stage model-call ceiling; overrides KILN_AGENT_MAX_STEPS. */+ maxSteps?: number;+ /** Shared aggregate allowance across compose, integration, observer, and repair phases. */+ generationCallBudget?: GenerationCallBudget;}export interface RunKilnComposerResult {@@ -88,6 +93,8 @@ export interface RunKilnComposerResult {steps: number;/** Best-effort token usage. */usage?: AgentUsage;+ /** Snapshot of the shared aggregate allowance after this stage, when supplied. */+ callBudget?: GenerationCallBudgetReceipt;/** The last assistant text (fallback / diagnostics). */lastText?: string;/** When refining (seedScene set): a unified diff from the parent program. */@@ -140,11 +147,11 @@ export async function runKilnComposer(// long the run gets, so the cap is a far-back safety net, not the primary stop; the// agent should finalize well before it. Env-overridable (0 disables); shares the// asset-gen knob name for one place to tune.- const maxSteps = Number(process.env['KILN_AGENT_MAX_STEPS'] ?? 80) || 0;+ const maxSteps = opts.maxSteps ?? (Number(process.env['KILN_AGENT_MAX_STEPS'] ?? 80) || 0);// Compact the transcript once it grows past this many messages: the scene state// lives in the model, so the history is disposable working memory. Env-tunable.const compactAt = Number(process.env['KILN_COMPOSER_COMPACT_AT'] ?? 24) || 0;- const metrics = new MetricsCollector(opts.onEvent, maxSteps);+ const metrics = new MetricsCollector(opts.onEvent, maxSteps, opts.generationCallBudget, 'author');const model = buildModel(opts);const parentProgram = opts.seedScene ? serialize(model) : undefined;const sink: ComposerSink = {};@@ -214,6 +221,7 @@ export async function runKilnComposer(toolCalls: collected.toolCalls,steps: collected.steps,...(collected.usage ? { usage: collected.usage } : {}),+ ...(opts.generationCallBudget ? { callBudget: opts.generationCallBudget.receipt() } : {}),...(lastText ? { lastText } : {}),};}@@ -231,6 +239,7 @@ export async function runKilnComposer(toolCalls: collected.toolCalls,steps: collected.steps,...(collected.usage ? { usage: collected.usage } : {}),+ ...(opts.generationCallBudget ? { callBudget: opts.generationCallBudget.receipt() } : {}),...(lastText ? { lastText } : {}),...(diff ? { diff } : {}),};@@ -242,6 +251,7 @@ export async function runKilnComposer(toolCalls: collected.toolCalls,steps: collected.steps,...(collected.usage ? { usage: collected.usage } : {}),+ ...(opts.generationCallBudget ? { callBudget: opts.generationCallBudget.receipt() } : {}),error: err instanceof Error ? err.message : String(err),};} finally {diff --git a/src/composer/agent/world-run.ts b/src/composer/agent/world-run.tsnew file mode 100644index 00000000..a0072495--- /dev/null+++ b/src/composer/agent/world-run.ts@@ -0,0 +1,233 @@+/** Engine-owned bounded second-stage compiler for canonical world integration. */+import {+ Agent,+ ImageBlock,+ JsonBlock,+ type JSONValue,+ type Message,+ type Tool,+ tool,+} from '@strands-agents/sdk';+import { z } from 'zod';+import { type AgentUsage, type KilnAgentEvent, MetricsCollector } from '../../agent/hooks';+import type { GenerationCallBudget, GenerationCallBudgetReceipt } from '../../agent/call-budget';+import { toCachedSystemPrompt } from '../../agent/providers';+import {+ hashWorldDocumentV2,+ parseWorldDocumentV2,+ PlacementModel,+ type Placement,+ type SceneRenderPort,+ type WorldDocumentV2,+ validateWorldIntegrationV2,+ worldDocumentV2ToSceneModelJSON,+} from '..';+import { WORLD_INTEGRATION_PROMPT_V2 } from './prompt';+import {+ makeWorldIntegrationToolsV2,+ type MakeWorldIntegrationToolsV2Options,+ type WorldIntegrationToolState,+} from './world-tools';++export interface RunKilnWorldIntegrationOptions+ extends Omit<MakeWorldIntegrationToolsV2Options, 'state'> {+ model: unknown;+ prompt: string;+ world: unknown;+ render: SceneRenderPort;+ agentName?: string;+ onEvent?: (event: KilnAgentEvent) => void;+ extraTools?: unknown[];+ /** Explicit integration-only model-call ceiling. Required without a shared budget. */+ maxSteps?: number;+ /** Preferred: the same aggregate allowance used by compose/observer/repair roles. */+ generationCallBudget?: GenerationCallBudget;+}++export interface RunKilnWorldIntegrationResult {+ world: WorldDocumentV2;+ worldHash: `sha256:${string}`;+ placements: Placement[];+ finalized: boolean;+ toolCalls: string[];+ steps: number;+ usage?: AgentUsage;+ callBudget?: GenerationCallBudgetReceipt;+ capped?: boolean;+ lastText?: string;+ error?: string;+}++const empty = z.object({}).strict();+const png = (base64: string): Uint8Array => new Uint8Array(Buffer.from(base64, 'base64'));++function placements(world: WorldDocumentV2): Placement[] {+ return PlacementModel.fromJSON(worldDocumentV2ToSceneModelJSON(world)).placements().placements;+}++function lastMessageText(message: Message | undefined): string | undefined {+ if (!message) return undefined;+ const text = message.content+ .filter((block) => (block as { type?: string }).type === 'textBlock')+ .map((block) => (block as { text?: string }).text ?? '')+ .join('\n')+ .trim();+ return text || undefined;+}++function lifecycleTools(+ state: WorldIntegrationToolState,+ render: SceneRenderPort,+ finalized: { value: boolean },+): Tool[] {+ return [+ tool({+ name: 'scene_world_view',+ description: 'Inspect the complete canonical world and authored integration counts.',+ inputSchema: empty,+ callback: async () =>+ ({+ ok: true,+ worldHash: await hashWorldDocumentV2(state.world),+ objects: state.world.objects.length,+ zones: state.world.authored.zones.length,+ paths: state.world.authored.paths.length,+ sockets: state.world.authored.sockets.length,+ spawns: state.world.spawns.length,+ terrain: state.world.terrain.kind,+ }) as JSONValue,+ }),+ tool({+ name: 'scene_world_validate',+ description:+ 'Check socket compatibility/occupancy and every reserved, portal, and spawn clearance.',+ inputSchema: empty,+ callback: () => {+ const issues = validateWorldIntegrationV2(state.world);+ return { ok: issues.length === 0, issues } as unknown as JSONValue;+ },+ }),+ tool({+ name: 'scene_world_render',+ description:+ 'Render the current canonical world after integration edits; inspect before finalizing.',+ inputSchema: empty,+ callback: async () => {+ const worldHash = await hashWorldDocumentV2(state.world);+ const result = await render({+ placements: placements(state.world),+ worldDocument: state.world,+ worldHash,+ lightingPresetId: state.world.environment.lightingPresetId,+ });+ if (!result.ok) return { ok: false, error: result.error ?? 'render failed' } as JSONValue;+ const frames = result.perCameraBase64?.length+ ? result.perCameraBase64+ : result.pngBase64+ ? [result.pngBase64]+ : [];+ return [+ ...frames.map(+ (frame) => new ImageBlock({ format: 'png', source: { bytes: png(frame) } }),+ ),+ new JsonBlock({ json: { ok: true, worldHash, views: frames.length } }),+ ] as unknown as JSONValue;+ },+ }),+ tool({+ name: 'scene_world_finalize',+ description: 'Finalize the validated canonical world after rendering it. Call exactly once.',+ inputSchema: empty,+ callback: async () => {+ const issues = validateWorldIntegrationV2(state.world);+ if (issues.length) return { ok: false, issues } as unknown as JSONValue;+ finalized.value = true;+ return { ok: true, worldHash: await hashWorldDocumentV2(state.world) } as JSONValue;+ },+ }),+ ];+}++/**+ * Run the bounded post-compose integration phase over one canonical authority.+ * Fresh flow: compose -> migrate v1 candidate -> run this. Refine flow: compose+ * candidate -> reconcileWorldDocumentV2Candidate(parent,candidate) -> run this.+ * Every placement-affecting world tool mutates the same state rendered/finalized.+ */+export async function runKilnWorldIntegration(+ options: RunKilnWorldIntegrationOptions,+): Promise<RunKilnWorldIntegrationResult> {+ const state: WorldIntegrationToolState = { world: parseWorldDocumentV2(options.world) };+ const finalized = { value: false };+ const maxSteps = options.maxSteps ?? 0;+ const metrics = new MetricsCollector(+ options.onEvent,+ maxSteps,+ options.generationCallBudget,+ 'author',+ );+ try {+ if (!options.generationCallBudget && (!Number.isInteger(maxSteps) || maxSteps < 1)) {+ throw new Error(+ 'runKilnWorldIntegration requires generationCallBudget or an explicit positive maxSteps',+ );+ }+ const mutationTools = makeWorldIntegrationToolsV2({+ state,+ ...(options.publishHeightfieldArtifact+ ? { publishHeightfieldArtifact: options.publishHeightfieldArtifact }+ : {}),+ ...(options.onWorldChanged ? { onWorldChanged: options.onWorldChanged } : {}),+ });+ const tools: unknown[] = [+ ...mutationTools,+ ...lifecycleTools(state, options.render, finalized),+ ...(options.extraTools ?? []),+ ];+ const agent = new Agent({+ model: options.model as never,+ systemPrompt: toCachedSystemPrompt(WORLD_INTEGRATION_PROMPT_V2, options.model),+ tools: tools as never,+ name: options.agentName ?? 'kiln-world-integrator',+ });+ metrics.attach(agent);+ const result = await agent.invoke(+ `## World integration task\n${options.prompt.trim()}\n\nInspect the current world, make only bounded integration edits that serve the request, render, validate, then finalize.` as never,+ );+ metrics.recordResultUsage(result.metrics?.latestAgentInvocation?.usage);+ const collected = metrics.readMetrics();+ const worldHash = await hashWorldDocumentV2(state.world);+ const lastText = lastMessageText(result.lastMessage);+ return {+ world: state.world,+ worldHash,+ placements: placements(state.world),+ finalized: finalized.value,+ toolCalls: collected.toolCalls,+ steps: collected.steps,+ ...(collected.usage ? { usage: collected.usage } : {}),+ ...(options.generationCallBudget+ ? { callBudget: options.generationCallBudget.receipt() }+ : {}),+ ...(metrics.wasCapped() ? { capped: true } : {}),+ ...(lastText ? { lastText } : {}),+ };+ } catch (error) {+ const collected = metrics.readMetrics();+ return {+ world: state.world,+ worldHash: await hashWorldDocumentV2(state.world),+ placements: placements(state.world),+ finalized: finalized.value,+ toolCalls: collected.toolCalls,+ steps: collected.steps,+ ...(collected.usage ? { usage: collected.usage } : {}),+ ...(options.generationCallBudget+ ? { callBudget: options.generationCallBudget.receipt() }+ : {}),+ error: error instanceof Error ? error.message : String(error),+ };+ } finally {+ metrics.detach();+ }+}diff --git a/src/composer/agent/world-tools.ts b/src/composer/agent/world-tools.tsnew file mode 100644index 00000000..a9737244--- /dev/null+++ b/src/composer/agent/world-tools.ts@@ -0,0 +1,234 @@+/** Bounded Strands tool surface for canonical Composer V2 integration primitives. */+import { type JSONValue, type Tool, tool } from '@strands-agents/sdk';+import { z } from 'zod';+import {+ createHeightfieldArtifactV1,+ encodeHeightfieldArtifactV1,+ hashHeightfieldArtifactV1,+ type HeightfieldArtifactV1,+ fillWorldPathV2,+ setWorldPathsV2,+ setWorldSocketsV2,+ setWorldSpawnsV2,+ setWorldTerrainV2,+ setWorldZonesV2,+ snapWorldObjectToSocketV2,+ type WorldDocumentV2,+} from '..';++export interface WorldIntegrationToolState {+ world: WorldDocumentV2;+}+export interface MakeWorldIntegrationToolsV2Options {+ state: WorldIntegrationToolState;+ publishHeightfieldArtifact?: (+ artifact: HeightfieldArtifactV1,+ bytes: Uint8Array,+ sha256: string,+ ) => Promise<{ uri: string; mediaType?: string }>;+ onWorldChanged?: (world: WorldDocumentV2) => void;+}++const finite = z.number().finite();+const vec2 = z.tuple([finite, finite]);+const vec3 = z.tuple([finite, finite, finite]);+const id = z.string().min(1).max(256);+const positiveVec2 = z.tuple([finite.positive(), finite.positive()]);++export function makeWorldIntegrationToolsV2(options: MakeWorldIntegrationToolsV2Options): Tool[] {+ const commit = (world: WorldDocumentV2): JSONValue => {+ options.state.world = world;+ options.onWorldChanged?.(world);+ return { ok: true, worldId: world.worldId };+ };+ const guarded = (operation: () => WorldDocumentV2): JSONValue => {+ try {+ return commit(operation());+ } catch (error) {+ return { ok: false, error: error instanceof Error ? error.message : String(error) };+ }+ };++ const setZones: Tool = tool({+ name: 'scene_world_set_zones',+ description:+ 'Replace bounded reserved/portal/spawn-clearance zones. Rect halfExtents must be positive.',+ inputSchema: z+ .object({+ zones: z+ .array(+ z+ .object({+ id,+ kind: z.enum(['reserved', 'portal-clearance', 'spawn-clearance']),+ shape: z.discriminatedUnion('type', [+ z+ .object({ type: z.literal('rect'), center: vec2, halfExtents: positiveVec2 })+ .strict(),+ z+ .object({ type: z.literal('circle'), center: vec2, radius: finite.positive() })+ .strict(),+ ]),+ })+ .strict(),+ )+ .max(32),+ })+ .strict(),+ callback: (input) => guarded(() => setWorldZonesV2(options.state.world, input.zones)),+ });+ const setPaths: Tool = tool({+ name: 'scene_world_set_paths',+ description: 'Replace authored navigational paths using world-space X/Y/Z points.',+ inputSchema: z+ .object({+ paths: z+ .array(+ z+ .object({+ id,+ points: z.array(vec3).min(2).max(64),+ halfWidth: finite.positive(),+ })+ .strict(),+ )+ .max(16),+ })+ .strict(),+ callback: (input) => guarded(() => setWorldPathsV2(options.state.world, input.paths)),+ });+ const setSockets: Tool = tool({+ name: 'scene_world_set_sockets',+ description:+ 'Replace named anchors/portals with compatibility, capacity, and portal clearance.',+ inputSchema: z+ .object({+ sockets: z+ .array(+ z+ .object({+ id,+ kind: z.enum(['anchor', 'portal']),+ position: vec3,+ rotationYDeg: finite,+ compatibilityTags: z.array(z.string().min(1).max(128)).min(1).max(16),+ capacity: z.number().int().min(1).max(8),+ clearanceRadius: finite.positive().optional(),+ })+ .strict(),+ )+ .max(32),+ })+ .strict(),+ callback: (input) => guarded(() => setWorldSocketsV2(options.state.world, input.sockets)),+ });+ const setSpawns: Tool = tool({+ name: 'scene_world_set_spawns',+ description: 'Replace player/actor spawns, each with a positive clearance radius.',+ inputSchema: z+ .object({+ spawns: z+ .array(+ z+ .object({+ id,+ position: vec3,+ rotationYDeg: finite,+ clearanceRadius: finite.positive(),+ })+ .strict(),+ )+ .max(16),+ })+ .strict(),+ callback: (input) => guarded(() => setWorldSpawnsV2(options.state.world, input.spawns)),+ });+ const snap: Tool = tool({+ name: 'scene_world_snap',+ description:+ 'Snap one compatible object exactly to a named socket; fails when incompatible or full.',+ inputSchema: z.object({ objectId: id, socketId: id }).strict(),+ callback: (input) => guarded(() => snapWorldObjectToSocketV2(options.state.world, input)),+ });+ const fillPath: Tool = tool({+ name: 'scene_world_fill_path',+ description:+ 'Repeat one existing object along a path with deterministic arc-length spacing and tangent facing.',+ inputSchema: z+ .object({+ pathId: id,+ templateObjectId: id,+ idPrefix: z.string().min(1).max(240),+ count: z.number().int().min(1).max(32),+ spacing: finite.positive(),+ startDistance: finite.nonnegative().optional(),+ })+ .strict(),+ callback: (input) => guarded(() => fillWorldPathV2(options.state.world, input)),+ });+ const stampSchema = z.discriminatedUnion('kind', [+ z+ .object({+ kind: z.enum(['road', 'path']),+ points: z.array(vec2).min(2).max(64),+ halfWidth: finite.positive(),+ targetHeight: finite,+ })+ .strict(),+ z+ .object({+ kind: z.literal('pad'),+ center: vec2,+ halfExtents: positiveVec2,+ targetHeight: finite,+ })+ .strict(),+ ]);+ const setHeightfield: Tool = tool({+ name: 'scene_world_set_heightfield',+ description:+ 'Generate and bind one bounded seeded heightfield with optional road/path/pad stamps.',+ inputSchema: z+ .object({+ origin: vec2,+ cellSize: finite.positive(),+ width: z.number().int().min(2).max(129),+ height: z.number().int().min(2).max(129),+ baseHeight: finite,+ amplitude: finite.nonnegative(),+ frequency: finite.positive(),+ stamps: z.array(stampSchema).max(16),+ })+ .strict(),+ callback: async (input) => {+ if (!options.publishHeightfieldArtifact)+ return {+ ok: false,+ error: 'heightfield artifact publisher is not configured',+ } as JSONValue;+ try {+ const artifact = createHeightfieldArtifactV1({ ...input, seed: options.state.world.seed });+ const bytes = encodeHeightfieldArtifactV1(artifact);+ const sha256 = await hashHeightfieldArtifactV1(artifact);+ const published = await options.publishHeightfieldArtifact(artifact, bytes, sha256);+ const result = commit(+ setWorldTerrainV2(options.state.world, {+ kind: 'heightfield',+ artifact: {+ uri: published.uri,+ sha256,+ mediaType: published.mediaType ?? 'application/vnd.kiln.heightfield+json',+ },+ }),+ ) as Record<string, JSONValue>;+ return { ...result, sha256, bytes: bytes.byteLength } as JSONValue;+ } catch (error) {+ return {+ ok: false,+ error: error instanceof Error ? error.message : String(error),+ } as JSONValue;+ }+ },+ });+ return [setZones, setPaths, setSockets, setSpawns, snap, fillPath, setHeightfield];+}diff --git a/src/composer/ground.ts b/src/composer/ground.tsindex 429f5a12..af7395ee 100644--- a/src/composer/ground.ts+++ b/src/composer/ground.ts@@ -9,10 +9,17 @@export interface GroundSampler {/** World-space terrain height at (x, z). */heightAt(x: number, z: number): number;+ /** World-space upward surface normal. Flat and canonical heightfields provide it. */+ normalAt?(x: number, z: number): [number, number, number];}/** Constant-height ground (the default, y = 0). */-export const flatGround = (y = 0): GroundSampler => ({ heightAt: () => y });+export const flatGround = (+ y = 0,+): GroundSampler & { normalAt(x: number, z: number): [number, number, number] } => ({+ heightAt: () => y,+ normalAt: () => [0, 1, 0],+});/** Mark a sampler as terrain — the heightmap seam. Identity today (a heightfield* is just a `GroundSampler`); exists so a scene program reads `heightmap(fn)`diff --git a/src/composer/index.ts b/src/composer/index.tsindex 3813039e..b70b0293 100644--- a/src/composer/index.ts+++ b/src/composer/index.ts@@ -10,4 +10,6 @@ export * from './layout';export * from './model';export * from './overlap';export * from './render-port';+export * from './terrain';export * from './world-document';+export * from './world-integration';diff --git a/src/composer/render-port.ts b/src/composer/render-port.tsindex 53a84cf8..40b99c45 100644--- a/src/composer/render-port.ts+++ b/src/composer/render-port.ts@@ -5,21 +5,57 @@* the rasterizer). Bun tests inject a stub returning a fixed PNG.*/import type { Placement } from './model';+import type { WorldDocumentV2 } from './world-document';export interface SceneCamera {position: [number, number, number];target: [number, number, number];+ /** World-space camera up vector. Host default is [0,1,0]. */+ up?: [number, number, number];/** Vertical FOV in degrees. Default ~50. */fovDeg?: number;+ aspect?: number;+ near?: number;+ far?: number;+}++/** Fully resolved camera values recorded in an immutable render receipt. */+export interface ResolvedSceneCamera {+ position: [number, number, number];+ target: [number, number, number];+ up: [number, number, number];+ fovDeg: number;+ aspect: number;+ near: number;+ far: number;}export interface SceneRenderRequest {/** The evaluated scene (generationId + transform per instance). */placements: Placement[];+ /** Canonical authority for terrain/artifact resolution on world-aware host adapters. */+ worldDocument?: WorldDocumentV2;/** Omit for the standard 3-angle grid; pass one camera for a custom shot. */cameras?: SceneCamera[];width?: number;height?: number;+ /** Canonical input identity for an immutable GPU milestone. */+ worldHash?: `sha256:${string}`;+ lightingPresetId?: string;+ /** Requested host backend, e.g. `webgpu` or `vulkan`; host reports actual backend. */+ backendPreference?: string;+}++/** Reproducibility/provenance record for a successful GPU milestone render. */+export interface SceneRenderReceipt {+ worldHash: `sha256:${string}`;+ cameras: ResolvedSceneCamera[];+ width: number;+ height: number;+ lightingPresetId: string;+ backend: string;+ rendererId: string;+ outputSha256: `sha256:${string}`;}export interface SceneRenderResult {@@ -29,6 +65,8 @@ export interface SceneRenderResult {/** One PNG per requested camera, when more than one was passed. */perCameraBase64?: string[];tris?: number;+ /** Present when the host renders an immutable canonical-world milestone. */+ receipt?: SceneRenderReceipt;error?: string;}diff --git a/src/composer/terrain-runtime.ts b/src/composer/terrain-runtime.tsnew file mode 100644index 00000000..9dfb8cca--- /dev/null+++ b/src/composer/terrain-runtime.ts@@ -0,0 +1,415 @@+/**+ * Canonical dependency-free heightfield runtime.+ *+ * This file is intentionally self-contained: no Node, Zod, THREE, or import-time+ * I/O. Hosts may copy its exact source through an identity-checked vendor step so+ * browser/server/Engine consumers execute one implementation.+ */+export const HEIGHTFIELD_RUNTIME_SOURCE_VERSION = 'kiln.heightfield-runtime.v1' as const;+export const HEIGHTFIELD_ARTIFACT_V1_SCHEMA_VERSION = 'kiln.heightfield.v1' as const;+/** Heights use nearest-step rounding to 1/1024 world unit; negative zero canonicalizes to zero. */+export const HEIGHTFIELD_QUANTIZATION_STEP = 1 / 1024;++export function quantizeHeightfieldSample(value: number): number {+ const quantized =+ Math.round(value / HEIGHTFIELD_QUANTIZATION_STEP) * HEIGHTFIELD_QUANTIZATION_STEP;+ return Object.is(quantized, -0) ? 0 : quantized;+}++export type HeightfieldVec2 = [number, number];+export type HeightfieldVec3 = [number, number, number];++export type TerrainStampV1 =+ | { kind: 'road' | 'path'; points: HeightfieldVec2[]; halfWidth: number; targetHeight: number }+ | { kind: 'pad'; center: HeightfieldVec2; halfExtents: HeightfieldVec2; targetHeight: number };++export interface HeightfieldArtifactV1 {+ schemaVersion: typeof HEIGHTFIELD_ARTIFACT_V1_SCHEMA_VERSION;+ seed: number;+ origin: HeightfieldVec2;+ cellSize: number;+ width: number;+ height: number;+ baseHeight: number;+ amplitude: number;+ frequency: number;+ stamps: TerrainStampV1[];+ heights: number[];+}++export interface CreateHeightfieldArtifactV1Input {+ seed: number;+ origin: HeightfieldVec2;+ cellSize: number;+ width: number;+ height: number;+ baseHeight: number;+ amplitude: number;+ frequency: number;+ stamps?: readonly TerrainStampV1[];+}++export interface TerrainSampler {+ heightAt(x: number, z: number): number;+ normalAt(x: number, z: number): HeightfieldVec3;+}++export interface HeightfieldMeshDataV1 {+ /** XYZ triples in canonical row-major grid order. */+ positions: number[];+ /** XYZ triples from the canonical sampler at each vertex. */+ normals: number[];+ /** Upward-wound triangle indices, two triangles per grid cell. */+ indices: number[];+}++const own = (value: object, key: string): boolean => Object.hasOwn(value, key);++function fail(path: string, message: string): never {+ throw new TypeError(`${path}: ${message}`);+}++function record(value: unknown, path: string): Record<string, unknown> {+ if (value === null || typeof value !== 'object' || Array.isArray(value))+ fail(path, 'expected object');+ return value as Record<string, unknown>;+}++function exactKeys(value: Record<string, unknown>, keys: readonly string[], path: string): void {+ const allowed = new Set(keys);+ for (const key of Object.keys(value))+ if (!allowed.has(key)) fail(`${path}.${key}`, 'unknown key');+ for (const key of keys) if (!own(value, key)) fail(`${path}.${key}`, 'required');+}++function finite(value: unknown, path: string): number {+ if (typeof value !== 'number' || !Number.isFinite(value)) fail(path, 'expected finite number');+ return value;+}++function positive(value: unknown, path: string): number {+ const parsed = finite(value, path);+ if (parsed <= 0) fail(path, 'expected positive number');+ return parsed;+}++function safeInteger(value: unknown, path: string, min?: number, max?: number): number {+ if (typeof value !== 'number' || !Number.isSafeInteger(value))+ fail(path, 'expected safe integer');+ if (min != null && value < min) fail(path, `expected at least ${min}`);+ if (max != null && value > max) fail(path, `expected at most ${max}`);+ return value;+}++function vec2(value: unknown, path: string, positiveOnly = false): HeightfieldVec2 {+ if (!Array.isArray(value) || value.length !== 2) fail(path, 'expected [x,z]');+ const result: HeightfieldVec2 = [finite(value[0], `${path}[0]`), finite(value[1], `${path}[1]`)];+ if (positiveOnly && (result[0] <= 0 || result[1] <= 0))+ fail(path, 'expected positive components');+ return result;+}++function parseStamp(value: unknown, path: string): TerrainStampV1 {+ const input = record(value, path);+ const kind = input.kind;+ if (kind === 'pad') {+ exactKeys(input, ['kind', 'center', 'halfExtents', 'targetHeight'], path);+ return {+ kind,+ center: vec2(input.center, `${path}.center`),+ halfExtents: vec2(input.halfExtents, `${path}.halfExtents`, true),+ targetHeight: quantizeHeightfieldSample(finite(input.targetHeight, `${path}.targetHeight`)),+ };+ }+ if (kind !== 'road' && kind !== 'path') fail(`${path}.kind`, 'expected road, path, or pad');+ exactKeys(input, ['kind', 'points', 'halfWidth', 'targetHeight'], path);+ if (!Array.isArray(input.points) || input.points.length < 2 || input.points.length > 128) {+ fail(`${path}.points`, 'expected 2..128 points');+ }+ return {+ kind,+ points: input.points.map((point, index) => vec2(point, `${path}.points[${index}]`)),+ halfWidth: positive(input.halfWidth, `${path}.halfWidth`),+ targetHeight: quantizeHeightfieldSample(finite(input.targetHeight, `${path}.targetHeight`)),+ };+}++/** Strict fail-closed parser and clone for serialized/runtime consumers. */+export function parseHeightfieldArtifactV1(value: unknown): HeightfieldArtifactV1 {+ const input = record(value, 'heightfield');+ exactKeys(+ input,+ [+ 'schemaVersion',+ 'seed',+ 'origin',+ 'cellSize',+ 'width',+ 'height',+ 'baseHeight',+ 'amplitude',+ 'frequency',+ 'stamps',+ 'heights',+ ],+ 'heightfield',+ );+ if (input.schemaVersion !== HEIGHTFIELD_ARTIFACT_V1_SCHEMA_VERSION) {+ fail('heightfield.schemaVersion', `expected ${HEIGHTFIELD_ARTIFACT_V1_SCHEMA_VERSION}`);+ }+ const width = safeInteger(input.width, 'heightfield.width', 2, 257);+ const height = safeInteger(input.height, 'heightfield.height', 2, 257);+ if (!Array.isArray(input.stamps) || input.stamps.length > 64)+ fail('heightfield.stamps', 'expected at most 64 stamps');+ if (!Array.isArray(input.heights) || input.heights.length !== width * height) {+ fail('heightfield.heights', `expected ${width * height} row-major samples`);+ }+ const amplitude = finite(input.amplitude, 'heightfield.amplitude');+ if (amplitude < 0) fail('heightfield.amplitude', 'expected non-negative number');+ return {+ schemaVersion: HEIGHTFIELD_ARTIFACT_V1_SCHEMA_VERSION,+ seed: safeInteger(input.seed, 'heightfield.seed'),+ origin: vec2(input.origin, 'heightfield.origin'),+ cellSize: positive(input.cellSize, 'heightfield.cellSize'),+ width,+ height,+ baseHeight: finite(input.baseHeight, 'heightfield.baseHeight'),+ amplitude,+ frequency: positive(input.frequency, 'heightfield.frequency'),+ stamps: input.stamps.map((stamp, index) => parseStamp(stamp, `heightfield.stamps[${index}]`)),+ heights: input.heights.map((sample, index) =>+ quantizeHeightfieldSample(finite(sample, `heightfield.heights[${index}]`)),+ ),+ };+}++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 entry = value as Record<string, unknown>;+ return `{${Object.keys(entry)+ .sort()+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(entry[key])}`)+ .join(',')}}`;+ }+ throw new TypeError(`unsupported canonical JSON value: ${typeof value}`);+}++function hashLattice(seed: number, x: number, z: number): number {+ let value = seed | 0;+ value ^= Math.imul(x | 0, 0x9e3779b1);+ value ^= Math.imul(z | 0, 0x85ebca77);+ value ^= value >>> 16;+ value = Math.imul(value, 0x7feb352d);+ value ^= value >>> 15;+ value = Math.imul(value, 0x846ca68b);+ value ^= value >>> 16;+ return (value >>> 0) / 0xffffffff;+}++const smooth = (value: number): number => value * value * (3 - 2 * value);++function valueNoise(seed: number, x: number, z: number): number {+ const x0 = Math.floor(x);+ const z0 = Math.floor(z);+ const tx = smooth(x - x0);+ const tz = smooth(z - z0);+ const top = hashLattice(seed, x0, z0) * (1 - tx) + hashLattice(seed, x0 + 1, z0) * tx;+ const bottom = hashLattice(seed, x0, z0 + 1) * (1 - tx) + hashLattice(seed, x0 + 1, z0 + 1) * tx;+ return top * (1 - tz) + bottom * tz;+}++export function createHeightfieldArtifactV1(+ input: CreateHeightfieldArtifactV1Input,+): HeightfieldArtifactV1 {+ const seed = safeInteger(input.seed, 'input.seed');+ const origin = vec2(input.origin, 'input.origin');+ const cellSize = positive(input.cellSize, 'input.cellSize');+ const width = safeInteger(input.width, 'input.width', 2, 257);+ const height = safeInteger(input.height, 'input.height', 2, 257);+ const baseHeight = finite(input.baseHeight, 'input.baseHeight');+ const amplitude = finite(input.amplitude, 'input.amplitude');+ if (amplitude < 0) fail('input.amplitude', 'expected non-negative number');+ const frequency = positive(input.frequency, 'input.frequency');+ const candidate: HeightfieldArtifactV1 = {+ schemaVersion: HEIGHTFIELD_ARTIFACT_V1_SCHEMA_VERSION,+ seed,+ origin,+ cellSize,+ width,+ height,+ baseHeight,+ amplitude,+ frequency,+ stamps: [],+ heights: Array.from({ length: width * height }, (_, index) => {+ const column = index % width;+ const row = Math.floor(index / width);+ const x = origin[0] + column * cellSize;+ const z = origin[1] + row * cellSize;+ return quantizeHeightfieldSample(+ baseHeight + amplitude * (valueNoise(seed, x * frequency, z * frequency) * 2 - 1),+ );+ }),+ };+ const parsed = parseHeightfieldArtifactV1(candidate);+ return input.stamps?.length ? stampHeightfieldArtifactV1(parsed, input.stamps) : parsed;+}++function squaredDistanceToSegment(+ x: number,+ z: number,+ start: HeightfieldVec2,+ end: HeightfieldVec2,+): number {+ const dx = end[0] - start[0];+ const dz = end[1] - start[1];+ const lengthSquared = dx * dx + dz * dz;+ const t =+ lengthSquared === 0+ ? 0+ : Math.max(0, Math.min(1, ((x - start[0]) * dx + (z - start[1]) * dz) / lengthSquared));+ const nearestX = start[0] + dx * t;+ const nearestZ = start[1] + dz * t;+ return (x - nearestX) ** 2 + (z - nearestZ) ** 2;+}++function stampContains(stamp: TerrainStampV1, x: number, z: number): boolean {+ if (stamp.kind === 'pad') {+ return (+ Math.abs(x - stamp.center[0]) <= stamp.halfExtents[0] &&+ Math.abs(z - stamp.center[1]) <= stamp.halfExtents[1]+ );+ }+ const radiusSquared = stamp.halfWidth * stamp.halfWidth;+ return stamp.points+ .slice(1)+ .some(+ (point, index) =>+ squaredDistanceToSegment(x, z, stamp.points[index]!, point) <= radiusSquared,+ );+}++export function stampHeightfieldArtifactV1(+ source: unknown,+ stampValues: readonly TerrainStampV1[],+): HeightfieldArtifactV1 {+ const artifact = parseHeightfieldArtifactV1(source);+ const stamps = stampValues.map((stamp, index) => parseStamp(stamp, `stamps[${index}]`));+ if (artifact.stamps.length + stamps.length > 64)+ fail('stamps', 'heightfield supports at most 64 stamps');+ const heights = [...artifact.heights];+ for (const stamp of stamps) {+ for (let row = 0; row < artifact.height; row++) {+ for (let column = 0; column < artifact.width; column++) {+ const x = artifact.origin[0] + column * artifact.cellSize;+ const z = artifact.origin[1] + row * artifact.cellSize;+ if (stampContains(stamp, x, z)) heights[row * artifact.width + column] = stamp.targetHeight;+ }+ }+ }+ return parseHeightfieldArtifactV1({+ ...artifact,+ stamps: [...artifact.stamps, ...stamps],+ heights,+ });+}++/** Exact canonical UTF-8 bytes bound by the world terrain artifact SHA-256. */+export function encodeHeightfieldArtifactV1(source: unknown): Uint8Array {+ return new TextEncoder().encode(canonicalJson(parseHeightfieldArtifactV1(source)));+}++function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {+ if (left.byteLength !== right.byteLength) return false;+ for (let index = 0; index < left.byteLength; index++) {+ if (left[index] !== right[index]) return false;+ }+ return true;+}++/** Decode only the one canonical byte representation bound by the artifact SHA-256. */+export function decodeHeightfieldArtifactV1(bytes: Uint8Array): HeightfieldArtifactV1 {+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);+ const artifact = parseHeightfieldArtifactV1(JSON.parse(text));+ if (!bytesEqual(bytes, encodeHeightfieldArtifactV1(artifact))) {+ throw new TypeError('heightfield bytes are not canonical');+ }+ return artifact;+}++export async function hashHeightfieldArtifactV1(source: unknown): Promise<string> {+ const bytes = encodeHeightfieldArtifactV1(source);+ const buffer = bytes.buffer.slice(+ bytes.byteOffset,+ bytes.byteOffset + bytes.byteLength,+ ) as ArrayBuffer;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', buffer));+ return [...digest].map((byte) => byte.toString(16).padStart(2, '0')).join('');+}++export function heightfieldGround(source: unknown): TerrainSampler {+ const artifact = parseHeightfieldArtifactV1(source);+ const maxX = artifact.origin[0] + (artifact.width - 1) * artifact.cellSize;+ const maxZ = artifact.origin[1] + (artifact.height - 1) * artifact.cellSize;+ const clamp = (value: number, min: number, max: number): number =>+ Math.max(min, Math.min(max, value));+ const heightAt = (worldX: number, worldZ: number): number => {+ const x = (clamp(worldX, artifact.origin[0], maxX) - artifact.origin[0]) / artifact.cellSize;+ const z = (clamp(worldZ, artifact.origin[1], maxZ) - artifact.origin[1]) / artifact.cellSize;+ const x0 = Math.floor(x);+ const z0 = Math.floor(z);+ const x1 = Math.min(artifact.width - 1, x0 + 1);+ const z1 = Math.min(artifact.height - 1, z0 + 1);+ const tx = x - x0;+ const tz = z - z0;+ const top =+ artifact.heights[z0 * artifact.width + x0]! * (1 - tx) ++ artifact.heights[z0 * artifact.width + x1]! * tx;+ const bottom =+ artifact.heights[z1 * artifact.width + x0]! * (1 - tx) ++ artifact.heights[z1 * artifact.width + x1]! * tx;+ return top * (1 - tz) + bottom * tz;+ };+ const normalAt = (x: number, z: number): HeightfieldVec3 => {+ const left = clamp(x - artifact.cellSize, artifact.origin[0], maxX);+ const right = clamp(x + artifact.cellSize, artifact.origin[0], maxX);+ const down = clamp(z - artifact.cellSize, artifact.origin[1], maxZ);+ const up = clamp(z + artifact.cellSize, artifact.origin[1], maxZ);+ const dx = right === left ? 0 : (heightAt(right, z) - heightAt(left, z)) / (right - left);+ const dz = up === down ? 0 : (heightAt(x, up) - heightAt(x, down)) / (up - down);+ const length = Math.hypot(dx, 1, dz);+ return [-dx / length, 1 / length, -dz / length];+ };+ return { heightAt, normalAt };+}++/** Canonical renderer-neutral mesh buffers; consumers only choose GPU buffer types/materials. */+export function heightfieldMeshDataV1(source: unknown): HeightfieldMeshDataV1 {+ const artifact = parseHeightfieldArtifactV1(source);+ const sampler = heightfieldGround(artifact);+ const positions: number[] = [];+ const normals: number[] = [];+ const indices: number[] = [];+ for (let row = 0; row < artifact.height; row++) {+ for (let column = 0; column < artifact.width; column++) {+ const x = artifact.origin[0] + column * artifact.cellSize;+ const z = artifact.origin[1] + row * artifact.cellSize;+ positions.push(x, artifact.heights[row * artifact.width + column]!, z);+ normals.push(...sampler.normalAt(x, z));+ }+ }+ for (let row = 0; row < artifact.height - 1; row++) {+ for (let column = 0; column < artifact.width - 1; column++) {+ const a = row * artifact.width + column;+ const b = a + 1;+ const c = a + artifact.width;+ const d = c + 1;+ indices.push(a, c, b, b, c, d);+ }+ }+ return { positions, normals, indices };+}diff --git a/src/composer/terrain.test.ts b/src/composer/terrain.test.tsnew file mode 100644index 00000000..fd4e8b62--- /dev/null+++ b/src/composer/terrain.test.ts@@ -0,0 +1,174 @@+import { createHash } from 'node:crypto';+import { describe, expect, test } from 'bun:test';+import {+ createHeightfieldArtifactV1,+ decodeHeightfieldArtifactV1,+ encodeHeightfieldArtifactV1,+ hashHeightfieldArtifactV1,+ HEIGHTFIELD_QUANTIZATION_STEP,+ heightfieldGround,+ heightfieldMeshDataV1,+ stampHeightfieldArtifactV1,+} from './terrain';+import { flatGround } from './ground';++describe('HeightfieldArtifactV1', () => {+ test('is deterministic by seed and hashes the exact canonical bytes', async () => {+ const input = {+ seed: 42,+ origin: [-4, -4] as [number, number],+ cellSize: 2,+ width: 5,+ height: 5,+ baseHeight: 1,+ amplitude: 3,+ frequency: 0.2,+ };+ const a = createHeightfieldArtifactV1(input);+ const b = createHeightfieldArtifactV1(input);+ const c = createHeightfieldArtifactV1({ ...input, seed: 43 });+ expect(encodeHeightfieldArtifactV1(a)).toEqual(encodeHeightfieldArtifactV1(b));+ expect(a.heights).not.toEqual(c.heights);+ expect(+ a.heights.every((height) => Number.isInteger(height / HEIGHTFIELD_QUANTIZATION_STEP)),+ ).toBe(true);+ const expected = createHash('sha256').update(encodeHeightfieldArtifactV1(a)).digest('hex');+ expect(await hashHeightfieldArtifactV1(a)).toBe(expected);+ expect(decodeHeightfieldArtifactV1(encodeHeightfieldArtifactV1(a))).toEqual(a);+ });++ test('samples bilinear height, clamped edges, and normalized terrain normals', () => {+ const artifact = {+ schemaVersion: 'kiln.heightfield.v1' as const,+ seed: 1,+ origin: [10, 20] as [number, number],+ cellSize: 2,+ width: 2,+ height: 2,+ baseHeight: 0,+ amplitude: 0,+ frequency: 1,+ stamps: [],+ heights: [0, 2, 4, 6],+ };+ const sampler = heightfieldGround(artifact);+ expect(sampler.heightAt(11, 21)).toBe(3);+ expect(sampler.heightAt(-100, -100)).toBe(0);+ expect(sampler.heightAt(100, 100)).toBe(6);+ const normal = sampler.normalAt(11, 21);+ expect(Math.hypot(...normal)).toBeCloseTo(1, 12);+ expect(normal[1]).toBeGreaterThan(0);+ expect(flatGround(9).normalAt(0, 0)).toEqual([0, 1, 0]);+ const mesh = heightfieldMeshDataV1(artifact);+ expect(mesh.positions).toEqual([10, 0, 20, 12, 2, 20, 10, 4, 22, 12, 6, 22]);+ expect(mesh.indices).toEqual([0, 2, 1, 1, 2, 3]);+ expect(mesh.normals).toHaveLength(12);+ });++ test('applies bounded road, path, and pad stamps without mutating the source', () => {+ const source = createHeightfieldArtifactV1({+ seed: 1,+ origin: [0, 0],+ cellSize: 1,+ width: 7,+ height: 7,+ baseHeight: 5,+ amplitude: 0,+ frequency: 1,+ });+ const stamped = stampHeightfieldArtifactV1(source, [+ {+ kind: 'road',+ points: [+ [0, 3],+ [6, 3],+ ],+ halfWidth: 0.6,+ targetHeight: 1,+ },+ {+ kind: 'path',+ points: [+ [3, 0],+ [3, 6],+ ],+ halfWidth: 0.4,+ targetHeight: 2,+ },+ { kind: 'pad', center: [5, 5], halfExtents: [0.75, 0.75], targetHeight: 3 },+ ]);+ expect(source.heights.every((height) => height === 5)).toBe(true);+ const sampler = heightfieldGround(stamped);+ expect(sampler.heightAt(1, 3)).toBe(1);+ expect(sampler.heightAt(3, 1)).toBe(2);+ expect(sampler.heightAt(5, 5)).toBe(3);+ expect(stamped.stamps).toHaveLength(3);+ });++ test('fails closed on unknown versions, invalid dimensions, and non-positive stamp extents', () => {+ expect(() =>+ createHeightfieldArtifactV1({+ seed: 1,+ origin: [0, 0],+ cellSize: 1,+ width: 258,+ height: 2,+ baseHeight: 0,+ amplitude: 1,+ frequency: 1,+ }),+ ).toThrow();+ expect(() =>+ decodeHeightfieldArtifactV1(+ new TextEncoder().encode(JSON.stringify({ schemaVersion: 'kiln.heightfield.v2' })),+ ),+ ).toThrow();+ const flat = createHeightfieldArtifactV1({+ seed: 1,+ origin: [0, 0],+ cellSize: 1,+ width: 2,+ height: 2,+ baseHeight: 0,+ amplitude: 0,+ frequency: 1,+ });+ expect(() =>+ stampHeightfieldArtifactV1(flat, [+ { kind: 'pad', center: [0, 0], halfExtents: [0, 1], targetHeight: 0 },+ ]),+ ).toThrow();+ });++ test('decode rejects every noncanonical byte representation and invalid UTF-8', () => {+ const artifact = createHeightfieldArtifactV1({+ seed: 3,+ origin: [0, 0],+ cellSize: 1,+ width: 2,+ height: 2,+ baseHeight: 0,+ amplitude: 0,+ frequency: 1,+ });+ const canonical = encodeHeightfieldArtifactV1(artifact);+ const text = new TextDecoder().decode(canonical);+ expect(decodeHeightfieldArtifactV1(canonical)).toEqual(artifact);+ expect(() => decodeHeightfieldArtifactV1(new TextEncoder().encode(` ${text}`))).toThrow(+ 'not canonical',+ );++ const parsed = JSON.parse(text) as Record<string, unknown>;+ const reversed = Object.fromEntries(Object.entries(parsed).reverse());+ expect(() =>+ decodeHeightfieldArtifactV1(new TextEncoder().encode(JSON.stringify(reversed))),+ ).toThrow('not canonical');++ const nonquantized = structuredClone(parsed) as { heights: number[] };+ nonquantized.heights[0] = HEIGHTFIELD_QUANTIZATION_STEP / 3;+ expect(() =>+ decodeHeightfieldArtifactV1(new TextEncoder().encode(JSON.stringify(nonquantized))),+ ).toThrow('not canonical');+ expect(() => decodeHeightfieldArtifactV1(new Uint8Array([0xc3, 0x28]))).toThrow();+ });+});diff --git a/src/composer/terrain.ts b/src/composer/terrain.tsnew file mode 100644index 00000000..4afeb031--- /dev/null+++ b/src/composer/terrain.ts@@ -0,0 +1,53 @@+/** Zod authoring schema around the dependency-free canonical terrain runtime. */+import { z } from 'zod';+import { HEIGHTFIELD_ARTIFACT_V1_SCHEMA_VERSION } from './terrain-runtime';++const finite = z.number().finite();+const vec2 = z.tuple([finite, finite]);+const positiveVec2 = z.tuple([finite.positive(), finite.positive()]);++export const TerrainStampV1Schema = z.discriminatedUnion('kind', [+ z+ .object({+ kind: z.enum(['road', 'path']),+ points: z.array(vec2).min(2).max(128),+ halfWidth: finite.positive(),+ targetHeight: finite,+ })+ .strict(),+ z+ .object({+ kind: z.literal('pad'),+ center: vec2,+ halfExtents: positiveVec2,+ targetHeight: finite,+ })+ .strict(),+]);++export const HeightfieldArtifactV1Schema = z+ .object({+ schemaVersion: z.literal(HEIGHTFIELD_ARTIFACT_V1_SCHEMA_VERSION),+ seed: z.number().int().safe(),+ origin: vec2,+ cellSize: finite.positive(),+ width: z.number().int().min(2).max(257),+ height: z.number().int().min(2).max(257),+ baseHeight: finite,+ amplitude: finite.nonnegative(),+ frequency: finite.positive(),+ stamps: z.array(TerrainStampV1Schema).max(64),+ heights: z.array(finite).max(257 * 257),+ })+ .strict()+ .superRefine((artifact, ctx) => {+ if (artifact.heights.length !== artifact.width * artifact.height) {+ ctx.addIssue({+ code: 'custom',+ path: ['heights'],+ message: `expected ${artifact.width * artifact.height} row-major samples`,+ });+ }+ });++export * from './terrain-runtime';diff --git a/src/composer/world-document.ts b/src/composer/world-document.tsindex 9656e1c0..d5673c25 100644--- a/src/composer/world-document.ts+++ b/src/composer/world-document.ts@@ -21,9 +21,13 @@ export const WORLD_DOCUMENT_V2_SCHEMA_VERSION = 'kiln.world.v2' as const;const finite = z.number().finite();const vec2 = z.tuple([finite, finite]);+const positiveVec2 = z.tuple([finite.positive(), finite.positive()]);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 generationIdSchema = z+ .string()+ .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/, 'expected a portable generation id');const boundsSchema = z.object({ min: vec3, max: vec3 })@@ -103,9 +107,24 @@ const paintZoneSchema = z}).strict();+const portableArtifactUri = z+ .string()+ .min(1)+ .max(2048)+ .refine(+ (uri) =>+ !uri.startsWith('/') &&+ !uri.includes('\\') &&+ !uri.includes('?') &&+ !uri.includes('#') &&+ !/^[a-z][a-z0-9+.-]*:/i.test(uri) &&+ uri.split('/').every((segment) => segment.length > 0 && segment !== '.' && segment !== '..'),+ 'expected a portable package-relative artifact URI',+ );+const artifactSchema = z.object({- uri: z.string().min(1).max(2048),+ uri: portableArtifactUri,sha256,mediaType: z.string().min(1).max(128).optional(),})@@ -114,7 +133,7 @@ const artifactSchema = zconst assetSchema = z.object({refId: nonEmptyId,- generationId: nonEmptyId,+ generationId: generationIdSchema,artifactSha256: sha256,bounds: boundsSchema,name: z.string().min(1).max(256).optional(),@@ -137,6 +156,7 @@ const objectSchema = z.strict(),role: roleSchema,groupId: nonEmptyId.optional(),+ socketId: nonEmptyId.optional(),collision: z.discriminatedUnion('policy', [z.object({ policy: z.literal('none') }).strict(),@@ -149,6 +169,24 @@ const objectSchema = zsourceStatementId: nonEmptyId,sourcePrompt: z.string().min(1).max(4000).optional(),parentGenerationId: nonEmptyId.optional(),+ activeAsset: z+ .object({ generationId: generationIdSchema, artifactSha256: sha256 })+ .strict()+ .optional(),+ assetHistory: z+ .array(+ z+ .object({+ kind: z.literal('asset-swap'),+ fromGenerationId: generationIdSchema,+ toGenerationId: generationIdSchema,+ fromArtifactSha256: sha256,+ toArtifactSha256: sha256,+ })+ .strict(),+ )+ .max(128)+ .optional(),}).strict(),})@@ -159,7 +197,7 @@ const zoneSchema = zid: 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('rect'), center: vec2, halfExtents: positiveVec2 }).strict(),z.object({ type: z.literal('circle'), center: vec2, radius: finite.positive() }).strict(),]),})@@ -176,11 +214,30 @@ const pathSchema = zconst socketSchema = z.object({id: nonEmptyId,+ kind: z.enum(['anchor', 'portal']),position: vec3,rotationYDeg: finite,- tags: z.array(z.string().min(1).max(128)).max(64),+ compatibilityTags: z.array(z.string().min(1).max(128)).min(1).max(64),+ capacity: z.number().int().min(1).max(32),+ clearanceRadius: finite.positive().optional(),})- .strict();+ .strict()+ .superRefine((socket, ctx) => {+ if (socket.kind === 'portal' && socket.clearanceRadius == null) {+ ctx.addIssue({+ code: 'custom',+ path: ['clearanceRadius'],+ message: 'portal sockets require positive clearanceRadius',+ });+ }+ for (const duplicate of duplicateValues(socket.compatibilityTags)) {+ ctx.addIssue({+ code: 'custom',+ path: ['compatibilityTags'],+ message: `duplicate compatibility tag "${duplicate}"`,+ });+ }+ });const terrainSchema = z.discriminatedUnion('kind', [z.object({ kind: z.literal('flat'), height: finite }).strict(),@@ -232,7 +289,7 @@ const v1ProvenanceSchema = zconst v1StatementCommon = {stmtId: nonEmptyId,alias: nonEmptyId,- generationId: nonEmptyId,+ generationId: generationIdSchema,role: roleSchema,scale: finite.positive(),group: nonEmptyId.optional(),@@ -288,7 +345,7 @@ export const SceneModelV1Schema = z.array(z.object({- generationId: nonEmptyId,+ generationId: generationIdSchema,bbox: boundsSchema,name: z.string().min(1).max(256).optional(),tags: z.array(z.string().min(1).max(128)).max(128).optional(),@@ -410,6 +467,7 @@ export const WorldDocumentV2Schema = zconst assetRefs = new Set(world.assets.map((asset) => asset.refId));const collisionRefs = new Set(world.collisionArtifacts.map((artifact) => artifact.refId));+ const socketRefs = new Set(world.authored.sockets.map((socket) => socket.id));const referencedAssets = new Set<string>();const referencedCollisions = new Set<string>();for (let index = 0; index < world.objects.length; index++) {@@ -422,6 +480,13 @@ export const WorldDocumentV2Schema = zmessage: `unknown asset ref "${object.assetRefId}"`,});}+ if (object.socketId && !socketRefs.has(object.socketId)) {+ ctx.addIssue({+ code: 'custom',+ path: ['objects', index, 'socketId'],+ message: `unknown socket ref "${object.socketId}"`,+ });+ }if (object.collision?.policy === 'artifact' &&!collisionRefs.has(object.collision.artifactRefId)@@ -461,6 +526,21 @@ export const WorldDocumentV2Schema = zexport type WorldDocumentV2 = z.infer<typeof WorldDocumentV2Schema>;export type WorldAssetRefV2 = WorldDocumentV2['assets'][number];export type WorldObjectV2 = WorldDocumentV2['objects'][number];+export type WorldZoneV2 = WorldDocumentV2['authored']['zones'][number];+export type WorldPathV2 = WorldDocumentV2['authored']['paths'][number];+export type WorldSocketV2 = WorldDocumentV2['authored']['sockets'][number];+export type WorldSpawnV2 = WorldDocumentV2['spawns'][number];+export type WorldTerrainV2 = WorldDocumentV2['terrain'];++export interface WorldDocumentV2ArtifactReference {+ kind: 'asset' | 'collision' | 'heightfield';+ refId: string;+ /** Canonical package-relative URI. Asset URIs are Engine-derived. */+ uri: string;+ packagePath: string;+ /** Plain lowercase 64-hex SHA-256. */+ sha256: string;+}/** Parse and clone current v1 persistence before it reaches PlacementModel.fromJSON. */export function parseSceneModelV1JSON(input: unknown): SceneModelJSON {@@ -477,6 +557,56 @@ export function safeParseWorldDocumentV2(input: unknown) {return WorldDocumentV2Schema.safeParse(input);}+/**+ * Enumerate the complete portable artifact closure in deterministic order.+ * Asset GLB paths are derived from their stable ref ids; terrain/collider paths+ * are the validated package-relative URIs stored in the document.+ */+export function worldDocumentV2ArtifactReferences(+ input: unknown,+): WorldDocumentV2ArtifactReference[] {+ const world = parseWorldDocumentV2(input);+ const references: WorldDocumentV2ArtifactReference[] = world.assets.map((asset) => {+ const packagePath = `models/${asset.generationId}.glb`;+ return {+ kind: 'asset',+ refId: asset.refId,+ uri: packagePath,+ packagePath,+ sha256: asset.artifactSha256,+ };+ });+ if (world.terrain.kind === 'heightfield') {+ references.push({+ kind: 'heightfield',+ refId: 'terrain',+ uri: world.terrain.artifact.uri,+ packagePath: world.terrain.artifact.uri,+ sha256: world.terrain.artifact.sha256,+ });+ }+ for (const collision of world.collisionArtifacts) {+ references.push({+ kind: 'collision',+ refId: collision.refId,+ uri: collision.artifact.uri,+ packagePath: collision.artifact.uri,+ sha256: collision.artifact.sha256,+ });+ }+ return references.sort((a, b) =>+ a.kind === b.kind+ ? a.refId < b.refId+ ? -1+ : a.refId > b.refId+ ? 1+ : 0+ : a.kind < b.kind+ ? -1+ : 1,+ );+}+function canonicalJson(value: unknown): string {if (value === null || typeof value === 'boolean' || typeof value === 'string') {return JSON.stringify(value);@@ -513,7 +643,7 @@ const reconciliationSchema = zz.object({id: nonEmptyId,- generationId: nonEmptyId,+ generationId: generationIdSchema,position: vec3,rotationYDeg: finite,uniformScale: finite.positive(),@@ -525,7 +655,7 @@ const reconciliationSchema = z.array(z.object({- generationId: nonEmptyId,+ generationId: generationIdSchema,artifactSha256: sha256,bounds: boundsSchema,name: z.string().min(1).max(256).optional(),@@ -571,9 +701,11 @@ 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.+ * Retained object ids preserve role/group/edit history and untouched world+ * fields. Same-asset edits preserve collision/socket bindings. An asset content+ * swap resets asset-bound collision to bounds, clears socket attachment, and+ * records the active asset transition. Removed references are pruned and output+ * arrays are sorted so caller ordering cannot change the document hash.*/export function reconcileWorldDocumentV2Objects(current: unknown,@@ -583,6 +715,7 @@ export function reconcileWorldDocumentV2Objects(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 existingAssetsByRef = new Map(world.assets.map((asset) => [asset.refId, 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);@@ -602,7 +735,44 @@ export function reconcileWorldDocumentV2Objects(...(suppliedAsset ?? existingAsset!),});resolvedAssets.set(asset.refId, asset);- return {+ const previousAsset = previous ? existingAssetsByRef.get(previous.assetRefId) : undefined;+ const previousActive =+ previous?.provenance.activeAsset ??+ (previousAsset+ ? {+ generationId: previousAsset.generationId,+ artifactSha256: previousAsset.artifactSha256,+ }+ : undefined);+ const assetChanged =+ previousActive != null &&+ (previousActive.generationId !== asset.generationId ||+ previousActive.artifactSha256 !== asset.artifactSha256);+ const assetHistory = [+ ...(previous?.provenance.assetHistory ?? []),+ ...(assetChanged+ ? [+ {+ kind: 'asset-swap' as const,+ fromGenerationId: previousActive.generationId,+ toGenerationId: asset.generationId,+ fromArtifactSha256: previousActive.artifactSha256,+ toArtifactSha256: asset.artifactSha256,+ },+ ]+ : []),+ ];+ const provenance = {+ ...(previous?.provenance ?? {+ sourceStatementId: `manual:${object.id}`.slice(0, 256),+ }),+ activeAsset: {+ generationId: asset.generationId,+ artifactSha256: asset.artifactSha256,+ },+ ...(assetHistory.length ? { assetHistory } : {}),+ };+ const reconciled: WorldObjectV2 = {id: object.id,assetRefId: asset.refId,transform: {@@ -611,12 +781,16 @@ export function reconcileWorldDocumentV2Objects(uniformScale: object.uniformScale,},role: previous?.role ?? placementRoleForAsset(asset.role) ?? 'support',- provenance: previous?.provenance ?? {- sourceStatementId: `manual:${object.id}`.slice(0, 256),- },+ provenance,...(previous?.groupId ? { groupId: previous.groupId } : {}),- ...(previous?.collision ? { collision: previous.collision } : {}),+ ...(!assetChanged && previous?.socketId ? { socketId: previous.socketId } : {}),+ ...(assetChanged+ ? { collision: { policy: 'bounds' as const } }+ : previous?.collision+ ? { collision: previous.collision }+ : {}),};+ return reconciled;});const referencedCollisions = new Set(@@ -721,6 +895,10 @@ export function migrateSceneModelV1ToWorldDocumentV2(sourceStatementId: placement.stmtId,...(sourcePrompt ? { sourcePrompt } : {}),...(parentGenerationId ? { parentGenerationId } : {}),+ activeAsset: {+ generationId: placement.generationId,+ artifactSha256: options.artifactSha256ByGenerationId[placement.generationId]!,+ },},};});diff --git a/src/composer/world-integration.test.ts b/src/composer/world-integration.test.tsnew file mode 100644index 00000000..a654e064--- /dev/null+++ b/src/composer/world-integration.test.ts@@ -0,0 +1,397 @@+import { describe, expect, test } from 'bun:test';+import type { SceneModelJSON } from './model';+import {+ hashWorldDocumentV2,+ migrateSceneModelV1ToWorldDocumentV2,+ parseWorldDocumentV2,+ reconcileWorldDocumentV2Objects,+ worldDocumentV2ArtifactReferences,+ type WorldPathV2,+} from './world-document';+import {+ setWorldPathsV2,+ setWorldSocketsV2,+ setWorldSpawnsV2,+ setWorldTerrainV2,+ setWorldZonesV2,+ alignWorldObjectsToPathV2,+ fillWorldPathV2,+ reconcileWorldDocumentV2Candidate,+ sampleWorldPathV2,+ snapWorldObjectToSocketV2,+ validateWorldIntegrationV2,+} from './world-integration';++const SHA_A = 'a'.repeat(64);+const SHA_B = 'b'.repeat(64);++function world() {+ const model: SceneModelJSON = {+ name: 'World',+ seed: 4,+ catalog: [+ {+ generationId: 'crate',+ bbox: { min: [-1, 0, -1], max: [1, 2, 1] },+ tags: ['cargo'],+ },+ {+ generationId: 'door',+ bbox: { min: [-0.5, 0, -0.25], max: [0.5, 2, 0.25] },+ tags: ['portal'],+ },+ ],+ statements: [+ {+ kind: 'place',+ stmtId: 's1',+ alias: 'crate-1',+ generationId: 'crate',+ role: 'support',+ scale: 1,+ at: [10, 10],+ face: 0,+ exact: { pos: [10, 0, 10], rotYDeg: 0 },+ },+ ],+ };+ return migrateSceneModelV1ToWorldDocumentV2(model, {+ worldId: 'world',+ artifactSha256ByGenerationId: { crate: SHA_A },+ });+}++describe('WorldDocumentV2 integration primitives', () => {+ test('authors deterministic full replacements and rejects non-positive rect half extents', async () => {+ let doc = world();+ doc = setWorldZonesV2(doc, [+ { id: 'z2', kind: 'reserved', shape: { type: 'circle', center: [20, 20], radius: 2 } },+ {+ id: 'z1',+ kind: 'reserved',+ shape: { type: 'rect', center: [30, 30], halfExtents: [2, 3] },+ },+ ]);+ doc = setWorldPathsV2(doc, [+ {+ id: 'p',+ points: [+ [0, 0, 0],+ [2, 0, 2],+ ],+ halfWidth: 1,+ },+ ]);+ doc = setWorldSocketsV2(doc, [+ {+ id: 'socket',+ kind: 'anchor',+ position: [5, 0, 5],+ rotationYDeg: 90,+ compatibilityTags: ['cargo'],+ capacity: 1,+ },+ ]);+ doc = setWorldSpawnsV2(doc, [+ { id: 'spawn', position: [-20, 0, -20], rotationYDeg: 0, clearanceRadius: 2 },+ ]);+ doc = setWorldTerrainV2(doc, { kind: 'flat', height: 3 });+ expect(doc.authored.zones.map(({ id }) => id)).toEqual(['z1', 'z2']);+ expect(doc.authored.paths).toHaveLength(1);+ expect(doc.authored.sockets).toHaveLength(1);+ expect(doc.spawns).toHaveLength(1);+ expect(doc.terrain).toEqual({ kind: 'flat', height: 3 });+ expect(await hashWorldDocumentV2(setWorldZonesV2(doc, [...doc.authored.zones].reverse()))).toBe(+ await hashWorldDocumentV2(doc),+ );+ expect(() =>+ setWorldZonesV2(doc, [+ {+ id: 'bad',+ kind: 'reserved',+ shape: { type: 'rect', center: [0, 0], halfExtents: [0, 1] },+ },+ ]),+ ).toThrow();+ });++ test('snaps compatible objects and validates occupancy, portal, reserved, and spawn clearance', () => {+ let doc = setWorldSocketsV2(world(), [+ {+ id: 'cargo-slot',+ kind: 'anchor',+ position: [0, 0, 0],+ rotationYDeg: 45,+ compatibilityTags: ['cargo'],+ capacity: 1,+ },+ ]);+ doc = snapWorldObjectToSocketV2(doc, { objectId: 'crate-1', socketId: 'cargo-slot' });+ expect(doc.objects[0]).toMatchObject({+ id: 'crate-1',+ socketId: 'cargo-slot',+ transform: { position: [0, 0, 0], rotationYDeg: 45 },+ });+ expect(validateWorldIntegrationV2(doc)).toEqual([]);++ expect(() =>+ setWorldZonesV2(doc, [+ {+ id: 'reserved',+ kind: 'reserved',+ shape: { type: 'circle', center: [0, 0], radius: 3 },+ },+ ]),+ ).toThrow('reserved zone');++ expect(() =>+ setWorldSocketsV2(world(), [+ {+ id: 'portal',+ kind: 'portal',+ position: [10, 0, 10],+ rotationYDeg: 0,+ compatibilityTags: ['portal'],+ capacity: 1,+ clearanceRadius: 3,+ },+ ]),+ ).toThrow('blocks portal');+ expect(() =>+ setWorldSpawnsV2(world(), [+ { id: 'spawn', position: [10, 0, 10], rotationYDeg: 0, clearanceRadius: 3 },+ ]),+ ).toThrow('blocks spawn');+ expect(() =>+ setWorldZonesV2(world(), [+ {+ id: 'portal-zone',+ kind: 'portal-clearance',+ shape: { type: 'circle', center: [10, 10], radius: 3 },+ },+ ]),+ ).toThrow('portal-clearance zone');+ expect(() =>+ setWorldZonesV2(world(), [+ {+ id: 'spawn-zone',+ kind: 'spawn-clearance',+ shape: { type: 'rect', center: [10, 10], halfExtents: [3, 3] },+ },+ ]),+ ).toThrow('spawn-clearance zone');+ });++ test('samples, aligns, and fills paths with deterministic tangent facing', () => {+ const path: WorldPathV2 = {+ id: 'route',+ points: [+ [0, 0, 0],+ [10, 0, 0],+ [10, 0, 10],+ ],+ halfWidth: 1,+ };+ const samples = sampleWorldPathV2(path, { spacing: 5 });+ expect(samples.map(({ position, rotationYDeg }) => ({ position, rotationYDeg }))).toEqual([+ { position: [0, 0, 0], rotationYDeg: -0 },+ { position: [5, 0, 0], rotationYDeg: -0 },+ { position: [10, 0, 0], rotationYDeg: -90 },+ { position: [10, 0, 5], rotationYDeg: -90 },+ { position: [10, 0, 10], rotationYDeg: -90 },+ ]);+ let doc = setWorldPathsV2(world(), [path]);+ doc = alignWorldObjectsToPathV2(doc, {+ pathId: 'route',+ objectIds: ['crate-1'],+ spacing: 5,+ startDistance: 5,+ });+ expect(doc.objects[0]!.transform).toMatchObject({ position: [5, 0, 0], rotationYDeg: -0 });+ const filled = fillWorldPathV2(doc, {+ pathId: 'route',+ templateObjectId: 'crate-1',+ idPrefix: 'route-crate',+ count: 2,+ spacing: 5,+ startDistance: 10,+ });+ expect(+ filled.objects+ .filter(({ id }) => id.startsWith('route-crate'))+ .map(({ id, transform }) => ({ id, transform })),+ ).toEqual([+ {+ id: 'route-crate#0',+ transform: { position: [10, 0, 0], rotationYDeg: -90, uniformScale: 1 },+ },+ {+ id: 'route-crate#1',+ transform: { position: [10, 0, 5], rotationYDeg: -90, uniformScale: 1 },+ },+ ]);+ expect(+ fillWorldPathV2(doc, {+ pathId: 'route',+ templateObjectId: 'crate-1',+ idPrefix: 'route-crate',+ count: 2,+ spacing: 5,+ startDistance: 10,+ }),+ ).toEqual(filled);+ });++ test('locks asset swaps while preserving world state and stable edit history', async () => {+ let doc = setWorldSocketsV2(world(), [+ {+ id: 'slot',+ kind: 'anchor',+ position: [0, 0, 0],+ rotationYDeg: 0,+ compatibilityTags: ['cargo'],+ capacity: 1,+ },+ ]);+ doc = snapWorldObjectToSocketV2(doc, { objectId: 'crate-1', socketId: 'slot' });+ doc.objects[0]!.collision = { policy: 'bounds' };+ const beforeAuthored = structuredClone(doc.authored);+ const swapped = reconcileWorldDocumentV2Objects(doc, {+ objects: [+ {+ id: 'crate-1',+ generationId: 'door',+ position: [2, 0, 3],+ rotationYDeg: 10,+ uniformScale: 1,+ },+ ],+ assets: [+ {+ generationId: 'door',+ artifactSha256: SHA_B,+ bounds: { min: [-0.5, 0, -0.25], max: [0.5, 2, 0.25] },+ tags: ['portal'],+ },+ ],+ });+ expect(swapped.authored).toEqual(beforeAuthored);+ expect(swapped.objects[0]!.id).toBe('crate-1');+ expect(swapped.objects[0]!.socketId).toBeUndefined();+ expect(swapped.objects[0]!.collision).toEqual({ policy: 'bounds' });+ expect(swapped.objects[0]!.provenance.activeAsset).toEqual({+ generationId: 'door',+ artifactSha256: SHA_B,+ });+ expect(swapped.objects[0]!.provenance.assetHistory).toHaveLength(1);+ expect(await hashWorldDocumentV2(swapped)).not.toBe(await hashWorldDocumentV2(doc));+ });++ test('enumerates a deterministic portable artifact closure', () => {+ const doc = world();+ doc.terrain = {+ kind: 'heightfield',+ artifact: {+ uri: 'terrain/world.heightfield.json',+ sha256: SHA_B,+ mediaType: 'application/vnd.kiln.heightfield+json',+ },+ };+ doc.collisionArtifacts.push({+ refId: 'collision:crate',+ artifact: {+ uri: 'collision/crate.glb',+ sha256: 'c'.repeat(64),+ mediaType: 'model/gltf-binary',+ },+ });+ doc.objects[0]!.collision = { policy: 'artifact', artifactRefId: 'collision:crate' };+ const refs = worldDocumentV2ArtifactReferences(parseWorldDocumentV2(doc));+ expect(refs).toEqual([+ {+ kind: 'asset',+ refId: 'asset:crate',+ uri: 'models/crate.glb',+ packagePath: 'models/crate.glb',+ sha256: SHA_A,+ },+ {+ kind: 'collision',+ refId: 'collision:crate',+ uri: 'collision/crate.glb',+ packagePath: 'collision/crate.glb',+ sha256: 'c'.repeat(64),+ },+ {+ kind: 'heightfield',+ refId: 'terrain',+ uri: 'terrain/world.heightfield.json',+ packagePath: 'terrain/world.heightfield.json',+ sha256: SHA_B,+ },+ ]);+ });++ test('reconciles an agent candidate without dropping parent integration state', () => {+ let parent = setWorldSocketsV2(world(), [+ {+ id: 'slot',+ kind: 'anchor',+ position: [10, 0, 10],+ rotationYDeg: 0,+ compatibilityTags: ['cargo'],+ capacity: 1,+ },+ ]);+ parent = snapWorldObjectToSocketV2(parent, { objectId: 'crate-1', socketId: 'slot' });+ parent = setWorldZonesV2(parent, [+ {+ id: 'reserve',+ kind: 'reserved',+ shape: { type: 'circle', center: [100, 100], radius: 3 },+ },+ ]);+ parent = setWorldPathsV2(parent, [+ {+ id: 'road',+ points: [+ [0, 0, 0],+ [20, 0, 0],+ ],+ halfWidth: 2,+ },+ ]);+ parent = setWorldSpawnsV2(parent, [+ { id: 'spawn', position: [-20, 0, -20], rotationYDeg: 0, clearanceRadius: 2 },+ ]);+ parent.objects[0]!.collision = { policy: 'bounds' };++ const candidate = structuredClone(parent);+ candidate.authored = { zones: [], paths: [], sockets: [] };+ candidate.spawns = [];+ candidate.objects[0]!.transform.position = [20, 0, 20];+ delete candidate.objects[0]!.socketId;+ candidate.objects.push({+ ...structuredClone(candidate.objects[0]!),+ id: 'agent-new',+ transform: { position: [30, 0, 30], rotationYDeg: 25, uniformScale: 1 },+ role: 'fill',+ provenance: {+ sourceStatementId: 'agent:s9',+ activeAsset: { generationId: 'crate', artifactSha256: SHA_A },+ },+ });+ const merged = reconcileWorldDocumentV2Candidate(parent, candidate);+ expect(merged.authored).toEqual(parent.authored);+ expect(merged.spawns).toEqual(parent.spawns);+ expect(merged.objects.find(({ id }) => id === 'crate-1')).toMatchObject({+ collision: { policy: 'bounds' },+ transform: { position: [20, 0, 20] },+ });+ expect(merged.objects.find(({ id }) => id === 'crate-1')!.socketId).toBeUndefined();+ expect(merged.objects.find(({ id }) => id === 'agent-new')).toMatchObject({+ role: 'fill',+ provenance: { sourceStatementId: 'agent:s9' },+ });+ });+});diff --git a/src/composer/world-integration.ts b/src/composer/world-integration.tsnew file mode 100644index 00000000..6aebb351--- /dev/null+++ b/src/composer/world-integration.ts@@ -0,0 +1,579 @@+/** Pure deterministic authoring and validation operations for Composer V2 world primitives. */+import { worldAabbFromLocal } from './overlap';+import {+ parseWorldDocumentV2,+ reconcileWorldDocumentV2Objects,+ type WorldDocumentV2,+ type WorldObjectV2,+ type WorldPathV2,+ type WorldSocketV2,+ type WorldSpawnV2,+ type WorldTerrainV2,+ type WorldZoneV2,+} from './world-document';++export type WorldIntegrationIssueCode =+ | 'socket-incompatible'+ | 'socket-over-capacity'+ | 'socket-transform-mismatch'+ | 'reserved-zone-occupied'+ | 'portal-clearance-blocked'+ | 'spawn-clearance-blocked';++export interface WorldIntegrationIssueV2 {+ code: WorldIntegrationIssueCode;+ message: string;+ objectId?: string;+ socketId?: string;+ zoneId?: string;+ spawnId?: string;+}++const compareId = (a: { id: string }, b: { id: string }): number =>+ a.id < b.id ? -1 : a.id > b.id ? 1 : 0;++function replaceAuthored(+ input: unknown,+ authored: Partial<WorldDocumentV2['authored']>,+): WorldDocumentV2 {+ const world = parseWorldDocumentV2(input);+ return parseWorldDocumentV2({ ...world, authored: { ...world.authored, ...authored } });+}++/** Full deterministic replacement; input ordering cannot alter the world hash. */+export function setWorldZonesV2(input: unknown, zones: readonly WorldZoneV2[]): WorldDocumentV2 {+ return assertWorldIntegrationValid(replaceAuthored(input, { zones: [...zones].sort(compareId) }));+}++/** Full deterministic replacement; input ordering cannot alter the world hash. */+export function setWorldPathsV2(input: unknown, paths: readonly WorldPathV2[]): WorldDocumentV2 {+ return replaceAuthored(input, { paths: [...paths].sort(compareId) });+}++/**+ * Full deterministic replacement. Attachments to removed sockets are cleared,+ * making socket occupancy a derived property with no dangling persisted state.+ */+export function setWorldSocketsV2(+ input: unknown,+ sockets: readonly WorldSocketV2[],+): WorldDocumentV2 {+ const world = parseWorldDocumentV2(input);+ const sorted = [...sockets].sort(compareId);+ const ids = new Set(sorted.map((socket) => socket.id));+ const objects = world.objects.map((object) => {+ if (!object.socketId || ids.has(object.socketId)) return object;+ const { socketId: _removed, ...detached } = object;+ return detached;+ });+ return assertWorldIntegrationValid(+ parseWorldDocumentV2({+ ...world,+ objects,+ authored: { ...world.authored, sockets: sorted },+ }),+ );+}++/** Full deterministic replacement; input ordering cannot alter the world hash. */+export function setWorldSpawnsV2(input: unknown, spawns: readonly WorldSpawnV2[]): WorldDocumentV2 {+ const world = parseWorldDocumentV2(input);+ return assertWorldIntegrationValid(+ parseWorldDocumentV2({ ...world, spawns: [...spawns].sort(compareId) }),+ );+}++/** Replace terrain without changing any other canonical world state. */+export function setWorldTerrainV2(input: unknown, terrain: WorldTerrainV2): WorldDocumentV2 {+ const world = parseWorldDocumentV2(input);+ return parseWorldDocumentV2({ ...world, terrain });+}++interface Footprint {+ object: WorldObjectV2;+ minX: number;+ maxX: number;+ minZ: number;+ maxZ: number;+}++function footprints(world: WorldDocumentV2): Footprint[] {+ const assets = new Map(world.assets.map((asset) => [asset.refId, asset]));+ return world.objects.map((object) => {+ const asset = assets.get(object.assetRefId)!;+ const box = worldAabbFromLocal(+ asset.bounds.min,+ asset.bounds.max,+ object.transform.position,+ object.transform.rotationYDeg,+ object.transform.uniformScale,+ );+ return {+ object,+ minX: box.min[0],+ maxX: box.max[0],+ minZ: box.min[2],+ maxZ: box.max[2],+ };+ });+}++function boxIntersectsCircle(box: Footprint, center: [number, number], radius: number): boolean {+ const x = Math.max(box.minX, Math.min(box.maxX, center[0]));+ const z = Math.max(box.minZ, Math.min(box.maxZ, center[1]));+ return (x - center[0]) ** 2 + (z - center[1]) ** 2 <= radius * radius;+}++function boxIntersectsZone(box: Footprint, zone: WorldZoneV2): boolean {+ if (zone.shape.type === 'circle') {+ return boxIntersectsCircle(box, zone.shape.center, zone.shape.radius);+ }+ return !(+ box.maxX < zone.shape.center[0] - zone.shape.halfExtents[0] ||+ box.minX > zone.shape.center[0] + zone.shape.halfExtents[0] ||+ box.maxZ < zone.shape.center[1] - zone.shape.halfExtents[1] ||+ box.minZ > zone.shape.center[1] + zone.shape.halfExtents[1]+ );+}++/** Validate compatibility/occupancy and reserved, portal, and spawn clearance. */+export function validateWorldIntegrationV2(input: unknown): WorldIntegrationIssueV2[] {+ const world = parseWorldDocumentV2(input);+ const issues: WorldIntegrationIssueV2[] = [];+ const assets = new Map(world.assets.map((asset) => [asset.refId, asset]));+ const sockets = new Map(world.authored.sockets.map((socket) => [socket.id, socket]));+ const occupancy = new Map<string, WorldObjectV2[]>();+ for (const object of world.objects) {+ if (!object.socketId) continue;+ const socket = sockets.get(object.socketId)!;+ const asset = assets.get(object.assetRefId)!;+ const compatible = (asset.tags ?? []).some((tag) => socket.compatibilityTags.includes(tag));+ if (!compatible) {+ issues.push({+ code: 'socket-incompatible',+ message: `object "${object.id}" is incompatible with socket "${socket.id}"`,+ objectId: object.id,+ socketId: socket.id,+ });+ }+ if (+ object.transform.position.some((value, index) => value !== socket.position[index]) ||+ object.transform.rotationYDeg !== socket.rotationYDeg+ ) {+ issues.push({+ code: 'socket-transform-mismatch',+ message: `object "${object.id}" is not aligned to socket "${socket.id}"`,+ objectId: object.id,+ socketId: socket.id,+ });+ }+ const occupants = occupancy.get(socket.id) ?? [];+ occupants.push(object);+ occupancy.set(socket.id, occupants);+ }+ for (const socket of world.authored.sockets) {+ const occupants = occupancy.get(socket.id) ?? [];+ if (occupants.length > socket.capacity) {+ issues.push({+ code: 'socket-over-capacity',+ message: `socket "${socket.id}" has ${occupants.length} occupants but capacity ${socket.capacity}`,+ socketId: socket.id,+ });+ }+ }++ const boxes = footprints(world);+ for (const zone of world.authored.zones) {+ for (const box of boxes) {+ if (boxIntersectsZone(box, zone)) {+ const code =+ zone.kind === 'reserved'+ ? 'reserved-zone-occupied'+ : zone.kind === 'portal-clearance'+ ? 'portal-clearance-blocked'+ : 'spawn-clearance-blocked';+ issues.push({+ code,+ message: `object "${box.object.id}" occupies ${zone.kind} zone "${zone.id}"`,+ objectId: box.object.id,+ zoneId: zone.id,+ });+ }+ }+ }+ for (const socket of world.authored.sockets) {+ if (socket.kind !== 'portal') continue;+ for (const box of boxes) {+ if (box.object.socketId === socket.id) continue;+ if (+ boxIntersectsCircle(box, [socket.position[0], socket.position[2]], socket.clearanceRadius!)+ ) {+ issues.push({+ code: 'portal-clearance-blocked',+ message: `object "${box.object.id}" blocks portal "${socket.id}"`,+ objectId: box.object.id,+ socketId: socket.id,+ });+ }+ }+ }+ for (const spawn of world.spawns) {+ for (const box of boxes) {+ if (boxIntersectsCircle(box, [spawn.position[0], spawn.position[2]], spawn.clearanceRadius)) {+ issues.push({+ code: 'spawn-clearance-blocked',+ message: `object "${box.object.id}" blocks spawn "${spawn.id}"`,+ objectId: box.object.id,+ spawnId: spawn.id,+ });+ }+ }+ }+ return issues.sort((a, b) => {+ const left = `${a.code}:${a.objectId ?? ''}:${a.socketId ?? ''}:${a.zoneId ?? ''}:${a.spawnId ?? ''}`;+ const right = `${b.code}:${b.objectId ?? ''}:${b.socketId ?? ''}:${b.zoneId ?? ''}:${b.spawnId ?? ''}`;+ return left < right ? -1 : left > right ? 1 : 0;+ });+}++export interface SnapWorldObjectToSocketV2Input {+ objectId: string;+ socketId: string;+}++/** Raised when a candidate would persist blocked reserved/portal/spawn space. */+export class WorldIntegrationValidationError extends Error {+ readonly issues: WorldIntegrationIssueV2[];++ constructor(issues: WorldIntegrationIssueV2[]) {+ super(+ `world integration validation failed: ${issues.map((issue) => issue.message).join('; ')}`,+ );+ this.name = 'WorldIntegrationValidationError';+ this.issues = issues;+ }+}++function assertWorldIntegrationValid(world: WorldDocumentV2): WorldDocumentV2 {+ const issues = validateWorldIntegrationV2(world);+ if (issues.length) throw new WorldIntegrationValidationError(issues);+ return world;+}++function clearInvalidSocketAttachments(world: WorldDocumentV2): WorldDocumentV2 {+ const sockets = new Map(world.authored.sockets.map((socket) => [socket.id, socket]));+ const assets = new Map(world.assets.map((asset) => [asset.refId, asset]));+ const occupancy = new Map<string, number>();+ const objects = [...world.objects].sort(compareId).map((object) => {+ if (!object.socketId) return object;+ const socket = sockets.get(object.socketId);+ const asset = assets.get(object.assetRefId)!;+ const compatible =+ socket != null && (asset.tags ?? []).some((tag) => socket.compatibilityTags.includes(tag));+ const aligned =+ socket != null &&+ object.transform.position.every((value, index) => value === socket.position[index]) &&+ object.transform.rotationYDeg === socket.rotationYDeg;+ const used = socket ? (occupancy.get(socket.id) ?? 0) : 0;+ if (!socket || !compatible || !aligned || used >= socket.capacity) {+ const { socketId: _removed, ...detached } = object;+ return detached;+ }+ occupancy.set(socket.id, used + 1);+ return object;+ });+ return parseWorldDocumentV2({ ...world, objects });+}++/**+ * Merge a freshly-authored/migrated agent candidate into its canonical parent.+ * Parent terrain, authored primitives, spawns, runtime policy, and world+ * provenance remain authoritative. Retained ids use locked reconciliation+ * semantics; new ids adopt candidate role/group/provenance. Invalid/dangling+ * socket occupancy is detached deterministically before final clearance checks.+ */+export function reconcileWorldDocumentV2Candidate(+ current: unknown,+ candidateInput: unknown,+): WorldDocumentV2 {+ const parent = parseWorldDocumentV2(current);+ const candidate = parseWorldDocumentV2(candidateInput);+ const parentIds = new Set(parent.objects.map((object) => object.id));+ const candidateAssets = new Map(candidate.assets.map((asset) => [asset.refId, asset]));+ let merged = reconcileWorldDocumentV2Objects(parent, {+ objects: candidate.objects.map((object) => {+ const asset = candidateAssets.get(object.assetRefId)!;+ return {+ id: object.id,+ generationId: asset.generationId,+ position: object.transform.position,+ rotationYDeg: object.transform.rotationYDeg,+ uniformScale: object.transform.uniformScale,+ };+ }),+ assets: candidate.assets.map(({ refId: _refId, ...asset }) => asset),+ environment: candidate.environment,+ });+ const candidateObjects = new Map(candidate.objects.map((object) => [object.id, object]));+ merged = parseWorldDocumentV2({+ ...merged,+ objects: merged.objects.map((object) => {+ if (parentIds.has(object.id)) return object;+ const authored = candidateObjects.get(object.id)!;+ return {+ ...object,+ role: authored.role,+ provenance: authored.provenance,+ ...(authored.groupId ? { groupId: authored.groupId } : {}),+ ...(authored.collision ? { collision: authored.collision } : {}),+ };+ }),+ });+ merged = clearInvalidSocketAttachments(merged);+ const issues = validateWorldIntegrationV2(merged);+ if (issues.length) throw new WorldIntegrationValidationError(issues);+ return merged;+}++/** Snap one object exactly to a compatible socket, failing before any mutation. */+export function snapWorldObjectToSocketV2(+ input: unknown,+ request: SnapWorldObjectToSocketV2Input,+): WorldDocumentV2 {+ const world = parseWorldDocumentV2(input);+ const index = world.objects.findIndex((object) => object.id === request.objectId);+ if (index < 0) throw new Error(`unknown object "${request.objectId}"`);+ const socket = world.authored.sockets.find((candidate) => candidate.id === request.socketId);+ if (!socket) throw new Error(`unknown socket "${request.socketId}"`);+ const object = world.objects[index]!;+ const asset = world.assets.find((candidate) => candidate.refId === object.assetRefId)!;+ if (!(asset.tags ?? []).some((tag) => socket.compatibilityTags.includes(tag))) {+ throw new Error(`object "${object.id}" is incompatible with socket "${socket.id}"`);+ }+ const occupied = world.objects.filter(+ (candidate) => candidate.id !== object.id && candidate.socketId === socket.id,+ ).length;+ if (occupied >= socket.capacity) throw new Error(`socket "${socket.id}" is at capacity`);+ const objects = [...world.objects];+ objects[index] = {+ ...object,+ socketId: socket.id,+ transform: {+ ...object.transform,+ position: [...socket.position],+ rotationYDeg: socket.rotationYDeg,+ },+ };+ return assertWorldIntegrationValid(parseWorldDocumentV2({ ...world, objects }));+}++export interface SampleWorldPathV2Options {+ spacing: number;+ startDistance?: number;+ includeEnd?: boolean;+ maxSamples?: number;+}++export interface WorldPathSampleV2 {+ distance: number;+ position: [number, number, number];+ tangent: [number, number, number];+ rotationYDeg: number;+}++interface PathSegment {+ start: [number, number, number];+ end: [number, number, number];+ length: number;+ cumulative: number;+ tangent: [number, number, number];+}++function pathSegments(path: WorldPathV2): { segments: PathSegment[]; total: number } {+ const segments: PathSegment[] = [];+ let cumulative = 0;+ for (let index = 1; index < path.points.length; index++) {+ const start = path.points[index - 1]!;+ const end = path.points[index]!;+ const dx = end[0] - start[0];+ const dy = end[1] - start[1];+ const dz = end[2] - start[2];+ const length = Math.hypot(dx, dy, dz);+ if (length === 0) continue;+ segments.push({+ start,+ end,+ length,+ cumulative,+ tangent: [dx / length, dy / length, dz / length],+ });+ cumulative += length;+ }+ if (!segments.length) throw new Error(`path "${path.id}" has zero length`);+ return { segments, total: cumulative };+}++function sampleAtDistance(+ segments: PathSegment[],+ total: number,+ requested: number,+): WorldPathSampleV2 {+ const distance = Math.max(0, Math.min(total, requested));+ const segment = segments.find(+ (candidate, index) =>+ distance < candidate.cumulative + candidate.length || index === segments.length - 1,+ )!;+ const t = Math.max(0, Math.min(1, (distance - segment.cumulative) / segment.length));+ const position: [number, number, number] = [+ segment.start[0] + (segment.end[0] - segment.start[0]) * t,+ segment.start[1] + (segment.end[1] - segment.start[1]) * t,+ segment.start[2] + (segment.end[2] - segment.start[2]) * t,+ ];+ return {+ distance,+ position,+ tangent: [...segment.tangent],+ rotationYDeg: Math.atan2(-segment.tangent[2], segment.tangent[0]) * (180 / Math.PI),+ };+}++/** Sample a path at stable arc-length intervals; segment-boundary ties use the next segment. */+export function sampleWorldPathV2(+ path: WorldPathV2,+ options: SampleWorldPathV2Options,+): WorldPathSampleV2[] {+ if (!Number.isFinite(options.spacing) || options.spacing <= 0)+ throw new Error('path spacing must be positive');+ const start = options.startDistance ?? 0;+ if (!Number.isFinite(start) || start < 0)+ throw new Error('path startDistance must be non-negative');+ const maxSamples = options.maxSamples ?? 200;+ if (!Number.isInteger(maxSamples) || maxSamples < 1 || maxSamples > 200)+ throw new Error('maxSamples must be an integer from 1 to 200');+ const { segments, total } = pathSegments(path);+ if (start > total) return [];+ const distances: number[] = [];+ for (+ let distance = start;+ distance <= total && distances.length < maxSamples;+ distance = start + distances.length * options.spacing+ ) {+ distances.push(distance);+ }+ if ((options.includeEnd ?? true) && distances.length < maxSamples && distances.at(-1) !== total)+ distances.push(total);+ return distances.map((distance) => sampleAtDistance(segments, total, distance));+}++export interface AlignWorldObjectsToPathV2Input {+ pathId: string;+ objectIds: readonly string[];+ spacing: number;+ startDistance?: number;+}++/** Align existing objects in caller order to path arc length and tangent; socket bindings clear. */+export function alignWorldObjectsToPathV2(+ input: unknown,+ request: AlignWorldObjectsToPathV2Input,+): WorldDocumentV2 {+ const world = parseWorldDocumentV2(input);+ if (+ request.objectIds.length > 200 ||+ new Set(request.objectIds).size !== request.objectIds.length+ )+ throw new Error('objectIds must be unique and bounded to 200');+ const path = world.authored.paths.find((candidate) => candidate.id === request.pathId);+ if (!path) throw new Error(`unknown path "${request.pathId}"`);+ const samples = sampleWorldPathV2(path, {+ spacing: request.spacing,+ startDistance: request.startDistance,+ includeEnd: false,+ maxSamples: Math.max(1, request.objectIds.length),+ });+ if (samples.length < request.objectIds.length)+ throw new Error('path is too short for requested alignment');+ const byId = new Map(world.objects.map((object) => [object.id, object]));+ for (const id of request.objectIds) if (!byId.has(id)) throw new Error(`unknown object "${id}"`);+ const updates = new Map(request.objectIds.map((id, index) => [id, samples[index]!]));+ const objects = world.objects.map((object) => {+ const sample = updates.get(object.id);+ if (!sample) return object;+ const { socketId: _socketId, ...detached } = object;+ return {+ ...detached,+ transform: {+ ...object.transform,+ position: sample.position,+ rotationYDeg: sample.rotationYDeg,+ },+ };+ });+ return assertWorldIntegrationValid(parseWorldDocumentV2({ ...world, objects }));+}++export interface FillWorldPathV2Input {+ pathId: string;+ templateObjectId: string;+ idPrefix: string;+ count: number;+ spacing: number;+ startDistance?: number;+}++/** Deterministically repeat one canonical object along path arc length and tangent. */+export function fillWorldPathV2(input: unknown, request: FillWorldPathV2Input): WorldDocumentV2 {+ const world = parseWorldDocumentV2(input);+ if (!Number.isInteger(request.count) || request.count < 1 || request.count > 64)+ throw new Error('path fill count must be 1..64');+ if (world.objects.length + request.count > 200)+ throw new Error('path fill exceeds 200-object world limit');+ if (!request.idPrefix || request.idPrefix.length > 240)+ throw new Error('path fill idPrefix must be 1..240 characters');+ const template = world.objects.find((object) => object.id === request.templateObjectId);+ if (!template) throw new Error(`unknown template object "${request.templateObjectId}"`);+ const path = world.authored.paths.find((candidate) => candidate.id === request.pathId);+ if (!path) throw new Error(`unknown path "${request.pathId}"`);+ const samples = sampleWorldPathV2(path, {+ spacing: request.spacing,+ startDistance: request.startDistance,+ includeEnd: false,+ maxSamples: request.count,+ });+ if (samples.length < request.count) throw new Error('path is too short for requested fill');+ const existingIds = new Set(world.objects.map((object) => object.id));+ const additions = samples.slice(0, request.count).map((sample, index): WorldObjectV2 => {+ const id = `${request.idPrefix}#${index}`;+ if (existingIds.has(id)) throw new Error(`path fill object id already exists: "${id}"`);+ return {+ id,+ assetRefId: template.assetRefId,+ transform: {+ position: sample.position,+ rotationYDeg: sample.rotationYDeg,+ uniformScale: template.transform.uniformScale,+ },+ role: template.role,+ ...(template.groupId ? { groupId: template.groupId } : {}),+ ...(template.collision ? { collision: template.collision } : {}),+ provenance: {+ sourceStatementId: `path:${path.id}:${id}`.slice(0, 256),+ ...(template.provenance.sourcePrompt+ ? { sourcePrompt: template.provenance.sourcePrompt }+ : {}),+ ...(template.provenance.parentGenerationId+ ? { parentGenerationId: template.provenance.parentGenerationId }+ : {}),+ ...(template.provenance.activeAsset+ ? { activeAsset: template.provenance.activeAsset }+ : {}),+ },+ };+ });+ return assertWorldIntegrationValid(+ parseWorldDocumentV2({+ ...world,+ objects: [...world.objects, ...additions].sort(compareId),+ }),+ );+}