@blazediff/agent 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { readFile, mkdir, writeFile, access, readdir, stat, rm, rename } from 'fs/promises';
1
+ import { mkdir, readFile, writeFile, copyFile, rm, access, readdir, stat, rename } from 'fs/promises';
2
2
  import path from 'path';
3
3
  import { availableParallelism, cpus } from 'os';
4
4
  import { existsSync, readFileSync } from 'fs';
@@ -11,6 +11,7 @@ import { compare } from '@blazediff/core-native';
11
11
  import * as util from 'util';
12
12
  import { Annotation, Command, StateGraph, START, Send, END, interrupt } from '@langchain/langgraph';
13
13
  import sharp from 'sharp';
14
+ import pc from 'picocolors';
14
15
  import { BaseCheckpointSaver, TASKS, maxChannelVersion, getCheckpointId, copyCheckpoint, WRITES_IDX_MAP } from '@langchain/langgraph-checkpoint';
15
16
 
16
17
  // src/browser/capture.ts
@@ -20,12 +21,15 @@ var DEFAULT_FULL_PAGE = true;
20
21
  var DEFAULT_THRESHOLD = 0.1;
21
22
  var MIN_AUTO_CONCURRENCY = 2;
22
23
  var MAX_AUTO_CONCURRENCY = 8;
