@blazediff/agent 0.2.1 → 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
@@ -3,22 +3,44 @@
3
3
  var promises = require('fs/promises');
4
4
  var path = require('path');
5
5
  var os = require('os');
6
+ var fs = require('fs');
7
+ var url = require('url');
6
8
  var playwright = require('playwright');
7
9
  var child_process = require('child_process');
8
- var fs = require('fs');
9
10
  var module$1 = require('module');
10
- var url = require('url');
11
11
  var crypto$1 = require('crypto');
12
12
  var coreNative = require('@blazediff/core-native');
13
+ var util = require('util');
13
14
  var langgraph = require('@langchain/langgraph');
14
15
  var sharp = require('sharp');
16
+ var pc = require('picocolors');
15
17
  var langgraphCheckpoint = require('@langchain/langgraph-checkpoint');
16
18
 
17
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
18
20
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
19
21
 
22
+ function _interopNamespace(e) {
23
+ if (e && e.__esModule) return e;
24
+ var n = Object.create(null);
25
+ if (e) {
26
+ Object.keys(e).forEach(function (k) {
27
+ if (k !== 'default') {
28
+ var d = Object.getOwnPropertyDescriptor(e, k);
29
+ Object.defineProperty(n, k, d.get ? d : {
30
+ enumerable: true,
31
+ get: function () { return e[k]; }
32
+ });
33
+ }
34
+ });
35
+ }
36
+ n.default = e;
37
+ return Object.freeze(n);
38
+ }
39
+
20
40
  var path__default = /*#__PURE__*/_interopDefault(path);
41
+ var util__namespace = /*#__PURE__*/_interopNamespace(util);
21
42
  var sharp__default = /*#__PURE__*/_interopDefault(sharp);
43
+ var pc__default = /*#__PURE__*/_interopDefault(pc);
22
44
 
23
45
  // src/browser/capture.ts
24
46
  var DEFAULT_VIEWPORT = { width: 1280, height: 800 };
@@ -27,12 +49,15 @@ var DEFAULT_FULL_PAGE = true;
27
49
  var DEFAULT_THRESHOLD = 0.1;
28
50
  var MIN_AUTO_CONCURRENCY = 2;
29
51
  var MAX_AUTO_CONCURRENCY = 8;
30
- function defaultConcurrency() {
52
+ function cpuCores() {
31
53
  const cores = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length;
32
54
  if (!cores || !Number.isFinite(cores)) return MIN_AUTO_CONCURRENCY;
55
+ return cores;
56
+ }
57
+ function defaultConcurrency() {
33
58
  return Math.max(
34
59
  MIN_AUTO_CONCURRENCY,
35
- Math.min(MAX_AUTO_CONCURRENCY, cores - 1)
60
+ Math.min(MAX_AUTO_CONCURRENCY, cpuCores() - 1)
36
61
  );
37
62
  }
38
63
  var BLAZEDIFF_DIR = ".blazediff";
@@ -42,16 +67,104 @@ var paths = (cwd = process.cwd()) => {
42
67
  root,
43
68
  config: path__default.default.join(root, "config.json"),
44
69
  manifest: path__default.default.join(root, "manifest.json"),
70
+ harnesses: path__default.default.join(root, "harnesses"),
45
71
  baselines: path__default.default.join(root, "baselines"),
46
72
  actual: path__default.default.join(root, "actual"),
47
73
  judgments: path__default.default.join(root, "judgments"),
48
74
  checkpoints: path__default.default.join(root, "checkpoints"),
49
- summary: path__default.default.join(root, "summary.md"),
75
+ report: path__default.default.join(root, "report.json"),
50
76
  gitignore: path__default.default.join(root, ".gitignore"),
51
77
  serverLog: path__default.default.join(root, "dev-server.log"),
52
78
  serverPid: path__default.default.join(root, "dev-server.pid")
53
79
  };
54
80
  };
81
+
82
+ // src/harness/loader.ts
83
+ var HarnessError = class extends Error {
84
+ constructor(message, cause) {
85
+ super(message);
86
+ this.cause = cause;
87
+ this.name = "HarnessError";
88
+ }
89
+ };
90
+ var moduleCache = /* @__PURE__ */ new Map();
91
+ function resolveHarnessFile(name, cwd) {
92
+ if (name.includes("/") || name.includes("\\") || path__default.default.isAbsolute(name)) {
93
+ return path__default.default.isAbsolute(name) ? name : path__default.default.resolve(cwd, name);
94
+ }
95
+ const dir = paths(cwd).harnesses;
96
+ const mjs = path__default.default.join(dir, `${name}.mjs`);
97
+ if (fs.existsSync(mjs)) return mjs;
98
+ return path__default.default.join(dir, `${name}.js`);
99
+ }
100
+ async function loadHarness(harnessFile) {
101
+ const absolute = path__default.default.isAbsolute(harnessFile) ? harnessFile : path__default.default.resolve(process.cwd(), harnessFile);
102
+ if (!fs.existsSync(absolute)) {
103
+ throw new HarnessError(
104
+ `harness not found at ${absolute}. Author one under .blazediff/harnesses/ (or run \`blazediff-agent harness record <name>\` to record one).`
105
+ );
106
+ }
107
+ const cached = moduleCache.get(absolute);
108
+ if (cached) return cached;
109
+ const url$1 = url.pathToFileURL(absolute).href;
110
+ const loading = (async () => {
111
+ let mod;
112
+ try {
113
+ mod = await import(
114
+ /* @vite-ignore */
115
+ url$1
116
+ );
117
+ } catch (err) {
118
+ throw new HarnessError(
119
+ `failed to load harness at ${absolute}: ${err.message}`,
120
+ err
121
+ );
122
+ }
123
+ const harness = mod.default;
124
+ if (!harness || typeof harness.run !== "function") {
125
+ if (typeof mod.login === "function") {
126
+ throw new HarnessError(
127
+ `legacy auth harness detected at ${absolute} (exports \`login\`). Re-run \`blazediff-agent harness record auth --login\` to regenerate it as a harness.`
128
+ );
129
+ }
130
+ throw new HarnessError(
131
+ `harness at ${absolute} must default-export an object with a \`run(ctx)\` function`
132
+ );
133
+ }
134
+ return { phase: harness.phase ?? "interact", run: harness.run };
135
+ })();
136
+ moduleCache.set(absolute, loading);
137
+ return loading;
138
+ }
139
+ function loginPathOf(loginUrl) {
140
+ try {
141
+ return new URL(loginUrl, "http://placeholder").pathname;
142
+ } catch {
143
+ return loginUrl;
144
+ }
145
+ }
146
+ async function assertLeftLoginPage(page, loginUrl) {
147
+ const loginPath = loginPathOf(loginUrl);
148
+ let currentPath;
149
+ try {
150
+ currentPath = new URL(page.url()).pathname;
151
+ } catch {
152
+ currentPath = page.url();
153
+ }
154
+ if (loginPath && currentPath === loginPath) {
155
+ throw new HarnessError(
156
+ `login harness returned but page is still on the login URL (${currentPath}). Check that the harness submits the form and waits for redirect.`
157
+ );
158
+ }
159
+ await page.locator('input[type="password"]').first().waitFor({ state: "detached", timeout: 2e3 }).catch(() => {
160
+ });
161
+ const passwordInputs = await page.locator('input[type="password"]:visible').count().catch(() => 0);
162
+ if (passwordInputs > 0) {
163
+ throw new HarnessError(
164
+ `login harness returned but a visible password input is still on the page. The login likely did not complete (wrong credentials, captcha, or selectors out of date).`
165
+ );
166
+ }
167
+ }
55
168
  var FROZEN_NOW = Date.UTC(2025, 0, 1, 0, 0, 0);
