@womp/spark-agent 17.9.0 → 17.10.0

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.
@@ -1,36 +1,17 @@
1
1
  import { KakapoAPI } from "@womp/kakapo-sdk";
2
- import { type BenchBounds } from "./bench-camera.js";
3
2
  import type { SparkRunSettings } from "./server/types.js";
4
3
  export declare const QUALITY_CASES_DIR: string;
5
- /** Standardized multi-view turntable rendered around the matched front side (used by --ab pairwise judging on any object). */
4
+ /** Standardized multi-view turntable rendered around Spark's front side (used by --ab pairwise judging on any object). */
6
5
  export declare const TURNTABLE_VIEWS: QualityView[];
7
- /** A close-up framed on part of the build, from the side it faces turned by `turn` degrees about +Y. */
6
+ /** A whole-build view from Spark's front side, turned by `turn` degrees about +Y. */
8
7
  export interface QualityView {
9
8
  name: string;
10
- /** What the close-up shows, for the judge (e.g. "shoulders, three-quarter view"); defaults to `name`. */
9
+ /** What the view shows, for the pairwise judge; defaults to `name`. */
11
10
  label?: string;
12
- /** Frame the parts in this band of the build's height (0 = lowest point, 1 = highest)... */
13
- band?: [number, number];
14
- /** ...or the parts whose name matches this pattern (case-insensitive), minus `exclude`. */
15
- match?: string;
16
- exclude?: string;
17
- /** With `match`: keep the parts on one side of the build (a = its right, b = its left), e.g. one hand. */
18
- half?: "a" | "b";
19
11
  turn: number;
20
12
  /** Camera height: up component of the view direction. */
21
13
  tilt?: number;
22
14
  }
