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.

fix: establish final world render barrier (#44)

Matthew Kissinger80e978312ed3
diff --git a/src/__tests__/composer-world-run.test.ts b/src/__tests__/composer-world-run.test.ts
index 2f07a904..9c67957e 100644
--- a/src/__tests__/composer-world-run.test.ts
+++ b/src/__tests__/composer-world-run.test.ts
@@ -61,24 +61,24 @@ const exactRender: SceneRenderPort = async (request) => ({
degraded: false,
receipt: {
worldHash: request.worldHash!,
- cameras: [
- {
- position: [8, 5, 8],
- target: [0, 1, 0],
- up: [0, 1, 0],
- fovDeg: 50,
- aspect: 16 / 9,
- near: 0.1,
- far: 100,
- },
- ],
+ cameras: (request.cameras ?? [{ position: [8, 5, 8], target: [0, 1, 0] }]).map((camera) => ({
+ position: camera.position,
+ target: camera.target,
+ up: camera.up ?? [0, 1, 0],
+ fovDeg: camera.fovDeg ?? 50,
+ aspect: camera.aspect ?? 16 / 9,
+ near: camera.near ?? 0.1,
+ far: camera.far ?? 100,
+ })),
width: request.width ?? 640,
height: request.height ?? 360,
lightingPresetId: request.lightingPresetId ?? 'neutral-studio-v1',
backend: 'vulkan',
rendererId: 'dawn-vulkan:test',
outputSha256: `sha256:${'b'.repeat(64)}`,
- perCameraOutputSha256: [`sha256:${'b'.repeat(64)}`],
+ perCameraOutputSha256: (request.cameras ?? [null]).map(
+ () => `sha256:${'b'.repeat(64)}` as const,
+ ),
outputSetSha256: `sha256:${'c'.repeat(64)}`,
},
});
@@ -115,7 +115,7 @@ describe('runKilnWorldIntegration', () => {
const calls: Parameters<SceneRenderPort>[0][] = [];
const render: SceneRenderPort = async (request) => {
calls.push(request);
- return { ok: true, pngBase64: Buffer.from('png').toString('base64') };
+ return exactRender(request);
};
const result = await runKilnWorldIntegration({
model,
@@ -250,7 +250,7 @@ describe('runKilnWorldIntegration', () => {
model,
prompt: 'inspect the authored presentation',
world: presented,
- render: async () => ({ ok: true }),
+ render: exactRender,
maxSteps: 5,
});
@@ -289,7 +289,7 @@ describe('runKilnWorldIntegration', () => {
model,
prompt: 'use the authored collider node',
world: world(),
- render: async () => ({ ok: true }),
+ render: exactRender,
resolveAuthoredColliderGeometry: async (request) => {
resolverRequest = request;
return {
@@ -538,7 +538,7 @@ describe('runKilnWorldIntegration', () => {
});
});
- test('host refuses to finalize when the exact render predates a later world mutation', async () => {
+ test('host renders and finalizes the exact world after a later model mutation', async () => {
const model = new ToolCapturingModel([
{ toolCalls: [{ name: 'scene_world_render' }] },
{
@@ -570,13 +570,20 @@ describe('runKilnWorldIntegration', () => {
maxSteps: 5,
});
- expect(result.finalized).toBe(false);
- expect(result.finalizedBy).toBeUndefined();
- expect(result.error).toContain('hash-bound non-degraded render of the final world');
+ expect(result.finalized).toBe(true);
+ expect(result.finalizedBy).toBe('host');
+ expect(result.error).toBeUndefined();
+ expect(result.renderEvidence).toHaveLength(2);
expect(result.renderEvidence[0]!.worldHash).not.toBe(result.worldHash);
+ expect(result.renderEvidence[1]).toMatchObject({
+ worldHash: result.worldHash,
+ views: 1,
+ degraded: false,
+ receipt: { worldHash: result.worldHash },
+ });
});
- test('host refuses to finalize a valid world that was never rendered', async () => {
+ test('host establishes the exact final render barrier when the model never rendered', async () => {
const result = await runKilnWorldIntegration({
model: new ToolCapturingModel([{ text: 'done' }]),
prompt: 'finish without inspection',
@@ -585,8 +592,44 @@ describe('runKilnWorldIntegration', () => {
maxSteps: 3,
});
+ expect(result).toMatchObject({ finalized: true, finalizedBy: 'host' });
+ expect(result.error).toBeUndefined();
+ expect(result.renderEvidence).toHaveLength(1);
+ expect(result.renderEvidence[0]).toMatchObject({
+ worldHash: result.worldHash,
+ views: 1,
+ degraded: false,
+ receipt: { worldHash: result.worldHash },
+ });
+ });
+
+ test('host refuses a degraded terminal render and does not invent exact evidence', async () => {
+ const fallbackReceipt = {
+ cameraAttested: false as const,
+ backend: 'cpu',
+ rendererId: 'cpu-raster:test',
+ outputSha256: `sha256:${'d'.repeat(64)}` as const,
+ };
+ const result = await runKilnWorldIntegration({
+ model: new ToolCapturingModel([{ text: 'done' }]),
+ prompt: 'finish without inspection',
+ world: world(),
+ render: async () => ({
+ ok: true,
+ pngBase64: Buffer.from('png').toString('base64'),
+ degraded: true,
+ degradeReason: 'GPU deadline; deterministic CPU fallback',
+ fallbackReceipt,
+ }),
+ maxSteps: 3,
+ });
+
expect(result.finalized).toBe(false);
+ expect(result.finalizedBy).toBeUndefined();
expect(result.error).toContain('hash-bound non-degraded render');
+ expect(result.renderEvidence).toEqual([
+ expect.objectContaining({ degraded: true, fallbackReceipt, views: 1 }),
+ ]);
});
test('host commits an exact final render even when the model-call cap blocks a ceremonial follow-up', async () => {
diff --git a/src/composer/agent/world-run.ts b/src/composer/agent/world-run.ts
index 1e54a1f1..842a0bc8 100644
--- a/src/composer/agent/world-run.ts
+++ b/src/composer/agent/world-run.ts
@@ -147,43 +147,9 @@ function lifecycleTools(
'Render the current canonical world with the host inspection profile; inspect before finalizing.',
inputSchema: empty,
callback: async () => {
- const worldHash = await hashWorldDocumentV2(state.world);
- const presentation = state.world.presentation;
- const result = await render({
- placements: placements(state.world),
- worldDocument: state.world,
- worldHash,
- ...(presentation
- ? {
- cameras: presentation.cameras.map(({ id: _id, cell: _cell, ...camera }) => camera),
- width: presentation.grid.cellWidth,
- height: presentation.grid.cellHeight,
- lightingPresetId: presentation.lightingPresetId,
- }
- : {}),
- });
- if (!result.ok) return { ok: false, error: result.error ?? 'render failed' } as JSONValue;
- if (presentation && result.receipt) {
- const receiptValidation = validatePresentationReceiptV1(
- {
- ...presentation,
- artifactBinding: { kind: 'world', sha256: worldHash },
- },
- result.receipt,
- );
- if (!receiptValidation.ok) {
- return {
- ok: false,
- error: `presentation receipt rejected: ${receiptValidation.reason}`,
- } as JSONValue;
- }
- }
- const frames = result.perCameraBase64?.length
- ? result.perCameraBase64
- : result.pngBase64
- ? [result.pngBase64]
- : [];
- const evidence = renderEvidenceOf(worldHash, frames.length, result);
+ const attempt = await renderCanonicalWorld(state.world, render);
+ if (!attempt.ok) return { ok: false, error: attempt.error } as JSONValue;
+ const { evidence, frames } = attempt;
renderEvidence.push(evidence);
return [
...frames.map(
@@ -207,6 +173,53 @@ function lifecycleTools(
];
}
+type CanonicalWorldRenderAttempt =
+ | { ok: true; frames: string[]; evidence: WorldIntegrationRenderEvidence }
+ | { ok: false; error: string };
+
+async function renderCanonicalWorld(
+ world: WorldDocumentV2,
+ render: SceneRenderPort,
+): Promise<CanonicalWorldRenderAttempt> {
+ const worldHash = await hashWorldDocumentV2(world);
+ const presentation = world.presentation;
+ const result = await render({
+ placements: placements(world),
+ worldDocument: world,
+ worldHash,
+ ...(presentation
+ ? {
+ cameras: presentation.cameras.map(({ id: _id, cell: _cell, ...camera }) => camera),
+ width: presentation.grid.cellWidth,
+ height: presentation.grid.cellHeight,
+ lightingPresetId: presentation.lightingPresetId,
+ }
+ : {}),
+ });
+ if (!result.ok) return { ok: false, error: result.error ?? 'render failed' };
+ if (presentation && result.receipt) {
+ const receiptValidation = validatePresentationReceiptV1(
+ {
+ ...presentation,
+ artifactBinding: { kind: 'world', sha256: worldHash },
+ },
+ result.receipt,
+ );
+ if (!receiptValidation.ok) {
+ return {
+ ok: false,
+ error: `presentation receipt rejected: ${receiptValidation.reason}`,
+ };
+ }
+ }
+ const frames = result.perCameraBase64?.length
+ ? result.perCameraBase64
+ : result.pngBase64
+ ? [result.pngBase64]
+ : [];
+ return { ok: true, frames, evidence: renderEvidenceOf(worldHash, frames.length, result) };
+}
+
function cloneReceipt(receipt: SceneRenderReceipt): SceneRenderReceipt {
if (
receipt.perCameraOutputSha256 !== undefined &&
@@ -268,6 +281,40 @@ function hostFinalizationError(
return undefined;
}
+async function establishHostFinalization(
+ world: WorldDocumentV2,
+ render: SceneRenderPort,
+ renderEvidence: WorldIntegrationRenderEvidence[],
+): Promise<{ worldHash: `sha256:${string}`; error?: string; renderedByHost: boolean }> {
+ const worldHash = await hashWorldDocumentV2(world);
+ const validationError = hostFinalizationError(world, worldHash, renderEvidence);
+ if (!validationError) return { worldHash, renderedByHost: false };
+ if (!validationError.startsWith('world integration ended before')) {
+ return { worldHash, error: validationError, renderedByHost: false };
+ }
+ // A render of this exact world already produced non-committable evidence.
+ // Preserve that terminal truth instead of hiding a degraded or malformed
+ // receipt behind an unchanged automatic retry.
+ if (renderEvidence.some((evidence) => evidence.worldHash === worldHash)) {
+ return { worldHash, error: validationError, renderedByHost: false };
+ }
+
+ const attempt = await renderCanonicalWorld(world, render);
+ if (!attempt.ok) {
+ return {
+ worldHash,
+ error: `final world render failed: ${attempt.error}`,
+ renderedByHost: true,
+ };
+ }
+ renderEvidence.push(attempt.evidence);
+ return {
+ worldHash,
+ error: hostFinalizationError(world, worldHash, renderEvidence),
+ renderedByHost: true,
+ };
+}
+
/**
* Run the bounded post-compose integration phase over one canonical authority.
* Fresh flow: compose -> migrate v1 candidate -> run this. Refine flow: compose
@@ -323,19 +370,24 @@ export async function runKilnWorldIntegration(
);
metrics.recordResultUsage(result.metrics?.latestAgentInvocation?.usage);
const collected = metrics.readMetrics();
- const worldHash = await hashWorldDocumentV2(state.world);
+ const finalization = await establishHostFinalization(
+ state.world,
+ options.render,
+ renderEvidence,
+ );
+ const { worldHash } = finalization;
const lastText = lastMessageText(result.lastMessage);
- const finalizationError = finalized.value
- ? undefined
- : hostFinalizationError(state.world, worldHash, renderEvidence);
- const hostFinalized = !finalized.value && finalizationError === undefined;
+ const finalizationError = finalization.error;
+ const hostFinalized =
+ finalizationError === undefined && (!finalized.value || finalization.renderedByHost);
return {
world: state.world,
worldHash,
placements: placements(state.world),
- finalized: finalized.value || hostFinalized,
- ...(finalized.value ? { finalizedBy: 'model' as const } : {}),
- ...(hostFinalized ? { finalizedBy: 'host' as const } : {}),
+ finalized: finalizationError === undefined,
+ ...(finalizationError === undefined
+ ? { finalizedBy: hostFinalized ? ('host' as const) : ('model' as const) }
+ : {}),
toolCalls: collected.toolCalls,
steps: collected.steps,
renderEvidence,