56
169
  var STABILITY_CSS = `
57
170
  *,*::before,*::after{
@@ -80,7 +193,13 @@ var contextPool = /* @__PURE__ */ new Map();
80
193
  async function getBrowser() {
81
194
  if (cachedBrowser?.isConnected()) return cachedBrowser;
82
195
  if (launchInFlight) return launchInFlight;
83
- 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) => {
84
203
  cachedBrowser = b;
85
204
  return b;
86
205
  }).finally(() => {
@@ -212,6 +331,11 @@ var DEFAULT_MASK_SELECTOR = `[${DEFAULT_MASK_ATTR}]`;
212
331
  async function applyMaskOverlays(page, masks) {
213
332
  const selectors = [DEFAULT_MASK_SELECTOR, ...masks];
214
333
  await page.evaluate((selectors2) => {
334
+ for (const stale of Array.from(
335
+ document.querySelectorAll("[data-blazediff-mask]")
336
+ )) {
337
+ stale.remove();
338
+ }
215
339
  for (const sel of selectors2) {
216
340
  for (const el of Array.from(
217
341
  document.querySelectorAll(sel)
@@ -234,39 +358,90 @@ async function applyMaskOverlays(page, masks) {
234
358
  }
235
359
 
236
360
  // src/browser/capture.ts
237
- async function captureScreenshot(baseUrl, opts, cwd = process.cwd(), auth) {
361
+ var SCREENSHOT_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/i;
362
+ async function shoot(page, outputPath, fullPage) {
363
+ await promises.mkdir(path__default.default.dirname(outputPath), { recursive: true });
364
+ const buffer = await page.screenshot({
365
+ path: outputPath,
366
+ type: "png",
367
+ fullPage,
368
+ animations: "disabled",
369
+ caret: "hide",
370
+ scale: "device"
371
+ });
372
+ return buffer.length;
373
+ }
374
+ async function stabilize(page, waitFor, masks) {
375
+ await waitForStability(page, waitFor);
376
+ await applyMaskOverlays(page, masks);
377
+ await page.evaluate(
378
+ () => new Promise((r) => requestAnimationFrame(() => r()))
379
+ );
380
+ }
381
+ async function captureScreenshot(baseUrl, opts, cwd = process.cwd(), harnesses) {
238
382
  const viewport = opts.viewport ?? DEFAULT_VIEWPORT;
239
383
  const waitFor = opts.waitFor ?? DEFAULT_WAIT_FOR;
240
384
  const masks = opts.mask ?? [];
241
385
  const fullPage = opts.fullPage ?? DEFAULT_FULL_PAGE;
386
+ const setup = (harnesses ?? []).filter(
387
+ (h) => (h.harness.phase ?? "interact") === "setup"
388
+ );
389
+ const interact = (harnesses ?? []).filter(
390
+ (h) => (h.harness.phase ?? "interact") !== "setup"
391
+ );
242
392
  const handle = await acquireStableContext(viewport, {
243
- pool: !auth,
393
+ pool: !(harnesses && harnesses.length > 0),
244
394
  baseURL: baseUrl || void 0
245
395
  });
396
+ const context = handle.context;
397
+ const browser = await getBrowser();
246
398
  const page = await openStablePage(handle);
247
399
  try {
248
- if (auth) {
249
- await auth.hook(page);
400
+ const rejectScreenshot = async () => {
401
+ throw new HarnessError("setup harness must not call screenshot()");
402
+ };
403
+ for (const { harness, params } of setup) {
404
+ await harness.run({
405
+ page,
406
+ browser,
407
+ context,
408
+ params,
409
+ screenshot: rejectScreenshot
410
+ });
250
411
  }
251
412
  const url = new URL(opts.url, baseUrl).toString();
252
413
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 3e4 });
253
- await waitForStability(page, waitFor);
254
- await applyMaskOverlays(page, masks);
255
- await page.evaluate(
256
- () => new Promise((r) => requestAnimationFrame(() => r()))
257
- );
414
+ await stabilize(page, waitFor, masks);
258
415
  const outputDir = opts.mode === "baseline" ? paths(cwd).baselines : paths(cwd).actual;
259
- await promises.mkdir(outputDir, { recursive: true });
260
416
  const outputPath = path__default.default.join(outputDir, `${opts.id}.png`);
261
- const buffer = await page.screenshot({
262
- path: outputPath,
263
- type: "png",
264
- fullPage,
265
- animations: "disabled",
266
- caret: "hide",
267
- scale: "device"
268
- });
269
- return { id: opts.id, outputPath, mode: opts.mode, bytes: buffer.length };
417
+ const bytes = await shoot(page, outputPath, fullPage);
418
+ const subCaptures = [];
419
+ const used = /* @__PURE__ */ new Set();
420
+ const screenshot = async (name) => {
421
+ if (!SCREENSHOT_NAME_RE.test(name)) {
422
+ throw new HarnessError(
423
+ `invalid screenshot name "${name}": use alphanumeric/kebab-case (no "__", spaces, or slashes)`
424
+ );
425
+ }
426
+ if (used.has(name)) {
427
+ throw new HarnessError(`duplicate screenshot name "${name}"`);
428
+ }
429
+ used.add(name);
430
+ await stabilize(page, waitFor, masks);
431
+ const subPath = path__default.default.join(outputDir, `${opts.id}__${name}.png`);
432
+ const subBytes = await shoot(page, subPath, fullPage);
433
+ subCaptures.push({ name, outputPath: subPath, bytes: subBytes });
434
+ };
435
+ for (const { harness, params } of interact) {
436
+ await harness.run({ page, browser, context, params, screenshot });
437
+ }
438
+ return {
439
+ id: opts.id,
440
+ outputPath,
441
+ mode: opts.mode,
442
+ bytes,
443
+ subCaptures: subCaptures.length > 0 ? subCaptures : void 0
444
+ };
270
445
  } finally {
271
446
  await page.close().catch(() => {
272
447
  });
@@ -320,112 +495,6 @@ async function installBrowsers(opts = {}) {
320
495
  const executablePath = await readExecutablePath();
321
496
  return { installed: Boolean(executablePath), executablePath, cliPath };
322
497
  }
323
-
324
- // src/auth/env.ts
325
- var LEGACY_REQUIRED = "required";
326
- var DEFAULT_PERSONA = "default";
327
- function canonicalPersona(auth) {
328
- return auth === LEGACY_REQUIRED ? DEFAULT_PERSONA : auth;
329
- }
330
- var AuthHarnessError = class extends Error {
331
- constructor(message, cause) {
332
- super(message);
333
- this.cause = cause;
334
- this.name = "AuthHarnessError";
335
- }
336
- };
337
- var moduleCache = /* @__PURE__ */ new Map();
338
- async function loadAuthHarness(harnessFile) {
339
- const absolute = path__default.default.isAbsolute(harnessFile) ? harnessFile : path__default.default.resolve(process.cwd(), harnessFile);
340
- if (!fs.existsSync(absolute)) {
341
- throw new AuthHarnessError(
342
- `auth harness not found at ${absolute}. Run \`blazediff-agent auth init\` to create one.`
343
- );
344
- }
345
- const cached = moduleCache.get(absolute);
346
- if (cached) return cached;
347
- const url$1 = url.pathToFileURL(absolute).href;
348
- const loading = (async () => {
349
- try {
350
- const mod = await import(url$1);
351
- if (typeof mod.login !== "function") {
352
- throw new AuthHarnessError(
353
- `auth harness at ${absolute} does not export a \`login\` function`
354
- );
355
- }
356
- return { login: mod.login };
357
- } catch (err) {
358
- if (err instanceof AuthHarnessError) throw err;
359
- throw new AuthHarnessError(
360
- `failed to load auth harness at ${absolute}: ${err.message}`,
361
- err
362
- );
363
- }
364
- })();
365
- moduleCache.set(absolute, loading);
366
- return loading;
367
- }
368
- function loginPathOf(loginUrl) {
369
- try {
370
- return new URL(loginUrl, "http://placeholder").pathname;
371
- } catch {
372
- return loginUrl;
373
- }
374
- }
375
- async function verifyPostLogin(page, loginUrl) {
376
- const loginPath = loginPathOf(loginUrl);
377
- let currentPath;
378
- try {
379
- currentPath = new URL(page.url()).pathname;
380
- } catch {
381
- currentPath = page.url();
382
- }
383
- if (loginPath && currentPath === loginPath) {
384
- throw new AuthHarnessError(
385
- `auth harness returned but page is still on the login URL (${currentPath}). Check that the harness submits the form and waits for redirect.`
386
- );
387
- }
388
- await page.locator('input[type="password"]').first().waitFor({ state: "detached", timeout: 2e3 }).catch(() => {
389
- });
390
- const passwordInputs = await page.locator('input[type="password"]:visible').count().catch(() => 0);
391
- if (passwordInputs > 0) {
392
- throw new AuthHarnessError(
393
- `auth harness returned but a visible password input is still on the page. The login likely did not complete (wrong credentials, captcha, or selectors out of date).`
394
- );
395
- }
396
- }
397
-
398
- // src/auth/hook.ts
399
- var AuthConfigMissingError = class extends Error {
400
- constructor(message) {
401
- super(message);
402
- this.name = "AuthConfigMissingError";
403
- }
404
- };
405
- function buildAuthHook(persona, authConfig, cwd) {
406
- if (!authConfig) {
407
- throw new AuthConfigMissingError(
408
- "auth required but .blazediff/config.json has no `auth` block. Run `blazediff-agent auth init`."
409
- );
410
- }
411
- const harnessFile = path__default.default.isAbsolute(authConfig.harness) ? authConfig.harness : path__default.default.join(cwd, authConfig.harness);
412
- const canonical = canonicalPersona(persona);
413
- const loginUrl = authConfig.loginUrl;
414
- return {
415
- hook: async (page) => {
416
- const mod = await loadAuthHarness(harnessFile);
417
- try {
418
- await mod.login(page, canonical);
419
- } catch (err) {
420
- throw new AuthHarnessError(
421
- `auth harness threw for persona "${canonical}": ${err.message}`,
422
- err
423
- );
424
- }
425
- await verifyPostLogin(page, loginUrl);
426
- }
427
- };
428
- }
429
498
  async function loadConfig(cwd = process.cwd()) {
430
499
  const file = paths(cwd).config;
431
500
  if (!fs.existsSync(file)) return null;
@@ -448,33 +517,40 @@ function resolveBaseUrl(config, override) {
448
517
  }
449
518
 
450
519
  // src/graph/semaphore.ts
451
- var Semaphore = class {
452
- constructor(limit) {
453
- this.limit = limit;
454
- this.current = 0;
455
- this.queue = [];
456
- if (limit < 1)
457
- throw new Error(`semaphore limit must be >= 1 (got ${limit})`);
458
- }
459
- async run(fn) {
460
- if (this.current >= this.limit) {
461
- 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));
462
527
  }
463
- this.current++;
528
+ current++;
464
529
  try {
465
530
  return await fn();
466
531
  } finally {
467
- this.current--;
468
- const next = this.queue.shift();
532
+ current--;
533
+ const next = queue.shift();
469
534
  if (next) next();
470
535
  }
471
536
  }
472
- };
537
+ return { run };
538
+ }
473
539
 
474
540
  // src/types.ts
475
541
  var STABILITY_HOOKS_VERSION = 1;
476
542
 
477
543
  // src/manifest.ts