23
- /**
24
- * A judged check: close-ups of the build, and the parts the judge compares with the reference picture. Each item maps
25
- * a part key to the part's name as the judge should find it, e.g. "left shoulder (where the left-hand sleeve meets
26
- * the jacket)". The judge rates each part 0-3 (matches / minor detail / visible join or wrong shape / wrong); the
27
- * check's score is the share of parts that pass.
28
- */
29
- export interface QualityCheck {
30
- id: string;
31
- views: QualityView[];
32
- items: Record<string, string>;
33
- }
34
15
  export interface QualityCase {
35
16
  id: string;
36
17
  /** Optional benchmark split ("tune" for prompt iteration, "holdout" for regression gating). */
@@ -38,11 +19,8 @@ export interface QualityCase {
38
19
  prompt: string;
39
20
  /** Attached to the prompt, relative to the case directory. */
40
21
  images: string[];
41
- /** Picture the judges compare against (usually the front view), relative to the case directory. */
22
+ /** Picture the pairwise judge compares against (usually the front view), relative to the case directory. */
42
23
  reference: string;
43
- /** Parts the likeness judge scores 0-10, front render against the reference. */
44
- likeness: string[];
45
- checks: QualityCheck[];
46
24
  }
47
25
  export interface QualityBenchOptions {
48
26
  cases: string[];
@@ -51,8 +29,6 @@ export interface QualityBenchOptions {
51
29
  kakapoUrl: string;
52
30
  settings: SparkRunSettings;
53
31
  output: string;
54
- /** Run AI vision judges (likeness + close-up checks); defaults to false for fast visual sheet comparison. */
55
- judge?: boolean;
56
32
  timeoutMs: number;
57
33
  signal: AbortSignal;
58
34
  log?: (line: string) => void;
@@ -128,7 +104,6 @@ export declare function runQualityBench(options: QualityBenchOptions): Promise<Q
128
104
  export interface QualityTimings {
129
105
  buildMs: number;
130
106
  renderMs: number;
131
- judgeMs: number;
132
107
  }
133
108
  export interface QualityRunResult {
134
109
  case: string;
@@ -139,27 +114,12 @@ export interface QualityRunResult {
139
114
  durationMs: number;
140
115
  timings?: QualityTimings;
141
116
  steps: number;
142
- likeness?: Judged & {
143
- side: string;
144
- };
145
- /** The side render the judge named as the build's front (`DEFAULT_FRONT` without a judge); turntable views turn from it. */
146
- front?: string;
147
- checks: Record<string, Judged>;
148
117
  structure?: SceneStructure;
149
118
  }
150
- interface Judged {
151
- scores: Record<string, number>;
152
- mean: number;
153
- notes?: unknown;
154
- }
155
119
  /** Spark's public +Z is forward and maps to renderer -X, so a build that follows the convention faces the `nx` side. */
156
120
  export declare const DEFAULT_FRONT = "nx";
157
121
  /** Fixed Spark-space perspective shots (`benchCamera`), fitted to Kakapo's native world bounding box. */
158
122
  export declare function renderFixedCameras(api: KakapoAPI, dir: string): Promise<string[]>;
159
- /** The part of `box` inside `to`, or undefined when they do not overlap. */
160
- export declare function clipBox(box: BenchBounds, to: BenchBounds): BenchBounds | undefined;
161
- /** The side a front answer names; "none", an unknown label or a malformed answer keeps Spark's convention. */
162
- export declare function frontFromAnswer(answer: unknown, keys: string[]): string;
163
123
  export interface PairwiseResult {
164
124
  winner: "A" | "B" | "tie";
165
125
  consistent: boolean;
@@ -235,8 +195,8 @@ export declare function compareQualityRuns(baselineDir: string, candidateDir: st
235
195
  }): Promise<PairwiseComparisonReport>;
236
196
  export declare function pairwiseReportMarkdown(report: PairwiseComparisonReport): string;
237
197
  /**
238
- * Recovers and scores an existing bench output directory from its saved `scene.json` files (e.g. after a Kakapo crash),
239
- * rendering any missing views/grids and reusing existing judge JSONs so completed Spark builds are never wasted.
198
+ * Recovers an existing bench output directory from its saved `scene.json` files (e.g. after a Kakapo crash), recounting
199
+ * structure and rendering any missing turntable grid, so completed Spark builds are never wasted.
240
200
  */
241
201
  export declare function scoreExistingBenchRun(outputDir: string, options: {
242
202
  kakapoUrl: string;
@@ -272,7 +232,6 @@ export interface QualityReport {
272
232
  version: 1;
273
233
  finishedAt: string;
274
234
  settings: SparkRunSettings;
275
- judge: string;
276
235
  repeat: number;
277
236
  cases: Record<string, {
278
237
  runs: number;
@@ -290,4 +249,3 @@ export interface QualityReport {
290
249
  export declare function generateBenchSheet(outputDir: string): Promise<string[]>;
291
250
  /** Markdown table per case; with a baseline report, each metric's change and whether it is beyond noise. */
292
251
  export declare function reportMarkdown(report: QualityReport, baseline?: QualityReport): string;
293
- export {};
@@ -1,12 +1,12 @@
1
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.
2
+ // parallel through a Kakapo multiplexer, renders every build and counts its scene structure; --ab compares two runs
3
+ // with a blinded pairwise vision judge.
3
4
  // Cases live in bench/quality/cases/<id>/case.json with their images (git LFS). Dev tooling, not part of the agent API.
4
5
  import { once } from "node:events";
5
6
  import { appendFileSync, existsSync } from "node:fs";
6
7
  import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
7
8
  import path from "node:path";
8
9
  import { generateText } from "ai";
9
- import { createAnthropic } from "@ai-sdk/anthropic";
10
10
  import { createGoogleGenerativeAI } from "@ai-sdk/google";
11
11
  import { KakapoAPI } from "@womp/kakapo-sdk";
12
12
  import { prepareAgentInput } from "./agent-run-input.js";
@@ -17,15 +17,9 @@ import { buildMasterSheet } from "./quality-bench-sheet.js";
17
17
  import { createBenchMetrics } from "./run-metrics.js";
18
18
  import { createStandaloneSparkAgentApp } from "./server/standalone.js";
19
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). */
20
+ /** The pairwise judge (`--ab`). */
21
+ const PAIR_JUDGE = { model: "gemini-4-neon", thinking: "low" };
22
+ /** Standardized multi-view turntable rendered around Spark's front side (used by --ab pairwise judging on any object). */
29
23
  export const TURNTABLE_VIEWS = [
30
24
  { name: "front", turn: 0, tilt: 0.05, label: "whole build, front view" },
31
25
  { name: "quarter-l", turn: 38, tilt: 0.28, label: "whole build, elevated three-quarter left view" },
@@ -181,14 +175,11 @@ export async function runQualityBench(options) {
181
175
  const dir = path.join(options.output, job.c.id, `run-${job.rep}`);
182
176
  const result = await runOne(job.c, job.rep, `${muxUrl}/s/${job.c.id}-run-${job.rep}`, dir, options);
183
177
  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
178
  const t = result.timings;
188
179
  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` : ""}`
180
+ ? `build ${Math.round(t.buildMs / 1000)}s, render ${(t.renderMs / 1000).toFixed(1)}s`
190
181
  : `${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}`);
182
+ log(`${job.c.id} run-${job.rep}: ${result.status}${result.error ? ` (${result.error})` : ""}, $${fmt(result.costUsd, 2)}, ${timingSummary}`);
192
183
  }
193
184
  }));
194
185
  }
@@ -201,7 +192,7 @@ export async function runQualityBench(options) {
201
192
  }
202
193
  async function runOne(c, rep, kakapoUrl, dir, options) {
203
194
  await mkdir(dir, { recursive: true });
204
- const result = { case: c.id, run: rep, status: "failed", costUsd: null, durationMs: 0, steps: 0, checks: {} };
195
+ const result = { case: c.id, run: rep, status: "failed", costUsd: null, durationMs: 0, steps: 0 };
205
196
  const started = performance.now();
206
197
  const app = await createStandaloneSparkAgentApp({
207
198
  kakapoUrl, storagePath: ":memory:",
@@ -234,7 +225,7 @@ async function runOne(c, rep, kakapoUrl, dir, options) {
234
225
  await writeFile(path.join(dir, "conversation.json"), JSON.stringify(await transport.getConversation(conversation.id), null, 2));
235
226
  const api = new KakapoAPI({ url: kakapoUrl, requestTimeoutMs: 180_000 });
236
227
  await api.connect();
237
- let renderMs = 0, judgeMs = 0;
228
+ let renderMs = 0;
238
229
  try {
239
230
  const sceneText = String(await api.rpc("scene_state_get"));
240
231
  await writeFile(path.join(dir, "scene.json"), sceneText);
@@ -243,37 +234,13 @@ async function runOne(c, rep, kakapoUrl, dir, options) {
243
234
  const boxes = await buildBoxes(api);
244
235
  if (!boxes.length)
245
236
  throw new Error("The build left nothing visible.");
246
- const pts = await resolveVisiblePoints(api, scene);
247
237
  const r0 = performance.now();
248
238
  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");
239
+ await renderSides(api, boxes, dir);
240
+ const turntable = await renderViews(api, boxes, TURNTABLE_VIEWS, dir, "turntable");
263
241
  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) };
242
+ renderMs += performance.now() - r0;
243
+ result.timings = { buildMs, renderMs: Math.round(renderMs) };
277
244
  }
278
245
  finally {
279
246
  api.disconnect();
@@ -302,34 +269,6 @@ export const DEFAULT_FRONT = "nx";
302
269
  const CAPTURE_ASPECT = 16 / 9;
303
270
  /** Space around the build in every view: 10% of the frame's tighter dimension. */
304
271
  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
272
  /** Fixed Spark-space perspective shots (`benchCamera`), fitted to Kakapo's native world bounding box. */
334
273
  export async function renderFixedCameras(api, dir) {
335
274
  try {
@@ -373,82 +312,30 @@ async function renderSides(api, boxes, dir) {
373
312
  }
374
313
  return files;
375
314
  }
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 ?? "");
315
+ /** Whole-build views turned from Spark's front side, each fitted to the build's native boxes. */
316
+ async function renderViews(api, boxes, views, dir, prefix = "view") {
317
+ const [fx, fz] = SIDES[DEFAULT_FRONT];
386
318
  const out = [];
387
319
  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
320
  const a = view.turn * Math.PI / 180;
415
321
  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);
322
+ const camera = fitOrthographicCamera(boxes, { x: dx, y: view.tilt ?? 0.1, z: dz }, CAPTURE_ASPECT, VIEW_MARGIN);
417
323
  const file = path.join(dir, `${prefix}-${view.name}.jpg`);
418
324
  await writeFile(file, (await api.captureScreenshot({ camera, timeoutMs: 120_000 })).data);
419
325
  out.push({ name: view.name, label: view.label, file });
420
326
  }
421
327
  return out;
422
328
  }
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
329
  let google;
441
330
  /** One judge call; a failed call or an answer without JSON is retried twice. */
442
- async function judge(content, judgeModel = "likeness") {
331
+ async function judge(content) {
443
332
  for (let attempt = 0;; attempt++) {
444
333
  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 }] });
334
+ const { text } = await generateText({
335
+ model: (google ??= createGoogleGenerativeAI({ apiKey: process.env.GEMINI_API_KEY }))(PAIR_JUDGE.model),
336
+ providerOptions: { google: { thinkingConfig: { thinkingLevel: PAIR_JUDGE.thinking } } },
337
+ maxOutputTokens: 16_000, messages: [{ role: "user", content }],
338
+ });
452
339
  return JSON.parse(firstObject(text));
453
340
  }
454
341
  catch (error) {
@@ -463,62 +350,6 @@ function mediaType(file) {
463
350
  return ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : "image/jpeg";
464
351
  }
465
352
  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
353
  /** Resolves order-swapped forward (A, B) and reverse (B, A) pairwise judgements; disagreement becomes a tie. */
523
354
  export function resolvePairwiseSwap(forward, reverse) {
524
355
  const norm = (w) => (w === "A" ? "A" : w === "B" ? "B" : "tie");
@@ -562,7 +393,7 @@ Answer only JSON: {"a_flaws":"...","b_flaws":"...","winner":"A|B|tie","reason":"
562
393
  ...await Promise.all(first.map((s) => image(s.file))),
563
394
  ...await Promise.all(second.map((s) => image(s.file))),
564
395
  ];
565
- return judge(content, "parts");
396
+ return judge(content);
566
397
  };
567
398
  const [forward, reverse] = await Promise.all([oneCall(shownA, shownB), oneCall(shownB, shownA)]);
568
399
  return resolvePairwiseSwap(forward, reverse);
@@ -618,7 +449,7 @@ export async function compareQualityRuns(baselineDir, candidateDir, options = {}
618
449
  const commonCases = baseEntries.filter((c) => candEntries.has(c)).sort();
619
450
  const report = {
620
451
  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)" : ""}`,
452
+ judge: `${PAIR_JUDGE.model} (${PAIR_JUDGE.thinking}), order-swapped pairwise${options.allPairs !== false ? " (all-vs-all)" : ""}`,
622
453
  overall: { pairs: 0, candidateWins: 0, baselineWins: 0, ties: 0, consistent: 0 },
623
454
  cases: {},
624
455
  };
@@ -727,8 +558,8 @@ export function pairwiseReportMarkdown(report) {
727
558
  return lines.join("\n");
728
559
  }
729
560
  /**
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.
561
+ * Recovers an existing bench output directory from its saved `scene.json` files (e.g. after a Kakapo crash), recounting
562
+ * structure and rendering any missing turntable grid, so completed Spark builds are never wasted.
732
563
  */
733
564
  export async function scoreExistingBenchRun(outputDir, options) {
734
565
  const log = options.log ?? console.log;
@@ -756,7 +587,7 @@ export async function scoreExistingBenchRun(outputDir, options) {
756
587
  const prev = existsSync(resultPath) ? JSON.parse(await readFile(resultPath, "utf8")) : {};
757
588
  const result = {
758
589
  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 ?? {}) },
590
+ durationMs: prev.durationMs ?? 0, steps: prev.steps ?? 0,
760
591
  };
761
592
  const scenePath = path.join(dir, "scene.json");
762
593
  if (!existsSync(scenePath)) {
@@ -768,8 +599,6 @@ export async function scoreExistingBenchRun(outputDir, options) {
768
599
  try {
769
600
  const scene = withWompEnvironment(JSON.parse(await readFile(scenePath, "utf8")));
770
601
  result.structure = sceneStructure(scene);
771
- if (prev.front)
772
- result.front = prev.front;
773
602
  await kakapoRawRpc(options.kakapoUrl, "scene_state_set", [JSON.stringify(scene)]);
774
603
  const api = new KakapoAPI({ url: options.kakapoUrl, requestTimeoutMs: 180_000 });
775
604
  await api.connect();
@@ -777,40 +606,16 @@ export async function scoreExistingBenchRun(outputDir, options) {
777
606
  const boxes = await buildBoxes(api);
778
607
  if (!boxes.length)
779
608
  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
609
  if (!existsSync(path.join(dir, "turntable-grid.jpg"))) {
794
- const tt = await renderViews(api, scene, boxes, pts, result.front, TURNTABLE_VIEWS, dir, "turntable");
610
+ const tt = await renderViews(api, boxes, TURNTABLE_VIEWS, dir, "turntable");
795
611
  await buildContactSheet(tt, path.join(dir, "turntable-grid.jpg"));
796
612
  }
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
613
  delete result.error;
809
614
  }
810
615
  finally {
811
616
  api.disconnect();
812
617
  }
813
- log(`${c.id} ${runName}: scored, likeness ${fmt(result.likeness?.mean)}, ${Object.entries(result.checks).map(([k, v]) => `${k} ${fmt(v.mean)}`).join(", ")}`);
618
+ log(`${c.id} ${runName}: scored`);
814
619
  }
815
620
  catch (error) {
816
621
  result.error = error instanceof Error ? error.message : String(error);
@@ -827,27 +632,6 @@ export async function scoreExistingBenchRun(outputDir, options) {
827
632
  await writeBenchOutputs(outputDir, report, cases, results, options.baseline);
828
633
  return report;
829
634
  }
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
635
  /** Estimates spacing ribbing on a V3 Bezier curve (mirrors Kakapo CurveBezier.cpp spacing logic). */
852
636
  export function curveRibbing(node, scale = 1) {
853
637
  const pts = node?.points ?? [];
@@ -990,11 +774,11 @@ export function sceneStructure(scene) {
990
774
  async function writeBenchOutputs(outputDir, report, cases, results, baselineReport) {
991
775
  await writeFile(path.join(outputDir, "report.json"), JSON.stringify(report, null, 2));
992
776
  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"];
777
+ const cols = ["case", "run", "status", "steps", "buildMs", "renderMs", "durationMs", "costUsd", "areas", "curves", "cubes", "seams", "ribbingDepth", "floatingClusters", "error"];
994
778
  const q = (v) => `"${String(v ?? "").replaceAll('"', '""')}"`;
995
779
  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 ?? "",
780
+ r.case, r.run, r.status, r.steps, r.timings?.buildMs ?? "", r.timings?.renderMs ?? "",
781
+ r.durationMs, r.costUsd ?? "", r.structure?.areas ?? "", r.structure?.curves ?? "",
998
782
  r.structure?.cubes ?? "", r.structure?.seams ?? "", r.structure?.ribbingDepth ?? "", r.structure?.floatingClusters ?? "", r.error ?? "",
999
783
  ].map(q).join(","));
1000
784
  await writeFile(path.join(outputDir, "results.csv"), [cols.join(","), ...csvRows].join("\n"));
@@ -1023,7 +807,7 @@ export async function generateBenchSheet(outputDir) {
1023
807
  const rp = path.join(dir, "result.json");
1024
808
  const r = existsSync(rp)
1025
809
  ? JSON.parse(await readFile(rp, "utf8"))
1026
- : { case: c.id, run: rep, status: "completed", costUsd: null, durationMs: 0, steps: 0, checks: {} };
810
+ : { case: c.id, run: rep, status: "completed", costUsd: null, durationMs: 0, steps: 0 };
1027
811
  results.push(r);
1028
812
  }
1029
813
  }
@@ -1035,33 +819,20 @@ export async function generateBenchSheet(outputDir) {
1035
819
  }
1036
820
  function summarize(cases, results, options) {
1037
821
  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: {},
822
+ version: 1, finishedAt: new Date().toISOString(), settings: options.settings, repeat: options.repeat, cases: {},
1040
823
  };
1041
824
  for (const c of cases) {
1042
825
  const rs = results.filter((r) => r.case === c.id);
1043
- const ok = rs.filter((r) => !r.error && (r.likeness || r.structure));
826
+ const ok = rs.filter((r) => !r.error && r.structure);
1044
827
  const values = {};
1045
828
  const add = (k, v) => { if (typeof v === "number" && Number.isFinite(v))
1046
829
  (values[k] ??= []).push(v); };
1047
830
  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
831
  for (const [k, v] of Object.entries(r.structure ?? {}))
1059
832
  add(`structure.${k}`, v);
1060
833
  if (r.timings) {
1061
834
  add("timing.buildS", r.timings.buildMs / 1000);
1062
835
  add("timing.renderS", r.timings.renderMs / 1000);
1063
- if (r.timings.judgeMs > 0)
1064
- add("timing.judgeS", r.timings.judgeMs / 1000);
1065
836
  }
1066
837
  add("timing.totalS", r.durationMs / 1000);
1067
838
  }
@@ -1075,7 +846,7 @@ function summarize(cases, results, options) {
1075
846
  }
1076
847
  /** Markdown table per case; with a baseline report, each metric's change and whether it is beyond noise. */
1077
848
  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}`, ``];
849
+ const lines = [`# Quality bench`, ``, `${report.settings.modelId} (${report.settings.reasoningEffort}), ${report.repeat} runs per case, ${report.finishedAt}`, ``];
1079
850
  for (const [id, c] of Object.entries(report.cases)) {
1080
851
  lines.push(`## ${id}`, ``, `${c.runs - c.failed}/${c.runs} scored, $${c.costUsd.toFixed(2)} total, ${c.durationS} s per build`, ``);
1081
852
  lines.push(baseline ? `| metric | mean | sd | baseline | change |` : `| metric | mean | sd |`, baseline ? `|---|---|---|---|---|` : `|---|---|---|`);