@womp/spark-agent 17.7.3 → 17.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1120 @@
1
+ // Quality bench: builds each case (a prompt with reference images, such as a character to rebuild) several times in
2
+ // parallel through a Kakapo multiplexer, renders every build, and scores it with vision judges and scene structure.
3
+ // Cases live in bench/quality/cases/<id>/case.json with their images (git LFS). Dev tooling, not part of the agent API.
4
+ import { once } from "node:events";
5
+ import { appendFileSync, existsSync } from "node:fs";
6
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
7
+ import path from "node:path";
8
+ import { generateText } from "ai";
9
+ import { createAnthropic } from "@ai-sdk/anthropic";
10
+ import { createGoogleGenerativeAI } from "@ai-sdk/google";
11
+ import { KakapoAPI } from "@womp/kakapo-sdk";
12
+ import { prepareAgentInput } from "./agent-run-input.js";
13
+ import { BENCH_SHEET_CAMERAS, benchCamera, benchGeometryIds, fitOrthographicCamera } from "./bench-camera.js";
14
+ import { SparkChatTransport } from "./client.js";
15
+ import { KakapoMux } from "./kakapo-mux.js";
16
+ import { buildMasterSheet } from "./quality-bench-sheet.js";
17
+ import { createBenchMetrics } from "./run-metrics.js";
18
+ import { createStandaloneSparkAgentApp } from "./server/standalone.js";
19
+ export const QUALITY_CASES_DIR = path.resolve("bench", "quality", "cases");
20
+ const LIKENESS_JUDGE = "claude-sonnet-5-5";
21
+ /**
22
+ * The part judge, calibrated against per-part human labels (.spark/judge-cal/research.md): Gemini 4 Neon at low
23
+ * thinking, the full reference picture first, a 0-3 severity per part, the median of three parallel calls, and a
24
+ * part fails at severity 2 or more.
25
+ */
26
+ const PART_JUDGE = { model: "gemini-4-neon", thinking: "low", votes: 3, failAt: 2 };
27
+ const JUDGES = `likeness ${LIKENESS_JUDGE}; parts ${PART_JUDGE.model} (${PART_JUDGE.thinking}), median of ${PART_JUDGE.votes}, fail at ${PART_JUDGE.failAt}`;
28
+ /** Standardized multi-view turntable rendered around the matched front side (used by --ab pairwise judging on any object). */
29
+ export const TURNTABLE_VIEWS = [
30
+ { name: "front", turn: 0, tilt: 0.05, label: "whole build, front view" },
31
+ { name: "quarter-l", turn: 38, tilt: 0.28, label: "whole build, elevated three-quarter left view" },
32
+ { name: "quarter-r", turn: -38, tilt: 0.28, label: "whole build, elevated three-quarter right view" },
33
+ { name: "back", turn: 180, tilt: 0.15, label: "whole build, back view" },
34
+ { name: "top", turn: 35, tilt: 0.72, label: "whole build, elevated top/isometric view" },
35
+ ];
36
+ export async function loadQualityCaseSpec(id) {
37
+ const dir = path.join(QUALITY_CASES_DIR, id);
38
+ const spec = JSON.parse(await readFile(path.join(dir, "case.json"), "utf8"));
39
+ if (spec.id !== id)
40
+ throw new Error(`Case ${id}: case.json says id ${spec.id}.`);
41
+ for (const file of [...spec.images, spec.reference]) {
42
+ if (!existsSync(path.join(dir, file)))
43
+ throw new Error(`Case ${id}: missing image ${file}.`);
44
+ }
45
+ return { ...spec, dir };
46
+ }
47
+ export async function loadQualityCase(id) {
48
+ const c = await loadQualityCaseSpec(id);
49
+ for (const file of [...c.images, c.reference]) {
50
+ const head = await readFile(path.join(c.dir, file)).then((b) => b.subarray(0, 40).toString("utf8"));
51
+ if (head.startsWith("version https://git-lfs"))
52
+ throw new Error(`Case ${id}: ${file} is a git LFS pointer; run git lfs pull.`);
53
+ }
54
+ return c;
55
+ }
56
+ export async function listQualityCases() {
57
+ const entries = await readdir(QUALITY_CASES_DIR, { withFileTypes: true });
58
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
59
+ }
60
+ /** Raw WebSocket JSON-RPC helper for Kakapo (used for scene_state_set/get before KakapoAPI.connect). */
61
+ async function kakapoRawRpc(url, method, params) {
62
+ return new Promise((resolve, reject) => {
63
+ const ws = new WebSocket(url);
64
+ const timer = setTimeout(() => { ws.close(); reject(new Error(`Kakapo ${method} timed out.`)); }, 15_000);
65
+ ws.onopen = () => ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method, ...(params ? { params } : {}) }));
66
+ ws.onmessage = (event) => {
67
+ // Engine broadcasts and binary frames can arrive before the reply.
68
+ if (typeof event.data !== "string")
69
+ return;
70
+ let message;
71
+ try {
72
+ message = JSON.parse(event.data);
73
+ }
74
+ catch {
75
+ return;
76
+ }
77
+ if (message?.id !== 1)
78
+ return;
79
+ clearTimeout(timer);
80
+ ws.close();
81
+ if (message.error)
82
+ reject(new Error(`Kakapo ${method}: ${message.error.message ?? JSON.stringify(message.error)}`));
83
+ else
84
+ resolve(message.result);
85
+ };
86
+ ws.onerror = (event) => { clearTimeout(timer); reject(new Error(`Kakapo WebSocket error on ${url}: ${String(event)}`)); };
87
+ });
88
+ }
89
+ /**
90
+ * A new Womp project's scene properties: swan-frontend src/utils/scene/data.tsx `defaultSceneProperty`, lit by the
91
+ * leadenhall_market environment. Builds start from these so they are lit as in the editor. Kakapo's own default
92
+ * environment, `sunset_small` (code/Modeller/Scene.h), is in no data tree, so a scene taken from a freshly started
93
+ * engine has no environment light and renders nearly black.
94
+ */
95
+ export const WOMP_SCENE_PROPERTIES = {
96
+ backdrop_color1: { x: 1, y: 1, z: 1 },
97
+ backdrop_color2: { x: 1, y: 1, z: 1 },
98
+ backdrop_grad_offset: { x: 1, y: 1 },
99
+ backdrop_multiplier: 0.8489999771118164,
100
+ backdrop_name: "dfsd_gaby",
101
+ flags: 0,
102
+ floor_blend_begin: 0,
103
+ floor_blend_end: 1,
104
+ floor_blending_factor: 0.5870000123977661,
105
+ hdr_multiplier: 1.2999999523162842,
106
+ hdr_name: "leadenhall_market",
107
+ hdr_orientation: { x: 0, y: 0 },
108
+ render_flags: 59,
109
+ dynamic_resolution: 1,
110
+ outline: { x: 0, y: 0, z: 0, w: 2 },
111
+ outline_mode: 0,
112
+ cel_shading_levels: 0,
113
+ exposure: 1,
114
+ tonemapper: 0,
115
+ use_image_background: false,
116
+ };
117
+ /** Kakapo's built-in environment name, which no data tree ships (see WOMP_SCENE_PROPERTIES). */
118
+ const KAKAPO_DEFAULT_HDR = "sunset_small";
119
+ /**
120
+ * A saved scene with its environment made renderable: one still on Kakapo's missing default environment (builds made
121
+ * before the bench seeded WOMP_SCENE_PROPERTIES) gets the Womp default environment; any other scene is unchanged.
122
+ */
123
+ export function withWompEnvironment(scene) {
124
+ if (scene?.properties?.hdr_name !== KAKAPO_DEFAULT_HDR)
125
+ return scene;
126
+ const { hdr_name, hdr_multiplier, hdr_orientation } = WOMP_SCENE_PROPERTIES;
127
+ return { ...scene, properties: { ...scene.properties, hdr_name, hdr_multiplier, hdr_orientation } };
128
+ }
129
+ /**
130
+ * Ensures Kakapo has a valid minimal scene (with `nodes["0"]`) before connecting `KakapoAPI` (prevents
131
+ * `Cannot convert undefined or null to object` when Kakapo is open with no project loaded).
132
+ * When `reset` is true, always replaces the engine scene with a clean empty root scene with a new Womp project's
133
+ * properties, so `KakapoMux` templates inherit neither stale scenes nor the engine's unlit default environment.
134
+ */
135
+ export async function ensureKakapoScene(url, reset = false) {
136
+ const raw = await kakapoRawRpc(url, "scene_state_get");
137
+ let parsed;
138
+ try {
139
+ parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
140
+ }
141
+ catch {
142
+ parsed = null;
143
+ }
144
+ if (!reset && parsed?.nodes && typeof parsed.nodes === "object" && Object.keys(parsed.nodes).length > 0)
145
+ return;
146
+ const current = parsed && typeof parsed === "object" ? parsed : {};
147
+ const starter = JSON.stringify({
148
+ ...current,
149
+ properties: { ...(current.properties ?? {}), ...WOMP_SCENE_PROPERTIES },
150
+ nodes: { "0": { type: 4, pos: { x: 0, y: 0, z: 0 }, rot: { x: 0, y: 0, z: 0 }, size: { x: 1, y: 1, z: 1 } } },
151
+ tree: { "0": {} },
152
+ ext: {},
153
+ materials: {},
154
+ });
155
+ await kakapoRawRpc(url, "scene_state_set", [starter]);
156
+ }
157
+ /** Runs every case `repeat` times, `parallel` builds at once, and writes report.json and report.md to `output`. */
158
+ export async function runQualityBench(options) {
159
+ const log = options.log ?? console.log;
160
+ const cases = await Promise.all(options.cases.map(loadQualityCase));
161
+ await ensureKakapoScene(options.kakapoUrl, true);
162
+ await mkdir(path.dirname(options.output), { recursive: true });
163
+ await mkdir(options.output);
164
+ const muxLogFile = path.join(options.output, "mux-debug.log");
165
+ const mux = new KakapoMux({
166
+ upstream: options.kakapoUrl,
167
+ port: 0,
168
+ log: (line) => { try {
169
+ appendFileSync(muxLogFile, `${new Date().toISOString()} ${line}\n`);
170
+ }
171
+ catch { } },
172
+ });
173
+ await mux.start();
174
+ const muxUrl = `ws://127.0.0.1:${mux.port}`;
175
+ const jobs = cases.flatMap((c) => Array.from({ length: options.repeat }, (_, i) => ({ c, rep: i + 1 })));
176
+ const results = [];
177
+ try {
178
+ await Promise.all(Array.from({ length: Math.max(1, options.parallel) }, async () => {
179
+ for (let job = jobs.shift(); job; job = jobs.shift()) {
180
+ options.signal.throwIfAborted();
181
+ const dir = path.join(options.output, job.c.id, `run-${job.rep}`);
182
+ const result = await runOne(job.c, job.rep, `${muxUrl}/s/${job.c.id}-run-${job.rep}`, dir, options);
183
+ results.push(result);
184
+ const judgeSummary = options.judge
185
+ ? `, likeness ${fmt(result.likeness?.mean)}${Object.keys(result.checks).length ? `, ${Object.entries(result.checks).map(([k, v]) => `${k} ${fmt(v.mean)}`).join(", ")}` : ""}`
186
+ : "";
187
+ const t = result.timings;
188
+ const timingSummary = t
189
+ ? `build ${Math.round(t.buildMs / 1000)}s, render ${(t.renderMs / 1000).toFixed(1)}s${t.judgeMs ? `, judge ${(t.judgeMs / 1000).toFixed(1)}s` : ""}`
190
+ : `${Math.round(result.durationMs / 1000)}s`;
191
+ log(`${job.c.id} run-${job.rep}: ${result.status}${result.error ? ` (${result.error})` : ""}${judgeSummary}, $${fmt(result.costUsd, 2)}, ${timingSummary}`);
192
+ }
193
+ }));
194
+ }
195
+ finally {
196
+ await mux.stop();
197
+ }
198
+ const report = summarize(cases, results, options);
199
+ await writeBenchOutputs(options.output, report, cases, results);
200
+ return report;
201
+ }
202
+ async function runOne(c, rep, kakapoUrl, dir, options) {
203
+ await mkdir(dir, { recursive: true });
204
+ const result = { case: c.id, run: rep, status: "failed", costUsd: null, durationMs: 0, steps: 0, checks: {} };
205
+ const started = performance.now();
206
+ const app = await createStandaloneSparkAgentApp({
207
+ kakapoUrl, storagePath: ":memory:",
208
+ openAiApiKey: process.env.OPENAI_API_KEY, anthropicApiKey: process.env.ANTHROPIC_API_KEY, geminiApiKey: process.env.GEMINI_API_KEY,
209
+ });
210
+ const server = app.listen(0, "127.0.0.1");
211
+ try {
212
+ await once(server, "listening");
213
+ const base = `http://127.0.0.1:${server.address().port}/agent`;
214
+ const transport = new SparkChatTransport({ api: base, getSettings: () => options.settings });
215
+ const signal = AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)]);
216
+ const clear = await fetch(`${base}/scene/clear`, { method: "POST", headers: { "X-Spark-Action": "clear-scene" }, signal });
217
+ if (!clear.ok)
218
+ throw new Error(`Scene cleanup failed: ${await clear.text()}`);
219
+ const conversation = await transport.createConversation({ title: `quality-bench ${c.id} ${rep}` });
220
+ const { message } = await prepareAgentInput(c.prompt, c.images.map((f) => path.join(c.dir, f)), options.settings);
221
+ const buildStart = performance.now();
222
+ const stream = await transport.sendMessages({ trigger: "submit-message", chatId: conversation.id, messageId: undefined, messages: [message], abortSignal: signal });
223
+ const metrics = createBenchMetrics();
224
+ for await (const chunk of stream) {
225
+ metrics.accept(chunk);
226
+ if (chunk.type === "data-run-status") {
227
+ result.status = chunk.data.status;
228
+ if (chunk.data.error)
229
+ result.error = chunk.data.error;
230
+ }
231
+ }
232
+ const buildMs = Math.round(performance.now() - buildStart);
233
+ Object.assign(result, { costUsd: metrics.snapshot().costUsd, steps: metrics.snapshot().steps });
234
+ await writeFile(path.join(dir, "conversation.json"), JSON.stringify(await transport.getConversation(conversation.id), null, 2));
235
+ const api = new KakapoAPI({ url: kakapoUrl, requestTimeoutMs: 180_000 });
236
+ await api.connect();
237
+ let renderMs = 0, judgeMs = 0;
238
+ try {
239
+ const sceneText = String(await api.rpc("scene_state_get"));
240
+ await writeFile(path.join(dir, "scene.json"), sceneText);
241
+ const scene = JSON.parse(sceneText);
242
+ result.structure = sceneStructure(scene);
243
+ const boxes = await buildBoxes(api);
244
+ if (!boxes.length)
245
+ throw new Error("The build left nothing visible.");
246
+ const pts = await resolveVisiblePoints(api, scene);
247
+ const r0 = performance.now();
248
+ await renderFixedCameras(api, dir);
249
+ const sides = await renderSides(api, boxes, dir);
250
+ renderMs += performance.now() - r0;
251
+ let frontSide = DEFAULT_FRONT;
252
+ if (options.judge) {
253
+ const j0 = performance.now();
254
+ const [likeness, front] = await Promise.all([judgeLikeness(c, sides), judgeFront(sides)]);
255
+ judgeMs += performance.now() - j0;
256
+ result.likeness = likeness;
257
+ frontSide = front;
258
+ await writeFile(path.join(dir, "likeness.json"), JSON.stringify(result.likeness, null, 1));
259
+ }
260
+ result.front = frontSide;
261
+ const r1 = performance.now();
262
+ const turntable = await renderViews(api, scene, boxes, pts, frontSide, TURNTABLE_VIEWS, dir, "turntable");
263
+ await buildContactSheet(turntable, path.join(dir, "turntable-grid.jpg"));
264
+ renderMs += performance.now() - r1;
265
+ for (const check of c.checks ?? []) {
266
+ const rc = performance.now();
267
+ const shots = await renderViews(api, scene, boxes, pts, frontSide, check.views, dir);
268
+ renderMs += performance.now() - rc;
269
+ if (options.judge) {
270
+ const jc = performance.now();
271
+ result.checks[check.id] = await judgeCheck(c, check, shots);
272
+ judgeMs += performance.now() - jc;
273
+ await writeFile(path.join(dir, `${check.id}.json`), JSON.stringify(result.checks[check.id], null, 1));
274
+ }
275
+ }
276
+ result.timings = { buildMs, renderMs: Math.round(renderMs), judgeMs: Math.round(judgeMs) };
277
+ }
278
+ finally {
279
+ api.disconnect();
280
+ }
281
+ }
282
+ catch (error) {
283
+ result.error = error instanceof Error ? error.message : String(error);
284
+ }
285
+ finally {
286
+ result.durationMs = Math.round(performance.now() - started);
287
+ await writeFile(path.join(dir, "result.json"), JSON.stringify(result, null, 2));
288
+ try {
289
+ await app.dispose();
290
+ }
291
+ finally {
292
+ server.closeAllConnections();
293
+ server.close();
294
+ }
295
+ }
296
+ return result;
297
+ }
298
+ const SIDES = { px: [1, 0], nx: [-1, 0], pz: [0, 1], nz: [0, -1] };
299
+ /** Spark's public +Z is forward and maps to renderer -X, so a build that follows the convention faces the `nx` side. */
300
+ export const DEFAULT_FRONT = "nx";
301
+ /** The local bench Kakapo captures 1280x720. */
302
+ const CAPTURE_ASPECT = 16 / 9;
303
+ /** Space around the build in every view: 10% of the frame's tighter dimension. */
304
+ const VIEW_MARGIN = 1.1;
305
+ function visiblePoints(scene, ids) {
306
+ const out = [];
307
+ for (const [id, n] of Object.entries(scene.nodes)) {
308
+ if (n.hide || n.op === 2 || (ids && !ids.has(id)))
309
+ continue;
310
+ for (const p of n.points ?? (n.type === 0 ? [n] : []))
311
+ out.push({ ...p.pos, r: Math.max(p.size.x, p.size.y, p.size.z) / 2, id });
312
+ }
313
+ return out;
314
+ }
315
+ /** Falls back to Kakapo's native bounding box for OpenSCAD / mesh / geometry-node scenes that have no primitive/curve points. */
316
+ async function resolveVisiblePoints(api, scene) {
317
+ const pts = visiblePoints(scene);
318
+ if (pts.length)
319
+ return pts;
320
+ const ids = benchGeometryIds(api);
321
+ if (!ids.length)
322
+ return [];
323
+ const b = await api.getNodesBoundingBox(ids);
324
+ if (!b?.min || !b?.max)
325
+ return [];
326
+ const corners = [];
327
+ for (const x of [b.min.x, b.max.x])
328
+ for (const y of [b.min.y, b.max.y])
329
+ for (const z of [b.min.z, b.max.z])
330
+ corners.push({ x, y, z, r: 0, id: String(ids[0]) });
331
+ return corners;
332
+ }
333
+ /** Fixed Spark-space perspective shots (`benchCamera`), fitted to Kakapo's native world bounding box. */
334
+ export async function renderFixedCameras(api, dir) {
335
+ try {
336
+ const ids = benchGeometryIds(api);
337
+ if (!ids.length)
338
+ return [];
339
+ const bounds = await api.getNodesBoundingBox(ids);
340
+ const files = [];
341
+ for (const view of BENCH_SHEET_CAMERAS) {
342
+ const camera = benchCamera(bounds, 16 / 9, view.offset);
343
+ const file = path.join(dir, view.file);
344
+ await writeFile(file, (await api.captureScreenshot({ camera, timeoutMs: 120_000 })).data);
345
+ files.push(file);
346
+ }
347
+ return files;
348
+ }
349
+ catch {
350
+ return [];
351
+ }
352
+ }
353
+ /** Each visible top-level geometry node's native world box (Kakapo bounds Areas, meshes and parts, not primitives). */
354
+ async function buildBoxes(api) {
355
+ const boxes = [];
356
+ for (const id of benchGeometryIds(api)) {
357
+ try {
358
+ const b = await api.getNodesBoundingBox([id]);
359
+ if ([b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z].every(Number.isFinite) && b.min.x <= b.max.x)
360
+ boxes.push({ min: b.min, max: b.max });
361
+ }
362
+ catch { /* a node without bounds of its own adds nothing to the framing */ }
363
+ }
364
+ return boxes;
365
+ }
366
+ /** Orthographic renders from the four sides, fitted to the whole build. */
367
+ async function renderSides(api, boxes, dir) {
368
+ const files = {};
369
+ for (const [name, [dx, dz]] of Object.entries(SIDES)) {
370
+ const camera = fitOrthographicCamera(boxes, { x: dx, y: 0.02, z: dz }, CAPTURE_ASPECT, VIEW_MARGIN);
371
+ files[name] = path.join(dir, `side-${name}.jpg`);
372
+ await writeFile(files[name], (await api.captureScreenshot({ camera, timeoutMs: 120_000 })).data);
373
+ }
374
+ return files;
375
+ }
376
+ /**
377
+ * Views turned from the build's front. A whole-build view is fitted to the native boxes. A close-up selects parts by
378
+ * height band or name; its points' box is clipped to the build's native box, since scene points carry a radius of
379
+ * half their largest size, which overstates thin parts. A view that selects nothing is skipped.
380
+ */
381
+ async function renderViews(api, scene, boxes, all, side, views, dir, prefix = "view") {
382
+ const build = unionBox(boxes);
383
+ const y0 = build.min.y, h = build.max.y - build.min.y;
384
+ const [fx, fz] = SIDES[side] ?? SIDES[DEFAULT_FRONT];
385
+ const names = (id) => String(scene.ext?.[id]?.name ?? "");
386
+ const out = [];
387
+ for (const view of views) {
388
+ let frame = boxes;
389
+ if (view.band || view.match) {
390
+ let pts = all;
391
+ if (view.band) {
392
+ const lo = y0 + view.band[0] * h, hi = y0 + view.band[1] * h;
393
+ pts = pts.filter((p) => p.y + p.r * 0.5 >= lo && p.y - p.r * 0.5 <= hi);
394
+ }
395
+ if (view.match) {
396
+ const match = new RegExp(view.match, "i"), exclude = view.exclude ? new RegExp(view.exclude, "i") : undefined;
397
+ pts = pts.filter((p) => match.test(names(p.id)) && !exclude?.test(names(p.id)));
398
+ if (view.half && pts.length) {
399
+ // The build's right (a) or left (b), seen from the side it faces.
400
+ const rx = -fz, rz = fx, u = (p) => p.x * rx + p.z * rz;
401
+ const us = pts.map(u), mid = (Math.min(...us) + Math.max(...us)) / 2;
402
+ pts = pts.filter((p) => view.half === "a" ? u(p) < mid : u(p) >= mid);
403
+ }
404
+ }
405
+ let box = pts.length ? clipBox(pointsBox(pts), build) : undefined;
406
+ if (box && view.band)
407
+ box = clipBox(box, { min: { ...build.min, y: y0 + view.band[0] * h }, max: { ...build.max, y: y0 + view.band[1] * h } });
408
+ if (!box) {
409
+ out.push({ name: view.name, label: view.label });
410
+ continue;
411
+ }
412
+ frame = [box];
413
+ }
414
+ const a = view.turn * Math.PI / 180;
415
+ const dx = fx * Math.cos(a) - fz * Math.sin(a), dz = fx * Math.sin(a) + fz * Math.cos(a);
416
+ const camera = fitOrthographicCamera(frame, { x: dx, y: view.tilt ?? 0.1, z: dz }, CAPTURE_ASPECT, VIEW_MARGIN);
417
+ const file = path.join(dir, `${prefix}-${view.name}.jpg`);
418
+ await writeFile(file, (await api.captureScreenshot({ camera, timeoutMs: 120_000 })).data);
419
+ out.push({ name: view.name, label: view.label, file });
420
+ }
421
+ return out;
422
+ }
423
+ function unionBox(boxes) {
424
+ const pick = (k, f) => ({
425
+ x: f(...boxes.map((b) => b[k].x)), y: f(...boxes.map((b) => b[k].y)), z: f(...boxes.map((b) => b[k].z)),
426
+ });
427
+ return { min: pick("min", Math.min), max: pick("max", Math.max) };
428
+ }
429
+ function pointsBox(pts) {
430
+ const lo = (k) => Math.min(...pts.map((p) => p[k] - p.r)), hi = (k) => Math.max(...pts.map((p) => p[k] + p.r));
431
+ return { min: { x: lo("x"), y: lo("y"), z: lo("z") }, max: { x: hi("x"), y: hi("y"), z: hi("z") } };
432
+ }
433
+ /** The part of `box` inside `to`, or undefined when they do not overlap. */
434
+ export function clipBox(box, to) {
435
+ const min = { x: Math.max(box.min.x, to.min.x), y: Math.max(box.min.y, to.min.y), z: Math.max(box.min.z, to.min.z) };
436
+ const max = { x: Math.min(box.max.x, to.max.x), y: Math.min(box.max.y, to.max.y), z: Math.min(box.max.z, to.max.z) };
437
+ return min.x <= max.x && min.y <= max.y && min.z <= max.z ? { min, max } : undefined;
438
+ }
439
+ let anthropic;
440
+ let google;
441
+ /** One judge call; a failed call or an answer without JSON is retried twice. */
442
+ async function judge(content, judgeModel = "likeness") {
443
+ for (let attempt = 0;; attempt++) {
444
+ try {
445
+ const { text } = judgeModel === "parts"
446
+ ? await generateText({
447
+ model: (google ??= createGoogleGenerativeAI({ apiKey: process.env.GEMINI_API_KEY }))(PART_JUDGE.model),
448
+ providerOptions: { google: { thinkingConfig: { thinkingLevel: PART_JUDGE.thinking } } },
449
+ maxOutputTokens: 16_000, messages: [{ role: "user", content }],
450
+ })
451
+ : await generateText({ model: (anthropic ??= createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY }))(LIKENESS_JUDGE), messages: [{ role: "user", content }] });
452
+ return JSON.parse(firstObject(text));
453
+ }
454
+ catch (error) {
455
+ if (attempt >= 2)
456
+ throw error;
457
+ }
458
+ }
459
+ }
460
+ const image = async (file) => ({ type: "file", data: await readFile(file), mediaType: mediaType(file) });
461
+ function mediaType(file) {
462
+ const ext = path.extname(file).toLowerCase();
463
+ return ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : "image/jpeg";
464
+ }
465
+ const mean = (values) => values.length ? values.reduce((a, b) => a + b, 0) / values.length : NaN;
466
+ /** Picks the render that shows the reference's side and scores the likeness parts on it. */
467
+ async function judgeLikeness(c, sides) {
468
+ const keys = Object.keys(sides);
469
+ const answer = await judge([
470
+ { type: "text", text: `The first image is a reference picture. After it come four renders of a 3D rebuild of it from four sides, each labelled (${keys.map((_, i) => String.fromCharCode(65 + i)).join(", ")}).
471
+ First pick the label of the render that shows the same side as the reference. Then, on that render, score how closely the rebuild matches the reference for each item, 0 to 10: 10 = indistinguishable in shape, size, position and colour; 7 = clearly the same with small differences; 4 = recognisable but clearly off; 0 = missing or wrong. Judge geometry and colour, not lighting, render style or background.
472
+ Items: ${c.likeness.join("; ")}.
473
+ Answer only JSON: {"view":"<label>","scores":{"<item>":n,...},"biggest_differences":["...","...","..."]}` },
474
+ { type: "text", text: "Reference:" },
475
+ await image(path.join(c.dir, c.reference)),
476
+ ...await labelledImages(keys.map((k) => sides[k])),
477
+ ]);
478
+ const side = keys[Math.max(0, String(answer.view ?? "A").toUpperCase().charCodeAt(0) - 65)] ?? keys[0];
479
+ return { side, scores: answer.scores, mean: mean(Object.values(answer.scores)), notes: answer.biggest_differences };
480
+ }
481
+ /**
482
+ * Which side render shows the build's front. Asked separately from likeness, and without the reference: the side that
483
+ * best matches the reference is the reference's camera angle, which for a three-quarter or profile reference is not
484
+ * the front.
485
+ */
486
+ async function judgeFront(sides) {
487
+ const keys = Object.keys(sides);
488
+ const answer = await judge([
489
+ { type: "text", text: `Four renders of one 3D build, each from a different side, labelled ${keys.map((_, i) => String.fromCharCode(65 + i)).join(", ")}. Which label shows the build's front: the side you face when you look at it head-on, such as a character's or animal's face, a vehicle's nose, or the side a product or piece of furniture is used or displayed from? A face with eyes is the front whenever one is visible. If the build looks the same from every side, answer "none".
490
+ Answer only JSON: {"front":"<label or none>","reason":"<one sentence>"}` },
491
+ ...await labelledImages(keys.map((k) => sides[k])),
492
+ ]);
493
+ return frontFromAnswer(answer, keys);
494
+ }
495
+ /**
496
+ * Images each preceded by its label ("Render A:"). A judge counting images by position ("image 3") misnumbers them
497
+ * once a reference picture comes first; a label next to each image does not.
498
+ */
499
+ async function labelledImages(files) {
500
+ return (await Promise.all(files.map(async (f, i) => [{ type: "text", text: `Render ${String.fromCharCode(65 + i)}:` }, await image(f)]))).flat();
501
+ }
502
+ /** The side a front answer names; "none", an unknown label or a malformed answer keeps Spark's convention. */
503
+ export function frontFromAnswer(answer, keys) {
504
+ const label = String(answer?.front ?? "").trim().toUpperCase();
505
+ return /^[A-Z]$/.test(label) ? keys[label.charCodeAt(0) - 65] ?? DEFAULT_FRONT : DEFAULT_FRONT;
506
+ }
507
+ /**
508
+ * The 0-3 scale. Its 1/2 line is anchored on construction, which is where the human labels put it: simplified or
509
+ * missing secondary detail is minor, while any visible join between separately built pieces fails.
510
+ */
511
+ const SEVERITY = `Rate the difference from the reference on this scale:
512
+ 0 = matches: the same shape, joins and pose; any differences are only colour, texture or render style.
513
+ 1 = minor: the shape and joins are right, but secondary detail is simplified, missing or drawn differently (for example loops, stitching, pleats, folds, buckle or button shape, finger creases).
514
+ 2 = clear: you can see where separately built pieces meet (a line, crease, step, ridge, tube edge or overlap at a join, even a soft one), or the part is boxy, lumpy, melted, floating, or in the wrong pose or size.
515
+ 3 = wrong: the part is badly built, missing, or not recognisable as the reference's part.`;
516
+ const TAGS = "wrong shape, wrong size or proportion, too blocky, lumpy or melted, missing part, extra or stray part, wrong position, pose or orientation, wrong count or symmetry, visible seam or step, gap or floating, poking through, fused, wrong edge sharpness, surface artifact";
517
+ /** Median, so one outlying call out of three cannot flip a part. */
518
+ function median(values) {
519
+ const v = values.filter(Number.isFinite).sort((a, b) => a - b), mid = v.length >> 1;
520
+ return !v.length ? NaN : v.length % 2 ? v[mid] : (v[mid - 1] + v[mid]) / 2;
521
+ }
522
+ /** Resolves order-swapped forward (A, B) and reverse (B, A) pairwise judgements; disagreement becomes a tie. */
523
+ export function resolvePairwiseSwap(forward, reverse) {
524
+ const norm = (w) => (w === "A" ? "A" : w === "B" ? "B" : "tie");
525
+ const fwd = norm(String(forward.winner ?? "tie").trim().toUpperCase());
526
+ const revRaw = norm(String(reverse.winner ?? "tie").trim().toUpperCase());
527
+ const rev = revRaw === "A" ? "B" : revRaw === "B" ? "A" : "tie";
528
+ const consistent = fwd === rev;
529
+ const winner = consistent ? fwd : "tie";
530
+ return {
531
+ winner,
532
+ consistent,
533
+ reason: consistent ? String(forward.reason ?? "") : `Order-swapped calls disagreed (forward=${fwd}, reverse=${rev}).`,
534
+ aFlaws: String(forward.a_flaws ?? ""),
535
+ bFlaws: String(forward.b_flaws ?? ""),
536
+ };
537
+ }
538
+ /**
539
+ * Blinded order-swapped pairwise judge (Gemini 4 Neon, low thinking): runs (A, B) and (B, A) in parallel so position
540
+ * bias cancels out into a tie. Works on any reference image or focused close-up view set.
541
+ */
542
+ export async function judgePairwise(referenceFile, shotsA, shotsB, focus) {
543
+ const shownA = shotsA.filter((s) => s.file);
544
+ const shownB = shotsB.filter((s) => s.file);
545
+ const focusLine = focus ? `\nFocus your comparison specifically on: ${focus} (as shown in the provided views).\n` : "";
546
+ const oneCall = async (first, second) => {
547
+ const aStart = 2, aEnd = aStart + first.length - 1, bStart = aEnd + 1, bEnd = bStart + second.length - 1;
548
+ const content = [
549
+ { type: "text", text: `Image 1 is the reference picture.
550
+ Images ${aStart}-${aEnd} are 3D Build A (${first.map((s, i) => `image ${aStart + i}: ${s.label ?? s.name}`).join("; ")}).
551
+ Images ${bStart}-${bEnd} are 3D Build B (${second.map((s, i) => `image ${bStart + i}: ${s.label ?? s.name}`).join("; ")}).
552
+ ${focusLine}
553
+ Compare Build A and Build B strictly on 3D modeling quality and fidelity to the reference:
554
+ 1. Clean construction and joins (no unintended seams, creases, steps, ridges, tube ends, overlaps, gaps, floating pieces, or parts poking through where the reference is continuous).
555
+ 2. Shape, proportions, symmetry, and edge character matching the reference (smooth where smooth, crisp/beveled where crisp or mechanical, not lumpy/melted or boxy).
556
+ 3. Part completeness, counts, and 3D depth across all shown views.
557
+ Ignore lighting, background, and render style; do not penalize simplified minor surface details over real construction, join, or shape defects.
558
+
559
+ Pick which build is better overall: "A", "B", or "tie" (only if genuinely indistinguishable in quality).
560
+ Answer only JSON: {"a_flaws":"...","b_flaws":"...","winner":"A|B|tie","reason":"..."}` },
561
+ await image(referenceFile),
562
+ ...await Promise.all(first.map((s) => image(s.file))),
563
+ ...await Promise.all(second.map((s) => image(s.file))),
564
+ ];
565
+ return judge(content, "parts");
566
+ };
567
+ const [forward, reverse] = await Promise.all([oneCall(shownA, shownB), oneCall(shownB, shownA)]);
568
+ return resolvePairwiseSwap(forward, reverse);
569
+ }
570
+ /**
571
+ * Stitches 4 turntable renders (front, quarter-l, back, top) into a single labeled 1280x720 2x2 contact sheet JPEG so
572
+ * pairwise VLM calls see only 3 images total (Reference, Build A grid, Build B grid) without image-overload bias.
573
+ */
574
+ export async function buildContactSheet(shots, outFile) {
575
+ const wanted = [["front", "FRONT"], ["quarter-l", "3/4 VIEW"], ["back", "BACK"], ["top", "TOP / ISO"]];
576
+ const tiles = wanted
577
+ .map(([name, title]) => ({ title, file: shots.find((s) => s.name === name)?.file }))
578
+ .filter((t) => Boolean(t.file));
579
+ if (tiles.length < 4)
580
+ return null;
581
+ const { default: sharp } = await import("sharp");
582
+ const w = 640, h = 360;
583
+ const composites = await Promise.all(tiles.map(async (t, i) => {
584
+ const left = (i % 2) * w, top = Math.floor(i / 2) * h;
585
+ const badge = Buffer.from(`<svg width="${w}" height="${h}"><rect x="10" y="10" width="128" height="28" rx="6" fill="rgba(0,0,0,0.65)"/><text x="20" y="29" font-family="Arial,sans-serif" font-size="16" font-weight="bold" fill="#ffffff">${t.title}</text></svg>`);
586
+ const tileBuf = await sharp(t.file)
587
+ .resize(w, h, { fit: "contain", background: { r: 245, g: 247, b: 250, alpha: 1 } })
588
+ .composite([{ input: badge, top: 0, left: 0 }])
589
+ .toBuffer();
590
+ return { input: tileBuf, left, top };
591
+ }));
592
+ await sharp({ create: { width: w * 2, height: h * 2, channels: 3, background: { r: 230, g: 234, b: 240 } } })
593
+ .composite(composites)
594
+ .jpeg({ quality: 90 })
595
+ .toFile(outFile);
596
+ return outFile;
597
+ }
598
+ async function listRunShots(runDir, viewFilter) {
599
+ const files = (await readdir(runDir)).filter((f) => f.endsWith(".jpg") || f.endsWith(".png")).sort();
600
+ let chosen;
601
+ if (viewFilter) {
602
+ const re = new RegExp(viewFilter, "i");
603
+ chosen = files.filter((f) => re.test(f));
604
+ }
605
+ else if (files.includes("turntable-grid.jpg")) {
606
+ return [{ name: "turntable-grid", label: "2x2 multi-view grid (FRONT, 3/4 VIEW, BACK, TOP/ISO)", file: path.join(runDir, "turntable-grid.jpg") }];
607
+ }
608
+ else {
609
+ const tt = files.filter((f) => f.startsWith("turntable-"));
610
+ chosen = tt.length ? tt : files.filter((f) => f.startsWith("view-") || f.startsWith("side-"));
611
+ }
612
+ return chosen.map((f) => ({ name: f.replace(/\.[^.]+$/, ""), label: f.replace(/\.[^.]+$/, "").replaceAll("-", " "), file: path.join(runDir, f) }));
613
+ }
614
+ /** Blinded order-swapped all-vs-all pairwise comparison of two completed quality-bench output directories (A = baseline, B = candidate). */
615
+ export async function compareQualityRuns(baselineDir, candidateDir, options = {}) {
616
+ const baseEntries = (await readdir(baselineDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
617
+ const candEntries = new Set((await readdir(candidateDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name));
618
+ const commonCases = baseEntries.filter((c) => candEntries.has(c)).sort();
619
+ const report = {
620
+ baselineDir, candidateDir, ...(options.focus ? { focus: options.focus } : {}), finishedAt: new Date().toISOString(),
621
+ judge: `${PART_JUDGE.model} (${PART_JUDGE.thinking}), order-swapped pairwise${options.allPairs !== false ? " (all-vs-all)" : ""}`,
622
+ overall: { pairs: 0, candidateWins: 0, baselineWins: 0, ties: 0, consistent: 0 },
623
+ cases: {},
624
+ };
625
+ for (const caseId of commonCases) {
626
+ const c = await loadQualityCase(caseId);
627
+ const refFile = path.join(c.dir, c.reference);
628
+ const rawBase = (await readdir(path.join(baselineDir, caseId), { withFileTypes: true })).filter((e) => e.isDirectory() && e.name.startsWith("run-")).map((e) => e.name).sort();
629
+ const rawCand = (await readdir(path.join(candidateDir, caseId), { withFileTypes: true })).filter((e) => e.isDirectory() && e.name.startsWith("run-")).map((e) => e.name).sort();
630
+ const skipped = [];
631
+ const baseShots = new Map();
632
+ const candShots = new Map();
633
+ for (const r of rawBase) {
634
+ const s = await listRunShots(path.join(baselineDir, caseId, r), options.viewFilter);
635
+ if (s.length)
636
+ baseShots.set(r, s);
637
+ else
638
+ skipped.push(`baseline/${r}`);
639
+ }
640
+ for (const r of rawCand) {
641
+ const s = await listRunShots(path.join(candidateDir, caseId, r), options.viewFilter);
642
+ if (s.length)
643
+ candShots.set(r, s);
644
+ else
645
+ skipped.push(`candidate/${r}`);
646
+ }
647
+ const baseRuns = [...baseShots.keys()];
648
+ const candRuns = [...candShots.keys()];
649
+ const pairList = options.allPairs !== false
650
+ ? baseRuns.flatMap((a) => candRuns.map((b) => [a, b]))
651
+ : baseRuns.filter((r) => candRuns.includes(r)).map((r) => [r, r]);
652
+ const runs = await Promise.all(pairList.map(async ([a, b]) => ({
653
+ pair: `${a} vs ${b}`,
654
+ baselineRun: a,
655
+ candidateRun: b,
656
+ ...(await judgePairwise(refFile, baseShots.get(a), candShots.get(b), options.focus)),
657
+ })));
658
+ const summary = {
659
+ pairs: runs.length,
660
+ candidateWins: runs.filter((r) => r.winner === "B").length,
661
+ baselineWins: runs.filter((r) => r.winner === "A").length,
662
+ ties: runs.filter((r) => r.winner === "tie").length,
663
+ consistent: runs.filter((r) => r.consistent).length,
664
+ ...(skipped.length ? { skipped } : {}),
665
+ runs,
666
+ };
667
+ report.cases[caseId] = summary;
668
+ report.overall.pairs += summary.pairs;
669
+ report.overall.candidateWins += summary.candidateWins;
670
+ report.overall.baselineWins += summary.baselineWins;
671
+ report.overall.ties += summary.ties;
672
+ report.overall.consistent += summary.consistent;
673
+ }
674
+ const suffix = options.focus ? `-${options.focus.toLowerCase().replace(/[^a-z0-9]+/g, "-")}` : "";
675
+ await writeFile(path.join(candidateDir, `ab-report${suffix}.json`), JSON.stringify(report, null, 2));
676
+ await writeFile(path.join(candidateDir, `ab-report${suffix}.md`), pairwiseReportMarkdown(report));
677
+ return report;
678
+ }
679
+ export function pairwiseReportMarkdown(report) {
680
+ const o = report.overall;
681
+ const decisive = o.candidateWins + o.baselineWins;
682
+ const winPct = decisive ? ((o.candidateWins / decisive) * 100).toFixed(0) : "–";
683
+ const lines = [
684
+ `# Pairwise A/B report${report.focus ? ` (${report.focus})` : ""}`,
685
+ ``,
686
+ `Baseline (A): \`${report.baselineDir}\` `,
687
+ `Candidate (B): \`${report.candidateDir}\` `,
688
+ `Judge: ${report.judge}, ${report.finishedAt}`,
689
+ ``,
690
+ `**Overall:** Candidate ${o.candidateWins}W – ${o.baselineWins}L – ${o.ties}T (${winPct}% decisive win rate, ${o.pairs} pairs, order consistency ${o.pairs ? ((o.consistent / o.pairs) * 100).toFixed(0) : "0"}%)`,
691
+ ``,
692
+ `| case | candidate wins | baseline wins | ties | consistency |`,
693
+ `|---|---|---|---|---|`,
694
+ ];
695
+ for (const [id, c] of Object.entries(report.cases)) {
696
+ lines.push(`| ${id} | ${c.candidateWins} | ${c.baselineWins} | ${c.ties} | ${c.pairs ? ((c.consistent / c.pairs) * 100).toFixed(0) : "0"}% |`);
697
+ }
698
+ lines.push(``);
699
+ for (const [id, c] of Object.entries(report.cases)) {
700
+ lines.push(`## ${id}`, ``);
701
+ if (c.skipped?.length)
702
+ lines.push(`*Skipped incomplete runs (no matching renders): ${c.skipped.join(", ")}*`, ``);
703
+ const byCand = new Map();
704
+ for (const r of c.runs) {
705
+ const k = r.candidateRun ?? r.pair.split(" vs ")[1] ?? r.pair;
706
+ const rec = byCand.get(k) ?? { w: 0, l: 0, t: 0 };
707
+ if (r.winner === "B")
708
+ rec.w++;
709
+ else if (r.winner === "A")
710
+ rec.l++;
711
+ else
712
+ rec.t++;
713
+ byCand.set(k, rec);
714
+ }
715
+ if (byCand.size > 0) {
716
+ lines.push(`| candidate run | wins | losses | ties |`, `|---|---|---|---|`);
717
+ for (const [run, rec] of byCand)
718
+ lines.push(`| ${run} | ${rec.w} | ${rec.l} | ${rec.t} |`);
719
+ lines.push(``);
720
+ }
721
+ for (const r of c.runs) {
722
+ const label = r.winner === "B" ? "Candidate (B)" : r.winner === "A" ? "Baseline (A)" : "Tie";
723
+ lines.push(`- **${r.pair}:** ${label} — ${r.reason}`);
724
+ }
725
+ lines.push(``);
726
+ }
727
+ return lines.join("\n");
728
+ }
729
+ /**
730
+ * Recovers and scores an existing bench output directory from its saved `scene.json` files (e.g. after a Kakapo crash),
731
+ * rendering any missing views/grids and reusing existing judge JSONs so completed Spark builds are never wasted.
732
+ */
733
+ export async function scoreExistingBenchRun(outputDir, options) {
734
+ const log = options.log ?? console.log;
735
+ await ensureKakapoScene(options.kakapoUrl);
736
+ const caseDirs = (await readdir(outputDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
737
+ const cases = await Promise.all(caseDirs.map(loadQualityCase));
738
+ const results = [];
739
+ let settings = { modelId: "gpt-6.2-astra", reasoningEffort: "xhigh" };
740
+ const prevReportPath = path.join(outputDir, "report.json");
741
+ if (existsSync(prevReportPath)) {
742
+ try {
743
+ settings = JSON.parse(await readFile(prevReportPath, "utf8")).settings ?? settings;
744
+ }
745
+ catch { }
746
+ }
747
+ let maxRuns = 1;
748
+ for (const c of cases) {
749
+ const runDirs = (await readdir(path.join(outputDir, c.id), { withFileTypes: true }))
750
+ .filter((e) => e.isDirectory() && e.name.startsWith("run-")).map((e) => e.name).sort();
751
+ maxRuns = Math.max(maxRuns, runDirs.length);
752
+ for (const runName of runDirs) {
753
+ const dir = path.join(outputDir, c.id, runName);
754
+ const rep = Number(runName.replace(/^run-/, "")) || 1;
755
+ const resultPath = path.join(dir, "result.json");
756
+ const prev = existsSync(resultPath) ? JSON.parse(await readFile(resultPath, "utf8")) : {};
757
+ const result = {
758
+ case: c.id, run: rep, status: prev.status ?? "completed", costUsd: prev.costUsd ?? null,
759
+ durationMs: prev.durationMs ?? 0, steps: prev.steps ?? 0, checks: { ...(prev.checks ?? {}) },
760
+ };
761
+ const scenePath = path.join(dir, "scene.json");
762
+ if (!existsSync(scenePath)) {
763
+ result.error = prev.error ?? "Missing scene.json (build did not save a scene).";
764
+ results.push(result);
765
+ log(`${c.id} ${runName}: skipped (no scene.json)`);
766
+ continue;
767
+ }
768
+ try {
769
+ const scene = withWompEnvironment(JSON.parse(await readFile(scenePath, "utf8")));
770
+ result.structure = sceneStructure(scene);
771
+ if (prev.front)
772
+ result.front = prev.front;
773
+ await kakapoRawRpc(options.kakapoUrl, "scene_state_set", [JSON.stringify(scene)]);
774
+ const api = new KakapoAPI({ url: options.kakapoUrl, requestTimeoutMs: 180_000 });
775
+ await api.connect();
776
+ try {
777
+ const boxes = await buildBoxes(api);
778
+ if (!boxes.length)
779
+ throw new Error("The build left nothing visible.");
780
+ const pts = await resolveVisiblePoints(api, scene);
781
+ const likenessPath = path.join(dir, "likeness.json");
782
+ const haveLikeness = existsSync(likenessPath);
783
+ if (haveLikeness)
784
+ result.likeness = JSON.parse(await readFile(likenessPath, "utf8"));
785
+ if (!haveLikeness || !result.front) {
786
+ const sides = await renderSides(api, boxes, dir);
787
+ if (!haveLikeness) {
788
+ result.likeness = await judgeLikeness(c, sides);
789
+ await writeFile(likenessPath, JSON.stringify(result.likeness, null, 1));
790
+ }
791
+ result.front ??= await judgeFront(sides);
792
+ }
793
+ if (!existsSync(path.join(dir, "turntable-grid.jpg"))) {
794
+ const tt = await renderViews(api, scene, boxes, pts, result.front, TURNTABLE_VIEWS, dir, "turntable");
795
+ await buildContactSheet(tt, path.join(dir, "turntable-grid.jpg"));
796
+ }
797
+ for (const check of c.checks ?? []) {
798
+ const checkPath = path.join(dir, `${check.id}.json`);
799
+ if (existsSync(checkPath)) {
800
+ result.checks[check.id] = JSON.parse(await readFile(checkPath, "utf8"));
801
+ }
802
+ else {
803
+ const shots = await renderViews(api, scene, boxes, pts, result.front, check.views, dir);
804
+ result.checks[check.id] = await judgeCheck(c, check, shots);
805
+ await writeFile(checkPath, JSON.stringify(result.checks[check.id], null, 1));
806
+ }
807
+ }
808
+ delete result.error;
809
+ }
810
+ finally {
811
+ api.disconnect();
812
+ }
813
+ log(`${c.id} ${runName}: scored, likeness ${fmt(result.likeness?.mean)}, ${Object.entries(result.checks).map(([k, v]) => `${k} ${fmt(v.mean)}`).join(", ")}`);
814
+ }
815
+ catch (error) {
816
+ result.error = error instanceof Error ? error.message : String(error);
817
+ log(`${c.id} ${runName}: failed (${result.error})`);
818
+ }
819
+ await writeFile(resultPath, JSON.stringify(result, null, 2));
820
+ results.push(result);
821
+ }
822
+ }
823
+ const report = summarize(cases, results, {
824
+ cases: caseDirs, repeat: maxRuns, parallel: 1, kakapoUrl: options.kakapoUrl,
825
+ settings, output: outputDir, timeoutMs: 0, signal: new AbortController().signal,
826
+ });
827
+ await writeBenchOutputs(outputDir, report, cases, results, options.baseline);
828
+ return report;
829
+ }
830
+ /** Rates each part 0-3 against the reference in `PART_JUDGE.votes` parallel calls; scores are median severities. */
831
+ async function judgeCheck(c, check, shots) {
832
+ const shown = shots.filter((s) => s.file);
833
+ const missing = shots.filter((s) => !s.file).map((s) => s.label ?? s.name);
834
+ const parts = Object.entries(check.items);
835
+ const content = [
836
+ { type: "text", text: `Image 1 is the reference picture a 3D build rebuilds. The other images are close-up renders of the build (${shown.map((s, i) => `image ${i + 2}: ${s.label ?? s.name}`).join("; ")}). Left and right mean the sides of the picture.${missing.length ? ` The build has nothing to show for: ${missing.join("; ")}.` : ""}
837
+ For each part below, first say what the reference shows for that part, then what the build shows, then rate it.
838
+ ${SEVERITY}
839
+ ${parts.map(([k, title]) => `- ${k}: the ${title} matches the reference as expected.`).join("\n")}
840
+ Name what is wrong with one or more of these tags when you rate 1 or more: ${TAGS}.
841
+ Answer only JSON, in this order:
842
+ {${parts.map(([k]) => `"${k}":{"reference":"...","build":"...","severity":0 to 3,"tags":[]}`).join(",")}}` },
843
+ await image(path.join(c.dir, c.reference)),
844
+ ...await Promise.all(shown.map((s) => image(s.file))),
845
+ ];
846
+ const votes = await Promise.all(Array.from({ length: PART_JUDGE.votes }, () => judge(content, "parts")));
847
+ const scores = Object.fromEntries(parts.map(([k]) => [k, median(votes.map((v) => Number(v[k]?.severity)))]));
848
+ const pass = Object.fromEntries(parts.map(([k]) => [k, scores[k] < PART_JUDGE.failAt]));
849
+ return { scores, pass, mean: mean(Object.values(pass).map(Number)), notes: votes };
850
+ }
851
+ /** Estimates spacing ribbing on a V3 Bezier curve (mirrors Kakapo CurveBezier.cpp spacing logic). */
852
+ export function curveRibbing(node, scale = 1) {
853
+ const pts = node?.points ?? [];
854
+ if (pts.length < 2 || (node.version ?? 0) < 3 || !(node.density > 0))
855
+ return null;
856
+ const MIN_FP = 0.00001, DENSE = 0.25, LEN_SCALE = 512 / 10 / 1000, MAX_PRIMS = 230, SAMPLES = 64;
857
+ const sub = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
858
+ const fp = (size, prim) => {
859
+ const sx = Math.abs(size.x), sy = Math.abs(size.y), sz = Math.abs(size.z);
860
+ const e = prim === 0 || prim === 11 ? { x: sx, y: sx, z: sx } : prim === 1 || prim === 3 ? { x: sx, y: sy, z: sx }
861
+ : prim === 13 ? { x: sx, y: Math.max(sy, sx), z: sx } : prim === 4 ? { x: sx, y: Math.min(sx, sy), z: sx } : { x: sx, y: sy, z: sz };
862
+ const f = [0, 11, 8, 1, 13, 3, 4].includes(prim) ? e.x : prim === 5 ? e.z : Math.min(e.x, e.y, e.z);
863
+ return { e, f: Math.max(MIN_FP, f) };
864
+ };
865
+ const segs = [];
866
+ const count = node.closed ? pts.length : pts.length - 1;
867
+ for (let i = 0; i < count; i++) {
868
+ const a = pts[i], b = pts[(i + 1) % pts.length];
869
+ const c1 = { x: a.pos.x + (a.handle_out?.x ?? 0), y: a.pos.y + (a.handle_out?.y ?? 0), z: a.pos.z + (a.handle_out?.z ?? 0) };
870
+ const c2 = { x: b.pos.x + (b.handle_in?.x ?? 0), y: b.pos.y + (b.handle_in?.y ?? 0), z: b.pos.z + (b.handle_in?.z ?? 0) };
871
+ let prev = null, distance = 0, posLen = 0, cov = 0, fpSum = 0;
872
+ for (let j = 0; j <= SAMPLES; j++) {
873
+ const u = j / SAMPLES, w = 1 - u, eu = u * u * (3 - 2 * u);
874
+ const pos = {
875
+ x: (a.pos.x * w * w * w + c1.x * 3 * w * w * u + c2.x * 3 * w * u * u + b.pos.x * u * u * u) * scale,
876
+ y: (a.pos.y * w * w * w + c1.y * 3 * w * w * u + c2.y * 3 * w * u * u + b.pos.y * u * u * u) * scale,
877
+ z: (a.pos.z * w * w * w + c1.z * 3 * w * w * u + c2.z * 3 * w * u * u + b.pos.z * u * u * u) * scale,
878
+ };
879
+ const sz = { x: (a.size.x * (1 - eu) + b.size.x * eu) * scale, y: (a.size.y * (1 - eu) + b.size.y * eu) * scale, z: (a.size.z * (1 - eu) + b.size.z * eu) * scale };
880
+ const { e, f } = fp(sz, node.prim);
881
+ fpSum += f;
882
+ if (prev) {
883
+ const dp = sub(pos, prev.pos), d = Math.hypot(dp, sub(e, prev.e));
884
+ distance += d;
885
+ posLen += dp;
886
+ cov += d / Math.max(MIN_FP, Math.min(f, prev.f) * DENSE);
887
+ }
888
+ prev = { pos, e, f };
889
+ }
890
+ const lenIntervals = Math.max(2, Math.ceil(250 * posLen * LEN_SCALE)) - 1;
891
+ segs.push({ distance, meanFp: fpSum / (SAMPLES + 1), full: Math.min(MAX_PRIMS, Math.max(1, Math.ceil(cov), lenIntervals)) });
892
+ }
893
+ const fullExtra = segs.reduce((acc, x) => acc + x.full - 1, 0);
894
+ let budget = Math.round(Math.min(1, node.density / 250) * Math.min(fullExtra, MAX_PRIMS - count));
895
+ const n = segs.map(() => 1);
896
+ while (budget-- > 0) {
897
+ let best = -1, bestGap = -1;
898
+ segs.forEach((sg, i) => { if (n[i] < sg.full && sg.distance / n[i] > bestGap) {
899
+ bestGap = sg.distance / n[i];
900
+ best = i;
901
+ } });
902
+ if (best < 0)
903
+ break;
904
+ n[best]++;
905
+ }
906
+ const ratios = segs.map((sg, i) => sg.distance / n[i] / sg.meanFp);
907
+ const depths = segs.map((sg, i) => (sg.distance / n[i]) ** 2 / (8 * sg.meanFp));
908
+ return { ratio: Math.max(...ratios), depth: Math.max(...depths), prims: n.reduce((a, b) => a + b, 0) + 1, density: node.density };
909
+ }
910
+ export function sceneStructure(scene) {
911
+ const N = scene.nodes ?? {}, T = scene.tree ?? {};
912
+ const s = { areas: 0, curves: 0, points: 0, primitives: 0, cubes: 0, seams: 0, ribbingDepth: 0, ribbedCurves: 0, floatingClusters: 0 };
913
+ let maxDepth = 0;
914
+ const additiveBoxes = [];
915
+ for (const [id, n] of Object.entries(N)) {
916
+ if (n.hide)
917
+ continue;
918
+ if (n.points?.length >= 2) {
919
+ s.curves++;
920
+ s.points += n.points.length;
921
+ const rib = curveRibbing(n);
922
+ if (rib) {
923
+ if (rib.depth > maxDepth)
924
+ maxDepth = rib.depth;
925
+ if (rib.ratio > 1.5 && rib.depth > 0.002)
926
+ s.ribbedCurves++;
927
+ }
928
+ }
929
+ if (n.type === 0) {
930
+ s.primitives++;
931
+ if (n.prim === 2 && n.op === 1)
932
+ s.cubes++;
933
+ }
934
+ if ((n.type === 0 || n.type === 3) && n.op === 1) {
935
+ for (const p of n.points ?? (n.type === 0 ? [n] : [])) {
936
+ if (!p?.pos || !p?.size)
937
+ continue;
938
+ const r = Math.max(p.size.x, p.size.y, p.size.z) * 0.52 + 0.015;
939
+ additiveBoxes.push({ box: [p.pos.x - r, p.pos.y - r, p.pos.z - r, p.pos.x + r, p.pos.y + r, p.pos.z + r], group: id });
940
+ }
941
+ }
942
+ }
943
+ s.ribbingDepth = Math.round(maxDepth * 1000 * 100) / 100;
944
+ const boxes = (n) => (n.points ?? (n.type === 0 ? [n] : [])).map((p) => {
945
+ const r = Math.max(p.size.x, p.size.y, p.size.z) * 0.45;
946
+ return [p.pos.x - r, p.pos.y - r, p.pos.z - r, p.pos.x + r, p.pos.y + r, p.pos.z + r];
947
+ });
948
+ const areas = new Map();
949
+ const collect = (id, area) => {
950
+ const n = N[id] ?? {};
951
+ if (n.hide)
952
+ return;
953
+ if (n.type === 1 && area === undefined) {
954
+ area = id;
955
+ areas.set(id, new Map());
956
+ }
957
+ else if (area !== undefined && (n.type === 0 || n.type === 3) && n.op === 1 && n.material_id != null) {
958
+ const byMaterial = areas.get(area);
959
+ byMaterial.set(n.material_id, [...byMaterial.get(n.material_id) ?? [], ...boxes(n)]);
960
+ }
961
+ for (const k of Object.keys(T[id] ?? {}).sort())
962
+ collect(String(T[id][k]), area);
963
+ };
964
+ collect("0");
965
+ const overlap = (a, b) => [0, 1, 2].every((i) => a[i] <= b[i + 3] && b[i] <= a[i + 3]);
966
+ s.areas = areas.size;
967
+ const list = [...areas.values()];
968
+ for (let i = 0; i < list.length; i++)
969
+ for (let j = i + 1; j < list.length; j++) {
970
+ if ([...list[i].keys()].some((m) => list[j].has(m) && list[i].get(m).some((a) => list[j].get(m).some((b) => overlap(a, b)))))
971
+ s.seams++;
972
+ }
973
+ // Connected components across visible additive geometry (same curve counts as connected).
974
+ if (additiveBoxes.length) {
975
+ const parent = additiveBoxes.map((_, i) => i);
976
+ const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));
977
+ const unite = (a, b) => { const ra = find(a), rb = find(b); if (ra !== rb)
978
+ parent[ra] = rb; };
979
+ for (let i = 0; i < additiveBoxes.length; i++) {
980
+ for (let j = i + 1; j < additiveBoxes.length; j++) {
981
+ if (additiveBoxes[i].group === additiveBoxes[j].group || overlap(additiveBoxes[i].box, additiveBoxes[j].box))
982
+ unite(i, j);
983
+ }
984
+ }
985
+ s.floatingClusters = new Set(additiveBoxes.map((_, i) => find(i))).size;
986
+ }
987
+ return s;
988
+ }
989
+ /** Writes report.json, report.md, results.csv, and full-res sheet.png for a bench output directory. */
990
+ async function writeBenchOutputs(outputDir, report, cases, results, baselineReport) {
991
+ await writeFile(path.join(outputDir, "report.json"), JSON.stringify(report, null, 2));
992
+ await writeFile(path.join(outputDir, "report.md"), reportMarkdown(report, baselineReport));
993
+ const cols = ["case", "run", "status", "steps", "buildMs", "renderMs", "judgeMs", "durationMs", "costUsd", "likeness", "areas", "curves", "cubes", "seams", "ribbingDepth", "floatingClusters", "error"];
994
+ const q = (v) => `"${String(v ?? "").replaceAll('"', '""')}"`;
995
+ const csvRows = results.map((r) => [
996
+ r.case, r.run, r.status, r.steps, r.timings?.buildMs ?? "", r.timings?.renderMs ?? "", r.timings?.judgeMs ?? "",
997
+ r.durationMs, r.costUsd ?? "", r.likeness?.mean ?? "", r.structure?.areas ?? "", r.structure?.curves ?? "",
998
+ r.structure?.cubes ?? "", r.structure?.seams ?? "", r.structure?.ribbingDepth ?? "", r.structure?.floatingClusters ?? "", r.error ?? "",
999
+ ].map(q).join(","));
1000
+ await writeFile(path.join(outputDir, "results.csv"), [cols.join(","), ...csvRows].join("\n"));
1001
+ const caseMap = new Map(cases.map((c) => [c.id, c]));
1002
+ const sheetRows = results.map((r) => ({
1003
+ caseId: r.case,
1004
+ run: r.run,
1005
+ runDir: path.join(outputDir, r.case, `run-${r.run}`),
1006
+ refFile: path.join(caseMap.get(r.case).dir, caseMap.get(r.case).reference),
1007
+ result: r,
1008
+ }));
1009
+ await buildMasterSheet(outputDir, sheetRows);
1010
+ }
1011
+ /** Generates or regenerates per-repeat `sheet-run-<n>.png` files for an existing bench output directory without running builds. */
1012
+ export async function generateBenchSheet(outputDir) {
1013
+ const caseDirs = (await readdir(outputDir, { withFileTypes: true }))
1014
+ .filter((e) => e.isDirectory() && !e.name.startsWith("_")).map((e) => e.name).sort();
1015
+ const cases = await Promise.all(caseDirs.map(loadQualityCase));
1016
+ const results = [];
1017
+ for (const c of cases) {
1018
+ const runDirs = (await readdir(path.join(outputDir, c.id), { withFileTypes: true }))
1019
+ .filter((e) => e.isDirectory() && e.name.startsWith("run-")).map((e) => e.name).sort();
1020
+ for (const runName of runDirs) {
1021
+ const dir = path.join(outputDir, c.id, runName);
1022
+ const rep = Number(runName.replace(/^run-/, "")) || 1;
1023
+ const rp = path.join(dir, "result.json");
1024
+ const r = existsSync(rp)
1025
+ ? JSON.parse(await readFile(rp, "utf8"))
1026
+ : { case: c.id, run: rep, status: "completed", costUsd: null, durationMs: 0, steps: 0, checks: {} };
1027
+ results.push(r);
1028
+ }
1029
+ }
1030
+ const caseMap = new Map(cases.map((c) => [c.id, c]));
1031
+ return buildMasterSheet(outputDir, results.map((r) => ({
1032
+ caseId: r.case, run: r.run, runDir: path.join(outputDir, r.case, `run-${r.run}`),
1033
+ refFile: path.join(caseMap.get(r.case).dir, caseMap.get(r.case).reference), result: r,
1034
+ })));
1035
+ }
1036
+ function summarize(cases, results, options) {
1037
+ const report = {
1038
+ version: 1, finishedAt: new Date().toISOString(), settings: options.settings,
1039
+ judge: options.judge ? JUDGES : "none (visual + structure only)", repeat: options.repeat, cases: {},
1040
+ };
1041
+ for (const c of cases) {
1042
+ const rs = results.filter((r) => r.case === c.id);
1043
+ const ok = rs.filter((r) => !r.error && (r.likeness || r.structure));
1044
+ const values = {};
1045
+ const add = (k, v) => { if (typeof v === "number" && Number.isFinite(v))
1046
+ (values[k] ??= []).push(v); };
1047
+ for (const r of ok) {
1048
+ if (r.likeness) {
1049
+ add("likeness", r.likeness.mean);
1050
+ for (const [k, v] of Object.entries(r.likeness.scores))
1051
+ add(`likeness.${k}`, v);
1052
+ }
1053
+ for (const [id, check] of Object.entries(r.checks)) {
1054
+ add(id, check.mean);
1055
+ for (const [k, v] of Object.entries(check.scores))
1056
+ add(`${id}.${k}`, v);
1057
+ }
1058
+ for (const [k, v] of Object.entries(r.structure ?? {}))
1059
+ add(`structure.${k}`, v);
1060
+ if (r.timings) {
1061
+ add("timing.buildS", r.timings.buildMs / 1000);
1062
+ add("timing.renderS", r.timings.renderMs / 1000);
1063
+ if (r.timings.judgeMs > 0)
1064
+ add("timing.judgeS", r.timings.judgeMs / 1000);
1065
+ }
1066
+ add("timing.totalS", r.durationMs / 1000);
1067
+ }
1068
+ const metrics = Object.fromEntries(Object.entries(values).map(([k, v]) => {
1069
+ const m = mean(v), sd = Math.sqrt(mean(v.map((x) => (x - m) ** 2)) * v.length / Math.max(1, v.length - 1));
1070
+ return [k, { mean: m, sd, n: v.length }];
1071
+ }));
1072
+ report.cases[c.id] = { runs: rs.length, failed: rs.length - ok.length, metrics, costUsd: rs.reduce((s, r) => s + (r.costUsd ?? 0), 0), durationS: Math.round(mean(rs.map((r) => r.durationMs)) / 1000) };
1073
+ }
1074
+ return report;
1075
+ }
1076
+ /** Markdown table per case; with a baseline report, each metric's change and whether it is beyond noise. */
1077
+ export function reportMarkdown(report, baseline) {
1078
+ const lines = [`# Quality bench`, ``, `${report.settings.modelId} (${report.settings.reasoningEffort}), judge ${report.judge}, ${report.repeat} runs per case, ${report.finishedAt}`, ``];
1079
+ for (const [id, c] of Object.entries(report.cases)) {
1080
+ lines.push(`## ${id}`, ``, `${c.runs - c.failed}/${c.runs} scored, $${c.costUsd.toFixed(2)} total, ${c.durationS} s per build`, ``);
1081
+ lines.push(baseline ? `| metric | mean | sd | baseline | change |` : `| metric | mean | sd |`, baseline ? `|---|---|---|---|---|` : `|---|---|---|`);
1082
+ for (const [k, m] of Object.entries(c.metrics)) {
1083
+ const b = baseline?.cases[id]?.metrics[k];
1084
+ if (!baseline) {
1085
+ lines.push(`| ${k} | ${fmt(m.mean)} | ${fmt(m.sd)} |`);
1086
+ continue;
1087
+ }
1088
+ // Two standard errors of the difference: a change inside it is noise at these run counts.
1089
+ const se = b ? Math.sqrt(m.sd ** 2 / m.n + b.sd ** 2 / b.n) : NaN, d = b ? m.mean - b.mean : NaN;
1090
+ lines.push(`| ${k} | ${fmt(m.mean)} | ${fmt(m.sd)} | ${b ? fmt(b.mean) : "–"} | ${b ? `${d >= 0 ? "+" : ""}${fmt(d)}${Math.abs(d) > 2 * se ? " **" : ""}` : "–"} |`);
1091
+ }
1092
+ lines.push(``);
1093
+ }
1094
+ if (baseline)
1095
+ lines.push(`** beyond two standard errors of the difference.`);
1096
+ return lines.join("\n");
1097
+ }
1098
+ function fmt(v, digits = 2) { return typeof v === "number" && Number.isFinite(v) ? v.toFixed(digits) : "–"; }
1099
+ /** The first balanced {...} in a reply (string-aware), so trailing text or a second object is ignored. */
1100
+ function firstObject(text) {
1101
+ const start = text.indexOf("{");
1102
+ let depth = 0, inString = false;
1103
+ for (let i = start; i >= 0 && i < text.length; i++) {
1104
+ const c = text[i];
1105
+ if (inString) {
1106
+ if (c === "\\")
1107
+ i++;
1108
+ else if (c === '"')
1109
+ inString = false;
1110
+ continue;
1111
+ }
1112
+ if (c === '"')
1113
+ inString = true;
1114
+ else if (c === "{")
1115
+ depth++;
1116
+ else if (c === "}" && --depth === 0)
1117
+ return text.slice(start, i + 1);
1118
+ }
1119
+ throw new Error(`The judge answered without JSON: ${text.slice(0, 200)}`);
1120
+ }