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.

test(core): expand kiln coverage to 60%+ on every file (W7.3)

Matt Kissinger5b3d594cce32
diff --git a/__tests__/primitives.test.ts b/__tests__/primitives.test.ts
new file mode 100644
index 00000000..f3e9237c
--- /dev/null
+++ b/__tests__/primitives.test.ts
@@ -0,0 +1,469 @@
+/**
+ * Primitive coverage tests (W7.3)
+ *
+ * Existence of these primitives is the entire substrate of the Kiln
+ * sandbox - the LLM is expected to call any of them. The render-only
+ * spike test only exercises a handful (boxGeo + gameMaterial), leaving
+ * most of primitives.ts uncovered. These tests call each primitive
+ * directly and assert real behavior:
+ * - return types are the expected Three.js classes
+ * - geometries produce non-zero positions / indices when applicable
+ * - materials carry through their option settings
+ * - animation track helpers produce KeyframeTrack instances with the
+ * right shape
+ * - the analysis helpers (countTriangles, countMaterials, getJointNames,
+ * validateAsset) compute correct numbers on a small built scene
+ */
+
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+
+import {
+ // construction
+ createRoot,
+ createPivot,
+ createPart,
+ // geometries
+ boxGeo,
+ sphereGeo,
+ cylinderGeo,
+ coneGeo,
+ capsuleGeo,
+ torusGeo,
+ planeGeo,
+ // materials
+ gameMaterial,
+ basicMaterial,
+ glassMaterial,
+ lambertMaterial,
+ // animation tracks
+ rotationTrack,
+ positionTrack,
+ scaleTrack,
+ createClip,
+ // animation patterns
+ idleBreathing,
+ bobbingAnimation,
+ spinAnimation,
+ // analysis
+ countTriangles,
+ countMaterials,
+ getJointNames,
+ validateAsset,
+ buildSandboxGlobals,
+} from '../primitives';
+
+// =============================================================================
+// Construction primitives
+// =============================================================================
+
+describe('createRoot / createPivot / createPart', () => {
+ test('createRoot returns a named Object3D', () => {
+ const root = createRoot('MyAsset');
+ expect(root).toBeInstanceOf(THREE.Object3D);
+ expect(root.name).toBe('MyAsset');
+ });
+
+ test('createPivot positions the joint and parents it', () => {
+ const root = createRoot('R');
+ const pivot = createPivot('Hip', [1, 2, 3], root);
+
+ expect(pivot.name).toBe('Joint_Hip');
+ expect(pivot.position.x).toBe(1);
+ expect(pivot.position.y).toBe(2);
+ expect(pivot.position.z).toBe(3);
+ expect(pivot.parent).toBe(root);
+ expect(root.children).toContain(pivot);
+ });
+
+ test('createPivot defaults position to origin and works without a parent', () => {
+ const orphan = createPivot('Lonely');
+ expect(orphan.position.x).toBe(0);
+ expect(orphan.position.y).toBe(0);
+ expect(orphan.position.z).toBe(0);
+ expect(orphan.parent).toBeNull();
+ });
+
+ test('createPart returns a Mesh by default and adds it to the parent', () => {
+ const root = createRoot('R');
+ const mesh = createPart('Body', boxGeo(1, 1, 1), gameMaterial(0xff0000), {
+ parent: root,
+ });
+
+ expect(mesh).toBeInstanceOf(THREE.Mesh);
+ expect(mesh.name).toBe('Mesh_Body');
+ expect(mesh.parent).toBe(root);
+ });
+
+ test('createPart applies position/rotation/scale options', () => {
+ const mesh = createPart('Cube', boxGeo(1, 1, 1), gameMaterial(0x00ff00), {
+ position: [1, 2, 3],
+ rotation: [90, 0, 45],
+ scale: [2, 1, 1],
+ });
+
+ expect(mesh.position.x).toBe(1);
+ expect(mesh.position.y).toBe(2);
+ expect(mesh.position.z).toBe(3);
+ // Rotation is converted from degrees to radians.
+ expect(mesh.rotation.x).toBeCloseTo(Math.PI / 2);
+ expect(mesh.rotation.z).toBeCloseTo(Math.PI / 4);
+ expect(mesh.scale.x).toBe(2);
+ });
+
+ test('createPart with pivot=true returns the wrapping pivot', () => {
+ const root = createRoot('R');
+ const wrapped = createPart('Door', boxGeo(1, 2, 0.1), gameMaterial(0x654321), {
+ pivot: true,
+ position: [0.5, 0, 0],
+ parent: root,
+ });
+
+ expect(wrapped.name).toBe('Joint_Door');
+ expect(wrapped.parent).toBe(root);
+ // The pivot should hold the offset; the inner mesh should be at origin.
+ expect(wrapped.position.x).toBe(0.5);
+ const child = wrapped.children[0] as THREE.Mesh;
+ expect(child).toBeInstanceOf(THREE.Mesh);
+ expect(child.position.x).toBe(0);
+ expect(child.name).toBe('Mesh_Door');
+ });
+});
+
+// =============================================================================
+// Geometry primitives
+// =============================================================================
+
+describe('geometry primitives produce real Three.js geometries', () => {
+ test('boxGeo', () => {
+ const g = boxGeo(1, 2, 3);
+ expect(g).toBeInstanceOf(THREE.BoxGeometry);
+ expect(g.getAttribute('position').count).toBeGreaterThan(0);
+ });
+
+ test('sphereGeo with default and custom segments', () => {
+ const def = sphereGeo(1);
+ expect(def).toBeInstanceOf(THREE.SphereGeometry);
+ const custom = sphereGeo(1, 16, 12);
+ expect(custom.parameters.widthSegments).toBe(16);
+ expect(custom.parameters.heightSegments).toBe(12);
+ });
+
+ test('cylinderGeo', () => {
+ const g = cylinderGeo(0.5, 0.5, 2, 12);
+ expect(g).toBeInstanceOf(THREE.CylinderGeometry);
+ expect(g.parameters.radialSegments).toBe(12);
+ });
+
+ test('coneGeo with default segments', () => {
+ const g = coneGeo(1, 2);
+ expect(g).toBeInstanceOf(THREE.ConeGeometry);
+ expect(g.parameters.radialSegments).toBe(8);
+ });
+
+ test('capsuleGeo with default segments', () => {
+ const g = capsuleGeo(0.5, 1);
+ expect(g).toBeInstanceOf(THREE.CapsuleGeometry);
+ expect(g.getAttribute('position').count).toBeGreaterThan(0);
+ });
+
+ test('torusGeo with custom segments', () => {
+ const g = torusGeo(1, 0.25, 16, 24);
+ expect(g).toBeInstanceOf(THREE.TorusGeometry);
+ expect(g.parameters.radialSegments).toBe(16);
+ expect(g.parameters.tubularSegments).toBe(24);
+ });
+
+ test('planeGeo', () => {
+ const g = planeGeo(2, 2);
+ expect(g).toBeInstanceOf(THREE.PlaneGeometry);
+ });
+});
+
+// =============================================================================
+// Materials
+// =============================================================================
+
+describe('materials carry option settings', () => {
+ test('gameMaterial defaults', () => {
+ const m = gameMaterial(0xff0000);
+ expect(m).toBeInstanceOf(THREE.MeshStandardMaterial);
+ expect(m.metalness).toBe(0);
+ expect(m.roughness).toBe(0.8);
+ expect(m.flatShading).toBe(true);
+ });
+
+ test('gameMaterial overrides applied', () => {
+ const m = gameMaterial('#00ff00', {
+ metalness: 0.5,
+ roughness: 0.2,
+ emissive: 0x111111,
+ emissiveIntensity: 2,
+ flatShading: false,
+ });
+ expect(m.metalness).toBe(0.5);
+ expect(m.roughness).toBe(0.2);
+ expect(m.emissiveIntensity).toBe(2);
+ expect(m.flatShading).toBe(false);
+ });
+
+ test('basicMaterial defaults and transparency override', () => {
+ const def = basicMaterial(0xffffff);
+ expect(def).toBeInstanceOf(THREE.MeshBasicMaterial);
+ expect(def.transparent).toBe(false);
+ expect(def.opacity).toBe(1);
+
+ const trans = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });
+ expect(trans.transparent).toBe(true);
+ expect(trans.opacity).toBe(0.5);
+ });
+
+ test('glassMaterial is transparent and double-sided', () => {
+ const m = glassMaterial(0x88ccff);
+ expect(m).toBeInstanceOf(THREE.MeshStandardMaterial);
+ expect(m.transparent).toBe(true);
+ expect(m.opacity).toBe(0.35);
+ expect(m.side).toBe(THREE.DoubleSide);
+ });
+
+ test('glassMaterial accepts custom options', () => {
+ const m = glassMaterial(0x88ccff, { opacity: 0.2, roughness: 0.5, metalness: 0.3 });
+ expect(m.opacity).toBe(0.2);
+ expect(m.roughness).toBe(0.5);
+ expect(m.metalness).toBe(0.3);
+ });
+
+ test('lambertMaterial defaults and overrides', () => {
+ const def = lambertMaterial(0xffffff);
+ expect(def).toBeInstanceOf(THREE.MeshLambertMaterial);
+ expect(def.flatShading).toBe(true);
+
+ const overridden = lambertMaterial(0xffffff, {
+ flatShading: false,
+ emissive: 0x222222,
+ });
+ expect(overridden.flatShading).toBe(false);
+ });
+});
+
+// =============================================================================
+// Animation track helpers
+// =============================================================================
+
+describe('keyframe track helpers', () => {
+ test('rotationTrack produces a QuaternionKeyframeTrack with 4 values per frame', () => {
+ const t = rotationTrack('Joint_X', [
+ { time: 0, rotation: [0, 0, 0] },
+ { time: 1, rotation: [90, 0, 0] },
+ ]);
+ expect(t).toBeInstanceOf(THREE.QuaternionKeyframeTrack);
+ expect(t.name).toBe('Joint_X.quaternion');
+ expect(t.times.length).toBe(2);
+ // 2 keyframes × 4 quaternion components.
+ expect(t.values.length).toBe(8);
+ });
+
+ test('positionTrack produces a VectorKeyframeTrack with 3 values per frame', () => {
+ const t = positionTrack('Joint_Y', [
+ { time: 0, position: [0, 0, 0] },
+ { time: 0.5, position: [1, 2, 3] },
+ ]);
+ expect(t).toBeInstanceOf(THREE.VectorKeyframeTrack);
+ expect(t.name).toBe('Joint_Y.position');
+ expect(t.values.length).toBe(6);
+ });
+
+ test('scaleTrack produces a VectorKeyframeTrack with 3 values per frame', () => {
+ const t = scaleTrack('Joint_Z', [
+ { time: 0, scale: [1, 1, 1] },
+ { time: 1, scale: [2, 2, 2] },
+ ]);
+ expect(t).toBeInstanceOf(THREE.VectorKeyframeTrack);
+ expect(t.name).toBe('Joint_Z.scale');
+ expect(t.values).toEqual(new Float32Array([1, 1, 1, 2, 2, 2]));
+ });
+
+ test('createClip wraps tracks in a named AnimationClip', () => {
+ const track = rotationTrack('Joint_X', [{ time: 0, rotation: [0, 0, 0] }]);
+ const clip = createClip('Wave', 1.5, [track]);
+ expect(clip).toBeInstanceOf(THREE.AnimationClip);
+ expect(clip.name).toBe('Wave');
+ expect(clip.duration).toBe(1.5);
+ expect(clip.tracks).toEqual([track]);
+ });
+});
+
+// =============================================================================
+// Animation patterns
+// =============================================================================
+
+describe('common animation patterns', () => {
+ test('idleBreathing produces a 3-keyframe positionTrack on the body joint', () => {
+ const clip = idleBreathing('Joint_Chest', 2, 0.05);
+ expect(clip.name).toBe('Idle');
+ expect(clip.duration).toBe(2);
+ expect(clip.tracks.length).toBe(1);
+ expect(clip.tracks[0]?.name).toBe('Joint_Chest.position');
+ // 3 keyframes × 3 components = 9.
+ expect(clip.tracks[0]?.values.length).toBe(9);
+ });
+
+ test('bobbingAnimation oscillates a root', () => {
+ const clip = bobbingAnimation('Floater', 1, 0.2);
+ expect(clip.name).toBe('Bob');
+ expect(clip.duration).toBe(1);
+ expect(clip.tracks[0]?.name).toBe('Floater.position');
+ });
+
+ test('spinAnimation defaults to Y axis', () => {
+ const clip = spinAnimation('Joint_Wheel');
+ expect(clip.name).toBe('Spin');
+ expect(clip.tracks.length).toBe(1);
+ expect(clip.tracks[0]?.name).toBe('Joint_Wheel.quaternion');
+ // 5 keyframes × 4 quaternion components.
+ expect(clip.tracks[0]?.values.length).toBe(20);
+ });
+
+ test('spinAnimation accepts an explicit axis', () => {
+ const xClip = spinAnimation('Joint_Wheel', 1, 'x');
+ const zClip = spinAnimation('Joint_Wheel', 1, 'z');
+ // We don't introspect quaternion contents; we just confirm both
+ // produce valid clips on the requested joint - meaning all three
+ // axis branches are taken.
+ expect(xClip.tracks[0]?.name).toBe('Joint_Wheel.quaternion');
+ expect(zClip.tracks[0]?.name).toBe('Joint_Wheel.quaternion');
+ });
+});
+
+// =============================================================================
+// Analysis helpers
+// =============================================================================
+
+describe('countTriangles / countMaterials / getJointNames', () => {
+ function buildScene(): THREE.Object3D {
+ const root = createRoot('Demo');
+ createPivot('Hip', [0, 0, 0], root);
+ createPart('Head', sphereGeo(0.3, 8, 6), gameMaterial(0xff0000), {
+ pivot: true,
+ parent: root,
+ });
+ createPart('Body', boxGeo(0.5, 1, 0.3), gameMaterial(0x00ff00), {
+ parent: root,
+ });
+ return root;
+ }
+
+ test('countTriangles counts both indexed and non-indexed geometry', () => {
+ const root = buildScene();
+ const tris = countTriangles(root);
+ // Box = 12 tris, sphere(8,6) ≈ 80 tris (indexed, poles share verts).
+ // The exact number depends on Three.js's primitive builder; we just
+ // need to confirm both indexed (sphere) and non-indexed paths are
+ // exercised and produce a reasonable total.
+ expect(tris).toBeGreaterThan(50);
+ expect(tris).toBeLessThan(200);
+ });
+
+ test('countTriangles handles a non-indexed geometry as well', () => {
+ const root = createRoot('R');
+ const geo = new THREE.BufferGeometry();
+ // A single triangle (3 verts, 9 floats), no index.
+ geo.setAttribute(
+ 'position',
+ new THREE.BufferAttribute(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), 3)
+ );
+ root.add(new THREE.Mesh(geo, gameMaterial(0x0)));
+ expect(countTriangles(root)).toBe(1);
+ });
+
+ test('countMaterials returns the number of unique materials in the scene', () => {
+ const root = buildScene();
+ expect(countMaterials(root)).toBe(2);
+ });
+
+ test('countMaterials handles arrays of materials per mesh', () => {
+ const root = createRoot('R');
+ const mesh = new THREE.Mesh(
+ boxGeo(1, 1, 1),
+ [gameMaterial(0xff0000), gameMaterial(0x00ff00)]
+ );
+ root.add(mesh);
+ expect(countMaterials(root)).toBe(2);
+ });
+
+ test('getJointNames returns every Joint_* in the tree', () => {
+ const root = buildScene();
+ const joints = getJointNames(root);
+ expect(joints).toContain('Joint_Hip');
+ expect(joints).toContain('Joint_Head');
+ expect(joints.length).toBe(2);
+ });
+});
+
+// =============================================================================
+// validateAsset advisory
+// =============================================================================
+
+describe('validateAsset advisories', () => {
+ test('returns valid=true with no warnings for a tiny prop', () => {
+ const root = createRoot('Tiny');
+ createPart('Body', boxGeo(1, 1, 1), gameMaterial(0xff0000), {
+ parent: root,
+ });
+ const r = validateAsset(root, 'prop');
+ expect(r.valid).toBe(true);
+ expect(r.warnings).toEqual([]);
+ expect(r.errors).toEqual([]);
+ });
+
+ test('warns when triangle budget is exceeded for the category', () => {
+ const root = createRoot('Heavy');
+ // A sphere(2, 64, 64) is ~8192 tris, blows the prop budget (3000).
+ createPart('Big', sphereGeo(2, 64, 64), gameMaterial(0x00ff00), {
+ parent: root,
+ });
+ const r = validateAsset(root, 'prop');
+ expect(r.valid).toBe(true);
+ expect(r.warnings.some((w) => w.startsWith('High triangle count'))).toBe(true);
+ });
+
+ test('warns when material budget is exceeded', () => {
+ const root = createRoot('ManyMats');
+ // 20 distinct materials; vfx category limit = 4.
+ for (let i = 0; i < 20; i++) {
+ createPart(`P${i}`, boxGeo(1, 1, 1), gameMaterial(i), { parent: root });
+ }
+ const r = validateAsset(root, 'vfx');
+ expect(r.warnings.some((w) => w.startsWith('High material count'))).toBe(true);
+ });
+
+ test('character / environment categories use their own budgets', () => {
+ // Drive both branches of the guidelines lookup.
+ const root = createRoot('R');
+ expect(validateAsset(root, 'character').valid).toBe(true);
+ expect(validateAsset(root, 'environment').valid).toBe(true);
+ });
+});
+
+// =============================================================================
+// Sandbox globals export
+// =============================================================================
+
+describe('buildSandboxGlobals', () => {
+ test('exposes every primitive the LLM is told it can use', () => {
+ const globals = buildSandboxGlobals();
+ const expected = [
+ 'createRoot', 'createPivot', 'createPart',
+ 'capsuleGeo', 'cylinderGeo', 'boxGeo', 'sphereGeo', 'coneGeo',
+ 'torusGeo', 'planeGeo',
+ 'gameMaterial', 'basicMaterial', 'glassMaterial', 'lambertMaterial',
+ 'rotationTrack', 'positionTrack', 'scaleTrack', 'createClip',
+ 'spinAnimation', 'bobbingAnimation', 'idleBreathing',
+ 'countTriangles', 'countMaterials', 'getJointNames', 'validateAsset',
+ 'Math', 'console',
+ ];
+ for (const name of expected) {
+ expect(globals[name]).toBeDefined();
+ }
+ });
+});
diff --git a/__tests__/prompt.test.ts b/__tests__/prompt.test.ts
new file mode 100644
index 00000000..07f8dd06
--- /dev/null
+++ b/__tests__/prompt.test.ts
@@ -0,0 +1,118 @@
+/**
+ * Prompt builder coverage (W7.3)
+ *
+ * `buildUserPrompt()` carries several conditional branches (style
+ * template, budget block, existing-code edit framing, no-animation
+ * flag) that weren't exercised by the spike test. `getSystemPrompt()`
+ * also has three modes - GLB, TSL, BOTH - and only one was hit before.
+ */
+
+import { describe, expect, test } from 'bun:test';
+
+import {
+ buildUserPrompt,
+ getSystemPrompt,
+ STYLE_TEMPLATES,
+ KILN_SYSTEM_PROMPT,
+ KILN_TSL_SYSTEM_PROMPT,
+ KILN_BOTH_SYSTEM_PROMPT,
+} from '../prompt';
+
+describe('getSystemPrompt', () => {
+ test('returns the GLB prompt for mode=glb', () => {
+ expect(getSystemPrompt('glb')).toBe(KILN_SYSTEM_PROMPT);
+ });
+
+ test('returns the TSL prompt for mode=tsl', () => {
+ expect(getSystemPrompt('tsl')).toBe(KILN_TSL_SYSTEM_PROMPT);
+ });
+
+ test('returns the combined prompt for mode=both', () => {
+ expect(getSystemPrompt('both')).toBe(KILN_BOTH_SYSTEM_PROMPT);
+ });
+});
+
+describe('STYLE_TEMPLATES', () => {
+ test('exposes a non-empty template for every supported style', () => {
+ for (const style of ['low-poly', 'stylized', 'voxel', 'detailed', 'realistic'] as const) {
+ expect(STYLE_TEMPLATES[style]).toBeDefined();
+ expect(STYLE_TEMPLATES[style].length).toBeGreaterThan(20);
+ }
+ });
+});
+
+describe('buildUserPrompt', () => {
+ test('includes the chosen style template at the top of the prompt', () => {
+ const prompt = buildUserPrompt({
+ prompt: 'thing',
+ mode: 'glb',
+ category: 'prop',
+ style: 'voxel',
+ });
+ expect(prompt).toContain(STYLE_TEMPLATES['voxel']);
+ // Style block must be before the task block.
+ expect(prompt.indexOf(STYLE_TEMPLATES['voxel'])).toBeLessThan(prompt.indexOf('## Task'));
+ });
+
+ test('emits budget constraints when budget is provided', () => {
+ const prompt = buildUserPrompt({
+ prompt: 'thing',
+ mode: 'glb',
+ category: 'prop',
+ budget: { maxTriangles: 1500, maxMaterials: 4 },
+ });
+ expect(prompt).toContain('## Constraints');
+ expect(prompt).toContain('Triangle budget: 1500');
+ expect(prompt).toContain('Material limit: 4');
+ });
+
+ test('skips budget block when no budget set', () => {
+ const prompt = buildUserPrompt({ prompt: 'p', mode: 'glb', category: 'prop' });
+ expect(prompt).not.toContain('## Constraints');
+ });
+
+ test('emits an Edit Request framing when existingCode is provided', () => {
+ const prompt = buildUserPrompt({
+ prompt: 'add a hat',
+ mode: 'glb',
+ category: 'character',
+ existingCode: 'const meta = {};',
+ });
+ expect(prompt).toContain('## Current Code');
+ expect(prompt).toContain('## Edit Request');
+ expect(prompt).toContain('add a hat');
+ expect(prompt).toContain('const meta = {};');
+ // No "Create a ..." framing when editing.
+ expect(prompt).not.toContain('## Task');
+ });
+
+ test('emits the standard Task framing when there is no existingCode', () => {
+ const prompt = buildUserPrompt({
+ prompt: 'red barrel',
+ mode: 'glb',
+ category: 'prop',
+ });
+ expect(prompt).toContain('## Task');
+ expect(prompt).toContain('Create a prop: red barrel');
+ });
+
+ test('emits the No Animation block when includeAnimation=false', () => {
+ const prompt = buildUserPrompt({
+ prompt: 'static prop',
+ mode: 'glb',
+ category: 'prop',
+ includeAnimation: false,
+ });
+ expect(prompt).toContain('## No Animation');
+ expect(prompt).not.toContain('Animation Requirements');
+ });
+
+ test('emits the Animation Requirements block by default', () => {
+ const prompt = buildUserPrompt({
+ prompt: 'animated prop',
+ mode: 'glb',
+ category: 'prop',
+ });
+ expect(prompt).toContain('## Animation Requirements');
+ });
+});
diff --git a/__tests__/render-edges.test.ts b/__tests__/render-edges.test.ts
new file mode 100644
index 00000000..94442231
--- /dev/null
+++ b/__tests__/render-edges.test.ts
@@ -0,0 +1,255 @@
+/**
+ * Render edge-cases (W7.3)
+ *
+ * The spike test covers the happy path for renderGLB with MeshStandard
+ * materials and quaternion tracks. This suite exercises the bits left
+ * uncovered: executeKilnCode guard clauses, Lambert/Basic material
+ * bridges, position/scale animation paths, missing target warnings,
+ * and the scale-track branch of inspectGeneratedAnimation.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { NodeIO } from '@gltf-transform/core';
+
+import {
+ executeKilnCode,
+ renderGLB,
+ inspectGeneratedAnimation,
+} from '../render';
+
+// =============================================================================
+// executeKilnCode guard clauses
+// =============================================================================
+
+describe('executeKilnCode input validation', () => {
+ test('throws on empty string', () => {
+ expect(() => executeKilnCode('')).toThrow(/non-empty string/);
+ });
+
+ test('throws when build is not defined at all', () => {
+ // The Function-constructor sandbox references `build` unconditionally
+ // in its return wrapper, so a missing declaration surfaces as a
+ // ReferenceError before the typeof check fires. Either failure
+ // mode is acceptable - the contract is "code without build() does
+ // not silently render".
+ expect(() =>
+ executeKilnCode(`const meta = { name: 'NoBuild' };`)
+ ).toThrow(/build is not defined|did not define `build`/);
+ });
+
+ test('throws when build is defined but is not a function', () => {
+ // This drives the explicit `typeof build !== 'function'` branch.
+ expect(() =>
+ executeKilnCode(`
+const meta = { name: 'NotFn' };
+const build = 'not a function';
+`)
+ ).toThrow(/did not define `build`/);
+ });
+
+ test('throws when build() does not return an Object3D', () => {
+ expect(() =>
+ executeKilnCode(`
+const meta = { name: 'BadReturn' };
+function build() { return 42; }
+`)
+ ).toThrow(/did not return a THREE.Object3D/);
+ });
+
+ test('normalizes CRLF line endings', () => {
+ const code = `\r\nconst meta = { name: 'CRLF' };\r\nfunction build() { return createRoot('CRLF'); }\r\n`;
+ const { meta, root } = executeKilnCode(code);
+ expect(meta.name).toBe('CRLF');
+ expect(root.name).toBe('CRLF');
+ });
+});
+
+// =============================================================================
+// Material bridges (Lambert + Basic)
+// =============================================================================
+
+describe('renderGLB with non-Standard materials', () => {
+ test('lambertMaterial is serialized into a valid GLB', async () => {
+ const code = `
+const meta = { name: 'Lambert' };
+function build() {
+ const root = createRoot('Lambert');
+ createPart('Body', boxGeo(1, 1, 1), lambertMaterial(0xff00ff, { emissive: 0x220011 }), {
+ parent: root,
+ });
+ return root;
+}
+`;
+ const r = await renderGLB(code);
+ expect(r.glb).toBeInstanceOf(Buffer);
+ expect(r.glb.byteLength).toBeGreaterThan(500);
+
+ const io = new NodeIO();
+ const doc = await io.readBinary(r.glb);
+ const mats = doc.getRoot().listMaterials();
+ expect(mats.length).toBe(1);
+ // Lambert maps to roughness=1, metallic=0 in the bridge.
+ expect(mats[0]?.getRoughnessFactor()).toBe(1);
+ expect(mats[0]?.getMetallicFactor()).toBe(0);
+ });
+
+ test('basicMaterial is serialized into a valid GLB', async () => {
+ const code = `
+const meta = { name: 'Basic' };
+function build() {
+ const root = createRoot('Basic');
+ createPart('Body', boxGeo(1, 1, 1), basicMaterial(0x00ffff, { transparent: true, opacity: 0.5 }), {
+ parent: root,
+ });
+ return root;
+}
+`;
+ const r = await renderGLB(code);
+ const io = new NodeIO();
+ const doc = await io.readBinary(r.glb);
+ const mats = doc.getRoot().listMaterials();
+ expect(mats.length).toBe(1);
+ expect(mats[0]?.getMetallicFactor()).toBe(0);
+ });
+
+ test('glassMaterial emits alphaMode=BLEND and doubleSided', async () => {
+ const code = `
+const meta = { name: 'Glass' };
+function build() {
+ const root = createRoot('Glass');
+ createPart('Pane', planeGeo(1, 1), glassMaterial(0x88ccff), { parent: root });
+ return root;
+}
+`;
+ const r = await renderGLB(code);
+ const io = new NodeIO();
+ const doc = await io.readBinary(r.glb);
+ const mat = doc.getRoot().listMaterials()[0];
+ expect(mat?.getAlphaMode()).toBe('BLEND');
+ expect(mat?.getDoubleSided()).toBe(true);
+ });
+});
+
+// =============================================================================
+// Animation track variants
+// =============================================================================
+
+describe('renderGLB animation track bridging', () => {
+ test('position tracks are written as translation channels', async () => {
+ const code = `
+const meta = { name: 'PosTrack' };
+function build() {
+ const root = createRoot('PosTrack');
+ createPivot('Body', [0, 0, 0], root);
+ return root;
+}
+function animate() {
+ return [createClip('Bob', 1, [
+ positionTrack('Joint_Body', [
+ { time: 0, position: [0, 0, 0] },
+ { time: 1, position: [0, 1, 0] },
+ ]),
+ ])];
+}
+`;
+ const r = await renderGLB(code);
+ expect(r.warnings).toEqual([]);
+
+ const io = new NodeIO();
+ const doc = await io.readBinary(r.glb);
+ const animation = doc.getRoot().listAnimations()[0];
+ expect(animation).toBeDefined();
+ const channel = animation?.listChannels()[0];
+ expect(channel?.getTargetPath()).toBe('translation');
+ });
+
+ test('scale tracks are written as scale channels', async () => {
+ const code = `
+const meta = { name: 'ScaleTrack' };
+function build() {
+ const root = createRoot('ScaleTrack');
+ createPivot('Body', [0, 0, 0], root);
+ return root;
+}
+function animate() {
+ return [createClip('Grow', 1, [
+ scaleTrack('Joint_Body', [
+ { time: 0, scale: [1, 1, 1] },
+ { time: 1, scale: [2, 2, 2] },
+ ]),
+ ])];
+}
+`;
+ const r = await renderGLB(code);
+ expect(r.warnings).toEqual([]);
+
+ const io = new NodeIO();
+ const doc = await io.readBinary(r.glb);
+ const channel = doc.getRoot().listAnimations()[0]?.listChannels()[0];
+ expect(channel?.getTargetPath()).toBe('scale');
+ });
+
+ test('warns (but does not fail) when an animation targets a missing joint', async () => {
+ const code = `
+const meta = { name: 'Missing' };
+function build() {
+ const root = createRoot('Missing');
+ createPivot('Body', [0, 0, 0], root);
+ return root;
+}
+function animate() {
+ return [createClip('Bad', 1, [
+ rotationTrack('Joint_DoesNotExist', [
+ { time: 0, rotation: [0, 0, 0] },
+ { time: 1, rotation: [30, 0, 0] },
+ ]),
+ ])];
+}
+`;
+ const r = await renderGLB(code);
+ // Still produces a GLB.
+ expect(r.glb).toBeInstanceOf(Buffer);
+ // But surfaces the warning both from inspectGeneratedAnimation and
+ // the bridge's own "target not found - skipped" path.
+ expect(r.warnings.some((w) => w.includes('Joint_DoesNotExist'))).toBe(true);
+ });
+});
+
+// =============================================================================
+// inspectGeneratedAnimation
+// =============================================================================
+
+describe('inspectGeneratedAnimation track validation', () => {
+ test('flags tracks whose name lacks a dot separator', () => {
+ const { root, clips } = executeKilnCode(`
+const meta = { name: 'R' };
+function build() { return createRoot('R'); }
+function animate() {
+ // Craft a track by hand so we can smuggle in a bad name.
+ const track = rotationTrack('Joint_X', [{ time: 0, rotation: [0, 0, 0] }]);
+ track.name = 'noSeparator'; // intentionally malformed
+ return [createClip('c', 1, [track])];
+}
+`);
+ const warnings = inspectGeneratedAnimation(root, clips);
+ expect(warnings.some((w) => w.includes('missing a node.property separator'))).toBe(true);
+ });
+
+ test('flags tracks using unsupported properties', () => {
+ const { root, clips } = executeKilnCode(`
+const meta = { name: 'R' };
+function build() {
+ const root = createRoot('R');
+ createPivot('Body', [0, 0, 0], root);
+ return root;
+}
+function animate() {
+ const track = rotationTrack('Joint_Body', [{ time: 0, rotation: [0, 0, 0] }]);
+ track.name = 'Joint_Body.unsupportedChannel';
+ return [createClip('c', 1, [track])];
+}
+`);
+ const warnings = inspectGeneratedAnimation(root, clips);
+ expect(warnings.some((w) => w.includes('unsupported property'))).toBe(true);
+ });
+});
diff --git a/__tests__/top-level-generate.test.ts b/__tests__/top-level-generate.test.ts
new file mode 100644
index 00000000..69ca1f86
--- /dev/null
+++ b/__tests__/top-level-generate.test.ts
@@ -0,0 +1,168 @@
+/**
+ * Top-level kiln.generate() coverage (W7.3)
+ *
+ * The promise-y end-to-end entry point in `kiln/index.ts` was uncovered:
+ * its zero-arg-spread happy path, its option pass-through to the
+ * underlying generator, and its hard-failure throw. Mocks the SDK so
+ * we can drive both branches without an LLM round-trip.
+ */
+
+import { describe, expect, test, mock, beforeEach } from 'bun:test';
+
+// Per-importer mock pattern, matching companions.test.ts. Each test gets
+// a fresh import of `../index` so the module-scoped mock state stays clean.
+let queryImpl = async function* (_args: unknown): AsyncGenerator<unknown> {
+ yield { type: 'result', subtype: 'success', result: '', session_id: 'test' };
+};
+
+mock.module('@anthropic-ai/claude-agent-sdk', () => ({
+ query: (args: unknown) => queryImpl(args),
+}));
+
+let counter = 0;
+let kiln: typeof import('../index');
+async function freshImport(): Promise<typeof import('../index')> {
+ counter += 1;
+ return (await import(`../index?top-level=${counter}`)) as typeof import('../index');
+}
+
+const VALID_CODE = `
+const meta = { name: 'TopLevel', category: 'prop' };
+function build() {
+ const root = createRoot('TopLevel');
+ createPart('Body', boxGeo(1, 1, 1), gameMaterial(0xff0000), { parent: root });
+ return root;
+}
+`;
+
+describe('kiln.generate() top-level pipeline', () => {
+ beforeEach(async () => {
+ queryImpl = async function* () {
+ yield {
+ type: 'result',
+ subtype: 'success',
+ structured_output: { code: VALID_CODE },
+ session_id: 'top-session',
+ };
+ };
+ kiln = await freshImport();
+ });
+
+ test('returns code + glb + meta + warnings for a valid response', async () => {
+ const out = await kiln.generate('a small red box');
+
+ expect(out.code).toContain('TopLevel');
+ expect(out.glb).toBeInstanceOf(Buffer);
+ expect(out.glb.byteLength).toBeGreaterThan(1000);
+ expect(out.meta.name).toBe('TopLevel');
+ expect(out.meta.category).toBe('prop');
+ expect(typeof out.meta.tris).toBe('number');
+ expect(Array.isArray(out.warnings)).toBe(true);
+ });
+
+ test('passes category, style, includeAnimation, model, timeoutMs through to the SDK', async () => {
+ let observedOptions:
+ | { abortController?: AbortController; model?: string; systemPrompt?: string }
+ | undefined;
+ let observedPrompt: string | undefined;
+ queryImpl = async function* (args: unknown) {
+ const a = args as {
+ prompt: string;
+ options?: { abortController?: AbortController; model?: string; systemPrompt?: string };
+ };
+ observedPrompt = a.prompt;
+ observedOptions = a.options;
+ yield {
+ type: 'result',
+ subtype: 'success',
+ structured_output: { code: VALID_CODE },
+ session_id: 's',
+ };
+ };
+ kiln = await freshImport();
+
+ await kiln.generate('a low-poly chest', {
+ category: 'prop',
+ style: 'low-poly',
+ includeAnimation: false,
+ model: 'claude-opus-4-7',
+ timeoutMs: 5000,
+ });
+
+ expect(observedOptions?.model).toBe('claude-opus-4-7');
+ expect(observedOptions?.abortController).toBeInstanceOf(AbortController);
+ // Style template lands in the prompt; "Do NOT include an animate()" too.
+ expect(observedPrompt).toContain('Low-Poly');
+ expect(observedPrompt).toContain('Do NOT include an animate()');
+ });
+
+ test('default category is prop and animation is requested by default', async () => {
+ let observedPrompt: string | undefined;
+ queryImpl = async function* (args: unknown) {
+ observedPrompt = (args as { prompt: string }).prompt;
+ yield {
+ type: 'result',
+ subtype: 'success',
+ structured_output: { code: VALID_CODE },
+ session_id: 's',
+ };
+ };
+ kiln = await freshImport();
+
+ await kiln.generate('a thing');
+ expect(observedPrompt).toContain('Create a prop');
+ expect(observedPrompt).toContain('Animation Requirements');
+ });
+
+ test('throws when SDK reports a failure', async () => {
+ queryImpl = async function* () {
+ yield {
+ type: 'result',
+ subtype: 'error_max_turns',
+ errors: ['ran out of turns'],
+ };
+ };
+ kiln = await freshImport();
+
+ await expect(kiln.generate('x')).rejects.toThrow(/Kiln code generation failed/);
+ });
+
+ test('throws when SDK reports auth failure', async () => {
+ queryImpl = async function* () {
+ yield { type: 'auth_status', error: 'invalid token' };
+ };
+ kiln = await freshImport();
+
+ await expect(kiln.generate('x')).rejects.toThrow(/Auth failed/);
+ });
+
+ test('throws when SDK loop yields nothing', async () => {
+ // Drives the "no result received from query" branch. Yielding once
+ // with an unrelated message type also reaches it (the for-await
+ // loop completes without ever seeing a `result`/`auth_status` event).
+ queryImpl = async function* () {
+ yield { type: 'system', subtype: 'init' };
+ };
+ kiln = await freshImport();
+
+ await expect(kiln.generate('x')).rejects.toThrow(/No result received/);
+ });
+
+ test('strips CLAUDECODE markers from the parent env before invoking the SDK', async () => {
+ process.env['CLAUDECODE'] = '1';
+ process.env['CLAUDE_CODE_ENTRYPOINT'] = 'cli';
+ queryImpl = async function* () {
+ // After strip, both env vars should be undefined inside the query.
+ expect(process.env['CLAUDECODE']).toBeUndefined();
+ expect(process.env['CLAUDE_CODE_ENTRYPOINT']).toBeUndefined();
+ yield {
+ type: 'result',
+ subtype: 'success',
+ structured_output: { code: VALID_CODE },
+ };
+ };
+ kiln = await freshImport();
+
+ await kiln.generate('x');
+ });
+});