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.

feat(core): port kiln companion entries, add timeout + joint warnings

Matt Kissingerec546f7c5b5b
diff --git a/generate.ts b/generate.ts
index abe83c33..068e697f 100644
--- a/generate.ts
+++ b/generate.ts
@@ -1,10 +1,16 @@
/**
* Claude-backed Kiln code generator
*
- * Headless wrapper over the Claude Agent SDK that mirrors the server's
- * packages/server/src/services/claude.ts generateKilnCode path. Intentionally
- * duplicated for the core spike so there's no cross-package runtime dep.
- * W2 dedupes this with the server implementation.
+ * Headless wrapper over the Claude Agent SDK. Drives prompt -> code
+ * generation (via structured JSON output) and the companion refactor flows:
+ * - generateKilnCode — primary generate path with validate+retry
+ * - editKilnCode — generate with an `existingCode` edit target
+ * - compactCode — code-golf pass via Haiku
+ * - refactorCode — structured edit with geometry + effect targeting
+ *
+ * Replaces the duplicate implementation that previously lived in
+ * packages/server/src/services/claude.ts; the server now delegates to
+ * these entry points.
*/
import { query } from '@anthropic-ai/claude-agent-sdk';
@@ -33,6 +39,21 @@ export interface KilnGenerateResult {
error?: string;
}
+export interface RefactorRequest {
+ instruction: string;
+ geometryCode?: string;
+ effectCode?: string;
+ target: 'geometry' | 'effect' | 'both';
+}
+
+/** Per-call tunables for the Opus generate path. */
+export interface KilnGenerateCallOptions {
+ /** Abort milliseconds (default 720_000 = 12 min). */
+ timeoutMs?: number;
+ /** Override the model (default `claude-opus-4-7`). */
+ model?: string;
+}
+
const KILN_OUTPUT_SCHEMA = {
type: 'object',
properties: {
@@ -49,23 +70,56 @@ const KILN_OUTPUT_SCHEMA = {
required: ['code'],
};
+// =============================================================================
+// Defaults
+// =============================================================================
+
+// Claude Opus can take 2-5 minutes on coordinate-heavy prompts (guard
+// towers, vehicles) and has occasionally stretched past 8 min in testing.
+// Default 12 min gives the compound-prompt path breathing room.
+const DEFAULT_QUERY_TIMEOUT_MS = 720_000;
+
+/** The pinned Opus generation model. Bump in one place. */
+const DEFAULT_OPUS_MODEL = 'claude-opus-4-7';
+
+/** The pinned Haiku compaction model. */
+const DEFAULT_HAIKU_MODEL = 'claude-haiku-4-5-20251001';
+
+/**
+ * The `@anthropic-ai/claude-agent-sdk` spawns a nested Claude Code process
+ * and refuses to run when `CLAUDECODE` or `CLAUDE_CODE_ENTRYPOINT` are set
+ * in the parent env — which is exactly the case when anything in this repo
+ * is invoked from a Claude Code session (tests, subagents, manual dev).
+ *
+ * We strip them unconditionally before every SDK query so the kiln.*
+ * entry points "just work" regardless of how they're called. If a future
+ * consumer needs the markers preserved, they can set them again in their
+ * own child process.
+ */
+function stripClaudeCodeNestingMarkers(): void {
+ delete process.env['CLAUDECODE'];
+ delete process.env['CLAUDE_CODE_ENTRYPOINT'];
+}
+
// =============================================================================
// Public API
// =============================================================================
/**
- * Generate Kiln code (LLM only, no rendering). Mirrors the server's
- * generateKilnCode semantics: validates GLB output and retries once with
- * feedback if validation fails.
+ * Generate Kiln code (LLM only, no rendering). Validates GLB output and
+ * retries once with feedback if validation fails.
*/
export async function generateKilnCode(
- request: KilnGenerateRequest
+ request: KilnGenerateRequest,
+ opts: KilnGenerateCallOptions = {}
): Promise<KilnGenerateResult> {
+ stripClaudeCodeNestingMarkers();
+
try {
const userPrompt = buildUserPrompt(request);
const systemPrompt = getSystemPrompt(request.mode);
- const result = await runStructuredQuery(userPrompt, systemPrompt, request.mode);
+ const result = await runStructuredQuery(userPrompt, systemPrompt, request.mode, opts);
if (!result.success) return result;
@@ -73,7 +127,7 @@ export async function generateKilnCode(
if (result.code && request.mode !== 'tsl') {
const validation = validate(result.code);
if (!validation.valid) {
- return retryWithFeedback(request, result.code, validation.errors);
+ return retryWithFeedback(request, result.code, validation.errors, opts);
}
}
@@ -84,29 +138,217 @@ export async function generateKilnCode(
}
}
+/**
+ * Edit existing Kiln code with an instruction. Delegates to
+ * `generateKilnCode` with the existing code wired in as context.
+ */
+export async function editKilnCode(
+ currentCode: string,
+ editRequest: string,
+ mode: RenderMode = 'glb',
+ opts: KilnGenerateCallOptions = {}
+): Promise<KilnGenerateResult> {
+ return generateKilnCode(
+ {
+ prompt: editRequest,
+ mode,
+ category: 'prop',
+ existingCode: currentCode,
+ },
+ opts
+ );
+}
+
+/**
+ * Compact a bloated Kiln code string via Haiku.
+ * Code golf: minimize characters while producing identical visual output.
+ */
+export async function compactCode(
+ code: string,
+ opts: KilnGenerateCallOptions = {}
+): Promise<KilnGenerateResult> {
+ stripClaudeCodeNestingMarkers();
+
+ const abortController = new AbortController();
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS;
+ const timeout = setTimeout(() => abortController.abort(), timeoutMs);
+
+ try {
+ const q = query({
+ prompt: `Code golf this Three.js code - minimize characters while producing IDENTICAL visual output.
+
+- Shorten variable names
+- Remove whitespace and comments
+- Inline simple expressions
+- Reuse identical materials/geometries
+- Keep EXACT same visual result
+
+\`\`\`typescript
+${code}
+\`\`\`
+
+Output minified code only.`,
+ options: {
+ abortController,
+ model: opts.model ?? DEFAULT_HAIKU_MODEL,
+ maxTurns: 1,
+ permissionMode: 'bypassPermissions',
+ allowDangerouslySkipPermissions: true,
+ },
+ });
+
+ let result = '';
+ for await (const message of q) {
+ if (message.type === 'assistant' && message.message?.content) {
+ for (const block of message.message.content) {
+ if (block.type === 'text') {
+ result += block.text;
+ }
+ }
+ }
+ }
+
+ // Extract code from markdown fences if present
+ const codeMatch = result.match(/```(?:typescript|ts|javascript|js)?\n?([\s\S]*?)\n?```/);
+ if (codeMatch?.[1]) {
+ result = codeMatch[1];
+ }
+
+ return { success: true, code: result.trim() };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Unknown error';
+ return { success: false, error: message };
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
+/**
+ * Refactor existing code (geometry, effect, or both) against an instruction.
+ * Preserves asset character; structured output keeps the client's downstream
+ * rendering path stable.
+ */
+export async function refactorCode(
+ request: RefactorRequest,
+ opts: KilnGenerateCallOptions = {}
+): Promise<KilnGenerateResult> {
+ stripClaudeCodeNestingMarkers();
+
+ const abortController = new AbortController();
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS;
+ const timeout = setTimeout(() => abortController.abort(), timeoutMs);
+
+ try {
+ const codeContext: string[] = [];
+ if (request.geometryCode) {
+ codeContext.push(
+ `## Current Geometry Code\n\`\`\`typescript\n${request.geometryCode}\n\`\`\``
+ );
+ }
+ if (request.effectCode) {
+ codeContext.push(
+ `## Current Effect Code\n\`\`\`typescript\n${request.effectCode}\n\`\`\``
+ );
+ }
+
+ const outputInstructions =
+ request.target === 'both'
+ ? 'Update BOTH geometry and effect code'
+ : request.target === 'geometry'
+ ? 'Update only the geometry code'
+ : 'Update only the effect code';
+
+ const prompt = `${codeContext.join('\n\n')}
+
+## Refactor Instructions
+${request.instruction}
+
+## Task
+${outputInstructions}`;
+
+ const systemPrompt = `You are refactoring existing 3D asset code.
+Preserve the asset's character and style while applying the requested changes.
+Keep working code - only modify what's necessary for the refactor.`;
+
+ const q = query({
+ prompt,
+ options: {
+ abortController,
+ model: opts.model ?? DEFAULT_OPUS_MODEL,
+ systemPrompt,
+ maxTurns: 1,
+ outputFormat: {
+ type: 'json_schema',
+ schema: KILN_OUTPUT_SCHEMA,
+ },
+ permissionMode: 'bypassPermissions',
+ allowDangerouslySkipPermissions: true,
+ },
+ });
+
+ let sessionId: string | undefined;
+
+ for await (const message of q) {
+ if (message.type === 'result' && message.subtype === 'success') {
+ sessionId = message.session_id;
+ if (message.structured_output) {
+ const output = message.structured_output as {
+ code: string;
+ effectCode?: string;
+ };
+ return {
+ success: true,
+ code: output.code,
+ effectCode: output.effectCode,
+ sessionId,
+ };
+ }
+ return parseResultText(message.result, sessionId);
+ }
+ if (message.type === 'result' && message.subtype?.startsWith('error')) {
+ const errMsg = (message as Record<string, unknown>).errors;
+ return {
+ success: false,
+ error: Array.isArray(errMsg) ? errMsg.join('; ') : 'Refactor failed',
+ };
+ }
+ if (message.type === 'auth_status' && message.error) {
+ return {
+ success: false,
+ error: `Auth failed: ${message.error}. Run "claude auth login".`,
+ };
+ }
+ }
+
+ return { success: false, error: 'No result received from refactor query' };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Unknown error';
+ return { success: false, error: message };
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
// =============================================================================
// Internal
// =============================================================================
-// Claude Opus can take 2-5 minutes on coordinate-heavy prompts (guard
-// towers, vehicles) and has occasionally stretched past 8 min in testing.
-// Default 12 min gives the compound-prompt path breathing room.
-const DEFAULT_QUERY_TIMEOUT_MS = 720_000;
-
async function runStructuredQuery(
userPrompt: string,
systemPrompt: string,
- _mode: RenderMode
+ _mode: RenderMode,
+ opts: KilnGenerateCallOptions
): Promise<KilnGenerateResult> {
const abortController = new AbortController();
- const timeout = setTimeout(() => abortController.abort(), DEFAULT_QUERY_TIMEOUT_MS);
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS;
+ const timeout = setTimeout(() => abortController.abort(), timeoutMs);
try {
const q = query({
prompt: userPrompt,
options: {
abortController,
- model: 'claude-opus-4-6',
+ model: opts.model ?? DEFAULT_OPUS_MODEL,
systemPrompt,
maxTurns: 3,
outputFormat: {
@@ -155,7 +397,8 @@ async function runStructuredQuery(
async function retryWithFeedback(
request: KilnGenerateRequest,
failedCode: string,
- errors: string[]
+ errors: string[],
+ opts: KilnGenerateCallOptions
): Promise<KilnGenerateResult> {
const retryPrompt = `Previous attempt had validation errors:
${errors.map((e) => `- ${e}`).join('\n')}
@@ -170,7 +413,7 @@ Fix these issues and regenerate. Remember: NO imports, NO exports, use rotation:
const systemPrompt = getSystemPrompt(request.mode);
try {
- return await runStructuredQuery(retryPrompt, systemPrompt, request.mode);
+ return await runStructuredQuery(retryPrompt, systemPrompt, request.mode, opts);
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
return { success: false, error: `Retry failed: ${message}` };
diff --git a/index.ts b/index.ts
index 02a24cac..b23b1419 100644
--- a/index.ts
+++ b/index.ts
@@ -12,14 +12,30 @@ import type { KilnCodeMeta } from './render';
import { renderGLB } from './render';
import { generateKilnCode } from './generate';
-export { renderGLB } from './render';
-export { generateKilnCode } from './generate';
+export { renderGLB, inspectGeneratedAnimation } from './render';
+export {
+ generateKilnCode,
+ editKilnCode,
+ compactCode,
+ refactorCode,
+ // Companion aliases on the namespace for agent ergonomics:
+ editKilnCode as editCode,
+ compactCode as compact,
+ refactorCode as refactor,
+} from './generate';
+export type {
+ RefactorRequest,
+ KilnGenerateResult,
+ KilnGenerateCallOptions,
+} from './generate';
export { validate, validateKilnCode } from './validation';
export {
buildUserPrompt,
getSystemPrompt,
STYLE_TEMPLATES,
KILN_SYSTEM_PROMPT,
+ KILN_TSL_SYSTEM_PROMPT,
+ KILN_BOTH_SYSTEM_PROMPT,
type KilnGenerateRequest,
type RenderMode,
type AssetCategory,
@@ -27,7 +43,6 @@ export {
type AssetBudget,
} from './prompt';
export type { KilnCodeMeta, RenderResult, ExecutedKilnCode } from './render';
-export type { KilnGenerateResult } from './generate';
export { executeKilnCode } from './render';
export {
buildSandboxGlobals,
@@ -74,6 +89,13 @@ export interface KilnGenerateOptions {
* match the server's behavior.
*/
includeAnimation?: boolean;
+ /**
+ * Abort milliseconds for the underlying SDK query. Defaults to 720_000
+ * (12 min) to fit Opus variance on coordinate-heavy prompts.
+ */
+ timeoutMs?: number;
+ /** Override the Claude model id used for generation. */
+ model?: string;
}
export interface KilnGenerateOutput {
@@ -99,14 +121,20 @@ export async function generate(
): Promise<KilnGenerateOutput> {
const category = opts.category ?? 'prop';
- const genResult = await generateKilnCode({
- prompt,
- mode: 'glb',
- category,
- style: opts.style,
- includeAnimation: opts.includeAnimation ?? true,
- referenceImageUrl: opts.referenceImageUrl,
- });
+ const genResult = await generateKilnCode(
+ {
+ prompt,
+ mode: 'glb',
+ category,
+ style: opts.style,
+ includeAnimation: opts.includeAnimation ?? true,
+ referenceImageUrl: opts.referenceImageUrl,
+ },
+ {
+ timeoutMs: opts.timeoutMs,
+ model: opts.model,
+ }
+ );
if (!genResult.success || !genResult.code) {
throw new Error(`Kiln code generation failed: ${genResult.error ?? 'unknown error'}`);
diff --git a/prompt.ts b/prompt.ts
index 0d73c873..e8b73667 100644
--- a/prompt.ts
+++ b/prompt.ts
@@ -1,12 +1,10 @@
/**
* Kiln System Prompts & User Prompt Builders
*
- * Copied from packages/shared/kiln-prompts.ts for the core spike so the
- * headless pipeline has no run-time dependency on the shared package's
- * prompt content. Duplication is intentional - W2 will dedupe once the
- * editor migration lands.
- *
- * Local types mirror @pixel-forge/shared api-types so we stay additive.
+ * Canonical source in @pixel-forge/core. Was previously duplicated in
+ * `packages/shared/kiln-prompts.ts`; that file has been retired in favor of
+ * this one. Server imports via `@pixel-forge/core/kiln` (the route wrapper
+ * re-exports through `services/claude`).
*/
export type RenderMode = 'glb' | 'tsl' | 'both';
@@ -65,7 +63,7 @@ Generate assets with realistic proportions and detail:
};
// =============================================================================
-// System Prompt (GLB mode - spike only cares about this)
+// System Prompts
// =============================================================================
export const KILN_SYSTEM_PROMPT = `You are an expert procedural 3D asset generator. Create game-ready models with character and style.
@@ -195,10 +193,199 @@ function animate(root) {
}
</example>`;
+export const KILN_TSL_SYSTEM_PROMPT = `You are an expert shader artist. Create stunning real-time visual effects using Three.js TSL.
+
+<file-format>
+import { MeshStandardNodeMaterial } from 'three/webgpu';
+import { color, float, vec3, time, positionWorld, normalWorld, cameraPosition, Fn } from 'three/tsl';
+
+const material = new MeshStandardNodeMaterial();
+
+// Configure shader nodes
+material.colorNode = ...;
+material.emissiveNode = ...;
+material.opacityNode = ...;
+
+export { material };
+</file-format>
+
+<api>
+// Types
+float(n), vec2(x,y), vec3(x,y,z), vec4(x,y,z,w), color(0xhex)
+
+// Geometry inputs
+positionLocal, positionWorld, normalLocal, normalWorld, uv()
+cameraPosition, time, deltaTime
+
+// Operations (method chaining)
+.add(n), .sub(n), .mul(n), .div(n)
+.sin(), .cos(), .abs(), .pow(n), .sqrt()
+.dot(v), .cross(v), .normalize(), .length()
+.mix(a,b), .smoothstep(min,max), .clamp(min,max), .saturate()
+.oneMinus() // = 1.0 - x
+
+// Functions
+Fn(() => { return nodeExpression; }) // Define reusable shader function
+
+// Material properties
+material.colorNode, material.emissiveNode, material.opacityNode
+material.metalnessNode, material.roughnessNode
+material.normalNode, material.positionNode
+</api>
+
+<patterns>
+// Fresnel (rim glow)
+const fresnel = cameraPosition.sub(positionWorld).normalize().dot(normalWorld).abs().oneMinus().pow(3);
+
+// Pulse
+const pulse = time.mul(2).sin().mul(0.5).add(0.5);
+
+// Color gradient by height
+const gradient = positionLocal.y.smoothstep(-1, 1);
+</patterns>
+
+<quality>
+- Effects should enhance the geometry, not overpower it
+- Use subtle animations (avoid jarring flashes)
+- Combine multiple effects (fresnel + pulse + gradient)
+- Colors should complement the base geometry
+</quality>
+
+<rules>
+- Method chaining: time.mul(2).sin() NOT sin(time * 2)
+- Always export { material }
+- Output ONLY valid JavaScript code
+</rules>
+
+## TSL Basics
+
+### Method Chaining (not operators)
+\`\`\`javascript
+// GLSL: sin(time * 2.0) * 0.5 + 0.5
+// TSL:
+time.mul(2.0).sin().mul(0.5).add(0.5)
+\`\`\`
+
+### Core Types
+\`\`\`javascript
+float(1.0) // Scalar
+vec2(x, y) // 2D vector
+vec3(x, y, z) // 3D vector
+color(0xff0000) // RGB from hex
+\`\`\`
+
+### Geometry Nodes
+\`\`\`javascript
+positionLocal // Model space position
+positionWorld // World space position
+normalWorld // World space normal
+cameraPosition // Camera world position
+uv() // UV coordinates
+time // Seconds since start
+\`\`\`
+
+### Material Properties
+\`\`\`javascript
+material.colorNode = color(0xff0000);
+material.emissiveNode = color(0x00ffff).mul(intensity);
+material.opacityNode = float(0.8);
+material.transparent = true;
+\`\`\`
+
+## Common Patterns
+
+### Fresnel (rim glow)
+\`\`\`javascript
+const fresnel = Fn(() => {
+ const viewDir = cameraPosition.sub(positionWorld).normalize();
+ const nDotV = normalWorld.dot(viewDir).saturate();
+ return float(1.0).sub(nDotV).pow(3.0);
+});
+material.emissiveNode = color(0x00ffff).mul(fresnel());
+\`\`\`
+
+### Pulse
+\`\`\`javascript
+const pulse = time.mul(2.0).sin().mul(0.5).add(0.5);
+material.emissiveNode = color(0xff0000).mul(pulse);
+\`\`\`
+
+## Rules
+1. Output ONLY code, no explanations or markdown
+2. Always import from three/webgpu and three/tsl
+3. Use method chaining for all operations
+4. Export the material for runtime use
+
+Generate complete, working code.`;
+
+export const KILN_BOTH_SYSTEM_PROMPT = `You generate TWO code files: geometry + shader effect.
+
+CRITICAL: geometry code has NO IMPORTS and NO EXPORTS. Just define meta, build, animate.
+
+OUTPUT FORMAT (MANDATORY):
+\`\`\`geometry
+const meta = { name: "Name", category: "prop" };
+
+function build() {
+ const root = createRoot("Name");
+ // createPart AUTO-ADDS to parent - NEVER call .add() on it!
+ createPart("Body", boxGeo(1, 1, 1), gameMaterial(0x4488ff), {
+ position: [0, 0.5, 0],
+ parent: root
+ });
+ return root;
+}
+
+function animate(root) {
+ // Track names must match Joint_* names created by createPivot
+ return [bobbingAnimation(root.name, 2, 0.1)];
+}
+\`\`\`
+
+\`\`\`effect
+import { MeshStandardNodeMaterial } from 'three/webgpu';
+import { color, float, time } from 'three/tsl';
+const material = new MeshStandardNodeMaterial();
+material.colorNode = color(0xff0000);
+export { material };
+\`\`\`
+
+GEOMETRY (no imports, no exports, globals available):
+createRoot(name) - creates root Object3D
+createPivot(name, [x,y,z], parent) - creates Joint_name pivot, returns it
+createPart(name, geo, mat, {position, rotation, scale, parent, pivot}) - AUTO-ADDS to parent!
+ NEVER: root.add(createPart(...)) // WRONG!
+ ALWAYS: createPart("Name", geo, mat, { parent: root }) // RIGHT!
+
+boxGeo, sphereGeo, cylinderGeo, coneGeo, capsuleGeo, torusGeo, planeGeo
+gameMaterial(0xcolor, {metalness, roughness, emissive, flatShading})
+glassMaterial(0xcolor, {opacity, roughness, metalness}) - transparent canopy/windows
+rotationTrack("Joint_Name", [{time, rotation:[x,y,z]}]) - degrees, NOT value!
+positionTrack("Joint_Name", [{time, position:[x,y,z]}]) - NOT value!
+createClip(name, duration, tracks) - 3 args!
+spinAnimation("Joint_Name", duration, axis), bobbingAnimation(rootName, duration, height)
+
+TSL (with imports/exports):
+float(n), vec3(x,y,z), color(0xhex)
+time, positionWorld, normalWorld, cameraPosition
+Method chaining: time.mul(2).sin().add(0.5)
+
+RULES:
+1. Output BOTH \`\`\`geometry AND \`\`\`effect blocks
+2. No text/explanations outside code blocks
+3. Effect enhances the geometry visually (glow, pulse, fresnel, etc)
+4. NEVER call .add() on createPart return value - it auto-adds to parent`;
+
// =============================================================================
// Prompt Helpers
// =============================================================================
+export function getSystemPrompt(mode: RenderMode): string {
+ if (mode === 'tsl') return KILN_TSL_SYSTEM_PROMPT;
+ if (mode === 'both') return KILN_BOTH_SYSTEM_PROMPT;
+ return KILN_SYSTEM_PROMPT;
+}
+
export interface AssetBudget {
maxTriangles?: number;
maxMaterials?: number;
@@ -215,21 +402,16 @@ export interface KilnGenerateRequest {
referenceImageUrl?: string;
}
-export function getSystemPrompt(mode: RenderMode): string {
- // Spike only supports GLB mode; tsl/both fall back to GLB so future callers
- // don't throw. W2 will pull the real TSL / Both prompts.
- void mode;
- return KILN_SYSTEM_PROMPT;
-}
-
export function buildUserPrompt(request: KilnGenerateRequest): string {
const parts: string[] = [];
+ // Add style template if specified
if (request.style && STYLE_TEMPLATES[request.style]) {
parts.push(STYLE_TEMPLATES[request.style]);
parts.push('');
}
+ // Budget constraints
if (request.budget) {
parts.push('## Constraints');
if (request.budget.maxTriangles) {
@@ -241,12 +423,14 @@ export function buildUserPrompt(request: KilnGenerateRequest): string {
parts.push('');
}
+ // Main request
if (request.existingCode) {
parts.push(`## Current Code\n\n\`\`\`typescript\n${request.existingCode}\n\`\`\`\n\n## Edit Request\n\n${request.prompt}`);
} else {
parts.push(`## Task\n\nCreate a ${request.category}: ${request.prompt}`);
}
+ // Animation instructions
if (request.includeAnimation !== false) {
parts.push(`
## Animation Requirements
diff --git a/render.ts b/render.ts
index eece03c6..4c2a34a7 100644
--- a/render.ts
+++ b/render.ts
@@ -321,6 +321,15 @@ export async function renderGLB(code: string): Promise<RenderResult> {
const { meta, root, clips } = executeKilnCode(code);
const tris = countTriangles(root);
+ // Runtime-aware joint-name validation (follow-up #6 from the W1.1 spike
+ // report). Walk the scene graph + animation tracks and surface any track
+ // whose target name doesn't resolve to a scene node. Non-fatal — the GLB
+ // still renders; agents iterating on code use these warnings to fix the
+ // next iteration. Runs before the bridge so the descriptive "rename the
+ // pivot" hint is first; the bridge also emits a briefer "target not
+ // found - skipped" for each unresolved track (kept for compatibility).
+ for (const w of inspectGeneratedAnimation(root, clips)) warnings.push(w);
+
const doc = new Document();
const buf = doc.createBuffer();
const matCache = new Map<THREE.Material, GtMaterial>();
@@ -343,3 +352,55 @@ export async function renderGLB(code: string): Promise<RenderResult> {
warnings,
};
}
+
+// =============================================================================
+// Runtime-aware animation inspection
+// =============================================================================
+
+/**
+ * Walk a Kiln-executed scene graph and its animation clips, and surface any
+ * track whose target (e.g. `Joint_LeftWheel.rotation`) doesn't resolve to a
+ * named node in the scene. These are *warnings*, not errors — the GLB still
+ * renders fine, the track just does nothing. Agents iterating on generated
+ * code use this signal to pick a real joint name on the next pass.
+ *
+ * Pure, side-effect free, safe to call without rendering.
+ */
+export function inspectGeneratedAnimation(
+ root: THREE.Object3D,
+ clips: THREE.AnimationClip[]
+): string[] {
+ const warnings: string[] = [];
+ if (clips.length === 0) return warnings;
+
+ const nodeNames = new Set<string>();
+ root.traverse((obj) => {
+ if (obj.name) nodeNames.add(obj.name);
+ });
+
+ for (const clip of clips) {
+ for (const track of clip.tracks) {
+ const dotIdx = track.name.lastIndexOf('.');
+ if (dotIdx === -1) {
+ warnings.push(`Track "${track.name}" is missing a node.property separator`);
+ continue;
+ }
+ const nodeName = track.name.substring(0, dotIdx);
+ const property = track.name.substring(dotIdx + 1);
+
+ if (!nodeNames.has(nodeName)) {
+ warnings.push(
+ `Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName}" — rename the pivot or fix the track`
+ );
+ }
+
+ if (!['position', 'quaternion', 'scale'].includes(property)) {
+ warnings.push(
+ `Animation track "${clip.name}:${track.name}" uses unsupported property "${property}"`
+ );
+ }
+ }
+ }
+
+ return warnings;
+}