544
+ function serializeHarnesses(harnesses) {
545
+ return JSON.stringify(
546
+ harnesses.map((h) => ({
547
+ name: h.name,
548
+ params: h.params ? Object.fromEntries(
549
+ Object.entries(h.params).sort(([a], [b]) => a.localeCompare(b))
550
+ ) : void 0
551
+ }))
552
+ );
553
+ }
478
554
  async function loadManifest(cwd = process.cwd()) {
479
555
  const file = paths(cwd).manifest;
480
556
  if (!fs.existsSync(file)) return null;
@@ -500,8 +576,9 @@ function hashMaterial(input) {
500
576
  viewport: input.viewport,
501
577
  mask: [...input.mask].sort(),
502
578
  waitFor: input.waitFor,
503
- auth: input.auth,
579
+ harnesses: serializeHarnesses(input.harnesses),
504
580
  fullPage: input.fullPage,
581
+ subName: input.subName ?? null,
505
582
  hooks: STABILITY_HOOKS_VERSION
506
583
  };
507
584
  return `sha256:${crypto$1.createHash("sha256").update(JSON.stringify(material)).digest("hex")}`;
@@ -510,24 +587,27 @@ function makeEntry(input) {
510
587
  const viewport = input.viewport ?? DEFAULT_VIEWPORT;
511
588
  const waitFor = input.waitFor ?? DEFAULT_WAIT_FOR;
512
589
  const mask = input.mask ?? [];
513
- const auth = input.auth ?? null;
590
+ const harnesses = input.harnesses ?? [];
514
591
  const fullPage = input.fullPage ?? DEFAULT_FULL_PAGE;
515
592
  return {
516
593
  id: input.id,
517
594
  url: input.url,
518
595
  viewport,
519
- auth,
596
+ harnesses: harnesses.length > 0 ? harnesses : void 0,
520
597
  waitFor,
521
598
  mask,
522
599
  fullPage,
600
+ parent: input.parent,
601
+ derived: input.derived || void 0,
523
602
  baselinePath: path__default.default.posix.join(".blazediff", "baselines", `${input.id}.png`),
524
603
  captureHash: hashMaterial({
525
604
  url: input.url,
526
605
  viewport,
527
606
  mask,
528
607
  waitFor,
529
- auth,
530
- fullPage
608
+ harnesses,
609
+ fullPage,
610
+ subName: input.subName
531
611
  }),
532
612
  createdBy: input.createdBy ?? "agent",
533
613
  createdAt: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)
@@ -540,19 +620,40 @@ function addOrReplaceEntry(manifest, entry) {
540
620
  ].sort((a, b) => a.id.localeCompare(b.id));
541
621
  return { ...manifest, entries };
542
622
  }
623
+ function isDerived(entry) {
624
+ return entry.derived === true || entry.parent != null && entry.id.includes("__");
625
+ }
626
+ function subNameOf(entry) {
627
+ if (!isDerived(entry)) return void 0;
628
+ const idx = entry.id.indexOf("__");
629
+ return idx === -1 ? void 0 : entry.id.slice(idx + 2);
630
+ }
543
631
  function isEntryStale(entry) {
544
632
  const recomputed = hashMaterial({
545
633
  url: entry.url,
546
634
  viewport: entry.viewport,
547
635
  mask: entry.mask,
548
636
  waitFor: entry.waitFor,
549
- auth: entry.auth,
550
- fullPage: entry.fullPage ?? DEFAULT_FULL_PAGE
637
+ harnesses: entry.harnesses ?? [],
638
+ fullPage: entry.fullPage ?? DEFAULT_FULL_PAGE,
639
+ subName: subNameOf(entry)
551
640
  });
552
641
  return recomputed !== entry.captureHash;
553
642
  }
554
643
 
555
644
  // src/captures.ts
645
+ function normalizeHarnessRefs(refs) {
646
+ if (!refs) return [];
647
+ return refs.map((ref) => typeof ref === "string" ? { name: ref } : ref);
648
+ }
649
+ async function resolveHarnesses(refs, cwd) {
650
+ return Promise.all(
651
+ refs.map(async (ref) => ({
652
+ harness: await loadHarness(resolveHarnessFile(ref.name, cwd)),
653
+ params: ref.params ?? {}
654
+ }))
655
+ );
656
+ }
556
657
  function validateRoute(route, i) {
557
658
  if (!route || typeof route !== "object")
558
659
  return `route[${i}] must be an object`;
@@ -591,14 +692,18 @@ async function runCaptures(opts) {
591
692
  let manifest = writeManifest ? await loadOrCreateManifest(cwd, config) : null;
592
693
  let manifestUpdates = 0;
593
694
  const slot = new Array(valid.length);
594
- 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());
595
699
  try {
596
700
  await Promise.all(
597
701
  valid.map(
598
702
  (r, i) => semaphore.run(async () => {
599
703
  const mode = r.mode ?? defaultMode;
600
704
  try {
601
- const auth = r.auth != null ? buildAuthHook(r.auth, config?.auth, cwd) : void 0;
705
+ const refs = normalizeHarnessRefs(r.harnesses);
706
+ const harnesses = await resolveHarnesses(refs, cwd);
602
707
  const shot = await captureScreenshot(
603
708
  opts.baseUrl,
604
709
  {
@@ -611,7 +716,7 @@ async function runCaptures(opts) {
611
716
  mode
612
717
  },
613
718
  cwd,
614
- auth
719
+ harnesses
615
720
  );
616
721
  slot[i] = {
617
722
  id: r.id,
@@ -619,22 +724,31 @@ async function runCaptures(opts) {
619
724
  mode,
620
725
  ok: true,
621
726
  outputPath: shot.outputPath,
622
- bytes: shot.bytes
727
+ bytes: shot.bytes,
728
+ subCaptures: shot.subCaptures?.map((s) => s.name)
623
729
  };
624
730
  if (mode === "baseline" && manifest) {
625
- manifest = addOrReplaceEntry(
626
- manifest,
627
- makeEntry({
628
- id: r.id,
629
- url: r.url,
630
- viewport: r.viewport,
631
- mask: r.mask,
632
- waitFor: r.waitFor,
633
- fullPage: r.fullPage,
634
- auth: r.auth ?? null
635
- })
636
- );
637
- manifestUpdates += 1;
731
+ const shared = {
732
+ url: r.url,
733
+ viewport: r.viewport,
734
+ mask: r.mask,
735
+ waitFor: r.waitFor,
736
+ fullPage: r.fullPage,
737
+ harnesses: refs.length > 0 ? refs : void 0
738
+ };
739
+ pendingUpdates[i] = {
740
+ baseId: r.id,
741
+ baseEntry: makeEntry({ id: r.id, ...shared }),
742
+ derivedEntries: (shot.subCaptures ?? []).map(
743
+ (sub) => makeEntry({
744
+ id: `${r.id}__${sub.name}`,
745
+ ...shared,
746
+ parent: r.id,
747
+ derived: true,
748
+ subName: sub.name
749
+ })
750
+ )
751
+ };
638
752
  }
639
753
  } catch (err) {
640
754
  slot[i] = {
@@ -649,7 +763,22 @@ async function runCaptures(opts) {
649
763
  )
650
764
  );
651
765
  for (const r of slot) results.push(r);
652
- 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
+ }
653
782
  } finally {
654
783
  await closeBrowser();
655
784
  }
@@ -692,7 +821,7 @@ async function diffEntry(id, baselinePath, actualPath, opts = {}, cwd = process.
692
821
  }
693
822
  const threshold = opts.threshold ?? DEFAULT_THRESHOLD;
694
823
  const antialiasing = opts.antialiasing ?? true;
695
- const result = await coreNative.compare(baselinePath, actualPath, diffPath, {
824
+ const result = await coreNative.compare(baselinePath, actualPath, void 0, {
696
825
  threshold,
697
826
  antialiasing,
698
827
  interpret: true
@@ -717,6 +846,13 @@ async function diffEntry(id, baselinePath, actualPath, opts = {}, cwd = process.
717
846
  reason: "layout-diff"
718
847
  };
719
848
  }
849
+ if (diffPath) {
850
+ await coreNative.compare(baselinePath, actualPath, diffPath, {
851
+ threshold,
852
+ antialiasing,
853
+ compression: 9
854
+ });
855
+ }
720
856
  return {
721
857
  id,
722
858
  baselinePath,
@@ -740,9 +876,9 @@ function extractInternalLinks(base, target, hrefs) {
740
876
  try {
741
877
  const u = new URL(href, target);
742
878
  if (u.origin !== base.origin) continue;
743
- const path20 = u.pathname + u.search;
744
- if (path20.startsWith("/api/")) continue;
745
- out.push(path20);
879
+ const path23 = u.pathname + u.search;
880
+ if (path23.startsWith("/api/")) continue;
881
+ out.push(path23);
746
882
  } catch {
747
883
  }
748
884
  }
@@ -796,15 +932,24 @@ async function crawlRoutes(opts) {
796
932
  }
797
933
  return discovered.slice(0, maxRoutes);
798
934
  }
799
- var DYNAMIC_SEGMENT = /\[[^\]]+\]/;
800
- async function readJson(file) {
801
- 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) {
802
944
  try {
803
945
  return JSON.parse(await promises.readFile(file, "utf8"));
804
946
  } catch {
805
947
  return null;
806
948
  }
807
949
  }
950
+
951
+ // src/discover/next.ts
952
+ var DYNAMIC_SEGMENT = /\[[^\]]+\]/;
808
953
  function isPublicRoute(route) {
809
954
  if (DYNAMIC_SEGMENT.test(route)) return false;
810
955
  if (route === "/api" || route.startsWith("/api/")) return false;
@@ -820,13 +965,13 @@ async function discoverFromNextManifest(cwd = process.cwd()) {
820
965
  seen.add(url);
821
966
  out.push({ url, source: "next-manifest" });
822
967
  };
823
- const routes = await readJson(
968
+ const routes = await readJsonOrNull(
824
969
  path__default.default.join(nextDir, "routes-manifest.json")
825
970
  );
826
971
  for (const r of routes?.staticRoutes ?? []) {
827
972
  if (isPublicRoute(r.page)) add(r.page);
828
973
  }
829
- const appPaths = await readJson(
974
+ const appPaths = await readJsonOrNull(
830
975
  path__default.default.join(nextDir, "server", "app-paths-manifest.json")
831
976
  );
832
977
  for (const route of Object.keys(appPaths ?? {})) {
@@ -886,17 +1031,73 @@ async function discover(opts) {
886
1031
  }
887
1032
  return Array.from(merged.values()).sort((a, b) => a.url.localeCompare(b.url));
888
1033
  }
1034
+ function envFiles(cwd) {
1035
+ const root = paths(cwd).root;
1036
+ return [
1037
+ path__default.default.join(root, ".env.local"),
1038
+ path__default.default.join(root, ".env"),
1039
+ path__default.default.join(cwd, ".env.local"),
1040
+ path__default.default.join(cwd, ".env")
1041
+ ];
1042
+ }
1043
+ function parse(content) {
1044
+ if (typeof util__namespace.parseEnv === "function") {
1045
+ return util__namespace.parseEnv(content);
1046
+ }
1047
+ const out = {};
1048
+ for (const raw of content.split("\n")) {
1049
+ const line = raw.trim();
1050
+ if (!line || line.startsWith("#")) continue;
1051
+ const eq = line.indexOf("=");
1052
+ if (eq === -1) continue;
1053
+ const key = line.slice(0, eq).trim();
1054
+ let value = line.slice(eq + 1).trim();
1055
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
1056
+ value = value.slice(1, -1);
1057
+ }
1058
+ if (key) out[key] = value;
1059
+ }
1060
+ return out;
1061
+ }
1062
+ function loadEnvFiles(cwd = process.cwd()) {
1063
+ const loaded = [];
1064
+ for (const file of envFiles(cwd)) {
1065
+ if (!fs.existsSync(file)) continue;
1066
+ let parsed;
1067
+ try {
1068
+ parsed = parse(fs.readFileSync(file, "utf8"));
1069
+ } catch {
1070
+ continue;
1071
+ }
1072
+ let applied = false;
1073
+ for (const [key, value] of Object.entries(parsed)) {
1074
+ if (process.env[key] === void 0) {
1075
+ process.env[key] = value;
1076
+ applied = true;
1077
+ }
1078
+ }
1079
+ if (applied) loaded.push(file);
1080
+ }
1081
+ return loaded;
1082
+ }
889
1083
  var ENTRIES = [
890
1084
  "actual/",
891
1085
  "judgments/",
892
1086
  "checkpoints/",
893
- "summary.md",
1087
+ "report.json",
894
1088
  "dev-server.log",
895
1089
  "dev-server.pid",
1090
+ ".env",
1091
+ ".env.local",
896
1092
  "*.tmp"
897
1093
  ];
898
- var STALE_ENTRIES = /* @__PURE__ */ new Set(["diffs/", "pending-judgments/", "report.json"]);
899
- var HEADER = "# blazediff: generated artifacts (committed: config.json, manifest.json, baselines/)\n";
1094
+ var STALE_ENTRIES = /* @__PURE__ */ new Set([
1095
+ "diffs/",
1096
+ "pending-judgments/",
1097
+ "summary.html",
1098
+ "summary.md"
1099
+ ]);
1100
+ var HEADER = "# blazediff: generated artifacts (committed: config.json, manifest.json, baselines/, harnesses/)\n";
900
1101
  async function ensureGitignore(cwd) {
901
1102
  const file = paths(cwd).gitignore;
902
1103
  await promises.mkdir(path__default.default.dirname(file), { recursive: true });
@@ -922,6 +1123,15 @@ ${missing.join("\n")}
922
1123
  await promises.writeFile(file, body, "utf8");
923
1124
  }
924
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;
925
1135
  var DEFAULT_PADDING = 16;
926
1136
  var DEFAULT_LOCATOR_MAX_WIDTH = 400;
927
1137
  var DEFAULT_GUTTER = 2;
@@ -939,17 +1149,75 @@ function padAndClamp(bbox, padding, imgWidth, imgHeight) {
939
1149
  height: Math.max(1, bottom - top)
940
1150
  };
941
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
+ }
942
1210
  async function prepareTiles(opts) {
943
1211
  const topN = opts.topN ?? DEFAULT_TOP_N;
944
1212
  const padding = opts.padding ?? DEFAULT_PADDING;
945
1213
  const locatorMaxWidth = opts.locatorMaxWidth ?? DEFAULT_LOCATOR_MAX_WIDTH;
946
1214
  const gutter = opts.gutter ?? DEFAULT_GUTTER;
947
1215
  const rowGutter = opts.rowGutter ?? DEFAULT_ROW_GUTTER;
948
- const diffMeta = await sharp__default.default(opts.diffPath).metadata();
949
- const imgWidth = diffMeta.width ?? 0;
950
- 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;
951
1219
  if (!imgWidth || !imgHeight) {
952
- throw new Error(`unable to read diff image dimensions: ${opts.diffPath}`);
1220
+ throw new Error(`unable to read image dimensions: ${opts.actualPath}`);
953
1221
  }
954
1222
  const ranked = [...opts.regions].sort((a, b) => b.pixelCount - a.pixelCount).slice(0, topN);
955
1223
  const regionData = await Promise.all(
@@ -999,19 +1267,22 @@ async function prepareTiles(opts) {
999
1267
  }
1000
1268
  }).composite(composites).png().toFile(path__default.default.join(opts.outputDir, tilesName));
1001
1269
  }
1002
- const scale = locatorMaxWidth / Math.max(imgWidth, imgHeight);
1003
- const locW = Math.max(1, Math.round(imgWidth * scale));
1004
- const locH = Math.max(1, Math.round(imgHeight * scale));
1005
- const rects = opts.regions.map((r) => {
1006
- const x = Math.round(r.bbox.x * scale);
1007
- const y = Math.round(r.bbox.y * scale);
1008
- const w = Math.max(1, Math.round(r.bbox.width * scale));
1009
- const h = Math.max(1, Math.round(r.bbox.height * scale));
1010
- return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="none" stroke="red" stroke-width="2" />`;
1011
- }).join("");
1012
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${locW}" height="${locH}">${rects}</svg>`;
1013
- const locatorName = "locator.png";
1014
- 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
+ }
1015
1286
  return {
1016
1287
  locatorPath: locatorName,
1017
1288
  tilesPath: tilesName,
@@ -1022,9 +1293,9 @@ async function prepareTiles(opts) {
1022
1293
  };
1023
1294
  }
1024
1295
 
1025
- // src/judge/host-harness.ts
1296
+ // src/judge/coding-agent-host.ts
1026
1297
  async function tryPrepareTiles(input, entryDir) {
1027
- if (!input.regions || input.regions.length === 0 || !input.diffPath) {
1298
+ if (!input.regions || input.regions.length === 0) {
1028
1299
  return null;
1029
1300
  }
1030
1301
  try {
@@ -1043,9 +1314,10 @@ async function tryPrepareTiles(input, entryDir) {
1043
1314
  return null;
1044
1315
  }
1045
1316
  }
1046
- var hostHarnessJudge = {
1317
+ var codingAgentHostJudge = {
1047
1318
  name: "host",
1048
1319
  async judge(input, cwd) {
1320
+ input.onJudgingStart?.();
1049
1321
  const p = paths(cwd);
1050
1322
  const entryDir = path__default.default.join(p.judgments, input.entry.id);
1051
1323
  await promises.mkdir(entryDir, { recursive: true });
@@ -1053,366 +1325,598 @@ var hostHarnessJudge = {
1053
1325
  return { kind: "deferred", requestPath: entryDir };
1054
1326
  }
1055
1327
  };
1328
+ var dim = pc__default.default.dim;
1329
+ var bold = pc__default.default.bold;
1056
1330
 
1057
- // src/judge/none.ts
1058
- var noneJudge = {
1059
- name: "none",
1060
- async judge(input) {
1061
- return { kind: "judged", verdict: input.heuristicVerdict };
1062
- }
1063
- };
1064
- var ROOT_NS_SENTINEL = "_root";
1065
- function nsDir(ns) {
1066
- return ns === "" ? ROOT_NS_SENTINEL : ns;
1067
- }
1068
- function encode(buf) {
1069
- return Buffer.from(buf).toString("base64");
1070
- }
1071
- function decode(s) {
1072
- 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
+ };
1073
1391
  }
1074
- async function readJson2(file) {
1392
+ async function loadTransformers() {
1075
1393
  try {
1076
- const raw = await promises.readFile(file, "utf8");
1077
- return JSON.parse(raw);
1394
+ return await import('@huggingface/transformers');
1078
1395
  } catch (err) {
1079
- if (err.code === "ENOENT") return void 0;
1080
- 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
+ );
1081
1400
  }
1082
1401
  }
1083
- async function writeJsonAtomic(file, value) {
1084
- const tmp = `${file}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
1085
- await promises.writeFile(tmp, JSON.stringify(value), "utf8");
1086
- 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
+ };
1087
1447
  }
1088
- var FsCheckpointSaver = class extends langgraphCheckpoint.BaseCheckpointSaver {
1089
- constructor(root, serde) {
1090
- super(serde);
1091
- this.locks = /* @__PURE__ */ new Map();
1092
- this.root = root;
1093
- }
1094
- threadDir(thread) {
1095
- return path__default.default.join(this.root, thread);
1096
- }
1097
- nsPath(thread, ns) {
1098
- return path__default.default.join(this.threadDir(thread), nsDir(ns));
1099
- }
1100
- ckptFile(thread, ns, id) {
1101
- return path__default.default.join(this.nsPath(thread, ns), `${id}.ckpt.json`);
1102
- }
1103
- writesFile(thread, ns, id) {
1104
- return path__default.default.join(this.nsPath(thread, ns), `${id}.writes.json`);
1105
- }
1106
- async withLock(key, fn) {
1107
- const prev = this.locks.get(key) ?? Promise.resolve();
1108
- const next = prev.then(fn, fn);
1109
- this.locks.set(key, next);
1110
- try {
1111
- return await next;
1112
- } finally {
1113
- 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;
1114
1454
  }
1115
- }
1116
- async listCheckpointIds(thread, ns) {
1117
- try {
1118
- const names = await promises.readdir(this.nsPath(thread, ns));
1119
- const suffix = ".ckpt.json";
1120
- return names.filter((n) => n.endsWith(suffix)).map((n) => n.slice(0, -suffix.length));
1121
- } catch (err) {
1122
- if (err.code === "ENOENT") return [];
1123
- 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]);
1124
1612
  }
1125
1613
  }
1126
- async listNamespaces(thread) {
1127
- try {
1128
- return await promises.readdir(this.threadDir(thread));
1129
- } catch (err) {
1130
- if (err.code === "ENOENT") return [];
1131
- 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++]);
1132
1626
  }
1133
1627
  }
1134
- async listThreads() {
1135
- try {
1136
- return await promises.readdir(this.root);
1137
- } catch (err) {
1138
- if (err.code === "ENOENT") return [];
1139
- 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();
1140
1704
  }
1141
- }
1142
- decodeNs(nsDirName) {
1143
- return nsDirName === ROOT_NS_SENTINEL ? "" : nsDirName;
1144
- }
1145
- async loadPendingWrites(thread, ns, ckptId) {
1146
- const data = await readJson2(
1147
- this.writesFile(thread, ns, ckptId)
1148
- );
1149
- if (!data) return [];
1150
- const out = [];
1151
- for (const [taskId, channel, serialized] of Object.values(data)) {
1152
- const value = await this.serde.loadsTyped("json", decode(serialized));
1153
- 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;
1154
1713
  }
1155
- return out;
1156
- }
1157
- async migratePendingSends(checkpoint, thread, ns, parentCheckpointId) {
1158
- const data = await readJson2(
1159
- this.writesFile(thread, ns, parentCheckpointId)
1160
- );
1161
- const pendingSends = data ? await Promise.all(
1162
- Object.values(data).filter(([, channel]) => channel === langgraphCheckpoint.TASKS).map(
1163
- ([, , serialized]) => this.serde.loadsTyped("json", decode(serialized))
1164
- )
1165
- ) : [];
1166
- const m = checkpoint;
1167
- m.channel_values ?? (m.channel_values = {});
1168
- m.channel_values[langgraphCheckpoint.TASKS] = pendingSends;
1169
- m.channel_versions ?? (m.channel_versions = {});
1170
- const versions = Object.values(m.channel_versions);
1171
- m.channel_versions[langgraphCheckpoint.TASKS] = versions.length > 0 ? langgraphCheckpoint.maxChannelVersion(...versions) : this.getNextVersion(void 0);
1172
- }
1173
- async readTuple(thread, ns, ckptId, config) {
1174
- const data = await readJson2(this.ckptFile(thread, ns, ckptId));
1175
- if (!data) return void 0;
1176
- const checkpoint = await this.serde.loadsTyped(
1177
- "json",
1178
- decode(data.checkpoint)
1179
- );
1180
- const metadata = await this.serde.loadsTyped(
1181
- "json",
1182
- decode(data.metadata)
1183
- );
1184
- if (checkpoint.v < 4 && data.parentCheckpointId !== void 0) {
1185
- await this.migratePendingSends(
1186
- checkpoint,
1187
- thread,
1188
- ns,
1189
- 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
+ })
1190
1835
  );
1836
+ return phrases.length === 1 ? phrases[0] : phrases.map((p, i) => `region ${i + 1}: ${p}`).join("; ");
1837
+ } catch {
1838
+ return null;
1191
1839
  }
1192
- const pendingWrites = await this.loadPendingWrites(thread, ns, ckptId);
1193
- const tuple = {
1194
- config,
1195
- checkpoint,
1196
- metadata,
1197
- pendingWrites
1198
- };
1199
- if (data.parentCheckpointId !== void 0) {
1200
- tuple.parentConfig = {
1201
- configurable: {
1202
- thread_id: thread,
1203
- checkpoint_ns: ns,
1204
- checkpoint_id: data.parentCheckpointId
1205
- }
1206
- };
1207
- }
1208
- return tuple;
1209
1840
  }
1210
- async getTuple(config) {
1211
- const thread = config.configurable?.thread_id;
1212
- if (!thread) return void 0;
1213
- const ns = config.configurable?.checkpoint_ns ?? "";
1214
- const explicitId = langgraphCheckpoint.getCheckpointId(config);
1215
- if (explicitId) {
1216
- return this.readTuple(thread, ns, explicitId, config);
1217
- }
1218
- const ids = (await this.listCheckpointIds(thread, ns)).sort(
1219
- (a, b) => b.localeCompare(a)
1220
- );
1221
- if (ids.length === 0) return void 0;
1222
- const ckptId = ids[0];
1223
- return this.readTuple(thread, ns, ckptId, {
1224
- configurable: {
1225
- thread_id: thread,
1226
- checkpoint_ns: ns,
1227
- checkpoint_id: ckptId
1228
- }
1229
- });
1841
+ async function describeScreenshot(input) {
1842
+ const v = await vision.get();
1843
+ return (await v.describe(input.actualPath, DESCRIBE_PROMPT)).trim();
1230
1844
  }
1231
- async *list(config, options) {
1232
- const filter = options?.filter;
1233
- const before = options?.before;
1234
- let limit = options?.limit;
1235
- const configThread = config.configurable?.thread_id;
1236
- const configNs = config.configurable?.checkpoint_ns;
1237
- const configCkptId = config.configurable?.checkpoint_id;
1238
- const threads = configThread ? [configThread] : await this.listThreads();
1239
- for (const thread of threads) {
1240
- const nsNames = await this.listNamespaces(thread);
1241
- for (const nsName of nsNames) {
1242
- const ns = this.decodeNs(nsName);
1243
- if (configNs !== void 0 && ns !== configNs) continue;
1244
- const ids = (await this.listCheckpointIds(thread, ns)).sort(
1245
- (a, b) => b.localeCompare(a)
1246
- );
1247
- for (const ckptId of ids) {
1248
- if (configCkptId && ckptId !== configCkptId) continue;
1249
- if (before?.configurable?.checkpoint_id && ckptId >= before.configurable.checkpoint_id)
1250
- continue;
1251
- const tuple = await this.readTuple(thread, ns, ckptId, {
1252
- configurable: {
1253
- thread_id: thread,
1254
- checkpoint_ns: ns,
1255
- checkpoint_id: ckptId
1256
- }
1257
- });
1258
- if (!tuple) continue;
1259
- if (filter) {
1260
- const md = tuple.metadata;
1261
- const matches = Object.entries(filter).every(
1262
- ([k, v]) => md?.[k] === v
1263
- );
1264
- if (!matches) continue;
1265
- }
1266
- if (limit !== void 0) {
1267
- if (limit <= 0) return;
1268
- limit -= 1;
1269
- }
1270
- yield tuple;
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
+ };
1271
1877
  }
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
+ };
1272
1897
  }
1273
1898
  }
1274
- }
1275
- async put(config, checkpoint, metadata) {
1276
- const thread = config.configurable?.thread_id;
1277
- if (!thread) {
1278
- throw new Error(
1279
- 'FsCheckpointSaver: missing "thread_id" in configurable. Pass `{ configurable: { thread_id } }` when streaming.'
1280
- );
1281
- }
1282
- const ns = config.configurable?.checkpoint_ns ?? "";
1283
- const parentCheckpointId = config.configurable?.checkpoint_id;
1284
- const prepared = langgraphCheckpoint.copyCheckpoint(checkpoint);
1285
- const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([
1286
- this.serde.dumpsTyped(prepared),
1287
- this.serde.dumpsTyped(metadata)
1288
- ]);
1289
- await promises.mkdir(this.nsPath(thread, ns), { recursive: true });
1290
- const file = this.ckptFile(thread, ns, checkpoint.id);
1291
- const body = {
1292
- checkpoint: encode(serializedCheckpoint),
1293
- metadata: encode(serializedMetadata),
1294
- parentCheckpointId
1295
- };
1296
- await writeJsonAtomic(file, body);
1297
- return {
1298
- configurable: {
1299
- thread_id: thread,
1300
- checkpoint_ns: ns,
1301
- checkpoint_id: checkpoint.id
1302
- }
1303
- };
1304
- }
1305
- async putWrites(config, writes, taskId) {
1306
- const thread = config.configurable?.thread_id;
1307
- if (!thread) {
1308
- throw new Error(
1309
- 'FsCheckpointSaver: missing "thread_id" in configurable for putWrites.'
1310
- );
1311
- }
1312
- const ns = config.configurable?.checkpoint_ns ?? "";
1313
- const ckptId = config.configurable?.checkpoint_id;
1314
- if (!ckptId) {
1315
- throw new Error(
1316
- 'FsCheckpointSaver: missing "checkpoint_id" in configurable for putWrites.'
1317
- );
1318
- }
1319
- const key = `${thread}|${ns}|${ckptId}`;
1320
- await this.withLock(key, async () => {
1321
- const existing = await readJson2(this.writesFile(thread, ns, ckptId)) ?? {};
1322
- let mutated = false;
1323
- for (let idx = 0; idx < writes.length; idx++) {
1324
- const [channel, value] = writes[idx];
1325
- const writeIdx = langgraphCheckpoint.WRITES_IDX_MAP[channel] ?? idx;
1326
- const innerKey = `${taskId},${writeIdx}`;
1327
- if (writeIdx >= 0 && innerKey in existing) continue;
1328
- const [, serialized] = await this.serde.dumpsTyped(value);
1329
- existing[innerKey] = [taskId, channel, encode(serialized)];
1330
- mutated = true;
1331
- }
1332
- if (!mutated) return;
1333
- await promises.mkdir(this.nsPath(thread, ns), { recursive: true });
1334
- await writeJsonAtomic(this.writesFile(thread, ns, ckptId), existing);
1335
- });
1336
- }
1337
- async deleteThread(threadId) {
1338
- await promises.rm(this.threadDir(threadId), { recursive: true, force: true });
1339
- }
1340
- };
1341
- var PREVIEW_WIDTH = 320;
1342
- function escapeCell(s) {
1343
- return s.replace(/\n/g, " ");
1344
- }
1345
- function toBlazediffRel(cwd, abs) {
1346
- if (!abs) return void 0;
1347
- const root = paths(cwd).root;
1348
- 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));
1349
- return rel.split(path__default.default.sep).join("/");
1350
- }
1351
- function img(src, alt) {
1352
- return `<img src="${src}" width="${PREVIEW_WIDTH}" alt="${alt}">`;
1353
- }
1354
- function baselineCell(r, cwd) {
1355
- const rel = toBlazediffRel(cwd, r.baselinePath) ?? `baselines/${r.id}.png`;
1356
- return img(rel, `${r.id} baseline`);
1357
- }
1358
- function actualCell(r, cwd) {
1359
- const actual = toBlazediffRel(cwd, r.actualPath);
1360
- return actual ? img(actual, `${r.id} actual`) : "-";
1361
- }
1362
- function diffCell(r, cwd) {
1363
- const diff = toBlazediffRel(cwd, r.diffPath);
1364
- return diff ? img(diff, `${r.id} diff`) : "-";
1365
- }
1366
- function verdictCell(r) {
1367
- if (r.status === "missing-baseline") {
1368
- return `missing-baseline - ${r.message ?? "baseline missing"}`;
1369
- }
1370
- if (r.status === "stale-baseline") {
1371
- return `stale-baseline - ${r.message ?? "manifest entry edited without re-capturing"}`;
1372
- }
1373
- if (r.status === "needs-judgment") {
1374
- return `needs-judgment - see judgments/${r.id}/`;
1375
- }
1376
- if (!r.verdict) {
1377
- return r.message ?? r.status;
1378
- }
1379
- return `${r.verdict.label} - ${r.verdict.headline} -> ${r.verdict.action}`;
1380
- }
1381
- function renderRow(r, cwd) {
1382
- return `| ${r.id} | ${escapeCell(baselineCell(r, cwd))} | ${escapeCell(actualCell(r, cwd))} | ${escapeCell(diffCell(r, cwd))} | ${escapeCell(verdictCell(r))} |`;
1383
- }
1384
- function headerLine(report) {
1385
- const { passed, failed, pendingJudgments, totalEntries } = report;
1386
- const parts = [`${passed}/${totalEntries} passed`];
1387
- if (failed > 0) parts.push(`${failed} failed`);
1388
- if (pendingJudgments > 0) parts.push(`${pendingJudgments} pending judgment`);
1389
- return parts.length > 1 ? `${parts[0]} (${parts.slice(1).join(", ")})` : parts[0];
1899
+ };
1390
1900
  }
1391
- function renderSummary(report, cwd = process.cwd()) {
1392
- const nonPass = report.results.filter((r) => r.status !== "pass");
1393
- const lines = [
1394
- `# blazediff check - ${report.createdAt}`,
1395
- "",
1396
- headerLine(report),
1397
- ""
1398
- ];
1399
- if (nonPass.length === 0) {
1400
- lines.push("All entries passed.");
1401
- return `${lines.join("\n")}
1402
- `;
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 };
1403
1908
  }
1404
- lines.push("| id | baseline | actual | diff | verdict |");
1405
- lines.push("| --- | --- | --- | --- | --- |");
1406
- for (const r of nonPass) lines.push(renderRow(r, cwd));
1407
- return `${lines.join("\n")}
1408
- `;
1409
- }
1410
- async function writeSummaryMarkdown(report, cwd = process.cwd()) {
1411
- const file = paths(cwd).summary;
1909
+ };
1910
+ async function writeReport(report, cwd = process.cwd()) {
1911
+ const file = paths(cwd).report;
1412
1912
  await promises.mkdir(path__default.default.dirname(file), { recursive: true });
1413
- await promises.writeFile(file, renderSummary(report, cwd), "utf8");
1913
+ await promises.writeFile(file, `${JSON.stringify(report, null, 2)}
1914
+ `, "utf8");
1414
1915
  return file;
1415
1916
  }
1917
+ async function readReport(cwd = process.cwd()) {
1918
+ return readJsonOrNull(paths(cwd).report);
1919
+ }
1416
1920
 
1417
1921
  // src/judge/apply.ts
1418
1922
  var VALID_LABELS = [
@@ -1450,21 +1954,6 @@ function parseVerdict(raw) {
1450
1954
  confidence: typeof r.confidence === "number" ? r.confidence : void 0
1451
1955
  };
1452
1956
  }
1453
- async function fileExists2(p) {
1454
- try {
1455
- await promises.access(p);
1456
- return true;
1457
- } catch {
1458
- return false;
1459
- }
1460
- }
1461
- async function readJsonOrNull(file) {
1462
- try {
1463
- return JSON.parse(await promises.readFile(file, "utf8"));
1464
- } catch {
1465
- return null;
1466
- }
1467
- }
1468
1957
  async function readJudgmentDirs(root) {
1469
1958
  let names;
1470
1959
  try {
@@ -1562,7 +2051,7 @@ async function reconstructFromDisk(cwd, dirs) {
1562
2051
  pendingJudgments,
1563
2052
  results
1564
2053
  };
1565
- await writeSummaryMarkdown(report, cwd);
2054
+ await writeReport(report, cwd);
1566
2055
  return report;
1567
2056
  }
1568
2057
  async function hasCheckpoint(cwd, threadId) {
@@ -1574,9 +2063,8 @@ async function hasCheckpoint(cwd, threadId) {
1574
2063
  return false;
1575
2064
  }
1576
2065
  }
1577
- async function applyJudgments(opts = process.cwd()) {
1578
- const options = typeof opts === "string" ? { cwd: opts } : opts;
1579
- const cwd = options.cwd ?? process.cwd();
2066
+ async function applyJudgments(opts = {}) {
2067
+ const cwd = opts.cwd ?? process.cwd();
1580
2068
  const manifest = await loadManifest(cwd);
1581
2069
  if (!manifest) {
1582
2070
  throw new Error(
@@ -1610,10 +2098,9 @@ async function applyJudgments(opts = process.cwd()) {
1610
2098
  cwd,
1611
2099
  verdicts,
1612
2100
  threadId,
1613
- onEvent: options.onEvent,
1614
- junitPath: options.junitPath
2101
+ onEvent: opts.onEvent,
2102
+ junitPath: opts.junitPath
1615
2103
  });
1616
- await new FsCheckpointSaver(paths(cwd).checkpoints).deleteThread(threadId).catch(() => void 0);
1617
2104
  return { report, applied, missing, invalid };
1618
2105
  }
1619
2106
  var HOST_INSTRUCTIONS = [
@@ -1623,32 +2110,18 @@ var HOST_INSTRUCTIONS = [
1623
2110
  "Decide whether the change is a regression, an intentional UI change, or rendering noise.",
1624
2111
  "Write your decision to `verdict.json` (next to this `request.json`) with shape:",
1625
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 }',
1626
- "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."
1627
2114
  ].join("\n");
1628
2115
  function relTo(cwd, abs) {
1629
- if (!abs) return void 0;
1630
- return path__default.default.relative(cwd, abs).split(path__default.default.sep).join("/");
1631
- }
1632
- function signatureOf(r) {
1633
- const pct = typeof r.diffPercentage === "number" ? r.diffPercentage.toFixed(4) : "?";
1634
- const regions = r.regions?.length ?? 0;
1635
- const severity = r.severity ?? "?";
1636
- return `${r.status}|diff:${pct}|regions:${regions}|severity:${severity}`;
1637
- }
1638
- async function fileExists3(p) {
1639
- try {
1640
- await promises.access(p);
1641
- return true;
1642
- } catch {
1643
- return false;
1644
- }
1645
- }
1646
- async function readJsonOrNull2(file) {
1647
- try {
1648
- return JSON.parse(await promises.readFile(file, "utf8"));
1649
- } catch {
1650
- return null;
1651
- }
2116
+ if (!abs) return void 0;
2117
+ return path__default.default.relative(cwd, abs).split(path__default.default.sep).join("/");
2118
+ }
2119
+ function signatureOf(r) {
2120
+ const pct = typeof r.diffPercentage === "number" ? r.diffPercentage.toFixed(4) : "?";
2121
+ const severity = r.severity ?? "?";
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}`;
1652
2125
  }
1653
2126
  function entryById(manifest, id) {
1654
2127
  return manifest.entries.find((e) => e.id === id);
@@ -1697,8 +2170,8 @@ async function discoverTiles(dir) {
1697
2170
  const locatorAbs = path__default.default.join(dir, "locator.png");
1698
2171
  const tilesAbs = path__default.default.join(dir, "regions.png");
1699
2172
  const [locator, tiles] = await Promise.all([
1700
- fileExists3(locatorAbs),
1701
- fileExists3(tilesAbs)
2173
+ fileExists2(locatorAbs),
2174
+ fileExists2(tilesAbs)
1702
2175
  ]);
1703
2176
  return {
1704
2177
  locatorPath: locator ? "locator.png" : void 0,
@@ -1715,92 +2188,380 @@ async function writeJudgments(opts) {
1715
2188
  opts.report.results.map(async (result) => {
1716
2189
  const dir = path__default.default.join(root, result.id);
1717
2190
  if (result.status === "pass") {
1718
- if (await fileExists3(dir))
2191
+ if (await fileExists2(dir))
1719
2192
  await promises.rm(dir, { recursive: true, force: true });
1720
2193
  return;
1721
2194
  }
1722
- const entry = entryById(opts.manifest, result.id);
1723
- if (!entry) return;
1724
- await promises.mkdir(dir, { recursive: true });
1725
- const tiles = await discoverTiles(dir);
1726
- const request = buildRequest(result, entry, cwd, tiles);
1727
- const requestFile = path__default.default.join(dir, "request.json");
1728
- const verdictFile = path__default.default.join(dir, "verdict.json");
1729
- const [prior, priorVerdict] = await Promise.all([
1730
- readJsonOrNull2(requestFile),
1731
- fileExists3(verdictFile).then(
1732
- (exists) => exists ? readJsonOrNull2(verdictFile) : null
1733
- )
1734
- ]);
1735
- const signatureMatches = prior !== null && prior.signature === request.signature;
1736
- await promises.writeFile(
1737
- requestFile,
1738
- `${JSON.stringify(request, null, 2)}
1739
- `,
1740
- "utf8"
2195
+ const entry = entryById(opts.manifest, result.id);
2196
+ if (!entry) return;
2197
+ await promises.mkdir(dir, { recursive: true });
2198
+ const tiles = await discoverTiles(dir);
2199
+ const request = buildRequest(result, entry, cwd, tiles);
2200
+ const requestFile = path__default.default.join(dir, "request.json");
2201
+ const verdictFile = path__default.default.join(dir, "verdict.json");
2202
+ const [prior, priorVerdict] = await Promise.all([
2203
+ readJsonOrNull(requestFile),
2204
+ fileExists2(verdictFile).then(
2205
+ (exists) => exists ? readJsonOrNull(verdictFile) : null
2206
+ )
2207
+ ]);
2208
+ const signatureMatches = prior !== null && prior.signature === request.signature;
2209
+ await promises.writeFile(
2210
+ requestFile,
2211
+ `${JSON.stringify(request, null, 2)}
2212
+ `,
2213
+ "utf8"
2214
+ );
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
2444
+ }
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)
2462
+ );
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
+ }
2488
+ }
2489
+ }
2490
+ }
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.'
1741
2496
  );
1742
- if (priorVerdict && signatureMatches) {
1743
- return;
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
1744
2518
  }
1745
- const auto = autoVerdict(result);
1746
- if (auto) {
1747
- await promises.writeFile(
1748
- verdictFile,
1749
- `${JSON.stringify(auto, null, 2)}
1750
- `,
1751
- "utf8"
1752
- );
1753
- } else if (priorVerdict && !signatureMatches) {
1754
- await promises.rm(verdictFile, { force: true });
2519
+ };
2520
+ }
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
+ );
2527
+ }
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;
1755
2547
  }
1756
- })
1757
- );
1758
- let entries;
1759
- try {
1760
- entries = await promises.readdir(root);
1761
- } catch {
1762
- return;
2548
+ if (!mutated) return;
2549
+ await promises.mkdir(this.nsPath(thread, ns), { recursive: true });
2550
+ await writeJsonAtomic(this.writesFile(thread, ns, ckptId), existing);
2551
+ });
1763
2552
  }
1764
- await Promise.all(
1765
- entries.filter((name) => !knownIds.has(name)).map(
1766
- (name) => promises.rm(path__default.default.join(root, name), { recursive: true, force: true })
1767
- )
1768
- );
1769
- }
1770
-
1771
- // src/judge/index.ts
1772
- function resolveJudge(backend) {
1773
- switch (backend) {
1774
- case "none":
1775
- return noneJudge;
1776
- case "host":
1777
- return hostHarnessJudge;
2553
+ async deleteThread(threadId) {
2554
+ await promises.rm(this.threadDir(threadId), { recursive: true, force: true });
1778
2555
  }
2556
+ };
2557
+
2558
+ // src/graph/events.ts
2559
+ var sink;
2560
+ function setEventSink(fn) {
2561
+ sink = fn;
1779
2562
  }
1780
- function escapeXml(value) {
1781
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1782
- }
1783
- async function writeJunit(report, destPath) {
1784
- await promises.mkdir(path__default.default.dirname(destPath), { recursive: true });
1785
- const cases = report.results.map((r) => {
1786
- if (r.status === "pass") {
1787
- return ` <testcase classname="blazediff" name="${escapeXml(r.id)}"/>`;
1788
- }
1789
- const message = r.message ?? r.status;
1790
- return ` <testcase classname="blazediff" name="${escapeXml(r.id)}">
1791
- <failure message="${escapeXml(message)}" type="${escapeXml(r.status)}">${escapeXml(message)}</failure>
1792
- </testcase>`;
1793
- });
1794
- const failures = report.totalEntries - report.passed;
1795
- const xml = `<?xml version="1.0" encoding="UTF-8"?>
1796
- <testsuites>
1797
- <testsuite name="blazediff" tests="${report.totalEntries}" failures="${failures}">
1798
- ${cases.join("\n")}
1799
- </testsuite>
1800
- </testsuites>
1801
- `;
1802
- await promises.writeFile(destPath, xml, "utf8");
1803
- return destPath;
2563
+ function emitEvent(event) {
2564
+ sink?.(event);
1804
2565
  }
1805
2566
 
1806
2567
  // src/graph/nodes/results.ts
@@ -1855,6 +2616,8 @@ function failResult(entry, outcome, actualPath, baselinePath, verdict) {
1855
2616
  diffPercentage: outcome.diffPercentage,
1856
2617
  severity: outcome.interpretation?.severity,
1857
2618
  regions: outcome.interpretation?.regions?.map(narrowRegion),
2619
+ width: outcome.interpretation?.width,
2620
+ height: outcome.interpretation?.height,
1858
2621
  verdict,
1859
2622
  diffPath: outcome.diffPath,
1860
2623
  baselinePath,
@@ -1864,13 +2627,8 @@ function failResult(entry, outcome, actualPath, baselinePath, verdict) {
1864
2627
  }
1865
2628
 
1866
2629
  // src/graph/nodes/capture.ts
1867
- var legacyAuthHinted = false;
1868
- function maybePrintLegacyHint() {
1869
- if (legacyAuthHinted) return;
1870
- legacyAuthHinted = true;
1871
- process.stderr.write(
1872
- 'blazediff: manifest entries with auth: "required" are treated as persona "default" \u2014 please migrate.\n'
1873
- );
2630
+ function asCaptured(entry, output) {
2631
+ return { entry, output };
1874
2632
  }
1875
2633
  function makeCaptureNode(semaphore) {
1876
2634
  return async function captureNode(state) {
@@ -1879,27 +2637,39 @@ function makeCaptureNode(semaphore) {
1879
2637
  if (!entry || !options) {
1880
2638
  throw new Error("captureNode: entry or options missing");
1881
2639
  }
2640
+ const children = state.children;
1882
2641
  if (isEntryStale(entry)) {
1883
2642
  return {
1884
- captureOutput: { id: entry.id, skipResult: staleResult(entry) }
2643
+ captured: [
2644
+ asCaptured(entry, {
2645
+ id: entry.id,
2646
+ skipResult: staleResult(entry)
2647
+ }),
2648
+ ...children.map(
2649
+ (c) => asCaptured(c, { id: c.id, skipResult: staleResult(c) })
2650
+ )
2651
+ ]
1885
2652
  };
1886
2653
  }
1887
- let auth;
1888
- if (entry.auth !== null) {
1889
- if (entry.auth === LEGACY_REQUIRED) maybePrintLegacyHint();
1890
- try {
1891
- auth = buildAuthHook(entry.auth, options.auth, options.cwd);
1892
- } catch (err) {
1893
- if (err instanceof AuthConfigMissingError) {
1894
- return {
1895
- captureOutput: {
1896
- id: entry.id,
1897
- skipResult: errorResult(entry, err.message)
1898
- }
1899
- };
1900
- }
1901
- throw err;
1902
- }
2654
+ const failAll = (message) => ({
2655
+ captured: [
2656
+ asCaptured(entry, {
2657
+ id: entry.id,
2658
+ skipResult: errorResult(entry, message)
2659
+ }),
2660
+ ...children.map(
2661
+ (c) => asCaptured(c, { id: c.id, skipResult: errorResult(c, message) })
2662
+ )
2663
+ ]
2664
+ });
2665
+ let harnesses;
2666
+ try {
2667
+ harnesses = await resolveHarnesses(
2668
+ normalizeHarnessRefs(entry.harnesses),
2669
+ options.cwd
2670
+ );
2671
+ } catch (err) {
2672
+ return failAll(`harness: ${err.message}`);
1903
2673
  }
1904
2674
  const baselinePath = path__default.default.join(options.baselinesDir, `${entry.id}.png`);
1905
2675
  try {
@@ -1916,24 +2686,54 @@ function makeCaptureNode(semaphore) {
1916
2686
  mode: "actual"
1917
2687
  },
1918
2688
  options.cwd,
1919
- auth
2689
+ harnesses
1920
2690
  )
1921
2691
  );
1922
- return {
1923
- captureOutput: {
2692
+ const items = [
2693
+ asCaptured(entry, {
1924
2694
  id: entry.id,
1925
2695
  captureOutputPath: capture.outputPath,
1926
2696
  baselinePath
2697
+ })
2698
+ ];
2699
+ const subByName = new Map(
2700
+ (capture.subCaptures ?? []).map((s) => [s.name, s])
2701
+ );
2702
+ for (const child of children) {
2703
+ const name = subNameOf(child);
2704
+ const sub = name ? subByName.get(name) : void 0;
2705
+ const childBaseline = path__default.default.join(
2706
+ options.baselinesDir,
2707
+ `${child.id}.png`
2708
+ );
2709
+ if (sub) {
2710
+ items.push(
2711
+ asCaptured(child, {
2712
+ id: child.id,
2713
+ captureOutputPath: sub.outputPath,
2714
+ baselinePath: childBaseline
2715
+ })
2716
+ );
2717
+ } else {
2718
+ items.push(
2719
+ asCaptured(child, {
2720
+ id: child.id,
2721
+ skipResult: errorResult(
2722
+ child,
2723
+ `harness did not produce screenshot "${name ?? child.id}"`
2724
+ )
2725
+ })
2726
+ );
1927
2727
  }
1928
- };
2728
+ }
2729
+ for (const item of items) {
2730
+ if (item.output.captureOutputPath)
2731
+ emitEvent({ type: "captured", entryId: item.entry.id });
2732
+ }
2733
+ return { captured: items };
1929
2734
  } catch (err) {
1930
- if (err instanceof AuthHarnessError) {
1931
- return {
1932
- captureOutput: {
1933
- id: entry.id,
1934
- skipResult: errorResult(entry, `auth: ${err.message}`)
1935
- }
1936
- };
2735
+ if (err instanceof HarnessError) {
2736
+ return failAll(`harness: ${err.message}`);
1937
2737
  }
1938
2738
  throw err;
1939
2739
  }
@@ -2158,6 +2958,7 @@ async function judgeNode(state) {
2158
2958
  throw new Error("judgeNode: entry, options, or diff missing");
2159
2959
  }
2160
2960
  if (diff.skipResult) {
2961
+ emitEvent({ type: "result", result: diff.skipResult });
2161
2962
  return { results: [diff.skipResult] };
2162
2963
  }
2163
2964
  const outcome = diff.outcome;
@@ -2167,7 +2968,9 @@ async function judgeNode(state) {
2167
2968
  throw new Error("judgeNode: diff outputs missing");
2168
2969
  }
2169
2970
  if (outcome.match) {
2170
- return { results: [passResult(entry, baselinePath, captureOutputPath)] };
2971
+ const r = passResult(entry, baselinePath, captureOutputPath);
2972
+ emitEvent({ type: "result", result: r });
2973
+ return { results: [r] };
2171
2974
  }
2172
2975
  const verdict = deriveVerdict({
2173
2976
  reason: outcome.reason,
@@ -2175,48 +2978,62 @@ async function judgeNode(state) {
2175
2978
  diffCount: outcome.diffCount,
2176
2979
  diffPercentage: outcome.diffPercentage
2177
2980
  });
2178
- let result = failResult(
2981
+ const initial = failResult(
2179
2982
  entry,
2180
2983
  outcome,
2181
2984
  captureOutputPath,
2182
2985
  baselinePath,
2183
2986
  verdict
2184
2987
  );
2185
- if (result.baselinePath && result.actualPath) {
2186
- const judge = resolveJudge(options.judge);
2187
- const output = await judge.judge(
2188
- {
2189
- entry,
2190
- baselinePath: result.baselinePath,
2191
- actualPath: result.actualPath,
2192
- diffPath: result.diffPath,
2193
- regions: result.regions,
2194
- diffPercentage: result.diffPercentage,
2195
- severity: result.severity,
2196
- heuristicVerdict: result.verdict ?? verdict
2197
- },
2198
- 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}`
2199
3013
  );
2200
- if (output.kind === "judged") {
2201
- result = { ...result, verdict: output.verdict };
2202
- } else {
2203
- const pending = {
2204
- ...result,
2205
- status: "needs-judgment",
2206
- message: `awaiting judgment in ${output.requestPath}`
2207
- };
2208
- const resumed = interruptForJudgment({
2209
- kind: "host-judgment-required",
2210
- entryId: entry.id,
2211
- url: entry.url,
2212
- requestPath: output.requestPath,
2213
- signature: signatureOf(result),
2214
- pendingResult: pending
2215
- });
2216
- result = resumed ? { ...result, verdict: resumed } : pending;
2217
- }
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;
2218
3034
  }
2219
- return { results: [result] };
3035
+ emitEvent({ type: "result", result: final });
3036
+ return { results: [final] };
2220
3037
  }
2221
3038
 
2222
3039
  // src/graph/nodes/load.ts
@@ -2232,67 +3049,80 @@ async function loadNode(state) {
2232
3049
  }
2233
3050
  return { entries: manifest.entries, manifest };
2234
3051
  }
2235
- 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({
2236
3057
  reducer: (acc, next) => [...acc, ...next],
2237
3058
  default: () => []
2238
3059
  });
2239
- var BranchState = langgraph.Annotation.Root({
2240
- entry: langgraph.Annotation({
2241
- reducer: (_, next) => next,
2242
- default: () => void 0
2243
- }),
2244
- options: langgraph.Annotation({
2245
- reducer: (acc, next) => next ?? acc,
2246
- default: () => void 0
2247
- }),
2248
- captureOutput: langgraph.Annotation({
2249
- reducer: (_, next) => next,
2250
- default: () => void 0
2251
- }),
2252
- diffOutput: langgraph.Annotation({
3060
+ var replaceList = () => langgraph.Annotation({
3061
+ reducer: (acc, next) => next ?? acc,
3062
+ default: () => []
3063
+ });
3064
+ var resultsChannel = appendList();
3065
+ var capturedChannel = appendList();
3066
+ var CaptureState = langgraph.Annotation.Root({
3067
+ entry: latest(),
3068
+ children: langgraph.Annotation({
2253
3069
  reducer: (_, next) => next,
2254
- default: () => void 0
3070
+ default: () => []
2255
3071
  }),
3072
+ options: latest(),
3073
+ captured: capturedChannel
3074
+ });
3075
+ var BranchState = langgraph.Annotation.Root({
3076
+ entry: latest(),
3077
+ options: latest(),
3078
+ captureOutput: latest(),
3079
+ diffOutput: latest(),
2256
3080
  results: resultsChannel
2257
3081
  });
2258
3082
  var GraphState = langgraph.Annotation.Root({
2259
- options: langgraph.Annotation({
2260
- reducer: (acc, next) => next ?? acc,
2261
- default: () => void 0
2262
- }),
2263
- entries: langgraph.Annotation({
2264
- reducer: (acc, next) => next ?? acc,
2265
- default: () => []
2266
- }),
3083
+ options: latest(),
3084
+ entries: replaceList(),
3085
+ captured: capturedChannel,
2267
3086
  results: resultsChannel,
2268
- manifest: langgraph.Annotation({
2269
- reducer: (acc, next) => next ?? acc,
2270
- default: () => void 0
2271
- }),
2272
- report: langgraph.Annotation({
2273
- reducer: (acc, next) => next ?? acc,
2274
- default: () => void 0
2275
- })
3087
+ manifest: latest(),
3088
+ report: latest()
2276
3089
  });
2277
3090
 
2278
3091
  // src/graph/index.ts
2279
- function cpuParallelism() {
2280
- const cores = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length;
2281
- if (!cores || !Number.isFinite(cores)) return 2;
2282
- return Math.max(2, cores);
2283
- }
2284
3092
  function threadIdFor(cwd) {
2285
3093
  return crypto$1.createHash("sha1").update(paths(cwd).manifest).digest("hex").slice(0, 16);
2286
3094
  }
2287
- function buildBranchGraph(captureSemaphore, diffSemaphore) {
2288
- return new langgraph.StateGraph(BranchState).addNode("capture", makeCaptureNode(captureSemaphore)).addNode("diff", makeDiffNode(diffSemaphore)).addNode("judge", judgeNode).addEdge(langgraph.START, "capture").addEdge("capture", "diff").addEdge("diff", "judge").addEdge("judge", langgraph.END).compile();
3095
+ function buildCaptureGraph(captureSemaphore) {
3096
+ return new langgraph.StateGraph(CaptureState).addNode("capture", makeCaptureNode(captureSemaphore)).addEdge(langgraph.START, "capture").addEdge("capture", langgraph.END).compile();
3097
+ }
3098
+ function buildBranchGraph(diffSemaphore) {
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();
3100
+ }
3101
+ async function dispatchNode(state) {
3102
+ if (state.options) await resolveJudge(state.options.judge).warmup?.();
3103
+ return {};
2289
3104
  }
2290
3105
  function buildGraph(captureSemaphore, diffSemaphore, checkpointer) {
2291
- const branch = buildBranchGraph(captureSemaphore, diffSemaphore);
2292
- return new langgraph.StateGraph(GraphState).addNode("load", loadNode).addNode("branch", branch).addEdge(langgraph.START, "load").addConditionalEdges(
3106
+ const captureBranch = buildCaptureGraph(captureSemaphore);
3107
+ const branch = buildBranchGraph(diffSemaphore);
3108
+ return new langgraph.StateGraph(GraphState).addNode("load", loadNode).addNode("capture", captureBranch).addNode("dispatch", dispatchNode).addNode("branch", branch).addEdge(langgraph.START, "load").addConditionalEdges(
2293
3109
  "load",
2294
- (state) => state.entries.map(
2295
- (entry) => new langgraph.Send("branch", { entry, options: state.options })
3110
+ (state) => state.entries.filter((entry) => !isDerived(entry)).map(
3111
+ (entry) => new langgraph.Send("capture", {
3112
+ entry,
3113
+ children: state.entries.filter((e) => e.parent === entry.id),
3114
+ options: state.options
3115
+ })
3116
+ ),
3117
+ ["capture"]
3118
+ ).addEdge("capture", "dispatch").addConditionalEdges(
3119
+ "dispatch",
3120
+ (state) => state.captured.map(
3121
+ (c) => new langgraph.Send("branch", {
3122
+ entry: c.entry,
3123
+ captureOutput: c.output,
3124
+ options: state.options
3125
+ })
2296
3126
  ),
2297
3127
  ["branch"]
2298
3128
  ).addEdge("branch", langgraph.END).compile({ checkpointer });
@@ -2322,10 +3152,7 @@ async function streamGraph(graph, input, threadId, onEvent) {
2322
3152
  const part = partial;
2323
3153
  if (!part) continue;
2324
3154
  if (part.results) {
2325
- for (const r of part.results) {
2326
- collect.results.push(r);
2327
- onEvent?.({ type: "result", result: r });
2328
- }
3155
+ for (const r of part.results) collect.results.push(r);
2329
3156
  }
2330
3157
  if (part.manifest) collect.manifest = part.manifest;
2331
3158
  if (part.report) {
@@ -2359,15 +3186,15 @@ async function buildPartialReport(collect, cwd) {
2359
3186
  if (manifest) {
2360
3187
  await writeJudgments({ report, manifest, cwd });
2361
3188
  }
2362
- await writeSummaryMarkdown(report, cwd);
3189
+ await writeReport(report, cwd);
2363
3190
  await ensureGitignore(cwd);
2364
3191
  return report;
2365
3192
  }
2366
3193
  async function runGraph(opts) {
2367
3194
  const cwd = opts.cwd ?? process.cwd();
2368
3195
  const concurrency = opts.concurrency ?? defaultConcurrency();
2369
- const captureSemaphore = new Semaphore(concurrency);
2370
- const diffSemaphore = new Semaphore(cpuParallelism());
3196
+ const captureSemaphore = createSemaphore(concurrency);
3197
+ const diffSemaphore = createSemaphore(cpuCores());
2371
3198
  const baselinesDir = paths(cwd).baselines;
2372
3199
  const checkpointer = new FsCheckpointSaver(paths(cwd).checkpoints);
2373
3200
  const graph = buildGraph(captureSemaphore, diffSemaphore, checkpointer);
@@ -2375,7 +3202,6 @@ async function runGraph(opts) {
2375
3202
  if (!opts.resume) {
2376
3203
  await checkpointer.deleteThread(threadId);
2377
3204
  }
2378
- const config = await loadConfig(cwd);
2379
3205
  const input = opts.resume ? new langgraph.Command({ resume: opts.resume }) : {
2380
3206
  options: {
2381
3207
  baseUrl: opts.baseUrl ?? "",
@@ -2384,14 +3210,15 @@ async function runGraph(opts) {
2384
3210
  concurrency,
2385
3211
  emitDiffPng: opts.emitDiffPng ?? true,
2386
3212
  judge: opts.judge ?? "none",
2387
- baselinesDir,
2388
- auth: config?.auth
3213
+ baselinesDir
2389
3214
  }
2390
3215
  };
2391
3216
  let collect;
3217
+ setEventSink(opts.onEvent);
2392
3218
  try {
2393
3219
  collect = await streamGraph(graph, input, threadId, opts.onEvent);
2394
3220
  } finally {
3221
+ setEventSink(void 0);
2395
3222
  await closeBrowser();
2396
3223
  }
2397
3224
  const report = collect.report ?? await buildPartialReport(collect, cwd);
@@ -2417,17 +3244,141 @@ function runCheck(opts) {
2417
3244
  return runGraph(opts);
2418
3245
  }
2419
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
+
3363
+ exports.HarnessError = HarnessError;
2420
3364
  exports.STABILITY_HOOKS_VERSION = STABILITY_HOOKS_VERSION;
2421
3365
  exports.applyJudgments = applyJudgments;
3366
+ exports.approveEntry = approveEntry;
3367
+ exports.assertLeftLoginPage = assertLeftLoginPage;
2422
3368
  exports.captureScreenshot = captureScreenshot;
2423
3369
  exports.configHash = configHash;
2424
3370
  exports.diffEntry = diffEntry;
2425
3371
  exports.discover = discover;
2426
3372
  exports.installBrowsers = installBrowsers;
2427
3373
  exports.loadConfig = loadConfig;
3374
+ exports.loadEnvFiles = loadEnvFiles;
3375
+ exports.loadHarness = loadHarness;
2428
3376
  exports.loadManifest = loadManifest;
2429
3377
  exports.paths = paths;
3378
+ exports.readReport = readReport;
3379
+ exports.rejectEntry = rejectEntry;
2430
3380
  exports.resolveBaseUrl = resolveBaseUrl;
3381
+ exports.resolveHarnessFile = resolveHarnessFile;
2431
3382
  exports.resolveJudge = resolveJudge;
2432
3383
  exports.resumeGraph = resumeGraph;
2433
3384
  exports.runCaptures = runCaptures;
@@ -2436,3 +3387,4 @@ exports.runGraph = runGraph;
2436
3387
  exports.saveConfig = saveConfig;
2437
3388
  exports.saveManifest = saveManifest;
2438
3389
  exports.threadIdFor = threadIdFor;
3390
+ exports.writeReport = writeReport;