@decocms/parity 0.35.13 → 0.35.15

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/cli.js CHANGED
@@ -36662,7 +36662,6 @@ var init_models = __esm(() => {
36662
36662
  "pdp-matching",
36663
36663
  "section-understanding",
36664
36664
  "visual-diff",
36665
- "issue-aggregation",
36666
36665
  "explain",
36667
36666
  "component-detection"
36668
36667
  ];
@@ -36674,13 +36673,11 @@ var init_models = __esm(() => {
36674
36673
  "pdp-matching": "sonnet",
36675
36674
  "section-understanding": "sonnet",
36676
36675
  "visual-diff": "sonnet",
36677
- "issue-aggregation": "sonnet",
36678
36676
  explain: "sonnet",
36679
36677
  "component-detection": "sonnet"
36680
36678
  };
36681
36679
  PREMIUM_FEATURE_TIER = {
36682
36680
  explain: "opus",
36683
- "issue-aggregation": "opus",
36684
36681
  "visual-diff": "opus"
36685
36682
  };
36686
36683
  PROVIDER_MODELS = {
@@ -76351,6 +76348,10 @@ async function disableHttpCache(page) {
76351
76348
  function sizeOf(preset) {
76352
76349
  return preset.viewport ? { width: preset.viewport.width, height: preset.viewport.height } : undefined;
76353
76350
  }
76351
+ var headersByContext = new WeakMap;
76352
+ function contextPinHeaders(ctx) {
76353
+ return headersByContext.get(ctx);
76354
+ }
76354
76355
  async function newContext(browser, opts) {
76355
76356
  const baseContext = VIEWPORT_PRESETS[opts.viewport];
76356
76357
  const ctx = await browser.newContext({
@@ -76362,8 +76363,13 @@ async function newContext(browser, opts) {
76362
76363
  recordVideo: opts.recordVideo ? { dir: opts.recordVideo.dir, size: opts.viewportSize ?? sizeOf(baseContext) } : undefined,
76363
76364
  bypassCSP: true,
76364
76365
  ignoreHTTPSErrors: true,
76365
- extraHTTPHeaders: opts.noCache ? { "Cache-Control": "no-cache", Pragma: "no-cache" } : undefined
76366
+ extraHTTPHeaders: opts.noCache || opts.headers ? {
76367
+ ...opts.headers,
76368
+ ...opts.noCache ? { "Cache-Control": "no-cache", Pragma: "no-cache" } : {}
76369
+ } : undefined
76366
76370
  });
76371
+ if (opts.headers && Object.keys(opts.headers).length > 0)
76372
+ headersByContext.set(ctx, opts.headers);
76367
76373
  if (opts.noCache || opts.diskCacheDisabled) {
76368
76374
  const rawNewPage = ctx.newPage.bind(ctx);
76369
76375
  ctx.newPage = async () => {
@@ -76496,7 +76502,7 @@ function parseCookieFlags(values, pageUrl) {
76496
76502
  return values.map((v) => {
76497
76503
  const eq = v.indexOf("=");
76498
76504
  if (eq <= 0)
76499
- throw new Error(`--prod-cookie expects name=value, got "${v}"`);
76505
+ throw new Error("cookie pin expects name=value");
76500
76506
  return { name: v.slice(0, eq).trim(), value: v.slice(eq + 1), domain, path: "/" };
76501
76507
  });
76502
76508
  }
@@ -79252,6 +79258,112 @@ function pickHome4(pages) {
79252
79258
  });
79253
79259
  }
79254
79260
 
79261
+ // src/engine/variant.ts
79262
+ var FRESH_MARKERS = [
79263
+ ["__FRSH_STATE", /__FRSH_STATE/],
79264
+ ["/_frsh/js", /\/_frsh\/js\//],
79265
+ ["island-*.js", /\bisland-[a-z0-9_.-]+\.js\b/i]
79266
+ ];
79267
+ var TANSTACK_MARKERS = [["$_TSR", /\$_TSR/]];
79268
+ var ASSETS_BUNDLE = /<script[^>]+src="[^"]*\/assets\/[^"]+\.js"/i;
79269
+ var STACK_HEADERS = ["x-powered-by", "x-deco-platform"];
79270
+ function isAbCookie(name) {
79271
+ return /bucket/i.test(name) || isExperimentName(name);
79272
+ }
79273
+ function fingerprintVariant(html, headers, cookieNames) {
79274
+ const signals = [];
79275
+ let fresh = false;
79276
+ let tanstack = false;
79277
+ for (const h of STACK_HEADERS) {
79278
+ const v = headers[h];
79279
+ if (!v)
79280
+ continue;
79281
+ signals.push(`${h}=${v.slice(0, 60)}`);
79282
+ if (/fresh/i.test(v))
79283
+ fresh = true;
79284
+ if (/tanstack/i.test(v))
79285
+ tanstack = true;
79286
+ }
79287
+ for (const [label, re] of FRESH_MARKERS)
79288
+ if (re.test(html)) {
79289
+ signals.push(`fresh:${label}`);
79290
+ fresh = true;
79291
+ }
79292
+ for (const [label, re] of TANSTACK_MARKERS)
79293
+ if (re.test(html)) {
79294
+ signals.push(`tanstack:${label}`);
79295
+ tanstack = true;
79296
+ }
79297
+ if (ASSETS_BUNDLE.test(html))
79298
+ signals.push("bundle:/assets/*.js");
79299
+ for (const n of [...new Set(cookieNames)].filter(isAbCookie).sort())
79300
+ signals.push(`cookie:${n}`);
79301
+ const stack = fresh === tanstack ? "unknown" : fresh ? "fresh" : "tanstack";
79302
+ return { stack, signals };
79303
+ }
79304
+ var LABEL = {
79305
+ fresh: "Fresh",
79306
+ tanstack: "TanStack"
79307
+ };
79308
+ function stackCounts(pages, keyOf) {
79309
+ const seen = new Map;
79310
+ for (const p of pages) {
79311
+ const s = p.variant?.stack;
79312
+ if (!s || s === "unknown")
79313
+ continue;
79314
+ seen.set(s, (seen.get(s) ?? new Set).add(keyOf(p)));
79315
+ }
79316
+ return new Map([...seen].map(([s, keys]) => [s, keys.size]));
79317
+ }
79318
+ function describeMix(counts) {
79319
+ if (counts.size < 2)
79320
+ return null;
79321
+ return [...counts].map(([s, n], i) => `${n}${i === 0 ? n === 1 ? " page" : " pages" : ""} ${LABEL[s]}`).join(", ");
79322
+ }
79323
+
79324
+ // src/checks/lib/variant-guard.ts
79325
+ function variantMismatches(prodPages, candPages) {
79326
+ const prodMix = describeMix(stackCounts(prodPages, captureKey));
79327
+ const candMix = describeMix(stackCounts(candPages, captureKey));
79328
+ if (!prodMix && !candMix)
79329
+ return null;
79330
+ const mixed = [prodMix && `prod served mixed variants: ${prodMix}`, candMix && `cand served mixed variants: ${candMix}`].filter(Boolean).join("; ");
79331
+ const keys = new Map;
79332
+ for (const { key, prod, cand } of pairCaptures(prodPages, candPages).pairs) {
79333
+ const p = prod.variant?.stack;
79334
+ const c = cand.variant?.stack;
79335
+ if (p && c && p !== "unknown" && c !== "unknown" && p !== c)
79336
+ keys.set(key, `prod=${p}, cand=${c}`);
79337
+ }
79338
+ return { mixed, keys };
79339
+ }
79340
+ function withSameVariant(check) {
79341
+ const guarded = async (ctx) => {
79342
+ const mismatch = variantMismatches(ctx.prodPages, ctx.candPages);
79343
+ if (!mismatch || mismatch.keys.size === 0)
79344
+ return check(ctx);
79345
+ const keep = (pages) => pages.filter((p) => !mismatch.keys.has(captureKey(p)));
79346
+ const result = await check({ ...ctx, prodPages: keep(ctx.prodPages), candPages: keep(ctx.candPages) });
79347
+ const issues = [...mismatch.keys].map(([key, stacks]) => ({
79348
+ id: `${result.name}:variant-mismatch:${key}`,
79349
+ severity: "low",
79350
+ inconclusive: true,
79351
+ category: "functional",
79352
+ page: key,
79353
+ check: result.name,
79354
+ summary: `${key}: prod and cand served by different builds (${stacks}) — not compared by ${result.name}`,
79355
+ details: `${mismatch.mixed} — pin with --prod-cookie/--prod-header. Script counts, request volume and vitals of a pair served by two different stacks measure the A/B bucket, not the migration.`
79356
+ }));
79357
+ return {
79358
+ ...result,
79359
+ status: result.status === "pass" ? "warn" : result.status,
79360
+ issues: [...result.issues, ...issues]
79361
+ };
79362
+ };
79363
+ Object.defineProperty(guarded, "name", { value: check.name });
79364
+ return guarded;
79365
+ }
79366
+
79255
79367
  // src/diff/network.ts
79256
79368
  function summarizeNetwork(entries) {
79257
79369
  const summary = {
@@ -82568,12 +82680,17 @@ async function warmBeforeCapture(ctx, url, viewport) {
82568
82680
  return;
82569
82681
  const start = Date.now();
82570
82682
  const cookies = await ctx.cookies(url).catch(() => []);
82683
+ const headers = contextPinHeaders(ctx);
82571
82684
  for (let i = 0;i < cfg.loads; i++) {
82572
82685
  cfg.stats.loads++;
82573
82686
  const deadline = Date.now() + VITALS_WARM_TIMEOUT_MS;
82574
82687
  let warm;
82575
82688
  try {
82576
- warm = await browser.newContext({ ...VIEWPORT_PRESETS[viewport], ignoreHTTPSErrors: true });
82689
+ warm = await browser.newContext({
82690
+ ...VIEWPORT_PRESETS[viewport],
82691
+ ignoreHTTPSErrors: true,
82692
+ extraHTTPHeaders: headers
82693
+ });
82577
82694
  if (cookies.length > 0)
82578
82695
  await warm.addCookies(cookies);
82579
82696
  const page = await warm.newPage();
@@ -83120,8 +83237,10 @@ async function capturePage(page, opts) {
83120
83237
  harPath: opts.harPath,
83121
83238
  tracePath: opts.tracePath,
83122
83239
  xRobotsTag,
83123
- pairKey: opts.pairKey
83240
+ pairKey: opts.pairKey,
83241
+ ...response ? { variant: fingerprintVariant(html, response.headers(), cookieNames) } : {}
83124
83242
  });
83243
+ let cookieNames = [];
83125
83244
  let response = null;
83126
83245
  let finalUrl = opts.url;
83127
83246
  let xRobotsTag = null;
@@ -83252,6 +83371,7 @@ async function capturePage(page, opts) {
83252
83371
  }
83253
83372
  dlog(opts.side, opts.viewport, ` capturePage: page.content() (cap=${Math.min(5000, remaining())}ms)`);
83254
83373
  html = await snapshotHtml(page, Math.min(5000, remaining()));
83374
+ cookieNames = await Promise.resolve().then(() => page.context().cookies(page.url())).then((cs) => cs.map((c) => c.name)).catch(() => []);
83255
83375
  dlog(opts.side, opts.viewport, ` capturePage: flushCollectors (cap=${Math.min(3000, remaining())}ms)`);
83256
83376
  await flushCollectors(state, Math.min(3000, remaining()));
83257
83377
  const extraRuns = Math.max(0, (opts.runs ?? 1) - 1);
@@ -84102,6 +84222,59 @@ function screenshotPath(ctx, label) {
84102
84222
  const safe = label.replace(/[^a-z0-9_-]+/gi, "-").toLowerCase();
84103
84223
  return `${ctx.outDir}/${safe}-${ctx.viewport}-${ctx.side}.png`;
84104
84224
  }
84225
+ var DEDICATED_FLOWS = new Set(["homepage", "plp", "pdp"]);
84226
+ var dedicatedCaptures = new WeakMap;
84227
+ function rememberDedicatedCaptures(flow, ctx, pages) {
84228
+ if (!DEDICATED_FLOWS.has(flow))
84229
+ return;
84230
+ let byKey = dedicatedCaptures.get(ctx);
84231
+ if (!byKey) {
84232
+ byKey = new Map;
84233
+ dedicatedCaptures.set(ctx, byKey);
84234
+ }
84235
+ for (const p of pages) {
84236
+ if (p.pairKey || p.status < 200 || p.status >= 400 || !p.html)
84237
+ continue;
84238
+ byKey.set(captureKey(p), p);
84239
+ }
84240
+ }
84241
+ async function captureOrVisit(page, ctx, url, label) {
84242
+ const shot = screenshotPath(ctx, label);
84243
+ const prior = dedicatedCaptures.get(ctx.ctx)?.get(captureKey({ url, viewport: ctx.viewport }));
84244
+ if (!prior) {
84245
+ const cap = await capturePage(page, {
84246
+ url,
84247
+ side: ctx.side,
84248
+ viewport: ctx.viewport,
84249
+ screenshotPath: shot
84250
+ });
84251
+ return {
84252
+ cap,
84253
+ reused: false,
84254
+ status: cap.status,
84255
+ finalUrl: cap.finalUrl,
84256
+ durationMs: cap.durationMs,
84257
+ screenshotPath: cap.screenshotPath
84258
+ };
84259
+ }
84260
+ const start = Date.now();
84261
+ const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 }).catch(() => null);
84262
+ await page.waitForLoadState("load", { timeout: 12000 }).catch(() => {
84263
+ return;
84264
+ });
84265
+ await page.waitForLoadState("networkidle", { timeout: 6000 }).catch(() => {
84266
+ return;
84267
+ });
84268
+ await screenshotStable(page, { path: shot });
84269
+ return {
84270
+ cap: prior,
84271
+ reused: true,
84272
+ status: response?.status() ?? 0,
84273
+ finalUrl: page.url(),
84274
+ durationMs: Date.now() - start,
84275
+ screenshotPath: shot
84276
+ };
84277
+ }
84105
84278
  function makeSkipStep(step, name, ctx, note) {
84106
84279
  return {
84107
84280
  step,
@@ -89061,7 +89234,9 @@ var cookieCepModalCls2 = withHtmlSnapshot(cookieCepModalCls);
89061
89234
  var faviconParity2 = withHtmlSnapshot(faviconParity);
89062
89235
  var fontParity2 = withHtmlSnapshot(fontParity);
89063
89236
  var footerLinksHealth2 = withHtmlSnapshot(footerLinksHealth);
89064
- var htmlStructuralDiff2 = withHtmlSnapshot(htmlStructuralDiff);
89237
+ var htmlStructuralDiff2 = withSameVariant(withHtmlSnapshot(htmlStructuralDiff));
89238
+ var networkSummaryDelta2 = withSameVariant(networkSummaryDelta);
89239
+ var webVitalsMobile2 = withSameVariant(webVitalsMobile);
89065
89240
  var imageLoadingHealth2 = withHtmlSnapshot(imageLoadingHealth);
89066
89241
  var lazySectionPresence2 = withHtmlSnapshot(lazySectionPresence);
89067
89242
  var metaSeoParity2 = withHtmlSnapshot(metaSeoParity);
@@ -89079,8 +89254,8 @@ var ALL_CHECKS = [
89079
89254
  metaSeoParity2,
89080
89255
  visualRegressionKeyframes,
89081
89256
  purchaseJourneyFlow,
89082
- networkSummaryDelta,
89083
- webVitalsMobile,
89257
+ networkSummaryDelta2,
89258
+ webVitalsMobile2,
89084
89259
  imageLoadingHealth2,
89085
89260
  bannerAspectRatio2,
89086
89261
  cartRevealModeDivergence,
@@ -89121,8 +89296,8 @@ var ALL_CHECKS_BY_NAME = {
89121
89296
  "meta-seo-parity": metaSeoParity2,
89122
89297
  "visual-regression-keyframes": visualRegressionKeyframes,
89123
89298
  "purchase-journey-flow": purchaseJourneyFlow,
89124
- "network-summary-delta": networkSummaryDelta,
89125
- "web-vitals-mobile": webVitalsMobile,
89299
+ "network-summary-delta": networkSummaryDelta2,
89300
+ "web-vitals-mobile": webVitalsMobile2,
89126
89301
  "image-loading-health": imageLoadingHealth2,
89127
89302
  "banner-aspect-ratio": bannerAspectRatio2,
89128
89303
  "cart-reveal-mode-divergence": cartRevealModeDivergence,
@@ -89447,6 +89622,11 @@ var NetworkEntry = z2.object({
89447
89622
  serverTiming: z2.string().nullable(),
89448
89623
  decoSection: z2.string().nullable()
89449
89624
  });
89625
+ var ServingStack = z2.enum(["fresh", "tanstack", "unknown"]);
89626
+ var VariantFingerprint = z2.object({
89627
+ stack: ServingStack,
89628
+ signals: z2.array(z2.string())
89629
+ });
89450
89630
  var PageCapture = z2.object({
89451
89631
  url: z2.string(),
89452
89632
  finalUrl: z2.string(),
@@ -89468,7 +89648,8 @@ var PageCapture = z2.object({
89468
89648
  harPath: z2.string().optional(),
89469
89649
  tracePath: z2.string().optional(),
89470
89650
  xRobotsTag: z2.string().nullable().optional(),
89471
- pairKey: z2.string().optional()
89651
+ pairKey: z2.string().optional(),
89652
+ variant: VariantFingerprint.optional()
89472
89653
  });
89473
89654
  var StepCapture = z2.object({
89474
89655
  step: z2.number(),
@@ -89808,6 +89989,10 @@ var Run = z2.object({
89808
89989
  partial: z2.boolean().optional(),
89809
89990
  partialReason: z2.string().optional(),
89810
89991
  caveats: z2.array(RunCaveat).optional(),
89992
+ pinned: z2.object({
89993
+ prod: z2.object({ cookies: z2.array(z2.string()), headers: z2.array(z2.string()) }),
89994
+ cand: z2.object({ cookies: z2.array(z2.string()), headers: z2.array(z2.string()) })
89995
+ }).optional(),
89811
89996
  pagePairs: z2.array(PagePairMeasurement).optional(),
89812
89997
  timings: z2.object({
89813
89998
  totalMs: z2.number(),
@@ -89842,6 +90027,10 @@ var Baseline = z2.object({
89842
90027
  var ParityRc = z2.object({
89843
90028
  cep: z2.string().default("01310-100"),
89844
90029
  profile: z2.enum(["commerce", "content"]).optional(),
90030
+ pin: z2.object({
90031
+ prod: z2.object({ cookies: z2.array(z2.string()).optional(), headers: z2.array(z2.string()).optional() }).optional(),
90032
+ cand: z2.object({ cookies: z2.array(z2.string()).optional(), headers: z2.array(z2.string()).optional() }).optional()
90033
+ }).optional(),
89845
90034
  plpUrlHint: z2.string().optional(),
89846
90035
  selectors: z2.object({
89847
90036
  categoryLink: z2.string().optional(),
@@ -92396,8 +92585,8 @@ function pathOf4(url) {
92396
92585
  }
92397
92586
 
92398
92587
  // src/storage/fs.ts
92399
- import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync9, readdirSync, writeFileSync as writeFileSync8 } from "node:fs";
92400
- import { join as join7 } from "node:path";
92588
+ import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync9, readdirSync, rmSync, writeFileSync as writeFileSync8 } from "node:fs";
92589
+ import { dirname as dirname4, join as join7 } from "node:path";
92401
92590
  function newRunId() {
92402
92591
  return new Date().toISOString().replace(/[:.]/g, "-").replace("T", "T");
92403
92592
  }
@@ -92418,7 +92607,9 @@ function createRunDir(outputDir, runId) {
92418
92607
  return paths;
92419
92608
  }
92420
92609
  function getRunPaths(outputDir, runId) {
92421
- const runDir = join7(outputDir, "runs", runId);
92610
+ return runPathsFor(join7(outputDir, "runs", runId));
92611
+ }
92612
+ function runPathsFor(runDir) {
92422
92613
  return {
92423
92614
  runDir,
92424
92615
  reportJson: join7(runDir, "report.json"),
@@ -92452,9 +92643,12 @@ function writeRunReportHtml(runDir, html) {
92452
92643
  return path;
92453
92644
  }
92454
92645
  function loadRun(outputDir, runId) {
92455
- const reportJson = join7(outputDir, "runs", runId, "report.json");
92646
+ return loadRunDir(join7(outputDir, "runs", runId), runId);
92647
+ }
92648
+ function loadRunDir(runDir, label = runDir) {
92649
+ const reportJson = join7(runDir, "report.json");
92456
92650
  if (!existsSync7(reportJson)) {
92457
- throw new Error(`Run not found: ${runId}`);
92651
+ throw new Error(`Run not found: ${label}`);
92458
92652
  }
92459
92653
  const raw = JSON.parse(readFileSync9(reportJson, "utf8"));
92460
92654
  return Run.parse(raw);
@@ -92469,19 +92663,19 @@ function sameModuleSet(a, b) {
92469
92663
  return false;
92470
92664
  return true;
92471
92665
  }
92666
+ function hostOf2(url) {
92667
+ try {
92668
+ return new URL(url).hostname;
92669
+ } catch {
92670
+ return url;
92671
+ }
92672
+ }
92472
92673
  function findPreviousRun(outputDir, opts) {
92473
92674
  return findComparableRuns(outputDir, opts, 1)[0] ?? null;
92474
92675
  }
92475
92676
  function findComparableRuns(outputDir, opts, limit) {
92476
- const hostOf = (url) => {
92477
- try {
92478
- return new URL(url).hostname;
92479
- } catch {
92480
- return url;
92481
- }
92482
- };
92483
- const prodHost = hostOf(opts.prodUrl);
92484
- const candHost = hostOf(opts.candUrl);
92677
+ const prodHost = hostOf2(opts.prodUrl);
92678
+ const candHost = hostOf2(opts.candUrl);
92485
92679
  const out = [];
92486
92680
  for (const entry of listRuns(outputDir)) {
92487
92681
  if (out.length >= limit)
@@ -92496,7 +92690,7 @@ function findComparableRuns(outputDir, opts, limit) {
92496
92690
  continue;
92497
92691
  if (opts.scoreVersion !== undefined && raw.verdict.scoreVersion !== opts.scoreVersion)
92498
92692
  continue;
92499
- if (hostOf(raw.prodUrl ?? "") !== prodHost || hostOf(raw.candUrl ?? "") !== candHost)
92693
+ if (hostOf2(raw.prodUrl ?? "") !== prodHost || hostOf2(raw.candUrl ?? "") !== candHost)
92500
92694
  continue;
92501
92695
  if (opts.modulesRun && opts.modulesRun.length > 0) {
92502
92696
  const candidateModules = raw.verdict?.modulesRun ?? [];
@@ -92531,6 +92725,26 @@ function listRuns(outputDir) {
92531
92725
  }).sort((a, b) => b.id.localeCompare(a.id));
92532
92726
  return entries;
92533
92727
  }
92728
+ function pruneRuns(outputDir, opts) {
92729
+ const prodHost = hostOf2(opts.prodUrl);
92730
+ const candHost = hostOf2(opts.candUrl);
92731
+ const samePair = listRuns(outputDir).filter((entry) => {
92732
+ try {
92733
+ const raw = JSON.parse(readFileSync9(entry.reportPath, "utf8"));
92734
+ return hostOf2(raw.prodUrl ?? "") === prodHost && hostOf2(raw.candUrl ?? "") === candHost;
92735
+ } catch {
92736
+ return false;
92737
+ }
92738
+ });
92739
+ const pruned = [];
92740
+ for (const entry of samePair.slice(opts.keep)) {
92741
+ if (opts.protect.has(entry.id))
92742
+ continue;
92743
+ rmSync(dirname4(entry.reportPath), { recursive: true, force: true });
92744
+ pruned.push(entry.id);
92745
+ }
92746
+ return pruned;
92747
+ }
92534
92748
 
92535
92749
  // src/util/pages.ts
92536
92750
  import chalk6 from "chalk";
@@ -94746,6 +94960,13 @@ async function measureProductCards(page) {
94746
94960
 
94747
94961
  // src/engine/flows/purchase-journey.ts
94748
94962
  var PURCHASE_JOURNEY_TOTAL_STEPS = 9;
94963
+ async function beforeShot(ctx, page, label) {
94964
+ if (!ctx.beforeShots)
94965
+ return;
94966
+ const path = screenshotPath(ctx, label);
94967
+ await screenshotStable(page, { path, fullPage: false });
94968
+ return path;
94969
+ }
94749
94970
  var DEFAULT_ADD_TO_CART_CONFIRM_MS = 3000;
94750
94971
  function resolveAddToCartConfirmMs(rc) {
94751
94972
  const v = rc.addToCartConfirmMs;
@@ -94765,13 +94986,9 @@ async function flowPurchaseJourney(ctx) {
94765
94986
  };
94766
94987
  try {
94767
94988
  reportStart(1, "visit-home");
94768
- const homeCap = await capturePage(page, {
94769
- url: ctx.baseUrl,
94770
- side: ctx.side,
94771
- viewport: ctx.viewport,
94772
- screenshotPath: screenshotPath(ctx, "pj-1-home")
94773
- });
94774
- pages.push(homeCap);
94989
+ const homeCap = await captureOrVisit(page, ctx, ctx.baseUrl, "pj-1-home");
94990
+ if (!homeCap.reused)
94991
+ pages.push(homeCap.cap);
94775
94992
  const step1Status = homeCap.status >= 200 && homeCap.status < 400 ? "ok" : "failed";
94776
94993
  steps.push({
94777
94994
  step: 1,
@@ -94796,13 +95013,9 @@ async function flowPurchaseJourney(ctx) {
94796
95013
  return { pages, steps };
94797
95014
  }
94798
95015
  const t2 = Date.now();
94799
- const plpCap = await capturePage(page, {
94800
- url: plpHit.url,
94801
- side: ctx.side,
94802
- viewport: ctx.viewport,
94803
- screenshotPath: screenshotPath(ctx, "pj-2-plp")
94804
- });
94805
- pages.push(plpCap);
95016
+ const plpCap = await captureOrVisit(page, ctx, plpHit.url, "pj-2-plp");
95017
+ if (!plpCap.reused)
95018
+ pages.push(plpCap.cap);
94806
95019
  const step2Status = plpCap.status >= 200 && plpCap.status < 400 ? "ok" : "failed";
94807
95020
  steps.push({
94808
95021
  step: 2,
@@ -94821,6 +95034,10 @@ async function flowPurchaseJourney(ctx) {
94821
95034
  steps[steps.length - 1].beforeUrl = ctx.baseUrl;
94822
95035
  reportStart(3, "enter-pdp");
94823
95036
  let pdpHit = await findProductUrl(page, ctx);
95037
+ if (!pdpHit && plpCap.reused) {
95038
+ await scrollPageInChunks(page);
95039
+ pdpHit = await findProductUrl(page, ctx);
95040
+ }
94824
95041
  let pdpRecoveredByLlm = false;
94825
95042
  if (!pdpHit && budget.remaining > 0) {
94826
95043
  const html = await page.content().catch(() => "");
@@ -94853,13 +95070,9 @@ async function flowPurchaseJourney(ctx) {
94853
95070
  return { pages, steps };
94854
95071
  }
94855
95072
  const t3 = Date.now();
94856
- const pdpCap = await capturePage(page, {
94857
- url: pdpHit.url,
94858
- side: ctx.side,
94859
- viewport: ctx.viewport,
94860
- screenshotPath: screenshotPath(ctx, "pj-3-pdp")
94861
- });
94862
- pages.push(pdpCap);
95073
+ const pdpCap = await captureOrVisit(page, ctx, pdpHit.url, "pj-3-pdp");
95074
+ if (!pdpCap.reused)
95075
+ pages.push(pdpCap.cap);
94863
95076
  const step3Status = pdpCap.status >= 200 && pdpCap.status < 400 ? "ok" : "failed";
94864
95077
  steps.push({
94865
95078
  step: 3,
@@ -94889,8 +95102,7 @@ async function flowPurchaseJourney(ctx) {
94889
95102
  reportStart(4, "select-variant");
94890
95103
  const t4 = Date.now();
94891
95104
  const beforeUrl4 = page.url();
94892
- const spBefore4 = screenshotPath(ctx, "pj-4-select-variant-before");
94893
- await screenshotStable(page, { path: spBefore4, fullPage: false });
95105
+ const spBefore4 = await beforeShot(ctx, page, "pj-4-select-variant-before");
94894
95106
  const variantResult = await selectVariant(page, ctx);
94895
95107
  let variantLlmAction = null;
94896
95108
  if (variantResult.actions.length === 0 && variantResult.variantRequired && budget.remaining > 0) {
@@ -94957,8 +95169,7 @@ async function flowPurchaseJourney(ctx) {
94957
95169
  if (cepInputPdp) {
94958
95170
  const t5 = Date.now();
94959
95171
  const beforeUrl5 = page.url();
94960
- const spBefore5 = screenshotPath(ctx, "pj-5-shipping-pdp-before");
94961
- await screenshotStable(page, { path: spBefore5, fullPage: false });
95172
+ const spBefore5 = await beforeShot(ctx, page, "pj-5-shipping-pdp-before");
94962
95173
  const ok = await fillCep(page, cepInputPdp, ctx.rc.cep);
94963
95174
  const sp = screenshotPath(ctx, "pj-5-shipping-pdp");
94964
95175
  await screenshotStable(page, { path: sp, fullPage: false });
@@ -95011,8 +95222,7 @@ async function flowPurchaseJourney(ctx) {
95011
95222
  }
95012
95223
  const t6 = Date.now();
95013
95224
  const beforeUrl6 = page.url();
95014
- const spBefore6 = screenshotPath(ctx, "pj-6-add-cart-before");
95015
- await screenshotStable(page, { path: spBefore6, fullPage: false });
95225
+ const spBefore6 = await beforeShot(ctx, page, "pj-6-add-cart-before");
95016
95226
  const cartCountBefore = await readCartCount(page, ctx);
95017
95227
  const drawersBefore = await visibleDrawerSelectors(page, ctx);
95018
95228
  const cartWatch = watchCartMutation(page);
@@ -95099,8 +95309,7 @@ async function flowPurchaseJourney(ctx) {
95099
95309
  reportStart(7, "open-minicart");
95100
95310
  const t7 = Date.now();
95101
95311
  const beforeUrl7 = page.url();
95102
- const spBefore7 = screenshotPath(ctx, "pj-7-minicart-before");
95103
- await screenshotStable(page, { path: spBefore7, fullPage: false });
95312
+ const spBefore7 = await beforeShot(ctx, page, "pj-7-minicart-before");
95104
95313
  let cartOpenMethod = "failed";
95105
95314
  let miniText = "";
95106
95315
  let cartRevealMode = "unknown";
@@ -95208,7 +95417,7 @@ async function flowPurchaseJourney(ctx) {
95208
95417
  recoveredByLlm: miniRecovered || undefined
95209
95418
  });
95210
95419
  reportEnd(7, "open-minicart", step7Status, Date.now() - t7, step7QuirkNote ?? step7RevealFailureNote);
95211
- await captureInpSnapshot(page, pdpCap);
95420
+ await captureInpSnapshot(page, pdpCap.cap);
95212
95421
  if (isProdCartEmptyQuirk) {
95213
95422
  const quirkNote = "cart-empty-prod-quirk: skipped (depende do cart que prod não persistiu)";
95214
95423
  reportStart(8, "shipping-calc-cart");
@@ -95244,8 +95453,7 @@ async function flowPurchaseJourney(ctx) {
95244
95453
  if (cepInputCart) {
95245
95454
  const t8 = Date.now();
95246
95455
  const beforeUrl8 = page.url();
95247
- const spBefore8 = screenshotPath(ctx, "pj-8-shipping-cart-before");
95248
- await screenshotStable(page, { path: spBefore8, fullPage: false });
95456
+ const spBefore8 = await beforeShot(ctx, page, "pj-8-shipping-cart-before");
95249
95457
  const ok = await fillCep(page, cepInputCart, ctx.rc.cep);
95250
95458
  const sp8 = screenshotPath(ctx, "pj-8-shipping-cart");
95251
95459
  await screenshotStable(page, { path: sp8, fullPage: false });
@@ -95322,8 +95530,7 @@ async function flowPurchaseJourney(ctx) {
95322
95530
  reportEnd(9, "go-checkout", "skipped", 0, "no checkout button found");
95323
95531
  return { pages, steps };
95324
95532
  }
95325
- const spBefore9 = screenshotPath(ctx, "pj-9-checkout-before");
95326
- await screenshotStable(page, { path: spBefore9, fullPage: false });
95533
+ const spBefore9 = await beforeShot(ctx, page, "pj-9-checkout-before");
95327
95534
  await Promise.race([
95328
95535
  dismissOverlays(page, ctx),
95329
95536
  new Promise((resolve) => setTimeout(resolve, 4000))
@@ -99149,6 +99356,9 @@ function groupIssues(issues) {
99149
99356
  }
99150
99357
  return [...groups.values()].sort((a, b) => SEVERITY_RANK3[a.severity] - SEVERITY_RANK3[b.severity] || b.count - a.count);
99151
99358
  }
99359
+ function rankTopIssues(issues, limit = 10) {
99360
+ return groupIssues(issues).sort((a, b) => SEVERITY_RANK3[a.severity] - SEVERITY_RANK3[b.severity] || b.pages.length - a.pages.length || b.count - a.count).slice(0, limit).map((g) => g.sample);
99361
+ }
99152
99362
 
99153
99363
  // src/report/visual-prompt-builder.ts
99154
99364
  import { relative as relative4 } from "node:path";
@@ -99315,10 +99525,13 @@ function buildWaterfallRows(entries) {
99315
99525
  rows.sort((a, b) => a.start - b.start);
99316
99526
  return rows;
99317
99527
  }
99528
+ var WATERFALL_MAX_BARS = 120;
99318
99529
  function renderWaterfall(entries) {
99319
- const rows = buildWaterfallRows(entries);
99320
- if (rows.length === 0)
99530
+ const all = buildWaterfallRows(entries);
99531
+ if (all.length === 0)
99321
99532
  return "";
99533
+ const rows = all.slice(0, WATERFALL_MAX_BARS);
99534
+ const cutNote = all.length > rows.length ? `<div class="hint">First ${rows.length} of ${all.length} timed requests by start time · +${all.length - rows.length} more in report.json</div>` : "";
99322
99535
  const ends = rows.map((r) => r.end).sort((a, b) => a - b);
99323
99536
  const p95 = ends[Math.floor(ends.length * 0.95)] ?? ends[ends.length - 1] ?? 1;
99324
99537
  const max = Math.max(p95, 100);
@@ -99356,7 +99569,7 @@ function renderWaterfall(entries) {
99356
99569
  <line x1="${x.toFixed(1)}" y1="14" x2="${x.toFixed(1)}" y2="${HEIGHT - 4}" class="wf-tick"/>
99357
99570
  <text x="${x.toFixed(1)}" y="10" class="wf-tick-label" text-anchor="middle">${t}ms</text>`;
99358
99571
  }).join("");
99359
- return `
99572
+ return `${cutNote}
99360
99573
  <div class="wf-wrap">
99361
99574
  <svg viewBox="0 0 ${WIDTH} ${HEIGHT}" preserveAspectRatio="xMinYMin meet" class="wf-svg">
99362
99575
  ${tickEls}
@@ -100084,8 +100297,9 @@ function renderNetworkPanel(run) {
100084
100297
  return `<div class="empty">No network requests captured.</div>`;
100085
100298
  }
100086
100299
  const report = buildCacheReport(candEntries, baseUrl);
100087
- return `${renderWaterfallsSection(perPage)}${renderNetworkTable(report)}`;
100300
+ return `${renderWaterfallsSection(perPage)}${renderNetworkTable(report, run.id)}`;
100088
100301
  }
100302
+ var NETWORK_TABLE_MAX_ROWS = 500;
100089
100303
  function renderWaterfallsSection(perPage) {
100090
100304
  if (perPage.length === 0)
100091
100305
  return "";
@@ -100111,8 +100325,10 @@ function renderWaterfallsSection(perPage) {
100111
100325
  ${blocks.join("")}
100112
100326
  </div>`;
100113
100327
  }
100114
- function renderNetworkTable(report) {
100115
- const rows = report.all.map((r, idx) => {
100328
+ function renderNetworkTable(report, runId) {
100329
+ const shown = [...report.all].sort((a, b) => Number(a.decision === "hit") - Number(b.decision === "hit") || (b.entry.bytes ?? 0) - (a.entry.bytes ?? 0)).slice(0, NETWORK_TABLE_MAX_ROWS);
100330
+ const hidden = report.all.length - shown.length;
100331
+ const rows = shown.map((r, idx) => {
100116
100332
  const url = r.entry.url;
100117
100333
  const sizeKb = r.entry.bytes != null ? (r.entry.bytes / 1024).toFixed(1) : "—";
100118
100334
  const cacheCls = r.decision === "hit" ? "cache-hit" : r.decision === "miss" || r.decision === "unknown" ? "cache-miss" : "cache-bypass";
@@ -100129,6 +100345,7 @@ function renderNetworkTable(report) {
100129
100345
  <div class="card">
100130
100346
  <h2>Network · ${report.total} requests · ${(report.totalBytes / 1024).toFixed(0)} KB</h2>
100131
100347
  <div class="hint">Hits, misses and categories per request captured in cand. Click a column header to sort.</div>
100348
+ ${hidden > 0 ? `<div class="hint net-capped">Showing ${shown.length} of ${report.all.length} requests (non-hits first, heaviest first) · +${hidden} more in report.json: <code>parity report ${escapeHtml(runId)} --section network --json</code></div>` : ""}
100132
100349
  <div class="net-toolbar">
100133
100350
  <input id="net-search" type="search" placeholder="filter by URL…" class="net-input"/>
100134
100351
  <select id="net-filter-cat" class="net-input">
@@ -101766,7 +101983,7 @@ import chalk14 from "chalk";
101766
101983
  // src/server/cockpit.ts
101767
101984
  import { readFileSync as readFileSync23 } from "node:fs";
101768
101985
  import { createServer as createServer2 } from "node:http";
101769
- import { dirname as dirname5, join as join24, resolve as resolve10 } from "node:path";
101986
+ import { dirname as dirname6, join as join24, resolve as resolve10 } from "node:path";
101770
101987
 
101771
101988
  // src/server/cockpit-actions.ts
101772
101989
  import { spawn as spawn2 } from "node:child_process";
@@ -102810,13 +103027,13 @@ import {
102810
103027
  readdirSync as readdirSync5,
102811
103028
  realpathSync,
102812
103029
  renameSync as renameSync2,
102813
- rmSync,
103030
+ rmSync as rmSync2,
102814
103031
  statSync,
102815
103032
  symlinkSync,
102816
103033
  unlinkSync as unlinkSync3,
102817
103034
  writeFileSync as writeFileSync20
102818
103035
  } from "node:fs";
102819
- import { dirname as dirname4, join as join22, resolve as resolve8 } from "node:path";
103036
+ import { dirname as dirname5, join as join22, resolve as resolve8 } from "node:path";
102820
103037
  import { fileURLToPath } from "node:url";
102821
103038
  var VIEWPORT = {
102822
103039
  mobile: { width: 412, height: 839 },
@@ -102831,7 +103048,7 @@ function validTaskId(id) {
102831
103048
  return /^[\w-]{6,64}$/.test(id);
102832
103049
  }
102833
103050
  function pluginDir() {
102834
- const root = resolve8(dirname4(fileURLToPath(import.meta.url)), "../../../..");
103051
+ const root = resolve8(dirname5(fileURLToPath(import.meta.url)), "../../../..");
102835
103052
  return existsSync17(join22(root, ".claude-plugin", "plugin.json")) ? root : null;
102836
103053
  }
102837
103054
  function targetDir(planDir) {
@@ -102840,7 +103057,7 @@ function targetDir(planDir) {
102840
103057
  if (typeof state?.target?.dir === "string" && existsSync17(state.target.dir))
102841
103058
  return state.target.dir;
102842
103059
  } catch {}
102843
- return dirname4(resolve8(planDir));
103060
+ return dirname5(resolve8(planDir));
102844
103061
  }
102845
103062
  function withPath(base, path) {
102846
103063
  try {
@@ -103630,7 +103847,7 @@ function autoMergePrs(planDir) {
103630
103847
  writeFileSync20(join22(dir, "pr-merge.json"), JSON.stringify({ at, ok: false, error: err.message.split(`
103631
103848
  `)[0] }));
103632
103849
  }
103633
- rmSync(join22(dir, "pr.json"), { force: true });
103850
+ rmSync2(join22(dir, "pr.json"), { force: true });
103634
103851
  } else if (pr.checks.failed > 0 && !existsSync17(join22(dir, "ci-retry.json"))) {
103635
103852
  writeFileSync20(join22(dir, "ci-retry.json"), JSON.stringify({ at, failing: pr.checks.failing }));
103636
103853
  retryTask(planDir, t.id, `CI failed on PR #${pr.number}: ${pr.checks.failing.join(", ")}.${waivers.length ? ` Not waivable: ${waivers.filter((w) => !w.waived).map((w) => w.why).join("; ")}.` : ""} Read the failing job logs, fix on the same branch, push, wait for every check, then merge.`);
@@ -103653,7 +103870,7 @@ function prInfo(branch, repo, dir, ended, fresh = false) {
103653
103870
  encoding: "utf8",
103654
103871
  timeout: 1e4,
103655
103872
  stdio: ["ignore", "pipe", "ignore"],
103656
- env: { ...process.env, ...ghEnv(getSettings(dirname4(dirname4(dir))).githubUser) }
103873
+ env: { ...process.env, ...ghEnv(getSettings(dirname5(dirname5(dir))).githubUser) }
103657
103874
  });
103658
103875
  const j = JSON.parse(out);
103659
103876
  info = {
@@ -103847,7 +104064,7 @@ function readTask(planDir, id) {
103847
104064
  const branch = verdict?.branch ?? fr.branch ?? null;
103848
104065
  let delivery = null;
103849
104066
  if (branch) {
103850
- const repo = task.worktree && existsSync17(task.worktree) ? task.worktree : targetDir(dirname4(dirname4(dir)));
104067
+ const repo = task.worktree && existsSync17(task.worktree) ? task.worktree : targetDir(dirname5(dirname5(dir)));
103851
104068
  const baseSha = task.base?.sha ?? fr.base;
103852
104069
  const git = (...a) => {
103853
104070
  try {
@@ -104452,7 +104669,7 @@ function targetDirOf(planDir) {
104452
104669
  if (typeof st?.target?.dir === "string")
104453
104670
  return st.target.dir;
104454
104671
  } catch {}
104455
- return dirname5(resolve10(planDir));
104672
+ return dirname6(resolve10(planDir));
104456
104673
  }
104457
104674
 
104458
104675
  // src/commands/cockpit.ts
@@ -104768,7 +104985,7 @@ async function contentFreshnessCommand(opts) {
104768
104985
 
104769
104986
  // src/commands/css-modules.ts
104770
104987
  import { readFileSync as readFileSync24, readdirSync as readdirSync6 } from "node:fs";
104771
- import { basename as basename3, dirname as dirname6, join as join25, resolve as resolve12 } from "node:path";
104988
+ import { basename as basename3, dirname as dirname7, join as join25, resolve as resolve12 } from "node:path";
104772
104989
  import chalk18 from "chalk";
104773
104990
  var SKIP_DIRS2 = new Set(["node_modules", ".git", ".next", ".faststore", "dist", "build"]);
104774
104991
  var MODULE_RE = /\.module\.(scss|sass|css)$/;
@@ -104796,7 +105013,7 @@ function scanCssModules(root) {
104796
105013
  scan.modules++;
104797
105014
  const classes = declaredClasses(readFileSync24(mod, "utf8"));
104798
105015
  const modName = basename3(mod);
104799
- for (const file of components.filter((c) => dirname6(c) === dirname6(mod))) {
105016
+ for (const file of components.filter((c) => dirname7(c) === dirname7(mod))) {
104800
105017
  const src = readFileSync24(file, "utf8");
104801
105018
  const imp = src.match(new RegExp(`import\\s+(\\w+)\\s+from\\s+["'][^"']*${modName.replace(/\./g, "\\.")}["']`));
104802
105019
  if (!imp)
@@ -107970,6 +108187,7 @@ async function runFlow(flow, ctx) {
107970
108187
  }
107971
108188
  }
107972
108189
  function finalize(flow, ctx, pages, steps, start) {
108190
+ rememberDedicatedCaptures(flow, ctx.ctx, pages);
107973
108191
  return {
107974
108192
  flow,
107975
108193
  side: ctx.side,
@@ -108010,13 +108228,14 @@ async function validateSelectors(page, selectors) {
108010
108228
  }
108011
108229
 
108012
108230
  // src/engine/selector-discovery-pass.ts
108013
- async function fetchHomeHtml(url, viewport = "desktop") {
108231
+ async function fetchHomeHtml(url, viewport = "desktop", extraHeaders = {}) {
108014
108232
  try {
108015
108233
  const res = await fetch(url, {
108016
108234
  headers: {
108017
108235
  "User-Agent": userAgentFor(viewport),
108018
108236
  Accept: "text/html,application/xhtml+xml",
108019
- "Accept-Language": "pt-BR,pt;q=0.9,en;q=0.8"
108237
+ "Accept-Language": "pt-BR,pt;q=0.9,en;q=0.8",
108238
+ ...extraHeaders
108020
108239
  },
108021
108240
  redirect: "follow"
108022
108241
  });
@@ -108305,7 +108524,7 @@ async function e2eCommand(opts) {
108305
108524
  const ignore = loadParityIgnore();
108306
108525
  const learned = loadLearned();
108307
108526
  const learnedBefore = JSON.stringify(learned);
108308
- const host = hostOf2(opts.url);
108527
+ const host = hostOf3(opts.url);
108309
108528
  const primaryViewport = viewports[0] ?? "mobile";
108310
108529
  const failOn = (opts.failOn || "critical,high").split(",").map((s) => s.trim()).filter(Boolean);
108311
108530
  const runId = newRunId();
@@ -108613,7 +108832,7 @@ async function collectFlowVideos(flowVideos, videosDir, viewport) {
108613
108832
  entry.cap.videoPaths = paths;
108614
108833
  }
108615
108834
  }
108616
- function hostOf2(url) {
108835
+ function hostOf3(url) {
108617
108836
  try {
108618
108837
  return new URL(url).hostname;
108619
108838
  } catch {
@@ -108675,11 +108894,11 @@ import chalk20 from "chalk";
108675
108894
 
108676
108895
  // src/events.ts
108677
108896
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync16 } from "node:fs";
108678
- import { dirname as dirname7, join as join28 } from "node:path";
108897
+ import { dirname as dirname8, join as join28 } from "node:path";
108679
108898
  function emitEvent(dir, type, data = {}) {
108680
108899
  try {
108681
108900
  const file = join28(dir, "events.jsonl");
108682
- mkdirSync16(dirname7(file), { recursive: true });
108901
+ mkdirSync16(dirname8(file), { recursive: true });
108683
108902
  const event = { ts: new Date().toISOString(), type, ...data };
108684
108903
  appendFileSync2(file, `${JSON.stringify(event)}
108685
108904
  `);
@@ -110159,7 +110378,7 @@ function formatPatch(patch) {
110159
110378
 
110160
110379
  // src/commands/ios.ts
110161
110380
  import { execFileSync as execFileSync4 } from "node:child_process";
110162
- import { existsSync as existsSync21, mkdirSync as mkdirSync20, readFileSync as readFileSync27, rmSync as rmSync2, writeFileSync as writeFileSync26 } from "node:fs";
110381
+ import { existsSync as existsSync21, mkdirSync as mkdirSync20, readFileSync as readFileSync27, rmSync as rmSync3, writeFileSync as writeFileSync26 } from "node:fs";
110163
110382
  import { homedir as homedir3, tmpdir as tmpdir2 } from "node:os";
110164
110383
  import { join as join32, resolve as resolve15 } from "node:path";
110165
110384
  import chalk25 from "chalk";
@@ -110542,9 +110761,9 @@ async function iosCommand(opts) {
110542
110761
  simctl("shutdown", device.udid);
110543
110762
  } catch {}
110544
110763
  }
110545
- rmSync2(scratch, { recursive: true, force: true });
110764
+ rmSync3(scratch, { recursive: true, force: true });
110546
110765
  if (existsSync21(LOCK) && Number(readFileSync27(LOCK, "utf8")) === process.pid)
110547
- rmSync2(LOCK);
110766
+ rmSync3(LOCK);
110548
110767
  }
110549
110768
  const missing = Object.entries(found).filter(([, v]) => v !== true).map(([k]) => k);
110550
110769
  let diff = null;
@@ -110663,7 +110882,8 @@ async function journeyCommand(opts) {
110663
110882
  platform,
110664
110883
  recoveryBudget: 3,
110665
110884
  onStep: onStepFor(viewport, side),
110666
- acceptProdQuirks: opts.acceptProdQuirks
110885
+ acceptProdQuirks: opts.acceptProdQuirks,
110886
+ beforeShots: true
110667
110887
  });
110668
110888
  return cap;
110669
110889
  } finally {
@@ -111668,11 +111888,11 @@ import { resolve as resolve17 } from "node:path";
111668
111888
 
111669
111889
  // src/util/version.ts
111670
111890
  import { readFileSync as readFileSync29 } from "node:fs";
111671
- import { dirname as dirname8, resolve as resolve16 } from "node:path";
111891
+ import { dirname as dirname9, resolve as resolve16 } from "node:path";
111672
111892
  import { fileURLToPath as fileURLToPath2 } from "node:url";
111673
111893
  function getPackageVersion() {
111674
111894
  try {
111675
- const here = dirname8(fileURLToPath2(import.meta.url));
111895
+ const here = dirname9(fileURLToPath2(import.meta.url));
111676
111896
  for (const up of ["..", "../..", "../../.."]) {
111677
111897
  try {
111678
111898
  const pkgPath = resolve16(here, up, "package.json");
@@ -112064,7 +112284,7 @@ async function mcpCommand(opts) {
112064
112284
  }
112065
112285
 
112066
112286
  // src/commands/migrate.ts
112067
- import { existsSync as existsSync28, mkdirSync as mkdirSync22, readFileSync as readFileSync35, rmSync as rmSync3, writeFileSync as writeFileSync31 } from "node:fs";
112287
+ import { existsSync as existsSync28, mkdirSync as mkdirSync22, readFileSync as readFileSync35, rmSync as rmSync4, writeFileSync as writeFileSync31 } from "node:fs";
112068
112288
  import { relative as relative5, resolve as resolve19 } from "node:path";
112069
112289
  import chalk31 from "chalk";
112070
112290
  import open2 from "open";
@@ -114456,13 +114676,13 @@ async function captureViewportVariants(browser, url, extraViewports, captured, r
114456
114676
  const dir = resolve19(componentDir, vp);
114457
114677
  const d = deltas.find((x) => x.viewport === vp);
114458
114678
  if (!d || d.absent || d.failed)
114459
- rmSync3(dir, { recursive: true, force: true });
114679
+ rmSync4(dir, { recursive: true, force: true });
114460
114680
  if (!d)
114461
114681
  continue;
114462
114682
  if (d.html !== undefined)
114463
114683
  writeFileSync31(resolve19(dir, "component.html"), d.html, "utf8");
114464
114684
  if (!d.keepScreenshot)
114465
- rmSync3(resolve19(dir, "screenshot.png"), { force: true });
114685
+ rmSync4(resolve19(dir, "screenshot.png"), { force: true });
114466
114686
  variants.push({
114467
114687
  viewport: vp,
114468
114688
  ...d.absent ? { absent: true } : {},
@@ -115673,7 +115893,7 @@ import { join as join45 } from "node:path";
115673
115893
  import chalk35 from "chalk";
115674
115894
 
115675
115895
  // src/commands/run.ts
115676
- import { existsSync as existsSync29, readFileSync as readFileSync38 } from "node:fs";
115896
+ import { existsSync as existsSync29, readFileSync as readFileSync38, rmSync as rmSync5 } from "node:fs";
115677
115897
  import { join as join44 } from "node:path";
115678
115898
  import chalk34 from "chalk";
115679
115899
  import ora8 from "ora";
@@ -115772,113 +115992,6 @@ function readLine2(prompt) {
115772
115992
  });
115773
115993
  }
115774
115994
 
115775
- // src/llm/aggregate-issues.ts
115776
- init_client();
115777
- var REPORT_ISSUES_TOOL = {
115778
- name: "report_issues",
115779
- description: "Report a prioritized list of aggregated issues from the parity run.",
115780
- input_schema: {
115781
- type: "object",
115782
- properties: {
115783
- issues: {
115784
- type: "array",
115785
- items: {
115786
- type: "object",
115787
- properties: {
115788
- id: { type: "string" },
115789
- severity: { type: "string", enum: ["critical", "high", "medium", "low"] },
115790
- category: {
115791
- type: "string",
115792
- enum: ["functional", "visual", "performance", "seo", "console", "network"]
115793
- },
115794
- page: { type: "string" },
115795
- check: { type: "string" },
115796
- summary: { type: "string" },
115797
- details: { type: "string" },
115798
- reproduction: { type: "string" },
115799
- suggestedFix: { type: "string" }
115800
- },
115801
- required: ["id", "severity", "category", "check", "summary"]
115802
- }
115803
- }
115804
- },
115805
- required: ["issues"]
115806
- }
115807
- };
115808
- async function aggregateIssues(input) {
115809
- if (!isLlmAvailable())
115810
- return fallbackAggregate(input);
115811
- const failedChecks = input.checks.filter((c) => c.status === "fail" || c.status === "warn");
115812
- if (failedChecks.length === 0)
115813
- return [];
115814
- const rawIssues = input.checks.flatMap((c) => c.issues);
115815
- const userContent = JSON.stringify({
115816
- run: {
115817
- id: input.runId,
115818
- prod: input.prodUrl,
115819
- cand: input.candUrl,
115820
- viewports: input.viewports,
115821
- flows: input.flows
115822
- },
115823
- checks_summary: failedChecks.map((c) => ({
115824
- name: c.name,
115825
- status: c.status,
115826
- severity: c.severity,
115827
- summary: c.summary,
115828
- issueCount: c.issues.length,
115829
- data: c.data
115830
- })),
115831
- raw_issues: rawIssues.map((i) => ({
115832
- id: i.id,
115833
- severity: i.severity,
115834
- category: i.category,
115835
- page: i.page,
115836
- check: i.check,
115837
- summary: i.summary,
115838
- details: i.details
115839
- }))
115840
- }, null, 2);
115841
- const parsed = await callTool({
115842
- feature: "issue-aggregation",
115843
- systemPrompt: ISSUE_AGGREGATOR_SYSTEM_PROMPT,
115844
- userText: `Analise os resultados abaixo e produza issues priorizadas via report_issues.
115845
-
115846
- ${userContent}`,
115847
- maxTokens: 4096,
115848
- timeoutMs: input.timeoutMs,
115849
- tool: {
115850
- name: REPORT_ISSUES_TOOL.name,
115851
- description: REPORT_ISSUES_TOOL.description,
115852
- inputSchema: REPORT_ISSUES_TOOL.input_schema
115853
- }
115854
- });
115855
- if (!parsed)
115856
- return fallbackAggregate(input);
115857
- return (parsed.issues ?? []).filter((i) => i.id && i.severity && i.category && i.check && i.summary).map((i) => ({
115858
- id: i.id,
115859
- severity: i.severity,
115860
- category: i.category,
115861
- page: i.page,
115862
- check: i.check,
115863
- summary: i.summary,
115864
- details: i.details,
115865
- reproduction: i.reproduction,
115866
- suggestedFix: i.suggestedFix,
115867
- evidence: []
115868
- }));
115869
- }
115870
- function fallbackAggregate(input) {
115871
- const seen = new Map;
115872
- for (const c of input.checks) {
115873
- for (const i of c.issues) {
115874
- if (!seen.has(i.id))
115875
- seen.set(i.id, i);
115876
- }
115877
- }
115878
- const order = { critical: 0, high: 1, medium: 2, low: 3 };
115879
- return [...seen.values()].sort((a, b) => order[a.severity] - order[b.severity]).slice(0, 10);
115880
- }
115881
-
115882
115995
  // src/commands/run.ts
115883
115996
  init_client();
115884
115997
 
@@ -116134,6 +116247,28 @@ function detectRunCaveats(input) {
116134
116247
  detail: `Os dois lados não estão no mesmo conteúdo (${mismatched.slice(0, 3).join(", ")}${mismatched.length > 3 ? "…" : ""}). O módulo visual vai apontar diferenças que são de produto, não de migração — leia estrutura e hierarquia, não conteúdo.`
116135
116248
  });
116136
116249
  }
116250
+ for (const side of ["prod", "cand"]) {
116251
+ const mix = describeMix(stackCounts(side === "prod" ? input.prodPages : input.candPages, captureKey));
116252
+ if (!mix)
116253
+ continue;
116254
+ out.push({
116255
+ id: `${side}-mixed-variants`,
116256
+ level: "warn",
116257
+ summary: `${side} served mixed variants: ${mix} — pin with --${side}-cookie/--${side}-header`,
116258
+ detail: `${side} answered with more than one build in this run (an A/B split between stacks), so its pages are not one reference. Script counts, network volume and vitals of pairs served by different stacks were marked inconclusive. Ask the site owner for the bucket/fallback cookie or header that forces one build, and pass it with --${side}-cookie name=value or --${side}-header "Name: value".`
116259
+ });
116260
+ }
116261
+ if (!input.prodPinned && !out.some((c) => c.id === "prod-mixed-variants")) {
116262
+ const abCookies = new Set(input.prodPages.flatMap((p) => (p.variant?.signals ?? []).filter((s) => s.startsWith("cookie:")).map((s) => s.slice(7))));
116263
+ if (abCookies.size > 0) {
116264
+ out.push({
116265
+ id: "prod-ab-unpinned",
116266
+ level: "info",
116267
+ summary: `prod sets A/B cookie(s) ${[...abCookies].join(", ")} and no variant was pinned`,
116268
+ detail: "Every page here came from one build, but which one was the bucket each fresh context drew. If prod is splitting traffic between builds, pin the reference with --prod-cookie/--prod-header."
116269
+ });
116270
+ }
116271
+ }
116137
116272
  if (!input.llmEnabled) {
116138
116273
  out.push({
116139
116274
  id: "llm-disabled",
@@ -116184,6 +116319,42 @@ function pathOf6(raw) {
116184
116319
  }
116185
116320
  }
116186
116321
 
116322
+ // src/engine/side-pin.ts
116323
+ function parseHeaderFlags(values) {
116324
+ const out = {};
116325
+ for (const v of values ?? []) {
116326
+ const colon = v.indexOf(":");
116327
+ const name = colon > 0 ? v.slice(0, colon).trim() : "";
116328
+ if (!name)
116329
+ throw new Error('header pin expects "Name: value"');
116330
+ out[name] = v.slice(colon + 1).trim();
116331
+ }
116332
+ return out;
116333
+ }
116334
+ function resolveSidePin(url, fromRc, cookieFlags, headerFlags) {
116335
+ const cookies = parseCookieFlags([...fromRc?.cookies ?? [], ...cookieFlags ?? []], url);
116336
+ return {
116337
+ cookies: [...new Map(cookies.map((c) => [c.name, c])).values()],
116338
+ headers: parseHeaderFlags([...fromRc?.headers ?? [], ...headerFlags ?? []])
116339
+ };
116340
+ }
116341
+ function isEmptyPin(pin) {
116342
+ return pin.cookies.length === 0 && Object.keys(pin.headers).length === 0;
116343
+ }
116344
+ function pinFetchHeaders(pin) {
116345
+ const cookie = pin.cookies.map((c) => `${c.name}=${c.value}`).join("; ");
116346
+ return { ...pin.headers, ...cookie ? { Cookie: cookie } : {} };
116347
+ }
116348
+ function pinNames(pin) {
116349
+ return { cookies: pin.cookies.map((c) => c.name), headers: Object.keys(pin.headers) };
116350
+ }
116351
+ function describePin(pin) {
116352
+ return [
116353
+ ...pin.cookies.map((c) => `cookie ${c.name}=***`),
116354
+ ...Object.keys(pin.headers).map((h) => `header ${h}: ***`)
116355
+ ].join(", ");
116356
+ }
116357
+
116187
116358
  // src/util/timing.ts
116188
116359
  async function withTiming(fn) {
116189
116360
  const start = performance.now();
@@ -116434,6 +116605,22 @@ async function runCommand(rawOpts) {
116434
116605
  if (rawOpts.preset) {
116435
116606
  console.log(chalk34.dim(` preset: ${rawOpts.preset}`));
116436
116607
  }
116608
+ let pins;
116609
+ try {
116610
+ const pinRc = loadParityRc().pin;
116611
+ pins = {
116612
+ prod: resolveSidePin(opts.prod, pinRc?.prod, opts.prodCookie, opts.prodHeader),
116613
+ cand: resolveSidePin(opts.cand, pinRc?.cand, opts.candCookie, opts.candHeader)
116614
+ };
116615
+ } catch (err) {
116616
+ console.error(chalk34.red(` ${err.message}`));
116617
+ return 2;
116618
+ }
116619
+ for (const side of ["prod", "cand"]) {
116620
+ if (!isEmptyPin(pins[side]))
116621
+ console.log(chalk34.dim(` ${side} pinned: ${describePin(pins[side])}`));
116622
+ }
116623
+ const pinContext = (side) => ({ cookies: pins[side].cookies, headers: pins[side].headers });
116437
116624
  if (opts.pt)
116438
116625
  setLlmLanguage("pt");
116439
116626
  if (opts.interactive === false)
@@ -116460,7 +116647,7 @@ async function runCommand(rawOpts) {
116460
116647
  profile = opts.profile;
116461
116648
  } else {
116462
116649
  const pv = opts.viewports.split(",")[0]?.trim() || "mobile";
116463
- earlyProdHtml = await fetchHomeHtml(opts.prod, pv);
116650
+ earlyProdHtml = await fetchHomeHtml(opts.prod, pv, pinFetchHeaders(pins.prod));
116464
116651
  profile = earlyProdHtml ? detectSiteProfile({ url: opts.prod, html: earlyProdHtml }) : "commerce";
116465
116652
  }
116466
116653
  const isContentProfile = profile === "content";
@@ -116524,22 +116711,16 @@ async function runCommand(rawOpts) {
116524
116711
  rc.addToCartConfirmMs = opts.addToCartTimeout;
116525
116712
  }
116526
116713
  const ignore = loadParityIgnore();
116527
- const llmTimeoutRaw = opts.llmTimeout ?? 60;
116528
- if (!Number.isFinite(llmTimeoutRaw)) {
116529
- console.error(chalk34.red(` --llm-timeout inválido: "${opts.llmTimeout}" não é um número`));
116530
- return 2;
116531
- }
116532
- const llmTimeoutSec = Math.max(5, Math.floor(llmTimeoutRaw));
116533
116714
  if (isLlmAvailable()) {
116534
- console.log(chalk34.dim(` llm: ${providerLabel()} (timeout=${llmTimeoutSec}s)`));
116715
+ console.log(chalk34.dim(` llm: ${providerLabel()}`));
116535
116716
  } else {
116536
- console.log(chalk34.dim(" llm: offline (LLM keys ausentes — agregação heurística)"));
116717
+ console.log(chalk34.dim(" llm: offline (LLM keys ausentes — selector discovery pulado)"));
116537
116718
  }
116538
116719
  if (isInteractiveMode()) {
116539
116720
  console.log(chalk34.dim(" interactive: enabled — TTY + no LLM. Missing selectors will pause to prompt (disable with --no-interactive). Issue #72."));
116540
116721
  }
116541
116722
  const primaryViewport = viewports[0] ?? "mobile";
116542
- const preflight = await preflightCheck(opts.prod, opts.cand, primaryViewport);
116723
+ const preflight = await preflightCheck(opts.prod, opts.cand, primaryViewport, pins);
116543
116724
  if (!preflight.ok) {
116544
116725
  console.error(chalk34.red(`
116545
116726
  ✖ pre-flight falhou:`));
@@ -116552,14 +116733,14 @@ async function runCommand(rawOpts) {
116552
116733
  const learned = loadLearned();
116553
116734
  const learnedBefore = JSON.stringify(learned);
116554
116735
  let platform = "custom";
116555
- const prodHomeHtml = earlyProdHtml ?? await fetchHomeHtml(opts.prod, primaryViewport);
116736
+ const prodHomeHtml = earlyProdHtml ?? await fetchHomeHtml(opts.prod, primaryViewport, pinFetchHeaders(pins.prod));
116556
116737
  if (prodHomeHtml) {
116557
116738
  platform = detectPlatform({ url: opts.prod, html: prodHomeHtml });
116558
116739
  if (platform !== "custom") {
116559
116740
  console.log(chalk34.dim(` Detected platform: ${platform}`));
116560
116741
  }
116561
116742
  }
116562
- const prodHost = hostOf3(opts.prod);
116743
+ const prodHost = hostOf4(opts.prod);
116563
116744
  let promotedCount = 0;
116564
116745
  let deprecatedCount = 0;
116565
116746
  const wantsAutoSelectors = opts.autoSelectors !== false && isLlmAvailable();
@@ -116664,11 +116845,10 @@ async function runCommand(rawOpts) {
116664
116845
  partialReason: `${reason} during ${currentPhase}`,
116665
116846
  timings: partialTimings
116666
116847
  });
116667
- writeRunReportJson(paths.runDir, partial);
116668
- const html = renderHtmlReport(partial, paths.runDir);
116669
- writeRunReportHtml(paths.runDir, html);
116670
- process.stderr.write(` report parcial em ${paths.reportHtml}
116671
- `);
116848
+ const where = writeRunReport(paths, partial, Boolean(opts.html || opts.open));
116849
+ process.stderr.write(` report parcial:
116850
+ ${where.map((l) => ` ${l}
116851
+ `).join("")}`);
116672
116852
  process.stderr.write(`
116673
116853
  ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
116674
116854
  `);
@@ -116702,13 +116882,14 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
116702
116882
  const warmupSpinner = ora8("Warmup: bustando cache em prod + cand…").start();
116703
116883
  const result = await warmupTargets({
116704
116884
  urls: [opts.prod, opts.cand],
116885
+ headersFor: [pinFetchHeaders(pins.prod), pinFetchHeaders(pins.cand)],
116705
116886
  viewports,
116706
116887
  bypassCache: opts.bypassCache !== false
116707
116888
  });
116708
116889
  if (result.failed.length === 0) {
116709
116890
  warmupSpinner.succeed(`Warmup ok — ${result.succeeded}/${result.attempted} workers serviram resposta fresca`);
116710
116891
  } else if (result.succeeded > 0) {
116711
- const failureSummary = result.failed.slice(0, 3).map((f) => `${f.viewport}/${hostOf3(f.url)} (${f.reason})`).join("; ");
116892
+ const failureSummary = result.failed.slice(0, 3).map((f) => `${f.viewport}/${hostOf4(f.url)} (${f.reason})`).join("; ");
116712
116893
  warmupSpinner.warn(`Warmup parcial — ${result.succeeded}/${result.attempted} ok; ${result.failed.length} falha(s): ${failureSummary}`);
116713
116894
  } else {
116714
116895
  const firstReason = result.failed[0]?.reason ?? "unknown";
@@ -116718,14 +116899,16 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
116718
116899
  const traceEnabled = process.env.PARITY_TRACE === "1";
116719
116900
  const runOneSide = async (viewport, side) => {
116720
116901
  const baseUrl = side === "prod" ? opts.prod : opts.cand;
116721
- const harPath = join44(paths.harDir, `${viewport}-${side}.har`);
116902
+ const harEnabled = process.env.PARITY_HAR === "1";
116903
+ const harPath = harEnabled ? join44(paths.harDir, `${viewport}-${side}.har`) : undefined;
116722
116904
  const tracePath = traceEnabled ? join44(paths.tracesDir, `${viewport}-${side}.zip`) : null;
116723
116905
  const ctx = await newContext(browser, {
116724
116906
  viewport,
116725
116907
  harPath,
116726
116908
  tracesDir: traceEnabled ? paths.tracesDir : undefined,
116727
116909
  cohortCookieValue: "control",
116728
- noCache: opts.bypassCache
116910
+ noCache: opts.bypassCache,
116911
+ ...pinContext(side)
116729
116912
  });
116730
116913
  setVitalsWarm(ctx, vitalsWarm);
116731
116914
  await installVitalsCollector(ctx);
@@ -116898,7 +117081,8 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
116898
117081
  viewport: task.viewport,
116899
117082
  cohortCookieValue: "control",
116900
117083
  noCache: opts.bypassCache,
116901
- keepMotion: true
117084
+ keepMotion: true,
117085
+ ...pinContext(task.side)
116902
117086
  });
116903
117087
  setVitalsWarm(c, vitalsWarm);
116904
117088
  return c;
@@ -117007,7 +117191,8 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
117007
117191
  cohortCookieValue: "control",
117008
117192
  noCache: opts.bypassCache,
117009
117193
  deviceScaleFactor: 1,
117010
- hideScrollbars: true
117194
+ hideScrollbars: true,
117195
+ ...pinContext(task.side)
117011
117196
  });
117012
117197
  setVitalsWarm(ctx, vitalsWarm);
117013
117198
  await installVitalsCollector(ctx);
@@ -117075,6 +117260,12 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
117075
117260
  checksHb.stop();
117076
117261
  stampPhase("checks");
117077
117262
  spinner.succeed(`Checks concluídos (${checks.length})`);
117263
+ if (process.env.PARITY_KEEP_ARTIFACTS !== "1") {
117264
+ for (const probe of visualProbes.values()) {
117265
+ if (probe.repeatScreenshot)
117266
+ rmSync5(probe.repeatScreenshot, { force: true });
117267
+ }
117268
+ }
117078
117269
  if (jsonl) {
117079
117270
  for (const c of checks)
117080
117271
  jsonl.write(checkToJsonl(runId, c));
@@ -117083,24 +117274,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
117083
117274
  const acceptance = applyAcceptedFindings(checks, ignore.expectedDivergences ?? []);
117084
117275
  const remainingChecks = withoutAccepted(checks);
117085
117276
  const remainingIssues = remainingChecks.flatMap((c) => c.issues);
117086
- currentPhase = "llm-aggregate";
117087
- setSpinnerLabel(isLlmAvailable() ? `Agregando issues via LLM (${providerLabel()}, timeout=${llmTimeoutSec}s)…` : "Agregando issues (modo offline — sem LLM keys)…");
117088
- spinner.start();
117089
- const llmHb = attachSpinnerHeartbeat(spinner, {
117090
- baseText: isLlmAvailable() ? "Agregando issues via LLM (Sonnet 4.6)…" : "Agregando issues (modo offline)…"
117091
- });
117092
- const topIssues = await aggregateIssues({
117093
- runId,
117094
- prodUrl: opts.prod,
117095
- candUrl: opts.cand,
117096
- viewports,
117097
- flows,
117098
- checks: remainingChecks,
117099
- timeoutMs: llmTimeoutSec * 1000
117100
- });
117101
- llmHb.stop();
117102
- stampPhase("llm-aggregate");
117103
- spinner.succeed(`${topIssues.length} issue(s) priorizada(s)`);
117277
+ const topIssues = rankTopIssues(remainingIssues);
117104
117278
  currentPhase = "report";
117105
117279
  const pagesAnalyzed = pairCaptures(checkCtx.prodPages, checkCtx.candPages).pairs.length;
117106
117280
  const scoreOf = (c, i) => {
@@ -117199,14 +117373,14 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
117199
117373
  candPages: checkCtx.candPages,
117200
117374
  verdict,
117201
117375
  llmEnabled: llmStillAvailable,
117202
- candIsProduction: opts.candIsProduction
117376
+ candIsProduction: opts.candIsProduction,
117377
+ prodPinned: !isEmptyPin(pins.prod)
117203
117378
  })),
117379
+ pinned: isEmptyPin(pins.prod) && isEmptyPin(pins.cand) ? undefined : { prod: pinNames(pins.prod), cand: pinNames(pins.cand) },
117204
117380
  pagePairs
117205
117381
  };
117206
117382
  const reportStart = performance.now();
117207
- writeRunReportJson(paths.runDir, run);
117208
- const html = renderHtmlReport(run, paths.runDir);
117209
- writeRunReportHtml(paths.runDir, html);
117383
+ const reportWhere = writeRunReport(paths, run, Boolean(opts.html || opts.open));
117210
117384
  const reportDurationMs = performance.now() - reportStart;
117211
117385
  runTimings.phases.push({ phase: "report", durationMs: reportDurationMs });
117212
117386
  runTimings.totalMs += reportDurationMs;
@@ -117220,7 +117394,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
117220
117394
  totalIssues: allIssues.length,
117221
117395
  verdict: { status: verdict.status, score: verdict.score, scoreVersion: SCORE_VERSION }
117222
117396
  });
117223
- printSummary8(run, paths.reportHtml, { promotedCount, deprecatedCount, platform });
117397
+ printSummary8(run, reportWhere, { promotedCount, deprecatedCount, platform });
117224
117398
  console.log(`
117225
117399
  ${formatTimingsSummary(runTimings, buildFlowBreakdown(allFlowCaptures))}`);
117226
117400
  if (pagePairs) {
@@ -117229,6 +117403,7 @@ ${formatTimingsSummary(runTimings, buildFlowBreakdown(allFlowCaptures))}`);
117229
117403
  ${formatPagePairTable(pagePairs)}`);
117230
117404
  const missed = pagePairs.filter((p) => !p.match).length;
117231
117405
  if (missed > 0) {
117406
+ pruneOldRuns(opts, runId);
117232
117407
  console.log(chalk34.red(`
117233
117408
  ✖ ${missed}/${pagePairs.length} requested page pair(s) were not measured as requested — this report describes other pages; fix the URLs or the capture`));
117234
117409
  }
@@ -117267,6 +117442,30 @@ ${formatPagePairTable(pagePairs)}`);
117267
117442
  jsonl?.close();
117268
117443
  }
117269
117444
  }
117445
+ function pruneOldRuns(opts, runId) {
117446
+ const keep = opts.keepRuns ?? 10;
117447
+ if (!Number.isFinite(keep) || keep <= 0)
117448
+ return;
117449
+ const protect = new Set([runId]);
117450
+ for (const b of listBaselines()) {
117451
+ try {
117452
+ protect.add(JSON.parse(readFileSync38(b.path, "utf8")).fromRunId);
117453
+ } catch {}
117454
+ }
117455
+ try {
117456
+ const pruned = pruneRuns(opts.output, {
117457
+ prodUrl: opts.prod,
117458
+ candUrl: opts.cand,
117459
+ keep,
117460
+ protect
117461
+ });
117462
+ if (pruned.length > 0) {
117463
+ console.log(chalk34.dim(` --keep-runs ${keep}: removed ${pruned.length} older run(s): ${pruned.join(", ")}`));
117464
+ }
117465
+ } catch (err) {
117466
+ console.log(chalk34.yellow(` --keep-runs: pruning skipped (${err.message})`));
117467
+ }
117468
+ }
117270
117469
  function buildPartialRun(args) {
117271
117470
  const allIssues = args.checks.flatMap((c) => c.issues);
117272
117471
  const verdict = computeVerdict(args.checks, allIssues);
@@ -117281,7 +117480,7 @@ function buildPartialRun(args) {
117281
117480
  cep: args.cep,
117282
117481
  durationMs: Date.now() - args.startedAt,
117283
117482
  verdict,
117284
- topIssues: [],
117483
+ topIssues: rankTopIssues(allIssues),
117285
117484
  issues: allIssues,
117286
117485
  checks: args.checks,
117287
117486
  flowCaptures: args.flowCaptures,
@@ -117397,7 +117596,7 @@ async function runWithConcurrency2(items, workers, fn) {
117397
117596
  }
117398
117597
  }));
117399
117598
  }
117400
- async function preflightCheck(prodUrl, candUrl, viewport) {
117599
+ async function preflightCheck(prodUrl, candUrl, viewport, pins) {
117401
117600
  const spinner = ora8("Pre-flight: verificando URLs…").start();
117402
117601
  const errors = [];
117403
117602
  const ua = userAgentFor(viewport);
@@ -117405,8 +117604,11 @@ async function preflightCheck(prodUrl, candUrl, viewport) {
117405
117604
  async function probeWithBrowser(label, url) {
117406
117605
  const ctx = await browser.newContext({
117407
117606
  userAgent: ua,
117408
- ignoreHTTPSErrors: true
117607
+ ignoreHTTPSErrors: true,
117608
+ extraHTTPHeaders: pins[label].headers
117409
117609
  });
117610
+ if (pins[label].cookies.length > 0)
117611
+ await ctx.addCookies(pins[label].cookies);
117410
117612
  const page = await ctx.newPage();
117411
117613
  try {
117412
117614
  const res = await page.goto(url, { waitUntil: "commit", timeout: 30000 });
@@ -117432,7 +117634,7 @@ async function preflightCheck(prodUrl, candUrl, viewport) {
117432
117634
  method: "GET",
117433
117635
  redirect: "follow",
117434
117636
  signal: controller.signal,
117435
- headers: { "User-Agent": ua }
117637
+ headers: { "User-Agent": ua, ...pinFetchHeaders(pins[label]) }
117436
117638
  });
117437
117639
  if (res.status >= 500)
117438
117640
  errors.push(`${label}: HTTP ${res.status} ${res.statusText} (${url})`);
@@ -117478,9 +117680,10 @@ function addCacheBuster(url) {
117478
117680
  }
117479
117681
  }
117480
117682
  async function warmupTargets(opts) {
117481
- const headers = opts.bypassCache ? { "Cache-Control": "no-cache", Pragma: "no-cache" } : {};
117683
+ const noCache = opts.bypassCache ? { "Cache-Control": "no-cache", Pragma: "no-cache" } : {};
117482
117684
  const jobs = [];
117483
- for (const url of opts.urls) {
117685
+ for (const [i, url] of opts.urls.entries()) {
117686
+ const headers = { ...opts.headersFor?.[i], ...noCache };
117484
117687
  for (const viewport of opts.viewports) {
117485
117688
  const ua = userAgentFor(viewport);
117486
117689
  const target = addCacheBuster(url);
@@ -117513,14 +117716,14 @@ function findPdpCapture(flows, side) {
117513
117716
  }
117514
117717
  return;
117515
117718
  }
117516
- function hostOf3(url) {
117719
+ function hostOf4(url) {
117517
117720
  try {
117518
117721
  return new URL(url).hostname;
117519
117722
  } catch {
117520
117723
  return url;
117521
117724
  }
117522
117725
  }
117523
- function printSummary8(run, htmlPath, meta) {
117726
+ function printSummary8(run, reportWhere, meta) {
117524
117727
  const { verdict } = run;
117525
117728
  const inconclusive = verdict.status === "inconclusive";
117526
117729
  const emoji = inconclusive ? chalk34.dim("○") : verdict.status === "pass" ? chalk34.green("✔") : verdict.status === "warn" ? chalk34.yellow("⚠") : chalk34.red("✖");
@@ -117581,9 +117784,18 @@ function printSummary8(run, htmlPath, meta) {
117581
117784
  console.log(chalk34.dim(` \uD83D\uDCDA learned-selectors [${meta.platform}]: ${chalk34.green(`+${meta.promotedCount}`)} promoted · ${chalk34.yellow(meta.deprecatedCount)} deprecated`));
117582
117785
  }
117583
117786
  console.log("");
117584
- console.log(chalk34.dim(` → ${htmlPath}`));
117787
+ for (const line of reportWhere)
117788
+ console.log(chalk34.dim(` ${line}`));
117585
117789
  console.log("");
117586
117790
  }
117791
+ function writeRunReport(paths, run, html) {
117792
+ writeRunReportJson(paths.runDir, run);
117793
+ if (html) {
117794
+ writeRunReportHtml(paths.runDir, renderHtmlReport(run, paths.runDir));
117795
+ return [`→ ${paths.reportHtml}`];
117796
+ }
117797
+ return [`→ ${paths.reportJson}`, `HTML report: parity report ${paths.runDir}`];
117798
+ }
117587
117799
 
117588
117800
  // src/commands/pr.ts
117589
117801
  var SEVERITY_EMOJI = {
@@ -117834,7 +118046,7 @@ function promptCommand(runId, opts) {
117834
118046
 
117835
118047
  // src/commands/qa.ts
117836
118048
  import { existsSync as existsSync35, readFileSync as readFileSync42 } from "node:fs";
117837
- import { basename as basename5, dirname as dirname9, join as join49 } from "node:path";
118049
+ import { basename as basename5, dirname as dirname10, join as join49 } from "node:path";
117838
118050
  import chalk38 from "chalk";
117839
118051
 
117840
118052
  // src/board/sweep-cards.ts
@@ -117848,7 +118060,7 @@ var SEVERITY_RANK6 = {
117848
118060
  medium: 2,
117849
118061
  low: 3
117850
118062
  };
117851
- function hostOf4(url) {
118063
+ function hostOf5(url) {
117852
118064
  try {
117853
118065
  return new URL(url).host;
117854
118066
  } catch {
@@ -117965,7 +118177,7 @@ function evidenceRef(path, run) {
117965
118177
  return `${run.artifactsUrl.replace(/\/$/, "")}/${rel}`;
117966
118178
  }
117967
118179
  function summaryCardTitle(run) {
117968
- return `${QA_PREFIX} Sweep ${hostOf4(run.url)} ${monthOf(run.timestamp)}`;
118180
+ return `${QA_PREFIX} Sweep ${hostOf5(run.url)} ${monthOf(run.timestamp)}`;
117969
118181
  }
117970
118182
  function summaryCardBody(run, filed, belowThreshold) {
117971
118183
  const t = run.totals;
@@ -118172,7 +118384,7 @@ function readSpecs(entries) {
118172
118384
  function evidenceLibraryPath(p, run) {
118173
118385
  const idx = Math.max(p.indexOf("/screenshots/"), p.indexOf("/videos/"));
118174
118386
  const rel = idx >= 0 ? p.slice(idx + 1) : p.split("/").pop() ?? p;
118175
- return `parity-sweep/${hostOf4(run.url)}/${run.runId}/${rel}`;
118387
+ return `parity-sweep/${hostOf5(run.url)}/${run.runId}/${rel}`;
118176
118388
  }
118177
118389
  function cardEvidencePaths(entries) {
118178
118390
  const paths = new Set;
@@ -118982,7 +119194,7 @@ function findPreviousSweep(outputDir, host, excludeRunId) {
118982
119194
  if (r.id === excludeRunId)
118983
119195
  continue;
118984
119196
  const rep = readReport(r.reportPath);
118985
- if (!rep || rep.mode !== "sweep" || hostOf4(rep.url) !== host)
119197
+ if (!rep || rep.mode !== "sweep" || hostOf5(rep.url) !== host)
118986
119198
  continue;
118987
119199
  return { runId: r.id, report: rep };
118988
119200
  }
@@ -119003,7 +119215,7 @@ function annotateTrend(outputDir, runId) {
119003
119215
  const report = readReport(paths.reportJson);
119004
119216
  if (!report)
119005
119217
  return null;
119006
- const prev = findPreviousSweep(outputDir, hostOf4(report.url), runId);
119218
+ const prev = findPreviousSweep(outputDir, hostOf5(report.url), runId);
119007
119219
  if (!prev) {
119008
119220
  report.trend = null;
119009
119221
  writeFileSync34(paths.reportJson, `${JSON.stringify(report, null, 2)}
@@ -119260,7 +119472,7 @@ function countTotals(issues) {
119260
119472
  var DEFAULT_SWEEP_IMAGE = "ghcr.io/decocms/parity";
119261
119473
  var DEFAULT_SWEEP_CRON = "0 6 1 * *";
119262
119474
  function buildScheduleJob(opts) {
119263
- const host = hostOf4(opts.url);
119475
+ const host = hostOf5(opts.url);
119264
119476
  const args = ["sweep", "--url", opts.url, "--board", "studio", "--yes", "--json"];
119265
119477
  if (opts.maxPages)
119266
119478
  args.push("--max-pages", String(opts.maxPages));
@@ -119335,7 +119547,7 @@ async function qaFileCommand(opts) {
119335
119547
  console.error(chalk38.red(`${opts.issues}: ${parsed.error.message}`));
119336
119548
  return 2;
119337
119549
  }
119338
- const dir = dirname9(opts.issues);
119550
+ const dir = dirname10(opts.issues);
119339
119551
  const review = readCardReview(dir);
119340
119552
  for (const i of [...parsed.data, ...review.issues])
119341
119553
  for (const e of i.evidence ?? [])
@@ -119396,7 +119608,7 @@ async function qaFileCommand(opts) {
119396
119608
 
119397
119609
  // src/commands/report.ts
119398
119610
  import { existsSync as existsSync36, readFileSync as readFileSync43, writeFileSync as writeFileSync35 } from "node:fs";
119399
- import { join as join50 } from "node:path";
119611
+ import { join as join50, resolve as resolve21 } from "node:path";
119400
119612
  import chalk39 from "chalk";
119401
119613
  import open3 from "open";
119402
119614
 
@@ -119722,7 +119934,7 @@ function renderDeckHtml(model, lang = "en") {
119722
119934
  const pages = [];
119723
119935
  pages.push(`<section class="page cover"><div class="page-inner">
119724
119936
  <div class="eyebrow">${L2("Relatório de migração", "Migration report", lang)}</div>
119725
- <h1 class="cover-h1">${esc3(hostOf5(model.candUrl))}<br/><span class="dim">${esc3(hostOf5(model.prodUrl))}</span> → <span class="lime-ink">${esc3(hostOf5(model.candUrl))}</span></h1>
119937
+ <h1 class="cover-h1">${esc3(hostOf6(model.candUrl))}<br/><span class="dim">${esc3(hostOf6(model.prodUrl))}</span> → <span class="lime-ink">${esc3(hostOf6(model.candUrl))}</span></h1>
119726
119938
  <div class="cover-meta">
119727
119939
  <div><b>${model.score}</b><small>${L2("score parity", "parity score", lang)}</small></div>
119728
119940
  <div><b>${esc3(model.status)}</b><small>${L2("veredito", "verdict", lang)}</small></div>
@@ -119769,7 +119981,7 @@ function renderDeckHtml(model, lang = "en") {
119769
119981
  <style>${DECK_CSS}</style>
119770
119982
  </head><body>
119771
119983
  <div class="nav">
119772
- <b>parity · ${esc3(hostOf5(model.candUrl))}</b>
119984
+ <b>parity · ${esc3(hostOf6(model.candUrl))}</b>
119773
119985
  <span class="spacer"></span>
119774
119986
  <div class="dots"><!-- filled by DECK_JS, one per page --></div>
119775
119987
  <span class="counter"></span>
@@ -119779,7 +119991,7 @@ function renderDeckHtml(model, lang = "en") {
119779
119991
  <script>${DECK_JS}</script>
119780
119992
  </body></html>`;
119781
119993
  }
119782
- function hostOf5(raw) {
119994
+ function hostOf6(raw) {
119783
119995
  try {
119784
119996
  return new URL(raw).host;
119785
119997
  } catch {
@@ -120046,12 +120258,24 @@ var REMOVED_SECTIONS = {
120046
120258
  sidebyside: "use `parity cockpit --prod <url> --cand <url>` for the live prod × cand view.",
120047
120259
  prompt: "use `parity prompt <runId>` for the LLM-ready Markdown."
120048
120260
  };
120261
+ function resolveRunPaths(output, runIdOrDir) {
120262
+ if (existsSync36(join50(runIdOrDir, "report.json")))
120263
+ return runPathsFor(resolve21(runIdOrDir));
120264
+ return getRunPaths(output, runIdOrDir);
120265
+ }
120266
+ function ensureReportHtml(paths) {
120267
+ if (existsSync36(paths.reportHtml))
120268
+ return { path: paths.reportHtml, rendered: false };
120269
+ const run = loadRunDir(paths.runDir);
120270
+ writeRunReportHtml(paths.runDir, renderHtmlReport(run, paths.runDir));
120271
+ return { path: paths.reportHtml, rendered: true };
120272
+ }
120049
120273
  async function reportCommand(runId, opts) {
120050
- const paths = getRunPaths(opts.output, runId);
120274
+ const paths = resolveRunPaths(opts.output, runId);
120051
120275
  if (opts.deck) {
120052
120276
  let run;
120053
120277
  try {
120054
- run = loadRun(opts.output, runId);
120278
+ run = loadRunDir(paths.runDir, runId);
120055
120279
  } catch (err) {
120056
120280
  console.error(chalk39.red(`failed to load run: ${err.message}`));
120057
120281
  return 1;
@@ -120093,7 +120317,7 @@ async function reportCommand(runId, opts) {
120093
120317
  }
120094
120318
  if (opts.json) {
120095
120319
  try {
120096
- const run = loadRun(opts.output, runId);
120320
+ const run = loadRunDir(paths.runDir, runId);
120097
120321
  const payload = extractReportSection({ kind: "json", section: opts.section, run });
120098
120322
  if (payload === null) {
120099
120323
  console.error(chalk39.red(`section "${opts.section}" not present in this run`));
@@ -120107,8 +120331,10 @@ async function reportCommand(runId, opts) {
120107
120331
  return 1;
120108
120332
  }
120109
120333
  }
120110
- if (!existsSync36(paths.reportHtml)) {
120111
- console.error(chalk39.red(`report.html not found at ${paths.reportHtml}`));
120334
+ try {
120335
+ ensureReportHtml(paths);
120336
+ } catch (err) {
120337
+ console.error(chalk39.red(`failed to render report.html: ${err.message}`));
120112
120338
  return 1;
120113
120339
  }
120114
120340
  const html = readFileSync43(paths.reportHtml, "utf8");
@@ -120120,7 +120346,13 @@ async function reportCommand(runId, opts) {
120120
120346
  process.stdout.write(slice);
120121
120347
  return 0;
120122
120348
  }
120123
- console.log(chalk39.dim(`opening ${paths.reportHtml}`));
120349
+ try {
120350
+ const { rendered } = ensureReportHtml(paths);
120351
+ console.log(`${rendered ? `${chalk39.green("✓")} rendered` : "→"} ${paths.reportHtml}`);
120352
+ } catch (err) {
120353
+ console.error(chalk39.red(`failed to render report.html: ${err.message}`));
120354
+ return 1;
120355
+ }
120124
120356
  await open3(paths.reportHtml).catch((err) => {
120125
120357
  console.error(chalk39.red(`failed to open: ${err.message}`));
120126
120358
  });
@@ -120454,8 +120686,10 @@ async function serveCommand(runId, opts) {
120454
120686
  console.error(chalk41.red(`✖ Run não encontrado: ${runId} (em ${opts.output})`));
120455
120687
  return 1;
120456
120688
  }
120457
- if (!existsSync37(paths.reportHtml)) {
120458
- console.error(chalk41.red(`✖ report.html não existe em ${paths.runDir}`));
120689
+ try {
120690
+ ensureReportHtml(paths);
120691
+ } catch (err) {
120692
+ console.error(chalk41.red(`✖ não foi possível gerar report.html: ${err.message}`));
120459
120693
  return 1;
120460
120694
  }
120461
120695
  return serveRunAndBlock(paths.runDir, {
@@ -122027,7 +122261,7 @@ program.command("run").description([
122027
122261
  " visual-pages=5, auto-selectors=ON (if LLM), learn=ON, visual-diff=ON,",
122028
122262
  " warmup=OFF, vitals warm=ON, bypass-cache=OFF, fail-on=critical (exit 1 if hit)."
122029
122263
  ].join(`
122030
- `)).option("--prod <url>", "Production URL (source of truth, e.g. Fresh site). Omit for a single site — the run will point you to `parity e2e` (issue #141).").requiredOption("--cand <url>", "Candidate URL (migrated site, e.g. TanStack)").option("--preset <name>", "Bundle of defaults: smoke (fast, ~30s, no LLM) | full (deep audit) | ci (CI-tuned)").option("--flows <list>", "Comma-separated flows: homepage,plp,pdp,purchase-journey", "purchase-journey").option("--viewports <list>", "Comma-separated viewports: mobile,desktop", "mobile,desktop").option("--cep <cep>", "CEP for shipping calculation", "01310-100").option("--add-to-cart-timeout <ms>", "How long (ms) the add-to-cart step polls for a success signal before failing. Default 3000. Raise/lower to match your site's success-toast lifetime (issue #143).", (v) => Number(v)).option("--runs <n>", "Repeat each measurement N times (median)", "1").option("--baseline <name>", "Compare against a saved baseline").option("--output <dir>", "Output directory", "./parity-output").option("--fail-on <severities>", "Comma-separated severities that cause exit 1 (default: critical)", "critical").option("--open", "Open the HTML report after the run completes", false).option("--no-auto-selectors", "Disable LLM-based selector discovery (uses defaults instead)").option("--refresh-selectors", "Bypass selector cache and re-run discovery", false).option("--no-learn", "Don't write to learned-selectors.json (read-only mode)").option("--vitals-pages <n>", "Extra pages from sitemap to crawl for Vitals coverage, beyond what --flows/--pages already cover (default 10). These are auto-sampled and can add significant unrelated noise to findings — pass 0 to scope the run to only the pages you explicitly requested.", (v) => Number(v), 10).option("--max-viewport-concurrency <n>", "How many viewports run concurrently during collect (default 2: mobile+desktop together). Set to 1 if you hit OOM with many viewports.", (v) => Number(v), 2).option("--visual-pages <n>", "Pages to compare visually with the heatmap engine — pixel diff + box-tree diff, no LLM (home + sampled PLPs/PDPs from sitemap, default 5)", (v) => Number(v), 5).option("--pages <list>", 'Comma-separated paths to compare visually (overrides sitemap discovery). E.g. "/,/account,/p/some-product". Use "prod->cand" for a page that lives at DIFFERENT paths on each side (partial migration), e.g. "/encimera-gc60/p->/ar-condicionado-12k/p". Use this when you want deterministic coverage instead of sampled. Scopes the visual-diff + vitals-extra-pages passes ONLY — the flows crawl (--flows, default purchase-journey) discovers its own target pages independently and ignores this flag. To scope which page(s) a flow visits, use --flows to pick a lighter flow and/or set the matching *UrlHint (e.g. plpUrlHint) in .parityrc.json. Issue #178.').option("--pages-file <path>", `Read paths to compare visually from a text file (one entry per line). Lines starting with # are ignored. Accepts the same "prod->cand" pair syntax as --pages. Overrides --pages when both are present. Same visual-diff/vitals-only scope as --pages — see that flag's help. Issue #178.`).option("--no-visual-diff", "Skip the visual diff capture pass entirely").option("--no-cache", "Deprecated, no effect (the visual verdict cache is gone).").option("--clear-cache", "Deprecated, no effect (the visual verdict cache is gone).", false).option("--bypass-cache", "Bypass CDN/edge caches AND the browser's own HTTP cache (CDP cache-disable), forcing a cold-visit fetch. Use right after a deploy to avoid false failures from stale CF edge content, or to approximate Lighthouse/CrUX-comparable TTFB/FCP/LCP numbers — without this flag, parity's vitals are a warm-connection/cache-enabled ('repeat visit') measurement, not a cold first-visit one, so they aren't directly comparable 1:1 to Lighthouse.", false).option("--warmup", "Before measurement, hit each target URL once (per viewport) with a cache-buster so the Worker serves a fresh response. Recommended after deploys.", false).option("--no-warm", "Don't warm each side's URL before measuring vitals. By default every vitals-measured page is loaded once on BOTH sides first, in a throwaway page (same device + cookies), so a cold edge/loader cache on whichever side hit the route first isn't reported as a Web Vitals or CLS regression. Ignored under --bypass-cache, which measures cold on purpose. Distinct from --warmup (a cache-busted homepage hit after a deploy).").option("--accept-prod-quirks", "Demote prod-side cart-empty journey failures (VTEX session quirk) from failed to skipped. The cart-reveal-mode-divergence check still emits critical if prod/cand markup intents differ, so this flag never masks a real regression. See issue #12.", false).option("--cand-is-production", "Cand is the final production domain, not a staging host. Disables staging detection (cand on another host with noindex everywhere), so noindex/nofollow on cand is critical and third-party origins missing on cand are high again.", false).option("--llm-timeout <seconds>", "Hard timeout for the LLM aggregation call (seconds). The run completes in offline mode if the LLM hangs past this. Default: 60.", (v) => Number(v), 60).option("--timeout <minutes>", "Hard wall-clock cap for the whole run (minutes). On expiry, parity writes a partial report and exits 130. Default: 30. Issue #56.", (v) => Number(v), 30).option("--flow <name>", "Alias for --flows when running a single flow (e.g. --flow cart). Issue #53.").option("--json <path|->", "Emit JSON-Lines (one line per check) to the given file path, or '-' for stdout. Schema versioned via leading metadata line. Issue #53.").option("--pt", "Tell the LLM to respond in Brazilian Portuguese. Only affects LLM-generated content (issues, explain, prompts) — the static HTML report stays in English. Issue #67.").option("--llm <provider>", "Force LLM provider: anthropic | openrouter | claude-code | none. Default: auto-detect (anthropic key → openrouter key → local claude CLI → none). Issue #66.").option("--llm-model <overrides>", "Per-feature model override, e.g. visual-diff=claude-opus-5,explain=claude-opus-5. Features: selector-discovery, step-recovery, search-terms, plp-matching, pdp-matching, section-understanding, visual-diff, issue-aggregation, explain, component-detection. Issue #66.").option("--llm-tier-default <tier>", "Override the default tier (haiku | sonnet | opus) for every feature that doesn't have a per-feature override. Issue #66.").option("--llm-model-default <model>", "Force every LLM call to use this exact model ID, ignoring per-feature defaults. Issue #66.").option("--llm-premium", "Bump the reasoning-heavy features (explain/issue-aggregation/visual-diff) to opus. Defaults are sonnet-first for cost/latency (opus blew the 60s timeout on most runs); opt into opus for hard fixes. Issue #256.").option("--no-interactive", "Disable the interactive selector prompt that auto-fires in a TTY without an LLM provider. Use in scripts and CI where stdin is technically a TTY but you don't want to pause. Issue #72.").option("--only <modules>", "Scope the run to these modules and/or single checks (comma-separated). Module names: e2e, seo, visual, vitals, cache, console, html, network. Single-check granularity via `check:<name>`, e.g. `--only e2e,check:cache-coverage`. Run `parity list modules` for the full check/flow mapping. Default: all modules. M3 module selection.").option("--skip <modules>", "Subtract these modules and/or single checks (comma-separated, same syntax as --only) from whatever base set was chosen (all modules, or --only's set if both are given). M3 module selection.").option("--why <text>", "Free-text reason for this run's scope, stored in report.json as `selectionReason`. Purely informational. M3 module selection.").option("--profile <type>", "Site profile: commerce | content. Scopes modules/flows/CEP. `content` (blog/custom site with no storefront) drops the e2e purchase journey, scopes flows to the homepage, and skips CEP. Auto-detected from the platform when omitted. Issues #254/#255.").action(async (opts) => {
122264
+ `)).option("--prod <url>", "Production URL (source of truth, e.g. Fresh site). Omit for a single site — the run will point you to `parity e2e` (issue #141).").requiredOption("--cand <url>", "Candidate URL (migrated site, e.g. TanStack)").option("--preset <name>", "Bundle of defaults: smoke (fast, ~30s, no LLM) | full (deep audit) | ci (CI-tuned)").option("--flows <list>", "Comma-separated flows: homepage,plp,pdp,purchase-journey", "purchase-journey").option("--viewports <list>", "Comma-separated viewports: mobile,desktop", "mobile,desktop").option("--cep <cep>", "CEP for shipping calculation", "01310-100").option("--prod-cookie <name=value>", "Cookie set on every prod browser context and plain request; repeatable. Pins prod to one A/B variant (e.g. a Fresh-vs-TanStack bucket cookie) so the run does not compare whichever build each fresh context drew. Values are redacted in logs and report.json.", collectCookie, []).option("--cand-cookie <name=value>", "Same as --prod-cookie, for the candidate side", collectCookie, []).option("--prod-header <Name: value>", "Request header sent on every prod request (all origins — no credentials); repeatable. The header twin of --prod-cookie. Values are redacted in logs and report.json.", collectHeader, []).option("--cand-header <Name: value>", "Same as --prod-header, for the candidate side", collectHeader, []).option("--add-to-cart-timeout <ms>", "How long (ms) the add-to-cart step polls for a success signal before failing. Default 3000. Raise/lower to match your site's success-toast lifetime (issue #143).", (v) => Number(v)).option("--runs <n>", "Repeat each measurement N times (median)", "1").option("--baseline <name>", "Compare against a saved baseline").option("--output <dir>", "Output directory", "./parity-output").option("--fail-on <severities>", "Comma-separated severities that cause exit 1 (default: critical)", "critical").option("--html", "Also write report.html (off by default: render it later with `parity report <runId>`)", false).option("--open", "Write report.html and open it after the run completes (implies --html)", false).option("--no-auto-selectors", "Disable LLM-based selector discovery (uses defaults instead)").option("--refresh-selectors", "Bypass selector cache and re-run discovery", false).option("--no-learn", "Don't write to learned-selectors.json (read-only mode)").option("--vitals-pages <n>", "Extra pages from sitemap to crawl for Vitals coverage, beyond what --flows/--pages already cover (default 10). These are auto-sampled and can add significant unrelated noise to findings — pass 0 to scope the run to only the pages you explicitly requested.", (v) => Number(v), 10).option("--max-viewport-concurrency <n>", "How many viewports run concurrently during collect (default 2: mobile+desktop together). Set to 1 if you hit OOM with many viewports.", (v) => Number(v), 2).option("--visual-pages <n>", "Pages to compare visually with the heatmap engine — pixel diff + box-tree diff, no LLM (home + sampled PLPs/PDPs from sitemap, default 5)", (v) => Number(v), 5).option("--pages <list>", 'Comma-separated paths to compare visually (overrides sitemap discovery). E.g. "/,/account,/p/some-product". Use "prod->cand" for a page that lives at DIFFERENT paths on each side (partial migration), e.g. "/encimera-gc60/p->/ar-condicionado-12k/p". Use this when you want deterministic coverage instead of sampled. Scopes the visual-diff + vitals-extra-pages passes ONLY — the flows crawl (--flows, default purchase-journey) discovers its own target pages independently and ignores this flag. To scope which page(s) a flow visits, use --flows to pick a lighter flow and/or set the matching *UrlHint (e.g. plpUrlHint) in .parityrc.json. Issue #178.').option("--pages-file <path>", `Read paths to compare visually from a text file (one entry per line). Lines starting with # are ignored. Accepts the same "prod->cand" pair syntax as --pages. Overrides --pages when both are present. Same visual-diff/vitals-only scope as --pages — see that flag's help. Issue #178.`).option("--no-visual-diff", "Skip the visual diff capture pass entirely").option("--no-cache", "Deprecated, no effect (the visual verdict cache is gone).").option("--clear-cache", "Deprecated, no effect (the visual verdict cache is gone).", false).option("--bypass-cache", "Bypass CDN/edge caches AND the browser's own HTTP cache (CDP cache-disable), forcing a cold-visit fetch. Use right after a deploy to avoid false failures from stale CF edge content, or to approximate Lighthouse/CrUX-comparable TTFB/FCP/LCP numbers — without this flag, parity's vitals are a warm-connection/cache-enabled ('repeat visit') measurement, not a cold first-visit one, so they aren't directly comparable 1:1 to Lighthouse.", false).option("--warmup", "Before measurement, hit each target URL once (per viewport) with a cache-buster so the Worker serves a fresh response. Recommended after deploys.", false).option("--no-warm", "Don't warm each side's URL before measuring vitals. By default every vitals-measured page is loaded once on BOTH sides first, in a throwaway page (same device + cookies), so a cold edge/loader cache on whichever side hit the route first isn't reported as a Web Vitals or CLS regression. Ignored under --bypass-cache, which measures cold on purpose. Distinct from --warmup (a cache-busted homepage hit after a deploy).").option("--accept-prod-quirks", "Demote prod-side cart-empty journey failures (VTEX session quirk) from failed to skipped. The cart-reveal-mode-divergence check still emits critical if prod/cand markup intents differ, so this flag never masks a real regression. See issue #12.", false).option("--cand-is-production", "Cand is the final production domain, not a staging host. Disables staging detection (cand on another host with noindex everywhere), so noindex/nofollow on cand is critical and third-party origins missing on cand are high again.", false).option("--llm-timeout <seconds>", "Deprecated, no effect: topIssues is ranked deterministically now, there is no LLM aggregation call to time out.").option("--keep-runs <n>", "After the run, delete all but the n newest runs of this prod/cand host pair under --output (other host pairs, runs without a readable report.json and baseline-referenced runs are never touched). 0 keeps everything. Default: 10.", (v) => Number(v), 10).option("--timeout <minutes>", "Hard wall-clock cap for the whole run (minutes). On expiry, parity writes a partial report and exits 130. Default: 30. Issue #56.", (v) => Number(v), 30).option("--flow <name>", "Alias for --flows when running a single flow (e.g. --flow cart). Issue #53.").option("--json <path|->", "Emit JSON-Lines (one line per check) to the given file path, or '-' for stdout. Schema versioned via leading metadata line. Issue #53.").option("--pt", "Tell the LLM to respond in Brazilian Portuguese. Only affects LLM-generated content (issues, explain, prompts) — the static HTML report stays in English. Issue #67.").option("--llm <provider>", "Force LLM provider: anthropic | openrouter | claude-code | none. Default: auto-detect (anthropic key → openrouter key → local claude CLI → none). Issue #66.").option("--llm-model <overrides>", "Per-feature model override, e.g. visual-diff=claude-opus-5,explain=claude-opus-5. Features: selector-discovery, step-recovery, search-terms, plp-matching, pdp-matching, section-understanding, visual-diff, explain, component-detection. Issue #66.").option("--llm-tier-default <tier>", "Override the default tier (haiku | sonnet | opus) for every feature that doesn't have a per-feature override. Issue #66.").option("--llm-model-default <model>", "Force every LLM call to use this exact model ID, ignoring per-feature defaults. Issue #66.").option("--llm-premium", "Bump the reasoning-heavy features (explain/visual-diff) to opus. Defaults are sonnet-first for cost/latency (opus blew the 60s timeout on most runs); opt into opus for hard fixes. Issue #256.").option("--no-interactive", "Disable the interactive selector prompt that auto-fires in a TTY without an LLM provider. Use in scripts and CI where stdin is technically a TTY but you don't want to pause. Issue #72.").option("--only <modules>", "Scope the run to these modules and/or single checks (comma-separated). Module names: e2e, seo, visual, vitals, cache, console, html, network. Single-check granularity via `check:<name>`, e.g. `--only e2e,check:cache-coverage`. Run `parity list modules` for the full check/flow mapping. Default: all modules. M3 module selection.").option("--skip <modules>", "Subtract these modules and/or single checks (comma-separated, same syntax as --only) from whatever base set was chosen (all modules, or --only's set if both are given). M3 module selection.").option("--why <text>", "Free-text reason for this run's scope, stored in report.json as `selectionReason`. Purely informational. M3 module selection.").option("--profile <type>", "Site profile: commerce | content. Scopes modules/flows/CEP. `content` (blog/custom site with no storefront) drops the e2e purchase journey, scopes flows to the homepage, and skips CEP. Auto-detected from the platform when omitted. Issues #254/#255.").action(async (opts) => {
122031
122265
  if (opts.flow) {
122032
122266
  opts.flows = opts.flow;
122033
122267
  }
@@ -122173,7 +122407,7 @@ program.command("serve").argument("<runId>", "Run ID to serve").description("[de
122173
122407
  program.command("event").argument("<type>", "Event type: phase-change | dispatch | bench | score | note | …").description("Record a migration event into <dir>/events.jsonl — the sanctioned emission path for hooks and the orchestrator. The cockpit daemon tails this file into its live activity feed.").option("--dir <dir>", "Directory holding events.jsonl (the target's .parity/)", ".parity").option("--data <json>", `JSON object of event fields, e.g. '{"agent":"porter","component":"hero"}'`).action((type, opts) => {
122174
122408
  process.exit(eventCommand(type, opts));
122175
122409
  });
122176
- program.command("report").argument("<runId>", "Run ID to open").description("Open the HTML report for a run in the default browser. With --section, extract a single tab to stdout instead — useful for agents that need just the SEO/Network/Vitals slice without parsing the whole report. Issue #74.").option("--output <dir>", "Output directory", "./parity-output").option("--section <name>", "Extract one tab to stdout instead of opening the report. Valid names: summary, visualdiff, seo, issues, vitals, cache, checks, pages, console, network, diff.").option("--json", "Pair with --section to emit a normalized JSON projection of the section (from report.json) instead of the raw HTML slice.").option("--deck", "Render the presentation deck instead: one topic per full-viewport page, advanced sideways, in a single self-contained HTML file. For showing the result to someone rather than debugging it. Issue #290.", false).option("--out <path>", "Where to write the deck (default: deck.html in the run dir)").option("--lang <pt|en>", "Initial deck language; the in-page toggle still switches live", "en").option("--open", "Open the rendered deck in the browser", false).option("--plan-dir <dir>", "With --deck: dir holding migration-plan.json. Adds the component heat map (grouped by page, plus global) and the block-by-block table. Without it those pages are omitted, not drawn empty. Issue #291.").action(async (runId, opts) => {
122410
+ program.command("report").argument("<runId>", "Run ID, or the run directory itself (runs/<runId>/)").description("Open the HTML report for a run in the default browser, rendering report.html from report.json first if the run has none (`parity run` only writes it with --html). With --section, extract a single tab to stdout instead — useful for agents that need just the SEO/Network/Vitals slice without parsing the whole report. Issue #74.").option("--output <dir>", "Output directory", "./parity-output").option("--section <name>", "Extract one tab to stdout instead of opening the report. Valid names: summary, visualdiff, seo, issues, vitals, cache, checks, pages, console, network, diff.").option("--json", "Pair with --section to emit a normalized JSON projection of the section (from report.json) instead of the raw HTML slice.").option("--deck", "Render the presentation deck instead: one topic per full-viewport page, advanced sideways, in a single self-contained HTML file. For showing the result to someone rather than debugging it. Issue #290.", false).option("--out <path>", "Where to write the deck (default: deck.html in the run dir)").option("--lang <pt|en>", "Initial deck language; the in-page toggle still switches live", "en").option("--open", "Open the rendered deck in the browser", false).option("--plan-dir <dir>", "With --deck: dir holding migration-plan.json. Adds the component heat map (grouped by page, plus global) and the block-by-block table. Without it those pages are omitted, not drawn empty. Issue #291.").action(async (runId, opts) => {
122177
122411
  process.exit(await reportCommand(runId, {
122178
122412
  output: opts.output,
122179
122413
  section: opts.section,
@@ -122308,6 +122542,11 @@ function collectCookie(value, prev) {
122308
122542
  throw new InvalidArgumentError2("expected name=value");
122309
122543
  return [...prev, value];
122310
122544
  }
122545
+ function collectHeader(value, prev) {
122546
+ if (value.indexOf(":") <= 0)
122547
+ throw new InvalidArgumentError2('expected "Name: value"');
122548
+ return [...prev, value];
122549
+ }
122311
122550
  program.command("ab-detect").description("Is prod A/B-testing this component? Opens N fresh sessions, hashes what --selector (or the page) rendered in each, and records experiment signals (cookies/storage keys, variant attributes, A/B SDK globals). Exit 0 = no A/B seen (same structure, no signal differs), 1 = A/B detected or possible (same structure but experiment signals differ between sessions — a behaviour-only test); either way it names the signals to pin with --prod-cookie, 2 = inconclusive.").requiredOption("--url <url>", "Production page URL").option("--sessions <n>", "Fresh sessions to open (min 2)", "3").option("--selector <sel>", "Component to compare across sessions. Without it, the whole page.").option("--viewport <viewport>", "mobile | desktop | tablet", "mobile").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
122312
122551
  process.exit(await abDetectCommand(opts));
122313
122552
  });