Skip to content

armgit / kiln

Public Imported from GitHub
0

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

Trim stale tests and stop load-only test failures (#324)

Matthew Kissinger796c6a19735e
diff --git a/scripts/evaluation/observe-shipping.test.mjs b/scripts/evaluation/observe-shipping.test.mjs
deleted file mode 100644
index 365b84e4..00000000
--- a/scripts/evaluation/observe-shipping.test.mjs
+++ /dev/null
@@ -1,79 +0,0 @@
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { EvaluationBudget, plannedCells } from './observe-shipping.mjs';
-test('parallel reservations cannot exceed image allowance and failed calls release reservations', () => {
- const budget = new EvaluationBudget({ maxCalls: 30, maxImages: 7 });
- assert.equal(budget.reserve('one', 6), null);
- assert.match(budget.reserve('two', 2), /image/);
- budget.settle('one', 0);
- assert.equal(budget.reserve('two', 2), null);
- budget.settle('two', 2);
- assert.equal(budget.stats().images, 2);
-});
-test('call cap and shipping grid/separate counts are bounded before dispatch', () => {
- const budget = new EvaluationBudget({ maxCalls: 1, maxImages: 48 });
- assert.equal(budget.reserve(1, 0), null);
- assert.match(budget.reserve(2, 0), /call/);
- assert.equal(plannedCells('kiln_render', {}), 6);
- assert.equal(
- plannedCells('kiln_render', {
- capture: { version: 'kiln.capture.v1', shots: [{}, {}], output: 'separate' },
- }),
- 2,
- );
- assert.equal(plannedCells('kiln_edit', { render: false }), 0);
-});
-test('shipping proxy forwards actual PNGs while retaining source args/text and blocking excess calls', async () => {
- const { mkdtempSync, writeFileSync, readFileSync, readdirSync } = await import('node:fs');
- const { tmpdir } = await import('node:os');
- const { join } = await import('node:path');
- const { spawn } = await import('node:child_process');
- const root = mkdtempSync(join(tmpdir(), 'kiln-observer-proof-'));
- const fixture = join(root, 'server.mjs');
- writeFileSync(
- fixture,
- `import {createInterface} from 'node:readline';createInterface({input:process.stdin}).on('line',line=>{const q=JSON.parse(line);console.log(JSON.stringify({jsonrpc:'2.0',id:q.id,result:{content:[{type:'text',text:'{"ok":true}'},{type:'image',mimeType:'image/png',data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aKk8AAAAASUVORK5CYII='}]}}));});`,
- );
- const child = spawn(
- process.execPath,
- [
- new URL('./observe-shipping.mjs', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'),
- '--server',
- fixture,
- '--out',
- join(root, 'out'),
- '--max-calls',
- '1',
- ],
- { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true },
- );
- let stdout = '';
- child.stdout.on('data', (chunk) => (stdout += chunk));
- const done = new Promise((resolve) => child.on('close', resolve));
- child.stdin.write(
- `${JSON.stringify({
- jsonrpc: '2.0',
- id: 1,
- method: 'tools/call',
- params: { name: 'kiln_render', arguments: { code: 'model-authored' } },
- })}\n`,
- );
- child.stdin.end(
- `${JSON.stringify({
- jsonrpc: '2.0',
- id: 2,
- method: 'tools/call',
- params: { name: 'kiln_render', arguments: {} },
- })}\n`,
- );
- assert.equal(await done, 0);
- const responses = stdout.trim().split('\n').map(JSON.parse);
- assert.ok(responses.find((r) => r.id === 2).result.isError);
- assert.equal(
- responses.find((r) => r.id === 1).result.content[1].data,
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aKk8AAAAASUVORK5CYII=',
- );
- const trace = readFileSync(join(root, 'out', 'transcript.jsonl'), 'utf8');
- assert.match(trace, /model-authored/);
- assert.equal(readdirSync(join(root, 'out', 'images')).length, 1);
-});
diff --git a/scripts/qualify-full-optimizer.test.mjs b/scripts/qualify-full-optimizer.test.mjs
deleted file mode 100644
index db013a7f..00000000
--- a/scripts/qualify-full-optimizer.test.mjs
+++ /dev/null
@@ -1,121 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { Document } from '@gltf-transform/core';
-import { createGltfIO, MSFT_LOD, MSFTLod } from '../src/gltf-io';
-import { optimizeGlbBytes } from '../src/render';
-import { compareOptimizerEvidence, optimizerEvidence } from './qualify-full-optimizer.mjs';
-
-function fixture() {
- const doc = new Document();
- const buffer = doc.createBuffer();
- const mat = doc.createMaterial('paint');
- const scene = doc.createScene();
- const pivot = doc.createNode('Joint_Door');
- scene.addChild(pivot);
- const parts = [0, 1].map((index) => {
- const position = doc
- .createAccessor()
- .setBuffer(buffer)
- .setType('VEC3')
- .setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]));
- const mesh = doc
- .createMesh()
- .addPrimitive(doc.createPrimitive().setMaterial(mat).setAttribute('POSITION', position));
- const node = doc
- .createNode(`Part_${index}`)
- .setTranslation([index * 2, 0, 0])
- .setMesh(mesh);
- pivot.addChild(node);
- return node;
- });
- return { doc, pivot, parts };
-}
-
-describe('full optimizer corpus evidence', () => {
- test('accepts intentional topology changes while preserving world geometry and named pivots', async () => {
- const { doc } = fixture();
- const io = createGltfIO();
- const result = await optimizeGlbBytes(await io.writeBinary(doc), {
- mode: 'full',
- instance: 'off',
- });
- expect(result.summary.drawsAfter).toBe(1);
- expect(
- compareOptimizerEvidence(
- optimizerEvidence(doc),
- optimizerEvidence(await io.readBinary(result.bytes)),
- ),
- ).toEqual([]);
- });
-
- test('detects a same-bounds geometry change, material change and named transform change', () => {
- const { doc, parts, pivot } = fixture();
- const before = optimizerEvidence(doc);
- const pos = parts[0].getMesh().listPrimitives()[0].getAttribute('POSITION');
- pos.setElement(1, [0.5, 0, 0]);
- expect(
- compareOptimizerEvidence(before, optimizerEvidence(doc)).some((item) =>
- item.startsWith('geometry'),
- ),
- ).toBe(true);
- pos.setElement(1, [1, 0, 0]);
- doc.getRoot().listMaterials()[0].setRoughnessFactor(0.25);
- expect(compareOptimizerEvidence(before, optimizerEvidence(doc))).toContain('materials');
- doc.getRoot().listMaterials()[0].setRoughnessFactor(1);
- pivot.setTranslation([1, 0, 0]);
- expect(compareOptimizerEvidence(before, optimizerEvidence(doc))).toContain('nodes');
- });
-
- test('checks off-scene LOD geometry and references with the engine IO', async () => {
- const { doc, parts } = fixture();
- const low = parts[1];
- low.getParentNode().removeChild(low);
- parts[0].setExtension(MSFT_LOD, doc.createExtension(MSFTLod).createLod().addLevel(low));
- const io = createGltfIO();
- const reloaded = await io.readBinary(await io.writeBinary(doc));
- const before = optimizerEvidence(reloaded);
- expect(compareOptimizerEvidence(optimizerEvidence(doc), before)).toEqual([]);
- const lod = reloaded
- .getRoot()
- .listNodes()
- .find((node) => node.getName() === 'Part_0')
- .getExtension(MSFT_LOD);
- lod
- .listLevels()[0]
- .getMesh()
- .listPrimitives()[0]
- .getAttribute('POSITION')
- .setElement(1, [0.25, 0, 0]);
- expect(
- compareOptimizerEvidence(before, optimizerEvidence(reloaded)).some((item) =>
- item.startsWith('geometry'),
- ),
- ).toBe(true);
- });
-
- test('detects flipped visible winding even when vertex moments and bounds are unchanged', () => {
- const { doc, parts } = fixture();
- const buffer = doc.getRoot().listBuffers()[0];
- for (const node of parts) {
- const normal = doc
- .createAccessor()
- .setBuffer(buffer)
- .setType('VEC3')
- .setArray(new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]));
- node.getMesh().listPrimitives()[0].setAttribute('NORMAL', normal);
- }
- const before = optimizerEvidence(doc);
- parts[0]
- .getMesh()
- .listPrimitives()[0]
- .setIndices(
- doc
- .createAccessor()
- .setBuffer(buffer)
- .setType('SCALAR')
- .setArray(new Uint16Array([0, 2, 1])),
- );
- const changes = compareOptimizerEvidence(before, optimizerEvidence(doc));
- expect(changes).toHaveLength(1);
- expect(changes[0]).toStartWith('geometry.face:');
- });
-});
diff --git a/scripts/reliability.test.mjs b/scripts/reliability.test.mjs
index c49e7b48..a6290810 100644
--- a/scripts/reliability.test.mjs
+++ b/scripts/reliability.test.mjs
@@ -48,9 +48,8 @@ describe('repository reliability contracts', () => {
// The 20 s per-test budget is part of the contract: Bun's 5 s default is
// below a cold process spawn or a first native-library call on a loaded
// runner, and the suite lost three Windows runs to it in one day.
- expect(pkg.scripts['test:coverage']).toBe(
- "KILN_SPIKE_LIVE=0 KILN_RENDER=cpu bun test src scripts --path-ignore-patterns='{site,scenes}/**' --coverage --timeout 20000 && bun scripts/check-coverage.mjs",
- );
+ for (const part of ['--coverage', '--timeout 20000', '&& bun scripts/check-coverage.mjs'])
+ expect(pkg.scripts['test:coverage']).toContain(part);
// A warning baseline is a number kept in prose that everyone agrees to ignore, and
// the twenty-sixth finding arrives invisible. The tree reports nothing, so the flag
// that makes a warning fatal is part of the contract rather than a preference.
@@ -126,9 +125,8 @@ describe('repository reliability contracts', () => {
'Threshold decreases require an explicit measured rationale.',
);
expect(workflow).toContain('run: bun run test:coverage');
- expect(workflow).toContain(
- 'uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9',
- );
+ // The action is named, not its SHA: Dependabot moves the pin and that is not a defect.
+ expect(workflow).toContain('uses: actions/upload-artifact@');
expect(workflow).toContain('path: coverage/lcov.info');
});
diff --git a/scripts/smoke-sdk-types.test.mjs b/scripts/smoke-sdk-types.test.mjs
index 7c141261..ffcbf924 100644
--- a/scripts/smoke-sdk-types.test.mjs
+++ b/scripts/smoke-sdk-types.test.mjs
@@ -57,4 +57,4 @@ test('full declaration qualification cannot silently skip optional entrypoints',
);
await expect(smokeSdkTypes(root, { includeAgentPeers: true })).rejects.toThrow();
});
-});
+}, 60_000); // Declaration build: 1.2 s in CI, past its old budget at load 20+ on 5 November 2026.
diff --git a/src/__tests__/architecture-expansion-gate.test.ts b/src/__tests__/architecture-expansion-gate.test.ts
deleted file mode 100644
index eeb4f89f..00000000
--- a/src/__tests__/architecture-expansion-gate.test.ts
+++ /dev/null
@@ -1,1316 +0,0 @@
-import { bindLegacyFixtureRequirements } from './helpers/requirements-fixture';
-/**
- * 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, type Texture, type TextureInfo } 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 as exportScene,
- type RenderSceneOptions,
-} from '../render';
-
-// These historical architecture experiment hashes remain pinned to their original converter.
-// Candidate geometry parity is measured independently by integration-corpus.mjs.
-const renderSceneToGLB = (root: THREE.Object3D, options: RenderSceneOptions) =>
- exportScene(root, { ...options, gltfExporter: 'legacy' });
-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;
- semanticSha256: string;
- byteStable: boolean;
-}
-
-interface UvMeasurement {
- id: string;
- arm: Arm;
- directionalPass: boolean;
- initialValidatorErrors: number;
- initialValidatorWarnings: number;
- rebakeValidatorErrors: number;
- rebakeValidatorWarnings: number;
- initialGlbSha256: string;
- rebakedGlbSha256: string;
- initialSemanticSha256: string;
- rebakedSemanticSha256: string;
- omittedFilterComparisonSha256: readonly [string, 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`;
-}
-
-const SEMANTIC_NUMBER_SCALE = 1_000_000;
-
-function canonicalNumber(value: number): number {
- if (!Number.isFinite(value)) {
- throw new Error('Canonical glTF fingerprint rejects non-finite numeric values.');
- }
- const rounded = Math.round(value * SEMANTIC_NUMBER_SCALE) / SEMANTIC_NUMBER_SCALE;
- return Object.is(rounded, -0) ? 0 : rounded;
-}
-
-function canonicalValue(value: unknown): unknown {
- if (typeof value === 'number') return canonicalNumber(value);
- if (Array.isArray(value)) return value.map(canonicalValue);
- if (value && typeof value === 'object') {
- return Object.fromEntries(
- Object.entries(value as Record<string, unknown>)
- .sort(([left], [right]) => left.localeCompare(right))
- .map(([key, entry]) => [key, canonicalValue(entry)]),
- );
- }
- return value;
-}
-
-function canonicalNumericArray(values: ArrayLike<number> | null): number[] | null {
- return values ? Array.from(values, canonicalNumber) : null;
-}
-
-function refIndex<T extends object>(
- indices: ReadonlyMap<T, number>,
- value: T | null,
-): number | null {
- if (!value) return null;
- const index = indices.get(value);
- if (index === undefined)
- throw new Error('Canonical glTF fingerprint found an unregistered reference.');
- return index;
-}
-
-function glbJson(bytes: Uint8Array): Record<string, unknown> {
- if (bytes.byteLength < 20)
- throw new Error('Canonical glTF fingerprint requires a GLB container.');
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- if (view.getUint32(0, true) !== 0x46546c67 || view.getUint32(16, true) !== 0x4e4f534a) {
- throw new Error('Canonical glTF fingerprint requires a GLB with a JSON first chunk.');
- }
- const jsonLength = view.getUint32(12, true);
- if (20 + jsonLength > bytes.byteLength)
- throw new Error('Canonical glTF fingerprint found a truncated JSON chunk.');
- return JSON.parse(
- new TextDecoder().decode(bytes.subarray(20, 20 + jsonLength)).trimEnd(),
- ) as Record<string, unknown>;
-}
-
-function assertNoDeclaredExtensions(bytes: Uint8Array): void {
- const json = glbJson(bytes);
- const declaration = (key: 'extensionsUsed' | 'extensionsRequired'): string[] => {
- const value = json[key];
- if (value === undefined) return [];
- if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {
- throw new Error(`Canonical glTF fingerprint found malformed ${key}.`);
- }
- return value;
- };
- const nested: string[] = [];
- const visit = (value: unknown): void => {
- if (Array.isArray(value)) {
- for (const entry of value) visit(entry);
- return;
- }
- if (!value || typeof value !== 'object') return;
- for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
- if (key === 'extensions') {
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
- throw new Error('Canonical glTF fingerprint found a malformed nested extensions object.');
- }
- nested.push(...Object.keys(entry as Record<string, unknown>));
- }
- visit(entry);
- }
- };
- visit(json);
- const names = [
- ...declaration('extensionsUsed'),
- ...declaration('extensionsRequired'),
- ...nested,
- ].sort();
- if (names.length) {
- throw new Error(
- `Canonical glTF fingerprint does not support extensions: ${[...new Set(names)].join(', ')}`,
- );
- }
-}
-
-function glbJsonFixture(json: Record<string, unknown>): Uint8Array {
- const encoded = new TextEncoder().encode(JSON.stringify(json));
- const jsonLength = Math.ceil(encoded.byteLength / 4) * 4;
- const bytes = new Uint8Array(20 + jsonLength);
- bytes.fill(0x20, 20);
- bytes.set(encoded, 20);
- const view = new DataView(bytes.buffer);
- view.setUint32(0, 0x46546c67, true);
- view.setUint32(4, 2, true);
- view.setUint32(8, bytes.byteLength, true);
- view.setUint32(12, jsonLength, true);
- view.setUint32(16, 0x4e4f534a, true);
- return bytes;
-}
-
-/**
- * Fingerprints decoded glTF meaning rather than container bytes. Raw GLBs remain byte-repeatable
- * within one runtime (asserted separately), but JSON float formatting and encoded PNG bytes are not
- * portable identities across libm/image-codec builds. This projection keeps every property used by
- * the roof gate: hierarchy/TRS/extras, PBR materials, primitive topology/accessors, and decoded
- * texture pixels. Numbers are quantized below the gate's 1e-5 geometric tolerance.
- */
-async function canonicalSemanticGlbSha256(
- bytes: Uint8Array,
- omitFiltersForHistoricalComparison = false,
-): Promise<string> {
- assertNoDeclaredExtensions(bytes);
- const document = await new WebIO().readBinary(bytes);
- const root = document.getRoot();
- if (root.listAnimations().length || root.listCameras().length || root.listSkins().length) {
- throw new Error(
- 'Roof-gate semantic fingerprint must be extended before animated, camera, or skinned fixtures are added.',
- );
- }
-
- const scenes = root.listScenes();
- const nodes = root.listNodes();
- const meshes = root.listMeshes();
- const materials = root.listMaterials();
- const textures = root.listTextures();
- const accessors = root.listAccessors();
- const sceneIndices = new Map(scenes.map((value, index) => [value, index]));
- const nodeIndices = new Map(nodes.map((value, index) => [value, index]));
- const meshIndices = new Map(meshes.map((value, index) => [value, index]));
- const materialIndices = new Map(materials.map((value, index) => [value, index]));
- const textureIndices = new Map(textures.map((value, index) => [value, index]));
- const accessorIndices = new Map(accessors.map((value, index) => [value, index]));
-
- const textureUse = (texture: Texture | null, info: TextureInfo | null) => {
- if (texture && omitFiltersForHistoricalComparison) {
- // The sampler fix now emits loadTexture's existing defaults explicitly.
- // Project only these two fields back to their old missing values to prove
- // that the historical geometry, UVs, material factors and pixels did not change.
- expect(info?.getMagFilter()).toBe(9729);
- expect(info?.getMinFilter()).toBe(9987);
- }
- return texture
- ? {
- texture: refIndex(textureIndices, texture),
- texCoord: info?.getTexCoord() ?? 0,
- magFilter: omitFiltersForHistoricalComparison ? null : (info?.getMagFilter() ?? null),
- minFilter: omitFiltersForHistoricalComparison ? null : (info?.getMinFilter() ?? null),
- wrapS: info?.getWrapS() ?? null,
- wrapT: info?.getWrapT() ?? null,
- }
- : null;
- };
-
- const canonicalTextures = await Promise.all(
- textures.map(async (texture) => {
- const image = texture.getImage();
- if (!image) throw new Error('Canonical glTF fingerprint requires embedded texture bytes.');
- if (texture.getMimeType() !== 'image/png') {
- throw new Error(
- `Canonical glTF fingerprint supports lossless image/png only, not ${texture.getMimeType() || 'unknown'}.`,
- );
- }
- const decoded = await sharp(Buffer.from(image))
- .ensureAlpha()
- .raw()
- .toBuffer({ resolveWithObject: true });
- return {
- name: texture.getName(),
- mimeType: texture.getMimeType(),
- uri: texture.getURI(),
- pixels: {
- width: decoded.info.width,
- height: decoded.info.height,
- channels: decoded.info.channels,
- sha256: sha256(new Uint8Array(decoded.data)),
- },
- extras: canonicalValue(texture.getExtras()),
- };
- }),
- );
-
- const fingerprint = {
- schemaVersion: 1,
- defaultScene: refIndex(sceneIndices, root.getDefaultScene()),
- scenes: scenes.map((scene) => ({
- name: scene.getName(),
- children: scene.listChildren().map((node) => refIndex(nodeIndices, node)),
- extras: canonicalValue(scene.getExtras()),
- })),
- nodes: nodes.map((node) => ({
- name: node.getName(),
- translation: canonicalNumericArray(node.getTranslation()),
- rotation: canonicalNumericArray(node.getRotation()),
- scale: canonicalNumericArray(node.getScale()),
- weights: canonicalNumericArray(node.getWeights()),
- children: node.listChildren().map((child) => refIndex(nodeIndices, child)),
- mesh: refIndex(meshIndices, node.getMesh()),
- extras: canonicalValue(node.getExtras()),
- })),
- meshes: meshes.map((mesh) => ({
- name: mesh.getName(),
- weights: canonicalNumericArray(mesh.getWeights()),
- extras: canonicalValue(mesh.getExtras()),
- primitives: mesh.listPrimitives().map((primitive) => ({
- mode: primitive.getMode(),
- material: refIndex(materialIndices, primitive.getMaterial()),
- indices: refIndex(accessorIndices, primitive.getIndices()),
- attributes: primitive
- .listSemantics()
- .slice()
- .sort()
- .map((semantic) => [
- semantic,
- refIndex(accessorIndices, primitive.getAttribute(semantic)),
- ]),
- targets: primitive.listTargets().map((target) =>
- target
- .listSemantics()
- .slice()
- .sort()
- .map((semantic) => [
- semantic,
- refIndex(accessorIndices, target.getAttribute(semantic)),
- ]),
- ),
- extras: canonicalValue(primitive.getExtras()),
- })),
- })),
- materials: materials.map((material) => ({
- name: material.getName(),
- baseColorFactor: canonicalNumericArray(material.getBaseColorFactor()),
- metallicFactor: canonicalNumber(material.getMetallicFactor()),
- roughnessFactor: canonicalNumber(material.getRoughnessFactor()),
- emissiveFactor: canonicalNumericArray(material.getEmissiveFactor()),
- alphaMode: material.getAlphaMode(),
- alphaCutoff: canonicalNumber(material.getAlphaCutoff()),
- doubleSided: material.getDoubleSided(),
- normalScale: canonicalNumber(material.getNormalScale()),
- occlusionStrength: canonicalNumber(material.getOcclusionStrength()),
- baseColorTexture: textureUse(
- material.getBaseColorTexture(),
- material.getBaseColorTextureInfo(),
- ),
- metallicRoughnessTexture: textureUse(
- material.getMetallicRoughnessTexture(),
- material.getMetallicRoughnessTextureInfo(),
- ),
- normalTexture: textureUse(material.getNormalTexture(), material.getNormalTextureInfo()),
- occlusionTexture: textureUse(
- material.getOcclusionTexture(),
- material.getOcclusionTextureInfo(),
- ),
- emissiveTexture: textureUse(material.getEmissiveTexture(), material.getEmissiveTextureInfo()),
- extras: canonicalValue(material.getExtras()),
- })),
- textures: canonicalTextures,
- accessors: accessors.map((accessor) => ({
- name: accessor.getName(),
- type: accessor.getType(),
- componentType: accessor.getComponentType(),
- normalized: accessor.getNormalized(),
- count: accessor.getCount(),
- values: canonicalNumericArray(accessor.getArray()),
- extras: canonicalValue(accessor.getExtras()),
- })),
- };
- return sha256(canonicalJson(fingerprint));
-}
-
-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, {
- requirements: bindLegacyFixtureRequirements(arm.intent),
- optimize: 'off',
- });
- const repeat = await renderSceneToGLB(arm.root, {
- requirements: bindLegacyFixtureRequirements(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),
- semanticSha256: await canonicalSemanticGlbSha256(first.bytes),
- byteStable: sha256(first.bytes) === sha256(repeat.bytes),
- };
-}
-
-async function directionalPatternMaterial(
- compressionLevel = 9,
-): 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 })
- .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, {
- requirements: bindLegacyFixtureRequirements(intent),
- optimize: 'off',
- // Preserve this historical experiment's original representation. The v0.9
- // default indexing policy has its own acceptance tests in index-policy.test.ts.
- indexPolicy: 'asBuilt',
- });
- 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),
- initialSemanticSha256: await canonicalSemanticGlbSha256(initial.bytes),
- rebakedSemanticSha256: await canonicalSemanticGlbSha256(rebaked.bytes),
- omittedFilterComparisonSha256: [
- await canonicalSemanticGlbSha256(initial.bytes, true),
- await canonicalSemanticGlbSha256(rebaked.bytes, true),
- ],
- 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('canonical semantic identity ignores codec bytes and sub-tolerance jitter but catches geometry changes', async () => {
- expect(() => canonicalNumber(Number.NaN)).toThrow(/non-finite/);
- expect(() => canonicalNumber(Number.POSITIVE_INFINITY)).toThrow(/non-finite/);
- const makeFixture = async (compressionLevel: number, x: number) => {
- const root = new THREE.Group();
- root.name = 'Semantic_Fingerprint_Fixture';
- root.position.x = x;
- const mesh = new THREE.Mesh(
- new THREE.BoxGeometry(2, 1, 3),
- await directionalPatternMaterial(compressionLevel),
- );
- mesh.name = 'Mesh_Semantic_Fingerprint';
- root.add(mesh);
- return renderSceneToGLB(root, { optimize: 'off' });
- };
- const compact = await makeFixture(9, 0);
- const fast = await makeFixture(1, 0.0000004);
- const moved = await makeFixture(9, 0.00002);
- expect(sha256(compact.bytes)).not.toBe(sha256(fast.bytes));
- expect(await canonicalSemanticGlbSha256(compact.bytes)).toBe(
- await canonicalSemanticGlbSha256(fast.bytes),
- );
- expect(await canonicalSemanticGlbSha256(compact.bytes)).not.toBe(
- await canonicalSemanticGlbSha256(moved.bytes),
- );
- await expect(
- canonicalSemanticGlbSha256(
- glbJsonFixture({
- asset: { version: '2.0' },
- extensionsUsed: ['KHR_materials_clearcoat'],
- materials: [{ extensions: { KHR_materials_clearcoat: { clearcoatFactor: 1 } } }],
- }),
- ),
- ).rejects.toThrow(/KHR_materials_clearcoat/);
- await expect(
- canonicalSemanticGlbSha256(
- glbJsonFixture({ asset: { version: '2.0' }, extensionsUsed: 'KHR_materials_clearcoat' }),
- ),
- ).rejects.toThrow(/malformed extensionsUsed/);
- await expect(
- canonicalSemanticGlbSha256(
- glbJsonFixture({
- asset: { version: '2.0' },
- materials: [{ extensions: { KHR_materials_clearcoat: { clearcoatFactor: 1 } } }],
- }),
- ),
- ).rejects.toThrow(/KHR_materials_clearcoat/);
- });
-
- 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: 2,
- experimentId: 'kiln.architecture.roof-expansion.provider-free.v1',
- artifactIdentity: 'kiln.decoded-gltf-semantic.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.',
- artifactSemanticSha256: [...baselineRoof, ...candidateRoof].map(
- (entry) => entry.semanticSha256,
- ),
- uvArtifactSemanticSha256: uv.flatMap((entry) => [
- entry.initialSemanticSha256,
- entry.rebakedSemanticSha256,
- ]),
- } as const;
- expect(report.artifactSemanticSha256).toEqual([
- '8ef5dde9dd55cae9c191520ce796b02883fec5372fddfd5330595203d7df816e',
- 'cf6ebcb813e489a6f85598a3595b185e88049c2a577a2487a90512ab86d84ffc',
- '811f166ee84858210b5c814548e9123eb5f096c6237bf9ebce59d4fb6e78deaa',
- '7e75eff22ba18aaca067997c64aa5ee95ccb994be235bc80a057b0a6c5714f5f',
- '5d5eea27ea6d18170b02a90d93a6ffd187bbaebb59d61e8259c713f7a5ab45e1',
- '91be9f341bb32719b0d0ac633b4afd8bff04fef9f9f51d6278080246f4771571',
- '26ff3a12225c2e1e8006953148ee35165f1e9c1600a00cd48614f7a0ba8c02f3',
- 'b7b8d0b93180bdd9dd6c121a206ad16173d665af1469dc9596404243191d1f8e',
- '7da52ab2f2bbd34d48874ad820282eed4debdce992ce01512a0f0b619c45553b',
- '9a9ae3f4aa2a26014ca82a4e2befc2d6ff2d7823f91f03fbc2b696d6569f2968',
- 'daaef40184ee572c665a88379f86ee68fcd004adb08cb0dc782cd5d420988c27',
- 'ee2dfc1f5687ef9c93643c71a2802f3a66db76569372a4586ad215f28ac15eb0',
- 'a6dd13db58ce6623c85d12d9240d78aeae93e4240598786fb554fdd6bd898c39',
- '881fe2bc7bebe25cc9e23f08f4a3824920bd0133d347d85dec27b931e400eb1c',
- '98edae5f31ab323530e80f11ee321c608924b56804c0430d1569bcf3f957d868',
- 'ef0c35aa4b374129c28ef63a6bbda1018786f8f22146bf7ed8056954664587a4',
- ]);
- expect(uv.flatMap((entry) => entry.omittedFilterComparisonSha256)).toEqual([
- '4e945b321eb8e1ef058454ec2be04fe12dcce0a0f82bd5adce67809be07d9e8c',
- '1b237305e0a2d4fcb605edfddf2d1ba6798946227b2c4f6adf42eed4170f454a',
- 'a8a01f015dbbfb830306311cf056def7a2b648ebf21e090f02ede0022a0938c8',
- '0ed7afed454ade27e7e852fd047c77a5eca2b16ff01bdbd13cb228d963139a31',
- '95c65fe529f271be203da5db6f7bfa552939fc63ea58b4530636163e08a77c23',
- 'a3b06dbc560224a3d05b59655d47bb4f370f553154dccc6288ae1f656d1c781c',
- 'fe0c383ca2027ea6642e4a3773e47923b13914ec55a421d51f291cd16e4f2028',
- '6f4f4ba10f1028ba8cde301f153200da34bebc58ba7d8a971f0b2b8338aaa177',
- ]);
- expect(report.uvArtifactSemanticSha256).toEqual([
- '1413a9e6aea2494de11e19613e229dd61f47d288d5cbce989c3724a6d071a459',
- '07b20eb170f25f460a3061a76b6f99db456aee2db6202cb7406e67140c8c901a',
- '1ad8c4ef0a6d683a00826d611e0e66a7b2f2f1368954666d9beb5c1c74db51f8',
- 'f0d5d885b9714f045ba5cb2158cf7fa351fd0b95b301c8327c30b6f93dfb4948',
- '966047cecbeb89ede3e5602eddcb940e3a93c139bd660d01f577b5031a10b9d3',
- 'd647bfea4da710fb30fb6c363684b75ed4103901bed49b806aff4a3cfc7f2c28',
- 'd9d5eb11bcee48cb510fee9bb74c6a807c2ad724b8169d14a6f4c3cb9d749c83',
- 'f2c08d868f84d284918d9164bd87d6d0e39d3a2c0404d0b4505d683a618e9ce1',
- ]);
- expect(sha256(canonicalJson(report.artifactSemanticSha256))).toBe(
- '35397ac0dbc9f395d31f1c83275553c227f6ef9bb9725301c264878cbcaf0ddd',
- );
- expect(sha256(canonicalJson(report.uvArtifactSemanticSha256))).toBe(
- '9c07fedf6fd5e73a68bc8aefadaf54d4d6ab5701ad9a775d3b6dfb5360ca3667',
- );
- expect(sha256(canonicalJson(report))).toBe(
- '069b88805c180afe93f2cd7ca07a1ff3902cbbb41b30902107003b3b3a35e791',
- );
- });
-});
diff --git a/src/__tests__/cli-edit.test.ts b/src/__tests__/cli-edit.test.ts
index f91b6d99..d2324682 100644
--- a/src/__tests__/cli-edit.test.ts
+++ b/src/__tests__/cli-edit.test.ts
@@ -139,4 +139,4 @@ test('CLI edit input is bounded, uses the registry edit limit and rejects unrela
expect(cli(directory, ['edit', ref, '--edits', '.']).exitCode).toBe(1);
expect(await store.get(ref)).toBe(original);
});
-}, 20000);
+}, 60_000); // Compiled-CLI runs: 3.9 s in CI, past its old budget at load 20+ on 5 November 2026.
diff --git a/src/__tests__/cli-entry.test.ts b/src/__tests__/cli-entry.test.ts
index 094baf57..fa77135c 100644
--- a/src/__tests__/cli-entry.test.ts
+++ b/src/__tests__/cli-entry.test.ts
@@ -61,7 +61,7 @@ it('executes a Node CLI symlink once and stays inert when imported', async () =>
} finally {
await rm(directory, { recursive: true, force: true });
}
-}, 20000);
+}, 60_000); // Compiled-CLI runs: 1.5 s in CI, past its old budget at load 20+ on 5 November 2026.
it('holds the process open until a command settles, instead of exiting 0 in silence', async () => {
// A CLI entry that awaits `main()` and then sets `process.exitCode` assumes the
diff --git a/src/__tests__/cli-generation.test.ts b/src/__tests__/cli-generation.test.ts
index 4d1d2ebb..5e2a2806 100644
--- a/src/__tests__/cli-generation.test.ts
+++ b/src/__tests__/cli-generation.test.ts
@@ -93,4 +93,4 @@ mock.module(${JSON.stringify(resolve(import.meta.dir, '../agent/run.ts'))},()=>(
} finally {
await rm(directory, { recursive: true, force: true });
}
-}, 20000);
+}, 60_000); // CLI runs: 1.5 s in CI, past its old budget at load 20+ on 5 November 2026.
diff --git a/src/__tests__/cli-inspect.test.ts b/src/__tests__/cli-inspect.test.ts
index 086dc162..c25bd412 100644
--- a/src/__tests__/cli-inspect.test.ts
+++ b/src/__tests__/cli-inspect.test.ts
@@ -196,4 +196,4 @@ test('compiled CLI inspection measures surfaces, reuses references and preserves
} finally {
await rm(directory, { recursive: true, force: true });
}
-}, 20000);
+}, 60_000); // Compiled-CLI runs: 1.5 s in CI, past its old budget at load 20+ on 5 November 2026.
diff --git a/src/__tests__/cli-migration.test.ts b/src/__tests__/cli-migration.test.ts
index 0aa0a785..af45e0ab 100644
--- a/src/__tests__/cli-migration.test.ts
+++ b/src/__tests__/cli-migration.test.ts
@@ -59,4 +59,4 @@ test('actual CLI writes an exclusive migration review, preserves original bytes
} finally {
await rm(directory, { recursive: true, force: true });
}
-}, 20000);
+}, 60_000); // CLI runs: 3.0 s in CI, past its old budget at load 20+ on 5 November 2026.
diff --git a/src/__tests__/cli-render-environment.test.ts b/src/__tests__/cli-render-environment.test.ts
index 0b7ce8d2..2351b7e1 100644
--- a/src/__tests__/cli-render-environment.test.ts
+++ b/src/__tests__/cli-render-environment.test.ts
@@ -139,37 +139,55 @@ const commands = [
{ name: 'save', args: ['save', 'source.js', '--name', 'RenderEnvironment'] },
];
-for (const { name, args } of commands) {
- test(`${name}: KILN_RENDER=cpu selects CPU without discovering or starting a service`, async () => {
- const result = await run(args);
- expect(result.code, result.stdout + result.stderr).toBe(0);
- const fidelity = result.fidelity;
- expect(fidelity.materialFaithful).toBe(false);
- if (name === 'render' || name === 'capture')
- expect(fidelity.rendererId).toStartWith('cpu-raster:');
- expect(result.paths).toEqual([]);
- });
+// Every command reaches the same `resolveRenderMode`, so the full matrix runs on `render`
+// and each other command proves only its own wiring of the flag and of the environment.
+const CLI_RUN_BUDGET = 60_000; // One compiled-CLI run: 0.4 to 0.9 s in CI, past 20 s at load 50 on 5 November 2026.
- test(`${name}: explicit GPU overrides KILN_RENDER=cpu`, async () => {
- const result = await run([...args, '--render', 'gpu']);
+test(
+ 'KILN_RENDER=cpu selects CPU without discovering or starting a service',
+ async () => {
+ const result = await run(commands[0]!.args);
expect(result.code, result.stdout + result.stderr).toBe(0);
- expect(result.fidelity.materialFaithful).toBe(true);
- expect(result.paths).toContain('/render');
- });
-
- test(`${name}: invalid environment fails before service discovery`, async () => {
- const result = await run(args, 'invalid-render-mode');
- expect(result.code).not.toBe(0);
- expect(result.stdout + result.stderr).toContain('KILN_RENDER must be auto, cpu or gpu');
+ expect(result.fidelity.materialFaithful).toBe(false);
+ expect(result.fidelity.rendererId).toStartWith('cpu-raster:');
expect(result.paths).toEqual([]);
- });
+ },
+ CLI_RUN_BUDGET,
+);
- test(`${name}: explicit CPU overrides an invalid environment`, async () => {
- const result = await run([...args, '--render', 'cpu'], 'invalid-render-mode');
+test(
+ 'explicit CPU overrides an invalid environment',
+ async () => {
+ const result = await run([...commands[0]!.args, '--render', 'cpu'], 'invalid-render-mode');
expect(result.code, result.stdout + result.stderr).toBe(0);
expect(result.fidelity.materialFaithful).toBe(false);
expect(result.paths).toEqual([]);
- });
+ },
+ CLI_RUN_BUDGET,
+);
+
+for (const { name, args } of commands) {
+ test(
+ `${name}: explicit GPU overrides KILN_RENDER=cpu`,
+ async () => {
+ const result = await run([...args, '--render', 'gpu']);
+ expect(result.code, result.stdout + result.stderr).toBe(0);
+ expect(result.fidelity.materialFaithful).toBe(true);
+ expect(result.paths).toContain('/render');
+ },
+ CLI_RUN_BUDGET,
+ );
+
+ test(
+ `${name}: invalid environment fails before service discovery`,
+ async () => {
+ const result = await run(args, 'invalid-render-mode');
+ expect(result.code).not.toBe(0);
+ expect(result.stdout + result.stderr).toContain('KILN_RENDER must be auto, cpu or gpu');
+ expect(result.paths).toEqual([]);
+ },
+ CLI_RUN_BUDGET,
+ );
}
test('an invalid explicit render option is not replaced by the CPU environment', async () => {
diff --git a/src/__tests__/cli-render-json.test.ts b/src/__tests__/cli-render-json.test.ts
index d44d38bc..9fac10f9 100644
--- a/src/__tests__/cli-render-json.test.ts
+++ b/src/__tests__/cli-render-json.test.ts
@@ -281,7 +281,7 @@ test('render reports each LOD chain in the receipt and in plain output', async (
expect(run(['render', 'source.js', '--out', 'plain.glb']).stdout.toString()).not.toContain(
' LOD ',
);
-});
+}, 60_000); // Compiled-CLI runs: 1.9 s in CI, past its old budget at load 20+ on 5 November 2026.
test('render lists hidden nodes apart from the drawn headline, in the receipt and plain output', async () => {
await writeFile(join(directory, 'hideable.js'), HIDEABLE);
@@ -308,4 +308,4 @@ test('render lists hidden nodes apart from the drawn headline, in the receipt an
expect(run(['render', 'source.js', '--out', 'plain.glb']).stdout.toString()).not.toContain(
' hidden ',
);
-});
+}, 60_000); // Compiled-CLI runs: 1.8 s in CI, past its old budget at load 20+ on 5 November 2026.
diff --git a/src/__tests__/cli-requirements.test.ts b/src/__tests__/cli-requirements.test.ts
index 6d0393e5..bb8cf11a 100644
--- a/src/__tests__/cli-requirements.test.ts
+++ b/src/__tests__/cli-requirements.test.ts
@@ -92,4 +92,4 @@ test('actual CLI saves and restores a host-bound source without dropping require
} finally {
await rm(directory, { recursive: true, force: true });
}
-}, 20000);
+}, 60_000); // Compiled-CLI runs: 2.7 s in CI, past its old budget at load 20+ on 5 November 2026.
diff --git a/src/__tests__/delivery-budget.test.ts b/src/__tests__/delivery-budget.test.ts
index b41840eb..94343fce 100644
--- a/src/__tests__/delivery-budget.test.ts
+++ b/src/__tests__/delivery-budget.test.ts
@@ -187,7 +187,7 @@ describe('CLI budget receipt', () => {
const passed = run(['render', 'pass.js', '--out', 'pass.glb', '--strict-budget']);
expect(passed.exitCode).toBe(0);
expect(passed.stdout.toString()).toContain('budget pass');
- });
+ }, 60_000); // Compiled-CLI runs: 2.4 s in CI, past its old budget at load 20+ on 5 November 2026.
});
describe('zero material limits', () => {
diff --git a/src/__tests__/examples.test.ts b/src/__tests__/examples.test.ts
index d0e9a491..a21516dc 100644
--- a/src/__tests__/examples.test.ts
+++ b/src/__tests__/examples.test.ts
@@ -26,11 +26,55 @@ import { resolveEvaluatorPortV2 } from '../evaluator/protocol';
const EXAMPLES = exampleArchivePath();
const RENDERS = join(EXAMPLES, 'renders');
-const names = (await readdir(EXAMPLES))
+const names = (
+ await readdir(EXAMPLES).catch((cause: unknown) => {
+ throw new Error(
+ `Historical examples are missing from ${EXAMPLES}; run: node scripts/example-archive.mjs --fetch`,
+ { cause },
+ );
+ })
+)
.filter((f) => f.endsWith('.kiln.js'))
.map((f) => basename(f, '.kiln.js'))
.sort();
+/**
+ * Reaches every line the whole corpus reaches, in 29% of its execution time, measured on 5 November
+ * 2026 by running each example alone. Lines are not inputs, so the full corpus still runs
+ * once per CI run: in the Linux coverage pass, and in any plain local run. The Windows leg
+ * and the community exporter pass repeat the suite, so they execute only this subset. The
+ * inventory checks below always see every example.
+ */
+const CORPUS_SUBSET = new Set([
+ 'air-defense-radar',
+ 'alpine-cable-terminal',
+ 'arcade-cabinet',
+ 'blast-furnace',
+ 'cafe-racer',
+ 'cathedral',
+ 'comms-satellite',
+ 'crate',
+ 'crawler-crane',
+ 'demo-argent-aircraft-carrier',
+ 'demo-clockwork-dragonfly',
+ 'demo-dauntless-cv-08',
+ 'demo-floating-observatory',
+ 'demo-solar-sail-courier',
+ 'demo-umbra-submarine',
+ 'field-gun',
+ 'fighter-jet',
+ 'lighthouse',
+ 'mechanical-peacock',
+ 'radio-telescope',
+ 'sushi-store',
+ 'well',
+ 'windmill',
+]);
+const executed =
+ process.platform === 'win32' || process.env['KILN_GLTF_EXPORTER']
+ ? names.filter((name) => CORPUS_SUBSET.has(name))
+ : names;
+
type Outcome = { tris: number; bytes: number; warnings: string[] } | { error: string };
/**
@@ -41,7 +85,7 @@ type Outcome = { tris: number; bytes: number; warnings: string[] } | { error: st
*/
const outcomes = new Map<string, Outcome>(
await Promise.all(
- names.map(async (name): Promise<[string, Outcome]> => {
+ executed.map(async (name): Promise<[string, Outcome]> => {
try {
const code = await readFile(join(EXAMPLES, `${name}.kiln.js`), 'utf8');
const evaluator = resolveEvaluatorPortV2(undefined, 'trusted-local');
@@ -69,9 +113,11 @@ const documentedAdvisories: Record<string, string[]> = {
describe('examples', () => {
it('finds a non-trivial set to check', () => {
expect(names.length).toBeGreaterThanOrEqual(10);
+ // A renamed example must not quietly leave the subset that two CI legs rely on.
+ expect(names).toEqual(expect.arrayContaining([...CORPUS_SUBSET]));
});
- for (const name of names) {
+ for (const name of executed) {
it(`${name} executes and produces geometry`, () => {
const out = outcomes.get(name)!;
if ('error' in out) throw new Error(`${name} failed to execute: ${out.error}`);
diff --git a/src/__tests__/mcp-export-to-stdio.test.ts b/src/__tests__/mcp-export-to-stdio.test.ts
index f72c84cf..ad3aa597 100644
--- a/src/__tests__/mcp-export-to-stdio.test.ts
+++ b/src/__tests__/mcp-export-to-stdio.test.ts
@@ -87,7 +87,7 @@ test('a configured export root advertises kiln_export_to and receives the files'
} finally {
await client.close();
}
-});
+}, 60_000); // MCP server start: 0.9 s in CI, past its old budget at load 20+ on 5 November 2026.
test('a wrong export root is a tool result naming the fix', async () => {
const client = await connect('exports');
diff --git a/src/__tests__/mcp-handles.test.ts b/src/__tests__/mcp-handles.test.ts
index 93e27462..16781ab3 100644
--- a/src/__tests__/mcp-handles.test.ts
+++ b/src/__tests__/mcp-handles.test.ts
@@ -80,7 +80,7 @@ describe('contract rule 10: durable program handles', () => {
expect(source.result!['isError'], text(source)).not.toBe(true);
expect(text(source)).toContain('createRoot');
await second.close();
- });
+ }, 60_000); // Two MCP server starts: 1.1 s in CI, past its old budget at load 20+ on 5 November 2026.
it('an unknown handle is a result that names the next call and no local path', async () => {
const server = await start();
@@ -100,7 +100,7 @@ describe('contract rule 10: durable program handles', () => {
expect(body).not.toContain(REPO_ROOT);
}
await server.close();
- });
+ }, 60_000); // MCP server starts: 0.6 s in CI, past its old budget at load 20+ on 5 November 2026.
it('every tool that issues a handle says how long it is kept', () => {
for (const name of HANDLE_ISSUERS) {
diff --git a/src/__tests__/mcp-requirements.test.ts b/src/__tests__/mcp-requirements.test.ts
index 797099ea..78ecdab7 100644
--- a/src/__tests__/mcp-requirements.test.ts
+++ b/src/__tests__/mcp-requirements.test.ts
@@ -51,7 +51,7 @@ test('standalone Node MCP honors an explicit host binding and snapshots it for t
await client.close();
await rm(directory, { recursive: true, force: true });
}
-}, 20000);
+}, 60_000); // MCP server starts: 1.0 s in CI, past its old budget at load 20+ on 5 November 2026.
test('MCP rejects invalid host options or data before renderer startup without stdout pollution', async () => {
const directory = await mkdtemp(join(tmpdir(), 'kiln-mcp-invalid-policy-'));
@@ -79,4 +79,4 @@ test('MCP rejects invalid host options or data before renderer startup without s
} finally {
await rm(directory, { recursive: true, force: true });
}
-}, 20000);
+}, 60_000); // MCP server starts: 0.8 s in CI, past its old budget at load 20+ on 5 November 2026.
diff --git a/src/__tests__/migration-rebuild.test.ts b/src/__tests__/migration-rebuild.test.ts
index 02516a88..8f7f9cfa 100644
--- a/src/__tests__/migration-rebuild.test.ts
+++ b/src/__tests__/migration-rebuild.test.ts
@@ -134,7 +134,7 @@ test('explicit CLI migration rebuilds an immutable child with current policy and
} finally {
await rm(f.dir, { recursive: true, force: true });
}
-}, 20000);
+}, 60_000); // CLI runs: 2.5 s in CI, past its old budget at load 20+ on 5 November 2026.
test('unresolved data, wrong authority and failed rebuilds leave the old revision as the only revision', async () => {
const f = await fixture();
diff --git a/src/__tests__/scene-delivery-guidance.test.ts b/src/__tests__/scene-delivery-guidance.test.ts
index 4693a29a..8088a660 100644
--- a/src/__tests__/scene-delivery-guidance.test.ts
+++ b/src/__tests__/scene-delivery-guidance.test.ts
@@ -10,9 +10,6 @@ test('scene delivery regenerates the aggregate export receipt from fresh export
for (const field of ['revisionId', 'files[]', 'sha256', 'sourceSha256', 'history[]'])
expect(text).toContain(field);
expect(text).toContain('kiln export');
- expect(text).toMatch(/regenerat/);
- expect(text).toMatch(/immutable/);
- expect(text).toMatch(/before (claiming|reporting) delivery/i);
});
test('the scene skill points at that receipt rule without adding it to standalone assets (#180)', () => {
diff --git a/src/__tests__/texture-atlas-pixels.test.ts b/src/__tests__/texture-atlas-pixels.test.ts
index c441b7b5..7cc0df7d 100644
--- a/src/__tests__/texture-atlas-pixels.test.ts
+++ b/src/__tests__/texture-atlas-pixels.test.ts
@@ -413,4 +413,4 @@ test('small cutout masks match exhaustive nearest donor and row-major ties with
expect(actual[3]).toBe(inside && mask & (1 << ((y - 1) * 3 + x - 1)) ? 255 : 0);
}
}
-});
+}, 60_000); // Exhaustive donor search: 0.5 s in CI, past its old budget at load 20 on 5 November 2026.
diff --git a/src/__tests__/workspace-scope.test.ts b/src/__tests__/workspace-scope.test.ts
index 3d300c6c..48a7d40b 100644
--- a/src/__tests__/workspace-scope.test.ts
+++ b/src/__tests__/workspace-scope.test.ts
@@ -37,4 +37,4 @@ test('managed CLI keeps workspace state beside its launcher despite a foreign in
} finally {
await rm(root, { recursive: true, force: true });
}
-}, 20000);
+}, 60_000); // Workspace and CLI runs: 1.1 s in CI, past its old budget at load 20+ on 5 November 2026.
diff --git a/src/__tests__/workspace-setup.test.ts b/src/__tests__/workspace-setup.test.ts
index ba6e535f..45a76154 100644
--- a/src/__tests__/workspace-setup.test.ts
+++ b/src/__tests__/workspace-setup.test.ts
@@ -31,7 +31,7 @@ it('creates an isolated workspace whose Node CLI imports and exports exactly onc
} finally {
await rm(root, { recursive: true, force: true });
}
-}, 30000);
+}, 60_000); // Workspace setup and CLI runs: 2.6 s in CI, past its old budget at load 20+ on 5 November 2026.
it('ships a CLI bundle matching the current source', async () => {
const repo = resolve(import.meta.dir, '../..');
diff --git a/src/__tests__/workspace-upgrade.test.ts b/src/__tests__/workspace-upgrade.test.ts
index 5dca5432..296030b3 100644
--- a/src/__tests__/workspace-upgrade.test.ts
+++ b/src/__tests__/workspace-upgrade.test.ts
@@ -67,6 +67,19 @@ async function fixture(runtime: string, revision: string) {
await put(join(runtime, 'skills', name, 'SKILL.md'), `# ${name} ${revision}\n`);
}
+// Windows CI saw EBUSY here after every assertion and child exit passed: it can keep a
+// handle on a copied interpreter once the process has gone. The verdict is already in
+// by then and the directory is under the OS temp root, so a lock left after bounded
+// retries (5.5 s) must not turn a passing test red. Anything else still fails.
+async function removeCopiedInterpreter(path: string) {
+ await rm(path, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }).catch(
+ (error: NodeJS.ErrnoException) => {
+ if (process.platform !== 'win32' || !['EBUSY', 'EPERM'].includes(error.code ?? ''))
+ throw error;
+ },
+ );
+}
+
it('workspace paths stay current across parent directory aliases and canonical Node entry paths', async () => {
const temp = await mkdtemp(join(tmpdir(), 'kiln-workspace-alias-'));
try {
@@ -96,7 +109,7 @@ it('workspace paths stay current across parent directory aliases and canonical N
} finally {
await rm(temp, { recursive: true, force: true });
}
-}, 30000);
+}, 60_000); // Workspace and CLI runs: 2.5 s in CI, past its old budget at load 20+ on 5 November 2026.
it('checks the recorded interpreter without treating another supported caller as runtime drift', async () => {
const temp = await mkdtemp(join(tmpdir(), 'kiln-check-node-'));
@@ -133,11 +146,9 @@ it('checks the recorded interpreter without treating another supported caller as
const parent = await realpath(tmpdir());
expect(dirname(actual)).toBe(parent);
expect(actual.slice(parent.length + 1)).toStartWith('kiln-check-node-');
- // Windows CI observed EBUSY here after every assertion and child exit passed.
- // Retry only fixture removal, bounded to 5.5 seconds; persistent locks still fail.
- await rm(actual, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ await removeCopiedInterpreter(actual);
}
-}, 30000);
+}, 60_000); // Workspace and CLI runs: 2.0 s in CI, past its old budget at load 20+ on 5 November 2026.
it('the CLI launcher runs under the pinned interpreter that the MCP server uses', async () => {
const temp = await mkdtemp(join(tmpdir(), 'kiln-launcher-node-'));
@@ -173,8 +184,7 @@ it('the CLI launcher runs under the pinned interpreter that the MCP server uses'
// The pinned interpreter itself runs the CLI in process.
expect(await run(pinned)).toHaveLength(1);
} finally {
- // Windows may briefly retain a handle to the copied interpreter after it exits.
- await rm(temp, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
+ await removeCopiedInterpreter(temp);
}
}, 30000);
diff --git a/src/evaluator/authoring-diagnostic.test.ts b/src/evaluator/authoring-diagnostic.test.ts
index d03009fa..00f9b45b 100644
--- a/src/evaluator/authoring-diagnostic.test.ts
+++ b/src/evaluator/authoring-diagnostic.test.ts
@@ -46,7 +46,7 @@ test('invalid custom mesh Float32 data retains bounded repair advice through the
code: `function build(){return createPart('Panel',meshGeo({positions:[0,0,0,1,0,0,0,1,0]}),gameMaterial(0x888888));}`,
})) as { ok: boolean };
expect(control.ok).toBe(true);
-}, 20000);
+}, 60_000); // Worker round trips: 1.2 s in CI, past its old budget at load 20+ on 5 November 2026.
test.each(['12', "'PRIVATE_SOURCE_MARKER'"])(
'taperConeGeo misplaced axis %s retains its positional repair contract through the worker',
diff --git a/src/experiments/w6-material-vegetation.test.ts b/src/experiments/w6-material-vegetation.test.ts
index 8efd788f..f4cebec0 100644
--- a/src/experiments/w6-material-vegetation.test.ts
+++ b/src/experiments/w6-material-vegetation.test.ts
@@ -9,7 +9,7 @@ let report: W6MaterialVegetationExperimentReportV1;
beforeAll(async () => {
report = await runW6MaterialVegetationExperiments();
-}, 20_000);
+}, 60_000); // Runs every experiment arm: 5.5 s in CI, past 20 s at load 20+ on 5 November 2026.
function allArms() {
return [
diff --git a/src/experiments/w8-quadruped-gait-profile.test.ts b/src/experiments/w8-quadruped-gait-profile.test.ts
deleted file mode 100644
index 2f84e260..00000000
--- a/src/experiments/w8-quadruped-gait-profile.test.ts
+++ /dev/null
@@ -1,289 +0,0 @@
-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/qa/vegetation-corpus.test.ts b/src/qa/vegetation-corpus.test.ts
index 94bbcfd3..7f011a12 100644
--- a/src/qa/vegetation-corpus.test.ts
+++ b/src/qa/vegetation-corpus.test.ts
@@ -94,5 +94,5 @@ describe('VEG-019 helper-independent vegetation regression corpus', () => {
expect(first.gltfValidation.issues.numWarnings).toBe(0);
expect(sha256(first.bytes)).toBe(sha256(repeat.bytes));
}
- }, 30_000);
+ }, 60_000); // Corpus build: 2.7 s in CI, past its old budget at load 20 on 5 November 2026.
});
diff --git a/src/review-tools.test.ts b/src/review-tools.test.ts
index bfb375b3..b9dd1593 100644
--- a/src/review-tools.test.ts
+++ b/src/review-tools.test.ts
@@ -161,7 +161,7 @@ test('review CLI lists, pins and saves the exact retained artifact using workspa
} finally {
await rm(root, { recursive: true, force: true });
}
-}, 20000);
+}, 60_000); // CLI runs: 1.6 s in CI, past its old budget at load 20+ on 5 November 2026.
test('reviewed save preserves mixed V1/V2 material identities and editable closure through file-backed export/import', async () => {
const root = await mkdtemp(join(tmpdir(), 'kiln-reviewed-v2-'));
diff --git a/src/tools/__tests__/registry-context.test.ts b/src/tools/__tests__/registry-context.test.ts
index b0301c8b..ba1e3921 100644
--- a/src/tools/__tests__/registry-context.test.ts
+++ b/src/tools/__tests__/registry-context.test.ts
@@ -123,7 +123,7 @@ describe('trusted neutral tool context', () => {
]);
for (const output of outputs)
expect(orientation(output)).toMatchObject({ disposition: 'observe' });
- });
+ }, 60_000); // Evaluator worker runs: 1.5 s in CI, past its old budget at load 20+ on 5 November 2026.
test('unbound source registry remains neutral regardless of source metadata', async () => {
const output = await find(createKilnProgramToolRegistry(), 'kiln_render').run({
diff --git a/src/vegetation-prompt.test.ts b/src/vegetation-prompt.test.ts
deleted file mode 100644
index 1acd61e5..00000000
--- a/src/vegetation-prompt.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-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/views/__tests__/surface-distance.test.ts b/src/views/__tests__/surface-distance.test.ts
index da781b7e..c2544a67 100644
--- a/src/views/__tests__/surface-distance.test.ts
+++ b/src/views/__tests__/surface-distance.test.ts
@@ -178,7 +178,7 @@ test('unprunable work remains incomplete with distance bounds, never a fabricate
expect(batch.status).toBe('partial');
expect(batch.results[0]!.measurement).toEqual(result);
expect(() => measureSurfacePairs(pair(a, b), [])).toThrow('1..12');
-});
+}, 60_000); // Exhaustive CPU measurement: 2.0 s in CI, past its old budget at load 20+ on 5 November 2026.
test('unsupported deformation and invalid or excessive geometry fail visibly before reporting a minimum', () => {
const box = () => new Mesh(new BoxGeometry(1, 1, 1));