Skip to content

armgit / kiln

Public Imported from GitHub
0

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

Material fidelity, bounded procedural authoring, and runtime truth (#34)

Matthew Kissinger133a97b43368
diff --git a/AGENTS.md b/AGENTS.md
index 3f73fc32..efcf0156 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -27,8 +27,9 @@ slow render blocks the agent mid-thought — that deadline is its own per-call a
lower. Never collapse the two onto one value. Routing there is conditional on
`sceneNeedsPbrShading(root)`: bound texture or `metalness > 0`, never material type, because
`gameMaterial` and `pbrMaterial` both construct a `MeshStandardMaterial` and are indistinguishable
-after construction. Who drew a grid is reported through the context's `onViewsRendered` callback, not
-the tool result, so the cached tool definition stays byte-identical.
+after construction. Host telemetry still rides `onViewsRendered`, while every unified `kiln_render`
+result also carries model-visible `ViewFidelityV1`; a geometry-flat CPU image must never be treated as
+material evidence. Keep the input schema stable unless the active program explicitly versions it.
`src/views/renderer-id.ts` runs `readFileSync` at MODULE LOAD. Reach `CPU_RASTER_RENDERER_ID` through
the lazy `await import('../views')` that render paths already use; a static import puts a `node:fs`
diff --git a/README.md b/README.md
index 72444e12..51f7ded0 100644
--- a/README.md
+++ b/README.md
@@ -58,10 +58,11 @@ The engine ships TypeScript source (Bun/tsx transpile on the fly); consume by su
| `@kiln/engine/arena` | Bradley-Terry + adaptive pairwise sampling (pure math) |
| `@kiln/engine/validation` | structural validator + AST analysis (acorn) |
| `@kiln/engine/primitives` | the 70+ primitive/helper registry |
+| `@kiln/engine/material-resources`, `/texture-resolver` | trusted-host approved texture registry and bounded resolver injection; generated code sees only approved resource IDs |
| `@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`, strict reconciliation, sockets/zones/paths/spawns, deterministic terrain, layout/overlap/DSL) + bounded compose and post-compose integration loops (`runKilnComposer`, `runKilnWorldIntegration`) |
+| `@kiln/engine/composer`, `/composer/agent` | THREE-free scene-composition core (canonical `WorldDocumentV2`, strict reconciliation, sockets/zones/paths/spawns, deterministic terrain, collider/reachability contracts, presentation receipts, `WorldPackageV2`, 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,
@@ -72,6 +73,10 @@ locked asset-swap semantics. The bounded integration loop renders and finalizes
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.
+Collider artifacts, reachability reports, presentation documents, and `WorldPackageV2` are strict,
+canonical, hash-bound contracts. They preserve source compatibility by extending `WorldDocumentV2`
+additively; browser capture and runtime consumption must still verify the declared external artifact
+bytes rather than trusting paths or labels.
Heightfield artifact SHA-256 binds the exact bytes from
`encodeHeightfieldArtifactV1`; portable asset paths remain the additive package contract
`models/<generationId>.glb`.
diff --git a/package.json b/package.json
index 55862ab9..16ce34ab 100644
--- a/package.json
+++ b/package.json
@@ -16,6 +16,7 @@
"./agent": "./src/agent/index.ts",
"./arena": "./src/arena/index.ts",
"./render": "./src/render.ts",
+ "./evaluator": "./src/evaluator/index.ts",
"./kit": "./src/kit.ts",
"./palette": "./src/palette.ts",
"./views": "./src/views/index.ts",
@@ -27,6 +28,7 @@
"./vehicle": "./src/vehicle.ts",
"./material-recipes": "./src/material-recipes.ts",
"./material-resources": "./src/material-resources.ts",
+ "./texture-resolver": "./src/texture-resolver.ts",
"./material-recipe-runtime": "./src/material-recipe-runtime.ts",
"./material-recipe-prompt": "./src/material-recipe-prompt.ts",
"./material-metrics": "./src/material-metrics.ts",
diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
index ed647d12..80909f56 100644
--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap
+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
@@ -170,6 +170,12 @@ await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?,
// PBR.
// NOTE: Use only listed kiln.material.*.v1 IDs and approved kiln.texture.* resource IDs. Leaf
// is MASK, glass is BLEND, and host file paths are forbidden.
+await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', name?, baseColor?, roughness?, metalness?, emissive?, emissiveIntensity?, alphaMode?, alphaCutoff?, doubleSided?, textures?: { baseColor?, normal?, metallicRoughness?, emissive?, occlusion? } })
+ // Compiles the strict portable material contract. Texture refs are either typed procedural V2
+ // specs or closed approved kiln.texture.* IDs; paths, URLs, raw textures, callbacks, and
+ // shader source are rejected.
+ // NOTE: Use metallicRoughness as one packed G=roughness/B=metalness map. Every procedural ref
+ // usage must match its slot; resource refs must be approved for that exact slot.
basicMaterial(color, opts?: { transparent, opacity })
// Unlit flat material. For UI / effects where lighting is baked in.
glassMaterial(color, opts?: { opacity, roughness, metalness })
@@ -312,22 +318,22 @@ panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)
// v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample
// only the clean strip.
-// Textures (loadTexture is async)
-await loadTexture(source, { usage?: 'albedo'|'emissive'|'normal'|'roughness'|'metalness'|'metallicRoughness'|'occlusion', name? })
- // Loads a PNG/JPG/WebP image with explicit slot usage. Albedo/emissive preview as sRGB;
- // normal/roughness/metalness/occlusion are linear data. Stashes encoded bytes and QA metadata
- // for lossless GLB export.
- // NOTE: NEVER texture.clone() a loaded texture (clone() corrupts the encoded bytes and breaks
- // GLB export). Share the same Texture object and remap UVs with panelRemapV on the smaller
- // mesh instead.
-proceduralTexture({ size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })
+// Textures (approved resource loading is async)
+await loadApprovedTexture(resourceId)
+ // Loads one approved kiln.texture.* resource ID through the host-injected closed resolver.
+ // The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte
+ // arrays, resolver objects, hashes, and options are rejected.
+ // NOTE: Use only a concrete resource ID listed in material capabilities; never invent one.
+ // Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for
+ // authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes
+ // and breaks GLB export).
+proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })
// Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite
// bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes
// and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.
- // NOTE: Sync — no await. Prefer this over loadTexture for any surface you can describe (wood,
- // rust, brick, fabric, dirt): it needs no asset files and cannot fail at load. Max 8 layers,
- // size must be a power of two up to 1024. Only the six listed ops exist; there is no custom
- // per-pixel callback.
+ // NOTE: Sync — no await. Strict V2 JSON boundary: unknown/prototype keys, callbacks, paths,
+ // URLs, and shader source are rejected. Prefer this over approved resources for describable
+ // surfaces. Max 8 layers, power-of-two size up to 1024. Only the six listed ops exist.
normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })
// Derives a tangent-space normal map from the source texture's brightness, treating it as
// height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at
@@ -559,15 +565,15 @@ decalBox(width: number, height: number, depth?: 0.01)
foliageCardGeo(opts?: { width?, height?, yPivot?: 0..1 })
// Single-quad foliage card with a configurable Y pivot. yPivot=0 plants the quad on the
// ground. Pair with an alpha-tested material and a leaf/plant sprite.
- // e.g. const leaves = await loadTexture('./fern.png', { usage: 'albedo' }); const quad =
- // foliageCardGeo({ width: 4, height: 6, yPivot: 0 }); createPart('Mesh_Fern', quad,
- // foliageMaterial(leaves), { parent: root });
+ // e.g. const leaves = await materialRecipe('kiln.material.leaf.v1'); const quad =
+ // foliageCardGeo({ width: 4, height: 6, yPivot: 0 }); createPart('Mesh_Fern', quad, leaves, {
+ // parent: root });
crossedQuadsGeo(opts?: { width?, height?, planes?: 2 | 3, yPivot? })
// Cross-billboard bush primitive: 2 or 3 planes intersecting along the Y axis. Reads as a
// dense plant from any angle, cheaper than real geometry.
- // e.g. const leaves = await loadTexture('./bush.png', { usage: 'albedo' }); const bush =
- // crossedQuadsGeo({ width: 2, height: 2, planes: 3 }); createPart('Mesh_Bush', bush,
- // foliageMaterial(leaves), { parent: root });
+ // e.g. const leaves = await materialRecipe('kiln.material.leaf.v1'); const bush =
+ // crossedQuadsGeo({ width: 2, height: 2, planes: 3 }); createPart('Mesh_Bush', bush, leaves,
+ // { parent: root });
octaGridPlane({ tilesX, tilesY, width?, height?, yPivot? })
// Atlas-ready billboard quad. UVs are pre-scaled to cover one tile of a tilesX×tilesY atlas;
// the consumer shader adds per-instance tile offsets at draw time.
@@ -599,6 +605,16 @@ await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?,
// NOTE: Use only listed kiln.material.*.v1 IDs and approved kiln.texture.* resource IDs. Leaf
// is MASK, glass is BLEND, and host file paths are forbidden.
// e.g. const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#6b4328' });
+await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', name?, baseColor?, roughness?, metalness?, emissive?, emissiveIntensity?, alphaMode?, alphaCutoff?, doubleSided?, textures?: { baseColor?, normal?, metallicRoughness?, emissive?, occlusion? } })
+ // Compiles the strict portable material contract. Texture refs are either typed procedural V2
+ // specs or closed approved kiln.texture.* IDs; paths, URLs, raw textures, callbacks, and
+ // shader source are rejected.
+ // NOTE: Use metallicRoughness as one packed G=roughness/B=metalness map. Every procedural ref
+ // usage must match its slot; resource refs must be approved for that exact slot.
+ // e.g. const steel = await compilePortableMaterialSpecV2({ schemaVersion: 2, model:
+ // 'pbrMetallicRoughness', roughness: 0.45, metalness: 0.85, textures: { metallicRoughness: {
+ // kind: 'procedural', spec: { schemaVersion: 2, usage: 'metallicRoughness', size: 64, layers:
+ // [{ op: 'solid', color: 0x0080cc }] } } } });
basicMaterial(color, opts?: { transparent, opacity })
// Unlit flat material. For UI / effects where lighting is baked in.
// e.g. const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });
@@ -612,13 +628,13 @@ pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emis
// Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness,
// B=metalness); separate data maps are rejected instead of silently dropping a channel.
// Supports OPAQUE/MASK/BLEND and double-sided output.
- // e.g. const wood = await loadTexture('./oak.png'); const crate = pbrMaterial({ albedo: wood,
- // roughness: 0.85, metalness: 0 });
+ // e.g. const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op:
+ // 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] }); const
+ // crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });
foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })
// Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and
// double-sided. Use an alpha-bearing albedo texture.
- // e.g. const leaves = await loadTexture('./leaf.png', { usage: 'albedo' }); const mat =
- // foliageMaterial(leaves, { alphaCutoff: 0.45 });
+ // e.g. const mat = await materialRecipe('kiln.material.leaf.v1');
// Instancing (share geometry+material; smaller GLBs)
createWheelGeometrySet(radius: number, width: number)
@@ -804,35 +820,35 @@ panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)
// e.g. const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30); const cowl
// = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed
-// Textures (loadTexture is async)
-await loadTexture(source, { usage?: 'albedo'|'emissive'|'normal'|'roughness'|'metalness'|'metallicRoughness'|'occlusion', name? })
- // Loads a PNG/JPG/WebP image with explicit slot usage. Albedo/emissive preview as sRGB;
- // normal/roughness/metalness/occlusion are linear data. Stashes encoded bytes and QA metadata
- // for lossless GLB export.
- // NOTE: NEVER texture.clone() a loaded texture (clone() corrupts the encoded bytes and breaks
- // GLB export). Share the same Texture object and remap UVs with panelRemapV on the smaller
- // mesh instead.
- // e.g. const wood = await loadTexture('./textures/oak-albedo.png', { usage: 'albedo' });
-proceduralTexture({ size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })
+// Textures (approved resource loading is async)
+await loadApprovedTexture(resourceId)
+ // Loads one approved kiln.texture.* resource ID through the host-injected closed resolver.
+ // The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte
+ // arrays, resolver objects, hashes, and options are rejected.
+ // NOTE: Use only a concrete resource ID listed in material capabilities; never invent one.
+ // Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for
+ // authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes
+ // and breaks GLB export).
+ // e.g. const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');
+proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })
// Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite
// bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes
// and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.
- // NOTE: Sync — no await. Prefer this over loadTexture for any surface you can describe (wood,
- // rust, brick, fabric, dirt): it needs no asset files and cannot fail at load. Max 8 layers,
- // size must be a power of two up to 1024. Only the six listed ops exist; there is no custom
- // per-pixel callback.
- // e.g. const bark = proceduralTexture({ size: 256, usage: 'albedo', name: 'Bark', layers: [{
- // op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale:
- // 6, octaves: 4, blend: 'overlay' }] });
+ // NOTE: Sync — no await. Strict V2 JSON boundary: unknown/prototype keys, callbacks, paths,
+ // URLs, and shader source are rejected. Prefer this over approved resources for describable
+ // surfaces. Max 8 layers, power-of-two size up to 1024. Only the six listed ops exist.
+ // e.g. const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name:
+ // 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB:
+ // 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });
normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })
// Derives a tangent-space normal map from the source texture's brightness, treating it as
// height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at
// the edges, so a tiling source gives a tiling normal map.
// NOTE: strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always
// linear data — never assign it to an albedo/emissive slot.
- // e.g. const bark = proceduralTexture({ usage: 'albedo', layers: [{ op: 'noise', colorA:
- // 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] }); const mat = pbrMaterial({ albedo:
- // bark, normal: normalMapFromHeight(bark, { strength: 4 }) });
+ // e.g. const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op:
+ // 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] }); const mat =
+ // pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });
// Animation — keyframes use "rotation"/"position"/"scale" keys, NOT "value"
rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')
diff --git a/src/__tests__/composer-agent-tools.test.ts b/src/__tests__/composer-agent-tools.test.ts
index 8002636f..b487950c 100644
--- a/src/__tests__/composer-agent-tools.test.ts
+++ b/src/__tests__/composer-agent-tools.test.ts
@@ -278,6 +278,64 @@ describe('render tools call the port and return content blocks', () => {
expect(r.ok).toBe(false);
expect(r.error).toBe('boom');
});
+
+ test('scene views expose valid derivative fidelity but never exactArtifact', async () => {
+ const model = new PlacementModel('T', { catalog: [asset('well')] });
+ const sink: ComposerSink = {};
+ const hash = `sha256:${'a'.repeat(64)}` as const;
+ const render: SceneRenderPort = async () => ({
+ ok: true,
+ pngBase64: PNG_B64,
+ viewFidelity: {
+ version: 'kiln.derivative-review-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: false,
+ degraded: false,
+ receipts: [
+ {
+ version: 'kiln.view-fidelity.v1',
+ derivativeLabel: 'Hero 3/4',
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: false,
+ rendererId: 'gpu:composer',
+ inputGlbSha256: hash,
+ degraded: false,
+ },
+ ],
+ },
+ });
+ const tools = makeSceneComposerTools({ model, render, sink });
+ await call(tools, 'scene_place', { asset: 'well', at: [0, 0] });
+ const result = await call(tools, 'scene_render');
+ expect(result[1].json.viewFidelity).toMatchObject({
+ materialFaithful: true,
+ exactArtifact: false,
+ receipts: [{ derivativeLabel: 'Hero 3/4', inputGlbSha256: hash, exactArtifact: false }],
+ });
+ });
+
+ test('scene views downgrade missing or malformed derivative receipts', async () => {
+ const model = new PlacementModel('T', { catalog: [asset('well')] });
+ const sink: ComposerSink = {};
+ const render: SceneRenderPort = async () => ({ ok: true, pngBase64: PNG_B64 });
+ const tools = makeSceneComposerTools({ model, render, sink });
+ await call(tools, 'scene_place', { asset: 'well', at: [0, 0] });
+ const result = await call(tools, 'scene_render');
+ expect(result[1].json.viewFidelity).toEqual({
+ version: 'kiln.derivative-review-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'none',
+ materialFaithful: false,
+ exactArtifact: false,
+ degraded: true,
+ receipts: [],
+ reasonCodes: ['DERIVATIVE_RECEIPT_UNAVAILABLE'],
+ });
+ });
});
describe('finalize', () => {
diff --git a/src/__tests__/composer-world-run.test.ts b/src/__tests__/composer-world-run.test.ts
index 22701c46..5a5f7621 100644
--- a/src/__tests__/composer-world-run.test.ts
+++ b/src/__tests__/composer-world-run.test.ts
@@ -1,7 +1,12 @@
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 {
+ decodeColliderArtifactV1,
+ migrateSceneModelV1ToWorldDocumentV2,
+ setWorldPresentationV1,
+ worldColliderAabbV1,
+} from '../composer';
import { createGenerationCallBudget } from '../agent/call-budget';
import {
runKilnComposer,
@@ -106,6 +111,12 @@ describe('runKilnWorldIntegration', () => {
expect.arrayContaining(['scene_world_snap', 'scene_world_render', 'scene_world_finalize']),
);
expect(String(model.seenSystemPrompts[0])).toContain(WORLD_INTEGRATION_PROMPT_V2.slice(0, 30));
+ expect(WORLD_INTEGRATION_PROMPT_V2).toContain('scene_world_view');
+ expect(WORLD_INTEGRATION_PROMPT_V2).toContain('scene_world_set_presentation');
+ expect(WORLD_INTEGRATION_PROMPT_V2).toContain('16,777,216');
+ expect(WORLD_INTEGRATION_PROMPT_V2).toContain('Do not send artifactBinding');
+ expect(WORLD_INTEGRATION_PROMPT_V2).toContain('scene_world_set_collision');
+ expect(WORLD_INTEGRATION_PROMPT_V2).toContain('authored-submesh');
});
test('surfaces and returns an exact GPU receipt for persistence', async () => {
@@ -178,6 +189,194 @@ describe('runKilnWorldIntegration', () => {
]);
});
+ test('makes exact current presentation values and aggregate limits model-visible', async () => {
+ const presented = setWorldPresentationV1(world(), {
+ schemaVersion: 'kiln.presentation.v1',
+ grid: { columns: 1, rows: 1, cellWidth: 640, cellHeight: 360 },
+ lightingPresetId: 'neutral-studio-v1',
+ receiptPolicy: {
+ requirePerCameraOutputSha256: true,
+ requireOutputSetSha256: true,
+ },
+ cameras: [
+ {
+ id: 'model-authored-hero',
+ cell: { column: 0, row: 0 },
+ position: [9, 6, 7],
+ target: [1, 2, 3],
+ up: [0, 1, 0],
+ fovDeg: 47,
+ aspect: 16 / 9,
+ near: 0.2,
+ far: 250,
+ },
+ ],
+ });
+ const model = new ToolCapturingModel([
+ { toolCalls: [{ name: 'scene_world_view' }] },
+ { toolCalls: [{ name: 'scene_world_finalize' }] },
+ { text: 'done' },
+ ]);
+ const result = await runKilnWorldIntegration({
+ model,
+ prompt: 'inspect the authored presentation',
+ world: presented,
+ render: async () => ({ ok: true }),
+ maxSteps: 5,
+ });
+
+ expect(result.finalized).toBe(true);
+ const modelContext = JSON.stringify(model.messages);
+ expect(modelContext).toContain('model-authored-hero');
+ expect(modelContext).toContain('"position":[9,6,7]');
+ expect(modelContext).toContain('"target":[1,2,3]');
+ expect(modelContext).toContain('"maxTotalPixels":16777216');
+ expect(modelContext).toContain('"authoredByModel":false');
+ });
+
+ test('routes authored GLB node geometry through the bounded production collider ports', async () => {
+ const model = new ToolCapturingModel([
+ {
+ toolCalls: [
+ {
+ name: 'scene_world_set_collision',
+ input: {
+ objectId: 'crate',
+ policy: {
+ kind: 'authored-submesh',
+ transformFrame: 'asset-local',
+ nodeNames: ['Collider_Main'],
+ },
+ },
+ },
+ ],
+ },
+ { toolCalls: [{ name: 'scene_world_finalize' }] },
+ { text: 'done' },
+ ]);
+ let resolverRequest: unknown;
+ let published: Uint8Array | undefined;
+ const result = await runKilnWorldIntegration({
+ model,
+ prompt: 'use the authored collider node',
+ world: world(),
+ render: async () => ({ ok: true }),
+ resolveAuthoredColliderGeometry: async (request) => {
+ resolverRequest = request;
+ return {
+ schemaVersion: 'kiln.authored-collider-geometry.v1',
+ sourceArtifactSha256: request.sourceArtifactSha256,
+ transformFrame: 'asset-local',
+ submeshes: [
+ {
+ nodeName: 'Collider_Main',
+ positions: [-1, 0, -1, 1, 0, -1, 0, 2, 1],
+ indices: [0, 1, 2],
+ },
+ ],
+ };
+ },
+ publishColliderArtifact: async (_artifact, bytes) => {
+ published = bytes;
+ return { uri: 'colliders/crate-authored.collider.json' };
+ },
+ maxSteps: 5,
+ });
+
+ expect(result.finalized).toBe(true);
+ expect(resolverRequest).toMatchObject({
+ sourceArtifactSha256: `sha256:${'a'.repeat(64)}`,
+ transformFrame: 'asset-local',
+ nodeNames: ['Collider_Main'],
+ });
+ const artifact = decodeColliderArtifactV1(published!);
+ expect(artifact.policy).toEqual({
+ kind: 'authored-submesh',
+ transformFrame: 'asset-local',
+ nodeNames: ['Collider_Main'],
+ });
+ expect(
+ worldColliderAabbV1(artifact, {
+ position: result.world.objects[0]!.transform.position,
+ rotationYDeg: result.world.objects[0]!.transform.rotationYDeg,
+ uniformScale: result.world.objects[0]!.transform.uniformScale,
+ }),
+ ).toEqual({ min: [4, 0, 4], max: [6, 2, 6] });
+ expect(result.world.objects[0]?.collision?.policy).toBe('artifact');
+ });
+
+ test('forwards persisted presentation parameters and accepts only their exact receipt', async () => {
+ const presented = setWorldPresentationV1(world(), {
+ schemaVersion: 'kiln.presentation.v1',
+ grid: { columns: 1, rows: 1, cellWidth: 320, cellHeight: 180 },
+ lightingPresetId: 'neutral-studio-v1',
+ receiptPolicy: {
+ requirePerCameraOutputSha256: true,
+ requireOutputSetSha256: true,
+ },
+ cameras: [
+ {
+ id: 'hero',
+ cell: { column: 0, row: 0 },
+ position: [8, 5, 8],
+ target: [0, 1, 0],
+ up: [0, 1, 0],
+ fovDeg: 50,
+ aspect: 16 / 9,
+ near: 0.1,
+ far: 100,
+ },
+ ],
+ });
+ const model = new ToolCapturingModel([
+ { toolCalls: [{ name: 'scene_world_render' }] },
+ { toolCalls: [{ name: 'scene_world_finalize' }] },
+ { text: 'done' },
+ ]);
+ let captured: Parameters<SceneRenderPort>[0] | undefined;
+ const result = await runKilnWorldIntegration({
+ model,
+ prompt: 'inspect the authored presentation',
+ world: presented,
+ render: async (request) => {
+ captured = request;
+ return {
+ ok: true,
+ pngBase64: Buffer.from('png').toString('base64'),
+ receipt: {
+ worldHash: request.worldHash!,
+ cameras: request.cameras!.map((camera) => ({
+ position: camera.position,
+ target: camera.target,
+ up: camera.up!,
+ fovDeg: camera.fovDeg!,
+ aspect: camera.aspect!,
+ near: camera.near!,
+ far: camera.far!,
+ })),
+ width: request.width!,
+ height: request.height!,
+ lightingPresetId: request.lightingPresetId!,
+ backend: 'vulkan',
+ rendererId: 'gpu:test',
+ perCameraOutputSha256: [`sha256:${'b'.repeat(64)}`],
+ outputSetSha256: `sha256:${'c'.repeat(64)}`,
+ outputSha256: `sha256:${'d'.repeat(64)}`,
+ },
+ };
+ },
+ maxSteps: 6,
+ });
+ expect(result.finalized).toBe(true);
+ expect(result.renderEvidence).toHaveLength(1);
+ expect(captured).toMatchObject({
+ width: 320,
+ height: 180,
+ lightingPresetId: 'neutral-studio-v1',
+ });
+ expect(captured?.cameras).toHaveLength(1);
+ });
+
test('rejects mismatched per-camera output evidence and exact/fallback ambiguity', async () => {
const exact = {
worldHash: `sha256:${'a'.repeat(64)}` as const,
diff --git a/src/__tests__/composer-world-tools.test.ts b/src/__tests__/composer-world-tools.test.ts
index cac93115..b577c8b5 100644
--- a/src/__tests__/composer-world-tools.test.ts
+++ b/src/__tests__/composer-world-tools.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'bun:test';
import type { Tool } from '@strands-agents/sdk';
import type { SceneModelJSON } from '../composer';
-import { migrateSceneModelV1ToWorldDocumentV2 } from '../composer';
+import { decodeColliderArtifactV1, migrateSceneModelV1ToWorldDocumentV2 } from '../composer';
import { makeWorldIntegrationToolsV2, type WorldIntegrationToolState } from '../composer/agent';
function state(): WorldIntegrationToolState {
@@ -43,13 +43,15 @@ const call = (tools: Tool[], name: string, input: unknown) =>
>;
describe('Composer V2 world tools', () => {
- test('exposes a bounded seven-tool integration surface and authors canonical state', async () => {
+ test('exposes a bounded nine-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_collision',
'scene_world_set_paths',
+ 'scene_world_set_presentation',
'scene_world_set_sockets',
'scene_world_set_spawns',
'scene_world_set_zones',
@@ -80,6 +82,59 @@ describe('Composer V2 world tools', () => {
socketId: 'slot',
transform: { position: [0, 0, 0], rotationYDeg: 90 },
});
+ expect(
+ (
+ await call(tools, 'scene_world_set_presentation', {
+ presentation: {
+ schemaVersion: 'kiln.presentation.v1',
+ grid: { columns: 1, rows: 1, cellWidth: 320, cellHeight: 180 },
+ lightingPresetId: 'neutral-studio-v1',
+ receiptPolicy: {
+ requirePerCameraOutputSha256: true,
+ requireOutputSetSha256: true,
+ },
+ cameras: [
+ {
+ id: 'hero',
+ cell: { column: 0, row: 0 },
+ position: [8, 5, 8],
+ target: [0, 1, 0],
+ up: [0, 1, 0],
+ fovDeg: 50,
+ aspect: 16 / 9,
+ near: 0.1,
+ far: 100,
+ },
+ ],
+ },
+ })
+ ).ok,
+ ).toBe(true);
+ expect(target.world.presentation?.cameras[0]?.id).toBe('hero');
+ await expect(
+ call(tools, 'scene_world_set_presentation', {
+ presentation: {
+ schemaVersion: 'kiln.presentation.v1',
+ grid: { columns: 4, rows: 3, cellWidth: 4096, cellHeight: 4096 },
+ lightingPresetId: 'neutral-studio-v1',
+ receiptPolicy: {
+ requirePerCameraOutputSha256: true,
+ requireOutputSetSha256: true,
+ },
+ cameras: Array.from({ length: 12 }, (_, index) => ({
+ id: `oversized-${index}`,
+ cell: { column: index % 4, row: Math.floor(index / 4) },
+ position: [index + 1, 2, 3],
+ target: [0, 0, 0],
+ up: [0, 1, 0],
+ fovDeg: 50,
+ aspect: 1,
+ near: 0.1,
+ far: 100,
+ })),
+ },
+ }),
+ ).rejects.toThrow(/total pixel budget/i);
});
test('publishes the exact heightfield bytes and binds the returned URI/hash', async () => {
@@ -109,4 +164,194 @@ describe('Composer V2 world tools', () => {
artifact: { uri: 'terrain/generated.heightfield.json' },
});
});
+
+ test('compiles and publishes a bounded generated collider while simple policies stay inline', async () => {
+ const target = state();
+ let published: Uint8Array | undefined;
+ const tools = makeWorldIntegrationToolsV2({
+ state: target,
+ publishColliderArtifact: async (_artifact, bytes) => {
+ published = bytes;
+ return { uri: 'colliders/crate.collider.json' };
+ },
+ });
+ expect(
+ (
+ await call(tools, 'scene_world_set_collision', {
+ objectId: 'crate',
+ policy: { kind: 'bounds', transformFrame: 'asset-local' },
+ })
+ ).ok,
+ ).toBe(true);
+ expect(target.world.objects[0]?.collision).toEqual({ policy: 'bounds' });
+
+ const generated = await call(tools, 'scene_world_set_collision', {
+ objectId: 'crate',
+ policy: { kind: 'generated-mesh', transformFrame: 'asset-local', method: 'bounds-box' },
+ });
+ expect(generated.ok).toBe(true);
+ expect(published).toBeDefined();
+ expect(decodeColliderArtifactV1(published!)).toMatchObject({
+ sourceArtifactSha256: `sha256:${'a'.repeat(64)}`,
+ bounds: { min: [-1, 0, -1], max: [1, 2, 1] },
+ });
+ const collisionRefId = `collision:${String(generated.sha256).slice('sha256:'.length)}`;
+ expect(target.world.objects[0]?.collision).toEqual({
+ policy: 'artifact',
+ artifactRefId: collisionRefId,
+ });
+ expect(target.world.collisionArtifacts[0]).toMatchObject({
+ refId: collisionRefId,
+ artifact: { uri: 'colliders/crate.collider.json' },
+ });
+
+ const unsupported = makeWorldIntegrationToolsV2({ state: state() });
+ expect(
+ await call(unsupported, 'scene_world_set_collision', {
+ objectId: 'crate',
+ policy: { kind: 'generated-mesh', transformFrame: 'asset-local', method: 'bounds-box' },
+ }),
+ ).toEqual({ ok: false, error: 'collider artifact publisher is not configured' });
+ expect(
+ await call(unsupported, 'scene_world_set_collision', {
+ objectId: 'crate',
+ policy: {
+ kind: 'authored-submesh',
+ transformFrame: 'asset-local',
+ nodeNames: ['Collider_Main'],
+ },
+ }),
+ ).toEqual({
+ ok: false,
+ error: 'authored collider geometry resolver is not configured',
+ });
+ });
+
+ test('resolves only hash-bound named GLB nodes for authored-submesh colliders', async () => {
+ const target = state();
+ let resolverRequest: unknown;
+ let published: Uint8Array | undefined;
+ const tools = makeWorldIntegrationToolsV2({
+ state: target,
+ resolveAuthoredColliderGeometry: async (request) => {
+ resolverRequest = request;
+ return {
+ schemaVersion: 'kiln.authored-collider-geometry.v1',
+ sourceArtifactSha256: `sha256:${'a'.repeat(64)}`,
+ transformFrame: 'asset-local',
+ submeshes: [
+ {
+ nodeName: 'Collider_Main',
+ positions: [-1, 0, -1, 1, 0, -1, 0, 2, 1],
+ indices: [0, 1, 2],
+ },
+ ],
+ };
+ },
+ publishColliderArtifact: async (_artifact, bytes) => {
+ published = bytes;
+ return { uri: 'colliders/authored.collider.json' };
+ },
+ });
+
+ const result = await call(tools, 'scene_world_set_collision', {
+ objectId: 'crate',
+ policy: {
+ kind: 'authored-submesh',
+ transformFrame: 'asset-local',
+ nodeNames: ['Collider_Main'],
+ },
+ });
+ expect(result.ok).toBe(true);
+ expect(resolverRequest).toEqual({
+ schemaVersion: 'kiln.authored-collider-geometry.v1',
+ sourceArtifactSha256: `sha256:${'a'.repeat(64)}`,
+ transformFrame: 'asset-local',
+ nodeNames: ['Collider_Main'],
+ limits: { maxNodes: 64, maxVertices: 65_536, maxTriangles: 65_536 },
+ });
+ expect(decodeColliderArtifactV1(published!)).toMatchObject({
+ transformFrame: 'asset-local',
+ sourceArtifactSha256: `sha256:${'a'.repeat(64)}`,
+ policy: { kind: 'authored-submesh', nodeNames: ['Collider_Main'] },
+ bounds: { min: [-1, 0, -1], max: [1, 2, 1] },
+ });
+
+ const failed = async (resolution: unknown) => {
+ const isolated = makeWorldIntegrationToolsV2({
+ state: state(),
+ resolveAuthoredColliderGeometry: async () => resolution,
+ publishColliderArtifact: async () => {
+ throw new Error('must not publish invalid geometry');
+ },
+ });
+ return call(isolated, 'scene_world_set_collision', {
+ objectId: 'crate',
+ policy: {
+ kind: 'authored-submesh',
+ transformFrame: 'asset-local',
+ nodeNames: ['Collider_Main'],
+ },
+ });
+ };
+ expect(
+ await failed({
+ schemaVersion: 'kiln.authored-collider-geometry.v1',
+ sourceArtifactSha256: `sha256:${'b'.repeat(64)}`,
+ transformFrame: 'asset-local',
+ submeshes: [
+ {
+ nodeName: 'Collider_Main',
+ positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
+ indices: [0, 1, 2],
+ },
+ ],
+ }),
+ ).toMatchObject({ ok: false, error: expect.stringContaining('SOURCE_HASH_MISMATCH') });
+ expect(
+ await failed({
+ schemaVersion: 'kiln.authored-collider-geometry.v1',
+ sourceArtifactSha256: `sha256:${'a'.repeat(64)}`,
+ transformFrame: 'asset-local',
+ submeshes: [
+ {
+ nodeName: 'Other',
+ positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
+ indices: [0, 1, 2],
+ },
+ ],
+ }),
+ ).toMatchObject({ ok: false, error: expect.stringContaining('SUBMESH_MISSING') });
+ expect(
+ await failed({
+ schemaVersion: 'kiln.authored-collider-geometry.v1',
+ sourceArtifactSha256: `sha256:${'a'.repeat(64)}`,
+ transformFrame: 'asset-local',
+ submeshes: [
+ {
+ nodeName: 'Collider_Main',
+ positions: Array.from({ length: 65_537 * 3 }, () => 0),
+ indices: [0, 1, 2],
+ },
+ ],
+ }),
+ ).toMatchObject({ ok: false, error: expect.stringContaining('BUDGET_EXCEEDED') });
+
+ const resolverOnly = makeWorldIntegrationToolsV2({
+ state: state(),
+ resolveAuthoredColliderGeometry: async () => {
+ throw new Error('must not resolve without a publisher');
+ },
+ });
+ expect(
+ await call(resolverOnly, 'scene_world_set_collision', {
+ objectId: 'crate',
+ policy: {
+ kind: 'authored-submesh',
+ transformFrame: 'asset-local',
+ nodeNames: ['Collider_Main'],
+ },
+ }),
+ ).toEqual({ ok: false, error: 'collider artifact publisher is not configured' });
+ });
});
diff --git a/src/__tests__/csg-sandbox.test.ts b/src/__tests__/csg-sandbox.test.ts
index 61d0d4b8..0edf1ee1 100644
--- a/src/__tests__/csg-sandbox.test.ts
+++ b/src/__tests__/csg-sandbox.test.ts
@@ -14,18 +14,16 @@ const meta = { name: 'Gear', category: 'prop' };
async function build() {
const root = createRoot('Gear');
const steel = gameMaterial(0xb0b0b0, { metalness: 0.7, roughness: 0.3 });
- const body = new (Object.getPrototypeOf(createPart('X', boxGeo(0,0,0), steel)).constructor)(cylinderGeo(1, 1, 0.3, 32), steel);
- // Use THREE.Mesh via createPart-less construction since the sandbox
- // does expose a Three-compatible Mesh through createPart.
- // Simpler: use createPart which returns a Mesh, grab it as an operand.
+ const body = createPart('Body', cylinderGeo(1, 1, 0.3, 32), steel, {});
+ const notch = createPart('Notch', boxGeo(0.3, 2.2, 0.5), steel, {});
+ const gear = await boolDiff('GearBody', body, notch);
+ root.add(gear);
return root;
}
`;
- // The above stub just verifies the async path works at all. A more
- // realistic sandbox path would involve THREE.Mesh, but the sandbox
- // doesn't expose THREE directly. See the follow-up scenario below.
const { root } = await executeKilnCode(code);
expect(root.name).toBe('Gear');
+ expect(root.children[0]?.name).toBe('Mesh_GearBody');
});
it('agent-style code using createPart siblings + boolDiff', async () => {
diff --git a/src/__tests__/generated-source-policy.test.ts b/src/__tests__/generated-source-policy.test.ts
new file mode 100644
index 00000000..0e7171e4
--- /dev/null
+++ b/src/__tests__/generated-source-policy.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, test } from 'bun:test';
+
+import { executeKilnCode } from '../render';
+import { validate } from '../validation';
+
+const wrap = (body: string): string => `
+const meta = { name: 'Policy test' };
+function build() {
+ const root = createRoot('Root');
+ ${body}
+ return root;
+}
+`;
+
+const policyCodes = (source: string): string[] =>
+ validate(source).issues.map((issue) => issue.code);
+
+describe('H6.5 generated-source policy', () => {
+ test.each([
+ ['globalThis', 'void globalThis;'],
+ ['global', 'void global;'],
+ ['process', 'void process;'],
+ ['fetch', "fetch('https://example.invalid');"],
+ ['XMLHttpRequest', 'new XMLHttpRequest();'],
+ ['WebSocket', "new WebSocket('wss://example.invalid');"],
+ ['Function', "Function('return 1')();"],
+ ['eval', "eval('1 + 1');"],
+ ])('rejects the ambient %s capability', (_name, expression) => {
+ expect(policyCodes(wrap(expression))).toContain('UNSAFE_GLOBAL_ACCESS');
+ });
+
+ test.each([
+ "this['pro' + 'cess']",
+ "globalThis['fe' + 'tch']",
+ 'globalThis[`WebSocket`]',
+ ])('rejects computed ambient-global access: %s', (expression) => {
+ expect(policyCodes(wrap(`void ${expression};`))).toContain('UNSAFE_GLOBAL_ACCESS');
+ });
+
+ test('rejects dynamic import without echoing its specifier', async () => {
+ const source = wrap("return import('node:fs');");
+ const result = validate(source);
+ expect(result.issues.map(({ code }) => code)).toContain('DYNAMIC_IMPORT');
+ expect(result.errors.join('\n')).not.toContain('node:fs');
+ await expect(executeKilnCode(source)).rejects.toMatchObject({
+ name: 'GeneratedSourcePolicyError',
+ code: 'DYNAMIC_IMPORT',
+ });
+ try {
+ await executeKilnCode(source);
+ } catch (error) {
+ expect(String(error)).not.toContain('node:fs');
+ }
+ });
+
+ test.each([
+ '(()=>{}).constructor',
+ "(()=>{})['constructor']",
+ "(()=>{})['con' + 'structor']",
+ '(()=>{})[`constructor`]',
+ "const key = 'con' + 'structor'; (()=>{})[key]",
+ "Reflect.get(()=>{}, 'constructor')",
+ 'const { constructor: makeFunction } = (()=>{}); void makeFunction;',
+ ])('rejects constructor-chain access: %s', (expression) => {
+ expect(policyCodes(wrap(`${expression};`))).toContain('DYNAMIC_CODE_ACCESS');
+ });
+
+ test.each([
+ 'new THREE.DataTexture()',
+ "new THREE['DataTexture']()",
+ "new THREE['Data' + 'Texture']()",
+ 'new THREE[`DataTexture`]()',
+ 'new THREE.ShaderMaterial()',
+ "new THREE['Shader' + 'Material']()",
+ 'new THREE.RawShaderMaterial()',
+ "new THREE['RawShaderMaterial']()",
+ 'const { DataTexture: TextureCtor } = THREE; new TextureCtor();',
+ ])('rejects generated raw material or texture construction: %s', (expression) => {
+ expect(policyCodes(wrap(`${expression};`))).toContain('UNSAFE_THREE_CONSTRUCTOR');
+ });
+
+ test.each([
+ 'const T = THREE; new T.DataTexture();',
+ 'let T; T = THREE; new T.ShaderMaterial();',
+ ])('rejects aliasing the THREE namespace: %s', (expression) => {
+ expect(policyCodes(wrap(expression))).toContain('UNSAFE_THREE_ALIAS');
+ });
+
+ test('rejects non-static computed THREE access while preserving direct safe constructors', () => {
+ expect(
+ policyCodes(wrap("const name = Math.random() ? 'Mesh' : 'Group'; new THREE[name]();")),
+ ).toContain('UNSAFE_THREE_COMPUTED_ACCESS');
+ expect(policyCodes(wrap('new THREE.Mesh(); new THREE.Vector3();'))).not.toContain(
+ 'UNSAFE_THREE_COMPUTED_ACCESS',
+ );
+ });
+
+ test('rejects descriptor-based constructor retrieval', () => {
+ expect(
+ policyCodes(wrap("Object.getOwnPropertyDescriptor((()=>{}), 'con' + 'structor').value;")),
+ ).toContain('DYNAMIC_CODE_ACCESS');
+ });
+
+ test('blocks policy violations before generated source has any side effect', async () => {
+ const marker = '__kilnH65ShouldNeverExecute';
+ delete (globalThis as Record<string, unknown>)[marker];
+ try {
+ await expect(executeKilnCode(wrap(`globalThis['${marker}'] = true;`))).rejects.toMatchObject({
+ name: 'GeneratedSourcePolicyError',
+ code: 'UNSAFE_GLOBAL_ACCESS',
+ });
+ expect((globalThis as Record<string, unknown>)[marker]).toBeUndefined();
+ } finally {
+ delete (globalThis as Record<string, unknown>)[marker];
+ }
+ });
+
+ test('keeps safe THREE constructors and ordinary computed properties valid', async () => {
+ const source = wrap(`
+ const labels = { process: 'paint process', fetch: 'fetch detail', constructorLabel: 'constructor' };
+ const axis = new THREE.Vector3(1, 0, 0);
+ const mesh = new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0x884422));
+ mesh.position[axis.x === 1 ? 'x' : 'z'] = labels['process'].length * 0.01;
+ root.add(mesh);
+ `);
+ expect(validate(source).valid).toBe(true);
+ await expect(executeKilnCode(source)).resolves.toMatchObject({
+ root: { isObject3D: true },
+ });
+ });
+
+ test('does not scan comments, strings, or benign object keys as capabilities', () => {
+ const source = wrap(`
+ // fetch(globalThis.process) and new THREE.DataTexture() are forbidden examples only.
+ const notes = ['eval', 'Function', 'WebSocket', 'constructor'];
+ const metadata = { globalThis: false, process: false, DataTexture: false };
+ root.userData.notes = notes;
+ root.userData.metadata = metadata;
+ `);
+ expect(validate(source).valid).toBe(true);
+ });
+});
diff --git a/src/__tests__/kit.test.ts b/src/__tests__/kit.test.ts
index c7d6e6cd..5edf97b4 100644
--- a/src/__tests__/kit.test.ts
+++ b/src/__tests__/kit.test.ts
@@ -45,7 +45,7 @@ async function build() {
size: 64,
layers: [
{ op: 'solid', color: 0x8a5a2b },
- { op: 'bricks', brick: 0xc09050, mortar: 0x6a4020, scale: 4, blend: 'overlay' },
+ { op: 'bricks', brick: 0xc09050, mortar: 0x6a4020, rows: 4, cols: 4, blend: 'overlay' },
],
});
root.add(createPart('Body', boxGeo(1, 1, 1), pbrMaterial({ albedo, roughness: 0.8 }), {}));
@@ -75,7 +75,7 @@ async function build() {
size: 64,
layers: [
{ op: 'solid', color: 0x8a5a2b },
- { op: 'bricks', brick: 0xc09050, mortar: 0x6a4020, scale: 4, blend: 'overlay' },
+ { op: 'bricks', brick: 0xc09050, mortar: 0x6a4020, rows: 4, cols: 4, blend: 'overlay' },
],
});
root.add(createPart('Body', boxGeo(1, 1, 1), pbrMaterial({ albedo, roughness: 0.8 }), {}));
@@ -104,7 +104,7 @@ async function build() {
usage: 'occlusion',
layers: [
{ op: 'solid', color: 0xffffff },
- { op: 'stripes', colorA: 0x808080, colorB: 0xffffff, scale: 6, blend: 'multiply' },
+ { op: 'stripes', colorA: 0x808080, colorB: 0xffffff, count: 6, blend: 'multiply' },
],
});
root.add(createPart('Body', boxGeo(1, 1, 1), pbrMaterial({ albedo: 0x8a5a2b, metallicRoughness: mr, aoMap: ao }), {}));
diff --git a/src/__tests__/material-resource-registry.test.ts b/src/__tests__/material-resource-registry.test.ts
index ec3d84d2..e49a2282 100644
--- a/src/__tests__/material-resource-registry.test.ts
+++ b/src/__tests__/material-resource-registry.test.ts
@@ -20,6 +20,7 @@ import {
import {
ApprovedTextureResourceCache,
ApprovedTextureResourceUnavailableError,
+ TEXTURE_RESOLVER_LIMITS_V1,
approvedTextureCatalogV1,
} from '../material-resources';
import { buildMaterialRecipePromptContextV1 } from '../material-recipe-prompt';
@@ -70,7 +71,7 @@ describe('runtime-delivered approved resources', () => {
test('resolved bytes carry the same provenance as embedded ones, marked by delivery', async () => {
const cache = new ApprovedTextureResourceCache({
registry: RUNTIME_REGISTRY,
- resolver: async () => goodBytes(),
+ resolver: async () => ({ bytes: goodBytes(), mime: 'image/png' }),
});
const resolved = await cache.resolveAsync(SUBJECT);
@@ -92,14 +93,14 @@ describe('runtime-delivered approved resources', () => {
const bytes = goodBytes();
const last = bytes.byteLength - 1;
bytes.set([(bytes[last] ?? 0) ^ 0xff], last);
- return bytes;
+ return { bytes, mime: 'image/png' };
},
});
await expect(wrong.resolveAsync(SUBJECT)).rejects.toThrow(/does not match the pinned/);
const truncated = new ApprovedTextureResourceCache({
registry: RUNTIME_REGISTRY,
- resolver: async () => goodBytes().subarray(0, 40),
+ resolver: async () => ({ bytes: goodBytes().subarray(0, 40), mime: 'image/png' }),
});
// Reported as a length, because the usual cause is an error document or a
// partial body, and a hash mismatch would read as corruption instead.
@@ -108,6 +109,72 @@ describe('runtime-delivered approved resources', () => {
);
});
+ test('host payloads reject oversize bytes, unsupported MIME/format, and unsafe dimensions', async () => {
+ const oversized = new ApprovedTextureResourceCache({
+ registry: RUNTIME_REGISTRY,
+ resolver: async () => ({
+ bytes: new Uint8Array(TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes + 1),
+ mime: 'image/png',
+ }),
+ });
+ await expect(oversized.resolveAsync(SUBJECT)).rejects.toThrow(/encoded-byte limit/);
+
+ const wrongMime = new ApprovedTextureResourceCache({
+ registry: RUNTIME_REGISTRY,
+ resolver: async () => ({ bytes: goodBytes(), mime: 'image/jpeg' as never }),
+ });
+ await expect(wrongMime.resolveAsync(SUBJECT)).rejects.toThrow(/MIME/);
+
+ const wrongFormat = new ApprovedTextureResourceCache({
+ registry: RUNTIME_REGISTRY,
+ resolver: async () => ({ bytes: new Uint8Array(goodBytes().byteLength), mime: 'image/png' }),
+ });
+ await expect(wrongFormat.resolveAsync(SUBJECT)).rejects.toThrow(/PNG signature|format/);
+
+ const hugeDimensions = goodBytes();
+ new DataView(hugeDimensions.buffer, hugeDimensions.byteOffset).setUint32(16, 8192, false);
+ const dimensions = new ApprovedTextureResourceCache({
+ registry: RUNTIME_REGISTRY,
+ resolver: async () => ({ bytes: hugeDimensions, mime: 'image/png' }),
+ });
+ await expect(dimensions.resolveAsync(SUBJECT)).rejects.toThrow(/dimension limit/);
+
+ const tooManyPixels = goodBytes();
+ const pixelView = new DataView(tooManyPixels.buffer, tooManyPixels.byteOffset);
+ pixelView.setUint32(16, 4096, false);
+ pixelView.setUint32(20, 4096, false);
+ const pixels = new ApprovedTextureResourceCache({
+ registry: RUNTIME_REGISTRY,
+ resolver: async () => ({ bytes: tooManyPixels, mime: 'image/png' }),
+ });
+ await expect(pixels.resolveAsync(SUBJECT)).rejects.toThrow(/pixel limit/);
+
+ const suppliedHash = new ApprovedTextureResourceCache({
+ registry: RUNTIME_REGISTRY,
+ resolver: async () =>
+ ({
+ bytes: goodBytes(),
+ mime: 'image/png',
+ sha256: shipped.contentHash,
+ }) as never,
+ });
+ await expect(suppliedHash.resolveAsync(SUBJECT)).rejects.toThrow(/only bytes and MIME/);
+ });
+
+ test('host resolution has a hard deadline and exposes only an abort signal to the host', async () => {
+ let signal: AbortSignal | undefined;
+ const cache = new ApprovedTextureResourceCache({
+ registry: RUNTIME_REGISTRY,
+ resolverDeadlineMs: 10,
+ resolver: async (_descriptor, context) => {
+ signal = context.signal;
+ return await new Promise(() => {});
+ },
+ });
+ await expect(cache.resolveAsync(SUBJECT)).rejects.toThrow(/deadline exceeded/);
+ expect(signal?.aborted).toBe(true);
+ });
+
test('concurrent requests for one resource share a single fetch', async () => {
let calls = 0;
const cache = new ApprovedTextureResourceCache({
@@ -115,7 +182,7 @@ describe('runtime-delivered approved resources', () => {
resolver: async () => {
calls += 1;
await Promise.resolve();
- return goodBytes();
+ return { bytes: goodBytes(), mime: 'image/png' };
},
});
@@ -137,7 +204,7 @@ describe('runtime-delivered approved resources', () => {
resolver: async () => {
calls += 1;
if (calls === 1) throw new Error('transient network failure');
- return goodBytes();
+ return { bytes: goodBytes(), mime: 'image/png' };
},
});
@@ -154,7 +221,7 @@ describe('runtime-delivered approved resources', () => {
registry: RUNTIME_REGISTRY,
resolver: async (descriptor) => {
seen.push(descriptor.id);
- return goodBytes();
+ return { bytes: goodBytes(), mime: 'image/png' };
},
});
@@ -211,7 +278,7 @@ describe('what the model is told it can bind', () => {
const withResolver = new ApprovedTextureResourceCache({
registry: production,
- resolver: async () => goodBytes(),
+ resolver: async () => ({ bytes: goodBytes(), mime: 'image/png' }),
});
const catalog = approvedTextureCatalogV1({ cache: withResolver });
expect(catalog).toHaveLength(25);
@@ -224,7 +291,7 @@ describe('what the model is told it can bind', () => {
// while nothing reported any, so the only way to use a slot was to guess an
// ID and be rejected by validation.
expect(empty).toContain('none are available in this');
- expect(empty).toContain('proceduralTexture()');
+ expect(empty).toContain('proceduralTexture({ schemaVersion: 2, ... })');
// It still names the shape of the IDs, but no concrete one — there is
// nothing to bind, and a guessable example would be guessed.
expect(empty).not.toMatch(/kiln\.texture\.[a-z]/);
diff --git a/src/__tests__/portable-material-runtime.test.ts b/src/__tests__/portable-material-runtime.test.ts
new file mode 100644
index 00000000..ea245e40
--- /dev/null
+++ b/src/__tests__/portable-material-runtime.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+
+import { readMaterialResourceProvenance } from '../material-resources';
+import { compilePortableMaterialSpecV2, ProceduralTextureError } from '../primitives';
+
+const solid = (
+ usage: 'albedo' | 'normal' | 'metallicRoughness' | 'emissive' | 'occlusion',
+ color: number,
+) => ({
+ kind: 'procedural' as const,
+ spec: {
+ schemaVersion: 2 as const,
+ size: 4,
+ usage,
+ layers: [{ op: 'solid' as const, color }],
+ },
+});
+
+describe('PortableMaterialSpecV2 runtime compiler', () => {
+ test('compiles only typed procedural slots with correct color spaces and packed MR identity', async () => {
+ const material = await compilePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ name: 'PortableIron',
+ baseColor: 0x806040,
+ roughness: 0.62,
+ metalness: 0.81,
+ emissive: 0x201008,
+ emissiveIntensity: 2,
+ alphaMode: 'mask',
+ alphaCutoff: 0.4,
+ doubleSided: true,
+ textures: {
+ baseColor: solid('albedo', 0x8a6542),
+ normal: solid('normal', 0x8080ff),
+ metallicRoughness: solid('metallicRoughness', 0x00a0d0),
+ emissive: solid('emissive', 0x402010),
+ occlusion: solid('occlusion', 0xffffff),
+ },
+ });
+
+ expect(material).toBeInstanceOf(THREE.MeshStandardMaterial);
+ expect(material.name).toBe('PortableIron');
+ expect(material.map?.colorSpace).toBe(THREE.SRGBColorSpace);
+ expect(material.emissiveMap?.colorSpace).toBe(THREE.SRGBColorSpace);
+ expect(material.normalMap?.colorSpace).toBe(THREE.NoColorSpace);
+ expect(material.roughnessMap?.colorSpace).toBe(THREE.NoColorSpace);
+ expect(material.aoMap?.colorSpace).toBe(THREE.NoColorSpace);
+ expect(material.roughnessMap).toBe(material.metalnessMap);
+ expect(material.roughness).toBe(0.62);
+ expect(material.metalness).toBe(0.81);
+ expect(material.alphaTest).toBe(0.4);
+ expect(material.side).toBe(THREE.DoubleSide);
+ expect((material.userData as Record<string, unknown>)['kilnPortableMaterial']).toMatchObject({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ name: 'PortableIron',
+ });
+ });
+
+ test('loads a closed approved resource ID and preserves its verified provenance', async () => {
+ const material = await compilePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ textures: {
+ baseColor: { kind: 'resource', resourceId: 'kiln.texture.bark-albedo.v1' },
+ },
+ });
+
+ expect(material.map?.name).toBe('kiln.texture.bark-albedo.v1');
+ expect(material.map?.colorSpace).toBe(THREE.SRGBColorSpace);
+ expect(readMaterialResourceProvenance(material.map!)).toMatchObject({
+ resourceId: 'kiln.texture.bark-albedo.v1',
+ usage: 'albedo',
+ hashAlgorithm: 'sha256',
+ });
+ });
+
+ test('rejects unapproved IDs, wrong-slot resources, and executable or raw texture escapes', async () => {
+ await expect(
+ compilePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ textures: {
+ baseColor: { kind: 'resource', resourceId: 'kiln.texture.not-approved.v1' },
+ },
+ }),
+ ).rejects.toThrow(/not an approved texture resource/i);
+
+ await expect(
+ compilePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ textures: {
+ baseColor: { kind: 'resource', resourceId: 'kiln.texture.neutral-normal.v1' },
+ },
+ }),
+ ).rejects.toThrow(/baseColor.*not approved for that slot/i);
+
+ const raw = new THREE.DataTexture(new Uint8Array(4 * 4 * 4), 4, 4);
+ await expect(
+ compilePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ textures: { baseColor: raw },
+ }),
+ ).rejects.toThrow(ProceduralTextureError);
+ await expect(
+ compilePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ textures: {
+ baseColor: { kind: 'resource', resourceId: 'https://example.invalid/wood.png' },
+ },
+ }),
+ ).rejects.toThrow(/bounded kiln.* resource ID/i);
+ await expect(
+ compilePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ shader: 'void main() {}',
+ }),
+ ).rejects.toThrow(/unknown key "shader"/i);
+ });
+});
diff --git a/src/__tests__/procedural-texture-v2.test.ts b/src/__tests__/procedural-texture-v2.test.ts
new file mode 100644
index 00000000..753bd2b2
--- /dev/null
+++ b/src/__tests__/procedural-texture-v2.test.ts
@@ -0,0 +1,290 @@
+import { createHash } from 'node:crypto';
+import { describe, expect, test } from 'bun:test';
+
+import {
+ MAX_PORTABLE_MATERIAL_TEXTURES,
+ ProceduralTextureError,
+ canonicalProceduralTextureJsonV2,
+ canonicalizePortableMaterialSpecV2,
+ canonicalizeProceduralTextureSpecV2,
+ compileProceduralTextureSpecV2,
+ hashProceduralTextureSpecV2,
+ migrateProceduralTextureSpecV1,
+ proceduralTexture,
+} from '../procedural-texture';
+
+const pixelSha256 = (pixels: Uint8Array): string =>
+ createHash('sha256').update(pixels).digest('hex');
+
+const FIXTURE_CORPUS = [
+ {
+ id: 'checker-albedo-v2',
+ spec: {
+ schemaVersion: 2 as const,
+ size: 8,
+ usage: 'albedo' as const,
+ name: 'FixtureChecker',
+ layers: [{ op: 'checker' as const, colorA: 0x102030, colorB: 0xd0e0f0, squares: 4 }],
+ },
+ pixelSha256: 'e9097b266f760d03a38952165177d75878c5520dde2a3ff0b61ba8149475123a',
+ },
+ {
+ id: 'layered-metallic-roughness-v2',
+ spec: {
+ schemaVersion: 2 as const,
+ size: 16,
+ usage: 'metallicRoughness' as const,
+ name: 'FixturePackedMr',
+ layers: [
+ { op: 'solid' as const, color: 0x00cc44 },
+ {
+ op: 'noise' as const,
+ colorA: 0x002211,
+ colorB: 0x00ee88,
+ scale: 4,
+ octaves: 3,
+ seed: 17,
+ blend: 'overlay' as const,
+ opacity: 0.35,
+ },
+ ],
+ },
+ pixelSha256: '62fb9afced5ea983d640465a954ecaf1c8af0a4abc3ad5f2e6455262a55b8212',
+ },
+] as const;
+
+describe('ProceduralTextureSpecV2 strict boundary', () => {
+ test('canonicalization applies defaults and makes explicit defaults byte-identical', async () => {
+ const implicit = {
+ schemaVersion: 2 as const,
+ layers: [{ op: 'noise' as const, colorA: 0, colorB: 0xffffff }],
+ };
+ const explicit = {
+ schemaVersion: 2 as const,
+ size: 256,
+ usage: 'albedo' as const,
+ layers: [
+ {
+ op: 'noise' as const,
+ colorA: 0,
+ colorB: 0xffffff,
+ scale: 8,
+ octaves: 3,
+ seed: 0,
+ blend: 'normal' as const,
+ opacity: 1,
+ },
+ ],
+ };
+
+ expect(canonicalizeProceduralTextureSpecV2(implicit)).toEqual(
+ canonicalizeProceduralTextureSpecV2(explicit),
+ );
+ expect(canonicalProceduralTextureJsonV2(implicit)).toBe(
+ canonicalProceduralTextureJsonV2(explicit),
+ );
+ expect(await hashProceduralTextureSpecV2(implicit)).toBe(
+ await hashProceduralTextureSpecV2(explicit),
+ );
+ expect(await hashProceduralTextureSpecV2(implicit)).toMatch(/^sha256:[0-9a-f]{64}$/);
+ expect(await hashProceduralTextureSpecV2(implicit)).toBe(
+ `sha256:${createHash('sha256').update(canonicalProceduralTextureJsonV2(implicit)).digest('hex')}`,
+ );
+
+ const ignoredBaseControls = {
+ schemaVersion: 2 as const,
+ layers: [
+ {
+ op: 'noise' as const,
+ colorA: 0,
+ colorB: 0xffffff,
+ blend: 'multiply' as const,
+ opacity: 0,
+ },
+ ],
+ };
+ expect(await hashProceduralTextureSpecV2(ignoredBaseControls)).toBe(
+ await hashProceduralTextureSpecV2(implicit),
+ );
+ });
+
+ test('rejects unknown keys at every discriminated boundary', () => {
+ expect(() =>
+ canonicalizeProceduralTextureSpecV2({
+ schemaVersion: 2,
+ layers: [{ op: 'solid', color: 0, callback: 'return red' }],
+ }),
+ ).toThrow(/layers\[0\].*unknown key "callback"/i);
+ expect(() =>
+ canonicalizeProceduralTextureSpecV2({
+ schemaVersion: 2,
+ layers: [{ op: 'solid', color: 0 }],
+ url: 'https://example.invalid/texture.png',
+ }),
+ ).toThrow(/unknown key "url"/i);
+ });
+
+ test('rejects prototype-bearing objects and prototype-pollution keys', () => {
+ const inherited = Object.create({ layers: [{ op: 'solid', color: 0 }] });
+ inherited.schemaVersion = 2;
+ expect(() => canonicalizeProceduralTextureSpecV2(inherited)).toThrow(/plain JSON object/i);
+
+ const polluted = JSON.parse(
+ '{"schemaVersion":2,"layers":[{"op":"solid","color":0,"__proto__":{}}]}',
+ );
+ expect(() => canonicalizeProceduralTextureSpecV2(polluted)).toThrow(/forbidden key/i);
+
+ const sparseLayers = new Array(1);
+ expect(() =>
+ canonicalizeProceduralTextureSpecV2({ schemaVersion: 2, layers: sparseLayers }),
+ ).toThrow(/dense JSON array/i);
+
+ const accessorLayer: Record<string, unknown> = { op: 'solid' };
+ Object.defineProperty(accessorLayer, 'color', {
+ enumerable: true,
+ get: () => 0,
+ });
+ expect(() =>
+ canonicalizeProceduralTextureSpecV2({ schemaVersion: 2, layers: [accessorLayer] }),
+ ).toThrow(/data field/i);
+ });
+
+ test('rejects invalid usage, non-finite numeric fields, and excessive work before compilation', () => {
+ expect(() =>
+ canonicalizeProceduralTextureSpecV2({
+ schemaVersion: 2,
+ usage: 'diffuse',
+ layers: [{ op: 'solid', color: 0 }],
+ }),
+ ).toThrow(/usage/i);
+ expect(() =>
+ canonicalizeProceduralTextureSpecV2({
+ schemaVersion: 2,
+ layers: [
+ { op: 'stripes', colorA: 0, colorB: 0xffffff, angleDeg: Number.POSITIVE_INFINITY },
+ ],
+ }),
+ ).toThrow(/angleDeg/i);
+ expect(() =>
+ canonicalizeProceduralTextureSpecV2({
+ schemaVersion: 2,
+ size: 2048,
+ layers: [{ op: 'solid', color: 0 }],
+ }),
+ ).toThrow(/power of two/i);
+ });
+});
+
+describe('V1 migration and frozen compiler corpus', () => {
+ test('legacy input migrates to the same canonical V2 recipe and pixels', () => {
+ const legacy = {
+ size: 8,
+ usage: 'albedo' as const,
+ name: 'LegacyChecker',
+ layers: [{ op: 'checker' as const, colorA: 0x111111, colorB: 0xeeeeee, squares: 2 }],
+ };
+ const migrated = migrateProceduralTextureSpecV1(legacy);
+ expect(migrated.schemaVersion).toBe(2);
+ expect(compileProceduralTextureSpecV2(legacy).pixels).toEqual(
+ compileProceduralTextureSpecV2(migrated).pixels,
+ );
+ expect(
+ (proceduralTexture(legacy).userData as Record<string, unknown>)['kilnProcedural'],
+ ).toMatchObject({ schemaVersion: 2 });
+ });
+
+ for (const fixture of FIXTURE_CORPUS) {
+ test(`${fixture.id} has frozen deterministic pixels and canonical identity`, async () => {
+ const first = compileProceduralTextureSpecV2(fixture.spec);
+ const second = compileProceduralTextureSpecV2(fixture.spec);
+ expect(second.pixels).toEqual(first.pixels);
+ expect(pixelSha256(first.pixels)).toBe(fixture.pixelSha256);
+ expect(first.canonicalJson).toBe(canonicalProceduralTextureJsonV2(fixture.spec));
+ expect(first.recipeHash).toBe(await hashProceduralTextureSpecV2(fixture.spec));
+ });
+ }
+});
+
+describe('PortableMaterialSpecV2 compatibility boundary', () => {
+ test('canonicalizes portable scalar fields and typed texture slots', () => {
+ const material = canonicalizePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ name: 'WeatheredIron',
+ baseColor: 0x6f665c,
+ roughness: 0.74,
+ metalness: 0.82,
+ textures: {
+ baseColor: {
+ kind: 'procedural',
+ spec: {
+ schemaVersion: 2,
+ usage: 'albedo',
+ layers: [{ op: 'noise', colorA: 0x403a34, colorB: 0x8a8176 }],
+ },
+ },
+ normal: { kind: 'resource', resourceId: 'kiln.texture.iron-normal.v1' },
+ },
+ });
+ expect(material.schemaVersion).toBe(2);
+ expect(material.textures.baseColor?.kind).toBe('procedural');
+ expect(material.textures.normal).toEqual({
+ kind: 'resource',
+ resourceId: 'kiln.texture.iron-normal.v1',
+ });
+ });
+
+ test('rejects slot/usage mismatch, executable references, and texture-count overflow', () => {
+ expect(() =>
+ canonicalizePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ textures: {
+ normal: {
+ kind: 'procedural',
+ spec: {
+ schemaVersion: 2,
+ usage: 'albedo',
+ layers: [{ op: 'solid', color: 0x8080ff }],
+ },
+ },
+ },
+ }),
+ ).toThrow(/normal.*usage.*normal/i);
+ expect(() =>
+ canonicalizePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ shader: 'fn main() {}',
+ }),
+ ).toThrow(/unknown key "shader"/i);
+ expect(MAX_PORTABLE_MATERIAL_TEXTURES).toBe(5);
+
+ const procedural = (usage: string) => ({
+ kind: 'procedural',
+ spec: {
+ schemaVersion: 2,
+ size: 1024,
+ usage,
+ layers: [{ op: 'solid', color: 0 }],
+ },
+ });
+ expect(() =>
+ canonicalizePortableMaterialSpecV2({
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ textures: {
+ baseColor: procedural('albedo'),
+ normal: procedural('normal'),
+ metallicRoughness: procedural('metallicRoughness'),
+ emissive: procedural('emissive'),
+ occlusion: procedural('occlusion'),
+ },
+ }),
+ ).toThrow(/texture budget/i);
+ });
+});
+
+test('errors remain the public authoring error type', () => {
+ expect(() => canonicalizeProceduralTextureSpecV2(null)).toThrow(ProceduralTextureError);
+});
diff --git a/src/__tests__/procedural-texture.test.ts b/src/__tests__/procedural-texture.test.ts
index 442e4f6c..59298ba6 100644
--- a/src/__tests__/procedural-texture.test.ts
+++ b/src/__tests__/procedural-texture.test.ts
@@ -231,10 +231,13 @@ describe('color space', () => {
layers: [{ op: 'solid', color: 0x404040 }],
});
expect((tex.userData as Record<string, unknown>)['kilnProcedural']).toEqual({
- schemaVersion: 1,
+ schemaVersion: 2,
size: 8,
usage: 'roughness',
- layers: [{ op: 'solid', color: 0x404040 }],
+ layers: [{ op: 'solid', color: 0x404040, blend: 'normal', opacity: 1 }],
+ canonicalJson:
+ '{"layers":[{"blend":"normal","color":4210752,"op":"solid","opacity":1}],"schemaVersion":2,"size":8,"usage":"roughness"}',
+ recipeHash: 'sha256:0ba0122424c854c14ff660e67a38fee4079a1d8da8cc2359b922d73453bfbce4',
});
});
});
diff --git a/src/__tests__/prompt.test.ts b/src/__tests__/prompt.test.ts
index 3af17c25..0304ba0e 100644
--- a/src/__tests__/prompt.test.ts
+++ b/src/__tests__/prompt.test.ts
@@ -54,7 +54,10 @@ describe('getSystemPrompt', () => {
expect(KILN_AUTHORING_STRATEGY).toContain('extrudeProfile');
expect(KILN_AUTHORING_STRATEGY).toContain('revolveProfile');
expect(KILN_AUTHORING_STRATEGY).toContain(
- 'proceduralTexture() creates deterministic image data',
+ 'proceduralTexture({ schemaVersion: 2, ... }) is the strict portable texture DSL',
+ );
+ expect(KILN_AUTHORING_STRATEGY).toContain(
+ 'no callbacks, shader source, URLs, filesystem paths',
);
expect(KILN_AUTHORING_STRATEGY).toContain('baked into the GLB');
expect(KILN_AUTHORING_STRATEGY).toContain('Do not replace a simple primitive');
diff --git a/src/__tests__/sandbox-three-bridge.test.ts b/src/__tests__/sandbox-three-bridge.test.ts
index fc79b96b..ce813ff5 100644
--- a/src/__tests__/sandbox-three-bridge.test.ts
+++ b/src/__tests__/sandbox-three-bridge.test.ts
@@ -65,23 +65,13 @@ test('sandbox new THREE.Mesh() with pbrMaterial+texture survives — texture ser
// Reproduces the textured-aircraft cycle issue: LLM does
// new THREE.Mesh(unwrappedGeo, pbrMaterial({ albedo: loadedTex }))
// and the resulting GLB needs to actually carry the texture.
- // Build a tiny in-memory PNG via sharp to avoid coupling to disk paths.
- const { default: sharp } = await import('sharp');
- const pngBytes = await sharp({
- create: { width: 16, height: 16, channels: 4, background: { r: 200, g: 80, b: 80, alpha: 1 } },
- })
- .png()
- .toBuffer();
- const tmpPath = `${process.cwd()}/.tmp-sandbox-three-bridge.png`;
- const fs = await import('node:fs');
- fs.writeFileSync(tmpPath, pngBytes);
-
- try {
- const code = `
+ // Use the closed approved-ID surface: raw paths are intentionally absent
+ // from new-generation globals.
+ const code = `
const meta = { name: 'sandbox-textured-mesh-test', category: 'prop' };
async function build() {
const root = createRoot('Root');
- const tex = await loadTexture(${JSON.stringify(tmpPath)});
+ const tex = await loadApprovedTexture('kiln.texture.bark-albedo.v1');
const mat = pbrMaterial({ albedo: tex, roughness: 0.85, metalness: 0 });
const geo = cylinderUnwrap(boxGeo(1, 1, 1));
const m = new THREE.Mesh(geo, mat);
@@ -90,18 +80,15 @@ async function build() {
return root;
}
`;
- const result = await renderGLB(code);
- expect(result.warnings).toEqual([]);
+ const result = await renderGLB(code);
+ expect(result.warnings).toEqual([]);
- const io = new NodeIO();
- const doc = await io.readBinary(result.glb);
- const root = doc.getRoot();
- // Texture carried through?
- expect(root.listTextures().length).toBeGreaterThan(0);
- // Material with base-color texture present?
- const matWithTex = root.listMaterials().find((m) => m.getBaseColorTexture());
- expect(matWithTex).toBeDefined();
- } finally {
- if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath);
- }
+ const io = new NodeIO();
+ const doc = await io.readBinary(result.glb);
+ const root = doc.getRoot();
+ // Texture carried through?
+ expect(root.listTextures().length).toBeGreaterThan(0);
+ // Material with base-color texture present?
+ const matWithTex = root.listMaterials().find((m) => m.getBaseColorTexture());
+ expect(matWithTex).toBeDefined();
});
diff --git a/src/__tests__/texture-bake.test.ts b/src/__tests__/texture-bake.test.ts
index 0ccc9ced..611a344a 100644
--- a/src/__tests__/texture-bake.test.ts
+++ b/src/__tests__/texture-bake.test.ts
@@ -10,7 +10,7 @@
import { describe, expect, test } from 'bun:test';
import * as THREE from 'three';
-import { renderSceneToGLB } from '../render';
+import { renderGLB, renderSceneToGLB } from '../render';
import { bakeSceneTextures, ensureNormalMapTangents } from '../texture-bake';
// -----------------------------------------------------------------------------
@@ -71,6 +71,41 @@ const glbText = (bytes: Uint8Array): string => Buffer.from(bytes).toString('lati
// -----------------------------------------------------------------------------
describe('procedural textures are baked into the GLB', () => {
+ test('public renderGLB preserves baked procedural lineage instead of dropping the sidecar', async () => {
+ const out = await renderGLB(`
+const meta = { name: 'PublicLineage', category: 'prop' };
+async function build() {
+ const root = createRoot('PublicLineage');
+ const albedo = proceduralTexture({
+ size: 8,
+ name: 'AuthoredChecker',
+ layers: [
+ { op: 'solid', color: 0x224466 },
+ { op: 'checker', colorA: 0xffffff, colorB: 0x000000, squares: 2, blend: 'overlay' },
+ ],
+ });
+ root.add(createPart('Body', boxGeo(1, 1, 1), pbrMaterial({ albedo }), {}));
+ return root;
+}
+`);
+
+ expect(out.bakedTextures).toHaveLength(1);
+ expect(out.bakedTextures?.[0]).toMatchObject({
+ schemaVersion: 1,
+ texture: 'AuthoredChecker',
+ node: 'Mesh_Body',
+ slot: 'map',
+ usage: 'albedo',
+ mime: 'image/png',
+ colorSpace: 'srgb',
+ procedural: { schemaVersion: 2, size: 8, usage: 'albedo' },
+ });
+ expect(out.bakedTextures?.[0]?.procedural?.recipeHash).toMatch(/^sha256:[0-9a-f]{64}$/);
+ expect(out.bakedTextures?.[0]?.imageSha256).toMatch(/^sha256:[0-9a-f]{64}$/);
+ expect(out.artifactGlbSha256).toMatch(/^sha256:[0-9a-f]{64}$/);
+ expect(out.bakedTextures?.[0]?.artifactGlbSha256).toBe(out.artifactGlbSha256);
+ });
+
test('a hand-built DataTexture is encoded, embedded, and reported — not dropped', async () => {
const mat = stdMaterial('ProcMat');
mat.map = albedoTexture('ProcChecker');
@@ -98,6 +133,8 @@ describe('procedural textures are baked into the GLB', () => {
});
expect(rec!.bytes).toBeGreaterThan(0);
expect(rec!.sha1).toMatch(/^[0-9a-f]{40}$/);
+ expect(rec!.imageSha256).toMatch(/^sha256:[0-9a-f]{64}$/);
+ expect(rec!.artifactGlbSha256).toBe(out.artifactGlbSha256);
});
test('three-channel RGB pixels bake as well as RGBA', async () => {
@@ -143,6 +180,33 @@ describe('procedural textures are baked into the GLB', () => {
['roughnessMap', 'roughness'],
]);
});
+
+ test('shared textures retain every node/material/slot binding while encoding once', async () => {
+ const shared = albedoTexture('SharedSurface');
+ const first = stdMaterial('FirstMaterial');
+ first.map = shared;
+ const second = stdMaterial('SecondMaterial');
+ second.map = shared;
+ const root = new THREE.Group();
+ root.name = 'Root';
+ root.add(
+ new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), first),
+ new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), second),
+ );
+ root.children[0]!.name = 'FirstNode';
+ root.children[1]!.name = 'SecondNode';
+
+ const warnings: string[] = [];
+ const baked = await bakeSceneTextures(root, warnings);
+
+ expect(warnings).toEqual([]);
+ expect(baked).toHaveLength(1);
+ expect(baked[0]?.bindings.map(({ node, material, slot }) => [node, material, slot])).toEqual([
+ ['FirstNode', 'FirstMaterial', 'map'],
+ ['SecondNode', 'SecondMaterial', 'map'],
+ ]);
+ expect(baked[0]?.imageSha256).toMatch(/^sha256:[0-9a-f]{64}$/);
+ });
});
// -----------------------------------------------------------------------------
diff --git a/src/__tests__/texture-resolver-boundary.test.ts b/src/__tests__/texture-resolver-boundary.test.ts
new file mode 100644
index 00000000..a5139cc8
--- /dev/null
+++ b/src/__tests__/texture-resolver-boundary.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, test } from 'bun:test';
+import type * as THREE from 'three';
+
+import { listPrimitives } from '../list-primitives';
+import {
+ APPROVED_TEXTURE_RESOURCES_V1,
+ type ApprovedTextureResourceDescriptorV1,
+ type ApprovedTextureResourceId,
+} from '../material-recipes';
+import { ApprovedTextureResourceCache } from '../material-resources';
+import { createTextureResolver } from '../texture-resolver';
+import { buildSandboxGlobals } from '../primitives';
+import { executeKilnCode } from '../render';
+
+const SUBJECT: ApprovedTextureResourceId = 'kiln.texture.bark-albedo.v1';
+const runtimeRegistry: Readonly<
+ Record<ApprovedTextureResourceId, ApprovedTextureResourceDescriptorV1>
+> = Object.freeze({
+ ...APPROVED_TEXTURE_RESOURCES_V1,
+ [SUBJECT]: Object.freeze({
+ ...APPROVED_TEXTURE_RESOURCES_V1[SUBJECT],
+ delivery: 'runtime',
+ } satisfies ApprovedTextureResourceDescriptorV1),
+});
+
+function goodBytes(): Uint8Array {
+ return new ApprovedTextureResourceCache().resolve(SUBJECT).bytes;
+}
+
+function firstTextureMetadata(root: THREE.Object3D): Record<string, unknown> | undefined {
+ const child = root.children[0];
+ if (!(child as { isMesh?: boolean } | undefined)?.isMesh) {
+ throw new TypeError('expected first generated child to be a mesh');
+ }
+ const material = (child as THREE.Mesh).material;
+ if (Array.isArray(material)) throw new TypeError('expected one generated material');
+ return (material as THREE.MeshStandardMaterial).map?.userData as
+ | Record<string, unknown>
+ | undefined;
+}
+
+describe('H6 generated texture boundary', () => {
+ test('raw loadTexture is absent while the one-argument approved-ID loader is present', () => {
+ const globals = buildSandboxGlobals();
+ expect(globals['loadTexture']).toBeUndefined();
+ expect(typeof globals['loadApprovedTexture']).toBe('function');
+ expect(listPrimitives().some(({ name }) => name === 'loadTexture')).toBe(false);
+ expect(listPrimitives().some(({ name }) => name === 'loadApprovedTexture')).toBe(true);
+ });
+
+ test.each([
+ './relative.png',
+ '/absolute/texture.png',
+ 'C:\\absolute\\texture.png',
+ '../traversal.png',
+ 'https://textures.example/asset.png',
+ 'kiln.texture.not-approved.v1',
+ ])('rejects non-approved generated source %s before any host resolver call', async (source) => {
+ let calls = 0;
+ const cache = new ApprovedTextureResourceCache({
+ registry: runtimeRegistry,
+ resolver: async () => {
+ calls += 1;
+ return { bytes: goodBytes(), mime: 'image/png' };
+ },
+ });
+ const resolver = createTextureResolver(cache);
+ await expect(resolver.loadApprovedTexture(source)).rejects.toThrow(
+ /approved texture resource ID/i,
+ );
+ expect(calls).toBe(0);
+ });
+
+ test('generated code cannot pass bytes, hashes, resolver objects, or a second options argument', async () => {
+ const globals = buildSandboxGlobals();
+ const loader = globals['loadApprovedTexture'] as (...args: unknown[]) => Promise<unknown>;
+ await expect(loader(new Uint8Array([137, 80, 78, 71]))).rejects.toThrow(
+ /exactly one approved resource ID/,
+ );
+ await expect(loader({ resourceId: SUBJECT, sha256: 'forged' })).rejects.toThrow(
+ /exactly one approved resource ID/,
+ );
+ await expect(loader(SUBJECT, { resolver: {}, path: './secret.png' })).rejects.toThrow(
+ /exactly one approved resource ID/,
+ );
+ const recipe = globals['materialRecipe'] as (...args: unknown[]) => Promise<unknown>;
+ await expect(
+ recipe('kiln.material.wood.v1', {}, { resolver: {}, hash: 'forged' }),
+ ).rejects.toThrow(/approved recipe ID and optional bounded overrides/);
+ });
+
+ test('approved embedded IDs work in generated code without exposing resolver internals', async () => {
+ const executed = await executeKilnCode(`
+ const meta = { name: 'approved-texture', category: 'prop' };
+ async function build() {
+ const root = createRoot('Root');
+ const albedo = await loadApprovedTexture('${SUBJECT}');
+ root.add(new THREE.Mesh(boxUnwrap(boxGeo(1, 1, 1)), pbrMaterial({ albedo })));
+ return root;
+ }
+ `);
+ expect(firstTextureMetadata(executed.root)?.['kilnTexture']).toMatchObject({
+ usage: 'albedo',
+ approvedResource: { resourceId: SUBJECT },
+ });
+ });
+
+ test('bounded host bytes work only through an injected resolver bound to an approved ID', async () => {
+ const cache = new ApprovedTextureResourceCache({
+ registry: runtimeRegistry,
+ resolver: async (descriptor, context) => {
+ expect(descriptor.id).toBe(SUBJECT);
+ expect(context.signal).toBeInstanceOf(AbortSignal);
+ expect(context.deadlineMs).toBeGreaterThan(0);
+ return { bytes: goodBytes(), mime: 'image/png' };
+ },
+ });
+ const executed = await executeKilnCode(
+ `
+ const meta = { name: 'host-texture', category: 'prop' };
+ async function build() {
+ const root = createRoot('Root');
+ const albedo = await loadApprovedTexture('${SUBJECT}');
+ root.add(new THREE.Mesh(boxUnwrap(boxGeo(1, 1, 1)), pbrMaterial({ albedo })));
+ return root;
+ }
+ `,
+ { textureResolver: createTextureResolver(cache) },
+ );
+ expect(firstTextureMetadata(executed.root)?.['kilnTexture']).toMatchObject({
+ approvedResource: { resourceId: SUBJECT, delivery: 'runtime' },
+ });
+ });
+
+ test('historical raw generated programs fail instead of reading a relative path', async () => {
+ await expect(
+ executeKilnCode(`
+ const meta = { name: 'legacy-path', category: 'prop' };
+ async function build() {
+ await loadTexture('./should-never-be-read.png');
+ return createRoot('Root');
+ }
+ `),
+ ).rejects.toThrow(/loadTexture is not defined/);
+ });
+});
diff --git a/src/agent/generate.test.ts b/src/agent/generate.test.ts
index 17206c90..3dc79352 100644
--- a/src/agent/generate.test.ts
+++ b/src/agent/generate.test.ts
@@ -7,7 +7,7 @@
* program, which renderGLB renders to actual GLB bytes. The live e2e
* (`pixelforge gen glb`) covers the LLM half.
*/
-import { test, expect, describe, mock, beforeAll, afterAll } from 'bun:test';
+import { test, expect, describe, mock, beforeAll, afterAll, spyOn } from 'bun:test';
import { createAssetIntentV1 } from '../contracts';
// A real, minimal, valid Kiln program (mirrors render-edges.test.ts). renderGLB
@@ -24,6 +24,19 @@ const FALSE_PROP_CODE = CANNED_CODE.replace(
"const meta = { name: 'TestBox' };",
"const meta = { name: 'TestBox', category: 'prop' };",
);
+const PROCEDURAL_CODE = `
+const meta = { name: 'TexturedBox', category: 'prop' };
+function build() {
+ const root = createRoot('TexturedBox');
+ const albedo = proceduralTexture({
+ size: 8,
+ name: 'GeneratedSurface',
+ layers: [{ op: 'checker', colorA: 0xffffff, colorB: 0x222222, squares: 2 }],
+ });
+ root.add(createPart('Body', boxGeo(1, 1, 1), pbrMaterial({ albedo }), {}));
+ return root;
+}
+`;
// Capture the REAL './run' exports BEFORE mocking. bun's mock.module patches the
// module (and any already-imported namespace) in place, but plain function
@@ -106,6 +119,21 @@ describe('generateKilnAsset', () => {
expect(captured?.['category']).toBe('prop');
});
+ test('preserves baked procedural texture lineage on the public generation result', async () => {
+ runImpl = async () => ({ code: PROCEDURAL_CODE, toolCalls: ['kiln_finalize'], steps: 1 });
+
+ const r = await generateKilnAsset({ prompt: 'a textured box' });
+
+ expect(r.bakedTextures).toHaveLength(1);
+ expect(r.bakedTextures?.[0]).toMatchObject({
+ texture: 'GeneratedSurface',
+ slot: 'map',
+ procedural: { schemaVersion: 2 },
+ });
+ expect(r.artifactGlbSha256).toMatch(/^sha256:[0-9a-f]{64}$/);
+ expect(r.bakedTextures?.[0]?.artifactGlbSha256).toBe(r.artifactGlbSha256);
+ });
+
test('threads an explicit model + refine fields', async () => {
let captured: Record<string, unknown> | undefined;
runImpl = async (opts) => {
@@ -242,19 +270,63 @@ describe('generateKilnAsset viewRenderPort (B3b/B4)', () => {
});
}
- test('option absent: views are byte-identical to the CPU grid, no degrade fields', async () => {
+ test('option absent: CPU grid comes from exact final bytes and fidelity is explicitly geometry-only', async () => {
runImpl = okRun;
const r = await generateKilnAsset({ prompt: 'a crate', captureViews: true });
- const { renderCodeViewGrid } = await import('../views');
- const cpu = (await renderCodeViewGrid(CANNED_CODE)).png;
+ const { renderGlbViewGrid } = await import('../views');
+ const cpu = (await renderGlbViewGrid(r.glb)).png;
expect(r.views).toBeInstanceOf(Buffer);
expect(Buffer.compare(r.views!, cpu)).toBe(0);
- // Pin: the port-absent result shape is unchanged — no provenance/degrade keys.
+ // Legacy port-specific fields remain absent; the additive fidelity contract
+ // now tells callers the image is not suitable for material acceptance.
expect(r.viewsRendererId).toBeUndefined();
expect(r.renderDegraded).toBeUndefined();
expect(r.renderDegradedReason).toBeUndefined();
expect('renderDegraded' in r).toBe(false);
+ expect(r.viewsFidelity).toMatchObject({
+ version: 'kiln.view-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ exactArtifact: true,
+ degraded: true,
+ degradeReason: 'material-faithful view render port unavailable',
+ reasonCodes: ['FULL_MATERIAL_RENDER_UNAVAILABLE'],
+ });
+ expect(r.viewsFidelity?.inputGlbSha256).toBe(r.artifactGlbSha256);
+ });
+
+ test('R2.11: final CPU fallback does not execute authored source a second time', async () => {
+ const countedCode = CANNED_CODE.replace(
+ 'boxGeo(1, 1, 1)',
+ 'boxGeo(0.5 + Math.clz32(1) * 0, 1, 1)',
+ );
+ runImpl = async () => ({ code: countedCode, toolCalls: ['kiln_submit'], steps: 1 });
+ const sourceExecutionSpy = spyOn(Math, 'clz32');
+ try {
+ const result = await generateKilnAsset({ prompt: 'a crate', captureViews: true });
+ expect(result.views).toBeInstanceOf(Buffer);
+ expect(sourceExecutionSpy).toHaveBeenCalledTimes(1);
+ expect(result.viewsFidelity?.exactArtifact).toBe(true);
+ expect(result.viewsFidelity?.inputGlbSha256).toBe(result.artifactGlbSha256);
+ } finally {
+ sourceExecutionSpy.mockRestore();
+ }
+ });
+
+ test('R2.11: textured exact-byte fallback reports its unsupported sampling code', async () => {
+ runImpl = async () => ({ code: PROCEDURAL_CODE, toolCalls: ['kiln_submit'], steps: 1 });
+ const result = await generateKilnAsset({ prompt: 'a textured crate', captureViews: true });
+
+ expect(result.views).toBeInstanceOf(Buffer);
+ expect(result.viewsFidelity).toMatchObject({
+ delivered: 'geometry-flat',
+ exactArtifact: true,
+ materialFaithful: false,
+ inputGlbSha256: result.artifactGlbSha256,
+ reasonCodes: ['FULL_MATERIAL_RENDER_UNAVAILABLE', 'GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED'],
+ });
});
test('port success: composited port views, port rendererId, renderDegraded false', async () => {
@@ -279,6 +351,13 @@ describe('generateKilnAsset viewRenderPort (B3b/B4)', () => {
expect(r.renderDegraded).toBe(false);
expect(r.renderDegradedReason).toBeUndefined();
expect(r.viewsRendererId).toBe('dawn-vulkan:test-gpu:1.0');
+ expect(r.viewsFidelity).toMatchObject({
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: true,
+ rendererId: 'dawn-vulkan:test-gpu:1.0',
+ degraded: false,
+ });
// The views are the port cells composited into the SAME 3x2 grid layout,
// and stamped with the same cell labels + gnomon the CPU path applies.
const { compositeViewPngGrid, SIX_VIEWS } = await import('../views');
@@ -312,12 +391,20 @@ describe('generateKilnAsset viewRenderPort (B3b/B4)', () => {
},
});
- const { renderCodeViewGrid, CPU_RASTER_RENDERER_ID } = await import('../views');
+ const { renderGlbViewGrid, CPU_RASTER_RENDERER_ID } = await import('../views');
expect(r.renderDegraded).toBe(true);
expect(r.renderDegradedReason).toContain('GPU service unreachable');
expect(r.viewsRendererId).toBe(CPU_RASTER_RENDERER_ID);
expect(r.viewsRendererId).toMatch(/^cpu-raster:/);
- const cpu = (await renderCodeViewGrid(CANNED_CODE)).png;
+ expect(r.viewsFidelity).toMatchObject({
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ exactArtifact: true,
+ degraded: true,
+ });
+ expect(r.viewsFidelity?.degradeReason).toContain('GPU service unreachable');
+ expect(r.viewsFidelity?.inputGlbSha256).toBe(r.artifactGlbSha256);
+ const cpu = (await renderGlbViewGrid(r.glb)).png;
expect(Buffer.compare(r.views!, cpu)).toBe(0);
});
@@ -352,6 +439,28 @@ describe('generateKilnAsset viewRenderPort (B3b/B4)', () => {
expect(r.views).toBeInstanceOf(Buffer);
});
+ test('R2.7: final view timeout consumes dynamic warm-up and generation budget context', async () => {
+ runImpl = okRun;
+ const requests: string[] = [];
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ viewRenderPort: () => new Promise(() => {}),
+ viewRenderTimeoutContext: () => ({
+ warmUpState: 'pending',
+ remainingGenerationBudgetMs: 17,
+ rendererDeadlineMs: 30,
+ }),
+ viewRenderTimeoutResolver: (context) => {
+ requests.push(context.requestKind);
+ return 1_000;
+ },
+ });
+ expect(r.renderDegraded).toBe(true);
+ expect(r.renderDegradedReason).toContain('timed out after 17ms');
+ expect(requests).toEqual(['final-grid']);
+ });
+
test('B4: undecodable or missing port PNGs degrade instead of throwing', async () => {
runImpl = okRun;
const garbage = await generateKilnAsset({
@@ -521,8 +630,8 @@ describe('generateKilnAsset viewRenderPort (B3b/B4)', () => {
// The whole point: a GPU outage must not reshape the artifact. The degraded
// sheet is exactly what the CPU path produces for the same request.
- const { renderCodeViewGrid } = await import('../views');
- const cpu = await renderCodeViewGrid(CANNED_CODE, { capture });
+ const { renderGlbViewGrid } = await import('../views');
+ const cpu = await renderGlbViewGrid(degraded.glb, { capture });
expect(Buffer.compare(degraded.views!, cpu.png)).toBe(0);
});
@@ -545,10 +654,8 @@ describe('generateKilnAsset viewRenderPort (B3b/B4)', () => {
expect(portCalls).toBe(0);
expect(r.renderDegraded).toBe(true);
expect(r.renderDegradedReason).toContain('zoom is not supported');
- const { renderCodeViewGrid } = await import('../views');
- expect(Buffer.compare(r.views!, (await renderCodeViewGrid(CANNED_CODE, { capture })).png)).toBe(
- 0,
- );
+ const { renderGlbViewGrid } = await import('../views');
+ expect(Buffer.compare(r.views!, (await renderGlbViewGrid(r.glb, { capture })).png)).toBe(0);
});
test('T3.3: an invalid capture warns and falls back — it never fails the run', async () => {
diff --git a/src/agent/generate.ts b/src/agent/generate.ts
index 415b3f81..05a9d5b6 100644
--- a/src/agent/generate.ts
+++ b/src/agent/generate.ts
@@ -15,7 +15,7 @@
* `@strands-agents/sdk` dependency never enters the browser/editor bundle graph.
*/
import { renderGLB, type KilnCodeMeta, type RenderResult } from '../render';
-import type { PbrRenderPort } from '../composer/render-port';
+import type { PbrRenderPort, ViewFidelityV1 } from '../composer/render-port';
import {
CaptureConfigError,
resolveGridCapture,
@@ -24,6 +24,7 @@ import {
type ResolvedCapture,
} from '../views/capture';
import { compositeViewPngGrid } from '../views/grid';
+import { decodePng } from '../views/png';
import type { AssetStyle } from '../prompt';
import { createAssetIntentV1, type AssetCategory, type AssetIntentV1 } from '../contracts';
import { runKilnAgent, type RefineMode, type KilnKnowhow, type KilnInputImage } from './run';
@@ -35,6 +36,11 @@ import {
} from './providers';
import type { EditRecord } from './tools';
import type { AgentUsage } from './hooks';
+import {
+ resolveViewRenderTimeoutMs,
+ type ViewRenderTimeoutContextProvider,
+ type ViewRenderTimeoutResolver,
+} from './view-render-timeout';
/**
* The hardcoded default Kiln agent model — the verified standout for GLB codegen.
@@ -86,6 +92,10 @@ export interface GenerateKilnAssetOptions {
viewRenderPort?: PbrRenderPort;
/** Deadline for one `viewRenderPort` call in ms. Default 8000. */
viewRenderTimeoutMs?: number;
+ /** Dynamic host warm-up/deadline/budget state, sampled for the final request. */
+ viewRenderTimeoutContext?: ViewRenderTimeoutContextProvider;
+ /** Host policy for deriving the final request deadline from that state. */
+ viewRenderTimeoutResolver?: ViewRenderTimeoutResolver;
/** Style anchor: a complete Kiln program rendered as "## Reference Asset" for
* FRESH generation (ignored on refine). ~5-15k input tokens/run, mostly
* absorbed by prompt caching when reused across a batch. */
@@ -99,6 +109,8 @@ export interface GenerateKilnAssetResult {
code: string;
/** Rendered GLB, ready to write to disk. */
glb: Buffer;
+ /** SHA-256 identity of the exact returned GLB bytes. */
+ artifactGlbSha256: `sha256:${string}`;
/** Extracted from the code's `const meta = {...}` block, plus `tris` + `primitiveUsage`. */
meta: KilnCodeMeta;
/** Non-fatal issues (structural warnings, animation target missing). */
@@ -136,10 +148,13 @@ export interface GenerateKilnAssetResult {
renderDegraded?: boolean;
/** Why the port was bypassed (rejection, ok:false, timeout, bad PNGs). */
renderDegradedReason?: string;
+ /** Material fidelity and exact-byte relationship of the final view sheet. */
+ viewsFidelity?: ViewFidelityV1;
/** Automatic trusted character skeleton/motion captures, when applicable. */
diagnosticViews?: NonNullable<RenderResult['diagnosticViews']>;
materialRecipeApplications?: NonNullable<RenderResult['materialRecipeApplications']>;
materialResourceProvenance?: NonNullable<RenderResult['materialResourceProvenance']>;
+ bakedTextures?: NonNullable<RenderResult['bakedTextures']>;
materialMetrics?: NonNullable<RenderResult['materialMetrics']>;
integrationManifest: RenderResult['integrationManifest'];
}
@@ -210,6 +225,13 @@ export async function generateKilnCodeAgent(opts: {
export const DEFAULT_VIEW_RENDER_TIMEOUT_MS = 8000;
+async function sha256Bytes(bytes: Uint8Array): Promise<`sha256:${string}`> {
+ const input = new Uint8Array(bytes.byteLength);
+ input.set(bytes);
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', input));
+ return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
+}
+
export type PortViewsOutcome =
| {
ok: true;
@@ -224,6 +246,91 @@ export type PortViewsOutcome =
}
| { ok: false; reason: string };
+export type PortViewPngsOutcome =
+ | {
+ ok: true;
+ pngs: Uint8Array[];
+ rendererId: string;
+ derivativeFidelityAttested: boolean;
+ inputGlbSha256?: `sha256:${string}`;
+ }
+ | { ok: false; reason: string };
+
+/**
+ * Lowest-level owner of the PBR-port deadline and reply validation. It accepts
+ * exact GLB bytes plus explicit view directions and returns unmodified square
+ * PNG cells. Contact sheets and derivative review surfaces both build on this
+ * function so timeout/error/shape policy cannot drift between them.
+ */
+export async function captureViewPngsViaPort(
+ port: PbrRenderPort,
+ glb: Buffer | Uint8Array,
+ timeoutMs: number,
+ viewDirs: readonly [number, number, number][],
+ size: number,
+): Promise<PortViewPngsOutcome> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const requestGlb = Uint8Array.from(glb);
+ const inputGlbSha256 = await sha256Bytes(requestGlb);
+ const deadline = new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(`view render port timed out after ${timeoutMs}ms`)),
+ timeoutMs,
+ );
+ });
+ const result = await Promise.race([
+ port({
+ glb: requestGlb,
+ viewDirs: viewDirs.map((dir) => [...dir] as [number, number, number]),
+ size,
+ }),
+ deadline,
+ ]);
+ if (!result?.ok) {
+ return { ok: false, reason: result?.error ?? 'view render port returned ok: false' };
+ }
+ if (typeof result.rendererId !== 'string' || !result.rendererId.trim()) {
+ return { ok: false, reason: 'view render port returned no rendererId' };
+ }
+ if (!result.viewsPng || result.viewsPng.length !== viewDirs.length) {
+ return {
+ ok: false,
+ reason: `view render port returned ${result.viewsPng?.length ?? 0} view PNGs, expected ${viewDirs.length}`,
+ };
+ }
+ if (result.derivativeFidelity && result.derivativeFidelity.inputGlbSha256 !== inputGlbSha256) {
+ return {
+ ok: false,
+ reason: `view render port derivative receipt hash mismatch (${result.derivativeFidelity.inputGlbSha256} != ${inputGlbSha256})`,
+ };
+ }
+ // Decode here even though callers may decode again for annotation. This is
+ // the transport trust boundary: an ok:true reply with malformed/non-square
+ // pixels is a degrade, never a successful material attestation.
+ for (const png of result.viewsPng) {
+ const decoded = decodePng(png);
+ if (decoded.width !== decoded.height) {
+ return {
+ ok: false,
+ reason: `view render port returned non-square ${decoded.width}x${decoded.height} PNG`,
+ };
+ }
+ }
+ return {
+ ok: true,
+ pngs: result.viewsPng.map((png) => Uint8Array.from(png)),
+ rendererId: result.rendererId,
+ derivativeFidelityAttested: result.derivativeFidelity?.materialFaithful === true,
+ ...(result.derivativeFidelity ? { inputGlbSha256 } : {}),
+ };
+ } catch (err) {
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+}
+
/**
* Call the host view-render port with the ALREADY-PRODUCED GLB bytes and
* composite its per-view PNGs into the same grid the CPU path emits.
@@ -270,46 +377,22 @@ export async function captureViewsViaPort(
};
}
- let timer: ReturnType<typeof setTimeout> | undefined;
+ const result = await captureViewPngsViaPort(
+ port,
+ glb,
+ timeoutMs,
+ views.map((view) => view.dir),
+ 384,
+ );
+ if (!result.ok) return result;
try {
- const deadline = new Promise<never>((_, reject) => {
- timer = setTimeout(
- () => reject(new Error(`view render port timed out after ${timeoutMs}ms`)),
- timeoutMs,
- );
- });
- const result = await Promise.race([
- port({
- // Copy, not alias: a buggy port implementation must not be able to
- // mutate the render.glb bytes returned as the generation artifact.
- glb: Uint8Array.from(glb),
- viewDirs: views.map((v) => [...v.dir] as [number, number, number]),
- size: 384,
- }),
- deadline,
- ]);
- if (!result?.ok) {
- return { ok: false, reason: result?.error ?? 'view render port returned ok: false' };
- }
- if (typeof result.rendererId !== 'string' || !result.rendererId.trim()) {
- return { ok: false, reason: 'view render port returned no rendererId' };
- }
- // Count must equal the cells that were REQUESTED — not a hardcoded six.
- // A host that truncates or pads the view list produces a differently-shaped
- // sheet than the caller asked for, which is a degrade, not a success.
- if (!result.viewsPng || result.viewsPng.length !== views.length) {
- return {
- ok: false,
- reason: `view render port returned ${result.viewsPng?.length ?? 0} view PNGs, expected ${views.length}`,
- };
- }
// Annotated with the SAME cell labels + gnomon the CPU path stamps. A host
// returns pixels and knows nothing of the Kiln camera vocabulary, so
// without this the GPU sheet arrives unlabelled and the model quietly loses
// its orientation cues on the one path that cannot tell it happened.
// Degrade stays reportable through `renderDegraded` / `viewsRendererId`,
// which is a structured field rather than a visual tell.
- const grid = compositeViewPngGrid(result.viewsPng, resolved.cols, views);
+ const grid = compositeViewPngGrid(result.pngs, resolved.cols, views);
return {
ok: true,
png: grid.png,
@@ -320,8 +403,6 @@ export async function captureViewsViaPort(
};
} catch (err) {
return { ok: false, reason: err instanceof Error ? err.message : String(err) };
- } finally {
- if (timer !== undefined) clearTimeout(timer);
}
}
@@ -376,8 +457,10 @@ export async function generateKilnAsset(
let viewsRendererId: string | undefined;
let renderDegraded: boolean | undefined;
let renderDegradedReason: string | undefined;
+ let viewsFidelity: ViewFidelityV1 | undefined;
const captureWarnings: string[] = [];
if (opts.captureViews) {
+ const inputGlbSha256 = await sha256Bytes(render.glb);
// T3.3: validate the requested layout ONCE, up front. A malformed config is
// a caller bug, not a render hazard, so it must not reach two producers and
// be reported differently by each. It also must not fail the run: the views
@@ -403,7 +486,17 @@ export async function generateKilnAsset(
const port = await captureViewsViaPort(
opts.viewRenderPort,
render.glb,
- opts.viewRenderTimeoutMs ?? DEFAULT_VIEW_RENDER_TIMEOUT_MS,
+ resolveViewRenderTimeoutMs({
+ requestKind: 'final-grid',
+ defaultTimeoutMs: DEFAULT_VIEW_RENDER_TIMEOUT_MS,
+ ...(opts.viewRenderTimeoutMs !== undefined
+ ? { timeoutMs: opts.viewRenderTimeoutMs }
+ : {}),
+ ...(opts.viewRenderTimeoutContext
+ ? { contextProvider: opts.viewRenderTimeoutContext }
+ : {}),
+ ...(opts.viewRenderTimeoutResolver ? { resolver: opts.viewRenderTimeoutResolver } : {}),
+ }),
capture,
);
if (port.ok) {
@@ -411,6 +504,16 @@ export async function generateKilnAsset(
viewsCapture = port.capture;
viewsRendererId = port.rendererId;
renderDegraded = false;
+ viewsFidelity = {
+ version: 'kiln.view-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: true,
+ rendererId: port.rendererId,
+ inputGlbSha256,
+ degraded: false,
+ };
} else {
renderDegraded = true;
renderDegradedReason = port.reason;
@@ -421,18 +524,60 @@ export async function generateKilnAsset(
// Keep the renderer id on this same lazy entrypoint. renderer-id.ts reads
// package metadata at module initialization; an eager import changes the
// production agent boot graph even when no CPU fallback is needed.
- const { renderCodeViewGrid, CPU_RASTER_RENDERER_ID } = await import('../views');
+ const { renderGlbViewGrid, CPU_RASTER_RENDERER_ID } = await import('../views');
// The degrade path must reproduce the SAME layout the port was asked
// for, or a GPU outage silently reshapes the artifact.
- const grid = await renderCodeViewGrid(agent.code, capture ? { capture } : {});
+ // R2.11: parse the exact final artifact. Generated source has already
+ // been executed once to produce render.glb and is never run again here.
+ const grid = await renderGlbViewGrid(render.glb, capture ? { capture } : {});
+ if (grid.inputGlbSha256 !== inputGlbSha256) {
+ throw new Error(
+ `GLB-native fallback hash mismatch (${grid.inputGlbSha256} != ${inputGlbSha256})`,
+ );
+ }
views = grid.png;
viewsCapture = grid.capture;
// Honest producer provenance, but only on the port-enabled path — the
// port-absent path stays byte-identical to the historical result shape.
if (opts.viewRenderPort) viewsRendererId = CPU_RASTER_RENDERER_ID;
- } catch {
+ const degradeReason =
+ renderDegradedReason ?? 'material-faithful view render port unavailable';
+ viewsFidelity = {
+ version: 'kiln.view-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ exactArtifact: true,
+ rendererId: CPU_RASTER_RENDERER_ID,
+ inputGlbSha256: grid.inputGlbSha256,
+ degraded: true,
+ degradeReason,
+ reasonCodes: ['FULL_MATERIAL_RENDER_UNAVAILABLE', ...grid.reasonCodes],
+ };
+ } catch (error) {
views = undefined;
viewsCapture = undefined;
+ const reasonCode =
+ error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
+ ? error.code
+ : undefined;
+ viewsFidelity = {
+ version: 'kiln.view-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'none',
+ materialFaithful: false,
+ exactArtifact: false,
+ rendererId: 'none',
+ inputGlbSha256,
+ degraded: true,
+ degradeReason:
+ renderDegradedReason ??
+ `material-faithful and geometry fallback renders unavailable${error instanceof Error ? `: ${error.message}` : ''}`,
+ reasonCodes: [
+ 'FULL_MATERIAL_RENDER_UNAVAILABLE',
+ ...(reasonCode ? [reasonCode] : []),
+ ] as ViewFidelityV1['reasonCodes'],
+ };
}
}
}
@@ -449,6 +594,7 @@ export async function generateKilnAsset(
return {
code: agent.code,
glb: render.glb,
+ artifactGlbSha256: render.artifactGlbSha256,
meta: render.meta,
warnings,
toolCalls: agent.toolCalls,
@@ -465,6 +611,7 @@ export async function generateKilnAsset(
...(viewsRendererId ? { viewsRendererId } : {}),
...(renderDegraded !== undefined ? { renderDegraded } : {}),
...(renderDegradedReason ? { renderDegradedReason } : {}),
+ ...(viewsFidelity ? { viewsFidelity } : {}),
...(render.diagnosticViews ? { diagnosticViews: render.diagnosticViews } : {}),
...(render.materialRecipeApplications
? { materialRecipeApplications: render.materialRecipeApplications }
@@ -472,6 +619,7 @@ export async function generateKilnAsset(
...(render.materialResourceProvenance
? { materialResourceProvenance: render.materialResourceProvenance }
: {}),
+ ...(render.bakedTextures ? { bakedTextures: render.bakedTextures } : {}),
...(render.materialMetrics ? { materialMetrics: render.materialMetrics } : {}),
integrationManifest: render.integrationManifest,
};
diff --git a/src/agent/index.ts b/src/agent/index.ts
index 73560d7f..263dc99a 100644
--- a/src/agent/index.ts
+++ b/src/agent/index.ts
@@ -132,3 +132,18 @@ export type {
GenerationCallBudgetReceipt,
GenerationModelCallRole,
} from './call-budget';
+
+export {
+ resolveViewRenderTimeoutMs,
+ MIN_VIEW_RENDER_TIMEOUT_MS,
+ MAX_VIEW_RENDER_TIMEOUT_MS,
+} from './view-render-timeout';
+export type {
+ ResolveViewRenderTimeoutInput,
+ ViewRenderRequestKind,
+ ViewRenderTimeoutContextProvider,
+ ViewRenderTimeoutHostContext,
+ ViewRenderTimeoutResolver,
+ ViewRenderTimeoutResolverContext,
+ ViewRenderWarmUpState,
+} from './view-render-timeout';
diff --git a/src/agent/run-surface.test.ts b/src/agent/run-surface.test.ts
index 2a56ea92..e2d6252b 100644
--- a/src/agent/run-surface.test.ts
+++ b/src/agent/run-surface.test.ts
@@ -104,6 +104,7 @@ describe('buildAgentTools', () => {
test('threads the host render port, its short deadline, and tally callback into unified kiln_render', async () => {
const events: InLoopViewRender[] = [];
+ const timeoutRequests: string[] = [];
let portCalls = 0;
const context: KilnToolContext = {
viewRenderPort: () => {
@@ -111,6 +112,15 @@ describe('buildAgentTools', () => {
return new Promise(() => {});
},
viewRenderTimeoutMs: 5,
+ viewRenderTimeoutContext: () => ({
+ warmUpState: 'pending',
+ remainingGenerationBudgetMs: 9,
+ rendererDeadlineMs: 8,
+ }),
+ viewRenderTimeoutResolver: (request) => {
+ timeoutRequests.push(request.requestKind);
+ return 7;
+ },
onViewsRendered: (event) => events.push(event),
};
const tools = buildAgentTools('unified', context, freshSinks());
@@ -120,10 +130,11 @@ describe('buildAgentTools', () => {
expect(Array.isArray(rendered)).toBe(true);
expect(portCalls).toBe(1);
+ expect(timeoutRequests).toEqual(['in-loop-grid']);
expect(events).toHaveLength(1);
expect(events[0]?.neededPbr).toBe(true);
expect(events[0]?.degraded).toBe(true);
- expect(events[0]?.degradedReason).toContain('timed out after 5ms');
+ expect(events[0]?.degradedReason).toContain('timed out after 7ms');
});
test('threads a host visual observer into unified kiln_render without returning pixels', async () => {
diff --git a/src/agent/run.ts b/src/agent/run.ts
index 7ae66e70..00caa641 100644
--- a/src/agent/run.ts
+++ b/src/agent/run.ts
@@ -100,6 +100,8 @@ export interface RunKilnAgentOptions
KilnToolContext,
| 'viewRenderPort'
| 'viewRenderTimeoutMs'
+ | 'viewRenderTimeoutContext'
+ | 'viewRenderTimeoutResolver'
| 'onViewsRendered'
| 'renderObservationPort'
| 'generationCallBudget'
diff --git a/src/agent/surface.ts b/src/agent/surface.ts
index 31a2378d..664869ae 100644
--- a/src/agent/surface.ts
+++ b/src/agent/surface.ts
@@ -75,6 +75,12 @@ export function buildAgentTools(
...(opts.viewRenderTimeoutMs !== undefined
? { viewRenderTimeoutMs: opts.viewRenderTimeoutMs }
: {}),
+ ...(opts.viewRenderTimeoutContext
+ ? { viewRenderTimeoutContext: opts.viewRenderTimeoutContext }
+ : {}),
+ ...(opts.viewRenderTimeoutResolver
+ ? { viewRenderTimeoutResolver: opts.viewRenderTimeoutResolver }
+ : {}),
...(opts.onViewsRendered ? { onViewsRendered: opts.onViewsRendered } : {}),
...(opts.renderObservationPort ? { renderObservationPort: opts.renderObservationPort } : {}),
...(opts.generationCallBudget ? { generationCallBudget: opts.generationCallBudget } : {}),
diff --git a/src/agent/tools-unified.test.ts b/src/agent/tools-unified.test.ts
index b8fcc23a..edc703dc 100644
--- a/src/agent/tools-unified.test.ts
+++ b/src/agent/tools-unified.test.ts
@@ -7,8 +7,10 @@
*/
import { describe, expect, test } from 'bun:test';
import { ImageBlock, JsonBlock } from '@strands-agents/sdk';
+import { createHash } from 'node:crypto';
import { KilnDraftBuffer, KilnEditBuffer, makeKilnUnifiedTools, type UnifiedSink } from './tools';
+import { encodePng } from '../views';
const BOX_CODE = `
const meta = { name: 'test-box', category: 'prop' };
@@ -218,6 +220,61 @@ describe('makeKilnUnifiedTools', () => {
expect(sink.capture).toEqual({ preset: '2x2' }); // failed renders never replace the last good layout
});
+ test('shares last faithful evidence across kiln_render then degraded kiln_inspect', async () => {
+ const sink: UnifiedSink = { edits: [] };
+ const materialCode = TWO_PART_CODE.replace(
+ "gameMaterial('#9aa0a6')",
+ "gameMaterial('#9aa0a6', { metalness: 0.6 })",
+ );
+ let calls = 0;
+ const tools = makeKilnUnifiedTools({
+ seedCode: materialCode,
+ sink,
+ viewRenderPort: async (request) => {
+ calls++;
+ if (calls > 1) return { ok: false, rendererId: 'gpu:test', error: 'device lost' };
+ const size = request.size!;
+ const png = new Uint8Array(encodePng(new Uint8Array(size * size * 3), size, size));
+ return {
+ ok: true,
+ rendererId: 'gpu:test',
+ viewsPng: request.viewDirs!.map(() => png),
+ derivativeFidelity: {
+ materialFaithful: true,
+ inputGlbSha256: `sha256:${createHash('sha256').update(request.glb).digest('hex')}`,
+ },
+ };
+ },
+ });
+ const render = (await findTool(tools, 'kiln_render').invoke({})) as unknown[];
+ const inspect = (await findTool(tools, 'kiln_inspect').invoke({ isolate: true })) as unknown[];
+ type EvidenceJson = {
+ viewEvidence: {
+ current: Record<string, unknown>;
+ lastFaithful?: Record<string, unknown>;
+ };
+ };
+ const renderJson = (render[1] as JsonBlock).json as unknown as EvidenceJson;
+ const inspectJson = (inspect[1] as JsonBlock).json as unknown as EvidenceJson;
+
+ expect(renderJson.viewEvidence.current).toMatchObject({
+ sequence: 1,
+ surface: 'kiln_render',
+ materialFaithful: true,
+ });
+ expect(inspectJson.viewEvidence.current).toMatchObject({
+ sequence: 2,
+ surface: 'kiln_inspect',
+ materialFaithful: false,
+ degraded: true,
+ });
+ expect(inspectJson.viewEvidence.lastFaithful).toMatchObject({
+ sequence: 1,
+ surface: 'kiln_render',
+ inputGlbSha256: renderJson.viewEvidence.current['inputGlbSha256'],
+ });
+ });
+
test('kiln_render emits a render candidate (buffer code + six-view png) via onCandidate', async () => {
const sink: UnifiedSink = { edits: [] };
const got: Array<{ code: string; pngBase64: string; tris?: number }> = [];
diff --git a/src/agent/tools.ts b/src/agent/tools.ts
index 138df396..cb659002 100644
--- a/src/agent/tools.ts
+++ b/src/agent/tools.ts
@@ -20,6 +20,7 @@
import { tool, ImageBlock, JsonBlock, type Tool, type JSONValue } from '@strands-agents/sdk';
import { z } from 'zod';
import type { CaptureConfig } from '../views/capture';
+import { ViewEvidenceHistoryStore } from '../views/evidence-history';
import {
createKilnToolRegistry,
@@ -190,10 +191,16 @@ function toStrandsTool(def: KilnToolDef, context: KilnToolContext = {}): Tool {
* @param sink - Receives the submitted final code. Read `sink.code` after invoke.
*/
export function makeKilnTools(sink: SubmitSink, context: KilnToolContext = {}): Tool[] {
- const kilnTools = createKilnToolRegistry(context).map((def) => toStrandsTool(def, context));
+ const toolContext: KilnToolContext = {
+ ...context,
+ viewEvidenceHistory: context.viewEvidenceHistory ?? new ViewEvidenceHistoryStore(),
+ };
+ const kilnTools = createKilnToolRegistry(toolContext).map((def) =>
+ toStrandsTool(def, toolContext),
+ );
// kiln_screenshot_animation rides alongside the four registry tools (it takes a
// `code` arg like them) so a from-scratch animated build can SEE its motion.
- const animationTool = toStrandsTool(createKilnScreenshotAnimationDef(context), context);
+ const animationTool = toStrandsTool(createKilnScreenshotAnimationDef(toolContext), toolContext);
const submitTool: Tool = tool({
name: KILN_SUBMIT_TOOL_NAME,
description:
@@ -389,8 +396,12 @@ export function makeKilnEditTools(
): Tool[] {
const buffer = new KilnDraftBuffer(opts.seedCode);
opts.sink.edits = buffer.edits; // share the live trace
- const registry = createKilnToolRegistry(opts);
- const animationDef = createKilnScreenshotAnimationDef(opts);
+ const toolContext: KilnToolContext = {
+ ...opts,
+ viewEvidenceHistory: opts.viewEvidenceHistory ?? new ViewEvidenceHistoryStore(),
+ };
+ const registry = createKilnToolRegistry(toolContext);
+ const animationDef = createKilnScreenshotAnimationDef(toolContext);
const find = (name: string): KilnToolDef => {
const def = registry.find((d) => d.name === name);
@@ -581,13 +592,17 @@ export function makeKilnUnifiedTools(
): Tool[] {
const buffer = new KilnDraftBuffer(opts.seedCode ?? '');
opts.sink.edits = buffer.edits; // share the live trace
+ const toolContext: KilnToolContext = {
+ ...opts,
+ viewEvidenceHistory: opts.viewEvidenceHistory ?? new ViewEvidenceHistoryStore(),
+ };
- const registry = createKilnToolRegistry(opts);
+ const registry = createKilnToolRegistry(toolContext);
const validateDef = registry.find((d) => d.name === 'kiln_validate');
if (!validateDef) throw new Error('makeKilnUnifiedTools: missing registry tool kiln_validate');
- const renderViewsDef = createKilnRenderViewsDef(opts);
- const animationDef = createKilnScreenshotAnimationDef(opts);
- const interiorDef = createKilnViewInteriorDef(opts);
+ const renderViewsDef = createKilnRenderViewsDef(toolContext);
+ const animationDef = createKilnScreenshotAnimationDef(toolContext);
+ const interiorDef = createKilnViewInteriorDef(toolContext);
// A1: the unified surface has no standalone kiln_validate tool — every buffer
// write (kiln_draft / a successful kiln_edit) runs the registry's static check
@@ -691,7 +706,7 @@ export function makeKilnUnifiedTools(
// Buffer-aware close-up: after kiln_render flags a suspect region, frame ONE
// view to that part's bounds for detail a grid cell cannot show.
- const inspectDef = createKilnInspectDef();
+ const inspectDef = createKilnInspectDef(toolContext);
const inspectTool: Tool = tool({
name: 'kiln_inspect',
description: `${inspectDef.description} Operates on your current working buffer (no code argument).`,
diff --git a/src/agent/view-render-timeout.test.ts b/src/agent/view-render-timeout.test.ts
new file mode 100644
index 00000000..337dc2f0
--- /dev/null
+++ b/src/agent/view-render-timeout.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ MAX_VIEW_RENDER_TIMEOUT_MS,
+ MIN_VIEW_RENDER_TIMEOUT_MS,
+ resolveViewRenderTimeoutMs,
+ type ViewRenderTimeoutContextProvider,
+} from './view-render-timeout';
+
+describe('R2.7 bounded per-request view-render timeout policy', () => {
+ test('keeps the existing numeric timeout option byte-for-byte compatible', () => {
+ expect(
+ resolveViewRenderTimeoutMs({
+ requestKind: 'in-loop-grid',
+ defaultTimeoutMs: 6_000,
+ timeoutMs: 25,
+ }),
+ ).toBe(25);
+ });
+
+ test('passes warm-up state and remaining budgets to a deterministic resolver', () => {
+ const seen: unknown[] = [];
+ expect(
+ resolveViewRenderTimeoutMs({
+ requestKind: 'derivative-cell',
+ defaultTimeoutMs: 6_000,
+ context: {
+ warmUpState: 'pending',
+ remainingGenerationBudgetMs: 18_000,
+ rendererDeadlineMs: 12_000,
+ },
+ resolver: (context) => {
+ seen.push(context);
+ return context.warmUpState === 'pending' ? 10_000 : 2_000;
+ },
+ }),
+ ).toBe(10_000);
+ expect(seen).toEqual([
+ {
+ requestKind: 'derivative-cell',
+ defaultTimeoutMs: 6_000,
+ timeoutMs: 6_000,
+ warmUpState: 'pending',
+ remainingGenerationBudgetMs: 18_000,
+ rendererDeadlineMs: 12_000,
+ },
+ ]);
+ expect(Object.isFrozen(seen[0])).toBe(true);
+ });
+
+ test('caps every resolver result to renderer, generation, and global bounds', () => {
+ expect(
+ resolveViewRenderTimeoutMs({
+ requestKind: 'final-grid',
+ defaultTimeoutMs: 8_000,
+ context: {
+ warmUpState: 'ready',
+ remainingGenerationBudgetMs: 4_500,
+ rendererDeadlineMs: 10_000,
+ },
+ resolver: () => Number.POSITIVE_INFINITY,
+ }),
+ ).toBe(4_500);
+ expect(
+ resolveViewRenderTimeoutMs({
+ requestKind: 'in-loop-grid',
+ defaultTimeoutMs: MAX_VIEW_RENDER_TIMEOUT_MS * 2,
+ }),
+ ).toBe(MAX_VIEW_RENDER_TIMEOUT_MS);
+ expect(
+ resolveViewRenderTimeoutMs({
+ requestKind: 'in-loop-grid',
+ defaultTimeoutMs: -1,
+ }),
+ ).toBe(MIN_VIEW_RENDER_TIMEOUT_MS);
+ });
+
+ test('samples host context for every request instead of freezing generation-start state', () => {
+ let sample = 0;
+ const provider: ViewRenderTimeoutContextProvider = () => {
+ sample += 1;
+ return {
+ warmUpState: sample === 1 ? 'pending' : 'ready',
+ remainingGenerationBudgetMs: sample === 1 ? 20_000 : 5_000,
+ rendererDeadlineMs: 30_000,
+ };
+ };
+ const resolver = (
+ context: Parameters<
+ NonNullable<Parameters<typeof resolveViewRenderTimeoutMs>[0]['resolver']>
+ >[0],
+ ) => (context.warmUpState === 'pending' ? 12_000 : 4_000);
+
+ const input = {
+ requestKind: 'in-loop-grid' as const,
+ defaultTimeoutMs: 6_000,
+ contextProvider: provider,
+ resolver,
+ };
+ expect(resolveViewRenderTimeoutMs(input)).toBe(12_000);
+ expect(resolveViewRenderTimeoutMs(input)).toBe(4_000);
+ expect(sample).toBe(2);
+ });
+
+ test('contains throwing host hooks and falls back to the bounded numeric policy', () => {
+ expect(
+ resolveViewRenderTimeoutMs({
+ requestKind: 'in-loop-grid',
+ defaultTimeoutMs: 6_000,
+ timeoutMs: 1_234,
+ contextProvider: () => {
+ throw new Error('host state unavailable');
+ },
+ resolver: () => {
+ throw new Error('must not run');
+ },
+ }),
+ ).toBe(1_234);
+ expect(
+ resolveViewRenderTimeoutMs({
+ requestKind: 'in-loop-grid',
+ defaultTimeoutMs: 6_000,
+ timeoutMs: 1_234,
+ resolver: () => Number.NaN,
+ }),
+ ).toBe(1_234);
+ });
+
+ test('normalizes untrusted runtime state before exposing it to the resolver', () => {
+ let seenWarmUpState = '';
+ const timeout = resolveViewRenderTimeoutMs({
+ requestKind: 'in-loop-grid',
+ defaultTimeoutMs: 6_000,
+ context: { warmUpState: 'invented' as 'ready', remainingGenerationBudgetMs: Number.NaN },
+ resolver: (context) => {
+ seenWarmUpState = context.warmUpState;
+ return 2_000;
+ },
+ });
+ expect(timeout).toBe(2_000);
+ expect(seenWarmUpState).toBe('unknown');
+ });
+});
diff --git a/src/agent/view-render-timeout.ts b/src/agent/view-render-timeout.ts
new file mode 100644
index 00000000..8bcf1e2d
--- /dev/null
+++ b/src/agent/view-render-timeout.ts
@@ -0,0 +1,110 @@
+/** Engine-owned bounds for every host-render deadline. */
+export const MIN_VIEW_RENDER_TIMEOUT_MS = 1;
+export const MAX_VIEW_RENDER_TIMEOUT_MS = 120_000;
+
+export type ViewRenderRequestKind = 'in-loop-grid' | 'derivative-cell' | 'final-grid';
+export type ViewRenderWarmUpState = 'unknown' | 'pending' | 'ready' | 'degraded';
+
+/** Dynamic host state sampled immediately before each renderer request. */
+export interface ViewRenderTimeoutHostContext {
+ warmUpState: ViewRenderWarmUpState;
+ /** Remaining wall-clock allowance for the generation. Zero means fail fast. */
+ remainingGenerationBudgetMs?: number;
+ /** The renderer adapter's own deadline. The Engine never waits longer. */
+ rendererDeadlineMs?: number;
+}
+
+export interface ViewRenderTimeoutResolverContext extends ViewRenderTimeoutHostContext {
+ requestKind: ViewRenderRequestKind;
+ defaultTimeoutMs: number;
+ /** Legacy numeric option after Engine bounds are applied. */
+ timeoutMs: number;
+}
+
+export type ViewRenderTimeoutContextProvider = () => ViewRenderTimeoutHostContext;
+export type ViewRenderTimeoutResolver = (
+ context: Readonly<ViewRenderTimeoutResolverContext>,
+) => number;
+
+export interface ResolveViewRenderTimeoutInput {
+ requestKind: ViewRenderRequestKind;
+ defaultTimeoutMs: number;
+ /** Backwards-compatible fixed deadline. */
+ timeoutMs?: number;
+ /** Static context, useful for deterministic adapters and tests. */
+ context?: ViewRenderTimeoutHostContext;
+ /** Dynamic context takes precedence and is sampled once per renderer request. */
+ contextProvider?: ViewRenderTimeoutContextProvider;
+ /** Optional host policy. Its result remains subject to every Engine cap. */
+ resolver?: ViewRenderTimeoutResolver;
+}
+
+const WARM_UP_STATES = new Set<ViewRenderWarmUpState>(['unknown', 'pending', 'ready', 'degraded']);
+
+function boundedTimeout(value: number, fallback: number): number {
+ if (Number.isNaN(value)) return fallback;
+ if (value === Number.POSITIVE_INFINITY) return MAX_VIEW_RENDER_TIMEOUT_MS;
+ if (value === Number.NEGATIVE_INFINITY) return MIN_VIEW_RENDER_TIMEOUT_MS;
+ return Math.min(
+ MAX_VIEW_RENDER_TIMEOUT_MS,
+ Math.max(MIN_VIEW_RENDER_TIMEOUT_MS, Math.floor(value)),
+ );
+}
+
+function optionalBudget(value: number | undefined): number | undefined {
+ if (value === undefined || Number.isNaN(value)) return undefined;
+ if (value === Number.POSITIVE_INFINITY) return MAX_VIEW_RENDER_TIMEOUT_MS;
+ if (value === Number.NEGATIVE_INFINITY) return 0;
+ return Math.min(MAX_VIEW_RENDER_TIMEOUT_MS, Math.max(0, Math.floor(value)));
+}
+
+/**
+ * Resolve one renderer deadline. Host hooks are advisory and failure-contained;
+ * the numeric/default policy always remains a safe fallback. The returned value
+ * is an integer inside the Engine bounds and never exceeds a supplied renderer
+ * or remaining-generation allowance.
+ */
+export function resolveViewRenderTimeoutMs(input: ResolveViewRenderTimeoutInput): number {
+ const defaultTimeoutMs = boundedTimeout(input.defaultTimeoutMs, MIN_VIEW_RENDER_TIMEOUT_MS);
+ const timeoutMs = boundedTimeout(input.timeoutMs ?? defaultTimeoutMs, defaultTimeoutMs);
+
+ let hostContext: ViewRenderTimeoutHostContext | undefined = input.context;
+ let hostContextAvailable = true;
+ if (input.contextProvider) {
+ try {
+ hostContext = input.contextProvider();
+ } catch {
+ hostContext = undefined;
+ hostContextAvailable = false;
+ }
+ }
+
+ const remainingGenerationBudgetMs = optionalBudget(hostContext?.remainingGenerationBudgetMs);
+ const rendererDeadlineMs = optionalBudget(hostContext?.rendererDeadlineMs);
+ const warmUpState = WARM_UP_STATES.has(hostContext?.warmUpState as ViewRenderWarmUpState)
+ ? (hostContext?.warmUpState as ViewRenderWarmUpState)
+ : 'unknown';
+ const resolverContext: ViewRenderTimeoutResolverContext = Object.freeze({
+ requestKind: input.requestKind,
+ defaultTimeoutMs,
+ timeoutMs,
+ warmUpState,
+ ...(remainingGenerationBudgetMs !== undefined ? { remainingGenerationBudgetMs } : {}),
+ ...(rendererDeadlineMs !== undefined ? { rendererDeadlineMs } : {}),
+ });
+
+ let resolved = timeoutMs;
+ if (input.resolver && hostContextAvailable) {
+ try {
+ resolved = boundedTimeout(input.resolver(resolverContext), timeoutMs);
+ } catch {
+ resolved = timeoutMs;
+ }
+ }
+
+ if (rendererDeadlineMs !== undefined) resolved = Math.min(resolved, rendererDeadlineMs);
+ if (remainingGenerationBudgetMs !== undefined) {
+ resolved = Math.min(resolved, remainingGenerationBudgetMs);
+ }
+ return boundedTimeout(resolved, timeoutMs);
+}
diff --git a/src/composer/agent/prompt.ts b/src/composer/agent/prompt.ts
index 89bf877a..20af2aca 100644
--- a/src/composer/agent/prompt.ts
+++ b/src/composer/agent/prompt.ts
@@ -57,13 +57,28 @@ 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. */
+/** Bounded Phase 2 contract for the canonical world integration agent. */
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.
+Honor the user's complete world intent; do not narrow the scene into a terrain-only or socket-only task. The canonical world is already composed. Make only bounded integration changes.
+
+## Inspect before editing
+- Call scene_world_view first. It returns the exact current world hash, every current presentation camera/value, and the hard presentation limits.
+- Preserve current values that already serve the request. Re-check with scene_world_view after edits.
+
+## Presentation
+- scene_world_set_presentation replaces persisted camera/grid/lighting/receipt PARAMETERS only. Do not send artifactBinding; the Engine binds the exact post-edit world SHA-256 at render/package time.
+- Camera order is output order. Each id and grid cell must be unique; camera aspect must equal cellWidth/cellHeight.
+- Limits: 1-12 cameras, grid up to 4x3, cells up to 4096x4096, and cameras x cellWidth x cellHeight must not exceed 16,777,216 total pixels.
+- Use the supported neutral-studio-v1 lighting profile unless the host advertises another versioned ID.
+
+## Collision, traversal, and terrain
+- scene_world_set_collision selects one object's explicit asset-local policy: none, bounds, selected authored-submesh GLB nodeNames, or deterministic generated-mesh bounds-box. Authored nodes are resolved only through the host's hash-bound geometry port; artifact modes require the host publisher. Do not invent paths, URLs, or hashes.
- 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.`;
+
+## Finish
+Call scene_world_render, inspect all returned ordered frames and evidence, then scene_world_validate. Fix failures before scene_world_finalize. Never trade readable composition for procedural complexity.`;
export interface BuildComposerPromptOptions {
/** Natural-language description of the scene to compose. */
diff --git a/src/composer/agent/tools.ts b/src/composer/agent/tools.ts
index 45889649..dfdd78e8 100644
--- a/src/composer/agent/tools.ts
+++ b/src/composer/agent/tools.ts
@@ -32,7 +32,12 @@ import type {
ScenePaintZoneSpec,
} from '../model';
import type { OverlapViolation } from '../overlap';
-import type { SceneRenderPort, SceneRenderResult } from '../render-port';
+import type {
+ DerivativeReviewFidelityV1,
+ SceneRenderPort,
+ SceneRenderResult,
+} from '../render-port';
+import { ViewEvidenceHistoryStore } from '../../views/evidence-history';
/**
* A mutable sink the composer tools write into. Create one per run; after every
@@ -114,12 +119,48 @@ const paintShape = z.union([
/** base64 PNG → the raw bytes an ImageBlock wants. */
const png = (b64: string): Uint8Array => new Uint8Array(Buffer.from(b64, 'base64'));
+const SHA256 = /^sha256:[0-9a-f]{64}$/;
+
+function composerViewFidelity(res: SceneRenderResult): DerivativeReviewFidelityV1 {
+ const value = res.viewFidelity;
+ const valid =
+ value?.version === 'kiln.derivative-review-fidelity.v1' &&
+ value.exactArtifact === false &&
+ value.receipts.length > 0 &&
+ value.receipts.every(
+ (receipt) =>
+ receipt.exactArtifact === false &&
+ receipt.derivativeLabel.trim().length > 0 &&
+ SHA256.test(receipt.inputGlbSha256),
+ );
+ if (valid) {
+ return {
+ ...value,
+ exactArtifact: false,
+ receipts: value.receipts.map((receipt) => ({ ...receipt, exactArtifact: false })),
+ };
+ }
+ return {
+ version: 'kiln.derivative-review-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'none',
+ materialFaithful: false,
+ exactArtifact: false,
+ degraded: true,
+ receipts: [],
+ reasonCodes: [value ? 'DERIVATIVE_RECEIPT_INVALID' : 'DERIVATIVE_RECEIPT_UNAVAILABLE'],
+ };
+}
/** Turn a host render result into the tool-callback value: one ImageBlock per
* returned view (perCamera grid or single frame) + a JsonBlock of metadata, or a
* plain `{ok:false}` when the render failed. Block arrays are a valid (untyped)
* Strands callback return — cast past JSONValue, same as the kiln_* tools. */
-function renderToCallback(res: SceneRenderResult): JSONValue {
+function renderToCallback(
+ res: SceneRenderResult,
+ surface: 'scene_render' | 'scene_screenshot_camera',
+ evidenceHistory: ViewEvidenceHistoryStore,
+): JSONValue {
if (!res.ok) {
return { ok: false, error: res.error ?? 'render failed' } as JSONValue;
}
@@ -128,14 +169,17 @@ function renderToCallback(res: SceneRenderResult): JSONValue {
: res.pngBase64
? [res.pngBase64]
: [];
+ const viewFidelity = composerViewFidelity(res);
const json = {
ok: true,
views: frames.length,
+ viewFidelity,
+ viewEvidence: evidenceHistory.record(surface, viewFidelity),
...(res.tris != null ? { tris: res.tris } : {}),
};
return [
...frames.map((b64) => new ImageBlock({ format: 'png', source: { bytes: png(b64) } })),
- new JsonBlock({ json: json as JSONValue }),
+ new JsonBlock({ json: json as unknown as JSONValue }),
] as unknown as JSONValue;
}
@@ -159,6 +203,8 @@ export interface MakeComposerToolsOptions {
sink: ComposerSink;
/** Best-effort live render candidates (one per successful scene_render). */
onCandidate?: (c: SceneRenderCandidate) => void;
+ /** Shared bounded hash-only material evidence ledger for this composer run. */
+ viewEvidenceHistory?: ViewEvidenceHistoryStore;
}
/**
@@ -169,6 +215,7 @@ export interface MakeComposerToolsOptions {
*/
export function makeSceneComposerTools(opts: MakeComposerToolsOptions): Tool[] {
const { model, render, sink } = opts;
+ const evidenceHistory = opts.viewEvidenceHistory ?? new ViewEvidenceHistoryStore();
/** Re-serialize + re-evaluate into the sink; the single autosave point. */
const capture = (): EvalResult => {
@@ -280,7 +327,7 @@ export function makeSceneComposerTools(opts: MakeComposerToolsOptions): Tool[] {
}
}
}
- return renderToCallback(res);
+ return renderToCallback(res, 'scene_render', evidenceHistory);
},
});
@@ -313,7 +360,7 @@ export function makeSceneComposerTools(opts: MakeComposerToolsOptions): Tool[] {
},
],
});
- return renderToCallback(res);
+ return renderToCallback(res, 'scene_screenshot_camera', evidenceHistory);
},
});
diff --git a/src/composer/agent/world-run.ts b/src/composer/agent/world-run.ts
index 540f87c8..4f7593a1 100644
--- a/src/composer/agent/world-run.ts
+++ b/src/composer/agent/world-run.ts
@@ -14,6 +14,7 @@ import type { GenerationCallBudget, GenerationCallBudgetReceipt } from '../../ag
import { toCachedSystemPrompt } from '../../agent/providers';
import {
hashWorldDocumentV2,
+ PRESENTATION_MAX_TOTAL_PIXELS_V1,
parseWorldDocumentV2,
PlacementModel,
type Placement,
@@ -22,6 +23,7 @@ import {
type SceneRenderPort,
type SceneRenderResult,
type WorldDocumentV2,
+ validatePresentationReceiptV1,
validateWorldIntegrationV2,
worldDocumentV2ToSceneModelJSON,
} from '..';
@@ -101,17 +103,31 @@ function lifecycleTools(
name: 'scene_world_view',
description: 'Inspect the complete canonical world and authored integration counts.',
inputSchema: empty,
- callback: async () =>
- ({
+ callback: async () => {
+ const worldHash = await hashWorldDocumentV2(state.world);
+ return {
ok: true,
- worldHash: await hashWorldDocumentV2(state.world),
+ worldHash,
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,
+ presentation: state.world.presentation ?? null,
+ presentationLimits: {
+ maxCameras: 12,
+ maxGridColumns: 4,
+ maxGridRows: 3,
+ maxCellWidth: 4096,
+ maxCellHeight: 4096,
+ maxTotalPixels: PRESENTATION_MAX_TOTAL_PIXELS_V1,
+ },
+ presentationBinding: state.world.presentation
+ ? { kind: 'world', sha256: worldHash, authoredByModel: false }
+ : null,
+ } as JSONValue;
+ },
}),
tool({
name: 'scene_world_validate',
@@ -130,12 +146,36 @@ function lifecycleTools(
inputSchema: empty,
callback: async () => {
const worldHash = await hashWorldDocumentV2(state.world);
+ const presentation = state.world.presentation;
const result = await render({
placements: placements(state.world),
worldDocument: state.world,
worldHash,
+ ...(presentation
+ ? {
+ cameras: presentation.cameras.map(({ id: _id, cell: _cell, ...camera }) => camera),
+ width: presentation.grid.cellWidth,
+ height: presentation.grid.cellHeight,
+ lightingPresetId: presentation.lightingPresetId,
+ }
+ : {}),
});
if (!result.ok) return { ok: false, error: result.error ?? 'render failed' } as JSONValue;
+ if (presentation && result.receipt) {
+ const receiptValidation = validatePresentationReceiptV1(
+ {
+ ...presentation,
+ artifactBinding: { kind: 'world', sha256: worldHash },
+ },
+ result.receipt,
+ );
+ if (!receiptValidation.ok) {
+ return {
+ ok: false,
+ error: `presentation receipt rejected: ${receiptValidation.reason}`,
+ } as JSONValue;
+ }
+ }
const frames = result.perCameraBase64?.length
? result.perCameraBase64
: result.pngBase64
@@ -234,6 +274,12 @@ export async function runKilnWorldIntegration(
...(options.publishHeightfieldArtifact
? { publishHeightfieldArtifact: options.publishHeightfieldArtifact }
: {}),
+ ...(options.publishColliderArtifact
+ ? { publishColliderArtifact: options.publishColliderArtifact }
+ : {}),
+ ...(options.resolveAuthoredColliderGeometry
+ ? { resolveAuthoredColliderGeometry: options.resolveAuthoredColliderGeometry }
+ : {}),
...(options.onWorldChanged ? { onWorldChanged: options.onWorldChanged } : {}),
});
const tools: unknown[] = [
diff --git a/src/composer/agent/world-tools.ts b/src/composer/agent/world-tools.ts
index a9737244..42f80192 100644
--- a/src/composer/agent/world-tools.ts
+++ b/src/composer/agent/world-tools.ts
@@ -2,18 +2,31 @@
import { type JSONValue, type Tool, tool } from '@strands-agents/sdk';
import { z } from 'zod';
import {
+ AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1,
+ AUTHORED_COLLIDER_GEOMETRY_V1_SCHEMA_VERSION,
+ ColliderCompileError,
+ ColliderPolicyV1Schema,
+ compileColliderArtifactV1,
+ encodeColliderArtifactV1,
+ hashColliderArtifactV1,
+ type ColliderArtifactV1,
+ parseAuthoredColliderGeometryV1,
+ type ResolveAuthoredColliderGeometryV1Port,
createHeightfieldArtifactV1,
encodeHeightfieldArtifactV1,
hashHeightfieldArtifactV1,
type HeightfieldArtifactV1,
fillWorldPathV2,
setWorldPathsV2,
+ setWorldPresentationV1,
setWorldSocketsV2,
setWorldSpawnsV2,
setWorldTerrainV2,
setWorldZonesV2,
snapWorldObjectToSocketV2,
type WorldDocumentV2,
+ PresentationParametersV1Schema,
+ parseWorldDocumentV2,
} from '..';
export interface WorldIntegrationToolState {
@@ -26,6 +39,12 @@ export interface MakeWorldIntegrationToolsV2Options {
bytes: Uint8Array,
sha256: string,
) => Promise<{ uri: string; mediaType?: string }>;
+ publishColliderArtifact?: (
+ artifact: ColliderArtifactV1,
+ bytes: Uint8Array,
+ sha256: `sha256:${string}`,
+ ) => Promise<{ uri: string; mediaType?: string }>;
+ resolveAuthoredColliderGeometry?: ResolveAuthoredColliderGeometryV1Port;
onWorldChanged?: (world: WorldDocumentV2) => void;
}
@@ -143,6 +162,154 @@ export function makeWorldIntegrationToolsV2(options: MakeWorldIntegrationToolsV2
.strict(),
callback: (input) => guarded(() => setWorldSpawnsV2(options.state.world, input.spawns)),
});
+ const setPresentation: Tool = tool({
+ name: 'scene_world_set_presentation',
+ description:
+ 'Replace persisted ordered camera/grid/lighting/receipt parameters. Do not send artifactBinding; Engine binds the post-edit world hash. Total requested pixels are capped at 16,777,216.',
+ inputSchema: z.object({ presentation: PresentationParametersV1Schema }).strict(),
+ callback: (input) =>
+ guarded(() => setWorldPresentationV1(options.state.world, input.presentation)),
+ });
+ const setCollision: Tool = tool({
+ name: 'scene_world_set_collision',
+ description:
+ 'Set one object collision policy to none, asset bounds, selected authored GLB mesh nodes, or a deterministic generated bounds-box artifact. Artifact policies require bounded host ports.',
+ inputSchema: z.object({ objectId: id, policy: ColliderPolicyV1Schema }).strict(),
+ callback: async (input) => {
+ try {
+ const object = options.state.world.objects.find(
+ (candidate) => candidate.id === input.objectId,
+ );
+ if (!object) return { ok: false, error: `unknown object "${input.objectId}"` } as JSONValue;
+ const asset = options.state.world.assets.find(
+ (candidate) => candidate.refId === object.assetRefId,
+ );
+ if (!asset)
+ return { ok: false, error: `missing asset for "${input.objectId}"` } as JSONValue;
+
+ if (input.policy.kind === 'none' || input.policy.kind === 'bounds') {
+ const objects = options.state.world.objects.map((candidate) =>
+ candidate.id === object.id
+ ? { ...candidate, collision: { policy: input.policy.kind } }
+ : candidate,
+ );
+ const referenced = new Set(
+ objects.flatMap((candidate) =>
+ candidate.collision?.policy === 'artifact' ? [candidate.collision.artifactRefId] : [],
+ ),
+ );
+ return commit(
+ parseWorldDocumentV2({
+ ...options.state.world,
+ objects,
+ collisionArtifacts: options.state.world.collisionArtifacts.filter((artifact) =>
+ referenced.has(artifact.refId),
+ ),
+ }),
+ );
+ }
+
+ if (input.policy.kind === 'authored-submesh' && !options.resolveAuthoredColliderGeometry) {
+ return {
+ ok: false,
+ error: 'authored collider geometry resolver is not configured',
+ } as JSONValue;
+ }
+ if (!options.publishColliderArtifact) {
+ return { ok: false, error: 'collider artifact publisher is not configured' } as JSONValue;
+ }
+ const sourceArtifactSha256 = `sha256:${asset.artifactSha256}` as const;
+ let artifact: ColliderArtifactV1;
+ if (input.policy.kind === 'authored-submesh') {
+ const resolved = parseAuthoredColliderGeometryV1(
+ await options.resolveAuthoredColliderGeometry!(
+ Object.freeze({
+ schemaVersion: AUTHORED_COLLIDER_GEOMETRY_V1_SCHEMA_VERSION,
+ sourceArtifactSha256,
+ transformFrame: 'asset-local',
+ nodeNames: Object.freeze([...input.policy.nodeNames]),
+ limits: AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1,
+ }),
+ ),
+ );
+ if (resolved.sourceArtifactSha256 !== sourceArtifactSha256) {
+ throw new ColliderCompileError(
+ 'COLLIDER_SOURCE_HASH_MISMATCH',
+ 'resolved collider geometry does not match the selected asset hash',
+ );
+ }
+ const requested = new Set(input.policy.nodeNames);
+ const returned = new Set(resolved.submeshes.map((entry) => entry.nodeName));
+ const missing = input.policy.nodeNames.filter((nodeName) => !returned.has(nodeName));
+ if (missing.length) {
+ throw new ColliderCompileError(
+ 'COLLIDER_AUTHORED_SUBMESH_MISSING',
+ `missing authored collider node(s): ${missing.join(', ')}`,
+ );
+ }
+ const unexpected = resolved.submeshes
+ .map((entry) => entry.nodeName)
+ .filter((nodeName) => !requested.has(nodeName));
+ if (unexpected.length) {
+ throw new ColliderCompileError(
+ 'COLLIDER_AUTHORED_SUBMESH_INVALID',
+ `resolver returned unrequested collider node(s): ${unexpected.join(', ')}`,
+ );
+ }
+ artifact = compileColliderArtifactV1(input.policy, {
+ sourceArtifactSha256,
+ bounds: asset.bounds,
+ authoredSubmeshes: resolved.submeshes,
+ });
+ } else {
+ artifact = compileColliderArtifactV1(input.policy, {
+ sourceArtifactSha256,
+ bounds: asset.bounds,
+ });
+ }
+ const bytes = encodeColliderArtifactV1(artifact);
+ const sha256 = await hashColliderArtifactV1(artifact);
+ const published = await options.publishColliderArtifact(artifact, bytes, sha256);
+ const refId = `collision:${sha256.slice('sha256:'.length)}`;
+ const objects = options.state.world.objects.map((candidate) =>
+ candidate.id === object.id
+ ? { ...candidate, collision: { policy: 'artifact' as const, artifactRefId: refId } }
+ : candidate,
+ );
+ const referenced = new Set(
+ objects.flatMap((candidate) =>
+ candidate.collision?.policy === 'artifact' ? [candidate.collision.artifactRefId] : [],
+ ),
+ );
+ const collisionArtifacts = [
+ ...options.state.world.collisionArtifacts.filter(
+ (candidate) => candidate.refId !== refId && referenced.has(candidate.refId),
+ ),
+ {
+ refId,
+ artifact: {
+ uri: published.uri,
+ sha256: sha256.slice('sha256:'.length),
+ mediaType: published.mediaType ?? 'application/vnd.kiln.collider+json',
+ },
+ },
+ ];
+ const result = commit(
+ parseWorldDocumentV2({
+ ...options.state.world,
+ objects,
+ collisionArtifacts,
+ }),
+ ) 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;
+ }
+ },
+ });
const snap: Tool = tool({
name: 'scene_world_snap',
description:
@@ -230,5 +397,15 @@ export function makeWorldIntegrationToolsV2(options: MakeWorldIntegrationToolsV2
}
},
});
- return [setZones, setPaths, setSockets, setSpawns, snap, fillPath, setHeightfield];
+ return [
+ setZones,
+ setPaths,
+ setSockets,
+ setSpawns,
+ setPresentation,
+ setCollision,
+ snap,
+ fillPath,
+ setHeightfield,
+ ];
}
diff --git a/src/composer/collision.ts b/src/composer/collision.ts
new file mode 100644
index 00000000..d9139e08
--- /dev/null
+++ b/src/composer/collision.ts
@@ -0,0 +1,448 @@
+import { z } from 'zod';
+import { worldAabbFromLocal, type Aabb, type Vec3 } from './overlap';
+import {
+ assertNoPrototypeKeys,
+ canonicalContractJson,
+ sha256ContractBytes,
+} from './contract-utils';
+
+export const COLLIDER_POLICY_V1_SCHEMA_VERSION = 'kiln.collider-policy.v1' as const;
+export const COLLIDER_ARTIFACT_V1_SCHEMA_VERSION = 'kiln.collider-artifact.v1' as const;
+export const AUTHORED_COLLIDER_GEOMETRY_V1_SCHEMA_VERSION =
+ 'kiln.authored-collider-geometry.v1' as const;
+export const AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1 = Object.freeze({
+ maxNodes: 64,
+ maxVertices: 65_536,
+ maxTriangles: 65_536,
+});
+
+const finite = z.number().finite();
+const vec3 = z.tuple([finite, finite, finite]);
+const sha256 = z.string().regex(/^sha256:[0-9a-f]{64}$/);
+const id = z
+ .string()
+ .min(1)
+ .max(256)
+ .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/);
+const bounds = z
+ .object({ min: vec3, max: vec3 })
+ .strict()
+ .superRefine((value, ctx) => {
+ for (let axis = 0; axis < 3; axis++) {
+ if (value.min[axis]! > value.max[axis]!) {
+ ctx.addIssue({ code: 'custom', path: ['min', axis], message: 'min must not exceed max' });
+ }
+ }
+ });
+
+const policyCommon = {
+ transformFrame: z.literal('asset-local'),
+};
+
+export const ColliderPolicyV1Schema = z.discriminatedUnion('kind', [
+ z.object({ kind: z.literal('none'), ...policyCommon }).strict(),
+ z.object({ kind: z.literal('bounds'), ...policyCommon }).strict(),
+ z
+ .object({
+ kind: z.literal('authored-submesh'),
+ ...policyCommon,
+ nodeNames: z.array(id).min(1).max(64),
+ })
+ .strict()
+ .superRefine((value, ctx) => {
+ if (new Set(value.nodeNames).size !== value.nodeNames.length) {
+ ctx.addIssue({ code: 'custom', path: ['nodeNames'], message: 'nodeNames must be unique' });
+ }
+ }),
+ z
+ .object({
+ kind: z.literal('generated-mesh'),
+ ...policyCommon,
+ method: z.literal('bounds-box'),
+ })
+ .strict(),
+]);
+
+const primitive = z
+ .object({
+ nodeName: id,
+ positions: z.array(finite).max(AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxVertices * 3),
+ indices: z
+ .array(z.number().int().nonnegative())
+ .max(AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxTriangles * 3),
+ })
+ .strict()
+ .superRefine((value, ctx) => {
+ if (value.positions.length < 9 || value.positions.length % 3 !== 0) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['positions'],
+ message: 'positions must contain 3D vertices',
+ });
+ }
+ if (value.indices.length < 3 || value.indices.length % 3 !== 0) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['indices'],
+ message: 'indices must contain triangles',
+ });
+ }
+ const vertexCount = value.positions.length / 3;
+ if (value.indices.some((index) => index >= vertexCount)) {
+ ctx.addIssue({ code: 'custom', path: ['indices'], message: 'index exceeds vertex count' });
+ }
+ });
+
+/** Strict output boundary for a host that flattens selected GLB mesh nodes into asset-local space. */
+export const AuthoredColliderGeometryV1Schema = z
+ .object({
+ schemaVersion: z.literal(AUTHORED_COLLIDER_GEOMETRY_V1_SCHEMA_VERSION),
+ sourceArtifactSha256: sha256,
+ transformFrame: z.literal('asset-local'),
+ submeshes: z.array(primitive).min(1).max(AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxNodes),
+ })
+ .strict()
+ .superRefine((value, ctx) => {
+ if (new Set(value.submeshes.map((entry) => entry.nodeName)).size !== value.submeshes.length) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['submeshes'],
+ message: 'submesh nodeName must be unique',
+ });
+ }
+ const vertexCount = value.submeshes.reduce((sum, entry) => sum + entry.positions.length / 3, 0);
+ const triangleCount = value.submeshes.reduce((sum, entry) => sum + entry.indices.length / 3, 0);
+ if (
+ vertexCount > AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxVertices ||
+ triangleCount > AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxTriangles
+ ) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['submeshes'],
+ message: 'resolved collider geometry exceeds aggregate budget',
+ });
+ }
+ });
+
+export const ColliderArtifactV1Schema = z
+ .object({
+ schemaVersion: z.literal(COLLIDER_ARTIFACT_V1_SCHEMA_VERSION),
+ transformFrame: z.literal('asset-local'),
+ sourceArtifactSha256: sha256,
+ policy: ColliderPolicyV1Schema,
+ bounds,
+ primitives: z.array(primitive).max(64),
+ })
+ .strict()
+ .superRefine((value, ctx) => {
+ if (new Set(value.primitives.map((entry) => entry.nodeName)).size !== value.primitives.length) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['primitives'],
+ message: 'primitive nodeName must be unique',
+ });
+ }
+ if (value.policy.kind === 'none' && value.primitives.length !== 0) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['primitives'],
+ message: 'none policy has no primitives',
+ });
+ }
+ if (value.policy.kind !== 'none' && value.primitives.length === 0) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['primitives'],
+ message: 'collider policy requires geometry',
+ });
+ }
+ if (value.primitives.length) {
+ const derived = boundsOfPrimitives(value.primitives);
+ if (
+ derived.min.some((entry, axis) => entry !== value.bounds.min[axis]) ||
+ derived.max.some((entry, axis) => entry !== value.bounds.max[axis])
+ ) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['bounds'],
+ message: 'bounds must exactly enclose collider vertices',
+ });
+ }
+ }
+ const vertexCount = value.primitives.reduce(
+ (sum, entry) => sum + entry.positions.length / 3,
+ 0,
+ );
+ const triangleCount = value.primitives.reduce(
+ (sum, entry) => sum + entry.indices.length / 3,
+ 0,
+ );
+ if (
+ vertexCount > AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxVertices ||
+ triangleCount > AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxTriangles
+ ) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['primitives'],
+ message: 'collider artifact exceeds aggregate geometry budget',
+ });
+ }
+ });
+
+export type ColliderPolicyV1 = z.infer<typeof ColliderPolicyV1Schema>;
+export type ColliderArtifactV1 = z.infer<typeof ColliderArtifactV1Schema>;
+type ParsedAuthoredColliderGeometryV1 = z.infer<typeof AuthoredColliderGeometryV1Schema>;
+export type AuthoredColliderGeometryV1 = Omit<
+ ParsedAuthoredColliderGeometryV1,
+ 'sourceArtifactSha256'
+> & {
+ sourceArtifactSha256: `sha256:${string}`;
+};
+
+export interface ResolveAuthoredColliderGeometryV1Request {
+ schemaVersion: typeof AUTHORED_COLLIDER_GEOMETRY_V1_SCHEMA_VERSION;
+ sourceArtifactSha256: `sha256:${string}`;
+ transformFrame: 'asset-local';
+ nodeNames: readonly string[];
+ limits: Readonly<typeof AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1>;
+}
+
+/** Host port: resolve only the requested hash-bound GLB nodes, never paths, URLs, or model code. */
+export type ResolveAuthoredColliderGeometryV1Port = (
+ request: ResolveAuthoredColliderGeometryV1Request,
+) => Promise<unknown>;
+
+export interface AuthoredColliderSubmeshV1 {
+ nodeName: string;
+ positions: readonly number[];
+ indices: readonly number[];
+}
+
+export interface CompileColliderArtifactV1Input {
+ sourceArtifactSha256: `sha256:${string}`;
+ bounds: Aabb;
+ authoredSubmeshes?: readonly AuthoredColliderSubmeshV1[];
+}
+
+export class ColliderCompileError extends Error {
+ constructor(
+ readonly code:
+ | 'COLLIDER_AUTHORED_SUBMESH_MISSING'
+ | 'COLLIDER_AUTHORED_SUBMESH_INVALID'
+ | 'COLLIDER_SOURCE_HASH_MISMATCH'
+ | 'COLLIDER_BUDGET_EXCEEDED',
+ message: string,
+ ) {
+ super(`${code}: ${message}`);
+ this.name = 'ColliderCompileError';
+ }
+}
+
+export function parseColliderPolicyV1(input: unknown): ColliderPolicyV1 {
+ assertNoPrototypeKeys(input);
+ return ColliderPolicyV1Schema.parse(input);
+}
+
+export function parseAuthoredColliderGeometryV1(input: unknown): AuthoredColliderGeometryV1 {
+ if (typeof input === 'object' && input !== null && 'submeshes' in input) {
+ const submeshes = (input as { submeshes?: unknown }).submeshes;
+ if (Array.isArray(submeshes)) {
+ let vertices = 0;
+ let triangles = 0;
+ for (const submesh of submeshes) {
+ if (typeof submesh !== 'object' || submesh === null) continue;
+ const positions = (submesh as { positions?: unknown }).positions;
+ const indices = (submesh as { indices?: unknown }).indices;
+ if (Array.isArray(positions)) vertices += positions.length / 3;
+ if (Array.isArray(indices)) triangles += indices.length / 3;
+ }
+ if (
+ submeshes.length > AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxNodes ||
+ vertices > AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxVertices ||
+ triangles > AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxTriangles
+ ) {
+ throw new ColliderCompileError(
+ 'COLLIDER_BUDGET_EXCEEDED',
+ 'resolved collider geometry exceeds node/vertex/triangle limits',
+ );
+ }
+ }
+ }
+ assertNoPrototypeKeys(input);
+ try {
+ return AuthoredColliderGeometryV1Schema.parse(input) as AuthoredColliderGeometryV1;
+ } catch (error) {
+ if (error instanceof ColliderCompileError) throw error;
+ throw new ColliderCompileError(
+ 'COLLIDER_AUTHORED_SUBMESH_INVALID',
+ error instanceof Error ? error.message : String(error),
+ );
+ }
+}
+
+export function parseColliderArtifactV1(input: unknown): ColliderArtifactV1 {
+ assertNoPrototypeKeys(input);
+ return ColliderArtifactV1Schema.parse(input);
+}
+
+function boxPrimitive(value: Aabb) {
+ const [x0, y0, z0] = value.min;
+ const [x1, y1, z1] = value.max;
+ return {
+ nodeName: 'generated:bounds-box',
+ positions: [
+ x0,
+ y0,
+ z0,
+ x1,
+ y0,
+ z0,
+ x1,
+ y1,
+ z0,
+ x0,
+ y1,
+ z0,
+ x0,
+ y0,
+ z1,
+ x1,
+ y0,
+ z1,
+ x1,
+ y1,
+ z1,
+ x0,
+ y1,
+ z1,
+ ],
+ indices: [
+ 0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 3, 7, 6, 3, 6, 2, 0, 4, 7, 0, 7, 3, 1,
+ 2, 6, 1, 6, 5,
+ ],
+ };
+}
+
+function boundsOfPrimitives(primitives: readonly { positions: readonly number[] }[]): Aabb {
+ const min: Vec3 = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];
+ const max: Vec3 = [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY];
+ for (const primitive of primitives) {
+ for (let offset = 0; offset < primitive.positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ min[axis] = Math.min(min[axis]!, primitive.positions[offset + axis]!);
+ max[axis] = Math.max(max[axis]!, primitive.positions[offset + axis]!);
+ }
+ }
+ }
+ return { min, max };
+}
+
+export function compileColliderArtifactV1(
+ policyInput: unknown,
+ input: CompileColliderArtifactV1Input,
+): ColliderArtifactV1 {
+ const policy = parseColliderPolicyV1(policyInput);
+ const parsedBounds = bounds.parse(input.bounds);
+ const sourceArtifactSha256 = sha256.parse(input.sourceArtifactSha256);
+ let primitives: Array<{ nodeName: string; positions: number[]; indices: number[] }> = [];
+ if (policy.kind === 'bounds' || policy.kind === 'generated-mesh') {
+ primitives = [boxPrimitive(parsedBounds)];
+ } else if (policy.kind === 'authored-submesh') {
+ const available = new Map(
+ (input.authoredSubmeshes ?? []).map((entry) => [entry.nodeName, entry]),
+ );
+ const missing = policy.nodeNames.filter((nodeName) => !available.has(nodeName));
+ if (missing.length) {
+ throw new ColliderCompileError(
+ 'COLLIDER_AUTHORED_SUBMESH_MISSING',
+ `missing authored collider node(s): ${missing.join(', ')}`,
+ );
+ }
+ try {
+ primitives = [...policy.nodeNames].sort().map((nodeName) => {
+ const source = available.get(nodeName)!;
+ return primitive.parse({
+ nodeName,
+ positions: [...source.positions],
+ indices: [...source.indices],
+ });
+ });
+ } catch (error) {
+ throw new ColliderCompileError(
+ 'COLLIDER_AUTHORED_SUBMESH_INVALID',
+ error instanceof Error ? error.message : String(error),
+ );
+ }
+ }
+ const vertexCount = primitives.reduce((sum, entry) => sum + entry.positions.length / 3, 0);
+ const triangleCount = primitives.reduce((sum, entry) => sum + entry.indices.length / 3, 0);
+ if (
+ vertexCount > AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxVertices ||
+ triangleCount > AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1.maxTriangles
+ ) {
+ throw new ColliderCompileError(
+ 'COLLIDER_BUDGET_EXCEEDED',
+ 'collider exceeds node/vertex/triangle limits',
+ );
+ }
+ const artifactBounds = primitives.length ? boundsOfPrimitives(primitives) : parsedBounds;
+ return parseColliderArtifactV1({
+ schemaVersion: COLLIDER_ARTIFACT_V1_SCHEMA_VERSION,
+ transformFrame: 'asset-local',
+ sourceArtifactSha256,
+ policy,
+ bounds: artifactBounds,
+ primitives,
+ });
+}
+
+export function canonicalColliderArtifactV1Json(input: unknown): string {
+ return canonicalContractJson(parseColliderArtifactV1(input));
+}
+
+export function encodeColliderArtifactV1(input: unknown): Uint8Array {
+ return new TextEncoder().encode(canonicalColliderArtifactV1Json(input));
+}
+
+export function decodeColliderArtifactV1(bytes: Uint8Array): ColliderArtifactV1 {
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
+ const artifact = parseColliderArtifactV1(JSON.parse(text));
+ if (canonicalColliderArtifactV1Json(artifact) !== text) {
+ throw new TypeError('collider artifact bytes are not canonical');
+ }
+ return artifact;
+}
+
+export function hashColliderArtifactV1(input: unknown): Promise<`sha256:${string}`> {
+ return sha256ContractBytes(encodeColliderArtifactV1(input));
+}
+
+export interface ColliderWorldTransformV1 {
+ position: Vec3;
+ rotationYDeg: number;
+ uniformScale: number;
+}
+
+export function worldColliderAabbV1(input: unknown, transform: ColliderWorldTransformV1): Aabb {
+ const artifact = parseColliderArtifactV1(input);
+ if (
+ !Number.isFinite(transform.rotationYDeg) ||
+ !Number.isFinite(transform.uniformScale) ||
+ transform.uniformScale <= 0
+ ) {
+ throw new TypeError('collider transform must have finite rotation and positive scale');
+ }
+ if (
+ transform.position.length !== 3 ||
+ transform.position.some((entry) => !Number.isFinite(entry))
+ ) {
+ throw new TypeError('collider transform position must be finite');
+ }
+ return worldAabbFromLocal(
+ artifact.bounds.min,
+ artifact.bounds.max,
+ transform.position,
+ transform.rotationYDeg,
+ transform.uniformScale,
+ );
+}
diff --git a/src/composer/contract-utils.ts b/src/composer/contract-utils.ts
new file mode 100644
index 00000000..8206568d
--- /dev/null
+++ b/src/composer/contract-utils.ts
@@ -0,0 +1,52 @@
+const FORBIDDEN_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
+
+/** Fail closed before schema parsing so prototype-shaped input is never normalized away. */
+export function assertNoPrototypeKeys(value: unknown, path = '$'): void {
+ if (value === null || typeof value !== 'object') return;
+ if (Array.isArray(value)) {
+ for (const [index, entry] of value.entries()) {
+ assertNoPrototypeKeys(entry, `${path}[${index}]`);
+ }
+ return;
+ }
+ for (const key of Object.keys(value)) {
+ if (FORBIDDEN_KEYS.has(key)) throw new TypeError(`${path}.${key} is forbidden`);
+ assertNoPrototypeKeys((value as Record<string, unknown>)[key], `${path}.${key}`);
+ }
+}
+
+export function canonicalContractJson(value: unknown): string {
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') {
+ return JSON.stringify(value);
+ }
+ if (typeof value === 'number') {
+ if (!Number.isFinite(value)) throw new TypeError('canonical JSON requires finite numbers');
+ return JSON.stringify(value);
+ }
+ if (Array.isArray(value)) return `[${value.map(canonicalContractJson).join(',')}]`;
+ if (typeof value === 'object') {
+ const record = value as Record<string, unknown>;
+ return `{${Object.keys(record)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${canonicalContractJson(record[key])}`)
+ .join(',')}}`;
+ }
+ throw new TypeError(`unsupported canonical JSON value: ${typeof value}`);
+}
+
+export async function sha256ContractBytes(bytes: Uint8Array): Promise<`sha256:${string}`> {
+ 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 `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
+}
+
+export async function sha256ContractJson(value: unknown): Promise<`sha256:${string}`> {
+ return sha256ContractBytes(new TextEncoder().encode(canonicalContractJson(value)));
+}
+
+export function sameCanonicalContract(a: unknown, b: unknown): boolean {
+ return canonicalContractJson(a) === canonicalContractJson(b);
+}
diff --git a/src/composer/index.ts b/src/composer/index.ts
index b70b0293..733135cb 100644
--- a/src/composer/index.ts
+++ b/src/composer/index.ts
@@ -5,11 +5,15 @@
* top of these.
*/
export * from './dsl';
+export * from './collision';
export * from './ground';
export * from './layout';
export * from './model';
export * from './overlap';
+export * from './presentation';
+export * from './reachability';
export * from './render-port';
export * from './terrain';
export * from './world-document';
export * from './world-integration';
+export * from './world-package';
diff --git a/src/composer/phase2-contracts.test.ts b/src/composer/phase2-contracts.test.ts
new file mode 100644
index 00000000..0b90f72d
--- /dev/null
+++ b/src/composer/phase2-contracts.test.ts
@@ -0,0 +1,580 @@
+import { describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import {
+ AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1,
+ AUTHORED_COLLIDER_GEOMETRY_V1_SCHEMA_VERSION,
+ COLLIDER_ARTIFACT_V1_SCHEMA_VERSION,
+ PRESENTATION_DOCUMENT_V1_SCHEMA_VERSION,
+ WORLD_PACKAGE_V2_SCHEMA_VERSION,
+ canonicalPresentationDocumentV1Json,
+ compileColliderArtifactV1,
+ createHeightfieldArtifactV1,
+ createWorldPackageV2,
+ decodeColliderArtifactV1,
+ encodeColliderArtifactV1,
+ hashColliderArtifactV1,
+ hashHeightfieldArtifactV1,
+ hashPresentationDocumentV1,
+ hashWorldPackageV2,
+ parseAuthoredColliderGeometryV1,
+ parseColliderPolicyV1,
+ parsePresentationDocumentV1,
+ parseWorldDocumentV2,
+ parseWorldPackageV2,
+ setWorldPresentationV1,
+ validatePresentationReceiptV1,
+ validateWorldPackageV2,
+ validateWorldPackageArtifactBytesV2,
+ validateWorldReachabilityV1,
+ worldColliderAabbV1,
+ type PresentationDocumentV1,
+ type WorldDocumentV2,
+} from './index';
+
+const A = 'a'.repeat(64);
+const B = 'b'.repeat(64);
+
+function world(): WorldDocumentV2 {
+ return {
+ schemaVersion: 'kiln.world.v2',
+ worldId: 'phase2-fixture',
+ name: 'Phase 2 Fixture',
+ seed: 7,
+ assets: [
+ {
+ refId: 'asset:wall',
+ generationId: 'wall',
+ artifactSha256: A,
+ bounds: { min: [-0.5, 0, -2], max: [0.5, 2, 2] },
+ },
+ ],
+ objects: [
+ {
+ id: 'wall-1',
+ assetRefId: 'asset:wall',
+ transform: { position: [5, 0, 5], rotationYDeg: 90, uniformScale: 2 },
+ role: 'support',
+ collision: { policy: 'bounds' },
+ provenance: { sourceStatementId: 'fixture:wall' },
+ },
+ ],
+ environment: { lightingPresetId: 'neutral-studio-v1', groundPaint: [] },
+ terrain: { kind: 'flat', height: 0 },
+ authored: { zones: [], paths: [], sockets: [] },
+ collisionArtifacts: [],
+ spawns: [
+ { id: 'start', position: [1, 0, 1], rotationYDeg: 0, clearanceRadius: 0.4 },
+ { id: 'goal', position: [9, 0, 9], rotationYDeg: 0, clearanceRadius: 0.4 },
+ ],
+ runtimePolicy: { mode: 'static-explore' },
+ provenance: { source: 'composer-v2' },
+ };
+}
+
+function presentation(): PresentationDocumentV1 {
+ return {
+ schemaVersion: PRESENTATION_DOCUMENT_V1_SCHEMA_VERSION,
+ grid: { columns: 2, rows: 1, cellWidth: 320, cellHeight: 180 },
+ lightingPresetId: 'neutral-studio-v1',
+ artifactBinding: { kind: 'world', sha256: `sha256:${A}` },
+ receiptPolicy: { requirePerCameraOutputSha256: true, requireOutputSetSha256: true },
+ cameras: [
+ {
+ id: 'front',
+ cell: { column: 0, row: 0 },
+ position: [0, 4, 10],
+ target: [0, 1, 0],
+ up: [0, 1, 0],
+ fovDeg: 50,
+ aspect: 16 / 9,
+ near: 0.1,
+ far: 100,
+ },
+ {
+ id: 'right',
+ cell: { column: 1, row: 0 },
+ position: [10, 4, 0],
+ target: [0, 1, 0],
+ up: [0, 1, 0],
+ fovDeg: 50,
+ aspect: 16 / 9,
+ near: 0.1,
+ far: 100,
+ },
+ ],
+ };
+}
+
+function presentationParameters() {
+ const { artifactBinding: _artifactBinding, ...parameters } = presentation();
+ return parameters;
+}
+
+describe('C5.1/C5.2 strict deterministic collider artifacts', () => {
+ test('freezes four policies, canonical bytes, and asset-local/world transform parity', async () => {
+ for (const kind of ['none', 'bounds', 'authored-submesh', 'generated-mesh'] as const) {
+ const policy =
+ kind === 'authored-submesh'
+ ? { kind, transformFrame: 'asset-local' as const, nodeNames: ['Collider_Main'] }
+ : kind === 'generated-mesh'
+ ? { kind, transformFrame: 'asset-local' as const, method: 'bounds-box' as const }
+ : { kind, transformFrame: 'asset-local' as const };
+ expect(parseColliderPolicyV1(policy)).toEqual(policy);
+ }
+
+ const artifact = compileColliderArtifactV1(
+ { kind: 'generated-mesh', transformFrame: 'asset-local', method: 'bounds-box' },
+ {
+ sourceArtifactSha256: `sha256:${A}`,
+ bounds: { min: [-1, 0, -2], max: [1, 3, 2] },
+ },
+ );
+ expect(artifact.schemaVersion).toBe(COLLIDER_ARTIFACT_V1_SCHEMA_VERSION);
+ expect(encodeColliderArtifactV1(artifact)).toEqual(encodeColliderArtifactV1(artifact));
+ expect(decodeColliderArtifactV1(encodeColliderArtifactV1(artifact))).toEqual(artifact);
+ expect(await hashColliderArtifactV1(artifact)).toMatch(/^sha256:[0-9a-f]{64}$/);
+ const worldBounds = worldColliderAabbV1(artifact, {
+ position: [5, 1, -3],
+ rotationYDeg: 90,
+ uniformScale: 2,
+ });
+ expect(worldBounds.min).toEqual([1, 1, -5]);
+ expect(worldBounds.max[0]).toBe(9);
+ expect(worldBounds.max[1]).toBe(7);
+ expect(worldBounds.max[2]).toBeCloseTo(-1, 12);
+ });
+
+ test('rejects unknown keys, prototype keys, missing authored submeshes, and invalid triangles', () => {
+ expect(() =>
+ parseColliderPolicyV1({
+ kind: 'bounds',
+ transformFrame: 'asset-local',
+ extra: true,
+ }),
+ ).toThrow();
+ const forged = Object.create(null) as Record<string, unknown>;
+ forged.kind = 'bounds';
+ forged.transformFrame = 'asset-local';
+ Object.defineProperty(forged, '__proto__', {
+ value: 'forged',
+ enumerable: true,
+ });
+ expect(() => parseColliderPolicyV1(forged)).toThrow();
+ expect(() =>
+ compileColliderArtifactV1(
+ { kind: 'authored-submesh', transformFrame: 'asset-local', nodeNames: ['Missing'] },
+ {
+ sourceArtifactSha256: `sha256:${A}`,
+ bounds: { min: [0, 0, 0], max: [1, 1, 1] },
+ authoredSubmeshes: [],
+ },
+ ),
+ ).toThrow('COLLIDER_AUTHORED_SUBMESH_MISSING');
+ expect(() =>
+ compileColliderArtifactV1(
+ { kind: 'authored-submesh', transformFrame: 'asset-local', nodeNames: ['Collider_Main'] },
+ {
+ sourceArtifactSha256: `sha256:${A}`,
+ bounds: { min: [0, 0, 0], max: [1, 1, 1] },
+ authoredSubmeshes: [
+ {
+ nodeName: 'Collider_Main',
+ positions: [0, 0, 0, 1, 0, 0],
+ indices: [0, 1, 2],
+ },
+ ],
+ },
+ ),
+ ).toThrow('COLLIDER_AUTHORED_SUBMESH_INVALID');
+ });
+
+ test('strictly bounds host-resolved GLB node geometry in the asset-local frame', () => {
+ const resolved = parseAuthoredColliderGeometryV1({
+ schemaVersion: AUTHORED_COLLIDER_GEOMETRY_V1_SCHEMA_VERSION,
+ sourceArtifactSha256: `sha256:${A}`,
+ transformFrame: 'asset-local',
+ submeshes: [
+ {
+ nodeName: 'Collider_Main',
+ positions: [-1, 0, -2, 1, 0, -2, 0, 3, 2],
+ indices: [0, 1, 2],
+ },
+ ],
+ });
+ expect(resolved.submeshes[0]?.nodeName).toBe('Collider_Main');
+ expect(AUTHORED_COLLIDER_GEOMETRY_LIMITS_V1).toEqual({
+ maxNodes: 64,
+ maxVertices: 65_536,
+ maxTriangles: 65_536,
+ });
+ const secondSubmesh = {
+ nodeName: 'Collider_Second',
+ positions: [2, 0, 0, 3, 0, 0, 2, 1, 0],
+ indices: [0, 1, 2],
+ };
+ const authoredPolicy = {
+ kind: 'authored-submesh' as const,
+ transformFrame: 'asset-local' as const,
+ nodeNames: ['Collider_Second', 'Collider_Main'],
+ };
+ const compileResolved = (submeshes: typeof resolved.submeshes) =>
+ compileColliderArtifactV1(authoredPolicy, {
+ sourceArtifactSha256: resolved.sourceArtifactSha256,
+ bounds: { min: [-1, 0, -2], max: [3, 3, 2] },
+ authoredSubmeshes: submeshes,
+ });
+ const ordered = compileResolved([...resolved.submeshes, secondSubmesh]);
+ const reversed = compileResolved([secondSubmesh, ...resolved.submeshes]);
+ expect(ordered.primitives.map(({ nodeName }) => nodeName)).toEqual([
+ 'Collider_Main',
+ 'Collider_Second',
+ ]);
+ expect(encodeColliderArtifactV1(ordered)).toEqual(encodeColliderArtifactV1(reversed));
+ expect(() =>
+ parseAuthoredColliderGeometryV1({ ...resolved, sourceUrl: 'file:///secret/model.glb' }),
+ ).toThrow();
+ expect(() =>
+ parseAuthoredColliderGeometryV1({ ...resolved, transformFrame: 'world' }),
+ ).toThrow();
+ const forged = { ...resolved } as Record<string, unknown>;
+ Object.defineProperty(forged, '__proto__', {
+ value: 'forged',
+ enumerable: true,
+ });
+ expect(() => parseAuthoredColliderGeometryV1(forged)).toThrow(/forbidden/);
+ expect(() =>
+ parseAuthoredColliderGeometryV1({
+ ...resolved,
+ submeshes: [
+ {
+ nodeName: 'Collider_Main',
+ positions: Array.from({ length: 65_537 * 3 }, () => 0),
+ indices: [0, 1, 2],
+ },
+ ],
+ }),
+ ).toThrow('COLLIDER_BUDGET_EXCEEDED');
+ });
+});
+
+describe('C5.3/C5.4 bounded spawn and critical-path reachability', () => {
+ test('finds a deterministic route around transformed bounds and reports exact budgets', async () => {
+ const report = await validateWorldReachabilityV1(world(), {
+ schemaVersion: 'kiln.reachability.v1',
+ grid: { origin: [0, 0], cellSize: 1, width: 11, height: 11 },
+ agent: { radius: 0.4, maxStepHeight: 0.5, maxSlopeDeg: 45 },
+ budget: { maxVisitedCells: 121, maxColliderTests: 1024 },
+ criticalPaths: [
+ {
+ id: 'start-to-goal',
+ from: { kind: 'spawn', id: 'start' },
+ to: { kind: 'spawn', id: 'goal' },
+ },
+ ],
+ });
+ expect(report.valid).toBe(true);
+ expect(report.paths).toHaveLength(1);
+ expect(report.paths[0]?.status).toBe('reachable');
+ expect(report.paths[0]?.cells[0]).toEqual([1, 1]);
+ expect(report.paths[0]?.cells.at(-1)).toEqual([9, 9]);
+ expect(report.visitedCells).toBeLessThanOrEqual(121);
+ });
+
+ test('fails closed on a blocked endpoint and on exhausted traversal budget', async () => {
+ const blocked = world();
+ blocked.spawns[0]!.position = [5, 0, 5];
+ const request = {
+ schemaVersion: 'kiln.reachability.v1' as const,
+ grid: { origin: [0, 0] as [number, number], cellSize: 1, width: 11, height: 11 },
+ agent: { radius: 0.4, maxStepHeight: 0.5, maxSlopeDeg: 45 },
+ budget: { maxVisitedCells: 121, maxColliderTests: 1024 },
+ criticalPaths: [
+ {
+ id: 'route',
+ from: { kind: 'spawn' as const, id: 'start' },
+ to: { kind: 'spawn' as const, id: 'goal' },
+ },
+ ],
+ };
+ expect((await validateWorldReachabilityV1(blocked, request)).issues[0]?.code).toBe(
+ 'ENDPOINT_BLOCKED',
+ );
+ expect(
+ (
+ await validateWorldReachabilityV1(world(), {
+ ...request,
+ budget: { ...request.budget, maxVisitedCells: 2 },
+ })
+ ).issues.some((issue) => issue.code === 'VISIT_BUDGET_EXCEEDED'),
+ ).toBe(true);
+ });
+
+ test('hash-binds canonical collider artifacts before using them for traversal', async () => {
+ const artifact = compileColliderArtifactV1(
+ { kind: 'generated-mesh', transformFrame: 'asset-local', method: 'bounds-box' },
+ {
+ sourceArtifactSha256: `sha256:${A}`,
+ bounds: { min: [-0.5, 0, -2], max: [0.5, 2, 2] },
+ },
+ );
+ const hash = await hashColliderArtifactV1(artifact);
+ const canonical = world();
+ canonical.collisionArtifacts = [
+ {
+ refId: 'collision:wall',
+ artifact: {
+ uri: 'colliders/wall.collider.json',
+ sha256: hash.slice('sha256:'.length),
+ mediaType: 'application/vnd.kiln.collider+json',
+ },
+ },
+ ];
+ canonical.objects[0]!.collision = {
+ policy: 'artifact',
+ artifactRefId: 'collision:wall',
+ };
+ const request = {
+ schemaVersion: 'kiln.reachability.v1' as const,
+ grid: { origin: [0, 0] as [number, number], cellSize: 1, width: 11, height: 11 },
+ agent: { radius: 0.4, maxStepHeight: 0.5, maxSlopeDeg: 45 },
+ budget: { maxVisitedCells: 121, maxColliderTests: 1024 },
+ criticalPaths: [
+ {
+ id: 'route',
+ from: { kind: 'spawn' as const, id: 'start' },
+ to: { kind: 'spawn' as const, id: 'goal' },
+ },
+ ],
+ };
+ expect(
+ (
+ await validateWorldReachabilityV1(canonical, request, {
+ collidersByRefId: { 'collision:wall': artifact },
+ })
+ ).valid,
+ ).toBe(true);
+ const forged = structuredClone(artifact);
+ forged.sourceArtifactSha256 = `sha256:${B}`;
+ expect(
+ (
+ await validateWorldReachabilityV1(canonical, request, {
+ collidersByRefId: { 'collision:wall': forged },
+ })
+ ).issues[0]?.code,
+ ).toBe('COLLIDER_ARTIFACT_HASH_MISMATCH');
+ });
+
+ test('samples only the hash-bound canonical heightfield for step and slope checks', async () => {
+ const heightfield = createHeightfieldArtifactV1({
+ seed: 7,
+ origin: [0, 0],
+ cellSize: 1,
+ width: 11,
+ height: 11,
+ baseHeight: 0,
+ amplitude: 0,
+ frequency: 0.25,
+ stamps: [],
+ });
+ const terrainHash = await hashHeightfieldArtifactV1(heightfield);
+ const terrainWorld = world();
+ terrainWorld.terrain = {
+ kind: 'heightfield',
+ artifact: {
+ uri: 'terrain/world.heightfield.json',
+ sha256: terrainHash,
+ },
+ };
+ const request = {
+ schemaVersion: 'kiln.reachability.v1' as const,
+ grid: { origin: [0, 0] as [number, number], cellSize: 1, width: 11, height: 11 },
+ agent: { radius: 0.4, maxStepHeight: 0.5, maxSlopeDeg: 45 },
+ budget: { maxVisitedCells: 121, maxColliderTests: 1024 },
+ criticalPaths: [
+ {
+ id: 'route',
+ from: { kind: 'spawn' as const, id: 'start' },
+ to: { kind: 'spawn' as const, id: 'goal' },
+ },
+ ],
+ };
+ expect((await validateWorldReachabilityV1(terrainWorld, request, { heightfield })).valid).toBe(
+ true,
+ );
+ const drifted = structuredClone(heightfield);
+ drifted.heights[0] = 1;
+ expect(
+ (
+ await validateWorldReachabilityV1(terrainWorld, request, {
+ heightfield: drifted,
+ })
+ ).issues[0]?.code,
+ ).toBe('TERRAIN_ARTIFACT_HASH_MISMATCH');
+ });
+});
+
+describe('C5.6/C5.7 strict presentation contract and world persistence', () => {
+ test('canonicalizes ordered camera cells and validates an exact receipt binding', async () => {
+ const doc = parsePresentationDocumentV1(presentation());
+ expect(JSON.parse(canonicalPresentationDocumentV1Json(doc))).toEqual(doc);
+ expect(await hashPresentationDocumentV1(doc)).toMatch(/^sha256:[0-9a-f]{64}$/);
+ expect(
+ validatePresentationReceiptV1(doc, {
+ worldHash: `sha256:${A}`,
+ cameras: doc.cameras.map(({ id: _id, cell: _cell, ...camera }) => camera),
+ width: 320,
+ height: 180,
+ lightingPresetId: 'neutral-studio-v1',
+ backend: 'webgpu',
+ rendererId: 'gpu:test',
+ perCameraOutputSha256: [`sha256:${A}`, `sha256:${B}`],
+ outputSetSha256: `sha256:${B}`,
+ outputSha256: `sha256:${B}`,
+ }),
+ ).toEqual({ ok: true });
+ expect(setWorldPresentationV1(world(), presentationParameters()).presentation).toEqual(
+ presentationParameters(),
+ );
+ });
+
+ test('rejects duplicate cells, aspect drift, unknown fields, and receipt camera drift', () => {
+ const duplicate = presentation();
+ duplicate.cameras[1]!.cell = { column: 0, row: 0 };
+ expect(() => parsePresentationDocumentV1(duplicate)).toThrow();
+ const badAspect = presentation();
+ badAspect.cameras[0]!.aspect = 1;
+ expect(() => parsePresentationDocumentV1(badAspect)).toThrow();
+ expect(() => parsePresentationDocumentV1({ ...presentation(), shader: 'raw' })).toThrow();
+ const doc = presentation();
+ expect(
+ validatePresentationReceiptV1(doc, {
+ worldHash: `sha256:${A}`,
+ cameras: doc.cameras.map(({ id: _id, cell: _cell, ...camera }) => camera).reverse(),
+ width: 320,
+ height: 180,
+ lightingPresetId: 'neutral-studio-v1',
+ backend: 'webgpu',
+ rendererId: 'gpu:test',
+ outputSha256: `sha256:${B}`,
+ }),
+ ).toEqual({ ok: false, reason: 'CAMERA_ORDER_MISMATCH' });
+ });
+});
+
+describe('C5.8 WorldPackageV2 closure', () => {
+ test('binds world, presentation, assets, runtime policy, and provenance deterministically', async () => {
+ const packageWorld = world();
+ packageWorld.collisionArtifacts = [
+ {
+ refId: 'collision:wall',
+ artifact: { uri: 'colliders/wall.collider.json', sha256: B },
+ },
+ ];
+ packageWorld.objects[0]!.collision = {
+ policy: 'artifact',
+ artifactRefId: 'collision:wall',
+ };
+ packageWorld.terrain = {
+ kind: 'heightfield',
+ artifact: { uri: 'terrain/world.heightfield.json', sha256: 'c'.repeat(64) },
+ };
+ const withPresentation = setWorldPresentationV1(packageWorld, presentationParameters());
+ const packageA = await createWorldPackageV2({ world: withPresentation });
+ const packageB = await createWorldPackageV2({ world: withPresentation });
+ expect(packageA).toEqual(packageB);
+ expect(packageA.schemaVersion).toBe(WORLD_PACKAGE_V2_SCHEMA_VERSION);
+ expect(packageA.artifacts.map((entry) => entry.path)).toEqual([
+ 'models/wall.glb',
+ 'colliders/wall.collider.json',
+ 'terrain/world.heightfield.json',
+ ]);
+ expect(packageA.runtimePolicy).toEqual({ mode: 'static-explore' });
+ expect(packageA.provenance.objectSources).toEqual([
+ { objectId: 'wall-1', sourceStatementId: 'fixture:wall' },
+ ]);
+ expect(await hashWorldPackageV2(packageA)).toMatch(/^sha256:[0-9a-f]{64}$/);
+ });
+
+ test('rejects hash drift, missing presentation, and arbitrary package paths', async () => {
+ await expect(createWorldPackageV2({ world: world() })).rejects.toThrow('presentation');
+ const built = await createWorldPackageV2({
+ world: setWorldPresentationV1(world(), presentationParameters()),
+ });
+ expect(() =>
+ parseWorldPackageV2({
+ ...built,
+ artifacts: [{ ...built.artifacts[0], path: '../escape.glb' }],
+ }),
+ ).toThrow();
+ await expect(validateWorldPackageV2({ ...built, worldSha256: `sha256:${B}` })).rejects.toThrow(
+ 'worldSha256',
+ );
+ });
+
+ test('rejects package-path aliases across model, terrain, and collider namespaces', async () => {
+ const collisionAlias = world();
+ collisionAlias.collisionArtifacts = [
+ {
+ refId: 'collision:wall',
+ artifact: { uri: 'models/wall.glb', sha256: B },
+ },
+ ];
+ collisionAlias.objects[0]!.collision = {
+ policy: 'artifact',
+ artifactRefId: 'collision:wall',
+ };
+ expect(() => parseWorldDocumentV2(collisionAlias)).toThrow(/duplicate package path/i);
+ await expect(
+ createWorldPackageV2({
+ world: { ...collisionAlias, presentation: presentationParameters() },
+ }),
+ ).rejects.toThrow(/duplicate package path/i);
+
+ const terrainAlias = world();
+ terrainAlias.terrain = {
+ kind: 'heightfield',
+ artifact: { uri: 'models/wall.glb', sha256: B },
+ };
+ expect(() => parseWorldDocumentV2(terrainAlias)).toThrow(/duplicate package path/i);
+
+ const packageWorld = world();
+ packageWorld.terrain = {
+ kind: 'heightfield',
+ artifact: { uri: 'terrain/world.heightfield.json', sha256: B },
+ };
+ const built = await createWorldPackageV2({
+ world: setWorldPresentationV1(packageWorld, presentationParameters()),
+ });
+ const forged = structuredClone(built);
+ forged.artifacts[1]!.path = forged.artifacts[0]!.path;
+ expect(() => parseWorldPackageV2(forged)).toThrow(/duplicate package path/i);
+ await expect(validateWorldPackageV2(forged)).rejects.toThrow(/duplicate package path/i);
+ });
+
+ test('verifies every exact artifact byte and refuses omissions, drift, or extras', async () => {
+ const assetBytes = new TextEncoder().encode('exact wall glb fixture');
+ const assetHash = createHash('sha256').update(assetBytes).digest('hex');
+ const exactWorld = world();
+ exactWorld.assets[0]!.artifactSha256 = assetHash;
+ const built = await createWorldPackageV2({
+ world: setWorldPresentationV1(exactWorld, presentationParameters()),
+ });
+ await expect(
+ validateWorldPackageArtifactBytesV2(built, {
+ 'models/wall.glb': assetBytes,
+ }),
+ ).resolves.toBeUndefined();
+ await expect(validateWorldPackageArtifactBytesV2(built, {})).rejects.toThrow('missing');
+ await expect(
+ validateWorldPackageArtifactBytesV2(built, {
+ 'models/wall.glb': new TextEncoder().encode('drift'),
+ }),
+ ).rejects.toThrow('hash mismatch');
+ await expect(
+ validateWorldPackageArtifactBytesV2(built, {
+ 'models/wall.glb': assetBytes,
+ 'extra.bin': assetBytes,
+ }),
+ ).rejects.toThrow('unexpected');
+ });
+});
diff --git a/src/composer/presentation-default.test.ts b/src/composer/presentation-default.test.ts
new file mode 100644
index 00000000..afd92e7f
--- /dev/null
+++ b/src/composer/presentation-default.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ DEFAULT_PRESENTATION_PARAMETERS_V1,
+ PRESENTATION_MAX_TOTAL_PIXELS_V1,
+ canonicalPresentationDocumentV1Json,
+ createDefaultPresentationDocumentV1,
+ createDefaultPresentationParametersV1,
+ parsePresentationDocumentV1,
+ parsePresentationParametersV1,
+} from './index';
+
+const WORLD_SHA256 = `sha256:${'a'.repeat(64)}` as const;
+
+describe('default PresentationDocumentV1', () => {
+ test('owns one strict, bounded, ordered neutral inspection presentation', () => {
+ const parameters = createDefaultPresentationParametersV1();
+
+ expect(parameters).toEqual(DEFAULT_PRESENTATION_PARAMETERS_V1);
+ expect(parameters).not.toBe(DEFAULT_PRESENTATION_PARAMETERS_V1);
+ expect(parsePresentationParametersV1(parameters)).toEqual(parameters);
+ expect(parameters).toMatchObject({
+ schemaVersion: 'kiln.presentation.v1',
+ grid: { columns: 3, rows: 1, cellWidth: 512, cellHeight: 512 },
+ lightingPresetId: 'neutral-studio-v1',
+ receiptPolicy: {
+ requirePerCameraOutputSha256: true,
+ requireOutputSetSha256: true,
+ },
+ });
+ expect(parameters.cameras.map(({ id, cell }) => ({ id, cell }))).toEqual([
+ { id: 'front-right', cell: { column: 0, row: 0 } },
+ { id: 'front-left', cell: { column: 1, row: 0 } },
+ { id: 'rear-overview', cell: { column: 2, row: 0 } },
+ ]);
+ expect(parameters.cameras).toHaveLength(3);
+ expect(parameters.cameras.every((camera) => camera.aspect === 1)).toBe(true);
+ });
+
+ test('returns fresh parameters while the exported default remains deeply frozen', () => {
+ expect(Object.isFrozen(DEFAULT_PRESENTATION_PARAMETERS_V1)).toBe(true);
+ expect(Object.isFrozen(DEFAULT_PRESENTATION_PARAMETERS_V1.grid)).toBe(true);
+ expect(Object.isFrozen(DEFAULT_PRESENTATION_PARAMETERS_V1.cameras)).toBe(true);
+ expect(Object.isFrozen(DEFAULT_PRESENTATION_PARAMETERS_V1.cameras[0])).toBe(true);
+ expect(Object.isFrozen(DEFAULT_PRESENTATION_PARAMETERS_V1.cameras[0]?.position)).toBe(true);
+
+ const first = createDefaultPresentationParametersV1();
+ first.cameras[0]!.position[0] = 999;
+ const second = createDefaultPresentationParametersV1();
+ expect(second.cameras[0]!.position[0]).not.toBe(999);
+ expect(second).toEqual(DEFAULT_PRESENTATION_PARAMETERS_V1);
+ });
+
+ test('binds the canonical document to exact world or GLB bytes deterministically', () => {
+ const worldA = createDefaultPresentationDocumentV1({
+ kind: 'world',
+ sha256: WORLD_SHA256,
+ });
+ const worldB = createDefaultPresentationDocumentV1({
+ kind: 'world',
+ sha256: WORLD_SHA256,
+ });
+ const glb = createDefaultPresentationDocumentV1({
+ kind: 'glb',
+ sha256: WORLD_SHA256,
+ });
+
+ expect(parsePresentationDocumentV1(worldA)).toEqual(worldA);
+ expect(worldA).toEqual(worldB);
+ expect(worldA).not.toBe(worldB);
+ expect(worldA.artifactBinding).toEqual({ kind: 'world', sha256: WORLD_SHA256 });
+ expect(glb.artifactBinding.kind).toBe('glb');
+ expect(canonicalPresentationDocumentV1Json(worldA)).toBe(
+ canonicalPresentationDocumentV1Json(worldB),
+ );
+ });
+
+ test('rejects malformed artifact bindings at the factory boundary', () => {
+ expect(() =>
+ createDefaultPresentationDocumentV1({ kind: 'world', sha256: 'not-a-hash' }),
+ ).toThrow();
+ expect(() =>
+ createDefaultPresentationDocumentV1({
+ kind: 'world',
+ sha256: WORLD_SHA256,
+ path: '../escape.glb',
+ }),
+ ).toThrow();
+ });
+
+ test('enforces the renderer-aligned aggregate camera pixel ceiling', () => {
+ const cameras = Array.from({ length: 12 }, (_, index) => ({
+ id: `camera-${index}`,
+ cell: { column: index % 4, row: Math.floor(index / 4) },
+ position: [index + 1, 2, 3] as [number, number, number],
+ target: [0, 0, 0] as [number, number, number],
+ up: [0, 1, 0] as [number, number, number],
+ fovDeg: 50,
+ aspect: 1,
+ near: 0.05,
+ far: 100,
+ }));
+ expect(PRESENTATION_MAX_TOTAL_PIXELS_V1).toBe(16_777_216);
+ expect(() =>
+ parsePresentationParametersV1({
+ ...createDefaultPresentationParametersV1(),
+ grid: { columns: 4, rows: 3, cellWidth: 4096, cellHeight: 4096 },
+ cameras,
+ }),
+ ).toThrow(/total pixel budget/i);
+ expect(
+ parsePresentationParametersV1({
+ ...createDefaultPresentationParametersV1(),
+ grid: { columns: 4, rows: 1, cellWidth: 2048, cellHeight: 2048 },
+ cameras: cameras.slice(0, 4).map((camera) => ({
+ ...camera,
+ cell: { column: camera.cell.column, row: 0 },
+ })),
+ }).cameras,
+ ).toHaveLength(4);
+ });
+});
diff --git a/src/composer/presentation.ts b/src/composer/presentation.ts
new file mode 100644
index 00000000..ff1c7396
--- /dev/null
+++ b/src/composer/presentation.ts
@@ -0,0 +1,309 @@
+import { z } from 'zod';
+import type { SceneRenderReceipt } from './render-port';
+import { assertNoPrototypeKeys, canonicalContractJson, sha256ContractJson } from './contract-utils';
+
+export const PRESENTATION_DOCUMENT_V1_SCHEMA_VERSION = 'kiln.presentation.v1' as const;
+/** Renderer-aligned ceiling across every requested camera frame. */
+export const PRESENTATION_MAX_TOTAL_PIXELS_V1 = 16_777_216;
+
+const finite = z.number().finite();
+const vec3 = z.tuple([finite, finite, finite]);
+const contentSha256 = z.string().regex(/^sha256:[0-9a-f]{64}$/);
+const id = z
+ .string()
+ .min(1)
+ .max(128)
+ .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/);
+
+const cameraSchema = z
+ .object({
+ id,
+ cell: z
+ .object({
+ column: z.number().int().min(0).max(11),
+ row: z.number().int().min(0).max(11),
+ })
+ .strict(),
+ position: vec3,
+ target: vec3,
+ up: vec3,
+ fovDeg: finite.gt(0).lt(180),
+ aspect: finite.positive(),
+ near: finite.positive(),
+ far: finite.positive(),
+ })
+ .strict()
+ .superRefine((camera, ctx) => {
+ if (camera.far <= camera.near) {
+ ctx.addIssue({ code: 'custom', path: ['far'], message: 'far must exceed near' });
+ }
+ const view = camera.target.map((entry, axis) => entry - camera.position[axis]!) as [
+ number,
+ number,
+ number,
+ ];
+ if (Math.hypot(...view) === 0) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['target'],
+ message: 'target must differ from position',
+ });
+ }
+ if (Math.hypot(...camera.up) === 0) {
+ ctx.addIssue({ code: 'custom', path: ['up'], message: 'up must be non-zero' });
+ }
+ const cross = [
+ view[1] * camera.up[2] - view[2] * camera.up[1],
+ view[2] * camera.up[0] - view[0] * camera.up[2],
+ view[0] * camera.up[1] - view[1] * camera.up[0],
+ ];
+ if (Math.hypot(...cross) <= Math.hypot(...view) * Math.hypot(...camera.up) * 1e-9) {
+ ctx.addIssue({ code: 'custom', path: ['up'], message: 'up must not be collinear with view' });
+ }
+ });
+
+const presentationParameterFields = {
+ schemaVersion: z.literal(PRESENTATION_DOCUMENT_V1_SCHEMA_VERSION),
+ grid: z
+ .object({
+ columns: z.number().int().min(1).max(4),
+ rows: z.number().int().min(1).max(3),
+ cellWidth: z.number().int().min(1).max(4096),
+ cellHeight: z.number().int().min(1).max(4096),
+ })
+ .strict(),
+ lightingPresetId: id,
+ receiptPolicy: z
+ .object({
+ requirePerCameraOutputSha256: z.boolean(),
+ requireOutputSetSha256: z.boolean(),
+ })
+ .strict(),
+ cameras: z.array(cameraSchema).min(1).max(12),
+};
+
+type PresentationShape = {
+ grid: { columns: number; rows: number; cellWidth: number; cellHeight: number };
+ cameras: Array<{ id: string; cell: { column: number; row: number }; aspect: number }>;
+};
+
+function refinePresentation(document: PresentationShape, ctx: z.RefinementCtx): void {
+ if (document.cameras.length > document.grid.columns * document.grid.rows) {
+ ctx.addIssue({ code: 'custom', path: ['cameras'], message: 'camera count exceeds grid cells' });
+ }
+ const totalPixels = document.cameras.length * document.grid.cellWidth * document.grid.cellHeight;
+ if (totalPixels > PRESENTATION_MAX_TOTAL_PIXELS_V1) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['grid'],
+ message: `presentation total pixel budget ${totalPixels} exceeds ${PRESENTATION_MAX_TOTAL_PIXELS_V1}`,
+ });
+ }
+ const ids = new Set<string>();
+ const cells = new Set<string>();
+ const cellAspect = document.grid.cellWidth / document.grid.cellHeight;
+ for (let index = 0; index < document.cameras.length; index++) {
+ const camera = document.cameras[index]!;
+ if (ids.has(camera.id)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['cameras', index, 'id'],
+ message: 'camera id must be unique',
+ });
+ }
+ ids.add(camera.id);
+ if (camera.cell.column >= document.grid.columns || camera.cell.row >= document.grid.rows) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['cameras', index, 'cell'],
+ message: 'camera cell is outside grid',
+ });
+ }
+ const cell = `${camera.cell.column}:${camera.cell.row}`;
+ if (cells.has(cell)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['cameras', index, 'cell'],
+ message: 'camera cell must be unique',
+ });
+ }
+ cells.add(cell);
+ if (Math.abs(camera.aspect - cellAspect) > Math.max(1, cellAspect) * 1e-9) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['cameras', index, 'aspect'],
+ message: 'aspect must equal grid cell aspect',
+ });
+ }
+ }
+}
+
+/** Model-authorable parameters persisted in WorldDocumentV2; no self-referential hash. */
+export const PresentationParametersV1Schema = z
+ .object(presentationParameterFields)
+ .strict()
+ .superRefine(refinePresentation);
+
+/** Capture-time presentation contract bound to an immutable world/GLB input. */
+export const PresentationDocumentV1Schema = z
+ .object({
+ ...presentationParameterFields,
+ artifactBinding: z.object({ kind: z.enum(['world', 'glb']), sha256: contentSha256 }).strict(),
+ })
+ .strict()
+ .superRefine(refinePresentation);
+
+export type PresentationParametersV1 = z.infer<typeof PresentationParametersV1Schema>;
+export type PresentationDocumentV1 = z.infer<typeof PresentationDocumentV1Schema>;
+
+export function parsePresentationParametersV1(input: unknown): PresentationParametersV1 {
+ assertNoPrototypeKeys(input);
+ return PresentationParametersV1Schema.parse(input);
+}
+
+export function parsePresentationDocumentV1(input: unknown): PresentationDocumentV1 {
+ assertNoPrototypeKeys(input);
+ return PresentationDocumentV1Schema.parse(input);
+}
+
+function deepFreeze<T>(value: T): T {
+ if (value === null || typeof value !== 'object' || Object.isFrozen(value)) return value;
+ for (const nested of Object.values(value)) deepFreeze(nested);
+ return Object.freeze(value);
+}
+
+/**
+ * Engine-owned baseline for new Composer worlds. The ordered cameras mirror the
+ * three bounded inspection directions used by the canonical scene renderer,
+ * while exact output hashes remain mandatory. Hosts should persist a fresh copy
+ * from {@link createDefaultPresentationParametersV1} rather than duplicating
+ * these values.
+ */
+export const DEFAULT_PRESENTATION_PARAMETERS_V1 = deepFreeze(
+ parsePresentationParametersV1({
+ schemaVersion: PRESENTATION_DOCUMENT_V1_SCHEMA_VERSION,
+ grid: { columns: 3, rows: 1, cellWidth: 512, cellHeight: 512 },
+ lightingPresetId: 'neutral-studio-v1',
+ receiptPolicy: {
+ requirePerCameraOutputSha256: true,
+ requireOutputSetSha256: true,
+ },
+ cameras: [
+ {
+ id: 'front-right',
+ cell: { column: 0, row: 0 },
+ position: [10, 7, 10],
+ target: [0, 0, 0],
+ up: [0, 1, 0],
+ fovDeg: 50,
+ aspect: 1,
+ near: 0.05,
+ far: 100,
+ },
+ {
+ id: 'front-left',
+ cell: { column: 1, row: 0 },
+ position: [-10, 5.5, 10],
+ target: [0, 0, 0],
+ up: [0, 1, 0],
+ fovDeg: 50,
+ aspect: 1,
+ near: 0.05,
+ far: 100,
+ },
+ {
+ id: 'rear-overview',
+ cell: { column: 2, row: 0 },
+ position: [2, 11, -10],
+ target: [0, 0, 0],
+ up: [0, 1, 0],
+ fovDeg: 50,
+ aspect: 1,
+ near: 0.05,
+ far: 100,
+ },
+ ],
+ }),
+);
+
+/** Return an independently mutable, strictly parsed copy of the Engine default. */
+export function createDefaultPresentationParametersV1(): PresentationParametersV1 {
+ return parsePresentationParametersV1(DEFAULT_PRESENTATION_PARAMETERS_V1);
+}
+
+/** Bind the Engine default presentation to exact canonical world or GLB bytes. */
+export function createDefaultPresentationDocumentV1(
+ artifactBinding: unknown,
+): PresentationDocumentV1 {
+ return parsePresentationDocumentV1({
+ ...createDefaultPresentationParametersV1(),
+ artifactBinding,
+ });
+}
+
+export function canonicalPresentationDocumentV1Json(input: unknown): string {
+ return canonicalContractJson(parsePresentationDocumentV1(input));
+}
+
+export function hashPresentationDocumentV1(input: unknown): Promise<`sha256:${string}`> {
+ return sha256ContractJson(parsePresentationDocumentV1(input));
+}
+
+export type PresentationReceiptReasonV1 =
+ | 'INPUT_HASH_MISMATCH'
+ | 'OUTPUT_SIZE_MISMATCH'
+ | 'LIGHTING_PROFILE_MISMATCH'
+ | 'CAMERA_ORDER_MISMATCH'
+ | 'PER_CAMERA_HASHES_REQUIRED'
+ | 'OUTPUT_SET_HASH_REQUIRED';
+
+export type PresentationReceiptValidationV1 =
+ | { ok: true }
+ | { ok: false; reason: PresentationReceiptReasonV1 };
+
+function sameNumbers(a: readonly number[], b: readonly number[]): boolean {
+ return a.length === b.length && a.every((value, index) => value === b[index]);
+}
+
+export function validatePresentationReceiptV1(
+ documentInput: unknown,
+ receipt: SceneRenderReceipt,
+): PresentationReceiptValidationV1 {
+ const document = parsePresentationDocumentV1(documentInput);
+ if (receipt.worldHash !== document.artifactBinding.sha256) {
+ return { ok: false, reason: 'INPUT_HASH_MISMATCH' };
+ }
+ if (receipt.width !== document.grid.cellWidth || receipt.height !== document.grid.cellHeight) {
+ return { ok: false, reason: 'OUTPUT_SIZE_MISMATCH' };
+ }
+ if (receipt.lightingPresetId !== document.lightingPresetId) {
+ return { ok: false, reason: 'LIGHTING_PROFILE_MISMATCH' };
+ }
+ if (
+ receipt.cameras.length !== document.cameras.length ||
+ receipt.cameras.some((actual, index) => {
+ const expected = document.cameras[index]!;
+ return !(
+ sameNumbers(actual.position, expected.position) &&
+ sameNumbers(actual.target, expected.target) &&
+ sameNumbers(actual.up, expected.up) &&
+ actual.fovDeg === expected.fovDeg &&
+ actual.aspect === expected.aspect &&
+ actual.near === expected.near &&
+ actual.far === expected.far
+ );
+ })
+ ) {
+ return { ok: false, reason: 'CAMERA_ORDER_MISMATCH' };
+ }
+ if (
+ document.receiptPolicy.requirePerCameraOutputSha256 &&
+ receipt.perCameraOutputSha256?.length !== document.cameras.length
+ ) {
+ return { ok: false, reason: 'PER_CAMERA_HASHES_REQUIRED' };
+ }
+ if (document.receiptPolicy.requireOutputSetSha256 && !receipt.outputSetSha256) {
+ return { ok: false, reason: 'OUTPUT_SET_HASH_REQUIRED' };
+ }
+ return { ok: true };
+}
diff --git a/src/composer/reachability.ts b/src/composer/reachability.ts
new file mode 100644
index 00000000..e2702148
--- /dev/null
+++ b/src/composer/reachability.ts
@@ -0,0 +1,407 @@
+import { z } from 'zod';
+import {
+ hashHeightfieldArtifactV1,
+ heightfieldGround,
+ type HeightfieldArtifactV1,
+} from './terrain';
+import {
+ hashColliderArtifactV1,
+ parseColliderArtifactV1,
+ worldColliderAabbV1,
+ type ColliderArtifactV1,
+} from './collision';
+import { worldAabbFromLocal, type Aabb } from './overlap';
+import { canonicalContractJson, assertNoPrototypeKeys, sha256ContractJson } from './contract-utils';
+import { hashWorldDocumentV2, parseWorldDocumentV2, type WorldDocumentV2 } from './world-document';
+
+export const REACHABILITY_DOCUMENT_V1_SCHEMA_VERSION = 'kiln.reachability.v1' as const;
+export const REACHABILITY_REPORT_V1_SCHEMA_VERSION = 'kiln.reachability-report.v1' as const;
+
+const finite = z.number().finite();
+const vec2 = z.tuple([finite, finite]);
+const id = z.string().min(1).max(256);
+const endpoint = z.discriminatedUnion('kind', [
+ z.object({ kind: z.literal('spawn'), id }).strict(),
+ z.object({ kind: z.literal('socket'), id }).strict(),
+ z.object({ kind: z.literal('point'), position: z.tuple([finite, finite, finite]) }).strict(),
+]);
+
+export const ReachabilityDocumentV1Schema = z
+ .object({
+ schemaVersion: z.literal(REACHABILITY_DOCUMENT_V1_SCHEMA_VERSION),
+ grid: z
+ .object({
+ origin: vec2,
+ cellSize: finite.positive(),
+ width: z.number().int().min(2).max(512),
+ height: z.number().int().min(2).max(512),
+ })
+ .strict(),
+ agent: z
+ .object({
+ radius: finite.nonnegative().max(100),
+ maxStepHeight: finite.nonnegative().max(100),
+ maxSlopeDeg: finite.min(0).max(89.9),
+ })
+ .strict(),
+ budget: z
+ .object({
+ maxVisitedCells: z.number().int().min(1).max(262_144),
+ maxColliderTests: z.number().int().min(1).max(10_000_000),
+ })
+ .strict(),
+ criticalPaths: z
+ .array(z.object({ id, from: endpoint, to: endpoint }).strict())
+ .min(1)
+ .max(32),
+ })
+ .strict()
+ .superRefine((document, ctx) => {
+ if (document.grid.width * document.grid.height > 262_144) {
+ ctx.addIssue({ code: 'custom', path: ['grid'], message: 'grid exceeds 262,144 cells' });
+ }
+ if (
+ new Set(document.criticalPaths.map((path) => path.id)).size !== document.criticalPaths.length
+ ) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['criticalPaths'],
+ message: 'critical path ids must be unique',
+ });
+ }
+ });
+
+export type ReachabilityDocumentV1 = z.infer<typeof ReachabilityDocumentV1Schema>;
+
+export type ReachabilityIssueCodeV1 =
+ | 'ENDPOINT_UNKNOWN'
+ | 'ENDPOINT_OUTSIDE_GRID'
+ | 'ENDPOINT_BLOCKED'
+ | 'PATH_UNREACHABLE'
+ | 'VISIT_BUDGET_EXCEEDED'
+ | 'COLLIDER_TEST_BUDGET_EXCEEDED'
+ | 'COLLIDER_ARTIFACT_REQUIRED'
+ | 'COLLIDER_ARTIFACT_HASH_MISMATCH'
+ | 'TERRAIN_ARTIFACT_REQUIRED'
+ | 'TERRAIN_ARTIFACT_HASH_MISMATCH';
+
+export interface ReachabilityIssueV1 {
+ code: ReachabilityIssueCodeV1;
+ message: string;
+ pathId?: string;
+ endpoint?: 'from' | 'to';
+ objectId?: string;
+}
+
+export interface ReachabilityPathResultV1 {
+ id: string;
+ status: 'reachable' | 'blocked' | 'unreachable' | 'budget-exceeded';
+ cells: Array<[number, number]>;
+ visitedCells: number;
+}
+
+export interface ReachabilityReportV1 {
+ schemaVersion: typeof REACHABILITY_REPORT_V1_SCHEMA_VERSION;
+ worldSha256: `sha256:${string}`;
+ requestSha256: `sha256:${string}`;
+ valid: boolean;
+ visitedCells: number;
+ colliderTests: number;
+ paths: ReachabilityPathResultV1[];
+ issues: ReachabilityIssueV1[];
+}
+
+export interface ReachabilityArtifactsV1 {
+ collidersByRefId?: Readonly<Record<string, ColliderArtifactV1>>;
+ heightfield?: HeightfieldArtifactV1;
+}
+
+export function parseReachabilityDocumentV1(input: unknown): ReachabilityDocumentV1 {
+ assertNoPrototypeKeys(input);
+ return ReachabilityDocumentV1Schema.parse(input);
+}
+
+export function canonicalReachabilityDocumentV1Json(input: unknown): string {
+ return canonicalContractJson(parseReachabilityDocumentV1(input));
+}
+
+interface ResolvedEndpoint {
+ position: [number, number, number];
+ clearanceRadius: number;
+}
+
+function resolveEndpoint(
+ world: WorldDocumentV2,
+ value: ReachabilityDocumentV1['criticalPaths'][number]['from'],
+): ResolvedEndpoint | undefined {
+ if (value.kind === 'point') return { position: [...value.position], clearanceRadius: 0 };
+ if (value.kind === 'spawn') {
+ const spawn = world.spawns.find((entry) => entry.id === value.id);
+ return spawn
+ ? { position: [...spawn.position], clearanceRadius: spawn.clearanceRadius }
+ : undefined;
+ }
+ const socket = world.authored.sockets.find((entry) => entry.id === value.id);
+ return socket
+ ? { position: [...socket.position], clearanceRadius: socket.clearanceRadius ?? 0 }
+ : undefined;
+}
+
+function circleIntersectsAabb(x: number, z: number, radius: number, box: Aabb): boolean {
+ const nearestX = Math.max(box.min[0], Math.min(x, box.max[0]));
+ const nearestZ = Math.max(box.min[2], Math.min(z, box.max[2]));
+ return Math.hypot(x - nearestX, z - nearestZ) <= radius;
+}
+
+async function resolveColliders(
+ world: WorldDocumentV2,
+ artifacts: ReachabilityArtifactsV1,
+ issues: ReachabilityIssueV1[],
+): Promise<Aabb[]> {
+ const assets = new Map(world.assets.map((asset) => [asset.refId, asset]));
+ const collisionRefs = new Map(world.collisionArtifacts.map((entry) => [entry.refId, entry]));
+ const boxes: Aabb[] = [];
+ for (const object of world.objects) {
+ if (object.collision?.policy === 'none') continue;
+ if (object.collision?.policy === 'artifact') {
+ const ref = collisionRefs.get(object.collision.artifactRefId)!;
+ const supplied = artifacts.collidersByRefId?.[ref.refId];
+ if (!supplied) {
+ issues.push({
+ code: 'COLLIDER_ARTIFACT_REQUIRED',
+ message: `collider artifact "${ref.refId}" is required`,
+ objectId: object.id,
+ });
+ continue;
+ }
+ const artifact = parseColliderArtifactV1(supplied);
+ const actualHash = await hashColliderArtifactV1(artifact);
+ if (actualHash !== `sha256:${ref.artifact.sha256}`) {
+ issues.push({
+ code: 'COLLIDER_ARTIFACT_HASH_MISMATCH',
+ message: `collider artifact "${ref.refId}" hash mismatch`,
+ objectId: object.id,
+ });
+ continue;
+ }
+ boxes.push(worldColliderAabbV1(artifact, object.transform));
+ continue;
+ }
+ const asset = assets.get(object.assetRefId)!;
+ boxes.push(
+ worldAabbFromLocal(
+ asset.bounds.min,
+ asset.bounds.max,
+ object.transform.position,
+ object.transform.rotationYDeg,
+ object.transform.uniformScale,
+ ),
+ );
+ }
+ return boxes;
+}
+
+function cellOf(
+ position: readonly number[],
+ document: ReachabilityDocumentV1,
+): [number, number] | undefined {
+ const column = Math.round((position[0]! - document.grid.origin[0]) / document.grid.cellSize);
+ const row = Math.round((position[2]! - document.grid.origin[1]) / document.grid.cellSize);
+ return column >= 0 && row >= 0 && column < document.grid.width && row < document.grid.height
+ ? [column, row]
+ : undefined;
+}
+
+function cellPosition(cell: [number, number], document: ReachabilityDocumentV1): [number, number] {
+ return [
+ document.grid.origin[0] + cell[0] * document.grid.cellSize,
+ document.grid.origin[1] + cell[1] * document.grid.cellSize,
+ ];
+}
+
+export async function validateWorldReachabilityV1(
+ worldInput: unknown,
+ documentInput: unknown,
+ artifacts: ReachabilityArtifactsV1 = {},
+): Promise<ReachabilityReportV1> {
+ const world = parseWorldDocumentV2(worldInput);
+ const document = parseReachabilityDocumentV1(documentInput);
+ const issues: ReachabilityIssueV1[] = [];
+ const boxes = await resolveColliders(world, artifacts, issues);
+ let terrainHeight = (_x: number, _z: number): number =>
+ world.terrain.kind === 'flat' ? world.terrain.height : 0;
+ let terrainNormalY = (_x: number, _z: number): number => 1;
+ if (world.terrain.kind === 'heightfield') {
+ if (!artifacts.heightfield) {
+ issues.push({
+ code: 'TERRAIN_ARTIFACT_REQUIRED',
+ message: 'heightfield artifact is required for reachability',
+ });
+ } else if (
+ (await hashHeightfieldArtifactV1(artifacts.heightfield)) !== world.terrain.artifact.sha256
+ ) {
+ issues.push({
+ code: 'TERRAIN_ARTIFACT_HASH_MISMATCH',
+ message: 'heightfield artifact hash mismatch',
+ });
+ } else {
+ const ground = heightfieldGround(artifacts.heightfield);
+ terrainHeight = ground.heightAt;
+ terrainNormalY = (x, z) => ground.normalAt(x, z)[1];
+ }
+ }
+
+ let colliderTests = 0;
+ let visitedCells = 0;
+ let colliderBudgetReported = false;
+ const blockedAt = (x: number, z: number, radius: number): boolean => {
+ for (const box of boxes) {
+ if (colliderTests >= document.budget.maxColliderTests) {
+ if (!colliderBudgetReported) {
+ issues.push({
+ code: 'COLLIDER_TEST_BUDGET_EXCEEDED',
+ message: 'collider test budget exhausted',
+ });
+ colliderBudgetReported = true;
+ }
+ return true;
+ }
+ colliderTests += 1;
+ if (circleIntersectsAabb(x, z, radius, box)) return true;
+ }
+ const slopeDeg = Math.acos(Math.max(-1, Math.min(1, terrainNormalY(x, z)))) * (180 / Math.PI);
+ return slopeDeg > document.agent.maxSlopeDeg;
+ };
+
+ const paths: ReachabilityPathResultV1[] = [];
+ for (const path of document.criticalPaths) {
+ const from = resolveEndpoint(world, path.from);
+ const to = resolveEndpoint(world, path.to);
+ let endpointFailure = false;
+ for (const [name, endpointValue, endpointSpec] of [
+ ['from', from, path.from],
+ ['to', to, path.to],
+ ] as const) {
+ if (!endpointValue) {
+ issues.push({
+ code: 'ENDPOINT_UNKNOWN',
+ message: `${name} endpoint "${endpointSpec.kind === 'point' ? 'point' : endpointSpec.id}" is unknown`,
+ pathId: path.id,
+ endpoint: name,
+ });
+ endpointFailure = true;
+ continue;
+ }
+ const cell = cellOf(endpointValue.position, document);
+ if (!cell) {
+ issues.push({
+ code: 'ENDPOINT_OUTSIDE_GRID',
+ message: `${name} endpoint is outside grid`,
+ pathId: path.id,
+ endpoint: name,
+ });
+ endpointFailure = true;
+ continue;
+ }
+ if (
+ blockedAt(
+ endpointValue.position[0],
+ endpointValue.position[2],
+ Math.max(document.agent.radius, endpointValue.clearanceRadius),
+ )
+ ) {
+ issues.push({
+ code: 'ENDPOINT_BLOCKED',
+ message: `${name} endpoint is blocked`,
+ pathId: path.id,
+ endpoint: name,
+ });
+ endpointFailure = true;
+ }
+ }
+ if (endpointFailure || !from || !to) {
+ paths.push({ id: path.id, status: 'blocked', cells: [], visitedCells: 0 });
+ continue;
+ }
+ const start = cellOf(from.position, document)!;
+ const goal = cellOf(to.position, document)!;
+ const key = (cell: [number, number]) => `${cell[0]}:${cell[1]}`;
+ const queue: Array<[number, number]> = [start];
+ const previous = new Map<string, [number, number] | undefined>([[key(start), undefined]]);
+ let cursor = 0;
+ let pathVisits = 0;
+ let exceeded = false;
+ while (cursor < queue.length) {
+ if (visitedCells >= document.budget.maxVisitedCells) {
+ issues.push({
+ code: 'VISIT_BUDGET_EXCEEDED',
+ message: 'visited-cell budget exhausted',
+ pathId: path.id,
+ });
+ exceeded = true;
+ break;
+ }
+ const current = queue[cursor++]!;
+ visitedCells += 1;
+ pathVisits += 1;
+ if (current[0] === goal[0] && current[1] === goal[1]) break;
+ const [x, z] = cellPosition(current, document);
+ const currentHeight = terrainHeight(x, z);
+ for (const [dx, dz] of [
+ [1, 0],
+ [0, 1],
+ [-1, 0],
+ [0, -1],
+ ] as const) {
+ const next: [number, number] = [current[0] + dx, current[1] + dz];
+ if (
+ next[0] < 0 ||
+ next[1] < 0 ||
+ next[0] >= document.grid.width ||
+ next[1] >= document.grid.height ||
+ previous.has(key(next))
+ )
+ continue;
+ const [nextX, nextZ] = cellPosition(next, document);
+ if (Math.abs(terrainHeight(nextX, nextZ) - currentHeight) > document.agent.maxStepHeight)
+ continue;
+ if (blockedAt(nextX, nextZ, document.agent.radius)) continue;
+ previous.set(key(next), current);
+ queue.push(next);
+ }
+ }
+ if (exceeded) {
+ paths.push({ id: path.id, status: 'budget-exceeded', cells: [], visitedCells: pathVisits });
+ continue;
+ }
+ if (!previous.has(key(goal))) {
+ issues.push({
+ code: 'PATH_UNREACHABLE',
+ message: `critical path "${path.id}" is unreachable`,
+ pathId: path.id,
+ });
+ paths.push({ id: path.id, status: 'unreachable', cells: [], visitedCells: pathVisits });
+ continue;
+ }
+ const cells: Array<[number, number]> = [];
+ for (
+ let current: [number, number] | undefined = goal;
+ current;
+ current = previous.get(key(current))
+ ) {
+ cells.push(current);
+ }
+ cells.reverse();
+ paths.push({ id: path.id, status: 'reachable', cells, visitedCells: pathVisits });
+ }
+ return {
+ schemaVersion: REACHABILITY_REPORT_V1_SCHEMA_VERSION,
+ worldSha256: await hashWorldDocumentV2(world),
+ requestSha256: await sha256ContractJson(document),
+ valid: issues.length === 0 && paths.every((path) => path.status === 'reachable'),
+ visitedCells,
+ colliderTests,
+ paths,
+ issues,
+ };
+}
diff --git a/src/composer/render-port.ts b/src/composer/render-port.ts
index 83612cf5..e368379f 100644
--- a/src/composer/render-port.ts
+++ b/src/composer/render-port.ts
@@ -93,6 +93,9 @@ export interface SceneRenderResult {
degraded?: boolean;
/** Stable, credential-free fallback explanation. Meaningful when degraded is true. */
degradeReason?: string;
+ /** Material truth for ordinary Composer review pixels. The host owns scene
+ * GLB assembly and therefore binds receipts to its derivative bytes. */
+ viewFidelity?: DerivativeReviewFidelityV1;
error?: string;
}
@@ -100,6 +103,110 @@ export interface SceneRenderResult {
* `{ ok:false, error }` (no image) so the agent gets a fixable error. */
export type SceneRenderPort = (req: SceneRenderRequest) => Promise<SceneRenderResult>;
+/** Requested material-review policy for one view operation. */
+export type ViewFidelityPolicy = 'full-preferred' | 'full-required' | 'geometry-only';
+
+/** What the renderer actually delivered. */
+export type DeliveredViewFidelity = 'full-material' | 'geometry-flat' | 'none';
+
+/** Stable machine-readable explanation for a degraded or unavailable view. */
+export type ViewFidelityReasonCode =
+ | 'FULL_MATERIAL_RENDER_UNAVAILABLE'
+ | 'DERIVATIVE_GPU_FRAMING_UNSUPPORTED'
+ | 'DERIVATIVE_RECEIPT_UNAVAILABLE'
+ | 'DERIVATIVE_RECEIPT_INVALID'
+ | 'GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED'
+ | 'GLB_FLAT_KTX2_SAMPLING_UNSUPPORTED'
+ | 'GLB_FLAT_NON_TRIANGLE_PRIMITIVE_UNSUPPORTED'
+ | 'GLB_FLAT_SKIN_DEFORMATION_UNSUPPORTED'
+ | 'GLB_FLAT_MORPH_TARGETS_UNSUPPORTED'
+ | 'GLB_FLAT_PARSE_FAILED'
+ | 'GLB_FLAT_NO_SCENE'
+ | 'GLB_FLAT_NO_RENDERABLE_GEOMETRY'
+ | 'GLB_FLAT_INVALID_INSTANCING';
+
+/**
+ * Truthful, model-visible provenance for a rendered view.
+ *
+ * `exactArtifact` distinguishes a view of persisted/final bytes from an
+ * in-loop or purpose-built derivative GLB. A GPU producer is not enough to
+ * make that claim by itself.
+ */
+export interface ViewFidelityV1 {
+ version: 'kiln.view-fidelity.v1';
+ requested: ViewFidelityPolicy;
+ delivered: DeliveredViewFidelity;
+ materialFaithful: boolean;
+ exactArtifact: boolean;
+ rendererId: string;
+ inputGlbSha256: `sha256:${string}`;
+ degraded: boolean;
+ degradeReason?: string;
+ /** Stable codes for policy and telemetry; no credentials or provider details. */
+ reasonCodes?: ViewFidelityReasonCode[];
+}
+
+/** One purpose-built review GLB and the pixels derived from those exact bytes. */
+export interface DerivativeViewReceiptV1 extends ViewFidelityV1 {
+ /** Stable cell/frame identity within the review surface. */
+ derivativeLabel: string;
+ /** Derivative bytes are never the persisted/final artifact. */
+ exactArtifact: false;
+}
+
+/** Aggregate material-fidelity truth for a derivative review surface. */
+export interface DerivativeReviewFidelityV1 {
+ version: 'kiln.derivative-review-fidelity.v1';
+ requested: ViewFidelityPolicy;
+ delivered: DeliveredViewFidelity;
+ materialFaithful: boolean;
+ exactArtifact: false;
+ degraded: boolean;
+ /** One receipt per deterministic derivative GLB, in displayed order. */
+ receipts: DerivativeViewReceiptV1[];
+ reasonCodes?: ViewFidelityReasonCode[];
+}
+
+export type ViewEvidenceSurface =
+ | 'kiln_render'
+ | 'kiln_inspect'
+ | 'kiln_screenshot_animation'
+ | 'kiln_view_interior'
+ | 'scene_render'
+ | 'scene_screenshot_camera';
+
+/** Hash-only pointer to one prior fully material-faithful review request. */
+export interface FaithfulViewEvidenceReferenceV1 {
+ version: 'kiln.faithful-view-evidence-ref.v1';
+ sequence: number;
+ surface: ViewEvidenceSurface;
+ materialFaithful: true;
+ exactArtifact: boolean;
+ inputGlbSha256: `sha256:${string}`[];
+ rendererIds: string[];
+}
+
+/** Unambiguous evidence status for the request that just completed. */
+export interface CurrentViewEvidenceV1 {
+ sequence: number;
+ surface: ViewEvidenceSurface;
+ delivered: DeliveredViewFidelity;
+ materialFaithful: boolean;
+ exactArtifact: boolean;
+ degraded: boolean;
+ inputGlbSha256: `sha256:${string}`[];
+ rendererIds: string[];
+ reasonCodes?: ViewFidelityReasonCode[];
+}
+
+/** Bounded, model-visible metadata only. Contains no source or pixel bytes. */
+export interface ViewEvidenceHistoryV1 {
+ version: 'kiln.view-evidence-history.v1';
+ current: CurrentViewEvidenceV1;
+ lastFaithful?: FaithfulViewEvidenceReferenceV1;
+ faithfulHistory: FaithfulViewEvidenceReferenceV1[];
+}
+
/**
* PbrRenderRequest — one PBR/beauty render of an ALREADY-PRODUCED GLB.
*
@@ -320,6 +427,12 @@ export interface PbrRenderResult {
lightingPresetId?: string;
/** One PNG per requested view direction, in request order. */
viewsPng?: Uint8Array[];
+ /** Optional derivative-byte attestation. Required before a derivative review
+ * may claim materialFaithful:true; legacy contact sheets remain compatible. */
+ derivativeFidelity?: {
+ materialFaithful: true;
+ inputGlbSha256: `sha256:${string}`;
+ };
/** The optional beauty shot. */
beautyPng?: Uint8Array;
/** Host-measured phase timings in milliseconds. */
diff --git a/src/composer/world-document.ts b/src/composer/world-document.ts
index d5673c25..3734fc12 100644
--- a/src/composer/world-document.ts
+++ b/src/composer/world-document.ts
@@ -16,6 +16,7 @@ import type {
Statement,
} from './model';
import { placementRoleForAsset, PlacementModel } from './model';
+import { PresentationParametersV1Schema } from './presentation';
export const WORLD_DOCUMENT_V2_SCHEMA_VERSION = 'kiln.world.v2' as const;
@@ -413,6 +414,8 @@ export const WorldDocumentV2Schema = z
.strict(),
collisionArtifacts: z.array(collisionArtifactSchema).max(512),
spawns: z.array(spawnSchema).max(128),
+ /** Additive Phase 2 presentation state. Historical v2 worlds may omit it. */
+ presentation: PresentationParametersV1Schema.optional(),
runtimePolicy: z.object({ mode: z.literal('static-explore') }).strict(),
provenance: z
.object({
@@ -521,6 +524,36 @@ export const WorldDocumentV2Schema = z
});
}
}
+
+ const packagePaths = [
+ ...world.assets.map((asset, index) => ({
+ path: `models/${asset.generationId}.glb`,
+ issuePath: ['assets', index, 'generationId'] as (string | number)[],
+ })),
+ ...(world.terrain.kind === 'heightfield'
+ ? [
+ {
+ path: world.terrain.artifact.uri,
+ issuePath: ['terrain', 'artifact', 'uri'] as (string | number)[],
+ },
+ ]
+ : []),
+ ...world.collisionArtifacts.map((artifact, index) => ({
+ path: artifact.artifact.uri,
+ issuePath: ['collisionArtifacts', index, 'artifact', 'uri'] as (string | number)[],
+ })),
+ ];
+ const seenPackagePaths = new Set<string>();
+ for (const entry of packagePaths) {
+ if (seenPackagePaths.has(entry.path)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: entry.issuePath,
+ message: `duplicate package path "${entry.path}"`,
+ });
+ }
+ seenPackagePaths.add(entry.path);
+ }
});
export type WorldDocumentV2 = z.infer<typeof WorldDocumentV2Schema>;
diff --git a/src/composer/world-integration.ts b/src/composer/world-integration.ts
index 6aebb351..0680c9d9 100644
--- a/src/composer/world-integration.ts
+++ b/src/composer/world-integration.ts
@@ -1,5 +1,6 @@
/** Pure deterministic authoring and validation operations for Composer V2 world primitives. */
import { worldAabbFromLocal } from './overlap';
+import { parsePresentationParametersV1 } from './presentation';
import {
parseWorldDocumentV2,
reconcileWorldDocumentV2Objects,
@@ -83,6 +84,15 @@ export function setWorldSpawnsV2(input: unknown, spawns: readonly WorldSpawnV2[]
);
}
+/** Persist one strict ordered presentation document without changing world transforms. */
+export function setWorldPresentationV1(input: unknown, presentation: unknown): WorldDocumentV2 {
+ const world = parseWorldDocumentV2(input);
+ return parseWorldDocumentV2({
+ ...world,
+ presentation: parsePresentationParametersV1(presentation),
+ });
+}
+
/** Replace terrain without changing any other canonical world state. */
export function setWorldTerrainV2(input: unknown, terrain: WorldTerrainV2): WorldDocumentV2 {
const world = parseWorldDocumentV2(input);
diff --git a/src/composer/world-package.ts b/src/composer/world-package.ts
new file mode 100644
index 00000000..f9fc93dc
--- /dev/null
+++ b/src/composer/world-package.ts
@@ -0,0 +1,255 @@
+import { z } from 'zod';
+import {
+ assertNoPrototypeKeys,
+ canonicalContractJson,
+ sameCanonicalContract,
+ sha256ContractBytes,
+ sha256ContractJson,
+} from './contract-utils';
+import {
+ parsePresentationDocumentV1,
+ hashPresentationDocumentV1,
+ PresentationDocumentV1Schema,
+} from './presentation';
+import {
+ hashWorldDocumentV2,
+ parseWorldDocumentV2,
+ worldDocumentV2ArtifactReferences,
+ WorldDocumentV2Schema,
+} from './world-document';
+
+export const WORLD_PACKAGE_V2_SCHEMA_VERSION = 'kiln.world-package.v2' as const;
+
+const contentSha256 = z.string().regex(/^sha256:[0-9a-f]{64}$/);
+const id = z.string().min(1).max(256);
+const portablePath = z
+ .string()
+ .min(1)
+ .max(2048)
+ .refine(
+ (path) =>
+ !path.startsWith('/') &&
+ !path.includes('\\') &&
+ !path.includes('?') &&
+ !path.includes('#') &&
+ !/^[a-z][a-z0-9+.-]*:/i.test(path) &&
+ path.split('/').every((segment) => segment.length > 0 && segment !== '.' && segment !== '..'),
+ 'expected a portable package-relative path',
+ );
+
+const provenanceSchema = z
+ .object({
+ worldSource: z.enum(['composer-v1', 'composer-v2', 'manual']),
+ parentWorldHash: contentSha256.optional(),
+ objectSources: z
+ .array(
+ z
+ .object({
+ objectId: id,
+ sourceStatementId: id,
+ activeAsset: z
+ .object({ generationId: id, artifactSha256: contentSha256 })
+ .strict()
+ .optional(),
+ })
+ .strict(),
+ )
+ .max(200),
+ })
+ .strict();
+
+const artifactSchema = z
+ .object({
+ kind: z.enum(['asset', 'collision', 'heightfield']),
+ refId: id,
+ path: portablePath,
+ sha256: contentSha256,
+ })
+ .strict();
+
+export const WorldPackageV2Schema = z
+ .object({
+ schemaVersion: z.literal(WORLD_PACKAGE_V2_SCHEMA_VERSION),
+ world: WorldDocumentV2Schema,
+ worldSha256: contentSha256,
+ presentation: PresentationDocumentV1Schema,
+ presentationSha256: contentSha256,
+ artifacts: z.array(artifactSchema).max(1024),
+ runtimePolicy: z.object({ mode: z.literal('static-explore') }).strict(),
+ provenance: provenanceSchema,
+ provenanceSha256: contentSha256,
+ })
+ .strict()
+ .superRefine((value, ctx) => {
+ const artifactPaths = new Set<string>();
+ for (let index = 0; index < value.artifacts.length; index++) {
+ const path = value.artifacts[index]!.path;
+ if (artifactPaths.has(path)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['artifacts', index, 'path'],
+ message: `duplicate package path "${path}"`,
+ });
+ }
+ artifactPaths.add(path);
+ }
+ const { artifactBinding, ...presentationParameters } = value.presentation;
+ if (
+ !value.world.presentation ||
+ !sameCanonicalContract(value.world.presentation, presentationParameters)
+ ) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['presentation'],
+ message: 'presentation must equal world presentation',
+ });
+ }
+ if (artifactBinding.kind !== 'world' || artifactBinding.sha256 !== value.worldSha256) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['presentation', 'artifactBinding'],
+ message: 'presentation artifact binding must equal worldSha256',
+ });
+ }
+ if (!sameCanonicalContract(value.runtimePolicy, value.world.runtimePolicy)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['runtimePolicy'],
+ message: 'runtimePolicy must equal world runtime policy',
+ });
+ }
+ const expectedArtifacts = worldDocumentV2ArtifactReferences(value.world).map((reference) => ({
+ kind: reference.kind,
+ refId: reference.refId,
+ path: reference.packagePath,
+ sha256: `sha256:${reference.sha256}`,
+ }));
+ if (!sameCanonicalContract(value.artifacts, expectedArtifacts)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['artifacts'],
+ message: 'artifacts must equal world artifact closure',
+ });
+ }
+ const expectedProvenance = provenanceOf(value.world);
+ if (!sameCanonicalContract(value.provenance, expectedProvenance)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['provenance'],
+ message: 'provenance must equal world provenance closure',
+ });
+ }
+ });
+
+export type WorldPackageV2 = z.infer<typeof WorldPackageV2Schema>;
+
+function provenanceOf(world: z.infer<typeof WorldDocumentV2Schema>) {
+ return {
+ worldSource: world.provenance.source,
+ ...(world.provenance.parentWorldHash
+ ? { parentWorldHash: world.provenance.parentWorldHash }
+ : {}),
+ objectSources: [...world.objects]
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
+ .map((object) => ({
+ objectId: object.id,
+ sourceStatementId: object.provenance.sourceStatementId,
+ ...(object.provenance.activeAsset
+ ? {
+ activeAsset: {
+ generationId: object.provenance.activeAsset.generationId,
+ artifactSha256: `sha256:${object.provenance.activeAsset.artifactSha256}`,
+ },
+ }
+ : {}),
+ })),
+ };
+}
+
+export function parseWorldPackageV2(input: unknown): WorldPackageV2 {
+ assertNoPrototypeKeys(input);
+ return WorldPackageV2Schema.parse(input);
+}
+
+export async function validateWorldPackageV2(input: unknown): Promise<WorldPackageV2> {
+ const packageDocument = parseWorldPackageV2(input);
+ const expectedWorldHash = await hashWorldDocumentV2(packageDocument.world);
+ if (packageDocument.worldSha256 !== expectedWorldHash) {
+ throw new TypeError(
+ `worldSha256 mismatch (${packageDocument.worldSha256} != ${expectedWorldHash})`,
+ );
+ }
+ const expectedPresentationHash = await hashPresentationDocumentV1(packageDocument.presentation);
+ if (packageDocument.presentationSha256 !== expectedPresentationHash) {
+ throw new TypeError('presentationSha256 mismatch');
+ }
+ const expectedProvenanceHash = await sha256ContractJson(packageDocument.provenance);
+ if (packageDocument.provenanceSha256 !== expectedProvenanceHash) {
+ throw new TypeError('provenanceSha256 mismatch');
+ }
+ return packageDocument;
+}
+
+export interface CreateWorldPackageV2Input {
+ world: unknown;
+}
+
+export async function createWorldPackageV2(
+ input: CreateWorldPackageV2Input,
+): Promise<WorldPackageV2> {
+ const world = parseWorldDocumentV2(input.world);
+ if (!world.presentation) throw new TypeError('WorldPackageV2 requires world presentation');
+ const worldSha256 = await hashWorldDocumentV2(world);
+ const presentation = parsePresentationDocumentV1({
+ ...world.presentation,
+ artifactBinding: { kind: 'world', sha256: worldSha256 },
+ });
+ const provenance = provenanceOf(world);
+ return validateWorldPackageV2({
+ schemaVersion: WORLD_PACKAGE_V2_SCHEMA_VERSION,
+ world,
+ worldSha256,
+ presentation,
+ presentationSha256: await hashPresentationDocumentV1(presentation),
+ artifacts: worldDocumentV2ArtifactReferences(world).map((reference) => ({
+ kind: reference.kind,
+ refId: reference.refId,
+ path: reference.packagePath,
+ sha256: `sha256:${reference.sha256}`,
+ })),
+ runtimePolicy: world.runtimePolicy,
+ provenance,
+ provenanceSha256: await sha256ContractJson(provenance),
+ });
+}
+
+export function canonicalWorldPackageV2Json(input: unknown): string {
+ return canonicalContractJson(parseWorldPackageV2(input));
+}
+
+export function hashWorldPackageV2(input: unknown): Promise<`sha256:${string}`> {
+ return sha256ContractJson(parseWorldPackageV2(input));
+}
+
+/** Verify the exact external artifact bytes that complete the portable package closure. */
+export async function validateWorldPackageArtifactBytesV2(
+ packageInput: unknown,
+ files: Readonly<Record<string, Uint8Array>>,
+): Promise<void> {
+ const packageDocument = await validateWorldPackageV2(packageInput);
+ assertNoPrototypeKeys(files, '$files');
+ const expectedPaths = new Set(packageDocument.artifacts.map((artifact) => artifact.path));
+ for (const path of Object.keys(files)) {
+ if (!expectedPaths.has(path)) throw new TypeError(`unexpected package artifact path "${path}"`);
+ }
+ for (const artifact of packageDocument.artifacts) {
+ const bytes = files[artifact.path];
+ if (!(bytes instanceof Uint8Array)) {
+ throw new TypeError(`missing package artifact bytes for "${artifact.path}"`);
+ }
+ const actual = await sha256ContractBytes(bytes);
+ if (actual !== artifact.sha256) {
+ throw new TypeError(`package artifact hash mismatch for "${artifact.path}"`);
+ }
+ }
+}
diff --git a/src/evaluator/index.ts b/src/evaluator/index.ts
new file mode 100644
index 00000000..36b5b1dd
--- /dev/null
+++ b/src/evaluator/index.ts
@@ -0,0 +1,27 @@
+export {
+ EVALUATOR_REQUEST_VERSION,
+ EVALUATOR_RESULT_VERSION,
+ evaluatorOutcomeMessage,
+ MAX_EVALUATOR_CODE_BYTES,
+ MAX_EVALUATOR_REQUEST_BYTES,
+ type EvaluatorOutcomeCode,
+ type EvaluatorRequestV1,
+ type EvaluatorResultV1,
+} from './protocol';
+export {
+ EvaluatorSubprocessError,
+ renderGLBViaSubprocess,
+ sanitizedEvaluatorEnv,
+ type EvaluatorSubprocessControls,
+} from './subprocess';
+export {
+ assertIsolatedEvaluatorReady,
+ EvaluatorIsolationReadinessError,
+ isolationReadinessFailureCode,
+ isolatedEvaluatorLaunch,
+ renderGLBViaIsolatedEvaluator,
+ type EvaluatorIsolationReadiness,
+ type EvaluatorIsolationReadinessFailureCode,
+ type IsolatedEvaluatorControls,
+ type IsolatedEvaluatorHost,
+} from './isolation';
diff --git a/src/evaluator/isolation-adversarial.test.ts b/src/evaluator/isolation-adversarial.test.ts
new file mode 100644
index 00000000..de0c9dcb
--- /dev/null
+++ b/src/evaluator/isolation-adversarial.test.ts
@@ -0,0 +1,58 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { renderGLB } from '../render';
+import { renderGLBViaSubprocess } from './subprocess';
+
+const previousMode = process.env['KILN_EVALUATOR_MODE'];
+afterEach(() => {
+ if (previousMode === undefined) delete process.env['KILN_EVALUATOR_MODE'];
+ else process.env['KILN_EVALUATOR_MODE'] = previousMode;
+});
+
+const BASE = `
+const meta = { name: 'AdversarialProbe' };
+function build() { return createRoot('AdversarialProbe'); }
+`;
+
+describe('isolated evaluator adversarial settlement', () => {
+ test('generated filesystem, environment, network, and process acquisition settle as sanitized rejections', async () => {
+ const probes = [
+ `const marker = process.env.SECRET; ${BASE}`,
+ `const marker = fetch('http://169.254.169.254/latest/meta-data/'); ${BASE}`,
+ `const marker = globalThis.process.mainModule.require('node:fs').readFileSync('/etc/passwd'); ${BASE}`,
+ `const marker = globalThis.process.mainModule.require('node:child_process').spawn('/bin/sh'); ${BASE}`,
+ `const marker = loadTexture('../../agent-runtime/src/server.ts'); ${BASE}`,
+ ];
+ for (const [index, source] of probes.entries()) {
+ const secretMarker = `DO_NOT_LEAK_PROBE_${index}`;
+ try {
+ await renderGLBViaSubprocess(`${source}\n// ${secretMarker}`, {}, { deadlineMs: 10_000 });
+ throw new Error('expected adversarial rejection');
+ } catch (error) {
+ expect(error).toMatchObject({ code: 'EXECUTION_REJECTED' });
+ expect(String(error)).toBe(
+ 'EvaluatorSubprocessError: Generated asset execution was rejected.',
+ );
+ expect(String(error)).not.toContain(secretMarker);
+ expect(String(error)).not.toContain('/etc/passwd');
+ }
+ }
+ }, 30_000);
+
+ test('an unavailable isolated boundary is terminal and never runs the valid source in-process', async () => {
+ process.env['KILN_EVALUATOR_MODE'] = 'isolated';
+ await expect(renderGLB(BASE)).rejects.toMatchObject({ code: 'ISOLATION_UNAVAILABLE' });
+ });
+
+ test('resource exhaustion settles at the deadline with no source or prompt echo', async () => {
+ const marker = 'EXHAUSTION_SOURCE_DO_NOT_ECHO';
+ const source = `async function build(){ ${marker}: await new Promise(() => {}); }`;
+ try {
+ await renderGLBViaSubprocess(source, {}, { deadlineMs: 100 });
+ throw new Error('expected deadline');
+ } catch (error) {
+ expect(error).toMatchObject({ code: 'DEADLINE_EXCEEDED' });
+ expect(String(error)).not.toContain(marker);
+ expect(String(error)).not.toContain(source);
+ }
+ }, 10_000);
+});
diff --git a/src/evaluator/isolation.test.ts b/src/evaluator/isolation.test.ts
new file mode 100644
index 00000000..6ec81c1b
--- /dev/null
+++ b/src/evaluator/isolation.test.ts
@@ -0,0 +1,196 @@
+import { describe, expect, test } from 'bun:test';
+import { resolveEvaluatorMode } from '../render';
+import { EvaluatorSubprocessError } from './subprocess';
+import {
+ decodeEvaluatorIsolationReadiness,
+ decodeEvaluatorIsolationTransport,
+ EvaluatorIsolationReadinessError,
+ isolationReadinessFailureCode,
+ isolatedEvaluatorLaunch,
+} from './isolation';
+import { processCapabilitiesAreEmpty } from './probe-invariants';
+
+const PATHS = new Set([
+ '/usr',
+ '/lib',
+ '/app/node_modules',
+ '/usr/local/bin/bwrap',
+ '/usr/bin/setpriv',
+ '/usr/bin/prlimit',
+ '/usr/local/bin/node',
+ '/app/node_modules/@kiln/engine/src/evaluator/worker.ts',
+]);
+
+function launch() {
+ return isolatedEvaluatorLaunch('/app/node_modules/@kiln/engine/src/evaluator/worker.ts', {
+ platform: 'linux',
+ pathExists: (path) => PATHS.has(path),
+ });
+}
+
+describe('isolated evaluator process contract', () => {
+ test('exposes only the reviewed readiness failure vocabulary', () => {
+ for (const code of [
+ 'wrapper-launch',
+ 'fd3-transport',
+ 'loader-probe-boot',
+ 'invariant-namespace',
+ 'invariant-environment',
+ 'invariant-filesystem',
+ 'invariant-network',
+ 'invariant-generated-policy',
+ 'deadline',
+ ] as const) {
+ const error = new EvaluatorIsolationReadinessError(code);
+ expect(error).toMatchObject({
+ code: 'ISOLATION_UNAVAILABLE',
+ message: 'Isolated evaluator readiness check failed.',
+ readinessCode: code,
+ });
+ expect(isolationReadinessFailureCode(error)).toBe(code);
+ }
+ expect(isolationReadinessFailureCode(new Error('bwrap /private/path secret'))).toBeUndefined();
+ });
+
+ test('accepts only bounded v1 negative readiness envelopes', () => {
+ for (const failure of [
+ 'loader-probe-boot',
+ 'invariant-namespace',
+ 'invariant-environment',
+ 'invariant-filesystem',
+ 'invariant-network',
+ 'invariant-generated-policy',
+ ] as const) {
+ expect(
+ decodeEvaluatorIsolationReadiness({
+ version: 'kiln.evaluator.isolation-readiness.v1',
+ mode: 'isolated',
+ failure,
+ }),
+ ).toEqual({ version: 'kiln.evaluator.isolation-readiness.v1', mode: 'isolated', failure });
+ }
+ for (const value of [
+ {
+ version: 'kiln.evaluator.isolation-readiness.v1',
+ mode: 'isolated',
+ failure: 'wrapper-launch',
+ },
+ {
+ version: 'kiln.evaluator.isolation-readiness.v1',
+ mode: 'isolated',
+ failure: 'invariant-namespace',
+ detail: '/private/path',
+ },
+ ]) {
+ expect(() => decodeEvaluatorIsolationReadiness(value)).toThrow(
+ 'Isolated evaluator is unavailable.',
+ );
+ }
+ });
+
+ test('accepts only the exact fd3 transport marker envelope', () => {
+ expect(
+ decodeEvaluatorIsolationTransport({
+ version: 'kiln.evaluator.isolation-transport.v1',
+ transport: 'fd3',
+ }),
+ ).toEqual({ version: 'kiln.evaluator.isolation-transport.v1', transport: 'fd3' });
+ for (const value of [
+ { version: 'kiln.evaluator.isolation-transport.v1', transport: 'stdout' },
+ {
+ version: 'kiln.evaluator.isolation-transport.v1',
+ transport: 'fd3',
+ detail: '/private/path',
+ },
+ ]) {
+ expect(() => decodeEvaluatorIsolationTransport(value)).toThrow(
+ 'Isolated evaluator is unavailable.',
+ );
+ }
+ });
+ test('selects isolated mode exactly and rejects near-miss flags', () => {
+ expect(resolveEvaluatorMode({ KILN_EVALUATOR_MODE: 'isolated' })).toBe('isolated');
+ expect(() => resolveEvaluatorMode({ KILN_EVALUATOR_MODE: 'isolate' })).toThrow(
+ 'Invalid KILN_EVALUATOR_MODE',
+ );
+ });
+
+ test('drops privileges before a no-network, read-only namespace boundary', () => {
+ const spec = launch();
+ expect(spec.command).toBe('/usr/bin/setpriv');
+ expect(spec.detached).toBe(true);
+ expect(spec.env).toEqual({ NODE_ENV: 'production', NO_COLOR: '1' });
+ expect(spec.args.slice(0, 5)).toEqual([
+ '--no-new-privs',
+ '--inh-caps=-all',
+ '--ambient-caps=-all',
+ '--',
+ '/usr/local/bin/bwrap',
+ ]);
+ expect(spec.args).not.toContain('--bounding-set=-all');
+ expect(spec.args).toContain('--unshare-all');
+ expect(spec.args).not.toContain('--share-net');
+ expect(spec.args).toContain('--disable-userns');
+ expect(spec.args).toContain('--cap-drop');
+ expect(spec.args).toContain('--clearenv');
+ expect(spec.args).toContain('--tmpfs');
+ expect(spec.args).toContain('--ro-bind');
+ expect(spec.args).toContain('--preserve-fds');
+ expect(spec.args).toContain('--cpu=65:65');
+ expect(spec.args).toContain('--as=6442450944:6442450944');
+ expect(spec.args).toContain('--nproc=64:64');
+ expect(spec.args).toContain('--max-old-space-size=512');
+ expect(spec.args).not.toContain('/app/agent-runtime');
+ expect(spec.args).not.toContain('/etc');
+ });
+
+ test('requires every Linux capability set to be present and empty', () => {
+ const emptyStatus = [
+ 'Name:\tnode',
+ 'CapInh:\t0000000000000000',
+ 'CapPrm:\t0000000000000000',
+ 'CapEff:\t0000000000000000',
+ 'CapBnd:\t0000000000000000',
+ 'CapAmb:\t0000000000000000',
+ ].join('\n');
+ expect(processCapabilitiesAreEmpty(emptyStatus)).toBe(true);
+ for (const field of ['CapInh', 'CapPrm', 'CapEff', 'CapBnd', 'CapAmb']) {
+ expect(
+ processCapabilitiesAreEmpty(emptyStatus.replace(`${field}:\t0000`, `${field}:\t0001`)),
+ ).toBe(false);
+ expect(
+ processCapabilitiesAreEmpty(emptyStatus.replace(new RegExp(`^${field}:.*$`, 'm'), '')),
+ ).toBe(false);
+ }
+ expect(processCapabilitiesAreEmpty(undefined)).toBe(false);
+ });
+
+ test('refuses non-Linux hosts, missing binaries, and workers outside installed dependencies', () => {
+ for (const invoke of [
+ () =>
+ isolatedEvaluatorLaunch('/app/node_modules/@kiln/engine/src/evaluator/worker.ts', {
+ platform: 'win32',
+ pathExists: () => true,
+ }),
+ () =>
+ isolatedEvaluatorLaunch('/app/node_modules/@kiln/engine/src/evaluator/worker.ts', {
+ platform: 'linux',
+ pathExists: () => false,
+ }),
+ () =>
+ isolatedEvaluatorLaunch('/app/agent-runtime/src/server.ts', {
+ platform: 'linux',
+ pathExists: () => true,
+ }),
+ ]) {
+ try {
+ invoke();
+ throw new Error('expected isolation refusal');
+ } catch (error) {
+ expect(error).toBeInstanceOf(EvaluatorSubprocessError);
+ expect(error).toMatchObject({ code: 'ISOLATION_UNAVAILABLE' });
+ expect(String(error)).not.toContain('/app/agent-runtime/src/server.ts');
+ }
+ }
+ });
+});
diff --git a/src/evaluator/isolation.ts b/src/evaluator/isolation.ts
new file mode 100644
index 00000000..0bb42823
--- /dev/null
+++ b/src/evaluator/isolation.ts
@@ -0,0 +1,446 @@
+import { spawn } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { posix } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { RenderGlbOptions, RenderResult } from '../render';
+import {
+ EvaluatorSubprocessError,
+ type EvaluatorProcessLaunch,
+ type EvaluatorSubprocessControls,
+ renderGLBViaProcessLaunch,
+ sanitizedEvaluatorEnv,
+} from './subprocess';
+
+const DEFAULT_RUNTIME_ROOT = '/app';
+const DEFAULT_BWRAP_PATH = '/usr/local/bin/bwrap';
+const DEFAULT_SETPRIV_PATH = '/usr/bin/setpriv';
+const DEFAULT_PRLIMIT_PATH = '/usr/bin/prlimit';
+const DEFAULT_NODE_PATH = '/usr/local/bin/node';
+const READINESS_VERSION = 'kiln.evaluator.isolation-readiness.v1';
+const TRANSPORT_VERSION = 'kiln.evaluator.isolation-transport.v1';
+const TRANSPORT_STDOUT_MARKER = 'kiln-evaluator-transport-boot-v1\n';
+const PROBE_DEADLINE_MS = 8_000;
+const MAX_READINESS_PROTOCOL_BYTES = 16 * 1024;
+const MAX_TRANSPORT_STDOUT_BYTES = 256;
+const READINESS_FAILURE_CODES = [
+ 'wrapper-launch',
+ 'fd3-transport',
+ 'loader-probe-boot',
+ 'invariant-namespace',
+ 'invariant-environment',
+ 'invariant-filesystem',
+ 'invariant-network',
+ 'invariant-generated-policy',
+ 'deadline',
+] as const;
+const READINESS_CHECKS = [
+ 'user-namespace',
+ 'no-new-privileges',
+ 'capabilities-empty',
+ 'environment-exact',
+ 'product-filesystem-denied',
+ 'host-filesystem-denied',
+ 'runtime-filesystem-read-only',
+ 'network-namespace-empty',
+ 'metadata-and-local-network-denied',
+ 'generated-capabilities-denied',
+] as const;
+
+export interface IsolatedEvaluatorHost {
+ platform?: NodeJS.Platform;
+ runtimeRoot?: string;
+ bwrapPath?: string;
+ setprivPath?: string;
+ prlimitPath?: string;
+ nodePath?: string;
+ pathExists?: (path: string) => boolean;
+}
+
+export interface IsolatedEvaluatorControls extends EvaluatorSubprocessControls {
+ host?: IsolatedEvaluatorHost;
+}
+
+export interface EvaluatorIsolationReadiness {
+ version: typeof READINESS_VERSION;
+ mode: 'isolated';
+ checks: readonly string[];
+}
+
+interface EvaluatorIsolationReadinessFailure {
+ version: typeof READINESS_VERSION;
+ mode: 'isolated';
+ failure: EvaluatorIsolationProbeFailureCode;
+}
+
+interface EvaluatorIsolationTransport {
+ version: typeof TRANSPORT_VERSION;
+ transport: 'fd3';
+}
+
+export type EvaluatorIsolationReadinessFailureCode = (typeof READINESS_FAILURE_CODES)[number];
+type EvaluatorIsolationProbeFailureCode = Extract<
+ EvaluatorIsolationReadinessFailureCode,
+ | 'loader-probe-boot'
+ | 'invariant-namespace'
+ | 'invariant-environment'
+ | 'invariant-filesystem'
+ | 'invariant-network'
+ | 'invariant-generated-policy'
+>;
+
+export class EvaluatorIsolationReadinessError extends EvaluatorSubprocessError {
+ readonly readinessCode: EvaluatorIsolationReadinessFailureCode;
+
+ constructor(readinessCode: EvaluatorIsolationReadinessFailureCode) {
+ super('ISOLATION_UNAVAILABLE', 'Isolated evaluator readiness check failed.');
+ this.name = 'EvaluatorIsolationReadinessError';
+ this.readinessCode = readinessCode;
+ }
+}
+
+export function isolationReadinessFailureCode(
+ error: unknown,
+): EvaluatorIsolationReadinessFailureCode | undefined {
+ if (!(error instanceof EvaluatorIsolationReadinessError)) return undefined;
+ return READINESS_FAILURE_CODES.includes(error.readinessCode) ? error.readinessCode : undefined;
+}
+
+function isolationUnavailable(): never {
+ throw new EvaluatorSubprocessError('ISOLATION_UNAVAILABLE', 'Isolated evaluator is unavailable.');
+}
+
+function requiredAbsolutePath(value: string): string {
+ if (!posix.isAbsolute(value) || posix.normalize(value) !== value) isolationUnavailable();
+ return value;
+}
+
+function requiredRuntimeRoot(value: string): string {
+ const root = requiredAbsolutePath(value);
+ if (root !== DEFAULT_RUNTIME_ROOT) isolationUnavailable();
+ return root;
+}
+
+function workerInsideRuntime(workerPath: string, runtimeRoot: string): string {
+ const normalized = requiredAbsolutePath(workerPath);
+ const packageRoot = posix.join(runtimeRoot, 'node_modules') + posix.sep;
+ if (!normalized.startsWith(packageRoot)) isolationUnavailable();
+ return normalized;
+}
+
+function runtimeMounts(runtimeRoot: string, pathExists: (path: string) => boolean): string[] {
+ const mounts = ['/usr', '/lib', '/lib64', posix.join(runtimeRoot, 'node_modules')];
+ const existing = mounts.filter((path) => pathExists(path));
+ if (!existing.includes('/usr') || !existing.includes(posix.join(runtimeRoot, 'node_modules'))) {
+ isolationUnavailable();
+ }
+ return existing;
+}
+
+/**
+ * Build the exact Linux process boundary used by production AgentCore images.
+ * The outer image runs as a non-root user. setpriv clears inheritable/ambient
+ * capabilities and locks no-new-privs before bubblewrap creates fresh user,
+ * PID, network, mount, IPC, UTS, and cgroup namespaces. bubblewrap drops the
+ * bounding/effective sets after entering its user namespace, where that drop
+ * is valid for the non-root caller. Only the language runtime and installed
+ * dependency tree are mounted read-only; scratch is tmpfs.
+ */
+function isolatedEvaluatorLaunchWithLoader(
+ workerPath: string,
+ host: IsolatedEvaluatorHost = {},
+ loader: 'tsx' | 'module' = 'tsx',
+): EvaluatorProcessLaunch {
+ const platform = host.platform ?? process.platform;
+ if (platform !== 'linux') isolationUnavailable();
+ const runtimeRoot = requiredRuntimeRoot(host.runtimeRoot ?? DEFAULT_RUNTIME_ROOT);
+ const pathExists = host.pathExists ?? existsSync;
+ const bwrapPath = requiredAbsolutePath(host.bwrapPath ?? DEFAULT_BWRAP_PATH);
+ const setprivPath = requiredAbsolutePath(host.setprivPath ?? DEFAULT_SETPRIV_PATH);
+ const prlimitPath = requiredAbsolutePath(host.prlimitPath ?? DEFAULT_PRLIMIT_PATH);
+ const nodePath = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);
+ for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath]) {
+ if (!pathExists(executable)) isolationUnavailable();
+ }
+ const resolvedWorkerPath = workerInsideRuntime(workerPath, runtimeRoot);
+ if (!pathExists(resolvedWorkerPath)) isolationUnavailable();
+
+ const bwrapArgs = [
+ '--unshare-all',
+ '--die-with-parent',
+ '--new-session',
+ '--disable-userns',
+ '--cap-drop',
+ 'ALL',
+ '--clearenv',
+ '--setenv',
+ 'NODE_ENV',
+ 'production',
+ '--setenv',
+ 'NO_COLOR',
+ '1',
+ '--proc',
+ '/proc',
+ '--dev',
+ '/dev',
+ '--tmpfs',
+ '/tmp',
+ '--dir',
+ runtimeRoot,
+ '--dir',
+ posix.join(runtimeRoot, 'node_modules'),
+ ];
+ for (const mount of runtimeMounts(runtimeRoot, pathExists)) {
+ bwrapArgs.push('--ro-bind', mount, mount);
+ }
+ const nodeArgs = [nodePath, '--max-old-space-size=512', '--disable-proto=throw'];
+ if (loader === 'tsx') nodeArgs.push('--import', 'tsx');
+ nodeArgs.push(resolvedWorkerPath);
+ bwrapArgs.push(
+ '--chdir',
+ runtimeRoot,
+ '--preserve-fds',
+ '1',
+ '--',
+ prlimitPath,
+ '--cpu=65:65',
+ '--as=6442450944:6442450944',
+ '--fsize=100663296:100663296',
+ '--nofile=64:64',
+ '--nproc=64:64',
+ '--',
+ ...nodeArgs,
+ );
+
+ return {
+ command: setprivPath,
+ args: [
+ '--no-new-privs',
+ '--inh-caps=-all',
+ '--ambient-caps=-all',
+ '--',
+ bwrapPath,
+ ...bwrapArgs,
+ ],
+ // The wrapper receives no product/provider environment. bubblewrap clears
+ // even this two-key environment before creating the worker environment.
+ env: sanitizedEvaluatorEnv({}),
+ detached: true,
+ };
+}
+
+export function isolatedEvaluatorLaunch(
+ workerPath: string,
+ host: IsolatedEvaluatorHost = {},
+): EvaluatorProcessLaunch {
+ return isolatedEvaluatorLaunchWithLoader(workerPath, host, 'tsx');
+}
+
+export async function renderGLBViaIsolatedEvaluator(
+ code: string,
+ options: RenderGlbOptions = {},
+ controls: IsolatedEvaluatorControls = {},
+): Promise<RenderResult> {
+ const workerPath = fileURLToPath(new URL('./worker.ts', import.meta.url));
+ const launch = isolatedEvaluatorLaunch(workerPath, controls.host);
+ const { host: _, ...processControls } = controls;
+ return renderGLBViaProcessLaunch(code, options, processControls, launch);
+}
+
+export function decodeEvaluatorIsolationReadiness(
+ value: unknown,
+): EvaluatorIsolationReadiness | EvaluatorIsolationReadinessFailure {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) isolationUnavailable();
+ const record = value as Record<string, unknown>;
+ if (
+ Object.keys(record).sort().join(',') === 'failure,mode,version' &&
+ record.version === READINESS_VERSION &&
+ record.mode === 'isolated' &&
+ [
+ 'loader-probe-boot',
+ 'invariant-namespace',
+ 'invariant-environment',
+ 'invariant-filesystem',
+ 'invariant-network',
+ 'invariant-generated-policy',
+ ].includes(String(record.failure))
+ ) {
+ return record as unknown as EvaluatorIsolationReadinessFailure;
+ }
+ if (
+ Object.keys(record).sort().join(',') !== 'checks,mode,version' ||
+ record.version !== READINESS_VERSION ||
+ record.mode !== 'isolated' ||
+ !Array.isArray(record.checks) ||
+ record.checks.length !== READINESS_CHECKS.length ||
+ record.checks.join(',') !== READINESS_CHECKS.join(',')
+ ) {
+ isolationUnavailable();
+ }
+ return record as unknown as EvaluatorIsolationReadiness;
+}
+
+export function decodeEvaluatorIsolationTransport(value: unknown): EvaluatorIsolationTransport {
+ if (
+ typeof value !== 'object' ||
+ value === null ||
+ Array.isArray(value) ||
+ Object.keys(value).sort().join(',') !== 'transport,version'
+ ) {
+ isolationUnavailable();
+ }
+ const record = value as Record<string, unknown>;
+ if (record.version !== TRANSPORT_VERSION || record.transport !== 'fd3') isolationUnavailable();
+ return record as unknown as EvaluatorIsolationTransport;
+}
+
+function terminateReadinessChild(child: ReturnType<typeof spawn>): void {
+ try {
+ if (child.pid) process.kill(-child.pid, 'SIGKILL');
+ } catch {}
+}
+
+async function assertIsolationTransport(launch: EvaluatorProcessLaunch): Promise<void> {
+ return await new Promise<void>((resolve, reject) => {
+ const child = spawn(launch.command, launch.args, {
+ env: launch.env,
+ windowsHide: true,
+ detached: true,
+ stdio: ['ignore', 'pipe', 'ignore', 'pipe'],
+ });
+ const stdoutChunks: Buffer[] = [];
+ const protocolChunks: Buffer[] = [];
+ let stdoutBytes = 0;
+ let protocolBytes = 0;
+ let settled = false;
+ const fail = (readinessCode: EvaluatorIsolationReadinessFailureCode) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ reject(new EvaluatorIsolationReadinessError(readinessCode));
+ };
+ const timer = setTimeout(() => {
+ terminateReadinessChild(child);
+ fail('deadline');
+ }, PROBE_DEADLINE_MS);
+ child.stdout?.on('data', (chunk: Buffer) => {
+ stdoutBytes += chunk.byteLength;
+ if (stdoutBytes > MAX_TRANSPORT_STDOUT_BYTES) {
+ terminateReadinessChild(child);
+ fail('wrapper-launch');
+ return;
+ }
+ stdoutChunks.push(Buffer.from(chunk));
+ });
+ const protocol = child.stdio[3];
+ if (!protocol) {
+ terminateReadinessChild(child);
+ fail('fd3-transport');
+ return;
+ }
+ protocol.on('data', (chunk: Buffer) => {
+ protocolBytes += chunk.byteLength;
+ if (protocolBytes > MAX_READINESS_PROTOCOL_BYTES) {
+ terminateReadinessChild(child);
+ fail('fd3-transport');
+ return;
+ }
+ protocolChunks.push(Buffer.from(chunk));
+ });
+ child.once('error', () => fail('wrapper-launch'));
+ child.once('close', (code) => {
+ if (settled) return;
+ const stdout = Buffer.concat(stdoutChunks).toString('utf8');
+ if (stdout !== TRANSPORT_STDOUT_MARKER) return fail('wrapper-launch');
+ if (code !== 0 || protocolChunks.length === 0) return fail('fd3-transport');
+ try {
+ decodeEvaluatorIsolationTransport(
+ JSON.parse(Buffer.concat(protocolChunks).toString('utf8')),
+ );
+ settled = true;
+ clearTimeout(timer);
+ resolve();
+ } catch {
+ fail('fd3-transport');
+ }
+ });
+ });
+}
+
+async function runIsolationProbe(
+ launch: EvaluatorProcessLaunch,
+): Promise<EvaluatorIsolationReadiness> {
+ return await new Promise<EvaluatorIsolationReadiness>((resolve, reject) => {
+ const child = spawn(launch.command, launch.args, {
+ env: launch.env,
+ windowsHide: true,
+ detached: true,
+ stdio: ['ignore', 'ignore', 'ignore', 'pipe'],
+ });
+ const protocol = child.stdio[3];
+ const chunks: Buffer[] = [];
+ let bytes = 0;
+ let settled = false;
+ const fail = (readinessCode: EvaluatorIsolationReadinessFailureCode) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ reject(new EvaluatorIsolationReadinessError(readinessCode));
+ };
+ const timer = setTimeout(() => {
+ terminateReadinessChild(child);
+ fail('deadline');
+ }, PROBE_DEADLINE_MS);
+ if (!protocol) {
+ terminateReadinessChild(child);
+ fail('fd3-transport');
+ return;
+ }
+ protocol.on('data', (chunk: Buffer) => {
+ bytes += chunk.byteLength;
+ if (bytes > MAX_READINESS_PROTOCOL_BYTES) {
+ terminateReadinessChild(child);
+ fail('loader-probe-boot');
+ return;
+ }
+ chunks.push(Buffer.from(chunk));
+ });
+ child.once('error', () => fail('wrapper-launch'));
+ child.once('close', (code) => {
+ if (settled) return;
+ if (chunks.length === 0) return fail('loader-probe-boot');
+ try {
+ const result = decodeEvaluatorIsolationReadiness(
+ JSON.parse(Buffer.concat(chunks).toString('utf8')),
+ );
+ if ('failure' in result) return fail(result.failure);
+ if (code !== 0) return fail('loader-probe-boot');
+ settled = true;
+ clearTimeout(timer);
+ resolve(result);
+ } catch {
+ fail('loader-probe-boot');
+ }
+ });
+ });
+}
+
+/** Fail-closed boot/readiness proof. Package presence alone is not accepted. */
+export async function assertIsolatedEvaluatorReady(
+ host: IsolatedEvaluatorHost = {},
+): Promise<EvaluatorIsolationReadiness> {
+ if (typeof process.getuid !== 'function' || process.getuid() === 0) {
+ throw new EvaluatorIsolationReadinessError('invariant-namespace');
+ }
+ const transportPath = fileURLToPath(new URL('./transport-worker.mjs', import.meta.url));
+ const probePath = fileURLToPath(new URL('./probe-worker.ts', import.meta.url));
+ let transportLaunch: EvaluatorProcessLaunch;
+ let probeLaunch: EvaluatorProcessLaunch;
+ try {
+ transportLaunch = isolatedEvaluatorLaunchWithLoader(transportPath, host, 'module');
+ probeLaunch = isolatedEvaluatorLaunch(probePath, host);
+ } catch {
+ throw new EvaluatorIsolationReadinessError('wrapper-launch');
+ }
+ await assertIsolationTransport(transportLaunch);
+ return await runIsolationProbe(probeLaunch);
+}
diff --git a/src/evaluator/probe-invariants.ts b/src/evaluator/probe-invariants.ts
new file mode 100644
index 00000000..6c3fa5c1
--- /dev/null
+++ b/src/evaluator/probe-invariants.ts
@@ -0,0 +1,9 @@
+const CAPABILITY_STATUS_FIELDS = ['CapInh', 'CapPrm', 'CapEff', 'CapBnd', 'CapAmb'] as const;
+
+/** Require every capability set exposed by /proc to be present and empty. */
+export function processCapabilitiesAreEmpty(status: string | undefined): boolean {
+ if (typeof status !== 'string') return false;
+ return CAPABILITY_STATUS_FIELDS.every((field) =>
+ new RegExp(`^${field}:\\s+0+$`, 'm').test(status),
+ );
+}
diff --git a/src/evaluator/probe-worker.ts b/src/evaluator/probe-worker.ts
new file mode 100644
index 00000000..25c51c62
--- /dev/null
+++ b/src/evaluator/probe-worker.ts
@@ -0,0 +1,158 @@
+import { readFile, writeFile } from 'node:fs/promises';
+import { connect } from 'node:net';
+import { networkInterfaces } from 'node:os';
+import { validate } from '../validation';
+import { writeFileSync } from 'node:fs';
+import { processCapabilitiesAreEmpty } from './probe-invariants';
+
+const VERSION = 'kiln.evaluator.isolation-readiness.v1';
+type ProbeFailure =
+ | 'loader-probe-boot'
+ | 'invariant-namespace'
+ | 'invariant-environment'
+ | 'invariant-filesystem'
+ | 'invariant-network'
+ | 'invariant-generated-policy';
+
+async function deniedRead(path: string): Promise<boolean> {
+ try {
+ await readFile(path);
+ return false;
+ } catch {
+ return true;
+ }
+}
+
+async function optionalRead(path: string): Promise<string | undefined> {
+ try {
+ return await readFile(path, 'utf8');
+ } catch {
+ return undefined;
+ }
+}
+
+async function deniedWrite(path: string): Promise<boolean> {
+ try {
+ await writeFile(path, 'denied');
+ return false;
+ } catch {
+ return true;
+ }
+}
+
+async function deniedConnect(host: string, port: number): Promise<boolean> {
+ return await new Promise<boolean>((resolve) => {
+ let socket: ReturnType<typeof connect>;
+ try {
+ socket = connect({ host, port });
+ } catch {
+ resolve(true);
+ return;
+ }
+ const timer = setTimeout(() => {
+ socket.destroy();
+ resolve(true);
+ }, 250);
+ socket.once('connect', () => {
+ clearTimeout(timer);
+ socket.destroy();
+ resolve(false);
+ });
+ socket.once('error', () => {
+ clearTimeout(timer);
+ resolve(true);
+ });
+ });
+}
+
+function isolationInterfaces(): ReturnType<typeof networkInterfaces> | undefined {
+ try {
+ return networkInterfaces();
+ } catch {
+ return undefined;
+ }
+}
+
+function writeFailure(failure: ProbeFailure): void {
+ writeFileSync(3, JSON.stringify({ version: VERSION, mode: 'isolated', failure }), {
+ encoding: 'utf8',
+ });
+}
+
+function groupedFailure(failedChecks: readonly string[]): ProbeFailure {
+ const failed = new Set(failedChecks);
+ if (
+ ['user-namespace', 'no-new-privileges', 'capabilities-empty'].some((name) => failed.has(name))
+ ) {
+ return 'invariant-namespace';
+ }
+ if (failed.has('environment-exact')) return 'invariant-environment';
+ if (
+ ['product-filesystem-denied', 'host-filesystem-denied', 'runtime-filesystem-read-only'].some(
+ (name) => failed.has(name),
+ )
+ ) {
+ return 'invariant-filesystem';
+ }
+ if (
+ ['network-namespace-empty', 'metadata-and-local-network-denied'].some((name) =>
+ failed.has(name),
+ )
+ ) {
+ return 'invariant-network';
+ }
+ return 'invariant-generated-policy';
+}
+
+function generatedDenials(): boolean {
+ const prelude = "const meta = { name: 'probe' }; function build(){ return createRoot('probe'); }";
+ const probes = [
+ `const leak = process.env; ${prelude}`,
+ `const leak = fetch('http://169.254.169.254/'); ${prelude}`,
+ `const leak = globalThis.process.mainModule.require('fs'); ${prelude}`,
+ `const leak = globalThis.process.mainModule.require('child_process'); ${prelude}`,
+ ];
+ return probes.every((source) => !validate(source).valid);
+}
+
+async function main(): Promise<void> {
+ const status = await optionalRead('/proc/self/status');
+ const uidMap = await optionalRead('/proc/self/uid_map');
+ const envKeys = Object.keys(process.env).sort();
+ const outsideUid = Number(uidMap?.trim().split(/\s+/)[1]);
+ const interfaceMap = isolationInterfaces();
+ const interfaces = interfaceMap ? Object.values(interfaceMap).flat().filter(Boolean) : undefined;
+ const checks: Array<[string, boolean]> = [
+ ['user-namespace', Number.isInteger(outsideUid) && outsideUid > 0],
+ ['no-new-privileges', typeof status === 'string' && /^NoNewPrivs:\s+1$/m.test(status)],
+ ['capabilities-empty', processCapabilitiesAreEmpty(status)],
+ ['environment-exact', envKeys.join(',') === 'NODE_ENV,NO_COLOR'],
+ ['product-filesystem-denied', await deniedRead('/app/agent-runtime/src/server.ts')],
+ ['host-filesystem-denied', await deniedRead('/etc/passwd')],
+ ['runtime-filesystem-read-only', await deniedWrite('/app/node_modules/.kiln-probe')],
+ ['network-namespace-empty', interfaces?.every((entry) => entry?.internal === true) === true],
+ [
+ 'metadata-and-local-network-denied',
+ (await deniedConnect('169.254.169.254', 80)) && (await deniedConnect('127.0.0.1', 8080)),
+ ],
+ ['generated-capabilities-denied', generatedDenials()],
+ ];
+ const failedChecks = checks.filter(([, ok]) => !ok).map(([name]) => name);
+ if (failedChecks.length > 0) {
+ writeFailure(groupedFailure(failedChecks));
+ process.exitCode = 1;
+ } else {
+ writeFileSync(
+ 3,
+ JSON.stringify({ version: VERSION, mode: 'isolated', checks: checks.map(([name]) => name) }),
+ { encoding: 'utf8' },
+ );
+ }
+}
+
+await main().catch(() => {
+ try {
+ writeFailure('loader-probe-boot');
+ } catch {}
+ process.exitCode = 1;
+});
diff --git a/src/evaluator/protocol.test.ts b/src/evaluator/protocol.test.ts
new file mode 100644
index 00000000..bd2bc4b5
--- /dev/null
+++ b/src/evaluator/protocol.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ decodeEvaluatorRequestV1,
+ decodeEvaluatorResultV1,
+ encodeRenderResultV1,
+ EVALUATOR_REQUEST_VERSION,
+ EVALUATOR_RESULT_VERSION,
+} from './protocol';
+
+const request = {
+ version: EVALUATOR_REQUEST_VERSION,
+ requestId: 'render-1',
+ operation: 'execute-export-glb' as const,
+ code: "const meta={name:'Box'}; function build(){return createRoot('Box');}",
+ options: { optimize: 'off' as const },
+ limits: { maxGlbBytes: 1024 },
+};
+
+describe('evaluator protocol v1', () => {
+ test('accepts the exact versioned request shape', () => {
+ expect(decodeEvaluatorRequestV1(JSON.stringify(request))).toEqual(request);
+ });
+
+ test('rejects unknown capabilities and oversized source', () => {
+ expect(() =>
+ decodeEvaluatorRequestV1(JSON.stringify({ ...request, url: 'https://example.invalid' })),
+ ).toThrow('invalid evaluator request');
+ expect(() =>
+ decodeEvaluatorRequestV1(JSON.stringify({ ...request, code: 'x'.repeat(513 * 1024) })),
+ ).toThrow('invalid evaluator request');
+ expect(() =>
+ decodeEvaluatorRequestV1(
+ JSON.stringify({ ...request, options: { ...request.options, category: 'spaceship' } }),
+ ),
+ ).toThrow('invalid evaluator request');
+ });
+
+ test('round-trips binary fields and verifies the exact GLB identity', () => {
+ const glb = Buffer.from('glTF-test');
+ const hash = `sha256:${new Bun.CryptoHasher('sha256').update(glb).digest('hex')}` as const;
+ const wire = encodeRenderResultV1('render-1', {
+ glb,
+ artifactGlbSha256: hash,
+ tris: 0,
+ meta: { name: 'Box' },
+ warnings: [],
+ diagnosticViews: [
+ {
+ id: 'front',
+ label: 'Front',
+ width: 1,
+ height: 1,
+ png: Buffer.from('png'),
+ },
+ ] as never,
+ integrationManifest: {} as never,
+ });
+ const decoded = decodeEvaluatorResultV1(JSON.stringify(wire), 1024);
+ expect(decoded.version).toBe(EVALUATOR_RESULT_VERSION);
+ expect(decoded.ok).toBe(true);
+ if (decoded.ok) {
+ expect(decoded.render.glb).toEqual(glb);
+ expect(decoded.render.diagnosticViews?.[0]?.png).toEqual(Buffer.from('png'));
+ }
+
+ if (!wire.ok) throw new Error('expected success wire result');
+ const corrupt = {
+ ...wire,
+ render: { ...wire.render, artifactGlbSha256: `sha256:${'0'.repeat(64)}` },
+ };
+ expect(() => decodeEvaluatorResultV1(JSON.stringify(corrupt), 1024)).toThrow(
+ 'invalid evaluator result',
+ );
+ });
+
+ test('rejects worker-controlled error text even when the outcome code is valid', () => {
+ const failure = {
+ version: EVALUATOR_RESULT_VERSION,
+ requestId: 'render-1',
+ ok: false,
+ error: {
+ code: 'EXECUTION_REJECTED',
+ message: 'provider prompt /app/private.ts sk-not-a-real-secret-but-sensitive',
+ },
+ };
+ expect(() => decodeEvaluatorResultV1(JSON.stringify(failure), 1024)).toThrow(
+ 'invalid evaluator result',
+ );
+ });
+});
diff --git a/src/evaluator/protocol.ts b/src/evaluator/protocol.ts
new file mode 100644
index 00000000..0f0d21b3
--- /dev/null
+++ b/src/evaluator/protocol.ts
@@ -0,0 +1,278 @@
+import { createHash } from 'node:crypto';
+import { isAssetCategory, validateAssetIntentV1, type AssetIntentV1 } from '../contracts';
+import type { RenderGlbOptions, RenderResult } from '../render';
+import type { KhronosGltfValidationReport } from '../qa/gltf';
+import type { AssetQaReportV1 } from '../qa/types';
+
+export const EVALUATOR_REQUEST_VERSION = 'kiln.evaluator.request.v1' as const;
+export const EVALUATOR_RESULT_VERSION = 'kiln.evaluator.result.v1' as const;
+export const MAX_EVALUATOR_CODE_BYTES = 512 * 1024;
+export const MAX_EVALUATOR_REQUEST_BYTES = 1024 * 1024;
+
+export type EvaluatorOutcomeCode =
+ | 'INPUT_INVALID'
+ | 'EXECUTION_REJECTED'
+ | 'QA_BLOCKED'
+ | 'DEADLINE_EXCEEDED'
+ | 'OUTPUT_LIMIT_EXCEEDED'
+ | 'ISOLATION_UNAVAILABLE'
+ | 'WORKER_FAILED'
+ | 'PROTOCOL_ERROR';
+
+const EVALUATOR_OUTCOME_MESSAGES: Record<EvaluatorOutcomeCode, string> = {
+ INPUT_INVALID: 'Evaluator request was invalid.',
+ EXECUTION_REJECTED: 'Generated asset execution was rejected.',
+ QA_BLOCKED: 'Generated asset did not pass quality checks.',
+ DEADLINE_EXCEEDED: 'Evaluator deadline exceeded.',
+ OUTPUT_LIMIT_EXCEEDED: 'Evaluator output limit exceeded.',
+ ISOLATION_UNAVAILABLE: 'Isolated evaluator is unavailable.',
+ WORKER_FAILED: 'Evaluator worker failed.',
+ PROTOCOL_ERROR: 'Evaluator returned invalid data.',
+};
+
+export function evaluatorOutcomeMessage(code: EvaluatorOutcomeCode): string {
+ return EVALUATOR_OUTCOME_MESSAGES[code];
+}
+
+export interface EvaluatorRequestV1 {
+ version: typeof EVALUATOR_REQUEST_VERSION;
+ requestId: string;
+ operation: 'execute-export-glb';
+ code: string;
+ options: Omit<RenderGlbOptions, 'textureResolver'>;
+ limits: { maxGlbBytes: number };
+}
+
+interface WireDiagnosticView {
+ [key: string]: unknown;
+ pngBase64: string;
+}
+
+interface WireRenderResult extends Omit<RenderResult, 'glb' | 'diagnosticViews'> {
+ glbBase64: string;
+ diagnosticViews?: WireDiagnosticView[];
+}
+
+export type EvaluatorResultV1 =
+ | {
+ version: typeof EVALUATOR_RESULT_VERSION;
+ requestId: string;
+ ok: true;
+ render: RenderResult;
+ }
+ | {
+ version: typeof EVALUATOR_RESULT_VERSION;
+ requestId: string;
+ ok: false;
+ error: {
+ code: EvaluatorOutcomeCode;
+ message: string;
+ qa?: {
+ report: AssetQaReportV1;
+ stage: 'scene' | 'final-glb';
+ gltfValidation?: KhronosGltfValidationReport;
+ };
+ };
+ };
+
+export type WireEvaluatorResultV1 =
+ | (Omit<Extract<EvaluatorResultV1, { ok: true }>, 'render'> & { render: WireRenderResult })
+ | Extract<EvaluatorResultV1, { ok: false }>;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function hasExactKeys(value: Record<string, unknown>, allowed: readonly string[]): boolean {
+ return Object.keys(value).every((key) => allowed.includes(key));
+}
+
+function fail(kind: 'request' | 'result'): never {
+ throw new Error(`invalid evaluator ${kind}`);
+}
+
+function validRequestId(value: unknown): value is string {
+ return typeof value === 'string' && /^[A-Za-z0-9._-]{1,64}$/.test(value);
+}
+
+function validInteger(value: unknown, min: number, max: number): value is number {
+ return Number.isInteger(value) && Number(value) >= min && Number(value) <= max;
+}
+
+function parseOptions(value: unknown): Omit<RenderGlbOptions, 'textureResolver'> {
+ if (!isRecord(value) || !hasExactKeys(value, ['optimize', 'instance', 'intent', 'category'])) {
+ return fail('request');
+ }
+ const options: Omit<RenderGlbOptions, 'textureResolver'> = {};
+ if (value.optimize !== undefined) {
+ if (!['off', 'auto', 'palette', 'full'].includes(String(value.optimize))) fail('request');
+ options.optimize = value.optimize as NonNullable<RenderGlbOptions['optimize']>;
+ }
+ if (value.instance !== undefined) {
+ if (!['off', 'auto', 'on'].includes(String(value.instance))) fail('request');
+ options.instance = value.instance as NonNullable<RenderGlbOptions['instance']>;
+ }
+ if (value.category !== undefined) {
+ if (!isAssetCategory(value.category)) fail('request');
+ options.category = value.category;
+ }
+ if (value.intent !== undefined) {
+ const result = validateAssetIntentV1(value.intent);
+ if (!result.valid) fail('request');
+ options.intent = result.value as AssetIntentV1;
+ }
+ return options;
+}
+
+export function decodeEvaluatorRequestV1(json: string): EvaluatorRequestV1 {
+ if (Buffer.byteLength(json, 'utf8') > MAX_EVALUATOR_REQUEST_BYTES) fail('request');
+ let value: unknown;
+ try {
+ value = JSON.parse(json);
+ } catch {
+ return fail('request');
+ }
+ if (
+ !isRecord(value) ||
+ !hasExactKeys(value, ['version', 'requestId', 'operation', 'code', 'options', 'limits']) ||
+ value.version !== EVALUATOR_REQUEST_VERSION ||
+ !validRequestId(value.requestId) ||
+ value.operation !== 'execute-export-glb' ||
+ typeof value.code !== 'string' ||
+ Buffer.byteLength(value.code, 'utf8') > MAX_EVALUATOR_CODE_BYTES ||
+ !isRecord(value.limits) ||
+ !hasExactKeys(value.limits, ['maxGlbBytes']) ||
+ !validInteger(value.limits.maxGlbBytes, 1, 64 * 1024 * 1024)
+ ) {
+ return fail('request');
+ }
+ return {
+ version: EVALUATOR_REQUEST_VERSION,
+ requestId: value.requestId,
+ operation: 'execute-export-glb',
+ code: value.code,
+ options: parseOptions(value.options),
+ limits: { maxGlbBytes: value.limits.maxGlbBytes },
+ };
+}
+
+export function encodeRenderResultV1(
+ requestId: string,
+ render: RenderResult,
+): WireEvaluatorResultV1 {
+ const { glb, diagnosticViews, ...rest } = render;
+ return {
+ version: EVALUATOR_RESULT_VERSION,
+ requestId,
+ ok: true,
+ render: {
+ ...rest,
+ glbBase64: glb.toString('base64'),
+ ...(diagnosticViews
+ ? {
+ diagnosticViews: diagnosticViews.map(({ png, ...view }) => ({
+ ...view,
+ pngBase64: Buffer.from(png).toString('base64'),
+ })),
+ }
+ : {}),
+ },
+ };
+}
+
+function isSha256(value: unknown): value is `sha256:${string}` {
+ return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value);
+}
+
+export function decodeEvaluatorResultV1(json: string, maxGlbBytes: number): EvaluatorResultV1 {
+ let value: unknown;
+ try {
+ value = JSON.parse(json);
+ } catch {
+ return fail('result');
+ }
+ if (
+ !isRecord(value) ||
+ !hasExactKeys(value, ['version', 'requestId', 'ok', 'render', 'error']) ||
+ value.version !== EVALUATOR_RESULT_VERSION ||
+ !validRequestId(value.requestId) ||
+ typeof value.ok !== 'boolean'
+ ) {
+ return fail('result');
+ }
+ if (!value.ok) {
+ if (value.render !== undefined) return fail('result');
+ if (!isRecord(value.error) || !hasExactKeys(value.error, ['code', 'message', 'qa'])) {
+ return fail('result');
+ }
+ const codes: EvaluatorOutcomeCode[] = [
+ 'INPUT_INVALID',
+ 'EXECUTION_REJECTED',
+ 'QA_BLOCKED',
+ 'DEADLINE_EXCEEDED',
+ 'OUTPUT_LIMIT_EXCEEDED',
+ 'ISOLATION_UNAVAILABLE',
+ 'WORKER_FAILED',
+ 'PROTOCOL_ERROR',
+ ];
+ if (
+ !codes.includes(value.error.code as EvaluatorOutcomeCode) ||
+ typeof value.error.message !== 'string' ||
+ value.error.message !== evaluatorOutcomeMessage(value.error.code as EvaluatorOutcomeCode)
+ ) {
+ return fail('result');
+ }
+ return value as unknown as Extract<EvaluatorResultV1, { ok: false }>;
+ }
+ if (value.error !== undefined || !isRecord(value.render)) fail('result');
+ const renderKeys = [
+ 'glbBase64',
+ 'artifactGlbSha256',
+ 'tris',
+ 'meta',
+ 'warnings',
+ 'diagnosticViews',
+ 'materialMetrics',
+ 'materialRecipeApplications',
+ 'materialResourceProvenance',
+ 'bakedTextures',
+ 'integrationManifest',
+ ] as const;
+ if (
+ !hasExactKeys(value.render, renderKeys) ||
+ typeof value.render.glbBase64 !== 'string' ||
+ !validInteger(value.render.tris, 0, Number.MAX_SAFE_INTEGER) ||
+ !isRecord(value.render.meta) ||
+ !Array.isArray(value.render.warnings) ||
+ !value.render.warnings.every((warning) => typeof warning === 'string') ||
+ !isRecord(value.render.integrationManifest)
+ ) {
+ fail('result');
+ }
+ const glb = Buffer.from(value.render.glbBase64, 'base64');
+ if (glb.byteLength > maxGlbBytes || glb.toString('base64') !== value.render.glbBase64)
+ fail('result');
+ if (!isSha256(value.render.artifactGlbSha256)) fail('result');
+ const actualHash = `sha256:${createHash('sha256').update(glb).digest('hex')}`;
+ if (actualHash !== value.render.artifactGlbSha256) fail('result');
+ const diagnosticViews = value.render.diagnosticViews;
+ if (diagnosticViews !== undefined && !Array.isArray(diagnosticViews)) fail('result');
+ const decodedViews = diagnosticViews?.map((candidate) => {
+ if (!isRecord(candidate) || typeof candidate.pngBase64 !== 'string') return fail('result');
+ const png = Buffer.from(candidate.pngBase64, 'base64');
+ if (png.toString('base64') !== candidate.pngBase64) return fail('result');
+ const { pngBase64: _, ...view } = candidate;
+ return { ...view, png };
+ });
+ const { glbBase64: _, diagnosticViews: __, ...rest } = value.render;
+ return {
+ version: EVALUATOR_RESULT_VERSION,
+ requestId: value.requestId,
+ ok: true,
+ render: {
+ ...rest,
+ glb,
+ ...(decodedViews ? { diagnosticViews: decodedViews } : {}),
+ } as unknown as RenderResult,
+ };
+}
diff --git a/src/evaluator/subprocess.test.ts b/src/evaluator/subprocess.test.ts
new file mode 100644
index 00000000..b06e033e
--- /dev/null
+++ b/src/evaluator/subprocess.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, test } from 'bun:test';
+import { renderGLBInProcess, resolveEvaluatorMode } from '../render';
+import {
+ EvaluatorSubprocessError,
+ renderGLBViaSubprocess,
+ sanitizedEvaluatorEnv,
+} from './subprocess';
+
+const BOX_CODE = `
+const meta = { name: 'EvaluatorBox' };
+function build() {
+ const root = createRoot('EvaluatorBox');
+ createPart('Body', boxGeo(1, 1, 1), gameMaterial('#ff0000'), { parent: root });
+ return root;
+}`;
+
+describe('subprocess evaluator scaffold', () => {
+ test('exports the same deterministic GLB through the v1 protocol', async () => {
+ const direct = await renderGLBInProcess(BOX_CODE);
+ const contained = await renderGLBViaSubprocess(BOX_CODE, {}, { deadlineMs: 30_000 });
+ expect(contained.artifactGlbSha256).toBe(direct.artifactGlbSha256);
+ expect(contained.glb).toEqual(direct.glb);
+ }, 60_000);
+
+ test('does not inherit provider, AWS, loader, or Kiln environment variables', () => {
+ const env = sanitizedEvaluatorEnv({
+ PATH: 'safe-path',
+ SystemRoot: 'safe-root',
+ AWS_SECRET_ACCESS_KEY: 'secret',
+ OPENAI_API_KEY: 'secret',
+ NODE_OPTIONS: '--require evil',
+ KILN_EVALUATOR_MODE: 'subprocess',
+ KILN_QA_MODE: 'observe',
+ });
+ expect(env.PATH).toBe('safe-path');
+ expect(env.SystemRoot).toBe('safe-root');
+ expect(env.AWS_SECRET_ACCESS_KEY).toBeUndefined();
+ expect(env.OPENAI_API_KEY).toBeUndefined();
+ expect(env.NODE_OPTIONS).toBeUndefined();
+ expect(env.KILN_EVALUATOR_MODE).toBeUndefined();
+ expect(env.KILN_QA_MODE).toBeUndefined();
+ });
+
+ test('is disabled by default and rejects misspelled modes', () => {
+ expect(resolveEvaluatorMode({})).toBe('in-process');
+ expect(resolveEvaluatorMode({ KILN_EVALUATOR_MODE: 'subprocess' })).toBe('subprocess');
+ expect(resolveEvaluatorMode({ KILN_EVALUATOR_MODE: 'isolated' })).toBe('isolated');
+ expect(() => resolveEvaluatorMode({ KILN_EVALUATOR_MODE: 'subproces' })).toThrow(
+ 'Invalid KILN_EVALUATOR_MODE',
+ );
+ });
+
+ test('refuses an unserializable trusted TextureResolver capability', async () => {
+ await expect(
+ renderGLBViaSubprocess(BOX_CODE, { textureResolver: {} as never }),
+ ).rejects.toMatchObject({ code: 'INPUT_INVALID' });
+ });
+
+ test('terminates a non-completing build at the host deadline', async () => {
+ const never = `async function build(){ await new Promise(() => {}); }`;
+ await expect(
+ renderGLBViaSubprocess(never, {}, { deadlineMs: 100, maxResponseBytes: 1024 * 1024 }),
+ ).rejects.toMatchObject({ code: 'DEADLINE_EXCEEDED' });
+ }, 10_000);
+
+ test('fails closed when the output cap is exceeded', async () => {
+ try {
+ await renderGLBViaSubprocess(BOX_CODE, {}, { deadlineMs: 30_000, maxGlbBytes: 32 });
+ throw new Error('expected output cap failure');
+ } catch (error) {
+ expect(error).toBeInstanceOf(EvaluatorSubprocessError);
+ expect(error).toMatchObject({ code: 'OUTPUT_LIMIT_EXCEEDED' });
+ }
+ }, 60_000);
+
+ test('does not leak rejected source text through the worker error', async () => {
+ const marker = 'DO_NOT_ECHO_SOURCE_8c183';
+ try {
+ await renderGLBViaSubprocess(
+ `const ${marker} = globalThis; function build(){}`,
+ {},
+ {
+ deadlineMs: 30_000,
+ },
+ );
+ throw new Error('expected rejection');
+ } catch (error) {
+ expect(error).toBeInstanceOf(EvaluatorSubprocessError);
+ expect(String(error)).not.toContain(marker);
+ expect(error).toMatchObject({ code: 'EXECUTION_REJECTED' });
+ }
+ });
+});
diff --git a/src/evaluator/subprocess.ts b/src/evaluator/subprocess.ts
new file mode 100644
index 00000000..e9cb1ac7
--- /dev/null
+++ b/src/evaluator/subprocess.ts
@@ -0,0 +1,203 @@
+import { spawn, type SpawnOptions } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import type { RenderGlbOptions, RenderResult } from '../render';
+import { AssetQaBlockedError } from '../qa/run';
+import {
+ decodeEvaluatorResultV1,
+ evaluatorOutcomeMessage,
+ EVALUATOR_REQUEST_VERSION,
+ type EvaluatorOutcomeCode,
+ type EvaluatorRequestV1,
+ MAX_EVALUATOR_REQUEST_BYTES,
+} from './protocol';
+
+const DEFAULT_DEADLINE_MS = 60_000;
+const DEFAULT_MAX_GLB_BYTES = 16 * 1024 * 1024;
+const DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
+const MAX_STDERR_BYTES = 16 * 1024;
+
+export interface EvaluatorSubprocessControls {
+ deadlineMs?: number;
+ maxGlbBytes?: number;
+ maxResponseBytes?: number;
+}
+
+export interface EvaluatorProcessLaunch {
+ command: string;
+ args: string[];
+ env: NodeJS.ProcessEnv;
+ detached?: boolean;
+}
+
+export class EvaluatorSubprocessError extends Error {
+ readonly code: EvaluatorOutcomeCode;
+
+ constructor(code: EvaluatorOutcomeCode, message: string) {
+ super(message);
+ this.name = 'EvaluatorSubprocessError';
+ this.code = code;
+ }
+}
+
+export function sanitizedEvaluatorEnv(
+ source: Record<string, string | undefined> = process.env,
+): NodeJS.ProcessEnv {
+ const env: NodeJS.ProcessEnv = { NODE_ENV: 'production', NO_COLOR: '1' };
+ for (const key of ['PATH', 'Path', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'TZ']) {
+ if (source[key] !== undefined) env[key] = source[key];
+ }
+ return env;
+}
+
+function boundedInteger(value: number | undefined, fallback: number, max: number): number {
+ const resolved = value ?? fallback;
+ if (!Number.isInteger(resolved) || resolved < 1 || resolved > max) {
+ throw new EvaluatorSubprocessError('INPUT_INVALID', 'Evaluator controls are invalid.');
+ }
+ return resolved;
+}
+
+function terminateProcess(child: ReturnType<typeof spawn>, detached: boolean): void {
+ if (!child.pid || child.killed) return;
+ try {
+ if (detached && process.platform !== 'win32') process.kill(-child.pid, 'SIGKILL');
+ else child.kill('SIGKILL');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
+ }
+}
+
+export async function renderGLBViaProcessLaunch(
+ code: string,
+ options: RenderGlbOptions = {},
+ controls: EvaluatorSubprocessControls = {},
+ launch?: EvaluatorProcessLaunch,
+): Promise<RenderResult> {
+ if (options.textureResolver) {
+ throw new EvaluatorSubprocessError(
+ 'INPUT_INVALID',
+ 'Subprocess evaluation does not accept host resolver capabilities.',
+ );
+ }
+ const deadlineMs = boundedInteger(controls.deadlineMs, DEFAULT_DEADLINE_MS, 120_000);
+ const maxGlbBytes = boundedInteger(controls.maxGlbBytes, DEFAULT_MAX_GLB_BYTES, 64 * 1024 * 1024);
+ const maxResponseBytes = boundedInteger(
+ controls.maxResponseBytes,
+ DEFAULT_MAX_RESPONSE_BYTES,
+ 96 * 1024 * 1024,
+ );
+ const request: EvaluatorRequestV1 = {
+ version: EVALUATOR_REQUEST_VERSION,
+ requestId: 'render-1',
+ operation: 'execute-export-glb',
+ code,
+ options,
+ limits: { maxGlbBytes },
+ };
+ const requestJson = JSON.stringify(request);
+ if (Buffer.byteLength(requestJson, 'utf8') > MAX_EVALUATOR_REQUEST_BYTES) {
+ throw new EvaluatorSubprocessError(
+ 'INPUT_INVALID',
+ 'Evaluator request exceeds its size limit.',
+ );
+ }
+
+ const workerPath = fileURLToPath(new URL('./worker.ts', import.meta.url));
+ const defaultLaunch: EvaluatorProcessLaunch = {
+ command: process.execPath,
+ args: process.versions.bun ? [workerPath] : ['--import', 'tsx', workerPath],
+ env: sanitizedEvaluatorEnv(),
+ };
+ const resolvedLaunch = launch ?? defaultLaunch;
+ const detached = resolvedLaunch.detached === true;
+
+ return await new Promise<RenderResult>((resolve, reject) => {
+ const spawnOptions: SpawnOptions = {
+ env: resolvedLaunch.env,
+ windowsHide: true,
+ stdio: ['pipe', 'ignore', 'pipe', 'pipe'],
+ ...(detached ? { detached: true } : {}),
+ };
+ const child = spawn(resolvedLaunch.command, resolvedLaunch.args, spawnOptions);
+ const protocol = child.stdio[3];
+ if (!protocol) {
+ terminateProcess(child, detached);
+ reject(new EvaluatorSubprocessError('WORKER_FAILED', 'Evaluator worker did not start.'));
+ return;
+ }
+ const chunks: Buffer[] = [];
+ let responseBytes = 0;
+ let stderrBytes = 0;
+ let settled = false;
+ const finish = (error?: Error, result?: RenderResult) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (error) reject(error);
+ else resolve(result as RenderResult);
+ };
+ const timer = setTimeout(() => {
+ terminateProcess(child, detached);
+ finish(new EvaluatorSubprocessError('DEADLINE_EXCEEDED', 'Evaluator deadline exceeded.'));
+ }, deadlineMs);
+
+ protocol.on('data', (chunk: Buffer) => {
+ responseBytes += chunk.byteLength;
+ if (responseBytes > maxResponseBytes) {
+ terminateProcess(child, detached);
+ finish(
+ new EvaluatorSubprocessError('OUTPUT_LIMIT_EXCEEDED', 'Evaluator output limit exceeded.'),
+ );
+ return;
+ }
+ chunks.push(Buffer.from(chunk));
+ });
+ child.stderr?.on('data', (chunk: Buffer) => {
+ stderrBytes = Math.min(MAX_STDERR_BYTES, stderrBytes + chunk.byteLength);
+ });
+ child.on('error', () => {
+ finish(new EvaluatorSubprocessError('WORKER_FAILED', 'Evaluator worker failed to start.'));
+ });
+ child.on('close', (exitCode) => {
+ if (settled) return;
+ if (exitCode !== 0 || chunks.length === 0) {
+ finish(new EvaluatorSubprocessError('WORKER_FAILED', 'Evaluator worker failed.'));
+ return;
+ }
+ try {
+ const result = decodeEvaluatorResultV1(Buffer.concat(chunks).toString('utf8'), maxGlbBytes);
+ if (!result.ok) {
+ if (result.error.code === 'QA_BLOCKED' && result.error.qa) {
+ finish(
+ new AssetQaBlockedError(
+ result.error.qa.report,
+ result.error.qa.stage,
+ result.error.qa.gltfValidation,
+ ),
+ );
+ return;
+ }
+ finish(
+ new EvaluatorSubprocessError(
+ result.error.code,
+ evaluatorOutcomeMessage(result.error.code),
+ ),
+ );
+ return;
+ }
+ finish(undefined, result.render);
+ } catch {
+ finish(new EvaluatorSubprocessError('PROTOCOL_ERROR', 'Evaluator returned invalid data.'));
+ }
+ });
+ child.stdin?.end(requestJson);
+ });
+}
+
+export async function renderGLBViaSubprocess(
+ code: string,
+ options: RenderGlbOptions = {},
+ controls: EvaluatorSubprocessControls = {},
+): Promise<RenderResult> {
+ return renderGLBViaProcessLaunch(code, options, controls);
+}
diff --git a/src/evaluator/transport-worker.mjs b/src/evaluator/transport-worker.mjs
new file mode 100644
index 00000000..956831b1
--- /dev/null
+++ b/src/evaluator/transport-worker.mjs
@@ -0,0 +1,8 @@
+import { writeFileSync } from 'node:fs';
+
+process.stdout.write('kiln-evaluator-transport-boot-v1\n');
+writeFileSync(
+ 3,
+ JSON.stringify({ version: 'kiln.evaluator.isolation-transport.v1', transport: 'fd3' }),
+ { encoding: 'utf8' },
+);
diff --git a/src/evaluator/worker.ts b/src/evaluator/worker.ts
new file mode 100644
index 00000000..6538a296
--- /dev/null
+++ b/src/evaluator/worker.ts
@@ -0,0 +1,79 @@
+import { writeFileSync } from 'node:fs';
+import { AssetQaBlockedError } from '../qa/run';
+import { renderGLBInProcess } from '../render';
+import {
+ decodeEvaluatorRequestV1,
+ encodeRenderResultV1,
+ evaluatorOutcomeMessage,
+ EVALUATOR_RESULT_VERSION,
+ MAX_EVALUATOR_REQUEST_BYTES,
+ type EvaluatorOutcomeCode,
+ type WireEvaluatorResultV1,
+} from './protocol';
+
+async function readBoundedInput(): Promise<string> {
+ const chunks: Buffer[] = [];
+ let bytes = 0;
+ for await (const chunk of process.stdin) {
+ const buffer = Buffer.from(chunk);
+ bytes += buffer.byteLength;
+ if (bytes > MAX_EVALUATOR_REQUEST_BYTES) throw new Error('request limit');
+ chunks.push(buffer);
+ }
+ return Buffer.concat(chunks).toString('utf8');
+}
+
+function sanitizedFailure(requestId: string, error: unknown): WireEvaluatorResultV1 {
+ if (error instanceof AssetQaBlockedError) {
+ return {
+ version: EVALUATOR_RESULT_VERSION,
+ requestId,
+ ok: false,
+ error: {
+ code: 'QA_BLOCKED',
+ message: evaluatorOutcomeMessage('QA_BLOCKED'),
+ qa: {
+ report: error.report,
+ stage: error.stage,
+ ...(error.gltfValidation ? { gltfValidation: error.gltfValidation } : {}),
+ },
+ },
+ };
+ }
+ const code: EvaluatorOutcomeCode =
+ error instanceof Error && error.message.includes('exceeds its configured output limit')
+ ? 'OUTPUT_LIMIT_EXCEEDED'
+ : 'EXECUTION_REJECTED';
+ return {
+ version: EVALUATOR_RESULT_VERSION,
+ requestId,
+ ok: false,
+ error: {
+ code,
+ message: evaluatorOutcomeMessage(code),
+ },
+ };
+}
+
+let output: WireEvaluatorResultV1;
+try {
+ const request = decodeEvaluatorRequestV1(await readBoundedInput());
+ try {
+ const render = await renderGLBInProcess(request.code, request.options);
+ if (render.glb.byteLength > request.limits.maxGlbBytes) {
+ throw new Error('GLB exceeds its configured output limit');
+ }
+ output = encodeRenderResultV1(request.requestId, render);
+ } catch (error) {
+ output = sanitizedFailure(request.requestId, error);
+ }
+} catch {
+ output = {
+ version: EVALUATOR_RESULT_VERSION,
+ requestId: 'invalid',
+ ok: false,
+ error: { code: 'INPUT_INVALID', message: evaluatorOutcomeMessage('INPUT_INVALID') },
+ };
+}
+
+writeFileSync(3, JSON.stringify(output), { encoding: 'utf8' });
diff --git a/src/list-primitives.ts b/src/list-primitives.ts
index c045dd8b..23152c95 100644
--- a/src/list-primitives.ts
+++ b/src/list-primitives.ts
@@ -460,7 +460,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
description:
'Single-quad foliage card with a configurable Y pivot. yPivot=0 plants the quad on the ground. Pair with an alpha-tested material and a leaf/plant sprite.',
example:
- "const leaves = await loadTexture('./fern.png', { usage: 'albedo' });\nconst quad = foliageCardGeo({ width: 4, height: 6, yPivot: 0 });\ncreatePart('Mesh_Fern', quad, foliageMaterial(leaves), { parent: root });",
+ "const leaves = await materialRecipe('kiln.material.leaf.v1');\nconst quad = foliageCardGeo({ width: 4, height: 6, yPivot: 0 });\ncreatePart('Mesh_Fern', quad, leaves, { parent: root });",
},
{
name: 'crossedQuadsGeo',
@@ -470,7 +470,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
description:
'Cross-billboard bush primitive: 2 or 3 planes intersecting along the Y axis. Reads as a dense plant from any angle, cheaper than real geometry.',
example:
- "const leaves = await loadTexture('./bush.png', { usage: 'albedo' });\nconst bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });\ncreatePart('Mesh_Bush', bush, foliageMaterial(leaves), { parent: root });",
+ "const leaves = await materialRecipe('kiln.material.leaf.v1');\nconst bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });\ncreatePart('Mesh_Bush', bush, leaves, { parent: root });",
},
{
name: 'octaGridPlane',
@@ -539,6 +539,19 @@ const PRIMITIVES: PrimitiveSpec[] = [
promptNotes:
'Use only listed kiln.material.*.v1 IDs and approved kiln.texture.* resource IDs. Leaf is MASK, glass is BLEND, and host file paths are forbidden.',
},
+ {
+ name: 'compilePortableMaterialSpecV2',
+ signature:
+ "await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', name?, baseColor?, roughness?, metalness?, emissive?, emissiveIntensity?, alphaMode?, alphaCutoff?, doubleSided?, textures?: { baseColor?, normal?, metallicRoughness?, emissive?, occlusion? } })",
+ returns: 'Promise<THREE.MeshStandardMaterial>',
+ category: 'material',
+ description:
+ 'Compiles the strict portable material contract. Texture refs are either typed procedural V2 specs or closed approved kiln.texture.* IDs; paths, URLs, raw textures, callbacks, and shader source are rejected.',
+ example:
+ "const steel = await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', roughness: 0.45, metalness: 0.85, textures: { metallicRoughness: { kind: 'procedural', spec: { schemaVersion: 2, usage: 'metallicRoughness', size: 64, layers: [{ op: 'solid', color: 0x0080cc }] } } } });",
+ promptNotes:
+ 'Use metallicRoughness as one packed G=roughness/B=metalness map. Every procedural ref usage must match its slot; resource refs must be approved for that exact slot.',
+ },
{
name: 'basicMaterial',
signature: 'basicMaterial(color, opts?: { transparent, opacity })',
@@ -934,29 +947,28 @@ const PRIMITIVES: PrimitiveSpec[] = [
// Textures + PBR (Wave 3B)
// ---------------------------------------------------------------------------
{
- name: 'loadTexture',
- signature:
- "await loadTexture(source, { usage?: 'albedo'|'emissive'|'normal'|'roughness'|'metalness'|'metallicRoughness'|'occlusion', name? })",
+ name: 'loadApprovedTexture',
+ signature: 'await loadApprovedTexture(resourceId)',
returns: 'Promise<THREE.DataTexture>',
category: 'textures',
description:
- 'Loads a PNG/JPG/WebP image with explicit slot usage. Albedo/emissive preview as sRGB; normal/roughness/metalness/occlusion are linear data. Stashes encoded bytes and QA metadata for lossless GLB export.',
- example: "const wood = await loadTexture('./textures/oak-albedo.png', { usage: 'albedo' });",
+ 'Loads one approved kiln.texture.* resource ID through the host-injected closed resolver. The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte arrays, resolver objects, hashes, and options are rejected.',
+ example: "const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');",
promptNotes:
- 'NEVER texture.clone() a loaded texture (clone() corrupts the encoded bytes and breaks GLB export). Share the same Texture object and remap UVs with panelRemapV on the smaller mesh instead.',
+ 'Use only a concrete resource ID listed in material capabilities; never invent one. Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes and breaks GLB export).',
},
{
name: 'proceduralTexture',
signature:
- "proceduralTexture({ size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })",
+ "proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })",
returns: 'THREE.DataTexture (tiling, sRGB or linear per usage)',
category: 'textures',
description:
'Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.',
example:
- "const bark = proceduralTexture({ size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",
+ "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",
promptNotes:
- 'Sync — no await. Prefer this over loadTexture for any surface you can describe (wood, rust, brick, fabric, dirt): it needs no asset files and cannot fail at load. Max 8 layers, size must be a power of two up to 1024. Only the six listed ops exist; there is no custom per-pixel callback.',
+ 'Sync — no await. Strict V2 JSON boundary: unknown/prototype keys, callbacks, paths, URLs, and shader source are rejected. Prefer this over approved resources for describable surfaces. Max 8 layers, power-of-two size up to 1024. Only the six listed ops exist.',
},
{
name: 'normalMapFromHeight',
@@ -966,7 +978,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
description:
"Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",
example:
- "const bark = proceduralTexture({ usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });\nconst mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });",
+ "const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });\nconst mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });",
promptNotes:
'strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot.',
},
@@ -979,7 +991,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
description:
'Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. Supports OPAQUE/MASK/BLEND and double-sided output.',
example:
- "const wood = await loadTexture('./oak.png');\nconst crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });",
+ "const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });\nconst crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });",
},
{
name: 'foliageMaterial',
@@ -988,8 +1000,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
category: 'material',
description:
'Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.',
- example:
- "const leaves = await loadTexture('./leaf.png', { usage: 'albedo' });\nconst mat = foliageMaterial(leaves, { alphaCutoff: 0.45 });",
+ example: "const mat = await materialRecipe('kiln.material.leaf.v1');",
},
// ---------------------------------------------------------------------------
diff --git a/src/material-recipe-prompt.ts b/src/material-recipe-prompt.ts
index d6174991..ab7046e6 100644
--- a/src/material-recipe-prompt.ts
+++ b/src/material-recipe-prompt.ts
@@ -48,13 +48,13 @@ const glow = await materialRecipe('kiln.material.emissive.v1');
function textureSlotContext(catalog: readonly MaterialPromptTextureEntry[]): string {
if (catalog.length === 0) {
return `Texture slots take approved kiln.texture.* resource IDs, and none are available in this
-environment: leave textureResources unset and build any surface detail with proceduralTexture().`;
+environment: leave textureResources unset and build any surface detail with proceduralTexture({ schemaVersion: 2, ... }).`;
}
const lines = catalog.map(
(entry) => `- ${entry.id} (${entry.usage}) for slots: ${entry.allowedSlots.join(', ')}`,
);
return `Texture slots accept only these approved resource IDs; do not invent one and do not pass a
-host path. For any surface not covered here, build it with proceduralTexture() rather than
+host path. For any surface not covered here, build it with proceduralTexture({ schemaVersion: 2, ... }) rather than
substituting an unrelated ID:
${lines.join('\n')}`;
}
@@ -68,6 +68,9 @@ Use ${MATERIAL_RECIPE_HELPER_SIGNATURE}. Recipe IDs are versioned and executable
ID or pass a host path. Available IDs: ${MATERIAL_RECIPE_IDS.join(', ')}. Recipes export through core
glTF pbrMetallicRoughness. Leaf uses MASK (not BLEND); glass is the explicit blended recipe.
+For authored maps, use proceduralTexture({ schemaVersion: 2, ... }). It is a strict finite DSL:
+callbacks, shader source, URLs, filesystem paths, prototype keys, and unknown fields are rejected.
+
${textureSlotContext(catalog)}
Choose recipes from the requested real-world material even when the user does not name this helper:
diff --git a/src/material-resources.ts b/src/material-resources.ts
index c46cfa12..bd6085cd 100644
--- a/src/material-resources.ts
+++ b/src/material-resources.ts
@@ -44,12 +44,36 @@ export interface MaterialResourceProvenanceV1 {
* length and hash before anything decodes them, so a resolver that is wrong,
* stale, or compromised fails loudly instead of substituting pixels.
*/
-export type ApprovedTextureResolver = (
+export const TEXTURE_RESOLVER_LIMITS_V1 = Object.freeze({
+ maxEncodedBytes: 8 * 1024 * 1024,
+ maxWidth: 4096,
+ maxHeight: 4096,
+ maxPixels: 8 * 1024 * 1024,
+ defaultDeadlineMs: 5_000,
+ maxDeadlineMs: 30_000,
+});
+
+export interface HostTextureBytesV1 {
+ bytes: Uint8Array;
+ mime: 'image/png';
+}
+
+export interface TrustedTextureResolverContextV1 {
+ /** Host may cancel its own I/O early; the engine enforces the deadline even
+ * when the host ignores this signal. */
+ signal: AbortSignal;
+ deadlineMs: number;
+}
+
+export type TrustedTextureByteResolver = (
descriptor: ApprovedTextureResourceDescriptorV1,
-) => Promise<Uint8Array>;
+ context: TrustedTextureResolverContextV1,
+) => Promise<HostTextureBytesV1>;
export interface ApprovedTextureResourceCacheOptions {
- resolver?: ApprovedTextureResolver;
+ resolver?: TrustedTextureByteResolver;
+ /** Host-owned and bounded. Generated code cannot set or observe this value. */
+ resolverDeadlineMs?: number;
/**
* Descriptor table this cache reads. Defaults to the shipped registry.
*
@@ -135,16 +159,86 @@ function provenance(
* fail here with a number a human can act on, rather than as an opaque hash
* mismatch that reads like corruption.
*/
-function verifyResourceBytes(
+function readPngDimensions(
descriptor: ApprovedTextureResourceDescriptorV1,
bytes: Uint8Array,
+): { width: number; height: number } {
+ const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
+ if (
+ bytes.byteLength < 24 ||
+ !signature.every((value, index) => bytes[index] === value) ||
+ String.fromCharCode(...bytes.subarray(12, 16)) !== 'IHDR'
+ ) {
+ throw new ApprovedTextureResourceUnavailableError(
+ descriptor.id,
+ 'declared image/png bytes do not have a valid PNG signature and IHDR format',
+ );
+ }
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ return { width: view.getUint32(16, false), height: view.getUint32(20, false) };
+}
+
+function verifyResourcePayload(
+ descriptor: ApprovedTextureResourceDescriptorV1,
+ payload: HostTextureBytesV1,
): string {
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
+ throw new ApprovedTextureResourceUnavailableError(
+ descriptor.id,
+ 'host payload must be { bytes, mime }',
+ );
+ }
+ const keys = Object.keys(payload).sort();
+ if (keys.length !== 2 || keys[0] !== 'bytes' || keys[1] !== 'mime') {
+ throw new ApprovedTextureResourceUnavailableError(
+ descriptor.id,
+ 'host payload must contain only bytes and MIME',
+ );
+ }
+ if (!(payload.bytes instanceof Uint8Array)) {
+ throw new ApprovedTextureResourceUnavailableError(
+ descriptor.id,
+ 'host bytes must be Uint8Array',
+ );
+ }
+ if (payload.mime !== descriptor.mime) {
+ throw new ApprovedTextureResourceUnavailableError(
+ descriptor.id,
+ `host MIME ${String(payload.mime)} does not match approved ${descriptor.mime}`,
+ );
+ }
+ const bytes = payload.bytes;
+ if (bytes.byteLength > TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes) {
+ throw new ApprovedTextureResourceUnavailableError(
+ descriptor.id,
+ `encoded-byte limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes}; received ${bytes.byteLength}`,
+ );
+ }
if (bytes.byteLength !== descriptor.byteLength) {
throw new ApprovedTextureResourceUnavailableError(
descriptor.id,
`expected ${descriptor.byteLength} bytes, received ${bytes.byteLength}`,
);
}
+ const { width, height } = readPngDimensions(descriptor, bytes);
+ if (
+ width < 1 ||
+ height < 1 ||
+ width > TEXTURE_RESOLVER_LIMITS_V1.maxWidth ||
+ height > TEXTURE_RESOLVER_LIMITS_V1.maxHeight
+ ) {
+ throw new ApprovedTextureResourceUnavailableError(
+ descriptor.id,
+ `dimension limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxWidth}x${TEXTURE_RESOLVER_LIMITS_V1.maxHeight}; received ${width}x${height}`,
+ );
+ }
+ const pixels = width * height;
+ if (!Number.isSafeInteger(pixels) || pixels > TEXTURE_RESOLVER_LIMITS_V1.maxPixels) {
+ throw new ApprovedTextureResourceUnavailableError(
+ descriptor.id,
+ `pixel limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxPixels}; received ${pixels}`,
+ );
+ }
const hash = sha256(bytes);
if (hash !== descriptor.contentHash) {
throw new ApprovedTextureResourceUnavailableError(
@@ -171,18 +265,32 @@ export class ApprovedTextureResourceCache {
readonly #registry: Readonly<
Record<ApprovedTextureResourceId, ApprovedTextureResourceDescriptorV1>
>;
- #resolver: ApprovedTextureResolver | undefined;
+ #resolver: TrustedTextureByteResolver | undefined;
+ readonly #resolverDeadlineMs: number;
constructor(options: ApprovedTextureResourceCacheOptions = {}) {
this.#resolver = options.resolver;
this.#registry = options.registry ?? APPROVED_TEXTURE_RESOURCES_V1;
+ const deadline = options.resolverDeadlineMs ?? TEXTURE_RESOLVER_LIMITS_V1.defaultDeadlineMs;
+ if (
+ !Number.isFinite(deadline) ||
+ deadline < 1 ||
+ deadline > TEXTURE_RESOLVER_LIMITS_V1.maxDeadlineMs
+ ) {
+ throw new RangeError(
+ `resolverDeadlineMs must be in [1,${TEXTURE_RESOLVER_LIMITS_V1.maxDeadlineMs}]`,
+ );
+ }
+ this.#resolverDeadlineMs = deadline;
}
/**
* Registered once by the host process at startup, never by generated code.
* Returns the previous resolver so a test can restore it.
*/
- setResolver(resolver: ApprovedTextureResolver | undefined): ApprovedTextureResolver | undefined {
+ setResolver(
+ resolver: TrustedTextureByteResolver | undefined,
+ ): TrustedTextureByteResolver | undefined {
const previous = this.#resolver;
this.#resolver = resolver;
return previous;
@@ -244,7 +352,11 @@ export class ApprovedTextureResourceCache {
);
}
const decoded = bytesFromBase64(EMBEDDED_RESOURCE_BASE64[id]);
- this.#cacheBytes(id, verifyResourceBytes(descriptor, decoded), decoded);
+ this.#cacheBytes(
+ id,
+ verifyResourcePayload(descriptor, { bytes: decoded, mime: descriptor.mime }),
+ decoded,
+ );
return this.#resolution(id, this.#hashById.get(id)!);
}
@@ -270,8 +382,37 @@ export class ApprovedTextureResourceCache {
'no runtime texture resolver is registered in this environment',
);
}
- const bytes = await resolver(descriptor);
- this.#cacheBytes(id, verifyResourceBytes(descriptor, bytes), bytes);
+ const controller = new AbortController();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(() => {
+ controller.abort();
+ reject(
+ new ApprovedTextureResourceUnavailableError(
+ id,
+ `host resolver deadline exceeded after ${this.#resolverDeadlineMs}ms`,
+ ),
+ );
+ }, this.#resolverDeadlineMs);
+ });
+ let payload: HostTextureBytesV1;
+ try {
+ payload = await Promise.race([
+ Promise.resolve().then(() =>
+ resolver(
+ descriptor,
+ Object.freeze({
+ signal: controller.signal,
+ deadlineMs: this.#resolverDeadlineMs,
+ }),
+ ),
+ ),
+ timeout,
+ ]);
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+ this.#cacheBytes(id, verifyResourcePayload(descriptor, payload), payload.bytes);
return this.#resolution(id, this.#hashById.get(id)!);
})().finally(() => {
// Dropped either way: a success is served from #hashById afterwards, and
@@ -337,13 +478,16 @@ export async function loadApprovedTextureResource(
return DEFAULT_APPROVED_TEXTURE_CACHE.load(id);
}
-/** Registers the host's byte source for runtime-delivered resources. */
-export function setApprovedTextureResolver(
- resolver: ApprovedTextureResolver | undefined,
-): ApprovedTextureResolver | undefined {
+/** Registers the trusted host's bounded byte source for runtime resources. */
+export function setTrustedTextureByteResolver(
+ resolver: TrustedTextureByteResolver | undefined,
+): TrustedTextureByteResolver | undefined {
return DEFAULT_APPROVED_TEXTURE_CACHE.setResolver(resolver);
}
+/** @deprecated Use setTrustedTextureByteResolver; never expose this setter to generated code. */
+export const setApprovedTextureResolver = setTrustedTextureByteResolver;
+
export interface ApprovedTextureCatalogEntryV1 {
id: ApprovedTextureResourceId;
label: string;
diff --git a/src/portable-material-runtime.ts b/src/portable-material-runtime.ts
new file mode 100644
index 00000000..89aeea5b
--- /dev/null
+++ b/src/portable-material-runtime.ts
@@ -0,0 +1,116 @@
+/** Compile the strict portable material contract into bounded Three.js state. */
+
+import type * as THREE from 'three';
+
+import {
+ APPROVED_TEXTURE_RESOURCE_IDS,
+ type ApprovedTextureResourceId,
+ type MaterialTextureSlot,
+} from './material-recipes';
+import { DEFAULT_APPROVED_TEXTURE_CACHE } from './material-resources';
+import {
+ type CanonicalPortableMaterialSpecV2,
+ type CanonicalPortableTextureRefV2,
+ ProceduralTextureError,
+ canonicalizePortableMaterialSpecV2,
+} from './procedural-material-v2';
+import { proceduralTexture } from './procedural-texture';
+import { pbrMaterial, type PbrMaterialOptions, type TextureUsage } from './textures';
+
+const SLOT_USAGE = {
+ baseColor: 'albedo',
+ normal: 'normal',
+ metallicRoughness: 'metallicRoughness',
+ emissive: 'emissive',
+ occlusion: 'occlusion',
+} as const satisfies Record<MaterialTextureSlot, TextureUsage>;
+
+type PortableSlot = keyof typeof SLOT_USAGE;
+
+const isApprovedResourceId = (value: string): value is ApprovedTextureResourceId =>
+ (APPROVED_TEXTURE_RESOURCE_IDS as readonly string[]).includes(value);
+
+/**
+ * Compile a JSON-shaped V2 material without exposing loaders, paths, URLs,
+ * DataTextures, shader source, or a host resolver to authored code.
+ *
+ * The whole contract and every resource/slot binding are validated before the
+ * first texture is compiled or loaded. A late invalid slot therefore cannot
+ * cause partial allocations or host resource calls.
+ */
+export async function compilePortableMaterialSpecV2(
+ input: unknown,
+): Promise<THREE.MeshStandardMaterial> {
+ const spec = canonicalizePortableMaterialSpecV2(input);
+ // Deliberately not injectable at this boundary. The host can register a
+ // resolver on the default closed-ID cache, but authored code cannot replace
+ // the cache with an object that returns arbitrary textures.
+ const cache = DEFAULT_APPROVED_TEXTURE_CACHE;
+ const entries = Object.entries(spec.textures) as Array<
+ [PortableSlot, CanonicalPortableTextureRefV2]
+ >;
+
+ for (const [slot, ref] of entries) {
+ if (ref.kind !== 'resource') continue;
+ if (!isApprovedResourceId(ref.resourceId)) {
+ throw new ProceduralTextureError(
+ `portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not an approved texture resource ID.`,
+ );
+ }
+ const descriptor = cache.descriptor(ref.resourceId);
+ if (!(descriptor.allowedSlots as readonly string[]).includes(slot)) {
+ throw new ProceduralTextureError(
+ `portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not approved for that slot.`,
+ );
+ }
+ if (descriptor.usage !== SLOT_USAGE[slot]) {
+ throw new ProceduralTextureError(
+ `portableMaterial.textures.${slot} requires ${SLOT_USAGE[slot]} data, but ${JSON.stringify(ref.resourceId)} provides ${descriptor.usage}.`,
+ );
+ }
+ }
+
+ const loaded = new Map<PortableSlot, THREE.Texture>();
+ await Promise.all(
+ entries.map(async ([slot, ref]) => {
+ const texture =
+ ref.kind === 'procedural'
+ ? proceduralTexture(ref.spec)
+ : (await cache.load(ref.resourceId as ApprovedTextureResourceId)).texture;
+ loaded.set(slot, texture);
+ }),
+ );
+
+ const materialOptions: PbrMaterialOptions = {
+ roughness: spec.roughness,
+ metalness: spec.metalness,
+ emissiveIntensity: spec.emissiveIntensity,
+ alphaMode: spec.alphaMode,
+ ...(spec.alphaMode === 'mask' ? { alphaCutoff: spec.alphaCutoff } : {}),
+ doubleSided: spec.doubleSided,
+ ...(loaded.get('baseColor')
+ ? { albedo: loaded.get('baseColor') }
+ : spec.baseColor !== undefined
+ ? { albedo: spec.baseColor }
+ : {}),
+ ...(loaded.get('normal') ? { normal: loaded.get('normal') } : {}),
+ ...(loaded.get('metallicRoughness')
+ ? { metallicRoughness: loaded.get('metallicRoughness') }
+ : {}),
+ ...(loaded.get('emissive')
+ ? { emissive: loaded.get('emissive') }
+ : spec.emissive !== undefined
+ ? { emissive: spec.emissive }
+ : {}),
+ ...(loaded.get('occlusion') ? { aoMap: loaded.get('occlusion') } : {}),
+ };
+ const material = pbrMaterial(materialOptions);
+ if (spec.name) material.name = spec.name;
+ if (loaded.has('baseColor') && spec.baseColor !== undefined)
+ material.color.setHex(spec.baseColor);
+ if (loaded.has('emissive') && spec.emissive !== undefined)
+ material.emissive.setHex(spec.emissive);
+ (material.userData as Record<string, unknown>)['kilnPortableMaterial'] =
+ spec satisfies CanonicalPortableMaterialSpecV2;
+ return material;
+}
diff --git a/src/primitives.ts b/src/primitives.ts
index 76dabcc5..46fa6a15 100644
--- a/src/primitives.ts
+++ b/src/primitives.ts
@@ -24,7 +24,8 @@ import * as profile from './profile';
import * as solids from './solids';
import * as proceduralTextures from './procedural-texture';
import * as textures from './textures';
-import { materialRecipe } from './material-recipe-runtime';
+import type { TextureResolver } from './texture-resolver';
+import { compilePortableMaterialSpecV2 } from './portable-material-runtime';
import { createVehicleFrame, createWheelAssembly, createWheelGeometrySet } from './vehicle';
import {
stampSemanticMetadataV1,
@@ -62,6 +63,31 @@ export {
export { materialRecipe } from './material-recipe-runtime';
export type { ApplyMaterialRecipeOptions } from './material-recipe-runtime';
export type { MaterialRecipeId, MaterialRecipeOverridesV1 } from './material-recipes';
+export { compilePortableMaterialSpecV2 } from './portable-material-runtime';
+export {
+ MAX_PORTABLE_MATERIAL_TEXELS,
+ MAX_PORTABLE_MATERIAL_TEXTURES,
+ MAX_PROCEDURAL_LAYERS,
+ MAX_PROCEDURAL_SIZE,
+ PORTABLE_MATERIAL_SPEC_VERSION,
+ PROCEDURAL_TEXTURE_SPEC_VERSION,
+ ProceduralTextureError,
+ canonicalProceduralTextureJsonV2,
+ canonicalizePortableMaterialSpecV2,
+ canonicalizeProceduralTextureSpecV2,
+ compileProceduralTextureSpecV2,
+ hashProceduralTextureSpecV2,
+ migrateProceduralTextureSpecV1,
+} from './procedural-texture';
+export type {
+ CanonicalPortableMaterialSpecV2,
+ CanonicalProceduralTextureSpecV2,
+ PortableMaterialSpecV2,
+ ProceduralLayer,
+ ProceduralTextureSpec,
+ ProceduralTextureSpecV1,
+ ProceduralTextureSpecV2,
+} from './procedural-texture';
export type {
VehicleFrameOptions,
VehicleFrameResult,
@@ -1503,7 +1529,16 @@ export function validateAsset(
* so render.ts can stash it into `render.meta.primitiveUsage` for
* downstream analysis. When omitted, wrapping is skipped (zero overhead).
*/
-export function buildSandboxGlobals(usage?: Record<string, number>): Record<string, unknown> {
+export interface SandboxGlobalsOptions {
+ /** Host-owned closed resolver. Generated code receives only the bound
+ * loadApprovedTexture(resourceId) closure, never this object. */
+ textureResolver?: TextureResolver;
+}
+
+export function buildSandboxGlobals(
+ usage?: Record<string, number>,
+ options: SandboxGlobalsOptions = {},
+): Record<string, unknown> {
// CSG ops remain lazy at their own call sites, so importing the wrapper here
// is safe for Node ESM builds and still avoids manifold WASM init unless used.
@@ -1584,6 +1619,32 @@ export function buildSandboxGlobals(usage?: Record<string, number>): Record<stri
const wrapGeo = <F extends (...args: any[]) => THREE.BufferGeometry>(name: string, fn: F): F =>
wrap(name, cacheGeo(name, fn));
+ const loadApprovedTexture = (...args: unknown[]): Promise<THREE.DataTexture> => {
+ if (args.length !== 1 || typeof args[0] !== 'string') {
+ return Promise.reject(
+ new TypeError('loadApprovedTexture accepts exactly one approved resource ID string'),
+ );
+ }
+ if (!options.textureResolver) {
+ return Promise.reject(new Error('loadApprovedTexture: no host TextureResolver is installed'));
+ }
+ return options.textureResolver.loadApprovedTexture(args[0]);
+ };
+
+ const sandboxMaterialRecipe = (...args: unknown[]): Promise<THREE.MeshStandardMaterial> => {
+ if (args.length < 1 || args.length > 2 || typeof args[0] !== 'string') {
+ return Promise.reject(
+ new TypeError(
+ 'materialRecipe accepts an approved recipe ID and optional bounded overrides',
+ ),
+ );
+ }
+ if (!options.textureResolver) {
+ return Promise.reject(new Error('materialRecipe: no host TextureResolver is installed'));
+ }
+ return options.textureResolver.materialRecipe(args[0], args[1]);
+ };
+
return {
createRoot: wrap('createRoot', createRoot),
createPivot: wrap('createPivot', createPivot),
@@ -1628,7 +1689,11 @@ export function buildSandboxGlobals(usage?: Record<string, number>): Record<stri
createRoofSurfaceLayout: wrap('createRoofSurfaceLayout', createRoofSurfaceLayout),
createStairs: wrap('createStairs', createStairs),
gameMaterial: wrap('gameMaterial', gameMaterial),
- materialRecipe: wrap('materialRecipe', materialRecipe),
+ materialRecipe: wrap('materialRecipe', sandboxMaterialRecipe),
+ compilePortableMaterialSpecV2: wrap(
+ 'compilePortableMaterialSpecV2',
+ compilePortableMaterialSpecV2,
+ ),
basicMaterial: wrap('basicMaterial', basicMaterial),
glassMaterial: wrap('glassMaterial', glassMaterial),
lambertMaterial: wrap('lambertMaterial', lambertMaterial),
@@ -1675,8 +1740,9 @@ export function buildSandboxGlobals(usage?: Record<string, number>): Record<stri
// Parametric primitives
gearGeo: wrapGeo('gearGeo', gears.gearGeo),
bladeGeo: wrapGeo('bladeGeo', gears.bladeGeo),
- // Textures + PBR (loadTexture is async)
- loadTexture: wrap('loadTexture', textures.loadTexture),
+ // Closed approved textures. Paths, URLs, bytes, hashes, and resolver
+ // objects are intentionally not accepted by this one-argument closure.
+ loadApprovedTexture: wrap('loadApprovedTexture', loadApprovedTexture),
// Procedural textures (sync — no I/O, so no await)
proceduralTexture: wrap('proceduralTexture', proceduralTextures.proceduralTexture),
normalMapFromHeight: wrap('normalMapFromHeight', proceduralTextures.normalMapFromHeight),
diff --git a/src/procedural-material-v2.ts b/src/procedural-material-v2.ts
new file mode 100644
index 00000000..dabd0966
--- /dev/null
+++ b/src/procedural-material-v2.ts
@@ -0,0 +1,680 @@
+/**
+ * Strict, browser-safe contracts for model-authored portable materials.
+ *
+ * These functions accept `unknown` on purpose. Generated programs are an
+ * untrusted JSON-shaped boundary even when TypeScript declarations say the
+ * input is well formed. Canonicalization rejects executable references,
+ * inherited state, unknown fields, and work outside the fixed budgets before
+ * the pixel compiler allocates an output buffer.
+ */
+
+import { TEXTURE_USAGES, type TextureUsage } from './textures';
+
+export const PROCEDURAL_TEXTURE_SPEC_VERSION = 2 as const;
+export const PORTABLE_MATERIAL_SPEC_VERSION = 2 as const;
+
+export const MAX_PROCEDURAL_SIZE = 1024;
+export const MIN_PROCEDURAL_SIZE = 4;
+export const MAX_PROCEDURAL_LAYERS = 8;
+export const MAX_NOISE_OCTAVES = 6;
+export const MAX_PROCEDURAL_NAME_LENGTH = 80;
+export const MAX_PROCEDURAL_PATTERN_COUNT = 256;
+export const MAX_PORTABLE_MATERIAL_TEXTURES = 5;
+/** Four 1024-square maps, or a larger number of smaller maps. */
+export const MAX_PORTABLE_MATERIAL_TEXELS = 4 * 1024 * 1024;
+
+export type ProceduralBlend = 'normal' | 'multiply' | 'screen' | 'overlay';
+
+interface LayerCommon {
+ blend?: ProceduralBlend;
+ opacity?: number;
+}
+
+export type ProceduralLayer = LayerCommon &
+ (
+ | { op: 'solid'; color: number }
+ | { op: 'checker'; colorA: number; colorB: number; squares?: number }
+ | { op: 'stripes'; colorA: number; colorB: number; count?: number; angleDeg?: number }
+ | { op: 'gradient'; from: number; to: number; angleDeg?: number }
+ | {
+ op: 'bricks';
+ brick: number;
+ mortar: number;
+ rows?: number;
+ cols?: number;
+ mortarWidth?: number;
+ stagger?: number;
+ }
+ | {
+ op: 'noise';
+ colorA: number;
+ colorB: number;
+ scale?: number;
+ octaves?: number;
+ seed?: number;
+ }
+ );
+
+/** Historical source shape. Absence of schemaVersion means V1. */
+export interface ProceduralTextureSpecV1 {
+ schemaVersion?: 1;
+ size?: number;
+ usage?: TextureUsage;
+ name?: string;
+ layers: ProceduralLayer[];
+}
+
+/** Current source shape. Validation still happens at runtime. */
+export interface ProceduralTextureSpecV2 {
+ schemaVersion: 2;
+ size?: number;
+ usage?: TextureUsage;
+ name?: string;
+ layers: ProceduralLayer[];
+}
+
+/** Compatibility name retained for existing generated programs. */
+export type ProceduralTextureSpec = ProceduralTextureSpecV1 | ProceduralTextureSpecV2;
+
+interface CanonicalLayerCommon {
+ blend: ProceduralBlend;
+ opacity: number;
+}
+
+export type CanonicalProceduralLayerV2 = CanonicalLayerCommon &
+ (
+ | { op: 'solid'; color: number }
+ | { op: 'checker'; colorA: number; colorB: number; squares: number }
+ | { op: 'stripes'; colorA: number; colorB: number; count: number; angleDeg: number }
+ | { op: 'gradient'; from: number; to: number; angleDeg: number }
+ | {
+ op: 'bricks';
+ brick: number;
+ mortar: number;
+ rows: number;
+ cols: number;
+ mortarWidth: number;
+ stagger: number;
+ }
+ | {
+ op: 'noise';
+ colorA: number;
+ colorB: number;
+ scale: number;
+ octaves: number;
+ seed: number;
+ }
+ );
+
+export interface CanonicalProceduralTextureSpecV2 {
+ schemaVersion: 2;
+ size: number;
+ usage: TextureUsage;
+ name?: string;
+ layers: CanonicalProceduralLayerV2[];
+}
+
+export type PortableTextureRefV2 =
+ | { kind: 'procedural'; spec: ProceduralTextureSpecV2 }
+ | { kind: 'resource'; resourceId: string };
+
+export interface PortableMaterialSpecV2 {
+ schemaVersion: 2;
+ model: 'pbrMetallicRoughness';
+ name?: string;
+ baseColor?: number;
+ roughness?: number;
+ metalness?: number;
+ emissive?: number;
+ emissiveIntensity?: number;
+ alphaMode?: 'opaque' | 'mask' | 'blend';
+ alphaCutoff?: number;
+ doubleSided?: boolean;
+ textures?: {
+ baseColor?: PortableTextureRefV2;
+ normal?: PortableTextureRefV2;
+ metallicRoughness?: PortableTextureRefV2;
+ emissive?: PortableTextureRefV2;
+ occlusion?: PortableTextureRefV2;
+ };
+}
+
+export type CanonicalPortableTextureRefV2 =
+ | { kind: 'procedural'; spec: CanonicalProceduralTextureSpecV2 }
+ | { kind: 'resource'; resourceId: string };
+
+export interface CanonicalPortableMaterialSpecV2 {
+ schemaVersion: 2;
+ model: 'pbrMetallicRoughness';
+ name?: string;
+ baseColor?: number;
+ roughness: number;
+ metalness: number;
+ emissive?: number;
+ emissiveIntensity: number;
+ alphaMode: 'opaque' | 'mask' | 'blend';
+ alphaCutoff: number;
+ doubleSided: boolean;
+ textures: {
+ baseColor?: CanonicalPortableTextureRefV2;
+ normal?: CanonicalPortableTextureRefV2;
+ metallicRoughness?: CanonicalPortableTextureRefV2;
+ emissive?: CanonicalPortableTextureRefV2;
+ occlusion?: CanonicalPortableTextureRefV2;
+ };
+}
+
+export class ProceduralTextureError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'ProceduralTextureError';
+ }
+}
+
+const OPS = ['solid', 'checker', 'stripes', 'gradient', 'bricks', 'noise'] as const;
+const BLENDS: readonly ProceduralBlend[] = ['normal', 'multiply', 'screen', 'overlay'];
+const FORBIDDEN_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
+
+function strictRecord(value: unknown, path: string): Record<string, unknown> {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new ProceduralTextureError(`${path} must be a plain JSON object.`);
+ }
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null) {
+ throw new ProceduralTextureError(
+ `${path} must be a plain JSON object with no custom prototype.`,
+ );
+ }
+ for (const key of Reflect.ownKeys(value)) {
+ if (typeof key !== 'string') {
+ throw new ProceduralTextureError(`${path} must not contain symbol keys.`);
+ }
+ if (FORBIDDEN_KEYS.has(key)) {
+ throw new ProceduralTextureError(`${path} contains forbidden key ${JSON.stringify(key)}.`);
+ }
+ if (!Object.prototype.propertyIsEnumerable.call(value, key)) {
+ throw new ProceduralTextureError(`${path}.${key} must be an enumerable JSON field.`);
+ }
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
+ if (!descriptor || !('value' in descriptor)) {
+ throw new ProceduralTextureError(`${path}.${key} must be a plain JSON data field.`);
+ }
+ }
+ return value as Record<string, unknown>;
+}
+
+function strictArray(value: unknown, path: string): unknown[] {
+ if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) {
+ throw new ProceduralTextureError(`${path} must be a plain JSON array.`);
+ }
+ for (const key of Reflect.ownKeys(value)) {
+ if (typeof key !== 'string') {
+ throw new ProceduralTextureError(`${path} must not contain symbol keys.`);
+ }
+ if (key === 'length') continue;
+ if (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length) {
+ throw new ProceduralTextureError(
+ `${path} has non-index JSON array key ${JSON.stringify(key)}.`,
+ );
+ }
+ }
+ for (let index = 0; index < value.length; index++) {
+ if (!Object.hasOwn(value, index)) {
+ throw new ProceduralTextureError(
+ `${path} must be a dense JSON array (missing index ${index}).`,
+ );
+ }
+ }
+ return value;
+}
+
+function assertKeys(
+ record: Record<string, unknown>,
+ allowed: readonly string[],
+ path: string,
+): void {
+ const allow = new Set(allowed);
+ for (const key of Object.keys(record)) {
+ if (!allow.has(key)) {
+ throw new ProceduralTextureError(`${path} has unknown key ${JSON.stringify(key)}.`);
+ }
+ }
+}
+
+function color(value: unknown, path: string): number {
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > 0xffffff) {
+ throw new ProceduralTextureError(
+ `${path} must be a color integer between 0x000000 and 0xffffff, got ${JSON.stringify(value)}.`,
+ );
+ }
+ return value;
+}
+
+function integer(value: unknown, path: string, fallback: number, min: number, max: number): number {
+ if (value === undefined) return fallback;
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) {
+ throw new ProceduralTextureError(
+ `${path} must be a whole number between ${min} and ${max}, got ${JSON.stringify(value)}.`,
+ );
+ }
+ return value;
+}
+
+function finite(value: unknown, path: string, fallback: number, min: number, max: number): number {
+ if (value === undefined) return fallback;
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max) {
+ throw new ProceduralTextureError(
+ `${path} must be a finite number between ${min} and ${max}, got ${JSON.stringify(value)}.`,
+ );
+ }
+ return value;
+}
+
+function unit(value: unknown, path: string, fallback: number): number {
+ return finite(value, path, fallback, 0, 1);
+}
+
+function optionalName(value: unknown, path: string): string | undefined {
+ if (value === undefined) return undefined;
+ const hasControlCharacter =
+ typeof value === 'string' &&
+ [...value].some((character) => {
+ const code = character.charCodeAt(0);
+ return code < 0x20 || code === 0x7f;
+ });
+ if (
+ typeof value !== 'string' ||
+ value.length === 0 ||
+ value.length > MAX_PROCEDURAL_NAME_LENGTH ||
+ hasControlCharacter
+ ) {
+ throw new ProceduralTextureError(
+ `${path} must be 1..${MAX_PROCEDURAL_NAME_LENGTH} visible characters.`,
+ );
+ }
+ return value;
+}
+
+function usage(value: unknown, path: string, fallback: TextureUsage): TextureUsage {
+ if (value === undefined) return fallback;
+ if (!(TEXTURE_USAGES as readonly unknown[]).includes(value)) {
+ throw new ProceduralTextureError(
+ `${path} must be one of ${TEXTURE_USAGES.join(', ')}, got ${JSON.stringify(value)}.`,
+ );
+ }
+ return value as TextureUsage;
+}
+
+function angle(value: unknown, path: string): number {
+ const bounded = finite(value, path, 0, -36_000, 36_000);
+ const normalized = ((bounded % 360) + 360) % 360;
+ return Object.is(normalized, -0) ? 0 : normalized;
+}
+
+function blend(record: Record<string, unknown>, path: string): ProceduralBlend {
+ const value = record['blend'] ?? 'normal';
+ if (!BLENDS.includes(value as ProceduralBlend)) {
+ throw new ProceduralTextureError(
+ `${path}.blend ${JSON.stringify(value)} is not one of ${BLENDS.join(', ')}.`,
+ );
+ }
+ return value as ProceduralBlend;
+}
+
+function canonicalLayer(value: unknown, index: number): CanonicalProceduralLayerV2 {
+ const path = `proceduralTexture.layers[${index}]`;
+ const record = strictRecord(value, path);
+ const op = record['op'];
+ if (!(OPS as readonly unknown[]).includes(op)) {
+ throw new ProceduralTextureError(
+ `${path}.op ${JSON.stringify(op)} is not one of ${OPS.join(', ')}.`,
+ );
+ }
+ const validatedBlend = blend(record, path);
+ const validatedOpacity = unit(record['opacity'], `${path}.opacity`, 1);
+ // The base layer has nothing beneath it. Normalize its ignored compositing
+ // controls so semantically identical recipes cannot receive different hashes.
+ const common = {
+ blend: index === 0 ? ('normal' as const) : validatedBlend,
+ opacity: index === 0 ? 1 : validatedOpacity,
+ };
+ switch (op) {
+ case 'solid':
+ assertKeys(record, ['op', 'color', 'blend', 'opacity'], path);
+ return { op, color: color(record['color'], `${path}.color`), ...common };
+ case 'checker':
+ assertKeys(record, ['op', 'colorA', 'colorB', 'squares', 'blend', 'opacity'], path);
+ return {
+ op,
+ colorA: color(record['colorA'], `${path}.colorA`),
+ colorB: color(record['colorB'], `${path}.colorB`),
+ squares: integer(record['squares'], `${path}.squares`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),
+ ...common,
+ };
+ case 'stripes':
+ assertKeys(record, ['op', 'colorA', 'colorB', 'count', 'angleDeg', 'blend', 'opacity'], path);
+ return {
+ op,
+ colorA: color(record['colorA'], `${path}.colorA`),
+ colorB: color(record['colorB'], `${path}.colorB`),
+ count: integer(record['count'], `${path}.count`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),
+ angleDeg: angle(record['angleDeg'], `${path}.angleDeg`),
+ ...common,
+ };
+ case 'gradient':
+ assertKeys(record, ['op', 'from', 'to', 'angleDeg', 'blend', 'opacity'], path);
+ return {
+ op,
+ from: color(record['from'], `${path}.from`),
+ to: color(record['to'], `${path}.to`),
+ angleDeg: angle(record['angleDeg'], `${path}.angleDeg`),
+ ...common,
+ };
+ case 'bricks':
+ assertKeys(
+ record,
+ ['op', 'brick', 'mortar', 'rows', 'cols', 'mortarWidth', 'stagger', 'blend', 'opacity'],
+ path,
+ );
+ return {
+ op,
+ brick: color(record['brick'], `${path}.brick`),
+ mortar: color(record['mortar'], `${path}.mortar`),
+ rows: integer(record['rows'], `${path}.rows`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),
+ cols: integer(record['cols'], `${path}.cols`, 4, 1, MAX_PROCEDURAL_PATTERN_COUNT),
+ mortarWidth: unit(record['mortarWidth'], `${path}.mortarWidth`, 0.06),
+ stagger: unit(record['stagger'], `${path}.stagger`, 0.5),
+ ...common,
+ };
+ case 'noise':
+ assertKeys(
+ record,
+ ['op', 'colorA', 'colorB', 'scale', 'octaves', 'seed', 'blend', 'opacity'],
+ path,
+ );
+ return {
+ op,
+ colorA: color(record['colorA'], `${path}.colorA`),
+ colorB: color(record['colorB'], `${path}.colorB`),
+ scale: integer(record['scale'], `${path}.scale`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),
+ octaves: integer(record['octaves'], `${path}.octaves`, 3, 1, MAX_NOISE_OCTAVES),
+ seed: integer(record['seed'], `${path}.seed`, 0, -0x80000000, 0x7fffffff),
+ ...common,
+ };
+ default:
+ throw new ProceduralTextureError(`${path}.op is unsupported.`);
+ }
+}
+
+export function migrateProceduralTextureSpecV1(input: unknown): ProceduralTextureSpecV2 {
+ const record = strictRecord(input, 'proceduralTexture');
+ assertKeys(record, ['schemaVersion', 'size', 'usage', 'name', 'layers'], 'proceduralTexture');
+ if (record['schemaVersion'] !== undefined && record['schemaVersion'] !== 1) {
+ throw new ProceduralTextureError(
+ `proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(record['schemaVersion'])}.`,
+ );
+ }
+ return {
+ schemaVersion: 2,
+ ...(record['size'] !== undefined ? { size: record['size'] as number } : {}),
+ ...(record['usage'] !== undefined ? { usage: record['usage'] as TextureUsage } : {}),
+ ...(record['name'] !== undefined ? { name: record['name'] as string } : {}),
+ layers: record['layers'] as ProceduralLayer[],
+ };
+}
+
+export function canonicalizeProceduralTextureSpecV2(
+ input: unknown,
+): CanonicalProceduralTextureSpecV2 {
+ const initial = strictRecord(input, 'proceduralTexture');
+ const source =
+ initial['schemaVersion'] === undefined || initial['schemaVersion'] === 1
+ ? strictRecord(migrateProceduralTextureSpecV1(initial), 'proceduralTexture')
+ : initial;
+ assertKeys(source, ['schemaVersion', 'size', 'usage', 'name', 'layers'], 'proceduralTexture');
+ if (source['schemaVersion'] !== 2) {
+ throw new ProceduralTextureError(
+ `proceduralTexture.schemaVersion must be 2, got ${JSON.stringify(source['schemaVersion'])}.`,
+ );
+ }
+ const size = source['size'] ?? 256;
+ if (
+ typeof size !== 'number' ||
+ !Number.isInteger(size) ||
+ size < MIN_PROCEDURAL_SIZE ||
+ size > MAX_PROCEDURAL_SIZE ||
+ (size & (size - 1)) !== 0
+ ) {
+ throw new ProceduralTextureError(
+ `proceduralTexture.size must be a power of two between ${MIN_PROCEDURAL_SIZE} and ${MAX_PROCEDURAL_SIZE}, got ${JSON.stringify(source['size'])}.`,
+ );
+ }
+ const rawLayers = source['layers'];
+ if (!Array.isArray(rawLayers) || rawLayers.length === 0) {
+ throw new ProceduralTextureError(
+ 'proceduralTexture.layers must be a non-empty array — the bottom layer is the base pattern.',
+ );
+ }
+ const layers = strictArray(rawLayers, 'proceduralTexture.layers');
+ if (layers.length > MAX_PROCEDURAL_LAYERS) {
+ throw new ProceduralTextureError(
+ `proceduralTexture: ${layers.length} layers exceeds the maximum of ${MAX_PROCEDURAL_LAYERS}.`,
+ );
+ }
+ const name = optionalName(source['name'], 'proceduralTexture.name');
+ return {
+ schemaVersion: 2,
+ size,
+ usage: usage(source['usage'], 'proceduralTexture.usage', 'albedo'),
+ ...(name !== undefined ? { name } : {}),
+ layers: layers.map(canonicalLayer),
+ };
+}
+
+function canonicalJson(value: unknown): string {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ const record = value as Record<string, unknown>;
+ return `{${Object.keys(record)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)
+ .join(',')}}`;
+}
+
+export function canonicalProceduralTextureJsonV2(input: unknown): string {
+ return canonicalJson(canonicalizeProceduralTextureSpecV2(input));
+}
+
+// Browser-safe synchronous SHA-256. Keeping this local avoids a module-load
+// `node:crypto` edge in the primitives graph while still giving synchronous
+// generated code a stable recipe identity.
+const SHA256_K = new Uint32Array([
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
+]);
+
+const rotateRight = (value: number, bits: number): number =>
+ (value >>> bits) | (value << (32 - bits));
+
+function sha256Hex(text: string): string {
+ const source = new TextEncoder().encode(text);
+ const bitLength = source.length * 8;
+ const paddedLength = Math.ceil((source.length + 9) / 64) * 64;
+ const bytes = new Uint8Array(paddedLength);
+ bytes.set(source);
+ bytes[source.length] = 0x80;
+ const view = new DataView(bytes.buffer);
+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000), false);
+ view.setUint32(paddedLength - 4, bitLength >>> 0, false);
+
+ const h = new Uint32Array([
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
+ ]);
+ const w = new Uint32Array(64);
+ for (let offset = 0; offset < bytes.length; offset += 64) {
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);
+ for (let i = 16; i < 64; i++) {
+ const a = w[i - 15]!;
+ const b = w[i - 2]!;
+ const s0 = rotateRight(a, 7) ^ rotateRight(a, 18) ^ (a >>> 3);
+ const s1 = rotateRight(b, 17) ^ rotateRight(b, 19) ^ (b >>> 10);
+ w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0;
+ }
+ let [a, b, c, d, e, f, g, hh] = h;
+ for (let i = 0; i < 64; i++) {
+ const s1 = rotateRight(e!, 6) ^ rotateRight(e!, 11) ^ rotateRight(e!, 25);
+ const choice = (e! & f!) ^ (~e! & g!);
+ const temp1 = (hh! + s1 + choice + SHA256_K[i]! + w[i]!) >>> 0;
+ const s0 = rotateRight(a!, 2) ^ rotateRight(a!, 13) ^ rotateRight(a!, 22);
+ const majority = (a! & b!) ^ (a! & c!) ^ (b! & c!);
+ const temp2 = (s0 + majority) >>> 0;
+ hh = g;
+ g = f;
+ f = e;
+ e = (d! + temp1) >>> 0;
+ d = c;
+ c = b;
+ b = a;
+ a = (temp1 + temp2) >>> 0;
+ }
+ const next = [a!, b!, c!, d!, e!, f!, g!, hh!];
+ for (let i = 0; i < 8; i++) h[i] = (h[i]! + next[i]!) >>> 0;
+ }
+ return [...h].map((value) => value.toString(16).padStart(8, '0')).join('');
+}
+
+export function hashProceduralTextureSpecV2(input: unknown): `sha256:${string}` {
+ return `sha256:${sha256Hex(canonicalProceduralTextureJsonV2(input))}`;
+}
+
+const MATERIAL_TEXTURE_USAGE = {
+ baseColor: 'albedo',
+ normal: 'normal',
+ metallicRoughness: 'metallicRoughness',
+ emissive: 'emissive',
+ occlusion: 'occlusion',
+} as const satisfies Record<string, TextureUsage>;
+
+function canonicalTextureRef(
+ value: unknown,
+ slot: keyof typeof MATERIAL_TEXTURE_USAGE,
+): CanonicalPortableTextureRefV2 {
+ const path = `portableMaterial.textures.${slot}`;
+ const record = strictRecord(value, path);
+ if (record['kind'] === 'procedural') {
+ assertKeys(record, ['kind', 'spec'], path);
+ const spec = canonicalizeProceduralTextureSpecV2(record['spec']);
+ const expected = MATERIAL_TEXTURE_USAGE[slot];
+ if (spec.usage !== expected) {
+ throw new ProceduralTextureError(
+ `${path} requires procedural usage ${JSON.stringify(expected)}, got ${JSON.stringify(spec.usage)}.`,
+ );
+ }
+ return { kind: 'procedural', spec };
+ }
+ if (record['kind'] === 'resource') {
+ assertKeys(record, ['kind', 'resourceId'], path);
+ const resourceId = record['resourceId'];
+ if (
+ typeof resourceId !== 'string' ||
+ resourceId.length > 128 ||
+ !/^kiln\.[a-z0-9][a-z0-9._-]+$/.test(resourceId)
+ ) {
+ throw new ProceduralTextureError(`${path}.resourceId must be a bounded kiln.* resource ID.`);
+ }
+ return { kind: 'resource', resourceId };
+ }
+ throw new ProceduralTextureError(`${path}.kind must be "procedural" or "resource".`);
+}
+
+export function canonicalizePortableMaterialSpecV2(
+ input: unknown,
+): CanonicalPortableMaterialSpecV2 {
+ const record = strictRecord(input, 'portableMaterial');
+ assertKeys(
+ record,
+ [
+ 'schemaVersion',
+ 'model',
+ 'name',
+ 'baseColor',
+ 'roughness',
+ 'metalness',
+ 'emissive',
+ 'emissiveIntensity',
+ 'alphaMode',
+ 'alphaCutoff',
+ 'doubleSided',
+ 'textures',
+ ],
+ 'portableMaterial',
+ );
+ if (record['schemaVersion'] !== 2) {
+ throw new ProceduralTextureError('portableMaterial.schemaVersion must be 2.');
+ }
+ if (record['model'] !== 'pbrMetallicRoughness') {
+ throw new ProceduralTextureError(
+ 'portableMaterial.model must be "pbrMetallicRoughness"; executable shader models are not portable.',
+ );
+ }
+ const textureInput = record['textures'] ?? {};
+ const textureRecord = strictRecord(textureInput, 'portableMaterial.textures');
+ const slots = Object.keys(MATERIAL_TEXTURE_USAGE) as Array<keyof typeof MATERIAL_TEXTURE_USAGE>;
+ assertKeys(textureRecord, slots, 'portableMaterial.textures');
+ if (Object.keys(textureRecord).length > MAX_PORTABLE_MATERIAL_TEXTURES) {
+ throw new ProceduralTextureError(
+ `portableMaterial has more than ${MAX_PORTABLE_MATERIAL_TEXTURES} texture slots.`,
+ );
+ }
+ const textures: CanonicalPortableMaterialSpecV2['textures'] = {};
+ let proceduralTexels = 0;
+ for (const slot of slots) {
+ if (textureRecord[slot] === undefined) continue;
+ const ref = canonicalTextureRef(textureRecord[slot], slot);
+ textures[slot] = ref;
+ if (ref.kind === 'procedural') proceduralTexels += ref.spec.size * ref.spec.size;
+ }
+ if (proceduralTexels > MAX_PORTABLE_MATERIAL_TEXELS) {
+ throw new ProceduralTextureError(
+ `portableMaterial procedural texture budget is ${proceduralTexels} texels, above ${MAX_PORTABLE_MATERIAL_TEXELS}.`,
+ );
+ }
+ const alphaMode = record['alphaMode'] ?? 'opaque';
+ if (alphaMode !== 'opaque' && alphaMode !== 'mask' && alphaMode !== 'blend') {
+ throw new ProceduralTextureError('portableMaterial.alphaMode must be opaque, mask, or blend.');
+ }
+ if (record['doubleSided'] !== undefined && typeof record['doubleSided'] !== 'boolean') {
+ throw new ProceduralTextureError('portableMaterial.doubleSided must be boolean.');
+ }
+ const name = optionalName(record['name'], 'portableMaterial.name');
+ return {
+ schemaVersion: 2,
+ model: 'pbrMetallicRoughness',
+ ...(name !== undefined ? { name } : {}),
+ ...(record['baseColor'] !== undefined
+ ? { baseColor: color(record['baseColor'], 'portableMaterial.baseColor') }
+ : {}),
+ roughness: unit(record['roughness'], 'portableMaterial.roughness', 1),
+ metalness: unit(record['metalness'], 'portableMaterial.metalness', 0),
+ ...(record['emissive'] !== undefined
+ ? { emissive: color(record['emissive'], 'portableMaterial.emissive') }
+ : {}),
+ emissiveIntensity: finite(
+ record['emissiveIntensity'],
+ 'portableMaterial.emissiveIntensity',
+ 1,
+ 0,
+ 64,
+ ),
+ alphaMode,
+ alphaCutoff: unit(record['alphaCutoff'], 'portableMaterial.alphaCutoff', 0.5),
+ doubleSided: record['doubleSided'] === true,
+ textures,
+ };
+}
diff --git a/src/procedural-texture.ts b/src/procedural-texture.ts
index 49230a4b..390414ea 100644
--- a/src/procedural-texture.ts
+++ b/src/procedural-texture.ts
@@ -33,81 +33,53 @@
* Unlike `texture-bake.ts` — which must never guess, because it is handed
* finished pixels whose meaning it cannot know — this function is told the
* usage up front and therefore sets `colorSpace` itself, exactly as
- * `loadTexture` does. Getting it wrong here is an authoring error the QA gate
+ * approved texture loading does. Getting it wrong here is an authoring error the QA gate
* still catches.
*/
import * as THREE from 'three';
-import type { TextureUsage } from './textures';
-
-// -----------------------------------------------------------------------------
-// Bounds — enforced before any work, so a bad spec costs nothing
-// -----------------------------------------------------------------------------
-
-/** Largest texture a spec may request. 1024^2 RGBA is 4 MB of intermediate. */
-export const MAX_PROCEDURAL_SIZE = 1024;
-/** Smallest useful size; below this the generators degenerate. */
-export const MIN_PROCEDURAL_SIZE = 4;
-/** Layers in one stack. Enough to build a convincing material, bounded enough to cost little. */
-export const MAX_PROCEDURAL_LAYERS = 8;
-/** fbm octaves. Past this, added octaves are sub-texel on a 1024 map. */
-export const MAX_NOISE_OCTAVES = 6;
-
-export type ProceduralBlend = 'normal' | 'multiply' | 'screen' | 'overlay';
-
-interface LayerCommon {
- /** How this layer combines with everything under it. Ignored on the first layer. */
- blend?: ProceduralBlend;
- /** 0..1 contribution. Ignored on the first layer. Default 1. */
- opacity?: number;
-}
-
-export type ProceduralLayer = LayerCommon &
- (
- | { op: 'solid'; color: number }
- | { op: 'checker'; colorA: number; colorB: number; squares?: number }
- | { op: 'stripes'; colorA: number; colorB: number; count?: number; angleDeg?: number }
- | { op: 'gradient'; from: number; to: number; angleDeg?: number }
- | {
- op: 'bricks';
- brick: number;
- mortar: number;
- rows?: number;
- cols?: number;
- mortarWidth?: number;
- /** Row offset as a fraction of brick width. 0.5 is a running bond. */
- stagger?: number;
- }
- | {
- op: 'noise';
- colorA: number;
- colorB: number;
- /** Lattice cells across the texture. Higher is finer. Default 8. */
- scale?: number;
- octaves?: number;
- seed?: number;
- }
- );
-
-export interface ProceduralTextureSpec {
- /** Power of two in [4, 1024]. Default 256. */
- size?: number;
- /** Sets `colorSpace` — sRGB for albedo/emissive, linear for data maps. Default albedo. */
- usage?: TextureUsage;
- name?: string;
- /** 1..8 layers, bottom first. */
- layers: ProceduralLayer[];
-}
-
-const OPS = ['solid', 'checker', 'stripes', 'gradient', 'bricks', 'noise'] as const;
-const BLENDS: readonly ProceduralBlend[] = ['normal', 'multiply', 'screen', 'overlay'];
-
-export class ProceduralTextureError extends Error {
- constructor(message: string) {
- super(message);
- this.name = 'ProceduralTextureError';
- }
-}
+import {
+ type CanonicalProceduralLayerV2,
+ type CanonicalProceduralTextureSpecV2,
+ type ProceduralBlend,
+ type ProceduralTextureSpec,
+ ProceduralTextureError,
+ canonicalProceduralTextureJsonV2,
+ canonicalizeProceduralTextureSpecV2,
+ hashProceduralTextureSpecV2,
+} from './procedural-material-v2';
+
+export {
+ MAX_NOISE_OCTAVES,
+ MAX_PORTABLE_MATERIAL_TEXELS,
+ MAX_PORTABLE_MATERIAL_TEXTURES,
+ MAX_PROCEDURAL_LAYERS,
+ MAX_PROCEDURAL_NAME_LENGTH,
+ MAX_PROCEDURAL_PATTERN_COUNT,
+ MAX_PROCEDURAL_SIZE,
+ MIN_PROCEDURAL_SIZE,
+ PORTABLE_MATERIAL_SPEC_VERSION,
+ PROCEDURAL_TEXTURE_SPEC_VERSION,
+ ProceduralTextureError,
+ canonicalProceduralTextureJsonV2,
+ canonicalizePortableMaterialSpecV2,
+ canonicalizeProceduralTextureSpecV2,
+ hashProceduralTextureSpecV2,
+ migrateProceduralTextureSpecV1,
+} from './procedural-material-v2';
+export type {
+ CanonicalPortableMaterialSpecV2,
+ CanonicalPortableTextureRefV2,
+ CanonicalProceduralLayerV2,
+ CanonicalProceduralTextureSpecV2,
+ PortableMaterialSpecV2,
+ PortableTextureRefV2,
+ ProceduralBlend,
+ ProceduralLayer,
+ ProceduralTextureSpec,
+ ProceduralTextureSpecV1,
+ ProceduralTextureSpecV2,
+} from './procedural-material-v2';
// -----------------------------------------------------------------------------
// Deterministic value noise
@@ -171,99 +143,6 @@ function fbm(u: number, v: number, period: number, octaves: number, seed: number
return total > 0 ? sum / total : 0;
}
-// -----------------------------------------------------------------------------
-// Validation
-// -----------------------------------------------------------------------------
-
-function isPowerOfTwo(n: number): boolean {
- return Number.isInteger(n) && n > 0 && (n & (n - 1)) === 0;
-}
-
-function checkColor(value: unknown, label: string): number {
- if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > 0xffffff) {
- throw new ProceduralTextureError(
- `proceduralTexture: ${label} must be a color integer between 0x000000 and 0xffffff, got ${JSON.stringify(value)}.`,
- );
- }
- return value;
-}
-
-function checkCount(value: unknown, label: string, fallback: number, max = 256): number {
- if (value === undefined) return fallback;
- if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > max) {
- throw new ProceduralTextureError(
- `proceduralTexture: ${label} must be a whole number between 1 and ${max}, got ${JSON.stringify(value)}.`,
- );
- }
- return value;
-}
-
-function checkUnit(value: unknown, label: string, fallback: number): number {
- if (value === undefined) return fallback;
- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
- throw new ProceduralTextureError(
- `proceduralTexture: ${label} must be between 0 and 1, got ${JSON.stringify(value)}.`,
- );
- }
- return value;
-}
-
-function validateSpec(spec: ProceduralTextureSpec): {
- size: number;
- usage: TextureUsage;
- layers: ProceduralLayer[];
-} {
- if (!spec || typeof spec !== 'object') {
- throw new ProceduralTextureError('proceduralTexture: a spec object is required.');
- }
-
- const size = spec.size ?? 256;
- if (!isPowerOfTwo(size) || size < MIN_PROCEDURAL_SIZE || size > MAX_PROCEDURAL_SIZE) {
- throw new ProceduralTextureError(
- `proceduralTexture: size must be a power of two between ${MIN_PROCEDURAL_SIZE} and ${MAX_PROCEDURAL_SIZE}, got ${JSON.stringify(spec.size)}.`,
- );
- }
-
- const layers = spec.layers;
- if (!Array.isArray(layers) || layers.length === 0) {
- throw new ProceduralTextureError(
- 'proceduralTexture: layers must be a non-empty array — the bottom layer is the base pattern.',
- );
- }
- if (layers.length > MAX_PROCEDURAL_LAYERS) {
- throw new ProceduralTextureError(
- `proceduralTexture: ${layers.length} layers exceeds the maximum of ${MAX_PROCEDURAL_LAYERS}.`,
- );
- }
-
- for (const [i, layer] of layers.entries()) {
- if (!layer || typeof layer !== 'object') {
- throw new ProceduralTextureError(`proceduralTexture: layers[${i}] must be an object.`);
- }
- if (!(OPS as readonly string[]).includes(layer.op)) {
- throw new ProceduralTextureError(
- `proceduralTexture: layers[${i}].op ${JSON.stringify(layer.op)} is not one of ${OPS.join(', ')}.`,
- );
- }
- if (layer.blend !== undefined && !BLENDS.includes(layer.blend)) {
- throw new ProceduralTextureError(
- `proceduralTexture: layers[${i}].blend ${JSON.stringify(layer.blend)} is not one of ${BLENDS.join(', ')}.`,
- );
- }
- checkUnit(layer.opacity, `layers[${i}].opacity`, 1);
- if (layer.op === 'noise') {
- const octaves = layer.octaves ?? 3;
- if (!Number.isInteger(octaves) || octaves < 1 || octaves > MAX_NOISE_OCTAVES) {
- throw new ProceduralTextureError(
- `proceduralTexture: layers[${i}].octaves must be a whole number between 1 and ${MAX_NOISE_OCTAVES}, got ${JSON.stringify(layer.octaves)}.`,
- );
- }
- }
- }
-
- return { size, usage: spec.usage ?? 'albedo', layers };
-}
-
// -----------------------------------------------------------------------------
// Layer evaluation
// -----------------------------------------------------------------------------
@@ -283,68 +162,51 @@ function project(u: number, v: number, angleDeg: number): number {
}
/** Evaluate one layer at a normalized coordinate, returning 0-255 RGB. */
-function evalLayer(layer: ProceduralLayer, u: number, v: number): [number, number, number] {
+function evalLayer(
+ layer: CanonicalProceduralLayerV2,
+ u: number,
+ v: number,
+): [number, number, number] {
switch (layer.op) {
case 'solid':
- return rgbOf(checkColor(layer.color, 'solid.color'));
+ return rgbOf(layer.color);
case 'checker': {
- const squares = checkCount(layer.squares, 'checker.squares', 8);
- const cx = Math.floor(u * squares);
- const cy = Math.floor(v * squares);
- return rgbOf(
- (cx + cy) % 2 === 0
- ? checkColor(layer.colorA, 'checker.colorA')
- : checkColor(layer.colorB, 'checker.colorB'),
- );
+ const cx = Math.floor(u * layer.squares);
+ const cy = Math.floor(v * layer.squares);
+ return rgbOf((cx + cy) % 2 === 0 ? layer.colorA : layer.colorB);
}
case 'stripes': {
- const count = checkCount(layer.count, 'stripes.count', 8);
- const t = project(u, v, layer.angleDeg ?? 0);
- return rgbOf(
- Math.floor(t * count) % 2 === 0
- ? checkColor(layer.colorA, 'stripes.colorA')
- : checkColor(layer.colorB, 'stripes.colorB'),
- );
+ const t = project(u, v, layer.angleDeg);
+ return rgbOf(Math.floor(t * layer.count) % 2 === 0 ? layer.colorA : layer.colorB);
}
case 'gradient': {
- const t = Math.min(1, Math.max(0, project(u, v, layer.angleDeg ?? 0)));
- const from = rgbOf(checkColor(layer.from, 'gradient.from'));
- const to = rgbOf(checkColor(layer.to, 'gradient.to'));
+ const t = Math.min(1, Math.max(0, project(u, v, layer.angleDeg)));
+ const from = rgbOf(layer.from);
+ const to = rgbOf(layer.to);
return [lerp(from[0], to[0], t), lerp(from[1], to[1], t), lerp(from[2], to[2], t)];
}
case 'bricks': {
- const rows = checkCount(layer.rows, 'bricks.rows', 8);
- const cols = checkCount(layer.cols, 'bricks.cols', 4);
- const mortarWidth = checkUnit(layer.mortarWidth, 'bricks.mortarWidth', 0.06);
- const stagger = checkUnit(layer.stagger, 'bricks.stagger', 0.5);
- const row = Math.floor(v * rows);
+ const row = Math.floor(v * layer.rows);
// Offset alternate rows, wrapping into [0,1) so the pattern still tiles.
- const shifted = (u + (row % 2 === 0 ? 0 : stagger / cols) + 1) % 1;
- const inCol = (shifted * cols) % 1;
- const inRow = (v * rows) % 1;
+ const shifted = (u + (row % 2 === 0 ? 0 : layer.stagger / layer.cols) + 1) % 1;
+ const inCol = (shifted * layer.cols) % 1;
+ const inRow = (v * layer.rows) % 1;
const isMortar =
- inCol < mortarWidth ||
- inCol > 1 - mortarWidth ||
- inRow < mortarWidth ||
- inRow > 1 - mortarWidth;
- return rgbOf(
- isMortar
- ? checkColor(layer.mortar, 'bricks.mortar')
- : checkColor(layer.brick, 'bricks.brick'),
- );
+ inCol < layer.mortarWidth ||
+ inCol > 1 - layer.mortarWidth ||
+ inRow < layer.mortarWidth ||
+ inRow > 1 - layer.mortarWidth;
+ return rgbOf(isMortar ? layer.mortar : layer.brick);
}
case 'noise': {
- const scale = checkCount(layer.scale, 'noise.scale', 8);
- const octaves = layer.octaves ?? 3;
- const seed = Number.isInteger(layer.seed) ? (layer.seed as number) : 0;
- const n = fbm(u, v, scale, octaves, seed);
- const a = rgbOf(checkColor(layer.colorA, 'noise.colorA'));
- const b = rgbOf(checkColor(layer.colorB, 'noise.colorB'));
+ const n = fbm(u, v, layer.scale, layer.octaves, layer.seed);
+ const a = rgbOf(layer.colorA);
+ const b = rgbOf(layer.colorB);
return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];
}
}
@@ -382,6 +244,7 @@ function blendChannel(mode: ProceduralBlend, base: number, top: number): number
*
* @example
* const bark = proceduralTexture({
+ * schemaVersion: 2,
* size: 256,
* usage: 'albedo',
* name: 'Bark',
@@ -394,9 +257,17 @@ function blendChannel(mode: ProceduralBlend, base: number, top: number): number
* });
* const trunk = createPart('Trunk', cylinderGeo(0.3, 0.3, 3), pbrMaterial({ albedo: bark }), { parent: root });
*/
-export function proceduralTexture(spec: ProceduralTextureSpec): THREE.DataTexture {
- const { size, usage, layers } = validateSpec(spec);
+export interface CompiledProceduralTextureV2 {
+ spec: CanonicalProceduralTextureSpecV2;
+ pixels: Uint8Array;
+ canonicalJson: string;
+ recipeHash: `sha256:${string}`;
+}
+/** Validate, canonicalize, and compile one texture without constructing Three.js state. */
+export function compileProceduralTextureSpecV2(input: unknown): CompiledProceduralTextureV2 {
+ const spec = canonicalizeProceduralTextureSpecV2(input);
+ const { size, layers } = spec;
const data = new Uint8Array(size * size * 4);
for (let y = 0; y < size; y++) {
// Sample at texel centers so a pattern with N divisions lands on exact
@@ -415,11 +286,9 @@ export function proceduralTexture(spec: ProceduralTextureSpec): THREE.DataTextur
b = lb;
continue;
}
- const mode = layer.blend ?? 'normal';
- const opacity = layer.opacity ?? 1;
- r = lerp(r, blendChannel(mode, r, lr), opacity);
- g = lerp(g, blendChannel(mode, g, lg), opacity);
- b = lerp(b, blendChannel(mode, b, lb), opacity);
+ r = lerp(r, blendChannel(layer.blend, r, lr), layer.opacity);
+ g = lerp(g, blendChannel(layer.blend, g, lg), layer.opacity);
+ b = lerp(b, blendChannel(layer.blend, b, lb), layer.opacity);
}
const o = (y * size + x) * 4;
data[o] = Math.max(0, Math.min(255, Math.round(r)));
@@ -429,8 +298,26 @@ export function proceduralTexture(spec: ProceduralTextureSpec): THREE.DataTextur
}
}
- const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat, THREE.UnsignedByteType);
- if (spec.name) tex.name = spec.name;
+ return {
+ spec,
+ pixels: data,
+ canonicalJson: canonicalProceduralTextureJsonV2(spec),
+ recipeHash: hashProceduralTextureSpecV2(spec),
+ };
+}
+
+export function proceduralTexture(spec: ProceduralTextureSpec): THREE.DataTexture {
+ const compiled = compileProceduralTextureSpecV2(spec);
+ const { size, usage, name, layers } = compiled.spec;
+
+ const tex = new THREE.DataTexture(
+ compiled.pixels,
+ size,
+ size,
+ THREE.RGBAFormat,
+ THREE.UnsignedByteType,
+ );
+ if (name) tex.name = name;
tex.colorSpace =
usage === 'albedo' || usage === 'emissive' ? THREE.SRGBColorSpace : THREE.NoColorSpace;
tex.wrapS = THREE.RepeatWrapping;
@@ -443,10 +330,13 @@ export function proceduralTexture(spec: ProceduralTextureSpec): THREE.DataTextur
// Recorded so the manifest says what was generated, not merely that something
// was. The spec is small, serializable, and enough to reproduce the bytes.
(tex.userData as Record<string, unknown>)['kilnProcedural'] = {
- schemaVersion: 1,
+ schemaVersion: 2,
size,
usage,
+ ...(name ? { name } : {}),
layers,
+ canonicalJson: compiled.canonicalJson,
+ recipeHash: compiled.recipeHash,
};
return tex;
@@ -478,7 +368,7 @@ export function normalMapFromHeight(
const height = image?.height ?? 0;
if (!data || !width || !height) {
throw new ProceduralTextureError(
- 'normalMapFromHeight: the source texture has no readable pixels. Pass a proceduralTexture() result or a loadTexture() result, not a texture built from an image element.',
+ 'normalMapFromHeight: the source texture has no readable pixels. Pass a proceduralTexture() result or a loadApprovedTexture() result, not a texture built from an image element.',
);
}
const channels = data.length / (width * height);
diff --git a/src/prompt-api.ts b/src/prompt-api.ts
index 90d2d415..f35e52a8 100644
--- a/src/prompt-api.ts
+++ b/src/prompt-api.ts
@@ -26,7 +26,7 @@ const CATEGORY_HEADERS: Array<[PrimitiveSpec['category'], string]> = [
['mesh-ops', '// Mesh ops'],
['curves', '// Curves'],
['uv', '// UV unwrapping'],
- ['textures', '// Textures (loadTexture is async)'],
+ ['textures', '// Textures (approved resource loading is async)'],
['animation', '// Animation — keyframes use "rotation"/"position"/"scale" keys, NOT "value"'],
['utility', '// Inspection utilities'],
];
diff --git a/src/prompt.ts b/src/prompt.ts
index 08bff39d..febb673d 100644
--- a/src/prompt.ts
+++ b/src/prompt.ts
@@ -88,7 +88,7 @@ Generate assets with realistic proportions and detail:
export const KILN_PROMPT_HEADER = `You are an expert procedural 3D asset generator. Create game-ready models with character and style.
-CRITICAL: NO import/export statements. Code runs in a sandbox with primitives as globals.`;
+CRITICAL: NO import/export statements. Code runs with documented primitives as globals. Use only those globals: never access globalThis/global/process/network APIs, dynamic import/eval/Function, constructor chains, or raw THREE.DataTexture/ShaderMaterial/RawShaderMaterial constructors.`;
export const KILN_FILE_FORMAT = `<file-format>
const meta = { name: "AssetName", category: "prop", role: "prop" };
@@ -145,7 +145,7 @@ export const KILN_API_IDIOMS = `// Usage idioms:
// Textured asset pipeline:
// 1. Build a geometry (boxGeo / CSG / subdivide / curveToMesh / etc)
// 2. \`await autoUnwrap(geo)\` → adds a uv attribute
-// 3. \`await loadTexture(path)\` → load albedo/normal/etc PNG
+// 3. \`await loadApprovedTexture(resourceId)\` → load a listed approved texture
// 4. \`pbrMaterial({ albedo: tex, ... })\` → build PBR material
// 5. new THREE.Mesh(unwrappedGeo, mat) → attach to scene
// THREE namespace is exposed — use \`new THREE.Mesh(geo, mat)\` when an op needs a
@@ -202,9 +202,12 @@ Model the requested construction, not just its outline:
Author portable material response, not render-only decoration:
- Use gameMaterial for deliberate flat/stylized colour. For metal, wood, stone, bark, cloth, skin,
glass, paint, or textured-hero requests, follow the resolved portable material recipe guidance.
-- proceduralTexture() creates deterministic image data that is baked into the GLB. Build restrained
- albedo/roughness patterns (and normalMapFromHeight when useful), unwrap the geometry, and bind them
- through pbrMaterial. Prefer a few coherent material roles over unique noisy textures per part.
+- proceduralTexture({ schemaVersion: 2, ... }) is the strict portable texture DSL: six finite layer
+ ops, no callbacks, shader source, URLs, filesystem paths, or unknown fields. It creates deterministic
+ image data that is baked into the GLB. Build restrained albedo/roughness patterns (and
+ normalMapFromHeight when useful), unwrap the geometry, and bind them through pbrMaterial. Prefer a
+ few coherent material roles over unique noisy textures per part. Historical recipes without a
+ schemaVersion still migrate, but author all new recipes as V2.
- Surface detail supports form: align grain, wear, seams, and pattern scale with the object's
construction. Do not fake texture by scattering hundreds of tiny meshes or by inventing filesystem
paths/resource IDs.
@@ -443,7 +446,19 @@ const meta = { name: "Crate", category: "prop" };
async function build() {
const root = createRoot("Crate");
- const wood = await loadTexture('./war-assets/textures/wood-planks.png');
+ const wood = proceduralTexture({
+ schemaVersion: 2,
+ size: 256,
+ usage: 'albedo',
+ name: 'WoodPlanks',
+ layers: [
+ { op: 'solid', color: 0x70482d },
+ { op: 'noise', colorA: 0x4a2d1c, colorB: 0xa06f45, scale: 8, octaves: 3, seed: 7,
+ blend: 'overlay', opacity: 0.35 },
+ { op: 'stripes', colorA: 0x3a2115, colorB: 0xc69762, count: 12, angleDeg: 0,
+ blend: 'multiply', opacity: 0.18 },
+ ],
+ });
const mat = pbrMaterial({ albedo: wood, roughness: 0.88, metalness: 0 });
const geo = await autoUnwrap(boxGeo(1, 1, 1), { resolution: 1024 });
const mesh = new THREE.Mesh(geo, mat);
@@ -747,7 +762,8 @@ The sandbox exposes ~70 primitive helpers as globals (no imports), grouped:
corner bevel, twist, taper), revolveProfile (solid lathe with a bevelled
rim), circleProfile (sync outline helper)
- Mesh ops & curves: subdivide, mergeVertices, curveToMesh, pipeAlongPath, lathe, revolveGeo
-- UV + textures: autoUnwrap, boxUnwrap, cylinderUnwrap, planeUnwrap, panelRemapV, loadTexture
+- UV + textures: autoUnwrap, boxUnwrap, cylinderUnwrap, planeUnwrap, panelRemapV,
+ loadApprovedTexture, proceduralTexture, normalMapFromHeight
- Animation: rotationTrack/positionTrack/scaleTrack (keys are "rotation"/"position"/"scale",
NOT "value"), createClip, spinAnimation, bobbingAnimation, idleBreathing
diff --git a/src/qa/material.ts b/src/qa/material.ts
index 2d87cba9..f38e0ee8 100644
--- a/src/qa/material.ts
+++ b/src/qa/material.ts
@@ -108,7 +108,7 @@ function validateTextureSlot(
message: `${slot} texture has no verified decoded/exportable image payload.`,
affected: affected(mesh, material, texture, slot),
repairText:
- 'Load a decodable PNG, JPEG, or WebP with loadTexture() before assigning it. A texture built in code is baked to PNG automatically, so reaching this means its pixels were unreadable — it must be a DataTexture holding 8-bit RGB or RGBA bytes, not float data or an image element.',
+ 'Use loadApprovedTexture(resourceId) or proceduralTexture() before assigning it. A texture built in code is baked to PNG automatically, so reaching this means its pixels were unreadable — it must be a DataTexture holding 8-bit RGB or RGBA bytes, not float data or an image element.',
});
}
if (actual !== expected) {
@@ -120,7 +120,7 @@ function validateTextureSlot(
message: `${slot} texture must use ${expected} data interpretation, not ${actual}.`,
affected: affected(mesh, material, texture, slot),
measurement: { name: 'colorSpace', actual, expected },
- repairText: `Reload the texture with loadTexture(..., { usage: '${slot === 'map' ? 'albedo' : slot}' }), or for a texture built in code set texture.colorSpace = ${expected === 'srgb' ? 'THREE.SRGBColorSpace' : 'THREE.NoColorSpace'} — it is never set for you, because reinterpreting an author's pixels silently is exactly the failure this check exists to catch.`,
+ repairText: `Choose an approved resource whose declared usage matches '${slot === 'map' ? 'albedo' : slot}', or for a texture built in code set texture.colorSpace = ${expected === 'srgb' ? 'THREE.SRGBColorSpace' : 'THREE.NoColorSpace'} — it is never set for you, because reinterpreting an author's pixels silently is exactly the failure this check exists to catch.`,
});
}
diff --git a/src/render.ts b/src/render.ts
index f48ec9aa..62303c16 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -87,6 +87,8 @@ import {
collectMaterialResourceProvenance,
type MaterialResourceProvenanceV1,
} from './material-resources';
+import { DEFAULT_TEXTURE_RESOLVER, type TextureResolver } from './texture-resolver';
+import { assertGeneratedSourceSafe } from './validation';
import { analyzePartPenetration, type PartPenetrationEvidenceV1 } from './qa/self-intersection';
import { applyKitContract, type KitPackOptions, type KitPackSummary } from './kit';
import {
@@ -316,7 +318,16 @@ export interface ExecutedKilnCode {
* return value is a Promise it is awaited, otherwise it is used as-is.
* Same for `animate()`.
*/
-export async function executeKilnCode(code: string): Promise<ExecutedKilnCode> {
+export interface ExecuteKilnCodeOptions {
+ /** Trusted host injection. Generated source receives only the closed
+ * loadApprovedTexture(resourceId) function. */
+ textureResolver?: TextureResolver;
+}
+
+export async function executeKilnCode(
+ code: string,
+ options: ExecuteKilnCodeOptions = {},
+): Promise<ExecutedKilnCode> {
if (!code || typeof code !== 'string') {
throw new Error('executeKilnCode: code must be a non-empty string');
}
@@ -325,8 +336,14 @@ export async function executeKilnCode(code: string): Promise<ExecutedKilnCode> {
// Function constructor.
const normalized = code.replace(/\r\n/g, '\n');
+ // Defense in depth only: reject known ambient/dynamic-code escape patterns
+ // before the Function constructor sees source. This is not process isolation.
+ assertGeneratedSourceSafe(normalized);
+
const primitiveUsage: Record<string, number> = {};
- const globals = buildSandboxGlobals(primitiveUsage);
+ const globals = buildSandboxGlobals(primitiveUsage, {
+ textureResolver: options.textureResolver ?? DEFAULT_TEXTURE_RESOLVER,
+ });
const globalNames = Object.keys(globals);
const globalValues = Object.values(globals);
@@ -804,6 +821,8 @@ function bridgeAnimations(
export interface RenderResult {
glb: Buffer;
+ /** SHA-256 identity of the exact returned GLB bytes. */
+ artifactGlbSha256: `sha256:${string}`;
tris: number;
meta: KilnCodeMeta;
warnings: string[];
@@ -812,6 +831,8 @@ export interface RenderResult {
materialMetrics?: MaterialMetricsV1;
materialRecipeApplications?: MaterialRecipeApplicationProvenanceV1[];
materialResourceProvenance?: MaterialResourceProvenanceV1[];
+ /** Textures baked into the returned GLB, including bounded procedural lineage. */
+ bakedTextures?: BakedTextureProvenanceV1[];
integrationManifest: IntegrationManifestV1;
}
@@ -869,6 +890,8 @@ export interface InstancingSummary {
export interface RenderSceneResult {
/** Binary GLB bytes, platform-agnostic (Buffer-compatible in Node). */
bytes: Uint8Array;
+ /** SHA-256 identity of `bytes`. */
+ artifactGlbSha256: `sha256:${string}`;
tris: number;
warnings: string[];
/** Official Khronos report for these exact post-transform bytes. */
@@ -1253,6 +1276,11 @@ export async function renderSceneToGLB(
const io = engineIO();
ensureDefaultScene(doc);
const bytes = await io.writeBinary(doc);
+ const artifactGlbSha256 = `sha256:${await sha256Hex(bytes)}` as const;
+ const boundBakedTextures = bakedTextures.map((entry) => ({
+ ...entry,
+ artifactGlbSha256,
+ }));
const gltfValidation = await validateFinalGlbBytes(bytes);
const finalGltfReport = appendFinalGltfQa(intent, sceneQaReport, gltfValidation);
const runtimeQaReport = appendRuntimeCostQa(
@@ -1312,6 +1340,7 @@ export async function renderSceneToGLB(
return {
bytes,
+ artifactGlbSha256,
tris,
warnings,
gltfValidation,
@@ -1324,7 +1353,7 @@ export async function renderSceneToGLB(
...(materialMetrics ? { materialMetrics } : {}),
...(materialRecipeApplications.length ? { materialRecipeApplications } : {}),
...(materialResourceProvenance.length ? { materialResourceProvenance } : {}),
- ...(bakedTextures.length ? { bakedTextures } : {}),
+ ...(boundBakedTextures.length ? { bakedTextures: boundBakedTextures } : {}),
integrationManifest,
};
}
@@ -1338,16 +1367,28 @@ export async function renderSceneToGLB(
*
* Pure function: no file I/O, no globals, no WebGL.
*/
-export async function renderGLB(
+export interface RenderGlbOptions {
+ optimize?: OptimizeMode;
+ instance?: InstanceMode;
+ intent?: AssetIntentV1;
+ category?: AssetCategory;
+ /** Trusted evaluator dependency; never derived from generated code. */
+ textureResolver?: TextureResolver;
+}
+
+/**
+ * Trusted in-process execute/export implementation.
+ *
+ * Hosts should normally call {@link renderGLB}. The subprocess evaluator calls
+ * this function directly to prevent recursive process creation.
+ */
+export async function renderGLBInProcess(
code: string,
- opts: {
- optimize?: OptimizeMode;
- instance?: InstanceMode;
- intent?: AssetIntentV1;
- category?: AssetCategory;
- } = {},
+ opts: RenderGlbOptions = {},
): Promise<RenderResult> {
- const { meta, root, clips, primitiveUsage } = await executeKilnCode(code);
+ const { meta, root, clips, primitiveUsage } = await executeKilnCode(code, {
+ textureResolver: opts.textureResolver ?? DEFAULT_TEXTURE_RESOLVER,
+ });
const requestedCategory = opts.intent?.category ?? opts.category;
const scene = await renderSceneToGLB(root, {
sceneName: meta.name || 'Scene',
@@ -1362,6 +1403,7 @@ export async function renderGLB(
const { category: modelCategory, ...modelMeta } = meta;
return {
glb: Buffer.from(scene.bytes),
+ artifactGlbSha256: scene.artifactGlbSha256,
tris: scene.tris,
meta: {
...modelMeta,
@@ -1387,10 +1429,42 @@ export async function renderGLB(
...(scene.materialResourceProvenance
? { materialResourceProvenance: scene.materialResourceProvenance }
: {}),
+ ...(scene.bakedTextures ? { bakedTextures: scene.bakedTextures } : {}),
integrationManifest: scene.integrationManifest,
};
}
+export type EvaluatorMode = 'in-process' | 'subprocess' | 'isolated';
+
+/** Resolve the trusted host evaluator flag. Unknown values fail closed. */
+export function resolveEvaluatorMode(
+ env: Record<string, string | undefined> = process.env,
+): EvaluatorMode {
+ const value = env['KILN_EVALUATOR_MODE'];
+ if (value === undefined || value === '' || value === 'in-process') return 'in-process';
+ if (value === 'subprocess') return 'subprocess';
+ if (value === 'isolated') return 'isolated';
+ throw new Error('Invalid KILN_EVALUATOR_MODE.');
+}
+
+/**
+ * Execute Kiln code and serialize it to GLB.
+ *
+ * Subprocess containment is disabled by default and selected only by the
+ * trusted host flag. A subprocess error is terminal; this boundary never
+ * falls back to unsafe in-process execution.
+ */
+export async function renderGLB(code: string, opts: RenderGlbOptions = {}): Promise<RenderResult> {
+ const mode = resolveEvaluatorMode();
+ if (mode === 'in-process') return renderGLBInProcess(code, opts);
+ if (mode === 'subprocess') {
+ const { renderGLBViaSubprocess } = await import('./evaluator/subprocess');
+ return renderGLBViaSubprocess(code, opts);
+ }
+ const { renderGLBViaIsolatedEvaluator } = await import('./evaluator/isolation');
+ return renderGLBViaIsolatedEvaluator(code, opts);
+}
+
/**
* Grade instanceability directly from baked GLB bytes.
*
diff --git a/src/texture-bake.ts b/src/texture-bake.ts
index 57ec38ac..96d89fb0 100644
--- a/src/texture-bake.ts
+++ b/src/texture-bake.ts
@@ -43,6 +43,13 @@ import { createHash } from 'node:crypto';
import * as THREE from 'three';
import type { EncodedTextureData, KilnTextureMetadata, TextureUsage } from './textures';
+export interface BakedTextureBindingV1 {
+ node: string;
+ material: string;
+ slot: string;
+ usage: TextureUsage;
+}
+
/** Provenance for one texture this pass encoded. Deterministic and sorted. */
export interface BakedTextureProvenanceV1 {
schemaVersion: 1;
@@ -50,14 +57,25 @@ export interface BakedTextureProvenanceV1 {
texture: string;
/** Owning material name, for locating it in the source. */
material: string;
+ /** Owning scene node name. This is a bounded semantic locator, never a host path. */
+ node: string;
/** glTF-facing slot the texture fills (`map`, `normalMap`, ...). */
slot: string;
usage: TextureUsage;
+ /** Every scene binding of these encoded bytes, in deterministic traversal order. */
+ bindings: BakedTextureBindingV1[];
width: number;
height: number;
channels: 3 | 4;
/** Encoded PNG size in bytes. */
bytes: number;
+ /** Encoding and interpretation of the exact embedded image bytes. */
+ mime: 'image/png';
+ colorSpace: 'srgb' | 'linear';
+ /** SHA-256 identity of the encoded PNG bytes. */
+ imageSha256: `sha256:${string}`;
+ /** SHA-256 identity of the final GLB containing this binding. Filled after export. */
+ artifactGlbSha256?: `sha256:${string}`;
/** SHA-1 of the PNG bytes — the handle a determinism test compares. */
sha1: string;
/**
@@ -72,10 +90,14 @@ export interface BakedTextureProvenanceV1 {
/** The `userData.kilnProcedural` stamp `proceduralTexture()` leaves behind. */
interface ProceduralRecipeRecord {
- schemaVersion: 1;
+ schemaVersion: 1 | 2;
size: number;
usage: TextureUsage;
+ name?: string;
layers: unknown[];
+ /** V2 canonical identity; absent on historical V1 texture stamps. */
+ canonicalJson?: string;
+ recipeHash?: `sha256:${string}`;
}
/**
@@ -200,13 +222,18 @@ export async function bakeSceneTextures(
): Promise<BakedTextureProvenanceV1[]> {
// Collect first, encode second: traversal is sync, encoding is not, and doing
// them together would interleave awaits with a mutating walk.
- const pending: Array<{
- texture: THREE.Texture;
- material: string;
- slot: string;
- usage: TextureUsage;
- }> = [];
- const seen = new Set<THREE.Texture>();
+ const pending = new Map<
+ THREE.Texture,
+ {
+ texture: THREE.Texture;
+ bindings: Array<{
+ node: string;
+ material: string;
+ slot: string;
+ usage: TextureUsage;
+ }>;
+ }
+ >();
root.traverse((node) => {
const material = (node as THREE.Mesh).material;
@@ -215,26 +242,29 @@ export async function bakeSceneTextures(
const bag = item as unknown as Record<string, unknown>;
for (const [slot, usage] of SLOT_USAGE) {
const texture = bag[slot];
- if (!isTexture(texture) || seen.has(texture)) continue;
- seen.add(texture);
+ if (!isTexture(texture)) continue;
if ((texture.userData as Record<string, unknown>)['encoded']) continue;
- pending.push({
- texture,
+ const existing = pending.get(texture) ?? { texture, bindings: [] };
+ existing.bindings.push({
+ node: node.name || '(unnamed node)',
material: item.name || '(unnamed material)',
slot,
usage,
});
+ pending.set(texture, existing);
}
}
});
const baked: BakedTextureProvenanceV1[] = [];
- for (const entry of pending) {
+ for (const entry of pending.values()) {
const name = entry.texture.name || '(unnamed texture)';
const raw = readPixels(entry.texture);
+ const firstBinding = entry.bindings[0]!;
+ const bindingSummary = `material ${JSON.stringify(firstBinding.material)} (${firstBinding.slot})${entry.bindings.length > 1 ? ` and ${entry.bindings.length - 1} other binding(s)` : ''}`;
if (typeof raw === 'string') {
warnings.push(
- `Texture ${JSON.stringify(name)} on material ${JSON.stringify(entry.material)} (${entry.slot}) was dropped from the GLB: ${raw}.`,
+ `Texture ${JSON.stringify(name)} on ${bindingSummary} was dropped from the GLB: ${raw}.`,
);
continue;
}
@@ -244,7 +274,7 @@ export async function bakeSceneTextures(
bytes = await encodePngFromRaw(raw);
} catch (err) {
warnings.push(
- `Texture ${JSON.stringify(name)} on material ${JSON.stringify(entry.material)} (${entry.slot}) was dropped from the GLB: PNG encoding failed (${err instanceof Error ? err.message : String(err)}).`,
+ `Texture ${JSON.stringify(name)} on ${bindingSummary} was dropped from the GLB: PNG encoding failed (${err instanceof Error ? err.message : String(err)}).`,
);
continue;
}
@@ -256,9 +286,14 @@ export async function bakeSceneTextures(
// Describe what the texture IS, not what the slot wants — QA compares this
// against `texture.colorSpace`, and reporting the slot's expectation here
// would make a mismatched color space pass by asserting itself.
+ const colorSpace = entry.texture.colorSpace === THREE.SRGBColorSpace ? 'srgb' : 'linear';
+ // A shared texture can legally occupy several bindings. Its own declared
+ // usage is taken from the first deterministic traversal binding; every
+ // binding remains present in provenance below.
+ const primaryUsage = entry.bindings[0]?.usage ?? 'albedo';
(entry.texture.userData as Record<string, unknown>)['kilnTexture'] = {
- usage: entry.usage,
- colorSpace: entry.texture.colorSpace === THREE.SRGBColorSpace ? 'srgb' : 'linear',
+ usage: primaryUsage,
+ colorSpace,
width: raw.width,
height: raw.height,
hasAlpha: hasTranslucentPixel(raw),
@@ -268,22 +303,33 @@ export async function bakeSceneTextures(
| ProceduralRecipeRecord
| undefined;
+ const sha1 = createHash('sha1').update(bytes).digest('hex');
+ const imageSha256 = `sha256:${createHash('sha256').update(bytes).digest('hex')}` as const;
baked.push({
schemaVersion: 1,
texture: name,
- material: entry.material,
- slot: entry.slot,
- usage: entry.usage,
+ node: firstBinding.node,
+ material: firstBinding.material,
+ slot: firstBinding.slot,
+ usage: firstBinding.usage,
+ bindings: entry.bindings,
width: raw.width,
height: raw.height,
channels: raw.channels,
bytes: bytes.length,
- sha1: createHash('sha1').update(bytes).digest('hex'),
+ mime: 'image/png',
+ colorSpace,
+ imageSha256,
+ sha1,
...(recipe ? { procedural: recipe } : {}),
});
}
- return baked.sort((a, b) => `${a.texture}:${a.slot}`.localeCompare(`${b.texture}:${b.slot}`));
+ return baked.sort((a, b) =>
+ `${a.node}:${a.material}:${a.texture}:${a.slot}`.localeCompare(
+ `${b.node}:${b.material}:${b.texture}:${b.slot}`,
+ ),
+ );
}
// -----------------------------------------------------------------------------
diff --git a/src/texture-resolver.ts b/src/texture-resolver.ts
new file mode 100644
index 00000000..c3ba3ec0
--- /dev/null
+++ b/src/texture-resolver.ts
@@ -0,0 +1,48 @@
+/**
+ * Closed texture/material dependency injected into generated-code evaluation.
+ *
+ * The trusted host may construct this object around a bounded resource cache.
+ * Generated source never receives the object: primitives.ts exposes only two
+ * argument-count-checked closures, so source cannot provide caches, paths,
+ * URLs, bytes, hashes, deadlines, resolvers, or filesystem handles.
+ */
+import type * as THREE from 'three';
+
+import {
+ type ApprovedTextureResourceCache,
+ DEFAULT_APPROVED_TEXTURE_CACHE,
+} from './material-resources';
+import { materialRecipe as applyTrustedMaterialRecipe } from './material-recipe-runtime';
+import type {
+ MaterialRecipeId,
+ MaterialRecipeOverridesV1,
+ ApprovedTextureResourceId,
+} from './material-recipes';
+
+export interface TextureResolver {
+ loadApprovedTexture(resourceId: unknown): Promise<THREE.DataTexture>;
+ materialRecipe(id: unknown, overrides?: unknown): Promise<THREE.MeshStandardMaterial>;
+}
+
+export function createTextureResolver(
+ cache: ApprovedTextureResourceCache = DEFAULT_APPROVED_TEXTURE_CACHE,
+): TextureResolver {
+ return Object.freeze({
+ async loadApprovedTexture(resourceId: unknown): Promise<THREE.DataTexture> {
+ if (typeof resourceId !== 'string') {
+ throw new RangeError('Unsupported approved texture resource ID.');
+ }
+ return (await cache.load(resourceId as ApprovedTextureResourceId)).texture;
+ },
+ async materialRecipe(id: unknown, overrides?: unknown): Promise<THREE.MeshStandardMaterial> {
+ if (typeof id !== 'string') throw new TypeError('materialRecipe id must be a string');
+ return applyTrustedMaterialRecipe(
+ id as MaterialRecipeId,
+ overrides as MaterialRecipeOverridesV1 | undefined,
+ { cache },
+ );
+ },
+ });
+}
+
+export const DEFAULT_TEXTURE_RESOLVER: TextureResolver = createTextureResolver();
diff --git a/src/textures.ts b/src/textures.ts
index 2f9350c3..b6717e76 100644
--- a/src/textures.ts
+++ b/src/textures.ts
@@ -54,7 +54,7 @@ export interface KilnTextureMetadata {
* by the GLB bridge so we don't re-encode PNG on every export.
*
* @example
- * const wood = await loadTexture('./textures/oak-albedo.png');
+ * const wood = await loadTexture(hostSuppliedPngBytes, { usage: 'albedo', name: 'Oak' });
* const barrel = new THREE.Mesh(unwrapped, pbrMaterial({ albedo: wood }));
*/
export async function loadTexture(
@@ -210,7 +210,11 @@ function requireTextureUsage(texture: THREE.Texture, usage: TextureUsage): void
* Maps to MeshStandardMaterial and exports as glTF pbrMetallicRoughness.
*
* @example
- * const wood = await loadTexture('./textures/oak-albedo.png');
+ * const wood = proceduralTexture({
+ * schemaVersion: 2,
+ * usage: 'albedo',
+ * layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, seed: 4 }],
+ * });
* const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });
*/
export function pbrMaterial(opts: PbrMaterialOptions = {}): THREE.MeshStandardMaterial {
diff --git a/src/tools/__tests__/registry-derivative-views.test.ts b/src/tools/__tests__/registry-derivative-views.test.ts
new file mode 100644
index 00000000..079a07ba
--- /dev/null
+++ b/src/tools/__tests__/registry-derivative-views.test.ts
@@ -0,0 +1,191 @@
+import { createHash } from 'node:crypto';
+import { describe, expect, spyOn, test } from 'bun:test';
+
+import * as renderModule from '../../render';
+import type { PbrRenderPort, PbrRenderRequest } from '../../composer/render-port';
+import { encodePng } from '../../views';
+import {
+ createKilnInspectDef,
+ createKilnScreenshotAnimationDef,
+ createKilnViewInteriorDef,
+ type KilnInspectResult,
+ type KilnScreenshotAnimationResult,
+ type KilnViewInteriorResult,
+} from '../registry';
+
+const ANIMATED = `
+const meta = { name: 'once', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ const pivot = createPivot('Arm', [0, 0, 0], root);
+ createPart('Blade', boxGeo(1, 1, 1), gameMaterial('#888888'), { parent: pivot });
+ return root;
+}
+function animate() {
+ return [createClip('move', 1, [rotationTrack('Arm', [
+ { time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [0, 90, 0] }
+ ])])];
+}`;
+
+const BUILDING = `
+const meta = { name: 'hut', category: 'architecture' };
+function build() {
+ const root = createRoot('Hut');
+ const mat = gameMaterial('#caa472');
+ room('Shell', mat, { width: 4, depth: 4, height: 2.8, parent: root });
+ const roof = createRoofPlanes('Roof', mat, { width: 4, depth: 4, height: 1.2, parent: root });
+ roof.root.position.set(0, 2.8, 0);
+ return root;
+}`;
+
+function solidPng(size: number): Uint8Array {
+ const rgb = new Uint8Array(size * size * 3);
+ rgb.fill(96);
+ return new Uint8Array(encodePng(rgb, size, size));
+}
+
+describe('derivative review surfaces', () => {
+ test('animation executes source once and binds every GPU frame receipt to its derivative GLB', async () => {
+ const requests: PbrRenderRequest[] = [];
+ const port: PbrRenderPort = async (request) => {
+ requests.push(request);
+ const inputGlbSha256 =
+ `sha256:${createHash('sha256').update(request.glb).digest('hex')}` as const;
+ return {
+ ok: true,
+ rendererId: 'gpu:derivative-test',
+ viewsPng: [solidPng(request.size!)],
+ derivativeFidelity: { materialFaithful: true, inputGlbSha256 },
+ };
+ };
+ const execute = spyOn(renderModule, 'executeKilnCode');
+ try {
+ const result = (await createKilnScreenshotAnimationDef({ viewRenderPort: port }).run({
+ code: ANIMATED,
+ clip: 'move',
+ })) as KilnScreenshotAnimationResult;
+ expect(result.ok).toBe(true);
+ expect(execute).toHaveBeenCalledTimes(1);
+ expect(requests).toHaveLength(6);
+ expect(result.viewFidelity).toMatchObject({
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: false,
+ degraded: false,
+ });
+ expect(result.viewFidelity?.receipts).toHaveLength(6);
+ for (let index = 0; index < requests.length; index++) {
+ const receipt = result.viewFidelity!.receipts[index]!;
+ expect(receipt.exactArtifact).toBe(false);
+ expect(receipt.derivativeLabel).toMatch(/%$/);
+ expect(receipt.inputGlbSha256).toBe(
+ `sha256:${createHash('sha256').update(requests[index]!.glb).digest('hex')}`,
+ );
+ }
+ } finally {
+ execute.mockRestore();
+ }
+ });
+
+ test('GPU failure uses GLB-native geometry-flat frames with stable reasons', async () => {
+ const execute = spyOn(renderModule, 'executeKilnCode');
+ try {
+ const result = (await createKilnScreenshotAnimationDef({
+ viewRenderPort: async () => ({ ok: false, rendererId: 'gpu:test', error: 'offline' }),
+ }).run({ code: ANIMATED, clip: 'move' })) as KilnScreenshotAnimationResult;
+ expect(result.ok).toBe(true);
+ expect(execute).toHaveBeenCalledTimes(1);
+ expect(result.viewFidelity).toMatchObject({
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ exactArtifact: false,
+ degraded: true,
+ reasonCodes: ['FULL_MATERIAL_RENDER_UNAVAILABLE'],
+ });
+ expect(
+ result.viewFidelity?.receipts.every((receipt) => receipt.degradeReason === 'offline'),
+ ).toBe(true);
+ } finally {
+ execute.mockRestore();
+ }
+ });
+
+ test('interior cutaway produces one derivative receipt per displayed cell', async () => {
+ const requests: PbrRenderRequest[] = [];
+ const result = (await createKilnViewInteriorDef({
+ viewRenderPort: async (request) => {
+ requests.push(request);
+ return {
+ ok: true,
+ rendererId: 'gpu:interior',
+ viewsPng: [solidPng(request.size!)],
+ derivativeFidelity: {
+ materialFaithful: true,
+ inputGlbSha256: `sha256:${createHash('sha256').update(request.glb).digest('hex')}`,
+ },
+ };
+ },
+ }).run({ code: BUILDING })) as KilnViewInteriorResult;
+ expect(result.ok).toBe(true);
+ expect(requests).toHaveLength(3);
+ expect(result.viewFidelity?.receipts.map((receipt) => receipt.derivativeLabel)).toEqual([
+ 'Floor plan',
+ 'Dollhouse',
+ 'Eye-level',
+ ]);
+ expect(result.viewFidelity?.exactArtifact).toBe(false);
+ });
+
+ test('contextual part inspect declines dishonest GPU auto-framing and reports the reason', async () => {
+ let portCalls = 0;
+ const result = (await createKilnInspectDef({
+ viewRenderPort: async () => {
+ portCalls++;
+ return { ok: true, rendererId: 'gpu:inspect', viewsPng: [solidPng(512)] };
+ },
+ }).run({ code: ANIMATED, part: 'Blade' })) as KilnInspectResult;
+ expect(result.ok).toBe(true);
+ expect(portCalls).toBe(0);
+ expect(result.viewFidelity).toMatchObject({
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ exactArtifact: false,
+ reasonCodes: ['FULL_MATERIAL_RENDER_UNAVAILABLE', 'DERIVATIVE_GPU_FRAMING_UNSUPPORTED'],
+ });
+ });
+
+ test('a later degraded request exposes current failure while retaining only a hash reference', async () => {
+ let succeed = true;
+ const def = createKilnInspectDef({
+ viewRenderPort: async (request) => {
+ if (!succeed) return { ok: false, rendererId: 'gpu:inspect', error: 'device lost' };
+ return {
+ ok: true,
+ rendererId: 'gpu:inspect',
+ viewsPng: [solidPng(request.size!)],
+ derivativeFidelity: {
+ materialFaithful: true,
+ inputGlbSha256: `sha256:${createHash('sha256').update(request.glb).digest('hex')}`,
+ },
+ };
+ },
+ });
+ const first = (await def.run({ code: ANIMATED, isolate: true })) as KilnInspectResult;
+ succeed = false;
+ const second = (await def.run({ code: ANIMATED, isolate: true })) as KilnInspectResult;
+
+ expect(first.viewEvidence?.current.materialFaithful).toBe(true);
+ expect(second.viewEvidence?.current).toMatchObject({
+ sequence: 2,
+ materialFaithful: false,
+ delivered: 'geometry-flat',
+ degraded: true,
+ });
+ expect(second.viewEvidence?.lastFaithful).toMatchObject({
+ sequence: 1,
+ materialFaithful: true,
+ inputGlbSha256: first.viewEvidence?.current.inputGlbSha256,
+ });
+ expect(JSON.stringify(second.viewEvidence)).not.toContain('png');
+ });
+});
diff --git a/src/tools/__tests__/registry-render-views-port.test.ts b/src/tools/__tests__/registry-render-views-port.test.ts
index 17ae7aa1..e31317a8 100644
--- a/src/tools/__tests__/registry-render-views-port.test.ts
+++ b/src/tools/__tests__/registry-render-views-port.test.ts
@@ -36,27 +36,18 @@ function build() {
}
`;
-// A real, QA-decodable DataTexture (8-bit RGBA, srgb) — an empty `new
-// THREE.Texture()` has no pixel payload and gets blocked by
-// MAT_TEXTURE_DECODE_FAILED before routing is ever reached.
+// A real, QA-decodable approved procedural texture. Generated source may not
+// construct raw THREE.DataTexture instances at the evaluator boundary.
const TEXTURED_CODE = `
const meta = { name: 'textured-box', category: 'prop' };
function build() {
const root = createRoot('Root');
- const mat = gameMaterial('#ffffff');
- const size = 8;
- const data = new Uint8Array(size * size * 4);
- for (let i = 0; i < size * size; i++) {
- data[i * 4] = 200;
- data[i * 4 + 1] = 100;
- data[i * 4 + 2] = 50;
- data[i * 4 + 3] = 255;
- }
- const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat, THREE.UnsignedByteType);
- tex.needsUpdate = true;
- tex.colorSpace = THREE.SRGBColorSpace;
- mat.map = tex;
- createPart('Body', boxGeo(1, 1, 1), mat, { parent: root });
+ const albedo = proceduralTexture({
+ size: 8,
+ name: 'RoutingFixture',
+ layers: [{ op: 'checker', colorA: 0xc86432, colorB: 0x643219, squares: 2 }],
+ });
+ createPart('Body', boxGeo(1, 1, 1), pbrMaterial({ albedo }), { parent: root });
return root;
}
`;
@@ -94,6 +85,16 @@ describe('kiln_render in-loop GPU port routing', () => {
expect(events[0]!.renderer).toMatch(/^cpu-raster:/);
expect(events[0]!.degraded).toBe(false);
expect(events[0]!.neededPbr).toBe(false);
+ expect(out.viewFidelity).toMatchObject({
+ version: 'kiln.view-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ exactArtifact: false,
+ rendererId: CPU_RASTER_RENDERER_ID,
+ degraded: false,
+ });
+ expect(out.viewFidelity?.inputGlbSha256).toMatch(/^sha256:[0-9a-f]{64}$/);
});
test('port injected + untextured metalness-0 scene: port is never called, CPU still draws', async () => {
@@ -143,6 +144,15 @@ describe('kiln_render in-loop GPU port routing', () => {
expect(events[0]!.renderer).toBe('dawn-vulkan:test-gpu:1.0');
expect(events[0]!.degraded).toBe(false);
expect(events[0]!.neededPbr).toBe(true);
+ expect(out.viewFidelity).toMatchObject({
+ version: 'kiln.view-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: false,
+ rendererId: 'dawn-vulkan:test-gpu:1.0',
+ degraded: false,
+ });
});
test('port injected + untextured metalness>0 scene: port IS called (the metal case)', async () => {
@@ -178,6 +188,27 @@ describe('kiln_render in-loop GPU port routing', () => {
expect(events[0]!.degraded).toBe(true);
expect(events[0]!.degradedReason).toContain('device lost');
expect(events[0]!.neededPbr).toBe(true);
+ expect(out.viewFidelity).toMatchObject({
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ rendererId: CPU_RASTER_RENDERER_ID,
+ degraded: true,
+ });
+ expect(out.viewFidelity?.degradeReason).toContain('device lost');
+ });
+
+ test('no port + textured scene returns explicit model-visible geometry-only fidelity', async () => {
+ const def = createKilnRenderViewsDef();
+ const out = (await def.run({ code: TEXTURED_CODE })) as KilnRenderViewsResult;
+
+ expect(out.ok).toBe(true);
+ expect(out.viewFidelity).toMatchObject({
+ requested: 'full-preferred',
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ degraded: true,
+ degradeReason: 'material-faithful view render port unavailable',
+ });
});
test('port throws: falls back to CPU, no throw escapes the tool', async () => {
@@ -213,6 +244,28 @@ describe('kiln_render in-loop GPU port routing', () => {
expect(events[0]!.degradedReason).toContain('timed out after 25ms');
});
+ test('samples warm-up and remaining budget for each in-loop request', async () => {
+ const requests: string[] = [];
+ const def = createKilnRenderViewsDef({
+ viewRenderPort: () => new Promise(() => {}),
+ viewRenderTimeoutMs: 25,
+ viewRenderTimeoutContext: () => ({
+ warmUpState: 'ready',
+ remainingGenerationBudgetMs: 13,
+ rendererDeadlineMs: 20,
+ }),
+ viewRenderTimeoutResolver: (context) => {
+ requests.push(context.requestKind);
+ return 19;
+ },
+ });
+ const out = (await def.run({ code: TEXTURED_CODE })) as KilnRenderViewsResult;
+
+ expect(out.ok).toBe(true);
+ expect(out.viewFidelity?.degradeReason).toContain('timed out after 13ms');
+ expect(requests).toEqual(['in-loop-grid']);
+ });
+
test('an onViewsRendered callback that throws does not fail the render', async () => {
const context: KilnToolContext = {
onViewsRendered: () => {
diff --git a/src/tools/__tests__/registry-render-views.test.ts b/src/tools/__tests__/registry-render-views.test.ts
index bb4e22ef..4d9410ca 100644
--- a/src/tools/__tests__/registry-render-views.test.ts
+++ b/src/tools/__tests__/registry-render-views.test.ts
@@ -35,6 +35,8 @@ describe('kilnRenderViewsDef (unified kiln_render)', () => {
expect(kilnRenderViewsDef.description).toContain('GPU PBR shading');
expect(kilnRenderViewsDef.description).toContain('textured or metallic materials');
expect(kilnRenderViewsDef.description).toContain('flat-shaded CPU render');
+ expect(kilnRenderViewsDef.description).toContain('viewFidelity');
+ expect(kilnRenderViewsDef.description).toContain('do not judge material');
});
test('valid code returns metrics AND the six-view grid PNG from one execution', async () => {
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 6e0c8d13..80bf1428 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -25,10 +25,23 @@ import { executeKilnCode, inspectSceneStructure, renderSceneToGLB } from '../ren
import { listPrimitives, type PrimitiveSpec } from '../list-primitives';
import type { AssetCategory, AssetIntentV1 } from '../contracts';
import type { AssetQaReportV1 } from '../qa';
-import type { PbrRenderPort } from '../composer/render-port';
+import type {
+ DerivativeReviewFidelityV1,
+ DerivativeViewReceiptV1,
+ PbrRenderPort,
+ ViewFidelityReasonCode,
+ ViewFidelityV1,
+ ViewEvidenceHistoryV1,
+} from '../composer/render-port';
import type { ViewGridResult } from '../views';
import { sceneNeedsPbrShading } from '../material-resources';
import type { GenerationCallBudget } from '../agent/call-budget';
+import {
+ resolveViewRenderTimeoutMs,
+ type ViewRenderTimeoutContextProvider,
+ type ViewRenderTimeoutResolver,
+} from '../agent/view-render-timeout';
+import { ViewEvidenceHistoryStore } from '../views/evidence-history';
// =============================================================================
// Tool definition contract
@@ -89,6 +102,10 @@ export interface KilnToolContext {
* {@link DEFAULT_INLOOP_VIEW_RENDER_TIMEOUT_MS}.
*/
viewRenderTimeoutMs?: number;
+ /** Dynamic host state sampled immediately before every port call. */
+ viewRenderTimeoutContext?: ViewRenderTimeoutContextProvider;
+ /** Host policy for deriving one deadline from warm-up/budget state. */
+ viewRenderTimeoutResolver?: ViewRenderTimeoutResolver;
/**
* Host tally hook, called once per in-loop grid with whoever actually drew it.
*
@@ -113,6 +130,8 @@ export interface KilnToolContext {
renderObservationPort?: RenderObservationPort;
/** Shared generation-global allowance, forwarded to the host observer port. */
generationCallBudget?: GenerationCallBudget;
+ /** Shared bounded hash-only evidence ledger for one agent/tool session. */
+ viewEvidenceHistory?: ViewEvidenceHistoryStore;
}
/** JSON-safe value accepted from a host visual observer. */
@@ -165,10 +184,178 @@ export interface InLoopViewRender {
*/
export const DEFAULT_INLOOP_VIEW_RENDER_TIMEOUT_MS = 6000;
+function resolveInLoopViewRenderTimeoutMs(
+ context: KilnToolContext,
+ requestKind: 'in-loop-grid' | 'derivative-cell',
+): number {
+ return resolveViewRenderTimeoutMs({
+ requestKind,
+ defaultTimeoutMs: DEFAULT_INLOOP_VIEW_RENDER_TIMEOUT_MS,
+ ...(context.viewRenderTimeoutMs !== undefined
+ ? { timeoutMs: context.viewRenderTimeoutMs }
+ : {}),
+ ...(context.viewRenderTimeoutContext
+ ? { contextProvider: context.viewRenderTimeoutContext }
+ : {}),
+ ...(context.viewRenderTimeoutResolver ? { resolver: context.viewRenderTimeoutResolver } : {}),
+ });
+}
+
function trustedCategory(context: KilnToolContext): AssetCategory | undefined {
return context.intent?.category ?? context.category;
}
+const viewEvidenceHistoryByContext = new WeakMap<KilnToolContext, ViewEvidenceHistoryStore>();
+const VIEW_EVIDENCE_GUIDANCE =
+ ' viewEvidence.current describes ONLY this request. lastFaithful is older hash-only evidence for reference, not reused pixels and not current verification.';
+
+function withViewEvidenceHistory(context: KilnToolContext): KilnToolContext {
+ if (context.viewEvidenceHistory) return context;
+ let history = viewEvidenceHistoryByContext.get(context);
+ if (!history) {
+ history = new ViewEvidenceHistoryStore();
+ viewEvidenceHistoryByContext.set(context, history);
+ }
+ return { ...context, viewEvidenceHistory: history };
+}
+
+async function sha256Glb(bytes: Uint8Array): Promise<`sha256:${string}`> {
+ const digest = new Uint8Array(
+ await globalThis.crypto.subtle.digest('SHA-256', Uint8Array.from(bytes)),
+ );
+ return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
+}
+
+/** Render one purpose-built review GLB. Generated source has already executed;
+ * both GPU and geometry-flat fallback consume only the serialized derivative. */
+async function renderDerivativeCell(
+ input: import('../views').DerivativeCellRenderInput,
+ context: KilnToolContext,
+): Promise<import('../views').DerivativeCellRenderResult> {
+ const rendered = await renderSceneToGLB(input.root as THREE.Object3D, {
+ ...(trustedCategory(context) ? { category: trustedCategory(context) } : {}),
+ ...(context.intent ? { intent: context.intent } : {}),
+ });
+ const derivativeGlb = Uint8Array.from(rendered.bytes);
+ const inputGlbSha256 = await sha256Glb(derivativeGlb);
+ let degradeReason: string | undefined;
+ const derivativeReasonCodes: ViewFidelityReasonCode[] = [];
+
+ if (context.viewRenderPort && !input.gpuUnsupportedReasonCode) {
+ const { captureViewPngsViaPort } = await import('../agent/generate');
+ const ported = await captureViewPngsViaPort(
+ context.viewRenderPort,
+ derivativeGlb,
+ resolveInLoopViewRenderTimeoutMs(context, 'derivative-cell'),
+ [input.view.dir],
+ input.size,
+ );
+ if (ported.ok && ported.derivativeFidelityAttested) {
+ if (ported.inputGlbSha256 !== inputGlbSha256) {
+ throw new Error(
+ `validated derivative receipt hash mismatch (${ported.inputGlbSha256} != ${inputGlbSha256})`,
+ );
+ }
+ const receipt: DerivativeViewReceiptV1 = {
+ version: 'kiln.view-fidelity.v1',
+ derivativeLabel: input.label,
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: false,
+ rendererId: ported.rendererId,
+ inputGlbSha256,
+ degraded: false,
+ };
+ try {
+ context.onViewsRendered?.({
+ renderer: ported.rendererId,
+ degraded: false,
+ neededPbr: true,
+ });
+ } catch {
+ /* best effort */
+ }
+ return { png: Buffer.from(ported.pngs[0]!), receipt };
+ }
+ if (ported.ok) {
+ degradeReason = 'view render port returned no derivative material/hash receipt';
+ derivativeReasonCodes.push('DERIVATIVE_RECEIPT_UNAVAILABLE');
+ } else {
+ degradeReason = ported.reason;
+ if (ported.reason.includes('derivative receipt hash mismatch')) {
+ derivativeReasonCodes.push('DERIVATIVE_RECEIPT_INVALID');
+ }
+ }
+ } else if (input.gpuUnsupportedReasonCode) {
+ degradeReason = 'GPU auto-framing cannot preserve the requested derivative focus bounds';
+ } else {
+ degradeReason = 'material-faithful view render port unavailable';
+ }
+
+ const { renderGlbViewCell, CPU_RASTER_RENDERER_ID } = await import('../views');
+ const flat = await renderGlbViewCell(derivativeGlb, input.view, {
+ size: input.size,
+ ...(input.backfaceCull !== undefined ? { backfaceCull: input.backfaceCull } : {}),
+ ...(input.frameBounds ? { frameBounds: input.frameBounds } : {}),
+ });
+ if (flat.inputGlbSha256 !== inputGlbSha256) {
+ throw new Error(
+ `derivative GLB fallback hash mismatch (${flat.inputGlbSha256} != ${inputGlbSha256})`,
+ );
+ }
+ const reasonCodes = [
+ 'FULL_MATERIAL_RENDER_UNAVAILABLE',
+ ...(input.gpuUnsupportedReasonCode ? [input.gpuUnsupportedReasonCode] : []),
+ ...derivativeReasonCodes,
+ ...flat.reasonCodes,
+ ] as ViewFidelityReasonCode[];
+ const receipt: DerivativeViewReceiptV1 = {
+ version: 'kiln.view-fidelity.v1',
+ derivativeLabel: input.label,
+ requested: 'full-preferred',
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ exactArtifact: false,
+ rendererId: CPU_RASTER_RENDERER_ID,
+ inputGlbSha256,
+ degraded: true,
+ degradeReason,
+ reasonCodes,
+ };
+ try {
+ context.onViewsRendered?.({
+ renderer: CPU_RASTER_RENDERER_ID,
+ degraded: true,
+ degradedReason: degradeReason,
+ neededPbr: true,
+ });
+ } catch {
+ /* best effort */
+ }
+ return { png: flat.png, receipt };
+}
+
+function derivativeReviewFidelity(
+ receipts: DerivativeViewReceiptV1[] | undefined,
+): DerivativeReviewFidelityV1 | undefined {
+ if (!receipts?.length) return undefined;
+ const materialFaithful = receipts.every((receipt) => receipt.materialFaithful);
+ const reasonCodes = [
+ ...new Set(receipts.flatMap((receipt) => receipt.reasonCodes ?? [])),
+ ] as ViewFidelityReasonCode[];
+ return {
+ version: 'kiln.derivative-review-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: materialFaithful ? 'full-material' : 'geometry-flat',
+ materialFaithful,
+ exactArtifact: false,
+ degraded: receipts.some((receipt) => receipt.degraded),
+ receipts,
+ ...(reasonCodes.length ? { reasonCodes } : {}),
+ };
+}
+
// =============================================================================
// Schemas
// =============================================================================
@@ -542,6 +729,9 @@ export interface KilnRenderViewsResult {
gridHeight?: number;
/** The 3x2 grid PNG, base64-encoded (transports with image support strip this and attach the bytes). */
pngBase64?: string;
+ /** Truthful material fidelity delivered by this render, visible to the model. */
+ viewFidelity?: ViewFidelityV1;
+ viewEvidence?: ViewEvidenceHistoryV1;
warnings: string[];
error?: string;
}
@@ -586,9 +776,10 @@ async function runRenderViews(
// so sending it costs a round trip and a warm GPU to draw a picture the CPU
// already draws correctly. `renderSceneToGLB` above ALREADY produced the
// bytes the port needs — this reuses them rather than paying a second bake.
- const neededPbr = context.viewRenderPort ? sceneNeedsPbrShading(root) : false;
+ const neededPbr = sceneNeedsPbrShading(root);
let grid: ViewGridResult | undefined;
let drawnBy: InLoopViewRender | undefined;
+ let materialFaithful = false;
if (context.viewRenderPort && neededPbr) {
// Lazy import: `../agent/generate` sits upstream of this module in the
@@ -600,7 +791,7 @@ async function runRenderViews(
const ported = await captureViewsViaPort(
context.viewRenderPort,
rendered.bytes,
- context.viewRenderTimeoutMs ?? DEFAULT_INLOOP_VIEW_RENDER_TIMEOUT_MS,
+ resolveInLoopViewRenderTimeoutMs(context, 'in-loop-grid'),
input.capture,
);
if (ported.ok) {
@@ -615,6 +806,7 @@ async function runRenderViews(
height: ported.height,
capture: ported.capture,
};
+ materialFaithful = true;
drawnBy = { renderer: ported.rendererId, degraded: false, neededPbr };
} else {
drawnBy = {
@@ -632,7 +824,38 @@ async function runRenderViews(
if (!grid) {
grid = await renderViewGrid(root, input.capture ? { capture: input.capture } : {});
}
- drawnBy ??= { renderer: CPU_RASTER_RENDERER_ID, degraded: false, neededPbr };
+ drawnBy ??= context.viewRenderPort
+ ? { renderer: CPU_RASTER_RENDERER_ID, degraded: false, neededPbr }
+ : {
+ renderer: CPU_RASTER_RENDERER_ID,
+ degraded: neededPbr,
+ ...(neededPbr
+ ? { degradedReason: 'material-faithful view render port unavailable' }
+ : {}),
+ neededPbr,
+ };
+
+ // Copy into an ArrayBuffer-backed view: render bytes are typed as
+ // `Uint8Array<ArrayBufferLike>`, while Web Crypto deliberately rejects a
+ // possible SharedArrayBuffer at its boundary.
+ const hashInput = new Uint8Array(rendered.bytes.byteLength);
+ hashInput.set(rendered.bytes);
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', hashInput));
+ const inputGlbSha256 = `sha256:${[...digest]
+ .map((byte) => byte.toString(16).padStart(2, '0'))
+ .join('')}` as const;
+ const viewFidelity: ViewFidelityV1 = {
+ version: 'kiln.view-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: materialFaithful ? 'full-material' : 'geometry-flat',
+ materialFaithful,
+ exactArtifact: false,
+ rendererId: drawnBy.renderer,
+ inputGlbSha256,
+ degraded: drawnBy.degraded,
+ ...(drawnBy.degradedReason ? { degradeReason: drawnBy.degradedReason } : {}),
+ };
+ const viewEvidence = context.viewEvidenceHistory?.record('kiln_render', viewFidelity);
// A host bookkeeping hook must never be able to fail a render the model is
// waiting on.
@@ -664,6 +887,8 @@ async function runRenderViews(
gridWidth: grid.width,
gridHeight: grid.height,
pngBase64: grid.png.toString('base64'),
+ viewFidelity,
+ ...(viewEvidence ? { viewEvidence } : {}),
warnings,
qaReport: rendered.qaReport,
};
@@ -696,15 +921,17 @@ const KILN_RENDER_VIEWS_DESCRIPTION =
'elevation 0 = eye level, positive looks down. Use it to aim every cell at what actually needs ' +
'checking — a seam, an underside, a joint the standard six leave occluded — instead of spending ' +
'cells on angles that show nothing. Max 9 cells. The reply echoes the grid shape it rendered. ' +
- 'If the build fails you get an error and NO image — fix the code and render again. Uses GPU PBR shading when the scene has textured or metallic materials and the renderer is reachable; otherwise uses a flat-shaded CPU render. Writes no files.';
+ 'If the build fails you get an error and NO image — fix the code and render again. Uses GPU PBR shading when the scene has textured or metallic materials and the renderer is reachable; otherwise uses a flat-shaded CPU render. Always read viewFidelity: when materialFaithful is false, use the image for geometry and silhouette only; do not judge material color, textures, normal relief, roughness, metalness, AO, or emissive response from it. Writes no files.' +
+ VIEW_EVIDENCE_GUIDANCE;
/** Create the unified render/view definition with host-owned QA context. */
export function createKilnRenderViewsDef(context: KilnToolContext = {}): KilnToolDef {
+ const statefulContext = withViewEvidenceHistory(context);
return {
name: 'kiln_render',
description: KILN_RENDER_VIEWS_DESCRIPTION,
inputSchema: renderViewsInput,
- run: async (input) => runRenderViews(renderViewsInput.parse(input), context),
+ run: async (input) => runRenderViews(renderViewsInput.parse(input), statefulContext),
media: screenshotMedia,
};
}
@@ -733,6 +960,9 @@ export interface KilnScreenshotAnimationResult {
pngBase64?: string;
/** Per-frame PNGs, base64 (perFrame mode; image transports attach each separately). */
framesBase64?: string[];
+ /** Material fidelity and SHA-256 receipt for every posed derivative GLB. */
+ viewFidelity?: DerivativeReviewFidelityV1;
+ viewEvidence?: ViewEvidenceHistoryV1;
/** Clip names available in the scene (set when the requested clip wasn't found). */
availableClips?: string[];
warnings: string[];
@@ -759,6 +989,7 @@ async function runScreenshotAnimation(
clip: input.clip,
...(input.camera ? { camera: input.camera } : {}),
...(input.perFrame ? { perFrame: true } : {}),
+ renderDerivativeCell: (cell) => renderDerivativeCell(cell, context),
});
if (!r.ok) {
return {
@@ -770,6 +1001,10 @@ async function runScreenshotAnimation(
...(r.availableClips ? { availableClips: r.availableClips } : {}),
};
}
+ const viewFidelity = derivativeReviewFidelity(r.derivativeReceipts);
+ const viewEvidence = viewFidelity
+ ? context.viewEvidenceHistory?.record('kiln_screenshot_animation', viewFidelity)
+ : undefined;
const base: KilnScreenshotAnimationResult = {
ok: true,
frames: r.frames,
@@ -781,6 +1016,8 @@ async function runScreenshotAnimation(
...(r.unresolvedTracks ? { unresolvedTracks: r.unresolvedTracks } : {}),
...(r.width ? { width: r.width } : {}),
...(r.height ? { height: r.height } : {}),
+ ...(viewFidelity ? { viewFidelity } : {}),
+ ...(viewEvidence ? { viewEvidence } : {}),
};
if (r.pngs) return { ...base, framesBase64: r.pngs.map((p) => p.toString('base64')) };
return { ...base, pngBase64: r.png!.toString('base64') };
@@ -834,15 +1071,19 @@ const KILN_SCREENSHOT_ANIMATION_DESCRIPTION =
'swing. args: clip (required, the clip name), camera (default right; also front/back/left/top/' +
'three-quarter), perFrame (optional, separate high-res frames). If unresolvedTracks comes back ' +
'non-empty the clip targets joints that do not exist (a name mismatch) and looks frozen — fix the ' +
- 'track names. Flat-shaded CPU render; writes no files.';
+ 'track names. Each frame is rendered from deterministic posed GLB bytes: GPU PBR when available, ' +
+ 'otherwise a GLB-native geometry-flat fallback. Read viewFidelity before judging materials; writes no files.' +
+ VIEW_EVIDENCE_GUIDANCE;
/** Create an animation-view definition with host-owned QA context. */
export function createKilnScreenshotAnimationDef(context: KilnToolContext = {}): KilnToolDef {
+ const statefulContext = withViewEvidenceHistory(context);
return {
name: 'kiln_screenshot_animation',
description: KILN_SCREENSHOT_ANIMATION_DESCRIPTION,
inputSchema: screenshotAnimationInput,
- run: async (input) => runScreenshotAnimation(screenshotAnimationInput.parse(input), context),
+ run: async (input) =>
+ runScreenshotAnimation(screenshotAnimationInput.parse(input), statefulContext),
media: screenshotAnimationMedia,
mediaMulti: screenshotAnimationMediaMulti,
};
@@ -867,6 +1108,9 @@ export interface KilnViewInteriorResult {
wallsHidden?: number;
/** The single-row grid PNG, base64 (image transports strip this and attach the bytes). */
pngBase64?: string;
+ /** Material fidelity and SHA-256 receipt for every cutaway derivative GLB. */
+ viewFidelity?: DerivativeReviewFidelityV1;
+ viewEvidence?: ViewEvidenceHistoryV1;
warnings: string[];
error?: string;
}
@@ -894,7 +1138,10 @@ async function runViewInterior(
// falls back to historical "Roof" naming) — so a correctly-roled roof named
// anything at all still lifts.
const nodeName = input.nodeName?.trim() ? input.nodeName : undefined;
- const grid = await renderInteriorGrid(root, { ...(nodeName ? { nodeName } : {}) });
+ const grid = await renderInteriorGrid(root, {
+ ...(nodeName ? { nodeName } : {}),
+ renderDerivativeCell: (cell) => renderDerivativeCell(cell, context),
+ });
const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });
if (grid.roofsHidden === 0) {
warnings.push(
@@ -903,6 +1150,10 @@ async function runViewInterior(
: 'No roof was found, so nothing could be lifted and the interior is still occluded. Build the roof with createRoofPlanes/createGableRoof (which tag it as a roof), or name the roof group "Roof".',
);
}
+ const viewFidelity = derivativeReviewFidelity(grid.derivativeReceipts);
+ const viewEvidence = viewFidelity
+ ? context.viewEvidenceHistory?.record('kiln_view_interior', viewFidelity)
+ : undefined;
return {
ok: true,
views: grid.views,
@@ -911,6 +1162,8 @@ async function runViewInterior(
roofsHidden: grid.roofsHidden,
wallsHidden: grid.wallsHidden,
pngBase64: grid.png.toString('base64'),
+ ...(viewFidelity ? { viewFidelity } : {}),
+ ...(viewEvidence ? { viewEvidence } : {}),
warnings,
};
} catch (err) {
@@ -937,15 +1190,19 @@ const KILN_VIEW_INTERIOR_DESCRIPTION =
'Call this before finalizing any building. Take no argument: the roof is found from its semantic ' +
'role, so any roof built with createRoofPlanes/createGableRoof lifts whatever it is named. If ' +
'roofsHidden comes back 0 no roof was resolvable and the interior stays hidden — build the roof ' +
- 'with a roof primitive (or name the group "Roof"). Flat-shaded CPU render; writes no files.';
+ 'with a roof primitive (or name the group "Roof"). Each cell is rendered from deterministic cutaway ' +
+ 'GLB bytes: GPU PBR when available, otherwise a GLB-native geometry-flat fallback. Read viewFidelity ' +
+ 'before judging materials; writes no files.' +
+ VIEW_EVIDENCE_GUIDANCE;
/** Create the interior-view definition with host-owned QA context. */
export function createKilnViewInteriorDef(context: KilnToolContext = {}): KilnToolDef {
+ const statefulContext = withViewEvidenceHistory(context);
return {
name: 'kiln_view_interior',
description: KILN_VIEW_INTERIOR_DESCRIPTION,
inputSchema: viewInteriorInput,
- run: async (input) => runViewInterior(viewInteriorInput.parse(input), context),
+ run: async (input) => runViewInterior(viewInteriorInput.parse(input), statefulContext),
media: screenshotMedia,
};
}
@@ -1026,6 +1283,9 @@ export interface KilnInspectResult {
height?: number;
/** The close-up PNG, base64 (image transports strip this and attach the bytes). */
pngBase64?: string;
+ /** Fidelity and exact derivative-byte receipt for this close-up. */
+ viewFidelity?: DerivativeReviewFidelityV1;
+ viewEvidence?: ViewEvidenceHistoryV1;
/** Part names available for framing (set when the requested part was not found). */
availableParts?: string[];
error?: string;
@@ -1039,11 +1299,14 @@ export interface KilnInspectResult {
* the model can retry by name. The views module is imported lazily (node:zlib)
* to keep it out of the browser bundle graph.
*/
-async function runInspect(input: z.infer<typeof inspectInput>): Promise<KilnInspectResult> {
+async function runInspect(
+ input: z.infer<typeof inspectInput>,
+ context: KilnToolContext,
+): Promise<KilnInspectResult> {
try {
- const { renderInspectView } = await import('../views/inspect');
+ const { prepareInspectView } = await import('../views/inspect');
const { root } = await executeKilnCode(input.code);
- const r = renderInspectView(root, {
+ const r = prepareInspectView(root, {
...(input.part !== undefined ? { part: input.part } : {}),
...(input.view !== undefined ? { view: input.view } : {}),
...(input.azimuthDeg !== undefined ? { azimuthDeg: input.azimuthDeg } : {}),
@@ -1060,6 +1323,26 @@ async function runInspect(input: z.infer<typeof inspectInput>): Promise<KilnInsp
availableParts: r.availableParts,
};
}
+ const rendered = await renderDerivativeCell(
+ {
+ root: r.root,
+ label: r.part ? `inspect:${r.part}` : 'inspect:whole-asset',
+ view: r.viewSpec,
+ size: r.size,
+ frameBounds: r.frameBounds,
+ // The PBR port's direction mode auto-frames the complete GLB. That is
+ // truthful for a whole asset and for an isolated part derivative, but
+ // cannot preserve a part close-up while contextual geometry remains.
+ ...(!r.part || r.isolated
+ ? {}
+ : { gpuUnsupportedReasonCode: 'DERIVATIVE_GPU_FRAMING_UNSUPPORTED' as const }),
+ },
+ context,
+ );
+ const viewFidelity = derivativeReviewFidelity([rendered.receipt]);
+ const viewEvidence = viewFidelity
+ ? context.viewEvidenceHistory?.record('kiln_inspect', viewFidelity)
+ : undefined;
// Always state the angles, named camera or not, so the model can step from
// where it actually is instead of guessing the next view by name.
const from = `the ${r.view} view (azimuth ${r.azimuthDeg}deg, elevation ${r.elevationDeg}deg)`;
@@ -1078,9 +1361,11 @@ async function runInspect(input: z.infer<typeof inspectInput>): Promise<KilnInsp
zoom: r.zoom,
isolated: r.isolated,
framed,
- width: r.width,
- height: r.height,
- pngBase64: r.png.toString('base64'),
+ width: r.size,
+ height: r.size,
+ pngBase64: rendered.png.toString('base64'),
+ ...(viewFidelity ? { viewFidelity } : {}),
+ ...(viewEvidence ? { viewEvidence } : {}),
};
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
@@ -1110,16 +1395,19 @@ const KILN_INSPECT_DESCRIPTION =
'If the part name does not resolve you get the list of available part names back — pick one and ' +
'retry. By default surrounding geometry stays visible for context and can occlude the part: ' +
'either pick a different view, or set isolate:true to hide everything else and see the part ' +
- 'unobstructed (use it for anything buried inside or behind other geometry). Flat-shaded CPU ' +
- 'render; writes no files.';
+ 'unobstructed (use it for anything buried inside or behind other geometry). The view is rendered ' +
+ 'from deterministic derivative GLB bytes; GPU PBR is used only when it can preserve the requested ' +
+ 'framing, otherwise the GLB-native geometry-flat fallback reports why in viewFidelity. Writes no files.' +
+ VIEW_EVIDENCE_GUIDANCE;
/** Create the close-up inspection definition. */
-export function createKilnInspectDef(): KilnToolDef {
+export function createKilnInspectDef(context: KilnToolContext = {}): KilnToolDef {
+ const statefulContext = withViewEvidenceHistory(context);
return {
name: 'kiln_inspect',
description: KILN_INSPECT_DESCRIPTION,
inputSchema: inspectInput,
- run: async (input) => runInspect(inspectInput.parse(input)),
+ run: async (input) => runInspect(inspectInput.parse(input), statefulContext),
media: screenshotMedia,
};
}
diff --git a/src/validation.ts b/src/validation.ts
index 70760248..96725985 100644
--- a/src/validation.ts
+++ b/src/validation.ts
@@ -7,6 +7,7 @@
* - `value:` keyframe typos (regex, cheap)
* - Infinite loops (`while(true)`, `for(;;)` without break) — AST
* - Recursive `build()` calls that'd blow the stack — AST
+ * - Ambient-runtime, dynamic-code, and raw material-constructor access — AST
* - Triangle budget estimate — AST sum of geometry calls
* - Syntax errors — acorn throws with line numbers
*
@@ -263,6 +264,8 @@ export function validate(code: string, opts: { category?: string } = {}): Valida
// --- Structural checks --------------------------------------------------
+ issues.push(...analyzeGeneratedSourceSafety(ast));
+
const structure = analyzeTopLevel(ast);
if (!structure.hasMetaConst) {
@@ -347,10 +350,351 @@ export function validate(code: string, opts: { category?: string } = {}): Valida
// Backward-compat alias.
export const validateKilnCode = validate;
+/**
+ * Sanitized execution-boundary error. It intentionally carries a stable code
+ * and line only; generated source text and dynamic-import specifiers are never
+ * copied into the message.
+ */
+export class GeneratedSourcePolicyError extends Error {
+ readonly code: string;
+ readonly line?: number;
+
+ constructor(issue: ValidationIssue) {
+ super(
+ `Generated source rejected by policy (${issue.code})${issue.line ? ` at line ${issue.line}` : ''}.`,
+ );
+ this.name = 'GeneratedSourcePolicyError';
+ this.code = issue.code;
+ this.line = issue.line;
+ }
+}
+
+/** Defense-in-depth gate used immediately before the Function evaluator. */
+export function assertGeneratedSourceSafe(code: string): void {
+ let ast: acorn.Program;
+ try {
+ ast = acorn.parse(code, {
+ ecmaVersion: 2022,
+ sourceType: 'script',
+ allowReturnOutsideFunction: false,
+ locations: true,
+ });
+ } catch (error) {
+ const line =
+ error && typeof error === 'object' && 'loc' in error
+ ? (error as { loc?: { line?: number } }).loc?.line
+ : undefined;
+ throw new GeneratedSourcePolicyError({
+ code: 'SYNTAX_ERROR',
+ message: 'Generated source has invalid syntax.',
+ line,
+ });
+ }
+ const issue = analyzeGeneratedSourceSafety(ast)[0];
+ if (issue) throw new GeneratedSourcePolicyError(issue);
+}
+
// =============================================================================
// Internals
// =============================================================================
+const FORBIDDEN_AMBIENT_IDENTIFIERS = new Set([
+ 'globalThis',
+ 'global',
+ 'process',
+ 'fetch',
+ 'XMLHttpRequest',
+ 'WebSocket',
+ 'Function',
+ 'eval',
+ // Other common host-global aliases are denied for the same reason. This is
+ // a denylist safety net, not a claim that the evaluator is isolated.
+ 'window',
+ 'self',
+ 'document',
+ 'navigator',
+ 'location',
+ 'Bun',
+ 'Deno',
+ 'Reflect',
+ 'require',
+ 'module',
+]);
+
+const FORBIDDEN_THREE_CONSTRUCTORS = new Set([
+ 'DataTexture',
+ 'ShaderMaterial',
+ 'RawShaderMaterial',
+]);
+
+function issueKey(issue: ValidationIssue): string {
+ return `${issue.code}:${issue.line ?? 0}:${issue.message}`;
+}
+
+function analyzeGeneratedSourceSafety(ast: acorn.Program): ValidationIssue[] {
+ const issues: ValidationIssue[] = [];
+ const seen = new Set<string>();
+ const staticStrings = collectStaticStringBindings(ast);
+ const add = (issue: ValidationIssue): void => {
+ const key = issueKey(issue);
+ if (seen.has(key)) return;
+ seen.add(key);
+ issues.push(issue);
+ };
+ const ambient = (name: string, line?: number): void =>
+ add({
+ code: 'UNSAFE_GLOBAL_ACCESS',
+ message: `Generated code cannot access ambient capability \`${name}\`.`,
+ fixHint: 'Use only the documented sandbox globals and approved resource helpers.',
+ line,
+ });
+ const dynamicCode = (line?: number): void =>
+ add({
+ code: 'DYNAMIC_CODE_ACCESS',
+ message: 'Generated code cannot access constructor chains or dynamic-code constructors.',
+ fixHint: 'Call documented sandbox helpers directly; do not derive constructors at runtime.',
+ line,
+ });
+ const unsafeThree = (name: string, line?: number): void =>
+ add({
+ code: 'UNSAFE_THREE_CONSTRUCTOR',
+ message: `Generated code cannot access raw THREE constructor \`${name}\`.`,
+ fixHint:
+ 'Use approved texture loading, proceduralTexture, pbrMaterial, or materialRecipe instead.',
+ line,
+ });
+ const unsafeThreeNamespace = (
+ code: 'UNSAFE_THREE_ALIAS' | 'UNSAFE_THREE_COMPUTED_ACCESS',
+ line?: number,
+ ): void =>
+ add({
+ code,
+ message:
+ code === 'UNSAFE_THREE_ALIAS'
+ ? 'Generated code cannot alias the THREE namespace.'
+ : 'Generated code cannot use non-static computed access on the THREE namespace.',
+ fixHint: 'Use a documented direct THREE constructor or a sandbox material/texture helper.',
+ line,
+ });
+
+ walk.ancestor(ast, {
+ Identifier(node, _state, ancestors) {
+ const parent = ancestors.at(-2);
+ if (identifierIsNonReferenceKey(node, parent)) return;
+ if (FORBIDDEN_AMBIENT_IDENTIFIERS.has(node.name)) {
+ ambient(node.name, node.loc?.start.line);
+ }
+ },
+ ThisExpression(node) {
+ ambient('this', node.loc?.start.line);
+ },
+ ImportExpression(node) {
+ add({
+ code: 'DYNAMIC_IMPORT',
+ message: 'Generated code cannot use dynamic import.',
+ fixHint: 'Remove import(); all supported helpers are already sandbox globals.',
+ line: node.loc?.start.line,
+ });
+ },
+ MemberExpression(node) {
+ const property = staticPropertyName(node, staticStrings);
+ if (property === 'constructor') dynamicCode(node.loc?.start.line);
+ if (
+ property &&
+ FORBIDDEN_THREE_CONSTRUCTORS.has(property) &&
+ expressionReferencesThree(node.object)
+ ) {
+ unsafeThree(property, node.loc?.start.line);
+ }
+ if (node.computed && property === undefined && expressionReferencesThree(node.object)) {
+ unsafeThreeNamespace('UNSAFE_THREE_COMPUTED_ACCESS', node.loc?.start.line);
+ }
+ },
+ VariableDeclarator(node) {
+ if (node.id.type === 'Identifier' && expressionReferencesThree(node.init)) {
+ unsafeThreeNamespace('UNSAFE_THREE_ALIAS', node.loc?.start.line);
+ }
+ if (node.id.type !== 'ObjectPattern') return;
+ analyzeObjectPatternSafety(
+ node.id,
+ node.init?.type === 'Identifier' && node.init.name === 'THREE',
+ staticStrings,
+ dynamicCode,
+ unsafeThree,
+ );
+ },
+ AssignmentExpression(node) {
+ if (node.left.type === 'Identifier' && expressionReferencesThree(node.right)) {
+ unsafeThreeNamespace('UNSAFE_THREE_ALIAS', node.loc?.start.line);
+ }
+ if (node.left.type !== 'ObjectPattern') return;
+ analyzeObjectPatternSafety(
+ node.left,
+ node.right.type === 'Identifier' && node.right.name === 'THREE',
+ staticStrings,
+ dynamicCode,
+ unsafeThree,
+ );
+ },
+ CallExpression(node) {
+ if (node.callee.type !== 'MemberExpression' || node.callee.object.type !== 'Identifier') {
+ return;
+ }
+ const owner = node.callee.object.name;
+ const method = staticPropertyName(node.callee, staticStrings);
+ if (
+ !(
+ (owner === 'Reflect' && method === 'get') ||
+ (owner === 'Object' && method === 'getOwnPropertyDescriptor')
+ )
+ ) {
+ return;
+ }
+ const property = staticExpressionString(node.arguments[1], staticStrings);
+ if (property === 'constructor') dynamicCode(node.loc?.start.line);
+ if (
+ owner === 'Reflect' &&
+ property &&
+ FORBIDDEN_THREE_CONSTRUCTORS.has(property) &&
+ expressionReferencesThree(node.arguments[0])
+ ) {
+ unsafeThree(property, node.loc?.start.line);
+ }
+ },
+ });
+
+ return issues;
+}
+
+function expressionReferencesThree(node: unknown): boolean {
+ if (!node || typeof node !== 'object') return false;
+ const expression = node as acorn.Expression;
+ if (expression.type === 'Identifier') return expression.name === 'THREE';
+ if (expression.type === 'ChainExpression')
+ return expressionReferencesThree(expression.expression);
+ if (expression.type === 'SequenceExpression') {
+ return expressionReferencesThree(expression.expressions.at(-1));
+ }
+ return false;
+}
+
+function identifierIsNonReferenceKey(
+ node: acorn.Identifier,
+ parent: acorn.Node | undefined,
+): boolean {
+ if (!parent) return false;
+ if (parent.type === 'MemberExpression') {
+ const member = parent as acorn.MemberExpression;
+ if (member.property === node && !member.computed) return true;
+ }
+ if (parent.type === 'Property') {
+ const property = parent as acorn.Property;
+ if (property.key === node && !property.computed && !property.shorthand) return true;
+ }
+ if (parent.type === 'MethodDefinition') {
+ const method = parent as acorn.MethodDefinition;
+ if (method.key === node && !method.computed) return true;
+ }
+ if (parent.type === 'LabeledStatement') {
+ if ((parent as acorn.LabeledStatement).label === node) return true;
+ }
+ if (parent.type === 'BreakStatement' || parent.type === 'ContinueStatement') {
+ if ((parent as acorn.BreakStatement | acorn.ContinueStatement).label === node) return true;
+ }
+ return false;
+}
+
+function analyzeObjectPatternSafety(
+ pattern: acorn.ObjectPattern,
+ fromThree: boolean,
+ staticStrings: ReadonlyMap<string, string>,
+ dynamicCode: (line?: number) => void,
+ unsafeThree: (name: string, line?: number) => void,
+): void {
+ for (const entry of pattern.properties) {
+ if (entry.type !== 'Property') continue;
+ const property =
+ !entry.computed && entry.key.type === 'Identifier'
+ ? entry.key.name
+ : staticExpressionString(entry.key, staticStrings);
+ if (property === 'constructor') dynamicCode(entry.loc?.start.line);
+ if (fromThree && property && FORBIDDEN_THREE_CONSTRUCTORS.has(property)) {
+ unsafeThree(property, entry.loc?.start.line);
+ }
+ }
+}
+
+function staticPropertyName(
+ node: acorn.MemberExpression,
+ staticStrings: ReadonlyMap<string, string>,
+): string | undefined {
+ if (!node.computed && node.property.type === 'Identifier') return node.property.name;
+ return staticExpressionString(node.property, staticStrings);
+}
+
+function staticExpressionString(
+ node: unknown,
+ staticStrings: ReadonlyMap<string, string> = new Map(),
+): string | undefined {
+ if (!node || typeof node !== 'object') return undefined;
+ const expression = node as acorn.Expression;
+ if (expression.type === 'Literal') {
+ return typeof expression.value === 'string' || typeof expression.value === 'number'
+ ? String(expression.value)
+ : undefined;
+ }
+ if (expression.type === 'Identifier') return staticStrings.get(expression.name);
+ if (expression.type === 'TemplateLiteral') {
+ let value = expression.quasis[0]?.value.cooked ?? expression.quasis[0]?.value.raw ?? '';
+ for (let index = 0; index < expression.expressions.length; index++) {
+ const part = staticExpressionString(expression.expressions[index], staticStrings);
+ if (part === undefined) return undefined;
+ const quasi = expression.quasis[index + 1];
+ value += part + (quasi?.value.cooked ?? quasi?.value.raw ?? '');
+ }
+ return value;
+ }
+ if (expression.type === 'BinaryExpression' && expression.operator === '+') {
+ const left = staticExpressionString(expression.left, staticStrings);
+ const right = staticExpressionString(expression.right, staticStrings);
+ return left === undefined || right === undefined ? undefined : left + right;
+ }
+ return undefined;
+}
+
+/** Resolve unambiguous const string/number bindings for common bracket-access
+ * obfuscations. Duplicate names across scopes are intentionally left unknown
+ * to avoid attaching one scope's value to another. */
+function collectStaticStringBindings(ast: acorn.Program): ReadonlyMap<string, string> {
+ const candidates = new Map<string, acorn.Expression>();
+ const duplicateNames = new Set<string>();
+ walk.simple(ast, {
+ VariableDeclaration(node) {
+ if (node.kind !== 'const') return;
+ for (const declaration of node.declarations) {
+ if (declaration.id.type !== 'Identifier' || !declaration.init) continue;
+ if (candidates.has(declaration.id.name)) duplicateNames.add(declaration.id.name);
+ else candidates.set(declaration.id.name, declaration.init);
+ }
+ },
+ });
+ for (const name of duplicateNames) candidates.delete(name);
+
+ const values = new Map<string, string>();
+ for (let pass = 0; pass < candidates.size; pass++) {
+ let changed = false;
+ for (const [name, expression] of candidates) {
+ if (values.has(name)) continue;
+ const value = staticExpressionString(expression, values);
+ if (value === undefined) continue;
+ values.set(name, value);
+ changed = true;
+ }
+ if (!changed) break;
+ }
+ return values;
+}
+
function toResult(issues: ValidationIssue[], warnings: ValidationIssue[]): ValidationResult {
return {
valid: issues.length === 0,
diff --git a/src/views/__tests__/evidence-history.test.ts b/src/views/__tests__/evidence-history.test.ts
new file mode 100644
index 00000000..ab567118
--- /dev/null
+++ b/src/views/__tests__/evidence-history.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, test } from 'bun:test';
+
+import type { DerivativeReviewFidelityV1, ViewFidelityV1 } from '../../composer/render-port';
+import { ViewEvidenceHistoryStore } from '../evidence-history';
+
+const hash = (char: string) => `sha256:${char.repeat(64)}` as const;
+
+function faithful(inputGlbSha256 = hash('a')): ViewFidelityV1 {
+ return {
+ version: 'kiln.view-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: false,
+ rendererId: 'gpu:test',
+ inputGlbSha256,
+ degraded: false,
+ };
+}
+
+function degraded(inputGlbSha256 = hash('a')): ViewFidelityV1 {
+ return {
+ version: 'kiln.view-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ exactArtifact: false,
+ rendererId: 'cpu:test',
+ inputGlbSha256,
+ degraded: true,
+ degradeReason: 'GPU unavailable',
+ reasonCodes: ['FULL_MATERIAL_RENDER_UNAVAILABLE'],
+ };
+}
+
+describe('bounded model-visible view evidence history', () => {
+ test('success then degrade preserves the older faithful reference without reusing pixels', () => {
+ const store = new ViewEvidenceHistoryStore(2);
+ store.record('kiln_render', faithful());
+ const state = store.record('kiln_render', degraded());
+
+ expect(state.current).toMatchObject({
+ sequence: 2,
+ surface: 'kiln_render',
+ delivered: 'geometry-flat',
+ materialFaithful: false,
+ degraded: true,
+ inputGlbSha256: [hash('a')],
+ });
+ expect(state.lastFaithful).toMatchObject({
+ sequence: 1,
+ surface: 'kiln_render',
+ materialFaithful: true,
+ inputGlbSha256: [hash('a')],
+ });
+ expect(JSON.stringify(state)).not.toContain('png');
+ expect(JSON.stringify(state)).not.toContain('source');
+ });
+
+ test('degrade-only history never invents a faithful reference', () => {
+ const state = new ViewEvidenceHistoryStore().record('kiln_inspect', degraded());
+ expect(state.current.degraded).toBe(true);
+ expect(state.lastFaithful).toBeUndefined();
+ expect(state.faithfulHistory).toEqual([]);
+ });
+
+ test('a changed current hash remains distinct from the last faithful input', () => {
+ const store = new ViewEvidenceHistoryStore();
+ store.record('kiln_render', faithful(hash('a')));
+ const state = store.record('kiln_render', degraded(hash('b')));
+ expect(state.current.inputGlbSha256).toEqual([hash('b')]);
+ expect(state.lastFaithful?.inputGlbSha256).toEqual([hash('a')]);
+ expect(state.current.sequence).toBeGreaterThan(state.lastFaithful!.sequence);
+ });
+
+ test('malformed derivative receipts degrade current evidence and cannot replace lastFaithful', () => {
+ const store = new ViewEvidenceHistoryStore();
+ store.record('kiln_render', faithful());
+ const malformed = {
+ version: 'kiln.derivative-review-fidelity.v1',
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ materialFaithful: true,
+ exactArtifact: false,
+ degraded: false,
+ receipts: [
+ {
+ ...faithful('sha256:not-a-hash' as `sha256:${string}`),
+ derivativeLabel: '',
+ exactArtifact: false,
+ },
+ ],
+ } satisfies DerivativeReviewFidelityV1;
+ const state = store.record('kiln_screenshot_animation', malformed);
+ expect(state.current).toMatchObject({
+ delivered: 'none',
+ materialFaithful: false,
+ degraded: true,
+ reasonCodes: ['DERIVATIVE_RECEIPT_INVALID'],
+ });
+ expect(state.lastFaithful?.sequence).toBe(1);
+ });
+
+ test('faithful history is bounded and returned snapshots cannot mutate the store', () => {
+ const store = new ViewEvidenceHistoryStore(2);
+ store.record('kiln_render', faithful(hash('a')));
+ store.record('kiln_inspect', faithful(hash('b')));
+ const state = store.record('kiln_view_interior', faithful(hash('c')));
+ expect(state.faithfulHistory.map((entry) => entry.inputGlbSha256[0])).toEqual([
+ hash('b'),
+ hash('c'),
+ ]);
+ state.faithfulHistory.length = 0;
+ expect(store.snapshot()!.faithfulHistory).toHaveLength(2);
+ });
+});
diff --git a/src/views/__tests__/glb.test.ts b/src/views/__tests__/glb.test.ts
new file mode 100644
index 00000000..788a4f5a
--- /dev/null
+++ b/src/views/__tests__/glb.test.ts
@@ -0,0 +1,134 @@
+import { createHash } from 'node:crypto';
+import { describe, expect, spyOn, test } from 'bun:test';
+import { Document, WebIO } from '@gltf-transform/core';
+import { EXTMeshGPUInstancing, KHRTextureBasisu } from '@gltf-transform/extensions';
+
+import * as renderModule from '../../render';
+import {
+ GLB_GEOMETRY_FLAT_REASON,
+ geometryFlatTextureReasonCode,
+ loadGlbGeometryFlatScene,
+ measureBounds,
+ renderGlbViewGrid,
+} from '..';
+
+const io = (): WebIO => new WebIO().registerExtensions([EXTMeshGPUInstancing, KHRTextureBasisu]);
+
+function triangleDocument(
+ options: {
+ alpha?: number;
+ texture?: boolean;
+ translation?: [number, number, number];
+ scale?: [number, number, number];
+ } = {},
+): Document {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const positions = doc
+ .createAccessor('positions')
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]))
+ .setBuffer(buffer);
+ const indices = doc
+ .createAccessor('indices')
+ .setType('SCALAR')
+ .setArray(new Uint16Array([0, 1, 2]))
+ .setBuffer(buffer);
+ const material = doc
+ .createMaterial('FactorMaterial')
+ .setBaseColorFactor([0.25, 0.5, 0.75, options.alpha ?? 1])
+ .setAlphaMode(options.alpha === undefined ? 'OPAQUE' : 'BLEND')
+ .setDoubleSided(true);
+ if (options.texture) {
+ material.setBaseColorTexture(
+ doc
+ .createTexture('TinyPng')
+ .setMimeType('image/png')
+ .setImage(
+ new Uint8Array(
+ Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFgAI/ScL9WQAAAABJRU5ErkJggg==',
+ 'base64',
+ ),
+ ),
+ ),
+ );
+ }
+ const primitive = doc
+ .createPrimitive()
+ .setAttribute('POSITION', positions)
+ .setIndices(indices)
+ .setMaterial(material);
+ const node = doc
+ .createNode('Triangle')
+ .setMesh(doc.createMesh('TriangleMesh').addPrimitive(primitive))
+ .setTranslation(options.translation ?? [0, 0, 0])
+ .setScale(options.scale ?? [1, 1, 1]);
+ const scene = doc.createScene('Scene').addChild(node);
+ doc.getRoot().setDefaultScene(scene);
+ return doc;
+}
+
+describe('GLB-native geometry-flat view input', () => {
+ test('reads exact bytes without executeKilnCode and reports their SHA-256 identity', async () => {
+ const bytes = await io().writeBinary(triangleDocument());
+ const executeSpy = spyOn(renderModule, 'executeKilnCode');
+ try {
+ const result = await renderGlbViewGrid(bytes, { size: 32 });
+ expect(result.png.byteLength).toBeGreaterThan(100);
+ expect(executeSpy).not.toHaveBeenCalled();
+ expect(result.inputGlbSha256).toBe(
+ `sha256:${createHash('sha256').update(bytes).digest('hex')}`,
+ );
+ } finally {
+ executeSpy.mockRestore();
+ }
+ });
+
+ test('preserves node world transforms and base color/alpha factors', async () => {
+ const bytes = await io().writeBinary(
+ triangleDocument({ alpha: 0.4, translation: [2, 3, 4], scale: [2, 3, 1] }),
+ );
+ const loaded = await loadGlbGeometryFlatScene(bytes);
+ expect(measureBounds(loaded.root)).toEqual({ min: [2, 3, 4], max: [4, 6, 4] });
+
+ const meshes: Array<{
+ material?: { color?: unknown; opacity?: number; doubleSided?: boolean };
+ }> = [];
+ loaded.root.traverse?.((value: unknown) => meshes.push(value as (typeof meshes)[number]));
+ expect(meshes[0]?.material).toMatchObject({
+ color: { r: 0.25, g: 0.5, b: 0.75 },
+ opacity: 0.4,
+ doubleSided: true,
+ });
+ });
+
+ test('expands EXT_mesh_gpu_instancing transforms into exact flat geometry', async () => {
+ const doc = triangleDocument();
+ const node = doc.getRoot().listNodes()[0]!;
+ const translations = doc
+ .createAccessor('instance translations')
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 0, 10, 0, 0]))
+ .setBuffer(doc.getRoot().listBuffers()[0]!);
+ const extension = doc.createExtension(EXTMeshGPUInstancing).setRequired(true);
+ node.setExtension(
+ 'EXT_mesh_gpu_instancing',
+ extension.createInstancedMesh().setAttribute('TRANSLATION', translations),
+ );
+
+ const loaded = await loadGlbGeometryFlatScene(await io().writeBinary(doc));
+ expect(loaded.instanceCount).toBe(2);
+ expect(measureBounds(loaded.root)).toEqual({ min: [0, 0, 0], max: [11, 1, 0] });
+ });
+
+ test('reports stable structured reasons for ignored PNG and KTX2 sampling', async () => {
+ const png = await loadGlbGeometryFlatScene(
+ await io().writeBinary(triangleDocument({ texture: true })),
+ );
+ expect(png.reasonCodes).toEqual([GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED]);
+ expect(geometryFlatTextureReasonCode('image/ktx2')).toBe(
+ GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED,
+ );
+ });
+});
diff --git a/src/views/evidence-history.ts b/src/views/evidence-history.ts
new file mode 100644
index 00000000..538181a3
--- /dev/null
+++ b/src/views/evidence-history.ts
@@ -0,0 +1,166 @@
+import type {
+ CurrentViewEvidenceV1,
+ DerivativeReviewFidelityV1,
+ FaithfulViewEvidenceReferenceV1,
+ ViewEvidenceHistoryV1,
+ ViewEvidenceSurface,
+ ViewFidelityReasonCode,
+ ViewFidelityV1,
+} from '../composer/render-port';
+
+const SHA256 = /^sha256:[0-9a-f]{64}$/;
+const DEFAULT_LIMIT = 4;
+const MAX_LIMIT = 8;
+
+type Fidelity = ViewFidelityV1 | DerivativeReviewFidelityV1;
+
+function unique<T>(values: readonly T[]): T[] {
+ return [...new Set(values)];
+}
+
+function cloneReference(
+ reference: FaithfulViewEvidenceReferenceV1,
+): FaithfulViewEvidenceReferenceV1 {
+ return {
+ ...reference,
+ inputGlbSha256: [...reference.inputGlbSha256],
+ rendererIds: [...reference.rendererIds],
+ };
+}
+
+function currentEvidence(
+ sequence: number,
+ surface: ViewEvidenceSurface,
+ fidelity: Fidelity,
+): CurrentViewEvidenceV1 {
+ if (fidelity.version === 'kiln.view-fidelity.v1') {
+ const valid =
+ SHA256.test(fidelity.inputGlbSha256) &&
+ fidelity.rendererId.trim().length > 0 &&
+ (!fidelity.materialFaithful ||
+ (fidelity.delivered === 'full-material' && !fidelity.degraded));
+ if (!valid) {
+ return {
+ sequence,
+ surface,
+ delivered: 'none',
+ materialFaithful: false,
+ exactArtifact: false,
+ degraded: true,
+ inputGlbSha256: [],
+ rendererIds: [],
+ reasonCodes: ['DERIVATIVE_RECEIPT_INVALID'],
+ };
+ }
+ return {
+ sequence,
+ surface,
+ delivered: fidelity.delivered,
+ materialFaithful: fidelity.materialFaithful,
+ exactArtifact: fidelity.exactArtifact,
+ degraded: fidelity.degraded,
+ inputGlbSha256: [fidelity.inputGlbSha256],
+ rendererIds: [fidelity.rendererId],
+ ...(fidelity.reasonCodes?.length ? { reasonCodes: [...fidelity.reasonCodes] } : {}),
+ };
+ }
+
+ const valid =
+ fidelity.exactArtifact === false &&
+ fidelity.receipts.length > 0 &&
+ fidelity.receipts.every(
+ (receipt) =>
+ receipt.exactArtifact === false &&
+ receipt.derivativeLabel.trim().length > 0 &&
+ receipt.rendererId.trim().length > 0 &&
+ SHA256.test(receipt.inputGlbSha256),
+ ) &&
+ (!fidelity.materialFaithful ||
+ (fidelity.delivered === 'full-material' &&
+ !fidelity.degraded &&
+ fidelity.receipts.every(
+ (receipt) =>
+ receipt.materialFaithful && receipt.delivered === 'full-material' && !receipt.degraded,
+ )));
+ if (!valid) {
+ return {
+ sequence,
+ surface,
+ delivered: 'none',
+ materialFaithful: false,
+ exactArtifact: false,
+ degraded: true,
+ inputGlbSha256: [],
+ rendererIds: [],
+ reasonCodes: ['DERIVATIVE_RECEIPT_INVALID'],
+ };
+ }
+ const reasonCodes = unique(
+ fidelity.receipts
+ .flatMap((receipt) => receipt.reasonCodes ?? [])
+ .concat(fidelity.reasonCodes ?? []),
+ ) as ViewFidelityReasonCode[];
+ return {
+ sequence,
+ surface,
+ delivered: fidelity.delivered,
+ materialFaithful: fidelity.materialFaithful,
+ exactArtifact: false,
+ degraded: fidelity.degraded,
+ inputGlbSha256: fidelity.receipts.map((receipt) => receipt.inputGlbSha256),
+ rendererIds: unique(fidelity.receipts.map((receipt) => receipt.rendererId)),
+ ...(reasonCodes.length ? { reasonCodes } : {}),
+ };
+}
+
+/** In-memory metadata ledger. It retains hashes/producer ids only, never pixels or source. */
+export class ViewEvidenceHistoryStore {
+ private readonly limit: number;
+ private sequence = 0;
+ private current?: CurrentViewEvidenceV1;
+ private readonly faithful: FaithfulViewEvidenceReferenceV1[] = [];
+
+ constructor(limit = DEFAULT_LIMIT) {
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
+ throw new RangeError(`view evidence history limit must be an integer in [1,${MAX_LIMIT}]`);
+ }
+ this.limit = limit;
+ }
+
+ record(surface: ViewEvidenceSurface, fidelity: Fidelity): ViewEvidenceHistoryV1 {
+ this.sequence++;
+ this.current = currentEvidence(this.sequence, surface, fidelity);
+ if (this.current.materialFaithful) {
+ this.faithful.push({
+ version: 'kiln.faithful-view-evidence-ref.v1',
+ sequence: this.current.sequence,
+ surface,
+ materialFaithful: true,
+ exactArtifact: this.current.exactArtifact,
+ inputGlbSha256: [...this.current.inputGlbSha256],
+ rendererIds: [...this.current.rendererIds],
+ });
+ if (this.faithful.length > this.limit)
+ this.faithful.splice(0, this.faithful.length - this.limit);
+ }
+ return this.snapshot()!;
+ }
+
+ snapshot(): ViewEvidenceHistoryV1 | undefined {
+ if (!this.current) return undefined;
+ const faithfulHistory = this.faithful.map(cloneReference);
+ return {
+ version: 'kiln.view-evidence-history.v1',
+ current: {
+ ...this.current,
+ inputGlbSha256: [...this.current.inputGlbSha256],
+ rendererIds: [...this.current.rendererIds],
+ ...(this.current.reasonCodes ? { reasonCodes: [...this.current.reasonCodes] } : {}),
+ },
+ ...(faithfulHistory.length
+ ? { lastFaithful: cloneReference(faithfulHistory[faithfulHistory.length - 1]!) }
+ : {}),
+ faithfulHistory,
+ };
+ }
+}
diff --git a/src/views/glb.ts b/src/views/glb.ts
new file mode 100644
index 00000000..f0d246d0
--- /dev/null
+++ b/src/views/glb.ts
@@ -0,0 +1,312 @@
+/** GLB-native input adapter for the deterministic CPU geometry-flat renderer. */
+
+import { Primitive, WebIO, type Accessor, type Material } from '@gltf-transform/core';
+import {
+ EXTMeshGPUInstancing,
+ KHRMaterialsVariants,
+ KHRTextureBasisu,
+} from '@gltf-transform/extensions';
+import { Matrix4, Quaternion, Vector3 } from 'three';
+
+export const GLB_GEOMETRY_FLAT_REASON = {
+ TEXTURE_SAMPLING_UNSUPPORTED: 'GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED',
+ KTX2_SAMPLING_UNSUPPORTED: 'GLB_FLAT_KTX2_SAMPLING_UNSUPPORTED',
+ NON_TRIANGLE_PRIMITIVE_UNSUPPORTED: 'GLB_FLAT_NON_TRIANGLE_PRIMITIVE_UNSUPPORTED',
+ SKIN_DEFORMATION_UNSUPPORTED: 'GLB_FLAT_SKIN_DEFORMATION_UNSUPPORTED',
+ MORPH_TARGETS_UNSUPPORTED: 'GLB_FLAT_MORPH_TARGETS_UNSUPPORTED',
+} as const;
+
+export type GlbGeometryFlatReasonCode =
+ (typeof GLB_GEOMETRY_FLAT_REASON)[keyof typeof GLB_GEOMETRY_FLAT_REASON];
+
+const REASON_ORDER: readonly GlbGeometryFlatReasonCode[] = [
+ GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED,
+ GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED,
+ GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED,
+ GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED,
+ GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED,
+];
+
+export type GlbGeometryFlatErrorCode =
+ | 'GLB_FLAT_PARSE_FAILED'
+ | 'GLB_FLAT_NO_SCENE'
+ | 'GLB_FLAT_NO_RENDERABLE_GEOMETRY'
+ | 'GLB_FLAT_INVALID_INSTANCING';
+
+export class GlbGeometryFlatError extends Error {
+ constructor(
+ readonly code: GlbGeometryFlatErrorCode,
+ message: string,
+ ) {
+ super(message);
+ this.name = 'GlbGeometryFlatError';
+ }
+}
+
+interface FlatAttribute {
+ array: ArrayLike<number>;
+ itemSize: number;
+ count: number;
+}
+
+interface FlatMaterial {
+ color: { r: number; g: number; b: number };
+ opacity: number;
+ doubleSided: boolean;
+}
+
+interface FlatMesh {
+ isMesh: true;
+ visible: true;
+ geometry: {
+ getAttribute(name: string): FlatAttribute | undefined;
+ index: FlatAttribute;
+ };
+ material: FlatMaterial;
+ matrixWorld: { elements: readonly number[] };
+}
+
+export interface GlbGeometryFlatRoot {
+ updateMatrixWorld(force?: boolean): void;
+ traverse(callback: (value: unknown) => void): void;
+}
+
+export interface LoadedGlbGeometryFlatScene {
+ root: GlbGeometryFlatRoot;
+ reasonCodes: GlbGeometryFlatReasonCode[];
+ meshCount: number;
+ instanceCount: number;
+}
+
+const glbIO = (): WebIO =>
+ new WebIO().registerExtensions([EXTMeshGPUInstancing, KHRMaterialsVariants, KHRTextureBasisu]);
+
+export function geometryFlatTextureReasonCode(mimeType: string | null): GlbGeometryFlatReasonCode {
+ return mimeType === 'image/ktx2'
+ ? GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED
+ : GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED;
+}
+
+function decodedAccessor(accessor: Accessor): Float64Array {
+ const itemSize = accessor.getElementSize();
+ const output = new Float64Array(accessor.getCount() * itemSize);
+ const element: number[] = [];
+ for (let index = 0; index < accessor.getCount(); index++) {
+ accessor.getElement(index, element);
+ for (let component = 0; component < itemSize; component++) {
+ output[index * itemSize + component] = element[component]!;
+ }
+ }
+ return output;
+}
+
+function triangleIndices(
+ primitive: import('@gltf-transform/core').Primitive,
+ vertexCount: number,
+): Uint32Array | undefined {
+ const sourceAccessor = primitive.getIndices();
+ const source = sourceAccessor
+ ? Array.from(decodedAccessor(sourceAccessor), (value) => Math.trunc(value))
+ : Array.from({ length: vertexCount }, (_, index) => index);
+ switch (primitive.getMode()) {
+ case Primitive.Mode.TRIANGLES:
+ return Uint32Array.from(source);
+ case Primitive.Mode.TRIANGLE_STRIP: {
+ const triangles: number[] = [];
+ for (let index = 0; index + 2 < source.length; index++) {
+ triangles.push(
+ source[index]!,
+ source[index + 1 + (index % 2)]!,
+ source[index + 2 - (index % 2)]!,
+ );
+ }
+ return Uint32Array.from(triangles);
+ }
+ case Primitive.Mode.TRIANGLE_FAN: {
+ const triangles: number[] = [];
+ for (let index = 1; index + 1 < source.length; index++) {
+ triangles.push(source[index]!, source[index + 1]!, source[0]!);
+ }
+ return Uint32Array.from(triangles);
+ }
+ default:
+ return undefined;
+ }
+}
+
+function flatMaterial(material: Material | null): FlatMaterial {
+ if (!material) {
+ return { color: { r: 0.7, g: 0.7, b: 0.7 }, opacity: 1, doubleSided: false };
+ }
+ const [r, g, b, factorAlpha] = material.getBaseColorFactor();
+ const alphaMode = material.getAlphaMode();
+ const opacity =
+ alphaMode === 'BLEND'
+ ? factorAlpha
+ : alphaMode === 'MASK' && factorAlpha < material.getAlphaCutoff()
+ ? 0
+ : 1;
+ return {
+ color: { r, g, b },
+ opacity,
+ doubleSided: material.getDoubleSided(),
+ };
+}
+
+function noteMaterialTextures(
+ material: Material | null,
+ reasons: Set<GlbGeometryFlatReasonCode>,
+): void {
+ if (!material) return;
+ const textures = [
+ material.getBaseColorTexture(),
+ material.getNormalTexture(),
+ material.getMetallicRoughnessTexture(),
+ material.getEmissiveTexture(),
+ material.getOcclusionTexture(),
+ ];
+ for (const texture of textures) {
+ if (texture) reasons.add(geometryFlatTextureReasonCode(texture.getMimeType()));
+ }
+}
+
+function instanceMatrices(node: import('@gltf-transform/core').Node): {
+ matrices: Matrix4[];
+ count: number;
+} {
+ const world = new Matrix4().fromArray(node.getWorldMatrix());
+ const extension = node.getExtension('EXT_mesh_gpu_instancing') as {
+ getAttribute(name: string): Accessor | null;
+ listAttributes(): Accessor[];
+ } | null;
+ if (!extension) return { matrices: [world], count: 1 };
+
+ const attributes = extension.listAttributes();
+ if (attributes.length === 0) {
+ throw new GlbGeometryFlatError(
+ 'GLB_FLAT_INVALID_INSTANCING',
+ `Node ${JSON.stringify(node.getName())} has EXT_mesh_gpu_instancing with no attributes.`,
+ );
+ }
+ const count = attributes[0]!.getCount();
+ if (attributes.some((attribute) => attribute.getCount() !== count)) {
+ throw new GlbGeometryFlatError(
+ 'GLB_FLAT_INVALID_INSTANCING',
+ `Node ${JSON.stringify(node.getName())} has mismatched EXT_mesh_gpu_instancing counts.`,
+ );
+ }
+ const translations = extension.getAttribute('TRANSLATION');
+ const rotations = extension.getAttribute('ROTATION');
+ const scales = extension.getAttribute('SCALE');
+ const translation: number[] = [];
+ const rotation: number[] = [];
+ const scale: number[] = [];
+ const matrices: Matrix4[] = [];
+ for (let index = 0; index < count; index++) {
+ translations?.getElement(index, translation);
+ rotations?.getElement(index, rotation);
+ scales?.getElement(index, scale);
+ const local = new Matrix4().compose(
+ new Vector3(
+ translations ? translation[0]! : 0,
+ translations ? translation[1]! : 0,
+ translations ? translation[2]! : 0,
+ ),
+ new Quaternion(
+ rotations ? rotation[0]! : 0,
+ rotations ? rotation[1]! : 0,
+ rotations ? rotation[2]! : 0,
+ rotations ? rotation[3]! : 1,
+ ).normalize(),
+ new Vector3(scales ? scale[0]! : 1, scales ? scale[1]! : 1, scales ? scale[2]! : 1),
+ );
+ matrices.push(world.clone().multiply(local));
+ }
+ return { matrices, count };
+}
+
+/** Parse final artifact bytes into the minimal scene contract consumed by the CPU rasterizer. */
+export async function loadGlbGeometryFlatScene(
+ bytes: Uint8Array,
+): Promise<LoadedGlbGeometryFlatScene> {
+ let document: import('@gltf-transform/core').Document;
+ try {
+ document = await glbIO().readBinary(Uint8Array.from(bytes));
+ } catch (error) {
+ throw new GlbGeometryFlatError(
+ 'GLB_FLAT_PARSE_FAILED',
+ `Could not parse final GLB bytes: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ const scene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];
+ if (!scene) throw new GlbGeometryFlatError('GLB_FLAT_NO_SCENE', 'Final GLB has no scene.');
+
+ const reasons = new Set<GlbGeometryFlatReasonCode>();
+ const meshes: FlatMesh[] = [];
+ let instanceCount = 0;
+ const sceneNodes = new Set<import('@gltf-transform/core').Node>();
+ const visit = (node: import('@gltf-transform/core').Node): void => {
+ if (sceneNodes.has(node)) return;
+ sceneNodes.add(node);
+ for (const child of node.listChildren()) visit(child);
+ };
+ for (const child of scene.listChildren()) visit(child);
+
+ for (const node of sceneNodes) {
+ const mesh = node.getMesh();
+ if (!mesh) continue;
+ if (node.getSkin()) reasons.add(GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED);
+ const instances = instanceMatrices(node);
+ instanceCount += instances.count;
+ for (const primitive of mesh.listPrimitives()) {
+ if (primitive.listTargets().length > 0) {
+ reasons.add(GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED);
+ }
+ const positionAccessor = primitive.getAttribute('POSITION');
+ if (positionAccessor?.getElementSize() !== 3) continue;
+ const positions = decodedAccessor(positionAccessor);
+ const indices = triangleIndices(primitive, positionAccessor.getCount());
+ if (!indices) {
+ reasons.add(GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED);
+ continue;
+ }
+ const material = primitive.getMaterial();
+ noteMaterialTextures(material, reasons);
+ const geometry = {
+ getAttribute(name: string): FlatAttribute | undefined {
+ return name === 'position'
+ ? { array: positions, itemSize: 3, count: positionAccessor.getCount() }
+ : undefined;
+ },
+ index: { array: indices, itemSize: 1, count: indices.length },
+ };
+ for (const matrix of instances.matrices) {
+ meshes.push({
+ isMesh: true,
+ visible: true,
+ geometry,
+ material: flatMaterial(material),
+ matrixWorld: { elements: [...matrix.elements] },
+ });
+ }
+ }
+ }
+ if (meshes.length === 0) {
+ throw new GlbGeometryFlatError(
+ 'GLB_FLAT_NO_RENDERABLE_GEOMETRY',
+ 'Final GLB contains no triangle geometry supported by the CPU fallback.',
+ );
+ }
+ const root: GlbGeometryFlatRoot = {
+ updateMatrixWorld() {},
+ traverse(callback) {
+ for (const mesh of meshes) callback(mesh);
+ },
+ };
+ return {
+ root,
+ reasonCodes: REASON_ORDER.filter((reason) => reasons.has(reason)),
+ meshCount: meshes.length,
+ instanceCount,
+ };
+}
diff --git a/src/views/index.ts b/src/views/index.ts
index c7fc4f2b..8a5eccc9 100644
--- a/src/views/index.ts
+++ b/src/views/index.ts
@@ -21,6 +21,7 @@ import {
type ViewSpec,
} from './raster';
import { encodePng } from './png';
+import { decodePng } from './png';
import { compositeCellGrid } from './grid';
import { annotateViewCell } from './annotate';
import { resolveGridCapture, type CaptureConfig, type CaptureShape } from './capture';
@@ -41,6 +42,7 @@ import {
type SnapPaletteSlot,
type Vec3,
} from '../palette-snap';
+import { loadGlbGeometryFlatScene, type GlbGeometryFlatReasonCode } from './glb';
export {
rasterizeView,
@@ -78,8 +80,21 @@ export type {
ResolvedCapture,
} from './capture';
export { compositeCellGrid, compositeViewPngGrid, GRID_COLS } from './grid';
+export { ViewEvidenceHistoryStore } from './evidence-history';
export type { ComposedCellGrid, ComposedPngGrid } from './grid';
export { CPU_RASTER_RENDERER_ID } from './renderer-id';
+export {
+ GLB_GEOMETRY_FLAT_REASON,
+ GlbGeometryFlatError,
+ geometryFlatTextureReasonCode,
+ loadGlbGeometryFlatScene,
+} from './glb';
+export type {
+ GlbGeometryFlatErrorCode,
+ GlbGeometryFlatReasonCode,
+ GlbGeometryFlatRoot,
+ LoadedGlbGeometryFlatScene,
+} from './glb';
export {
ARCHITECTURE_ROOF_ROLE_PREFIXES,
hasArchitectureRoofRole,
@@ -320,6 +335,7 @@ export async function renderViewGrid(
const cell = rasterizeView(root, views[vi]!.dir, {
size,
backfaceCull: opts.backfaceCull,
+ ...(opts.frameBounds ? { frameBounds: opts.frameBounds } : {}),
...(sceneBounds && zoom !== undefined
? { frameBounds: expandFrameBounds(sceneBounds, zoom) }
: {}),
@@ -339,6 +355,76 @@ export async function renderViewGrid(
};
}
+export interface GlbViewGridResult extends ViewGridResult {
+ /** Identity of the exact byte array parsed for this fallback. */
+ inputGlbSha256: `sha256:${string}`;
+ /** Stable limitations of geometry-flat rendering for this artifact. */
+ reasonCodes: GlbGeometryFlatReasonCode[];
+ meshCount: number;
+ instanceCount: number;
+}
+
+async function hashGlbViewInput(bytes: Uint8Array): Promise<`sha256:${string}`> {
+ const copy = Uint8Array.from(bytes);
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', copy));
+ return `sha256:${[...digest].map((value) => value.toString(16).padStart(2, '0')).join('')}`;
+}
+
+export interface GlbViewCellResult {
+ png: Buffer;
+ width: number;
+ height: number;
+ inputGlbSha256: `sha256:${string}`;
+ reasonCodes: GlbGeometryFlatReasonCode[];
+ meshCount: number;
+ instanceCount: number;
+}
+
+/** Render one unannotated geometry-flat cell from an immutable GLB snapshot. */
+export async function renderGlbViewCell(
+ bytes: Uint8Array,
+ view: ViewSpec,
+ options: RasterOptions = {},
+): Promise<GlbViewCellResult> {
+ const exactBytes = Uint8Array.from(bytes);
+ const loaded = await loadGlbGeometryFlatScene(exactBytes);
+ const size = options.size ?? 256;
+ const rgb = rasterizeView(loaded.root, view.dir, {
+ size,
+ ...(options.backfaceCull !== undefined ? { backfaceCull: options.backfaceCull } : {}),
+ ...(options.frameBounds ? { frameBounds: options.frameBounds } : {}),
+ });
+ return {
+ png: encodePng(rgb, size, size),
+ width: size,
+ height: size,
+ inputGlbSha256: await hashGlbViewInput(exactBytes),
+ reasonCodes: loaded.reasonCodes,
+ meshCount: loaded.meshCount,
+ instanceCount: loaded.instanceCount,
+ };
+}
+
+/** Render the geometry-flat contact sheet from exact final GLB bytes. */
+export async function renderGlbViewGrid(
+ bytes: Uint8Array,
+ options: ViewGridOptions = {},
+): Promise<GlbViewGridResult> {
+ // One immutable snapshot owns both parsing and identity. Even a caller that
+ // mutates its Buffer while this async render is running cannot make the
+ // rasterized geometry and reported hash refer to different byte sequences.
+ const exactBytes = Uint8Array.from(bytes);
+ const loaded = await loadGlbGeometryFlatScene(exactBytes);
+ const grid = await renderViewGrid(loaded.root, options);
+ return {
+ ...grid,
+ inputGlbSha256: await hashGlbViewInput(exactBytes),
+ reasonCodes: loaded.reasonCodes,
+ meshCount: loaded.meshCount,
+ instanceCount: loaded.instanceCount,
+ };
+}
+
/** Grow a bounds box about its center — the per-cell `zoom` padding. */
function expandFrameBounds(
b: { min: [number, number, number]; max: [number, number, number] },
@@ -409,8 +495,31 @@ export interface AnimationViewOptions extends RasterOptions {
frames?: number;
/** Return the frames as separate PNGs instead of one composite grid. Default false. */
perFrame?: boolean;
+ /** Internal derivative renderer. Receives the already-posed scene and must
+ * render exactly one square cell without executing generated source. */
+ renderDerivativeCell?: DerivativeCellRenderer;
}
+export interface DerivativeCellRenderInput {
+ root: unknown;
+ label: string;
+ view: ViewSpec;
+ size: number;
+ backfaceCull?: boolean;
+ frameBounds?: { min: [number, number, number]; max: [number, number, number] };
+ /** Stable reason to decline GPU when its auto-framing cannot honor this view. */
+ gpuUnsupportedReasonCode?: 'DERIVATIVE_GPU_FRAMING_UNSUPPORTED';
+}
+
+export interface DerivativeCellRenderResult {
+ png: Buffer;
+ receipt: import('../composer/render-port').DerivativeViewReceiptV1;
+}
+
+export type DerivativeCellRenderer = (
+ input: DerivativeCellRenderInput,
+) => Promise<DerivativeCellRenderResult>;
+
export interface AnimationViewResult {
ok: boolean;
clip?: string;
@@ -431,6 +540,7 @@ export interface AnimationViewResult {
/** Clip names available in the scene (set on a not-found error). */
availableClips?: string[];
error?: string;
+ derivativeReceipts?: import('../composer/render-port').DerivativeViewReceiptV1[];
}
/** Phase percentage label for frame i of n, e.g. "0%" … "100%". */
@@ -502,13 +612,34 @@ export async function renderClipAnimation(
// Pass 2 — render + label each frame against the fixed framing.
const labelScale = Math.max(2, Math.round(size / 80));
const cells: Uint8Array[] = [];
+ const derivativeReceipts: import('../composer/render-port').DerivativeViewReceiptV1[] = [];
for (let i = 0; i < times.length; i++) {
poseSceneAtTime(root as never, prepared, times[i]!);
- const cell = rasterizeView(root, cam.dir, {
- size,
- ...(opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {}),
- ...(frameBounds ? { frameBounds } : {}),
- });
+ let cell: Uint8Array;
+ if (opts.renderDerivativeCell) {
+ const rendered = await opts.renderDerivativeCell({
+ root,
+ label: phaseLabel(i, times.length),
+ view: cam,
+ size,
+ ...(opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {}),
+ ...(frameBounds ? { frameBounds } : {}),
+ });
+ const decoded = decodePng(rendered.png);
+ if (decoded.width !== size || decoded.height !== size) {
+ throw new Error(
+ `derivative animation cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`,
+ );
+ }
+ cell = decoded.rgb;
+ derivativeReceipts.push(rendered.receipt);
+ } else {
+ cell = rasterizeView(root, cam.dir, {
+ size,
+ ...(opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {}),
+ ...(frameBounds ? { frameBounds } : {}),
+ });
+ }
stampLabel(cell, size, size, labelScale, labelScale, phaseLabel(i, times.length), labelScale);
cells.push(cell);
}
@@ -521,6 +652,7 @@ export async function renderClipAnimation(
frameTimes,
duration: prepared.duration,
...(prepared.unresolved.length ? { unresolvedTracks: prepared.unresolved } : {}),
+ ...(derivativeReceipts.length ? { derivativeReceipts } : {}),
};
if (opts.perFrame) {
@@ -547,6 +679,7 @@ export interface InteriorGridResult extends ViewGridResult {
roofsHidden: number;
/** Near-wall subtree roots hidden for the eye-level cutaway (0 → not a room()). */
wallsHidden: number;
+ derivativeReceipts?: import('../composer/render-port').DerivativeViewReceiptV1[];
}
export interface InteriorGridOptions extends RasterOptions {
@@ -554,6 +687,8 @@ export interface InteriorGridOptions extends RasterOptions {
* the roof semantically. Omit it for the ordinary path — role first, then a
* narrow historical-name fallback. */
nodeName?: string;
+ /** Internal exact-derivative renderer; omitted preserves the historical CPU path. */
+ renderDerivativeCell?: DerivativeCellRenderer;
}
/** Outward face normals of room() walls, by lowercased name suffix (front faces +X). */
@@ -564,7 +699,7 @@ const ROOM_WALL_NORMALS: Array<{ suffix: string; n: [number, number, number] }>
{ suffix: 'wallright', n: [0, 0, 1] },
];
-const INTERIOR_VIEWS: ViewSpec[] = [
+export const INTERIOR_VIEWS: ViewSpec[] = [
{ name: 'Floor plan', dir: [0, 1, 0.0001] }, // top-down, roof off
{ name: 'Dollhouse', dir: [0.7, 0.5, 0.7] }, // 3/4 cutaway, roof off
{ name: 'Eye-level', dir: [0.55, 0.35, 0.45] }, // low angle, roof + near walls off
@@ -607,6 +742,7 @@ export async function renderInteriorGrid(
let wallsHidden = 0;
const cells: Uint8Array[] = [];
+ const derivativeReceipts: import('../composer/render-port').DerivativeViewReceiptV1[] = [];
for (const view of INTERIOR_VIEWS) {
if (view.name === 'Eye-level') {
// Cutaway: also remove the walls facing the camera so the eye looks past
@@ -620,7 +756,26 @@ export async function renderInteriorGrid(
return false;
});
}
- const cell = rasterizeView(root, view.dir, { size, backfaceCull: false });
+ let cell: Uint8Array;
+ if (opts.renderDerivativeCell) {
+ const rendered = await opts.renderDerivativeCell({
+ root,
+ label: view.name,
+ view,
+ size,
+ backfaceCull: false,
+ });
+ const decoded = decodePng(rendered.png);
+ if (decoded.width !== size || decoded.height !== size) {
+ throw new Error(
+ `derivative interior cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`,
+ );
+ }
+ cell = decoded.rgb;
+ derivativeReceipts.push(rendered.receipt);
+ } else {
+ cell = rasterizeView(root, view.dir, { size, backfaceCull: false });
+ }
stampLabel(cell, size, size, labelScale, labelScale, view.name, labelScale);
cells.push(cell);
}
@@ -635,5 +790,6 @@ export async function renderInteriorGrid(
views: INTERIOR_VIEWS.map((v) => v.name),
roofsHidden,
wallsHidden,
+ ...(derivativeReceipts.length ? { derivativeReceipts } : {}),
};
}
diff --git a/src/views/inspect.ts b/src/views/inspect.ts
index 974d6750..5140f95b 100644
--- a/src/views/inspect.ts
+++ b/src/views/inspect.ts
@@ -25,7 +25,7 @@ export const INSPECT_MAX_ZOOM = 4;
export const INSPECT_MAX_PART_NAMES = 40;
/** Camera names accepted by kiln_inspect (same directions as the six-view grid). */
-const INSPECT_CAMERAS: Record<string, [number, number, number]> = {
+export const INSPECT_CAMERAS: Record<string, [number, number, number]> = {
front: [1, 0, 0],
right: [0, 0, 1],
back: [-1, 0, 0],
@@ -98,6 +98,28 @@ export type InspectViewResult =
availableParts: string[];
};
+export type PreparedInspectView =
+ | {
+ ok: true;
+ root: unknown;
+ part?: string;
+ view: string;
+ viewSpec: { name: string; dir: [number, number, number] };
+ azimuthDeg: number;
+ elevationDeg: number;
+ zoom: number;
+ isolated: boolean;
+ size: number;
+ frameBounds: Bounds;
+ }
+ | {
+ ok: false;
+ view: string;
+ zoom: number;
+ error: string;
+ availableParts: string[];
+ };
+
/** Named scene nodes in traversal (scene) order, deduped, capped. */
export function listPartNames(root: unknown, cap = INSPECT_MAX_PART_NAMES): string[] {
const names: string[] = [];
@@ -172,7 +194,10 @@ function isolateSubtree(root: unknown, keep: DuckNamedNode): void {
* asset when no part is given). Never throws on a bad part name — that comes
* back as { ok:false, availableParts } so the agent loop can retry by name.
*/
-export function renderInspectView(root: unknown, opts: InspectViewOptions = {}): InspectViewResult {
+export function prepareInspectView(
+ root: unknown,
+ opts: InspectViewOptions = {},
+): PreparedInspectView {
const size = opts.size ?? INSPECT_SIZE;
// Orbit angles win over the named presets, but ONLY when at least one is
@@ -233,19 +258,37 @@ export function renderInspectView(root: unknown, opts: InspectViewOptions = {}):
bounds = measureBounds(root);
}
- const rgb = rasterizeView(root, dir, {
- size,
- frameBounds: expandBounds(bounds, zoom),
- });
return {
ok: true,
+ root,
...(part ? { part } : {}),
view,
+ viewSpec: { name: view, dir },
...angles,
zoom,
isolated,
- width: size,
- height: size,
- png: encodePng(rgb, size, size),
+ size,
+ frameBounds: expandBounds(bounds, zoom),
+ };
+}
+
+export function renderInspectView(root: unknown, opts: InspectViewOptions = {}): InspectViewResult {
+ const prepared = prepareInspectView(root, opts);
+ if (!prepared.ok) return prepared;
+ const rgb = rasterizeView(prepared.root, prepared.viewSpec.dir, {
+ size: prepared.size,
+ frameBounds: prepared.frameBounds,
+ });
+ return {
+ ok: true,
+ ...(prepared.part ? { part: prepared.part } : {}),
+ view: prepared.view,
+ azimuthDeg: prepared.azimuthDeg,
+ elevationDeg: prepared.elevationDeg,
+ zoom: prepared.zoom,
+ isolated: prepared.isolated,
+ width: prepared.size,
+ height: prepared.size,
+ png: encodePng(rgb, prepared.size, prepared.size),
};
}
diff --git a/src/views/raster.ts b/src/views/raster.ts
index 2b85519f..196be74f 100644
--- a/src/views/raster.ts
+++ b/src/views/raster.ts
@@ -157,6 +157,9 @@ interface DuckGeometry {
}
interface DuckMaterial {
color?: { r: number; g: number; b: number };
+ /** Effective glTF base-color alpha after OPAQUE/MASK/BLEND handling. */
+ opacity?: number;
+ doubleSided?: boolean;
visible?: boolean;
}
interface DuckMesh {
@@ -176,6 +179,8 @@ interface Tri {
// World-space vertices, flattened [x0,y0,z0, x1,y1,z1, x2,y2,z2]
v: Float64Array;
color: [number, number, number];
+ alpha: number;
+ doubleSided: boolean;
}
/** Collect world-space triangles + base colors from a (possibly cross-realm) scene. */
@@ -203,16 +208,15 @@ function collectTriangles(root: DuckObject3D): { tris: Tri[]; bbox: { min: Vec3;
// own `materialIndex`. Colors are already per-triangle here, so resolve the
// group covering each triangle's first buffer position; meshes without
// groups (the common single-material case) keep the flat first material.
- const fallback = colorOf(mats[0]);
const groups = mats.length > 1 && geo.groups?.length ? geo.groups : undefined;
- const colorAt = (bufferPos: number): [number, number, number] => {
- if (!groups) return fallback;
+ const materialAt = (bufferPos: number): DuckMaterial | undefined => {
+ if (!groups) return mats[0];
for (const g of groups) {
if (bufferPos >= g.start && bufferPos < g.start + g.count) {
- return colorOf(mats[g.materialIndex ?? 0]);
+ return mats[g.materialIndex ?? 0];
}
}
- return fallback;
+ return mats[0];
};
const m = mesh.matrixWorld?.elements;
@@ -238,7 +242,7 @@ function collectTriangles(root: DuckObject3D): { tris: Tri[]; bbox: { min: Vec3;
if (wz > max[2]) max[2] = wz;
}
- const pushTri = (a: number, b: number, c2: number, color: [number, number, number]) => {
+ const pushTri = (a: number, b: number, c2: number, material: DuckMaterial | undefined) => {
const v = new Float64Array(9);
v[0] = world[a * 3]!;
v[1] = world[a * 3 + 1]!;
@@ -249,7 +253,12 @@ function collectTriangles(root: DuckObject3D): { tris: Tri[]; bbox: { min: Vec3;
v[6] = world[c2 * 3]!;
v[7] = world[c2 * 3 + 1]!;
v[8] = world[c2 * 3 + 2]!;
- tris.push({ v, color });
+ tris.push({
+ v,
+ color: colorOf(material),
+ alpha: clamp01(material?.opacity ?? 1),
+ doubleSided: material?.doubleSided === true,
+ });
};
// Geometry groups address the index buffer for indexed geometry and the
@@ -259,11 +268,11 @@ function collectTriangles(root: DuckObject3D): { tris: Tri[]; bbox: { min: Vec3;
if (index) {
const ia = index.array;
for (let i = 0; i + 2 < index.count; i += 3) {
- pushTri(ia[i]!, ia[i + 1]!, ia[i + 2]!, colorAt(i));
+ pushTri(ia[i]!, ia[i + 1]!, ia[i + 2]!, materialAt(i));
}
} else {
for (let i = 0; i + 2 < pos.count; i += 3) {
- pushTri(i, i + 1, i + 2, colorAt(i));
+ pushTri(i, i + 1, i + 2, materialAt(i));
}
}
});
@@ -354,7 +363,8 @@ export function rasterizeView(
const N: Vec3 = [n[0] / nLen, n[1] / nLen, n[2] / nLen];
const facing = dot(N, z);
- if (cull && facing <= 0) continue;
+ if (cull && facing <= 0 && !tri.doubleSided) continue;
+ if (tri.alpha <= 0) continue;
// Project to screen space.
for (let i = 0; i < 3; i++) {
@@ -409,9 +419,16 @@ export function rasterizeView(
const pi = py * size + px;
if (depth <= zbuf[pi]!) continue;
zbuf[pi] = depth;
- out[pi * 3] = r;
- out[pi * 3 + 1] = g;
- out[pi * 3 + 2] = b;
+ if (tri.alpha >= 1) {
+ out[pi * 3] = r;
+ out[pi * 3 + 1] = g;
+ out[pi * 3 + 2] = b;
+ } else {
+ const inverse = 1 - tri.alpha;
+ out[pi * 3] = Math.round(r * tri.alpha + out[pi * 3]! * inverse);
+ out[pi * 3 + 1] = Math.round(g * tri.alpha + out[pi * 3 + 1]! * inverse);
+ out[pi * 3 + 2] = Math.round(b * tri.alpha + out[pi * 3 + 2]! * inverse);
+ }
}
}
}