23
- function defaultConcurrency() {
24
+ function cpuCores() {
24
25
  const cores = typeof availableParallelism === "function" ? availableParallelism() : cpus().length;
25
26
  if (!cores || !Number.isFinite(cores)) return MIN_AUTO_CONCURRENCY;
27
+ return cores;
28
+ }
29
+ function defaultConcurrency() {
26
30
  return Math.max(
27
31
  MIN_AUTO_CONCURRENCY,
28
- Math.min(MAX_AUTO_CONCURRENCY, cores - 1)
32
+ Math.min(MAX_AUTO_CONCURRENCY, cpuCores() - 1)
29
33
  );
30
34
  }
31
35
  var BLAZEDIFF_DIR = ".blazediff";
@@ -36,12 +40,11 @@ var paths = (cwd = process.cwd()) => {
36
40
  config: path.join(root, "config.json"),
37
41
  manifest: path.join(root, "manifest.json"),
38
42
  harnesses: path.join(root, "harnesses"),
39
- authHarness: path.join(root, "harnesses", "auth.js"),
40
43
  baselines: path.join(root, "baselines"),
41
44
  actual: path.join(root, "actual"),
42
45
  judgments: path.join(root, "judgments"),
43
46
  checkpoints: path.join(root, "checkpoints"),
44
- summary: path.join(root, "summary.md"),
47
+ report: path.join(root, "report.json"),
45
48
  gitignore: path.join(root, ".gitignore"),
46
49
  serverLog: path.join(root, "dev-server.log"),
47
50
  serverPid: path.join(root, "dev-server.pid")
@@ -70,7 +73,7 @@ async function loadHarness(harnessFile) {
70
73
  const absolute = path.isAbsolute(harnessFile) ? harnessFile : path.resolve(process.cwd(), harnessFile);
71
74
  if (!existsSync(absolute)) {
72
75
  throw new HarnessError(
73
- `harness not found at ${absolute}. Author one under .blazediff/harnesses/ (or run \`blazediff-agent auth init\` for a login harness).`
76
+ `harness not found at ${absolute}. Author one under .blazediff/harnesses/ (or run \`blazediff-agent harness record <name>\` to record one).`
74
77
  );
75
78
  }
76
79
  const cached = moduleCache.get(absolute);
@@ -79,7 +82,10 @@ async function loadHarness(harnessFile) {
79
82
  const loading = (async () => {
80
83
  let mod;
81
84
  try {
82
- mod = await import(url);
85
+ mod = await import(
86
+ /* @vite-ignore */
87
+ url
88
+ );
83
89
  } catch (err) {
84
90
  throw new HarnessError(
85
91
  `failed to load harness at ${absolute}: ${err.message}`,
@@ -90,7 +96,7 @@ async function loadHarness(harnessFile) {
90
96
  if (!harness || typeof harness.run !== "function") {
91
97
  if (typeof mod.login === "function") {
92
98
  throw new HarnessError(
93
- `legacy auth harness detected at ${absolute} (exports \`login\`). Re-run \`blazediff-agent auth init\` to regenerate it as a harness.`
99
+ `legacy auth harness detected at ${absolute} (exports \`login\`). Re-run \`blazediff-agent harness record auth --login\` to regenerate it as a harness.`
94
100
  );
95
101
  }
96
102
  throw new HarnessError(
@@ -159,7 +165,13 @@ var contextPool = /* @__PURE__ */ new Map();
159
165
  async function getBrowser() {
160
166
  if (cachedBrowser?.isConnected()) return cachedBrowser;
161
167
  if (launchInFlight) return launchInFlight;
162
- launchInFlight = chromium.launch({ headless: true, args: CHROMIUM_FLAGS }).then((b) => {
168
+ launchInFlight = chromium.launch({
169
+ headless: true,
170
+ args: CHROMIUM_FLAGS,
171
+ handleSIGINT: false,
172
+ handleSIGTERM: false,
173
+ handleSIGHUP: false
174
+ }).then((b) => {
163
175
  cachedBrowser = b;
164
176
  return b;
165
177
  }).finally(() => {
@@ -477,28 +489,25 @@ function resolveBaseUrl(config, override) {
477
489
  }
478
490
 
479
491
  // src/graph/semaphore.ts
480
- var Semaphore = class {
481
- constructor(limit) {
482
- this.limit = limit;
483
- this.current = 0;
484
- this.queue = [];
485
- if (limit < 1)
486
- throw new Error(`semaphore limit must be >= 1 (got ${limit})`);
487
- }
488
- async run(fn) {
489
- if (this.current >= this.limit) {
490
- await new Promise((resolve) => this.queue.push(resolve));
492
+ function createSemaphore(limit) {
493
+ if (limit < 1) throw new Error(`semaphore limit must be >= 1 (got ${limit})`);
494
+ let current = 0;
495
+ const queue = [];
496
+ async function run(fn) {
497
+ if (current >= limit) {
498
+ await new Promise((resolve) => queue.push(resolve));
491
499
  }
492
- this.current++;
500
+ current++;
493
501
  try {
494
502
  return await fn();
495
503
  } finally {
496
- this.current--;
497
- const next = this.queue.shift();
504
+ current--;
505
+ const next = queue.shift();
498
506
  if (next) next();
499
507
  }
500
508
  }
501
- };
509
+ return { run };
510
+ }
502
511
 
503
512
  // src/types.ts
504
513
  var STABILITY_HOOKS_VERSION = 1;
@@ -655,7 +664,10 @@ async function runCaptures(opts) {
655
664
  let manifest = writeManifest ? await loadOrCreateManifest(cwd, config) : null;
656
665
  let manifestUpdates = 0;
657
666
  const slot = new Array(valid.length);
658
- const semaphore = new Semaphore(opts.concurrency ?? defaultConcurrency());
667
+ const pendingUpdates = new Array(valid.length).fill(
668
+ null
669
+ );
670
+ const semaphore = createSemaphore(opts.concurrency ?? defaultConcurrency());
659
671
  try {
660
672
  await Promise.all(
661
673
  valid.map(
@@ -696,28 +708,19 @@ async function runCaptures(opts) {
696
708
  fullPage: r.fullPage,
697
709
  harnesses: refs.length > 0 ? refs : void 0
698
710
  };
699
- manifest = {
700
- ...manifest,
701
- entries: manifest.entries.filter((e) => e.parent !== r.id)
702
- };
703
- manifest = addOrReplaceEntry(
704
- manifest,
705
- makeEntry({ id: r.id, ...shared })
706
- );
707
- manifestUpdates += 1;
708
- for (const sub of shot.subCaptures ?? []) {
709
- manifest = addOrReplaceEntry(
710
- manifest,
711
- makeEntry({
711
+ pendingUpdates[i] = {
712
+ baseId: r.id,
713
+ baseEntry: makeEntry({ id: r.id, ...shared }),
714
+ derivedEntries: (shot.subCaptures ?? []).map(
715
+ (sub) => makeEntry({
712
716
  id: `${r.id}__${sub.name}`,
713
717
  ...shared,
714
718
  parent: r.id,
715
719
  derived: true,
716
720
  subName: sub.name
717
721
  })
718
- );
719
- manifestUpdates += 1;
720
- }
722
+ )
723
+ };
721
724
  }
722
725
  } catch (err) {
723
726
  slot[i] = {
@@ -732,7 +735,22 @@ async function runCaptures(opts) {
732
735
  )
733
736
  );
734
737
  for (const r of slot) results.push(r);
735
- if (manifest && manifestUpdates > 0) await saveManifest(manifest, cwd);
738
+ if (manifest) {
739
+ for (const update of pendingUpdates) {
740
+ if (!update) continue;
741
+ manifest = {
742
+ ...manifest,
743
+ entries: manifest.entries.filter((e) => e.parent !== update.baseId)
744
+ };
745
+ manifest = addOrReplaceEntry(manifest, update.baseEntry);
746
+ manifestUpdates += 1;
747
+ for (const derived of update.derivedEntries) {
748
+ manifest = addOrReplaceEntry(manifest, derived);
749
+ manifestUpdates += 1;
750
+ }
751
+ }
752
+ if (manifestUpdates > 0) await saveManifest(manifest, cwd);
753
+ }
736
754
  } finally {
737
755
  await closeBrowser();
738
756
  }
@@ -775,7 +793,7 @@ async function diffEntry(id, baselinePath, actualPath, opts = {}, cwd = process.
775
793
  }
776
794
  const threshold = opts.threshold ?? DEFAULT_THRESHOLD;
777
795
  const antialiasing = opts.antialiasing ?? true;
778
- const result = await compare(baselinePath, actualPath, diffPath, {
796
+ const result = await compare(baselinePath, actualPath, void 0, {
779
797
  threshold,
780
798
  antialiasing,
781
799
  interpret: true
@@ -800,6 +818,13 @@ async function diffEntry(id, baselinePath, actualPath, opts = {}, cwd = process.
800
818
  reason: "layout-diff"
801
819
  };
802
820
  }
821
+ if (diffPath) {
822
+ await compare(baselinePath, actualPath, diffPath, {
823
+ threshold,
824
+ antialiasing,
825
+ compression: 9
826
+ });
827
+ }
803
828
  return {
804
829
  id,
805
830
  baselinePath,
@@ -823,9 +848,9 @@ function extractInternalLinks(base, target, hrefs) {
823
848
  try {
824
849
  const u = new URL(href, target);
825
850
  if (u.origin !== base.origin) continue;
826
- const path20 = u.pathname + u.search;
827
- if (path20.startsWith("/api/")) continue;
828
- out.push(path20);
851
+ const path23 = u.pathname + u.search;
852
+ if (path23.startsWith("/api/")) continue;
853
+ out.push(path23);
829
854
  } catch {
830
855
  }
831
856
  }
@@ -879,15 +904,24 @@ async function crawlRoutes(opts) {
879
904
  }
880
905
  return discovered.slice(0, maxRoutes);
881
906
  }
882
- var DYNAMIC_SEGMENT = /\[[^\]]+\]/;
883
- async function readJson(file) {
884
- if (!existsSync(file)) return null;
907
+ async function fileExists2(p) {
908
+ try {
909
+ await access(p);
910
+ return true;
911
+ } catch {
912
+ return false;
913
+ }
914
+ }
915
+ async function readJsonOrNull(file) {
885
916
  try {
886
917
  return JSON.parse(await readFile(file, "utf8"));
887
918
  } catch {
888
919
  return null;
889
920
  }
890
921
  }
922
+
923
+ // src/discover/next.ts
924
+ var DYNAMIC_SEGMENT = /\[[^\]]+\]/;
891
925
  function isPublicRoute(route) {
892
926
  if (DYNAMIC_SEGMENT.test(route)) return false;
893
927
  if (route === "/api" || route.startsWith("/api/")) return false;
@@ -903,13 +937,13 @@ async function discoverFromNextManifest(cwd = process.cwd()) {
903
937
  seen.add(url);
904
938
  out.push({ url, source: "next-manifest" });
905
939
  };
906
- const routes = await readJson(
940
+ const routes = await readJsonOrNull(
907
941
  path.join(nextDir, "routes-manifest.json")
908
942
  );
909
943
  for (const r of routes?.staticRoutes ?? []) {
910
944
  if (isPublicRoute(r.page)) add(r.page);
911
945
  }
912
- const appPaths = await readJson(
946
+ const appPaths = await readJsonOrNull(
913
947
  path.join(nextDir, "server", "app-paths-manifest.json")
914
948
  );
915
949
  for (const route of Object.keys(appPaths ?? {})) {
@@ -1022,14 +1056,19 @@ var ENTRIES = [
1022
1056
  "actual/",
1023
1057
  "judgments/",
1024
1058
  "checkpoints/",
1025
- "summary.md",
1059
+ "report.json",
1026
1060
  "dev-server.log",
1027
1061
  "dev-server.pid",
1028
1062
  ".env",
1029
1063
  ".env.local",
1030
1064
  "*.tmp"
1031
1065
  ];
1032
- var STALE_ENTRIES = /* @__PURE__ */ new Set(["diffs/", "pending-judgments/", "report.json"]);
1066
+ var STALE_ENTRIES = /* @__PURE__ */ new Set([
1067
+ "diffs/",
1068
+ "pending-judgments/",
1069
+ "summary.html",
1070
+ "summary.md"
1071
+ ]);
1033
1072
  var HEADER = "# blazediff: generated artifacts (committed: config.json, manifest.json, baselines/, harnesses/)\n";
1034
1073
  async function ensureGitignore(cwd) {
1035
1074
  const file = paths(cwd).gitignore;
@@ -1056,6 +1095,15 @@ ${missing.join("\n")}
1056
1095
  await writeFile(file, body, "utf8");
1057
1096
  }
1058
1097
  var DEFAULT_TOP_N = 5;
1098
+ var READ_PAD_X_FACTOR = 2.5;
1099
+ var READ_PAD_X_MIN = 48;
1100
+ var READ_PAD_X_MAX = 130;
1101
+ var READ_PAD_Y_FACTOR = 0.6;
1102
+ var READ_PAD_Y_MIN = 4;
1103
+ var READ_PAD_Y_MAX = 12;
1104
+ var READ_TARGET_WIDTH = 480;
1105
+ var READ_SCALE_MIN = 2;
1106
+ var READ_SCALE_MAX = 6;
1059
1107
  var DEFAULT_PADDING = 16;
1060
1108
  var DEFAULT_LOCATOR_MAX_WIDTH = 400;
1061
1109
  var DEFAULT_GUTTER = 2;
@@ -1073,17 +1121,75 @@ function padAndClamp(bbox, padding, imgWidth, imgHeight) {
1073
1121
  height: Math.max(1, bottom - top)
1074
1122
  };
1075
1123
  }
1124
+ var clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
1125
+ async function prepareRegionReads(opts) {
1126
+ const topN = opts.topN ?? DEFAULT_TOP_N;
1127
+ const meta = await sharp(opts.actualPath).metadata();
1128
+ const imgWidth = meta.width ?? 0;
1129
+ const imgHeight = meta.height ?? 0;
1130
+ if (!imgWidth || !imgHeight) {
1131
+ throw new Error(`unable to read image dimensions: ${opts.actualPath}`);
1132
+ }
1133
+ const ranked = [...opts.regions].sort((a, b) => b.pixelCount - a.pixelCount).slice(0, topN);
1134
+ return Promise.all(
1135
+ ranked.map(async (region, i) => {
1136
+ const padX = clamp(
1137
+ Math.round(region.bbox.width * READ_PAD_X_FACTOR),
1138
+ READ_PAD_X_MIN,
1139
+ READ_PAD_X_MAX
1140
+ );
1141
+ const padY = clamp(
1142
+ Math.round(region.bbox.height * READ_PAD_Y_FACTOR),
1143
+ READ_PAD_Y_MIN,
1144
+ READ_PAD_Y_MAX
1145
+ );
1146
+ const left = Math.max(0, Math.floor(region.bbox.x - padX));
1147
+ const top = Math.max(0, Math.floor(region.bbox.y - padY));
1148
+ const right = Math.min(
1149
+ imgWidth,
1150
+ Math.ceil(region.bbox.x + region.bbox.width + padX)
1151
+ );
1152
+ const bottom = Math.min(
1153
+ imgHeight,
1154
+ Math.ceil(region.bbox.y + region.bbox.height + padY)
1155
+ );
1156
+ const extract = {
1157
+ left,
1158
+ top,
1159
+ width: Math.max(1, right - left),
1160
+ height: Math.max(1, bottom - top)
1161
+ };
1162
+ const scale = clamp(
1163
+ Math.round(READ_TARGET_WIDTH / extract.width),
1164
+ READ_SCALE_MIN,
1165
+ READ_SCALE_MAX
1166
+ );
1167
+ const render = async (src, suffix) => {
1168
+ const name = `read-${i}.${suffix}.png`;
1169
+ await sharp(src).extract(extract).resize(extract.width * scale, extract.height * scale, {
1170
+ kernel: "lanczos3"
1171
+ }).png().toFile(path.join(opts.outputDir, name));
1172
+ return path.join(opts.outputDir, name);
1173
+ };
1174
+ const [beforePath, afterPath] = await Promise.all([
1175
+ render(opts.baselinePath, "before"),
1176
+ render(opts.actualPath, "after")
1177
+ ]);
1178
+ return { changeType: region.changeType, beforePath, afterPath };
1179
+ })
1180
+ );
1181
+ }
1076
1182
  async function prepareTiles(opts) {
1077
1183
  const topN = opts.topN ?? DEFAULT_TOP_N;
1078
1184
  const padding = opts.padding ?? DEFAULT_PADDING;
1079
1185
  const locatorMaxWidth = opts.locatorMaxWidth ?? DEFAULT_LOCATOR_MAX_WIDTH;
1080
1186
  const gutter = opts.gutter ?? DEFAULT_GUTTER;
1081
1187
  const rowGutter = opts.rowGutter ?? DEFAULT_ROW_GUTTER;
1082
- const diffMeta = await sharp(opts.diffPath).metadata();
1083
- const imgWidth = diffMeta.width ?? 0;
1084
- const imgHeight = diffMeta.height ?? 0;
1188
+ const meta = await sharp(opts.actualPath).metadata();
1189
+ const imgWidth = meta.width ?? 0;
1190
+ const imgHeight = meta.height ?? 0;
1085
1191
  if (!imgWidth || !imgHeight) {
1086
- throw new Error(`unable to read diff image dimensions: ${opts.diffPath}`);
1192
+ throw new Error(`unable to read image dimensions: ${opts.actualPath}`);
1087
1193
  }
1088
1194
  const ranked = [...opts.regions].sort((a, b) => b.pixelCount - a.pixelCount).slice(0, topN);
1089
1195
  const regionData = await Promise.all(
@@ -1133,19 +1239,22 @@ async function prepareTiles(opts) {
1133
1239
  }
1134
1240
  }).composite(composites).png().toFile(path.join(opts.outputDir, tilesName));
1135
1241
  }
1136
- const scale = locatorMaxWidth / Math.max(imgWidth, imgHeight);
1137
- const locW = Math.max(1, Math.round(imgWidth * scale));
1138
- const locH = Math.max(1, Math.round(imgHeight * scale));
1139
- const rects = opts.regions.map((r) => {
1140
- const x = Math.round(r.bbox.x * scale);
1141
- const y = Math.round(r.bbox.y * scale);
1142
- const w = Math.max(1, Math.round(r.bbox.width * scale));
1143
- const h = Math.max(1, Math.round(r.bbox.height * scale));
1144
- return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="none" stroke="red" stroke-width="2" />`;
1145
- }).join("");
1146
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${locW}" height="${locH}">${rects}</svg>`;
1147
- const locatorName = "locator.png";
1148
- await sharp(opts.diffPath).resize(locW, locH, { fit: "fill" }).composite([{ input: Buffer.from(svg), left: 0, top: 0 }]).png().toFile(path.join(opts.outputDir, locatorName));
1242
+ let locatorName;
1243
+ if (opts.diffPath) {
1244
+ const scale = locatorMaxWidth / Math.max(imgWidth, imgHeight);
1245
+ const locW = Math.max(1, Math.round(imgWidth * scale));
1246
+ const locH = Math.max(1, Math.round(imgHeight * scale));
1247
+ const rects = opts.regions.map((r) => {
1248
+ const x = Math.round(r.bbox.x * scale);
1249
+ const y = Math.round(r.bbox.y * scale);
1250
+ const w = Math.max(1, Math.round(r.bbox.width * scale));
1251
+ const h = Math.max(1, Math.round(r.bbox.height * scale));
1252
+ return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="none" stroke="red" stroke-width="2" />`;
1253
+ }).join("");
1254
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${locW}" height="${locH}">${rects}</svg>`;
1255
+ locatorName = "locator.png";
1256
+ await sharp(opts.diffPath).resize(locW, locH, { fit: "fill" }).composite([{ input: Buffer.from(svg), left: 0, top: 0 }]).png().toFile(path.join(opts.outputDir, locatorName));
1257
+ }
1149
1258
  return {
1150
1259
  locatorPath: locatorName,
1151
1260
  tilesPath: tilesName,
@@ -1156,9 +1265,9 @@ async function prepareTiles(opts) {
1156
1265
  };
1157
1266
  }
1158
1267
 
1159
- // src/judge/host-harness.ts
1268
+ // src/judge/coding-agent-host.ts
1160
1269
  async function tryPrepareTiles(input, entryDir) {
1161
- if (!input.regions || input.regions.length === 0 || !input.diffPath) {
1270
+ if (!input.regions || input.regions.length === 0) {
1162
1271
  return null;
1163
1272
  }
1164
1273
  try {
@@ -1177,9 +1286,10 @@ async function tryPrepareTiles(input, entryDir) {
1177
1286
  return null;
1178
1287
  }
1179
1288
  }
1180
- var hostHarnessJudge = {
1289
+ var codingAgentHostJudge = {
1181
1290
  name: "host",
1182
1291
  async judge(input, cwd) {
1292
+ input.onJudgingStart?.();
1183
1293
  const p = paths(cwd);
1184
1294
  const entryDir = path.join(p.judgments, input.entry.id);
1185
1295
  await mkdir(entryDir, { recursive: true });
@@ -1187,366 +1297,598 @@ var hostHarnessJudge = {
1187
1297
  return { kind: "deferred", requestPath: entryDir };
1188
1298
  }
1189
1299
  };
1300
+ var dim = pc.dim;
1301
+ var bold = pc.bold;
1190
1302
 
1191
- // src/judge/none.ts
1192
- var noneJudge = {
1193
- name: "none",
1194
- async judge(input) {
1195
- return { kind: "judged", verdict: input.heuristicVerdict };
1196
- }
1197
- };
1198
- var ROOT_NS_SENTINEL = "_root";
1199
- function nsDir(ns) {
1200
- return ns === "" ? ROOT_NS_SENTINEL : ns;
1201
- }
1202
- function encode(buf) {
1203
- return Buffer.from(buf).toString("base64");
1204
- }
1205
- function decode(s) {
1206
- return Buffer.from(s, "base64");
1303
+ // src/judge/transformers.ts
1304
+ var toMb = (bytes) => (bytes / 1048576).toFixed(1);
1305
+ function createLoadProgress(label) {
1306
+ const interactive = Boolean(process.stderr.isTTY);
1307
+ const bytes = /* @__PURE__ */ new Map();
1308
+ let announced = false;
1309
+ let lastPct = -1;
1310
+ let lastBucket = -1;
1311
+ const totals = () => {
1312
+ let loaded = 0;
1313
+ let total = 0;
1314
+ for (const b of bytes.values()) {
1315
+ loaded += b.loaded;
1316
+ total += b.total;
1317
+ }
1318
+ const pct = total > 0 ? Math.min(100, Math.floor(loaded / total * 100)) : 0;
1319
+ return { loaded, total, pct };
1320
+ };
1321
+ return {
1322
+ onProgress(event) {
1323
+ if (!announced) {
1324
+ process.stderr.write(
1325
+ `${dim("[blazediff]")} loading ${bold(label)} model ${dim("(first run downloads weights)\u2026")}
1326
+ `
1327
+ );
1328
+ announced = true;
1329
+ }
1330
+ if (event.status !== "progress" || !event.file || typeof event.total !== "number")
1331
+ return;
1332
+ bytes.set(event.file, { loaded: event.loaded ?? 0, total: event.total });
1333
+ const { loaded, total, pct } = totals();
1334
+ if (pct === lastPct) return;
1335
+ lastPct = pct;
1336
+ const line = ` ${label}: ${pct}% ${dim(`(${toMb(loaded)}/${toMb(total)} MB)`)}`;
1337
+ if (interactive) {
1338
+ process.stderr.write(`\r${line}\x1B[K`);
1339
+ return;
1340
+ }
1341
+ const bucket = Math.floor(pct / 25);
1342
+ if (bucket > lastBucket) {
1343
+ lastBucket = bucket;
1344
+ process.stderr.write(`${line}
1345
+ `);
1346
+ }
1347
+ },
1348
+ done() {
1349
+ if (!announced) return;
1350
+ if (interactive) {
1351
+ const { total } = totals();
1352
+ const size = total > 0 ? dim(` (${toMb(total)} MB)`) : "";
1353
+ process.stderr.write(
1354
+ `\r ${label}: ${pc.green("ready")}${size}\x1B[K
1355
+ `
1356
+ );
1357
+ } else if (lastPct < 100) {
1358
+ process.stderr.write(` ${label}: ${pc.green("ready")}
1359
+ `);
1360
+ }
1361
+ }
1362
+ };
1207
1363
  }
1208
- async function readJson2(file) {
1364
+ async function loadTransformers() {
1209
1365
  try {
1210
- const raw = await readFile(file, "utf8");
1211
- return JSON.parse(raw);
1366
+ return await import('@huggingface/transformers');
1212
1367
  } catch (err) {
1213
- if (err.code === "ENOENT") return void 0;
1214
- throw err;
1368
+ throw new Error(
1369
+ 'stack=local requires the optional peer dependency "@huggingface/transformers". Install it with `npm i @huggingface/transformers` (or pnpm/bun add).',
1370
+ { cause: err instanceof Error ? err : void 0 }
1371
+ );
1215
1372
  }
1216
1373
  }
1217
- async function writeJsonAtomic(file, value) {
1218
- const tmp = `${file}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
1219
- await writeFile(tmp, JSON.stringify(value), "utf8");
1220
- await rename(tmp, file);
1374
+
1375
+ // src/judge/classifier.ts
1376
+ var MODEL_ID = "onnx-community/Qwen3.5-0.8B-ONNX";
1377
+ var MAX_NEW_TOKENS = 64;
1378
+ async function defaultFactory() {
1379
+ const mod = await loadTransformers();
1380
+ const progress = createLoadProgress("classifier");
1381
+ const progress_callback = progress.onProgress;
1382
+ const [tokenizer, model] = await Promise.all([
1383
+ mod.AutoTokenizer.from_pretrained(MODEL_ID, { progress_callback }),
1384
+ mod.Qwen3_5ForConditionalGeneration.from_pretrained(MODEL_ID, {
1385
+ dtype: {
1386
+ embed_tokens: "fp32",
1387
+ vision_encoder: "q8",
1388
+ decoder_model_merged: "q4"
1389
+ },
1390
+ device: "cpu",
1391
+ progress_callback
1392
+ })
1393
+ ]);
1394
+ progress.done();
1395
+ return {
1396
+ async complete(prompt) {
1397
+ const inputs = tokenizer.apply_chat_template(
1398
+ [{ role: "user", content: prompt }],
1399
+ {
1400
+ add_generation_prompt: true,
1401
+ return_dict: true,
1402
+ enable_thinking: false
1403
+ }
1404
+ );
1405
+ const output = await model.generate({
1406
+ ...inputs,
1407
+ do_sample: false,
1408
+ max_new_tokens: MAX_NEW_TOKENS
1409
+ });
1410
+ const promptLen = inputs.input_ids.dims.at(-1);
1411
+ const generated = output.slice(null, [promptLen, null]);
1412
+ const decoded = tokenizer.batch_decode(generated, {
1413
+ skip_special_tokens: true
1414
+ });
1415
+ const raw = Array.isArray(decoded) ? String(decoded[0] ?? "") : String(decoded);
1416
+ return raw.trim();
1417
+ }
1418
+ };
1221
1419
  }
1222
- var FsCheckpointSaver = class extends BaseCheckpointSaver {
1223
- constructor(root, serde) {
1224
- super(serde);
1225
- this.locks = /* @__PURE__ */ new Map();
1226
- this.root = root;
1227
- }
1228
- threadDir(thread) {
1229
- return path.join(this.root, thread);
1230
- }
1231
- nsPath(thread, ns) {
1232
- return path.join(this.threadDir(thread), nsDir(ns));
1233
- }
1234
- ckptFile(thread, ns, id) {
1235
- return path.join(this.nsPath(thread, ns), `${id}.ckpt.json`);
1236
- }
1237
- writesFile(thread, ns, id) {
1238
- return path.join(this.nsPath(thread, ns), `${id}.writes.json`);
1239
- }
1240
- async withLock(key, fn) {
1241
- const prev = this.locks.get(key) ?? Promise.resolve();
1242
- const next = prev.then(fn, fn);
1243
- this.locks.set(key, next);
1244
- try {
1245
- return await next;
1246
- } finally {
1247
- if (this.locks.get(key) === next) this.locks.delete(key);
1420
+ function createClassifierRunnerHolder(factory = defaultFactory) {
1421
+ let runnerPromise;
1422
+ return {
1423
+ get() {
1424
+ if (!runnerPromise) runnerPromise = factory();
1425
+ return runnerPromise;
1248
1426
  }
1249
- }
1250
- async listCheckpointIds(thread, ns) {
1251
- try {
1252
- const names = await readdir(this.nsPath(thread, ns));
1253
- const suffix = ".ckpt.json";
1254
- return names.filter((n) => n.endsWith(suffix)).map((n) => n.slice(0, -suffix.length));
1255
- } catch (err) {
1256
- if (err.code === "ENOENT") return [];
1257
- throw err;
1427
+ };
1428
+ }
1429
+
1430
+ // src/judge/region-diff.ts
1431
+ var FILLER = /* @__PURE__ */ new Set([
1432
+ "the",
1433
+ "a",
1434
+ "an",
1435
+ "is",
1436
+ "are",
1437
+ "was",
1438
+ "were",
1439
+ "be",
1440
+ "this",
1441
+ "that",
1442
+ "these",
1443
+ "those",
1444
+ "it",
1445
+ "its",
1446
+ "there",
1447
+ "here",
1448
+ "and",
1449
+ "or",
1450
+ "but",
1451
+ "of",
1452
+ "in",
1453
+ "on",
1454
+ "at",
1455
+ "to",
1456
+ "with",
1457
+ "within",
1458
+ "against",
1459
+ "around",
1460
+ "surrounding",
1461
+ "into",
1462
+ "from",
1463
+ "by",
1464
+ "for",
1465
+ "as",
1466
+ "no",
1467
+ "not",
1468
+ "other",
1469
+ "some",
1470
+ "also",
1471
+ "another",
1472
+ "word",
1473
+ "words",
1474
+ "text",
1475
+ "letter",
1476
+ "letters",
1477
+ "character",
1478
+ "characters",
1479
+ "number",
1480
+ "numbers",
1481
+ "digit",
1482
+ "digits",
1483
+ "phrase",
1484
+ "label",
1485
+ "title",
1486
+ "written",
1487
+ "writes",
1488
+ "reads",
1489
+ "read",
1490
+ "says",
1491
+ "displayed",
1492
+ "displays",
1493
+ "display",
1494
+ "shows",
1495
+ "show",
1496
+ "showing",
1497
+ "shown",
1498
+ "appears",
1499
+ "appear",
1500
+ "reading",
1501
+ "prominently",
1502
+ "visible",
1503
+ "positioned",
1504
+ "located",
1505
+ "white",
1506
+ "black",
1507
+ "blue",
1508
+ "red",
1509
+ "green",
1510
+ "purple",
1511
+ "gray",
1512
+ "grey",
1513
+ "background",
1514
+ "foreground",
1515
+ "color",
1516
+ "colors",
1517
+ "colored",
1518
+ "colour",
1519
+ "font",
1520
+ "style",
1521
+ "styled",
1522
+ "bold",
1523
+ "italic",
1524
+ "blurred",
1525
+ "slightly",
1526
+ "image",
1527
+ "photo",
1528
+ "picture",
1529
+ "frame",
1530
+ "scene",
1531
+ "object",
1532
+ "objects",
1533
+ "element",
1534
+ "elements",
1535
+ "ui",
1536
+ "screen",
1537
+ "page",
1538
+ "logo",
1539
+ "icon",
1540
+ "button",
1541
+ "large",
1542
+ "small",
1543
+ "big",
1544
+ "left",
1545
+ "right",
1546
+ "top",
1547
+ "bottom",
1548
+ "center",
1549
+ "corner",
1550
+ "side",
1551
+ "above",
1552
+ "below",
1553
+ "ink",
1554
+ "company",
1555
+ "name",
1556
+ "brand",
1557
+ "create",
1558
+ "creating",
1559
+ "artistic",
1560
+ "effect",
1561
+ "design",
1562
+ "additional"
1563
+ ]);
1564
+ function tokenize(text) {
1565
+ return text.toLowerCase().match(/[a-z0-9]+/g) ?? [];
1566
+ }
1567
+ function extractQuoted(read) {
1568
+ const spans = [...read.matchAll(/["“”']([^"“”']+)["“”']/g)].map(
1569
+ (m) => m[1].trim()
1570
+ );
1571
+ if (spans.length === 0) return null;
1572
+ return spans.reduce((a, b) => b.length > a.length ? b : a).trim() || null;
1573
+ }
1574
+ function diffTokens(base, actual) {
1575
+ const n = base.length;
1576
+ const m = actual.length;
1577
+ const dp = Array.from(
1578
+ { length: n + 1 },
1579
+ () => new Array(m + 1).fill(0)
1580
+ );
1581
+ for (let i2 = n - 1; i2 >= 0; i2--) {
1582
+ for (let j2 = m - 1; j2 >= 0; j2--) {
1583
+ dp[i2][j2] = base[i2] === actual[j2] ? dp[i2 + 1][j2 + 1] + 1 : Math.max(dp[i2 + 1][j2], dp[i2][j2 + 1]);
1258
1584
  }
1259
1585
  }
1260
- async listNamespaces(thread) {
1261
- try {
1262
- return await readdir(this.threadDir(thread));
1263
- } catch (err) {
1264
- if (err.code === "ENOENT") return [];
1265
- throw err;
1586
+ const inserted = [];
1587
+ const removed = [];
1588
+ let i = 0;
1589
+ let j = 0;
1590
+ while (i < n && j < m) {
1591
+ if (base[i] === actual[j]) {
1592
+ i++;
1593
+ j++;
1594
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
1595
+ removed.push(base[i++]);
1596
+ } else {
1597
+ inserted.push(actual[j++]);
1266
1598
  }
1267
1599
  }
1268
- async listThreads() {
1269
- try {
1270
- return await readdir(this.root);
1271
- } catch (err) {
1272
- if (err.code === "ENOENT") return [];
1273
- throw err;
1600
+ while (i < n) removed.push(base[i++]);
1601
+ while (j < m) inserted.push(actual[j++]);
1602
+ return { inserted, removed };
1603
+ }
1604
+ var keepToken = (t) => /\d/.test(t) || !FILLER.has(t);
1605
+ var quote = (tokens) => `"${tokens.join(" ")}"`;
1606
+ function describeRegionChange(changeType, baseRead, actualRead) {
1607
+ const baseQuoted = extractQuoted(baseRead);
1608
+ const actualQuoted = extractQuoted(actualRead);
1609
+ const haveCores = baseQuoted !== null && actualQuoted !== null;
1610
+ const base = tokenize(baseQuoted ?? baseRead);
1611
+ const actual = tokenize(actualQuoted ?? actualRead);
1612
+ const { inserted, removed } = diffTokens(base, actual);
1613
+ const ins = haveCores ? inserted : inserted.filter(keepToken);
1614
+ const rem = haveCores ? removed : removed.filter(keepToken);
1615
+ const updated = actualQuoted && actualQuoted.length <= 60 ? ` (region now reads "${actualQuoted}")` : "";
1616
+ if (ins.length > 0 && rem.length === 0)
1617
+ return `added ${quote(ins)}${updated}`;
1618
+ if (rem.length > 0 && ins.length === 0)
1619
+ return `removed ${quote(rem)}${updated}`;
1620
+ if (ins.length > 0 && rem.length > 0)
1621
+ return `replaced ${quote(rem)} with ${quote(ins)}${updated}`;
1622
+ const kind = changeType.replace(/-/g, " ");
1623
+ return `${kind} with no readable text change${updated}`;
1624
+ }
1625
+
1626
+ // src/judge/vision.ts
1627
+ var MODEL_ID2 = "Xenova/moondream2";
1628
+ var PATCH_SIZE = 14;
1629
+ var MAX_NEW_TOKENS2 = 64;
1630
+ var ANSWER_MARKER = "Answer:";
1631
+ async function defaultFactory2() {
1632
+ const mod = await loadTransformers();
1633
+ const progress = createLoadProgress("vision");
1634
+ const progress_callback = progress.onProgress;
1635
+ const [tokenizer, processor, model] = await Promise.all([
1636
+ mod.AutoTokenizer.from_pretrained(MODEL_ID2, { progress_callback }),
1637
+ mod.AutoProcessor.from_pretrained(MODEL_ID2, { progress_callback }),
1638
+ mod.Moondream1ForConditionalGeneration.from_pretrained(MODEL_ID2, {
1639
+ dtype: {
1640
+ embed_tokens: "fp32",
1641
+ vision_encoder: "q8",
1642
+ decoder_model_merged: "q4"
1643
+ },
1644
+ device: "cpu",
1645
+ progress_callback
1646
+ })
1647
+ ]);
1648
+ progress.done();
1649
+ return {
1650
+ async describe(imagePath, question) {
1651
+ const image = await mod.RawImage.read(imagePath);
1652
+ const vision = await processor(image);
1653
+ const [, , height, width] = vision.pixel_values.dims;
1654
+ const numImageTokens = Math.floor(height / PATCH_SIZE) * Math.floor(width / PATCH_SIZE);
1655
+ const prompt = `${"<image>".repeat(numImageTokens)}
1656
+
1657
+ Question: ${question}
1658
+
1659
+ ${ANSWER_MARKER}`;
1660
+ const textInputs = tokenizer(prompt);
1661
+ const output = await model.generate({
1662
+ ...textInputs,
1663
+ ...vision,
1664
+ do_sample: false,
1665
+ max_new_tokens: MAX_NEW_TOKENS2,
1666
+ // Moondream loops the same sentence on composite tiles without these.
1667
+ repetition_penalty: 1.3,
1668
+ no_repeat_ngram_size: 3
1669
+ });
1670
+ const decoded = tokenizer.batch_decode(output, {
1671
+ skip_special_tokens: true
1672
+ });
1673
+ const raw = Array.isArray(decoded) ? String(decoded[0] ?? "") : String(decoded);
1674
+ const idx = raw.lastIndexOf(ANSWER_MARKER);
1675
+ return (idx >= 0 ? raw.slice(idx + ANSWER_MARKER.length) : raw).trim();
1274
1676
  }
1275
- }
1276
- decodeNs(nsDirName) {
1277
- return nsDirName === ROOT_NS_SENTINEL ? "" : nsDirName;
1278
- }
1279
- async loadPendingWrites(thread, ns, ckptId) {
1280
- const data = await readJson2(
1281
- this.writesFile(thread, ns, ckptId)
1282
- );
1283
- if (!data) return [];
1284
- const out = [];
1285
- for (const [taskId, channel, serialized] of Object.values(data)) {
1286
- const value = await this.serde.loadsTyped("json", decode(serialized));
1287
- out.push([taskId, channel, value]);
1677
+ };
1678
+ }
1679
+ function createVisionRunnerHolder(factory = defaultFactory2) {
1680
+ let runnerPromise;
1681
+ return {
1682
+ get() {
1683
+ if (!runnerPromise) runnerPromise = factory();
1684
+ return runnerPromise;
1288
1685
  }
1289
- return out;
1290
- }
1291
- async migratePendingSends(checkpoint, thread, ns, parentCheckpointId) {
1292
- const data = await readJson2(
1293
- this.writesFile(thread, ns, parentCheckpointId)
1294
- );
1295
- const pendingSends = data ? await Promise.all(
1296
- Object.values(data).filter(([, channel]) => channel === TASKS).map(
1297
- ([, , serialized]) => this.serde.loadsTyped("json", decode(serialized))
1298
- )
1299
- ) : [];
1300
- const m = checkpoint;
1301
- m.channel_values ?? (m.channel_values = {});
1302
- m.channel_values[TASKS] = pendingSends;
1303
- m.channel_versions ?? (m.channel_versions = {});
1304
- const versions = Object.values(m.channel_versions);
1305
- m.channel_versions[TASKS] = versions.length > 0 ? maxChannelVersion(...versions) : this.getNextVersion(void 0);
1306
- }
1307
- async readTuple(thread, ns, ckptId, config) {
1308
- const data = await readJson2(this.ckptFile(thread, ns, ckptId));
1309
- if (!data) return void 0;
1310
- const checkpoint = await this.serde.loadsTyped(
1311
- "json",
1312
- decode(data.checkpoint)
1313
- );
1314
- const metadata = await this.serde.loadsTyped(
1315
- "json",
1316
- decode(data.metadata)
1317
- );
1318
- if (checkpoint.v < 4 && data.parentCheckpointId !== void 0) {
1319
- await this.migratePendingSends(
1320
- checkpoint,
1321
- thread,
1322
- ns,
1323
- data.parentCheckpointId
1686
+ };
1687
+ }
1688
+
1689
+ // src/judge/local.ts
1690
+ var READ_PROMPT = [
1691
+ "Read the text in this image. Reply with only the exact words and numbers you",
1692
+ 'see, wrapped in double quotes. If there is no text, reply "".'
1693
+ ].join(" ");
1694
+ var DESCRIBE_PROMPT = [
1695
+ "In one sentence, describe the main UI elements and any visible text in this",
1696
+ "screenshot. Do not judge whether it is good or bad."
1697
+ ].join(" ");
1698
+ var LABELS = [
1699
+ "regression-likely",
1700
+ "intentional-likely",
1701
+ "noise-likely",
1702
+ "ambiguous"
1703
+ ];
1704
+ var ACTION_BY_LABEL = {
1705
+ "regression-likely": "investigate",
1706
+ "intentional-likely": "rewrite-if-intended",
1707
+ "noise-likely": "ignore-or-rewrite",
1708
+ ambiguous: "investigate"
1709
+ };
1710
+ var VERDICT_MARKER = "VERDICT:";
1711
+ function summarizeInterpret(input) {
1712
+ const lines = [];
1713
+ lines.push(
1714
+ `diff area: ${(input.diffPercentage ?? 0).toFixed(3)}% of the page`
1715
+ );
1716
+ lines.push(`severity: ${input.severity ?? "unknown"}`);
1717
+ const regions = input.regions ?? [];
1718
+ lines.push(`changed regions: ${regions.length}`);
1719
+ if (regions.length > 0) {
1720
+ const counts = /* @__PURE__ */ new Map();
1721
+ for (const r of regions)
1722
+ counts.set(r.changeType, (counts.get(r.changeType) ?? 0) + 1);
1723
+ const byType = [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([type, n]) => `${type} x${n}`).join(", ");
1724
+ lines.push(`change types: ${byType}`);
1725
+ }
1726
+ return lines.join("\n");
1727
+ }
1728
+ function buildClassifyPrompt(summary, description) {
1729
+ return [
1730
+ "You classify a visual regression-test diff into exactly one label.",
1731
+ "",
1732
+ "Deterministic analysis of the changed pixels:",
1733
+ summary,
1734
+ "",
1735
+ "The change in the affected region, read from the screenshots, is:",
1736
+ `"${description}"`,
1737
+ "",
1738
+ "Labels:",
1739
+ "- regression-likely: something looks broken, missing, clipped, or misaligned.",
1740
+ "- intentional-likely: a deliberate content or style update.",
1741
+ "- noise-likely: negligible anti-aliasing / sub-pixel rendering differences.",
1742
+ "- ambiguous: cannot tell from the evidence.",
1743
+ "",
1744
+ "First explain your reasoning in one short sentence. Then, on the final",
1745
+ `line, write "${VERDICT_MARKER} <label>" using exactly one label above.`
1746
+ ].join("\n");
1747
+ }
1748
+ function parseLabel(text) {
1749
+ const t = text.toLowerCase();
1750
+ const marked = t.match(/verdict:\s*([a-z-]+)/);
1751
+ if (marked) {
1752
+ const hit = LABELS.find((label) => marked[1].startsWith(label));
1753
+ if (hit) return hit;
1754
+ }
1755
+ let latest2 = null;
1756
+ for (const label of LABELS) {
1757
+ const idx = t.lastIndexOf(label);
1758
+ if (idx >= 0 && (!latest2 || idx > latest2.idx)) latest2 = { label, idx };
1759
+ }
1760
+ return latest2?.label ?? null;
1761
+ }
1762
+ function firstSentence(text) {
1763
+ const trimmed = text.trim().replace(/\s+/g, " ");
1764
+ const m = trimmed.match(/^.*?[.!?](\s|$)/);
1765
+ return (m ? m[0] : trimmed).trim();
1766
+ }
1767
+ function reasonOf(answer, label) {
1768
+ const beforeVerdict = answer.split(/verdict:/i)[0];
1769
+ const withoutLabel = beforeVerdict.replace(new RegExp(label, "gi"), "").trim();
1770
+ return firstSentence(withoutLabel) || firstSentence(answer);
1771
+ }
1772
+ function toError(err) {
1773
+ return err instanceof Error ? err : new Error(String(err));
1774
+ }
1775
+ function classifyFailure(err) {
1776
+ const m = err.message.toLowerCase();
1777
+ if (m.includes("model") || m.includes("weights") || m.includes("download") || m.includes("transformers"))
1778
+ return "model-load";
1779
+ if (m.includes("enoent") || m.includes("read") || m.includes("sharp") || m.includes("crop"))
1780
+ return "read";
1781
+ return "internal";
1782
+ }
1783
+ function createLocalJudge(deps = {}) {
1784
+ const vision = deps.vision ?? createVisionRunnerHolder();
1785
+ const classifier = deps.classifier ?? createClassifierRunnerHolder();
1786
+ const visionSemaphore = createSemaphore(1);
1787
+ const classifierSemaphore = createSemaphore(1);
1788
+ async function describeChange(input, entryDir) {
1789
+ if (!input.regions || input.regions.length === 0) return null;
1790
+ try {
1791
+ const crops = await prepareRegionReads({
1792
+ regions: input.regions,
1793
+ baselinePath: input.baselinePath,
1794
+ actualPath: input.actualPath,
1795
+ outputDir: entryDir
1796
+ });
1797
+ if (crops.length === 0) return null;
1798
+ const v = await vision.get();
1799
+ const phrases = await Promise.all(
1800
+ crops.map(async (crop) => {
1801
+ const [before, after] = await Promise.all([
1802
+ v.describe(crop.beforePath, READ_PROMPT),
1803
+ v.describe(crop.afterPath, READ_PROMPT)
1804
+ ]);
1805
+ return describeRegionChange(crop.changeType, before, after);
1806
+ })
1324
1807
  );
1808
+ return phrases.length === 1 ? phrases[0] : phrases.map((p, i) => `region ${i + 1}: ${p}`).join("; ");
1809
+ } catch {
1810
+ return null;
1325
1811
  }
1326
- const pendingWrites = await this.loadPendingWrites(thread, ns, ckptId);
1327
- const tuple = {
1328
- config,
1329
- checkpoint,
1330
- metadata,
1331
- pendingWrites
1332
- };
1333
- if (data.parentCheckpointId !== void 0) {
1334
- tuple.parentConfig = {
1335
- configurable: {
1336
- thread_id: thread,
1337
- checkpoint_ns: ns,
1338
- checkpoint_id: data.parentCheckpointId
1812
+ }
1813
+ async function describeScreenshot(input) {
1814
+ const v = await vision.get();
1815
+ return (await v.describe(input.actualPath, DESCRIBE_PROMPT)).trim();
1816
+ }
1817
+ return {
1818
+ name: "local",
1819
+ // Stream both models' weights up front (concurrently) so the multi-second
1820
+ // load is a single visible phase before judging, not a silent stall on the
1821
+ // first test. Both are cached promises, so the judge reuses them after.
1822
+ async warmup() {
1823
+ await Promise.all([vision.get(), classifier.get()]);
1824
+ },
1825
+ async judge(input, cwd) {
1826
+ const entryDir = path.join(paths(cwd).judgments, input.entry.id);
1827
+ await mkdir(entryDir, { recursive: true });
1828
+ try {
1829
+ const description = await visionSemaphore.run(async () => {
1830
+ input.onJudgingStart?.();
1831
+ const fromRegions = await describeChange(input, entryDir);
1832
+ const text = fromRegions ?? await describeScreenshot(input);
1833
+ return text.trim();
1834
+ });
1835
+ const summary = summarizeInterpret(input);
1836
+ const prompt = buildClassifyPrompt(summary, description);
1837
+ const answer = await classifierSemaphore.run(async () => {
1838
+ const c = await classifier.get();
1839
+ return (await c.complete(prompt)).trim();
1840
+ });
1841
+ const label = parseLabel(answer);
1842
+ if (!label) {
1843
+ return {
1844
+ kind: "judged",
1845
+ verdict: input.heuristicVerdict,
1846
+ rationale: `${description}
1847
+ ${answer}`.trim()
1848
+ };
1339
1849
  }
1340
- };
1850
+ const reason = reasonOf(answer, label);
1851
+ const verdict = {
1852
+ label,
1853
+ headline: reason || input.heuristicVerdict.headline,
1854
+ // The headline already carries the classifier's reasoning; keep only
1855
+ // the deterministic region read here so the report doesn't repeat the
1856
+ // reasoning or echo the raw `VERDICT:` line back to the reader.
1857
+ rationale: [description].filter(Boolean),
1858
+ action: ACTION_BY_LABEL[label]
1859
+ };
1860
+ return { kind: "judged", verdict, rationale: answer, confidence: 0.6 };
1861
+ } catch (err) {
1862
+ const error = toError(err);
1863
+ return {
1864
+ kind: "failed",
1865
+ reason: classifyFailure(error),
1866
+ error,
1867
+ fallback: input.heuristicVerdict
1868
+ };
1869
+ }
1341
1870
  }
1342
- return tuple;
1343
- }
1344
- async getTuple(config) {
1345
- const thread = config.configurable?.thread_id;
1346
- if (!thread) return void 0;
1347
- const ns = config.configurable?.checkpoint_ns ?? "";
1348
- const explicitId = getCheckpointId(config);
1349
- if (explicitId) {
1350
- return this.readTuple(thread, ns, explicitId, config);
1351
- }
1352
- const ids = (await this.listCheckpointIds(thread, ns)).sort(
1353
- (a, b) => b.localeCompare(a)
1354
- );
1355
- if (ids.length === 0) return void 0;
1356
- const ckptId = ids[0];
1357
- return this.readTuple(thread, ns, ckptId, {
1358
- configurable: {
1359
- thread_id: thread,
1360
- checkpoint_ns: ns,
1361
- checkpoint_id: ckptId
1362
- }
1363
- });
1364
- }
1365
- async *list(config, options) {
1366
- const filter = options?.filter;
1367
- const before = options?.before;
1368
- let limit = options?.limit;
1369
- const configThread = config.configurable?.thread_id;
1370
- const configNs = config.configurable?.checkpoint_ns;
1371
- const configCkptId = config.configurable?.checkpoint_id;
1372
- const threads = configThread ? [configThread] : await this.listThreads();
1373
- for (const thread of threads) {
1374
- const nsNames = await this.listNamespaces(thread);
1375
- for (const nsName of nsNames) {
1376
- const ns = this.decodeNs(nsName);
1377
- if (configNs !== void 0 && ns !== configNs) continue;
1378
- const ids = (await this.listCheckpointIds(thread, ns)).sort(
1379
- (a, b) => b.localeCompare(a)
1380
- );
1381
- for (const ckptId of ids) {
1382
- if (configCkptId && ckptId !== configCkptId) continue;
1383
- if (before?.configurable?.checkpoint_id && ckptId >= before.configurable.checkpoint_id)
1384
- continue;
1385
- const tuple = await this.readTuple(thread, ns, ckptId, {
1386
- configurable: {
1387
- thread_id: thread,
1388
- checkpoint_ns: ns,
1389
- checkpoint_id: ckptId
1390
- }
1391
- });
1392
- if (!tuple) continue;
1393
- if (filter) {
1394
- const md = tuple.metadata;
1395
- const matches = Object.entries(filter).every(
1396
- ([k, v]) => md?.[k] === v
1397
- );
1398
- if (!matches) continue;
1399
- }
1400
- if (limit !== void 0) {
1401
- if (limit <= 0) return;
1402
- limit -= 1;
1403
- }
1404
- yield tuple;
1405
- }
1406
- }
1407
- }
1408
- }
1409
- async put(config, checkpoint, metadata) {
1410
- const thread = config.configurable?.thread_id;
1411
- if (!thread) {
1412
- throw new Error(
1413
- 'FsCheckpointSaver: missing "thread_id" in configurable. Pass `{ configurable: { thread_id } }` when streaming.'
1414
- );
1415
- }
1416
- const ns = config.configurable?.checkpoint_ns ?? "";
1417
- const parentCheckpointId = config.configurable?.checkpoint_id;
1418
- const prepared = copyCheckpoint(checkpoint);
1419
- const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([
1420
- this.serde.dumpsTyped(prepared),
1421
- this.serde.dumpsTyped(metadata)
1422
- ]);
1423
- await mkdir(this.nsPath(thread, ns), { recursive: true });
1424
- const file = this.ckptFile(thread, ns, checkpoint.id);
1425
- const body = {
1426
- checkpoint: encode(serializedCheckpoint),
1427
- metadata: encode(serializedMetadata),
1428
- parentCheckpointId
1429
- };
1430
- await writeJsonAtomic(file, body);
1431
- return {
1432
- configurable: {
1433
- thread_id: thread,
1434
- checkpoint_ns: ns,
1435
- checkpoint_id: checkpoint.id
1436
- }
1437
- };
1438
- }
1439
- async putWrites(config, writes, taskId) {
1440
- const thread = config.configurable?.thread_id;
1441
- if (!thread) {
1442
- throw new Error(
1443
- 'FsCheckpointSaver: missing "thread_id" in configurable for putWrites.'
1444
- );
1445
- }
1446
- const ns = config.configurable?.checkpoint_ns ?? "";
1447
- const ckptId = config.configurable?.checkpoint_id;
1448
- if (!ckptId) {
1449
- throw new Error(
1450
- 'FsCheckpointSaver: missing "checkpoint_id" in configurable for putWrites.'
1451
- );
1452
- }
1453
- const key = `${thread}|${ns}|${ckptId}`;
1454
- await this.withLock(key, async () => {
1455
- const existing = await readJson2(this.writesFile(thread, ns, ckptId)) ?? {};
1456
- let mutated = false;
1457
- for (let idx = 0; idx < writes.length; idx++) {
1458
- const [channel, value] = writes[idx];
1459
- const writeIdx = WRITES_IDX_MAP[channel] ?? idx;
1460
- const innerKey = `${taskId},${writeIdx}`;
1461
- if (writeIdx >= 0 && innerKey in existing) continue;
1462
- const [, serialized] = await this.serde.dumpsTyped(value);
1463
- existing[innerKey] = [taskId, channel, encode(serialized)];
1464
- mutated = true;
1465
- }
1466
- if (!mutated) return;
1467
- await mkdir(this.nsPath(thread, ns), { recursive: true });
1468
- await writeJsonAtomic(this.writesFile(thread, ns, ckptId), existing);
1469
- });
1470
- }
1471
- async deleteThread(threadId) {
1472
- await rm(this.threadDir(threadId), { recursive: true, force: true });
1473
- }
1474
- };
1475
- var PREVIEW_WIDTH = 320;
1476
- function escapeCell(s) {
1477
- return s.replace(/\n/g, " ");
1478
- }
1479
- function toBlazediffRel(cwd, abs) {
1480
- if (!abs) return void 0;
1481
- const root = paths(cwd).root;
1482
- const rel = path.isAbsolute(abs) ? path.relative(root, abs) : path.relative(paths(cwd).root, path.join(cwd, abs));
1483
- return rel.split(path.sep).join("/");
1484
- }
1485
- function img(src, alt) {
1486
- return `<img src="${src}" width="${PREVIEW_WIDTH}" alt="${alt}">`;
1487
- }
1488
- function baselineCell(r, cwd) {
1489
- const rel = toBlazediffRel(cwd, r.baselinePath) ?? `baselines/${r.id}.png`;
1490
- return img(rel, `${r.id} baseline`);
1491
- }
1492
- function actualCell(r, cwd) {
1493
- const actual = toBlazediffRel(cwd, r.actualPath);
1494
- return actual ? img(actual, `${r.id} actual`) : "-";
1495
- }
1496
- function diffCell(r, cwd) {
1497
- const diff = toBlazediffRel(cwd, r.diffPath);
1498
- return diff ? img(diff, `${r.id} diff`) : "-";
1499
- }
1500
- function verdictCell(r) {
1501
- if (r.status === "missing-baseline") {
1502
- return `missing-baseline - ${r.message ?? "baseline missing"}`;
1503
- }
1504
- if (r.status === "stale-baseline") {
1505
- return `stale-baseline - ${r.message ?? "manifest entry edited without re-capturing"}`;
1506
- }
1507
- if (r.status === "needs-judgment") {
1508
- return `needs-judgment - see judgments/${r.id}/`;
1509
- }
1510
- if (!r.verdict) {
1511
- return r.message ?? r.status;
1512
- }
1513
- return `${r.verdict.label} - ${r.verdict.headline} -> ${r.verdict.action}`;
1514
- }
1515
- function renderRow(r, cwd) {
1516
- return `| ${r.id} | ${escapeCell(baselineCell(r, cwd))} | ${escapeCell(actualCell(r, cwd))} | ${escapeCell(diffCell(r, cwd))} | ${escapeCell(verdictCell(r))} |`;
1517
- }
1518
- function headerLine(report) {
1519
- const { passed, failed, pendingJudgments, totalEntries } = report;
1520
- const parts = [`${passed}/${totalEntries} passed`];
1521
- if (failed > 0) parts.push(`${failed} failed`);
1522
- if (pendingJudgments > 0) parts.push(`${pendingJudgments} pending judgment`);
1523
- return parts.length > 1 ? `${parts[0]} (${parts.slice(1).join(", ")})` : parts[0];
1871
+ };
1524
1872
  }
1525
- function renderSummary(report, cwd = process.cwd()) {
1526
- const nonPass = report.results.filter((r) => r.status !== "pass");
1527
- const lines = [
1528
- `# blazediff check - ${report.createdAt}`,
1529
- "",
1530
- headerLine(report),
1531
- ""
1532
- ];
1533
- if (nonPass.length === 0) {
1534
- lines.push("All entries passed.");
1535
- return `${lines.join("\n")}
1536
- `;
1873
+ var localJudge = createLocalJudge();
1874
+
1875
+ // src/judge/none.ts
1876
+ var noneJudge = {
1877
+ name: "none",
1878
+ async judge(input) {
1879
+ return { kind: "judged", verdict: input.heuristicVerdict };
1537
1880
  }
1538
- lines.push("| id | baseline | actual | diff | verdict |");
1539
- lines.push("| --- | --- | --- | --- | --- |");
1540
- for (const r of nonPass) lines.push(renderRow(r, cwd));
1541
- return `${lines.join("\n")}
1542
- `;
1543
- }
1544
- async function writeSummaryMarkdown(report, cwd = process.cwd()) {
1545
- const file = paths(cwd).summary;
1881
+ };
1882
+ async function writeReport(report, cwd = process.cwd()) {
1883
+ const file = paths(cwd).report;
1546
1884
  await mkdir(path.dirname(file), { recursive: true });
1547
- await writeFile(file, renderSummary(report, cwd), "utf8");
1885
+ await writeFile(file, `${JSON.stringify(report, null, 2)}
1886
+ `, "utf8");
1548
1887
  return file;
1549
1888
  }
1889
+ async function readReport(cwd = process.cwd()) {
1890
+ return readJsonOrNull(paths(cwd).report);
1891
+ }
1550
1892
 
1551
1893
  // src/judge/apply.ts
1552
1894
  var VALID_LABELS = [
@@ -1584,21 +1926,6 @@ function parseVerdict(raw) {
1584
1926
  confidence: typeof r.confidence === "number" ? r.confidence : void 0
1585
1927
  };
1586
1928
  }
1587
- async function fileExists2(p) {
1588
- try {
1589
- await access(p);
1590
- return true;
1591
- } catch {
1592
- return false;
1593
- }
1594
- }
1595
- async function readJsonOrNull(file) {
1596
- try {
1597
- return JSON.parse(await readFile(file, "utf8"));
1598
- } catch {
1599
- return null;
1600
- }
1601
- }
1602
1929
  async function readJudgmentDirs(root) {
1603
1930
  let names;
1604
1931
  try {
@@ -1696,7 +2023,7 @@ async function reconstructFromDisk(cwd, dirs) {
1696
2023
  pendingJudgments,
1697
2024
  results
1698
2025
  };
1699
- await writeSummaryMarkdown(report, cwd);
2026
+ await writeReport(report, cwd);
1700
2027
  return report;
1701
2028
  }
1702
2029
  async function hasCheckpoint(cwd, threadId) {
@@ -1708,9 +2035,8 @@ async function hasCheckpoint(cwd, threadId) {
1708
2035
  return false;
1709
2036
  }
1710
2037
  }
1711
- async function applyJudgments(opts = process.cwd()) {
1712
- const options = typeof opts === "string" ? { cwd: opts } : opts;
1713
- const cwd = options.cwd ?? process.cwd();
2038
+ async function applyJudgments(opts = {}) {
2039
+ const cwd = opts.cwd ?? process.cwd();
1714
2040
  const manifest = await loadManifest(cwd);
1715
2041
  if (!manifest) {
1716
2042
  throw new Error(
@@ -1744,10 +2070,9 @@ async function applyJudgments(opts = process.cwd()) {
1744
2070
  cwd,
1745
2071
  verdicts,
1746
2072
  threadId,
1747
- onEvent: options.onEvent,
1748
- junitPath: options.junitPath
2073
+ onEvent: opts.onEvent,
2074
+ junitPath: opts.junitPath
1749
2075
  });
1750
- await new FsCheckpointSaver(paths(cwd).checkpoints).deleteThread(threadId).catch(() => void 0);
1751
2076
  return { report, applied, missing, invalid };
1752
2077
  }
1753
2078
  var HOST_INSTRUCTIONS = [
@@ -1757,7 +2082,7 @@ var HOST_INSTRUCTIONS = [
1757
2082
  "Decide whether the change is a regression, an intentional UI change, or rendering noise.",
1758
2083
  "Write your decision to `verdict.json` (next to this `request.json`) with shape:",
1759
2084
  ' { "id": string, "verdict": { "label": "regression-likely" | "intentional-likely" | "noise-likely", "headline": string, "rationale": string[], "action": "investigate" | "rewrite-if-intended" | "ignore-or-rewrite" }, "rationale": string, "confidence": number }',
1760
- "Then re-run `blazediff-agent check --apply-judgments --json` to regenerate summary.md."
2085
+ "Then re-run `blazediff-agent check --apply-judgments --json` to regenerate report.json."
1761
2086
  ].join("\n");
1762
2087
  function relTo(cwd, abs) {
1763
2088
  if (!abs) return void 0;
@@ -1765,24 +2090,10 @@ function relTo(cwd, abs) {
1765
2090
  }
1766
2091
  function signatureOf(r) {
1767
2092
  const pct = typeof r.diffPercentage === "number" ? r.diffPercentage.toFixed(4) : "?";
1768
- const regions = r.regions?.length ?? 0;
1769
2093
  const severity = r.severity ?? "?";
1770
- return `${r.status}|diff:${pct}|regions:${regions}|severity:${severity}`;
1771
- }
1772
- async function fileExists3(p) {
1773
- try {
1774
- await access(p);
1775
- return true;
1776
- } catch {
1777
- return false;
1778
- }
1779
- }
1780
- async function readJsonOrNull2(file) {
1781
- try {
1782
- return JSON.parse(await readFile(file, "utf8"));
1783
- } catch {
1784
- return null;
1785
- }
2094
+ const regions = (r.regions ?? []).map((reg) => `${reg.changeType}:${reg.pixelCount}`).sort().join(",");
2095
+ const regionsKey = regions ? `[${regions}]` : "0";
2096
+ return `${r.status}|diff:${pct}|regions:${regionsKey}|severity:${severity}`;
1786
2097
  }
1787
2098
  function entryById(manifest, id) {
1788
2099
  return manifest.entries.find((e) => e.id === id);
@@ -1831,8 +2142,8 @@ async function discoverTiles(dir) {
1831
2142
  const locatorAbs = path.join(dir, "locator.png");
1832
2143
  const tilesAbs = path.join(dir, "regions.png");
1833
2144
  const [locator, tiles] = await Promise.all([
1834
- fileExists3(locatorAbs),
1835
- fileExists3(tilesAbs)
2145
+ fileExists2(locatorAbs),
2146
+ fileExists2(tilesAbs)
1836
2147
  ]);
1837
2148
  return {
1838
2149
  locatorPath: locator ? "locator.png" : void 0,
@@ -1849,7 +2160,7 @@ async function writeJudgments(opts) {
1849
2160
  opts.report.results.map(async (result) => {
1850
2161
  const dir = path.join(root, result.id);
1851
2162
  if (result.status === "pass") {
1852
- if (await fileExists3(dir))
2163
+ if (await fileExists2(dir))
1853
2164
  await rm(dir, { recursive: true, force: true });
1854
2165
  return;
1855
2166
  }
@@ -1861,9 +2172,9 @@ async function writeJudgments(opts) {
1861
2172
  const requestFile = path.join(dir, "request.json");
1862
2173
  const verdictFile = path.join(dir, "verdict.json");
1863
2174
  const [prior, priorVerdict] = await Promise.all([
1864
- readJsonOrNull2(requestFile),
1865
- fileExists3(verdictFile).then(
1866
- (exists) => exists ? readJsonOrNull2(verdictFile) : null
2175
+ readJsonOrNull(requestFile),
2176
+ fileExists2(verdictFile).then(
2177
+ (exists) => exists ? readJsonOrNull(verdictFile) : null
1867
2178
  )
1868
2179
  ]);
1869
2180
  const signatureMatches = prior !== null && prior.signature === request.signature;
@@ -1873,68 +2184,356 @@ async function writeJudgments(opts) {
1873
2184
  `,
1874
2185
  "utf8"
1875
2186
  );
1876
- if (priorVerdict && signatureMatches) {
1877
- return;
2187
+ if (priorVerdict && signatureMatches) {
2188
+ return;
2189
+ }
2190
+ const auto = autoVerdict(result);
2191
+ if (auto) {
2192
+ await writeFile(
2193
+ verdictFile,
2194
+ `${JSON.stringify(auto, null, 2)}
2195
+ `,
2196
+ "utf8"
2197
+ );
2198
+ } else if (priorVerdict && !signatureMatches) {
2199
+ await rm(verdictFile, { force: true });
2200
+ }
2201
+ })
2202
+ );
2203
+ let entries;
2204
+ try {
2205
+ entries = await readdir(root);
2206
+ } catch {
2207
+ return;
2208
+ }
2209
+ await Promise.all(
2210
+ entries.filter((name) => !knownIds.has(name)).map(
2211
+ (name) => rm(path.join(root, name), { recursive: true, force: true })
2212
+ )
2213
+ );
2214
+ }
2215
+
2216
+ // src/judge/index.ts
2217
+ function resolveJudge(backend) {
2218
+ switch (backend) {
2219
+ case "none":
2220
+ return noneJudge;
2221
+ case "host":
2222
+ return codingAgentHostJudge;
2223
+ case "local":
2224
+ return localJudge;
2225
+ }
2226
+ }
2227
+ function escapeXml(value) {
2228
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2229
+ }
2230
+ async function writeJunit(report, destPath) {
2231
+ await mkdir(path.dirname(destPath), { recursive: true });
2232
+ const cases = report.results.map((r) => {
2233
+ if (r.status === "pass") {
2234
+ return ` <testcase classname="blazediff" name="${escapeXml(r.id)}"/>`;
2235
+ }
2236
+ const message = r.message ?? r.status;
2237
+ return ` <testcase classname="blazediff" name="${escapeXml(r.id)}">
2238
+ <failure message="${escapeXml(message)}" type="${escapeXml(r.status)}">${escapeXml(message)}</failure>
2239
+ </testcase>`;
2240
+ });
2241
+ const failures = report.totalEntries - report.passed;
2242
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
2243
+ <testsuites>
2244
+ <testsuite name="blazediff" tests="${report.totalEntries}" failures="${failures}">
2245
+ ${cases.join("\n")}
2246
+ </testsuite>
2247
+ </testsuites>
2248
+ `;
2249
+ await writeFile(destPath, xml, "utf8");
2250
+ return destPath;
2251
+ }
2252
+ var ROOT_NS_SENTINEL = "_root";
2253
+ function nsDir(ns) {
2254
+ return ns === "" ? ROOT_NS_SENTINEL : ns;
2255
+ }
2256
+ function encode(buf) {
2257
+ return Buffer.from(buf).toString("base64");
2258
+ }
2259
+ function decode(s) {
2260
+ return Buffer.from(s, "base64");
2261
+ }
2262
+ async function readJson(file) {
2263
+ try {
2264
+ const raw = await readFile(file, "utf8");
2265
+ return JSON.parse(raw);
2266
+ } catch (err) {
2267
+ if (err.code === "ENOENT") return void 0;
2268
+ throw err;
2269
+ }
2270
+ }
2271
+ async function writeJsonAtomic(file, value) {
2272
+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
2273
+ await writeFile(tmp, JSON.stringify(value), "utf8");
2274
+ await rename(tmp, file);
2275
+ }
2276
+ var FsCheckpointSaver = class extends BaseCheckpointSaver {
2277
+ constructor(root, serde) {
2278
+ super(serde);
2279
+ this.locks = /* @__PURE__ */ new Map();
2280
+ this.root = root;
2281
+ }
2282
+ threadDir(thread) {
2283
+ return path.join(this.root, thread);
2284
+ }
2285
+ nsPath(thread, ns) {
2286
+ return path.join(this.threadDir(thread), nsDir(ns));
2287
+ }
2288
+ ckptFile(thread, ns, id) {
2289
+ return path.join(this.nsPath(thread, ns), `${id}.ckpt.json`);
2290
+ }
2291
+ writesFile(thread, ns, id) {
2292
+ return path.join(this.nsPath(thread, ns), `${id}.writes.json`);
2293
+ }
2294
+ async withLock(key, fn) {
2295
+ const prev = this.locks.get(key) ?? Promise.resolve();
2296
+ const next = prev.then(fn, fn);
2297
+ this.locks.set(key, next);
2298
+ try {
2299
+ return await next;
2300
+ } finally {
2301
+ if (this.locks.get(key) === next) this.locks.delete(key);
2302
+ }
2303
+ }
2304
+ async listCheckpointIds(thread, ns) {
2305
+ try {
2306
+ const names = await readdir(this.nsPath(thread, ns));
2307
+ const suffix = ".ckpt.json";
2308
+ return names.filter((n) => n.endsWith(suffix)).map((n) => n.slice(0, -suffix.length));
2309
+ } catch (err) {
2310
+ if (err.code === "ENOENT") return [];
2311
+ throw err;
2312
+ }
2313
+ }
2314
+ async listNamespaces(thread) {
2315
+ try {
2316
+ return await readdir(this.threadDir(thread));
2317
+ } catch (err) {
2318
+ if (err.code === "ENOENT") return [];
2319
+ throw err;
2320
+ }
2321
+ }
2322
+ async listThreads() {
2323
+ try {
2324
+ return await readdir(this.root);
2325
+ } catch (err) {
2326
+ if (err.code === "ENOENT") return [];
2327
+ throw err;
2328
+ }
2329
+ }
2330
+ decodeNs(nsDirName) {
2331
+ return nsDirName === ROOT_NS_SENTINEL ? "" : nsDirName;
2332
+ }
2333
+ async loadPendingWrites(thread, ns, ckptId) {
2334
+ const data = await readJson(
2335
+ this.writesFile(thread, ns, ckptId)
2336
+ );
2337
+ if (!data) return [];
2338
+ const out = [];
2339
+ for (const [taskId, channel, serialized] of Object.values(data)) {
2340
+ const value = await this.serde.loadsTyped("json", decode(serialized));
2341
+ out.push([taskId, channel, value]);
2342
+ }
2343
+ return out;
2344
+ }
2345
+ async migratePendingSends(checkpoint, thread, ns, parentCheckpointId) {
2346
+ const data = await readJson(
2347
+ this.writesFile(thread, ns, parentCheckpointId)
2348
+ );
2349
+ const pendingSends = data ? await Promise.all(
2350
+ Object.values(data).filter(([, channel]) => channel === TASKS).map(
2351
+ ([, , serialized]) => this.serde.loadsTyped("json", decode(serialized))
2352
+ )
2353
+ ) : [];
2354
+ const m = checkpoint;
2355
+ m.channel_values ?? (m.channel_values = {});
2356
+ m.channel_values[TASKS] = pendingSends;
2357
+ m.channel_versions ?? (m.channel_versions = {});
2358
+ const versions = Object.values(m.channel_versions);
2359
+ m.channel_versions[TASKS] = versions.length > 0 ? maxChannelVersion(...versions) : this.getNextVersion(void 0);
2360
+ }
2361
+ async readTuple(thread, ns, ckptId, config) {
2362
+ const data = await readJson(this.ckptFile(thread, ns, ckptId));
2363
+ if (!data) return void 0;
2364
+ const checkpoint = await this.serde.loadsTyped(
2365
+ "json",
2366
+ decode(data.checkpoint)
2367
+ );
2368
+ const metadata = await this.serde.loadsTyped(
2369
+ "json",
2370
+ decode(data.metadata)
2371
+ );
2372
+ if (checkpoint.v < 4 && data.parentCheckpointId !== void 0) {
2373
+ await this.migratePendingSends(
2374
+ checkpoint,
2375
+ thread,
2376
+ ns,
2377
+ data.parentCheckpointId
2378
+ );
2379
+ }
2380
+ const pendingWrites = await this.loadPendingWrites(thread, ns, ckptId);
2381
+ const tuple = {
2382
+ config,
2383
+ checkpoint,
2384
+ metadata,
2385
+ pendingWrites
2386
+ };
2387
+ if (data.parentCheckpointId !== void 0) {
2388
+ tuple.parentConfig = {
2389
+ configurable: {
2390
+ thread_id: thread,
2391
+ checkpoint_ns: ns,
2392
+ checkpoint_id: data.parentCheckpointId
2393
+ }
2394
+ };
2395
+ }
2396
+ return tuple;
2397
+ }
2398
+ async getTuple(config) {
2399
+ const thread = config.configurable?.thread_id;
2400
+ if (!thread) return void 0;
2401
+ const ns = config.configurable?.checkpoint_ns ?? "";
2402
+ const explicitId = getCheckpointId(config);
2403
+ if (explicitId) {
2404
+ return this.readTuple(thread, ns, explicitId, config);
2405
+ }
2406
+ const ids = (await this.listCheckpointIds(thread, ns)).sort(
2407
+ (a, b) => b.localeCompare(a)
2408
+ );
2409
+ if (ids.length === 0) return void 0;
2410
+ const ckptId = ids[0];
2411
+ return this.readTuple(thread, ns, ckptId, {
2412
+ configurable: {
2413
+ thread_id: thread,
2414
+ checkpoint_ns: ns,
2415
+ checkpoint_id: ckptId
1878
2416
  }
1879
- const auto = autoVerdict(result);
1880
- if (auto) {
1881
- await writeFile(
1882
- verdictFile,
1883
- `${JSON.stringify(auto, null, 2)}
1884
- `,
1885
- "utf8"
2417
+ });
2418
+ }
2419
+ async *list(config, options) {
2420
+ const filter = options?.filter;
2421
+ const before = options?.before;
2422
+ let limit = options?.limit;
2423
+ const configThread = config.configurable?.thread_id;
2424
+ const configNs = config.configurable?.checkpoint_ns;
2425
+ const configCkptId = config.configurable?.checkpoint_id;
2426
+ const threads = configThread ? [configThread] : await this.listThreads();
2427
+ for (const thread of threads) {
2428
+ const nsNames = await this.listNamespaces(thread);
2429
+ for (const nsName of nsNames) {
2430
+ const ns = this.decodeNs(nsName);
2431
+ if (configNs !== void 0 && ns !== configNs) continue;
2432
+ const ids = (await this.listCheckpointIds(thread, ns)).sort(
2433
+ (a, b) => b.localeCompare(a)
1886
2434
  );
1887
- } else if (priorVerdict && !signatureMatches) {
1888
- await rm(verdictFile, { force: true });
2435
+ for (const ckptId of ids) {
2436
+ if (configCkptId && ckptId !== configCkptId) continue;
2437
+ if (before?.configurable?.checkpoint_id && ckptId >= before.configurable.checkpoint_id)
2438
+ continue;
2439
+ const tuple = await this.readTuple(thread, ns, ckptId, {
2440
+ configurable: {
2441
+ thread_id: thread,
2442
+ checkpoint_ns: ns,
2443
+ checkpoint_id: ckptId
2444
+ }
2445
+ });
2446
+ if (!tuple) continue;
2447
+ if (filter) {
2448
+ const md = tuple.metadata;
2449
+ const matches = Object.entries(filter).every(
2450
+ ([k, v]) => md?.[k] === v
2451
+ );
2452
+ if (!matches) continue;
2453
+ }
2454
+ if (limit !== void 0) {
2455
+ if (limit <= 0) return;
2456
+ limit -= 1;
2457
+ }
2458
+ yield tuple;
2459
+ }
1889
2460
  }
1890
- })
1891
- );
1892
- let entries;
1893
- try {
1894
- entries = await readdir(root);
1895
- } catch {
1896
- return;
2461
+ }
1897
2462
  }
1898
- await Promise.all(
1899
- entries.filter((name) => !knownIds.has(name)).map(
1900
- (name) => rm(path.join(root, name), { recursive: true, force: true })
1901
- )
1902
- );
1903
- }
1904
-
1905
- // src/judge/index.ts
1906
- function resolveJudge(backend) {
1907
- switch (backend) {
1908
- case "none":
1909
- return noneJudge;
1910
- case "host":
1911
- return hostHarnessJudge;
2463
+ async put(config, checkpoint, metadata) {
2464
+ const thread = config.configurable?.thread_id;
2465
+ if (!thread) {
2466
+ throw new Error(
2467
+ 'FsCheckpointSaver: missing "thread_id" in configurable. Pass `{ configurable: { thread_id } }` when streaming.'
2468
+ );
2469
+ }
2470
+ const ns = config.configurable?.checkpoint_ns ?? "";
2471
+ const parentCheckpointId = config.configurable?.checkpoint_id;
2472
+ const prepared = copyCheckpoint(checkpoint);
2473
+ const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([
2474
+ this.serde.dumpsTyped(prepared),
2475
+ this.serde.dumpsTyped(metadata)
2476
+ ]);
2477
+ await mkdir(this.nsPath(thread, ns), { recursive: true });
2478
+ const file = this.ckptFile(thread, ns, checkpoint.id);
2479
+ const body = {
2480
+ checkpoint: encode(serializedCheckpoint),
2481
+ metadata: encode(serializedMetadata),
2482
+ parentCheckpointId
2483
+ };
2484
+ await writeJsonAtomic(file, body);
2485
+ return {
2486
+ configurable: {
2487
+ thread_id: thread,
2488
+ checkpoint_ns: ns,
2489
+ checkpoint_id: checkpoint.id
2490
+ }
2491
+ };
1912
2492
  }
1913
- }
1914
- function escapeXml(value) {
1915
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1916
- }
1917
- async function writeJunit(report, destPath) {
1918
- await mkdir(path.dirname(destPath), { recursive: true });
1919
- const cases = report.results.map((r) => {
1920
- if (r.status === "pass") {
1921
- return ` <testcase classname="blazediff" name="${escapeXml(r.id)}"/>`;
2493
+ async putWrites(config, writes, taskId) {
2494
+ const thread = config.configurable?.thread_id;
2495
+ if (!thread) {
2496
+ throw new Error(
2497
+ 'FsCheckpointSaver: missing "thread_id" in configurable for putWrites.'
2498
+ );
1922
2499
  }
1923
- const message = r.message ?? r.status;
1924
- return ` <testcase classname="blazediff" name="${escapeXml(r.id)}">
1925
- <failure message="${escapeXml(message)}" type="${escapeXml(r.status)}">${escapeXml(message)}</failure>
1926
- </testcase>`;
1927
- });
1928
- const failures = report.totalEntries - report.passed;
1929
- const xml = `<?xml version="1.0" encoding="UTF-8"?>
1930
- <testsuites>
1931
- <testsuite name="blazediff" tests="${report.totalEntries}" failures="${failures}">
1932
- ${cases.join("\n")}
1933
- </testsuite>
1934
- </testsuites>
1935
- `;
1936
- await writeFile(destPath, xml, "utf8");
1937
- return destPath;
2500
+ const ns = config.configurable?.checkpoint_ns ?? "";
2501
+ const ckptId = config.configurable?.checkpoint_id;
2502
+ if (!ckptId) {
2503
+ throw new Error(
2504
+ 'FsCheckpointSaver: missing "checkpoint_id" in configurable for putWrites.'
2505
+ );
2506
+ }
2507
+ const key = `${thread}|${ns}|${ckptId}`;
2508
+ await this.withLock(key, async () => {
2509
+ const existing = await readJson(this.writesFile(thread, ns, ckptId)) ?? {};
2510
+ let mutated = false;
2511
+ for (let idx = 0; idx < writes.length; idx++) {
2512
+ const [channel, value] = writes[idx];
2513
+ const writeIdx = WRITES_IDX_MAP[channel] ?? idx;
2514
+ const innerKey = `${taskId},${writeIdx}`;
2515
+ if (writeIdx >= 0 && innerKey in existing) continue;
2516
+ const [, serialized] = await this.serde.dumpsTyped(value);
2517
+ existing[innerKey] = [taskId, channel, encode(serialized)];
2518
+ mutated = true;
2519
+ }
2520
+ if (!mutated) return;
2521
+ await mkdir(this.nsPath(thread, ns), { recursive: true });
2522
+ await writeJsonAtomic(this.writesFile(thread, ns, ckptId), existing);
2523
+ });
2524
+ }
2525
+ async deleteThread(threadId) {
2526
+ await rm(this.threadDir(threadId), { recursive: true, force: true });
2527
+ }
2528
+ };
2529
+
2530
+ // src/graph/events.ts
2531
+ var sink;
2532
+ function setEventSink(fn) {
2533
+ sink = fn;
2534
+ }
2535
+ function emitEvent(event) {
2536
+ sink?.(event);
1938
2537
  }
1939
2538
 
1940
2539
  // src/graph/nodes/results.ts
@@ -1989,6 +2588,8 @@ function failResult(entry, outcome, actualPath, baselinePath, verdict) {
1989
2588
  diffPercentage: outcome.diffPercentage,
1990
2589
  severity: outcome.interpretation?.severity,
1991
2590
  regions: outcome.interpretation?.regions?.map(narrowRegion),
2591
+ width: outcome.interpretation?.width,
2592
+ height: outcome.interpretation?.height,
1992
2593
  verdict,
1993
2594
  diffPath: outcome.diffPath,
1994
2595
  baselinePath,
@@ -2097,6 +2698,10 @@ function makeCaptureNode(semaphore) {
2097
2698
  );
2098
2699
  }
2099
2700
  }
2701
+ for (const item of items) {
2702
+ if (item.output.captureOutputPath)
2703
+ emitEvent({ type: "captured", entryId: item.entry.id });
2704
+ }
2100
2705
  return { captured: items };
2101
2706
  } catch (err) {
2102
2707
  if (err instanceof HarnessError) {
@@ -2325,6 +2930,7 @@ async function judgeNode(state) {
2325
2930
  throw new Error("judgeNode: entry, options, or diff missing");
2326
2931
  }
2327
2932
  if (diff.skipResult) {
2933
+ emitEvent({ type: "result", result: diff.skipResult });
2328
2934
  return { results: [diff.skipResult] };
2329
2935
  }
2330
2936
  const outcome = diff.outcome;
@@ -2334,7 +2940,9 @@ async function judgeNode(state) {
2334
2940
  throw new Error("judgeNode: diff outputs missing");
2335
2941
  }
2336
2942
  if (outcome.match) {
2337
- return { results: [passResult(entry, baselinePath, captureOutputPath)] };
2943
+ const r = passResult(entry, baselinePath, captureOutputPath);
2944
+ emitEvent({ type: "result", result: r });
2945
+ return { results: [r] };
2338
2946
  }
2339
2947
  const verdict = deriveVerdict({
2340
2948
  reason: outcome.reason,
@@ -2342,48 +2950,62 @@ async function judgeNode(state) {
2342
2950
  diffCount: outcome.diffCount,
2343
2951
  diffPercentage: outcome.diffPercentage
2344
2952
  });
2345
- let result = failResult(
2953
+ const initial = failResult(
2346
2954
  entry,
2347
2955
  outcome,
2348
2956
  captureOutputPath,
2349
2957
  baselinePath,
2350
2958
  verdict
2351
2959
  );
2352
- if (result.baselinePath && result.actualPath) {
2353
- const judge = resolveJudge(options.judge);
2354
- const output = await judge.judge(
2355
- {
2356
- entry,
2357
- baselinePath: result.baselinePath,
2358
- actualPath: result.actualPath,
2359
- diffPath: result.diffPath,
2360
- regions: result.regions,
2361
- diffPercentage: result.diffPercentage,
2362
- severity: result.severity,
2363
- heuristicVerdict: result.verdict ?? verdict
2364
- },
2365
- options.cwd
2960
+ if (!initial.baselinePath || !initial.actualPath) {
2961
+ emitEvent({ type: "result", result: initial });
2962
+ return { results: [initial] };
2963
+ }
2964
+ const judge = resolveJudge(options.judge);
2965
+ const output = await judge.judge(
2966
+ {
2967
+ entry,
2968
+ baselinePath: initial.baselinePath,
2969
+ actualPath: initial.actualPath,
2970
+ diffPath: initial.diffPath,
2971
+ regions: initial.regions,
2972
+ diffPercentage: initial.diffPercentage,
2973
+ severity: initial.severity,
2974
+ heuristicVerdict: initial.verdict ?? verdict,
2975
+ onJudgingStart: options.judge !== "none" ? () => emitEvent({ type: "judging", entryId: entry.id, url: entry.url }) : void 0
2976
+ },
2977
+ options.cwd
2978
+ );
2979
+ let final;
2980
+ if (output.kind === "judged") {
2981
+ final = { ...initial, verdict: output.verdict };
2982
+ } else if (output.kind === "failed") {
2983
+ console.warn(
2984
+ `[blazediff] judge "${judge.name}" failed for ${entry.id} (${output.reason}): ${output.error.message}`
2366
2985
  );
2367
- if (output.kind === "judged") {
2368
- result = { ...result, verdict: output.verdict };
2369
- } else {
2370
- const pending = {
2371
- ...result,
2372
- status: "needs-judgment",
2373
- message: `awaiting judgment in ${output.requestPath}`
2374
- };
2375
- const resumed = interruptForJudgment({
2376
- kind: "host-judgment-required",
2377
- entryId: entry.id,
2378
- url: entry.url,
2379
- requestPath: output.requestPath,
2380
- signature: signatureOf(result),
2381
- pendingResult: pending
2382
- });
2383
- result = resumed ? { ...result, verdict: resumed } : pending;
2384
- }
2986
+ final = {
2987
+ ...initial,
2988
+ verdict: output.fallback,
2989
+ message: `${initial.message ?? ""}${initial.message ? " \u2014 " : ""}judge failed (${output.reason}): ${output.error.message}`
2990
+ };
2991
+ } else {
2992
+ const pending = {
2993
+ ...initial,
2994
+ status: "needs-judgment",
2995
+ message: `awaiting judgment in ${output.requestPath}`
2996
+ };
2997
+ const resumed = interruptForJudgment({
2998
+ kind: "host-judgment-required",
2999
+ entryId: entry.id,
3000
+ url: entry.url,
3001
+ requestPath: output.requestPath,
3002
+ signature: signatureOf(initial),
3003
+ pendingResult: pending
3004
+ });
3005
+ final = resumed ? { ...initial, verdict: resumed } : pending;
2385
3006
  }
2386
- return { results: [result] };
3007
+ emitEvent({ type: "result", result: final });
3008
+ return { results: [final] };
2387
3009
  }
2388
3010
 
2389
3011
  // src/graph/nodes/load.ts
@@ -2399,75 +3021,46 @@ async function loadNode(state) {
2399
3021
  }
2400
3022
  return { entries: manifest.entries, manifest };
2401
3023
  }
2402
- var resultsChannel = Annotation({
3024
+ var latest = () => Annotation({
3025
+ reducer: (acc, next) => next ?? acc,
3026
+ default: () => void 0
3027
+ });
3028
+ var appendList = () => Annotation({
2403
3029
  reducer: (acc, next) => [...acc, ...next],
2404
3030
  default: () => []
2405
3031
  });
2406
- var capturedChannel = Annotation({
2407
- reducer: (acc, next) => [...acc, ...next],
3032
+ var replaceList = () => Annotation({
3033
+ reducer: (acc, next) => next ?? acc,
2408
3034
  default: () => []
2409
3035
  });
3036
+ var resultsChannel = appendList();
3037
+ var capturedChannel = appendList();
2410
3038
  var CaptureState = Annotation.Root({
2411
- entry: Annotation({
2412
- reducer: (_, next) => next,
2413
- default: () => void 0
2414
- }),
3039
+ entry: latest(),
2415
3040
  children: Annotation({
2416
3041
  reducer: (_, next) => next,
2417
3042
  default: () => []
2418
3043
  }),
2419
- options: Annotation({
2420
- reducer: (acc, next) => next ?? acc,
2421
- default: () => void 0
2422
- }),
3044
+ options: latest(),
2423
3045
  captured: capturedChannel
2424
3046
  });
2425
3047
  var BranchState = Annotation.Root({
2426
- entry: Annotation({
2427
- reducer: (_, next) => next,
2428
- default: () => void 0
2429
- }),
2430
- options: Annotation({
2431
- reducer: (acc, next) => next ?? acc,
2432
- default: () => void 0
2433
- }),
2434
- captureOutput: Annotation({
2435
- reducer: (_, next) => next,
2436
- default: () => void 0
2437
- }),
2438
- diffOutput: Annotation({
2439
- reducer: (_, next) => next,
2440
- default: () => void 0
2441
- }),
3048
+ entry: latest(),
3049
+ options: latest(),
3050
+ captureOutput: latest(),
3051
+ diffOutput: latest(),
2442
3052
  results: resultsChannel
2443
3053
  });
2444
3054
  var GraphState = Annotation.Root({
2445
- options: Annotation({
2446
- reducer: (acc, next) => next ?? acc,
2447
- default: () => void 0
2448
- }),
2449
- entries: Annotation({
2450
- reducer: (acc, next) => next ?? acc,
2451
- default: () => []
2452
- }),
3055
+ options: latest(),
3056
+ entries: replaceList(),
2453
3057
  captured: capturedChannel,
2454
3058
  results: resultsChannel,
2455
- manifest: Annotation({
2456
- reducer: (acc, next) => next ?? acc,
2457
- default: () => void 0
2458
- }),
2459
- report: Annotation({
2460
- reducer: (acc, next) => next ?? acc,
2461
- default: () => void 0
2462
- })
3059
+ manifest: latest(),
3060
+ report: latest()
2463
3061
  });
2464
3062
 
2465
3063
  // src/graph/index.ts
2466
- function cpuParallelism() {
2467
- const cores = typeof availableParallelism === "function" ? availableParallelism() : cpus().length;
2468
- if (!cores || !Number.isFinite(cores)) return 2;
2469
- return Math.max(2, cores);
2470
- }
2471
3064
  function threadIdFor(cwd) {
2472
3065
  return createHash("sha1").update(paths(cwd).manifest).digest("hex").slice(0, 16);
2473
3066
  }
@@ -2477,7 +3070,8 @@ function buildCaptureGraph(captureSemaphore) {
2477
3070
  function buildBranchGraph(diffSemaphore) {
2478
3071
  return new StateGraph(BranchState).addNode("diff", makeDiffNode(diffSemaphore)).addNode("judge", judgeNode).addEdge(START, "diff").addEdge("diff", "judge").addEdge("judge", END).compile();
2479
3072
  }
2480
- function dispatchNode() {
3073
+ async function dispatchNode(state) {
3074
+ if (state.options) await resolveJudge(state.options.judge).warmup?.();
2481
3075
  return {};
2482
3076
  }
2483
3077
  function buildGraph(captureSemaphore, diffSemaphore, checkpointer) {
@@ -2530,10 +3124,7 @@ async function streamGraph(graph, input, threadId, onEvent) {
2530
3124
  const part = partial;
2531
3125
  if (!part) continue;
2532
3126
  if (part.results) {
2533
- for (const r of part.results) {
2534
- collect.results.push(r);
2535
- onEvent?.({ type: "result", result: r });
2536
- }
3127
+ for (const r of part.results) collect.results.push(r);
2537
3128
  }
2538
3129
  if (part.manifest) collect.manifest = part.manifest;
2539
3130
  if (part.report) {
@@ -2567,15 +3158,15 @@ async function buildPartialReport(collect, cwd) {
2567
3158
  if (manifest) {
2568
3159
  await writeJudgments({ report, manifest, cwd });
2569
3160
  }
2570
- await writeSummaryMarkdown(report, cwd);
3161
+ await writeReport(report, cwd);
2571
3162
  await ensureGitignore(cwd);
2572
3163
  return report;
2573
3164
  }
2574
3165
  async function runGraph(opts) {
2575
3166
  const cwd = opts.cwd ?? process.cwd();
2576
3167
  const concurrency = opts.concurrency ?? defaultConcurrency();
2577
- const captureSemaphore = new Semaphore(concurrency);
2578
- const diffSemaphore = new Semaphore(cpuParallelism());
3168
+ const captureSemaphore = createSemaphore(concurrency);
3169
+ const diffSemaphore = createSemaphore(cpuCores());
2579
3170
  const baselinesDir = paths(cwd).baselines;
2580
3171
  const checkpointer = new FsCheckpointSaver(paths(cwd).checkpoints);
2581
3172
  const graph = buildGraph(captureSemaphore, diffSemaphore, checkpointer);
@@ -2595,9 +3186,11 @@ async function runGraph(opts) {
2595
3186
  }
2596
3187
  };
2597
3188
  let collect;
3189
+ setEventSink(opts.onEvent);
2598
3190
  try {
2599
3191
  collect = await streamGraph(graph, input, threadId, opts.onEvent);
2600
3192
  } finally {
3193
+ setEventSink(void 0);
2601
3194
  await closeBrowser();
2602
3195
  }
2603
3196
  const report = collect.report ?? await buildPartialReport(collect, cwd);
@@ -2623,4 +3216,120 @@ function runCheck(opts) {
2623
3216
  return runGraph(opts);
2624
3217
  }
2625
3218
 
2626
- export { HarnessError, STABILITY_HOOKS_VERSION, applyJudgments, assertLeftLoginPage, captureScreenshot, configHash, diffEntry, discover, installBrowsers, loadConfig, loadEnvFiles, loadHarness, loadManifest, paths, resolveBaseUrl, resolveHarnessFile, resolveJudge, resumeGraph, runCaptures, runCheck, runGraph, saveConfig, saveManifest, threadIdFor };
3219
+ // src/review/map.ts
3220
+ var DEFAULT_DIMS = { width: 1280, height: 800 };
3221
+ function mapLabelToClass(label) {
3222
+ switch (label) {
3223
+ case "regression-likely":
3224
+ return "regression";
3225
+ case "ambiguous":
3226
+ return "layout-shift";
3227
+ default:
3228
+ return "intentional-likely";
3229
+ }
3230
+ }
3231
+ function mapRegion(region, index) {
3232
+ return {
3233
+ id: index + 1,
3234
+ bbox: {
3235
+ x: region.bbox.x,
3236
+ y: region.bbox.y,
3237
+ w: region.bbox.width,
3238
+ h: region.bbox.height
3239
+ },
3240
+ kind: region.changeType,
3241
+ pixels: region.pixelCount,
3242
+ change: region.percentage
3243
+ };
3244
+ }
3245
+ function reviewStatus(r) {
3246
+ if (r.review === "approved") return "approved";
3247
+ if (r.review === "rejected") return "rejected";
3248
+ return "unreviewed";
3249
+ }
3250
+ function mapResultToEntry(r) {
3251
+ return {
3252
+ id: r.id,
3253
+ name: r.id,
3254
+ url: r.url,
3255
+ width: r.width ?? DEFAULT_DIMS.width,
3256
+ height: r.height ?? DEFAULT_DIMS.height,
3257
+ diff: r.diffPercentage ?? 0,
3258
+ classification: mapLabelToClass(r.verdict?.label),
3259
+ severity: r.severity ?? "low",
3260
+ action: r.verdict?.action ?? "investigate",
3261
+ summary: r.verdict?.headline ?? r.message ?? r.status,
3262
+ changes: r.verdict?.rationale ?? [],
3263
+ regions: (r.regions ?? []).map(mapRegion),
3264
+ status: reviewStatus(r),
3265
+ reviewedBy: r.review ? "you" : void 0
3266
+ };
3267
+ }
3268
+
3269
+ // src/review/actions.ts
3270
+ function recountReport(report) {
3271
+ const passed = report.results.filter((r) => r.status === "pass").length;
3272
+ const pending = report.results.filter(
3273
+ (r) => r.status === "needs-judgment"
3274
+ ).length;
3275
+ report.passed = passed;
3276
+ report.pendingJudgments = pending;
3277
+ report.failed = report.results.length - passed - pending;
3278
+ }
3279
+ async function approveEntry(id, cwd = process.cwd()) {
3280
+ const p = paths(cwd);
3281
+ const actualPng = path.join(p.actual, `${id}.png`);
3282
+ if (!existsSync(actualPng)) return null;
3283
+ await mkdir(p.baselines, { recursive: true });
3284
+ await copyFile(actualPng, path.join(p.baselines, `${id}.png`));
3285
+ await Promise.all([
3286
+ rm(actualPng, { force: true }),
3287
+ rm(path.join(p.actual, `${id}.diff.png`), { force: true }),
3288
+ rm(path.join(p.judgments, id), { recursive: true, force: true })
3289
+ ]);
3290
+ const report = await readReport(cwd);
3291
+ const result = report?.results.find((r) => r.id === id);
3292
+ if (!report || !result) return null;
3293
+ result.status = "pass";
3294
+ result.review = "approved";
3295
+ result.diffPercentage = void 0;
3296
+ result.diffCount = void 0;
3297
+ result.regions = void 0;
3298
+ result.verdict = void 0;
3299
+ result.diffPath = void 0;
3300
+ recountReport(report);
3301
+ await writeReport(report, cwd);
3302
+ return mapResultToEntry(result);
3303
+ }
3304
+ async function rejectEntry(id, cwd = process.cwd()) {
3305
+ const report = await readReport(cwd);
3306
+ const result = report?.results.find((r) => r.id === id);
3307
+ if (!report || !result) return null;
3308
+ const verdict = {
3309
+ label: "regression-likely",
3310
+ headline: result.verdict?.headline ?? "Confirmed regression during review",
3311
+ rationale: result.verdict?.rationale ?? [],
3312
+ action: "investigate"
3313
+ };
3314
+ const p = paths(cwd);
3315
+ const dir = path.join(p.judgments, id);
3316
+ await mkdir(dir, { recursive: true });
3317
+ await writeFile(
3318
+ path.join(dir, "verdict.json"),
3319
+ `${JSON.stringify({ id, verdict, rationale: "rejected via review" }, null, 2)}
3320
+ `,
3321
+ "utf8"
3322
+ );
3323
+ const updated = {
3324
+ ...result,
3325
+ status: "fail",
3326
+ review: "rejected",
3327
+ verdict
3328
+ };
3329
+ report.results = report.results.map((r) => r.id === id ? updated : r);
3330
+ recountReport(report);
3331
+ await writeReport(report, cwd);
3332
+ return mapResultToEntry(updated);
3333
+ }
3334
+
3335
+ export { HarnessError, STABILITY_HOOKS_VERSION, applyJudgments, approveEntry, assertLeftLoginPage, captureScreenshot, configHash, diffEntry, discover, installBrowsers, loadConfig, loadEnvFiles, loadHarness, loadManifest, paths, readReport, rejectEntry, resolveBaseUrl, resolveHarnessFile, resolveJudge, resumeGraph, runCaptures, runCheck, runGraph, saveConfig, saveManifest, threadIdFor, writeReport };