Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat: complete asset generation quality engine
Matt Kissingerb6e0455c819b
diff --git a/bun.lock b/bun.lockindex c09205b4..5d505c6f 100644--- a/bun.lock+++ b/bun.lock@@ -12,6 +12,7 @@"@types/three": "^0.185.1","acorn": "^8.17.0","acorn-walk": "^8.3.5",+ "gltf-validator": "2.0.0-dev.3.10","manifold-3d": "^3.5.1","sharp": "^0.35.3","three": "0.185.1",@@ -415,6 +416,8 @@"get-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],+ "gltf-validator": ["[email protected]", "", {}, "sha512-odJ4k0tRkGXiDGn78yDBg+fBbAIvBnXxh3RwAta0emSxGtyagFE8B4xELB1oYe3S5RD8Ci3uZAsZaascH2LAEQ=="],+"google-auth-library": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^7.1.4", "gcp-metadata": "8.1.2", "google-logging-utils": "1.1.3", "jws": "^4.0.0" } }, "sha512-QpTAbNJ36TliZLx3TTtahR8HG0hN9RllL1e3FymOvQSIKK8JmgV58H924ub2wa2DsS3ANjjP1Aw1N+Ramc8hqQ=="],"google-logging-utils": ["[email protected]", "", {}, "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA=="],diff --git a/package.json b/package.jsonindex d89b7d5d..8d75cb6a 100644--- a/package.json+++ b/package.json@@ -14,11 +14,21 @@"./views": "./src/views/index.ts","./validation": "./src/validation.ts","./primitives": "./src/primitives.ts",+ "./architecture": "./src/architecture.ts",+ "./character": "./src/character.ts",+ "./vehicle": "./src/vehicle.ts",+ "./material-recipes": "./src/material-recipes.ts",+ "./material-resources": "./src/material-resources.ts",+ "./material-recipe-runtime": "./src/material-recipe-runtime.ts",+ "./material-recipe-prompt": "./src/material-recipe-prompt.ts",+ "./material-metrics": "./src/material-metrics.ts","./prompt": "./src/prompt.ts","./prompt-api": "./src/prompt-api.ts","./list-primitives": "./src/list-primitives.ts","./metrics": "./src/metrics.ts","./inspect": "./src/inspect.ts",+ "./contracts": "./src/contracts/index.ts",+ "./qa": "./src/qa/index.ts","./composer": "./src/composer/index.ts","./composer/agent": "./src/composer/agent/index.ts"},@@ -45,6 +55,7 @@"@types/three": "^0.185.1","acorn": "^8.17.0","acorn-walk": "^8.3.5",+ "gltf-validator": "2.0.0-dev.3.10","manifold-3d": "^3.5.1","sharp": "^0.35.3","three": "0.185.1",diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snapindex b273f162..332859fd 100644--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap@@ -5,6 +5,21 @@ exports[`system prompt embeds the generated catalog api section snapshot (reviewcreateRoot(name: string) // Creates the root Object3D for an asset. Call first in build().createPivot(name: string, position?: [x, y, z], parent?: Object3D)// Creates an empty pivot node for skeletal animation. Name is auto-prefixed with \`Joint_\`.+createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })+ // Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest+ // frames, local axes, end effectors, contacts, and semantic metadata.+ // NOTE: Use only the resolved body-plan graph. Offsets are local to the previous joint;+ // contact end effectors must land at world Y=0.+createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })+ // Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for+ // chassis, support, steering, and propulsion.+ // NOTE: Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use+ // declared support/propulsion sockets, not wheel rules.+createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })+ // Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact+ // marker, +Z spin frame, and optional steering pivot.+ // NOTE: Keep tire, rim, and hub descendants concentric at the axle pivot. Reuse one geometry+ // set across matching wheels.createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })// Creates a mesh, optionally wrapped in a pivot, and attaches it to \`opts.parent\`. \`rotation\`// is in DEGREES (like rotationTrack), NOT radians: [0, 0, 90] is a quarter turn; [0, 0, 1.57]@@ -45,6 +60,26 @@ createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?:// (e.g. \`Roof\`) the engine can lift to reveal the interior.// NOTE: The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does// this for you. Drop it onto the walls (position.y = wall height).+createGableRoof(name, material, { spanX, spanZ, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })+ // Explicit-axis gable roof using unambiguous footprint spans. Each face owns a rigid frame+ // with ridge tangent, outward normal, downhill direction, ridge/eave endpoints, dimensions,+ // and a live local-to-world transform.+ // NOTE: Prefer this over width/depth roof math. ridgeAxis is the direction of the ridge; roof+ // panels run along each returned face downhill direction.+createGableEndPanel(name, material, { span, rise, thickness?, ridgeAxis?: 'x'|'z', side?: 'positive'|'negative', openings?: [{ id?, offset?, bottom?, width, height }], parent? })+ // Exact thick triangular end closure for a gable roof, with optional rectangular openings cut+ // from the geometry and semantic boundary metadata.+createGableShell(name, { wall, roof, floor?, gable? }, { spanX, spanZ, wallHeight?, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, wallThickness?, floorThickness?, closedEnds?, enterable?, openings?, gableOpenings?, parent? })+ // Closed-by-default, correct-by-construction gable building: hollow room, floor, two opposing+ // roof slopes, two complete gable ends, and a real front doorway when enterable.+ // NOTE: Use for complete gable buildings. It stamps wall, floor, slope, gable, opening,+ // adjacency, coverage, and separability semantics for deterministic QA and roof-off views.+createRoofSurfaceLayout(name, material, { face, kind: 'panels'|'shingles'|'seams'|'corrugations', parent?, panelWidth?, rowHeight?, spacing?, thickness? })+ // Places roof-local panels, shingles, seams, or corrugations from a returned RoofFaceFrame,+ // so repeated elements run ridge-to-eave for either ridge axis without manual Euler+ // rotations.+ // NOTE: Always pass the face object returned by createGableRoof/createGableShell. Never infer+ // the panel rotation from world axes.createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })// A straight flight of stairs: box treads (with optional risers) climbing totalRise over// totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in@@ -129,17 +164,29 @@ bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?:// MaterialsgameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })// Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.+await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })+ // Resolves a versioned portable+ // bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF+ // 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.basicMaterial(color, opts?: { transparent, opacity })// Unlit flat material. For UI / effects where lighting is baked in.glassMaterial(color, opts?: { opacity, roughness, metalness })// Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.lambertMaterial(color, opts?: { flatShading, emissive })// Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.-pbrMaterial({ albedo?, normal?, roughness?, metalness?, emissive?, aoMap? })- // Full PBR material. Each slot can be a hex color/scalar or a Texture loaded via loadTexture.- // Exports as glTF pbrMetallicRoughness.+pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, aoMap?, alphaMode?, alphaCutoff?, doubleSided? })+ // 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.+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.// Instancing (share geometry+material; smaller GLBs)+createWheelGeometrySet(radius: number, width: number)+ // Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.cloneGeometry(geo: BufferGeometry)// Returns the same geometry reference. Use it as a signal that you are intentionally sharing// geometry across multiple parts; gltf-transform dedupes on export.@@ -228,9 +275,10 @@ panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)// only the clean strip.// Textures (loadTexture is async)-await loadTexture(source: string | Buffer | Uint8Array)- // Loads a PNG/JPG/WebP image into a Three.js Texture. Stashes the encoded bytes on- // userData.encoded so GLB export is lossless.+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.@@ -254,7 +302,7 @@ spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')countTriangles(root: Object3D) // Sums triangle count across every mesh in the subtree.countMaterials(root: Object3D) // Unique material count (by reference) across the subtree.getJointNames(root: Object3D) // All node names beginning with \`Joint_\`. Use to sanity-check animation targets.-validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment')+validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture' | 'vegetation' | 'vehicle')// Warns on category-appropriate triangle / material budgets."`;@@ -265,6 +313,29 @@ createRoot(name: string) // Creates the root Object3D for an asset. Call firstcreatePivot(name: string, position?: [x, y, z], parent?: Object3D)// Creates an empty pivot node for skeletal animation. Name is auto-prefixed with \`Joint_\`.// e.g. const hip = createPivot('Hip', [0, 1, 0], root);+createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })+ // Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest+ // frames, local axes, end effectors, contacts, and semantic metadata.+ // NOTE: Use only the resolved body-plan graph. Offsets are local to the previous joint;+ // contact end effectors must land at world Y=0.+ // e.g. const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side:+ // 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left',+ // offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });+createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })+ // Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for+ // chassis, support, steering, and propulsion.+ // NOTE: Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use+ // declared support/propulsion sockets, not wheel rules.+ // e.g. const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2,+ // 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });+createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })+ // Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact+ // marker, +Z spin frame, and optional steering pivot.+ // NOTE: Keep tire, rim, and hub descendants concentric at the axle pivot. Reuse one geometry+ // set across matching wheels.+ // e.g. createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width:+ // 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true,+ // geometries: wheelGeo, parent: frame.root });createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })// Creates a mesh, optionally wrapped in a pivot, and attaches it to \`opts.parent\`. \`rotation\`// is in DEGREES (like rotationTrack), NOT radians: [0, 0, 90] is a quarter turn; [0, 0, 1.57]@@ -321,6 +392,34 @@ createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?:// this for you. Drop it onto the walls (position.y = wall height).// e.g. const { root: roof } = createRoofPlanes('Roof', shingle, { width: 5, depth: 4, height:// 1.6, overhang: 0.4, ridgeAxis: 'x', parent: root }); roof.position.y = 2.8;+createGableRoof(name, material, { spanX, spanZ, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })+ // Explicit-axis gable roof using unambiguous footprint spans. Each face owns a rigid frame+ // with ridge tangent, outward normal, downhill direction, ridge/eave endpoints, dimensions,+ // and a live local-to-world transform.+ // NOTE: Prefer this over width/depth roof math. ridgeAxis is the direction of the ridge; roof+ // panels run along each returned face downhill direction.+ // e.g. const roof = createGableRoof('Roof', shingles, { spanX: 8, spanZ: 5, pitchDegrees: 35,+ // overhang: 0.35, ridgeAxis: 'x', parent: root });+createGableEndPanel(name, material, { span, rise, thickness?, ridgeAxis?: 'x'|'z', side?: 'positive'|'negative', openings?: [{ id?, offset?, bottom?, width, height }], parent? })+ // Exact thick triangular end closure for a gable roof, with optional rectangular openings cut+ // from the geometry and semantic boundary metadata.+ // e.g. createGableEndPanel('FrontGable', siding, { span: 5, rise: 1.8, ridgeAxis: 'x', side:+ // 'positive', parent: root });+createGableShell(name, { wall, roof, floor?, gable? }, { spanX, spanZ, wallHeight?, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, wallThickness?, floorThickness?, closedEnds?, enterable?, openings?, gableOpenings?, parent? })+ // Closed-by-default, correct-by-construction gable building: hollow room, floor, two opposing+ // roof slopes, two complete gable ends, and a real front doorway when enterable.+ // NOTE: Use for complete gable buildings. It stamps wall, floor, slope, gable, opening,+ // adjacency, coverage, and separability semantics for deterministic QA and roof-off views.+ // e.g. const house = createGableShell('House', { wall: plaster, roof: shingles }, { spanX: 8,+ // spanZ: 5, wallHeight: 2.8, pitchDegrees: 35, ridgeAxis: 'x', parent: root });+createRoofSurfaceLayout(name, material, { face, kind: 'panels'|'shingles'|'seams'|'corrugations', parent?, panelWidth?, rowHeight?, spacing?, thickness? })+ // Places roof-local panels, shingles, seams, or corrugations from a returned RoofFaceFrame,+ // so repeated elements run ridge-to-eave for either ridge axis without manual Euler+ // rotations.+ // NOTE: Always pass the face object returned by createGableRoof/createGableShell. Never infer+ // the panel rotation from world axes.+ // e.g. for (const face of roof.faces) createRoofSurfaceLayout('Panels_' + face.side, metal, {+ // face, kind: 'panels', parent: roof.root });createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })// A straight flight of stairs: box treads (with optional risers) climbing totalRise over// totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in@@ -408,13 +507,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 quad = foliageCardGeo({ width: 4, height: 6, yPivot: 0 });- // createPart('Mesh_Fern', quad, gameMaterial(0x3a6b2e), { parent: root });+ // 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 });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 bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });- // createPart('Mesh_Bush', bush, gameMaterial(0x2f4a1a), { parent: root });+ // 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 });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.@@ -439,6 +540,13 @@ bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?:gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })// Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.// e.g. const mat = gameMaterial(0x8b7355, { roughness: 0.9 });+await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })+ // Resolves a versioned portable+ // bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF+ // 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.+ // e.g. const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#6b4328' });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 });@@ -448,13 +556,22 @@ glassMaterial(color, opts?: { opacity, roughness, metalness })lambertMaterial(color, opts?: { flatShading, emissive })// Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.// e.g. const mat = lambertMaterial(0x2a4d14, { flatShading: true });-pbrMaterial({ albedo?, normal?, roughness?, metalness?, emissive?, aoMap? })- // Full PBR material. Each slot can be a hex color/scalar or a Texture loaded via loadTexture.- // Exports as glTF pbrMetallicRoughness.+pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, aoMap?, alphaMode?, alphaCutoff?, doubleSided? })+ // 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 });+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 });// Instancing (share geometry+material; smaller GLBs)+createWheelGeometrySet(radius: number, width: number)+ // Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.+ // e.g. const wheelGeo = createWheelGeometrySet(0.45, 0.22);cloneGeometry(geo: BufferGeometry)// Returns the same geometry reference. Use it as a signal that you are intentionally sharing// geometry across multiple parts; gltf-transform dedupes on export.@@ -587,13 +704,14 @@ panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)// = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed// Textures (loadTexture is async)-await loadTexture(source: string | Buffer | Uint8Array)- // Loads a PNG/JPG/WebP image into a Three.js Texture. Stashes the encoded bytes on- // userData.encoded so GLB export is lossless.+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');+ // e.g. const wood = await loadTexture('./textures/oak-albedo.png', { usage: 'albedo' });// Animation — keyframes use "rotation"/"position"/"scale" keys, NOT "value"rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')@@ -627,7 +745,7 @@ countMaterials(root: Object3D) // Unique material count (by reference) across t// e.g. const mats = countMaterials(root);getJointNames(root: Object3D) // All node names beginning with \`Joint_\`. Use to sanity-check animation targets.// e.g. const joints = getJointNames(root);-validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment')+validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture' | 'vegetation' | 'vehicle')// Warns on category-appropriate triangle / material budgets.// e.g. const v = validateAsset(root, 'prop');"`;diff --git a/src/__tests__/architecture-expansion-gate.test.ts b/src/__tests__/architecture-expansion-gate.test.tsnew file mode 100644index 00000000..0da8850f--- /dev/null+++ b/src/__tests__/architecture-expansion-gate.test.ts@@ -0,0 +1,911 @@+/**+ * W8 G-ROOF-EXPAND provider-free ablation.+ *+ * Candidate shed/hip scaffolds and an explicit roof-UV remap stay test-only.+ * This file measures whether either candidate earns a public P2 surface over+ * the existing freeform primitives and face-local gable geometry.+ */+import { createHash } from 'node:crypto';++import { WebIO } from '@gltf-transform/core';+import { beforeAll, describe, expect, test } from 'bun:test';+import sharp from 'sharp';+import * as THREE from 'three';++import { createGableShell, type RidgeAxis } from '../architecture';+import {+ createAssetIntentV1,+ readSemanticMetadataV1,+ readSemanticMetadataV1FromExtras,+ stampSemanticMetadataV1,+ type AssetIntentV1,+ type SemanticLocalFrameV1,+} from '../contracts';+import { optimizeGlbBytes, renderSceneToGLB } from '../render';+import { loadTexture } from '../textures';++const PUBLIC_HELPER_MINIMUM_LIFT = 0.15;+const EPSILON = 1e-5;++type RoofType = 'shed' | 'hip';+type Arm = 'baseline' | 'candidate';++interface RoofGateCase {+ id: string;+ type: RoofType;+ ridgeAxis: RidgeAxis;+ spanX: number;+ spanZ: number;+ wallHeight: number;+ rise: number;+ overhang: number;+ transform: {+ position: readonly [number, number, number];+ rotation: readonly [number, number, number];+ };+}++interface FaceDefinition {+ id: string;+ role: string;+ vertices: readonly THREE.Vector3[];+}++interface BuiltRoofArm {+ root: THREE.Group;+ roof: THREE.Group;+ intent: AssetIntentV1;+ expectedFaces: readonly FaceDefinition[];+}++interface ArmMeasurement {+ id: string;+ structuralPass: boolean;+ faceCount: number;+ frameCount: number;+ validatorErrors: number;+ validatorWarnings: number;+ glbBytes: number;+ glbSha256: string;+ repeatGlbSha256: string;+ byteStable: boolean;+}++interface UvMeasurement {+ id: string;+ arm: Arm;+ directionalPass: boolean;+ initialValidatorErrors: number;+ initialValidatorWarnings: number;+ rebakeValidatorErrors: number;+ rebakeValidatorWarnings: number;+ initialGlbSha256: string;+ rebakedGlbSha256: string;+ texturedMaterials: number;+}++const ROOF_GATE_CORPUS = Object.freeze([+ {+ id: 'shed-ridge-x-wide',+ type: 'shed',+ ridgeAxis: 'x',+ spanX: 8,+ spanZ: 5,+ wallHeight: 3,+ rise: 1.4,+ overhang: 0.35,+ transform: { position: [0, 0, 0], rotation: [0, 0, 0] },+ },+ {+ id: 'shed-ridge-z-long',+ type: 'shed',+ ridgeAxis: 'z',+ spanX: 5,+ spanZ: 9,+ wallHeight: 3.2,+ rise: 1.1,+ overhang: 0.45,+ transform: { position: [2.2, 0.4, -3.1], rotation: [0.04, 0.61, -0.03] },+ },+ {+ id: 'shed-ridge-x-square',+ type: 'shed',+ ridgeAxis: 'x',+ spanX: 6,+ spanZ: 6,+ wallHeight: 2.7,+ rise: 2,+ overhang: 0.2,+ transform: { position: [-1.7, 0.2, 2.8], rotation: [-0.02, -0.37, 0.05] },+ },+ {+ id: 'shed-ridge-z-steep',+ type: 'shed',+ ridgeAxis: 'z',+ spanX: 4,+ spanZ: 7,+ wallHeight: 4.1,+ rise: 2.6,+ overhang: 0.6,+ transform: { position: [4.3, 1.1, 1.6], rotation: [0.06, 0.22, -0.04] },+ },+ {+ id: 'hip-ridge-x-wide',+ type: 'hip',+ ridgeAxis: 'x',+ spanX: 9,+ spanZ: 5,+ wallHeight: 3,+ rise: 1.8,+ overhang: 0.35,+ transform: { position: [0, 0, 0], rotation: [0, 0, 0] },+ },+ {+ id: 'hip-ridge-z-long',+ type: 'hip',+ ridgeAxis: 'z',+ spanX: 5,+ spanZ: 10,+ wallHeight: 3.4,+ rise: 2.1,+ overhang: 0.4,+ transform: { position: [-3.4, 0.5, -2.2], rotation: [0.03, 0.73, 0.02] },+ },+ {+ id: 'hip-ridge-x-square',+ type: 'hip',+ ridgeAxis: 'x',+ spanX: 6,+ spanZ: 6,+ wallHeight: 2.8,+ rise: 1.6,+ overhang: 0.25,+ transform: { position: [1.3, 0.3, 3.7], rotation: [-0.03, -0.48, 0.04] },+ },+ {+ id: 'hip-ridge-z-square',+ type: 'hip',+ ridgeAxis: 'z',+ spanX: 7,+ spanZ: 7,+ wallHeight: 3.6,+ rise: 2.4,+ overhang: 0.55,+ transform: { position: [3.8, 0.8, -1.4], rotation: [0.05, 0.31, -0.02] },+ },+] as const satisfies readonly RoofGateCase[]);++const UV_GATE_CORPUS = Object.freeze([+ { id: 'gable-uv-ridge-x', ridgeAxis: 'x', spanX: 8, spanZ: 5, rise: 1.7, overhang: 0.35 },+ { id: 'gable-uv-ridge-z', ridgeAxis: 'z', spanX: 5, spanZ: 8, rise: 1.7, overhang: 0.35 },+] as const);++const sha256 = (value: string | Uint8Array): string =>+ createHash('sha256').update(value).digest('hex');++function canonicalJson(value: unknown): string {+ return `${JSON.stringify(value, null, 2)}\n`;+}++function semantic<T extends THREE.Object3D>(+ node: T,+ roles: readonly string[],+ frames: readonly SemanticLocalFrameV1[] = [],+): T {+ return stampSemanticMetadataV1(node, { roles, frames });+}++function vectorKey(value: THREE.Vector3): string {+ return value+ .toArray()+ .map((entry) => Math.round(entry * 1_000_000) / 1_000_000)+ .join(',');+}++function normalizedVertices(vertices: readonly THREE.Vector3[]): THREE.Vector3[] {+ const seen = new Set<string>();+ const copy = vertices+ .filter((vertex) => {+ const key = vectorKey(vertex);+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ })+ .map((vertex) => vertex.clone());+ if (copy.length < 3) throw new TypeError('A roof face needs at least three unique vertices.');+ const normal = copy[1]!.clone().sub(copy[0]!).cross(copy[2]!.clone().sub(copy[0]!));+ if (normal.y < 0) copy.reverse();+ return copy;+}++function faceGeometry(vertices: readonly THREE.Vector3[]): THREE.BufferGeometry {+ const ordered = normalizedVertices(vertices);+ const geometry = new THREE.BufferGeometry();+ geometry.setAttribute(+ 'position',+ new THREE.Float32BufferAttribute(+ ordered.flatMap((vertex) => vertex.toArray()),+ 3,+ ),+ );+ geometry.setAttribute(+ 'uv',+ new THREE.Float32BufferAttribute(+ ordered.flatMap((vertex) => [vertex.x, vertex.z]),+ 2,+ ),+ );+ geometry.setIndex(ordered.length === 3 ? [0, 1, 2] : [0, 1, 2, 0, 2, 3]);+ geometry.computeVertexNormals();+ return geometry;+}++function roofFaceDefinitions(spec: RoofGateCase): FaceDefinition[] {+ const halfX = spec.spanX / 2 + spec.overhang;+ const halfZ = spec.spanZ / 2 + spec.overhang;+ if (spec.type === 'shed') {+ return spec.ridgeAxis === 'x'+ ? [+ {+ id: 'surface',+ role: 'roof.shed.surface',+ vertices: [+ new THREE.Vector3(-halfX, spec.rise, -halfZ),+ new THREE.Vector3(halfX, spec.rise, -halfZ),+ new THREE.Vector3(halfX, 0, halfZ),+ new THREE.Vector3(-halfX, 0, halfZ),+ ],+ },+ ]+ : [+ {+ id: 'surface',+ role: 'roof.shed.surface',+ vertices: [+ new THREE.Vector3(-halfX, spec.rise, -halfZ),+ new THREE.Vector3(-halfX, spec.rise, halfZ),+ new THREE.Vector3(halfX, 0, halfZ),+ new THREE.Vector3(halfX, 0, -halfZ),+ ],+ },+ ];+ }++ if (spec.ridgeAxis === 'x') {+ const ridgeHalf = Math.max(0, halfX - halfZ);+ const ridgeLeft = new THREE.Vector3(-ridgeHalf, spec.rise, 0);+ const ridgeRight = new THREE.Vector3(ridgeHalf, spec.rise, 0);+ return [+ {+ id: 'negative',+ role: 'roof.hip.negative',+ vertices: [+ new THREE.Vector3(-halfX, 0, -halfZ),+ new THREE.Vector3(halfX, 0, -halfZ),+ ridgeRight,+ ridgeLeft,+ ],+ },+ {+ id: 'positive',+ role: 'roof.hip.positive',+ vertices: [+ new THREE.Vector3(halfX, 0, halfZ),+ new THREE.Vector3(-halfX, 0, halfZ),+ ridgeLeft,+ ridgeRight,+ ],+ },+ {+ id: 'left',+ role: 'roof.hip.left',+ vertices: [+ new THREE.Vector3(-halfX, 0, halfZ),+ new THREE.Vector3(-halfX, 0, -halfZ),+ ridgeLeft,+ ],+ },+ {+ id: 'right',+ role: 'roof.hip.right',+ vertices: [+ new THREE.Vector3(halfX, 0, -halfZ),+ new THREE.Vector3(halfX, 0, halfZ),+ ridgeRight,+ ],+ },+ ];+ }++ const ridgeHalf = Math.max(0, halfZ - halfX);+ const ridgeBack = new THREE.Vector3(0, spec.rise, -ridgeHalf);+ const ridgeFront = new THREE.Vector3(0, spec.rise, ridgeHalf);+ return [+ {+ id: 'left',+ role: 'roof.hip.left',+ vertices: [+ new THREE.Vector3(-halfX, 0, halfZ),+ new THREE.Vector3(-halfX, 0, -halfZ),+ ridgeBack,+ ridgeFront,+ ],+ },+ {+ id: 'right',+ role: 'roof.hip.right',+ vertices: [+ new THREE.Vector3(halfX, 0, -halfZ),+ new THREE.Vector3(halfX, 0, halfZ),+ ridgeFront,+ ridgeBack,+ ],+ },+ {+ id: 'negative',+ role: 'roof.hip.negative',+ vertices: [+ new THREE.Vector3(-halfX, 0, -halfZ),+ new THREE.Vector3(halfX, 0, -halfZ),+ ridgeBack,+ ],+ },+ {+ id: 'positive',+ role: 'roof.hip.positive',+ vertices: [+ new THREE.Vector3(halfX, 0, halfZ),+ new THREE.Vector3(-halfX, 0, halfZ),+ ridgeFront,+ ],+ },+ ];+}++function addShellEnvelope(root: THREE.Group, spec: RoofGateCase, material: THREE.Material): void {+ const thickness = 0.15;+ const walls = [+ [+ 'front',+ new THREE.BoxGeometry(thickness, spec.wallHeight, spec.spanZ),+ [spec.spanX / 2, spec.wallHeight / 2, 0],+ ],+ [+ 'back',+ new THREE.BoxGeometry(thickness, spec.wallHeight, spec.spanZ),+ [-spec.spanX / 2, spec.wallHeight / 2, 0],+ ],+ [+ 'left',+ new THREE.BoxGeometry(spec.spanX, spec.wallHeight, thickness),+ [0, spec.wallHeight / 2, -spec.spanZ / 2],+ ],+ [+ 'right',+ new THREE.BoxGeometry(spec.spanX, spec.wallHeight, thickness),+ [0, spec.wallHeight / 2, spec.spanZ / 2],+ ],+ ] as const;+ for (const [id, geometry, position] of walls) {+ const wall = semantic(new THREE.Mesh(geometry, material), [`wall.${id}`]);+ wall.name = `Wall_${id}`;+ wall.position.set(position[0], position[1], position[2]);+ root.add(wall);+ }+ const floor = semantic(+ new THREE.Mesh(new THREE.BoxGeometry(spec.spanX, 0.1, spec.spanZ), material),+ ['floor'],+ );+ floor.name = 'Floor';+ floor.position.y = -0.05;+ root.add(floor);+}++function candidateFrames(spec: RoofGateCase, face: FaceDefinition): SemanticLocalFrameV1[] {+ const ordered = normalizedVertices(face.vertices);+ const center = ordered+ .reduce((sum, vertex) => sum.add(vertex), new THREE.Vector3())+ .multiplyScalar(1 / ordered.length);+ const normal = ordered[1]!+ .clone()+ .sub(ordered[0]!)+ .cross(ordered[2]!.clone().sub(ordered[0]!))+ .normalize();+ const requestedRidge =+ spec.ridgeAxis === 'x' ? new THREE.Vector3(1, 0, 0) : new THREE.Vector3(0, 0, 1);+ const ridge = requestedRidge+ .clone()+ .addScaledVector(normal, -requestedRidge.dot(normal))+ .normalize();+ // Match the public gable RoofFaceFrame's right-handed basis: X is ridge,+ // Y is outward normal, and Z is downhill, so X cross Y must equal Z.+ const downhill = ridge.clone().cross(normal).normalize();+ const rotation = new THREE.Quaternion()+ .setFromRotationMatrix(new THREE.Matrix4().makeBasis(ridge, normal, downhill))+ .normalize();+ return [+ {+ id: 'surface',+ translation: center.toArray(),+ rotation: rotation.toArray(),+ },+ ];+}++function buildRoofArm(spec: RoofGateCase, arm: Arm): BuiltRoofArm {+ const root = semantic(new THREE.Group(), [`architecture.shell.${spec.type}`]);+ root.name = `${arm}_${spec.id}`;+ root.position.set(...spec.transform.position);+ root.rotation.set(...spec.transform.rotation);+ const wallMaterial = new THREE.MeshStandardMaterial({ color: 0xc8ad82, roughness: 0.9 });+ const roofMaterial = new THREE.MeshStandardMaterial({ color: 0x59616d, roughness: 0.82 });+ addShellEnvelope(root, spec, wallMaterial);++ const roof = semantic(new THREE.Group(), ['roof.assembly']);+ roof.name = 'Roof';+ roof.position.y = spec.wallHeight;+ root.add(roof);+ const expectedFaces = roofFaceDefinitions(spec);+ for (const face of expectedFaces) {+ const mesh = semantic(+ new THREE.Mesh(faceGeometry(face.vertices), roofMaterial),+ [face.role],+ arm === 'candidate' ? candidateFrames(spec, face) : [],+ );+ mesh.name = `Roof_${face.id}`;+ roof.add(mesh);+ }+ root.updateMatrixWorld(true);++ const halfRun = (spec.ridgeAxis === 'x' ? spec.spanZ : spec.spanX) / 2;+ const intent = createAssetIntentV1({+ category: 'architecture',+ architecture: {+ subtype: `${spec.type}-roof building`,+ enterable: false,+ footprint: { spanX: spec.spanX, spanZ: spec.spanZ },+ wallHeight: spec.wallHeight,+ roof: {+ type: spec.type,+ ridgeAxis: spec.ridgeAxis,+ rise: spec.rise,+ pitchDegrees: THREE.MathUtils.radToDeg(Math.atan2(spec.rise, halfRun)),+ overhang: spec.overhang,+ closedEnds: false,+ },+ },+ });+ return { root, roof, intent, expectedFaces };+}++function sceneFaceSignature(roof: THREE.Group): string[] {+ return roof.children+ .filter((node): node is THREE.Mesh => node instanceof THREE.Mesh)+ .map((mesh) => {+ const position = mesh.geometry.getAttribute('position') as THREE.BufferAttribute;+ const vertices = new Set<string>();+ for (let index = 0; index < position.count; index++) {+ vertices.add(+ vectorKey(+ new THREE.Vector3(position.getX(index), position.getY(index), position.getZ(index)),+ ),+ );+ }+ return [...vertices].sort().join('|');+ })+ .sort();+}++function expectedFaceSignature(faces: readonly FaceDefinition[]): string[] {+ return faces.map((face) => [...new Set(face.vertices.map(vectorKey))].sort().join('|')).sort();+}++function faceNormal(vertices: readonly THREE.Vector3[]): THREE.Vector3 {+ const ordered = normalizedVertices(vertices);+ return ordered[1]!+ .clone()+ .sub(ordered[0]!)+ .cross(ordered[2]!.clone().sub(ordered[0]!))+ .normalize();+}++function everyTriangleFacesUp(mesh: THREE.Mesh): boolean {+ const position = mesh.geometry.getAttribute('position') as THREE.BufferAttribute;+ const index = mesh.geometry.getIndex();+ const draw = index+ ? Array.from({ length: index.count }, (_, offset) => index.getX(offset))+ : Array.from({ length: position.count }, (_, offset) => offset);+ if (draw.length === 0 || draw.length % 3 !== 0) return false;+ for (let offset = 0; offset < draw.length; offset += 3) {+ const a = new THREE.Vector3().fromBufferAttribute(position, draw[offset]!);+ const b = new THREE.Vector3().fromBufferAttribute(position, draw[offset + 1]!);+ const c = new THREE.Vector3().fromBufferAttribute(position, draw[offset + 2]!);+ const normal = b.sub(a).cross(c.sub(a));+ if (!normal.toArray().every(Number.isFinite) || normal.lengthSq() <= EPSILON || normal.y <= 0) {+ return false;+ }+ }+ return true;+}++function frameMatchesFace(node: THREE.Object3D, face: FaceDefinition): boolean {+ const frames = readSemanticMetadataV1(node)?.frames ?? [];+ if (frames.length !== 1 || frames[0]?.id !== 'surface') return false;+ const frame = frames[0];+ const translation = new THREE.Vector3().fromArray(frame.translation);+ const rotation = new THREE.Quaternion().fromArray(frame.rotation);+ const expectedCenter = normalizedVertices(face.vertices)+ .reduce((sum, vertex) => sum.add(vertex), new THREE.Vector3())+ .multiplyScalar(1 / normalizedVertices(face.vertices).length);+ const expectedNormal = faceNormal(face.vertices);+ const frameNormal = new THREE.Vector3(0, 1, 0).applyQuaternion(rotation).normalize();+ return (+ translation.distanceTo(expectedCenter) <= EPSILON &&+ Math.abs(rotation.length() - 1) <= EPSILON &&+ frameNormal.dot(expectedNormal) >= 1 - EPSILON+ );+}++function structurePass(arm: BuiltRoofArm, armName: Arm): boolean {+ const meshes = arm.roof.children.filter((node): node is THREE.Mesh => node instanceof THREE.Mesh);+ if (+ sceneFaceSignature(arm.roof).join(';') !== expectedFaceSignature(arm.expectedFaces).join(';')+ ) {+ return false;+ }+ for (const [index, mesh] of meshes.entries()) {+ const roles = readSemanticMetadataV1(mesh)?.roles ?? [];+ if (!roles.some((role) => role.startsWith('roof.'))) return false;+ if (!everyTriangleFacesUp(mesh)) return false;+ const face = arm.expectedFaces[index];+ if (!face) return false;+ const frameCount = readSemanticMetadataV1(mesh)?.frames.length ?? 0;+ if (armName === 'baseline' ? frameCount !== 0 : !frameMatchesFace(mesh, face)) return false;+ }+ arm.root.updateMatrixWorld(true);+ const actualBounds = new THREE.Box3();+ for (const mesh of meshes) {+ const position = mesh.geometry.getAttribute('position') as THREE.BufferAttribute;+ for (let index = 0; index < position.count; index++) {+ actualBounds.expandByPoint(+ mesh.localToWorld(new THREE.Vector3().fromBufferAttribute(position, index)),+ );+ }+ }+ const expectedBounds = new THREE.Box3();+ for (const face of arm.expectedFaces) {+ for (const vertex of face.vertices) {+ expectedBounds.expandByPoint(arm.roof.localToWorld(vertex.clone()));+ }+ }+ return (+ !actualBounds.isEmpty() &&+ actualBounds.min.distanceTo(expectedBounds.min) <= EPSILON &&+ actualBounds.max.distanceTo(expectedBounds.max) <= EPSILON+ );+}++async function measureRoofArm(spec: RoofGateCase, armName: Arm): Promise<ArmMeasurement> {+ const arm = buildRoofArm(spec, armName);+ const first = await renderSceneToGLB(arm.root, { intent: arm.intent, optimize: 'off' });+ const repeat = await renderSceneToGLB(arm.root, { intent: arm.intent, optimize: 'off' });+ const document = await new WebIO().readBinary(first.bytes);+ const exportedFaces = document+ .getRoot()+ .listNodes()+ .filter((node) => node.getName().startsWith('Roof_'));+ const exportedFaceCount = exportedFaces.length;+ const frameCount = exportedFaces.reduce(+ (count, node) =>+ count + (readSemanticMetadataV1FromExtras(node.getExtras())?.frames.length ?? 0),+ 0,+ );+ return {+ id: spec.id,+ structuralPass:+ structurePass(arm, armName) &&+ exportedFaceCount === arm.expectedFaces.length &&+ frameCount === (armName === 'candidate' ? arm.expectedFaces.length : 0) &&+ first.gltfValidation.issues.numErrors === 0,+ faceCount: arm.expectedFaces.length,+ frameCount,+ validatorErrors: first.gltfValidation.issues.numErrors,+ validatorWarnings: first.gltfValidation.issues.numWarnings,+ glbBytes: first.bytes.byteLength,+ glbSha256: sha256(first.bytes),+ repeatGlbSha256: sha256(repeat.bytes),+ byteStable: sha256(first.bytes) === sha256(repeat.bytes),+ };+}++async function directionalPatternMaterial(): Promise<THREE.MeshStandardMaterial> {+ const width = 2;+ const height = 4;+ const rows = [+ [230, 50, 45, 255],+ [230, 180, 45, 255],+ [55, 175, 90, 255],+ [55, 95, 220, 255],+ ] as const;+ const pixels = new Uint8Array(width * height * 4);+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) pixels.set(rows[y]!, (y * width + x) * 4);+ }+ const encoded = await sharp(Buffer.from(pixels), {+ raw: { width, height, channels: 4 },+ })+ .png({ compressionLevel: 9 })+ .toBuffer();+ const texture = await loadTexture(new Uint8Array(encoded), {+ usage: 'albedo',+ name: 'Roof_RidgeU_DownhillV_TestPattern',+ });+ texture.flipY = false;+ return new THREE.MeshStandardMaterial({ map: texture, color: 0xffffff, roughness: 0.8 });+}++function remapTopFaceUv(geometry: THREE.BufferGeometry): void {+ const position = geometry.getAttribute('position') as THREE.BufferAttribute;+ const normal = geometry.getAttribute('normal') as THREE.BufferAttribute;+ const uv = geometry.getAttribute('uv') as THREE.BufferAttribute;+ const xs: number[] = [];+ const zs: number[] = [];+ for (let index = 0; index < position.count; index++) {+ if (normal.getY(index) > 0.9) {+ xs.push(position.getX(index));+ zs.push(position.getZ(index));+ }+ }+ const minX = Math.min(...xs);+ const maxX = Math.max(...xs);+ const minZ = Math.min(...zs);+ const maxZ = Math.max(...zs);+ for (let index = 0; index < position.count; index++) {+ if (normal.getY(index) <= 0.9) continue;+ uv.setXY(+ index,+ (position.getX(index) - minX) / (maxX - minX),+ 1 - (position.getZ(index) - minZ) / (maxZ - minZ),+ );+ }+ uv.needsUpdate = true;+}++function correlation(left: readonly number[], right: readonly number[]): number {+ const leftMean = left.reduce((sum, value) => sum + value, 0) / left.length;+ const rightMean = right.reduce((sum, value) => sum + value, 0) / right.length;+ let numerator = 0;+ let leftSquare = 0;+ let rightSquare = 0;+ for (let index = 0; index < left.length; index++) {+ const a = left[index]! - leftMean;+ const b = right[index]! - rightMean;+ numerator += a * b;+ leftSquare += a * a;+ rightSquare += b * b;+ }+ return numerator / Math.sqrt(leftSquare * rightSquare);+}++async function inspectDirectionalUv(bytes: Uint8Array): Promise<{+ pass: boolean;+ texturedMaterials: number;+}> {+ const document = await new WebIO().readBinary(bytes);+ const texturedMaterials = document+ .getRoot()+ .listMaterials()+ .filter((material) => material.getBaseColorTexture() !== null).length;+ const roofNodes = document+ .getRoot()+ .listNodes()+ .filter((node) => node.getName().startsWith('Mesh_Roof_'));+ const passes = roofNodes.map((node) => {+ const primitive = node.getMesh()?.listPrimitives()[0];+ if (!primitive?.getMaterial()?.getBaseColorTexture()) return false;+ const positions = primitive?.getAttribute('POSITION')?.getArray();+ const normals = primitive?.getAttribute('NORMAL')?.getArray();+ const uvs = primitive?.getAttribute('TEXCOORD_0')?.getArray();+ if (!positions || !normals || !uvs) return false;+ const x: number[] = [];+ const z: number[] = [];+ const u: number[] = [];+ const v: number[] = [];+ for (let index = 0; index < normals.length / 3; index++) {+ if ((normals[index * 3 + 1] ?? -1) <= 0.9) continue;+ x.push(positions[index * 3] ?? 0);+ z.push(positions[index * 3 + 2] ?? 0);+ u.push(uvs[index * 2] ?? 0);+ v.push(uvs[index * 2 + 1] ?? 0);+ }+ return (+ x.length === 4 &&+ Math.abs(correlation(x, u)) > 1 - EPSILON &&+ Math.abs(correlation(z, v)) > 1 - EPSILON &&+ Math.abs(correlation(x, v)) < EPSILON &&+ Math.abs(correlation(z, u)) < EPSILON+ );+ });+ return { pass: roofNodes.length === 2 && passes.every(Boolean), texturedMaterials };+}++async function measureUvCase(+ spec: (typeof UV_GATE_CORPUS)[number],+ arm: Arm,+): Promise<UvMeasurement> {+ const wall = new THREE.MeshStandardMaterial({ color: 0xc8ad82, roughness: 0.9 });+ const roofMaterial = await directionalPatternMaterial();+ const shell = createGableShell(+ `Uv_${arm}_${spec.id}`,+ { wall, roof: roofMaterial },+ {+ spanX: spec.spanX,+ spanZ: spec.spanZ,+ wallHeight: 3,+ rise: spec.rise,+ overhang: spec.overhang,+ ridgeAxis: spec.ridgeAxis,+ enterable: false,+ closedEnds: true,+ },+ );+ if (arm === 'candidate') {+ for (const slope of shell.roof.slopes) {+ if (!(slope instanceof THREE.Mesh)) continue;+ slope.geometry = slope.geometry.clone();+ remapTopFaceUv(slope.geometry);+ }+ }+ const halfRun = (spec.ridgeAxis === 'x' ? spec.spanZ : spec.spanX) / 2;+ const intent = createAssetIntentV1({+ category: 'architecture',+ architecture: {+ subtype: 'gable building',+ enterable: false,+ footprint: { spanX: spec.spanX, spanZ: spec.spanZ },+ wallHeight: 3,+ roof: {+ type: 'gable',+ ridgeAxis: spec.ridgeAxis,+ rise: spec.rise,+ pitchDegrees: THREE.MathUtils.radToDeg(Math.atan2(spec.rise, halfRun)),+ overhang: spec.overhang,+ closedEnds: true,+ },+ },+ });+ const initial = await renderSceneToGLB(shell.root, { intent, optimize: 'off' });+ const rebaked = await optimizeGlbBytes(initial.bytes, {+ mode: 'palette',+ category: 'architecture',+ });+ if (!rebaked) throw new Error('Expected the architecture UV fixture to rebake.');+ const initialInspection = await inspectDirectionalUv(initial.bytes);+ const rebakedInspection = await inspectDirectionalUv(rebaked.bytes);+ return {+ id: spec.id,+ arm,+ directionalPass: initialInspection.pass && rebakedInspection.pass,+ initialValidatorErrors: initial.gltfValidation.issues.numErrors,+ initialValidatorWarnings: initial.gltfValidation.issues.numWarnings,+ rebakeValidatorErrors: rebaked.gltfValidation.issues.numErrors,+ rebakeValidatorWarnings: rebaked.gltfValidation.issues.numWarnings,+ initialGlbSha256: sha256(initial.bytes),+ rebakedGlbSha256: sha256(rebaked.bytes),+ texturedMaterials: Math.min(+ initialInspection.texturedMaterials,+ rebakedInspection.texturedMaterials,+ ),+ };+}++let baselineRoof: ArmMeasurement[];+let candidateRoof: ArmMeasurement[];+let uv: UvMeasurement[];++beforeAll(async () => {+ baselineRoof = [];+ candidateRoof = [];+ for (const spec of ROOF_GATE_CORPUS) {+ baselineRoof.push(await measureRoofArm(spec, 'baseline'));+ candidateRoof.push(await measureRoofArm(spec, 'candidate'));+ }+ uv = [];+ for (const spec of UV_GATE_CORPUS) {+ uv.push(await measureUvCase(spec, 'baseline'));+ uv.push(await measureUvCase(spec, 'candidate'));+ }+}, 40_000);++describe('W8 G-ROOF-EXPAND provider-free gate', () => {+ test('fixed shed/hip candidate fixtures do not beat correct freeform controls', () => {+ const baselinePasses = baselineRoof.filter((entry) => entry.structuralPass).length;+ const candidatePasses = candidateRoof.filter((entry) => entry.structuralPass).length;+ const lift = candidatePasses / candidateRoof.length - baselinePasses / baselineRoof.length;+ expect(sha256(canonicalJson(ROOF_GATE_CORPUS))).toBe(+ '8facf880d90fb1e4d1b47c525ac732139dfddd00296590f265dd388215b19567',+ );+ expect(baselinePasses).toBe(8);+ expect(candidatePasses).toBe(8);+ expect(lift).toBe(0);+ expect(lift).toBeLessThan(PUBLIC_HELPER_MINIMUM_LIFT);+ expect(baselineRoof.every((entry) => entry.frameCount === 0)).toBe(true);+ expect(candidateRoof.every((entry) => entry.frameCount === entry.faceCount)).toBe(true);+ });++ test('all scaffold arms are exact, byte-stable, and Khronos-clean', () => {+ for (const entry of [...baselineRoof, ...candidateRoof]) {+ expect(entry.structuralPass, entry.id).toBe(true);+ expect(entry.validatorErrors, entry.id).toBe(0);+ expect(entry.validatorWarnings, entry.id).toBe(0);+ expect(entry.byteStable, entry.id).toBe(true);+ expect(entry.glbSha256, entry.id).toBe(entry.repeatGlbSha256);+ expect(entry.glbBytes, entry.id).toBeGreaterThan(1_000);+ }+ });++ test('existing face-local gable UVs already run ridge-to-eave through export and rebake', () => {+ expect(sha256(canonicalJson(UV_GATE_CORPUS))).toBe(+ '061cad5800ed7122da9f8e7d85bb97b013831b317b93d99c841a8178b6fb7640',+ );+ expect(uv).toHaveLength(4);+ for (const entry of uv) {+ expect(entry.directionalPass, `${entry.arm}:${entry.id}`).toBe(true);+ expect(entry.initialValidatorErrors, `${entry.arm}:${entry.id}`).toBe(0);+ expect(entry.initialValidatorWarnings, `${entry.arm}:${entry.id}`).toBe(0);+ expect(entry.rebakeValidatorErrors, `${entry.arm}:${entry.id}`).toBe(0);+ expect(entry.rebakeValidatorWarnings, `${entry.arm}:${entry.id}`).toBe(0);+ expect(entry.texturedMaterials, `${entry.arm}:${entry.id}`).toBeGreaterThanOrEqual(1);+ }+ const baselinePasses = uv.filter(+ (entry) => entry.arm === 'baseline' && entry.directionalPass,+ ).length;+ const candidatePasses = uv.filter(+ (entry) => entry.arm === 'candidate' && entry.directionalPass,+ ).length;+ expect(baselinePasses).toBe(2);+ expect(candidatePasses).toBe(2);+ expect(candidatePasses / 2 - baselinePasses / 2).toBe(0);+ });++ test('pins the complete negative gate report', () => {+ const report = {+ schemaVersion: 1,+ experimentId: 'kiln.architecture.roof-expansion.provider-free.v1',+ providerCalls: 0,+ publicHelperMinimumLift: PUBLIC_HELPER_MINIMUM_LIFT,+ scaffold: {+ corpusSha256: sha256(canonicalJson(ROOF_GATE_CORPUS)),+ baselinePasses: baselineRoof.filter((entry) => entry.structuralPass).length,+ candidatePasses: candidateRoof.filter((entry) => entry.structuralPass).length,+ total: ROOF_GATE_CORPUS.length,+ lift: 0,+ candidateOwnFixtureFrames: candidateRoof.reduce((sum, entry) => sum + entry.frameCount, 0),+ },+ uv: {+ corpusSha256: sha256(canonicalJson(UV_GATE_CORPUS)),+ baselinePasses: uv.filter((entry) => entry.arm === 'baseline' && entry.directionalPass)+ .length,+ candidatePasses: uv.filter((entry) => entry.arm === 'candidate' && entry.directionalPass)+ .length,+ totalPerArm: UV_GATE_CORPUS.length,+ lift: 0,+ },+ delegatedHumanLabels: 0,+ gate: 'closed',+ gateReason:+ 'Neither P2 candidate improves the fixed deterministic pass rate over the existing public surface; no public API expansion is justified.',+ artifactSha256: [...baselineRoof, ...candidateRoof].map((entry) => entry.glbSha256),+ uvArtifactSha256: uv.flatMap((entry) => [entry.initialGlbSha256, entry.rebakedGlbSha256]),+ } as const;+ expect(sha256(canonicalJson(report.artifactSha256))).toBe(+ 'ca879d9107e2e750a7e9e61fba1d8ebc098e6390c774f47c4cddf1e61e7236ea',+ );+ expect(sha256(canonicalJson(report.uvArtifactSha256))).toBe(+ 'b2f1b1f2d950ca0c7c550a18a5aaf6d1e696c9a1938dac682870b44aa47c8300',+ );+ expect(sha256(canonicalJson(report))).toBe(+ '782b8ed3bec42c7c4e90eb8d1739d588412a4c3b326adf6a8a44942757f6b559',+ );+ });+});diff --git a/src/__tests__/architecture-prompt-examples.test.ts b/src/__tests__/architecture-prompt-examples.test.tsnew file mode 100644index 00000000..c0ed514f--- /dev/null+++ b/src/__tests__/architecture-prompt-examples.test.ts@@ -0,0 +1,77 @@+import { describe, expect, test } from 'bun:test';++import { createAssetIntentV1 } from '../contracts';+import { ARCHITECTURE_RIDGE_X_SCAFFOLD, ARCHITECTURE_RIDGE_Z_SCAFFOLD } from '../prompt';+import type { AssetQaReportV1 } from '../qa/types';+import { renderGLB } from '../render';++const CANONICAL_ARCHITECTURE_CODES = new Set([+ 'ARCH_ROOF_AXIS',+ 'ARCH_OPEN_GABLE',+ 'ARCH_RIDGE_GAP',+ 'ARCH_ENVELOPE_GAP',+ 'ARCH_BLOCKED_PORTAL',+]);++function architectureIntent(+ ridgeAxis: 'x' | 'z',+ spanX: number,+ spanZ: number,+ wallHeight: number,+ rise: number,+ overhang: number,+) {+ const halfRun = (ridgeAxis === 'x' ? spanZ : spanX) / 2;+ return createAssetIntentV1({+ category: 'architecture',+ capabilities: ['enterable', 'grounded', 'navigable'],+ bounds: { x: spanX, y: wallHeight, z: spanZ, units: 'm' },+ architecture: {+ subtype: 'building',+ enterable: true,+ footprint: { spanX, spanZ },+ wallHeight,+ scaleMode: 'realistic',+ roof: {+ type: 'gable',+ ridgeAxis,+ rise,+ pitchDegrees: Math.atan2(rise, halfRun) * (180 / Math.PI),+ overhang,+ closedEnds: true,+ },+ portal: {+ width: ridgeAxis === 'x' ? 1.1 : 1.2,+ height: ridgeAxis === 'x' ? 2.1 : 2.2,+ depth: 0.15,+ },+ },+ });+}++describe('ARCH-017 executable architecture prompt scaffolds', () => {+ for (const fixture of [+ {+ name: 'ridge +X',+ code: ARCHITECTURE_RIDGE_X_SCAFFOLD,+ intent: architectureIntent('x', 8, 6, 3, 1.6, 0.4),+ },+ {+ name: 'ridge +Z',+ code: ARCHITECTURE_RIDGE_Z_SCAFFOLD,+ intent: architectureIntent('z', 7, 10, 3.2, 1.8, 0.45),+ },+ ]) {+ test(`${fixture.name} compiles, renders, and passes exact architecture QA`, async () => {+ const rendered = await renderGLB(fixture.code, { intent: fixture.intent });+ expect(rendered.glb.subarray(0, 4).toString()).toBe('glTF');+ const report = rendered.meta.qaReport as AssetQaReportV1;+ expect(report.disposition).toBe('pass');+ expect(report.dimensions.exportIntegrity.metrics?.['gltfErrors']).toBe(0);+ const canonicalFindings = Object.values(report.dimensions)+ .flatMap((dimension) => dimension.findings)+ .filter((finding) => CANONICAL_ARCHITECTURE_CODES.has(finding.code));+ expect(canonicalFindings).toEqual([]);+ });+ }+});diff --git a/src/__tests__/architecture.test.ts b/src/__tests__/architecture.test.tsnew file mode 100644index 00000000..951d18e2--- /dev/null+++ b/src/__tests__/architecture.test.ts@@ -0,0 +1,277 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import {+ createGableEndPanel,+ createGableRoof,+ createGableShell,+ createRoofSurfaceLayout,+ type RidgeAxis,+ type RoofFaceFrame,+} from '../architecture';+import { readSemanticMetadataV1 } from '../contracts';++const EPSILON = 1e-6;++function material(color = 0x8899aa): THREE.MeshStandardMaterial {+ return new THREE.MeshStandardMaterial({ color, side: THREE.DoubleSide });+}++function expectVectorClose(actual: THREE.Vector3, expected: THREE.Vector3): void {+ expect(actual.distanceTo(expected)).toBeLessThan(EPSILON);+}++function expectUnorderedEndpoints(+ actual: [THREE.Vector3, THREE.Vector3],+ expected: [THREE.Vector3, THREE.Vector3],+): void {+ const direct = actual[0].distanceTo(expected[0]) + actual[1].distanceTo(expected[1]);+ const reversed = actual[0].distanceTo(expected[1]) + actual[1].distanceTo(expected[0]);+ expect(Math.min(direct, reversed)).toBeLessThan(EPSILON);+}++function worldPoint(root: THREE.Object3D, point: THREE.Vector3): THREE.Vector3 {+ root.updateWorldMatrix(true, false);+ return point.clone().applyMatrix4(root.matrixWorld);+}++function expectedFaceEndpoints(+ root: THREE.Object3D,+ axis: RidgeAxis,+ side: 'positive' | 'negative',+ spanX: number,+ spanZ: number,+ overhang: number,+ rise: number,+ pitchDegrees: number,+): { ridge: [THREE.Vector3, THREE.Vector3]; eave: [THREE.Vector3, THREE.Vector3] } {+ const sign = side === 'positive' ? 1 : -1;+ const ridgeHalf = (axis === 'x' ? spanX : spanZ) / 2 + overhang;+ const eaveOffset = (axis === 'x' ? spanZ : spanX) / 2 + overhang;+ const eaveY = -Math.tan((pitchDegrees * Math.PI) / 180) * overhang;+ const ridgeLocal: [THREE.Vector3, THREE.Vector3] =+ axis === 'x'+ ? [new THREE.Vector3(-ridgeHalf, rise, 0), new THREE.Vector3(ridgeHalf, rise, 0)]+ : [new THREE.Vector3(0, rise, -ridgeHalf), new THREE.Vector3(0, rise, ridgeHalf)];+ const eaveLocal: [THREE.Vector3, THREE.Vector3] =+ axis === 'x'+ ? [+ new THREE.Vector3(-ridgeHalf, eaveY, sign * eaveOffset),+ new THREE.Vector3(ridgeHalf, eaveY, sign * eaveOffset),+ ]+ : [+ new THREE.Vector3(sign * eaveOffset, eaveY, -ridgeHalf),+ new THREE.Vector3(sign * eaveOffset, eaveY, ridgeHalf),+ ];+ return {+ ridge: [worldPoint(root, ridgeLocal[0]), worldPoint(root, ridgeLocal[1])],+ eave: [worldPoint(root, eaveLocal[0]), worldPoint(root, eaveLocal[1])],+ };+}++function assertRigidFaceFrame(face: RoofFaceFrame): void {+ expect(face.ridgeTangent.length()).toBeCloseTo(1, 8);+ expect(face.downhillDirection.length()).toBeCloseTo(1, 8);+ expect(face.outwardNormal.length()).toBeCloseTo(1, 8);+ expect(Math.abs(face.ridgeTangent.dot(face.downhillDirection))).toBeLessThan(EPSILON);+ expect(Math.abs(face.ridgeTangent.dot(face.outwardNormal))).toBeLessThan(EPSILON);+ expect(Math.abs(face.downhillDirection.dot(face.outwardNormal))).toBeLessThan(EPSILON);+ expect(+ face.ridgeTangent.clone().cross(face.outwardNormal).dot(face.downhillDirection),+ ).toBeCloseTo(1, 8);+ expect(face.downhillDirection.y).toBeLessThan(0);+ expect(face.outwardNormal.y).toBeGreaterThan(0);+}++describe('correct-by-construction architecture helpers', () => {+ for (const fixture of [+ { axis: 'x' as const, spanX: 8, spanZ: 5, pitchDegrees: 27, overhang: 0.35 },+ { axis: 'z' as const, spanX: 5, spanZ: 9, pitchDegrees: 41, overhang: 0.5 },+ { axis: 'x' as const, spanX: 6, spanZ: 6, pitchDegrees: 52, overhang: 0.2 },+ { axis: 'z' as const, spanX: 6, spanZ: 6, pitchDegrees: 33, overhang: 0.4 },+ ]) {+ test(`returns exact live face frames for ridge-${fixture.axis}, ${fixture.spanX}x${fixture.spanZ}`, () => {+ const parent = new THREE.Object3D();+ parent.position.set(3.25, 1.4, -2.75);+ parent.rotation.y = 0.61;+ const roof = createGableRoof('Roof', material(), {+ spanX: fixture.spanX,+ spanZ: fixture.spanZ,+ pitchDegrees: fixture.pitchDegrees,+ overhang: fixture.overhang,+ ridgeAxis: fixture.axis,+ parent,+ });+ roof.root.position.set(0.7, 2.9, -0.35);+ roof.root.rotation.y = -0.23;++ for (const face of roof.faces) {+ assertRigidFaceFrame(face);+ const expected = expectedFaceEndpoints(+ roof.root,+ fixture.axis,+ face.side,+ fixture.spanX,+ fixture.spanZ,+ fixture.overhang,+ roof.rise,+ roof.pitchDegrees,+ );+ expectUnorderedEndpoints([face.ridgeStart, face.ridgeEnd], expected.ridge);+ expectUnorderedEndpoints([face.eaveStart, face.eaveEnd], expected.eave);+ const ridgeToEave = face.eaveStart.clone().sub(face.ridgeStart).normalize();+ expectVectorClose(ridgeToEave, face.downhillDirection);+ }+ expectUnorderedEndpoints(+ [roof.faces[0].ridgeStart, roof.faces[0].ridgeEnd],+ [roof.faces[1].ridgeStart, roof.faces[1].ridgeEnd],+ );++ const before = roof.faces[0].ridgeStart;+ parent.position.x += 2;+ const after = roof.faces[0].ridgeStart;+ expect(after.x - before.x).toBeCloseTo(2, 8);+ });+ }++ test('builds an exact thick gable boundary and subtracts optional openings', () => {+ const solid = createGableEndPanel('Gable', material(), {+ span: 5,+ rise: 2,+ thickness: 0.2,+ ridgeAxis: 'z',+ });+ solid.geometry.computeBoundingBox();+ const size = new THREE.Vector3();+ solid.geometry.boundingBox!.getSize(size);+ expectVectorClose(size, new THREE.Vector3(5, 2, 0.2));++ const raycaster = new THREE.Raycaster();+ for (const fractionY of [0.1, 0.35, 0.7, 0.9]) {+ const y = fractionY * 2;+ const halfWidth = 2.5 * (1 - fractionY);+ for (const fractionX of [-0.9, 0, 0.9]) {+ raycaster.set(new THREE.Vector3(halfWidth * fractionX, y, 1), new THREE.Vector3(0, 0, -1));+ expect(raycaster.intersectObject(solid.root, false).length).toBeGreaterThan(0);+ }+ raycaster.set(new THREE.Vector3(halfWidth * 1.02, y, 1), new THREE.Vector3(0, 0, -1));+ expect(raycaster.intersectObject(solid.root, false)).toHaveLength(0);+ }++ const opened = createGableEndPanel('VentGable', material(), {+ span: 5,+ rise: 2,+ thickness: 0.2,+ ridgeAxis: 'z',+ openings: [{ id: 'vent', offset: 0.25, bottom: 0.3, width: 0.8, height: 0.7 }],+ });+ raycaster.set(new THREE.Vector3(0.25, 0.65, 1), new THREE.Vector3(0, 0, -1));+ expect(raycaster.intersectObject(opened.root, false)).toHaveLength(0);+ raycaster.set(new THREE.Vector3(0.9, 0.65, 1), new THREE.Vector3(0, 0, -1));+ expect(raycaster.intersectObject(opened.root, false).length).toBeGreaterThan(0);+ expect(() =>+ createGableEndPanel('Invalid', material(), {+ span: 2,+ rise: 1,+ openings: [{ width: 1.8, height: 0.9, bottom: 0.2 }],+ }),+ ).toThrow();+ });++ test('composes a closed, enterable semantic shell with a real doorway gap by default', () => {+ const shell = createGableShell(+ 'House',+ { wall: material(0xbb9988), roof: material(0x554433) },+ { spanX: 8, spanZ: 5, wallHeight: 2.8, pitchDegrees: 35, ridgeAxis: 'x' },+ );+ expect(shell.gables).toHaveLength(2);+ expect(shell.gables[0]!.parent).toBe(shell.roof.root);+ expect(shell.gables[1]!.parent).toBe(shell.roof.root);+ expect(shell.openings).toHaveLength(1);+ expect(shell.openings[0]).not.toBeInstanceOf(THREE.Mesh);+ expect(shell.openings[0]!.scale.toArray()).toEqual([0.15, 2.1, 1.1]);++ const expectedRoles = new Map<THREE.Object3D, string>([+ [shell.root, 'architecture.shell.gable'],+ [shell.floor, 'floor'],+ [shell.roof.root, 'roof.assembly'],+ [shell.roof.slopes[0], 'roof.slope.positive'],+ [shell.roof.slopes[1], 'roof.slope.negative'],+ [shell.gables[0]!, 'roof.gable.positive'],+ [shell.gables[1]!, 'roof.gable.negative'],+ [shell.walls.front, 'wall.front'],+ [shell.walls.back, 'wall.back'],+ [shell.walls.left, 'wall.left'],+ [shell.walls.right, 'wall.right'],+ [shell.openings[0]!, 'opening.front.door'],+ ]);+ for (const [node, role] of expectedRoles) {+ expect(readSemanticMetadataV1(node)?.roles).toContain(role);+ }+ expect(+ readSemanticMetadataV1(shell.roof.root)?.relationships.some(+ (entry) => entry.kind === 'separable-from',+ ),+ ).toBe(true);+ expect(+ shell.gables.every((gable) =>+ readSemanticMetadataV1(gable)?.relationships.some(+ (entry) => entry.kind === 'separable-from',+ ),+ ),+ ).toBe(true);+ expect(+ readSemanticMetadataV1(shell.openings[0]!)?.relationships.map((entry) => entry.kind),+ ).toEqual(['cutout-of', 'portal-through']);+ expect(readSemanticMetadataV1(shell.openings[0]!)?.frames.map((frame) => frame.id)).toEqual([+ 'clearance',+ ]);++ const doorwayWorld = shell.openings[0]!.getWorldPosition(new THREE.Vector3());+ const blockers = shell.walls.front.children.filter(+ (child): child is THREE.Mesh => child instanceof THREE.Mesh,+ );+ expect(+ blockers.some((mesh) => new THREE.Box3().setFromObject(mesh).containsPoint(doorwayWorld)),+ ).toBe(false);+ });++ for (const axis of ['x', 'z'] as const) {+ test(`lays every roof surface family downhill from the ridge-${axis} face frame`, () => {+ const roof = createGableRoof('Roof', material(), {+ spanX: axis === 'x' ? 9 : 5,+ spanZ: axis === 'x' ? 5 : 9,+ rise: 1.8,+ overhang: 0.35,+ ridgeAxis: axis,+ });+ for (const kind of ['panels', 'shingles', 'seams', 'corrugations'] as const) {+ const layout = createRoofSurfaceLayout(`Surface_${kind}`, material(), {+ face: roof.faces[0],+ kind,+ parent: roof.root,+ });+ expect(layout.items.length).toBeGreaterThan(1);+ for (const item of layout.items.slice(0, 3)) {+ item.updateWorldMatrix(true, false);+ const itemLength = new THREE.Vector3(0, 0, 1).transformDirection(item.matrixWorld);+ expect(Math.abs(itemLength.dot(roof.faces[0].downhillDirection))).toBeCloseTo(1, 8);+ }+ expect(readSemanticMetadataV1(layout.root)?.roles).toContain(`roof.surface.${kind}`);+ }+ });+ }++ test('rejects ambiguous or contradictory roof dimensions instead of guessing', () => {+ expect(() => createGableRoof('Bad', material(), { spanX: 0, spanZ: 4 })).toThrow();+ expect(() =>+ createGableRoof('Bad', material(), {+ spanX: 8,+ spanZ: 4,+ rise: 1,+ pitchDegrees: 60,+ ridgeAxis: 'x',+ }),+ ).toThrow();+ });+});diff --git a/src/__tests__/character.test.ts b/src/__tests__/character.test.tsnew file mode 100644index 00000000..a38826bf--- /dev/null+++ b/src/__tests__/character.test.ts@@ -0,0 +1,278 @@+import { describe, expect, test } from 'bun:test';+import { WebIO } from '@gltf-transform/core';+import * as THREE from 'three';++import {+ BIPED_RIG_PRESET_V1,+ QUADRUPED_RIG_PRESET_V1,+ characterBodyPlanRecipe,+ characterJointNodeName,+ createCharacterJointDescriptorV1,+ createCharacterRigGraphV1,+ createJointChain,+ expandCharacterRigPreset,+ readCharacterJointDescriptorV1,+ stampCharacterRigGraphV1,+ validateCharacterRigGraphV1,+ type JointChainSegmentV1,+} from '../character';+import { createAssetIntentV1, readSemanticMetadataV1 } from '../contracts';+import { renderSceneToGLB } from '../render';++const chainCases: Array<{ name: string; segments: JointChainSegmentV1[] }> = [+ {+ name: 'BipedLeg',+ segments: [+ { role: 'hip.left', offset: [0, 1, -0.15], side: 'left' },+ { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' },+ {+ role: 'ankle.left',+ offset: [0, -0.5, 0],+ side: 'left',+ endEffector: true,+ contact: true,+ },+ ],+ },+ {+ name: 'QuadrupedForeleg',+ segments: [+ { role: 'shoulder.fore.right', offset: [0.3, 0.7, 0.25], side: 'right' },+ { role: 'elbow.fore.right', offset: [0, -0.4, 0], side: 'right' },+ {+ role: 'paw.fore.right',+ offset: [0, -0.3, 0],+ side: 'right',+ endEffector: true,+ contact: true,+ },+ ],+ },+ {+ name: 'Wing',+ segments: [+ { role: 'shoulder.wing.left', offset: [0, 1, -0.2], side: 'left' },+ { role: 'wing.mid.left', offset: [0, 0, -0.5], side: 'left' },+ { role: 'wing.tip.left', offset: [0, 0, -0.5], side: 'left', endEffector: true },+ ],+ },+ {+ name: 'Tail',+ segments: [+ { role: 'tail.base', offset: [-0.3, 0.6, 0] },+ { role: 'tail.mid', offset: [-0.4, 0, 0] },+ { role: 'tail.tip', offset: [-0.4, 0, 0], endEffector: true },+ ],+ },+ {+ name: 'Tentacle',+ segments: [+ { role: 'tentacle.3.base', offset: [0, 0.3, 0.2] },+ { role: 'tentacle.3.mid', offset: [0.2, 0, 0] },+ { role: 'tentacle.3.tip', offset: [0.2, 0, 0], endEffector: true },+ ],+ },+];++describe('CHAR-003/005 semantic rig graphs', () => {+ test('biped and quadruped presets are data graphs with every declared parent present', () => {+ for (const preset of [BIPED_RIG_PRESET_V1, QUADRUPED_RIG_PRESET_V1]) {+ const roles = new Set(preset.joints.map((joint) => joint.role));+ expect(validateCharacterRigGraphV1(preset).valid).toBe(true);+ expect(preset.joints.every((joint) => !joint.parentRole || roles.has(joint.parentRole))).toBe(+ true,+ );+ expect(new Set(preset.joints.map((joint) => joint.role)).size).toBe(preset.joints.length);+ }+ expect(BIPED_RIG_PRESET_V1.joints.map((joint) => joint.role)).toEqual(+ expect.arrayContaining([+ 'hips',+ 'spine',+ 'head',+ 'shoulder.left',+ 'elbow.left',+ 'wrist.left',+ 'hip.right',+ 'knee.right',+ 'ankle.right',+ ]),+ );+ expect(+ QUADRUPED_RIG_PRESET_V1.joints.filter((joint) => joint.contact).map((joint) => joint.role),+ ).toEqual(['paw.fore.left', 'paw.fore.right', 'paw.hind.left', 'paw.hind.right']);+ });++ test('custom graph accepts non-humanoid roles and rejects missing parents/cycles', () => {+ const serpent = createCharacterRigGraphV1({+ bodyPlan: 'serpentine',+ joints: [+ createCharacterJointDescriptorV1({ role: 'spine.0' }),+ createCharacterJointDescriptorV1({ role: 'spine.1', parentRole: 'spine.0' }),+ createCharacterJointDescriptorV1({+ role: 'tail.tip',+ parentRole: 'spine.1',+ endEffector: true,+ contact: true,+ }),+ ],+ });+ expect(validateCharacterRigGraphV1(serpent)).toEqual({+ valid: true,+ value: serpent,+ issues: [],+ });+ expect(+ validateCharacterRigGraphV1({+ schemaVersion: 1,+ bodyPlan: 'custom',+ joints: [+ createCharacterJointDescriptorV1({ role: 'a', parentRole: 'b' }),+ createCharacterJointDescriptorV1({ role: 'b', parentRole: 'a' }),+ ],+ }).issues.map((issue) => issue.code),+ ).toContain('JOINT_PARENT_CYCLE');+ });++ test('preset expansion returns a detached graph', () => {+ const expanded = expandCharacterRigPreset('biped');+ expect(expanded).toEqual(BIPED_RIG_PRESET_V1);+ expect(expanded).not.toBe(BIPED_RIG_PRESET_V1);+ expect(expanded.joints).not.toBe(BIPED_RIG_PRESET_V1.joints);+ });+});++describe('CHAR-006/007 body-plan-agnostic createJointChain', () => {+ for (const fixture of chainCases) {+ test(`${fixture.name} has deterministic names, hierarchy, pivots, frames, and transformed-parent behavior`, () => {+ const asset = new THREE.Object3D();+ asset.name = `Asset_${fixture.name}`;+ asset.position.set(3, 2, -4);+ asset.rotation.set(0.2, 0.6, -0.1);+ asset.scale.set(1.5, 1.5, 1.5);+ const chain = createJointChain(fixture.name, fixture.segments, { parent: asset });++ expect(chain.nodes.map((node) => node.name)).toEqual(+ fixture.segments.map((segment) => characterJointNodeName(fixture.name, segment.role)),+ );+ expect(chain.root.parent).toBe(asset);+ for (let index = 1; index < chain.nodes.length; index++) {+ expect(chain.nodes[index]?.parent).toBe(chain.nodes[index - 1]);+ }+ const localEnd = fixture.segments.reduce(+ (sum, segment) => sum.add(new THREE.Vector3(...segment.offset)),+ new THREE.Vector3(),+ );+ asset.updateMatrixWorld(true);+ const expectedWorld = localEnd.applyMatrix4(asset.matrixWorld);+ expect(+ chain.end.getWorldPosition(new THREE.Vector3()).distanceTo(expectedWorld),+ ).toBeLessThan(1e-8);++ const before = chain.end.getWorldPosition(new THREE.Vector3());+ const childOffset = new THREE.Vector3(...fixture.segments[2]!.offset);+ if (Math.abs(childOffset.y) >= Math.max(Math.abs(childOffset.x), Math.abs(childOffset.z))) {+ chain.nodes[1]?.rotateZ(0.35);+ } else {+ chain.nodes[1]?.rotateY(0.35);+ }+ asset.updateMatrixWorld(true);+ expect(chain.end.getWorldPosition(new THREE.Vector3()).distanceTo(before)).toBeGreaterThan(+ 0.01,+ );++ for (const [index, node] of chain.nodes.entries()) {+ const descriptor = readCharacterJointDescriptorV1(node)!;+ expect(descriptor.role).toBe(fixture.segments[index]!.role);+ expect(descriptor.parentRole).toBe(+ index === 0 ? undefined : fixture.segments[index - 1]?.role,+ );+ const semantic = readSemanticMetadataV1(node)!;+ expect(semantic.roles).toContain(`joint.${descriptor.role}`);+ expect(semantic.frames.map((frame) => frame.id)).toEqual(+ expect.arrayContaining(['rest', 'forward', 'bend']),+ );+ }+ });+ }++ test('rejects duplicate roles instead of creating ambiguous Joint_* nodes', () => {+ expect(() =>+ createJointChain('Bad', [+ { role: 'segment', offset: [0, 0, 0] },+ { role: 'segment', offset: [1, 0, 0] },+ ]),+ ).toThrow('Duplicate joint-chain role');+ });++ test('semantic joint extras survive exact GLB export/reload', async () => {+ const root = new THREE.Object3D();+ root.name = 'SemanticChain';+ const chain = createJointChain('Tail', chainCases[3]!.segments, { parent: root });+ stampCharacterRigGraphV1(root, { bodyPlan: 'custom', joints: chain.descriptors });+ const visual = new THREE.Mesh(+ new THREE.BoxGeometry(0.2, 0.2, 0.2),+ new THREE.MeshStandardMaterial(),+ );+ visual.name = 'Mesh_Body';+ root.add(visual);+ const rendered = await renderSceneToGLB(root, {+ intent: createAssetIntentV1({+ category: 'character',+ capabilities: [],+ character: { bodyPlan: 'custom', grounded: false },+ }),+ });+ const document = await new WebIO().readBinary(rendered.bytes);+ const exported = document+ .getRoot()+ .listNodes()+ .filter((node) => node.getName().startsWith('Joint_'));+ expect(exported).toHaveLength(3);+ const exportedRoot = document+ .getRoot()+ .listNodes()+ .find((node) => node.getName() === 'SemanticChain');+ expect(exportedRoot).toBeDefined();+ const rootSemantic = exportedRoot!.getExtras()['kilnSemantic'] as { roles: string[] };+ expect(rootSemantic.roles).toEqual(+ expect.arrayContaining(['character.rig', 'character.body-plan.custom']),+ );+ for (const node of exported) {+ const semantic = node.getExtras()['kilnSemantic'] as {+ roles: string[];+ frames: Array<{ id: string }>;+ relationships: Array<{ kind: string; target: string }>;+ };+ expect(semantic.roles).toContain('skeleton.joint');+ expect(semantic.roles.some((role) => role.startsWith('joint.'))).toBe(true);+ expect(semantic.frames.map((frame) => frame.id)).toEqual(+ expect.arrayContaining(['rest', 'forward', 'bend']),+ );+ }+ });+});++describe('CHAR-031 resolved body-plan recipe', () => {+ test('injects one resolved recipe without cross-plan anatomy', () => {+ const dog = characterBodyPlanRecipe('quadruped');+ expect(dog).toContain('QUADRUPED');+ expect(dog).not.toContain('BIPED');+ const serpent = characterBodyPlanRecipe('serpentine');+ expect(serpent).toContain('SERPENTINE');+ expect(serpent.toLowerCase()).not.toContain('knee');+ expect(serpent).not.toContain('BIPED');+ });++ test('custom recipe names only roles from its declared graph', () => {+ const graph = createCharacterRigGraphV1({+ bodyPlan: 'custom',+ joints: [+ createCharacterJointDescriptorV1({ role: 'core' }),+ createCharacterJointDescriptorV1({ role: 'sensor.tip', parentRole: 'core' }),+ ],+ });+ const recipe = characterBodyPlanRecipe('custom', graph);+ expect(recipe).toContain('core, sensor.tip');+ expect(recipe).not.toContain('shoulder');+ });+});diff --git a/src/__tests__/geometry-gains.test.ts b/src/__tests__/geometry-gains.test.tsindex 4703b0bb..8d169335 100644--- a/src/__tests__/geometry-gains.test.ts+++ b/src/__tests__/geometry-gains.test.ts@@ -6,8 +6,14 @@import { describe, expect, test } from 'bun:test';import * as THREE from 'three';import { buildSandboxGlobals, snapTo } from '../primitives';-import { executeKilnCode, inspectSceneStructure, settleContacts } from '../render';+import {+ executeKilnCode,+ inspectSceneStructure,+ renderSceneToGLB,+ settleContacts,+} from '../render';import { validate } from '../validation';+import { createAssetIntentV1 } from '../contracts';const FLOATER_CODE = `const meta = { name: 'floaty', category: 'prop' };@@ -92,6 +98,43 @@ describe('orientation advisory', () => {// No category → no orientation check at all.expect(inspectSceneStructure(sideways.root).some((w) => w.includes('Orientation'))).toBe(false);});++ test('intent-only render uses the trusted vehicle profile for inspection and runtime cost', async () => {+ const sideways = await executeKilnCode(`+ const meta = { name: 'sideways', category: 'prop' };+ function build() {+ const root = createRoot('Root');+ const frame = createVehicleFrame('VehicleFrame', {+ axles: [{ id: 'front', position: [0.3, 0.35, 0] }, { id: 'rear', position: [-0.3, 0.35, 0] }],+ parent: root,+ });+ createPart('Mesh_Hull', boxGeo(0.8, 0.5, 3.0), gameMaterial('#445544'), { parent: frame.root, position: [0, 0.5, 0] });+ const rubber = gameMaterial('#111111', { roughness: 0.95 });+ const metal = gameMaterial('#888888', { metalness: 0.8 });+ const geometries = createWheelGeometrySet(0.35, 0.18);+ for (const [index, x] of [['front', 0.3], ['rear', -0.3]]) {+ for (const [side, z] of [['left', -1.6], ['right', 1.6]]) {+ createWheelAssembly(index + side, { tire: rubber, rim: metal }, {+ radius: 0.35, width: 0.18, side, index,+ position: [x, 0.35, z], steering: index === 'front', geometries, parent: frame.root,+ });+ }+ }+ return root;+ }+ `);+ const rendered = await renderSceneToGLB(sideways.root, {+ intent: createAssetIntentV1({ category: 'vehicle' }),+ });++ expect(rendered.warnings.some((warning) => warning.includes('Orientation'))).toBe(true);+ expect(rendered.qaReport.category).toBe('vehicle');+ expect(rendered.qaReport.dimensions.runtimeCost.status).toBe('pass');+ expect(rendered.qaReport.dimensions.runtimeCost.metrics?.['instanceabilityGrade']).toBe(+ rendered.instanceability?.grade,+ );+ expect(rendered.qaReport.dimensions.exportIntegrity.metrics?.['gltfErrors']).toBe(0);+ });});describe('settleContacts', () => {diff --git a/src/__tests__/instancing.test.ts b/src/__tests__/instancing.test.tsindex d769dda1..e35e513e 100644--- a/src/__tests__/instancing.test.ts+++ b/src/__tests__/instancing.test.ts@@ -195,7 +195,11 @@ describe('M1c: GPU-instancing pass (instance option)', () => {});it('animated docs and Joint_* pivots are never instanced', async () => {- const spin = new THREE.NumberKeyframeTrack('Post0.position[y]', [0, 1], [0.6, 0.8]);+ const spin = new THREE.VectorKeyframeTrack(+ 'Mesh_Post0.position',+ [0, 1],+ [0, 0.6, 0, 0, 0.8, 0],+ );const clip = new THREE.AnimationClip('bob', 1, [spin]);const animated = await renderSceneToGLB(fenceScene(10), { instance: 'on', clips: [clip] });expect(animated.instancing).toBeUndefined();diff --git a/src/__tests__/material-metrics.test.ts b/src/__tests__/material-metrics.test.tsnew file mode 100644index 00000000..f2222b14--- /dev/null+++ b/src/__tests__/material-metrics.test.ts@@ -0,0 +1,174 @@+import { describe, expect, test } from 'bun:test';+import { Document, WebIO } from '@gltf-transform/core';+import { KHRMaterialsUnlit } from '@gltf-transform/extensions';+import * as THREE from 'three';++import { applyMaterialRecipeV1 } from '../material-recipe-runtime';+import {+ collectMaterialMetricsV1,+ evaluateMaterialBudgetV1,+ materialBudgetProfileForQaProfile,+ type MaterialMetricsV1,+} from '../material-metrics';+import { createMaterialRecipeRequestV1 } from '../material-recipes';+import { ApprovedTextureResourceCache } from '../material-resources';+import { renderSceneToGLB } from '../render';++async function materialGalleryMetrics(): Promise<MaterialMetricsV1> {+ const cache = new ApprovedTextureResourceCache();+ const root = new THREE.Group();+ const bark = await applyMaterialRecipeV1(+ createMaterialRecipeRequestV1('kiln.material.bark.v1', {+ textureResources: { baseColor: 'kiln.texture.bark-albedo.v1' },+ }),+ { cache },+ );+ const leaf = await applyMaterialRecipeV1(+ createMaterialRecipeRequestV1('kiln.material.leaf.v1', {+ textureResources: { baseColor: 'kiln.texture.leaf-mask-albedo.v1' },+ }),+ { cache },+ );+ const glass = await applyMaterialRecipeV1(+ createMaterialRecipeRequestV1('kiln.material.glass.v1'),+ { cache },+ );+ for (const [index, applied] of [bark, leaf, glass].entries()) {+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(index + 1, 1, 1), applied.material);+ mesh.position.x = index * 3;+ root.add(mesh);+ }+ const rendered = await renderSceneToGLB(root, { sceneName: 'MaterialMetricsGallery' });+ expect(rendered.gltfValidation.issues.numErrors).toBe(0);+ return collectMaterialMetricsV1(await new WebIO().readBinary(rendered.bytes));+}++describe('MAT-010 material metrics', () => {+ test('attaches separate material metrics to the five-dimension QA report', async () => {+ const applied = await applyMaterialRecipeV1(+ createMaterialRecipeRequestV1('kiln.material.leaf.v1'),+ );+ const root = new THREE.Group();+ root.add(new THREE.Mesh(new THREE.PlaneGeometry(1, 1), applied.material));+ const rendered = await renderSceneToGLB(root, { sceneName: 'LeafMetricsReport' });+ expect(rendered.materialMetrics).toMatchObject({+ maskedMaterials: 1,+ blendedMaterials: 0,+ doubleSidedMaterials: 1,+ });+ expect(rendered.qaReport.dimensions.runtimeCost.metrics).toMatchObject({+ maskedMaterials: 1,+ blendedMaterials: 0,+ doubleSidedMaterials: 1,+ imageCount: 0,+ });+ });++ test('separates alpha mode, sidedness, textures, images, resolution, and decoded memory', async () => {+ const metrics = await materialGalleryMetrics();+ expect(metrics).toMatchObject({+ schemaVersion: 1,+ materialCount: 3,+ opaqueMaterials: 1,+ maskedMaterials: 1,+ blendedMaterials: 1,+ singleSidedMaterials: 1,+ doubleSidedMaterials: 2,+ texturedMaterials: 2,+ untexturedMaterials: 1,+ extensionCount: 0,+ extensionsUsed: [],+ materialExtensionCount: 0,+ materialExtensionsUsed: [],+ imageCount: 2,+ maxImageDimension: 4,+ totalImagePixels: 32,+ decodedImageBytesRgba8: 128,+ });+ expect(metrics.images).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ width: 4, height: 4, decodedBytesRgba8: 64 }),+ ]),+ );+ expect(metrics.totalSurfaceArea).toBeGreaterThan(0);+ expect(metrics.blendedSurfaceArea).toBeGreaterThan(0);+ expect(metrics.blendedSurfaceAreaRatio).toBeGreaterThan(0);+ // A masked leaf is counted only as MASK, never as blended transparency.+ expect(metrics.maskedMaterials + metrics.blendedMaterials + metrics.opaqueMaterials).toBe(+ metrics.materialCount,+ );+ });++ test('reports ratified extension use independently from core material counts', () => {+ const document = new Document();+ const material = document.createMaterial('UnlitMarker');+ const extension = document.createExtension(KHRMaterialsUnlit);+ material.setExtension('KHR_materials_unlit', extension.createUnlit());+ const metrics = collectMaterialMetricsV1(document);+ expect(metrics.extensionCount).toBe(1);+ expect(metrics.extensionsUsed).toEqual(['KHR_materials_unlit']);+ expect(metrics.materialExtensionCount).toBe(1);+ expect(metrics.materialExtensionsUsed).toEqual(['KHR_materials_unlit']);+ expect(metrics.materialCount).toBe(1);+ });+});++describe('MAT-018 advisory texture budgets', () => {+ test('selects a tier/profile and reports measured cost with downscale advice', async () => {+ const base = await materialGalleryMetrics();+ const over: MaterialMetricsV1 = {+ ...base,+ imageCount: 9,+ maxImageDimension: 8192,+ decodedImageBytesRgba8: 256 * 1024 * 1024,+ blendedSurfaceArea: 80,+ totalSurfaceArea: 100,+ blendedSurfaceAreaRatio: 0.8,+ images: [+ {+ name: 'hero-albedo',+ width: 8192,+ height: 8192,+ maxDimension: 8192,+ decodedBytesRgba8: 256 * 1024 * 1024,+ estimatedGpuBytesWithMipmaps: 342 * 1024 * 1024,+ },+ ],+ };+ expect(materialBudgetProfileForQaProfile('vehicle.mobile')).toBe('mobile.portable.v1');+ expect(materialBudgetProfileForQaProfile('architecture.default')).toBe('web.portable.v1');+ const warnings = evaluateMaterialBudgetV1(over, {+ profile: 'web.portable.v1',+ tier: 'standard',+ });+ expect(warnings.map((warning) => warning.code)).toEqual([+ 'MATERIAL_TEXTURE_RESOLUTION_BUDGET',+ 'MATERIAL_IMAGE_COUNT_BUDGET',+ 'MATERIAL_DECODED_MEMORY_BUDGET',+ 'MATERIAL_BLEND_AREA_BUDGET',+ ]);+ expect(warnings.every((warning) => warning.disposition === 'warn')).toBe(true);+ expect(+ warnings.every((warning) => warning.measurement.actual > warning.measurement.threshold),+ ).toBe(true);+ expect(warnings.map((warning) => warning.advice).join(' ')).toMatch(/Downscale.*atlas.*MASK/is);+ expect(warnings.map((warning) => warning.message).join(' ')).toMatch(+ /8192px.*9 images.*256\.00 MiB.*80\.0%/s,+ );+ });++ test('stays advisory and quiet within the selected budget', async () => {+ const measured = await materialGalleryMetrics();+ const metrics = {+ ...measured,+ blendedSurfaceArea: measured.totalSurfaceArea * 0.3,+ blendedSurfaceAreaRatio: 0.3,+ };+ expect(+ evaluateMaterialBudgetV1(metrics, {+ profile: 'web.portable.v1',+ tier: 'hero',+ }),+ ).toEqual([]);+ });+});diff --git a/src/__tests__/material-recipes.test.ts b/src/__tests__/material-recipes.test.tsnew file mode 100644index 00000000..064330d7--- /dev/null+++ b/src/__tests__/material-recipes.test.ts@@ -0,0 +1,199 @@+import { describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { WebIO } from '@gltf-transform/core';+import * as THREE from 'three';++import { applyMaterialRecipeV1 } from '../material-recipe-runtime';+import {+ MATERIAL_RECIPE_IDS,+ createMaterialRecipeRequestV1,+ listMaterialRecipeCapabilitiesV1,+ materialRecipeSnapshotV1,+ resolveMaterialRecipeV1,+ validateMaterialRecipeRequestV1,+} from '../material-recipes';+import { executeKilnCode, renderSceneToGLB } from '../render';++describe('MAT-013 versioned material recipe contract', () => {+ test('publishes ten exact versioned IDs and rejects unsupported IDs/overrides', () => {+ expect(MATERIAL_RECIPE_IDS).toEqual([+ 'kiln.material.bark.v1',+ 'kiln.material.leaf.v1',+ 'kiln.material.wood.v1',+ 'kiln.material.stone.v1',+ 'kiln.material.rubber.v1',+ 'kiln.material.painted-metal.v1',+ 'kiln.material.cloth.v1',+ 'kiln.material.skin.v1',+ 'kiln.material.glass.v1',+ 'kiln.material.emissive.v1',+ ]);+ expect(+ validateMaterialRecipeRequestV1({ schemaVersion: 1, id: 'wood-ish' }).issues.map(+ (issue) => issue.code,+ ),+ ).toContain('UNSUPPORTED_RECIPE_ID');+ expect(+ validateMaterialRecipeRequestV1({+ schemaVersion: 1,+ id: 'kiln.material.skin.v1',+ overrides: { opacity: 0.4 },+ }).issues.map((issue) => issue.code),+ ).toContain('UNSUPPORTED_OVERRIDE');+ expect(() =>+ createMaterialRecipeRequestV1('kiln.material.leaf.v1', { alphaCutoff: 4 }),+ ).toThrow(/alphaCutoff/);+ });++ test('validates approved resource slot and recipe compatibility', () => {+ const unsupportedOverride = validateMaterialRecipeRequestV1({+ schemaVersion: 1,+ id: 'kiln.material.glass.v1',+ overrides: {+ textureResources: { normal: 'kiln.texture.leaf-mask-albedo.v1' },+ },+ });+ expect(unsupportedOverride.valid).toBe(false);+ expect(unsupportedOverride.issues.map((issue) => issue.code)).toEqual(+ expect.arrayContaining(['UNSUPPORTED_OVERRIDE']),+ );+ const wrongSlot = validateMaterialRecipeRequestV1({+ schemaVersion: 1,+ id: 'kiln.material.bark.v1',+ overrides: {+ textureResources: { baseColor: 'kiln.texture.neutral-normal.v1' },+ },+ });+ expect(wrongSlot.issues.map((issue) => issue.code)).toContain('RESOURCE_SLOT_MISMATCH');+ const wrongRecipe = validateMaterialRecipeRequestV1({+ schemaVersion: 1,+ id: 'kiln.material.leaf.v1',+ overrides: {+ textureResources: { baseColor: 'kiln.texture.bark-albedo.v1' },+ },+ });+ expect(wrongRecipe.issues.map((issue) => issue.code)).toContain('RESOURCE_RECIPE_MISMATCH');++ const leaf = validateMaterialRecipeRequestV1({+ schemaVersion: 1,+ id: 'kiln.material.leaf.v1',+ overrides: {+ textureResources: { baseColor: 'kiln.texture.leaf-mask-albedo.v1' },+ },+ });+ expect(leaf.valid).toBe(true);+ });++ test('recipe snapshot is byte-stable and contains only core glTF PBR fields', () => {+ const snapshot = `${JSON.stringify(materialRecipeSnapshotV1(), null, 2)}\n`;+ expect(Buffer.byteLength(snapshot)).toBe(5742);+ expect(createHash('sha256').update(snapshot).digest('hex')).toBe(+ 'a3a10b73867e6e2c615e490b6d3d63c1b264d278be931c513917103b4871f737',+ );+ for (const entry of materialRecipeSnapshotV1()) {+ expect(entry.defaults).toEqual(+ expect.objectContaining({+ baseColorFactor: expect.any(Array),+ metallicFactor: expect.any(Number),+ roughnessFactor: expect.any(Number),+ emissiveFactor: expect.any(Array),+ alphaMode: expect.stringMatching(/^(OPAQUE|MASK|BLEND)$/),+ doubleSided: expect.any(Boolean),+ textureResources: expect.any(Object),+ }),+ );+ expect(entry.defaults).not.toHaveProperty('shader');+ expect(entry.defaults).not.toHaveProperty('extension');+ }+ });++ test('masked leaf remains distinct from blended glass', () => {+ const leaf = resolveMaterialRecipeV1(createMaterialRecipeRequestV1('kiln.material.leaf.v1'));+ const glass = resolveMaterialRecipeV1(createMaterialRecipeRequestV1('kiln.material.glass.v1'));+ expect(leaf).toMatchObject({ alphaMode: 'MASK', alphaCutoff: 0.5, doubleSided: true });+ expect(glass).toMatchObject({ alphaMode: 'BLEND', doubleSided: true });+ expect(leaf.alphaMode).not.toBe(glass.alphaMode);+ });+});++describe('MAT-014 executable portable recipe library', () => {+ test('all ten recipes render as validator-clean core glTF materials', async () => {+ const root = new THREE.Group();+ root.name = 'MaterialRecipeGallery';+ for (const [index, id] of MATERIAL_RECIPE_IDS.entries()) {+ const applied = await applyMaterialRecipeV1(createMaterialRecipeRequestV1(id));+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(0.8, 0.8, 0.8), applied.material);+ mesh.name = `Recipe_${id}`;+ mesh.position.x = index;+ root.add(mesh);+ }+ const rendered = await renderSceneToGLB(root, { sceneName: 'MaterialRecipeGallery' });+ expect(rendered.gltfValidation.issues.numErrors).toBe(0);+ const document = await new WebIO().readBinary(rendered.bytes);+ expect(document.getRoot().listExtensionsUsed()).toEqual([]);+ const byName = new Map(+ document+ .getRoot()+ .listMaterials()+ .map((material) => [material.getName(), material]),+ );+ for (const id of MATERIAL_RECIPE_IDS) expect(byName.has(id)).toBe(true);+ expect(byName.get('kiln.material.leaf.v1')?.getAlphaMode()).toBe('MASK');+ expect(byName.get('kiln.material.leaf.v1')?.getDoubleSided()).toBe(true);+ expect(byName.get('kiln.material.glass.v1')?.getAlphaMode()).toBe('BLEND');+ expect(byName.get('kiln.material.emissive.v1')?.getEmissiveFactor()).not.toEqual([0, 0, 0]);+ });++ test('sandbox executes the discovered helper with approved resource IDs', async () => {+ const executed = await executeKilnCode(`+ const meta = { name: 'RecipeSandbox', category: 'vegetation' };+ async function build() {+ const root = createRoot('RecipeSandbox');+ const leaf = await materialRecipe('kiln.material.leaf.v1', {+ alphaCutoff: 0.42,+ textureResources: { baseColor: 'kiln.texture.leaf-mask-albedo.v1' },+ });+ createPart('Mesh_Leaf', foliageCardGeo({ width: 1, height: 1 }), leaf, { parent: root });+ return root;+ }+ `);+ expect(executed.primitiveUsage).toMatchObject({+ materialRecipe: 1,+ createRoot: 1,+ createPart: 1,+ foliageCardGeo: 1,+ });+ const rendered = await renderSceneToGLB(executed.root, { sceneName: 'RecipeSandbox' });+ expect(rendered.gltfValidation.issues.numErrors).toBe(0);+ expect(rendered.materialRecipeApplications).toMatchObject([+ {+ schemaVersion: 1,+ recipeId: 'kiln.material.leaf.v1',+ recipeVersion: 1,+ portableModel: 'pbrMetallicRoughness',+ },+ ]);+ expect(rendered.materialResourceProvenance).toMatchObject([+ {+ schemaVersion: 1,+ resourceId: 'kiln.texture.leaf-mask-albedo.v1',+ usage: 'albedo',+ colorSpace: 'srgb',+ },+ ]);+ expect(rendered.materialResourceProvenance?.[0]?.contentHash).toMatch(/^[a-f0-9]{64}$/);+ const document = await new WebIO().readBinary(rendered.bytes);+ const material = document.getRoot().listMaterials()[0];+ expect(material?.getAlphaMode()).toBe('MASK');+ expect(material?.getAlphaCutoff()).toBeCloseTo(0.42);+ expect(document.getRoot().listTextures()).toHaveLength(1);+ });++ test('capability DTO is executable, bounded, and path-free', () => {+ const capabilities = listMaterialRecipeCapabilitiesV1();+ expect(capabilities.recipes).toHaveLength(10);+ expect(capabilities.resources.length).toBeGreaterThan(0);+ expect(JSON.stringify(capabilities)).not.toMatch(/(?:file:|[A-Z]:\\|\/home\/|secret|token)/i);+ expect(capabilities.recipes.every((recipe) => recipe.portable)).toBe(true);+ });+});diff --git a/src/__tests__/material-resources.test.ts b/src/__tests__/material-resources.test.tsnew file mode 100644index 00000000..53fff3ab--- /dev/null+++ b/src/__tests__/material-resources.test.ts@@ -0,0 +1,89 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import { applyMaterialRecipeV1 } from '../material-recipe-runtime';+import { createMaterialRecipeRequestV1 } from '../material-recipes';+import {+ ApprovedTextureResourceCache,+ collectMaterialResourceProvenance,+ loadLegacyTextureSource,+ readMaterialResourceProvenance,+} from '../material-resources';++describe('MAT-016 approved resource boundary', () => {+ test('resolves only a closed ID and exposes bytes without paths or secrets', () => {+ const cache = new ApprovedTextureResourceCache();+ const resolved = cache.resolve('kiln.texture.bark-albedo.v1');+ expect(resolved.bytes.subarray(0, 4)).toEqual(new Uint8Array([137, 80, 78, 71]));+ expect(resolved.provenance).toMatchObject({+ resourceId: 'kiln.texture.bark-albedo.v1',+ hashAlgorithm: 'sha256',+ usage: 'albedo',+ colorSpace: 'srgb',+ resourceVersion: 1,+ recipeVersion: 1,+ });+ expect(resolved.provenance.contentHash).toBe(+ 'ec74fd42fe317f578018a13a65d81a726e9baeade068ae016cff30c15507017f',+ );+ expect(resolved.descriptor.contentHash).toBe(resolved.provenance.contentHash);+ expect(JSON.stringify(resolved.descriptor)).not.toMatch(+ /(?:path|file:|secret|token|[A-Z]:\\)/i,+ );+ expect(() => cache.resolve('kiln.texture.not-approved.v1' as never)).toThrow(/Unsupported/);+ });++ test('retains an explicit compatibility read for legacy byte/path programs', async () => {+ const cache = new ApprovedTextureResourceCache();+ const bytes = cache.resolve('kiln.texture.bark-albedo.v1').bytes;+ const legacy = await loadLegacyTextureSource(bytes, { usage: 'albedo', name: 'legacy-bark' });+ expect(legacy.name).toBe('legacy-bark');+ expect(legacy.userData['kilnTextureSource']).toEqual({+ schemaVersion: 1,+ source: 'legacy-compatible-read',+ });+ expect(readMaterialResourceProvenance(legacy)).toBeUndefined();+ });+});++describe('MAT-017 content cache and provenance', () => {+ test('deduplicates encoded content and decoded variants by content hash', async () => {+ const cache = new ApprovedTextureResourceCache();+ const first = await cache.load('kiln.texture.leaf-mask-albedo.v1');+ const second = await cache.load('kiln.texture.leaf-mask-albedo.v1');+ expect(second.texture).toBe(first.texture);+ expect(second.provenance).toEqual(first.provenance);+ expect(cache.stats()).toEqual({+ approvedIdsResolved: 1,+ uniqueContentHashes: 1,+ decodedTextureVariants: 1,+ encodedBytes: first.bytes.byteLength,+ });+ });++ test('recipe application records ID/hash/usage/color space/version and scene collection', async () => {+ const cache = new ApprovedTextureResourceCache();+ const applied = await applyMaterialRecipeV1(+ createMaterialRecipeRequestV1('kiln.material.leaf.v1', {+ textureResources: { baseColor: 'kiln.texture.leaf-mask-albedo.v1' },+ }),+ { cache, name: 'ApprovedLeaf' },+ );+ expect(applied.material.map).toBeDefined();+ expect(applied.material.alphaTest).toBe(0.5);+ expect(applied.material.transparent).toBe(false);+ expect(applied.provenance.resources).toHaveLength(1);+ expect(applied.provenance.resources[0]).toMatchObject({+ resourceId: 'kiln.texture.leaf-mask-albedo.v1',+ usage: 'albedo',+ colorSpace: 'srgb',+ resourceVersion: 1,+ recipeVersion: 1,+ });+ expect(applied.provenance.resources[0]!.contentHash).toMatch(/^[0-9a-f]{64}$/);++ const root = new THREE.Group();+ root.add(new THREE.Mesh(new THREE.PlaneGeometry(1, 1), applied.material));+ expect(collectMaterialResourceProvenance(root)).toEqual(applied.provenance.resources);+ });+});diff --git a/src/__tests__/prompt.test.ts b/src/__tests__/prompt.test.tsindex 7ff8ca84..34735b05 100644--- a/src/__tests__/prompt.test.ts+++ b/src/__tests__/prompt.test.ts@@ -18,17 +18,30 @@ import {KILN_BOTH_SYSTEM_PROMPT,KILN_REFINE_DIRECTIVE,ARCHITECTURE_CONTEXT,+ ARCHITECTURE_RIDGE_X_SCAFFOLD,+ ARCHITECTURE_RIDGE_Z_SCAFFOLD,+ ARCHITECTURE_PANEL_DIRECTION_ANTI_EXAMPLE,PROP_CONTEXT,ENVIRONMENT_CONTEXT,+ VEGETATION_CONTEXT,VFX_CONTEXT,KILN_API_SECTION,KILN_API_SECTION_UNIFIED,KILN_VISUAL_QA_UNIFIED,KILN_REFINE_DIRECTIVE_UNIFIED,KILN_EDIT_DIRECTIVE_UNIFIED,+ KILN_COORDINATE_CONTRACT,} from '../prompt';+import { KILN_ASSET_FRAME, createAssetIntentV1 } from '../contracts';describe('getSystemPrompt', () => {+ test('coordinate prompt derives from the canonical engine frame', () => {+ expect(KILN_COORDINATE_CONTRACT).toContain(`${KILN_ASSET_FRAME.forward} = forward`);+ expect(KILN_COORDINATE_CONTRACT).toContain(`${KILN_ASSET_FRAME.up} = up`);+ expect(KILN_COORDINATE_CONTRACT).toContain(`${KILN_ASSET_FRAME.right} = asset right`);+ expect(KILN_COORDINATE_CONTRACT).toContain(`Y=${KILN_ASSET_FRAME.groundY}`);+ });+test('returns the GLB prompt for mode=glb', () => {expect(getSystemPrompt('glb')).toBe(KILN_SYSTEM_PROMPT);});@@ -123,9 +136,42 @@ describe('buildUserPrompt', () => {expect(ARCHITECTURE_CONTEXT).toContain('Roof');});+ test('architecture context carries exactly one executable scaffold per ridge axis and one panel anti-example', () => {+ expect(ARCHITECTURE_CONTEXT.split(ARCHITECTURE_RIDGE_X_SCAFFOLD)).toHaveLength(2);+ expect(ARCHITECTURE_CONTEXT.split(ARCHITECTURE_RIDGE_Z_SCAFFOLD)).toHaveLength(2);+ expect(ARCHITECTURE_CONTEXT.split(ARCHITECTURE_PANEL_DIRECTION_ANTI_EXAMPLE)).toHaveLength(2);+ expect(ARCHITECTURE_RIDGE_X_SCAFFOLD).toContain("ridgeAxis: 'x'");+ expect(ARCHITECTURE_RIDGE_Z_SCAFFOLD).toContain("ridgeAxis: 'z'");+ expect(ARCHITECTURE_PANEL_DIRECTION_ANTI_EXAMPLE).toContain('WRONG:');+ expect(ARCHITECTURE_PANEL_DIRECTION_ANTI_EXAMPLE).toContain('ridge to eave');+ });+test('does not append the architecture directive for other categories', () => {const prompt = buildUserPrompt({ prompt: 'a barrel', mode: 'glb', category: 'prop' });expect(prompt).not.toContain(ARCHITECTURE_CONTEXT);+ expect(prompt).not.toContain(ARCHITECTURE_RIDGE_X_SCAFFOLD);+ expect(prompt).not.toContain(ARCHITECTURE_RIDGE_Z_SCAFFOLD);+ });++ test('CHAR-031 injects only the resolved character body-plan recipe', () => {+ const dog = buildUserPrompt({+ prompt: 'a dog',+ mode: 'glb',+ category: 'character',+ intent: createAssetIntentV1({ category: 'character', subtype: 'quadruped' }),+ });+ expect(dog).toContain('Resolved body plan: QUADRUPED');+ expect(dog).not.toContain('Resolved body plan: BIPED');+ expect(dog).not.toContain('Resolved body plan: SERPENTINE');++ const serpent = buildUserPrompt({+ prompt: 'a serpent',+ mode: 'glb',+ category: 'character',+ intent: createAssetIntentV1({ category: 'character', subtype: 'serpentine' }),+ });+ expect(serpent).toContain('Resolved body plan: SERPENTINE');+ expect(serpent.toLowerCase()).not.toContain('knee');});test('appends the per-category rig context for prop / environment / vfx', () => {@@ -141,6 +187,80 @@ describe('buildUserPrompt', () => {expect(env).not.toContain(PROP_CONTEXT);});+ test('injects trusted W7 scope, modular grid, and VFX contracts into fresh prompts only', () => {+ const modularIntent = createAssetIntentV1({+ category: 'environment',+ subtype: 'modular-wall',+ scope: { scope: 'modularSet', explicit: true },+ modular: { grid: [2, 1, 2], units: 'm' },+ });+ const modular = buildUserPrompt({+ prompt: 'a modular stone wall kit',+ mode: 'glb',+ category: 'environment',+ intent: modularIntent,+ });+ expect(modular).toContain('## Resolved Asset Scope');+ expect(modular).toContain('trusted 2x1x2 m grid');+ expect(modular).toContain('reciprocal compatibleTypes');+ expect(modular).toContain('explicit allowedRotationsDegrees');+ expect(modular).toContain('Do not encode the grid in arbitrary userData');++ const vfxIntent = createAssetIntentV1({ category: 'vfx', subtype: 'billboard' });+ const vfx = buildUserPrompt({+ prompt: 'soft smoke billboard',+ mode: 'glb',+ category: 'vfx',+ intent: vfxIntent,+ });+ expect(vfx).toContain('## Resolved VFX Contract');+ expect(vfx).toContain('portability=portable');+ expect(vfx).toContain('mode=camera-spherical');+ expect(vfx).toContain('real alpha data');+ expect(vfx).toContain('vfx.effect.surface.<card|beam|trail|volume|core>');++ const refine = buildUserPrompt({+ prompt: 'make the stones darker',+ mode: 'glb',+ category: 'environment',+ intent: modularIntent,+ existingCode: 'function build() { return createRoot("WallKit"); }',+ });+ expect(refine).not.toContain('## Resolved Asset Scope');+ expect(refine).not.toContain('trusted 2x1x2 m grid');+ });++ test('VEG-018 injects only resolved vegetation structure and material-mode guidance', () => {+ const rich = buildUserPrompt({+ prompt: 'a lush oak',+ mode: 'glb',+ category: 'vegetation',+ intent: createAssetIntentV1({+ category: 'vegetation',+ vegetation: { subtype: 'tree', growthState: 'lush' },+ material: { mode: 'pbrRecipe' },+ }),+ });+ expect(rich).toContain(VEGETATION_CONTEXT);+ expect(rich).toContain('Growth form: tree; state: lush; canopy profile: broadleaf');+ expect(rich).toContain('two to six restrained foliage value roles');+ expect(rich).toContain("materialRecipe('kiln.material.leaf.v1'");+ expect(rich).not.toContain('taperedBranchGeo');++ const optimized = buildUserPrompt({+ prompt: 'an optimized shrub',+ mode: 'glb',+ category: 'vegetation',+ intent: createAssetIntentV1({+ category: 'vegetation',+ vegetation: { subtype: 'shrub' },+ material: { mode: 'flatOptimized' },+ }),+ });+ expect(optimized).toContain('Use one coherent foliage value role.');+ expect(optimized).not.toContain('## Portable material recipes');+ });+test('per-category rig context is dropped when refining (existingCode set)', () => {const prompt = buildUserPrompt({prompt: 'open the lid',@@ -160,6 +280,8 @@ describe('buildUserPrompt', () => {existingCode: 'function build() { return createRoot("Tower"); }',});expect(prompt).not.toContain(ARCHITECTURE_CONTEXT);+ expect(prompt).not.toContain(ARCHITECTURE_RIDGE_X_SCAFFOLD);+ expect(prompt).not.toContain(ARCHITECTURE_RIDGE_Z_SCAFFOLD);expect(prompt).toContain('## Edit Request');});diff --git a/src/__tests__/render-edges.test.ts b/src/__tests__/render-edges.test.tsindex 133c8683..5045f658 100644--- a/src/__tests__/render-edges.test.ts+++ b/src/__tests__/render-edges.test.ts@@ -137,7 +137,8 @@ describe('renderGLB animation track bridging', () => {const meta = { name: 'PosTrack' };function build() {const root = createRoot('PosTrack');- createPivot('Body', [0, 0, 0], root);+ const body = createPivot('Body', [0, 0, 0], root);+ createPart('BodyMesh', boxGeo(0.2, 0.2, 0.2), gameMaterial(0x888888), { parent: body });return root;}function animate() {@@ -165,7 +166,8 @@ function animate() {const meta = { name: 'ScaleTrack' };function build() {const root = createRoot('ScaleTrack');- createPivot('Body', [0, 0, 0], root);+ const body = createPivot('Body', [0, 0, 0], root);+ createPart('BodyMesh', boxGeo(0.2, 0.2, 0.2), gameMaterial(0x888888), { parent: body });return root;}function animate() {@@ -191,7 +193,8 @@ function animate() {const meta = { name: 'Missing' };function build() {const root = createRoot('Missing');- createPivot('Body', [0, 0, 0], root);+ const body = createPivot('Body', [0, 0, 0], root);+ createPart('BodyMesh', boxGeo(0.2, 0.2, 0.2), gameMaterial(0x888888), { parent: body });return root;}function animate() {diff --git a/src/__tests__/scene-palette.test.ts b/src/__tests__/scene-palette.test.tsindex 034b7b6f..13b03189 100644--- a/src/__tests__/scene-palette.test.ts+++ b/src/__tests__/scene-palette.test.ts@@ -120,6 +120,7 @@ describe('snapGlbToPalette', () => {expect(out!.report!.metrics.uniqueMaterials).toBeLessThanOrEqual(PAL.length);expect(out!.summary.materialsAfter).toBeLessThan(out!.summary.materialsBefore);expect(out!.report!.grade).not.toBe('F');+ expect(out!.gltfValidation.issues.numErrors).toBe(0);// valid GLB outconst doc = await new WebIO().readBinary(out!.bytes);expect(doc.getRoot().listNodes().length).toBeGreaterThan(0);diff --git a/src/__tests__/textures.test.ts b/src/__tests__/textures.test.tsindex 8f0369f5..bdfd5455 100644--- a/src/__tests__/textures.test.ts+++ b/src/__tests__/textures.test.ts@@ -6,24 +6,49 @@ import { describe, it, expect } from 'bun:test';import * as THREE from 'three';import sharp from 'sharp';import { NodeIO } from '@gltf-transform/core';-import { createRoot, boxGeo, gameMaterial } from '../primitives';-import { loadTexture, pbrMaterial } from '../textures';+import { createRoot, boxGeo, foliageCardGeo, gameMaterial } from '../primitives';+import { foliageMaterial, loadTexture, pbrMaterial } from '../textures';import { autoUnwrap } from '../uv';-import { renderSceneToGLB } from '../render';+import { optimizeGlbBytes, renderSceneToGLB } from '../render';+import { createAssetIntentV1 } from '../contracts';+import { inspectSceneMaterials } from '../qa/material';+import { validateFinalGlbBytes } from '../qa/gltf';-async function makeSolidPng(color: { r: number; g: number; b: number }): Promise<Buffer> {+async function makeSolidPng(+ color: { r: number; g: number; b: number },+ alpha = 1,+): Promise<Buffer> {return sharp({create: {width: 16,height: 16,channels: 4,- background: { ...color, alpha: 1 },+ background: { ...color, alpha },},}).png().toBuffer();}+async function makePatternPng(color: { r: number; g: number; b: number }): Promise<Buffer> {+ const width = 16;+ const height = 16;+ const pixels = Buffer.alloc(width * height * 4);+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const offset = (y * width + x) * 4;+ const scale = (x + y) % 2 === 0 ? 1 : 0.5;+ pixels[offset] = Math.round(color.r * scale);+ pixels[offset + 1] = Math.round(color.g * scale);+ pixels[offset + 2] = Math.round(color.b * scale);+ pixels[offset + 3] = 255;+ }+ }+ return sharp(pixels, { raw: { width, height, channels: 4 } })+ .png()+ .toBuffer();+}+describe('Wave 3B: loadTexture + pbrMaterial', () => {it('loadTexture decodes a PNG into a DataTexture with encoded bytes stashed', async () => {const png = await makeSolidPng({ r: 255, g: 100, b: 50 });@@ -39,6 +64,34 @@ describe('Wave 3B: loadTexture + pbrMaterial', () => {expect(encoded).toBeDefined();expect(encoded.mime).toBe('image/png');expect(encoded.bytes.length).toBe(png.length);+ const meta = (tex.userData as Record<string, unknown>)['kilnTexture'] as {+ hasAlpha: boolean;+ };+ expect(meta.hasAlpha).toBe(false);++ const translucent = await loadTexture(await makeSolidPng({ r: 255, g: 100, b: 50 }, 0.4));+ expect(+ (+ (translucent.userData as Record<string, unknown>)['kilnTexture'] as {+ hasAlpha: boolean;+ }+ ).hasAlpha,+ ).toBe(true);+ });++ it('assigns sRGB only to color textures and linear space to data textures', async () => {+ const png = await makeSolidPng({ r: 128, g: 128, b: 255 });+ expect((await loadTexture(png, { usage: 'albedo' })).colorSpace).toBe(THREE.SRGBColorSpace);+ expect((await loadTexture(png, { usage: 'emissive' })).colorSpace).toBe(THREE.SRGBColorSpace);+ for (const usage of [+ 'normal',+ 'roughness',+ 'metalness',+ 'metallicRoughness',+ 'occlusion',+ ] as const) {+ expect((await loadTexture(png, { usage })).colorSpace).toBe(THREE.NoColorSpace);+ }});it('pbrMaterial with scalar inputs produces a MeshStandardMaterial', () => {@@ -58,6 +111,138 @@ describe('Wave 3B: loadTexture + pbrMaterial', () => {expect(mat.color.getHex()).toBe(0xffffff);});+ it('requires one explicit packed G/B metallic-roughness texture', async () => {+ const png = await makeSolidPng({ r: 0, g: 180, b: 80 });+ const packed = await loadTexture(png, { usage: 'metallicRoughness' });+ const mat = pbrMaterial({ metallicRoughness: packed });+ expect(mat.roughnessMap).toBe(packed);+ expect(mat.metalnessMap).toBe(packed);++ const roughness = await loadTexture(png, { usage: 'roughness' });+ const metalness = await loadTexture(png, { usage: 'metalness' });+ expect(() => pbrMaterial({ roughness, metalness })).toThrow(/Pack G=roughness\/B=metalness/);+ expect(() => pbrMaterial({ roughness })).toThrow(/same packed G\/B texture/);+ expect(() => pbrMaterial({ metallicRoughness: roughness })).toThrow(+ /loaded for roughness, not metallicRoughness/,+ );+ });++ it('rejects invalid portable alpha and sidedness combinations at construction', () => {+ expect(() => pbrMaterial({ alphaMode: 'invalid' as never })).toThrow(/alphaMode must be/);+ expect(() => pbrMaterial({ alphaMode: 'opaque', alphaCutoff: 0.5 })).toThrow(+ /only when alphaMode is "mask"/,+ );+ expect(() => pbrMaterial({ alphaMode: 'mask', alphaCutoff: Number.NaN })).toThrow(+ /finite number in \[0,1\]/,+ );+ expect(() => pbrMaterial({ doubleSided: 'yes' as never })).toThrow(+ /doubleSided must be a boolean/,+ );+ });++ it('reports stable blockers for decode, dimensions, UVs, and color-space errors', async () => {+ const png = await makeSolidPng({ r: 80, g: 120, b: 160 });+ const intent = createAssetIntentV1({ category: 'prop' });+ const findingsFor = (root: THREE.Object3D) => inspectSceneMaterials({ intent, scene: root });+ const findingCodes = (root: THREE.Object3D): string[] =>+ findingsFor(root).map((finding) => finding.code);++ const undecodable = new THREE.DataTexture(+ new Uint8Array([255, 255, 255, 255]),+ 1,+ 1,+ THREE.RGBAFormat,+ );+ undecodable.name = 'raw-data';+ const decodeMaterial = pbrMaterial({ albedo: undecodable });+ decodeMaterial.name = 'DecodeMaterial';+ const decodeMesh = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), decodeMaterial);+ decodeMesh.name = 'Mesh_Decode';+ const decodeRoot = createRoot('DecodeFailure');+ decodeRoot.add(decodeMesh);+ const decodeFinding = findingsFor(decodeRoot).find(+ (finding) => finding.code === 'MAT_TEXTURE_DECODE_FAILED',+ );+ expect(decodeFinding?.affected).toEqual({+ node: 'Mesh_Decode',+ material: 'DecodeMaterial',+ texture: 'raw-data',+ attribute: 'map',+ });++ const invalidDimensions = await loadTexture(png, { usage: 'albedo' });+ (invalidDimensions.image as { width: number }).width = 0;+ const dimensionsRoot = createRoot('InvalidDimensions');+ dimensionsRoot.add(+ new THREE.Mesh(new THREE.PlaneGeometry(1, 1), pbrMaterial({ albedo: invalidDimensions })),+ );+ expect(findingCodes(dimensionsRoot)).toContain('MAT_TEXTURE_INVALID_DIMENSIONS');++ const withoutUvs = await loadTexture(png, { usage: 'albedo' });+ withoutUvs.name = 'missing-uv-albedo';+ const noUvGeometry = new THREE.PlaneGeometry(1, 1);+ noUvGeometry.deleteAttribute('uv');+ const noUvMaterial = pbrMaterial({ albedo: withoutUvs });+ noUvMaterial.name = 'MissingUvMaterial';+ const noUvMesh = new THREE.Mesh(noUvGeometry, noUvMaterial);+ noUvMesh.name = 'Mesh_MissingUv';+ const uvRoot = createRoot('MissingUvs');+ uvRoot.add(noUvMesh);+ const uvFinding = findingsFor(uvRoot).find(+ (finding) => finding.code === 'MAT_TEXTURE_UV_MISSING',+ );+ expect(uvFinding?.affected).toEqual({+ node: 'Mesh_MissingUv',+ material: 'MissingUvMaterial',+ texture: 'missing-uv-albedo',+ attribute: 'map',+ });++ const wrongColorSpace = await loadTexture(png, { usage: 'albedo' });+ const wrongColorMaterial = pbrMaterial({ albedo: wrongColorSpace });+ wrongColorSpace.colorSpace = THREE.NoColorSpace;+ const colorRoot = createRoot('WrongColorSpace');+ colorRoot.add(new THREE.Mesh(new THREE.PlaneGeometry(1, 1), wrongColorMaterial));+ expect(findingCodes(colorRoot)).toContain('MAT_TEXTURE_COLOR_SPACE');+ });++ it('localizes non-finite factors and missing tangent-space data', async () => {+ const intent = createAssetIntentV1({ category: 'prop' });+ const png = await makePatternPng({ r: 128, g: 128, b: 255 });+ const normal = await loadTexture(png, { usage: 'normal', name: 'normal-detail' });+ const material = pbrMaterial({ normal });+ material.name = 'DamagedPbr';+ material.roughness = Number.NaN;+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), material);+ mesh.name = 'Mesh_Panel';+ const root = createRoot('MaterialDiagnostics');+ root.add(mesh);++ const findings = inspectSceneMaterials({ intent, scene: root });+ const factor = findings.find((finding) => finding.code === 'MAT_NONFINITE_FACTOR');+ expect(factor?.affected?.material).toBe('DamagedPbr');+ expect(factor?.measurement?.name).toBe('roughness');+ const tangents = findings.find((finding) => finding.code === 'MAT_NORMAL_TANGENTS_MISSING');+ expect(tangents?.affected).toEqual({+ node: 'Mesh_Panel',+ material: 'DamagedPbr',+ texture: 'normal-detail',+ attribute: 'normal',+ });+ expect(tangents?.disposition).toBe('warn');++ const strictFindings = inspectSceneMaterials({+ intent: createAssetIntentV1({+ category: 'prop',+ capabilities: ['precomputedTangents'],+ }),+ scene: root,+ });+ expect(+ strictFindings.find((finding) => finding.code === 'MAT_NORMAL_TANGENTS_MISSING')?.disposition,+ ).toBe('block');+ });+it('texture survives round-trip through GLB export', async () => {const png = await makeSolidPng({ r: 255, g: 0, b: 128 });const tex = await loadTexture(png);@@ -96,4 +281,147 @@ describe('Wave 3B: loadTexture + pbrMaterial', () => {const mats = doc.getRoot().listMaterials();expect(mats[0]!.getBaseColorTexture()).toBeNull();});++ it('foliage cards export MASK cutoff + double-sided and remain valid after rebake', async () => {+ const png = await makeSolidPng({ r: 30, g: 180, b: 60 }, 0.4);+ const albedo = await loadTexture(png, { usage: 'albedo', name: 'leaf-albedo' });+ const root = createRoot('Foliage');+ const card = new THREE.Mesh(+ foliageCardGeo({ width: 2, height: 3 }),+ foliageMaterial(albedo, { alphaCutoff: 0.42 }),+ );+ card.name = 'Mesh_Leaves';+ root.add(card);++ const sceneQa = inspectSceneMaterials({+ intent: createAssetIntentV1({ category: 'vegetation' }),+ scene: root,+ });+ expect(sceneQa).toEqual([]);++ const rendered = await renderSceneToGLB(root);+ expect(rendered.gltfValidation.issues.numErrors).toBe(0);+ const doc = await new NodeIO().readBinary(rendered.bytes);+ const mat = doc.getRoot().listMaterials()[0]!;+ expect(mat.getAlphaMode()).toBe('MASK');+ expect(mat.getAlphaCutoff()).toBeCloseTo(0.42);+ expect(mat.getDoubleSided()).toBe(true);++ const rebaked = await optimizeGlbBytes(rendered.bytes, { mode: 'palette' });+ expect(rebaked?.gltfValidation.issues.numErrors).toBe(0);+ const rebakedDoc = await new NodeIO().readBinary(rebaked!.bytes);+ const rebakedMat = rebakedDoc.getRoot().listMaterials()[0]!;+ expect(rebakedMat.getAlphaMode()).toBe('MASK');+ expect(rebakedMat.getAlphaCutoff()).toBeCloseTo(0.42);+ expect(rebakedMat.getDoubleSided()).toBe(true);+ });++ it('preserves UVs, tangents, PBR factors, and texture slots through a validated rebake', async () => {+ const albedo = await loadTexture(await makePatternPng({ r: 180, g: 120, b: 80 }), {+ usage: 'albedo',+ });+ const normal = await loadTexture(await makePatternPng({ r: 128, g: 128, b: 255 }), {+ usage: 'normal',+ });+ const metallicRoughness = await loadTexture(await makePatternPng({ r: 0, g: 180, b: 80 }), {+ usage: 'metallicRoughness',+ });+ const geometry = new THREE.PlaneGeometry(1, 1);+ const tangentValues = new Float32Array(geometry.getAttribute('position').count * 4);+ for (let offset = 0; offset < tangentValues.length; offset += 4) {+ tangentValues.set([1, 0, 0, 1], offset);+ }+ geometry.setAttribute('tangent', new THREE.BufferAttribute(tangentValues, 4));++ const root = createRoot('PortablePbr');+ root.add(+ new THREE.Mesh(+ geometry,+ pbrMaterial({+ albedo,+ normal,+ metallicRoughness,+ roughness: 0.37,+ metalness: 0.62,+ }),+ ),+ );++ const rendered = await renderSceneToGLB(root);+ expect(rendered.gltfValidation.issues.numErrors).toBe(0);+ const renderedDoc = await new NodeIO().readBinary(rendered.bytes);+ const renderedMaterial = renderedDoc.getRoot().listMaterials()[0]!;+ expect(renderedMaterial.getBaseColorTexture()).not.toBeNull();+ expect(renderedMaterial.getNormalTexture()).not.toBeNull();+ expect(renderedMaterial.getMetallicRoughnessTexture()).not.toBeNull();+ const rebaked = await optimizeGlbBytes(rendered.bytes, { mode: 'palette' });+ expect(rebaked).toBeDefined();+ expect(rebaked!.gltfValidation.issues.numErrors).toBe(0);++ const doc = await new NodeIO().readBinary(rebaked!.bytes);+ const material = doc.getRoot().listMaterials()[0]!;+ expect(material.getBaseColorTexture()).not.toBeNull();+ expect(material.getNormalTexture()).not.toBeNull();+ expect(material.getMetallicRoughnessTexture()).not.toBeNull();+ expect(material.getRoughnessFactor()).toBeCloseTo(0.37);+ expect(material.getMetallicFactor()).toBeCloseTo(0.62);+ const primitive = doc.getRoot().listMeshes()[0]!.listPrimitives()[0]!;+ expect(primitive.getAttribute('TEXCOORD_0')).not.toBeNull();+ expect(primitive.getAttribute('TANGENT')).not.toBeNull();+ });++ it('preserves slot semantics when different usages have byte-identical source images', async () => {+ const sharedBytes = await makeSolidPng({ r: 22, g: 33, b: 44 });+ const albedo = await loadTexture(sharedBytes, { usage: 'albedo' });+ const normal = await loadTexture(sharedBytes, { usage: 'normal' });+ const metallicRoughness = await loadTexture(sharedBytes, {+ usage: 'metallicRoughness',+ });+ const geometry = new THREE.PlaneGeometry(1, 1);+ const tangentValues = new Float32Array(geometry.getAttribute('position').count * 4);+ for (let offset = 0; offset < tangentValues.length; offset += 4) {+ tangentValues.set([1, 0, 0, 1], offset);+ }+ geometry.setAttribute('tangent', new THREE.BufferAttribute(tangentValues, 4));++ const root = createRoot('IdenticalTextureBytes');+ root.add(+ new THREE.Mesh(+ geometry,+ pbrMaterial({ albedo, normal, metallicRoughness, roughness: 0.4, metalness: 0.6 }),+ ),+ );++ const rendered = await renderSceneToGLB(root);+ const rebaked = await optimizeGlbBytes(rendered.bytes, { mode: 'palette' });+ expect(rendered.gltfValidation.issues.numErrors).toBe(0);+ expect(rebaked?.gltfValidation.issues.numErrors).toBe(0);++ for (const bytes of [rendered.bytes, rebaked!.bytes]) {+ const doc = await new NodeIO().readBinary(bytes);+ const material = doc.getRoot().listMaterials()[0]!;+ expect(material.getBaseColorTexture()).not.toBeNull();+ expect(material.getNormalTexture()).not.toBeNull();+ expect(material.getMetallicRoughnessTexture()).not.toBeNull();+ expect(material.getRoughnessFactor()).toBeCloseTo(0.4);+ expect(material.getMetallicFactor()).toBeCloseTo(0.6);+ }+ });++ it('rejects an opaque foliage card with a stable structured finding', () => {+ const root = createRoot('BadFoliage');+ const card = new THREE.Mesh(foliageCardGeo(), gameMaterial(0x228833));+ card.name = 'Mesh_BadLeaves';+ root.add(card);+ const findings = inspectSceneMaterials({+ intent: createAssetIntentV1({ category: 'vegetation' }),+ scene: root,+ });+ expect(findings.map((finding) => finding.code)).toContain('MAT_FOLIAGE_CARD_CONTRACT');+ });++ it('Khronos validator reports malformed final bytes as errors', async () => {+ const report = await validateFinalGlbBytes(new Uint8Array([0x67, 0x6c, 0x54, 0x46]));+ expect(report.issues.numErrors).toBeGreaterThan(0);+ });});diff --git a/src/__tests__/vegetation-prompt-integration.test.ts b/src/__tests__/vegetation-prompt-integration.test.tsnew file mode 100644index 00000000..bbe27f8f--- /dev/null+++ b/src/__tests__/vegetation-prompt-integration.test.ts@@ -0,0 +1,27 @@+import { describe, expect, test } from 'bun:test';++import { createAssetIntentV1, VEGETATION_SUBTYPES } from '../contracts';+import { buildUserPrompt } from '../prompt';+import {+ VEGETATION_REJECTED_HELPER_NAMES,+ VEGETATION_SUBTYPE_RECIPES_V1,+} from '../vegetation-prompt';++describe('VEG-017 generation-prompt integration', () => {+ test('injects only the resolved current-API vegetation recipe', () => {+ for (const subtype of VEGETATION_SUBTYPES) {+ const prompt = buildUserPrompt({+ prompt: `a ${subtype} specimen`,+ mode: 'glb',+ category: 'vegetation',+ intent: createAssetIntentV1({ category: 'vegetation', vegetation: { subtype } }),+ });+ expect(prompt).toContain(VEGETATION_SUBTYPE_RECIPES_V1[subtype].marker);+ for (const other of VEGETATION_SUBTYPES) {+ if (other === subtype) continue;+ expect(prompt).not.toContain(VEGETATION_SUBTYPE_RECIPES_V1[other].marker);+ }+ for (const helper of VEGETATION_REJECTED_HELPER_NAMES) expect(prompt).not.toContain(helper);+ }+ });+});diff --git a/src/__tests__/vehicle.test.ts b/src/__tests__/vehicle.test.tsnew file mode 100644index 00000000..1906121e--- /dev/null+++ b/src/__tests__/vehicle.test.ts@@ -0,0 +1,161 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import { readSemanticMetadataV1 } from '../contracts';+import {+ VEHICLE_AXES,+ createVehicleFrame,+ createWheelAssembly,+ createWheelGeometrySet,+ hasCanonicalVehicleFront,+ resolveVehicleWheelAssemblies,+} from '../vehicle';++const tire = new THREE.MeshStandardMaterial({ color: 0x181818 });+const metal = new THREE.MeshStandardMaterial({ color: 0x999999, metalness: 0.8 });++function layout(count: 2 | 4 | 6, transformed = false) {+ const parent = new THREE.Object3D();+ if (transformed) {+ parent.position.set(4, 2, -3);+ parent.rotation.set(0.2, 0.7, -0.1);+ }+ const axleXs = count === 2 ? [0] : count === 4 ? [1.2, -1.2] : [1.6, 0, -1.6];+ const frame = createVehicleFrame(`Vehicle${count}`, {+ parent,+ axles: axleXs.map((x, index) => ({ id: String(index), position: [x, 0.5, 0] })),+ seats: [{ id: 'driver', position: [0.25, 1, -0.25] }],+ contacts: axleXs.flatMap((x, index) => [+ { id: `${index}-left`, position: [x, 0, -0.8] as [number, number, number] },+ { id: `${index}-right`, position: [x, 0, 0.8] as [number, number, number] },+ ]),+ steering: [{ id: 'front', position: [axleXs[0]!, 0.5, 0] }],+ propulsion: [{ id: 'motor', position: [-0.5, 0.65, 0] }],+ });+ const geometries = createWheelGeometrySet(0.5, 0.2);+ const wheels = axleXs.flatMap((x, index) =>+ (['left', 'right'] as const).map((side) =>+ createWheelAssembly(+ 'Wheel',+ { tire, rim: metal },+ {+ radius: 0.5,+ width: 0.2,+ side,+ index,+ position: [x, 0.5, side === 'left' ? -0.8 : 0.8],+ steering: index === 0,+ geometries,+ parent: frame.root,+ },+ ),+ ),+ );+ parent.updateMatrixWorld(true);+ return { parent, frame, wheels, resolved: resolveVehicleWheelAssemblies(frame.root) };+}++describe('vehicle frame and wheel assembly', () => {+ test('owns the canonical +X/+Y/+Z frame and all typed socket families', () => {+ const { frame } = layout(4);+ expect(VEHICLE_AXES).toEqual({+ forward: [1, 0, 0],+ up: [0, 1, 0],+ right: [0, 0, 1],+ wheelAxle: [0, 0, 1],+ });+ expect(hasCanonicalVehicleFront(frame.root)).toBe(true);+ expect(frame.chassis.name).toBe('Socket_chassis_main');+ expect(frame.axles).toHaveLength(2);+ expect(frame.seats).toHaveLength(1);+ expect(frame.contacts).toHaveLength(4);+ expect(frame.steering).toHaveLength(1);+ expect(frame.propulsion).toHaveLength(1);+ expect(readSemanticMetadataV1(frame.axles[0]!)?.sockets[0]?.type).toBe('vehicle.axle');+ });++ for (const count of [2, 4, 6] as const) {+ test(`${count}-wheel transformed layout preserves one assembly per corner and +Z axles`, () => {+ const { frame, wheels, resolved } = layout(count, true);+ expect(resolved).toHaveLength(count);+ expect(new Set(resolved.map((wheel) => wheel.id)).size).toBe(count);+ const expectedAxle = new THREE.Vector3(0, 0, 1).transformDirection(frame.root.matrixWorld);+ for (const [wheelIndex, wheel] of resolved.entries()) {+ expect(wheel.source).toBe('semantic');+ expect(wheel.radius).toBeCloseTo(0.5, 4);+ expect(wheel.width).toBeCloseTo(0.2, 4);+ expect(wheel.spinAxisWorld.length()).toBeCloseTo(1, 6);+ expect(THREE.MathUtils.radToDeg(wheel.spinAxisWorld.angleTo(expectedAxle))).toBeCloseTo(+ 0,+ 6,+ );+ expect(wheel.centerWorld.distanceTo(wheel.pivotCenterWorld)).toBeCloseTo(0, 6);+ expect(wheel.pivot.name).toMatch(/^WheelPivot_(left|right)_\d+$/);+ expect(wheel.tire?.name).toMatch(/^Tire_(left|right)_\d+$/);+ expect(wheel.rim?.name).toMatch(/^Rim_(left|right)_\d+$/);+ expect(wheel.hub?.name).toMatch(/^Hub_(left|right)_\d+$/);+ expect(wheel.tire?.parent).toBe(wheel.pivot);+ expect(wheel.rim?.parent).toBe(wheel.pivot);+ expect(wheel.hub?.parent).toBe(wheel.pivot);+ wheel.pivot.rotation.z = (wheelIndex + 1) * 0.125;+ expect(wheel.pivot.rotation.z).toBeCloseTo((wheelIndex + 1) * 0.125, 8);+ }+ expect(wheels[0]!.tire.geometry).toBe(wheels.at(-1)!.tire.geometry);+ expect(wheels[0]!.rim.geometry).toBe(wheels.at(-1)!.rim.geometry);+ expect(wheels[0]!.hub.geometry).toBe(wheels.at(-1)!.hub.geometry);+ });+ }++ test('optional steering remains centered above the spin pivot and spin is animatable around +Z', () => {+ const { wheels } = layout(2);+ const wheel = wheels[0]!;+ expect(wheel.steeringPivot).toBeDefined();+ expect(wheel.spinPivot.parent).toBe(wheel.steeringPivot!);+ expect(wheel.spinPivot.position.length()).toBe(0);+ wheel.steeringPivot!.rotation.y = Math.PI / 8;+ wheel.spinPivot.rotation.z = Math.PI / 2;+ expect(wheel.steeringPivot!.rotation.y).toBeCloseTo(Math.PI / 8);+ expect(wheel.spinPivot.rotation.z).toBeCloseTo(Math.PI / 2);+ expect(readSemanticMetadataV1(wheel.spinPivot)?.frames.map((frame) => frame.id)).toContain(+ 'spin-axis.+z',+ );+ });++ test('declared tire width is exact and cannot equal or exceed the diameter', () => {+ const geometry = createWheelGeometrySet(0.5, 0.22);+ geometry.tire.computeBoundingBox();+ expect(geometry.tire.boundingBox!.max.z - geometry.tire.boundingBox!.min.z).toBeCloseTo(+ 0.22,+ 6,+ );+ expect(() => createWheelGeometrySet(0.5, 1)).toThrow('less than its diameter');+ });++ test('canonical component names recover one legacy corner as one assembly', () => {+ const root = new THREE.Object3D();+ const pivot = new THREE.Object3D();+ pivot.name = 'WheelPivot_front_left';+ const legacyTire = new THREE.Mesh(new THREE.TorusGeometry(0.4, 0.1, 8, 16), tire);+ legacyTire.name = 'Tire_front_left';+ const legacyRim = new THREE.Mesh(+ new THREE.CylinderGeometry(0.28, 0.28, 0.16, 16).rotateX(Math.PI / 2),+ metal,+ );+ legacyRim.name = 'Rim_front_left';+ const legacyHub = new THREE.Mesh(+ new THREE.CylinderGeometry(0.14, 0.14, 0.18, 16).rotateX(Math.PI / 2),+ metal,+ );+ legacyHub.name = 'Hub_front_left';+ pivot.add(legacyTire, legacyRim, legacyHub);+ root.add(pivot);+ const resolved = resolveVehicleWheelAssemblies(root);+ expect(resolved).toHaveLength(1);+ expect(resolved[0]?.source).toBe('legacy');+ expect(resolved[0]?.side).toBe('left');+ expect(resolved[0]?.index).toBe('front');+ expect(resolved[0]?.tire).toBe(legacyTire);+ expect(resolved[0]?.rim).toBe(legacyRim);+ expect(resolved[0]?.hub).toBe(legacyHub);+ });+});diff --git a/src/agent/generate.test.ts b/src/agent/generate.test.tsindex 03507d55..930a01c3 100644--- a/src/agent/generate.test.ts+++ b/src/agent/generate.test.ts@@ -8,6 +8,7 @@* (`pixelforge gen glb`) covers the LLM half.*/import { test, expect, describe, mock, beforeAll, afterAll } from 'bun:test';+import { createAssetIntentV1 } from '../contracts';// A real, minimal, valid Kiln program (mirrors render-edges.test.ts). renderGLB// executes this for real to prove the engine wires the agent's code into a GLB.@@ -19,6 +20,10 @@ function build() {return root;}`;+const FALSE_PROP_CODE = CANNED_CODE.replace(+ "const meta = { name: 'TestBox' };",+ "const meta = { name: 'TestBox', category: 'prop' };",+);// Mutable impl the mocked runKilnAgent delegates to (set per test).let runImpl: (opts: Record<string, unknown>) => Promise<Record<string, unknown>>;@@ -105,6 +110,33 @@ describe('generateKilnAsset', () => {expect(captured?.['originalPrompt']).toBe('a tower');});+ test('full intent is authoritative through agent options and final render', async () => {+ let captured: Record<string, unknown> | undefined;+ runImpl = async (opts) => {+ captured = opts;+ return { code: FALSE_PROP_CODE, toolCalls: ['kiln_submit'], steps: 1 };+ };+ const intent = createAssetIntentV1({ category: 'environment', subtype: 'set-piece' });++ const result = await generateKilnAsset({+ prompt: 'a compact car',+ category: 'vehicle',+ intent,+ });++ expect(captured?.['category']).toBe('environment');+ expect(captured?.['intent']).toBe(intent);+ expect(result.meta.category).toBe('environment');+ expect(result.meta.modelCategory).toBe('prop');+ const qaReport = result.meta.qaReport as {+ category: string;+ dimensions: { runtimeCost: { status: string; metrics?: Record<string, unknown> } };+ };+ expect(qaReport.category).toBe('environment');+ expect(qaReport.dimensions.runtimeCost.status).toBe('pass');+ expect(qaReport.dimensions.runtimeCost.metrics?.['instanceabilityGrade']).toBeDefined();+ });+test('throws when the agent returns an error', async () => {runImpl = async () => ({error: 'stream ended without completing a message',diff --git a/src/agent/generate.ts b/src/agent/generate.tsindex 0544fcf9..beca1b1b 100644--- a/src/agent/generate.ts+++ b/src/agent/generate.ts@@ -14,8 +14,9 @@* non-agent `kiln` module must import it lazily (dynamic `import()`), so the* `@strands-agents/sdk` dependency never enters the browser/editor bundle graph.*/-import { renderGLB, type KilnCodeMeta } from '../render';-import type { AssetCategory, AssetStyle } from '../prompt';+import { renderGLB, type KilnCodeMeta, type RenderResult } from '../render';+import type { AssetStyle } from '../prompt';+import { createAssetIntentV1, type AssetCategory, type AssetIntentV1 } from '../contracts';import { runKilnAgent, type RefineMode, type KilnKnowhow, type KilnInputImage } from './run';import {makeKilnModel,@@ -42,6 +43,8 @@ export interface GenerateKilnAssetOptions {apiKey?: string;/** Asset category (drives prompt framing). Default 'prop'. */category?: AssetCategory;+ /** Full closure-owned intent. Authoritative over category when supplied. */+ intent?: AssetIntentV1;/** Optional style template (low-poly / stylized / voxel / detailed / realistic). */style?: AssetStyle;/** Ask the model for an animate() function too. Default false (static). */@@ -94,6 +97,11 @@ export interface GenerateKilnAssetResult {diff?: string;/** Six-view grid PNG of the final asset (only when `captureViews` was set and the render succeeded). */views?: Buffer;+ /** Automatic trusted character skeleton/motion captures, when applicable. */+ diagnosticViews?: NonNullable<RenderResult['diagnosticViews']>;+ materialRecipeApplications?: NonNullable<RenderResult['materialRecipeApplications']>;+ materialResourceProvenance?: NonNullable<RenderResult['materialResourceProvenance']>;+ materialMetrics?: NonNullable<RenderResult['materialMetrics']>;}/**@@ -107,6 +115,7 @@ export interface GenerateKilnAssetResult {export async function generateKilnCodeAgent(opts: {prompt: string;category?: AssetCategory;+ intent?: AssetIntentV1;style?: AssetStyle;includeAnimation?: boolean;existingCode?: string;@@ -130,11 +139,13 @@ export async function generateKilnCodeAgent(opts: {DEFAULT_KILN_AGENT_MODEL;const desc = resolveKilnAgentModel(modelId);const model = makeKilnModel(desc);+ const intent = opts.intent ?? createAssetIntentV1({ category: opts.category ?? 'prop' });const agent = await runKilnAgent({model,prompt: opts.prompt,- category: opts.category ?? 'prop',+ category: intent.category,+ intent,includeAnimation: opts.includeAnimation ?? false,...(opts.style ? { style: opts.style } : {}),...(opts.existingCode ? { existingCode: opts.existingCode } : {}),@@ -172,11 +183,13 @@ export async function generateKilnAsset(DEFAULT_KILN_AGENT_MODEL;const desc: KilnModelDescriptor = resolveKilnAgentModel(modelId);const model = makeKilnModel(desc, opts.apiKey ? { apiKey: opts.apiKey } : {});+ const intent = opts.intent ?? createAssetIntentV1({ category: opts.category ?? 'prop' });const agent = await runKilnAgent({model,prompt: opts.prompt,- category: opts.category ?? 'prop',+ category: intent.category,+ intent,knowhow: opts.knowhow ?? 'inline',includeAnimation: opts.includeAnimation ?? false,...(opts.style ? { style: opts.style } : {}),@@ -195,7 +208,7 @@ export async function generateKilnAsset(// Grade-aware consolidation by default: lifts material-sprawl heroes from// grade C/D/F to A/B, byte-stable on already-lean assets (M1a, plan/05 §3.1).- const render = await renderGLB(agent.code, { optimize: 'auto' });+ const render = await renderGLB(agent.code, { optimize: 'auto', intent });// Best-effort views artifact: what the vision loop / review UIs show.// Never fails the run — a rasterizer error just drops the sidecar.@@ -222,5 +235,13 @@ export async function generateKilnAsset(...(agent.edits ? { edits: agent.edits } : {}),...(agent.diff ? { diff: agent.diff } : {}),...(views ? { views } : {}),+ ...(render.diagnosticViews ? { diagnosticViews: render.diagnosticViews } : {}),+ ...(render.materialRecipeApplications+ ? { materialRecipeApplications: render.materialRecipeApplications }+ : {}),+ ...(render.materialResourceProvenance+ ? { materialResourceProvenance: render.materialResourceProvenance }+ : {}),+ ...(render.materialMetrics ? { materialMetrics: render.materialMetrics } : {}),};}diff --git a/src/agent/grade-refine.ts b/src/agent/grade-refine.tsindex 09321b85..e81ea86c 100644--- a/src/agent/grade-refine.ts+++ b/src/agent/grade-refine.ts@@ -15,6 +15,7 @@*/import { WebIO } from '@gltf-transform/core';+import type { AssetCategory, AssetIntentV1 } from '../contracts';import type { InstanceabilityGrade, InstanceabilityReport } from '../metrics';import { renderGLB } from '../render';@@ -80,9 +81,12 @@ async function listMaterialLabels(glb: Uint8Array): Promise<string[]> {* so the refine trigger keys on the grade the asset actually ships with.* Deterministic CPU work; never throws.*/-export async function assessProgramGrade(code: string): Promise<ProgramGradeAssessment> {+export async function assessProgramGrade(+ code: string,+ opts: { intent?: AssetIntentV1; category?: AssetCategory } = {},+): Promise<ProgramGradeAssessment> {try {- const render = await renderGLB(code, { optimize: 'auto' });+ const render = await renderGLB(code, { optimize: 'auto', ...opts });const report = render.meta.instanceability;// Metrics computation failing is non-fatal everywhere else — same here: the// program is valid, there is just no grade signal to act on.diff --git a/src/agent/providers.test.ts b/src/agent/providers.test.tsindex bf68a8e3..cb23e4e2 100644--- a/src/agent/providers.test.ts+++ b/src/agent/providers.test.ts@@ -77,7 +77,13 @@ describe('resolveKilnAgentModel', () => {describe('makeKilnModel', () => {const saved: Record<string, string | undefined> = {};- const KEYS = ['GEMINI_API_KEY', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'MODEL_API_KEY'];+ const KEYS = [+ 'GEMINI_API_KEY',+ 'ANTHROPIC_API_KEY',+ 'OPENAI_API_KEY',+ 'OPENROUTER_API_KEY',+ 'MODEL_API_KEY',+ ];beforeAll(() => {for (const k of KEYS) {diff --git a/src/agent/providers.ts b/src/agent/providers.tsindex 7b959d99..2e6cffbd 100644--- a/src/agent/providers.ts+++ b/src/agent/providers.ts@@ -51,7 +51,13 @@ export function makeOpenRouterModel(opts: OpenRouterModelOptions): Model {// =============================================================================/** Strands-native provider vocabulary for the Kiln agent loop. */-export type KilnAgentProvider = 'anthropic' | 'openai' | 'google' | 'bedrock' | 'openrouter' | 'meta';+export type KilnAgentProvider =+ | 'anthropic'+ | 'openai'+ | 'google'+ | 'bedrock'+ | 'openrouter'+ | 'meta';/*** Minimal model descriptor `makeKilnModel` needs. Structurally compatible with@@ -187,7 +193,9 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpticase 'meta': {const apiKey = metaApiKey(opts);if (!apiKey) {- throw new Error('Meta Model API key is required. Set MODEL_API_KEY, META_MODEL_API_KEY, or META_API_KEY.');+ throw new Error(+ 'Meta Model API key is required. Set MODEL_API_KEY, META_MODEL_API_KEY, or META_API_KEY.',+ );}return new OpenAIModel({modelId: desc.model,diff --git a/src/agent/run.ts b/src/agent/run.tsindex a546016f..5dfcf702 100644--- a/src/agent/run.ts+++ b/src/agent/run.ts@@ -34,6 +34,7 @@ import {KILN_EDIT_DIRECTIVE_UNIFIED,} from '../prompt';import type { AssetCategory, AssetStyle } from '../prompt';+import type { AssetIntentV1 } from '../contracts';import type { SubmitSink, EditSink, UnifiedSink, EditRecord, KilnRenderCandidate } from './tools';import {resolveToolSurface,@@ -85,6 +86,8 @@ export interface RunKilnAgentOptions {prompt: string;/** Asset category (drives prompt framing). Default 'prop'. */category?: AssetCategory;+ /** Full closure-owned intent. Authoritative over category when supplied. */+ intent?: AssetIntentV1;/** Optional style template (low-poly / stylized / voxel / detailed / realistic) injected into the user prompt. */style?: AssetStyle;/** Know-how source: inline system prompt (default) or the kiln-glb skill. */@@ -201,6 +204,11 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgconst maxSteps = Number(process.env['KILN_AGENT_MAX_STEPS'] ?? 40) || 0;const metrics = new MetricsCollector(opts.onEvent, maxSteps);const surface = resolveToolSurface(opts.toolSurface);+ const trustedCategory = opts.intent?.category ?? opts.category ?? 'prop';+ const gradeAssessmentOptions = {+ category: trustedCategory,+ ...(opts.intent ? { intent: opts.intent } : {}),+ };// Edit mode is a `current`-surface concept (the unified surface always uses the// buffer factory, regardless of refineMode). Engages only when refining.const editMode =@@ -209,7 +217,11 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgconst editSink: EditSink = { edits: [] };const unifiedSink: UnifiedSink = { edits: [] };try {- const tools: Tool[] = buildAgentTools(surface, opts, { sink, editSink, unifiedSink });+ const tools: Tool[] = buildAgentTools(+ surface,+ { ...opts, category: trustedCategory },+ { sink, editSink, unifiedSink },+ );const allTools: unknown[] = opts.extraTools ? [...tools, ...opts.extraTools] : tools;const plugins: Plugin[] = [];@@ -290,7 +302,8 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgbuildUserPrompt({prompt: promptText,mode: 'glb',- category: opts.category ?? 'prop',+ category: trustedCategory,+ ...(opts.intent ? { intent: opts.intent } : {}),includeAnimation: opts.includeAnimation ?? false,...(opts.style ? { style: opts.style } : {}),...(opts.existingCode ? { existingCode: opts.existingCode } : {}),@@ -342,7 +355,9 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg// it flagged `capped` (an honest best effort); only a cap with nothing// renderable stays a hard failure.const captured = readSinkCode();- const salvage = captured ? await assessProgramGrade(captured) : undefined;+ const salvage = captured+ ? await assessProgramGrade(captured, gradeAssessmentOptions)+ : undefined;if (!salvage?.ok) {const collected = metrics.readMetrics();return {@@ -362,7 +377,7 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg// only if its grade actually improves.const captured = readSinkCode();if (captured && code === captured) {- const assess = await assessProgramGrade(captured);+ const assess = await assessProgramGrade(captured, gradeAssessmentOptions);const trigger = {mode: 'auto' as const,report: assess.report,@@ -400,7 +415,7 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAglastText = lastMessageText(refineResult.lastMessage) ?? lastText;const refined = readSinkCode();if (refined && refined !== captured) {- const reassess = await assessProgramGrade(refined);+ const reassess = await assessProgramGrade(refined, gradeAssessmentOptions);if (reassess.ok &&reassess.report &&diff --git a/src/agent/surface.ts b/src/agent/surface.tsindex b1f9aa32..ef03e680 100644--- a/src/agent/surface.ts+++ b/src/agent/surface.ts@@ -6,6 +6,7 @@* loop (generate.test.ts) does not also stub these helpers.*/import type { Tool } from '@strands-agents/sdk';+import type { AssetCategory, AssetIntentV1 } from '../contracts';import {makeKilnTools,@@ -29,6 +30,10 @@ export type RefineMode = 'rewrite' | 'edit';export interface ToolBuildOptions {existingCode?: string;refineMode?: RefineMode;+ /** Trusted request category captured outside generated source. */+ category?: AssetCategory;+ /** Full trusted request intent; authoritative over `category` when present. */+ intent?: AssetIntentV1;/** Live render-candidate sink, wired into the unified surface's kiln_render.* Only the unified surface emits candidates (current/edit surfaces ignore it). */onCandidate?: (c: KilnRenderCandidate) => void;@@ -61,15 +66,24 @@ export function buildAgentTools(opts: ToolBuildOptions,sinks: AgentSinks,): Tool[] {+ const trustedContext = {+ ...(opts.intent ? { intent: opts.intent } : {}),+ ...(opts.category ? { category: opts.category } : {}),+ };if (surface === 'unified') {return makeKilnUnifiedTools({...(opts.existingCode ? { seedCode: opts.existingCode } : {}),sink: sinks.unifiedSink,...(opts.onCandidate ? { onCandidate: opts.onCandidate } : {}),+ ...trustedContext,});}const editMode = Boolean(opts.existingCode) && opts.refineMode === 'edit';return editMode- ? makeKilnEditTools({ seedCode: opts.existingCode!, sink: sinks.editSink })- : makeKilnTools(sinks.sink);+ ? makeKilnEditTools({+ seedCode: opts.existingCode!,+ sink: sinks.editSink,+ ...trustedContext,+ })+ : makeKilnTools(sinks.sink, trustedContext);}diff --git a/src/agent/tools-context.test.ts b/src/agent/tools-context.test.tsnew file mode 100644index 00000000..b5c31ef6--- /dev/null+++ b/src/agent/tools-context.test.ts@@ -0,0 +1,90 @@+import { describe, expect, test } from 'bun:test';+import type { JsonBlock } from '@strands-agents/sdk';++import { createAssetIntentV1 } from '../contracts';+import { buildAgentTools, type AgentSinks } from './surface';++const SIDEWAYS_FALSE_PROP_CODE = `+const meta = { name: 'sideways', category: 'prop' };+function build() {+ const root = createRoot('Root');+ const frame = createVehicleFrame('VehicleFrame', {+ axles: [+ { id: 'front', position: [0.3, 0.35, 0] },+ { id: 'rear', position: [-0.3, 0.35, 0] },+ ],+ parent: root,+ });+ createPart('Body', boxGeo(1, 0.7, 4), gameMaterial('#aa3333'), {+ parent: frame.root,+ position: [0, 0.5, 0],+ });+ const rubber = gameMaterial('#111111', { roughness: 0.95 });+ const metal = gameMaterial('#888888', { metalness: 0.8 });+ const geometries = createWheelGeometrySet(0.35, 0.18);+ for (const [index, x] of [['front', 0.3], ['rear', -0.3]]) {+ createWheelAssembly(index + 'Left', { tire: rubber, rim: metal }, {+ radius: 0.35, width: 0.18, side: 'left', index,+ position: [x, 0.35, -1.6], steering: index === 'front', geometries, parent: frame.root,+ });+ createWheelAssembly(index + 'Right', { tire: rubber, rim: metal }, {+ radius: 0.35, width: 0.18, side: 'right', index,+ position: [x, 0.35, 1.6], steering: index === 'front', geometries, parent: frame.root,+ });+ }+ return root;+}+`;++const sinks = (): AgentSinks => ({+ sink: {},+ editSink: { edits: [] },+ unifiedSink: { edits: [] },+});++function findTool(tools: ReturnType<typeof buildAgentTools>, name: string) {+ const found = tools.find((tool) => tool.name === name) as+ | { invoke(input: unknown): Promise<unknown> }+ | undefined;+ if (!found) throw new Error(`Missing agent tool ${name}`);+ return found;+}++describe('agent trusted tool context', () => {+ test('current surface binds requested category outside generated source', async () => {+ const tools = buildAgentTools('current', { category: 'vehicle' }, sinks());+ const output = (await findTool(tools, 'kiln_render').invoke({+ code: SIDEWAYS_FALSE_PROP_CODE,+ })) as { warnings: string[] };+ expect(output.warnings.some((warning) => warning.includes('Orientation'))).toBe(true);+ });++ test('unified surface binds full intent and carries it into collapsed render', async () => {+ const tools = buildAgentTools(+ 'unified',+ {+ existingCode: SIDEWAYS_FALSE_PROP_CODE,+ intent: createAssetIntentV1({ category: 'vehicle' }),+ },+ sinks(),+ );+ const output = (await findTool(tools, 'kiln_render').invoke({})) as unknown[];+ const json = (output[1] as JsonBlock).json as { warnings: string[] };+ expect(json.warnings.some((warning) => warning.includes('Orientation'))).toBe(true);+ });++ test('edit surface preserves requested category for screenshot QA', async () => {+ const tools = buildAgentTools(+ 'current',+ {+ existingCode: SIDEWAYS_FALSE_PROP_CODE,+ refineMode: 'edit',+ category: 'vehicle',+ },+ sinks(),+ );+ const output = (await findTool(tools, 'kiln_screenshot').invoke({})) as unknown[];+ const json = (output[1] as JsonBlock).json as { warnings: string[] };+ expect(json.warnings.some((warning) => warning.includes('Orientation'))).toBe(true);+ });+});diff --git a/src/agent/tools.ts b/src/agent/tools.tsindex 4e0a11b3..027f87ff 100644--- a/src/agent/tools.ts+++ b/src/agent/tools.ts@@ -21,10 +21,12 @@ import { tool, ImageBlock, JsonBlock, type Tool, type JSONValue } from '@strandsimport { z } from 'zod';import {- kilnToolRegistry,- kilnRenderViewsDef,- kilnScreenshotAnimationDef,- kilnViewInteriorDef,+ createKilnToolRegistry,+ createKilnRenderViewsDef,+ createKilnScreenshotAnimationDef,+ createKilnViewInteriorDef,+ type KilnToolContext,+ type KilnToolDef,} from '../tools/registry';/** Name of the terminal tool the agent calls to record its final program. */@@ -57,7 +59,7 @@ const submitInput = z.object({* tool-result coercion passes block arrays through as-is — so it is cast past* JSONValue.*/-function toCallbackResult(def: (typeof kilnToolRegistry)[number], output: unknown): JSONValue {+function toCallbackResult(def: KilnToolDef, output: unknown): JSONValue {const multi = def.mediaMulti?.(output);if (multi) {return [@@ -92,16 +94,16 @@ const animationBufferInput = z.object({/** Build a buffer-aware kiln_screenshot_animation tool that runs against `getCode()`* (the working buffer) instead of a `code` argument. Same behavior as the registry* def otherwise; image transports attach the frame(s) via toCallbackResult. */-function makeBufferAnimationTool(getCode: () => string): Tool {+function makeBufferAnimationTool(getCode: () => string, def: KilnToolDef): Tool {return tool({- name: kilnScreenshotAnimationDef.name,- description: `${kilnScreenshotAnimationDef.description} Operates on your current working buffer (omit code).`,+ name: def.name,+ description: `${def.description} Operates on your current working buffer (omit code).`,inputSchema: animationBufferInput,callback: async (input) => {const i = input as { clip: string; camera?: string; perFrame?: boolean };return toCallbackResult(- kilnScreenshotAnimationDef,- await kilnScreenshotAnimationDef.run({+ def,+ await def.run({code: getCode(),clip: i.clip,...(i.camera ? { camera: i.camera } : {}),@@ -112,7 +114,7 @@ function makeBufferAnimationTool(getCode: () => string): Tool {});}-function toStrandsTool(def: (typeof kilnToolRegistry)[number]): Tool {+function toStrandsTool(def: KilnToolDef): Tool {return tool({name: def.name,description: def.description,@@ -128,11 +130,11 @@ function toStrandsTool(def: (typeof kilnToolRegistry)[number]): Tool {** @param sink - Receives the submitted final code. Read `sink.code` after invoke.*/-export function makeKilnTools(sink: SubmitSink): Tool[] {- const kilnTools = kilnToolRegistry.map(toStrandsTool);+export function makeKilnTools(sink: SubmitSink, context: KilnToolContext = {}): Tool[] {+ const kilnTools = createKilnToolRegistry(context).map(toStrandsTool);// 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(kilnScreenshotAnimationDef);+ const animationTool = toStrandsTool(createKilnScreenshotAnimationDef(context));const submitTool: Tool = tool({name: KILN_SUBMIT_TOOL_NAME,description:@@ -323,12 +325,16 @@ const submitEditInput = z.object({* `sink.edits`; `sink.code` tracks the latest buffer (so an un-submitted run* still captures the edits).*/-export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): Tool[] {+export function makeKilnEditTools(+ opts: { seedCode: string; sink: EditSink } & KilnToolContext,+): 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 find = (name: string): (typeof kilnToolRegistry)[number] => {- const def = kilnToolRegistry.find((d) => d.name === name);+ const find = (name: string): KilnToolDef => {+ const def = registry.find((d) => d.name === name);if (!def) throw new Error(`makeKilnEditTools: missing registry tool ${name}`);return def;};@@ -395,7 +401,7 @@ export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): T// Buffer-aware motion view: a refine that touches an animated character can SEE// the clip move and confirm the edit didn't break it.- const animationTool = makeBufferAnimationTool(() => buffer.code);+ const animationTool = makeBufferAnimationTool(() => buffer.code, animationDef);const submitTool: Tool = tool({name: KILN_SUBMIT_TOOL_NAME,@@ -492,19 +498,25 @@ const draftInput = z.object({* every draft/edit (so an un-finalized run still captures the work). `kiln_edit`* failures point at `kiln_draft` as the always-reliable rewrite escape hatch.*/-export function makeKilnUnifiedTools(opts: {- seedCode?: string;- sink: UnifiedSink;- /** Best-effort sink for live render candidates (one per successful kiln_render).- * Lets the host surface a filmstrip of intermediate renders + pick a version.- * Never affects the agent's view; sink errors are swallowed. */- onCandidate?: (c: KilnRenderCandidate) => void;-}): Tool[] {+export function makeKilnUnifiedTools(+ opts: {+ seedCode?: string;+ sink: UnifiedSink;+ /** Best-effort sink for live render candidates (one per successful kiln_render).+ * Lets the host surface a filmstrip of intermediate renders + pick a version.+ * Never affects the agent's view; sink errors are swallowed. */+ onCandidate?: (c: KilnRenderCandidate) => void;+ } & KilnToolContext,+): Tool[] {const buffer = new KilnDraftBuffer(opts.seedCode ?? '');opts.sink.edits = buffer.edits; // share the live trace- const validateDef = kilnToolRegistry.find((d) => d.name === 'kiln_validate');+ const registry = createKilnToolRegistry(opts);+ 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 draftTool: Tool = tool({name: 'kiln_draft',@@ -564,11 +576,10 @@ export function makeKilnUnifiedTools(opts: {const renderTool: Tool = tool({name: 'kiln_render',- description:- kilnRenderViewsDef.description + ' Operates on your current working buffer (no argument).',+ description: `${renderViewsDef.description} Operates on your current working buffer (no argument).`,inputSchema: viewInput,callback: async () => {- const out = await kilnRenderViewsDef.run({ code: buffer.code });+ const out = await renderViewsDef.run({ code: buffer.code });// Out-of-band: surface a SUCCESSFUL render as a live candidate (the working// buffer + the six-view image the agent just saw). Best-effort; a build// failure is image-free and not a candidate. Never changes the agent's view.@@ -586,30 +597,29 @@ export function makeKilnUnifiedTools(opts: {}}}- return toCallbackResult(kilnRenderViewsDef, out);+ return toCallbackResult(renderViewsDef, out);},});// Buffer-aware motion view: after drafting/editing an animated character, SEE a// clip move (sideways walk, reverse knee, backward swing, item not tracking).- const animationTool = makeBufferAnimationTool(() => buffer.code);+ const animationTool = makeBufferAnimationTool(() => buffer.code, animationDef);// Buffer-aware interior view: after drafting/editing a BUILDING, SEE inside it// (roof off — open floor, real doorway gap, fixtures grounded, nothing buried).const interiorTool: Tool = tool({name: 'kiln_view_interior',- description:- kilnViewInteriorDef.description + ' Operates on your current working buffer (omit code).',+ description: `${interiorDef.description} Operates on your current working buffer (omit code).`,inputSchema: z.object({nodeName: z.string().optional().describe('The roof part to lift, by name (default "Roof").'),}),callback: async (input) => {const n = (input as { nodeName?: string }).nodeName;- const out = await kilnViewInteriorDef.run({+ const out = await interiorDef.run({code: buffer.code,...(n ? { nodeName: n } : {}),});- return toCallbackResult(kilnViewInteriorDef, out);+ return toCallbackResult(interiorDef, out);},});diff --git a/src/architecture.ts b/src/architecture.tsnew file mode 100644index 00000000..0cd5b975--- /dev/null+++ b/src/architecture.ts@@ -0,0 +1,840 @@+/** Correct-by-construction architecture scaffolds in Kiln's +X/+Y/+Z frame. */+import * as THREE from 'three';++import {+ stampSemanticMetadataV1,+ type SemanticLocalFrameV1,+ type SemanticRelationshipV1,+} from './contracts';++export type RidgeAxis = 'x' | 'z';+export type RoofSide = 'positive' | 'negative';++export interface GableRoofOptions {+ /** Exact footprint extent along world/local X, in meters. */+ spanX: number;+ /** Exact footprint extent along world/local Z, in meters. */+ spanZ: number;+ /** Ridge rise above the wall bearing line. Supply rise or pitchDegrees. */+ rise?: number;+ /** Pitch from horizontal. Supply pitchDegrees or rise. */+ pitchDegrees?: number;+ overhang?: number;+ ridgeAxis?: RidgeAxis;+ thickness?: number;+ parent?: THREE.Object3D;+}++export interface RoofFaceDimensions {+ alongRidge: number;+ downhill: number;+ thickness: number;+}++/**+ * A face-owned rigid frame. Local +X is ridge tangent, +Y is outward normal,+ * and +Z is downhill. World properties are getters, so parent transforms made+ * after construction cannot stale them.+ */+export interface RoofFaceFrame {+ side: RoofSide;+ ridgeAxis: RidgeAxis;+ roofRoot: THREE.Object3D;+ localToRoof: THREE.Matrix4;+ readonly localToWorld: THREE.Matrix4;+ readonly ridgeTangent: THREE.Vector3;+ readonly downhillDirection: THREE.Vector3;+ readonly outwardNormal: THREE.Vector3;+ readonly ridgeStart: THREE.Vector3;+ readonly ridgeEnd: THREE.Vector3;+ readonly eaveStart: THREE.Vector3;+ readonly eaveEnd: THREE.Vector3;+ dimensions: RoofFaceDimensions;+}++export interface GableRoofResult {+ root: THREE.Object3D;+ slopes: [THREE.Object3D, THREE.Object3D];+ faces: [RoofFaceFrame, RoofFaceFrame];+ rise: number;+ pitchDegrees: number;+}++export interface RoofPlanesOptions {+ /** Compatibility name for spanZ. */+ width: number;+ /** Compatibility name for spanX. */+ depth: number;+ /** Compatibility rise from the outer eave to the ridge. */+ height: number;+ overhang?: number;+ ridgeAxis?: RidgeAxis;+ thickness?: number;+ parent?: THREE.Object3D;+}++export interface GableOpening {+ id?: string;+ offset?: number;+ bottom?: number;+ width: number;+ height: number;+}++export interface GableEndPanelOptions {+ span: number;+ rise: number;+ thickness?: number;+ ridgeAxis?: RidgeAxis;+ side?: RoofSide;+ openings?: readonly GableOpening[];+ parent?: THREE.Object3D;+}++export interface GableEndPanelResult {+ root: THREE.Object3D;+ geometry: THREE.BufferGeometry;+ openings: THREE.Object3D[];+}++export type ShellWall = 'front' | 'back' | 'left' | 'right';++export interface GableShellOpening {+ id?: string;+ wall: ShellWall;+ kind?: 'door' | 'window';+ offset?: number;+ width?: number;+ height?: number;+ sill?: number;+ depth?: number;+}++export interface GableShellMaterials {+ wall: THREE.Material;+ roof: THREE.Material;+ floor?: THREE.Material;+ gable?: THREE.Material;+}++export interface GableShellOptions extends GableRoofOptions {+ wallHeight?: number;+ wallThickness?: number;+ floorThickness?: number;+ closedEnds?: boolean;+ enterable?: boolean;+ openings?: readonly GableShellOpening[];+ gableOpenings?: Partial<Record<RoofSide, readonly GableOpening[]>>;+}++export interface GableShellResult {+ root: THREE.Object3D;+ walls: Record<ShellWall, THREE.Object3D>;+ floor: THREE.Object3D;+ roof: GableRoofResult;+ gables: [THREE.Object3D, THREE.Object3D] | [];+ openings: THREE.Object3D[];+}++export type RoofSurfaceLayoutKind = 'panels' | 'shingles' | 'seams' | 'corrugations';++export interface RoofSurfaceLayoutOptions {+ face: RoofFaceFrame;+ kind: RoofSurfaceLayoutKind;+ parent?: THREE.Object3D;+ panelWidth?: number;+ rowHeight?: number;+ spacing?: number;+ thickness?: number;+}++export interface RoofSurfaceLayoutResult {+ root: THREE.Object3D;+ items: THREE.Object3D[];+}++const DEG = Math.PI / 180;+const EPSILON = 1e-7;++function positive(value: number, name: string): number {+ if (!Number.isFinite(value) || value <= 0) throw new RangeError(`${name} must be finite and > 0`);+ return value;+}++function nonNegative(value: number, name: string): number {+ if (!Number.isFinite(value) || value < 0) throw new RangeError(`${name} must be finite and >= 0`);+ return value;+}++function roleMetadata(+ roles: readonly string[],+ relationships: readonly SemanticRelationshipV1[] = [],+ frames: readonly SemanticLocalFrameV1[] = [],+) {+ return { roles, relationships, frames, sockets: [] };+}++function relationship(kind: string, target: string): SemanticRelationshipV1 {+ return { kind, target, targetType: 'role' };+}++function setTransform(object: THREE.Object3D, matrix: THREE.Matrix4): void {+ matrix.decompose(object.position, object.quaternion, object.scale);+}++function resolvePitch(+ halfRun: number,+ rise: number | undefined,+ pitchDegrees: number | undefined,+): { rise: number; pitchDegrees: number } {+ positive(halfRun, 'roof half-run');+ if (rise === undefined && pitchDegrees === undefined) pitchDegrees = 30;+ if (pitchDegrees !== undefined) {+ if (!Number.isFinite(pitchDegrees) || pitchDegrees <= 0 || pitchDegrees >= 89) {+ throw new RangeError('pitchDegrees must be finite, > 0, and < 89');+ }+ }+ if (rise !== undefined) positive(rise, 'rise');+ const resolvedPitch = pitchDegrees ?? Math.atan2(rise!, halfRun) / DEG;+ const resolvedRise = rise ?? Math.tan(resolvedPitch * DEG) * halfRun;+ const expected = Math.tan(resolvedPitch * DEG) * halfRun;+ if (Math.abs(resolvedRise - expected) > Math.max(EPSILON, expected * 1e-6)) {+ throw new RangeError('rise and pitchDegrees disagree for the requested footprint');+ }+ return { rise: resolvedRise, pitchDegrees: resolvedPitch };+}++interface ResolvedRoofProfile {+ spanX: number;+ spanZ: number;+ ridgeAxis: RidgeAxis;+ overhang: number;+ thickness: number;+ rise: number;+ pitchDegrees: number;+ ridgeY: number;+ eaveY: number;+}++function resolveRoofProfile(options: GableRoofOptions): ResolvedRoofProfile {+ const spanX = positive(options.spanX, 'spanX');+ const spanZ = positive(options.spanZ, 'spanZ');+ const ridgeAxis = options.ridgeAxis ?? 'x';+ const overhang = nonNegative(options.overhang ?? 0.3, 'overhang');+ const thickness = positive(options.thickness ?? 0.08, 'thickness');+ const halfRun = (ridgeAxis === 'x' ? spanZ : spanX) / 2;+ const pitch = resolvePitch(halfRun, options.rise, options.pitchDegrees);+ return {+ spanX,+ spanZ,+ ridgeAxis,+ overhang,+ thickness,+ ...pitch,+ ridgeY: pitch.rise,+ eaveY: -Math.tan(pitch.pitchDegrees * DEG) * overhang,+ };+}++function buildFace(+ roofRoot: THREE.Object3D,+ profile: ResolvedRoofProfile,+ sideSign: 1 | -1,+): RoofFaceFrame {+ const side: RoofSide = sideSign > 0 ? 'positive' : 'negative';+ const halfFoot = (profile.ridgeAxis === 'x' ? profile.spanZ : profile.spanX) / 2;+ const horizontalRun = halfFoot + profile.overhang;+ const verticalRun = profile.ridgeY - profile.eaveY;+ const downhillLength = Math.hypot(horizontalRun, verticalRun);+ const alongRidge =+ (profile.ridgeAxis === 'x' ? profile.spanX : profile.spanZ) + profile.overhang * 2;+ const downhill =+ profile.ridgeAxis === 'x'+ ? new THREE.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize()+ : new THREE.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();+ const tangent =+ profile.ridgeAxis === 'x'+ ? new THREE.Vector3(sideSign, 0, 0)+ : new THREE.Vector3(0, 0, -sideSign);+ const normal = downhill.clone().cross(tangent).normalize();+ const localToRoof = new THREE.Matrix4().makeBasis(tangent, normal, downhill);+ localToRoof.setPosition(0, profile.ridgeY, 0);++ const world = (): THREE.Matrix4 => {+ roofRoot.updateWorldMatrix(true, false);+ return roofRoot.matrixWorld.clone().multiply(localToRoof);+ };+ const direction = (axis: THREE.Vector3): THREE.Vector3 =>+ axis.clone().transformDirection(world());+ const point = (x: number, z: number): THREE.Vector3 =>+ new THREE.Vector3(x, 0, z).applyMatrix4(world());++ return {+ side,+ ridgeAxis: profile.ridgeAxis,+ roofRoot,+ localToRoof,+ get localToWorld() {+ return world();+ },+ get ridgeTangent() {+ return direction(new THREE.Vector3(1, 0, 0));+ },+ get downhillDirection() {+ return direction(new THREE.Vector3(0, 0, 1));+ },+ get outwardNormal() {+ return direction(new THREE.Vector3(0, 1, 0));+ },+ get ridgeStart() {+ return point(-alongRidge / 2, 0);+ },+ get ridgeEnd() {+ return point(alongRidge / 2, 0);+ },+ get eaveStart() {+ return point(-alongRidge / 2, downhillLength);+ },+ get eaveEnd() {+ return point(alongRidge / 2, downhillLength);+ },+ dimensions: { alongRidge, downhill: downhillLength, thickness: profile.thickness },+ };+}++function buildRoof(+ name: string,+ material: THREE.Material,+ profile: ResolvedRoofProfile,+ parent?: THREE.Object3D,+): GableRoofResult {+ const root = new THREE.Object3D();+ root.name = name;+ if (parent) parent.add(root);+ stampSemanticMetadataV1(+ root,+ roleMetadata(['roof.assembly'], [relationship('separable-from', 'architecture.shell.gable')]),+ );++ const faces = [buildFace(root, profile, 1), buildFace(root, profile, -1)] as const;+ const buildSlope = (face: RoofFaceFrame): THREE.Object3D => {+ const geometry = new THREE.BoxGeometry(+ face.dimensions.alongRidge,+ profile.thickness,+ face.dimensions.downhill,+ );+ const mesh = new THREE.Mesh(geometry, material);+ mesh.name = `Mesh_${name}_${face.side}`;+ const center = new THREE.Matrix4().makeTranslation(+ 0,+ -profile.thickness / 2,+ face.dimensions.downhill / 2,+ );+ setTransform(mesh, face.localToRoof.clone().multiply(center));+ const coveredWall =+ profile.ridgeAxis === 'x'+ ? face.side === 'positive'+ ? 'wall.right'+ : 'wall.left'+ : face.side === 'positive'+ ? 'wall.front'+ : 'wall.back';+ stampSemanticMetadataV1(+ mesh,+ roleMetadata(+ [`roof.slope.${face.side}`],+ [+ relationship(+ 'adjacent-to',+ `roof.slope.${face.side === 'positive' ? 'negative' : 'positive'}`,+ ),+ relationship('coverage-of', coveredWall),+ relationship('separable-from', 'architecture.shell.gable'),+ ],+ [+ { id: 'surface', translation: [0, profile.thickness / 2, 0], rotation: [0, 0, 0, 1] },+ {+ id: 'ridge',+ translation: [0, profile.thickness / 2, -face.dimensions.downhill / 2],+ rotation: [0, 0, 0, 1],+ },+ {+ id: 'eave',+ translation: [0, profile.thickness / 2, face.dimensions.downhill / 2],+ rotation: [0, 0, 0, 1],+ },+ ],+ ),+ );+ root.add(mesh);+ return mesh;+ };+ const slopes: [THREE.Object3D, THREE.Object3D] = [buildSlope(faces[0]), buildSlope(faces[1])];+ return {+ root,+ slopes,+ faces: [faces[0], faces[1]],+ rise: profile.rise,+ pitchDegrees: profile.pitchDegrees,+ };+}++/** Explicit-axis, wall-bearing gable roof. */+export function createGableRoof(+ name: string,+ material: THREE.Material,+ options: GableRoofOptions,+): GableRoofResult {+ return buildRoof(name, material, resolveRoofProfile(options), options.parent);+}++/** Tested compatibility wrapper: width maps to spanZ and depth maps to spanX. */+export function createRoofPlanes(+ name: string,+ material: THREE.Material,+ options: RoofPlanesOptions,+): GableRoofResult {+ const ridgeAxis = options.ridgeAxis ?? 'x';+ const overhang = nonNegative(options.overhang ?? 0.3, 'overhang');+ const halfFoot =+ (ridgeAxis === 'x' ? positive(options.width, 'width') : positive(options.depth, 'depth')) / 2;+ const totalRun = halfFoot + overhang;+ const height = positive(options.height, 'height');+ const pitchDegrees = Math.atan2(height, totalRun) / DEG;+ const profile = resolveRoofProfile({+ spanX: options.depth,+ spanZ: options.width,+ ridgeAxis,+ overhang,+ thickness: options.thickness,+ rise: Math.tan(pitchDegrees * DEG) * halfFoot,+ });+ // Legacy API defined the outer eave at Y=0 and ridge at Y=height.+ profile.ridgeY = height;+ profile.eaveY = 0;+ profile.pitchDegrees = pitchDegrees;+ return buildRoof(name, material, profile, options.parent);+}++function openingFitsTriangle(+ opening: Required<Omit<GableOpening, 'id'>>,+ span: number,+ rise: number,+): boolean {+ const half = span / 2;+ const left = opening.offset - opening.width / 2;+ const right = opening.offset + opening.width / 2;+ const top = opening.bottom + opening.height;+ const maxAt = (u: number) => rise * (1 - Math.abs(u) / half);+ return (+ left > -half && right < half && opening.bottom >= 0 && top < Math.min(maxAt(left), maxAt(right))+ );+}++/** Exact extruded triangular gable panel with optional rectangular holes. */+export function createGableEndPanel(+ name: string,+ material: THREE.Material,+ options: GableEndPanelOptions,+): GableEndPanelResult {+ const span = positive(options.span, 'span');+ const rise = positive(options.rise, 'rise');+ const thickness = positive(options.thickness ?? 0.15, 'thickness');+ const ridgeAxis = options.ridgeAxis ?? 'x';+ const side = options.side ?? 'positive';+ const half = span / 2;+ const shape = new THREE.Shape();+ shape.moveTo(-half, 0);+ shape.lineTo(half, 0);+ shape.lineTo(0, rise);+ shape.closePath();++ const normalized = (options.openings ?? []).map((opening) => ({+ id: opening.id,+ offset: opening.offset ?? 0,+ bottom: opening.bottom ?? 0.25,+ width: positive(opening.width, 'opening.width'),+ height: positive(opening.height, 'opening.height'),+ }));+ for (const opening of normalized) {+ if (!openingFitsTriangle(opening, span, rise))+ throw new RangeError('gable opening must fit strictly inside the triangular boundary');+ const left = opening.offset - opening.width / 2;+ const right = opening.offset + opening.width / 2;+ const bottom = opening.bottom;+ const top = bottom + opening.height;+ const hole = new THREE.Path();+ hole.moveTo(left, bottom);+ hole.lineTo(left, top);+ hole.lineTo(right, top);+ hole.lineTo(right, bottom);+ hole.closePath();+ shape.holes.push(hole);+ }++ const geometry = new THREE.ExtrudeGeometry(shape, {+ depth: thickness,+ bevelEnabled: false,+ steps: 1,+ });+ geometry.translate(0, 0, -thickness / 2);+ if (ridgeAxis === 'x') geometry.rotateY(-Math.PI / 2);+ geometry.computeVertexNormals();+ const root = new THREE.Mesh(geometry, material);+ root.name = `Mesh_${name}`;+ stampSemanticMetadataV1(+ root,+ roleMetadata(+ [`roof.gable.${side}`],+ [+ relationship('adjacent-to', 'roof.slope.positive'),+ relationship('adjacent-to', 'roof.slope.negative'),+ relationship(+ 'coverage-of',+ ridgeAxis === 'x'+ ? side === 'positive'+ ? 'wall.front'+ : 'wall.back'+ : side === 'positive'+ ? 'wall.right'+ : 'wall.left',+ ),+ relationship('separable-from', 'architecture.shell.gable'),+ ],+ [+ { id: 'base', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ {+ id: 'apex',+ translation: ridgeAxis === 'x' ? [0, rise, 0] : [0, rise, 0],+ rotation: [0, 0, 0, 1],+ },+ ],+ ),+ );+ const markers = normalized.map((opening, index) => {+ const marker = new THREE.Object3D();+ marker.name = `Opening_${name}_${opening.id ?? index + 1}`;+ marker.position.set(+ ridgeAxis === 'z' ? opening.offset : 0,+ opening.bottom + opening.height / 2,+ ridgeAxis === 'x' ? opening.offset : 0,+ );+ marker.scale.set(+ ridgeAxis === 'x' ? thickness : opening.width,+ opening.height,+ ridgeAxis === 'x' ? opening.width : thickness,+ );+ stampSemanticMetadataV1(+ marker,+ roleMetadata(+ [`opening.gable.${side}.${opening.id ?? index + 1}`],+ [relationship('cutout-of', `roof.gable.${side}`)],+ ),+ );+ root.add(marker);+ return marker;+ });+ if (options.parent) options.parent.add(root);+ return { root, geometry, openings: markers };+}++function wallRunAxis(wall: ShellWall): RidgeAxis {+ return wall === 'front' || wall === 'back' ? 'z' : 'x';+}++function wallNeighbors(wall: ShellWall): [ShellWall, ShellWall] {+ return wall === 'front' || wall === 'back' ? ['left', 'right'] : ['front', 'back'];+}++function createShellWall(+ name: string,+ wall: ShellWall,+ material: THREE.Material,+ length: number,+ height: number,+ thickness: number,+ openings: readonly GableShellOpening[],+): { root: THREE.Object3D; openings: THREE.Object3D[] } {+ const axis = wallRunAxis(wall);+ const root = new THREE.Object3D();+ root.name = `${name}_Wall_${wall}`;+ const neighbors = wallNeighbors(wall);+ stampSemanticMetadataV1(+ root,+ roleMetadata(+ [`wall.${wall}`],+ [+ relationship('adjacent-to', `wall.${neighbors[0]}`),+ relationship('adjacent-to', `wall.${neighbors[1]}`),+ relationship('adjacent-to', 'floor'),+ ],+ ),+ );++ const sorted = openings+ .map((opening, index) => ({+ ...opening,+ id: opening.id ?? `${opening.kind ?? 'door'}-${index + 1}`,+ kind: opening.kind ?? 'door',+ offset: opening.offset ?? 0,+ width: positive(opening.width ?? (opening.kind === 'window' ? 1 : 1.1), 'opening.width'),+ height: positive(opening.height ?? (opening.kind === 'window' ? 1 : 2.1), 'opening.height'),+ sill: opening.kind === 'window' ? nonNegative(opening.sill ?? 1, 'opening.sill') : 0,+ depth: positive(opening.depth ?? thickness, 'opening.depth'),+ }))+ .sort((a, b) => a.offset - b.offset);+ if (sorted.length > 1)+ throw new RangeError('the minimal gable shell supports at most one opening per wall');++ const panel = (suffix: string, lo: number, hi: number, y0: number, y1: number): void => {+ if (hi - lo <= EPSILON || y1 - y0 <= EPSILON) return;+ const geometry =+ axis === 'x'+ ? new THREE.BoxGeometry(hi - lo, y1 - y0, thickness)+ : new THREE.BoxGeometry(thickness, y1 - y0, hi - lo);+ const mesh = new THREE.Mesh(geometry, material);+ mesh.name = `Mesh_${name}_${wall}_${suffix}`;+ mesh.position.set(+ axis === 'x' ? (lo + hi) / 2 : 0,+ (y0 + y1) / 2,+ axis === 'z' ? (lo + hi) / 2 : 0,+ );+ root.add(mesh);+ };+ const markers: THREE.Object3D[] = [];+ const opening = sorted[0];+ if (!opening) panel('solid', -length / 2, length / 2, 0, height);+ else {+ const left = opening.offset - opening.width / 2;+ const right = opening.offset + opening.width / 2;+ const top = opening.sill + opening.height;+ if (left <= -length / 2 || right >= length / 2 || top >= height)+ throw new RangeError(`opening on wall.${wall} must fit strictly inside the wall boundary`);+ panel('left', -length / 2, left, 0, height);+ panel('right', right, length / 2, 0, height);+ panel('lintel', left, right, top, height);+ if (opening.sill > 0) panel('sill', left, right, 0, opening.sill);+ const marker = new THREE.Object3D();+ marker.name = `Opening_${wall}_${opening.id}`;+ marker.position.set(+ axis === 'x' ? opening.offset : 0,+ opening.sill + opening.height / 2,+ axis === 'z' ? opening.offset : 0,+ );+ marker.scale.set(+ axis === 'x' ? opening.width : opening.depth,+ opening.height,+ axis === 'z' ? opening.width : opening.depth,+ );+ stampSemanticMetadataV1(+ marker,+ roleMetadata(+ [`opening.${wall}.${opening.kind}`],+ [+ relationship('cutout-of', `wall.${wall}`),+ relationship(+ opening.kind === 'door' ? 'portal-through' : 'aperture-through',+ `wall.${wall}`,+ ),+ ],+ [{ id: 'clearance', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ ),+ );+ root.add(marker);+ markers.push(marker);+ }+ return { root, openings: markers };+}++/** Closed-by-default room, floor, two roof slopes, and two exact gable ends. */+export function createGableShell(+ name: string,+ materials: GableShellMaterials,+ options: GableShellOptions,+): GableShellResult {+ const spanX = positive(options.spanX, 'spanX');+ const spanZ = positive(options.spanZ, 'spanZ');+ const wallHeight = positive(options.wallHeight ?? 2.8, 'wallHeight');+ const wallThickness = positive(options.wallThickness ?? 0.15, 'wallThickness');+ const floorThickness = positive(options.floorThickness ?? 0.1, 'floorThickness');+ const ridgeAxis = options.ridgeAxis ?? 'x';+ const closedEnds = options.closedEnds ?? true;+ const enterable = options.enterable ?? true;+ const shellOpenings =+ options.openings ?? (enterable ? [{ wall: 'front' as const, kind: 'door' as const }] : []);+ const root = new THREE.Object3D();+ root.name = name;+ if (options.parent) options.parent.add(root);+ stampSemanticMetadataV1(+ root,+ roleMetadata(+ ['architecture.shell.gable'],+ [relationship('contains', 'floor'), relationship('contains', 'roof.assembly')],+ ),+ );++ const wallSpecs: Record<ShellWall, { length: number; position: [number, number, number] }> = {+ front: { length: spanZ, position: [spanX / 2, 0, 0] },+ back: { length: spanZ, position: [-spanX / 2, 0, 0] },+ left: { length: spanX, position: [0, 0, -spanZ / 2] },+ right: { length: spanX, position: [0, 0, spanZ / 2] },+ };+ const walls = {} as Record<ShellWall, THREE.Object3D>;+ const openingMarkers: THREE.Object3D[] = [];+ for (const wall of ['front', 'back', 'left', 'right'] as const) {+ const built = createShellWall(+ name,+ wall,+ materials.wall,+ wallSpecs[wall].length,+ wallHeight,+ wallThickness,+ shellOpenings.filter((opening) => opening.wall === wall),+ );+ built.root.position.set(...wallSpecs[wall].position);+ root.add(built.root);+ walls[wall] = built.root;+ openingMarkers.push(...built.openings);+ }+ const floor = new THREE.Mesh(+ new THREE.BoxGeometry(spanX, floorThickness, spanZ),+ materials.floor ?? materials.wall,+ );+ floor.name = `Mesh_${name}_Floor`;+ floor.position.y = -floorThickness / 2;+ stampSemanticMetadataV1(+ floor,+ roleMetadata(+ ['floor'],+ ['front', 'back', 'left', 'right'].map((wall) => relationship('adjacent-to', `wall.${wall}`)),+ ),+ );+ root.add(floor);++ const roof = createGableRoof('Roof', materials.roof, {+ ...options,+ spanX,+ spanZ,+ ridgeAxis,+ parent: root,+ });+ roof.root.position.y = wallHeight;+ let gables: [THREE.Object3D, THREE.Object3D] | [] = [];+ if (closedEnds) {+ const gableMaterial = materials.gable ?? materials.wall;+ const span = ridgeAxis === 'x' ? spanZ : spanX;+ const ridgeSpan = ridgeAxis === 'x' ? spanX : spanZ;+ const positiveEnd = createGableEndPanel(`${name}_Gable_positive`, gableMaterial, {+ span,+ rise: roof.rise,+ thickness: wallThickness,+ ridgeAxis,+ side: 'positive',+ openings: options.gableOpenings?.positive,+ parent: roof.root,+ });+ const negativeEnd = createGableEndPanel(`${name}_Gable_negative`, gableMaterial, {+ span,+ rise: roof.rise,+ thickness: wallThickness,+ ridgeAxis,+ side: 'negative',+ openings: options.gableOpenings?.negative,+ parent: roof.root,+ });+ const coordinate = ridgeSpan / 2;+ positiveEnd.root.position.set(+ ridgeAxis === 'x' ? coordinate : 0,+ 0,+ ridgeAxis === 'z' ? coordinate : 0,+ );+ negativeEnd.root.position.set(+ ridgeAxis === 'x' ? -coordinate : 0,+ 0,+ ridgeAxis === 'z' ? -coordinate : 0,+ );+ gables = [positiveEnd.root, negativeEnd.root];+ openingMarkers.push(...positiveEnd.openings, ...negativeEnd.openings);+ }+ return { root, walls, floor, roof, gables, openings: openingMarkers };+}++/** Matrix-driven roof-local panels, shingles, seams, or corrugations. */+export function createRoofSurfaceLayout(+ name: string,+ material: THREE.Material,+ options: RoofSurfaceLayoutOptions,+): RoofSurfaceLayoutResult {+ const parent = options.parent ?? options.face.roofRoot;+ const root = new THREE.Object3D();+ root.name = name;+ parent.add(root);+ stampSemanticMetadataV1(+ root,+ roleMetadata(+ [`roof.surface.${options.kind}`],+ [relationship('coverage-of', `roof.slope.${options.face.side}`)],+ ),+ );+ root.updateWorldMatrix(true, false);+ const faceToRoot = root.matrixWorld.clone().invert().multiply(options.face.localToWorld);+ const thickness = positive(options.thickness ?? 0.025, 'thickness');+ const along = options.face.dimensions.alongRidge;+ const downhill = options.face.dimensions.downhill;+ const specs: Array<{ width: number; length: number; x: number; z: number }> = [];++ if (options.kind === 'panels') {+ const count = Math.max(1, Math.ceil(along / positive(options.panelWidth ?? 0.9, 'panelWidth')));+ const width = along / count;+ for (let i = 0; i < count; i++)+ specs.push({+ width: width * 0.98,+ length: downhill,+ x: -along / 2 + width * (i + 0.5),+ z: downhill / 2,+ });+ } else if (options.kind === 'shingles') {+ const rowHeight = positive(options.rowHeight ?? 0.32, 'rowHeight');+ const tileWidth = positive(options.panelWidth ?? 0.42, 'panelWidth');+ const rows = Math.max(1, Math.ceil(downhill / rowHeight));+ const columns = Math.max(1, Math.ceil(along / tileWidth));+ for (let row = 0; row < rows; row++) {+ const length = Math.min(rowHeight * 1.08, downhill);+ for (let column = 0; column < columns; column++) {+ const offset = row % 2 === 0 ? 0 : tileWidth / 2;+ const x = -along / 2 + tileWidth * (column + 0.5) + offset;+ if (x + tileWidth / 2 <= along / 2 + EPSILON)+ specs.push({+ width: tileWidth * 0.96,+ length,+ x,+ z: Math.min(downhill - length / 2, row * rowHeight + length / 2),+ });+ }+ }+ } else {+ const spacing = positive(options.spacing ?? (options.kind === 'seams' ? 0.6 : 0.18), 'spacing');+ const count = Math.max(2, Math.floor(along / spacing) + 1);+ const width = options.kind === 'seams' ? 0.025 : 0.018;+ for (let i = 0; i < count; i++)+ specs.push({+ width,+ length: downhill,+ x: -along / 2 + (along * i) / (count - 1),+ z: downhill / 2,+ });+ }++ const items = specs.map((spec, index) => {+ const mesh = new THREE.Mesh(+ new THREE.BoxGeometry(spec.width, thickness, spec.length),+ material,+ );+ mesh.name = `Mesh_${name}_${index + 1}`;+ const local = new THREE.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);+ setTransform(mesh, faceToRoot.clone().multiply(local));+ root.add(mesh);+ return mesh;+ });+ return { root, items };+}diff --git a/src/breadth-prompt.ts b/src/breadth-prompt.tsnew file mode 100644index 00000000..0723d6b5--- /dev/null+++ b/src/breadth-prompt.ts@@ -0,0 +1,79 @@+import {+ validateModularKitContractV1,+ validateVfxIntentV1,+ type AssetScopeIntentV1,+ type ModularIntentV1,+ type ModularKitContractV1,+ type VfxIntentV1,+} from './contracts/breadth';++/**+ * Render only the resolved VFX recipe. This is intentionally not a noun catalog:+ * it communicates the trusted frame/runtime contract the model must satisfy.+ */+export function renderVfxBreadthPrompt(intent: VfxIntentV1): string {+ const result = validateVfxIntentV1(intent);+ if (!result.valid || !result.value) throw new TypeError('Cannot prompt from invalid VFX intent.');+ const value = result.value;+ const direction = value.facing.directionAxis ? `; direction=${value.facing.directionAxis}` : '';+ const lines = [+ `VFX contract: subtype=${value.subtype}; portability=${value.portability}; alpha=${value.transparency}; doubleSided=${value.doubleSided}.`,+ `Facing: source=${value.facing.source}; mode=${value.facing.mode}; normal=${value.facing.normalAxis ?? 'not-applicable'}${direction}.`,+ `Animation: playback=${value.animation.playback}; duration=${value.animation.durationSeconds}s; endpoint=${value.animation.endpointBehavior}; driver=${value.animation.driver}.`,+ ];+ if (value.animation.driver === 'clip') {+ lines.push(`Emit exact clip ${value.animation.clipName}; looping endpoints must match.`);+ }+ if (value.animation.driver === 'timeUniform') {+ lines.push(`Runtime sidecar must expose time uniform ${value.animation.timeUniformName}.`);+ }+ if (value.sidecar) {+ lines.push(+ `Attach nonportable ${value.sidecar.kind.toUpperCase()} sidecar ${value.sidecar.id}@${value.sidecar.version}; keep it distinct from the portable GLB fallback.`,+ );+ } else {+ lines.push('Use standard glTF PBR only; do not invent a runtime shader dependency.');+ }+ if (value.transparency !== 'opaque') {+ lines.push(+ `Every effect surface must carry real alpha data and final ${value.transparency.toUpperCase()} export metadata; opaque card rectangles fail.`,+ );+ }+ lines.push(+ 'Stamp every effect-rendering node with vfx.effect.surface.<card|beam|trail|volume|core>; stamp opaque emitter/support geometry with vfx.support.* so alpha QA scopes only the effect surface.',+ );+ return lines.join('\n');+}++export function renderModularKitPrompt(contract: ModularKitContractV1): string {+ const result = validateModularKitContractV1(contract);+ if (!result.valid || !result.value)+ throw new TypeError('Cannot prompt from an invalid modular kit.');+ const value = result.value;+ const socketLines = value.sockets.map(+ (socket) =>+ `- ${socket.pieceId}/${socket.id}: type=${socket.type}; compatible=${socket.compatibleTypes.join(',')}; rotations=${socket.allowedRotationsDegrees.join(',')}deg`,+ );+ return [+ `Modular contract: units=${value.units}; grid=${value.grid.join('x')} m.`,+ 'Stamp the exact socket frames and keep the named piece boundaries separable.',+ ...socketLines,+ 'A declared pair must join with zero seam and zero overlap within the QA tolerance.',+ ].join('\n');+}++export function renderAssetScopePrompt(+ intent: AssetScopeIntentV1,+ modular?: ModularIntentV1,+): string {+ const explicit = intent.explicit ? 'explicit user/product requirement' : 'resolved default';+ const instruction: Record<AssetScopeIntentV1['scope'], string> = {+ single:+ 'Return one reusable asset root; omit unrelated terrain, props, people, and scene dressing.',+ cluster:+ 'Return one intentional reusable cluster; members may repeat but unrelated diorama dressing is out of scope.',+ modularSet: `Return separable compatible pieces on the trusted ${modular?.grid.join('x') ?? '1x1x1'} m grid; stamp each piece with semantic socket frames, reciprocal compatibleTypes, and explicit allowedRotationsDegrees so the assembled pair can be measured for zero seam and overlap. Do not encode the grid in arbitrary userData.`,+ packMember: 'Return only this pack member; shared pack context must not become extra geometry.',+ };+ return `Asset scope (${explicit}): ${intent.scope}. ${instruction[intent.scope]}`;+}diff --git a/src/character.ts b/src/character.tsnew file mode 100644index 00000000..67f4c86e--- /dev/null+++ b/src/character.ts@@ -0,0 +1,776 @@+/**+ * Body-plan-neutral character rig contracts and the one approved joint-chain+ * scaffold. Presets are semantic data only; they do not introduce humanoid or+ * animal geometry primitive families.+ */+import * as THREE from 'three';++import { stampSemanticMetadataV1 } from './contracts';++export const KILN_CHARACTER_JOINT_EXTRAS_KEY = 'kilnCharacterJoint' as const;+export const KILN_CHARACTER_RIG_EXTRAS_KEY = 'kilnCharacterRig' as const;+export const KILN_CHARACTER_JOINT_SCHEMA_VERSION = 1 as const;++export const CHARACTER_BODY_PLANS = [+ 'biped',+ 'quadruped',+ 'avian',+ 'serpentine',+ 'multi-limb',+ 'wheeled',+ 'custom',+] as const;+export type CharacterBodyPlan = (typeof CHARACTER_BODY_PLANS)[number];++export const CHARACTER_JOINT_SIDES = ['left', 'right', 'center'] as const;+export type CharacterJointSide = (typeof CHARACTER_JOINT_SIDES)[number];++export type CharacterVector3 = [number, number, number];+export type CharacterQuaternion = [number, number, number, number];++export interface CharacterJointRestTransformV1 {+ translation: CharacterVector3;+ rotation: CharacterQuaternion;+ scale: CharacterVector3;+}++/** Portable, node-local character-joint declaration preserved in glTF extras. */+export interface CharacterJointDescriptorV1 {+ schemaVersion: 1;+ role: string;+ aliases: string[];+ parentRole?: string;+ side: CharacterJointSide;+ rest: CharacterJointRestTransformV1;+ localForwardAxis: CharacterVector3;+ localBendAxis: CharacterVector3;+ endEffector: boolean;+ contact: boolean;+}++export interface CharacterJointDescriptorV1Input {+ role: string;+ aliases?: readonly string[];+ parentRole?: string;+ side?: CharacterJointSide;+ rest?: {+ translation?: CharacterVector3;+ rotation?: CharacterQuaternion;+ scale?: CharacterVector3;+ };+ localForwardAxis?: CharacterVector3;+ localBendAxis?: CharacterVector3;+ endEffector?: boolean;+ contact?: boolean;+}++export interface CharacterRigGraphV1 {+ schemaVersion: 1;+ bodyPlan: CharacterBodyPlan;+ joints: CharacterJointDescriptorV1[];+}++export interface CharacterRigGraphV1Input {+ bodyPlan: CharacterBodyPlan;+ joints: readonly (CharacterJointDescriptorV1 | CharacterJointDescriptorV1Input)[];+}++export interface CharacterContractIssue {+ code: string;+ path: string;+ message: string;+}++export interface CharacterJointValidationResult {+ valid: boolean;+ value?: CharacterJointDescriptorV1;+ issues: CharacterContractIssue[];+}++export interface CharacterRigValidationResult {+ valid: boolean;+ value?: CharacterRigGraphV1;+ issues: CharacterContractIssue[];+}++const IDENTITY_QUATERNION: CharacterQuaternion = [0, 0, 0, 1];+const UNIT_SCALE: CharacterVector3 = [1, 1, 1];+const FORWARD_AXIS: CharacterVector3 = [1, 0, 0];+const BEND_AXIS: CharacterVector3 = [0, 0, 1];++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const isFiniteTuple = (value: unknown, length: number): value is number[] =>+ Array.isArray(value) &&+ value.length === length &&+ value.every((component) => typeof component === 'number' && Number.isFinite(component));++const tuple3 = (value: readonly number[]): CharacterVector3 => [value[0]!, value[1]!, value[2]!];+const tuple4 = (value: readonly number[]): CharacterQuaternion => [+ value[0]!,+ value[1]!,+ value[2]!,+ value[3]!,+];++function validRole(value: unknown): value is string {+ return typeof value === 'string' && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value);+}++function validateUnitVector(+ value: unknown,+ path: string,+ issues: CharacterContractIssue[],+): value is number[] {+ if (!isFiniteTuple(value, 3)) {+ issues.push({ code: 'INVALID_AXIS', path, message: `${path} must be three finite numbers.` });+ return false;+ }+ const magnitude = Math.hypot(...value);+ if (Math.abs(magnitude - 1) > 1e-6) {+ issues.push({ code: 'NON_UNIT_AXIS', path, message: `${path} must be normalized.` });+ return false;+ }+ return true;+}++export function cloneCharacterJointDescriptorV1(+ descriptor: CharacterJointDescriptorV1,+): CharacterJointDescriptorV1 {+ return {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ role: descriptor.role,+ aliases: [...descriptor.aliases],+ ...(descriptor.parentRole ? { parentRole: descriptor.parentRole } : {}),+ side: descriptor.side,+ rest: {+ translation: tuple3(descriptor.rest.translation),+ rotation: tuple4(descriptor.rest.rotation),+ scale: tuple3(descriptor.rest.scale),+ },+ localForwardAxis: tuple3(descriptor.localForwardAxis),+ localBendAxis: tuple3(descriptor.localBendAxis),+ endEffector: descriptor.endEffector,+ contact: descriptor.contact,+ };+}++export function validateCharacterJointDescriptorV1(value: unknown): CharacterJointValidationResult {+ const issues: CharacterContractIssue[] = [];+ if (!isRecord(value)) {+ return {+ valid: false,+ issues: [+ { code: 'EXPECTED_OBJECT', path: '', message: 'Joint descriptor must be an object.' },+ ],+ };+ }+ if (value.schemaVersion !== KILN_CHARACTER_JOINT_SCHEMA_VERSION) {+ issues.push({+ code: 'UNSUPPORTED_SCHEMA_VERSION',+ path: 'schemaVersion',+ message: `schemaVersion must be ${KILN_CHARACTER_JOINT_SCHEMA_VERSION}.`,+ });+ }+ if (!validRole(value.role)) {+ issues.push({+ code: 'INVALID_ROLE',+ path: 'role',+ message: 'role must be a stable lowercase ID.',+ });+ }+ if (+ !Array.isArray(value.aliases) ||+ value.aliases.some((alias) => typeof alias !== 'string' || alias.trim().length === 0)+ ) {+ issues.push({+ code: 'INVALID_ALIASES',+ path: 'aliases',+ message: 'aliases must be non-empty strings.',+ });+ } else if (new Set(value.aliases).size !== value.aliases.length) {+ issues.push({ code: 'DUPLICATE_ALIAS', path: 'aliases', message: 'aliases must be unique.' });+ }+ if (value.parentRole !== undefined && !validRole(value.parentRole)) {+ issues.push({+ code: 'INVALID_PARENT_ROLE',+ path: 'parentRole',+ message: 'parentRole must be a stable lowercase ID.',+ });+ }+ if (!(CHARACTER_JOINT_SIDES as readonly unknown[]).includes(value.side)) {+ issues.push({+ code: 'INVALID_SIDE',+ path: 'side',+ message: 'side must be left, right, or center.',+ });+ }+ if (!isRecord(value.rest)) {+ issues.push({ code: 'INVALID_REST', path: 'rest', message: 'rest transform is required.' });+ } else {+ if (!isFiniteTuple(value.rest.translation, 3)) {+ issues.push({+ code: 'INVALID_REST_TRANSLATION',+ path: 'rest.translation',+ message: 'rest.translation must be three finite meters.',+ });+ }+ if (!isFiniteTuple(value.rest.rotation, 4)) {+ issues.push({+ code: 'INVALID_REST_ROTATION',+ path: 'rest.rotation',+ message: 'rest.rotation must be a finite quaternion.',+ });+ } else if (Math.abs(Math.hypot(...value.rest.rotation) - 1) > 1e-6) {+ issues.push({+ code: 'NON_UNIT_REST_ROTATION',+ path: 'rest.rotation',+ message: 'rest.rotation must be normalized.',+ });+ }+ if (+ !isFiniteTuple(value.rest.scale, 3) ||+ value.rest.scale.some((component) => component <= 0)+ ) {+ issues.push({+ code: 'INVALID_REST_SCALE',+ path: 'rest.scale',+ message: 'rest.scale must contain three positive finite values.',+ });+ }+ }+ const forwardAxis = value.localForwardAxis;+ const bendAxis = value.localBendAxis;+ const forwardValid = validateUnitVector(forwardAxis, 'localForwardAxis', issues);+ const bendValid = validateUnitVector(bendAxis, 'localBendAxis', issues);+ if (forwardValid && bendValid) {+ const dot =+ forwardAxis[0]! * bendAxis[0]! ++ forwardAxis[1]! * bendAxis[1]! ++ forwardAxis[2]! * bendAxis[2]!;+ if (Math.abs(dot) > 1e-6) {+ issues.push({+ code: 'NON_ORTHOGONAL_AXES',+ path: 'localBendAxis',+ message: 'local forward and bend axes must be orthogonal.',+ });+ }+ }+ if (typeof value.endEffector !== 'boolean') {+ issues.push({+ code: 'INVALID_END_EFFECTOR',+ path: 'endEffector',+ message: 'endEffector must be boolean.',+ });+ }+ if (typeof value.contact !== 'boolean') {+ issues.push({ code: 'INVALID_CONTACT', path: 'contact', message: 'contact must be boolean.' });+ }+ if (issues.length > 0) return { valid: false, issues };+ return {+ valid: true,+ value: cloneCharacterJointDescriptorV1(value as unknown as CharacterJointDescriptorV1),+ issues,+ };+}++export function createCharacterJointDescriptorV1(+ input: CharacterJointDescriptorV1Input,+): CharacterJointDescriptorV1 {+ const descriptor: CharacterJointDescriptorV1 = {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ role: input.role,+ aliases: [...(input.aliases ?? [])],+ ...(input.parentRole ? { parentRole: input.parentRole } : {}),+ side: input.side ?? 'center',+ rest: {+ translation: tuple3(input.rest?.translation ?? [0, 0, 0]),+ rotation: tuple4(input.rest?.rotation ?? IDENTITY_QUATERNION),+ scale: tuple3(input.rest?.scale ?? UNIT_SCALE),+ },+ localForwardAxis: tuple3(input.localForwardAxis ?? FORWARD_AXIS),+ localBendAxis: tuple3(input.localBendAxis ?? BEND_AXIS),+ endEffector: input.endEffector ?? false,+ contact: input.contact ?? false,+ };+ const validation = validateCharacterJointDescriptorV1(descriptor);+ if (!validation.valid || !validation.value) {+ throw new TypeError(+ `Invalid CharacterJointDescriptorV1: ${validation.issues+ .map((issue) => `${issue.path}: ${issue.message}`)+ .join('; ')}`,+ );+ }+ return validation.value;+}++export function validateCharacterRigGraphV1(value: unknown): CharacterRigValidationResult {+ const issues: CharacterContractIssue[] = [];+ if (!isRecord(value)) {+ return {+ valid: false,+ issues: [{ code: 'EXPECTED_OBJECT', path: '', message: 'Rig graph must be an object.' }],+ };+ }+ if (value.schemaVersion !== KILN_CHARACTER_JOINT_SCHEMA_VERSION) {+ issues.push({+ code: 'UNSUPPORTED_SCHEMA_VERSION',+ path: 'schemaVersion',+ message: `schemaVersion must be ${KILN_CHARACTER_JOINT_SCHEMA_VERSION}.`,+ });+ }+ if (!(CHARACTER_BODY_PLANS as readonly unknown[]).includes(value.bodyPlan)) {+ issues.push({+ code: 'INVALID_BODY_PLAN',+ path: 'bodyPlan',+ message: 'bodyPlan is unsupported.',+ });+ }+ if (!Array.isArray(value.joints) || value.joints.length === 0) {+ issues.push({ code: 'INVALID_JOINTS', path: 'joints', message: 'joints must not be empty.' });+ }+ const joints: CharacterJointDescriptorV1[] = [];+ if (Array.isArray(value.joints)) {+ value.joints.forEach((joint, index) => {+ const result = validateCharacterJointDescriptorV1(joint);+ if (result.value) joints.push(result.value);+ for (const issue of result.issues) {+ issues.push({ ...issue, path: `joints[${index}]${issue.path ? `.${issue.path}` : ''}` });+ }+ });+ }+ const byRole = new Map<string, number>();+ const aliasOwners = new Map<string, string>();+ joints.forEach((joint, index) => {+ const prior = byRole.get(joint.role);+ if (prior !== undefined) {+ issues.push({+ code: 'DUPLICATE_JOINT_ROLE',+ path: `joints[${index}].role`,+ message: `role ${joint.role} duplicates joints[${prior}].role.`,+ });+ } else byRole.set(joint.role, index);+ for (const alias of joint.aliases) {+ const owner = aliasOwners.get(alias);+ if (owner && owner !== joint.role) {+ issues.push({+ code: 'AMBIGUOUS_JOINT_ALIAS',+ path: `joints[${index}].aliases`,+ message: `alias ${alias} is already owned by ${owner}.`,+ });+ } else aliasOwners.set(alias, joint.role);+ }+ });+ joints.forEach((joint, index) => {+ if (joint.parentRole && !byRole.has(joint.parentRole)) {+ issues.push({+ code: 'UNKNOWN_PARENT_ROLE',+ path: `joints[${index}].parentRole`,+ message: `parentRole ${joint.parentRole} is not declared.`,+ });+ }+ const seen = new Set<string>([joint.role]);+ let cursor = joint.parentRole;+ while (cursor) {+ if (seen.has(cursor)) {+ issues.push({+ code: 'JOINT_PARENT_CYCLE',+ path: `joints[${index}].parentRole`,+ message: `parent chain for ${joint.role} contains a cycle at ${cursor}.`,+ });+ break;+ }+ seen.add(cursor);+ const parentIndex = byRole.get(cursor);+ cursor = parentIndex === undefined ? undefined : joints[parentIndex]?.parentRole;+ }+ });+ if (issues.length > 0) return { valid: false, issues };+ return {+ valid: true,+ value: {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ bodyPlan: value.bodyPlan as CharacterBodyPlan,+ joints: joints.map(cloneCharacterJointDescriptorV1),+ },+ issues,+ };+}++export function createCharacterRigGraphV1(input: CharacterRigGraphV1Input): CharacterRigGraphV1 {+ const graph = {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ bodyPlan: input.bodyPlan,+ joints: input.joints.map((joint) =>+ 'schemaVersion' in joint+ ? cloneCharacterJointDescriptorV1(joint)+ : createCharacterJointDescriptorV1(joint),+ ),+ };+ const result = validateCharacterRigGraphV1(graph);+ if (!result.valid || !result.value) {+ throw new TypeError(+ `Invalid CharacterRigGraphV1: ${result.issues+ .map((issue) => `${issue.path}: ${issue.message}`)+ .join('; ')}`,+ );+ }+ return result.value;+}++export function stampCharacterRigGraphV1<T extends { userData: Record<string, unknown> }>(+ target: T,+ input: CharacterRigGraphV1 | CharacterRigGraphV1Input,+): T {+ const graph = createCharacterRigGraphV1(input);+ stampSemanticMetadataV1(target, {+ roles: ['character.rig', `character.body-plan.${graph.bodyPlan}`],+ relationships: graph.joints.map((joint) => ({+ kind: 'contains-joint',+ target: `joint.${joint.role}`,+ targetType: 'role' as const,+ })),+ });+ target.userData[KILN_CHARACTER_RIG_EXTRAS_KEY] = createCharacterRigGraphV1(graph);+ return target;+}++export function readCharacterRigGraphV1(target: {+ userData?: Record<string, unknown>;+}): CharacterRigGraphV1 | undefined {+ const value = target.userData?.[KILN_CHARACTER_RIG_EXTRAS_KEY];+ const result = validateCharacterRigGraphV1(value);+ return result.valid ? result.value : undefined;+}++function axisQuaternion(from: CharacterVector3, to: CharacterVector3): CharacterQuaternion {+ const value = new THREE.Quaternion().setFromUnitVectors(+ new THREE.Vector3(...from),+ new THREE.Vector3(...to),+ );+ return [value.x, value.y, value.z, value.w];+}++export function stampCharacterJointDescriptorV1<T extends { userData: Record<string, unknown> }>(+ target: T,+ input: CharacterJointDescriptorV1 | CharacterJointDescriptorV1Input,+): T {+ const descriptor = createCharacterJointDescriptorV1(input);+ const frames = [+ { id: 'rest', translation: [0, 0, 0] as CharacterVector3, rotation: IDENTITY_QUATERNION },+ {+ id: 'forward',+ translation: [0, 0, 0] as CharacterVector3,+ rotation: axisQuaternion(FORWARD_AXIS, descriptor.localForwardAxis),+ },+ {+ id: 'bend',+ translation: [0, 0, 0] as CharacterVector3,+ rotation: axisQuaternion([0, 1, 0], descriptor.localBendAxis),+ },+ ...(descriptor.endEffector+ ? [+ {+ id: 'end-effector',+ translation: [0, 0, 0] as CharacterVector3,+ rotation: IDENTITY_QUATERNION,+ },+ ]+ : []),+ ...(descriptor.contact+ ? [+ {+ id: 'contact',+ translation: [0, 0, 0] as CharacterVector3,+ rotation: IDENTITY_QUATERNION,+ },+ ]+ : []),+ ];+ stampSemanticMetadataV1(target, {+ roles: [+ 'skeleton.joint',+ `joint.${descriptor.role}`,+ `joint.side.${descriptor.side}`,+ ...descriptor.aliases.map((alias) => `joint.alias.${alias}`),+ ...(descriptor.endEffector ? ['joint.end-effector'] : []),+ ...(descriptor.contact ? ['contact.ground'] : []),+ ],+ relationships: descriptor.parentRole+ ? [{ kind: 'parent-joint', target: `joint.${descriptor.parentRole}`, targetType: 'role' }]+ : [],+ frames,+ sockets: [+ ...(descriptor.endEffector+ ? [+ {+ id: 'end-effector',+ type: 'character.attachment',+ frame: 'end-effector',+ compatibleTypes: ['character.held-item'],+ },+ ]+ : []),+ ...(descriptor.contact+ ? [+ {+ id: 'ground-contact',+ type: 'character.contact',+ frame: 'contact',+ compatibleTypes: ['world.ground'],+ },+ ]+ : []),+ ],+ });+ target.userData[KILN_CHARACTER_JOINT_EXTRAS_KEY] = cloneCharacterJointDescriptorV1(descriptor);+ return target;+}++export function readCharacterJointDescriptorV1(target: {+ userData?: Record<string, unknown>;+}): CharacterJointDescriptorV1 | undefined {+ const value = target.userData?.[KILN_CHARACTER_JOINT_EXTRAS_KEY];+ const result = validateCharacterJointDescriptorV1(value);+ return result.valid ? result.value : undefined;+}++export interface JointChainSegmentV1 {+ role: string;+ aliases?: readonly string[];+ offset: CharacterVector3;+ restRotation?: CharacterQuaternion;+ restScale?: CharacterVector3;+ side?: CharacterJointSide;+ localForwardAxis?: CharacterVector3;+ localBendAxis?: CharacterVector3;+ endEffector?: boolean;+ contact?: boolean;+}++export interface CreateJointChainOptionsV1 {+ parent?: THREE.Object3D;+ /** Semantic parent role for the first node when `parent` is a declared joint. */+ parentRole?: string;+}++export interface JointChainResultV1 {+ root: THREE.Object3D;+ end: THREE.Object3D;+ nodes: THREE.Object3D[];+ byRole: ReadonlyMap<string, THREE.Object3D>;+ descriptors: CharacterJointDescriptorV1[];+}++export function characterJointNodeName(chainName: string, role: string): string {+ const safeChain = chainName+ .trim()+ .replace(/[^A-Za-z0-9]+/g, '_')+ .replace(/^_+|_+$/g, '');+ const safeRole = role.replace(/[^A-Za-z0-9]+/g, '_');+ if (!safeChain)+ throw new TypeError('createJointChain chainName must contain a letter or number.');+ return `Joint_${safeChain}_${safeRole}`;+}++/**+ * Create one deterministic parented chain. The helper owns only pivots, local+ * rest transforms, frames, and semantic metadata; callers remain free to build+ * any biped, quadruped, wing, tail, tentacle, or custom geometry around it.+ */+export function createJointChain(+ chainName: string,+ segments: readonly JointChainSegmentV1[],+ options: CreateJointChainOptionsV1 = {},+): JointChainResultV1 {+ if (segments.length === 0) throw new TypeError('createJointChain requires at least one segment.');+ const seen = new Set<string>();+ const nodes: THREE.Object3D[] = [];+ const descriptors: CharacterJointDescriptorV1[] = [];+ const byRole = new Map<string, THREE.Object3D>();+ let parent = options.parent;+ let parentRole = options.parentRole;+ for (const segment of segments) {+ if (seen.has(segment.role)) throw new TypeError(`Duplicate joint-chain role: ${segment.role}.`);+ seen.add(segment.role);+ const descriptor = createCharacterJointDescriptorV1({+ role: segment.role,+ aliases: segment.aliases,+ ...(parentRole ? { parentRole } : {}),+ side: segment.side,+ rest: {+ translation: segment.offset,+ rotation: segment.restRotation,+ scale: segment.restScale,+ },+ localForwardAxis: segment.localForwardAxis,+ localBendAxis: segment.localBendAxis,+ endEffector: segment.endEffector,+ contact: segment.contact,+ });+ const node = new THREE.Object3D();+ node.name = characterJointNodeName(chainName, segment.role);+ node.position.fromArray(descriptor.rest.translation);+ node.quaternion.fromArray(descriptor.rest.rotation);+ node.scale.fromArray(descriptor.rest.scale);+ stampCharacterJointDescriptorV1(node, descriptor);+ if (parent) parent.add(node);+ parent = node;+ parentRole = descriptor.role;+ nodes.push(node);+ descriptors.push(descriptor);+ byRole.set(descriptor.role, node);+ }+ return {+ root: nodes[0]!,+ end: nodes[nodes.length - 1]!,+ nodes,+ byRole,+ descriptors,+ };+}++export interface CharacterJointNodeEvidenceV1 {+ node: THREE.Object3D;+ nodePath: string;+ descriptor: CharacterJointDescriptorV1;+}++/** Deterministic indexed paths shared by QA and diagnostic descriptors. */+export function collectCharacterJointNodes(root: THREE.Object3D): CharacterJointNodeEvidenceV1[] {+ const joints: CharacterJointNodeEvidenceV1[] = [];+ const visit = (node: THREE.Object3D, parentPath: string, siblingIndex: number): void => {+ const segment = `${node.name.trim() || node.type || 'Object3D'}[${siblingIndex}]`;+ const nodePath = parentPath ? `${parentPath}/${segment}` : segment;+ const descriptor = readCharacterJointDescriptorV1(node);+ if (descriptor) joints.push({ node, nodePath, descriptor });+ node.children.forEach((child, index) => {+ visit(child, nodePath, index);+ });+ };+ visit(root, '', 0);+ return joints;+}++const presetJoint = (+ role: string,+ parentRole: string | undefined,+ translation: CharacterVector3,+ options: Omit<CharacterJointDescriptorV1Input, 'role' | 'parentRole' | 'rest'> = {},+): CharacterJointDescriptorV1 =>+ createCharacterJointDescriptorV1({+ role,+ ...(parentRole ? { parentRole } : {}),+ ...options,+ rest: { translation },+ });++export const BIPED_RIG_PRESET_V1: CharacterRigGraphV1 = createCharacterRigGraphV1({+ bodyPlan: 'biped',+ joints: [+ presetJoint('hips', undefined, [0, 1, 0], { aliases: ['pelvis'] }),+ presetJoint('spine', 'hips', [0, 0.45, 0], { aliases: ['torso'] }),+ presetJoint('head', 'spine', [0, 0.55, 0]),+ presetJoint('shoulder.left', 'spine', [0, 0.3, -0.25], { side: 'left' }),+ presetJoint('elbow.left', 'shoulder.left', [0, -0.35, 0], { side: 'left' }),+ presetJoint('wrist.left', 'elbow.left', [0, -0.35, 0], {+ side: 'left',+ aliases: ['hand.left', 'grip.left'],+ endEffector: true,+ }),+ presetJoint('shoulder.right', 'spine', [0, 0.3, 0.25], { side: 'right' }),+ presetJoint('elbow.right', 'shoulder.right', [0, -0.35, 0], { side: 'right' }),+ presetJoint('wrist.right', 'elbow.right', [0, -0.35, 0], {+ side: 'right',+ aliases: ['hand.right', 'grip.right'],+ endEffector: true,+ }),+ presetJoint('hip.left', 'hips', [0, -0.1, -0.14], { side: 'left' }),+ presetJoint('knee.left', 'hip.left', [0, -0.45, 0], { side: 'left' }),+ presetJoint('ankle.left', 'knee.left', [0, -0.45, 0], {+ side: 'left',+ aliases: ['foot.left'],+ endEffector: true,+ contact: true,+ }),+ presetJoint('hip.right', 'hips', [0, -0.1, 0.14], { side: 'right' }),+ presetJoint('knee.right', 'hip.right', [0, -0.45, 0], { side: 'right' }),+ presetJoint('ankle.right', 'knee.right', [0, -0.45, 0], {+ side: 'right',+ aliases: ['foot.right'],+ endEffector: true,+ contact: true,+ }),+ ],+});++export const QUADRUPED_RIG_PRESET_V1: CharacterRigGraphV1 = createCharacterRigGraphV1({+ bodyPlan: 'quadruped',+ joints: [+ presetJoint('hips', undefined, [0, 0.8, 0], { aliases: ['pelvis'] }),+ presetJoint('spine', 'hips', [0.7, 0, 0]),+ presetJoint('neck', 'spine', [0.45, 0.1, 0]),+ presetJoint('head', 'neck', [0.3, 0, 0]),+ presetJoint('shoulder.fore.left', 'spine', [0.2, -0.1, -0.28], { side: 'left' }),+ presetJoint('elbow.fore.left', 'shoulder.fore.left', [0, -0.4, 0], { side: 'left' }),+ presetJoint('paw.fore.left', 'elbow.fore.left', [0, -0.3, 0], {+ side: 'left',+ endEffector: true,+ contact: true,+ }),+ presetJoint('shoulder.fore.right', 'spine', [0.2, -0.1, 0.28], { side: 'right' }),+ presetJoint('elbow.fore.right', 'shoulder.fore.right', [0, -0.4, 0], { side: 'right' }),+ presetJoint('paw.fore.right', 'elbow.fore.right', [0, -0.3, 0], {+ side: 'right',+ endEffector: true,+ contact: true,+ }),+ presetJoint('hip.hind.left', 'hips', [0, -0.1, -0.28], { side: 'left' }),+ presetJoint('knee.hind.left', 'hip.hind.left', [0, -0.4, 0], { side: 'left' }),+ presetJoint('paw.hind.left', 'knee.hind.left', [0, -0.3, 0], {+ side: 'left',+ endEffector: true,+ contact: true,+ }),+ presetJoint('hip.hind.right', 'hips', [0, -0.1, 0.28], { side: 'right' }),+ presetJoint('knee.hind.right', 'hip.hind.right', [0, -0.4, 0], { side: 'right' }),+ presetJoint('paw.hind.right', 'knee.hind.right', [0, -0.3, 0], {+ side: 'right',+ endEffector: true,+ contact: true,+ }),+ ],+});++export function expandCharacterRigPreset(bodyPlan: 'biped' | 'quadruped'): CharacterRigGraphV1 {+ const source = bodyPlan === 'biped' ? BIPED_RIG_PRESET_V1 : QUADRUPED_RIG_PRESET_V1;+ return createCharacterRigGraphV1(source);+}++/** Return only the already-resolved body-plan recipe for prompt/skill injection. */+export function characterBodyPlanRecipe(+ bodyPlan: CharacterBodyPlan,+ customGraph?: CharacterRigGraphV1,+): string {+ if (bodyPlan === 'biped') {+ return 'Resolved body plan: BIPED. Declare hips → spine → head; paired shoulder → elbow → wrist and hip → knee → ankle chains. Wrists are grip end effectors; ankles are Y=0 contacts. Animate only unique Joint_* nodes and preserve +X locomotion.';+ }+ if (bodyPlan === 'quadruped') {+ return 'Resolved body plan: QUADRUPED. Declare hips → spine → neck → head plus left/right fore shoulder → elbow → paw and left/right hind hip → knee → paw chains. All four paws are Y=0 contacts; locomotion travels +X.';+ }+ if (bodyPlan === 'avian') {+ return 'Resolved body plan: AVIAN. Declare an axial torso/neck/head graph, paired shoulder → wing-mid → wing-tip chains, and the requested leg/contact chains. Wing tips are end effectors; preserve +X flight direction.';+ }+ if (bodyPlan === 'serpentine') {+ return 'Resolved body plan: SERPENTINE. Build one continuous axial root → spine segments → tail-tip graph with explicit local bend axes and requested ground contacts. Do not add humanoid limb assumptions; locomotion travels +X.';+ }+ if (bodyPlan === 'multi-limb') {+ return 'Resolved body plan: MULTI-LIMB. Expand exactly the declared custom role graph, keep every branch parent edge explicit, and tag each requested terminal/contact node. Do not collapse repeated branches into duplicate Joint_* names.';+ }+ if (bodyPlan === 'wheeled') {+ return 'Resolved body plan: WHEELED CHARACTER. Declare the character core and each articulated appendage as explicit unique joint roles; keep wheel locomotion semantics separate from limb/contact roles and travel +X.';+ }+ const roles = customGraph?.joints.map((joint) => joint.role).join(', ');+ return `Resolved body plan: CUSTOM. Expand only the declared semantic graph${roles ? ` (${roles})` : ''}; preserve every explicit parent edge, end effector, contact, and local axis without adding another body-plan preset.`;+}diff --git a/src/contracts/asset.test.ts b/src/contracts/asset.test.tsnew file mode 100644index 00000000..be352e1c--- /dev/null+++ b/src/contracts/asset.test.ts@@ -0,0 +1,341 @@+import { describe, expect, test } from 'bun:test';++import {+ ASSET_CATEGORIES,+ KILN_ASSET_FRAME,+ createAssetIntentV1,+ isAssetIntentV1,+ migrateLegacyAssetIntentV1Scope,+ validateAssetIntentV1,+ VEGETATION_SUBTYPES,+} from './asset';+import { ASSET_SCOPES, VFX_SUBTYPES } from './breadth';++describe('asset contracts', () => {+ test('SCOPE-001 normalizes mandatory scope from request closure without model metadata', () => {+ expect(ASSET_SCOPES).toEqual(['single', 'cluster', 'modularSet', 'packMember']);+ expect(createAssetIntentV1({ category: 'prop' }).scope).toEqual({+ schemaVersion: 1,+ scope: 'single',+ explicit: false,+ });+ expect(+ createAssetIntentV1({ category: 'environment', subtype: 'set-dressing-cluster' }).scope.scope,+ ).toBe('cluster');+ expect(+ createAssetIntentV1({ category: 'architecture', subtype: 'modular-wall' }).scope.scope,+ ).toBe('modularSet');+ expect(+ createAssetIntentV1({+ category: 'prop',+ scope: { scope: 'packMember', explicit: true },+ }).scope,+ ).toEqual({ schemaVersion: 1, scope: 'packMember', explicit: true });+ });++ test('migrates only missing legacy scope while keeping VFX contract validation strict', () => {+ const current = createAssetIntentV1({ category: 'prop', subtype: 'crate' });+ const { scope: _scope, ...legacy } = current;+ expect(validateAssetIntentV1(legacy).issues.map((issue) => issue.code)).toContain(+ 'INVALID_ASSET_SCOPE',+ );+ const migratedWithUntrustedMeta = migrateLegacyAssetIntentV1Scope({+ ...legacy,+ meta: { scope: 'cluster' },+ });+ expect(migratedWithUntrustedMeta.valid).toBe(true);+ expect(migratedWithUntrustedMeta.issues).toEqual([]);+ expect(migratedWithUntrustedMeta.migratedScope).toBe(true);+ expect(migratedWithUntrustedMeta.value?.scope).toEqual(current.scope);+ expect((migratedWithUntrustedMeta.value as unknown as { meta?: unknown })?.meta).toEqual({+ scope: 'cluster',+ });++ const vfx = createAssetIntentV1({ category: 'vfx', subtype: 'portal' });+ const { scope: _vfxScope, vfx: _vfx, ...legacyVfx } = vfx;+ const migrated = migrateLegacyAssetIntentV1Scope(legacyVfx);+ expect(migrated.migratedScope).toBe(true);+ expect(migrated.valid).toBe(false);+ expect(migrated.issues.map((issue) => issue.code)).toContain('EXPECTED_OBJECT');+ });++ test('VFX-001 normalizes every subtype and enforces category-exclusive portability truth', () => {+ for (const subtype of VFX_SUBTYPES) {+ const intent = createAssetIntentV1({ category: 'vfx', subtype });+ expect(intent.vfx?.subtype).toBe(subtype);+ expect(intent.subtype).toBe(subtype);+ expect(intent.material.transparency).toBe(intent.vfx?.transparency);+ expect(intent.capabilities).toContain('transparentSurface');+ expect(validateAssetIntentV1(intent).valid).toBe(true);+ if (subtype === 'runtimeShader') {+ expect(intent.vfx?.portability).toBe('sidecar');+ expect(intent.material.mode).toBe('runtimeTsl');+ expect(intent.capabilities).toContain('runtimeShader');+ }+ }+ const vfx = createAssetIntentV1({ category: 'vfx', subtype: 'billboard' });+ expect(vfx.vfx?.facing).toMatchObject({+ source: 'inferred',+ mode: 'camera-spherical',+ });+ expect(+ validateAssetIntentV1({+ ...createAssetIntentV1({ category: 'prop' }),+ vfx: vfx.vfx,+ }).issues.map((issue) => issue.code),+ ).toContain('VFX_INTENT_CATEGORY_MISMATCH');+ expect(+ validateAssetIntentV1({+ ...vfx,+ material: { ...vfx.material, transparency: 'opaque' },+ }).issues.map((issue) => issue.code),+ ).toContain('VFX_MATERIAL_TRANSPARENCY_MISMATCH');+ });+ test('VEG-001 normalizes every supported vegetation growth form into trusted intent', () => {+ expect(VEGETATION_SUBTYPES).toEqual([+ 'tree',+ 'conifer',+ 'shrub',+ 'grass',+ 'frond/palm',+ 'vine',+ 'crop/flower',+ 'succulent',+ 'fungus',+ 'aquatic',+ 'bare/dead',+ 'custom',+ ]);+ for (const subtype of VEGETATION_SUBTYPES) {+ const intent = createAssetIntentV1({ category: 'vegetation', vegetation: { subtype } });+ expect(intent.subtype).toBe(subtype);+ expect(intent.vegetation?.subtype).toBe(subtype);+ expect(intent.vegetation?.growthState).toBe(subtype === 'bare/dead' ? 'bare' : 'lush');+ expect(intent.capabilities).toContain('grounded');+ expect(validateAssetIntentV1(intent).valid).toBe(true);+ }+ });++ test('VEG-001 rejects category drift and inconsistent bare canopy state', () => {+ const intent = createAssetIntentV1({+ category: 'vegetation',+ vegetation: { subtype: 'tree', growthState: 'sparse' },+ });+ expect(+ validateAssetIntentV1({+ ...intent,+ vegetation: { ...intent.vegetation, subtype: 'conifer' },+ }).issues.map((issue) => issue.code),+ ).toContain('VEGETATION_SUBTYPE_MISMATCH');+ expect(+ validateAssetIntentV1({+ ...intent,+ vegetation: { ...intent.vegetation, growthState: 'bare', canopyProfile: 'broadleaf' },+ }).issues.map((issue) => issue.code),+ ).toContain('VEGETATION_BARE_PROFILE_MISMATCH');+ });++ test('publishes one exact frame and all seven canonical categories', () => {+ expect(KILN_ASSET_FRAME).toEqual({+ units: 'm',+ forward: '+X',+ up: '+Y',+ right: '+Z',+ groundY: 0,+ });+ expect(ASSET_CATEGORIES).toEqual([+ 'prop',+ 'character',+ 'vfx',+ 'environment',+ 'architecture',+ 'vegetation',+ 'vehicle',+ ]);+ });++ test('creates a fully normalized intent with portable PBR as the default', () => {+ const intent = createAssetIntentV1({+ category: 'vehicle',+ subtype: 'wheeled',+ capabilities: ['driveable', 'grounded'],+ bounds: { x: 4.2, y: 1.6, z: 1.8, units: 'm' },+ requiredParts: ['chassis', 'wheel.frontLeft'],+ forbiddenExtras: ['terrainBase'],+ });++ expect(intent.schemaVersion).toBe(1);+ expect(intent.frame).toBe(KILN_ASSET_FRAME);+ expect(intent.material).toEqual({ mode: 'pbrRecipe' });+ expect(intent.qaProfile).toBe('vehicle.default');+ expect(isAssetIntentV1(intent)).toBe(true);+ });++ test('copies trusted arrays instead of retaining mutable caller references', () => {+ const required = ['body'];+ const intent = createAssetIntentV1({ category: 'prop', requiredParts: required });+ required.push('surprise');+ expect(intent.requiredParts).toEqual(['body']);+ });++ test('normalizes explicit character construction and per-clip playback semantics', () => {+ const intent = createAssetIntentV1({+ category: 'character',+ subtype: 'quadruped',+ animation: {+ clips: ['Walk', 'Death'],+ locomotionDirection: '+X',+ rootMotion: 'forward',+ gait: 'trot',+ },+ character: { grounded: true, heldItem: { required: true, attachmentRole: 'grip.right' } },+ });++ expect(intent.character).toEqual({+ bodyPlan: 'quadruped',+ grounded: true,+ locomotion: 'walk',+ gait: 'trot',+ rootMotion: 'forward',+ clips: [+ { name: 'Walk', playback: 'loop' },+ { name: 'Death', playback: 'oneShot' },+ ],+ heldItem: { required: true, attachmentRole: 'grip.right' },+ });+ expect(intent.capabilities).toContain('grounded');+ expect(validateAssetIntentV1(intent).valid).toBe(true);+ });++ test('normalizes subtype-specific vehicle assemblies without leaking wheel rules to boats', () => {+ const car = createAssetIntentV1({ category: 'vehicle', subtype: 'wheeled' });+ const boat = createAssetIntentV1({ category: 'vehicle', subtype: 'watercraft' });++ expect(car.vehicle).toMatchObject({+ subtype: 'wheeled',+ supportAssemblies: ['wheel'],+ wheelCount: 4,+ axleCount: 2,+ steering: 'front',+ supportPolicy: 'grounded',+ });+ expect(boat.vehicle).toEqual({+ subtype: 'watercraft',+ supportAssemblies: ['hull'],+ propulsionAssemblies: ['propeller'],+ wheelCount: 0,+ axleCount: 0,+ steering: 'rear',+ supportPolicy: 'waterborne',+ animationAssemblies: [],+ });+ expect(boat.capabilities).not.toContain('grounded');+ });++ test('rejects category-specific character and vehicle contract drift', () => {+ const character = createAssetIntentV1({ category: 'character', subtype: 'biped' });+ const badCharacter = {+ ...character,+ character: { ...character.character!, bodyPlan: 'centaur' },+ };+ expect(validateAssetIntentV1(badCharacter).issues.map((issue) => issue.code)).toContain(+ 'INVALID_CHARACTER_BODY_PLAN',+ );++ const boat = createAssetIntentV1({ category: 'vehicle', subtype: 'watercraft' });+ const wheeledBoat = { ...boat, vehicle: { ...boat.vehicle!, wheelCount: 4, axleCount: 2 } };+ expect(validateAssetIntentV1(wheeledBoat).issues.map((issue) => issue.code)).toContain(+ 'VEHICLE_WHEEL_POLICY_MISMATCH',+ );+ });++ test('normalizes a complete architecture intent with consistent pitch, rise, and portal clearance', () => {+ const intent = createAssetIntentV1({+ category: 'architecture',+ subtype: 'barn',+ architecture: {+ enterable: true,+ footprint: { spanX: 8, spanZ: 6 },+ wallHeight: 3.2,+ scaleMode: 'realistic',+ roof: { type: 'gable', ridgeAxis: 'x', pitchDegrees: 35, overhang: 0.45 },+ portal: { width: 1.8, height: 2.5, depth: 0.2 },+ },+ });++ expect(intent.architecture).toMatchObject({+ subtype: 'barn',+ enterable: true,+ footprint: { spanX: 8, spanZ: 6, units: 'm' },+ wallHeight: 3.2,+ scaleMode: 'realistic',+ roof: {+ type: 'gable',+ ridgeAxis: 'x',+ pitchDegrees: 35,+ overhang: 0.45,+ closedEnds: true,+ },+ portal: { width: 1.8, height: 2.5, depth: 0.2 },+ });+ expect(intent.architecture!.roof.rise).toBeCloseTo(Math.tan((35 * Math.PI) / 180) * 3);+ expect(intent.capabilities).toContain('enterable');+ expect(validateAssetIntentV1(intent)).toEqual({ valid: true, value: intent, issues: [] });+ });++ test('rejects inconsistent architecture geometry and category-specific fields on another category', () => {+ const architecture = createAssetIntentV1({ category: 'architecture' });+ const inconsistent = {+ ...architecture,+ architecture: {+ ...architecture.architecture!,+ roof: { ...architecture.architecture!.roof, rise: 99 },+ },+ };+ expect(validateAssetIntentV1(inconsistent).issues.map((issue) => issue.code)).toContain(+ 'ARCHITECTURE_ROOF_GEOMETRY_MISMATCH',+ );++ const propWithArchitecture = {+ ...createAssetIntentV1({ category: 'prop' }),+ architecture: architecture.architecture,+ };+ expect(validateAssetIntentV1(propWithArchitecture).issues.map((issue) => issue.code)).toContain(+ 'ARCHITECTURE_INTENT_CATEGORY_MISMATCH',+ );+ });++ test('rejects category/frame drift, invalid extents, and contradictory parts', () => {+ const value = {+ ...createAssetIntentV1({ category: 'architecture', requiredParts: ['roof'] }),+ category: 'building',+ frame: { ...KILN_ASSET_FRAME, forward: '+Z' },+ bounds: { x: -1, units: 'cm' },+ forbiddenExtras: ['roof'],+ };++ const result = validateAssetIntentV1(value);+ expect(result.valid).toBe(false);+ expect(result.issues.map((issue) => issue.code)).toEqual(+ expect.arrayContaining([+ 'INVALID_CATEGORY',+ 'FRAME_CONTRACT_MISMATCH',+ 'INVALID_UNITS',+ 'INVALID_BOUND_EXTENT',+ 'CONTRADICTORY_PART_REQUIREMENT',+ ]),+ );+ });++ test('rejects unknown and duplicate capabilities deterministically', () => {+ const value = {+ ...createAssetIntentV1({ category: 'environment' }),+ capabilities: ['tileable', 'tileable', 'telepathic'],+ };+ const result = validateAssetIntentV1(value);+ expect(result.issues.map((issue) => issue.code)).toEqual([+ 'DUPLICATE_VALUE',+ 'INVALID_CAPABILITY',+ ]);+ });+});diff --git a/src/contracts/asset.ts b/src/contracts/asset.tsnew file mode 100644index 00000000..bd955c2d--- /dev/null+++ b/src/contracts/asset.ts@@ -0,0 +1,1919 @@+/**+ * Stable, browser-safe contracts shared by every Kiln asset-generation surface.+ *+ * Keep this module dependency-free: Studio, workers, CLI consumers, and the+ * engine must all be able to import the same values without pulling in Three,+ * Node APIs, or a model-provider SDK.+ */++import {+ ASSET_SCOPES,+ KILN_DEFAULT_MODULAR_GRID,+ VFX_SUBTYPES,+ validateVfxIntentV1,+ type AssetScopeIntentV1,+ type ModularIntentV1,+ type ModularIntentV1Input,+ type VfxIntentV1,+ type VfxIntentV1Input,+ type VfxSubtype,+} from './breadth';++export const KILN_ASSET_FRAME = Object.freeze({+ units: 'm',+ forward: '+X',+ up: '+Y',+ right: '+Z',+ groundY: 0,+} as const);++export type AssetFrameContract = typeof KILN_ASSET_FRAME;++export const ASSET_CATEGORIES = [+ 'prop',+ 'character',+ 'vfx',+ 'environment',+ 'architecture',+ 'vegetation',+ 'vehicle',+] as const;++export type AssetCategory = (typeof ASSET_CATEGORIES)[number];++export function isAssetCategory(value: unknown): value is AssetCategory {+ return typeof value === 'string' && (ASSET_CATEGORIES as readonly string[]).includes(value);+}++export const ASSET_CAPABILITIES = [+ 'enterable',+ 'articulated',+ 'driveable',+ 'tileable',+ 'transparentSurface',+ 'runtimeShader',+ 'grounded',+ 'openable',+ 'navigable',+ 'skinned',+ /** Trusted consumer requires TANGENT accessors instead of deriving them at load time. */+ 'precomputedTangents',+] as const;++export type AssetCapability = (typeof ASSET_CAPABILITIES)[number];++export const MATERIAL_INTENT_MODES = [+ 'flatOptimized',+ 'pbrRecipe',+ 'texturedHero',+ 'runtimeTsl',+] as const;++export type MaterialIntentMode = (typeof MATERIAL_INTENT_MODES)[number];++export const MATERIAL_TRANSPARENCY_MODES = ['opaque', 'mask', 'blend'] as const;+export type MaterialTransparencyMode = (typeof MATERIAL_TRANSPARENCY_MODES)[number];++export interface AssetBoundsV1 {+ /** Requested width/length along the engine's forward axis, in meters. */+ x?: number;+ /** Requested height along the engine's up axis, in meters. */+ y?: number;+ /** Requested width along the engine's right axis, in meters. */+ z?: number;+ units: 'm';+}++export interface MaterialIntentV1 {+ /** Portable standard-glTF PBR is the default authoring path. */+ mode: MaterialIntentMode;+ recipeId?: string;+ paletteId?: string;+ transparency?: MaterialTransparencyMode;+}++export interface AnimationIntentV1 {+ /** Exact clip names required by trusted user/product intent. */+ clips: string[];+ locomotionDirection?: '+X';+ rootMotion?: 'inPlace' | 'forward';+ loop?: boolean;+ gait?: string;+}++export const CHARACTER_BODY_PLANS = [+ 'biped',+ 'quadruped',+ 'avian',+ 'serpentine',+ 'multi-limb',+ 'wheeled',+ 'custom',+] as const;+export type CharacterBodyPlan = (typeof CHARACTER_BODY_PLANS)[number];++export const CHARACTER_LOCOMOTION_MODES = [+ 'stationary',+ 'walk',+ 'run',+ 'fly',+ 'swim',+ 'slither',+ 'roll',+ 'custom',+] as const;+export type CharacterLocomotionMode = (typeof CHARACTER_LOCOMOTION_MODES)[number];+export type CharacterClipPlayback = 'loop' | 'oneShot';++export interface CharacterClipIntentV1 {+ name: string;+ playback: CharacterClipPlayback;+}++export interface CharacterHeldItemIntentV1 {+ required: boolean;+ /** Semantic end-effector role, not a model-authored node name. */+ attachmentRole: string;+}++/** Trusted, body-plan-specific requirements for character generation and QA. */+export interface CharacterIntentV1 {+ bodyPlan: CharacterBodyPlan;+ grounded: boolean;+ locomotion: CharacterLocomotionMode;+ gait: string;+ rootMotion: 'inPlace' | 'forward';+ clips: CharacterClipIntentV1[];+ heldItem: CharacterHeldItemIntentV1;+}++export interface CharacterIntentV1Input {+ bodyPlan?: CharacterBodyPlan;+ grounded?: boolean;+ locomotion?: CharacterLocomotionMode;+ gait?: string;+ rootMotion?: 'inPlace' | 'forward';+ clips?: readonly CharacterClipIntentV1[];+ heldItem?: Partial<CharacterHeldItemIntentV1>;+}++export const VEHICLE_SUBTYPES = [+ 'wheeled',+ 'tracked',+ 'rail',+ 'watercraft',+ 'fixed-wing',+ 'rotorcraft',+ 'hover',+ 'walking',+ 'custom',+] as const;+export type VehicleSubtype = (typeof VEHICLE_SUBTYPES)[number];++export const VEHICLE_STEERING_ARRANGEMENTS = [+ 'none',+ 'front',+ 'rear',+ 'all',+ 'articulated',+ 'custom',+] as const;+export type VehicleSteeringArrangement = (typeof VEHICLE_STEERING_ARRANGEMENTS)[number];++export const VEHICLE_SUPPORT_POLICIES = ['grounded', 'waterborne', 'airborne'] as const;+export type VehicleSupportPolicy = (typeof VEHICLE_SUPPORT_POLICIES)[number];++/** Trusted subtype requirements; non-wheeled subtypes deliberately normalize to zero wheels. */+export interface VehicleIntentV1 {+ subtype: VehicleSubtype;+ supportAssemblies: string[];+ propulsionAssemblies: string[];+ wheelCount: number;+ axleCount: number;+ steering: VehicleSteeringArrangement;+ supportPolicy: VehicleSupportPolicy;+ animationAssemblies: string[];+}++export interface VehicleIntentV1Input {+ subtype?: VehicleSubtype;+ supportAssemblies?: readonly string[];+ propulsionAssemblies?: readonly string[];+ wheelCount?: number;+ axleCount?: number;+ steering?: VehicleSteeringArrangement;+ supportPolicy?: VehicleSupportPolicy;+ animationAssemblies?: readonly string[];+}++export const ARCHITECTURE_ROOF_TYPES = ['gable', 'shed', 'hip', 'flat', 'none', 'custom'] as const;+export type ArchitectureRoofType = (typeof ARCHITECTURE_ROOF_TYPES)[number];++export const ARCHITECTURE_SCALE_MODES = ['realistic', 'stylized'] as const;+export type ArchitectureScaleMode = (typeof ARCHITECTURE_SCALE_MODES)[number];++export interface ArchitectureFootprintV1 {+ spanX: number;+ spanZ: number;+ units: 'm';+}++export interface ArchitecturePortalV1 {+ /** Clear opening width along the wall, in meters. */+ width: number;+ /** Clear opening height above its threshold, in meters. */+ height: number;+ /** Clear passage depth through the wall, in meters. */+ depth: number;+}++export interface ArchitectureRoofIntentV1 {+ type: ArchitectureRoofType;+ ridgeAxis: 'x' | 'z';+ /** Ridge rise above the wall bearing line, in meters. */+ rise: number;+ /** Pitch measured from horizontal, in degrees. */+ pitchDegrees: number;+ /** Horizontal projection beyond each footprint edge, in meters. */+ overhang: number;+ /** Whether roof end planes requested by the profile must be closed. */+ closedEnds: boolean;+}++/** Trusted, category-specific architecture requirements. */+export interface ArchitectureIntentV1 {+ subtype: string;+ enterable: boolean;+ footprint: ArchitectureFootprintV1;+ wallHeight: number;+ scaleMode: ArchitectureScaleMode;+ roof: ArchitectureRoofIntentV1;+ /** Requested exterior-to-interior clearance when `enterable` is true. */+ portal?: ArchitecturePortalV1;+}++export interface ArchitectureIntentV1Input {+ subtype?: string;+ enterable?: boolean;+ footprint?: Partial<Omit<ArchitectureFootprintV1, 'units'>> & { units?: 'm' };+ wallHeight?: number;+ scaleMode?: ArchitectureScaleMode;+ roof?: Partial<ArchitectureRoofIntentV1>;+ portal?: Partial<ArchitecturePortalV1>;+}++export const VEGETATION_SUBTYPES = [+ 'tree',+ 'conifer',+ 'shrub',+ 'grass',+ 'frond/palm',+ 'vine',+ 'crop/flower',+ 'succulent',+ 'fungus',+ 'aquatic',+ 'bare/dead',+ 'custom',+] as const;+export type VegetationSubtype = (typeof VEGETATION_SUBTYPES)[number];++export const VEGETATION_GROWTH_STATES = ['lush', 'sparse', 'bare'] as const;+export type VegetationGrowthState = (typeof VEGETATION_GROWTH_STATES)[number];++export const VEGETATION_CANOPY_PROFILES = ['broadleaf', 'conifer', 'topiary', 'bare/dead'] as const;+export type VegetationCanopyProfile = (typeof VEGETATION_CANOPY_PROFILES)[number];++/** Trusted vegetation construction choices resolved before model execution. */+export interface VegetationIntentV1 {+ subtype: VegetationSubtype;+ growthState: VegetationGrowthState;+ canopyProfile: VegetationCanopyProfile;+ /** Standalone assets own one ground contact and exclude unrequested dressing. */+ standalone: boolean;+ grounded: boolean;+}++export interface VegetationIntentV1Input {+ subtype?: VegetationSubtype;+ growthState?: VegetationGrowthState;+ canopyProfile?: VegetationCanopyProfile;+ standalone?: boolean;+ grounded?: boolean;+}++export interface AssetIntentV1 {+ schemaVersion: 1;+ /** Closure-owned; model-authored metadata cannot replace this value. */+ category: AssetCategory;+ /** Category-specific profile selector, without expanding the top-level taxonomy. */+ subtype?: string;+ /** Required normalized scope; defaults are explicit and never inferred from model source. */+ scope: AssetScopeIntentV1;+ capabilities: AssetCapability[];+ bounds?: AssetBoundsV1;+ frame: AssetFrameContract;+ requiredParts: string[];+ forbiddenExtras: string[];+ material: MaterialIntentV1;+ animation?: AnimationIntentV1;+ /** Present exactly when `category === 'architecture'`. */+ architecture?: ArchitectureIntentV1;+ /** Present exactly when `category === 'character'`. */+ character?: CharacterIntentV1;+ /** Present exactly when `category === 'vehicle'`. */+ vehicle?: VehicleIntentV1;+ /** Present exactly when `category === 'vegetation'`. */+ vegetation?: VegetationIntentV1;+ /** Present exactly when `category === 'vfx'`. */+ vfx?: VfxIntentV1;+ /** Present exactly when scope is modularSet; grid comes from trusted request/defaults. */+ modular?: ModularIntentV1;+ qaProfile: string;+}++export type AssetIntentV1Input = Omit<+ AssetIntentV1,+ | 'schemaVersion'+ | 'frame'+ | 'capabilities'+ | 'requiredParts'+ | 'forbiddenExtras'+ | 'material'+ | 'architecture'+ | 'character'+ | 'vehicle'+ | 'vegetation'+ | 'vfx'+ | 'modular'+ | 'scope'+ | 'qaProfile'+> & {+ capabilities?: readonly AssetCapability[];+ requiredParts?: readonly string[];+ forbiddenExtras?: readonly string[];+ material?: Partial<MaterialIntentV1>;+ architecture?: ArchitectureIntentV1Input;+ character?: CharacterIntentV1Input;+ vehicle?: VehicleIntentV1Input;+ vegetation?: VegetationIntentV1Input;+ vfx?: VfxIntentV1Input;+ modular?: ModularIntentV1Input;+ scope?: Partial<Omit<AssetScopeIntentV1, 'schemaVersion'>>;+ qaProfile?: string;+};++export interface ContractValidationIssue {+ code: string;+ path: string;+ message: string;+}++export interface ContractValidationResult<T> {+ valid: boolean;+ value?: T;+ issues: ContractValidationIssue[];+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const isNonEmptyString = (value: unknown): value is string =>+ typeof value === 'string' && value.trim().length > 0;++const isEnumValue = <T extends readonly string[]>(values: T, value: unknown): value is T[number] =>+ typeof value === 'string' && (values as readonly string[]).includes(value);++function pushStringArrayIssues(+ issues: ContractValidationIssue[],+ value: unknown,+ path: string,+): value is string[] {+ if (!Array.isArray(value)) {+ issues.push({ code: 'EXPECTED_ARRAY', path, message: `${path} must be an array.` });+ return false;+ }+ const seen = new Set<string>();+ let valid = true;+ for (let i = 0; i < value.length; i++) {+ const item = value[i];+ if (!isNonEmptyString(item)) {+ issues.push({+ code: 'EXPECTED_NONEMPTY_STRING',+ path: `${path}[${i}]`,+ message: `${path}[${i}] must be a non-empty string.`,+ });+ valid = false;+ continue;+ }+ if (seen.has(item)) {+ issues.push({+ code: 'DUPLICATE_VALUE',+ path: `${path}[${i}]`,+ message: `${path} contains duplicate value ${JSON.stringify(item)}.`,+ });+ valid = false;+ }+ seen.add(item);+ }+ return valid;+}++function validateFrame(+ value: unknown,+ issues: ContractValidationIssue[],+): value is AssetFrameContract {+ if (!isRecord(value)) {+ issues.push({ code: 'INVALID_FRAME', path: 'frame', message: 'frame must be an object.' });+ return false;+ }+ let valid = true;+ for (const [key, expected] of Object.entries(KILN_ASSET_FRAME)) {+ if (value[key] !== expected) {+ issues.push({+ code: 'FRAME_CONTRACT_MISMATCH',+ path: `frame.${key}`,+ message: `frame.${key} must be ${JSON.stringify(expected)}.`,+ });+ valid = false;+ }+ }+ return valid;+}++function validateBounds(value: unknown, issues: ContractValidationIssue[]): value is AssetBoundsV1 {+ if (!isRecord(value)) {+ issues.push({ code: 'INVALID_BOUNDS', path: 'bounds', message: 'bounds must be an object.' });+ return false;+ }+ let valid = true;+ if (value.units !== 'm') {+ issues.push({+ code: 'INVALID_UNITS',+ path: 'bounds.units',+ message: 'bounds.units must be "m".',+ });+ valid = false;+ }+ for (const axis of ['x', 'y', 'z'] as const) {+ const extent = value[axis];+ if (+ extent !== undefined &&+ (typeof extent !== 'number' || !Number.isFinite(extent) || extent <= 0)+ ) {+ issues.push({+ code: 'INVALID_BOUND_EXTENT',+ path: `bounds.${axis}`,+ message: `bounds.${axis} must be a finite number greater than zero.`,+ });+ valid = false;+ }+ }+ return valid;+}++function validateScope(+ value: unknown,+ issues: ContractValidationIssue[],+): value is AssetScopeIntentV1 {+ if (!isRecord(value)) {+ issues.push({+ code: 'INVALID_ASSET_SCOPE',+ path: 'scope',+ message: 'scope must be a normalized AssetScopeIntentV1 object.',+ });+ return false;+ }+ let valid = true;+ if (value.schemaVersion !== 1) {+ issues.push({+ code: 'INVALID_ASSET_SCOPE_VERSION',+ path: 'scope.schemaVersion',+ message: 'scope.schemaVersion must be 1.',+ });+ valid = false;+ }+ if (!isEnumValue(ASSET_SCOPES, value.scope)) {+ issues.push({+ code: 'INVALID_ASSET_SCOPE_KIND',+ path: 'scope.scope',+ message: `scope.scope must be one of ${ASSET_SCOPES.join(', ')}.`,+ });+ valid = false;+ }+ if (typeof value.explicit !== 'boolean') {+ issues.push({+ code: 'INVALID_ASSET_SCOPE_EXPLICIT',+ path: 'scope.explicit',+ message: 'scope.explicit must be boolean.',+ });+ valid = false;+ }+ return valid;+}++function validateModularIntent(+ value: unknown,+ issues: ContractValidationIssue[],+): value is ModularIntentV1 {+ if (!isRecord(value)) {+ issues.push({+ code: 'INVALID_MODULAR_INTENT',+ path: 'modular',+ message: 'modular must be a trusted ModularIntentV1 object for modularSet scope.',+ });+ return false;+ }+ let valid = true;+ if (value.schemaVersion !== 1) {+ issues.push({+ code: 'INVALID_MODULAR_INTENT_VERSION',+ path: 'modular.schemaVersion',+ message: 'modular.schemaVersion must be 1.',+ });+ valid = false;+ }+ if (value.units !== 'm') {+ issues.push({+ code: 'INVALID_MODULAR_UNITS',+ path: 'modular.units',+ message: 'modular.units must be meters.',+ });+ valid = false;+ }+ if (+ !Array.isArray(value.grid) ||+ value.grid.length !== 3 ||+ value.grid.some(+ (component) => typeof component !== 'number' || !Number.isFinite(component) || component <= 0,+ )+ ) {+ issues.push({+ code: 'INVALID_MODULAR_GRID',+ path: 'modular.grid',+ message: 'modular.grid must contain three positive finite meter steps.',+ });+ valid = false;+ }+ return valid;+}++function validateMaterial(+ value: unknown,+ issues: ContractValidationIssue[],+): value is MaterialIntentV1 {+ if (!isRecord(value)) {+ issues.push({+ code: 'INVALID_MATERIAL_INTENT',+ path: 'material',+ message: 'material must be an object.',+ });+ return false;+ }+ let valid = true;+ if (!isEnumValue(MATERIAL_INTENT_MODES, value.mode)) {+ issues.push({+ code: 'INVALID_MATERIAL_MODE',+ path: 'material.mode',+ message: `material.mode must be one of ${MATERIAL_INTENT_MODES.join(', ')}.`,+ });+ valid = false;+ }+ if (value.recipeId !== undefined && !isNonEmptyString(value.recipeId)) {+ issues.push({+ code: 'INVALID_RECIPE_ID',+ path: 'material.recipeId',+ message: 'material.recipeId must be a non-empty string.',+ });+ valid = false;+ }+ if (value.paletteId !== undefined && !isNonEmptyString(value.paletteId)) {+ issues.push({+ code: 'INVALID_PALETTE_ID',+ path: 'material.paletteId',+ message: 'material.paletteId must be a non-empty string.',+ });+ valid = false;+ }+ if (+ value.transparency !== undefined &&+ !isEnumValue(MATERIAL_TRANSPARENCY_MODES, value.transparency)+ ) {+ issues.push({+ code: 'INVALID_TRANSPARENCY_MODE',+ path: 'material.transparency',+ message: `material.transparency must be one of ${MATERIAL_TRANSPARENCY_MODES.join(', ')}.`,+ });+ valid = false;+ }+ return valid;+}++function validateAnimation(+ value: unknown,+ issues: ContractValidationIssue[],+): value is AnimationIntentV1 {+ if (!isRecord(value)) {+ issues.push({+ code: 'INVALID_ANIMATION_INTENT',+ path: 'animation',+ message: 'animation must be an object.',+ });+ return false;+ }+ let valid = pushStringArrayIssues(issues, value.clips, 'animation.clips');+ if (value.locomotionDirection !== undefined && value.locomotionDirection !== '+X') {+ issues.push({+ code: 'INVALID_LOCOMOTION_DIRECTION',+ path: 'animation.locomotionDirection',+ message: 'animation.locomotionDirection must be "+X".',+ });+ valid = false;+ }+ if (+ value.rootMotion !== undefined &&+ value.rootMotion !== 'inPlace' &&+ value.rootMotion !== 'forward'+ ) {+ issues.push({+ code: 'INVALID_ROOT_MOTION',+ path: 'animation.rootMotion',+ message: 'animation.rootMotion must be "inPlace" or "forward".',+ });+ valid = false;+ }+ if (value.loop !== undefined && typeof value.loop !== 'boolean') {+ issues.push({+ code: 'INVALID_LOOP_POLICY',+ path: 'animation.loop',+ message: 'animation.loop must be boolean.',+ });+ valid = false;+ }+ if (value.gait !== undefined && !isNonEmptyString(value.gait)) {+ issues.push({+ code: 'INVALID_GAIT',+ path: 'animation.gait',+ message: 'animation.gait must be a non-empty string.',+ });+ valid = false;+ }+ return valid;+}++function validateCharacter(+ value: unknown,+ issues: ContractValidationIssue[],+): value is CharacterIntentV1 {+ if (!isRecord(value)) {+ issues.push({+ code: 'INVALID_CHARACTER_INTENT',+ path: 'character',+ message: 'character must be an object for character assets.',+ });+ return false;+ }++ let valid = true;+ if (!isEnumValue(CHARACTER_BODY_PLANS, value.bodyPlan)) {+ issues.push({+ code: 'INVALID_CHARACTER_BODY_PLAN',+ path: 'character.bodyPlan',+ message: `character.bodyPlan must be one of ${CHARACTER_BODY_PLANS.join(', ')}.`,+ });+ valid = false;+ }+ if (typeof value.grounded !== 'boolean') {+ issues.push({+ code: 'INVALID_CHARACTER_GROUNDED',+ path: 'character.grounded',+ message: 'character.grounded must be boolean.',+ });+ valid = false;+ }+ if (!isEnumValue(CHARACTER_LOCOMOTION_MODES, value.locomotion)) {+ issues.push({+ code: 'INVALID_CHARACTER_LOCOMOTION',+ path: 'character.locomotion',+ message: `character.locomotion must be one of ${CHARACTER_LOCOMOTION_MODES.join(', ')}.`,+ });+ valid = false;+ }+ if (!isNonEmptyString(value.gait)) {+ issues.push({+ code: 'INVALID_CHARACTER_GAIT',+ path: 'character.gait',+ message: 'character.gait must be a non-empty string.',+ });+ valid = false;+ }+ if (value.rootMotion !== 'inPlace' && value.rootMotion !== 'forward') {+ issues.push({+ code: 'INVALID_CHARACTER_ROOT_MOTION',+ path: 'character.rootMotion',+ message: 'character.rootMotion must be "inPlace" or "forward".',+ });+ valid = false;+ }+ if (!Array.isArray(value.clips)) {+ issues.push({+ code: 'INVALID_CHARACTER_CLIPS',+ path: 'character.clips',+ message: 'character.clips must be an array.',+ });+ valid = false;+ } else {+ const names = new Set<string>();+ for (let i = 0; i < value.clips.length; i++) {+ const clip = value.clips[i];+ if (!isRecord(clip) || !isNonEmptyString(clip.name)) {+ issues.push({+ code: 'INVALID_CHARACTER_CLIP',+ path: `character.clips[${i}]`,+ message: 'Each character clip requires a non-empty name.',+ });+ valid = false;+ continue;+ }+ if (names.has(clip.name)) {+ issues.push({+ code: 'DUPLICATE_VALUE',+ path: `character.clips[${i}].name`,+ message: `character.clips contains duplicate name ${JSON.stringify(clip.name)}.`,+ });+ valid = false;+ }+ names.add(clip.name);+ if (clip.playback !== 'loop' && clip.playback !== 'oneShot') {+ issues.push({+ code: 'INVALID_CHARACTER_CLIP_PLAYBACK',+ path: `character.clips[${i}].playback`,+ message: 'Character clip playback must be "loop" or "oneShot".',+ });+ valid = false;+ }+ }+ }+ if (!isRecord(value.heldItem)) {+ issues.push({+ code: 'INVALID_CHARACTER_HELD_ITEM',+ path: 'character.heldItem',+ message: 'character.heldItem must be an object.',+ });+ valid = false;+ } else {+ if (typeof value.heldItem.required !== 'boolean') {+ issues.push({+ code: 'INVALID_CHARACTER_HELD_ITEM_REQUIRED',+ path: 'character.heldItem.required',+ message: 'character.heldItem.required must be boolean.',+ });+ valid = false;+ }+ if (!isNonEmptyString(value.heldItem.attachmentRole)) {+ issues.push({+ code: 'INVALID_CHARACTER_ATTACHMENT_ROLE',+ path: 'character.heldItem.attachmentRole',+ message: 'character.heldItem.attachmentRole must be a non-empty semantic role.',+ });+ valid = false;+ }+ }+ return valid;+}++function validateNonNegativeInteger(+ value: unknown,+ path: string,+ issues: ContractValidationIssue[],+): value is number {+ if (typeof value === 'number' && Number.isInteger(value) && value >= 0) return true;+ issues.push({+ code: 'INVALID_NONNEGATIVE_INTEGER',+ path,+ message: `${path} must be a non-negative integer.`,+ });+ return false;+}++function validateVehicle(+ value: unknown,+ issues: ContractValidationIssue[],+): value is VehicleIntentV1 {+ if (!isRecord(value)) {+ issues.push({+ code: 'INVALID_VEHICLE_INTENT',+ path: 'vehicle',+ message: 'vehicle must be an object for vehicle assets.',+ });+ return false;+ }+ let valid = true;+ if (!isEnumValue(VEHICLE_SUBTYPES, value.subtype)) {+ issues.push({+ code: 'INVALID_VEHICLE_SUBTYPE',+ path: 'vehicle.subtype',+ message: `vehicle.subtype must be one of ${VEHICLE_SUBTYPES.join(', ')}.`,+ });+ valid = false;+ }+ valid =+ pushStringArrayIssues(issues, value.supportAssemblies, 'vehicle.supportAssemblies') && valid;+ valid =+ pushStringArrayIssues(issues, value.propulsionAssemblies, 'vehicle.propulsionAssemblies') &&+ valid;+ valid = validateNonNegativeInteger(value.wheelCount, 'vehicle.wheelCount', issues) && valid;+ valid = validateNonNegativeInteger(value.axleCount, 'vehicle.axleCount', issues) && valid;+ if (!isEnumValue(VEHICLE_STEERING_ARRANGEMENTS, value.steering)) {+ issues.push({+ code: 'INVALID_VEHICLE_STEERING',+ path: 'vehicle.steering',+ message: `vehicle.steering must be one of ${VEHICLE_STEERING_ARRANGEMENTS.join(', ')}.`,+ });+ valid = false;+ }+ if (!isEnumValue(VEHICLE_SUPPORT_POLICIES, value.supportPolicy)) {+ issues.push({+ code: 'INVALID_VEHICLE_SUPPORT_POLICY',+ path: 'vehicle.supportPolicy',+ message: `vehicle.supportPolicy must be one of ${VEHICLE_SUPPORT_POLICIES.join(', ')}.`,+ });+ valid = false;+ }+ valid =+ pushStringArrayIssues(issues, value.animationAssemblies, 'vehicle.animationAssemblies') &&+ valid;+ if (value.subtype === 'watercraft' && value.wheelCount !== 0) {+ issues.push({+ code: 'VEHICLE_WHEEL_POLICY_MISMATCH',+ path: 'vehicle.wheelCount',+ message: 'Watercraft must not inherit wheeled-vehicle wheel rules.',+ });+ valid = false;+ }+ if (value.subtype === 'wheeled' && value.wheelCount === 0) {+ issues.push({+ code: 'VEHICLE_WHEEL_POLICY_MISMATCH',+ path: 'vehicle.wheelCount',+ message: 'wheeled vehicles require a positive wheel count.',+ });+ valid = false;+ }+ if (typeof value.wheelCount === 'number' && typeof value.axleCount === 'number') {+ if (value.axleCount > value.wheelCount) {+ issues.push({+ code: 'VEHICLE_AXLE_COUNT_MISMATCH',+ path: 'vehicle.axleCount',+ message: 'vehicle.axleCount cannot exceed vehicle.wheelCount.',+ });+ valid = false;+ }+ }+ return valid;+}++function validateVegetation(+ value: unknown,+ issues: ContractValidationIssue[],+): value is VegetationIntentV1 {+ if (!isRecord(value)) {+ issues.push({+ code: 'INVALID_VEGETATION_INTENT',+ path: 'vegetation',+ message: 'vegetation must be an object for vegetation assets.',+ });+ return false;+ }+ let valid = true;+ if (!isEnumValue(VEGETATION_SUBTYPES, value.subtype)) {+ issues.push({+ code: 'INVALID_VEGETATION_SUBTYPE',+ path: 'vegetation.subtype',+ message: `vegetation.subtype must be one of ${VEGETATION_SUBTYPES.join(', ')}.`,+ });+ valid = false;+ }+ if (!isEnumValue(VEGETATION_GROWTH_STATES, value.growthState)) {+ issues.push({+ code: 'INVALID_VEGETATION_GROWTH_STATE',+ path: 'vegetation.growthState',+ message: `vegetation.growthState must be one of ${VEGETATION_GROWTH_STATES.join(', ')}.`,+ });+ valid = false;+ }+ if (!isEnumValue(VEGETATION_CANOPY_PROFILES, value.canopyProfile)) {+ issues.push({+ code: 'INVALID_VEGETATION_CANOPY_PROFILE',+ path: 'vegetation.canopyProfile',+ message: `vegetation.canopyProfile must be one of ${VEGETATION_CANOPY_PROFILES.join(', ')}.`,+ });+ valid = false;+ }+ for (const property of ['standalone', 'grounded'] as const) {+ if (typeof value[property] !== 'boolean') {+ issues.push({+ code: 'INVALID_VEGETATION_BOOLEAN',+ path: `vegetation.${property}`,+ message: `vegetation.${property} must be boolean.`,+ });+ valid = false;+ }+ }+ if (value.growthState === 'bare' && value.canopyProfile !== 'bare/dead') {+ issues.push({+ code: 'VEGETATION_BARE_PROFILE_MISMATCH',+ path: 'vegetation.canopyProfile',+ message: 'Bare vegetation must use the bare/dead canopy profile.',+ });+ valid = false;+ }+ return valid;+}++function validatePositiveMeter(+ value: unknown,+ path: string,+ issues: ContractValidationIssue[],+): value is number {+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) return true;+ issues.push({+ code: 'INVALID_ARCHITECTURE_DIMENSION',+ path,+ message: `${path} must be a finite number greater than zero meters.`,+ });+ return false;+}++function validateArchitecture(+ value: unknown,+ issues: ContractValidationIssue[],+): value is ArchitectureIntentV1 {+ if (!isRecord(value)) {+ issues.push({+ code: 'INVALID_ARCHITECTURE_INTENT',+ path: 'architecture',+ message: 'architecture must be an object for architecture assets.',+ });+ return false;+ }++ let valid = true;+ if (!isNonEmptyString(value.subtype)) {+ issues.push({+ code: 'INVALID_ARCHITECTURE_SUBTYPE',+ path: 'architecture.subtype',+ message: 'architecture.subtype must be a non-empty string.',+ });+ valid = false;+ }+ if (typeof value.enterable !== 'boolean') {+ issues.push({+ code: 'INVALID_ARCHITECTURE_ENTERABLE',+ path: 'architecture.enterable',+ message: 'architecture.enterable must be boolean.',+ });+ valid = false;+ }+ if (!isEnumValue(ARCHITECTURE_SCALE_MODES, value.scaleMode)) {+ issues.push({+ code: 'INVALID_ARCHITECTURE_SCALE_MODE',+ path: 'architecture.scaleMode',+ message: `architecture.scaleMode must be one of ${ARCHITECTURE_SCALE_MODES.join(', ')}.`,+ });+ valid = false;+ }+ valid = validatePositiveMeter(value.wallHeight, 'architecture.wallHeight', issues) && valid;++ if (!isRecord(value.footprint)) {+ issues.push({+ code: 'INVALID_ARCHITECTURE_FOOTPRINT',+ path: 'architecture.footprint',+ message: 'architecture.footprint must be an object.',+ });+ valid = false;+ } else {+ if (value.footprint.units !== 'm') {+ issues.push({+ code: 'INVALID_UNITS',+ path: 'architecture.footprint.units',+ message: 'architecture.footprint.units must be "m".',+ });+ valid = false;+ }+ valid =+ validatePositiveMeter(value.footprint.spanX, 'architecture.footprint.spanX', issues) && valid;+ valid =+ validatePositiveMeter(value.footprint.spanZ, 'architecture.footprint.spanZ', issues) && valid;+ }++ if (!isRecord(value.roof)) {+ issues.push({+ code: 'INVALID_ARCHITECTURE_ROOF',+ path: 'architecture.roof',+ message: 'architecture.roof must be an object.',+ });+ valid = false;+ } else {+ const roof = value.roof;+ if (!isEnumValue(ARCHITECTURE_ROOF_TYPES, roof.type)) {+ issues.push({+ code: 'INVALID_ARCHITECTURE_ROOF_TYPE',+ path: 'architecture.roof.type',+ message: `architecture.roof.type must be one of ${ARCHITECTURE_ROOF_TYPES.join(', ')}.`,+ });+ valid = false;+ }+ if (roof.ridgeAxis !== 'x' && roof.ridgeAxis !== 'z') {+ issues.push({+ code: 'INVALID_ARCHITECTURE_RIDGE_AXIS',+ path: 'architecture.roof.ridgeAxis',+ message: 'architecture.roof.ridgeAxis must be "x" or "z".',+ });+ valid = false;+ }+ const flat = roof.type === 'flat' || roof.type === 'none';+ if (+ typeof roof.rise !== 'number' ||+ !Number.isFinite(roof.rise) ||+ (flat ? roof.rise !== 0 : roof.rise <= 0)+ ) {+ issues.push({+ code: 'INVALID_ARCHITECTURE_ROOF_RISE',+ path: 'architecture.roof.rise',+ message: flat+ ? 'Flat or absent roofs must have zero rise.'+ : 'Pitched roofs must have a finite positive rise.',+ });+ valid = false;+ }+ if (+ typeof roof.pitchDegrees !== 'number' ||+ !Number.isFinite(roof.pitchDegrees) ||+ (flat ? roof.pitchDegrees !== 0 : roof.pitchDegrees <= 0 || roof.pitchDegrees >= 89)+ ) {+ issues.push({+ code: 'INVALID_ARCHITECTURE_ROOF_PITCH',+ path: 'architecture.roof.pitchDegrees',+ message: flat+ ? 'Flat or absent roofs must have zero pitch.'+ : 'Pitched roofs must have a pitch greater than 0 and less than 89 degrees.',+ });+ valid = false;+ }+ if (typeof roof.overhang !== 'number' || !Number.isFinite(roof.overhang) || roof.overhang < 0) {+ issues.push({+ code: 'INVALID_ARCHITECTURE_OVERHANG',+ path: 'architecture.roof.overhang',+ message: 'architecture.roof.overhang must be a finite non-negative number.',+ });+ valid = false;+ }+ if (typeof roof.closedEnds !== 'boolean') {+ issues.push({+ code: 'INVALID_ARCHITECTURE_CLOSED_ENDS',+ path: 'architecture.roof.closedEnds',+ message: 'architecture.roof.closedEnds must be boolean.',+ });+ valid = false;+ }++ if (+ !flat &&+ isRecord(value.footprint) &&+ typeof value.footprint.spanX === 'number' &&+ typeof value.footprint.spanZ === 'number' &&+ Number.isFinite(roof.rise as number) &&+ Number.isFinite(roof.pitchDegrees as number) &&+ (roof.ridgeAxis === 'x' || roof.ridgeAxis === 'z')+ ) {+ const run = (roof.ridgeAxis === 'x' ? value.footprint.spanZ : value.footprint.spanX) / 2;+ const expectedRise = Math.tan(THREE_DEGREES * (roof.pitchDegrees as number)) * run;+ const tolerance = Math.max(1e-6, Math.abs(expectedRise) * 1e-6);+ if (Math.abs((roof.rise as number) - expectedRise) > tolerance) {+ issues.push({+ code: 'ARCHITECTURE_ROOF_GEOMETRY_MISMATCH',+ path: 'architecture.roof',+ message:+ 'architecture.roof.rise and pitchDegrees disagree for the footprint and ridgeAxis.',+ });+ valid = false;+ }+ }+ }++ if (value.portal !== undefined) {+ if (!isRecord(value.portal)) {+ issues.push({+ code: 'INVALID_ARCHITECTURE_PORTAL',+ path: 'architecture.portal',+ message: 'architecture.portal must be an object.',+ });+ valid = false;+ } else {+ for (const dimension of ['width', 'height', 'depth'] as const) {+ valid =+ validatePositiveMeter(+ value.portal[dimension],+ `architecture.portal.${dimension}`,+ issues,+ ) && valid;+ }+ }+ }++ return valid;+}++const THREE_DEGREES = Math.PI / 180;++/** Validate untrusted JSON-like input without adding a runtime schema dependency. */+export function validateAssetIntentV1(value: unknown): ContractValidationResult<AssetIntentV1> {+ const issues: ContractValidationIssue[] = [];+ if (!isRecord(value)) {+ return {+ valid: false,+ issues: [{ code: 'EXPECTED_OBJECT', path: '', message: 'AssetIntentV1 must be an object.' }],+ };+ }++ if (value.schemaVersion !== 1) {+ issues.push({+ code: 'UNSUPPORTED_SCHEMA_VERSION',+ path: 'schemaVersion',+ message: 'schemaVersion must be 1.',+ });+ }+ if (!isEnumValue(ASSET_CATEGORIES, value.category)) {+ issues.push({+ code: 'INVALID_CATEGORY',+ path: 'category',+ message: `category must be one of ${ASSET_CATEGORIES.join(', ')}.`,+ });+ }+ if (value.subtype !== undefined && !isNonEmptyString(value.subtype)) {+ issues.push({+ code: 'INVALID_SUBTYPE',+ path: 'subtype',+ message: 'subtype must be a non-empty string.',+ });+ }++ if (Array.isArray(value.capabilities)) {+ const seen = new Set<string>();+ for (let i = 0; i < value.capabilities.length; i++) {+ const capability = value.capabilities[i];+ if (!isEnumValue(ASSET_CAPABILITIES, capability)) {+ issues.push({+ code: 'INVALID_CAPABILITY',+ path: `capabilities[${i}]`,+ message: `Unknown capability ${JSON.stringify(capability)}.`,+ });+ } else if (seen.has(capability)) {+ issues.push({+ code: 'DUPLICATE_VALUE',+ path: `capabilities[${i}]`,+ message: `capabilities contains duplicate value ${JSON.stringify(capability)}.`,+ });+ }+ if (typeof capability === 'string') seen.add(capability);+ }+ } else {+ issues.push({+ code: 'EXPECTED_ARRAY',+ path: 'capabilities',+ message: 'capabilities must be an array.',+ });+ }++ const requiredOk = pushStringArrayIssues(issues, value.requiredParts, 'requiredParts');+ const forbiddenOk = pushStringArrayIssues(issues, value.forbiddenExtras, 'forbiddenExtras');+ if (requiredOk && forbiddenOk) {+ const forbidden = new Set(value.forbiddenExtras as string[]);+ for (let i = 0; i < (value.requiredParts as string[]).length; i++) {+ const part = (value.requiredParts as string[])[i]!;+ if (forbidden.has(part)) {+ issues.push({+ code: 'CONTRADICTORY_PART_REQUIREMENT',+ path: `requiredParts[${i}]`,+ message: `${JSON.stringify(part)} cannot be both required and forbidden.`,+ });+ }+ }+ }++ validateFrame(value.frame, issues);+ validateScope(value.scope, issues);+ if (isRecord(value.scope) && value.scope.scope === 'modularSet') {+ validateModularIntent(value.modular, issues);+ } else if (value.modular !== undefined) {+ issues.push({+ code: 'MODULAR_INTENT_SCOPE_MISMATCH',+ path: 'modular',+ message: 'modular intent is allowed only when scope.scope is "modularSet".',+ });+ }+ if (value.bounds !== undefined) validateBounds(value.bounds, issues);+ validateMaterial(value.material, issues);+ if (value.animation !== undefined) validateAnimation(value.animation, issues);+ if (value.category === 'architecture') {+ validateArchitecture(value.architecture, issues);+ if (+ isRecord(value.architecture) &&+ isNonEmptyString(value.subtype) &&+ isNonEmptyString(value.architecture.subtype) &&+ value.subtype !== value.architecture.subtype+ ) {+ issues.push({+ code: 'ARCHITECTURE_SUBTYPE_MISMATCH',+ path: 'architecture.subtype',+ message: 'architecture.subtype must match the top-level subtype.',+ });+ }+ if (+ isRecord(value.architecture) &&+ typeof value.architecture.enterable === 'boolean' &&+ Array.isArray(value.capabilities) &&+ value.capabilities.includes('enterable') !== value.architecture.enterable+ ) {+ issues.push({+ code: 'ARCHITECTURE_ENTERABLE_CAPABILITY_MISMATCH',+ path: 'capabilities',+ message: 'The enterable capability must exactly match architecture.enterable.',+ });+ }+ } else if (value.architecture !== undefined) {+ issues.push({+ code: 'ARCHITECTURE_INTENT_CATEGORY_MISMATCH',+ path: 'architecture',+ message: 'architecture intent is allowed only when category is "architecture".',+ });+ }+ if (value.category === 'character') {+ validateCharacter(value.character, issues);+ if (+ isRecord(value.character) &&+ typeof value.character.grounded === 'boolean' &&+ Array.isArray(value.capabilities) &&+ value.capabilities.includes('grounded') !== value.character.grounded+ ) {+ issues.push({+ code: 'CHARACTER_GROUNDED_CAPABILITY_MISMATCH',+ path: 'capabilities',+ message: 'The grounded capability must exactly match character.grounded.',+ });+ }+ } else if (value.character !== undefined) {+ issues.push({+ code: 'CHARACTER_INTENT_CATEGORY_MISMATCH',+ path: 'character',+ message: 'character intent is allowed only when category is "character".',+ });+ }+ if (value.category === 'vehicle') {+ validateVehicle(value.vehicle, issues);+ if (+ isRecord(value.vehicle) &&+ isNonEmptyString(value.subtype) &&+ isEnumValue(VEHICLE_SUBTYPES, value.vehicle.subtype) &&+ value.subtype !== value.vehicle.subtype+ ) {+ issues.push({+ code: 'VEHICLE_SUBTYPE_MISMATCH',+ path: 'vehicle.subtype',+ message: 'vehicle.subtype must match the top-level subtype.',+ });+ }+ if (+ isRecord(value.vehicle) &&+ value.vehicle.supportPolicy === 'grounded' &&+ Array.isArray(value.capabilities) &&+ !value.capabilities.includes('grounded')+ ) {+ issues.push({+ code: 'VEHICLE_SUPPORT_CAPABILITY_MISMATCH',+ path: 'capabilities',+ message: 'Grounded vehicle support requires the grounded capability.',+ });+ }+ } else if (value.vehicle !== undefined) {+ issues.push({+ code: 'VEHICLE_INTENT_CATEGORY_MISMATCH',+ path: 'vehicle',+ message: 'vehicle intent is allowed only when category is "vehicle".',+ });+ }+ if (value.category === 'vegetation') {+ validateVegetation(value.vegetation, issues);+ if (+ isRecord(value.vegetation) &&+ isNonEmptyString(value.subtype) &&+ isEnumValue(VEGETATION_SUBTYPES, value.vegetation.subtype) &&+ value.subtype !== value.vegetation.subtype+ ) {+ issues.push({+ code: 'VEGETATION_SUBTYPE_MISMATCH',+ path: 'vegetation.subtype',+ message: 'vegetation.subtype must match the top-level subtype.',+ });+ }+ if (+ isRecord(value.vegetation) &&+ value.vegetation.grounded === true &&+ Array.isArray(value.capabilities) &&+ !value.capabilities.includes('grounded')+ ) {+ issues.push({+ code: 'VEGETATION_GROUNDED_CAPABILITY_MISMATCH',+ path: 'capabilities',+ message: 'Grounded vegetation requires the grounded capability.',+ });+ }+ } else if (value.vegetation !== undefined) {+ issues.push({+ code: 'VEGETATION_INTENT_CATEGORY_MISMATCH',+ path: 'vegetation',+ message: 'vegetation intent is allowed only when category is "vegetation".',+ });+ }+ if (value.category === 'vfx') {+ const result = validateVfxIntentV1(value.vfx);+ if (!result.valid) {+ issues.push(+ ...result.issues.map((issue) => ({+ code: issue.code,+ path: issue.path ? `vfx.${issue.path}` : 'vfx',+ message: issue.message,+ })),+ );+ }+ if (+ isRecord(value.vfx) &&+ isNonEmptyString(value.subtype) &&+ isEnumValue(VFX_SUBTYPES, value.vfx.subtype) &&+ value.subtype !== value.vfx.subtype+ ) {+ issues.push({+ code: 'VFX_SUBTYPE_MISMATCH',+ path: 'vfx.subtype',+ message: 'vfx.subtype must match the top-level subtype.',+ });+ }+ if (isRecord(value.vfx) && Array.isArray(value.capabilities)) {+ const transparent = value.vfx.transparency !== 'opaque';+ if (value.capabilities.includes('transparentSurface') !== transparent) {+ issues.push({+ code: 'VFX_TRANSPARENCY_CAPABILITY_MISMATCH',+ path: 'capabilities',+ message: 'transparentSurface must exactly match the normalized VFX transparency mode.',+ });+ }+ const sidecar = value.vfx.portability === 'sidecar';+ if (value.capabilities.includes('runtimeShader') !== sidecar) {+ issues.push({+ code: 'VFX_RUNTIME_CAPABILITY_MISMATCH',+ path: 'capabilities',+ message: 'runtimeShader must exactly match the normalized VFX portability mode.',+ });+ }+ }+ if (isRecord(value.vfx) && isRecord(value.material)) {+ if (value.material.transparency !== value.vfx.transparency) {+ issues.push({+ code: 'VFX_MATERIAL_TRANSPARENCY_MISMATCH',+ path: 'material.transparency',+ message: 'material.transparency must exactly match vfx.transparency.',+ });+ }+ if ((value.vfx.portability === 'sidecar') !== (value.material.mode === 'runtimeTsl')) {+ issues.push({+ code: 'VFX_MATERIAL_PORTABILITY_MISMATCH',+ path: 'material.mode',+ message: 'runtimeTsl is required exactly for sidecar VFX intent.',+ });+ }+ }+ } else if (value.vfx !== undefined) {+ issues.push({+ code: 'VFX_INTENT_CATEGORY_MISMATCH',+ path: 'vfx',+ message: 'vfx intent is allowed only when category is "vfx".',+ });+ }+ if (!isNonEmptyString(value.qaProfile)) {+ issues.push({+ code: 'INVALID_QA_PROFILE',+ path: 'qaProfile',+ message: 'qaProfile must be a non-empty string.',+ });+ }++ return issues.length === 0+ ? { valid: true, value: value as unknown as AssetIntentV1, issues }+ : { valid: false, issues };+}++export interface LegacyAssetIntentScopeMigrationResult+ extends ContractValidationResult<AssetIntentV1> {+ migratedScope: boolean;+}++/**+ * Add only the new scope default to a trusted legacy v1 request/persistence+ * payload. This does not invent category-specific contracts: an old VFX row+ * without `vfx` remains invalid for new-generation QA and should be surfaced as+ * legacy-unassessed by its persistence reader.+ */+export function migrateLegacyAssetIntentV1Scope(+ value: unknown,+): LegacyAssetIntentScopeMigrationResult {+ if (+ !isRecord(value) ||+ value.schemaVersion !== 1 ||+ !isEnumValue(ASSET_CATEGORIES, value.category) ||+ value.scope !== undefined+ ) {+ return { ...validateAssetIntentV1(value), migratedScope: false };+ }+ const candidate = {+ ...value,+ scope: normalizeAssetScope({+ category: value.category,+ ...(isNonEmptyString(value.subtype) ? { subtype: value.subtype } : {}),+ }),+ };+ return { ...validateAssetIntentV1(candidate), migratedScope: true };+}++export function isAssetIntentV1(value: unknown): value is AssetIntentV1 {+ return validateAssetIntentV1(value).valid;+}++function normalizeArchitectureIntent(input: AssetIntentV1Input): ArchitectureIntentV1 | undefined {+ if (input.category !== 'architecture' && input.architecture === undefined) return undefined;++ const architecture = input.architecture ?? {};+ const spanX = architecture.footprint?.spanX ?? input.bounds?.x ?? 4;+ const spanZ = architecture.footprint?.spanZ ?? input.bounds?.z ?? 4;+ const ridgeAxis = architecture.roof?.ridgeAxis ?? 'x';+ const roofType = architecture.roof?.type ?? 'gable';+ const flat = roofType === 'flat' || roofType === 'none';+ const halfRun = (ridgeAxis === 'x' ? spanZ : spanX) / 2;+ const suppliedRise = architecture.roof?.rise;+ const suppliedPitch = architecture.roof?.pitchDegrees;+ const pitchDegrees = flat+ ? (suppliedPitch ?? 0)+ : (suppliedPitch ??+ (suppliedRise !== undefined && halfRun > 0+ ? Math.atan2(suppliedRise, halfRun) / THREE_DEGREES+ : 30));+ const rise = flat+ ? (suppliedRise ?? 0)+ : (suppliedRise ?? Math.tan(pitchDegrees * THREE_DEGREES) * halfRun);+ const enterable = architecture.enterable ?? true;++ return {+ subtype: architecture.subtype ?? input.subtype ?? 'building',+ enterable,+ footprint: { spanX, spanZ, units: 'm' },+ wallHeight: architecture.wallHeight ?? input.bounds?.y ?? 2.8,+ scaleMode: architecture.scaleMode ?? 'realistic',+ roof: {+ type: roofType,+ ridgeAxis,+ rise,+ pitchDegrees,+ overhang: architecture.roof?.overhang ?? 0.3,+ closedEnds: architecture.roof?.closedEnds ?? true,+ },+ ...(architecture.portal || enterable+ ? {+ portal: {+ width: architecture.portal?.width ?? 1.1,+ height: architecture.portal?.height ?? 2.1,+ depth: architecture.portal?.depth ?? 0.15,+ },+ }+ : {}),+ };+}++const ONE_SHOT_CLIP = /(?:death|die|impact|hit|attack|jump|land|spawn|despawn|emote)/i;++function normalizeCharacterIntent(input: AssetIntentV1Input): CharacterIntentV1 | undefined {+ if (input.category !== 'character' && input.character === undefined) return undefined;+ const character = input.character ?? {};+ const requestedSubtype = input.subtype;+ const bodyPlan =+ character.bodyPlan ??+ (isEnumValue(CHARACTER_BODY_PLANS, requestedSubtype)+ ? requestedSubtype+ : requestedSubtype+ ? 'custom'+ : 'biped');+ const grounded = character.grounded ?? input.capabilities?.includes('grounded') ?? true;+ const defaultLocomotion: Record<CharacterBodyPlan, CharacterLocomotionMode> = {+ biped: 'walk',+ quadruped: 'walk',+ avian: grounded ? 'walk' : 'fly',+ serpentine: 'slither',+ 'multi-limb': 'walk',+ wheeled: 'roll',+ custom: 'custom',+ };+ const rootMotion = character.rootMotion ?? input.animation?.rootMotion ?? 'inPlace';+ const gait = character.gait ?? input.animation?.gait ?? defaultLocomotion[bodyPlan];+ const clips = character.clips+ ? character.clips.map((clip) => ({ name: clip.name, playback: clip.playback }))+ : (input.animation?.clips ?? []).map((name) => ({+ name,+ playback:+ input.animation?.loop === false || ONE_SHOT_CLIP.test(name)+ ? ('oneShot' as const)+ : ('loop' as const),+ }));+ return {+ bodyPlan,+ grounded,+ locomotion: character.locomotion ?? defaultLocomotion[bodyPlan],+ gait,+ rootMotion,+ clips,+ heldItem: {+ required: character.heldItem?.required ?? false,+ attachmentRole: character.heldItem?.attachmentRole ?? 'grip',+ },+ };+}++function inferVehicleSubtype(value: string | undefined): VehicleSubtype {+ if (isEnumValue(VEHICLE_SUBTYPES, value)) return value;+ if (value && /(?:car|truck|jeep|wagon|bike|bicycle|scooter|rover|buggy)/i.test(value)) {+ return 'wheeled';+ }+ return value ? 'custom' : 'wheeled';+}++const VEHICLE_DEFAULTS: Record<+ VehicleSubtype,+ Pick<+ VehicleIntentV1,+ | 'supportAssemblies'+ | 'propulsionAssemblies'+ | 'wheelCount'+ | 'axleCount'+ | 'steering'+ | 'supportPolicy'+ >+> = {+ wheeled: {+ supportAssemblies: ['wheel'],+ propulsionAssemblies: ['wheel'],+ wheelCount: 4,+ axleCount: 2,+ steering: 'front',+ supportPolicy: 'grounded',+ },+ tracked: {+ supportAssemblies: ['track'],+ propulsionAssemblies: ['track'],+ wheelCount: 0,+ axleCount: 0,+ steering: 'none',+ supportPolicy: 'grounded',+ },+ rail: {+ supportAssemblies: ['rail-wheel'],+ propulsionAssemblies: ['rail-wheel'],+ wheelCount: 0,+ axleCount: 0,+ steering: 'none',+ supportPolicy: 'grounded',+ },+ watercraft: {+ supportAssemblies: ['hull'],+ propulsionAssemblies: ['propeller'],+ wheelCount: 0,+ axleCount: 0,+ steering: 'rear',+ supportPolicy: 'waterborne',+ },+ 'fixed-wing': {+ supportAssemblies: ['landing-gear'],+ propulsionAssemblies: ['propeller'],+ wheelCount: 0,+ axleCount: 0,+ steering: 'front',+ supportPolicy: 'airborne',+ },+ rotorcraft: {+ supportAssemblies: ['landing-gear'],+ propulsionAssemblies: ['rotor'],+ wheelCount: 0,+ axleCount: 0,+ steering: 'none',+ supportPolicy: 'airborne',+ },+ hover: {+ supportAssemblies: ['hover-pad'],+ propulsionAssemblies: ['thruster'],+ wheelCount: 0,+ axleCount: 0,+ steering: 'custom',+ supportPolicy: 'airborne',+ },+ walking: {+ supportAssemblies: ['leg'],+ propulsionAssemblies: ['leg'],+ wheelCount: 0,+ axleCount: 0,+ steering: 'custom',+ supportPolicy: 'grounded',+ },+ custom: {+ supportAssemblies: ['support'],+ propulsionAssemblies: ['propulsion'],+ wheelCount: 0,+ axleCount: 0,+ steering: 'custom',+ supportPolicy: 'grounded',+ },+};++function normalizeVehicleIntent(input: AssetIntentV1Input): VehicleIntentV1 | undefined {+ if (input.category !== 'vehicle' && input.vehicle === undefined) return undefined;+ const vehicle = input.vehicle ?? {};+ const subtype = vehicle.subtype ?? inferVehicleSubtype(input.subtype);+ const defaults = VEHICLE_DEFAULTS[subtype];+ return {+ subtype,+ supportAssemblies: [...(vehicle.supportAssemblies ?? defaults.supportAssemblies)],+ propulsionAssemblies: [...(vehicle.propulsionAssemblies ?? defaults.propulsionAssemblies)],+ wheelCount: vehicle.wheelCount ?? defaults.wheelCount,+ axleCount: vehicle.axleCount ?? defaults.axleCount,+ steering: vehicle.steering ?? defaults.steering,+ supportPolicy: vehicle.supportPolicy ?? defaults.supportPolicy,+ animationAssemblies: [...(vehicle.animationAssemblies ?? [])],+ };+}++function inferVegetationSubtype(value: string | undefined): VegetationSubtype {+ if (isEnumValue(VEGETATION_SUBTYPES, value)) return value;+ if (!value) return 'tree';+ if (/(?:palm|frond|fern)/i.test(value)) return 'frond/palm';+ if (/(?:flower|crop|grain|wheat|corn)/i.test(value)) return 'crop/flower';+ if (/(?:dead|bare|snag)/i.test(value)) return 'bare/dead';+ if (/(?:pine|fir|spruce|conifer)/i.test(value)) return 'conifer';+ if (/(?:oak|tree|broadleaf)/i.test(value)) return 'tree';+ if (/(?:shrub|bush|hedge|topiary)/i.test(value)) return 'shrub';+ if (/(?:grass|reed|sedge)/i.test(value)) return 'grass';+ if (/(?:vine|ivy|liana)/i.test(value)) return 'vine';+ if (/(?:succulent|cactus|agave)/i.test(value)) return 'succulent';+ if (/(?:fungus|mushroom)/i.test(value)) return 'fungus';+ if (/(?:aquatic|lily|kelp|lotus)/i.test(value)) return 'aquatic';+ return 'custom';+}++function normalizeVegetationIntent(input: AssetIntentV1Input): VegetationIntentV1 | undefined {+ if (input.category !== 'vegetation' && input.vegetation === undefined) return undefined;+ const vegetation = input.vegetation ?? {};+ const subtype = vegetation.subtype ?? inferVegetationSubtype(input.subtype);+ const growthState = vegetation.growthState ?? (subtype === 'bare/dead' ? 'bare' : 'lush');+ const canopyProfile =+ growthState === 'bare'+ ? 'bare/dead'+ : (vegetation.canopyProfile ??+ (subtype === 'conifer'+ ? 'conifer'+ : /topiary/i.test(input.qaProfile ?? '')+ ? 'topiary'+ : 'broadleaf'));+ return {+ subtype,+ growthState,+ canopyProfile,+ standalone: vegetation.standalone ?? true,+ grounded: vegetation.grounded ?? true,+ };+}++function inferVfxSubtype(value: string | undefined): VfxSubtype {+ if (isEnumValue(VFX_SUBTYPES, value)) return value;+ if (!value) return 'billboard';+ if (/(?:beam|laser|ray)/i.test(value)) return 'beam';+ if (/(?:trail|streak)/i.test(value)) return 'trail';+ if (/(?:aura|halo|shield)/i.test(value)) return 'aura';+ if (/(?:portal|rift|gateway)/i.test(value)) return 'portal';+ if (/(?:impact|burst|hit|explosion)/i.test(value)) return 'impact';+ if (/(?:volume|fog|cloud)/i.test(value)) return 'volume-like';+ if (/(?:shader|tsl|procedural)/i.test(value)) return 'runtimeShader';+ return 'billboard';+}++function stableVfxSidecarId(subtype: VfxSubtype): string {+ return `kiln.vfx.${subtype.replace(/[^a-z0-9]+/gi, '-').toLowerCase()}.tsl.v1`;+}++function normalizeVfxIntent(input: AssetIntentV1Input): VfxIntentV1 | undefined {+ if (input.category !== 'vfx' && input.vfx === undefined) return undefined;+ const source = input.vfx ?? {};+ const subtype = source.subtype ?? inferVfxSubtype(input.subtype);+ const portability =+ source.portability ??+ (subtype === 'runtimeShader' ||+ input.material?.mode === 'runtimeTsl' ||+ input.capabilities?.includes('runtimeShader')+ ? 'sidecar'+ : 'portable');+ const transparency = source.transparency ?? input.material?.transparency ?? 'blend';+ // THREE.Sprite is Kiln's portable billboard primitive and implements full+ // spherical camera-facing. A Y-axis-only billboard requires an explicit+ // runtime contract; defaulting to it would make the normalized request+ // impossible for the canonical portable export path to satisfy.+ const facingMode =+ source.facing?.mode ?? (subtype === 'billboard' ? 'camera-spherical' : 'fixed');+ const requestedDriver = source.animation?.driver;+ const hasTopLevelClip = (input.animation?.clips.length ?? 0) > 0;+ const playback =+ source.animation?.playback ??+ (requestedDriver === 'clip' || requestedDriver === 'timeUniform' || hasTopLevelClip+ ? input.animation?.loop === false+ ? 'oneShot'+ : 'loop'+ : portability === 'sidecar'+ ? 'loop'+ : 'static');+ const driver =+ source.animation?.driver ??+ (playback === 'static' ? 'none' : portability === 'sidecar' ? 'timeUniform' : 'clip');+ const durationSeconds = source.animation?.durationSeconds ?? (playback === 'static' ? 0 : 1);+ const endpointBehavior =+ source.animation?.endpointBehavior ??+ (playback === 'static' ? 'none' : playback === 'loop' ? 'matchStart' : 'holdLast');+ const sidecar =+ portability === 'sidecar'+ ? {+ kind: 'tsl' as const,+ id: source.sidecar?.id ?? stableVfxSidecarId(subtype),+ version: source.sidecar?.version ?? '1.0.0',+ }+ : undefined;+ return {+ schemaVersion: 1,+ subtype,+ portability,+ transparency,+ doubleSided: source.doubleSided ?? true,+ facing: {+ source: source.facing?.source ?? (source.facing ? 'explicit' : 'inferred'),+ mode: facingMode,+ ...(source.facing?.normalAxis || facingMode !== 'none'+ ? { normalAxis: source.facing?.normalAxis ?? '+X' }+ : {}),+ ...(source.facing?.directionAxis || subtype === 'beam' || subtype === 'trail'+ ? { directionAxis: source.facing?.directionAxis ?? '+X' }+ : {}),+ },+ animation: {+ playback,+ durationSeconds,+ endpointBehavior,+ driver,+ ...(driver === 'clip'+ ? {+ clipName:+ source.animation?.clipName ??+ input.animation?.clips[0] ??+ `${subtype}.${playback === 'loop' ? 'loop' : 'one-shot'}`,+ }+ : {}),+ ...(driver === 'timeUniform'+ ? { timeUniformName: source.animation?.timeUniformName ?? 'kilnTimeSeconds' }+ : {}),+ },+ ...(sidecar ? { sidecar } : {}),+ };+}++function normalizeAssetScope(input: AssetIntentV1Input): AssetScopeIntentV1 {+ const inferred = /(?:^|[-_ ])modular(?:$|[-_ ])/i.test(input.subtype ?? '')+ ? 'modularSet'+ : input.category === 'environment' && /(?:cluster|set[-_ ]?dressing)/i.test(input.subtype ?? '')+ ? 'cluster'+ : 'single';+ return {+ schemaVersion: 1,+ scope: input.scope?.scope ?? inferred,+ explicit: input.scope?.explicit ?? false,+ };+}++function normalizeModularIntent(+ input: AssetIntentV1Input,+ scope: AssetScopeIntentV1,+): ModularIntentV1 | undefined {+ if (scope.scope !== 'modularSet' && input.modular === undefined) return undefined;+ const grid = input.modular?.grid ?? KILN_DEFAULT_MODULAR_GRID;+ return {+ schemaVersion: 1,+ units: 'm',+ grid: [grid[0], grid[1], grid[2]],+ };+}++/**+ * Create and validate closure-owned intent. Arrays are copied so callers cannot+ * mutate the trusted contract after it has entered an agent/tool closure.+ */+export function createAssetIntentV1(input: AssetIntentV1Input): AssetIntentV1 {+ const architecture = normalizeArchitectureIntent(input);+ const character = normalizeCharacterIntent(input);+ const vehicle = normalizeVehicleIntent(input);+ const vegetation = normalizeVegetationIntent(input);+ const vfx = normalizeVfxIntent(input);+ const scope = normalizeAssetScope(input);+ const modular = normalizeModularIntent(input, scope);+ const capabilities = [...(input.capabilities ?? [])];+ if (architecture?.enterable && !capabilities.includes('enterable'))+ capabilities.push('enterable');+ if (character?.grounded && !capabilities.includes('grounded')) capabilities.push('grounded');+ if (vehicle?.supportPolicy === 'grounded' && !capabilities.includes('grounded')) {+ capabilities.push('grounded');+ }+ if (vegetation?.grounded && !capabilities.includes('grounded')) capabilities.push('grounded');+ if (vfx && vfx.transparency !== 'opaque' && !capabilities.includes('transparentSurface')) {+ capabilities.push('transparentSurface');+ }+ if (vfx?.portability === 'sidecar' && !capabilities.includes('runtimeShader')) {+ capabilities.push('runtimeShader');+ }+ const intent: AssetIntentV1 = {+ schemaVersion: 1,+ category: input.category,+ ...(input.subtype ||+ architecture?.subtype ||+ vehicle?.subtype ||+ character?.bodyPlan ||+ vegetation?.subtype ||+ vfx?.subtype+ ? {+ subtype:+ (input.category === 'vehicle' ? vehicle?.subtype : undefined) ??+ (input.category === 'vegetation' ? vegetation?.subtype : undefined) ??+ (input.category === 'vfx' ? vfx?.subtype : undefined) ??+ input.subtype ??+ architecture?.subtype ??+ character?.bodyPlan,+ }+ : {}),+ scope,+ capabilities,+ ...(input.bounds+ ? {+ bounds: {+ ...(input.bounds.x !== undefined ? { x: input.bounds.x } : {}),+ ...(input.bounds.y !== undefined ? { y: input.bounds.y } : {}),+ ...(input.bounds.z !== undefined ? { z: input.bounds.z } : {}),+ units: 'm',+ },+ }+ : {}),+ frame: KILN_ASSET_FRAME,+ requiredParts: [...(input.requiredParts ?? [])],+ forbiddenExtras: [...(input.forbiddenExtras ?? [])],+ material: {+ mode: input.material?.mode ?? (vfx?.portability === 'sidecar' ? 'runtimeTsl' : 'pbrRecipe'),+ ...(input.material?.recipeId ? { recipeId: input.material.recipeId } : {}),+ ...(input.material?.paletteId ? { paletteId: input.material.paletteId } : {}),+ ...(input.material?.transparency || vfx?.transparency+ ? { transparency: input.material?.transparency ?? vfx?.transparency }+ : {}),+ },+ ...(input.animation+ ? {+ animation: {+ clips: [...input.animation.clips],+ ...(input.animation.locomotionDirection+ ? { locomotionDirection: input.animation.locomotionDirection }+ : {}),+ ...(input.animation.rootMotion ? { rootMotion: input.animation.rootMotion } : {}),+ ...(input.animation.loop !== undefined ? { loop: input.animation.loop } : {}),+ ...(input.animation.gait ? { gait: input.animation.gait } : {}),+ },+ }+ : {}),+ ...(architecture ? { architecture } : {}),+ ...(character ? { character } : {}),+ ...(vehicle ? { vehicle } : {}),+ ...(vegetation ? { vegetation } : {}),+ ...(vfx ? { vfx } : {}),+ ...(modular ? { modular } : {}),+ qaProfile: input.qaProfile ?? `${input.category}.default`,+ };++ const result = validateAssetIntentV1(intent);+ if (!result.valid) {+ const summary = result.issues.map((issue) => `${issue.path}: ${issue.message}`).join('; ');+ throw new TypeError(`Invalid AssetIntentV1: ${summary}`);+ }+ return intent;+}diff --git a/src/contracts/breadth.test.ts b/src/contracts/breadth.test.tsnew file mode 100644index 00000000..f917697c--- /dev/null+++ b/src/contracts/breadth.test.ts@@ -0,0 +1,241 @@+import { describe, expect, test } from 'bun:test';++import {+ ASSET_SCOPES,+ REFERENCE_QA_RUN_MODES,+ VFX_SUBTYPES,+ assessAssetScopeV1,+ evaluateModularJoinV1,+ scoreReferenceAgreementV1,+ shouldRunReferenceQa,+ validateReferenceViewAssumptionsV1,+ validateModularKitContractV1,+ validateVfxIntentV1,+ type ModularKitContractV1,+ type VfxIntentV1,+} from './breadth';++const billboard = (): VfxIntentV1 => ({+ schemaVersion: 1,+ subtype: 'billboard',+ portability: 'portable',+ transparency: 'blend',+ doubleSided: true,+ facing: { source: 'explicit', mode: 'camera-y-axis', normalAxis: '+X' },+ animation: {+ playback: 'loop',+ durationSeconds: 2,+ endpointBehavior: 'matchStart',+ driver: 'clip',+ clipName: 'SmokeLoop',+ },+});++const modularKit = (): ModularKitContractV1 => ({+ schemaVersion: 1,+ units: 'm',+ grid: [1, 1, 1],+ sockets: [+ {+ id: 'wall-a.east',+ pieceId: 'wall-a',+ type: 'wall.edge.east',+ compatibleTypes: ['wall.edge.west'],+ frame: { translation: [1, 0, 0], rotation: [0, 0, 0, 1] },+ allowedRotationsDegrees: [0, 90, 180, 270],+ },+ {+ id: 'wall-b.west',+ pieceId: 'wall-b',+ type: 'wall.edge.west',+ compatibleTypes: ['wall.edge.east'],+ frame: { translation: [-1, 0, 0], rotation: [0, 1, 0, 0] },+ allowedRotationsDegrees: [0, 90, 180, 270],+ },+ ],+});++describe('W7 dependency-free breadth contracts', () => {+ test('VFX-001 freezes every subtype plus an explicit portable/sidecar requirement', () => {+ expect(VFX_SUBTYPES).toEqual([+ 'billboard',+ 'beam',+ 'trail',+ 'aura',+ 'portal',+ 'impact',+ 'volume-like',+ 'runtimeShader',+ ]);+ expect(validateVfxIntentV1(billboard())).toEqual({+ valid: true,+ value: billboard(),+ issues: [],+ });++ const runtimeShader: VfxIntentV1 = {+ ...billboard(),+ subtype: 'runtimeShader',+ portability: 'sidecar',+ facing: { source: 'explicit', mode: 'fixed', normalAxis: '+X' },+ animation: {+ playback: 'loop',+ durationSeconds: 1,+ endpointBehavior: 'matchStart',+ driver: 'timeUniform',+ timeUniformName: 'kilnTimeSeconds',+ },+ sidecar: { kind: 'tsl', id: 'kiln.vfx.portal.tsl.v1', version: '1.0.0' },+ };+ expect(validateVfxIntentV1(runtimeShader).valid).toBe(true);+ expect(+ validateVfxIntentV1({ ...runtimeShader, portability: 'portable' }).issues.map(+ (issue) => issue.code,+ ),+ ).toEqual(+ expect.arrayContaining(['VFX_PORTABLE_SIDECAR_CONFLICT', 'VFX_RUNTIME_SHADER_NOT_PORTABLE']),+ );+ });++ test('VFX-003/004 reject incomplete facing, direction, loop, and runtime-driver contracts', () => {+ const beam = {+ ...billboard(),+ subtype: 'beam',+ facing: { source: 'explicit', mode: 'fixed', normalAxis: '+Y' },+ animation: {+ playback: 'loop',+ durationSeconds: 0,+ endpointBehavior: 'holdLast',+ driver: 'none',+ },+ };+ expect(validateVfxIntentV1(beam).issues.map((issue) => issue.code)).toEqual(+ expect.arrayContaining([+ 'VFX_DIRECTION_REQUIRED',+ 'VFX_ANIMATION_DURATION_REQUIRED',+ 'VFX_ANIMATION_DRIVER_REQUIRED',+ 'VFX_LOOP_ENDPOINT_REQUIRED',+ ]),+ );+ });++ test('SCOPE-001 carries all four scopes and flags only the evidence it measured', () => {+ expect(ASSET_SCOPES).toEqual(['single', 'cluster', 'modularSet', 'packMember']);+ const explicit = assessAssetScopeV1(+ { schemaVersion: 1, scope: 'single', explicit: true },+ { topLevelAssetRoots: 2, reusableMemberCount: 2, sceneDressingRoles: [] },+ );+ expect(explicit).toMatchObject({+ status: 'flagged',+ code: 'ASSET_SCOPE_EXPLICIT_SINGLE_CLUSTER',+ explicitSingleViolation: true,+ });+ const cluster = assessAssetScopeV1(+ { schemaVersion: 1, scope: 'cluster', explicit: true },+ { topLevelAssetRoots: 3, reusableMemberCount: 3, sceneDressingRoles: [] },+ );+ expect(cluster.status).toBe('pass');+ expect('disposition' in explicit).toBe(false);+ });++ test('MOD-001 validates grid/units/socket compatibility and proves a zero-seam two-piece join', () => {+ const kit = modularKit();+ expect(validateModularKitContractV1(kit)).toEqual({ valid: true, value: kit, issues: [] });+ const joined = evaluateModularJoinV1(kit, {+ aSocketId: 'wall-a.east',+ bSocketId: 'wall-b.west',+ aWorldPosition: [1, 0, 0],+ bWorldPosition: [1, 0, 0],+ aWorldNormal: [1, 0, 0],+ bWorldNormal: [-1, 0, 0],+ relativeRotationDegrees: 0,+ });+ expect(joined).toMatchObject({+ pass: true,+ seamMeters: 0,+ overlapMeters: 0,+ lateralOffsetMeters: 0,+ normalErrorDegrees: 0,+ codes: [],+ });+ const overlapped = evaluateModularJoinV1(kit, {+ aSocketId: 'wall-a.east',+ bSocketId: 'wall-b.west',+ aWorldPosition: [1, 0, 0],+ bWorldPosition: [0.99, 0, 0],+ aWorldNormal: [1, 0, 0],+ bWorldNormal: [-1, 0, 0],+ relativeRotationDegrees: 45,+ });+ expect(overlapped.pass).toBe(false);+ expect(overlapped.codes).toEqual(+ expect.arrayContaining([+ 'MOD_ROTATION_NOT_ALLOWED',+ 'MOD_GRID_MISALIGNED',+ 'MOD_JOIN_OVERLAP',+ ]),+ );+ });++ test('REF-001 is scheduled only for Bench/flagged/sample and never collapses separate scores', () => {+ expect(REFERENCE_QA_RUN_MODES).toEqual(['bench', 'flagged', 'sample']);+ expect(shouldRunReferenceQa('generation')).toBe(false);+ const assumptions = [+ {+ id: 'reference.front',+ targetViewId: 'front',+ projection: 'perspective' as const,+ mirrored: false,+ materialVisibility: 'full' as const,+ },+ {+ id: 'reference.right',+ targetViewId: 'right',+ projection: 'unknown' as const,+ mirrored: false,+ materialVisibility: 'partial' as const,+ },+ ];+ const report = scoreReferenceAgreementV1({+ runMode: 'sample',+ assumptions,+ samples: [+ {+ assumptionId: 'reference.front',+ silhouetteIntersectionPixels: 80,+ silhouetteUnionPixels: 100,+ meanMaterialDeltaE: 10,+ },+ ],+ structuralReadiness: 'warn',+ });+ expect(report).toEqual({+ schemaVersion: 1,+ scheduled: true,+ runMode: 'sample',+ silhouetteAgreement: 0.8,+ materialAgreement: 0.9,+ structuralReadiness: 'warn',+ evaluatedViews: ['reference.front'],+ insufficientEvidenceViews: ['reference.right'],+ assumptionIssues: [],+ disposition: 'observe',+ repairEligible: false,+ });+ expect('overallScore' in report).toBe(false);+ expect(+ validateReferenceViewAssumptionsV1([+ assumptions[0],+ { ...assumptions[0], targetViewId: 'right' },+ ]).issues.map((issue) => issue.code),+ ).toContain('DUPLICATE_REFERENCE_VIEW_ID');+ expect(+ scoreReferenceAgreementV1({+ runMode: 'generation',+ assumptions,+ samples: [],+ structuralReadiness: 'block',+ }),+ ).toMatchObject({ scheduled: false, disposition: 'observe', repairEligible: false });+ });+});diff --git a/src/contracts/breadth.ts b/src/contracts/breadth.tsnew file mode 100644index 00000000..882d5934--- /dev/null+++ b/src/contracts/breadth.ts@@ -0,0 +1,888 @@+/**+ * Dependency-free contracts for the remaining W7 category breadth.+ *+ * These values are deliberately JSON-shaped so Studio, SDK and engine-free+ * consumers can validate the same payload without importing Three.js.+ */++export const VFX_SUBTYPES = [+ 'billboard',+ 'beam',+ 'trail',+ 'aura',+ 'portal',+ 'impact',+ 'volume-like',+ 'runtimeShader',+] as const;+export type VfxSubtype = (typeof VFX_SUBTYPES)[number];++export const VFX_PORTABILITY_MODES = ['portable', 'sidecar'] as const;+export type VfxPortabilityMode = (typeof VFX_PORTABILITY_MODES)[number];++export const VFX_AXIS_DIRECTIONS = ['+X', '-X', '+Y', '-Y', '+Z', '-Z'] as const;+export type VfxAxisDirection = (typeof VFX_AXIS_DIRECTIONS)[number];++export const VFX_FACING_MODES = ['none', 'camera-spherical', 'camera-y-axis', 'fixed'] as const;+export type VfxFacingMode = (typeof VFX_FACING_MODES)[number];++export const VFX_PLAYBACK_POLICIES = ['static', 'loop', 'oneShot'] as const;+export type VfxPlaybackPolicy = (typeof VFX_PLAYBACK_POLICIES)[number];++export const VFX_RUNTIME_DRIVERS = ['none', 'clip', 'timeUniform'] as const;+export type VfxRuntimeDriver = (typeof VFX_RUNTIME_DRIVERS)[number];++export const VFX_ENDPOINT_BEHAVIORS = ['none', 'matchStart', 'holdLast', 'disappear'] as const;+export type VfxEndpointBehavior = (typeof VFX_ENDPOINT_BEHAVIORS)[number];++export type VfxTransparencyMode = 'opaque' | 'mask' | 'blend';++export interface VfxFacingIntentV1 {+ /** Explicit trusted intent may gate; inferred facing remains advisory. */+ source: 'explicit' | 'inferred';+ mode: VfxFacingMode;+ normalAxis?: VfxAxisDirection;+ directionAxis?: VfxAxisDirection;+}++export interface VfxAnimationIntentV1 {+ playback: VfxPlaybackPolicy;+ durationSeconds: number;+ endpointBehavior: VfxEndpointBehavior;+ driver: VfxRuntimeDriver;+ clipName?: string;+ timeUniformName?: string;+}++export interface VfxRuntimeSidecarV1 {+ kind: 'tsl';+ id: string;+ version: string;+}++/** Trusted VFX construction/runtime requirements resolved before model execution. */+export interface VfxIntentV1 {+ schemaVersion: 1;+ subtype: VfxSubtype;+ portability: VfxPortabilityMode;+ transparency: VfxTransparencyMode;+ doubleSided: boolean;+ facing: VfxFacingIntentV1;+ animation: VfxAnimationIntentV1;+ sidecar?: VfxRuntimeSidecarV1;+}++export interface VfxIntentV1Input {+ schemaVersion?: 1;+ subtype?: VfxSubtype;+ portability?: VfxPortabilityMode;+ transparency?: VfxTransparencyMode;+ doubleSided?: boolean;+ facing?: Partial<VfxFacingIntentV1>;+ animation?: Partial<VfxAnimationIntentV1>;+ sidecar?: Partial<VfxRuntimeSidecarV1>;+}++export interface BreadthValidationIssue {+ code: string;+ path: string;+ message: string;+}++export interface BreadthValidationResult<T> {+ valid: boolean;+ value?: T;+ issues: BreadthValidationIssue[];+}++const record = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const trimmed = (value: unknown): value is string =>+ typeof value === 'string' && value.length > 0 && value === value.trim();++const enumValue = <T extends readonly string[]>(values: T, value: unknown): value is T[number] =>+ typeof value === 'string' && (values as readonly string[]).includes(value);++const finitePositive = (value: unknown): value is number =>+ typeof value === 'number' && Number.isFinite(value) && value > 0;++const finiteNonNegative = (value: unknown): value is number =>+ typeof value === 'number' && Number.isFinite(value) && value >= 0;++function cloneVfxIntentV1(value: VfxIntentV1): VfxIntentV1 {+ return {+ schemaVersion: 1,+ subtype: value.subtype,+ portability: value.portability,+ transparency: value.transparency,+ doubleSided: value.doubleSided,+ facing: { ...value.facing },+ animation: { ...value.animation },+ ...(value.sidecar ? { sidecar: { ...value.sidecar } } : {}),+ };+}++/** Validate the closure-owned VFX contract and its portable/sidecar boundary. */+export function validateVfxIntentV1(value: unknown): BreadthValidationResult<VfxIntentV1> {+ const issues: BreadthValidationIssue[] = [];+ if (!record(value)) {+ return {+ valid: false,+ issues: [{ code: 'EXPECTED_OBJECT', path: '', message: 'VfxIntentV1 must be an object.' }],+ };+ }+ if (value.schemaVersion !== 1) {+ issues.push({+ code: 'UNSUPPORTED_SCHEMA_VERSION',+ path: 'schemaVersion',+ message: 'schemaVersion must be 1.',+ });+ }+ if (!enumValue(VFX_SUBTYPES, value.subtype)) {+ issues.push({+ code: 'INVALID_VFX_SUBTYPE',+ path: 'subtype',+ message: `subtype must be one of ${VFX_SUBTYPES.join(', ')}.`,+ });+ }+ if (!enumValue(VFX_PORTABILITY_MODES, value.portability)) {+ issues.push({+ code: 'INVALID_VFX_PORTABILITY',+ path: 'portability',+ message: 'portability must be portable or sidecar.',+ });+ }+ if (+ value.transparency !== 'opaque' &&+ value.transparency !== 'mask' &&+ value.transparency !== 'blend'+ ) {+ issues.push({+ code: 'INVALID_VFX_TRANSPARENCY',+ path: 'transparency',+ message: 'transparency must be opaque, mask, or blend.',+ });+ }+ if (typeof value.doubleSided !== 'boolean') {+ issues.push({+ code: 'INVALID_VFX_SIDEDNESS',+ path: 'doubleSided',+ message: 'doubleSided must be boolean.',+ });+ }++ if (!record(value.facing)) {+ issues.push({ code: 'INVALID_VFX_FACING', path: 'facing', message: 'facing is required.' });+ } else {+ if (value.facing.source !== 'explicit' && value.facing.source !== 'inferred') {+ issues.push({+ code: 'INVALID_VFX_FACING_SOURCE',+ path: 'facing.source',+ message: 'facing.source must be explicit or inferred.',+ });+ }+ if (!enumValue(VFX_FACING_MODES, value.facing.mode)) {+ issues.push({+ code: 'INVALID_VFX_FACING_MODE',+ path: 'facing.mode',+ message: `facing.mode must be one of ${VFX_FACING_MODES.join(', ')}.`,+ });+ }+ for (const field of ['normalAxis', 'directionAxis'] as const) {+ if (+ value.facing[field] !== undefined &&+ !enumValue(VFX_AXIS_DIRECTIONS, value.facing[field])+ ) {+ issues.push({+ code: 'INVALID_VFX_AXIS',+ path: `facing.${field}`,+ message: `${field} must use a signed Kiln axis.`,+ });+ }+ }+ if (+ value.subtype === 'billboard' &&+ value.facing.mode !== 'camera-spherical' &&+ value.facing.mode !== 'camera-y-axis'+ ) {+ issues.push({+ code: 'VFX_BILLBOARD_FACING_REQUIRED',+ path: 'facing.mode',+ message: 'A billboard must declare spherical or Y-axis camera facing.',+ });+ }+ if (+ (value.subtype === 'beam' || value.subtype === 'trail') &&+ value.facing.directionAxis === undefined+ ) {+ issues.push({+ code: 'VFX_DIRECTION_REQUIRED',+ path: 'facing.directionAxis',+ message: 'Beam and trail effects must declare a signed direction axis.',+ });+ }+ }++ if (!record(value.animation)) {+ issues.push({+ code: 'INVALID_VFX_ANIMATION',+ path: 'animation',+ message: 'animation is required, including an explicit static policy.',+ });+ } else {+ if (!enumValue(VFX_PLAYBACK_POLICIES, value.animation.playback)) {+ issues.push({+ code: 'INVALID_VFX_PLAYBACK',+ path: 'animation.playback',+ message: `playback must be one of ${VFX_PLAYBACK_POLICIES.join(', ')}.`,+ });+ }+ if (!finiteNonNegative(value.animation.durationSeconds)) {+ issues.push({+ code: 'INVALID_VFX_DURATION',+ path: 'animation.durationSeconds',+ message: 'durationSeconds must be finite and non-negative.',+ });+ }+ if (!enumValue(VFX_ENDPOINT_BEHAVIORS, value.animation.endpointBehavior)) {+ issues.push({+ code: 'INVALID_VFX_ENDPOINT',+ path: 'animation.endpointBehavior',+ message: `endpointBehavior must be one of ${VFX_ENDPOINT_BEHAVIORS.join(', ')}.`,+ });+ }+ if (!enumValue(VFX_RUNTIME_DRIVERS, value.animation.driver)) {+ issues.push({+ code: 'INVALID_VFX_DRIVER',+ path: 'animation.driver',+ message: `driver must be one of ${VFX_RUNTIME_DRIVERS.join(', ')}.`,+ });+ }+ if (value.animation.playback === 'static') {+ if (+ value.animation.durationSeconds !== 0 ||+ value.animation.driver !== 'none' ||+ value.animation.endpointBehavior !== 'none'+ ) {+ issues.push({+ code: 'INVALID_VFX_STATIC_POLICY',+ path: 'animation',+ message: 'Static effects require duration 0, driver none, and endpoint none.',+ });+ }+ } else {+ if (!finitePositive(value.animation.durationSeconds)) {+ issues.push({+ code: 'VFX_ANIMATION_DURATION_REQUIRED',+ path: 'animation.durationSeconds',+ message: 'Animated effects require a positive duration.',+ });+ }+ if (value.animation.driver === 'none') {+ issues.push({+ code: 'VFX_ANIMATION_DRIVER_REQUIRED',+ path: 'animation.driver',+ message: 'Animated effects require a clip or time-uniform driver.',+ });+ }+ if (+ value.animation.playback === 'loop' &&+ value.animation.endpointBehavior !== 'matchStart'+ ) {+ issues.push({+ code: 'VFX_LOOP_ENDPOINT_REQUIRED',+ path: 'animation.endpointBehavior',+ message: 'Looping effects must declare matchStart endpoint behavior.',+ });+ }+ if (+ value.animation.playback === 'oneShot' &&+ value.animation.endpointBehavior !== 'holdLast' &&+ value.animation.endpointBehavior !== 'disappear'+ ) {+ issues.push({+ code: 'VFX_ONESHOT_ENDPOINT_REQUIRED',+ path: 'animation.endpointBehavior',+ message: 'One-shot effects must hold the last state or disappear.',+ });+ }+ }+ if (value.animation.driver === 'clip' && !trimmed(value.animation.clipName)) {+ issues.push({+ code: 'VFX_CLIP_NAME_REQUIRED',+ path: 'animation.clipName',+ message: 'Clip-driven VFX requires a non-empty clipName.',+ });+ }+ if (value.animation.driver === 'timeUniform' && !trimmed(value.animation.timeUniformName)) {+ issues.push({+ code: 'VFX_TIME_UNIFORM_REQUIRED',+ path: 'animation.timeUniformName',+ message: 'Time-uniform VFX requires a non-empty timeUniformName.',+ });+ }+ }++ if (value.sidecar !== undefined) {+ if (+ !record(value.sidecar) ||+ value.sidecar.kind !== 'tsl' ||+ !trimmed(value.sidecar.id) ||+ !trimmed(value.sidecar.version)+ ) {+ issues.push({+ code: 'INVALID_VFX_SIDECAR',+ path: 'sidecar',+ message: 'sidecar requires kind tsl plus non-empty id and version.',+ });+ }+ }+ if (value.portability === 'portable' && value.sidecar !== undefined) {+ issues.push({+ code: 'VFX_PORTABLE_SIDECAR_CONFLICT',+ path: 'sidecar',+ message: 'Portable VFX cannot require a runtime shader sidecar.',+ });+ }+ if (value.portability === 'sidecar' && value.sidecar === undefined) {+ issues.push({+ code: 'VFX_SIDECAR_REQUIRED',+ path: 'sidecar',+ message: 'Sidecar VFX requires a versioned runtime sidecar descriptor.',+ });+ }+ if (value.subtype === 'runtimeShader' && value.portability !== 'sidecar') {+ issues.push({+ code: 'VFX_RUNTIME_SHADER_NOT_PORTABLE',+ path: 'portability',+ message: 'runtimeShader is an explicit nonportable sidecar subtype.',+ });+ }++ if (issues.length > 0) return { valid: false, issues };+ return { valid: true, value: cloneVfxIntentV1(value as unknown as VfxIntentV1), issues };+}++export const ASSET_SCOPES = ['single', 'cluster', 'modularSet', 'packMember'] as const;+export type AssetScope = (typeof ASSET_SCOPES)[number];++export interface AssetScopeIntentV1 {+ schemaVersion: 1;+ scope: AssetScope;+ /** True only when the user/product explicitly required the scope. */+ explicit: boolean;+}++export interface AssetScopeObservationV1 {+ topLevelAssetRoots: number;+ reusableMemberCount: number;+ sceneDressingRoles: string[];+}++export interface AssetScopeAssessmentV1 {+ schemaVersion: 1;+ requested: AssetScope;+ observed: 'single' | 'cluster';+ status: 'pass' | 'flagged';+ code?: 'ASSET_SCOPE_ACCIDENTAL_DIORAMA' | 'ASSET_SCOPE_EXPLICIT_SINGLE_CLUSTER';+ /** S-class signal only; default QA remains observe/warn, never a blocker. */+ explicitSingleViolation: boolean;+ evidence: string[];+}++export function assessAssetScopeV1(+ intent: AssetScopeIntentV1,+ observation: AssetScopeObservationV1,+): AssetScopeAssessmentV1 {+ const observed =+ observation.topLevelAssetRoots > 1 || observation.reusableMemberCount > 1+ ? 'cluster'+ : 'single';+ const dressing = [...new Set(observation.sceneDressingRoles.filter(trimmed))].sort();+ const accidentalDiorama = dressing.length > 0 && intent.scope !== 'cluster';+ const explicitSingleViolation =+ intent.scope === 'single' && intent.explicit && observed === 'cluster';+ const flagged = accidentalDiorama || explicitSingleViolation;+ return {+ schemaVersion: 1,+ requested: intent.scope,+ observed,+ status: flagged ? 'flagged' : 'pass',+ ...(flagged+ ? {+ code: explicitSingleViolation+ ? ('ASSET_SCOPE_EXPLICIT_SINGLE_CLUSTER' as const)+ : ('ASSET_SCOPE_ACCIDENTAL_DIORAMA' as const),+ }+ : {}),+ explicitSingleViolation,+ evidence: [+ `topLevelAssetRoots=${observation.topLevelAssetRoots}`,+ `reusableMemberCount=${observation.reusableMemberCount}`,+ ...(dressing.length > 0 ? [`sceneDressingRoles=${dressing.join(',')}`] : []),+ ],+ };+}++export type ModularVector3 = [number, number, number];+export type ModularQuaternion = [number, number, number, number];++export const KILN_DEFAULT_MODULAR_GRID: ModularVector3 = Object.freeze([1, 1, 1]) as ModularVector3;++/** Trusted request-side modular units/grid; artifact sockets remain engine-derived evidence. */+export interface ModularIntentV1 {+ schemaVersion: 1;+ units: 'm';+ grid: ModularVector3;+}++export interface ModularIntentV1Input {+ schemaVersion?: 1;+ units?: 'm';+ grid?: ModularVector3;+}++export interface ModularSocketContractV1 {+ id: string;+ pieceId: string;+ type: string;+ compatibleTypes: string[];+ frame: {+ translation: ModularVector3;+ rotation: ModularQuaternion;+ };+ allowedRotationsDegrees: number[];+}++export interface ModularKitContractV1 {+ schemaVersion: 1;+ units: 'm';+ grid: ModularVector3;+ sockets: ModularSocketContractV1[];+}++export interface ModularJoinObservationV1 {+ aSocketId: string;+ bSocketId: string;+ aWorldPosition: ModularVector3;+ bWorldPosition: ModularVector3;+ aWorldNormal: ModularVector3;+ bWorldNormal: ModularVector3;+ relativeRotationDegrees: number;+ toleranceMeters?: number;+ normalToleranceDegrees?: number;+}++export interface ModularJoinResultV1 {+ schemaVersion: 1;+ pass: boolean;+ compatible: boolean;+ rotationAllowed: boolean;+ gridAligned: boolean;+ seamMeters: number;+ overlapMeters: number;+ lateralOffsetMeters: number;+ normalErrorDegrees: number;+ toleranceMeters: number;+ codes: string[];+}++const finiteTuple = (value: unknown, length: number): value is number[] =>+ Array.isArray(value) &&+ value.length === length &&+ value.every((component) => typeof component === 'number' && Number.isFinite(component));++const stable = (value: number): number => Math.round(value * 1_000_000) / 1_000_000;++function normalizeVector(value: ModularVector3): ModularVector3 {+ const length = Math.hypot(...value);+ if (length <= 1e-9) throw new TypeError('Socket normals must be non-zero.');+ return [value[0] / length, value[1] / length, value[2] / length];+}++const dot = (a: ModularVector3, b: ModularVector3): number =>+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2];++const subtract = (a: ModularVector3, b: ModularVector3): ModularVector3 => [+ a[0] - b[0],+ a[1] - b[1],+ a[2] - b[2],+];++const multiply = (value: ModularVector3, scalar: number): ModularVector3 => [+ value[0] * scalar,+ value[1] * scalar,+ value[2] * scalar,+];++const length = (value: ModularVector3): number => Math.hypot(...value);++const normalizedDegrees = (value: number): number => {+ const normalized = ((value % 360) + 360) % 360;+ return Object.is(normalized, -0) ? 0 : normalized;+};++export function validateModularKitContractV1(+ value: unknown,+): BreadthValidationResult<ModularKitContractV1> {+ const issues: BreadthValidationIssue[] = [];+ if (!record(value)) {+ return {+ valid: false,+ issues: [+ { code: 'EXPECTED_OBJECT', path: '', message: 'ModularKitContractV1 must be an object.' },+ ],+ };+ }+ if (value.schemaVersion !== 1) {+ issues.push({+ code: 'UNSUPPORTED_SCHEMA_VERSION',+ path: 'schemaVersion',+ message: 'schemaVersion must be 1.',+ });+ }+ if (value.units !== 'm') {+ issues.push({+ code: 'INVALID_MODULAR_UNITS',+ path: 'units',+ message: 'Modular kit units must be meters.',+ });+ }+ if (!finiteTuple(value.grid, 3) || value.grid.some((component) => component <= 0)) {+ issues.push({+ code: 'INVALID_MODULAR_GRID',+ path: 'grid',+ message: 'grid must contain three positive meter steps.',+ });+ }+ const sockets = Array.isArray(value.sockets) ? value.sockets : [];+ if (!Array.isArray(value.sockets) || sockets.length < 2) {+ issues.push({+ code: 'INVALID_MODULAR_SOCKETS',+ path: 'sockets',+ message: 'A modular kit requires at least two sockets.',+ });+ }+ const ids = new Set<string>();+ for (const [index, socket] of sockets.entries()) {+ const path = `sockets[${index}]`;+ if (!record(socket)) {+ issues.push({ code: 'INVALID_MODULAR_SOCKET', path, message: `${path} must be an object.` });+ continue;+ }+ for (const field of ['id', 'pieceId', 'type'] as const) {+ if (!trimmed(socket[field])) {+ issues.push({+ code: 'INVALID_MODULAR_SOCKET_FIELD',+ path: `${path}.${field}`,+ message: `${field} is required.`,+ });+ }+ }+ if (trimmed(socket.id)) {+ if (ids.has(socket.id))+ issues.push({+ code: 'DUPLICATE_MODULAR_SOCKET',+ path: `${path}.id`,+ message: `Duplicate socket ${socket.id}.`,+ });+ ids.add(socket.id);+ }+ if (!Array.isArray(socket.compatibleTypes) || !socket.compatibleTypes.every(trimmed)) {+ issues.push({+ code: 'INVALID_MODULAR_COMPATIBILITY',+ path: `${path}.compatibleTypes`,+ message: 'compatibleTypes must contain strings.',+ });+ }+ if (+ !record(socket.frame) ||+ !finiteTuple(socket.frame.translation, 3) ||+ !finiteTuple(socket.frame.rotation, 4)+ ) {+ issues.push({+ code: 'INVALID_MODULAR_FRAME',+ path: `${path}.frame`,+ message: 'Socket frame requires finite translation and quaternion.',+ });+ } else if (Math.abs(Math.hypot(...socket.frame.rotation) - 1) > 1e-6) {+ issues.push({+ code: 'NON_UNIT_MODULAR_FRAME',+ path: `${path}.frame.rotation`,+ message: 'Socket frame quaternion must be normalized.',+ });+ }+ if (+ !Array.isArray(socket.allowedRotationsDegrees) ||+ socket.allowedRotationsDegrees.length === 0 ||+ !socket.allowedRotationsDegrees.every(+ (angle) => typeof angle === 'number' && Number.isFinite(angle),+ )+ ) {+ issues.push({+ code: 'INVALID_MODULAR_ROTATIONS',+ path: `${path}.allowedRotationsDegrees`,+ message: 'At least one finite allowed rotation is required.',+ });+ }+ }+ if (issues.length > 0) return { valid: false, issues };+ const contract = value as unknown as ModularKitContractV1;+ return {+ valid: true,+ value: {+ schemaVersion: 1,+ units: 'm',+ grid: [...contract.grid],+ sockets: contract.sockets.map((socket) => ({+ ...socket,+ compatibleTypes: [...socket.compatibleTypes],+ allowedRotationsDegrees: [...socket.allowedRotationsDegrees],+ frame: {+ translation: [...socket.frame.translation],+ rotation: [...socket.frame.rotation],+ },+ })),+ },+ issues,+ };+}++/** Exact two-piece snap evidence. Correct fixtures have zero seam and overlap within tolerance. */+export function evaluateModularJoinV1(+ kit: ModularKitContractV1,+ observation: ModularJoinObservationV1,+): ModularJoinResultV1 {+ const validated = validateModularKitContractV1(kit);+ if (!validated.valid)+ throw new TypeError('Cannot evaluate a join against an invalid modular kit.');+ const a = kit.sockets.find((socket) => socket.id === observation.aSocketId);+ const b = kit.sockets.find((socket) => socket.id === observation.bSocketId);+ if (!a || !b) throw new TypeError('Join observation references an unknown socket.');+ const toleranceMeters = observation.toleranceMeters ?? 0.0001;+ const normalToleranceDegrees = observation.normalToleranceDegrees ?? 0.1;+ if (!finiteNonNegative(toleranceMeters) || !finiteNonNegative(normalToleranceDegrees)) {+ throw new TypeError('Join tolerances must be finite and non-negative.');+ }+ const aNormal = normalizeVector(observation.aWorldNormal);+ const bNormal = normalizeVector(observation.bWorldNormal);+ const delta = subtract(observation.bWorldPosition, observation.aWorldPosition);+ const axial = dot(delta, aNormal);+ const lateral = length(subtract(delta, multiply(aNormal, axial)));+ const seamMeters = Math.max(0, axial);+ const overlapMeters = Math.max(0, -axial);+ const normalCosine = Math.max(-1, Math.min(1, dot(aNormal, bNormal)));+ const normalErrorDegrees = Math.abs(180 - (Math.acos(normalCosine) * 180) / Math.PI);+ const compatible = a.compatibleTypes.includes(b.type) && b.compatibleTypes.includes(a.type);+ const angle = normalizedDegrees(observation.relativeRotationDegrees);+ const rotationAllowed = [a, b].every((socket) =>+ socket.allowedRotationsDegrees.some(+ (allowed) => Math.abs(normalizedDegrees(allowed) - angle) <= 1e-6,+ ),+ );+ const gridAligned = [observation.aWorldPosition, observation.bWorldPosition].every((position) =>+ position.every((component, index) => {+ const step = kit.grid[index]!;+ return Math.abs(component / step - Math.round(component / step)) <= 1e-6;+ }),+ );+ const codes: string[] = [];+ if (!compatible) codes.push('MOD_SOCKET_INCOMPATIBLE');+ if (!rotationAllowed) codes.push('MOD_ROTATION_NOT_ALLOWED');+ if (!gridAligned) codes.push('MOD_GRID_MISALIGNED');+ if (seamMeters > toleranceMeters || lateral > toleranceMeters) codes.push('MOD_JOIN_SEAM');+ if (overlapMeters > toleranceMeters) codes.push('MOD_JOIN_OVERLAP');+ if (normalErrorDegrees > normalToleranceDegrees) codes.push('MOD_SOCKET_NORMAL_MISMATCH');+ return {+ schemaVersion: 1,+ pass: codes.length === 0,+ compatible,+ rotationAllowed,+ gridAligned,+ seamMeters: stable(seamMeters),+ overlapMeters: stable(overlapMeters),+ lateralOffsetMeters: stable(lateral),+ normalErrorDegrees: stable(normalErrorDegrees),+ toleranceMeters,+ codes,+ };+}++export const REFERENCE_QA_RUN_MODES = ['bench', 'flagged', 'sample'] as const;+export type ReferenceQaRunMode = (typeof REFERENCE_QA_RUN_MODES)[number];++export interface ReferenceViewAssumptionV1 {+ id: string;+ targetViewId: string;+ projection: 'perspective' | 'orthographic' | 'unknown';+ mirrored: boolean;+ materialVisibility: 'full' | 'partial' | 'unknown';+}++export interface ReferenceAgreementSampleV1 {+ assumptionId: string;+ silhouetteIntersectionPixels: number;+ silhouetteUnionPixels: number;+ meanMaterialDeltaE?: number;+}++export interface ReferenceAgreementReportV1 {+ schemaVersion: 1;+ scheduled: boolean;+ runMode?: ReferenceQaRunMode;+ silhouetteAgreement: number | null;+ materialAgreement: number | null;+ structuralReadiness: 'pass' | 'warn' | 'block' | 'notEvaluated';+ evaluatedViews: string[];+ insufficientEvidenceViews: string[];+ assumptionIssues: string[];+ disposition: 'observe';+ repairEligible: false;+}++export function shouldRunReferenceQa(value: unknown): value is ReferenceQaRunMode {+ return enumValue(REFERENCE_QA_RUN_MODES, value);+}++export function validateReferenceViewAssumptionsV1(+ value: unknown,+): BreadthValidationResult<ReferenceViewAssumptionV1[]> {+ const issues: BreadthValidationIssue[] = [];+ if (!Array.isArray(value) || value.length === 0) {+ return {+ valid: false,+ issues: [+ {+ code: 'REFERENCE_VIEWS_REQUIRED',+ path: 'assumptions',+ message: 'At least one reference-view assumption is required.',+ },+ ],+ };+ }+ const ids = new Set<string>();+ for (const [index, assumption] of value.entries()) {+ const path = `assumptions[${index}]`;+ if (!record(assumption)) {+ issues.push({ code: 'INVALID_REFERENCE_VIEW', path, message: `${path} must be an object.` });+ continue;+ }+ for (const field of ['id', 'targetViewId'] as const) {+ if (!trimmed(assumption[field])) {+ issues.push({+ code: 'INVALID_REFERENCE_VIEW_FIELD',+ path: `${path}.${field}`,+ message: `${field} must be a trimmed non-empty string.`,+ });+ }+ }+ if (trimmed(assumption.id)) {+ if (ids.has(assumption.id)) {+ issues.push({+ code: 'DUPLICATE_REFERENCE_VIEW_ID',+ path: `${path}.id`,+ message: `Duplicate reference-view assumption ${assumption.id}.`,+ });+ }+ ids.add(assumption.id);+ }+ if (!['perspective', 'orthographic', 'unknown'].includes(String(assumption.projection))) {+ issues.push({+ code: 'INVALID_REFERENCE_PROJECTION',+ path: `${path}.projection`,+ message: 'projection must be perspective, orthographic, or unknown.',+ });+ }+ if (typeof assumption.mirrored !== 'boolean') {+ issues.push({+ code: 'INVALID_REFERENCE_MIRRORED',+ path: `${path}.mirrored`,+ message: 'mirrored must be boolean.',+ });+ }+ if (!['full', 'partial', 'unknown'].includes(String(assumption.materialVisibility))) {+ issues.push({+ code: 'INVALID_REFERENCE_MATERIAL_VISIBILITY',+ path: `${path}.materialVisibility`,+ message: 'materialVisibility must be full, partial, or unknown.',+ });+ }+ }+ if (issues.length > 0) return { valid: false, issues };+ return {+ valid: true,+ value: (value as ReferenceViewAssumptionV1[]).map((assumption) => ({ ...assumption })),+ issues,+ };+}++/**+ * Score reference agreement only for Bench, flagged, or sampled work. Silhouette+ * and material agreement remain separate from structural readiness and cannot+ * trigger a hard failure or automatic repair.+ */+export function scoreReferenceAgreementV1(input: {+ runMode: unknown;+ assumptions: readonly ReferenceViewAssumptionV1[];+ samples: readonly ReferenceAgreementSampleV1[];+ structuralReadiness: ReferenceAgreementReportV1['structuralReadiness'];+}): ReferenceAgreementReportV1 {+ const validatedAssumptions = validateReferenceViewAssumptionsV1(input.assumptions);+ const assumptions = validatedAssumptions.value ?? [];+ if (!shouldRunReferenceQa(input.runMode)) {+ return {+ schemaVersion: 1,+ scheduled: false,+ silhouetteAgreement: null,+ materialAgreement: null,+ structuralReadiness: input.structuralReadiness,+ evaluatedViews: [],+ insufficientEvidenceViews: assumptions.map((assumption) => assumption.id).sort(),+ assumptionIssues: validatedAssumptions.issues.map((issue) => issue.code),+ disposition: 'observe',+ repairEligible: false,+ };+ }+ const assumptionIds = new Set(assumptions.map((assumption) => assumption.id));+ const silhouette: number[] = [];+ const material: number[] = [];+ const evaluatedViews: string[] = [];+ for (const sample of input.samples) {+ if (!assumptionIds.has(sample.assumptionId)) continue;+ if (+ !finiteNonNegative(sample.silhouetteIntersectionPixels) ||+ !finitePositive(sample.silhouetteUnionPixels) ||+ sample.silhouetteIntersectionPixels > sample.silhouetteUnionPixels+ ) {+ continue;+ }+ silhouette.push(sample.silhouetteIntersectionPixels / sample.silhouetteUnionPixels);+ if (finiteNonNegative(sample.meanMaterialDeltaE)) {+ material.push(Math.max(0, 1 - Math.min(100, sample.meanMaterialDeltaE) / 100));+ }+ evaluatedViews.push(sample.assumptionId);+ }+ const evaluated = [...new Set(evaluatedViews)].sort();+ const insufficient = assumptions+ .map((assumption) => assumption.id)+ .filter((id) => !evaluated.includes(id))+ .sort();+ const mean = (values: number[]): number | null =>+ values.length > 0+ ? stable(values.reduce((sum, value) => sum + value, 0) / values.length)+ : null;+ return {+ schemaVersion: 1,+ scheduled: true,+ runMode: input.runMode,+ silhouetteAgreement: mean(silhouette),+ materialAgreement: mean(material),+ structuralReadiness: input.structuralReadiness,+ evaluatedViews: evaluated,+ insufficientEvidenceViews: insufficient,+ assumptionIssues: validatedAssumptions.issues.map((issue) => issue.code),+ disposition: 'observe',+ repairEligible: false,+ };+}diff --git a/src/contracts/environment.ts b/src/contracts/environment.tsnew file mode 100644index 00000000..58a26db8--- /dev/null+++ b/src/contracts/environment.ts@@ -0,0 +1,81 @@+import type { AssetIntentV1 } from './asset';++export const ENVIRONMENT_SUBTYPES = [+ 'terrain-tile',+ 'rock-cliff',+ 'cave',+ 'road-path',+ 'shoreline',+ 'wall-gate',+ 'bridge',+ 'set-dressing-cluster',+ 'custom',+] as const;+export type EnvironmentSubtype = (typeof ENVIRONMENT_SUBTYPES)[number];++export const ENVIRONMENT_SOCKET_TYPES = [+ 'environment.tile.x-negative',+ 'environment.tile.x-positive',+ 'environment.tile.z-negative',+ 'environment.tile.z-positive',+ 'environment.road.start',+ 'environment.road.end',+ 'environment.bridge.start',+ 'environment.bridge.end',+ 'environment.wall.left',+ 'environment.wall.right',+ 'environment.gate.left',+ 'environment.gate.right',+ 'environment.scatter-zone',+] as const;+export type EnvironmentSocketType = (typeof ENVIRONMENT_SOCKET_TYPES)[number];++export interface EnvironmentIntentProfileV1 {+ schemaVersion: 1;+ subtype: EnvironmentSubtype;+ tileable: boolean;+ navigable: boolean;+}++function normalizeEnvironmentSubtype(value: string | undefined): EnvironmentSubtype {+ const normalized = (value ?? '')+ .trim()+ .toLowerCase()+ .replace(/[ _/]+/g, '-');+ if (normalized === 'terrain' || normalized === 'tile' || normalized === 'terrain-tile') {+ return 'terrain-tile';+ }+ if (normalized === 'rock' || normalized === 'cliff' || normalized === 'rock-cliff') {+ return 'rock-cliff';+ }+ if (normalized === 'cave' || normalized === 'cave-entrance') return 'cave';+ if (normalized === 'road' || normalized === 'path' || normalized === 'road-path') {+ return 'road-path';+ }+ if (normalized === 'shore' || normalized === 'shoreline') return 'shoreline';+ if (normalized === 'wall' || normalized === 'gate' || normalized === 'wall-gate') {+ return 'wall-gate';+ }+ if (normalized === 'bridge') return 'bridge';+ if (+ normalized === 'cluster' ||+ normalized === 'set-dressing' ||+ normalized === 'set-dressing-cluster'+ ) {+ return 'set-dressing-cluster';+ }+ return 'custom';+}++/** Canonical ENV-001 profile derived only from closure-owned intent. */+export function resolveEnvironmentIntentProfile(+ intent: AssetIntentV1,+): EnvironmentIntentProfileV1 | undefined {+ if (intent.category !== 'environment') return undefined;+ return {+ schemaVersion: 1,+ subtype: normalizeEnvironmentSubtype(intent.subtype),+ tileable: intent.capabilities.includes('tileable'),+ navigable: intent.capabilities.includes('navigable'),+ };+}diff --git a/src/contracts/index.ts b/src/contracts/index.tsnew file mode 100644index 00000000..beb2e2ec--- /dev/null+++ b/src/contracts/index.ts@@ -0,0 +1,4 @@+export * from './asset';+export * from './breadth';+export * from './environment';+export * from './semantic';diff --git a/src/contracts/semantic.test.ts b/src/contracts/semantic.test.tsnew file mode 100644index 00000000..e7a54449--- /dev/null+++ b/src/contracts/semantic.test.ts@@ -0,0 +1,146 @@+import { describe, expect, test } from 'bun:test';+import { WebIO } from '@gltf-transform/core';+import * as THREE from 'three';++import { boxGeo, createPart } from '../primitives';+import { renderSceneToGLB } from '../render';+import {+ KILN_SEMANTIC_EXTRAS_KEY,+ createSemanticMetadataV1,+ readSemanticMetadataV1,+ readSemanticMetadataV1FromExtras,+ semanticMetadataBytesV1,+ stampSemanticMetadataV1,+ validateSemanticMetadataV1,+} from './semantic';++const fullMetadata = () =>+ createSemanticMetadataV1({+ roles: ['vehicle.chassis', 'vehicle.driveable'],+ frames: [+ { id: 'axle.front', translation: [1.25, 0.42, 0], rotation: [0, 0, 0, 1] },+ {+ id: 'seat.driver',+ translation: [-0.2, 1.05, 0.35],+ rotation: [0, Math.SQRT1_2, 0, Math.SQRT1_2],+ },+ ],+ relationships: [+ {+ kind: 'supports',+ target: 'vehicle.wheel.frontLeft',+ targetType: 'role',+ sourceFrame: 'axle.front',+ },+ {+ kind: 'drivenBy',+ target: 'driver',+ targetType: 'socket',+ sourceFrame: 'seat.driver',+ },+ ],+ sockets: [+ {+ id: 'driver',+ type: 'occupant.driver',+ frame: 'seat.driver',+ compatibleTypes: ['character.seated'],+ allowedRotationsDegrees: [0, 180],+ },+ ],+ });++describe('semantic metadata contract', () => {+ test('creates detached, validated role/relationship/frame/socket metadata', () => {+ const metadata = fullMetadata();+ const object = new THREE.Group();+ stampSemanticMetadataV1(object, metadata);++ metadata.roles.push('mutated.after.stamp');+ const stamped = readSemanticMetadataV1(object);+ expect(stamped?.schemaVersion).toBe(1);+ expect(stamped?.roles).toEqual(['vehicle.chassis', 'vehicle.driveable']);+ expect(stamped?.relationships[0]?.sourceFrame).toBe('axle.front');+ expect(stamped?.sockets[0]?.frame).toBe('seat.driver');+ });++ test('rejects duplicate IDs, unknown frame references, and non-rigid frames', () => {+ const invalid = {+ schemaVersion: 1,+ roles: ['roof.slope.left'],+ relationships: [],+ frames: [+ { id: 'ridge', translation: [0, 0, 0], rotation: [0, 0, 0, 2] },+ { id: 'ridge', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ ],+ sockets: [+ { id: 'join', type: 'roof.join', frame: 'missing', compatibleTypes: ['roof.join'] },+ ],+ };+ const result = validateSemanticMetadataV1(invalid);+ expect(result.valid).toBe(false);+ expect(result.issues.map((issue) => issue.code)).toEqual(+ expect.arrayContaining([+ 'NON_UNIT_FRAME_ROTATION',+ 'DUPLICATE_FRAME_ID',+ 'UNKNOWN_FRAME_REFERENCE',+ ]),+ );+ });++ test('survives final GLB export, reload, rewrite, and reload byte-for-byte in node extras', async () => {+ const root = new THREE.Group();+ root.name = 'SemanticVehicle';+ const metadata = fullMetadata();+ const chassis = createPart(+ 'Chassis',+ boxGeo(2.5, 0.6, 1.4),+ new THREE.MeshStandardMaterial({ color: 0x334455 }),+ { parent: root, semantic: metadata },+ );+ expect(readSemanticMetadataV1(chassis)?.roles).toEqual([+ 'vehicle.chassis',+ 'vehicle.driveable',+ ]);++ const rendered = await renderSceneToGLB(root, { optimize: 'full' });+ const io = new WebIO();+ const document = await io.readBinary(rendered.bytes);+ const loadedNode = document+ .getRoot()+ .listNodes()+ .find((node) => node.getName() === 'Mesh_Chassis');+ expect(loadedNode).toBeDefined();+ const loaded = readSemanticMetadataV1FromExtras(loadedNode!.getExtras());+ expect(loaded).toBeDefined();+ expect(semanticMetadataBytesV1(loaded!)).toEqual(semanticMetadataBytesV1(metadata));+ expect(+ Array.from(+ new TextEncoder().encode(JSON.stringify(loadedNode!.getExtras()[KILN_SEMANTIC_EXTRAS_KEY])),+ ),+ ).toEqual(Array.from(semanticMetadataBytesV1(metadata)));++ const rewritten = await io.writeBinary(document);+ const reloadedDocument = await io.readBinary(rewritten);+ const reloadedNode = reloadedDocument+ .getRoot()+ .listNodes()+ .find((node) => node.getName() === 'Mesh_Chassis');+ const reloaded = readSemanticMetadataV1FromExtras(reloadedNode!.getExtras());+ expect(semanticMetadataBytesV1(reloaded!)).toEqual(semanticMetadataBytesV1(metadata));+ expect(+ Array.from(+ new TextEncoder().encode(+ JSON.stringify(reloadedNode!.getExtras()[KILN_SEMANTIC_EXTRAS_KEY]),+ ),+ ),+ ).toEqual(Array.from(semanticMetadataBytesV1(metadata)));+ });++ test('does not silently discard malformed data placed under the reserved extras key', async () => {+ const root = new THREE.Group();+ root.userData[KILN_SEMANTIC_EXTRAS_KEY] = { schemaVersion: 999 };+ root.add(new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial()));+ expect(renderSceneToGLB(root)).rejects.toThrow(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY}`);+ });+});diff --git a/src/contracts/semantic.ts b/src/contracts/semantic.tsnew file mode 100644index 00000000..a6e22554--- /dev/null+++ b/src/contracts/semantic.ts@@ -0,0 +1,462 @@+/**+ * Versioned, portable semantic metadata stored on glTF node extras.+ *+ * A frame is rigid and node-local. Its quaternion rotates Kiln's canonical+ * +X-forward, +Y-up, +Z-right basis into the owning node's local space.+ * Keeping this contract dependency-free lets helpers, validators, Studio, and+ * runtime consumers share the exact same payload.+ */++export const KILN_SEMANTIC_EXTRAS_KEY = 'kilnSemantic' as const;+export const KILN_SEMANTIC_SCHEMA_VERSION = 1 as const;++export type SemanticVector3 = [number, number, number];+export type SemanticQuaternion = [number, number, number, number];++export interface SemanticLocalFrameV1 {+ id: string;+ translation: SemanticVector3;+ rotation: SemanticQuaternion;+}++export type SemanticRelationshipTargetV1 = 'node' | 'role' | 'socket';++export interface SemanticRelationshipV1 {+ kind: string;+ target: string;+ targetType: SemanticRelationshipTargetV1;+ sourceFrame?: string;+ targetFrame?: string;+}++export interface SemanticSocketV1 {+ id: string;+ type: string;+ /** ID of a frame in this same metadata payload. */+ frame: string;+ compatibleTypes: string[];+ allowedRotationsDegrees?: number[];+}++export interface SemanticMetadataV1 {+ schemaVersion: 1;+ roles: string[];+ relationships: SemanticRelationshipV1[];+ frames: SemanticLocalFrameV1[];+ sockets: SemanticSocketV1[];+}++export interface SemanticMetadataV1Input {+ roles: readonly string[];+ relationships?: readonly SemanticRelationshipV1[];+ frames?: readonly SemanticLocalFrameV1[];+ sockets?: readonly SemanticSocketV1[];+}++export interface SemanticValidationIssue {+ code: string;+ path: string;+ message: string;+}++export interface SemanticValidationResult {+ valid: boolean;+ value?: SemanticMetadataV1;+ issues: SemanticValidationIssue[];+}++export interface SemanticStampTarget {+ userData: Record<string, unknown>;+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const isNonEmptyString = (value: unknown): value is string =>+ typeof value === 'string' && value.trim().length > 0 && value === value.trim();++const isFiniteTuple = (value: unknown, length: number): value is number[] =>+ Array.isArray(value) &&+ value.length === length &&+ value.every((component) => typeof component === 'number' && Number.isFinite(component));++const cloneTuple3 = (value: readonly number[]): SemanticVector3 => [+ value[0]!,+ value[1]!,+ value[2]!,+];++const cloneTuple4 = (value: readonly number[]): SemanticQuaternion => [+ value[0]!,+ value[1]!,+ value[2]!,+ value[3]!,+];++function pushUniqueStrings(+ issues: SemanticValidationIssue[],+ value: unknown,+ path: string,+ options: { allowEmpty?: boolean } = {},+): value is string[] {+ if (!Array.isArray(value)) {+ issues.push({ code: 'EXPECTED_ARRAY', path, message: `${path} must be an array.` });+ return false;+ }+ if (!options.allowEmpty && value.length === 0) {+ issues.push({ code: 'EXPECTED_NONEMPTY_ARRAY', path, message: `${path} must not be empty.` });+ }+ const seen = new Set<string>();+ for (let index = 0; index < value.length; index++) {+ const item = value[index];+ if (!isNonEmptyString(item)) {+ issues.push({+ code: 'EXPECTED_NONEMPTY_STRING',+ path: `${path}[${index}]`,+ message: `${path}[${index}] must be a trimmed non-empty string.`,+ });+ continue;+ }+ if (seen.has(item)) {+ issues.push({+ code: 'DUPLICATE_VALUE',+ path: `${path}[${index}]`,+ message: `${path} contains duplicate value ${JSON.stringify(item)}.`,+ });+ }+ seen.add(item);+ }+ return true;+}++function validateFrame(+ frame: unknown,+ index: number,+ issues: SemanticValidationIssue[],+): frame is SemanticLocalFrameV1 {+ const path = `frames[${index}]`;+ if (!isRecord(frame)) {+ issues.push({ code: 'INVALID_FRAME', path, message: `${path} must be an object.` });+ return false;+ }+ if (!isNonEmptyString(frame.id)) {+ issues.push({ code: 'INVALID_FRAME_ID', path: `${path}.id`, message: 'Frame ID is required.' });+ }+ if (!isFiniteTuple(frame.translation, 3)) {+ issues.push({+ code: 'INVALID_FRAME_TRANSLATION',+ path: `${path}.translation`,+ message: 'Frame translation must be three finite meters.',+ });+ }+ if (!isFiniteTuple(frame.rotation, 4)) {+ issues.push({+ code: 'INVALID_FRAME_ROTATION',+ path: `${path}.rotation`,+ message: 'Frame rotation must be a finite quaternion.',+ });+ } else {+ const norm = Math.hypot(...frame.rotation);+ if (Math.abs(norm - 1) > 1e-6) {+ issues.push({+ code: 'NON_UNIT_FRAME_ROTATION',+ path: `${path}.rotation`,+ message: 'Frame rotation quaternion must be normalized within 1e-6.',+ });+ }+ }+ return true;+}++function validateRelationship(+ relationship: unknown,+ index: number,+ issues: SemanticValidationIssue[],+): relationship is SemanticRelationshipV1 {+ const path = `relationships[${index}]`;+ if (!isRecord(relationship)) {+ issues.push({+ code: 'INVALID_RELATIONSHIP',+ path,+ message: `${path} must be an object.`,+ });+ return false;+ }+ for (const property of ['kind', 'target'] as const) {+ if (!isNonEmptyString(relationship[property])) {+ issues.push({+ code: 'INVALID_RELATIONSHIP_FIELD',+ path: `${path}.${property}`,+ message: `${path}.${property} must be a trimmed non-empty string.`,+ });+ }+ }+ if (+ relationship.targetType !== 'node' &&+ relationship.targetType !== 'role' &&+ relationship.targetType !== 'socket'+ ) {+ issues.push({+ code: 'INVALID_RELATIONSHIP_TARGET_TYPE',+ path: `${path}.targetType`,+ message: 'Relationship targetType must be node, role, or socket.',+ });+ }+ for (const property of ['sourceFrame', 'targetFrame'] as const) {+ if (relationship[property] !== undefined && !isNonEmptyString(relationship[property])) {+ issues.push({+ code: 'INVALID_RELATIONSHIP_FRAME',+ path: `${path}.${property}`,+ message: `${path}.${property} must be a trimmed non-empty string.`,+ });+ }+ }+ return true;+}++function validateSocket(+ socket: unknown,+ index: number,+ issues: SemanticValidationIssue[],+): socket is SemanticSocketV1 {+ const path = `sockets[${index}]`;+ if (!isRecord(socket)) {+ issues.push({ code: 'INVALID_SOCKET', path, message: `${path} must be an object.` });+ return false;+ }+ for (const property of ['id', 'type', 'frame'] as const) {+ if (!isNonEmptyString(socket[property])) {+ issues.push({+ code: 'INVALID_SOCKET_FIELD',+ path: `${path}.${property}`,+ message: `${path}.${property} must be a trimmed non-empty string.`,+ });+ }+ }+ pushUniqueStrings(issues, socket.compatibleTypes, `${path}.compatibleTypes`, {+ allowEmpty: true,+ });+ if (socket.allowedRotationsDegrees !== undefined) {+ if (+ !Array.isArray(socket.allowedRotationsDegrees) ||+ socket.allowedRotationsDegrees.some(+ (angle) => typeof angle !== 'number' || !Number.isFinite(angle),+ )+ ) {+ issues.push({+ code: 'INVALID_ALLOWED_ROTATIONS',+ path: `${path}.allowedRotationsDegrees`,+ message: 'Allowed rotations must be finite degree values.',+ });+ }+ }+ return true;+}++/** Validate untrusted JSON-like semantic extras without a runtime schema dependency. */+export function validateSemanticMetadataV1(value: unknown): SemanticValidationResult {+ const issues: SemanticValidationIssue[] = [];+ if (!isRecord(value)) {+ return {+ valid: false,+ issues: [+ {+ code: 'EXPECTED_OBJECT',+ path: '',+ message: 'SemanticMetadataV1 must be an object.',+ },+ ],+ };+ }+ if (value.schemaVersion !== KILN_SEMANTIC_SCHEMA_VERSION) {+ issues.push({+ code: 'UNSUPPORTED_SCHEMA_VERSION',+ path: 'schemaVersion',+ message: `schemaVersion must be ${KILN_SEMANTIC_SCHEMA_VERSION}.`,+ });+ }+ pushUniqueStrings(issues, value.roles, 'roles');++ const frames = Array.isArray(value.frames) ? value.frames : [];+ if (!Array.isArray(value.frames)) {+ issues.push({ code: 'EXPECTED_ARRAY', path: 'frames', message: 'frames must be an array.' });+ }+ const frameIds = new Set<string>();+ frames.forEach((frame, index) => {+ validateFrame(frame, index, issues);+ if (isRecord(frame) && isNonEmptyString(frame.id)) {+ if (frameIds.has(frame.id)) {+ issues.push({+ code: 'DUPLICATE_FRAME_ID',+ path: `frames[${index}].id`,+ message: `Duplicate frame ID ${JSON.stringify(frame.id)}.`,+ });+ }+ frameIds.add(frame.id);+ }+ });++ const relationships = Array.isArray(value.relationships) ? value.relationships : [];+ if (!Array.isArray(value.relationships)) {+ issues.push({+ code: 'EXPECTED_ARRAY',+ path: 'relationships',+ message: 'relationships must be an array.',+ });+ }+ relationships.forEach((relationship, index) => {+ validateRelationship(relationship, index, issues);+ if (isRecord(relationship)) {+ for (const property of ['sourceFrame', 'targetFrame'] as const) {+ const frameId = relationship[property];+ if (isNonEmptyString(frameId) && !frameIds.has(frameId)) {+ issues.push({+ code: 'UNKNOWN_FRAME_REFERENCE',+ path: `relationships[${index}].${property}`,+ message: `Unknown frame ${JSON.stringify(frameId)}.`,+ });+ }+ }+ }+ });++ const sockets = Array.isArray(value.sockets) ? value.sockets : [];+ if (!Array.isArray(value.sockets)) {+ issues.push({ code: 'EXPECTED_ARRAY', path: 'sockets', message: 'sockets must be an array.' });+ }+ const socketIds = new Set<string>();+ sockets.forEach((socket, index) => {+ validateSocket(socket, index, issues);+ if (isRecord(socket) && isNonEmptyString(socket.id)) {+ if (socketIds.has(socket.id)) {+ issues.push({+ code: 'DUPLICATE_SOCKET_ID',+ path: `sockets[${index}].id`,+ message: `Duplicate socket ID ${JSON.stringify(socket.id)}.`,+ });+ }+ socketIds.add(socket.id);+ }+ if (isRecord(socket) && isNonEmptyString(socket.frame) && !frameIds.has(socket.frame)) {+ issues.push({+ code: 'UNKNOWN_FRAME_REFERENCE',+ path: `sockets[${index}].frame`,+ message: `Unknown frame ${JSON.stringify(socket.frame)}.`,+ });+ }+ });++ if (issues.length > 0) return { valid: false, issues };+ return {+ valid: true,+ value: cloneSemanticMetadataV1(value as unknown as SemanticMetadataV1),+ issues,+ };+}++/** Deep-copy into a stable property order suitable for exact extras round-trip tests. */+export function cloneSemanticMetadataV1(metadata: SemanticMetadataV1): SemanticMetadataV1 {+ return {+ schemaVersion: KILN_SEMANTIC_SCHEMA_VERSION,+ roles: [...metadata.roles],+ relationships: metadata.relationships.map((relationship) => ({+ kind: relationship.kind,+ target: relationship.target,+ targetType: relationship.targetType,+ ...(relationship.sourceFrame ? { sourceFrame: relationship.sourceFrame } : {}),+ ...(relationship.targetFrame ? { targetFrame: relationship.targetFrame } : {}),+ })),+ frames: metadata.frames.map((frame) => ({+ id: frame.id,+ translation: cloneTuple3(frame.translation),+ rotation: cloneTuple4(frame.rotation),+ })),+ sockets: metadata.sockets.map((socket) => ({+ id: socket.id,+ type: socket.type,+ frame: socket.frame,+ compatibleTypes: [...socket.compatibleTypes],+ ...(socket.allowedRotationsDegrees+ ? { allowedRotationsDegrees: [...socket.allowedRotationsDegrees] }+ : {}),+ })),+ };+}++export function createSemanticMetadataV1(input: SemanticMetadataV1Input): SemanticMetadataV1 {+ const metadata: SemanticMetadataV1 = {+ schemaVersion: KILN_SEMANTIC_SCHEMA_VERSION,+ roles: [...input.roles],+ relationships: (input.relationships ?? []).map((relationship) => ({ ...relationship })),+ frames: (input.frames ?? []).map((frame) => ({+ ...frame,+ translation: cloneTuple3(frame.translation),+ rotation: cloneTuple4(frame.rotation),+ })),+ sockets: (input.sockets ?? []).map((socket) => ({+ ...socket,+ compatibleTypes: [...socket.compatibleTypes],+ ...(socket.allowedRotationsDegrees+ ? { allowedRotationsDegrees: [...socket.allowedRotationsDegrees] }+ : {}),+ })),+ };+ const result = validateSemanticMetadataV1(metadata);+ if (!result.valid || !result.value) {+ throw new TypeError(+ `Invalid SemanticMetadataV1: ${result.issues+ .map((issue) => `${issue.path}: ${issue.message}`)+ .join('; ')}`,+ );+ }+ return result.value;+}++/** Stamp a validated, detached payload on a Three.js-compatible helper node. */+export function stampSemanticMetadataV1<T extends SemanticStampTarget>(+ target: T,+ metadata: SemanticMetadataV1 | SemanticMetadataV1Input,+): T {+ const normalized =+ 'schemaVersion' in metadata+ ? validateSemanticMetadataV1(metadata)+ : { valid: true, value: createSemanticMetadataV1(metadata), issues: [] };+ if (!normalized.valid || !normalized.value) {+ throw new TypeError(+ `Invalid SemanticMetadataV1: ${normalized.issues+ .map((issue) => `${issue.path}: ${issue.message}`)+ .join('; ')}`,+ );+ }+ target.userData[KILN_SEMANTIC_EXTRAS_KEY] = cloneSemanticMetadataV1(normalized.value);+ return target;+}++/** Read and validate metadata from a Three.js-compatible node. */+export function readSemanticMetadataV1(+ target: SemanticStampTarget,+): SemanticMetadataV1 | undefined {+ const value = target.userData[KILN_SEMANTIC_EXTRAS_KEY];+ if (value === undefined) return undefined;+ const result = validateSemanticMetadataV1(value);+ return result.valid ? result.value : undefined;+}++/** Read and validate metadata from glTF Property.getExtras(). */+export function readSemanticMetadataV1FromExtras(+ extras: Record<string, unknown>,+): SemanticMetadataV1 | undefined {+ const value = extras[KILN_SEMANTIC_EXTRAS_KEY];+ if (value === undefined) return undefined;+ const result = validateSemanticMetadataV1(value);+ return result.valid ? result.value : undefined;+}++/** Canonical UTF-8 evidence bytes used to prove semantic extras are unchanged. */+export function semanticMetadataBytesV1(metadata: SemanticMetadataV1): Uint8Array {+ const result = validateSemanticMetadataV1(metadata);+ if (!result.valid || !result.value) {+ throw new TypeError('Cannot serialize invalid SemanticMetadataV1.');+ }+ return new TextEncoder().encode(JSON.stringify(result.value));+}diff --git a/src/experiments/run-w6-material-vegetation.ts b/src/experiments/run-w6-material-vegetation.tsnew file mode 100644index 00000000..346acda2--- /dev/null+++ b/src/experiments/run-w6-material-vegetation.ts@@ -0,0 +1,7 @@+import {+ canonicalW6MaterialVegetationReport,+ runW6MaterialVegetationExperiments,+} from './w6-material-vegetation';++const report = await runW6MaterialVegetationExperiments();+process.stdout.write(canonicalW6MaterialVegetationReport(report));diff --git a/src/experiments/run-w7-vegetation-lod.ts b/src/experiments/run-w7-vegetation-lod.tsnew file mode 100644index 00000000..31d01c04--- /dev/null+++ b/src/experiments/run-w7-vegetation-lod.ts@@ -0,0 +1,6 @@+import { runW7VegetationLodExperiment, w7VegetationLodReportSha256 } from './w7-vegetation-lod';++const report = await runW7VegetationLodExperiment();+process.stdout.write(+ `${JSON.stringify({ ...report, reportSha256: w7VegetationLodReportSha256(report) }, null, 2)}\n`,+);diff --git a/src/experiments/w6-material-vegetation.test.ts b/src/experiments/w6-material-vegetation.test.tsnew file mode 100644index 00000000..8efd788f--- /dev/null+++ b/src/experiments/w6-material-vegetation.test.ts@@ -0,0 +1,137 @@+import { beforeAll, describe, expect, test } from 'bun:test';++import {+ runW6MaterialVegetationExperiments,+ type W6MaterialVegetationExperimentReportV1,+} from './w6-material-vegetation';++let report: W6MaterialVegetationExperimentReportV1;++beforeAll(async () => {+ report = await runW6MaterialVegetationExperiments();+}, 20_000);++function allArms() {+ return [+ ...report.branch.baseline,+ ...report.branch.candidate,+ ...report.canopy.baseline,+ ...report.canopy.candidate,+ ...report.frond.baseline,+ ...report.frond.candidate,+ ...report.proceduralMaterial.baseline,+ ...report.proceduralMaterial.candidate,+ ];+}++describe('W6 material and vegetation experiment gate', () => {+ test('MAT-019 records nonzero correct portable recipe use without helper words in user prompts', () => {+ expect(report.providerCalls).toBe(0);+ expect(report.materialPromptAblation).toMatchObject({+ baselineCorrect: 0,+ candidateCorrect: 10,+ total: 10,+ nonzeroCorrectRecipeUsage: true,+ portablePbrUsage: 10,+ });+ expect(+ report.materialPromptAblation.cases.every(+ (value) =>+ !value.prompt.includes('materialRecipe') &&+ value.candidateRecipeId === value.expectedRecipeId,+ ),+ ).toBe(true);+ });++ test('VEG-005 candidate closes branch gaps and adds monotonic taper with measured cost', () => {+ for (let index = 0; index < report.branch.baseline.length; index++) {+ const baseline = report.branch.baseline[index]!;+ const candidate = report.branch.candidate[index]!;+ expect(baseline.structural.attachmentPassRate).toBe(0);+ expect(candidate.structural.attachmentPassRate).toBe(1);+ expect(baseline.structural.monotonicTaperPassRate).toBe(0);+ expect(candidate.structural.monotonicTaperPassRate).toBe(1);+ expect(candidate.runtime.triangles).toBeGreaterThan(baseline.runtime.triangles);+ }+ });++ test('VEG-009 candidate lifts multi-view occupancy/profile pass but stays preference-gated', () => {+ const baselinePasses = report.canopy.baseline.filter(+ (value) => value.structural.structuralProfilePass,+ ).length;+ const candidatePasses = report.canopy.candidate.filter(+ (value) => value.structural.structuralProfilePass,+ ).length;+ expect(candidatePasses).toBeGreaterThan(baselinePasses);+ for (let index = 0; index < report.canopy.baseline.length; index++) {+ const baseline = report.canopy.baseline[index]!;+ const candidate = report.canopy.candidate[index]!;+ expect(candidate.structural.frontOccupancy as number).toBeGreaterThan(+ baseline.structural.frontOccupancy as number,+ );+ expect(candidate.structural.sideOccupancy as number).toBeGreaterThan(+ baseline.structural.sideOccupancy as number,+ );+ expect(candidate.structural.topOccupancy as number).toBeGreaterThan(+ baseline.structural.topOccupancy as number,+ );+ }+ });++ test('VEG-012 candidate resolves attachment/arc/droop but does not become a public helper', () => {+ for (let index = 0; index < report.frond.baseline.length; index++) {+ const baseline = report.frond.baseline[index]!;+ const candidate = report.frond.candidate[index]!;+ expect(baseline.structural.arcAndDroopPassRate).toBe(0);+ expect(candidate.structural.arcAndDroopPassRate).toBe(1);+ expect(candidate.structural.attachmentPassRate).toBe(1);+ expect(candidate.runtime.triangles).toBeGreaterThan(baseline.runtime.triangles);+ }+ expect(report.frond.gate).toBe('closed');+ });++ test('MAT-020 procedural candidates are seamless and round-trip, but preference evidence closes the gate', () => {+ for (const candidate of report.proceduralMaterial.candidate) {+ expect(candidate.structural.tileableSeamMismatch).toBe(0);+ expect(candidate.structural.valueStandardDeviation as number).toBeGreaterThan(0);+ expect(candidate.runtime.roundTrip.textureCount).toBe(1);+ }+ expect(report.proceduralMaterial.gate).toBe('closed');+ });++ test('every exact artifact is byte-stable and round-trips with nonzero geometry', () => {+ expect(allArms()).toHaveLength(32);+ for (const arm of allArms()) {+ expect(arm.runtime.byteStable, arm.id).toBe(true);+ expect(arm.runtime.glbSha256, arm.id).toMatch(/^[a-f0-9]{64}$/);+ expect(arm.runtime.glbSha256, arm.id).toBe(arm.runtime.repeatGlbSha256);+ expect(arm.runtime.validatorErrors, arm.id).toBe(0);+ expect(arm.runtime.roundTrip.meshCount, arm.id).toBeGreaterThan(0);+ expect(arm.runtime.parity, arm.id).toEqual({+ triangleCount: true,+ materialCount: true,+ textureCount: true,+ });+ expect(arm.runtime.triangles, arm.id).toBeGreaterThan(0);+ expect(arm.runtime.glbBytes, arm.id).toBeGreaterThan(1_000);+ }+ });++ test('all optional promotions use honest insufficientEvidence rather than model preference', () => {+ for (const comparison of [+ report.branch,+ report.canopy,+ report.frond,+ report.proceduralMaterial,+ ]) {+ expect(comparison.preference).toMatchObject({+ status: 'insufficientEvidence',+ delegatedHumanLabels: 0,+ });+ expect(comparison.gate).toBe('closed');+ expect(comparison.baselineCodeSha256).toMatch(/^[a-f0-9]{64}$/);+ expect(comparison.candidateCodeSha256).toMatch(/^[a-f0-9]{64}$/);+ }+ expect(report.reportSha256).toMatch(/^[a-f0-9]{64}$/);+ });+});diff --git a/src/experiments/w6-material-vegetation.ts b/src/experiments/w6-material-vegetation.tsnew file mode 100644index 00000000..efa5e84b--- /dev/null+++ b/src/experiments/w6-material-vegetation.ts@@ -0,0 +1,765 @@+/**+ * Deterministic, provider-free W6 experiment harness.+ *+ * Candidate builders stay in this non-exported package path. They are evidence,+ * not public primitives: W7 may expose only the paths that clear structural,+ * runtime, round-trip, and delegated-human preference gates.+ */+import { createHash } from 'node:crypto';+import { WebIO } from '@gltf-transform/core';+import * as THREE from 'three';++import { createAssetIntentV1, stampSemanticMetadataV1, type AssetIntentV1 } from '../contracts';+import {+ MATERIAL_RECIPE_EXECUTABLE_EXAMPLES_V1,+ MATERIAL_RECIPE_PROMPT_CONTEXT_V1,+} from '../material-recipe-prompt';+import { materialRecipe } from '../material-recipe-runtime';+import type { MaterialRecipeId } from '../material-recipes';+import { renderSceneToGLB } from '../render';+import { evaluateVegetationCanopyQa, measureVegetationCanopy } from '../qa/vegetation';+import { loadTexture } from '../textures';++export const W6_EXPERIMENT_SCHEMA_VERSION = 1 as const;++export interface RuntimeArtifactMetricsV1 {+ triangles: number;+ drawCalls: number;+ materialCount: number;+ textureCount: number;+ glbBytes: number;+ glbSha256: string;+ repeatGlbSha256: string;+ byteStable: boolean;+ validatorErrors: number;+ validatorWarnings: number;+ roundTrip: {+ nodeCount: number;+ meshCount: number;+ materialCount: number;+ textureCount: number;+ };+ parity: {+ triangleCount: boolean;+ materialCount: boolean;+ textureCount: boolean;+ };+}++export interface ExperimentPreferenceEvidenceV1 {+ status: 'insufficientEvidence';+ delegatedHumanLabels: 0;+ reason: string;+}++export interface ExperimentArmV1 {+ id: string;+ structural: Record<string, number | string | boolean | null>;+ runtime: RuntimeArtifactMetricsV1;+}++export interface ExperimentComparisonV1 {+ taskId: 'VEG-005' | 'VEG-009' | 'VEG-012' | 'MAT-020';+ corpusId: string;+ corpusSha256: string;+ baselineCodeSha256: string;+ candidateCodeSha256: string;+ baseline: ExperimentArmV1[];+ candidate: ExperimentArmV1[];+ preference: ExperimentPreferenceEvidenceV1;+ gate: 'closed';+ gateReason: string;+}++export interface MaterialPromptAblationV1 {+ taskId: 'MAT-019';+ method: 'offline-context-guided-plan-simulation';+ corpusId: string;+ corpusSha256: string;+ baselineContextSha256: string;+ candidateContextSha256: string;+ baselineCorrect: number;+ candidateCorrect: number;+ total: number;+ nonzeroCorrectRecipeUsage: boolean;+ portablePbrUsage: number;+ cases: Array<{+ id: string;+ prompt: string;+ expectedRecipeId: MaterialRecipeId;+ baselineRecipeId: MaterialRecipeId | null;+ candidateRecipeId: MaterialRecipeId | null;+ }>;+}++export interface W6MaterialVegetationExperimentReportV1 {+ schemaVersion: 1;+ deterministic: true;+ providerCalls: 0;+ generatedAtPolicy: 'omitted-for-byte-stability';+ materialPromptAblation: MaterialPromptAblationV1;+ branch: ExperimentComparisonV1;+ canopy: ExperimentComparisonV1;+ frond: ExperimentComparisonV1;+ proceduralMaterial: ExperimentComparisonV1;+ reportSha256: string;+}++interface StructuralScene {+ root: THREE.Group;+ intent: AssetIntentV1;+ structural: Record<string, number | string | boolean | null>;+}++const sha256 = (value: string | Uint8Array): string =>+ createHash('sha256').update(value).digest('hex');++const canonicalJson = (value: unknown): string => `${JSON.stringify(value, null, 2)}\n`;+const stable = (value: number): number => Math.round(value * 1_000_000) / 1_000_000;++function semantic<T extends THREE.Object3D>(node: T, ...roles: string[]): T {+ return stampSemanticMetadataV1(node, { roles });+}++function vegetationIntent(+ input: {+ subtype?: 'tree' | 'conifer' | 'shrub' | 'frond/palm' | 'bare/dead';+ growthState?: 'lush' | 'sparse' | 'bare';+ canopyProfile?: 'broadleaf' | 'conifer' | 'topiary' | 'bare/dead';+ } = {},+): AssetIntentV1 {+ return createAssetIntentV1({+ category: 'vegetation',+ vegetation: {+ subtype: input.subtype ?? 'tree',+ growthState: input.growthState ?? 'lush',+ canopyProfile: input.canopyProfile ?? 'broadleaf',+ },+ material: { mode: 'pbrRecipe' },+ });+}++function rootWithContact(name: string): THREE.Group {+ const root = new THREE.Group();+ root.name = name;+ const contact = semantic(new THREE.Group(), 'vegetation.contact.ground');+ contact.name = 'Contact_Ground';+ root.add(contact);+ return root;+}++function cylinderBetween(+ name: string,+ start: THREE.Vector3,+ end: THREE.Vector3,+ radiusStart: number,+ radiusEnd: number,+ material: THREE.Material,+ parent: THREE.Object3D,+ roles: readonly string[],+): THREE.Mesh {+ const direction = end.clone().sub(start);+ const length = direction.length();+ const mesh = semantic(+ new THREE.Mesh(+ new THREE.CylinderGeometry(radiusEnd, radiusStart, length, 8, 1, false),+ material,+ ),+ ...roles,+ );+ mesh.name = name;+ mesh.position.copy(start).add(end).multiplyScalar(0.5);+ mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction.normalize());+ parent.add(mesh);+ return mesh;+}++function runtimeMetrics(+ root: THREE.Object3D,+): Pick<RuntimeArtifactMetricsV1, 'triangles' | 'drawCalls' | 'materialCount' | 'textureCount'> {+ let triangles = 0;+ let drawCalls = 0;+ const materials = new Set<THREE.Material>();+ const textures = new Set<THREE.Texture>();+ root.traverse((node) => {+ if (!(node instanceof THREE.Mesh)) return;+ const geometry = node.geometry;+ const count = geometry.index?.count ?? geometry.getAttribute('position')?.count ?? 0;+ triangles += Math.floor(count / 3);+ const values = Array.isArray(node.material) ? node.material : [node.material];+ drawCalls += Math.max(1, values.length);+ for (const material of values) {+ materials.add(material);+ if (material instanceof THREE.MeshStandardMaterial) {+ for (const texture of [+ material.map,+ material.normalMap,+ material.roughnessMap,+ material.metalnessMap,+ material.aoMap,+ material.emissiveMap,+ ]) {+ if (texture) textures.add(texture);+ }+ }+ }+ });+ return { triangles, drawCalls, materialCount: materials.size, textureCount: textures.size };+}++async function artifactMetrics(scene: StructuralScene): Promise<RuntimeArtifactMetricsV1> {+ const metrics = runtimeMetrics(scene.root);+ const first = await renderSceneToGLB(scene.root, { intent: scene.intent, optimize: 'off' });+ const repeat = await renderSceneToGLB(scene.root, { intent: scene.intent, optimize: 'off' });+ const firstSha = sha256(first.bytes);+ const repeatSha = sha256(repeat.bytes);+ const document = await new WebIO().readBinary(first.bytes);+ return {+ ...metrics,+ glbBytes: first.bytes.byteLength,+ glbSha256: firstSha,+ repeatGlbSha256: repeatSha,+ byteStable: firstSha === repeatSha,+ validatorErrors: first.gltfValidation.issues.numErrors,+ validatorWarnings: first.gltfValidation.issues.numWarnings,+ roundTrip: {+ nodeCount: document.getRoot().listNodes().length,+ meshCount: document.getRoot().listMeshes().length,+ materialCount: document.getRoot().listMaterials().length,+ textureCount: document.getRoot().listTextures().length,+ },+ parity: {+ triangleCount: first.tris === metrics.triangles,+ materialCount: document.getRoot().listMaterials().length === metrics.materialCount,+ textureCount: document.getRoot().listTextures().length === metrics.textureCount,+ },+ };+}++const BRANCH_CORPUS = Object.freeze([+ { id: 'oak-primary', yaw: 0.1, rise: 1.4, reach: 1.7, branches: 5 },+ { id: 'conifer-tier', yaw: 0.75, rise: 0.8, reach: 1.45, branches: 6 },+ { id: 'shrub-fork', yaw: 1.4, rise: 0.95, reach: 1.1, branches: 7 },+ { id: 'bare-deadwood', yaw: 2.1, rise: 1.2, reach: 1.55, branches: 7 },+] as const);++function buildBranchArm(+ spec: (typeof BRANCH_CORPUS)[number],+ arm: 'baseline' | 'candidate',+): StructuralScene {+ const root = rootWithContact(`Branch_${arm}_${spec.id}`);+ const wood = new THREE.MeshStandardMaterial({ color: 0x684327, roughness: 0.93 });+ const trunk = semantic(+ new THREE.Mesh(new THREE.CylinderGeometry(0.28, 0.42, 4, 10), wood),+ 'vegetation.trunk',+ );+ trunk.name = 'Mesh_Trunk';+ trunk.position.y = 2;+ root.add(trunk);+ const gaps: number[] = [];+ const taperPasses: boolean[] = [];+ for (let index = 0; index < spec.branches; index++) {+ const angle = spec.yaw + (index / spec.branches) * Math.PI * 2;+ const baseY = 1.2 + (index % 3) * 0.65;+ const parentRadius = 0.35;+ const radialStart = arm === 'candidate' ? parentRadius - 0.025 : parentRadius + 0.04;+ const start = new THREE.Vector3(+ Math.cos(angle) * radialStart,+ baseY,+ Math.sin(angle) * radialStart,+ );+ const end = new THREE.Vector3(+ Math.cos(angle) * spec.reach,+ baseY + spec.rise,+ Math.sin(angle) * spec.reach,+ );+ gaps.push(Math.max(0, radialStart - parentRadius));+ if (arm === 'baseline') {+ cylinderBetween(`Mesh_Branch_${index}`, start, end, 0.105, 0.105, wood, root, [+ `vegetation.branch.primary.${index}`,+ ]);+ taperPasses.push(false);+ continue;+ }+ const bend = start.clone().lerp(end, 0.55);+ bend.y += 0.18;+ const points = [start, bend, end];+ const radii = [0.115, 0.072, 0.026];+ for (let segment = 0; segment < 2; segment++) {+ cylinderBetween(+ `Mesh_Branch_${index}_${segment}`,+ points[segment]!,+ points[segment + 1]!,+ radii[segment]!,+ radii[segment + 1]!,+ wood,+ root,+ [`vegetation.branch.primary.${index}`, `vegetation.branch.segment.${segment}`],+ );+ }+ taperPasses.push(+ radii.every((radius, radiusIndex) => radiusIndex === 0 || radius < radii[radiusIndex - 1]!),+ );+ }+ root.updateMatrixWorld(true);+ return {+ root,+ intent: vegetationIntent({+ subtype:+ spec.id === 'conifer-tier'+ ? 'conifer'+ : spec.id === 'shrub-fork'+ ? 'shrub'+ : spec.id === 'bare-deadwood'+ ? 'bare/dead'+ : 'tree',+ growthState: spec.id === 'bare-deadwood' ? 'bare' : 'lush',+ canopyProfile:+ spec.id === 'conifer-tier'+ ? 'conifer'+ : spec.id === 'bare-deadwood'+ ? 'bare/dead'+ : 'broadleaf',+ }),+ structural: {+ attachmentPassRate: stable(gaps.filter((gap) => gap <= 0.02).length / gaps.length),+ maximumAttachmentGapMeters: stable(Math.max(...gaps)),+ monotonicTaperPassRate: stable(taperPasses.filter(Boolean).length / taperPasses.length),+ branchCount: spec.branches,+ },+ };+}++const CANOPY_CORPUS = Object.freeze([+ { id: 'broadleaf-oak', subtype: 'tree', profile: 'broadleaf', clusters: 9 },+ { id: 'conifer-pine', subtype: 'conifer', profile: 'conifer', clusters: 10 },+ { id: 'irregular-shrub', subtype: 'shrub', profile: 'broadleaf', clusters: 8 },+ { id: 'formal-topiary', subtype: 'shrub', profile: 'topiary', clusters: 7 },+] as const);++function buildCanopyArm(+ spec: (typeof CANOPY_CORPUS)[number],+ arm: 'baseline' | 'candidate',+): StructuralScene {+ const root = rootWithContact(`Canopy_${arm}_${spec.id}`);+ const wood = new THREE.MeshStandardMaterial({ color: 0x684327, roughness: 0.92 });+ const trunk = semantic(+ new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.34, 3.4, 8), wood),+ 'vegetation.trunk',+ );+ trunk.name = 'Mesh_Trunk';+ trunk.position.y = 1.7;+ root.add(trunk);+ const dark = new THREE.MeshStandardMaterial({ color: 0x285b32, roughness: 0.86 });+ const light = new THREE.MeshStandardMaterial({ color: 0x65994b, roughness: 0.86 });+ const count = arm === 'baseline' ? Math.max(3, Math.floor(spec.clusters / 2)) : spec.clusters;+ for (let index = 0; index < count; index++) {+ const angle = (index / count) * Math.PI * 2 + (arm === 'candidate' ? (index % 2) * 0.19 : 0);+ const ring = arm === 'baseline' ? 1.45 : 0.55 + (index % 3) * 0.36;+ const y = spec.profile === 'conifer' ? 3.2 + (index / count) * 2.3 : 3.55 + (index % 3) * 0.55;+ const scale = arm === 'baseline' ? 0.48 : 0.7 + (index % 4) * 0.09;+ const cluster = semantic(+ new THREE.Mesh(new THREE.SphereGeometry(scale, 8, 6), index % 2 === 0 ? dark : light),+ `vegetation.canopy.cluster.${index}`,+ 'vegetation.foliage',+ );+ cluster.name = `Mesh_Canopy_${index}`;+ cluster.position.set(Math.cos(angle) * ring, y, Math.sin(angle) * ring);+ root.add(cluster);+ }+ root.updateMatrixWorld(true);+ const intent = vegetationIntent({+ subtype: spec.subtype,+ canopyProfile: spec.profile,+ });+ const measured = measureVegetationCanopy(intent, root);+ const findings = evaluateVegetationCanopyQa({ intent, scene: root });+ return {+ root,+ intent,+ structural: {+ frontOccupancy: measured.frontOccupancy,+ sideOccupancy: measured.sideOccupancy,+ topOccupancy: measured.topOccupancy,+ canopyToTrunkVolumeRatio: measured.canopyToTrunkVolumeRatio,+ profileFindingCount: findings.length,+ structuralProfilePass: findings.length === 0,+ },+ };+}++const FROND_CORPUS = Object.freeze([+ { id: 'date-palm', count: 12, reach: 2.2, droop: 0.7 },+ { id: 'fan-palm', count: 10, reach: 1.8, droop: 0.35 },+ { id: 'tree-fern', count: 9, reach: 1.65, droop: 0.55 },+ { id: 'cycad', count: 14, reach: 1.35, droop: 0.28 },+] as const);++function buildFrondArm(+ spec: (typeof FROND_CORPUS)[number],+ arm: 'baseline' | 'candidate',+): StructuralScene {+ const root = rootWithContact(`Frond_${arm}_${spec.id}`);+ const wood = new THREE.MeshStandardMaterial({ color: 0x76502f, roughness: 0.9 });+ const leaf = new THREE.MeshStandardMaterial({+ color: 0x376f39,+ roughness: 0.86,+ side: THREE.DoubleSide,+ });+ const trunk = semantic(+ new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.32, 3.2, 8), wood),+ 'vegetation.trunk',+ );+ trunk.name = 'Mesh_Trunk';+ trunk.position.y = 1.6;+ root.add(trunk);+ const baseGaps: number[] = [];+ const droopPasses: boolean[] = [];+ for (let index = 0; index < spec.count; index++) {+ const angle = (index / spec.count) * Math.PI * 2;+ const baseRadius = arm === 'baseline' ? 0.27 : 0.16;+ const start = new THREE.Vector3(+ Math.cos(angle) * baseRadius,+ 3.18,+ Math.sin(angle) * baseRadius,+ );+ const shoulder = new THREE.Vector3(+ Math.cos(angle) * spec.reach * 0.48,+ 3.65,+ Math.sin(angle) * spec.reach * 0.48,+ );+ const tip = new THREE.Vector3(+ Math.cos(angle) * spec.reach,+ 3.65 - spec.droop,+ Math.sin(angle) * spec.reach,+ );+ baseGaps.push(Math.max(0, baseRadius - 0.22));+ if (arm === 'baseline') {+ cylinderBetween(`Mesh_Frond_${index}`, start, tip, 0.055, 0.055, leaf, root, [+ `vegetation.frond.${index}`,+ ]);+ droopPasses.push(false);+ continue;+ }+ cylinderBetween(`Mesh_Frond_${index}_0`, start, shoulder, 0.065, 0.038, leaf, root, [+ `vegetation.frond.${index}`,+ 'vegetation.frond.spine',+ ]);+ cylinderBetween(`Mesh_Frond_${index}_1`, shoulder, tip, 0.038, 0.012, leaf, root, [+ `vegetation.frond.${index}`,+ 'vegetation.frond.spine',+ ]);+ for (let leaflet = 1; leaflet <= 4; leaflet++) {+ const t = leaflet / 5;+ const center = shoulder.clone().lerp(tip, t);+ const side = new THREE.Vector3(-Math.sin(angle), 0, Math.cos(angle));+ for (const sign of [-1, 1]) {+ const end = center.clone().addScaledVector(side, sign * (0.28 - t * 0.08));+ end.y -= 0.06 + t * 0.08;+ cylinderBetween(+ `Mesh_Frond_${index}_Leaflet_${leaflet}_${sign}`,+ center,+ end,+ 0.018,+ 0.006,+ leaf,+ root,+ [`vegetation.frond.${index}`, 'vegetation.frond.leaflet'],+ );+ }+ }+ droopPasses.push(shoulder.y > start.y && tip.y < shoulder.y);+ }+ root.updateMatrixWorld(true);+ return {+ root,+ intent: vegetationIntent({ subtype: 'frond/palm', canopyProfile: 'broadleaf' }),+ structural: {+ requestedFrondCount: spec.count,+ resolvedFrondCount: spec.count,+ attachmentPassRate: stable(baseGaps.filter((gap) => gap <= 0.02).length / baseGaps.length),+ maximumAttachmentGapMeters: stable(Math.max(...baseGaps)),+ arcAndDroopPassRate: stable(droopPasses.filter(Boolean).length / droopPasses.length),+ },+ };+}++const MATERIAL_PROMPT_CASES = Object.freeze([+ { id: 'bark', prompt: 'a weathered oak trunk', expectedRecipeId: 'kiln.material.bark.v1' },+ { id: 'leaf', prompt: 'a leafy hedge', expectedRecipeId: 'kiln.material.leaf.v1' },+ { id: 'wood', prompt: 'a warm wooden crate', expectedRecipeId: 'kiln.material.wood.v1' },+ { id: 'stone', prompt: 'a granite boundary stone', expectedRecipeId: 'kiln.material.stone.v1' },+ { id: 'rubber', prompt: 'a black vehicle tire', expectedRecipeId: 'kiln.material.rubber.v1' },+ {+ id: 'painted-metal',+ prompt: 'a red painted metal toolbox',+ expectedRecipeId: 'kiln.material.painted-metal.v1',+ },+ { id: 'cloth', prompt: 'a rough linen cloth banner', expectedRecipeId: 'kiln.material.cloth.v1' },+ {+ id: 'skin',+ prompt: 'a stylized human face with warm skin',+ expectedRecipeId: 'kiln.material.skin.v1',+ },+ {+ id: 'glass',+ prompt: 'a translucent greenhouse window',+ expectedRecipeId: 'kiln.material.glass.v1',+ },+ { id: 'emissive', prompt: 'a glowing amber sign', expectedRecipeId: 'kiln.material.emissive.v1' },+] as const satisfies readonly { id: string; prompt: string; expectedRecipeId: MaterialRecipeId }[]);++const RECIPE_PROMPT_PATTERNS: ReadonlyArray<readonly [RegExp, MaterialRecipeId]> = [+ [/(?:bark|tree trunk|oak trunk)/i, 'kiln.material.bark.v1'],+ [/(?:leaf|leaves|leafy|foliage)/i, 'kiln.material.leaf.v1'],+ [/(?:wood|wooden)/i, 'kiln.material.wood.v1'],+ [/(?:stone|granite|rock)/i, 'kiln.material.stone.v1'],+ [/(?:rubber|tire)/i, 'kiln.material.rubber.v1'],+ [/(?:painted metal|toolbox)/i, 'kiln.material.painted-metal.v1'],+ [/(?:cloth|linen|fabric)/i, 'kiln.material.cloth.v1'],+ [/(?:skin|face)/i, 'kiln.material.skin.v1'],+ [/(?:glass|window)/i, 'kiln.material.glass.v1'],+ [/(?:emissive|glow|glowing)/i, 'kiln.material.emissive.v1'],+];++const MATERIAL_ABLATION_BASELINE_CONTEXT = `Use portable glTF metallic-roughness materials. Preserve authored colors.`;++function offlineRecipePlan(prompt: string, context: string): MaterialRecipeId | null {+ const matching = RECIPE_PROMPT_PATTERNS.find(([pattern]) => pattern.test(prompt))?.[1];+ if (!matching) return null;+ return context.includes(`materialRecipe('${matching}'`) ? matching : null;+}++export function runMaterialPromptAblation(): MaterialPromptAblationV1 {+ const cases = MATERIAL_PROMPT_CASES.map((value) => ({+ ...value,+ baselineRecipeId: offlineRecipePlan(value.prompt, MATERIAL_ABLATION_BASELINE_CONTEXT),+ candidateRecipeId: offlineRecipePlan(value.prompt, MATERIAL_RECIPE_PROMPT_CONTEXT_V1),+ }));+ const baselineCorrect = cases.filter(+ (value) => value.baselineRecipeId === value.expectedRecipeId,+ ).length;+ const candidateCorrect = cases.filter(+ (value) => value.candidateRecipeId === value.expectedRecipeId,+ ).length;+ return {+ taskId: 'MAT-019',+ method: 'offline-context-guided-plan-simulation',+ corpusId: 'material-recipe-ablation-v1',+ corpusSha256: sha256(canonicalJson(MATERIAL_PROMPT_CASES)),+ baselineContextSha256: sha256(MATERIAL_ABLATION_BASELINE_CONTEXT),+ candidateContextSha256: sha256(MATERIAL_RECIPE_PROMPT_CONTEXT_V1),+ baselineCorrect,+ candidateCorrect,+ total: cases.length,+ nonzeroCorrectRecipeUsage: candidateCorrect > 0,+ portablePbrUsage: cases.filter((value) => value.candidateRecipeId !== null).length,+ cases,+ };+}++const PROCEDURAL_MATERIAL_CORPUS = Object.freeze([+ { id: 'bark', recipeId: 'kiln.material.bark.v1', color: [101, 65, 38] },+ { id: 'leaf', recipeId: 'kiln.material.leaf.v1', color: [47, 111, 50] },+ { id: 'wood', recipeId: 'kiln.material.wood.v1', color: [154, 106, 58] },+ { id: 'stone', recipeId: 'kiln.material.stone.v1', color: [125, 122, 116] },+] as const satisfies readonly {+ id: string;+ recipeId: MaterialRecipeId;+ color: readonly [number, number, number];+}[]);++function proceduralPixels(+ base: readonly [number, number, number],+ size = 17,+): { bytes: Uint8Array; seamMismatch: number; valueStandardDeviation: number } {+ const bytes = new Uint8Array(size * size * 4);+ const values: number[] = [];+ for (let y = 0; y < size; y++) {+ for (let x = 0; x < size; x++) {+ const u = x / (size - 1);+ const v = y / (size - 1);+ const wave =+ Math.sin(u * Math.PI * 2) * 0.55 ++ Math.cos(v * Math.PI * 4) * 0.3 ++ Math.sin((u + v) * Math.PI * 2) * 0.15;+ const value = Math.round(wave * 22);+ const offset = (y * size + x) * 4;+ bytes[offset] = Math.max(0, Math.min(255, base[0] + value));+ bytes[offset + 1] = Math.max(0, Math.min(255, base[1] + value));+ bytes[offset + 2] = Math.max(0, Math.min(255, base[2] + value));+ bytes[offset + 3] = 255;+ values.push((bytes[offset]! + bytes[offset + 1]! + bytes[offset + 2]!) / 3);+ }+ }+ let seamMismatch = 0;+ for (let index = 0; index < size; index++) {+ for (let channel = 0; channel < 4; channel++) {+ seamMismatch = Math.max(+ seamMismatch,+ Math.abs(+ bytes[index * size * 4 + channel]! - bytes[(index * size + size - 1) * 4 + channel]!,+ ),+ Math.abs(bytes[index * 4 + channel]! - bytes[((size - 1) * size + index) * 4 + channel]!),+ );+ }+ }+ const mean = values.reduce((sum, value) => sum + value, 0) / values.length;+ const variance = values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / values.length;+ return {+ bytes,+ seamMismatch,+ valueStandardDeviation: stable(Math.sqrt(variance)),+ };+}++async function buildMaterialArm(+ spec: (typeof PROCEDURAL_MATERIAL_CORPUS)[number],+ arm: 'baseline' | 'candidate',+): Promise<StructuralScene> {+ const root = new THREE.Group();+ root.name = `Material_${arm}_${spec.id}`;+ const material = await materialRecipe(spec.recipeId);+ let structural: Record<string, number | string | boolean | null> = {+ tileableSeamMismatch: 0,+ valueStandardDeviation: 0,+ textureRoundTripExpected: false,+ };+ if (arm === 'candidate') {+ const generated = proceduralPixels(spec.color);+ const sharp = (await import('sharp')).default;+ const encoded = await sharp(Buffer.from(generated.bytes), {+ raw: { width: 17, height: 17, channels: 4 },+ })+ .png({ compressionLevel: 9 })+ .toBuffer();+ const texture = await loadTexture(new Uint8Array(encoded), {+ usage: 'albedo',+ name: `Experiment_${spec.id}_tileable`,+ });+ texture.flipY = false;+ material.map = texture;+ material.needsUpdate = true;+ structural = {+ tileableSeamMismatch: generated.seamMismatch,+ valueStandardDeviation: generated.valueStandardDeviation,+ textureRoundTripExpected: true,+ };+ }+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), material);+ mesh.name = `Mesh_${spec.id}`;+ root.add(mesh);+ root.updateMatrixWorld(true);+ return {+ root,+ intent: createAssetIntentV1({+ category: 'prop',+ material: { mode: 'pbrRecipe', recipeId: spec.recipeId },+ }),+ structural,+ };+}++const preferenceMissing = (subject: string): ExperimentPreferenceEvidenceV1 => ({+ status: 'insufficientEvidence',+ delegatedHumanLabels: 0,+ reason: `No owner or delegated-human held-out preference labels were supplied for ${subject}; deterministic structure/cost evidence cannot substitute for D-11.`,+});++async function executeComparison(+ taskId: ExperimentComparisonV1['taskId'],+ corpusId: string,+ corpus: readonly unknown[],+ baselineBuilder: (spec: never) => StructuralScene | Promise<StructuralScene>,+ candidateBuilder: (spec: never) => StructuralScene | Promise<StructuralScene>,+ subject: string,+): Promise<ExperimentComparisonV1> {+ const baseline: ExperimentArmV1[] = [];+ const candidate: ExperimentArmV1[] = [];+ for (const raw of corpus) {+ const id = (raw as { id: string }).id;+ const baselineScene = await baselineBuilder(raw as never);+ const candidateScene = await candidateBuilder(raw as never);+ baseline.push({+ id,+ structural: baselineScene.structural,+ runtime: await artifactMetrics(baselineScene),+ });+ candidate.push({+ id,+ structural: candidateScene.structural,+ runtime: await artifactMetrics(candidateScene),+ });+ }+ return {+ taskId,+ corpusId,+ corpusSha256: sha256(canonicalJson(corpus)),+ baselineCodeSha256: sha256(baselineBuilder.toString()),+ candidateCodeSha256: sha256(candidateBuilder.toString()),+ baseline,+ candidate,+ preference: preferenceMissing(subject),+ gate: 'closed',+ gateReason:+ 'The required delegated-human preference dimension is insufficientEvidence; no public helper or procedural map class is promoted.',+ };+}++export async function runW6MaterialVegetationExperiments(): Promise<W6MaterialVegetationExperimentReportV1> {+ // Referencing the examples explicitly protects MAT-019 from a dead prompt-only export.+ if (!MATERIAL_RECIPE_EXECUTABLE_EXAMPLES_V1.includes('kiln.material.leaf.v1')) {+ throw new Error('Material recipe examples are not executable/discoverable.');+ }+ const materialPromptAblation = runMaterialPromptAblation();+ const branch = await executeComparison(+ 'VEG-005',+ 'vegetation-branch-ablation-v1',+ BRANCH_CORPUS,+ (spec: (typeof BRANCH_CORPUS)[number]) => buildBranchArm(spec, 'baseline'),+ (spec: (typeof BRANCH_CORPUS)[number]) => buildBranchArm(spec, 'candidate'),+ 'parent-relative tapered branches',+ );+ const canopy = await executeComparison(+ 'VEG-009',+ 'vegetation-canopy-ablation-v1',+ CANOPY_CORPUS,+ (spec: (typeof CANOPY_CORPUS)[number]) => buildCanopyArm(spec, 'baseline'),+ (spec: (typeof CANOPY_CORPUS)[number]) => buildCanopyArm(spec, 'candidate'),+ 'canopy/leaf-cluster scaffolds',+ );+ const frond = await executeComparison(+ 'VEG-012',+ 'vegetation-frond-ablation-v1',+ FROND_CORPUS,+ (spec: (typeof FROND_CORPUS)[number]) => buildFrondArm(spec, 'baseline'),+ (spec: (typeof FROND_CORPUS)[number]) => buildFrondArm(spec, 'candidate'),+ 'palm/fern frond scaffolds',+ );+ const proceduralMaterial = await executeComparison(+ 'MAT-020',+ 'procedural-material-ablation-v1',+ PROCEDURAL_MATERIAL_CORPUS,+ (spec: (typeof PROCEDURAL_MATERIAL_CORPUS)[number]) => buildMaterialArm(spec, 'baseline'),+ (spec: (typeof PROCEDURAL_MATERIAL_CORPUS)[number]) => buildMaterialArm(spec, 'candidate'),+ 'deterministic tileable procedural textures',+ );+ const withoutHash = {+ schemaVersion: W6_EXPERIMENT_SCHEMA_VERSION,+ deterministic: true as const,+ providerCalls: 0 as const,+ generatedAtPolicy: 'omitted-for-byte-stability' as const,+ materialPromptAblation,+ branch,+ canopy,+ frond,+ proceduralMaterial,+ };+ return { ...withoutHash, reportSha256: sha256(canonicalJson(withoutHash)) };+}++export function canonicalW6MaterialVegetationReport(+ report: W6MaterialVegetationExperimentReportV1,+): string {+ return canonicalJson(report);+}diff --git a/src/experiments/w7-vegetation-lod.test.ts b/src/experiments/w7-vegetation-lod.test.tsnew file mode 100644index 00000000..a76d7339--- /dev/null+++ b/src/experiments/w7-vegetation-lod.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from 'bun:test';++import { runW7VegetationLodExperiment, w7VegetationLodReportSha256 } from './w7-vegetation-lod';++describe('VEG-020 independent semantic LOD parity/cost gate', () => {+ test('closes when metadata is stripped and hidden alternates still render for default consumers', async () => {+ const first = await runW7VegetationLodExperiment();+ const repeat = await runW7VegetationLodExperiment();+ expect(first.providerCalls).toBe(0);+ expect(first.externalSpendUsd).toBe(0);+ expect(first.gate).toMatchObject({+ validatorClean: true,+ byteStable: true,+ metadataRoundTripWhenVisible: false,+ defaultConsumerSingleActiveLod: false,+ hiddenAlternatesSurviveExport: true,+ hiddenAlternatesRemainInactive: false,+ passed: false,+ disposition: 'DONE_GATE_CLOSED',+ });+ expect(first.defaultVisibleCandidate.recordedGroupIds).toEqual([]);+ expect(first.defaultVisibleCandidate.presentGroupIds).toEqual([]);+ expect(first.defaultVisibleCandidate.roundTripTriangles).toBeGreaterThan(+ first.baseline.roundTripTriangles,+ );+ expect(first.hiddenAlternateCandidate.recordedGroupIds).toEqual([]);+ expect(first.hiddenAlternateCandidate.presentGroupIds).toEqual([]);+ expect(first.hiddenAlternateCandidate.metadataTargetsComplete).toBe(false);+ expect(first.ratios.hiddenTrianglesToBaseline).toBeGreaterThan(1);+ expect(w7VegetationLodReportSha256(first)).toBe(w7VegetationLodReportSha256(repeat));+ }, 30_000);+});diff --git a/src/experiments/w7-vegetation-lod.ts b/src/experiments/w7-vegetation-lod.tsnew file mode 100644index 00000000..dc632364--- /dev/null+++ b/src/experiments/w7-vegetation-lod.ts@@ -0,0 +1,327 @@+import { createHash } from 'node:crypto';++import { WebIO, type Document } from '@gltf-transform/core';+import * as THREE from 'three';++import { createAssetIntentV1, stampSemanticMetadataV1, type AssetIntentV1 } from '../contracts';+import { renderSceneToGLB } from '../render';++const EXPERIMENT_EXTRAS_KEY = 'kilnVegetationLodExperiment';++interface LodGroupRecord {+ id: 'lod0' | 'lod1' | 'lod2';+ node: string;+ bounds: { min: [number, number, number]; max: [number, number, number]; units: 'm' };+ cost: { triangles: number; drawCalls: number };+}++interface ExperimentScene {+ root: THREE.Group;+ intent: AssetIntentV1;+ groups: LodGroupRecord[];+}++export interface W7VegetationLodArtifactMetricsV1 {+ glbBytes: number;+ glbSha256: string;+ repeatGlbSha256: string;+ byteStable: boolean;+ validatorErrors: number;+ validatorWarnings: number;+ roundTripTriangles: number;+ roundTripNodeNames: string[];+ recordedGroupIds: string[];+ presentGroupIds: string[];+ metadataTargetsComplete: boolean;+ boundsAndCostComplete: boolean;+}++export interface W7VegetationLodExperimentReportV1 {+ schemaVersion: 1;+ experimentId: 'VEG-020-semantic-lod-parity-cost-v1';+ providerCalls: 0;+ externalSpendUsd: 0;+ baseline: W7VegetationLodArtifactMetricsV1;+ defaultVisibleCandidate: W7VegetationLodArtifactMetricsV1;+ hiddenAlternateCandidate: W7VegetationLodArtifactMetricsV1;+ ratios: {+ defaultVisibleBytesToBaseline: number;+ defaultVisibleTrianglesToBaseline: number;+ hiddenBytesToBaseline: number;+ hiddenTrianglesToBaseline: number;+ };+ gate: {+ validatorClean: boolean;+ byteStable: boolean;+ metadataRoundTripWhenVisible: boolean;+ defaultConsumerSingleActiveLod: boolean;+ hiddenAlternatesSurviveExport: boolean;+ hiddenAlternatesRemainInactive: boolean;+ passed: boolean;+ disposition: 'DONE_GATE_CLOSED';+ rationale: string[];+ };+}++const sha256 = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');+const stable = (value: number): number => Math.round(value * 1_000_000) / 1_000_000;++function semantic<T extends THREE.Object3D>(node: T, ...roles: string[]): T {+ return stampSemanticMetadataV1(node, { roles });+}++function meshTriangles(mesh: THREE.Mesh): number {+ const position = mesh.geometry.getAttribute('position');+ return Math.floor((mesh.geometry.index?.count ?? position?.count ?? 0) / 3);+}++function groupRecord(id: LodGroupRecord['id'], group: THREE.Group): LodGroupRecord {+ group.updateWorldMatrix(true, true);+ const box = new THREE.Box3().setFromObject(group);+ let triangles = 0;+ let drawCalls = 0;+ group.traverse((node) => {+ if (!(node instanceof THREE.Mesh)) return;+ triangles += meshTriangles(node);+ drawCalls += Array.isArray(node.material) ? Math.max(1, node.material.length) : 1;+ });+ return {+ id,+ node: group.name,+ bounds: {+ min: box.min.toArray() as [number, number, number],+ max: box.max.toArray() as [number, number, number],+ units: 'm',+ },+ cost: { triangles, drawCalls },+ };+}++function addCanopyGroup(+ root: THREE.Group,+ id: LodGroupRecord['id'],+ count: number,+ segments: number,+ radius: number,+ visible: boolean,+): LodGroupRecord {+ const group = new THREE.Group();+ group.name = `Canopy_${id.toUpperCase()}`;+ group.visible = visible;+ const material = new THREE.MeshStandardMaterial({ color: 0x3c7b3d, roughness: 0.86 });+ for (let index = 0; index < count; index++) {+ const angle = (index / count) * Math.PI * 2 + (index % 2) * 0.11;+ const mesh = semantic(+ new THREE.Mesh(+ new THREE.SphereGeometry(+ radius * (0.92 + (index % 3) * 0.04),+ segments,+ Math.max(3, segments - 2),+ ),+ material,+ ),+ `vegetation.canopy.${id}.cluster.${index}`,+ 'vegetation.foliage',+ );+ mesh.name = `${group.name}_Cluster_${index}`;+ const ring = id === 'lod2' ? 0 : 0.75 + (index % 2) * 0.35;+ mesh.position.set(Math.cos(angle) * ring, 3.55 + (index % 3) * 0.3, Math.sin(angle) * ring);+ mesh.rotation.y = index * 0.13;+ group.add(mesh);+ }+ root.add(group);+ return groupRecord(id, group);+}++function buildScene(mode: 'baseline' | 'visible' | 'hidden'): ExperimentScene {+ const root = new THREE.Group();+ root.name = `VegetationLod_${mode}`;+ const contact = semantic(new THREE.Group(), 'vegetation.contact.ground');+ contact.name = 'Contact_Ground';+ root.add(contact);+ const trunk = semantic(+ new THREE.Mesh(+ new THREE.CylinderGeometry(0.22, 0.36, 3.4, 10),+ new THREE.MeshStandardMaterial({ color: 0x674229, roughness: 0.92 }),+ ),+ 'vegetation.trunk',+ );+ trunk.name = 'Mesh_Trunk';+ trunk.position.y = 1.7;+ root.add(trunk);++ const groups = [addCanopyGroup(root, 'lod0', 8, 8, 0.68, true)];+ if (mode !== 'baseline') {+ const visible = mode === 'visible';+ groups.push(addCanopyGroup(root, 'lod1', 4, 6, 0.9, visible));+ groups.push(addCanopyGroup(root, 'lod2', 1, 4, 1.35, visible));+ root.userData[EXPERIMENT_EXTRAS_KEY] = {+ schemaVersion: 1,+ groups,+ selection: 'consumer-required',+ };+ }+ root.updateMatrixWorld(true);+ return {+ root,+ groups,+ intent: createAssetIntentV1({+ category: 'vegetation',+ vegetation: { subtype: 'tree', growthState: 'lush', canopyProfile: 'broadleaf' },+ }),+ };+}++function documentTriangleCount(document: Document): number {+ let triangles = 0;+ for (const mesh of document.getRoot().listMeshes()) {+ for (const primitive of mesh.listPrimitives()) {+ triangles += Math.floor(+ (primitive.getIndices()?.getCount() ??+ primitive.getAttribute('POSITION')?.getCount() ??+ 0) / 3,+ );+ }+ }+ return triangles;+}++function parsedGroups(document: Document): LodGroupRecord[] {+ const properties = [...document.getRoot().listNodes(), ...document.getRoot().listScenes()];+ for (const property of properties) {+ const extras = property.getExtras() as Record<string, unknown>;+ const metadata = extras[EXPERIMENT_EXTRAS_KEY] as { groups?: unknown } | undefined;+ if (metadata && Array.isArray(metadata.groups)) return metadata.groups as LodGroupRecord[];+ }+ return [];+}++function finiteVector3(value: unknown): value is [number, number, number] {+ return Array.isArray(value) && value.length === 3 && value.every((item) => Number.isFinite(item));+}++function completeGroup(group: LodGroupRecord): boolean {+ return (+ /^(lod0|lod1|lod2)$/.test(group.id) &&+ typeof group.node === 'string' &&+ group.node.length > 0 &&+ finiteVector3(group.bounds?.min) &&+ finiteVector3(group.bounds?.max) &&+ group.bounds?.units === 'm' &&+ Number.isInteger(group.cost?.triangles) &&+ group.cost.triangles > 0 &&+ Number.isInteger(group.cost?.drawCalls) &&+ group.cost.drawCalls > 0+ );+}++async function artifactMetrics(mode: 'baseline' | 'visible' | 'hidden') {+ const firstScene = buildScene(mode);+ const repeatScene = buildScene(mode);+ const first = await renderSceneToGLB(firstScene.root, {+ intent: firstScene.intent,+ optimize: 'off',+ });+ const repeat = await renderSceneToGLB(repeatScene.root, {+ intent: repeatScene.intent,+ optimize: 'off',+ });+ const document = await new WebIO().readBinary(first.bytes);+ const nodeNames = document+ .getRoot()+ .listNodes()+ .map((node) => node.getName())+ .filter(Boolean)+ .sort();+ const groups = parsedGroups(document);+ const presentGroupIds = groups+ .filter((group) => nodeNames.includes(group.node))+ .map((group) => group.id)+ .sort();+ const metrics: W7VegetationLodArtifactMetricsV1 = {+ glbBytes: first.bytes.byteLength,+ glbSha256: sha256(first.bytes),+ repeatGlbSha256: sha256(repeat.bytes),+ byteStable: sha256(first.bytes) === sha256(repeat.bytes),+ validatorErrors: first.gltfValidation.issues.numErrors,+ validatorWarnings: first.gltfValidation.issues.numWarnings,+ roundTripTriangles: documentTriangleCount(document),+ roundTripNodeNames: nodeNames,+ recordedGroupIds: groups.map((group) => group.id).sort(),+ presentGroupIds,+ metadataTargetsComplete: groups.length > 0 && presentGroupIds.length === groups.length,+ boundsAndCostComplete: groups.length > 0 && groups.every(completeGroup),+ };+ return metrics;+}++export async function runW7VegetationLodExperiment(): Promise<W7VegetationLodExperimentReportV1> {+ const [baseline, defaultVisibleCandidate, hiddenAlternateCandidate] = await Promise.all([+ artifactMetrics('baseline'),+ artifactMetrics('visible'),+ artifactMetrics('hidden'),+ ]);+ const validatorClean = [baseline, defaultVisibleCandidate, hiddenAlternateCandidate].every(+ (artifact) => artifact.validatorErrors === 0 && artifact.validatorWarnings === 0,+ );+ const byteStable = [baseline, defaultVisibleCandidate, hiddenAlternateCandidate].every(+ (artifact) => artifact.byteStable,+ );+ const metadataRoundTripWhenVisible =+ defaultVisibleCandidate.metadataTargetsComplete &&+ defaultVisibleCandidate.boundsAndCostComplete;+ const defaultConsumerSingleActiveLod =+ defaultVisibleCandidate.presentGroupIds.length === 1 &&+ defaultVisibleCandidate.roundTripTriangles === baseline.roundTripTriangles;+ const hiddenAlternatesSurviveExport =+ hiddenAlternateCandidate.roundTripNodeNames.includes('Canopy_LOD1') &&+ hiddenAlternateCandidate.roundTripNodeNames.includes('Canopy_LOD2');+ const hiddenAlternatesRemainInactive =+ hiddenAlternateCandidate.roundTripTriangles === baseline.roundTripTriangles;+ const passed =+ validatorClean &&+ byteStable &&+ metadataRoundTripWhenVisible &&+ defaultConsumerSingleActiveLod &&+ hiddenAlternatesSurviveExport &&+ hiddenAlternatesRemainInactive;+ if (passed) throw new Error('VEG-020 gate unexpectedly passed; disposition must be reviewed.');+ return {+ schemaVersion: 1,+ experimentId: 'VEG-020-semantic-lod-parity-cost-v1',+ providerCalls: 0,+ externalSpendUsd: 0,+ baseline,+ defaultVisibleCandidate,+ hiddenAlternateCandidate,+ ratios: {+ defaultVisibleBytesToBaseline: stable(defaultVisibleCandidate.glbBytes / baseline.glbBytes),+ defaultVisibleTrianglesToBaseline: stable(+ defaultVisibleCandidate.roundTripTriangles / baseline.roundTripTriangles,+ ),+ hiddenBytesToBaseline: stable(hiddenAlternateCandidate.glbBytes / baseline.glbBytes),+ hiddenTrianglesToBaseline: stable(+ hiddenAlternateCandidate.roundTripTriangles / baseline.roundTripTriangles,+ ),+ },+ gate: {+ validatorClean,+ byteStable,+ metadataRoundTripWhenVisible,+ defaultConsumerSingleActiveLod,+ hiddenAlternatesSurviveExport,+ hiddenAlternatesRemainInactive,+ passed,+ disposition: 'DONE_GATE_CLOSED',+ rationale: [+ 'The experimental root LOD extras do not survive the current final-byte pipeline, so recorded bounds/cost and target identity cannot round-trip.',+ 'All three groups are exported for ordinary consumers even when lower groups are marked hidden; triangle/visual parity remains 1.442857x the baseline.',+ 'No engine, Studio, or starter public consumer contract exists that can select exactly one level without a new schema/runtime expansion.',+ ],+ },+ };+}++export function w7VegetationLodReportSha256(report: W7VegetationLodExperimentReportV1): string {+ return sha256(new TextEncoder().encode(JSON.stringify(report)));+}diff --git a/src/experiments/w8-quadruped-gait-profile.test.ts b/src/experiments/w8-quadruped-gait-profile.test.tsnew file mode 100644index 00000000..2f84e260--- /dev/null+++ b/src/experiments/w8-quadruped-gait-profile.test.ts@@ -0,0 +1,289 @@+import { createHash } from 'node:crypto';++import { describe, expect, test } from 'bun:test';++type CandidateGait = 'walk' | 'trot' | 'gallop';+type LegRole = 'front.left' | 'front.right' | 'rear.left' | 'rear.right';+type PhaseProfile = Readonly<Record<LegRole, number>>;++const LEG_ROLES: readonly LegRole[] = Object.freeze([+ 'front.left',+ 'front.right',+ 'rear.left',+ 'rear.right',+]);++/**+ * W8 test-only candidates. These are deliberately not exported through the engine, injected into+ * prompts, or registered as QA rules. Their purpose is to measure whether an optional profile is+ * mechanically testable before human calibration, not to claim that one phase sequence is+ * universal animal-motion truth.+ */+const CANDIDATE_PROFILES: Readonly<Record<CandidateGait, PhaseProfile>> = Object.freeze({+ walk: Object.freeze({+ 'front.left': 0,+ 'front.right': 0.5,+ 'rear.left': 0.75,+ 'rear.right': 0.25,+ }),+ trot: Object.freeze({+ 'front.left': 0,+ 'front.right': 0.5,+ 'rear.left': 0.5,+ 'rear.right': 0,+ }),+ gallop: Object.freeze({+ 'front.left': 0.5,+ 'front.right': 0.65,+ 'rear.left': 0,+ 'rear.right': 0.15,+ }),+});++const MAX_PHASE_RMSE = 0.08;++function wrapPhase(value: number): number {+ const wrapped = value % 1;+ return wrapped < 0 ? wrapped + 1 : wrapped;+}++function circularDistance(left: number, right: number): number {+ const distance = Math.abs(wrapPhase(left) - wrapPhase(right));+ return Math.min(distance, 1 - distance);+}++function signedCircularDelta(value: number, reference: number): number {+ let delta = wrapPhase(value) - wrapPhase(reference);+ if (delta > 0.5) delta -= 1;+ if (delta <= -0.5) delta += 1;+ return delta;+}++function shifted(profile: PhaseProfile, offset: number, jitter: readonly number[]): PhaseProfile {+ return Object.freeze(+ Object.fromEntries(+ LEG_ROLES.map((role, index) => [+ role,+ wrapPhase(profile[role] + offset + (jitter[index] ?? 0)),+ ]),+ ) as Record<LegRole, number>,+ );+}++function bestAlignedPhaseRmse(expected: PhaseProfile, observed: PhaseProfile): number {+ const residuals = LEG_ROLES.map((role) => wrapPhase(observed[role] - expected[role]));+ // Circular least squares is piecewise Euclidean between the antipodes of the+ // residuals. Enumerate every interval, unwrap at its midpoint, solve the+ // Euclidean mean, and include the interval boundaries for constrained minima.+ const boundaries = [...new Set(residuals.map((residual) => wrapPhase(residual + 0.5)))].sort(+ (left, right) => left - right,+ );+ const intervalMeans = boundaries.map((start, index) => {+ const next = boundaries[(index + 1) % boundaries.length]!;+ const end = index + 1 < boundaries.length ? next : next + 1;+ const midpoint = wrapPhase((start + end) / 2);+ const mean =+ residuals.reduce(+ (sum, residual) => sum + midpoint + signedCircularDelta(residual, midpoint),+ 0,+ ) / residuals.length;+ return wrapPhase(mean);+ });+ const candidateOffsets = [...boundaries, ...intervalMeans];+ return Math.min(+ ...candidateOffsets.map((offset) => {+ const squaredError = LEG_ROLES.reduce((sum, role) => {+ const distance = circularDistance(observed[role], expected[role] + offset);+ return sum + distance * distance;+ }, 0);+ return Math.sqrt(squaredError / LEG_ROLES.length);+ }),+ );+}++function evaluateCandidate(+ gait: CandidateGait | undefined,+ observed?: PhaseProfile,+): Readonly<{+ status: 'evaluated' | 'not-applicable' | 'insufficient-evidence';+ findingCount: number;+ predictedDefect: boolean;+ phaseRmse: number | null;+}> {+ if (gait === undefined) {+ return Object.freeze({+ status: 'not-applicable',+ findingCount: 0,+ predictedDefect: false,+ phaseRmse: null,+ });+ }+ if (observed === undefined) {+ return Object.freeze({+ status: 'insufficient-evidence',+ findingCount: 0,+ predictedDefect: false,+ phaseRmse: null,+ });+ }+ const phaseRmse = bestAlignedPhaseRmse(CANDIDATE_PROFILES[gait], observed);+ const predictedDefect = phaseRmse > MAX_PHASE_RMSE;+ return Object.freeze({+ status: 'evaluated',+ findingCount: predictedDefect ? 1 : 0,+ predictedDefect,+ phaseRmse: Math.round(phaseRmse * 1_000_000) / 1_000_000,+ });+}++const SYNCHRONOUS: PhaseProfile = Object.freeze({+ 'front.left': 0,+ 'front.right': 0,+ 'rear.left': 0,+ 'rear.right': 0,+});++const PACE: PhaseProfile = Object.freeze({+ 'front.left': 0,+ 'front.right': 0.5,+ 'rear.left': 0,+ 'rear.right': 0.5,+});++interface SyntheticCase {+ id: string;+ gait: CandidateGait;+ expectedDefect: boolean;+ phases: PhaseProfile;+}++const SYNTHETIC_CASES: readonly SyntheticCase[] = Object.freeze(+ (Object.keys(CANDIDATE_PROFILES) as CandidateGait[]).flatMap((gait) => [+ Object.freeze({+ id: `${gait}-shifted-control-a`,+ gait,+ expectedDefect: false,+ phases: shifted(CANDIDATE_PROFILES[gait], 0.17, [0, 0.01, -0.01, 0.015]),+ }),+ Object.freeze({+ id: `${gait}-shifted-control-b`,+ gait,+ expectedDefect: false,+ phases: shifted(CANDIDATE_PROFILES[gait], 0.61, [0.012, -0.008, 0.006, -0.01]),+ }),+ Object.freeze({+ id: `${gait}-synchronous-adversary`,+ gait,+ expectedDefect: true,+ phases: SYNCHRONOUS,+ }),+ Object.freeze({+ id: `${gait}-pace-adversary`,+ gait,+ expectedDefect: true,+ phases: PACE,+ }),+ ]),+);++function experimentReport() {+ const evaluated = SYNTHETIC_CASES.map((entry) => ({+ id: entry.id,+ gait: entry.gait,+ expectedDefect: entry.expectedDefect,+ result: evaluateCandidate(entry.gait, entry.phases),+ }));+ const truePositive = evaluated.filter(+ (entry) => entry.expectedDefect && entry.result.predictedDefect,+ ).length;+ const falsePositive = evaluated.filter(+ (entry) => !entry.expectedDefect && entry.result.predictedDefect,+ ).length;+ const trueNegative = evaluated.filter(+ (entry) => !entry.expectedDefect && !entry.result.predictedDefect,+ ).length;+ const falseNegative = evaluated.filter(+ (entry) => entry.expectedDefect && !entry.result.predictedDefect,+ ).length;+ return Object.freeze({+ schemaVersion: 1,+ experimentId: 'kiln.w8.quadruped-gait-profile-experiment.v1',+ surface: 'test-only',+ threshold: { metric: 'global-phase-aligned-rmse', maximum: MAX_PHASE_RMSE },+ profileNames: Object.keys(CANDIDATE_PROFILES),+ syntheticCaseCount: evaluated.length,+ syntheticValidExamples: trueNegative + falsePositive,+ syntheticDefectiveExamples: truePositive + falseNegative,+ syntheticConfusion: { truePositive, falsePositive, trueNegative, falseNegative },+ unspecifiedGait: evaluateCandidate(undefined, SYNCHRONOUS),+ missingPhaseEvidence: evaluateCandidate('walk'),+ humanLabelCount: 0,+ eligibleForPublicSurface: false,+ eligibleForPromotion: false,+ reasons: [+ 'No production-authority human labels exist for quadruped gait.',+ 'Synthetic construction fixtures do not estimate frontier-model false-positive or false-negative rates.',+ 'No R4 owner acceptance exists for a public gait-profile surface.',+ ],+ });+}++describe('CHAR-028 provider-free optional quadruped gait-profile experiment', () => {+ test('tests walk/trot/gallop phase relations without penalizing unspecified gait', () => {+ expect(new Set(Object.keys(CANDIDATE_PROFILES))).toEqual(new Set(['walk', 'trot', 'gallop']));+ expect(new Set(Object.values(CANDIDATE_PROFILES.walk)).size).toBe(4);+ expect(CANDIDATE_PROFILES.trot['front.left']).toBe(CANDIDATE_PROFILES.trot['rear.right']);+ expect(CANDIDATE_PROFILES.trot['front.right']).toBe(CANDIDATE_PROFILES.trot['rear.left']);+ expect(CANDIDATE_PROFILES.gallop['rear.right']).toBeGreaterThan(+ CANDIDATE_PROFILES.gallop['rear.left'],+ );+ expect(CANDIDATE_PROFILES.gallop['front.right']).toBeGreaterThan(+ CANDIDATE_PROFILES.gallop['front.left'],+ );+ expect(evaluateCandidate(undefined, SYNCHRONOUS)).toEqual({+ status: 'not-applicable',+ findingCount: 0,+ predictedDefect: false,+ phaseRmse: null,+ });+ expect(evaluateCandidate('walk')).toEqual({+ status: 'insufficient-evidence',+ findingCount: 0,+ predictedDefect: false,+ phaseRmse: null,+ });+ const jitter = [0, 0.01, -0.01, 0.015] as const;+ const earlyStart = bestAlignedPhaseRmse(+ CANDIDATE_PROFILES.walk,+ shifted(CANDIDATE_PROFILES.walk, 0.17, jitter),+ );+ const lateStart = bestAlignedPhaseRmse(+ CANDIDATE_PROFILES.walk,+ shifted(CANDIDATE_PROFILES.walk, 0.61, jitter),+ );+ expect(earlyStart).toBeCloseTo(lateStart, 12);+ expect(earlyStart).toBeLessThan(MAX_PHASE_RMSE);+ });++ test('reproduces the synthetic profile experiment but refuses to treat it as calibration', () => {+ const report = experimentReport();+ expect(report).toMatchObject({+ surface: 'test-only',+ syntheticCaseCount: 12,+ syntheticValidExamples: 6,+ syntheticDefectiveExamples: 6,+ syntheticConfusion: {+ truePositive: 6,+ falsePositive: 0,+ trueNegative: 6,+ falseNegative: 0,+ },+ humanLabelCount: 0,+ eligibleForPublicSurface: false,+ eligibleForPromotion: false,+ });+ expect(JSON.stringify(experimentReport())).toBe(JSON.stringify(report));+ const sha256 = createHash('sha256').update(JSON.stringify(report)).digest('hex');+ expect(sha256).toBe('076a2ac0c7c4f902a9fc4e4ad1da0802021b0892edfea8df701de286d69bc191');+ });+});diff --git a/src/gltf-validator-shims.d.ts b/src/gltf-validator-shims.d.tsnew file mode 100644index 00000000..14490c50--- /dev/null+++ b/src/gltf-validator-shims.d.ts@@ -0,0 +1,12 @@+declare module 'gltf-validator' {+ export interface ValidationOptions {+ uri?: string;+ maxIssues?: number;+ ignoredIssues?: string[];+ onlyIssues?: string[];+ severityOverrides?: Record<string, number>;+ externalResourceFunction?: (uri: string) => Promise<Uint8Array>;+ }++ export function validateBytes(data: Uint8Array, options?: ValidationOptions): Promise<unknown>;+}diff --git a/src/list-primitives.ts b/src/list-primitives.tsindex 801026fb..469468aa 100644--- a/src/list-primitives.ts+++ b/src/list-primitives.ts@@ -66,6 +66,55 @@ const PRIMITIVES: PrimitiveSpec[] = ['Creates an empty pivot node for skeletal animation. Name is auto-prefixed with `Joint_`.',example: "const hip = createPivot('Hip', [0, 1, 0], root);",},+ {+ name: 'createJointChain',+ signature:+ 'createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })',+ returns: '{ root, end, nodes, byRole, descriptors }',+ category: 'structure',+ description:+ 'Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest frames, local axes, end effectors, contacts, and semantic metadata.',+ example:+ "const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side: 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left', offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });",+ promptNotes:+ 'Use only the resolved body-plan graph. Offsets are local to the previous joint; contact end effectors must land at world Y=0.',+ },+ {+ name: 'createVehicleFrame',+ signature:+ 'createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })',+ returns: '{ root, chassis, axles, seats, contacts, steering, propulsion }',+ category: 'structure',+ description:+ 'Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for chassis, support, steering, and propulsion.',+ example:+ "const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2, 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });",+ promptNotes:+ 'Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use declared support/propulsion sockets, not wheel rules.',+ },+ {+ name: 'createWheelGeometrySet',+ signature: 'createWheelGeometrySet(radius: number, width: number)',+ returns: '{ tire, rim, hub } shared THREE.BufferGeometry set',+ category: 'instancing',+ description:+ 'Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.',+ example: 'const wheelGeo = createWheelGeometrySet(0.45, 0.22);',+ },+ {+ name: 'createWheelAssembly',+ signature:+ 'createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })',+ returns:+ '{ root, steeringPivot?, spinPivot, tire, rim, hub, contact, radius, width, side, index, spinAxis }',+ category: 'structure',+ description:+ 'Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact marker, +Z spin frame, and optional steering pivot.',+ example:+ "createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width: 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true, geometries: wheelGeo, parent: frame.root });",+ promptNotes:+ 'Keep tire, rim, and hub descendants concentric at the axle pivot. Reuse one geometry set across matching wheels.',+ },{name: 'createPart',signature:@@ -160,6 +209,57 @@ const PRIMITIVES: PrimitiveSpec[] = [promptNotes:'The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does this for you. Drop it onto the walls (position.y = wall height).',},+ {+ name: 'createGableRoof',+ signature:+ "createGableRoof(name, material, { spanX, spanZ, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",+ returns:+ '{ root, slopes: [Object3D, Object3D], faces: [RoofFaceFrame, RoofFaceFrame], rise, pitchDegrees }',+ category: 'structure',+ description:+ 'Explicit-axis gable roof using unambiguous footprint spans. Each face owns a rigid frame with ridge tangent, outward normal, downhill direction, ridge/eave endpoints, dimensions, and a live local-to-world transform.',+ example:+ "const roof = createGableRoof('Roof', shingles, { spanX: 8, spanZ: 5, pitchDegrees: 35, overhang: 0.35, ridgeAxis: 'x', parent: root });",+ promptNotes:+ 'Prefer this over width/depth roof math. ridgeAxis is the direction of the ridge; roof panels run along each returned face downhill direction.',+ },+ {+ name: 'createGableEndPanel',+ signature:+ "createGableEndPanel(name, material, { span, rise, thickness?, ridgeAxis?: 'x'|'z', side?: 'positive'|'negative', openings?: [{ id?, offset?, bottom?, width, height }], parent? })",+ returns: '{ root, geometry, openings }',+ category: 'structure',+ description:+ 'Exact thick triangular end closure for a gable roof, with optional rectangular openings cut from the geometry and semantic boundary metadata.',+ example:+ "createGableEndPanel('FrontGable', siding, { span: 5, rise: 1.8, ridgeAxis: 'x', side: 'positive', parent: root });",+ },+ {+ name: 'createGableShell',+ signature:+ "createGableShell(name, { wall, roof, floor?, gable? }, { spanX, spanZ, wallHeight?, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, wallThickness?, floorThickness?, closedEnds?, enterable?, openings?, gableOpenings?, parent? })",+ returns: '{ root, walls, floor, roof, gables, openings }',+ category: 'structure',+ description:+ 'Closed-by-default, correct-by-construction gable building: hollow room, floor, two opposing roof slopes, two complete gable ends, and a real front doorway when enterable.',+ example:+ "const house = createGableShell('House', { wall: plaster, roof: shingles }, { spanX: 8, spanZ: 5, wallHeight: 2.8, pitchDegrees: 35, ridgeAxis: 'x', parent: root });",+ promptNotes:+ 'Use for complete gable buildings. It stamps wall, floor, slope, gable, opening, adjacency, coverage, and separability semantics for deterministic QA and roof-off views.',+ },+ {+ name: 'createRoofSurfaceLayout',+ signature:+ "createRoofSurfaceLayout(name, material, { face, kind: 'panels'|'shingles'|'seams'|'corrugations', parent?, panelWidth?, rowHeight?, spacing?, thickness? })",+ returns: '{ root, items: Object3D[] }',+ category: 'structure',+ description:+ 'Places roof-local panels, shingles, seams, or corrugations from a returned RoofFaceFrame, so repeated elements run ridge-to-eave for either ridge axis without manual Euler rotations.',+ example:+ "for (const face of roof.faces) createRoofSurfaceLayout('Panels_' + face.side, metal, { face, kind: 'panels', parent: roof.root });",+ promptNotes:+ 'Always pass the face object returned by createGableRoof/createGableShell. Never infer the panel rotation from world axes.',+ },{name: 'createStairs',signature:@@ -356,7 +456,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 quad = foliageCardGeo({ width: 4, height: 6, yPivot: 0 });\ncreatePart('Mesh_Fern', quad, gameMaterial(0x3a6b2e), { parent: root });",+ "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 });",},{name: 'crossedQuadsGeo',@@ -366,7 +466,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 bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });\ncreatePart('Mesh_Bush', bush, gameMaterial(0x2f4a1a), { parent: root });",+ "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 });",},{name: 'octaGridPlane',@@ -422,6 +522,19 @@ const PRIMITIVES: PrimitiveSpec[] = [description: 'Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.',example: 'const mat = gameMaterial(0x8b7355, { roughness: 0.9 });',},+ {+ name: 'materialRecipe',+ signature:+ 'await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })',+ returns: 'Promise<THREE.MeshStandardMaterial>',+ category: 'material',+ description:+ 'Resolves a versioned portable bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF PBR.',+ example:+ "const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#6b4328' });",+ 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: 'basicMaterial',signature: 'basicMaterial(color, opts?: { transparent, opacity })',@@ -769,25 +882,37 @@ const PRIMITIVES: PrimitiveSpec[] = [// ---------------------------------------------------------------------------{name: 'loadTexture',- signature: 'await loadTexture(source: string | Buffer | Uint8Array)',+ signature:+ "await loadTexture(source, { usage?: 'albedo'|'emissive'|'normal'|'roughness'|'metalness'|'metallicRoughness'|'occlusion', name? })",returns: 'Promise<THREE.DataTexture>',category: 'textures',description:- 'Loads a PNG/JPG/WebP image into a Three.js Texture. Stashes the encoded bytes on userData.encoded so GLB export is lossless.',- example: "const wood = await loadTexture('./textures/oak-albedo.png');",+ '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' });",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.',},{name: 'pbrMaterial',- signature: 'pbrMaterial({ albedo?, normal?, roughness?, metalness?, emissive?, aoMap? })',+ signature:+ 'pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, aoMap?, alphaMode?, alphaCutoff?, doubleSided? })',returns: 'THREE.MeshStandardMaterial',category: 'material',description:- 'Full PBR material. Each slot can be a hex color/scalar or a Texture loaded via loadTexture. Exports as glTF pbrMetallicRoughness.',+ '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 });",},+ {+ name: 'foliageMaterial',+ signature: 'foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })',+ returns: 'THREE.MeshStandardMaterial',+ 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 });",+ },// ---------------------------------------------------------------------------// Utility@@ -819,7 +944,7 @@ const PRIMITIVES: PrimitiveSpec[] = [{name: 'validateAsset',signature:- "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment')",+ "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture' | 'vegetation' | 'vehicle')",returns: '{ valid, errors, warnings }',category: 'utility',description: 'Warns on category-appropriate triangle / material budgets.',diff --git a/src/material-metrics.ts b/src/material-metrics.tsnew file mode 100644index 00000000..7f822dba--- /dev/null+++ b/src/material-metrics.ts@@ -0,0 +1,354 @@+/** Deterministic material/texture metrics and advisory tier/profile budgets. */++import type { Accessor, Document, Material, Node, Primitive, Texture } from '@gltf-transform/core';++export interface MaterialImageMetricV1 {+ name: string;+ width: number;+ height: number;+ maxDimension: number;+ decodedBytesRgba8: number;+ estimatedGpuBytesWithMipmaps: number;+}++export interface MaterialMetricsV1 {+ schemaVersion: 1;+ materialCount: number;+ opaqueMaterials: number;+ maskedMaterials: number;+ blendedMaterials: number;+ singleSidedMaterials: number;+ doubleSidedMaterials: number;+ texturedMaterials: number;+ untexturedMaterials: number;+ extensionCount: number;+ extensionsUsed: string[];+ materialExtensionCount: number;+ materialExtensionsUsed: string[];+ imageCount: number;+ images: MaterialImageMetricV1[];+ maxImageDimension: number;+ totalImagePixels: number;+ decodedImageBytesRgba8: number;+ estimatedGpuBytesWithMipmaps: number;+ totalSurfaceArea: number;+ blendedSurfaceArea: number;+ blendedSurfaceAreaRatio: number;+}++export type MaterialBudgetProfileId = 'web.portable.v1' | 'mobile.portable.v1';+export type MaterialAssetTier = 'hero' | 'standard' | 'background';++export interface MaterialBudgetLimitsV1 {+ maxImageDimension: number;+ maxImageCount: number;+ maxDecodedBytesRgba8: number;+ maxBlendedSurfaceAreaRatio: number;+}++export interface MaterialBudgetWarningV1 {+ code:+ | 'MATERIAL_TEXTURE_RESOLUTION_BUDGET'+ | 'MATERIAL_IMAGE_COUNT_BUDGET'+ | 'MATERIAL_DECODED_MEMORY_BUDGET'+ | 'MATERIAL_BLEND_AREA_BUDGET';+ disposition: 'warn';+ profile: MaterialBudgetProfileId;+ tier: MaterialAssetTier;+ message: string;+ measurement: {+ name: string;+ actual: number;+ threshold: number;+ unit: 'px' | 'images' | 'bytes' | 'ratio';+ };+ advice: string;+}++export const MATERIAL_BUDGET_PROFILES_V1: Readonly<+ Record<MaterialBudgetProfileId, Readonly<Record<MaterialAssetTier, MaterialBudgetLimitsV1>>>+> = Object.freeze({+ 'web.portable.v1': Object.freeze({+ hero: Object.freeze({+ maxImageDimension: 4096,+ maxImageCount: 8,+ maxDecodedBytesRgba8: 128 * 1024 * 1024,+ maxBlendedSurfaceAreaRatio: 0.35,+ }),+ standard: Object.freeze({+ maxImageDimension: 2048,+ maxImageCount: 4,+ maxDecodedBytesRgba8: 32 * 1024 * 1024,+ maxBlendedSurfaceAreaRatio: 0.15,+ }),+ background: Object.freeze({+ maxImageDimension: 1024,+ maxImageCount: 2,+ maxDecodedBytesRgba8: 8 * 1024 * 1024,+ maxBlendedSurfaceAreaRatio: 0.05,+ }),+ }),+ 'mobile.portable.v1': Object.freeze({+ hero: Object.freeze({+ maxImageDimension: 2048,+ maxImageCount: 6,+ maxDecodedBytesRgba8: 48 * 1024 * 1024,+ maxBlendedSurfaceAreaRatio: 0.2,+ }),+ standard: Object.freeze({+ maxImageDimension: 1024,+ maxImageCount: 3,+ maxDecodedBytesRgba8: 16 * 1024 * 1024,+ maxBlendedSurfaceAreaRatio: 0.1,+ }),+ background: Object.freeze({+ maxImageDimension: 512,+ maxImageCount: 1,+ maxDecodedBytesRgba8: 4 * 1024 * 1024,+ maxBlendedSurfaceAreaRatio: 0.03,+ }),+ }),+});++const materialTextures = (material: Material): Array<Texture | null> => [+ material.getBaseColorTexture(),+ material.getMetallicRoughnessTexture(),+ material.getNormalTexture(),+ material.getOcclusionTexture(),+ material.getEmissiveTexture(),+];++const hasTexture = (material: Material): boolean => materialTextures(material).some(Boolean);++const transformPoint = (+ matrix: readonly number[],+ x: number,+ y: number,+ z: number,+): [number, number, number] => {+ const w = matrix[3]! * x + matrix[7]! * y + matrix[11]! * z + matrix[15]!;+ const reciprocal = w === 0 ? 1 : 1 / w;+ return [+ (matrix[0]! * x + matrix[4]! * y + matrix[8]! * z + matrix[12]!) * reciprocal,+ (matrix[1]! * x + matrix[5]! * y + matrix[9]! * z + matrix[13]!) * reciprocal,+ (matrix[2]! * x + matrix[6]! * y + matrix[10]! * z + matrix[14]!) * reciprocal,+ ];+};++const accessorPoint = (+ accessor: Accessor,+ index: number,+ matrix: readonly number[],+): [number, number, number] => {+ const array = accessor.getArray();+ if (!array) return [0, 0, 0];+ const size = accessor.getElementSize();+ const offset = index * size;+ return transformPoint(+ matrix,+ Number(array[offset]),+ Number(array[offset + 1]),+ Number(array[offset + 2]),+ );+};++const triangleArea = (a: readonly number[], b: readonly number[], c: readonly number[]): number => {+ const abx = b[0]! - a[0]!;+ const aby = b[1]! - a[1]!;+ const abz = b[2]! - a[2]!;+ const acx = c[0]! - a[0]!;+ const acy = c[1]! - a[1]!;+ const acz = c[2]! - a[2]!;+ const crossX = aby * acz - abz * acy;+ const crossY = abz * acx - abx * acz;+ const crossZ = abx * acy - aby * acx;+ return Math.hypot(crossX, crossY, crossZ) / 2;+};++function primitiveSurfaceArea(primitive: Primitive, node: Node): number {+ // TRIANGLES only. Lines/points are not a meaningful blend-area proxy.+ if (primitive.getMode() !== 4) return 0;+ const position = primitive.getAttribute('POSITION');+ if (!position) return 0;+ const indices = primitive.getIndices()?.getArray();+ const count = indices?.length ?? position.getCount();+ const matrix = node.getWorldMatrix();+ let area = 0;+ for (let offset = 0; offset + 2 < count; offset += 3) {+ const aIndex = indices ? Number(indices[offset]) : offset;+ const bIndex = indices ? Number(indices[offset + 1]) : offset + 1;+ const cIndex = indices ? Number(indices[offset + 2]) : offset + 2;+ area += triangleArea(+ accessorPoint(position, aIndex, matrix),+ accessorPoint(position, bIndex, matrix),+ accessorPoint(position, cIndex, matrix),+ );+ }+ return area;+}++/** Collect material signals independently of the A-F instanceability grade. */+export function collectMaterialMetricsV1(document: Document): MaterialMetricsV1 {+ const root = document.getRoot();+ const materials = root.listMaterials();+ const images = root.listTextures().map((texture, index): MaterialImageMetricV1 => {+ const size = texture.getSize() ?? [0, 0];+ const width = size[0] ?? 0;+ const height = size[1] ?? 0;+ const decodedBytesRgba8 = width * height * 4;+ return {+ name: texture.getName() || `image-${index + 1}`,+ width,+ height,+ maxDimension: Math.max(width, height),+ decodedBytesRgba8,+ estimatedGpuBytesWithMipmaps: Math.ceil((decodedBytesRgba8 * 4) / 3),+ };+ });+ let totalSurfaceArea = 0;+ let blendedSurfaceArea = 0;+ const visit = (node: Node): void => {+ const mesh = node.getMesh();+ if (mesh) {+ for (const primitive of mesh.listPrimitives()) {+ const area = primitiveSurfaceArea(primitive, node);+ totalSurfaceArea += area;+ if (primitive.getMaterial()?.getAlphaMode() === 'BLEND') blendedSurfaceArea += area;+ }+ }+ node.listChildren().forEach(visit);+ };+ for (const scene of root.listScenes()) scene.listChildren().forEach(visit);+ const extensionsUsed = root+ .listExtensionsUsed()+ .map((extension) => extension.extensionName)+ .sort();+ const materialExtensionsUsed = extensionsUsed.filter((name) =>+ /^(?:KHR|EXT)_materials_/.test(name),+ );+ const opaqueMaterials = materials.filter(+ (material) => material.getAlphaMode() === 'OPAQUE',+ ).length;+ const maskedMaterials = materials.filter((material) => material.getAlphaMode() === 'MASK').length;+ const blendedMaterials = materials.filter(+ (material) => material.getAlphaMode() === 'BLEND',+ ).length;+ const doubleSidedMaterials = materials.filter((material) => material.getDoubleSided()).length;+ const texturedMaterials = materials.filter(hasTexture).length;+ return {+ schemaVersion: 1,+ materialCount: materials.length,+ opaqueMaterials,+ maskedMaterials,+ blendedMaterials,+ singleSidedMaterials: materials.length - doubleSidedMaterials,+ doubleSidedMaterials,+ texturedMaterials,+ untexturedMaterials: materials.length - texturedMaterials,+ extensionCount: extensionsUsed.length,+ extensionsUsed,+ materialExtensionCount: materialExtensionsUsed.length,+ materialExtensionsUsed,+ imageCount: images.length,+ images,+ maxImageDimension: Math.max(0, ...images.map((image) => image.maxDimension)),+ totalImagePixels: images.reduce((sum, image) => sum + image.width * image.height, 0),+ decodedImageBytesRgba8: images.reduce((sum, image) => sum + image.decodedBytesRgba8, 0),+ estimatedGpuBytesWithMipmaps: images.reduce(+ (sum, image) => sum + image.estimatedGpuBytesWithMipmaps,+ 0,+ ),+ totalSurfaceArea,+ blendedSurfaceArea,+ blendedSurfaceAreaRatio: totalSurfaceArea > 0 ? blendedSurfaceArea / totalSurfaceArea : 0,+ };+}++const mib = (bytes: number): string => `${(bytes / (1024 * 1024)).toFixed(2)} MiB`;++export function materialBudgetProfileForQaProfile(qaProfile: string): MaterialBudgetProfileId {+ return /(?:mobile|constrained|low-memory)/i.test(qaProfile)+ ? 'mobile.portable.v1'+ : 'web.portable.v1';+}++/** Advisory-only budget evaluation with measured costs and concrete remediation. */+export function evaluateMaterialBudgetV1(+ metrics: MaterialMetricsV1,+ options: { profile: MaterialBudgetProfileId; tier: MaterialAssetTier },+): MaterialBudgetWarningV1[] {+ const limits = MATERIAL_BUDGET_PROFILES_V1[options.profile][options.tier];+ const warnings: MaterialBudgetWarningV1[] = [];+ if (metrics.maxImageDimension > limits.maxImageDimension) {+ const offenders = metrics.images+ .filter((image) => image.maxDimension > limits.maxImageDimension)+ .map((image) => `${image.name} ${image.width}x${image.height}`)+ .join(', ');+ warnings.push({+ code: 'MATERIAL_TEXTURE_RESOLUTION_BUDGET',+ disposition: 'warn',+ profile: options.profile,+ tier: options.tier,+ message: `Maximum image dimension is ${metrics.maxImageDimension}px; ${options.profile}/${options.tier} allows ${limits.maxImageDimension}px. Offenders: ${offenders}.`,+ measurement: {+ name: 'maxImageDimension',+ actual: metrics.maxImageDimension,+ threshold: limits.maxImageDimension,+ unit: 'px',+ },+ advice: `Downscale the named images so their longest edge is at most ${limits.maxImageDimension}px; preserve aspect ratio and rerun glTF validation.`,+ });+ }+ if (metrics.imageCount > limits.maxImageCount) {+ warnings.push({+ code: 'MATERIAL_IMAGE_COUNT_BUDGET',+ disposition: 'warn',+ profile: options.profile,+ tier: options.tier,+ message: `${metrics.imageCount} images exceed the ${limits.maxImageCount}-image ${options.profile}/${options.tier} budget.`,+ measurement: {+ name: 'imageCount',+ actual: metrics.imageCount,+ threshold: limits.maxImageCount,+ unit: 'images',+ },+ advice:+ 'Reuse approved resource IDs, remove unused images, or atlas compatible same-color-space slots; never atlas normal/data maps into an sRGB image.',+ });+ }+ if (metrics.decodedImageBytesRgba8 > limits.maxDecodedBytesRgba8) {+ const scale = Math.sqrt(limits.maxDecodedBytesRgba8 / metrics.decodedImageBytesRgba8);+ warnings.push({+ code: 'MATERIAL_DECODED_MEMORY_BUDGET',+ disposition: 'warn',+ profile: options.profile,+ tier: options.tier,+ message: `Decoded RGBA8 image memory is ${mib(metrics.decodedImageBytesRgba8)}; ${options.profile}/${options.tier} allows ${mib(limits.maxDecodedBytesRgba8)} before mip overhead.`,+ measurement: {+ name: 'decodedImageBytesRgba8',+ actual: metrics.decodedImageBytesRgba8,+ threshold: limits.maxDecodedBytesRgba8,+ unit: 'bytes',+ },+ advice: `Downscale image width and height by approximately ${(Math.min(1, scale) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`,+ });+ }+ if (metrics.blendedSurfaceAreaRatio > limits.maxBlendedSurfaceAreaRatio) {+ warnings.push({+ code: 'MATERIAL_BLEND_AREA_BUDGET',+ disposition: 'warn',+ profile: options.profile,+ tier: options.tier,+ message: `Blended primitive surface area is ${(metrics.blendedSurfaceAreaRatio * 100).toFixed(1)}% (${metrics.blendedSurfaceArea.toFixed(3)} of ${metrics.totalSurfaceArea.toFixed(3)} square asset units); the budget is ${(limits.maxBlendedSurfaceAreaRatio * 100).toFixed(1)}%.`,+ measurement: {+ name: 'blendedSurfaceAreaRatio',+ actual: metrics.blendedSurfaceAreaRatio,+ threshold: limits.maxBlendedSurfaceAreaRatio,+ unit: 'ratio',+ },+ advice:+ 'Use MASK for binary cutouts such as foliage, reduce layered transparent surfaces, and reserve BLEND for genuinely translucent glass/effects.',+ });+ }+ return warnings;+}diff --git a/src/material-recipe-prompt.ts b/src/material-recipe-prompt.tsnew file mode 100644index 00000000..f8b8af00--- /dev/null+++ b/src/material-recipe-prompt.ts@@ -0,0 +1,48 @@+/** Material-specific prompt/API discovery block; coordinator wires it into root prompt surfaces. */++import {+ MATERIAL_RECIPE_IDS,+ MATERIAL_RECIPE_LIBRARY_V1,+ type MaterialRecipeRequestV1,+} from './material-recipes';++export const MATERIAL_RECIPE_HELPER_SIGNATURE =+ 'await materialRecipe(recipeId, { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })';++/** Executable, provider-independent examples used by MAT-019's prompt ablation. */+export const MATERIAL_RECIPE_EXECUTABLE_EXAMPLES_V1 = `+\`\`\`js+const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#654126' });+const leafDark = await materialRecipe('kiln.material.leaf.v1', { baseColor: '#285b32' });+const leafLight = await materialRecipe('kiln.material.leaf.v1', { baseColor: '#609447' });+const wood = await materialRecipe('kiln.material.wood.v1');+const stone = await materialRecipe('kiln.material.stone.v1');+const rubber = await materialRecipe('kiln.material.rubber.v1');+const paintedMetal = await materialRecipe('kiln.material.painted-metal.v1');+const cloth = await materialRecipe('kiln.material.cloth.v1');+const skin = await materialRecipe('kiln.material.skin.v1');+const glass = await materialRecipe('kiln.material.glass.v1');+const glow = await materialRecipe('kiln.material.emissive.v1');+\`\`\``;++export const MATERIAL_RECIPE_PROMPT_CONTEXT_V1 = `## Portable material recipes++Use ${MATERIAL_RECIPE_HELPER_SIGNATURE}. Recipe IDs are versioned and executable; do not invent an+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. Texture+slots accept only approved kiln.texture.* resource IDs reported by capabilities.++Choose recipes from the requested real-world material even when the user does not name this helper:+${MATERIAL_RECIPE_EXECUTABLE_EXAMPLES_V1}`;++export function materialRecipeRequestDirective(request: MaterialRecipeRequestV1): string {+ const recipe = MATERIAL_RECIPE_LIBRARY_V1[request.id];+ return [+ '## Requested portable material recipe',+ `Use exactly ${request.id} (${recipe.name}), recipe schema/version 1.`,+ request.overrides+ ? `Apply only these validated typed overrides: ${JSON.stringify(request.overrides)}.`+ : 'Use the recipe defaults without inventing overrides.',+ 'Keep the result portable glTF PBR; do not substitute a runtime shader or filesystem texture path.',+ ].join('\n');+}diff --git a/src/material-recipe-runtime.ts b/src/material-recipe-runtime.tsnew file mode 100644index 00000000..13624ef8--- /dev/null+++ b/src/material-recipe-runtime.ts@@ -0,0 +1,162 @@+/** Execute a validated portable recipe with approved texture resources. */++import * as THREE from 'three';++import {+ createMaterialRecipeRequestV1,+ resolveMaterialRecipeV1,+ type MaterialRecipeId,+ type MaterialRecipeOverridesV1,+ type MaterialRecipeRequestV1,+ type MaterialTextureSlot,+ type PortablePbrRecipeV1,+} from './material-recipes';+import {+ type ApprovedTextureResourceCache,+ DEFAULT_APPROVED_TEXTURE_CACHE,+ type MaterialResourceProvenanceV1,+} from './material-resources';+import { pbrMaterial, type PbrMaterialOptions } from './textures';++export interface MaterialRecipeApplicationProvenanceV1 {+ schemaVersion: 1;+ recipeId: MaterialRecipeId;+ recipeVersion: 1;+ request: MaterialRecipeRequestV1;+ portableModel: 'pbrMetallicRoughness';+ resources: MaterialResourceProvenanceV1[];+}++export interface AppliedMaterialRecipeV1 {+ material: THREE.MeshStandardMaterial;+ resolved: PortablePbrRecipeV1;+ provenance: MaterialRecipeApplicationProvenanceV1;+}++export interface ApplyMaterialRecipeOptions {+ cache?: ApprovedTextureResourceCache;+ name?: string;+}++const lowerAlphaMode = (+ value: PortablePbrRecipeV1['alphaMode'],+): NonNullable<PbrMaterialOptions['alphaMode']> =>+ value === 'MASK' ? 'mask' : value === 'BLEND' ? 'blend' : 'opaque';++/**+ * One executable recipe path used by prompt helpers and manifest execution.+ * Every texture slot is resolved from the closed approved-ID registry.+ */+export async function applyMaterialRecipeV1(+ request: MaterialRecipeRequestV1,+ options: ApplyMaterialRecipeOptions = {},+): Promise<AppliedMaterialRecipeV1> {+ const resolved = resolveMaterialRecipeV1(request);+ const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;+ const loaded = new Map<+ MaterialTextureSlot,+ Awaited<ReturnType<ApprovedTextureResourceCache['load']>>+ >();+ for (const [slot, id] of Object.entries(resolved.textureResources)) {+ if (id) loaded.set(slot as MaterialTextureSlot, await cache.load(id));+ }++ const materialOptions: PbrMaterialOptions = {+ roughness: resolved.roughnessFactor,+ metalness: resolved.metallicFactor,+ alphaMode: lowerAlphaMode(resolved.alphaMode),+ ...(resolved.alphaMode === 'MASK' ? { alphaCutoff: resolved.alphaCutoff ?? 0.5 } : {}),+ doubleSided: resolved.doubleSided,+ ...(loaded.get('baseColor') ? { albedo: loaded.get('baseColor')!.texture } : {}),+ ...(loaded.get('normal') ? { normal: loaded.get('normal')!.texture } : {}),+ ...(loaded.get('metallicRoughness')+ ? { metallicRoughness: loaded.get('metallicRoughness')!.texture }+ : {}),+ ...(loaded.get('emissive') ? { emissive: loaded.get('emissive')!.texture } : {}),+ ...(loaded.get('occlusion') ? { aoMap: loaded.get('occlusion')!.texture } : {}),+ };+ const material = pbrMaterial(materialOptions);+ material.name = options.name ?? request.id;+ material.color.setRGB(+ resolved.baseColorFactor[0],+ resolved.baseColorFactor[1],+ resolved.baseColorFactor[2],+ THREE.LinearSRGBColorSpace,+ );+ material.opacity = resolved.baseColorFactor[3];+ material.emissive.setRGB(+ resolved.emissiveFactor[0],+ resolved.emissiveFactor[1],+ resolved.emissiveFactor[2],+ THREE.LinearSRGBColorSpace,+ );++ const resources = [...loaded.values()]+ .map((entry) => entry.provenance)+ .sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));+ const provenance: MaterialRecipeApplicationProvenanceV1 = {+ schemaVersion: 1,+ recipeId: request.id,+ recipeVersion: 1,+ request: {+ schemaVersion: 1,+ id: request.id,+ ...(request.overrides+ ? {+ overrides: {+ ...request.overrides,+ ...(request.overrides.textureResources+ ? { textureResources: { ...request.overrides.textureResources } }+ : {}),+ },+ }+ : {}),+ },+ portableModel: 'pbrMetallicRoughness',+ resources,+ };+ (material.userData as Record<string, unknown>)['kilnMaterialRecipe'] = provenance;+ return { material, resolved, provenance };+}++/** Concise sandbox helper: materialRecipe('kiln.material.wood.v1', overrides?). */+export async function materialRecipe(+ id: MaterialRecipeId,+ overrides?: MaterialRecipeOverridesV1,+ options: ApplyMaterialRecipeOptions = {},+): Promise<THREE.MeshStandardMaterial> {+ return (await applyMaterialRecipeV1(createMaterialRecipeRequestV1(id, overrides), options))+ .material;+}++export function readMaterialRecipeApplication(+ material: THREE.Material,+): MaterialRecipeApplicationProvenanceV1 | undefined {+ return (material.userData as Record<string, unknown>)['kilnMaterialRecipe'] as+ | MaterialRecipeApplicationProvenanceV1+ | undefined;+}++/** Scene-side hook for exact render/provenance persistence. */+export function collectMaterialRecipeApplications(+ root: THREE.Object3D,+): MaterialRecipeApplicationProvenanceV1[] {+ const applications = new Map<string, MaterialRecipeApplicationProvenanceV1>();+ root.traverse((node) => {+ const value = (node as THREE.Mesh).material;+ const materials = Array.isArray(value) ? value : value ? [value] : [];+ for (const material of materials) {+ const application = readMaterialRecipeApplication(material);+ if (!application) continue;+ const resourceKey = application.resources+ .map((resource) => `${resource.resourceId}:${resource.contentHash}`)+ .sort()+ .join(',');+ applications.set(+ `${application.recipeId}:${JSON.stringify(application.request)}:${resourceKey}`,+ application,+ );+ }+ });+ return [...applications.values()].sort((a, b) => a.recipeId.localeCompare(b.recipeId));+}diff --git a/src/material-recipes.ts b/src/material-recipes.tsnew file mode 100644index 00000000..f8f5aa07--- /dev/null+++ b/src/material-recipes.ts@@ -0,0 +1,630 @@+/**+ * Browser-safe, provider-independent portable material recipe contract.+ *+ * Recipes resolve only to core glTF 2.0 metallic-roughness fields. Runtime+ * material construction and approved byte resolution live in sibling modules+ * so capability/SDK/UI consumers can import this file without Three, sharp,+ * filesystem access, or provider credentials.+ */++export const MATERIAL_RECIPE_SCHEMA_VERSION = 1 as const;++export const MATERIAL_RECIPE_IDS = [+ 'kiln.material.bark.v1',+ 'kiln.material.leaf.v1',+ 'kiln.material.wood.v1',+ 'kiln.material.stone.v1',+ 'kiln.material.rubber.v1',+ 'kiln.material.painted-metal.v1',+ 'kiln.material.cloth.v1',+ 'kiln.material.skin.v1',+ 'kiln.material.glass.v1',+ 'kiln.material.emissive.v1',+] as const;++export type MaterialRecipeId = (typeof MATERIAL_RECIPE_IDS)[number];++export const MATERIAL_RECIPE_OVERRIDE_KEYS = [+ 'baseColor',+ 'roughness',+ 'metalness',+ 'opacity',+ 'alphaCutoff',+ 'doubleSided',+ 'emissiveColor',+ 'emissiveIntensity',+ 'textureResources',+] as const;++export type MaterialRecipeOverrideKey = (typeof MATERIAL_RECIPE_OVERRIDE_KEYS)[number];++export const APPROVED_TEXTURE_RESOURCE_IDS = [+ 'kiln.texture.bark-albedo.v1',+ 'kiln.texture.leaf-mask-albedo.v1',+ 'kiln.texture.neutral-normal.v1',+ 'kiln.texture.neutral-metallic-roughness.v1',+ 'kiln.texture.emissive-grid.v1',+] as const;++export type ApprovedTextureResourceId = (typeof APPROVED_TEXTURE_RESOURCE_IDS)[number];++export const MATERIAL_TEXTURE_SLOTS = [+ 'baseColor',+ 'normal',+ 'metallicRoughness',+ 'emissive',+ 'occlusion',+] as const;++export type MaterialTextureSlot = (typeof MATERIAL_TEXTURE_SLOTS)[number];+export type PortableAlphaMode = 'OPAQUE' | 'MASK' | 'BLEND';+export type PortableColorFactor = readonly [number, number, number, number];+export type PortableRgbFactor = readonly [number, number, number];++export interface MaterialRecipeOverridesV1 {+ /** Six-digit sRGB authoring color. */+ baseColor?: string;+ roughness?: number;+ metalness?: number;+ opacity?: number;+ alphaCutoff?: number;+ doubleSided?: boolean;+ emissiveColor?: string;+ /** Baked into the standard emissive factor; no extension is required. */+ emissiveIntensity?: number;+ textureResources?: Partial<Record<MaterialTextureSlot, ApprovedTextureResourceId>>;+}++export interface MaterialRecipeRequestV1 {+ schemaVersion: 1;+ id: MaterialRecipeId;+ overrides?: MaterialRecipeOverridesV1;+}++export interface PortablePbrRecipeV1 {+ baseColorFactor: PortableColorFactor;+ metallicFactor: number;+ roughnessFactor: number;+ emissiveFactor: PortableRgbFactor;+ alphaMode: PortableAlphaMode;+ alphaCutoff?: number;+ doubleSided: boolean;+ textureResources: Partial<Record<MaterialTextureSlot, ApprovedTextureResourceId>>;+}++export interface MaterialRecipeDescriptorV1 {+ schemaVersion: 1;+ id: MaterialRecipeId;+ version: 1;+ name: string;+ description: string;+ portable: true;+ gltfMaterialModel: 'pbrMetallicRoughness';+ allowedOverrides: readonly MaterialRecipeOverrideKey[];+ defaults: PortablePbrRecipeV1;+}++export interface ApprovedTextureResourceDescriptorV1 {+ schemaVersion: 1;+ id: ApprovedTextureResourceId;+ version: 1;+ label: string;+ usage: 'albedo' | 'normal' | 'metallicRoughness' | 'emissive';+ colorSpace: 'srgb' | 'linear';+ mime: 'image/png';+ contentHash: string;+ allowedSlots: readonly MaterialTextureSlot[];+ recipeIds: readonly MaterialRecipeId[];+}++export interface MaterialRecipeValidationIssue {+ code:+ | 'EXPECTED_OBJECT'+ | 'UNSUPPORTED_SCHEMA_VERSION'+ | 'UNSUPPORTED_RECIPE_ID'+ | 'INVALID_OVERRIDES'+ | 'UNSUPPORTED_OVERRIDE'+ | 'INVALID_OVERRIDE_VALUE'+ | 'UNKNOWN_TEXTURE_SLOT'+ | 'UNSUPPORTED_RESOURCE_ID'+ | 'RESOURCE_SLOT_MISMATCH'+ | 'RESOURCE_RECIPE_MISMATCH';+ path: string;+ message: string;+}++export interface MaterialRecipeValidationResult {+ valid: boolean;+ value?: MaterialRecipeRequestV1;+ issues: MaterialRecipeValidationIssue[];+}++const srgbChannelToLinear = (value: number): number =>+ value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;++const rgba = (hex: string, alpha = 1): PortableColorFactor => {+ const normalized = hex.replace(/^#/, '');+ return Object.freeze([+ srgbChannelToLinear(Number.parseInt(normalized.slice(0, 2), 16) / 255),+ srgbChannelToLinear(Number.parseInt(normalized.slice(2, 4), 16) / 255),+ srgbChannelToLinear(Number.parseInt(normalized.slice(4, 6), 16) / 255),+ alpha,+ ]) as unknown as PortableColorFactor;+};++const rgb = (hex: string, intensity = 1): PortableRgbFactor => {+ const color = rgba(hex);+ return Object.freeze([+ color[0] * intensity,+ color[1] * intensity,+ color[2] * intensity,+ ]) as unknown as PortableRgbFactor;+};++const defaults = (+ baseColor: string,+ roughnessFactor: number,+ metallicFactor = 0,+ over: Partial<PortablePbrRecipeV1> = {},+): PortablePbrRecipeV1 =>+ Object.freeze({+ baseColorFactor: rgba(baseColor),+ metallicFactor,+ roughnessFactor,+ emissiveFactor: Object.freeze([0, 0, 0]) as PortableRgbFactor,+ alphaMode: 'OPAQUE',+ doubleSided: false,+ textureResources: Object.freeze({}),+ ...over,+ });++const commonSurface = Object.freeze([+ 'baseColor',+ 'roughness',+ 'metalness',+ 'doubleSided',+ 'textureResources',+] satisfies MaterialRecipeOverrideKey[]);++const descriptor = (+ value: Omit<+ MaterialRecipeDescriptorV1,+ 'schemaVersion' | 'version' | 'portable' | 'gltfMaterialModel'+ >,+): MaterialRecipeDescriptorV1 =>+ Object.freeze({+ schemaVersion: 1,+ version: 1,+ portable: true,+ gltfMaterialModel: 'pbrMetallicRoughness',+ ...value,+ });++export const MATERIAL_RECIPE_LIBRARY_V1: Readonly<+ Record<MaterialRecipeId, MaterialRecipeDescriptorV1>+> = Object.freeze({+ 'kiln.material.bark.v1': descriptor({+ id: 'kiln.material.bark.v1',+ name: 'Bark',+ description: 'Rough, nonmetal tree bark with optional approved albedo and normal resources.',+ allowedOverrides: commonSurface,+ defaults: defaults('#6b4426', 0.93),+ }),+ 'kiln.material.leaf.v1': descriptor({+ id: 'kiln.material.leaf.v1',+ name: 'Leaf',+ description: 'Alpha-tested, double-sided foliage using glTF MASK rather than blending.',+ allowedOverrides: Object.freeze([+ 'baseColor',+ 'roughness',+ 'alphaCutoff',+ 'doubleSided',+ 'textureResources',+ ]),+ defaults: defaults('#3f7f3a', 0.86, 0, {+ alphaMode: 'MASK',+ alphaCutoff: 0.5,+ doubleSided: true,+ }),+ }),+ 'kiln.material.wood.v1': descriptor({+ id: 'kiln.material.wood.v1',+ name: 'Wood',+ description: 'Portable nonmetal wood with a warm authored base color.',+ allowedOverrides: commonSurface,+ defaults: defaults('#9a6a3a', 0.78),+ }),+ 'kiln.material.stone.v1': descriptor({+ id: 'kiln.material.stone.v1',+ name: 'Stone',+ description: 'Dry rough stone with no runtime shader dependency.',+ allowedOverrides: commonSurface,+ defaults: defaults('#7d7a74', 0.95),+ }),+ 'kiln.material.rubber.v1': descriptor({+ id: 'kiln.material.rubber.v1',+ name: 'Rubber',+ description: 'Dark, high-roughness rubber for tires, grips, and seals.',+ allowedOverrides: commonSurface,+ defaults: defaults('#202124', 0.88),+ }),+ 'kiln.material.painted-metal.v1': descriptor({+ id: 'kiln.material.painted-metal.v1',+ name: 'Painted metal',+ description: 'Coated metal with restrained metallic response and a durable painted finish.',+ allowedOverrides: commonSurface,+ defaults: defaults('#b33a32', 0.38, 0.18),+ }),+ 'kiln.material.cloth.v1': descriptor({+ id: 'kiln.material.cloth.v1',+ name: 'Cloth',+ description: 'Very rough, nonmetal woven cloth represented with core glTF PBR.',+ allowedOverrides: commonSurface,+ defaults: defaults('#6f7583', 1),+ }),+ 'kiln.material.skin.v1': descriptor({+ id: 'kiln.material.skin.v1',+ name: 'Skin',+ description: 'Portable skin baseline without nonstandard subsurface extensions.',+ allowedOverrides: Object.freeze(['baseColor', 'roughness', 'doubleSided']),+ defaults: defaults('#b87962', 0.62),+ }),+ 'kiln.material.glass.v1': descriptor({+ id: 'kiln.material.glass.v1',+ name: 'Glass',+ description: 'Portable alpha-blended glass fallback using core glTF fields only.',+ allowedOverrides: Object.freeze(['baseColor', 'roughness', 'opacity', 'doubleSided']),+ defaults: defaults('#a9d8e8', 0.12, 0, {+ baseColorFactor: rgba('#a9d8e8', 0.32),+ alphaMode: 'BLEND',+ doubleSided: true,+ }),+ }),+ 'kiln.material.emissive.v1': descriptor({+ id: 'kiln.material.emissive.v1',+ name: 'Emissive',+ description: 'Core glTF emissive material with intensity baked into emissiveFactor.',+ allowedOverrides: Object.freeze([+ 'baseColor',+ 'roughness',+ 'doubleSided',+ 'emissiveColor',+ 'emissiveIntensity',+ 'textureResources',+ ]),+ defaults: defaults('#3a2410', 0.5, 0, {+ emissiveFactor: rgb('#ff8a22', 1),+ }),+ }),+});++export const APPROVED_TEXTURE_RESOURCES_V1: Readonly<+ Record<ApprovedTextureResourceId, ApprovedTextureResourceDescriptorV1>+> = Object.freeze({+ 'kiln.texture.bark-albedo.v1': Object.freeze({+ schemaVersion: 1,+ id: 'kiln.texture.bark-albedo.v1',+ version: 1,+ label: 'Bark albedo reference',+ usage: 'albedo',+ colorSpace: 'srgb',+ mime: 'image/png',+ contentHash: 'ec74fd42fe317f578018a13a65d81a726e9baeade068ae016cff30c15507017f',+ allowedSlots: Object.freeze(['baseColor'] as const),+ recipeIds: Object.freeze(['kiln.material.bark.v1', 'kiln.material.wood.v1'] as const),+ }),+ 'kiln.texture.leaf-mask-albedo.v1': Object.freeze({+ schemaVersion: 1,+ id: 'kiln.texture.leaf-mask-albedo.v1',+ version: 1,+ label: 'Leaf alpha-mask albedo reference',+ usage: 'albedo',+ colorSpace: 'srgb',+ mime: 'image/png',+ contentHash: 'ae9ad7f5389529a42fd9e63cb16aa7dc2c803739953242422b0ccc8003bd827c',+ allowedSlots: Object.freeze(['baseColor'] as const),+ recipeIds: Object.freeze(['kiln.material.leaf.v1'] as const),+ }),+ 'kiln.texture.neutral-normal.v1': Object.freeze({+ schemaVersion: 1,+ id: 'kiln.texture.neutral-normal.v1',+ version: 1,+ label: 'Neutral tangent-space normal',+ usage: 'normal',+ colorSpace: 'linear',+ mime: 'image/png',+ contentHash: '2be025139faed13fb12ac50101f7d91f8a758ce6a668104a7e8003eccdab7db7',+ allowedSlots: Object.freeze(['normal'] as const),+ recipeIds: Object.freeze([+ 'kiln.material.bark.v1',+ 'kiln.material.wood.v1',+ 'kiln.material.stone.v1',+ 'kiln.material.rubber.v1',+ 'kiln.material.painted-metal.v1',+ 'kiln.material.cloth.v1',+ ] as const),+ }),+ 'kiln.texture.neutral-metallic-roughness.v1': Object.freeze({+ schemaVersion: 1,+ id: 'kiln.texture.neutral-metallic-roughness.v1',+ version: 1,+ label: 'Packed roughness-metalness reference',+ usage: 'metallicRoughness',+ colorSpace: 'linear',+ mime: 'image/png',+ contentHash: '5e03d1e2863800c5f1a88411dd4447ccc0ec8470232129d8682db8f6ea76ad52',+ allowedSlots: Object.freeze(['metallicRoughness'] as const),+ recipeIds: Object.freeze([+ 'kiln.material.rubber.v1',+ 'kiln.material.painted-metal.v1',+ ] as const),+ }),+ 'kiln.texture.emissive-grid.v1': Object.freeze({+ schemaVersion: 1,+ id: 'kiln.texture.emissive-grid.v1',+ version: 1,+ label: 'Emissive grid reference',+ usage: 'emissive',+ colorSpace: 'srgb',+ mime: 'image/png',+ contentHash: 'a0b2f4e243ec0ec914b80d4998cf4624ff68181aafc4b97a6bafa765a41e4814',+ allowedSlots: Object.freeze(['emissive'] as const),+ recipeIds: Object.freeze(['kiln.material.emissive.v1'] as const),+ }),+});++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const recipeId = (value: unknown): value is MaterialRecipeId =>+ typeof value === 'string' && (MATERIAL_RECIPE_IDS as readonly string[]).includes(value);++const resourceId = (value: unknown): value is ApprovedTextureResourceId =>+ typeof value === 'string' && (APPROVED_TEXTURE_RESOURCE_IDS as readonly string[]).includes(value);++const finiteUnit = (value: unknown): value is number =>+ typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1;++const hexColor = (value: unknown): value is string =>+ typeof value === 'string' && /^#[0-9a-fA-F]{6}$/.test(value);++export function validateMaterialRecipeRequestV1(value: unknown): MaterialRecipeValidationResult {+ const issues: MaterialRecipeValidationIssue[] = [];+ if (!isRecord(value)) {+ return {+ valid: false,+ issues: [{ code: 'EXPECTED_OBJECT', path: '', message: 'materialRecipe must be an object.' }],+ };+ }+ if (value.schemaVersion !== 1) {+ issues.push({+ code: 'UNSUPPORTED_SCHEMA_VERSION',+ path: 'schemaVersion',+ message: 'materialRecipe.schemaVersion must be 1.',+ });+ }+ if (!recipeId(value.id)) {+ issues.push({+ code: 'UNSUPPORTED_RECIPE_ID',+ path: 'id',+ message: `Unsupported material recipe ID ${JSON.stringify(value.id)}.`,+ });+ }+ if (value.overrides !== undefined && !isRecord(value.overrides)) {+ issues.push({+ code: 'INVALID_OVERRIDES',+ path: 'overrides',+ message: 'materialRecipe.overrides must be an object.',+ });+ }+ if (recipeId(value.id) && isRecord(value.overrides)) {+ const allowed = new Set(MATERIAL_RECIPE_LIBRARY_V1[value.id].allowedOverrides);+ for (const [key, override] of Object.entries(value.overrides)) {+ if (!(MATERIAL_RECIPE_OVERRIDE_KEYS as readonly string[]).includes(key)) {+ issues.push({+ code: 'UNSUPPORTED_OVERRIDE',+ path: `overrides.${key}`,+ message: `Unknown material recipe override ${JSON.stringify(key)}.`,+ });+ continue;+ }+ if (!allowed.has(key as MaterialRecipeOverrideKey)) {+ issues.push({+ code: 'UNSUPPORTED_OVERRIDE',+ path: `overrides.${key}`,+ message: `${key} is not supported by ${value.id}.`,+ });+ continue;+ }+ if ((key === 'baseColor' || key === 'emissiveColor') && !hexColor(override)) {+ issues.push({+ code: 'INVALID_OVERRIDE_VALUE',+ path: `overrides.${key}`,+ message: `${key} must be a six-digit #RRGGBB color.`,+ });+ } else if (+ (key === 'roughness' ||+ key === 'metalness' ||+ key === 'opacity' ||+ key === 'alphaCutoff') &&+ !finiteUnit(override)+ ) {+ issues.push({+ code: 'INVALID_OVERRIDE_VALUE',+ path: `overrides.${key}`,+ message: `${key} must be a finite number in [0,1].`,+ });+ } else if (key === 'doubleSided' && typeof override !== 'boolean') {+ issues.push({+ code: 'INVALID_OVERRIDE_VALUE',+ path: `overrides.${key}`,+ message: 'doubleSided must be boolean.',+ });+ } else if (+ key === 'emissiveIntensity' &&+ (typeof override !== 'number' || !Number.isFinite(override) || override < 0 || override > 1)+ ) {+ issues.push({+ code: 'INVALID_OVERRIDE_VALUE',+ path: `overrides.${key}`,+ message: 'emissiveIntensity must be a finite number in [0,1] for core glTF.',+ });+ } else if (key === 'textureResources') {+ if (!isRecord(override)) {+ issues.push({+ code: 'INVALID_OVERRIDE_VALUE',+ path: 'overrides.textureResources',+ message: 'textureResources must be an object keyed by portable material slot.',+ });+ continue;+ }+ for (const [slot, selected] of Object.entries(override)) {+ if (!(MATERIAL_TEXTURE_SLOTS as readonly string[]).includes(slot)) {+ issues.push({+ code: 'UNKNOWN_TEXTURE_SLOT',+ path: `overrides.textureResources.${slot}`,+ message: `Unknown portable texture slot ${JSON.stringify(slot)}.`,+ });+ continue;+ }+ if (!resourceId(selected)) {+ issues.push({+ code: 'UNSUPPORTED_RESOURCE_ID',+ path: `overrides.textureResources.${slot}`,+ message: `Unsupported approved texture resource ID ${JSON.stringify(selected)}.`,+ });+ continue;+ }+ const resource = APPROVED_TEXTURE_RESOURCES_V1[selected];+ if (!resource.allowedSlots.includes(slot as MaterialTextureSlot)) {+ issues.push({+ code: 'RESOURCE_SLOT_MISMATCH',+ path: `overrides.textureResources.${slot}`,+ message: `${selected} cannot be used in ${slot}.`,+ });+ }+ if (!resource.recipeIds.includes(value.id)) {+ issues.push({+ code: 'RESOURCE_RECIPE_MISMATCH',+ path: `overrides.textureResources.${slot}`,+ message: `${selected} is not approved for ${value.id}.`,+ });+ }+ }+ }+ }+ }++ if (issues.length > 0) return { valid: false, issues };+ return {+ valid: true,+ value: cloneMaterialRecipeRequestV1(value as unknown as MaterialRecipeRequestV1),+ issues,+ };+}++export function cloneMaterialRecipeRequestV1(+ value: MaterialRecipeRequestV1,+): MaterialRecipeRequestV1 {+ return {+ schemaVersion: 1,+ id: value.id,+ ...(value.overrides+ ? {+ overrides: {+ ...value.overrides,+ ...(value.overrides.textureResources+ ? { textureResources: { ...value.overrides.textureResources } }+ : {}),+ },+ }+ : {}),+ };+}++export function createMaterialRecipeRequestV1(+ id: MaterialRecipeId,+ overrides?: MaterialRecipeOverridesV1,+): MaterialRecipeRequestV1 {+ const candidate = { schemaVersion: 1 as const, id, ...(overrides ? { overrides } : {}) };+ const result = validateMaterialRecipeRequestV1(candidate);+ if (!result.valid || !result.value) {+ throw new TypeError(result.issues.map((issue) => `${issue.path}: ${issue.message}`).join('; '));+ }+ return result.value;+}++export function resolveMaterialRecipeV1(value: MaterialRecipeRequestV1): PortablePbrRecipeV1 {+ const validation = validateMaterialRecipeRequestV1(value);+ if (!validation.valid || !validation.value) {+ throw new TypeError(+ validation.issues.map((issue) => `${issue.path}: ${issue.message}`).join('; '),+ );+ }+ const recipe = MATERIAL_RECIPE_LIBRARY_V1[validation.value.id];+ const over = validation.value.overrides ?? {};+ const baseAlpha = over.opacity ?? recipe.defaults.baseColorFactor[3];+ const baseColorFactor = over.baseColor+ ? rgba(over.baseColor, baseAlpha)+ : (Object.freeze([+ recipe.defaults.baseColorFactor[0],+ recipe.defaults.baseColorFactor[1],+ recipe.defaults.baseColorFactor[2],+ baseAlpha,+ ]) as PortableColorFactor);+ const emissiveIntensity = over.emissiveIntensity;+ const emissiveFactor = over.emissiveColor+ ? rgb(over.emissiveColor, over.emissiveIntensity ?? 1)+ : emissiveIntensity !== undefined+ ? (Object.freeze(+ recipe.defaults.emissiveFactor.map((component) => component * emissiveIntensity),+ ) as unknown as PortableRgbFactor)+ : recipe.defaults.emissiveFactor;+ return Object.freeze({+ baseColorFactor,+ metallicFactor: over.metalness ?? recipe.defaults.metallicFactor,+ roughnessFactor: over.roughness ?? recipe.defaults.roughnessFactor,+ emissiveFactor,+ alphaMode: recipe.defaults.alphaMode,+ ...(recipe.defaults.alphaMode === 'MASK'+ ? { alphaCutoff: over.alphaCutoff ?? recipe.defaults.alphaCutoff ?? 0.5 }+ : {}),+ doubleSided: over.doubleSided ?? recipe.defaults.doubleSided,+ textureResources: Object.freeze({+ ...recipe.defaults.textureResources,+ ...(over.textureResources ?? {}),+ }),+ });+}++export function listMaterialRecipeCapabilitiesV1(): {+ schemaVersion: 1;+ requestShape: string;+ recipes: MaterialRecipeDescriptorV1[];+ resources: ApprovedTextureResourceDescriptorV1[];+} {+ return {+ schemaVersion: 1,+ requestShape: 'materialRecipe: { schemaVersion: 1, id, overrides? }',+ recipes: MATERIAL_RECIPE_IDS.map((id) => MATERIAL_RECIPE_LIBRARY_V1[id]),+ resources: APPROVED_TEXTURE_RESOURCE_IDS.map((id) => APPROVED_TEXTURE_RESOURCES_V1[id]),+ };+}++/** Stable JSON-ready snapshot used by engine, SDK, MCP, Studio, and starter parity tests. */+export function materialRecipeSnapshotV1(): Array<{+ id: MaterialRecipeId;+ name: string;+ allowedOverrides: readonly MaterialRecipeOverrideKey[];+ defaults: PortablePbrRecipeV1;+}> {+ return MATERIAL_RECIPE_IDS.map((id) => {+ const recipe = MATERIAL_RECIPE_LIBRARY_V1[id];+ return {+ id,+ name: recipe.name,+ allowedOverrides: recipe.allowedOverrides,+ defaults: recipe.defaults,+ };+ });+}diff --git a/src/material-resources.ts b/src/material-resources.tsnew file mode 100644index 00000000..a4836062--- /dev/null+++ b/src/material-resources.ts@@ -0,0 +1,239 @@+/** Approved, ID-only texture resources and content-addressed runtime cache. */++import { createHash } from 'node:crypto';+import type * as THREE from 'three';++import {+ APPROVED_TEXTURE_RESOURCE_IDS,+ APPROVED_TEXTURE_RESOURCES_V1,+ type ApprovedTextureResourceId,+} from './material-recipes';+import {+ loadTexture,+ type KilnTextureMetadata,+ type TextureLoadOptions,+ type TextureSource,+ type TextureUsage,+} from './textures';++export interface MaterialResourceProvenanceV1 {+ schemaVersion: 1;+ resourceId: ApprovedTextureResourceId;+ contentHash: string;+ hashAlgorithm: 'sha256';+ usage: TextureUsage;+ colorSpace: 'srgb' | 'linear';+ resourceVersion: 1;+ recipeVersion: 1;+}++export interface ApprovedTextureResolutionV1 {+ descriptor: (typeof APPROVED_TEXTURE_RESOURCES_V1)[ApprovedTextureResourceId];+ /** Caller-owned copy; the cache retains one canonical content-addressed byte array. */+ bytes: Uint8Array;+ provenance: MaterialResourceProvenanceV1;+}++export interface LoadedApprovedTextureV1 extends ApprovedTextureResolutionV1 {+ texture: THREE.DataTexture;+}++export interface MaterialResourceCacheStatsV1 {+ approvedIdsResolved: number;+ uniqueContentHashes: number;+ decodedTextureVariants: number;+ encodedBytes: number;+}++const EMBEDDED_RESOURCE_BASE64: Readonly<Record<ApprovedTextureResourceId, string>> = Object.freeze(+ {+ 'kiln.texture.bark-albedo.v1':+ 'iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAFklEQVQImWMIMpT6X+Ch9h9GM5AuAACfBRvJB4zLLQAAAABJRU5ErkJggg==',+ 'kiln.texture.leaf-mask-albedo.v1':+ 'iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAKUlEQVQImWMwaLFiMGixSjBosdoCYsM4/6E4ASQAkoEJbAEJwARBKhkACRMXLR+u+yUAAAAASUVORK5CYII=',+ 'kiln.texture.neutral-normal.v1':+ 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEUlEQVQImWNoaPj/H4QZYAwAZ9IL+W19YCAAAAAASUVORK5CYII=',+ 'kiln.texture.neutral-metallic-roughness.v1':+ 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEElEQVQImWNguCT0H4xhDAA/hAeNGSjqWAAAAABJRU5ErkJggg==',+ 'kiln.texture.emissive-grid.v1':+ 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAFklEQVQImWP4P0Hhv4MEy38GEAHiAABG+wgTqOP6IAAAAABJRU5ErkJggg==',+ },+);++const isApprovedId = (value: string): value is ApprovedTextureResourceId =>+ (APPROVED_TEXTURE_RESOURCE_IDS as readonly string[]).includes(value);++const bytesFromBase64 = (value: string): Uint8Array => new Uint8Array(Buffer.from(value, 'base64'));+const sha256 = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');++function usageForResource(id: ApprovedTextureResourceId): TextureUsage {+ return APPROVED_TEXTURE_RESOURCES_V1[id].usage;+}++function provenance(id: ApprovedTextureResourceId, hash: string): MaterialResourceProvenanceV1 {+ const descriptor = APPROVED_TEXTURE_RESOURCES_V1[id];+ return {+ schemaVersion: 1,+ resourceId: id,+ contentHash: hash,+ hashAlgorithm: 'sha256',+ usage: usageForResource(id),+ colorSpace: descriptor.colorSpace,+ resourceVersion: descriptor.version,+ recipeVersion: 1,+ };+}++/**+ * The only path used by new generations/refines. Inputs are closed approved+ * IDs, and the returned DTO contains no filesystem location, URL, credential,+ * or provider-specific identifier.+ */+export class ApprovedTextureResourceCache {+ readonly #bytesByHash = new Map<string, Uint8Array>();+ readonly #hashById = new Map<ApprovedTextureResourceId, string>();+ readonly #textureByVariant = new Map<string, Promise<THREE.DataTexture>>();++ resolve(id: ApprovedTextureResourceId): ApprovedTextureResolutionV1 {+ if (!isApprovedId(id)) throw new RangeError(`Unsupported approved texture resource ID ${id}.`);+ let hash = this.#hashById.get(id);+ let canonical: Uint8Array | undefined;+ if (!hash) {+ const decoded = bytesFromBase64(EMBEDDED_RESOURCE_BASE64[id]);+ hash = sha256(decoded);+ if (hash !== APPROVED_TEXTURE_RESOURCES_V1[id].contentHash) {+ throw new Error(`Approved resource ${id} failed its pinned content hash.`);+ }+ canonical = this.#bytesByHash.get(hash);+ if (!canonical) {+ canonical = decoded;+ this.#bytesByHash.set(hash, canonical);+ }+ this.#hashById.set(id, hash);+ } else {+ canonical = this.#bytesByHash.get(hash);+ }+ if (!canonical) throw new Error(`Approved resource cache lost content ${hash}.`);+ return {+ descriptor: APPROVED_TEXTURE_RESOURCES_V1[id],+ bytes: canonical.slice(),+ provenance: provenance(id, hash),+ };+ }++ async load(id: ApprovedTextureResourceId): Promise<LoadedApprovedTextureV1> {+ const resolved = this.resolve(id);+ const variantKey = [+ resolved.provenance.contentHash,+ resolved.provenance.usage,+ resolved.provenance.colorSpace,+ ].join(':');+ let pending = this.#textureByVariant.get(variantKey);+ if (!pending) {+ pending = loadTexture(resolved.bytes, {+ usage: resolved.provenance.usage,+ name: id,+ }).then((texture) => {+ const metadata = (texture.userData as Record<string, unknown>)['kilnTexture'] as+ | KilnTextureMetadata+ | undefined;+ (texture.userData as Record<string, unknown>)['kilnTexture'] = {+ ...metadata,+ approvedResource: resolved.provenance,+ };+ return texture;+ });+ this.#textureByVariant.set(variantKey, pending);+ }+ return { ...resolved, texture: await pending };+ }++ stats(): MaterialResourceCacheStatsV1 {+ return {+ approvedIdsResolved: this.#hashById.size,+ uniqueContentHashes: this.#bytesByHash.size,+ decodedTextureVariants: this.#textureByVariant.size,+ encodedBytes: [...this.#bytesByHash.values()].reduce(+ (sum, bytes) => sum + bytes.byteLength,+ 0,+ ),+ };+ }+}++export const DEFAULT_APPROVED_TEXTURE_CACHE = new ApprovedTextureResourceCache();++export function resolveApprovedTextureResource(+ id: ApprovedTextureResourceId,+): ApprovedTextureResolutionV1 {+ return DEFAULT_APPROVED_TEXTURE_CACHE.resolve(id);+}++export async function loadApprovedTextureResource(+ id: ApprovedTextureResourceId,+): Promise<LoadedApprovedTextureV1> {+ return DEFAULT_APPROVED_TEXTURE_CACHE.load(id);+}++/**+ * Compatibility-only reader for historical source programs. New manifests and+ * prompts must use loadApprovedTextureResource() so an untrusted model cannot+ * select a host path. This function deliberately does not claim approved+ * provenance.+ */+export async function loadLegacyTextureSource(+ source: TextureSource,+ options: TextureLoadOptions = {},+): Promise<THREE.DataTexture> {+ const texture = await loadTexture(source, options);+ (texture.userData as Record<string, unknown>)['kilnTextureSource'] = {+ schemaVersion: 1,+ source: 'legacy-compatible-read',+ };+ return texture;+}++export function readMaterialResourceProvenance(+ texture: THREE.Texture,+): MaterialResourceProvenanceV1 | undefined {+ const metadata = (texture.userData as Record<string, unknown>)['kilnTexture'] as+ | { approvedResource?: MaterialResourceProvenanceV1 }+ | undefined;+ return metadata?.approvedResource;+}++const materialTextures = (material: THREE.Material): THREE.Texture[] => {+ const standard = material as THREE.MeshStandardMaterial;+ const candidates = [+ standard.map,+ standard.normalMap,+ standard.roughnessMap,+ standard.metalnessMap,+ standard.emissiveMap,+ standard.aoMap,+ ];+ return [+ ...new Set(candidates.filter((value): value is THREE.Texture => value?.isTexture === true)),+ ];+};++/** Deterministic scene-side provenance hook for render/wire/provenance integration. */+export function collectMaterialResourceProvenance(+ root: THREE.Object3D,+): MaterialResourceProvenanceV1[] {+ const records = new Map<string, MaterialResourceProvenanceV1>();+ root.traverse((node) => {+ const material = (node as THREE.Mesh).material;+ const materials = Array.isArray(material) ? material : material ? [material] : [];+ for (const item of materials) {+ for (const texture of materialTextures(item)) {+ const record = readMaterialResourceProvenance(texture);+ if (record)+ records.set(`${record.resourceId}:${record.contentHash}:${record.usage}`, record);+ }+ }+ });+ return [...records.values()].sort((a, b) =>+ `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`),+ );+}diff --git a/src/primitives.ts b/src/primitives.tsindex 7f4ec519..d0a55a85 100644--- a/src/primitives.ts+++ b/src/primitives.ts@@ -10,13 +10,65 @@*/import * as THREE from 'three';+import { createJointChain } from './character';+import {+ createGableEndPanel,+ createGableRoof,+ createGableShell,+ createRoofPlanes as createRoofPlanesExplicit,+ createRoofSurfaceLayout,+} from './architecture';import * as gears from './gears';import * as ops from './ops';import * as solids from './solids';import * as textures from './textures';+import { materialRecipe } from './material-recipe-runtime';+import { createVehicleFrame, createWheelAssembly, createWheelGeometrySet } from './vehicle';+import {+ stampSemanticMetadataV1,+ type AssetCategory,+ type SemanticMetadataV1,+ type SemanticMetadataV1Input,+} from './contracts';import * as uv from './uv';import * as uvShapes from './uv-shapes';+export {+ createGableEndPanel,+ createGableRoof,+ createGableShell,+ createRoofSurfaceLayout,+} from './architecture';+export type {+ GableEndPanelOptions,+ GableRoofOptions,+ GableShellOptions,+ RoofFaceFrame,+ RoofSurfaceLayoutOptions,+} from './architecture';+export { createJointChain } from './character';+export type {+ CreateJointChainOptionsV1,+ JointChainResultV1,+ JointChainSegmentV1,+} from './character';+export {+ createVehicleFrame,+ createWheelAssembly,+ createWheelGeometrySet,+} from './vehicle';+export { materialRecipe } from './material-recipe-runtime';+export type { ApplyMaterialRecipeOptions } from './material-recipe-runtime';+export type { MaterialRecipeId, MaterialRecipeOverridesV1 } from './material-recipes';+export type {+ VehicleFrameOptions,+ VehicleFrameResult,+ WheelAssemblyOptions,+ WheelAssemblyResult,+ WheelGeometrySet,+ WheelMaterialSet,+} from './vehicle';+type Vec3Tuple = [number, number, number];function vectorToTuple(v: THREE.Vector3): Vec3Tuple {@@ -69,6 +121,9 @@ export function createPart(scale?: [number, number, number];pivot?: boolean; // Wrap in pivot for animationparent?: THREE.Object3D;+ /** Versioned roles/relationships/local frames/sockets stamped on the returned+ * helper node and preserved in glTF node extras. */+ semantic?: SemanticMetadataV1 | SemanticMetadataV1Input;} = {},): THREE.Object3D {const mesh = new THREE.Mesh(geometry, material);@@ -90,10 +145,12 @@ export function createPart(mesh.position.set(0, 0, 0); // Reset - pivot controls positionif (options.position) pivot.position.set(...options.position);if (options.parent) options.parent.add(pivot);+ if (options.semantic) stampSemanticMetadataV1(pivot, options.semantic);return pivot; // Return the pivot (the animatable node)}if (options.parent) options.parent.add(mesh);+ if (options.semantic) stampSemanticMetadataV1(mesh, options.semantic);return mesh; // Return the mesh}@@ -324,6 +381,7 @@ export function foliageCardGeo(opts: FoliageCardOptions = {}): THREE.PlaneGeometconst geom = new THREE.PlaneGeometry(w, h);// Shift so the pivot offset becomes the local origin.geom.translate(0, h * (0.5 - yPivot), 0);+ geom.userData['kilnGeometryRole'] = 'foliageCard';return geom;}@@ -388,6 +446,7 @@ export function crossedQuadsGeo(opts: CrossedQuadsOptions = {}): THREE.BufferGeoout.setAttribute('normal', new THREE.BufferAttribute(normals, 3));out.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));out.setIndex(indices);+ out.userData['kilnGeometryRole'] = 'foliageCard';return out;}@@ -962,48 +1021,22 @@ export function createRoofPlanes(material: THREE.Material,options: RoofPlanesOptions,): { root: THREE.Object3D; slopes: [THREE.Object3D, THREE.Object3D] } {- const {- width,- depth,- height,- overhang = 0.3,- ridgeAxis = 'x',- thickness = 0.08,- parent,- } = options;- const group = new THREE.Object3D();- group.name = name;-- // Half-span of the slope direction (perpendicular to the ridge) + overhang,- // and the ridge-direction length.- const halfSpan = (ridgeAxis === 'x' ? width : depth) / 2 + overhang;- const ridgeLen = (ridgeAxis === 'x' ? depth : width) + overhang * 2;- const rafterLen = Math.hypot(halfSpan, height);- const angle = Math.atan2(height, halfSpan);-- const slopes: THREE.Object3D[] = [];- for (const side of [1, -1] as const) {- const geo =- ridgeAxis === 'x'- ? boxGeo(ridgeLen, thickness, rafterLen)- : boxGeo(rafterLen, thickness, ridgeLen);- const mesh = new THREE.Mesh(geo, material);- mesh.name = `Mesh_${name}${side > 0 ? 'A' : 'B'}`;- if (ridgeAxis === 'x') {- // Ridge along X; slopes drop toward +Z (side=+1) / -Z (side=-1).- mesh.position.set(0, height / 2, (side * halfSpan) / 2);- mesh.rotation.x = side * angle;- } else {- // Ridge along Z; slopes drop toward +X (side=+1) / -X (side=-1).- mesh.position.set((side * halfSpan) / 2, height / 2, 0);- mesh.rotation.z = -side * angle;- }- group.add(mesh);- slopes.push(mesh);+ const result = createRoofPlanesExplicit(name, material, options);+ result.slopes[0].name = `Mesh_${name}A`;+ result.slopes[1].name = `Mesh_${name}B`;+ for (let index = 0; index < result.slopes.length; index++) {+ const normal = new THREE.Vector3().setFromMatrixColumn(result.faces[index]!.localToRoof, 1);+ result.slopes[index]!.position.addScaledVector(normal, (options.thickness ?? 0.08) / 2);}-- if (parent) parent.add(group);- return { root: group, slopes: [slopes[0]!, slopes[1]!] };+ // Preserve the legacy, opposite-sign X Euler readout for ridge-X callers.+ // The explicit face frame reverses the negative face's ridge tangent to stay+ // right-handed, whose equivalent default Euler representation differs by PI.+ if ((options.ridgeAxis ?? 'x') === 'x') {+ const halfRun = options.width / 2 + (options.overhang ?? 0.3);+ const angle = Math.atan2(options.height, halfRun);+ result.slopes[1].rotation.set(-angle, Math.PI, 0);+ }+ return result;}export interface StairsOptions {@@ -1384,6 +1417,10 @@ export function countTriangles(root: THREE.Object3D): number {const position = geometry.getAttribute('position');if (position) count += position.count / 3;}+ } else if ((child as { isSprite?: boolean }).isSprite) {+ // The canonical GLB bridge materializes every Three.js Sprite as one+ // semantic camera-facing quad.+ count += 2;}});return Math.floor(count);@@ -1395,10 +1432,14 @@ export function countMaterials(root: THREE.Object3D): number {if ((child as { isMesh?: boolean }).isMesh) {const meshChild = child as THREE.Mesh;if (Array.isArray(meshChild.material)) {- meshChild.material.forEach((m) => materials.add(m));+ meshChild.material.forEach((material) => {+ materials.add(material);+ });} else {materials.add(meshChild.material);}+ } else if ((child as { isSprite?: boolean }).isSprite) {+ materials.add((child as THREE.Sprite).material);}});return materials.size;@@ -1420,7 +1461,7 @@ export function getJointNames(root: THREE.Object3D): string[] {*/export function validateAsset(root: THREE.Object3D,- category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture',+ category: AssetCategory,): { valid: boolean; errors: string[]; warnings: string[] } {const errors: string[] = [];const warnings: string[] = [];@@ -1431,6 +1472,8 @@ export function validateAsset(vfx: { suggestedTris: 2000, suggestedMats: 4 },environment: { suggestedTris: 15000, suggestedMats: 12 },architecture: { suggestedTris: 15000, suggestedMats: 12 },+ vegetation: { suggestedTris: 12000, suggestedMats: 8 },+ vehicle: { suggestedTris: 20000, suggestedMats: 10 },};const limits = guidelines[category];@@ -1542,6 +1585,10 @@ export function buildSandboxGlobals(usage?: Record<string, number>): Record<strireturn {createRoot: wrap('createRoot', createRoot),createPivot: wrap('createPivot', createPivot),+ createJointChain: wrap('createJointChain', createJointChain),+ createVehicleFrame: wrap('createVehicleFrame', createVehicleFrame),+ createWheelGeometrySet: wrap('createWheelGeometrySet', createWheelGeometrySet),+ createWheelAssembly: wrap('createWheelAssembly', createWheelAssembly),createPart: wrap('createPart', createPart),capsuleGeo: wrapGeo('capsuleGeo', capsuleGeo),capsuleXGeo: wrapGeo('capsuleXGeo', capsuleXGeo),@@ -1573,8 +1620,13 @@ export function buildSandboxGlobals(usage?: Record<string, number>): Record<striroom: wrap('room', room),wallWithOpening: wrap('wallWithOpening', wallWithOpening),createRoofPlanes: wrap('createRoofPlanes', createRoofPlanes),+ createGableRoof: wrap('createGableRoof', createGableRoof),+ createGableEndPanel: wrap('createGableEndPanel', createGableEndPanel),+ createGableShell: wrap('createGableShell', createGableShell),+ createRoofSurfaceLayout: wrap('createRoofSurfaceLayout', createRoofSurfaceLayout),createStairs: wrap('createStairs', createStairs),gameMaterial: wrap('gameMaterial', gameMaterial),+ materialRecipe: wrap('materialRecipe', materialRecipe),basicMaterial: wrap('basicMaterial', basicMaterial),glassMaterial: wrap('glassMaterial', glassMaterial),lambertMaterial: wrap('lambertMaterial', lambertMaterial),@@ -1617,6 +1669,7 @@ export function buildSandboxGlobals(usage?: Record<string, number>): Record<stri// Textures + PBR (loadTexture is async)loadTexture: wrap('loadTexture', textures.loadTexture),pbrMaterial: wrap('pbrMaterial', textures.pbrMaterial),+ foliageMaterial: wrap('foliageMaterial', textures.foliageMaterial),countTriangles: wrap('countTriangles', countTriangles),countMaterials: wrap('countMaterials', countMaterials),getJointNames: wrap('getJointNames', getJointNames),diff --git a/src/prompt.ts b/src/prompt.tsindex 1784a6f1..df411cd3 100644--- a/src/prompt.ts+++ b/src/prompt.ts@@ -17,9 +17,17 @@import { listPrimitives } from './list-primitives';import { renderApiSection } from './prompt-api';+import { KILN_ASSET_FRAME, type AssetCategory, type AssetIntentV1 } from './contracts';+import { characterBodyPlanRecipe } from './character';+import { MATERIAL_RECIPE_PROMPT_CONTEXT_V1 } from './material-recipe-prompt';+import { vegetationSubtypePromptContext } from './vegetation-prompt';+import { vehicleSubtypeRecipe } from './vehicle';+import { renderAssetScopePrompt, renderVfxBreadthPrompt } from './breadth-prompt';+import { buildPropEnvironmentSemanticGuidance } from './qa/prop-environment-prompt';++export type { AssetCategory } from './contracts';export type RenderMode = 'glb' | 'tsl' | 'both';-export type AssetCategory = 'character' | 'prop' | 'vfx' | 'environment' | 'architecture';export type AssetStyle = 'low-poly' | 'stylized' | 'voxel' | 'detailed' | 'realistic';// =============================================================================@@ -110,10 +118,10 @@ function animate(root) { // optionalexport const KILN_COORDINATE_CONTRACT = `<coordinate-contract>World coordinates are strict:-- +X = forward / nose / muzzle direction-- +Y = up-- +Z = asset right side-- Ground rests at Y=0+- ${KILN_ASSET_FRAME.forward} = forward / nose / muzzle direction+- ${KILN_ASSET_FRAME.up} = up+- ${KILN_ASSET_FRAME.right} = asset right side+- Ground rests at Y=${KILN_ASSET_FRAME.groundY}Vehicles, aircraft, weapons, boats, and buildings must follow this frame. If apart points forward, build it along +X. If a part spans left/right, build it@@ -782,6 +790,8 @@ export interface KilnGenerateRequest {prompt: string;mode: RenderMode;category: AssetCategory;+ /** Closure-owned normalized intent; used only for resolved, category-specific guidance. */+ intent?: AssetIntentV1;style?: AssetStyle;budget?: AssetBudget;includeAnimation?: boolean;@@ -812,32 +822,96 @@ export interface KilnGenerateRequest {* Keep the two maps disjoint by category so a directive is injected exactly* once: studio owns `character`; core owns `architecture`.*/-export const ARCHITECTURE_CONTEXT =- 'This is a BUILDING the player can go INSIDE. Build it HOLLOW: thin walls enclosing real ' +- 'interior space with a floor — never a solid block. Its foundation rests flat on the ground, ' +- 'and the main entrance faces forward so the front reads clearly.\n\n' +- 'Give it true human architectural scale: a doorway tall and wide enough for a person to walk ' +- 'through, windows at standing height, and a ceiling high enough to stand under with headroom. ' +- "The building's mass should dwarf a single doorway.\n\n" +- 'Cut REAL openings into the walls — a doorway is an actual gap you could pass through, not a ' +- 'panel painted on a wall; windows are inset panes or holes flush with the wall surface. Never ' +- 'float a pane in front of a wall or bury glass inside a solid block, and never seal the entrance.\n\n' +- 'Walls meet squarely at the corners with no gaps; give large coplanar surfaces a hair of ' +- 'separation so they do not flicker. Cap it with a roof that matches the footprint and overhangs ' +- "slightly at the eaves; a pitched roof's two sides slope DOWN-AND-OUTWARD from one ridge line — " +- 'they fall away from each other, never tilt the same way. Name the roof group exactly `Roof` (its ' +- 'own part) so the engine — and the interior view — can lift it to reveal the inside.\n\n' +- 'Spend detail where a building reads: the roofline and eaves, a framed door, window sills or ' +- 'mullions, a chimney, a porch or entry overhang, a foundation course, corner posts, trim — and ' +- 'built-in fixtures (a hearth, a counter, shelving). Leave the floor space open for furniture to ' +- 'be placed later.\n\n' +- 'Use room(...) to build the hollow walled-and-floored shell with its doorway, wallWithOpening(...) ' +- 'for extra doors or windows, and createRoofPlanes(...) for the pitched roof; createStairs(...) ' +- 'makes porch steps or connects floors.\n\n' +- 'Before you finalize, call kiln_view_interior and check the roof-off views: the interior is open ' +- 'and walkable (no solid fill, no interior wall left buried in a mass), the doorway is a real gap ' +- 'you could pass through, and any built-in fixtures rest on the floor. Fix anything sealed, buried, ' +- 'or floating, then view the interior again.';+/** Complete executable architecture programs embedded only in fresh architecture requests. */+export const ARCHITECTURE_RIDGE_X_SCAFFOLD = `const meta = { name: 'RidgeXHouse', category: 'architecture' };+function build() {+ const root = createRoot('RidgeXHouse');+ const wall = gameMaterial(0xd8c4a0, { roughness: 0.9 });+ const roof = gameMaterial(0x7a3e35, { roughness: 0.82 });+ const shell = createGableShell('House', { wall, roof }, {+ spanX: 8, spanZ: 6, wallHeight: 3, rise: 1.6, overhang: 0.4,+ ridgeAxis: 'x', closedEnds: true, enterable: true, parent: root,+ openings: [{ id: 'front-door', wall: 'front', kind: 'door', width: 1.1, height: 2.1 }],+ });+ for (const face of shell.roof.faces) {+ createRoofSurfaceLayout('RoofPanels_' + face.side, roof, {+ face, kind: 'panels', panelWidth: 0.8, parent: shell.roof.root,+ });+ }+ return root;+}`;++export const ARCHITECTURE_RIDGE_Z_SCAFFOLD = `const meta = { name: 'RidgeZHouse', category: 'architecture' };+function build() {+ const root = createRoot('RidgeZHouse');+ const wall = gameMaterial(0xc9b895, { roughness: 0.92 });+ const roof = gameMaterial(0x40566e, { roughness: 0.8 });+ const shell = createGableShell('House', { wall, roof }, {+ spanX: 7, spanZ: 10, wallHeight: 3.2, rise: 1.8, overhang: 0.45,+ ridgeAxis: 'z', closedEnds: true, enterable: true, parent: root,+ openings: [{ id: 'front-door', wall: 'front', kind: 'door', width: 1.2, height: 2.2 }],+ });+ for (const face of shell.roof.faces) {+ createRoofSurfaceLayout('RoofPanels_' + face.side, roof, {+ face, kind: 'panels', panelWidth: 0.8, parent: shell.roof.root,+ });+ }+ return root;+}`;++export const ARCHITECTURE_PANEL_DIRECTION_ANTI_EXAMPLE = `// WRONG: stepping panels along face.ridgeTangent turns their long dimension along the ridge+// and leaves open strips from ridge to eave. Do not hand-place or rotate roof panels this way.+// CORRECT: pass the owned face frame to createRoofSurfaceLayout; it repeats panel widths along+// the ridge while every panel's long dimension runs downhill from ridge to eave.+createRoofSurfaceLayout('RoofPanels', roofMaterial, {+ face, kind: 'panels', panelWidth: 0.8, parent: face.roofRoot,+});`;++export const ARCHITECTURE_CONTEXT = `This is a BUILDING the player can go INSIDE. Build it HOLLOW: thin walls enclosing real+interior space with a floor — never a solid block. Its foundation rests flat on the ground,+and the main entrance faces forward so the front reads clearly.++Give it true human architectural scale: a doorway tall and wide enough for a person to walk+through, windows at standing height, and a ceiling high enough to stand under with headroom.+The building's mass should dwarf a single doorway.++Cut REAL openings into the walls — a doorway is an actual gap you could pass through, not a+panel painted on a wall; windows are inset panes or holes flush with the wall surface. Never+float a pane in front of a wall or bury glass inside a solid block, and never seal the entrance.++Walls meet squarely at the corners with no gaps. Prefer createGableShell(...) for a hollow floor,+four walls with real openings, a separable Roof assembly, two correctly opposed slopes, and closed+gable ends. Set ridgeAxis explicitly from the requested +X/+Z frame. Use createRoofSurfaceLayout(...)+with each returned face instead of guessing Euler rotations or panel directions.++## Correct scaffold — ridge along +X++\`\`\`js+${ARCHITECTURE_RIDGE_X_SCAFFOLD}+\`\`\`++## Correct scaffold — ridge along +Z++\`\`\`js+${ARCHITECTURE_RIDGE_Z_SCAFFOLD}+\`\`\`++## Roof-panel direction anti-example++\`\`\`js+${ARCHITECTURE_PANEL_DIRECTION_ANTI_EXAMPLE}+\`\`\`++Spend detail where a building reads: the roofline and eaves, a framed door, window sills or+mullions, a chimney, a porch or entry overhang, a foundation course, corner posts, trim — and+built-in fixtures (a hearth, a counter, shelving). Leave the floor space open for furniture to+be placed later. room(...), wallWithOpening(...), createRoofPlanes(...), and createStairs(...)+remain compatibility helpers for non-gable or custom construction.++Before you finalize, call kiln_view_interior and check the roof-off views: the interior is open+and walkable (no solid fill, no interior wall left buried in a mass), the doorway is a real gap+you could pass through, and any built-in fixtures rest on the floor. Fix anything sealed, buried,+or floating, then view the interior again.`;/** PROP build context — make movable parts distinct and correctly hinged so they* read well statically AND can be animated about their real pivot. */@@ -857,6 +931,24 @@ export const ENVIRONMENT_CONTEXT ='with a gentle, looping sway; when several elements move, offset their phase so they do not all swing ' +'in lockstep.';+/** VEG-018 organic construction guidance. Branch/canopy/frond experiments are+ * deliberately absent: until their gates pass, vegetation uses existing primitives. */+export const VEGETATION_CONTEXT = `This is a STANDALONE VEGETATION asset in the canonical +Y-up frame.+Build only the requested plant or fungus: do not add a terrain disk, soil mound, rocks, pot, planter,+grass skirt, or display plate unless the request explicitly includes it. Add semantic roles for the+trunk/stem/root support, canopy or foliage clusters, and one vegetation.contact.ground marker at+asset-local Y=0. Prefer a nonrendering local frame on the support mesh, for example+\`semantic: { roles: ['vegetation.trunk', 'vegetation.contact.ground'], frames:+[{ id: 'ground-contact', translation: [0, -trunkHeight / 2, 0], rotation: [0, 0, 0, 1] }] }\`.+Seat visible support material on that plane without floating or burying it.++Use the current general primitives for branches, canopy masses/cards, and fronds. Keep every branch+or frond base embedded into its parent, decrease branch radii toward tips, and verify foliage from+front, right, top, and three-quarter views. Deliberately bare/dead growth has no missing-foliage+requirement. In portable PBR/textured modes, use two to six restrained foliage value roles (for+example cooler inner leaves and slightly lighter outer leaves); in flatOptimized mode, keep one+coherent foliage role so material consolidation remains intentional.`;+/** VFX build context — emitter-like parts driven by transform on Joint_ pivots. */export const VFX_CONTEXT ='This is a VFX / effect asset. Build the moving or emitting elements — pulses, rings, sparks, swirls, ' +@@ -876,6 +968,7 @@ export const CATEGORY_CONTEXT: Partial<Record<AssetCategory, string>> = {architecture: ARCHITECTURE_CONTEXT,prop: PROP_CONTEXT,environment: ENVIRONMENT_CONTEXT,+ vegetation: VEGETATION_CONTEXT,vfx: VFX_CONTEXT,};@@ -925,6 +1018,56 @@ export function buildUserPrompt(request: KilnGenerateRequest): string {// so every consumer — including the deployed runtime — gets it once.const categoryContext = CATEGORY_CONTEXT[request.category];if (categoryContext) parts.push(`\n${categoryContext}`);+ if (request.intent) {+ parts.push(+ `\n## Resolved Asset Scope\n${renderAssetScopePrompt(request.intent.scope, request.intent.modular)}`,+ );+ const semanticGuidance = buildPropEnvironmentSemanticGuidance(request.intent);+ if (semanticGuidance) parts.push(`\n${semanticGuidance}`);+ }+ if (request.category === 'character' && request.intent?.character) {+ const character = request.intent.character;+ const clips = character.clips.length+ ? character.clips.map((clip) => `${clip.name}:${clip.playback}`).join(', ')+ : 'none requested';+ parts.push(+ `\n## Resolved Character Contract\n${characterBodyPlanRecipe(character.bodyPlan)}\n` ++ `Grounded: ${character.grounded}; locomotion: ${character.locomotion}; gait: ${character.gait}; ` ++ `root motion: ${character.rootMotion}; clips: ${clips}; held item: ` ++ `${character.heldItem.required ? `required at ${character.heldItem.attachmentRole}` : 'none'}.`,+ );+ }+ if (request.category === 'vehicle' && request.intent?.vehicle) {+ const vehicle = request.intent.vehicle;+ parts.push(+ `\n## Resolved Vehicle Contract\n${vehicleSubtypeRecipe(vehicle)}\n` ++ `Wheel assemblies: ${vehicle.wheelCount}; axles: ${vehicle.axleCount}; steering: ` ++ `${vehicle.steering}; animation assemblies: ` ++ `${vehicle.animationAssemblies.join(', ') || 'none requested'}.`,+ );+ }+ if (request.category === 'vegetation' && request.intent?.vegetation) {+ const vegetation = request.intent.vegetation;+ const materialGuidance =+ request.intent.material.mode === 'flatOptimized'+ ? 'Use one coherent foliage value role.'+ : 'Use two to six restrained foliage value roles and evaluate material coherence separately from structure.';+ parts.push(+ `\n## Resolved Vegetation Contract\nGrowth form: ${vegetation.subtype}; state: ` ++ `${vegetation.growthState}; canopy profile: ${vegetation.canopyProfile}; standalone: ` ++ `${vegetation.standalone}; grounded: ${vegetation.grounded}. ${materialGuidance}`,+ );+ parts.push(vegetationSubtypePromptContext(request.intent));+ }+ if (request.category === 'vfx' && request.intent?.vfx) {+ parts.push(`\n## Resolved VFX Contract\n${renderVfxBreadthPrompt(request.intent.vfx)}`);+ }+ if (+ request.intent?.material.mode === 'pbrRecipe' ||+ request.intent?.material.mode === 'texturedHero'+ ) {+ parts.push(`\n${MATERIAL_RECIPE_PROMPT_CONTEXT_V1}`);+ }}// Animation instructions — only for fresh generation. When editing existing codediff --git a/src/qa/architecture-corpus.ts b/src/qa/architecture-corpus.tsnew file mode 100644index 00000000..329fbcb3--- /dev/null+++ b/src/qa/architecture-corpus.ts@@ -0,0 +1,600 @@+import * as THREE from 'three';++import {+ createAssetIntentV1,+ stampSemanticMetadataV1,+ type AssetIntentV1,+ type ArchitectureIntentV1Input,+} from '../contracts';++export type ArchitectureCorpusKind = 'failure' | 'control' | 'false-positive';++export interface ArchitectureCorpusPayload {+ intent: AssetIntentV1;+ scene: THREE.Object3D;+}++export interface ArchitectureCorpusDescriptor {+ id: string;+ kind: ArchitectureCorpusKind;+ description: string;+ pairId?: string;+ expectedPrimaryCode?: string;+ forbiddenCodes: readonly string[];+ build: () => ArchitectureCorpusPayload;+}++export interface ArchitectureCorpusFixtureOptions {+ ridgeAxis?: 'x' | 'z';+ panelAxis?: 'correct' | 'rotated-90' | 'none';+ sameFacing?: boolean;+ gables?: 'complete' | 'missing' | 'sparse';+ ridgeGap?: number;+ envelopeGap?: number;+ sealedPortal?: boolean;+ sealedBox?: boolean;+ overhang?: number;+ pavilion?: boolean;+ stylized?: boolean;+}++const CANONICAL_ARCHITECTURE_CODES = Object.freeze([+ 'ARCH_ROOF_AXIS',+ 'ARCH_OPEN_GABLE',+ 'ARCH_RIDGE_GAP',+ 'ARCH_ENVELOPE_GAP',+ 'ARCH_BLOCKED_PORTAL',+]);++function semantic<T extends THREE.Object3D>(node: T, role: string): T {+ return stampSemanticMetadataV1(node, { roles: [role] });+}++function part(+ root: THREE.Object3D,+ name: string,+ geometry: THREE.BufferGeometry,+ material: THREE.Material,+ role: string,+ position: [number, number, number],+ rotation: [number, number, number] = [0, 0, 0],+): THREE.Mesh {+ const mesh = semantic(new THREE.Mesh(geometry, material), role);+ mesh.name = name;+ mesh.position.set(...position);+ mesh.rotation.set(...rotation);+ root.add(mesh);+ return mesh;+}++function gableGeometry(span: number, rise: number): THREE.BufferGeometry {+ const geometry = new THREE.BufferGeometry();+ geometry.setAttribute(+ 'position',+ new THREE.Float32BufferAttribute([0, 0, -span / 2, 0, 0, span / 2, 0, rise, 0], 3),+ );+ geometry.setIndex([0, 1, 2]);+ geometry.computeVertexNormals();+ return geometry;+}++export function buildArchitectureCorpusFixture(+ options: ArchitectureCorpusFixtureOptions = {},+): ArchitectureCorpusPayload {+ const stylized = options.stylized === true;+ const pavilion = options.pavilion === true;+ const ridgeAxis = options.ridgeAxis ?? 'x';+ const spanX = stylized ? 0.8 : 6;+ const spanZ = stylized ? 0.7 : 4;+ const wallHeight = stylized ? 0.8 : 3;+ const rise = stylized ? 0.35 : 1.5;+ const overhang = options.overhang ?? (stylized ? 0.08 : 0.3);+ const portal = stylized+ ? { width: 0.25, height: 0.5, depth: 0.06 }+ : { width: 1.1, height: 2.1, depth: 0.15 };+ const halfRun = (ridgeAxis === 'x' ? spanZ : spanX) / 2;+ const pitch = Math.atan2(rise, halfRun);+ const architecture: ArchitectureIntentV1Input = {+ subtype: pavilion ? 'open pavilion' : 'gable building',+ enterable: !pavilion && !stylized,+ footprint: { spanX, spanZ, units: 'm' },+ wallHeight,+ scaleMode: stylized ? 'stylized' : 'realistic',+ roof: {+ type: 'gable',+ ridgeAxis,+ rise,+ pitchDegrees: THREE.MathUtils.radToDeg(pitch),+ overhang,+ closedEnds: !pavilion,+ },+ ...(!pavilion && !stylized ? { portal } : {}),+ };+ const intent = createAssetIntentV1({ category: 'architecture', architecture });+ const root = semantic(new THREE.Group(), 'architecture.shell.gable');+ root.name = `ArchitectureCorpus_${ridgeAxis}`;+ const wallMaterial = new THREE.MeshStandardMaterial({ color: 0xc8ad82 });+ const roofMaterial = new THREE.MeshStandardMaterial({ color: 0x59616d });+ const markerMaterial = new THREE.MeshStandardMaterial({ color: 0x39424d });+ const thickness = stylized ? 0.03 : 0.15;+ const roofThickness = stylized ? 0.02 : 0.06;++ if (!pavilion) {+ part(+ root,+ 'Floor',+ new THREE.BoxGeometry(spanX, stylized ? 0.03 : 0.08, spanZ),+ wallMaterial,+ 'floor',+ [0, stylized ? 0.015 : 0.04, 0],+ );++ const addFullWall = (+ name: string,+ role: string,+ size: [number, number, number],+ position: [number, number, number],+ ): void => {+ part(root, name, new THREE.BoxGeometry(...size), wallMaterial, role, position);+ };+ addFullWall(+ 'WallBack',+ 'wall.back',+ [thickness, wallHeight, spanZ],+ [-spanX / 2, wallHeight / 2, 0],+ );+ addFullWall(+ 'WallLeft',+ 'wall.left',+ [spanX, wallHeight, thickness],+ [0, wallHeight / 2, -spanZ / 2],+ );+ addFullWall(+ 'WallRight',+ 'wall.right',+ [spanX, wallHeight, thickness],+ [0, wallHeight / 2, spanZ / 2],+ );++ if (!stylized && options.sealedBox) {+ addFullWall(+ 'WallFrontSolid',+ 'wall.front',+ [thickness, wallHeight, spanZ],+ [spanX / 2, wallHeight / 2, 0],+ );+ } else if (!stylized) {+ const sideWidth = (spanZ - portal.width) / 2;+ const sideOffset = portal.width / 2 + sideWidth / 2;+ addFullWall(+ 'WallFrontLeft',+ 'wall.front',+ [thickness, wallHeight, sideWidth],+ [spanX / 2, wallHeight / 2, -sideOffset],+ );+ addFullWall(+ 'WallFrontRight',+ 'wall.front',+ [thickness, wallHeight, sideWidth],+ [spanX / 2, wallHeight / 2, sideOffset],+ );+ const lintelHeight = wallHeight - portal.height;+ addFullWall(+ 'WallFrontLintel',+ 'wall.front',+ [thickness, lintelHeight, portal.width],+ [spanX / 2, portal.height + lintelHeight / 2, 0],+ );+ const opening = semantic(new THREE.Object3D(), 'opening.front.door');+ opening.name = 'Opening_front_door';+ opening.position.set(spanX / 2, portal.height / 2, 0);+ opening.scale.set(portal.depth, portal.height, portal.width);+ root.add(opening);+ if (options.sealedPortal) {+ part(+ root,+ 'PaintedDoorOnSolidOpening',+ new THREE.BoxGeometry(portal.depth, portal.height, portal.width),+ markerMaterial,+ 'door.painted',+ [spanX / 2, portal.height / 2, 0],+ );+ }+ } else {+ addFullWall(+ 'WallFront',+ 'wall.front',+ [thickness, wallHeight, spanZ],+ [spanX / 2, wallHeight / 2, 0],+ );+ }+ }++ const ridgeSpan = (ridgeAxis === 'x' ? spanX : spanZ) + overhang * 2;+ const totalRun = halfRun + overhang;+ const totalDrop = Math.tan(pitch) * totalRun;+ const slopeLength = totalRun / Math.cos(pitch);+ const centerY = wallHeight + rise - totalDrop / 2 + (options.envelopeGap ?? 0);+ const positiveLateral = totalRun / 2 + (options.ridgeGap ?? 0);+ const negativeLateral = -totalRun / 2 - (options.ridgeGap ?? 0);+ const slopeGeometry =+ ridgeAxis === 'x'+ ? new THREE.BoxGeometry(ridgeSpan, roofThickness, slopeLength)+ : new THREE.BoxGeometry(slopeLength, roofThickness, ridgeSpan);+ const positivePosition: [number, number, number] =+ ridgeAxis === 'x' ? [0, centerY, positiveLateral] : [positiveLateral, centerY, 0];+ const negativePosition: [number, number, number] =+ ridgeAxis === 'x' ? [0, centerY, negativeLateral] : [negativeLateral, centerY, 0];+ const positiveRotation: [number, number, number] =+ ridgeAxis === 'x' ? [pitch, 0, 0] : [0, 0, -pitch];+ const negativeRotation: [number, number, number] = options.sameFacing+ ? positiveRotation+ : ridgeAxis === 'x'+ ? [-pitch, 0, 0]+ : [0, 0, pitch];+ part(+ root,+ 'SlopePositive',+ slopeGeometry,+ roofMaterial,+ 'roof.slope.positive',+ positivePosition,+ positiveRotation,+ );+ part(+ root,+ 'SlopeNegative',+ slopeGeometry.clone(),+ roofMaterial,+ 'roof.slope.negative',+ negativePosition,+ negativeRotation,+ );++ if (!pavilion && options.gables !== 'missing') {+ const scale = options.gables === 'sparse' ? 0.3 : 1;+ const lateralSpan = (ridgeAxis === 'x' ? spanZ : spanX) * scale;+ const gableRise = rise * scale;+ const gable = gableGeometry(lateralSpan, gableRise);+ const positiveEnd: [number, number, number] =+ ridgeAxis === 'x' ? [spanX / 2, wallHeight, 0] : [0, wallHeight, spanZ / 2];+ const negativeEnd: [number, number, number] =+ ridgeAxis === 'x' ? [-spanX / 2, wallHeight, 0] : [0, wallHeight, -spanZ / 2];+ const gableRotation: [number, number, number] =+ ridgeAxis === 'x' ? [0, 0, 0] : [0, Math.PI / 2, 0];+ part(+ root,+ 'GablePositive',+ gable,+ wallMaterial,+ 'roof.gable.positive',+ positiveEnd,+ gableRotation,+ );+ part(+ root,+ 'GableNegative',+ gable.clone(),+ wallMaterial,+ 'roof.gable.negative',+ negativeEnd,+ gableRotation,+ );+ }++ if (options.panelAxis && options.panelAxis !== 'none') {+ const correct = options.panelAxis === 'correct';+ const panelRidge = correct ? Math.min(0.7, ridgeSpan * 0.2) : slopeLength * 0.75;+ const panelDownhill = correct ? slopeLength * 0.75 : Math.min(0.7, slopeLength * 0.25);+ const panelGeometry =+ ridgeAxis === 'x'+ ? new THREE.BoxGeometry(panelRidge, roofThickness / 2, panelDownhill)+ : new THREE.BoxGeometry(panelDownhill, roofThickness / 2, panelRidge);+ part(+ root,+ 'RoofPanelPositive',+ panelGeometry,+ roofMaterial,+ 'roof.panel.positive',+ positivePosition,+ positiveRotation,+ );+ part(+ root,+ 'RoofPanelNegative',+ panelGeometry.clone(),+ roofMaterial,+ 'roof.panel.negative',+ negativePosition,+ negativeRotation,+ );+ }++ root.updateMatrixWorld(true);+ return { intent, scene: root };+}++function buildNonGableControl(+ subtype: 'bridge' | 'shed' | 'hip-roof building',+ roofType: 'none' | 'shed' | 'hip',+): ArchitectureCorpusPayload {+ const spanX = subtype === 'bridge' ? 12 : 6;+ const spanZ = subtype === 'bridge' ? 3 : 5;+ const wallHeight = subtype === 'bridge' ? 1.2 : 3;+ const intent = createAssetIntentV1({+ category: 'architecture',+ architecture: {+ subtype,+ enterable: false,+ footprint: { spanX, spanZ, units: 'm' },+ wallHeight,+ roof: { type: roofType, closedEnds: false },+ },+ });+ const root = semantic(new THREE.Group(), `architecture.${subtype.replaceAll(' ', '-')}`);+ root.name = `ArchitectureControl_${roofType}`;+ const wall = new THREE.MeshStandardMaterial({ color: 0xa58e71 });+ const roof = new THREE.MeshStandardMaterial({ color: 0x4f5965 });+ part(+ root,+ subtype === 'bridge' ? 'BridgeDeck' : 'Floor',+ new THREE.BoxGeometry(spanX, 0.12, spanZ),+ wall,+ subtype === 'bridge' ? 'bridge.deck' : 'floor',+ [0, 0.06, 0],+ );+ if (subtype === 'bridge') {+ for (const side of [-1, 1] as const) {+ part(+ root,+ `BridgeRail_${side}`,+ new THREE.BoxGeometry(spanX, 1, 0.08),+ wall,+ 'bridge.railing',+ [0, 0.55, side * (spanZ / 2)],+ );+ }+ } else {+ part(root, 'WallFront', new THREE.BoxGeometry(0.15, wallHeight, spanZ), wall, 'wall.front', [+ spanX / 2,+ wallHeight / 2,+ 0,+ ]);+ part(root, 'WallBack', new THREE.BoxGeometry(0.15, wallHeight, spanZ), wall, 'wall.back', [+ -spanX / 2,+ wallHeight / 2,+ 0,+ ]);+ if (roofType === 'shed') {+ part(+ root,+ 'ShedRoofSurface',+ new THREE.BoxGeometry(spanX + 0.6, 0.08, spanZ + 0.6),+ roof,+ 'roof.shed.surface',+ [0, wallHeight + 0.45, 0],+ [0.12, 0, 0],+ );+ } else {+ for (const side of ['front', 'back', 'left', 'right'] as const) {+ part(+ root,+ `HipRoof_${side}`,+ new THREE.BoxGeometry(spanX * 0.55, 0.08, spanZ * 0.55),+ roof,+ `roof.hip.${side}`,+ [0, wallHeight + 0.65, 0],+ [+ side === 'front' ? 0.18 : side === 'back' ? -0.18 : 0,+ 0,+ side === 'left' ? 0.18 : side === 'right' ? -0.18 : 0,+ ],+ );+ }+ }+ }+ root.updateMatrixWorld(true);+ return { intent, scene: root };+}++function buildPorchIntersectionControl(): ArchitectureCorpusPayload {+ const payload = buildArchitectureCorpusFixture();+ const porchMaterial = new THREE.MeshStandardMaterial({ color: 0x59616d });+ part(+ payload.scene,+ 'PorchRoofIntersection',+ new THREE.BoxGeometry(2.4, 0.08, 1.5),+ porchMaterial,+ 'roof.porch.intersection',+ [2.8, 2.45, 1.8],+ [0.08, 0, -0.12],+ );+ payload.scene.updateMatrixWorld(true);+ return payload;+}++const failure = (+ id: string,+ pairId: string,+ description: string,+ code: string,+ options: ArchitectureCorpusFixtureOptions,+): ArchitectureCorpusDescriptor => ({+ id,+ kind: 'failure',+ pairId,+ description,+ expectedPrimaryCode: code,+ forbiddenCodes: [],+ build: () => buildArchitectureCorpusFixture(options),+});++const control = (+ id: string,+ pairId: string,+ description: string,+ options: ArchitectureCorpusFixtureOptions = {},+): ArchitectureCorpusDescriptor => ({+ id,+ kind: 'control',+ pairId,+ description,+ forbiddenCodes: CANONICAL_ARCHITECTURE_CODES,+ build: () => buildArchitectureCorpusFixture(options),+});++export const ARCHITECTURE_REGRESSION_CORPUS = Object.freeze([+ failure(+ 'roof-panels-rotated-90',+ 'roof-panels-axis-control',+ 'Individual roof panels run along the ridge instead of ridge-to-eave.',+ 'ARCH_ROOF_AXIS',+ { panelAxis: 'rotated-90' },+ ),+ control(+ 'roof-panels-axis-control',+ 'roof-panels-rotated-90',+ 'Equivalent panels run in the declared roof-local downhill direction.',+ { panelAxis: 'correct' },+ ),+ failure(+ 'same-facing-slopes',+ 'opposing-slopes-control',+ 'Both slopes use the same downhill frame instead of mirroring.',+ 'ARCH_ROOF_AXIS',+ { sameFacing: true },+ ),+ control(+ 'opposing-slopes-control',+ 'same-facing-slopes',+ 'The two slope normals have opposite lateral components.',+ ),+ failure(+ 'missing-gables',+ 'complete-gables-control',+ 'closedEnds=true has neither semantic gable closure.',+ 'ARCH_OPEN_GABLE',+ { gables: 'missing' },+ ),+ control(+ 'complete-gables-control',+ 'missing-gables',+ 'Both gable boundaries cover the full wall-top-to-ridge cross-section.',+ ),+ failure(+ 'sparse-gables',+ 'dense-gables-control',+ 'Tagged end panels cover only a small central triangle.',+ 'ARCH_OPEN_GABLE',+ { gables: 'sparse' },+ ),+ control(+ 'dense-gables-control',+ 'sparse-gables',+ 'Equivalent tagged end panels cover the requested boundaries.',+ ),+ failure(+ 'ridge-gap',+ 'ridge-contact-control',+ 'Both slope high edges are displaced away from the ridge.',+ 'ARCH_RIDGE_GAP',+ { ridgeGap: 0.14 },+ ),+ control(+ 'ridge-contact-control',+ 'ridge-gap',+ 'Equivalent slope high edges share the ridge within tolerance.',+ ),+ failure(+ 'wall-roof-gap',+ 'wall-roof-contact-control',+ 'The complete roof is lifted above the wall bearing line.',+ 'ARCH_ENVELOPE_GAP',+ { envelopeGap: 0.18 },+ ),+ control(+ 'wall-roof-contact-control',+ 'wall-roof-gap',+ 'Equivalent wall-top samples meet the roof underside.',+ ),+ failure(+ 'sealed-doorway',+ 'clear-portal-control',+ 'A painted door mesh occupies the requested portal clearance.',+ 'ARCH_BLOCKED_PORTAL',+ { sealedPortal: true },+ ),+ control(+ 'clear-portal-control',+ 'sealed-doorway',+ 'The semantic clearance prism connects exterior to interior.',+ ),+ failure(+ 'sealed-enterable-box',+ 'clear-box-portal-control',+ 'An enterable sealed box has no semantic or geometric portal.',+ 'ARCH_BLOCKED_PORTAL',+ { sealedBox: true },+ ),+ control(+ 'clear-box-portal-control',+ 'sealed-enterable-box',+ 'Equivalent architecture has a real exterior-to-interior clearance prism.',+ ),+ {+ id: 'valid-large-overhang',+ kind: 'false-positive',+ description: 'A large overhang still meets the wall at the bearing line.',+ forbiddenCodes: CANONICAL_ARCHITECTURE_CODES,+ build: () => buildArchitectureCorpusFixture({ overhang: 0.9 }),+ },+ {+ id: 'intentional-open-pavilion',+ kind: 'false-positive',+ description: 'An explicit open pavilion has no walls or closed end requirement.',+ forbiddenCodes: ['ARCH_OPEN_GABLE', 'ARCH_ENVELOPE_GAP', 'ARCH_BLOCKED_PORTAL'],+ build: () => buildArchitectureCorpusFixture({ pavilion: true }),+ },+ {+ id: 'explicit-stylized-scale',+ kind: 'false-positive',+ description: 'Explicit stylized scale suppresses realistic dimension-band observations.',+ forbiddenCodes: [+ 'ARCH_SCALE_CEILING_HEIGHT',+ 'ARCH_SCALE_FOOTPRINT_X',+ 'ARCH_SCALE_FOOTPRINT_Z',+ 'ARCH_SCALE_DOOR_WIDTH',+ 'ARCH_SCALE_DOOR_HEIGHT',+ 'ARCH_SCALE_WALL_THICKNESS',+ ],+ build: () => buildArchitectureCorpusFixture({ stylized: true }),+ },+ {+ id: 'roofless-bridge-control',+ kind: 'false-positive',+ description: 'A roofless bridge has no gable, ridge, closure, or portal contract to enforce.',+ forbiddenCodes: CANONICAL_ARCHITECTURE_CODES,+ build: () => buildNonGableControl('bridge', 'none'),+ },+ {+ id: 'shed-roof-control',+ kind: 'false-positive',+ description: 'A declared shed roof is not misclassified as an incomplete gable.',+ forbiddenCodes: CANONICAL_ARCHITECTURE_CODES,+ build: () => buildNonGableControl('shed', 'shed'),+ },+ {+ id: 'hip-roof-control',+ kind: 'false-positive',+ description: 'A declared hip roof is not misclassified as an incomplete gable.',+ forbiddenCodes: CANONICAL_ARCHITECTURE_CODES,+ build: () => buildNonGableControl('hip-roof building', 'hip'),+ },+ {+ id: 'porch-roof-intersection-control',+ kind: 'false-positive',+ description: 'A correctly intersecting porch roof does not invalidate the complete main gable.',+ forbiddenCodes: CANONICAL_ARCHITECTURE_CODES,+ build: buildPorchIntersectionControl,+ },+] satisfies readonly ArchitectureCorpusDescriptor[]);diff --git a/src/qa/architecture-repairs.ts b/src/qa/architecture-repairs.tsnew file mode 100644index 00000000..0d4d0083--- /dev/null+++ b/src/qa/architecture-repairs.ts@@ -0,0 +1,92 @@+import type { QaFinding } from './types';++export const ARCHITECTURE_REPAIR_CODES = [+ 'ARCH_ROOF_AXIS',+ 'ARCH_OPEN_GABLE',+ 'ARCH_RIDGE_GAP',+ 'ARCH_ENVELOPE_GAP',+ 'ARCH_BLOCKED_PORTAL',+] as const;++export type ArchitectureRepairCode = (typeof ARCHITECTURE_REPAIR_CODES)[number];++export interface ArchitectureRepairRecipe {+ code: ArchitectureRepairCode;+ repairText: string;+ viewHints: readonly string[];+}++/**+ * Stable, localized repair recipes shared by category QA and the bounded repair+ * loop. Each recipe names the semantic surface to edit and the diagnostic view+ * that proves the edit, rather than asking the model to broadly "fix the asset".+ */+export const ARCHITECTURE_REPAIR_RECIPES: Readonly<+ Record<ArchitectureRepairCode, ArchitectureRepairRecipe>+> = Object.freeze({+ ARCH_ROOF_AXIS: Object.freeze({+ code: 'ARCH_ROOF_AXIS',+ repairText:+ 'Edit only the reported roof slope or panel: keep the declared ridge axis fixed, mirror the two slope frames, and rotate panel span 90 degrees in roof-local space so it runs ridge-to-eave. Recheck both gable elevations and the top wireframe.',+ viewHints: Object.freeze([+ 'architecture.gable.positive',+ 'architecture.gable.negative',+ 'generic.top.wireframe',+ ]),+ }),+ ARCH_OPEN_GABLE: Object.freeze({+ code: 'ARCH_OPEN_GABLE',+ repairText:+ 'Add or complete only the reported roof.gable end panel. Its projected triangle must cover the full wall-top-to-ridge cross-section and meet both slopes; preserve intentional openings and the opposite end.',+ viewHints: Object.freeze([+ 'architecture.gable.positive',+ 'architecture.gable.negative',+ 'generic.front.semantic-overlay',+ ]),+ }),+ ARCH_RIDGE_GAP: Object.freeze({+ code: 'ARCH_RIDGE_GAP',+ repairText:+ 'Move only the reported slope high edge in its roof-local downhill direction until both high edges share the declared ridge line within tolerance. Do not change footprint, pitch, eaves, or overhang.',+ viewHints: Object.freeze([+ 'architecture.gable.positive',+ 'architecture.gable.negative',+ 'generic.top.depth-contact',+ ]),+ }),+ ARCH_ENVELOPE_GAP: Object.freeze({+ code: 'ARCH_ENVELOPE_GAP',+ repairText:+ 'At the reported wall-boundary samples, align the roof underside to the wall top plate within tolerance. Preserve the declared exterior overhang and do not close sides marked as an open pavilion.',+ viewHints: Object.freeze([+ 'architecture.cutaway.dollhouse',+ 'generic.front.depth-contact',+ 'generic.right.depth-contact',+ ]),+ }),+ ARCH_BLOCKED_PORTAL: Object.freeze({+ code: 'ARCH_BLOCKED_PORTAL',+ repairText:+ 'Remove or split only the reported blocker inside the opening clearance prism so the tagged exterior portal connects to the interior at the requested width, height, and depth. A painted door on a solid wall is not an opening.',+ viewHints: Object.freeze([+ 'architecture.portal.eye',+ 'architecture.cutaway.plan',+ 'generic.front.depth-contact',+ ]),+ }),+});++export function architectureRepairRecipe(code: string): ArchitectureRepairRecipe | undefined {+ return (ARCHITECTURE_REPAIR_RECIPES as Readonly<Record<string, ArchitectureRepairRecipe>>)[code];+}++/** Apply the canonical recipe without discarding finding-specific localization. */+export function withArchitectureRepair(finding: QaFinding): QaFinding {+ const recipe = architectureRepairRecipe(finding.code);+ if (!recipe) return finding;+ return {+ ...finding,+ repairText: finding.repairText ?? recipe.repairText,+ viewHints: [...new Set([...(finding.viewHints ?? []), ...recipe.viewHints])],+ };+}diff --git a/src/qa/architecture.test.ts b/src/qa/architecture.test.tsnew file mode 100644index 00000000..c3007f06--- /dev/null+++ b/src/qa/architecture.test.ts@@ -0,0 +1,350 @@+import { describe, expect, test } from 'bun:test';+import { WebIO, type Node as GltfNode } from '@gltf-transform/core';+import * as THREE from 'three';++import { createGableShell, createRoofSurfaceLayout } from '../architecture';+import {+ createAssetIntentV1,+ readSemanticMetadataV1FromExtras,+ stampSemanticMetadataV1,+} from '../contracts';+import { renderSceneToGLB } from '../render';+import { hideArchitectureRoofInScene } from '../views/architecture';+import {+ ARCHITECTURE_REGRESSION_CORPUS,+ buildArchitectureCorpusFixture,+} from './architecture-corpus';+import {+ ARCHITECTURE_REPAIR_CODES,+ architectureRepairRecipe,+ withArchitectureRepair,+} from './architecture-repairs';+import { ARCHITECTURE_REALISTIC_SCALE_BANDS, evaluateArchitectureQa } from './architecture';+import { DETERMINISTIC_QA_REGISTRY, runDeterministicSceneQa } from './run';++const canonicalCodes = new Set([+ 'ARCH_ROOF_AXIS',+ 'ARCH_OPEN_GABLE',+ 'ARCH_RIDGE_GAP',+ 'ARCH_ENVELOPE_GAP',+ 'ARCH_BLOCKED_PORTAL',+]);++function canonicalHelperShell(ridgeAxis: 'x' | 'z' = 'x') {+ const wall = new THREE.MeshStandardMaterial({ color: 0xc8ad82 });+ const roof = new THREE.MeshStandardMaterial({ color: 0x59616d });+ const shell = createGableShell(+ `Canonical_${ridgeAxis}`,+ { wall, roof },+ {+ spanX: 6,+ spanZ: 4,+ wallHeight: 3,+ wallThickness: 0.15,+ rise: ridgeAxis === 'x' ? 1.5 : 2.25,+ ridgeAxis,+ overhang: 0.3,+ enterable: true,+ closedEnds: true,+ },+ );+ for (const face of shell.roof.faces) {+ createRoofSurfaceLayout(`Panels_${face.side}`, roof, {+ face,+ kind: 'panels',+ panelWidth: 0.9,+ });+ }+ const halfRun = (ridgeAxis === 'x' ? 4 : 6) / 2;+ const rise = ridgeAxis === 'x' ? 1.5 : 2.25;+ const intent = createAssetIntentV1({+ category: 'architecture',+ architecture: {+ subtype: 'gable building',+ enterable: true,+ footprint: { spanX: 6, spanZ: 4 },+ wallHeight: 3,+ roof: {+ type: 'gable',+ ridgeAxis,+ rise,+ pitchDegrees: THREE.MathUtils.radToDeg(Math.atan2(rise, halfRun)),+ overhang: 0.3,+ closedEnds: true,+ },+ portal: { width: 1.1, height: 2.1, depth: 0.15 },+ },+ });+ return { shell, intent };+}++describe('ARCH-019 executable reciprocal architecture corpus', () => {+ for (const descriptor of ARCHITECTURE_REGRESSION_CORPUS) {+ test(`${descriptor.kind}: ${descriptor.id}`, () => {+ const payload = descriptor.build();+ const findings = evaluateArchitectureQa({+ intent: payload.intent,+ scene: payload.scene,+ });+ const codes = findings.map((finding) => finding.code);+ if (descriptor.expectedPrimaryCode) {+ const primary = findings.find((finding) => canonicalCodes.has(finding.code));+ expect(primary?.code).toBe(descriptor.expectedPrimaryCode);+ expect(primary?.affected?.node).toBeTruthy();+ expect(primary?.measurement).toBeTruthy();+ expect(primary?.viewHints?.length).toBeGreaterThan(0);+ expect(primary?.repairText).toBeTruthy();+ }+ for (const forbidden of descriptor.forbiddenCodes) expect(codes).not.toContain(forbidden);+ });+ }++ test('covers every observed architecture failure with a reciprocal control', () => {+ const byId = new Map(ARCHITECTURE_REGRESSION_CORPUS.map((fixture) => [fixture.id, fixture]));+ for (const fixture of ARCHITECTURE_REGRESSION_CORPUS) {+ if (fixture.kind !== 'failure') continue;+ const pair = byId.get(fixture.pairId!);+ expect(pair?.kind).toBe('control');+ expect(pair?.pairId).toBe(fixture.id);+ }+ });+});++describe('ARCH-010–016 validator policy', () => {+ test('the canonical shell and roof-local panels pass exact QA for both ridge axes', () => {+ for (const ridgeAxis of ['x', 'z'] as const) {+ const { shell, intent } = canonicalHelperShell(ridgeAxis);+ shell.root.position.set(3, 1, -2);+ shell.root.rotation.set(0.08, 0.55, -0.04);+ shell.root.updateMatrixWorld(true);+ const findings = evaluateArchitectureQa({ intent, scene: shell.root });+ expect(findings.filter((finding) => canonicalCodes.has(finding.code))).toEqual([]);+ expect(findings.filter((finding) => finding.code.startsWith('ARCH_SCALE_'))).toEqual([]);+ }+ });++ test('final export preserves helper portal/roof semantics and safely degrades full optimize', async () => {+ const { shell, intent } = canonicalHelperShell('x');+ const rendered = await renderSceneToGLB(shell.root, { intent, optimize: 'full' });+ expect(rendered.optimize?.mode).toBe('palette');+ expect(rendered.qaReport.disposition).toBe('pass');+ const document = await new WebIO().readBinary(rendered.bytes);+ const opening = document+ .getRoot()+ .listNodes()+ .find((node) => node.getName().startsWith('Opening_front_'));+ expect(readSemanticMetadataV1FromExtras(opening!.getExtras())?.roles).toContain(+ 'opening.front.door',+ );+ expect(opening?.getScale()).toEqual([0.15, 2.1, 1.1]);+ const roofRoles = document+ .getRoot()+ .listNodes()+ .flatMap((node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [])+ .filter((role) => role.startsWith('roof.'));+ expect(roofRoles).toEqual(+ expect.arrayContaining([+ 'roof.assembly',+ 'roof.slope.positive',+ 'roof.slope.negative',+ 'roof.gable.positive',+ 'roof.gable.negative',+ ]),+ );++ const adapt = (node: GltfNode): Record<string, unknown> => ({+ name: node.getName(),+ visible: true,+ userData: node.getExtras(),+ children: node.listChildren().map(adapt),+ });+ const reloaded = {+ name: 'ReloadedShell',+ visible: true,+ userData: {},+ children: document.getRoot().listScenes()[0]!.listChildren().map(adapt),+ };+ const selection = hideArchitectureRoofInScene(reloaded);+ expect(selection.mode).toBe('semantic');+ expect(selection.nodes.map((node) => node.name).sort()).toEqual(['Roof']);+ expect(+ (selection.nodes[0]!.children ?? [])+ .map((node) => node.name)+ .filter((name): name is string => typeof name === 'string' && name.includes('_Gable_'))+ .sort(),+ ).toEqual(['Mesh_Canonical_x_Gable_negative', 'Mesh_Canonical_x_Gable_positive']);+ for (const selected of selection.nodes) {+ const roles = readSemanticMetadataV1FromExtras(selected.userData ?? {})?.roles ?? [];+ expect(roles.some((role) => role.startsWith('roof.'))).toBe(true);+ }+ const wallNode = document+ .getRoot()+ .listNodes()+ .find((node) =>+ readSemanticMetadataV1FromExtras(node.getExtras())?.roles.includes('wall.front'),+ );+ const adaptedWall = (reloaded.children as Array<Record<string, unknown>>)+ .flatMap(function flatten(node): Array<Record<string, unknown>> {+ return [+ node,+ ...((node.children as Array<Record<string, unknown>> | undefined)?.flatMap(flatten) ??+ []),+ ];+ })+ .find((node) => node.name === wallNode?.getName());+ expect(adaptedWall?.visible).toBe(true);+ });++ test('registry selects architecture rules and hard-gates a tagged exact defect', () => {+ const payload = buildArchitectureCorpusFixture({ panelAxis: 'rotated-90' });+ const context = { intent: payload.intent, scene: payload.scene };+ expect(DETERMINISTIC_QA_REGISTRY.list(context).map((rule) => rule.id)).toContain(+ 'ARCHITECTURE_PROFILE',+ );+ const report = runDeterministicSceneQa(context);+ expect(report.disposition).toBe('block');+ expect(report.dimensions.categoryReadiness.findings.map((finding) => finding.code)).toContain(+ 'ARCH_ROOF_AXIS',+ );+ });++ test('passes a ridge-Z nonsquare shell under translated and rotated root transforms', () => {+ const payload = buildArchitectureCorpusFixture({ ridgeAxis: 'z' });+ payload.scene.position.set(7, 2, -4);+ payload.scene.rotation.set(0.1, 0.7, -0.05);+ payload.scene.updateMatrixWorld(true);+ const findings = evaluateArchitectureQa({ intent: payload.intent, scene: payload.scene });+ expect(findings.filter((finding) => canonicalCodes.has(finding.code))).toEqual([]);+ });++ test('rejects complete-looking gables that do not occupy the claimed end boundaries', () => {+ const { shell, intent } = canonicalHelperShell('x');+ expect(+ evaluateArchitectureQa({ intent, scene: shell.root }).map((finding) => finding.code),+ ).not.toContain('ARCH_OPEN_GABLE');+ shell.gables[0]!.position.x = 0;+ shell.gables[1]!.position.x = 0;+ shell.root.updateMatrixWorld(true);+ const findings = evaluateArchitectureQa({ intent, scene: shell.root });+ const misplaced = findings.filter((finding) => finding.code === 'ARCH_OPEN_GABLE');+ expect(misplaced).toHaveLength(2);+ expect(misplaced.every((finding) => finding.measurement?.name.endsWith('EndSeparation'))).toBe(+ true,+ );+ });++ test('rejects a clearance marker floating outside its claimed exterior wall', () => {+ const { shell, intent } = canonicalHelperShell('x');+ expect(+ evaluateArchitectureQa({ intent, scene: shell.root }).map((finding) => finding.code),+ ).not.toContain('ARCH_BLOCKED_PORTAL');+ shell.openings[0]!.position.x = 100;+ shell.root.updateMatrixWorld(true);+ const finding = evaluateArchitectureQa({ intent, scene: shell.root }).find(+ (candidate) => candidate.code === 'ARCH_BLOCKED_PORTAL',+ );+ expect(finding?.measurement).toMatchObject({+ name: 'portalClaimedWallCoverageRatio',+ actual: 0,+ threshold: 0.9,+ });+ });++ test('keeps untagged/inferred roof defects warn-only and asks for semantic roles', () => {+ const scene = new THREE.Group();+ scene.name = 'LegacyBuilding';+ const roof = new THREE.Mesh(new THREE.BoxGeometry(4, 0.1, 2), new THREE.MeshStandardMaterial());+ roof.name = 'Roof_Plane';+ scene.add(roof);+ const intent = createAssetIntentV1({+ category: 'architecture',+ architecture: { enterable: false, roof: { closedEnds: false } },+ });+ const findings = evaluateArchitectureQa({ intent, scene });+ expect(findings.some((finding) => finding.code === 'ARCH_MISSING_ROOF_ROLES')).toBe(true);+ expect(findings.every((finding) => finding.disposition !== 'block')).toBe(true);+ });++ test('explicit stylized scale suppresses every realistic scale-band warning', () => {+ const payload = buildArchitectureCorpusFixture({ stylized: true });+ const findings = evaluateArchitectureQa({ intent: payload.intent, scene: payload.scene });+ expect(findings.some((finding) => finding.code.startsWith('ARCH_SCALE_'))).toBe(false);+ });++ test('reports every realistic door, ceiling, stair, wall, and footprint band', () => {+ expect(Object.keys(ARCHITECTURE_REALISTIC_SCALE_BANDS).sort()).toEqual([+ 'ceilingHeight',+ 'doorHeight',+ 'doorWidth',+ 'footprint',+ 'stairRiser',+ 'stairTread',+ 'wallThickness',+ ]);+ const payload = buildArchitectureCorpusFixture();+ const opening = payload.scene.getObjectByName('Opening_front_door')!;+ opening.scale.set(0.15, 1, 0.4);+ const thinWall = payload.scene.getObjectByName('WallBack')!;+ thinWall.scale.x = 0.1;+ const stair = stampSemanticMetadataV1(+ new THREE.Mesh(new THREE.BoxGeometry(1, 0.5, 0.8), new THREE.MeshStandardMaterial()),+ { roles: ['stair.step.1'] },+ );+ stair.name = 'OversizeStairStep';+ payload.scene.add(stair);+ payload.scene.updateMatrixWorld(true);+ const tinyIntent = createAssetIntentV1({+ category: 'architecture',+ architecture: {+ enterable: false,+ footprint: { spanX: 1, spanZ: 1 },+ wallHeight: 1,+ roof: { rise: 0.3 },+ },+ });+ const codes = evaluateArchitectureQa({ intent: tinyIntent, scene: payload.scene }).map(+ (finding) => finding.code,+ );+ expect(codes).toEqual(+ expect.arrayContaining([+ 'ARCH_SCALE_DOOR_WIDTH',+ 'ARCH_SCALE_DOOR_HEIGHT',+ 'ARCH_SCALE_CEILING_HEIGHT',+ 'ARCH_SCALE_STAIR_RISER',+ 'ARCH_SCALE_STAIR_TREAD',+ 'ARCH_SCALE_WALL_THICKNESS',+ 'ARCH_SCALE_FOOTPRINT_X',+ 'ARCH_SCALE_FOOTPRINT_Z',+ ]),+ );+ });+});++describe('ARCH-018 evidence-bound repair recipes', () => {+ test('maps all five approved defect codes to localized repairs and views', () => {+ expect(ARCHITECTURE_REPAIR_CODES).toHaveLength(5);+ for (const code of ARCHITECTURE_REPAIR_CODES) {+ const recipe = architectureRepairRecipe(code);+ expect(recipe?.code).toBe(code);+ expect(recipe?.repairText.length).toBeGreaterThan(80);+ expect(recipe?.viewHints.length).toBeGreaterThan(1);+ }+ });++ test('preserves finding-specific localization when applying a recipe', () => {+ const finding = withArchitectureRepair({+ code: 'ARCH_RIDGE_GAP',+ disposition: 'block',+ dimension: 'categoryReadiness',+ profile: 'architecture.test',+ message: 'Localized ridge gap.',+ affected: { node: 'SlopeNegative' },+ measurement: { name: 'ridgeGap', actual: 0.2, threshold: 0.05, unit: 'm' },+ viewHints: ['custom.localized.view'],+ });+ expect(finding.affected?.node).toBe('SlopeNegative');+ expect(finding.measurement?.actual).toBe(0.2);+ expect(finding.viewHints).toContain('custom.localized.view');+ expect(finding.viewHints).toContain('architecture.gable.positive');+ });+});diff --git a/src/qa/architecture.ts b/src/qa/architecture.tsnew file mode 100644index 00000000..0d31dc8f--- /dev/null+++ b/src/qa/architecture.ts@@ -0,0 +1,1141 @@+import * as THREE from 'three';++import { readSemanticMetadataV1FromExtras, type ArchitectureIntentV1 } from '../contracts';+import { withArchitectureRepair } from './architecture-repairs';+import { conformancePromotionAuthorization, KILN_ENGINE_QA_OWNER, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';++type Axis = 'x' | 'y' | 'z';+type HorizontalAxis = 'x' | 'z';++interface Bounds3 {+ min: THREE.Vector3;+ max: THREE.Vector3;+}++interface ArchitectureTriangle {+ a: THREE.Vector3;+ b: THREE.Vector3;+ c: THREE.Vector3;+}++interface ArchitecturePart {+ node: THREE.Object3D;+ nodeName: string;+ nodePath: string;+ directRoles: readonly string[];+ roles: readonly string[];+ isMesh: boolean;+ bounds: Bounds3;+ vertices: readonly THREE.Vector3[];+ triangles: readonly ArchitectureTriangle[];+ /** Normal of the geometry's thinnest local axis, expressed asset-locally. */+ planeNormal?: THREE.Vector3;+}++interface ArchitectureSceneEvidence {+ root: THREE.Object3D;+ parts: ArchitecturePart[];+ semanticRoles: Set<string>;+}++interface ArchitectureAggregate {+ parts: ArchitecturePart[];+ bounds: Bounds3;+ vertices: THREE.Vector3[];+ triangles: ArchitectureTriangle[];+ normals: THREE.Vector3[];+}++const PROFILE_RULE_ID = 'ARCHITECTURE_PROFILE';+const EPSILON = 1e-6;++export const ARCHITECTURE_REALISTIC_SCALE_BANDS = Object.freeze({+ doorWidth: Object.freeze({ minimum: 0.75, maximum: 2.5, unit: 'm' as const }),+ doorHeight: Object.freeze({ minimum: 1.8, maximum: 3.2, unit: 'm' as const }),+ ceilingHeight: Object.freeze({ minimum: 2.1, maximum: 6, unit: 'm' as const }),+ stairRiser: Object.freeze({ minimum: 0.1, maximum: 0.25, unit: 'm' as const }),+ stairTread: Object.freeze({ minimum: 0.2, maximum: 0.45, unit: 'm' as const }),+ wallThickness: Object.freeze({ minimum: 0.05, maximum: 0.6, unit: 'm' as const }),+ footprint: Object.freeze({ minimum: 1.5, maximum: 200, unit: 'm' as const }),+});++const emptyBounds = (): Bounds3 => ({+ min: new THREE.Vector3(Infinity, Infinity, Infinity),+ max: new THREE.Vector3(-Infinity, -Infinity, -Infinity),+});++const expandBounds = (bounds: Bounds3, point: THREE.Vector3): void => {+ bounds.min.min(point);+ bounds.max.max(point);+};++const boundsFinite = (bounds: Bounds3): boolean => Number.isFinite(bounds.min.x);++const extent = (bounds: Bounds3, axis: Axis): number => bounds.max[axis] - bounds.min[axis];++function semanticRoles(node: THREE.Object3D): readonly string[] {+ return readSemanticMetadataV1FromExtras(node.userData)?.roles ?? [];+}++function markerBounds(matrix: THREE.Matrix4): Bounds3 {+ const bounds = emptyBounds();+ for (let corner = 0; corner < 8; corner++) {+ expandBounds(+ bounds,+ new THREE.Vector3(+ corner & 1 ? 0.5 : -0.5,+ corner & 2 ? 0.5 : -0.5,+ corner & 4 ? 0.5 : -0.5,+ ).applyMatrix4(matrix),+ );+ }+ return bounds;+}++function geometryPlaneNormal(+ geometry: THREE.BufferGeometry,+ relativeMatrix: THREE.Matrix4,+): THREE.Vector3 | undefined {+ geometry.computeBoundingBox();+ const local = geometry.boundingBox;+ if (!local) return undefined;+ const size = local.getSize(new THREE.Vector3());+ const dimensions: Array<[Axis, number]> = [+ ['x', size.x],+ ['y', size.y],+ ['z', size.z],+ ];+ dimensions.sort((a, b) => a[1] - b[1]);+ const axis = dimensions[0]?.[0];+ if (!axis) return undefined;+ const normal = new THREE.Vector3(+ axis === 'x' ? 1 : 0,+ axis === 'y' ? 1 : 0,+ axis === 'z' ? 1 : 0,+ ).transformDirection(relativeMatrix);+ if (normal.y < 0) normal.multiplyScalar(-1);+ return normal.normalize();+}++function geometryEvidence(+ geometry: THREE.BufferGeometry,+ relativeMatrix: THREE.Matrix4,+): {+ bounds: Bounds3;+ vertices: THREE.Vector3[];+ triangles: ArchitectureTriangle[];+ planeNormal?: THREE.Vector3;+} {+ const position = geometry.getAttribute('position');+ const bounds = emptyBounds();+ const vertices: THREE.Vector3[] = [];+ if (position?.itemSize !== 3) return { bounds, vertices, triangles: [] };++ for (let index = 0; index < position.count; index++) {+ const point = new THREE.Vector3(+ position.getX(index),+ position.getY(index),+ position.getZ(index),+ );+ point.applyMatrix4(relativeMatrix);+ vertices.push(point);+ expandBounds(bounds, point);+ }++ const triangles: ArchitectureTriangle[] = [];+ const indices = geometry.getIndex();+ const addTriangle = (a: number, b: number, c: number): void => {+ const va = vertices[a];+ const vb = vertices[b];+ const vc = vertices[c];+ if (va && vb && vc) triangles.push({ a: va, b: vb, c: vc });+ };+ if (indices) {+ for (let index = 0; index + 2 < indices.count; index += 3) {+ addTriangle(indices.getX(index), indices.getX(index + 1), indices.getX(index + 2));+ }+ } else {+ for (let index = 0; index + 2 < vertices.length; index += 3) {+ addTriangle(index, index + 1, index + 2);+ }+ }++ const planeNormal = geometryPlaneNormal(geometry, relativeMatrix);+ return { bounds, vertices, triangles, ...(planeNormal ? { planeNormal } : {}) };+}++function collectArchitectureEvidence(scene: unknown): ArchitectureSceneEvidence | undefined {+ if (!(scene instanceof THREE.Object3D)) return undefined;+ scene.updateMatrixWorld(true);+ const rootInverse = scene.matrixWorld.clone().invert();+ const parts: ArchitecturePart[] = [];+ const allRoles = new Set<string>();++ const visit = (+ node: THREE.Object3D,+ parentPath: string,+ siblingIndex: number,+ inheritedRoles: readonly string[],+ ): void => {+ const directRoles = semanticRoles(node);+ directRoles.forEach((role) => {+ allRoles.add(role);+ });+ const roles = [...new Set([...inheritedRoles, ...directRoles])];+ const segment = `${node.name.trim() || node.type || 'Object3D'}[${siblingIndex}]`;+ const nodePath = parentPath ? `${parentPath}/${segment}` : segment;+ const relativeMatrix = rootInverse.clone().multiply(node.matrixWorld);+ const mesh = node as THREE.Mesh;+ const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE.BufferGeometry;+ const evidence = isMesh+ ? geometryEvidence(mesh.geometry, relativeMatrix)+ : {+ bounds: markerBounds(relativeMatrix),+ vertices: [] as THREE.Vector3[],+ triangles: [] as ArchitectureTriangle[],+ };++ if (isMesh || directRoles.length > 0) {+ parts.push({+ node,+ nodeName: node.name || node.type,+ nodePath,+ directRoles,+ roles,+ isMesh,+ ...evidence,+ });+ }+ node.children.forEach((child, index) => {+ visit(child, nodePath, index, roles);+ });+ };++ visit(scene, '', 0, []);+ return { root: scene, parts, semanticRoles: allRoles };+}++const hasRole = (part: ArchitecturePart, role: string): boolean => part.roles.includes(role);++const hasRolePrefix = (part: ArchitecturePart, prefix: string): boolean =>+ part.roles.some((role) => role.startsWith(prefix));++function aggregate(parts: readonly ArchitecturePart[]): ArchitectureAggregate | undefined {+ if (parts.length === 0) return undefined;+ const bounds = emptyBounds();+ const vertices: THREE.Vector3[] = [];+ const triangles: ArchitectureTriangle[] = [];+ const normals: THREE.Vector3[] = [];+ for (const part of parts) {+ if (boundsFinite(part.bounds)) {+ expandBounds(bounds, part.bounds.min);+ expandBounds(bounds, part.bounds.max);+ }+ vertices.push(...part.vertices);+ triangles.push(...part.triangles);+ if (part.planeNormal) normals.push(part.planeNormal);+ }+ if (!boundsFinite(bounds)) return undefined;+ return { parts: [...parts], bounds, vertices, triangles, normals };+}++function aggregateRole(+ evidence: ArchitectureSceneEvidence,+ role: string,+): ArchitectureAggregate | undefined {+ return aggregate(evidence.parts.filter((part) => hasRole(part, role)));+}++function architectureFinding(+ context: QaContext,+ value: Omit<QaFinding, 'profile' | 'dimension'>,+): QaFinding {+ return withArchitectureRepair({+ ...value,+ profile: context.intent.qaProfile,+ dimension: 'categoryReadiness',+ });+}++function averageNormal(normals: readonly THREE.Vector3[]): THREE.Vector3 | undefined {+ if (normals.length === 0) return undefined;+ const result = normals.reduce((sum, normal) => sum.add(normal), new THREE.Vector3());+ return result.lengthSq() > EPSILON ? result.normalize() : undefined;+}++function intervalCoverage(+ min: number,+ max: number,+ expectedMin: number,+ expectedMax: number,+): number {+ const expected = expectedMax - expectedMin;+ if (expected <= EPSILON) return 1;+ return Math.max(0, Math.min(max, expectedMax) - Math.max(min, expectedMin)) / expected;+}++function intervalSeparation(aMin: number, aMax: number, bMin: number, bMax: number): number {+ if (aMax < bMin) return bMin - aMax;+ if (bMax < aMin) return aMin - bMax;+ return 0;+}++function requestedGable(architecture: ArchitectureIntentV1): boolean {+ return architecture.roof.type === 'gable';+}++function taggedGable(evidence: ArchitectureSceneEvidence): boolean {+ return [...evidence.semanticRoles].some(+ (role) =>+ role === 'architecture.shell.gable' ||+ role.startsWith('roof.slope.') ||+ role.startsWith('roof.gable.'),+ );+}++function isOpenPavilion(+ architecture: ArchitectureIntentV1,+ evidence: ArchitectureSceneEvidence,+): boolean {+ return (+ /(?:^|[. _-])(?:open[. _-])?pavilion(?:$|[. _-])/i.test(architecture.subtype) ||+ evidence.semanticRoles.has('architecture.open-pavilion')+ );+}++function highEdgeVertices(aggregateValue: ArchitectureAggregate, rise: number): THREE.Vector3[] {+ const band = Math.max(0.006, rise * 0.02);+ const maximumY = aggregateValue.bounds.max.y;+ return aggregateValue.vertices.filter((point) => point.y >= maximumY - band);+}++function ridgeCrossSectionDistance(+ positive: ArchitectureAggregate,+ negative: ArchitectureAggregate,+ lateralAxis: HorizontalAxis,+ rise: number,+): number {+ const a = highEdgeVertices(positive, rise);+ const b = highEdgeVertices(negative, rise);+ let distance = Infinity;+ for (const pointA of a) {+ for (const pointB of b) {+ distance = Math.min(+ distance,+ Math.hypot(pointA[lateralAxis] - pointB[lateralAxis], pointA.y - pointB.y),+ );+ }+ }+ return distance;+}++function roofFindings(+ context: QaContext,+ architecture: ArchitectureIntentV1,+ evidence: ArchitectureSceneEvidence,+): QaFinding[] {+ if (!requestedGable(architecture) && !taggedGable(evidence)) return [];+ const positive = aggregateRole(evidence, 'roof.slope.positive');+ const negative = aggregateRole(evidence, 'roof.slope.negative');+ const tagged = taggedGable(evidence);+ const exactDisposition = tagged ? ('block' as const) : ('warn' as const);+ const findings: QaFinding[] = [];++ if (!positive || !negative) {+ findings.push(+ architectureFinding(context, {+ code: 'ARCH_ROOF_AXIS',+ disposition: exactDisposition,+ message: `A gable requires exactly two semantic slope roles; found ${positive ? 1 : 0} positive and ${negative ? 1 : 0} negative slope surfaces.`,+ measurement: {+ name: 'semanticSlopeRoleCount',+ actual: Number(Boolean(positive)) + Number(Boolean(negative)),+ expected: 2,+ threshold: 2,+ },+ affected: { node: evidence.root.name || 'architecture-root' },+ }),+ );+ }++ const semanticRoofRoles = [...evidence.semanticRoles].filter((role) => role.startsWith('roof.'));+ if (semanticRoofRoles.length === 0) {+ const inferredRoof = evidence.parts.find(+ (part) => part.isMesh && /(?:^|[_ .-])roof(?:$|[_ .-])/i.test(part.nodeName),+ );+ findings.push(+ architectureFinding(context, {+ code: 'ARCH_MISSING_ROOF_ROLES',+ disposition: 'warn',+ message:+ 'The architecture has no portable roof.* semantic roles, so ridge, coverage, diagnostic cutaway, and separability checks cannot be exact.',+ affected: inferredRoof+ ? { node: inferredRoof.nodeName, nodePath: inferredRoof.nodePath }+ : { node: evidence.root.name || 'architecture-root' },+ viewHints: ['generic.top.semantic-overlay', 'architecture.cutaway.dollhouse'],+ repairText:+ 'Build the roof with the gable shell helper or stamp roof.slope.positive/negative and roof.gable.positive/negative roles plus separable-from relationships.',+ }),+ );+ return findings;+ }++ if (!positive || !negative) return findings;++ const ridgeAxis = architecture.roof.ridgeAxis;+ const lateralAxis: HorizontalAxis = ridgeAxis === 'x' ? 'z' : 'x';+ const positiveNormal = averageNormal(positive.normals);+ const negativeNormal = averageNormal(negative.normals);+ const lateralProduct =+ positiveNormal && negativeNormal+ ? positiveNormal[lateralAxis] * negativeNormal[lateralAxis]+ : null;+ if (lateralProduct === null || lateralProduct >= -0.0025) {+ findings.push(+ architectureFinding(context, {+ code: 'ARCH_ROOF_AXIS',+ disposition: exactDisposition,+ message:+ 'The two semantic gable slopes do not face opposite downhill directions in the declared roof-local frame.',+ affected: { node: negative.parts[0]?.nodeName ?? 'roof.slope.negative' },+ measurement: {+ name: 'slopeLateralNormalProduct',+ actual: lateralProduct,+ expected: '< -0.0025',+ threshold: -0.0025,+ },+ }),+ );+ }++ const { spanX, spanZ } = architecture.footprint;+ const expectedRidgeSpan = (ridgeAxis === 'x' ? spanX : spanZ) + architecture.roof.overhang * 2;+ const expectedLateralSpan =+ (lateralAxis === 'x' ? spanX : spanZ) + architecture.roof.overhang * 2;+ const ridgeCoverage = Math.min(+ extent(positive.bounds, ridgeAxis) / expectedRidgeSpan,+ extent(negative.bounds, ridgeAxis) / expectedRidgeSpan,+ );+ const roofMinLateral = Math.min(+ positive.bounds.min[lateralAxis],+ negative.bounds.min[lateralAxis],+ );+ const roofMaxLateral = Math.max(+ positive.bounds.max[lateralAxis],+ negative.bounds.max[lateralAxis],+ );+ const lateralCoverage = intervalCoverage(+ roofMinLateral,+ roofMaxLateral,+ -expectedLateralSpan / 2,+ expectedLateralSpan / 2,+ );+ if (ridgeCoverage < 0.9 || lateralCoverage < 0.9) {+ const actual = Math.min(ridgeCoverage, lateralCoverage);+ findings.push(+ architectureFinding(context, {+ code: 'ARCH_ROOF_AXIS',+ disposition: exactDisposition,+ message: `The semantic slopes cover ${(ridgeCoverage * 100).toFixed(1)}% of the ridge span and ${(lateralCoverage * 100).toFixed(1)}% of the ridge-to-eave span.`,+ measurement: {+ name: 'minimumRoofFootprintCoverageRatio',+ actual,+ expected: '>= 0.9',+ threshold: 0.9,+ },+ affected: { node: positive.parts[0]?.nodeName ?? 'roof.slope.positive' },+ }),+ );+ }++ const panels = evidence.parts.filter(+ (part) =>+ part.isMesh &&+ (part.directRoles.some((role) => role.startsWith('roof.panel.')) ||+ hasRole(part, 'roof.surface.panels') ||+ (hasRolePrefix(part, 'roof.') && /panel|sheet|shingle|seam|corrugat/i.test(part.nodeName))),+ );+ const wrongPanel = panels.find((panel) => {+ const ridgeExtent = extent(panel.bounds, ridgeAxis);+ const downhillExtent = Math.hypot(extent(panel.bounds, lateralAxis), extent(panel.bounds, 'y'));+ return ridgeExtent > downhillExtent * 1.05;+ });+ if (wrongPanel) {+ const ridgeExtent = extent(wrongPanel.bounds, ridgeAxis);+ const downhillExtent = Math.hypot(+ extent(wrongPanel.bounds, lateralAxis),+ extent(wrongPanel.bounds, 'y'),+ );+ findings.push(+ architectureFinding(context, {+ code: 'ARCH_ROOF_AXIS',+ disposition: exactDisposition,+ message: `Roof panel ${wrongPanel.nodeName} runs along the ridge instead of ridge-to-eave.`,+ affected: { node: wrongPanel.nodeName, nodePath: wrongPanel.nodePath },+ measurement: {+ name: 'panelRidgeToDownhillExtentRatio',+ actual: ridgeExtent / Math.max(EPSILON, downhillExtent),+ expected: '<= 1.05',+ threshold: 1.05,+ },+ }),+ );+ }++ const ridgeDistance = ridgeCrossSectionDistance(+ positive,+ negative,+ lateralAxis,+ architecture.roof.rise,+ );+ const ridgeTolerance = Math.max(0.04, expectedLateralSpan * 0.0125);+ if (!Number.isFinite(ridgeDistance) || ridgeDistance > ridgeTolerance) {+ findings.push(+ architectureFinding(context, {+ code: 'ARCH_RIDGE_GAP',+ disposition: exactDisposition,+ message: `The two slope high edges miss the declared ridge by ${Number.isFinite(ridgeDistance) ? ridgeDistance.toFixed(3) : 'an unmeasurable'} m.`,+ affected: { node: negative.parts[0]?.nodeName ?? 'roof.slope.negative' },+ measurement: {+ name: 'ridgeCrossSectionGap',+ actual: Number.isFinite(ridgeDistance) ? ridgeDistance : null,+ expected: `<= ${ridgeTolerance}`,+ threshold: ridgeTolerance,+ unit: 'm',+ },+ }),+ );+ }++ return findings;+}++function projectedGableArea(+ aggregateValue: ArchitectureAggregate,+ lateralAxis: HorizontalAxis,+): number {+ let area = 0;+ for (const triangle of aggregateValue.triangles) {+ const abLateral = triangle.b[lateralAxis] - triangle.a[lateralAxis];+ const abY = triangle.b.y - triangle.a.y;+ const acLateral = triangle.c[lateralAxis] - triangle.a[lateralAxis];+ const acY = triangle.c.y - triangle.a.y;+ area += Math.abs(abLateral * acY - abY * acLateral) / 2;+ }+ return area;+}++function endFindings(+ context: QaContext,+ architecture: ArchitectureIntentV1,+ evidence: ArchitectureSceneEvidence,+): QaFinding[] {+ if (!requestedGable(architecture) || isOpenPavilion(architecture, evidence)) return [];+ const closedEnds = architecture.roof.closedEnds;+ if (!closedEnds) return [];++ const positive = aggregateRole(evidence, 'roof.gable.positive');+ const negative = aggregateRole(evidence, 'roof.gable.negative');+ const hasTaggedRoof = taggedGable(evidence);+ const disposition = hasTaggedRoof ? ('block' as const) : ('warn' as const);+ const ridgeAxis = architecture.roof.ridgeAxis;+ const lateralAxis: HorizontalAxis = ridgeAxis === 'x' ? 'z' : 'x';+ const lateralSpan =+ lateralAxis === 'x' ? architecture.footprint.spanX : architecture.footprint.spanZ;+ const ridgeSpan = ridgeAxis === 'x' ? architecture.footprint.spanX : architecture.footprint.spanZ;+ const expectedArea = (lateralSpan * architecture.roof.rise) / 2;+ const findings: QaFinding[] = [];++ for (const [end, aggregateValue] of [+ ['positive', positive],+ ['negative', negative],+ ] as const) {+ if (!aggregateValue) {+ findings.push(+ architectureFinding(context, {+ code: 'ARCH_OPEN_GABLE',+ disposition,+ message: `closedEnds=true but roof.gable.${end} is missing.`,+ affected: { node: `roof.gable.${end}` },+ measurement: {+ name: `${end}GableCoverageRatio`,+ actual: 0,+ expected: '>= 0.9 boundary coverage',+ threshold: 0.9,+ },+ }),+ );+ continue;+ }++ const wallRole =+ ridgeAxis === 'x'+ ? end === 'positive'+ ? 'wall.front'+ : 'wall.back'+ : end === 'positive'+ ? 'wall.right'+ : 'wall.left';+ const endWall = aggregate(+ evidence.parts.filter((part) => part.isMesh && hasRole(part, wallRole)),+ );+ const gableCenter =+ (aggregateValue.bounds.min[ridgeAxis] + aggregateValue.bounds.max[ridgeAxis]) / 2;+ const expectedCenter = (end === 'positive' ? 1 : -1) * (ridgeSpan / 2);+ const endSeparation = endWall+ ? intervalSeparation(+ aggregateValue.bounds.min[ridgeAxis],+ aggregateValue.bounds.max[ridgeAxis],+ endWall.bounds.min[ridgeAxis],+ endWall.bounds.max[ridgeAxis],+ )+ : Math.abs(gableCenter - expectedCenter);+ const endTolerance = 0.05;+ if (endSeparation > endTolerance) {+ findings.push(+ architectureFinding(context, {+ code: 'ARCH_OPEN_GABLE',+ disposition,+ message: `roof.gable.${end} is ${endSeparation.toFixed(3)} m away from its ${wallRole} end boundary, so it does not close the shell.`,+ affected: {+ node: aggregateValue.parts[0]?.nodeName ?? `roof.gable.${end}`,+ nodePath: aggregateValue.parts[0]?.nodePath,+ },+ measurement: {+ name: `${end}GableEndSeparation`,+ actual: endSeparation,+ expected: `<= ${endTolerance}`,+ threshold: endTolerance,+ unit: 'm',+ },+ }),+ );+ continue;+ }++ const lateralCoverage = extent(aggregateValue.bounds, lateralAxis) / lateralSpan;+ const heightCoverage = extent(aggregateValue.bounds, 'y') / architecture.roof.rise;+ const areaCoverage =+ expectedArea > EPSILON ? projectedGableArea(aggregateValue, lateralAxis) / expectedArea : 1;+ const boundaryCoverage = Math.min(lateralCoverage, heightCoverage);+ if (boundaryCoverage < 0.9 || areaCoverage < 0.45) {+ findings.push(+ architectureFinding(context, {+ code: 'ARCH_OPEN_GABLE',+ disposition,+ message: `roof.gable.${end} is sparse: boundary coverage ${(boundaryCoverage * 100).toFixed(1)}%, projected filled area ${(areaCoverage * 100).toFixed(1)}%.`,+ affected: {+ node: aggregateValue.parts[0]?.nodeName ?? `roof.gable.${end}`,+ nodePath: aggregateValue.parts[0]?.nodePath,+ },+ measurement: {+ name: `${end}GableMinimumCoverageRatio`,+ actual: Math.min(boundaryCoverage, areaCoverage / 0.5),+ expected: '>= 0.9 boundary and >= 0.45 area',+ threshold: 0.9,+ },+ }),+ );+ }+ }++ return findings;+}++function pointInProjectedTriangle(+ x: number,+ z: number,+ triangle: ArchitectureTriangle,+): { inside: boolean; weights: [number, number, number] } {+ const ax = triangle.a.x;+ const az = triangle.a.z;+ const bx = triangle.b.x;+ const bz = triangle.b.z;+ const cx = triangle.c.x;+ const cz = triangle.c.z;+ const denominator = (bz - cz) * (ax - cx) + (cx - bx) * (az - cz);+ if (Math.abs(denominator) <= EPSILON) return { inside: false, weights: [0, 0, 0] };+ const wa = ((bz - cz) * (x - cx) + (cx - bx) * (z - cz)) / denominator;+ const wb = ((cz - az) * (x - cx) + (ax - cx) * (z - cz)) / denominator;+ const wc = 1 - wa - wb;+ const tolerance = 1e-5;+ return {+ inside: wa >= -tolerance && wb >= -tolerance && wc >= -tolerance,+ weights: [wa, wb, wc],+ };+}++function nearestRoofHeight(+ triangles: readonly ArchitectureTriangle[],+ x: number,+ z: number,+ targetY: number,+): number | undefined {+ const heights: number[] = [];+ for (const triangle of triangles) {+ const projected = pointInProjectedTriangle(x, z, triangle);+ if (!projected.inside) continue;+ const [wa, wb, wc] = projected.weights;+ heights.push(wa * triangle.a.y + wb * triangle.b.y + wc * triangle.c.y);+ }+ return heights.sort((a, b) => Math.abs(a - targetY) - Math.abs(b - targetY))[0];+}++function envelopeFindings(+ context: QaContext,+ architecture: ArchitectureIntentV1,+ evidence: ArchitectureSceneEvidence,+): QaFinding[] {+ if (!requestedGable(architecture) || isOpenPavilion(architecture, evidence)) return [];+ const roof = aggregate(+ evidence.parts.filter(+ (part) =>+ part.isMesh &&+ (hasRole(part, 'roof.slope.positive') || hasRole(part, 'roof.slope.negative')),+ ),+ );+ if (!roof || roof.triangles.length === 0) return [];++ const ridgeAxis = architecture.roof.ridgeAxis;+ const lateralAxis: HorizontalAxis = ridgeAxis === 'x' ? 'z' : 'x';+ const ridgeSpan = ridgeAxis === 'x' ? architecture.footprint.spanX : architecture.footprint.spanZ;+ const lateralSpan =+ lateralAxis === 'x' ? architecture.footprint.spanX : architecture.footprint.spanZ;+ const wallRoles =+ ridgeAxis === 'x'+ ? (['wall.left', 'wall.right'] as const)+ : (['wall.front', 'wall.back'] as const);+ const findings: QaFinding[] = [];+ const gapTolerance = 0.05;+ const penetrationTolerance = 0.12;++ for (const [sideIndex, wallRole] of wallRoles.entries()) {+ const wall = aggregateRole(evidence, wallRole);+ if (!wall) continue;+ const sign = sideIndex === 0 ? -1 : 1;+ const lateral = sign * (lateralSpan / 2);+ const wallTop = wall.bounds.max.y;+ const offsets = [-0.4, 0, 0.4];+ const separations: number[] = [];+ for (const offset of offsets) {+ const ridge = offset * ridgeSpan;+ const x = ridgeAxis === 'x' ? ridge : lateral;+ const z = ridgeAxis === 'x' ? lateral : ridge;+ const roofY = nearestRoofHeight(roof.triangles, x, z, wallTop);+ if (roofY !== undefined) separations.push(roofY - wallTop);+ }+ if (separations.length === 0) continue;+ const worstGap = Math.max(...separations);+ const worstPenetration = -Math.min(...separations);+ if (worstGap > gapTolerance || worstPenetration > penetrationTolerance) {+ const daylight = worstGap > gapTolerance;+ findings.push(+ architectureFinding(context, {+ code: 'ARCH_ENVELOPE_GAP',+ disposition: 'warn',+ message: daylight+ ? `${wallRole} has a ${worstGap.toFixed(3)} m daylight gap to the roof underside at sampled bearing points.`+ : `${wallRole} penetrates the roof envelope by ${worstPenetration.toFixed(3)} m at sampled bearing points.`,+ affected: {+ node: wall.parts[0]?.nodeName ?? wallRole,+ nodePath: wall.parts[0]?.nodePath,+ },+ measurement: {+ name: daylight ? 'maximumWallRoofGap' : 'maximumWallRoofPenetration',+ actual: daylight ? worstGap : worstPenetration,+ expected: daylight ? `<= ${gapTolerance}` : `<= ${penetrationTolerance}`,+ threshold: daylight ? gapTolerance : penetrationTolerance,+ unit: 'm',+ },+ }),+ );+ }+ }++ return findings;+}++function boundsOverlap(a: Bounds3, b: Bounds3, tolerance = 0): boolean {+ return (+ a.min.x < b.max.x - tolerance &&+ a.max.x > b.min.x + tolerance &&+ a.min.y < b.max.y - tolerance &&+ a.max.y > b.min.y + tolerance &&+ a.min.z < b.max.z - tolerance &&+ a.max.z > b.min.z + tolerance+ );+}++function shrunkenPortalBounds(bounds: Bounds3, wall: string): Bounds3 {+ const result = { min: bounds.min.clone(), max: bounds.max.clone() };+ const widthAxis: HorizontalAxis = wall === 'front' || wall === 'back' ? 'z' : 'x';+ const normalAxis: HorizontalAxis = widthAxis === 'x' ? 'z' : 'x';+ const widthInset = Math.min(0.04, extent(result, widthAxis) * 0.08);+ const heightInset = Math.min(0.04, extent(result, 'y') * 0.04);+ result.min[widthAxis] += widthInset;+ result.max[widthAxis] -= widthInset;+ result.min.y += heightInset;+ result.max.y -= heightInset;+ // Keep the full normal passage depth: a wall or painted door crossing any of+ // it is a real blocker, not an edge-contact artifact.+ if (extent(result, normalAxis) <= EPSILON) {+ result.min[normalAxis] -= 0.01;+ result.max[normalAxis] += 0.01;+ }+ return result;+}++function portalRoleWall(roles: readonly string[]): string | undefined {+ for (const role of roles) {+ const match = /^opening\.(front|back|left|right)\.(?:door|portal|entry)(?:\.|$)/.exec(role);+ if (match) return match[1];+ }+ return undefined;+}++function portalFindings(+ context: QaContext,+ architecture: ArchitectureIntentV1,+ evidence: ArchitectureSceneEvidence,+): QaFinding[] {+ if (!architecture.enterable && !context.intent.capabilities.includes('enterable')) return [];+ const requested = architecture.portal ?? { width: 1.1, height: 2.1, depth: 0.15 };+ const markers = evidence.parts.filter(+ (part) => !part.isMesh && portalRoleWall(part.directRoles) !== undefined,+ );+ if (markers.length === 0) {+ return [+ architectureFinding(context, {+ code: 'ARCH_BLOCKED_PORTAL',+ disposition: 'block',+ message:+ 'enterable=true requires a non-rendered semantic opening.<wall>.door clearance node; no exterior-to-interior portal was found.',+ affected: { node: evidence.root.name || 'architecture-root' },+ measurement: {+ name: 'semanticPortalCount',+ actual: 0,+ expected: '>= 1',+ threshold: 1,+ },+ }),+ ];+ }++ const failures: Array<{+ marker: ArchitecturePart;+ wall: string;+ blocker?: ArchitecturePart;+ width: number;+ height: number;+ depth: number;+ placementCoverage: number;+ undersized: boolean;+ misplaced: boolean;+ }> = [];++ for (const marker of markers) {+ const wall = portalRoleWall(marker.directRoles)!;+ const widthAxis: HorizontalAxis = wall === 'front' || wall === 'back' ? 'z' : 'x';+ const depthAxis: HorizontalAxis = widthAxis === 'x' ? 'z' : 'x';+ const width = extent(marker.bounds, widthAxis);+ const height = extent(marker.bounds, 'y');+ const depth = extent(marker.bounds, depthAxis);+ const claimedWall = aggregate(+ evidence.parts.filter(+ (part) => part.isMesh && hasRole(part, `wall.${wall}`) && !hasRolePrefix(part, 'opening.'),+ ),+ );+ const placementCoverage = claimedWall+ ? Math.min(+ intervalCoverage(+ marker.bounds.min[depthAxis],+ marker.bounds.max[depthAxis],+ claimedWall.bounds.min[depthAxis],+ claimedWall.bounds.max[depthAxis],+ ),+ intervalCoverage(+ claimedWall.bounds.min[widthAxis],+ claimedWall.bounds.max[widthAxis],+ marker.bounds.min[widthAxis],+ marker.bounds.max[widthAxis],+ ),+ intervalCoverage(+ claimedWall.bounds.min.y,+ claimedWall.bounds.max.y,+ marker.bounds.min.y,+ marker.bounds.max.y,+ ),+ )+ : 0;+ const misplaced = placementCoverage < 0.9;+ const clearance = shrunkenPortalBounds(marker.bounds, wall);+ const blocker = evidence.parts.find((part) => {+ if (!part.isMesh) return false;+ if (+ hasRolePrefix(part, 'roof.') ||+ hasRole(part, 'floor') ||+ hasRolePrefix(part, 'opening.')+ ) {+ return false;+ }+ if (+ context.intent.capabilities.includes('openable') &&+ part.roles.some((role) => role === 'door.leaf' || role.startsWith('door.leaf.'))+ ) {+ return false;+ }+ return boundsOverlap(part.bounds, clearance, 0.004);+ });+ const undersized =+ width + 0.01 < requested.width ||+ height + 0.01 < requested.height ||+ depth + 0.01 < requested.depth;+ if (!blocker && !undersized && !misplaced) return [];+ failures.push({+ marker,+ wall,+ ...(blocker ? { blocker } : {}),+ width,+ height,+ depth,+ placementCoverage,+ undersized,+ misplaced,+ });+ }++ const failure = failures[0]!;+ const undersizedBy = Math.max(+ 0,+ requested.width - failure.width,+ requested.height - failure.height,+ requested.depth - failure.depth,+ );+ return [+ architectureFinding(context, {+ code: 'ARCH_BLOCKED_PORTAL',+ disposition: 'block',+ message: failure.blocker+ ? `Portal ${failure.marker.nodeName} is blocked by ${failure.blocker.nodeName}; the semantic clearance does not connect exterior to interior.`+ : failure.undersized+ ? `Portal ${failure.marker.nodeName} is smaller than the requested ${requested.width.toFixed(2)} x ${requested.height.toFixed(2)} x ${requested.depth.toFixed(2)} m clearance.`+ : `Portal ${failure.marker.nodeName} overlaps only ${(failure.placementCoverage * 100).toFixed(1)}% of its claimed wall passage, so it does not connect exterior to interior through wall.${failure.wall}.`,+ affected: failure.blocker+ ? { node: failure.blocker.nodeName, nodePath: failure.blocker.nodePath }+ : { node: failure.marker.nodeName, nodePath: failure.marker.nodePath },+ measurement: failure.blocker+ ? {+ name: 'portalBlockerCount',+ actual: 1,+ expected: 0,+ threshold: 0,+ }+ : failure.undersized+ ? {+ name: 'maximumPortalClearanceDeficit',+ actual: undersizedBy,+ expected: 0,+ threshold: 0.01,+ unit: 'm',+ }+ : {+ name: 'portalClaimedWallCoverageRatio',+ actual: failure.placementCoverage,+ expected: '>= 0.9',+ threshold: 0.9,+ },+ viewHints: ['architecture.portal.eye'],+ }),+ ];+}++interface ScaleBand {+ code: string;+ label: string;+ actual: number;+ minimum: number;+ maximum: number;+ unit: 'm';+ affected?: ArchitecturePart;+}++function scaleBandFinding(context: QaContext, band: ScaleBand): QaFinding | undefined {+ if (band.actual >= band.minimum && band.actual <= band.maximum) return undefined;+ return architectureFinding(context, {+ code: band.code,+ disposition: 'warn',+ message: `${band.label} is ${band.actual.toFixed(3)} m; the realistic-scale observation band is ${band.minimum.toFixed(3)}–${band.maximum.toFixed(3)} m.`,+ ...(band.affected+ ? { affected: { node: band.affected.nodeName, nodePath: band.affected.nodePath } }+ : {}),+ measurement: {+ name: band.label,+ actual: band.actual,+ expected: `${band.minimum}..${band.maximum}`,+ threshold: band.actual < band.minimum ? band.minimum : band.maximum,+ unit: band.unit,+ },+ viewHints: ['architecture.cutaway.dollhouse'],+ repairText:+ 'Adjust only the reported architecture dimension into the realistic band, or explicitly select scaleMode=stylized to retain intentional exaggeration.',+ });+}++function scaleFindings(+ context: QaContext,+ architecture: ArchitectureIntentV1,+ evidence: ArchitectureSceneEvidence,+): QaFinding[] {+ if (architecture.scaleMode === 'stylized') return [];+ const scaleBands = ARCHITECTURE_REALISTIC_SCALE_BANDS;+ const bands: ScaleBand[] = [+ {+ code: 'ARCH_SCALE_CEILING_HEIGHT',+ label: 'ceilingHeight',+ actual: architecture.wallHeight,+ minimum: scaleBands.ceilingHeight.minimum,+ maximum: scaleBands.ceilingHeight.maximum,+ unit: 'm',+ },+ {+ code: 'ARCH_SCALE_FOOTPRINT_X',+ label: 'footprintSpanX',+ actual: architecture.footprint.spanX,+ minimum: scaleBands.footprint.minimum,+ maximum: scaleBands.footprint.maximum,+ unit: 'm',+ },+ {+ code: 'ARCH_SCALE_FOOTPRINT_Z',+ label: 'footprintSpanZ',+ actual: architecture.footprint.spanZ,+ minimum: scaleBands.footprint.minimum,+ maximum: scaleBands.footprint.maximum,+ unit: 'm',+ },+ ];++ const portal = evidence.parts.find(+ (part) => !part.isMesh && portalRoleWall(part.directRoles) !== undefined,+ );+ if (portal) {+ const wall = portalRoleWall(portal.directRoles)!;+ const widthAxis: HorizontalAxis = wall === 'front' || wall === 'back' ? 'z' : 'x';+ bands.push(+ {+ code: 'ARCH_SCALE_DOOR_WIDTH',+ label: 'doorClearWidth',+ actual: extent(portal.bounds, widthAxis),+ minimum: scaleBands.doorWidth.minimum,+ maximum: scaleBands.doorWidth.maximum,+ unit: 'm',+ affected: portal,+ },+ {+ code: 'ARCH_SCALE_DOOR_HEIGHT',+ label: 'doorClearHeight',+ actual: extent(portal.bounds, 'y'),+ minimum: scaleBands.doorHeight.minimum,+ maximum: scaleBands.doorHeight.maximum,+ unit: 'm',+ affected: portal,+ },+ );+ }++ const wallParts = evidence.parts.filter(+ (part) => part.isMesh && part.roles.some((role) => role.startsWith('wall.')),+ );+ for (const wall of wallParts) {+ const thickness = Math.min(extent(wall.bounds, 'x'), extent(wall.bounds, 'z'));+ bands.push({+ code: 'ARCH_SCALE_WALL_THICKNESS',+ label: 'wallThickness',+ actual: thickness,+ minimum: scaleBands.wallThickness.minimum,+ maximum: scaleBands.wallThickness.maximum,+ unit: 'm',+ affected: wall,+ });+ }++ const steps = evidence.parts.filter(+ (part) => part.isMesh && part.directRoles.some((role) => role.startsWith('stair.step')),+ );+ for (const step of steps) {+ bands.push(+ {+ code: 'ARCH_SCALE_STAIR_RISER',+ label: 'stairRiser',+ actual: extent(step.bounds, 'y'),+ minimum: scaleBands.stairRiser.minimum,+ maximum: scaleBands.stairRiser.maximum,+ unit: 'm',+ affected: step,+ },+ {+ code: 'ARCH_SCALE_STAIR_TREAD',+ label: 'stairTread',+ actual: Math.min(extent(step.bounds, 'x'), extent(step.bounds, 'z')),+ minimum: scaleBands.stairTread.minimum,+ maximum: scaleBands.stairTread.maximum,+ unit: 'm',+ affected: step,+ },+ );+ }++ return bands.flatMap((band) => {+ const finding = scaleBandFinding(context, band);+ return finding ? [finding] : [];+ });+}++/** Deterministic architecture checks selected only by closure-owned intent. */+export function evaluateArchitectureQa(context: QaContext): readonly QaFinding[] {+ const architecture = context.intent.architecture;+ if (!architecture || context.intent.category !== 'architecture') return [];+ const evidence = collectArchitectureEvidence(context.scene);+ if (!evidence) return [];+ return [+ ...roofFindings(context, architecture, evidence),+ ...endFindings(context, architecture, evidence),+ ...envelopeFindings(context, architecture, evidence),+ ...portalFindings(context, architecture, evidence),+ ...scaleFindings(context, architecture, evidence),+ ];+}++export const ARCHITECTURE_QA_RULE: QaRule = {+ id: PROFILE_RULE_ID,+ profile: 'architecture.default',+ scope: { kind: 'category', category: 'architecture' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'architecture-qa-v1',+ 'src/qa/architecture.test.ts',+ 'd83b6f3696455bb8c14bb4d36fa61e9470314af75959cb20b6da8da76c83e3da',+ ),+ defaultMode: 'enforce',+ evaluate: (context) =>+ evaluateArchitectureQa(context).filter((finding) => finding.disposition === 'block'),+};++/** Inferred geometry and realistic-scale bands remain observe-only until QA-026 calibration. */+export const ARCHITECTURE_ADVISORY_QA_RULE: QaRule = {+ id: 'ARCHITECTURE_ADVISORY_PROFILE',+ profile: 'architecture.advisory',+ scope: { kind: 'category', category: 'architecture' },+ ruleClass: 'heuristic',+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: 'observe',+ evaluate: (context) =>+ evaluateArchitectureQa(context).filter((finding) => finding.disposition !== 'block'),+};++export const ARCHITECTURE_QA_RULES: readonly QaRule[] = [+ ARCHITECTURE_QA_RULE,+ ARCHITECTURE_ADVISORY_QA_RULE,+] as const;diff --git a/src/qa/breadth-corpus.test.ts b/src/qa/breadth-corpus.test.tsnew file mode 100644index 00000000..4bc747b4--- /dev/null+++ b/src/qa/breadth-corpus.test.ts@@ -0,0 +1,233 @@+import { describe, expect, test } from 'bun:test';++import {+ renderAssetScopePrompt,+ renderModularKitPrompt,+ renderVfxBreadthPrompt,+} from '../breadth-prompt';+import { createAssetIntentV1, type AssetIntentV1 } from '../contracts/asset';+import type {+ AssetScopeIntentV1,+ AssetScopeObservationV1,+ ModularJoinObservationV1,+ ModularKitContractV1,+ VfxIntentV1,+} from '../contracts/breadth';+import {+ W7_BREADTH_QA_RULES,+ evaluateAssetScopeQa,+ evaluateModularJoinQa,+ evaluateVfxAdvisoryQa,+ evaluateVfxExactQa,+ measureVfxRuntimeCostV1,+} from './breadth';+import { VFX_BENCH_RUBRIC_V1, VFX_BREADTH_CORPUS_V1 } from './breadth-corpus';+import { QaRegistry } from './registry';+import type { QaContext } from './types';++const context = (+ category: AssetIntentV1['category'],+ extras: {+ vfx?: VfxIntentV1;+ scope?: AssetScopeIntentV1;+ scopeObservation?: AssetScopeObservationV1;+ modularKit?: ModularKitContractV1;+ modularJoin?: ModularJoinObservationV1;+ },+ vfxArtifact?: unknown,+): QaContext => ({+ intent: createAssetIntentV1({+ category,+ subtype: category === 'vfx' ? extras.vfx?.subtype : undefined,+ ...(extras.vfx ? { vfx: extras.vfx } : {}),+ ...(extras.scope ? { scope: extras.scope } : {}),+ ...(extras.modularKit ? { scope: { scope: 'modularSet' as const, explicit: true } } : {}),+ material: {+ mode: extras.vfx?.portability === 'sidecar' ? 'runtimeTsl' : 'pbrRecipe',+ ...(extras.vfx ? { transparency: extras.vfx.transparency } : {}),+ },+ }),+ derivedEvidence: {+ source: 'engine-scene-analysis',+ ...(vfxArtifact !== undefined ? { vfxArtifact } : {}),+ ...(extras.scopeObservation ? { assetScope: extras.scopeObservation } : {}),+ ...(extras.modularKit ? { modularKit: extras.modularKit } : {}),+ ...(extras.modularJoin ? { modularJoin: extras.modularJoin } : {}),+ },+});++const modularKit = (): ModularKitContractV1 => ({+ schemaVersion: 1,+ units: 'm',+ grid: [1, 1, 1],+ sockets: [+ {+ id: 'a.east',+ pieceId: 'a',+ type: 'wall.east',+ compatibleTypes: ['wall.west'],+ frame: { translation: [1, 0, 0], rotation: [0, 0, 0, 1] },+ allowedRotationsDegrees: [0, 90, 180, 270],+ },+ {+ id: 'b.west',+ pieceId: 'b',+ type: 'wall.west',+ compatibleTypes: ['wall.east'],+ frame: { translation: [-1, 0, 0], rotation: [0, 1, 0, 0] },+ allowedRotationsDegrees: [0, 90, 180, 270],+ },+ ],+});++const joined = (overlap = 0): ModularJoinObservationV1 => ({+ aSocketId: 'a.east',+ bSocketId: 'b.west',+ aWorldPosition: [1, 0, 0],+ bWorldPosition: [1 - overlap, 0, 0],+ aWorldNormal: [1, 0, 0],+ bWorldNormal: [-1, 0, 0],+ relativeRotationDegrees: 0,+});++describe('W7 VFX/modular/scope/reference corpus', () => {+ test('VFX-002/003/004 exact fixtures emit only their frozen expected codes', () => {+ for (const fixture of VFX_BREADTH_CORPUS_V1) {+ const findings = evaluateVfxExactQa(+ context('vfx', { vfx: fixture.intent }, fixture.evidence),+ );+ expect(+ findings.map((finding) => finding.code),+ fixture.id,+ ).toEqual(fixture.expectedExactCodes);+ for (const finding of findings) expect(finding.disposition).toBe('block');+ }+ });++ test('VFX-005 reports transparent area/layers/overdraw/texture/sidecar separately', () => {+ const fixture = VFX_BREADTH_CORPUS_V1.find((value) => value.id === 'vfx.tsl-sidecar.valid')!;+ const cost = measureVfxRuntimeCostV1(fixture.evidence);+ expect(cost).toEqual({+ schemaVersion: 1,+ blendedScreenAreaRatio: 0.24,+ transparentLayerCount: 2,+ overdrawProxy: 0.48,+ textureMemoryBytes: 1_048_576,+ shaderSidecarRequired: true,+ });+ expect('instanceabilityGrade' in cost).toBe(false);+ const findings = evaluateVfxAdvisoryQa(+ context('vfx', { vfx: fixture.intent }, fixture.evidence),+ );+ expect(findings.map((finding) => finding.code)).toContain('VFX_RUNTIME_COST_REPORT');+ expect(findings.every((finding) => finding.disposition === 'observe')).toBe(true);+ });++ test('VFX-006 corpus covers every subtype and freezes the Studio rubric identities', () => {+ expect(new Set(VFX_BREADTH_CORPUS_V1.map((fixture) => fixture.intent.subtype))).toEqual(+ new Set([+ 'billboard',+ 'beam',+ 'trail',+ 'aura',+ 'portal',+ 'impact',+ 'volume-like',+ 'runtimeShader',+ ]),+ );+ expect(VFX_BENCH_RUBRIC_V1.criteria).toEqual([+ 'vfx.intent-readability',+ 'vfx.transparency',+ 'vfx.facing',+ 'vfx.temporal-policy',+ 'vfx.runtime-portability',+ ]);+ expect(VFX_BENCH_RUBRIC_V1.deterministicEvidenceIsDelegatedDecision).toBe(false);+ });++ test('VFX prompt is resolved to one subtype and preserves portable/sidecar truth', () => {+ const beam = VFX_BREADTH_CORPUS_V1.find((value) => value.id === 'vfx.beam.valid')!.intent;+ const portal = VFX_BREADTH_CORPUS_V1.find(+ (value) => value.id === 'vfx.tsl-sidecar.valid',+ )!.intent;+ const beamPrompt = renderVfxBreadthPrompt(beam);+ expect(beamPrompt).toContain('subtype=beam');+ expect(beamPrompt).toContain('direction=+X');+ expect(beamPrompt).toContain('standard glTF PBR only');+ expect(beamPrompt).not.toContain('runtimeShader');+ const sidecarPrompt = renderVfxBreadthPrompt(portal);+ expect(sidecarPrompt).toContain('nonportable TSL sidecar');+ expect(sidecarPrompt).toContain('kilnTimeSeconds');+ });++ test('MOD-001 blocks only an explicit modular contract failure and prompt names the exact sockets', () => {+ const kit = modularKit();+ expect(+ evaluateModularJoinQa(context('environment', { modularKit: kit, modularJoin: joined() })),+ ).toEqual([]);+ const findings = evaluateModularJoinQa(+ context('environment', { modularKit: kit, modularJoin: joined(0.02) }),+ );+ expect(findings.map((finding) => finding.code)).toEqual(+ expect.arrayContaining(['MOD_GRID_MISALIGNED', 'MOD_JOIN_OVERLAP']),+ );+ expect(findings.every((finding) => finding.disposition === 'block')).toBe(true);+ const prompt = renderModularKitPrompt(kit);+ expect(prompt).toContain('a/a.east');+ expect(prompt).toContain('b/b.west');+ expect(prompt).toContain('zero seam and zero overlap');+ });++ test('SCOPE-001 remains observe-only even for an explicit single-vs-cluster violation', () => {+ const scope: AssetScopeIntentV1 = { schemaVersion: 1, scope: 'single', explicit: true };+ const findings = evaluateAssetScopeQa(+ context('prop', {+ scope,+ scopeObservation: {+ topLevelAssetRoots: 3,+ reusableMemberCount: 2,+ sceneDressingRoles: ['terrain.disk'],+ },+ }),+ );+ expect(findings).toHaveLength(1);+ expect(findings[0]).toMatchObject({+ code: 'ASSET_SCOPE_EXPLICIT_SINGLE_CLUSTER',+ disposition: 'observe',+ dimension: 'promptAlignment',+ });+ expect(renderAssetScopePrompt(scope)).toContain('one reusable asset root');+ });++ test('REF-001 has no synchronous deterministic registry rule or automatic repair surface', () => {+ expect(W7_BREADTH_QA_RULES.map((rule) => rule.id)).toEqual([+ 'VFX_EXACT_PROFILE',+ 'VFX_ADVISORY_PROFILE',+ 'MODULAR_JOIN_PROFILE',+ 'ASSET_SCOPE_PROFILE',+ ]);+ expect(W7_BREADTH_QA_RULES.some((rule) => /REF|REFERENCE/.test(rule.id))).toBe(false);+ const registry = new QaRegistry(W7_BREADTH_QA_RULES);+ const fixture = VFX_BREADTH_CORPUS_V1.find(+ (value) => value.id === 'vfx.billboard-smoke.valid',+ )!;+ const result = registry.run(context('vfx', { vfx: fixture.intent }, fixture.evidence));+ expect(result.decisions.map((decision) => [decision.ruleId, decision.mode])).toEqual([+ ['VFX_EXACT_PROFILE', 'enforce'],+ ['VFX_ADVISORY_PROFILE', 'observe'],+ ['MODULAR_JOIN_PROFILE', 'enforce'],+ ['ASSET_SCOPE_PROFILE', 'observe'],+ ]);+ });++ test('missing trusted VFX contract is a request-normalization blocker, not model repair evidence', () => {+ const valid = context('vfx', {});+ const findings = evaluateVfxExactQa({+ ...valid,+ intent: { ...valid.intent, vfx: undefined } as unknown as AssetIntentV1,+ });+ expect(findings[0]).toMatchObject({ code: 'VFX_INTENT_INVALID', disposition: 'block' });+ expect(findings[0]?.repairText).toContain('cannot repair trusted intent');+ });+});diff --git a/src/qa/breadth-corpus.ts b/src/qa/breadth-corpus.tsnew file mode 100644index 00000000..b6a5eb93--- /dev/null+++ b/src/qa/breadth-corpus.ts@@ -0,0 +1,168 @@+import type { VfxIntentV1 } from '../contracts/breadth';+import type { VfxArtifactEvidenceV1 } from './breadth';++export interface VfxBreadthCorpusFixtureV1 {+ id: string;+ intent: VfxIntentV1;+ evidence: VfxArtifactEvidenceV1;+ expectedExactCodes: string[];+}++const material = (+ id: string,+ alphaMode: 'opaque' | 'mask' | 'blend' = 'blend',+ overrides: Partial<VfxArtifactEvidenceV1['materials'][number]> = {},+): VfxArtifactEvidenceV1['materials'][number] => ({+ id,+ surfaceRole: 'card',+ alphaMode,+ alphaData: alphaMode !== 'opaque',+ doubleSided: true,+ ...(alphaMode === 'mask' ? { alphaCutoff: 0.45 } : {}),+ screenAreaRatio: 0.24,+ transparentLayers: alphaMode === 'blend' ? 2 : 0,+ textureMemoryBytes: 1_048_576,+ ...overrides,+});++const intent = (+ subtype: VfxIntentV1['subtype'],+ overrides: Partial<VfxIntentV1> = {},+): VfxIntentV1 => ({+ schemaVersion: 1,+ subtype,+ portability: 'portable',+ transparency: 'blend',+ doubleSided: true,+ facing: {+ source: 'explicit',+ mode: subtype === 'billboard' ? 'camera-y-axis' : 'fixed',+ normalAxis: '+X',+ ...((subtype === 'beam' || subtype === 'trail') && { directionAxis: '+X' as const }),+ },+ animation: {+ playback: 'loop',+ durationSeconds: 1,+ endpointBehavior: 'matchStart',+ driver: 'clip',+ clipName: `${subtype}.loop`,+ },+ ...overrides,+});++const evidence = (+ requested: VfxIntentV1,+ overrides: Partial<VfxArtifactEvidenceV1> = {},+): VfxArtifactEvidenceV1 => ({+ schemaVersion: 1,+ facing: { ...requested.facing },+ animation: { ...requested.animation, endpointMatches: true },+ ...(requested.sidecar ? { sidecar: { ...requested.sidecar } } : {}),+ materials: [material(`${requested.subtype}.material`, requested.transparency)],+ clips:+ requested.animation.driver === 'clip'+ ? [+ {+ name: requested.animation.clipName!,+ durationSeconds: requested.animation.durationSeconds,+ },+ ]+ : [],+ uniforms:+ requested.animation.driver === 'timeUniform' ? [requested.animation.timeUniformName!] : [],+ ...overrides,+});++const fixture = (+ id: string,+ requested: VfxIntentV1,+ overrides: Partial<VfxArtifactEvidenceV1> = {},+ expectedExactCodes: string[] = [],+): VfxBreadthCorpusFixtureV1 => ({+ id,+ intent: requested,+ evidence: evidence(requested, overrides),+ expectedExactCodes,+});++const billboardSmoke = intent('billboard');+const beam = intent('beam');+const trail = intent('trail');+const portal = intent('portal');+const impact = intent('impact', {+ animation: {+ playback: 'oneShot',+ durationSeconds: 0.35,+ endpointBehavior: 'disappear',+ driver: 'clip',+ clipName: 'impact.burst',+ },+});+const aura = intent('aura');+const volume = intent('volume-like', {+ transparency: 'mask',+ animation: { playback: 'static', durationSeconds: 0, endpointBehavior: 'none', driver: 'none' },+});+const runtimeShader = intent('runtimeShader', {+ portability: 'sidecar',+ sidecar: { kind: 'tsl', id: 'kiln.vfx.energy-portal.tsl.v1', version: '1.0.0' },+ animation: {+ playback: 'loop',+ durationSeconds: 1.5,+ endpointBehavior: 'matchStart',+ driver: 'timeUniform',+ timeUniformName: 'kilnTimeSeconds',+ },+});++/** Fixed, no-provider VFX corpus spanning every approved subtype and primary failure class. */+export const VFX_BREADTH_CORPUS_V1: readonly VfxBreadthCorpusFixtureV1[] = Object.freeze([+ fixture('vfx.billboard-smoke.valid', billboardSmoke),+ fixture('vfx.beam.valid', beam),+ fixture('vfx.trail.valid', trail),+ fixture('vfx.portal.valid', portal),+ fixture('vfx.impact.valid', impact),+ fixture('vfx.aura.valid', aura),+ fixture('vfx.volume.valid', volume),+ fixture('vfx.tsl-sidecar.valid', runtimeShader),+ fixture(+ 'vfx.billboard-smoke.opaque-card',+ billboardSmoke,+ { materials: [material('smoke.card', 'opaque', { alphaData: false })] },+ ['VFX_TRANSPARENCY_MODE_MISMATCH', 'VFX_ALPHA_DATA_MISSING'],+ ),+ fixture('vfx.beam.wrong-direction', beam, { facing: { ...beam.facing, directionAxis: '-X' } }, [+ 'VFX_FACING_CONTRACT_MISMATCH',+ ]),+ fixture(+ 'vfx.portal.open-loop',+ portal,+ { animation: { ...portal.animation, endpointMatches: false } },+ ['VFX_LOOP_ENDPOINT_MISMATCH'],+ ),+ fixture('vfx.tsl-sidecar.missing-time-uniform', runtimeShader, { uniforms: [] }, [+ 'VFX_REQUIRED_TIME_UNIFORM_MISSING',+ ]),+]);++export const VFX_BENCH_RUBRIC_V1 = Object.freeze({+ schemaVersion: 1 as const,+ category: 'vfx' as const,+ deterministicEvidenceIsDelegatedDecision: false as const,+ criteria: [+ 'vfx.intent-readability',+ 'vfx.transparency',+ 'vfx.facing',+ 'vfx.temporal-policy',+ 'vfx.runtime-portability',+ ] as const,+ requiredFixtures: [+ 'vfx.billboard-smoke.valid',+ 'vfx.beam.valid',+ 'vfx.trail.valid',+ 'vfx.portal.valid',+ 'vfx.impact.valid',+ 'vfx.aura.valid',+ 'vfx.tsl-sidecar.valid',+ ] as const,+});diff --git a/src/qa/breadth-evidence.test.ts b/src/qa/breadth-evidence.test.tsnew file mode 100644index 00000000..2161d41d--- /dev/null+++ b/src/qa/breadth-evidence.test.ts@@ -0,0 +1,412 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import { createAssetIntentV1, stampSemanticMetadataV1 } from '../contracts';+import { renderSceneToGLB } from '../render';+import {+ analyzeAssetScopeObservationV1,+ analyzeModularEvidenceV1,+ analyzeVfxArtifactEvidenceV1,+} from './breadth-evidence';+import { analyzeFinalVfxGlbBytesV1 } from './breadth-final';+import { AssetQaBlockedError, DETERMINISTIC_QA_REGISTRY, runDeterministicSceneQa } from './run';++function vfxScene(material: THREE.Material, actualCameraFacing = true): THREE.Group {+ const root = new THREE.Group();+ root.name = 'SmokeBillboard';+ const card = actualCameraFacing+ ? new THREE.Sprite(material as THREE.SpriteMaterial)+ : new THREE.Mesh(new THREE.PlaneGeometry(1, 1), material);+ card.name = 'SmokeCard';+ stampSemanticMetadataV1(card, {+ roles: ['vfx.effect.surface.card', 'vfx.facing.camera-y-axis', 'vfx.normal.+x'],+ });+ root.add(card);+ // A self-report must never override analyzed materials/clips.+ root.userData.kilnVfxEvidence = {+ schemaVersion: 1,+ materials: [{ id: 'forged', alphaMode: 'opaque', alphaData: false }],+ };+ return root;+}++function loopClip(end = 0): THREE.AnimationClip {+ return new THREE.AnimationClip('SmokeLoop', 1, [+ new THREE.NumberKeyframeTrack('SmokeCard.scale[x]', [0, 0.5, 1], [0, 1, end]),+ ]);+}++function exportableLoopClip(): THREE.AnimationClip {+ return new THREE.AnimationClip('SmokeLoop', 1, [+ new THREE.VectorKeyframeTrack(+ 'SmokeCard.scale',+ [0, 0.5, 1],+ [1, 1, 1, 1.25, 1.25, 1.25, 1, 1, 1],+ ),+ ]);+}++function addOpaqueEmitterSupport(root: THREE.Group): void {+ const support = new THREE.Mesh(+ new THREE.CylinderGeometry(0.15, 0.2, 0.4, 8),+ new THREE.MeshStandardMaterial({ color: '#333333' }),+ );+ support.name = 'EmitterSupport';+ support.material.name = 'OpaqueEmitter';+ stampSemanticMetadataV1(support, { roles: ['vfx.support.emitter'] });+ root.add(support);+}++function vfxIntent() {+ return createAssetIntentV1({+ category: 'vfx',+ subtype: 'billboard',+ vfx: {+ transparency: 'blend',+ doubleSided: true,+ facing: { source: 'explicit', mode: 'camera-spherical', normalAxis: '+X' },+ animation: {+ playback: 'loop',+ durationSeconds: 1,+ endpointBehavior: 'matchStart',+ driver: 'clip',+ clipName: 'SmokeLoop',+ },+ },+ });+}++function modularScene(offset = 0): THREE.Group {+ const root = new THREE.Group();+ root.name = 'WallKit';+ root.userData.kilnModularGrid = [99, 99, 99];+ const material = new THREE.MeshStandardMaterial({ color: '#888888' });+ const pieceA = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 0.2), material);+ pieceA.name = 'WallA';+ stampSemanticMetadataV1(pieceA, {+ roles: ['modular.piece.a'],+ frames: [{ id: 'socket.east', translation: [1, 0, 0], rotation: [0, 0, 0, 1] }],+ sockets: [+ {+ id: 'wall-a.east',+ type: 'wall.edge.east',+ frame: 'socket.east',+ compatibleTypes: ['wall.edge.west'],+ allowedRotationsDegrees: [0, 90, 180, 270],+ },+ ],+ });+ const pieceB = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 0.2), material);+ pieceB.name = 'WallB';+ pieceB.position.x = 2 + offset;+ stampSemanticMetadataV1(pieceB, {+ roles: ['modular.piece.b'],+ frames: [{ id: 'socket.west', translation: [-1, 0, 0], rotation: [0, 1, 0, 0] }],+ sockets: [+ {+ id: 'wall-b.west',+ type: 'wall.edge.west',+ frame: 'socket.west',+ compatibleTypes: ['wall.edge.east'],+ allowedRotationsDegrees: [0, 90, 180, 270],+ },+ ],+ });+ root.add(pieceA, pieceB);+ return root;+}++describe('W7 engine-derived QA evidence', () => {+ test('VFX exact evidence comes from actual materials and clips, never scene self-report', () => {+ const material = new THREE.SpriteMaterial({+ color: '#aabbcc',+ transparent: true,+ opacity: 0.5,+ });+ material.side = THREE.DoubleSide;+ material.name = 'SmokeBlend';+ const root = vfxScene(material);+ const clip = loopClip();+ const evidence = analyzeVfxArtifactEvidenceV1(vfxIntent().vfx!, root, [clip]);+ expect(evidence.materials).toEqual([+ expect.objectContaining({+ id: 'SmokeBlend',+ alphaMode: 'blend',+ alphaData: true,+ doubleSided: true,+ }),+ ]);+ expect(evidence.clips).toEqual([{ name: 'SmokeLoop', durationSeconds: 1 }]);+ expect(evidence.animation).toMatchObject({+ playback: 'loop',+ driver: 'clip',+ endpointMatches: true,+ });+ const report = runDeterministicSceneQa({ intent: vfxIntent(), scene: root, clips: [clip] });+ expect(report.disposition).not.toBe('block');+ expect(+ Object.values(report.dimensions)+ .flatMap((dimension) => dimension.findings)+ .map((finding) => finding.code),+ ).not.toContain('VFX_TRANSPARENCY_MODE_MISMATCH');+ });++ test('actual opaque material and non-loop clip block despite forged passing metadata', () => {+ const material = new THREE.MeshStandardMaterial({+ color: '#ffffff',+ side: THREE.FrontSide,+ });+ const report = runDeterministicSceneQa({+ intent: vfxIntent(),+ scene: vfxScene(material, false),+ clips: [loopClip(2)],+ });+ const codes = Object.values(report.dimensions)+ .flatMap((dimension) => dimension.findings)+ .map((finding) => finding.code);+ expect(report.disposition).toBe('block');+ expect(codes).toEqual(+ expect.arrayContaining([+ 'VFX_TRANSPARENCY_MODE_MISMATCH',+ 'VFX_ALPHA_DATA_MISSING',+ 'VFX_SIDEDNESS_MISMATCH',+ 'VFX_ANIMATION_POLICY_MISMATCH',+ 'VFX_LOOP_ENDPOINT_MISMATCH',+ ]),+ );+ });++ test('scope observation is derived from real members and dressing nodes', () => {+ const root = modularScene();+ const dressing = new THREE.Mesh(+ new THREE.BoxGeometry(4, 0.1, 4),+ new THREE.MeshStandardMaterial(),+ );+ dressing.name = 'DioramaDisplayPlate';+ root.add(dressing);+ expect(analyzeAssetScopeObservationV1(root)).toEqual({+ topLevelAssetRoots: 2,+ reusableMemberCount: 2,+ sceneDressingRoles: ['name:DioramaDisplayPlate'],+ });+ const report = runDeterministicSceneQa({+ intent: createAssetIntentV1({+ category: 'prop',+ scope: { scope: 'single', explicit: true },+ }),+ scene: root,+ });+ const finding = report.dimensions.promptAlignment.findings.find((value) =>+ value.code.startsWith('ASSET_SCOPE_'),+ );+ expect(finding).toMatchObject({+ code: 'ASSET_SCOPE_EXPLICIT_SINGLE_CLUSTER',+ disposition: 'observe',+ });+ });++ test('MOD-001 consumes actual semantic socket/grid measurements in the production registry', () => {+ const intent = createAssetIntentV1({+ category: 'environment',+ subtype: 'modular-wall',+ scope: { scope: 'modularSet', explicit: true },+ });+ const analyzed = analyzeModularEvidenceV1(modularScene(), intent.modular!.grid);+ expect(analyzed.kit).toMatchObject({ schemaVersion: 1, units: 'm', grid: [1, 1, 1] });+ expect(analyzed.join).toMatchObject({+ aSocketId: 'wall-a.east',+ bSocketId: 'wall-b.west',+ aWorldPosition: [1, 0, 0],+ bWorldPosition: [1, 0, 0],+ });+ expect(runDeterministicSceneQa({ intent, scene: modularScene() }).disposition).not.toBe(+ 'block',+ );+ const failed = runDeterministicSceneQa({ intent, scene: modularScene(0.1) });+ const codes = Object.values(failed.dimensions)+ .flatMap((dimension) => dimension.findings)+ .map((finding) => finding.code);+ expect(failed.disposition).toBe('block');+ expect(codes).toEqual(expect.arrayContaining(['MOD_GRID_MISALIGNED', 'MOD_JOIN_SEAM']));+ });++ test('fake sidecar/userData and semantic facing roles cannot satisfy exact VFX evidence', () => {+ const material = new THREE.ShaderMaterial({+ transparent: true,+ side: THREE.DoubleSide,+ uniforms: { kilnTimeSeconds: { value: 0 } },+ });+ material.opacity = 0.5;+ material.userData.kilnVfxSidecar = {+ kind: 'tsl',+ id: 'kiln.vfx.runtime-shader.tsl.v1',+ version: '1.0.0',+ };+ material.userData.kilnVfxDurationSeconds = 1;+ material.userData.kilnVfxEndpointMatches = true;+ const root = vfxScene(material, false);+ root.userData.kilnVfxSidecar = material.userData.kilnVfxSidecar;+ const intent = createAssetIntentV1({ category: 'vfx', subtype: 'runtimeShader' });+ const evidence = analyzeVfxArtifactEvidenceV1(intent.vfx!, root, []);+ expect(evidence.sidecar).toBeUndefined();+ expect(evidence.facing.mode).toBe('fixed');+ expect(evidence.animation).toMatchObject({ durationSeconds: 0, endpointMatches: false });+ const report = runDeterministicSceneQa({ intent, scene: root });+ const codes = Object.values(report.dimensions)+ .flatMap((dimension) => dimension.findings)+ .map((finding) => finding.code);+ expect(codes).toContain('VFX_SIDECAR_IDENTITY_MISMATCH');+ });++ test('dedicated alphaMap is actual alpha evidence even without raw RGBA pixels', () => {+ const material = new THREE.SpriteMaterial({ transparent: true, opacity: 1 });+ material.side = THREE.DoubleSide;+ material.alphaMap = new THREE.Texture({ width: 2, height: 2 });+ const evidence = analyzeVfxArtifactEvidenceV1(vfxIntent().vfx!, vfxScene(material), [+ loopClip(),+ ]);+ expect(evidence.materials[0]).toMatchObject({ alphaMode: 'blend', alphaData: true });+ });++ test('render path exports Sprite as a semantic quad and re-proves exact final-byte parity', async () => {+ const material = new THREE.SpriteMaterial({+ color: '#aabbcc',+ transparent: true,+ opacity: 0.5,+ });+ material.side = THREE.DoubleSide;+ material.name = 'SmokeBlend';+ const clip = exportableLoopClip();+ const root = vfxScene(material);+ addOpaqueEmitterSupport(root);+ const sceneEvidence = analyzeVfxArtifactEvidenceV1(vfxIntent().vfx!, root, [clip]);+ expect(sceneEvidence.materials).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: 'SmokeBlend', effectSurface: true, alphaMode: 'blend' }),+ expect.objectContaining({ id: 'OpaqueEmitter', effectSurface: false, alphaMode: 'opaque' }),+ ]),+ );+ expect(+ runDeterministicSceneQa({ intent: vfxIntent(), scene: root, clips: [clip] }).disposition,+ ).not.toBe('block');+ const rendered = await renderSceneToGLB(root, {+ intent: vfxIntent(),+ clips: [clip],+ });+ const finalEvidence = await analyzeFinalVfxGlbBytesV1(rendered.bytes);+ expect(rendered.tris).toBe(finalEvidence.triangleCount);+ expect(finalEvidence).toMatchObject({+ facingSemantics: ['camera-spherical'],+ clips: [{ name: 'SmokeLoop', durationSeconds: 1 }],+ });+ expect(finalEvidence.meshCount).toBe(2);+ expect(finalEvidence.primitiveCount).toBe(2);+ expect(finalEvidence.triangleCount).toBeGreaterThan(2);+ expect(finalEvidence.materials).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: 'SmokeBlend',+ effectSurface: true,+ alphaMode: 'blend',+ alphaData: true,+ doubleSided: true,+ }),+ expect.objectContaining({+ id: 'OpaqueEmitter',+ effectSurface: false,+ alphaMode: 'opaque',+ }),+ ]),+ );+ expect(rendered.qaReport.dimensions.exportIntegrity.metrics).toMatchObject({+ finalVfxTriangles: finalEvidence.triangleCount,+ finalVfxFacingSemantics: 'camera-spherical',+ finalVfxClipCount: 1,+ finalVfxEffectMaterialCount: 1,+ });+ });++ test('final-byte QA blocks a standalone alphaMap that the GLB bridge cannot pack', async () => {+ const material = new THREE.SpriteMaterial({ transparent: true, opacity: 1 });+ material.side = THREE.DoubleSide;+ material.alphaMap = new THREE.Texture({ width: 2, height: 2 });+ try {+ await renderSceneToGLB(vfxScene(material), {+ intent: vfxIntent(),+ clips: [exportableLoopClip()],+ });+ throw new Error('expected final-byte VFX QA to block');+ } catch (error) {+ expect(error).toBeInstanceOf(AssetQaBlockedError);+ expect((error as AssetQaBlockedError).stage).toBe('final-glb');+ const codes = Object.values((error as AssetQaBlockedError).report.dimensions)+ .flatMap((dimension) => dimension.findings)+ .map((finding) => finding.code);+ expect(codes).toContain('VFX_GLTF_ALPHA_DATA_MISSING');+ }+ });++ test('final-byte VFX-003 remeasures an explicit beam normal and direction', async () => {+ const material = new THREE.MeshStandardMaterial({+ color: '#66ccff',+ transparent: true,+ opacity: 0.5,+ side: THREE.DoubleSide,+ });+ material.name = 'BeamBlend';+ const beam = new THREE.Mesh(new THREE.BoxGeometry(2, 0.1, 0.1), material);+ beam.name = 'BeamSurface';+ stampSemanticMetadataV1(beam, { roles: ['vfx.effect.surface.beam'] });+ const root = new THREE.Group();+ root.name = 'BeamRoot';+ root.add(beam);+ const intent = createAssetIntentV1({+ category: 'vfx',+ subtype: 'beam',+ vfx: {+ facing: {+ source: 'explicit',+ mode: 'fixed',+ normalAxis: '+Y',+ directionAxis: '+X',+ },+ },+ });+ const rendered = await renderSceneToGLB(root, { intent });+ const evidence = await analyzeFinalVfxGlbBytesV1(rendered.bytes);+ expect(evidence).toMatchObject({ normalAxis: '+Y', directionAxis: '+X' });+ expect(rendered.qaReport.disposition).not.toBe('block');+ expect(rendered.qaReport.dimensions.exportIntegrity.metrics).toMatchObject({+ finalVfxNormalAxis: '+Y',+ finalVfxDirectionAxis: '+X',+ });+ });++ test('inferred modular scope never enables exact MOD blockers', () => {+ const intent = createAssetIntentV1({ category: 'environment', subtype: 'modular-wall' });+ expect(intent.scope).toEqual({ schemaVersion: 1, scope: 'modularSet', explicit: false });+ const report = runDeterministicSceneQa({ intent, scene: modularScene(0.1) });+ const modularFindings = Object.values(report.dimensions)+ .flatMap((dimension) => dimension.findings)+ .filter((finding) => finding.code.startsWith('MOD_'));+ expect(modularFindings).toEqual([]);+ });++ test('registers prop, environment, VFX, modular, and scope production rules', () => {+ expect(DETERMINISTIC_QA_REGISTRY.list().map((rule) => rule.id)).toEqual(+ expect.arrayContaining([+ 'PROP_CAPABILITY_EXACT_PROFILE',+ 'PROP_ADVISORY_PROFILE',+ 'ENVIRONMENT_EXACT_PROFILE',+ 'ENVIRONMENT_ADVISORY_PROFILE',+ 'VFX_EXACT_PROFILE',+ 'VFX_ADVISORY_PROFILE',+ 'MODULAR_JOIN_PROFILE',+ 'ASSET_SCOPE_PROFILE',+ ]),+ );+ expect(DETERMINISTIC_QA_REGISTRY.list().some((rule) => /REF|REFERENCE/.test(rule.id))).toBe(+ false,+ );+ });+});diff --git a/src/qa/breadth-evidence.ts b/src/qa/breadth-evidence.tsnew file mode 100644index 00000000..3fbef04c--- /dev/null+++ b/src/qa/breadth-evidence.ts@@ -0,0 +1,573 @@+import * as THREE from 'three';++import {+ readSemanticMetadataV1,+ type AssetIntentV1,+ type AssetScopeObservationV1,+ type ModularJoinObservationV1,+ type ModularKitContractV1,+ type ModularSocketContractV1,+ type VfxAxisDirection,+ type VfxIntentV1,+} from '../contracts';+import type { VfxArtifactEvidenceV1, VfxMaterialEvidenceV1 } from './breadth';+import type { QaContext } from './types';++const stable = (value: number): number => Math.round(value * 1_000_000) / 1_000_000;++function record(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function isObject3D(value: unknown): value is THREE.Object3D {+ return record(value) && value.isObject3D === true && typeof value.traverse === 'function';+}++function isMeshNode(value: THREE.Object3D): value is THREE.Mesh {+ return (value as THREE.Object3D & { isMesh?: boolean }).isMesh === true;+}++function isSpriteNode(value: THREE.Object3D): value is THREE.Sprite {+ return (value as THREE.Object3D & { isSprite?: boolean }).isSprite === true;+}++function isTexture(value: unknown): value is THREE.Texture {+ return record(value) && value.isTexture === true;+}++function isAnimationClip(value: unknown): value is THREE.AnimationClip {+ return (+ record(value) &&+ typeof value.name === 'string' &&+ typeof value.duration === 'number' &&+ Number.isFinite(value.duration) &&+ Array.isArray(value.tracks)+ );+}++function localRenderableBox(+ rootInverse: THREE.Matrix4,+ node: THREE.Object3D,+): THREE.Box3 | undefined {+ if (isSpriteNode(node)) {+ const transform = rootInverse.clone().multiply(node.matrixWorld);+ return new THREE.Box3(+ new THREE.Vector3(-0.5, -0.5, -0.0005),+ new THREE.Vector3(0.5, 0.5, 0.0005),+ ).applyMatrix4(transform);+ }+ if (!isMeshNode(node) || !node.geometry?.isBufferGeometry) return undefined;+ node.geometry.computeBoundingBox();+ const source = node.geometry.boundingBox;+ if (!source || source.isEmpty()) return undefined;+ const transform = rootInverse.clone().multiply(node.matrixWorld);+ const result = new THREE.Box3();+ for (const x of [source.min.x, source.max.x]) {+ for (const y of [source.min.y, source.max.y]) {+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(transform));+ }+ }+ }+ return result;+}++function textureDimensions(texture: THREE.Texture): [number, number] | undefined {+ const image = texture.image as { width?: unknown; height?: unknown } | undefined;+ return image &&+ typeof image.width === 'number' &&+ Number.isFinite(image.width) &&+ image.width > 0 &&+ typeof image.height === 'number' &&+ Number.isFinite(image.height) &&+ image.height > 0+ ? [image.width, image.height]+ : undefined;+}++function textureHasAlpha(texture: THREE.Texture | null | undefined): boolean {+ if (!texture) return false;+ const image = texture.image as+ | { data?: ArrayLike<number>; width?: number; height?: number }+ | undefined;+ if (!image?.data || !image.width || !image.height) return false;+ const pixelCount = image.width * image.height;+ if (pixelCount <= 0 || image.data.length < pixelCount * 4) return false;+ for (let index = 3; index < pixelCount * 4; index += 4) {+ if ((image.data[index] ?? 255) < 255) return true;+ }+ return false;+}++function materialTextures(material: THREE.Material): THREE.Texture[] {+ const candidate = material as unknown as THREE.Material & Record<string, unknown>;+ const textures = new Set<THREE.Texture>();+ for (const key of [+ 'map',+ 'alphaMap',+ 'emissiveMap',+ 'normalMap',+ 'roughnessMap',+ 'metalnessMap',+ 'aoMap',+ ]) {+ const value = candidate[key];+ if (isTexture(value)) textures.add(value);+ }+ return [...textures];+}++function materialTextureBytes(material: THREE.Material): number {+ return materialTextures(material).reduce((sum, texture) => {+ const dimensions = textureDimensions(texture);+ return sum + (dimensions ? Math.ceil(dimensions[0] * dimensions[1] * 4 * (4 / 3)) : 0);+ }, 0);+}++function alphaMode(material: THREE.Material): 'opaque' | 'mask' | 'blend' {+ const standard = material as THREE.Material & {+ alphaTest?: number;+ transparent?: boolean;+ opacity?: number;+ alphaMap?: THREE.Texture | null;+ };+ if ((standard.alphaTest ?? 0) > 0) return 'mask';+ if (standard.transparent || (standard.opacity ?? 1) < 1 || standard.alphaMap) return 'blend';+ return 'opaque';+}++function alphaData(material: THREE.Material): boolean {+ const standard = material as THREE.Material & {+ alphaTest?: number;+ opacity?: number;+ alphaMap?: THREE.Texture | null;+ map?: THREE.Texture | null;+ };+ return (+ (standard.opacity ?? 1) < 1 ||+ (standard.alphaMap !== undefined && standard.alphaMap !== null) ||+ textureHasAlpha(standard.alphaMap) ||+ textureHasAlpha(standard.map) ||+ ((standard.alphaTest ?? 0) > 0 && standard.alphaMap !== undefined && standard.alphaMap !== null)+ );+}++function surfaceRole(+ nodes: readonly THREE.Object3D[],+ intent: VfxIntentV1,+): VfxMaterialEvidenceV1['surfaceRole'] {+ const evidence = nodes.flatMap((node) => [+ node.name,+ ...(readSemanticMetadataV1(node)?.roles ?? []),+ ]);+ if (evidence.some((value) => /(?:^|[._ -])beam(?:$|[._ -])/i.test(value))) return 'beam';+ if (evidence.some((value) => /(?:^|[._ -])trail(?:$|[._ -])/i.test(value))) return 'trail';+ if (evidence.some((value) => /(?:^|[._ -])(?:volume|aura|portal)(?:$|[._ -])/i.test(value))) {+ return 'volume';+ }+ if (intent.subtype === 'beam') return 'beam';+ if (intent.subtype === 'trail') return 'trail';+ if (+ intent.subtype === 'volume-like' ||+ intent.subtype === 'aura' ||+ intent.subtype === 'portal'+ ) {+ return 'volume';+ }+ return 'card';+}++const EFFECT_SURFACE_ROLE = /^vfx\.effect\.surface(?:\.|$)/;++function isEffectSurface(nodes: readonly THREE.Object3D[]): boolean {+ return nodes.some(+ (node) =>+ isSpriteNode(node) ||+ (readSemanticMetadataV1(node)?.roles ?? []).some((role) => EFFECT_SURFACE_ROLE.test(role)),+ );+}++function coverageRatio(boxes: readonly THREE.Box3[], overall: THREE.Box3): number {+ if (boxes.length === 0 || overall.isEmpty()) return 0;+ const overallSize = overall.getSize(new THREE.Vector3());+ const denominator = Math.max(+ 1e-9,+ overallSize.x * overallSize.y,+ overallSize.z * overallSize.y,+ overallSize.x * overallSize.z,+ );+ const area = boxes.reduce((sum, box) => {+ const size = box.getSize(new THREE.Vector3());+ return sum + Math.max(size.x * size.y, size.z * size.y, size.x * size.z);+ }, 0);+ return stable(Math.min(1, area / denominator));+}++function collectMaterialEvidence(+ root: THREE.Object3D,+ intent: VfxIntentV1,+): VfxMaterialEvidenceV1[] {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const byMaterial = new Map<THREE.Material, { nodes: THREE.Object3D[]; boxes: THREE.Box3[] }>();+ const overall = new THREE.Box3();+ root.traverse((node) => {+ const box = localRenderableBox(inverse, node);+ if (!box || (!isMeshNode(node) && !isSpriteNode(node))) return;+ overall.union(box);+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ for (const material of materials) {+ if (!material) continue;+ const value = byMaterial.get(material) ?? { nodes: [], boxes: [] };+ value.nodes.push(node);+ value.boxes.push(box);+ byMaterial.set(material, value);+ }+ });+ return [...byMaterial.entries()]+ .map(([material, value], index): VfxMaterialEvidenceV1 => {+ const mode = alphaMode(material);+ const standard = material as THREE.Material & { alphaTest?: number };+ return {+ id: material.name || `material.${index}`,+ surfaceRole: surfaceRole(value.nodes, intent),+ effectSurface: isEffectSurface(value.nodes),+ alphaMode: mode,+ alphaData: alphaData(material),+ doubleSided: material.side === THREE.DoubleSide,+ ...(mode === 'mask' ? { alphaCutoff: standard.alphaTest ?? 0 } : {}),+ screenAreaRatio: coverageRatio(value.boxes, overall),+ transparentLayers: mode === 'blend' ? value.nodes.length : 0,+ textureMemoryBytes: materialTextureBytes(material),+ };+ })+ .sort((a, b) => a.id.localeCompare(b.id));+}++function signedAxis(vector: THREE.Vector3): VfxAxisDirection {+ const values = [+ { axis: 'X', value: vector.x },+ { axis: 'Y', value: vector.y },+ { axis: 'Z', value: vector.z },+ ] as const;+ const dominant = [...values].sort((a, b) => Math.abs(b.value) - Math.abs(a.value))[0]!;+ return `${dominant.value < 0 ? '-' : '+'}${dominant.axis}` as VfxAxisDirection;+}++function dominantGeometryAxis(root: THREE.Object3D, mode: 'normal' | 'length'): VfxAxisDirection {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ let best: { score: number; direction: THREE.Vector3 } | undefined;+ root.traverse((node) => {+ if (!isMeshNode(node) || !node.geometry?.isBufferGeometry || !isEffectSurface([node])) return;+ node.geometry.computeBoundingBox();+ const bounds = node.geometry.boundingBox;+ if (!bounds || bounds.isEmpty()) return;+ const size = bounds.getSize(new THREE.Vector3());+ const axes = [+ { score: size.x, direction: new THREE.Vector3(1, 0, 0) },+ { score: size.y, direction: new THREE.Vector3(0, 1, 0) },+ { score: size.z, direction: new THREE.Vector3(0, 0, 1) },+ ];+ const selected = axes.reduce((candidate, value) =>+ mode === 'length'+ ? value.score > candidate.score+ ? value+ : candidate+ : value.score < candidate.score+ ? value+ : candidate,+ );+ const relative = inverse.clone().multiply(node.matrixWorld);+ const direction = selected.direction.transformDirection(relative);+ const score = selected.score * node.getWorldScale(new THREE.Vector3()).length();+ if (!best || (mode === 'length' ? score > best.score : score < best.score)) {+ best = { score, direction };+ }+ });+ if (best) return signedAxis(best.direction);++ const overall = new THREE.Box3();+ root.traverse((node) => {+ const box = localRenderableBox(inverse, node);+ if (box) overall.union(box);+ });+ if (overall.isEmpty()) return '+X';+ const size = overall.getSize(new THREE.Vector3());+ const vector =+ mode === 'length'+ ? size.x >= size.y && size.x >= size.z+ ? new THREE.Vector3(1, 0, 0)+ : size.y >= size.z+ ? new THREE.Vector3(0, 1, 0)+ : new THREE.Vector3(0, 0, 1)+ : size.x <= size.y && size.x <= size.z+ ? new THREE.Vector3(1, 0, 0)+ : size.y <= size.z+ ? new THREE.Vector3(0, 1, 0)+ : new THREE.Vector3(0, 0, 1);+ return signedAxis(vector);+}++function analyzedFacing(+ root: THREE.Object3D,+ intent: VfxIntentV1,+): VfxArtifactEvidenceV1['facing'] {+ let cameraFacing = false;+ root.traverse((node) => {+ if (isSpriteNode(node)) cameraFacing = true;+ });+ return {+ source: cameraFacing ? 'explicit' : 'inferred',+ mode: cameraFacing ? 'camera-spherical' : 'fixed',+ normalAxis: cameraFacing ? '+X' : dominantGeometryAxis(root, 'normal'),+ ...((intent.subtype === 'beam' || intent.subtype === 'trail') && {+ directionAxis: dominantGeometryAxis(root, 'length'),+ }),+ };+}++function clipEndpointMatches(clip: THREE.AnimationClip | undefined): boolean {+ if (!clip || clip.tracks.length === 0) return false;+ return clip.tracks.every((track) => {+ const stride = track.getValueSize();+ if (stride <= 0 || track.values.length < stride * 2) return false;+ for (let index = 0; index < stride; index++) {+ const first = Number(track.values[index]);+ const last = Number(track.values[track.values.length - stride + index]);+ if (!Number.isFinite(first) || !Number.isFinite(last) || Math.abs(first - last) > 1e-6) {+ return false;+ }+ }+ return true;+ });+}++function shaderMaterials(root: THREE.Object3D): THREE.Material[] {+ const values = new Set<THREE.Material>();+ root.traverse((node) => {+ if (!isMeshNode(node) && !isSpriteNode(node)) return;+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ for (const material of materials) {+ if (+ (material as THREE.Material & { isShaderMaterial?: boolean }).isShaderMaterial ||+ (material as THREE.Material & { isNodeMaterial?: boolean }).isNodeMaterial+ ) {+ values.add(material);+ }+ }+ });+ return [...values];+}++function shaderUniforms(materials: readonly THREE.Material[]): string[] {+ const values = new Set<string>();+ for (const material of materials) {+ const uniforms = (material as THREE.ShaderMaterial).uniforms;+ if (record(uniforms)) for (const key of Object.keys(uniforms)) values.add(key);+ }+ return [...values].sort();+}++/** Build the exact VFX evidence from actual scene materials and AnimationClip objects. */+export function analyzeVfxArtifactEvidenceV1(+ intent: VfxIntentV1,+ root: THREE.Object3D,+ clips: readonly unknown[] = [],+): VfxArtifactEvidenceV1 {+ const actualClips = clips.filter(isAnimationClip);+ const selectedClip =+ actualClips.find((clip) => clip.name === intent.animation.clipName) ?? actualClips[0];+ const shaders = shaderMaterials(root);+ const uniforms = shaderUniforms(shaders);+ const actualDriver = selectedClip ? 'clip' : uniforms.length > 0 ? 'timeUniform' : 'none';+ const endpointMatches = selectedClip ? clipEndpointMatches(selectedClip) : false;+ const playback =+ actualDriver === 'none'+ ? 'static'+ : actualDriver === 'clip'+ ? endpointMatches+ ? 'loop'+ : 'oneShot'+ : endpointMatches+ ? 'loop'+ : 'oneShot';+ const durationSeconds = selectedClip?.duration ?? 0;+ return {+ schemaVersion: 1,+ facing: analyzedFacing(root, intent),+ animation: {+ playback,+ durationSeconds: stable(durationSeconds),+ endpointBehavior:+ playback === 'static' ? 'none' : playback === 'loop' ? 'matchStart' : 'holdLast',+ driver: actualDriver,+ ...(selectedClip ? { clipName: selectedClip.name } : {}),+ ...(actualDriver === 'timeUniform' && intent.animation.timeUniformName+ ? { timeUniformName: intent.animation.timeUniformName }+ : {}),+ endpointMatches,+ },+ materials: collectMaterialEvidence(root, intent),+ clips: actualClips.map((clip) => ({ name: clip.name, durationSeconds: stable(clip.duration) })),+ uniforms,+ };+}++const MEMBER_ROLE = /^(?:asset|scope|cluster|modular)\.member(?:\.|$)|^modular\.piece(?:\.|$)/;+const DRESSING_ROLE = /^(?:scene\.dressing|scope\.extra|environment\.dressing)(?:\.|$)/;+const DRESSING_NAME = /(?:diorama|display[-_ ]?plate|terrain[-_ ]?base|backdrop)/i;++/** SCOPE-001 artifact evidence is derived from the actual scene graph. */+export function analyzeAssetScopeObservationV1(root: THREE.Object3D): AssetScopeObservationV1 {+ let renderableCount = 0;+ const members = new Set<THREE.Object3D>();+ const dressing = new Set<string>();+ root.traverse((node) => {+ if ((isMeshNode(node) || isSpriteNode(node)) && node.visible) renderableCount++;+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ if (roles.some((role) => MEMBER_ROLE.test(role))) members.add(node);+ for (const role of roles) if (DRESSING_ROLE.test(role)) dressing.add(role);+ if (node !== root && DRESSING_NAME.test(node.name)) dressing.add(`name:${node.name}`);+ });+ const memberCount = members.size > 0 ? members.size : renderableCount > 0 ? 1 : 0;+ return {+ topLevelAssetRoots: memberCount,+ reusableMemberCount: memberCount,+ sceneDressingRoles: [...dressing].sort(),+ };+}++interface AnalyzedSocket {+ contract: ModularSocketContractV1;+ worldPosition: [number, number, number];+ worldNormal: [number, number, number];+ worldRotation: THREE.Quaternion;+}++function pathOf(root: THREE.Object3D, node: THREE.Object3D): string {+ const values: string[] = [];+ let cursor: THREE.Object3D | null = node;+ while (cursor) {+ values.push(cursor.name || cursor.type);+ if (cursor === root) break;+ cursor = cursor.parent;+ }+ return values.reverse().join('/');+}++function analyzeSockets(root: THREE.Object3D): AnalyzedSocket[] {+ root.updateWorldMatrix(true, true);+ const rootInverse = root.matrixWorld.clone().invert();+ const rootWorldRotation = root.getWorldQuaternion(new THREE.Quaternion()).invert();+ const values: AnalyzedSocket[] = [];+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ if (!metadata) return;+ const nodeWorldRotation = node.getWorldQuaternion(new THREE.Quaternion());+ for (const socket of metadata.sockets) {+ const frame = metadata.frames.find((candidate) => candidate.id === socket.frame);+ if (!frame) continue;+ const frameRotation = new THREE.Quaternion(...frame.rotation);+ const worldRotation = rootWorldRotation+ .clone()+ .multiply(nodeWorldRotation)+ .multiply(frameRotation);+ const position = new THREE.Vector3(...frame.translation)+ .applyMatrix4(node.matrixWorld)+ .applyMatrix4(rootInverse);+ const normal = new THREE.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();+ values.push({+ contract: {+ id: socket.id,+ pieceId: pathOf(root, node),+ type: socket.type,+ compatibleTypes: [...socket.compatibleTypes],+ frame: {+ translation: [...frame.translation],+ rotation: [...frame.rotation],+ },+ allowedRotationsDegrees: [...(socket.allowedRotationsDegrees ?? [])],+ },+ worldPosition: [stable(position.x), stable(position.y), stable(position.z)],+ worldNormal: [stable(normal.x), stable(normal.y), stable(normal.z)],+ worldRotation,+ });+ }+ });+ return values.sort((a, b) => a.contract.id.localeCompare(b.contract.id));+}++/** Analyze the first reciprocal cross-piece socket pair from the actual scene. */+export function analyzeModularEvidenceV1(+ root: THREE.Object3D,+ trustedGrid: readonly [number, number, number],+): {+ kit?: ModularKitContractV1;+ join?: ModularJoinObservationV1;+} {+ const sockets = analyzeSockets(root);+ const kit = {+ schemaVersion: 1 as const,+ units: 'm' as const,+ grid: [trustedGrid[0], trustedGrid[1], trustedGrid[2]] as [number, number, number],+ sockets: sockets.map((value) => value.contract),+ };+ const pair = sockets+ .flatMap((a, index) => sockets.slice(index + 1).map((b) => [a, b] as const))+ .find(+ ([a, b]) =>+ a.contract.pieceId !== b.contract.pieceId &&+ a.contract.compatibleTypes.includes(b.contract.type) &&+ b.contract.compatibleTypes.includes(a.contract.type),+ );+ if (!pair) return { kit };+ const relative = pair[0].worldRotation.clone().invert().multiply(pair[1].worldRotation);+ const euler = new THREE.Euler().setFromQuaternion(relative, 'YXZ');+ const rotation = THREE.MathUtils.euclideanModulo(THREE.MathUtils.radToDeg(euler.y), 360);+ return {+ kit,+ join: {+ aSocketId: pair[0].contract.id,+ bSocketId: pair[1].contract.id,+ aWorldPosition: pair[0].worldPosition,+ bWorldPosition: pair[1].worldPosition,+ aWorldNormal: pair[0].worldNormal,+ bWorldNormal: pair[1].worldNormal,+ relativeRotationDegrees: stable(rotation),+ },+ };+}++/** Trusted seam populated by runDeterministicSceneQa before registry evaluation. */+export function deriveW7BreadthEvidence(context: QaContext): QaContext['derivedEvidence'] {+ if (!isObject3D(context.scene)) return context.derivedEvidence;+ const derived: NonNullable<QaContext['derivedEvidence']> = {+ source: 'engine-scene-analysis',+ assetScope: analyzeAssetScopeObservationV1(context.scene),+ };+ if (context.intent.category === 'vfx' && context.intent.vfx) {+ derived.vfxArtifact = analyzeVfxArtifactEvidenceV1(+ context.intent.vfx,+ context.scene,+ context.clips,+ );+ }+ if (context.intent.scope.scope === 'modularSet') {+ const modular = analyzeModularEvidenceV1(+ context.scene,+ context.intent.modular?.grid ?? [1, 1, 1],+ );+ if (modular.kit) derived.modularKit = modular.kit;+ if (modular.join) derived.modularJoin = modular.join;+ }+ return derived;+}++export function withDerivedW7BreadthEvidence(context: QaContext): QaContext {+ const derivedEvidence = deriveW7BreadthEvidence(context);+ return derivedEvidence ? { ...context, derivedEvidence } : context;+}++/** Compile-time guard that keeps analyzer input on the canonical trusted intent. */+export function assertW7EvidenceIntent(_intent: AssetIntentV1): void {}diff --git a/src/qa/breadth-final.ts b/src/qa/breadth-final.tsnew file mode 100644index 00000000..446ea088--- /dev/null+++ b/src/qa/breadth-final.ts@@ -0,0 +1,439 @@+import { WebIO } from '@gltf-transform/core';+import { EXTMeshGPUInstancing } from '@gltf-transform/extensions';+import * as THREE from 'three';++import {+ readSemanticMetadataV1FromExtras,+ type AssetIntentV1,+ type VfxAxisDirection,+ type VfxFacingMode,+ type VfxTransparencyMode,+} from '../contracts';+import { createAssetQaReportV1, type AssetQaReportV1, type QaFinding } from './types';++export interface FinalVfxMaterialEvidenceV1 {+ id: string;+ effectSurface: boolean;+ alphaMode: VfxTransparencyMode;+ alphaData: boolean;+ doubleSided: boolean;+ alphaCutoff?: number;+}++export interface FinalVfxGlbEvidenceV1 {+ schemaVersion: 1;+ meshCount: number;+ primitiveCount: number;+ triangleCount: number;+ materials: FinalVfxMaterialEvidenceV1[];+ facingSemantics: VfxFacingMode[];+ normalAxis?: VfxAxisDirection;+ directionAxis?: VfxAxisDirection;+ clips: Array<{ name: string; durationSeconds: number }>;+}++const stable = (value: number): number => Math.round(value * 1_000_000) / 1_000_000;++function bytesContainAscii(bytes: Uint8Array, value: string): boolean {+ const needle = new TextEncoder().encode(value);+ outer: for (let index = 0; index <= bytes.length - needle.length; index++) {+ for (let offset = 0; offset < needle.length; offset++) {+ if (bytes[index + offset] !== needle[offset]) continue outer;+ }+ return true;+ }+ return false;+}++/** Inspect alpha-bearing structure in the exact embedded final-byte image. */+function encodedTextureHasAlpha(mimeType: string, bytes: Uint8Array): boolean {+ if (mimeType === 'image/png') {+ // PNG IHDR color type: 4/6 carry alpha directly; tRNS adds it to+ // grayscale/RGB/indexed images. Byte 25 is stable after the 8-byte+ // signature + IHDR length/type + width/height/bit-depth fields.+ const colorType = bytes[25];+ return colorType === 4 || colorType === 6 || bytesContainAscii(bytes, 'tRNS');+ }+ if (mimeType === 'image/webp') {+ // Lossless/extended WebP signals alpha with ALPH or the VP8X alpha flag.+ if (bytesContainAscii(bytes, 'ALPH')) return true;+ const vp8xIndex = (() => {+ const marker = new TextEncoder().encode('VP8X');+ for (let index = 0; index <= bytes.length - marker.length; index++) {+ if (marker.every((value, offset) => bytes[index + offset] === value)) return index;+ }+ return -1;+ })();+ return vp8xIndex >= 0 && ((bytes[vp8xIndex + 8] ?? 0) & 0x10) !== 0;+ }+ return false;+}++function animationDuration(animation: import('@gltf-transform/core').Animation): number {+ let duration = 0;+ for (const sampler of animation.listSamplers()) {+ const max = sampler.getInput()?.getMax([]);+ if (max && typeof max[0] === 'number' && Number.isFinite(max[0])) {+ duration = Math.max(duration, max[0]);+ }+ }+ return stable(duration);+}++function signedAxis(vector: THREE.Vector3): VfxAxisDirection {+ const values = [+ { axis: 'X', value: vector.x },+ { axis: 'Y', value: vector.y },+ { axis: 'Z', value: vector.z },+ ] as const;+ const dominant = [...values].sort((a, b) => Math.abs(b.value) - Math.abs(a.value))[0]!;+ return `${dominant.value < 0 ? '-' : '+'}${dominant.axis}` as VfxAxisDirection;+}++function finalEffectAxis(+ nodes: readonly import('@gltf-transform/core').Node[],+ mode: 'normal' | 'length',+): VfxAxisDirection | undefined {+ let best: { score: number; direction: THREE.Vector3 } | undefined;+ for (const node of nodes) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ continue;+ }+ const matrix = new THREE.Matrix4().fromArray(node.getWorldMatrix());+ const scale = node.getWorldScale();+ const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {+ const position = primitive.getAttribute('POSITION');+ if (!position) continue;+ const min = position.getMin([]);+ const max = position.getMax([]);+ const axes = [+ { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE.Vector3(1, 0, 0) },+ { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE.Vector3(0, 1, 0) },+ { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE.Vector3(0, 0, 1) },+ ];+ const selected = axes.reduce((candidate, value) =>+ mode === 'length'+ ? value.score > candidate.score+ ? value+ : candidate+ : value.score < candidate.score+ ? value+ : candidate,+ );+ const candidate = {+ score: selected.score * scaleMagnitude,+ direction: selected.direction.transformDirection(matrix),+ };+ if (+ !best ||+ (mode === 'length' ? candidate.score > best.score : candidate.score < best.score)+ ) {+ best = candidate;+ }+ }+ }+ return best ? signedAxis(best.direction) : undefined;+}++/**+ * Re-open the exact serialized GLB bytes and derive VFX evidence from resources+ * that survived bridge + dedup/optimization. This deliberately does not trust+ * the pre-export Three.js scene.+ */+export async function analyzeFinalVfxGlbBytesV1(bytes: Uint8Array): Promise<FinalVfxGlbEvidenceV1> {+ const io = new WebIO().registerExtensions([EXTMeshGPUInstancing]);+ const document = await io.readBinary(bytes);+ const root = document.getRoot();+ const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);+ const meshes = [...new Set(renderableNodes.map((node) => node.getMesh()).filter(Boolean))];+ const primitives = meshes.flatMap((mesh) => mesh?.listPrimitives() ?? []);+ let triangleCount = 0;+ for (const primitive of primitives) {+ const indices = primitive.getIndices();+ const position = primitive.getAttribute('POSITION');+ triangleCount += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;+ }++ const effectSurfaceMaterials = new Set<import('@gltf-transform/core').Material>();+ for (const node of renderableNodes) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ continue;+ }+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {+ const material = primitive.getMaterial();+ if (material) effectSurfaceMaterials.add(material);+ }+ }++ const materials = [+ ...new Set(primitives.map((primitive) => primitive.getMaterial()).filter(Boolean)),+ ].map((material, index): FinalVfxMaterialEvidenceV1 => {+ const baseColor = material!.getBaseColorFactor();+ const texture = material!.getBaseColorTexture();+ const image = texture?.getImage();+ const mimeType = texture?.getMimeType() ?? '';+ const mode = material!.getAlphaMode().toLowerCase() as VfxTransparencyMode;+ return {+ id: material!.getName() || `material.${index}`,+ effectSurface: effectSurfaceMaterials.has(material!),+ alphaMode: mode,+ alphaData:+ (baseColor[3] ?? 1) < 1 ||+ (image !== null && image !== undefined && encodedTextureHasAlpha(mimeType, image)),+ doubleSided: material!.getDoubleSided(),+ ...(mode === 'mask' ? { alphaCutoff: material!.getAlphaCutoff() } : {}),+ };+ });++ const facingSemantics = new Set<VfxFacingMode>();+ for (const node of renderableNodes) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ for (const role of semantic?.roles ?? []) {+ const match = /^vfx\.facing\.(fixed|camera-spherical|camera-y-axis)$/.exec(role);+ if (match) facingSemantics.add(match[1] as VfxFacingMode);+ }+ }+ const normalAxis = finalEffectAxis(renderableNodes, 'normal');+ const directionAxis = finalEffectAxis(renderableNodes, 'length');++ return {+ schemaVersion: 1,+ meshCount: meshes.length,+ primitiveCount: primitives.length,+ triangleCount: Math.floor(triangleCount),+ materials,+ facingSemantics: [...facingSemantics].sort(),+ ...(normalAxis ? { normalAxis } : {}),+ ...(directionAxis ? { directionAxis } : {}),+ clips: root.listAnimations().map((animation) => ({+ name: animation.getName(),+ durationSeconds: animationDuration(animation),+ })),+ };+}++function finalFinding(intent: AssetIntentV1, value: Omit<QaFinding, 'profile'>): QaFinding {+ return { ...value, profile: intent.qaProfile || 'vfx.w7.final-glb' };+}++/** Exact VFX-002/003 checks against the final serialized artifact. */+export function evaluateFinalVfxGlbEvidenceV1(+ intent: AssetIntentV1,+ evidence: FinalVfxGlbEvidenceV1,+): QaFinding[] {+ if (intent.category !== 'vfx' || !intent.vfx) return [];+ const contract = intent.vfx;+ const findings: QaFinding[] = [];+ if (evidence.meshCount === 0 || evidence.primitiveCount === 0 || evidence.triangleCount === 0) {+ findings.push(+ finalFinding(intent, {+ code: 'VFX_GLTF_RENDERABLE_MISSING',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: 'Final GLB contains no renderable VFX geometry.',+ measurement: {+ name: 'finalVfxTriangles',+ actual: evidence.triangleCount,+ expected: '>=1',+ },+ repairText: 'Export the effect surface as portable geometry before final-byte approval.',+ }),+ );+ }+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface);+ if (effectMaterials.length === 0) {+ findings.push(+ finalFinding(intent, {+ code: 'VFX_GLTF_EFFECT_SURFACE_MISSING',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: 'Final GLB contains no material attached to a vfx.effect.surface.* node.',+ repairText:+ 'Preserve an explicit vfx.effect.surface.* semantic on each renderable effect node; use vfx.support.* for opaque support geometry.',+ }),+ );+ }+ for (const material of effectMaterials) {+ if (material.alphaMode !== contract.transparency) {+ findings.push(+ finalFinding(intent, {+ code: 'VFX_GLTF_TRANSPARENCY_MODE_MISMATCH',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: `${material.id} final GLB alpha mode is ${material.alphaMode}; expected ${contract.transparency}.`,+ affected: { material: material.id },+ measurement: {+ name: 'finalAlphaMode',+ actual: material.alphaMode,+ expected: contract.transparency,+ },+ }),+ );+ }+ if (contract.transparency !== 'opaque' && !material.alphaData) {+ findings.push(+ finalFinding(intent, {+ code: 'VFX_GLTF_ALPHA_DATA_MISSING',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: `${material.id} final GLB has no alpha-bearing factor or embedded texture.`,+ affected: { material: material.id },+ measurement: { name: 'finalAlphaData', actual: false, expected: true },+ repairText:+ 'Pack a standalone alphaMap into the exported base-color texture alpha channel, or use an alpha-bearing base-color factor.',+ }),+ );+ }+ if (material.doubleSided !== contract.doubleSided) {+ findings.push(+ finalFinding(intent, {+ code: 'VFX_GLTF_SIDEDNESS_MISMATCH',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: `${material.id} final GLB sidedness differs from trusted VFX intent.`,+ affected: { material: material.id },+ measurement: {+ name: 'finalDoubleSided',+ actual: material.doubleSided,+ expected: contract.doubleSided,+ },+ }),+ );+ }+ if (+ contract.transparency === 'mask' &&+ (material.alphaCutoff === undefined || material.alphaCutoff <= 0 || material.alphaCutoff > 1)+ ) {+ findings.push(+ finalFinding(intent, {+ code: 'VFX_GLTF_ALPHA_CUTOFF_INVALID',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: `${material.id} final GLB MASK cutoff is outside (0, 1].`,+ affected: { material: material.id },+ }),+ );+ }+ }++ if (+ contract.facing.mode !== 'fixed' &&+ !evidence.facingSemantics.includes(contract.facing.mode)+ ) {+ findings.push(+ finalFinding(intent, {+ code: 'VFX_GLTF_FACING_SEMANTIC_MISSING',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: `Final GLB does not carry the ${contract.facing.mode} runtime-facing semantic.`,+ measurement: {+ name: 'finalFacingSemantics',+ actual: evidence.facingSemantics.join(',') || null,+ expected: contract.facing.mode,+ },+ repairText: 'Preserve the exporter-derived billboard semantic on the renderable quad node.',+ }),+ );+ }++ if (+ contract.facing.source === 'explicit' &&+ contract.facing.mode === 'fixed' &&+ contract.facing.normalAxis !== evidence.normalAxis+ ) {+ findings.push(+ finalFinding(intent, {+ code: 'VFX_GLTF_NORMAL_AXIS_MISMATCH',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: 'Final GLB effect-surface normal axis differs from explicit VFX intent.',+ measurement: {+ name: 'finalNormalAxis',+ actual: evidence.normalAxis ?? null,+ expected: contract.facing.normalAxis ?? null,+ },+ }),+ );+ }+ if (+ contract.facing.source === 'explicit' &&+ contract.facing.directionAxis !== undefined &&+ contract.facing.directionAxis !== evidence.directionAxis+ ) {+ findings.push(+ finalFinding(intent, {+ code: 'VFX_GLTF_DIRECTION_AXIS_MISMATCH',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: 'Final GLB effect-surface direction axis differs from explicit VFX intent.',+ measurement: {+ name: 'finalDirectionAxis',+ actual: evidence.directionAxis ?? null,+ expected: contract.facing.directionAxis,+ },+ }),+ );+ }++ if (contract.animation.driver === 'clip') {+ const clip = evidence.clips.find((candidate) => candidate.name === contract.animation.clipName);+ if (!clip || Math.abs(clip.durationSeconds - contract.animation.durationSeconds) > 0.000001) {+ findings.push(+ finalFinding(intent, {+ code: 'VFX_GLTF_REQUIRED_CLIP_MISSING',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: 'Final GLB dropped or changed the declared VFX animation clip.',+ affected: { clip: contract.animation.clipName ?? '<missing>' },+ measurement: {+ name: 'finalClipDurationSeconds',+ actual: clip?.durationSeconds ?? null,+ expected: contract.animation.durationSeconds,+ threshold: 0.000001,+ unit: 's',+ },+ }),+ );+ }+ }+ return findings;+}++export async function appendFinalVfxGlbQa(+ intent: AssetIntentV1,+ report: AssetQaReportV1,+ bytes: Uint8Array,+): Promise<AssetQaReportV1> {+ if (intent.category !== 'vfx') return report;+ const evidence = await analyzeFinalVfxGlbBytesV1(bytes);+ const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);+ findings.push(...evaluateFinalVfxGlbEvidenceV1(intent, evidence));+ const evaluatedDimensions = Object.entries(report.dimensions)+ .filter(([, dimension]) => dimension.status !== 'notEvaluated')+ .map(([dimension]) => dimension as keyof AssetQaReportV1['dimensions']);+ if (!evaluatedDimensions.includes('exportIntegrity')) evaluatedDimensions.push('exportIntegrity');+ const metrics = Object.fromEntries(+ Object.entries(report.dimensions).flatMap(([dimension, result]) =>+ result.metrics ? [[dimension, result.metrics]] : [],+ ),+ ) as Partial<+ Record<keyof AssetQaReportV1['dimensions'], Record<string, number | string | boolean | null>>+ >;+ metrics.exportIntegrity = {+ ...(metrics.exportIntegrity ?? {}),+ finalVfxMeshCount: evidence.meshCount,+ finalVfxPrimitiveCount: evidence.primitiveCount,+ finalVfxTriangles: evidence.triangleCount,+ finalVfxMaterialCount: evidence.materials.length,+ finalVfxEffectMaterialCount: evidence.materials.filter((material) => material.effectSurface)+ .length,+ finalVfxFacingSemantics: evidence.facingSemantics.join(','),+ finalVfxNormalAxis: evidence.normalAxis ?? null,+ finalVfxDirectionAxis: evidence.directionAxis ?? null,+ finalVfxClipCount: evidence.clips.length,+ };+ return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });+}diff --git a/src/qa/breadth.ts b/src/qa/breadth.tsnew file mode 100644index 00000000..b3d90082--- /dev/null+++ b/src/qa/breadth.ts@@ -0,0 +1,641 @@+import {+ assessAssetScopeV1,+ evaluateModularJoinV1,+ validateModularKitContractV1,+ validateVfxIntentV1,+ type AssetScopeObservationV1,+ type ModularJoinObservationV1,+ type VfxAnimationIntentV1,+ type VfxFacingIntentV1,+ type VfxIntentV1,+ type VfxRuntimeSidecarV1,+ type VfxTransparencyMode,+} from '../contracts/breadth';+import { KILN_ENGINE_QA_OWNER, conformancePromotionAuthorization, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';++export interface VfxMaterialEvidenceV1 {+ id: string;+ surfaceRole: 'card' | 'beam' | 'trail' | 'volume' | 'core';+ /** Engine-analyzed role scope. False identifies support/emitter geometry. */+ effectSurface?: boolean;+ alphaMode: VfxTransparencyMode;+ alphaData: boolean;+ doubleSided: boolean;+ alphaCutoff?: number;+ /** Diagnostic-view estimate, not an instanceability grade. */+ screenAreaRatio: number;+ transparentLayers: number;+ textureMemoryBytes: number;+}++export interface VfxArtifactEvidenceV1 {+ schemaVersion: 1;+ facing: VfxFacingIntentV1;+ animation: VfxAnimationIntentV1 & { endpointMatches: boolean };+ sidecar?: VfxRuntimeSidecarV1;+ materials: VfxMaterialEvidenceV1[];+ clips: Array<{ name: string; durationSeconds: number }>;+ uniforms: string[];+}++export interface VfxRuntimeCostV1 {+ schemaVersion: 1;+ blendedScreenAreaRatio: number;+ transparentLayerCount: number;+ overdrawProxy: number;+ textureMemoryBytes: number;+ shaderSidecarRequired: boolean;+}++const record = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const stable = (value: number): number => Math.round(value * 1_000_000) / 1_000_000;++const finiteTuple = (value: unknown, length: number): value is number[] =>+ Array.isArray(value) &&+ value.length === length &&+ value.every((component) => typeof component === 'number' && Number.isFinite(component));++function validModularJoinObservation(value: unknown): value is ModularJoinObservationV1 {+ if (!record(value)) return false;+ return (+ typeof value.aSocketId === 'string' &&+ value.aSocketId.length > 0 &&+ typeof value.bSocketId === 'string' &&+ value.bSocketId.length > 0 &&+ finiteTuple(value.aWorldPosition, 3) &&+ finiteTuple(value.bWorldPosition, 3) &&+ finiteTuple(value.aWorldNormal, 3) &&+ finiteTuple(value.bWorldNormal, 3) &&+ typeof value.relativeRotationDegrees === 'number' &&+ Number.isFinite(value.relativeRotationDegrees) &&+ (value.toleranceMeters === undefined ||+ (typeof value.toleranceMeters === 'number' &&+ Number.isFinite(value.toleranceMeters) &&+ value.toleranceMeters >= 0)) &&+ (value.normalToleranceDegrees === undefined ||+ (typeof value.normalToleranceDegrees === 'number' &&+ Number.isFinite(value.normalToleranceDegrees) &&+ value.normalToleranceDegrees >= 0))+ );+}++function validVfxArtifactEvidence(value: unknown): value is VfxArtifactEvidenceV1 {+ if (!record(value) || value.schemaVersion !== 1) return false;+ if (!record(value.facing) || !record(value.animation)) return false;+ if (!Array.isArray(value.materials)) return false;+ if (!Array.isArray(value.clips) || !Array.isArray(value.uniforms)) return false;+ if (!value.uniforms.every((name) => typeof name === 'string' && name.length > 0)) return false;+ if (+ !value.clips.every(+ (clip) =>+ record(clip) &&+ typeof clip.name === 'string' &&+ clip.name.length > 0 &&+ typeof clip.durationSeconds === 'number' &&+ Number.isFinite(clip.durationSeconds) &&+ clip.durationSeconds >= 0,+ )+ ) {+ return false;+ }+ return value.materials.every(+ (material) =>+ record(material) &&+ typeof material.id === 'string' &&+ material.id.length > 0 &&+ ['card', 'beam', 'trail', 'volume', 'core'].includes(String(material.surfaceRole)) &&+ ['opaque', 'mask', 'blend'].includes(String(material.alphaMode)) &&+ (material.effectSurface === undefined || typeof material.effectSurface === 'boolean') &&+ typeof material.alphaData === 'boolean' &&+ typeof material.doubleSided === 'boolean' &&+ typeof material.screenAreaRatio === 'number' &&+ Number.isFinite(material.screenAreaRatio) &&+ material.screenAreaRatio >= 0 &&+ typeof material.transparentLayers === 'number' &&+ Number.isInteger(material.transparentLayers) &&+ material.transparentLayers >= 0 &&+ typeof material.textureMemoryBytes === 'number' &&+ Number.isInteger(material.textureMemoryBytes) &&+ material.textureMemoryBytes >= 0,+ );+}++function artifactEvidence(context: QaContext): VfxArtifactEvidenceV1 | undefined {+ if (context.derivedEvidence?.source !== 'engine-scene-analysis') return undefined;+ const candidate = context.derivedEvidence.vfxArtifact;+ return validVfxArtifactEvidence(candidate) ? candidate : undefined;+}++function finding(+ context: QaContext,+ value: Omit<QaFinding, 'profile'>,+ profile = 'vfx.w7',+): QaFinding {+ return { ...value, profile: context.intent.qaProfile || profile };+}++export function measureVfxRuntimeCostV1(evidence: VfxArtifactEvidenceV1): VfxRuntimeCostV1 {+ let blendedScreenAreaRatio = 0;+ let transparentLayerCount = 0;+ let overdrawProxy = 0;+ let textureMemoryBytes = 0;+ for (const material of evidence.materials) {+ textureMemoryBytes += material.textureMemoryBytes;+ if (material.alphaMode !== 'blend') continue;+ blendedScreenAreaRatio += material.screenAreaRatio;+ transparentLayerCount += material.transparentLayers;+ overdrawProxy += material.screenAreaRatio * Math.max(1, material.transparentLayers);+ }+ return {+ schemaVersion: 1,+ blendedScreenAreaRatio: stable(blendedScreenAreaRatio),+ transparentLayerCount,+ overdrawProxy: stable(overdrawProxy),+ textureMemoryBytes,+ shaderSidecarRequired: evidence.sidecar !== undefined,+ };+}++function exactVfxIntent(+ context: QaContext,+): { intent: VfxIntentV1; evidence: VfxArtifactEvidenceV1 } | { findings: QaFinding[] } {+ const candidate = context.intent.vfx;+ const validated = validateVfxIntentV1(candidate);+ if (!validated.valid || !validated.value) {+ return {+ findings: [+ finding(context, {+ code: 'VFX_INTENT_INVALID',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Trusted VFX intent is missing or invalid: ${validated.issues+ .map((issue) => `${issue.path || '<root>'}:${issue.code}`)+ .join(', ')}`,+ measurement: {+ name: 'vfxIntentIssueCount',+ actual: validated.issues.length,+ expected: 0,+ },+ repairText:+ 'Return to request normalization; model-authored source cannot repair trusted intent.',+ }),+ ],+ };+ }+ const evidence = artifactEvidence(context);+ if (!evidence) {+ return {+ findings: [+ finding(context, {+ code: 'VFX_RUNTIME_CONTRACT_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message:+ 'VFX output is missing its versioned facing/material/animation runtime evidence.',+ measurement: { name: 'vfxEvidencePresent', actual: false, expected: true },+ repairText:+ 'Return a renderable Three.js scene so the engine can analyze actual materials, facing behavior, clips/uniforms, and sidecar availability.',+ }),+ ],+ };+ }+ return { intent: validated.value, evidence };+}++/** H/H* VFX contract checks. Only explicit trusted requirements can block. */+export function evaluateVfxExactQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'vfx') return [];+ const resolved = exactVfxIntent(context);+ if ('findings' in resolved) return resolved.findings;+ const { intent, evidence } = resolved;+ const findings: QaFinding[] = [];+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface !== false);+ if (effectMaterials.length === 0) {+ findings.push(+ finding(context, {+ code: 'VFX_EFFECT_SURFACE_MISSING',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: 'VFX output has no explicitly analyzed effect-surface material.',+ measurement: { name: 'effectMaterialCount', actual: 0, expected: '>=1' },+ repairText:+ 'Stamp effect-rendering nodes with vfx.effect.surface.* and keep opaque support geometry in vfx.support.* roles.',+ }),+ );+ }+ for (const material of effectMaterials) {+ if (material.alphaMode !== intent.transparency) {+ findings.push(+ finding(context, {+ code: 'VFX_TRANSPARENCY_MODE_MISMATCH',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: `${material.id} exported ${material.alphaMode} but trusted VFX intent requires ${intent.transparency}.`,+ affected: { material: material.id },+ measurement: {+ name: 'alphaMode',+ actual: material.alphaMode,+ expected: intent.transparency,+ },+ repairText: `Set ${material.id} to the declared ${intent.transparency} alpha mode without changing unrelated materials.`,+ }),+ );+ }+ if (intent.transparency !== 'opaque' && !material.alphaData) {+ findings.push(+ finding(context, {+ code: 'VFX_ALPHA_DATA_MISSING',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: `${material.id} declares ${intent.transparency} but has no alpha-bearing factor or texture data.`,+ affected: { material: material.id },+ measurement: { name: 'alphaData', actual: false, expected: true },+ repairText: `Add alpha-bearing data to ${material.id}; do not leave an opaque effect-card rectangle.`,+ }),+ );+ }+ if (material.doubleSided !== intent.doubleSided) {+ findings.push(+ finding(context, {+ code: 'VFX_SIDEDNESS_MISMATCH',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: `${material.id} sidedness does not match trusted VFX intent.`,+ affected: { material: material.id },+ measurement: {+ name: 'doubleSided',+ actual: material.doubleSided,+ expected: intent.doubleSided,+ },+ repairText: `Set ${material.id} doubleSided=${intent.doubleSided}.`,+ }),+ );+ }+ if (+ intent.transparency === 'mask' &&+ (material.alphaCutoff === undefined ||+ !Number.isFinite(material.alphaCutoff) ||+ material.alphaCutoff <= 0 ||+ material.alphaCutoff > 1)+ ) {+ findings.push(+ finding(context, {+ code: 'VFX_ALPHA_CUTOFF_INVALID',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: `${material.id} uses MASK without a finite cutoff in (0, 1].`,+ affected: { material: material.id },+ measurement: {+ name: 'alphaCutoff',+ actual: material.alphaCutoff ?? null,+ expected: '0 < cutoff <= 1',+ },+ repairText: `Set a valid alpha cutoff on ${material.id}.`,+ }),+ );+ }+ }++ const facingFields = ['mode', 'normalAxis', 'directionAxis'] as const;+ for (const field of facingFields) {+ if (intent.facing[field] === evidence.facing[field]) continue;+ if (intent.facing.source !== 'explicit') continue;+ findings.push(+ finding(context, {+ code: 'VFX_FACING_CONTRACT_MISMATCH',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Explicit VFX facing ${field} does not match the emitted runtime contract.`,+ measurement: {+ name: `facing.${field}`,+ actual: evidence.facing[field] ?? null,+ expected: intent.facing[field] ?? null,+ },+ repairText: `Stamp and implement the requested ${field}; preserve the canonical Kiln frame.`,+ }),+ );+ }++ const requestedAnimation = intent.animation;+ const actualAnimation = evidence.animation;+ for (const field of ['playback', 'endpointBehavior', 'driver'] as const) {+ if (requestedAnimation[field] === actualAnimation[field]) continue;+ findings.push(+ finding(context, {+ code: 'VFX_ANIMATION_POLICY_MISMATCH',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `VFX animation ${field} does not match trusted intent.`,+ measurement: {+ name: `animation.${field}`,+ actual: actualAnimation[field],+ expected: requestedAnimation[field],+ },+ repairText: `Implement the declared ${field} without changing the effect subtype.`,+ }),+ );+ }+ if (Math.abs(requestedAnimation.durationSeconds - actualAnimation.durationSeconds) > 1e-6) {+ findings.push(+ finding(context, {+ code: 'VFX_ANIMATION_DURATION_MISMATCH',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: 'VFX animation duration does not match trusted intent.',+ measurement: {+ name: 'animation.durationSeconds',+ actual: actualAnimation.durationSeconds,+ expected: requestedAnimation.durationSeconds,+ threshold: 0.000001,+ unit: 's',+ },+ repairText: 'Use the declared duration and resample endpoint keys deterministically.',+ }),+ );+ }+ if (requestedAnimation.playback === 'loop' && !actualAnimation.endpointMatches) {+ findings.push(+ finding(context, {+ code: 'VFX_LOOP_ENDPOINT_MISMATCH',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: 'Looping VFX does not return to its start state at the declared endpoint.',+ measurement: { name: 'endpointMatches', actual: false, expected: true },+ repairText: 'Make the final loop sample equal the initial sample for every driven channel.',+ }),+ );+ }+ if (+ requestedAnimation.driver === 'clip' &&+ !evidence.clips.some(+ (clip) =>+ clip.name === requestedAnimation.clipName &&+ Math.abs(clip.durationSeconds - requestedAnimation.durationSeconds) <= 1e-6,+ )+ ) {+ findings.push(+ finding(context, {+ code: 'VFX_REQUIRED_CLIP_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: 'The declared VFX clip name/duration is absent from the artifact evidence.',+ affected: { clip: requestedAnimation.clipName ?? '<missing>' },+ repairText: `Emit clip ${requestedAnimation.clipName ?? '<declared clip>'} with the requested duration.`,+ }),+ );+ }+ if (+ requestedAnimation.driver === 'timeUniform' &&+ !evidence.uniforms.includes(requestedAnimation.timeUniformName ?? '')+ ) {+ findings.push(+ finding(context, {+ code: 'VFX_REQUIRED_TIME_UNIFORM_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: 'The declared runtime time uniform is absent from the sidecar evidence.',+ measurement: {+ name: 'timeUniformName',+ actual: evidence.uniforms.join(','),+ expected: requestedAnimation.timeUniformName ?? null,+ },+ repairText: `Expose ${requestedAnimation.timeUniformName ?? 'the declared uniform'} in the runtime sidecar.`,+ }),+ );+ }+ if (intent.portability === 'portable' && evidence.sidecar !== undefined) {+ findings.push(+ finding(context, {+ code: 'VFX_UNDECLARED_SIDECAR',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: 'Portable VFX unexpectedly requires a runtime shader sidecar.',+ repairText:+ 'Bake the portable appearance into standard glTF materials or update trusted intent before spend.',+ }),+ );+ }+ if (+ intent.portability === 'sidecar' &&+ (evidence.sidecar?.id !== intent.sidecar?.id ||+ evidence.sidecar?.version !== intent.sidecar?.version)+ ) {+ findings.push(+ finding(context, {+ code: 'VFX_SIDECAR_IDENTITY_MISMATCH',+ disposition: 'block',+ dimension: 'exportIntegrity',+ message: 'Runtime VFX sidecar identity/version does not match trusted intent.',+ measurement: {+ name: 'sidecarIdentity',+ actual: evidence.sidecar ? `${evidence.sidecar.id}@${evidence.sidecar.version}` : null,+ expected: intent.sidecar ? `${intent.sidecar.id}@${intent.sidecar.version}` : null,+ },+ repairText: 'Attach the exact declared sidecar identity and keep the GLB fallback honest.',+ }),+ );+ }+ return findings;+}++/** S-class VFX evidence. It reports cost and inferred-facing drift without blocking. */+export function evaluateVfxAdvisoryQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'vfx') return [];+ const intent = context.intent.vfx;+ const validated = validateVfxIntentV1(intent);+ const evidence = artifactEvidence(context);+ if (!validated.valid || !validated.value || !evidence) return [];+ const findings: QaFinding[] = [];+ if (validated.value.facing.source === 'inferred') {+ const mismatch = (['mode', 'normalAxis', 'directionAxis'] as const).some(+ (field) => validated.value?.facing[field] !== evidence.facing[field],+ );+ if (mismatch) {+ findings.push(+ finding(context, {+ code: 'VFX_FACING_INFERRED_DRIFT',+ disposition: 'observe',+ dimension: 'categoryReadiness',+ message: 'Inferred VFX facing differs from emitted metadata; review the named views.',+ viewHints: ['front', 'right', 'three-quarter'],+ }),+ );+ }+ }+ const cost = measureVfxRuntimeCostV1(evidence);+ findings.push(+ finding(context, {+ code: 'VFX_RUNTIME_COST_REPORT',+ disposition: 'observe',+ dimension: 'runtimeCost',+ message: 'VFX transparency/runtime cost is reported separately from instanceability.',+ measurement: {+ name: 'vfxRuntimeCost',+ actual: `blendArea=${cost.blendedScreenAreaRatio};layers=${cost.transparentLayerCount};overdraw=${cost.overdrawProxy};textureBytes=${cost.textureMemoryBytes};sidecar=${cost.shaderSidecarRequired}`,+ },+ viewHints: ['front', 'right', 'three-quarter'],+ }),+ );+ if (cost.overdrawProxy > 2 || cost.textureMemoryBytes > 32 * 1024 * 1024) {+ findings.push(+ finding(context, {+ code: 'VFX_RUNTIME_PRESSURE',+ disposition: 'observe',+ dimension: 'runtimeCost',+ message: 'VFX exceeds the observe-mode overdraw or texture-memory review threshold.',+ measurement: {+ name: 'overdrawProxy',+ actual: cost.overdrawProxy,+ threshold: 2,+ unit: 'screen-layers',+ },+ }),+ );+ }+ return findings;+}++/** MOD-001 applies only when trusted modular-kit data and a join observation are present. */+export function evaluateModularJoinQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.scope.scope !== 'modularSet' || !context.intent.scope.explicit) return [];+ const modularKit = context.derivedEvidence?.modularKit;+ const modularJoin = context.derivedEvidence?.modularJoin;+ const validation = validateModularKitContractV1(modularKit);+ if (!validation.valid || !validation.value || !validModularJoinObservation(modularJoin)) {+ return [+ finding(+ context,+ {+ code: 'MODULAR_CONTRACT_INVALID',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Explicit modular-set intent requires a valid grid/units/socket contract and join observation: ${validation.issues+ .map((issue) => issue.code)+ .join(', ')}`,+ repairText:+ 'Emit the requested modular socket metadata; do not infer a noun-specific primitive.',+ },+ 'modular.w7',+ ),+ ];+ }+ const result = evaluateModularJoinV1(validation.value, modularJoin);+ if (result.pass) return [];+ return result.codes.map((code) =>+ finding(+ context,+ {+ code,+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Explicit modular join failed ${code}: seam=${result.seamMeters} m, overlap=${result.overlapMeters} m, lateral=${result.lateralOffsetMeters} m.`,+ measurement: {+ name: 'modularJoinError',+ actual: Math.max(result.seamMeters, result.overlapMeters, result.lateralOffsetMeters),+ expected: 0,+ threshold: result.toleranceMeters,+ unit: 'm',+ },+ repairText:+ 'Snap the named compatible sockets on the declared meter grid using an allowed rotation.',+ },+ 'modular.w7',+ ),+ );+}++/** SCOPE-001 remains advisory under the owner-approved S-rule policy. */+export function evaluateAssetScopeQa(context: QaContext): readonly QaFinding[] {+ const scope = context.intent.scope;+ const scopeObservation = context.derivedEvidence?.assetScope;+ if (+ context.derivedEvidence?.source !== 'engine-scene-analysis' ||+ !record(scopeObservation) ||+ typeof scopeObservation.topLevelAssetRoots !== 'number' ||+ typeof scopeObservation.reusableMemberCount !== 'number' ||+ !Array.isArray(scopeObservation.sceneDressingRoles)+ ) {+ return [];+ }+ const result = assessAssetScopeV1(scope, scopeObservation as unknown as AssetScopeObservationV1);+ if (result.status === 'pass' || !result.code) return [];+ return [+ finding(+ context,+ {+ code: result.code,+ disposition: 'observe',+ dimension: 'promptAlignment',+ message: `Requested ${result.requested} scope produced ${result.observed} evidence: ${result.evidence.join('; ')}.`,+ measurement: {+ name: 'explicitSingleViolation',+ actual: result.explicitSingleViolation,+ expected: false,+ },+ viewHints: ['top', 'three-quarter'],+ },+ 'scope.w7',+ ),+ ];+}++export const VFX_EXACT_QA_RULE: QaRule = {+ id: 'VFX_EXACT_PROFILE',+ profile: 'vfx.w7.exact',+ scope: { kind: 'category', category: 'vfx' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'vfx-w7-conformance-v1',+ 'src/qa/breadth-corpus.test.ts',+ '58837182f467de6757194d54c8b42682d21d3d9355daecab694888cd742d2405',+ ),+ defaultMode: 'enforce',+ evaluate: evaluateVfxExactQa,+};++export const VFX_ADVISORY_QA_RULE: QaRule = {+ id: 'VFX_ADVISORY_PROFILE',+ profile: 'vfx.w7.advisory',+ scope: { kind: 'category', category: 'vfx' },+ ruleClass: 'heuristic',+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: 'observe',+ evaluate: evaluateVfxAdvisoryQa,+};++export const MODULAR_JOIN_QA_RULE: QaRule = {+ id: 'MODULAR_JOIN_PROFILE',+ profile: 'modular.w7.exact',+ scope: { kind: 'universal' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'modular-w7-conformance-v1',+ 'src/qa/breadth-corpus.test.ts',+ '58837182f467de6757194d54c8b42682d21d3d9355daecab694888cd742d2405',+ ),+ defaultMode: 'enforce',+ evaluate: evaluateModularJoinQa,+};++export const ASSET_SCOPE_QA_RULE: QaRule = {+ id: 'ASSET_SCOPE_PROFILE',+ profile: 'scope.w7.advisory',+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: 'observe',+ evaluate: evaluateAssetScopeQa,+};++/** REF-001 is intentionally absent: reference QA is sampled/Bench/flagged only. */+export const W7_BREADTH_QA_RULES: readonly QaRule[] = [+ VFX_EXACT_QA_RULE,+ VFX_ADVISORY_QA_RULE,+ MODULAR_JOIN_QA_RULE,+ ASSET_SCOPE_QA_RULE,+] as const;diff --git a/src/qa/character-advisory.ts b/src/qa/character-advisory.tsnew file mode 100644index 00000000..9b51521f--- /dev/null+++ b/src/qa/character-advisory.ts@@ -0,0 +1,591 @@+import * as THREE from 'three';++import {+ collectCharacterJointNodes,+ type CharacterJointDescriptorV1,+ type CharacterJointNodeEvidenceV1,+} from '../character';+import type { AssetIntentV1, CharacterIntentV1 } from '../contracts';+import { KILN_ENGINE_QA_OWNER, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';++const SKELETON_VIEWS = ['character.skeleton.front', 'character.skeleton.right'];+const MOTION_VIEWS = ['character.motion-strip.front', 'character.motion-strip.right'];+const REST_SYMMETRY_RATIO = 0.08;+const REST_ORDER_RATIO = 0.01;+const FORWARD_ANGLE_DEGREES = 45;+const LATERAL_ENERGY_RATIO = 1.5;+const PHASE_CORRELATION_THRESHOLD = 0.25;+const REVERSE_BEND_DEGREES = 15;+const FOOT_SLIDE_RATIO = 0.05;+const SAMPLE_FRACTIONS = [0, 0.25, 0.5, 0.75, 1] as const;++interface TrackLike {+ name: string;+ times: ArrayLike<number>;+ values: ArrayLike<number>;+ createInterpolant?: () => { evaluate(time: number): ArrayLike<number> };+}++interface ClipLike {+ name: string;+ duration: number;+ tracks: TrackLike[];+}++interface JointPoint {+ evidence: CharacterJointNodeEvidenceV1;+ local: THREE.Vector3;+}++function isClipLike(value: unknown): value is ClipLike {+ if (typeof value !== 'object' || value === null) return false;+ const candidate = value as Partial<ClipLike>;+ return (+ typeof candidate.name === 'string' &&+ typeof candidate.duration === 'number' &&+ Array.isArray(candidate.tracks)+ );+}++function characterIntent(intent: AssetIntentV1): CharacterIntentV1 | undefined {+ return intent.character;+}++function advisory(+ context: QaContext,+ value: Omit<QaFinding, 'profile' | 'dimension' | 'disposition'>,+): QaFinding {+ return {+ ...value,+ disposition: 'warn',+ dimension: 'categoryReadiness',+ profile: context.intent.qaProfile,+ };+}++function rootInverse(root: THREE.Object3D): THREE.Matrix4 {+ root.updateMatrixWorld(true);+ return root.matrixWorld.clone().invert();+}++function jointPoints(root: THREE.Object3D): JointPoint[] {+ const inverse = rootInverse(root);+ return collectCharacterJointNodes(root).map((evidence) => ({+ evidence,+ local: evidence.node.getWorldPosition(new THREE.Vector3()).applyMatrix4(inverse),+ }));+}++function characterScale(points: readonly JointPoint[]): number {+ if (points.length === 0) return 1;+ const bounds = new THREE.Box3();+ for (const point of points) bounds.expandByPoint(point.local);+ const size = bounds.getSize(new THREE.Vector3());+ return Math.max(size.x, size.y, size.z, 1);+}++function pairKey(descriptor: CharacterJointDescriptorV1): string {+ return descriptor.role+ .split(/[._-]/)+ .filter((token) => token !== 'left' && token !== 'right')+ .join('.');+}++function bilateralSymmetryFindings(context: QaContext, root: THREE.Object3D): QaFinding[] {+ const points = jointPoints(root);+ const scale = characterScale(points);+ const threshold = Math.max(0.02, scale * REST_SYMMETRY_RATIO);+ const left = new Map(+ points+ .filter((point) => point.evidence.descriptor.side === 'left')+ .map((point) => [pairKey(point.evidence.descriptor), point] as const),+ );+ const right = new Map(+ points+ .filter((point) => point.evidence.descriptor.side === 'right')+ .map((point) => [pairKey(point.evidence.descriptor), point] as const),+ );+ const findings: QaFinding[] = [];+ for (const key of [...new Set([...left.keys(), ...right.keys()])].sort()) {+ const a = left.get(key);+ const b = right.get(key);+ if (!a || !b) continue;+ const mirrorDelta = Math.hypot(+ a.local.x - b.local.x,+ a.local.y - b.local.y,+ a.local.z + b.local.z,+ );+ const sideSwapped = a.local.z > b.local.z;+ if (!sideSwapped && mirrorDelta <= threshold) continue;+ findings.push(+ advisory(context, {+ code: 'CHAR_REST_BILATERAL_SYMMETRY',+ message:+ `Bilateral rest pair ${a.evidence.descriptor.role} / ${b.evidence.descriptor.role} ` ++ `${sideSwapped ? 'appears left/right swapped' : 'is grossly asymmetric'} ` ++ `(mirror delta ${mirrorDelta.toFixed(6)} m).`,+ affected: {+ node: b.evidence.node.name,+ nodePath: b.evidence.nodePath,+ },+ measurement: {+ name: 'bilateralMirrorDelta',+ actual: mirrorDelta,+ expected: 0,+ threshold,+ unit: 'm',+ },+ viewHints: [...SKELETON_VIEWS],+ }),+ );+ }+ return findings;+}++const BIPED_CHAINS = [+ ['shoulder.left', 'elbow.left', 'wrist.left'],+ ['shoulder.right', 'elbow.right', 'wrist.right'],+ ['hip.left', 'knee.left', 'ankle.left'],+ ['hip.right', 'knee.right', 'ankle.right'],+] as const;++const QUADRUPED_CHAINS = [+ ['shoulder.fore.left', 'elbow.fore.left', 'paw.fore.left'],+ ['shoulder.fore.right', 'elbow.fore.right', 'paw.fore.right'],+ ['hip.hind.left', 'knee.hind.left', 'paw.hind.left'],+ ['hip.hind.right', 'knee.hind.right', 'paw.hind.right'],+] as const;++function restChainFindings(context: QaContext, root: THREE.Object3D): QaFinding[] {+ const trusted = characterIntent(context.intent);+ if (trusted?.bodyPlan !== 'biped' && trusted?.bodyPlan !== 'quadruped') return [];+ const points = jointPoints(root);+ const byRole = new Map(points.map((point) => [point.evidence.descriptor.role, point] as const));+ const scale = characterScale(points);+ const minimumSegment = Math.max(0.01, scale * REST_ORDER_RATIO);+ const chains = trusted.bodyPlan === 'biped' ? BIPED_CHAINS : QUADRUPED_CHAINS;+ const findings: QaFinding[] = [];+ for (const roles of chains) {+ const chain = roles+ .map((role) => byRole.get(role))+ .filter((value): value is JointPoint => !!value);+ if (chain.length !== roles.length) continue;+ for (let index = 1; index < chain.length; index++) {+ const parent = chain[index - 1]!;+ const child = chain[index]!;+ const verticalDrop = parent.local.y - child.local.y;+ if (verticalDrop >= minimumSegment) continue;+ findings.push(+ advisory(context, {+ code: 'CHAR_REST_CHAIN_ORDER',+ message:+ `Rest chain ${roles.join(' -> ')} is vertically inverted or collapsed at ` ++ `${parent.evidence.descriptor.role} -> ${child.evidence.descriptor.role}.`,+ affected: { node: child.evidence.node.name, nodePath: child.evidence.nodePath },+ measurement: {+ name: 'parentToChildVerticalDrop',+ actual: verticalDrop,+ expected: `>=${minimumSegment}`,+ threshold: minimumSegment,+ unit: 'm',+ },+ viewHints: [...SKELETON_VIEWS],+ }),+ );+ }+ const lengths = [+ chain[0]!.local.distanceTo(chain[1]!.local),+ chain[1]!.local.distanceTo(chain[2]!.local),+ ];+ const ratio = Math.max(...lengths) / Math.max(Math.min(...lengths), 1e-9);+ if (Math.min(...lengths) >= minimumSegment && ratio <= 2.5) continue;+ findings.push(+ advisory(context, {+ code: 'CHAR_REST_SEGMENT_LENGTH',+ message: `Rest chain ${roles.join(' -> ')} has collapsed or grossly unmatched segment lengths.`,+ affected: { node: chain[1]!.evidence.node.name, nodePath: chain[1]!.evidence.nodePath },+ measurement: {+ name: 'chainSegmentLengthRatio',+ actual: ratio,+ expected: '<=2.5',+ threshold: 2.5,+ },+ viewHints: [...SKELETON_VIEWS],+ }),+ );+ }+ return findings;+}++function forwardMarkerFindings(context: QaContext, root: THREE.Object3D): QaFinding[] {+ root.updateMatrixWorld(true);+ const expected = new THREE.Vector3(1, 0, 0).transformDirection(root.matrixWorld);+ const markers = collectCharacterJointNodes(root).filter((joint) =>+ /(?:^|[._-])(?:toe|muzzle|head)(?:$|[._-])/i.test(joint.descriptor.role),+ );+ return markers.flatMap((marker) => {+ const quaternion = marker.node.getWorldQuaternion(new THREE.Quaternion());+ const actual = new THREE.Vector3(...marker.descriptor.localForwardAxis)+ .applyQuaternion(quaternion)+ .normalize();+ const angle = THREE.MathUtils.radToDeg(+ Math.acos(THREE.MathUtils.clamp(actual.dot(expected), -1, 1)),+ );+ if (angle <= FORWARD_ANGLE_DEGREES) return [];+ return [+ advisory(context, {+ code: 'CHAR_FORWARD_MARKER',+ message:+ `Declared forward marker ${marker.descriptor.role} differs from canonical +X by ` ++ `${angle.toFixed(3)} degrees.`,+ affected: { node: marker.node.name, nodePath: marker.nodePath },+ measurement: {+ name: 'forwardMarkerAngle',+ actual: angle,+ expected: 0,+ threshold: FORWARD_ANGLE_DEGREES,+ unit: 'degrees',+ },+ viewHints: [...SKELETON_VIEWS],+ }),+ ];+ });+}++function trackTarget(trackName: string): string | undefined {+ const dot = trackName.lastIndexOf('.');+ return dot > 0 ? trackName.slice(0, dot) : undefined;+}++function trackProperty(trackName: string): string | undefined {+ const dot = trackName.lastIndexOf('.');+ return dot > 0 ? trackName.slice(dot + 1) : undefined;+}++function applyTrack(root: THREE.Object3D, track: TrackLike, time: number): void {+ const target = trackTarget(track.name);+ const property = trackProperty(track.name);+ const node = target ? root.getObjectByName(target) : undefined;+ if (!node || !property || !track.createInterpolant) return;+ const value = track.createInterpolant().evaluate(time);+ if (property === 'position') node.position.fromArray(value);+ else if (property === 'scale') node.scale.fromArray(value);+ else if (property === 'quaternion') node.quaternion.fromArray(value).normalize();+}++interface MotionSample {+ fraction: number;+ byRole: Map<string, { point: THREE.Vector3; evidence: CharacterJointNodeEvidenceV1 }>;+}++function sampleClip(root: THREE.Object3D, clip: ClipLike): MotionSample[] {+ const inverse = rootInverse(root);+ return SAMPLE_FRACTIONS.map((fraction) => {+ const clone = root.clone(true);+ for (const track of clip.tracks) applyTrack(clone, track, fraction * clip.duration);+ clone.updateMatrixWorld(true);+ return {+ fraction,+ byRole: new Map(+ collectCharacterJointNodes(clone).map((evidence) => [+ evidence.descriptor.role,+ {+ point: evidence.node.getWorldPosition(new THREE.Vector3()).applyMatrix4(inverse),+ evidence,+ },+ ]),+ ),+ };+ });+}++function locomotionClips(context: QaContext): ClipLike[] {+ const trusted = characterIntent(context.intent);+ if (!trusted || trusted.locomotion === 'stationary') return [];+ const names = new Set(+ trusted.clips.filter((clip) => clip.playback === 'loop').map((clip) => clip.name),+ );+ return (context.clips ?? [])+ .filter(isClipLike)+ .filter((clip) => names.size === 0 || names.has(clip.name));+}++function limbRole(role: string): boolean {+ return /(?:shoulder|elbow|wrist|hip|knee|ankle|paw|toe|wing)/i.test(role);+}++function lateralEnergyFindings(+ context: QaContext,+ root: THREE.Object3D,+ clips: readonly ClipLike[],+): QaFinding[] {+ const rest = jointPoints(root);+ const scale = characterScale(rest);+ const minimumEnergy = scale * scale * 1e-4;+ const findings: QaFinding[] = [];+ for (const clip of clips) {+ const samples = sampleClip(root, clip);+ const roles = [...samples[0]!.byRole.keys()].filter(limbRole).sort();+ for (const role of roles) {+ let sagittal = 0;+ let lateral = 0;+ let maximumLateral = 0;+ let maximumFraction = 0;+ for (let index = 1; index < samples.length; index++) {+ const before = samples[index - 1]!.byRole.get(role)?.point;+ const after = samples[index]!.byRole.get(role)?.point;+ if (!before || !after) continue;+ const delta = after.clone().sub(before);+ sagittal += delta.x * delta.x + delta.y * delta.y;+ lateral += delta.z * delta.z;+ if (Math.abs(delta.z) > maximumLateral) {+ maximumLateral = Math.abs(delta.z);+ maximumFraction = samples[index]!.fraction;+ }+ }+ if (lateral + sagittal < minimumEnergy || lateral <= sagittal * LATERAL_ENERGY_RATIO)+ continue;+ const evidence = samples[0]!.byRole.get(role)!.evidence;+ findings.push(+ advisory(context, {+ code: 'CHAR_GAIT_LATERAL_ENERGY',+ message:+ `Locomotion chain ${role} in ${clip.name} is lateral-motion dominant; ` ++ `largest offending step ends at phase ${maximumFraction}.`,+ affected: { node: evidence.node.name, nodePath: evidence.nodePath, clip: clip.name },+ measurement: {+ name: 'lateralToSagittalEnergy',+ actual: lateral / Math.max(sagittal, minimumEnergy),+ expected: `<=${LATERAL_ENERGY_RATIO}`,+ threshold: LATERAL_ENERGY_RATIO,+ },+ viewHints: [...MOTION_VIEWS],+ }),+ );+ }+ }+ return findings;+}++function correlation(a: readonly number[], b: readonly number[]): number | undefined {+ if (a.length !== b.length || a.length < 3) return undefined;+ const meanA = a.reduce((sum, value) => sum + value, 0) / a.length;+ const meanB = b.reduce((sum, value) => sum + value, 0) / b.length;+ let numerator = 0;+ let varianceA = 0;+ let varianceB = 0;+ for (let index = 0; index < a.length; index++) {+ const da = a[index]! - meanA;+ const db = b[index]! - meanB;+ numerator += da * db;+ varianceA += da * da;+ varianceB += db * db;+ }+ const denominator = Math.sqrt(varianceA * varianceB);+ return denominator > 1e-9 ? numerator / denominator : undefined;+}++function phaseOppositionFindings(+ context: QaContext,+ root: THREE.Object3D,+ clips: readonly ClipLike[],+): QaFinding[] {+ const trusted = characterIntent(context.intent);+ if (trusted?.bodyPlan !== 'biped' || !/(?:walk|run)/i.test(trusted.locomotion)) return [];+ const findings: QaFinding[] = [];+ for (const clip of clips) {+ const samples = sampleClip(root, clip);+ const left = samples.map((sample) => sample.byRole.get('ankle.left')?.point.x);+ const right = samples.map((sample) => sample.byRole.get('ankle.right')?.point.x);+ if (left.some((value) => value === undefined) || right.some((value) => value === undefined)) {+ continue;+ }+ const phaseCorrelation = correlation(left as number[], right as number[]);+ if (phaseCorrelation === undefined || phaseCorrelation <= PHASE_CORRELATION_THRESHOLD) continue;+ const evidence = samples[0]!.byRole.get('ankle.right')!.evidence;+ findings.push(+ advisory(context, {+ code: 'CHAR_GAIT_SAME_PHASE',+ message:+ `Biped ${clip.name} drives left and right legs in the same phase ` ++ `(correlation ${phaseCorrelation.toFixed(6)}).`,+ affected: { node: evidence.node.name, nodePath: evidence.nodePath, clip: clip.name },+ measurement: {+ name: 'leftRightLegPhaseCorrelation',+ actual: phaseCorrelation,+ expected: '<=0.25',+ threshold: PHASE_CORRELATION_THRESHOLD,+ },+ viewHints: [...MOTION_VIEWS],+ }),+ );+ }+ return findings;+}++function signedBendDegrees(+ descriptor: CharacterJointDescriptorV1,+ quaternion: THREE.Quaternion,+): number {+ const rest = new THREE.Quaternion(...descriptor.rest.rotation);+ const delta = rest.invert().multiply(quaternion).normalize();+ const axis = new THREE.Vector3(delta.x, delta.y, delta.z);+ const signedMagnitude = axis.dot(new THREE.Vector3(...descriptor.localBendAxis));+ const angle = 2 * Math.atan2(signedMagnitude, delta.w);+ return THREE.MathUtils.radToDeg(+ THREE.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI,+ );+}++function bendDirectionFindings(+ context: QaContext,+ root: THREE.Object3D,+ clips: readonly ClipLike[],+): QaFinding[] {+ const joints = collectCharacterJointNodes(root).filter((joint) =>+ /(?:^|[._-])(?:knee|elbow)(?:$|[._-])/i.test(joint.descriptor.role),+ );+ const findings: QaFinding[] = [];+ for (const clip of clips) {+ for (const joint of joints) {+ const track = clip.tracks.find(+ (candidate) =>+ trackTarget(candidate.name) === joint.node.name &&+ trackProperty(candidate.name) === 'quaternion' &&+ candidate.createInterpolant,+ );+ if (!track?.createInterpolant) continue;+ let maximum = 0;+ let maximumFraction = 0;+ for (const fraction of SAMPLE_FRACTIONS) {+ const value = track.createInterpolant().evaluate(fraction * clip.duration);+ const bend = signedBendDegrees(+ joint.descriptor,+ new THREE.Quaternion().fromArray(value).normalize(),+ );+ if (Math.abs(bend) > Math.abs(maximum)) {+ maximum = bend;+ maximumFraction = fraction;+ }+ }+ if (maximum >= -REVERSE_BEND_DEGREES) continue;+ findings.push(+ advisory(context, {+ code: 'CHAR_JOINT_REVERSE_BEND',+ message:+ `${joint.descriptor.role} bends opposite its declared local bend axis at ` ++ `${clip.name} phase ${maximumFraction}.`,+ affected: {+ node: joint.node.name,+ nodePath: joint.nodePath,+ clip: clip.name,+ track: track.name,+ },+ measurement: {+ name: 'signedMaximumFlexion',+ actual: maximum,+ expected: `>=-${REVERSE_BEND_DEGREES}`,+ threshold: REVERSE_BEND_DEGREES,+ unit: 'degrees',+ },+ viewHints: [...MOTION_VIEWS],+ }),+ );+ }+ }+ return findings;+}++function footSlideFindings(+ context: QaContext,+ root: THREE.Object3D,+ clips: readonly ClipLike[],+): QaFinding[] {+ const trusted = characterIntent(context.intent);+ if (!trusted?.grounded) return [];+ const rest = jointPoints(root);+ const threshold = Math.max(0.02, characterScale(rest) * FOOT_SLIDE_RATIO);+ const contactTolerance = Math.max(0.02, threshold * 0.4);+ const contacts = rest+ .filter((point) => point.evidence.descriptor.contact)+ .map((point) => point.evidence.descriptor.role);+ const findings: QaFinding[] = [];+ for (const clip of clips) {+ const samples = sampleClip(root, clip);+ for (const role of contacts) {+ let anchor: THREE.Vector3 | undefined;+ let maximum = 0;+ let maximumFraction = 0;+ for (const sample of samples) {+ const entry = sample.byRole.get(role);+ if (!entry || entry.point.y > contactTolerance) {+ anchor = undefined;+ continue;+ }+ anchor ??= entry.point.clone();+ const slide = Math.hypot(entry.point.x - anchor.x, entry.point.z - anchor.z);+ if (slide > maximum) {+ maximum = slide;+ maximumFraction = sample.fraction;+ }+ }+ if (maximum <= threshold) continue;+ const evidence = samples[0]!.byRole.get(role)?.evidence;+ findings.push(+ advisory(context, {+ code: 'CHAR_FOOT_SLIDE',+ message:+ `Planted contact ${role} slides ${maximum.toFixed(6)} m horizontally in ` ++ `${clip.name} by phase ${maximumFraction}.`,+ affected: {+ node: evidence?.node.name ?? role,+ ...(evidence ? { nodePath: evidence.nodePath } : {}),+ clip: clip.name,+ },+ measurement: {+ name: 'plantedContactHorizontalSlide',+ actual: maximum,+ expected: 0,+ threshold,+ unit: 'm',+ },+ viewHints: [...MOTION_VIEWS, 'generic.front.depth-contact'],+ }),+ );+ }+ }+ return findings;+}++/** W6 anatomy and motion measurements. Every result remains heuristic and nonblocking. */+export function evaluateCharacterAdvisoryQa(context: QaContext): QaFinding[] {+ if (context.intent.category !== 'character' || !(context.scene instanceof THREE.Object3D)) {+ return [];+ }+ const root = context.scene;+ const clips = locomotionClips(context);+ return [+ ...bilateralSymmetryFindings(context, root),+ ...restChainFindings(context, root),+ ...forwardMarkerFindings(context, root),+ ...lateralEnergyFindings(context, root, clips),+ ...phaseOppositionFindings(context, root, clips),+ ...bendDirectionFindings(context, root, clips),+ ...footSlideFindings(context, root, clips),+ ].sort((a, b) =>+ `${a.code}:${a.affected?.nodePath ?? ''}:${a.affected?.clip ?? ''}`.localeCompare(+ `${b.code}:${b.affected?.nodePath ?? ''}:${b.affected?.clip ?? ''}`,+ ),+ );+}++export const CHARACTER_ADVISORY_QA_RULE: QaRule = Object.freeze({+ id: 'CHARACTER_ADVISORY_PROFILE',+ profile: 'character.advisory',+ scope: { kind: 'category' as const, category: 'character' as const },+ ruleClass: 'heuristic',+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: 'observe',+ evaluate: evaluateCharacterAdvisoryQa,+});diff --git a/src/qa/character-repairs.ts b/src/qa/character-repairs.tsnew file mode 100644index 00000000..3345808c--- /dev/null+++ b/src/qa/character-repairs.ts@@ -0,0 +1,185 @@+import type { QaFinding } from './types';++export const CHARACTER_REPAIR_CODES = [+ 'CHAR_DUPLICATE_ANIMATED_NODE_NAME',+ 'CHAR_DUPLICATE_JOINT_ROLE',+ 'CHAR_PARENT_EDGE',+ 'CHAR_BIPED_REQUIRED_ROLE',+ 'CHAR_QUADRUPED_REQUIRED_ROLE',+ 'CHAR_CUSTOM_GRAPH_MISSING',+ 'CHAR_CUSTOM_REQUIRED_ROLE',+ 'CHAR_HELD_ITEM_MISSING',+ 'CHAR_HELD_ITEM_ATTACHMENT',+ 'CHAR_HELD_ITEM_GRIP_BREAK',+ 'CHAR_CONTACT_MISSING',+ 'CHAR_CONTACT_FLOATING',+ 'CHAR_CONTACT_BURIED',+ 'CHAR_CLIP_MISSING',+ 'CHAR_CLIP_DUPLICATE',+ 'CHAR_CLIP_UNEXPECTED',+ 'CHAR_CLIP_DURATION',+ 'CHAR_ANIMATION_NONFINITE',+ 'CHAR_KEY_TIME_ORDER',+ 'CHAR_KEY_OUT_OF_RANGE',+ 'CHAR_TRACK_VALUE_COUNT',+ 'CHAR_LOOP_ENDPOINT',+ 'CHAR_ROOT_MOTION_BACKWARD',+ 'CHAR_ROOT_MOTION_LATERAL',+] as const;++export type CharacterRepairCode = (typeof CHARACTER_REPAIR_CODES)[number];++export interface CharacterRepairRecipe {+ code: CharacterRepairCode;+ repairText: string;+ viewHints: readonly string[];+}++const skeletonViews = Object.freeze(['character.skeleton.front', 'character.skeleton.right']);+const motionViews = Object.freeze(['character.motion-strip.front', 'character.motion-strip.right']);++const recipe = (+ code: CharacterRepairCode,+ repairText: string,+ viewHints: readonly string[],+): CharacterRepairRecipe =>+ Object.freeze({ code, repairText, viewHints: Object.freeze([...viewHints]) });++export const CHARACTER_REPAIR_RECIPES: Readonly<+ Record<CharacterRepairCode, CharacterRepairRecipe>+> = Object.freeze({+ CHAR_DUPLICATE_ANIMATED_NODE_NAME: recipe(+ 'CHAR_DUPLICATE_ANIMATED_NODE_NAME',+ 'Rename only the reported duplicate Joint_* pivot and update its animation-track target so every animated node name is unique.',+ skeletonViews,+ ),+ CHAR_DUPLICATE_JOINT_ROLE: recipe(+ 'CHAR_DUPLICATE_JOINT_ROLE',+ 'Give the reported joint its intended unique semantic role; do not remove or merge unrelated branches.',+ skeletonViews,+ ),+ CHAR_PARENT_EDGE: recipe(+ 'CHAR_PARENT_EDGE',+ 'Reparent only the reported joint directly under its declared parent role while preserving its asset-local rest pose.',+ skeletonViews,+ ),+ CHAR_BIPED_REQUIRED_ROLE: recipe(+ 'CHAR_BIPED_REQUIRED_ROLE',+ 'Add the reported missing biped joint role and declared parent edge without redesigning already-valid chains.',+ skeletonViews,+ ),+ CHAR_QUADRUPED_REQUIRED_ROLE: recipe(+ 'CHAR_QUADRUPED_REQUIRED_ROLE',+ 'Add the reported missing quadruped joint role and declared parent edge without changing the other three limb chains.',+ skeletonViews,+ ),+ CHAR_CUSTOM_GRAPH_MISSING: recipe(+ 'CHAR_CUSTOM_GRAPH_MISSING',+ 'Declare the requested custom rig graph before authoring animation; do not substitute biped assumptions.',+ skeletonViews,+ ),+ CHAR_CUSTOM_REQUIRED_ROLE: recipe(+ 'CHAR_CUSTOM_REQUIRED_ROLE',+ 'Add only the reported role from the trusted custom graph and attach it to its declared parent.',+ skeletonViews,+ ),+ CHAR_HELD_ITEM_MISSING: recipe(+ 'CHAR_HELD_ITEM_MISSING',+ 'Add the declared held item as its own node under the requested grip end effector.',+ skeletonViews,+ ),+ CHAR_HELD_ITEM_ATTACHMENT: recipe(+ 'CHAR_HELD_ITEM_ATTACHMENT',+ 'Reparent only the held-item node under the reported hand, wrist, or grip end effector; never attach it to a shoulder or elbow.',+ skeletonViews,+ ),+ CHAR_HELD_ITEM_GRIP_BREAK: recipe(+ 'CHAR_HELD_ITEM_GRIP_BREAK',+ 'Keep the reported held item under its declared grip end effector and remove only the item-local animation keys that change its grip distance.',+ motionViews,+ ),+ CHAR_CONTACT_MISSING: recipe(+ 'CHAR_CONTACT_MISSING',+ 'Tag the requested foot, paw, or terminal support as a ground contact without changing body plan.',+ ['character.skeleton.front', 'generic.front.depth-contact'],+ ),+ CHAR_CONTACT_FLOATING: recipe(+ 'CHAR_CONTACT_FLOATING',+ 'Move only the reported contact down to asset-local Y=0 while preserving its parent chain and lateral placement.',+ ['character.skeleton.front', 'generic.front.depth-contact'],+ ),+ CHAR_CONTACT_BURIED: recipe(+ 'CHAR_CONTACT_BURIED',+ 'Move only the reported contact up to asset-local Y=0 while preserving its parent chain and lateral placement.',+ ['character.skeleton.front', 'generic.front.depth-contact'],+ ),+ CHAR_CLIP_MISSING: recipe(+ 'CHAR_CLIP_MISSING',+ 'Author exactly the reported requested clip name using existing unique Joint_* targets.',+ motionViews,+ ),+ CHAR_CLIP_DUPLICATE: recipe(+ 'CHAR_CLIP_DUPLICATE',+ 'Keep one clip with the requested name and remove or correctly rename the duplicate; preserve requested clip names exactly.',+ motionViews,+ ),+ CHAR_CLIP_UNEXPECTED: recipe(+ 'CHAR_CLIP_UNEXPECTED',+ 'Remove the unrequested clip without changing any requested clip.',+ motionViews,+ ),+ CHAR_CLIP_DURATION: recipe(+ 'CHAR_CLIP_DURATION',+ 'Set the reported clip to one finite positive duration and keep all keys inside it.',+ motionViews,+ ),+ CHAR_ANIMATION_NONFINITE: recipe(+ 'CHAR_ANIMATION_NONFINITE',+ 'Replace only the reported non-finite key time or value with the intended finite value.',+ motionViews,+ ),+ CHAR_KEY_TIME_ORDER: recipe(+ 'CHAR_KEY_TIME_ORDER',+ 'Sort the reported track keys into strictly increasing unique times without changing their poses.',+ motionViews,+ ),+ CHAR_KEY_OUT_OF_RANGE: recipe(+ 'CHAR_KEY_OUT_OF_RANGE',+ 'Move only the reported key inside the inclusive [0, clip duration] interval.',+ motionViews,+ ),+ CHAR_TRACK_VALUE_COUNT: recipe(+ 'CHAR_TRACK_VALUE_COUNT',+ 'Provide exactly one complete value tuple for every reported key time.',+ motionViews,+ ),+ CHAR_LOOP_ENDPOINT: recipe(+ 'CHAR_LOOP_ENDPOINT',+ 'For the declared looping clip, make the reported track end pose equal its start pose; do not change one-shot clips.',+ motionViews,+ ),+ CHAR_ROOT_MOTION_BACKWARD: recipe(+ 'CHAR_ROOT_MOTION_BACKWARD',+ 'Reverse only the declared locomotion root translation so net travel is toward canonical +X.',+ motionViews,+ ),+ CHAR_ROOT_MOTION_LATERAL: recipe(+ 'CHAR_ROOT_MOTION_LATERAL',+ 'Rotate or rewrite only the declared locomotion root translation so +X travel dominates Z travel.',+ motionViews,+ ),+});++export function characterRepairRecipe(code: string): CharacterRepairRecipe | undefined {+ return (CHARACTER_REPAIR_RECIPES as Readonly<Record<string, CharacterRepairRecipe>>)[code];+}++export function withCharacterRepair(finding: QaFinding): QaFinding {+ const found = characterRepairRecipe(finding.code);+ if (!found) return finding;+ return {+ ...finding,+ repairText: finding.repairText ?? found.repairText,+ viewHints: [...new Set([...(finding.viewHints ?? []), ...found.viewHints])],+ };+}diff --git a/src/qa/character-vehicle-corpus.test.ts b/src/qa/character-vehicle-corpus.test.tsnew file mode 100644index 00000000..6ed1a461--- /dev/null+++ b/src/qa/character-vehicle-corpus.test.ts@@ -0,0 +1,220 @@+import { describe, expect, test } from 'bun:test';++import type { CharacterBodyPlan } from '../character';+import {+ createAssetIntentV1,+ type AssetIntentV1,+ type CharacterLocomotionMode,+} from '../contracts';+import { buildUserPrompt } from '../prompt';+import { evaluateCharacterQa } from './character';+import { CHARACTER_ADVISORY_QA_RULE, evaluateCharacterAdvisoryQa } from './character-advisory';+import {+ W6_CHARACTER_BODY_PLAN_COVERAGE,+ W6_CHARACTER_PROMPT_CORPUS,+ W6_CHARACTER_VEHICLE_FIXTURE_CORPUS,+ W6_VEHICLE_PROMPT_CORPUS,+} from './character-vehicle-corpus';+import { QaRegistry } from './registry';+import { evaluateVehicleQa } from './vehicle';+import { VEHICLE_W6_ADVISORY_QA_RULE, evaluateVehicleAdvisoryQa } from './vehicle-advisory';++function evaluate(+ fixture: ReturnType<(typeof W6_CHARACTER_VEHICLE_FIXTURE_CORPUS)[number]['build']>,+) {+ const context = {+ intent: fixture.intent,+ scene: fixture.scene,+ clips: fixture.clips,+ };+ return fixture.intent.category === 'character'+ ? [...evaluateCharacterQa(context), ...evaluateCharacterAdvisoryQa(context)]+ : [...evaluateVehicleQa(context), ...evaluateVehicleAdvisoryQa(context)];+}++describe('CHAR-032 / VEH-030 W6 deterministic corpus', () => {+ test('covers every requested body plan, vehicle subtype, reciprocal pair, and adversary', () => {+ expect(W6_CHARACTER_BODY_PLAN_COVERAGE).toEqual([+ 'biped',+ 'quadruped',+ 'avian',+ 'serpentine',+ 'multi-limb',+ 'wheeled',+ ]);+ expect(new Set(W6_VEHICLE_PROMPT_CORPUS.map((entry) => entry.subtype))).toEqual(+ new Set([+ 'wheeled',+ 'tracked',+ 'rail',+ 'watercraft',+ 'fixed-wing',+ 'rotorcraft',+ 'hover',+ 'walking',+ 'custom',+ ]),+ );+ expect(W6_CHARACTER_VEHICLE_FIXTURE_CORPUS).toHaveLength(40);+ const ids = new Set(W6_CHARACTER_VEHICLE_FIXTURE_CORPUS.map((entry) => entry.id));+ for (const entry of W6_CHARACTER_VEHICLE_FIXTURE_CORPUS) {+ expect(ids.has(entry.pairId), entry.id).toBe(true);+ const pair = W6_CHARACTER_VEHICLE_FIXTURE_CORPUS.find(+ (candidate) => candidate.id === entry.pairId,+ )!;+ expect(pair.pairId).toBe(entry.id);+ expect(pair.kind).not.toBe(entry.kind);+ }+ for (const id of [+ 'vehicle-offset-hub-failure',+ 'vehicle-wrong-axle-failure',+ 'vehicle-duplicate-wheel-failure',+ 'vehicle-buried-tire-failure',+ 'vehicle-sideways-body-failure',+ 'vehicle-open-track-failure',+ 'vehicle-off-center-rotor-failure',+ ]) {+ expect(ids.has(id), id).toBe(true);+ }+ });++ for (const fixture of W6_CHARACTER_VEHICLE_FIXTURE_CORPUS) {+ test(`${fixture.id} produces only its declared reciprocal expectations`, () => {+ const findings = evaluate(fixture.build());+ const codes = findings.map((finding) => finding.code);+ for (const code of fixture.expectedCodes) {+ expect(codes, `${fixture.id}:${code}`).toContain(code);+ const found = findings.find((finding) => finding.code === code)!;+ expect(found.measurement, `${fixture.id}:${code}:measurement`).toBeDefined();+ expect(found.viewHints?.length, `${fixture.id}:${code}:views`).toBeGreaterThan(0);+ }+ for (const code of fixture.forbiddenCodes) {+ expect(codes, `${fixture.id}:${code}`).not.toContain(code);+ }+ });+ }++ test('fixture findings and measurements reproduce byte-for-byte across builds', () => {+ const evidence = () =>+ JSON.stringify(+ W6_CHARACTER_VEHICLE_FIXTURE_CORPUS.map((fixture) => ({+ id: fixture.id,+ findings: evaluate(fixture.build()).map((finding) => ({+ code: finding.code,+ disposition: finding.disposition,+ affected: finding.affected,+ measurement: finding.measurement,+ viewHints: finding.viewHints,+ })),+ })),+ );+ expect(evidence()).toBe(evidence());+ });+});++describe('W6 advisory rollout boundary', () => {+ test('registry rewrites every character and vehicle heuristic to observe', () => {+ const registry = new QaRegistry([CHARACTER_ADVISORY_QA_RULE, VEHICLE_W6_ADVISORY_QA_RULE]);+ for (const fixture of W6_CHARACTER_VEHICLE_FIXTURE_CORPUS.filter(+ (entry) =>+ entry.kind === 'failure' &&+ !entry.expectedCodes.includes('CHAR_HELD_ITEM_GRIP_BREAK') &&+ !entry.expectedCodes.includes('VEH_DUPLICATE_ASSEMBLY') &&+ !entry.expectedCodes.includes('VEH_SUPPORT_SET_MISSING') &&+ !entry.expectedCodes.includes('VEH_SUPPORT_PLANE') &&+ !entry.expectedCodes.includes('VEH_WHEEL_CONCENTRICITY') &&+ !entry.expectedCodes.includes('VEH_WHEEL_AXLE_AXIS') &&+ !entry.expectedCodes.includes('VEH_CONTACT_PLANE') &&+ !entry.expectedCodes.includes('VEH_ROTOR_PIVOT'),+ )) {+ const payload = fixture.build();+ const result = registry.run({+ intent: payload.intent,+ scene: payload.scene,+ clips: payload.clips,+ });+ expect(result.findings.length, fixture.id).toBeGreaterThan(0);+ expect(+ result.findings.every((finding) => finding.disposition === 'observe'),+ fixture.id,+ ).toBe(true);+ expect(+ result.decisions.every((decision) => decision.mode === 'observe'),+ fixture.id,+ ).toBe(true);+ }+ });++ test('only explicit grip, duplicate-corner, and declared support contracts block', () => {+ for (const [id, code] of [+ ['character-grip-motion-failure', 'CHAR_HELD_ITEM_GRIP_BREAK'],+ ['vehicle-duplicate-wheel-failure', 'VEH_DUPLICATE_ASSEMBLY'],+ ['vehicle-support-set-failure', 'VEH_SUPPORT_SET_MISSING'],+ ['vehicle-support-plane-failure', 'VEH_SUPPORT_PLANE'],+ ] as const) {+ const fixture = W6_CHARACTER_VEHICLE_FIXTURE_CORPUS.find((entry) => entry.id === id)!;+ const finding = evaluate(fixture.build()).find((entry) => entry.code === code)!;+ expect(finding.disposition, id).toBe('block');+ expect(finding.repairText?.length, id).toBeGreaterThan(50);+ }+ });+});++describe('CHAR-031/032 and VEH-030 resolved prompt corpus', () => {+ const locomotion = (subtype: string, motion: 'static' | 'animated'): CharacterLocomotionMode => {+ if (motion === 'static') return 'stationary';+ if (subtype === 'avian') return 'fly';+ if (subtype === 'serpentine') return 'slither';+ if (subtype === 'wheeled') return 'roll';+ return 'walk';+ };++ for (const entry of W6_CHARACTER_PROMPT_CORPUS) {+ test(`${entry.id} injects only its resolved body-plan contract`, () => {+ const movement = locomotion(entry.subtype, entry.motion);+ const intent = createAssetIntentV1({+ category: 'character',+ character: {+ bodyPlan: entry.subtype as CharacterBodyPlan,+ grounded: movement !== 'fly',+ locomotion: movement,+ gait: movement,+ rootMotion: 'inPlace',+ clips: entry.motion === 'animated' ? [{ name: movement, playback: 'loop' }] : [],+ },+ });+ const prompt = buildUserPrompt({+ prompt: entry.prompt,+ category: 'character',+ mode: 'glb',+ intent,+ includeAnimation: entry.motion === 'animated',+ });+ for (const expected of entry.expectedGuidance) expect(prompt).toContain(expected);+ for (const other of ['BIPED', 'QUADRUPED', 'AVIAN', 'SERPENTINE', 'MULTI-LIMB']) {+ if (other === entry.subtype.toUpperCase()) continue;+ expect(prompt).not.toContain(`Resolved body plan: ${other}.`);+ }+ });+ }++ for (const entry of W6_VEHICLE_PROMPT_CORPUS) {+ test(`${entry.id} injects subtype-specific vehicle guidance`, () => {+ const intent = createAssetIntentV1({+ category: 'vehicle',+ subtype: entry.subtype,+ vehicle: { subtype: entry.subtype as NonNullable<AssetIntentV1['vehicle']>['subtype'] },+ });+ const prompt = buildUserPrompt({+ prompt: entry.prompt,+ category: 'vehicle',+ mode: 'glb',+ intent,+ includeAnimation: entry.motion === 'animated',+ });+ expect(prompt).toContain('## Resolved Vehicle Contract');+ for (const expected of entry.expectedGuidance) expect(prompt).toContain(expected);+ expect(prompt).not.toContain('## Resolved Character Contract');+ });+ }+});diff --git a/src/qa/character-vehicle-corpus.ts b/src/qa/character-vehicle-corpus.tsnew file mode 100644index 00000000..851186d1--- /dev/null+++ b/src/qa/character-vehicle-corpus.ts@@ -0,0 +1,802 @@+import * as THREE from 'three';++import {+ BIPED_RIG_PRESET_V1,+ createCharacterRigGraphV1,+ stampCharacterJointDescriptorV1,+ stampCharacterRigGraphV1,+ type CharacterBodyPlan,+ type CharacterRigGraphV1,+} from '../character';+import { createAssetIntentV1, stampSemanticMetadataV1, type AssetIntentV1 } from '../contracts';+import {+ createVehicleFrame,+ createWheelAssembly,+ createWheelGeometrySet,+ type WheelAssemblyResult,+} from '../vehicle';++export interface W6CharacterVehicleCorpusPayload {+ intent: AssetIntentV1;+ scene: THREE.Object3D;+ clips: THREE.AnimationClip[];+}++export interface W6CharacterVehicleCorpusCase {+ id: string;+ pairId: string;+ kind: 'failure' | 'control';+ category: 'character' | 'vehicle';+ description: string;+ expectedCodes: readonly string[];+ forbiddenCodes: readonly string[];+ build: () => W6CharacterVehicleCorpusPayload;+}++export interface W6PromptCorpusCase {+ id: string;+ category: 'character' | 'vehicle';+ subtype: string;+ motion: 'static' | 'animated';+ prompt: string;+ expectedGuidance: readonly string[];+}++interface RigFixture {+ root: THREE.Object3D;+ byRole: Map<string, THREE.Object3D>;+}++function instantiateGraph(graph: CharacterRigGraphV1): RigFixture {+ const root = new THREE.Object3D();+ root.name = 'Character';+ stampCharacterRigGraphV1(root, graph);+ const byRole = new Map<string, THREE.Object3D>();+ for (const descriptor of graph.joints) {+ const node = new THREE.Object3D();+ node.name = `Joint_${descriptor.role.replace(/[^A-Za-z0-9]+/g, '_')}`;+ node.position.fromArray(descriptor.rest.translation);+ node.quaternion.fromArray(descriptor.rest.rotation);+ node.scale.fromArray(descriptor.rest.scale);+ stampCharacterJointDescriptorV1(node, descriptor);+ (descriptor.parentRole ? byRole.get(descriptor.parentRole) : root)?.add(node);+ byRole.set(descriptor.role, node);+ }+ return { root, byRole };+}++function characterIntent(+ options: {+ grounded?: boolean;+ locomotion?: 'stationary' | 'walk' | 'run';+ clips?: readonly { name: string; playback: 'loop' | 'oneShot' }[];+ heldItem?: boolean;+ } = {},+): AssetIntentV1 {+ return createAssetIntentV1({+ category: 'character',+ capabilities: ['articulated'],+ character: {+ bodyPlan: 'biped',+ grounded: options.grounded ?? false,+ locomotion: options.locomotion ?? 'stationary',+ gait: options.locomotion ?? 'none',+ rootMotion: 'inPlace',+ clips: options.clips ?? [],+ heldItem: options.heldItem ? { required: true, attachmentRole: 'grip' } : { required: false },+ },+ });+}++function characterStaticFixture(+ defect: 'none' | 'symmetry' | 'order' | 'forward',+): W6CharacterVehicleCorpusPayload {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ if (defect === 'symmetry') rig.byRole.get('knee.right')!.position.x = 0.5;+ if (defect === 'order') rig.byRole.get('knee.left')!.position.y = 0.2;+ if (defect === 'forward') rig.byRole.get('head')!.rotation.y = Math.PI;+ return { intent: characterIntent(), scene: rig.root, clips: [] };+}++function loopPositionTrack(+ node: THREE.Object3D,+ axis: 'x' | 'z',+ middle: number,+): THREE.VectorKeyframeTrack {+ const base = node.position.clone();+ const values = [base.clone(), base.clone(), base.clone()];+ values[1]![axis] += middle;+ return new THREE.VectorKeyframeTrack(+ `${node.name}.position`,+ [0, 0.5, 1],+ values.flatMap((value) => value.toArray()),+ );+}++function characterEnergyFixture(lateral: boolean): W6CharacterVehicleCorpusPayload {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ const knee = rig.byRole.get('knee.left')!;+ const clip = new THREE.AnimationClip('Walk', 1, [+ loopPositionTrack(knee, lateral ? 'z' : 'x', 0.35),+ ]);+ return {+ intent: characterIntent({ locomotion: 'walk', clips: [{ name: 'Walk', playback: 'loop' }] }),+ scene: rig.root,+ clips: [clip],+ };+}++function characterPhaseFixture(samePhase: boolean): W6CharacterVehicleCorpusPayload {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ const left = rig.byRole.get('ankle.left')!;+ const right = rig.byRole.get('ankle.right')!;+ const clip = new THREE.AnimationClip('Run', 1, [+ loopPositionTrack(left, 'x', 0.3),+ loopPositionTrack(right, 'x', samePhase ? 0.3 : -0.3),+ ]);+ return {+ intent: characterIntent({ locomotion: 'run', clips: [{ name: 'Run', playback: 'loop' }] }),+ scene: rig.root,+ clips: [clip],+ };+}++function characterBendFixture(reverse: boolean): W6CharacterVehicleCorpusPayload {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ const knee = rig.byRole.get('knee.left')!;+ const middle = new THREE.Quaternion().setFromAxisAngle(+ new THREE.Vector3(0, 0, 1),+ THREE.MathUtils.degToRad(reverse ? -45 : 45),+ );+ const identity = new THREE.Quaternion();+ const clip = new THREE.AnimationClip('Walk', 1, [+ new THREE.QuaternionKeyframeTrack(+ `${knee.name}.quaternion`,+ [0, 0.5, 1],+ [...identity.toArray(), ...middle.toArray(), ...identity.toArray()],+ ),+ ]);+ return {+ intent: characterIntent({ locomotion: 'walk', clips: [{ name: 'Walk', playback: 'loop' }] }),+ scene: rig.root,+ clips: [clip],+ };+}++function characterGripFixture(breaksGrip: boolean): W6CharacterVehicleCorpusPayload {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ const item = new THREE.Object3D();+ item.name = 'HeldLantern';+ item.position.set(0.1, 0, 0);+ item.userData['kilnHeldItem'] = true;+ stampSemanticMetadataV1(item, { roles: ['character.held-item'] });+ rig.byRole.get('wrist.left')!.add(item);+ const clips = breaksGrip+ ? [new THREE.AnimationClip('Action', 1, [loopPositionTrack(item, 'x', 0.25)])]+ : [new THREE.AnimationClip('Action', 1, [])];+ return {+ intent: characterIntent({ clips: [{ name: 'Action', playback: 'loop' }], heldItem: true }),+ scene: rig.root,+ clips,+ };+}++function characterFootSlideFixture(slides: boolean): W6CharacterVehicleCorpusPayload {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ const ankle = rig.byRole.get('ankle.left')!;+ const clips = slides+ ? [new THREE.AnimationClip('Walk', 1, [loopPositionTrack(ankle, 'x', 0.2)])]+ : [new THREE.AnimationClip('Walk', 1, [])];+ return {+ intent: characterIntent({+ grounded: true,+ locomotion: 'walk',+ clips: [{ name: 'Walk', playback: 'loop' }],+ }),+ scene: rig.root,+ clips,+ };+}++const tireMaterial = new THREE.MeshStandardMaterial({ color: 0x202124 });+const metalMaterial = new THREE.MeshStandardMaterial({ color: 0x8b949e });+const bodyMaterial = new THREE.MeshStandardMaterial({ color: 0x415a77 });++interface CarFixture {+ root: THREE.Object3D;+ chassis: THREE.Mesh;+ wheels: WheelAssemblyResult[];+ intent: AssetIntentV1;+}++function carFixture(sideways = false): CarFixture {+ const frame = createVehicleFrame('Car', {+ axles: [+ { id: 'front', position: [1.2, 0.5, 0] },+ { id: 'rear', position: [-1.2, 0.5, 0] },+ ],+ });+ const chassis = new THREE.Mesh(+ sideways ? new THREE.BoxGeometry(1.2, 0.5, 4) : new THREE.BoxGeometry(3.4, 0.5, 1.2),+ bodyMaterial,+ );+ chassis.name = 'Vehicle_Chassis';+ chassis.position.set(0, 1, 0);+ stampSemanticMetadataV1(chassis, { roles: ['vehicle.chassis'] });+ frame.root.add(chassis);+ const geometry = createWheelGeometrySet(0.5, 0.2);+ const wheels: WheelAssemblyResult[] = [];+ for (const [index, x] of [+ ['front', 1.2],+ ['rear', -1.2],+ ] as const) {+ for (const side of ['left', 'right'] as const) {+ wheels.push(+ createWheelAssembly(+ 'Wheel',+ { tire: tireMaterial, rim: metalMaterial },+ {+ radius: 0.5,+ width: 0.2,+ side,+ index,+ position: [x, 0.5, side === 'left' ? -0.85 : 0.85],+ steering: index === 'front',+ geometries: geometry,+ parent: frame.root,+ },+ ),+ );+ }+ }+ return {+ root: frame.root,+ chassis,+ wheels,+ intent: createAssetIntentV1({+ category: 'vehicle',+ subtype: 'wheeled',+ vehicle: {+ subtype: 'wheeled',+ wheelCount: 4,+ axleCount: 2,+ steering: 'front',+ supportPolicy: 'grounded',+ },+ }),+ };+}++function carPayload(+ defect:+ | 'none'+ | 'offset-hub'+ | 'wrong-axle'+ | 'duplicate'+ | 'buried'+ | 'symmetry'+ | 'penetration'+ | 'fender-overlap'+ | 'sideways',+): W6CharacterVehicleCorpusPayload {+ const car = carFixture(defect === 'sideways');+ if (defect === 'offset-hub') car.wheels[0]!.hub.position.y = 0.18;+ if (defect === 'wrong-axle') car.wheels[0]!.spinPivot.rotation.y = Math.PI / 2;+ if (defect === 'buried') car.wheels[0]!.spinPivot.position.y = 0.2;+ if (defect === 'symmetry') car.wheels[1]!.spinPivot.position.x += 0.25;+ if (defect === 'penetration') {+ car.wheels[0]!.spinPivot.position.y = 0.85;+ car.chassis.position.z = -0.55;+ }+ if (defect === 'fender-overlap') {+ const fender = new THREE.Mesh(new THREE.BoxGeometry(0.8, 0.4, 0.4), bodyMaterial);+ fender.name = 'FrontLeftFender';+ fender.position.set(1.2, 0.8, -0.85);+ stampSemanticMetadataV1(fender, { roles: ['vehicle.fender.front.left'] });+ car.root.add(fender);+ }+ if (defect === 'duplicate') {+ car.wheels[3]!.root.removeFromParent();+ car.wheels.pop();+ car.wheels.push(+ createWheelAssembly(+ 'DuplicateWheel',+ { tire: tireMaterial, rim: metalMaterial },+ {+ radius: 0.5,+ width: 0.2,+ side: 'left',+ index: 'front',+ position: [1.2, 0.5, -0.85],+ steering: true,+ parent: car.root,+ },+ ),+ );+ }+ return { intent: car.intent, scene: car.root, clips: [] };+}++function wideFixedWingPayload(): W6CharacterVehicleCorpusPayload {+ const frame = createVehicleFrame('WideFixedWing');+ const wing = new THREE.Mesh(new THREE.BoxGeometry(3, 0.15, 8), bodyMaterial);+ wing.name = 'WideWing';+ wing.position.y = 1;+ stampSemanticMetadataV1(wing, { roles: ['vehicle.wing.main'] });+ frame.root.add(wing);+ return {+ intent: createAssetIntentV1({+ category: 'vehicle',+ subtype: 'fixed-wing',+ vehicle: { subtype: 'fixed-wing', propulsionAssemblies: [] },+ }),+ scene: frame.root,+ clips: [],+ };+}++function rotorPayload(offCenter: boolean): W6CharacterVehicleCorpusPayload {+ const frame = createVehicleFrame('Rotorcraft');+ const pivot = new THREE.Object3D();+ pivot.name = 'MainRotorPivot';+ pivot.position.set(0, 1.5, 0);+ stampSemanticMetadataV1(pivot, {+ roles: ['propulsion.pivot.main'],+ frames: [{ id: 'propulsion-axis.+y', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ });+ const rotor = new THREE.Mesh(new THREE.BoxGeometry(3, 0.05, 0.12), metalMaterial);+ rotor.name = 'MainRotor';+ rotor.position.x = offCenter ? 0.25 : 0;+ stampSemanticMetadataV1(rotor, { roles: ['propulsion.rotor.main'] });+ pivot.add(rotor);+ frame.root.add(pivot);+ return {+ intent: createAssetIntentV1({ category: 'vehicle', subtype: 'rotorcraft' }),+ scene: frame.root,+ clips: [],+ };+}++function trackLoop(name: string, side: 'left' | 'right', open: boolean): THREE.Object3D {+ const loop = new THREE.Object3D();+ loop.name = name;+ loop.position.set(0, 1.15, side === 'left' ? -0.7 : 0.7);+ loop.userData['kilnTrackLoopClosed'] = !open;+ stampSemanticMetadataV1(loop, { roles: [`track.loop.${side}`, `support.track.${side}`] });+ const geometry = open+ ? new THREE.PlaneGeometry(2, 1, 2, 1)+ : new THREE.TorusGeometry(1, 0.15, 8, 24);+ const mesh = new THREE.Mesh(geometry, tireMaterial);+ mesh.name = `${name}_Mesh`;+ loop.add(mesh);+ return loop;+}++function trackedPayload(+ options: {+ open?: boolean;+ escapedWheel?: boolean;+ uneven?: boolean;+ missingSupport?: boolean;+ } = {},+): W6CharacterVehicleCorpusPayload {+ const frame = createVehicleFrame('TrackedVehicle');+ const left = trackLoop('LeftTrack', 'left', options.open ?? false);+ const right = trackLoop('RightTrack', 'right', false);+ if (options.uneven) right.position.y += 0.2;+ if (options.missingSupport) {+ stampSemanticMetadataV1(left, { roles: ['track.loop.left'] });+ stampSemanticMetadataV1(right, { roles: ['track.loop.right'] });+ }+ frame.root.add(left, right);+ for (const [side, z] of [+ ['left', -0.7],+ ['right', 0.7],+ ] as const) {+ const roadWheel = new THREE.Mesh(+ new THREE.CylinderGeometry(0.35, 0.35, 0.16, 12).rotateX(Math.PI / 2),+ metalMaterial,+ );+ roadWheel.name = `RoadWheel_${side}`;+ roadWheel.position.set(options.escapedWheel && side === 'left' ? 2.5 : 0, 1.15, z);+ stampSemanticMetadataV1(roadWheel, { roles: [`track.road-wheel.${side}.1`] });+ frame.root.add(roadWheel);+ }+ return {+ intent: createAssetIntentV1({+ category: 'vehicle',+ subtype: 'tracked',+ vehicle: { subtype: 'tracked', supportPolicy: 'grounded' },+ }),+ scene: frame.root,+ clips: [],+ };+}++function pair(+ base: string,+ category: 'character' | 'vehicle',+ description: string,+ code: string,+ failure: () => W6CharacterVehicleCorpusPayload,+ control: () => W6CharacterVehicleCorpusPayload,+): W6CharacterVehicleCorpusCase[] {+ const failureId = `${base}-failure`;+ const controlId = `${base}-control`;+ return [+ {+ id: failureId,+ pairId: controlId,+ kind: 'failure',+ category,+ description,+ expectedCodes: [code],+ forbiddenCodes: [],+ build: failure,+ },+ {+ id: controlId,+ pairId: failureId,+ kind: 'control',+ category,+ description: `Known-good reciprocal control for ${description}`,+ expectedCodes: [],+ forbiddenCodes: [code],+ build: control,+ },+ ];+}++/** Varied model-independent prompts; no provider/model roster is embedded. */+export const W6_CHARACTER_PROMPT_CORPUS: readonly W6PromptCorpusCase[] = Object.freeze([+ {+ id: 'character-biped-static',+ category: 'character',+ subtype: 'biped',+ motion: 'static',+ prompt: 'A balanced biped courier in a readable neutral rest pose, facing +X.',+ expectedGuidance: ['BIPED', '+X'],+ },+ {+ id: 'character-biped-animated',+ category: 'character',+ subtype: 'biped',+ motion: 'animated',+ prompt: 'A biped runner with an in-place looping run and alternating planted feet.',+ expectedGuidance: ['BIPED', 'run'],+ },+ {+ id: 'character-quadruped-static',+ category: 'character',+ subtype: 'quadruped',+ motion: 'static',+ prompt: 'A grounded four-legged hound with all paws at Y=0 and muzzle facing +X.',+ expectedGuidance: ['QUADRUPED', 'muzzle'],+ },+ {+ id: 'character-quadruped-animated',+ category: 'character',+ subtype: 'quadruped',+ motion: 'animated',+ prompt: 'A quadruped walking forward with four semantic paw chains and stable contacts.',+ expectedGuidance: ['QUADRUPED', 'walk'],+ },+ {+ id: 'character-avian-static',+ category: 'character',+ subtype: 'avian',+ motion: 'static',+ prompt: 'A perched avian character with paired wing chains and a +X beak marker.',+ expectedGuidance: ['AVIAN', 'wing'],+ },+ {+ id: 'character-avian-animated',+ category: 'character',+ subtype: 'avian',+ motion: 'animated',+ prompt: 'An avian flapping loop with opposed wings and no unintended root travel.',+ expectedGuidance: ['AVIAN', 'flight'],+ },+ {+ id: 'character-serpentine-static',+ category: 'character',+ subtype: 'serpentine',+ motion: 'static',+ prompt: 'A serpentine creature built as one axial graph with no invented humanoid limbs.',+ expectedGuidance: ['SERPENTINE', 'axial'],+ },+ {+ id: 'character-serpentine-animated',+ category: 'character',+ subtype: 'serpentine',+ motion: 'animated',+ prompt: 'A +X slither loop with sequential spine phases and stable ground contacts.',+ expectedGuidance: ['SERPENTINE', 'slither'],+ },+ {+ id: 'character-multilimb-static',+ category: 'character',+ subtype: 'multi-limb',+ motion: 'static',+ prompt: 'A six-limbed original creature with six unique terminal roles.',+ expectedGuidance: ['MULTI-LIMB', 'unique'],+ },+ {+ id: 'character-multilimb-animated',+ category: 'character',+ subtype: 'multi-limb',+ motion: 'animated',+ prompt: 'A six-limbed locomotion loop preserving every declared branch.',+ expectedGuidance: ['MULTI-LIMB', 'branch'],+ },+ {+ id: 'character-wheeled-static',+ category: 'character',+ subtype: 'wheeled',+ motion: 'static',+ prompt: 'A wheeled robot character with a semantic core and separate arm graph.',+ expectedGuidance: ['WHEELED CHARACTER', 'wheel'],+ },+ {+ id: 'character-wheeled-animated',+ category: 'character',+ subtype: 'wheeled',+ motion: 'animated',+ prompt: 'A wheeled robot rolling +X while waving one articulated arm.',+ expectedGuidance: ['WHEELED CHARACTER', '+X'],+ },+]);++export const W6_VEHICLE_PROMPT_CORPUS: readonly W6PromptCorpusCase[] = Object.freeze([+ {+ id: 'vehicle-wheeled',+ category: 'vehicle',+ subtype: 'wheeled',+ motion: 'animated',+ prompt: 'A four-wheel car with front steering, facing +X.',+ expectedGuidance: ['WHEELED', 'createWheelAssembly'],+ },+ {+ id: 'vehicle-tracked',+ category: 'vehicle',+ subtype: 'tracked',+ motion: 'animated',+ prompt: 'A tracked utility carrier with two closed loops.',+ expectedGuidance: ['TRACKED', 'track.loop'],+ },+ {+ id: 'vehicle-rail',+ category: 'vehicle',+ subtype: 'rail',+ motion: 'animated',+ prompt: 'A compact rail maintenance car.',+ expectedGuidance: ['RAIL', 'rail-wheel'],+ },+ {+ id: 'vehicle-watercraft',+ category: 'vehicle',+ subtype: 'watercraft',+ motion: 'animated',+ prompt: 'A small patrol boat with propeller and rudder.',+ expectedGuidance: ['WATERCRAFT', 'Do not add wheels'],+ },+ {+ id: 'vehicle-fixed-wing',+ category: 'vehicle',+ subtype: 'fixed-wing',+ motion: 'animated',+ prompt: 'A propeller aircraft with wide wings.',+ expectedGuidance: ['FIXED-WING', 'Wingspan'],+ },+ {+ id: 'vehicle-rotorcraft',+ category: 'vehicle',+ subtype: 'rotorcraft',+ motion: 'animated',+ prompt: 'A utility helicopter on two skids.',+ expectedGuidance: ['ROTORCRAFT', 'rotor pivot'],+ },+ {+ id: 'vehicle-hover',+ category: 'vehicle',+ subtype: 'hover',+ motion: 'static',+ prompt: 'A small hover courier with four pads.',+ expectedGuidance: ['HOVER', 'hover pads'],+ },+ {+ id: 'vehicle-walking',+ category: 'vehicle',+ subtype: 'walking',+ motion: 'animated',+ prompt: 'A four-legged walking transport.',+ expectedGuidance: ['WALKING', 'load-bearing leg'],+ },+ {+ id: 'vehicle-custom',+ category: 'vehicle',+ subtype: 'custom',+ motion: 'static',+ prompt: 'A custom fantastical transport using declared supports only.',+ expectedGuidance: ['CUSTOM', 'declared support'],+ },+]);++export const W6_CHARACTER_VEHICLE_FIXTURE_CORPUS: readonly W6CharacterVehicleCorpusCase[] =+ Object.freeze([+ ...pair(+ 'character-bilateral-symmetry',+ 'character',+ 'Swapped or asymmetric bilateral joints.',+ 'CHAR_REST_BILATERAL_SYMMETRY',+ () => characterStaticFixture('symmetry'),+ () => characterStaticFixture('none'),+ ),+ ...pair(+ 'character-chain-order',+ 'character',+ 'Inverted hip-knee-ankle rest ordering.',+ 'CHAR_REST_CHAIN_ORDER',+ () => characterStaticFixture('order'),+ () => characterStaticFixture('none'),+ ),+ ...pair(+ 'character-forward-marker',+ 'character',+ 'Head marker facing away from +X.',+ 'CHAR_FORWARD_MARKER',+ () => characterStaticFixture('forward'),+ () => characterStaticFixture('none'),+ ),+ ...pair(+ 'character-lateral-energy',+ 'character',+ 'Lateral-dominant locomotion chain.',+ 'CHAR_GAIT_LATERAL_ENERGY',+ () => characterEnergyFixture(true),+ () => characterEnergyFixture(false),+ ),+ ...pair(+ 'character-leg-phase',+ 'character',+ 'Same-phase left/right biped legs.',+ 'CHAR_GAIT_SAME_PHASE',+ () => characterPhaseFixture(true),+ () => characterPhaseFixture(false),+ ),+ ...pair(+ 'character-bend-direction',+ 'character',+ 'Knee flexion opposite its declared bend axis.',+ 'CHAR_JOINT_REVERSE_BEND',+ () => characterBendFixture(true),+ () => characterBendFixture(false),+ ),+ ...pair(+ 'character-grip-motion',+ 'character',+ 'Held item breaks its declared grip while animated.',+ 'CHAR_HELD_ITEM_GRIP_BREAK',+ () => characterGripFixture(true),+ () => characterGripFixture(false),+ ),+ ...pair(+ 'character-foot-slide',+ 'character',+ 'Planted foot slides horizontally.',+ 'CHAR_FOOT_SLIDE',+ () => characterFootSlideFixture(true),+ () => characterFootSlideFixture(false),+ ),+ ...pair(+ 'vehicle-offset-hub',+ 'vehicle',+ 'Hub center is offset from its tire and rim.',+ 'VEH_WHEEL_CONCENTRICITY',+ () => carPayload('offset-hub'),+ () => carPayload('none'),+ ),+ ...pair(+ 'vehicle-wrong-axle',+ 'vehicle',+ 'Wheel spin axis is not vehicle-local +Z.',+ 'VEH_WHEEL_AXLE_AXIS',+ () => carPayload('wrong-axle'),+ () => carPayload('none'),+ ),+ ...pair(+ 'vehicle-duplicate-wheel',+ 'vehicle',+ 'One corner contains two semantic wheel assemblies.',+ 'VEH_DUPLICATE_ASSEMBLY',+ () => carPayload('duplicate'),+ () => carPayload('none'),+ ),+ ...pair(+ 'vehicle-buried-tire',+ 'vehicle',+ 'Load-bearing tire is buried below Y=0.',+ 'VEH_CONTACT_PLANE',+ () => carPayload('buried'),+ () => carPayload('none'),+ ),+ ...pair(+ 'vehicle-sideways-body',+ 'vehicle',+ 'Longitudinal wheeled body is Z-dominant while wide fixed-wing bounds are exempt.',+ 'VEH_ORIENTATION_SIDEWAYS',+ () => carPayload('sideways'),+ wideFixedWingPayload,+ ),+ ...pair(+ 'vehicle-open-track',+ 'vehicle',+ 'Track loop has localized open boundary edges.',+ 'VEH_TRACK_LOOP_OPEN',+ () => trackedPayload({ open: true }),+ () => trackedPayload(),+ ),+ ...pair(+ 'vehicle-off-center-rotor',+ 'vehicle',+ 'Rotor geometry is offset from its declared pivot.',+ 'VEH_ROTOR_PIVOT',+ () => rotorPayload(true),+ () => rotorPayload(false),+ ),+ ...pair(+ 'vehicle-bilateral-symmetry',+ 'vehicle',+ 'Wheel pair has asymmetric center placement.',+ 'VEH_BILATERAL_SYMMETRY',+ () => carPayload('symmetry'),+ () => carPayload('none'),+ ),+ ...pair(+ 'vehicle-chassis-penetration',+ 'vehicle',+ 'Tire penetrates non-fender chassis geometry while intentional fender overlap is allowed.',+ 'VEH_WHEEL_CHASSIS_PENETRATION',+ () => carPayload('penetration'),+ () => carPayload('fender-overlap'),+ ),+ ...pair(+ 'vehicle-support-set',+ 'vehicle',+ 'Declared tracked support semantics are missing.',+ 'VEH_SUPPORT_SET_MISSING',+ () => trackedPayload({ missingSupport: true }),+ () => trackedPayload(),+ ),+ ...pair(+ 'vehicle-support-plane',+ 'vehicle',+ 'Non-wheel support sets do not share one contact plane.',+ 'VEH_SUPPORT_PLANE',+ () => trackedPayload({ uneven: true }),+ () => trackedPayload(),+ ),+ ...pair(+ 'vehicle-track-containment',+ 'vehicle',+ 'Road wheel escapes its declared track loop.',+ 'VEH_TRACK_ROAD_WHEEL_ESCAPED',+ () => trackedPayload({ escapedWheel: true }),+ () => trackedPayload(),+ ),+ ]);++export const W6_CHARACTER_BODY_PLAN_COVERAGE: readonly CharacterBodyPlan[] = Object.freeze(+ W6_CHARACTER_PROMPT_CORPUS.map((entry) => entry.subtype as CharacterBodyPlan).filter(+ (value, index, all) => all.indexOf(value) === index,+ ),+);++export const W6_CUSTOM_GRAPH_CONTROL = createCharacterRigGraphV1({+ bodyPlan: 'serpentine',+ joints: BIPED_RIG_PRESET_V1.joints.slice(0, 1).map((joint) => ({+ ...joint,+ role: 'spine.0',+ aliases: [],+ })),+});diff --git a/src/qa/character.test.ts b/src/qa/character.test.tsnew file mode 100644index 00000000..b2aafeaf--- /dev/null+++ b/src/qa/character.test.ts@@ -0,0 +1,418 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import {+ BIPED_RIG_PRESET_V1,+ QUADRUPED_RIG_PRESET_V1,+ createCharacterJointDescriptorV1,+ createCharacterRigGraphV1,+ createJointChain,+ stampCharacterJointDescriptorV1,+ stampCharacterRigGraphV1,+ type CharacterBodyPlan,+ type CharacterRigGraphV1,+} from '../character';+import { createAssetIntentV1, stampSemanticMetadataV1, type AssetIntentV1 } from '../contracts';+import { evaluateCharacterQa, sampleCharacterAnimation } from './character';++interface InstantiatedRig {+ root: THREE.Object3D;+ byRole: Map<string, THREE.Object3D>;+}++function instantiateGraph(graph: CharacterRigGraphV1, name = 'Character'): InstantiatedRig {+ const root = new THREE.Object3D();+ root.name = name;+ stampCharacterRigGraphV1(root, graph);+ const byRole = new Map<string, THREE.Object3D>();+ for (const descriptor of graph.joints) {+ const node = new THREE.Object3D();+ node.name = `Joint_${descriptor.role.replace(/[^A-Za-z0-9]+/g, '_')}`;+ node.position.fromArray(descriptor.rest.translation);+ node.quaternion.fromArray(descriptor.rest.rotation);+ node.scale.fromArray(descriptor.rest.scale);+ stampCharacterJointDescriptorV1(node, descriptor);+ const parent = descriptor.parentRole ? byRole.get(descriptor.parentRole) : root;+ if (!parent) throw new Error(`fixture parent ${descriptor.parentRole} missing`);+ parent.add(node);+ byRole.set(descriptor.role, node);+ }+ return { root, byRole };+}++function intent(+ options: {+ bodyPlan?: CharacterBodyPlan;+ articulated?: boolean;+ grounded?: boolean;+ rootMotion?: 'inPlace' | 'forward';+ locomotion?: 'stationary' | 'walk' | 'run' | 'fly' | 'swim' | 'slither' | 'roll' | 'custom';+ clips?: Array<{ name: string; playback: 'loop' | 'oneShot' }>;+ heldItem?: { required: boolean; attachmentRole: string };+ } = {},+): AssetIntentV1 {+ return createAssetIntentV1({+ category: 'character',+ capabilities: [+ ...(options.articulated === false ? [] : ['articulated' as const]),+ ...(options.grounded ? ['grounded' as const] : []),+ ],+ character: {+ bodyPlan: options.bodyPlan ?? 'biped',+ grounded: options.grounded ?? false,+ locomotion: options.locomotion ?? 'walk',+ rootMotion: options.rootMotion ?? 'inPlace',+ clips: options.clips ?? [],+ heldItem: options.heldItem ?? { required: false, attachmentRole: 'grip' },+ },+ });+}++function findings(+ trusted: AssetIntentV1,+ scene?: THREE.Object3D,+ clips: readonly THREE.AnimationClip[] = [],+) {+ return evaluateCharacterQa({ intent: trusted, scene, clips });+}++function codes(values: ReturnType<typeof findings>): string[] {+ return values.map((finding) => finding.code);+}++function positionClip(+ name: string,+ nodeName: string,+ end: [number, number, number],+ duration = 1,+): THREE.AnimationClip {+ return new THREE.AnimationClip(name, duration, [+ new THREE.VectorKeyframeTrack(`${nodeName}.position`, [0, duration], [0, 0, 0, ...end]),+ ]);+}++describe('W4 explicit character contract pass controls', () => {+ test('complete biped passes hierarchy, roles, contacts, grip, clips, and in-place policy', () => {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ const item = new THREE.Object3D();+ item.name = 'HeldLantern';+ stampSemanticMetadataV1(item, { roles: ['character.held-item'] });+ rig.byRole.get('wrist.right')!.add(item);+ const trusted = intent({+ grounded: true,+ rootMotion: 'inPlace',+ clips: [+ { name: 'Idle', playback: 'loop' },+ { name: 'Impact', playback: 'oneShot' },+ ],+ heldItem: { required: true, attachmentRole: 'grip' },+ });+ expect(+ findings(trusted, rig.root, [+ positionClip('Idle', 'Character', [0, 0, 0]),+ positionClip('Impact', 'Character', [0.2, 0, 0]),+ ]),+ ).toEqual([]);+ });++ test('complete quadruped passes four chains, contacts, and exact walk clip', () => {+ const rig = instantiateGraph(QUADRUPED_RIG_PRESET_V1);+ const trusted = intent({+ bodyPlan: 'quadruped',+ grounded: true,+ clips: [{ name: 'Walk', playback: 'loop' }],+ });+ expect(findings(trusted, rig.root, [positionClip('Walk', 'Character', [0, 0, 0])])).toEqual([]);+ });+});++describe('CHAR-008–012 exact semantic rig validation', () => {+ test('duplicate Joint_* names block before export and report both exact paths', () => {+ const root = new THREE.Object3D();+ root.name = 'Character';+ const first = new THREE.Object3D();+ first.name = 'Joint_KneeL';+ const second = new THREE.Object3D();+ second.name = 'Joint_KneeL';+ root.add(first, second);+ const result = findings(intent({ articulated: false }), root);+ const duplicate = result.find(+ (finding) => finding.code === 'CHAR_DUPLICATE_ANIMATED_NODE_NAME',+ )!;+ expect(duplicate.message).toContain('Character[0]/Joint_KneeL[0]');+ expect(duplicate.message).toContain('Character[0]/Joint_KneeL[1]');+ expect(duplicate.measurement).toEqual({+ name: 'animatedNodeNameCount',+ actual: 2,+ expected: 1,+ });+ });++ test('broken declared adjacency reports the exact child path and parent edge', () => {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ const knee = rig.byRole.get('knee.left')!;+ rig.root.add(knee);+ const result = findings(intent(), rig.root);+ const edge = result.find(+ (finding) =>+ finding.code === 'CHAR_PARENT_EDGE' && finding.measurement?.expected === 'hip.left',+ )!;+ expect(edge.affected?.nodePath).toContain('/Joint_knee_left[');+ expect(edge.measurement).toEqual({+ name: 'parentRole',+ actual: 'Character',+ expected: 'hip.left',+ });+ expect(edge.repairText).toContain('Reparent only the reported joint');+ expect(edge.viewHints).toEqual(+ expect.arrayContaining(['character.skeleton.front', 'character.skeleton.right']),+ );+ });++ test('explicit biped requires paired arm/leg roles; static biped does not', () => {+ const incomplete = createCharacterRigGraphV1({+ bodyPlan: 'biped',+ joints: BIPED_RIG_PRESET_V1.joints.filter((joint) => joint.role !== 'wrist.right'),+ });+ const rig = instantiateGraph(incomplete);+ expect(codes(findings(intent(), rig.root))).toContain('CHAR_BIPED_REQUIRED_ROLE');+ expect(codes(findings(intent({ articulated: false }), rig.root))).not.toContain(+ 'CHAR_BIPED_REQUIRED_ROLE',+ );+ });++ test('explicit quadruped requires all four limb chains plus spine/neck/head', () => {+ const incomplete = createCharacterRigGraphV1({+ bodyPlan: 'quadruped',+ joints: QUADRUPED_RIG_PRESET_V1.joints.filter((joint) => joint.role !== 'paw.hind.right'),+ });+ const rig = instantiateGraph(incomplete);+ const result = findings(intent({ bodyPlan: 'quadruped' }), rig.root);+ const missing = result.find((finding) => finding.code === 'CHAR_QUADRUPED_REQUIRED_ROLE')!;+ expect(missing.measurement?.expected).toBe('paw.hind.right');+ });++ test('serpentine and many-limbed custom graphs pass without humanoid assumptions', () => {+ const graphs = [+ createCharacterRigGraphV1({+ bodyPlan: 'serpentine',+ joints: [+ createCharacterJointDescriptorV1({ role: 'spine.0' }),+ createCharacterJointDescriptorV1({ role: 'spine.1', parentRole: 'spine.0' }),+ createCharacterJointDescriptorV1({ role: 'tail.tip', parentRole: 'spine.1' }),+ ],+ }),+ createCharacterRigGraphV1({+ bodyPlan: 'multi-limb',+ joints: [+ createCharacterJointDescriptorV1({ role: 'core' }),+ ...Array.from({ length: 6 }, (_, index) =>+ createCharacterJointDescriptorV1({+ role: `arm.${index + 1}`,+ parentRole: 'core',+ endEffector: true,+ }),+ ),+ ],+ }),+ ];+ for (const graph of graphs) {+ const rig = instantiateGraph(graph);+ expect(findings(intent({ bodyPlan: graph.bodyPlan }), rig.root)).toEqual([]);+ }+ });+});++describe('CHAR-013/014 held-item and contact validation', () => {+ test('held item passes under a grip end effector and fails under shoulder/elbow', () => {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ const item = new THREE.Object3D();+ item.name = 'Sword';+ item.userData['kilnHeldItem'] = true;+ stampSemanticMetadataV1(item, { roles: ['character.held-item'] });+ rig.byRole.get('wrist.left')!.add(item);+ const heldIntent = intent({ heldItem: { required: true, attachmentRole: 'grip' } });+ expect(codes(findings(heldIntent, rig.root))).not.toContain('CHAR_HELD_ITEM_ATTACHMENT');++ rig.byRole.get('shoulder.left')!.add(item);+ const bad = findings(heldIntent, rig.root).find(+ (finding) => finding.code === 'CHAR_HELD_ITEM_ATTACHMENT',+ )!;+ expect(bad.measurement).toEqual({+ name: 'heldItemAttachmentRole',+ actual: 'shoulder.left',+ expected: 'grip',+ });+ expect(bad.affected?.nodePath).toBe(+ 'Character[0]/Joint_hips[0]/Joint_spine[0]/Joint_shoulder_left[1]/Sword[1]',+ );+ });++ test('ground contacts use asset-local Y=0 under transformed roots', () => {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ rig.root.position.set(5, 7, -3);+ rig.root.rotation.set(0.2, 0.5, -0.1);+ rig.root.scale.setScalar(1.4);+ expect(findings(intent({ grounded: true }), rig.root)).toEqual([]);+ });++ test('floating and buried contacts report exact path, signed Y, and tolerance', () => {+ for (const [offset, expectedCode] of [+ [0.1, 'CHAR_CONTACT_FLOATING'],+ [-0.1, 'CHAR_CONTACT_BURIED'],+ ] as const) {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ rig.byRole.get('ankle.left')!.position.y += offset;+ const result = findings(intent({ grounded: true }), rig.root);+ const contact = result.find((finding) => finding.code === expectedCode)!;+ expect(contact.affected?.nodePath).toContain('/Joint_ankle_left[0]');+ expect(contact.measurement?.name).toBe('contactY');+ expect(contact.measurement?.actual).toBeCloseTo(offset, 8);+ expect(contact.measurement?.threshold).toBe(0.02);+ expect(contact.measurement?.unit).toBe('m');+ }+ });+});++describe('CHAR-026 declared attachment motion', () => {+ test('blocks item-local animation that breaks a declared grip and accepts a stable grip', () => {+ const rig = instantiateGraph(BIPED_RIG_PRESET_V1);+ const item = new THREE.Object3D();+ item.name = 'HeldLantern';+ item.position.set(0.1, 0, 0);+ item.userData['kilnHeldItem'] = true;+ stampSemanticMetadataV1(item, { roles: ['character.held-item'] });+ rig.byRole.get('wrist.left')!.add(item);+ const trusted = intent({+ clips: [{ name: 'Carry', playback: 'loop' }],+ heldItem: { required: true, attachmentRole: 'grip' },+ });+ const stable = new THREE.AnimationClip('Carry', 1, []);+ expect(codes(findings(trusted, rig.root, [stable]))).not.toContain('CHAR_HELD_ITEM_GRIP_BREAK');++ const broken = new THREE.AnimationClip('Carry', 1, [+ new THREE.VectorKeyframeTrack(+ `${item.name}.position`,+ [0, 0.5, 1],+ [0.1, 0, 0, 0.4, 0, 0, 0.1, 0, 0],+ ),+ ]);+ const finding = findings(trusted, rig.root, [broken]).find(+ (value) => value.code === 'CHAR_HELD_ITEM_GRIP_BREAK',+ )!;+ expect(finding.disposition).toBe('block');+ expect(finding.affected).toMatchObject({ node: 'HeldLantern', clip: 'Carry' });+ expect(finding.measurement?.name).toBe('heldItemGripDistanceDrift');+ expect(finding.measurement?.actual).toBeCloseTo(0.3, 6);+ expect(finding.repairText).toContain('remove only the item-local animation keys');+ });+});++describe('CHAR-018–020 exact clip/key/loop validation', () => {+ test('requires exactly requested names and rejects missing, duplicate, and extra clips', () => {+ const trusted = intent({+ clips: [+ { name: 'Idle', playback: 'loop' },+ { name: 'Impact', playback: 'oneShot' },+ ],+ });+ const idle = positionClip('Idle', 'Character', [0, 0, 0]);+ const duplicateIdle = positionClip('Idle', 'Character', [0, 0, 0]);+ const extra = positionClip('Dance', 'Character', [0, 0, 0]);+ const result = findings(trusted, undefined, [idle, duplicateIdle, extra]);+ expect(codes(result)).toEqual(+ expect.arrayContaining(['CHAR_CLIP_DUPLICATE', 'CHAR_CLIP_MISSING', 'CHAR_CLIP_UNEXPECTED']),+ );+ });++ test('rejects invalid duration, non-finite values, duplicate/unsorted/out-of-range keys, and tuple mismatch', () => {+ const trusted = intent({ clips: [{ name: 'Bad', playback: 'oneShot' }] });+ const track = new THREE.VectorKeyframeTrack(+ 'Character.position',+ [0, 0.5, 0.5, 2],+ [0, 0, 0, 1, 0, 0, Number.NaN, 0, 0, 2, 0, 0],+ );+ track.values = new Float32Array([...track.values, 7]);+ const clip = new THREE.AnimationClip('Bad', 1, [track]);+ clip.duration = 0;+ const result = findings(trusted, undefined, [clip]);+ expect(codes(result)).toEqual(+ expect.arrayContaining([+ 'CHAR_CLIP_DURATION',+ 'CHAR_ANIMATION_NONFINITE',+ 'CHAR_KEY_TIME_ORDER',+ 'CHAR_TRACK_VALUE_COUNT',+ ]),+ );++ clip.duration = 1;+ expect(codes(findings(trusted, undefined, [clip]))).toContain('CHAR_KEY_OUT_OF_RANGE');+ });++ test('loop endpoints must match while declared one-shot impact is exempt', () => {+ const loopIntent = intent({ clips: [{ name: 'Idle', playback: 'loop' }] });+ const mismatch = positionClip('Idle', 'Character', [0.2, 0, 0]);+ expect(codes(findings(loopIntent, undefined, [mismatch]))).toContain('CHAR_LOOP_ENDPOINT');++ const oneShotIntent = intent({ clips: [{ name: 'Impact', playback: 'oneShot' }] });+ const impact = positionClip('Impact', 'Character', [0.2, 0, 0]);+ expect(codes(findings(oneShotIntent, undefined, [impact]))).not.toContain('CHAR_LOOP_ENDPOINT');+ });+});++describe('CHAR-021/022 deterministic sampling and root motion', () => {+ test('fixed normalized samples reproduce joint positions across runs', () => {+ const root = new THREE.Object3D();+ root.name = 'Character';+ const chain = createJointChain(+ 'Leg',+ [+ { role: 'hip.left', offset: [0, 1, 0], side: 'left' },+ { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' },+ ],+ { parent: root },+ );+ const clip = new THREE.AnimationClip('Step', 2, [+ new THREE.VectorKeyframeTrack(`${chain.nodes[0]!.name}.position`, [0, 2], [0, 1, 0, 2, 1, 0]),+ ]);+ const first = sampleCharacterAnimation(root, clip);+ const second = sampleCharacterAnimation(root, clip);+ expect(second).toEqual(first);+ expect(first.fractions).toEqual([0, 0.25, 0.5, 0.75, 1]);+ expect(first.samples[2]?.nodes.find((node) => node.role === 'hip.left')?.worldPosition).toEqual(+ [1, 1, 0],+ );+ });++ test('forward root motion rejects -X and Z-dominant travel; +X and in-place pass', () => {+ const root = new THREE.Object3D();+ root.name = 'Character';+ const forwardIntent = intent({+ articulated: false,+ rootMotion: 'forward',+ clips: [{ name: 'Walk', playback: 'loop' }],+ });+ expect(+ codes(findings(forwardIntent, root, [positionClip('Walk', 'Character', [-1, 0, 0])])),+ ).toContain('CHAR_ROOT_MOTION_BACKWARD');+ expect(+ codes(findings(forwardIntent, root, [positionClip('Walk', 'Character', [0.1, 0, 1])])),+ ).toContain('CHAR_ROOT_MOTION_LATERAL');+ expect(+ codes(findings(forwardIntent, root, [positionClip('Walk', 'Character', [1, 0, 0])])),+ ).not.toEqual(+ expect.arrayContaining(['CHAR_ROOT_MOTION_BACKWARD', 'CHAR_ROOT_MOTION_LATERAL']),+ );++ const inPlaceIntent = intent({+ articulated: false,+ rootMotion: 'inPlace',+ clips: [{ name: 'Walk', playback: 'loop' }],+ });+ expect(+ codes(findings(inPlaceIntent, root, [positionClip('Walk', 'Character', [0, 0, 0])])),+ ).not.toEqual(+ expect.arrayContaining(['CHAR_ROOT_MOTION_BACKWARD', 'CHAR_ROOT_MOTION_LATERAL']),+ );+ });+});diff --git a/src/qa/character.ts b/src/qa/character.tsnew file mode 100644index 00000000..9722557f--- /dev/null+++ b/src/qa/character.ts@@ -0,0 +1,975 @@+import * as THREE from 'three';++import {+ BIPED_RIG_PRESET_V1,+ QUADRUPED_RIG_PRESET_V1,+ collectCharacterJointNodes,+ readCharacterJointDescriptorV1,+ readCharacterRigGraphV1,+ type CharacterJointDescriptorV1,+ type CharacterRigGraphV1,+} from '../character';+import {+ readSemanticMetadataV1,+ type AssetIntentV1,+ type CharacterClipIntentV1,+ type CharacterIntentV1,+} from '../contracts';+import { withCharacterRepair } from './character-repairs';+import { conformancePromotionAuthorization, KILN_ENGINE_QA_OWNER, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';++const PROFILE_RULE_ID = 'CHARACTER_PROFILE';+const CONTACT_TOLERANCE = 0.02;+const LOOP_TOLERANCE = 1e-5;+const ROOT_MOTION_TOLERANCE = 0.01;+const GRIP_MOTION_RATIO = 0.02;++interface CharacterIntentExtensions {+ /** Optional semantic node name that owns declared root motion. */+ rootMotionNode?: string;+ /** Optional trusted custom graph; the scene-root graph is used otherwise. */+ rigGraph?: CharacterRigGraphV1;+ /** Optional tighter/looser asset-local contact tolerance in meters. */+ contactTolerance?: number;+}++interface CharacterNodeEvidence {+ node: THREE.Object3D;+ nodePath: string;+}++interface TrackLike {+ name: string;+ times: ArrayLike<number>;+ values: ArrayLike<number>;+ getValueSize?: () => number;+ createInterpolant?: () => { evaluate(time: number): ArrayLike<number> };+}++interface ClipLike {+ name: string;+ duration: number;+ tracks: TrackLike[];+}++export interface CharacterSampleNodeV1 {+ nodeName: string;+ nodePath: string;+ role: string;+ worldPosition: [number, number, number];+ worldQuaternion: [number, number, number, number];+}++export interface CharacterAnimationSampleV1 {+ fraction: number;+ time: number;+ nodes: CharacterSampleNodeV1[];+}++export interface CharacterAnimationSamplesV1 {+ schemaVersion: 1;+ clipName: string;+ duration: number;+ fractions: number[];+ samples: CharacterAnimationSampleV1[];+}++export const CHARACTER_SAMPLE_FRACTIONS = Object.freeze([0, 0.25, 0.5, 0.75, 1]);++function isClipLike(value: unknown): value is ClipLike {+ if (typeof value !== 'object' || value === null) return false;+ const clip = value as Partial<ClipLike>;+ return typeof clip.name === 'string' && Array.isArray(clip.tracks);+}++function collectNodes(root: THREE.Object3D): CharacterNodeEvidence[] {+ const nodes: CharacterNodeEvidence[] = [];+ const visit = (node: THREE.Object3D, parentPath: string, siblingIndex: number): void => {+ const segment = `${node.name.trim() || node.type || 'Object3D'}[${siblingIndex}]`;+ const nodePath = parentPath ? `${parentPath}/${segment}` : segment;+ nodes.push({ node, nodePath });+ node.children.forEach((child, index) => {+ visit(child, nodePath, index);+ });+ };+ visit(root, '', 0);+ return nodes;+}++function characterIntent(+ intent: AssetIntentV1,+): (CharacterIntentV1 & CharacterIntentExtensions) | undefined {+ return intent.character as (CharacterIntentV1 & CharacterIntentExtensions) | undefined;+}++function block(+ intent: AssetIntentV1,+ code: string,+ message: string,+ options: Pick<QaFinding, 'dimension' | 'affected' | 'measurement' | 'viewHints'>,+): QaFinding {+ return withCharacterRepair({+ code,+ disposition: 'block',+ profile: intent.qaProfile,+ message,+ ...options,+ });+}++function targetName(trackName: string): string | undefined {+ const dot = trackName.lastIndexOf('.');+ return dot > 0 ? trackName.slice(0, dot) : undefined;+}++function propertyName(trackName: string): string | undefined {+ const dot = trackName.lastIndexOf('.');+ return dot > 0 ? trackName.slice(dot + 1) : undefined;+}++function blockerKey(finding: QaFinding): string {+ return [+ finding.code,+ finding.affected?.nodePath ?? '',+ finding.affected?.clip ?? '',+ finding.affected?.track ?? '',+ String(finding.measurement?.expected ?? ''),+ ].join('|');+}++function dedupeFindings(findings: readonly QaFinding[]): QaFinding[] {+ const byKey = new Map<string, QaFinding>();+ for (const finding of findings) byKey.set(blockerKey(finding), finding);+ return [...byKey.values()].sort((a, b) => blockerKey(a).localeCompare(blockerKey(b)));+}++function duplicateNameFindings(+ intent: AssetIntentV1,+ nodes: readonly CharacterNodeEvidence[],+ clips: readonly ClipLike[],+): QaFinding[] {+ const animatedTargets = new Set(+ clips.flatMap((clip) => clip.tracks.map((track) => targetName(track.name)).filter(Boolean)),+ );+ const byName = new Map<string, CharacterNodeEvidence[]>();+ for (const evidence of nodes) {+ if (!evidence.node.name) continue;+ if (!evidence.node.name.startsWith('Joint_') && !animatedTargets.has(evidence.node.name))+ continue;+ const values = byName.get(evidence.node.name) ?? [];+ values.push(evidence);+ byName.set(evidence.node.name, values);+ }+ const findings: QaFinding[] = [];+ for (const [name, matches] of [...byName.entries()].sort(([a], [b]) => a.localeCompare(b))) {+ if (matches.length < 2) continue;+ const paths = matches.map((match) => match.nodePath).sort();+ findings.push(+ block(+ intent,+ 'CHAR_DUPLICATE_ANIMATED_NODE_NAME',+ `Animated node name ${JSON.stringify(name)} resolves to multiple exact paths: ${paths.join(', ')}.`,+ {+ dimension: 'exportIntegrity',+ affected: { node: name, nodePath: paths[0] },+ measurement: {+ name: 'animatedNodeNameCount',+ actual: matches.length,+ expected: 1,+ },+ viewHints: ['character.skeleton.front', 'character.skeleton.right'],+ },+ ),+ );+ }+ return findings;+}++function parentAndRoleFindings(+ intent: AssetIntentV1,+ root: THREE.Object3D,+): { findings: QaFinding[]; byRole: Map<string, ReturnType<typeof collectCharacterJointNodes>> } {+ const joints = collectCharacterJointNodes(root);+ const byRole = new Map<string, typeof joints>();+ for (const joint of joints) {+ const values = byRole.get(joint.descriptor.role) ?? [];+ values.push(joint);+ byRole.set(joint.descriptor.role, values);+ }+ const findings: QaFinding[] = [];+ for (const [role, matches] of [...byRole.entries()].sort(([a], [b]) => a.localeCompare(b))) {+ if (matches.length < 2) continue;+ const paths = matches.map((match) => match.nodePath).sort();+ findings.push(+ block(+ intent,+ 'CHAR_DUPLICATE_JOINT_ROLE',+ `Joint role ${role} is declared at ${paths.join(', ')}.`,+ {+ dimension: 'categoryReadiness',+ affected: { node: role, nodePath: paths[0] },+ measurement: { name: 'jointRoleCount', actual: matches.length, expected: 1 },+ viewHints: ['character.skeleton.front', 'character.skeleton.right'],+ },+ ),+ );+ }+ for (const joint of joints) {+ const expected = joint.descriptor.parentRole;+ if (!expected) continue;+ const actualDescriptor = joint.node.parent+ ? readCharacterJointDescriptorV1(joint.node.parent)+ : undefined;+ const actual = actualDescriptor?.role ?? joint.node.parent?.name ?? '(none)';+ if (actualDescriptor?.role === expected) continue;+ findings.push(+ block(+ intent,+ 'CHAR_PARENT_EDGE',+ `Broken joint edge ${expected} -> ${joint.descriptor.role}: actual direct parent is ${actual}.`,+ {+ dimension: 'categoryReadiness',+ affected: { node: joint.node.name, nodePath: joint.nodePath },+ measurement: { name: 'parentRole', actual, expected },+ viewHints: ['character.skeleton.front', 'character.skeleton.right'],+ },+ ),+ );+ }+ return { findings, byRole };+}++function requiredGraphFindings(+ intent: AssetIntentV1,+ graph: CharacterRigGraphV1,+ actualByRole: Map<string, ReturnType<typeof collectCharacterJointNodes>>,+ code: 'CHAR_BIPED_REQUIRED_ROLE' | 'CHAR_QUADRUPED_REQUIRED_ROLE' | 'CHAR_CUSTOM_REQUIRED_ROLE',+): QaFinding[] {+ const findings: QaFinding[] = [];+ for (const expected of graph.joints) {+ const actual = actualByRole.get(expected.role)?.[0];+ if (!actual) {+ findings.push(+ block(+ intent,+ code,+ `Explicit ${graph.bodyPlan} articulation is missing joint role ${expected.role}.`,+ {+ dimension: 'categoryReadiness',+ affected: { node: expected.role },+ measurement: { name: 'requiredJointRole', actual: false, expected: expected.role },+ viewHints: ['character.skeleton.front', 'character.skeleton.right'],+ },+ ),+ );+ continue;+ }+ if (expected.parentRole && actual.descriptor.parentRole !== expected.parentRole) {+ findings.push(+ block(+ intent,+ 'CHAR_PARENT_EDGE',+ `Role ${expected.role} declares parent ${actual.descriptor.parentRole ?? '(none)'}; ${expected.parentRole} is required by the ${graph.bodyPlan} graph.`,+ {+ dimension: 'categoryReadiness',+ affected: { node: actual.node.name, nodePath: actual.nodePath },+ measurement: {+ name: 'declaredParentRole',+ actual: actual.descriptor.parentRole ?? '(none)',+ expected: expected.parentRole,+ },+ viewHints: ['character.skeleton.front', 'character.skeleton.right'],+ },+ ),+ );+ }+ }+ return findings;+}++function rigProfileFindings(+ intent: AssetIntentV1,+ root: THREE.Object3D,+ byRole: Map<string, ReturnType<typeof collectCharacterJointNodes>>,+): QaFinding[] {+ const trusted = characterIntent(intent);+ if (!trusted || !intent.capabilities.includes('articulated')) return [];+ if (trusted.bodyPlan === 'biped') {+ return requiredGraphFindings(intent, BIPED_RIG_PRESET_V1, byRole, 'CHAR_BIPED_REQUIRED_ROLE');+ }+ if (trusted.bodyPlan === 'quadruped') {+ return requiredGraphFindings(+ intent,+ QUADRUPED_RIG_PRESET_V1,+ byRole,+ 'CHAR_QUADRUPED_REQUIRED_ROLE',+ );+ }+ const customGraph = trusted.rigGraph ?? readCharacterRigGraphV1(root);+ if (!customGraph) {+ return [+ block(+ intent,+ 'CHAR_CUSTOM_GRAPH_MISSING',+ `Explicit articulated ${trusted.bodyPlan} character requires its declared semantic rig graph; no biped fallback is allowed.`,+ {+ dimension: 'categoryReadiness',+ affected: { node: root.name },+ measurement: { name: 'customRigGraphPresent', actual: false, expected: true },+ viewHints: ['character.skeleton.front', 'character.skeleton.right'],+ },+ ),+ ];+ }+ return requiredGraphFindings(intent, customGraph, byRole, 'CHAR_CUSTOM_REQUIRED_ROLE');+}++function heldItemFindings(+ intent: AssetIntentV1,+ nodes: readonly CharacterNodeEvidence[],+): QaFinding[] {+ const held = characterIntent(intent)?.heldItem;+ if (!held?.required) return [];+ const item = nodes.find((evidence) => {+ const roles = readSemanticMetadataV1(evidence.node)?.roles ?? [];+ return (+ evidence.node.userData['kilnHeldItem'] === true ||+ roles.some(+ (role) =>+ role === 'held-item' || role.startsWith('held-item.') || role === 'character.held-item',+ )+ );+ });+ if (!item) {+ return [+ block(+ intent,+ 'CHAR_HELD_ITEM_MISSING',+ 'Trusted intent requires a held item, but none is declared.',+ {+ dimension: 'categoryReadiness',+ affected: { node: held.attachmentRole },+ measurement: { name: 'heldItemPresent', actual: false, expected: true },+ viewHints: ['character.skeleton.front', 'character.skeleton.right'],+ },+ ),+ ];+ }+ let cursor = item.node.parent;+ let attachment: CharacterJointDescriptorV1 | undefined;+ while (cursor) {+ attachment = readCharacterJointDescriptorV1(cursor);+ if (attachment) break;+ cursor = cursor.parent;+ }+ const roleMatches = (descriptor: CharacterJointDescriptorV1): boolean => {+ const candidates = [descriptor.role, ...descriptor.aliases];+ return candidates.some(+ (role) => role === held.attachmentRole || role.split(/[._-]/).includes(held.attachmentRole),+ );+ };+ if (attachment?.endEffector && roleMatches(attachment)) return [];+ return [+ block(+ intent,+ 'CHAR_HELD_ITEM_ATTACHMENT',+ `Held item at ${item.nodePath} must be under ${held.attachmentRole} end effector; actual attachment is ${attachment?.role ?? '(non-joint)'}.`,+ {+ dimension: 'categoryReadiness',+ affected: { node: item.node.name, nodePath: item.nodePath },+ measurement: {+ name: 'heldItemAttachmentRole',+ actual: attachment?.role ?? '(non-joint)',+ expected: held.attachmentRole,+ },+ viewHints: ['character.skeleton.front', 'character.skeleton.right'],+ },+ ),+ ];+}++function contactFindings(intent: AssetIntentV1, root: THREE.Object3D): QaFinding[] {+ const trusted = characterIntent(intent);+ if (!trusted?.grounded) return [];+ const contacts = collectCharacterJointNodes(root).filter((joint) => joint.descriptor.contact);+ if (contacts.length === 0) {+ return [+ block(intent, 'CHAR_CONTACT_MISSING', 'Grounded character declares no contact joint.', {+ dimension: 'categoryReadiness',+ affected: { node: root.name },+ measurement: { name: 'groundContactCount', actual: 0, expected: '>=1' },+ viewHints: ['character.skeleton.front', 'generic.front.depth-contact'],+ }),+ ];+ }+ root.updateMatrixWorld(true);+ const rootInverse = root.matrixWorld.clone().invert();+ const tolerance =+ Number.isFinite(trusted.contactTolerance) && (trusted.contactTolerance ?? 0) >= 0+ ? trusted.contactTolerance!+ : CONTACT_TOLERANCE;+ const findings: QaFinding[] = [];+ for (const contact of contacts) {+ const point = contact.node.getWorldPosition(new THREE.Vector3()).applyMatrix4(rootInverse);+ if (point.y > tolerance) {+ findings.push(+ block(+ intent,+ 'CHAR_CONTACT_FLOATING',+ `Ground contact ${contact.descriptor.role} is ${point.y.toFixed(6)} m above asset-local ground.`,+ {+ dimension: 'categoryReadiness',+ affected: { node: contact.node.name, nodePath: contact.nodePath },+ measurement: {+ name: 'contactY',+ actual: point.y,+ expected: 0,+ threshold: tolerance,+ unit: 'm',+ },+ viewHints: ['character.skeleton.front', 'generic.front.depth-contact'],+ },+ ),+ );+ } else if (point.y < -tolerance) {+ findings.push(+ block(+ intent,+ 'CHAR_CONTACT_BURIED',+ `Ground contact ${contact.descriptor.role} is ${Math.abs(point.y).toFixed(6)} m below asset-local ground.`,+ {+ dimension: 'categoryReadiness',+ affected: { node: contact.node.name, nodePath: contact.nodePath },+ measurement: {+ name: 'contactY',+ actual: point.y,+ expected: 0,+ threshold: tolerance,+ unit: 'm',+ },+ viewHints: ['character.skeleton.front', 'generic.front.depth-contact'],+ },+ ),+ );+ }+ }+ return findings;+}++function requestedClipFindings(+ intent: AssetIntentV1,+ clips: readonly ClipLike[],+ requested: readonly CharacterClipIntentV1[],+): QaFinding[] {+ const findings: QaFinding[] = [];+ const requestedNames = new Set(requested.map((clip) => clip.name));+ const counts = new Map<string, number>();+ for (const clip of clips) counts.set(clip.name, (counts.get(clip.name) ?? 0) + 1);+ for (const [name, count] of [...counts.entries()].sort(([a], [b]) => a.localeCompare(b))) {+ if (count < 2) continue;+ findings.push(+ block(intent, 'CHAR_CLIP_DUPLICATE', `Clip ${name} appears ${count} times.`, {+ dimension: 'exportIntegrity',+ affected: { clip: name },+ measurement: { name: 'clipCount', actual: count, expected: 1 },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ }),+ );+ }+ for (const request of requested) {+ const count = counts.get(request.name) ?? 0;+ if (count === 0) {+ findings.push(+ block(intent, 'CHAR_CLIP_MISSING', `Requested clip ${request.name} is missing.`, {+ dimension: 'categoryReadiness',+ affected: { clip: request.name },+ measurement: { name: 'clipCount', actual: 0, expected: 1 },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ }),+ );+ }+ }+ for (const name of [...counts.keys()].sort()) {+ if (requestedNames.has(name)) continue;+ findings.push(+ block(intent, 'CHAR_CLIP_UNEXPECTED', `Clip ${name} was not requested by trusted intent.`, {+ dimension: 'categoryReadiness',+ affected: { clip: name },+ measurement: { name: 'requestedClip', actual: name, expected: 'absent' },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ }),+ );+ }+ return findings;+}++function valueSize(track: TrackLike): number | undefined {+ const explicit = track.getValueSize?.();+ if (typeof explicit === 'number' && Number.isInteger(explicit) && explicit > 0) return explicit;+ if (track.times.length > 0 && track.values.length % track.times.length === 0) {+ return track.values.length / track.times.length;+ }+ return undefined;+}++function endpointDelta(track: TrackLike, size: number): number {+ const first = Array.from({ length: size }, (_, index) => Number(track.values[index]));+ const lastOffset = track.values.length - size;+ const last = Array.from({ length: size }, (_, index) => Number(track.values[lastOffset + index]));+ if (track.name.endsWith('.quaternion') && size === 4) {+ const dot = Math.abs(first.reduce((sum, value, index) => sum + value * last[index]!, 0));+ return Math.abs(1 - Math.min(1, dot));+ }+ return Math.max(...first.map((value, index) => Math.abs(value - last[index]!)));+}++function animationDataFindings(+ intent: AssetIntentV1,+ clips: readonly ClipLike[],+ requested: readonly CharacterClipIntentV1[],+ root?: THREE.Object3D,+): QaFinding[] {+ const findings: QaFinding[] = [];+ const playback = new Map(requested.map((clip) => [clip.name, clip.playback]));+ const trusted = characterIntent(intent);+ const hipsName = root+ ? collectCharacterJointNodes(root).find((joint) => joint.descriptor.role === 'hips')?.node.name+ : undefined;+ const rootMotionNames = new Set(+ [trusted?.rootMotionNode, root?.name, hipsName].filter((name): name is string => Boolean(name)),+ );+ for (const clip of clips) {+ const durationValid = Number.isFinite(clip.duration) && clip.duration > 0;+ if (!durationValid) {+ findings.push(+ block(+ intent,+ 'CHAR_CLIP_DURATION',+ `Clip ${clip.name} duration must be finite and positive.`,+ {+ dimension: 'exportIntegrity',+ affected: { clip: clip.name },+ measurement: { name: 'clipDuration', actual: clip.duration, expected: '>0', unit: 's' },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ },+ ),+ );+ }+ for (const track of clip.tracks) {+ const times = Array.from(track.times, Number);+ const values = Array.from(track.values, Number);+ const nonFiniteTime = times.findIndex((value) => !Number.isFinite(value));+ const nonFiniteValue = values.findIndex((value) => !Number.isFinite(value));+ if (nonFiniteTime >= 0 || nonFiniteValue >= 0) {+ findings.push(+ block(+ intent,+ 'CHAR_ANIMATION_NONFINITE',+ `Clip ${clip.name} track ${track.name} contains a non-finite ${nonFiniteTime >= 0 ? 'time' : 'value'}.`,+ {+ dimension: 'exportIntegrity',+ affected: { clip: clip.name, track: track.name },+ measurement: {+ name: nonFiniteTime >= 0 ? 'nonFiniteTimeIndex' : 'nonFiniteValueIndex',+ actual: nonFiniteTime >= 0 ? nonFiniteTime : nonFiniteValue,+ expected: 'none',+ },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ },+ ),+ );+ }+ const badOrder = times.findIndex((time, index) => index > 0 && time <= times[index - 1]!);+ if (badOrder >= 0) {+ findings.push(+ block(+ intent,+ 'CHAR_KEY_TIME_ORDER',+ `Clip ${clip.name} track ${track.name} key times must be strictly increasing and unique.`,+ {+ dimension: 'exportIntegrity',+ affected: { clip: clip.name, track: track.name },+ measurement: {+ name: 'firstNonIncreasingKey',+ actual: badOrder,+ expected: 'strictly increasing',+ },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ },+ ),+ );+ }+ if (durationValid) {+ const outside = times.findIndex(+ (time) => Number.isFinite(time) && (time < 0 || time > clip.duration),+ );+ if (outside >= 0) {+ findings.push(+ block(+ intent,+ 'CHAR_KEY_OUT_OF_RANGE',+ `Clip ${clip.name} track ${track.name} key ${outside} lies outside [0, ${clip.duration}].`,+ {+ dimension: 'exportIntegrity',+ affected: { clip: clip.name, track: track.name },+ measurement: {+ name: 'keyTime',+ actual: times[outside]!,+ expected: `0..${clip.duration}`,+ unit: 's',+ },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ },+ ),+ );+ }+ }+ const size = valueSize(track);+ if (!size || values.length !== times.length * size) {+ findings.push(+ block(+ intent,+ 'CHAR_TRACK_VALUE_COUNT',+ `Clip ${clip.name} track ${track.name} does not contain one complete value per key time.`,+ {+ dimension: 'exportIntegrity',+ affected: { clip: clip.name, track: track.name },+ measurement: {+ name: 'trackValueCount',+ actual: values.length,+ expected: size ? times.length * size : 'integral tuple count',+ },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ },+ ),+ );+ } else if (+ playback.get(clip.name) === 'loop' &&+ !(+ trusted?.rootMotion === 'forward' &&+ track.name.endsWith('.position') &&+ rootMotionNames.has(targetName(track.name) ?? '')+ ) &&+ times.length > 1 &&+ nonFiniteValue < 0 &&+ endpointDelta(track, size) > LOOP_TOLERANCE+ ) {+ const delta = endpointDelta(track, size);+ findings.push(+ block(+ intent,+ 'CHAR_LOOP_ENDPOINT',+ `Looping clip ${clip.name} track ${track.name} ends ${delta} away from its start pose.`,+ {+ dimension: 'categoryReadiness',+ affected: { clip: clip.name, track: track.name },+ measurement: {+ name: 'loopEndpointDelta',+ actual: delta,+ expected: 0,+ threshold: LOOP_TOLERANCE,+ },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ },+ ),+ );+ }+ }+ }+ return findings;+}++function rounded(value: number): number {+ const result = Math.round(value * 1e9) / 1e9;+ return Object.is(result, -0) ? 0 : result;+}++function applyTrackAt(root: THREE.Object3D, track: TrackLike, time: number): void {+ const nodeName = targetName(track.name);+ const property = propertyName(track.name);+ const node = nodeName ? root.getObjectByName(nodeName) : undefined;+ if (!node || !property || !track.createInterpolant) return;+ const value = track.createInterpolant().evaluate(time);+ if (property === 'position') node.position.fromArray(value as ArrayLike<number>);+ else if (property === 'scale') node.scale.fromArray(value as ArrayLike<number>);+ else if (property === 'quaternion') {+ node.quaternion.fromArray(value as ArrayLike<number>).normalize();+ }+}++/** Deterministically evaluate authored tracks and report joint world transforms. */+export function sampleCharacterAnimation(+ root: THREE.Object3D,+ clip: ClipLike,+ fractions: readonly number[] = CHARACTER_SAMPLE_FRACTIONS,+): CharacterAnimationSamplesV1 {+ if (!Number.isFinite(clip.duration) || clip.duration <= 0) {+ throw new TypeError('Cannot sample a clip without a finite positive duration.');+ }+ if (fractions.some((fraction) => !Number.isFinite(fraction) || fraction < 0 || fraction > 1)) {+ throw new TypeError('Animation sample fractions must be finite values in [0, 1].');+ }+ const samples = fractions.map((fraction): CharacterAnimationSampleV1 => {+ const clone = root.clone(true);+ const time = fraction * clip.duration;+ for (const track of clip.tracks) applyTrackAt(clone, track, time);+ clone.updateMatrixWorld(true);+ const joints = collectCharacterJointNodes(clone);+ const rootPath = `${clone.name.trim() || clone.type || 'Object3D'}[0]`;+ const selected = [+ { node: clone, nodePath: rootPath, role: 'asset.root' },+ ...joints.map((joint) => ({+ node: joint.node,+ nodePath: joint.nodePath,+ role: joint.descriptor.role,+ })),+ ];+ return {+ fraction,+ time: rounded(time),+ nodes: selected.map((entry) => {+ const position = entry.node.getWorldPosition(new THREE.Vector3());+ const quaternion = entry.node.getWorldQuaternion(new THREE.Quaternion());+ return {+ nodeName: entry.node.name,+ nodePath: entry.nodePath,+ role: entry.role,+ worldPosition: [rounded(position.x), rounded(position.y), rounded(position.z)],+ worldQuaternion: [+ rounded(quaternion.x),+ rounded(quaternion.y),+ rounded(quaternion.z),+ rounded(quaternion.w),+ ],+ };+ }),+ };+ });+ return {+ schemaVersion: 1,+ clipName: clip.name,+ duration: clip.duration,+ fractions: [...fractions],+ samples,+ };+}++function locomotionClipNames(character: CharacterIntentV1): string[] {+ const loopingMotion = character.clips+ .filter(+ (clip) =>+ clip.playback === 'loop' && /(?:walk|run|fly|swim|slither|roll|locom)/i.test(clip.name),+ )+ .map((clip) => clip.name);+ if (loopingMotion.length > 0) return loopingMotion;+ return character.clips.filter((clip) => clip.playback === 'loop').map((clip) => clip.name);+}++function rootMotionFindings(+ intent: AssetIntentV1,+ root: THREE.Object3D,+ clips: readonly ClipLike[],+): QaFinding[] {+ const trusted = characterIntent(intent);+ if (trusted?.rootMotion !== 'forward') return [];+ const names = new Set(locomotionClipNames(trusted));+ const findings: QaFinding[] = [];+ const hips = collectCharacterJointNodes(root).find((joint) => joint.descriptor.role === 'hips');+ for (const clip of clips.filter((candidate) => names.has(candidate.name))) {+ const positionTracks = clip.tracks.filter((track) => track.name.endsWith('.position'));+ const preferredName = trusted.rootMotionNode ?? root.name;+ const rootTrack =+ positionTracks.find((track) => targetName(track.name) === preferredName) ??+ positionTracks.find((track) => targetName(track.name) === hips?.node.name) ??+ positionTracks[0];+ if (!rootTrack || rootTrack.times.length === 0 || !rootTrack.createInterpolant) continue;+ const interpolant = rootTrack.createInterpolant();+ const first = Array.from(interpolant.evaluate(0), Number);+ const last = Array.from(interpolant.evaluate(clip.duration), Number);+ const dx = Number(last[0]) - Number(first[0]);+ const dz = Number(last[2]) - Number(first[2]);+ if (!Number.isFinite(dx) || !Number.isFinite(dz)) continue;+ if (dx < -ROOT_MOTION_TOLERANCE) {+ findings.push(+ block(+ intent,+ 'CHAR_ROOT_MOTION_BACKWARD',+ `Forward locomotion clip ${clip.name} travels ${dx.toFixed(6)} m along X.`,+ {+ dimension: 'categoryReadiness',+ affected: { clip: clip.name, track: rootTrack.name },+ measurement: {+ name: 'rootMotionDeltaX',+ actual: dx,+ expected: '>=0',+ threshold: ROOT_MOTION_TOLERANCE,+ unit: 'm',+ },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ },+ ),+ );+ }+ if (+ Math.abs(dz) > ROOT_MOTION_TOLERANCE &&+ Math.abs(dz) > Math.max(Math.abs(dx) * 1.25, ROOT_MOTION_TOLERANCE)+ ) {+ findings.push(+ block(+ intent,+ 'CHAR_ROOT_MOTION_LATERAL',+ `Forward locomotion clip ${clip.name} is Z-dominant (dx=${dx.toFixed(6)}, dz=${dz.toFixed(6)}).`,+ {+ dimension: 'categoryReadiness',+ affected: { clip: clip.name, track: rootTrack.name },+ measurement: {+ name: 'rootMotionLateralToForward',+ actual: Math.abs(dz) / Math.max(Math.abs(dx), ROOT_MOTION_TOLERANCE),+ expected: '<=1.25',+ threshold: 1.25,+ },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ },+ ),+ );+ }+ }+ return findings;+}++function declaredHeldItem(+ nodes: readonly CharacterNodeEvidence[],+): CharacterNodeEvidence | undefined {+ return nodes.find((evidence) => {+ const roles = readSemanticMetadataV1(evidence.node)?.roles ?? [];+ return (+ evidence.node.userData['kilnHeldItem'] === true ||+ roles.some(+ (role) =>+ role === 'held-item' || role.startsWith('held-item.') || role === 'character.held-item',+ )+ );+ });+}++function characterJointScale(root: THREE.Object3D): number {+ root.updateMatrixWorld(true);+ const inverse = root.matrixWorld.clone().invert();+ const bounds = new THREE.Box3();+ for (const joint of collectCharacterJointNodes(root)) {+ bounds.expandByPoint(joint.node.getWorldPosition(new THREE.Vector3()).applyMatrix4(inverse));+ }+ if (bounds.isEmpty()) return 1;+ const size = bounds.getSize(new THREE.Vector3());+ return Math.max(size.x, size.y, size.z, 1);+}++/** Explicit declared grip relationships are deterministic contracts, not anatomy heuristics. */+function heldItemMotionFindings(+ intent: AssetIntentV1,+ root: THREE.Object3D,+ clips: readonly ClipLike[],+): QaFinding[] {+ const held = characterIntent(intent)?.heldItem;+ if (!held?.required || clips.length === 0) return [];+ const item = declaredHeldItem(collectNodes(root));+ if (!item) return [];+ let attachmentNode = item.node.parent;+ let attachment = attachmentNode ? readCharacterJointDescriptorV1(attachmentNode) : undefined;+ while (attachmentNode && !attachment) {+ attachmentNode = attachmentNode.parent;+ attachment = attachmentNode ? readCharacterJointDescriptorV1(attachmentNode) : undefined;+ }+ if (!attachmentNode || !attachment?.endEffector) return [];+ const tolerance = Math.max(0.01, characterJointScale(root) * GRIP_MOTION_RATIO);+ const findings: QaFinding[] = [];+ for (const clip of clips) {+ if (!Number.isFinite(clip.duration) || clip.duration <= 0) continue;+ let baseline: number | undefined;+ let maximumDrift = 0;+ let maximumFraction = 0;+ for (const fraction of CHARACTER_SAMPLE_FRACTIONS) {+ const clone = root.clone(true);+ for (const track of clip.tracks) applyTrackAt(clone, track, fraction * clip.duration);+ clone.updateMatrixWorld(true);+ const cloneItem = clone.getObjectByName(item.node.name);+ const cloneAttachment = collectCharacterJointNodes(clone).find(+ (joint) => joint.descriptor.role === attachment.role,+ )?.node;+ if (!cloneItem || !cloneAttachment) continue;+ const inverse = clone.matrixWorld.clone().invert();+ const itemPoint = cloneItem.getWorldPosition(new THREE.Vector3()).applyMatrix4(inverse);+ const gripPoint = cloneAttachment.getWorldPosition(new THREE.Vector3()).applyMatrix4(inverse);+ const distance = itemPoint.distanceTo(gripPoint);+ baseline ??= distance;+ const drift = Math.abs(distance - baseline);+ if (drift > maximumDrift) {+ maximumDrift = drift;+ maximumFraction = fraction;+ }+ }+ if (maximumDrift <= tolerance) continue;+ findings.push(+ block(+ intent,+ 'CHAR_HELD_ITEM_GRIP_BREAK',+ `Held item ${item.node.name} breaks its declared ${attachment.role} grip relationship in ${clip.name} at phase ${maximumFraction}.`,+ {+ dimension: 'categoryReadiness',+ affected: {+ node: item.node.name,+ nodePath: item.nodePath,+ clip: clip.name,+ },+ measurement: {+ name: 'heldItemGripDistanceDrift',+ actual: maximumDrift,+ expected: 0,+ threshold: tolerance,+ unit: 'm',+ },+ viewHints: ['character.motion-strip.front', 'character.motion-strip.right'],+ },+ ),+ );+ }+ return findings;+}++export function evaluateCharacterQa(context: QaContext): QaFinding[] {+ if (context.intent.category !== 'character') return [];+ const root = context.scene instanceof THREE.Object3D ? context.scene : undefined;+ const clips = (context.clips ?? []).filter(isClipLike);+ const findings: QaFinding[] = [];+ if (root) {+ const nodes = collectNodes(root);+ findings.push(...duplicateNameFindings(context.intent, nodes, clips));+ const rig = parentAndRoleFindings(context.intent, root);+ findings.push(...rig.findings);+ findings.push(...rigProfileFindings(context.intent, root, rig.byRole));+ findings.push(...heldItemFindings(context.intent, nodes));+ findings.push(...contactFindings(context.intent, root));+ findings.push(...rootMotionFindings(context.intent, root, clips));+ findings.push(...heldItemMotionFindings(context.intent, root, clips));+ }+ const requested = characterIntent(context.intent)?.clips ?? [];+ findings.push(...requestedClipFindings(context.intent, clips, requested));+ findings.push(...animationDataFindings(context.intent, clips, requested, root));+ return dedupeFindings(findings);+}++export const CHARACTER_QA_RULE: QaRule = Object.freeze({+ id: PROFILE_RULE_ID,+ profile: 'character',+ scope: { kind: 'category' as const, category: 'character' as const },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'character-qa-v1',+ 'src/qa/character.test.ts',+ '53086f1350c61cb8ddd32a5a4a97d23256e5dbde2e5b9765e47a3c76045bd6ed',+ ),+ defaultMode: 'enforce',+ evaluate: evaluateCharacterQa,+});diff --git a/src/qa/corpus.test.ts b/src/qa/corpus.test.tsnew file mode 100644index 00000000..b799efb3--- /dev/null+++ b/src/qa/corpus.test.ts@@ -0,0 +1,134 @@+import { describe, expect, test } from 'bun:test';+import type * as THREE from 'three';++import { renderSceneToGLB } from '../render';+import { W1_KNOWN_BAD_CORPUS, type CorpusFixturePayload } from './corpus';+import { validateFinalGlbBytes } from './gltf';+import { inspectSceneMaterials } from './material';+import { gltfReportFindings } from './run';++const buildById = async (id: string): Promise<CorpusFixturePayload> => {+ const fixture = W1_KNOWN_BAD_CORPUS.find((candidate) => candidate.id === id);+ if (!fixture) throw new Error(`Missing fixture ${id}`);+ return fixture.build();+};++describe('W1 known-bad executable corpus', () => {+ test('every failure has one reciprocal valid control and stable expected codes', () => {+ const byId = new Map(W1_KNOWN_BAD_CORPUS.map((fixture) => [fixture.id, fixture]));+ const failures = W1_KNOWN_BAD_CORPUS.filter((fixture) => fixture.kind === 'failure');+ expect(failures).toHaveLength(8);++ for (const failure of failures) {+ const control = byId.get(failure.pairId);+ expect(failure.implementation).toBe('active');+ expect(control?.implementation).toBe('active');+ expect(control?.kind).toBe('control');+ expect(control?.pairId).toBe(failure.id);+ expect(control?.expectedCodes).toEqual([]);+ expect(failure.expectedCodes.length).toBeGreaterThan(0);+ for (const code of failure.expectedCodes) expect(code).toMatch(/^[A-Z][A-Z0-9_]*$/);+ }+ });++ test('reserves the complete requested W1 failure surface', () => {+ expect(+ W1_KNOWN_BAD_CORPUS.filter((fixture) => fixture.kind === 'failure').map(+ (fixture) => fixture.id,+ ),+ ).toEqual([+ 'invalid-glb',+ 'floating-part',+ 'sideways-vehicle',+ 'inverted-limb',+ 'open-gable',+ 'rotated-roof-panels',+ 'wheel-chassis-penetration',+ 'bad-foliage-card',+ ]);+ });++ test('executes every builder into finite renderable geometry or concrete GLB bytes', async () => {+ for (const fixture of W1_KNOWN_BAD_CORPUS) {+ const payload = await fixture.build();+ expect(payload.intent.category).toBe(fixture.category);+ expect(Object.keys(payload.measurements).length).toBeGreaterThan(0);+ if (payload.kind === 'glb') {+ expect(payload.glbBytes.byteLength).toBeGreaterThan(0);+ const report = await validateFinalGlbBytes(payload.glbBytes, `${fixture.id}.glb`);+ expect(report.issues.numErrors > 0).toBe(fixture.kind === 'failure');+ if (fixture.kind === 'failure') {+ expect(+ gltfReportFindings(report, payload.intent.qaProfile).map((finding) => finding.code),+ ).toEqual([...fixture.expectedCodes]);+ }+ continue;+ }++ let renderableCount = 0;+ let allFinite = true;+ payload.scene.traverse((node) => {+ const mesh = node as THREE.Mesh;+ if (!mesh.isMesh) return;+ const position = mesh.geometry.getAttribute('position');+ if (!position || position.count === 0) return;+ renderableCount++;+ for (const value of position.array) {+ if (!Number.isFinite(value)) allFinite = false;+ }+ });+ expect(renderableCount).toBeGreaterThan(0);+ expect(allFinite).toBe(true);+ }+ });++ test('valid control scenes serialize to Khronos-clean GLBs', async () => {+ for (const fixture of W1_KNOWN_BAD_CORPUS.filter((candidate) => candidate.kind === 'control')) {+ const payload = await fixture.build();+ if (payload.kind !== 'scene') continue;+ const rendered = await renderSceneToGLB(payload.scene, { intent: payload.intent });+ expect(rendered.gltfValidation.issues.numErrors).toBe(0);+ }+ });++ test('pairs encode reciprocal measured states, including active foliage QA', async () => {+ expect((await buildById('floating-part')).measurements['contactGapMeters']).toBeGreaterThan(0);+ expect((await buildById('attached-part-control')).measurements['contactGapMeters']).toBe(0);+ expect((await buildById('sideways-vehicle')).measurements['dominantLengthAxis']).toBe('z');+ expect((await buildById('forward-vehicle-control')).measurements['dominantLengthAxis']).toBe(+ 'x',+ );+ expect((await buildById('inverted-limb')).measurements['jointOrder']).toBe(+ 'Joint_Hip>Joint_Ankle>Joint_Knee',+ );+ expect((await buildById('ordered-limb-control')).measurements['jointOrder']).toBe(+ 'Joint_Hip>Joint_Knee>Joint_Ankle',+ );+ expect((await buildById('open-gable')).measurements['gableClosureCount']).toBe(1);+ expect((await buildById('closed-gable-control')).measurements['gableClosureCount']).toBe(2);+ expect((await buildById('rotated-roof-panels')).measurements['panelSpanAxis']).toBe('x');+ expect((await buildById('aligned-roof-panels-control')).measurements['panelSpanAxis']).toBe(+ 'z',+ );+ expect(+ (await buildById('wheel-chassis-penetration')).measurements['wheelChassisOverlapMeters'],+ ).toBeGreaterThan(0);+ expect(+ (await buildById('wheel-clearance-control')).measurements['wheelChassisOverlapMeters'],+ ).toBe(0);++ const badFoliage = await buildById('bad-foliage-card');+ const validFoliage = await buildById('valid-foliage-card-control');+ if (badFoliage.kind !== 'scene' || validFoliage.kind !== 'scene') {+ throw new Error('Foliage corpus fixtures must be scenes.');+ }+ expect(+ inspectSceneMaterials({ intent: badFoliage.intent, scene: badFoliage.scene }).map(+ (finding) => finding.code,+ ),+ ).toContain('MAT_FOLIAGE_CARD_CONTRACT');+ expect(+ inspectSceneMaterials({ intent: validFoliage.intent, scene: validFoliage.scene }),+ ).toEqual([]);+ });+});diff --git a/src/qa/corpus.ts b/src/qa/corpus.tsnew file mode 100644index 00000000..0d463077--- /dev/null+++ b/src/qa/corpus.ts@@ -0,0 +1,499 @@+import * as THREE from 'three';++import {+ boxGeo,+ createPart,+ createPivot,+ createRoot,+ createVehicleFrame,+ createWheelAssembly,+ createWheelGeometrySet,+ foliageCardGeo,+ gameMaterial,+ sphereGeo,+} from '../primitives';+import {+ createAssetIntentV1,+ stampSemanticMetadataV1,+ type ArchitectureIntentV1Input,+ type AssetCategory,+ type AssetIntentV1,+ type CharacterIntentV1Input,+} from '../contracts';+import { foliageMaterial } from '../textures';++export type CorpusFixtureImplementation = 'active';++export type CorpusFixtureMeasurement = number | string | boolean;++export type CorpusFixturePayload =+ | {+ kind: 'scene';+ intent: AssetIntentV1;+ scene: THREE.Object3D;+ measurements: Readonly<Record<string, CorpusFixtureMeasurement>>;+ }+ | {+ kind: 'glb';+ intent: AssetIntentV1;+ glbBytes: Uint8Array;+ measurements: Readonly<Record<string, CorpusFixtureMeasurement>>;+ };++export interface KnownBadCorpusDescriptor {+ id: string;+ kind: 'failure' | 'control';+ category: AssetCategory;+ description: string;+ expectedCodes: readonly string[];+ implementation: CorpusFixtureImplementation;+ pairId: string;+ /** Deterministic executable fixture; category rules can consume these as they land. */+ build: () => CorpusFixturePayload | Promise<CorpusFixturePayload>;+}++const scenePayload = (+ category: AssetCategory,+ scene: THREE.Object3D,+ measurements: Readonly<Record<string, CorpusFixtureMeasurement>>,+ requiredParts: readonly string[] = [],+ architecture?: ArchitectureIntentV1Input,+ character?: CharacterIntentV1Input,+): CorpusFixturePayload => ({+ kind: 'scene',+ intent: createAssetIntentV1({+ category,+ requiredParts,+ ...(architecture ? { architecture } : {}),+ ...(character ? { character } : {}),+ }),+ scene,+ measurements,+});++function contactFixture(attached: boolean): CorpusFixturePayload {+ const root = createRoot(attached ? 'AttachedPartControl' : 'FloatingPart');+ const material = gameMaterial('#708090');+ createPart('Host', boxGeo(2, 1, 2), material, { parent: root, position: [0, 0.5, 0] });+ const partY = attached ? 1.25 : 1.6;+ createPart('Part', boxGeo(0.5, 0.5, 0.5), material, {+ parent: root,+ position: [0, partY, 0],+ });+ return scenePayload('prop', root, { contactGapMeters: partY - 1.25 }, ['Mesh_Host', 'Mesh_Part']);+}++function vehicleOrientationFixture(sideways: boolean): CorpusFixturePayload {+ const root = createRoot(sideways ? 'SidewaysVehicle' : 'ForwardVehicleControl');+ const material = gameMaterial('#445544');+ const frame = createVehicleFrame('VehicleFrame', {+ axles: [+ { id: 'front', position: [0.9, 0.3, 0] },+ { id: 'rear', position: [-0.9, 0.3, 0] },+ ],+ parent: root,+ });+ createPart('Hull', sideways ? boxGeo(0.8, 0.5, 3) : boxGeo(3, 0.5, 0.8), material, {+ parent: frame.root,+ position: [0, 0.25, 0],+ });+ const geometries = createWheelGeometrySet(0.3, 0.16);+ for (const [index, x] of [+ ['front', 0.9],+ ['rear', -0.9],+ ] as const) {+ for (const [side, z] of [+ ['left', -0.55],+ ['right', 0.55],+ ] as const) {+ createWheelAssembly(+ `${index}.${side}`,+ { tire: material, rim: material },+ {+ radius: 0.3,+ width: 0.16,+ side,+ index,+ position: [x, 0.3, z],+ steering: index === 'front',+ geometries,+ parent: frame.root,+ },+ );+ }+ }+ return scenePayload('vehicle', root, { dominantLengthAxis: sideways ? 'z' : 'x' }, ['Mesh_Hull']);+}++function limbFixture(inverted: boolean): CorpusFixturePayload {+ const root = createRoot(inverted ? 'InvertedLimb' : 'OrderedLimbControl');+ const material = gameMaterial('#a97852');+ const hip = createPivot('Hip', [0, 2, 0], root);+ const middleName = inverted ? 'Ankle' : 'Knee';+ const terminalName = inverted ? 'Knee' : 'Ankle';+ const middle = createPivot(middleName, [0, -0.8, 0], hip);+ const terminal = createPivot(terminalName, [0, -0.8, 0], middle);+ createPart('HipMarker', sphereGeo(0.16), material, { parent: hip });+ createPart('MiddleMarker', sphereGeo(0.14), material, { parent: middle });+ createPart('TerminalMarker', sphereGeo(0.12), material, { parent: terminal });+ return scenePayload(+ 'character',+ root,+ { jointOrder: `Joint_Hip>Joint_${middleName}>Joint_${terminalName}` },+ ['Joint_Hip', 'Joint_Knee', 'Joint_Ankle'],+ undefined,+ { bodyPlan: 'biped', grounded: false, locomotion: 'stationary' },+ );+}++function gableGeometry(): THREE.BufferGeometry {+ const geometry = new THREE.BufferGeometry();+ geometry.setAttribute(+ 'position',+ new THREE.Float32BufferAttribute([0, 0, -1.5, 0, 0, 1.5, 0, 1.2, 0], 3),+ );+ geometry.computeVertexNormals();+ return geometry;+}++function gableFixture(closed: boolean): CorpusFixturePayload {+ const root = createRoot(closed ? 'ClosedGableControl' : 'OpenGable');+ const wall = gameMaterial('#c9b38c');+ const roof = gameMaterial('#5f646d');+ createPart('Building', boxGeo(5, 2, 3), wall, { parent: root, position: [0, 1, 0] });+ createPart('RoofA', boxGeo(5.4, 0.1, 1.9), roof, {+ parent: root,+ position: [0, 2.5, 0.72],+ rotation: [32, 0, 0],+ });+ createPart('RoofB', boxGeo(5.4, 0.1, 1.9), roof, {+ parent: root,+ position: [0, 2.5, -0.72],+ rotation: [-32, 0, 0],+ });+ const front = new THREE.Mesh(gableGeometry(), wall);+ front.name = 'Gable_Front';+ front.position.set(2.51, 2, 0);+ root.add(front);+ if (closed) {+ const back = new THREE.Mesh(gableGeometry(), wall);+ back.name = 'Gable_Back';+ back.position.set(-2.51, 2, 0);+ root.add(back);+ }+ return scenePayload(+ 'architecture',+ root,+ { gableClosureCount: closed ? 2 : 1 },+ ['Gable_Front', 'Gable_Back'],+ { enterable: false },+ );+}++function roofPanelFixture(aligned: boolean): CorpusFixturePayload {+ const root = createRoot(aligned ? 'AlignedRoofPanelsControl' : 'RotatedRoofPanels');+ const roof = new THREE.Object3D();+ roof.name = 'Roof';+ root.add(roof);+ const material = gameMaterial('#59606a');+ for (const side of [-1, 1] as const) {+ for (let index = 0; index < 4; index++) {+ const panel = new THREE.Mesh(+ aligned ? boxGeo(0.9, 0.08, 2.3) : boxGeo(2.3, 0.08, 0.9),+ material,+ );+ panel.name = `RoofPanel_${side > 0 ? 'A' : 'B'}_${index}`;+ panel.position.set(-1.35 + index * 0.9, 2.4, side * 0.75);+ panel.rotation.x = side * 0.55;+ panel.userData['kilnRoofPanel'] = {+ ridgeAxis: 'x',+ spanAxis: aligned ? 'z' : 'x',+ };+ roof.add(panel);+ }+ }+ return scenePayload(+ 'architecture',+ root,+ { ridgeAxis: 'x', panelSpanAxis: aligned ? 'z' : 'x' },+ ['Roof'],+ { enterable: false, roof: { closedEnds: false } },+ );+}++function wheelFixture(penetrating: boolean): CorpusFixturePayload {+ const root = createRoot(penetrating ? 'WheelChassisPenetration' : 'WheelClearanceControl');+ const body = gameMaterial('#3e5368');+ const rubber = gameMaterial('#202124');+ const rim = gameMaterial('#8b949e', { metalness: 0.7 });+ const chassisBottom = 0.8;+ const wheelRadius = 0.4;+ const wheelY = penetrating ? 1.05 : 0.4;+ const frame = createVehicleFrame('VehicleFrame', {+ axles: [+ { id: 'front', position: [1.05, wheelY, 0] },+ { id: 'rear', position: [-1.05, wheelY, 0] },+ ],+ parent: root,+ });+ createPart('Chassis', boxGeo(3, 0.6, 1.2), body, {+ parent: frame.root,+ position: [0, 1.1, 0],+ });+ const wheelWidth = 0.2;+ const geometries = createWheelGeometrySet(wheelRadius, wheelWidth);+ for (const x of [-1.05, 1.05]) {+ for (const z of [-0.75, 0.75]) {+ const index = x > 0 ? 'front' : 'rear';+ createWheelAssembly(+ `Wheel_${x}_${z}`,+ { tire: rubber, rim },+ {+ radius: wheelRadius,+ width: wheelWidth,+ side: z < 0 ? 'left' : 'right',+ index,+ position: [x, wheelY, z],+ steering: index === 'front',+ geometries,+ parent: frame.root,+ },+ );+ }+ }+ return scenePayload('vehicle', root, {+ wheelChassisOverlapMeters: Math.max(0, wheelY + wheelRadius - chassisBottom),+ });+}++const TRANSLUCENT_GREEN_PNG = new Uint8Array([+ 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 2, 0, 0, 0, 2, 8, 6, 0, 0,+ 0, 114, 182, 13, 36, 0, 0, 0, 9, 112, 72, 89, 115, 0, 0, 3, 232, 0, 0, 3, 232, 1, 181, 123, 82,+ 107, 0, 0, 0, 17, 73, 68, 65, 84, 8, 153, 99, 80, 88, 224, 208, 0, 194, 12, 48, 6, 0, 52, 146, 6,+ 1, 143, 41, 75, 7, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,+]);++function translucentLeafTexture(): THREE.DataTexture {+ const pixels = new Uint8Array([+ 32, 160, 64, 128, 32, 160, 64, 128, 32, 160, 64, 128, 32, 160, 64, 128,+ ]);+ const texture = new THREE.DataTexture(pixels, 2, 2, THREE.RGBAFormat);+ texture.name = 'leaf-albedo';+ texture.colorSpace = THREE.SRGBColorSpace;+ texture.needsUpdate = true;+ texture.userData['encoded'] = { mime: 'image/png', bytes: TRANSLUCENT_GREEN_PNG };+ texture.userData['kilnTexture'] = {+ usage: 'albedo',+ colorSpace: 'srgb',+ width: 2,+ height: 2,+ hasAlpha: true,+ };+ return texture;+}++function foliageFixture(valid: boolean): CorpusFixturePayload {+ const root = createRoot(valid ? 'ValidFoliageCardControl' : 'BadFoliageCard');+ const contact = new THREE.Object3D();+ contact.name = 'Contact_Ground';+ stampSemanticMetadataV1(contact, { roles: ['vegetation.contact.ground'] });+ root.add(contact);+ const material = valid+ ? foliageMaterial(translucentLeafTexture(), { alphaCutoff: 0.5 })+ : gameMaterial('#228833');+ const card = new THREE.Mesh(foliageCardGeo({ width: 1.5, height: 2 }), material);+ card.name = 'Mesh_Leaves';+ root.add(card);+ return scenePayload('vegetation', root, { portableFoliageCardContract: valid }, ['Mesh_Leaves']);+}++async function validGlbFixture(): Promise<CorpusFixturePayload> {+ const root = createRoot('ValidGlbControl');+ createPart('Cube', boxGeo(1, 1, 1), gameMaterial('#778899'), {+ parent: root,+ position: [0, 0.5, 0],+ });+ const intent = createAssetIntentV1({ category: 'prop' });+ const { renderSceneToGLB } = await import('../render');+ const result = await renderSceneToGLB(root, { intent });+ return {+ kind: 'glb',+ intent,+ glbBytes: result.bytes,+ measurements: { validatorExpectedErrors: false },+ };+}++/**+ * Fixed W1 regression corpus. Every entry owns an executable deterministic+ * payload now; category-specific rules may consume the reserved expected codes+ * in later waves without having to invent or reinterpret test geometry.+ */+export const W1_KNOWN_BAD_CORPUS = [+ {+ id: 'invalid-glb',+ kind: 'failure',+ category: 'prop',+ description: 'Malformed final GLB bytes rejected by the Khronos validator.',+ expectedCodes: ['GLTF_GLB_UNEXPECTED_END_OF_HEADER'],+ implementation: 'active',+ pairId: 'valid-glb-control',+ build: () => ({+ kind: 'glb',+ intent: createAssetIntentV1({ category: 'prop' }),+ glbBytes: new Uint8Array([0x67, 0x6c, 0x54, 0x46]),+ measurements: { validatorExpectedErrors: true },+ }),+ },+ {+ id: 'valid-glb-control',+ kind: 'control',+ category: 'prop',+ description: 'Minimal validator-clean GLB.',+ expectedCodes: [],+ implementation: 'active',+ pairId: 'invalid-glb',+ build: validGlbFixture,+ },+ {+ id: 'floating-part',+ kind: 'failure',+ category: 'prop',+ description: 'One visible part has no contact with any intended assembly.',+ expectedCodes: ['UNIVERSAL_FLOATING_PART'],+ implementation: 'active',+ pairId: 'attached-part-control',+ build: () => contactFixture(false),+ },+ {+ id: 'attached-part-control',+ kind: 'control',+ category: 'prop',+ description: 'Equivalent part attached to its intended host.',+ expectedCodes: [],+ implementation: 'active',+ pairId: 'floating-part',+ build: () => contactFixture(true),+ },+ {+ id: 'sideways-vehicle',+ kind: 'failure',+ category: 'vehicle',+ description: 'Vehicle body is built along Z instead of trusted +X forward.',+ expectedCodes: ['VEH_ORIENTATION_SIDEWAYS'],+ implementation: 'active',+ pairId: 'forward-vehicle-control',+ build: () => vehicleOrientationFixture(true),+ },+ {+ id: 'forward-vehicle-control',+ kind: 'control',+ category: 'vehicle',+ description: 'Equivalent vehicle is built nose-first along +X.',+ expectedCodes: [],+ implementation: 'active',+ pairId: 'sideways-vehicle',+ build: () => vehicleOrientationFixture(false),+ },+ {+ id: 'inverted-limb',+ kind: 'failure',+ category: 'character',+ description: 'Declared limb chain has inverted semantic joint ordering.',+ expectedCodes: ['CHAR_LIMB_ORDER_INVERTED'],+ implementation: 'active',+ pairId: 'ordered-limb-control',+ build: () => limbFixture(true),+ },+ {+ id: 'ordered-limb-control',+ kind: 'control',+ category: 'character',+ description: 'Equivalent limb follows its declared parent/child order.',+ expectedCodes: [],+ implementation: 'active',+ pairId: 'inverted-limb',+ build: () => limbFixture(false),+ },+ {+ id: 'open-gable',+ kind: 'failure',+ category: 'architecture',+ description: 'Trusted closed gable shell is missing an end closure.',+ expectedCodes: ['ARCH_OPEN_GABLE'],+ implementation: 'active',+ pairId: 'closed-gable-control',+ build: () => gableFixture(false),+ },+ {+ id: 'closed-gable-control',+ kind: 'control',+ category: 'architecture',+ description: 'Equivalent gable shell has both complete end closures.',+ expectedCodes: [],+ implementation: 'active',+ pairId: 'open-gable',+ build: () => gableFixture(true),+ },+ {+ id: 'rotated-roof-panels',+ kind: 'failure',+ category: 'architecture',+ description: 'Roof panels run along the ridge instead of ridge-to-eave.',+ expectedCodes: ['ARCH_ROOF_AXIS'],+ implementation: 'active',+ pairId: 'aligned-roof-panels-control',+ build: () => roofPanelFixture(false),+ },+ {+ id: 'aligned-roof-panels-control',+ kind: 'control',+ category: 'architecture',+ description: 'Equivalent roof panels run ridge-to-eave in roof-local coordinates.',+ expectedCodes: [],+ implementation: 'active',+ pairId: 'rotated-roof-panels',+ build: () => roofPanelFixture(true),+ },+ {+ id: 'wheel-chassis-penetration',+ kind: 'failure',+ category: 'vehicle',+ description: 'A wheel assembly penetrates the chassis beyond allowed fender overlap.',+ expectedCodes: ['VEH_WHEEL_CHASSIS_PENETRATION'],+ implementation: 'active',+ pairId: 'wheel-clearance-control',+ build: () => wheelFixture(true),+ },+ {+ id: 'wheel-clearance-control',+ kind: 'control',+ category: 'vehicle',+ description: 'Equivalent wheel assembly retains valid chassis/fender clearance.',+ expectedCodes: [],+ implementation: 'active',+ pairId: 'wheel-chassis-penetration',+ build: () => wheelFixture(false),+ },+ {+ id: 'bad-foliage-card',+ kind: 'failure',+ category: 'vegetation',+ description: 'Foliage card lacks the required UV/alpha-mask/double-sided material contract.',+ expectedCodes: ['MAT_FOLIAGE_CARD_CONTRACT'],+ implementation: 'active',+ pairId: 'valid-foliage-card-control',+ build: () => foliageFixture(false),+ },+ {+ id: 'valid-foliage-card-control',+ kind: 'control',+ category: 'vegetation',+ description:+ 'Equivalent foliage card has UVs, alpha data, MASK cutoff, and double-sided output.',+ expectedCodes: [],+ implementation: 'active',+ pairId: 'bad-foliage-card',+ build: () => foliageFixture(true),+ },+] as const satisfies readonly KnownBadCorpusDescriptor[];diff --git a/src/qa/environment.test.ts b/src/qa/environment.test.tsnew file mode 100644index 00000000..8d73a49d--- /dev/null+++ b/src/qa/environment.test.ts@@ -0,0 +1,381 @@+import { describe, expect, test } from 'bun:test';+import { WebIO } from '@gltf-transform/core';+import * as THREE from 'three';++import {+ createAssetIntentV1,+ readSemanticMetadataV1FromExtras,+ stampSemanticMetadataV1,+} from '../contracts';+import { renderSceneToGLB } from '../render';+import {+ ENVIRONMENT_SOCKET_TYPES,+ ENVIRONMENT_SUBTYPES,+ evaluateEnvironmentGroundQa,+ evaluateEnvironmentNavigabilityQa,+ evaluateEnvironmentSocketQa,+ evaluateEnvironmentTileEdgeQa,+ resolveEnvironmentIntentProfile,+ resolveEnvironmentSockets,+} from './environment';+import { buildPropEnvironmentSemanticGuidance } from './prop-environment-prompt';+import type { QaContext } from './types';++const material = new THREE.MeshStandardMaterial({ color: '#68765c', roughness: 0.9 });++function context(+ root: THREE.Object3D,+ options: {+ subtype?: string;+ capabilities?: Array<'tileable' | 'navigable' | 'grounded'>;+ } = {},+): QaContext {+ return {+ intent: createAssetIntentV1({+ category: 'environment',+ ...(options.subtype ? { subtype: options.subtype } : {}),+ capabilities: options.capabilities ?? [],+ }),+ scene: root,+ };+}++function codes(findings: readonly { code: string }[]): string[] {+ return findings.map((finding) => finding.code);+}++function semanticTile(options: { heightSeam?: boolean; socketOffset?: number } = {}): THREE.Group {+ const root = new THREE.Group();+ root.name = 'TileRoot';+ const geometry = new THREE.PlaneGeometry(2, 2, 4, 4);+ geometry.rotateX(-Math.PI / 2);+ if (options.heightSeam) {+ const positions = geometry.getAttribute('position');+ for (let index = 0; index < positions.count; index++) {+ if (positions.getX(index) > 0.99) positions.setY(index, 0.2);+ }+ positions.needsUpdate = true;+ geometry.computeVertexNormals();+ }+ const tile = new THREE.Mesh(geometry, material);+ tile.name = 'EnvironmentTile';+ const zOffset = options.socketOffset ?? 0;+ stampSemanticMetadataV1(tile, {+ roles: ['environment.tile.surface', 'environment.ground.surface'],+ frames: [+ { id: 'tile.x-negative', translation: [-1, 0, 0], rotation: [0, 0, 0, 1] },+ { id: 'tile.x-positive', translation: [1, 0, zOffset], rotation: [0, 0, 0, 1] },+ { id: 'tile.z-negative', translation: [0, 0, -1], rotation: [0, 0, 0, 1] },+ { id: 'tile.z-positive', translation: [0, 0, 1], rotation: [0, 0, 0, 1] },+ ],+ sockets: [+ {+ id: 'tile-x-negative',+ type: 'environment.tile.x-negative',+ frame: 'tile.x-negative',+ compatibleTypes: ['environment.tile.x-positive'],+ },+ {+ id: 'tile-x-positive',+ type: 'environment.tile.x-positive',+ frame: 'tile.x-positive',+ compatibleTypes: ['environment.tile.x-negative'],+ },+ {+ id: 'tile-z-negative',+ type: 'environment.tile.z-negative',+ frame: 'tile.z-negative',+ compatibleTypes: ['environment.tile.z-positive'],+ },+ {+ id: 'tile-z-positive',+ type: 'environment.tile.z-positive',+ frame: 'tile.z-positive',+ compatibleTypes: ['environment.tile.z-negative'],+ },+ ],+ });+ root.add(tile);+ return root;+}++function box(+ name: string,+ size: [number, number, number],+ position: [number, number, number],+ role?: string,+) {+ const value = new THREE.Mesh(new THREE.BoxGeometry(...size), material);+ value.name = name;+ value.position.set(...position);+ if (role) stampSemanticMetadataV1(value, { roles: [role] });+ return value;+}++function corridor(size: [number, number, number] = [1.2, 2, 4], blocker = false): THREE.Group {+ const root = new THREE.Group();+ root.name = 'CaveEntrance';+ root.add(box('Path', [1.4, 0.05, 4.2], [0, -0.025, 0], 'environment.path.surface'));+ const marker = new THREE.Group();+ marker.name = 'ClearRoute';+ marker.position.y = size[1] / 2;+ marker.scale.set(...size);+ stampSemanticMetadataV1(marker, { roles: ['environment.navigation.corridor.main'] });+ root.add(marker);+ if (blocker) root.add(box('RockBlocker', [0.4, 1, 0.4], [0, 0.5, 0]));+ return root;+}++function socketCarrier(types: string[]): THREE.Group {+ const opposite = new Map<string, string>([+ ['environment.tile.x-negative', 'environment.tile.x-positive'],+ ['environment.tile.x-positive', 'environment.tile.x-negative'],+ ['environment.tile.z-negative', 'environment.tile.z-positive'],+ ['environment.tile.z-positive', 'environment.tile.z-negative'],+ ['environment.road.start', 'environment.road.end'],+ ['environment.road.end', 'environment.road.start'],+ ]);+ const carrier = new THREE.Group();+ carrier.name = 'DeclaredSocketCarrier';+ stampSemanticMetadataV1(carrier, {+ roles: ['environment.socket-carrier'],+ frames: types.map((_type, index) => ({+ id: `socket.${index}`,+ translation: [index, 0, 0],+ rotation: [0, 0, 0, 1],+ })),+ sockets: types.map((type, index) => ({+ id: `socket-${index}`,+ type,+ frame: `socket.${index}`,+ compatibleTypes: opposite.has(type) ? [opposite.get(type)!] : [],+ })),+ });+ return carrier;+}++describe('ENV-001 intent profile', () => {+ test('freezes all requested subtypes and closure-owned capabilities', () => {+ expect(ENVIRONMENT_SUBTYPES).toEqual([+ 'terrain-tile',+ 'rock-cliff',+ 'cave',+ 'road-path',+ 'shoreline',+ 'wall-gate',+ 'bridge',+ 'set-dressing-cluster',+ 'custom',+ ]);+ expect(ENVIRONMENT_SOCKET_TYPES).toHaveLength(13);+ const profile = resolveEnvironmentIntentProfile(+ createAssetIntentV1({+ category: 'environment',+ subtype: 'road',+ capabilities: ['tileable', 'navigable'],+ }),+ );+ expect(profile).toEqual({+ schemaVersion: 1,+ subtype: 'road-path',+ tileable: true,+ navigable: true,+ });+ expect(+ resolveEnvironmentIntentProfile(createAssetIntentV1({ category: 'prop' })),+ ).toBeUndefined();+ });+});++describe('ENV-002 tile edge continuity', () => {+ test('accepts aligned height/normal/material samples and paired semantic sockets', () => {+ const value = context(semanticTile(), { subtype: 'terrain-tile', capabilities: ['tileable'] });+ expect(evaluateEnvironmentSocketQa(value)).toEqual([]);+ expect(evaluateEnvironmentTileEdgeQa(value)).toEqual([]);+ });++ test('blocks a measured tagged height seam and socket misalignment', () => {+ const seam = context(semanticTile({ heightSeam: true }), {+ subtype: 'terrain-tile',+ capabilities: ['tileable'],+ });+ const seamFindings = evaluateEnvironmentTileEdgeQa(seam);+ expect(codes(seamFindings)).toContain('ENV_TILE_EDGE_HEIGHT_SEAM');+ expect(+ seamFindings.find((finding) => finding.code === 'ENV_TILE_EDGE_HEIGHT_SEAM')?.disposition,+ ).toBe('block');++ const socket = context(semanticTile({ socketOffset: 0.1 }), {+ subtype: 'terrain-tile',+ capabilities: ['tileable'],+ });+ expect(codes(evaluateEnvironmentSocketQa(socket))).toContain('ENV_SOCKET_PAIR_MISALIGNED');+ });++ test('keeps untagged inferred edge evidence nonblocking', () => {+ const tile = semanticTile({ heightSeam: true });+ const mesh = tile.getObjectByName('EnvironmentTile')!;+ delete mesh.userData.kilnSemantic;+ const findings = evaluateEnvironmentTileEdgeQa(+ context(tile, { subtype: 'terrain-tile', capabilities: ['tileable'] }),+ );+ expect(findings.length).toBeGreaterThan(0);+ expect(findings.every((finding) => finding.disposition === 'warn')).toBe(true);+ });+});++describe('ENV-003 navigable negative space', () => {+ test('accepts a clear corridor, observes default dimensions, and blocks authored obstacles', () => {+ expect(+ evaluateEnvironmentNavigabilityQa(+ context(corridor(), { subtype: 'cave', capabilities: ['navigable'] }),+ ),+ ).toEqual([]);++ const undersized = evaluateEnvironmentNavigabilityQa(+ context(corridor([0.6, 1.4, 4]), { subtype: 'cave', capabilities: ['navigable'] }),+ );+ expect(codes(undersized)).toEqual(['ENV_NAV_CORRIDOR_TOO_NARROW', 'ENV_NAV_HEADROOM_TOO_LOW']);+ expect(undersized.every((finding) => finding.disposition === 'warn')).toBe(true);+ expect(+ codes(+ evaluateEnvironmentNavigabilityQa(+ context(corridor([1.2, 2, 4], true), { subtype: 'cave', capabilities: ['navigable'] }),+ ),+ ),+ ).toContain('ENV_NAV_CORRIDOR_BLOCKED');+ });++ test('measures rotated corridors in their local frame instead of their inflated AABB', () => {+ const root = corridor([0.6, 2, 4]);+ root.getObjectByName('ClearRoute')!.rotation.y = Math.PI / 4;+ root.add(box('AabbOnlyRock', [0.2, 1, 0.2], [1.2, 0.5, -1.2]));+ const outside = evaluateEnvironmentNavigabilityQa(+ context(root, { subtype: 'cave', capabilities: ['navigable'] }),+ );+ expect(codes(outside)).toContain('ENV_NAV_CORRIDOR_TOO_NARROW');+ expect(codes(outside)).not.toContain('ENV_NAV_CORRIDOR_BLOCKED');++ root.add(box('TrueBlocker', [0.2, 1, 0.2], [0, 0.5, 0]));+ expect(+ codes(+ evaluateEnvironmentNavigabilityQa(+ context(root, { subtype: 'cave', capabilities: ['navigable'] }),+ ),+ ),+ ).toContain('ENV_NAV_CORRIDOR_BLOCKED');+ });++ test('reports untagged inferred navigation as an observe-path warning, never a blocker', () => {+ const root = new THREE.Group();+ root.add(box('Road', [2, 0.1, 4], [0, 0, 0]));+ const findings = evaluateEnvironmentNavigabilityQa(+ context(root, { subtype: 'road', capabilities: ['navigable'] }),+ );+ expect(codes(findings)).toEqual(['ENV_NAV_CLEARANCE_UNASSESSED']);+ expect(findings[0]?.disposition).toBe('warn');+ });+});++describe('ENV-004 semantic placement sockets', () => {+ test('enforces only socket pairs that were explicitly declared', () => {+ expect(evaluateEnvironmentSocketQa(context(new THREE.Group(), { subtype: 'road' }))).toEqual(+ [],+ );+ expect(+ codes(+ evaluateEnvironmentSocketQa(+ context(socketCarrier(['environment.road.start']), { subtype: 'road' }),+ ),+ ),+ ).toEqual(['ENV_SOCKET_MISSING']);+ expect(+ evaluateEnvironmentSocketQa(+ context(socketCarrier(['environment.tile.x-negative', 'environment.tile.x-positive']), {+ subtype: 'terrain-tile',+ capabilities: ['tileable'],+ }),+ ),+ ).toEqual([]);+ });++ test('resolves declared frames in asset-local space', () => {+ const sockets = resolveEnvironmentSockets(semanticTile());+ expect(sockets.map((socket) => socket.type)).toEqual([+ 'environment.tile.x-negative',+ 'environment.tile.x-positive',+ 'environment.tile.z-negative',+ 'environment.tile.z-positive',+ ]);+ expect(+ sockets.find((socket) => socket.type === 'environment.tile.x-positive')?.translation,+ ).toEqual([1, 0, 0]);+ });++ test('preserves exact frame/socket metadata through GLB export and reload', async () => {+ const root = semanticTile();+ const rendered = await renderSceneToGLB(root, {+ intent: createAssetIntentV1({+ category: 'environment',+ subtype: 'terrain-tile',+ capabilities: ['tileable'],+ }),+ optimize: 'full',+ });+ const document = await new WebIO().readBinary(rendered.bytes);+ const node = document+ .getRoot()+ .listNodes()+ .find((candidate) => candidate.getName() === 'EnvironmentTile');+ const loaded = readSemanticMetadataV1FromExtras(node?.getExtras() ?? {});+ expect(loaded?.frames.map((frame) => frame.id)).toEqual([+ 'tile.x-negative',+ 'tile.x-positive',+ 'tile.z-negative',+ 'tile.z-positive',+ ]);+ expect(loaded?.sockets.map((socket) => socket.type)).toEqual([+ 'environment.tile.x-negative',+ 'environment.tile.x-positive',+ 'environment.tile.z-negative',+ 'environment.tile.z-positive',+ ]);+ });+});++describe('ENV-005 ground policy', () => {+ test('allows intentional terrain volume and localizes buried, floating, and skirt layers', () => {+ const root = new THREE.Group();+ root.add(+ box('Terrain', [4, 0.6, 4], [0, -0.3, 0], 'environment.terrain.volume.main'),+ box('BuriedRoad', [2, 0.2, 2], [0, -0.1, 0], 'environment.road.surface'),+ box('FloatingDeck', [1, 0.1, 1], [3, 1, 0], 'environment.bridge.deck'),+ box('ThinSkirt', [3, 0.04, 3], [-4, -0.2, 0]),+ );+ const findings = evaluateEnvironmentGroundQa(context(root, { subtype: 'custom' }));+ expect(codes(findings)).toEqual([+ 'ENV_FUNCTIONAL_PART_BURIED',+ 'ENV_LAYER_UNSUPPORTED',+ 'ENV_GROUND_UNDECLARED_SKIRT',+ ]);+ expect(findings.every((finding) => finding.disposition === 'warn')).toBe(true);+ });+});++describe('prop/environment prompt guidance', () => {+ test('names subtype, tile seams, sockets, corridor, and ground-policy roles', () => {+ const intent = createAssetIntentV1({+ category: 'environment',+ subtype: 'bridge',+ capabilities: ['tileable', 'navigable'],+ });+ const guidance = buildPropEnvironmentSemanticGuidance(intent);+ expect(guidance).toContain('Resolved subtype: bridge');+ expect(guidance).toContain('environment.bridge.start/end');+ expect(guidance).toContain('sampled height, vertex normal');+ expect(guidance).toContain('explicitly requested tile axis');+ expect(guidance).not.toContain('opposing X and Z');+ expect(guidance).toContain('environment.navigation.corridor.<id>');+ expect(guidance).toContain('environment.terrain.volume.*');+ });+});diff --git a/src/qa/environment.ts b/src/qa/environment.tsnew file mode 100644index 00000000..50e59240--- /dev/null+++ b/src/qa/environment.ts@@ -0,0 +1,824 @@+import * as THREE from 'three';++import {+ readSemanticMetadataV1,+ type SemanticQuaternion,+ type SemanticSocketV1,+} from '../contracts';+import type { EnvironmentSocketType } from '../contracts/environment';+import {+ createOrientedProbeBox3,+ probeLocalFrameFromQuaternion,+ probeOrientedPenetration,+ type OrientedProbeBox3,+} from './geometry-relations';+import { conformancePromotionAuthorization, KILN_ENGINE_QA_OWNER, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';++const PROFILE = 'environment.semantic';+const EDGE_HEIGHT_TOLERANCE_METERS = 0.02;+const EDGE_NORMAL_TOLERANCE_DEGREES = 8;+const SOCKET_ALIGNMENT_TOLERANCE_METERS = 0.02;+const GROUND_TOLERANCE_METERS = 0.02;++export {+ ENVIRONMENT_SOCKET_TYPES,+ ENVIRONMENT_SUBTYPES,+ resolveEnvironmentIntentProfile,+ type EnvironmentIntentProfileV1,+ type EnvironmentSocketType,+ type EnvironmentSubtype,+} from '../contracts/environment';++export interface ResolvedEnvironmentSocketV1 {+ id: string;+ type: string;+ node: string;+ translation: [number, number, number];+ rotation: SemanticQuaternion;+ compatibleTypes: string[];+ allowedRotationsDegrees?: number[];+}++interface LocalPart {+ node: THREE.Object3D;+ roles: readonly string[];+ box?: THREE.Box3;+ orientedBox?: OrientedProbeBox3;+ renderable: boolean;+}++interface BoundarySample {+ bin: number;+ height: number;+ normal: THREE.Vector3;+ material: string;+}++interface EdgePairMeasurements {+ axis: 'x' | 'z';+ source: 'semantic' | 'fallback';+ sampleCoverage: number;+ maximumHeightDelta: number;+ maximumNormalDeltaDegrees: number;+ materialMismatch: boolean;+ socketCrossAxisDelta: number | null;+}++const stable = (value: number): number => Math.round(value * 1_000_000) / 1_000_000;++function finding(context: QaContext, value: Omit<QaFinding, 'profile'>): QaFinding {+ return { ...value, profile: context.intent.qaProfile || PROFILE };+}++function rolesOf(node: THREE.Object3D): readonly string[] {+ return readSemanticMetadataV1(node)?.roles ?? [];+}++function nodePath(root: THREE.Object3D, node: THREE.Object3D): string {+ const names: string[] = [];+ let cursor: THREE.Object3D | null = node;+ while (cursor) {+ names.push(cursor.name || cursor.type);+ if (cursor === root) break;+ cursor = cursor.parent;+ }+ return names.reverse().join('/');+}++function transformedBox(source: THREE.Box3, transform: THREE.Matrix4): THREE.Box3 {+ const result = new THREE.Box3();+ for (const x of [source.min.x, source.max.x]) {+ for (const y of [source.min.y, source.max.y]) {+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(transform));+ }+ }+ }+ return result;+}++function orientedBoxFromLocalBounds(+ root: THREE.Object3D,+ node: THREE.Object3D,+ source: THREE.Box3,+): OrientedProbeBox3 | undefined {+ const relative = root.matrixWorld.clone().invert().multiply(node.matrixWorld);+ if (!relative.elements.every(Number.isFinite)) return undefined;+ const position = new THREE.Vector3();+ const rotation = new THREE.Quaternion();+ const scale = new THREE.Vector3();+ relative.decompose(position, rotation, scale);+ const recomposed = new THREE.Matrix4().compose(position, rotation, scale);+ const residual = Math.max(+ ...relative.elements.map((component, index) =>+ Math.abs(component - (recomposed.elements[index] ?? component)),+ ),+ );+ // Non-uniformly scaled rotated ancestors can introduce shear. An OBB built+ // from a lossy decomposition would be unsafe evidence, so leave it unassessed.+ if (residual > 1e-5) return undefined;+ const center = source.getCenter(new THREE.Vector3()).applyMatrix4(relative);+ const sourceHalf = source.getSize(new THREE.Vector3()).multiplyScalar(0.5);+ const halfExtents: [number, number, number] = [+ Math.abs(sourceHalf.x * scale.x),+ Math.abs(sourceHalf.y * scale.y),+ Math.abs(sourceHalf.z * scale.z),+ ];+ if (halfExtents.some((extent) => !Number.isFinite(extent) || extent <= 1e-9)) return undefined;+ rotation.normalize();+ return createOrientedProbeBox3({+ id: `${node.name || node.type}:${node.uuid}`,+ frame: probeLocalFrameFromQuaternion(+ `${node.name || node.type}:asset-local`,+ [stable(center.x), stable(center.y), stable(center.z)],+ [rotation.x, rotation.y, rotation.z, rotation.w],+ ),+ halfExtents,+ });+}++function collectParts(root: THREE.Object3D): LocalPart[] {+ root.updateWorldMatrix(true, true);+ const rootInverse = root.matrixWorld.clone().invert();+ const result: LocalPart[] = [];+ root.traverse((node) => {+ const roles = rolesOf(node);+ const renderable = node instanceof THREE.Mesh;+ let box: THREE.Box3 | undefined;+ let orientedBox: OrientedProbeBox3 | undefined;+ let source: THREE.Box3 | undefined;+ if (renderable && node.geometry instanceof THREE.BufferGeometry) {+ node.geometry.computeBoundingBox();+ if (node.geometry.boundingBox) {+ source = node.geometry.boundingBox;+ }+ } else if (roles.length > 0) {+ source = new THREE.Box3(+ new THREE.Vector3(-0.5, -0.5, -0.5),+ new THREE.Vector3(0.5, 0.5, 0.5),+ );+ }+ if (source) {+ box = transformedBox(source, rootInverse.clone().multiply(node.matrixWorld));+ orientedBox = orientedBoxFromLocalBounds(root, node, source);+ }+ if (box?.isEmpty()) box = undefined;+ result.push({+ node,+ roles,+ ...(box ? { box } : {}),+ ...(orientedBox ? { orientedBox } : {}),+ renderable,+ });+ });+ return result;+}++function quaternionTuple(value: THREE.Quaternion): SemanticQuaternion {+ return [stable(value.x), stable(value.y), stable(value.z), stable(value.w)];+}++function resolveSocket(+ root: THREE.Object3D,+ node: THREE.Object3D,+ socket: SemanticSocketV1,+): ResolvedEnvironmentSocketV1 | undefined {+ const metadata = readSemanticMetadataV1(node);+ const frame = metadata?.frames.find((candidate) => candidate.id === socket.frame);+ if (!frame) return undefined;+ root.updateWorldMatrix(true, true);+ const rootInverse = root.matrixWorld.clone().invert();+ const point = new THREE.Vector3(...frame.translation)+ .applyMatrix4(node.matrixWorld)+ .applyMatrix4(rootInverse);+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE.Quaternion()).invert();+ const rotation = node+ .getWorldQuaternion(new THREE.Quaternion())+ .multiply(new THREE.Quaternion(...frame.rotation))+ .premultiply(rootInverseQuaternion)+ .normalize();+ return {+ id: socket.id,+ type: socket.type,+ node: node.name || node.type,+ translation: [stable(point.x), stable(point.y), stable(point.z)],+ rotation: quaternionTuple(rotation),+ compatibleTypes: [...socket.compatibleTypes],+ ...(socket.allowedRotationsDegrees+ ? { allowedRotationsDegrees: [...socket.allowedRotationsDegrees] }+ : {}),+ };+}++/** Resolve semantic frames in asset-local space for Studio/starter consumers. */+export function resolveEnvironmentSockets(root: THREE.Object3D): ResolvedEnvironmentSocketV1[] {+ const result: ResolvedEnvironmentSocketV1[] = [];+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ for (const socket of metadata?.sockets ?? []) {+ if (!socket.type.startsWith('environment.')) continue;+ const resolved = resolveSocket(root, node, socket);+ if (resolved) result.push(resolved);+ }+ });+ return result.sort((a, b) => `${a.type}:${a.id}`.localeCompare(`${b.type}:${b.id}`));+}++function socketByType(+ sockets: readonly ResolvedEnvironmentSocketV1[],+ type: EnvironmentSocketType,+): ResolvedEnvironmentSocketV1 | undefined {+ return sockets.find((socket) => socket.type === type);+}++const SOCKET_PAIR_CONTRACTS = [+ {+ label: 'X tile axis',+ negative: ['environment.tile.x-negative'],+ positive: ['environment.tile.x-positive'],+ },+ {+ label: 'Z tile axis',+ negative: ['environment.tile.z-negative'],+ positive: ['environment.tile.z-positive'],+ },+ {+ label: 'road join',+ negative: ['environment.road.start'],+ positive: ['environment.road.end'],+ },+ {+ label: 'bridge join',+ negative: ['environment.bridge.start'],+ positive: ['environment.bridge.end'],+ },+ {+ label: 'wall/gate join',+ negative: ['environment.wall.left', 'environment.gate.left'],+ positive: ['environment.wall.right', 'environment.gate.right'],+ },+] as const;++/** Exact socket presence/alignment for trusted environment profiles. */+export function evaluateEnvironmentSocketQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'environment' || !(context.scene instanceof THREE.Object3D)) {+ return [];+ }+ const root = context.scene;+ const sockets = resolveEnvironmentSockets(root);+ const findings: QaFinding[] = [];+ for (const pair of SOCKET_PAIR_CONTRACTS) {+ const declared = [...pair.negative, ...pair.positive].some((type) =>+ sockets.some((socket) => socket.type === type),+ );+ if (!declared) continue;+ for (const side of [pair.negative, pair.positive]) {+ if (side.some((type) => sockets.some((socket) => socket.type === type))) continue;+ findings.push(+ finding(context, {+ code: 'ENV_SOCKET_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Declared ${pair.label} is incomplete; its opposite socket is missing.`,+ affected: { node: root.name || 'environment-root' },+ measurement: { name: 'declaredPairSocketCount', actual: 0, expected: 1, threshold: 1 },+ viewHints: ['top', 'generic.top.semantic-overlay'],+ repairText: `Complete the declared ${pair.label} with ${side.join(' or ')} without inventing unrelated axes or joins.`,+ }),+ );+ }+ }+ for (const axis of ['x', 'z'] as const) {+ const negative = socketByType(sockets, `environment.tile.${axis}-negative`);+ const positive = socketByType(sockets, `environment.tile.${axis}-positive`);+ if (!negative || !positive) continue;+ const cross = axis === 'x' ? 2 : 0;+ const crossDelta = Math.hypot(+ negative.translation[1] - positive.translation[1],+ negative.translation[cross]! - positive.translation[cross]!,+ );+ if (crossDelta <= SOCKET_ALIGNMENT_TOLERANCE_METERS) continue;+ findings.push(+ finding(context, {+ code: 'ENV_SOCKET_PAIR_MISALIGNED',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Opposing ${axis.toUpperCase()} tile sockets differ by ${crossDelta.toFixed(6)} m in their paired height/cross-axis frame.`,+ affected: { node: positive.node, attribute: positive.id },+ measurement: {+ name: 'socketCrossAxisDelta',+ actual: stable(crossDelta),+ expected: 0,+ threshold: SOCKET_ALIGNMENT_TOLERANCE_METERS,+ unit: 'm',+ },+ viewHints: ['top', 'generic.top.semantic-overlay'],+ repairText: `Align the ${axis}-negative/${axis}-positive socket frames in height and cross-axis offset.`,+ }),+ );+ }+ return findings;+}++function materialSignature(material: THREE.Material | THREE.Material[]): string {+ const values = Array.isArray(material) ? material : [material];+ return values+ .map((value) => {+ const standard = value as THREE.MeshStandardMaterial;+ const color = standard.color?.getHexString?.() ?? 'none';+ return `${value.type}:${value.name}:${color}`;+ })+ .sort()+ .join('|');+}++function boundarySamples(+ root: THREE.Object3D,+ axis: 'x' | 'z',+ side: 'negative' | 'positive',+ bins = 12,+): BoundarySample[] {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const bounds = new THREE.Box3().setFromObject(root);+ const localBounds = transformedBox(bounds, root.matrixWorld.clone().invert());+ const edge = side === 'negative' ? localBounds.min[axis] : localBounds.max[axis];+ const axisExtent = localBounds.max[axis] - localBounds.min[axis];+ const band = Math.max(0.002, axisExtent * 0.005);+ const crossAxis = axis === 'x' ? 'z' : 'x';+ const crossMin = localBounds.min[crossAxis];+ const crossExtent = Math.max(1e-9, localBounds.max[crossAxis] - crossMin);+ const byBin = new Map<number, BoundarySample>();++ root.traverse((node) => {+ if (!(node instanceof THREE.Mesh) || !(node.geometry instanceof THREE.BufferGeometry)) return;+ const positions = node.geometry.getAttribute('position');+ if (positions?.itemSize !== 3) return;+ const normals = node.geometry.getAttribute('normal');+ const transform = inverse.clone().multiply(node.matrixWorld);+ const normalMatrix = new THREE.Matrix3().getNormalMatrix(transform);+ const material = materialSignature(node.material);+ for (let index = 0; index < positions.count; index++) {+ const point = new THREE.Vector3(+ positions.getX(index),+ positions.getY(index),+ positions.getZ(index),+ ).applyMatrix4(transform);+ if (Math.abs(point[axis] - edge) > band) continue;+ const t = THREE.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);+ const bin = Math.min(bins - 1, Math.floor(t * bins));+ const normal = normals+ ? new THREE.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index))+ .applyMatrix3(normalMatrix)+ .normalize()+ : new THREE.Vector3(0, 1, 0);+ const current = byBin.get(bin);+ if (+ !current ||+ point.y > current.height ||+ (point.y === current.height && normal.y > current.normal.y)+ ) {+ byBin.set(bin, { bin, height: point.y, normal, material });+ }+ }+ });+ return Array.from(byBin.values()).sort((a, b) => a.bin - b.bin);+}++function edgePairMeasurements(+ root: THREE.Object3D,+ axis: 'x' | 'z',+ sockets: readonly ResolvedEnvironmentSocketV1[],+): EdgePairMeasurements {+ const negative = boundarySamples(root, axis, 'negative');+ const positive = boundarySamples(root, axis, 'positive');+ const negativeByBin = new Map(negative.map((sample) => [sample.bin, sample]));+ const pairs = positive.flatMap((sample) => {+ const other = negativeByBin.get(sample.bin);+ return other ? [[other, sample] as const] : [];+ });+ const unionBins = new Set([+ ...negative.map((sample) => sample.bin),+ ...positive.map((sample) => sample.bin),+ ]);+ const maximumHeightDelta = pairs.length+ ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height)))+ : Number.POSITIVE_INFINITY;+ const maximumNormalDeltaDegrees = pairs.length+ ? Math.max(+ ...pairs.map(([a, b]) =>+ THREE.MathUtils.radToDeg(Math.acos(THREE.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))),+ ),+ )+ : 180;+ const materialMismatch = pairs.some(([a, b]) => a.material !== b.material);+ const negativeSocket = socketByType(sockets, `environment.tile.${axis}-negative`);+ const positiveSocket = socketByType(sockets, `environment.tile.${axis}-positive`);+ const crossIndex = axis === 'x' ? 2 : 0;+ const socketCrossAxisDelta =+ negativeSocket && positiveSocket+ ? Math.hypot(+ negativeSocket.translation[1] - positiveSocket.translation[1],+ negativeSocket.translation[crossIndex]! - positiveSocket.translation[crossIndex]!,+ )+ : null;+ return {+ axis,+ source: negativeSocket && positiveSocket ? 'semantic' : 'fallback',+ sampleCoverage: unionBins.size === 0 ? 0 : pairs.length / unionBins.size,+ maximumHeightDelta: stable(maximumHeightDelta),+ maximumNormalDeltaDegrees: stable(maximumNormalDeltaDegrees),+ materialMismatch,+ socketCrossAxisDelta: socketCrossAxisDelta === null ? null : stable(socketCrossAxisDelta),+ };+}++/** Height/normal/material edge sampling; only fully tagged tiles can block. */+export function evaluateEnvironmentTileEdgeQa(context: QaContext): readonly QaFinding[] {+ if (+ context.intent.category !== 'environment' ||+ !context.intent.capabilities.includes('tileable') ||+ !(context.scene instanceof THREE.Object3D)+ ) {+ return [];+ }+ const root = context.scene;+ const sockets = resolveEnvironmentSockets(root);+ const findings: QaFinding[] = [];+ for (const axis of ['x', 'z'] as const) {+ const measured = edgePairMeasurements(root, axis, sockets);+ const disposition = measured.source === 'semantic' ? ('block' as const) : ('warn' as const);+ if (measured.sampleCoverage < 0.5) {+ findings.push(+ finding(context, {+ code: 'ENV_TILE_EDGE_EVIDENCE_SPARSE',+ disposition,+ dimension: 'categoryReadiness',+ message: `${axis.toUpperCase()} tile edges share only ${(measured.sampleCoverage * 100).toFixed(1)}% sampled boundary coverage.`,+ affected: { node: root.name || 'environment-root', attribute: `${axis}-edge` },+ measurement: {+ name: 'pairedBoundarySampleCoverage',+ actual: measured.sampleCoverage,+ expected: '>=0.5',+ threshold: 0.5,+ unit: 'ratio',+ },+ viewHints: ['top', 'right'],+ repairText: `Author matching ${axis}-negative/${axis}-positive boundary vertices and semantic tile sockets.`,+ }),+ );+ continue;+ }+ if (measured.maximumHeightDelta > EDGE_HEIGHT_TOLERANCE_METERS) {+ findings.push(+ finding(context, {+ code: 'ENV_TILE_EDGE_HEIGHT_SEAM',+ disposition,+ dimension: 'categoryReadiness',+ message: `${axis.toUpperCase()} tile boundaries differ by ${measured.maximumHeightDelta.toFixed(6)} m.`,+ affected: { node: root.name || 'environment-root', attribute: `${axis}-edge-height` },+ measurement: {+ name: 'maximumBoundaryHeightDelta',+ actual: measured.maximumHeightDelta,+ expected: 0,+ threshold: EDGE_HEIGHT_TOLERANCE_METERS,+ unit: 'm',+ },+ viewHints: ['top', 'right'],+ repairText: `Match the sampled ${axis}-negative/${axis}-positive boundary heights without flattening the tile interior.`,+ }),+ );+ }+ if (measured.maximumNormalDeltaDegrees > EDGE_NORMAL_TOLERANCE_DEGREES) {+ findings.push(+ finding(context, {+ code: 'ENV_TILE_EDGE_NORMAL_SEAM',+ disposition,+ dimension: 'categoryReadiness',+ message: `${axis.toUpperCase()} tile boundary normals differ by ${measured.maximumNormalDeltaDegrees.toFixed(3)} degrees.`,+ affected: { node: root.name || 'environment-root', attribute: `${axis}-edge-normal` },+ measurement: {+ name: 'maximumBoundaryNormalDelta',+ actual: measured.maximumNormalDeltaDegrees,+ expected: 0,+ threshold: EDGE_NORMAL_TOLERANCE_DEGREES,+ unit: 'deg',+ },+ viewHints: ['top', 'three-quarter'],+ repairText: `Align the ${axis}-edge vertex normals while preserving intentional interior shading.`,+ }),+ );+ }+ if (measured.materialMismatch) {+ findings.push(+ finding(context, {+ code: 'ENV_TILE_EDGE_MATERIAL_SEAM',+ disposition,+ dimension: 'visualQuality',+ message: `${axis.toUpperCase()} tile boundaries use different material signatures.`,+ affected: { node: root.name || 'environment-root', attribute: `${axis}-edge-material` },+ measurement: { name: 'boundaryMaterialMismatch', actual: true, expected: false },+ viewHints: ['top', 'three-quarter'],+ repairText: `Use the same portable PBR material role on both ${axis} boundary samples.`,+ }),+ );+ }+ }+ return findings;+}++function isCorridor(part: LocalPart): boolean {+ return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));+}++/** Exact blocker checks plus advisory default dimensions for authored corridor prisms. */+export function evaluateEnvironmentNavigabilityQa(context: QaContext): readonly QaFinding[] {+ if (+ context.intent.category !== 'environment' ||+ !context.intent.capabilities.includes('navigable') ||+ !(context.scene instanceof THREE.Object3D)+ ) {+ return [];+ }+ const root = context.scene;+ const parts = collectParts(root);+ const corridors = parts.filter((part) => isCorridor(part));+ if (corridors.length === 0) {+ return [+ finding(context, {+ code: 'ENV_NAV_CLEARANCE_UNASSESSED',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message:+ 'navigable=true has no measurable semantic corridor prism; geometry inference cannot hard-gate traversal.',+ affected: { node: root.name || 'environment-root' },+ measurement: { name: 'semanticCorridorCount', actual: 0, expected: '>=1', threshold: 1 },+ viewHints: ['top', 'right'],+ repairText:+ 'Add a scaled non-rendered environment.navigation.corridor.<id> marker through the intended route.',+ }),+ ];+ }+ const findings: QaFinding[] = [];+ for (const corridor of corridors) {+ if (!corridor.orientedBox) {+ findings.push(+ finding(context, {+ code: 'ENV_NAV_CLEARANCE_UNASSESSED',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `Traversal corridor ${corridor.node.name || '(unnamed)'} has a sheared or degenerate transform that cannot be measured safely.`,+ affected: {+ node: corridor.node.name || 'navigation-corridor',+ nodePath: nodePath(root, corridor.node),+ },+ measurement: { name: 'orientedCorridorEvidence', actual: false, expected: true },+ viewHints: ['top', 'right'],+ repairText: 'Author the corridor marker with a finite non-sheared local transform.',+ }),+ );+ continue;+ }+ const width = Math.min(+ corridor.orientedBox.halfExtents[0] * 2,+ corridor.orientedBox.halfExtents[2] * 2,+ );+ const height = corridor.orientedBox.halfExtents[1] * 2;+ if (width + 1e-6 < 0.8) {+ findings.push(+ finding(context, {+ code: 'ENV_NAV_CORRIDOR_TOO_NARROW',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `Traversal corridor ${corridor.node.name || '(unnamed)'} is only ${width.toFixed(4)} m wide.`,+ affected: {+ node: corridor.node.name || 'navigation-corridor',+ nodePath: nodePath(root, corridor.node),+ },+ measurement: {+ name: 'minimumCorridorWidth',+ actual: stable(width),+ expected: '>=0.8',+ threshold: 0.8,+ unit: 'm',+ },+ viewHints: ['top', 'right'],+ repairText:+ 'Widen only the declared corridor to at least 0.8 m while preserving surrounding structure.',+ }),+ );+ }+ if (height + 1e-6 < 1.8) {+ findings.push(+ finding(context, {+ code: 'ENV_NAV_HEADROOM_TOO_LOW',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `Traversal corridor ${corridor.node.name || '(unnamed)'} has only ${height.toFixed(4)} m headroom.`,+ affected: {+ node: corridor.node.name || 'navigation-corridor',+ nodePath: nodePath(root, corridor.node),+ },+ measurement: {+ name: 'minimumCorridorHeadroom',+ actual: stable(height),+ expected: '>=1.8',+ threshold: 1.8,+ unit: 'm',+ },+ viewHints: ['right', 'three-quarter'],+ repairText:+ 'Raise or clear only the corridor ceiling to provide at least 1.8 m headroom.',+ }),+ );+ }+ const blocker = parts.find(+ (part) =>+ part.renderable &&+ part.orientedBox &&+ part.node !== corridor.node &&+ !part.roles.some(+ (role) =>+ role.startsWith('environment.ground') ||+ role.startsWith('environment.surface') ||+ role.startsWith('environment.path.surface') ||+ role.startsWith('environment.bridge.deck'),+ ) &&+ !probeOrientedPenetration(part.orientedBox, corridor.orientedBox!, {+ maxDepth: 0,+ tolerance: 0.004,+ }).pass,+ );+ if (blocker) {+ findings.push(+ finding(context, {+ code: 'ENV_NAV_CORRIDOR_BLOCKED',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Traversal corridor ${corridor.node.name || '(unnamed)'} is blocked by ${blocker.node.name || 'an unnamed mesh'}.`,+ affected: {+ node: blocker.node.name || 'navigation-blocker',+ nodePath: nodePath(root, blocker.node),+ },+ measurement: { name: 'corridorBlockerCount', actual: 1, expected: 0, threshold: 0 },+ viewHints: ['top', 'right'],+ repairText:+ 'Remove or split only the reported blocker from the declared navigation corridor.',+ }),+ );+ }+ }+ return findings;+}++function horizontalOverlap(a: THREE.Box3, b: THREE.Box3): boolean {+ return a.min.x < b.max.x && a.max.x > b.min.x && a.min.z < b.max.z && a.max.z > b.min.z;+}++function intentionalGround(part: LocalPart): boolean {+ return part.roles.some(+ (role) =>+ role.startsWith('environment.ground') ||+ role.startsWith('environment.terrain.volume') ||+ role.startsWith('environment.cliff.volume'),+ );+}++function functionalLayer(part: LocalPart): boolean {+ return part.roles.some(+ (role) =>+ role.startsWith('environment.functional') ||+ role.startsWith('environment.layer') ||+ role.startsWith('environment.path') ||+ role.startsWith('environment.road') ||+ role.startsWith('environment.bridge') ||+ role.startsWith('environment.gate'),+ );+}++/** Ground-policy signals are intentionally advisory and separate terrain volume from accidents. */+export function evaluateEnvironmentGroundQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'environment' || !(context.scene instanceof THREE.Object3D)) {+ return [];+ }+ const root = context.scene;+ const parts = collectParts(root).filter((part) => part.renderable && part.box);+ const findings: QaFinding[] = [];+ for (const part of parts) {+ const box = part.box!;+ if (intentionalGround(part)) continue;+ if (functionalLayer(part) && box.min.y < -GROUND_TOLERANCE_METERS) {+ findings.push(+ finding(context, {+ code: 'ENV_FUNCTIONAL_PART_BURIED',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `${part.node.name || 'Functional environment part'} is buried ${Math.abs(box.min.y).toFixed(6)} m below asset-local ground.`,+ affected: {+ node: part.node.name || 'environment-part',+ nodePath: nodePath(root, part.node),+ },+ measurement: {+ name: 'minimumY',+ actual: stable(box.min.y),+ expected: '>=-0.02',+ threshold: GROUND_TOLERANCE_METERS,+ unit: 'm',+ },+ viewHints: ['right', 'three-quarter'],+ }),+ );+ }+ if (functionalLayer(part) && box.min.y > GROUND_TOLERANCE_METERS) {+ const supported = parts.some(+ (support) =>+ support !== part &&+ support.box &&+ horizontalOverlap(box, support.box) &&+ Math.abs(support.box.max.y - box.min.y) <= 0.04,+ );+ if (!supported) {+ findings.push(+ finding(context, {+ code: 'ENV_LAYER_UNSUPPORTED',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `${part.node.name || 'Environment layer'} floats without a contacting support.`,+ affected: {+ node: part.node.name || 'environment-layer',+ nodePath: nodePath(root, part.node),+ },+ measurement: { name: 'supportContactCount', actual: 0, expected: '>=1', threshold: 1 },+ viewHints: ['right', 'three-quarter'],+ }),+ );+ }+ }+ const size = box.getSize(new THREE.Vector3());+ if (+ box.min.y < -0.05 &&+ size.y <= Math.max(0.05, Math.min(size.x, size.z) * 0.03) &&+ Math.max(size.x, size.z) >= 1+ ) {+ findings.push(+ finding(context, {+ code: 'ENV_GROUND_UNDECLARED_SKIRT',+ disposition: 'warn',+ dimension: 'promptAlignment',+ message: `${part.node.name || 'Environment layer'} resembles an undeclared below-ground skirt rather than intentional terrain volume.`,+ affected: {+ node: part.node.name || 'environment-skirt',+ nodePath: nodePath(root, part.node),+ },+ measurement: {+ name: 'skirtThickness',+ actual: stable(size.y),+ expected: 'declared terrain volume or supported layer',+ unit: 'm',+ },+ viewHints: ['right', 'three-quarter'],+ }),+ );+ }+ }+ return findings;+}++export const ENVIRONMENT_EXACT_QA_RULE: QaRule = Object.freeze({+ id: 'ENVIRONMENT_EXACT_PROFILE',+ profile: PROFILE,+ scope: { kind: 'category' as const, category: 'environment' as const },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'environment-semantic-v1',+ 'src/qa/environment.test.ts',+ '13b0c50894074bf93a5dd9eb1c93e519b030312e030e5123493a4833a1438b28',+ ),+ defaultMode: 'enforce',+ evaluate: (context: QaContext) => [+ ...evaluateEnvironmentSocketQa(context),+ ...evaluateEnvironmentTileEdgeQa(context).filter((value) => value.disposition === 'block'),+ ...evaluateEnvironmentNavigabilityQa(context).filter((value) => value.disposition === 'block'),+ ],+});++export const ENVIRONMENT_ADVISORY_QA_RULE: QaRule = Object.freeze({+ id: 'ENVIRONMENT_ADVISORY_PROFILE',+ profile: 'environment.advisory',+ scope: { kind: 'category' as const, category: 'environment' as const },+ ruleClass: 'heuristic',+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: 'observe',+ evaluate: (context: QaContext) => [+ ...evaluateEnvironmentTileEdgeQa(context).filter((value) => value.disposition !== 'block'),+ ...evaluateEnvironmentNavigabilityQa(context).filter((value) => value.disposition !== 'block'),+ ...evaluateEnvironmentGroundQa(context),+ ],+});++export const ENVIRONMENT_QA_RULES: readonly QaRule[] = [+ ENVIRONMENT_EXACT_QA_RULE,+ ENVIRONMENT_ADVISORY_QA_RULE,+] as const;diff --git a/src/qa/geometry-relations.test.ts b/src/qa/geometry-relations.test.tsnew file mode 100644index 00000000..3440f726--- /dev/null+++ b/src/qa/geometry-relations.test.ts@@ -0,0 +1,246 @@+import { describe, expect, test } from 'bun:test';++import {+ createOrientedProbeBox3,+ probeLocalFrameFromQuaternion,+ probeOrientedAlignment,+ probeOrientedClearance,+ probeOrientedConcentricity,+ probeOrientedContact,+ probeOrientedContainment,+ probeOrientedCoverage,+ probeOrientedPenetration,+ type OrientedProbeBox3,+ type ProbeVector3,+} from './geometry-relations';++const yawQuaternion = (degrees: number): [number, number, number, number] => {+ const radians = (degrees * Math.PI) / 180;+ return [0, Math.sin(radians / 2), 0, Math.cos(radians / 2)];+};++const box = (+ id: string,+ origin: ProbeVector3,+ halfExtents: ProbeVector3,+ yawDegrees = 0,+): OrientedProbeBox3 =>+ createOrientedProbeBox3({+ id,+ frame: probeLocalFrameFromQuaternion(`${id}.frame`, origin, yawQuaternion(yawDegrees)),+ halfExtents,+ });++const rotateY = (point: ProbeVector3, degrees: number, translation: ProbeVector3): ProbeVector3 => {+ const radians = (degrees * Math.PI) / 180;+ const cosine = Math.cos(radians);+ const sine = Math.sin(radians);+ return [+ cosine * point[0] + sine * point[2] + translation[0],+ point[1] + translation[1],+ -sine * point[0] + cosine * point[2] + translation[2],+ ];+};++describe('oriented local-space relation probes', () => {+ test('contact, clearance, and penetration are reciprocal with localized evidence', () => {+ const reference = box('chassis', [0, 0, 0], [1, 1, 1], 23);+ const touching = box(+ 'wheel',+ [2 * Math.cos((23 * Math.PI) / 180), 0, -2 * Math.sin((23 * Math.PI) / 180)],+ [1, 0.5, 0.5],+ 23,+ );++ const forward = probeOrientedContact(touching, reference);+ const reciprocal = probeOrientedContact(reference, touching);+ expect(forward.pass).toBe(true);+ expect(reciprocal.pass).toBe(true);+ expect(forward.measurements.separation).toBe(reciprocal.measurements.separation);+ expect(forward.measurements.penetration).toBe(reciprocal.measurements.penetration);+ expect(forward.evidence.coordinateSpace).toBe('reference-local');+ expect(forward.evidence.referenceFrameId).toBe('chassis.frame');+ expect(forward.evidence.points).toHaveLength(2);++ const separated = box(+ 'separatedWheel',+ [2.25 * Math.cos((23 * Math.PI) / 180), 0, -2.25 * Math.sin((23 * Math.PI) / 180)],+ [1, 0.5, 0.5],+ 23,+ );+ const clearance = probeOrientedClearance(separated, reference, { minimumClearance: 0.2 });+ const clearanceReciprocal = probeOrientedClearance(reference, separated, {+ minimumClearance: 0.2,+ });+ expect(clearance.pass).toBe(true);+ expect(clearance.measurements.clearance).toBeCloseTo(0.25, 7);+ expect(clearanceReciprocal.measurements.clearance).toBe(clearance.measurements.clearance);++ const embedded = box(+ 'embeddedWheel',+ [1.6 * Math.cos((23 * Math.PI) / 180), 0, -1.6 * Math.sin((23 * Math.PI) / 180)],+ [1, 0.5, 0.5],+ 23,+ );+ const penetration = probeOrientedPenetration(embedded, reference, { maxDepth: 0.1 });+ const penetrationReciprocal = probeOrientedPenetration(reference, embedded, {+ maxDepth: 0.1,+ });+ expect(penetration.pass).toBe(false);+ expect(penetration.measurements.penetrationDepth).toBeCloseTo(0.4, 7);+ expect(penetrationReciprocal.measurements.penetrationDepth).toBe(+ penetration.measurements.penetrationDepth,+ );+ });++ test('distinguishes rotated OBB separation where global AABBs overlap', () => {+ const yaw = 45;+ const radians = (yaw * Math.PI) / 180;+ const perpendicular: ProbeVector3 = [Math.sin(radians), 0, Math.cos(radians)];+ const reference = box('beamA', [0, 0, 0], [2, 0.2, 0.1], yaw);+ const subject = box(+ 'beamB',+ [perpendicular[0] * 0.5, 0, perpendicular[2] * 0.5],+ [2, 0.2, 0.1],+ yaw,+ );++ // Each world AABB spans ~2.97m on X and Z, so those AABBs overlap. The+ // local-space slabs are actually 0.3m apart along their narrow Z axes.+ const relation = probeOrientedClearance(subject, reference, { minimumClearance: 0.25 });+ expect(relation.pass).toBe(true);+ expect(relation.measurements.clearance).toBeCloseTo(0.3, 7);+ expect(probeOrientedContact(subject, reference).pass).toBe(false);+ expect(relation.evidence.axis).toEqual([0, 0, 1]);+ });++ test('containment is directional and reports the exact escaped corners', () => {+ const container = box('cargoBay', [3, 2, -4], [2, 1.5, 1.25], 37);+ const contained = box('crate', [3, 2, -4], [0.5, 0.5, 0.5], 52);+ const inside = probeOrientedContainment(contained, container);+ const reciprocal = probeOrientedContainment(container, contained);+ expect(inside.pass).toBe(true);+ expect(inside.measurements.outsideCornerCount).toBe(0);+ expect(inside.measurements.minimumInteriorMargin).toBeGreaterThan(0);+ expect(reciprocal.pass).toBe(false);+ expect(reciprocal.measurements.outsideCornerCount).toBeGreaterThan(0);+ expect(+ reciprocal.evidence.points.every((point) => point.label.startsWith('cargoBay.corner.')),+ ).toBe(true);+ });++ test('alignment and concentricity separate angular, lateral, and axial measurements', () => {+ const axle = box('axle', [5, 1, 2], [1.5, 0.1, 0.1], 31);+ const centeredHub = box('hub', rotateY([0.35, 0, 0], 31, [5, 1, 2]), [0.2, 0.5, 0.5], 31);+ const aligned = probeOrientedAlignment(centeredHub, axle, {+ maxAngleDegrees: 0.01,+ maxLateralOffset: 0.001,+ });+ const concentric = probeOrientedConcentricity(centeredHub, axle, {+ maxRadialOffset: 0.001,+ maxAngleDegrees: 0.01,+ });+ expect(aligned.pass).toBe(true);+ expect(concentric.pass).toBe(true);+ expect(concentric.measurements.radialOffset).toBe(0);+ expect(concentric.measurements.axialOffset).toBeCloseTo(0.35, 10);++ const offsetHub = box(+ 'offsetHub',+ rotateY([0.35, 0, 0.08], 31, [5, 1, 2]),+ [0.2, 0.5, 0.5],+ 43,+ );+ const failed = probeOrientedConcentricity(offsetHub, axle, {+ maxRadialOffset: 0.02,+ maxAngleDegrees: 2,+ });+ expect(failed.pass).toBe(false);+ expect(failed.measurements.radialOffset).toBeCloseTo(0.08, 10);+ expect(failed.measurements.angleDegrees).toBeCloseTo(12, 6);+ });++ test('coverage clips a rotated projected polygon and remains intentionally directional', () => {+ const target = box('roofFootprint', [0, 0, 0], [1, 0.1, 1], 18);+ const cover = box('roofPanel', [0, 0.15, 0], [1.35, 0.05, 1.35], 33);+ const covered = probeOrientedCoverage(cover, target, {+ normalAxis: 'y',+ minimumRatio: 0.999,+ });+ const reciprocal = probeOrientedCoverage(target, cover, {+ normalAxis: 'y',+ minimumRatio: 0.9,+ });+ expect(covered.pass).toBe(true);+ expect(covered.measurements.coverageRatio).toBe(1);+ expect(covered.measurements.coveredArea).toBeCloseTo(4, 10);+ expect(covered.measurements.normalOffset).toBeCloseTo(0.15, 10);+ expect(reciprocal.pass).toBe(false);+ expect(reciprocal.measurements.coverageRatio).toBeLessThan(0.9);+ expect(covered.evidence.points.length).toBeGreaterThanOrEqual(4);+ });++ test('all seven probes are invariant under a shared rigid transform and deterministic on rerun', () => {+ const sharedYaw = 57;+ const translation: ProbeVector3 = [8, -3, 11];+ const baseReference = box('reference', [0, 0, 0], [1, 1, 1], 10);+ const baseSubject = box('subject', [1.75, 0, 0], [0.75, 0.5, 0.5], 10);+ const movedReference = box(+ 'reference',+ rotateY(baseReference.frame.origin, sharedYaw, translation),+ [1, 1, 1],+ 10 + sharedYaw,+ );+ const movedSubject = box(+ 'subject',+ rotateY(baseSubject.frame.origin, sharedYaw, translation),+ [0.75, 0.5, 0.5],+ 10 + sharedYaw,+ );++ const evaluate = (subject: OrientedProbeBox3, reference: OrientedProbeBox3) => [+ probeOrientedContact(subject, reference, { maxPenetration: 0.01 }),+ probeOrientedContainment(subject, reference),+ probeOrientedClearance(subject, reference, { minimumClearance: 0.1 }),+ probeOrientedConcentricity(subject, reference, { maxRadialOffset: 0.01 }),+ probeOrientedAlignment(subject, reference, { maxLateralOffset: 0.01 }),+ probeOrientedCoverage(subject, reference),+ probeOrientedPenetration(subject, reference, { maxDepth: 0.1 }),+ ];+ const base = evaluate(baseSubject, baseReference);+ const moved = evaluate(movedSubject, movedReference);+ expect(moved.map((result) => result.pass)).toEqual(base.map((result) => result.pass));+ moved.forEach((result, resultIndex) => {+ const baseMeasurements = base[resultIndex]!.measurements;+ expect(Object.keys(result.measurements)).toEqual(Object.keys(baseMeasurements));+ for (const [name, value] of Object.entries(result.measurements)) {+ expect(Math.abs(value - baseMeasurements[name]!)).toBeLessThan(2e-6);+ }+ });+ expect(evaluate(movedSubject, movedReference)).toEqual(moved);+ expect(new Set(moved.map((result) => result.relation))).toEqual(+ new Set([+ 'contact',+ 'containment',+ 'clearance',+ 'concentricity',+ 'alignment',+ 'coverage',+ 'penetration',+ ]),+ );+ });++ test('directed local-axis clearance measures headroom rather than nearest global separation', () => {+ const ceiling = box('ceiling', [2, 3, -1], [2, 0.1, 2], 28);+ const actor = box('actor', rotateY([0, -1.1, 0], 28, [2, 3, -1]), [0.4, 0.9, 0.4], 28);+ const headroom = probeOrientedClearance(ceiling, actor, {+ minimumClearance: 0.09,+ axis: 'y',+ direction: 1,+ });+ expect(headroom.pass).toBe(true);+ expect(headroom.measurements.clearance).toBeCloseTo(0.1, 10);+ expect(headroom.evidence.axis).toEqual([0, 1, 0]);+ });+});diff --git a/src/qa/geometry-relations.ts b/src/qa/geometry-relations.tsnew file mode 100644index 00000000..187e9b84--- /dev/null+++ b/src/qa/geometry-relations.ts@@ -0,0 +1,843 @@+/**+ * Deterministic local-space geometry relation probes.+ *+ * These probes deliberately operate on oriented boxes and explicit rigid+ * frames. They do not collapse assets into global AABBs, so a shared parent+ * transform, a rotated assembly, or a narrow diagonal part retains its true+ * relationship. Evidence is always localized in the reference box's frame.+ */++export type ProbeVector3 = [number, number, number];+export type ProbeQuaternion = [number, number, number, number];+export type ProbeLocalAxis = 'x' | 'y' | 'z';++export interface ProbeLocalFrame3 {+ id: string;+ origin: ProbeVector3;+ xAxis: ProbeVector3;+ yAxis: ProbeVector3;+ zAxis: ProbeVector3;+}++export interface OrientedProbeBox3 {+ id: string;+ frame: ProbeLocalFrame3;+ halfExtents: ProbeVector3;+}++export type GeometryRelation =+ | 'contact'+ | 'containment'+ | 'clearance'+ | 'concentricity'+ | 'alignment'+ | 'coverage'+ | 'penetration';++export interface LocalizedProbePoint {+ label: string;+ position: ProbeVector3;+}++export interface GeometryProbeEvidence {+ subjectId: string;+ referenceId: string;+ coordinateSpace: 'reference-local';+ referenceFrameId: string;+ /** Direction expressed in the reference frame. */+ axis?: ProbeVector3;+ axisLabel?: string;+ points: LocalizedProbePoint[];+}++export interface GeometryProbeResult {+ relation: GeometryRelation;+ pass: boolean;+ /** Stable scalar output. All distances are meters and angles are degrees. */+ measurements: Record<string, number>;+ evidence: GeometryProbeEvidence;+}++export interface ContactProbeOptions {+ maxSeparation?: number;+ maxPenetration?: number;+}++export interface ContainmentProbeOptions {+ tolerance?: number;+}++export interface ClearanceProbeOptions {+ minimumClearance: number;+ /** Optional directed reference-local clearance, useful for headroom or a wheel well. */+ axis?: ProbeLocalAxis;+ direction?: 1 | -1;+ tolerance?: number;+}++export interface AlignmentProbeOptions {+ subjectAxis?: ProbeLocalAxis;+ referenceAxis?: ProbeLocalAxis;+ allowOpposite?: boolean;+ maxAngleDegrees?: number;+ maxLateralOffset?: number;+}++export interface ConcentricityProbeOptions extends AlignmentProbeOptions {+ maxRadialOffset?: number;+}++export interface CoverageProbeOptions {+ /** Face normal in the reference box's local frame. */+ normalAxis?: ProbeLocalAxis;+ minimumRatio?: number;+ tolerance?: number;+}++export interface PenetrationProbeOptions {+ maxDepth?: number;+ tolerance?: number;+}++interface ProjectionInterval {+ min: number;+ max: number;+}++interface SatResult {+ separation: number;+ penetration: number;+ axisWorld: ProbeVector3;+ axisLabel: string;+}++type Point2 = [number, number];++const EPSILON = 1e-10;+const DEFAULT_TOLERANCE = 1e-6;++const finiteVector = (value: readonly number[]): boolean =>+ value.length === 3 && value.every((component) => Number.isFinite(component));++const add = (a: readonly number[], b: readonly number[]): ProbeVector3 => [+ a[0]! + b[0]!,+ a[1]! + b[1]!,+ a[2]! + b[2]!,+];++const subtract = (a: readonly number[], b: readonly number[]): ProbeVector3 => [+ a[0]! - b[0]!,+ a[1]! - b[1]!,+ a[2]! - b[2]!,+];++const scale = (value: readonly number[], amount: number): ProbeVector3 => [+ value[0]! * amount,+ value[1]! * amount,+ value[2]! * amount,+];++const dot = (a: readonly number[], b: readonly number[]): number =>+ a[0]! * b[0]! + a[1]! * b[1]! + a[2]! * b[2]!;++const cross = (a: readonly number[], b: readonly number[]): ProbeVector3 => [+ a[1]! * b[2]! - a[2]! * b[1]!,+ a[2]! * b[0]! - a[0]! * b[2]!,+ a[0]! * b[1]! - a[1]! * b[0]!,+];++const length = (value: readonly number[]): number => Math.hypot(value[0]!, value[1]!, value[2]!);++const normalize = (value: readonly number[]): ProbeVector3 => {+ const magnitude = length(value);+ if (magnitude <= EPSILON) throw new TypeError('Cannot normalize a zero-length probe axis.');+ return scale(value, 1 / magnitude);+};++const stable = (value: number): number => {+ if (Math.abs(value) < 1e-10) return 0;+ return Number(value.toFixed(9));+};++const stableVector = (value: readonly number[]): ProbeVector3 => [+ stable(value[0]!),+ stable(value[1]!),+ stable(value[2]!),+];++const assertNonNegative = (value: number, name: string): void => {+ if (!Number.isFinite(value) || value < 0) {+ throw new TypeError(`${name} must be a finite non-negative number.`);+ }+};++const axes = (frame: ProbeLocalFrame3): [ProbeVector3, ProbeVector3, ProbeVector3] => [+ frame.xAxis,+ frame.yAxis,+ frame.zAxis,+];++const axisIndex = (axis: ProbeLocalAxis): 0 | 1 | 2 => (axis === 'x' ? 0 : axis === 'y' ? 1 : 2);++const axisVector = (frame: ProbeLocalFrame3, axis: ProbeLocalAxis): ProbeVector3 =>+ axes(frame)[axisIndex(axis)];++/** Build a checked right-handed orthonormal frame. */+export function createProbeLocalFrame3(input: ProbeLocalFrame3): ProbeLocalFrame3 {+ if (!input.id.trim()) throw new TypeError('Probe frame ID must be non-empty.');+ if (!finiteVector(input.origin)) throw new TypeError('Probe frame origin must be finite.');+ const basis = [input.xAxis, input.yAxis, input.zAxis] as const;+ for (const [index, value] of basis.entries()) {+ if (!finiteVector(value) || Math.abs(length(value) - 1) > 1e-6) {+ throw new TypeError(`Probe frame axis ${index} must be finite and normalized within 1e-6.`);+ }+ }+ if (+ Math.abs(dot(input.xAxis, input.yAxis)) > 1e-6 ||+ Math.abs(dot(input.xAxis, input.zAxis)) > 1e-6 ||+ Math.abs(dot(input.yAxis, input.zAxis)) > 1e-6 ||+ dot(cross(input.xAxis, input.yAxis), input.zAxis) < 1 - 1e-6+ ) {+ throw new TypeError('Probe frame axes must be orthonormal and right-handed.');+ }+ return {+ id: input.id,+ origin: stableVector(input.origin),+ xAxis: stableVector(input.xAxis),+ yAxis: stableVector(input.yAxis),+ zAxis: stableVector(input.zAxis),+ };+}++/** Convenience constructor for a rigid frame from a unit quaternion. */+export function probeLocalFrameFromQuaternion(+ id: string,+ origin: ProbeVector3,+ quaternion: ProbeQuaternion,+): ProbeLocalFrame3 {+ if (!quaternion.every((component) => Number.isFinite(component))) {+ throw new TypeError('Probe frame quaternion must be finite.');+ }+ const quaternionLength = Math.hypot(...quaternion);+ if (Math.abs(quaternionLength - 1) > 1e-6) {+ throw new TypeError('Probe frame quaternion must be normalized within 1e-6.');+ }+ const [x, y, z, w] = quaternion;+ const xx = x * x;+ const yy = y * y;+ const zz = z * z;+ const xy = x * y;+ const xz = x * z;+ const yz = y * z;+ const wx = w * x;+ const wy = w * y;+ const wz = w * z;+ return createProbeLocalFrame3({+ id,+ origin,+ xAxis: [1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy)],+ yAxis: [2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx)],+ zAxis: [2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy)],+ });+}++export function createOrientedProbeBox3(input: OrientedProbeBox3): OrientedProbeBox3 {+ if (!input.id.trim()) throw new TypeError('Oriented probe box ID must be non-empty.');+ if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent) => extent <= 0)) {+ throw new TypeError('Oriented probe box half-extents must be finite and greater than zero.');+ }+ return {+ id: input.id,+ frame: createProbeLocalFrame3(input.frame),+ halfExtents: stableVector(input.halfExtents),+ };+}++export function worldPointToProbeLocal(+ frame: ProbeLocalFrame3,+ worldPoint: ProbeVector3,+): ProbeVector3 {+ const offset = subtract(worldPoint, frame.origin);+ return stableVector([+ dot(offset, frame.xAxis),+ dot(offset, frame.yAxis),+ dot(offset, frame.zAxis),+ ]);+}++export function probeLocalPointToWorld(+ frame: ProbeLocalFrame3,+ localPoint: ProbeVector3,+): ProbeVector3 {+ return stableVector(+ add(+ frame.origin,+ add(+ scale(frame.xAxis, localPoint[0]),+ add(scale(frame.yAxis, localPoint[1]), scale(frame.zAxis, localPoint[2])),+ ),+ ),+ );+}++function worldVectorToProbeLocal(frame: ProbeLocalFrame3, worldVector: ProbeVector3): ProbeVector3 {+ return stableVector([+ dot(worldVector, frame.xAxis),+ dot(worldVector, frame.yAxis),+ dot(worldVector, frame.zAxis),+ ]);+}++function corners(box: OrientedProbeBox3): ProbeVector3[] {+ const boxAxes = axes(box.frame);+ const result: ProbeVector3[] = [];+ for (let bits = 0; bits < 8; bits++) {+ let point: ProbeVector3 = [...box.frame.origin];+ for (let dimension = 0; dimension < 3; dimension++) {+ const sign = bits & (1 << dimension) ? 1 : -1;+ point = add(point, scale(boxAxes[dimension]!, sign * box.halfExtents[dimension]!));+ }+ result.push(stableVector(point));+ }+ return result;+}++function projection(box: OrientedProbeBox3, axisWorld: ProbeVector3): ProjectionInterval {+ const center = dot(box.frame.origin, axisWorld);+ const radius = axes(box.frame).reduce(+ (total, boxAxis, index) => total + Math.abs(dot(boxAxis, axisWorld)) * box.halfExtents[index]!,+ 0,+ );+ return { min: center - radius, max: center + radius };+}++function orientFromReferenceToSubject(+ axisWorld: ProbeVector3,+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+): ProbeVector3 {+ return dot(subtract(subject.frame.origin, reference.frame.origin), axisWorld) < 0+ ? scale(axisWorld, -1)+ : axisWorld;+}++function candidateSatAxes(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+): Array<{ axis: ProbeVector3; label: string }> {+ const subjectAxes = axes(subject.frame);+ const referenceAxes = axes(reference.frame);+ const candidates: Array<{ axis: ProbeVector3; label: string }> = [];+ const pushUnique = (rawAxis: ProbeVector3, label: string): void => {+ if (length(rawAxis) <= EPSILON) return;+ const axis = normalize(rawAxis);+ if (candidates.some((candidate) => Math.abs(dot(candidate.axis, axis)) > 1 - 1e-9)) return;+ candidates.push({ axis, label });+ };+ for (let index = 0; index < 3; index++) {+ pushUnique(referenceAxes[index]!, `reference.${(['x', 'y', 'z'] as const)[index]}`);+ }+ for (let index = 0; index < 3; index++) {+ pushUnique(subjectAxes[index]!, `subject.${(['x', 'y', 'z'] as const)[index]}`);+ }+ for (let subjectIndex = 0; subjectIndex < 3; subjectIndex++) {+ for (let referenceIndex = 0; referenceIndex < 3; referenceIndex++) {+ pushUnique(+ cross(subjectAxes[subjectIndex]!, referenceAxes[referenceIndex]!),+ `cross.subject.${(['x', 'y', 'z'] as const)[subjectIndex]}.reference.${+ (['x', 'y', 'z'] as const)[referenceIndex]+ }`,+ );+ }+ }+ return candidates;+}++function sat(subject: OrientedProbeBox3, reference: OrientedProbeBox3): SatResult {+ let maximumSeparation = -Infinity;+ let separatingAxis: ProbeVector3 = reference.frame.xAxis;+ let separatingLabel = 'reference.x';+ let minimumOverlap = Infinity;+ let overlapAxis: ProbeVector3 = reference.frame.xAxis;+ let overlapLabel = 'reference.x';++ for (const candidate of candidateSatAxes(subject, reference)) {+ const subjectProjection = projection(subject, candidate.axis);+ const referenceProjection = projection(reference, candidate.axis);+ const gap = Math.max(+ subjectProjection.min - referenceProjection.max,+ referenceProjection.min - subjectProjection.max,+ );+ if (gap > maximumSeparation) {+ maximumSeparation = gap;+ separatingAxis = candidate.axis;+ separatingLabel = candidate.label;+ }+ const overlap =+ Math.min(subjectProjection.max, referenceProjection.max) -+ Math.max(subjectProjection.min, referenceProjection.min);+ if (overlap < minimumOverlap) {+ minimumOverlap = overlap;+ overlapAxis = candidate.axis;+ overlapLabel = candidate.label;+ }+ }++ if (maximumSeparation > 0) {+ return {+ separation: stable(maximumSeparation),+ penetration: 0,+ axisWorld: orientFromReferenceToSubject(separatingAxis, subject, reference),+ axisLabel: separatingLabel,+ };+ }+ return {+ separation: 0,+ penetration: stable(Math.max(0, minimumOverlap)),+ axisWorld: orientFromReferenceToSubject(overlapAxis, subject, reference),+ axisLabel: overlapLabel,+ };+}++function supportPoint(box: OrientedProbeBox3, direction: ProbeVector3): ProbeVector3 {+ let point: ProbeVector3 = [...box.frame.origin];+ axes(box.frame).forEach((boxAxis, index) => {+ const projectionValue = dot(boxAxis, direction);+ if (Math.abs(projectionValue) <= EPSILON) return;+ point = add(point, scale(boxAxis, Math.sign(projectionValue) * box.halfExtents[index]!));+ });+ return stableVector(point);+}++function evidence(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+ points: LocalizedProbePoint[],+ axisWorld?: ProbeVector3,+ axisLabel?: string,+): GeometryProbeEvidence {+ return {+ subjectId: subject.id,+ referenceId: reference.id,+ coordinateSpace: 'reference-local',+ referenceFrameId: reference.frame.id,+ ...(axisWorld ? { axis: worldVectorToProbeLocal(reference.frame, axisWorld) } : {}),+ ...(axisLabel ? { axisLabel } : {}),+ points,+ };+}++function satEvidencePoints(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+ axisWorld: ProbeVector3,+): LocalizedProbePoint[] {+ return [+ {+ label: `${reference.id}.support`,+ position: worldPointToProbeLocal(reference.frame, supportPoint(reference, axisWorld)),+ },+ {+ label: `${subject.id}.support`,+ position: worldPointToProbeLocal(+ reference.frame,+ supportPoint(subject, scale(axisWorld, -1)),+ ),+ },+ ];+}++/** Contact passes only near the surface: both a visible gap and deep overlap fail. */+export function probeOrientedContact(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+ options: ContactProbeOptions = {},+): GeometryProbeResult {+ const maxSeparation = options.maxSeparation ?? DEFAULT_TOLERANCE;+ const maxPenetration = options.maxPenetration ?? DEFAULT_TOLERANCE;+ assertNonNegative(maxSeparation, 'maxSeparation');+ assertNonNegative(maxPenetration, 'maxPenetration');+ const relation = sat(subject, reference);+ return {+ relation: 'contact',+ pass: relation.separation <= maxSeparation && relation.penetration <= maxPenetration,+ measurements: {+ separation: relation.separation,+ penetration: relation.penetration,+ signedDistance: relation.separation > 0 ? relation.separation : stable(-relation.penetration),+ maxSeparation,+ maxPenetration,+ },+ evidence: evidence(+ subject,+ reference,+ satEvidencePoints(subject, reference, relation.axisWorld),+ relation.axisWorld,+ relation.axisLabel,+ ),+ };+}++export function probeOrientedContainment(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+ options: ContainmentProbeOptions = {},+): GeometryProbeResult {+ const tolerance = options.tolerance ?? DEFAULT_TOLERANCE;+ assertNonNegative(tolerance, 'tolerance');+ let maximumOutsideDistance = 0;+ let minimumInteriorMargin = Infinity;+ const localized = corners(subject).map((corner, index) => ({+ label: `${subject.id}.corner.${index}`,+ position: worldPointToProbeLocal(reference.frame, corner),+ }));+ const outside: LocalizedProbePoint[] = [];+ for (const point of localized) {+ const overflow = point.position.map((component, index) =>+ Math.max(0, Math.abs(component) - reference.halfExtents[index]!),+ );+ const outsideDistance = Math.hypot(...overflow);+ maximumOutsideDistance = Math.max(maximumOutsideDistance, outsideDistance);+ minimumInteriorMargin = Math.min(+ minimumInteriorMargin,+ ...point.position.map(+ (component, index) => reference.halfExtents[index]! - Math.abs(component),+ ),+ );+ if (outsideDistance > tolerance) outside.push(point);+ }+ const mostExposed = [...localized].sort((a, b) => {+ const aOverflow = Math.max(+ ...a.position.map((value, index) => Math.abs(value) - reference.halfExtents[index]!),+ );+ const bOverflow = Math.max(+ ...b.position.map((value, index) => Math.abs(value) - reference.halfExtents[index]!),+ );+ return bOverflow - aOverflow || a.label.localeCompare(b.label);+ })[0]!;+ return {+ relation: 'containment',+ pass: maximumOutsideDistance <= tolerance,+ measurements: {+ maximumOutsideDistance: stable(maximumOutsideDistance),+ minimumInteriorMargin: stable(minimumInteriorMargin),+ tolerance,+ outsideCornerCount: outside.length,+ },+ evidence: evidence(subject, reference, outside.length > 0 ? outside : [mostExposed]),+ };+}++export function probeOrientedClearance(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+ options: ClearanceProbeOptions,+): GeometryProbeResult {+ const tolerance = options.tolerance ?? DEFAULT_TOLERANCE;+ assertNonNegative(options.minimumClearance, 'minimumClearance');+ assertNonNegative(tolerance, 'tolerance');++ let clearance: number;+ let penetration: number;+ let probeAxis: ProbeVector3;+ let axisLabel: string;+ if (options.axis) {+ const direction = options.direction ?? 1;+ probeAxis = scale(axisVector(reference.frame, options.axis), direction);+ axisLabel = `reference.${options.axis}${direction === -1 ? '.negative' : '.positive'}`;+ const subjectProjection = projection(subject, probeAxis);+ const referenceProjection = projection(reference, probeAxis);+ const signedClearance = subjectProjection.min - referenceProjection.max;+ clearance = stable(Math.max(0, signedClearance));+ penetration = stable(Math.max(0, -signedClearance));+ } else {+ const relation = sat(subject, reference);+ clearance = relation.separation;+ penetration = relation.penetration;+ probeAxis = relation.axisWorld;+ axisLabel = relation.axisLabel;+ }++ return {+ relation: 'clearance',+ pass: clearance + tolerance >= options.minimumClearance && penetration <= tolerance,+ measurements: {+ clearance,+ penetration,+ minimumClearance: options.minimumClearance,+ tolerance,+ },+ evidence: evidence(+ subject,+ reference,+ satEvidencePoints(subject, reference, probeAxis),+ probeAxis,+ axisLabel,+ ),+ };+}++function angleBetweenAxes(+ subjectAxis: ProbeVector3,+ referenceAxis: ProbeVector3,+ allowOpposite: boolean,+): number {+ let cosine = Math.max(+ -1,+ Math.min(+ 1,+ allowOpposite ? Math.abs(dot(subjectAxis, referenceAxis)) : dot(subjectAxis, referenceAxis),+ ),+ );+ if (Math.abs(1 - cosine) < 1e-8) cosine = 1;+ if (Math.abs(-1 - cosine) < 1e-8) cosine = -1;+ return stable((Math.acos(cosine) * 180) / Math.PI);+}++function lateralOffset(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+ referenceAxis: ProbeVector3,+): number {+ const offset = subtract(subject.frame.origin, reference.frame.origin);+ const axial = scale(referenceAxis, dot(offset, referenceAxis));+ return stable(length(subtract(offset, axial)));+}++export function probeOrientedAlignment(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+ options: AlignmentProbeOptions = {},+): GeometryProbeResult {+ const subjectAxisName = options.subjectAxis ?? 'x';+ const referenceAxisName = options.referenceAxis ?? 'x';+ const maxAngleDegrees = options.maxAngleDegrees ?? 1;+ const maxLateralOffset = options.maxLateralOffset ?? DEFAULT_TOLERANCE;+ assertNonNegative(maxAngleDegrees, 'maxAngleDegrees');+ assertNonNegative(maxLateralOffset, 'maxLateralOffset');+ const subjectAxis = axisVector(subject.frame, subjectAxisName);+ const referenceAxis = axisVector(reference.frame, referenceAxisName);+ const angleDegrees = angleBetweenAxes(subjectAxis, referenceAxis, options.allowOpposite ?? false);+ const offset = lateralOffset(subject, reference, referenceAxis);+ const localizedCenter = worldPointToProbeLocal(reference.frame, subject.frame.origin);+ return {+ relation: 'alignment',+ pass: angleDegrees <= maxAngleDegrees && offset <= maxLateralOffset,+ measurements: { angleDegrees, lateralOffset: offset, maxAngleDegrees, maxLateralOffset },+ evidence: evidence(+ subject,+ reference,+ [+ { label: `${reference.id}.center`, position: [0, 0, 0] },+ { label: `${subject.id}.center`, position: localizedCenter },+ ],+ referenceAxis,+ `reference.${referenceAxisName}`,+ ),+ };+}++export function probeOrientedConcentricity(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+ options: ConcentricityProbeOptions = {},+): GeometryProbeResult {+ const subjectAxisName = options.subjectAxis ?? 'x';+ const referenceAxisName = options.referenceAxis ?? 'x';+ const maxRadialOffset = options.maxRadialOffset ?? DEFAULT_TOLERANCE;+ const maxAngleDegrees = options.maxAngleDegrees ?? 1;+ assertNonNegative(maxRadialOffset, 'maxRadialOffset');+ assertNonNegative(maxAngleDegrees, 'maxAngleDegrees');+ const subjectAxis = axisVector(subject.frame, subjectAxisName);+ const referenceAxis = axisVector(reference.frame, referenceAxisName);+ const offset = subtract(subject.frame.origin, reference.frame.origin);+ const axialOffset = stable(dot(offset, referenceAxis));+ const radialOffset = stable(length(subtract(offset, scale(referenceAxis, axialOffset))));+ const angleDegrees = angleBetweenAxes(subjectAxis, referenceAxis, options.allowOpposite ?? true);+ return {+ relation: 'concentricity',+ pass: radialOffset <= maxRadialOffset && angleDegrees <= maxAngleDegrees,+ measurements: {+ radialOffset,+ axialOffset,+ angleDegrees,+ maxRadialOffset,+ maxAngleDegrees,+ },+ evidence: evidence(+ subject,+ reference,+ [+ { label: `${reference.id}.axisOrigin`, position: [0, 0, 0] },+ {+ label: `${subject.id}.axisOrigin`,+ position: worldPointToProbeLocal(reference.frame, subject.frame.origin),+ },+ ],+ referenceAxis,+ `reference.${referenceAxisName}`,+ ),+ };+}++function cross2(origin: Point2, a: Point2, b: Point2): number {+ return (a[0] - origin[0]) * (b[1] - origin[1]) - (a[1] - origin[1]) * (b[0] - origin[0]);+}++function convexHull(points: Point2[]): Point2[] {+ const unique = [+ ...new Map(points.map((point) => [`${stable(point[0])},${stable(point[1])}`, point])).values(),+ ]+ .map((point): Point2 => [stable(point[0]), stable(point[1])])+ .sort((a, b) => a[0] - b[0] || a[1] - b[1]);+ if (unique.length <= 2) return unique;+ const lower: Point2[] = [];+ for (const point of unique) {+ while (lower.length >= 2 && cross2(lower.at(-2)!, lower.at(-1)!, point) <= EPSILON) lower.pop();+ lower.push(point);+ }+ const upper: Point2[] = [];+ for (let index = unique.length - 1; index >= 0; index--) {+ const point = unique[index]!;+ while (upper.length >= 2 && cross2(upper.at(-2)!, upper.at(-1)!, point) <= EPSILON) upper.pop();+ upper.push(point);+ }+ lower.pop();+ upper.pop();+ return [...lower, ...upper];+}++function clipPolygon(+ polygon: Point2[],+ coordinate: 0 | 1,+ boundary: number,+ keepGreater: boolean,+): Point2[] {+ if (polygon.length === 0) return [];+ const result: Point2[] = [];+ const inside = (point: Point2): boolean =>+ keepGreater ? point[coordinate] >= boundary - EPSILON : point[coordinate] <= boundary + EPSILON;+ let previous = polygon.at(-1)!;+ let previousInside = inside(previous);+ for (const current of polygon) {+ const currentInside = inside(current);+ if (currentInside !== previousInside) {+ const denominator = current[coordinate] - previous[coordinate];+ const t =+ Math.abs(denominator) <= EPSILON ? 0 : (boundary - previous[coordinate]) / denominator;+ result.push([+ stable(previous[0] + (current[0] - previous[0]) * t),+ stable(previous[1] + (current[1] - previous[1]) * t),+ ]);+ }+ if (currentInside) result.push(current);+ previous = current;+ previousInside = currentInside;+ }+ return result;+}++function polygonArea(polygon: Point2[]): number {+ if (polygon.length < 3) return 0;+ let twiceArea = 0;+ for (let index = 0; index < polygon.length; index++) {+ const current = polygon[index]!;+ const next = polygon[(index + 1) % polygon.length]!;+ twiceArea += current[0] * next[1] - current[1] * next[0];+ }+ return Math.abs(twiceArea) / 2;+}++export function probeOrientedCoverage(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+ options: CoverageProbeOptions = {},+): GeometryProbeResult {+ const normalAxis = options.normalAxis ?? 'y';+ const minimumRatio = options.minimumRatio ?? 0.99;+ const tolerance = options.tolerance ?? DEFAULT_TOLERANCE;+ if (!Number.isFinite(minimumRatio) || minimumRatio < 0 || minimumRatio > 1) {+ throw new TypeError('minimumRatio must be between zero and one.');+ }+ assertNonNegative(tolerance, 'tolerance');+ const normalIndex = axisIndex(normalAxis);+ const planeIndices = ([0, 1, 2] as const).filter((index) => index !== normalIndex) as [+ 0 | 1 | 2,+ 0 | 1 | 2,+ ];+ const projected = convexHull(+ corners(subject).map((corner) => {+ const local = worldPointToProbeLocal(reference.frame, corner);+ return [local[planeIndices[0]], local[planeIndices[1]]];+ }),+ );+ let covered = projected;+ for (const planeDimension of [0, 1] as const) {+ const extent = reference.halfExtents[planeIndices[planeDimension]]!;+ covered = clipPolygon(covered, planeDimension, -extent, true);+ covered = clipPolygon(covered, planeDimension, extent, false);+ }+ const targetArea =+ 4 * reference.halfExtents[planeIndices[0]]! * reference.halfExtents[planeIndices[1]]!;+ const projectedArea = polygonArea(projected);+ const coveredArea = Math.min(targetArea, polygonArea(covered));+ const coverageRatio = targetArea <= EPSILON ? 0 : coveredArea / targetArea;+ const localCenter = worldPointToProbeLocal(reference.frame, subject.frame.origin);+ const evidencePoints: LocalizedProbePoint[] = covered.map((point, index) => {+ const position: ProbeVector3 = [0, 0, 0];+ position[planeIndices[0]] = point[0];+ position[planeIndices[1]] = point[1];+ position[normalIndex] = 0;+ return { label: `coveredPolygon.${index}`, position };+ });+ return {+ relation: 'coverage',+ pass: coverageRatio + tolerance >= minimumRatio,+ measurements: {+ coverageRatio: stable(coverageRatio),+ coveredArea: stable(coveredArea),+ uncoveredArea: stable(Math.max(0, targetArea - coveredArea)),+ projectedArea: stable(projectedArea),+ targetArea: stable(targetArea),+ normalOffset: stable(Math.abs(localCenter[normalIndex])),+ minimumRatio,+ tolerance,+ },+ evidence: evidence(+ subject,+ reference,+ evidencePoints,+ axisVector(reference.frame, normalAxis),+ `reference.${normalAxis}`,+ ),+ };+}++export function probeOrientedPenetration(+ subject: OrientedProbeBox3,+ reference: OrientedProbeBox3,+ options: PenetrationProbeOptions = {},+): GeometryProbeResult {+ const maxDepth = options.maxDepth ?? 0;+ const tolerance = options.tolerance ?? DEFAULT_TOLERANCE;+ assertNonNegative(maxDepth, 'maxDepth');+ assertNonNegative(tolerance, 'tolerance');+ const relation = sat(subject, reference);+ return {+ relation: 'penetration',+ pass: relation.penetration <= maxDepth + tolerance,+ measurements: {+ penetrationDepth: relation.penetration,+ separation: relation.separation,+ maxDepth,+ tolerance,+ },+ evidence: evidence(+ subject,+ reference,+ satEvidencePoints(subject, reference, relation.axisWorld),+ relation.axisWorld,+ relation.axisLabel,+ ),+ };+}diff --git a/src/qa/gltf.test.ts b/src/qa/gltf.test.tsnew file mode 100644index 00000000..97dbe34e--- /dev/null+++ b/src/qa/gltf.test.ts@@ -0,0 +1,73 @@+import { describe, expect, test } from 'bun:test';++import { createAssetIntentV1 } from '../contracts';+import { appendFinalGltfQa, gltfReportFindings } from './run';+import { createAssetQaReportV1 } from './types';+import { validateFinalGlbBytes } from './gltf';++/**+ * A complete glTF document whose POSITION accessor declares 24 bytes of data+ * inside a 12-byte bufferView. This is more specific than a malformed-header+ * fixture: the container parses, then Khronos rejects the accessor contract.+ */+const INVALID_ACCESSOR_GLTF = new TextEncoder().encode(+ JSON.stringify({+ asset: { version: '2.0' },+ buffers: [+ {+ byteLength: 12,+ uri: 'data:application/octet-stream;base64,AAAAAAAAAAAAAAAA',+ },+ ],+ bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 12, target: 34962 }],+ accessors: [+ {+ bufferView: 0,+ componentType: 5126,+ count: 2,+ type: 'VEC3',+ min: [0, 0, 0],+ max: [1, 1, 1],+ },+ ],+ meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }],+ nodes: [{ mesh: 0 }],+ scenes: [{ nodes: [0] }],+ scene: 0,+ }),+);++describe('Khronos final-byte conformance fixtures', () => {+ test('localizes a parsed but out-of-bounds accessor as a deterministic blocker', async () => {+ const validation = await validateFinalGlbBytes(INVALID_ACCESSOR_GLTF, 'invalid-accessor.gltf');+ expect(validation.issues.numErrors).toBeGreaterThan(0);+ expect(validation.issues.messages).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ code: 'ACCESSOR_TOO_LONG',+ severity: 0,+ pointer: '/accessors/0',+ }),+ ]),+ );++ const findings = gltfReportFindings(validation, 'universal');+ expect(findings).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ code: 'GLTF_ACCESSOR_TOO_LONG',+ disposition: 'block',+ affected: { nodePath: '/accessors/0' },+ }),+ ]),+ );++ const intent = createAssetIntentV1({ category: 'prop' });+ const finalReport = appendFinalGltfQa(+ intent,+ createAssetQaReportV1(intent, { evaluatedDimensions: ['categoryReadiness'] }),+ validation,+ );+ expect(finalReport.disposition).toBe('block');+ });+});diff --git a/src/qa/gltf.ts b/src/qa/gltf.tsnew file mode 100644index 00000000..098d9a14--- /dev/null+++ b/src/qa/gltf.ts@@ -0,0 +1,103 @@+/** Official Khronos glTF Validator integration for final persisted GLB bytes. */++export interface KhronosGltfIssue {+ code: string;+ message: string;+ severity: number;+ pointer?: string;+}++export interface KhronosGltfValidationReport {+ uri?: string;+ mimeType?: string;+ validatorVersion?: string;+ validatedAt?: string;+ issues: {+ numErrors: number;+ numWarnings: number;+ numInfos: number;+ numHints: number;+ messages: KhronosGltfIssue[];+ truncated?: boolean;+ };+ info?: Record<string, unknown>;+}++function finiteCount(value: unknown): number {+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;+}++function normalizeIssue(value: unknown): KhronosGltfIssue {+ const issue = (value ?? {}) as Record<string, unknown>;+ return {+ code: typeof issue.code === 'string' ? issue.code : 'GLTF_VALIDATOR_UNKNOWN',+ message: typeof issue.message === 'string' ? issue.message : 'Unknown glTF validation issue.',+ severity: finiteCount(issue.severity),+ ...(typeof issue.pointer === 'string' ? { pointer: issue.pointer } : {}),+ };+}++function normalizeReport(value: unknown): KhronosGltfValidationReport {+ const report = (value ?? {}) as Record<string, unknown>;+ const sourceIssues = (report.issues ?? {}) as Record<string, unknown>;+ return {+ ...(typeof report.uri === 'string' ? { uri: report.uri } : {}),+ ...(typeof report.mimeType === 'string' ? { mimeType: report.mimeType } : {}),+ ...(typeof report.validatorVersion === 'string'+ ? { validatorVersion: report.validatorVersion }+ : {}),+ ...(typeof report.validatedAt === 'string' ? { validatedAt: report.validatedAt } : {}),+ issues: {+ numErrors: finiteCount(sourceIssues.numErrors),+ numWarnings: finiteCount(sourceIssues.numWarnings),+ numInfos: finiteCount(sourceIssues.numInfos),+ numHints: finiteCount(sourceIssues.numHints),+ messages: Array.isArray(sourceIssues.messages)+ ? sourceIssues.messages.map(normalizeIssue)+ : [],+ ...(typeof sourceIssues.truncated === 'boolean' ? { truncated: sourceIssues.truncated } : {}),+ },+ ...(report.info && typeof report.info === 'object'+ ? { info: report.info as Record<string, unknown> }+ : {}),+ };+}++export class GltfValidationError extends Error {+ readonly report: KhronosGltfValidationReport;++ constructor(report: KhronosGltfValidationReport) {+ const first = report.issues.messages.find((issue) => issue.severity === 0);+ super(+ `Final GLB failed Khronos validation with ${report.issues.numErrors} error(s)` ++ (first ? `: ${first.code} — ${first.message}` : '.'),+ );+ this.name = 'GltfValidationError';+ this.report = report;+ }+}++/** Validate the exact bytes intended for persistence. No network resources are permitted. */+export async function validateFinalGlbBytes(+ bytes: Uint8Array,+ uri = 'model.glb',+): Promise<KhronosGltfValidationReport> {+ const validator = await import('gltf-validator');+ const raw = await validator.validateBytes(bytes, {+ uri,+ maxIssues: 1_000,+ externalResourceFunction: async (externalUri: string) => {+ throw new Error(`External glTF resource is forbidden in final GLB: ${externalUri}`);+ },+ });+ return normalizeReport(raw);+}++export async function assertFinalGlbValid(+ bytes: Uint8Array,+ uri = 'model.glb',+): Promise<KhronosGltfValidationReport> {+ const report = await validateFinalGlbBytes(bytes, uri);+ if (report.issues.numErrors > 0) throw new GltfValidationError(report);+ return report;+}diff --git a/src/qa/index.ts b/src/qa/index.tsnew file mode 100644index 00000000..b8576289--- /dev/null+++ b/src/qa/index.ts@@ -0,0 +1,27 @@+export * from './types';+export * from './registry';+export * from './universal';+export * from './corpus';+export * from './gltf';+export * from './geometry-relations';+export * from './material';+export * from './architecture';+export * from './architecture-repairs';+export * from './architecture-corpus';+export * from './character';+export * from './character-advisory';+export * from './character-repairs';+export * from './character-vehicle-corpus';+export * from './vehicle';+export * from './vehicle-advisory';+export * from './vegetation';+export * from './vegetation-corpus';+export * from './prop';+export * from './prop-helper-policy';+export * from './prop-environment-prompt';+export * from './environment';+export * from './breadth';+export * from './breadth-evidence';+export * from './breadth-final';+export * from './breadth-corpus';+export * from './run';diff --git a/src/qa/material.test.ts b/src/qa/material.test.tsnew file mode 100644index 00000000..17d3da13--- /dev/null+++ b/src/qa/material.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import { createAssetIntentV1 } from '../contracts';+import { inspectSceneMaterials } from './material';++const intent = createAssetIntentV1({ category: 'prop' });++describe('material portable-PBR conformance fixtures', () => {+ test('accepts a finite untextured standard material control', () => {+ const scene = new THREE.Group();+ scene.add(+ new THREE.Mesh(+ new THREE.BoxGeometry(1, 1, 1),+ new THREE.MeshStandardMaterial({ roughness: 0.7, metalness: 0.1 }),+ ),+ );++ expect(inspectSceneMaterials({ intent, scene })).toEqual([]);+ });++ test('blocks a non-finite portable-PBR factor with the exact finding code', () => {+ const scene = new THREE.Group();+ const material = new THREE.MeshStandardMaterial();+ material.roughness = Number.NaN;+ scene.add(new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), material));++ const findings = inspectSceneMaterials({ intent, scene });+ expect(findings.map((finding) => finding.code)).toEqual(['MAT_NONFINITE_FACTOR']);+ expect(findings[0]?.disposition).toBe('block');+ });+});diff --git a/src/qa/material.ts b/src/qa/material.tsnew file mode 100644index 00000000..2e08b839--- /dev/null+++ b/src/qa/material.ts@@ -0,0 +1,292 @@+import * as THREE from 'three';++import type { KilnTextureMetadata } from '../textures';+import { conformancePromotionAuthorization, KILN_ENGINE_QA_OWNER, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';++type StandardMaterial = THREE.MeshStandardMaterial & {+ isMeshStandardMaterial?: boolean;+};++type EncodedTextureLike = {+ mime?: unknown;+ bytes?: unknown;+};++function textureMeta(texture: THREE.Texture): KilnTextureMetadata | undefined {+ return (texture.userData as Record<string, unknown>)['kilnTexture'] as+ | KilnTextureMetadata+ | undefined;+}++function affected(+ mesh: THREE.Mesh,+ material: THREE.Material,+ texture?: THREE.Texture,+ attribute?: string,+) {+ return {+ node: mesh.name || '(unnamed mesh)',+ material: material.name || '(unnamed material)',+ ...(texture ? { texture: texture.name || '(unnamed texture)' } : {}),+ ...(attribute ? { attribute } : {}),+ };+}++function textureHasAlpha(texture: THREE.Texture): boolean {+ const meta = textureMeta(texture);+ if (meta) return meta.hasAlpha;+ const image = texture.image as+ | { data?: ArrayLike<number>; width?: number; height?: number }+ | undefined;+ const data = image?.data;+ if (!data || data.length < 4) return false;+ for (let i = 3; i < data.length; i += 4) {+ if ((data[i] ?? 255) < 255) return true;+ }+ return false;+}++function encodedTextureIsExportable(texture: THREE.Texture): boolean {+ const encoded = (texture.userData as Record<string, unknown>)['encoded'] as+ | EncodedTextureLike+ | undefined;+ if (!encoded || typeof encoded.mime !== 'string') return false;+ const bytes = encoded.bytes as ArrayLike<number> | undefined;+ if (!bytes || typeof bytes.length !== 'number' || bytes.length < 4) return false;++ if (encoded.mime === 'image/png') {+ return (+ bytes.length >= 8 &&+ bytes[0] === 0x89 &&+ bytes[1] === 0x50 &&+ bytes[2] === 0x4e &&+ bytes[3] === 0x47+ );+ }+ if (encoded.mime === 'image/jpeg') {+ return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;+ }+ if (encoded.mime === 'image/webp') {+ return (+ bytes.length >= 12 &&+ bytes[0] === 0x52 &&+ bytes[1] === 0x49 &&+ bytes[2] === 0x46 &&+ bytes[3] === 0x46 &&+ bytes[8] === 0x57 &&+ bytes[9] === 0x45 &&+ bytes[10] === 0x42 &&+ bytes[11] === 0x50+ );+ }+ return false;+}++function validateTextureSlot(+ findings: QaFinding[],+ mesh: THREE.Mesh,+ material: StandardMaterial,+ texture: THREE.Texture | null,+ slot: string,+ expected: 'srgb' | 'linear',+): void {+ if (!texture) return;+ const meta = textureMeta(texture);+ const actual =+ texture.colorSpace === THREE.SRGBColorSpace+ ? 'srgb'+ : texture.colorSpace === THREE.NoColorSpace+ ? 'linear'+ : (meta?.colorSpace ?? 'linear');+ if (!meta || !encodedTextureIsExportable(texture)) {+ findings.push({+ code: 'MAT_TEXTURE_DECODE_FAILED',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'material.portablePbr',+ 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.',+ });+ }+ if (actual !== expected) {+ findings.push({+ code: 'MAT_TEXTURE_COLOR_SPACE',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'material.portablePbr',+ 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}' }).`,+ });+ }++ const image = texture.image as { width?: number; height?: number } | undefined;+ if (+ !image ||+ !Number.isFinite(image.width) ||+ !Number.isFinite(image.height) ||+ (image.width ?? 0) <= 0 ||+ (image.height ?? 0) <= 0+ ) {+ findings.push({+ code: 'MAT_TEXTURE_INVALID_DIMENSIONS',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'material.portablePbr',+ message: `${slot} texture has invalid or undecodable dimensions.`,+ affected: affected(mesh, material, texture, slot),+ repairText: 'Use a decodable PNG, JPEG, or WebP with positive dimensions.',+ });+ }+ if (!mesh.geometry.getAttribute('uv')) {+ findings.push({+ code: 'MAT_TEXTURE_UV_MISSING',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'material.portablePbr',+ message: `${slot} texture is used on geometry without TEXCOORD_0 UVs.`,+ affected: affected(mesh, material, texture, slot),+ repairText: 'Unwrap the geometry before assigning a texture-backed material.',+ });+ }+}++function validateMaterial(+ mesh: THREE.Mesh,+ material: THREE.Material,+ requiresPrecomputedTangents: boolean,+): QaFinding[] {+ const findings: QaFinding[] = [];+ const standard = material as StandardMaterial;+ if (!standard.isMeshStandardMaterial) return findings;++ for (const [name, value] of [+ ['roughness', standard.roughness],+ ['metalness', standard.metalness],+ ['opacity', standard.opacity],+ ['emissiveIntensity', standard.emissiveIntensity],+ ] as const) {+ if (!Number.isFinite(value)) {+ findings.push({+ code: 'MAT_NONFINITE_FACTOR',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'material.portablePbr',+ message: `Material factor ${name} is non-finite.`,+ affected: affected(mesh, material),+ measurement: { name, actual: String(value) },+ });+ }+ }++ validateTextureSlot(findings, mesh, standard, standard.map, 'map', 'srgb');+ validateTextureSlot(findings, mesh, standard, standard.emissiveMap, 'emissive', 'srgb');+ validateTextureSlot(findings, mesh, standard, standard.normalMap, 'normal', 'linear');+ validateTextureSlot(+ findings,+ mesh,+ standard,+ standard.roughnessMap,+ 'metallicRoughness',+ 'linear',+ );+ validateTextureSlot(+ findings,+ mesh,+ standard,+ standard.metalnessMap,+ 'metallicRoughness',+ 'linear',+ );+ validateTextureSlot(findings, mesh, standard, standard.aoMap, 'occlusion', 'linear');++ if (standard.normalMap && !mesh.geometry.getAttribute('tangent')) {+ findings.push({+ code: 'MAT_NORMAL_TANGENTS_MISSING',+ disposition: requiresPrecomputedTangents ? 'block' : 'warn',+ dimension: 'categoryReadiness',+ profile: 'material.portablePbr',+ message: requiresPrecomputedTangents+ ? 'The trusted consumer profile requires precomputed tangents for normal-mapped geometry.'+ : 'Normal-mapped geometry has no precomputed tangents; the consumer must derive them.',+ affected: affected(mesh, material, standard.normalMap, 'normal'),+ repairText: 'Generate and export TANGENT data for the normal-mapped geometry.',+ });+ }++ if (+ standard.roughnessMap &&+ standard.metalnessMap &&+ standard.roughnessMap !== standard.metalnessMap+ ) {+ findings.push({+ code: 'MAT_SEPARATE_METALLIC_ROUGHNESS',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'material.portablePbr',+ message: 'glTF requires one packed metallic-roughness texture (G=roughness, B=metalness).',+ affected: affected(mesh, material),+ repairText: 'Pack both channels and pass the result as metallicRoughness.',+ });+ }++ if (mesh.geometry.userData['kilnGeometryRole'] === 'foliageCard') {+ const validMask = standard.alphaTest > 0 && !standard.transparent;+ if (+ !standard.map ||+ !textureHasAlpha(standard.map) ||+ !validMask ||+ standard.side !== THREE.DoubleSide ||+ !mesh.geometry.getAttribute('uv')+ ) {+ findings.push({+ code: 'MAT_FOLIAGE_CARD_CONTRACT',+ disposition: 'block',+ dimension: 'categoryReadiness',+ profile: 'material.foliageCard',+ message:+ 'Foliage cards require UVs, an alpha-bearing base-color texture, MASK cutoff, and double-sided output.',+ affected: affected(mesh, material, standard.map ?? undefined),+ repairText: 'Use foliageMaterial() with an alpha-bearing albedo texture.',+ });+ }+ }++ return findings;+}++export function inspectSceneMaterials(context: QaContext): QaFinding[] {+ const root = context.scene as THREE.Object3D | undefined;+ if (!root?.traverse) return [];+ const findings: QaFinding[] = [];+ const requiresPrecomputedTangents = context.intent.capabilities.includes('precomputedTangents');+ root.traverse((node) => {+ const mesh = node as THREE.Mesh;+ if (!mesh.isMesh || !mesh.geometry) return;+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];+ for (const material of materials) {+ if (material) {+ findings.push(...validateMaterial(mesh, material, requiresPrecomputedTangents));+ }+ }+ });+ return findings;+}++export const MATERIAL_QA_RULE: QaRule = {+ id: 'MATERIAL_PORTABLE_PBR_RULE',+ profile: 'material.portablePbr',+ scope: { kind: 'universal' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'material-portable-pbr-v1',+ 'src/qa/material.test.ts',+ '27f7469603ba986acfac2c6acbfb293ad787717aecdf4a3d03cae625f86f45e7',+ ),+ defaultMode: 'enforce',+ evaluate: inspectSceneMaterials,+};diff --git a/src/qa/prop-environment-prompt.ts b/src/qa/prop-environment-prompt.tsnew file mode 100644index 00000000..850b7b41--- /dev/null+++ b/src/qa/prop-environment-prompt.ts@@ -0,0 +1,58 @@+import type { AssetIntentV1 } from '../contracts';+import { resolveEnvironmentIntentProfile } from '../contracts/environment';++/**+ * Semantic construction guidance appended only for the resolved category.+ * This owns capability vocabulary, not noun-specific geometry recipes.+ */+export function buildPropEnvironmentSemanticGuidance(intent: AssetIntentV1): string {+ if (intent.category === 'prop') {+ const sections: string[] = [+ '## Prop capability contract',+ 'Keep +X forward, +Y up, +Z right, meters, and asset-local ground Y=0.',+ ];+ if (intent.capabilities.includes('articulated')) {+ sections.push(+ 'For each moving assembly choose hinge, slider, or spinner. Tag the real pivot as prop.pivot.<kind>.<id>, the moving subtree as prop.motion.<kind>.<id>, add a normalized axis.+x/+y/+z local frame, and add a scaled non-rendered prop.clearance.<id> (or prop.clearance.<kind>.<id>) sweep marker. Parent only the moving meshes beneath the pivot. If a stationary hinge mount legitimately touches that sweep, give only that support prop.articulation.support.<id> and declare a mountedTo or allowsClearanceContact relationship from the pivot/clearance marker to that exact role.',+ );+ }+ if (intent.capabilities.includes('openable')) {+ sections.push(+ 'Openable containers must have real negative space: tag non-rendered scaled prop.container.interior.main and prop.container.opening.main prisms, keep solid filler out of the opening, and keep the lid/door a distinct moving subtree.',+ );+ }+ if (intent.bounds) {+ sections.push(+ `Honor declared bounds ${JSON.stringify(intent.bounds)} and place prop.pivot.placement on the support base.`,+ );+ }+ if (/(?:barrel|drum)/i.test(intent.subtype ?? '')) {+ sections.push(+ 'For a circular barrel/drum assembly, tag prop.circular.assembly and prop.circular.member.<id>, distribute members around a complete ring, and keep stave width tangent to the ring unless prop.circular.expected.radial is explicitly tagged.',+ );+ }+ return sections.join('\n');+ }++ if (intent.category === 'environment') {+ const profile = resolveEnvironmentIntentProfile(intent)!;+ const sections = [+ '## Environment capability contract',+ `Resolved subtype: ${profile.subtype}. Keep +X forward, +Y up, +Z right, meters, and asset-local ground Y=0.`,+ 'Use semantic socket frames, not guessed node origins: requested tile axes use environment.tile.x-negative/x-positive or environment.tile.z-negative/z-positive; requested road and bridge joins use environment.road.start/end or environment.bridge.start/end; requested wall/gate joins use environment.wall.left/right or environment.gate.left/right; dressing clusters may declare environment.scatter-zone. Every axis or join you declare must include its complete opposing pair; do not invent unrequested axes or joins.',+ 'Tag intentional terrain volume as environment.ground.* or environment.terrain.volume.*. Tag functional surfaces/layers explicitly so below-ground terrain is not confused with a buried road, deck, gate, or unsupported floating layer.',+ ];+ if (profile.tileable) {+ sections.push(+ 'For each explicitly requested tile axis, make its opposing boundaries agree in sampled height, vertex normal, and portable material role, and put the paired socket frames at matching boundary locations. Do not assume both X and Z axes were requested.',+ );+ }+ if (profile.navigable) {+ sections.push(+ 'Add a scaled non-rendered environment.navigation.corridor.<id> prism along every requested path/cave/bridge route and keep it free of renderable blockers. Size it to explicit user/gameplay dimensions; when none are declared, 0.8 m width and 1.8 m headroom are advisory review heuristics only.',+ );+ }+ return sections.join('\n');+ }+ return '';+}diff --git a/src/qa/prop-helper-policy.ts b/src/qa/prop-helper-policy.tsnew file mode 100644index 00000000..9d3cb6ab--- /dev/null+++ b/src/qa/prop-helper-policy.ts@@ -0,0 +1,118 @@+export const PROP_HELPER_ABLATION_SCHEMA_VERSION = 1 as const;+export const PROP_HELPER_ABLATION_MINIMUM_LIFT = 0.15;++export type PropHelperCandidateKind = 'capability-scaffold' | 'noun-specific-helper';++export interface PropHelperAblationArmV1 {+ passedCases: number;+ evaluatedCases: number;+}++export interface PropHelperAblationEvidenceV1 {+ schemaVersion: typeof PROP_HELPER_ABLATION_SCHEMA_VERSION;+ experimentId: string;+ candidateKind: PropHelperCandidateKind;+ fixedCorpusId: string;+ baseline: PropHelperAblationArmV1;+ /** Generic capability scaffold, which is the mandatory comparison for noun helpers. */+ capabilityScaffold: PropHelperAblationArmV1;+ candidate: PropHelperAblationArmV1;+ propControlCorpusId: string;+ propControlCases: number;+ propControlRegressions: number;+}++export interface PropHelperAblationDecisionV1 {+ schemaVersion: typeof PROP_HELPER_ABLATION_SCHEMA_VERSION;+ experimentId: string;+ approved: boolean;+ baselineRate: number;+ capabilityScaffoldRate: number;+ candidateRate: number;+ requiredComparatorRate: number;+ lift: number;+ reasons: string[];+}++const rate = (arm: PropHelperAblationArmV1): number =>+ arm.evaluatedCases === 0 ? 0 : arm.passedCases / arm.evaluatedCases;+const stable = (value: number): number => Math.round(value * 1_000_000) / 1_000_000;++function validateArm(arm: PropHelperAblationArmV1, path: string): void {+ if (+ !Number.isInteger(arm.evaluatedCases) ||+ arm.evaluatedCases <= 0 ||+ !Number.isInteger(arm.passedCases) ||+ arm.passedCases < 0 ||+ arm.passedCases > arm.evaluatedCases+ ) {+ throw new TypeError(+ `${path} must contain integer passed/evaluated counts with 0 <= passed <= evaluated.`,+ );+ }+}++/**+ * PROP-006 policy. A capability scaffold must beat free composition; a future+ * noun-specific helper must then beat that scaffold. Either path closes when a+ * single frozen prop control regresses.+ */+export function evaluatePropHelperAblation(+ evidence: PropHelperAblationEvidenceV1,+): PropHelperAblationDecisionV1 {+ if (evidence.schemaVersion !== PROP_HELPER_ABLATION_SCHEMA_VERSION) {+ throw new TypeError(`schemaVersion must be ${PROP_HELPER_ABLATION_SCHEMA_VERSION}.`);+ }+ if (+ !evidence.experimentId.trim() ||+ !evidence.fixedCorpusId.trim() ||+ !evidence.propControlCorpusId.trim()+ ) {+ throw new TypeError('experimentId, fixedCorpusId, and propControlCorpusId are required.');+ }+ validateArm(evidence.baseline, 'baseline');+ validateArm(evidence.capabilityScaffold, 'capabilityScaffold');+ validateArm(evidence.candidate, 'candidate');+ if (+ !Number.isInteger(evidence.propControlCases) ||+ evidence.propControlCases <= 0 ||+ !Number.isInteger(evidence.propControlRegressions) ||+ evidence.propControlRegressions < 0 ||+ evidence.propControlRegressions > evidence.propControlCases+ ) {+ throw new TypeError('Prop control counts are invalid.');+ }++ const baselineRate = rate(evidence.baseline);+ const capabilityScaffoldRate = rate(evidence.capabilityScaffold);+ const candidateRate = rate(evidence.candidate);+ const comparatorRate =+ evidence.candidateKind === 'capability-scaffold' ? baselineRate : capabilityScaffoldRate;+ const lift = candidateRate - comparatorRate;+ const reasons: string[] = [];+ if (evidence.propControlRegressions > 0) {+ reasons.push(`${evidence.propControlRegressions} frozen prop control cases regressed.`);+ }+ if (+ evidence.candidateKind === 'capability-scaffold' &&+ capabilityScaffoldRate !== candidateRate+ ) {+ reasons.push('Capability-scaffold candidate arm must equal the named capabilityScaffold arm.');+ }+ if (lift + 1e-12 < PROP_HELPER_ABLATION_MINIMUM_LIFT) {+ reasons.push(+ `Candidate lift ${stable(lift)} is below the required ${PROP_HELPER_ABLATION_MINIMUM_LIFT}.`,+ );+ }+ return {+ schemaVersion: PROP_HELPER_ABLATION_SCHEMA_VERSION,+ experimentId: evidence.experimentId,+ approved: reasons.length === 0,+ baselineRate: stable(baselineRate),+ capabilityScaffoldRate: stable(capabilityScaffoldRate),+ candidateRate: stable(candidateRate),+ requiredComparatorRate: stable(comparatorRate),+ lift: stable(lift),+ reasons,+ };+}diff --git a/src/qa/prop.test.ts b/src/qa/prop.test.tsnew file mode 100644index 00000000..bcb6cb3c--- /dev/null+++ b/src/qa/prop.test.ts@@ -0,0 +1,330 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import { createAssetIntentV1, stampSemanticMetadataV1 } from '../contracts';+import { buildPropEnvironmentSemanticGuidance } from './prop-environment-prompt';+import {+ evaluatePropArticulationQa,+ evaluatePropCircularAssemblyQa,+ evaluatePropContainerQa,+ evaluatePropScalePivotQa,+} from './prop';+import {+ evaluatePropHelperAblation,+ PROP_HELPER_ABLATION_MINIMUM_LIFT,+ type PropHelperAblationEvidenceV1,+} from './prop-helper-policy';+import type { QaContext } from './types';++const material = new THREE.MeshStandardMaterial({ color: '#777777' });++function mesh(name: string, size: [number, number, number], position: [number, number, number]) {+ const value = new THREE.Mesh(new THREE.BoxGeometry(...size), material);+ value.name = name;+ value.position.set(...position);+ return value;+}++function marker(+ name: string,+ role: string,+ position: [number, number, number],+ scale: [number, number, number],+) {+ const value = new THREE.Group();+ value.name = name;+ value.position.set(...position);+ value.scale.set(...scale);+ stampSemanticMetadataV1(value, { roles: [role] });+ return value;+}++function context(+ root: THREE.Object3D,+ options: {+ subtype?: string;+ capabilities?: Array<'articulated' | 'openable' | 'grounded'>;+ bounds?: { x?: number; y?: number; z?: number; units: 'm' };+ clips?: THREE.AnimationClip[];+ qaProfile?: string;+ } = {},+): QaContext {+ const intent = createAssetIntentV1({+ category: 'prop',+ subtype: options.subtype,+ capabilities: options.capabilities ?? [],+ bounds: options.bounds,+ qaProfile: options.qaProfile,+ animation: options.clips+ ? { clips: options.clips.map((clip) => clip.name), loop: false }+ : undefined,+ });+ return { intent, scene: root, clips: options.clips ?? [] };+}++function codes(findings: readonly { code: string }[]): string[] {+ return findings.map((finding) => finding.code);+}++function validHinge(): THREE.Group {+ const root = new THREE.Group();+ root.name = 'SemanticChest';+ root.add(mesh('StaticBody', [1, 0.8, 0.8], [-1.2, 0.4, 0]));+ const pivot = new THREE.Group();+ pivot.name = 'Joint_Lid';+ stampSemanticMetadataV1(pivot, {+ roles: ['prop.pivot.hinge.lid'],+ frames: [{ id: 'axis.+x', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ });+ const moving = mesh('Lid', [0.8, 0.12, 0.5], [0, 0.2, 0]);+ stampSemanticMetadataV1(moving, { roles: ['prop.motion.hinge.lid'] });+ pivot.add(moving);+ root.add(pivot, marker('LidSweep', 'prop.clearance.hinge.lid', [0, 0.6, 0], [1, 1, 1]));+ return root;+}++describe('PROP-002 articulated capability profile', () => {+ test('accepts a semantic hinge with pivot, axis, moving subtree, and clear sweep', () => {+ expect(+ evaluatePropArticulationQa(context(validHinge(), { capabilities: ['articulated'] })),+ ).toEqual([]);+ });++ test('localizes missing axis, wrong subtree, missing clearance, and blocked clearance', () => {+ const root = validHinge();+ const pivot = root.getObjectByName('Joint_Lid')!;+ stampSemanticMetadataV1(pivot, { roles: ['prop.pivot.hinge.lid'] });+ const moving = root.getObjectByName('Lid')!;+ root.attach(moving);+ const sweep = root.getObjectByName('LidSweep')!;+ root.remove(sweep);+ expect(+ codes(evaluatePropArticulationQa(context(root, { capabilities: ['articulated'] }))),+ ).toEqual([+ 'PROP_ARTICULATION_AXIS_MISSING',+ 'PROP_ARTICULATION_SUBTREE_INVALID',+ 'PROP_ARTICULATION_CLEARANCE_MISSING',+ ]);++ const blocked = validHinge();+ blocked.add(mesh('SolidFiller', [0.3, 0.3, 0.3], [0, 0.6, 0]));+ expect(+ codes(evaluatePropArticulationQa(context(blocked, { capabilities: ['articulated'] }))),+ ).toContain('PROP_ARTICULATION_CLEARANCE_BLOCKED');+ });++ test('allows only explicitly declared stationary hinge support inside the sweep', () => {+ const root = validHinge();+ const body = root.getObjectByName('StaticBody')!;+ body.position.x = 0;+ stampSemanticMetadataV1(body, { roles: ['prop.articulation.support.lid'] });+ const pivot = root.getObjectByName('Joint_Lid')!;+ stampSemanticMetadataV1(pivot, {+ roles: ['prop.pivot.hinge.lid'],+ frames: [{ id: 'axis.+x', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ relationships: [+ {+ kind: 'mountedTo',+ target: 'prop.articulation.support.lid',+ targetType: 'role',+ },+ ],+ });+ expect(evaluatePropArticulationQa(context(root, { capabilities: ['articulated'] }))).toEqual(+ [],+ );++ root.add(mesh('UndeclaredFiller', [0.2, 0.2, 0.2], [0, 0.6, 0]));+ expect(+ codes(evaluatePropArticulationQa(context(root, { capabilities: ['articulated'] }))),+ ).toContain('PROP_ARTICULATION_CLEARANCE_BLOCKED');+ });++ test('preserves the narrow W5 Joint_Lid + Open-clip legacy fallback', () => {+ const root = new THREE.Group();+ root.name = 'PropControlAnimatedFieldChest';+ root.add(mesh('Mesh_Base', [1.3, 0.66, 0.78], [0, 0.33, 0]));+ const pivot = new THREE.Group();+ pivot.name = 'Joint_Lid';+ pivot.add(mesh('Mesh_Lid', [1.34, 0.16, 0.82], [0, 0.08, 0.39]));+ root.add(pivot);+ const clip = new THREE.AnimationClip('Open', 1, [+ new THREE.QuaternionKeyframeTrack(+ 'Joint_Lid.quaternion',+ [0, 1],+ [0, 0, 0, 1, Math.SQRT1_2, 0, 0, Math.SQRT1_2],+ ),+ ]);+ const value = context(root, {+ subtype: 'field-chest',+ capabilities: ['grounded', 'articulated', 'openable'],+ clips: [clip],+ qaProfile: 'prop.legacy-control',+ });+ expect(evaluatePropArticulationQa(value)).toEqual([]);+ expect(evaluatePropContainerQa(value)).toEqual([]);++ const newOutput = context(root, {+ subtype: 'field-chest',+ capabilities: ['grounded', 'articulated', 'openable'],+ clips: [clip],+ });+ expect(codes(evaluatePropArticulationQa(newOutput))).toEqual(['PROP_ARTICULATION_MISSING']);+ expect(codes(evaluatePropContainerQa(newOutput))).toEqual(['PROP_CONTAINER_OPENING_MISSING']);+ });+});++describe('PROP-003 container negative-space profile', () => {+ function containerScene(blocked = false): THREE.Group {+ const root = new THREE.Group();+ root.name = 'OpenContainer';+ const shell = mesh('Shell', [1.2, 0.7, 0.8], [0, 0.35, 0]);+ stampSemanticMetadataV1(shell, { roles: ['prop.container.shell'] });+ root.add(+ shell,+ marker('Interior', 'prop.container.interior.main', [0, 0.4, 0], [0.8, 0.45, 0.5]),+ marker('Opening', 'prop.container.opening.main', [0, 0.72, 0], [0.8, 0.16, 0.5]),+ );+ if (blocked) root.add(mesh('SolidFiller', [0.6, 0.12, 0.35], [0, 0.72, 0]));+ return root;+ }++ test('accepts measurable interior/opening markers and rejects a solid filler', () => {+ expect(+ evaluatePropContainerQa(+ context(containerScene(), { subtype: 'open-container', capabilities: ['openable'] }),+ ),+ ).toEqual([]);+ expect(+ codes(+ evaluatePropContainerQa(+ context(containerScene(true), { subtype: 'open-container', capabilities: ['openable'] }),+ ),+ ),+ ).toContain('PROP_CONTAINER_OPENING_BLOCKED');+ });++ test('rejects missing or unusably thin negative space when semantic evidence is claimed', () => {+ const root = new THREE.Group();+ root.add(marker('Opening', 'prop.container.opening.main', [0, 0.5, 0], [0.5, 0.2, 0.5]));+ expect(+ codes(+ evaluatePropContainerQa(+ context(root, { subtype: 'open-container', capabilities: ['openable'] }),+ ),+ ),+ ).toContain('PROP_CONTAINER_INTERIOR_MISSING');+ root.add(marker('Interior', 'prop.container.interior.main', [0, 0.3, 0], [0.5, 0.02, 0.5]));+ expect(+ codes(+ evaluatePropContainerQa(+ context(root, { subtype: 'open-container', capabilities: ['openable'] }),+ ),+ ),+ ).toContain('PROP_CONTAINER_INTERIOR_UNUSABLE');+ });+});++describe('PROP-004/005 advisory evidence', () => {+ function ring(options: { missing?: boolean; radial?: boolean } = {}): THREE.Group {+ const root = new THREE.Group();+ root.name = 'Barrel';+ stampSemanticMetadataV1(root, { roles: ['prop.circular.assembly'] });+ const count = options.missing ? 7 : 8;+ for (let index = 0; index < count; index++) {+ const sourceIndex = options.missing && index >= 4 ? index + 1 : index;+ const angle = (sourceIndex / 8) * Math.PI * 2;+ const stave = mesh(`Stave_${index}`, [0.45, 1, 0.1], [Math.cos(angle), 0.5, Math.sin(angle)]);+ const desired = options.radial+ ? new THREE.Vector3(Math.cos(angle), 0, Math.sin(angle))+ : new THREE.Vector3(-Math.sin(angle), 0, Math.cos(angle));+ stave.quaternion.setFromUnitVectors(new THREE.Vector3(1, 0, 0), desired);+ stampSemanticMetadataV1(stave, { roles: [`prop.circular.member.${index}`] });+ root.add(stave);+ }+ return root;+ }++ test('finds incomplete and radial-vs-tangent rings but ignores arbitrary radial art', () => {+ expect(+ codes(+ evaluatePropCircularAssemblyQa(context(ring({ missing: true }), { subtype: 'barrel' })),+ ),+ ).toContain('PROP_CIRCULAR_RING_INCOMPLETE');+ expect(+ codes(evaluatePropCircularAssemblyQa(context(ring({ radial: true }), { subtype: 'barrel' }))),+ ).toContain('PROP_CIRCULAR_MEMBER_ORIENTATION');+ const art = ring({ radial: true });+ art.traverse((node) => {+ if (node.userData.kilnSemantic) delete node.userData.kilnSemantic;+ });+ expect(evaluatePropCircularAssemblyQa(context(art, { subtype: 'abstract-sunburst' }))).toEqual(+ [],+ );+ });++ test('reports declared scale, ground, and placement-pivot deltas without blocking', () => {+ const root = new THREE.Group();+ root.add(mesh('Body', [2, 1, 1], [0, 0.7, 0]));+ root.add(marker('Placement', 'prop.pivot.placement', [2, 0.8, 0], [0.01, 0.01, 0.01]));+ const findings = evaluatePropScalePivotQa(+ context(root, {+ capabilities: ['grounded'],+ bounds: { x: 1, y: 1, z: 1, units: 'm' },+ }),+ );+ expect(codes(findings)).toEqual([+ 'PROP_SCALE_BOUNDS_MISMATCH',+ 'PROP_GROUND_MISMATCH',+ 'PROP_PLACEMENT_PIVOT_OFF_BASE',+ ]);+ expect(findings.every((finding) => finding.disposition === 'warn')).toBe(true);+ });+});++describe('PROP-006 capability-first helper policy and prompt guidance', () => {+ const evidence: PropHelperAblationEvidenceV1 = {+ schemaVersion: 1,+ experimentId: 'kiln.prop-capability-scaffold.v1',+ candidateKind: 'capability-scaffold',+ fixedCorpusId: 'kiln.prop-capability-defects.v1',+ baseline: { passedCases: 4, evaluatedCases: 8 },+ capabilityScaffold: { passedCases: 8, evaluatedCases: 8 },+ candidate: { passedCases: 8, evaluatedCases: 8 },+ propControlCorpusId: 'kiln.prop-control.v1',+ propControlCases: 4,+ propControlRegressions: 0,+ };++ test('approves the generic capability scaffold and closes regressing/noun-only candidates', () => {+ const approved = evaluatePropHelperAblation(evidence);+ expect(approved.approved).toBe(true);+ expect(approved.lift).toBe(0.5);+ expect(approved.lift).toBeGreaterThanOrEqual(PROP_HELPER_ABLATION_MINIMUM_LIFT);++ expect(evaluatePropHelperAblation({ ...evidence, propControlRegressions: 1 }).approved).toBe(+ false,+ );+ expect(+ evaluatePropHelperAblation({+ ...evidence,+ candidateKind: 'noun-specific-helper',+ candidate: { passedCases: 8, evaluatedCases: 8 },+ }).approved,+ ).toBe(false);+ });++ test('emits capability vocabulary instead of noun-specific construction recipes', () => {+ const intent = createAssetIntentV1({+ category: 'prop',+ subtype: 'barrel',+ capabilities: ['articulated', 'openable', 'grounded'],+ bounds: { x: 1, y: 1.2, z: 1, units: 'm' },+ });+ const guidance = buildPropEnvironmentSemanticGuidance(intent);+ expect(guidance).toContain('hinge, slider, or spinner');+ expect(guidance).toContain('prop.container.interior.main');+ expect(guidance).toContain('prop.circular.member.<id>');+ expect(guidance).not.toContain('createBarrel');+ });+});diff --git a/src/qa/prop.ts b/src/qa/prop.tsnew file mode 100644index 00000000..d5f4d701--- /dev/null+++ b/src/qa/prop.ts@@ -0,0 +1,737 @@+import * as THREE from 'three';++import { readSemanticMetadataV1 } from '../contracts';+import { conformancePromotionAuthorization, KILN_ENGINE_QA_OWNER, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';++const PROFILE = 'prop.capability';+const GROUND_TOLERANCE_METERS = 0.02;+const CLEARANCE_TOLERANCE_METERS = 0.004;++export const PROP_MOTION_KINDS = ['hinge', 'slider', 'spinner'] as const;+export type PropMotionKind = (typeof PROP_MOTION_KINDS)[number];++interface LocalPart {+ node: THREE.Object3D;+ roles: readonly string[];+ box?: THREE.Box3;+ renderable: boolean;+}++interface PropMotionAssembly {+ id: string;+ kind: PropMotionKind;+ pivot?: LocalPart;+ moving?: LocalPart;+ clearance?: LocalPart;+}++const stable = (value: number): number => Math.round(value * 1_000_000) / 1_000_000;++function finding(context: QaContext, value: Omit<QaFinding, 'profile'>): QaFinding {+ return { ...value, profile: context.intent.qaProfile || PROFILE };+}++function rolesOf(node: THREE.Object3D): readonly string[] {+ return readSemanticMetadataV1(node)?.roles ?? [];+}++function nodePath(root: THREE.Object3D, node: THREE.Object3D): string {+ const names: string[] = [];+ let cursor: THREE.Object3D | null = node;+ while (cursor) {+ names.push(cursor.name || cursor.type);+ if (cursor === root) break;+ cursor = cursor.parent;+ }+ return names.reverse().join('/');+}++function transformedBox(source: THREE.Box3, transform: THREE.Matrix4): THREE.Box3 {+ const result = new THREE.Box3();+ for (const x of [source.min.x, source.max.x]) {+ for (const y of [source.min.y, source.max.y]) {+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(transform));+ }+ }+ }+ return result;+}++function collectParts(root: THREE.Object3D): LocalPart[] {+ root.updateWorldMatrix(true, true);+ const rootInverse = root.matrixWorld.clone().invert();+ const result: LocalPart[] = [];+ root.traverse((node) => {+ const roles = rolesOf(node);+ const renderable = node instanceof THREE.Mesh;+ let box: THREE.Box3 | undefined;+ if (renderable && node.geometry instanceof THREE.BufferGeometry) {+ node.geometry.computeBoundingBox();+ if (node.geometry.boundingBox) {+ box = transformedBox(+ node.geometry.boundingBox,+ rootInverse.clone().multiply(node.matrixWorld),+ );+ }+ } else if (roles.length > 0) {+ // Non-rendered semantic marker groups use their ordinary transform/scale+ // as a one-meter local prism, matching the architecture clearance contract.+ box = transformedBox(+ new THREE.Box3(new THREE.Vector3(-0.5, -0.5, -0.5), new THREE.Vector3(0.5, 0.5, 0.5)),+ rootInverse.clone().multiply(node.matrixWorld),+ );+ }+ if (box?.isEmpty()) box = undefined;+ result.push({ node, roles, ...(box ? { box } : {}), renderable });+ });+ return result;+}++function descendantOf(node: THREE.Object3D, ancestor: THREE.Object3D): boolean {+ let cursor: THREE.Object3D | null = node;+ while (cursor) {+ if (cursor === ancestor) return true;+ cursor = cursor.parent;+ }+ return false;+}++function boxesOverlap(a: THREE.Box3, b: THREE.Box3, inset = 0): boolean {+ return (+ a.min.x < b.max.x - inset &&+ a.max.x > b.min.x + inset &&+ a.min.y < b.max.y - inset &&+ a.max.y > b.min.y + inset &&+ a.min.z < b.max.z - inset &&+ a.max.z > b.min.z + inset+ );+}++function motionAssemblies(parts: readonly LocalPart[]): PropMotionAssembly[] {+ const values = new Map<string, PropMotionAssembly>();+ const get = (kind: PropMotionKind, id: string): PropMotionAssembly => {+ const key = `${kind}:${id}`;+ let value = values.get(key);+ if (!value) {+ value = { kind, id };+ values.set(key, value);+ }+ return value;+ };+ for (const part of parts) {+ for (const role of part.roles) {+ const pivot = /^prop\.pivot\.(hinge|slider|spinner)\.([^.]+)$/.exec(role);+ if (pivot) get(pivot[1] as PropMotionKind, pivot[2]!).pivot = part;+ const moving = /^prop\.motion\.(hinge|slider|spinner)\.([^.]+)$/.exec(role);+ if (moving) get(moving[1] as PropMotionKind, moving[2]!).moving = part;+ const clearance = /^prop\.clearance\.(?:hinge\.|slider\.|spinner\.)?([^.]+)$/.exec(role);+ if (clearance) {+ const direct = Array.from(values.values()).find((value) => value.id === clearance[1]);+ if (direct) direct.clearance = part;+ }+ }+ }+ // A clearance role may be encountered before its pivot/moving role.+ for (const part of parts) {+ for (const role of part.roles) {+ const match = /^prop\.clearance\.(?:(hinge|slider|spinner)\.)?([^.]+)$/.exec(role);+ if (!match) continue;+ if (match[1]) get(match[1] as PropMotionKind, match[2]!).clearance = part;+ else {+ const candidates = Array.from(values.values()).filter((value) => value.id === match[2]);+ if (candidates.length === 1) candidates[0]!.clearance = part;+ }+ }+ }+ return Array.from(values.values()).sort((a, b) =>+ `${a.kind}:${a.id}`.localeCompare(`${b.kind}:${b.id}`),+ );+}++function hasMotionAxis(part: LocalPart): boolean {+ const frames = readSemanticMetadataV1(part.node)?.frames ?? [];+ return frames.some((frame) => /^(?:prop\.)?(?:motion-)?axis\.[+-]?[xyz]$/.test(frame.id));+}++function usesExplicitLegacyProfile(context: QaContext): boolean {+ return (+ context.intent.qaProfile === 'prop.legacy' || context.intent.qaProfile === 'prop.legacy-control'+ );+}++function allowedClearanceContactRoles(assembly: PropMotionAssembly): ReadonlySet<string> {+ const result = new Set<string>();+ for (const part of [assembly.pivot, assembly.clearance]) {+ const metadata = part ? readSemanticMetadataV1(part.node) : undefined;+ for (const relationship of metadata?.relationships ?? []) {+ if (+ relationship.targetType === 'role' &&+ /^(?:mountedTo|allowsContact|allowsClearanceContact)$/.test(relationship.kind) &&+ /^prop\.articulation\.support\.[^.]+$/.test(relationship.target)+ ) {+ result.add(relationship.target);+ }+ }+ }+ return result;+}++function legacyArticulationEvidence(context: QaContext, root: THREE.Object3D): boolean {+ const joints: string[] = [];+ root.traverse((node) => {+ if (/^(?:Joint|Pivot)[_.-]/i.test(node.name)) joints.push(node.name);+ });+ if (joints.length === 0) return false;+ const clips = (context.clips ?? []).filter(+ (clip): clip is THREE.AnimationClip => clip instanceof THREE.AnimationClip,+ );+ if ((context.intent.animation?.clips.length ?? 0) === 0 && clips.length === 0) return true;+ const targets = new Set(+ clips.flatMap((clip) => clip.tracks.map((track) => track.name.split('.')[0] ?? '')),+ );+ return joints.some((joint) => targets.has(joint));+}++/**+ * Exact articulated-prop contract. Canonical Joint_/Pivot_ names are accepted+ * only under an explicit legacy QA profile; names never bypass new-output+ * semantics. Geometry inference never becomes a blocker.+ */+export function evaluatePropArticulationQa(context: QaContext): readonly QaFinding[] {+ if (+ context.intent.category !== 'prop' ||+ !context.intent.capabilities.includes('articulated') ||+ !(context.scene instanceof THREE.Object3D)+ ) {+ return [];+ }+ const root = context.scene;+ const parts = collectParts(root);+ const assemblies = motionAssemblies(parts);+ if (assemblies.length === 0) {+ if (usesExplicitLegacyProfile(context) && legacyArticulationEvidence(context, root)) return [];+ return [+ finding(context, {+ code: 'PROP_ARTICULATION_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message:+ 'articulated=true requires a semantic hinge, slider, or spinner assembly with a real pivot and moving subtree.',+ affected: { node: root.name || 'prop-root' },+ measurement: { name: 'motionAssemblyCount', actual: 0, expected: '>=1', threshold: 1 },+ viewHints: ['front', 'right', 'top'],+ repairText:+ 'Create prop.pivot.<hinge|slider|spinner>.<id>, parent only prop.motion.<kind>.<id> beneath it, and add an axis frame plus prop.clearance.<id>.',+ }),+ ];+ }++ const findings: QaFinding[] = [];+ for (const assembly of assemblies) {+ const label = `${assembly.kind}.${assembly.id}`;+ if (!assembly.pivot) {+ findings.push(+ finding(context, {+ code: 'PROP_ARTICULATION_PIVOT_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Motion assembly ${label} has no semantic pivot.`,+ affected: { node: assembly.moving?.node.name || label },+ measurement: { name: 'pivotCount', actual: 0, expected: 1, threshold: 1 },+ viewHints: ['right', 'top'],+ repairText: `Add prop.pivot.${label} at the physical hinge/rail/axle origin.`,+ }),+ );+ continue;+ }+ if (!hasMotionAxis(assembly.pivot)) {+ findings.push(+ finding(context, {+ code: 'PROP_ARTICULATION_AXIS_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Motion pivot ${label} has no declared local axis frame.`,+ affected: {+ node: assembly.pivot.node.name || label,+ nodePath: nodePath(root, assembly.pivot.node),+ },+ measurement: { name: 'motionAxisFrameCount', actual: 0, expected: 1, threshold: 1 },+ viewHints: ['right', 'top'],+ repairText: `Add a normalized axis.+x, axis.+y, or axis.+z frame to prop.pivot.${label}.`,+ }),+ );+ }+ if (!assembly.moving || !descendantOf(assembly.moving.node, assembly.pivot.node)) {+ findings.push(+ finding(context, {+ code: 'PROP_ARTICULATION_SUBTREE_INVALID',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Motion assembly ${label} does not own exactly its declared moving subtree beneath the pivot.`,+ affected: {+ node: assembly.moving?.node.name || assembly.pivot.node.name || label,+ nodePath: assembly.moving ? nodePath(root, assembly.moving.node) : undefined,+ },+ measurement: {+ name: 'movingSubtreeParentedToPivot',+ actual: assembly.moving+ ? descendantOf(assembly.moving.node, assembly.pivot.node)+ : false,+ expected: true,+ },+ viewHints: ['front', 'right'],+ repairText: `Parent only prop.motion.${label} beneath prop.pivot.${label}; keep the static body outside that subtree.`,+ }),+ );+ }+ if (!assembly.clearance?.box) {+ findings.push(+ finding(context, {+ code: 'PROP_ARTICULATION_CLEARANCE_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Motion assembly ${label} has no measurable semantic sweep/clearance prism.`,+ affected: { node: assembly.pivot.node.name || label },+ measurement: { name: 'clearanceMarkerCount', actual: 0, expected: 1, threshold: 1 },+ viewHints: ['front', 'right', 'top'],+ repairText: `Add a non-rendered scaled prop.clearance.${label} marker covering the requested motion sweep.`,+ }),+ );+ continue;+ }+ const allowedStationaryRoles = allowedClearanceContactRoles(assembly);+ const blocker = parts.find(+ (part) =>+ part.renderable &&+ part.box &&+ !descendantOf(part.node, assembly.pivot!.node) &&+ !part.roles.some((role) => allowedStationaryRoles.has(role)) &&+ boxesOverlap(part.box, assembly.clearance!.box!, CLEARANCE_TOLERANCE_METERS),+ );+ if (blocker) {+ findings.push(+ finding(context, {+ code: 'PROP_ARTICULATION_CLEARANCE_BLOCKED',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Motion sweep ${label} is blocked by ${blocker.node.name || 'an unnamed mesh'}.`,+ affected: {+ node: blocker.node.name || 'prop-motion-blocker',+ nodePath: nodePath(root, blocker.node),+ },+ measurement: {+ name: 'motionClearanceBlockerCount',+ actual: 1,+ expected: 0,+ threshold: 0,+ },+ viewHints: ['front', 'right', 'top'],+ repairText: `Remove only the reported blocker from prop.clearance.${label}; do not move unrelated geometry.`,+ }),+ );+ }+ }+ return findings;+}++function rolePart(parts: readonly LocalPart[], expression: RegExp): LocalPart | undefined {+ return parts.find((part) => part.roles.some((role) => expression.test(role)));+}++function interiorUsable(box: THREE.Box3): boolean {+ const size = box.getSize(new THREE.Vector3());+ return size.x >= 0.08 && size.y >= 0.08 && size.z >= 0.08;+}++/** Exact negative-space checks activate only for authored semantic container markers. */+export function evaluatePropContainerQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'prop' || !(context.scene instanceof THREE.Object3D)) return [];+ const explicitlyOpen = context.intent.capabilities.includes('openable');+ const explicitContainment = /^(?:open-)?(?:container|chest|case|box)$/i.test(+ context.intent.subtype ?? '',+ );+ if (!explicitlyOpen && !explicitContainment) return [];+ const root = context.scene;+ const parts = collectParts(root);+ const interior = rolePart(parts, /^prop\.container\.interior(?:\.|$)/);+ const opening = rolePart(parts, /^prop\.container\.opening(?:\.|$)/);+ const hasSemanticContainerEvidence = Boolean(interior || opening);++ if (!hasSemanticContainerEvidence) {+ // Preserve the W5 canonical-name control while keeping fallback narrow: a+ // jointed lid is evidence of an opening, but is never used to hard-judge+ // the invisible interior volume.+ const names: string[] = [];+ root.traverse((node) => names.push(node.name));+ if (+ usesExplicitLegacyProfile(context) &&+ names.some((name) => /^(?:Joint|Pivot)[_.-].*(?:lid|door|hatch)/i.test(name)) &&+ names.some((name) => /(?:Mesh[_.-])?(?:lid|door|hatch)/i.test(name))+ ) {+ return [];+ }+ if (!explicitlyOpen) return [];+ return [+ finding(context, {+ code: 'PROP_CONTAINER_OPENING_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: 'openable=true has no semantic opening/interior markers or canonical jointed lid.',+ affected: { node: root.name || 'prop-root' },+ measurement: {+ name: 'containerOpeningEvidenceCount',+ actual: 0,+ expected: '>=1',+ threshold: 1,+ },+ viewHints: ['front', 'right', 'top'],+ repairText:+ 'Author distinct prop.container.opening.main and prop.container.interior.main clearance markers; do not fill the interior with a solid mesh.',+ }),+ ];+ }++ const findings: QaFinding[] = [];+ if (!interior?.box) {+ findings.push(+ finding(context, {+ code: 'PROP_CONTAINER_INTERIOR_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: 'The semantic container profile has no measurable interior negative-space prism.',+ affected: { node: root.name || 'prop-root' },+ measurement: { name: 'containerInteriorMarkerCount', actual: 0, expected: 1, threshold: 1 },+ viewHints: ['front', 'top'],+ repairText:+ 'Add a non-rendered scaled prop.container.interior.main marker inside the shell.',+ }),+ );+ } else if (!interiorUsable(interior.box)) {+ const size = interior.box.getSize(new THREE.Vector3());+ findings.push(+ finding(context, {+ code: 'PROP_CONTAINER_INTERIOR_UNUSABLE',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: 'The declared container interior has no usable three-dimensional negative space.',+ affected: {+ node: interior.node.name || 'container-interior',+ nodePath: nodePath(root, interior.node),+ },+ measurement: {+ name: 'minimumInteriorExtent',+ actual: stable(Math.min(size.x, size.y, size.z)),+ expected: '>=0.08',+ threshold: 0.08,+ unit: 'm',+ },+ viewHints: ['front', 'top'],+ repairText:+ 'Enlarge the interior marker and remove solid filler so all three clear extents are at least 0.08 m.',+ }),+ );+ }+ if (!opening?.box) {+ findings.push(+ finding(context, {+ code: 'PROP_CONTAINER_OPENING_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: 'The semantic container profile has no measurable opening into its interior.',+ affected: { node: root.name || 'prop-root' },+ measurement: { name: 'containerOpeningMarkerCount', actual: 0, expected: 1, threshold: 1 },+ viewHints: ['front', 'top'],+ repairText:+ 'Add a non-rendered scaled prop.container.opening.main marker connecting outside to the interior.',+ }),+ );+ } else {+ const blocker = parts.find(+ (part) =>+ part.renderable &&+ part.box &&+ !part.roles.some(+ (role) =>+ role.startsWith('prop.container.shell') ||+ role.startsWith('prop.container.lid') ||+ role.startsWith('prop.motion.'),+ ) &&+ boxesOverlap(part.box, opening.box!, CLEARANCE_TOLERANCE_METERS),+ );+ if (blocker) {+ findings.push(+ finding(context, {+ code: 'PROP_CONTAINER_OPENING_BLOCKED',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `Container opening is blocked by ${blocker.node.name || 'an unnamed solid filler'}.`,+ affected: {+ node: blocker.node.name || 'container-blocker',+ nodePath: nodePath(root, blocker.node),+ },+ measurement: {+ name: 'containerOpeningBlockerCount',+ actual: 1,+ expected: 0,+ threshold: 0,+ },+ viewHints: ['front', 'top'],+ repairText:+ 'Remove or split only the reported filler so the opening connects to the interior negative space.',+ }),+ );+ }+ }+ return findings;+}++interface CircularMember {+ part: LocalPart;+ angle: number;+ center: THREE.Vector3;+ horizontalDirection?: THREE.Vector3;+}++function horizontalDirection(part: LocalPart, root: THREE.Object3D): THREE.Vector3 | undefined {+ if (!(part.node instanceof THREE.Mesh) || !(part.node.geometry instanceof THREE.BufferGeometry)) {+ return undefined;+ }+ part.node.geometry.computeBoundingBox();+ const box = part.node.geometry.boundingBox;+ if (!box) return undefined;+ const size = box.getSize(new THREE.Vector3());+ const axis = size.x >= size.z ? new THREE.Vector3(1, 0, 0) : new THREE.Vector3(0, 0, 1);+ root.updateWorldMatrix(true, true);+ const rootQuaternion = root.getWorldQuaternion(new THREE.Quaternion()).invert();+ return axis+ .applyQuaternion(part.node.getWorldQuaternion(new THREE.Quaternion()))+ .applyQuaternion(rootQuaternion)+ .setY(0)+ .normalize();+}++/** Likely circular-assembly defects remain advisory until human calibration. */+export function evaluatePropCircularAssemblyQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'prop' || !(context.scene instanceof THREE.Object3D)) return [];+ const root = context.scene;+ const parts = collectParts(root);+ const tagged = parts.some((part) =>+ part.roles.some(+ (role) => role === 'prop.circular.assembly' || role.startsWith('prop.circular.member.'),+ ),+ );+ const namedProfile = /(?:barrel|drum)/i.test(context.intent.subtype ?? '');+ if (!tagged && !namedProfile) return [];+ const memberParts = parts.filter(+ (part) =>+ part.box &&+ (part.roles.some((role) => role.startsWith('prop.circular.member.')) ||+ (namedProfile && /(?:stave|ring[_.-]?segment)/i.test(part.node.name))),+ );+ if (memberParts.length < 3) return [];+ const centers = memberParts.map((part) => part.box!.getCenter(new THREE.Vector3()));+ const ringCenter = centers+ .reduce((sum, center) => sum.add(center), new THREE.Vector3())+ .multiplyScalar(1 / centers.length);+ const members: CircularMember[] = memberParts.map((part, index) => {+ const center = centers[index]!;+ return {+ part,+ center,+ angle: Math.atan2(center.z - ringCenter.z, center.x - ringCenter.x),+ horizontalDirection: horizontalDirection(part, root),+ };+ });+ members.sort((a, b) => a.angle - b.angle);+ const gaps = members.map((member, index) => {+ const next = members[(index + 1) % members.length]!;+ return (next.angle - member.angle + Math.PI * 2) % (Math.PI * 2);+ });+ const expectedGap = (Math.PI * 2) / members.length;+ const maximumGap = Math.max(...gaps);+ const findings: QaFinding[] = [];+ if (maximumGap > Math.max(Math.PI / 3, expectedGap * 1.5)) {+ findings.push(+ finding(context, {+ code: 'PROP_CIRCULAR_RING_INCOMPLETE',+ disposition: 'warn',+ dimension: 'visualQuality',+ message: `Circular assembly has a likely missing sector of ${((maximumGap * 180) / Math.PI).toFixed(2)} degrees.`,+ affected: { node: root.name || 'prop-root' },+ measurement: {+ name: 'maximumAngularGap',+ actual: stable((maximumGap * 180) / Math.PI),+ expected: `<=${stable(Math.max(60, (expectedGap * 1.5 * 180) / Math.PI))}`,+ unit: 'deg',+ },+ viewHints: ['top', 'three-quarter'],+ }),+ );+ }+ const expectedOrientation = parts.some((part) =>+ part.roles.includes('prop.circular.expected.radial'),+ )+ ? 'radial'+ : 'tangent';+ const wrong = members.filter((member) => {+ if (!member.horizontalDirection) return false;+ const radial = member.center.clone().sub(ringCenter).setY(0).normalize();+ const tangent = new THREE.Vector3(-radial.z, 0, radial.x);+ const radialScore = Math.abs(member.horizontalDirection.dot(radial));+ const tangentScore = Math.abs(member.horizontalDirection.dot(tangent));+ return expectedOrientation === 'tangent'+ ? tangentScore + 0.1 < radialScore+ : radialScore + 0.1 < tangentScore;+ });+ if (wrong.length > 0) {+ findings.push(+ finding(context, {+ code: 'PROP_CIRCULAR_MEMBER_ORIENTATION',+ disposition: 'warn',+ dimension: 'visualQuality',+ message: `${wrong.length} circular members appear ${expectedOrientation === 'tangent' ? 'radial' : 'tangent'} instead of ${expectedOrientation}.`,+ affected: {+ node: wrong[0]!.part.node.name || 'circular-member',+ nodePath: nodePath(root, wrong[0]!.part.node),+ },+ measurement: {+ name: 'misorientedCircularMemberCount',+ actual: wrong.length,+ expected: 0,+ threshold: 0,+ },+ viewHints: ['top', 'three-quarter'],+ }),+ );+ }+ return findings;+}++/** Scale, placement pivot, and grounding evidence is advisory by policy. */+export function evaluatePropScalePivotQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'prop' || !(context.scene instanceof THREE.Object3D)) return [];+ const root = context.scene;+ const parts = collectParts(root);+ const renderable = parts.filter((part) => part.renderable && part.box);+ if (renderable.length === 0) return [];+ const bounds = renderable.reduce((box, part) => box.union(part.box!), new THREE.Box3());+ const size = bounds.getSize(new THREE.Vector3());+ const findings: QaFinding[] = [];+ for (const axis of ['x', 'y', 'z'] as const) {+ const expected = context.intent.bounds?.[axis];+ if (expected === undefined) continue;+ const actual = size[axis];+ const tolerance = Math.max(0.05, expected * 0.2);+ if (Math.abs(actual - expected) <= tolerance) continue;+ findings.push(+ finding(context, {+ code: 'PROP_SCALE_BOUNDS_MISMATCH',+ disposition: 'warn',+ dimension: 'promptAlignment',+ message: `Prop ${axis.toUpperCase()} extent is ${actual.toFixed(4)} m, outside the declared ${expected.toFixed(4)} m scale band.`,+ affected: { node: root.name || 'prop-root', attribute: `bounds.${axis}` },+ measurement: {+ name: `bounds.${axis}`,+ actual: stable(actual),+ expected: stable(expected),+ threshold: stable(tolerance),+ unit: 'm',+ },+ viewHints: ['front', 'right', 'top'],+ }),+ );+ }+ if (context.intent.capabilities.includes('grounded')) {+ if (Math.abs(bounds.min.y) > GROUND_TOLERANCE_METERS) {+ findings.push(+ finding(context, {+ code: 'PROP_GROUND_MISMATCH',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `Grounded prop base is ${Math.abs(bounds.min.y).toFixed(6)} m ${bounds.min.y > 0 ? 'above' : 'below'} asset-local Y=0.`,+ affected: { node: root.name || 'prop-root' },+ measurement: {+ name: 'minimumY',+ actual: stable(bounds.min.y),+ expected: 0,+ threshold: GROUND_TOLERANCE_METERS,+ unit: 'm',+ },+ viewHints: ['right', 'three-quarter'],+ }),+ );+ }+ }+ const placement = parts.find((part) => part.roles.includes('prop.pivot.placement'));+ if (placement) {+ const point = placement.node.getWorldPosition(new THREE.Vector3());+ point.applyMatrix4(root.matrixWorld.clone().invert());+ const horizontalOutside =+ point.x < bounds.min.x - GROUND_TOLERANCE_METERS ||+ point.x > bounds.max.x + GROUND_TOLERANCE_METERS ||+ point.z < bounds.min.z - GROUND_TOLERANCE_METERS ||+ point.z > bounds.max.z + GROUND_TOLERANCE_METERS;+ const verticalDelta = Math.abs(point.y - bounds.min.y);+ if (horizontalOutside || verticalDelta > GROUND_TOLERANCE_METERS) {+ findings.push(+ finding(context, {+ code: 'PROP_PLACEMENT_PIVOT_OFF_BASE',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: 'Declared placement pivot is not on the prop support base.',+ affected: {+ node: placement.node.name || 'placement-pivot',+ nodePath: nodePath(root, placement.node),+ },+ measurement: {+ name: 'placementPivotBaseDelta',+ actual: stable(verticalDelta),+ expected: 0,+ threshold: GROUND_TOLERANCE_METERS,+ unit: 'm',+ },+ viewHints: ['right', 'top'],+ }),+ );+ }+ }+ return findings;+}++export const PROP_EXACT_QA_RULE: QaRule = Object.freeze({+ id: 'PROP_CAPABILITY_EXACT_PROFILE',+ profile: PROFILE,+ scope: { kind: 'category' as const, category: 'prop' as const },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'prop-capability-v1',+ 'src/qa/prop.test.ts',+ 'a152104990fa6b92eea3c201ce39497a5d165ee19080a29e42b96ebe450d936c',+ ),+ defaultMode: 'enforce',+ evaluate: (context: QaContext) => [+ ...evaluatePropArticulationQa(context),+ ...evaluatePropContainerQa(context),+ ],+});++export const PROP_ADVISORY_QA_RULE: QaRule = Object.freeze({+ id: 'PROP_ADVISORY_PROFILE',+ profile: 'prop.advisory',+ scope: { kind: 'category' as const, category: 'prop' as const },+ ruleClass: 'heuristic',+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: 'observe',+ evaluate: (context: QaContext) => [+ ...evaluatePropCircularAssemblyQa(context),+ ...evaluatePropScalePivotQa(context),+ ],+});++export const PROP_QA_RULES: readonly QaRule[] = [+ PROP_EXACT_QA_RULE,+ PROP_ADVISORY_QA_RULE,+] as const;diff --git a/src/qa/registry.test.ts b/src/qa/registry.test.tsnew file mode 100644index 00000000..da0c0169--- /dev/null+++ b/src/qa/registry.test.ts@@ -0,0 +1,731 @@+import { describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';++import { createAssetIntentV1 } from '../contracts';+import {+ calibrationReportEvidenceSha256,+ conformancePromotionAuthorization,+ QaRegistry,+ QA_026_CALIBRATION_THRESHOLD_ID,+ QA_026_CALIBRATION_THRESHOLD_SHA256,+ QA_026_HELD_OUT_SET_SHA256,+ QA_026_HELD_OUT_SET_VERSION,+ QA_026_REVIEW_AUTHORITY_KEY_ID,+ QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256,+ QA_026_REVIEW_AUTHORITY_SCHEME,+ type QaCalibrationPromotionAuthorization,+ type QaCalibrationReportEvidenceV1,+ type QaRule,+ type QaRuleOwner,+} from './registry';+import { DETERMINISTIC_QA_REGISTRY } from './run';+import {+ createAssetQaReportV1,+ createLegacyUnassessedQaReportV1,+ isQaFinding,+ type QaFinding,+} from './types';++const finding = (code: string, disposition: QaFinding['disposition'] = 'block'): QaFinding => ({+ code,+ disposition,+ dimension: 'categoryReadiness',+ profile: 'test',+ message: code,+});++const TEST_EVIDENCE_SHA = 'a'.repeat(64);+const TEST_OWNER: QaRuleOwner = { id: 'qa-test-owner', authority: 'named' };++const rule = (overrides: Partial<QaRule> & Pick<QaRule, 'id' | 'scope'>): QaRule => ({+ profile: 'test',+ ruleClass: 'exact',+ owner: TEST_OWNER,+ promotion: conformancePromotionAuthorization(+ 'qa-test-fixtures-v1',+ 'src/qa/registry.test.ts',+ TEST_EVIDENCE_SHA,+ TEST_OWNER,+ ),+ defaultMode: 'enforce',+ evaluate: () => [finding(overrides.id)],+ ...overrides,+});++interface CalibrationOptions {+ source?: QaCalibrationReportEvidenceV1['source'];+ authorizedMode?: QaCalibrationPromotionAuthorization['authorizedMode'];+ report?: Partial<QaCalibrationReportEvidenceV1>;+ authorization?: Partial<QaCalibrationPromotionAuthorization>;+}++function calibrationReport(+ ruleCode: string,+ options: CalibrationOptions = {},+): QaCalibrationReportEvidenceV1 {+ const authorizedMode = options.authorizedMode ?? 'warn';+ const source = options.source ?? 'deterministic-heuristic';+ const enforce = authorizedMode === 'enforce';+ const validExamples = enforce ? 30 : 10;+ const defectiveExamples = enforce ? 30 : 10;+ const truePositive = enforce ? 27 : 9;+ const falsePositive = enforce ? 0 : 1;+ const trueNegative = validExamples - falsePositive;+ const falseNegative = defectiveExamples - truePositive;+ return {+ schemaVersion: 1,+ reportId: `qa-026:${ruleCode.toLowerCase()}:v1`,+ thresholdId: QA_026_CALIBRATION_THRESHOLD_ID,+ thresholdSha256: QA_026_CALIBRATION_THRESHOLD_SHA256,+ heldOutSetVersion: QA_026_HELD_OUT_SET_VERSION,+ heldOutSetSha256: QA_026_HELD_OUT_SET_SHA256,+ reviewAuthorityScheme: QA_026_REVIEW_AUTHORITY_SCHEME,+ reviewAuthorityKeyId: QA_026_REVIEW_AUTHORITY_KEY_ID,+ reviewAuthorityPublicKeySha256: QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256,+ ruleCode,+ source,+ generatedAt: '2026-07-09T12:00:00.000Z',+ labeledCases: validExamples + defectiveExamples,+ evaluatedCases: validExamples + defectiveExamples,+ insufficientEvidenceCases: 0,+ humanDisagreementCases: 0,+ validExamples,+ defectiveExamples,+ truePositive,+ falsePositive,+ trueNegative,+ falseNegative,+ precision: enforce ? 1 : 0.9,+ recall: 0.9,+ meanConfidence: source === 'vlm' ? 0.9 : null,+ styles: enforce ? 3 : 2,+ falseBlocks: 0,+ ...options.report,+ };+}++function calibration(+ owner: QaRuleOwner,+ ruleCode: string,+ options: CalibrationOptions = {},+): QaCalibrationPromotionAuthorization {+ const report = calibrationReport(ruleCode, options);+ return {+ basis: 'qa-026-calibration',+ authorizedMode: options.authorizedMode ?? 'warn',+ packetId: report.reportId,+ evidenceSha256: calibrationReportEvidenceSha256(report),+ frozenAt: '2026-07-09T13:00:00.000Z',+ authorizedBy: owner.id,+ report,+ ...options.authorization,+ };+}++describe('QaRegistry', () => {+ const context = {+ intent: createAssetIntentV1({+ category: 'vehicle',+ subtype: 'wheeled',+ capabilities: ['driveable', 'grounded'],+ }),+ };++ test('composes universal, category, subtype, and capability rules', () => {+ const registry = new QaRegistry([+ rule({ id: 'TEST_UNIVERSAL', scope: { kind: 'universal' } }),+ rule({ id: 'TEST_CATEGORY', scope: { kind: 'category', category: 'vehicle' } }),+ rule({+ id: 'TEST_SUBTYPE',+ scope: { kind: 'subtype', category: 'vehicle', subtype: 'wheeled' },+ }),+ rule({ id: 'TEST_CAPABILITY', scope: { kind: 'capability', capability: 'driveable' } }),+ rule({ id: 'TEST_WRONG_CATEGORY', scope: { kind: 'category', category: 'character' } }),+ ]);++ expect(registry.run(context).executedRules).toEqual([+ 'TEST_UNIVERSAL',+ 'TEST_CATEGORY',+ 'TEST_SUBTYPE',+ 'TEST_CAPABILITY',+ ]);+ });++ test('applies off, observe, warn, and enforce deterministically', () => {+ const registry = new QaRegistry([+ rule({ id: 'TEST_OFF', scope: { kind: 'universal' } }),+ rule({ id: 'TEST_OBSERVE', scope: { kind: 'universal' } }),+ rule({ id: 'TEST_WARN', scope: { kind: 'universal' } }),+ rule({ id: 'TEST_ENFORCE', scope: { kind: 'universal' } }),+ ]);+ const result = registry.run(context, {+ byRule: {+ TEST_OFF: 'off',+ TEST_OBSERVE: 'observe',+ TEST_WARN: 'warn',+ TEST_ENFORCE: 'enforce',+ },+ });++ expect(result.skippedRules).toEqual(['TEST_OFF']);+ expect(result.findings.map((item) => [item.code, item.disposition])).toEqual([+ ['TEST_OBSERVE', 'observe'],+ ['TEST_WARN', 'warn'],+ ['TEST_ENFORCE', 'block'],+ ]);+ expect(result.decisions.map(({ ruleId, mode }) => [ruleId, mode])).toEqual([+ ['TEST_OFF', 'off'],+ ['TEST_OBSERVE', 'observe'],+ ['TEST_WARN', 'warn'],+ ['TEST_ENFORCE', 'enforce'],+ ]);+ });++ test('requires a stable named or delegated owner on every rule', () => {+ expect(+ () =>+ new QaRegistry([+ {+ ...rule({ id: 'TEST_MISSING_OWNER', scope: { kind: 'universal' } }),+ owner: undefined,+ } as unknown as QaRule,+ ]),+ ).toThrow('must name a stable rule owner');+ expect(+ () =>+ new QaRegistry([+ rule({+ id: 'TEST_UNKNOWN_OWNER',+ scope: { kind: 'universal' },+ owner: { id: 'unknown', authority: 'named' },+ }),+ ]),+ ).toThrow('must name a stable rule owner');+ });++ test('allows exact warn/enforce only with owner-authorized conformance evidence', () => {+ expect(+ () =>+ new QaRegistry([+ rule({+ id: 'TEST_EXACT_WITHOUT_FIXTURES',+ scope: { kind: 'universal' },+ promotion: undefined,+ }),+ ]),+ ).toThrow('without frozen promotion evidence');+ expect(+ () =>+ new QaRegistry([+ rule({+ id: 'TEST_EXACT_WRONG_AUTHORIZER',+ scope: { kind: 'universal' },+ promotion: {+ ...conformancePromotionAuthorization(+ 'qa-test-fixtures-v1',+ 'src/qa/registry.test.ts',+ TEST_EVIDENCE_SHA,+ TEST_OWNER,+ ),+ authorizedBy: 'someone-else',+ },+ }),+ ]),+ ).toThrow('authorized by its named rule owner');+ });++ test('keeps an uncalibrated heuristic observe-only, then permits owner-approved QA-026 warn', () => {+ const observeOnly = rule({+ id: 'TEST_HEURISTIC',+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ defaultMode: 'observe',+ promotion: undefined,+ });+ const registry = new QaRegistry([observeOnly]);+ expect(registry.run(context).findings[0]?.disposition).toBe('observe');+ expect(() => registry.run(context, { byRule: { TEST_HEURISTIC: 'warn' } })).toThrow(+ 'without frozen promotion evidence',+ );++ const delegatedOwner: QaRuleOwner = { id: 'qa-delegate:motion', authority: 'delegated' };+ const calibrated = new QaRegistry([+ rule({+ id: 'TEST_CALIBRATED_HEURISTIC',+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner: delegatedOwner,+ defaultMode: 'warn',+ promotion: calibration(delegatedOwner, 'TEST_CALIBRATED_HEURISTIC'),+ }),+ ]);+ expect(calibrated.run(context).findings[0]?.disposition).toBe('warn');+ expect(() =>+ calibrated.run(context, { byRule: { TEST_CALIBRATED_HEURISTIC: 'enforce' } }),+ ).toThrow('authorizes warn, not enforce');+ });++ test('allows a calibrated VLM warning but never VLM enforcement', () => {+ const owner: QaRuleOwner = { id: 'qa-delegate:vlm', authority: 'delegated' };+ const vlm = rule({+ id: 'TEST_VLM',+ scope: { kind: 'universal' },+ ruleClass: 'vlm',+ owner,+ defaultMode: 'warn',+ promotion: calibration(owner, 'TEST_VLM', { source: 'vlm' }),+ });+ const registry = new QaRegistry([vlm]);+ expect(registry.run(context).findings[0]?.disposition).toBe('warn');+ expect(() => registry.run(context, { byRule: { TEST_VLM: 'enforce' } })).toThrow(+ 'VLM findings are never blockers',+ );+ });++ test('rejects zero-sample calibration and threshold/report identity mismatches', () => {+ const owner: QaRuleOwner = { id: 'qa-delegate:strict', authority: 'delegated' };+ const id = 'TEST_STRICT_CALIBRATION';+ const zeroSample = calibration(owner, id, {+ report: {+ labeledCases: 0,+ evaluatedCases: 0,+ validExamples: 0,+ defectiveExamples: 0,+ truePositive: 0,+ falsePositive: 0,+ trueNegative: 0,+ falseNegative: 0,+ precision: 0,+ recall: 0,+ styles: 0,+ },+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'warn',+ promotion: zeroSample,+ }),+ ]),+ ).toThrow('warn promotion minimums');++ const wrongThreshold = calibration(owner, id, {+ report: {+ thresholdId:+ 'kiln.asset-quality-calibration.thresholds.forged' as typeof QA_026_CALIBRATION_THRESHOLD_ID,+ },+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'warn',+ promotion: wrongThreshold,+ }),+ ]),+ ).toThrow('threshold identity mismatch');++ const packetMismatch = calibration(owner, id, {+ authorization: { packetId: 'qa-026:different-report:v1' },+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'warn',+ promotion: packetMismatch,+ }),+ ]),+ ).toThrow('packet/report identity mismatch');+ });++ test('rejects test and caller-selected review authorities for warn and enforce', () => {+ const owner: QaRuleOwner = { id: 'qa-delegate:authority', authority: 'delegated' };+ const id = 'TEST_REVIEW_AUTHORITY';+ const untrustedAuthorities: Array<{+ label: string;+ report: Partial<QaCalibrationReportEvidenceV1>;+ }> = [+ {+ label: 'test authority',+ report: {+ reviewAuthorityKeyId:+ 'kiln-studio.asset-quality-review.test.v1' as typeof QA_026_REVIEW_AUTHORITY_KEY_ID,+ reviewAuthorityPublicKeySha256: 'b'.repeat(+ 64,+ ) as typeof QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256,+ },+ },+ {+ label: 'caller authority',+ report: {+ reviewAuthorityKeyId:+ 'caller-selected.review-authority.v1' as typeof QA_026_REVIEW_AUTHORITY_KEY_ID,+ reviewAuthorityPublicKeySha256: 'c'.repeat(+ 64,+ ) as typeof QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256,+ },+ },+ ];++ for (const { label, report } of untrustedAuthorities) {+ for (const authorizedMode of ['warn', 'enforce'] as const) {+ const promotion = calibration(owner, id, { authorizedMode, report });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: authorizedMode,+ promotion,+ }),+ ]),+ `${label}/${authorizedMode}`,+ ).toThrow('review authority identity mismatch');+ }+ }++ const wrongScheme = calibration(owner, id, {+ report: {+ reviewAuthorityScheme: 'hmac-sha256' as typeof QA_026_REVIEW_AUTHORITY_SCHEME,+ },+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'warn',+ promotion: wrongScheme,+ }),+ ]),+ ).toThrow('review authority identity mismatch');+ });++ test('binds review authority fields into the report hash and rejects tampering', () => {+ const owner: QaRuleOwner = { id: 'qa-delegate:authority-hash', authority: 'delegated' };+ const id = 'TEST_REVIEW_AUTHORITY_HASH';+ const report = calibrationReport(id);+ const canonicalHash = calibrationReportEvidenceSha256(report);+ const authorityMutations: Array<Partial<QaCalibrationReportEvidenceV1>> = [+ {+ reviewAuthorityScheme: 'other-scheme' as typeof QA_026_REVIEW_AUTHORITY_SCHEME,+ },+ {+ reviewAuthorityKeyId: 'other.key.v1' as typeof QA_026_REVIEW_AUTHORITY_KEY_ID,+ },+ {+ reviewAuthorityPublicKeySha256: 'd'.repeat(+ 64,+ ) as typeof QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256,+ },+ ];+ for (const mutation of authorityMutations) {+ expect(calibrationReportEvidenceSha256({ ...report, ...mutation })).not.toBe(canonicalHash);+ }++ const tamperedAuthority = calibration(owner, id);+ tamperedAuthority.report.reviewAuthorityPublicKeySha256 = 'e'.repeat(+ 64,+ ) as typeof QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256;+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'warn',+ promotion: tamperedAuthority,+ }),+ ]),+ ).toThrow('review authority identity mismatch');++ const tamperedHash = calibration(owner, id, {+ authorization: { evidenceSha256: 'f'.repeat(64) },+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'warn',+ promotion: tamperedHash,+ }),+ ]),+ ).toThrow('report SHA-256 mismatch');+ });++ test('rejects missing held-out identity, bad evidence hashes, and forged metrics', () => {+ const owner: QaRuleOwner = { id: 'qa-delegate:evidence', authority: 'delegated' };+ const id = 'TEST_EVIDENCE_CALIBRATION';+ const missingHeldOut = calibration(owner, id, {+ report: {+ heldOutSetVersion: undefined as unknown as typeof QA_026_HELD_OUT_SET_VERSION,+ },+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'warn',+ promotion: missingHeldOut,+ }),+ ]),+ ).toThrow('held-out set identity mismatch');++ const hashMismatch = calibration(owner, id, {+ authorization: { evidenceSha256: 'f'.repeat(64) },+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'warn',+ promotion: hashMismatch,+ }),+ ]),+ ).toThrow('report SHA-256 mismatch');++ const forgedMetrics = calibration(owner, id, { report: { precision: 0.99 } });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'warn',+ promotion: forgedMetrics,+ }),+ ]),+ ).toThrow('metrics do not match confusion counts');+ });++ test('requires the stronger enforcement bar and rejects false blocks', () => {+ const owner: QaRuleOwner = { id: 'qa-delegate:enforce', authority: 'delegated' };+ const id = 'TEST_ENFORCED_HEURISTIC';+ const excessiveFalseBlocks = calibration(owner, id, {+ authorizedMode: 'enforce',+ report: { falseBlocks: 1 },+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'enforce',+ promotion: excessiveFalseBlocks,+ }),+ ]),+ ).toThrow('enforce promotion minimums');++ const registry = new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'enforce',+ promotion: calibration(owner, id, { authorizedMode: 'enforce' }),+ }),+ ]);+ expect(registry.run(context).findings[0]?.disposition).toBe('block');+ });++ test('requires resolved evidence and calibrated VLM confidence', () => {+ const owner: QaRuleOwner = { id: 'qa-delegate:resolution', authority: 'delegated' };+ const id = 'TEST_RESOLVED_HEURISTIC';+ const unresolved = calibration(owner, id, {+ report: { labeledCases: 21, insufficientEvidenceCases: 1 },+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id,+ scope: { kind: 'universal' },+ ruleClass: 'heuristic',+ owner,+ defaultMode: 'warn',+ promotion: unresolved,+ }),+ ]),+ ).toThrow('unresolved evidence or human disagreement');++ const vlmId = 'TEST_LOW_CONFIDENCE_VLM';+ const lowConfidence = calibration(owner, vlmId, {+ source: 'vlm',+ report: { meanConfidence: 0.5 },+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id: vlmId,+ scope: { kind: 'universal' },+ ruleClass: 'vlm',+ owner,+ defaultMode: 'warn',+ promotion: lowConfidence,+ }),+ ]),+ ).toThrow('confidence is below the warn minimum');++ const vlmEnforce = calibration(owner, vlmId, {+ source: 'vlm',+ authorizedMode: 'enforce',+ });+ expect(+ () =>+ new QaRegistry([+ rule({+ id: vlmId,+ scope: { kind: 'universal' },+ ruleClass: 'vlm',+ owner,+ defaultMode: 'observe',+ promotion: vlmEnforce,+ }),+ ]),+ ).toThrow('permanently capped at warn');+ });++ test('rejects unknown runtime rollout modes before blocker severity can survive', () => {+ const registry = new QaRegistry([+ rule({ id: 'TEST_RUNTIME_MODE', scope: { kind: 'universal' } }),+ ]);+ expect(() =>+ registry.run(context, {+ byRule: { TEST_RUNTIME_MODE: 'not-a-mode' as never },+ }),+ ).toThrow('unsupported rollout mode');+ });++ test('publishes a stable auditable state and owner for every checked-in rule', () => {+ const decisions = DETERMINISTIC_QA_REGISTRY.describePolicy();+ expect(decisions).toHaveLength(24);+ expect(+ decisions+ .filter((item) => item.ruleClass === 'exact')+ .every((item) => item.mode === 'enforce'),+ ).toBe(true);+ expect(+ decisions+ .filter((item) => item.ruleClass !== 'exact')+ .every((item) => item.mode === 'observe'),+ ).toBe(true);+ expect(decisions.every((item) => item.owner.id === 'kiln-engine-maintainers')).toBe(true);+ expect(+ decisions+ .filter((item) => item.ruleClass === 'exact')+ .every((item) => item.promotionBasis === 'conformance'),+ ).toBe(true);+ expect(+ decisions.some(+ (item) => item.ruleClass !== 'exact' && (item.mode === 'warn' || item.mode === 'enforce'),+ ),+ ).toBe(false);+ });++ test('keeps mixed architecture and vehicle advisories outside exact conformance promotion', () => {+ for (const ruleId of ['ARCHITECTURE_ADVISORY_PROFILE', 'VEHICLE_ADVISORY_PROFILE']) {+ const ruleEntry = DETERMINISTIC_QA_REGISTRY.list().find((item) => item.id === ruleId);+ expect(ruleEntry).toMatchObject({ ruleClass: 'heuristic', defaultMode: 'observe' });+ expect(ruleEntry?.promotion).toBeUndefined();+ expect(() =>+ DETERMINISTIC_QA_REGISTRY.describePolicy({ byRule: { [ruleId]: 'warn' } }),+ ).toThrow('without frozen promotion evidence');+ }+ });++ test('pins every checked-in conformance authorization to the actual fixture bytes', async () => {+ for (const rule of DETERMINISTIC_QA_REGISTRY.list()) {+ if (rule.promotion?.basis !== 'conformance') continue;+ const bytes = await Bun.file(rule.promotion.fixturePath).arrayBuffer();+ const actual = createHash('sha256').update(new Uint8Array(bytes)).digest('hex');+ expect(actual, `${rule.id}: ${rule.promotion.fixturePath}`).toBe(+ rule.promotion.evidenceSha256,+ );+ }+ });++ test('rejects unstable or duplicate rule ids', () => {+ expect(() => new QaRegistry([rule({ id: 'bad-id', scope: { kind: 'universal' } })])).toThrow();+ const duplicate = rule({ id: 'TEST_DUPLICATE', scope: { kind: 'universal' } });+ expect(() => new QaRegistry([duplicate, duplicate])).toThrow('Duplicate QA rule id');+ });+});++describe('AssetQaReportV1', () => {+ test('keeps all five dimensions separate and marks unrun dimensions notEvaluated', () => {+ const intent = createAssetIntentV1({ category: 'prop' });+ const report = createAssetQaReportV1(intent, {+ evaluatedDimensions: ['exportIntegrity', 'runtimeCost'],+ findings: [+ {+ code: 'TEST_WARNING',+ disposition: 'warn',+ dimension: 'runtimeCost',+ profile: 'test',+ message: 'cost warning',+ },+ ],+ });++ expect(report.disposition).toBe('warn');+ expect(report.dimensions.exportIntegrity.status).toBe('pass');+ expect(report.dimensions.runtimeCost.status).toBe('warn');+ expect(report.dimensions.promptAlignment.status).toBe('notEvaluated');+ expect(report.dimensions.visualQuality.status).toBe('notEvaluated');+ expect(Object.keys(report.dimensions)).toHaveLength(5);+ });++ test('validates stable structured findings', () => {+ expect(isQaFinding(finding('TEST_STABLE_CODE'))).toBe(true);+ expect(isQaFinding({ ...finding('TEST_STABLE_CODE'), code: 'not-stable' })).toBe(false);+ });++ test('represents historical rows honestly as legacy-unassessed', () => {+ const report = createLegacyUnassessedQaReportV1('prop');+ expect(report.disposition).toBe('legacy-unassessed');+ expect(+ Object.values(report.dimensions).every((dimension) => dimension.status === 'notEvaluated'),+ ).toBe(true);+ });+});diff --git a/src/qa/registry.ts b/src/qa/registry.tsnew file mode 100644index 00000000..a10af48b--- /dev/null+++ b/src/qa/registry.ts@@ -0,0 +1,567 @@+import { createHash } from 'node:crypto';++import type { AssetCapability, AssetCategory } from '../contracts';+import type { QaContext, QaFinding } from './types';++export const QA_RULE_MODES = ['off', 'observe', 'warn', 'enforce'] as const;+export type QaRuleMode = (typeof QA_RULE_MODES)[number];++export const QA_RULE_CLASSES = ['exact', 'heuristic', 'vlm'] as const;+export type QaRuleClass = (typeof QA_RULE_CLASSES)[number];++/** Cross-repo identities frozen by QA-023/026. The exact matrix must keep Studio in lock-step. */+export const QA_026_CALIBRATION_THRESHOLD_ID =+ 'kiln.asset-quality-calibration.thresholds.v1' as const;+export const QA_026_CALIBRATION_THRESHOLD_SHA256 =+ '054ce5088b6b0685bbc0492f8bed0121311cf18920c5697bd6dce66dcb7b2cf9' as const;+export const QA_026_HELD_OUT_SET_VERSION = 'kiln.asset-quality.held-out.v1' as const;+export const QA_026_HELD_OUT_SET_SHA256 =+ '27c17e0e9dbcf22915550b46a94e6afaafe80584f30429e4eb97435163a176bd' as const;+export const QA_026_REVIEW_AUTHORITY_SCHEME = 'ed25519' as const;+export const QA_026_REVIEW_AUTHORITY_KEY_ID = 'kiln-studio.asset-quality-review.prod.v1' as const;+export const QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256 =+ '08791ade50e377dfb3dc6bc1e852419515fbdaadabcd3880770507a2f192a528' as const;++export const QA_026_WARN_PROMOTION_MINIMUMS = Object.freeze({+ evaluatedCases: 20,+ validExamples: 5,+ defectiveExamples: 5,+ precision: 0.9,+ recall: 0.7,+ vlmMeanConfidence: 0.75,+ styles: 1,+} as const);++/** Owner-approved H* enforcement bar from implementation-plan §8. */+export const QA_026_ENFORCE_PROMOTION_MINIMUMS = Object.freeze({+ evaluatedCases: 60,+ validExamples: 30,+ defectiveExamples: 30,+ precision: 0.9,+ recall: 0.9,+ styles: 3,+ falseBlocks: 0,+} as const);++export interface QaRuleOwner {+ /** Stable human/team identity, never a generic value such as "unknown". */+ id: string;+ authority: 'named' | 'delegated';+}++export interface QaConformancePromotionAuthorization {+ basis: 'conformance';+ authorizedMode: 'warn' | 'enforce';+ fixtureSetId: string;+ /** Repository-relative fixture source whose exact bytes produce evidenceSha256. */+ fixturePath: string;+ evidenceSha256: string;+ frozenAt: string;+ authorizedBy: string;+}++export interface QaCalibrationPromotionAuthorization {+ basis: 'qa-026-calibration';+ authorizedMode: 'warn' | 'enforce';+ packetId: string;+ evidenceSha256: string;+ frozenAt: string;+ authorizedBy: string;+ report: QaCalibrationReportEvidenceV1;+}++export interface QaCalibrationReportEvidenceV1 {+ schemaVersion: 1;+ reportId: string;+ thresholdId: typeof QA_026_CALIBRATION_THRESHOLD_ID;+ thresholdSha256: typeof QA_026_CALIBRATION_THRESHOLD_SHA256;+ heldOutSetVersion: typeof QA_026_HELD_OUT_SET_VERSION;+ heldOutSetSha256: typeof QA_026_HELD_OUT_SET_SHA256;+ reviewAuthorityScheme: typeof QA_026_REVIEW_AUTHORITY_SCHEME;+ reviewAuthorityKeyId: typeof QA_026_REVIEW_AUTHORITY_KEY_ID;+ reviewAuthorityPublicKeySha256: typeof QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256;+ ruleCode: string;+ source: 'deterministic-heuristic' | 'vlm';+ generatedAt: string;+ labeledCases: number;+ evaluatedCases: number;+ insufficientEvidenceCases: number;+ humanDisagreementCases: number;+ validExamples: number;+ defectiveExamples: number;+ truePositive: number;+ falsePositive: number;+ trueNegative: number;+ falseNegative: number;+ precision: number;+ recall: number;+ meanConfidence: number | null;+ styles: number;+ falseBlocks: number;+}++function canonicalCalibrationReportEvidence(report: QaCalibrationReportEvidenceV1): string {+ return JSON.stringify({+ schemaVersion: report.schemaVersion,+ reportId: report.reportId,+ thresholdId: report.thresholdId,+ thresholdSha256: report.thresholdSha256,+ heldOutSetVersion: report.heldOutSetVersion,+ heldOutSetSha256: report.heldOutSetSha256,+ reviewAuthorityScheme: report.reviewAuthorityScheme,+ reviewAuthorityKeyId: report.reviewAuthorityKeyId,+ reviewAuthorityPublicKeySha256: report.reviewAuthorityPublicKeySha256,+ ruleCode: report.ruleCode,+ source: report.source,+ generatedAt: report.generatedAt,+ labeledCases: report.labeledCases,+ evaluatedCases: report.evaluatedCases,+ insufficientEvidenceCases: report.insufficientEvidenceCases,+ humanDisagreementCases: report.humanDisagreementCases,+ validExamples: report.validExamples,+ defectiveExamples: report.defectiveExamples,+ truePositive: report.truePositive,+ falsePositive: report.falsePositive,+ trueNegative: report.trueNegative,+ falseNegative: report.falseNegative,+ precision: report.precision,+ recall: report.recall,+ meanConfidence: report.meanConfidence,+ styles: report.styles,+ falseBlocks: report.falseBlocks,+ });+}++export function calibrationReportEvidenceSha256(report: QaCalibrationReportEvidenceV1): string {+ return createHash('sha256').update(canonicalCalibrationReportEvidence(report)).digest('hex');+}++export type QaPromotionAuthorization =+ | QaConformancePromotionAuthorization+ | QaCalibrationPromotionAuthorization;++/** Checked-in owner for engine conformance rules. Delegated rules must name their delegate instead. */+export const KILN_ENGINE_QA_OWNER: QaRuleOwner = Object.freeze({+ id: 'kiln-engine-maintainers',+ authority: 'named',+});++export function conformancePromotionAuthorization(+ fixtureSetId: string,+ fixturePath: string,+ evidenceSha256: string,+ owner: QaRuleOwner = KILN_ENGINE_QA_OWNER,+ frozenAt = '2026-07-09T00:00:00.000Z',+ authorizedMode: 'warn' | 'enforce' = 'enforce',+): QaConformancePromotionAuthorization {+ return {+ basis: 'conformance',+ authorizedMode,+ fixtureSetId,+ fixturePath,+ evidenceSha256,+ frozenAt,+ authorizedBy: owner.id,+ };+}++export type QaRuleScope =+ | { kind: 'universal' }+ | { kind: 'category'; category: AssetCategory }+ | { kind: 'subtype'; category: AssetCategory; subtype: string }+ | { kind: 'capability'; capability: AssetCapability };++export interface QaRule {+ /** Stable registry identity. Findings may use more specific stable codes. */+ id: string;+ profile: string;+ scope: QaRuleScope;+ ruleClass: QaRuleClass;+ owner: QaRuleOwner;+ /** Required before warn/enforce promotion; exact and calibrated rules use different evidence. */+ promotion?: QaPromotionAuthorization;+ defaultMode: QaRuleMode;+ evaluate(context: QaContext): readonly QaFinding[];+}++export interface QaRulePolicy {+ defaultMode?: QaRuleMode;+ byProfile?: Readonly<Record<string, QaRuleMode>>;+ byRule?: Readonly<Record<string, QaRuleMode>>;+}++export interface QaRegistryResult {+ findings: QaFinding[];+ executedRules: string[];+ skippedRules: string[];+ decisions: QaRulePolicyDecision[];+}++export interface QaRulePolicyDecision {+ ruleId: string;+ profile: string;+ mode: QaRuleMode;+ ruleClass: QaRuleClass;+ owner: QaRuleOwner;+ promotionBasis?: QaPromotionAuthorization['basis'];+ authorizedMode?: QaPromotionAuthorization['authorizedMode'];+ evidenceId?: string;+}++const SHA256_PATTERN = /^[a-f0-9]{64}$/;+const OWNER_ID_PATTERN = /^[a-z0-9][a-z0-9:._/-]*$/;++function evidenceId(promotion: QaPromotionAuthorization): string {+ return promotion.basis === 'conformance' ? promotion.fixtureSetId : promotion.packetId;+}++function assertOwner(owner: QaRuleOwner | undefined, ruleId: string): asserts owner is QaRuleOwner {+ if (!owner || !OWNER_ID_PATTERN.test(owner.id) || owner.id === 'unknown') {+ throw new TypeError(`QA rule ${ruleId} must name a stable rule owner`);+ }+ if (owner.authority !== 'named' && owner.authority !== 'delegated') {+ throw new TypeError(`QA rule ${ruleId} has an invalid owner authority`);+ }+}++function assertNonNegativeInteger(value: number, path: string, ruleId: string): void {+ if (!Number.isInteger(value) || value < 0) {+ throw new TypeError(`QA rule ${ruleId} calibration ${path} must be a non-negative integer`);+ }+}++const roundedRatio = (numerator: number, denominator: number): number =>+ Math.round((numerator / denominator) * 1_000_000) / 1_000_000;++function assertCalibrationPromotion(+ rule: QaRule,+ promotion: QaCalibrationPromotionAuthorization,+): void {+ const report = promotion.report;+ if (report.schemaVersion !== 1) {+ throw new TypeError(`QA rule ${rule.id} calibration report schemaVersion must be 1`);+ }+ if (!OWNER_ID_PATTERN.test(report.reportId) || promotion.packetId !== report.reportId) {+ throw new TypeError(`QA rule ${rule.id} calibration packet/report identity mismatch`);+ }+ if (+ report.thresholdId !== QA_026_CALIBRATION_THRESHOLD_ID ||+ report.thresholdSha256 !== QA_026_CALIBRATION_THRESHOLD_SHA256+ ) {+ throw new TypeError(`QA rule ${rule.id} calibration threshold identity mismatch`);+ }+ if (+ report.heldOutSetVersion !== QA_026_HELD_OUT_SET_VERSION ||+ report.heldOutSetSha256 !== QA_026_HELD_OUT_SET_SHA256+ ) {+ throw new TypeError(`QA rule ${rule.id} calibration held-out set identity mismatch`);+ }+ if (+ report.reviewAuthorityScheme !== QA_026_REVIEW_AUTHORITY_SCHEME ||+ report.reviewAuthorityKeyId !== QA_026_REVIEW_AUTHORITY_KEY_ID ||+ report.reviewAuthorityPublicKeySha256 !== QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256+ ) {+ throw new TypeError(`QA rule ${rule.id} calibration review authority identity mismatch`);+ }+ if (report.ruleCode !== rule.id) {+ throw new TypeError(`QA rule ${rule.id} calibration report targets ${report.ruleCode}`);+ }+ const expectedSource = rule.ruleClass === 'vlm' ? 'vlm' : 'deterministic-heuristic';+ if (report.source !== expectedSource) {+ throw new TypeError(`QA rule ${rule.id} calibration source must be ${expectedSource}`);+ }+ if (!Number.isFinite(Date.parse(report.generatedAt))) {+ throw new TypeError(`QA rule ${rule.id} calibration report generatedAt is invalid`);+ }+ if (Date.parse(promotion.frozenAt) < Date.parse(report.generatedAt)) {+ throw new TypeError(`QA rule ${rule.id} calibration cannot be frozen before its report`);+ }+ const actualReportSha256 = calibrationReportEvidenceSha256(report);+ if (promotion.evidenceSha256 !== actualReportSha256) {+ throw new TypeError(`QA rule ${rule.id} calibration report SHA-256 mismatch`);+ }++ for (const field of [+ 'labeledCases',+ 'evaluatedCases',+ 'insufficientEvidenceCases',+ 'humanDisagreementCases',+ 'validExamples',+ 'defectiveExamples',+ 'truePositive',+ 'falsePositive',+ 'trueNegative',+ 'falseNegative',+ 'styles',+ 'falseBlocks',+ ] as const) {+ assertNonNegativeInteger(report[field], field, rule.id);+ }+ if (+ !Number.isFinite(report.precision) ||+ report.precision < 0 ||+ report.precision > 1 ||+ !Number.isFinite(report.recall) ||+ report.recall < 0 ||+ report.recall > 1+ ) {+ throw new TypeError(`QA rule ${rule.id} calibration precision/recall must be within [0, 1]`);+ }+ if (report.validExamples !== report.trueNegative + report.falsePositive) {+ throw new TypeError(`QA rule ${rule.id} calibration valid-example confusion counts mismatch`);+ }+ if (report.defectiveExamples !== report.truePositive + report.falseNegative) {+ throw new TypeError(+ `QA rule ${rule.id} calibration defective-example confusion counts mismatch`,+ );+ }+ if (report.evaluatedCases !== report.validExamples + report.defectiveExamples) {+ throw new TypeError(`QA rule ${rule.id} calibration evaluated-case count mismatch`);+ }+ if (+ report.labeledCases !==+ report.evaluatedCases + report.insufficientEvidenceCases + report.humanDisagreementCases+ ) {+ throw new TypeError(`QA rule ${rule.id} calibration labeled-case count mismatch`);+ }+ const warn = QA_026_WARN_PROMOTION_MINIMUMS;+ if (+ report.evaluatedCases < warn.evaluatedCases ||+ report.validExamples < warn.validExamples ||+ report.defectiveExamples < warn.defectiveExamples ||+ report.styles < warn.styles+ ) {+ throw new Error(`QA rule ${rule.id} calibration does not meet the warn promotion minimums`);+ }+ const expectedPrecision = roundedRatio(+ report.truePositive,+ report.truePositive + report.falsePositive,+ );+ const expectedRecall = roundedRatio(+ report.truePositive,+ report.truePositive + report.falseNegative,+ );+ if (+ !Number.isFinite(expectedPrecision) ||+ !Number.isFinite(expectedRecall) ||+ report.precision !== expectedPrecision ||+ report.recall !== expectedRecall+ ) {+ throw new TypeError(`QA rule ${rule.id} calibration metrics do not match confusion counts`);+ }+ if (report.insufficientEvidenceCases !== 0 || report.humanDisagreementCases !== 0) {+ throw new Error(`QA rule ${rule.id} calibration has unresolved evidence or human disagreement`);+ }++ if (report.precision < warn.precision || report.recall < warn.recall) {+ throw new Error(`QA rule ${rule.id} calibration does not meet the warn promotion minimums`);+ }+ if (report.source === 'vlm') {+ if (+ report.meanConfidence === null ||+ !Number.isFinite(report.meanConfidence) ||+ report.meanConfidence < warn.vlmMeanConfidence ||+ report.meanConfidence > 1+ ) {+ throw new Error(`QA rule ${rule.id} VLM calibration confidence is below the warn minimum`);+ }+ if (promotion.authorizedMode !== 'warn') {+ throw new Error(`VLM QA rule ${rule.id} promotion is permanently capped at warn`);+ }+ } else if (report.meanConfidence !== null) {+ throw new TypeError(`QA rule ${rule.id} deterministic calibration meanConfidence must be null`);+ }++ if (promotion.authorizedMode === 'warn') {+ if (report.falseBlocks !== 0) {+ throw new Error(`QA rule ${rule.id} warning calibration cannot report false blocks`);+ }+ return;+ }++ const enforce = QA_026_ENFORCE_PROMOTION_MINIMUMS;+ if (+ report.evaluatedCases < enforce.evaluatedCases ||+ report.validExamples < enforce.validExamples ||+ report.defectiveExamples < enforce.defectiveExamples ||+ report.precision < enforce.precision ||+ report.recall < enforce.recall ||+ report.styles < enforce.styles ||+ report.falsePositive !== 0 ||+ report.falseBlocks !== enforce.falseBlocks+ ) {+ throw new Error(`QA rule ${rule.id} calibration does not meet the enforce promotion minimums`);+ }+}++function assertPromotionShape(rule: QaRule, promotion: QaPromotionAuthorization): void {+ if (promotion.authorizedMode !== 'warn' && promotion.authorizedMode !== 'enforce') {+ throw new TypeError(`QA rule ${rule.id} promotion must explicitly authorize warn or enforce`);+ }+ if (!evidenceId(promotion).trim()) {+ throw new TypeError(`QA rule ${rule.id} promotion evidence must have a stable id`);+ }+ if (+ promotion.basis === 'conformance' &&+ (!promotion.fixturePath.startsWith('src/qa/') || !promotion.fixturePath.endsWith('.test.ts'))+ ) {+ throw new TypeError(+ `QA rule ${rule.id} conformance evidence must name a repository-relative src/qa/*.test.ts fixture`,+ );+ }+ if (!SHA256_PATTERN.test(promotion.evidenceSha256)) {+ throw new TypeError(`QA rule ${rule.id} promotion evidence must have a lowercase SHA-256`);+ }+ if (!Number.isFinite(Date.parse(promotion.frozenAt))) {+ throw new TypeError(`QA rule ${rule.id} promotion evidence must have a frozenAt timestamp`);+ }+ if (promotion.authorizedBy !== rule.owner.id) {+ throw new TypeError(`QA rule ${rule.id} promotion must be authorized by its named rule owner`);+ }+ if (promotion.basis === 'conformance') {+ if (rule.ruleClass !== 'exact') {+ throw new TypeError(`Non-exact QA rule ${rule.id} cannot use conformance promotion evidence`);+ }+ } else {+ if (rule.ruleClass === 'exact') {+ throw new TypeError(`Exact QA rule ${rule.id} cannot use QA-026 calibration evidence`);+ }+ assertCalibrationPromotion(rule, promotion);+ }+}++function assertModeAuthorized(rule: QaRule, mode: QaRuleMode): void {+ assertOwner(rule.owner, rule.id);+ if (!(QA_RULE_MODES as readonly string[]).includes(mode)) {+ throw new TypeError(`QA rule ${rule.id} received unsupported rollout mode ${String(mode)}`);+ }+ if (mode === 'off' || mode === 'observe') {+ if (rule.promotion) assertPromotionShape(rule, rule.promotion);+ return;+ }++ const promotion = rule.promotion;+ if (!promotion) {+ throw new Error(+ `QA rule ${rule.id} cannot enter ${mode} without frozen promotion evidence and owner authorization`,+ );+ }+ assertPromotionShape(rule, promotion);+ if (rule.ruleClass === 'vlm' && mode === 'enforce') {+ throw new Error(`VLM QA rule ${rule.id} cannot be enforced; VLM findings are never blockers`);+ }+ if (mode === 'enforce' && promotion.authorizedMode !== 'enforce') {+ throw new Error(+ `QA rule ${rule.id} promotion authorizes warn, not enforce; a new owner approval is required`,+ );+ }++ if (rule.ruleClass === 'exact' && promotion.basis !== 'conformance') {+ throw new Error(`Exact QA rule ${rule.id} requires conformance-fixture promotion evidence`);+ }+ if (rule.ruleClass !== 'exact' && promotion.basis !== 'qa-026-calibration') {+ throw new Error(`QA rule ${rule.id} requires frozen QA-026 calibration evidence`);+ }+}++function policyDecision(rule: QaRule, mode: QaRuleMode): QaRulePolicyDecision {+ const promotion = rule.promotion;+ return {+ ruleId: rule.id,+ profile: rule.profile,+ mode,+ ruleClass: rule.ruleClass,+ owner: { ...rule.owner },+ ...(promotion+ ? {+ promotionBasis: promotion.basis,+ authorizedMode: promotion.authorizedMode,+ evidenceId: evidenceId(promotion),+ }+ : {}),+ };+}++function applies(rule: QaRule, context: QaContext): boolean {+ const { scope } = rule;+ if (scope.kind === 'universal') return true;+ if (scope.kind === 'category') return context.intent.category === scope.category;+ if (scope.kind === 'subtype') {+ return context.intent.category === scope.category && context.intent.subtype === scope.subtype;+ }+ return context.intent.capabilities.includes(scope.capability);+}++function effectiveMode(rule: QaRule, policy: QaRulePolicy): QaRuleMode {+ return (+ policy.byRule?.[rule.id] ??+ policy.byProfile?.[rule.profile] ??+ policy.defaultMode ??+ rule.defaultMode+ );+}++function applyMode(finding: QaFinding, mode: QaRuleMode): QaFinding {+ if (mode === 'observe') return { ...finding, disposition: 'observe' };+ if (mode === 'warn') return { ...finding, disposition: 'warn' };+ return finding;+}++/** Composes universal, category, subtype, and capability rules without branching callers. */+export class QaRegistry {+ readonly #rules: QaRule[] = [];+ readonly #ids = new Set<string>();++ constructor(rules: readonly QaRule[] = []) {+ for (const rule of rules) this.register(rule);+ }++ register(rule: QaRule): this {+ if (!/^[A-Z][A-Z0-9_]*$/.test(rule.id)) {+ throw new TypeError(`QA rule id must be a stable uppercase code: ${rule.id}`);+ }+ if (this.#ids.has(rule.id)) throw new Error(`Duplicate QA rule id: ${rule.id}`);+ if (!(QA_RULE_CLASSES as readonly string[]).includes(rule.ruleClass)) {+ throw new TypeError(`QA rule ${rule.id} has an invalid rule class: ${rule.ruleClass}`);+ }+ assertModeAuthorized(rule, rule.defaultMode);+ this.#ids.add(rule.id);+ this.#rules.push(rule);+ return this;+ }++ list(context?: QaContext): readonly QaRule[] {+ return context ? this.#rules.filter((rule) => applies(rule, context)) : [...this.#rules];+ }++ /** Stable, auditable rollout state for every registered rule, including rules outside a context. */+ describePolicy(policy: QaRulePolicy = {}): readonly QaRulePolicyDecision[] {+ return this.#rules.map((rule) => {+ const mode = effectiveMode(rule, policy);+ assertModeAuthorized(rule, mode);+ return policyDecision(rule, mode);+ });+ }++ run(context: QaContext, policy: QaRulePolicy = {}): QaRegistryResult {+ const findings: QaFinding[] = [];+ const executedRules: string[] = [];+ const skippedRules: string[] = [];+ const decisions: QaRulePolicyDecision[] = [];++ for (const rule of this.#rules) {+ if (!applies(rule, context)) continue;+ const mode = effectiveMode(rule, policy);+ assertModeAuthorized(rule, mode);+ decisions.push(policyDecision(rule, mode));+ if (mode === 'off') {+ skippedRules.push(rule.id);+ continue;+ }+ executedRules.push(rule.id);+ for (const finding of rule.evaluate(context)) findings.push(applyMode(finding, mode));+ }++ return { findings, executedRules, skippedRules, decisions };+ }+}diff --git a/src/qa/run.ts b/src/qa/run.tsnew file mode 100644index 00000000..67250412--- /dev/null+++ b/src/qa/run.ts@@ -0,0 +1,208 @@+import type { AssetIntentV1 } from '../contracts';+import type { InstanceabilityReport } from '../metrics';+import { MATERIAL_QA_RULE } from './material';+import { ARCHITECTURE_QA_RULES } from './architecture';+import { CHARACTER_QA_RULE } from './character';+import { CHARACTER_ADVISORY_QA_RULE } from './character-advisory';+import { VEHICLE_QA_RULES } from './vehicle';+import { VEGETATION_QA_RULES } from './vegetation';+import { PROP_QA_RULES } from './prop';+import { ENVIRONMENT_QA_RULES } from './environment';+import { W7_BREADTH_QA_RULES } from './breadth';+import { withDerivedW7BreadthEvidence } from './breadth-evidence';+import { QaRegistry, type QaRulePolicy } from './registry';+import {+ createAssetQaReportV1,+ type AssetQaReportV1,+ type QaContext,+ type QaFinding,+} from './types';+import { UNIVERSAL_QA_RULES } from './universal';+import type { KhronosGltfValidationReport } from './gltf';+import type { MaterialBudgetWarningV1, MaterialMetricsV1 } from '../material-metrics';++export const DETERMINISTIC_QA_REGISTRY = new QaRegistry([+ ...UNIVERSAL_QA_RULES,+ MATERIAL_QA_RULE,+ ...ARCHITECTURE_QA_RULES,+ CHARACTER_QA_RULE,+ CHARACTER_ADVISORY_QA_RULE,+ ...VEHICLE_QA_RULES,+ ...VEGETATION_QA_RULES,+ ...PROP_QA_RULES,+ ...ENVIRONMENT_QA_RULES,+ ...W7_BREADTH_QA_RULES,+]);++export function runDeterministicSceneQa(+ context: QaContext,+ policy: QaRulePolicy = {},+): AssetQaReportV1 {+ const result = DETERMINISTIC_QA_REGISTRY.run(withDerivedW7BreadthEvidence(context), policy);+ return createAssetQaReportV1(context.intent, {+ findings: result.findings,+ evaluatedDimensions: ['exportIntegrity', 'categoryReadiness'],+ });+}++export function gltfReportFindings(+ report: KhronosGltfValidationReport,+ profile: string,+): QaFinding[] {+ return report.issues.messages+ .filter((issue) => issue.severity === 0 || issue.severity === 1)+ .map((issue) => ({+ code: `GLTF_${issue.code}`.replace(/[^A-Z0-9_]/g, '_'),+ disposition: issue.severity === 0 ? ('block' as const) : ('warn' as const),+ dimension: 'exportIntegrity' as const,+ profile,+ message: issue.message,+ ...(issue.pointer ? { affected: { nodePath: issue.pointer } } : {}),+ }));+}++export function appendFinalGltfQa(+ intent: AssetIntentV1,+ sceneReport: AssetQaReportV1,+ gltfReport: KhronosGltfValidationReport,+): AssetQaReportV1 {+ const findings = Object.values(sceneReport.dimensions).flatMap((dimension) => dimension.findings);+ findings.push(...gltfReportFindings(gltfReport, intent.qaProfile));+ return createAssetQaReportV1(intent, {+ findings,+ evaluatedDimensions: ['exportIntegrity', 'categoryReadiness'],+ metrics: {+ exportIntegrity: {+ gltfErrors: gltfReport.issues.numErrors,+ gltfWarnings: gltfReport.issues.numWarnings,+ },+ },+ });+}++/**+ * Attach the existing A–F instanceability result only to the runtime-cost+ * dimension. It is deliberately not promoted to a composite quality grade.+ */+export function appendRuntimeCostQa(+ intent: AssetIntentV1,+ report: AssetQaReportV1,+ instanceability?: InstanceabilityReport,+ metricsError?: string,+): AssetQaReportV1 {+ const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);+ if (metricsError) {+ findings.push({+ code: 'RUNTIME_COST_METRICS_FAILED',+ disposition: 'warn',+ dimension: 'runtimeCost',+ profile: intent.qaProfile,+ message: `Runtime-cost metrics could not be computed: ${metricsError}`,+ });+ }+ const evaluatedDimensions = Object.entries(report.dimensions)+ .filter(([, dimension]) => dimension.status !== 'notEvaluated')+ .map(([dimension]) => dimension as keyof AssetQaReportV1['dimensions']);+ evaluatedDimensions.push('runtimeCost');+ const metrics = Object.fromEntries(+ Object.entries(report.dimensions).flatMap(([dimension, result]) =>+ result.metrics ? [[dimension, result.metrics]] : [],+ ),+ ) as Partial<+ Record<keyof AssetQaReportV1['dimensions'], Record<string, number | string | boolean | null>>+ >;+ if (instanceability) {+ metrics.runtimeCost = {+ instanceabilityGrade: instanceability.grade,+ instanceabilitySummary: instanceability.summary,+ uniqueGeometries: instanceability.metrics.uniqueGeometries,+ uniqueMaterials: instanceability.metrics.uniqueMaterials,+ drawCalls: instanceability.metrics.drawCalls,+ textureCount: instanceability.metrics.textureCount,+ transparentMaterials: instanceability.metrics.transparentMaterials,+ triangles: instanceability.metrics.triangles,+ skinned: instanceability.metrics.skinned,+ };+ }++ return createAssetQaReportV1(intent, {+ findings,+ evaluatedDimensions,+ ...(Object.keys(metrics).length > 0 ? { metrics } : {}),+ });+}++/** Attach portable material metrics and advisory budget findings to runtimeCost+ * without collapsing them into the independent instanceability grade. */+export function appendMaterialMetricsQa(+ intent: AssetIntentV1,+ report: AssetQaReportV1,+ materialMetrics: MaterialMetricsV1,+ budgetWarnings: readonly MaterialBudgetWarningV1[] = [],+): AssetQaReportV1 {+ const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);+ findings.push(+ ...budgetWarnings.map(+ (warning): QaFinding => ({+ code: warning.code,+ disposition: 'warn',+ dimension: 'runtimeCost',+ profile: `${warning.profile}.${warning.tier}`,+ message: `${warning.message} ${warning.advice}`,+ measurement: warning.measurement,+ }),+ ),+ );+ const evaluatedDimensions = Object.entries(report.dimensions)+ .filter(([, dimension]) => dimension.status !== 'notEvaluated')+ .map(([dimension]) => dimension as keyof AssetQaReportV1['dimensions']);+ if (!evaluatedDimensions.includes('runtimeCost')) evaluatedDimensions.push('runtimeCost');+ const metrics = Object.fromEntries(+ Object.entries(report.dimensions).flatMap(([dimension, result]) =>+ result.metrics ? [[dimension, result.metrics]] : [],+ ),+ ) as Partial<+ Record<keyof AssetQaReportV1['dimensions'], Record<string, number | string | boolean | null>>+ >;+ metrics.runtimeCost = {+ ...(metrics.runtimeCost ?? {}),+ materialCount: materialMetrics.materialCount,+ opaqueMaterials: materialMetrics.opaqueMaterials,+ maskedMaterials: materialMetrics.maskedMaterials,+ blendedMaterials: materialMetrics.blendedMaterials,+ singleSidedMaterials: materialMetrics.singleSidedMaterials,+ doubleSidedMaterials: materialMetrics.doubleSidedMaterials,+ texturedMaterials: materialMetrics.texturedMaterials,+ materialExtensionCount: materialMetrics.materialExtensionCount,+ materialExtensionsUsed: materialMetrics.materialExtensionsUsed.join(','),+ imageCount: materialMetrics.imageCount,+ maxImageDimension: materialMetrics.maxImageDimension,+ decodedImageBytesRgba8: materialMetrics.decodedImageBytesRgba8,+ estimatedGpuBytesWithMipmaps: materialMetrics.estimatedGpuBytesWithMipmaps,+ blendedSurfaceAreaRatio: materialMetrics.blendedSurfaceAreaRatio,+ };+ return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });+}++export class AssetQaBlockedError extends Error {+ readonly report: AssetQaReportV1;+ readonly stage: 'scene' | 'final-glb';+ readonly gltfValidation?: KhronosGltfValidationReport;++ constructor(+ report: AssetQaReportV1,+ stage: 'scene' | 'final-glb',+ gltfValidation?: KhronosGltfValidationReport,+ ) {+ const blockers = Object.values(report.dimensions)+ .flatMap((dimension) => dimension.findings)+ .filter((finding) => finding.disposition === 'block');+ super(+ `Asset QA blocked at ${stage}: ${blockers.map((finding) => finding.code).join(', ') || 'unknown blocker'}`,+ );+ this.name = 'AssetQaBlockedError';+ this.report = report;+ this.stage = stage;+ this.gltfValidation = gltfValidation;+ }+}diff --git a/src/qa/types.ts b/src/qa/types.tsnew file mode 100644index 00000000..aa5f91eb--- /dev/null+++ b/src/qa/types.ts@@ -0,0 +1,174 @@+import type { AssetCategory, AssetIntentV1 } from '../contracts';++export const QA_DIMENSIONS = [+ 'exportIntegrity',+ 'categoryReadiness',+ 'promptAlignment',+ 'visualQuality',+ 'runtimeCost',+] as const;++export type QaDimension = (typeof QA_DIMENSIONS)[number];+export type QaDimensionStatus = 'pass' | 'warn' | 'block' | 'notEvaluated';+export type QaFindingDisposition = 'observe' | 'warn' | 'block';+export type AssetQaDisposition = 'pass' | 'warn' | 'block' | 'notEvaluated' | 'legacy-unassessed';++export interface QaAffectedEntity {+ node?: string;+ nodePath?: string;+ material?: string;+ texture?: string;+ attribute?: string;+ clip?: string;+ track?: string;+}++export interface QaMeasurement {+ name: string;+ actual: number | string | boolean | null;+ expected?: number | string | boolean | null;+ threshold?: number;+ unit?: string;+}++/** Stable, machine-readable finding returned by every new QA rule. */+export interface QaFinding {+ code: string;+ disposition: QaFindingDisposition;+ dimension: QaDimension;+ profile: string;+ message: string;+ affected?: QaAffectedEntity;+ measurement?: QaMeasurement;+ viewHints?: string[];+ repairText?: string;+}++export interface QaDimensionResult {+ status: QaDimensionStatus;+ findings: QaFinding[];+ /** Optional dimension-specific metrics. Never interpreted as an overall grade. */+ metrics?: Record<string, number | string | boolean | null>;+}++export interface AssetQaReportV1 {+ schemaVersion: 1;+ category: AssetCategory;+ qaProfile: string;+ disposition: AssetQaDisposition;+ dimensions: Record<QaDimension, QaDimensionResult>;+}++/**+ * Honest compatibility state for historical rows that predate trusted intent+ * and final-byte QA. It is neither a pass nor a failure and must never be used+ * to block ordinary view/download/reuse.+ */+export function createLegacyUnassessedQaReportV1(+ category: AssetCategory,+ qaProfile = `${category}.legacy`,+): AssetQaReportV1 {+ const dimensions = {} as Record<QaDimension, QaDimensionResult>;+ for (const dimension of QA_DIMENSIONS) {+ dimensions[dimension] = { status: 'notEvaluated', findings: [] };+ }+ return {+ schemaVersion: 1,+ category,+ qaProfile,+ disposition: 'legacy-unassessed',+ dimensions,+ };+}++export interface QaContext {+ intent: AssetIntentV1;+ /** Deliberately unknown here; concrete rules own their scene/runtime dependency. */+ scene?: unknown;+ clips?: readonly unknown[];+ source?: string;+ glbBytes?: Uint8Array;+ /** Engine-derived measurements. Callers cannot substitute model-authored metadata for this seam. */+ derivedEvidence?: {+ source: 'engine-scene-analysis';+ vfxArtifact?: unknown;+ assetScope?: unknown;+ modularKit?: unknown;+ modularJoin?: unknown;+ };+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++export function isQaFinding(value: unknown): value is QaFinding {+ if (!isRecord(value)) return false;+ return (+ typeof value.code === 'string' &&+ /^[A-Z][A-Z0-9_]*$/.test(value.code) &&+ (value.disposition === 'observe' ||+ value.disposition === 'warn' ||+ value.disposition === 'block') &&+ (QA_DIMENSIONS as readonly unknown[]).includes(value.dimension) &&+ typeof value.profile === 'string' &&+ value.profile.length > 0 &&+ typeof value.message === 'string' &&+ value.message.length > 0+ );+}++const statusForFindings = (+ findings: readonly QaFinding[],+): Exclude<QaDimensionStatus, 'notEvaluated'> => {+ if (findings.some((finding) => finding.disposition === 'block')) return 'block';+ if (findings.some((finding) => finding.disposition === 'warn')) return 'warn';+ return 'pass';+};++export interface CreateAssetQaReportOptions {+ findings?: readonly QaFinding[];+ evaluatedDimensions?: readonly QaDimension[];+ metrics?: Partial<Record<QaDimension, Record<string, number | string | boolean | null>>>;+}++/**+ * Build the five independent result dimensions. Unrun VLM or cost passes remain+ * explicitly `notEvaluated`; no synthetic score or composite letter is invented.+ */+export function createAssetQaReportV1(+ intent: AssetIntentV1,+ options: CreateAssetQaReportOptions = {},+): AssetQaReportV1 {+ const findings = [...(options.findings ?? [])];+ const evaluated = new Set(options.evaluatedDimensions ?? []);+ for (const finding of findings) evaluated.add(finding.dimension);++ const dimensions = Object.fromEntries(+ QA_DIMENSIONS.map((dimension) => {+ const dimensionFindings = findings.filter((finding) => finding.dimension === dimension);+ const result: QaDimensionResult = {+ status: evaluated.has(dimension) ? statusForFindings(dimensionFindings) : 'notEvaluated',+ findings: dimensionFindings,+ ...(options.metrics?.[dimension] ? { metrics: options.metrics[dimension] } : {}),+ };+ return [dimension, result];+ }),+ ) as unknown as Record<QaDimension, QaDimensionResult>;++ const statuses = QA_DIMENSIONS.map((dimension) => dimensions[dimension].status);+ const disposition: AssetQaDisposition = statuses.includes('block')+ ? 'block'+ : statuses.includes('warn')+ ? 'warn'+ : statuses.every((status) => status === 'notEvaluated')+ ? 'notEvaluated'+ : 'pass';++ return {+ schemaVersion: 1,+ category: intent.category,+ qaProfile: intent.qaProfile,+ disposition,+ dimensions,+ };+}diff --git a/src/qa/universal.test.ts b/src/qa/universal.test.tsnew file mode 100644index 00000000..129f5a9f--- /dev/null+++ b/src/qa/universal.test.ts@@ -0,0 +1,140 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import { createAssetIntentV1 } from '../contracts';+import { createUniversalQaRegistry } from './universal';++function validRoot(): THREE.Group {+ const root = new THREE.Group();+ root.name = 'Root';+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial());+ mesh.name = 'Body';+ root.add(mesh);+ return root;+}++const codes = (root: THREE.Object3D, overrides: Record<string, unknown> = {}): string[] => {+ const context = {+ intent: createAssetIntentV1({ category: 'prop' }),+ scene: root,+ ...overrides,+ };+ return createUniversalQaRegistry()+ .run(context)+ .findings.map((finding) => finding.code);+};++describe('universal scene QA', () => {+ test('valid control is finding-free', () => {+ expect(codes(validRoot())).toEqual([]);+ });++ test('blocks empty output', () => {+ const root = new THREE.Group();+ root.name = 'Root';+ expect(codes(root)).toContain('UNIVERSAL_EMPTY_OUTPUT');+ });++ test('localizes non-finite transforms and attributes', () => {+ const root = validRoot();+ const mesh = root.getObjectByName('Body') as THREE.Mesh;+ mesh.position.x = Number.NaN;+ const position = mesh.geometry.getAttribute('position');+ position.setX(0, Number.POSITIVE_INFINITY);++ expect(codes(root)).toEqual(+ expect.arrayContaining(['UNIVERSAL_NONFINITE_TRANSFORM', 'UNIVERSAL_NONFINITE_ATTRIBUTE']),+ );+ });++ test('blocks an out-of-range geometry index', () => {+ const root = new THREE.Group();+ root.name = 'Root';+ const geometry = new THREE.BufferGeometry();+ geometry.setAttribute(+ 'position',+ new THREE.Float32BufferAttribute([0, 0, 0, 1, 0, 0, 0, 1, 0], 3),+ );+ geometry.setIndex([0, 1, 99]);+ const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());+ mesh.name = 'Broken';+ root.add(mesh);+ expect(codes(root)).toContain('UNIVERSAL_INVALID_INDEX');+ });++ test('blocks zero scale on renderable/required nodes but only warns on empty organization', () => {+ const root = validRoot();+ const mesh = root.getObjectByName('Body')!;+ mesh.scale.x = 0;+ const organization = new THREE.Group();+ organization.name = 'DisabledBucket';+ organization.scale.y = 0;+ root.add(organization);++ const findings = createUniversalQaRegistry().run({+ intent: createAssetIntentV1({ category: 'prop', requiredParts: ['Body'] }),+ scene: root,+ }).findings;+ expect(+ findings.find((finding) => finding.code === 'UNIVERSAL_ZERO_SCALE_RENDERABLE')?.disposition,+ ).toBe('block');+ expect(+ findings.find((finding) => finding.code === 'UNIVERSAL_ZERO_SCALE_ORGANIZATIONAL')+ ?.disposition,+ ).toBe('warn');+ });++ test('warns on ordinary duplicate names and blocks required duplicates', () => {+ const root = validRoot();+ const duplicate = new THREE.Group();+ duplicate.name = 'Body';+ root.add(duplicate);++ const warning = createUniversalQaRegistry().run({+ intent: createAssetIntentV1({ category: 'prop' }),+ scene: root,+ }).findings;+ expect(+ warning.find((finding) => finding.code === 'UNIVERSAL_DUPLICATE_NODE_NAME')?.disposition,+ ).toBe('warn');++ const blocker = createUniversalQaRegistry().run({+ intent: createAssetIntentV1({ category: 'prop', requiredParts: ['Body'] }),+ scene: root,+ }).findings;+ expect(+ blocker.find((finding) => finding.code === 'UNIVERSAL_DUPLICATE_REQUIRED_NODE_NAME')+ ?.disposition,+ ).toBe('block');+ });++ test('blocks missing required clips and unresolved targets', () => {+ const root = validRoot();+ const intent = createAssetIntentV1({+ category: 'character',+ animation: { clips: ['walk'], locomotionDirection: '+X' },+ });+ const unresolved = new THREE.AnimationClip('walk', 1, [+ new THREE.VectorKeyframeTrack('MissingJoint.position', [0, 1], [0, 0, 0, 1, 0, 0]),+ ]);+ const registry = createUniversalQaRegistry();++ expect(+ registry.run({ intent, scene: root, clips: [] }).findings.map((item) => item.code),+ ).toContain('UNIVERSAL_REQUIRED_CLIP_MISSING');+ expect(+ registry.run({ intent, scene: root, clips: [unresolved] }).findings.map((item) => item.code),+ ).toContain('UNIVERSAL_REQUIRED_ANIMATION_TARGET_UNRESOLVED');+ });++ test('rule modes can demote objective blockers to observe during rollout', () => {+ const root = new THREE.Group();+ const result = createUniversalQaRegistry().run(+ { intent: createAssetIntentV1({ category: 'prop' }), scene: root },+ { byRule: { UNIVERSAL_SCENE_CONTENT_RULE: 'observe' } },+ );+ expect(+ result.findings.find((finding) => finding.code === 'UNIVERSAL_EMPTY_OUTPUT')?.disposition,+ ).toBe('observe');+ });+});diff --git a/src/qa/universal.ts b/src/qa/universal.tsnew file mode 100644index 00000000..3b169b92--- /dev/null+++ b/src/qa/universal.ts@@ -0,0 +1,451 @@+import {+ conformancePromotionAuthorization,+ KILN_ENGINE_QA_OWNER,+ QaRegistry,+ type QaRule,+} from './registry';+import type { QaAffectedEntity, QaContext, QaFinding } from './types';++interface VectorLike {+ x: number;+ y: number;+ z: number;+}++interface QuaternionLike extends VectorLike {+ w: number;+}++interface AttributeLike {+ array?: ArrayLike<number>;+ count?: number;+ itemSize?: number;+}++interface GeometryLike {+ attributes?: Record<string, AttributeLike>;+ index?: AttributeLike | null;+}++interface SceneNodeLike {+ name?: string;+ parent?: SceneNodeLike | null;+ children?: SceneNodeLike[];+ traverse?: (visitor: (node: SceneNodeLike) => void) => void;+ position?: VectorLike;+ quaternion?: QuaternionLike;+ scale?: VectorLike;+ matrix?: { elements?: ArrayLike<number> };+ geometry?: GeometryLike;+ isMesh?: boolean;+ isSprite?: boolean;+ isLine?: boolean;+ isPoints?: boolean;+}++interface AnimationTrackLike {+ name?: string;+}++interface AnimationClipLike {+ name?: string;+ tracks?: AnimationTrackLike[];+}++const ZERO_SCALE_EPSILON = 1e-8;++function isSceneNode(value: unknown): value is SceneNodeLike {+ return typeof value === 'object' && value !== null;+}++function sceneNodes(context: QaContext): SceneNodeLike[] {+ if (!isSceneNode(context.scene)) return [];+ const nodes: SceneNodeLike[] = [];+ const seen = new Set<SceneNodeLike>();+ const add = (node: SceneNodeLike) => {+ if (!seen.has(node)) {+ seen.add(node);+ nodes.push(node);+ }+ };++ if (typeof context.scene.traverse === 'function') {+ context.scene.traverse(add);+ return nodes;+ }++ const pending = [context.scene];+ while (pending.length > 0) {+ const node = pending.shift()!;+ add(node);+ for (const child of node.children ?? []) pending.push(child);+ }+ return nodes;+}++function nodeName(node: SceneNodeLike): string {+ return node.name?.trim() || '(unnamed)';+}++function nodePath(node: SceneNodeLike): string {+ const names: string[] = [];+ const seen = new Set<SceneNodeLike>();+ let cursor: SceneNodeLike | null | undefined = node;+ while (cursor && !seen.has(cursor)) {+ seen.add(cursor);+ names.unshift(nodeName(cursor));+ cursor = cursor.parent;+ }+ return names.join('/');+}++function affectedNode(node: SceneNodeLike, extra: QaAffectedEntity = {}): QaAffectedEntity {+ return { node: nodeName(node), nodePath: nodePath(node), ...extra };+}++function isRenderable(node: SceneNodeLike): boolean {+ // Three.js Sprite has no BufferGeometry in the source scene; Kiln's bridge+ // deterministically materializes it as a two-triangle semantic quad.+ if (node.isSprite) return true;+ if (!(node.isMesh || node.isLine || node.isPoints)) return false;+ const position = node.geometry?.attributes?.position;+ return typeof position?.count === 'number'+ ? position.count > 0+ : Boolean(position?.array?.length);+}++function descendantsContainRenderable(node: SceneNodeLike): boolean {+ const pending = [...(node.children ?? [])];+ while (pending.length > 0) {+ const child = pending.shift()!;+ if (isRenderable(child)) return true;+ pending.push(...(child.children ?? []));+ }+ return false;+}++function finiteComponents(value: VectorLike | QuaternionLike | undefined): boolean {+ if (!value) return true;+ const values = 'w' in value ? [value.x, value.y, value.z, value.w] : [value.x, value.y, value.z];+ return values.every(Number.isFinite);+}++function iterableValues(value: ArrayLike<number> | undefined): number[] {+ if (!value) return [];+ const out: number[] = [];+ for (let i = 0; i < value.length; i++) out.push(value[i]!);+ return out;+}++function emptyOutputFindings(context: QaContext): QaFinding[] {+ const nodes = sceneNodes(context);+ if (nodes.some(isRenderable)) return [];+ return [+ {+ code: 'UNIVERSAL_EMPTY_OUTPUT',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'universal',+ message: 'The generated scene contains no renderable geometry.',+ measurement: { name: 'renderableNodeCount', actual: 0, expected: 1 },+ repairText: 'Return at least one non-empty renderable mesh or Sprite from build().',+ },+ ];+}++function finiteDataFindings(context: QaContext): QaFinding[] {+ const findings: QaFinding[] = [];+ for (const node of sceneNodes(context)) {+ const badTransform =+ !finiteComponents(node.position) ||+ !finiteComponents(node.quaternion) ||+ !finiteComponents(node.scale) ||+ iterableValues(node.matrix?.elements).some((value) => !Number.isFinite(value));+ if (badTransform) {+ findings.push({+ code: 'UNIVERSAL_NONFINITE_TRANSFORM',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'universal',+ message: `Node ${JSON.stringify(nodeName(node))} contains a non-finite transform value.`,+ affected: affectedNode(node),+ repairText: 'Replace NaN/Infinity transform components with finite numbers.',+ });+ }++ for (const [attributeName, attribute] of Object.entries(node.geometry?.attributes ?? {})) {+ const values = iterableValues(attribute.array);+ const badIndex = values.findIndex((value) => !Number.isFinite(value));+ if (badIndex >= 0) {+ findings.push({+ code: 'UNIVERSAL_NONFINITE_ATTRIBUTE',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'universal',+ message: `Geometry attribute ${attributeName} on ${JSON.stringify(nodeName(node))} contains a non-finite value.`,+ affected: affectedNode(node, { attribute: attributeName }),+ measurement: { name: 'arrayIndex', actual: badIndex },+ repairText: `Rebuild the ${attributeName} attribute with finite numeric data.`,+ });+ }+ }+ }+ return findings;+}++function invalidIndexFindings(context: QaContext): QaFinding[] {+ const findings: QaFinding[] = [];+ for (const node of sceneNodes(context)) {+ const index = node.geometry?.index;+ if (!index?.array) continue;+ const vertexCount = node.geometry?.attributes?.position?.count ?? 0;+ const values = iterableValues(index.array);+ const badPosition = values.findIndex(+ (value) => !Number.isInteger(value) || value < 0 || value >= vertexCount,+ );+ if (badPosition >= 0) {+ findings.push({+ code: 'UNIVERSAL_INVALID_INDEX',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'universal',+ message: `Geometry index on ${JSON.stringify(nodeName(node))} references an invalid vertex.`,+ affected: affectedNode(node, { attribute: 'index' }),+ measurement: {+ name: 'indexValue',+ actual: values[badPosition] ?? null,+ threshold: vertexCount - 1,+ },+ repairText: 'Rebuild the index so every value is an integer within the POSITION accessor.',+ });+ }+ }+ return findings;+}++function zeroScaleFindings(context: QaContext): QaFinding[] {+ const required = new Set(context.intent.requiredParts);+ const findings: QaFinding[] = [];+ for (const node of sceneNodes(context)) {+ const scale = node.scale;+ if (!scale) continue;+ const zeroAxes = (['x', 'y', 'z'] as const).filter(+ (axis) => Number.isFinite(scale[axis]) && Math.abs(scale[axis]) <= ZERO_SCALE_EPSILON,+ );+ if (zeroAxes.length === 0) continue;+ const outputBearing =+ isRenderable(node) || descendantsContainRenderable(node) || required.has(nodeName(node));+ findings.push({+ code: outputBearing+ ? 'UNIVERSAL_ZERO_SCALE_RENDERABLE'+ : 'UNIVERSAL_ZERO_SCALE_ORGANIZATIONAL',+ disposition: outputBearing ? 'block' : 'warn',+ dimension: outputBearing ? 'exportIntegrity' : 'categoryReadiness',+ profile: 'universal',+ message: outputBearing+ ? `Renderable or required node ${JSON.stringify(nodeName(node))} has zero scale.`+ : `Organizational node ${JSON.stringify(nodeName(node))} has zero scale.`,+ affected: affectedNode(node),+ measurement: { name: 'zeroScaleAxes', actual: zeroAxes.join(',') },+ repairText: outputBearing+ ? 'Use a finite non-zero scale for geometry and required semantic nodes.'+ : 'Remove the zero scale unless the organizational node is intentionally disabled.',+ });+ }+ return findings;+}++function clipList(context: QaContext): AnimationClipLike[] {+ return (context.clips ?? []).filter(+ (clip): clip is AnimationClipLike => typeof clip === 'object' && clip !== null,+ );+}++function trackTarget(trackName: string): string | undefined {+ const dot = trackName.indexOf('.');+ if (dot <= 0) return undefined;+ const path = trackName.slice(0, dot);+ const slash = path.lastIndexOf('/');+ return path.slice(slash + 1) || undefined;+}++function requiredTrackTargets(context: QaContext): Set<string> {+ const requested = new Set(context.intent.animation?.clips ?? []);+ const targets = new Set<string>();+ for (const clip of clipList(context)) {+ if (!clip.name || !requested.has(clip.name)) continue;+ for (const track of clip.tracks ?? []) {+ if (track.name) {+ const target = trackTarget(track.name);+ if (target) targets.add(target);+ }+ }+ }+ return targets;+}++function duplicateNameFindings(context: QaContext): QaFinding[] {+ const byName = new Map<string, SceneNodeLike[]>();+ for (const node of sceneNodes(context)) {+ const name = node.name?.trim();+ if (!name) continue;+ const nodes = byName.get(name) ?? [];+ nodes.push(node);+ byName.set(name, nodes);+ }++ const required = new Set([...context.intent.requiredParts, ...requiredTrackTargets(context)]);+ const findings: QaFinding[] = [];+ for (const [name, nodes] of byName) {+ if (nodes.length < 2) continue;+ const contractCritical = required.has(name);+ findings.push({+ code: contractCritical+ ? 'UNIVERSAL_DUPLICATE_REQUIRED_NODE_NAME'+ : 'UNIVERSAL_DUPLICATE_NODE_NAME',+ disposition: contractCritical ? 'block' : 'warn',+ dimension: 'categoryReadiness',+ profile: 'universal',+ message: `${nodes.length} scene nodes share the name ${JSON.stringify(name)}.`,+ affected: { node: name, nodePath: nodes.map(nodePath).join(' | ') },+ measurement: { name: 'duplicateCount', actual: nodes.length, expected: 1 },+ repairText: contractCritical+ ? 'Give every required or animated target a unique name.'+ : 'Use unique names when nodes must be addressed independently.',+ });+ }+ return findings;+}++function animationTargetFindings(context: QaContext): QaFinding[] {+ const animation = context.intent.animation;+ if (!animation || animation.clips.length === 0) return [];+ const nodes = sceneNodes(context);+ const names = new Set(nodes.map((node) => node.name?.trim()).filter(Boolean) as string[]);+ const clips = clipList(context);+ const byName = new Map(clips.map((clip) => [clip.name, clip]));+ const findings: QaFinding[] = [];++ for (const requiredClip of animation.clips) {+ const clip = byName.get(requiredClip);+ if (!clip) {+ findings.push({+ code: 'UNIVERSAL_REQUIRED_CLIP_MISSING',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'universal',+ message: `Required animation clip ${JSON.stringify(requiredClip)} is missing.`,+ affected: { clip: requiredClip },+ repairText: `Create and return the required ${requiredClip} clip from animate().`,+ });+ continue;+ }+ for (const track of clip.tracks ?? []) {+ const trackName = track.name ?? '';+ const target = trackTarget(trackName);+ if (!target || !names.has(target)) {+ findings.push({+ code: 'UNIVERSAL_REQUIRED_ANIMATION_TARGET_UNRESOLVED',+ disposition: 'block',+ dimension: 'exportIntegrity',+ profile: 'universal',+ message: `Required clip ${JSON.stringify(requiredClip)} has an unresolved track target.`,+ affected: { clip: requiredClip, track: trackName, ...(target ? { node: target } : {}) },+ repairText: 'Rename the track target to exactly match one unique scene node.',+ });+ }+ }+ }+ return findings;+}++export const UNIVERSAL_QA_RULES: readonly QaRule[] = [+ {+ id: 'UNIVERSAL_SCENE_CONTENT_RULE',+ profile: 'universal',+ scope: { kind: 'universal' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'universal-qa-v1',+ 'src/qa/universal.test.ts',+ '82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78',+ ),+ defaultMode: 'enforce',+ evaluate: emptyOutputFindings,+ },+ {+ id: 'UNIVERSAL_FINITE_DATA_RULE',+ profile: 'universal',+ scope: { kind: 'universal' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'universal-qa-v1',+ 'src/qa/universal.test.ts',+ '82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78',+ ),+ defaultMode: 'enforce',+ evaluate: finiteDataFindings,+ },+ {+ id: 'UNIVERSAL_INDEX_RULE',+ profile: 'universal',+ scope: { kind: 'universal' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'universal-qa-v1',+ 'src/qa/universal.test.ts',+ '82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78',+ ),+ defaultMode: 'enforce',+ evaluate: invalidIndexFindings,+ },+ {+ id: 'UNIVERSAL_ZERO_SCALE_RULE',+ profile: 'universal',+ scope: { kind: 'universal' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'universal-qa-v1',+ 'src/qa/universal.test.ts',+ '82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78',+ ),+ defaultMode: 'enforce',+ evaluate: zeroScaleFindings,+ },+ {+ id: 'UNIVERSAL_NODE_NAME_RULE',+ profile: 'universal',+ scope: { kind: 'universal' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'universal-qa-v1',+ 'src/qa/universal.test.ts',+ '82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78',+ ),+ defaultMode: 'enforce',+ evaluate: duplicateNameFindings,+ },+ {+ id: 'UNIVERSAL_ANIMATION_TARGET_RULE',+ profile: 'universal',+ scope: { kind: 'universal' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'universal-qa-v1',+ 'src/qa/universal.test.ts',+ '82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78',+ ),+ defaultMode: 'enforce',+ evaluate: animationTargetFindings,+ },+] as const;++export function createUniversalQaRegistry(): QaRegistry {+ return new QaRegistry(UNIVERSAL_QA_RULES);+}diff --git a/src/qa/vegetation-corpus.test.ts b/src/qa/vegetation-corpus.test.tsnew file mode 100644index 00000000..bed2d313--- /dev/null+++ b/src/qa/vegetation-corpus.test.ts@@ -0,0 +1,97 @@+import { createHash } from 'node:crypto';++import { describe, expect, test } from 'bun:test';+import type * as THREE from 'three';++import { renderSceneToGLB } from '../render';+import { evaluateVegetationAdvisoryQa, evaluateVegetationContactQa } from './vegetation';+import {+ W7_VEGETATION_CORPUS,+ W7_VEGETATION_CORPUS_VERSION,+ w7VegetationCorpusDescriptor,+} from './vegetation-corpus';++const sha256 = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');++describe('VEG-019 helper-independent vegetation regression corpus', () => {+ test('freezes the exact requested control and adversary surface', () => {+ expect(W7_VEGETATION_CORPUS_VERSION).toBe('kiln.vegetation.helper-independent.v1');+ expect(W7_VEGETATION_CORPUS.map((fixture) => fixture.id)).toEqual([+ 'oak-control',+ 'conifer-control',+ 'palm-control',+ 'shrub-control',+ 'grass-tuft-control',+ 'vine-control',+ 'mushroom-control',+ 'flower-control',+ 'succulent-control',+ 'bare-tree-control',+ 'aquatic-control',+ 'sparse-adversary',+ 'floating-adversary',+ 'base-clutter-adversary',+ ]);+ const descriptor = JSON.stringify(w7VegetationCorpusDescriptor());+ expect(sha256(new TextEncoder().encode(descriptor))).toMatch(/^[a-f0-9]{64}$/);+ });++ test('executes semantic/fallback validators with stable expected and forbidden codes', () => {+ for (const fixture of W7_VEGETATION_CORPUS) {+ const payload = fixture.build();+ const findings = [+ ...evaluateVegetationContactQa(payload),+ ...evaluateVegetationAdvisoryQa(payload),+ ];+ const codes = findings.map((finding) => finding.code);+ for (const code of fixture.expectedCodes) expect(codes).toContain(code);+ for (const code of fixture.forbiddenCodes) expect(codes).not.toContain(code);+ expect(+ findings.every((finding) => finding.measurement || finding.code === 'VEG_SCOPE_EXTRA'),+ ).toBe(true);+ }+ });++ test('contains only finite renderable geometry', () => {+ for (const fixture of W7_VEGETATION_CORPUS) {+ const payload = fixture.build();+ let renderables = 0;+ payload.scene.traverse((node) => {+ const mesh = node as THREE.Mesh;+ if (!mesh.isMesh) return;+ const position = mesh.geometry.getAttribute('position');+ expect(position?.count ?? 0).toBeGreaterThan(0);+ for (const value of position!.array) expect(Number.isFinite(value)).toBe(true);+ renderables++;+ });+ expect(renderables).toBeGreaterThan(0);+ }+ });++ test('serializes nonblocking cases byte-stably and rejects the exact floating blocker', async () => {+ for (const fixture of W7_VEGETATION_CORPUS) {+ const firstPayload = fixture.build();+ const repeatPayload = fixture.build();+ if (fixture.id === 'floating-adversary') {+ await expect(+ renderSceneToGLB(firstPayload.scene, {+ intent: firstPayload.intent,+ optimize: 'off',+ }),+ ).rejects.toThrow('VEG_CONTACT_FLOATING');+ continue;+ }+ const first = await renderSceneToGLB(firstPayload.scene, {+ intent: firstPayload.intent,+ optimize: 'off',+ });+ const repeat = await renderSceneToGLB(repeatPayload.scene, {+ intent: repeatPayload.intent,+ optimize: 'off',+ });+ expect(first.gltfValidation.issues.numErrors).toBe(0);+ expect(first.gltfValidation.issues.numWarnings).toBe(0);+ expect(sha256(first.bytes)).toBe(sha256(repeat.bytes));+ }+ }, 30_000);+});diff --git a/src/qa/vegetation-corpus.ts b/src/qa/vegetation-corpus.tsnew file mode 100644index 00000000..a2108719--- /dev/null+++ b/src/qa/vegetation-corpus.ts@@ -0,0 +1,404 @@+import * as THREE from 'three';++import {+ createAssetIntentV1,+ stampSemanticMetadataV1,+ type AssetIntentV1,+ type VegetationCanopyProfile,+ type VegetationGrowthState,+ type VegetationSubtype,+} from '../contracts';++export const W7_VEGETATION_CORPUS_VERSION = 'kiln.vegetation.helper-independent.v1' as const;++export interface W7VegetationCorpusPayload {+ intent: AssetIntentV1;+ scene: THREE.Group;+}++export interface W7VegetationCorpusCase {+ id: string;+ kind: 'control' | 'adversary';+ subtype: VegetationSubtype;+ description: string;+ expectedCodes: readonly string[];+ forbiddenCodes: readonly string[];+ build: () => W7VegetationCorpusPayload;+}++const wood = new THREE.MeshStandardMaterial({ color: 0x674229, roughness: 0.92 });+const leafDark = new THREE.MeshStandardMaterial({ color: 0x285b32, roughness: 0.86 });+const leafLight = new THREE.MeshStandardMaterial({ color: 0x65964a, roughness: 0.86 });++function semantic<T extends THREE.Object3D>(node: T, ...roles: string[]): T {+ return stampSemanticMetadataV1(node, { roles });+}++function rootWithContact(name: string, contactY = 0): THREE.Group {+ const root = new THREE.Group();+ root.name = name;+ const contact = semantic(new THREE.Group(), 'vegetation.contact.ground');+ contact.name = 'Contact_Ground';+ contact.position.y = contactY;+ root.add(contact);+ return root;+}++function cylinderBetween(+ name: string,+ start: THREE.Vector3,+ end: THREE.Vector3,+ baseRadius: number,+ tipRadius: number,+ roles: readonly string[],+): THREE.Mesh {+ const direction = end.clone().sub(start);+ const mesh = semantic(+ new THREE.Mesh(new THREE.CylinderGeometry(tipRadius, baseRadius, direction.length(), 8), wood),+ ...roles,+ );+ mesh.name = name;+ mesh.position.copy(start).add(end).multiplyScalar(0.5);+ mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction.normalize());+ return mesh;+}++interface PlantSpec {+ id: string;+ subtype: VegetationSubtype;+ growthState?: VegetationGrowthState;+ canopyProfile?: VegetationCanopyProfile;+ trunkHeight: number;+ trunkBase: number;+ trunkTip: number;+ branchCount: number;+ branchReach: number;+ branchRise: number;+ foliageScale: number;+ foliageShape?: 'sphere' | 'blade' | 'cap' | 'pad';+ noFoliage?: boolean;+}++function foliageGeometry(shape: PlantSpec['foliageShape'], scale: number): THREE.BufferGeometry {+ if (shape === 'blade') return new THREE.PlaneGeometry(scale * 0.5, scale * 2.2);+ if (shape === 'cap')+ return new THREE.SphereGeometry(scale, 10, 5, 0, Math.PI * 2, 0, Math.PI / 2);+ if (shape === 'pad') return new THREE.SphereGeometry(scale, 8, 6).scale(0.55, 1.35, 0.3);+ return new THREE.SphereGeometry(scale, 8, 6);+}++function buildPlant(spec: PlantSpec): W7VegetationCorpusPayload {+ const root = rootWithContact(spec.id);+ const trunk = semantic(+ new THREE.Mesh(+ new THREE.CylinderGeometry(spec.trunkTip, spec.trunkBase, spec.trunkHeight, 10),+ wood,+ ),+ spec.subtype === 'grass' ? 'vegetation.stem' : 'vegetation.trunk',+ );+ trunk.name = spec.subtype === 'fungus' ? 'Mesh_Stipe' : 'Mesh_Trunk';+ trunk.position.y = spec.trunkHeight / 2;+ root.add(trunk);++ for (let index = 0; index < spec.branchCount; index++) {+ const angle = (index / Math.max(1, spec.branchCount)) * Math.PI * 2 + (index % 2) * 0.13;+ const baseY = Math.max(0.12, spec.trunkHeight * (0.45 + (index % 3) * 0.12));+ const start = new THREE.Vector3(+ Math.cos(angle) * spec.trunkBase * 0.78,+ baseY,+ Math.sin(angle) * spec.trunkBase * 0.78,+ );+ const reach = spec.branchReach * (0.82 + (index % 3) * 0.09);+ const end = new THREE.Vector3(+ Math.cos(angle) * reach,+ Math.min(spec.trunkHeight + spec.branchRise, baseY + spec.branchRise + (index % 2) * 0.12),+ Math.sin(angle) * reach,+ );+ const branch = cylinderBetween(+ `Mesh_Branch_${index}`,+ start,+ end,+ Math.max(0.018, spec.trunkTip * 0.48),+ Math.max(0.008, spec.trunkTip * 0.16),+ [`vegetation.branch.primary.${index}`],+ );+ root.add(branch);+ if (spec.noFoliage) continue;+ const cluster = semantic(+ new THREE.Mesh(+ foliageGeometry(spec.foliageShape, spec.foliageScale * (0.88 + (index % 4) * 0.06)),+ index % 2 === 0 ? leafDark : leafLight,+ ),+ `vegetation.canopy.cluster.${index}`,+ 'vegetation.foliage',+ );+ cluster.name = `Mesh_Foliage_${index}`;+ cluster.position.copy(end);+ cluster.rotation.set(0.07 * (index % 2), angle + index * 0.07, 0.05 * ((index % 3) - 1));+ root.add(cluster);+ }++ if (!spec.noFoliage && spec.branchCount === 0) {+ const cluster = semantic(+ new THREE.Mesh(foliageGeometry(spec.foliageShape, spec.foliageScale), leafDark),+ 'vegetation.canopy.cluster.0',+ 'vegetation.foliage',+ );+ cluster.name = 'Mesh_Foliage_0';+ cluster.position.y = spec.trunkHeight;+ root.add(cluster);+ }+ root.updateMatrixWorld(true);+ return {+ intent: createAssetIntentV1({+ category: 'vegetation',+ vegetation: {+ subtype: spec.subtype,+ growthState: spec.growthState ?? (spec.subtype === 'bare/dead' ? 'bare' : 'lush'),+ canopyProfile:+ spec.canopyProfile ??+ (spec.subtype === 'conifer'+ ? 'conifer'+ : spec.subtype === 'bare/dead'+ ? 'bare/dead'+ : 'broadleaf'),+ },+ material: { mode: 'pbrRecipe' },+ }),+ scene: root,+ };+}++const CONTROL_SPECS = Object.freeze([+ {+ id: 'oak-control',+ subtype: 'tree',+ trunkHeight: 4,+ trunkBase: 0.42,+ trunkTip: 0.25,+ branchCount: 7,+ branchReach: 1.75,+ branchRise: 1.1,+ foliageScale: 0.72,+ },+ {+ id: 'conifer-control',+ subtype: 'conifer',+ trunkHeight: 4.8,+ trunkBase: 0.38,+ trunkTip: 0.2,+ branchCount: 9,+ branchReach: 1.45,+ branchRise: 0.65,+ foliageScale: 0.58,+ canopyProfile: 'conifer',+ },+ {+ id: 'palm-control',+ subtype: 'frond/palm',+ trunkHeight: 3.6,+ trunkBase: 0.28,+ trunkTip: 0.2,+ branchCount: 8,+ branchReach: 1.8,+ branchRise: 0.35,+ foliageScale: 0.7,+ foliageShape: 'blade',+ },+ {+ id: 'shrub-control',+ subtype: 'shrub',+ trunkHeight: 1.2,+ trunkBase: 0.24,+ trunkTip: 0.12,+ branchCount: 7,+ branchReach: 0.9,+ branchRise: 0.55,+ foliageScale: 0.5,+ },+ {+ id: 'grass-tuft-control',+ subtype: 'grass',+ trunkHeight: 0.6,+ trunkBase: 0.07,+ trunkTip: 0.025,+ branchCount: 7,+ branchReach: 0.34,+ branchRise: 0.7,+ foliageScale: 0.25,+ foliageShape: 'blade',+ },+ {+ id: 'vine-control',+ subtype: 'vine',+ trunkHeight: 1.8,+ trunkBase: 0.08,+ trunkTip: 0.035,+ branchCount: 6,+ branchReach: 0.65,+ branchRise: 1.1,+ foliageScale: 0.28,+ },+ {+ id: 'mushroom-control',+ subtype: 'fungus',+ trunkHeight: 0.8,+ trunkBase: 0.16,+ trunkTip: 0.12,+ branchCount: 0,+ branchReach: 0,+ branchRise: 0,+ foliageScale: 0.55,+ foliageShape: 'cap',+ },+ {+ id: 'flower-control',+ subtype: 'crop/flower',+ trunkHeight: 1.1,+ trunkBase: 0.055,+ trunkTip: 0.035,+ branchCount: 5,+ branchReach: 0.45,+ branchRise: 0.48,+ foliageScale: 0.26,+ },+ {+ id: 'succulent-control',+ subtype: 'succulent',+ trunkHeight: 0.5,+ trunkBase: 0.18,+ trunkTip: 0.13,+ branchCount: 6,+ branchReach: 0.42,+ branchRise: 0.45,+ foliageScale: 0.32,+ foliageShape: 'pad',+ },+ {+ id: 'bare-tree-control',+ subtype: 'bare/dead',+ growthState: 'bare',+ canopyProfile: 'bare/dead',+ trunkHeight: 3.8,+ trunkBase: 0.4,+ trunkTip: 0.22,+ branchCount: 7,+ branchReach: 1.5,+ branchRise: 1.2,+ foliageScale: 0,+ noFoliage: true,+ },+ {+ id: 'aquatic-control',+ subtype: 'aquatic',+ trunkHeight: 1.4,+ trunkBase: 0.08,+ trunkTip: 0.035,+ branchCount: 6,+ branchReach: 0.75,+ branchRise: 0.35,+ foliageScale: 0.42,+ foliageShape: 'blade',+ },+] as const satisfies readonly PlantSpec[]);++const CONTROL_FORBIDDEN_CODES = Object.freeze([+ 'VEG_CONTACT_MISSING',+ 'VEG_CONTACT_FLOATING',+ 'VEG_CONTACT_BURIED',+ 'VEG_MATERIAL_BURIED',+ 'VEG_SCOPE_EXTRA',+ 'VEG_FOLIAGE_DETACHED',+] as const);++function sparseAdversary(): W7VegetationCorpusPayload {+ const payload = buildPlant({ ...CONTROL_SPECS[0]!, id: 'sparse-adversary' });+ const clusters = payload.scene.children.filter((node) => /Mesh_Foliage_/.test(node.name));+ clusters.slice(2).forEach((node) => {+ payload.scene.remove(node);+ });+ clusters.slice(0, 2).forEach((node, index) => {+ node.scale.setScalar(0.18);+ node.position.set(index === 0 ? -2.4 : 2.4, 4.2, index === 0 ? -0.4 : 0.4);+ });+ payload.scene.updateMatrixWorld(true);+ payload.intent.vegetation!.growthState = 'lush';+ return payload;+}++function floatingAdversary(): W7VegetationCorpusPayload {+ const payload = buildPlant({ ...CONTROL_SPECS[3]!, id: 'floating-adversary' });+ payload.scene.getObjectByName('Contact_Ground')!.position.y = 0.12;+ payload.scene.updateMatrixWorld(true);+ return payload;+}++function baseClutterAdversary(): W7VegetationCorpusPayload {+ const payload = buildPlant({ ...CONTROL_SPECS[3]!, id: 'base-clutter-adversary' });+ const material = new THREE.MeshStandardMaterial({ color: 0x5d4129 });+ material.name = 'SoilMaterial';+ const soil = semantic(+ new THREE.Mesh(new THREE.CylinderGeometry(1.6, 1.6, 0.05, 16), material),+ 'terrain.soil.base',+ );+ soil.name = 'Mesh_Soil_Mound';+ soil.position.y = 0.025;+ payload.scene.add(soil);+ payload.scene.updateMatrixWorld(true);+ return payload;+}++export const W7_VEGETATION_CORPUS: readonly W7VegetationCorpusCase[] = Object.freeze([+ ...CONTROL_SPECS.map(+ (spec): W7VegetationCorpusCase => ({+ id: spec.id,+ kind: 'control',+ subtype: spec.subtype,+ description: `Helper-independent ${spec.id.replaceAll('-', ' ')} using current primitives.`,+ expectedCodes: [],+ forbiddenCodes: CONTROL_FORBIDDEN_CODES,+ build: () => buildPlant(spec),+ }),+ ),+ {+ id: 'sparse-adversary',+ kind: 'adversary',+ subtype: 'tree',+ description: 'Lush tree intent with two tiny, widely separated foliage clusters.',+ expectedCodes: ['VEG_CANOPY_OCCUPANCY_SIDE', 'VEG_CANOPY_OCCUPANCY_TOP'],+ forbiddenCodes: [],+ build: sparseAdversary,+ },+ {+ id: 'floating-adversary',+ kind: 'adversary',+ subtype: 'shrub',+ description: 'Trusted vegetation contact marker floats above asset-local ground.',+ expectedCodes: ['VEG_CONTACT_FLOATING'],+ forbiddenCodes: [],+ build: floatingAdversary,+ },+ {+ id: 'base-clutter-adversary',+ kind: 'adversary',+ subtype: 'shrub',+ description: 'Standalone shrub carries a corroborated unrequested soil mound.',+ expectedCodes: ['VEG_SCOPE_EXTRA'],+ forbiddenCodes: [],+ build: baseClutterAdversary,+ },+]);++export function w7VegetationCorpusDescriptor(): unknown {+ return {+ version: W7_VEGETATION_CORPUS_VERSION,+ cases: W7_VEGETATION_CORPUS.map((fixture) => ({+ id: fixture.id,+ kind: fixture.kind,+ subtype: fixture.subtype,+ description: fixture.description,+ expectedCodes: [...fixture.expectedCodes],+ forbiddenCodes: [...fixture.forbiddenCodes],+ })),+ };+}diff --git a/src/qa/vegetation.test.ts b/src/qa/vegetation.test.tsnew file mode 100644index 00000000..417b1f44--- /dev/null+++ b/src/qa/vegetation.test.ts@@ -0,0 +1,402 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import { createAssetIntentV1, stampSemanticMetadataV1 } from '../contracts';+import {+ evaluateVegetationAdvisoryQa,+ evaluateVegetationCanopyQa,+ evaluateVegetationContactQa,+ evaluateVegetationFoliageAttachmentQa,+ evaluateVegetationGrowthQa,+ evaluateVegetationMaterialQa,+ evaluateVegetationRepetitionQa,+ evaluateVegetationScopeQa,+ measureVegetationCanopy,+ measureVegetationFoliageAttachment,+ measureVegetationFoliageMaterials,+ measureVegetationGrowth,+ measureVegetationRepetition,+ VEGETATION_CONTACT_TOLERANCE_METERS,+} from './vegetation';+import { runDeterministicSceneQa } from './run';++function semantic<T extends THREE.Object3D>(node: T, ...roles: string[]): T {+ return stampSemanticMetadataV1(node, { roles });+}++function vegetationIntent(+ growthState: 'lush' | 'sparse' | 'bare' = 'lush',+ mode: 'flatOptimized' | 'pbrRecipe' = 'pbrRecipe',+) {+ return createAssetIntentV1({+ category: 'vegetation',+ vegetation: {+ subtype: growthState === 'bare' ? 'bare/dead' : 'tree',+ growthState,+ canopyProfile: growthState === 'bare' ? 'bare/dead' : 'broadleaf',+ },+ material: { mode },+ });+}++function treeScene(+ options: {+ contactY?: number;+ trunkBottomY?: number;+ sparseCanopy?: boolean;+ foliageColors?: number[];+ clutter?: boolean;+ contact?: boolean;+ } = {},+): THREE.Group {+ const root = new THREE.Group();+ root.name = 'VegetationRoot';+ const trunkBottomY = options.trunkBottomY ?? 0;+ const trunkHeight = 3;+ const trunk = semantic(+ new THREE.Mesh(+ new THREE.CylinderGeometry(0.24, 0.34, trunkHeight, 8),+ new THREE.MeshStandardMaterial({ color: 0x6b4426, roughness: 0.9 }),+ ),+ 'vegetation.trunk',+ );+ trunk.name = 'Mesh_Trunk';+ trunk.position.y = trunkBottomY + trunkHeight / 2;+ root.add(trunk);++ if (options.contact !== false) {+ const contact = semantic(new THREE.Group(), 'vegetation.contact.ground');+ contact.name = 'Contact_Ground';+ contact.position.y = options.contactY ?? 0;+ root.add(contact);+ }++ const colors = options.foliageColors ?? [0x2f6f32, 0x5f9142];+ const positions = options.sparseCanopy+ ? [+ [-1.8, 4, 0],+ [1.8, 4, 0],+ ]+ : [+ [-0.7, 3.8, 0],+ [0.7, 3.9, 0.2],+ [0, 4.45, -0.45],+ [0.1, 3.65, 0.75],+ ];+ positions.forEach(([x, y, z], index) => {+ const foliage = semantic(+ new THREE.Mesh(+ new THREE.SphereGeometry(options.sparseCanopy ? 0.25 : 0.9, 8, 6),+ new THREE.MeshStandardMaterial({ color: colors[index % colors.length], roughness: 0.86 }),+ ),+ `vegetation.canopy.cluster.${index}`,+ 'vegetation.foliage',+ );+ foliage.name = `Mesh_Canopy_${index}`;+ foliage.position.set(x!, y!, z!);+ root.add(foliage);+ });++ if (options.clutter) {+ const soil = semantic(+ new THREE.Mesh(+ new THREE.CylinderGeometry(2.2, 2.2, 0.05, 16),+ Object.assign(new THREE.MeshStandardMaterial({ color: 0x5d4129 }), {+ name: 'SoilMaterial',+ }),+ ),+ 'terrain.soil.base',+ );+ soil.name = 'Mesh_Soil_Mound';+ soil.position.y = 0.025;+ root.add(soil);+ }+ root.updateMatrixWorld(true);+ return root;+}++function cylinderBetween(+ name: string,+ start: THREE.Vector3,+ end: THREE.Vector3,+ baseRadius: number,+ tipRadius: number,+ roles: string[],+): THREE.Mesh {+ const direction = end.clone().sub(start);+ const mesh = new THREE.Mesh(+ new THREE.CylinderGeometry(tipRadius, baseRadius, direction.length(), 12),+ new THREE.MeshStandardMaterial({ color: 0x6b4426 }),+ );+ if (roles.length > 0) semantic(mesh, ...roles);+ mesh.name = name;+ mesh.position.copy(start).add(end).multiplyScalar(0.5);+ mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction.normalize());+ return mesh;+}++function growthScene(options: { badTaper?: boolean; fallback?: boolean } = {}): THREE.Group {+ const root = new THREE.Group();+ root.name = 'GrowthFixture';+ const trunk = new THREE.Mesh(+ new THREE.CylinderGeometry(0.24, 0.4, 4, 12),+ new THREE.MeshStandardMaterial({ color: 0x6b4426 }),+ );+ trunk.name = 'Mesh_Trunk';+ trunk.position.y = 2;+ if (!options.fallback) semantic(trunk, 'vegetation.trunk');+ root.add(trunk);+ const branch = cylinderBetween(+ 'Mesh_Branch_Primary',+ new THREE.Vector3(0.28, 2.1, 0),+ new THREE.Vector3(1.8, 3.25, 0),+ options.badTaper ? 0.04 : 0.12,+ options.badTaper ? 0.42 : 0.04,+ options.fallback ? [] : ['vegetation.branch.primary.0'],+ );+ root.add(branch);+ root.updateMatrixWorld(true);+ return root;+}++function attachmentScene(detached = false): THREE.Group {+ const root = growthScene();+ for (let index = 0; index < 4; index++) {+ const cluster = semantic(+ new THREE.Mesh(+ new THREE.SphereGeometry(0.36, 8, 6),+ new THREE.MeshStandardMaterial({ color: 0x34743b }),+ ),+ `vegetation.canopy.cluster.${index}`,+ 'vegetation.foliage',+ );+ cluster.name = `Mesh_Foliage_${index}`;+ cluster.position.set(+ index === 0 && detached ? 4.5 : 1.45 + index * 0.08,+ 3.05 + index * 0.08,+ (index - 1.5) * 0.16,+ );+ cluster.scale.setScalar(1 + index * 0.04);+ cluster.rotation.y = index * 0.17;+ root.add(cluster);+ }+ root.updateMatrixWorld(true);+ return root;+}++function radialScene(topiary = false): {+ scene: THREE.Group;+ intent: ReturnType<typeof vegetationIntent>;+} {+ const root = growthScene();+ for (let index = 0; index < 6; index++) {+ const angle = (index / 6) * Math.PI * 2;+ const cluster = semantic(+ new THREE.Mesh(+ new THREE.SphereGeometry(0.35, 8, 6),+ new THREE.MeshStandardMaterial({ color: 0x34743b }),+ ),+ `vegetation.canopy.cluster.${index}`,+ );+ cluster.name = `Mesh_Radial_${index}`;+ cluster.position.set(Math.cos(angle) * 1.6, 3.5, Math.sin(angle) * 1.6);+ root.add(cluster);+ }+ root.updateMatrixWorld(true);+ const intent = vegetationIntent();+ if (topiary && intent.vegetation) intent.vegetation.canopyProfile = 'topiary';+ return { scene: root, intent };+}++describe('W6 vegetation QA', () => {+ test('VEG-003 blocks missing, floating, buried, and materially buried contacts', () => {+ const intent = vegetationIntent();+ expect(+ evaluateVegetationContactQa({ intent, scene: treeScene({ contact: false }) }).map(+ (finding) => finding.code,+ ),+ ).toContain('VEG_CONTACT_MISSING');+ expect(+ evaluateVegetationContactQa({+ intent,+ scene: treeScene({ contactY: VEGETATION_CONTACT_TOLERANCE_METERS + 0.01 }),+ }).map((finding) => finding.code),+ ).toContain('VEG_CONTACT_FLOATING');+ expect(+ evaluateVegetationContactQa({+ intent,+ scene: treeScene({ contactY: -VEGETATION_CONTACT_TOLERANCE_METERS - 0.01 }),+ }).map((finding) => finding.code),+ ).toContain('VEG_CONTACT_BURIED');+ expect(+ evaluateVegetationContactQa({+ intent,+ scene: treeScene({ trunkBottomY: -VEGETATION_CONTACT_TOLERANCE_METERS - 0.01 }),+ }).map((finding) => finding.code),+ ).toContain('VEG_MATERIAL_BURIED');+ });++ test('VEG-003 evaluates asset-local contact under a transformed root', () => {+ const scene = treeScene();+ scene.position.set(10, 4, -3);+ scene.rotation.set(0.1, 0.8, -0.15);+ scene.scale.setScalar(1.3);+ scene.updateMatrixWorld(true);+ expect(evaluateVegetationContactQa({ intent: vegetationIntent(), scene })).toEqual([]);+ });++ test('VEG-003 accepts a nonrendering ground-contact frame on the semantic trunk', () => {+ const scene = treeScene({ contact: false });+ const trunk = scene.getObjectByName('Mesh_Trunk')!;+ stampSemanticMetadataV1(trunk, {+ roles: ['vegetation.trunk', 'vegetation.contact.ground'],+ frames: [+ {+ id: 'ground-contact',+ translation: [0, -1.5, 0],+ rotation: [0, 0, 0, 1],+ },+ ],+ });+ scene.updateMatrixWorld(true);+ expect(evaluateVegetationContactQa({ intent: vegetationIntent(), scene })).toEqual([]);+ });++ test('VEG-004 needs corroborating scope evidence and remains observe-only in the registry', () => {+ const intent = vegetationIntent();+ const clean = treeScene();+ expect(evaluateVegetationScopeQa({ intent, scene: clean })).toEqual([]);+ const cluttered = treeScene({ clutter: true });+ const direct = evaluateVegetationScopeQa({ intent, scene: cluttered });+ expect(direct.map((finding) => finding.code)).toContain('VEG_SCOPE_EXTRA');+ expect(direct.every((finding) => finding.disposition === 'warn')).toBe(true);+ const report = runDeterministicSceneQa({ intent, scene: cluttered });+ const scope = report.dimensions.promptAlignment.findings.find(+ (finding) => finding.code === 'VEG_SCOPE_EXTRA',+ );+ expect(scope?.disposition).toBe('observe');+ expect(report.disposition).not.toBe('block');+ });++ test('VEG-014 measures front, side, top occupancy and canopy-to-trunk ratio by profile', () => {+ const intent = vegetationIntent();+ const full = measureVegetationCanopy(intent, treeScene());+ expect(full.profile).toBe('broadleaf');+ expect(full.source).toBe('semantic');+ expect(full.frontOccupancy).toBeGreaterThan(0.4);+ expect(full.sideOccupancy).toBeGreaterThan(0.4);+ expect(full.topOccupancy).toBeGreaterThan(0.32);+ expect(full.canopyToTrunkVolumeRatio).toBeGreaterThan(1.5);++ const sparseFindings = evaluateVegetationCanopyQa({+ intent,+ scene: treeScene({ sparseCanopy: true }),+ });+ expect(sparseFindings.some((finding) => finding.code.startsWith('VEG_CANOPY_OCCUPANCY_'))).toBe(+ true,+ );+ expect(+ sparseFindings.every((finding) => finding.measurement && finding.disposition === 'warn'),+ ).toBe(true);+ });++ test('VEG-014 treats explicitly bare/dead growth as a distinct zero-canopy profile', () => {+ const scene = treeScene();+ for (const node of [...scene.children]) {+ if (/Canopy/.test(node.name)) scene.remove(node);+ }+ const intent = vegetationIntent('bare');+ const measured = measureVegetationCanopy(intent, scene);+ expect(measured.profile).toBe('bare/dead');+ expect(measured.canopyNodeCount).toBe(0);+ expect(evaluateVegetationCanopyQa({ intent, scene })).toEqual([]);+ });++ test('VEG-018 keeps optimized one-role foliage while rich organic mode asks for restrained variation', () => {+ const oneColor = treeScene({ foliageColors: [0x3f7f3a] });+ const optimized = vegetationIntent('lush', 'flatOptimized');+ expect(measureVegetationFoliageMaterials(optimized, oneColor)).toMatchObject({+ valueRoleCount: 1,+ coherent: true,+ });+ expect(evaluateVegetationMaterialQa({ intent: optimized, scene: oneColor })).toEqual([]);++ const rich = vegetationIntent('lush', 'pbrRecipe');+ expect(measureVegetationFoliageMaterials(rich, oneColor).coherent).toBe(false);+ expect(evaluateVegetationMaterialQa({ intent: rich, scene: oneColor })[0]).toMatchObject({+ code: 'VEG_FOLIAGE_VALUE_ROLES',+ dimension: 'visualQuality',+ disposition: 'warn',+ });+ const varied = treeScene({ foliageColors: [0x245b2d, 0x72a94d] });+ expect(measureVegetationFoliageMaterials(rich, varied).coherent).toBe(true);+ expect(evaluateVegetationMaterialQa({ intent: rich, scene: varied })).toEqual([]);+ });++ test('VEG-013 measures semantic and fallback taper/length ratios with subtype bands', () => {+ const intent = vegetationIntent();+ const good = measureVegetationGrowth(intent, growthScene());+ expect(good).toMatchObject({+ subtype: 'tree',+ source: 'semantic',+ trunkCount: 1,+ branchCount: 1,+ });+ expect(good.nodes.every((node) => node.taperRatio !== null)).toBe(true);+ expect(evaluateVegetationGrowthQa({ intent, scene: growthScene() })).toEqual([]);++ const fallback = measureVegetationGrowth(intent, growthScene({ fallback: true }));+ expect(fallback.source).toBe('fallback');+ const bad = evaluateVegetationGrowthQa({ intent, scene: growthScene({ badTaper: true }) });+ expect(bad.map((finding) => finding.code)).toContain('VEG_GROWTH_TAPER_OUTLIER');+ expect(bad.every((finding) => finding.measurement && finding.disposition === 'warn')).toBe(+ true,+ );+ });++ test('VEG-015 lists detached foliage with nearest-support gap measurements', () => {+ const attached = measureVegetationFoliageAttachment(attachmentScene());+ expect(attached.source).toBe('semantic');+ expect(attached.clusters).toHaveLength(4);+ expect(attached.clusters.every((cluster) => !cluster.detached)).toBe(true);+ const findings = evaluateVegetationFoliageAttachmentQa({+ intent: vegetationIntent(),+ scene: attachmentScene(true),+ });+ expect(findings).toHaveLength(1);+ expect(findings[0]).toMatchObject({+ code: 'VEG_FOLIAGE_DETACHED',+ disposition: 'warn',+ affected: { node: 'Mesh_Foliage_0' },+ });+ expect(findings[0]!.measurement?.actual).toBeGreaterThan(+ findings[0]!.measurement?.threshold ?? 0,+ );+ });++ test('VEG-016 detects identical transforms and perfect radial lockstep but suppresses formal topiary', () => {+ const regular = radialScene();+ const measured = measureVegetationRepetition(regular.intent, regular.scene);+ expect(measured.identicalTransformGroups[0]?.nodes).toHaveLength(6);+ expect(measured.perfectRadialLockstep).toBe(true);+ expect(evaluateVegetationRepetitionQa(regular).map((finding) => finding.code)).toEqual([+ 'VEG_CLUSTER_TRANSFORM_REPEAT',+ 'VEG_CLUSTER_RADIAL_LOCKSTEP',+ ]);++ const topiary = radialScene(true);+ expect(measureVegetationRepetition(topiary.intent, topiary.scene).suppressedForTopiary).toBe(+ true,+ );+ expect(evaluateVegetationRepetitionQa(topiary)).toEqual([]);+ });++ test('advisory aggregation never upgrades heuristic findings to blockers', () => {+ const findings = evaluateVegetationAdvisoryQa({+ intent: vegetationIntent(),+ scene: treeScene({ clutter: true, sparseCanopy: true, foliageColors: [0x3f7f3a] }),+ });+ expect(findings.length).toBeGreaterThan(2);+ expect(findings.every((finding) => finding.disposition === 'warn')).toBe(true);+ });+});diff --git a/src/qa/vegetation.ts b/src/qa/vegetation.tsnew file mode 100644index 00000000..6509bcd1--- /dev/null+++ b/src/qa/vegetation.ts@@ -0,0 +1,1113 @@+import * as THREE from 'three';++import {+ readSemanticMetadataV1,+ type AssetIntentV1,+ type VegetationCanopyProfile,+} from '../contracts';+import { conformancePromotionAuthorization, KILN_ENGINE_QA_OWNER, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';++const PROFILE = 'vegetation.semantic';+export const VEGETATION_CONTACT_TOLERANCE_METERS = 0.02;+const RASTER_SIZE = 48;++interface LocalBounds {+ node: THREE.Object3D;+ box: THREE.Box3;+ roles: string[];+ source: 'semantic' | 'fallback';+}++interface VegetationContactMarker {+ node: THREE.Object3D;+ frameTranslation?: readonly [number, number, number];+}++export interface VegetationCanopyMeasurementsV1 {+ schemaVersion: 1;+ profile: VegetationCanopyProfile;+ source: 'semantic' | 'fallback' | 'none';+ canopyNodeCount: number;+ trunkNodeCount: number;+ frontOccupancy: number;+ sideOccupancy: number;+ topOccupancy: number;+ canopyToTrunkVolumeRatio: number | null;+}++export interface VegetationFoliageMaterialMeasurementsV1 {+ schemaVersion: 1;+ mode: AssetIntentV1['material']['mode'];+ foliageNodeCount: number;+ valueRoleCount: number;+ valueRange: number;+ coherent: boolean;+}++export interface VegetationGrowthNodeMeasurementV1 {+ node: string;+ nodePath: string;+ kind: 'trunk' | 'branch';+ source: 'semantic' | 'fallback';+ lengthMeters: number;+ baseRadiusMeters: number;+ tipRadiusMeters: number;+ taperRatio: number | null;+ lengthRadiusRatio: number | null;+ expectedTaperRatio: string;+ expectedLengthRadiusRatio: string;+ taperOutlier: boolean;+ lengthRadiusOutlier: boolean;+}++export interface VegetationGrowthMeasurementsV1 {+ schemaVersion: 1;+ subtype: NonNullable<AssetIntentV1['vegetation']>['subtype'];+ source: 'semantic' | 'fallback' | 'mixed' | 'none';+ trunkCount: number;+ branchCount: number;+ nodes: VegetationGrowthNodeMeasurementV1[];+}++export interface VegetationFoliageAttachmentMeasurementV1 {+ node: string;+ nodePath: string;+ source: 'semantic' | 'fallback';+ nearestSupport: string | null;+ gapMeters: number | null;+ thresholdMeters: number;+ detached: boolean;+}++export interface VegetationFoliageAttachmentMeasurementsV1 {+ schemaVersion: 1;+ source: 'semantic' | 'fallback' | 'mixed' | 'none';+ supportNodeCount: number;+ foliageClusterCount: number;+ clusters: VegetationFoliageAttachmentMeasurementV1[];+}++export interface VegetationRepetitionMeasurementsV1 {+ schemaVersion: 1;+ source: 'semantic' | 'fallback' | 'mixed' | 'none';+ clusterCount: number;+ identicalTransformGroups: Array<{ signature: string; nodes: string[] }>;+ radialGapRangeRadians: number | null;+ radialRadiusSpreadRatio: number | null;+ perfectRadialLockstep: boolean;+ suppressedForTopiary: boolean;+}++const stable = (value: number): number => Math.round(value * 1_000_000) / 1_000_000;++function rolesOf(node: THREE.Object3D): string[] {+ return readSemanticMetadataV1(node)?.roles ?? [];+}++function pathOf(node: THREE.Object3D, root: THREE.Object3D): string {+ const names: string[] = [];+ let cursor: THREE.Object3D | null = node;+ while (cursor) {+ names.push(cursor.name || cursor.type);+ if (cursor === root) break;+ cursor = cursor.parent;+ }+ return names.reverse().join('/');+}++function localPoint(rootInverse: THREE.Matrix4, node: THREE.Object3D): THREE.Vector3 {+ return node.getWorldPosition(new THREE.Vector3()).applyMatrix4(rootInverse);+}++function meshLocalBox(mesh: THREE.Mesh, rootInverse: THREE.Matrix4): THREE.Box3 | undefined {+ if (!(mesh.geometry instanceof THREE.BufferGeometry)) return undefined;+ mesh.geometry.computeBoundingBox();+ const source = mesh.geometry.boundingBox;+ if (!source || source.isEmpty()) return undefined;+ const transform = rootInverse.clone().multiply(mesh.matrixWorld);+ const result = new THREE.Box3();+ for (const x of [source.min.x, source.max.x]) {+ for (const y of [source.min.y, source.max.y]) {+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(transform));+ }+ }+ }+ return result;+}++function collectRenderableBounds(root: THREE.Object3D): LocalBounds[] {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const values: LocalBounds[] = [];+ root.traverse((node) => {+ if (!(node instanceof THREE.Mesh)) return;+ const box = meshLocalBox(node, inverse);+ if (!box) return;+ const roles = rolesOf(node);+ values.push({ node, box, roles, source: roles.length > 0 ? 'semantic' : 'fallback' });+ });+ return values;+}++function finding(context: QaContext, value: Omit<QaFinding, 'profile'>): QaFinding {+ return { ...value, profile: context.intent.qaProfile || PROFILE };+}++function vegetationIntent(intent: AssetIntentV1) {+ return intent.category === 'vegetation' ? intent.vegetation : undefined;+}++/** Exact, trusted contact contract. Name/material inference never enters this blocker path. */+export function evaluateVegetationContactQa(context: QaContext): readonly QaFinding[] {+ const trusted = vegetationIntent(context.intent);+ if (!trusted?.grounded || !(context.scene instanceof THREE.Object3D)) return [];+ const root = context.scene;+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const contacts: VegetationContactMarker[] = [];+ const semanticSupports: THREE.Object3D[] = [];+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ const roles = metadata?.roles ?? [];+ if (+ roles.some(+ (role) =>+ role === 'vegetation.contact' ||+ role === 'vegetation.contact.ground' ||+ role === 'contact.ground',+ )+ ) {+ const frame = metadata?.frames.find(+ (value) => value.id === 'ground-contact' || value.id === 'vegetation-ground-contact',+ );+ contacts.push({+ node,+ ...(frame ? { frameTranslation: frame.translation } : {}),+ });+ }+ if (+ roles.some(+ (role) =>+ role === 'vegetation.trunk' ||+ role === 'vegetation.stem' ||+ role === 'vegetation.root' ||+ role === 'vegetation.base' ||+ role.startsWith('vegetation.support.'),+ )+ ) {+ semanticSupports.push(node);+ }+ });+ if (contacts.length === 0) {+ return [+ finding(context, {+ code: 'VEG_CONTACT_MISSING',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: 'Standalone grounded vegetation requires one semantic ground-contact marker.',+ affected: { node: root.name || 'vegetation-root' },+ measurement: { name: 'groundContactCount', actual: 0, expected: '>=1' },+ viewHints: ['right', 'vegetation.base-contact'],+ repairText:+ 'Add a vegetation.contact.ground semantic marker at asset-local Y=0 and seat the plant base on it.',+ }),+ ];+ }++ const findings: QaFinding[] = [];+ for (const contact of contacts) {+ const contactPoint = contact.frameTranslation+ ? new THREE.Vector3(...contact.frameTranslation)+ .applyMatrix4(contact.node.matrixWorld)+ .applyMatrix4(inverse)+ : localPoint(inverse, contact.node);+ const y = contactPoint.y;+ if (Math.abs(y) <= VEGETATION_CONTACT_TOLERANCE_METERS) continue;+ const floating = y > 0;+ findings.push(+ finding(context, {+ code: floating ? 'VEG_CONTACT_FLOATING' : 'VEG_CONTACT_BURIED',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `${contact.node.name || 'Vegetation contact'} is ${Math.abs(y).toFixed(6)} m ${floating ? 'above' : 'below'} asset-local ground.`,+ affected: {+ node: contact.node.name || 'vegetation-contact',+ nodePath: pathOf(contact.node, root),+ },+ measurement: {+ name: 'contactY',+ actual: stable(y),+ expected: 0,+ threshold: VEGETATION_CONTACT_TOLERANCE_METERS,+ unit: 'm',+ },+ viewHints: ['right', 'vegetation.base-contact'],+ repairText: `Move ${contact.node.name || 'the contact marker'} or its ground-contact frame to asset-local Y=0 without moving unrelated canopy parts.`,+ }),+ );+ }++ for (const support of semanticSupports) {+ let minimumY = Infinity;+ support.traverse((node) => {+ if (!(node instanceof THREE.Mesh)) return;+ const box = meshLocalBox(node, inverse);+ if (box) minimumY = Math.min(minimumY, box.min.y);+ });+ if (!Number.isFinite(minimumY) || minimumY >= -VEGETATION_CONTACT_TOLERANCE_METERS) continue;+ findings.push(+ finding(context, {+ code: 'VEG_MATERIAL_BURIED',+ disposition: 'block',+ dimension: 'categoryReadiness',+ message: `${support.name || 'Vegetation support'} extends materially below the standalone ground plane.`,+ affected: { node: support.name || 'vegetation-support', nodePath: pathOf(support, root) },+ measurement: {+ name: 'supportMinimumY',+ actual: stable(minimumY),+ expected: 0,+ threshold: VEGETATION_CONTACT_TOLERANCE_METERS,+ unit: 'm',+ },+ viewHints: ['right', 'vegetation.base-contact'],+ repairText:+ 'Raise or trim the declared trunk/stem/root support so its visible material stops at Y=0.',+ }),+ );+ }+ return findings;+}++const CLUTTER_NAME =+ /(?:^|[._ -])(?:terrain|soil|dirt|mound|rock|stone|pot|planter|grass[._ -]?skirt|base[._ -]?(?:disk|plate))(?:$|[._ -])/i;++function materialNames(node: THREE.Object3D): string[] {+ if (!(node instanceof THREE.Mesh)) return [];+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ return materials.filter(Boolean).map((material) => material.name ?? '');+}++/** Heuristic scope evidence. It is intentionally advisory and never a hard failure alone. */+export function evaluateVegetationScopeQa(context: QaContext): readonly QaFinding[] {+ const trusted = vegetationIntent(context.intent);+ if (!trusted?.standalone || !(context.scene instanceof THREE.Object3D)) return [];+ const root = context.scene;+ const renderables = collectRenderableBounds(root);+ if (renderables.length === 0) return [];+ const overall = renderables.reduce((box, value) => box.union(value.box), new THREE.Box3());+ const overallSize = overall.getSize(new THREE.Vector3());+ const findings: QaFinding[] = [];+ for (const value of renderables) {+ const size = value.box.getSize(new THREE.Vector3());+ const center = value.box.getCenter(new THREE.Vector3());+ const names = [value.node.name, ...value.roles];+ const nameEvidence = names.some((name) => CLUTTER_NAME.test(name));+ const roleEvidence = value.roles.some((role) =>+ /(?:terrain|soil|rock|pot|planter|base)/i.test(role),+ );+ const materialEvidence = materialNames(value.node).some((name) => CLUTTER_NAME.test(name));+ const footprintRatio = (size.x * size.z) / Math.max(1e-9, overallSize.x * overallSize.z);+ const flatEvidence =+ footprintRatio >= 0.35 &&+ size.y <= Math.max(0.08, overallSize.y * 0.08) &&+ center.y <= VEGETATION_CONTACT_TOLERANCE_METERS + size.y;+ const evidence = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);+ if (evidence.length < 2) continue;+ findings.push(+ finding(context, {+ code: 'VEG_SCOPE_EXTRA',+ disposition: 'warn',+ dimension: 'promptAlignment',+ message: `${value.node.name || 'Renderable'} is likely unrequested standalone-vegetation base clutter; review before removal.`,+ affected: {+ node: value.node.name || 'vegetation-extra',+ nodePath: pathOf(value.node, root),+ },+ measurement: {+ name: 'scopeEvidence',+ actual: [+ nameEvidence ? 'name' : '',+ roleEvidence ? 'role' : '',+ materialEvidence ? 'material' : '',+ flatEvidence ? 'flat-footprint' : '',+ ]+ .filter(Boolean)+ .join(','),+ expected: 'standalone plant/fungus only',+ },+ viewHints: ['top', 'three-quarter', 'vegetation.base-contact'],+ }),+ );+ }+ return findings;+}++function unionVolume(boxes: readonly THREE.Box3[]): number {+ if (boxes.length === 0) return 0;+ const union = boxes.reduce((result, box) => result.union(box), new THREE.Box3());+ const size = union.getSize(new THREE.Vector3());+ return size.x * size.y * size.z;+}++function projectedOccupancy(+ boxes: readonly THREE.Box3[],+ axes: readonly [0 | 1 | 2, 0 | 1 | 2],+): number {+ if (boxes.length === 0) return 0;+ const minimum = [Infinity, Infinity];+ const maximum = [-Infinity, -Infinity];+ for (const box of boxes) {+ const min = [box.min.x, box.min.y, box.min.z];+ const max = [box.max.x, box.max.y, box.max.z];+ for (const dimension of [0, 1] as const) {+ minimum[dimension] = Math.min(minimum[dimension]!, min[axes[dimension]]!);+ maximum[dimension] = Math.max(maximum[dimension]!, max[axes[dimension]]!);+ }+ }+ const spans = [maximum[0]! - minimum[0]!, maximum[1]! - minimum[1]!];+ if (spans[0]! <= 1e-9 || spans[1]! <= 1e-9) return 0;+ const occupied = new Uint8Array(RASTER_SIZE * RASTER_SIZE);+ for (const box of boxes) {+ const min = [box.min.x, box.min.y, box.min.z];+ const max = [box.max.x, box.max.y, box.max.z];+ const x0 = Math.max(+ 0,+ Math.floor(((min[axes[0]]! - minimum[0]!) / spans[0]!) * (RASTER_SIZE - 1)),+ );+ const x1 = Math.min(+ RASTER_SIZE - 1,+ Math.ceil(((max[axes[0]]! - minimum[0]!) / spans[0]!) * (RASTER_SIZE - 1)),+ );+ const y0 = Math.max(+ 0,+ Math.floor(((min[axes[1]]! - minimum[1]!) / spans[1]!) * (RASTER_SIZE - 1)),+ );+ const y1 = Math.min(+ RASTER_SIZE - 1,+ Math.ceil(((max[axes[1]]! - minimum[1]!) / spans[1]!) * (RASTER_SIZE - 1)),+ );+ for (let y = y0; y <= y1; y++) {+ for (let x = x0; x <= x1; x++) occupied[y * RASTER_SIZE + x] = 1;+ }+ }+ return stable(occupied.reduce((sum, value) => sum + value, 0) / occupied.length);+}++function matchesAny(value: LocalBounds, patterns: readonly RegExp[]): boolean {+ const candidates = [value.node.name, ...value.roles];+ return candidates.some((candidate) => patterns.some((pattern) => pattern.test(candidate)));+}++const CANOPY_PATTERNS = [/(?:^|[._ -])(?:canopy|foliage|leaf|leaves|needle|frond)(?:$|[._ -])/i];+const TRUNK_PATTERNS = [/(?:^|[._ -])(?:trunk|stem|stalk|branch-primary)(?:$|[._ -])/i];+const BRANCH_PATTERNS = [+ /(?:^|[._ -])(?:branch|twig|bough|limb)(?:$|[._ -])/i,+ /^vegetation\.branch(?:\.|$)/i,+];++type GrowthBand = Readonly<{+ trunk: Readonly<{ taper: readonly [number, number]; lengthRadius: readonly [number, number] }>;+ branch: Readonly<{ taper: readonly [number, number]; lengthRadius: readonly [number, number] }>;+}>;++/**+ * Broad measurement bands, not aesthetic truth. They only localize conspicuous geometry outliers and+ * remain observe-only under D-02. Different growth forms intentionally use different ranges.+ */+export const VEGETATION_GROWTH_BANDS_V1: Readonly<+ Record<NonNullable<AssetIntentV1['vegetation']>['subtype'], GrowthBand>+> = Object.freeze({+ tree: {+ trunk: { taper: [0.35, 1.05], lengthRadius: [4, 80] },+ branch: { taper: [0.12, 1.05], lengthRadius: [4, 100] },+ },+ conifer: {+ trunk: { taper: [0.25, 1.05], lengthRadius: [6, 110] },+ branch: { taper: [0.1, 1.05], lengthRadius: [5, 140] },+ },+ shrub: {+ trunk: { taper: [0.25, 1.1], lengthRadius: [2, 65] },+ branch: { taper: [0.1, 1.1], lengthRadius: [2, 80] },+ },+ grass: {+ trunk: { taper: [0.05, 1.15], lengthRadius: [6, 260] },+ branch: { taper: [0.05, 1.15], lengthRadius: [5, 260] },+ },+ 'frond/palm': {+ trunk: { taper: [0.35, 1.05], lengthRadius: [6, 140] },+ branch: { taper: [0.04, 1.1], lengthRadius: [8, 300] },+ },+ vine: {+ trunk: { taper: [0.1, 1.15], lengthRadius: [8, 320] },+ branch: { taper: [0.04, 1.15], lengthRadius: [8, 360] },+ },+ 'crop/flower': {+ trunk: { taper: [0.15, 1.1], lengthRadius: [5, 220] },+ branch: { taper: [0.05, 1.15], lengthRadius: [4, 240] },+ },+ succulent: {+ trunk: { taper: [0.3, 1.2], lengthRadius: [1.2, 35] },+ branch: { taper: [0.15, 1.2], lengthRadius: [1.2, 50] },+ },+ fungus: {+ trunk: { taper: [0.25, 1.25], lengthRadius: [1.2, 45] },+ branch: { taper: [0.1, 1.25], lengthRadius: [1.2, 60] },+ },+ aquatic: {+ trunk: { taper: [0.08, 1.15], lengthRadius: [4, 260] },+ branch: { taper: [0.04, 1.15], lengthRadius: [4, 300] },+ },+ 'bare/dead': {+ trunk: { taper: [0.25, 1.05], lengthRadius: [4, 100] },+ branch: { taper: [0.08, 1.05], lengthRadius: [3, 140] },+ },+ custom: {+ trunk: { taper: [0.05, 1.25], lengthRadius: [1.2, 320] },+ branch: { taper: [0.03, 1.25], lengthRadius: [1.2, 360] },+ },+});++function measurementSource(+ values: readonly { source: 'semantic' | 'fallback' }[],+): 'semantic' | 'fallback' | 'mixed' | 'none' {+ if (values.length === 0) return 'none';+ const semantic = values.some((value) => value.source === 'semantic');+ const fallback = values.some((value) => value.source === 'fallback');+ return semantic && fallback ? 'mixed' : semantic ? 'semantic' : 'fallback';+}++function roleOrNameSource(+ value: LocalBounds,+ patterns: readonly RegExp[],+): 'semantic' | 'fallback' | undefined {+ if (value.roles.some((role) => patterns.some((pattern) => pattern.test(role)))) return 'semantic';+ if (patterns.some((pattern) => pattern.test(value.node.name))) return 'fallback';+ return undefined;+}++interface GrowthCandidate extends LocalBounds {+ kind: 'trunk' | 'branch';+ growthSource: 'semantic' | 'fallback';+}++function growthCandidates(root: THREE.Object3D): GrowthCandidate[] {+ const result: GrowthCandidate[] = [];+ for (const value of collectRenderableBounds(root)) {+ const branchSource = roleOrNameSource(value, BRANCH_PATTERNS);+ const trunkSource = roleOrNameSource(value, TRUNK_PATTERNS);+ if (branchSource) result.push({ ...value, kind: 'branch', growthSource: branchSource });+ else if (trunkSource) result.push({ ...value, kind: 'trunk', growthSource: trunkSource });+ }+ return result;+}++function boxDistanceToPoint(box: THREE.Box3, point: THREE.Vector3): number {+ return box.distanceToPoint(point);+}++function endpointRadius(+ position: THREE.BufferAttribute | THREE.InterleavedBufferAttribute,+ axis: 0 | 1 | 2,+ axisValue: number,+ tolerance: number,+ scale: THREE.Vector3,+): { center: THREE.Vector3; radius: number } | undefined {+ const radialAxes = ([0, 1, 2] as const).filter((value) => value !== axis);+ const points: THREE.Vector3[] = [];+ const point = new THREE.Vector3();+ for (let index = 0; index < position.count; index++) {+ point.fromBufferAttribute(position, index);+ if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance) points.push(point.clone());+ }+ if (points.length === 0) return undefined;+ const center = new THREE.Vector3();+ center.setComponent(axis, axisValue);+ for (const radialAxis of radialAxes) {+ center.setComponent(+ radialAxis,+ points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length,+ );+ }+ let radius = 0;+ for (const value of points) {+ const a =+ (value.getComponent(radialAxes[0]!) - center.getComponent(radialAxes[0]!)) *+ Math.abs(scale.getComponent(radialAxes[0]!));+ const b =+ (value.getComponent(radialAxes[1]!) - center.getComponent(radialAxes[1]!)) *+ Math.abs(scale.getComponent(radialAxes[1]!));+ radius = Math.max(radius, Math.hypot(a, b));+ }+ return { center, radius };+}++function growthNodeMeasurement(+ root: THREE.Object3D,+ candidate: GrowthCandidate,+ allCandidates: readonly GrowthCandidate[],+ band: GrowthBand,+): VegetationGrowthNodeMeasurementV1 | undefined {+ if (!(candidate.node instanceof THREE.Mesh)) return undefined;+ const geometry = candidate.node.geometry;+ const position = geometry.getAttribute('position');+ if (!position || position.count < 2) return undefined;+ geometry.computeBoundingBox();+ const geometryBox = geometry.boundingBox;+ if (!geometryBox || geometryBox.isEmpty()) return undefined;++ root.updateWorldMatrix(true, true);+ const relative = root.matrixWorld.clone().invert().multiply(candidate.node.matrixWorld);+ const relativeScale = new THREE.Vector3();+ relative.decompose(new THREE.Vector3(), new THREE.Quaternion(), relativeScale);+ const size = geometryBox.getSize(new THREE.Vector3());+ const scaledSizes = [+ Math.abs(size.x * relativeScale.x),+ Math.abs(size.y * relativeScale.y),+ Math.abs(size.z * relativeScale.z),+ ];+ const axis = scaledSizes.indexOf(Math.max(...scaledSizes)) as 0 | 1 | 2;+ const minimum = geometryBox.min.getComponent(axis);+ const maximum = geometryBox.max.getComponent(axis);+ const tolerance = Math.max(1e-6, (maximum - minimum) * 1e-4);+ const first = endpointRadius(position, axis, minimum, tolerance, relativeScale);+ const second = endpointRadius(position, axis, maximum, tolerance, relativeScale);+ if (!first || !second) return undefined;++ const firstPoint = first.center.clone().applyMatrix4(relative);+ const secondPoint = second.center.clone().applyMatrix4(relative);+ const supportBoxes = allCandidates+ .filter((value) => value !== candidate)+ .map((value) => value.box);+ let firstIsBase: boolean;+ if (candidate.kind === 'trunk') {+ firstIsBase = firstPoint.y <= secondPoint.y;+ } else if (supportBoxes.length > 0) {+ const firstGap = Math.min(...supportBoxes.map((box) => boxDistanceToPoint(box, firstPoint)));+ const secondGap = Math.min(...supportBoxes.map((box) => boxDistanceToPoint(box, secondPoint)));+ firstIsBase =+ Math.abs(firstGap - secondGap) > 1e-6 ? firstGap < secondGap : first.radius >= second.radius;+ } else {+ firstIsBase = first.radius >= second.radius;+ }++ const baseRadius = firstIsBase ? first.radius : second.radius;+ const tipRadius = firstIsBase ? second.radius : first.radius;+ const length = firstPoint.distanceTo(secondPoint);+ const averageRadius = (baseRadius + tipRadius) / 2;+ const taperRatio = baseRadius > 1e-9 ? tipRadius / baseRadius : null;+ const lengthRadiusRatio = averageRadius > 1e-9 ? length / averageRadius : null;+ const selected = band[candidate.kind];+ const taperOutlier =+ taperRatio !== null && (taperRatio < selected.taper[0] || taperRatio > selected.taper[1]);+ const lengthRadiusOutlier =+ lengthRadiusRatio !== null &&+ (lengthRadiusRatio < selected.lengthRadius[0] || lengthRadiusRatio > selected.lengthRadius[1]);+ return {+ node: candidate.node.name || candidate.kind,+ nodePath: pathOf(candidate.node, root),+ kind: candidate.kind,+ source: candidate.growthSource,+ lengthMeters: stable(length),+ baseRadiusMeters: stable(baseRadius),+ tipRadiusMeters: stable(tipRadius),+ taperRatio: taperRatio === null ? null : stable(taperRatio),+ lengthRadiusRatio: lengthRadiusRatio === null ? null : stable(lengthRadiusRatio),+ expectedTaperRatio: `${selected.taper[0]}..${selected.taper[1]}`,+ expectedLengthRadiusRatio: `${selected.lengthRadius[0]}..${selected.lengthRadius[1]}`,+ taperOutlier,+ lengthRadiusOutlier,+ };+}++export function measureVegetationGrowth(+ intent: AssetIntentV1,+ root: THREE.Object3D,+): VegetationGrowthMeasurementsV1 {+ const trusted = vegetationIntent(intent);+ const subtype = trusted?.subtype ?? 'custom';+ const candidates = growthCandidates(root);+ const nodes = candidates+ .map((candidate) =>+ growthNodeMeasurement(root, candidate, candidates, VEGETATION_GROWTH_BANDS_V1[subtype]),+ )+ .filter((value): value is VegetationGrowthNodeMeasurementV1 => Boolean(value));+ return {+ schemaVersion: 1,+ subtype,+ source: measurementSource(nodes),+ trunkCount: nodes.filter((value) => value.kind === 'trunk').length,+ branchCount: nodes.filter((value) => value.kind === 'branch').length,+ nodes,+ };+}++export function evaluateVegetationGrowthQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'vegetation' || !(context.scene instanceof THREE.Object3D))+ return [];+ const measured = measureVegetationGrowth(context.intent, context.scene);+ const findings: QaFinding[] = [];+ for (const node of measured.nodes) {+ if (node.taperOutlier) {+ findings.push(+ finding(context, {+ code: 'VEG_GROWTH_TAPER_OUTLIER',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `${node.kind} taper measurement is outside the ${measured.subtype} measurement band.`,+ affected: { node: node.node, nodePath: node.nodePath },+ measurement: {+ name: 'tipToBaseRadiusRatio',+ actual: node.taperRatio ?? 'unmeasurable',+ expected: node.expectedTaperRatio,+ unit: 'ratio',+ },+ viewHints: ['front', 'right', 'three-quarter'],+ }),+ );+ }+ if (node.lengthRadiusOutlier) {+ findings.push(+ finding(context, {+ code: 'VEG_GROWTH_LENGTH_RADIUS_OUTLIER',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `${node.kind} length/radius measurement is outside the ${measured.subtype} measurement band.`,+ affected: { node: node.node, nodePath: node.nodePath },+ measurement: {+ name: 'lengthToAverageRadiusRatio',+ actual: node.lengthRadiusRatio ?? 'unmeasurable',+ expected: node.expectedLengthRadiusRatio,+ unit: 'ratio',+ },+ viewHints: ['front', 'right', 'three-quarter'],+ }),+ );+ }+ }+ return findings;+}++function distanceBetweenBoxes(a: THREE.Box3, b: THREE.Box3): number {+ const dx = Math.max(0, a.min.x - b.max.x, b.min.x - a.max.x);+ const dy = Math.max(0, a.min.y - b.max.y, b.min.y - a.max.y);+ const dz = Math.max(0, a.min.z - b.max.z, b.min.z - a.max.z);+ return Math.hypot(dx, dy, dz);+}++export function measureVegetationFoliageAttachment(+ root: THREE.Object3D,+): VegetationFoliageAttachmentMeasurementsV1 {+ const renderables = collectRenderableBounds(root);+ const support = renderables.filter(+ (value) => roleOrNameSource(value, TRUNK_PATTERNS) || roleOrNameSource(value, BRANCH_PATTERNS),+ );+ const foliage = renderables.filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));+ const clusters = foliage.map((value): VegetationFoliageAttachmentMeasurementV1 => {+ const size = value.box.getSize(new THREE.Vector3());+ const threshold = stable(Math.max(0.03, Math.min(0.18, size.length() * 0.12)));+ const nearest = support+ .map((candidate) => ({ candidate, gap: distanceBetweenBoxes(value.box, candidate.box) }))+ .sort(+ (a, b) =>+ a.gap - b.gap || (a.candidate.node.name || '').localeCompare(b.candidate.node.name || ''),+ )[0];+ const source = roleOrNameSource(value, CANOPY_PATTERNS) ?? 'fallback';+ return {+ node: value.node.name || 'foliage-cluster',+ nodePath: pathOf(value.node, root),+ source,+ nearestSupport: nearest?.candidate.node.name || null,+ gapMeters: nearest ? stable(nearest.gap) : null,+ thresholdMeters: threshold,+ detached: !nearest || nearest.gap > threshold,+ };+ });+ return {+ schemaVersion: 1,+ source: measurementSource(clusters),+ supportNodeCount: support.length,+ foliageClusterCount: foliage.length,+ clusters,+ };+}++export function evaluateVegetationFoliageAttachmentQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'vegetation' || !(context.scene instanceof THREE.Object3D))+ return [];+ return measureVegetationFoliageAttachment(context.scene)+ .clusters.filter((cluster) => cluster.detached)+ .map((cluster) =>+ finding(context, {+ code: 'VEG_FOLIAGE_DETACHED',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `${cluster.node} is detached from the nearest inferred or semantic branch/twig support.`,+ affected: { node: cluster.node, nodePath: cluster.nodePath },+ measurement: {+ name: 'foliageSupportGap',+ actual: cluster.gapMeters ?? 'no support found',+ expected: `<=${cluster.thresholdMeters}`,+ threshold: cluster.thresholdMeters,+ unit: 'm',+ },+ viewHints: ['front', 'right', 'three-quarter'],+ }),+ );+}++function relativeTransformSignature(root: THREE.Object3D, node: THREE.Object3D): string {+ const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);+ const scale = new THREE.Vector3();+ const quaternion = new THREE.Quaternion();+ matrix.decompose(new THREE.Vector3(), quaternion, scale);+ if (quaternion.w < 0) quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);+ const values = [...scale.toArray(), ...quaternion.toArray()].map((value) => stable(value));+ return values.join(',');+}++export function measureVegetationRepetition(+ intent: AssetIntentV1,+ root: THREE.Object3D,+): VegetationRepetitionMeasurementsV1 {+ root.updateWorldMatrix(true, true);+ const foliage = collectRenderableBounds(root).filter((value) =>+ roleOrNameSource(value, CANOPY_PATTERNS),+ );+ const bySignature = new Map<string, LocalBounds[]>();+ for (const value of foliage) {+ const signature = relativeTransformSignature(root, value.node);+ const entries = bySignature.get(signature) ?? [];+ entries.push(value);+ bySignature.set(signature, entries);+ }+ const identicalTransformGroups = [...bySignature.entries()]+ .filter(([, values]) => values.length >= 3)+ .map(([signature, values]) => ({+ signature,+ nodes: values.map((value) => value.node.name || 'foliage-cluster').sort(),+ }))+ .sort((a, b) => a.signature.localeCompare(b.signature));++ const supports = collectRenderableBounds(root).filter((value) =>+ roleOrNameSource(value, TRUNK_PATTERNS),+ );+ const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE.Box3());+ const centers = foliage.map((value) => value.box.getCenter(new THREE.Vector3()));+ const center = centerBox.isEmpty()+ ? centers+ .reduce((result, value) => result.add(value), new THREE.Vector3())+ .multiplyScalar(centers.length > 0 ? 1 / centers.length : 0)+ : centerBox.getCenter(new THREE.Vector3());+ const radial = centers+ .map((value) => ({+ angle: Math.atan2(value.z - center.z, value.x - center.x),+ radius: Math.hypot(value.x - center.x, value.z - center.z),+ }))+ .filter((value) => value.radius > 1e-6)+ .sort((a, b) => a.angle - b.angle);+ let radialGapRangeRadians: number | null = null;+ let radialRadiusSpreadRatio: number | null = null;+ let perfectRadialLockstep = false;+ if (radial.length >= 4) {+ const gaps = radial.map((value, index) => {+ const next = radial[(index + 1) % radial.length]!;+ const raw = next.angle - value.angle;+ return raw > 0 ? raw : raw + Math.PI * 2;+ });+ radialGapRangeRadians = stable(Math.max(...gaps) - Math.min(...gaps));+ const radii = radial.map((value) => value.radius);+ const meanRadius = radii.reduce((sum, value) => sum + value, 0) / radii.length;+ radialRadiusSpreadRatio = stable((Math.max(...radii) - Math.min(...radii)) / meanRadius);+ perfectRadialLockstep = radialGapRangeRadians <= 0.02 && radialRadiusSpreadRatio <= 0.02;+ }+ const suppressedForTopiary = vegetationIntent(intent)?.canopyProfile === 'topiary';+ return {+ schemaVersion: 1,+ source: measurementSource(+ foliage.map((value) => ({+ source: roleOrNameSource(value, CANOPY_PATTERNS) ?? 'fallback',+ })),+ ),+ clusterCount: foliage.length,+ identicalTransformGroups,+ radialGapRangeRadians,+ radialRadiusSpreadRatio,+ perfectRadialLockstep,+ suppressedForTopiary,+ };+}++export function evaluateVegetationRepetitionQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'vegetation' || !(context.scene instanceof THREE.Object3D))+ return [];+ const measured = measureVegetationRepetition(context.intent, context.scene);+ if (measured.suppressedForTopiary) return [];+ const findings: QaFinding[] = measured.identicalTransformGroups.map((group) =>+ finding(context, {+ code: 'VEG_CLUSTER_TRANSFORM_REPEAT',+ disposition: 'warn',+ dimension: 'visualQuality',+ message: `${group.nodes.length} foliage clusters use an identical scale/rotation signature.`,+ affected: { node: group.nodes[0], nodePath: group.nodes.join(',') },+ measurement: {+ name: 'identicalClusterTransformCount',+ actual: group.nodes.length,+ expected: '<3 outside formal topiary intent',+ },+ viewHints: ['front', 'right', 'top', 'three-quarter'],+ }),+ );+ if (measured.perfectRadialLockstep) {+ findings.push(+ finding(context, {+ code: 'VEG_CLUSTER_RADIAL_LOCKSTEP',+ disposition: 'warn',+ dimension: 'visualQuality',+ message: 'Foliage clusters form a perfect equal-radius, equal-angle radial sequence.',+ measurement: {+ name: 'radialGapAndRadiusSpread',+ actual: `${measured.radialGapRangeRadians},${measured.radialRadiusSpreadRatio}`,+ expected: 'angle gap range >0.02 or radius spread ratio >0.02',+ unit: 'ratio',+ },+ viewHints: ['top', 'three-quarter'],+ }),+ );+ }+ return findings;+}++export function measureVegetationCanopy(+ intent: AssetIntentV1,+ root: THREE.Object3D,+): VegetationCanopyMeasurementsV1 {+ const profile = vegetationIntent(intent)?.canopyProfile ?? 'broadleaf';+ const renderables = collectRenderableBounds(root);+ const canopy = renderables.filter((value) => matchesAny(value, CANOPY_PATTERNS));+ const trunk = renderables.filter((value) => matchesAny(value, TRUNK_PATTERNS));+ const semanticCanopy = canopy.some((value) => value.roles.length > 0);+ const source = canopy.length === 0 ? 'none' : semanticCanopy ? 'semantic' : 'fallback';+ const canopyBoxes = canopy.map((value) => value.box);+ const trunkVolume = unionVolume(trunk.map((value) => value.box));+ const ratio = trunkVolume > 1e-9 ? unionVolume(canopyBoxes) / trunkVolume : null;+ return {+ schemaVersion: 1,+ profile,+ source,+ canopyNodeCount: canopy.length,+ trunkNodeCount: trunk.length,+ frontOccupancy: projectedOccupancy(canopyBoxes, [2, 1]),+ sideOccupancy: projectedOccupancy(canopyBoxes, [0, 1]),+ topOccupancy: projectedOccupancy(canopyBoxes, [0, 2]),+ canopyToTrunkVolumeRatio: ratio === null ? null : stable(ratio),+ };+}++const PROFILE_BANDS: Readonly<+ Record<+ VegetationCanopyProfile,+ {+ occupancy: { front: [number, number]; side: [number, number]; top: [number, number] };+ ratio: [number, number];+ }+ >+> = Object.freeze({+ broadleaf: {+ occupancy: { front: [0.4, 0.99], side: [0.4, 0.99], top: [0.32, 0.99] },+ ratio: [1.5, 120],+ },+ conifer: {+ occupancy: { front: [0.32, 0.97], side: [0.32, 0.97], top: [0.2, 0.95] },+ ratio: [1, 100],+ },+ topiary: {+ occupancy: { front: [0.62, 1], side: [0.62, 1], top: [0.58, 1] },+ ratio: [1, 120],+ },+ 'bare/dead': {+ occupancy: { front: [0, 0.08], side: [0, 0.08], top: [0, 0.08] },+ ratio: [0, 0.2],+ },+});++export function evaluateVegetationCanopyQa(context: QaContext): readonly QaFinding[] {+ const trusted = vegetationIntent(context.intent);+ if (!trusted || !(context.scene instanceof THREE.Object3D)) return [];+ const measurements = measureVegetationCanopy(context.intent, context.scene);+ const bands = PROFILE_BANDS[measurements.profile];+ const sparseFactor = trusted.growthState === 'sparse' ? 0.55 : 1;+ const values = [+ ['FRONT', 'frontOccupancy', measurements.frontOccupancy, bands.occupancy.front, 'front'],+ ['SIDE', 'sideOccupancy', measurements.sideOccupancy, bands.occupancy.side, 'right'],+ ['TOP', 'topOccupancy', measurements.topOccupancy, bands.occupancy.top, 'top'],+ ] as const;+ const findings: QaFinding[] = [];+ if (measurements.canopyNodeCount === 0 && measurements.profile !== 'bare/dead') {+ findings.push(+ finding(context, {+ code: 'VEG_CANOPY_MISSING',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `The ${trusted.subtype} profile resolved no semantic or inferred canopy renderables.`,+ measurement: { name: 'canopyNodeCount', actual: 0, expected: '>=1' },+ viewHints: ['front', 'right', 'top'],+ }),+ );+ return findings;+ }+ for (const [suffix, name, actual, [minimum, maximum], view] of values) {+ const adjustedMinimum = minimum * sparseFactor;+ if (actual >= adjustedMinimum && actual <= maximum) continue;+ findings.push(+ finding(context, {+ code: `VEG_CANOPY_OCCUPANCY_${suffix}`,+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `${measurements.profile} ${name} is outside its measured ${trusted.growthState} profile band.`,+ measurement: {+ name,+ actual,+ expected: `${stable(adjustedMinimum)}..${maximum}`,+ threshold: adjustedMinimum,+ unit: 'ratio',+ },+ viewHints: [view, 'three-quarter'],+ }),+ );+ }+ const ratio = measurements.canopyToTrunkVolumeRatio;+ if (ratio !== null && (ratio < bands.ratio[0] || ratio > bands.ratio[1])) {+ findings.push(+ finding(context, {+ code: 'VEG_CANOPY_TRUNK_RATIO',+ disposition: 'warn',+ dimension: 'categoryReadiness',+ message: `${measurements.profile} canopy-to-trunk volume ratio is outside its subtype band.`,+ measurement: {+ name: 'canopyToTrunkVolumeRatio',+ actual: ratio,+ expected: `${bands.ratio[0]}..${bands.ratio[1]}`,+ threshold: bands.ratio[0],+ unit: 'ratio',+ },+ viewHints: ['front', 'right', 'top'],+ }),+ );+ }+ return findings;+}++function materialValue(material: THREE.Material): number | undefined {+ if (+ !(material instanceof THREE.MeshStandardMaterial) &&+ !(material instanceof THREE.MeshBasicMaterial)+ ) {+ return undefined;+ }+ const color = material.color;+ return 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;+}++export function measureVegetationFoliageMaterials(+ intent: AssetIntentV1,+ root: THREE.Object3D,+): VegetationFoliageMaterialMeasurementsV1 {+ const values: number[] = [];+ let foliageNodeCount = 0;+ root.traverse((node) => {+ if (!(node instanceof THREE.Mesh)) return;+ const bounds: LocalBounds = {+ node,+ box: new THREE.Box3(),+ roles: rolesOf(node),+ source: rolesOf(node).length > 0 ? 'semantic' : 'fallback',+ };+ if (!matchesAny(bounds, CANOPY_PATTERNS)) return;+ foliageNodeCount++;+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ for (const material of materials) {+ const value = materialValue(material);+ if (value !== undefined) values.push(value);+ }+ });+ const buckets = new Set(values.map((value) => Math.round(value * 20) / 20));+ const valueRange = values.length > 0 ? Math.max(...values) - Math.min(...values) : 0;+ const optimized = intent.material.mode === 'flatOptimized';+ return {+ schemaVersion: 1,+ mode: intent.material.mode,+ foliageNodeCount,+ valueRoleCount: buckets.size,+ valueRange: stable(valueRange),+ coherent: optimized+ ? buckets.size <= 1+ : buckets.size >= 2 && buckets.size <= 6 && valueRange >= 0.03,+ };+}++export function evaluateVegetationMaterialQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'vegetation' || !(context.scene instanceof THREE.Object3D))+ return [];+ const measured = measureVegetationFoliageMaterials(context.intent, context.scene);+ if (measured.foliageNodeCount === 0 || measured.coherent) return [];+ const optimized = measured.mode === 'flatOptimized';+ return [+ finding(context, {+ code: 'VEG_FOLIAGE_VALUE_ROLES',+ disposition: 'warn',+ dimension: 'visualQuality',+ message: optimized+ ? 'Optimized vegetation should retain one coherent foliage value role.'+ : 'Rich organic vegetation should use two to six restrained foliage value roles with visible value separation.',+ measurement: {+ name: 'foliageValueRoles',+ actual: `${measured.valueRoleCount} roles; range ${measured.valueRange}`,+ expected: optimized ? '1 role' : '2..6 roles; range >=0.03',+ },+ viewHints: ['front', 'three-quarter'],+ }),+ ];+}++export function evaluateVegetationAdvisoryQa(context: QaContext): readonly QaFinding[] {+ return [+ ...evaluateVegetationScopeQa(context),+ ...evaluateVegetationGrowthQa(context),+ ...evaluateVegetationCanopyQa(context),+ ...evaluateVegetationFoliageAttachmentQa(context),+ ...evaluateVegetationRepetitionQa(context),+ ...evaluateVegetationMaterialQa(context),+ ];+}++export const VEGETATION_CONTACT_QA_RULE: QaRule = {+ id: 'VEGETATION_CONTACT_PROFILE',+ profile: PROFILE,+ scope: { kind: 'category', category: 'vegetation' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'vegetation-contact-v1',+ 'src/qa/vegetation.test.ts',+ '8ad8f1753fc76e5e1b0114ad7d7f2c6c02c6f1c60953727027219424422a8ac4',+ ),+ defaultMode: 'enforce',+ evaluate: evaluateVegetationContactQa,+};++export const VEGETATION_ADVISORY_QA_RULE: QaRule = {+ id: 'VEGETATION_ADVISORY_PROFILE',+ profile: 'vegetation.advisory',+ scope: { kind: 'category', category: 'vegetation' },+ ruleClass: 'heuristic',+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: 'observe',+ evaluate: evaluateVegetationAdvisoryQa,+};++export const VEGETATION_QA_RULES: readonly QaRule[] = [+ VEGETATION_CONTACT_QA_RULE,+ VEGETATION_ADVISORY_QA_RULE,+] as const;diff --git a/src/qa/vehicle-advisory.ts b/src/qa/vehicle-advisory.tsnew file mode 100644index 00000000..cb1831ce--- /dev/null+++ b/src/qa/vehicle-advisory.ts@@ -0,0 +1,457 @@+import * as THREE from 'three';++import { readSemanticMetadataV1, type VehicleIntentV1 } from '../contracts';+import { resolveVehicleWheelAssemblies, type ResolvedWheelAssembly } from '../vehicle';+import {+ createOrientedProbeBox3,+ createProbeLocalFrame3,+ probeOrientedPenetration,+ type OrientedProbeBox3,+ type ProbeVector3,+} from './geometry-relations';+import { KILN_ENGINE_QA_OWNER, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';++const SYMMETRY_RATIO = 0.08;+const PENETRATION_RATIO = 0.25;+const ORIENTATION_RATIO = 1.15;+const TRACK_CONTAINMENT_TOLERANCE = 0.02;+const VEHICLE_VIEWS = [+ 'vehicle.underbody',+ 'vehicle.wheel-section.right',+ 'generic.top.semantic-overlay',+];++function advisory(+ context: QaContext,+ value: Omit<QaFinding, 'profile' | 'dimension' | 'disposition'>,+): QaFinding {+ return {+ ...value,+ disposition: 'warn',+ dimension: 'categoryReadiness',+ profile: context.intent.qaProfile,+ viewHints: value.viewHints ?? [...VEHICLE_VIEWS],+ };+}++function localPoint(inverse: THREE.Matrix4, point: THREE.Vector3): THREE.Vector3 {+ return point.clone().applyMatrix4(inverse);+}++function wheelPairs(+ wheels: readonly ResolvedWheelAssembly[],+): Array<[string, ResolvedWheelAssembly, ResolvedWheelAssembly]> {+ const groups = new Map<string, ResolvedWheelAssembly[]>();+ for (const wheel of wheels) {+ if (!wheel.index) continue;+ const group = groups.get(wheel.index) ?? [];+ group.push(wheel);+ groups.set(wheel.index, group);+ }+ return [...groups.entries()].flatMap(([index, group]) => {+ const left = group.find((wheel) => wheel.side === 'left');+ const right = group.find((wheel) => wheel.side === 'right');+ return left && right ? ([[index, left, right]] as const) : [];+ });+}++function bilateralSymmetryFindings(+ context: QaContext,+ root: THREE.Object3D,+ wheels: readonly ResolvedWheelAssembly[],+): QaFinding[] {+ root.updateMatrixWorld(true);+ const inverse = root.matrixWorld.clone().invert();+ const findings: QaFinding[] = [];+ for (const [index, left, right] of wheelPairs(wheels)) {+ const a = localPoint(inverse, left.centerWorld);+ const b = localPoint(inverse, right.centerWorld);+ const centerDelta = Math.hypot(a.x - b.x, a.y - b.y, a.z + b.z);+ const radiusDelta = Math.abs((left.radius ?? 0) - (right.radius ?? 0));+ const widthDelta = Math.abs((left.width ?? 0) - (right.width ?? 0));+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(0.01, scale * SYMMETRY_RATIO);+ const maximum = Math.max(centerDelta, radiusDelta, widthDelta);+ if (maximum <= threshold) continue;+ const measurementName =+ maximum === centerDelta+ ? 'bilateralCenterMirrorDelta'+ : maximum === radiusDelta+ ? 'bilateralRadiusDelta'+ : 'bilateralWidthDelta';+ findings.push(+ advisory(context, {+ code: 'VEH_BILATERAL_SYMMETRY',+ message:+ `Axle ${index} left/right assemblies differ in center, radius, or width ` ++ `(center=${centerDelta.toFixed(6)}, radius=${radiusDelta.toFixed(6)}, width=${widthDelta.toFixed(6)} m).`,+ affected: { node: right.root.name },+ measurement: {+ name: measurementName,+ actual: maximum,+ expected: 0,+ threshold,+ unit: 'm',+ },+ }),+ );+ }+ return findings;+}++function semanticRoles(node: THREE.Object3D): readonly string[] {+ return readSemanticMetadataV1(node)?.roles ?? [];+}++function trackSide(node: THREE.Object3D): 'left' | 'right' | undefined {+ for (const role of semanticRoles(node)) {+ const match = role.match(+ /(?:track\.loop|support\.track|track\.road-wheel)\.(left|right)(?:\.|$)/,+ );+ if (match?.[1] === 'left' || match?.[1] === 'right') return match[1];+ }+ return undefined;+}++function isFender(node: THREE.Object3D): boolean {+ return (+ semanticRoles(node).some((role) => /(?:^|\.)(?:fender|wheel-arch)(?:\.|$)/i.test(role)) ||+ /fender|wheel[ _.-]?arch/i.test(node.name)+ );+}++function isChassisMesh(node: THREE.Object3D): node is THREE.Mesh {+ if (!(node instanceof THREE.Mesh) || isFender(node)) return false;+ return (+ semanticRoles(node).some((role) =>+ /^(?:vehicle\.)?(?:chassis|body|hull)(?:\.|$)/i.test(role),+ ) || /chassis|vehicle[ _.-]?body|fuselage|hull/i.test(node.name)+ );+}++function objectBoundsInFrame(+ object: THREE.Object3D,+ frame: THREE.Object3D,+): THREE.Box3 | undefined {+ object.updateWorldMatrix(true, true);+ frame.updateWorldMatrix(true, false);+ const worldToFrame = frame.matrixWorld.clone().invert();+ const bounds = new THREE.Box3();+ let found = false;+ object.traverse((part) => {+ if (!(part instanceof THREE.Mesh) || !(part.geometry instanceof THREE.BufferGeometry)) return;+ part.geometry.computeBoundingBox();+ const box = part.geometry.boundingBox;+ if (!box) return;+ const matrix = worldToFrame.clone().multiply(part.matrixWorld);+ for (const x of [box.min.x, box.max.x])+ for (const y of [box.min.y, box.max.y])+ for (const z of [box.min.z, box.max.z]) {+ bounds.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(matrix));+ found = true;+ }+ });+ return found ? bounds : undefined;+}++function tuple(value: THREE.Vector3): ProbeVector3 {+ return [value.x, value.y, value.z];+}++function probeBox(id: string, root: THREE.Object3D, bounds: THREE.Box3): OrientedProbeBox3 {+ root.updateWorldMatrix(true, false);+ const center = bounds.getCenter(new THREE.Vector3()).applyMatrix4(root.matrixWorld);+ const size = bounds.getSize(new THREE.Vector3());+ const position = new THREE.Vector3();+ const quaternion = new THREE.Quaternion();+ const scale = new THREE.Vector3();+ root.matrixWorld.decompose(position, quaternion, scale);+ const xAxis = new THREE.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();+ const yAxis = new THREE.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();+ const zAxis = new THREE.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();+ return createOrientedProbeBox3({+ id,+ frame: createProbeLocalFrame3({+ id: `${id}.frame`,+ origin: tuple(center),+ xAxis: tuple(xAxis),+ yAxis: tuple(yAxis),+ zAxis: tuple(zAxis),+ }),+ halfExtents: [+ (size.x * Math.abs(scale.x)) / 2,+ (size.y * Math.abs(scale.y)) / 2,+ (size.z * Math.abs(scale.z)) / 2,+ ],+ });+}++function chassisMeshes(root: THREE.Object3D): THREE.Mesh[] {+ const meshes: THREE.Mesh[] = [];+ root.traverse((node) => {+ if (isChassisMesh(node)) meshes.push(node);+ });+ return meshes;+}++function penetrationFindings(+ context: QaContext,+ root: THREE.Object3D,+ wheels: readonly ResolvedWheelAssembly[],+): QaFinding[] {+ const chassis = chassisMeshes(root);+ const findings: QaFinding[] = [];+ for (const wheel of wheels) {+ if (!wheel.tire || wheel.radius === undefined) continue;+ const tireBounds = objectBoundsInFrame(wheel.tire, root);+ if (!tireBounds) continue;+ const threshold = Math.max(0.02, wheel.radius * PENETRATION_RATIO);+ for (const body of chassis) {+ const bodyBounds = objectBoundsInFrame(body, root);+ if (!bodyBounds) continue;+ const result = probeOrientedPenetration(+ probeBox(`${wheel.id}.tire`, root, tireBounds),+ probeBox(body.name || 'vehicle.chassis', root, bodyBounds),+ { maxDepth: threshold },+ );+ if (result.pass) continue;+ findings.push(+ advisory(context, {+ code: 'VEH_WHEEL_CHASSIS_PENETRATION',+ message:+ `Wheel ${wheel.id} penetrates chassis ${body.name || '(unnamed)'} by ` ++ `${result.measurements.penetrationDepth?.toFixed(6)} m beyond the allowed non-fender overlap.`,+ affected: { node: wheel.tire.name || wheel.root.name },+ measurement: {+ name: 'tireChassisPenetrationDepth',+ actual: result.measurements.penetrationDepth ?? 0,+ expected: 0,+ threshold,+ unit: 'm',+ },+ viewHints: ['vehicle.underbody', 'vehicle.wheel-section.right'],+ }),+ );+ }+ }+ return findings;+}++function wholeAssetBounds(root: THREE.Object3D): THREE.Box3 | undefined {+ return objectBoundsInFrame(root, root);+}++function orientationFindings(+ context: QaContext,+ root: THREE.Object3D,+ intent: VehicleIntentV1,+): QaFinding[] {+ if (+ intent.subtype === 'fixed-wing' ||+ intent.subtype === 'rotorcraft' ||+ intent.subtype === 'walking' ||+ intent.subtype === 'custom'+ ) {+ return [];+ }+ const bounds = wholeAssetBounds(root);+ if (!bounds) return [];+ const size = bounds.getSize(new THREE.Vector3());+ const ratio = size.z / Math.max(size.x, 1e-9);+ if (ratio <= ORIENTATION_RATIO) return [];+ return [+ advisory(context, {+ code: 'VEH_ORIENTATION_SIDEWAYS',+ message:+ `${intent.subtype} bounds are Z-dominant despite canonical +X travel ` ++ `(spanX=${size.x.toFixed(6)}, spanZ=${size.z.toFixed(6)} m).`,+ affected: { node: root.name || 'vehicle-root' },+ measurement: {+ name: 'boundsSpanZToSpanX',+ actual: ratio,+ expected: `<=${ORIENTATION_RATIO}`,+ threshold: ORIENTATION_RATIO,+ },+ viewHints: ['generic.top.semantic-overlay', 'vehicle.underbody'],+ }),+ ];+}++function nodePath(root: THREE.Object3D, target: THREE.Object3D): string {+ let found = '';+ const visit = (node: THREE.Object3D, parent: string, index: number): void => {+ if (found) return;+ const segment = `${node.name.trim() || node.type || 'Object3D'}[${index}]`;+ const path = parent ? `${parent}/${segment}` : segment;+ if (node === target) {+ found = path;+ return;+ }+ node.children.forEach((child, childIndex) => {+ visit(child, path, childIndex);+ });+ };+ visit(root, '', 0);+ return found;+}++function weldedBoundaryEdges(root: THREE.Object3D, loop: THREE.Object3D): number | undefined {+ root.updateMatrixWorld(true);+ const inverse = loop.matrixWorld.clone().invert();+ const edges = new Map<string, number>();+ let triangleCount = 0;+ const vertexKey = (point: THREE.Vector3): string =>+ [point.x, point.y, point.z].map((value) => Math.round(value * 1e6)).join(',');+ loop.traverse((node) => {+ if (!(node instanceof THREE.Mesh) || !(node.geometry instanceof THREE.BufferGeometry)) return;+ const positions = node.geometry.getAttribute('position');+ if (!positions) return;+ const matrix = inverse.clone().multiply(node.matrixWorld);+ const keys = Array.from({ length: positions.count }, (_, index) =>+ vertexKey(new THREE.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)),+ );+ const index = node.geometry.getIndex();+ const indices = index+ ? Array.from(index.array, Number)+ : Array.from({ length: positions.count }, (_, value) => value);+ for (let offset = 0; offset + 2 < indices.length; offset += 3) {+ triangleCount++;+ const triangle = [indices[offset]!, indices[offset + 1]!, indices[offset + 2]!];+ for (let edge = 0; edge < 3; edge++) {+ const a = keys[triangle[edge]!]!;+ const b = keys[triangle[(edge + 1) % 3]!]!;+ const id = a < b ? `${a}|${b}` : `${b}|${a}`;+ edges.set(id, (edges.get(id) ?? 0) + 1);+ }+ }+ });+ if (triangleCount === 0) return undefined;+ return [...edges.values()].filter((count) => count === 1).length;+}++function trackProfileFindings(+ context: QaContext,+ root: THREE.Object3D,+ intent: VehicleIntentV1,+): QaFinding[] {+ if (intent.subtype !== 'tracked') return [];+ const loops: THREE.Object3D[] = [];+ const roadWheels: THREE.Object3D[] = [];+ root.traverse((node) => {+ const roles = semanticRoles(node);+ if (+ roles.some((role) => role.startsWith('track.loop.')) ||+ roles.some((role) => role.startsWith('support.track.'))+ ) {+ loops.push(node);+ }+ if (+ roles.some((role) => role.startsWith('track.road-wheel.')) ||+ /road[ _.-]?wheel/i.test(node.name)+ ) {+ roadWheels.push(node);+ }+ });+ if (loops.length === 0) {+ return [+ advisory(context, {+ code: 'VEH_TRACK_LOOP_MISSING',+ message: 'Tracked vehicle exposes no semantic track.loop.* assembly to inspect.',+ affected: { node: root.name || 'vehicle-root' },+ measurement: { name: 'trackLoopCount', actual: 0, expected: '>=1', threshold: 1 },+ viewHints: ['vehicle.underbody', 'generic.right.semantic-overlay'],+ }),+ ];+ }+ const findings: QaFinding[] = [];+ for (const loop of loops) {+ const loopSide = trackSide(loop);+ const declaredClosed = loop.userData['kilnTrackLoopClosed'];+ const boundaryEdges = weldedBoundaryEdges(root, loop);+ if (declaredClosed === false || (boundaryEdges !== undefined && boundaryEdges > 0)) {+ findings.push(+ advisory(context, {+ code: 'VEH_TRACK_LOOP_OPEN',+ message:+ `Track loop ${loop.name || '(unnamed)'} is open ` ++ `(boundary edges ${boundaryEdges ?? 'declared'}).`,+ affected: { node: loop.name || 'track-loop', nodePath: nodePath(root, loop) },+ measurement: {+ name: 'trackLoopBoundaryEdgeCount',+ actual: boundaryEdges ?? 1,+ expected: 0,+ threshold: 0,+ },+ viewHints: ['vehicle.underbody', 'generic.right.wireframe'],+ }),+ );+ }+ const loopBounds = objectBoundsInFrame(loop, root);+ if (!loopBounds) continue;+ const expanded = loopBounds.clone().expandByScalar(TRACK_CONTAINMENT_TOLERANCE);+ for (const roadWheel of roadWheels.filter(+ (candidate) => !loopSide || !trackSide(candidate) || trackSide(candidate) === loopSide,+ )) {+ const wheelBounds = objectBoundsInFrame(roadWheel, root);+ if (!wheelBounds) continue;+ const center = wheelBounds.getCenter(new THREE.Vector3());+ if (expanded.containsPoint(center)) continue;+ const clamped = center.clone().clamp(expanded.min, expanded.max);+ const overflow = center.distanceTo(clamped);+ findings.push(+ advisory(context, {+ code: 'VEH_TRACK_ROAD_WHEEL_ESCAPED',+ message:+ `Road wheel ${roadWheel.name || '(unnamed)'} escapes track loop ` ++ `${loop.name || '(unnamed)'} by ${overflow.toFixed(6)} m.`,+ affected: {+ node: roadWheel.name || 'track-road-wheel',+ nodePath: nodePath(root, roadWheel),+ },+ measurement: {+ name: 'roadWheelTrackContainmentOverflow',+ actual: overflow,+ expected: 0,+ threshold: TRACK_CONTAINMENT_TOLERANCE,+ unit: 'm',+ },+ viewHints: ['vehicle.underbody', 'generic.right.semantic-overlay'],+ }),+ );+ }+ }+ return findings;+}++/** W6 plausibility signals. The policy registry always rewrites them to observe. */+export function evaluateVehicleAdvisoryQa(context: QaContext): QaFinding[] {+ if (context.intent.category !== 'vehicle' || !(context.scene instanceof THREE.Object3D)) {+ return [];+ }+ const intent = context.intent.vehicle;+ if (!intent) return [];+ const root = context.scene;+ root.updateMatrixWorld(true);+ const wheels = resolveVehicleWheelAssemblies(root);+ return [+ ...bilateralSymmetryFindings(context, root, wheels),+ ...penetrationFindings(context, root, wheels),+ ...orientationFindings(context, root, intent),+ ...trackProfileFindings(context, root, intent),+ ].sort((a, b) =>+ `${a.code}:${a.affected?.nodePath ?? a.affected?.node ?? ''}`.localeCompare(+ `${b.code}:${b.affected?.nodePath ?? b.affected?.node ?? ''}`,+ ),+ );+}++export const VEHICLE_W6_ADVISORY_QA_RULE: QaRule = Object.freeze({+ id: 'VEHICLE_W6_ADVISORY_PROFILE',+ profile: 'vehicle.w6-advisory',+ scope: { kind: 'category' as const, category: 'vehicle' as const },+ ruleClass: 'heuristic',+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: 'observe',+ evaluate: evaluateVehicleAdvisoryQa,+});diff --git a/src/qa/vehicle.test.ts b/src/qa/vehicle.test.tsnew file mode 100644index 00000000..f3833b90--- /dev/null+++ b/src/qa/vehicle.test.ts@@ -0,0 +1,286 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import { createAssetIntentV1, stampSemanticMetadataV1 } from '../contracts';+import {+ createVehicleFrame,+ createWheelAssembly,+ createWheelGeometrySet,+ type WheelAssemblyResult,+} from '../vehicle';+import { evaluateVehicleQa } from './vehicle';++const tireMaterial = new THREE.MeshStandardMaterial({ color: 0x171717 });+const metalMaterial = new THREE.MeshStandardMaterial({ color: 0xaaaaaa });++function wheeledVehicle() {+ const frame = createVehicleFrame('Car', {+ axles: [+ { id: 'front', position: [1.2, 0.5, 0] },+ { id: 'rear', position: [-1.2, 0.5, 0] },+ ],+ });+ frame.root.position.set(3, 1, -2);+ frame.root.rotation.set(0.1, 0.6, -0.05);+ const geometry = createWheelGeometrySet(0.5, 0.2);+ const wheels: WheelAssemblyResult[] = [];+ for (const [index, x] of [+ ['front', 1.2],+ ['rear', -1.2],+ ] as const) {+ for (const side of ['left', 'right'] as const) {+ wheels.push(+ createWheelAssembly(+ 'Wheel',+ { tire: tireMaterial, rim: metalMaterial },+ {+ radius: 0.5,+ width: 0.2,+ side,+ index,+ position: [x, 0.5, side === 'left' ? -0.85 : 0.85],+ steering: index === 'front',+ geometries: geometry,+ parent: frame.root,+ },+ ),+ );+ }+ }+ const intent = createAssetIntentV1({+ category: 'vehicle',+ subtype: 'wheeled',+ vehicle: {+ subtype: 'wheeled',+ wheelCount: 4,+ axleCount: 2,+ steering: 'front',+ supportPolicy: 'grounded',+ },+ });+ const findings = () => evaluateVehicleQa({ intent, scene: frame.root });+ return { frame, wheels, intent, findings };+}++function codes(findings: readonly { code: string }[]): string[] {+ return findings.map((finding) => finding.code);+}++describe('vehicle semantic QA', () => {+ test('accepts a transformed canonical four-wheel assembly', () => {+ const { findings } = wheeledVehicle();+ expect(findings()).toEqual([]);+ });++ test('blocks an explicit four-wheel intent when five assemblies resolve', () => {+ const fixture = wheeledVehicle();+ createWheelAssembly(+ 'Spare',+ { tire: tireMaterial, rim: metalMaterial },+ {+ radius: 0.5,+ width: 0.2,+ side: 'left',+ index: 'spare',+ position: [0, 0.5, -0.85],+ parent: fixture.frame.root,+ },+ );+ const findings = fixture.findings();+ expect(codes(findings)).toContain('VEH_WHEEL_COUNT');+ expect(findings.find((finding) => finding.code === 'VEH_WHEEL_COUNT')?.disposition).toBe(+ 'block',+ );+ });++ test('blocks duplicate semantic assemblies at one corner even when total count remains four', () => {+ const fixture = wheeledVehicle();+ fixture.wheels[3]!.root.removeFromParent();+ createWheelAssembly(+ 'Duplicate',+ { tire: tireMaterial, rim: metalMaterial },+ {+ radius: 0.5,+ width: 0.2,+ side: 'left',+ index: 'front',+ position: [1.2, 0.5, -0.85],+ steering: true,+ parent: fixture.frame.root,+ },+ );+ const duplicate = fixture+ .findings()+ .find((finding) => finding.code === 'VEH_DUPLICATE_ASSEMBLY')!;+ expect(duplicate.disposition).toBe('block');+ expect(duplicate.measurement?.name).toBe('duplicateAssemblyCenterDelta');+ expect(duplicate.measurement?.actual).toBeCloseTo(0, 8);+ expect(duplicate.repairText).toContain('Remove only duplicate assembly');+ });++ test('localizes raised hubcaps and invalid nested radii', () => {+ const fixture = wheeledVehicle();+ fixture.wheels[0]!.hub.position.y = 0.16;+ fixture.wheels[1]!.hub.scale.setScalar(2.4);+ const findings = fixture.findings();+ expect(codes(findings)).toContain('VEH_WHEEL_CONCENTRICITY');+ expect(codes(findings)).toContain('VEH_WHEEL_RADIUS');+ expect(+ findings.find((finding) => finding.code === 'VEH_WHEEL_CONCENTRICITY')?.measurement?.actual,+ ).toBeGreaterThan(0.1);+ });++ test('uses scale-relative local measurements for concentricity', () => {+ const fixture = wheeledVehicle();+ fixture.frame.root.scale.setScalar(10);+ fixture.wheels[0]!.hub.position.y = 0.005;+ expect(codes(fixture.findings())).not.toContain('VEH_WHEEL_CONCENTRICITY');+ fixture.wheels[0]!.hub.position.y = 0.02;+ const concentricity = fixture+ .findings()+ .find((finding) => finding.code === 'VEH_WHEEL_CONCENTRICITY');+ expect(concentricity?.measurement?.actual).toBeCloseTo(0.02, 6);+ expect(concentricity?.measurement?.threshold).toBeCloseTo(0.015, 6);+ });++ test('detects wrong axle orientation and off-center component ownership', () => {+ const fixture = wheeledVehicle();+ fixture.wheels[0]!.spinPivot.rotation.y = Math.PI / 2;+ for (const part of [fixture.wheels[1]!.tire, fixture.wheels[1]!.rim, fixture.wheels[1]!.hub]) {+ part.position.x = 0.2;+ }+ const findings = fixture.findings();+ expect(codes(findings)).toContain('VEH_WHEEL_AXLE_AXIS');+ expect(codes(findings)).toContain('VEH_WHEEL_PIVOT');+ });++ test('detects paired-X/Y mismatch and floating contact', () => {+ const fixture = wheeledVehicle();+ fixture.wheels[1]!.root.position.x = 0.2;+ fixture.wheels[2]!.root.position.y = 0.18;+ const findings = fixture.findings();+ expect(codes(findings)).toContain('VEH_AXLE_PAIR');+ expect(codes(findings)).toContain('VEH_CONTACT_PLANE');+ });++ test('requires declared non-wheel supports to touch the canonical contact plane', () => {+ const frame = createVehicleFrame('TrackedVehicle');+ const leftTrack = new THREE.Mesh(new THREE.BoxGeometry(2.4, 0.2, 0.25), metalMaterial);+ leftTrack.name = 'LeftTrackSupport';+ leftTrack.position.set(0, 0.2, -0.75); // bottom = +0.1, floating+ stampSemanticMetadataV1(leftTrack, { roles: ['support.track.left'] });+ const rightTrack = leftTrack.clone();+ rightTrack.name = 'RightTrackSupport';+ rightTrack.position.set(0, 0, 0.75); // bottom = -0.1, buried+ stampSemanticMetadataV1(rightTrack, { roles: ['support.track.right'] });+ frame.root.add(leftTrack, rightTrack);+ const intent = createAssetIntentV1({ category: 'vehicle', subtype: 'tracked' });+ const findings = evaluateVehicleQa({ intent, scene: frame.root }).filter(+ (finding) => finding.code === 'VEH_CONTACT_PLANE',+ );+ expect(findings).toHaveLength(2);+ expect(findings.map((finding) => finding.measurement?.actual)).toEqual(+ expect.arrayContaining([expect.closeTo(0.1, 6), expect.closeTo(-0.1, 6)]),+ );+ leftTrack.position.y = 0.1;+ rightTrack.position.y = 0.1;+ expect(codes(evaluateVehicleQa({ intent, scene: frame.root }))).not.toContain(+ 'VEH_CONTACT_PLANE',+ );+ });++ test('requires declared non-wheel support types and one stable contact plane', () => {+ const frame = createVehicleFrame('TrackedVehicle');+ const left = new THREE.Mesh(new THREE.BoxGeometry(2.4, 0.2, 0.25), metalMaterial);+ left.name = 'LeftTrack';+ left.position.set(0, 0.1, -0.75);+ const right = left.clone();+ right.name = 'RightTrack';+ right.position.set(0, 0.3, 0.75);+ frame.root.add(left, right);+ const intent = createAssetIntentV1({ category: 'vehicle', subtype: 'tracked' });+ expect(codes(evaluateVehicleQa({ intent, scene: frame.root }))).toContain(+ 'VEH_SUPPORT_SET_MISSING',+ );++ stampSemanticMetadataV1(left, { roles: ['support.track.left'] });+ stampSemanticMetadataV1(right, { roles: ['support.track.right'] });+ const findings = evaluateVehicleQa({ intent, scene: frame.root });+ expect(codes(findings)).not.toContain('VEH_SUPPORT_SET_MISSING');+ expect(codes(findings)).toContain('VEH_SUPPORT_PLANE');+ expect(+ findings.find((finding) => finding.code === 'VEH_SUPPORT_PLANE')?.measurement?.actual,+ ).toBeCloseTo(0.2, 6);++ right.position.y = 0.1;+ expect(codes(evaluateVehicleQa({ intent, scene: frame.root }))).not.toEqual(+ expect.arrayContaining(['VEH_SUPPORT_SET_MISSING', 'VEH_SUPPORT_PLANE']),+ );+ });++ test('requires generated +X-front semantics and centered steering ownership', () => {+ const fixture = wheeledVehicle();+ fixture.frame.root.userData = {};+ fixture.wheels[0]!.spinPivot.removeFromParent();+ fixture.frame.root.add(fixture.wheels[0]!.spinPivot);+ fixture.wheels[0]!.spinPivot.position.copy(fixture.wheels[0]!.steeringPivot!.position);+ const findings = fixture.findings();+ expect(codes(findings)).toContain('VEH_FRONT_AXIS');+ expect(codes(findings)).toContain('VEH_STEERING_PIVOT');+ });++ test('rejects a centered steering pivot whose declared local axis is not vehicle +Y', () => {+ const fixture = wheeledVehicle();+ fixture.wheels[0]!.steeringPivot!.rotation.z = Math.PI / 2;+ const steering = fixture.findings().find((finding) => finding.code === 'VEH_STEERING_PIVOT');+ expect(steering?.disposition).toBe('block');+ expect(steering?.measurement?.actual).not.toBe(0);+ });++ test('boat and wheelless profiles never inherit wheel rules', () => {+ const frame = createVehicleFrame('Boat');+ const intent = createAssetIntentV1({ category: 'vehicle', subtype: 'watercraft' });+ const findings = evaluateVehicleQa({ intent, scene: frame.root });+ expect(codes(findings)).not.toContain('VEH_WHEEL_COUNT');+ expect(codes(findings)).not.toContain('VEH_WHEEL_RADIUS');+ });++ test('validates declared rotor pivot, hierarchy, mast center, and +Y axis frame', () => {+ const frame = createVehicleFrame('Helicopter');+ const intent = createAssetIntentV1({ category: 'vehicle', subtype: 'rotorcraft' });+ expect(codes(evaluateVehicleQa({ intent, scene: frame.root }))).toContain('VEH_ROTOR_PIVOT');+ const pivot = new THREE.Object3D();+ pivot.name = 'MainRotorPivot';+ stampSemanticMetadataV1(pivot, {+ roles: ['propulsion.pivot.main'],+ frames: [{ id: 'propulsion-axis.+y', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ });+ const rotor = new THREE.Mesh(new THREE.BoxGeometry(3, 0.05, 0.12), metalMaterial);+ rotor.name = 'MainRotor';+ stampSemanticMetadataV1(rotor, { roles: ['propulsion.rotor.main'] });+ pivot.add(rotor);+ frame.root.add(pivot);+ expect(evaluateVehicleQa({ intent, scene: frame.root })).toEqual([]);++ pivot.rotation.z = Math.PI / 2;+ expect(codes(evaluateVehicleQa({ intent, scene: frame.root }))).toContain('VEH_ROTOR_PIVOT');+ });++ test('validates a declared propeller shaft at its center on vehicle-local +X', () => {+ const frame = createVehicleFrame('PropPlane');+ const pivot = new THREE.Object3D();+ pivot.name = 'PropellerPivot';+ stampSemanticMetadataV1(pivot, {+ roles: ['propulsion.pivot.main'],+ frames: [{ id: 'propulsion-axis.+x', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ });+ const propeller = new THREE.Mesh(new THREE.BoxGeometry(0.08, 2.4, 0.12), metalMaterial);+ stampSemanticMetadataV1(propeller, { roles: ['propulsion.propeller.main'] });+ pivot.add(propeller);+ frame.root.add(pivot);+ const intent = createAssetIntentV1({ category: 'vehicle', subtype: 'fixed-wing' });+ expect(evaluateVehicleQa({ intent, scene: frame.root })).toEqual([]);+ propeller.position.y = 0.2;+ expect(codes(evaluateVehicleQa({ intent, scene: frame.root }))).toContain('VEH_ROTOR_PIVOT');+ });+});diff --git a/src/qa/vehicle.ts b/src/qa/vehicle.tsnew file mode 100644index 00000000..dc7e79ce--- /dev/null+++ b/src/qa/vehicle.ts@@ -0,0 +1,728 @@+import * as THREE from 'three';++import { readSemanticMetadataV1, type VehicleIntentV1 } from '../contracts';+import {+ hasCanonicalVehicleFront,+ resolveVehicleWheelAssemblies,+ type ResolvedWheelAssembly,+} from '../vehicle';+import { conformancePromotionAuthorization, KILN_ENGINE_QA_OWNER, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';+import { VEHICLE_W6_ADVISORY_QA_RULE } from './vehicle-advisory';++const PROFILE = 'vehicle.semantic';+const CENTER_RATIO = 0.03;+const CENTER_MINIMUM = 0.01;+const AXIS_TOLERANCE_DEGREES = 1;+const PAIR_TOLERANCE = 0.015;+const CONTACT_TOLERANCE = 0.02;++function finding(context: QaContext, value: Omit<QaFinding, 'profile' | 'dimension'>): QaFinding {+ return {+ ...value,+ profile: context.intent.qaProfile || PROFILE,+ dimension: 'categoryReadiness',+ viewHints: value.viewHints ?? ['vehicle.underbody', 'vehicle.wheel-section'],+ };+}++function localPoint(rootInverse: THREE.Matrix4, value: THREE.Vector3): THREE.Vector3 {+ return value.clone().applyMatrix4(rootInverse);+}++function rootAxis(root: THREE.Object3D, axis: THREE.Vector3): THREE.Vector3 {+ root.updateWorldMatrix(true, false);+ return axis.clone().transformDirection(root.matrixWorld);+}++function angleDegrees(a: THREE.Vector3, b: THREE.Vector3): number {+ return THREE.MathUtils.radToDeg(+ Math.acos(THREE.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)),+ );+}++function isDescendant(node: THREE.Object3D | undefined, ancestor: THREE.Object3D): boolean {+ let current = node;+ while (current) {+ if (current === ancestor) return true;+ current = current.parent ?? undefined;+ }+ return false;+}++function componentDisposition(wheel: ResolvedWheelAssembly): 'block' | 'warn' {+ return wheel.source === 'semantic' ? 'block' : 'warn';+}++function wheelCountFindings(+ context: QaContext,+ intent: VehicleIntentV1,+ wheels: readonly ResolvedWheelAssembly[],+): QaFinding[] {+ const findings: QaFinding[] = [];+ if (wheels.length !== intent.wheelCount) {+ findings.push(+ finding(context, {+ code: 'VEH_WHEEL_COUNT',+ disposition: 'block',+ message: `Trusted vehicle intent requires ${intent.wheelCount} wheel assemblies; resolved ${wheels.length}.`,+ measurement: {+ name: 'wheelAssemblyCount',+ actual: wheels.length,+ expected: intent.wheelCount,+ threshold: intent.wheelCount,+ },+ repairText:+ 'Create exactly the requested number of axle-centered wheel assemblies and remove duplicate or ungrouped wheel parts.',+ }),+ );+ }+ const axleIds = new Set(wheels.map((wheel) => wheel.index).filter(Boolean));+ if (intent.axleCount > 0 && axleIds.size !== intent.axleCount) {+ findings.push(+ finding(context, {+ code: 'VEH_AXLE_COUNT',+ disposition: 'block',+ message: `Trusted vehicle intent requires ${intent.axleCount} axles; wheel grouping resolved ${axleIds.size}.`,+ measurement: {+ name: 'wheelAxleCount',+ actual: axleIds.size,+ expected: intent.axleCount,+ threshold: intent.axleCount,+ },+ }),+ );+ }+ return findings;+}++function wheelGeometryFindings(+ context: QaContext,+ root: THREE.Object3D,+ wheels: readonly ResolvedWheelAssembly[],+): QaFinding[] {+ const findings: QaFinding[] = [];+ const expectedAxle = rootAxis(root, new THREE.Vector3(0, 0, 1));+ for (const wheel of wheels) {+ const disposition = componentDisposition(wheel);+ const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);+ const pivotInverse = wheel.pivot.matrixWorld.clone().invert();+ const componentCenters = [wheel.tireCenterWorld, wheel.rimCenterWorld, wheel.hubCenterWorld]+ .filter((center): center is THREE.Vector3 => !!center)+ .map((center) => localPoint(pivotInverse, center));+ let centerDelta = 0;+ for (let a = 0; a < componentCenters.length; a++) {+ for (let b = a + 1; b < componentCenters.length; b++) {+ centerDelta = Math.max(centerDelta, componentCenters[a]!.distanceTo(componentCenters[b]!));+ }+ }+ if (!wheel.tire || !wheel.rim || !wheel.hub || centerDelta > centerTolerance) {+ findings.push(+ finding(context, {+ code: 'VEH_WHEEL_CONCENTRICITY',+ disposition,+ message: `Wheel ${wheel.id} tire, rim, and hub must share one axle center.`,+ affected: { node: wheel.root.name },+ measurement: {+ name: 'maximumComponentCenterDelta',+ actual: Number.isFinite(centerDelta) ? centerDelta : null,+ expected: 0,+ threshold: centerTolerance,+ unit: 'm',+ },+ repairText: `Move the tire, rim, and hub of ${wheel.id} to its axle-centered wheel pivot.`,+ }),+ );+ }++ const nested =+ wheel.radius !== undefined &&+ wheel.rimRadius !== undefined &&+ wheel.hubRadius !== undefined &&+ wheel.hubRadius < wheel.rimRadius &&+ wheel.rimRadius < wheel.radius &&+ wheel.rimWidth !== undefined &&+ wheel.hubWidth !== undefined &&+ wheel.width !== undefined &&+ wheel.rimWidth <= wheel.width + 1e-6 &&+ wheel.hubWidth <= wheel.width + 1e-6;+ if (!nested) {+ findings.push(+ finding(context, {+ code: 'VEH_WHEEL_RADIUS',+ disposition,+ message: `Wheel ${wheel.id} must satisfy hub radius < rim radius < tire radius and keep rim/hub widths inside the tire envelope.`,+ affected: { node: wheel.root.name },+ measurement: {+ name: 'nestedRadii',+ actual: false,+ expected: true,+ },+ repairText: `Resize ${wheel.id} so its hub is nested inside its rim and its rim is nested inside its tire.`,+ }),+ );+ }++ const axleAngle = angleDegrees(wheel.spinAxisWorld, expectedAxle);+ if (axleAngle > AXIS_TOLERANCE_DEGREES) {+ findings.push(+ finding(context, {+ code: 'VEH_WHEEL_AXLE_AXIS',+ disposition,+ message: `Wheel ${wheel.id} spin axis must align with vehicle-local +Z.`,+ affected: { node: wheel.pivot.name },+ measurement: {+ name: 'axleAxisAngle',+ actual: axleAngle,+ expected: 0,+ threshold: AXIS_TOLERANCE_DEGREES,+ unit: 'degrees',+ },+ repairText: `Orient ${wheel.pivot.name} so its local +Z is the axle/spin axis.`,+ }),+ );+ }++ const pivotDelta = localPoint(pivotInverse, wheel.pivotCenterWorld).distanceTo(+ localPoint(pivotInverse, wheel.centerWorld),+ );+ const descendants = [wheel.tire, wheel.rim, wheel.hub].every((part) =>+ isDescendant(part, wheel.pivot),+ );+ if (!descendants || pivotDelta > centerTolerance) {+ findings.push(+ finding(context, {+ code: 'VEH_WHEEL_PIVOT',+ disposition,+ message: `Wheel ${wheel.id} pivot must be at the axle center and own every moving component.`,+ affected: { node: wheel.pivot.name },+ measurement: {+ name: 'pivotCenterDelta',+ actual: pivotDelta,+ expected: 0,+ threshold: centerTolerance,+ unit: 'm',+ },+ repairText: `Place ${wheel.pivot.name} at the axle center and parent tire, rim, and hub beneath it.`,+ }),+ );+ }+ }+ return findings;+}++function axlePairFindings(+ context: QaContext,+ root: THREE.Object3D,+ wheels: readonly ResolvedWheelAssembly[],+): QaFinding[] {+ root.updateWorldMatrix(true, false);+ const inverse = root.matrixWorld.clone().invert();+ const groups = new Map<string, ResolvedWheelAssembly[]>();+ for (const wheel of wheels) {+ if (!wheel.index) continue;+ const group = groups.get(wheel.index) ?? [];+ group.push(wheel);+ groups.set(wheel.index, group);+ }+ const findings: QaFinding[] = [];+ for (const [index, pair] of groups) {+ const left = pair.find((wheel) => wheel.side === 'left');+ const right = pair.find((wheel) => wheel.side === 'right');+ if (!left || !right) continue;+ const leftCenter = localPoint(inverse, left.centerWorld);+ const rightCenter = localPoint(inverse, right.centerWorld);+ const delta = Math.hypot(leftCenter.x - rightCenter.x, leftCenter.y - rightCenter.y);+ if (delta > PAIR_TOLERANCE) {+ findings.push(+ finding(context, {+ code: 'VEH_AXLE_PAIR',+ disposition: left.source === 'semantic' && right.source === 'semantic' ? 'block' : 'warn',+ message: `Axle ${index} left/right wheel centers disagree in vehicle-local X/Y.`,+ affected: { node: right.root.name },+ measurement: {+ name: 'pairedCenterXYDelta',+ actual: delta,+ expected: 0,+ threshold: PAIR_TOLERANCE,+ unit: 'm',+ },+ repairText: `Align both wheels on axle ${index} to the same local X and Y coordinates.`,+ }),+ );+ }+ }+ return findings;+}++function duplicateAssemblyFindings(+ context: QaContext,+ root: THREE.Object3D,+ wheels: readonly ResolvedWheelAssembly[],+): QaFinding[] {+ root.updateMatrixWorld(true);+ const inverse = root.matrixWorld.clone().invert();+ const findings: QaFinding[] = [];+ for (let a = 0; a < wheels.length; a++) {+ for (let b = a + 1; b < wheels.length; b++) {+ const left = wheels[a]!;+ const right = wheels[b]!;+ const sameDeclaredCorner =+ left.side !== undefined &&+ left.side === right.side &&+ left.index !== undefined &&+ left.index === right.index;+ const centerDelta = localPoint(inverse, left.centerWorld).distanceTo(+ localPoint(inverse, right.centerWorld),+ );+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(CENTER_MINIMUM, scale * CENTER_RATIO);+ if (!sameDeclaredCorner && centerDelta > threshold) continue;+ const semantic = left.source === 'semantic' && right.source === 'semantic';+ findings.push(+ finding(context, {+ code: 'VEH_DUPLICATE_ASSEMBLY',+ disposition: semantic ? 'block' : 'warn',+ message:+ `Wheel assemblies ${left.id} and ${right.id} resolve to the same ` ++ `${sameDeclaredCorner ? `${left.side}-${left.index} corner` : 'scale-relative center'}.`,+ affected: { node: right.root.name },+ measurement: {+ name: 'duplicateAssemblyCenterDelta',+ actual: centerDelta,+ expected: `>${threshold}`,+ threshold,+ unit: 'm',+ },+ viewHints: [+ 'vehicle.underbody',+ 'vehicle.wheel-section.right',+ 'generic.top.semantic-overlay',+ ],+ repairText: `Remove only duplicate assembly ${right.id} at the reported center; preserve ${left.id} and rebuild the actually missing corner from trusted wheel/axle intent.`,+ }),+ );+ }+ }+ return findings;+}++function contactFindings(+ context: QaContext,+ root: THREE.Object3D,+ intent: VehicleIntentV1,+ wheels: readonly ResolvedWheelAssembly[],+): QaFinding[] {+ if (intent.supportPolicy !== 'grounded') return [];+ root.updateWorldMatrix(true, false);+ const inverse = root.matrixWorld.clone().invert();+ const findings: QaFinding[] = [];+ for (const wheel of wheels.filter((value) => value.loadBearing)) {+ const center = localPoint(inverse, wheel.centerWorld);+ const contactY = center.y - (wheel.radius ?? 0);+ if (wheel.radius === undefined || Math.abs(contactY) > CONTACT_TOLERANCE) {+ findings.push(+ finding(context, {+ code: 'VEH_CONTACT_PLANE',+ disposition: componentDisposition(wheel),+ message: `Load-bearing wheel ${wheel.id} must touch the shared ground plane Y=0 without floating or burial.`,+ affected: { node: wheel.tire?.name ?? wheel.root.name },+ measurement: {+ name: 'tireContactY',+ actual: wheel.radius === undefined ? null : contactY,+ expected: 0,+ threshold: CONTACT_TOLERANCE,+ unit: 'm',+ },+ repairText: `Set ${wheel.id} axle-center Y to its tire radius so its contact point is Y=0.`,+ }),+ );+ }+ }+ return findings;+}++interface SupportContactMeasurement {+ node: THREE.Object3D;+ contactY: number;+ source: 'contact' | 'support';+}++function renderableMinYInRoot(+ rootInverse: THREE.Matrix4,+ node: THREE.Object3D,+): number | undefined {+ let minimum = Infinity;+ node.traverse((part) => {+ if (!(part instanceof THREE.Mesh) || !(part.geometry instanceof THREE.BufferGeometry)) return;+ part.geometry.computeBoundingBox();+ const bounds = part.geometry.boundingBox;+ if (!bounds) return;+ const matrix = rootInverse.clone().multiply(part.matrixWorld);+ for (const x of [bounds.min.x, bounds.max.x]) {+ for (const y of [bounds.min.y, bounds.max.y]) {+ for (const z of [bounds.min.z, bounds.max.z]) {+ minimum = Math.min(minimum, new THREE.Vector3(x, y, z).applyMatrix4(matrix).y);+ }+ }+ }+ });+ return Number.isFinite(minimum) ? minimum : undefined;+}++/** Minimal W4 support contact contract. Missing/stability-set policy remains VEH-022;+ * any declared support/contact that is present must already honor canonical ground Y=0. */+function supportContactFindings(+ context: QaContext,+ root: THREE.Object3D,+ intent: VehicleIntentV1,+): QaFinding[] {+ if (intent.supportPolicy !== 'grounded') return [];+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const explicitContacts: SupportContactMeasurement[] = [];+ const supports: SupportContactMeasurement[] = [];+ root.traverse((node) => {+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ const isWheelContact = roles.some((role) => role.startsWith('wheel.contact.'));+ if (!isWheelContact && roles.some((role) => role.startsWith('contact.'))) {+ explicitContacts.push({+ node,+ contactY: localPoint(inverse, new THREE.Vector3().setFromMatrixPosition(node.matrixWorld))+ .y,+ source: 'contact',+ });+ }+ if (roles.some((role) => role.startsWith('support.'))) {+ const contactY = renderableMinYInRoot(inverse, node);+ if (contactY !== undefined) supports.push({ node, contactY, source: 'support' });+ }+ });+ const measurements = explicitContacts.length > 0 ? explicitContacts : supports;+ const findings = measurements.flatMap((measurement) => {+ if (Math.abs(measurement.contactY) <= CONTACT_TOLERANCE) return [];+ return [+ finding(context, {+ code: 'VEH_CONTACT_PLANE',+ disposition: 'block',+ message: `Load-bearing ${measurement.source} ${measurement.node.name || '(unnamed)'} must touch the shared ground plane Y=0 without floating or burial.`,+ affected: { node: measurement.node.name || 'vehicle-support' },+ measurement: {+ name: 'supportContactY',+ actual: measurement.contactY,+ expected: 0,+ threshold: CONTACT_TOLERANCE,+ unit: 'm',+ },+ repairText: `Move ${measurement.node.name || 'the support'} so its declared contact rests at vehicle-local Y=0.`,+ }),+ ];+ });+ if (intent.wheelCount === 0) {+ for (const expected of intent.supportAssemblies) {+ const matches = [...explicitContacts, ...supports].filter((measurement) =>+ (readSemanticMetadataV1(measurement.node)?.roles ?? []).some(+ (role) =>+ role === `support.${expected}` ||+ role.startsWith(`support.${expected}.`) ||+ role === `contact.${expected}` ||+ role.startsWith(`contact.${expected}.`),+ ),+ );+ if (matches.length > 0) continue;+ findings.push(+ finding(context, {+ code: 'VEH_SUPPORT_SET_MISSING',+ disposition: 'block',+ message: `Trusted grounded ${intent.subtype} intent requires semantic ${expected} supports or contacts.`,+ affected: { node: root.name || 'vehicle-root' },+ measurement: {+ name: `${expected}SupportCount`,+ actual: 0,+ expected: '>=1',+ threshold: 1,+ },+ viewHints: ['vehicle.underbody', 'generic.front.depth-contact'],+ repairText: `Add only the declared ${expected} support set, tag each load-bearing part/contact semantically, and place every contact on vehicle-local Y=0.`,+ }),+ );+ }+ if (measurements.length > 1) {+ const values = measurements.map((measurement) => measurement.contactY);+ const range = Math.max(...values) - Math.min(...values);+ if (range > CONTACT_TOLERANCE) {+ findings.push(+ finding(context, {+ code: 'VEH_SUPPORT_PLANE',+ disposition: 'block',+ message: `Declared non-wheel supports do not share one stable vehicle-local contact plane.`,+ affected: { node: root.name || 'vehicle-root' },+ measurement: {+ name: 'supportContactPlaneRange',+ actual: range,+ expected: 0,+ threshold: CONTACT_TOLERANCE,+ unit: 'm',+ },+ viewHints: ['vehicle.underbody', 'generic.front.depth-contact'],+ repairText:+ 'Move only the reported skid, landing-gear, track, or other support contacts onto one vehicle-local Y=0 plane while preserving their stance.',+ }),+ );+ }+ }+ }+ return findings;+}++function steeringFindings(+ context: QaContext,+ root: THREE.Object3D,+ intent: VehicleIntentV1,+ wheels: readonly ResolvedWheelAssembly[],+): QaFinding[] {+ if (intent.steering === 'none' || wheels.length === 0) return [];+ root.updateWorldMatrix(true, false);+ const inverse = root.matrixWorld.clone().invert();+ const expectedAxis = rootAxis(root, new THREE.Vector3(0, 1, 0));+ const localCenters = wheels.map((wheel) => ({+ wheel,+ center: localPoint(inverse, wheel.centerWorld),+ }));+ const extreme =+ intent.steering === 'rear'+ ? Math.min(...localCenters.map((entry) => entry.center.x))+ : Math.max(...localCenters.map((entry) => entry.center.x));+ const targets =+ intent.steering === 'all'+ ? localCenters+ : localCenters.filter((entry) => Math.abs(entry.center.x - extreme) <= PAIR_TOLERANCE);+ const findings: QaFinding[] = [];+ for (const { wheel } of targets) {+ const steering = wheel.steeringPivot;+ const centerDelta = steering+ ? localPoint(+ inverse,+ new THREE.Vector3().setFromMatrixPosition(steering.matrixWorld),+ ).distanceTo(localPoint(inverse, wheel.centerWorld))+ : Infinity;+ const axisAngle = steering+ ? angleDegrees(+ new THREE.Vector3(0, 1, 0).transformDirection(steering.matrixWorld),+ expectedAxis,+ )+ : Infinity;+ if (+ !steering ||+ !isDescendant(wheel.pivot, steering) ||+ centerDelta > CENTER_MINIMUM ||+ axisAngle > AXIS_TOLERANCE_DEGREES+ ) {+ const axisInvalid = axisAngle > AXIS_TOLERANCE_DEGREES;+ findings.push(+ finding(context, {+ code: 'VEH_STEERING_PIVOT',+ disposition: componentDisposition(wheel),+ message: `Declared steering wheel ${wheel.id} requires a centered +Y steering pivot owning its spin pivot.`,+ affected: { node: steering?.name ?? wheel.pivot.name },+ measurement: {+ name: axisInvalid ? 'steeringAxisAngle' : 'steeringPivotCenterDelta',+ actual: axisInvalid+ ? Number.isFinite(axisAngle)+ ? axisAngle+ : null+ : Number.isFinite(centerDelta)+ ? centerDelta+ : null,+ expected: 0,+ threshold: axisInvalid ? AXIS_TOLERANCE_DEGREES : CENTER_MINIMUM,+ unit: axisInvalid ? 'degrees' : 'm',+ },+ repairText: `Move the steering pivot for ${wheel.id} to the axle center, orient local +Y as steering axis, and parent the wheel spin pivot beneath it.`,+ }),+ );+ }+ }+ return findings;+}++interface PropulsionPart {+ id: string;+ kind: 'rotor' | 'propeller';+ node: THREE.Object3D;+}++function propulsionFindings(+ context: QaContext,+ root: THREE.Object3D,+ intent: VehicleIntentV1,+): QaFinding[] {+ const expectedKinds = intent.propulsionAssemblies.filter(+ (value): value is 'rotor' | 'propeller' => value === 'rotor' || value === 'propeller',+ );+ if (expectedKinds.length === 0) return [];+ const pivots = new Map<string, THREE.Object3D>();+ const components: PropulsionPart[] = [];+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ for (const role of metadata?.roles ?? []) {+ if (role.startsWith('propulsion.pivot.'))+ pivots.set(role.slice('propulsion.pivot.'.length), node);+ for (const kind of ['rotor', 'propeller'] as const) {+ if (role.startsWith(`propulsion.${kind}.`)) {+ components.push({ id: role.slice(`propulsion.${kind}.`.length), kind, node });+ }+ }+ }+ });+ const findings: QaFinding[] = [];+ root.updateWorldMatrix(true, false);+ const rootInverse = root.matrixWorld.clone().invert();+ for (const kind of expectedKinds) {+ const candidates = components.filter((part) => part.kind === kind);+ if (candidates.length === 0) {+ findings.push(+ finding(context, {+ code: 'VEH_ROTOR_PIVOT',+ disposition: 'block',+ message: `Trusted vehicle intent requires a semantic ${kind} assembly and centered pivot.`,+ measurement: { name: `${kind}AssemblyCount`, actual: 0, expected: 1, threshold: 1 },+ }),+ );+ continue;+ }+ for (const component of candidates) {+ const pivot = pivots.get(component.id);+ const box = new THREE.Box3().setFromObject(component.node);+ const center = box.isEmpty() ? undefined : box.getCenter(new THREE.Vector3());+ const pivotCenter = pivot+ ? new THREE.Vector3().setFromMatrixPosition(pivot.matrixWorld)+ : undefined;+ const delta =+ center && pivotCenter+ ? localPoint(rootInverse, center).distanceTo(localPoint(rootInverse, pivotCenter))+ : Infinity;+ const frameId = kind === 'rotor' ? 'propulsion-axis.+y' : 'propulsion-axis.+x';+ const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find(+ (frame) => frame.id === frameId,+ );+ const canonicalAxis =+ kind === 'rotor' ? new THREE.Vector3(0, 1, 0) : new THREE.Vector3(1, 0, 0);+ const axisAngle =+ pivot && axisFrame+ ? angleDegrees(+ canonicalAxis+ .clone()+ .applyQuaternion(new THREE.Quaternion(...axisFrame.rotation))+ .transformDirection(pivot.matrixWorld),+ rootAxis(root, canonicalAxis),+ )+ : Infinity;+ if (+ !pivot ||+ !isDescendant(component.node, pivot) ||+ delta > CENTER_MINIMUM ||+ !axisFrame ||+ axisAngle > AXIS_TOLERANCE_DEGREES+ ) {+ findings.push(+ finding(context, {+ code: 'VEH_ROTOR_PIVOT',+ disposition: 'block',+ message: `${kind} ${component.id} requires a centered owning pivot with ${frameId}.`,+ affected: { node: pivot?.name ?? component.node.name },+ measurement: {+ name:+ axisAngle > AXIS_TOLERANCE_DEGREES+ ? 'propulsionAxisAngle'+ : 'propulsionPivotCenterDelta',+ actual:+ axisAngle > AXIS_TOLERANCE_DEGREES+ ? Number.isFinite(axisAngle)+ ? axisAngle+ : null+ : Number.isFinite(delta)+ ? delta+ : null,+ expected: 0,+ threshold:+ axisAngle > AXIS_TOLERANCE_DEGREES ? AXIS_TOLERANCE_DEGREES : CENTER_MINIMUM,+ unit: axisAngle > AXIS_TOLERANCE_DEGREES ? 'degrees' : 'm',+ },+ repairText: `Place the ${kind} pivot at the mast/shaft center, parent the moving geometry beneath it, and declare ${frameId}.`,+ }),+ );+ }+ }+ }+ return findings;+}++export function evaluateVehicleQa(context: QaContext): readonly QaFinding[] {+ if (context.intent.category !== 'vehicle' || !(context.scene instanceof THREE.Object3D))+ return [];+ const intent = context.intent.vehicle;+ if (!intent) return [];+ const root = context.scene;+ root.updateMatrixWorld(true);+ const wheels = resolveVehicleWheelAssemblies(root);+ const findings: QaFinding[] = [];+ if (!hasCanonicalVehicleFront(root)) {+ findings.push(+ finding(context, {+ code: 'VEH_FRONT_AXIS',+ disposition: 'block',+ message: 'Generated vehicles must declare the trusted semantic +X front frame.',+ affected: { node: root.name || 'vehicle-root' },+ measurement: { name: 'canonicalFrontDeclared', actual: false, expected: true },+ repairText:+ 'Author the vehicle beneath createVehicleFrame() and preserve vehicle.front.+x semantics.',+ }),+ );+ }+ if (intent.wheelCount > 0 || intent.subtype === 'wheeled') {+ findings.push(...wheelCountFindings(context, intent, wheels));+ findings.push(...wheelGeometryFindings(context, root, wheels));+ findings.push(...axlePairFindings(context, root, wheels));+ findings.push(...duplicateAssemblyFindings(context, root, wheels));+ findings.push(...contactFindings(context, root, intent, wheels));+ findings.push(...steeringFindings(context, root, intent, wheels));+ }+ findings.push(...supportContactFindings(context, root, intent));+ findings.push(...propulsionFindings(context, root, intent));+ return findings;+}++export const VEHICLE_QA_RULE: QaRule = {+ id: 'VEHICLE_PROFILE',+ profile: PROFILE,+ scope: { kind: 'category', category: 'vehicle' },+ ruleClass: 'exact',+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization(+ 'vehicle-qa-v1',+ 'src/qa/vehicle.test.ts',+ '4bffa0dff0ed33be2ce7003ee36ac33efc5b4900e57d390898e43551912e626b',+ ),+ defaultMode: 'enforce',+ evaluate: (context) =>+ evaluateVehicleQa(context).filter((finding) => finding.disposition === 'block'),+};++/** Name/geometric fallback inference remains observe-only until subtype calibration is frozen. */+export const VEHICLE_ADVISORY_QA_RULE: QaRule = {+ id: 'VEHICLE_ADVISORY_PROFILE',+ profile: 'vehicle.advisory',+ scope: { kind: 'category', category: 'vehicle' },+ ruleClass: 'heuristic',+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: 'observe',+ evaluate: (context) =>+ evaluateVehicleQa(context).filter((finding) => finding.disposition !== 'block'),+};++export const VEHICLE_QA_RULES: readonly QaRule[] = [+ VEHICLE_QA_RULE,+ VEHICLE_ADVISORY_QA_RULE,+ VEHICLE_W6_ADVISORY_QA_RULE,+] as const;diff --git a/src/render.ts b/src/render.tsindex d596190e..ad599e71 100644--- a/src/render.ts+++ b/src/render.ts@@ -40,6 +40,52 @@ import {type InstanceabilityMetrics,type InstanceabilityReport,} from './metrics';+import {+ cloneSemanticMetadataV1,+ createAssetIntentV1,+ createSemanticMetadataV1,+ isAssetCategory,+ KILN_SEMANTIC_EXTRAS_KEY,+ validateSemanticMetadataV1,+ type AssetCategory,+ type AssetIntentV1,+} from './contracts';+import {+ assertFinalGlbValid,+ GltfValidationError,+ validateFinalGlbBytes,+ type KhronosGltfValidationReport,+} from './qa/gltf';+import {+ appendFinalGltfQa,+ appendMaterialMetricsQa,+ appendRuntimeCostQa,+ AssetQaBlockedError,+ runDeterministicSceneQa,+} from './qa/run';+import { appendFinalVfxGlbQa } from './qa/breadth-final';+import type { AssetQaReportV1 } from './qa/types';+import {+ collectMaterialMetricsV1,+ evaluateMaterialBudgetV1,+ materialBudgetProfileForQaProfile,+ type MaterialMetricsV1,+} from './material-metrics';+import {+ collectMaterialRecipeApplications,+ type MaterialRecipeApplicationProvenanceV1,+} from './material-recipe-runtime';+import {+ collectMaterialResourceProvenance,+ type MaterialResourceProvenanceV1,+} from './material-resources';+import {+ captureCharacterDiagnosticViews,+ type CharacterCapturedDiagnosticV1,+} from './views/character-capture';+import { captureVehicleDiagnosticViews, type VehicleCapturedDiagnosticV1 } from './views/vehicle';++export type CapturedDiagnosticV1 = CharacterCapturedDiagnosticV1 | VehicleCapturedDiagnosticV1;// WebIO (not NodeIO) is used for GLB serialization so the same code path// works in both Node and browser environments. writeBinary() only builds the@@ -210,6 +256,7 @@ function bridgeMaterial(isMeshStandardMaterial?: boolean;isMeshLambertMaterial?: boolean;isMeshBasicMaterial?: boolean;+ isSpriteMaterial?: boolean;};if (matFlags.isMeshStandardMaterial) {const stdMat = threeMat as THREE.MeshStandardMaterial;@@ -219,7 +266,10 @@ function bridgeMaterial(if (stdMat.emissive) {mat.setEmissiveFactor([stdMat.emissive.r, stdMat.emissive.g, stdMat.emissive.b]);}- if (stdMat.transparent) {+ if (stdMat.alphaTest > 0) {+ mat.setAlphaMode('MASK');+ mat.setAlphaCutoff(stdMat.alphaTest);+ } else if (stdMat.transparent) {mat.setAlphaMode('BLEND');}if (stdMat.side === THREE.DoubleSide) {@@ -237,6 +287,11 @@ function bridgeMaterial(// metallic + roughness live in one glTF texture (R=unused, G=rough, B=metal).// If the agent used separate Three.js maps we emit the roughness one as// the combined channel — the common case is a single combined map anyway.+ if (stdMat.roughnessMap && stdMat.metalnessMap && stdMat.roughnessMap !== stdMat.metalnessMap) {+ throw new TypeError(+ `Material ${JSON.stringify(threeMat.name || '(unnamed)')} uses separate roughness/metalness textures. Pack G=roughness/B=metalness before export.`,+ );+ }const mrSource = stdMat.roughnessMap ?? stdMat.metalnessMap;if (mrSource) {const t = bridgeTexture(doc, mrSource, textureCache);@@ -269,6 +324,38 @@ function bridgeMaterial(]);mat.setRoughnessFactor(1.0);mat.setMetallicFactor(0.0);+ } else if (matFlags.isSpriteMaterial) {+ const spriteMat = threeMat as THREE.SpriteMaterial;+ mat.setBaseColorFactor([+ spriteMat.color.r,+ spriteMat.color.g,+ spriteMat.color.b,+ spriteMat.opacity,+ ]);+ mat.setRoughnessFactor(1.0);+ mat.setMetallicFactor(0.0);+ }++ // Material alpha/sidedness is shared across Three.js material families.+ // Keep this after the family-specific PBR mapping so SpriteMaterial and+ // MeshBasic/Lambert materials cannot pass scene QA and then become opaque or+ // single-sided in the GLB bridge.+ const common = threeMat as THREE.Material & {+ alphaTest?: number;+ transparent?: boolean;+ opacity?: number;+ map?: THREE.Texture | null;+ };+ if ((common.alphaTest ?? 0) > 0) {+ mat.setAlphaMode('MASK');+ mat.setAlphaCutoff(common.alphaTest ?? 0.5);+ } else if (common.transparent || (common.opacity ?? 1) < 1) {+ mat.setAlphaMode('BLEND');+ }+ if (threeMat.side === THREE.DoubleSide) mat.setDoubleSided(true);+ if (common.map && !mat.getBaseColorTexture()) {+ const texture = bridgeTexture(doc, common.map, textureCache);+ if (texture) mat.setBaseColorTexture(texture);}cache.set(threeMat, mat);@@ -352,6 +439,18 @@ function bridgeGeometry();}+ const tangentAttr = geometry.getAttribute('tangent') as THREE.BufferAttribute | undefined;+ if (tangentAttr?.itemSize === 4) {+ prim.setAttribute(+ 'TANGENT',+ doc+ .createAccessor(meshName + '_tangent')+ .setArray(new Float32Array(tangentAttr.array))+ .setType(TYPE_VEC4)+ .setBuffer(buf),+ );+ }+const indexAttr = geometry.getIndex();if (indexAttr) {// Uint16 holds indices up to 65535; a geometry with more vertices needs@@ -381,6 +480,55 @@ function bridgeNode(): GtNode {const gtNode = doc.createNode(threeObj.name || undefined);+ // Only the versioned Kiln semantic payload is promoted from Three.js+ // userData into glTF extras. Arbitrary userData can contain encoded textures+ // and other non-JSON values, so exporting it wholesale is intentionally+ // forbidden. A malformed reserved payload is an authoring error rather than+ // something the bridge may silently drop.+ const semanticValue = threeObj.userData[KILN_SEMANTIC_EXTRAS_KEY];+ let semanticForExport = semanticValue;+ if ((threeObj as THREE.Object3D & { isSprite?: boolean }).isSprite) {+ // glTF has no native Sprite primitive. The bridge emits a quad below and+ // stamps the actual Three.js spherical-facing behavior as a portable+ // semantic so a runtime consumer can reconstruct it deterministically.+ if (semanticValue === undefined) {+ semanticForExport = createSemanticMetadataV1({+ roles: ['vfx.facing.camera-spherical', 'vfx.effect.surface.card'],+ });+ } else {+ const existing = validateSemanticMetadataV1(semanticValue);+ if (existing.valid && existing.value) {+ semanticForExport = {+ ...cloneSemanticMetadataV1(existing.value),+ roles: [+ // The exporter owns the runtime truth for Sprite facing. Drop any+ // contradictory model-authored facing self-report before stamping+ // the actual spherical behavior.+ ...existing.value.roles.filter((role) => !role.startsWith('vfx.facing.')),+ 'vfx.facing.camera-spherical',+ ...(existing.value.roles.some((role) => role.startsWith('vfx.effect.surface'))+ ? []+ : ['vfx.effect.surface.card']),+ ],+ };+ }+ }+ }+ if (semanticForExport !== undefined) {+ const semantic = validateSemanticMetadataV1(semanticForExport);+ if (!semantic.valid || !semantic.value) {+ const detail = semantic.issues+ .map((issue) => `${issue.path || '<root>'}: ${issue.message}`)+ .join('; ');+ throw new TypeError(+ `Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on node ${threeObj.name || '<unnamed>'}: ${detail}`,+ );+ }+ gtNode.setExtras({+ [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic.value),+ });+ }+gtNode.setTranslation([threeObj.position.x, threeObj.position.y, threeObj.position.z]);gtNode.setRotation([threeObj.quaternion.x,@@ -406,6 +554,28 @@ function bridgeNode(meshCache.set(cacheKey, gtMesh);}gtNode.setMesh(gtMesh);+ } else if ((threeObj as THREE.Object3D & { isSprite?: boolean }).isSprite) {+ const sprite = threeObj as THREE.Sprite;+ const threeMat = sprite.material;+ const gtMat = bridgeMaterial(doc, threeMat, matCache, texCache);+ // Unit XY quad matches Three.js Sprite scale semantics. Non-default center+ // and material rotation are baked into the quad; camera-facing remains an+ // explicit semantic runtime behavior on the exported node.+ const centerX = sprite.center?.x ?? 0.5;+ const centerY = sprite.center?.y ?? 0.5;+ const rotation = sprite.material.rotation ?? 0;+ const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;+ let gtMesh = meshCache.get(cacheKey);+ if (!gtMesh) {+ const geometry = new THREE.PlaneGeometry(1, 1);+ if (centerX !== 0.5 || centerY !== 0.5) {+ geometry.translate(0.5 - centerX, 0.5 - centerY, 0);+ }+ if (rotation !== 0) geometry.rotateZ(rotation);+ gtMesh = bridgeGeometry(doc, buf, geometry, gtMat, sprite.name || 'sprite-quad');+ meshCache.set(cacheKey, gtMesh);+ }+ gtNode.setMesh(gtMesh);}if (threeObj.name) {@@ -484,6 +654,11 @@ function bridgeAnimations(anim.addSampler(sampler);anim.addChannel(channel);}++ // Never serialize an empty Animation object: Khronos correctly reports+ // EMPTY_ENTITY as an error. Advisory-only unresolved tracks are skipped;+ // explicit required tracks have already been blocked by deterministic QA.+ if (anim.listChannels().length === 0) anim.dispose();}}@@ -496,6 +671,11 @@ export interface RenderResult {tris: number;meta: KilnCodeMeta;warnings: string[];+ /** Automatic category diagnostics captured from the exact final source scene. */+ diagnosticViews?: CapturedDiagnosticV1[];+ materialMetrics?: MaterialMetricsV1;+ materialRecipeApplications?: MaterialRecipeApplicationProvenanceV1[];+ materialResourceProvenance?: MaterialResourceProvenanceV1[];}/**@@ -554,6 +734,10 @@ export interface RenderSceneResult {bytes: Uint8Array;tris: number;warnings: string[];+ /** Official Khronos report for these exact post-transform bytes. */+ gltfValidation: KhronosGltfValidationReport;+ /** Five-signal deterministic report for the exact scene and final bytes. */+ qaReport: AssetQaReportV1;/** Post-dedup (and post-optimize, when enabled) instanceability report* (informational). Undefined if it threw. */instanceability?: InstanceabilityReport;@@ -563,6 +747,11 @@ export interface RenderSceneResult {optimize?: OptimizeSummary;/** Set when the GPU-instancing pass created batches (instance !== 'off'). */instancing?: InstancingSummary;+ /** Category captures selected only by trusted intent from the exact source scene. */+ diagnosticViews?: CapturedDiagnosticV1[];+ materialMetrics?: MaterialMetricsV1;+ materialRecipeApplications?: MaterialRecipeApplicationProvenanceV1[];+ materialResourceProvenance?: MaterialResourceProvenanceV1[];}export interface RenderSceneOptions {@@ -577,6 +766,8 @@ export interface RenderSceneOptions {dedup?: boolean;/** Asset category, threaded into the instanceability grade context. */category?: string;+ /** Full closure-owned intent. Authoritative over category when supplied. */+ intent?: AssetIntentV1;/*** Opt-in material consolidation, applied after dedup. Defaults to the* `KILN_BAKE_OPTIMIZE` env (else `off`). `off` is byte-identical to today.@@ -688,13 +879,12 @@ async function applyGpuInstancing(* `palette` collapses distinct untextured flat-color materials into one palette* material + a small palette texture (textured materials pass through untouched);* `weld` + `prune` clean up. `full` adds `flatten → join` to also reduce draws,- * but ONLY for static assets — if the Document carries animations or skins it- * auto-degrades to `palette` so a rig is never disturbed (flatten leaves animated- * nodes + skeletons in place by design, and join({keepNamed:true}) never merges a- * named pivot, but degrading is the belt-and-braces guarantee). `prune` keeps- * empty leaf nodes + extras so named pivots that Kiln City behaviors target by- * name survive. palette groups by alpha mode, so opaque + the one glass slot stay- * distinct materials (transparency is never flattened into opaque).+ * but ONLY for static, semantics-free assets — animations, skins, or any reserved+ * semantic extras auto-degrade to `palette` so a rig, portal-clearance node,+ * socket, or separable role is never flattened away. `prune` keeps empty leaf+ * nodes + extras so named pivots that Kiln City behaviors target by name survive.+ * palette groups by alpha mode, so opaque + the one glass slot stay distinct+ * materials (transparency is never flattened into opaque).** Returns what it did; throws are the caller's to handle (the GLB is otherwise* valid). Pure w.r.t. inputs other than the mutated Document.@@ -706,15 +896,27 @@ async function consolidateMaterials(const before = collectGlbMetrics(doc);const root = doc.getRoot();const animatedOrSkinned = root.listAnimations().length > 0 || root.listSkins().length > 0;- const effective: 'palette' | 'full' = mode === 'full' && animatedOrSkinned ? 'palette' : mode;+ const semanticGraph = root+ .listNodes()+ .some((node) => node.getExtras()[KILN_SEMANTIC_EXTRAS_KEY] !== undefined);+ const effective: 'palette' | 'full' =+ mode === 'full' && (animatedOrSkinned || semanticGraph) ? 'palette' : mode;const steps = [palette({ min: PALETTE_MIN })];if (effective === 'full') {- // flatten() leaves skeletons + animation-targeted nodes in place; join keeps- // named meshes/nodes intact so pivots survive. Both only run on static assets.+ // flatten() leaves skeletons + animation-targeted nodes in place, but it may+ // remove empty semantic clearance/socket nodes even when prune keeps leaves+ // and extras. Full therefore runs only on static, semantics-free graphs.steps.push(flatten(), join({ keepNamed: true }));}- steps.push(weld(), prune({ keepLeaves: true, keepExtras: true }));+ // A solid texture can be semantically meaningful in more than one slot (for+ // example the same unnamed bytes used as base color, normal, and packed MR).+ // gltf-transform's default solid-texture pruning folds base/MR pixels into+ // factors but retains the normal binding, corrupting that shared-slot case+ // while remaining validator-clean. Preserve authored textures across every+ // material rebake; palette-generated textures and ordinary dead resources are+ // still cleaned normally.+ steps.push(weld(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));await doc.transform(...steps);@@ -749,6 +951,14 @@ export async function renderSceneToGLB(const clips = opts.clips ?? [];const warnings: string[] = [];const tris = countTriangles(root);+ const intent =+ opts.intent ??+ createAssetIntentV1({+ category: isAssetCategory(opts.category) ? opts.category : 'prop',+ });+ const trustedCategory = intent.category;+ const materialRecipeApplications = collectMaterialRecipeApplications(root);+ const materialResourceProvenance = collectMaterialResourceProvenance(root);// Runtime-aware joint-name validation (follow-up #6 from the W1.1 spike// report). Walk the scene graph + animation tracks and surface any track@@ -758,7 +968,12 @@ export async function renderSceneToGLB(// pivot" hint is first; the bridge also emits a briefer "target not// found - skipped" for each unresolved track (kept for compatibility).for (const w of inspectGeneratedAnimation(root, clips)) warnings.push(w);- for (const w of inspectSceneStructure(root)) warnings.push(w);+ for (const w of inspectSceneStructure(root, { category: trustedCategory })) warnings.push(w);++ const sceneQaReport = runDeterministicSceneQa({ intent, scene: root, clips });+ if (sceneQaReport.disposition === 'block') {+ throw new AssetQaBlockedError(sceneQaReport, 'scene');+ }const doc = new Document();const buf = doc.createBuffer();@@ -833,22 +1048,95 @@ export async function renderSceneToGLB(doc,optimize || instancing ? undefined : tris,);- instanceability = gradeInstanceability(metrics, { category: opts.category });+ instanceability = gradeInstanceability(metrics, { category: trustedCategory });} catch (err) {metricsError = err instanceof Error ? err.message : String(err);}+ let materialMetrics: MaterialMetricsV1 | undefined;+ let materialBudgetWarnings = [] as ReturnType<typeof evaluateMaterialBudgetV1>;+ try {+ materialMetrics = collectMaterialMetricsV1(doc);+ const tier = /(?:^|\.)hero(?:\.|$)/i.test(intent.qaProfile)+ ? 'hero'+ : /(?:^|\.)background(?:\.|$)/i.test(intent.qaProfile)+ ? 'background'+ : 'standard';+ materialBudgetWarnings = evaluateMaterialBudgetV1(materialMetrics, {+ profile: materialBudgetProfileForQaProfile(intent.qaProfile),+ tier,+ });+ } catch (error) {+ warnings.push(+ `material metrics failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+const io = engineIO();const bytes = await io.writeBinary(doc);+ const gltfValidation = await validateFinalGlbBytes(bytes);+ const finalGltfReport = appendFinalGltfQa(intent, sceneQaReport, gltfValidation);+ const runtimeQaReport = appendRuntimeCostQa(+ intent,+ finalGltfReport,+ instanceability,+ metricsError,+ );+ const materialQaReport = materialMetrics+ ? appendMaterialMetricsQa(intent, runtimeQaReport, materialMetrics, materialBudgetWarnings)+ : runtimeQaReport;+ const qaReport = await appendFinalVfxGlbQa(intent, materialQaReport, bytes);+ if (qaReport.disposition === 'block') {+ throw new AssetQaBlockedError(qaReport, 'final-glb', gltfValidation);+ }+ for (const issue of gltfValidation.issues.messages) {+ if (issue.severity !== 1) continue;+ warnings.push(+ `glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ''}: ${issue.message}`,+ );+ }++ let diagnosticViews: CapturedDiagnosticV1[] | undefined;+ if (intent.category === 'character' && intent.character) {+ try {+ const findings = Object.values(qaReport.dimensions).flatMap(+ (dimension) => dimension.findings,+ );+ diagnosticViews = await captureCharacterDiagnosticViews(+ root,+ clips,+ intent.character,+ findings,+ );+ } catch (error) {+ warnings.push(+ `character diagnostic capture failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ } else if (intent.category === 'vehicle' && intent.vehicle) {+ try {+ diagnosticViews = captureVehicleDiagnosticViews(root, intent);+ } catch (error) {+ warnings.push(+ `vehicle diagnostic capture failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ }return {bytes,tris,warnings,+ gltfValidation,+ qaReport,instanceability,metricsError,...(optimize ? { optimize } : {}),...(instancing ? { instancing } : {}),+ ...(diagnosticViews ? { diagnosticViews } : {}),+ ...(materialMetrics ? { materialMetrics } : {}),+ ...(materialRecipeApplications.length ? { materialRecipeApplications } : {}),+ ...(materialResourceProvenance.length ? { materialResourceProvenance } : {}),};}@@ -863,23 +1151,33 @@ export async function renderSceneToGLB(*/export async function renderGLB(code: string,- opts: { optimize?: OptimizeMode; instance?: InstanceMode } = {},+ opts: {+ optimize?: OptimizeMode;+ instance?: InstanceMode;+ intent?: AssetIntentV1;+ category?: AssetCategory;+ } = {},): Promise<RenderResult> {const { meta, root, clips, primitiveUsage } = await executeKilnCode(code);+ const requestedCategory = opts.intent?.category ?? opts.category;const scene = await renderSceneToGLB(root, {sceneName: meta.name || 'Scene',clips,- category: typeof meta.category === 'string' ? meta.category : undefined,+ ...(requestedCategory ? { category: requestedCategory } : {}),+ ...(opts.intent ? { intent: opts.intent } : {}),role: meta.role,...(opts.optimize ? { optimize: opts.optimize } : {}),...(opts.instance ? { instance: opts.instance } : {}),});+ const { category: modelCategory, ...modelMeta } = meta;return {glb: Buffer.from(scene.bytes),tris: scene.tris,meta: {- ...meta,+ ...modelMeta,+ ...(modelCategory !== undefined ? { modelCategory } : {}),+ ...(requestedCategory ? { category: requestedCategory } : {}),tris: scene.tris,primitiveUsage,...(scene.instanceability@@ -888,8 +1186,18 @@ export async function renderGLB(...(scene.metricsError ? { metricsError: scene.metricsError } : {}),...(scene.optimize ? { optimize: scene.optimize } : {}),...(scene.instancing ? { instancing: scene.instancing } : {}),+ gltfValidation: scene.gltfValidation,+ qaReport: scene.qaReport,},warnings: scene.warnings,+ ...(scene.diagnosticViews ? { diagnosticViews: scene.diagnosticViews } : {}),+ ...(scene.materialMetrics ? { materialMetrics: scene.materialMetrics } : {}),+ ...(scene.materialRecipeApplications+ ? { materialRecipeApplications: scene.materialRecipeApplications }+ : {}),+ ...(scene.materialResourceProvenance+ ? { materialResourceProvenance: scene.materialResourceProvenance }+ : {}),};}@@ -924,6 +1232,8 @@ export interface OptimizeGlbResult {summary?: OptimizeSummary;/** What the GPU-instancing pass did (absent when it was off / skipped / no-op). */instancing?: InstancingSummary;+ /** Official Khronos report for the exact rebaked bytes. */+ gltfValidation: KhronosGltfValidationReport;}/**@@ -969,6 +1279,7 @@ export async function optimizeGlbBytes(if (mode) summary = await consolidateMaterials(doc, mode);if (!summary && !instancing) return undefined;const outBytes = await io.writeBinary(doc);+ const gltfValidation = await assertFinalGlbValid(outBytes);let report: InstanceabilityReport | undefined;try {report = gradeInstanceability(collectGlbMetrics(doc), { category: opts.category });@@ -977,11 +1288,13 @@ export async function optimizeGlbBytes(}return {bytes: outBytes,+ gltfValidation,...(report ? { report } : {}),...(summary ? { summary } : {}),...(instancing ? { instancing } : {}),};- } catch {+ } catch (error) {+ if (error instanceof GltfValidationError) throw error;return undefined;}}@@ -1002,6 +1315,8 @@ export interface SnapGlbResult {snapped: number;/** Materials left unchanged (textured / hero, or no eligible slot). */skipped: number;+ /** Official Khronos report for the exact palette-rebaked bytes. */+ gltfValidation: KhronosGltfValidationReport;}/**@@ -1076,14 +1391,23 @@ export async function snapGlbToPalette(drawsAfter: after.drawCalls,};const outBytes = await io.writeBinary(doc);+ const gltfValidation = await assertFinalGlbValid(outBytes);let report: InstanceabilityReport | undefined;try {report = gradeInstanceability(after, { category: opts.category });} catch {report = undefined;}- return { bytes: outBytes, ...(report ? { report } : {}), summary, snapped, skipped };- } catch {+ return {+ bytes: outBytes,+ ...(report ? { report } : {}),+ summary,+ snapped,+ skipped,+ gltfValidation,+ };+ } catch (error) {+ if (error instanceof GltfValidationError) throw error;return undefined;}}@@ -1126,6 +1450,8 @@ export interface SceneComposeResult {materials: number;/** Per-part skip notes + transform warnings (never throws on one bad part). */warnings: string[];+ /** Official Khronos report for the exact composed bytes. */+ gltfValidation: KhronosGltfValidationReport;}/** Euler degrees (XYZ) → a glTF quaternion [x, y, z, w] via THREE (the viewer's frame). */@@ -1232,12 +1558,20 @@ export async function composeSceneGLB(const metrics = collectGlbMetrics(master);const bytes = await io.writeBinary(master);+ const gltfValidation = await assertFinalGlbValid(bytes, 'scene.glb');+ for (const issue of gltfValidation.issues.messages) {+ if (issue.severity !== 1) continue;+ warnings.push(+ `glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ''}: ${issue.message}`,+ );+ }return {bytes,tris: metrics.triangles,draws: metrics.drawCalls,materials: metrics.uniqueMaterials,warnings,+ gltfValidation,};}diff --git a/src/textures.ts b/src/textures.tsindex b246b719..2f9350c3 100644--- a/src/textures.ts+++ b/src/textures.ts@@ -12,11 +12,38 @@ import * as THREE from 'three';export type TextureSource = string | Buffer | Uint8Array;+export const TEXTURE_USAGES = [+ 'albedo',+ 'emissive',+ 'normal',+ 'roughness',+ 'metalness',+ 'metallicRoughness',+ 'occlusion',+] as const;++export type TextureUsage = (typeof TEXTURE_USAGES)[number];++export interface TextureLoadOptions {+ /** glTF material slot this image will occupy. Defaults to albedo for compatibility. */+ usage?: TextureUsage;+ /** Optional stable texture name used by QA/provenance. */+ name?: string;+}+export interface EncodedTextureData {mime: 'image/png' | 'image/jpeg' | 'image/webp';bytes: Uint8Array;}+export interface KilnTextureMetadata {+ usage: TextureUsage;+ colorSpace: 'srgb' | 'linear';+ width: number;+ height: number;+ hasAlpha: boolean;+}+/*** Load an image into a Three.js Texture. Accepts a file path, a Buffer,* or a Uint8Array of encoded bytes.@@ -30,7 +57,10 @@ export interface EncodedTextureData {* const wood = await loadTexture('./textures/oak-albedo.png');* const barrel = new THREE.Mesh(unwrapped, pbrMaterial({ albedo: wood }));*/-export async function loadTexture(source: TextureSource): Promise<THREE.DataTexture> {+export async function loadTexture(+ source: TextureSource,+ opts: TextureLoadOptions = {},+): Promise<THREE.DataTexture> {let bytes: Uint8Array;if (typeof source === 'string') {const fs = await import('node:fs');@@ -66,7 +96,17 @@ export async function loadTexture(source: TextureSource): Promise<THREE.DataTextTHREE.RGBAFormat,THREE.UnsignedByteType,);- tex.colorSpace = THREE.SRGBColorSpace;+ const usage = opts.usage ?? 'albedo';+ const colorSpace = usage === 'albedo' || usage === 'emissive' ? 'srgb' : 'linear';+ let hasAlpha = false;+ for (let offset = 3; offset < data.length; offset += 4) {+ if ((data[offset] ?? 255) < 255) {+ hasAlpha = true;+ break;+ }+ }+ tex.colorSpace = colorSpace === 'srgb' ? THREE.SRGBColorSpace : THREE.NoColorSpace;+ if (opts.name) tex.name = opts.name;tex.needsUpdate = true;tex.wrapS = THREE.RepeatWrapping;tex.wrapT = THREE.RepeatWrapping;@@ -78,6 +118,15 @@ export async function loadTexture(source: TextureSource): Promise<THREE.DataTextmime,bytes,} satisfies EncodedTextureData;+ (tex.userData as Record<string, unknown>)['kilnTexture'] = {+ usage,+ colorSpace,+ width: meta.width,+ height: meta.height,+ // `sharp.metadata().hasAlpha` only means that an alpha channel exists. QA+ // needs the stronger signal: at least one pixel is actually translucent.+ hasAlpha,+ } satisfies KilnTextureMetadata;return tex;}@@ -117,10 +166,12 @@ export interface PbrMaterialOptions {albedo?: number | string | THREE.Texture;/** Normal map Texture. */normal?: THREE.Texture;- /** Roughness: scalar [0,1] or Texture (R channel). */+ /** Roughness scalar [0,1], or the same packed texture supplied for metalness. */roughness?: number | THREE.Texture;- /** Metalness: scalar [0,1] or Texture (R channel). */+ /** Metalness scalar [0,1], or the same packed texture supplied for roughness. */metalness?: number | THREE.Texture;+ /** Explicit glTF metallic-roughness texture: G=roughness, B=metalness. */+ metallicRoughness?: THREE.Texture;/** Emissive: hex color or Texture. */emissive?: number | string | THREE.Texture;/** Emissive intensity multiplier. */@@ -129,6 +180,29 @@ export interface PbrMaterialOptions {aoMap?: THREE.Texture;/** AO intensity [0,1]. Default 1. */aoMapIntensity?: number;+ /** Portable glTF alpha mode. Defaults to opaque. */+ alphaMode?: 'opaque' | 'mask' | 'blend';+ /** Alpha cutoff for mask mode. Defaults to 0.5; invalid outside [0,1]. */+ alphaCutoff?: number;+ /** Render both sides of the surface. Defaults false. */+ doubleSided?: boolean;+}++function textureMetadata(texture: THREE.Texture): KilnTextureMetadata | undefined {+ return (texture.userData as Record<string, unknown>)['kilnTexture'] as+ | KilnTextureMetadata+ | undefined;+}++function requireTextureUsage(texture: THREE.Texture, usage: TextureUsage): void {+ const meta = textureMetadata(texture);+ if (meta && meta.usage !== usage) {+ throw new TypeError(+ `Texture ${JSON.stringify(texture.name || '(unnamed)')} was loaded for ${meta.usage}, not ${usage}.`,+ );+ }+ texture.colorSpace =+ usage === 'albedo' || usage === 'emissive' ? THREE.SRGBColorSpace : THREE.NoColorSpace;}/**@@ -148,31 +222,58 @@ export function pbrMaterial(opts: PbrMaterialOptions = {}): THREE.MeshStandardMa!!(v as { isTexture?: boolean } | null)?.isTexture;if (isTex(opts.albedo)) {+ requireTextureUsage(opts.albedo, 'albedo');mat.map = opts.albedo;mat.color = new THREE.Color(0xffffff);} else if (opts.albedo !== undefined) {mat.color = new THREE.Color(opts.albedo as number | string);}- if (opts.normal) mat.normalMap = opts.normal;+ if (opts.normal) {+ requireTextureUsage(opts.normal, 'normal');+ mat.normalMap = opts.normal;+ }- if (isTex(opts.roughness)) {- mat.roughnessMap = opts.roughness;- mat.roughness = 1;- } else if (opts.roughness !== undefined) {+ const roughnessTexture = isTex(opts.roughness) ? opts.roughness : undefined;+ const metalnessTexture = isTex(opts.metalness) ? opts.metalness : undefined;+ if (opts.metallicRoughness && (roughnessTexture || metalnessTexture)) {+ throw new TypeError(+ 'Use metallicRoughness for the packed G/B map; do not also pass texture-valued roughness/metalness.',+ );+ }+ if (roughnessTexture && metalnessTexture && roughnessTexture !== metalnessTexture) {+ throw new TypeError(+ 'Separate roughness and metalness textures are ambiguous in glTF. Pack G=roughness/B=metalness and pass metallicRoughness.',+ );+ }+ if ((roughnessTexture && !metalnessTexture) || (!roughnessTexture && metalnessTexture)) {+ throw new TypeError(+ 'A texture-valued roughness or metalness must be the same packed G/B texture in both slots, or use metallicRoughness.',+ );+ }+ const packedMr = opts.metallicRoughness ?? roughnessTexture;+ if (packedMr) {+ requireTextureUsage(packedMr, 'metallicRoughness');+ mat.roughnessMap = packedMr;+ mat.metalnessMap = packedMr;+ }++ if (typeof opts.roughness === 'number') {mat.roughness = opts.roughness as number;+ } else if (packedMr) {+ mat.roughness = 1;} else {mat.roughness = 0.8;}- if (isTex(opts.metalness)) {- mat.metalnessMap = opts.metalness;- mat.metalness = 1;- } else if (opts.metalness !== undefined) {+ if (typeof opts.metalness === 'number') {mat.metalness = opts.metalness as number;+ } else if (packedMr) {+ mat.metalness = 1;}if (isTex(opts.emissive)) {+ requireTextureUsage(opts.emissive, 'emissive');mat.emissiveMap = opts.emissive;mat.emissive = new THREE.Color(0xffffff);} else if (opts.emissive !== undefined) {@@ -182,8 +283,62 @@ export function pbrMaterial(opts: PbrMaterialOptions = {}): THREE.MeshStandardMamat.emissiveIntensity = opts.emissiveIntensity;}- if (opts.aoMap) mat.aoMap = opts.aoMap;+ if (opts.aoMap) {+ requireTextureUsage(opts.aoMap, 'occlusion');+ mat.aoMap = opts.aoMap;+ }if (opts.aoMapIntensity !== undefined) mat.aoMapIntensity = opts.aoMapIntensity;+ const alphaMode = opts.alphaMode ?? 'opaque';+ if (alphaMode !== 'opaque' && alphaMode !== 'mask' && alphaMode !== 'blend') {+ throw new TypeError('alphaMode must be one of "opaque", "mask", or "blend".');+ }+ if (opts.doubleSided !== undefined && typeof opts.doubleSided !== 'boolean') {+ throw new TypeError('doubleSided must be a boolean when provided.');+ }+ if (opts.alphaCutoff !== undefined && alphaMode !== 'mask') {+ throw new TypeError('alphaCutoff is valid only when alphaMode is "mask".');+ }+ if (+ opts.alphaCutoff !== undefined &&+ (!Number.isFinite(opts.alphaCutoff) || opts.alphaCutoff < 0 || opts.alphaCutoff > 1)+ ) {+ throw new RangeError('alphaCutoff must be a finite number in [0,1].');+ }+ if (alphaMode === 'mask') {+ mat.alphaTest = opts.alphaCutoff ?? 0.5;+ mat.transparent = false;+ } else if (alphaMode === 'blend') {+ mat.alphaTest = 0;+ mat.transparent = true;+ }+ if (opts.doubleSided) mat.side = THREE.DoubleSide;+ (mat.userData as Record<string, unknown>)['kilnMaterial'] = {+ alphaMode,+ ...(alphaMode === 'mask' ? { alphaCutoff: mat.alphaTest } : {}),+ doubleSided: opts.doubleSided === true,+ };+return mat;}++export interface FoliageMaterialOptions {+ alphaCutoff?: number;+ roughness?: number;+ doubleSided?: boolean;+}++/** Portable foliage material: glTF MASK + cutoff + double-sided by default. */+export function foliageMaterial(+ albedo: number | string | THREE.Texture,+ opts: FoliageMaterialOptions = {},+): THREE.MeshStandardMaterial {+ return pbrMaterial({+ albedo,+ roughness: opts.roughness ?? 0.9,+ metalness: 0,+ alphaMode: 'mask',+ alphaCutoff: opts.alphaCutoff ?? 0.5,+ doubleSided: opts.doubleSided ?? true,+ });+}diff --git a/src/tools/__tests__/registry-context.test.ts b/src/tools/__tests__/registry-context.test.tsnew file mode 100644index 00000000..94b1649f--- /dev/null+++ b/src/tools/__tests__/registry-context.test.ts@@ -0,0 +1,109 @@+import { describe, expect, test } from 'bun:test';++import { createAssetIntentV1 } from '../../contracts';+import {+ createKilnRenderViewsDef,+ createKilnScreenshotAnimationDef,+ createKilnToolRegistry,+ createKilnViewInteriorDef,+ kilnToolRegistry,+} from '../registry';++const SIDEWAYS_FALSE_PROP_CODE = `+const meta = { name: 'sideways', category: 'prop' };+function build() {+ const root = createRoot('Root');+ const frame = createVehicleFrame('VehicleFrame', {+ axles: [+ { id: 'front', position: [0.3, 0.35, 0] },+ { id: 'rear', position: [-0.3, 0.35, 0] },+ ],+ parent: root,+ });+ createPart('Body', boxGeo(1, 0.7, 4), gameMaterial('#aa3333'), {+ parent: frame.root,+ position: [0, 0.5, 0],+ });+ const rubber = gameMaterial('#111111', { roughness: 0.95 });+ const metal = gameMaterial('#888888', { metalness: 0.8 });+ const geometries = createWheelGeometrySet(0.35, 0.18);+ for (const [index, x] of [['front', 0.3], ['rear', -0.3]]) {+ for (const [side, z] of [['left', -1.6], ['right', 1.6]]) {+ createWheelAssembly(index + side, { tire: rubber, rim: metal }, {+ radius: 0.35, width: 0.18, side, index,+ position: [x, 0.35, z], steering: index === 'front', geometries, parent: frame.root,+ });+ }+ }+ return root;+}+`;++const FALSE_PROP_BUDGET_CODE = `+const meta = { name: 'budget', category: 'prop' };+function build() {+ const root = createRoot('Root');+ for (let i = 0; i < 30; i++) {+ createPart('Part_' + i, sphereGeo(1, 32, 24), gameMaterial('#777777'), { parent: root });+ }+ return root;+}+`;++const find = (registry: ReturnType<typeof createKilnToolRegistry>, name: string) => {+ const def = registry.find((candidate) => candidate.name === name);+ if (!def) throw new Error(`Missing tool ${name}`);+ return def;+};++const warningStrings = (output: unknown): string[] =>+ ((output as { warnings?: string[] }).warnings ?? []).map(String);++describe('trusted tool context', () => {+ test('validation uses requested vehicle and ignores false model meta.category', async () => {+ const vehicleValidate = find(createKilnToolRegistry({ category: 'vehicle' }), 'kiln_validate');+ const propValidate = find(createKilnToolRegistry({ category: 'prop' }), 'kiln_validate');+ const neutralValidate = find(createKilnToolRegistry(), 'kiln_validate');++ const vehicle = await vehicleValidate.run({ code: FALSE_PROP_BUDGET_CODE });+ const prop = await propValidate.run({ code: FALSE_PROP_BUDGET_CODE });+ const neutral = await neutralValidate.run({ code: FALSE_PROP_BUDGET_CODE });++ expect(warningStrings(vehicle).some((warning) => warning.includes('TRI_BUDGET'))).toBe(false);+ expect(warningStrings(prop).some((warning) => warning.includes('Estimated'))).toBe(true);+ expect(warningStrings(neutral).some((warning) => warning.includes('Estimated'))).toBe(false);+ });++ test('intent is authoritative and render/screenshot paths receive vehicle context', async () => {+ const intent = createAssetIntentV1({ category: 'vehicle' });+ const registry = createKilnToolRegistry({ intent, category: 'prop' });++ for (const name of ['kiln_render', 'kiln_screenshot']) {+ const output = await find(registry, name).run({ code: SIDEWAYS_FALSE_PROP_CODE });+ expect(warningStrings(output).some((warning) => warning.includes('Orientation'))).toBe(true);+ }+ });++ test('collapsed render and dedicated view definitions share the closure context', async () => {+ const context = { intent: createAssetIntentV1({ category: 'vehicle' }) };+ const outputs = await Promise.all([+ createKilnRenderViewsDef(context).run({ code: SIDEWAYS_FALSE_PROP_CODE }),+ createKilnScreenshotAnimationDef(context).run({+ code: SIDEWAYS_FALSE_PROP_CODE,+ clip: 'missing',+ }),+ createKilnViewInteriorDef(context).run({ code: SIDEWAYS_FALSE_PROP_CODE }),+ ]);++ for (const output of outputs) {+ expect(warningStrings(output).some((warning) => warning.includes('Orientation'))).toBe(true);+ }+ });++ test('legacy registry export is neutral and never trusts source metadata', async () => {+ const output = await find(kilnToolRegistry, 'kiln_render').run({+ code: SIDEWAYS_FALSE_PROP_CODE.replace("category: 'prop'", "category: 'vehicle'"),+ });+ expect(warningStrings(output).some((warning) => warning.includes('Orientation'))).toBe(false);+ });+});diff --git a/src/tools/registry.ts b/src/tools/registry.tsindex 12a3ea16..78264a26 100644--- a/src/tools/registry.ts+++ b/src/tools/registry.ts@@ -23,6 +23,8 @@ import * as THREE from 'three';import { validate } from '../validation';import { executeKilnCode, inspectSceneStructure, renderSceneToGLB } from '../render';import { listPrimitives, type PrimitiveSpec } from '../list-primitives';+import type { AssetCategory, AssetIntentV1 } from '../contracts';+import type { AssetQaReportV1 } from '../qa';// =============================================================================// Tool definition contract@@ -54,6 +56,21 @@ export interface KilnToolDef {mediaMulti?(output: unknown): { pngs: Uint8Array[]; json: unknown } | undefined;}+/**+ * Host-owned context captured by tool closures. This object is never part of a+ * model-facing input schema, so generated source cannot select its own category+ * or QA profile. An intent, when present, is authoritative over the convenience+ * category field.+ */+export interface KilnToolContext {+ intent?: AssetIntentV1;+ category?: AssetCategory;+}++function trustedCategory(context: KilnToolContext): AssetCategory | undefined {+ return context.intent?.category ?? context.category;+}+// =============================================================================// Schemas// =============================================================================@@ -136,20 +153,15 @@ function runListPrimitives(input: z.infer<typeof listPrimitivesInput>): {// kiln_validate// =============================================================================-/** Cheaply extract the declared category from the code's `meta` block so the- * tri advisory has a reference point. The model writes `category` into meta, so- * this reaches every door (CLI/MCP/studio) without threading external context. */-function extractCategory(code: string): string | undefined {- const m = /category\s*:\s*['"]([^'"]+)['"]/.exec(code);- return m?.[1];-}--function runValidate(input: z.infer<typeof validateInput>): {+function runValidate(+ input: z.infer<typeof validateInput>,+ context: KilnToolContext,+): {valid: boolean;errors: string[];warnings: string[];} {- const category = extractCategory(input.code);+ const category = trustedCategory(context);const result = validate(input.code, category ? { category } : {});return {valid: result.valid,@@ -174,6 +186,8 @@ export interface KilnRenderMetrics {lowestPart?: { name: string; y: number };/** Post-dedup instanceability grade (informational): how cheap to render at scale. */instanceability?: { grade: string; summary: string };+ /** Structured deterministic report; five dimensions remain separate. */+ qaReport?: AssetQaReportV1;warnings: string[];error?: string;}@@ -237,18 +251,25 @@ function collectSceneMetrics(root: THREE.Object3D): SceneMetrics {* Execute Kiln code, render it to an in-memory GLB, and report metrics.* Never writes files; never throws — failures come back as { ok:false, error }.*/-async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRenderMetrics> {+async function runRender(+ input: z.infer<typeof renderInput>,+ context: KilnToolContext,+): Promise<KilnRenderMetrics> {try {- const { meta, root, clips } = await executeKilnCode(input.code);+ const { root, clips } = await executeKilnCode(input.code);+ const category = trustedCategory(context);// Structural advisories (floating parts / stray planes at origin).- const structuralWarnings = inspectSceneStructure(root);+ const structuralWarnings = inspectSceneStructure(root, { category });const metrics = collectSceneMetrics(root);// Render to GLB bytes for the triangle count. Output is discarded — pure// metrics, no files written.- const category = typeof meta.category === 'string' ? meta.category : undefined;- const rendered = await renderSceneToGLB(root, { clips, category });+ const rendered = await renderSceneToGLB(root, {+ clips,+ ...(category ? { category } : {}),+ ...(context.intent ? { intent: context.intent } : {}),+ });const warnings = [...structuralWarnings, ...rendered.warnings];@@ -268,6 +289,7 @@ async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRender}: {}),warnings,+ qaReport: rendered.qaReport,};} catch (err) {return {@@ -302,11 +324,12 @@ export interface KilnScreenshotResult {*/async function runScreenshot(input: z.infer<typeof screenshotInput>,+ context: KilnToolContext,): Promise<KilnScreenshotResult> {try {const { renderViewGrid } = await import('../views');const { root } = await executeKilnCode(input.code);- const warnings = inspectSceneStructure(root);+ const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });const grid = await renderViewGrid(root);return {ok: true,@@ -347,6 +370,8 @@ export interface KilnRenderViewsResult {lowestPart?: { name: string; y: number };/** Post-dedup instanceability grade (informational): how cheap to render at scale. */instanceability?: { grade: string; summary: string };+ /** Structured deterministic report; five dimensions remain separate. */+ qaReport?: AssetQaReportV1;/** View names in grid order (row-major): Front, Right, Back, Left, Top, 3/4. */views?: string[];gridWidth?: number;@@ -367,17 +392,24 @@ export interface KilnRenderViewsResult {* The views module is imported lazily (node:zlib) to keep it out of the browser* bundle graph.*/-async function runRenderViews(input: z.infer<typeof renderInput>): Promise<KilnRenderViewsResult> {+async function runRenderViews(+ input: z.infer<typeof renderInput>,+ context: KilnToolContext,+): Promise<KilnRenderViewsResult> {try {const { renderViewGrid } = await import('../views');- const { meta, root, clips } = await executeKilnCode(input.code);+ const { root, clips } = await executeKilnCode(input.code);+ const category = trustedCategory(context);- const structuralWarnings = inspectSceneStructure(root);+ const structuralWarnings = inspectSceneStructure(root, { category });const metrics = collectSceneMetrics(root);// Single execution, two consumers — both read-only on `root`.- const category = typeof meta.category === 'string' ? meta.category : undefined;- const rendered = await renderSceneToGLB(root, { clips, category });+ const rendered = await renderSceneToGLB(root, {+ clips,+ ...(category ? { category } : {}),+ ...(context.intent ? { intent: context.intent } : {}),+ });const grid = await renderViewGrid(root);const warnings = [...structuralWarnings, ...rendered.warnings];@@ -402,6 +434,7 @@ async function runRenderViews(input: z.infer<typeof renderInput>): Promise<KilnRgridHeight: grid.height,pngBase64: grid.png.toString('base64'),warnings,+ qaReport: rendered.qaReport,};} catch (err) {return {@@ -418,18 +451,26 @@ async function runRenderViews(input: z.infer<typeof renderInput>): Promise<KilnR* stays the four-tool bench baseline). Shares `screenshotMedia` so transports* with image support attach the PNG bytes and strip the base64 from the JSON.*/-export const kilnRenderViewsDef: KilnToolDef = {- name: 'kiln_render',- description:- 'Execute the current model and SEE it: returns geometry metrics (triangle count, mesh + material counts, world-space bounding box, lowestPart — the mesh touching the lowest point, which must be intentional below Y=0 like earthworks or keels, never wheels/tails/equipment, and an instanceability grade A–F — informational, how cheap to render at scale) TOGETHER with a six-view image grid. ' +- 'Row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); ' +- 'row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). ' +- 'Use it to confirm the model builds and to verify orientation (+X forward), attachment (no floating parts), proportion, and silhouette. ' +- 'If the build fails you get an error and NO image — fix the code and render again. Flat-shaded CPU render; writes no files.',- inputSchema: renderInput,- run: async (input) => runRenderViews(renderInput.parse(input)),- media: screenshotMedia,-};+const KILN_RENDER_VIEWS_DESCRIPTION =+ 'Execute the current model and SEE it: returns geometry metrics (triangle count, mesh + material counts, world-space bounding box, lowestPart — the mesh touching the lowest point, which must be intentional below Y=0 like earthworks or keels, never wheels/tails/equipment, and an instanceability grade A–F — informational, how cheap to render at scale) TOGETHER with a six-view image grid. ' ++ 'Row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); ' ++ 'row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). ' ++ 'Use it to confirm the model builds and to verify orientation (+X forward), attachment (no floating parts), proportion, and silhouette. ' ++ 'If the build fails you get an error and NO image — fix the code and render again. Flat-shaded CPU render; writes no files.';++/** Create the unified render/view definition with host-owned QA context. */+export function createKilnRenderViewsDef(context: KilnToolContext = {}): KilnToolDef {+ return {+ name: 'kiln_render',+ description: KILN_RENDER_VIEWS_DESCRIPTION,+ inputSchema: renderInput,+ run: async (input) => runRenderViews(renderInput.parse(input), context),+ media: screenshotMedia,+ };+}++/** Neutral compatibility export. It never reads category from generated source. */+export const kilnRenderViewsDef: KilnToolDef = createKilnRenderViewsDef();// =============================================================================// kiln_screenshot_animation — SEE one clip's motion (6 phase-labeled frames)@@ -468,11 +509,12 @@ export interface KilnScreenshotAnimationResult {*/async function runScreenshotAnimation(input: z.infer<typeof screenshotAnimationInput>,+ context: KilnToolContext,): Promise<KilnScreenshotAnimationResult> {try {const { renderClipAnimation } = await import('../views');const { root, clips } = await executeKilnCode(input.code);- const warnings = inspectSceneStructure(root);+ const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });const r = await renderClipAnimation(root, clips, {clip: input.clip,...(input.camera ? { camera: input.camera } : {}),@@ -539,27 +581,35 @@ export function screenshotAnimationMediaMulti(* Carries both `media` (grid) and `mediaMulti` (perFrame) so image transports show* the right thing in either mode.*/-export const kilnScreenshotAnimationDef: KilnToolDef = {- name: 'kiln_screenshot_animation',- description:- 'SEE one animation clip move: renders the named clip as six frames sampled evenly from start to end ' +- '(each labeled with its phase %) from one camera, as a 3x2 grid. Use this after animating ANY asset to ' +- 'verify the MOTION — a static screenshot cannot show it — whether it is a character walking, a door or ' +- 'chest lid swinging on its hinge, a wheel/gear/turret/windmill turning on its axle, a lever or hatch ' +- 'throwing, or a flag/frond/branch swaying. Read the side (right) view and confirm each moving part ' +- 'travels the way it should about its OWN real pivot, and that the static base stays put. For a ' +- 'character specifically: a walk swings the legs forward and back (not splayed sideways and not sliding ' +- 'the body sideways), knees bend backward at the joint (not forward like a bird), an attack swings down ' +- 'and FORWARD through the front (not behind the back), and a held weapon tracks the hand through the ' +- '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.',- inputSchema: screenshotAnimationInput,- run: async (input) => runScreenshotAnimation(screenshotAnimationInput.parse(input)),- media: screenshotAnimationMedia,- mediaMulti: screenshotAnimationMediaMulti,-};+const KILN_SCREENSHOT_ANIMATION_DESCRIPTION =+ 'SEE one animation clip move: renders the named clip as six frames sampled evenly from start to end ' ++ '(each labeled with its phase %) from one camera, as a 3x2 grid. Use this after animating ANY asset to ' ++ 'verify the MOTION — a static screenshot cannot show it — whether it is a character walking, a door or ' ++ 'chest lid swinging on its hinge, a wheel/gear/turret/windmill turning on its axle, a lever or hatch ' ++ 'throwing, or a flag/frond/branch swaying. Read the side (right) view and confirm each moving part ' ++ 'travels the way it should about its OWN real pivot, and that the static base stays put. For a ' ++ 'character specifically: a walk swings the legs forward and back (not splayed sideways and not sliding ' ++ 'the body sideways), knees bend backward at the joint (not forward like a bird), an attack swings down ' ++ 'and FORWARD through the front (not behind the back), and a held weapon tracks the hand through the ' ++ '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.';++/** Create an animation-view definition with host-owned QA context. */+export function createKilnScreenshotAnimationDef(context: KilnToolContext = {}): KilnToolDef {+ return {+ name: 'kiln_screenshot_animation',+ description: KILN_SCREENSHOT_ANIMATION_DESCRIPTION,+ inputSchema: screenshotAnimationInput,+ run: async (input) => runScreenshotAnimation(screenshotAnimationInput.parse(input), context),+ media: screenshotAnimationMedia,+ mediaMulti: screenshotAnimationMediaMulti,+ };+}++/** Neutral compatibility export. It never reads category from generated source. */+export const kilnScreenshotAnimationDef: KilnToolDef = createKilnScreenshotAnimationDef();// =============================================================================// kiln_view_interior (unified) — see INSIDE an enterable building, roof off@@ -588,18 +638,19 @@ export interface KilnViewInteriorResult {* Eye-level. A build error comes back image-free ({ ok:false, error }). When the roof* could not be lifted (roofsHidden === 0) the interior stays occluded — a warning tells* the agent to name the roof part "Roof". Pure visual QA: does NOT run the structural- * inspector (the agent already gets floating/stray warnings from kiln_render). The views- * module is imported lazily to keep node:zlib out of the browser bundle graph.+ * inspector uses the same host-owned category as every other view path. The views module+ * is imported lazily to keep node:zlib out of the browser bundle graph.*/async function runViewInterior(input: z.infer<typeof viewInteriorInput>,+ context: KilnToolContext,): Promise<KilnViewInteriorResult> {try {const { renderInteriorGrid } = await import('../views');const { root } = await executeKilnCode(input.code);const nodeName = input.nodeName ?? 'Roof';const grid = await renderInteriorGrid(root, { nodeName });- const warnings: string[] = [];+ const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });if (grid.roofsHidden === 0) {warnings.push(`No node named "${nodeName}" was found, so the roof could not be lifted and the interior is still occluded. Name the roof group exactly "${nodeName}".`,@@ -629,58 +680,76 @@ async function runViewInterior(* part of `kilnToolRegistry` (the four-tool bench baseline stays unchanged). Shares* `screenshotMedia` so image transports attach the PNG bytes and strip the base64.*/-export const kilnViewInteriorDef: KilnToolDef = {- name: 'kiln_view_interior',- description:- 'SEE INSIDE an enterable building: renders it with the roof (the part named "Roof") lifted off, as a ' +- 'three-view grid. (1) Floor plan: top-down — check the interior is open and walkable and the footprint ' +- 'is right. (2) Dollhouse: a 3/4 cutaway — check built-in fixtures (hearth, counter, shelves) rest ON the ' +- 'floor, not floating or sunk, and the walls enclose a real volume with headroom. (3) Eye-level: a low ' +- 'angle looking in through the doorway with the near walls also removed — confirm the doorway is a REAL ' +- 'gap you could walk through (not a panel) and no wall or glass is buried inside a solid mass. ' +- 'Call this before finalizing any building. If roofsHidden comes back 0 the roof part was not named ' +- '"Roof" (the interior stays hidden — rename it). Flat-shaded CPU render; writes no files.',- inputSchema: viewInteriorInput,- run: async (input) => runViewInterior(viewInteriorInput.parse(input)),- media: screenshotMedia,-};+const KILN_VIEW_INTERIOR_DESCRIPTION =+ 'SEE INSIDE an enterable building: renders it with the roof (the part named "Roof") lifted off, as a ' ++ 'three-view grid. (1) Floor plan: top-down — check the interior is open and walkable and the footprint ' ++ 'is right. (2) Dollhouse: a 3/4 cutaway — check built-in fixtures (hearth, counter, shelves) rest ON the ' ++ 'floor, not floating or sunk, and the walls enclose a real volume with headroom. (3) Eye-level: a low ' ++ 'angle looking in through the doorway with the near walls also removed — confirm the doorway is a REAL ' ++ 'gap you could walk through (not a panel) and no wall or glass is buried inside a solid mass. ' ++ 'Call this before finalizing any building. If roofsHidden comes back 0 the roof part was not named ' ++ '"Roof" (the interior stays hidden — rename it). Flat-shaded CPU render; writes no files.';++/** Create the interior-view definition with host-owned QA context. */+export function createKilnViewInteriorDef(context: KilnToolContext = {}): KilnToolDef {+ return {+ name: 'kiln_view_interior',+ description: KILN_VIEW_INTERIOR_DESCRIPTION,+ inputSchema: viewInteriorInput,+ run: async (input) => runViewInterior(viewInteriorInput.parse(input), context),+ media: screenshotMedia,+ };+}++/** Neutral compatibility export. It never reads category from generated source. */+export const kilnViewInteriorDef: KilnToolDef = createKilnViewInteriorDef();// =============================================================================// Registry// =============================================================================-export const kilnToolRegistry: KilnToolDef[] = [- {- name: 'kiln_list_primitives',- description:- 'List the Kiln sandbox primitives available to generated 3D code: geometry helpers (boxGeo, cylinderXGeo, capsuleGeo, ...), materials (gameMaterial, glassMaterial, ...), structure (createRoot, createPart, createPivot), animation, CSG, arrays, UV, and textures. Call this before writing Kiln code to discover exact signatures and idiomatic usage. Optionally filter by category.',- inputSchema: listPrimitivesInput,- run: async (input) => runListPrimitives(listPrimitivesInput.parse(input)),- },- {- name: 'kiln_validate',- description:- 'Statically validate Kiln source code before rendering. Checks for the required `meta` const and `build()` function, `value:` keyframe typos, infinite loops, recursive build() calls, and syntax errors. Returns { valid, errors, warnings }. Warnings are advisory only (they never make code invalid), including a soft, generous triangle-count nudge. Run this to catch mistakes cheaply before kiln_render.',- inputSchema: validateInput,- run: async (input) => runValidate(validateInput.parse(input)),- },- {- name: 'kiln_render',- description:- 'Execute Kiln code and render it to an in-memory GLB, returning geometry metrics: triangle count, mesh count, material count, the world-space bounding box, lowestPart (the mesh touching the lowest point — anything below Y=0 must be intentionally below-grade like earthworks or keels, never wheels/tails/equipment), and an instanceability grade (A–F, informational: how cheap the asset is to render at scale — driven by distinct-material count; fewer shared materials grade higher). Includes structural warnings for floating parts and stray planes left at the origin. Use this to confirm a model builds and to inspect its size and structure. Does not write any files.',- inputSchema: renderInput,- run: async (input) => runRender(renderInput.parse(input)),- },- {- name: 'kiln_screenshot',- description:- 'Render Kiln code to a six-view image grid so you can SEE the asset: ' +- 'row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); ' +- 'row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). ' +- 'Use it to verify orientation (+X forward), attachment (no floating parts), and silhouette before submitting. ' +- 'If a view looks wrong, fix the code and screenshot again. Flat-shaded CPU render; does not write files.',- inputSchema: screenshotInput,- run: async (input) => runScreenshot(screenshotInput.parse(input)),- media: screenshotMedia,- },-];+/**+ * Create the four-tool baseline registry with trusted host context captured in+ * every validate/render/view closure. Tool schemas remain byte-for-byte neutral:+ * the model cannot provide or override this context.+ */+export function createKilnToolRegistry(context: KilnToolContext = {}): KilnToolDef[] {+ return [+ {+ name: 'kiln_list_primitives',+ description:+ 'List the Kiln sandbox primitives available to generated 3D code: geometry helpers (boxGeo, cylinderXGeo, capsuleGeo, ...), materials (gameMaterial, glassMaterial, ...), structure (createRoot, createPart, createPivot), animation, CSG, arrays, UV, and textures. Call this before writing Kiln code to discover exact signatures and idiomatic usage. Optionally filter by category.',+ inputSchema: listPrimitivesInput,+ run: async (input) => runListPrimitives(listPrimitivesInput.parse(input)),+ },+ {+ name: 'kiln_validate',+ description:+ 'Statically validate Kiln source code before rendering. Checks for the required `meta` const and `build()` function, `value:` keyframe typos, infinite loops, recursive build() calls, and syntax errors. Returns { valid, errors, warnings }. Warnings are advisory only (they never make code invalid), including a soft, generous triangle-count nudge. Run this to catch mistakes cheaply before kiln_render.',+ inputSchema: validateInput,+ run: async (input) => runValidate(validateInput.parse(input), context),+ },+ {+ name: 'kiln_render',+ description:+ 'Execute Kiln code and render it to an in-memory GLB, returning geometry metrics: triangle count, mesh count, material count, the world-space bounding box, lowestPart (the mesh touching the lowest point — anything below Y=0 must be intentionally below-grade like earthworks or keels, never wheels/tails/equipment), and an instanceability grade (A–F, informational: how cheap to render at scale — driven by distinct-material count; fewer shared materials grade higher). Includes structural warnings for floating parts and stray planes left at the origin. Use this to confirm a model builds and to inspect its size and structure. Does not write any files.',+ inputSchema: renderInput,+ run: async (input) => runRender(renderInput.parse(input), context),+ },+ {+ name: 'kiln_screenshot',+ description:+ 'Render Kiln code to a six-view image grid so you can SEE the asset: ' ++ 'row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); ' ++ 'row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). ' ++ 'Use it to verify orientation (+X forward), attachment (no floating parts), and silhouette before submitting. ' ++ 'If a view looks wrong, fix the code and screenshot again. Flat-shaded CPU render; does not write files.',+ inputSchema: screenshotInput,+ run: async (input) => runScreenshot(screenshotInput.parse(input), context),+ media: screenshotMedia,+ },+ ];+}++/** Neutral compatibility registry. It never reads category from generated source. */+export const kilnToolRegistry: KilnToolDef[] = createKilnToolRegistry();diff --git a/src/validation.ts b/src/validation.tsindex 9a75a614..70760248 100644--- a/src/validation.ts+++ b/src/validation.ts@@ -165,6 +165,7 @@ const CATEGORY_TRI_BUDGETS: Record<string, number> = {prop: 25000,vfx: 15000,environment: 120000,+ vegetation: 40000,vehicle: 40000,weapon: 20000,building: 60000,diff --git a/src/vegetation-prompt.test.ts b/src/vegetation-prompt.test.tsnew file mode 100644index 00000000..1acd61e5--- /dev/null+++ b/src/vegetation-prompt.test.ts@@ -0,0 +1,52 @@+import { describe, expect, test } from 'bun:test';++import { createAssetIntentV1, VEGETATION_SUBTYPES } from './contracts';+import {+ VEGETATION_REJECTED_HELPER_NAMES,+ VEGETATION_SUBTYPE_RECIPES_V1,+ vegetationSubtypePromptContext,+} from './vegetation-prompt';++describe('VEG-017 model-independent subtype prompt skills', () => {+ test('selects exactly one relevant subtype recipe and no rejected helper', () => {+ for (const subtype of VEGETATION_SUBTYPES) {+ const context = vegetationSubtypePromptContext(+ createAssetIntentV1({ category: 'vegetation', vegetation: { subtype } }),+ );+ const selected = VEGETATION_SUBTYPE_RECIPES_V1[subtype];+ expect(context).toContain(selected.marker);+ expect(context).toContain(`only the ${subtype} recipe`);+ for (const otherSubtype of VEGETATION_SUBTYPES) {+ if (otherSubtype === subtype) continue;+ expect(context).not.toContain(VEGETATION_SUBTYPE_RECIPES_V1[otherSubtype].marker);+ }+ for (const helper of VEGETATION_REJECTED_HELPER_NAMES) expect(context).not.toContain(helper);+ }+ });++ test('changes only state/material guidance, preserving the selected recipe', () => {+ const sparse = vegetationSubtypePromptContext(+ createAssetIntentV1({+ category: 'vegetation',+ vegetation: { subtype: 'shrub', growthState: 'sparse' },+ material: { mode: 'flatOptimized' },+ }),+ );+ expect(sparse).toContain('RECIPE_SHRUB_V1');+ expect(sparse).toContain('requested sparse state');+ expect(sparse).toContain('one coherent foliage value role');++ const bare = vegetationSubtypePromptContext(+ createAssetIntentV1({+ category: 'vegetation',+ vegetation: { subtype: 'bare/dead', growthState: 'bare' },+ }),+ );+ expect(bare).toContain('RECIPE_BARE_DEAD_V1');+ expect(bare).toContain('Bare growth is intentional');+ });++ test('returns no category leakage for non-vegetation intent', () => {+ expect(vegetationSubtypePromptContext(createAssetIntentV1({ category: 'prop' }))).toBe('');+ });+});diff --git a/src/vegetation-prompt.ts b/src/vegetation-prompt.tsnew file mode 100644index 00000000..8fba3038--- /dev/null+++ b/src/vegetation-prompt.ts@@ -0,0 +1,109 @@+import type { AssetIntentV1, VegetationSubtype } from './contracts';++export const VEGETATION_REJECTED_HELPER_NAMES = Object.freeze([+ 'taperedBranchGeo',+ 'createBranchAttachment',+ 'createCanopyScaffold',+ 'createLeafDistribution',+ 'createFrondScaffold',+ 'proceduralBarkMap',+ 'proceduralLeafMap',+] as const);++interface VegetationSubtypeRecipeV1 {+ marker: string;+ guidance: string;+}++/**+ * Provider-independent recipes constrained to the currently executable primitive/material surface.+ * The map is never appended wholesale: {@link vegetationSubtypePromptContext} selects one entry.+ */+export const VEGETATION_SUBTYPE_RECIPES_V1: Readonly<+ Record<VegetationSubtype, VegetationSubtypeRecipeV1>+> = Object.freeze({+ tree: {+ marker: 'RECIPE_TREE_V1',+ guidance:+ 'Use cylinderGeo/cylinderOnAxis or beamBetween for a tapered-looking trunk/branch composition, sphereGeo or foliageCardGeo for several attached foliage masses, and stamp vegetation.trunk, vegetation.branch.*, vegetation.foliage, and vegetation.canopy.cluster.* roles.',+ },+ conifer: {+ marker: 'RECIPE_CONIFER_V1',+ guidance:+ 'Build a narrow central cylinderGeo trunk with successively shorter branch tiers. Compose a tapered silhouette from overlapping coneGeo, sphereGeo, or foliageCardGeo masses; vary tier rotation and radius without perfect lockstep.',+ },+ shrub: {+ marker: 'RECIPE_SHRUB_V1',+ guidance:+ 'Use several short cylinderOnAxis or beamBetween stems rooted at one grounded base, then attach irregular overlapping sphereGeo/card clusters. Keep the center filled while preserving an uneven outer contour unless formal topiary is explicit.',+ },+ grass: {+ marker: 'RECIPE_GRASS_V1',+ guidance:+ 'Build individual blades from narrow planeGeo or foliageCardGeo parts pivoted at Y=0. Fan heights and lean angles deterministically, keep the tuft contact compact, and avoid adding an unrequested terrain disk or grass skirt.',+ },+ 'frond/palm': {+ marker: 'RECIPE_FROND_PALM_V1',+ guidance:+ 'Use a cylinderGeo trunk or stem and compose each frond from curveToMesh, narrow planeGeo, or multiple foliageCardGeo leaflets. Embed every frond base into the crown and introduce an explicit outward arc and terminal droop using current primitives.',+ },+ vine: {+ marker: 'RECIPE_VINE_V1',+ guidance:+ 'Trace the vine with curveToMesh or short cylinderOnAxis segments and attach sparse foliageCardGeo/sphereGeo leaves along the path. Preserve the requested support relationship; do not invent a wall, trellis, pot, or terrain prop.',+ },+ 'crop/flower': {+ marker: 'RECIPE_CROP_FLOWER_V1',+ guidance:+ 'Use one or more slender cylinderGeo stems, attached planeGeo/foliageCardGeo leaves, and a distinct sphereGeo/coneGeo petal, seed, or flower-head assembly. Keep the requested plant count and grounded contacts explicit.',+ },+ succulent: {+ marker: 'RECIPE_SUCCULENT_V1',+ guidance:+ 'Compose thick leaves or pads from scaled sphereGeo, capsuleGeo, or rounded boxGeo parts around a grounded center. Vary vertical reach and azimuth modestly while keeping each pad visibly joined to the base.',+ },+ fungus: {+ marker: 'RECIPE_FUNGUS_V1',+ guidance:+ 'Build the stipe from cylinderGeo/capsuleGeo and the cap from sphereGeo, dome-like sphere segments, or coneGeo. Seat the stipe at Y=0 and keep gills, spots, or secondary caps subordinate to the requested fungus.',+ },+ aquatic: {+ marker: 'RECIPE_AQUATIC_V1',+ guidance:+ 'Use curveToMesh/cylinderOnAxis stems plus planeGeo, foliageCardGeo, or flattened sphereGeo leaves. Treat the asset-local origin as the declared anchor; do not author a water plane, pond rim, rocks, or soil unless requested.',+ },+ 'bare/dead': {+ marker: 'RECIPE_BARE_DEAD_V1',+ guidance:+ 'Use cylinderGeo/cylinderOnAxis, beamBetween, or curveToMesh for a visibly tapered trunk and irregular branch graph. Omit foliage intentionally, preserve branch attachment, and avoid symmetric radial tiers.',+ },+ custom: {+ marker: 'RECIPE_CUSTOM_VEGETATION_V1',+ guidance:+ 'Use only current reported primitives and portable material recipes. Declare support, foliage, contact, and any custom semantic roles explicitly so generic growth, attachment, repetition, scope, and material measurements remain available.',+ },+});++export function vegetationSubtypePromptContext(intent: AssetIntentV1): string {+ if (intent.category !== 'vegetation' || !intent.vegetation) return '';+ const vegetation = intent.vegetation;+ const recipe = VEGETATION_SUBTYPE_RECIPES_V1[vegetation.subtype];+ const state =+ vegetation.growthState === 'bare'+ ? 'Bare growth is intentional; do not add foliage to satisfy a generic canopy pattern.'+ : vegetation.growthState === 'sparse'+ ? 'Keep the requested sparse state while retaining attached, readable clusters.'+ : 'Build the requested lush state from overlapping, attached masses with restrained variation.';+ const material =+ intent.material.mode === 'flatOptimized'+ ? 'Use one coherent foliage value role for intentional consolidation.'+ : 'Use two to six restrained foliage value roles and keep material coherence separate from structural checks.';+ return [+ `## Vegetation subtype recipe (${recipe.marker})`,+ `Apply only the ${vegetation.subtype} recipe; do not append recipes for other growth forms.`,+ recipe.guidance,+ state,+ material,+ 'Use current executable APIs only. No branch, canopy, leaf-distribution, frond, procedural-map, or LOD helper has been promoted.',+ ].join('\n');+}diff --git a/src/vehicle.ts b/src/vehicle.tsnew file mode 100644index 00000000..86e4e422--- /dev/null+++ b/src/vehicle.ts@@ -0,0 +1,647 @@+/** Frame-owning vehicle and wheel scaffolds for Kiln's +X-forward asset frame. */+import * as THREE from 'three';++import {+ readSemanticMetadataV1,+ stampSemanticMetadataV1,+ type SemanticMetadataV1Input,+ type SemanticSocketV1,+ type VehicleIntentV1,+} from './contracts';++export const VEHICLE_AXES = Object.freeze({+ forward: Object.freeze([1, 0, 0] as const),+ up: Object.freeze([0, 1, 0] as const),+ right: Object.freeze([0, 0, 1] as const),+ wheelAxle: Object.freeze([0, 0, 1] as const),+} as const);++export type VehicleSocketKind = 'chassis' | 'axle' | 'seat' | 'contact' | 'steering' | 'propulsion';++export interface VehicleSocketInput {+ id: string;+ position: [number, number, number];+ rotation?: [number, number, number, number];+ compatibleTypes?: readonly string[];+}++export interface VehicleFrameOptions {+ chassis?: VehicleSocketInput;+ axles?: readonly VehicleSocketInput[];+ seats?: readonly VehicleSocketInput[];+ contacts?: readonly VehicleSocketInput[];+ steering?: readonly VehicleSocketInput[];+ propulsion?: readonly VehicleSocketInput[];+ parent?: THREE.Object3D;+}++export interface VehicleFrameResult {+ root: THREE.Object3D;+ chassis: THREE.Object3D;+ axles: THREE.Object3D[];+ seats: THREE.Object3D[];+ contacts: THREE.Object3D[];+ steering: THREE.Object3D[];+ propulsion: THREE.Object3D[];+}++export type WheelSide = 'left' | 'right';++export interface WheelGeometrySet {+ tire: THREE.BufferGeometry;+ rim: THREE.BufferGeometry;+ hub: THREE.BufferGeometry;+}++export interface WheelMaterialSet {+ tire: THREE.Material;+ rim: THREE.Material;+ hub?: THREE.Material;+}++export interface WheelAssemblyOptions {+ radius: number;+ width: number;+ side: WheelSide;+ /** Axle index or stable axle label shared by its left/right pair. */+ index: number | string;+ position?: [number, number, number];+ rimRadius?: number;+ hubRadius?: number;+ rimWidth?: number;+ hubWidth?: number;+ steering?: boolean;+ loadBearing?: boolean;+ geometries?: Partial<WheelGeometrySet>;+ parent?: THREE.Object3D;+}++export interface WheelAssemblyResult {+ root: THREE.Object3D;+ steeringPivot?: THREE.Object3D;+ spinPivot: THREE.Object3D;+ tire: THREE.Mesh;+ rim: THREE.Mesh;+ hub: THREE.Mesh;+ contact: THREE.Object3D;+ radius: number;+ width: number;+ side: WheelSide;+ index: string;+ spinAxis: readonly [0, 0, 1];+}++export interface ResolvedWheelAssembly {+ id: string;+ source: 'semantic' | 'legacy';+ side?: WheelSide;+ index?: string;+ root: THREE.Object3D;+ pivot: THREE.Object3D;+ steeringPivot?: THREE.Object3D;+ tire?: THREE.Object3D;+ rim?: THREE.Object3D;+ hub?: THREE.Object3D;+ contact?: THREE.Object3D;+ centerWorld: THREE.Vector3;+ pivotCenterWorld: THREE.Vector3;+ tireCenterWorld?: THREE.Vector3;+ rimCenterWorld?: THREE.Vector3;+ hubCenterWorld?: THREE.Vector3;+ spinAxisWorld: THREE.Vector3;+ radius?: number;+ width?: number;+ rimRadius?: number;+ rimWidth?: number;+ hubRadius?: number;+ hubWidth?: number;+ loadBearing: boolean;+}++const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;++function assertId(value: string, name: string): string {+ if (!ID_PATTERN.test(value)) throw new TypeError(`${name} must be a stable identifier`);+ return value;+}++function positive(value: number, name: string): number {+ if (!Number.isFinite(value) || value <= 0) throw new RangeError(`${name} must be finite and > 0`);+ return value;+}++function normalizedQuaternion(+ value: readonly [number, number, number, number] | undefined,+): [number, number, number, number] {+ const source = value ?? [0, 0, 0, 1];+ const length = Math.hypot(source[0], source[1], source[2], source[3]);+ if (!Number.isFinite(length) || length <= 1e-9)+ throw new TypeError('socket rotation must be a finite quaternion');+ return [source[0] / length, source[1] / length, source[2] / length, source[3] / length];+}++function semantic(+ roles: readonly string[],+ options: Omit<SemanticMetadataV1Input, 'roles'> = {},+): SemanticMetadataV1Input {+ return {+ roles,+ relationships: options.relationships ?? [],+ frames: options.frames ?? [],+ sockets: options.sockets ?? [],+ };+}++function socketRole(kind: VehicleSocketKind, id: string): string {+ if (kind === 'chassis') return 'chassis.main';+ if (kind === 'axle') return `axle.${id}`;+ return `${kind}.${id}`;+}++function createTypedSocket(+ kind: VehicleSocketKind,+ input: VehicleSocketInput,+ parent: THREE.Object3D,+): THREE.Object3D {+ const id = assertId(input.id, `${kind} socket id`);+ if (!input.position.every(Number.isFinite))+ throw new TypeError(`${kind}.${id} position must be finite`);+ const rotation = normalizedQuaternion(input.rotation);+ const node = new THREE.Object3D();+ node.name = `Socket_${kind}_${id}`;+ node.position.set(...input.position);+ node.quaternion.set(...rotation);+ const socket: SemanticSocketV1 = {+ id,+ type: `vehicle.${kind}`,+ frame: 'socket',+ compatibleTypes: [...(input.compatibleTypes ?? [`vehicle.${kind}`])],+ };+ stampSemanticMetadataV1(+ node,+ semantic([`socket.${kind}.${id}`, socketRole(kind, id)], {+ frames: [{ id: 'socket', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ sockets: [socket],+ relationships: [{ kind: 'owned-by', target: 'vehicle.frame', targetType: 'role' }],+ }),+ );+ parent.add(node);+ return node;+}++/** Create a typed vehicle socket frame whose local basis is always +X/+Y/+Z. */+export function createVehicleFrame(+ name: string,+ options: VehicleFrameOptions = {},+): VehicleFrameResult {+ const root = new THREE.Object3D();+ root.name = name;+ stampSemanticMetadataV1(+ root,+ semantic(['vehicle.frame', 'vehicle.front.+x'], {+ frames: [+ { id: 'origin', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: 'forward.+x', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: 'up.+y', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: 'right.+z', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ ],+ }),+ );+ if (options.parent) options.parent.add(root);++ const chassis = createTypedSocket(+ 'chassis',+ options.chassis ?? { id: 'main', position: [0, 0, 0] },+ root,+ );+ const build = (+ kind: Exclude<VehicleSocketKind, 'chassis'>,+ values: readonly VehicleSocketInput[] | undefined,+ ) => (values ?? []).map((value) => createTypedSocket(kind, value, root));+ return {+ root,+ chassis,+ axles: build('axle', options.axles),+ seats: build('seat', options.seats),+ contacts: build('contact', options.contacts),+ steering: build('steering', options.steering),+ propulsion: build('propulsion', options.propulsion),+ };+}++function cylinderZ(radius: number, width: number, segments = 16): THREE.CylinderGeometry {+ const geometry = new THREE.CylinderGeometry(radius, radius, width, segments);+ geometry.rotateX(Math.PI / 2);+ return geometry;+}++/** Shared geometry can be passed to every wheel to preserve GLB instancing. */+export function createWheelGeometrySet(radius: number, width: number): WheelGeometrySet {+ positive(radius, 'radius');+ positive(width, 'width');+ if (width >= radius * 2) throw new RangeError('wheel width must be less than its diameter');+ const tube = width / 2;+ return {+ tire: new THREE.TorusGeometry(radius - tube, tube, 8, 20),+ rim: cylinderZ(radius * 0.68, width * 0.8),+ hub: cylinderZ(radius * 0.34, width * 0.94),+ };+}++/** One axle-centered wheel hierarchy, optionally nested below a +Y steering pivot. */+export function createWheelAssembly(+ name: string,+ materials: WheelMaterialSet,+ options: WheelAssemblyOptions,+): WheelAssemblyResult {+ const radius = positive(options.radius, 'radius');+ const width = positive(options.width, 'width');+ const rimRadius = positive(options.rimRadius ?? radius * 0.68, 'rimRadius');+ const hubRadius = positive(options.hubRadius ?? radius * 0.34, 'hubRadius');+ const rimWidth = positive(options.rimWidth ?? width * 0.8, 'rimWidth');+ const hubWidth = positive(options.hubWidth ?? width * 0.94, 'hubWidth');+ if (rimRadius >= radius || hubRadius >= rimRadius)+ throw new RangeError('wheel radii must satisfy hub < rim < tire');+ if (rimWidth > width || hubWidth > width)+ throw new RangeError('rim/hub width must not exceed tire width');+ const index = assertId(String(options.index), 'wheel index');+ const key = `${options.side}.${index}`;+ const parent = options.parent;+ const root = new THREE.Object3D();+ root.name = `${name}_Assembly_${options.side}_${index}`;++ let steeringPivot: THREE.Object3D | undefined;+ if (options.steering) {+ steeringPivot = new THREE.Object3D();+ steeringPivot.name = `SteeringPivot_${options.side}_${index}`;+ steeringPivot.position.set(...(options.position ?? [0, 0, 0]));+ stampSemanticMetadataV1(+ steeringPivot,+ semantic([`steering.pivot.${key}`], {+ frames: [{ id: 'steering-axis.+y', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ relationships: [{ kind: 'steers', target: `wheel.assembly.${key}`, targetType: 'role' }],+ }),+ );+ root.add(steeringPivot);+ }++ const spinPivot = new THREE.Object3D();+ spinPivot.name = `WheelPivot_${options.side}_${index}`;+ if (!steeringPivot) spinPivot.position.set(...(options.position ?? [0, 0, 0]));+ stampSemanticMetadataV1(+ spinPivot,+ semantic(+ [+ `wheel.assembly.${key}`,+ `wheel.pivot.${key}`,+ ...(options.loadBearing === false ? [] : [`wheel.load-bearing.${key}`]),+ ],+ {+ frames: [+ { id: 'axle-center', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: 'spin-axis.+z', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ ],+ relationships: [+ { kind: 'mounted-on', target: `axle.${index}`, targetType: 'role' },+ { kind: 'contains', target: `wheel.tire.${key}`, targetType: 'role' },+ { kind: 'contains', target: `wheel.rim.${key}`, targetType: 'role' },+ { kind: 'contains', target: `wheel.hub.${key}`, targetType: 'role' },+ ],+ },+ ),+ );+ (steeringPivot ?? root).add(spinPivot);++ const defaults = createWheelGeometrySet(radius, width);+ const tire = new THREE.Mesh(options.geometries?.tire ?? defaults.tire, materials.tire);+ const rim = new THREE.Mesh(+ options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth),+ materials.rim,+ );+ const hub = new THREE.Mesh(+ options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth),+ materials.hub ?? materials.rim,+ );+ tire.name = `Tire_${options.side}_${index}`;+ rim.name = `Rim_${options.side}_${index}`;+ hub.name = `Hub_${options.side}_${index}`;+ stampSemanticMetadataV1(+ tire,+ semantic([`wheel.tire.${key}`], {+ relationships: [{ kind: 'descends-from', target: `wheel.pivot.${key}`, targetType: 'role' }],+ }),+ );+ stampSemanticMetadataV1(+ rim,+ semantic([`wheel.rim.${key}`], {+ relationships: [{ kind: 'contained-by', target: `wheel.tire.${key}`, targetType: 'role' }],+ }),+ );+ stampSemanticMetadataV1(+ hub,+ semantic([`wheel.hub.${key}`], {+ relationships: [{ kind: 'contained-by', target: `wheel.rim.${key}`, targetType: 'role' }],+ }),+ );+ spinPivot.add(tire, rim, hub);++ const contact = new THREE.Object3D();+ contact.name = `Contact_${options.side}_${index}`;+ contact.position.y = -radius;+ stampSemanticMetadataV1(+ contact,+ semantic([`wheel.contact.${key}`, `contact.${key}`], {+ frames: [{ id: 'contact', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ relationships: [{ kind: 'supports', target: 'vehicle.frame', targetType: 'role' }],+ }),+ );+ spinPivot.add(contact);+ if (parent) parent.add(root);+ return {+ root,+ ...(steeringPivot ? { steeringPivot } : {}),+ spinPivot,+ tire,+ rim,+ hub,+ contact,+ radius,+ width,+ side: options.side,+ index,+ spinAxis: VEHICLE_AXES.wheelAxle,+ };+}++function roles(node: THREE.Object3D): readonly string[] {+ return readSemanticMetadataV1(node)?.roles ?? [];+}++function descendantWithRole(root: THREE.Object3D, prefix: string): THREE.Object3D | undefined {+ let found: THREE.Object3D | undefined;+ root.traverse((node) => {+ if (!found && roles(node).some((role) => role.startsWith(prefix))) found = node;+ });+ return found;+}++function ancestorWithRole(node: THREE.Object3D, prefix: string): THREE.Object3D | undefined {+ let current = node.parent;+ while (current) {+ if (roles(current).some((role) => role.startsWith(prefix))) return current;+ current = current.parent;+ }+ return undefined;+}++function parseWheelRole(role: string): { side?: WheelSide; index?: string } {+ const parts = role.split('.');+ const side = parts.at(-2);+ return {+ ...(side === 'left' || side === 'right' ? { side } : {}),+ ...(parts.at(-1) ? { index: parts.at(-1)! } : {}),+ };+}++function objectBoundsInFrame(+ object: THREE.Object3D,+ frame: THREE.Object3D,+): THREE.Box3 | undefined {+ object.updateWorldMatrix(true, true);+ frame.updateWorldMatrix(true, false);+ const worldToFrame = frame.matrixWorld.clone().invert();+ const bounds = new THREE.Box3();+ let found = false;+ object.traverse((node) => {+ if (!(node instanceof THREE.Mesh) || !(node.geometry instanceof THREE.BufferGeometry)) return;+ node.geometry.computeBoundingBox();+ const local = node.geometry.boundingBox;+ if (!local) return;+ const matrix = worldToFrame.clone().multiply(node.matrixWorld);+ for (const x of [local.min.x, local.max.x])+ for (const y of [local.min.y, local.max.y])+ for (const z of [local.min.z, local.max.z]) {+ bounds.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(matrix));+ found = true;+ }+ });+ return found ? bounds : undefined;+}++function dimensions(+ object: THREE.Object3D | undefined,+ frame: THREE.Object3D,+): { center: THREE.Vector3; radius: number; width: number } | undefined {+ if (!object) return undefined;+ const bounds = objectBoundsInFrame(object, frame);+ if (!bounds) return undefined;+ const size = bounds.getSize(new THREE.Vector3());+ return {+ center: bounds.getCenter(new THREE.Vector3()),+ radius: Math.max(size.x, size.y) / 2,+ width: size.z,+ };+}++function resolved(+ source: 'semantic' | 'legacy',+ id: string,+ root: THREE.Object3D,+ pivot: THREE.Object3D,+ parts: {+ side?: WheelSide;+ index?: string;+ tire?: THREE.Object3D;+ rim?: THREE.Object3D;+ hub?: THREE.Object3D;+ contact?: THREE.Object3D;+ steeringPivot?: THREE.Object3D;+ },+): ResolvedWheelAssembly {+ pivot.updateWorldMatrix(true, false);+ const tire = dimensions(parts.tire, pivot);+ const rim = dimensions(parts.rim, pivot);+ const hub = dimensions(parts.hub, pivot);+ const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE.Vector3();+ const toWorld = (value: THREE.Vector3): THREE.Vector3 =>+ value.clone().applyMatrix4(pivot.matrixWorld);+ return {+ id,+ source,+ ...(parts.side ? { side: parts.side } : {}),+ ...(parts.index ? { index: parts.index } : {}),+ root,+ pivot,+ ...(parts.steeringPivot ? { steeringPivot: parts.steeringPivot } : {}),+ ...(parts.tire ? { tire: parts.tire } : {}),+ ...(parts.rim ? { rim: parts.rim } : {}),+ ...(parts.hub ? { hub: parts.hub } : {}),+ ...(parts.contact ? { contact: parts.contact } : {}),+ centerWorld: toWorld(centerLocal),+ pivotCenterWorld: new THREE.Vector3().setFromMatrixPosition(pivot.matrixWorld),+ ...(tire ? { tireCenterWorld: toWorld(tire.center) } : {}),+ ...(rim ? { rimCenterWorld: toWorld(rim.center) } : {}),+ ...(hub ? { hubCenterWorld: toWorld(hub.center) } : {}),+ spinAxisWorld: new THREE.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),+ ...(tire ? { radius: tire.radius, width: tire.width } : {}),+ ...(rim ? { rimRadius: rim.radius, rimWidth: rim.width } : {}),+ ...(hub ? { hubRadius: hub.radius, hubWidth: hub.width } : {}),+ loadBearing: roles(pivot).some((role) => role.startsWith('wheel.load-bearing.')),+ };+}++function semanticAssemblies(root: THREE.Object3D): ResolvedWheelAssembly[] {+ const result: ResolvedWheelAssembly[] = [];+ root.traverse((node) => {+ const assemblyRole = roles(node).find((role) => role.startsWith('wheel.assembly.'));+ if (!assemblyRole) return;+ const parsed = parseWheelRole(assemblyRole);+ result.push(+ resolved('semantic', assemblyRole, node, node, {+ ...parsed,+ tire: descendantWithRole(node, 'wheel.tire.'),+ rim: descendantWithRole(node, 'wheel.rim.'),+ hub: descendantWithRole(node, 'wheel.hub.'),+ contact: descendantWithRole(node, 'wheel.contact.'),+ steeringPivot: ancestorWithRole(node, 'steering.pivot.'),+ }),+ );+ });+ return result;+}++function legacyCorner(name: string): { key: string; side?: WheelSide; index?: string } | undefined {+ const value = name.toLowerCase().replace(/[^a-z0-9]+/g, '-');+ if (!/(wheel|tire|rim|hub)/.test(value)) return undefined;+ const side: WheelSide | undefined = /(?:left|(^|-)l($|-)|fl|rl)/.test(value)+ ? 'left'+ : /(?:right|(^|-)r($|-)|fr|rr)/.test(value)+ ? 'right'+ : undefined;+ const index = /(?:front|(^|-)f($|-)|fl|fr)/.test(value)+ ? 'front'+ : /(?:rear|back|(^|-)r[lr]($|-)|rl|rr)/.test(value)+ ? 'rear'+ : value.match(/\d+/)?.[0];+ return {+ key: `${side ?? 'unknown'}.${index ?? value}`,+ ...(side ? { side } : {}),+ ...(index ? { index } : {}),+ };+}++function legacyAssemblies(root: THREE.Object3D): ResolvedWheelAssembly[] {+ const groups = new Map<+ string,+ {+ side?: WheelSide;+ index?: string;+ pivot?: THREE.Object3D;+ tire?: THREE.Object3D;+ rim?: THREE.Object3D;+ hub?: THREE.Object3D;+ }+ >();+ root.traverse((node) => {+ const corner = legacyCorner(node.name);+ if (!corner) return;+ const entry = groups.get(corner.key) ?? {+ ...(corner.side ? { side: corner.side } : {}),+ ...(corner.index ? { index: corner.index } : {}),+ };+ const lower = node.name.toLowerCase();+ if (lower.includes('pivot')) entry.pivot = node;+ else if (lower.includes('rim')) entry.rim = node;+ else if (lower.includes('hub')) entry.hub = node;+ else entry.tire = node;+ groups.set(corner.key, entry);+ });+ return [...groups.entries()].map(([key, parts]) => {+ const pivot =+ parts.pivot ?? parts.tire?.parent ?? parts.rim?.parent ?? parts.hub?.parent ?? root;+ return resolved('legacy', key, pivot, pivot, parts);+ });+}++/** Semantic grouping wins completely; canonical names are legacy-only fallback. */+export function resolveVehicleWheelAssemblies(root: THREE.Object3D): ResolvedWheelAssembly[] {+ const semantic = semanticAssemblies(root);+ return semantic.length > 0 ? semantic : legacyAssemblies(root);+}++export function hasCanonicalVehicleFront(root: THREE.Object3D): boolean {+ let found = false;+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ if (+ metadata?.roles.includes('vehicle.frame') &&+ metadata.roles.includes('vehicle.front.+x') &&+ metadata.frames.some((frame) => frame.id === 'forward.+x')+ ) {+ found = true;+ }+ });+ return found;+}++/** Resolved subtype guidance; one recipe is injected and unrelated noun helpers stay absent. */+export function vehicleSubtypeRecipe(intent: VehicleIntentV1): string {+ const contract =+ `Resolved vehicle subtype: ${intent.subtype.toUpperCase()}. Canonical front is +X, up is +Y, ` ++ `and wheel/rail axles run across +Z. Support policy: ${intent.supportPolicy}; supports: ` ++ `${intent.supportAssemblies.join(', ') || 'none'}; propulsion: ` ++ `${intent.propulsionAssemblies.join(', ') || 'none'}.`;+ if (intent.subtype === 'wheeled') {+ return (+ `${contract} Build exactly ${intent.wheelCount} axle-centered semantic wheel assemblies across ` ++ `${intent.axleCount} axles with createVehicleFrame() and createWheelAssembly(). Keep each tire, ` ++ 'rim, and hub concentric and nested; mirror left/right centers, radii, and widths; never stack two assemblies at one corner; place every load-bearing tire on Y=0.'+ );+ }+ if (intent.subtype === 'tracked') {+ return (+ `${contract} Author complete closed track.loop.left/right geometry, keep every road wheel inside ` ++ 'its loop, tag support.track.* and track.road-wheel.* roles, and place both track support sets on one Y=0 contact plane. Do not invent ordinary car-wheel rules.'+ );+ }+ if (intent.subtype === 'rail') {+ return (+ `${contract} Keep rail-wheel/support assemblies paired on +Z axles, centered under the chassis, ` ++ 'and coplanar at Y=0. Preserve a longitudinal +X body and do not apply tire/fender assumptions.'+ );+ }+ if (intent.subtype === 'watercraft') {+ return (+ `${contract} Build a watertight longitudinal +X hull with an explicit waterline. Center each ` ++ 'propeller on its +X shaft and place the rudder behind it. Do not add wheels, axles, tires, hubs, or ground-contact rules.'+ );+ }+ if (intent.subtype === 'fixed-wing') {+ return (+ `${contract} Wingspan may exceed body length and must not be mistaken for sideways orientation. ` ++ 'Keep fuselage/cockpit front +X, center propeller or jet propulsion on declared shaft/pivots, and tag landing gear independently from airborne policy.'+ );+ }+ if (intent.subtype === 'rotorcraft') {+ return (+ `${contract} Wingspan-style bounds do not determine front. Center each rotor pivot at its mast, ` ++ 'declare the correct propulsion axis, keep blades coplanar, and author skids/landing gear as explicit support sets without inheriting car-wheel rules.'+ );+ }+ if (intent.subtype === 'hover') {+ return (+ `${contract} Keep hover pads/thrusters as explicit centered assemblies, preserve readable +X ` ++ 'travel, and do not add wheels or force airborne supports onto Y=0.'+ );+ }+ if (intent.subtype === 'walking') {+ return (+ `${contract} Declare each load-bearing leg/contact set and put grounded contacts on one stable ` ++ 'Y=0 plane; keep propulsion/joints distinct from wheeled-vehicle axle assumptions.'+ );+ }+ return (+ `${contract} Follow only the declared support and propulsion semantics, preserve +X front, and ` ++ 'avoid adding wheel, track, rotor, or waterline assumptions not present in trusted intent.'+ );+}diff --git a/src/views/__tests__/architecture.test.ts b/src/views/__tests__/architecture.test.tsnew file mode 100644index 00000000..c57be714--- /dev/null+++ b/src/views/__tests__/architecture.test.ts@@ -0,0 +1,120 @@+import { describe, expect, test } from 'bun:test';+import { WebIO, type Node as GltfNode } from '@gltf-transform/core';+import * as THREE from 'three';++import { readSemanticMetadataV1FromExtras, stampSemanticMetadataV1 } from '../../contracts';+import { renderSceneToGLB } from '../../render';+import { hideArchitectureRoofInScene, selectArchitectureRoofNodes } from '../architecture';++const semantic = (node: THREE.Object3D, role: string): THREE.Object3D =>+ stampSemanticMetadataV1(node, { roles: [role] });++describe('semantic architecture roof selection', () => {+ test('lifts every semantic roof subtree and no non-roof sibling', () => {+ const root = new THREE.Group();+ const roof = semantic(new THREE.Group(), 'roof.assembly');+ roof.name = 'CopperCap';+ const slope = semantic(new THREE.Mesh(new THREE.BoxGeometry(2, 0.1, 2)), 'roof.slope.positive');+ slope.name = 'SlopeWithoutLegacyName';+ roof.add(slope);+ const wall = semantic(new THREE.Mesh(new THREE.BoxGeometry(2, 2, 0.1)), 'wall.front');+ wall.name = 'RoofDecoration';+ root.add(roof, wall);++ const selection = hideArchitectureRoofInScene(root);+ expect(selection.mode).toBe('semantic');+ expect(selection.nodes).toEqual([roof]);+ expect(roof.visible).toBe(false);+ expect(slope.visible).toBe(false);+ expect(wall.visible).toBe(true);+ });++ test('uses narrow legacy names only when semantic roles are absent', () => {+ const root = new THREE.Group();+ const roof = new THREE.Group();+ roof.name = 'Roof';+ roof.add(new THREE.Mesh(new THREE.BoxGeometry(1, 0.1, 1)));+ const rooftopGarden = new THREE.Group();+ rooftopGarden.name = 'RooftopGarden';+ root.add(roof, rooftopGarden);++ const selection = selectArchitectureRoofNodes(root);+ expect(selection.mode).toBe('legacy-name');+ expect(selection.nodes).toEqual([roof]);+ });++ test('semantic roles suppress legacy fallback so unrelated named nodes remain', () => {+ const root = new THREE.Group();+ const semanticSlope = semantic(new THREE.Group(), 'roof.slope.negative');+ semanticSlope.name = 'CapB';+ const legacy = new THREE.Group();+ legacy.name = 'Roof_OldCopy';+ root.add(semanticSlope, legacy);++ const selection = selectArchitectureRoofNodes(root);+ expect(selection.mode).toBe('semantic');+ expect(selection.nodes).toEqual([semanticSlope]);+ });++ test('selects and lifts the semantic roof after final GLB export and reload', async () => {+ const source = new THREE.Group();+ source.name = 'ExportedShell';+ const roof = semantic(new THREE.Group(), 'roof.assembly');+ roof.name = 'CopperCap';+ const slope = semantic(+ new THREE.Mesh(new THREE.BoxGeometry(3, 0.1, 2), new THREE.MeshStandardMaterial()),+ 'roof.slope.positive',+ );+ slope.name = 'SlopePositive';+ roof.add(slope);+ const wall = semantic(+ new THREE.Mesh(new THREE.BoxGeometry(3, 2, 0.1), new THREE.MeshStandardMaterial()),+ 'wall.front',+ );+ wall.name = 'WallFront';+ const opening = semantic(new THREE.Object3D(), 'opening.front.door');+ opening.name = 'Opening_front_door';+ opening.position.set(1.5, 1, 0);+ opening.scale.set(0.15, 2, 1);+ source.add(roof, wall, opening);++ const rendered = await renderSceneToGLB(source, { optimize: 'full' });+ expect(rendered.optimize?.mode).toBe('palette');+ const document = await new WebIO().readBinary(rendered.bytes);+ const reloadedOpening = document+ .getRoot()+ .listNodes()+ .find((node) => node.getName() === 'Opening_front_door');+ expect(readSemanticMetadataV1FromExtras(reloadedOpening!.getExtras())?.roles).toEqual([+ 'opening.front.door',+ ]);+ expect(reloadedOpening?.getTranslation()).toEqual([1.5, 1, 0]);+ expect(reloadedOpening?.getScale()).toEqual([0.15, 2, 1]);+ const adapt = (node: GltfNode): Record<string, unknown> => ({+ name: node.getName(),+ visible: true,+ userData: node.getExtras(),+ children: node.listChildren().map(adapt),+ });+ const reloaded = {+ name: 'ReloadedScene',+ visible: true,+ userData: {},+ children: document.getRoot().listScenes()[0]!.listChildren().map(adapt),+ };+ const selection = hideArchitectureRoofInScene(reloaded);+ expect(selection.mode).toBe('semantic');+ expect(selection.nodes.map((node) => node.name)).toEqual(['CopperCap']);+ expect(selection.nodes[0]?.visible).toBe(false);+ const reloadedWall = (reloaded.children as Array<Record<string, unknown>>)+ .flatMap(function flatten(node): Array<Record<string, unknown>> {+ return [+ node,+ ...((node.children as Array<Record<string, unknown>> | undefined)?.flatMap(flatten) ??+ []),+ ];+ })+ .find((node) => node.name === 'WallFront');+ expect(reloadedWall?.visible).toBe(true);+ });+});diff --git a/src/views/__tests__/character.test.ts b/src/views/__tests__/character.test.tsnew file mode 100644index 00000000..ad863ffb--- /dev/null+++ b/src/views/__tests__/character.test.ts@@ -0,0 +1,246 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import { createJointChain } from '../../character';+import { createAssetIntentV1 } from '../../contracts';+import type { QaFinding } from '../../qa/types';+import {+ CHARACTER_MOTION_DIAGNOSTIC_PHASES,+ buildCharacterDiagnosticDescriptor,+ planCharacterDiagnosticRequests,+} from '../character';+import { captureCharacterDiagnosticViews } from '../character-capture';++describe('CHAR-029 skeleton/local-axis/contact diagnostic descriptor', () => {+ test('labels joints, colors chains, shows +X/axes/contacts, and aligns invalid edges to paths', () => {+ const root = new THREE.Object3D();+ root.name = 'Creature';+ root.position.set(4, 3, -2);+ root.rotation.set(0.1, 0.8, -0.2);+ root.scale.setScalar(1.7);+ const chain = createJointChain(+ 'Foreleg',+ [+ { role: 'shoulder.fore.left', offset: [0.2, 0.7, -0.2], side: 'left' },+ { role: 'elbow.fore.left', offset: [0, -0.4, 0], side: 'left' },+ {+ role: 'paw.fore.left',+ offset: [0, -0.3, 0],+ side: 'left',+ endEffector: true,+ contact: true,+ },+ ],+ { parent: root },+ );+ const initial = buildCharacterDiagnosticDescriptor(root);+ const elbow = initial.joints.find((joint) => joint.role === 'elbow.fore.left')!;+ const finding: QaFinding = {+ code: 'CHAR_PARENT_EDGE',+ disposition: 'block',+ dimension: 'categoryReadiness',+ profile: 'character.quadruped',+ message: 'broken edge',+ affected: { node: chain.nodes[1]!.name, nodePath: elbow.nodePath },+ };+ const descriptor = buildCharacterDiagnosticDescriptor(root, [finding]);++ expect(descriptor.canonicalForwardArrow).toEqual({+ start: [0, 0, 0],+ end: [1, 0, 0],+ label: '+X forward',+ });+ expect(descriptor.joints.map((joint) => joint.label)).toEqual([+ 'shoulder.fore.left',+ 'elbow.fore.left',+ 'paw.fore.left',+ ]);+ expect(descriptor.joints.every((joint) => joint.color === descriptor.joints[0]?.color)).toBe(+ true,+ );+ expect(descriptor.joints.every((joint) => joint.forwardAxisEnd !== joint.assetPosition)).toBe(+ true,+ );+ expect(descriptor.contacts).toEqual([+ {+ role: 'paw.fore.left',+ nodePath: descriptor.joints[2]!.nodePath,+ assetPosition: [0.2, 0, -0.2],+ },+ ]);+ expect(descriptor.invalidFindingNodePaths).toEqual([elbow.nodePath]);+ expect(descriptor.edges.find((edge) => edge.childRole === 'elbow.fore.left')?.valid).toBe(+ false,+ );+ expect(descriptor.edges.find((edge) => edge.childRole === 'paw.fore.left')?.valid).toBe(true);+ });++ test('descriptor is byte-repeatable and does not mutate transformed source nodes', () => {+ const root = new THREE.Object3D();+ root.name = 'TailCreature';+ const chain = createJointChain(+ 'Tail',+ [+ { role: 'tail.base', offset: [-0.2, 0.5, 0] },+ { role: 'tail.tip', offset: [-0.4, 0, 0], endEffector: true },+ ],+ { parent: root },+ );+ const before = chain.nodes.map((node) => ({+ position: node.position.toArray(),+ quaternion: node.quaternion.toArray(),+ scale: node.scale.toArray(),+ }));+ expect(JSON.stringify(buildCharacterDiagnosticDescriptor(root))).toBe(+ JSON.stringify(buildCharacterDiagnosticDescriptor(root)),+ );+ expect(+ chain.nodes.map((node) => ({+ position: node.position.toArray(),+ quaternion: node.quaternion.toArray(),+ scale: node.scale.toArray(),+ })),+ ).toEqual(before);+ });+});++describe('CHAR-030 automatic fixed-phase motion diagnostics', () => {+ test('captures labeled skeleton overlays and both cameras for resolved clips without mutating the rig', async () => {+ const root = new THREE.Object3D();+ root.name = 'AnimatedCreature';+ const chain = createJointChain(+ 'Leg',+ [+ { role: 'hip.left', offset: [0, 1, 0], side: 'left' },+ { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' },+ {+ role: 'ankle.left',+ offset: [0, -0.5, 0],+ side: 'left',+ endEffector: true,+ contact: true,+ },+ ],+ { parent: root },+ );+ for (const [index, joint] of chain.nodes.entries()) {+ joint.add(+ new THREE.Mesh(+ new THREE.SphereGeometry(0.09 - index * 0.01, 8, 6),+ new THREE.MeshStandardMaterial({ color: 0x7799bb }),+ ),+ );+ }+ const clips = [+ new THREE.AnimationClip('Run', 1, [+ new THREE.VectorKeyframeTrack(+ `${chain.nodes[0]!.name}.position`,+ [0, 0.5, 1],+ [0, 1, 0, 0.25, 1, 0, 0, 1, 0],+ ),+ ]),+ new THREE.AnimationClip('Bite', 1, [+ new THREE.QuaternionKeyframeTrack(+ `${chain.nodes[1]!.name}.quaternion`,+ [0, 1],+ [0, 0, 0, 1, 0, 0, 0.3826834, 0.9238795],+ ),+ ]),+ ];+ const character = createAssetIntentV1({+ category: 'character',+ character: {+ bodyPlan: 'custom',+ grounded: true,+ locomotion: 'run',+ clips: [+ { name: 'Run', playback: 'loop' },+ { name: 'Bite', playback: 'oneShot' },+ ],+ },+ }).character!;+ const before = chain.nodes.map((node) => ({+ position: node.position.toArray(),+ quaternion: node.quaternion.toArray(),+ }));+ const captures = await captureCharacterDiagnosticViews(root, clips, character, [], 64);++ expect(captures.map((capture) => capture.id)).toEqual([+ 'character.skeleton.front',+ 'character.skeleton.right',+ 'character.motion-strip.front.run',+ 'character.motion-strip.right.run',+ 'character.motion-strip.front.bite',+ 'character.motion-strip.right.bite',+ ]);+ expect(captures.every((capture) => capture.png.byteLength > 100)).toBe(true);+ expect(+ captures+ .filter((capture) => capture.kind === 'skeleton')+ .every((capture) =>+ capture.regions.some((region) => region.semanticRoles[0]?.startsWith('joint.')),+ ),+ ).toBe(true);+ expect(+ captures+ .filter((capture) => capture.kind === 'motion-strip')+ .every((capture) => capture.phaseFractions?.join(',') === '0,0.2,0.4,0.6,0.8,1'),+ ).toBe(true);+ expect(+ chain.nodes.map((node) => ({+ position: node.position.toArray(),+ quaternion: node.quaternion.toArray(),+ })),+ ).toEqual(before);+ });++ test('plans front/right strips for resolved locomotion and primary action', () => {+ const trusted = createAssetIntentV1({+ category: 'character',+ character: {+ bodyPlan: 'quadruped',+ grounded: true,+ locomotion: 'run',+ clips: [+ { name: 'Run', playback: 'loop' },+ { name: 'Bite', playback: 'oneShot' },+ { name: 'Idle', playback: 'loop' },+ ],+ },+ }).character!;+ const requests = planCharacterDiagnosticRequests(trusted);+ expect(requests.slice(0, 2).map((request) => request.id)).toEqual([+ 'character.skeleton.front',+ 'character.skeleton.right',+ ]);+ expect(requests.map((request) => request.id)).toEqual(+ expect.arrayContaining([+ 'character.motion-strip.front.run',+ 'character.motion-strip.right.run',+ 'character.motion-strip.front.bite',+ 'character.motion-strip.right.bite',+ ]),+ );+ expect(+ requests+ .filter((request) => request.variant === 'character-motion-strip')+ .every((request) => request.automatic),+ ).toBe(true);+ for (const request of requests.filter(+ (candidate) => candidate.variant === 'character-motion-strip',+ )) {+ expect(request.phaseFractions).toEqual(CHARACTER_MOTION_DIAGNOSTIC_PHASES);+ }+ });++ test('no animation still gets automatic skeleton views and no phantom strip', () => {+ const trusted = createAssetIntentV1({+ category: 'character',+ character: { bodyPlan: 'custom', grounded: false, locomotion: 'stationary', clips: [] },+ }).character!;+ expect(planCharacterDiagnosticRequests(trusted).map((request) => request.id)).toEqual([+ 'character.skeleton.front',+ 'character.skeleton.right',+ ]);+ });+});diff --git a/src/views/__tests__/diagnostic.test.ts b/src/views/__tests__/diagnostic.test.tsnew file mode 100644index 00000000..9e41e952--- /dev/null+++ b/src/views/__tests__/diagnostic.test.ts@@ -0,0 +1,356 @@+import { describe, expect, test } from 'bun:test';+import { BoxGeometry, Group, Mesh, MeshStandardMaterial, PlaneGeometry } from 'three';+import { createAssetIntentV1, stampSemanticMetadataV1, type AssetCategory } from '../../contracts';+import { SIX_VIEWS } from '../raster';+import {+ GENERIC_DIAGNOSTIC_BUFFER_IDS,+ GENERIC_DIAGNOSTIC_CAMERAS,+ GENERIC_DIAGNOSTIC_REQUESTS,+ planDiagnosticViews,+ renderDiagnosticView,+ renderDiagnosticViews,+ type DiagnosticViewRequest,+} from '../diagnostic';++function intent(+ category: AssetCategory,+ materialMode: 'flatOptimized' | 'pbrRecipe' | 'texturedHero' = 'flatOptimized',+) {+ return createAssetIntentV1({+ category,+ qaProfile: `${category}.test`,+ material: { mode: materialMode },+ });+}++function semanticPart(name: string, role: string, position: [number, number, number]): Group {+ const part = new Group();+ part.name = name;+ part.position.set(...position);+ stampSemanticMetadataV1(part, { roles: [role] });+ const mesh = new Mesh(+ new BoxGeometry(1, 1, 1),+ new MeshStandardMaterial({ color: role.startsWith('roof.') ? 0xb54a42 : 0x4f83cc }),+ );+ mesh.name = `${name}Mesh`;+ part.add(mesh);+ return part;+}++function fixtureScene(): Group {+ const root = new Group();+ root.name = 'Asset';+ root.position.set(0.25, 0.5, -0.15);+ root.rotation.y = 0.12;+ root.add(semanticPart('Chassis', 'chassis.main', [0, 0.5, 0]));+ root.add(semanticPart('WheelFrontLeft', 'wheel.front-left', [0.5, 0, 0.9]));+ root.add(semanticPart('Roof', 'roof.slope.left', [0, 1.5, 0]));+ root.updateMatrixWorld(true);+ return root;+}++function sourceFingerprint(root: Group): string {+ const nodes: unknown[] = [];+ root.traverse((node) => {+ const mesh = node as Mesh;+ const materials = mesh.isMesh+ ? (Array.isArray(mesh.material) ? mesh.material : [mesh.material]).map((material) => {+ const color = (material as { color?: { toArray(): number[] } }).color;+ return { visible: material.visible, color: color?.toArray() };+ })+ : undefined;+ nodes.push({+ name: node.name,+ visible: node.visible,+ position: node.position.toArray(),+ quaternion: node.quaternion.toArray(),+ scale: node.scale.toArray(),+ matrix: node.matrix.toArray(),+ matrixWorld: node.matrixWorld.toArray(),+ userData: node.userData,+ materials,+ });+ });+ return JSON.stringify(nodes);+}++describe('QA-018 deterministic generic diagnostic buffers', () => {+ test('uses the unchanged six named cameras and stable request IDs', () => {+ expect(GENERIC_DIAGNOSTIC_CAMERAS).toHaveLength(6);+ expect(GENERIC_DIAGNOSTIC_CAMERAS.map(({ name, dir }) => ({ name, dir }))).toEqual(SIX_VIEWS);+ expect(GENERIC_DIAGNOSTIC_REQUESTS).toHaveLength(30);+ expect(new Set(GENERIC_DIAGNOSTIC_REQUESTS.map((view) => view.id)).size).toBe(30);+ expect(GENERIC_DIAGNOSTIC_REQUESTS.slice(0, 5).map((view) => view.id)).toEqual(+ GENERIC_DIAGNOSTIC_BUFFER_IDS.map((buffer) => `generic.front.${buffer}`),+ );+ expect(Object.isFrozen(GENERIC_DIAGNOSTIC_CAMERAS)).toBe(true);+ expect(Object.isFrozen(GENERIC_DIAGNOSTIC_CAMERAS[0]!.dir)).toBe(true);+ });++ test('renders all five buffers byte-deterministically from one named camera', () => {+ const root = fixtureScene();+ const requests = GENERIC_DIAGNOSTIC_REQUESTS.filter((view) => view.cameraId === 'front');+ const first = renderDiagnosticViews(root, requests, { size: 64 });+ const second = renderDiagnosticViews(root, requests, { size: 64 });++ expect(first.map((frame) => frame.id)).toEqual(requests.map((view) => view.id));+ for (let index = 0; index < first.length; index++) {+ expect(first[index]!.camera).toBe(GENERIC_DIAGNOSTIC_CAMERAS[0]!);+ expect(first[index]!.rgb).toEqual(second[index]!.rgb);+ expect(first[index]!.png.equals(second[index]!.png)).toBe(true);+ expect(first[index]!.png.subarray(1, 4).toString()).toBe('PNG');+ }+ expect(new Set(first.map((frame) => Buffer.from(frame.rgb).toString('base64'))).size).toBe(5);+ });++ test('localizes semantic overlays to stable node paths and pixel bounds', () => {+ const root = fixtureScene();+ const overlayRequest = GENERIC_DIAGNOSTIC_REQUESTS.find(+ (view) => view.id === 'generic.right.semantic-overlay',+ )!;+ const frame = renderDiagnosticView(root, overlayRequest, { size: 80 });+ const chassis = frame.regions.find((region) => region.nodeName === 'ChassisMesh');+ const wheel = frame.regions.find((region) => region.nodeName === 'WheelFrontLeftMesh');++ expect(chassis?.nodePath).toBe('Asset[0]/Chassis[0]/ChassisMesh[0]');+ expect(wheel?.nodePath).toBe('Asset[0]/WheelFrontLeft[1]/WheelFrontLeftMesh[0]');+ // Roles stamped on semantic parent groups address their rendered descendants.+ expect(chassis?.semanticRoles).toEqual(['chassis.main']);+ expect(wheel?.semanticRoles).toEqual(['wheel.front-left']);+ for (const region of frame.regions) {+ const [minX, minY, maxX, maxY] = region.pixelBounds;+ expect(minX).toBeGreaterThanOrEqual(0);+ expect(minY).toBeGreaterThanOrEqual(0);+ expect(maxX).toBeLessThan(80);+ expect(maxY).toBeLessThan(80);+ expect(maxX).toBeGreaterThanOrEqual(minX);+ expect(maxY).toBeGreaterThanOrEqual(minY);+ expect(region.triangleCount).toBeGreaterThan(0);+ }+ });++ test('colors inherited semantic overlays by the most-specific rendered role', () => {+ const root = new Group();+ root.name = 'Vehicle';+ stampSemanticMetadataV1(root, { roles: ['vehicle.frame'] });++ const tire = semanticPart('Tire', 'wheel.tire.right.front', [0, 0, 0]);+ const hub = semanticPart('Hub', 'wheel.hub.right.front', [0, 0, 0.1]);+ root.add(tire, hub);++ const overlayRequest = GENERIC_DIAGNOSTIC_REQUESTS.find(+ (view) => view.id === 'generic.right.semantic-overlay',+ )!;+ const frame = renderDiagnosticView(root, overlayRequest, { size: 80 });+ const tireRegion = frame.regions.find((region) => region.nodeName === 'TireMesh');+ const hubRegion = frame.regions.find((region) => region.nodeName === 'HubMesh');++ expect(tireRegion?.semanticRoles).toEqual(['vehicle.frame', 'wheel.tire.right.front']);+ expect(hubRegion?.semanticRoles).toEqual(['vehicle.frame', 'wheel.hub.right.front']);+ expect(tireRegion?.color).not.toEqual(hubRegion?.color);+ });++ test('shows explicit backfaces and ground contact in their dedicated buffers', () => {+ const reversed = new Group();+ reversed.name = 'Reversed';+ const planeGeometry = new PlaneGeometry(1, 1);+ planeGeometry.rotateY(-Math.PI / 2);+ const plane = new Mesh(planeGeometry, new MeshStandardMaterial({ color: 0xffffff }));+ plane.name = 'BackFacingPlane';+ reversed.add(plane);+ const normals = renderDiagnosticView(+ reversed,+ GENERIC_DIAGNOSTIC_REQUESTS.find((view) => view.id === 'generic.front.normals-backface')!,+ { size: 48 },+ );+ let redPixels = 0;+ for (let index = 0; index < normals.rgb.length; index += 3) {+ if (+ normals.rgb[index] === 238 &&+ normals.rgb[index + 1] === 48 &&+ normals.rgb[index + 2] === 64+ ) {+ redPixels++;+ }+ }+ expect(redPixels).toBeGreaterThan(0);++ const grounded = new Group();+ const box = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial());+ box.position.y = 0.5;+ grounded.add(box);+ const contact = renderDiagnosticView(+ grounded,+ GENERIC_DIAGNOSTIC_REQUESTS.find((view) => view.id === 'generic.front.depth-contact')!,+ { size: 64 },+ );+ let contactPixels = 0;+ for (let index = 0; index < contact.rgb.length; index += 3) {+ if (+ contact.rgb[index] === 58 &&+ contact.rgb[index + 1] === 220 &&+ contact.rgb[index + 2] === 126+ ) {+ contactPixels++;+ }+ }+ expect(contactPixels).toBeGreaterThan(0);+ });+});++describe('QA-019 additive category diagnostic profiles', () => {+ test('selects required extras without changing the generic six or their buffers', () => {+ const expected: Record<AssetCategory, string[]> = {+ prop: [],+ vfx: [],+ environment: [],+ architecture: [+ 'architecture.gable.positive',+ 'architecture.gable.negative',+ 'architecture.cutaway.plan',+ 'architecture.cutaway.dollhouse',+ 'architecture.portal.eye',+ ],+ character: ['character.skeleton.front', 'character.skeleton.right'],+ vehicle: ['vehicle.underbody', 'vehicle.wheel-section.right'],+ vegetation: ['vegetation.canopy-underside'],+ };+ for (const category of Object.keys(expected) as AssetCategory[]) {+ const plan = planDiagnosticViews(intent(category));+ expect(plan.category).toBe(category);+ expect(plan.qaProfile).toBe(`${category}.test`);+ expect(plan.generic).toBe(GENERIC_DIAGNOSTIC_REQUESTS);+ expect(plan.genericCameraIds).toEqual([+ 'front',+ 'right',+ 'back',+ 'left',+ 'top',+ 'three-quarter',+ ]);+ expect(plan.extra.map((view) => view.id)).toEqual(expected[category]);+ }+ });++ test('requests deterministic motion phases, underside, wheel section, and grazing light', () => {+ const character = planDiagnosticViews(+ createAssetIntentV1({+ category: 'character',+ character: {+ bodyPlan: 'biped',+ grounded: true,+ locomotion: 'walk',+ clips: [{ name: 'Walk', playback: 'loop' }],+ },+ }),+ );+ const motion = character.extra.filter((view) => view.variant === 'character-motion-strip');+ expect(motion.map((view) => view.id)).toEqual([+ 'character.motion-strip.front.walk',+ 'character.motion-strip.right.walk',+ ]);+ expect(motion.every((view) => view.phaseFractions?.join(',') === '0,0.2,0.4,0.6,0.8,1')).toBe(+ true,+ );++ const vegetation = planDiagnosticViews(intent('vegetation'));+ expect(+ vegetation.extra.find((view) => view.id === 'vegetation.canopy-underside')?.cameraId,+ ).toBe('underside');++ const vehicle = planDiagnosticViews(intent('vehicle'));+ expect(vehicle.extra.find((view) => view.id === 'vehicle.underbody')?.cameraId).toBe(+ 'underside',+ );+ expect(+ vehicle.extra.find((view) => view.id === 'vehicle.wheel-section.right')?.focusRolePrefixes,+ ).toEqual(['wheel.', 'axle.', 'hub.', 'tire.']);++ const materialPlan = planDiagnosticViews(intent('prop', 'pbrRecipe'));+ expect(materialPlan.extra.map((view) => view.id)).toEqual(['material.grazing-light']);+ });++ test('binds both gable elevations to the trusted ridge axis and keeps non-gables separate', () => {+ const ridgeZ = createAssetIntentV1({+ category: 'architecture',+ architecture: { roof: { ridgeAxis: 'z' } },+ });+ const ridgeZPlan = planDiagnosticViews(ridgeZ);+ expect(+ ridgeZPlan.extra.find((view) => view.id === 'architecture.gable.positive')?.cameraId,+ ).toBe('right');+ expect(+ ridgeZPlan.extra.find((view) => view.id === 'architecture.gable.negative')?.cameraId,+ ).toBe('left');++ const bridge = createAssetIntentV1({+ category: 'architecture',+ architecture: {+ subtype: 'bridge',+ enterable: false,+ roof: { type: 'none', rise: 0, pitchDegrees: 0, closedEnds: false },+ },+ });+ const bridgeIds = planDiagnosticViews(bridge).extra.map((view) => view.id);+ expect(bridgeIds).not.toContain('architecture.gable.positive');+ expect(bridgeIds).not.toContain('architecture.gable.negative');+ expect(bridgeIds).not.toContain('architecture.portal.eye');+ });++ test('renders a semantic roof-off cutaway without mutating the source scene', () => {+ const root = fixtureScene();+ // A spoofed model-authored category cannot influence trusted intent selection.+ root.userData.category = 'vehicle';+ const before = sourceFingerprint(root);+ const plan = planDiagnosticViews(intent('architecture', 'pbrRecipe'));+ expect(plan.extra.map((view) => view.id)).toEqual([+ 'architecture.gable.positive',+ 'architecture.gable.negative',+ 'architecture.cutaway.plan',+ 'architecture.cutaway.dollhouse',+ 'architecture.portal.eye',+ 'material.grazing-light',+ ]);++ const frame = renderDiagnosticView(+ root,+ plan.extra.find((view) => view.id === 'architecture.cutaway.dollhouse')!,+ { size: 72 },+ );+ expect(frame.regions.some((region) => region.semanticRoles.includes('roof.slope.left'))).toBe(+ false,+ );+ expect(frame.regions.some((region) => region.semanticRoles.includes('chassis.main'))).toBe(+ true,+ );+ expect(sourceFingerprint(root)).toBe(before);+ });++ test('grazing-light rendering is deterministic and keeps a stable custom camera', () => {+ const root = fixtureScene();+ const grazingRequest = planDiagnosticViews(intent('prop', 'texturedHero')).extra[0];+ const actual = planDiagnosticViews(intent('vehicle', 'pbrRecipe')).extra.find(+ (view) => view.id === 'material.grazing-light',+ )!;+ expect(grazingRequest?.id).toBe('material.grazing-light');+ const first = renderDiagnosticView(root, actual, { size: 48 });+ const second = renderDiagnosticView(root, actual, { size: 48 });+ expect(first.variant).toBe('material-grazing-light');+ expect(first.camera.id).toBe('grazing');+ expect(first.rgb).toEqual(second.rgb);+ expect(first.png.equals(second.png)).toBe(true);+ });++ test('rejects an unregistered camera rather than silently changing evidence', () => {+ const invalid: DiagnosticViewRequest = {+ id: 'invalid.camera',+ label: 'Invalid',+ cameraId: 'model-invented-camera',+ buffer: 'silhouette-unlit',+ scope: 'generic',+ };+ expect(() => renderDiagnosticView(fixtureScene(), invalid)).toThrow(+ 'Unknown diagnostic camera',+ );+ });+});diff --git a/src/views/__tests__/vehicle.test.ts b/src/views/__tests__/vehicle.test.tsnew file mode 100644index 00000000..80e72082--- /dev/null+++ b/src/views/__tests__/vehicle.test.ts@@ -0,0 +1,142 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';++import { createAssetIntentV1, stampSemanticMetadataV1 } from '../../contracts';+import { renderSceneToGLB } from '../../render';+import { createVehicleFrame, createWheelAssembly } from '../../vehicle';+import {+ captureVehicleDiagnosticViews,+ createVehicleDiagnosticOverlay,+ describeVehicleDiagnostics,+} from '../vehicle';++function fixture() {+ const frame = createVehicleFrame('DiagnosticCar');+ frame.root.position.set(2, 1, -4);+ frame.root.rotation.y = 0.55;+ const chassis = new THREE.Mesh(+ new THREE.BoxGeometry(2.8, 0.6, 1.4),+ new THREE.MeshStandardMaterial(),+ );+ chassis.name = 'Chassis';+ chassis.position.y = 0.75;+ stampSemanticMetadataV1(chassis, { roles: ['chassis.main'] });+ frame.root.add(chassis);+ for (const [index, x] of [+ ['front', 1],+ ['rear', -1],+ ] as const) {+ for (const side of ['left', 'right'] as const) {+ createWheelAssembly(+ 'Wheel',+ {+ tire: new THREE.MeshStandardMaterial(),+ rim: new THREE.MeshStandardMaterial(),+ },+ {+ radius: 0.45,+ width: 0.18,+ side,+ index,+ position: [x, 0.45, side === 'left' ? -0.75 : 0.75],+ steering: index === 'front',+ parent: frame.root,+ },+ );+ }+ }+ frame.root.updateMatrixWorld(true);+ return frame.root;+}++describe('vehicle diagnostics', () => {+ test('describes +X, chassis, axle, wheel, support, underbody, and section evidence', () => {+ const descriptor = describeVehicleDiagnostics(fixture());+ expect(descriptor.forwardArrow).toEqual({ start: [0, 0, 0], end: [1, 0, 0] });+ expect(descriptor.chassisBox?.min[0]).toBeCloseTo(-1.4, 6);+ expect(descriptor.chassisBox?.min[1]).toBeCloseTo(0.45, 6);+ expect(descriptor.chassisBox?.min[2]).toBeCloseTo(-0.7, 6);+ expect(descriptor.chassisBox?.max[0]).toBeCloseTo(1.4, 6);+ expect(descriptor.chassisBox?.max[1]).toBeCloseTo(1.05, 6);+ expect(descriptor.chassisBox?.max[2]).toBeCloseTo(0.7, 6);+ expect(descriptor.axles).toHaveLength(2);+ expect(descriptor.wheels).toHaveLength(4);+ expect(descriptor.wheels.every((wheel) => wheel.axle[2] > 0.999)).toBe(true);+ expect(descriptor.supportPlaneY).toBeCloseTo(0, 6);+ expect(descriptor.views.map((view) => view.id)).toEqual(+ expect.arrayContaining(['vehicle.front-direction', 'vehicle.axles.top', 'vehicle.underbody']),+ );+ expect(+ descriptor.views.filter((view) => view.id.startsWith('vehicle.wheel-section.')),+ ).toHaveLength(2);+ });++ test('creates a separate renderable overlay without mutating the source', () => {+ const root = fixture();+ const before = root.children.map((child) => ({+ child,+ visible: child.visible,+ position: child.position.clone(),+ quaternion: child.quaternion.clone(),+ }));+ const overlay = createVehicleDiagnosticOverlay(root);+ expect(overlay.parent).toBeNull();+ expect(overlay.getObjectByName('Diagnostic_Forward_+X')).toBeDefined();+ expect(overlay.getObjectByName('Diagnostic_ChassisBox')).toBeDefined();+ expect(overlay.getObjectByName('Diagnostic_SupportPlane')).toBeDefined();+ expect(+ overlay.children.filter((child) => child.name.startsWith('Diagnostic_Axle_')),+ ).toHaveLength(2);+ expect(+ overlay.children.filter((child) => child.name.startsWith('Diagnostic_Wheel_')),+ ).toHaveLength(4);+ for (const snapshot of before) {+ expect(snapshot.child.visible).toBe(snapshot.visible);+ expect(snapshot.child.position).toEqual(snapshot.position);+ expect(snapshot.child.quaternion.angleTo(snapshot.quaternion)).toBeCloseTo(0, 8);+ }+ });++ test('captures underbody and one wheel close-up through the production render path', async () => {+ const root = fixture();+ const intent = createAssetIntentV1({ category: 'vehicle', subtype: 'wheeled' });+ const rootSnapshot = {+ position: root.position.clone(),+ quaternion: root.quaternion.clone(),+ scale: root.scale.clone(),+ children: [...root.children],+ };+ const focused = captureVehicleDiagnosticViews(root, intent, 72);+ expect(focused.map((capture) => capture.kind)).toEqual(['underbody', 'wheel-section']);+ expect(focused.every((capture) => capture.png.byteLength > 100)).toBe(true);+ expect(focused[1]?.id).toContain('wheel.assembly.right.front');+ const underbodyRoles = new Set(+ focused[0]?.regions.flatMap((region) => region.semanticRoles) ?? [],+ );+ expect(underbodyRoles.size).toBeGreaterThan(0);+ for (const role of [+ 'diagnostic.vehicle.forward',+ 'diagnostic.vehicle.chassis',+ 'diagnostic.vehicle.support-plane',+ ]) {+ expect(underbodyRoles.has(role)).toBe(true);+ }+ expect([...underbodyRoles].some((role) => role.startsWith('diagnostic.vehicle.axle.'))).toBe(+ true,+ );+ expect([...underbodyRoles].some((role) => role.startsWith('diagnostic.vehicle.wheel.'))).toBe(+ true,+ );++ const rendered = await renderSceneToGLB(root, { intent });+ expect(rendered.diagnosticViews?.map((capture) => capture.kind)).toEqual([+ 'underbody',+ 'wheel-section',+ ]);+ expect(root.position).toEqual(rootSnapshot.position);+ expect(root.quaternion.angleTo(rootSnapshot.quaternion)).toBeCloseTo(0, 8);+ expect(root.scale).toEqual(rootSnapshot.scale);+ expect(root.children).toEqual(rootSnapshot.children);+ expect(root.children.every((child) => child.parent === root)).toBe(true);+ });+});diff --git a/src/views/architecture.ts b/src/views/architecture.tsnew file mode 100644index 00000000..eead0aeb--- /dev/null+++ b/src/views/architecture.ts@@ -0,0 +1,73 @@+import { readSemanticMetadataV1FromExtras } from '../contracts';++export interface ArchitectureViewNode {+ name?: string;+ visible?: boolean;+ userData?: Record<string, unknown>;+ children?: ArchitectureViewNode[];+}++export type ArchitectureRoofSelectionMode = 'semantic' | 'legacy-name' | 'none';++export interface ArchitectureRoofSelection {+ mode: ArchitectureRoofSelectionMode;+ /** Minimal subtree roots: a selected ancestor suppresses selected descendants. */+ nodes: ArchitectureViewNode[];+}++export const ARCHITECTURE_ROOF_ROLE_PREFIXES = Object.freeze(['roof.', 'architecture.roof.']);++function nodeRoles(node: ArchitectureViewNode): readonly string[] {+ return readSemanticMetadataV1FromExtras(node.userData ?? {})?.roles ?? [];+}++export function hasArchitectureRoofRole(node: ArchitectureViewNode): boolean {+ return nodeRoles(node).some((role) =>+ ARCHITECTURE_ROOF_ROLE_PREFIXES.some((prefix) => role.startsWith(prefix)),+ );+}++function legacyRoofName(name: string | undefined): boolean {+ if (!name) return false;+ // Deliberately does not match "RooftopGarden" or "RoofRack". This fallback+ // exists only for historical Kiln roof naming conventions.+ return /^roof(?:$|[_. -]|(?:slope|panel|gable|ridge)|[ab](?:$|[_. -]))/i.test(name.trim());+}++function minimalMatches(+ root: ArchitectureViewNode,+ predicate: (node: ArchitectureViewNode) => boolean,+): ArchitectureViewNode[] {+ const matches: ArchitectureViewNode[] = [];+ const visit = (node: ArchitectureViewNode, ancestorMatched: boolean): void => {+ const matched = predicate(node);+ if (matched && !ancestorMatched) matches.push(node);+ for (const child of node.children ?? []) visit(child, ancestorMatched || matched);+ };+ visit(root, false);+ return matches;+}++/**+ * Resolve a separable roof from portable semantic roles. Historical name+ * inference is consulted only when the asset carries no roof semantics at all.+ */+export function selectArchitectureRoofNodes(root: unknown): ArchitectureRoofSelection {+ const candidate = root as ArchitectureViewNode;+ const semantic = minimalMatches(candidate, hasArchitectureRoofRole);+ if (semantic.length > 0) return { mode: 'semantic', nodes: semantic };+ const legacy = minimalMatches(candidate, (node) => legacyRoofName(node.name));+ return legacy.length > 0 ? { mode: 'legacy-name', nodes: legacy } : { mode: 'none', nodes: [] };+}++function setSubtreeVisibility(node: ArchitectureViewNode, visible: boolean): void {+ node.visible = visible;+ for (const child of node.children ?? []) setSubtreeVisibility(child, visible);+}++/** Hide the whole selected roof and no non-roof sibling. Returns subtree roots hidden. */+export function hideArchitectureRoofInScene(root: unknown): ArchitectureRoofSelection {+ const selection = selectArchitectureRoofNodes(root);+ for (const node of selection.nodes) setSubtreeVisibility(node, false);+ return selection;+}diff --git a/src/views/character-capture.ts b/src/views/character-capture.tsnew file mode 100644index 00000000..fdae5c24--- /dev/null+++ b/src/views/character-capture.ts@@ -0,0 +1,277 @@+import * as THREE from 'three';++import type { CharacterIntentV1 } from '../contracts';+import type { QaFinding } from '../qa/types';+import { buildCharacterDiagnosticDescriptor, planCharacterDiagnosticRequests } from './character';+import {+ renderDiagnosticView,+ type DiagnosticOverlayRegion,+ type DiagnosticViewRequest,+} from './diagnostic';+import { encodePng } from './png';+import { renderClipAnimation } from './index';+import { stampLabel, type DuckClip } from './pose';++export interface CharacterCapturedDiagnosticV1 {+ id: string;+ label: string;+ cameraId: 'front' | 'right';+ kind: 'skeleton' | 'motion-strip';+ width: number;+ height: number;+ png: Buffer;+ regions: DiagnosticOverlayRegion[];+ clipName?: string;+ phaseFractions?: readonly number[];+}++type Point2 = [number, number];++const rgbFromHex = (value: string): [number, number, number] => {+ const parsed = Number.parseInt(value.replace(/^#/, ''), 16);+ return [(parsed >>> 16) & 255, (parsed >>> 8) & 255, parsed & 255];+};++function drawLine(+ rgb: Uint8Array,+ width: number,+ height: number,+ from: Point2,+ to: Point2,+ color: [number, number, number],+): void {+ let x0 = Math.round(from[0]);+ let y0 = Math.round(from[1]);+ const x1 = Math.round(to[0]);+ const y1 = Math.round(to[1]);+ const dx = Math.abs(x1 - x0);+ const sx = x0 < x1 ? 1 : -1;+ const dy = -Math.abs(y1 - y0);+ const sy = y0 < y1 ? 1 : -1;+ let error = dx + dy;+ while (true) {+ if (x0 >= 0 && x0 < width && y0 >= 0 && y0 < height) {+ const offset = (y0 * width + x0) * 3;+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];+ }+ if (x0 === x1 && y0 === y1) break;+ const doubled = 2 * error;+ if (doubled >= dy) {+ error += dy;+ x0 += sx;+ }+ if (doubled <= dx) {+ error += dx;+ y0 += sy;+ }+ }+}++function drawCross(+ rgb: Uint8Array,+ width: number,+ height: number,+ point: Point2,+ color: [number, number, number],+ radius = 3,+): void {+ drawLine(rgb, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color);+ drawLine(rgb, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color);+}++function projector(+ root: THREE.Object3D,+ cameraId: 'front' | 'right',+ size: number,+): (assetPoint: readonly [number, number, number]) => Point2 {+ root.updateMatrixWorld(true);+ const bounds = new THREE.Box3().setFromObject(root);+ if (bounds.isEmpty())+ bounds.set(new THREE.Vector3(-0.5, 0, -0.5), new THREE.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE.Vector3());+ const camera = cameraId === 'front' ? new THREE.Vector3(1, 0, 0) : new THREE.Vector3(0, 0, 1);+ const upHint = new THREE.Vector3(0, 1, 0);+ const xAxis = new THREE.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE.Vector3().crossVectors(camera, xAxis).normalize();+ let extent = 1e-6;+ for (let corner = 0; corner < 8; corner++) {+ const point = new THREE.Vector3(+ corner & 1 ? bounds.max.x : bounds.min.x,+ corner & 2 ? bounds.max.y : bounds.min.y,+ corner & 4 ? bounds.max.z : bounds.min.z,+ ).sub(center);+ extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));+ }+ const scale = (size * 0.45) / extent;+ return (assetPoint) => {+ const world = new THREE.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);+ return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];+ };+}++function skeletonCapture(+ root: THREE.Object3D,+ request: ReturnType<typeof planCharacterDiagnosticRequests>[number],+ findings: readonly QaFinding[],+ size: number,+): CharacterCapturedDiagnosticV1 {+ const baseRequest: DiagnosticViewRequest = {+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,+ buffer: 'semantic-overlay',+ scope: 'category',+ variant: 'character-skeleton',+ focusRolePrefixes: request.focusRolePrefixes,+ };+ const frame = renderDiagnosticView(root, baseRequest, { size });+ const descriptor = buildCharacterDiagnosticDescriptor(root, findings);+ const project = projector(root, request.cameraId, size);+ const byRole = new Map(descriptor.joints.map((joint) => [joint.role, joint]));++ for (const edge of descriptor.edges) {+ const parent = byRole.get(edge.parentRole);+ const child = byRole.get(edge.childRole);+ if (!parent || !child) continue;+ drawLine(+ frame.rgb,+ frame.width,+ frame.height,+ project(parent.assetPosition),+ project(child.assetPosition),+ edge.valid ? rgbFromHex(edge.color) : [255, 62, 72],+ );+ }++ for (const joint of descriptor.joints) {+ const point = project(joint.assetPosition);+ const color = rgbFromHex(joint.color);+ drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color);+ drawLine(+ frame.rgb,+ frame.width,+ frame.height,+ point,+ project(joint.forwardAxisEnd),+ [64, 220, 255],+ );+ drawLine(+ frame.rgb,+ frame.width,+ frame.height,+ point,+ project(joint.bendAxisEnd),+ [255, 105, 210],+ );+ stampLabel(+ frame.rgb,+ frame.width,+ frame.height,+ Math.max(0, Math.min(frame.width - 2, Math.round(point[0] + 3))),+ Math.max(0, Math.min(frame.height - 7, Math.round(point[1] - 6))),+ joint.label+ .toUpperCase()+ .replace(/[^A-Z0-9]+/g, ' ')+ .slice(0, 18),+ 1,+ );+ frame.regions.push({+ nodeName: joint.nodeName,+ nodePath: joint.nodePath,+ semanticRoles: [`joint.${joint.role}`, ...(joint.contact ? ['contact.character'] : [])],+ pixelBounds: [+ Math.max(0, Math.round(point[0]) - 4),+ Math.max(0, Math.round(point[1]) - 4),+ Math.min(frame.width - 1, Math.round(point[0]) + 4),+ Math.min(frame.height - 1, Math.round(point[1]) + 4),+ ],+ color,+ triangleCount: 0,+ });+ }+ const arrow = descriptor.canonicalForwardArrow;+ drawLine(+ frame.rgb,+ frame.width,+ frame.height,+ project(arrow.start),+ project(arrow.end),+ [255, 220, 64],+ );+ frame.regions.sort((a, b) => a.nodePath.localeCompare(b.nodePath));+ return {+ id: frame.id,+ label: frame.label,+ cameraId: request.cameraId,+ kind: 'skeleton',+ width: frame.width,+ height: frame.height,+ png: encodePng(frame.rgb, frame.width, frame.height),+ regions: frame.regions,+ };+}++/** Actual automatic capture path: two labeled skeleton overlays plus front/right+ * fixed-phase strips for resolved locomotion and primary one-shot clips. */+export async function captureCharacterDiagnosticViews(+ root: THREE.Object3D,+ clips: readonly DuckClip[],+ intent: CharacterIntentV1,+ findings: readonly QaFinding[] = [],+ size = 256,+): Promise<CharacterCapturedDiagnosticV1[]> {+ const transforms: Array<{+ node: THREE.Object3D;+ position: THREE.Vector3;+ quaternion: THREE.Quaternion;+ scale: THREE.Vector3;+ }> = [];+ root.traverse((node) => {+ transforms.push({+ node,+ position: node.position.clone(),+ quaternion: node.quaternion.clone(),+ scale: node.scale.clone(),+ });+ });+ const requests = planCharacterDiagnosticRequests(intent);+ const captures: CharacterCapturedDiagnosticV1[] = [];+ try {+ for (const request of requests) {+ if (request.variant === 'character-skeleton') {+ captures.push(skeletonCapture(root, request, findings, size));+ continue;+ }+ if (!request.clipName) continue;+ const strip = await renderClipAnimation(root, clips, {+ clip: request.clipName,+ camera: request.cameraId,+ frames: request.phaseFractions?.length ?? 6,+ size,+ });+ if (!strip.ok || !strip.png || !strip.width || !strip.height) continue;+ captures.push({+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,+ kind: 'motion-strip',+ width: strip.width,+ height: strip.height,+ png: strip.png,+ regions: [],+ clipName: request.clipName,+ phaseFractions: request.phaseFractions,+ });+ }+ } finally {+ for (const saved of transforms) {+ saved.node.position.copy(saved.position);+ saved.node.quaternion.copy(saved.quaternion);+ saved.node.scale.copy(saved.scale);+ }+ root.updateMatrixWorld(true);+ }+ return captures;+}diff --git a/src/views/character.ts b/src/views/character.tsnew file mode 100644index 00000000..6f01e2a0--- /dev/null+++ b/src/views/character.ts@@ -0,0 +1,266 @@+import * as THREE from 'three';++import {+ collectCharacterJointNodes,+ type CharacterJointDescriptorV1,+ type CharacterVector3,+} from '../character';+import type { CharacterIntentV1 } from '../contracts';+import type { QaFinding } from '../qa/types';++const CHAIN_COLORS = Object.freeze([+ '#4fc3f7',+ '#ff8a65',+ '#81c784',+ '#ba68c8',+ '#ffd54f',+ '#4db6ac',+ '#f06292',+ '#90a4ae',+]);+const AXIAL_ROLES = new Set(['root', 'hips', 'spine', 'neck', 'head']);++export interface CharacterDiagnosticJointV1 {+ role: string;+ aliases: string[];+ side: CharacterJointDescriptorV1['side'];+ nodeName: string;+ nodePath: string;+ label: string;+ chainId: string;+ color: string;+ assetPosition: CharacterVector3;+ forwardAxisEnd: CharacterVector3;+ bendAxisEnd: CharacterVector3;+ endEffector: boolean;+ contact: boolean;+}++export interface CharacterDiagnosticEdgeV1 {+ parentRole: string;+ childRole: string;+ parentNodePath?: string;+ childNodePath: string;+ valid: boolean;+ color: string;+}++export interface CharacterDiagnosticDescriptorV1 {+ schemaVersion: 1;+ joints: CharacterDiagnosticJointV1[];+ edges: CharacterDiagnosticEdgeV1[];+ contacts: Array<{ role: string; nodePath: string; assetPosition: CharacterVector3 }>;+ canonicalForwardArrow: { start: CharacterVector3; end: CharacterVector3; label: '+X forward' };+ invalidFindingNodePaths: string[];+}++function rounded(value: number): number {+ const result = Math.round(value * 1e9) / 1e9;+ return Object.is(result, -0) ? 0 : result;+}++function tuple(vector: THREE.Vector3): CharacterVector3 {+ return [rounded(vector.x), rounded(vector.y), rounded(vector.z)];+}++function chainIdFor(+ descriptor: CharacterJointDescriptorV1,+ byRole: ReadonlyMap<string, CharacterJointDescriptorV1>,+): string {+ if (AXIAL_ROLES.has(descriptor.role)) return 'axial';+ let current = descriptor;+ const seen = new Set([current.role]);+ while (current.parentRole && !AXIAL_ROLES.has(current.parentRole)) {+ const parent = byRole.get(current.parentRole);+ if (!parent || seen.has(parent.role)) break;+ seen.add(parent.role);+ current = parent;+ }+ return current.role;+}++function colorFor(value: string): string {+ let hash = 2166136261;+ for (let index = 0; index < value.length; index++) {+ hash ^= value.charCodeAt(index);+ hash = Math.imul(hash, 16777619);+ }+ return CHAIN_COLORS[Math.abs(hash) % CHAIN_COLORS.length]!;+}++/**+ * Build the node-addressable overlay payload used by front/right skeleton+ * views. All positions and axes are asset-local, so transformed parents do not+ * rotate the canonical +X evidence frame.+ */+export function buildCharacterDiagnosticDescriptor(+ root: THREE.Object3D,+ findings: readonly QaFinding[] = [],+): CharacterDiagnosticDescriptorV1 {+ root.updateMatrixWorld(true);+ const rootInverse = root.matrixWorld.clone().invert();+ const evidence = collectCharacterJointNodes(root);+ const descriptorByRole = new Map(+ evidence.map((joint) => [joint.descriptor.role, joint.descriptor]),+ );+ const evidenceByRole = new Map(evidence.map((joint) => [joint.descriptor.role, joint]));+ const invalidFindingNodePaths = [+ ...new Set(+ findings+ .filter((finding) => finding.code === 'CHAR_PARENT_EDGE')+ .map((finding) => finding.affected?.nodePath)+ .filter((path): path is string => Boolean(path)),+ ),+ ].sort();+ const invalidPaths = new Set(invalidFindingNodePaths);++ const joints = evidence.map((joint): CharacterDiagnosticJointV1 => {+ const relative = rootInverse.clone().multiply(joint.node.matrixWorld);+ const position = new THREE.Vector3().setFromMatrixPosition(relative);+ const forward = new THREE.Vector3(...joint.descriptor.localForwardAxis)+ .transformDirection(relative)+ .multiplyScalar(0.2)+ .add(position);+ const bend = new THREE.Vector3(...joint.descriptor.localBendAxis)+ .transformDirection(relative)+ .multiplyScalar(0.2)+ .add(position);+ const chainId = chainIdFor(joint.descriptor, descriptorByRole);+ return {+ role: joint.descriptor.role,+ aliases: [...joint.descriptor.aliases],+ side: joint.descriptor.side,+ nodeName: joint.node.name,+ nodePath: joint.nodePath,+ label: joint.descriptor.role,+ chainId,+ color: colorFor(chainId),+ assetPosition: tuple(position),+ forwardAxisEnd: tuple(forward),+ bendAxisEnd: tuple(bend),+ endEffector: joint.descriptor.endEffector,+ contact: joint.descriptor.contact,+ };+ });++ const edges = evidence+ .filter((joint) => joint.descriptor.parentRole)+ .map((joint): CharacterDiagnosticEdgeV1 => {+ const parentRole = joint.descriptor.parentRole!;+ const parent = evidenceByRole.get(parentRole);+ const chainId = chainIdFor(joint.descriptor, descriptorByRole);+ return {+ parentRole,+ childRole: joint.descriptor.role,+ ...(parent ? { parentNodePath: parent.nodePath } : {}),+ childNodePath: joint.nodePath,+ valid: Boolean(parent) && !invalidPaths.has(joint.nodePath),+ color: colorFor(chainId),+ };+ })+ .sort((a, b) =>+ `${a.parentRole}:${a.childRole}`.localeCompare(`${b.parentRole}:${b.childRole}`),+ );++ return {+ schemaVersion: 1,+ joints,+ edges,+ contacts: joints+ .filter((joint) => joint.contact)+ .map((joint) => ({+ role: joint.role,+ nodePath: joint.nodePath,+ assetPosition: joint.assetPosition,+ })),+ canonicalForwardArrow: { start: [0, 0, 0], end: [1, 0, 0], label: '+X forward' },+ invalidFindingNodePaths,+ };+}++export const CHARACTER_MOTION_DIAGNOSTIC_PHASES = Object.freeze([0, 0.2, 0.4, 0.6, 0.8, 1]);++export interface CharacterDiagnosticRequestV1 {+ id: string;+ label: string;+ cameraId: 'front' | 'right';+ buffer: 'semantic-overlay' | 'silhouette-unlit';+ variant: 'character-skeleton' | 'character-motion-strip';+ clipName?: string;+ phaseFractions?: readonly number[];+ focusRolePrefixes: readonly string[];+ automatic: true;+}++const diagnosticRequest = (value: CharacterDiagnosticRequestV1): CharacterDiagnosticRequestV1 =>+ Object.freeze({+ ...value,+ focusRolePrefixes: Object.freeze([...value.focusRolePrefixes]),+ ...(value.phaseFractions ? { phaseFractions: Object.freeze([...value.phaseFractions]) } : {}),+ });++function safeClipId(name: string): string {+ return name+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '');+}++/** Automatically request both skeleton elevations and fixed-phase strips for+ * the resolved locomotion and primary one-shot action clips. */+export function planCharacterDiagnosticRequests(+ intent: CharacterIntentV1,+): readonly CharacterDiagnosticRequestV1[] {+ const requests: CharacterDiagnosticRequestV1[] = [+ diagnosticRequest({+ id: 'character.skeleton.front',+ label: 'Character skeleton front',+ cameraId: 'front',+ buffer: 'semantic-overlay',+ variant: 'character-skeleton',+ focusRolePrefixes: ['skeleton.', 'joint.', 'contact.'],+ automatic: true,+ }),+ diagnosticRequest({+ id: 'character.skeleton.right',+ label: 'Character skeleton right',+ cameraId: 'right',+ buffer: 'semantic-overlay',+ variant: 'character-skeleton',+ focusRolePrefixes: ['skeleton.', 'joint.', 'contact.'],+ automatic: true,+ }),+ ];+ const locomotion =+ intent.clips.find(+ (clip) =>+ clip.playback === 'loop' &&+ new RegExp(intent.locomotion === 'stationary' ? 'idle' : intent.locomotion, 'i').test(+ clip.name,+ ),+ ) ?? intent.clips.find((clip) => clip.playback === 'loop');+ const action = intent.clips.find((clip) => clip.playback === 'oneShot');+ const selected = [locomotion, action].filter(+ (clip, index, values): clip is NonNullable<typeof clip> =>+ Boolean(clip) && values.findIndex((candidate) => candidate?.name === clip?.name) === index,+ );+ for (const clip of selected) {+ for (const cameraId of ['front', 'right'] as const) {+ requests.push(+ diagnosticRequest({+ id: `character.motion-strip.${cameraId}.${safeClipId(clip.name)}`,+ label: `${clip.name} fixed-phase ${cameraId} strip`,+ cameraId,+ buffer: 'silhouette-unlit',+ variant: 'character-motion-strip',+ clipName: clip.name,+ phaseFractions: CHARACTER_MOTION_DIAGNOSTIC_PHASES,+ focusRolePrefixes: ['skeleton.', 'joint.', 'limb.', 'held-item'],+ automatic: true,+ }),+ );+ }+ }+ return Object.freeze(requests);+}diff --git a/src/views/diagnostic.ts b/src/views/diagnostic.tsnew file mode 100644index 00000000..bb773274--- /dev/null+++ b/src/views/diagnostic.ts@@ -0,0 +1,850 @@+/**+ * Deterministic, read-only diagnostic views for asset QA.+ *+ * The ordinary six-view grid is a product artifact. These buffers are additive+ * evidence: every generic buffer uses the same frozen six named cameras, while+ * category profiles may request narrowly-scoped extra views. The CPU collector+ * composes local transforms itself and never updates, poses, hides, recolors, or+ * otherwise mutates the source scene.+ */++import type { AssetCategory, AssetIntentV1 } from '../contracts';+import { readSemanticMetadataV1FromExtras } from '../contracts';+import { planCharacterDiagnosticRequests } from './character';+import { encodePng } from './png';++type Vec3 = [number, number, number];+type Mat4 = Float64Array;++export const GENERIC_DIAGNOSTIC_BUFFER_IDS = [+ 'silhouette-unlit',+ 'wireframe',+ 'normals-backface',+ 'depth-contact',+ 'semantic-overlay',+] as const;++export type GenericDiagnosticBufferId = (typeof GENERIC_DIAGNOSTIC_BUFFER_IDS)[number];++export interface DiagnosticCameraSpec {+ id: string;+ name: string;+ /** Direction from model center toward the camera in Kiln's canonical frame. */+ dir: Vec3;+}++const frozenCamera = (id: string, name: string, dir: Vec3): DiagnosticCameraSpec =>+ Object.freeze({ id, name, dir: Object.freeze([...dir]) as unknown as Vec3 });++/** The exact named cameras used by the generic six-view product grid. */+export const GENERIC_DIAGNOSTIC_CAMERAS: readonly DiagnosticCameraSpec[] = Object.freeze([+ frozenCamera('front', 'Front', [1, 0, 0]),+ frozenCamera('right', 'Right', [0, 0, 1]),+ frozenCamera('back', 'Back', [-1, 0, 0]),+ frozenCamera('left', 'Left', [0, 0, -1]),+ frozenCamera('top', 'Top', [0, 1, 0.0001]),+ frozenCamera('three-quarter', '3/4', [0.7, 0.5, 0.7]),+]);++const EXTRA_CAMERAS = Object.freeze({+ underside: frozenCamera('underside', 'Canopy underside', [0.15, -0.85, 0.5]),+ grazing: frozenCamera('grazing', 'Material grazing light', [0.08, 0.12, 1]),+});++const cameraById = new Map(+ [...GENERIC_DIAGNOSTIC_CAMERAS, ...Object.values(EXTRA_CAMERAS)].map((camera) => [+ camera.id,+ camera,+ ]),+);++export type CategoryDiagnosticVariant =+ | 'architecture-cutaway'+ | 'architecture-gable-elevation'+ | 'architecture-portal-eye'+ | 'character-skeleton'+ | 'character-motion-strip'+ | 'vehicle-underbody'+ | 'vehicle-wheel-section'+ | 'vegetation-canopy-underside'+ | 'material-grazing-light';++export interface DiagnosticViewRequest {+ /** Stable evidence ID; never derived from model-authored scene metadata. */+ id: string;+ label: string;+ cameraId: string;+ buffer: GenericDiagnosticBufferId;+ scope: 'generic' | 'category' | 'material';+ variant?: CategoryDiagnosticVariant;+ /** Read-only cutaway filter over canonical semantic role prefixes. */+ omitRolePrefixes?: readonly string[];+ /** Optional framing target; non-matching geometry remains visible. */+ focusRolePrefixes?: readonly string[];+ /** Fixed normalized phases requested from the later animation sampler. */+ phaseFractions?: readonly number[];+ /** Exact clip selected by trusted character intent for an automatic motion strip. */+ clipName?: string;+}++const request = (value: DiagnosticViewRequest): DiagnosticViewRequest =>+ Object.freeze({+ ...value,+ ...(value.omitRolePrefixes+ ? { omitRolePrefixes: Object.freeze([...value.omitRolePrefixes]) }+ : {}),+ ...(value.focusRolePrefixes+ ? { focusRolePrefixes: Object.freeze([...value.focusRolePrefixes]) }+ : {}),+ ...(value.phaseFractions ? { phaseFractions: Object.freeze([...value.phaseFractions]) } : {}),+ });++/** Five deterministic buffers from every one of the unchanged generic six cameras. */+export const GENERIC_DIAGNOSTIC_REQUESTS: readonly DiagnosticViewRequest[] = Object.freeze(+ GENERIC_DIAGNOSTIC_CAMERAS.flatMap((camera) =>+ GENERIC_DIAGNOSTIC_BUFFER_IDS.map((buffer) =>+ request({+ id: `generic.${camera.id}.${buffer}`,+ label: `${camera.name} ${buffer}`,+ cameraId: camera.id,+ buffer,+ scope: 'generic',+ }),+ ),+ ),+);++const CATEGORY_REQUESTS: Readonly<Record<AssetCategory, readonly DiagnosticViewRequest[]>> =+ Object.freeze({+ prop: Object.freeze([]),+ vfx: Object.freeze([]),+ environment: Object.freeze([]),+ architecture: Object.freeze([]),+ character: Object.freeze([]),+ vehicle: Object.freeze([+ request({+ id: 'vehicle.underbody',+ label: 'Vehicle underbody and support plane',+ cameraId: 'underside',+ buffer: 'semantic-overlay',+ scope: 'category',+ variant: 'vehicle-underbody',+ focusRolePrefixes: [+ 'chassis.',+ 'wheel.',+ 'axle.',+ 'support.',+ 'contact.',+ 'diagnostic.vehicle.',+ ],+ }),+ request({+ id: 'vehicle.wheel-section.right',+ label: 'Vehicle wheel section',+ cameraId: 'right',+ buffer: 'semantic-overlay',+ scope: 'category',+ variant: 'vehicle-wheel-section',+ focusRolePrefixes: ['wheel.', 'axle.', 'hub.', 'tire.'],+ }),+ ]),+ vegetation: Object.freeze([+ request({+ id: 'vegetation.canopy-underside',+ label: 'Vegetation canopy underside',+ cameraId: 'underside',+ buffer: 'normals-backface',+ scope: 'category',+ variant: 'vegetation-canopy-underside',+ focusRolePrefixes: ['canopy.', 'foliage.', 'leaf.'],+ }),+ ]),+ });++function architectureDiagnosticRequests(intent: AssetIntentV1): readonly DiagnosticViewRequest[] {+ const architecture = intent.architecture;+ if (!architecture) return [];+ const requests: DiagnosticViewRequest[] = [];+ const buildingProfile =+ architecture.roof.type === 'gable' ||+ /(?:building|house|cottage|barn|hut|gable)/i.test(architecture.subtype);+ if (buildingProfile) {+ const ridgeX = architecture.roof.ridgeAxis === 'x';+ requests.push(+ request({+ id: 'architecture.gable.positive',+ label: 'Architecture positive gable elevation',+ cameraId: ridgeX ? 'front' : 'right',+ buffer: 'semantic-overlay',+ scope: 'category',+ variant: 'architecture-gable-elevation',+ focusRolePrefixes: ['roof.gable.positive', 'roof.slope.', 'wall.'],+ }),+ request({+ id: 'architecture.gable.negative',+ label: 'Architecture negative gable elevation',+ cameraId: ridgeX ? 'back' : 'left',+ buffer: 'semantic-overlay',+ scope: 'category',+ variant: 'architecture-gable-elevation',+ focusRolePrefixes: ['roof.gable.negative', 'roof.slope.', 'wall.'],+ }),+ );+ }+ requests.push(+ request({+ id: 'architecture.cutaway.plan',+ label: 'Architecture roof-off plan',+ cameraId: 'top',+ buffer: 'semantic-overlay',+ scope: 'category',+ variant: 'architecture-cutaway',+ omitRolePrefixes: ['roof.'],+ }),+ request({+ id: 'architecture.cutaway.dollhouse',+ label: 'Architecture roof-off dollhouse',+ cameraId: 'three-quarter',+ buffer: 'semantic-overlay',+ scope: 'category',+ variant: 'architecture-cutaway',+ omitRolePrefixes: ['roof.'],+ }),+ );+ if (architecture.enterable) {+ requests.push(+ request({+ id: 'architecture.portal.eye',+ label: 'Architecture portal eye view',+ cameraId: 'front',+ buffer: 'depth-contact',+ scope: 'category',+ variant: 'architecture-portal-eye',+ focusRolePrefixes: ['opening.', 'wall.', 'floor'],+ }),+ );+ }+ return Object.freeze(requests);+}++function characterDiagnosticRequests(intent: AssetIntentV1): readonly DiagnosticViewRequest[] {+ if (!intent.character) return [];+ return Object.freeze(+ planCharacterDiagnosticRequests(intent.character).map((value) =>+ request({+ id: value.id,+ label: value.label,+ cameraId: value.cameraId,+ buffer: value.buffer,+ scope: 'category',+ variant: value.variant,+ focusRolePrefixes: value.focusRolePrefixes,+ ...(value.phaseFractions ? { phaseFractions: value.phaseFractions } : {}),+ ...(value.clipName ? { clipName: value.clipName } : {}),+ }),+ ),+ );+}++const MATERIAL_GRAZING_REQUEST = request({+ id: 'material.grazing-light',+ label: 'Material grazing light',+ cameraId: 'grazing',+ buffer: 'silhouette-unlit',+ scope: 'material',+ variant: 'material-grazing-light',+});++export interface DiagnosticViewPlanV1 {+ schemaVersion: 1;+ category: AssetCategory;+ qaProfile: string;+ /** These IDs stay byte-for-byte identical for every profile. */+ genericCameraIds: readonly string[];+ generic: readonly DiagnosticViewRequest[];+ /** Additive requests selected only from trusted intent. */+ extra: readonly DiagnosticViewRequest[];+}++/**+ * Select additive category/material views from closure-owned intent. Scene names,+ * userData, and model-authored category claims are deliberately not inputs.+ */+export function planDiagnosticViews(intent: AssetIntentV1): DiagnosticViewPlanV1 {+ const categoryRequests =+ intent.category === 'architecture'+ ? architectureDiagnosticRequests(intent)+ : intent.category === 'character'+ ? characterDiagnosticRequests(intent)+ : CATEGORY_REQUESTS[intent.category];+ const includeGrazing = intent.material.mode !== 'flatOptimized';+ return {+ schemaVersion: 1,+ category: intent.category,+ qaProfile: intent.qaProfile,+ genericCameraIds: Object.freeze(GENERIC_DIAGNOSTIC_CAMERAS.map((camera) => camera.id)),+ generic: GENERIC_DIAGNOSTIC_REQUESTS,+ extra: includeGrazing+ ? Object.freeze([...categoryRequests, MATERIAL_GRAZING_REQUEST])+ : categoryRequests,+ };+}++interface DuckAttribute {+ array: ArrayLike<number>;+ itemSize: number;+ count: number;+}++interface DuckGeometry {+ getAttribute?(name: string): DuckAttribute | undefined;+ index?: DuckAttribute | null;+ userData?: Record<string, unknown>;+}++interface DuckMaterial {+ color?: { r: number; g: number; b: number };+ visible?: boolean;+}++interface DuckNode {+ name?: string;+ type?: string;+ visible?: boolean;+ children?: DuckNode[];+ isMesh?: boolean;+ geometry?: DuckGeometry;+ material?: DuckMaterial | DuckMaterial[];+ userData?: Record<string, unknown>;+ matrix?: { elements: ArrayLike<number> };+ matrixAutoUpdate?: boolean;+ position?: { x: number; y: number; z: number };+ quaternion?: { x: number; y: number; z: number; w: number };+ scale?: { x: number; y: number; z: number };+}++interface DiagnosticTriangle {+ vertices: Float64Array;+ color: Vec3;+ nodeName: string;+ nodePath: string;+ semanticRoles: readonly string[];+}++interface CollectedScene {+ triangles: DiagnosticTriangle[];+ bounds: { min: Vec3; max: Vec3 };+ focusBounds?: { min: Vec3; max: Vec3 };+}++const IDENTITY = new Float64Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);++function multiplyMatrices(a: ArrayLike<number>, b: ArrayLike<number>): Mat4 {+ const out = new Float64Array(16);+ for (let column = 0; column < 4; column++) {+ for (let row = 0; row < 4; row++) {+ let value = 0;+ for (let k = 0; k < 4; k++) value += a[k * 4 + row]! * b[column * 4 + k]!;+ out[column * 4 + row] = value;+ }+ }+ return out;+}++function composeLocalMatrix(node: DuckNode): Mat4 {+ if (node.matrixAutoUpdate === false && node.matrix?.elements) {+ return new Float64Array(Array.from(node.matrix.elements));+ }+ const p = node.position;+ const q = node.quaternion;+ const s = node.scale;+ if (!p || !q || !s) {+ return node.matrix?.elements+ ? new Float64Array(Array.from(node.matrix.elements))+ : new Float64Array(IDENTITY);+ }++ const x2 = q.x + q.x;+ const y2 = q.y + q.y;+ const z2 = q.z + q.z;+ const xx = q.x * x2;+ const xy = q.x * y2;+ const xz = q.x * z2;+ const yy = q.y * y2;+ const yz = q.y * z2;+ const zz = q.z * z2;+ const wx = q.w * x2;+ const wy = q.w * y2;+ const wz = q.w * z2;++ return new Float64Array([+ (1 - (yy + zz)) * s.x,+ (xy + wz) * s.x,+ (xz - wy) * s.x,+ 0,+ (xy - wz) * s.y,+ (1 - (xx + zz)) * s.y,+ (yz + wx) * s.y,+ 0,+ (xz + wy) * s.z,+ (yz - wx) * s.z,+ (1 - (xx + yy)) * s.z,+ 0,+ p.x,+ p.y,+ p.z,+ 1,+ ]);+}++function transformPoint(matrix: ArrayLike<number>, x: number, y: number, z: number): Vec3 {+ return [+ matrix[0]! * x + matrix[4]! * y + matrix[8]! * z + matrix[12]!,+ matrix[1]! * x + matrix[5]! * y + matrix[9]! * z + matrix[13]!,+ matrix[2]! * x + matrix[6]! * y + matrix[10]! * z + matrix[14]!,+ ];+}++function matchesRole(roles: readonly string[], prefixes: readonly string[] | undefined): boolean {+ return Boolean(prefixes?.some((prefix) => roles.some((role) => role.startsWith(prefix))));+}++function semanticRoles(node: DuckNode): readonly string[] {+ const metadata = readSemanticMetadataV1FromExtras(node.userData ?? {});+ if (metadata) return metadata.roles;+ const geometryRole = node.geometry?.userData?.['kilnGeometryRole'];+ return typeof geometryRole === 'string' ? [geometryRole] : [];+}++function clamp01(value: number): number {+ return value < 0 ? 0 : value > 1 ? 1 : value;+}++function collectScene(root: unknown, requestValue: DiagnosticViewRequest): CollectedScene {+ const triangles: DiagnosticTriangle[] = [];+ const min: Vec3 = [Infinity, Infinity, Infinity];+ const max: Vec3 = [-Infinity, -Infinity, -Infinity];+ const focusMin: Vec3 = [Infinity, Infinity, Infinity];+ const focusMax: Vec3 = [-Infinity, -Infinity, -Infinity];++ const visit = (+ node: DuckNode,+ parentMatrix: ArrayLike<number>,+ parentPath: string,+ siblingIndex: number,+ ancestorVisible: boolean,+ inheritedRoles: readonly string[],+ ): void => {+ const local = composeLocalMatrix(node);+ const world = multiplyMatrices(parentMatrix, local);+ const visible = ancestorVisible && node.visible !== false;+ const segment = `${node.name?.trim() || node.type || 'Node'}[${siblingIndex}]`;+ const nodePath = parentPath ? `${parentPath}/${segment}` : segment;+ const roles = [...new Set([...inheritedRoles, ...semanticRoles(node)])];+ const omitted = matchesRole(roles, requestValue.omitRolePrefixes);++ if (visible && !omitted && node.isMesh && node.geometry) {+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ const material = materials[0];+ if (material?.visible !== false) {+ const position = node.geometry.getAttribute?.('position');+ if (position?.itemSize === 3) {+ const worldPositions: Vec3[] = [];+ for (let index = 0; index < position.count; index++) {+ const point = transformPoint(+ world,+ position.array[index * 3]!,+ position.array[index * 3 + 1]!,+ position.array[index * 3 + 2]!,+ );+ worldPositions.push(point);+ }+ const materialColor = material?.color;+ const color: Vec3 = materialColor+ ? [clamp01(materialColor.r), clamp01(materialColor.g), clamp01(materialColor.b)]+ : [0.7, 0.7, 0.7];+ const focused = matchesRole(roles, requestValue.focusRolePrefixes);+ const addTriangle = (a: number, b: number, c: number): void => {+ const points = [worldPositions[a], worldPositions[b], worldPositions[c]];+ if (points.some((point) => !point || point.some((value) => !Number.isFinite(value)))) {+ return;+ }+ const vertices = new Float64Array(9);+ points.forEach((point, pointIndex) => {+ for (let axis = 0; axis < 3; axis++) {+ const value = point![axis]!;+ vertices[pointIndex * 3 + axis] = value;+ min[axis] = Math.min(min[axis]!, value);+ max[axis] = Math.max(max[axis]!, value);+ if (focused) {+ focusMin[axis] = Math.min(focusMin[axis]!, value);+ focusMax[axis] = Math.max(focusMax[axis]!, value);+ }+ }+ });+ triangles.push({+ vertices,+ color,+ nodeName: node.name ?? '',+ nodePath,+ semanticRoles: roles,+ });+ };+ const index = node.geometry.index;+ if (index) {+ for (let i = 0; i + 2 < index.count; i += 3) {+ addTriangle(index.array[i]!, index.array[i + 1]!, index.array[i + 2]!);+ }+ } else {+ for (let i = 0; i + 2 < position.count; i += 3) addTriangle(i, i + 1, i + 2);+ }+ }+ }+ }++ (node.children ?? []).forEach((child, index) => {+ visit(child, world, nodePath, index, visible && !omitted, roles);+ });+ };++ visit(root as DuckNode, IDENTITY, '', 0, true, []);+ const empty = !Number.isFinite(min[0]);+ const focusEmpty = !Number.isFinite(focusMin[0]);+ return {+ triangles,+ bounds: empty ? { min: [0, 0, 0], max: [0, 0, 0] } : { min, max },+ ...(!focusEmpty ? { focusBounds: { min: focusMin, max: focusMax } } : {}),+ };+}++function normalize(vector: Vec3): Vec3 {+ const length = Math.hypot(...vector) || 1;+ return [vector[0] / length, vector[1] / length, vector[2] / length];+}++function cross(a: Vec3, b: Vec3): Vec3 {+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+}++function dot(a: Vec3, b: Vec3): number {+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+}++function stableColor(key: string): [number, number, number] {+ let hash = 2166136261;+ for (let index = 0; index < key.length; index++) {+ hash ^= key.charCodeAt(index);+ hash = Math.imul(hash, 16777619);+ }+ return [96 + (hash & 0x7f), 96 + ((hash >>> 8) & 0x7f), 96 + ((hash >>> 16) & 0x7f)];+}++export interface DiagnosticOverlayRegion {+ nodeName: string;+ nodePath: string;+ semanticRoles: readonly string[];+ /** Inclusive pixel bounds [minX,minY,maxX,maxY]. */+ pixelBounds: [number, number, number, number];+ color: [number, number, number];+ triangleCount: number;+}++export interface DiagnosticViewFrame {+ id: string;+ label: string;+ camera: DiagnosticCameraSpec;+ buffer: GenericDiagnosticBufferId;+ variant?: CategoryDiagnosticVariant;+ width: number;+ height: number;+ rgb: Uint8Array;+ png: Buffer;+ regions: DiagnosticOverlayRegion[];+ phaseFractions?: readonly number[];+}++export interface DiagnosticRenderOptions {+ /** Square output size. Clamped to 16..1024; default 256. */+ size?: number;+ groundY?: number;+}++interface ProjectedTriangle {+ source: DiagnosticTriangle;+ x: [number, number, number];+ y: [number, number, number];+ z: [number, number, number];+ worldY: [number, number, number];+ normal: Vec3;+ frontFacing: boolean;+}++function projectScene(+ scene: CollectedScene,+ camera: DiagnosticCameraSpec,+ size: number,+): ProjectedTriangle[] {+ const zAxis = normalize(camera.dir);+ const upHint: Vec3 = Math.abs(zAxis[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];+ const xAxis = normalize(cross(upHint, zAxis));+ const yAxis = cross(zAxis, xAxis);+ const frame = scene.focusBounds ?? scene.bounds;+ const center: Vec3 = [+ (frame.min[0] + frame.max[0]) / 2,+ (frame.min[1] + frame.max[1]) / 2,+ (frame.min[2] + frame.max[2]) / 2,+ ];+ let extent = 1e-6;+ for (let corner = 0; corner < 8; corner++) {+ const point: Vec3 = [+ (corner & 1 ? frame.max[0] : frame.min[0]) - center[0],+ (corner & 2 ? frame.max[1] : frame.min[1]) - center[1],+ (corner & 4 ? frame.max[2] : frame.min[2]) - center[2],+ ];+ extent = Math.max(extent, Math.abs(dot(point, xAxis)), Math.abs(dot(point, yAxis)));+ }+ const scale = (size * 0.45) / extent;+ const half = size / 2;++ return scene.triangles.flatMap((triangle): ProjectedTriangle[] => {+ const v = triangle.vertices;+ const edgeA: Vec3 = [v[3]! - v[0]!, v[4]! - v[1]!, v[5]! - v[2]!];+ const edgeB: Vec3 = [v[6]! - v[0]!, v[7]! - v[1]!, v[8]! - v[2]!];+ const normalRaw = cross(edgeA, edgeB);+ const length = Math.hypot(...normalRaw);+ if (length < 1e-12) return [];+ const normal: Vec3 = normalRaw.map((component) => component / length) as Vec3;+ const xs: number[] = [];+ const ys: number[] = [];+ const zs: number[] = [];+ const worldY: number[] = [];+ for (let index = 0; index < 3; index++) {+ const point: Vec3 = [+ v[index * 3]! - center[0],+ v[index * 3 + 1]! - center[1],+ v[index * 3 + 2]! - center[2],+ ];+ xs.push(half + dot(point, xAxis) * scale);+ ys.push(half - dot(point, yAxis) * scale);+ zs.push(dot(point, zAxis));+ worldY.push(v[index * 3 + 1]!);+ }+ return [+ {+ source: triangle,+ x: xs as [number, number, number],+ y: ys as [number, number, number],+ z: zs as [number, number, number],+ worldY: worldY as [number, number, number],+ normal,+ frontFacing: dot(normal, zAxis) > 0,+ },+ ];+ });+}++function drawLine(+ rgb: Uint8Array,+ size: number,+ from: [number, number],+ to: [number, number],+ color: [number, number, number],+): void {+ let x0 = Math.round(from[0]);+ let y0 = Math.round(from[1]);+ const x1 = Math.round(to[0]);+ const y1 = Math.round(to[1]);+ const dx = Math.abs(x1 - x0);+ const sx = x0 < x1 ? 1 : -1;+ const dy = -Math.abs(y1 - y0);+ const sy = y0 < y1 ? 1 : -1;+ let error = dx + dy;+ while (true) {+ if (x0 >= 0 && x0 < size && y0 >= 0 && y0 < size) {+ const offset = (y0 * size + x0) * 3;+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];+ }+ if (x0 === x1 && y0 === y1) break;+ const doubled = 2 * error;+ if (doubled >= dy) {+ error += dy;+ x0 += sx;+ }+ if (doubled <= dx) {+ error += dx;+ y0 += sy;+ }+ }+}++function drawRegionBox(rgb: Uint8Array, size: number, region: DiagnosticOverlayRegion): void {+ const [minX, minY, maxX, maxY] = region.pixelBounds;+ drawLine(rgb, size, [minX, minY], [maxX, minY], region.color);+ drawLine(rgb, size, [maxX, minY], [maxX, maxY], region.color);+ drawLine(rgb, size, [maxX, maxY], [minX, maxY], region.color);+ drawLine(rgb, size, [minX, maxY], [minX, minY], region.color);+}++/** Render one diagnostic request without modifying any property on `root`. */+export function renderDiagnosticView(+ root: unknown,+ requestValue: DiagnosticViewRequest,+ options: DiagnosticRenderOptions = {},+): DiagnosticViewFrame {+ const camera = cameraById.get(requestValue.cameraId);+ if (!camera)+ throw new TypeError(`Unknown diagnostic camera ${JSON.stringify(requestValue.cameraId)}.`);+ const size = Math.max(16, Math.min(1024, Math.round(options.size ?? 256)));+ const groundY = options.groundY ?? 0;+ const scene = collectScene(root, requestValue);+ const triangles = projectScene(scene, camera, size);+ const background: [number, number, number] = [18, 20, 24];+ const rgb = new Uint8Array(size * size * 3);+ for (let pixel = 0; pixel < size * size; pixel++) {+ rgb[pixel * 3] = background[0];+ rgb[pixel * 3 + 1] = background[1];+ rgb[pixel * 3 + 2] = background[2];+ }+ const depth = new Float64Array(size * size).fill(-Infinity);+ const depths = triangles.flatMap((triangle) => triangle.z);+ const minDepth = depths.length > 0 ? Math.min(...depths) : 0;+ const maxDepth = depths.length > 0 ? Math.max(...depths) : 1;+ const depthRange = Math.max(1e-9, maxDepth - minDepth);+ const contactTolerance = Math.max(1e-4, (scene.bounds.max[1] - scene.bounds.min[1]) * 0.015);+ const regionMap = new Map<string, DiagnosticOverlayRegion>();++ for (const triangle of triangles) {+ const minX = Math.max(0, Math.floor(Math.min(...triangle.x)));+ const maxX = Math.min(size - 1, Math.ceil(Math.max(...triangle.x)));+ const minY = Math.max(0, Math.floor(Math.min(...triangle.y)));+ const maxY = Math.min(size - 1, Math.ceil(Math.max(...triangle.y)));+ if (minX > maxX || minY > maxY) continue;++ // Roles are inherited from root to leaf. Color by the most-specific role+ // so a broad ancestor such as `vehicle.frame` does not flatten every body,+ // tire, rim, and hub into the same overlay color.+ const key = triangle.source.semanticRoles.at(-1) ?? triangle.source.nodePath;+ const regionColor = stableColor(key);+ const existing = regionMap.get(triangle.source.nodePath);+ if (existing) {+ existing.pixelBounds[0] = Math.min(existing.pixelBounds[0], minX);+ existing.pixelBounds[1] = Math.min(existing.pixelBounds[1], minY);+ existing.pixelBounds[2] = Math.max(existing.pixelBounds[2], maxX);+ existing.pixelBounds[3] = Math.max(existing.pixelBounds[3], maxY);+ existing.triangleCount++;+ } else {+ regionMap.set(triangle.source.nodePath, {+ nodeName: triangle.source.nodeName,+ nodePath: triangle.source.nodePath,+ semanticRoles: [...triangle.source.semanticRoles],+ pixelBounds: [minX, minY, maxX, maxY],+ color: regionColor,+ triangleCount: 1,+ });+ }++ if (requestValue.buffer === 'wireframe') continue;+ const ax = triangle.x[0];+ const ay = triangle.y[0];+ const bx = triangle.x[1];+ const by = triangle.y[1];+ const cx = triangle.x[2];+ const cy = triangle.y[2];+ const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);+ if (Math.abs(area) < 1e-9) continue;+ const inverseArea = 1 / area;++ for (let py = minY; py <= maxY; py++) {+ for (let px = minX; px <= maxX; px++) {+ const sampleX = px + 0.5;+ const sampleY = py + 0.5;+ const w0 = ((bx - ax) * (sampleY - ay) - (by - ay) * (sampleX - ax)) * inverseArea;+ const w1 = ((cx - bx) * (sampleY - by) - (cy - by) * (sampleX - bx)) * inverseArea;+ const w2 = 1 - w0 - w1;+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;+ const pixelDepth = w1 * triangle.z[0] + w2 * triangle.z[1] + w0 * triangle.z[2];+ const pixel = py * size + px;+ if (pixelDepth <= depth[pixel]!) continue;+ depth[pixel] = pixelDepth;+ const offset = pixel * 3;+ let color: [number, number, number];+ if (requestValue.variant === 'material-grazing-light') {+ const grazingDirection = normalize([0.25, 0.08, 1]);+ const light = 0.08 + 0.92 * Math.max(0, dot(triangle.normal, grazingDirection));+ color = triangle.source.color.map((value) =>+ Math.round(clamp01(value * light) * 255),+ ) as [number, number, number];+ } else if (requestValue.buffer === 'silhouette-unlit') {+ color = [235, 238, 242];+ } else if (requestValue.buffer === 'normals-backface') {+ color = triangle.frontFacing+ ? (triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) as [+ number,+ number,+ number,+ ])+ : [238, 48, 64];+ } else if (requestValue.buffer === 'depth-contact') {+ const worldY =+ w1 * triangle.worldY[0] + w2 * triangle.worldY[1] + w0 * triangle.worldY[2];+ if (Math.abs(worldY - groundY) <= contactTolerance) color = [58, 220, 126];+ else if (worldY < groundY - contactTolerance) color = [245, 94, 72];+ else {+ const value = Math.round(48 + 190 * ((pixelDepth - minDepth) / depthRange));+ color = [value, value, value];+ }+ } else {+ color = regionColor;+ }+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];+ }+ }+ }++ if (requestValue.buffer === 'wireframe') {+ for (const triangle of triangles) {+ const color: [number, number, number] = triangle.frontFacing+ ? [225, 235, 245]+ : [230, 72, 84];+ for (const [a, b] of [+ [0, 1],+ [1, 2],+ [2, 0],+ ] as const) {+ drawLine(rgb, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color);+ }+ }+ }++ const regions = [...regionMap.values()].sort((a, b) => a.nodePath.localeCompare(b.nodePath));+ if (requestValue.buffer === 'semantic-overlay') {+ for (const region of regions) drawRegionBox(rgb, size, region);+ }++ return {+ id: requestValue.id,+ label: requestValue.label,+ camera,+ buffer: requestValue.buffer,+ ...(requestValue.variant ? { variant: requestValue.variant } : {}),+ width: size,+ height: size,+ rgb,+ png: encodePng(rgb, size, size),+ regions,+ ...(requestValue.phaseFractions ? { phaseFractions: requestValue.phaseFractions } : {}),+ };+}++/** Render an already-selected deterministic request list in stable input order. */+export function renderDiagnosticViews(+ root: unknown,+ requests: readonly DiagnosticViewRequest[],+ options: DiagnosticRenderOptions = {},+): DiagnosticViewFrame[] {+ return requests.map((viewRequest) => renderDiagnosticView(root, viewRequest, options));+}diff --git a/src/views/index.ts b/src/views/index.tsindex 54b0dd4f..1a8504a1 100644--- a/src/views/index.ts+++ b/src/views/index.ts@@ -29,6 +29,7 @@ import {stampLabel,type DuckClip,} from './pose';+import { hideArchitectureRoofInScene } from './architecture';import {buildSlotIndex,chooseSlot,@@ -40,8 +41,60 @@ import {export { rasterizeView, measureBounds, hideNodeInScene, SIX_VIEWS, coverage } from './raster';export type { RasterOptions, ViewSpec } from './raster';export { encodePng } from './png';+export {+ ARCHITECTURE_ROOF_ROLE_PREFIXES,+ hasArchitectureRoofRole,+ hideArchitectureRoofInScene,+ selectArchitectureRoofNodes,+} from './architecture';+export type {+ ArchitectureRoofSelection,+ ArchitectureRoofSelectionMode,+ ArchitectureViewNode,+} from './architecture';export { rasterizeComposedScene, SCENE_VIEWS } from './scene-raster';export type { ComposedPart, ComposedSceneRasterResult } from './scene-raster';+export {+ GENERIC_DIAGNOSTIC_BUFFER_IDS,+ GENERIC_DIAGNOSTIC_CAMERAS,+ GENERIC_DIAGNOSTIC_REQUESTS,+ planDiagnosticViews,+ renderDiagnosticView,+ renderDiagnosticViews,+} from './diagnostic';+export {+ CHARACTER_MOTION_DIAGNOSTIC_PHASES,+ buildCharacterDiagnosticDescriptor,+ planCharacterDiagnosticRequests,+} from './character';+export type {+ CharacterDiagnosticDescriptorV1,+ CharacterDiagnosticEdgeV1,+ CharacterDiagnosticJointV1,+ CharacterDiagnosticRequestV1,+} from './character';+export {+ captureVehicleDiagnosticViews,+ createVehicleDiagnosticOverlay,+ describeVehicleDiagnostics,+} from './vehicle';+export type {+ VehicleCapturedDiagnosticV1,+ VehicleDiagnosticAxleV1,+ VehicleDiagnosticDescriptorV1,+ VehicleDiagnosticViewV1,+ VehicleDiagnosticWheelV1,+} from './vehicle';+export type {+ CategoryDiagnosticVariant,+ DiagnosticCameraSpec,+ DiagnosticOverlayRegion,+ DiagnosticRenderOptions,+ DiagnosticViewFrame,+ DiagnosticViewPlanV1,+ DiagnosticViewRequest,+ GenericDiagnosticBufferId,+} from './diagnostic';export {prepareClip,poseSceneAtTime,@@ -484,8 +537,12 @@ export async function renderInteriorGrid(const size = opts.size ?? 256;const labelScale = Math.max(2, Math.round(size / 80));- // Lift the roof once — persists for every cell.- const roofsHidden = hideNodeInScene(root, opts.nodeName ?? 'Roof');+ // Lift the roof once — persists for every cell. Explicit nodeName remains an+ // opt-in compatibility override; ordinary architecture views are semantic+ // first with a narrow historical-name fallback.+ const roofsHidden = opts.nodeName+ ? hideNodeInScene(root, opts.nodeName)+ : hideArchitectureRoofInScene(root).nodes.length;let wallsHidden = 0;const cells: Uint8Array[] = [];diff --git a/src/views/vehicle.ts b/src/views/vehicle.tsnew file mode 100644index 00000000..d3aa8865--- /dev/null+++ b/src/views/vehicle.ts@@ -0,0 +1,431 @@+/** Renderable vehicle diagnostic evidence without mutating the authored scene. */+import * as THREE from 'three';++import { readSemanticMetadataV1, stampSemanticMetadataV1, type AssetIntentV1 } from '../contracts';+import { resolveVehicleWheelAssemblies } from '../vehicle';+import {+ planDiagnosticViews,+ renderDiagnosticView,+ type DiagnosticOverlayRegion,+ type DiagnosticViewRequest,+} from './diagnostic';++export interface VehicleDiagnosticWheelV1 {+ id: string;+ center: [number, number, number];+ radius: number;+ width: number;+ axle: [number, number, number];+ loadBearing: boolean;+}++export interface VehicleDiagnosticAxleV1 {+ id: string;+ start: [number, number, number];+ end: [number, number, number];+}++export interface VehicleDiagnosticViewV1 {+ id: string;+ label: string;+ cameraDirection: [number, number, number];+ focus?: string;+}++export interface VehicleDiagnosticDescriptorV1 {+ schemaVersion: 1;+ forwardArrow: { start: [number, number, number]; end: [number, number, number] };+ chassisBox?: { min: [number, number, number]; max: [number, number, number] };+ axles: VehicleDiagnosticAxleV1[];+ wheels: VehicleDiagnosticWheelV1[];+ supportPlaneY?: number;+ views: VehicleDiagnosticViewV1[];+}++export interface VehicleCapturedDiagnosticV1 {+ id: string;+ label: string;+ cameraId: 'underside' | 'right';+ kind: 'underbody' | 'wheel-section';+ buffer: 'semantic-overlay';+ width: number;+ height: number;+ png: Buffer;+ regions: DiagnosticOverlayRegion[];+ /** Exact metric/axis evidence rendered into this capture. */+ descriptor: VehicleDiagnosticDescriptorV1;+}++const tuple = (value: THREE.Vector3): [number, number, number] => [value.x, value.y, value.z];++function hasRole(node: THREE.Object3D, prefix: string): boolean {+ return (+ readSemanticMetadataV1(node)?.roles.some(+ (role) => role === prefix || role.startsWith(`${prefix}.`),+ ) ?? false+ );+}++function chassisBounds(root: THREE.Object3D, inverse: THREE.Matrix4): THREE.Box3 | undefined {+ const bounds = new THREE.Box3();+ let found = false;+ root.traverse((node) => {+ if (!hasRole(node, 'chassis')) return;+ node.traverse((part) => {+ if (!(part instanceof THREE.Mesh) || !(part.geometry instanceof THREE.BufferGeometry)) return;+ part.geometry.computeBoundingBox();+ const box = part.geometry.boundingBox;+ if (!box) return;+ const matrix = inverse.clone().multiply(part.matrixWorld);+ for (const x of [box.min.x, box.max.x])+ for (const y of [box.min.y, box.max.y])+ for (const z of [box.min.z, box.max.z]) {+ bounds.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(matrix));+ found = true;+ }+ });+ });+ return found ? bounds : undefined;+}++/** Stable overlay/view descriptor in vehicle-root local meters. */+export function describeVehicleDiagnostics(root: THREE.Object3D): VehicleDiagnosticDescriptorV1 {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const assemblies = resolveVehicleWheelAssemblies(root);+ const wheels = assemblies.map((wheel) => ({+ id: wheel.id,+ center: tuple(wheel.centerWorld.clone().applyMatrix4(inverse)),+ radius: wheel.radius ?? 0,+ width: wheel.width ?? 0,+ axle: tuple(wheel.spinAxisWorld.clone().transformDirection(inverse)),+ loadBearing: wheel.loadBearing,+ }));+ const byAxle = new Map<string, VehicleDiagnosticWheelV1[]>();+ for (let index = 0; index < assemblies.length; index++) {+ const key = assemblies[index]!.index ?? assemblies[index]!.id;+ const group = byAxle.get(key) ?? [];+ group.push(wheels[index]!);+ byAxle.set(key, group);+ }+ const axles = [...byAxle].flatMap(([id, members]) => {+ if (members.length < 2) return [];+ const sorted = [...members].sort((a, b) => a.center[2] - b.center[2]);+ return [{ id, start: sorted[0]!.center, end: sorted.at(-1)!.center }];+ });+ const contacts = wheels+ .filter((wheel) => wheel.loadBearing && wheel.radius > 0)+ .map((wheel) => wheel.center[1] - wheel.radius);+ const supportPlaneY =+ contacts.length > 0+ ? contacts.reduce((sum, value) => sum + value, 0) / contacts.length+ : undefined;+ const chassis = chassisBounds(root, inverse);+ const views: VehicleDiagnosticViewV1[] = [+ { id: 'vehicle.front-direction', label: '+X front and chassis', cameraDirection: [1, 0.15, 0] },+ {+ id: 'vehicle.axles.top',+ label: 'Chassis and axle projection',+ cameraDirection: [0.001, 1, 0],+ },+ {+ id: 'vehicle.underbody',+ label: 'Underbody support plane',+ cameraDirection: [-0.3, -0.8, 0.5],+ },+ ...wheels.slice(0, 2).map((wheel) => ({+ id: `vehicle.wheel-section.${wheel.id.replace(/[^a-zA-Z0-9.-]/g, '-')}`,+ label: `Wheel section ${wheel.id}`,+ cameraDirection: [0, 0, wheel.center[2] < 0 ? -1 : 1] as [number, number, number],+ focus: wheel.id,+ })),+ ];+ return {+ schemaVersion: 1,+ forwardArrow: { start: [0, 0, 0], end: [1, 0, 0] },+ ...(chassis ? { chassisBox: { min: tuple(chassis.min), max: tuple(chassis.max) } } : {}),+ axles,+ wheels,+ ...(supportPlaneY !== undefined ? { supportPlaneY } : {}),+ views,+ };+}++function tagDiagnostic(node: THREE.Object3D, role: string): void {+ stampSemanticMetadataV1(node, { roles: [role] });+}++function rod(+ name: string,+ start: readonly [number, number, number],+ end: readonly [number, number, number],+ radius: number,+ color: number,+ role: string,+): THREE.Mesh {+ const from = new THREE.Vector3(...start);+ const to = new THREE.Vector3(...end);+ const direction = to.clone().sub(from);+ const length = direction.length();+ const geometry =+ length > 1e-9+ ? new THREE.CylinderGeometry(radius, radius, length, 8)+ : new THREE.SphereGeometry(radius, 8, 6);+ const result = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color }));+ result.name = name;+ result.position.copy(from).add(to).multiplyScalar(0.5);+ if (length > 1e-9) {+ result.quaternion.setFromUnitVectors(+ new THREE.Vector3(0, 1, 0),+ direction.multiplyScalar(1 / length),+ );+ }+ tagDiagnostic(result, role);+ return result;+}++/** A separate renderable overlay group; source visibility/transforms stay untouched. */+export function createVehicleDiagnosticOverlay(+ root: THREE.Object3D,+ descriptor = describeVehicleDiagnostics(root),+): THREE.Group {+ const overlay = new THREE.Group();+ overlay.name = 'VehicleDiagnosticOverlay';+ const chassisSpan = descriptor.chassisBox+ ? Math.max(+ descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0],+ descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1],+ descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2],+ )+ : 1;+ const thickness = Math.max(0.01, chassisSpan * 0.008);++ const arrow = new THREE.Group();+ arrow.name = 'Diagnostic_Forward_+X';+ tagDiagnostic(arrow, 'diagnostic.vehicle.forward');+ arrow.add(+ rod(+ 'Diagnostic_Forward_Shaft',+ descriptor.forwardArrow.start,+ [descriptor.forwardArrow.end[0] - 0.12, 0, 0],+ thickness,+ 0xff3344,+ 'diagnostic.vehicle.forward',+ ),+ );+ const arrowHead = new THREE.Mesh(+ new THREE.ConeGeometry(thickness * 3.2, 0.24, 10),+ new THREE.MeshBasicMaterial({ color: 0xff3344 }),+ );+ arrowHead.name = 'Diagnostic_Forward_Head';+ arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);+ arrowHead.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), new THREE.Vector3(1, 0, 0));+ tagDiagnostic(arrowHead, 'diagnostic.vehicle.forward');+ arrow.add(arrowHead);+ overlay.add(arrow);++ for (const axle of descriptor.axles) {+ overlay.add(+ rod(+ `Diagnostic_Axle_${axle.id}`,+ axle.start,+ axle.end,+ thickness,+ 0x33aaff,+ `diagnostic.vehicle.axle.${axle.id}`,+ ),+ );+ }+ for (const wheel of descriptor.wheels) {+ const ring = new THREE.Mesh(+ new THREE.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32),+ new THREE.MeshBasicMaterial({ color: 0xffcc33 }),+ );+ ring.name = `Diagnostic_Wheel_${wheel.id}`;+ ring.position.set(...wheel.center);+ const axle = new THREE.Vector3(...wheel.axle);+ if (axle.lengthSq() > 1e-12) {+ ring.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), axle.normalize());+ }+ tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);+ overlay.add(ring);+ }+ if (descriptor.chassisBox) {+ const chassis = new THREE.Group();+ chassis.name = 'Diagnostic_ChassisBox';+ tagDiagnostic(chassis, 'diagnostic.vehicle.chassis');+ const { min, max } = descriptor.chassisBox;+ const corners: Array<[number, number, number]> = [+ [min[0], min[1], min[2]],+ [max[0], min[1], min[2]],+ [max[0], max[1], min[2]],+ [min[0], max[1], min[2]],+ [min[0], min[1], max[2]],+ [max[0], min[1], max[2]],+ [max[0], max[1], max[2]],+ [min[0], max[1], max[2]],+ ];+ const edges = [+ [0, 1],+ [1, 2],+ [2, 3],+ [3, 0],+ [4, 5],+ [5, 6],+ [6, 7],+ [7, 4],+ [0, 4],+ [1, 5],+ [2, 6],+ [3, 7],+ ] as const;+ for (const [index, edge] of edges.entries()) {+ chassis.add(+ rod(+ `Diagnostic_ChassisEdge_${index}`,+ corners[edge[0]]!,+ corners[edge[1]]!,+ thickness,+ 0x55ff77,+ 'diagnostic.vehicle.chassis',+ ),+ );+ }+ overlay.add(chassis);+ }+ if (descriptor.supportPlaneY !== undefined) {+ const plane = new THREE.Group();+ plane.name = 'Diagnostic_SupportPlane';+ tagDiagnostic(plane, 'diagnostic.vehicle.support-plane');+ const halfX =+ Math.max(+ 1,+ ...(descriptor.chassisBox+ ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])]+ : []),+ ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius),+ ) + 0.2;+ const halfZ =+ Math.max(+ 0.8,+ ...(descriptor.chassisBox+ ? [Math.abs(descriptor.chassisBox.min[2]), Math.abs(descriptor.chassisBox.max[2])]+ : []),+ ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2),+ ) + 0.2;+ const y = descriptor.supportPlaneY;+ const planeLines: Array<[[number, number, number], [number, number, number]]> = [+ [+ [-halfX, y, -halfZ],+ [halfX, y, -halfZ],+ ],+ [+ [halfX, y, -halfZ],+ [halfX, y, halfZ],+ ],+ [+ [halfX, y, halfZ],+ [-halfX, y, halfZ],+ ],+ [+ [-halfX, y, halfZ],+ [-halfX, y, -halfZ],+ ],+ [+ [-halfX, y, 0],+ [halfX, y, 0],+ ],+ [+ [0, y, -halfZ],+ [0, y, halfZ],+ ],+ ];+ for (const [index, [start, end]] of planeLines.entries()) {+ plane.add(+ rod(+ `Diagnostic_SupportLine_${index}`,+ start,+ end,+ thickness * 0.7,+ 0x66ffff,+ 'diagnostic.vehicle.support-plane',+ ),+ );+ }+ overlay.add(plane);+ }+ return overlay;+}++function compositeForCapture(root: THREE.Object3D, overlay: THREE.Object3D): unknown {+ if (root.matrixAutoUpdate === false) {+ overlay.matrix.copy(root.matrix);+ overlay.matrixAutoUpdate = false;+ } else {+ overlay.position.copy(root.position);+ overlay.quaternion.copy(root.quaternion);+ overlay.scale.copy(root.scale);+ }+ return {+ name: 'VehicleDiagnosticCaptureRoot',+ type: 'Group',+ visible: true,+ position: { x: 0, y: 0, z: 0 },+ quaternion: { x: 0, y: 0, z: 0, w: 1 },+ scale: { x: 1, y: 1, z: 1 },+ children: [root, overlay],+ };+}++function selectWheelSectionRequest(+ requestValue: DiagnosticViewRequest,+ descriptor: VehicleDiagnosticDescriptorV1,+): DiagnosticViewRequest {+ const target =+ descriptor.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ??+ descriptor.wheels.find((wheel) => /right/i.test(wheel.id)) ??+ descriptor.wheels[0];+ if (!target?.id.startsWith('wheel.assembly.')) return requestValue;+ const suffix = target.id.replace(/[^a-zA-Z0-9.-]/g, '-');+ return {+ ...requestValue,+ id: `vehicle.wheel-section.${suffix}`,+ label: `Vehicle wheel section ${target.id}`,+ focusRolePrefixes: [target.id],+ };+}++/** Production capture for the exact final source scene. The source is only read; the+ * metric overlay is rendered through a detached sibling with the same local transform. */+export function captureVehicleDiagnosticViews(+ root: THREE.Object3D,+ intent: AssetIntentV1,+ size = 256,+): VehicleCapturedDiagnosticV1[] {+ if (intent.category !== 'vehicle') return [];+ const descriptor = describeVehicleDiagnostics(root);+ const overlay = createVehicleDiagnosticOverlay(root, descriptor);+ const composite = compositeForCapture(root, overlay);+ const requests = planDiagnosticViews(intent).extra.filter(+ (value) => value.variant === 'vehicle-underbody' || value.variant === 'vehicle-wheel-section',+ );+ return requests.map((baseRequest) => {+ const requestValue =+ baseRequest.variant === 'vehicle-wheel-section'+ ? selectWheelSectionRequest(baseRequest, descriptor)+ : baseRequest;+ const frame = renderDiagnosticView(composite, requestValue, { size });+ return {+ id: frame.id,+ label: frame.label,+ cameraId: frame.camera.id as 'underside' | 'right',+ kind: requestValue.variant === 'vehicle-underbody' ? 'underbody' : 'wheel-section',+ buffer: 'semantic-overlay',+ width: frame.width,+ height: frame.height,+ png: frame.png,+ regions: frame.regions,+ descriptor,+ };+ });+}