Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Evaluation harness: the runner, report, blind A/B review, compare and promote

Claudee2fd067fb540
diff --git a/eslint.config.mjs b/eslint.config.mjs
index e1f3d63a..6197aace 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -15,6 +15,10 @@ const eslintConfig = defineConfig([
// Agent worktrees and local data live inside the checkout but aren't part of it.
".claude/**",
"data/**",
+ // The evaluation harness's metrics venv, run results and your own inputs (all git-ignored).
+ "scripts/eval/metrics/.venv/**",
+ "scripts/eval/results/**",
+ "scripts/eval/local/**",
]),
]);
diff --git a/package.json b/package.json
index b6181572..80e7dab6 100644
--- a/package.json
+++ b/package.json
@@ -17,7 +17,15 @@
"test:e2e:mobile": "node tests/e2e/no-horizontal-scroll.mjs",
"test:e2e:shell": "node tests/e2e/shell.mjs",
"gen:catalog": "python3 scripts/gen-cloud-models.py && python3 scripts/gen-higgsfield-models.py && python3 scripts/gen-higgsfield-presets.py && python3 scripts/gen-oss-loras.py && node scripts/gen-icon-map.mjs",
- "typecheck": "tsc --noEmit"
+ "typecheck": "tsc --noEmit",
+ "eval:run": "node scripts/eval/eval.mjs run",
+ "eval:report": "node scripts/eval/eval.mjs report",
+ "eval:review": "node scripts/eval/eval.mjs review",
+ "eval:compare": "node scripts/eval/eval.mjs compare",
+ "eval:promote": "node scripts/eval/eval.mjs promote",
+ "eval:history": "node scripts/eval/eval.mjs history",
+ "eval:validate": "node scripts/eval/eval.mjs validate",
+ "eval:setup": "node scripts/eval/eval.mjs setup"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.135.0",
diff --git a/scripts/eval/eval.mjs b/scripts/eval/eval.mjs
new file mode 100644
index 00000000..8eeaf0ef
--- /dev/null
+++ b/scripts/eval/eval.mjs
@@ -0,0 +1,354 @@
+#!/usr/bin/env node
+// The evaluation harness's command line: pnpm eval:<command> (or fuobe eval <command>). See
+// scripts/eval/README.md. Every command takes --json for scripts, and --url / --token for the
+// Fuobe to measure (else FUOBE_URL / FUOBE_TOKEN, else what `fuobe login` saved).
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { parseArgs } from "node:util";
+import { loadSuite, suiteFiles, validateAll } from "./lib/cases.mjs";
+import { compareRuns, compareText, promote, promoteText } from "./lib/compare.mjs";
+import { scoreRun } from "./lib/metrics.mjs";
+import { METRICS_DIR, REPO_DIR, resultsDir } from "./lib/paths.mjs";
+import { writeReport } from "./lib/report.mjs";
+import { serveReview, writeReview } from "./lib/review.mjs";
+import { DEFAULT_CLOUD_CAP, money, runEval } from "./lib/run.mjs";
+import { connect } from "./lib/server.mjs";
+import { listRuns, readJsonl, resolveRun } from "./lib/store.mjs";
+
+const list = (v) => (v ? String(v).split(",").map((s) => s.trim()).filter(Boolean) : undefined);
+const num = (v, name) => {
+ if (v === undefined) return undefined;
+ const n = Number(v);
+ if (!Number.isFinite(n)) throw new Usage(`--${name} takes a number, not “${v}”`);
+ return n;
+};
+
+class Usage extends Error {}
+
+const COMMON = { url: { type: "string" }, token: { type: "string" }, out: { type: "string" }, json: { type: "boolean" }, help: { type: "boolean", short: "h" } };
+const SCORE = { "no-metrics": { type: "boolean" }, metrics: { type: "string" }, device: { type: "string" }, "clip-model": { type: "string" }, "identity-model": { type: "string" }, "accept-noncommercial": { type: "boolean" }, force: { type: "boolean" } };
+
+const HELP = {
+ run: `pnpm eval:run --suite <name> --engine demo|open|cloud [options]
+
+ --suite <name|file> soul, soul-id, dop, genjutsu, mixed-media, shorts, speak, cinema, selftest (or a path)
+ --engine <e> demo (free self-test), open (your ComfyUI) or cloud (hosted open models)
+ --looks <a,b> Soul looks by slug, name or id (v1-general, "Flash editorial")
+ --cases <ids> case ids or prefixes with * (dop/motion-*)
+ --tags <t> cases with any of these tags (v1, civitai, train-own…)
+ --variants <a,b> recipe variants to run (default: the suite's default); all = every variant
+ --model <id> one model id for every job instead of the suite's targets
+ --limit <n> at most n cases · --prompts <n> at most n prompts per case · --seeds 1,2
+ --dry-run list the jobs and the estimated spend; uploads and starts nothing
+ --max-usd <n> the cloud spend cap (default $${DEFAULT_CLOUD_CAP}); the run stops before going over
+ --concurrency <n> jobs at a time (open 1, others 4)
+ --resume <runId> run the failed and missing jobs of an earlier run again
+ --allow-fixtures use the synthetic fixtures where your own inputs are missing
+ --comfy-url <url> ComfyUI's address, for memory and its own timings (open engine; default COMFYUI_URL)
+ --label <text> a note for this run
+ --no-metrics don't score afterwards · --no-report: don't write the report either`,
+ report: "pnpm eval:report <runId|latest> [--no-metrics] [--metrics clip,style] [--device cpu|cuda|auto] [--force]",
+ review: "pnpm eval:review <runId|latest> [--against variants|references|<otherRunId>] [--port 4173] [--no-serve] [--limit n]",
+ compare: "pnpm eval:compare <runA[:variant]> <runB[:variant]> [--fail-on clip,aesthetic] [--threshold 1|5%] [--per-case]",
+ promote: "pnpm eval:promote <runId> [--candidate recipe] [--against prompt-only,half-strength,plain]",
+ history: "pnpm eval:history [--suite soul] [--case soul/v1-general] [--limit 20]",
+ validate: "pnpm eval:validate [suite files…] checks every case file and that the generated suites match the research",
+ setup: "pnpm eval:setup [--identity] [--download] [--torch-backend cpu|auto|cu128…] the metrics venv (needs uv)",
+};
+
+function usage() {
+ return [
+ "Fuobe evaluation harness. Commands:",
+ ...Object.values(HELP).map((h) => ` ${h.split("\n")[0]}`),
+ "",
+ "Results go to scripts/eval/results/<runId>/ (git-ignored; --out or FUOBE_EVAL_RESULTS to move them).",
+ "More: scripts/eval/README.md",
+ ].join("\n");
+}
+
+/**
+ * @param {string[]} argv the arguments after the command name's position (command first)
+ * @param {{ stdout?: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, env?: Record<string, string | undefined>, fetch?: typeof fetch, signal?: AbortSignal }} [io]
+ * @returns {Promise<number>} the exit code
+ */
+export async function main(argv, io = {}) {
+ const out = io.stdout ?? process.stdout;
+ const err = io.stderr ?? process.stderr;
+ const env = io.env ?? process.env;
+ const print = (s) => out.write(`${s}\n`);
+ const note = (s) => err.write(`${s}\n`);
+ const [command, ...rest] = argv;
+ if (!command || command === "help" || command === "--help" || command === "-h") {
+ print(rest[0] && HELP[rest[0]] ? HELP[rest[0]] : usage());
+ return 0;
+ }
+ const commands = { run, report, review, compare, promote: promoteCmd, history, validate, setup };
+ if (!commands[command]) {
+ note(`Unknown command “${command}”.\n${usage()}`);
+ return 2;
+ }
+ try {
+ return (await commands[command](rest, { print, note, env, io })) ?? 0;
+ } catch (e) {
+ if (e instanceof Usage) {
+ note(`${e.message}\n\n${HELP[command] ?? usage()}`);
+ return 2;
+ }
+ if (env.FUOBE_DEBUG) note(e.stack);
+ note(e.message);
+ return 1;
+ }
+}
+
+function parse(args, options, { positionals = false } = {}) {
+ try {
+ return parseArgs({ args, options: { ...COMMON, ...options }, allowPositionals: positionals, strict: true });
+ } catch (e) {
+ throw new Usage(e.message.replace(/^TypeError \[[A-Z_]+\]: /, ""));
+ }
+}
+
+const root = (values, env) => resultsDir(env, values.out);
+
+async function score(dir, v, ctx) {
+ if (v["no-metrics"]) return null;
+ ctx.note("Scoring the outputs…");
+ const r = await scoreRun(dir, { metrics: v.metrics, device: v.device, clipModel: v["clip-model"], identityModel: v["identity-model"], acceptNoncommercial: v["accept-noncommercial"], force: v.force, log: ctx.note, env: ctx.env });
+ if (!r.ok) ctx.note(`Not scored: ${r.reason}. Timing and cost are in the report; pnpm eval:report ${path.basename(dir)} scores it later.`);
+ return r;
+}
+
+function reportAll(dir, rootDir, ctx) {
+ const summary = writeReport(dir, rootDir);
+ const loaded = { dir, runId: summary.runId, rows: readJsonl(path.join(dir, "jobs.jsonl")) };
+ // The latest row per job (a resumed run appends retries).
+ loaded.rows = [...new Map(loaded.rows.map((r) => [r.id, r])).values()];
+ const rv = writeReview(loaded);
+ ctx.note(`Report: ${path.join(dir, "report.html")}`);
+ ctx.note(`Review: ${rv.pairs} blind pair${rv.pairs === 1 ? "" : "s"} · pnpm eval:review ${summary.runId}`);
+ return summary;
+}
+
+function printSummary(summary, ctx) {
+ const free = summary.engine !== "cloud";
+ ctx.print(`${summary.title} · ${summary.engine} · ${summary.counts.succeeded}/${summary.counts.jobs} done${summary.counts.failed ? ` · ${summary.counts.failed} failed` : ""}${summary.counts.skipped ? ` · ${summary.counts.skipped} skipped` : ""} · ${free ? "Free" : money(summary.costUsd.spent)}`);
+ for (const [v, s] of Object.entries(summary.variants)) {
+ const means = Object.entries(s.mean)
+ .map(([k, x]) => `${k} ${k === "costUsd" ? money(x) : Number(x).toFixed(k === "clip" || k === "seconds" ? 1 : 3)}`)
+ .join(" · ");
+ ctx.print(` ${v}: ${s.succeeded}/${s.jobs}${means ? ` · ${means}` : ""}`);
+ }
+ for (const s of summary.skips.slice(0, 5)) ctx.print(` skipped ${s.count}: ${s.reason}`);
+ for (const f of summary.failures.slice(0, 5)) ctx.print(` failed ${f.id}: ${f.error}`);
+}
+
+async function run(args, ctx) {
+ const { values: v } = parse(args, {
+ suite: { type: "string" },
+ engine: { type: "string" },
+ looks: { type: "string" },
+ cases: { type: "string" },
+ tags: { type: "string" },
+ variants: { type: "string" },
+ model: { type: "string" },
+ limit: { type: "string" },
+ prompts: { type: "string" },
+ seeds: { type: "string" },
+ "dry-run": { type: "boolean" },
+ list: { type: "boolean" },
+ "max-usd": { type: "string" },
+ concurrency: { type: "string" },
+ resume: { type: "string" },
+ "allow-fixtures": { type: "boolean" },
+ "comfy-url": { type: "string" },
+ label: { type: "string" },
+ "no-report": { type: "boolean" },
+ ...SCORE,
+ });
+ if (v.help) return ctx.print(HELP.run), 0;
+ const rootDir = root(v, ctx.env);
+ // A resumed run keeps its own suite and engine.
+ const resumeRun = v.resume ? resolveRun(rootDir, v.resume) : null;
+ const before = resumeRun ? JSON.parse(fs.readFileSync(path.join(resumeRun.dir, "run.json"), "utf8")) : null;
+ const suiteName = v.suite ?? before?.harness?.suiteFile ?? before?.suite;
+ if (!suiteName) throw new Usage("Name a suite with --suite (soul, dop, selftest…)");
+ const suite = loadSuite(before?.harness?.suiteFile && !v.suite ? path.join(REPO_DIR, before.harness.suiteFile) : suiteName);
+ const engine = v.engine ?? before?.engine;
+ if (!["demo", "open", "cloud"].includes(engine)) throw new Usage("Pick --engine demo, open or cloud");
+ const variants = v.variants === "all" ? Object.keys(suite.variants ?? { default: {} }) : list(v.variants);
+ const { client, target } = connect({ url: v.url, token: v.token }, { env: ctx.env, fetch: ctx.io.fetch });
+ const ac = new AbortController();
+ const signal = ctx.io.signal ?? ac.signal;
+ const onInt = () => {
+ if (ac.signal.aborted) process.exit(130);
+ ctx.note("Stopping: no new jobs start; the ones running keep going on the server. Ctrl+C again to quit now.");
+ ac.abort();
+ };
+ if (!ctx.io.signal) process.on("SIGINT", onInt);
+ try {
+ const result = await runEval(
+ {
+ suite,
+ engine,
+ variants,
+ cases: list(v.cases),
+ looks: list(v.looks),
+ tags: list(v.tags),
+ limit: num(v.limit, "limit"),
+ prompts: num(v.prompts, "prompts"),
+ seeds: list(v.seeds)?.map((s) => num(s, "seeds")),
+ model: v.model,
+ dryRun: v["dry-run"],
+ maxUsd: num(v["max-usd"], "max-usd"),
+ concurrency: num(v.concurrency, "concurrency"),
+ root: rootDir,
+ resume: resumeRun?.runId,
+ allowFixtures: v["allow-fixtures"],
+ comfyUrl: v["comfy-url"] ?? (engine === "open" ? (ctx.env.COMFYUI_URL ?? "http://127.0.0.1:8188") : undefined),
+ label: v.label,
+ },
+ { client, target, log: ctx.note, signal, fetch: ctx.io.fetch },
+ );
+ if (result.dryRun) {
+ if (v.json) return ctx.print(JSON.stringify(result, null, 2)), 0;
+ const free = engine !== "cloud";
+ ctx.print(`${suite.title} on ${engine} (${result.server})`);
+ ctx.print(`${result.jobs} jobs · ${result.runnable} can run · ${result.skipped} skipped · ${result.cases} cases · estimated ${free ? "Free" : money(result.estimateUsd)}${result.unknownCost ? ` (+${result.unknownCost} without a price)` : ""}${engine === "cloud" ? ` · cap ${money(result.maxUsd)}` : ""}`);
+ if (result.models.length) ctx.print(`Models: ${result.models.join(", ")} · variants: ${result.variants.join(", ")}`);
+ for (const [why, n] of Object.entries(result.skipReasons).sort((a, b) => b[1] - a[1]).slice(0, 8)) ctx.print(` ${n} skipped: ${why}`);
+ if (v.list) for (const j of result.jobs) ctx.print(` ${j.skip ? "·" : "▸"} ${j.case} · ${j.variant} · ${j.prompt} · s${j.seed} · ${j.model} · ${j.costUsd == null ? "?" : free ? "Free" : money(j.costUsd)}${j.loras?.applied ? ` · ${j.loras.applied.join(" + ") || "no LoRAs"}` : ""}${j.skip ? ` — ${j.skip}` : ""}`);
+ return 0;
+ }
+ if (v["no-report"]) {
+ ctx.note(`Results: ${result.dir}`);
+ return result.run.results.failed ? 1 : 0;
+ }
+ await score(result.dir, v, ctx);
+ const summary = reportAll(result.dir, rootDir, ctx);
+ if (v.json) ctx.print(JSON.stringify(summary, null, 2));
+ else printSummary(summary, ctx);
+ return summary.counts.failed || result.run.interrupted ? 1 : 0;
+ } finally {
+ if (!ctx.io.signal) process.off("SIGINT", onInt);
+ }
+}
+
+async function report(args, ctx) {
+ const { values: v, positionals } = parse(args, SCORE, { positionals: true });
+ if (v.help) return ctx.print(HELP.report), 0;
+ const rootDir = root(v, ctx.env);
+ const { dir } = resolveRun(rootDir, positionals[0] ?? "latest");
+ await score(dir, v, ctx);
+ const summary = reportAll(dir, rootDir, ctx);
+ if (v.json) ctx.print(JSON.stringify(summary, null, 2));
+ else printSummary(summary, ctx);
+ return 0;
+}
+
+async function review(args, ctx) {
+ const { values: v, positionals } = parse(args, { against: { type: "string" }, port: { type: "string" }, "no-serve": { type: "boolean" }, limit: { type: "string" } }, { positionals: true });
+ if (v.help) return ctx.print(HELP.review), 0;
+ const rootDir = root(v, ctx.env);
+ const { dir, runId } = resolveRun(rootDir, positionals[0] ?? "latest");
+ let against = v.against;
+ if (against && !["variants", "references"].includes(against)) {
+ const other = resolveRun(rootDir, against);
+ against = { dir: other.dir, runId: other.runId, rows: [...new Map(readJsonl(path.join(other.dir, "jobs.jsonl")).map((r) => [r.id, r])).values()] };
+ }
+ const rows = [...new Map(readJsonl(path.join(dir, "jobs.jsonl")).map((r) => [r.id, r])).values()];
+ const r = writeReview({ dir, runId, rows }, { against, limit: num(v.limit, "limit") });
+ if (!r.pairs) ctx.note("Nothing to compare yet: the run needs two variants of a case, your own references (scripts/eval/local/references/…), or --against another run.");
+ if (v["no-serve"]) {
+ ctx.print(r.file);
+ return 0;
+ }
+ const { server, url } = await serveReview(dir, { port: num(v.port, "port") ?? 4173 });
+ ctx.print(`Blind review of ${r.pairs} pair${r.pairs === 1 ? "" : "s"}: ${url}`);
+ ctx.note("Ratings are saved to review/ratings.json as you go. Ctrl+C stops the server; pnpm eval:report then adds them to the summary.");
+ await new Promise((resolve) => {
+ const stop = () => server.close(resolve);
+ process.once("SIGINT", stop);
+ ctx.io.signal?.addEventListener("abort", stop, { once: true });
+ });
+ return 0;
+}
+
+async function compare(args, ctx) {
+ const { values: v, positionals } = parse(args, { "fail-on": { type: "string" }, metric: { type: "string" }, threshold: { type: "string" }, "per-case": { type: "boolean" } }, { positionals: true });
+ if (v.help) return ctx.print(HELP.compare), 0;
+ if (positionals.length !== 2) throw new Usage("Give two runs: pnpm eval:compare <runA> <runB> (latest~1 latest compares the last two)");
+ const rootDir = root(v, ctx.env);
+ const a = resolveRun(rootDir, positionals[0]);
+ const b = resolveRun(rootDir, positionals[1]);
+ const c = compareRuns(a, b, { failOn: list(v["fail-on"] ?? v.metric), threshold: v.threshold, perCase: v["per-case"] });
+ ctx.print(v.json ? JSON.stringify(c, null, 2) : compareText(c));
+ return c.failed ? 1 : 0;
+}
+
+async function promoteCmd(args, ctx) {
+ const { values: v, positionals } = parse(args, { candidate: { type: "string" }, against: { type: "string" } }, { positionals: true });
+ if (v.help) return ctx.print(HELP.promote), 0;
+ const { dir } = resolveRun(root(v, ctx.env), positionals[0] ?? "latest");
+ const doc = promote(dir, { candidate: v.candidate, alternatives: list(v.against) });
+ ctx.print(v.json ? JSON.stringify(doc, null, 2) : promoteText(doc));
+ return 0;
+}
+
+async function history(args, ctx) {
+ const { values: v } = parse(args, { suite: { type: "string" }, case: { type: "string" }, limit: { type: "string" } });
+ if (v.help) return ctx.print(HELP.history), 0;
+ const rootDir = root(v, ctx.env);
+ const runs = listRuns(rootDir).filter((r) => !v.suite || r.run.suite === v.suite);
+ const rows = readJsonl(path.join(rootDir, "history.jsonl")).filter((r) => (!v.suite || r.suite === v.suite) && (!v.case || r.caseId === v.case));
+ if (v.json) return ctx.print(JSON.stringify({ runs: runs.map((r) => ({ runId: r.runId, ...r.run.results, engine: r.run.engine, suite: r.run.suite, startedAt: r.run.startedAt, label: r.run.label })), history: rows }, null, 2)), 0;
+ if (!runs.length) return ctx.print(`No runs in ${rootDir} yet. Start with: pnpm eval:run --suite selftest --engine demo`), 0;
+ for (const r of runs.slice(0, num(v.limit, "limit") ?? 20)) {
+ const res = r.run.results ?? {};
+ ctx.print(`${r.runId} ${r.run.engine} ${res.succeeded ?? 0} done${res.failed ? ` · ${res.failed} failed` : ""}${res.skipped ? ` · ${res.skipped} skipped` : ""}${r.run.engine === "cloud" && r.run.spentUsd != null ? ` · ${money(r.run.spentUsd)}` : ""}${r.run.label ? ` ${r.run.label}` : ""}`);
+ }
+ if (v.case) for (const h of rows) ctx.print(` ${h.runId} ${h.variant}: ${Object.entries(h.scores).map(([k, x]) => `${k} ${Number(x).toFixed(3)}`).join(" · ")}`);
+ return 0;
+}
+
+async function validate(args, ctx) {
+ const { values: v, positionals } = parse(args, {}, { positionals: true });
+ const results = validateAll(positionals.length ? positionals.map((p) => path.resolve(p)) : suiteFiles());
+ let bad = results.filter((r) => !r.ok).length;
+ const { generated } = await import("./gen-cases.mjs");
+ const gen = generated();
+ const stale = ["soul.json", "dop.json", "case.schema.json"].filter((name) => {
+ const file = path.join(path.dirname(new URL(import.meta.url).pathname), "cases", name);
+ const want = `${JSON.stringify(gen[name], null, 2)}\n`;
+ return !fs.existsSync(file) || fs.readFileSync(file, "utf8") !== want;
+ });
+ if (v.json) return ctx.print(JSON.stringify({ suites: results, stale }, null, 2)), bad || stale.length ? 1 : 0;
+ for (const r of results) {
+ ctx.print(`${r.ok ? "✓" : "✗"} ${path.relative(REPO_DIR, r.file)}${r.ok ? ` · ${r.cases} cases` : ""}`);
+ for (const l of r.lines) ctx.print(` ${l}`);
+ }
+ for (const s of stale) ctx.print(`✗ cases/${s} is out of date with the research: node scripts/eval/gen-cases.mjs`);
+ bad += stale.length;
+ return bad ? 1 : 0;
+}
+
+async function setup(args, ctx) {
+ const { values: v } = parse(args, { identity: { type: "boolean" }, download: { type: "boolean" }, "torch-backend": { type: "string" } });
+ const step = (cmd, a, opts = {}) => {
+ ctx.note(`$ ${cmd} ${a.join(" ")}`);
+ const r = spawnSync(cmd, a, { cwd: METRICS_DIR, stdio: "inherit", env: ctx.env, ...opts });
+ if (r.error) throw new Error(`${cmd} isn't installed: get uv from https://docs.astral.sh/uv/ (one command), then run pnpm eval:setup again`);
+ if (r.status !== 0) throw new Error(`${cmd} ${a[0]} failed (exit ${r.status})`);
+ };
+ const py = process.platform === "win32" ? ".venv/Scripts/python.exe" : ".venv/bin/python";
+ if (!fs.existsSync(path.join(METRICS_DIR, py))) step("uv", ["venv", ".venv", "--python", ">=3.11"]);
+ step("uv", ["pip", "install", "--python", py, "-r", "requirements.txt", "--torch-backend", v["torch-backend"] ?? "cpu"]);
+ if (v.identity) step("uv", ["pip", "install", "--python", py, "-r", "requirements-identity.txt"]);
+ if (v.download) step(py, ["-m", "fuobe_metrics.download", ...(v.identity ? ["--identity"] : [])]);
+ ctx.print(`Metrics ready in ${path.join(METRICS_DIR, ".venv")}${v.download ? "" : " (weights download on first use, or run pnpm eval:setup --download)"}.`);
+ return 0;
+}
+
+if (import.meta.url === `file://${process.argv[1]}`) {
+ process.exitCode = await main(process.argv.slice(2));
+}
diff --git a/scripts/eval/lib/compare.mjs b/scripts/eval/lib/compare.mjs
new file mode 100644
index 00000000..7de273f3
--- /dev/null
+++ b/scripts/eval/lib/compare.mjs
@@ -0,0 +1,234 @@
+// Comparing runs, and the promote rule.
+//
+// compare A B: the jobs both runs made (same case, prompt, seed and variant; or two variants named
+// with run:variant), per metric how often B is better, worse or the same as A, and the mean gain.
+// With --fail-on, it exits non-zero when a chosen metric's mean gets worse by more than --threshold
+// (an absolute amount in the metric's units, or a percentage of A's mean like 5%).
+//
+// promote: a recipe becomes a look's default only when it wins (see PROMOTE_RULE). The command
+// writes promote.json and says what to change; the catalog default stays a code change a person
+// reviews.
+import path from "node:path";
+import { fmt, gain, METRIC_INFO, METRIC_ORDER, verdict } from "./metric-info.mjs";
+import { jobScores, loadRun } from "./report.mjs";
+import { aggregateRatings } from "./review.mjs";
+import { writeJson } from "./store.mjs";
+
+const mean = (xs) => {
+ const v = xs.filter((x) => typeof x === "number" && !Number.isNaN(x));
+ return v.length ? v.reduce((a, b) => a + b, 0) / v.length : null;
+};
+
+/** {key → scores} of a run's succeeded jobs, optionally one variant's. */
+function scoreMap(loaded, variant) {
+ const m = new Map();
+ for (const r of loaded.rows) {
+ if (r.status !== "succeeded" || (variant && r.variant !== variant)) continue;
+ m.set(variant ? r.key : `${r.key}|${r.variant}`, { row: r, scores: jobScores(r, loaded.metrics) });
+ }
+ return m;
+}
+
+/**
+ * @param {{ dir: string, variant?: string | null }} a
+ * @param {{ dir: string, variant?: string | null }} b
+ * @param {{ failOn?: string[], threshold?: string | number, perCase?: boolean }} [opts]
+ */
+export function compareRuns(a, b, opts = {}) {
+ const A = loadRun(a.dir);
+ const B = loadRun(b.dir);
+ // Naming a variant on one side only compares it with the same variant on the other.
+ const va = a.variant ?? b.variant ?? null;
+ const vb = b.variant ?? a.variant ?? null;
+ const ma = scoreMap(A, va);
+ const mb = scoreMap(B, vb);
+ const keys = [...ma.keys()].filter((k) => mb.has(k));
+ const metrics = [...new Set(keys.flatMap((k) => [...Object.keys(ma.get(k).scores), ...Object.keys(mb.get(k).scores)]))].filter((k) => METRIC_INFO[k] && METRIC_INFO[k].better !== "none").sort((x, y) => METRIC_ORDER.indexOf(x) - METRIC_ORDER.indexOf(y));
+ const rows = metrics.map((metric) => {
+ const s = { metric, wins: 0, losses: 0, ties: 0, a: [], b: [], gains: [] };
+ for (const k of keys) {
+ const x = ma.get(k).scores[metric];
+ const y = mb.get(k).scores[metric];
+ const v = verdict(metric, x, y);
+ if (!v) continue;
+ s[v === "win" ? "wins" : v === "loss" ? "losses" : "ties"]++;
+ s.a.push(x);
+ s.b.push(y);
+ s.gains.push(gain(metric, x, y));
+ }
+ return { metric, label: METRIC_INFO[metric].label, better: METRIC_INFO[metric].better, n: s.gains.length, wins: s.wins, losses: s.losses, ties: s.ties, meanA: mean(s.a), meanB: mean(s.b), meanGain: mean(s.gains) };
+ });
+
+ // Per case, for --per-case and the worst losses.
+ const cases = new Map();
+ for (const k of keys) {
+ const caseId = ma.get(k).row.caseId;
+ for (const metric of metrics) {
+ const g = gain(metric, ma.get(k).scores[metric], mb.get(k).scores[metric]);
+ if (g == null) continue;
+ const c = cases.get(caseId) ?? {};
+ (c[metric] ??= []).push(g);
+ cases.set(caseId, c);
+ }
+ }
+ const perCase = [...cases.entries()].map(([caseId, byMetric]) => ({ caseId, gains: Object.fromEntries(Object.entries(byMetric).map(([m, g]) => [m, mean(g)])) }));
+
+ const regressions = [];
+ for (const metric of opts.failOn ?? []) {
+ const row = rows.find((r) => r.metric === metric);
+ if (!METRIC_INFO[metric]) throw new Error(`Unknown metric “${metric}” (have ${METRIC_ORDER.join(", ")})`);
+ if (!row || row.n === 0) {
+ regressions.push({ metric, reason: `no ${metric} scores in both runs`, missing: true });
+ continue;
+ }
+ const limit = thresholdFor(opts.threshold, row.meanA);
+ if (row.meanGain < -limit) regressions.push({ metric, reason: `mean ${fmt(metric, row.meanA)} → ${fmt(metric, row.meanB)} (${signed(metric, row.meanGain)}), worse than the ${fmt(metric, limit)} allowed` });
+ if (opts.perCase) {
+ for (const c of perCase) {
+ const g = c.gains[metric];
+ if (g != null && g < -limit) regressions.push({ metric, caseId: c.caseId, reason: `${c.caseId}: ${signed(metric, g)}, worse than the ${fmt(metric, limit)} allowed` });
+ }
+ }
+ }
+ return {
+ a: { runId: A.run.runId, suite: A.run.suite, engine: A.run.engine, variant: va },
+ b: { runId: B.run.runId, suite: B.run.suite, engine: B.run.engine, variant: vb },
+ matched: keys.length,
+ onlyA: ma.size - keys.length,
+ onlyB: mb.size - keys.length,
+ metrics: rows,
+ perCase,
+ regressions,
+ // A metric you asked to guard that has no scores fails too: the check can't pass by not running.
+ failed: regressions.length > 0,
+ };
+}
+
+/** --threshold: a number in the metric's units, "5%" of A's mean, or the metric's tie band when not given. */
+function thresholdFor(t, base) {
+ if (t == null || t === "") return 0;
+ const s = String(t).trim();
+ if (s.endsWith("%")) return (Math.abs(base ?? 0) * Number(s.slice(0, -1))) / 100;
+ const n = Number(s);
+ if (!Number.isFinite(n) || n < 0) throw new Error(`--threshold takes a number or a percentage, not “${t}”`);
+ return n;
+}
+
+const signed = (metric, g) => `${g >= 0 ? "+" : "−"}${fmt(metric, Math.abs(g))}`;
+
+/** The comparison as lines for a terminal. */
+export function compareText(c) {
+ const name = (x) => `${x.runId}${x.variant ? `:${x.variant}` : ""} (${x.suite} · ${x.engine})`;
+ const lines = [`A ${name(c.a)}`, `B ${name(c.b)}`, `${c.matched} jobs in both${c.onlyA || c.onlyB ? ` · ${c.onlyA} only in A · ${c.onlyB} only in B` : ""}`, ""];
+ if (!c.metrics.length) lines.push("No scores to compare (run pnpm eval:report on both runs first).");
+ const w = Math.max(10, ...c.metrics.map((r) => r.label.length));
+ if (c.metrics.length) lines.push(`${"metric".padEnd(w)} ${"A".padStart(9)} ${"B".padStart(9)} ${"B better".padStart(8)} ${"worse".padStart(5)} ${"same".padStart(4)} gain`);
+ for (const r of c.metrics) {
+ lines.push(`${r.label.padEnd(w)} ${fmt(r.metric, r.meanA).padStart(9)} ${fmt(r.metric, r.meanB).padStart(9)} ${String(r.wins).padStart(8)} ${String(r.losses).padStart(5)} ${String(r.ties).padStart(4)} ${r.meanGain == null ? "–" : signed(r.metric, r.meanGain)}`);
+ }
+ if (c.regressions.length) {
+ lines.push("", "Regressions:");
+ for (const r of c.regressions) lines.push(` ✗ ${METRIC_INFO[r.metric]?.label ?? r.metric}: ${r.reason}`);
+ } else if (c.metrics.length) lines.push("", "No regressions beyond the threshold.");
+ return lines.join("\n");
+}
+
+/**
+ * The promote rule. A recipe (the candidate variant) becomes a look's default only when, in one run
+ * with the same prompts and seeds:
+ * 1. its licence allows it: every LoRA it loaded is commercial, hostable when the run is on the
+ * cloud, and none of the recipe's LoRAs was left out on this engine;
+ * 2. it made at least `minJobs` results for the look;
+ * 3. against every alternative in the run (prompt only, half strength, the bare base, today's
+ * default…) it scores at least as well on the look's main metric (style when the look has
+ * references, else aesthetic), and it doesn't give up more than 1.0 CLIP or 0.15 aesthetic;
+ * 4. people prefer it in a blind review: at least `minRatings` ratings against the alternatives,
+ * and at least 55% of the non-tie ones for the candidate.
+ * Half strength beating the full recipe means the LoRAs over-cook: lower them (and run again).
+ * Passing the rule makes a recipe eligible; the catalog default is still changed by hand, in a
+ * reviewed commit, on both engines.
+ */
+export const PROMOTE_RULE = { minJobs: 3, clipGuard: 1.0, aestheticGuard: 0.15, minRatings: 6, minPreference: 0.55 };
+
+export function promote(dir, { candidate, alternatives, rule = PROMOTE_RULE } = {}) {
+ const L = loadRun(dir);
+ const variants = L.run.variants ?? [...new Set(L.rows.map((r) => r.variant))];
+ const cand = candidate ?? variants[0];
+ if (!variants.includes(cand)) throw new Error(`The run has no variant “${cand}” (it has ${variants.join(", ")})`);
+ const alts = (alternatives?.length ? alternatives : variants.filter((v) => v !== cand)).filter((v) => variants.includes(v));
+ const ratings = aggregateRatings(L);
+ const results = [];
+ for (const caseId of [...new Set(L.rows.map((r) => r.caseId))]) {
+ const rows = L.rows.filter((r) => r.caseId === caseId);
+ const mine = rows.filter((r) => r.variant === cand);
+ const ok = mine.filter((r) => r.status === "succeeded");
+ const scoresOf = (list) => list.map((r) => jobScores(r, L.metrics));
+ const m = (list, k) => mean(scoresOf(list).map((s) => s[k]));
+ const reasons = [];
+ const notes = [];
+ let verdictText;
+ const recipe = ok[0]?.recipe ?? mine[0]?.recipe;
+ // 1. licence and completeness
+ const applied = recipe?.applied ?? recipe?.sent?.loras ?? [];
+ const lib = new Map((recipe?.loras ?? []).map((l) => [l.file, l]));
+ const nonCommercial = applied.filter((l) => lib.get(l.file)?.commercial === false);
+ const notHostable = L.run.engine === "cloud" ? applied.filter((l) => lib.get(l.file)?.hostedOk === false) : [];
+ if (recipe?.commercialOk === false || nonCommercial.length) reasons.push(`non-commercial LoRA${nonCommercial.length > 1 ? "s" : ""}: ${nonCommercial.map((l) => l.file).join(", ") || "the recipe is flagged"}`);
+ if (notHostable.length) reasons.push(`not allowed on hosted services: ${notHostable.map((l) => l.file).join(", ")}`);
+ if (mine.some((r) => r.recipe?.complete === false || r.recipe?.sent?.complete === false)) reasons.push("some of the recipe's LoRAs were left out on this engine, so this isn't the recipe");
+ // 2. enough results
+ if (ok.length < rule.minJobs) reasons.push(`${ok.length} result${ok.length === 1 ? "" : "s"}, the rule wants ${rule.minJobs}`);
+ // 3. metrics against each alternative
+ const main = scoresOf(ok).some((s) => s.style != null) ? "style" : "aesthetic";
+ const against = [];
+ for (const alt of alts) {
+ const theirs = rows.filter((r) => r.variant === alt && r.status === "succeeded");
+ if (!theirs.length) continue;
+ const row = { variant: alt, [main]: { candidate: m(ok, main), alternative: m(theirs, main) }, clip: { candidate: m(ok, "clip"), alternative: m(theirs, "clip") }, aesthetic: { candidate: m(ok, "aesthetic"), alternative: m(theirs, "aesthetic") } };
+ against.push(row);
+ const mc = row[main];
+ if (mc.candidate == null || mc.alternative == null) reasons.push(`no ${main} scores against ${alt} (run pnpm eval:report)`);
+ else if (mc.candidate < mc.alternative) {
+ reasons.push(`${alt} scores higher on ${main} (${fmt(main, mc.alternative)} vs ${fmt(main, mc.candidate)})`);
+ if (/half/.test(alt)) notes.push("half strength wins: the LoRAs over-cook here — lower their strengths in the research JSON and run again");
+ }
+ if (row.clip.candidate != null && row.clip.alternative != null && row.clip.candidate < row.clip.alternative - rule.clipGuard) reasons.push(`it follows the prompt worse than ${alt} (CLIP ${fmt("clip", row.clip.candidate)} vs ${fmt("clip", row.clip.alternative)})`);
+ if (main !== "aesthetic" && row.aesthetic.candidate != null && row.aesthetic.alternative != null && row.aesthetic.candidate < row.aesthetic.alternative - rule.aestheticGuard) reasons.push(`it looks worse than ${alt} (aesthetic ${fmt("aesthetic", row.aesthetic.candidate)} vs ${fmt("aesthetic", row.aesthetic.alternative)})`);
+ }
+ if (!against.length) reasons.push("no alternative in this run to beat (run it with --variants recipe,prompt-only,half-strength,plain)");
+ // 4. blind review
+ const rated = ratings.pairs.filter((p) => (p.a === cand && alts.includes(p.b)) || (p.b === cand && alts.includes(p.a)));
+ const forCand = rated.reduce((n, p) => n + (p.a === cand ? p.aWins : p.bWins), 0);
+ const forAlt = rated.reduce((n, p) => n + (p.a === cand ? p.bWins : p.aWins), 0);
+ const ties = rated.reduce((n, p) => n + p.ties, 0);
+ if (forCand + forAlt + ties < rule.minRatings) reasons.push(`needs a blind review: ${forCand + forAlt + ties} rating${forCand + forAlt + ties === 1 ? "" : "s"} for the whole run, the rule wants ${rule.minRatings} (pnpm eval:review)`);
+ else if (forCand + forAlt && forCand / (forCand + forAlt) < rule.minPreference) reasons.push(`people preferred it ${Math.round((100 * forCand) / (forCand + forAlt))}% of the time, the rule wants ${Math.round(rule.minPreference * 100)}%`);
+ // Over-cooking is its own verdict: the fix is a lower strength, not another recipe.
+ verdictText = !reasons.length ? "promote" : notes.length ? "lower strengths" : "hold";
+ results.push({ caseId, title: mine[0]?.caseTitle ?? caseId, look: recipe?.look ?? null, candidate: cand, verdict: verdictText, reasons, notes, mainMetric: main, against, recipe: recipe ? { loras: applied.map((l) => ({ file: l.file, strength: l.strength ?? 1 })), source: recipe.source } : null });
+ }
+ const doc = {
+ runId: L.run.runId,
+ suite: L.run.suite,
+ engine: L.run.engine,
+ candidate: cand,
+ alternatives: alts,
+ rule,
+ note: "Eligible recipes still become defaults only by a code change a person reviews (the Original's catalog and the research JSON), checked on both engines.",
+ otherEngine: L.run.engine === "demo" ? "demo runs measure the harness, not models: nothing here can be promoted" : `this run is on the ${L.run.engine} engine only; check the ${L.run.engine === "open" ? "cloud" : "open"} engine before changing a default`,
+ results: L.run.engine === "demo" ? results.map((r) => ({ ...r, verdict: "hold", reasons: ["demo media, not model output", ...r.reasons] })) : results,
+ };
+ writeJson(path.join(dir, "promote.json"), doc);
+ return doc;
+}
+
+export function promoteText(doc) {
+ const count = (v) => doc.results.filter((r) => r.verdict === v).length;
+ const lines = [`${doc.suite} · ${doc.engine} · candidate “${doc.candidate}” against ${doc.alternatives.join(", ") || "nothing"}`, `${count("promote")} eligible · ${count("lower strengths")} to lower · ${count("hold")} on hold`, ""];
+ for (const r of doc.results) {
+ lines.push(`${r.verdict === "promote" ? "✓" : r.verdict === "lower strengths" ? "↓" : "·"} ${r.title}: ${r.verdict}`);
+ for (const why of [...r.reasons, ...r.notes]) lines.push(` ${why}`);
+ }
+ lines.push("", doc.otherEngine, doc.note);
+ return lines.join("\n");
+}
diff --git a/scripts/eval/lib/html.mjs b/scripts/eval/lib/html.mjs
new file mode 100644
index 00000000..be085641
--- /dev/null
+++ b/scripts/eval/lib/html.mjs
@@ -0,0 +1,86 @@
+// What the report and the review page share: escaping, and one small stylesheet with light and dark
+// tokens (Fuobe's neutral palette), sized so nothing scrolls sideways on a 390 px phone.
+
+export const esc = (s) =>
+ String(s ?? "")
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;")
+ .replaceAll('"', "&quot;");
+
+/** A relative URL for a path inside the run folder (each segment encoded). */
+export const href = (rel) => String(rel).split(/[\\/]/).map(encodeURIComponent).join("/");
+
+export const BASE_CSS = `
+:root {
+ --bg: #ffffff; --fg: #18181b; --muted: #71717a; --card: #fafafa; --border: #e4e4e7;
+ --accent: #4f46e5; --accent-fg: #ffffff; --good: #15803d; --bad: #b91c1c; --chip: #f4f4f5;
+ color-scheme: light;
+}
+@media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]) {
+ --bg: #09090b; --fg: #fafafa; --muted: #a1a1aa; --card: #18181b; --border: #27272a;
+ --accent: #818cf8; --accent-fg: #09090b; --good: #4ade80; --bad: #f87171; --chip: #27272a;
+ color-scheme: dark;
+ }
+}
+:root[data-theme="dark"] {
+ --bg: #09090b; --fg: #fafafa; --muted: #a1a1aa; --card: #18181b; --border: #27272a;
+ --accent: #818cf8; --accent-fg: #09090b; --good: #4ade80; --bad: #f87171; --chip: #27272a;
+ color-scheme: dark;
+}
+* { box-sizing: border-box; }
+html { -webkit-text-size-adjust: 100%; }
+body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; overflow-wrap: anywhere; }
+main { max-width: 1200px; margin: 0 auto; padding: 24px 16px 64px; }
+h1 { font-size: 22px; line-height: 1.25; margin: 0 0 4px; letter-spacing: -0.01em; }
+h2 { font-size: 16px; margin: 32px 0 12px; }
+h3 { font-size: 14px; margin: 0 0 8px; }
+p { margin: 0 0 8px; }
+a { color: var(--accent); }
+.muted { color: var(--muted); }
+.row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
+.chip { display: inline-flex; gap: 4px; align-items: center; padding: 2px 8px; border-radius: 999px; background: var(--chip); font-size: 12px; white-space: nowrap; }
+.chip.good { color: var(--good); } .chip.bad { color: var(--bad); }
+.card { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 12px; min-width: 0; }
+.grid { display: grid; gap: 12px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 220px), 1fr)); }
+.media { width: 100%; aspect-ratio: 1; object-fit: contain; background: var(--chip); border-radius: 8px; display: block; }
+.facts { display: grid; gap: 4px 16px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 200px), 1fr)); margin: 12px 0; }
+.facts div { min-width: 0; } .facts b { display: block; font-size: 12px; color: var(--muted); font-weight: 500; }
+.btn { appearance: none; border: 1px solid var(--border); background: var(--card); color: var(--fg); border-radius: 8px; padding: 8px 12px; font: inherit; cursor: pointer; }
+.btn.primary { background: var(--accent); color: var(--accent-fg); border-color: var(--accent); }
+.btn:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+kbd { font: 12px ui-monospace, monospace; border: 1px solid var(--border); border-bottom-width: 2px; border-radius: 4px; padding: 0 4px; background: var(--card); }
+.stats { display: grid; gap: 8px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr)); }
+.stat { display: flex; justify-content: space-between; gap: 8px; font-size: 13px; border-bottom: 1px solid var(--border); padding: 4px 0; }
+.stat span:last-child { font-variant-numeric: tabular-nums; text-align: right; }
+`;
+
+/** The theme switch: follows the system until you pick, remembered per browser. */
+export const THEME_SCRIPT = `
+(() => {
+ const root = document.documentElement;
+ try { const t = localStorage.getItem("fuobe-eval-theme"); if (t) root.dataset.theme = t; } catch {}
+ window.toggleTheme = () => {
+ const dark = root.dataset.theme ? root.dataset.theme === "dark" : matchMedia("(prefers-color-scheme: dark)").matches;
+ root.dataset.theme = dark ? "light" : "dark";
+ try { localStorage.setItem("fuobe-eval-theme", root.dataset.theme); } catch {}
+ };
+})();
+`;
+
+export const page = ({ title, body, head = "", script = "" }) => `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>${esc(title)}</title>
+<style>${BASE_CSS}${head}</style>
+<script>${THEME_SCRIPT}</script>
+</head>
+<body>
+${body}
+${script ? `<script>${script}</script>` : ""}
+</body>
+</html>
+`;
diff --git a/scripts/eval/lib/media.mjs b/scripts/eval/lib/media.mjs
index 3c4d7176..baf5e6b2 100644
--- a/scripts/eval/lib/media.mjs
+++ b/scripts/eval/lib/media.mjs
@@ -125,5 +125,8 @@ export function fillTemplate(value, vars) {
return value;
}
-/** A requestId for a studio route (8–64 characters): the same job id gets the same one, so a resumed run doesn't start a pipeline twice. */
-export const requestIdFor = (runId, jobId) => `eval-${crypto.createHash("sha256").update(`${runId}/${jobId}`).digest("hex").slice(0, 24)}`;
+/**
+ * A requestId for a studio route (8–64 characters). The same job and attempt get the same one, so a run
+ * interrupted mid-submit doesn't start a pipeline twice; a retry of a failed job is a new attempt.
+ */
+export const requestIdFor = (runId, jobId, attempt = 1) => `eval-${crypto.createHash("sha256").update(`${runId}/${jobId}/${attempt}`).digest("hex").slice(0, 24)}`;
diff --git a/scripts/eval/lib/report.mjs b/scripts/eval/lib/report.mjs
new file mode 100644
index 00000000..7cde28c3
--- /dev/null
+++ b/scripts/eval/lib/report.mjs
@@ -0,0 +1,273 @@
+// A run's report: summary.json (what ran, means per variant, how variants of the same case compare,
+// blind ratings, failures), report.html (a contact sheet: every case × variant with its scores), and
+// the run's lines in results/history.jsonl (one per case and variant).
+import fs from "node:fs";
+import path from "node:path";
+import { esc, href, page } from "./html.mjs";
+import { fmt, gain, METRIC_INFO, METRIC_ORDER, verdict } from "./metric-info.mjs";
+import { aggregateRatings } from "./review.mjs";
+import { money } from "./run.mjs";
+import { latestJobs, readJson, writeHistory, writeJson } from "./store.mjs";
+
+const mean = (xs) => {
+ const v = xs.filter((x) => typeof x === "number" && !Number.isNaN(x));
+ return v.length ? v.reduce((a, b) => a + b, 0) / v.length : null;
+};
+
+/** A run folder's files: run.json, the latest row per job, metrics.json, the review's ratings and key. */
+export function loadRun(dir) {
+ const run = readJson(path.join(dir, "run.json"));
+ if (!run) throw new Error(`${dir} isn't a run folder (no run.json)`);
+ return {
+ dir,
+ run,
+ rows: latestJobs(dir),
+ metrics: readJson(path.join(dir, "metrics.json"), null),
+ ratings: readJson(path.join(dir, "review", "ratings.json"), null),
+ key: readJson(path.join(dir, "review", "key.json"), null),
+ };
+}
+
+/** One job's numbers: the Python metrics plus time, cost and memory from the runner. */
+export function jobScores(row, metricsDoc) {
+ const m = metricsDoc?.jobs?.[row.id] ?? {};
+ const out = {};
+ for (const [k, v] of Object.entries(m)) if (!k.startsWith("_") && typeof v === "number") out[k] = v;
+ const ms = row.comfy?.execMs ?? row.timing?.serverMs ?? row.timing?.wallMs;
+ if (row.status === "succeeded" && ms != null) out.seconds = Math.round(ms / 100) / 10;
+ const cost = row.costUsd?.actual ?? row.costUsd?.estimate;
+ if (row.status === "succeeded" && cost != null) out.costUsd = cost;
+ const vram = row.vram?.torchPeakGb ?? row.vram?.peakUsedGb;
+ if (vram != null) out.vramGb = vram;
+ return out;
+}
+
+/** Continuity and other group scores land on every job of the group. */
+function groupScores(metricsDoc) {
+ const byJob = new Map();
+ for (const g of Object.values(metricsDoc?.groups ?? {})) for (const id of g.jobs ?? []) byJob.set(id, { continuity: g.continuity });
+ return byJob;
+}
+
+const recipeLine = (r) => {
+ if (!r) return null;
+ const loras = (r.applied ?? r.sent?.loras ?? []).map((l) => `${l.file.replace(/\.safetensors$/, "")}@${l.strength ?? 1}`);
+ return [r.look?.name ?? (r.presets ?? []).join(" / "), loras.length ? loras.join(" + ") : "no LoRAs", r.complete === false || r.sent?.complete === false ? "incomplete" : null].filter(Boolean).join(" · ");
+};
+
+/** Everything the report says, as data. */
+export function summarize(loaded) {
+ const { run, rows, metrics } = loaded;
+ const groups = groupScores(metrics);
+ const scored = rows.map((r) => ({ row: r, scores: { ...jobScores(r, metrics), ...(groups.get(r.id) ?? {}) } }));
+ const variants = run.variants?.length ? run.variants : [...new Set(rows.map((r) => r.variant))];
+ const keysOf = (list) => [...new Set(list.flatMap((x) => Object.keys(x.scores)))].filter((k) => METRIC_INFO[k]).sort((a, b) => METRIC_ORDER.indexOf(a) - METRIC_ORDER.indexOf(b));
+ const metricKeys = keysOf(scored);
+
+ const perVariant = {};
+ for (const v of variants) {
+ const mine = scored.filter((x) => x.row.variant === v);
+ const ok = mine.filter((x) => x.row.status === "succeeded");
+ perVariant[v] = {
+ description: run.variantInfo?.[v] ?? "",
+ jobs: mine.length,
+ succeeded: ok.length,
+ failed: mine.filter((x) => ["failed", "timeout", "canceled", "interrupted"].includes(x.row.status)).length,
+ skipped: mine.filter((x) => x.row.status === "skipped").length,
+ mean: Object.fromEntries(metricKeys.map((k) => [k, mean(ok.map((x) => x.scores[k]))]).filter(([, v2]) => v2 != null)),
+ n: Object.fromEntries(metricKeys.map((k) => [k, ok.filter((x) => typeof x.scores[k] === "number").length])),
+ costUsd: ok.reduce((a, x) => a + (x.scores.costUsd ?? 0), 0),
+ models: [...new Set(ok.map((x) => x.row.model?.id).filter(Boolean))],
+ };
+ }
+
+ // Variants of the same job key (case/prompt/seed), each against the first variant of the run.
+ const base = variants[0];
+ const byKey = new Map();
+ for (const x of scored) if (x.row.status === "succeeded") byKey.set(`${x.row.key}|${x.row.variant}`, x);
+ const pairs = variants.slice(1).map((other) => {
+ const res = {};
+ for (const k of metricKeys) {
+ const s = { wins: 0, losses: 0, ties: 0, gains: [] };
+ for (const x of scored.filter((y) => y.row.variant === base && y.row.status === "succeeded")) {
+ const y = byKey.get(`${x.row.key}|${other}`);
+ if (!y) continue;
+ const v = verdict(k, y.scores[k], x.scores[k]);
+ if (!v) continue;
+ s[v === "win" ? "wins" : v === "loss" ? "losses" : "ties"]++;
+ s.gains.push(gain(k, y.scores[k], x.scores[k]));
+ }
+ if (s.wins + s.losses + s.ties) res[k] = { wins: s.wins, losses: s.losses, ties: s.ties, meanGain: mean(s.gains) };
+ }
+ return { base, other, metrics: res };
+ });
+
+ // Cases with each variant's jobs, for the contact sheet and history.
+ const cases = [];
+ for (const caseId of [...new Set(rows.map((r) => r.caseId))]) {
+ const mine = scored.filter((x) => x.row.caseId === caseId);
+ const entry = { caseId, title: mine[0].row.caseTitle, variants: {} };
+ for (const v of variants) {
+ const jobs = mine.filter((x) => x.row.variant === v);
+ if (!jobs.length) continue;
+ const ok = jobs.filter((x) => x.row.status === "succeeded");
+ entry.variants[v] = {
+ mean: Object.fromEntries(metricKeys.map((k) => [k, mean(ok.map((x) => x.scores[k]))]).filter(([, val]) => val != null)),
+ succeeded: ok.length,
+ jobs: jobs.length,
+ model: ok[0]?.row.model?.id ?? jobs[0].row.model?.id,
+ recipe: recipeLine(ok[0]?.row.recipe ?? jobs[0].row.recipe),
+ recipeComplete: jobs.every((x) => x.row.recipe?.complete !== false && x.row.recipe?.sent?.complete !== false),
+ items: jobs.map((x) => ({
+ id: x.row.id,
+ promptId: x.row.promptId,
+ seed: x.row.seed,
+ status: x.row.status,
+ error: x.row.error ?? x.row.skip ?? null,
+ outputs: (x.row.outputs ?? []).filter((o) => o.kind === "image" || o.kind === "video").map((o) => ({ file: o.file, kind: o.kind })),
+ scores: x.scores,
+ notes: [...(x.row.notes ?? []), ...(metrics?.jobs?.[x.row.id]?._notes ?? [])],
+ })),
+ };
+ }
+ cases.push(entry);
+ }
+
+ const ok = rows.filter((r) => r.status === "succeeded");
+ return {
+ runId: run.runId,
+ suite: run.suite,
+ title: run.title,
+ original: run.original,
+ engine: run.engine,
+ label: run.label,
+ server: run.server,
+ comfy: run.comfy,
+ harness: run.harness,
+ startedAt: run.startedAt,
+ finishedAt: run.finishedAt,
+ counts: {
+ jobs: rows.length,
+ succeeded: ok.length,
+ failed: rows.filter((r) => ["failed", "timeout", "canceled", "interrupted"].includes(r.status)).length,
+ skipped: rows.filter((r) => r.status === "skipped").length,
+ },
+ costUsd: { estimate: run.estimateUsd ?? null, spent: ok.reduce((a, r) => a + (r.costUsd?.actual ?? r.costUsd?.estimate ?? 0), 0) },
+ metrics: { keys: metricKeys, models: metrics?.models ?? {}, skipped: metrics?.skipped ?? (metrics ? {} : { all: "not scored yet: pnpm eval:report runs the metrics" }), device: metrics?.device ?? null },
+ variants: perVariant,
+ pairs,
+ ratings: aggregateRatings(loaded),
+ cases,
+ failures: rows.filter((r) => r.status !== "succeeded" && r.status !== "skipped").map((r) => ({ id: r.id, status: r.status, error: r.error })),
+ skips: Object.entries(rows.filter((r) => r.status === "skipped").reduce((acc, r) => ({ ...acc, [r.skip]: (acc[r.skip] ?? 0) + 1 }), {})).map(([reason, count]) => ({ reason, count })),
+ };
+}
+
+/** One history line per case and variant (means over its prompts and seeds). */
+export function historyRows(summary) {
+ return summary.cases.flatMap((c) =>
+ Object.entries(c.variants).map(([variant, v]) => ({
+ runId: summary.runId,
+ at: summary.startedAt,
+ suite: summary.suite,
+ engine: summary.engine,
+ caseId: c.caseId,
+ variant,
+ model: v.model,
+ recipe: v.recipe,
+ recipeComplete: v.recipeComplete,
+ succeeded: v.succeeded,
+ jobs: v.jobs,
+ scores: v.mean,
+ })),
+ );
+}
+
+const when = (t) => (t ? new Date(t).toISOString().replace("T", " ").slice(0, 16) + " UTC" : "–");
+
+function chips(scores, keys) {
+ return keys
+ .filter((k) => scores[k] != null)
+ .map((k) => `<span class="chip" title="${esc(METRIC_INFO[k].label)} (${esc(METRIC_INFO[k].unit)}${METRIC_INFO[k].better === "none" ? "" : `, ${METRIC_INFO[k].better} is better`})">${esc(k)} ${k === "costUsd" ? esc(money(scores[k])) : esc(fmt(k, scores[k]))}</span>`)
+ .join(" ");
+}
+
+/** The contact sheet. */
+export function reportHtml(summary) {
+ const keys = summary.metrics.keys;
+ const free = summary.engine !== "cloud";
+ const variantCards = Object.entries(summary.variants)
+ .map(([v, s]) => {
+ const lines = keys.filter((k) => s.mean[k] != null).map((k) => `<div class="stat"><span>${esc(METRIC_INFO[k].label)}</span><span>${k === "costUsd" ? esc(money(s.mean[k])) : esc(fmt(k, s.mean[k]))} <span class="muted">n=${s.n[k]}</span></span></div>`);
+ return `<div class="card"><h3>${esc(v)}</h3><p class="muted">${esc(s.description)}</p><p>${s.succeeded}/${s.jobs} done${s.failed ? ` · <span class="chip bad">${s.failed} failed</span>` : ""}${s.skipped ? ` · ${s.skipped} skipped` : ""} · ${free ? "Free" : esc(money(s.costUsd))}</p>${s.models.length ? `<p class="muted">${esc(s.models.join(", "))}</p>` : ""}${lines.join("")}</div>`;
+ })
+ .join("");
+ const pairCards = summary.pairs
+ .filter((p) => Object.keys(p.metrics).length)
+ .map(
+ (p) =>
+ `<div class="card"><h3>${esc(p.base)} vs ${esc(p.other)}</h3>${Object.entries(p.metrics)
+ .map(([k, s]) => `<div class="stat"><span>${esc(METRIC_INFO[k].label)}</span><span><span class="chip good">${s.wins} better</span> <span class="chip bad">${s.losses} worse</span> <span class="chip">${s.ties} same</span></span></div>`)
+ .join("")}</div>`,
+ )
+ .join("");
+ const ratings = summary.ratings?.pairs?.length
+ ? `<h2>Blind review</h2><div class="stats">${summary.ratings.pairs
+ .map((r) => `<div class="card"><h3>${esc(r.a)} vs ${esc(r.b)}</h3><p>${esc(r.a)} preferred ${r.aWins}, ${esc(r.b)} ${r.bWins}, same ${r.ties} · ${r.preferA == null ? "–" : `${Math.round(r.preferA * 100)}% for ${esc(r.a)}`}</p></div>`)
+ .join("")}</div>`
+ : "";
+ const caseBlocks = summary.cases
+ .map((c) => {
+ const cols = Object.entries(c.variants)
+ .map(([v, s]) => {
+ const tiles = s.items
+ .map((it) => {
+ const media = it.outputs[0]
+ ? it.outputs[0].kind === "video"
+ ? `<video class="media" src="${href(it.outputs[0].file)}" muted loop playsinline preload="metadata" controls></video>`
+ : `<img class="media" src="${href(it.outputs[0].file)}" alt="${esc(`${c.title}, ${v}, ${it.promptId}`)}" loading="lazy">`
+ : `<div class="media row" style="justify-content:center"><span class="chip ${it.status === "skipped" ? "" : "bad"}">${esc(it.status)}</span></div>`;
+ return `<figure style="margin:0">${media}<figcaption class="muted" style="font-size:12px;margin-top:4px">${esc(it.promptId)} · seed ${esc(it.seed)}${it.error ? ` · ${esc(it.error)}` : ""}</figcaption><div class="row" style="margin-top:4px">${chips(it.scores, keys)}</div></figure>`;
+ })
+ .join("");
+ return `<div class="card"><h3>${esc(v)}${s.recipeComplete ? "" : ' <span class="chip bad" title="Some of the recipe\'s LoRAs were left out on this engine">recipe incomplete</span>'}</h3>${s.recipe ? `<p class="muted" style="font-size:12px">${esc(s.recipe)}</p>` : ""}<div class="grid" style="grid-template-columns:repeat(auto-fill,minmax(min(100%,140px),1fr))">${tiles}</div></div>`;
+ })
+ .join("");
+ return `<section><h2 id="${esc(c.caseId)}">${esc(c.title)} <span class="muted" style="font-weight:400">${esc(c.caseId)}</span></h2><div class="grid">${cols}</div></section>`;
+ })
+ .join("");
+ const skipped = Object.entries(summary.metrics.skipped ?? {});
+ const models = Object.entries(summary.metrics.models ?? {});
+ const body = `<main>
+<div class="row" style="justify-content:space-between"><h1>${esc(summary.title)}</h1><button class="btn" type="button" onclick="toggleTheme()">Light / dark</button></div>
+<p class="muted">${esc(summary.runId)}${summary.label ? ` · ${esc(summary.label)}` : ""}</p>
+<div class="facts">
+<div><b>Engine</b>${esc(summary.engine)}${summary.engine === "demo" ? " (demo media, not model output)" : ""}</div>
+<div><b>Server</b>${esc(summary.server?.url)}</div>
+<div><b>Jobs</b>${summary.counts.succeeded} done · ${summary.counts.failed} failed · ${summary.counts.skipped} skipped</div>
+<div><b>Cost</b>${free ? "Free" : `${esc(money(summary.costUsd.spent))} (estimated ${esc(money(summary.costUsd.estimate))})`}</div>
+<div><b>Started</b>${esc(when(summary.startedAt))}</div>
+<div><b>Harness</b>${esc(summary.harness?.commit ?? "–")} · recipes ${esc(summary.harness?.recipes?.sha ?? "–")}</div>
+${summary.comfy ? `<div><b>ComfyUI</b>${esc(summary.comfy.version ?? (summary.comfy.unreachable ? "not reachable" : "–"))} ${esc((summary.comfy.devices ?? []).map((d) => `${d.name} ${d.vramTotalGb} GB`).join(", "))}</div>` : ""}
+</div>
+${skipped.length ? `<p class="muted">Not scored: ${skipped.map(([k, v]) => `${esc(k)} (${esc(v)})`).join("; ")}</p>` : ""}
+${summary.skips.length ? `<p class="muted">Skipped jobs: ${summary.skips.map((s) => `${s.count} × ${esc(s.reason)}`).join("; ")}</p>` : ""}
+<h2>Variants</h2><div class="stats">${variantCards}</div>
+${pairCards ? `<h2>Same case, same seed</h2><div class="stats">${pairCards}</div>` : ""}
+${ratings}
+<h2>Cases</h2>
+${caseBlocks}
+${models.length ? `<h2>Metric models</h2><div class="stats">${models.map(([k, m]) => `<div class="card"><h3>${esc(k)}</h3><p class="muted">${esc(JSON.stringify(m))}</p></div>`).join("")}</div>` : ""}
+</main>`;
+ return page({ title: `${summary.title} · ${summary.runId}`, body });
+}
+
+/** Write summary.json, report.html and the run's history lines; returns the summary. */
+export function writeReport(dir, root) {
+ const loaded = loadRun(dir);
+ const summary = summarize(loaded);
+ writeJson(path.join(dir, "summary.json"), summary);
+ fs.writeFileSync(path.join(dir, "report.html"), reportHtml(summary));
+ writeHistory(root, summary.runId, historyRows(summary));
+ return summary;
+}
diff --git a/scripts/eval/lib/review.mjs b/scripts/eval/lib/review.mjs
new file mode 100644
index 00000000..77ab8c93
--- /dev/null
+++ b/scripts/eval/lib/review.mjs
@@ -0,0 +1,264 @@
+// Blind A/B review: a static page per run (review/index.html) shows two results side by side in an
+// order the page can't reveal — a Fuobe output against your own reference (local/references/…),
+// another variant of the same case and seed, or the same job in another run. You rate with the
+// keyboard; ratings land in review/ratings.json (pnpm eval:review serves the page and saves them;
+// opened as a file it keeps them in the browser and offers a download). review/key.json, which the
+// page never loads, says which side was which; the summary unblinds the ratings with it.
+import crypto from "node:crypto";
+import fs from "node:fs";
+import http from "node:http";
+import path from "node:path";
+import { esc, page } from "./html.mjs";
+import { latestJobs, readJson, writeJson } from "./store.mjs";
+
+const IMAGE = /\.(png|jpe?g|webp|gif|svg)$/i;
+const VIDEO = /\.(mp4|mov|m4v|webm)$/i;
+const hash = (s) => crypto.createHash("sha256").update(s).digest("hex");
+
+/** The first picture or clip of a succeeded row (helpers like masks left out). */
+const mainOutput = (row) => (row.outputs ?? []).find((o) => (o.kind === "image" || o.kind === "video") && !["mask", "first-frame", "depth"].includes(o.role));
+
+/**
+ * The pairs to rate.
+ * @param {{ dir: string, rows: object[] }} run
+ * @param {{ against?: "variants" | "references" | { dir: string, runId: string, rows: object[] }, limit?: number }} [opts]
+ */
+export function buildPairs(run, opts = {}) {
+ const ok = run.rows.filter((r) => r.status === "succeeded" && mainOutput(r));
+ const variants = [...new Set(ok.map((r) => r.variant))];
+ const against = opts.against ?? (variants.length > 1 ? "variants" : "references");
+ const side = (label, file, extra = {}) => ({ label, file, ...extra });
+ const pairs = [];
+ if (against === "variants") {
+ const base = variants[0];
+ const byKey = new Map(ok.map((r) => [`${r.key}|${r.variant}`, r]));
+ for (const r of ok.filter((x) => x.variant === base)) {
+ for (const v of variants.slice(1)) {
+ const o = byKey.get(`${r.key}|${v}`);
+ if (o) pairs.push({ a: side(base, path.join(run.dir, mainOutput(r).file), { job: r.id }), b: side(v, path.join(run.dir, mainOutput(o).file), { job: o.id }), prompt: r.prompt, caseTitle: r.caseTitle });
+ }
+ }
+ } else if (against === "references") {
+ for (const r of ok) {
+ const out = mainOutput(r);
+ const refs = (r.references ?? []).filter((f) => (out.kind === "video" ? VIDEO.test(f) || IMAGE.test(f) : IMAGE.test(f)) && fs.existsSync(f));
+ if (!refs.length) continue;
+ // Spread the references over the case's jobs, so one image isn't the yardstick for all of them.
+ const ref = refs[parseInt(hash(r.id).slice(0, 8), 16) % refs.length];
+ pairs.push({ a: side(r.variant, path.join(run.dir, out.file), { job: r.id }), b: side("reference", ref, { reference: ref }), prompt: r.prompt, caseTitle: r.caseTitle });
+ }
+ } else {
+ const other = new Map(against.rows.filter((r) => r.status === "succeeded" && mainOutput(r)).map((r) => [`${r.key}|${r.variant}`, r]));
+ for (const r of ok) {
+ const o = other.get(`${r.key}|${r.variant}`);
+ if (o) pairs.push({ a: side(`${r.variant} (this run)`, path.join(run.dir, mainOutput(r).file), { job: r.id }), b: side(`${o.variant} (${against.runId})`, path.join(against.dir, mainOutput(o).file), { job: o.id, run: against.runId }), prompt: r.prompt, caseTitle: r.caseTitle });
+ }
+ }
+ return pairs.slice(0, opts.limit ?? Infinity).map((p) => {
+ const id = hash(`${p.a.file}|${p.b.file}`).slice(0, 12);
+ // Which side shows on the left comes from the pair's id, so rebuilding the page keeps it.
+ const aLeft = parseInt(id.slice(-1), 16) % 2 === 0;
+ return { id, ...p, aLeft, order: hash(`order|${id}`) };
+ });
+}
+
+/** Write review/index.html, the media under neutral names, and review/key.json; returns the pair count. */
+export function writeReview(run, opts = {}) {
+ const pairs = buildPairs(run, opts).sort((x, y) => x.order.localeCompare(y.order));
+ const out = path.join(run.dir, "review");
+ const mediaDir = path.join(out, "media");
+ fs.rmSync(mediaDir, { recursive: true, force: true });
+ fs.mkdirSync(mediaDir, { recursive: true });
+ const placed = new Map();
+ const place = (file) => {
+ if (placed.has(file)) return placed.get(file);
+ const name = `${hash(`media|${file}`).slice(0, 10)}${path.extname(file).toLowerCase()}`;
+ const dest = path.join(mediaDir, name);
+ try {
+ fs.linkSync(file, dest);
+ } catch {
+ fs.copyFileSync(file, dest);
+ }
+ placed.set(file, `media/${name}`);
+ return `media/${name}`;
+ };
+ const items = pairs.map((p) => {
+ const [left, right] = p.aLeft ? [p.a, p.b] : [p.b, p.a];
+ return { id: p.id, prompt: p.prompt ?? "", title: p.caseTitle ?? "", left: place(left.file), right: place(right.file), video: [left.file, right.file].some((f) => VIDEO.test(f)) };
+ });
+ writeJson(path.join(out, "key.json"), {
+ runId: run.runId,
+ against: opts.against?.runId ?? opts.against ?? null,
+ pairs: pairs.map((p) => ({ id: p.id, a: p.a, b: p.b, left: p.aLeft ? "a" : "b" })),
+ });
+ fs.writeFileSync(path.join(out, "index.html"), reviewHtml(run.runId, items));
+ return { pairs: items.length, file: path.join(out, "index.html") };
+}
+
+/** The review page: one pair at a time, keyboard first, works on a phone. */
+export function reviewHtml(runId, items) {
+ const css = `
+.pair { display: grid; gap: 12px; grid-template-columns: 1fr 1fr; }
+@media (max-width: 640px) { .pair { grid-template-columns: 1fr; } }
+.side { position: relative; border: 2px solid var(--border); border-radius: 12px; padding: 8px; background: var(--card); min-width: 0; }
+.side.picked { border-color: var(--accent); }
+.side .tag { position: absolute; top: 12px; left: 12px; background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 0 6px; font-weight: 600; }
+.side img, .side video { width: 100%; max-height: 62vh; object-fit: contain; display: block; border-radius: 8px; background: var(--chip); }
+.bar { position: sticky; bottom: 0; background: var(--bg); border-top: 1px solid var(--border); padding: 12px 0; margin-top: 16px; }
+.bar .row { justify-content: center; }
+progress { width: 100%; height: 6px; accent-color: var(--accent); }
+`;
+ const body = `<main>
+<div class="row" style="justify-content:space-between"><h1>Blind review</h1><div class="row"><button class="btn" type="button" id="download">Download ratings</button><button class="btn" type="button" onclick="toggleTheme()">Light / dark</button></div></div>
+<p class="muted">${esc(runId)} · Which result is better for the words below? The sides are shuffled; nothing on the page says which is which.</p>
+<p class="muted" id="saved" role="status" aria-live="polite"></p>
+<progress id="progress" max="${items.length}" value="0" aria-label="Pairs rated"></progress>
+<p id="count" class="muted"></p>
+<section id="stage" aria-live="polite"></section>
+<div class="bar"><div class="row">
+<button class="btn" type="button" data-choice="left"><kbd>←</kbd> Left is better</button>
+<button class="btn" type="button" data-choice="same"><kbd>↓</kbd> About the same</button>
+<button class="btn" type="button" data-choice="right">Right is better <kbd>→</kbd></button>
+<button class="btn" type="button" data-choice="skip"><kbd>S</kbd> Skip</button>
+<button class="btn" type="button" id="undo"><kbd>U</kbd> Undo</button>
+</div><p class="muted" style="text-align:center;margin-top:8px;font-size:12px">Keys: <kbd>←</kbd>/<kbd>1</kbd> left · <kbd>→</kbd>/<kbd>2</kbd> right · <kbd>↓</kbd>/<kbd>0</kbd>/<kbd>Space</kbd> same · <kbd>S</kbd> skip · <kbd>U</kbd> undo</p></div>
+</main>`;
+ const script = `
+const RUN = ${JSON.stringify(runId)};
+const PAIRS = ${JSON.stringify(items).replaceAll("<", "\\u003c")};
+const STORE = "fuobe-eval-ratings:" + RUN;
+const served = location.protocol.startsWith("http");
+let ratings = [];
+try { ratings = JSON.parse(localStorage.getItem(STORE) || "[]"); } catch {}
+let shownAt = performance.now();
+const $ = (id) => document.getElementById(id);
+const doneIds = () => new Set(ratings.map((r) => r.pair));
+const next = () => PAIRS.find((p) => !doneIds().has(p.id));
+function media(src, video, label) {
+ return video ? '<video src="' + src + '" muted loop playsinline autoplay controls aria-label="' + label + '"></video>' : '<img src="' + src + '" alt="' + label + '">';
+}
+function render() {
+ const p = next();
+ const rated = ratings.filter((r) => r.choice !== "skip").length;
+ $("progress").value = doneIds().size;
+ $("count").textContent = doneIds().size + " of " + PAIRS.length + " pairs · " + rated + " rated";
+ if (!PAIRS.length) { $("stage").innerHTML = "<p>There is nothing to compare in this run yet: it needs two variants of the same case, or your own references in scripts/eval/local/references/.</p>"; return; }
+ if (!p) { $("stage").innerHTML = "<h2>All done</h2><p>Thanks — " + rated + " ratings. " + (served ? "They are saved in the run folder." : "Download them and put ratings.json in the run's review folder.") + "</p>"; return; }
+ const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
+ $("stage").innerHTML = '<p><b>' + esc(p.title) + '</b></p><p class="muted">' + esc(p.prompt) + '</p><div class="pair">' +
+ '<div class="side" id="L"><span class="tag">Left</span>' + media(p.left, p.video, "Left result") + '</div>' +
+ '<div class="side" id="R"><span class="tag">Right</span>' + media(p.right, p.video, "Right result") + '</div></div>';
+ shownAt = performance.now();
+}
+async function persist() {
+ try { localStorage.setItem(STORE, JSON.stringify(ratings)); } catch {}
+ if (!served) { $("saved").textContent = "Saved in this browser. Download the ratings when you're done."; return; }
+ try {
+ const res = await fetch("ratings", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ runId: RUN, ratings }) });
+ $("saved").textContent = res.ok ? "Saved to the run folder." : "Couldn't save to the run folder (" + res.status + "): they are kept in this browser.";
+ } catch { $("saved").textContent = "The review server isn't answering: ratings are kept in this browser."; }
+}
+function rate(choice) {
+ const p = next();
+ if (!p) return;
+ const el = choice === "left" ? $("L") : choice === "right" ? $("R") : null;
+ if (el) el.classList.add("picked");
+ ratings.push({ pair: p.id, choice, at: new Date().toISOString(), ms: Math.round(performance.now() - shownAt) });
+ persist();
+ setTimeout(render, el ? 120 : 0);
+}
+function undo() { ratings.pop(); persist(); render(); }
+document.querySelectorAll("[data-choice]").forEach((b) => b.addEventListener("click", () => rate(b.dataset.choice)));
+$("undo").addEventListener("click", undo);
+$("download").addEventListener("click", () => {
+ const blob = new Blob([JSON.stringify({ runId: RUN, ratings }, null, 2)], { type: "application/json" });
+ const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "ratings.json"; a.click(); URL.revokeObjectURL(a.href);
+});
+document.addEventListener("keydown", (e) => {
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ const k = e.key;
+ const choice = k === "ArrowLeft" || k === "1" ? "left" : k === "ArrowRight" || k === "2" ? "right" : k === "ArrowDown" || k === "0" || k === " " ? "same" : k === "s" || k === "S" ? "skip" : null;
+ if (choice) { e.preventDefault(); rate(choice); }
+ else if (k === "u" || k === "U" || k === "Backspace") { e.preventDefault(); undo(); }
+});
+(async () => {
+ if (served) {
+ try { const r = await fetch("ratings.json", { cache: "no-store" }); if (r.ok) { const d = await r.json(); if (Array.isArray(d.ratings) && d.ratings.length >= ratings.length) ratings = d.ratings; } } catch {}
+ }
+ render();
+})();
+`;
+ return page({ title: `Blind review · ${runId}`, body, head: css, script });
+}
+
+/** Ratings unblinded with the key: per pair of labels, how often each side won. */
+export function aggregateRatings(loaded) {
+ const key = loaded.key ?? readJson(path.join(loaded.dir, "review", "key.json"), null);
+ const ratings = loaded.ratings ?? readJson(path.join(loaded.dir, "review", "ratings.json"), null);
+ if (!key || !ratings?.ratings?.length) return { total: 0, pairs: [] };
+ const byId = new Map(key.pairs.map((p) => [p.id, p]));
+ const last = new Map();
+ for (const r of ratings.ratings) last.set(r.pair, r);
+ const groups = new Map();
+ let total = 0;
+ for (const r of last.values()) {
+ const p = byId.get(r.pair);
+ if (!p || r.choice === "skip") continue;
+ total++;
+ const g = groups.get(`${p.a.label}|${p.b.label}`) ?? { a: p.a.label, b: p.b.label, aWins: 0, bWins: 0, ties: 0 };
+ const picked = r.choice === "same" ? null : r.choice === "left" ? p.left : p.left === "a" ? "b" : "a";
+ if (picked === "a") g.aWins++;
+ else if (picked === "b") g.bWins++;
+ else g.ties++;
+ groups.set(`${p.a.label}|${p.b.label}`, g);
+ }
+ return { total, pairs: [...groups.values()].map((g) => ({ ...g, preferA: g.aWins + g.bWins ? g.aWins / (g.aWins + g.bWins) : null })) };
+}
+
+const TYPES = { ".html": "text/html; charset=utf-8", ".json": "application/json", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif", ".svg": "image/svg+xml", ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".m4v": "video/mp4" };
+
+/**
+ * Serve a run's review folder on 127.0.0.1 and save ratings it POSTs. Only files inside review/
+ * are served; the key stays private.
+ */
+export function serveReview(dir, { port = 0, host = "127.0.0.1" } = {}) {
+ const root = path.join(dir, "review");
+ const server = http.createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://local");
+ const send = (status, body, type = "text/plain; charset=utf-8") => {
+ res.writeHead(status, { "content-type": type, "cache-control": "no-store" });
+ res.end(body);
+ };
+ if (req.method === "POST" && url.pathname === "/ratings") {
+ let raw = "";
+ for await (const c of req) {
+ raw += c;
+ if (raw.length > 5_000_000) return send(413, "too large");
+ }
+ let doc;
+ try {
+ doc = JSON.parse(raw);
+ } catch {
+ return send(400, "not JSON");
+ }
+ const valid = Array.isArray(doc?.ratings) && doc.ratings.every((r) => typeof r?.pair === "string" && ["left", "right", "same", "skip"].includes(r.choice));
+ if (!valid) return send(400, "ratings must be [{pair, choice: left|right|same|skip}]");
+ writeJson(path.join(root, "ratings.json"), { runId: path.basename(dir), savedAt: new Date().toISOString(), ratings: doc.ratings.map(({ pair, choice, at, ms }) => ({ pair, choice, at, ms })) });
+ return send(204, "");
+ }
+ if (req.method !== "GET" && req.method !== "HEAD") return send(405, "GET or POST /ratings");
+ const rel = decodeURIComponent(url.pathname === "/" ? "index.html" : url.pathname.slice(1));
+ const abs = path.resolve(root, rel);
+ if (!abs.startsWith(root + path.sep) || path.basename(abs) === "key.json") return send(404, "not found");
+ fs.stat(abs, (err, st) => {
+ if (err || !st.isFile()) return send(404, "not found");
+ res.writeHead(200, { "content-type": TYPES[path.extname(abs).toLowerCase()] ?? "application/octet-stream", "content-length": st.size, "cache-control": "no-store" });
+ if (req.method === "HEAD") return res.end();
+ fs.createReadStream(abs).pipe(res);
+ });
+ });
+ return new Promise((resolve) => server.listen(port, host, () => resolve({ server, url: `http://${host}:${server.address().port}/` })));
+}
+
+/** A run's rows, for building pairs against another run. */
+export const runRows = (dir) => latestJobs(dir);
diff --git a/scripts/eval/lib/run.mjs b/scripts/eval/lib/run.mjs
new file mode 100644
index 00000000..fbf3214a
--- /dev/null
+++ b/scripts/eval/lib/run.mjs
@@ -0,0 +1,476 @@
+// The runner: a suite's jobs through a running Fuobe's REST API, on one engine. For each job it
+// prices the request (POST /api/generations?preview=1, or a studio route's /estimate), uploads its
+// inputs, submits it, waits, downloads the outputs and records what ran: model, route, final prompt,
+// the LoRAs the route loaded (and those it left out), seed, time, cost, and on the open engine the
+// memory ComfyUI used. Rows go to results/<runId>/jobs.jsonl as each job ends, so --resume picks up.
+import { execFileSync } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { comfyProbe } from "./comfy.mjs";
+import { listMedia, REPO_DIR, safeName } from "./paths.mjs";
+import { expandJobs, planSummary } from "./plan.mjs";
+import { fillTemplate, probeClip, requestIdFor, uploader } from "./media.mjs";
+import { RECIPES_FILE, LOOKS_FILE } from "./recipes.mjs";
+import { engineProblem, serverFacts } from "./server.mjs";
+import { appendJsonl, latestJobs, newRunId, readJson, runDir, writeJson } from "./store.mjs";
+
+const TERMINAL = new Set(["succeeded", "failed", "canceled"]);
+/** The cloud's spend cap when none is given (US$). The open engine and demo runs are free. */
+export const DEFAULT_CLOUD_CAP = 5;
+const MAX_ELEMENT_PHOTOS = 20;
+
+const money = (n) => (n == null ? "unknown" : n === 0 ? "Free" : `$${n < 0.1 ? n.toFixed(4) : n.toFixed(2)}`);
+const sum = (xs) => xs.reduce((a, b) => a + (b ?? 0), 0);
+const fileSha = (abs) => {
+ try {
+ return crypto.createHash("sha256").update(fs.readFileSync(abs)).digest("hex").slice(0, 16);
+ } catch {
+ return null;
+ }
+};
+const gitCommit = () => {
+ try {
+ return execFileSync("git", ["-C", REPO_DIR, "rev-parse", "--short", "HEAD"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
+ } catch {
+ return null;
+ }
+};
+
+/** Run `fn` over `items` with at most `n` at a time, in order of start. */
+async function pool(items, n, fn) {
+ let next = 0;
+ const workers = Array.from({ length: Math.max(1, Math.min(n, items.length)) }, async () => {
+ while (next < items.length) {
+ const i = next++;
+ await fn(items[i], i);
+ }
+ });
+ await Promise.all(workers);
+}
+
+/** The model a studio route's answer names and its generations: {final, items}. */
+const routeResult = (answer, how) => {
+ const items = answer?.items ?? [];
+ const final = answer?.final ?? items.at(-1);
+ if (how === "all") return items.length ? items : [final].filter(Boolean);
+ if (how === "last") return [items.at(-1) ?? final].filter(Boolean);
+ return [final].filter(Boolean);
+};
+
+/**
+ * @typedef {object} RunOptions
+ * @property {object} suite a parsed suite (loadSuite)
+ * @property {"demo" | "open" | "cloud"} engine
+ * @property {string[]} [variants] @property {string[]} [cases] @property {string[]} [looks] @property {string[]} [tags]
+ * @property {number} [limit] @property {number} [prompts] @property {number[]} [seeds] @property {string} [model]
+ * @property {boolean} [dryRun] price and list the jobs; nothing is uploaded or started
+ * @property {number} [maxUsd] stop before the run's cost goes over this (cloud default DEFAULT_CLOUD_CAP)
+ * @property {number} [concurrency] jobs at a time (open 1, cloud 4, demo 4)
+ * @property {string} root the results folder
+ * @property {string} [resume] a run id to continue (failed and missing jobs run again)
+ * @property {boolean} [allowFixtures] use the synthetic fixtures when your own inputs are missing
+ * @property {string} [comfyUrl] ComfyUI's address, for memory and /history (open engine)
+ * @property {string} [label] a note for this run (shown in reports)
+ */
+
+/**
+ * @param {RunOptions} opts
+ * @param {{ client: ReturnType<import("../../../bin/lib/client.mjs").createClient>, target?: object, log?: (s: string) => void, now?: () => number, sleep?: (ms: number) => Promise<void>, signal?: AbortSignal, pollMs?: number, fetch?: typeof fetch }} io
+ */
+export async function runEval(opts, io) {
+ const log = io.log ?? (() => {});
+ const now = io.now ?? Date.now;
+ const sleep = io.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+ const { client } = io;
+ const { suite, engine } = opts;
+
+ const facts = await serverFacts(client);
+ const problem = engineProblem(engine, facts);
+ if (problem) throw new Error(problem);
+
+ // Resume: the same run's settings, so the same jobs come out.
+ let runId = opts.resume ?? null;
+ let dir = runId ? runDir(opts.root, runId) : null;
+ const previous = dir ? readJson(path.join(dir, "run.json")) : null;
+ if (runId && !previous) throw new Error(`There's no run “${runId}” in ${opts.root} to resume`);
+ const filters = previous?.filters ?? {
+ variants: opts.variants,
+ cases: opts.cases,
+ looks: opts.looks,
+ tags: opts.tags,
+ limit: opts.limit,
+ prompts: opts.prompts,
+ seeds: opts.seeds,
+ model: opts.model,
+ allowFixtures: !!opts.allowFixtures,
+ };
+
+ const jobs = expandJobs(suite, { engine, ...filters, available: facts.available });
+ const summary = planSummary(jobs);
+ const maxUsd = opts.maxUsd ?? previous?.maxUsd ?? (engine === "cloud" ? DEFAULT_CLOUD_CAP : Infinity);
+ const concurrency = opts.concurrency ?? (engine === "open" ? 1 : 4);
+
+ if (!opts.dryRun && !dir) {
+ runId = newRunId(suite.suite, engine, new Date(now()));
+ dir = runDir(opts.root, runId);
+ }
+ const up = uploader(client, opts.dryRun ? null : dir, { dry: !!opts.dryRun, log });
+
+ // Training cases: one element per case, trained (or, in demo runs, made from the fixtures) before its prompts run.
+ const elements = new Map();
+ const trainCases = [...new Map(jobs.filter((j) => j.train && !j.skip).map((j) => [j.caseId, j])).values()];
+ for (const j of trainCases) {
+ const why = trainingProblem(j, engine);
+ if (why) for (const x of jobs.filter((y) => y.caseId === j.caseId && !y.skip)) x.skip = why;
+ }
+
+ // Price every runnable job with what the server says the route runs.
+ const priced = [];
+ for (const job of jobs) {
+ if (job.skip) continue;
+ try {
+ // A training case's files are the element's photos, not inputs of each request.
+ const inputs = job.train ? {} : await up.inputs(job.inputs);
+ const p = await price(client, job, inputs, { engine, runId: runId ?? "dry-run" });
+ job.preview = p;
+ if (engine === "demo" && !p.demo) job.skip = `would run for real on ${p.providerId}: turn on Settings → Demo mode for a free self-test`;
+ else if (engine !== "demo" && p.demo) job.skip = `would run as a demo: ${p.modelName ?? job.model.id} has no ${engine === "open" ? "ComfyUI" : "cloud provider"} connected on that Fuobe`;
+ else if (engine !== "demo" && p.engine && p.engine !== engine) job.skip = `${p.modelName ?? job.model.id} is ${p.engine === "open" ? "an open-source" : "a cloud"} model, not ${engine}`;
+ else priced.push(job);
+ } catch (e) {
+ job.skip = `the server refused it: ${e.message}`;
+ }
+ }
+ const estimate = sum(priced.map((j) => j.preview.costUsd));
+ const unknownCost = priced.filter((j) => j.preview.costUsd == null).length;
+
+ if (opts.dryRun) {
+ const final = planSummary(jobs);
+ return { dryRun: true, suite: suite.suite, engine, server: io.target?.url ?? client.url, ...final, estimateUsd: estimate, unknownCost, maxUsd, jobs: jobs.map(publicJob) };
+ }
+ if (engine === "cloud" && estimate > maxUsd) {
+ throw new Error(`This run would cost about ${money(estimate)}, over the spend cap of ${money(maxUsd)}. Raise it with --max-usd ${Math.ceil(estimate)} or run fewer jobs (--looks, --cases, --limit, --prompts).`);
+ }
+
+ // The run's record: what ran, where, with which research files, before anything starts.
+ const comfy = engine === "open" && opts.comfyUrl ? comfyProbe(opts.comfyUrl, { fetch: io.fetch }) : null;
+ const comfyInfo = comfy ? await comfy.info() : null;
+ const run = {
+ runId,
+ suite: suite.suite,
+ title: suite.title,
+ original: suite.original,
+ kind: suite.kind,
+ engine,
+ label: opts.label ?? previous?.label ?? null,
+ server: { url: io.target?.url ?? client.url, engineMode: facts.engineMode, demoMode: facts.demoMode, cloudProvider: facts.cloudProvider, providers: facts.providers },
+ comfy: comfy ? { url: comfy.url, ...(comfyInfo ?? { unreachable: true }) } : null,
+ filters,
+ variants: summary.variants,
+ variantInfo: Object.fromEntries(summary.variants.map((v) => [v, suite.variants?.[v]?.description ?? ""])),
+ maxUsd: Number.isFinite(maxUsd) ? maxUsd : null,
+ estimateUsd: estimate,
+ harness: { commit: gitCommit(), recipes: { file: RECIPES_FILE, sha: fileSha(path.join(REPO_DIR, RECIPES_FILE)) }, looks: { file: LOOKS_FILE, sha: fileSha(path.join(REPO_DIR, LOOKS_FILE)) }, suiteFile: path.relative(REPO_DIR, suite.file ?? "") },
+ startedAt: previous?.startedAt ?? now(),
+ resumedAt: previous ? now() : undefined,
+ finishedAt: null,
+ counts: summary,
+ };
+ writeJson(path.join(dir, "run.json"), run);
+ log(`Run ${runId}: ${priced.length} job${priced.length === 1 ? "" : "s"} on ${engine}${summary.skipped ? `, ${jobs.length - priced.length} skipped` : ""} · estimated ${money(estimate)}${unknownCost ? ` (+${unknownCost} unpriced)` : ""}`);
+
+ // Rows from an earlier attempt: succeeded jobs are kept, the rest run again; skipped ones are recorded once.
+ const done = new Map(latestJobs(dir).map((r) => [r.id, r]));
+ for (const job of jobs.filter((j) => j.skip)) {
+ if (done.get(job.id)?.status === "succeeded") continue;
+ appendJsonl(path.join(dir, "jobs.jsonl"), { ...recordBase(job), status: "skipped", skip: job.skip, at: now() });
+ }
+
+ for (const j of trainCases) {
+ if (jobs.some((x) => x.caseId === j.caseId && !x.skip)) {
+ try {
+ elements.set(j.caseId, await prepareElement(client, j, { engine, runId, dir, up, log, sleep, now, signal: io.signal }));
+ } catch (e) {
+ for (const x of priced.filter((y) => y.caseId === j.caseId)) x.skip = `training didn't finish: ${e.message}`;
+ }
+ }
+ }
+
+ let spent = 0;
+ const queue = priced.filter((j) => !j.skip && done.get(j.id)?.status !== "succeeded");
+ for (const j of priced.filter((x) => x.skip)) appendJsonl(path.join(dir, "jobs.jsonl"), { ...recordBase(j), status: "skipped", skip: j.skip, at: now() });
+ const kept = priced.length - queue.length - priced.filter((x) => x.skip).length;
+ if (kept) log(`${kept} job${kept === 1 ? "" : "s"} already done in this run; running the other ${queue.length}`);
+
+ let finished = 0;
+ await pool(queue, concurrency, async (job) => {
+ if (io.signal?.aborted) return;
+ const est = job.preview.costUsd ?? 0;
+ if (engine === "cloud" && spent + est > maxUsd + 1e-9) {
+ appendJsonl(path.join(dir, "jobs.jsonl"), { ...recordBase(job), status: "skipped", skip: `the spend cap (${money(maxUsd)}) was reached`, at: now() });
+ return;
+ }
+ spent += est;
+ const attempt = (done.get(job.id)?.attempt ?? 0) + 1;
+ const row = await runJob(client, job, { engine, runId, dir, up, comfy, element: elements.get(job.caseId), attempt, log, sleep, now, signal: io.signal, pollMs: io.pollMs ?? (engine === "demo" ? 500 : 2000) });
+ // The actual cost replaces the estimate once the server knows it.
+ if (row.costUsd?.actual != null) spent += row.costUsd.actual - est;
+ appendJsonl(path.join(dir, "jobs.jsonl"), row);
+ finished++;
+ const took = row.timing?.wallMs != null ? ` in ${(row.timing.wallMs / 1000).toFixed(1)} s` : "";
+ log(`[${finished}/${queue.length}] ${row.status === "succeeded" ? "✓" : "✗"} ${job.key} · ${job.variant}${took}${row.error ? ` — ${row.error}` : ""}`);
+ });
+
+ const rows = latestJobs(dir);
+ const count = (s) => rows.filter((r) => r.status === s).length;
+ run.finishedAt = now();
+ run.interrupted = !!io.signal?.aborted || undefined;
+ run.spentUsd = sum(rows.map((r) => r.costUsd?.actual ?? (r.status === "succeeded" ? r.costUsd?.estimate : 0)));
+ run.results = { succeeded: count("succeeded"), failed: count("failed") + count("timeout") + count("canceled"), skipped: count("skipped"), interrupted: count("interrupted") };
+ writeJson(path.join(dir, "run.json"), run);
+ return { runId, dir, run, rows };
+}
+
+/** What a job is, for its row (also written for jobs that never ran). */
+function recordBase(job) {
+ return {
+ id: job.id,
+ key: job.key,
+ suite: job.suite,
+ caseId: job.caseId,
+ caseTitle: job.caseTitle,
+ variant: job.variant,
+ promptId: job.promptId,
+ prompt: job.prompt,
+ seed: job.seed,
+ engine: job.engine,
+ kind: job.kind,
+ model: { id: job.model.id, candidates: job.model.candidates },
+ metrics: job.metrics,
+ references: job.references,
+ inputs: job.inputs,
+ notes: job.notes,
+ ...(job.shot && { shot: job.shot }),
+ recipe: job.recipe ?? null,
+ };
+}
+
+/** A job as the dry run lists it. */
+function publicJob(job) {
+ return {
+ id: job.id,
+ case: job.caseId,
+ variant: job.variant,
+ prompt: job.promptId,
+ seed: job.seed,
+ model: job.preview?.modelId ?? job.model.id,
+ costUsd: job.preview?.costUsd ?? null,
+ loras: job.preview?.loras ? { applied: job.preview.loras.applied.map((l) => `${l.file}@${l.strength ?? 1}`), dropped: job.preview.loras.dropped } : job.request.loras?.map((l) => `${l.file}@${l.strength ?? 1}`),
+ ...(job.skip && { skip: job.skip }),
+ ...(job.notes.length && { notes: job.notes }),
+ };
+}
+
+/** Why a training case can't run here (or null). */
+function trainingProblem(job, engine) {
+ const t = job.train;
+ if (engine === "demo" || t.element) return null;
+ if (!t.target) return `no training target for ${engine} in this case`;
+ if (!t.consent) return 'training needs "consent": true in the case (only when the person in the photos agreed)';
+ const photos = listMedia(t.photos).filter((f) => /\.(png|jpe?g|webp)$/i.test(f));
+ if (photos.length < t.minPhotos) return `add at least ${t.minPhotos} photos to ${path.relative(REPO_DIR, t.photos)} (there ${photos.length === 1 ? "is" : "are"} ${photos.length})`;
+ return null;
+}
+
+/** The studio vars a route body can name. */
+function routeVars(job, inputs, { engine, runId, attempt = 1 }) {
+ const sources = {};
+ for (const [slot, v] of Object.entries(job.inputs ?? {})) {
+ if (typeof v !== "string" || !/\.(mp4|mov|m4v|webm)$/i.test(v)) continue;
+ sources[`inputs.${slot}`] = { url: inputs[slot], name: path.basename(v), ...probeClip(v) };
+ }
+ return {
+ inputs,
+ sources,
+ prompt: job.request.prompt ?? job.prompt,
+ seed: job.seed,
+ engine: engine === "demo" ? "open" : engine,
+ modelId: job.model.id,
+ requestId: requestIdFor(runId, job.id, attempt),
+ };
+}
+
+/** The price and what the server would run, for one job. */
+async function price(client, job, inputs, ctx) {
+ if (job.submit) {
+ const body = fillTemplate(job.submit.body, routeVars(job, inputs, ctx));
+ const route = job.submit.estimate === false ? null : (job.submit.estimate ?? `${job.submit.route}/estimate`);
+ if (!route) return { costUsd: null, demo: ctx.engine === "demo", modelId: job.model.id };
+ const e = await client.request("POST", route, { json: body });
+ return { costUsd: e.costUsd ?? e.totalUsd ?? null, demo: e.demo ?? ctx.engine === "demo", modelId: e.modelId ?? job.model.id, notes: e.notes };
+ }
+ return client.request("POST", "/api/generations", { json: { ...job.request, inputs }, query: { preview: 1 } });
+}
+
+/** Make (or reuse) the trained element a training case @mentions; returns {id, handle, training}. */
+async function prepareElement(client, job, ctx) {
+ const t = job.train;
+ const file = path.join(ctx.dir, "elements.json");
+ const saved = readJson(file, {});
+ const reuse = t.element ?? saved[job.caseId]?.id;
+ if (reuse && saved[job.caseId]?.status !== "failed") {
+ const el = await client.request("GET", `/api/elements/${encodeURIComponent(reuse)}`);
+ if (ctx.engine === "demo" || t.element || el.status !== "training") return { id: el.id, handle: el.handle, reused: true };
+ }
+ // Demo runs don't train: the fixtures' drawn faces become the element's reference images.
+ const photos = ctx.engine === "demo" ? Object.values(job.inputs).flat() : listMedia(t.photos).filter((f) => /\.(png|jpe?g|webp)$/i.test(f));
+ const refs = [];
+ for (const f of photos.slice(0, MAX_ELEMENT_PHOTOS)) refs.push(await ctx.up.url(f));
+ const name = `${t.name ?? "Eval character"} ${ctx.runId.slice(-4)}`.slice(0, 60);
+ const el = await client.request("POST", "/api/elements", { json: { name, kind: "character", references: refs } });
+ const record = { id: el.id, handle: el.handle, photos: refs.length, ...(photos.length > MAX_ELEMENT_PHOTOS && { note: `the first ${MAX_ELEMENT_PHOTOS} of ${photos.length} photos (an element holds ${MAX_ELEMENT_PHOTOS})` }) };
+ if (ctx.engine === "demo") {
+ writeJson(file, { ...saved, [job.caseId]: { ...record, status: "demo" } });
+ return record;
+ }
+ ctx.log(`Training ${name} on ${t.target} with ${refs.length} photos`);
+ const started = ctx.now();
+ const tr = await client.request("POST", `/api/elements/${encodeURIComponent(el.id)}/trainings`, { json: { target: t.target } });
+ writeJson(file, { ...saved, [job.caseId]: { ...record, training: tr.id, target: t.target, status: "training", startedAt: started } });
+ for (;;) {
+ if (ctx.signal?.aborted) throw new Error("stopped");
+ await ctx.sleep(15_000);
+ const list = await client.request("GET", `/api/elements/${encodeURIComponent(el.id)}/trainings`);
+ const now = (list.items ?? []).find((x) => x.id === tr.id);
+ if (now?.status === "succeeded") {
+ const done = { ...record, training: tr.id, target: t.target, status: "succeeded", costUsd: now.costUsd ?? null, startedAt: started, finishedAt: ctx.now() };
+ writeJson(file, { ...readJson(file, {}), [job.caseId]: done });
+ return done;
+ }
+ if (now?.status === "failed" || now?.status === "canceled") {
+ writeJson(file, { ...readJson(file, {}), [job.caseId]: { ...record, training: tr.id, status: "failed", error: now.error } });
+ throw new Error(now.error ?? "the training failed");
+ }
+ if (ctx.now() - started > 4 * 3600_000) throw new Error("still training after 4 hours");
+ }
+}
+
+/** One generation by id. */
+const getGeneration = (client, id) => client.request("GET", `/api/generations/${encodeURIComponent(id)}`);
+
+/** Submit, wait, download and record one job. */
+async function runJob(client, job, ctx) {
+ const base = recordBase(job);
+ const t0 = ctx.now();
+ const row = { ...base, attempt: ctx.attempt, at: t0, costUsd: { estimate: job.preview?.costUsd ?? null } };
+ let watched = [];
+ ctx.comfy?.start();
+ try {
+ const inputs = job.train ? {} : await ctx.up.inputs(job.inputs);
+ const mention = (s) => (ctx.element && typeof s === "string" ? s.replaceAll("{character}", `@${ctx.element.handle}`) : s);
+ if (job.submit) {
+ const vars = routeVars(job, inputs, ctx);
+ vars.prompt = mention(vars.prompt);
+ const body = fillTemplate(job.submit.body, vars);
+ row.request = { route: job.submit.route, body };
+ const answer = await client.request("POST", job.submit.route, { json: body });
+ watched = routeResult(answer, job.submit.result);
+ row.steps = (answer.items ?? []).map((g) => g.id);
+ } else {
+ const request = { ...job.request, prompt: mention(job.request.prompt), inputs };
+ row.request = request;
+ // The preview again with the real prompt: it names the route and the LoRAs it loads.
+ const p = ctx.element ? await client.request("POST", "/api/generations", { json: request, query: { preview: 1 } }) : job.preview;
+ row.route = p.route ?? null;
+ row.serverPrompt = p.prompt ?? null;
+ if (job.recipe && p.loras) {
+ row.recipe = { ...job.recipe, applied: p.loras.applied, dropped: p.loras.dropped, complete: !!job.recipe.sent?.complete && !p.loras.dropped.some((d) => job.recipe.sent.loras.some((l) => l.file === d.file)) };
+ }
+ const answer = await client.request("POST", "/api/generations", { json: request });
+ watched = answer.items ?? [];
+ }
+ if (!watched.length) throw new Error("the server started nothing");
+ row.generations = watched.map((g) => g.id);
+
+ // Wait for every generation (a studio route's final step waits for the steps before it).
+ const deadline = t0 + (job.timeoutSeconds ?? 1800) * 1000;
+ let final = watched;
+ for (;;) {
+ final = await Promise.all(watched.map((g) => (TERMINAL.has(g.status) ? g : getGeneration(client, g.id))));
+ watched = final;
+ if (final.every((g) => TERMINAL.has(g.status))) break;
+ if (ctx.signal?.aborted) {
+ row.status = "interrupted";
+ row.error = "stopped before it finished (it keeps running on the server)";
+ return finish(row, final, t0, ctx);
+ }
+ if (ctx.now() > deadline) {
+ row.status = "timeout";
+ row.error = `still running after ${job.timeoutSeconds} s`;
+ return finish(row, final, t0, ctx);
+ }
+ await ctx.sleep(ctx.pollMs);
+ }
+ const bad = final.find((g) => g.status !== "succeeded");
+ row.status = bad ? (bad.status === "canceled" ? "canceled" : "failed") : "succeeded";
+ if (bad) row.error = bad.error ?? `the generation ${bad.status}`;
+ await finish(row, final, t0, ctx);
+ if (row.status === "succeeded") row.outputs = await download(client, final, path.join(ctx.dir, "outputs", safeName(job.id)), ctx.dir);
+ return row;
+ } catch (e) {
+ row.status = "failed";
+ row.error = e.message;
+ return finish(row, [], t0, ctx);
+ } finally {
+ ctx.comfy?.stop();
+ }
+}
+
+/** Timing, cost and (open engine) memory and ComfyUI's own times. */
+async function finish(row, gens, t0, ctx) {
+ const t1 = ctx.now();
+ const created = Math.min(...gens.map((g) => g.createdAt ?? Infinity));
+ const completed = Math.max(...gens.map((g) => g.completedAt ?? -Infinity));
+ row.timing = { submittedAt: t0, finishedAt: t1, wallMs: t1 - t0, ...(Number.isFinite(created) && Number.isFinite(completed) && { serverMs: completed - created }) };
+ const actual = gens.map((g) => g.costUsd).filter((c) => c != null);
+ row.costUsd = { estimate: row.costUsd?.estimate ?? null, actual: actual.length ? Math.round(sum(actual) * 1e6) / 1e6 : null };
+ row.model = { ...row.model, ...(gens[0] && { id: gens[0].modelId, name: gens[0].modelName, provider: gens[0].provider, demo: gens[0].provider === "mock" }) };
+ row.generationInfo = gens.map((g) => ({ id: g.id, status: g.status, provider: g.provider, modelId: g.modelId, costUsd: g.costUsd, createdAt: g.createdAt, completedAt: g.completedAt, ...(g.error && { error: g.error }) }));
+ if (ctx.comfy && gens.length) {
+ row.vram = ctx.comfy.peak(t0, t1);
+ const hist = [];
+ for (const g of gens) {
+ const h = await ctx.comfy.history(g.id);
+ if (h) hist.push(h);
+ }
+ if (hist.length) row.comfy = { promptIds: hist.flatMap((h) => h.promptIds), execMs: sum(hist.map((h) => h.execMs)) || null, cachedNodes: sum(hist.map((h) => h.cachedNodes)), passes: sum(hist.map((h) => h.passes)) };
+ }
+ return row;
+}
+
+/** Save every output of the finished generations; returns the files relative to the run folder. */
+async function download(client, gens, folder, runFolder) {
+ const files = [];
+ let n = 0;
+ for (const g of gens) {
+ for (const o of g.outputs ?? []) {
+ n++;
+ const role = o.meta?.role ? `-${safeName(o.meta.role)}` : "";
+ if (typeof o.text === "string" && !o.url) {
+ const dest = path.join(folder, `${n}${role}.txt`);
+ fs.mkdirSync(folder, { recursive: true });
+ fs.writeFileSync(dest, o.text);
+ files.push({ file: path.relative(runFolder, dest), kind: "text", generationId: g.id, bytes: Buffer.byteLength(o.text) });
+ continue;
+ }
+ const ext = /^\.[a-z\d]{1,10}$/i.exec(path.extname(new URL(o.url, "http://x").pathname))?.[0] ?? ".bin";
+ const dest = path.join(folder, `${n}${role}${ext}`);
+ const bytes = await client.download(o.url, dest);
+ files.push({ file: path.relative(runFolder, dest), url: o.url, kind: o.kind, contentType: o.contentType ?? null, generationId: g.id, bytes, ...(o.meta?.role && { role: o.meta.role }), ...(o.meta?.demo && { demo: true }) });
+ }
+ }
+ return files;
+}
+
+export { money };
diff --git a/tests/eval-harness.test.ts b/tests/eval-harness.test.ts
new file mode 100644
index 00000000..929c1527
--- /dev/null
+++ b/tests/eval-harness.test.ts
@@ -0,0 +1,418 @@
+import fs from "node:fs";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { Writable } from "node:stream";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+/**
+ * The evaluation harness (scripts/eval) end to end against Fuobe's real route handlers, served over
+ * HTTP the way a running Fuobe serves them, with the demo provider (no keys, no GPU): plan, price,
+ * upload, submit, wait, download, record; then report, blind review, compare and promote.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 120_000, hookTimeout: 60_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-eval-harness-"));
+const results = path.join(dir, "results");
+process.env.FUOBE_DATA_DIR = path.join(dir, "data");
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const status = await import("@/app/api/status/route");
+const models = await import("@/app/api/models/route");
+const generations = await import("@/app/api/generations/route");
+const generation = await import("@/app/api/generations/[id]/route");
+const uploads = await import("@/app/api/uploads/route");
+const files = await import("@/app/api/files/[...path]/route");
+const elements = await import("@/app/api/elements/route");
+const element = await import("@/app/api/elements/[id]/route");
+const genjutsu = await import("@/app/api/genjutsu/route");
+const genjutsuEstimate = await import("@/app/api/genjutsu/estimate/route");
+
+// The harness is plain ESM JavaScript (it runs with node, no build step).
+const evalCli = (await import("../scripts/eval/eval.mjs")) as { main: (argv: string[], io?: object) => Promise<number> };
+const cases = (await import("../scripts/eval/lib/cases.mjs")) as { loadSuite: (n: string) => Record<string, unknown>; validateAll: () => { ok: boolean; file: string; lines: string[] }[] };
+const runner = (await import("../scripts/eval/lib/run.mjs")) as { runEval: (opts: object, io: object) => Promise<Record<string, unknown>> };
+const report = (await import("../scripts/eval/lib/report.mjs")) as { writeReport: (dir: string, root: string) => Record<string, unknown> };
+const review = (await import("../scripts/eval/lib/review.mjs")) as {
+ writeReview: (run: object, opts?: object) => { pairs: number };
+ serveReview: (dir: string, opts?: object) => Promise<{ server: http.Server; url: string }>;
+};
+const compare = (await import("../scripts/eval/lib/compare.mjs")) as { promote: (dir: string, opts?: object) => { results: { caseId: string; verdict: string; reasons: string[]; notes: string[] }[] } };
+const store = (await import("../scripts/eval/lib/store.mjs")) as { latestJobs: (d: string) => Row[]; readJsonl: (f: string) => Record<string, unknown>[] };
+const { createClient } = (await import("../bin/lib/client.mjs")) as { createClient: (t: { url: string }) => unknown };
+
+type Row = Record<string, unknown> & { id: string; status: string; variant: string; key: string; caseId: string; outputs?: { file: string; kind: string }[]; recipe?: Record<string, unknown>; request?: Record<string, unknown> };
+
+const ctx = (params: Record<string, unknown>) => ({ params: Promise.resolve(params) }) as never;
+const ROUTES: [string, RegExp, (req: Request, m: RegExpExecArray) => Promise<Response>][] = [
+ ["GET", /^\/api\/status$/, () => status.GET()],
+ ["GET", /^\/api\/models$/, (r) => models.GET(r)],
+ ["POST", /^\/api\/generations$/, (r) => generations.POST(r)],
+ ["GET", /^\/api\/generations\/([^/]+)$/, (r, m) => generation.GET(r, ctx({ id: m[1] }))],
+ ["POST", /^\/api\/uploads$/, (r) => uploads.POST(r)],
+ ["GET", /^\/api\/files\/(.+)$/, (r, m) => files.GET(r, ctx({ path: m[1].split("/").map(decodeURIComponent) }))],
+ ["POST", /^\/api\/elements$/, (r) => elements.POST(r)],
+ ["GET", /^\/api\/elements\/([^/]+)$/, (r, m) => element.GET(r, ctx({ id: m[1] }))],
+ ["POST", /^\/api\/genjutsu$/, (r) => genjutsu.POST(r)],
+ ["POST", /^\/api\/genjutsu\/estimate$/, (r) => genjutsuEstimate.POST(r)],
+];
+
+let server: http.Server;
+let base = "";
+const seen: string[] = [];
+
+beforeAll(async () => {
+ setSetting("demoMode", "auto");
+ server = http.createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://fuobe.test");
+ const chunks: Buffer[] = [];
+ for await (const c of req) chunks.push(c as Buffer);
+ seen.push(`${req.method} ${url.pathname}`);
+ const route = ROUTES.find(([method, re]) => method === req.method && re.test(url.pathname));
+ if (!route) {
+ res.writeHead(404, { "content-type": "application/json" });
+ return res.end(JSON.stringify({ error: "Not found" }));
+ }
+ const body = chunks.length && req.method !== "GET" ? Buffer.concat(chunks) : undefined;
+ const request = new Request(`http://localhost${url.pathname}${url.search}`, { method: req.method, headers: req.headers as Record<string, string>, body });
+ try {
+ const answer = await route[2](request, route[1].exec(url.pathname)!);
+ res.writeHead(answer.status, Object.fromEntries(answer.headers));
+ res.end(Buffer.from(await answer.arrayBuffer()));
+ } catch (e) {
+ res.writeHead(500, { "content-type": "application/json" });
+ res.end(JSON.stringify({ error: (e as Error).message }));
+ }
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+});
+
+afterAll(async () => {
+ await new Promise((r) => server.close(r));
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+const sink = () => {
+ let text = "";
+ const stream = new Writable({
+ write(chunk, _enc, done) {
+ text += chunk.toString();
+ done();
+ },
+ });
+ return { stream, text: () => text };
+};
+
+/** The harness's own command line, as `pnpm eval:<command>` runs it, against the bridged server. */
+async function cli(argv: string[]) {
+ const out = sink();
+ const err = sink();
+ const code = await evalCli.main(argv, { stdout: out.stream, stderr: err.stream, env: { ...process.env, FUOBE_EVAL_RESULTS: results, FUOBE_URL: base, FUOBE_CONFIG: path.join(dir, "no-config.json"), FUOBE_EVAL_PYTHON: "/nonexistent/python" } });
+ return { code, stdout: out.text(), stderr: err.text() };
+}
+
+const runIdFrom = (text: string) => /Run (\S+):/.exec(text)?.[1] ?? "";
+
+describe("case files", () => {
+ it("every suite in scripts/eval/cases validates, and the generated ones match the research", async () => {
+ const all = cases.validateAll();
+ expect(all.filter((r) => !r.ok).map((r) => `${r.file}: ${r.lines.join("; ")}`)).toEqual([]);
+ expect(all.length).toBeGreaterThanOrEqual(9);
+ const v = await cli(["validate"]);
+ expect(v.code, v.stdout).toBe(0);
+ const soul = cases.loadSuite("soul") as { cases: { id: string; look: string }[] };
+ expect(soul.cases).toHaveLength(139);
+ });
+
+ it("refuses a malformed suite with the path to each problem", () => {
+ const bad = path.join(dir, "bad.json");
+ fs.writeFileSync(bad, JSON.stringify({ suite: "Bad Name", title: "x", description: "x", original: "x", kind: "image", targets: {}, cases: [{ id: "a", title: "a", prompts: [{ text: "p", seed: -1 }], look: "v1-general" }, { id: "a", title: "dup" }] }));
+ let message = "";
+ try {
+ cases.loadSuite(bad);
+ } catch (e) {
+ message = (e as Error).message;
+ }
+ expect(message).toMatch(/suite: lower-case letters/);
+ expect(message).toMatch(/targets: name a target for at least one engine/);
+ expect(message).toMatch(/cases\[0\]\.prompts\[0\]\.seed/);
+ expect(message).toMatch(/duplicate case id a/);
+ expect(message).toMatch(/a look needs "recipe": "soul-look"/);
+ });
+});
+
+describe("the runner on the demo provider", () => {
+ let selftestRun = "";
+
+ it("runs the self-test suite through the API: uploads, submits, waits, downloads and records each job", async () => {
+ const r = await cli(["run", "--suite", "selftest", "--engine", "demo", "--label", "e2e"]);
+ expect(r.code, r.stderr).toBe(0);
+ selftestRun = runIdFrom(r.stderr);
+ const runDir = path.join(results, selftestRun);
+ const run = JSON.parse(fs.readFileSync(path.join(runDir, "run.json"), "utf8"));
+ expect(run).toMatchObject({ suite: "selftest", engine: "demo", label: "e2e", server: { url: base, demoMode: "auto" }, results: { succeeded: 5, failed: 0 } });
+ expect(run.harness.recipes.sha).toMatch(/^[0-9a-f]{16}$/);
+ const rows = store.latestJobs(runDir);
+ expect(rows.map((x) => x.status)).toEqual(Array(5).fill("succeeded"));
+ for (const row of rows) {
+ expect(row.outputs?.length, row.id).toBeGreaterThan(0);
+ for (const o of row.outputs!) expect(fs.statSync(path.join(runDir, o.file)).size).toBeGreaterThan(0);
+ expect(row).toMatchObject({ model: { demo: true, provider: "mock" }, costUsd: { estimate: 0 } });
+ expect((row.timing as { wallMs: number }).wallMs).toBeGreaterThan(0);
+ }
+ // Inputs went up once each and the requests carried the server's URLs.
+ const trim = rows.find((x) => x.caseId === "selftest/trim")!;
+ expect((trim.request!.inputs as { video: string }).video).toMatch(/^\/api\/files\/uploads\//);
+ expect(seen.filter((s) => s === "POST /api/uploads").length).toBeGreaterThanOrEqual(3);
+ // Scoring had no Python here: the report says so instead of failing.
+ expect(r.stderr).toMatch(/Not scored: Couldn't start \/nonexistent\/python|Not scored/);
+ const summary = JSON.parse(fs.readFileSync(path.join(runDir, "summary.json"), "utf8"));
+ expect(summary.counts).toMatchObject({ jobs: 5, succeeded: 5 });
+ expect(fs.readFileSync(path.join(runDir, "report.html"), "utf8")).toContain("Harness self-test");
+ expect(r.stdout).toMatch(/Harness self-test · demo · 5\/5 done · Free/);
+ });
+
+ it("records the recipe a Soul look ran with: the look's words, its LoRAs at each variant's strength, and what the route loads", async () => {
+ const r = await cli(["run", "--suite", "soul", "--engine", "demo", "--looks", "v2-flash-editorial", "--variants", "recipe,prompt-only,half-strength", "--prompts", "1", "--no-metrics"]);
+ expect(r.code, r.stderr).toBe(0);
+ const runDir = path.join(results, runIdFrom(r.stderr));
+ const rows = store.latestJobs(runDir);
+ expect(rows).toHaveLength(3);
+ const by = Object.fromEntries(rows.map((x) => [x.variant, x]));
+ const sent = (v: string) => (by[v].request!.loras as { file: string; strength: number }[] | undefined) ?? [];
+ expect(sent("recipe").map((l) => l.strength)).toEqual([0.7, 0.4]);
+ expect(sent("half-strength").map((l) => l.strength)).toEqual([0.35, 0.2]);
+ expect(sent("prompt-only")).toEqual([]);
+ expect(String(by.recipe.request!.prompt)).toMatch(/^hardflashy, a young woman .*Direct on-camera flash/);
+ // The preview named the open route, and ComfyUI loads every LoRA the harness sent.
+ expect(by.recipe.route).toEqual({ provider: "comfyui", endpoint: "z-image-turbo-t2i" });
+ expect(by.recipe.recipe).toMatchObject({ kind: "soul-look", look: { name: "Flash editorial", family: "v2" }, complete: true, dropped: [] });
+ expect((by.recipe.recipe!.applied as unknown[]).length).toBe(2);
+ expect(by.recipe.seed).toBe(1001);
+ });
+
+ it("runs a studio route (Genjutsu) with a probed source clip and a stable requestId", async () => {
+ const r = await cli(["run", "--suite", "genjutsu", "--engine", "demo", "--cases", "genjutsu/move", "--no-metrics"]);
+ expect(r.code, r.stderr).toBe(0);
+ const [row] = store.latestJobs(path.join(results, runIdFrom(r.stderr)));
+ expect(row.status).toBe("succeeded");
+ const body = (row.request as { route: string; body: Record<string, unknown> }).body;
+ expect((row.request as { route: string }).route).toBe("/api/genjutsu");
+ expect(body).toMatchObject({ engine: "open", mode: "motion", modelId: "oss-wan22-animate", seed: 1001 });
+ expect(String(body.requestId)).toMatch(/^eval-[0-9a-f]{24}$/);
+ expect((body.source as { url: string }).url).toMatch(/^\/api\/files\//);
+ if (fs.existsSync("/usr/bin/ffprobe")) expect(body.source).toMatchObject({ fps: 24, width: 432, height: 768, duration: 4 });
+ expect(row.outputs?.[0]?.kind).toBe("video");
+ });
+
+ it("a training case in a demo run makes an element from the fixtures and @mentions it (no training)", async () => {
+ const r = await cli(["run", "--suite", "soul-id", "--engine", "demo", "--prompts", "1", "--variants", "trained", "--no-metrics"]);
+ const runDir = path.join(results, runIdFrom(r.stderr));
+ const el = JSON.parse(fs.readFileSync(path.join(runDir, "elements.json"), "utf8"))["soul-id/character"];
+ expect(el).toMatchObject({ status: "demo", photos: 3 });
+ const [row] = store.latestJobs(runDir);
+ expect(String((row.request as { prompt: string }).prompt)).toContain(`@${el.handle} as a chef`);
+ });
+
+ it("refuses an engine the server can't run, and skips jobs that would run as a demo on a real engine", async () => {
+ const dry = await cli(["run", "--suite", "soul", "--engine", "cloud", "--looks", "v1-general", "--dry-run"]);
+ expect(dry.code, dry.stderr).toBe(0);
+ expect(dry.stdout).toMatch(/would run as a demo/);
+ setSetting("engineMode", "open");
+ try {
+ const r = await cli(["run", "--suite", "soul", "--engine", "cloud", "--looks", "v1-general"]);
+ expect(r.code).toBe(1);
+ expect(r.stderr).toMatch(/runs open-source models only \(Settings → Engine mode\)/);
+ } finally {
+ setSetting("engineMode", "both");
+ }
+ });
+
+ it("prices a cloud run before anything starts, and stops it at the spend cap", async () => {
+ setSetting("falKey", "fal-test-key");
+ try {
+ const dry = await cli(["run", "--suite", "soul", "--engine", "cloud", "--looks", "v2-flash-editorial,v1-general", "--dry-run", "--json"]);
+ const plan = JSON.parse(dry.stdout);
+ expect(plan).toMatchObject({ engine: "cloud", runnable: 6, skipped: 0, maxUsd: 5 });
+ expect(plan.estimateUsd).toBeGreaterThan(0);
+ const flash = plan.jobs.find((j: { case: string }) => j.case === "soul/v2-flash-editorial");
+ // On the cloud the civitai Hard Flash LoRA is left out (its link needs a token); fal's LoRA endpoint takes the HF one.
+ expect(flash.loras.applied).toEqual(["[email protected]"]);
+ expect(flash.notes.join(" ")).toMatch(/Hard Flash left out on the cloud/);
+ const before = seen.filter((s) => s === "POST /api/generations").length;
+ const r = await cli(["run", "--suite", "soul", "--engine", "cloud", "--looks", "v2-flash-editorial", "--max-usd", "0.00001"]);
+ expect(r.code).toBe(1);
+ expect(r.stderr).toMatch(/over the spend cap of \$0\.0000.*--max-usd/);
+ // Only the three previews went out (POST ?preview=1 is the same path): nothing was started.
+ expect(seen.filter((s) => s === "POST /api/generations").length - before).toBe(3);
+ } finally {
+ setSetting("falKey", "");
+ }
+ });
+
+ it("resume runs only what isn't done", async () => {
+ const runDir = path.join(results, selftestRun);
+ const lines = fs.readFileSync(path.join(runDir, "jobs.jsonl"), "utf8").trim().split("\n");
+ // Pretend the last job failed.
+ const last = JSON.parse(lines.at(-1)!);
+ fs.appendFileSync(path.join(runDir, "jobs.jsonl"), `${JSON.stringify({ ...last, status: "failed", error: "pretend" })}\n`);
+ const r = await cli(["run", "--resume", selftestRun, "--no-metrics"]);
+ expect(r.code, r.stderr).toBe(0);
+ expect(r.stderr).toMatch(/4 jobs already done in this run; running the other 1/);
+ expect(store.latestJobs(runDir).every((x) => x.status === "succeeded")).toBe(true);
+ expect(store.latestJobs(runDir).find((x) => x.id === last.id)?.attempt).toBe(2);
+ });
+});
+
+/** A run folder made by hand: rows and metrics as the runner and the scorer write them. */
+function fakeRun(name: string, engine: string, scores: Record<string, Record<string, number>>, extra: Partial<Row> = {}) {
+ const runDir = path.join(results, name);
+ fs.mkdirSync(path.join(runDir, "outputs"), { recursive: true });
+ const png = Buffer.from("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c63f8cfc0f01f0005000201a2e2b6a40000000049454e44ae426082", "hex");
+ const ids = Object.keys(scores);
+ const variants = [...new Set(ids.map((id) => id.split("--").at(-1)!))];
+ fs.writeFileSync(path.join(runDir, "run.json"), JSON.stringify({ runId: name, suite: "soul", title: "Fuobe Soul", engine, variants, startedAt: Date.now(), server: { url: "x" } }));
+ const rows = ids.map((id) => {
+ const [caseId, promptId, seed, variant] = id.split("--");
+ fs.writeFileSync(path.join(runDir, "outputs", `${id}.png`), png);
+ return {
+ id,
+ key: `soul/${caseId}/${promptId}/${seed}`,
+ caseId: `soul/${caseId}`,
+ caseTitle: caseId,
+ variant,
+ promptId,
+ seed: Number(seed.slice(1)),
+ prompt: "a portrait",
+ status: "succeeded",
+ outputs: [{ file: `outputs/${id}.png`, kind: "image" }],
+ references: [],
+ recipe: { kind: "soul-look", loras: [{ file: "a.safetensors", commercial: true, hostedOk: true }], applied: variant === "plain" ? [] : [{ file: "a.safetensors", strength: 0.7 }], complete: true, sent: { complete: true, loras: [] } },
+ costUsd: { estimate: 0 },
+ timing: { wallMs: 1000 },
+ ...extra,
+ };
+ });
+ fs.writeFileSync(path.join(runDir, "jobs.jsonl"), rows.map((r) => JSON.stringify(r)).join("\n") + "\n");
+ fs.writeFileSync(path.join(runDir, "metrics.json"), JSON.stringify({ version: 1, jobs: scores, groups: {}, models: {}, skipped: {} }));
+ return runDir;
+}
+
+describe("report, blind review, compare and promote", () => {
+ const ids = (variant: string) => ["s1001", "s2002", "s3003"].map((s) => `look-a--p1--${s}--${variant}`);
+ const scored = (variant: string, style: number, clip: number) => Object.fromEntries(ids(variant).map((id, i) => [id, { style: style + i * 0.001, clip: clip + i * 0.1, aesthetic: 6 }]));
+
+ it("summarises variants against each other and writes history lines per case and variant", () => {
+ const runDir = fakeRun("fake-open-1", "open", { ...scored("recipe", 0.8, 30), ...scored("prompt-only", 0.7, 31) });
+ const s = report.writeReport(runDir, results) as { variants: Record<string, { mean: Record<string, number> }>; pairs: { other: string; metrics: Record<string, { wins: number; losses: number }> }[] };
+ expect(s.variants.recipe.mean.style).toBeCloseTo(0.801, 3);
+ expect(s.pairs[0]).toMatchObject({ other: "prompt-only", metrics: { style: { wins: 3, losses: 0 }, clip: { wins: 0, losses: 3 } } });
+ const hist = store.readJsonl(path.join(results, "history.jsonl")).filter((h) => h.runId === "fake-open-1");
+ expect(hist.map((h) => h.variant).sort()).toEqual(["prompt-only", "recipe"]);
+ // A second report of the same run replaces its lines instead of adding more.
+ report.writeReport(runDir, results);
+ expect(store.readJsonl(path.join(results, "history.jsonl")).filter((h) => h.runId === "fake-open-1")).toHaveLength(2);
+ const html = fs.readFileSync(path.join(runDir, "report.html"), "utf8");
+ expect(html).toContain('<meta name="viewport"');
+ expect(html).toContain("prefers-color-scheme: dark");
+ });
+
+ it("builds blind pairs whose page doesn't say which side is which, saves ratings and unblinds them in the summary", async () => {
+ const runDir = path.join(results, "fake-open-1");
+ const rows = store.latestJobs(runDir);
+ const made = review.writeReview({ dir: runDir, runId: "fake-open-1", rows });
+ expect(made.pairs).toBe(3);
+ const html = fs.readFileSync(path.join(runDir, "review", "index.html"), "utf8");
+ expect(html).not.toMatch(/prompt-only|recipe|look-a--/);
+ const key = JSON.parse(fs.readFileSync(path.join(runDir, "review", "key.json"), "utf8"));
+ const { server, url } = await review.serveReview(runDir);
+ try {
+ expect((await fetch(`${url}key.json`)).status).toBe(404);
+ expect((await fetch(`${url}..%2Frun.json`)).status).toBe(404);
+ expect((await fetch(url)).status).toBe(200);
+ // Pick the recipe side every time.
+ const ratings = key.pairs.map((p: { id: string; left: "a" | "b"; a: { label: string } }) => ({ pair: p.id, choice: (p.a.label === "recipe") === (p.left === "a") ? "left" : "right" }));
+ expect((await fetch(`${url}ratings`, { method: "POST", body: JSON.stringify({ ratings: [{ pair: "x", choice: "maybe" }] }) })).status).toBe(400);
+ expect((await fetch(`${url}ratings`, { method: "POST", body: JSON.stringify({ ratings }) })).status).toBe(204);
+ } finally {
+ await new Promise((r) => server.close(r));
+ }
+ const s = report.writeReport(runDir, results) as { ratings: { total: number; pairs: { a: string; b: string; aWins: number; bWins: number; preferA: number }[] } };
+ expect(s.ratings).toEqual({ total: 3, pairs: [{ a: "recipe", b: "prompt-only", aWins: 3, bWins: 0, ties: 0, preferA: 1 }] });
+ });
+
+ it("promotes a recipe only when it wins on metrics and in the blind review, and says when strengths over-cook", () => {
+ const runDir = path.join(results, "fake-open-1");
+ // 3 ratings are fewer than the rule's 6.
+ let doc = compare.promote(runDir);
+ expect(doc.results[0].verdict).toBe("hold");
+ expect(doc.results[0].reasons.join(" ")).toMatch(/needs a blind review: 3 ratings/);
+ const ratingsFile = path.join(runDir, "review", "ratings.json");
+ const saved = JSON.parse(fs.readFileSync(ratingsFile, "utf8"));
+ const key = JSON.parse(fs.readFileSync(path.join(runDir, "review", "key.json"), "utf8"));
+ // Six ratings: the same three pairs rated by a second reviewer (another key entry per pair).
+ key.pairs = [...key.pairs, ...key.pairs.map((p: { id: string }) => ({ ...p, id: `${p.id}-2` }))];
+ fs.writeFileSync(path.join(runDir, "review", "key.json"), JSON.stringify(key));
+ fs.writeFileSync(ratingsFile, JSON.stringify({ ...saved, ratings: [...saved.ratings, ...saved.ratings.map((r: { pair: string }) => ({ ...r, pair: `${r.pair}-2` }))] }));
+ doc = compare.promote(runDir);
+ expect(doc.results[0]).toMatchObject({ verdict: "promote", reasons: [] });
+ // Half strength scoring higher on the look's main metric: lower the strengths instead.
+ const over = fakeRun("fake-open-2", "open", { ...scored("recipe", 0.8, 30), ...scored("half-strength", 0.9, 30) });
+ const d2 = compare.promote(over);
+ expect(d2.results[0].verdict).toBe("lower strengths");
+ expect(d2.results[0].notes.join(" ")).toMatch(/over-cook/);
+ // Demo runs never promote anything.
+ const demo = fakeRun("fake-demo-1", "demo", { ...scored("recipe", 0.9, 30), ...scored("prompt-only", 0.1, 30) });
+ expect(compare.promote(demo).results[0].reasons[0]).toBe("demo media, not model output");
+ });
+
+ it("compare prints wins and losses and fails when a chosen metric regresses beyond the threshold", async () => {
+ fakeRun("fake-open-3", "open", { ...scored("recipe", 0.8, 28.5), ...scored("prompt-only", 0.7, 31) });
+ const ok = await cli(["compare", "fake-open-1", "fake-open-3", "--fail-on", "style"]);
+ expect(ok.code, ok.stdout).toBe(0);
+ expect(ok.stdout).toMatch(/6 jobs in both/);
+ expect(ok.stdout).toMatch(/No regressions beyond the threshold/);
+ // The recipe lost 1.5 CLIP on its three jobs: 0.75 over all six, more than the 0.5 allowed.
+ const bad = await cli(["compare", "fake-open-1", "fake-open-3", "--fail-on", "clip", "--threshold", "0.5"]);
+ expect(bad.code).toBe(1);
+ expect(bad.stdout).toMatch(/CLIP prompt adherence: mean 30\.6 → 29\.[89] \(−0\.8\)/);
+ expect((await cli(["compare", "fake-open-1", "fake-open-3", "--fail-on", "clip", "--threshold", "1"])).code).toBe(0);
+ // --per-case catches the one case that lost more than its share.
+ expect((await cli(["compare", "fake-open-1", "fake-open-3", "--fail-on", "clip", "--threshold", "0.5", "--per-case"])).stdout).toMatch(/soul\/look-a: −0\.8/);
+ // A percentage threshold of A's mean: 0.75 CLIP lost is under 5% of 30.6.
+ expect((await cli(["compare", "fake-open-1", "fake-open-3", "--fail-on", "clip", "--threshold", "5%"])).code).toBe(0);
+ // One variant against another of the same run.
+ const v = await cli(["compare", "fake-open-1:prompt-only", "fake-open-1:recipe", "--fail-on", "style", "--json"]);
+ expect(JSON.parse(v.stdout)).toMatchObject({ matched: 3, failed: false, metrics: expect.arrayContaining([expect.objectContaining({ metric: "style", wins: 3 })]) });
+ const unknown = await cli(["compare", "fake-open-1", "fake-open-3", "--fail-on", "smell"]);
+ expect(unknown.code).toBe(1);
+ expect(unknown.stderr).toMatch(/Unknown metric “smell”/);
+ });
+
+ it("history lists runs, newest first", async () => {
+ const h = await cli(["history", "--json"]);
+ const doc = JSON.parse(h.stdout);
+ expect(doc.runs.length).toBeGreaterThanOrEqual(5);
+ expect(doc.history.length).toBeGreaterThan(0);
+ });
+});
+
+describe("runEval as a library", () => {
+ it("expands, prices and lists a dry run without uploading anything", async () => {
+ const before = seen.filter((s) => s === "POST /api/uploads").length;
+ const suite = cases.loadSuite("dop");
+ const plan = (await runner.runEval({ suite, engine: "demo", dryRun: true, limit: 2, variants: ["catalog", "prompt-only", "research"], root: results }, { client: createClient({ url: base }) })) as { jobs: { variant: string; loras?: { applied: string[] } }[]; runnable: number };
+ expect(plan.runnable).toBe(12);
+ expect(seen.filter((s) => s === "POST /api/uploads").length).toBe(before);
+ const research = plan.jobs.find((j) => j.variant === "research")!;
+ expect(research.loras?.applied.length).toBeGreaterThan(0);
+ const promptOnly = plan.jobs.find((j) => j.variant === "prompt-only")!;
+ expect(promptOnly.loras?.applied).toEqual([]);
+ });
+});
diff --git a/tests/eval-metrics.test.ts b/tests/eval-metrics.test.ts
new file mode 100644
index 00000000..47dd62ea
--- /dev/null
+++ b/tests/eval-metrics.test.ts
@@ -0,0 +1,32 @@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+/**
+ * The evaluation harness's metric tests (scripts/eval/metrics/tests, pytest). They run in the
+ * metrics venv when pnpm eval:setup made one, else through uv with the small test requirements;
+ * with neither (or no network for uv's first install) they are skipped, not failed.
+ */
+
+const METRICS = path.join(process.cwd(), "scripts/eval/metrics");
+const VENV = path.join(METRICS, process.platform === "win32" ? ".venv/Scripts/python.exe" : ".venv/bin/python");
+
+function python(): { cmd: string; args: string[] } | null {
+ if (fs.existsSync(VENV)) return { cmd: VENV, args: [] };
+ const uv = spawnSync("uv", ["--version"], { encoding: "utf8" });
+ if (uv.status !== 0) return null;
+ return { cmd: "uv", args: ["run", "--no-project", "--with-requirements", path.join(METRICS, "requirements-test.txt"), "python"] };
+}
+
+const py = python();
+// Can that Python import what the maths tests need? (uv's first run downloads them; offline it can't.)
+const ready = py && spawnSync(py.cmd, [...py.args, "-c", "import numpy, PIL, pytest"], { cwd: METRICS, encoding: "utf8", timeout: 300_000 }).status === 0;
+
+describe.skipIf(!ready)("metric maths and media (pytest)", () => {
+ it("passes", () => {
+ const r = spawnSync(py!.cmd, [...py!.args, "-m", "pytest", "-q", "-p", "no:cacheprovider", "tests"], { cwd: METRICS, encoding: "utf8", timeout: 600_000 });
+ expect(r.status, `${r.stdout}\n${r.stderr}`).toBe(0);
+ expect(r.stdout).toMatch(/\d+ passed/);
+ }, 600_000);
+});