@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.js CHANGED
@@ -13,6 +13,7 @@ var coreNative = require('@blazediff/core-native');
13
13
  var util = require('util');
14
14
  var langgraph = require('@langchain/langgraph');
15
15
  var sharp = require('sharp');
16
+ var pc = require('picocolors');
16
17
  var langgraphCheckpoint = require('@langchain/langgraph-checkpoint');
17
18
 
18
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -39,6 +40,7 @@ function _interopNamespace(e) {
39
40
  var path__default = /*#__PURE__*/_interopDefault(path);
40
41
  var util__namespace = /*#__PURE__*/_interopNamespace(util);
41
42
  var sharp__default = /*#__PURE__*/_interopDefault(sharp);
43
+ var pc__default = /*#__PURE__*/_interopDefault(pc);
42
44
 
43
45
  // src/browser/capture.ts
44
46
  var DEFAULT_VIEWPORT = { width: 1280, height: 800 };
@@ -47,12 +49,15 @@ var DEFAULT_FULL_PAGE = true;
47
49
  var DEFAULT_THRESHOLD = 0.1;
48
50
  var MIN_AUTO_CONCURRENCY = 2;
49
51
  var MAX_AUTO_CONCURRENCY = 8;
50
- function defaultConcurrency() {
52
+ function cpuCores() {
51
53
  const cores = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length;
52
54
  if (!cores || !Number.isFinite(cores)) return MIN_AUTO_CONCURRENCY;
55
+ return cores;
56
+ }
57
+ function defaultConcurrency() {
53
58
  return Math.max(
54
59
  MIN_AUTO_CONCURRENCY,
55
- Math.min(MAX_AUTO_CONCURRENCY, cores - 1)
60
+ Math.min(MAX_AUTO_CONCURRENCY, cpuCores() - 1)
56
61
  );
57
62
  }
58
63
  var BLAZEDIFF_DIR = ".blazediff";
@@ -63,12 +68,11 @@ var paths = (cwd = process.cwd()) => {
63
68
  config: path__default.default.join(root, "config.json"),
64
69
  manifest: path__default.default.join(root, "manifest.json"),
65
70
  harnesses: path__default.default.join(root, "harnesses"),
66
- authHarness: path__default.default.join(root, "harnesses", "auth.js"),
67
71
  baselines: path__default.default.join(root, "baselines"),
68
72
  actual: path__default.default.join(root, "actual"),
69
73
  judgments: path__default.default.join(root, "judgments"),
70
74
  checkpoints: path__default.default.join(root, "checkpoints"),
71
- summary: path__default.default.join(root, "summary.md"),
75
+ report: path__default.default.join(root, "report.json"),
72
76
  gitignore: path__default.default.join(root, ".gitignore"),
73
77
  serverLog: path__default.default.join(root, "dev-server.log"),
74
78
  serverPid: path__default.default.join(root, "dev-server.pid")
@@ -97,7 +101,7 @@ async function loadHarness(harnessFile) {
97
101
  const absolute = path__default.default.isAbsolute(harnessFile) ? harnessFile : path__default.default.resolve(process.cwd(), harnessFile);
98
102
  if (!fs.existsSync(absolute)) {
99
103
  throw new HarnessError(
100
- `harness not found at ${absolute}. Author one under .blazediff/harnesses/ (or run \`blazediff-agent auth init\` for a login harness).`
104
+ `harness not found at ${absolute}. Author one under .blazediff/harnesses/ (or run \`blazediff-agent harness record <name>\` to record one).`
101
105
  );
102
106
  }
103
107
  const cached = moduleCache.get(absolute);
@@ -106,7 +110,10 @@ async function loadHarness(harnessFile) {
106
110
  const loading = (async () => {
107
111
  let mod;
108
112
  try {
109
- mod = await import(url$1);
113
+ mod = await import(
114
+ /* @vite-ignore */
115
+ url$1
116
+ );
110
117
  } catch (err) {
111
118
  throw new HarnessError(
112
119
  `failed to load harness at ${absolute}: ${err.message}`,
@@ -117,7 +124,7 @@ async function loadHarness(harnessFile) {
117
124
  if (!harness || typeof harness.run !== "function") {
118
125
  if (typeof mod.login === "function") {
119
126
  throw new HarnessError(
120
- `legacy auth harness detected at ${absolute} (exports \`login\`). Re-run \`blazediff-agent auth init\` to regenerate it as a harness.`
127
+ `legacy auth harness detected at ${absolute} (exports \`login\`). Re-run \`blazediff-agent harness record auth --login\` to regenerate it as a harness.`
121
128
  );
122
129
  }
123
130
  throw new HarnessError(
@@ -186,7 +193,13 @@ var contextPool = /* @__PURE__ */ new Map();
186
193
  async function getBrowser() {
187
194
  if (cachedBrowser?.isConnected()) return cachedBrowser;
188
195
  if (launchInFlight) return launchInFlight;
189
- launchInFlight = playwright.chromium.launch({ headless: true, args: CHROMIUM_FLAGS }).then((b) => {
196
+ launchInFlight = playwright.chromium.launch({
197
+ headless: true,
198
+ args: CHROMIUM_FLAGS,
199
+ handleSIGINT: false,
200
+ handleSIGTERM: false,
201
+ handleSIGHUP: false
202
+ }).then((b) => {
190
203
  cachedBrowser = b;
191
204
  return b;
192
205
  }).finally(() => {
@@ -504,28 +517,25 @@ function resolveBaseUrl(config, override) {
504
517
  }
505
518
 
506
519
  // src/graph/semaphore.ts
507
- var Semaphore = class {
508
- constructor(limit) {
509
- this.limit = limit;
510
- this.current = 0;
511
- this.queue = [];
512
- if (limit < 1)
513
- throw new Error(`semaphore limit must be >= 1 (got ${limit})`);
514
- }
515
- async run(fn) {
516
- if (this.current >= this.limit) {
517
- await new Promise((resolve) => this.queue.push(resolve));
520
+ function createSemaphore(limit) {
521
+ if (limit < 1) throw new Error(`semaphore limit must be >= 1 (got ${limit})`);
522
+ let current = 0;
523
+ const queue = [];
524
+ async function run(fn) {
525
+ if (current >= limit) {
526
+ await new Promise((resolve) => queue.push(resolve));
518
527
  }
519
- this.current++;
528
+ current++;
520
529
  try {
521
530
  return await fn();
522
531
  } finally {
523
- this.current--;
524
- const next = this.queue.shift();
532
+ current--;
533
+ const next = queue.shift();
525
534
  if (next) next();
526
535
  }
527
536
  }
528
- };
537
+ return { run };
538
+ }
529
539
 
530
540
  // src/types.ts
531
541
  var STABILITY_HOOKS_VERSION = 1;
@@ -682,7 +692,10 @@ async function runCaptures(opts) {
682
692
  let manifest = writeManifest ? await loadOrCreateManifest(cwd, config) : null;
683
693
  let manifestUpdates = 0;
684
694
  const slot = new Array(valid.length);
685
- const semaphore = new Semaphore(opts.concurrency ?? defaultConcurrency());
695
+ const pendingUpdates = new Array(valid.length).fill(
696
+ null
697
+ );
698
+ const semaphore = createSemaphore(opts.concurrency ?? defaultConcurrency());
686
699
  try {
687
700
  await Promise.all(
688
701
  valid.map(
@@ -723,28 +736,19 @@ async function runCaptures(opts) {
723
736
  fullPage: r.fullPage,
724
737
  harnesses: refs.length > 0 ? refs : void 0
725
738
  };
726
- manifest = {
727
- ...manifest,
728
- entries: manifest.entries.filter((e) => e.parent !== r.id)
729
- };
730
- manifest = addOrReplaceEntry(
731
- manifest,
732
- makeEntry({ id: r.id, ...shared })
733
- );
734
- manifestUpdates += 1;
735
- for (const sub of shot.subCaptures ?? []) {
736
- manifest = addOrReplaceEntry(
737
- manifest,
738
- makeEntry({
739
+ pendingUpdates[i] = {
740
+ baseId: r.id,
741
+ baseEntry: makeEntry({ id: r.id, ...shared }),
742
+ derivedEntries: (shot.subCaptures ?? []).map(
743
+ (sub) => makeEntry({
739
744
  id: `${r.id}__${sub.name}`,
740
745
  ...shared,
741
746
  parent: r.id,
742
747
  derived: true,
743
748
  subName: sub.name
744
749
  })
745
- );
746
- manifestUpdates += 1;
747
- }
750
+ )
751
+ };
748
752
  }
749
753
  } catch (err) {
750
754
  slot[i] = {
@@ -759,7 +763,22 @@ async function runCaptures(opts) {
759
763
  )
760
764
  );
761
765
  for (const r of slot) results.push(r);
762
- if (manifest && manifestUpdates > 0) await saveManifest(manifest, cwd);
766
+ if (manifest) {
767
+ for (const update of pendingUpdates) {
768
+ if (!update) continue;
769
+ manifest = {
770
+ ...manifest,
771
+ entries: manifest.entries.filter((e) => e.parent !== update.baseId)
772
+ };
773
+ manifest = addOrReplaceEntry(manifest, update.baseEntry);
774
+ manifestUpdates += 1;
775
+ for (const derived of update.derivedEntries) {
776
+ manifest = addOrReplaceEntry(manifest, derived);
777
+ manifestUpdates += 1;
778
+ }
779
+ }
780
+ if (manifestUpdates > 0) await saveManifest(manifest, cwd);
781
+ }
763
782
  } finally {
764
783
  await closeBrowser();
765
784
  }
@@ -802,7 +821,7 @@ async function diffEntry(id, baselinePath, actualPath, opts = {}, cwd = process.
802
821
  }
803
822
  const threshold = opts.threshold ?? DEFAULT_THRESHOLD;
804
823
  const antialiasing = opts.antialiasing ?? true;
805
- const result = await coreNative.compare(baselinePath, actualPath, diffPath, {
824
+ const result = await coreNative.compare(baselinePath, actualPath, void 0, {
806
825
  threshold,
807
826
  antialiasing,
808
827
  interpret: true
@@ -827,6 +846,13 @@ async function diffEntry(id, baselinePath, actualPath, opts = {}, cwd = process.
827
846
  reason: "layout-diff"
828
847
  };
829
848
  }
849
+ if (diffPath) {
850
+ await coreNative.compare(baselinePath, actualPath, diffPath, {
851
+ threshold,
852
+ antialiasing,
853
+ compression: 9
854
+ });
855
+ }
830
856
  return {
831
857
  id,
832
858
  baselinePath,
@@ -850,9 +876,9 @@ function extractInternalLinks(base, target, hrefs) {
850
876
  try {
851
877
  const u = new URL(href, target);
852
878
  if (u.origin !== base.origin) continue;
853
- const path20 = u.pathname + u.search;
854
- if (path20.startsWith("/api/")) continue;
855
- out.push(path20);
879
+ const path23 = u.pathname + u.search;
880
+ if (path23.startsWith("/api/")) continue;
881
+ out.push(path23);
856
882
  } catch {
857
883
  }
858
884
  }
@@ -906,15 +932,24 @@ async function crawlRoutes(opts) {
906
932
  }
907
933
  return discovered.slice(0, maxRoutes);
908
934
  }
909
- var DYNAMIC_SEGMENT = /\[[^\]]+\]/;
910
- async function readJson(file) {
911
- if (!fs.existsSync(file)) return null;
935
+ async function fileExists2(p) {
936
+ try {
937
+ await promises.access(p);
938
+ return true;
939
+ } catch {
940
+ return false;
941
+ }
942
+ }
943
+ async function readJsonOrNull(file) {
912
944
  try {
913
945
  return JSON.parse(await promises.readFile(file, "utf8"));
914
946
  } catch {
915
947
  return null;
916
948
  }
917
949
  }
950
+
951
+ // src/discover/next.ts
952
+ var DYNAMIC_SEGMENT = /\[[^\]]+\]/;
918
953
  function isPublicRoute(route) {
919
954
  if (DYNAMIC_SEGMENT.test(route)) return false;
920
955
  if (route === "/api" || route.startsWith("/api/")) return false;
@@ -930,13 +965,13 @@ async function discoverFromNextManifest(cwd = process.cwd()) {
930
965
  seen.add(url);
931
966
  out.push({ url, source: "next-manifest" });
932
967
  };
933
- const routes = await readJson(
968
+ const routes = await readJsonOrNull(
934
969
  path__default.default.join(nextDir, "routes-manifest.json")
935
970
  );
936
971
  for (const r of routes?.staticRoutes ?? []) {
937
972
  if (isPublicRoute(r.page)) add(r.page);
938
973
  }
939
- const appPaths = await readJson(
974
+ const appPaths = await readJsonOrNull(
940
975
  path__default.default.join(nextDir, "server", "app-paths-manifest.json")
941
976
  );
942
977
  for (const route of Object.keys(appPaths ?? {})) {
@@ -1049,14 +1084,19 @@ var ENTRIES = [
1049
1084
  "actual/",
1050
1085
  "judgments/",
1051
1086
  "checkpoints/",
1052
- "summary.md",
1087
+ "report.json",
1053
1088
  "dev-server.log",
1054
1089
  "dev-server.pid",
1055
1090
  ".env",
1056
1091
  ".env.local",
1057
1092
  "*.tmp"
1058
1093
  ];
1059
- var STALE_ENTRIES = /* @__PURE__ */ new Set(["diffs/", "pending-judgments/", "report.json"]);
1094
+ var STALE_ENTRIES = /* @__PURE__ */ new Set([
1095
+ "diffs/",
1096
+ "pending-judgments/",
1097
+ "summary.html",
1098
+ "summary.md"
1099
+ ]);
1060
1100
  var HEADER = "# blazediff: generated artifacts (committed: config.json, manifest.json, baselines/, harnesses/)\n";
1061
1101
  async function ensureGitignore(cwd) {
1062
1102
  const file = paths(cwd).gitignore;
@@ -1083,6 +1123,15 @@ ${missing.join("\n")}
1083
1123
  await promises.writeFile(file, body, "utf8");
1084
1124
  }
1085
1125
  var DEFAULT_TOP_N = 5;
1126
+ var READ_PAD_X_FACTOR = 2.5;
1127
+ var READ_PAD_X_MIN = 48;
1128
+ var READ_PAD_X_MAX = 130;
1129
+ var READ_PAD_Y_FACTOR = 0.6;
1130
+ var READ_PAD_Y_MIN = 4;
1131
+ var READ_PAD_Y_MAX = 12;
1132
+ var READ_TARGET_WIDTH = 480;
1133
+ var READ_SCALE_MIN = 2;
1134
+ var READ_SCALE_MAX = 6;
1086
1135
  var DEFAULT_PADDING = 16;
1087
1136
  var DEFAULT_LOCATOR_MAX_WIDTH = 400;
1088
1137
  var DEFAULT_GUTTER = 2;
@@ -1100,17 +1149,75 @@ function padAndClamp(bbox, padding, imgWidth, imgHeight) {
1100
1149
  height: Math.max(1, bottom - top)
1101
1150
  };
1102
1151
  }
1152
+ var clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
1153
+ async function prepareRegionReads(opts) {
1154
+ const topN = opts.topN ?? DEFAULT_TOP_N;
1155
+ const meta = await sharp__default.default(opts.actualPath).metadata();
1156
+ const imgWidth = meta.width ?? 0;
1157
+ const imgHeight = meta.height ?? 0;
1158
+ if (!imgWidth || !imgHeight) {
1159
+ throw new Error(`unable to read image dimensions: ${opts.actualPath}`);
1160
+ }
1161
+ const ranked = [...opts.regions].sort((a, b) => b.pixelCount - a.pixelCount).slice(0, topN);
1162
+ return Promise.all(
1163
+ ranked.map(async (region, i) => {
1164
+ const padX = clamp(
1165
+ Math.round(region.bbox.width * READ_PAD_X_FACTOR),
1166
+ READ_PAD_X_MIN,
1167
+ READ_PAD_X_MAX
1168
+ );
1169
+ const padY = clamp(
1170
+ Math.round(region.bbox.height * READ_PAD_Y_FACTOR),
1171
+ READ_PAD_Y_MIN,
1172
+ READ_PAD_Y_MAX
1173
+ );
1174
+ const left = Math.max(0, Math.floor(region.bbox.x - padX));
1175
+ const top = Math.max(0, Math.floor(region.bbox.y - padY));
1176
+ const right = Math.min(
1177
+ imgWidth,
1178
+ Math.ceil(region.bbox.x + region.bbox.width + padX)
1179
+ );
1180
+ const bottom = Math.min(
1181
+ imgHeight,
1182
+ Math.ceil(region.bbox.y + region.bbox.height + padY)
1183
+ );
1184
+ const extract = {
1185
+ left,
1186
+ top,
1187
+ width: Math.max(1, right - left),
1188
+ height: Math.max(1, bottom - top)
1189
+ };
1190
+ const scale = clamp(
1191
+ Math.round(READ_TARGET_WIDTH / extract.width),
1192
+ READ_SCALE_MIN,
1193
+ READ_SCALE_MAX
1194
+ );
1195
+ const render = async (src, suffix) => {
1196
+ const name = `read-${i}.${suffix}.png`;
1197
+ await sharp__default.default(src).extract(extract).resize(extract.width * scale, extract.height * scale, {
1198
+ kernel: "lanczos3"
1199
+ }).png().toFile(path__default.default.join(opts.outputDir, name));
1200
+ return path__default.default.join(opts.outputDir, name);
1201
+ };
1202
+ const [beforePath, afterPath] = await Promise.all([
1203
+ render(opts.baselinePath, "before"),
1204
+ render(opts.actualPath, "after")
1205
+ ]);
1206
+ return { changeType: region.changeType, beforePath, afterPath };
1207
+ })
1208
+ );
1209
+ }
1103
1210
  async function prepareTiles(opts) {
1104
1211
  const topN = opts.topN ?? DEFAULT_TOP_N;
1105
1212
  const padding = opts.padding ?? DEFAULT_PADDING;
1106
1213
  const locatorMaxWidth = opts.locatorMaxWidth ?? DEFAULT_LOCATOR_MAX_WIDTH;
1107
1214
  const gutter = opts.gutter ?? DEFAULT_GUTTER;
1108
1215
  const rowGutter = opts.rowGutter ?? DEFAULT_ROW_GUTTER;
1109
- const diffMeta = await sharp__default.default(opts.diffPath).metadata();
1110
- const imgWidth = diffMeta.width ?? 0;
1111
- const imgHeight = diffMeta.height ?? 0;
1216
+ const meta = await sharp__default.default(opts.actualPath).metadata();
1217
+ const imgWidth = meta.width ?? 0;
1218
+ const imgHeight = meta.height ?? 0;
1112
1219
  if (!imgWidth || !imgHeight) {
1113
- throw new Error(`unable to read diff image dimensions: ${opts.diffPath}`);
1220
+ throw new Error(`unable to read image dimensions: ${opts.actualPath}`);
1114
1221
  }
1115
1222
  const ranked = [...opts.regions].sort((a, b) => b.pixelCount - a.pixelCount).slice(0, topN);
1116
1223
  const regionData = await Promise.all(
@@ -1160,19 +1267,22 @@ async function prepareTiles(opts) {
1160
1267
  }
1161
1268
  }).composite(composites).png().toFile(path__default.default.join(opts.outputDir, tilesName));
1162
1269
  }
1163
- const scale = locatorMaxWidth / Math.max(imgWidth, imgHeight);
1164
- const locW = Math.max(1, Math.round(imgWidth * scale));
1165
- const locH = Math.max(1, Math.round(imgHeight * scale));
1166
- const rects = opts.regions.map((r) => {
1167
- const x = Math.round(r.bbox.x * scale);
1168
- const y = Math.round(r.bbox.y * scale);
1169
- const w = Math.max(1, Math.round(r.bbox.width * scale));
1170
- const h = Math.max(1, Math.round(r.bbox.height * scale));
1171
- return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="none" stroke="red" stroke-width="2" />`;
1172
- }).join("");
1173
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${locW}" height="${locH}">${rects}</svg>`;
1174
- const locatorName = "locator.png";
1175
- await sharp__default.default(opts.diffPath).resize(locW, locH, { fit: "fill" }).composite([{ input: Buffer.from(svg), left: 0, top: 0 }]).png().toFile(path__default.default.join(opts.outputDir, locatorName));
1270
+ let locatorName;
1271
+ if (opts.diffPath) {
1272
+ const scale = locatorMaxWidth / Math.max(imgWidth, imgHeight);
1273
+ const locW = Math.max(1, Math.round(imgWidth * scale));
1274
+ const locH = Math.max(1, Math.round(imgHeight * scale));
1275
+ const rects = opts.regions.map((r) => {
1276
+ const x = Math.round(r.bbox.x * scale);
1277
+ const y = Math.round(r.bbox.y * scale);
1278
+ const w = Math.max(1, Math.round(r.bbox.width * scale));
1279
+ const h = Math.max(1, Math.round(r.bbox.height * scale));
1280
+ return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="none" stroke="red" stroke-width="2" />`;
1281
+ }).join("");
1282
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${locW}" height="${locH}">${rects}</svg>`;
1283
+ locatorName = "locator.png";
1284
+ await sharp__default.default(opts.diffPath).resize(locW, locH, { fit: "fill" }).composite([{ input: Buffer.from(svg), left: 0, top: 0 }]).png().toFile(path__default.default.join(opts.outputDir, locatorName));
1285
+ }
1176
1286
  return {
1177
1287
  locatorPath: locatorName,
1178
1288
  tilesPath: tilesName,
@@ -1183,9 +1293,9 @@ async function prepareTiles(opts) {
1183
1293
  };
1184
1294
  }
1185
1295
 
1186
- // src/judge/host-harness.ts
1296
+ // src/judge/coding-agent-host.ts
1187
1297
  async function tryPrepareTiles(input, entryDir) {
1188
- if (!input.regions || input.regions.length === 0 || !input.diffPath) {
1298
+ if (!input.regions || input.regions.length === 0) {
1189
1299
  return null;
1190
1300
  }
1191
1301
  try {
@@ -1204,9 +1314,10 @@ async function tryPrepareTiles(input, entryDir) {
1204
1314
  return null;
1205
1315
  }
1206
1316
  }
1207
- var hostHarnessJudge = {
1317
+ var codingAgentHostJudge = {
1208
1318
  name: "host",
1209
1319
  async judge(input, cwd) {
1320
+ input.onJudgingStart?.();
1210
1321
  const p = paths(cwd);
1211
1322
  const entryDir = path__default.default.join(p.judgments, input.entry.id);
1212
1323
  await promises.mkdir(entryDir, { recursive: true });
@@ -1214,366 +1325,598 @@ var hostHarnessJudge = {
1214
1325
  return { kind: "deferred", requestPath: entryDir };
1215
1326
  }
1216
1327
  };
1328
+ var dim = pc__default.default.dim;
1329
+ var bold = pc__default.default.bold;
1217
1330
 
1218
- // src/judge/none.ts
1219
- var noneJudge = {
1220
- name: "none",
1221
- async judge(input) {
1222
- return { kind: "judged", verdict: input.heuristicVerdict };
1223
- }
1224
- };
1225
- var ROOT_NS_SENTINEL = "_root";
1226
- function nsDir(ns) {
1227
- return ns === "" ? ROOT_NS_SENTINEL : ns;
1228
- }
1229
- function encode(buf) {
1230
- return Buffer.from(buf).toString("base64");
1231
- }
1232
- function decode(s) {
1233
- return Buffer.from(s, "base64");
1331
+ // src/judge/transformers.ts
1332
+ var toMb = (bytes) => (bytes / 1048576).toFixed(1);
1333
+ function createLoadProgress(label) {
1334
+ const interactive = Boolean(process.stderr.isTTY);
1335
+ const bytes = /* @__PURE__ */ new Map();
1336
+ let announced = false;
1337
+ let lastPct = -1;
1338
+ let lastBucket = -1;
1339
+ const totals = () => {
1340
+ let loaded = 0;
1341
+ let total = 0;
1342
+ for (const b of bytes.values()) {
1343
+ loaded += b.loaded;
1344
+ total += b.total;
1345
+ }
1346
+ const pct = total > 0 ? Math.min(100, Math.floor(loaded / total * 100)) : 0;
1347
+ return { loaded, total, pct };
1348
+ };
1349
+ return {
1350
+ onProgress(event) {
1351
+ if (!announced) {
1352
+ process.stderr.write(
1353
+ `${dim("[blazediff]")} loading ${bold(label)} model ${dim("(first run downloads weights)\u2026")}
1354
+ `
1355
+ );
1356
+ announced = true;
1357
+ }
1358
+ if (event.status !== "progress" || !event.file || typeof event.total !== "number")
1359
+ return;
1360
+ bytes.set(event.file, { loaded: event.loaded ?? 0, total: event.total });
1361
+ const { loaded, total, pct } = totals();
1362
+ if (pct === lastPct) return;
1363
+ lastPct = pct;
1364
+ const line = ` ${label}: ${pct}% ${dim(`(${toMb(loaded)}/${toMb(total)} MB)`)}`;
1365
+ if (interactive) {
1366
+ process.stderr.write(`\r${line}\x1B[K`);
1367
+ return;
1368
+ }
1369
+ const bucket = Math.floor(pct / 25);
1370
+ if (bucket > lastBucket) {
1371
+ lastBucket = bucket;
1372
+ process.stderr.write(`${line}
1373
+ `);
1374
+ }
1375
+ },
1376
+ done() {
1377
+ if (!announced) return;
1378
+ if (interactive) {
1379
+ const { total } = totals();
1380
+ const size = total > 0 ? dim(` (${toMb(total)} MB)`) : "";
1381
+ process.stderr.write(
1382
+ `\r ${label}: ${pc__default.default.green("ready")}${size}\x1B[K
1383
+ `
1384
+ );
1385
+ } else if (lastPct < 100) {
1386
+ process.stderr.write(` ${label}: ${pc__default.default.green("ready")}
1387
+ `);
1388
+ }
1389
+ }
1390
+ };
1234
1391
  }
1235
- async function readJson2(file) {
1392
+ async function loadTransformers() {
1236
1393
  try {
1237
- const raw = await promises.readFile(file, "utf8");
1238
- return JSON.parse(raw);
1394
+ return await import('@huggingface/transformers');
1239
1395
  } catch (err) {
1240
- if (err.code === "ENOENT") return void 0;
1241
- throw err;
1396
+ throw new Error(
1397
+ 'stack=local requires the optional peer dependency "@huggingface/transformers". Install it with `npm i @huggingface/transformers` (or pnpm/bun add).',
1398
+ { cause: err instanceof Error ? err : void 0 }
1399
+ );
1242
1400
  }
1243
1401
  }
1244
- async function writeJsonAtomic(file, value) {
1245
- const tmp = `${file}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
1246
- await promises.writeFile(tmp, JSON.stringify(value), "utf8");
1247
- await promises.rename(tmp, file);
1402
+
1403
+ // src/judge/classifier.ts
1404
+ var MODEL_ID = "onnx-community/Qwen3.5-0.8B-ONNX";
1405
+ var MAX_NEW_TOKENS = 64;
1406
+ async function defaultFactory() {
1407
+ const mod = await loadTransformers();
1408
+ const progress = createLoadProgress("classifier");
1409
+ const progress_callback = progress.onProgress;
1410
+ const [tokenizer, model] = await Promise.all([
1411
+ mod.AutoTokenizer.from_pretrained(MODEL_ID, { progress_callback }),
1412
+ mod.Qwen3_5ForConditionalGeneration.from_pretrained(MODEL_ID, {
1413
+ dtype: {
1414
+ embed_tokens: "fp32",
1415
+ vision_encoder: "q8",
1416
+ decoder_model_merged: "q4"
1417
+ },
1418
+ device: "cpu",
1419
+ progress_callback
1420
+ })
1421
+ ]);
1422
+ progress.done();
1423
+ return {
1424
+ async complete(prompt) {
1425
+ const inputs = tokenizer.apply_chat_template(
1426
+ [{ role: "user", content: prompt }],
1427
+ {
1428
+ add_generation_prompt: true,
1429
+ return_dict: true,
1430
+ enable_thinking: false
1431
+ }
1432
+ );
1433
+ const output = await model.generate({
1434
+ ...inputs,
1435
+ do_sample: false,
1436
+ max_new_tokens: MAX_NEW_TOKENS
1437
+ });
1438
+ const promptLen = inputs.input_ids.dims.at(-1);
1439
+ const generated = output.slice(null, [promptLen, null]);
1440
+ const decoded = tokenizer.batch_decode(generated, {
1441
+ skip_special_tokens: true
1442
+ });
1443
+ const raw = Array.isArray(decoded) ? String(decoded[0] ?? "") : String(decoded);
1444
+ return raw.trim();
1445
+ }
1446
+ };
1248
1447
  }
1249
- var FsCheckpointSaver = class extends langgraphCheckpoint.BaseCheckpointSaver {
1250
- constructor(root, serde) {
1251
- super(serde);
1252
- this.locks = /* @__PURE__ */ new Map();
1253
- this.root = root;
1254
- }
1255
- threadDir(thread) {
1256
- return path__default.default.join(this.root, thread);
1257
- }
1258
- nsPath(thread, ns) {
1259
- return path__default.default.join(this.threadDir(thread), nsDir(ns));
1260
- }
1261
- ckptFile(thread, ns, id) {
1262
- return path__default.default.join(this.nsPath(thread, ns), `${id}.ckpt.json`);
1263
- }
1264
- writesFile(thread, ns, id) {
1265
- return path__default.default.join(this.nsPath(thread, ns), `${id}.writes.json`);
1266
- }
1267
- async withLock(key, fn) {
1268
- const prev = this.locks.get(key) ?? Promise.resolve();
1269
- const next = prev.then(fn, fn);
1270
- this.locks.set(key, next);
1271
- try {
1272
- return await next;
1273
- } finally {
1274
- if (this.locks.get(key) === next) this.locks.delete(key);
1448
+ function createClassifierRunnerHolder(factory = defaultFactory) {
1449
+ let runnerPromise;
1450
+ return {
1451
+ get() {
1452
+ if (!runnerPromise) runnerPromise = factory();
1453
+ return runnerPromise;
1275
1454
  }
1276
- }
1277
- async listCheckpointIds(thread, ns) {
1278
- try {
1279
- const names = await promises.readdir(this.nsPath(thread, ns));
1280
- const suffix = ".ckpt.json";
1281
- return names.filter((n) => n.endsWith(suffix)).map((n) => n.slice(0, -suffix.length));
1282
- } catch (err) {
1283
- if (err.code === "ENOENT") return [];
1284
- throw err;
1455
+ };
1456
+ }
1457
+
1458
+ // src/judge/region-diff.ts
1459
+ var FILLER = /* @__PURE__ */ new Set([
1460
+ "the",
1461
+ "a",
1462
+ "an",
1463
+ "is",
1464
+ "are",
1465
+ "was",
1466
+ "were",
1467
+ "be",
1468
+ "this",
1469
+ "that",
1470
+ "these",
1471
+ "those",
1472
+ "it",
1473
+ "its",
1474
+ "there",
1475
+ "here",
1476
+ "and",
1477
+ "or",
1478
+ "but",
1479
+ "of",
1480
+ "in",
1481
+ "on",
1482
+ "at",
1483
+ "to",
1484
+ "with",
1485
+ "within",
1486
+ "against",
1487
+ "around",
1488
+ "surrounding",
1489
+ "into",
1490
+ "from",
1491
+ "by",
1492
+ "for",
1493
+ "as",
1494
+ "no",
1495
+ "not",
1496
+ "other",
1497
+ "some",
1498
+ "also",
1499
+ "another",
1500
+ "word",
1501
+ "words",
1502
+ "text",
1503
+ "letter",
1504
+ "letters",
1505
+ "character",
1506
+ "characters",
1507
+ "number",
1508
+ "numbers",
1509
+ "digit",
1510
+ "digits",
1511
+ "phrase",
1512
+ "label",
1513
+ "title",
1514
+ "written",
1515
+ "writes",
1516
+ "reads",
1517
+ "read",
1518
+ "says",
1519
+ "displayed",
1520
+ "displays",
1521
+ "display",
1522
+ "shows",
1523
+ "show",
1524
+ "showing",
1525
+ "shown",
1526
+ "appears",
1527
+ "appear",
1528
+ "reading",
1529
+ "prominently",
1530
+ "visible",
1531
+ "positioned",
1532
+ "located",
1533
+ "white",
1534
+ "black",
1535
+ "blue",
1536
+ "red",
1537
+ "green",
1538
+ "purple",
1539
+ "gray",
1540
+ "grey",
1541
+ "background",
1542
+ "foreground",
1543
+ "color",
1544
+ "colors",
1545
+ "colored",
1546
+ "colour",
1547
+ "font",
1548
+ "style",
1549
+ "styled",
1550
+ "bold",
1551
+ "italic",
1552
+ "blurred",
1553
+ "slightly",
1554
+ "image",
1555
+ "photo",
1556
+ "picture",
1557
+ "frame",
1558
+ "scene",
1559
+ "object",
1560
+ "objects",
1561
+ "element",
1562
+ "elements",
1563
+ "ui",
1564
+ "screen",
1565
+ "page",
1566
+ "logo",
1567
+ "icon",
1568
+ "button",
1569
+ "large",
1570
+ "small",
1571
+ "big",
1572
+ "left",
1573
+ "right",
1574
+ "top",
1575
+ "bottom",
1576
+ "center",
1577
+ "corner",
1578
+ "side",
1579
+ "above",
1580
+ "below",
1581
+ "ink",
1582
+ "company",
1583
+ "name",
1584
+ "brand",
1585
+ "create",
1586
+ "creating",
1587
+ "artistic",
1588
+ "effect",
1589
+ "design",
1590
+ "additional"
1591
+ ]);
1592
+ function tokenize(text) {
1593
+ return text.toLowerCase().match(/[a-z0-9]+/g) ?? [];
1594
+ }
1595
+ function extractQuoted(read) {
1596
+ const spans = [...read.matchAll(/["“”']([^"“”']+)["“”']/g)].map(
1597
+ (m) => m[1].trim()
1598
+ );
1599
+ if (spans.length === 0) return null;
1600
+ return spans.reduce((a, b) => b.length > a.length ? b : a).trim() || null;
1601
+ }
1602
+ function diffTokens(base, actual) {
1603
+ const n = base.length;
1604
+ const m = actual.length;
1605
+ const dp = Array.from(
1606
+ { length: n + 1 },
1607
+ () => new Array(m + 1).fill(0)
1608
+ );
1609
+ for (let i2 = n - 1; i2 >= 0; i2--) {
1610
+ for (let j2 = m - 1; j2 >= 0; j2--) {
1611
+ dp[i2][j2] = base[i2] === actual[j2] ? dp[i2 + 1][j2 + 1] + 1 : Math.max(dp[i2 + 1][j2], dp[i2][j2 + 1]);
1285
1612
  }
1286
1613
  }
1287
- async listNamespaces(thread) {
1288
- try {
1289
- return await promises.readdir(this.threadDir(thread));
1290
- } catch (err) {
1291
- if (err.code === "ENOENT") return [];
1292
- throw err;
1614
+ const inserted = [];
1615
+ const removed = [];
1616
+ let i = 0;
1617
+ let j = 0;
1618
+ while (i < n && j < m) {
1619
+ if (base[i] === actual[j]) {
1620
+ i++;
1621
+ j++;
1622
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
1623
+ removed.push(base[i++]);
1624
+ } else {
1625
+ inserted.push(actual[j++]);
1293
1626
  }
1294
1627
  }
1295
- async listThreads() {
1296
- try {
1297
- return await promises.readdir(this.root);
1298
- } catch (err) {
1299
- if (err.code === "ENOENT") return [];
1300
- throw err;
1628
+ while (i < n) removed.push(base[i++]);
1629
+ while (j < m) inserted.push(actual[j++]);
1630
+ return { inserted, removed };
1631
+ }
1632
+ var keepToken = (t) => /\d/.test(t) || !FILLER.has(t);
1633
+ var quote = (tokens) => `"${tokens.join(" ")}"`;
1634
+ function describeRegionChange(changeType, baseRead, actualRead) {
1635
+ const baseQuoted = extractQuoted(baseRead);
1636
+ const actualQuoted = extractQuoted(actualRead);
1637
+ const haveCores = baseQuoted !== null && actualQuoted !== null;
1638
+ const base = tokenize(baseQuoted ?? baseRead);
1639
+ const actual = tokenize(actualQuoted ?? actualRead);
1640
+ const { inserted, removed } = diffTokens(base, actual);
1641
+ const ins = haveCores ? inserted : inserted.filter(keepToken);
1642
+ const rem = haveCores ? removed : removed.filter(keepToken);
1643
+ const updated = actualQuoted && actualQuoted.length <= 60 ? ` (region now reads "${actualQuoted}")` : "";
1644
+ if (ins.length > 0 && rem.length === 0)
1645
+ return `added ${quote(ins)}${updated}`;
1646
+ if (rem.length > 0 && ins.length === 0)
1647
+ return `removed ${quote(rem)}${updated}`;
1648
+ if (ins.length > 0 && rem.length > 0)
1649
+ return `replaced ${quote(rem)} with ${quote(ins)}${updated}`;
1650
+ const kind = changeType.replace(/-/g, " ");
1651
+ return `${kind} with no readable text change${updated}`;
1652
+ }
1653
+
1654
+ // src/judge/vision.ts
1655
+ var MODEL_ID2 = "Xenova/moondream2";
1656
+ var PATCH_SIZE = 14;
1657
+ var MAX_NEW_TOKENS2 = 64;
1658
+ var ANSWER_MARKER = "Answer:";
1659
+ async function defaultFactory2() {
1660
+ const mod = await loadTransformers();
1661
+ const progress = createLoadProgress("vision");
1662
+ const progress_callback = progress.onProgress;
1663
+ const [tokenizer, processor, model] = await Promise.all([
1664
+ mod.AutoTokenizer.from_pretrained(MODEL_ID2, { progress_callback }),
1665
+ mod.AutoProcessor.from_pretrained(MODEL_ID2, { progress_callback }),
1666
+ mod.Moondream1ForConditionalGeneration.from_pretrained(MODEL_ID2, {
1667
+ dtype: {
1668
+ embed_tokens: "fp32",
1669
+ vision_encoder: "q8",
1670
+ decoder_model_merged: "q4"
1671
+ },
1672
+ device: "cpu",
1673
+ progress_callback
1674
+ })
1675
+ ]);
1676
+ progress.done();
1677
+ return {
1678
+ async describe(imagePath, question) {
1679
+ const image = await mod.RawImage.read(imagePath);
1680
+ const vision = await processor(image);
1681
+ const [, , height, width] = vision.pixel_values.dims;
1682
+ const numImageTokens = Math.floor(height / PATCH_SIZE) * Math.floor(width / PATCH_SIZE);
1683
+ const prompt = `${"<image>".repeat(numImageTokens)}
1684
+
1685
+ Question: ${question}
1686
+
1687
+ ${ANSWER_MARKER}`;
1688
+ const textInputs = tokenizer(prompt);
1689
+ const output = await model.generate({
1690
+ ...textInputs,
1691
+ ...vision,
1692
+ do_sample: false,
1693
+ max_new_tokens: MAX_NEW_TOKENS2,
1694
+ // Moondream loops the same sentence on composite tiles without these.
1695
+ repetition_penalty: 1.3,
1696
+ no_repeat_ngram_size: 3
1697
+ });
1698
+ const decoded = tokenizer.batch_decode(output, {
1699
+ skip_special_tokens: true
1700
+ });
1701
+ const raw = Array.isArray(decoded) ? String(decoded[0] ?? "") : String(decoded);
1702
+ const idx = raw.lastIndexOf(ANSWER_MARKER);
1703
+ return (idx >= 0 ? raw.slice(idx + ANSWER_MARKER.length) : raw).trim();
1301
1704
  }
1302
- }
1303
- decodeNs(nsDirName) {
1304
- return nsDirName === ROOT_NS_SENTINEL ? "" : nsDirName;
1305
- }
1306
- async loadPendingWrites(thread, ns, ckptId) {
1307
- const data = await readJson2(
1308
- this.writesFile(thread, ns, ckptId)
1309
- );
1310
- if (!data) return [];
1311
- const out = [];
1312
- for (const [taskId, channel, serialized] of Object.values(data)) {
1313
- const value = await this.serde.loadsTyped("json", decode(serialized));
1314
- out.push([taskId, channel, value]);
1705
+ };
1706
+ }
1707
+ function createVisionRunnerHolder(factory = defaultFactory2) {
1708
+ let runnerPromise;
1709
+ return {
1710
+ get() {
1711
+ if (!runnerPromise) runnerPromise = factory();
1712
+ return runnerPromise;
1315
1713
  }
1316
- return out;
1317
- }
1318
- async migratePendingSends(checkpoint, thread, ns, parentCheckpointId) {
1319
- const data = await readJson2(
1320
- this.writesFile(thread, ns, parentCheckpointId)
1321
- );
1322
- const pendingSends = data ? await Promise.all(
1323
- Object.values(data).filter(([, channel]) => channel === langgraphCheckpoint.TASKS).map(
1324
- ([, , serialized]) => this.serde.loadsTyped("json", decode(serialized))
1325
- )
1326
- ) : [];
1327
- const m = checkpoint;
1328
- m.channel_values ?? (m.channel_values = {});
1329
- m.channel_values[langgraphCheckpoint.TASKS] = pendingSends;
1330
- m.channel_versions ?? (m.channel_versions = {});
1331
- const versions = Object.values(m.channel_versions);
1332
- m.channel_versions[langgraphCheckpoint.TASKS] = versions.length > 0 ? langgraphCheckpoint.maxChannelVersion(...versions) : this.getNextVersion(void 0);
1333
- }
1334
- async readTuple(thread, ns, ckptId, config) {
1335
- const data = await readJson2(this.ckptFile(thread, ns, ckptId));
1336
- if (!data) return void 0;
1337
- const checkpoint = await this.serde.loadsTyped(
1338
- "json",
1339
- decode(data.checkpoint)
1340
- );
1341
- const metadata = await this.serde.loadsTyped(
1342
- "json",
1343
- decode(data.metadata)
1344
- );
1345
- if (checkpoint.v < 4 && data.parentCheckpointId !== void 0) {
1346
- await this.migratePendingSends(
1347
- checkpoint,
1348
- thread,
1349
- ns,
1350
- data.parentCheckpointId
1714
+ };
1715
+ }
1716
+
1717
+ // src/judge/local.ts
1718
+ var READ_PROMPT = [
1719
+ "Read the text in this image. Reply with only the exact words and numbers you",
1720
+ 'see, wrapped in double quotes. If there is no text, reply "".'
1721
+ ].join(" ");
1722
+ var DESCRIBE_PROMPT = [
1723
+ "In one sentence, describe the main UI elements and any visible text in this",
1724
+ "screenshot. Do not judge whether it is good or bad."
1725
+ ].join(" ");
1726
+ var LABELS = [
1727
+ "regression-likely",
1728
+ "intentional-likely",
1729
+ "noise-likely",
1730
+ "ambiguous"
1731
+ ];
1732
+ var ACTION_BY_LABEL = {
1733
+ "regression-likely": "investigate",
1734
+ "intentional-likely": "rewrite-if-intended",
1735
+ "noise-likely": "ignore-or-rewrite",
1736
+ ambiguous: "investigate"
1737
+ };
1738
+ var VERDICT_MARKER = "VERDICT:";
1739
+ function summarizeInterpret(input) {
1740
+ const lines = [];
1741
+ lines.push(
1742
+ `diff area: ${(input.diffPercentage ?? 0).toFixed(3)}% of the page`
1743
+ );
1744
+ lines.push(`severity: ${input.severity ?? "unknown"}`);
1745
+ const regions = input.regions ?? [];
1746
+ lines.push(`changed regions: ${regions.length}`);
1747
+ if (regions.length > 0) {
1748
+ const counts = /* @__PURE__ */ new Map();
1749
+ for (const r of regions)
1750
+ counts.set(r.changeType, (counts.get(r.changeType) ?? 0) + 1);
1751
+ const byType = [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([type, n]) => `${type} x${n}`).join(", ");
1752
+ lines.push(`change types: ${byType}`);
1753
+ }
1754
+ return lines.join("\n");
1755
+ }
1756
+ function buildClassifyPrompt(summary, description) {
1757
+ return [
1758
+ "You classify a visual regression-test diff into exactly one label.",
1759
+ "",
1760
+ "Deterministic analysis of the changed pixels:",
1761
+ summary,
1762
+ "",
1763
+ "The change in the affected region, read from the screenshots, is:",
1764
+ `"${description}"`,
1765
+ "",
1766
+ "Labels:",
1767
+ "- regression-likely: something looks broken, missing, clipped, or misaligned.",
1768
+ "- intentional-likely: a deliberate content or style update.",
1769
+ "- noise-likely: negligible anti-aliasing / sub-pixel rendering differences.",
1770
+ "- ambiguous: cannot tell from the evidence.",
1771
+ "",
1772
+ "First explain your reasoning in one short sentence. Then, on the final",
1773
+ `line, write "${VERDICT_MARKER} <label>" using exactly one label above.`
1774
+ ].join("\n");
1775
+ }
1776
+ function parseLabel(text) {
1777
+ const t = text.toLowerCase();
1778
+ const marked = t.match(/verdict:\s*([a-z-]+)/);
1779
+ if (marked) {
1780
+ const hit = LABELS.find((label) => marked[1].startsWith(label));
1781
+ if (hit) return hit;
1782
+ }
1783
+ let latest2 = null;
1784
+ for (const label of LABELS) {
1785
+ const idx = t.lastIndexOf(label);
1786
+ if (idx >= 0 && (!latest2 || idx > latest2.idx)) latest2 = { label, idx };
1787
+ }
1788
+ return latest2?.label ?? null;
1789
+ }
1790
+ function firstSentence(text) {
1791
+ const trimmed = text.trim().replace(/\s+/g, " ");
1792
+ const m = trimmed.match(/^.*?[.!?](\s|$)/);
1793
+ return (m ? m[0] : trimmed).trim();
1794
+ }
1795
+ function reasonOf(answer, label) {
1796
+ const beforeVerdict = answer.split(/verdict:/i)[0];
1797
+ const withoutLabel = beforeVerdict.replace(new RegExp(label, "gi"), "").trim();
1798
+ return firstSentence(withoutLabel) || firstSentence(answer);
1799
+ }
1800
+ function toError(err) {
1801
+ return err instanceof Error ? err : new Error(String(err));
1802
+ }
1803
+ function classifyFailure(err) {
1804
+ const m = err.message.toLowerCase();
1805
+ if (m.includes("model") || m.includes("weights") || m.includes("download") || m.includes("transformers"))
1806
+ return "model-load";
1807
+ if (m.includes("enoent") || m.includes("read") || m.includes("sharp") || m.includes("crop"))
1808
+ return "read";
1809
+ return "internal";
1810
+ }
1811
+ function createLocalJudge(deps = {}) {
1812
+ const vision = deps.vision ?? createVisionRunnerHolder();
1813
+ const classifier = deps.classifier ?? createClassifierRunnerHolder();
1814
+ const visionSemaphore = createSemaphore(1);
1815
+ const classifierSemaphore = createSemaphore(1);
1816
+ async function describeChange(input, entryDir) {
1817
+ if (!input.regions || input.regions.length === 0) return null;
1818
+ try {
1819
+ const crops = await prepareRegionReads({
1820
+ regions: input.regions,
1821
+ baselinePath: input.baselinePath,
1822
+ actualPath: input.actualPath,
1823
+ outputDir: entryDir
1824
+ });
1825
+ if (crops.length === 0) return null;
1826
+ const v = await vision.get();
1827
+ const phrases = await Promise.all(
1828
+ crops.map(async (crop) => {
1829
+ const [before, after] = await Promise.all([
1830
+ v.describe(crop.beforePath, READ_PROMPT),
1831
+ v.describe(crop.afterPath, READ_PROMPT)
1832
+ ]);
1833
+ return describeRegionChange(crop.changeType, before, after);
1834
+ })
1351
1835
  );
1836
+ return phrases.length === 1 ? phrases[0] : phrases.map((p, i) => `region ${i + 1}: ${p}`).join("; ");
1837
+ } catch {
1838
+ return null;
1352
1839
  }
1353
- const pendingWrites = await this.loadPendingWrites(thread, ns, ckptId);
1354
- const tuple = {
1355
- config,
1356
- checkpoint,
1357
- metadata,
1358
- pendingWrites
1359
- };
1360
- if (data.parentCheckpointId !== void 0) {
1361
- tuple.parentConfig = {
1362
- configurable: {
1363
- thread_id: thread,
1364
- checkpoint_ns: ns,
1365
- checkpoint_id: data.parentCheckpointId
1840
+ }
1841
+ async function describeScreenshot(input) {
1842
+ const v = await vision.get();
1843
+ return (await v.describe(input.actualPath, DESCRIBE_PROMPT)).trim();
1844
+ }
1845
+ return {
1846
+ name: "local",
1847
+ // Stream both models' weights up front (concurrently) so the multi-second
1848
+ // load is a single visible phase before judging, not a silent stall on the
1849
+ // first test. Both are cached promises, so the judge reuses them after.
1850
+ async warmup() {
1851
+ await Promise.all([vision.get(), classifier.get()]);
1852
+ },
1853
+ async judge(input, cwd) {
1854
+ const entryDir = path__default.default.join(paths(cwd).judgments, input.entry.id);
1855
+ await promises.mkdir(entryDir, { recursive: true });
1856
+ try {
1857
+ const description = await visionSemaphore.run(async () => {
1858
+ input.onJudgingStart?.();
1859
+ const fromRegions = await describeChange(input, entryDir);
1860
+ const text = fromRegions ?? await describeScreenshot(input);
1861
+ return text.trim();
1862
+ });
1863
+ const summary = summarizeInterpret(input);
1864
+ const prompt = buildClassifyPrompt(summary, description);
1865
+ const answer = await classifierSemaphore.run(async () => {
1866
+ const c = await classifier.get();
1867
+ return (await c.complete(prompt)).trim();
1868
+ });
1869
+ const label = parseLabel(answer);
1870
+ if (!label) {
1871
+ return {
1872
+ kind: "judged",
1873
+ verdict: input.heuristicVerdict,
1874
+ rationale: `${description}
1875
+ ${answer}`.trim()
1876
+ };
1366
1877
  }
1367
- };
1878
+ const reason = reasonOf(answer, label);
1879
+ const verdict = {
1880
+ label,
1881
+ headline: reason || input.heuristicVerdict.headline,
1882
+ // The headline already carries the classifier's reasoning; keep only
1883
+ // the deterministic region read here so the report doesn't repeat the
1884
+ // reasoning or echo the raw `VERDICT:` line back to the reader.
1885
+ rationale: [description].filter(Boolean),
1886
+ action: ACTION_BY_LABEL[label]
1887
+ };
1888
+ return { kind: "judged", verdict, rationale: answer, confidence: 0.6 };
1889
+ } catch (err) {
1890
+ const error = toError(err);
1891
+ return {
1892
+ kind: "failed",
1893
+ reason: classifyFailure(error),
1894
+ error,
1895
+ fallback: input.heuristicVerdict
1896
+ };
1897
+ }
1368
1898
  }
1369
- return tuple;
1370
- }
1371
- async getTuple(config) {
1372
- const thread = config.configurable?.thread_id;
1373
- if (!thread) return void 0;
1374
- const ns = config.configurable?.checkpoint_ns ?? "";
1375
- const explicitId = langgraphCheckpoint.getCheckpointId(config);
1376
- if (explicitId) {
1377
- return this.readTuple(thread, ns, explicitId, config);
1378
- }
1379
- const ids = (await this.listCheckpointIds(thread, ns)).sort(
1380
- (a, b) => b.localeCompare(a)
1381
- );
1382
- if (ids.length === 0) return void 0;
1383
- const ckptId = ids[0];
1384
- return this.readTuple(thread, ns, ckptId, {
1385
- configurable: {
1386
- thread_id: thread,
1387
- checkpoint_ns: ns,
1388
- checkpoint_id: ckptId
1389
- }
1390
- });
1391
- }
1392
- async *list(config, options) {
1393
- const filter = options?.filter;
1394
- const before = options?.before;
1395
- let limit = options?.limit;
1396
- const configThread = config.configurable?.thread_id;
1397
- const configNs = config.configurable?.checkpoint_ns;
1398
- const configCkptId = config.configurable?.checkpoint_id;
1399
- const threads = configThread ? [configThread] : await this.listThreads();
1400
- for (const thread of threads) {
1401
- const nsNames = await this.listNamespaces(thread);
1402
- for (const nsName of nsNames) {
1403
- const ns = this.decodeNs(nsName);
1404
- if (configNs !== void 0 && ns !== configNs) continue;
1405
- const ids = (await this.listCheckpointIds(thread, ns)).sort(
1406
- (a, b) => b.localeCompare(a)
1407
- );
1408
- for (const ckptId of ids) {
1409
- if (configCkptId && ckptId !== configCkptId) continue;
1410
- if (before?.configurable?.checkpoint_id && ckptId >= before.configurable.checkpoint_id)
1411
- continue;
1412
- const tuple = await this.readTuple(thread, ns, ckptId, {
1413
- configurable: {
1414
- thread_id: thread,
1415
- checkpoint_ns: ns,
1416
- checkpoint_id: ckptId
1417
- }
1418
- });
1419
- if (!tuple) continue;
1420
- if (filter) {
1421
- const md = tuple.metadata;
1422
- const matches = Object.entries(filter).every(
1423
- ([k, v]) => md?.[k] === v
1424
- );
1425
- if (!matches) continue;
1426
- }
1427
- if (limit !== void 0) {
1428
- if (limit <= 0) return;
1429
- limit -= 1;
1430
- }
1431
- yield tuple;
1432
- }
1433
- }
1434
- }
1435
- }
1436
- async put(config, checkpoint, metadata) {
1437
- const thread = config.configurable?.thread_id;
1438
- if (!thread) {
1439
- throw new Error(
1440
- 'FsCheckpointSaver: missing "thread_id" in configurable. Pass `{ configurable: { thread_id } }` when streaming.'
1441
- );
1442
- }
1443
- const ns = config.configurable?.checkpoint_ns ?? "";
1444
- const parentCheckpointId = config.configurable?.checkpoint_id;
1445
- const prepared = langgraphCheckpoint.copyCheckpoint(checkpoint);
1446
- const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([
1447
- this.serde.dumpsTyped(prepared),
1448
- this.serde.dumpsTyped(metadata)
1449
- ]);
1450
- await promises.mkdir(this.nsPath(thread, ns), { recursive: true });
1451
- const file = this.ckptFile(thread, ns, checkpoint.id);
1452
- const body = {
1453
- checkpoint: encode(serializedCheckpoint),
1454
- metadata: encode(serializedMetadata),
1455
- parentCheckpointId
1456
- };
1457
- await writeJsonAtomic(file, body);
1458
- return {
1459
- configurable: {
1460
- thread_id: thread,
1461
- checkpoint_ns: ns,
1462
- checkpoint_id: checkpoint.id
1463
- }
1464
- };
1465
- }
1466
- async putWrites(config, writes, taskId) {
1467
- const thread = config.configurable?.thread_id;
1468
- if (!thread) {
1469
- throw new Error(
1470
- 'FsCheckpointSaver: missing "thread_id" in configurable for putWrites.'
1471
- );
1472
- }
1473
- const ns = config.configurable?.checkpoint_ns ?? "";
1474
- const ckptId = config.configurable?.checkpoint_id;
1475
- if (!ckptId) {
1476
- throw new Error(
1477
- 'FsCheckpointSaver: missing "checkpoint_id" in configurable for putWrites.'
1478
- );
1479
- }
1480
- const key = `${thread}|${ns}|${ckptId}`;
1481
- await this.withLock(key, async () => {
1482
- const existing = await readJson2(this.writesFile(thread, ns, ckptId)) ?? {};
1483
- let mutated = false;
1484
- for (let idx = 0; idx < writes.length; idx++) {
1485
- const [channel, value] = writes[idx];
1486
- const writeIdx = langgraphCheckpoint.WRITES_IDX_MAP[channel] ?? idx;
1487
- const innerKey = `${taskId},${writeIdx}`;
1488
- if (writeIdx >= 0 && innerKey in existing) continue;
1489
- const [, serialized] = await this.serde.dumpsTyped(value);
1490
- existing[innerKey] = [taskId, channel, encode(serialized)];
1491
- mutated = true;
1492
- }
1493
- if (!mutated) return;
1494
- await promises.mkdir(this.nsPath(thread, ns), { recursive: true });
1495
- await writeJsonAtomic(this.writesFile(thread, ns, ckptId), existing);
1496
- });
1497
- }
1498
- async deleteThread(threadId) {
1499
- await promises.rm(this.threadDir(threadId), { recursive: true, force: true });
1500
- }
1501
- };
1502
- var PREVIEW_WIDTH = 320;
1503
- function escapeCell(s) {
1504
- return s.replace(/\n/g, " ");
1505
- }
1506
- function toBlazediffRel(cwd, abs) {
1507
- if (!abs) return void 0;
1508
- const root = paths(cwd).root;
1509
- const rel = path__default.default.isAbsolute(abs) ? path__default.default.relative(root, abs) : path__default.default.relative(paths(cwd).root, path__default.default.join(cwd, abs));
1510
- return rel.split(path__default.default.sep).join("/");
1511
- }
1512
- function img(src, alt) {
1513
- return `<img src="${src}" width="${PREVIEW_WIDTH}" alt="${alt}">`;
1514
- }
1515
- function baselineCell(r, cwd) {
1516
- const rel = toBlazediffRel(cwd, r.baselinePath) ?? `baselines/${r.id}.png`;
1517
- return img(rel, `${r.id} baseline`);
1518
- }
1519
- function actualCell(r, cwd) {
1520
- const actual = toBlazediffRel(cwd, r.actualPath);
1521
- return actual ? img(actual, `${r.id} actual`) : "-";
1522
- }
1523
- function diffCell(r, cwd) {
1524
- const diff = toBlazediffRel(cwd, r.diffPath);
1525
- return diff ? img(diff, `${r.id} diff`) : "-";
1526
- }
1527
- function verdictCell(r) {
1528
- if (r.status === "missing-baseline") {
1529
- return `missing-baseline - ${r.message ?? "baseline missing"}`;
1530
- }
1531
- if (r.status === "stale-baseline") {
1532
- return `stale-baseline - ${r.message ?? "manifest entry edited without re-capturing"}`;
1533
- }
1534
- if (r.status === "needs-judgment") {
1535
- return `needs-judgment - see judgments/${r.id}/`;
1536
- }
1537
- if (!r.verdict) {
1538
- return r.message ?? r.status;
1539
- }
1540
- return `${r.verdict.label} - ${r.verdict.headline} -> ${r.verdict.action}`;
1541
- }
1542
- function renderRow(r, cwd) {
1543
- return `| ${r.id} | ${escapeCell(baselineCell(r, cwd))} | ${escapeCell(actualCell(r, cwd))} | ${escapeCell(diffCell(r, cwd))} | ${escapeCell(verdictCell(r))} |`;
1544
- }
1545
- function headerLine(report) {
1546
- const { passed, failed, pendingJudgments, totalEntries } = report;
1547
- const parts = [`${passed}/${totalEntries} passed`];
1548
- if (failed > 0) parts.push(`${failed} failed`);
1549
- if (pendingJudgments > 0) parts.push(`${pendingJudgments} pending judgment`);
1550
- return parts.length > 1 ? `${parts[0]} (${parts.slice(1).join(", ")})` : parts[0];
1899
+ };
1551
1900
  }
1552
- function renderSummary(report, cwd = process.cwd()) {
1553
- const nonPass = report.results.filter((r) => r.status !== "pass");
1554
- const lines = [
1555
- `# blazediff check - ${report.createdAt}`,
1556
- "",
1557
- headerLine(report),
1558
- ""
1559
- ];
1560
- if (nonPass.length === 0) {
1561
- lines.push("All entries passed.");
1562
- return `${lines.join("\n")}
1563
- `;
1901
+ var localJudge = createLocalJudge();
1902
+
1903
+ // src/judge/none.ts
1904
+ var noneJudge = {
1905
+ name: "none",
1906
+ async judge(input) {
1907
+ return { kind: "judged", verdict: input.heuristicVerdict };
1564
1908
  }
1565
- lines.push("| id | baseline | actual | diff | verdict |");
1566
- lines.push("| --- | --- | --- | --- | --- |");
1567
- for (const r of nonPass) lines.push(renderRow(r, cwd));
1568
- return `${lines.join("\n")}
1569
- `;
1570
- }
1571
- async function writeSummaryMarkdown(report, cwd = process.cwd()) {
1572
- const file = paths(cwd).summary;
1909
+ };
1910
+ async function writeReport(report, cwd = process.cwd()) {
1911
+ const file = paths(cwd).report;
1573
1912
  await promises.mkdir(path__default.default.dirname(file), { recursive: true });
1574
- await promises.writeFile(file, renderSummary(report, cwd), "utf8");
1913
+ await promises.writeFile(file, `${JSON.stringify(report, null, 2)}
1914
+ `, "utf8");
1575
1915
  return file;
1576
1916
  }
1917
+ async function readReport(cwd = process.cwd()) {
1918
+ return readJsonOrNull(paths(cwd).report);
1919
+ }
1577
1920
 
1578
1921
  // src/judge/apply.ts
1579
1922
  var VALID_LABELS = [
@@ -1611,21 +1954,6 @@ function parseVerdict(raw) {
1611
1954
  confidence: typeof r.confidence === "number" ? r.confidence : void 0
1612
1955
  };
1613
1956
  }
1614
- async function fileExists2(p) {
1615
- try {
1616
- await promises.access(p);
1617
- return true;
1618
- } catch {
1619
- return false;
1620
- }
1621
- }
1622
- async function readJsonOrNull(file) {
1623
- try {
1624
- return JSON.parse(await promises.readFile(file, "utf8"));
1625
- } catch {
1626
- return null;
1627
- }
1628
- }
1629
1957
  async function readJudgmentDirs(root) {
1630
1958
  let names;
1631
1959
  try {
@@ -1723,7 +2051,7 @@ async function reconstructFromDisk(cwd, dirs) {
1723
2051
  pendingJudgments,
1724
2052
  results
1725
2053
  };
1726
- await writeSummaryMarkdown(report, cwd);
2054
+ await writeReport(report, cwd);
1727
2055
  return report;
1728
2056
  }
1729
2057
  async function hasCheckpoint(cwd, threadId) {
@@ -1735,9 +2063,8 @@ async function hasCheckpoint(cwd, threadId) {
1735
2063
  return false;
1736
2064
  }
1737
2065
  }
1738
- async function applyJudgments(opts = process.cwd()) {
1739
- const options = typeof opts === "string" ? { cwd: opts } : opts;
1740
- const cwd = options.cwd ?? process.cwd();
2066
+ async function applyJudgments(opts = {}) {
2067
+ const cwd = opts.cwd ?? process.cwd();
1741
2068
  const manifest = await loadManifest(cwd);
1742
2069
  if (!manifest) {
1743
2070
  throw new Error(
@@ -1771,10 +2098,9 @@ async function applyJudgments(opts = process.cwd()) {
1771
2098
  cwd,
1772
2099
  verdicts,
1773
2100
  threadId,
1774
- onEvent: options.onEvent,
1775
- junitPath: options.junitPath
2101
+ onEvent: opts.onEvent,
2102
+ junitPath: opts.junitPath
1776
2103
  });
1777
- await new FsCheckpointSaver(paths(cwd).checkpoints).deleteThread(threadId).catch(() => void 0);
1778
2104
  return { report, applied, missing, invalid };
1779
2105
  }
1780
2106
  var HOST_INSTRUCTIONS = [
@@ -1784,7 +2110,7 @@ var HOST_INSTRUCTIONS = [
1784
2110
  "Decide whether the change is a regression, an intentional UI change, or rendering noise.",
1785
2111
  "Write your decision to `verdict.json` (next to this `request.json`) with shape:",
1786
2112
  ' { "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 }',
1787
- "Then re-run `blazediff-agent check --apply-judgments --json` to regenerate summary.md."
2113
+ "Then re-run `blazediff-agent check --apply-judgments --json` to regenerate report.json."
1788
2114
  ].join("\n");
1789
2115
  function relTo(cwd, abs) {
1790
2116
  if (!abs) return void 0;
@@ -1792,24 +2118,10 @@ function relTo(cwd, abs) {
1792
2118
  }
1793
2119
  function signatureOf(r) {
1794
2120
  const pct = typeof r.diffPercentage === "number" ? r.diffPercentage.toFixed(4) : "?";
1795
- const regions = r.regions?.length ?? 0;
1796
2121
  const severity = r.severity ?? "?";
1797
- return `${r.status}|diff:${pct}|regions:${regions}|severity:${severity}`;
1798
- }
1799
- async function fileExists3(p) {
1800
- try {
1801
- await promises.access(p);
1802
- return true;
1803
- } catch {
1804
- return false;
1805
- }
1806
- }
1807
- async function readJsonOrNull2(file) {
1808
- try {
1809
- return JSON.parse(await promises.readFile(file, "utf8"));
1810
- } catch {
1811
- return null;
1812
- }
2122
+ const regions = (r.regions ?? []).map((reg) => `${reg.changeType}:${reg.pixelCount}`).sort().join(",");
2123
+ const regionsKey = regions ? `[${regions}]` : "0";
2124
+ return `${r.status}|diff:${pct}|regions:${regionsKey}|severity:${severity}`;
1813
2125
  }
1814
2126
  function entryById(manifest, id) {
1815
2127
  return manifest.entries.find((e) => e.id === id);
@@ -1858,8 +2170,8 @@ async function discoverTiles(dir) {
1858
2170
  const locatorAbs = path__default.default.join(dir, "locator.png");
1859
2171
  const tilesAbs = path__default.default.join(dir, "regions.png");
1860
2172
  const [locator, tiles] = await Promise.all([
1861
- fileExists3(locatorAbs),
1862
- fileExists3(tilesAbs)
2173
+ fileExists2(locatorAbs),
2174
+ fileExists2(tilesAbs)
1863
2175
  ]);
1864
2176
  return {
1865
2177
  locatorPath: locator ? "locator.png" : void 0,
@@ -1876,7 +2188,7 @@ async function writeJudgments(opts) {
1876
2188
  opts.report.results.map(async (result) => {
1877
2189
  const dir = path__default.default.join(root, result.id);
1878
2190
  if (result.status === "pass") {
1879
- if (await fileExists3(dir))
2191
+ if (await fileExists2(dir))
1880
2192
  await promises.rm(dir, { recursive: true, force: true });
1881
2193
  return;
1882
2194
  }
@@ -1888,9 +2200,9 @@ async function writeJudgments(opts) {
1888
2200
  const requestFile = path__default.default.join(dir, "request.json");
1889
2201
  const verdictFile = path__default.default.join(dir, "verdict.json");
1890
2202
  const [prior, priorVerdict] = await Promise.all([
1891
- readJsonOrNull2(requestFile),
1892
- fileExists3(verdictFile).then(
1893
- (exists) => exists ? readJsonOrNull2(verdictFile) : null
2203
+ readJsonOrNull(requestFile),
2204
+ fileExists2(verdictFile).then(
2205
+ (exists) => exists ? readJsonOrNull(verdictFile) : null
1894
2206
  )
1895
2207
  ]);
1896
2208
  const signatureMatches = prior !== null && prior.signature === request.signature;
@@ -1900,68 +2212,356 @@ async function writeJudgments(opts) {
1900
2212
  `,
1901
2213
  "utf8"
1902
2214
  );
1903
- if (priorVerdict && signatureMatches) {
1904
- return;
2215
+ if (priorVerdict && signatureMatches) {
2216
+ return;
2217
+ }
2218
+ const auto = autoVerdict(result);
2219
+ if (auto) {
2220
+ await promises.writeFile(
2221
+ verdictFile,
2222
+ `${JSON.stringify(auto, null, 2)}
2223
+ `,
2224
+ "utf8"
2225
+ );
2226
+ } else if (priorVerdict && !signatureMatches) {
2227
+ await promises.rm(verdictFile, { force: true });
2228
+ }
2229
+ })
2230
+ );
2231
+ let entries;
2232
+ try {
2233
+ entries = await promises.readdir(root);
2234
+ } catch {
2235
+ return;
2236
+ }
2237
+ await Promise.all(
2238
+ entries.filter((name) => !knownIds.has(name)).map(
2239
+ (name) => promises.rm(path__default.default.join(root, name), { recursive: true, force: true })
2240
+ )
2241
+ );
2242
+ }
2243
+
2244
+ // src/judge/index.ts
2245
+ function resolveJudge(backend) {
2246
+ switch (backend) {
2247
+ case "none":
2248
+ return noneJudge;
2249
+ case "host":
2250
+ return codingAgentHostJudge;
2251
+ case "local":
2252
+ return localJudge;
2253
+ }
2254
+ }
2255
+ function escapeXml(value) {
2256
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2257
+ }
2258
+ async function writeJunit(report, destPath) {
2259
+ await promises.mkdir(path__default.default.dirname(destPath), { recursive: true });
2260
+ const cases = report.results.map((r) => {
2261
+ if (r.status === "pass") {
2262
+ return ` <testcase classname="blazediff" name="${escapeXml(r.id)}"/>`;
2263
+ }
2264
+ const message = r.message ?? r.status;
2265
+ return ` <testcase classname="blazediff" name="${escapeXml(r.id)}">
2266
+ <failure message="${escapeXml(message)}" type="${escapeXml(r.status)}">${escapeXml(message)}</failure>
2267
+ </testcase>`;
2268
+ });
2269
+ const failures = report.totalEntries - report.passed;
2270
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
2271
+ <testsuites>
2272
+ <testsuite name="blazediff" tests="${report.totalEntries}" failures="${failures}">
2273
+ ${cases.join("\n")}
2274
+ </testsuite>
2275
+ </testsuites>
2276
+ `;
2277
+ await promises.writeFile(destPath, xml, "utf8");
2278
+ return destPath;
2279
+ }
2280
+ var ROOT_NS_SENTINEL = "_root";
2281
+ function nsDir(ns) {
2282
+ return ns === "" ? ROOT_NS_SENTINEL : ns;
2283
+ }
2284
+ function encode(buf) {
2285
+ return Buffer.from(buf).toString("base64");
2286
+ }
2287
+ function decode(s) {
2288
+ return Buffer.from(s, "base64");
2289
+ }
2290
+ async function readJson(file) {
2291
+ try {
2292
+ const raw = await promises.readFile(file, "utf8");
2293
+ return JSON.parse(raw);
2294
+ } catch (err) {
2295
+ if (err.code === "ENOENT") return void 0;
2296
+ throw err;
2297
+ }
2298
+ }
2299
+ async function writeJsonAtomic(file, value) {
2300
+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
2301
+ await promises.writeFile(tmp, JSON.stringify(value), "utf8");
2302
+ await promises.rename(tmp, file);
2303
+ }
2304
+ var FsCheckpointSaver = class extends langgraphCheckpoint.BaseCheckpointSaver {
2305
+ constructor(root, serde) {
2306
+ super(serde);
2307
+ this.locks = /* @__PURE__ */ new Map();
2308
+ this.root = root;
2309
+ }
2310
+ threadDir(thread) {
2311
+ return path__default.default.join(this.root, thread);
2312
+ }
2313
+ nsPath(thread, ns) {
2314
+ return path__default.default.join(this.threadDir(thread), nsDir(ns));
2315
+ }
2316
+ ckptFile(thread, ns, id) {
2317
+ return path__default.default.join(this.nsPath(thread, ns), `${id}.ckpt.json`);
2318
+ }
2319
+ writesFile(thread, ns, id) {
2320
+ return path__default.default.join(this.nsPath(thread, ns), `${id}.writes.json`);
2321
+ }
2322
+ async withLock(key, fn) {
2323
+ const prev = this.locks.get(key) ?? Promise.resolve();
2324
+ const next = prev.then(fn, fn);
2325
+ this.locks.set(key, next);
2326
+ try {
2327
+ return await next;
2328
+ } finally {
2329
+ if (this.locks.get(key) === next) this.locks.delete(key);
2330
+ }
2331
+ }
2332
+ async listCheckpointIds(thread, ns) {
2333
+ try {
2334
+ const names = await promises.readdir(this.nsPath(thread, ns));
2335
+ const suffix = ".ckpt.json";
2336
+ return names.filter((n) => n.endsWith(suffix)).map((n) => n.slice(0, -suffix.length));
2337
+ } catch (err) {
2338
+ if (err.code === "ENOENT") return [];
2339
+ throw err;
2340
+ }
2341
+ }
2342
+ async listNamespaces(thread) {
2343
+ try {
2344
+ return await promises.readdir(this.threadDir(thread));
2345
+ } catch (err) {
2346
+ if (err.code === "ENOENT") return [];
2347
+ throw err;
2348
+ }
2349
+ }
2350
+ async listThreads() {
2351
+ try {
2352
+ return await promises.readdir(this.root);
2353
+ } catch (err) {
2354
+ if (err.code === "ENOENT") return [];
2355
+ throw err;
2356
+ }
2357
+ }
2358
+ decodeNs(nsDirName) {
2359
+ return nsDirName === ROOT_NS_SENTINEL ? "" : nsDirName;
2360
+ }
2361
+ async loadPendingWrites(thread, ns, ckptId) {
2362
+ const data = await readJson(
2363
+ this.writesFile(thread, ns, ckptId)
2364
+ );
2365
+ if (!data) return [];
2366
+ const out = [];
2367
+ for (const [taskId, channel, serialized] of Object.values(data)) {
2368
+ const value = await this.serde.loadsTyped("json", decode(serialized));
2369
+ out.push([taskId, channel, value]);
2370
+ }
2371
+ return out;
2372
+ }
2373
+ async migratePendingSends(checkpoint, thread, ns, parentCheckpointId) {
2374
+ const data = await readJson(
2375
+ this.writesFile(thread, ns, parentCheckpointId)
2376
+ );
2377
+ const pendingSends = data ? await Promise.all(
2378
+ Object.values(data).filter(([, channel]) => channel === langgraphCheckpoint.TASKS).map(
2379
+ ([, , serialized]) => this.serde.loadsTyped("json", decode(serialized))
2380
+ )
2381
+ ) : [];
2382
+ const m = checkpoint;
2383
+ m.channel_values ?? (m.channel_values = {});
2384
+ m.channel_values[langgraphCheckpoint.TASKS] = pendingSends;
2385
+ m.channel_versions ?? (m.channel_versions = {});
2386
+ const versions = Object.values(m.channel_versions);
2387
+ m.channel_versions[langgraphCheckpoint.TASKS] = versions.length > 0 ? langgraphCheckpoint.maxChannelVersion(...versions) : this.getNextVersion(void 0);
2388
+ }
2389
+ async readTuple(thread, ns, ckptId, config) {
2390
+ const data = await readJson(this.ckptFile(thread, ns, ckptId));
2391
+ if (!data) return void 0;
2392
+ const checkpoint = await this.serde.loadsTyped(
2393
+ "json",
2394
+ decode(data.checkpoint)
2395
+ );
2396
+ const metadata = await this.serde.loadsTyped(
2397
+ "json",
2398
+ decode(data.metadata)
2399
+ );
2400
+ if (checkpoint.v < 4 && data.parentCheckpointId !== void 0) {
2401
+ await this.migratePendingSends(
2402
+ checkpoint,
2403
+ thread,
2404
+ ns,
2405
+ data.parentCheckpointId
2406
+ );
2407
+ }
2408
+ const pendingWrites = await this.loadPendingWrites(thread, ns, ckptId);
2409
+ const tuple = {
2410
+ config,
2411
+ checkpoint,
2412
+ metadata,
2413
+ pendingWrites
2414
+ };
2415
+ if (data.parentCheckpointId !== void 0) {
2416
+ tuple.parentConfig = {
2417
+ configurable: {
2418
+ thread_id: thread,
2419
+ checkpoint_ns: ns,
2420
+ checkpoint_id: data.parentCheckpointId
2421
+ }
2422
+ };
2423
+ }
2424
+ return tuple;
2425
+ }
2426
+ async getTuple(config) {
2427
+ const thread = config.configurable?.thread_id;
2428
+ if (!thread) return void 0;
2429
+ const ns = config.configurable?.checkpoint_ns ?? "";
2430
+ const explicitId = langgraphCheckpoint.getCheckpointId(config);
2431
+ if (explicitId) {
2432
+ return this.readTuple(thread, ns, explicitId, config);
2433
+ }
2434
+ const ids = (await this.listCheckpointIds(thread, ns)).sort(
2435
+ (a, b) => b.localeCompare(a)
2436
+ );
2437
+ if (ids.length === 0) return void 0;
2438
+ const ckptId = ids[0];
2439
+ return this.readTuple(thread, ns, ckptId, {
2440
+ configurable: {
2441
+ thread_id: thread,
2442
+ checkpoint_ns: ns,
2443
+ checkpoint_id: ckptId
1905
2444
  }
1906
- const auto = autoVerdict(result);
1907
- if (auto) {
1908
- await promises.writeFile(
1909
- verdictFile,
1910
- `${JSON.stringify(auto, null, 2)}
1911
- `,
1912
- "utf8"
2445
+ });
2446
+ }
2447
+ async *list(config, options) {
2448
+ const filter = options?.filter;
2449
+ const before = options?.before;
2450
+ let limit = options?.limit;
2451
+ const configThread = config.configurable?.thread_id;
2452
+ const configNs = config.configurable?.checkpoint_ns;
2453
+ const configCkptId = config.configurable?.checkpoint_id;
2454
+ const threads = configThread ? [configThread] : await this.listThreads();
2455
+ for (const thread of threads) {
2456
+ const nsNames = await this.listNamespaces(thread);
2457
+ for (const nsName of nsNames) {
2458
+ const ns = this.decodeNs(nsName);
2459
+ if (configNs !== void 0 && ns !== configNs) continue;
2460
+ const ids = (await this.listCheckpointIds(thread, ns)).sort(
2461
+ (a, b) => b.localeCompare(a)
1913
2462
  );
1914
- } else if (priorVerdict && !signatureMatches) {
1915
- await promises.rm(verdictFile, { force: true });
2463
+ for (const ckptId of ids) {
2464
+ if (configCkptId && ckptId !== configCkptId) continue;
2465
+ if (before?.configurable?.checkpoint_id && ckptId >= before.configurable.checkpoint_id)
2466
+ continue;
2467
+ const tuple = await this.readTuple(thread, ns, ckptId, {
2468
+ configurable: {
2469
+ thread_id: thread,
2470
+ checkpoint_ns: ns,
2471
+ checkpoint_id: ckptId
2472
+ }
2473
+ });
2474
+ if (!tuple) continue;
2475
+ if (filter) {
2476
+ const md = tuple.metadata;
2477
+ const matches = Object.entries(filter).every(
2478
+ ([k, v]) => md?.[k] === v
2479
+ );
2480
+ if (!matches) continue;
2481
+ }
2482
+ if (limit !== void 0) {
2483
+ if (limit <= 0) return;
2484
+ limit -= 1;
2485
+ }
2486
+ yield tuple;
2487
+ }
1916
2488
  }
1917
- })
1918
- );
1919
- let entries;
1920
- try {
1921
- entries = await promises.readdir(root);
1922
- } catch {
1923
- return;
2489
+ }
1924
2490
  }
1925
- await Promise.all(
1926
- entries.filter((name) => !knownIds.has(name)).map(
1927
- (name) => promises.rm(path__default.default.join(root, name), { recursive: true, force: true })
1928
- )
1929
- );
1930
- }
1931
-
1932
- // src/judge/index.ts
1933
- function resolveJudge(backend) {
1934
- switch (backend) {
1935
- case "none":
1936
- return noneJudge;
1937
- case "host":
1938
- return hostHarnessJudge;
2491
+ async put(config, checkpoint, metadata) {
2492
+ const thread = config.configurable?.thread_id;
2493
+ if (!thread) {
2494
+ throw new Error(
2495
+ 'FsCheckpointSaver: missing "thread_id" in configurable. Pass `{ configurable: { thread_id } }` when streaming.'
2496
+ );
2497
+ }
2498
+ const ns = config.configurable?.checkpoint_ns ?? "";
2499
+ const parentCheckpointId = config.configurable?.checkpoint_id;
2500
+ const prepared = langgraphCheckpoint.copyCheckpoint(checkpoint);
2501
+ const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([
2502
+ this.serde.dumpsTyped(prepared),
2503
+ this.serde.dumpsTyped(metadata)
2504
+ ]);
2505
+ await promises.mkdir(this.nsPath(thread, ns), { recursive: true });
2506
+ const file = this.ckptFile(thread, ns, checkpoint.id);
2507
+ const body = {
2508
+ checkpoint: encode(serializedCheckpoint),
2509
+ metadata: encode(serializedMetadata),
2510
+ parentCheckpointId
2511
+ };
2512
+ await writeJsonAtomic(file, body);
2513
+ return {
2514
+ configurable: {
2515
+ thread_id: thread,
2516
+ checkpoint_ns: ns,
2517
+ checkpoint_id: checkpoint.id
2518
+ }
2519
+ };
1939
2520
  }
1940
- }
1941
- function escapeXml(value) {
1942
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1943
- }
1944
- async function writeJunit(report, destPath) {
1945
- await promises.mkdir(path__default.default.dirname(destPath), { recursive: true });
1946
- const cases = report.results.map((r) => {
1947
- if (r.status === "pass") {
1948
- return ` <testcase classname="blazediff" name="${escapeXml(r.id)}"/>`;
2521
+ async putWrites(config, writes, taskId) {
2522
+ const thread = config.configurable?.thread_id;
2523
+ if (!thread) {
2524
+ throw new Error(
2525
+ 'FsCheckpointSaver: missing "thread_id" in configurable for putWrites.'
2526
+ );
1949
2527
  }
1950
- const message = r.message ?? r.status;
1951
- return ` <testcase classname="blazediff" name="${escapeXml(r.id)}">
1952
- <failure message="${escapeXml(message)}" type="${escapeXml(r.status)}">${escapeXml(message)}</failure>
1953
- </testcase>`;
1954
- });
1955
- const failures = report.totalEntries - report.passed;
1956
- const xml = `<?xml version="1.0" encoding="UTF-8"?>
1957
- <testsuites>
1958
- <testsuite name="blazediff" tests="${report.totalEntries}" failures="${failures}">
1959
- ${cases.join("\n")}
1960
- </testsuite>
1961
- </testsuites>
1962
- `;
1963
- await promises.writeFile(destPath, xml, "utf8");
1964
- return destPath;
2528
+ const ns = config.configurable?.checkpoint_ns ?? "";
2529
+ const ckptId = config.configurable?.checkpoint_id;
2530
+ if (!ckptId) {
2531
+ throw new Error(
2532
+ 'FsCheckpointSaver: missing "checkpoint_id" in configurable for putWrites.'
2533
+ );
2534
+ }
2535
+ const key = `${thread}|${ns}|${ckptId}`;
2536
+ await this.withLock(key, async () => {
2537
+ const existing = await readJson(this.writesFile(thread, ns, ckptId)) ?? {};
2538
+ let mutated = false;
2539
+ for (let idx = 0; idx < writes.length; idx++) {
2540
+ const [channel, value] = writes[idx];
2541
+ const writeIdx = langgraphCheckpoint.WRITES_IDX_MAP[channel] ?? idx;
2542
+ const innerKey = `${taskId},${writeIdx}`;
2543
+ if (writeIdx >= 0 && innerKey in existing) continue;
2544
+ const [, serialized] = await this.serde.dumpsTyped(value);
2545
+ existing[innerKey] = [taskId, channel, encode(serialized)];
2546
+ mutated = true;
2547
+ }
2548
+ if (!mutated) return;
2549
+ await promises.mkdir(this.nsPath(thread, ns), { recursive: true });
2550
+ await writeJsonAtomic(this.writesFile(thread, ns, ckptId), existing);
2551
+ });
2552
+ }
2553
+ async deleteThread(threadId) {
2554
+ await promises.rm(this.threadDir(threadId), { recursive: true, force: true });
2555
+ }
2556
+ };
2557
+
2558
+ // src/graph/events.ts
2559
+ var sink;
2560
+ function setEventSink(fn) {
2561
+ sink = fn;
2562
+ }
2563
+ function emitEvent(event) {
2564
+ sink?.(event);
1965
2565
  }
1966
2566
 
1967
2567
  // src/graph/nodes/results.ts
@@ -2016,6 +2616,8 @@ function failResult(entry, outcome, actualPath, baselinePath, verdict) {
2016
2616
  diffPercentage: outcome.diffPercentage,
2017
2617
  severity: outcome.interpretation?.severity,
2018
2618
  regions: outcome.interpretation?.regions?.map(narrowRegion),
2619
+ width: outcome.interpretation?.width,
2620
+ height: outcome.interpretation?.height,
2019
2621
  verdict,
2020
2622
  diffPath: outcome.diffPath,
2021
2623
  baselinePath,
@@ -2124,6 +2726,10 @@ function makeCaptureNode(semaphore) {
2124
2726
  );
2125
2727
  }
2126
2728
  }
2729
+ for (const item of items) {
2730
+ if (item.output.captureOutputPath)
2731
+ emitEvent({ type: "captured", entryId: item.entry.id });
2732
+ }
2127
2733
  return { captured: items };
2128
2734
  } catch (err) {
2129
2735
  if (err instanceof HarnessError) {
@@ -2352,6 +2958,7 @@ async function judgeNode(state) {
2352
2958
  throw new Error("judgeNode: entry, options, or diff missing");
2353
2959
  }
2354
2960
  if (diff.skipResult) {
2961
+ emitEvent({ type: "result", result: diff.skipResult });
2355
2962
  return { results: [diff.skipResult] };
2356
2963
  }
2357
2964
  const outcome = diff.outcome;
@@ -2361,7 +2968,9 @@ async function judgeNode(state) {
2361
2968
  throw new Error("judgeNode: diff outputs missing");
2362
2969
  }
2363
2970
  if (outcome.match) {
2364
- return { results: [passResult(entry, baselinePath, captureOutputPath)] };
2971
+ const r = passResult(entry, baselinePath, captureOutputPath);
2972
+ emitEvent({ type: "result", result: r });
2973
+ return { results: [r] };
2365
2974
  }
2366
2975
  const verdict = deriveVerdict({
2367
2976
  reason: outcome.reason,
@@ -2369,48 +2978,62 @@ async function judgeNode(state) {
2369
2978
  diffCount: outcome.diffCount,
2370
2979
  diffPercentage: outcome.diffPercentage
2371
2980
  });
2372
- let result = failResult(
2981
+ const initial = failResult(
2373
2982
  entry,
2374
2983
  outcome,
2375
2984
  captureOutputPath,
2376
2985
  baselinePath,
2377
2986
  verdict
2378
2987
  );
2379
- if (result.baselinePath && result.actualPath) {
2380
- const judge = resolveJudge(options.judge);
2381
- const output = await judge.judge(
2382
- {
2383
- entry,
2384
- baselinePath: result.baselinePath,
2385
- actualPath: result.actualPath,
2386
- diffPath: result.diffPath,
2387
- regions: result.regions,
2388
- diffPercentage: result.diffPercentage,
2389
- severity: result.severity,
2390
- heuristicVerdict: result.verdict ?? verdict
2391
- },
2392
- options.cwd
2988
+ if (!initial.baselinePath || !initial.actualPath) {
2989
+ emitEvent({ type: "result", result: initial });
2990
+ return { results: [initial] };
2991
+ }
2992
+ const judge = resolveJudge(options.judge);
2993
+ const output = await judge.judge(
2994
+ {
2995
+ entry,
2996
+ baselinePath: initial.baselinePath,
2997
+ actualPath: initial.actualPath,
2998
+ diffPath: initial.diffPath,
2999
+ regions: initial.regions,
3000
+ diffPercentage: initial.diffPercentage,
3001
+ severity: initial.severity,
3002
+ heuristicVerdict: initial.verdict ?? verdict,
3003
+ onJudgingStart: options.judge !== "none" ? () => emitEvent({ type: "judging", entryId: entry.id, url: entry.url }) : void 0
3004
+ },
3005
+ options.cwd
3006
+ );
3007
+ let final;
3008
+ if (output.kind === "judged") {
3009
+ final = { ...initial, verdict: output.verdict };
3010
+ } else if (output.kind === "failed") {
3011
+ console.warn(
3012
+ `[blazediff] judge "${judge.name}" failed for ${entry.id} (${output.reason}): ${output.error.message}`
2393
3013
  );
2394
- if (output.kind === "judged") {
2395
- result = { ...result, verdict: output.verdict };
2396
- } else {
2397
- const pending = {
2398
- ...result,
2399
- status: "needs-judgment",
2400
- message: `awaiting judgment in ${output.requestPath}`
2401
- };
2402
- const resumed = interruptForJudgment({
2403
- kind: "host-judgment-required",
2404
- entryId: entry.id,
2405
- url: entry.url,
2406
- requestPath: output.requestPath,
2407
- signature: signatureOf(result),
2408
- pendingResult: pending
2409
- });
2410
- result = resumed ? { ...result, verdict: resumed } : pending;
2411
- }
3014
+ final = {
3015
+ ...initial,
3016
+ verdict: output.fallback,
3017
+ message: `${initial.message ?? ""}${initial.message ? " \u2014 " : ""}judge failed (${output.reason}): ${output.error.message}`
3018
+ };
3019
+ } else {
3020
+ const pending = {
3021
+ ...initial,
3022
+ status: "needs-judgment",
3023
+ message: `awaiting judgment in ${output.requestPath}`
3024
+ };
3025
+ const resumed = interruptForJudgment({
3026
+ kind: "host-judgment-required",
3027
+ entryId: entry.id,
3028
+ url: entry.url,
3029
+ requestPath: output.requestPath,
3030
+ signature: signatureOf(initial),
3031
+ pendingResult: pending
3032
+ });
3033
+ final = resumed ? { ...initial, verdict: resumed } : pending;
2412
3034
  }
2413
- return { results: [result] };
3035
+ emitEvent({ type: "result", result: final });
3036
+ return { results: [final] };
2414
3037
  }
2415
3038
 
2416
3039
  // src/graph/nodes/load.ts
@@ -2426,75 +3049,46 @@ async function loadNode(state) {
2426
3049
  }
2427
3050
  return { entries: manifest.entries, manifest };
2428
3051
  }
2429
- var resultsChannel = langgraph.Annotation({
3052
+ var latest = () => langgraph.Annotation({
3053
+ reducer: (acc, next) => next ?? acc,
3054
+ default: () => void 0
3055
+ });
3056
+ var appendList = () => langgraph.Annotation({
2430
3057
  reducer: (acc, next) => [...acc, ...next],
2431
3058
  default: () => []
2432
3059
  });
2433
- var capturedChannel = langgraph.Annotation({
2434
- reducer: (acc, next) => [...acc, ...next],
3060
+ var replaceList = () => langgraph.Annotation({
3061
+ reducer: (acc, next) => next ?? acc,
2435
3062
  default: () => []
2436
3063
  });
3064
+ var resultsChannel = appendList();
3065
+ var capturedChannel = appendList();
2437
3066
  var CaptureState = langgraph.Annotation.Root({
2438
- entry: langgraph.Annotation({
2439
- reducer: (_, next) => next,
2440
- default: () => void 0
2441
- }),
3067
+ entry: latest(),
2442
3068
  children: langgraph.Annotation({
2443
3069
  reducer: (_, next) => next,
2444
3070
  default: () => []
2445
3071
  }),
2446
- options: langgraph.Annotation({
2447
- reducer: (acc, next) => next ?? acc,
2448
- default: () => void 0
2449
- }),
3072
+ options: latest(),
2450
3073
  captured: capturedChannel
2451
3074
  });
2452
3075
  var BranchState = langgraph.Annotation.Root({
2453
- entry: langgraph.Annotation({
2454
- reducer: (_, next) => next,
2455
- default: () => void 0
2456
- }),
2457
- options: langgraph.Annotation({
2458
- reducer: (acc, next) => next ?? acc,
2459
- default: () => void 0
2460
- }),
2461
- captureOutput: langgraph.Annotation({
2462
- reducer: (_, next) => next,
2463
- default: () => void 0
2464
- }),
2465
- diffOutput: langgraph.Annotation({
2466
- reducer: (_, next) => next,
2467
- default: () => void 0
2468
- }),
3076
+ entry: latest(),
3077
+ options: latest(),
3078
+ captureOutput: latest(),
3079
+ diffOutput: latest(),
2469
3080
  results: resultsChannel
2470
3081
  });
2471
3082
  var GraphState = langgraph.Annotation.Root({
2472
- options: langgraph.Annotation({
2473
- reducer: (acc, next) => next ?? acc,
2474
- default: () => void 0
2475
- }),
2476
- entries: langgraph.Annotation({
2477
- reducer: (acc, next) => next ?? acc,
2478
- default: () => []
2479
- }),
3083
+ options: latest(),
3084
+ entries: replaceList(),
2480
3085
  captured: capturedChannel,
2481
3086
  results: resultsChannel,
2482
- manifest: langgraph.Annotation({
2483
- reducer: (acc, next) => next ?? acc,
2484
- default: () => void 0
2485
- }),
2486
- report: langgraph.Annotation({
2487
- reducer: (acc, next) => next ?? acc,
2488
- default: () => void 0
2489
- })
3087
+ manifest: latest(),
3088
+ report: latest()
2490
3089
  });
2491
3090
 
2492
3091
  // src/graph/index.ts
2493
- function cpuParallelism() {
2494
- const cores = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length;
2495
- if (!cores || !Number.isFinite(cores)) return 2;
2496
- return Math.max(2, cores);
2497
- }
2498
3092
  function threadIdFor(cwd) {
2499
3093
  return crypto$1.createHash("sha1").update(paths(cwd).manifest).digest("hex").slice(0, 16);
2500
3094
  }
@@ -2504,7 +3098,8 @@ function buildCaptureGraph(captureSemaphore) {
2504
3098
  function buildBranchGraph(diffSemaphore) {
2505
3099
  return new langgraph.StateGraph(BranchState).addNode("diff", makeDiffNode(diffSemaphore)).addNode("judge", judgeNode).addEdge(langgraph.START, "diff").addEdge("diff", "judge").addEdge("judge", langgraph.END).compile();
2506
3100
  }
2507
- function dispatchNode() {
3101
+ async function dispatchNode(state) {
3102
+ if (state.options) await resolveJudge(state.options.judge).warmup?.();
2508
3103
  return {};
2509
3104
  }
2510
3105
  function buildGraph(captureSemaphore, diffSemaphore, checkpointer) {
@@ -2557,10 +3152,7 @@ async function streamGraph(graph, input, threadId, onEvent) {
2557
3152
  const part = partial;
2558
3153
  if (!part) continue;
2559
3154
  if (part.results) {
2560
- for (const r of part.results) {
2561
- collect.results.push(r);
2562
- onEvent?.({ type: "result", result: r });
2563
- }
3155
+ for (const r of part.results) collect.results.push(r);
2564
3156
  }
2565
3157
  if (part.manifest) collect.manifest = part.manifest;
2566
3158
  if (part.report) {
@@ -2594,15 +3186,15 @@ async function buildPartialReport(collect, cwd) {
2594
3186
  if (manifest) {
2595
3187
  await writeJudgments({ report, manifest, cwd });
2596
3188
  }
2597
- await writeSummaryMarkdown(report, cwd);
3189
+ await writeReport(report, cwd);
2598
3190
  await ensureGitignore(cwd);
2599
3191
  return report;
2600
3192
  }
2601
3193
  async function runGraph(opts) {
2602
3194
  const cwd = opts.cwd ?? process.cwd();
2603
3195
  const concurrency = opts.concurrency ?? defaultConcurrency();
2604
- const captureSemaphore = new Semaphore(concurrency);
2605
- const diffSemaphore = new Semaphore(cpuParallelism());
3196
+ const captureSemaphore = createSemaphore(concurrency);
3197
+ const diffSemaphore = createSemaphore(cpuCores());
2606
3198
  const baselinesDir = paths(cwd).baselines;
2607
3199
  const checkpointer = new FsCheckpointSaver(paths(cwd).checkpoints);
2608
3200
  const graph = buildGraph(captureSemaphore, diffSemaphore, checkpointer);
@@ -2622,9 +3214,11 @@ async function runGraph(opts) {
2622
3214
  }
2623
3215
  };
2624
3216
  let collect;
3217
+ setEventSink(opts.onEvent);
2625
3218
  try {
2626
3219
  collect = await streamGraph(graph, input, threadId, opts.onEvent);
2627
3220
  } finally {
3221
+ setEventSink(void 0);
2628
3222
  await closeBrowser();
2629
3223
  }
2630
3224
  const report = collect.report ?? await buildPartialReport(collect, cwd);
@@ -2650,9 +3244,126 @@ function runCheck(opts) {
2650
3244
  return runGraph(opts);
2651
3245
  }
2652
3246
 
3247
+ // src/review/map.ts
3248
+ var DEFAULT_DIMS = { width: 1280, height: 800 };
3249
+ function mapLabelToClass(label) {
3250
+ switch (label) {
3251
+ case "regression-likely":
3252
+ return "regression";
3253
+ case "ambiguous":
3254
+ return "layout-shift";
3255
+ default:
3256
+ return "intentional-likely";
3257
+ }
3258
+ }
3259
+ function mapRegion(region, index) {
3260
+ return {
3261
+ id: index + 1,
3262
+ bbox: {
3263
+ x: region.bbox.x,
3264
+ y: region.bbox.y,
3265
+ w: region.bbox.width,
3266
+ h: region.bbox.height
3267
+ },
3268
+ kind: region.changeType,
3269
+ pixels: region.pixelCount,
3270
+ change: region.percentage
3271
+ };
3272
+ }
3273
+ function reviewStatus(r) {
3274
+ if (r.review === "approved") return "approved";
3275
+ if (r.review === "rejected") return "rejected";
3276
+ return "unreviewed";
3277
+ }
3278
+ function mapResultToEntry(r) {
3279
+ return {
3280
+ id: r.id,
3281
+ name: r.id,
3282
+ url: r.url,
3283
+ width: r.width ?? DEFAULT_DIMS.width,
3284
+ height: r.height ?? DEFAULT_DIMS.height,
3285
+ diff: r.diffPercentage ?? 0,
3286
+ classification: mapLabelToClass(r.verdict?.label),
3287
+ severity: r.severity ?? "low",
3288
+ action: r.verdict?.action ?? "investigate",
3289
+ summary: r.verdict?.headline ?? r.message ?? r.status,
3290
+ changes: r.verdict?.rationale ?? [],
3291
+ regions: (r.regions ?? []).map(mapRegion),
3292
+ status: reviewStatus(r),
3293
+ reviewedBy: r.review ? "you" : void 0
3294
+ };
3295
+ }
3296
+
3297
+ // src/review/actions.ts
3298
+ function recountReport(report) {
3299
+ const passed = report.results.filter((r) => r.status === "pass").length;
3300
+ const pending = report.results.filter(
3301
+ (r) => r.status === "needs-judgment"
3302
+ ).length;
3303
+ report.passed = passed;
3304
+ report.pendingJudgments = pending;
3305
+ report.failed = report.results.length - passed - pending;
3306
+ }
3307
+ async function approveEntry(id, cwd = process.cwd()) {
3308
+ const p = paths(cwd);
3309
+ const actualPng = path__default.default.join(p.actual, `${id}.png`);
3310
+ if (!fs.existsSync(actualPng)) return null;
3311
+ await promises.mkdir(p.baselines, { recursive: true });
3312
+ await promises.copyFile(actualPng, path__default.default.join(p.baselines, `${id}.png`));
3313
+ await Promise.all([
3314
+ promises.rm(actualPng, { force: true }),
3315
+ promises.rm(path__default.default.join(p.actual, `${id}.diff.png`), { force: true }),
3316
+ promises.rm(path__default.default.join(p.judgments, id), { recursive: true, force: true })
3317
+ ]);
3318
+ const report = await readReport(cwd);
3319
+ const result = report?.results.find((r) => r.id === id);
3320
+ if (!report || !result) return null;
3321
+ result.status = "pass";
3322
+ result.review = "approved";
3323
+ result.diffPercentage = void 0;
3324
+ result.diffCount = void 0;
3325
+ result.regions = void 0;
3326
+ result.verdict = void 0;
3327
+ result.diffPath = void 0;
3328
+ recountReport(report);
3329
+ await writeReport(report, cwd);
3330
+ return mapResultToEntry(result);
3331
+ }
3332
+ async function rejectEntry(id, cwd = process.cwd()) {
3333
+ const report = await readReport(cwd);
3334
+ const result = report?.results.find((r) => r.id === id);
3335
+ if (!report || !result) return null;
3336
+ const verdict = {
3337
+ label: "regression-likely",
3338
+ headline: result.verdict?.headline ?? "Confirmed regression during review",
3339
+ rationale: result.verdict?.rationale ?? [],
3340
+ action: "investigate"
3341
+ };
3342
+ const p = paths(cwd);
3343
+ const dir = path__default.default.join(p.judgments, id);
3344
+ await promises.mkdir(dir, { recursive: true });
3345
+ await promises.writeFile(
3346
+ path__default.default.join(dir, "verdict.json"),
3347
+ `${JSON.stringify({ id, verdict, rationale: "rejected via review" }, null, 2)}
3348
+ `,
3349
+ "utf8"
3350
+ );
3351
+ const updated = {
3352
+ ...result,
3353
+ status: "fail",
3354
+ review: "rejected",
3355
+ verdict
3356
+ };
3357
+ report.results = report.results.map((r) => r.id === id ? updated : r);
3358
+ recountReport(report);
3359
+ await writeReport(report, cwd);
3360
+ return mapResultToEntry(updated);
3361
+ }
3362
+
2653
3363
  exports.HarnessError = HarnessError;
2654
3364
  exports.STABILITY_HOOKS_VERSION = STABILITY_HOOKS_VERSION;
2655
3365
  exports.applyJudgments = applyJudgments;
3366
+ exports.approveEntry = approveEntry;
2656
3367
  exports.assertLeftLoginPage = assertLeftLoginPage;
2657
3368
  exports.captureScreenshot = captureScreenshot;
2658
3369
  exports.configHash = configHash;
@@ -2664,6 +3375,8 @@ exports.loadEnvFiles = loadEnvFiles;
2664
3375
  exports.loadHarness = loadHarness;
2665
3376
  exports.loadManifest = loadManifest;
2666
3377
  exports.paths = paths;
3378
+ exports.readReport = readReport;
3379
+ exports.rejectEntry = rejectEntry;
2667
3380
  exports.resolveBaseUrl = resolveBaseUrl;
2668
3381
  exports.resolveHarnessFile = resolveHarnessFile;
2669
3382
  exports.resolveJudge = resolveJudge;
@@ -2674,3 +3387,4 @@ exports.runGraph = runGraph;
2674
3387
  exports.saveConfig = saveConfig;
2675
3388
  exports.saveManifest = saveManifest;
2676
3389
  exports.threadIdFor = threadIdFor;
3390
+ exports.writeReport = writeReport;