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: inspect isolation, reachable semantic roof, OpenRouter cache, role vocabulary (#10)

Matthew Kissinger62a8db06df4e
diff --git a/README.md b/README.md
index 186e368e..9ac138e1 100644
--- a/README.md
+++ b/README.md
@@ -60,7 +60,7 @@ The engine ships TypeScript source (Bun/tsx transpile on the fly); consume by su
| `@kiln/engine/primitives` | the 70+ primitive/helper registry |
| `@kiln/engine/prompt`, `/prompt-api`, `/list-primitives` | system-prompt generation + catalog |
| `@kiln/engine/metrics`, `/inspect` | instanceability grade + scene-structure analysis |
-| `@kiln/engine/contracts` | browser-safe asset and integration contracts, including `IntegrationManifestV1` |
+| `@kiln/engine/contracts` | browser-safe asset and integration contracts, including `IntegrationManifestV1` and the semantic role vocabulary (`KILN_SEMANTIC_ROLES`, `semanticRole`, `semanticRoleMatches`, `hasSemanticRole`) |
| `@kiln/engine/composer`, `/composer/agent` | THREE-free scene-composition core (placement model, layout, overlap, DSL) + its Strands agent loop (`runKilnComposer`) |
Finished renders include `integrationManifest`, a versioned sidecar with the artifact
diff --git a/src/agent/providers.test.ts b/src/agent/providers.test.ts
index e6ea5f79..a2833c27 100644
--- a/src/agent/providers.test.ts
+++ b/src/agent/providers.test.ts
@@ -394,3 +394,77 @@ describe('toCachedSystemPrompt (A2 portable cache breakpoint)', () => {
expect(toCachedSystemPrompt(TEXT, {})).toBe(TEXT);
});
});
+
+describe('OpenRouter-Anthropic prompt caching (cache_control)', () => {
+ /** The LanguageModelV3 the Vercel bridge wraps (through the stream-start proxy,
+ * which forwards every non-doStream property untouched). */
+ const settingsOf = (model: unknown): Record<string, unknown> =>
+ (model as { _provider: { settings: Record<string, unknown> } })._provider.settings;
+
+ test('an anthropic/* slug is built with the ephemeral cache_control directive', () => {
+ const model = makeKilnModel(
+ { provider: 'openrouter', model: 'anthropic/claude-sonnet-5' },
+ { apiKey: 'test-key' },
+ );
+ expect(settingsOf(model)['cache_control']).toEqual({ type: 'ephemeral' });
+ });
+
+ test('the directive reaches the outgoing request body (fetch captured, no network)', async () => {
+ const model = makeKilnModel(
+ { provider: 'openrouter', model: 'anthropic/claude-opus-4.8' },
+ { apiKey: 'test-key' },
+ );
+ const provider = (model as unknown as { _provider: { doStream(o: unknown): Promise<unknown> } })
+ ._provider;
+
+ const realFetch = globalThis.fetch;
+ let body: Record<string, unknown> | undefined;
+ globalThis.fetch = (async (_url: unknown, init: { body: string }) => {
+ body = JSON.parse(init.body) as Record<string, unknown>;
+ return new Response('data: [DONE]\n\n', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ });
+ }) as unknown as typeof fetch;
+ try {
+ const result = (await provider.doStream({
+ prompt: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }],
+ })) as { stream: ReadableStream<unknown> };
+ const reader = result.stream.getReader();
+ while (!(await reader.read()).done) {
+ // drain
+ }
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+
+ expect(body?.['model']).toBe('anthropic/claude-opus-4.8');
+ // Top-level directive → Anthropic automatic caching of the stable prefix.
+ expect(body?.['cache_control']).toEqual({ type: 'ephemeral' });
+ });
+
+ test('non-Anthropic OpenRouter vendors do NOT get the flag', () => {
+ for (const model of ['x-ai/grok-4.3', 'openai/gpt-5.5', 'moonshotai/kimi-k2.5']) {
+ const built = makeKilnModel({ provider: 'openrouter', model }, { apiKey: 'test-key' });
+ expect(settingsOf(built)['cache_control']).toBeUndefined();
+ }
+ // ...and the reasoning setting is still the only thing that lands there.
+ const reasoning = makeKilnModel(
+ { provider: 'openrouter', model: 'x-ai/grok-4.3', maxTokens: 64000, thinking: 'high' },
+ { apiKey: 'test-key' },
+ );
+ expect(settingsOf(reasoning)).toEqual({ reasoning: { effort: 'high' } });
+ });
+
+ test('the two caching mechanisms stay separate: cache_control is not a system cache point', () => {
+ const model = makeKilnModel(
+ { provider: 'openrouter', model: 'anthropic/claude-sonnet-5' },
+ { apiKey: 'test-key' },
+ );
+ // The Vercel bridge DROPS CachePointBlocks, so the system prompt must stay a
+ // plain string even for the vendor whose upstream supports caching. The
+ // request-settings directive above is how OpenRouter gets it instead.
+ expect(modelConsumesSystemPromptCachePoints(model)).toBe(false);
+ expect(toCachedSystemPrompt('SYSTEM', model)).toBe('SYSTEM');
+ });
+});
diff --git a/src/agent/providers.ts b/src/agent/providers.ts
index fa342bfc..fe735fa3 100644
--- a/src/agent/providers.ts
+++ b/src/agent/providers.ts
@@ -107,6 +107,18 @@ export interface OpenRouterModelOptions {
* outright; other OpenRouter models don't need this. Model-scoped by the
* caller (see the 'openrouter' case below), default false. */
splitToolResultImages?: boolean;
+ /** Set OpenRouter's top-level `cache_control: {type:'ephemeral'}` directive,
+ * which turns on Anthropic AUTOMATIC prompt caching for the request — the
+ * upstream picks the breakpoints, so the stable tools+system prefix is cached
+ * without us placing any block. Anthropic-hosted models only (the provider
+ * documents it as such); harmless-but-pointless elsewhere, so callers gate it
+ * on the slug's vendor segment (see the 'openrouter' case below).
+ *
+ * This is a DIFFERENT mechanism from {@link toCachedSystemPrompt}'s explicit
+ * `CachePointBlock`, and the two must not be conflated: the Vercel bridge
+ * drops cache-point blocks outright (@strands-agents/sdk vercel.js), which is
+ * exactly why the OpenRouter fix lives here in request settings instead. */
+ promptCache?: boolean;
}
/**
@@ -116,10 +128,10 @@ export interface OpenRouterModelOptions {
export function makeOpenRouterModel(opts: OpenRouterModelOptions): Model {
const openrouter = createOpenRouter({ apiKey: opts.apiKey ?? process.env['OPENROUTER_API_KEY'] });
let provider = ensureStreamStart(
- openrouter.chat(
- opts.modelId,
- opts.reasoning ? { reasoning: opts.reasoning } : {},
- ) as LanguageModelV3,
+ openrouter.chat(opts.modelId, {
+ ...(opts.reasoning ? { reasoning: opts.reasoning } : {}),
+ ...(opts.promptCache ? { cache_control: { type: 'ephemeral' } } : {}),
+ }) as LanguageModelV3,
);
if (opts.splitToolResultImages) provider = splitToolResultImages(provider);
return new VercelModel({
@@ -349,6 +361,13 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpti
// Together's Inkling hosting rejects images embedded in a tool-result
// message (verified live 2026-07-19) — see split-tool-result-images.ts.
...(desc.model === 'thinkingmachines/inkling' ? { splitToolResultImages: true } : {}),
+ // Anthropic automatic prompt caching. Gating on the slug's vendor segment
+ // is not a heuristic: it IS OpenRouter's routing key, and the capability
+ // is vendor-scoped by construction (@openrouter/ai-sdk-provider documents
+ // cache_control as Anthropic-only). Deliberately NOT a ModelDescriptor
+ // capability field — that type crosses the AgentCore wire, and this value
+ // is 100% derivable from a model id the engine already holds.
+ ...(desc.model.startsWith('anthropic/') ? { promptCache: true } : {}),
});
}
default: {
@@ -374,6 +393,13 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpti
* - GoogleModel joins the text blocks and DROPS cache points (Gemini caching is
* implicit); OpenAI warns-and-ignores them; the Vercel bridge only forwards
* text. Those providers get the plain string so nothing changes for them.
+ *
+ * This is a statement about the ADAPTER, not about the upstream vendor, so it
+ * stays false for OpenRouter-hosted Anthropic even though that upstream does
+ * support caching: emitting a `CachePointBlock` the Vercel bridge discards
+ * (vercel.js drops them and logs a warning) would be strictly worse than
+ * today's silent no-op. OpenRouter gets caching through a different seam —
+ * {@link OpenRouterModelOptions.promptCache}.
*/
export function modelConsumesSystemPromptCachePoints(model: unknown): boolean {
return model instanceof AnthropicModel || model instanceof BedrockModel;
diff --git a/src/agent/tools-unified.test.ts b/src/agent/tools-unified.test.ts
index 54e58780..f02b596f 100644
--- a/src/agent/tools-unified.test.ts
+++ b/src/agent/tools-unified.test.ts
@@ -261,6 +261,38 @@ describe('makeKilnUnifiedTools', () => {
expect(out.availableParts).toContain('Mesh_Head');
});
+ test('kiln_inspect isolate:true reaches the renderer and is reported back', async () => {
+ const sink: UnifiedSink = { edits: [] };
+ const tools = makeKilnUnifiedTools({ seedCode: TWO_PART_CODE, sink });
+ const out = (await findTool(tools, 'kiln_inspect').invoke({
+ part: 'head',
+ isolate: true,
+ })) as unknown[];
+ expect(out[0]).toBeInstanceOf(ImageBlock);
+ const json = (out[1] as JsonBlock).json as Record<string, unknown>;
+ expect(json['isolated']).toBe(true);
+ expect(json['framed']).toContain('nothing in this image occludes it');
+ });
+
+ test('kiln_inspect defaults to isolate:false and says so in the framing line', async () => {
+ const sink: UnifiedSink = { edits: [] };
+ const tools = makeKilnUnifiedTools({ seedCode: TWO_PART_CODE, sink });
+ const out = (await findTool(tools, 'kiln_inspect').invoke({ part: 'head' })) as unknown[];
+ const json = (out[1] as JsonBlock).json as Record<string, unknown>;
+ expect(json['isolated']).toBe(false);
+ expect(json['framed']).toContain('may occlude it');
+ });
+
+ test('kiln_inspect isolate:true without a part is a no-op, not an error', async () => {
+ const sink: UnifiedSink = { edits: [] };
+ const tools = makeKilnUnifiedTools({ seedCode: TWO_PART_CODE, sink });
+ const out = (await findTool(tools, 'kiln_inspect').invoke({ isolate: true })) as unknown[];
+ const json = (out[1] as JsonBlock).json as Record<string, unknown>;
+ expect(json['ok']).toBe(true);
+ expect(json['isolated']).toBe(false);
+ expect(json['framed']).toContain('whole asset');
+ });
+
test('kiln_inspect with no part frames the whole asset in one view', async () => {
const sink: UnifiedSink = { edits: [] };
const tools = makeKilnUnifiedTools({ seedCode: TWO_PART_CODE, sink });
@@ -301,14 +333,43 @@ describe('makeKilnUnifiedTools', () => {
expect(out.error).toBeDefined();
});
- test('kiln_view_interior warns when the roof is not named "Roof"', async () => {
+ test('kiln_view_interior lifts a semantically-roled roof that is NOT named "Roof"', async () => {
const sink: UnifiedSink = { edits: [] };
const lidCode = BUILDING_CODE.replace("createRoofPlanes('Roof'", "createRoofPlanes('Lid'");
const tools = makeKilnUnifiedTools({ seedCode: lidCode, sink });
const out = (await findTool(tools, 'kiln_view_interior').invoke({})) as unknown[];
const json = (out[1] as JsonBlock).json as Record<string, unknown>;
- expect(json['roofsHidden']).toBe(0); // no node named "Roof" → nothing lifted
- expect((json['warnings'] as string[]).join(' ')).toContain('Roof');
+ // createRoofPlanes stamps roof.* roles regardless of the node's name, so the
+ // tool resolves the roof by role. The asset is already correct — there must
+ // be no warning telling the model to rename anything.
+ expect(json['roofsHidden']).toBe(1);
+ expect((json['warnings'] as string[]).join(' ')).not.toContain('could not be lifted');
+ expect((json['warnings'] as string[]).join(' ')).not.toContain('still occluded');
+ });
+
+ test('kiln_view_interior warns in explicit-override mode when the named node is absent', async () => {
+ const sink: UnifiedSink = { edits: [] };
+ const tools = makeKilnUnifiedTools({ seedCode: BUILDING_CODE, sink });
+ const out = (await findTool(tools, 'kiln_view_interior').invoke({
+ nodeName: 'Canopy',
+ })) as unknown[];
+ const json = (out[1] as JsonBlock).json as Record<string, unknown>;
+ expect(json['roofsHidden']).toBe(0);
+ const warnings = (json['warnings'] as string[]).join(' ');
+ expect(warnings).toContain('Canopy');
+ // The advice must point at the override, not at renaming the asset.
+ expect(warnings).toContain('omit nodeName');
+ });
+
+ test('kiln_view_interior warns in semantic mode when no roof is resolvable at all', async () => {
+ const sink: UnifiedSink = { edits: [] };
+ const tools = makeKilnUnifiedTools({ seedCode: BOX_CODE, sink });
+ const out = (await findTool(tools, 'kiln_view_interior').invoke({})) as unknown[];
+ const json = (out[1] as JsonBlock).json as Record<string, unknown>;
+ expect(json['roofsHidden']).toBe(0);
+ const warnings = (json['warnings'] as string[]).join(' ');
+ expect(warnings).toContain('No roof was found');
+ expect(warnings).toContain('createRoofPlanes');
});
test('kiln_finalize captures the buffer and marks finalized', async () => {
diff --git a/src/agent/tools.ts b/src/agent/tools.ts
index e53c1abc..7f5d47de 100644
--- a/src/agent/tools.ts
+++ b/src/agent/tools.ts
@@ -514,6 +514,13 @@ const inspectBufferInput = z.object({
.number()
.optional()
.describe('Padding multiplier around the part bounds, clamped to 1-4. Default 1.2.'),
+ isolate: z
+ .boolean()
+ .optional()
+ .describe(
+ 'Hide everything except the named part so nothing can occlude it. Needs `part`. ' +
+ 'Default false.',
+ ),
});
/**
@@ -640,12 +647,13 @@ export function makeKilnUnifiedTools(
description: `${inspectDef.description} Operates on your current working buffer (no code argument).`,
inputSchema: inspectBufferInput,
callback: async (input) => {
- const i = input as { part?: string; view?: string; zoom?: number };
+ const i = input as { part?: string; view?: string; zoom?: number; isolate?: boolean };
const out = await inspectDef.run({
code: buffer.code,
...(i.part !== undefined ? { part: i.part } : {}),
...(i.view !== undefined ? { view: i.view } : {}),
...(i.zoom !== undefined ? { zoom: i.zoom } : {}),
+ ...(i.isolate !== undefined ? { isolate: i.isolate } : {}),
});
return toCallbackResult(inspectDef, out);
},
@@ -661,7 +669,13 @@ export function makeKilnUnifiedTools(
name: 'kiln_view_interior',
description: `${interiorDef.description} Operates on your current working buffer (omit code).`,
inputSchema: z.object({
- nodeName: z.string().optional().describe('The roof part to lift, by name (default "Roof").'),
+ nodeName: z
+ .string()
+ .optional()
+ .describe(
+ 'Override: lift the roof by exact node name. Normally omit it — the roof is found by ' +
+ 'its semantic role whatever it is named.',
+ ),
}),
callback: async (input) => {
const n = (input as { nodeName?: string }).nodeName;
diff --git a/src/architecture.ts b/src/architecture.ts
index 0cd5b975..8a1e6450 100644
--- a/src/architecture.ts
+++ b/src/architecture.ts
@@ -2,6 +2,8 @@
import * as THREE from 'three';
import {
+ KILN_SEMANTIC_ROLES,
+ semanticRole,
stampSemanticMetadataV1,
type SemanticLocalFrameV1,
type SemanticRelationshipV1,
@@ -313,7 +315,10 @@ function buildRoof(
if (parent) parent.add(root);
stampSemanticMetadataV1(
root,
- roleMetadata(['roof.assembly'], [relationship('separable-from', 'architecture.shell.gable')]),
+ roleMetadata(
+ [semanticRole(KILN_SEMANTIC_ROLES.roof, 'assembly')],
+ [relationship('separable-from', 'architecture.shell.gable')],
+ ),
);
const faces = [buildFace(root, profile, 1), buildFace(root, profile, -1)] as const;
@@ -342,11 +347,15 @@ function buildRoof(
stampSemanticMetadataV1(
mesh,
roleMetadata(
- [`roof.slope.${face.side}`],
+ [semanticRole(KILN_SEMANTIC_ROLES.roof, 'slope', face.side)],
[
relationship(
'adjacent-to',
- `roof.slope.${face.side === 'positive' ? 'negative' : 'positive'}`,
+ semanticRole(
+ KILN_SEMANTIC_ROLES.roof,
+ 'slope',
+ face.side === 'positive' ? 'negative' : 'positive',
+ ),
),
relationship('coverage-of', coveredWall),
relationship('separable-from', 'architecture.shell.gable'),
diff --git a/src/contracts/semantic.test.ts b/src/contracts/semantic.test.ts
index e7a54449..7b4c0299 100644
--- a/src/contracts/semantic.test.ts
+++ b/src/contracts/semantic.test.ts
@@ -4,12 +4,17 @@ import * as THREE from 'three';
import { boxGeo, createPart } from '../primitives';
import { renderSceneToGLB } from '../render';
+import { createVehicleFrame, createWheelAssembly } from '../vehicle';
import {
KILN_SEMANTIC_EXTRAS_KEY,
+ KILN_SEMANTIC_ROLES,
createSemanticMetadataV1,
+ hasSemanticRole,
readSemanticMetadataV1,
readSemanticMetadataV1FromExtras,
semanticMetadataBytesV1,
+ semanticRole,
+ semanticRoleMatches,
stampSemanticMetadataV1,
validateSemanticMetadataV1,
} from './semantic';
@@ -144,3 +149,108 @@ describe('semantic metadata contract', () => {
expect(renderSceneToGLB(root)).rejects.toThrow(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY}`);
});
});
+
+// =============================================================================
+// Role vocabulary — the shared constants Studio's city-kit reads back.
+//
+// The point of these constants is that producer and consumer stop typing the
+// same string independently. So the tests that matter are the CONFORMANCE ones:
+// what the engine actually stamps on a real vehicle must be addressable through
+// the exported vocabulary alone, with no literal typed in the reader.
+// =============================================================================
+describe('semantic role vocabulary', () => {
+ test('semanticRole joins instance segments onto a base and drops blanks', () => {
+ expect(semanticRole(KILN_SEMANTIC_ROLES.wheelTire, 'left.0')).toBe('wheel.tire.left.0');
+ expect(semanticRole(KILN_SEMANTIC_ROLES.axle, 0)).toBe('axle.0');
+ expect(semanticRole(KILN_SEMANTIC_ROLES.socket, 'axle', 'rear')).toBe('socket.axle.rear');
+ expect(semanticRole(KILN_SEMANTIC_ROLES.chassis)).toBe('chassis');
+ expect(semanticRole(KILN_SEMANTIC_ROLES.chassis, '', ' ')).toBe('chassis');
+ });
+
+ test('semanticRoleMatches is segment-bounded, not a bare prefix test', () => {
+ expect(semanticRoleMatches('roof.assembly', KILN_SEMANTIC_ROLES.roof)).toBe(true);
+ expect(semanticRoleMatches('roof', KILN_SEMANTIC_ROLES.roof)).toBe(true);
+ // The whole reason a shared matcher exists: startsWith would say true here.
+ expect(semanticRoleMatches('rooftop.garden', KILN_SEMANTIC_ROLES.roof)).toBe(false);
+ expect(semanticRoleMatches('wheel.tireish.0', KILN_SEMANTIC_ROLES.wheelTire)).toBe(false);
+ expect(semanticRoleMatches('wheel.tire.left.0', KILN_SEMANTIC_ROLES.wheelTire)).toBe(true);
+ });
+
+ test('hasSemanticRole scans a role list with the same boundary rule', () => {
+ const roles = ['wheel.assembly.left.0', 'wheel.pivot.left.0', 'wheel.load-bearing.left.0'];
+ expect(hasSemanticRole(roles, KILN_SEMANTIC_ROLES.wheelAssembly)).toBe(true);
+ expect(hasSemanticRole(roles, KILN_SEMANTIC_ROLES.wheelLoadBearing)).toBe(true);
+ expect(hasSemanticRole(roles, KILN_SEMANTIC_ROLES.wheelTire)).toBe(false);
+ expect(hasSemanticRole([], KILN_SEMANTIC_ROLES.wheelTire)).toBe(false);
+ });
+
+ test('the vocabulary is frozen — values are the published GLB contract', () => {
+ expect(Object.isFrozen(KILN_SEMANTIC_ROLES)).toBe(true);
+ expect(KILN_SEMANTIC_ROLES.vehicleFrame).toBe('vehicle.frame');
+ expect(KILN_SEMANTIC_ROLES.wheelAssembly).toBe('wheel.assembly');
+ expect(KILN_SEMANTIC_ROLES.chassisMain).toBe('chassis.main');
+ expect(KILN_SEMANTIC_ROLES.roof).toBe('roof');
+ });
+
+ test('CONFORMANCE: a real engine-built vehicle is fully addressable through the vocabulary', () => {
+ const frame = createVehicleFrame('Cart', {
+ axles: [{ id: '0', position: [0.8, 0.3, 0] }],
+ seats: [{ id: 'driver', position: [0, 0.6, 0] }],
+ });
+ const rubber = new THREE.MeshStandardMaterial();
+ createWheelAssembly(
+ 'Cart',
+ { tire: rubber, rim: rubber },
+ {
+ side: 'left',
+ index: 0,
+ radius: 0.3,
+ width: 0.16,
+ position: [0.8, 0.3, 0.5],
+ steering: true,
+ parent: frame.root,
+ },
+ );
+
+ const rolesAt = (node: THREE.Object3D): readonly string[] =>
+ readSemanticMetadataV1(node)?.roles ?? [];
+ const findWith = (base: string): THREE.Object3D | undefined => {
+ let hit: THREE.Object3D | undefined;
+ frame.root.traverse((node) => {
+ if (!hit && hasSemanticRole(rolesAt(node), base)) hit = node;
+ });
+ return hit;
+ };
+
+ // Every base a downstream rig reader needs must resolve on the real asset.
+ for (const base of [
+ KILN_SEMANTIC_ROLES.vehicleFrame,
+ KILN_SEMANTIC_ROLES.chassis,
+ KILN_SEMANTIC_ROLES.axle,
+ KILN_SEMANTIC_ROLES.seat,
+ KILN_SEMANTIC_ROLES.socket,
+ KILN_SEMANTIC_ROLES.wheelAssembly,
+ KILN_SEMANTIC_ROLES.wheelPivot,
+ KILN_SEMANTIC_ROLES.wheelLoadBearing,
+ KILN_SEMANTIC_ROLES.wheelTire,
+ KILN_SEMANTIC_ROLES.wheelRim,
+ KILN_SEMANTIC_ROLES.wheelHub,
+ KILN_SEMANTIC_ROLES.wheelContact,
+ KILN_SEMANTIC_ROLES.contact,
+ KILN_SEMANTIC_ROLES.steeringPivot,
+ ]) {
+ expect(findWith(base)).toBeDefined();
+ }
+
+ // The exact spellings that cross the repo boundary, pinned.
+ expect(rolesAt(frame.root)).toEqual(['vehicle.frame', 'vehicle.front.+x']);
+ expect(rolesAt(frame.chassis)).toEqual(['socket.chassis.main', 'chassis.main']);
+ expect(rolesAt(frame.axles[0]!)).toEqual(['socket.axle.0', 'axle.0']);
+ expect(rolesAt(frame.seats[0]!)).toEqual(['socket.seat.driver', 'seat.driver']);
+ expect(rolesAt(findWith(KILN_SEMANTIC_ROLES.wheelAssembly)!)).toEqual([
+ 'wheel.assembly.left.0',
+ 'wheel.pivot.left.0',
+ 'wheel.load-bearing.left.0',
+ ]);
+ });
+});
diff --git a/src/contracts/semantic.ts b/src/contracts/semantic.ts
index a6e22554..3aa50b01 100644
--- a/src/contracts/semantic.ts
+++ b/src/contracts/semantic.ts
@@ -10,6 +10,88 @@
export const KILN_SEMANTIC_EXTRAS_KEY = 'kilnSemantic' as const;
export const KILN_SEMANTIC_SCHEMA_VERSION = 1 as const;
+// =============================================================================
+// Role vocabulary
+//
+// A role is a dot-delimited path: a BASE naming the concept plus instance
+// segments naming the occurrence ('wheel.tire' + 'left.0' -> 'wheel.tire.left.0').
+// Producers build roles from these constants; consumers match against them with
+// {@link semanticRoleMatches}. Both sides therefore share one spelling instead
+// of two independently typed string literals — a rename here is a compile error
+// at every emit site rather than a silently empty match downstream.
+// =============================================================================
+
+/**
+ * Canonical base roles Kiln stamps on nodes. Values are the portable wire
+ * spelling and are part of the GLB contract: renaming one changes published
+ * assets, so treat a change here as a versioned contract change.
+ */
+export const KILN_SEMANTIC_ROLES = Object.freeze({
+ // -- vehicle frame + typed sockets ------------------------------------------
+ /** The +X-forward/+Y-up/+Z-right frame root of a vehicle. */
+ vehicleFrame: 'vehicle.frame',
+ /** Declares the frame's forward axis explicitly, for readers that check it. */
+ vehicleForward: 'vehicle.front.+x',
+ /** Any typed socket node; full role is `socket.<kind>.<id>`. */
+ socket: 'socket',
+ /** Chassis mount point. */
+ chassis: 'chassis',
+ /** The single primary chassis mount (`chassis` sockets are id-less by convention). */
+ chassisMain: 'chassis.main',
+ axle: 'axle',
+ seat: 'seat',
+ contact: 'contact',
+ steering: 'steering',
+ propulsion: 'propulsion',
+
+ // -- wheel assembly ---------------------------------------------------------
+ /** The spin pivot that owns one wheel; the anchor readers rig from. */
+ wheelAssembly: 'wheel.assembly',
+ wheelPivot: 'wheel.pivot',
+ /** Present only on wheels that carry load (drivable ground contact). */
+ wheelLoadBearing: 'wheel.load-bearing',
+ wheelTire: 'wheel.tire',
+ wheelRim: 'wheel.rim',
+ wheelHub: 'wheel.hub',
+ wheelContact: 'wheel.contact',
+ /** Steering pivot above a steered wheel assembly. */
+ steeringPivot: 'steering.pivot',
+
+ // -- architecture -----------------------------------------------------------
+ /** Separable roof. Interior views lift every node under this role. */
+ roof: 'roof',
+ /** Long-form spelling of {@link KILN_SEMANTIC_ROLES.roof}, accepted on read. */
+ architectureRoof: 'architecture.roof',
+} as const);
+
+export type KilnSemanticRoleKey = keyof typeof KILN_SEMANTIC_ROLES;
+
+/**
+ * Build a concrete role from a base plus instance segments. Segments are joined
+ * with `.`; empty/blank segments are dropped so `semanticRole('chassis')` stays
+ * `'chassis'`.
+ */
+export function semanticRole(base: string, ...segments: readonly (string | number)[]): string {
+ const tail = segments
+ .map((segment) => String(segment).trim())
+ .filter((segment) => segment !== '');
+ return tail.length > 0 ? `${base}.${tail.join('.')}` : base;
+}
+
+/**
+ * Whether `role` IS `base` or lives beneath it. Matching is on a segment
+ * boundary, so base `'roof'` matches `'roof.assembly'` but never `'rooftop'` —
+ * the property a bare `startsWith` does not give you.
+ */
+export function semanticRoleMatches(role: string, base: string): boolean {
+ return role === base || role.startsWith(`${base}.`);
+}
+
+/** Whether any role in `roles` matches `base` per {@link semanticRoleMatches}. */
+export function hasSemanticRole(roles: readonly string[], base: string): boolean {
+ return roles.some((role) => semanticRoleMatches(role, base));
+}
+
export type SemanticVector3 = [number, number, number];
export type SemanticQuaternion = [number, number, number, number];
diff --git a/src/prompt.ts b/src/prompt.ts
index 490d8040..967101e9 100644
--- a/src/prompt.ts
+++ b/src/prompt.ts
@@ -312,7 +312,8 @@ If any view looks wrong, fix the code (kiln_edit or kiln_draft) and re-render be
If a view reveals a suspect REGION — a floating part, a bad joint, a wrong proportion — call
kiln_inspect with that part's name for a single framed close-up before editing; prefer it over
re-reading the whole grid for fine detail. An unresolved name returns the list of part names to
-retry with.
+retry with. If surrounding geometry blocks the part from every angle, pass isolate:true to hide
+everything else.
If this is an ANIMATED CHARACTER, also call kiln_screenshot_animation on your key clips
before finalizing — at least the walk and the main attack — from the right (side) camera,
and check the MOTION (the static render cannot show it):
@@ -332,7 +333,8 @@ three roof-off views the exterior six cannot, and you check the INSIDE:
floating or sunk through it; the walls enclose a real volume with standing headroom.
- Eye-level (looking in through the doorway, near walls removed): the doorway is a REAL gap you
could walk through (not a panel), and no glass or wall is buried inside a solid mass.
-If roofsHidden comes back 0 the roof was not named Roof — rename it so the tool can lift it. Fix any
+If roofsHidden comes back 0 no roof could be lifted — build the roof with a roof primitive
+(createRoofPlanes / createGableRoof), which tags it so the tool finds it whatever it is named. Fix any
sealed, buried, or floating interior and view it again.
</visual-qa>`;
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index c7de1387..e679d430 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -126,7 +126,9 @@ const viewInteriorInput = z.object({
.string()
.optional()
.describe(
- 'The roof part to lift, by name (default "Roof"). Matches that node and its children.',
+ 'Override: lift the roof by exact node name instead of by role. Matches that node and its ' +
+ 'children. Normally OMIT it — Kiln finds the roof from its semantic role (anything built ' +
+ 'with createRoofPlanes/createGableRoof), falling back to historical "Roof" naming.',
),
});
@@ -621,7 +623,7 @@ export interface KilnViewInteriorResult {
views?: string[];
gridWidth?: number;
gridHeight?: number;
- /** Roof subtree roots hidden (0 → the roof part was not named "Roof"). */
+ /** Roof subtree roots hidden (0 → no roof was resolvable by role or by name). */
roofsHidden?: number;
/** Near-wall subtree roots removed for the eye-level cutaway (0 → not a room()). */
wallsHidden?: number;
@@ -636,10 +638,11 @@ export interface KilnViewInteriorResult {
* exterior views cannot (open/walkable floor, a doorway that is a real gap, fixtures
* on the floor, nothing buried/sealed). Three roof-off cells: Floor plan, Dollhouse,
* Eye-level. A build error comes back image-free ({ ok:false, error }). When the roof
- * could not be lifted (roofsHidden === 0) the interior stays occluded — a warning tells
- * the agent to name the roof part "Roof". Pure visual QA: does NOT run the structural
- * inspector uses the same host-owned category as every other view path. The views module
- * is imported lazily to keep node:zlib out of the browser bundle graph.
+ * could not be lifted (roofsHidden === 0) the interior stays occluded — the warning is
+ * mode-specific: a bad explicit nodeName vs no resolvable roof at all. Pure visual QA:
+ * does NOT run the structural inspector uses the same host-owned category as every other
+ * view path. The views module is imported lazily to keep node:zlib out of the browser
+ * bundle graph.
*/
async function runViewInterior(
input: z.infer<typeof viewInteriorInput>,
@@ -648,12 +651,18 @@ async function runViewInterior(
try {
const { renderInteriorGrid } = await import('../views');
const { root } = await executeKilnCode(input.code);
- const nodeName = input.nodeName ?? 'Roof';
- const grid = await renderInteriorGrid(root, { nodeName });
+ // No default name. An explicit nodeName stays an exact-name override; with
+ // none, the grid resolves the roof from its semantic role (and only then
+ // falls back to historical "Roof" naming) — so a correctly-roled roof named
+ // anything at all still lifts.
+ const nodeName = input.nodeName?.trim() ? input.nodeName : undefined;
+ const grid = await renderInteriorGrid(root, { ...(nodeName ? { nodeName } : {}) });
const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });
if (grid.roofsHidden === 0) {
warnings.push(
- `No node named "${nodeName}" was found, so the roof could not be lifted and the interior is still occluded. Name the roof group exactly "${nodeName}".`,
+ nodeName
+ ? `No node named "${nodeName}" was found, so the roof could not be lifted and the interior is still occluded. Check that name, or omit nodeName so the roof is found by its semantic role instead.`
+ : 'No roof was found, so nothing could be lifted and the interior is still occluded. Build the roof with createRoofPlanes/createGableRoof (which tag it as a roof), or name the roof group "Roof".',
);
}
return {
@@ -681,14 +690,16 @@ async function runViewInterior(
* `screenshotMedia` so image transports attach the PNG bytes and strip the base64.
*/
const KILN_VIEW_INTERIOR_DESCRIPTION =
- 'SEE INSIDE an enterable building: renders it with the roof (the part named "Roof") lifted off, as a ' +
+ 'SEE INSIDE an enterable building: renders it with the roof lifted off, as a ' +
'three-view grid. (1) Floor plan: top-down — check the interior is open and walkable and the footprint ' +
'is right. (2) Dollhouse: a 3/4 cutaway — check built-in fixtures (hearth, counter, shelves) rest ON the ' +
'floor, not floating or sunk, and the walls enclose a real volume with headroom. (3) Eye-level: a low ' +
'angle looking in through the doorway with the near walls also removed — confirm the doorway is a REAL ' +
'gap you could walk through (not a panel) and no wall or glass is buried inside a solid mass. ' +
- 'Call this before finalizing any building. If roofsHidden comes back 0 the roof part was not named ' +
- '"Roof" (the interior stays hidden — rename it). Flat-shaded CPU render; writes no files.';
+ 'Call this before finalizing any building. Take no argument: the roof is found from its semantic ' +
+ 'role, so any roof built with createRoofPlanes/createGableRoof lifts whatever it is named. If ' +
+ 'roofsHidden comes back 0 no roof was resolvable and the interior stays hidden — build the roof ' +
+ 'with a roof primitive (or name the group "Roof"). Flat-shaded CPU render; writes no files.';
/** Create the interior-view definition with host-owned QA context. */
export function createKilnViewInteriorDef(context: KilnToolContext = {}): KilnToolDef {
@@ -728,6 +739,14 @@ const inspectInput = z.object({
'Padding multiplier around the part bounds, clamped to 1-4. Default 1.2; raise it to see ' +
'more surrounding context.',
),
+ isolate: z
+ .boolean()
+ .optional()
+ .describe(
+ 'Hide everything except the named part (and its descendants) so nothing can block the view. ' +
+ 'Use it when the part is buried inside or behind other geometry. Needs `part`; without ' +
+ 'one it does nothing. Default false — surrounding geometry stays visible for context.',
+ ),
});
export interface KilnInspectResult {
@@ -736,6 +755,8 @@ export interface KilnInspectResult {
part?: string;
view?: string;
zoom?: number;
+ /** True when everything outside the framed part was hidden (isolate honored). */
+ isolated?: boolean;
/** One line stating what was framed and from which view. */
framed?: string;
width?: number;
@@ -763,6 +784,7 @@ async function runInspect(input: z.infer<typeof inspectInput>): Promise<KilnInsp
...(input.part !== undefined ? { part: input.part } : {}),
...(input.view !== undefined ? { view: input.view } : {}),
...(input.zoom !== undefined ? { zoom: input.zoom } : {}),
+ ...(input.isolate !== undefined ? { isolate: input.isolate } : {}),
});
if (!r.ok) {
return {
@@ -774,13 +796,17 @@ async function runInspect(input: z.infer<typeof inspectInput>): Promise<KilnInsp
};
}
const framed = r.part
- ? `Framed part "${r.part}" (with its descendants) from the ${r.view} view at zoom ${r.zoom}.`
+ ? `Framed part "${r.part}" (with its descendants) from the ${r.view} view at zoom ${r.zoom}.` +
+ (r.isolated
+ ? ' Everything else is hidden, so nothing in this image occludes it.'
+ : ' Surrounding geometry is still drawn and may occlude it.')
: `Framed the whole asset from the ${r.view} view.`;
return {
ok: true,
...(r.part ? { part: r.part } : {}),
view: r.view,
zoom: r.zoom,
+ isolated: r.isolated,
framed,
width: r.width,
height: r.height,
@@ -805,9 +831,12 @@ const KILN_INSPECT_DESCRIPTION =
'joint, a wrong proportion — to see fine detail one grid cell cannot show. args: part (omit to ' +
'frame the whole asset in one large view), view (front/right/back/left/top/three-quarter, ' +
'default three-quarter), zoom (padding multiplier around the part bounds, 1 = tight crop up to ' +
- '4 = wide context, default 1.2). If the part name does not resolve you get the list of available ' +
- 'part names back — pick one and retry. Surrounding geometry stays visible and can occlude the ' +
- 'part; pick a different view if blocked. Flat-shaded CPU render; writes no files.';
+ '4 = wide context, default 1.2), isolate (hide everything except that part, default false). ' +
+ 'If the part name does not resolve you get the list of available part names back — pick one and ' +
+ 'retry. By default surrounding geometry stays visible for context and can occlude the part: ' +
+ 'either pick a different view, or set isolate:true to hide everything else and see the part ' +
+ 'unobstructed (use it for anything buried inside or behind other geometry). Flat-shaded CPU ' +
+ 'render; writes no files.';
/** Create the close-up inspection definition. */
export function createKilnInspectDef(): KilnToolDef {
diff --git a/src/vehicle.ts b/src/vehicle.ts
index 86e4e422..1ae02350 100644
--- a/src/vehicle.ts
+++ b/src/vehicle.ts
@@ -2,13 +2,20 @@
import * as THREE from 'three';
import {
+ hasSemanticRole,
+ KILN_SEMANTIC_ROLES,
readSemanticMetadataV1,
+ semanticRole,
+ semanticRoleMatches,
stampSemanticMetadataV1,
type SemanticMetadataV1Input,
type SemanticSocketV1,
type VehicleIntentV1,
} from './contracts';
+/** Local alias — the shared role vocabulary is referenced on nearly every stamp. */
+const ROLE = KILN_SEMANTIC_ROLES;
+
export const VEHICLE_AXES = Object.freeze({
forward: Object.freeze([1, 0, 0] as const),
up: Object.freeze([0, 1, 0] as const),
@@ -152,10 +159,20 @@ function semantic(
};
}
+/** Base role per socket kind — the shared vocabulary, not a local literal. */
+const SOCKET_ROLE_BASE: Readonly<Record<VehicleSocketKind, string>> = Object.freeze({
+ chassis: KILN_SEMANTIC_ROLES.chassis,
+ axle: KILN_SEMANTIC_ROLES.axle,
+ seat: KILN_SEMANTIC_ROLES.seat,
+ contact: KILN_SEMANTIC_ROLES.contact,
+ steering: KILN_SEMANTIC_ROLES.steering,
+ propulsion: KILN_SEMANTIC_ROLES.propulsion,
+});
+
function socketRole(kind: VehicleSocketKind, id: string): string {
- if (kind === 'chassis') return 'chassis.main';
- if (kind === 'axle') return `axle.${id}`;
- return `${kind}.${id}`;
+ // The chassis socket is singular by construction, so it keeps a fixed role.
+ if (kind === 'chassis') return KILN_SEMANTIC_ROLES.chassisMain;
+ return semanticRole(SOCKET_ROLE_BASE[kind], id);
}
function createTypedSocket(
@@ -179,10 +196,12 @@ function createTypedSocket(
};
stampSemanticMetadataV1(
node,
- semantic([`socket.${kind}.${id}`, socketRole(kind, id)], {
+ semantic([semanticRole(KILN_SEMANTIC_ROLES.socket, kind, id), socketRole(kind, id)], {
frames: [{ id: 'socket', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],
sockets: [socket],
- relationships: [{ kind: 'owned-by', target: 'vehicle.frame', targetType: 'role' }],
+ relationships: [
+ { kind: 'owned-by', target: KILN_SEMANTIC_ROLES.vehicleFrame, targetType: 'role' },
+ ],
}),
);
parent.add(node);
@@ -198,7 +217,7 @@ export function createVehicleFrame(
root.name = name;
stampSemanticMetadataV1(
root,
- semantic(['vehicle.frame', 'vehicle.front.+x'], {
+ semantic([KILN_SEMANTIC_ROLES.vehicleFrame, KILN_SEMANTIC_ROLES.vehicleForward], {
frames: [
{ id: 'origin', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },
{ id: 'forward.+x', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },
@@ -277,9 +296,11 @@ export function createWheelAssembly(
steeringPivot.position.set(...(options.position ?? [0, 0, 0]));
stampSemanticMetadataV1(
steeringPivot,
- semantic([`steering.pivot.${key}`], {
+ semantic([semanticRole(ROLE.steeringPivot, key)], {
frames: [{ id: 'steering-axis.+y', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],
- relationships: [{ kind: 'steers', target: `wheel.assembly.${key}`, targetType: 'role' }],
+ relationships: [
+ { kind: 'steers', target: semanticRole(ROLE.wheelAssembly, key), targetType: 'role' },
+ ],
}),
);
root.add(steeringPivot);
@@ -292,9 +313,9 @@ export function createWheelAssembly(
spinPivot,
semantic(
[
- `wheel.assembly.${key}`,
- `wheel.pivot.${key}`,
- ...(options.loadBearing === false ? [] : [`wheel.load-bearing.${key}`]),
+ semanticRole(ROLE.wheelAssembly, key),
+ semanticRole(ROLE.wheelPivot, key),
+ ...(options.loadBearing === false ? [] : [semanticRole(ROLE.wheelLoadBearing, key)]),
],
{
frames: [
@@ -302,10 +323,10 @@ export function createWheelAssembly(
{ id: 'spin-axis.+z', translation: [0, 0, 0], rotation: [0, 0, 0, 1] },
],
relationships: [
- { kind: 'mounted-on', target: `axle.${index}`, targetType: 'role' },
- { kind: 'contains', target: `wheel.tire.${key}`, targetType: 'role' },
- { kind: 'contains', target: `wheel.rim.${key}`, targetType: 'role' },
- { kind: 'contains', target: `wheel.hub.${key}`, targetType: 'role' },
+ { kind: 'mounted-on', target: semanticRole(ROLE.axle, index), targetType: 'role' },
+ { kind: 'contains', target: semanticRole(ROLE.wheelTire, key), targetType: 'role' },
+ { kind: 'contains', target: semanticRole(ROLE.wheelRim, key), targetType: 'role' },
+ { kind: 'contains', target: semanticRole(ROLE.wheelHub, key), targetType: 'role' },
],
},
),
@@ -327,20 +348,26 @@ export function createWheelAssembly(
hub.name = `Hub_${options.side}_${index}`;
stampSemanticMetadataV1(
tire,
- semantic([`wheel.tire.${key}`], {
- relationships: [{ kind: 'descends-from', target: `wheel.pivot.${key}`, targetType: 'role' }],
+ semantic([semanticRole(ROLE.wheelTire, key)], {
+ relationships: [
+ { kind: 'descends-from', target: semanticRole(ROLE.wheelPivot, key), targetType: 'role' },
+ ],
}),
);
stampSemanticMetadataV1(
rim,
- semantic([`wheel.rim.${key}`], {
- relationships: [{ kind: 'contained-by', target: `wheel.tire.${key}`, targetType: 'role' }],
+ semantic([semanticRole(ROLE.wheelRim, key)], {
+ relationships: [
+ { kind: 'contained-by', target: semanticRole(ROLE.wheelTire, key), targetType: 'role' },
+ ],
}),
);
stampSemanticMetadataV1(
hub,
- semantic([`wheel.hub.${key}`], {
- relationships: [{ kind: 'contained-by', target: `wheel.rim.${key}`, targetType: 'role' }],
+ semantic([semanticRole(ROLE.wheelHub, key)], {
+ relationships: [
+ { kind: 'contained-by', target: semanticRole(ROLE.wheelRim, key), targetType: 'role' },
+ ],
}),
);
spinPivot.add(tire, rim, hub);
@@ -350,9 +377,9 @@ export function createWheelAssembly(
contact.position.y = -radius;
stampSemanticMetadataV1(
contact,
- semantic([`wheel.contact.${key}`, `contact.${key}`], {
+ semantic([semanticRole(ROLE.wheelContact, key), semanticRole(ROLE.contact, key)], {
frames: [{ id: 'contact', translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],
- relationships: [{ kind: 'supports', target: 'vehicle.frame', targetType: 'role' }],
+ relationships: [{ kind: 'supports', target: ROLE.vehicleFrame, targetType: 'role' }],
}),
);
spinPivot.add(contact);
@@ -486,24 +513,24 @@ function resolved(
...(tire ? { radius: tire.radius, width: tire.width } : {}),
...(rim ? { rimRadius: rim.radius, rimWidth: rim.width } : {}),
...(hub ? { hubRadius: hub.radius, hubWidth: hub.width } : {}),
- loadBearing: roles(pivot).some((role) => role.startsWith('wheel.load-bearing.')),
+ loadBearing: hasSemanticRole(roles(pivot), ROLE.wheelLoadBearing),
};
}
function semanticAssemblies(root: THREE.Object3D): ResolvedWheelAssembly[] {
const result: ResolvedWheelAssembly[] = [];
root.traverse((node) => {
- const assemblyRole = roles(node).find((role) => role.startsWith('wheel.assembly.'));
+ const assemblyRole = roles(node).find((role) => semanticRoleMatches(role, ROLE.wheelAssembly));
if (!assemblyRole) return;
const parsed = parseWheelRole(assemblyRole);
result.push(
resolved('semantic', assemblyRole, node, node, {
...parsed,
- tire: descendantWithRole(node, 'wheel.tire.'),
- rim: descendantWithRole(node, 'wheel.rim.'),
- hub: descendantWithRole(node, 'wheel.hub.'),
- contact: descendantWithRole(node, 'wheel.contact.'),
- steeringPivot: ancestorWithRole(node, 'steering.pivot.'),
+ tire: descendantWithRole(node, `${ROLE.wheelTire}.`),
+ rim: descendantWithRole(node, `${ROLE.wheelRim}.`),
+ hub: descendantWithRole(node, `${ROLE.wheelHub}.`),
+ contact: descendantWithRole(node, `${ROLE.wheelContact}.`),
+ steeringPivot: ancestorWithRole(node, `${ROLE.steeringPivot}.`),
}),
);
});
@@ -574,8 +601,8 @@ export function hasCanonicalVehicleFront(root: THREE.Object3D): boolean {
root.traverse((node) => {
const metadata = readSemanticMetadataV1(node);
if (
- metadata?.roles.includes('vehicle.frame') &&
- metadata.roles.includes('vehicle.front.+x') &&
+ metadata?.roles.includes(ROLE.vehicleFrame) &&
+ metadata.roles.includes(ROLE.vehicleForward) &&
metadata.frames.some((frame) => frame.id === 'forward.+x')
) {
found = true;
diff --git a/src/views/__tests__/inspect.test.ts b/src/views/__tests__/inspect.test.ts
new file mode 100644
index 00000000..7ebb6ce1
--- /dev/null
+++ b/src/views/__tests__/inspect.test.ts
@@ -0,0 +1,155 @@
+/**
+ * Unit tests for the part-framed close-up (kiln_inspect's render half).
+ *
+ * The interesting property is `isolate`: framing a part does NOT stop a sibling
+ * from covering it, so a buried part is unreadable at every camera angle. These
+ * tests prove isolation removes the occluder's triangles entirely (not merely
+ * dims them), that it is a no-op without a part, and that the framing box is
+ * unaffected either way.
+ */
+import { describe, expect, test } from 'bun:test';
+import sharp from 'sharp';
+import * as THREE from 'three';
+
+import { renderInspectView, listPartNames, INSPECT_SIZE } from '../inspect';
+import { executeKilnCode } from '../../render';
+
+// A small red core fully enclosed by a larger blue shell. From EVERY camera the
+// shell covers the core, so this is the "buried part" the model cannot inspect
+// by picking another view.
+const BURIED_CODE = `
+const meta = { name: 'buried-core', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ createPart('Core', boxGeo(0.4, 0.4, 0.4), gameMaterial('#ff0000'), { parent: root, position: [0, 0.8, 0] });
+ createPart('Shell', boxGeo(1.6, 1.6, 1.6), gameMaterial('#0000ff'), { parent: root, position: [0, 0.8, 0] });
+ return root;
+}
+`;
+
+/** Pixels whose hue is unambiguously the red part vs the blue occluder.
+ * Shading is a scalar multiply on a linear color, so a pure-red material can
+ * never produce a blue-dominant pixel and vice versa. */
+async function hueCounts(png: Buffer): Promise<{ red: number; blue: number; background: number }> {
+ const { data, info } = await sharp(png).raw().toBuffer({ resolveWithObject: true });
+ let red = 0;
+ let blue = 0;
+ let background = 0;
+ for (let i = 0; i < info.width * info.height; i++) {
+ const r = data[i * info.channels]!;
+ const g = data[i * info.channels + 1]!;
+ const b = data[i * info.channels + 2]!;
+ if (r === 26 && g === 26 && b === 26) background++;
+ else if (r > b) red++;
+ else if (b > r) blue++;
+ }
+ return { red, blue, background };
+}
+
+describe('renderInspectView isolate', () => {
+ test('a buried part is fully occluded by default — the sibling owns every drawn pixel', async () => {
+ const { root } = await executeKilnCode(BURIED_CODE);
+ const r = renderInspectView(root, { part: 'Core', size: 96 });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.part).toBe('Mesh_Core');
+ expect(r.isolated).toBe(false);
+ const counts = await hueCounts(r.png);
+ expect(counts.blue).toBeGreaterThan(0); // the occluding shell is drawn...
+ expect(counts.red).toBe(0); // ...and nothing of the framed part survives it
+ });
+
+ test('isolate:true removes the occluding sibling entirely — it contributes zero triangles', async () => {
+ const { root } = await executeKilnCode(BURIED_CODE);
+ const r = renderInspectView(root, { part: 'Core', size: 96, isolate: true });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.isolated).toBe(true);
+ const counts = await hueCounts(r.png);
+ expect(counts.blue).toBe(0); // the sibling drew nothing at all
+ expect(counts.red).toBeGreaterThan(0); // the part is now visible
+ });
+
+ test('isolation does not move the camera: same part, same framing, same size', async () => {
+ const plain = renderInspectView((await executeKilnCode(BURIED_CODE)).root, {
+ part: 'Core',
+ size: 96,
+ });
+ const isolated = renderInspectView((await executeKilnCode(BURIED_CODE)).root, {
+ part: 'Core',
+ size: 96,
+ isolate: true,
+ });
+ expect(plain.ok && isolated.ok).toBe(true);
+ if (!plain.ok || !isolated.ok) return;
+ expect(isolated.view).toBe(plain.view);
+ expect(isolated.zoom).toBe(plain.zoom);
+ expect(isolated.width).toBe(plain.width);
+ // Framing is measured from the part's own bounds, which isolation cannot
+ // change — so the visible core lands on exactly the same pixels.
+ const before = await hueCounts(plain.png);
+ const after = await hueCounts(isolated.png);
+ expect(after.red + after.background).toBe(before.red + before.blue + before.background);
+ });
+
+ test('isolate without a part is a no-op — the whole asset still renders', async () => {
+ const { root } = await executeKilnCode(BURIED_CODE);
+ const whole = renderInspectView(root, { isolate: true, size: 96 });
+ expect(whole.ok).toBe(true);
+ if (!whole.ok) return;
+ expect(whole.isolated).toBe(false); // nothing was singled out, so nothing was hidden
+ expect('part' in whole).toBe(false);
+ const counts = await hueCounts(whole.png);
+ expect(counts.blue).toBeGreaterThan(0); // the shell is still drawn
+ });
+
+ test('isolate:false is the documented default framing (occluders kept for context)', async () => {
+ const { root } = await executeKilnCode(BURIED_CODE);
+ const r = renderInspectView(root, { part: 'Core', size: 96, isolate: false });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.isolated).toBe(false);
+ expect((await hueCounts(r.png)).blue).toBeGreaterThan(0);
+ });
+
+ test('an unresolved part is still a retryable miss, isolate or not', async () => {
+ const { root } = await executeKilnCode(BURIED_CODE);
+ const r = renderInspectView(root, { part: 'Nonexistent', isolate: true });
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.error).toContain('Nonexistent');
+ expect(r.availableParts).toEqual(listPartNames(root));
+ // Nothing was hidden on the way out: a miss must not mutate the scene.
+ const whole = renderInspectView(root, { size: 64 });
+ expect(whole.ok).toBe(true);
+ if (!whole.ok) return;
+ expect((await hueCounts(whole.png)).blue).toBeGreaterThan(0);
+ });
+
+ test('a resolvable part with no drawable geometry is a miss, not a blank frame', async () => {
+ const root = new THREE.Group();
+ const empty = new THREE.Group(); // a pivot/holder the model named but never filled
+ empty.name = 'Hollow';
+ const solid = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1));
+ solid.name = 'Mesh_Solid';
+ root.add(empty, solid);
+
+ const r = renderInspectView(root, { part: 'Hollow', isolate: true });
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.error).toContain('no visible geometry');
+ expect(r.availableParts).toContain('Hollow');
+ // Bailing before isolation matters: hiding the rest of the scene for a part
+ // that cannot be drawn would leave the caller a blank image.
+ expect(solid.visible).toBe(true);
+ });
+
+ test('the default square size is unchanged by the new option', async () => {
+ const { root } = await executeKilnCode(BURIED_CODE);
+ const r = renderInspectView(root, { part: 'Core', isolate: true });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.width).toBe(INSPECT_SIZE);
+ expect(r.height).toBe(INSPECT_SIZE);
+ });
+});
diff --git a/src/views/__tests__/views.test.ts b/src/views/__tests__/views.test.ts
index f37c5ab2..ca27a2a0 100644
--- a/src/views/__tests__/views.test.ts
+++ b/src/views/__tests__/views.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'bun:test';
import sharp from 'sharp';
+import * as THREE from 'three';
import {
coverage,
rasterizeView,
@@ -366,4 +367,36 @@ describe('renderInteriorGrid', () => {
expect(grid.wallsHidden).toBe(0);
expect(grid.png.length).toBeGreaterThan(100);
});
+
+ test('an explicit nodeName stays an exact-name override, semantics ignored', async () => {
+ // The roof carries roof.* roles AND is named Roof; naming a node that does
+ // not exist must NOT silently fall through to the semantic path, or the
+ // override would be unable to report its own miss.
+ const { root } = await executeKilnCode(BUILDING_CODE);
+ expect((await renderInteriorGrid(root, { size: 48, nodeName: 'Lid' })).roofsHidden).toBe(0);
+ expect((await renderInteriorGrid(root, { size: 48, nodeName: 'Roof' })).roofsHidden).toBe(1);
+ });
+
+ test('legacy-name fallback is narrow: Roof_Ridge lifts, RoofTop does not', async () => {
+ // Deliberate behavior NARROWING vs the old unconditional hideNodeInScene
+ // pass, whose startsWith('roof') also swept up RoofTop/RoofRack/Roofing.
+ // Assets built with a roof primitive are unaffected — they carry a role and
+ // never reach this fallback. Hand-rolled groups named like a roof but not
+ // named "Roof" no longer lift; that is the price of not hiding a rooftop
+ // garden along with the roof.
+ const build = (name: string): THREE.Group => {
+ const scene = new THREE.Group();
+ const lid = new THREE.Group();
+ lid.name = name;
+ lid.add(new THREE.Mesh(new THREE.BoxGeometry(2, 0.2, 2)));
+ scene.add(lid);
+ return scene;
+ };
+ expect((await renderInteriorGrid(build('Roof_Ridge'), { size: 32 })).roofsHidden).toBe(1);
+ expect((await renderInteriorGrid(build('RoofTop'), { size: 32 })).roofsHidden).toBe(0);
+ // The override is still available for exactly this case.
+ expect(
+ (await renderInteriorGrid(build('RoofTop'), { size: 32, nodeName: 'RoofTop' })).roofsHidden,
+ ).toBe(1);
+ });
});
diff --git a/src/views/architecture.ts b/src/views/architecture.ts
index eead0aeb..2da7e382 100644
--- a/src/views/architecture.ts
+++ b/src/views/architecture.ts
@@ -1,4 +1,4 @@
-import { readSemanticMetadataV1FromExtras } from '../contracts';
+import { KILN_SEMANTIC_ROLES, readSemanticMetadataV1FromExtras } from '../contracts';
export interface ArchitectureViewNode {
name?: string;
@@ -15,7 +15,11 @@ export interface ArchitectureRoofSelection {
nodes: ArchitectureViewNode[];
}
-export const ARCHITECTURE_ROOF_ROLE_PREFIXES = Object.freeze(['roof.', 'architecture.roof.']);
+/** Derived from the shared vocabulary so a role rename cannot desync the views. */
+export const ARCHITECTURE_ROOF_ROLE_PREFIXES = Object.freeze([
+ `${KILN_SEMANTIC_ROLES.roof}.`,
+ `${KILN_SEMANTIC_ROLES.architectureRoof}.`,
+]);
function nodeRoles(node: ArchitectureViewNode): readonly string[] {
return readSemanticMetadataV1FromExtras(node.userData ?? {})?.roles ?? [];
diff --git a/src/views/index.ts b/src/views/index.ts
index 62f7a010..fa62dbef 100644
--- a/src/views/index.ts
+++ b/src/views/index.ts
@@ -540,14 +540,17 @@ export async function renderClipAnimation(
// =============================================================================
export interface InteriorGridResult extends ViewGridResult {
- /** Roof subtree roots hidden (0 → the roof part was not named like nodeName). */
+ /** Roof subtree roots hidden (0 → no roof resolved: no `roof.` role, no
+ * historical roof name, or an explicit `nodeName` that matched nothing). */
roofsHidden: number;
/** Near-wall subtree roots hidden for the eye-level cutaway (0 → not a room()). */
wallsHidden: number;
}
export interface InteriorGridOptions extends RasterOptions {
- /** Name of the roof part to lift. Default 'Roof'. */
+ /** Exact-name override: lift this node and its children instead of resolving
+ * the roof semantically. Omit it for the ordinary path — role first, then a
+ * narrow historical-name fallback. */
nodeName?: string;
}
diff --git a/src/views/inspect.ts b/src/views/inspect.ts
index 9f041d90..5865cafa 100644
--- a/src/views/inspect.ts
+++ b/src/views/inspect.ts
@@ -7,9 +7,10 @@
* proportion — at full-image detail instead of one grid cell. Part selection is
* name-driven by design (the model authored the names via createPart), NOT a
* free camera: an unresolved name comes back with the list of available part
- * names so the model can retry. Surrounding geometry stays visible (and may
- * occlude the part from some angles), matching the diagnostic views'
- * focus-bounds framing model (see ./diagnostic.ts).
+ * names so the model can retry. Surrounding geometry stays visible by default
+ * (and may occlude the part from some angles), matching the diagnostic views'
+ * focus-bounds framing model (see ./diagnostic.ts); `isolate` opts out of that
+ * and hides everything outside the part so nothing can block the view.
*/
import { rasterizeView, measureBounds } from './raster';
@@ -36,6 +37,8 @@ const INSPECT_CAMERAS: Record<string, [number, number, number]> = {
/** Minimal duck-typed view of a (possibly cross-realm) scene node. */
interface DuckNamedNode {
name?: string;
+ isMesh?: boolean;
+ visible?: boolean;
updateMatrixWorld?(force?: boolean): void;
traverse?(cb: (obj: unknown) => void): void;
}
@@ -51,6 +54,10 @@ export interface InspectViewOptions {
zoom?: number;
/** Square output size in pixels. Default {@link INSPECT_SIZE}. */
size?: number;
+ /** Hide every mesh outside the framed part's subtree, so surrounding geometry
+ * cannot occlude it from any angle. Requires `part` — with nothing singled
+ * out there is nothing to isolate, so it is a no-op. Default false. */
+ isolate?: boolean;
}
export type InspectViewResult =
@@ -62,6 +69,9 @@ export type InspectViewResult =
view: string;
/** Effective (clamped) padding multiplier. */
zoom: number;
+ /** Whether everything outside the framed part was actually hidden. False
+ * whenever no part was singled out, even if `isolate` was requested. */
+ isolated: boolean;
width: number;
height: number;
png: Buffer;
@@ -124,6 +134,26 @@ function isEmptyBounds(b: Bounds): boolean {
return b.min.every((v) => v === 0) && b.max.every((v) => v === 0);
}
+/**
+ * Hide every mesh that is NOT inside `keep`'s subtree, so the framed part cannot
+ * be occluded from any angle. A FLAT mesh-level pass is exactly right here:
+ * `collectTriangles` culls per-MESH on `.visible` and ignores ancestor-group
+ * visibility (raster.ts), so flipping groups would be both insufficient (their
+ * child meshes still draw) and unnecessary.
+ *
+ * MUTATES `.visible` on the passed scene — safe because every caller renders a
+ * freshly executed program, the same contract `renderInteriorGrid` relies on.
+ */
+function isolateSubtree(root: unknown, keep: DuckNamedNode): void {
+ const kept = new Set<unknown>();
+ keep.traverse?.((obj) => kept.add(obj));
+ (root as DuckNamedNode).traverse?.((obj) => {
+ const node = obj as DuckNamedNode;
+ if (!node.isMesh || kept.has(obj)) return;
+ node.visible = false;
+ });
+}
+
/**
* Render one close-up view framed to a named part's world bounds (or the whole
* asset when no part is given). Never throws on a bad part name — that comes
@@ -144,6 +174,7 @@ export function renderInspectView(root: unknown, opts: InspectViewOptions = {}):
let part: string | undefined;
let bounds: Bounds;
+ let isolated = false;
const requested = opts.part?.trim();
if (requested) {
const node = findPartNode(root, requested);
@@ -168,6 +199,12 @@ export function renderInspectView(root: unknown, opts: InspectViewOptions = {}):
}
part = node.name!.trim();
bounds = b;
+ // Framing is measured first: isolation only removes geometry OUTSIDE the
+ // part, so the framed box is identical either way.
+ if (opts.isolate) {
+ isolateSubtree(root, node);
+ isolated = true;
+ }
} else {
bounds = measureBounds(root);
}
@@ -181,6 +218,7 @@ export function renderInspectView(root: unknown, opts: InspectViewOptions = {}):
...(part ? { part } : {}),
view,
zoom,
+ isolated,
width: size,
height: size,
png: encodePng(rgb, size, size),