@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.mjs CHANGED
@@ -1,15 +1,17 @@
1
- import { mkdir, readFile, writeFile, access, readdir, stat, rm, rename } from 'fs/promises';
1
+ import { mkdir, readFile, writeFile, copyFile, rm, access, readdir, stat, rename } from 'fs/promises';
2
2
  import path from 'path';
3
3
  import { availableParallelism, cpus } from 'os';
4
+ import { existsSync, readFileSync } from 'fs';
5
+ import { pathToFileURL } from 'url';
4
6
  import { chromium } from 'playwright';
5
7
  import { spawn } from 'child_process';
6
- import { existsSync } from 'fs';
7
8
  import { createRequire } from 'module';
8
- import { pathToFileURL } from 'url';
9
9
  import { createHash } from 'crypto';
10
10
  import { compare } from '@blazediff/core-native';
11
+ import * as util from 'util';
11
12
  import { Annotation, Command, StateGraph, START, Send, END, interrupt } from '@langchain/langgraph';
12
13
  import sharp from 'sharp';
14
+ import pc from 'picocolors';
13
15
  import { BaseCheckpointSaver, TASKS, maxChannelVersion, getCheckpointId, copyCheckpoint, WRITES_IDX_MAP } from '@langchain/langgraph-checkpoint';
14
16
 
15
17
  // src/browser/capture.ts
@@ -19,12 +21,15 @@ var DEFAULT_FULL_PAGE = true;
19
21
  var DEFAULT_THRESHOLD = 0.1;
20
22
  var MIN_AUTO_CONCURRENCY = 2;
21
23
  var MAX_AUTO_CONCURRENCY = 8;
22
- function defaultConcurrency() {
24
+ function cpuCores() {
23
25
  const cores = typeof availableParallelism === "function" ? availableParallelism() : cpus().length;
24
26
  if (!cores || !Number.isFinite(cores)) return MIN_AUTO_CONCURRENCY;
27
+ return cores;
28
+ }
29
+ function defaultConcurrency() {
25
30
  return Math.max(
26
31
  MIN_AUTO_CONCURRENCY,
27
- Math.min(MAX_AUTO_CONCURRENCY, cores - 1)
32
+ Math.min(MAX_AUTO_CONCURRENCY, cpuCores() - 1)
28
33
  );
29
34
  }
30
35
  var BLAZEDIFF_DIR = ".blazediff";
@@ -34,16 +39,104 @@ var paths = (cwd = process.cwd()) => {
34
39
  root,
35
40
  config: path.join(root, "config.json"),
36
41
  manifest: path.join(root, "manifest.json"),
42
+ harnesses: path.join(root, "harnesses"),
37
43
  baselines: path.join(root, "baselines"),
38
44
  actual: path.join(root, "actual"),
39
45
  judgments: path.join(root, "judgments"),
40
46
  checkpoints: path.join(root, "checkpoints"),
41
- summary: path.join(root, "summary.md"),
47
+ report: path.join(root, "report.json"),
42
48
  gitignore: path.join(root, ".gitignore"),
43
49
  serverLog: path.join(root, "dev-server.log"),
44
50
  serverPid: path.join(root, "dev-server.pid")
45
51
  };
46
52
  };
53
+
54
+ // src/harness/loader.ts
55
+ var HarnessError = class extends Error {
56
+ constructor(message, cause) {
57
+ super(message);
58
+ this.cause = cause;
59
+ this.name = "HarnessError";
60
+ }
61
+ };
62
+ var moduleCache = /* @__PURE__ */ new Map();
63
+ function resolveHarnessFile(name, cwd) {
64
+ if (name.includes("/") || name.includes("\\") || path.isAbsolute(name)) {
65
+ return path.isAbsolute(name) ? name : path.resolve(cwd, name);
66
+ }
67
+ const dir = paths(cwd).harnesses;
68
+ const mjs = path.join(dir, `${name}.mjs`);
69
+ if (existsSync(mjs)) return mjs;
70
+ return path.join(dir, `${name}.js`);
71
+ }
72
+ async function loadHarness(harnessFile) {
73
+ const absolute = path.isAbsolute(harnessFile) ? harnessFile : path.resolve(process.cwd(), harnessFile);
74
+ if (!existsSync(absolute)) {
75
+ throw new HarnessError(
76
+ `harness not found at ${absolute}. Author one under .blazediff/harnesses/ (or run \`blazediff-agent harness record <name>\` to record one).`
77
+ );
78
+ }
79
+ const cached = moduleCache.get(absolute);
80
+ if (cached) return cached;
81
+ const url = pathToFileURL(absolute).href;
82
+ const loading = (async () => {
83
+ let mod;
84
+ try {
85
+ mod = await import(
86
+ /* @vite-ignore */
87
+ url
88
+ );
89
+ } catch (err) {
90
+ throw new HarnessError(
91
+ `failed to load harness at ${absolute}: ${err.message}`,
92
+ err
93
+ );
94
+ }
95
+ const harness = mod.default;
96
+ if (!harness || typeof harness.run !== "function") {
97
+ if (typeof mod.login === "function") {
98
+ throw new HarnessError(
99
+ `legacy auth harness detected at ${absolute} (exports \`login\`). Re-run \`blazediff-agent harness record auth --login\` to regenerate it as a harness.`
100
+ );
101
+ }
102
+ throw new HarnessError(
103
+ `harness at ${absolute} must default-export an object with a \`run(ctx)\` function`
104
+ );
105
+ }
106
+ return { phase: harness.phase ?? "interact", run: harness.run };
107
+ })();
108
+ moduleCache.set(absolute, loading);
109
+ return loading;
110
+ }
111
+ function loginPathOf(loginUrl) {
112
+ try {
113
+ return new URL(loginUrl, "http://placeholder").pathname;
114
+ } catch {
115
+ return loginUrl;
116
+ }
117
+ }
118
+ async function assertLeftLoginPage(page, loginUrl) {
119
+ const loginPath = loginPathOf(loginUrl);
120
+ let currentPath;
121
+ try {
122
+ currentPath = new URL(page.url()).pathname;
123
+ } catch {
124
+ currentPath = page.url();
125
+ }
126
+ if (loginPath && currentPath === loginPath) {
127
+ throw new HarnessError(
128
+ `login harness returned but page is still on the login URL (${currentPath}). Check that the harness submits the form and waits for redirect.`
129
+ );
130
+ }
131
+ await page.locator('input[type="password"]').first().waitFor({ state: "detached", timeout: 2e3 }).catch(() => {
132
+ });
133
+ const passwordInputs = await page.locator('input[type="password"]:visible').count().catch(() => 0);
134
+ if (passwordInputs > 0) {
135
+ throw new HarnessError(
136
+ `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).`
137
+ );
138
+ }
139
+ }
47
140
  var FROZEN_NOW = Date.UTC(2025, 0, 1, 0, 0, 0);
