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(agent): PBR render port seam, gate integrity guards, degrade policy (#7)

Matthew Kissingercd3101bff287
diff --git a/src/__tests__/composer-run-port.test.ts b/src/__tests__/composer-run-port.test.ts
new file mode 100644
index 00000000..5e3fd40d
--- /dev/null
+++ b/src/__tests__/composer-run-port.test.ts
@@ -0,0 +1,107 @@
+/**
+ * B3a — the composer-path PbrRenderPort seam.
+ *
+ * The port is landed as a TYPED OPTION ONLY: no default implementation and no
+ * composer tool calls it yet. These tests pin exactly that: a real
+ * `runKilnComposer` run (over a ScriptedModel driving the genuine Strands
+ * Agent) with and without `pbrRender` exposes the identical tool surface and
+ * produces the identical result, and the injected port is never invoked.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { Message, ModelStreamEvent, StreamOptions } from '@strands-agents/sdk';
+
+import type {
+ CatalogEntry,
+ PbrRenderPort,
+ PbrRenderRequest,
+ PbrRenderResult,
+ SceneRenderPort,
+} from '../composer';
+import { runKilnComposer } from '../composer/agent';
+import { ScriptedModel } from '../agent/__tests__/scripted-model';
+
+const PNG_B64 = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]).toString('base64');
+
+const asset = (id: string): CatalogEntry => ({
+ generationId: id,
+ bbox: { min: [-1, 0, -1], max: [1, 2, 1] },
+ name: id,
+});
+
+/** ScriptedModel that also records the tool surface offered on every model call. */
+class ToolCapturingModel extends ScriptedModel {
+ readonly toolNames: string[][] = [];
+
+ override async *stream(
+ messages: Message[],
+ options?: StreamOptions,
+ ): AsyncIterable<ModelStreamEvent> {
+ this.toolNames.push((options?.toolSpecs ?? []).map((t) => t.name));
+ yield* super.stream(messages, options);
+ }
+}
+
+const render: SceneRenderPort = async () => ({ ok: true, pngBase64: PNG_B64 });
+
+async function runOnce(pbrRender?: PbrRenderPort) {
+ const model = new ToolCapturingModel([{ text: 'scene looks good' }]);
+ const result = await runKilnComposer({
+ model,
+ prompt: 'a small plaza',
+ sceneName: 'Plaza',
+ catalog: [asset('well'), asset('crate')],
+ seed: 7,
+ render,
+ ...(pbrRender ? { pbrRender } : {}),
+ });
+ return { result, toolNames: model.toolNames };
+}
+
+describe('composer pbrRender seam (B3a)', () => {
+ test('PbrRenderPort types express the render-service contract', async () => {
+ // Type-level: a conforming implementation assigns cleanly and round-trips.
+ const port: PbrRenderPort = async (req: PbrRenderRequest): Promise<PbrRenderResult> => ({
+ ok: true,
+ rendererId: 'dawn-vulkan:nvidia-rtx-a4500:NVIDIA: 550.100',
+ viewsPng: (req.viewDirs ?? []).map(() => new Uint8Array([1])),
+ timings: { renderMs: 12 },
+ });
+ const res = await port({
+ glb: new Uint8Array([0x67, 0x6c, 0x54, 0x46]),
+ viewDirs: [
+ [1, 0, 0],
+ [0, 0, 1],
+ ],
+ size: 384,
+ beautySize: 1024,
+ });
+ expect(res.ok).toBe(true);
+ expect(res.rendererId).toMatch(/^[a-z0-9-]+:/);
+ expect(res.viewsPng).toHaveLength(2);
+ });
+
+ test('threading pbrRender changes nothing: identical tool surface and result, port never called', async () => {
+ let calls = 0;
+ const stub: PbrRenderPort = async () => {
+ calls++;
+ return { ok: true, rendererId: 'dawn-vulkan:test-gpu:1.0' };
+ };
+
+ const without = await runOnce();
+ const withPort = await runOnce(stub);
+
+ // The seam is dormant: no tool ever invokes it.
+ expect(calls).toBe(0);
+
+ // Identical tool surfaces offered to the model on every call.
+ expect(withPort.toolNames).toEqual(without.toolNames);
+ expect(withPort.toolNames.length).toBeGreaterThan(0);
+ expect(withPort.toolNames[0]).toContain('scene_render');
+ expect(withPort.toolNames[0]).toContain('scene_finalize');
+
+ // Identical run result (program, scene, placements, metrics, everything).
+ expect(withPort.result).toEqual(without.result);
+ expect(withPort.result.finalized).toBe(false);
+ expect(withPort.result.program).toBeTruthy();
+ });
+});
diff --git a/src/agent/generate.test.ts b/src/agent/generate.test.ts
index f09f8090..596a09e2 100644
--- a/src/agent/generate.test.ts
+++ b/src/agent/generate.test.ts
@@ -213,3 +213,199 @@ describe('generateKilnAsset', () => {
await expect(generateKilnAsset({ prompt: 'x' })).rejects.toThrow(/provider returned 500/);
});
});
+
+describe('generateKilnAsset viewRenderPort (B3b/B4)', () => {
+ const saved: Record<string, string | undefined> = {};
+ const KEYS = ['GEMINI_API_KEY', 'ANTHROPIC_API_KEY', 'KILN_MODEL', 'PIXEL_FORGE_MODEL'];
+ beforeAll(() => {
+ for (const k of KEYS) saved[k] = process.env[k];
+ if (!process.env['GEMINI_API_KEY']) process.env['GEMINI_API_KEY'] = 'test-gemini-key';
+ delete process.env['KILN_MODEL'];
+ delete process.env['PIXEL_FORGE_MODEL'];
+ });
+ afterAll(() => {
+ for (const k of KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ });
+
+ const okRun = async () => ({ code: CANNED_CODE, toolCalls: ['kiln_submit'], steps: 1 });
+
+ /** 6 tiny solid-color per-view PNGs, like a host PBR renderer would return. */
+ async function stubViewPngs(size = 8): Promise<Uint8Array[]> {
+ const { encodePng } = await import('../views');
+ return Array.from({ length: 6 }, (_, i) => {
+ const rgb = new Uint8Array(size * size * 3);
+ for (let p = 0; p < size * size; p++) rgb[p * 3] = 30 + i * 30;
+ return new Uint8Array(encodePng(rgb, size, size));
+ });
+ }
+
+ test('option absent: views are byte-identical to the CPU grid, no degrade fields', async () => {
+ runImpl = okRun;
+ const r = await generateKilnAsset({ prompt: 'a crate', captureViews: true });
+
+ const { renderCodeViewGrid } = await import('../views');
+ const cpu = (await renderCodeViewGrid(CANNED_CODE)).png;
+ expect(r.views).toBeInstanceOf(Buffer);
+ expect(Buffer.compare(r.views!, cpu)).toBe(0);
+ // Pin: the port-absent result shape is unchanged — no provenance/degrade keys.
+ expect(r.viewsRendererId).toBeUndefined();
+ expect(r.renderDegraded).toBeUndefined();
+ expect(r.renderDegradedReason).toBeUndefined();
+ expect('renderDegraded' in r).toBe(false);
+ });
+
+ test('port success: composited port views, port rendererId, renderDegraded false', async () => {
+ runImpl = okRun;
+ const viewsPng = await stubViewPngs();
+ const requests: import('../composer/render-port').PbrRenderRequest[] = [];
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ viewRenderPort: async (req) => {
+ requests.push(req);
+ return { ok: true, rendererId: 'dawn-vulkan:test-gpu:1.0', viewsPng };
+ },
+ });
+
+ // The port saw the ALREADY-PRODUCED GLB bytes and the six grid view dirs.
+ expect(requests).toHaveLength(1);
+ expect(Buffer.compare(Buffer.from(requests[0]!.glb), r.glb)).toBe(0);
+ expect(requests[0]!.viewDirs).toHaveLength(6);
+ expect(requests[0]!.size).toBe(384);
+
+ expect(r.renderDegraded).toBe(false);
+ expect(r.renderDegradedReason).toBeUndefined();
+ expect(r.viewsRendererId).toBe('dawn-vulkan:test-gpu:1.0');
+ // The views are the port cells composited into the SAME 3x2 grid layout.
+ const { compositeViewPngGrid } = await import('../views');
+ expect(Buffer.compare(r.views!, compositeViewPngGrid(viewsPng).png)).toBe(0);
+ });
+
+ test('port is never consulted when captureViews is off', async () => {
+ runImpl = okRun;
+ let calls = 0;
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ viewRenderPort: async () => {
+ calls++;
+ return { ok: true, rendererId: 'dawn-vulkan:test-gpu:1.0' };
+ },
+ });
+ expect(calls).toBe(0);
+ expect(r.views).toBeUndefined();
+ expect(r.renderDegraded).toBeUndefined();
+ });
+
+ test('B4: a rejecting port degrades to the CPU grid with honest provenance', async () => {
+ runImpl = okRun;
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ viewRenderPort: async () => {
+ throw new Error('GPU service unreachable');
+ },
+ });
+
+ const { renderCodeViewGrid, CPU_RASTER_RENDERER_ID } = await import('../views');
+ expect(r.renderDegraded).toBe(true);
+ expect(r.renderDegradedReason).toContain('GPU service unreachable');
+ expect(r.viewsRendererId).toBe(CPU_RASTER_RENDERER_ID);
+ expect(r.viewsRendererId).toMatch(/^cpu-raster:/);
+ const cpu = (await renderCodeViewGrid(CANNED_CODE)).png;
+ expect(Buffer.compare(r.views!, cpu)).toBe(0);
+ });
+
+ test('B4: an ok:false port degrades with the port error as the reason', async () => {
+ runImpl = okRun;
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ viewRenderPort: async () => ({
+ ok: false,
+ rendererId: 'dawn-vulkan:test-gpu:1.0',
+ error: 'device lost',
+ }),
+ });
+ expect(r.renderDegraded).toBe(true);
+ expect(r.renderDegradedReason).toContain('device lost');
+ expect(r.viewsRendererId).toMatch(/^cpu-raster:/);
+ expect(r.views).toBeInstanceOf(Buffer);
+ });
+
+ test('B4: a hanging port trips the deadline and degrades', async () => {
+ runImpl = okRun;
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ viewRenderTimeoutMs: 25,
+ viewRenderPort: () => new Promise(() => {}), // never settles
+ });
+ expect(r.renderDegraded).toBe(true);
+ expect(r.renderDegradedReason).toContain('timed out after 25ms');
+ expect(r.viewsRendererId).toMatch(/^cpu-raster:/);
+ expect(r.views).toBeInstanceOf(Buffer);
+ });
+
+ test('B4: undecodable or missing port PNGs degrade instead of throwing', async () => {
+ runImpl = okRun;
+ const garbage = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ viewRenderPort: async () => ({
+ ok: true,
+ rendererId: 'dawn-vulkan:test-gpu:1.0',
+ viewsPng: Array.from({ length: 6 }, () => new Uint8Array([1, 2, 3])),
+ }),
+ });
+ expect(garbage.renderDegraded).toBe(true);
+ expect(garbage.renderDegradedReason).toContain('bad signature');
+ expect(garbage.views).toBeInstanceOf(Buffer);
+
+ const empty = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ viewRenderPort: async () => ({ ok: true, rendererId: 'dawn-vulkan:test-gpu:1.0' }),
+ });
+ expect(empty.renderDegraded).toBe(true);
+ expect(empty.renderDegradedReason).toContain('returned 0 view PNGs, expected 6');
+ });
+
+ test('B4: a port returning fewer PNGs than requested degrades instead of shrinking the grid', async () => {
+ runImpl = okRun;
+ const viewsPng = await stubViewPngs();
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ viewRenderPort: async () => ({
+ ok: true,
+ rendererId: 'dawn-vulkan:test-gpu:1.0',
+ viewsPng: viewsPng.slice(0, 3),
+ }),
+ });
+ expect(r.renderDegraded).toBe(true);
+ expect(r.renderDegradedReason).toContain('returned 3 view PNGs, expected 6');
+ expect(r.viewsRendererId).toMatch(/^cpu-raster:/);
+ expect(r.views).toBeInstanceOf(Buffer);
+ });
+
+ test('B4: the port receives a copy of the GLB bytes, not a live alias', async () => {
+ runImpl = okRun;
+ const viewsPng = await stubViewPngs();
+ let seen: Uint8Array | undefined;
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ viewRenderPort: async (req) => {
+ seen = req.glb;
+ req.glb.fill(0); // a hostile/buggy port scribbling on its input
+ return { ok: true, rendererId: 'dawn-vulkan:test-gpu:1.0', viewsPng };
+ },
+ });
+ expect(seen!.every((b) => b === 0)).toBe(true);
+ // The returned artifact is untouched: still a valid GLB with the magic intact.
+ expect(r.glb.readUInt32LE(0)).toBe(0x46546c67);
+ });
+});
diff --git a/src/agent/generate.ts b/src/agent/generate.ts
index 3e139dc2..b35637df 100644
--- a/src/agent/generate.ts
+++ b/src/agent/generate.ts
@@ -15,6 +15,10 @@
* `@strands-agents/sdk` dependency never enters the browser/editor bundle graph.
*/
import { renderGLB, type KilnCodeMeta, type RenderResult } from '../render';
+import type { PbrRenderPort } from '../composer/render-port';
+import { resolveGridViews } from '../views/raster';
+import { compositeViewPngGrid } from '../views/grid';
+import { CPU_RASTER_RENDERER_ID } from '../views/renderer-id';
import type { AssetStyle } from '../prompt';
import { createAssetIntentV1, type AssetCategory, type AssetIntentV1 } from '../contracts';
import { runKilnAgent, type RefineMode, type KilnKnowhow, type KilnInputImage } from './run';
@@ -64,6 +68,14 @@ export interface GenerateKilnAssetOptions {
/** Also rasterize the final asset into the six-view grid PNG (`result.views`).
* Best-effort: a views failure never fails the run. Default false. */
captureViews?: boolean;
+ /** OPTIONAL host PBR renderer (GLB bytes -> per-view PNGs). Only consulted when
+ * `captureViews` is on: the already-produced GLB bytes are routed to the port
+ * and its per-view PNGs are composited into the same 3x2 grid the CPU path
+ * emits. ANY failure/timeout degrades to the CPU rasterizer (never fails the
+ * run; see `renderDegraded`). Absent = byte-identical CPU behavior. */
+ viewRenderPort?: PbrRenderPort;
+ /** Deadline for one `viewRenderPort` call in ms. Default 8000. */
+ viewRenderTimeoutMs?: number;
/** Style anchor: a complete Kiln program rendered as "## Reference Asset" for
* FRESH generation (ignored on refine). ~5-15k input tokens/run, mostly
* absorbed by prompt caching when reused across a batch. */
@@ -102,6 +114,14 @@ export interface GenerateKilnAssetResult {
salvageError?: string;
/** Six-view grid PNG of the final asset (only when `captureViews` was set and the render succeeded). */
views?: Buffer;
+ /** Honest producer of `views` (only when `viewRenderPort` was supplied): the
+ * port's rendererId on success, else the CPU rasterizer's deterministic id. */
+ viewsRendererId?: string;
+ /** Only when `viewRenderPort` was supplied: false when the port produced the
+ * views, true when the run fell back to the CPU rasterizer. */
+ renderDegraded?: boolean;
+ /** Why the port was bypassed (rejection, ok:false, timeout, bad PNGs). */
+ renderDegradedReason?: string;
/** Automatic trusted character skeleton/motion captures, when applicable. */
diagnosticViews?: NonNullable<RenderResult['diagnosticViews']>;
materialRecipeApplications?: NonNullable<RenderResult['materialRecipeApplications']>;
@@ -174,6 +194,69 @@ export async function generateKilnCodeAgent(opts: {
};
}
+const DEFAULT_VIEW_RENDER_TIMEOUT_MS = 8000;
+
+type PortViewsOutcome =
+ | { ok: true; png: Buffer; rendererId: string }
+ | { ok: false; reason: string };
+
+/**
+ * Call the host view-render port with the ALREADY-PRODUCED GLB bytes and
+ * composite its per-view PNGs into the same 3x2 grid the CPU path emits.
+ *
+ * This shell is NOT a render compute path: the deadline is a plain timer (no
+ * Date.now() enters any rasterizer), and every failure mode — thrown/rejected
+ * port, ok:false, timeout, missing rendererId, undecodable or mismatched PNGs —
+ * returns `{ ok: false, reason }` so the caller degrades to the CPU rasterizer
+ * instead of failing the generation.
+ */
+async function captureViewsViaPort(
+ port: PbrRenderPort,
+ glb: Buffer,
+ timeoutMs: number,
+): Promise<PortViewsOutcome> {
+ // Same views + cell size as the CPU grid default, so the composited layout
+ // matches renderCodeViewGrid (H-33 env variant included).
+ const views = resolveGridViews(process.env['KILN_GRID_VARIANT']);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const deadline = new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(`view render port timed out after ${timeoutMs}ms`)),
+ timeoutMs,
+ );
+ });
+ const result = await Promise.race([
+ port({
+ // Copy, not alias: a buggy port implementation must not be able to
+ // mutate the render.glb bytes returned as the generation artifact.
+ glb: Uint8Array.from(glb),
+ viewDirs: views.map((v) => [...v.dir] as [number, number, number]),
+ size: 384,
+ }),
+ deadline,
+ ]);
+ if (!result?.ok) {
+ return { ok: false, reason: result?.error ?? 'view render port returned ok: false' };
+ }
+ if (typeof result.rendererId !== 'string' || !result.rendererId.trim()) {
+ return { ok: false, reason: 'view render port returned no rendererId' };
+ }
+ if (!result.viewsPng || result.viewsPng.length !== views.length) {
+ return {
+ ok: false,
+ reason: `view render port returned ${result.viewsPng?.length ?? 0} view PNGs, expected ${views.length}`,
+ };
+ }
+ const grid = compositeViewPngGrid(result.viewsPng);
+ return { ok: true, png: grid.png, rendererId: result.rendererId };
+ } catch (err) {
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+}
+
/**
* Run one Kiln agent generation end-to-end: model -> tool loop -> GLB render.
* Throws on a hard failure (agent error / no code / render failure); non-fatal
@@ -221,12 +304,38 @@ export async function generateKilnAsset(
// Best-effort views artifact: what the vision loop / review UIs show.
// Never fails the run — a rasterizer error just drops the sidecar.
let views: Buffer | undefined;
+ let viewsRendererId: string | undefined;
+ let renderDegraded: boolean | undefined;
+ let renderDegradedReason: string | undefined;
if (opts.captureViews) {
- try {
- const { renderCodeViewGrid } = await import('../views');
- views = (await renderCodeViewGrid(agent.code)).png;
- } catch {
- views = undefined;
+ // B3b: an injected host PBR renderer sees the already-produced GLB bytes
+ // (never re-executes the program). B4: ANY port failure degrades to the CPU
+ // rasterizer below — the GPU being unavailable can never fail a generation.
+ if (opts.viewRenderPort) {
+ const port = await captureViewsViaPort(
+ opts.viewRenderPort,
+ render.glb,
+ opts.viewRenderTimeoutMs ?? DEFAULT_VIEW_RENDER_TIMEOUT_MS,
+ );
+ if (port.ok) {
+ views = port.png;
+ viewsRendererId = port.rendererId;
+ renderDegraded = false;
+ } else {
+ renderDegraded = true;
+ renderDegradedReason = port.reason;
+ }
+ }
+ if (!views) {
+ try {
+ const { renderCodeViewGrid } = await import('../views');
+ views = (await renderCodeViewGrid(agent.code)).png;
+ // Honest producer provenance, but only on the port-enabled path — the
+ // port-absent path stays byte-identical to the historical result shape.
+ if (opts.viewRenderPort) viewsRendererId = CPU_RASTER_RENDERER_ID;
+ } catch {
+ views = undefined;
+ }
}
}
@@ -254,6 +363,9 @@ export async function generateKilnAsset(
...(agent.salvaged ? { salvaged: agent.salvaged } : {}),
...(agent.salvaged && agent.error ? { salvageError: agent.error } : {}),
...(views ? { views } : {}),
+ ...(viewsRendererId ? { viewsRendererId } : {}),
+ ...(renderDegraded !== undefined ? { renderDegraded } : {}),
+ ...(renderDegradedReason ? { renderDegradedReason } : {}),
...(render.diagnosticViews ? { diagnosticViews: render.diagnosticViews } : {}),
...(render.materialRecipeApplications
? { materialRecipeApplications: render.materialRecipeApplications }
diff --git a/src/composer/agent/run.ts b/src/composer/agent/run.ts
index 985013a1..0a07857e 100644
--- a/src/composer/agent/run.ts
+++ b/src/composer/agent/run.ts
@@ -29,7 +29,7 @@ import {
type SceneModelJSON,
} from '../model';
import type { OverlapViolation } from '../overlap';
-import type { SceneRenderPort } from '../render-port';
+import type { PbrRenderPort, SceneRenderPort } from '../render-port';
import { buildComposerUserPrompt, COMPOSER_SYSTEM_PROMPT } from './prompt';
import { type ComposerSink, makeSceneComposerTools, type SceneRenderCandidate } from './tools';
@@ -44,6 +44,11 @@ export interface RunKilnComposerOptions {
/** Host renderer: placements (+ optional cameras) → PNG(s). Injected so the
* composer core stays THREE-free; tests pass a stub returning a fixed PNG. */
render: SceneRenderPort;
+ /** OPTIONAL host PBR renderer seam (GLB bytes → per-view PNGs). Landed as a
+ * seam only: NO default implementation, and no composer tool calls it yet —
+ * absent means the feature is off and the run is byte-identical to today.
+ * Studio wiring is a separate, later change. */
+ pbrRender?: PbrRenderPort;
/** Display name for the scene (used in framing + the serialized program). */
sceneName?: string;
/** Terrain sampler. Default flat ground at y=0; a heightmap drops in unchanged. */
diff --git a/src/composer/render-port.ts b/src/composer/render-port.ts
index f300da59..e25913bf 100644
--- a/src/composer/render-port.ts
+++ b/src/composer/render-port.ts
@@ -35,3 +35,40 @@ export interface SceneRenderResult {
/** Inject this at `runKilnComposer` call time. A build/render failure returns
* `{ ok:false, error }` (no image) so the agent gets a fixable error. */
export type SceneRenderPort = (req: SceneRenderRequest) => Promise<SceneRenderResult>;
+
+/**
+ * PbrRenderRequest — one PBR/beauty render of an ALREADY-PRODUCED GLB.
+ *
+ * The engine never talks to a render service directly: hosts implement
+ * {@link PbrRenderPort} (Studio wires it to its GPU render service; tests inject
+ * stubs). The GPU path is a non-deterministic VIEW producer only — GLB compute
+ * stays deterministic and never depends on this seam.
+ */
+export interface PbrRenderRequest {
+ /** The rendered GLB bytes (route the produced asset; do NOT re-execute programs). */
+ glb: Uint8Array;
+ /** View directions from model center toward the camera, max 12. Omit for the host default. */
+ viewDirs?: [number, number, number][];
+ /** Square per-view cell size in pixels. */
+ size?: number;
+ /** Optional larger single beauty-shot size. */
+ beautySize?: number;
+}
+
+export interface PbrRenderResult {
+ ok: boolean;
+ /** Honest producer identity, e.g. "dawn-vulkan:nvidia-rtx-a4500:NVIDIA: 550.100"
+ * or the CPU fallback's deterministic "cpu-raster:<engine-version>". */
+ rendererId: string;
+ /** One PNG per requested view direction, in request order. */
+ viewsPng?: Uint8Array[];
+ /** The optional beauty shot. */
+ beautyPng?: Uint8Array;
+ /** Host-measured phase timings in milliseconds. */
+ timings?: Record<string, number>;
+ error?: string;
+}
+
+/** Host-supplied PBR renderer seam. Absent everywhere it is optional means the
+ * feature is off and behavior is byte-identical to the CPU-only path. */
+export type PbrRenderPort = (req: PbrRenderRequest) => Promise<PbrRenderResult>;
diff --git a/src/qa/registry.test.ts b/src/qa/registry.test.ts
index da0c0169..586c0ee6 100644
--- a/src/qa/registry.test.ts
+++ b/src/qa/registry.test.ts
@@ -117,6 +117,7 @@ function calibration(
evidenceSha256: calibrationReportEvidenceSha256(report),
frozenAt: '2026-07-09T13:00:00.000Z',
authorizedBy: owner.id,
+ rendererId: 'cpu-raster:legacy',
report,
...options.authorization,
};
@@ -626,6 +627,157 @@ describe('QaRegistry', () => {
).toThrow('permanently capped at warn');
});
+ test('requires a rendererId on promotion evidence and rejects missing/malformed values', () => {
+ // Valid: the checked-in helper stamps legacy evidence and passes.
+ const valid = conformancePromotionAuthorization(
+ 'qa-test-fixtures-v1',
+ 'src/qa/registry.test.ts',
+ TEST_EVIDENCE_SHA,
+ TEST_OWNER,
+ );
+ expect(valid.rendererId).toBe('cpu-raster:legacy');
+ expect(
+ () => new QaRegistry([rule({ id: 'TEST_RENDERER_OK', scope: { kind: 'universal' } })]),
+ ).not.toThrow();
+
+ // Valid: an explicit non-legacy rendererId with a family prefix.
+ expect(
+ () =>
+ new QaRegistry([
+ rule({
+ id: 'TEST_RENDERER_EXPLICIT',
+ scope: { kind: 'universal' },
+ promotion: conformancePromotionAuthorization(
+ 'qa-test-fixtures-v1',
+ 'src/qa/registry.test.ts',
+ TEST_EVIDENCE_SHA,
+ TEST_OWNER,
+ undefined,
+ 'enforce',
+ 'cpu-raster:0.6.0',
+ ),
+ }),
+ ]),
+ ).not.toThrow();
+
+ // Missing rendererId throws with an actionable message.
+ expect(
+ () =>
+ new QaRegistry([
+ rule({
+ id: 'TEST_RENDERER_MISSING',
+ scope: { kind: 'universal' },
+ promotion: {
+ ...valid,
+ rendererId: undefined,
+ } as unknown as QaRule['promotion'],
+ }),
+ ]),
+ ).toThrow('must name its producing rendererId');
+ expect(
+ () =>
+ new QaRegistry([
+ rule({
+ id: 'TEST_RENDERER_EMPTY',
+ scope: { kind: 'universal' },
+ promotion: { ...valid, rendererId: ' ' },
+ }),
+ ]),
+ ).toThrow('must name its producing rendererId');
+
+ // Malformed prefix (no family ':' separator / illegal characters) throws.
+ for (const bad of ['cpu-raster', 'CPU-RASTER:legacy', 'gpu_render:x', ':nvidia']) {
+ expect(
+ () =>
+ new QaRegistry([
+ rule({
+ id: 'TEST_RENDERER_MALFORMED',
+ scope: { kind: 'universal' },
+ promotion: { ...valid, rendererId: bad },
+ }),
+ ]),
+ bad,
+ ).toThrow('renderer family prefix');
+ }
+
+ // Calibration evidence carries the same requirement.
+ const owner: QaRuleOwner = { id: 'qa-delegate:renderer', authority: 'delegated' };
+ const noRenderer = calibration(owner, 'TEST_RENDERER_CALIBRATION', {
+ authorization: { rendererId: 'not-prefixed' },
+ });
+ expect(
+ () =>
+ new QaRegistry([
+ rule({
+ id: 'TEST_RENDERER_CALIBRATION',
+ scope: { kind: 'universal' },
+ ruleClass: 'heuristic',
+ owner,
+ defaultMode: 'warn',
+ promotion: noRenderer,
+ }),
+ ]),
+ ).toThrow('renderer family prefix');
+ });
+
+ test('appearance rules register at observe but can never exceed it', () => {
+ const owner: QaRuleOwner = { id: 'qa-delegate:appearance', authority: 'delegated' };
+ const appearance = rule({
+ id: 'TEST_APPEARANCE',
+ scope: { kind: 'universal' },
+ ruleClass: 'appearance',
+ owner,
+ defaultMode: 'observe',
+ promotion: undefined,
+ });
+ const registry = new QaRegistry([appearance]);
+ expect(registry.run(context).findings[0]?.disposition).toBe('observe');
+
+ // Off also registers (below observe).
+ expect(
+ () =>
+ new QaRegistry([
+ rule({
+ id: 'TEST_APPEARANCE_OFF',
+ scope: { kind: 'universal' },
+ ruleClass: 'appearance',
+ owner,
+ defaultMode: 'off',
+ promotion: undefined,
+ }),
+ ]),
+ ).not.toThrow();
+
+ // Any mode above observe throws at registration — even with calibration
+ // evidence a heuristic could use (stricter than the VLM warn cap).
+ for (const defaultMode of ['warn', 'enforce'] as const) {
+ expect(
+ () =>
+ new QaRegistry([
+ rule({
+ id: 'TEST_APPEARANCE_PROMOTED',
+ scope: { kind: 'universal' },
+ ruleClass: 'appearance',
+ owner,
+ defaultMode,
+ promotion: calibration(owner, 'TEST_APPEARANCE_PROMOTED', {
+ authorizedMode: defaultMode,
+ }),
+ }),
+ ]),
+ defaultMode,
+ ).toThrow('cannot exceed observe');
+ }
+
+ // A runtime policy escalation is rejected the same way.
+ expect(() => registry.run(context, { byRule: { TEST_APPEARANCE: 'warn' } })).toThrow(
+ 'cannot exceed observe',
+ );
+ expect(() => registry.describePolicy({ byRule: { TEST_APPEARANCE: 'enforce' } })).toThrow(
+ 'cannot exceed observe',
+ );
+ });
+
test('rejects unknown runtime rollout modes before blocker severity can survive', () => {
const registry = new QaRegistry([
rule({ id: 'TEST_RUNTIME_MODE', scope: { kind: 'universal' } }),
diff --git a/src/qa/registry.ts b/src/qa/registry.ts
index a10af48b..3255e3f5 100644
--- a/src/qa/registry.ts
+++ b/src/qa/registry.ts
@@ -6,9 +6,12 @@ import type { QaContext, QaFinding } from './types';
export const QA_RULE_MODES = ['off', 'observe', 'warn', 'enforce'] as const;
export type QaRuleMode = (typeof QA_RULE_MODES)[number];
-export const QA_RULE_CLASSES = ['exact', 'heuristic', 'vlm'] as const;
+export const QA_RULE_CLASSES = ['exact', 'heuristic', 'vlm', 'appearance'] as const;
export type QaRuleClass = (typeof QA_RULE_CLASSES)[number];
+/** rendererId stamped onto promotion evidence produced before renderer identity existed. */
+export const LEGACY_CPU_RASTER_RENDERER_ID = 'cpu-raster:legacy' as const;
+
/** Cross-repo identities frozen by QA-023/026. The exact matrix must keep Studio in lock-step. */
export const QA_026_CALIBRATION_THRESHOLD_ID =
'kiln.asset-quality-calibration.thresholds.v1' as const;
@@ -58,6 +61,10 @@ export interface QaConformancePromotionAuthorization {
evidenceSha256: string;
frozenAt: string;
authorizedBy: string;
+ /** Renderer that produced the evidence: a `<family>:` prefix plus identity, e.g.
+ * `cpu-raster:0.6.0` or `dawn-vulkan:nvidia-rtx-a4500:...`. Evidence frozen before
+ * renderer identity existed carries {@link LEGACY_CPU_RASTER_RENDERER_ID}. */
+ rendererId: string;
}
export interface QaCalibrationPromotionAuthorization {
@@ -67,6 +74,8 @@ export interface QaCalibrationPromotionAuthorization {
evidenceSha256: string;
frozenAt: string;
authorizedBy: string;
+ /** Renderer that produced the evidence (same format as conformance evidence). */
+ rendererId: string;
report: QaCalibrationReportEvidenceV1;
}
@@ -153,6 +162,10 @@ export function conformancePromotionAuthorization(
owner: QaRuleOwner = KILN_ENGINE_QA_OWNER,
frozenAt = '2026-07-09T00:00:00.000Z',
authorizedMode: 'warn' | 'enforce' = 'enforce',
+ /** Default stamps pre-existing frozen evidence honestly: it was produced by the
+ * CPU rasterizer before renderer identity was recorded. New evidence generated
+ * under a known renderer must pass that renderer's real id explicitly. */
+ rendererId: string = LEGACY_CPU_RASTER_RENDERER_ID,
): QaConformancePromotionAuthorization {
return {
basis: 'conformance',
@@ -162,6 +175,7 @@ export function conformancePromotionAuthorization(
evidenceSha256,
frozenAt,
authorizedBy: owner.id,
+ rendererId,
};
}
@@ -210,6 +224,8 @@ export interface QaRulePolicyDecision {
const SHA256_PATTERN = /^[a-f0-9]{64}$/;
const OWNER_ID_PATTERN = /^[a-z0-9][a-z0-9:._/-]*$/;
+/** Renderer family prefix + ':' — e.g. "cpu-raster:0.6.0", "dawn-vulkan:nvidia-...". */
+const RENDERER_ID_PATTERN = /^[a-z0-9-]+:/;
function evidenceId(promotion: QaPromotionAuthorization): string {
return promotion.basis === 'conformance' ? promotion.fixtureSetId : promotion.packetId;
@@ -412,6 +428,18 @@ function assertPromotionShape(rule: QaRule, promotion: QaPromotionAuthorization)
if (!SHA256_PATTERN.test(promotion.evidenceSha256)) {
throw new TypeError(`QA rule ${rule.id} promotion evidence must have a lowercase SHA-256`);
}
+ if (typeof promotion.rendererId !== 'string' || !promotion.rendererId.trim()) {
+ throw new TypeError(
+ `QA rule ${rule.id} promotion evidence must name its producing rendererId ` +
+ `(e.g. "cpu-raster:0.6.0"; pre-existing evidence uses "${LEGACY_CPU_RASTER_RENDERER_ID}")`,
+ );
+ }
+ if (!RENDERER_ID_PATTERN.test(promotion.rendererId)) {
+ throw new TypeError(
+ `QA rule ${rule.id} promotion rendererId "${promotion.rendererId}" must start with a ` +
+ `renderer family prefix followed by ':' (e.g. "cpu-raster:", "dawn-vulkan:")`,
+ );
+ }
if (!Number.isFinite(Date.parse(promotion.frozenAt))) {
throw new TypeError(`QA rule ${rule.id} promotion evidence must have a frozenAt timestamp`);
}
@@ -440,6 +468,15 @@ function assertModeAuthorized(rule: QaRule, mode: QaRuleMode): void {
return;
}
+ // Stricter than the VLM warn cap below: appearance evidence derives from
+ // rendered/GPU output, which is a non-deterministic VIEW producer — findings
+ // may inform, never gate.
+ if (rule.ruleClass === 'appearance') {
+ throw new Error(
+ `Appearance QA rule ${rule.id} cannot exceed observe; appearance findings derive from rendered output and are never gates`,
+ );
+ }
+
const promotion = rule.promotion;
if (!promotion) {
throw new Error(
diff --git a/src/views/__tests__/grid.test.ts b/src/views/__tests__/grid.test.ts
new file mode 100644
index 00000000..7d0cbe7f
--- /dev/null
+++ b/src/views/__tests__/grid.test.ts
@@ -0,0 +1,240 @@
+/**
+ * decodePng + grid compositor + CPU renderer id — the PbrRenderPort support
+ * seam. PNGs for the decoder tests are hand-built per the PNG spec (all five
+ * filter types, RGB + RGBA) so every unfilter branch is exercised; the decoder
+ * deliberately ignores CRCs, so the builder writes zeroed ones.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { deflateSync } from 'node:zlib';
+
+import { decodePng, encodePng } from '../png';
+import { compositeCellGrid, compositeViewPngGrid, GRID_COLS, PAD, PAD_COLOR } from '../grid';
+import { CPU_RASTER_RENDERER_ID } from '../renderer-id';
+
+const SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
+
+function chunk(type: string, data: Uint8Array): Buffer {
+ const out = Buffer.alloc(8 + data.length + 4); // CRC left zero — not verified
+ out.writeUInt32BE(data.length, 0);
+ out.write(type, 4, 'ascii');
+ out.set(data, 8);
+ return out;
+}
+
+/** Forward-filter one scanline (the encoder side of decodePng's unfilter). */
+function filterRow(cur: Uint8Array, prior: Uint8Array, filter: number, bpp: number): Uint8Array {
+ const out = new Uint8Array(cur.length);
+ for (let i = 0; i < cur.length; i++) {
+ const x = cur[i]!;
+ const a = i >= bpp ? cur[i - bpp]! : 0;
+ const b = prior[i]!;
+ const c = i >= bpp ? prior[i - bpp]! : 0;
+ let v: number;
+ if (filter === 0) v = x;
+ else if (filter === 1) v = x - a;
+ else if (filter === 2) v = x - b;
+ else if (filter === 3) v = x - ((a + b) >> 1);
+ else {
+ const p = a + b - c;
+ const pa = Math.abs(p - a);
+ const pb = Math.abs(p - b);
+ const pc = Math.abs(p - c);
+ v = x - (pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
+ }
+ out[i] = v & 0xff;
+ }
+ return out;
+}
+
+function buildPng(
+ pixels: Uint8Array,
+ width: number,
+ height: number,
+ channels: 3 | 4,
+ filters: number[],
+): Buffer {
+ const stride = width * channels;
+ const raw = Buffer.alloc(height * (1 + stride));
+ let prior: Uint8Array = new Uint8Array(stride);
+ for (let y = 0; y < height; y++) {
+ const f = filters[y % filters.length]!;
+ const cur = pixels.subarray(y * stride, (y + 1) * stride);
+ raw[y * (1 + stride)] = f;
+ raw.set(filterRow(cur, prior, f, channels), y * (1 + stride) + 1);
+ prior = cur;
+ }
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 8;
+ ihdr[9] = channels === 4 ? 6 : 2;
+ return Buffer.concat([
+ Buffer.from(SIG),
+ chunk('IHDR', ihdr),
+ chunk('IDAT', deflateSync(raw)),
+ chunk('IEND', new Uint8Array(0)),
+ ]);
+}
+
+/** Deterministic pseudo-gradient pixel data. */
+function pixels(width: number, height: number, channels: number): Uint8Array {
+ const out = new Uint8Array(width * height * channels);
+ for (let i = 0; i < out.length; i++) out[i] = (i * 37 + 11) % 256;
+ return out;
+}
+
+describe('decodePng', () => {
+ test('round-trips encodePng output', () => {
+ const rgb = pixels(5, 4, 3);
+ const decoded = decodePng(encodePng(rgb, 5, 4));
+ expect(decoded.width).toBe(5);
+ expect(decoded.height).toBe(4);
+ expect(decoded.rgb).toEqual(rgb);
+ });
+
+ test.each([[0], [1], [2], [3], [4]])('unfilters RGB scanlines with filter type %i', (f) => {
+ const rgb = pixels(6, 5, 3);
+ expect(decodePng(buildPng(rgb, 6, 5, 3, [f])).rgb).toEqual(rgb);
+ });
+
+ test('unfilters mixed filter types across rows', () => {
+ const rgb = pixels(4, 5, 3);
+ expect(decodePng(buildPng(rgb, 4, 5, 3, [0, 1, 2, 3, 4])).rgb).toEqual(rgb);
+ });
+
+ test('decodes RGBA and drops the alpha channel', () => {
+ const rgba = pixels(3, 3, 4);
+ const expected = new Uint8Array(3 * 3 * 3);
+ for (let p = 0; p < 9; p++) {
+ expected[p * 3] = rgba[p * 4]!;
+ expected[p * 3 + 1] = rgba[p * 4 + 1]!;
+ expected[p * 3 + 2] = rgba[p * 4 + 2]!;
+ }
+ expect(decodePng(buildPng(rgba, 3, 3, 4, [1, 4])).rgb).toEqual(expected);
+ });
+
+ test('rejects non-PNG bytes, unsupported formats, and corrupt streams', () => {
+ expect(() => decodePng(new Uint8Array([1, 2, 3]))).toThrow('bad signature');
+
+ const rgb = pixels(2, 2, 3);
+ const png = buildPng(rgb, 2, 2, 3, [0]);
+
+ const depth16 = Buffer.from(png);
+ depth16[8 + 8 + 8] = 16; // IHDR bit depth
+ expect(() => decodePng(depth16)).toThrow('unsupported PNG');
+
+ const paletted = Buffer.from(png);
+ paletted[8 + 8 + 9] = 3; // IHDR color type
+ expect(() => decodePng(paletted)).toThrow('unsupported PNG');
+
+ const interlaced = Buffer.from(png);
+ interlaced[8 + 8 + 12] = 1; // IHDR interlace
+ expect(() => decodePng(interlaced)).toThrow('unsupported PNG');
+
+ const badFilter = pixels(2, 2, 3);
+ const raw = Buffer.alloc(2 * (1 + 6));
+ raw[0] = 7; // unknown filter type
+ raw.set(badFilter.subarray(0, 6), 1);
+ raw[7] = 0;
+ raw.set(badFilter.subarray(6, 12), 8);
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(2, 0);
+ ihdr.writeUInt32BE(2, 4);
+ ihdr[8] = 8;
+ ihdr[9] = 2;
+ const badFilterPng = Buffer.concat([
+ Buffer.from(SIG),
+ chunk('IHDR', ihdr),
+ chunk('IDAT', deflateSync(raw)),
+ chunk('IEND', new Uint8Array(0)),
+ ]);
+ expect(() => decodePng(badFilterPng)).toThrow('unknown filter type');
+
+ const shortRaw = Buffer.concat([
+ Buffer.from(SIG),
+ chunk('IHDR', ihdr),
+ chunk('IDAT', deflateSync(Buffer.from([0, 1, 2]))),
+ chunk('IEND', new Uint8Array(0)),
+ ]);
+ expect(() => decodePng(shortRaw)).toThrow('raw bytes');
+
+ expect(() => decodePng(Buffer.from(SIG))).toThrow('missing IHDR or IDAT');
+
+ // Cut mid-IDAT: the chunk header fits but its declared data does not.
+ const idatStart = 8 + 8 + 13 + 4; // signature + IHDR chunk
+ const truncated = png.subarray(0, idatStart + 8 + 2);
+ expect(() => decodePng(truncated)).toThrow('truncated chunk');
+ });
+});
+
+describe('compositeCellGrid', () => {
+ test('lays cells into the padded 3-column grid with the gutter color', () => {
+ const size = 2;
+ const red = new Uint8Array(size * size * 3);
+ for (let p = 0; p < size * size; p++) red[p * 3] = 255;
+ const green = new Uint8Array(size * size * 3);
+ for (let p = 0; p < size * size; p++) green[p * 3 + 1] = 255;
+
+ const { rgb, width, height } = compositeCellGrid([red, green], size);
+ expect(width).toBe(GRID_COLS * size + (GRID_COLS + 1) * PAD);
+ expect(height).toBe(size + 2 * PAD);
+
+ // Gutter pixel at (0,0).
+ expect([rgb[0], rgb[1], rgb[2]]).toEqual([...PAD_COLOR]);
+ // Cell 0 top-left pixel at (PAD, PAD) is red.
+ const c0 = (PAD * width + PAD) * 3;
+ expect([rgb[c0], rgb[c0 + 1], rgb[c0 + 2]]).toEqual([255, 0, 0]);
+ // Cell 1 top-left pixel at (PAD + (size+PAD), PAD) is green.
+ const c1 = (PAD * width + PAD + size + PAD) * 3;
+ expect([rgb[c1], rgb[c1 + 1], rgb[c1 + 2]]).toEqual([0, 255, 0]);
+ });
+
+ test('six cells make the 3x2 layout; bad input throws', () => {
+ const size = 4;
+ const cells = Array.from({ length: 6 }, () => new Uint8Array(size * size * 3));
+ const grid = compositeCellGrid(cells, size);
+ expect(grid.width).toBe(3 * size + 4 * PAD);
+ expect(grid.height).toBe(2 * size + 3 * PAD);
+
+ expect(() => compositeCellGrid([], size)).toThrow('no cells');
+ expect(() => compositeCellGrid([new Uint8Array(5)], size)).toThrow('must be');
+ });
+});
+
+describe('compositeViewPngGrid', () => {
+ test('decodes per-view PNGs and composites the same 3x2 layout as the CPU grid', () => {
+ const size = 8;
+ const views = Array.from({ length: 6 }, (_, i) => {
+ const rgb = new Uint8Array(size * size * 3);
+ for (let p = 0; p < size * size; p++) rgb[p * 3] = i * 40;
+ return new Uint8Array(encodePng(rgb, size, size));
+ });
+ const grid = compositeViewPngGrid(views);
+ expect(grid.cellSize).toBe(size);
+ expect(grid.width).toBe(3 * size + 4 * PAD);
+ expect(grid.height).toBe(2 * size + 3 * PAD);
+
+ // Round-trip the composited PNG and spot-check cell 3 (row 2, col 1).
+ const decoded = decodePng(grid.png);
+ const p3 = ((PAD + size + PAD) * grid.width + PAD) * 3;
+ expect(decoded.rgb[p3]).toBe(120);
+ });
+
+ test('rejects an empty view list and mismatched cell sizes', () => {
+ expect(() => compositeViewPngGrid([])).toThrow('no views');
+ const a = new Uint8Array(encodePng(new Uint8Array(4 * 4 * 3), 4, 4));
+ const b = new Uint8Array(encodePng(new Uint8Array(8 * 8 * 3), 8, 8));
+ expect(() => compositeViewPngGrid([a, b])).toThrow('square');
+ });
+});
+
+describe('CPU_RASTER_RENDERER_ID', () => {
+ test('is the deterministic cpu-raster:<engine-version> constant', () => {
+ const pkg = JSON.parse(
+ readFileSync(new URL('../../../package.json', import.meta.url), 'utf8'),
+ ) as { version: string };
+ expect(CPU_RASTER_RENDERER_ID).toBe(`cpu-raster:${pkg.version}`);
+ expect(CPU_RASTER_RENDERER_ID).toMatch(/^[a-z0-9-]+:/);
+ });
+});
diff --git a/src/views/grid.ts b/src/views/grid.ts
new file mode 100644
index 00000000..566ee7ef
--- /dev/null
+++ b/src/views/grid.ts
@@ -0,0 +1,100 @@
+/**
+ * Shared grid compositor for view cells — the single owner of the grid layout
+ * constants (cell padding, gutter color, 3-column default) used by the six-view
+ * grid, the animation strip, and the interior cutaway row. Extracted so the
+ * PbrRenderPort path can composite host-rendered per-view PNGs into the SAME
+ * 3x2 layout the CPU rasterizer produces without duplicating layout math.
+ * Pure and deterministic.
+ */
+
+import { decodePng, encodePng } from './png';
+
+export const PAD = 4;
+export const PAD_COLOR: [number, number, number] = [10, 11, 13];
+/** Default column count of the view grids (3x2 for six views). */
+export const GRID_COLS = 3;
+
+export interface ComposedCellGrid {
+ /** Row-major RGB bytes (width*height*3). */
+ rgb: Uint8Array;
+ width: number;
+ height: number;
+}
+
+/**
+ * Composite equal-size square RGB cells (size*size*3 bytes each) into a padded
+ * row-major grid. `cols` columns; rows grow as needed (6 cells @ 3 cols = 3x2).
+ */
+export function compositeCellGrid(
+ cells: readonly Uint8Array[],
+ size: number,
+ cols: number = GRID_COLS,
+): ComposedCellGrid {
+ if (cells.length === 0) throw new Error('compositeCellGrid: no cells to composite');
+ const rows = Math.ceil(cells.length / cols);
+ const width = cols * size + (cols + 1) * PAD;
+ const height = rows * size + (rows + 1) * PAD;
+
+ const grid = new Uint8Array(width * height * 3);
+ for (let p = 0; p < width * height; p++) {
+ grid[p * 3] = PAD_COLOR[0];
+ grid[p * 3 + 1] = PAD_COLOR[1];
+ grid[p * 3 + 2] = PAD_COLOR[2];
+ }
+
+ for (let i = 0; i < cells.length; i++) {
+ const cell = cells[i]!;
+ if (cell.length !== size * size * 3) {
+ throw new Error(
+ `compositeCellGrid: cell ${i} must be ${size * size * 3} bytes (size ${size}), got ${cell.length}`,
+ );
+ }
+ const col = i % cols;
+ const row = Math.floor(i / cols);
+ const x0 = PAD + col * (size + PAD);
+ const y0 = PAD + row * (size + PAD);
+ for (let y = 0; y < size; y++) {
+ const src = y * size * 3;
+ const dst = ((y0 + y) * width + x0) * 3;
+ grid.set(cell.subarray(src, src + size * 3), dst);
+ }
+ }
+
+ return { rgb: grid, width, height };
+}
+
+export interface ComposedPngGrid {
+ png: Buffer;
+ width: number;
+ height: number;
+ /** The square cell size shared by every view. */
+ cellSize: number;
+}
+
+/**
+ * Decode per-view PNGs (e.g. from a host PbrRenderPort) and composite them into
+ * the same padded 3-column grid layout the CPU six-view path produces. Every
+ * view must be the same square size; unsupported PNG formats or mismatched
+ * sizes throw — the caller treats that as a render-port degrade.
+ */
+export function compositeViewPngGrid(
+ pngs: readonly Uint8Array[],
+ cols: number = GRID_COLS,
+): ComposedPngGrid {
+ if (pngs.length === 0) throw new Error('compositeViewPngGrid: no views to composite');
+ const decoded = pngs.map((png) => decodePng(png));
+ const size = decoded[0]!.width;
+ for (const d of decoded) {
+ if (d.width !== size || d.height !== size) {
+ throw new Error(
+ `compositeViewPngGrid: every view must be a ${size}x${size} square; got ${d.width}x${d.height}`,
+ );
+ }
+ }
+ const { rgb, width, height } = compositeCellGrid(
+ decoded.map((d) => d.rgb),
+ size,
+ cols,
+ );
+ return { png: encodePng(rgb, width, height), width, height, cellSize: size };
+}
diff --git a/src/views/index.ts b/src/views/index.ts
index d3ebc2fc..62f7a010 100644
--- a/src/views/index.ts
+++ b/src/views/index.ts
@@ -22,6 +22,7 @@ import {
type ViewSpec,
} from './raster';
import { encodePng } from './png';
+import { compositeCellGrid } from './grid';
import {
prepareClip,
poseSceneAtTime,
@@ -50,7 +51,11 @@ export {
coverage,
} from './raster';
export type { RasterOptions, ViewSpec, ViewGridVariant } from './raster';
-export { encodePng } from './png';
+export { encodePng, decodePng } from './png';
+export type { DecodedPng } from './png';
+export { compositeCellGrid, compositeViewPngGrid, GRID_COLS } from './grid';
+export type { ComposedCellGrid, ComposedPngGrid } from './grid';
+export { CPU_RASTER_RENDERER_ID } from './renderer-id';
export {
ARCHITECTURE_ROOF_ROLE_PREFIXES,
hasArchitectureRoofRole,
@@ -115,9 +120,6 @@ export {
type PreparedClip,
} from './pose';
-const PAD = 4;
-const PAD_COLOR: [number, number, number] = [10, 11, 13];
-
interface DuckColor {
r: number;
g: number;
@@ -330,38 +332,21 @@ export async function renderViewGrid(
// always wins; unset/unknown env keeps SIX_VIEWS.
const views = opts.views ?? resolveGridViews(process.env['KILN_GRID_VARIANT']);
if (opts.snapPalette?.length) snapSceneToPalette(root, opts.snapPalette);
- const cols = 3;
- const rows = Math.ceil(views.length / cols);
- const width = cols * size + (cols + 1) * PAD;
- const height = rows * size + (rows + 1) * PAD;
-
- const grid = new Uint8Array(width * height * 3);
- for (let i = 0; i < width * height; i++) {
- grid[i * 3] = PAD_COLOR[0];
- grid[i * 3 + 1] = PAD_COLOR[1];
- grid[i * 3 + 2] = PAD_COLOR[2];
- }
const labelScale = Math.max(2, Math.round(size / 96));
+ const cells: Uint8Array[] = [];
for (let vi = 0; vi < views.length; vi++) {
const cell = rasterizeView(root, views[vi]!.dir, { size, backfaceCull: opts.backfaceCull });
// H-30: stamp the view name + axis gnomon into the cell (small, corner-
// anchored, away from the centered silhouette — SeeAct caveat).
stampLabel(cell, size, size, labelScale, labelScale, views[vi]!.name, labelScale);
stampAxisGnomon(cell, size, views[vi]!.dir);
- const col = vi % cols;
- const row = Math.floor(vi / cols);
- const x0 = PAD + col * (size + PAD);
- const y0 = PAD + row * (size + PAD);
- for (let y = 0; y < size; y++) {
- const src = y * size * 3;
- const dst = ((y0 + y) * width + x0) * 3;
- grid.set(cell.subarray(src, src + size * 3), dst);
- }
+ cells.push(cell);
}
+ const { rgb, width, height } = compositeCellGrid(cells, size);
return {
- png: encodePng(grid, width, height),
+ png: encodePng(rgb, width, height),
width,
height,
views: views.map((v) => v.name),
@@ -546,28 +531,8 @@ export async function renderClipAnimation(
}
// Compose into a 3x2 grid (same layout as the six-view grid).
- const cols = 3;
- const rows = Math.ceil(cells.length / cols);
- const width = cols * size + (cols + 1) * PAD;
- const height = rows * size + (rows + 1) * PAD;
- const grid = new Uint8Array(width * height * 3);
- for (let p = 0; p < width * height; p++) {
- grid[p * 3] = PAD_COLOR[0];
- grid[p * 3 + 1] = PAD_COLOR[1];
- grid[p * 3 + 2] = PAD_COLOR[2];
- }
- for (let i = 0; i < cells.length; i++) {
- const col = i % cols;
- const row = Math.floor(i / cols);
- const x0 = PAD + col * (size + PAD);
- const y0 = PAD + row * (size + PAD);
- for (let y = 0; y < size; y++) {
- const src = y * size * 3;
- const dst = ((y0 + y) * width + x0) * 3;
- grid.set(cells[i]!.subarray(src, src + size * 3), dst);
- }
- }
- return { ...baseMeta, width, height, png: encodePng(grid, width, height) };
+ const { rgb, width, height } = compositeCellGrid(cells, size);
+ return { ...baseMeta, width, height, png: encodePng(rgb, width, height) };
}
// =============================================================================
@@ -656,27 +621,10 @@ export async function renderInteriorGrid(
}
// Single-row grid (reuse the six-view PAD/PAD_COLOR layout).
- const cols = INTERIOR_VIEWS.length;
- const width = cols * size + (cols + 1) * PAD;
- const height = size + 2 * PAD;
- const grid = new Uint8Array(width * height * 3);
- for (let p = 0; p < width * height; p++) {
- grid[p * 3] = PAD_COLOR[0];
- grid[p * 3 + 1] = PAD_COLOR[1];
- grid[p * 3 + 2] = PAD_COLOR[2];
- }
- for (let i = 0; i < cells.length; i++) {
- const x0 = PAD + i * (size + PAD);
- const y0 = PAD;
- for (let y = 0; y < size; y++) {
- const src = y * size * 3;
- const dst = ((y0 + y) * width + x0) * 3;
- grid.set(cells[i]!.subarray(src, src + size * 3), dst);
- }
- }
+ const { rgb, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);
return {
- png: encodePng(grid, width, height),
+ png: encodePng(rgb, width, height),
width,
height,
views: INTERIOR_VIEWS.map((v) => v.name),
diff --git a/src/views/png.ts b/src/views/png.ts
index c395d111..c7ad508f 100644
--- a/src/views/png.ts
+++ b/src/views/png.ts
@@ -1,12 +1,14 @@
/**
- * Minimal PNG encoder (8-bit RGB, no interlace) over node:zlib.
+ * Minimal PNG encoder + decoder (8-bit truecolor, no interlace) over node:zlib.
*
* Deliberately dependency-free: this module must load inside the kiln-studio
* agent-runtime container and under Bun without native modules (sharp is NOT
- * acceptable here). ~70 lines is cheaper than a dependency.
+ * acceptable here). ~150 lines is cheaper than a dependency. The decoder exists
+ * so host-rendered per-view PNGs (PbrRenderPort) can be composited into the same
+ * grids the CPU rasterizer emits; unsupported formats throw and callers degrade.
*/
-import { deflateSync } from 'node:zlib';
+import { deflateSync, inflateSync } from 'node:zlib';
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
@@ -68,3 +70,106 @@ export function encodePng(rgb: Uint8Array, width: number, height: number): Buffe
chunk('IEND', new Uint8Array(0)),
]);
}
+
+const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] as const;
+
+export interface DecodedPng {
+ /** Row-major RGB bytes (width*height*3); RGBA sources drop alpha. */
+ rgb: Uint8Array;
+ width: number;
+ height: number;
+}
+
+/**
+ * Decode an 8-bit non-interlaced truecolor PNG (color type 2 RGB or 6 RGBA,
+ * filters 0-4) into a row-major RGB buffer. Anything else — palettes, 16-bit,
+ * grayscale, Adam7 — throws; the port-calling shell treats that as a degrade.
+ */
+export function decodePng(png: Uint8Array): DecodedPng {
+ if (png.length < 8 || PNG_SIGNATURE.some((b, i) => png[i] !== b)) {
+ throw new Error('decodePng: not a PNG (bad signature)');
+ }
+ const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
+ let width = 0;
+ let height = 0;
+ let bitDepth = 0;
+ let colorType = 0;
+ let interlace = 0;
+ let sawIhdr = false;
+ const idat: Buffer[] = [];
+
+ let off = 8;
+ while (off + 8 <= png.length) {
+ const len = view.getUint32(off);
+ const type = String.fromCharCode(png[off + 4]!, png[off + 5]!, png[off + 6]!, png[off + 7]!);
+ const dataStart = off + 8;
+ if (dataStart + len + 4 > png.length) throw new Error('decodePng: truncated chunk');
+ if (type === 'IHDR') {
+ width = view.getUint32(dataStart);
+ height = view.getUint32(dataStart + 4);
+ bitDepth = png[dataStart + 8]!;
+ colorType = png[dataStart + 9]!;
+ interlace = png[dataStart + 12]!;
+ sawIhdr = true;
+ } else if (type === 'IDAT') {
+ idat.push(Buffer.from(png.subarray(dataStart, dataStart + len)));
+ } else if (type === 'IEND') {
+ break;
+ }
+ off = dataStart + len + 4;
+ }
+
+ if (!sawIhdr || idat.length === 0) throw new Error('decodePng: missing IHDR or IDAT');
+ if (bitDepth !== 8 || (colorType !== 2 && colorType !== 6) || interlace !== 0) {
+ throw new Error(
+ `decodePng: unsupported PNG (bitDepth ${bitDepth}, colorType ${colorType}, interlace ` +
+ `${interlace}); only 8-bit non-interlaced RGB/RGBA is supported`,
+ );
+ }
+ if (width <= 0 || height <= 0) throw new Error('decodePng: empty image');
+
+ const channels = colorType === 6 ? 4 : 3;
+ const stride = width * channels;
+ const raw = inflateSync(idat.length === 1 ? idat[0]! : Buffer.concat(idat));
+ if (raw.length !== height * (1 + stride)) {
+ throw new Error(`decodePng: expected ${height * (1 + stride)} raw bytes, got ${raw.length}`);
+ }
+
+ const rgb = new Uint8Array(width * height * 3);
+ const cur = new Uint8Array(stride);
+ const prior = new Uint8Array(stride); // zero-filled: the row above row 0
+ for (let y = 0; y < height; y++) {
+ const rowStart = y * (1 + stride);
+ const filter = raw[rowStart]!;
+ if (filter > 4) throw new Error(`decodePng: unknown filter type ${filter}`);
+ for (let i = 0; i < stride; i++) {
+ const x = raw[rowStart + 1 + i]!;
+ const a = i >= channels ? cur[i - channels]! : 0; // left
+ const b = prior[i]!; // up
+ let value: number;
+ if (filter === 0) value = x;
+ else if (filter === 1) value = x + a;
+ else if (filter === 2) value = x + b;
+ else if (filter === 3) value = x + ((a + b) >> 1);
+ else {
+ // Paeth
+ const c = i >= channels ? prior[i - channels]! : 0; // up-left
+ const p = a + b - c;
+ const pa = Math.abs(p - a);
+ const pb = Math.abs(p - b);
+ const pc = Math.abs(p - c);
+ value = x + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
+ }
+ cur[i] = value & 0xff;
+ }
+ for (let px = 0; px < width; px++) {
+ const src = px * channels;
+ const dst = (y * width + px) * 3;
+ rgb[dst] = cur[src]!;
+ rgb[dst + 1] = cur[src + 1]!;
+ rgb[dst + 2] = cur[src + 2]!;
+ }
+ prior.set(cur);
+ }
+ return { rgb, width, height };
+}
diff --git a/src/views/renderer-id.ts b/src/views/renderer-id.ts
new file mode 100644
index 00000000..bde87b63
--- /dev/null
+++ b/src/views/renderer-id.ts
@@ -0,0 +1,24 @@
+/**
+ * Deterministic identity of the pure-CPU rasterizer view producer.
+ *
+ * Mirrors the external render-service `rendererId` contract
+ * ("<family>:<identity...>", e.g. "dawn-vulkan:nvidia-rtx-a4500:NVIDIA: 550.100")
+ * so QA evidence and generation results can always name the honest producer of a
+ * view artifact. The engine version is read from package.json ONCE at module
+ * load — never per call — keeping the constant deterministic for a given build.
+ */
+
+import { readFileSync } from 'node:fs';
+
+function engineVersion(): string {
+ try {
+ const raw = readFileSync(new URL('../../package.json', import.meta.url), 'utf8');
+ const version = (JSON.parse(raw) as { version?: unknown }).version;
+ return typeof version === 'string' && version.length > 0 ? version : 'unknown';
+ } catch {
+ return 'unknown';
+ }
+}
+
+/** e.g. "cpu-raster:0.6.0" — the CPU rasterizer's deterministic rendererId. */
+export const CPU_RASTER_RENDERER_ID = `cpu-raster:${engineVersion()}`;