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