48
141
  var STABILITY_CSS = `
49
142
  *,*::before,*::after{
@@ -72,7 +165,13 @@ var contextPool = /* @__PURE__ */ new Map();
72
165
  async function getBrowser() {
73
166
  if (cachedBrowser?.isConnected()) return cachedBrowser;
74
167
  if (launchInFlight) return launchInFlight;
75
- launchInFlight = chromium.launch({ headless: true, args: CHROMIUM_FLAGS }).then((b) => {
168
+ launchInFlight = chromium.launch({
169
+ headless: true,
170
+ args: CHROMIUM_FLAGS,
171
+ handleSIGINT: false,
172
+ handleSIGTERM: false,
173
+ handleSIGHUP: false
174
+ }).then((b) => {
76
175
  cachedBrowser = b;
77
176
  return b;
78
177
  }).finally(() => {
@@ -204,6 +303,11 @@ var DEFAULT_MASK_SELECTOR = `[${DEFAULT_MASK_ATTR}]`;
204
303
  async function applyMaskOverlays(page, masks) {
205
304
  const selectors = [DEFAULT_MASK_SELECTOR, ...masks];
206
305
  await page.evaluate((selectors2) => {
306
+ for (const stale of Array.from(
307
+ document.querySelectorAll("[data-blazediff-mask]")
308
+ )) {
309
+ stale.remove();
310
+ }
207
311
  for (const sel of selectors2) {
208
312
  for (const el of Array.from(
209
313
  document.querySelectorAll(sel)
@@ -226,39 +330,90 @@ async function applyMaskOverlays(page, masks) {
226
330
  }
227
331
 
228
332
  // src/browser/capture.ts
229
- async function captureScreenshot(baseUrl, opts, cwd = process.cwd(), auth) {
333
+ var SCREENSHOT_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/i;
334
+ async function shoot(page, outputPath, fullPage) {
335
+ await mkdir(path.dirname(outputPath), { recursive: true });
336
+ const buffer = await page.screenshot({
337
+ path: outputPath,
338
+ type: "png",
339
+ fullPage,
340
+ animations: "disabled",
341
+ caret: "hide",
342
+ scale: "device"
343
+ });
344
+ return buffer.length;
345
+ }
346
+ async function stabilize(page, waitFor, masks) {
347
+ await waitForStability(page, waitFor);
348
+ await applyMaskOverlays(page, masks);
349
+ await page.evaluate(
350
+ () => new Promise((r) => requestAnimationFrame(() => r()))
351
+ );
352
+ }
353
+ async function captureScreenshot(baseUrl, opts, cwd = process.cwd(), harnesses) {
230
354
  const viewport = opts.viewport ?? DEFAULT_VIEWPORT;
231
355
  const waitFor = opts.waitFor ?? DEFAULT_WAIT_FOR;
232
356
  const masks = opts.mask ?? [];
233
357
  const fullPage = opts.fullPage ?? DEFAULT_FULL_PAGE;
358
+ const setup = (harnesses ?? []).filter(
359
+ (h) => (h.harness.phase ?? "interact") === "setup"
360
+ );
361
+ const interact = (harnesses ?? []).filter(
362
+ (h) => (h.harness.phase ?? "interact") !== "setup"
363
+ );
234
364
  const handle = await acquireStableContext(viewport, {
235
- pool: !auth,
365
+ pool: !(harnesses && harnesses.length > 0),
236
366
  baseURL: baseUrl || void 0
237
367
  });
368
+ const context = handle.context;
369
+ const browser = await getBrowser();
238
370
  const page = await openStablePage(handle);
239
371
  try {
240
- if (auth) {
241
- await auth.hook(page);
372
+ const rejectScreenshot = async () => {
373
+ throw new HarnessError("setup harness must not call screenshot()");
374
+ };
375
+ for (const { harness, params } of setup) {
376
+ await harness.run({
377
+ page,
378
+ browser,
379
+ context,
380
+ params,
381
+ screenshot: rejectScreenshot
382
+ });
242
383
  }
243
384
  const url = new URL(opts.url, baseUrl).toString();
244
385
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 3e4 });
245
- await waitForStability(page, waitFor);
246
- await applyMaskOverlays(page, masks);
247
- await page.evaluate(
248
- () => new Promise((r) => requestAnimationFrame(() => r()))
249
- );
386
+ await stabilize(page, waitFor, masks);
250
387
  const outputDir = opts.mode === "baseline" ? paths(cwd).baselines : paths(cwd).actual;
251
- await mkdir(outputDir, { recursive: true });
252
388
  const outputPath = path.join(outputDir, `${opts.id}.png`);
253
- const buffer = await page.screenshot({
254
- path: outputPath,
255
- type: "png",
256
- fullPage,
257
- animations: "disabled",
258
- caret: "hide",
259
- scale: "device"
260
- });
261
- return { id: opts.id, outputPath, mode: opts.mode, bytes: buffer.length };
389
+ const bytes = await shoot(page, outputPath, fullPage);
390
+ const subCaptures = [];
391
+ const used = /* @__PURE__ */ new Set();
392
+ const screenshot = async (name) => {
393
+ if (!SCREENSHOT_NAME_RE.test(name)) {
394
+ throw new HarnessError(
395
+ `invalid screenshot name "${name}": use alphanumeric/kebab-case (no "__", spaces, or slashes)`
396
+ );
397
+ }
398
+ if (used.has(name)) {
399
+ throw new HarnessError(`duplicate screenshot name "${name}"`);
400
+ }
401
+ used.add(name);
402
+ await stabilize(page, waitFor, masks);
403
+ const subPath = path.join(outputDir, `${opts.id}__${name}.png`);
404
+ const subBytes = await shoot(page, subPath, fullPage);
405
+ subCaptures.push({ name, outputPath: subPath, bytes: subBytes });
406
+ };
407
+ for (const { harness, params } of interact) {
408
+ await harness.run({ page, browser, context, params, screenshot });
409
+ }
410
+ return {
411
+ id: opts.id,
412
+ outputPath,
413
+ mode: opts.mode,
414
+ bytes,
415
+ subCaptures: subCaptures.length > 0 ? subCaptures : void 0
416
+ };
262
417
  } finally {
263
418
  await page.close().catch(() => {
264
419
  });
@@ -312,112 +467,6 @@ async function installBrowsers(opts = {}) {
312
467
  const executablePath = await readExecutablePath();
313
468
  return { installed: Boolean(executablePath), executablePath, cliPath };
314
469
  }
315
-
316
- // src/auth/env.ts
317
- var LEGACY_REQUIRED = "required";
318
- var DEFAULT_PERSONA = "default";
319
- function canonicalPersona(auth) {
320
- return auth === LEGACY_REQUIRED ? DEFAULT_PERSONA : auth;
321
- }
322
- var AuthHarnessError = class extends Error {
323
- constructor(message, cause) {
324
- super(message);
325
- this.cause = cause;
326
- this.name = "AuthHarnessError";
327
- }
328
- };
329
- var moduleCache = /* @__PURE__ */ new Map();
330
- async function loadAuthHarness(harnessFile) {
331
- const absolute = path.isAbsolute(harnessFile) ? harnessFile : path.resolve(process.cwd(), harnessFile);
332
- if (!existsSync(absolute)) {
333
- throw new AuthHarnessError(
334
- `auth harness not found at ${absolute}. Run \`blazediff-agent auth init\` to create one.`
335
- );
336
- }
337
- const cached = moduleCache.get(absolute);
338
- if (cached) return cached;
339
- const url = pathToFileURL(absolute).href;
340
- const loading = (async () => {
341
- try {
342
- const mod = await import(url);
343
- if (typeof mod.login !== "function") {
344
- throw new AuthHarnessError(
345
- `auth harness at ${absolute} does not export a \`login\` function`
346
- );
347
- }
348
- return { login: mod.login };
349
- } catch (err) {
350
- if (err instanceof AuthHarnessError) throw err;
351
- throw new AuthHarnessError(
352
- `failed to load auth harness at ${absolute}: ${err.message}`,
353
- err
354
- );
355
- }
356
- })();
357
- moduleCache.set(absolute, loading);
358
- return loading;
359
- }
360
- function loginPathOf(loginUrl) {
361
- try {
362
- return new URL(loginUrl, "http://placeholder").pathname;
363
- } catch {
364
- return loginUrl;
365
- }
366
- }
367
- async function verifyPostLogin(page, loginUrl) {
368
- const loginPath = loginPathOf(loginUrl);
369
- let currentPath;
370
- try {
371
- currentPath = new URL(page.url()).pathname;
372
- } catch {
373
- currentPath = page.url();
374
- }
375
- if (loginPath && currentPath === loginPath) {
376
- throw new AuthHarnessError(
377
- `auth harness returned but page is still on the login URL (${currentPath}). Check that the harness submits the form and waits for redirect.`
378
- );
379
- }
380
- await page.locator('input[type="password"]').first().waitFor({ state: "detached", timeout: 2e3 }).catch(() => {
381
- });
382
- const passwordInputs = await page.locator('input[type="password"]:visible').count().catch(() => 0);
383
- if (passwordInputs > 0) {
384
- throw new AuthHarnessError(
385
- `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).`
386
- );
387
- }
388
- }
389
-
390
- // src/auth/hook.ts
391
- var AuthConfigMissingError = class extends Error {
392
- constructor(message) {
393
- super(message);
394
- this.name = "AuthConfigMissingError";
395
- }
396
- };
397
- function buildAuthHook(persona, authConfig, cwd) {
398
- if (!authConfig) {
399
- throw new AuthConfigMissingError(
400
- "auth required but .blazediff/config.json has no `auth` block. Run `blazediff-agent auth init`."
401
- );
402
- }
403
- const harnessFile = path.isAbsolute(authConfig.harness) ? authConfig.harness : path.join(cwd, authConfig.harness);
404
- const canonical = canonicalPersona(persona);
405
- const loginUrl = authConfig.loginUrl;
406
- return {
407
- hook: async (page) => {
408
- const mod = await loadAuthHarness(harnessFile);
409
- try {
410
- await mod.login(page, canonical);
411
- } catch (err) {
412
- throw new AuthHarnessError(
413
- `auth harness threw for persona "${canonical}": ${err.message}`,
414
- err
415
- );
416
- }
417
- await verifyPostLogin(page, loginUrl);
418
- }
419
- };
420
- }
421
470
  async function loadConfig(cwd = process.cwd()) {
422
471
  const file = paths(cwd).config;
423
472
  if (!existsSync(file)) return null;
@@ -440,33 +489,40 @@ function resolveBaseUrl(config, override) {
440
489
  }
441
490
 
442
491
  // src/graph/semaphore.ts
443
- var Semaphore = class {
444
- constructor(limit) {
445
- this.limit = limit;
446
- this.current = 0;
447
- this.queue = [];
448
- if (limit < 1)
449
- throw new Error(`semaphore limit must be >= 1 (got ${limit})`);
450
- }
451
- async run(fn) {
452
- if (this.current >= this.limit) {
453
- await new Promise((resolve) => this.queue.push(resolve));
492
+ function createSemaphore(limit) {
493
+ if (limit < 1) throw new Error(`semaphore limit must be >= 1 (got ${limit})`);
494
+ let current = 0;
495
+ const queue = [];
496
+ async function run(fn) {
497
+ if (current >= limit) {
498
+ await new Promise((resolve) => queue.push(resolve));
454
499
  }
455
- this.current++;
500
+ current++;
456
501
  try {
457
502
  return await fn();
458
503
  } finally {
459
- this.current--;
460
- const next = this.queue.shift();
504
+ current--;
505
+ const next = queue.shift();
461
506
  if (next) next();
462
507
  }
463
508
  }
464
- };
509
+ return { run };
510
+ }
465
511
 
466
512
  // src/types.ts
467
513
  var STABILITY_HOOKS_VERSION = 1;
468
514
 
469
515
  // src/manifest.ts
516
+ function serializeHarnesses(harnesses) {
517
+ return JSON.stringify(
518
+ harnesses.map((h) => ({
519
+ name: h.name,
520
+ params: h.params ? Object.fromEntries(
521
+ Object.entries(h.params).sort(([a], [b]) => a.localeCompare(b))
522
+ ) : void 0
523
+ }))
524
+ );
525
+ }
470
526
  async function loadManifest(cwd = process.cwd()) {
471
527
  const file = paths(cwd).manifest;
472
528
  if (!existsSync(file)) return null;
@@ -492,8 +548,9 @@ function hashMaterial(input) {
492
548
  viewport: input.viewport,
493
549
  mask: [...input.mask].sort(),
494
550
  waitFor: input.waitFor,
495
- auth: input.auth,
551
+ harnesses: serializeHarnesses(input.harnesses),
496
552
  fullPage: input.fullPage,
553
+ subName: input.subName ?? null,
497
554
  hooks: STABILITY_HOOKS_VERSION
498
555
  };
499
556
  return `sha256:${createHash("sha256").update(JSON.stringify(material)).digest("hex")}`;
@@ -502,24 +559,27 @@ function makeEntry(input) {
502
559
  const viewport = input.viewport ?? DEFAULT_VIEWPORT;
503
560
  const waitFor = input.waitFor ?? DEFAULT_WAIT_FOR;
504
561
  const mask = input.mask ?? [];
505
- const auth = input.auth ?? null;
562
+ const harnesses = input.harnesses ?? [];
506
563
  const fullPage = input.fullPage ?? DEFAULT_FULL_PAGE;
507
564
  return {
508
565
  id: input.id,
509
566
  url: input.url,
510
567
  viewport,
511
- auth,
568
+ harnesses: harnesses.length > 0 ? harnesses : void 0,
512
569
  waitFor,
513
570
  mask,
514
571
  fullPage,
572
+ parent: input.parent,
573
+ derived: input.derived || void 0,
515
574
  baselinePath: path.posix.join(".blazediff", "baselines", `${input.id}.png`),
516
575
  captureHash: hashMaterial({
517
576
  url: input.url,
518
577
  viewport,
519
578
  mask,
520
579
  waitFor,
521
- auth,
522
- fullPage
580
+ harnesses,
581
+ fullPage,
582
+ subName: input.subName
523
583
  }),
524
584
  createdBy: input.createdBy ?? "agent",
525
585
  createdAt: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)
@@ -532,19 +592,40 @@ function addOrReplaceEntry(manifest, entry) {
532
592
  ].sort((a, b) => a.id.localeCompare(b.id));
533
593
  return { ...manifest, entries };
534
594
  }
595
+ function isDerived(entry) {
596
+ return entry.derived === true || entry.parent != null && entry.id.includes("__");
597
+ }
598
+ function subNameOf(entry) {
599
+ if (!isDerived(entry)) return void 0;
600
+ const idx = entry.id.indexOf("__");
601
+ return idx === -1 ? void 0 : entry.id.slice(idx + 2);
602
+ }
535
603
  function isEntryStale(entry) {
536
604
  const recomputed = hashMaterial({
537
605
  url: entry.url,
538
606
  viewport: entry.viewport,
539
607
  mask: entry.mask,
540
608
  waitFor: entry.waitFor,
541
- auth: entry.auth,
542
- fullPage: entry.fullPage ?? DEFAULT_FULL_PAGE
609
+ harnesses: entry.harnesses ?? [],
610
+ fullPage: entry.fullPage ?? DEFAULT_FULL_PAGE,
611
+ subName: subNameOf(entry)
543
612
  });
544
613
  return recomputed !== entry.captureHash;
545
614
  }
546
615
 
547
616
  // src/captures.ts
617
+ function normalizeHarnessRefs(refs) {
618
+ if (!refs) return [];
619
+ return refs.map((ref) => typeof ref === "string" ? { name: ref } : ref);
620
+ }
621
+ async function resolveHarnesses(refs, cwd) {
622
+ return Promise.all(
623
+ refs.map(async (ref) => ({
624
+ harness: await loadHarness(resolveHarnessFile(ref.name, cwd)),
625
+ params: ref.params ?? {}
626
+ }))
627
+ );
628
+ }
548
629
  function validateRoute(route, i) {
549
630
  if (!route || typeof route !== "object")
550
631
  return `route[${i}] must be an object`;
@@ -583,14 +664,18 @@ async function runCaptures(opts) {
583
664
  let manifest = writeManifest ? await loadOrCreateManifest(cwd, config) : null;
584
665
  let manifestUpdates = 0;
585
666
  const slot = new Array(valid.length);
586
- const semaphore = new Semaphore(opts.concurrency ?? defaultConcurrency());
667
+ const pendingUpdates = new Array(valid.length).fill(
668
+ null
669
+ );
670
+ const semaphore = createSemaphore(opts.concurrency ?? defaultConcurrency());
587
671
  try {
588
672
  await Promise.all(
589
673
  valid.map(
590
674
  (r, i) => semaphore.run(async () => {
591
675
  const mode = r.mode ?? defaultMode;
592
676
  try {
593
- const auth = r.auth != null ? buildAuthHook(r.auth, config?.auth, cwd) : void 0;
677
+ const refs = normalizeHarnessRefs(r.harnesses);
678
+ const harnesses = await resolveHarnesses(refs, cwd);
594
679
  const shot = await captureScreenshot(
595
680
  opts.baseUrl,
596
681
  {
@@ -603,7 +688,7 @@ async function runCaptures(opts) {
603
688
  mode
604
689
  },
605
690
  cwd,
606
- auth
691
+ harnesses
607
692
  );
608
693
  slot[i] = {
609
694
  id: r.id,
@@ -611,22 +696,31 @@ async function runCaptures(opts) {
611
696
  mode,
612
697
  ok: true,
613
698
  outputPath: shot.outputPath,
614
- bytes: shot.bytes
699
+ bytes: shot.bytes,
700
+ subCaptures: shot.subCaptures?.map((s) => s.name)
615
701
  };
616
702
  if (mode === "baseline" && manifest) {
617
- manifest = addOrReplaceEntry(
618
- manifest,
619
- makeEntry({
620
- id: r.id,
621
- url: r.url,
622
- viewport: r.viewport,
623
- mask: r.mask,
624
- waitFor: r.waitFor,
625
- fullPage: r.fullPage,
626
- auth: r.auth ?? null
627
- })
628
- );
629
- manifestUpdates += 1;
703
+ const shared = {
704
+ url: r.url,
705
+ viewport: r.viewport,
706
+ mask: r.mask,
707
+ waitFor: r.waitFor,
708
+ fullPage: r.fullPage,
709
+ harnesses: refs.length > 0 ? refs : void 0
710
+ };
711
+ pendingUpdates[i] = {
712
+ baseId: r.id,
713
+ baseEntry: makeEntry({ id: r.id, ...shared }),
714
+ derivedEntries: (shot.subCaptures ?? []).map(
715
+ (sub) => makeEntry({
716
+ id: `${r.id}__${sub.name}`,
717
+ ...shared,
718
+ parent: r.id,
719
+ derived: true,
720
+ subName: sub.name
721
+ })
722
+ )
723
+ };
630
724
  }
631
725
  } catch (err) {
632
726
  slot[i] = {
@@ -641,7 +735,22 @@ async function runCaptures(opts) {
641
735
  )
642
736
  );
643
737
  for (const r of slot) results.push(r);
644
- if (manifest && manifestUpdates > 0) await saveManifest(manifest, cwd);
738
+ if (manifest) {
739
+ for (const update of pendingUpdates) {
740
+ if (!update) continue;
741
+ manifest = {
742
+ ...manifest,
743
+ entries: manifest.entries.filter((e) => e.parent !== update.baseId)
744
+ };
745
+ manifest = addOrReplaceEntry(manifest, update.baseEntry);
746
+ manifestUpdates += 1;
747
+ for (const derived of update.derivedEntries) {
748
+ manifest = addOrReplaceEntry(manifest, derived);
749
+ manifestUpdates += 1;
750
+ }
751
+ }
752
+ if (manifestUpdates > 0) await saveManifest(manifest, cwd);
753
+ }
645
754
  } finally {
646
755
  await closeBrowser();
647
756
  }
@@ -684,7 +793,7 @@ async function diffEntry(id, baselinePath, actualPath, opts = {}, cwd = process.
684
793
  }
685
794
  const threshold = opts.threshold ?? DEFAULT_THRESHOLD;
686
795
  const antialiasing = opts.antialiasing ?? true;
687
- const result = await compare(baselinePath, actualPath, diffPath, {
796
+ const result = await compare(baselinePath, actualPath, void 0, {
688
797
  threshold,
689
798
  antialiasing,
690
799
  interpret: true
@@ -709,6 +818,13 @@ async function diffEntry(id, baselinePath, actualPath, opts = {}, cwd = process.
709
818
  reason: "layout-diff"
710
819
  };
711
820
  }
821
+ if (diffPath) {
822
+ await compare(baselinePath, actualPath, diffPath, {
823
+ threshold,
824
+ antialiasing,
825
+ compression: 9
826
+ });
827
+ }
712
828
  return {
713
829
  id,
714
830
  baselinePath,
@@ -732,9 +848,9 @@ function extractInternalLinks(base, target, hrefs) {
732
848
  try {
733
849
  const u = new URL(href, target);
734
850
  if (u.origin !== base.origin) continue;
735
- const path20 = u.pathname + u.search;
736
- if (path20.startsWith("/api/")) continue;
737
- out.push(path20);
851
+ const path23 = u.pathname + u.search;
852
+ if (path23.startsWith("/api/")) continue;
853
+ out.push(path23);
738
854
  } catch {
739
855
  }
740
856
  }
@@ -788,15 +904,24 @@ async function crawlRoutes(opts) {
788
904
  }
789
905
  return discovered.slice(0, maxRoutes);
790
906
  }
791
- var DYNAMIC_SEGMENT = /\[[^\]]+\]/;
792
- async function readJson(file) {
793
- if (!existsSync(file)) return null;
907
+ async function fileExists2(p) {
908
+ try {
909
+ await access(p);
910
+ return true;
911
+ } catch {
912
+ return false;
913
+ }
914
+ }
915
+ async function readJsonOrNull(file) {
794
916
  try {
795
917
  return JSON.parse(await readFile(file, "utf8"));
796
918
  } catch {
797
919
  return null;
798
920
  }
799
921
  }
922
+
923
+ // src/discover/next.ts
924
+ var DYNAMIC_SEGMENT = /\[[^\]]+\]/;
800
925
  function isPublicRoute(route) {
801
926
  if (DYNAMIC_SEGMENT.test(route)) return false;
802
927
  if (route === "/api" || route.startsWith("/api/")) return false;
@@ -812,13 +937,13 @@ async function discoverFromNextManifest(cwd = process.cwd()) {
812
937
  seen.add(url);
813
938
  out.push({ url, source: "next-manifest" });
814
939
  };
815
- const routes = await readJson(
940
+ const routes = await readJsonOrNull(
816
941
  path.join(nextDir, "routes-manifest.json")
817
942
  );
818
943
  for (const r of routes?.staticRoutes ?? []) {
819
944
  if (isPublicRoute(r.page)) add(r.page);
820
945
  }
821
- const appPaths = await readJson(
946
+ const appPaths = await readJsonOrNull(
822
947
  path.join(nextDir, "server", "app-paths-manifest.json")
823
948
  );
824
949
  for (const route of Object.keys(appPaths ?? {})) {
@@ -878,17 +1003,73 @@ async function discover(opts) {
878
1003
  }
879
1004
  return Array.from(merged.values()).sort((a, b) => a.url.localeCompare(b.url));
880
1005
  }
1006
+ function envFiles(cwd) {
1007
+ const root = paths(cwd).root;
1008
+ return [
1009
+ path.join(root, ".env.local"),
1010
+ path.join(root, ".env"),
1011
+ path.join(cwd, ".env.local"),
1012
+ path.join(cwd, ".env")
1013
+ ];
1014
+ }
1015
+ function parse(content) {
1016
+ if (typeof util.parseEnv === "function") {
1017
+ return util.parseEnv(content);
1018
+ }
1019
+ const out = {};
1020
+ for (const raw of content.split("\n")) {
1021
+ const line = raw.trim();
1022
+ if (!line || line.startsWith("#")) continue;
1023
+ const eq = line.indexOf("=");
1024
+ if (eq === -1) continue;
1025
+ const key = line.slice(0, eq).trim();
1026
+ let value = line.slice(eq + 1).trim();
1027
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
1028
+ value = value.slice(1, -1);
1029
+ }
1030
+ if (key) out[key] = value;
1031
+ }
1032
+ return out;
1033
+ }
1034
+ function loadEnvFiles(cwd = process.cwd()) {
1035
+ const loaded = [];
1036
+ for (const file of envFiles(cwd)) {
1037
+ if (!existsSync(file)) continue;
1038
+ let parsed;
1039
+ try {
1040
+ parsed = parse(readFileSync(file, "utf8"));
1041
+ } catch {
1042
+ continue;
1043
+ }
1044
+ let applied = false;
1045
+ for (const [key, value] of Object.entries(parsed)) {
1046
+ if (process.env[key] === void 0) {
1047
+ process.env[key] = value;
1048
+ applied = true;
1049
+ }
1050
+ }
1051
+ if (applied) loaded.push(file);
1052
+ }
1053
+ return loaded;
1054
+ }
881
1055
  var ENTRIES = [
882
1056
  "actual/",
883
1057
  "judgments/",
884
1058
  "checkpoints/",
885
- "summary.md",
1059
+ "report.json",
886
1060
  "dev-server.log",
887
1061
  "dev-server.pid",
1062
+ ".env",
1063
+ ".env.local",
888
1064
  "*.tmp"
889
1065
  ];
890
- var STALE_ENTRIES = /* @__PURE__ */ new Set(["diffs/", "pending-judgments/", "report.json"]);
891
- var HEADER = "# blazediff: generated artifacts (committed: config.json, manifest.json, baselines/)\n";
1066
+ var STALE_ENTRIES = /* @__PURE__ */ new Set([
1067
+ "diffs/",
1068
+ "pending-judgments/",
1069
+ "summary.html",
1070
+ "summary.md"
1071
+ ]);
1072
+ var HEADER = "# blazediff: generated artifacts (committed: config.json, manifest.json, baselines/, harnesses/)\n";
892
1073
  async function ensureGitignore(cwd) {
893
1074
  const file = paths(cwd).gitignore;
894
1075
  await mkdir(path.dirname(file), { recursive: true });
@@ -914,6 +1095,15 @@ ${missing.join("\n")}
914
1095
  await writeFile(file, body, "utf8");
915
1096
  }
916
1097
  var DEFAULT_TOP_N = 5;
1098
+ var READ_PAD_X_FACTOR = 2.5;
1099
+ var READ_PAD_X_MIN = 48;
1100
+ var READ_PAD_X_MAX = 130;
1101
+ var READ_PAD_Y_FACTOR = 0.6;
1102
+ var READ_PAD_Y_MIN = 4;
1103
+ var READ_PAD_Y_MAX = 12;
1104
+ var READ_TARGET_WIDTH = 480;
1105
+ var READ_SCALE_MIN = 2;
1106
+ var READ_SCALE_MAX = 6;
917
1107
  var DEFAULT_PADDING = 16;
918
1108
  var DEFAULT_LOCATOR_MAX_WIDTH = 400;
919
1109
  var DEFAULT_GUTTER = 2;
@@ -931,17 +1121,75 @@ function padAndClamp(bbox, padding, imgWidth, imgHeight) {
931
1121
  height: Math.max(1, bottom - top)
932
1122
  };
933
1123
  }
1124
+ var clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
1125
+ async function prepareRegionReads(opts) {
1126
+ const topN = opts.topN ?? DEFAULT_TOP_N;
1127
+ const meta = await sharp(opts.actualPath).metadata();
1128
+ const imgWidth = meta.width ?? 0;
1129
+ const imgHeight = meta.height ?? 0;
1130
+ if (!imgWidth || !imgHeight) {
1131
+ throw new Error(`unable to read image dimensions: ${opts.actualPath}`);
1132
+ }
1133
+ const ranked = [...opts.regions].sort((a, b) => b.pixelCount - a.pixelCount).slice(0, topN);
1134
+ return Promise.all(
1135
+ ranked.map(async (region, i) => {
1136
+ const padX = clamp(
1137
+ Math.round(region.bbox.width * READ_PAD_X_FACTOR),
1138
+ READ_PAD_X_MIN,
1139
+ READ_PAD_X_MAX
1140
+ );
1141
+ const padY = clamp(
1142
+ Math.round(region.bbox.height * READ_PAD_Y_FACTOR),
1143
+ READ_PAD_Y_MIN,
1144
+ READ_PAD_Y_MAX
1145
+ );
1146
+ const left = Math.max(0, Math.floor(region.bbox.x - padX));
1147
+ const top = Math.max(0, Math.floor(region.bbox.y - padY));
1148
+ const right = Math.min(
1149
+ imgWidth,
1150
+ Math.ceil(region.bbox.x + region.bbox.width + padX)
1151
+ );
1152
+ const bottom = Math.min(
1153
+ imgHeight,
1154
+ Math.ceil(region.bbox.y + region.bbox.height + padY)
1155
+ );
1156
+ const extract = {
1157
+ left,
1158
+ top,
1159
+ width: Math.max(1, right - left),
1160
+ height: Math.max(1, bottom - top)
1161
+ };
1162
+ const scale = clamp(
1163
+ Math.round(READ_TARGET_WIDTH / extract.width),
1164
+ READ_SCALE_MIN,
1165
+ READ_SCALE_MAX
1166
+ );
1167
+ const render = async (src, suffix) => {
1168
+ const name = `read-${i}.${suffix}.png`;
1169
+ await sharp(src).extract(extract).resize(extract.width * scale, extract.height * scale, {
1170
+ kernel: "lanczos3"
1171
+ }).png().toFile(path.join(opts.outputDir, name));
1172
+ return path.join(opts.outputDir, name);
1173
+ };
1174
+ const [beforePath, afterPath] = await Promise.all([
1175
+ render(opts.baselinePath, "before"),
1176
+ render(opts.actualPath, "after")
1177
+ ]);
1178
+ return { changeType: region.changeType, beforePath, afterPath };
1179
+ })
1180
+ );
1181
+ }
934
1182
  async function prepareTiles(opts) {
935
1183
  const topN = opts.topN ?? DEFAULT_TOP_N;
936
1184
  const padding = opts.padding ?? DEFAULT_PADDING;
937
1185
  const locatorMaxWidth = opts.locatorMaxWidth ?? DEFAULT_LOCATOR_MAX_WIDTH;
938
1186
  const gutter = opts.gutter ?? DEFAULT_GUTTER;
939
1187
  const rowGutter = opts.rowGutter ?? DEFAULT_ROW_GUTTER;
940
- const diffMeta = await sharp(opts.diffPath).metadata();
941
- const imgWidth = diffMeta.width ?? 0;
942
- const imgHeight = diffMeta.height ?? 0;
1188
+ const meta = await sharp(opts.actualPath).metadata();
1189
+ const imgWidth = meta.width ?? 0;
1190
+ const imgHeight = meta.height ?? 0;
943
1191
  if (!imgWidth || !imgHeight) {
944
- throw new Error(`unable to read diff image dimensions: ${opts.diffPath}`);
1192
+ throw new Error(`unable to read image dimensions: ${opts.actualPath}`);
945
1193
  }
946
1194
  const ranked = [...opts.regions].sort((a, b) => b.pixelCount - a.pixelCount).slice(0, topN);
947
1195
  const regionData = await Promise.all(
@@ -991,19 +1239,22 @@ async function prepareTiles(opts) {
991
1239
  }
992
1240
  }).composite(composites).png().toFile(path.join(opts.outputDir, tilesName));
993
1241
  }
994
- const scale = locatorMaxWidth / Math.max(imgWidth, imgHeight);
995
- const locW = Math.max(1, Math.round(imgWidth * scale));
996
- const locH = Math.max(1, Math.round(imgHeight * scale));
997
- const rects = opts.regions.map((r) => {
998
- const x = Math.round(r.bbox.x * scale);
999
- const y = Math.round(r.bbox.y * scale);
1000
- const w = Math.max(1, Math.round(r.bbox.width * scale));
1001
- const h = Math.max(1, Math.round(r.bbox.height * scale));
1002
- return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="none" stroke="red" stroke-width="2" />`;
1003
- }).join("");
1004
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${locW}" height="${locH}">${rects}</svg>`;
1005
- const locatorName = "locator.png";
1006
- await sharp(opts.diffPath).resize(locW, locH, { fit: "fill" }).composite([{ input: Buffer.from(svg), left: 0, top: 0 }]).png().toFile(path.join(opts.outputDir, locatorName));
1242
+ let locatorName;
1243
+ if (opts.diffPath) {
1244
+ const scale = locatorMaxWidth / Math.max(imgWidth, imgHeight);
1245
+ const locW = Math.max(1, Math.round(imgWidth * scale));
1246
+ const locH = Math.max(1, Math.round(imgHeight * scale));
1247
+ const rects = opts.regions.map((r) => {
1248
+ const x = Math.round(r.bbox.x * scale);
1249
+ const y = Math.round(r.bbox.y * scale);
1250
+ const w = Math.max(1, Math.round(r.bbox.width * scale));
1251
+ const h = Math.max(1, Math.round(r.bbox.height * scale));
1252
+ return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="none" stroke="red" stroke-width="2" />`;
1253
+ }).join("");
1254
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${locW}" height="${locH}">${rects}</svg>`;
1255
+ locatorName = "locator.png";
1256
+ await sharp(opts.diffPath).resize(locW, locH, { fit: "fill" }).composite([{ input: Buffer.from(svg), left: 0, top: 0 }]).png().toFile(path.join(opts.outputDir, locatorName));
1257
+ }
1007
1258
  return {
1008
1259
  locatorPath: locatorName,
1009
1260
  tilesPath: tilesName,
@@ -1014,9 +1265,9 @@ async function prepareTiles(opts) {
1014
1265
  };
1015
1266
  }
1016
1267
 
1017
- // src/judge/host-harness.ts
1268
+ // src/judge/coding-agent-host.ts
1018
1269
  async function tryPrepareTiles(input, entryDir) {
1019
- if (!input.regions || input.regions.length === 0 || !input.diffPath) {
1270
+ if (!input.regions || input.regions.length === 0) {
1020
1271
  return null;
1021
1272
  }
1022
1273
  try {
@@ -1035,9 +1286,10 @@ async function tryPrepareTiles(input, entryDir) {
1035
1286
  return null;
1036
1287
  }
1037
1288
  }
1038
- var hostHarnessJudge = {
1289
+ var codingAgentHostJudge = {
1039
1290
  name: "host",
1040
1291
  async judge(input, cwd) {
1292
+ input.onJudgingStart?.();
1041
1293
  const p = paths(cwd);
1042
1294
  const entryDir = path.join(p.judgments, input.entry.id);
1043
1295
  await mkdir(entryDir, { recursive: true });
@@ -1045,366 +1297,598 @@ var hostHarnessJudge = {
1045
1297
  return { kind: "deferred", requestPath: entryDir };
1046
1298
  }
1047
1299
  };
1300
+ var dim = pc.dim;
1301
+ var bold = pc.bold;
1048
1302
 
1049
- // src/judge/none.ts
1050
- var noneJudge = {
1051
- name: "none",
1052
- async judge(input) {
1053
- return { kind: "judged", verdict: input.heuristicVerdict };
1054
- }
1055
- };
1056
- var ROOT_NS_SENTINEL = "_root";
1057
- function nsDir(ns) {
1058
- return ns === "" ? ROOT_NS_SENTINEL : ns;
1059
- }
1060
- function encode(buf) {
1061
- return Buffer.from(buf).toString("base64");
1062
- }
1063
- function decode(s) {
1064
- return Buffer.from(s, "base64");
1303
+ // src/judge/transformers.ts
1304
+ var toMb = (bytes) => (bytes / 1048576).toFixed(1);
1305
+ function createLoadProgress(label) {
1306
+ const interactive = Boolean(process.stderr.isTTY);
1307
+ const bytes = /* @__PURE__ */ new Map();
1308
+ let announced = false;
1309
+ let lastPct = -1;
1310
+ let lastBucket = -1;
1311
+ const totals = () => {
1312
+ let loaded = 0;
1313
+ let total = 0;
1314
+ for (const b of bytes.values()) {
1315
+ loaded += b.loaded;
1316
+ total += b.total;
1317
+ }
1318
+ const pct = total > 0 ? Math.min(100, Math.floor(loaded / total * 100)) : 0;
1319
+ return { loaded, total, pct };
1320
+ };
1321
+ return {
1322
+ onProgress(event) {
1323
+ if (!announced) {
1324
+ process.stderr.write(
1325
+ `${dim("[blazediff]")} loading ${bold(label)} model ${dim("(first run downloads weights)\u2026")}
1326
+ `
1327
+ );
1328
+ announced = true;
1329
+ }
1330
+ if (event.status !== "progress" || !event.file || typeof event.total !== "number")
1331
+ return;
1332
+ bytes.set(event.file, { loaded: event.loaded ?? 0, total: event.total });
1333
+ const { loaded, total, pct } = totals();
1334
+ if (pct === lastPct) return;
1335
+ lastPct = pct;
1336
+ const line = ` ${label}: ${pct}% ${dim(`(${toMb(loaded)}/${toMb(total)} MB)`)}`;
1337
+ if (interactive) {
1338
+ process.stderr.write(`\r${line}\x1B[K`);
1339
+ return;
1340
+ }
1341
+ const bucket = Math.floor(pct / 25);
1342
+ if (bucket > lastBucket) {
1343
+ lastBucket = bucket;
1344
+ process.stderr.write(`${line}
1345
+ `);
1346
+ }
1347
+ },
1348
+ done() {
1349
+ if (!announced) return;
1350
+ if (interactive) {
1351
+ const { total } = totals();
1352
+ const size = total > 0 ? dim(` (${toMb(total)} MB)`) : "";
1353
+ process.stderr.write(
1354
+ `\r ${label}: ${pc.green("ready")}${size}\x1B[K
1355
+ `
1356
+ );
1357
+ } else if (lastPct < 100) {
1358
+ process.stderr.write(` ${label}: ${pc.green("ready")}
1359
+ `);
1360
+ }
1361
+ }
1362
+ };
1065
1363
  }
1066
- async function readJson2(file) {
1364
+ async function loadTransformers() {
1067
1365
  try {
1068
- const raw = await readFile(file, "utf8");
1069
- return JSON.parse(raw);
1366
+ return await import('@huggingface/transformers');
1070
1367
  } catch (err) {
1071
- if (err.code === "ENOENT") return void 0;
1072
- throw err;
1368
+ throw new Error(
1369
+ 'stack=local requires the optional peer dependency "@huggingface/transformers". Install it with `npm i @huggingface/transformers` (or pnpm/bun add).',
1370
+ { cause: err instanceof Error ? err : void 0 }
1371
+ );
1073
1372
  }
1074
1373
  }
1075
- async function writeJsonAtomic(file, value) {
1076
- const tmp = `${file}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
1077
- await writeFile(tmp, JSON.stringify(value), "utf8");
1078
- await rename(tmp, file);
1374
+
1375
+ // src/judge/classifier.ts
1376
+ var MODEL_ID = "onnx-community/Qwen3.5-0.8B-ONNX";
1377
+ var MAX_NEW_TOKENS = 64;
1378
+ async function defaultFactory() {
1379
+ const mod = await loadTransformers();
1380
+ const progress = createLoadProgress("classifier");
1381
+ const progress_callback = progress.onProgress;
1382
+ const [tokenizer, model] = await Promise.all([
1383
+ mod.AutoTokenizer.from_pretrained(MODEL_ID, { progress_callback }),
1384
+ mod.Qwen3_5ForConditionalGeneration.from_pretrained(MODEL_ID, {
1385
+ dtype: {
1386
+ embed_tokens: "fp32",
1387
+ vision_encoder: "q8",
1388
+ decoder_model_merged: "q4"
1389
+ },
1390
+ device: "cpu",
1391
+ progress_callback
1392
+ })
1393
+ ]);
1394
+ progress.done();
1395
+ return {
1396
+ async complete(prompt) {
1397
+ const inputs = tokenizer.apply_chat_template(
1398
+ [{ role: "user", content: prompt }],
1399
+ {
1400
+ add_generation_prompt: true,
1401
+ return_dict: true,
1402
+ enable_thinking: false
1403
+ }
1404
+ );
1405
+ const output = await model.generate({
1406
+ ...inputs,
1407
+ do_sample: false,
1408
+ max_new_tokens: MAX_NEW_TOKENS
1409
+ });
1410
+ const promptLen = inputs.input_ids.dims.at(-1);
1411
+ const generated = output.slice(null, [promptLen, null]);
1412
+ const decoded = tokenizer.batch_decode(generated, {
1413
+ skip_special_tokens: true
1414
+ });
1415
+ const raw = Array.isArray(decoded) ? String(decoded[0] ?? "") : String(decoded);
1416
+ return raw.trim();
1417
+ }
1418
+ };
1079
1419
  }
1080
- var FsCheckpointSaver = class extends BaseCheckpointSaver {
1081
- constructor(root, serde) {
1082
- super(serde);
1083
- this.locks = /* @__PURE__ */ new Map();
1084
- this.root = root;
1085
- }
1086
- threadDir(thread) {
1087
- return path.join(this.root, thread);
1088
- }
1089
- nsPath(thread, ns) {
1090
- return path.join(this.threadDir(thread), nsDir(ns));
1091
- }
1092
- ckptFile(thread, ns, id) {
1093
- return path.join(this.nsPath(thread, ns), `${id}.ckpt.json`);
1094
- }
1095
- writesFile(thread, ns, id) {
1096
- return path.join(this.nsPath(thread, ns), `${id}.writes.json`);
1097
- }
1098
- async withLock(key, fn) {
1099
- const prev = this.locks.get(key) ?? Promise.resolve();
1100
- const next = prev.then(fn, fn);
1101
- this.locks.set(key, next);
1102
- try {
1103
- return await next;
1104
- } finally {
1105
- if (this.locks.get(key) === next) this.locks.delete(key);
1420
+ function createClassifierRunnerHolder(factory = defaultFactory) {
1421
+ let runnerPromise;
1422
+ return {
1423
+ get() {
1424
+ if (!runnerPromise) runnerPromise = factory();
1425
+ return runnerPromise;
1106
1426
  }
1107
- }
1108
- async listCheckpointIds(thread, ns) {
1109
- try {
1110
- const names = await readdir(this.nsPath(thread, ns));
1111
- const suffix = ".ckpt.json";
1112
- return names.filter((n) => n.endsWith(suffix)).map((n) => n.slice(0, -suffix.length));
1113
- } catch (err) {
1114
- if (err.code === "ENOENT") return [];
1115
- throw err;
1427
+ };
1428
+ }
1429
+
1430
+ // src/judge/region-diff.ts
1431
+ var FILLER = /* @__PURE__ */ new Set([
1432
+ "the",
1433
+ "a",
1434
+ "an",
1435
+ "is",
1436
+ "are",
1437
+ "was",
1438
+ "were",
1439
+ "be",
1440
+ "this",
1441
+ "that",
1442
+ "these",
1443
+ "those",
1444
+ "it",
1445
+ "its",
1446
+ "there",
1447
+ "here",
1448
+ "and",
1449
+ "or",
1450
+ "but",
1451
+ "of",
1452
+ "in",
1453
+ "on",
1454
+ "at",
1455
+ "to",
1456
+ "with",
1457
+ "within",
1458
+ "against",
1459
+ "around",
1460
+ "surrounding",
1461
+ "into",
1462
+ "from",
1463
+ "by",
1464
+ "for",
1465
+ "as",
1466
+ "no",
1467
+ "not",
1468
+ "other",
1469
+ "some",
1470
+ "also",
1471
+ "another",
1472
+ "word",
1473
+ "words",
1474
+ "text",
1475
+ "letter",
1476
+ "letters",
1477
+ "character",
1478
+ "characters",
1479
+ "number",
1480
+ "numbers",
1481
+ "digit",
1482
+ "digits",
1483
+ "phrase",
1484
+ "label",
1485
+ "title",
1486
+ "written",
1487
+ "writes",
1488
+ "reads",
1489
+ "read",
1490
+ "says",
1491
+ "displayed",
1492
+ "displays",
1493
+ "display",
1494
+ "shows",
1495
+ "show",
1496
+ "showing",
1497
+ "shown",
1498
+ "appears",
1499
+ "appear",
1500
+ "reading",
1501
+ "prominently",
1502
+ "visible",
1503
+ "positioned",
1504
+ "located",
1505
+ "white",
1506
+ "black",
1507
+ "blue",
1508
+ "red",
1509
+ "green",
1510
+ "purple",
1511
+ "gray",
1512
+ "grey",
1513
+ "background",
1514
+ "foreground",
1515
+ "color",
1516
+ "colors",
1517
+ "colored",
1518
+ "colour",
1519
+ "font",
1520
+ "style",
1521
+ "styled",
1522
+ "bold",
1523
+ "italic",
1524
+ "blurred",
1525
+ "slightly",
1526
+ "image",
1527
+ "photo",
1528
+ "picture",
1529
+ "frame",
1530
+ "scene",
1531
+ "object",
1532
+ "objects",
1533
+ "element",
1534
+ "elements",
1535
+ "ui",
1536
+ "screen",
1537
+ "page",
1538
+ "logo",
1539
+ "icon",
1540
+ "button",
1541
+ "large",
1542
+ "small",
1543
+ "big",
1544
+ "left",
1545
+ "right",
1546
+ "top",
1547
+ "bottom",
1548
+ "center",
1549
+ "corner",
1550
+ "side",
1551
+ "above",
1552
+ "below",
1553
+ "ink",
1554
+ "company",
1555
+ "name",
1556
+ "brand",
1557
+ "create",
1558
+ "creating",
1559
+ "artistic",
1560
+ "effect",
1561
+ "design",
1562
+ "additional"
1563
+ ]);
1564
+ function tokenize(text) {
1565
+ return text.toLowerCase().match(/[a-z0-9]+/g) ?? [];
1566
+ }
1567
+ function extractQuoted(read) {
1568
+ const spans = [...read.matchAll(/["“”']([^"“”']+)["“”']/g)].map(
1569
+ (m) => m[1].trim()
1570
+ );
1571
+ if (spans.length === 0) return null;
1572
+ return spans.reduce((a, b) => b.length > a.length ? b : a).trim() || null;
1573
+ }
1574
+ function diffTokens(base, actual) {
1575
+ const n = base.length;
1576
+ const m = actual.length;
1577
+ const dp = Array.from(
1578
+ { length: n + 1 },
1579
+ () => new Array(m + 1).fill(0)
1580
+ );
1581
+ for (let i2 = n - 1; i2 >= 0; i2--) {
1582
+ for (let j2 = m - 1; j2 >= 0; j2--) {
1583
+ dp[i2][j2] = base[i2] === actual[j2] ? dp[i2 + 1][j2 + 1] + 1 : Math.max(dp[i2 + 1][j2], dp[i2][j2 + 1]);
1116
1584
  }
1117
1585
  }
1118
- async listNamespaces(thread) {
1119
- try {
1120
- return await readdir(this.threadDir(thread));
1121
- } catch (err) {
1122
- if (err.code === "ENOENT") return [];
1123
- throw err;
1586
+ const inserted = [];
1587
+ const removed = [];
1588
+ let i = 0;
1589
+ let j = 0;
1590
+ while (i < n && j < m) {
1591
+ if (base[i] === actual[j]) {
1592
+ i++;
1593
+ j++;
1594
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
1595
+ removed.push(base[i++]);
1596
+ } else {
1597
+ inserted.push(actual[j++]);
1124
1598
  }
1125
1599
  }
1126
- async listThreads() {
1127
- try {
1128
- return await readdir(this.root);
1129
- } catch (err) {
1130
- if (err.code === "ENOENT") return [];
1131
- throw err;
1600
+ while (i < n) removed.push(base[i++]);
1601
+ while (j < m) inserted.push(actual[j++]);
1602
+ return { inserted, removed };
1603
+ }
1604
+ var keepToken = (t) => /\d/.test(t) || !FILLER.has(t);
1605
+ var quote = (tokens) => `"${tokens.join(" ")}"`;
1606
+ function describeRegionChange(changeType, baseRead, actualRead) {
1607
+ const baseQuoted = extractQuoted(baseRead);
1608
+ const actualQuoted = extractQuoted(actualRead);
1609
+ const haveCores = baseQuoted !== null && actualQuoted !== null;
1610
+ const base = tokenize(baseQuoted ?? baseRead);
1611
+ const actual = tokenize(actualQuoted ?? actualRead);
1612
+ const { inserted, removed } = diffTokens(base, actual);
1613
+ const ins = haveCores ? inserted : inserted.filter(keepToken);
1614
+ const rem = haveCores ? removed : removed.filter(keepToken);
1615
+ const updated = actualQuoted && actualQuoted.length <= 60 ? ` (region now reads "${actualQuoted}")` : "";
1616
+ if (ins.length > 0 && rem.length === 0)
1617
+ return `added ${quote(ins)}${updated}`;
1618
+ if (rem.length > 0 && ins.length === 0)
1619
+ return `removed ${quote(rem)}${updated}`;
1620
+ if (ins.length > 0 && rem.length > 0)
1621
+ return `replaced ${quote(rem)} with ${quote(ins)}${updated}`;
1622
+ const kind = changeType.replace(/-/g, " ");
1623
+ return `${kind} with no readable text change${updated}`;
1624
+ }
1625
+
1626
+ // src/judge/vision.ts
1627
+ var MODEL_ID2 = "Xenova/moondream2";
1628
+ var PATCH_SIZE = 14;
1629
+ var MAX_NEW_TOKENS2 = 64;
1630
+ var ANSWER_MARKER = "Answer:";
1631
+ async function defaultFactory2() {
1632
+ const mod = await loadTransformers();
1633
+ const progress = createLoadProgress("vision");
1634
+ const progress_callback = progress.onProgress;
1635
+ const [tokenizer, processor, model] = await Promise.all([
1636
+ mod.AutoTokenizer.from_pretrained(MODEL_ID2, { progress_callback }),
1637
+ mod.AutoProcessor.from_pretrained(MODEL_ID2, { progress_callback }),
1638
+ mod.Moondream1ForConditionalGeneration.from_pretrained(MODEL_ID2, {
1639
+ dtype: {
1640
+ embed_tokens: "fp32",
1641
+ vision_encoder: "q8",
1642
+ decoder_model_merged: "q4"
1643
+ },
1644
+ device: "cpu",
1645
+ progress_callback
1646
+ })
1647
+ ]);
1648
+ progress.done();
1649
+ return {
1650
+ async describe(imagePath, question) {
1651
+ const image = await mod.RawImage.read(imagePath);
1652
+ const vision = await processor(image);
1653
+ const [, , height, width] = vision.pixel_values.dims;
1654
+ const numImageTokens = Math.floor(height / PATCH_SIZE) * Math.floor(width / PATCH_SIZE);
1655
+ const prompt = `${"<image>".repeat(numImageTokens)}
1656
+
1657
+ Question: ${question}
1658
+
1659
+ ${ANSWER_MARKER}`;
1660
+ const textInputs = tokenizer(prompt);
1661
+ const output = await model.generate({
1662
+ ...textInputs,
1663
+ ...vision,
1664
+ do_sample: false,
1665
+ max_new_tokens: MAX_NEW_TOKENS2,
1666
+ // Moondream loops the same sentence on composite tiles without these.
1667
+ repetition_penalty: 1.3,
1668
+ no_repeat_ngram_size: 3
1669
+ });
1670
+ const decoded = tokenizer.batch_decode(output, {
1671
+ skip_special_tokens: true
1672
+ });
1673
+ const raw = Array.isArray(decoded) ? String(decoded[0] ?? "") : String(decoded);
1674
+ const idx = raw.lastIndexOf(ANSWER_MARKER);
1675
+ return (idx >= 0 ? raw.slice(idx + ANSWER_MARKER.length) : raw).trim();
1132
1676
  }
1133
- }
1134
- decodeNs(nsDirName) {
1135
- return nsDirName === ROOT_NS_SENTINEL ? "" : nsDirName;
1136
- }
1137
- async loadPendingWrites(thread, ns, ckptId) {
1138
- const data = await readJson2(
1139
- this.writesFile(thread, ns, ckptId)
1140
- );
1141
- if (!data) return [];
1142
- const out = [];
1143
- for (const [taskId, channel, serialized] of Object.values(data)) {
1144
- const value = await this.serde.loadsTyped("json", decode(serialized));
1145
- out.push([taskId, channel, value]);
1677
+ };
1678
+ }
1679
+ function createVisionRunnerHolder(factory = defaultFactory2) {
1680
+ let runnerPromise;
1681
+ return {
1682
+ get() {
1683
+ if (!runnerPromise) runnerPromise = factory();
1684
+ return runnerPromise;
1146
1685
  }
1147
- return out;
1148
- }
1149
- async migratePendingSends(checkpoint, thread, ns, parentCheckpointId) {
1150
- const data = await readJson2(
1151
- this.writesFile(thread, ns, parentCheckpointId)
1152
- );
1153
- const pendingSends = data ? await Promise.all(
1154
- Object.values(data).filter(([, channel]) => channel === TASKS).map(
1155
- ([, , serialized]) => this.serde.loadsTyped("json", decode(serialized))
1156
- )
1157
- ) : [];
1158
- const m = checkpoint;
1159
- m.channel_values ?? (m.channel_values = {});
1160
- m.channel_values[TASKS] = pendingSends;
1161
- m.channel_versions ?? (m.channel_versions = {});
1162
- const versions = Object.values(m.channel_versions);
1163
- m.channel_versions[TASKS] = versions.length > 0 ? maxChannelVersion(...versions) : this.getNextVersion(void 0);
1164
- }
1165
- async readTuple(thread, ns, ckptId, config) {
1166
- const data = await readJson2(this.ckptFile(thread, ns, ckptId));
1167
- if (!data) return void 0;
1168
- const checkpoint = await this.serde.loadsTyped(
1169
- "json",
1170
- decode(data.checkpoint)
1171
- );
1172
- const metadata = await this.serde.loadsTyped(
1173
- "json",
1174
- decode(data.metadata)
1175
- );
1176
- if (checkpoint.v < 4 && data.parentCheckpointId !== void 0) {
1177
- await this.migratePendingSends(
1178
- checkpoint,
1179
- thread,
1180
- ns,
1181
- data.parentCheckpointId
1686
+ };
1687
+ }
1688
+
1689
+ // src/judge/local.ts
1690
+ var READ_PROMPT = [
1691
+ "Read the text in this image. Reply with only the exact words and numbers you",
1692
+ 'see, wrapped in double quotes. If there is no text, reply "".'
1693
+ ].join(" ");
1694
+ var DESCRIBE_PROMPT = [
1695
+ "In one sentence, describe the main UI elements and any visible text in this",
1696
+ "screenshot. Do not judge whether it is good or bad."
1697
+ ].join(" ");
1698
+ var LABELS = [
1699
+ "regression-likely",
1700
+ "intentional-likely",
1701
+ "noise-likely",
1702
+ "ambiguous"
1703
+ ];
1704
+ var ACTION_BY_LABEL = {
1705
+ "regression-likely": "investigate",
1706
+ "intentional-likely": "rewrite-if-intended",
1707
+ "noise-likely": "ignore-or-rewrite",
1708
+ ambiguous: "investigate"
1709
+ };
1710
+ var VERDICT_MARKER = "VERDICT:";
1711
+ function summarizeInterpret(input) {
1712
+ const lines = [];
1713
+ lines.push(
1714
+ `diff area: ${(input.diffPercentage ?? 0).toFixed(3)}% of the page`
1715
+ );
1716
+ lines.push(`severity: ${input.severity ?? "unknown"}`);
1717
+ const regions = input.regions ?? [];
1718
+ lines.push(`changed regions: ${regions.length}`);
1719
+ if (regions.length > 0) {
1720
+ const counts = /* @__PURE__ */ new Map();
1721
+ for (const r of regions)
1722
+ counts.set(r.changeType, (counts.get(r.changeType) ?? 0) + 1);
1723
+ const byType = [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([type, n]) => `${type} x${n}`).join(", ");
1724
+ lines.push(`change types: ${byType}`);
1725
+ }
1726
+ return lines.join("\n");
1727
+ }
1728
+ function buildClassifyPrompt(summary, description) {
1729
+ return [
1730
+ "You classify a visual regression-test diff into exactly one label.",
1731
+ "",
1732
+ "Deterministic analysis of the changed pixels:",
1733
+ summary,
1734
+ "",
1735
+ "The change in the affected region, read from the screenshots, is:",
1736
+ `"${description}"`,
1737
+ "",
1738
+ "Labels:",
1739
+ "- regression-likely: something looks broken, missing, clipped, or misaligned.",
1740
+ "- intentional-likely: a deliberate content or style update.",
1741
+ "- noise-likely: negligible anti-aliasing / sub-pixel rendering differences.",
1742
+ "- ambiguous: cannot tell from the evidence.",
1743
+ "",
1744
+ "First explain your reasoning in one short sentence. Then, on the final",
1745
+ `line, write "${VERDICT_MARKER} <label>" using exactly one label above.`
1746
+ ].join("\n");
1747
+ }
1748
+ function parseLabel(text) {
1749
+ const t = text.toLowerCase();
1750
+ const marked = t.match(/verdict:\s*([a-z-]+)/);
1751
+ if (marked) {
1752
+ const hit = LABELS.find((label) => marked[1].startsWith(label));
1753
+ if (hit) return hit;
1754
+ }
1755
+ let latest2 = null;
1756
+ for (const label of LABELS) {
1757
+ const idx = t.lastIndexOf(label);
1758
+ if (idx >= 0 && (!latest2 || idx > latest2.idx)) latest2 = { label, idx };
1759
+ }
1760
+ return latest2?.label ?? null;
1761
+ }
1762
+ function firstSentence(text) {
1763
+ const trimmed = text.trim().replace(/\s+/g, " ");
1764
+ const m = trimmed.match(/^.*?[.!?](\s|$)/);
1765
+ return (m ? m[0] : trimmed).trim();
1766
+ }
1767
+ function reasonOf(answer, label) {
1768
+ const beforeVerdict = answer.split(/verdict:/i)[0];
1769
+ const withoutLabel = beforeVerdict.replace(new RegExp(label, "gi"), "").trim();
1770
+ return firstSentence(withoutLabel) || firstSentence(answer);
1771
+ }
1772
+ function toError(err) {
1773
+ return err instanceof Error ? err : new Error(String(err));
1774
+ }
1775
+ function classifyFailure(err) {
1776
+ const m = err.message.toLowerCase();
1777
+ if (m.includes("model") || m.includes("weights") || m.includes("download") || m.includes("transformers"))
1778
+ return "model-load";
1779
+ if (m.includes("enoent") || m.includes("read") || m.includes("sharp") || m.includes("crop"))
1780
+ return "read";
1781
+ return "internal";
1782
+ }
1783
+ function createLocalJudge(deps = {}) {
1784
+ const vision = deps.vision ?? createVisionRunnerHolder();
1785
+ const classifier = deps.classifier ?? createClassifierRunnerHolder();
1786
+ const visionSemaphore = createSemaphore(1);
1787
+ const classifierSemaphore = createSemaphore(1);
1788
+ async function describeChange(input, entryDir) {
1789
+ if (!input.regions || input.regions.length === 0) return null;
1790
+ try {
1791
+ const crops = await prepareRegionReads({
1792
+ regions: input.regions,
1793
+ baselinePath: input.baselinePath,
1794
+ actualPath: input.actualPath,
1795
+ outputDir: entryDir
1796
+ });
1797
+ if (crops.length === 0) return null;
1798
+ const v = await vision.get();
1799
+ const phrases = await Promise.all(
1800
+ crops.map(async (crop) => {
1801
+ const [before, after] = await Promise.all([
1802
+ v.describe(crop.beforePath, READ_PROMPT),
1803
+ v.describe(crop.afterPath, READ_PROMPT)
1804
+ ]);
1805
+ return describeRegionChange(crop.changeType, before, after);
1806
+ })
1182
1807
  );
1808
+ return phrases.length === 1 ? phrases[0] : phrases.map((p, i) => `region ${i + 1}: ${p}`).join("; ");
1809
+ } catch {
1810
+ return null;
1183
1811
  }
1184
- const pendingWrites = await this.loadPendingWrites(thread, ns, ckptId);
1185
- const tuple = {
1186
- config,
1187
- checkpoint,
1188
- metadata,
1189
- pendingWrites
1190
- };
1191
- if (data.parentCheckpointId !== void 0) {
1192
- tuple.parentConfig = {
1193
- configurable: {
1194
- thread_id: thread,
1195
- checkpoint_ns: ns,
1196
- checkpoint_id: data.parentCheckpointId
1197
- }
1198
- };
1199
- }
1200
- return tuple;
1201
1812
  }
1202
- async getTuple(config) {
1203
- const thread = config.configurable?.thread_id;
1204
- if (!thread) return void 0;
1205
- const ns = config.configurable?.checkpoint_ns ?? "";
1206
- const explicitId = getCheckpointId(config);
1207
- if (explicitId) {
1208
- return this.readTuple(thread, ns, explicitId, config);
1209
- }
1210
- const ids = (await this.listCheckpointIds(thread, ns)).sort(
1211
- (a, b) => b.localeCompare(a)
1212
- );
1213
- if (ids.length === 0) return void 0;
1214
- const ckptId = ids[0];
1215
- return this.readTuple(thread, ns, ckptId, {
1216
- configurable: {
1217
- thread_id: thread,
1218
- checkpoint_ns: ns,
1219
- checkpoint_id: ckptId
1220
- }
1221
- });
1813
+ async function describeScreenshot(input) {
1814
+ const v = await vision.get();
1815
+ return (await v.describe(input.actualPath, DESCRIBE_PROMPT)).trim();
1222
1816
  }
1223
- async *list(config, options) {
1224
- const filter = options?.filter;
1225
- const before = options?.before;
1226
- let limit = options?.limit;
1227
- const configThread = config.configurable?.thread_id;
1228
- const configNs = config.configurable?.checkpoint_ns;
1229
- const configCkptId = config.configurable?.checkpoint_id;
1230
- const threads = configThread ? [configThread] : await this.listThreads();
1231
- for (const thread of threads) {
1232
- const nsNames = await this.listNamespaces(thread);
1233
- for (const nsName of nsNames) {
1234
- const ns = this.decodeNs(nsName);
1235
- if (configNs !== void 0 && ns !== configNs) continue;
1236
- const ids = (await this.listCheckpointIds(thread, ns)).sort(
1237
- (a, b) => b.localeCompare(a)
1238
- );
1239
- for (const ckptId of ids) {
1240
- if (configCkptId && ckptId !== configCkptId) continue;
1241
- if (before?.configurable?.checkpoint_id && ckptId >= before.configurable.checkpoint_id)
1242
- continue;
1243
- const tuple = await this.readTuple(thread, ns, ckptId, {
1244
- configurable: {
1245
- thread_id: thread,
1246
- checkpoint_ns: ns,
1247
- checkpoint_id: ckptId
1248
- }
1249
- });
1250
- if (!tuple) continue;
1251
- if (filter) {
1252
- const md = tuple.metadata;
1253
- const matches = Object.entries(filter).every(
1254
- ([k, v]) => md?.[k] === v
1255
- );
1256
- if (!matches) continue;
1257
- }
1258
- if (limit !== void 0) {
1259
- if (limit <= 0) return;
1260
- limit -= 1;
1261
- }
1262
- yield tuple;
1817
+ return {
1818
+ name: "local",
1819
+ // Stream both models' weights up front (concurrently) so the multi-second
1820
+ // load is a single visible phase before judging, not a silent stall on the
1821
+ // first test. Both are cached promises, so the judge reuses them after.
1822
+ async warmup() {
1823
+ await Promise.all([vision.get(), classifier.get()]);
1824
+ },
1825
+ async judge(input, cwd) {
1826
+ const entryDir = path.join(paths(cwd).judgments, input.entry.id);
1827
+ await mkdir(entryDir, { recursive: true });
1828
+ try {
1829
+ const description = await visionSemaphore.run(async () => {
1830
+ input.onJudgingStart?.();
1831
+ const fromRegions = await describeChange(input, entryDir);
1832
+ const text = fromRegions ?? await describeScreenshot(input);
1833
+ return text.trim();
1834
+ });
1835
+ const summary = summarizeInterpret(input);
1836
+ const prompt = buildClassifyPrompt(summary, description);
1837
+ const answer = await classifierSemaphore.run(async () => {
1838
+ const c = await classifier.get();
1839
+ return (await c.complete(prompt)).trim();
1840
+ });
1841
+ const label = parseLabel(answer);
1842
+ if (!label) {
1843
+ return {
1844
+ kind: "judged",
1845
+ verdict: input.heuristicVerdict,
1846
+ rationale: `${description}
1847
+ ${answer}`.trim()
1848
+ };
1263
1849
  }
1850
+ const reason = reasonOf(answer, label);
1851
+ const verdict = {
1852
+ label,
1853
+ headline: reason || input.heuristicVerdict.headline,
1854
+ // The headline already carries the classifier's reasoning; keep only
1855
+ // the deterministic region read here so the report doesn't repeat the
1856
+ // reasoning or echo the raw `VERDICT:` line back to the reader.
1857
+ rationale: [description].filter(Boolean),
1858
+ action: ACTION_BY_LABEL[label]
1859
+ };
1860
+ return { kind: "judged", verdict, rationale: answer, confidence: 0.6 };
1861
+ } catch (err) {
1862
+ const error = toError(err);
1863
+ return {
1864
+ kind: "failed",
1865
+ reason: classifyFailure(error),
1866
+ error,
1867
+ fallback: input.heuristicVerdict
1868
+ };
1264
1869
  }
1265
1870
  }
1266
- }
1267
- async put(config, checkpoint, metadata) {
1268
- const thread = config.configurable?.thread_id;
1269
- if (!thread) {
1270
- throw new Error(
1271
- 'FsCheckpointSaver: missing "thread_id" in configurable. Pass `{ configurable: { thread_id } }` when streaming.'
1272
- );
1273
- }
1274
- const ns = config.configurable?.checkpoint_ns ?? "";
1275
- const parentCheckpointId = config.configurable?.checkpoint_id;
1276
- const prepared = copyCheckpoint(checkpoint);
1277
- const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([
1278
- this.serde.dumpsTyped(prepared),
1279
- this.serde.dumpsTyped(metadata)
1280
- ]);
1281
- await mkdir(this.nsPath(thread, ns), { recursive: true });
1282
- const file = this.ckptFile(thread, ns, checkpoint.id);
1283
- const body = {
1284
- checkpoint: encode(serializedCheckpoint),
1285
- metadata: encode(serializedMetadata),
1286
- parentCheckpointId
1287
- };
1288
- await writeJsonAtomic(file, body);
1289
- return {
1290
- configurable: {
1291
- thread_id: thread,
1292
- checkpoint_ns: ns,
1293
- checkpoint_id: checkpoint.id
1294
- }
1295
- };
1296
- }
1297
- async putWrites(config, writes, taskId) {
1298
- const thread = config.configurable?.thread_id;
1299
- if (!thread) {
1300
- throw new Error(
1301
- 'FsCheckpointSaver: missing "thread_id" in configurable for putWrites.'
1302
- );
1303
- }
1304
- const ns = config.configurable?.checkpoint_ns ?? "";
1305
- const ckptId = config.configurable?.checkpoint_id;
1306
- if (!ckptId) {
1307
- throw new Error(
1308
- 'FsCheckpointSaver: missing "checkpoint_id" in configurable for putWrites.'
1309
- );
1310
- }
1311
- const key = `${thread}|${ns}|${ckptId}`;
1312
- await this.withLock(key, async () => {
1313
- const existing = await readJson2(this.writesFile(thread, ns, ckptId)) ?? {};
1314
- let mutated = false;
1315
- for (let idx = 0; idx < writes.length; idx++) {
1316
- const [channel, value] = writes[idx];
1317
- const writeIdx = WRITES_IDX_MAP[channel] ?? idx;
1318
- const innerKey = `${taskId},${writeIdx}`;
1319
- if (writeIdx >= 0 && innerKey in existing) continue;
1320
- const [, serialized] = await this.serde.dumpsTyped(value);
1321
- existing[innerKey] = [taskId, channel, encode(serialized)];
1322
- mutated = true;
1323
- }
1324
- if (!mutated) return;
1325
- await mkdir(this.nsPath(thread, ns), { recursive: true });
1326
- await writeJsonAtomic(this.writesFile(thread, ns, ckptId), existing);
1327
- });
1328
- }
1329
- async deleteThread(threadId) {
1330
- await rm(this.threadDir(threadId), { recursive: true, force: true });
1331
- }
1332
- };
1333
- var PREVIEW_WIDTH = 320;
1334
- function escapeCell(s) {
1335
- return s.replace(/\n/g, " ");
1336
- }
1337
- function toBlazediffRel(cwd, abs) {
1338
- if (!abs) return void 0;
1339
- const root = paths(cwd).root;
1340
- const rel = path.isAbsolute(abs) ? path.relative(root, abs) : path.relative(paths(cwd).root, path.join(cwd, abs));
1341
- return rel.split(path.sep).join("/");
1342
- }
1343
- function img(src, alt) {
1344
- return `<img src="${src}" width="${PREVIEW_WIDTH}" alt="${alt}">`;
1345
- }
1346
- function baselineCell(r, cwd) {
1347
- const rel = toBlazediffRel(cwd, r.baselinePath) ?? `baselines/${r.id}.png`;
1348
- return img(rel, `${r.id} baseline`);
1349
- }
1350
- function actualCell(r, cwd) {
1351
- const actual = toBlazediffRel(cwd, r.actualPath);
1352
- return actual ? img(actual, `${r.id} actual`) : "-";
1353
- }
1354
- function diffCell(r, cwd) {
1355
- const diff = toBlazediffRel(cwd, r.diffPath);
1356
- return diff ? img(diff, `${r.id} diff`) : "-";
1357
- }
1358
- function verdictCell(r) {
1359
- if (r.status === "missing-baseline") {
1360
- return `missing-baseline - ${r.message ?? "baseline missing"}`;
1361
- }
1362
- if (r.status === "stale-baseline") {
1363
- return `stale-baseline - ${r.message ?? "manifest entry edited without re-capturing"}`;
1364
- }
1365
- if (r.status === "needs-judgment") {
1366
- return `needs-judgment - see judgments/${r.id}/`;
1367
- }
1368
- if (!r.verdict) {
1369
- return r.message ?? r.status;
1370
- }
1371
- return `${r.verdict.label} - ${r.verdict.headline} -> ${r.verdict.action}`;
1372
- }
1373
- function renderRow(r, cwd) {
1374
- return `| ${r.id} | ${escapeCell(baselineCell(r, cwd))} | ${escapeCell(actualCell(r, cwd))} | ${escapeCell(diffCell(r, cwd))} | ${escapeCell(verdictCell(r))} |`;
1375
- }
1376
- function headerLine(report) {
1377
- const { passed, failed, pendingJudgments, totalEntries } = report;
1378
- const parts = [`${passed}/${totalEntries} passed`];
1379
- if (failed > 0) parts.push(`${failed} failed`);
1380
- if (pendingJudgments > 0) parts.push(`${pendingJudgments} pending judgment`);
1381
- return parts.length > 1 ? `${parts[0]} (${parts.slice(1).join(", ")})` : parts[0];
1871
+ };
1382
1872
  }
1383
- function renderSummary(report, cwd = process.cwd()) {
1384
- const nonPass = report.results.filter((r) => r.status !== "pass");
1385
- const lines = [
1386
- `# blazediff check - ${report.createdAt}`,
1387
- "",
1388
- headerLine(report),
1389
- ""
1390
- ];
1391
- if (nonPass.length === 0) {
1392
- lines.push("All entries passed.");
1393
- return `${lines.join("\n")}
1394
- `;
1873
+ var localJudge = createLocalJudge();
1874
+
1875
+ // src/judge/none.ts
1876
+ var noneJudge = {
1877
+ name: "none",
1878
+ async judge(input) {
1879
+ return { kind: "judged", verdict: input.heuristicVerdict };
1395
1880
  }
1396
- lines.push("| id | baseline | actual | diff | verdict |");
1397
- lines.push("| --- | --- | --- | --- | --- |");
1398
- for (const r of nonPass) lines.push(renderRow(r, cwd));
1399
- return `${lines.join("\n")}
1400
- `;
1401
- }
1402
- async function writeSummaryMarkdown(report, cwd = process.cwd()) {
1403
- const file = paths(cwd).summary;
1881
+ };
1882
+ async function writeReport(report, cwd = process.cwd()) {
1883
+ const file = paths(cwd).report;
1404
1884
  await mkdir(path.dirname(file), { recursive: true });
1405
- await writeFile(file, renderSummary(report, cwd), "utf8");
1885
+ await writeFile(file, `${JSON.stringify(report, null, 2)}
1886
+ `, "utf8");
1406
1887
  return file;
1407
1888
  }
1889
+ async function readReport(cwd = process.cwd()) {
1890
+ return readJsonOrNull(paths(cwd).report);
1891
+ }
1408
1892
 
1409
1893
  // src/judge/apply.ts
1410
1894
  var VALID_LABELS = [
@@ -1442,21 +1926,6 @@ function parseVerdict(raw) {
1442
1926
  confidence: typeof r.confidence === "number" ? r.confidence : void 0
1443
1927
  };
1444
1928
  }
1445
- async function fileExists2(p) {
1446
- try {
1447
- await access(p);
1448
- return true;
1449
- } catch {
1450
- return false;
1451
- }
1452
- }
1453
- async function readJsonOrNull(file) {
1454
- try {
1455
- return JSON.parse(await readFile(file, "utf8"));
1456
- } catch {
1457
- return null;
1458
- }
1459
- }
1460
1929
  async function readJudgmentDirs(root) {
1461
1930
  let names;
1462
1931
  try {
@@ -1554,7 +2023,7 @@ async function reconstructFromDisk(cwd, dirs) {
1554
2023
  pendingJudgments,
1555
2024
  results
1556
2025
  };
1557
- await writeSummaryMarkdown(report, cwd);
2026
+ await writeReport(report, cwd);
1558
2027
  return report;
1559
2028
  }
1560
2029
  async function hasCheckpoint(cwd, threadId) {
@@ -1566,9 +2035,8 @@ async function hasCheckpoint(cwd, threadId) {
1566
2035
  return false;
1567
2036
  }
1568
2037
  }
1569
- async function applyJudgments(opts = process.cwd()) {
1570
- const options = typeof opts === "string" ? { cwd: opts } : opts;
1571
- const cwd = options.cwd ?? process.cwd();
2038
+ async function applyJudgments(opts = {}) {
2039
+ const cwd = opts.cwd ?? process.cwd();
1572
2040
  const manifest = await loadManifest(cwd);
1573
2041
  if (!manifest) {
1574
2042
  throw new Error(
@@ -1602,10 +2070,9 @@ async function applyJudgments(opts = process.cwd()) {
1602
2070
  cwd,
1603
2071
  verdicts,
1604
2072
  threadId,
1605
- onEvent: options.onEvent,
1606
- junitPath: options.junitPath
2073
+ onEvent: opts.onEvent,
2074
+ junitPath: opts.junitPath
1607
2075
  });
1608
- await new FsCheckpointSaver(paths(cwd).checkpoints).deleteThread(threadId).catch(() => void 0);
1609
2076
  return { report, applied, missing, invalid };
1610
2077
  }
1611
2078
  var HOST_INSTRUCTIONS = [
@@ -1615,32 +2082,18 @@ var HOST_INSTRUCTIONS = [
1615
2082
  "Decide whether the change is a regression, an intentional UI change, or rendering noise.",
1616
2083
  "Write your decision to `verdict.json` (next to this `request.json`) with shape:",
1617
2084
  ' { "id": string, "verdict": { "label": "regression-likely" | "intentional-likely" | "noise-likely", "headline": string, "rationale": string[], "action": "investigate" | "rewrite-if-intended" | "ignore-or-rewrite" }, "rationale": string, "confidence": number }',
1618
- "Then re-run `blazediff-agent check --apply-judgments --json` to regenerate summary.md."
2085
+ "Then re-run `blazediff-agent check --apply-judgments --json` to regenerate report.json."
1619
2086
  ].join("\n");
1620
2087
  function relTo(cwd, abs) {
1621
- if (!abs) return void 0;
1622
- return path.relative(cwd, abs).split(path.sep).join("/");
1623
- }
1624
- function signatureOf(r) {
1625
- const pct = typeof r.diffPercentage === "number" ? r.diffPercentage.toFixed(4) : "?";
1626
- const regions = r.regions?.length ?? 0;
1627
- const severity = r.severity ?? "?";
1628
- return `${r.status}|diff:${pct}|regions:${regions}|severity:${severity}`;
1629
- }
1630
- async function fileExists3(p) {
1631
- try {
1632
- await access(p);
1633
- return true;
1634
- } catch {
1635
- return false;
1636
- }
1637
- }
1638
- async function readJsonOrNull2(file) {
1639
- try {
1640
- return JSON.parse(await readFile(file, "utf8"));
1641
- } catch {
1642
- return null;
1643
- }
2088
+ if (!abs) return void 0;
2089
+ return path.relative(cwd, abs).split(path.sep).join("/");
2090
+ }
2091
+ function signatureOf(r) {
2092
+ const pct = typeof r.diffPercentage === "number" ? r.diffPercentage.toFixed(4) : "?";
2093
+ const severity = r.severity ?? "?";
2094
+ const regions = (r.regions ?? []).map((reg) => `${reg.changeType}:${reg.pixelCount}`).sort().join(",");
2095
+ const regionsKey = regions ? `[${regions}]` : "0";
2096
+ return `${r.status}|diff:${pct}|regions:${regionsKey}|severity:${severity}`;
1644
2097
  }
1645
2098
  function entryById(manifest, id) {
1646
2099
  return manifest.entries.find((e) => e.id === id);
@@ -1689,8 +2142,8 @@ async function discoverTiles(dir) {
1689
2142
  const locatorAbs = path.join(dir, "locator.png");
1690
2143
  const tilesAbs = path.join(dir, "regions.png");
1691
2144
  const [locator, tiles] = await Promise.all([
1692
- fileExists3(locatorAbs),
1693
- fileExists3(tilesAbs)
2145
+ fileExists2(locatorAbs),
2146
+ fileExists2(tilesAbs)
1694
2147
  ]);
1695
2148
  return {
1696
2149
  locatorPath: locator ? "locator.png" : void 0,
@@ -1707,92 +2160,380 @@ async function writeJudgments(opts) {
1707
2160
  opts.report.results.map(async (result) => {
1708
2161
  const dir = path.join(root, result.id);
1709
2162
  if (result.status === "pass") {
1710
- if (await fileExists3(dir))
2163
+ if (await fileExists2(dir))
1711
2164
  await rm(dir, { recursive: true, force: true });
1712
2165
  return;
1713
2166
  }
1714
- const entry = entryById(opts.manifest, result.id);
1715
- if (!entry) return;
1716
- await mkdir(dir, { recursive: true });
1717
- const tiles = await discoverTiles(dir);
1718
- const request = buildRequest(result, entry, cwd, tiles);
1719
- const requestFile = path.join(dir, "request.json");
1720
- const verdictFile = path.join(dir, "verdict.json");
1721
- const [prior, priorVerdict] = await Promise.all([
1722
- readJsonOrNull2(requestFile),
1723
- fileExists3(verdictFile).then(
1724
- (exists) => exists ? readJsonOrNull2(verdictFile) : null
1725
- )
1726
- ]);
1727
- const signatureMatches = prior !== null && prior.signature === request.signature;
1728
- await writeFile(
1729
- requestFile,
1730
- `${JSON.stringify(request, null, 2)}
1731
- `,
1732
- "utf8"
2167
+ const entry = entryById(opts.manifest, result.id);
2168
+ if (!entry) return;
2169
+ await mkdir(dir, { recursive: true });
2170
+ const tiles = await discoverTiles(dir);
2171
+ const request = buildRequest(result, entry, cwd, tiles);
2172
+ const requestFile = path.join(dir, "request.json");
2173
+ const verdictFile = path.join(dir, "verdict.json");
2174
+ const [prior, priorVerdict] = await Promise.all([
2175
+ readJsonOrNull(requestFile),
2176
+ fileExists2(verdictFile).then(
2177
+ (exists) => exists ? readJsonOrNull(verdictFile) : null
2178
+ )
2179
+ ]);
2180
+ const signatureMatches = prior !== null && prior.signature === request.signature;
2181
+ await writeFile(
2182
+ requestFile,
2183
+ `${JSON.stringify(request, null, 2)}
2184
+ `,
2185
+ "utf8"
2186
+ );
2187
+ if (priorVerdict && signatureMatches) {
2188
+ return;
2189
+ }
2190
+ const auto = autoVerdict(result);
2191
+ if (auto) {
2192
+ await writeFile(
2193
+ verdictFile,
2194
+ `${JSON.stringify(auto, null, 2)}
2195
+ `,
2196
+ "utf8"
2197
+ );
2198
+ } else if (priorVerdict && !signatureMatches) {
2199
+ await rm(verdictFile, { force: true });
2200
+ }
2201
+ })
2202
+ );
2203
+ let entries;
2204
+ try {
2205
+ entries = await readdir(root);
2206
+ } catch {
2207
+ return;
2208
+ }
2209
+ await Promise.all(
2210
+ entries.filter((name) => !knownIds.has(name)).map(
2211
+ (name) => rm(path.join(root, name), { recursive: true, force: true })
2212
+ )
2213
+ );
2214
+ }
2215
+
2216
+ // src/judge/index.ts
2217
+ function resolveJudge(backend) {
2218
+ switch (backend) {
2219
+ case "none":
2220
+ return noneJudge;
2221
+ case "host":
2222
+ return codingAgentHostJudge;
2223
+ case "local":
2224
+ return localJudge;
2225
+ }
2226
+ }
2227
+ function escapeXml(value) {
2228
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2229
+ }
2230
+ async function writeJunit(report, destPath) {
2231
+ await mkdir(path.dirname(destPath), { recursive: true });
2232
+ const cases = report.results.map((r) => {
2233
+ if (r.status === "pass") {
2234
+ return ` <testcase classname="blazediff" name="${escapeXml(r.id)}"/>`;
2235
+ }
2236
+ const message = r.message ?? r.status;
2237
+ return ` <testcase classname="blazediff" name="${escapeXml(r.id)}">
2238
+ <failure message="${escapeXml(message)}" type="${escapeXml(r.status)}">${escapeXml(message)}</failure>
2239
+ </testcase>`;
2240
+ });
2241
+ const failures = report.totalEntries - report.passed;
2242
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
2243
+ <testsuites>
2244
+ <testsuite name="blazediff" tests="${report.totalEntries}" failures="${failures}">
2245
+ ${cases.join("\n")}
2246
+ </testsuite>
2247
+ </testsuites>
2248
+ `;
2249
+ await writeFile(destPath, xml, "utf8");
2250
+ return destPath;
2251
+ }
2252
+ var ROOT_NS_SENTINEL = "_root";
2253
+ function nsDir(ns) {
2254
+ return ns === "" ? ROOT_NS_SENTINEL : ns;
2255
+ }
2256
+ function encode(buf) {
2257
+ return Buffer.from(buf).toString("base64");
2258
+ }
2259
+ function decode(s) {
2260
+ return Buffer.from(s, "base64");
2261
+ }
2262
+ async function readJson(file) {
2263
+ try {
2264
+ const raw = await readFile(file, "utf8");
2265
+ return JSON.parse(raw);
2266
+ } catch (err) {
2267
+ if (err.code === "ENOENT") return void 0;
2268
+ throw err;
2269
+ }
2270
+ }
2271
+ async function writeJsonAtomic(file, value) {
2272
+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
2273
+ await writeFile(tmp, JSON.stringify(value), "utf8");
2274
+ await rename(tmp, file);
2275
+ }
2276
+ var FsCheckpointSaver = class extends BaseCheckpointSaver {
2277
+ constructor(root, serde) {
2278
+ super(serde);
2279
+ this.locks = /* @__PURE__ */ new Map();
2280
+ this.root = root;
2281
+ }
2282
+ threadDir(thread) {
2283
+ return path.join(this.root, thread);
2284
+ }
2285
+ nsPath(thread, ns) {
2286
+ return path.join(this.threadDir(thread), nsDir(ns));
2287
+ }
2288
+ ckptFile(thread, ns, id) {
2289
+ return path.join(this.nsPath(thread, ns), `${id}.ckpt.json`);
2290
+ }
2291
+ writesFile(thread, ns, id) {
2292
+ return path.join(this.nsPath(thread, ns), `${id}.writes.json`);
2293
+ }
2294
+ async withLock(key, fn) {
2295
+ const prev = this.locks.get(key) ?? Promise.resolve();
2296
+ const next = prev.then(fn, fn);
2297
+ this.locks.set(key, next);
2298
+ try {
2299
+ return await next;
2300
+ } finally {
2301
+ if (this.locks.get(key) === next) this.locks.delete(key);
2302
+ }
2303
+ }
2304
+ async listCheckpointIds(thread, ns) {
2305
+ try {
2306
+ const names = await readdir(this.nsPath(thread, ns));
2307
+ const suffix = ".ckpt.json";
2308
+ return names.filter((n) => n.endsWith(suffix)).map((n) => n.slice(0, -suffix.length));
2309
+ } catch (err) {
2310
+ if (err.code === "ENOENT") return [];
2311
+ throw err;
2312
+ }
2313
+ }
2314
+ async listNamespaces(thread) {
2315
+ try {
2316
+ return await readdir(this.threadDir(thread));
2317
+ } catch (err) {
2318
+ if (err.code === "ENOENT") return [];
2319
+ throw err;
2320
+ }
2321
+ }
2322
+ async listThreads() {
2323
+ try {
2324
+ return await readdir(this.root);
2325
+ } catch (err) {
2326
+ if (err.code === "ENOENT") return [];
2327
+ throw err;
2328
+ }
2329
+ }
2330
+ decodeNs(nsDirName) {
2331
+ return nsDirName === ROOT_NS_SENTINEL ? "" : nsDirName;
2332
+ }
2333
+ async loadPendingWrites(thread, ns, ckptId) {
2334
+ const data = await readJson(
2335
+ this.writesFile(thread, ns, ckptId)
2336
+ );
2337
+ if (!data) return [];
2338
+ const out = [];
2339
+ for (const [taskId, channel, serialized] of Object.values(data)) {
2340
+ const value = await this.serde.loadsTyped("json", decode(serialized));
2341
+ out.push([taskId, channel, value]);
2342
+ }
2343
+ return out;
2344
+ }
2345
+ async migratePendingSends(checkpoint, thread, ns, parentCheckpointId) {
2346
+ const data = await readJson(
2347
+ this.writesFile(thread, ns, parentCheckpointId)
2348
+ );
2349
+ const pendingSends = data ? await Promise.all(
2350
+ Object.values(data).filter(([, channel]) => channel === TASKS).map(
2351
+ ([, , serialized]) => this.serde.loadsTyped("json", decode(serialized))
2352
+ )
2353
+ ) : [];
2354
+ const m = checkpoint;
2355
+ m.channel_values ?? (m.channel_values = {});
2356
+ m.channel_values[TASKS] = pendingSends;
2357
+ m.channel_versions ?? (m.channel_versions = {});
2358
+ const versions = Object.values(m.channel_versions);
2359
+ m.channel_versions[TASKS] = versions.length > 0 ? maxChannelVersion(...versions) : this.getNextVersion(void 0);
2360
+ }
2361
+ async readTuple(thread, ns, ckptId, config) {
2362
+ const data = await readJson(this.ckptFile(thread, ns, ckptId));
2363
+ if (!data) return void 0;
2364
+ const checkpoint = await this.serde.loadsTyped(
2365
+ "json",
2366
+ decode(data.checkpoint)
2367
+ );
2368
+ const metadata = await this.serde.loadsTyped(
2369
+ "json",
2370
+ decode(data.metadata)
2371
+ );
2372
+ if (checkpoint.v < 4 && data.parentCheckpointId !== void 0) {
2373
+ await this.migratePendingSends(
2374
+ checkpoint,
2375
+ thread,
2376
+ ns,
2377
+ data.parentCheckpointId
2378
+ );
2379
+ }
2380
+ const pendingWrites = await this.loadPendingWrites(thread, ns, ckptId);
2381
+ const tuple = {
2382
+ config,
2383
+ checkpoint,
2384
+ metadata,
2385
+ pendingWrites
2386
+ };
2387
+ if (data.parentCheckpointId !== void 0) {
2388
+ tuple.parentConfig = {
2389
+ configurable: {
2390
+ thread_id: thread,
2391
+ checkpoint_ns: ns,
2392
+ checkpoint_id: data.parentCheckpointId
2393
+ }
2394
+ };
2395
+ }
2396
+ return tuple;
2397
+ }
2398
+ async getTuple(config) {
2399
+ const thread = config.configurable?.thread_id;
2400
+ if (!thread) return void 0;
2401
+ const ns = config.configurable?.checkpoint_ns ?? "";
2402
+ const explicitId = getCheckpointId(config);
2403
+ if (explicitId) {
2404
+ return this.readTuple(thread, ns, explicitId, config);
2405
+ }
2406
+ const ids = (await this.listCheckpointIds(thread, ns)).sort(
2407
+ (a, b) => b.localeCompare(a)
2408
+ );
2409
+ if (ids.length === 0) return void 0;
2410
+ const ckptId = ids[0];
2411
+ return this.readTuple(thread, ns, ckptId, {
2412
+ configurable: {
2413
+ thread_id: thread,
2414
+ checkpoint_ns: ns,
2415
+ checkpoint_id: ckptId
2416
+ }
2417
+ });
2418
+ }
2419
+ async *list(config, options) {
2420
+ const filter = options?.filter;
2421
+ const before = options?.before;
2422
+ let limit = options?.limit;
2423
+ const configThread = config.configurable?.thread_id;
2424
+ const configNs = config.configurable?.checkpoint_ns;
2425
+ const configCkptId = config.configurable?.checkpoint_id;
2426
+ const threads = configThread ? [configThread] : await this.listThreads();
2427
+ for (const thread of threads) {
2428
+ const nsNames = await this.listNamespaces(thread);
2429
+ for (const nsName of nsNames) {
2430
+ const ns = this.decodeNs(nsName);
2431
+ if (configNs !== void 0 && ns !== configNs) continue;
2432
+ const ids = (await this.listCheckpointIds(thread, ns)).sort(
2433
+ (a, b) => b.localeCompare(a)
2434
+ );
2435
+ for (const ckptId of ids) {
2436
+ if (configCkptId && ckptId !== configCkptId) continue;
2437
+ if (before?.configurable?.checkpoint_id && ckptId >= before.configurable.checkpoint_id)
2438
+ continue;
2439
+ const tuple = await this.readTuple(thread, ns, ckptId, {
2440
+ configurable: {
2441
+ thread_id: thread,
2442
+ checkpoint_ns: ns,
2443
+ checkpoint_id: ckptId
2444
+ }
2445
+ });
2446
+ if (!tuple) continue;
2447
+ if (filter) {
2448
+ const md = tuple.metadata;
2449
+ const matches = Object.entries(filter).every(
2450
+ ([k, v]) => md?.[k] === v
2451
+ );
2452
+ if (!matches) continue;
2453
+ }
2454
+ if (limit !== void 0) {
2455
+ if (limit <= 0) return;
2456
+ limit -= 1;
2457
+ }
2458
+ yield tuple;
2459
+ }
2460
+ }
2461
+ }
2462
+ }
2463
+ async put(config, checkpoint, metadata) {
2464
+ const thread = config.configurable?.thread_id;
2465
+ if (!thread) {
2466
+ throw new Error(
2467
+ 'FsCheckpointSaver: missing "thread_id" in configurable. Pass `{ configurable: { thread_id } }` when streaming.'
1733
2468
  );
1734
- if (priorVerdict && signatureMatches) {
1735
- return;
2469
+ }
2470
+ const ns = config.configurable?.checkpoint_ns ?? "";
2471
+ const parentCheckpointId = config.configurable?.checkpoint_id;
2472
+ const prepared = copyCheckpoint(checkpoint);
2473
+ const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([
2474
+ this.serde.dumpsTyped(prepared),
2475
+ this.serde.dumpsTyped(metadata)
2476
+ ]);
2477
+ await mkdir(this.nsPath(thread, ns), { recursive: true });
2478
+ const file = this.ckptFile(thread, ns, checkpoint.id);
2479
+ const body = {
2480
+ checkpoint: encode(serializedCheckpoint),
2481
+ metadata: encode(serializedMetadata),
2482
+ parentCheckpointId
2483
+ };
2484
+ await writeJsonAtomic(file, body);
2485
+ return {
2486
+ configurable: {
2487
+ thread_id: thread,
2488
+ checkpoint_ns: ns,
2489
+ checkpoint_id: checkpoint.id
1736
2490
  }
1737
- const auto = autoVerdict(result);
1738
- if (auto) {
1739
- await writeFile(
1740
- verdictFile,
1741
- `${JSON.stringify(auto, null, 2)}
1742
- `,
1743
- "utf8"
1744
- );
1745
- } else if (priorVerdict && !signatureMatches) {
1746
- await rm(verdictFile, { force: true });
2491
+ };
2492
+ }
2493
+ async putWrites(config, writes, taskId) {
2494
+ const thread = config.configurable?.thread_id;
2495
+ if (!thread) {
2496
+ throw new Error(
2497
+ 'FsCheckpointSaver: missing "thread_id" in configurable for putWrites.'
2498
+ );
2499
+ }
2500
+ const ns = config.configurable?.checkpoint_ns ?? "";
2501
+ const ckptId = config.configurable?.checkpoint_id;
2502
+ if (!ckptId) {
2503
+ throw new Error(
2504
+ 'FsCheckpointSaver: missing "checkpoint_id" in configurable for putWrites.'
2505
+ );
2506
+ }
2507
+ const key = `${thread}|${ns}|${ckptId}`;
2508
+ await this.withLock(key, async () => {
2509
+ const existing = await readJson(this.writesFile(thread, ns, ckptId)) ?? {};
2510
+ let mutated = false;
2511
+ for (let idx = 0; idx < writes.length; idx++) {
2512
+ const [channel, value] = writes[idx];
2513
+ const writeIdx = WRITES_IDX_MAP[channel] ?? idx;
2514
+ const innerKey = `${taskId},${writeIdx}`;
2515
+ if (writeIdx >= 0 && innerKey in existing) continue;
2516
+ const [, serialized] = await this.serde.dumpsTyped(value);
2517
+ existing[innerKey] = [taskId, channel, encode(serialized)];
2518
+ mutated = true;
1747
2519
  }
1748
- })
1749
- );
1750
- let entries;
1751
- try {
1752
- entries = await readdir(root);
1753
- } catch {
1754
- return;
2520
+ if (!mutated) return;
2521
+ await mkdir(this.nsPath(thread, ns), { recursive: true });
2522
+ await writeJsonAtomic(this.writesFile(thread, ns, ckptId), existing);
2523
+ });
1755
2524
  }
1756
- await Promise.all(
1757
- entries.filter((name) => !knownIds.has(name)).map(
1758
- (name) => rm(path.join(root, name), { recursive: true, force: true })
1759
- )
1760
- );
1761
- }
1762
-
1763
- // src/judge/index.ts
1764
- function resolveJudge(backend) {
1765
- switch (backend) {
1766
- case "none":
1767
- return noneJudge;
1768
- case "host":
1769
- return hostHarnessJudge;
2525
+ async deleteThread(threadId) {
2526
+ await rm(this.threadDir(threadId), { recursive: true, force: true });
1770
2527
  }
2528
+ };
2529
+
2530
+ // src/graph/events.ts
2531
+ var sink;
2532
+ function setEventSink(fn) {
2533
+ sink = fn;
1771
2534
  }
1772
- function escapeXml(value) {
1773
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1774
- }
1775
- async function writeJunit(report, destPath) {
1776
- await mkdir(path.dirname(destPath), { recursive: true });
1777
- const cases = report.results.map((r) => {
1778
- if (r.status === "pass") {
1779
- return ` <testcase classname="blazediff" name="${escapeXml(r.id)}"/>`;
1780
- }
1781
- const message = r.message ?? r.status;
1782
- return ` <testcase classname="blazediff" name="${escapeXml(r.id)}">
1783
- <failure message="${escapeXml(message)}" type="${escapeXml(r.status)}">${escapeXml(message)}</failure>
1784
- </testcase>`;
1785
- });
1786
- const failures = report.totalEntries - report.passed;
1787
- const xml = `<?xml version="1.0" encoding="UTF-8"?>
1788
- <testsuites>
1789
- <testsuite name="blazediff" tests="${report.totalEntries}" failures="${failures}">
1790
- ${cases.join("\n")}
1791
- </testsuite>
1792
- </testsuites>
1793
- `;
1794
- await writeFile(destPath, xml, "utf8");
1795
- return destPath;
2535
+ function emitEvent(event) {
2536
+ sink?.(event);
1796
2537
  }
1797
2538
 
1798
2539
  // src/graph/nodes/results.ts
@@ -1847,6 +2588,8 @@ function failResult(entry, outcome, actualPath, baselinePath, verdict) {
1847
2588
  diffPercentage: outcome.diffPercentage,
1848
2589
  severity: outcome.interpretation?.severity,
1849
2590
  regions: outcome.interpretation?.regions?.map(narrowRegion),
2591
+ width: outcome.interpretation?.width,
2592
+ height: outcome.interpretation?.height,
1850
2593
  verdict,
1851
2594
  diffPath: outcome.diffPath,
1852
2595
  baselinePath,
@@ -1856,13 +2599,8 @@ function failResult(entry, outcome, actualPath, baselinePath, verdict) {
1856
2599
  }
1857
2600
 
1858
2601
  // src/graph/nodes/capture.ts
1859
- var legacyAuthHinted = false;
1860
- function maybePrintLegacyHint() {
1861
- if (legacyAuthHinted) return;
1862
- legacyAuthHinted = true;
1863
- process.stderr.write(
1864
- 'blazediff: manifest entries with auth: "required" are treated as persona "default" \u2014 please migrate.\n'
1865
- );
2602
+ function asCaptured(entry, output) {
2603
+ return { entry, output };
1866
2604
  }
1867
2605
  function makeCaptureNode(semaphore) {
1868
2606
  return async function captureNode(state) {
@@ -1871,27 +2609,39 @@ function makeCaptureNode(semaphore) {
1871
2609
  if (!entry || !options) {
1872
2610
  throw new Error("captureNode: entry or options missing");
1873
2611
  }
2612
+ const children = state.children;
1874
2613
  if (isEntryStale(entry)) {
1875
2614
  return {
1876
- captureOutput: { id: entry.id, skipResult: staleResult(entry) }
2615
+ captured: [
2616
+ asCaptured(entry, {
2617
+ id: entry.id,
2618
+ skipResult: staleResult(entry)
2619
+ }),
2620
+ ...children.map(
2621
+ (c) => asCaptured(c, { id: c.id, skipResult: staleResult(c) })
2622
+ )
2623
+ ]
1877
2624
  };
1878
2625
  }
1879
- let auth;
1880
- if (entry.auth !== null) {
1881
- if (entry.auth === LEGACY_REQUIRED) maybePrintLegacyHint();
1882
- try {
1883
- auth = buildAuthHook(entry.auth, options.auth, options.cwd);
1884
- } catch (err) {
1885
- if (err instanceof AuthConfigMissingError) {
1886
- return {
1887
- captureOutput: {
1888
- id: entry.id,
1889
- skipResult: errorResult(entry, err.message)
1890
- }
1891
- };
1892
- }
1893
- throw err;
1894
- }
2626
+ const failAll = (message) => ({
2627
+ captured: [
2628
+ asCaptured(entry, {
2629
+ id: entry.id,
2630
+ skipResult: errorResult(entry, message)
2631
+ }),
2632
+ ...children.map(
2633
+ (c) => asCaptured(c, { id: c.id, skipResult: errorResult(c, message) })
2634
+ )
2635
+ ]
2636
+ });
2637
+ let harnesses;
2638
+ try {
2639
+ harnesses = await resolveHarnesses(
2640
+ normalizeHarnessRefs(entry.harnesses),
2641
+ options.cwd
2642
+ );
2643
+ } catch (err) {
2644
+ return failAll(`harness: ${err.message}`);
1895
2645
  }
1896
2646
  const baselinePath = path.join(options.baselinesDir, `${entry.id}.png`);
1897
2647
  try {
@@ -1908,24 +2658,54 @@ function makeCaptureNode(semaphore) {
1908
2658
  mode: "actual"
1909
2659
  },
1910
2660
  options.cwd,
1911
- auth
2661
+ harnesses
1912
2662
  )
1913
2663
  );
1914
- return {
1915
- captureOutput: {
2664
+ const items = [
2665
+ asCaptured(entry, {
1916
2666
  id: entry.id,
1917
2667
  captureOutputPath: capture.outputPath,
1918
2668
  baselinePath
2669
+ })
2670
+ ];
2671
+ const subByName = new Map(
2672
+ (capture.subCaptures ?? []).map((s) => [s.name, s])
2673
+ );
2674
+ for (const child of children) {
2675
+ const name = subNameOf(child);
2676
+ const sub = name ? subByName.get(name) : void 0;
2677
+ const childBaseline = path.join(
2678
+ options.baselinesDir,
2679
+ `${child.id}.png`
2680
+ );
2681
+ if (sub) {
2682
+ items.push(
2683
+ asCaptured(child, {
2684
+ id: child.id,
2685
+ captureOutputPath: sub.outputPath,
2686
+ baselinePath: childBaseline
2687
+ })
2688
+ );
2689
+ } else {
2690
+ items.push(
2691
+ asCaptured(child, {
2692
+ id: child.id,
2693
+ skipResult: errorResult(
2694
+ child,
2695
+ `harness did not produce screenshot "${name ?? child.id}"`
2696
+ )
2697
+ })
2698
+ );
1919
2699
  }
1920
- };
2700
+ }
2701
+ for (const item of items) {
2702
+ if (item.output.captureOutputPath)
2703
+ emitEvent({ type: "captured", entryId: item.entry.id });
2704
+ }
2705
+ return { captured: items };
1921
2706
  } catch (err) {
1922
- if (err instanceof AuthHarnessError) {
1923
- return {
1924
- captureOutput: {
1925
- id: entry.id,
1926
- skipResult: errorResult(entry, `auth: ${err.message}`)
1927
- }
1928
- };
2707
+ if (err instanceof HarnessError) {
2708
+ return failAll(`harness: ${err.message}`);
1929
2709
  }
1930
2710
  throw err;
1931
2711
  }
@@ -2150,6 +2930,7 @@ async function judgeNode(state) {
2150
2930
  throw new Error("judgeNode: entry, options, or diff missing");
2151
2931
  }
2152
2932
  if (diff.skipResult) {
2933
+ emitEvent({ type: "result", result: diff.skipResult });
2153
2934
  return { results: [diff.skipResult] };
2154
2935
  }
2155
2936
  const outcome = diff.outcome;
@@ -2159,7 +2940,9 @@ async function judgeNode(state) {
2159
2940
  throw new Error("judgeNode: diff outputs missing");
2160
2941
  }
2161
2942
  if (outcome.match) {
2162
- return { results: [passResult(entry, baselinePath, captureOutputPath)] };
2943
+ const r = passResult(entry, baselinePath, captureOutputPath);
2944
+ emitEvent({ type: "result", result: r });
2945
+ return { results: [r] };
2163
2946
  }
2164
2947
  const verdict = deriveVerdict({
2165
2948
  reason: outcome.reason,
@@ -2167,48 +2950,62 @@ async function judgeNode(state) {
2167
2950
  diffCount: outcome.diffCount,
2168
2951
  diffPercentage: outcome.diffPercentage
2169
2952
  });
2170
- let result = failResult(
2953
+ const initial = failResult(
2171
2954
  entry,
2172
2955
  outcome,
2173
2956
  captureOutputPath,
2174
2957
  baselinePath,
2175
2958
  verdict
2176
2959
  );
2177
- if (result.baselinePath && result.actualPath) {
2178
- const judge = resolveJudge(options.judge);
2179
- const output = await judge.judge(
2180
- {
2181
- entry,
2182
- baselinePath: result.baselinePath,
2183
- actualPath: result.actualPath,
2184
- diffPath: result.diffPath,
2185
- regions: result.regions,
2186
- diffPercentage: result.diffPercentage,
2187
- severity: result.severity,
2188
- heuristicVerdict: result.verdict ?? verdict
2189
- },
2190
- options.cwd
2960
+ if (!initial.baselinePath || !initial.actualPath) {
2961
+ emitEvent({ type: "result", result: initial });
2962
+ return { results: [initial] };
2963
+ }
2964
+ const judge = resolveJudge(options.judge);
2965
+ const output = await judge.judge(
2966
+ {
2967
+ entry,
2968
+ baselinePath: initial.baselinePath,
2969
+ actualPath: initial.actualPath,
2970
+ diffPath: initial.diffPath,
2971
+ regions: initial.regions,
2972
+ diffPercentage: initial.diffPercentage,
2973
+ severity: initial.severity,
2974
+ heuristicVerdict: initial.verdict ?? verdict,
2975
+ onJudgingStart: options.judge !== "none" ? () => emitEvent({ type: "judging", entryId: entry.id, url: entry.url }) : void 0
2976
+ },
2977
+ options.cwd
2978
+ );
2979
+ let final;
2980
+ if (output.kind === "judged") {
2981
+ final = { ...initial, verdict: output.verdict };
2982
+ } else if (output.kind === "failed") {
2983
+ console.warn(
2984
+ `[blazediff] judge "${judge.name}" failed for ${entry.id} (${output.reason}): ${output.error.message}`
2191
2985
  );
2192
- if (output.kind === "judged") {
2193
- result = { ...result, verdict: output.verdict };
2194
- } else {
2195
- const pending = {
2196
- ...result,
2197
- status: "needs-judgment",
2198
- message: `awaiting judgment in ${output.requestPath}`
2199
- };
2200
- const resumed = interruptForJudgment({
2201
- kind: "host-judgment-required",
2202
- entryId: entry.id,
2203
- url: entry.url,
2204
- requestPath: output.requestPath,
2205
- signature: signatureOf(result),
2206
- pendingResult: pending
2207
- });
2208
- result = resumed ? { ...result, verdict: resumed } : pending;
2209
- }
2986
+ final = {
2987
+ ...initial,
2988
+ verdict: output.fallback,
2989
+ message: `${initial.message ?? ""}${initial.message ? " \u2014 " : ""}judge failed (${output.reason}): ${output.error.message}`
2990
+ };
2991
+ } else {
2992
+ const pending = {
2993
+ ...initial,
2994
+ status: "needs-judgment",
2995
+ message: `awaiting judgment in ${output.requestPath}`
2996
+ };
2997
+ const resumed = interruptForJudgment({
2998
+ kind: "host-judgment-required",
2999
+ entryId: entry.id,
3000
+ url: entry.url,
3001
+ requestPath: output.requestPath,
3002
+ signature: signatureOf(initial),
3003
+ pendingResult: pending
3004
+ });
3005
+ final = resumed ? { ...initial, verdict: resumed } : pending;
2210
3006
  }
2211
- return { results: [result] };
3007
+ emitEvent({ type: "result", result: final });
3008
+ return { results: [final] };
2212
3009
  }
2213
3010
 
2214
3011
  // src/graph/nodes/load.ts
@@ -2224,67 +3021,80 @@ async function loadNode(state) {
2224
3021
  }
2225
3022
  return { entries: manifest.entries, manifest };
2226
3023
  }
2227
- var resultsChannel = Annotation({
3024
+ var latest = () => Annotation({
3025
+ reducer: (acc, next) => next ?? acc,
3026
+ default: () => void 0
3027
+ });
3028
+ var appendList = () => Annotation({
2228
3029
  reducer: (acc, next) => [...acc, ...next],
2229
3030
  default: () => []
2230
3031
  });
2231
- var BranchState = Annotation.Root({
2232
- entry: Annotation({
2233
- reducer: (_, next) => next,
2234
- default: () => void 0
2235
- }),
2236
- options: Annotation({
2237
- reducer: (acc, next) => next ?? acc,
2238
- default: () => void 0
2239
- }),
2240
- captureOutput: Annotation({
2241
- reducer: (_, next) => next,
2242
- default: () => void 0
2243
- }),
2244
- diffOutput: Annotation({
3032
+ var replaceList = () => Annotation({
3033
+ reducer: (acc, next) => next ?? acc,
3034
+ default: () => []
3035
+ });
3036
+ var resultsChannel = appendList();
3037
+ var capturedChannel = appendList();
3038
+ var CaptureState = Annotation.Root({
3039
+ entry: latest(),
3040
+ children: Annotation({
2245
3041
  reducer: (_, next) => next,
2246
- default: () => void 0
3042
+ default: () => []
2247
3043
  }),
3044
+ options: latest(),
3045
+ captured: capturedChannel
3046
+ });
3047
+ var BranchState = Annotation.Root({
3048
+ entry: latest(),
3049
+ options: latest(),
3050
+ captureOutput: latest(),
3051
+ diffOutput: latest(),
2248
3052
  results: resultsChannel
2249
3053
  });
2250
3054
  var GraphState = Annotation.Root({
2251
- options: Annotation({
2252
- reducer: (acc, next) => next ?? acc,
2253
- default: () => void 0
2254
- }),
2255
- entries: Annotation({
2256
- reducer: (acc, next) => next ?? acc,
2257
- default: () => []
2258
- }),
3055
+ options: latest(),
3056
+ entries: replaceList(),
3057
+ captured: capturedChannel,
2259
3058
  results: resultsChannel,
2260
- manifest: Annotation({
2261
- reducer: (acc, next) => next ?? acc,
2262
- default: () => void 0
2263
- }),
2264
- report: Annotation({
2265
- reducer: (acc, next) => next ?? acc,
2266
- default: () => void 0
2267
- })
3059
+ manifest: latest(),
3060
+ report: latest()
2268
3061
  });
2269
3062
 
2270
3063
  // src/graph/index.ts
2271
- function cpuParallelism() {
2272
- const cores = typeof availableParallelism === "function" ? availableParallelism() : cpus().length;
2273
- if (!cores || !Number.isFinite(cores)) return 2;
2274
- return Math.max(2, cores);
2275
- }
2276
3064
  function threadIdFor(cwd) {
2277
3065
  return createHash("sha1").update(paths(cwd).manifest).digest("hex").slice(0, 16);
2278
3066
  }
2279
- function buildBranchGraph(captureSemaphore, diffSemaphore) {
2280
- return new StateGraph(BranchState).addNode("capture", makeCaptureNode(captureSemaphore)).addNode("diff", makeDiffNode(diffSemaphore)).addNode("judge", judgeNode).addEdge(START, "capture").addEdge("capture", "diff").addEdge("diff", "judge").addEdge("judge", END).compile();
3067
+ function buildCaptureGraph(captureSemaphore) {
3068
+ return new StateGraph(CaptureState).addNode("capture", makeCaptureNode(captureSemaphore)).addEdge(START, "capture").addEdge("capture", END).compile();
3069
+ }
3070
+ function buildBranchGraph(diffSemaphore) {
3071
+ return new StateGraph(BranchState).addNode("diff", makeDiffNode(diffSemaphore)).addNode("judge", judgeNode).addEdge(START, "diff").addEdge("diff", "judge").addEdge("judge", END).compile();
3072
+ }
3073
+ async function dispatchNode(state) {
3074
+ if (state.options) await resolveJudge(state.options.judge).warmup?.();
3075
+ return {};
2281
3076
  }
2282
3077
  function buildGraph(captureSemaphore, diffSemaphore, checkpointer) {
2283
- const branch = buildBranchGraph(captureSemaphore, diffSemaphore);
2284
- return new StateGraph(GraphState).addNode("load", loadNode).addNode("branch", branch).addEdge(START, "load").addConditionalEdges(
3078
+ const captureBranch = buildCaptureGraph(captureSemaphore);
3079
+ const branch = buildBranchGraph(diffSemaphore);
3080
+ return new StateGraph(GraphState).addNode("load", loadNode).addNode("capture", captureBranch).addNode("dispatch", dispatchNode).addNode("branch", branch).addEdge(START, "load").addConditionalEdges(
2285
3081
  "load",
2286
- (state) => state.entries.map(
2287
- (entry) => new Send("branch", { entry, options: state.options })
3082
+ (state) => state.entries.filter((entry) => !isDerived(entry)).map(
3083
+ (entry) => new Send("capture", {
3084
+ entry,
3085
+ children: state.entries.filter((e) => e.parent === entry.id),
3086
+ options: state.options
3087
+ })
3088
+ ),
3089
+ ["capture"]
3090
+ ).addEdge("capture", "dispatch").addConditionalEdges(
3091
+ "dispatch",
3092
+ (state) => state.captured.map(
3093
+ (c) => new Send("branch", {
3094
+ entry: c.entry,
3095
+ captureOutput: c.output,
3096
+ options: state.options
3097
+ })
2288
3098
  ),
2289
3099
  ["branch"]
2290
3100
  ).addEdge("branch", END).compile({ checkpointer });
@@ -2314,10 +3124,7 @@ async function streamGraph(graph, input, threadId, onEvent) {
2314
3124
  const part = partial;
2315
3125
  if (!part) continue;
2316
3126
  if (part.results) {
2317
- for (const r of part.results) {
2318
- collect.results.push(r);
2319
- onEvent?.({ type: "result", result: r });
2320
- }
3127
+ for (const r of part.results) collect.results.push(r);
2321
3128
  }
2322
3129
  if (part.manifest) collect.manifest = part.manifest;
2323
3130
  if (part.report) {
@@ -2351,15 +3158,15 @@ async function buildPartialReport(collect, cwd) {
2351
3158
  if (manifest) {
2352
3159
  await writeJudgments({ report, manifest, cwd });
2353
3160
  }
2354
- await writeSummaryMarkdown(report, cwd);
3161
+ await writeReport(report, cwd);
2355
3162
  await ensureGitignore(cwd);
2356
3163
  return report;
2357
3164
  }
2358
3165
  async function runGraph(opts) {
2359
3166
  const cwd = opts.cwd ?? process.cwd();
2360
3167
  const concurrency = opts.concurrency ?? defaultConcurrency();
2361
- const captureSemaphore = new Semaphore(concurrency);
2362
- const diffSemaphore = new Semaphore(cpuParallelism());
3168
+ const captureSemaphore = createSemaphore(concurrency);
3169
+ const diffSemaphore = createSemaphore(cpuCores());
2363
3170
  const baselinesDir = paths(cwd).baselines;
2364
3171
  const checkpointer = new FsCheckpointSaver(paths(cwd).checkpoints);
2365
3172
  const graph = buildGraph(captureSemaphore, diffSemaphore, checkpointer);
@@ -2367,7 +3174,6 @@ async function runGraph(opts) {
2367
3174
  if (!opts.resume) {
2368
3175
  await checkpointer.deleteThread(threadId);
2369
3176
  }
2370
- const config = await loadConfig(cwd);
2371
3177
  const input = opts.resume ? new Command({ resume: opts.resume }) : {
2372
3178
  options: {
2373
3179
  baseUrl: opts.baseUrl ?? "",
@@ -2376,14 +3182,15 @@ async function runGraph(opts) {
2376
3182
  concurrency,
2377
3183
  emitDiffPng: opts.emitDiffPng ?? true,
2378
3184
  judge: opts.judge ?? "none",
2379
- baselinesDir,
2380
- auth: config?.auth
3185
+ baselinesDir
2381
3186
  }
2382
3187
  };
2383
3188
  let collect;
3189
+ setEventSink(opts.onEvent);
2384
3190
  try {
2385
3191
  collect = await streamGraph(graph, input, threadId, opts.onEvent);
2386
3192
  } finally {
3193
+ setEventSink(void 0);
2387
3194
  await closeBrowser();
2388
3195
  }
2389
3196
  const report = collect.report ?? await buildPartialReport(collect, cwd);
@@ -2409,4 +3216,120 @@ function runCheck(opts) {
2409
3216
  return runGraph(opts);
2410
3217
  }
2411
3218
 
2412
- export { STABILITY_HOOKS_VERSION, applyJudgments, captureScreenshot, configHash, diffEntry, discover, installBrowsers, loadConfig, loadManifest, paths, resolveBaseUrl, resolveJudge, resumeGraph, runCaptures, runCheck, runGraph, saveConfig, saveManifest, threadIdFor };
3219
+ // src/review/map.ts
3220
+ var DEFAULT_DIMS = { width: 1280, height: 800 };
3221
+ function mapLabelToClass(label) {
3222
+ switch (label) {
3223
+ case "regression-likely":
3224
+ return "regression";
3225
+ case "ambiguous":
3226
+ return "layout-shift";
3227
+ default:
3228
+ return "intentional-likely";
3229
+ }
3230
+ }
3231
+ function mapRegion(region, index) {
3232
+ return {
3233
+ id: index + 1,
3234
+ bbox: {
3235
+ x: region.bbox.x,
3236
+ y: region.bbox.y,
3237
+ w: region.bbox.width,
3238
+ h: region.bbox.height
3239
+ },
3240
+ kind: region.changeType,
3241
+ pixels: region.pixelCount,
3242
+ change: region.percentage
3243
+ };
3244
+ }
3245
+ function reviewStatus(r) {
3246
+ if (r.review === "approved") return "approved";
3247
+ if (r.review === "rejected") return "rejected";
3248
+ return "unreviewed";
3249
+ }
3250
+ function mapResultToEntry(r) {
3251
+ return {
3252
+ id: r.id,
3253
+ name: r.id,
3254
+ url: r.url,
3255
+ width: r.width ?? DEFAULT_DIMS.width,
3256
+ height: r.height ?? DEFAULT_DIMS.height,
3257
+ diff: r.diffPercentage ?? 0,
3258
+ classification: mapLabelToClass(r.verdict?.label),
3259
+ severity: r.severity ?? "low",
3260
+ action: r.verdict?.action ?? "investigate",
3261
+ summary: r.verdict?.headline ?? r.message ?? r.status,
3262
+ changes: r.verdict?.rationale ?? [],
3263
+ regions: (r.regions ?? []).map(mapRegion),
3264
+ status: reviewStatus(r),
3265
+ reviewedBy: r.review ? "you" : void 0
3266
+ };
3267
+ }
3268
+
3269
+ // src/review/actions.ts
3270
+ function recountReport(report) {
3271
+ const passed = report.results.filter((r) => r.status === "pass").length;
3272
+ const pending = report.results.filter(
3273
+ (r) => r.status === "needs-judgment"
3274
+ ).length;
3275
+ report.passed = passed;
3276
+ report.pendingJudgments = pending;
3277
+ report.failed = report.results.length - passed - pending;
3278
+ }
3279
+ async function approveEntry(id, cwd = process.cwd()) {
3280
+ const p = paths(cwd);
3281
+ const actualPng = path.join(p.actual, `${id}.png`);
3282
+ if (!existsSync(actualPng)) return null;
3283
+ await mkdir(p.baselines, { recursive: true });
3284
+ await copyFile(actualPng, path.join(p.baselines, `${id}.png`));
3285
+ await Promise.all([
3286
+ rm(actualPng, { force: true }),
3287
+ rm(path.join(p.actual, `${id}.diff.png`), { force: true }),
3288
+ rm(path.join(p.judgments, id), { recursive: true, force: true })
3289
+ ]);
3290
+ const report = await readReport(cwd);
3291
+ const result = report?.results.find((r) => r.id === id);
3292
+ if (!report || !result) return null;
3293
+ result.status = "pass";
3294
+ result.review = "approved";
3295
+ result.diffPercentage = void 0;
3296
+ result.diffCount = void 0;
3297
+ result.regions = void 0;
3298
+ result.verdict = void 0;
3299
+ result.diffPath = void 0;
3300
+ recountReport(report);
3301
+ await writeReport(report, cwd);
3302
+ return mapResultToEntry(result);
3303
+ }
3304
+ async function rejectEntry(id, cwd = process.cwd()) {
3305
+ const report = await readReport(cwd);
3306
+ const result = report?.results.find((r) => r.id === id);
3307
+ if (!report || !result) return null;
3308
+ const verdict = {
3309
+ label: "regression-likely",
3310
+ headline: result.verdict?.headline ?? "Confirmed regression during review",
3311
+ rationale: result.verdict?.rationale ?? [],
3312
+ action: "investigate"
3313
+ };
3314
+ const p = paths(cwd);
3315
+ const dir = path.join(p.judgments, id);
3316
+ await mkdir(dir, { recursive: true });
3317
+ await writeFile(
3318
+ path.join(dir, "verdict.json"),
3319
+ `${JSON.stringify({ id, verdict, rationale: "rejected via review" }, null, 2)}
3320
+ `,
3321
+ "utf8"
3322
+ );
3323
+ const updated = {
3324
+ ...result,
3325
+ status: "fail",
3326
+ review: "rejected",
3327
+ verdict
3328
+ };
3329
+ report.results = report.results.map((r) => r.id === id ? updated : r);
3330
+ recountReport(report);
3331
+ await writeReport(report, cwd);
3332
+ return mapResultToEntry(updated);
3333
+ }
3334
+
3335
+ export { HarnessError, STABILITY_HOOKS_VERSION, applyJudgments, approveEntry, assertLeftLoginPage, captureScreenshot, configHash, diffEntry, discover, installBrowsers, loadConfig, loadEnvFiles, loadHarness, loadManifest, paths, readReport, rejectEntry, resolveBaseUrl, resolveHarnessFile, resolveJudge, resumeGraph, runCaptures, runCheck, runGraph, saveConfig, saveManifest, threadIdFor, writeReport };