@decocms/parity 0.33.32 → 0.33.34

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.
Files changed (2) hide show
  1. package/dist/cli.js +2917 -554
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -39004,6 +39004,63 @@ async function waitForSkeletonsToResolve(page, maxMs = 1e4) {
39004
39004
  });
39005
39005
  }
39006
39006
  }
39007
+ var SETTLE_SAMPLES = 3;
39008
+ var SETTLE_INTERVAL_MS = 200;
39009
+ async function waitForLayoutStable(page, maxMs = 8000) {
39010
+ const start = Date.now();
39011
+ const sample = () => page.evaluate(() => ({
39012
+ height: document.body?.scrollHeight ?? 0,
39013
+ elements: document.querySelectorAll("*").length
39014
+ })).catch(() => null);
39015
+ let last = null;
39016
+ let repeats = 0;
39017
+ let samples = 0;
39018
+ while (Date.now() - start < maxMs) {
39019
+ const now = await sample();
39020
+ samples++;
39021
+ if (!now)
39022
+ break;
39023
+ repeats = last && now.height === last.height && now.elements === last.elements ? repeats + 1 : 0;
39024
+ last = now;
39025
+ if (repeats + 1 >= SETTLE_SAMPLES) {
39026
+ return { stable: true, heightPx: now.height, waitedMs: Date.now() - start, samples };
39027
+ }
39028
+ await page.waitForTimeout(SETTLE_INTERVAL_MS).catch(() => {
39029
+ return;
39030
+ });
39031
+ }
39032
+ return {
39033
+ stable: false,
39034
+ heightPx: last?.height ?? 0,
39035
+ waitedMs: Date.now() - start,
39036
+ samples
39037
+ };
39038
+ }
39039
+ async function reloadIfOptionalFonts(page, waitMs = 0) {
39040
+ const optional = await page.evaluate(() => {
39041
+ for (const face of document.fonts) {
39042
+ if (face.display === "optional")
39043
+ return true;
39044
+ }
39045
+ return false;
39046
+ }).catch(() => false);
39047
+ if (!optional)
39048
+ return false;
39049
+ await page.reload({ waitUntil: "domcontentloaded", timeout: 30000 }).catch(() => {
39050
+ return;
39051
+ });
39052
+ await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
39053
+ return;
39054
+ });
39055
+ if (waitMs > 0)
39056
+ await page.waitForTimeout(waitMs).catch(() => {
39057
+ return;
39058
+ });
39059
+ return true;
39060
+ }
39061
+ function formatSettleCaveat(side, settle) {
39062
+ return settle.stable ? null : `${side}: layout still changing after ${settle.waitedMs}ms (height ${settle.heightPx}px) — measured anyway, so a large rect delta may be a timing artifact`;
39063
+ }
39007
39064
  async function scrollFullPage(page, budgetMs = 45000) {
39008
39065
  const start = Date.now();
39009
39066
  const result = await page.evaluate(async (budget) => {
@@ -41558,6 +41615,13 @@ var RunCaveat = z.object({
41558
41615
  summary: z.string(),
41559
41616
  detail: z.string()
41560
41617
  });
41618
+ var ScoreBand = z.object({
41619
+ scores: z.array(z.number()),
41620
+ spread: z.number(),
41621
+ priorRuns: z.number(),
41622
+ flipping: z.array(z.object({ name: z.string(), statuses: z.array(z.string()) })),
41623
+ worthShowing: z.boolean()
41624
+ });
41561
41625
  var Run = z.object({
41562
41626
  schemaVersion: z.literal("0.1"),
41563
41627
  id: z.string(),
@@ -41569,6 +41633,7 @@ var Run = z.object({
41569
41633
  cep: z.string(),
41570
41634
  durationMs: z.number(),
41571
41635
  verdict: Verdict,
41636
+ scoreBand: ScoreBand.optional(),
41572
41637
  previousRun: z.object({
41573
41638
  id: z.string(),
41574
41639
  timestamp: z.string(),
@@ -41761,6 +41826,9 @@ function sameModuleSet(a, b) {
41761
41826
  return true;
41762
41827
  }
41763
41828
  function findPreviousRun(outputDir, opts) {
41829
+ return findComparableRuns(outputDir, opts, 1)[0] ?? null;
41830
+ }
41831
+ function findComparableRuns(outputDir, opts, limit) {
41764
41832
  const hostOf = (url) => {
41765
41833
  try {
41766
41834
  return new URL(url).hostname;
@@ -41770,7 +41838,10 @@ function findPreviousRun(outputDir, opts) {
41770
41838
  };
41771
41839
  const prodHost = hostOf(opts.prodUrl);
41772
41840
  const candHost = hostOf(opts.candUrl);
41841
+ const out = [];
41773
41842
  for (const entry of listRuns(outputDir)) {
41843
+ if (out.length >= limit)
41844
+ break;
41774
41845
  if (entry.id === opts.excludeRunId)
41775
41846
  continue;
41776
41847
  try {
@@ -41788,14 +41859,15 @@ function findPreviousRun(outputDir, opts) {
41788
41859
  if (!sameModuleSet(candidateModules, opts.modulesRun))
41789
41860
  continue;
41790
41861
  }
41791
- return {
41862
+ out.push({
41792
41863
  id: raw.id ?? entry.id,
41793
41864
  timestamp: raw.timestamp ?? entry.timestamp,
41794
- score: raw.verdict.score
41795
- };
41865
+ score: raw.verdict.score,
41866
+ reportPath: entry.reportPath
41867
+ });
41796
41868
  } catch {}
41797
41869
  }
41798
- return null;
41870
+ return out;
41799
41871
  }
41800
41872
  function listRuns(outputDir) {
41801
41873
  const runsDir = join(outputDir, "runs");
@@ -62302,12 +62374,13 @@ function sanitizeDetectedComponents(components) {
62302
62374
  }
62303
62375
  return out;
62304
62376
  }
62377
+ var ZERO_AREA_ALLOWED = new Set(["header", "footer", "nav", "banner"]);
62305
62378
  function dedupeByContainment(candidates) {
62306
- const valid = candidates.filter((c) => c.rect.width > 0 && c.rect.height > 0);
62379
+ const valid = candidates.filter((c) => c.rect.width > 0 && c.rect.height > 0 || ZERO_AREA_ALLOWED.has(c.role));
62307
62380
  const sorted = [...valid].sort((a, b) => boxArea(b.rect) - boxArea(a.rect));
62308
62381
  const accepted = [];
62309
62382
  for (const candidate of sorted) {
62310
- const containedInAccepted = accepted.some((a) => a.priority >= candidate.priority && containmentRatio(candidate.rect, a.rect) >= 0.9);
62383
+ const containedInAccepted = boxArea(candidate.rect) > 0 && accepted.some((a) => boxArea(a.rect) > 0 && a.priority >= candidate.priority && containmentRatio(candidate.rect, a.rect) >= 0.9);
62311
62384
  if (containedInAccepted)
62312
62385
  continue;
62313
62386
  accepted.push(candidate);
@@ -62621,12 +62694,12 @@ import { writeFile } from "node:fs/promises";
62621
62694
 
62622
62695
  // src/engine/capture-utils.ts
62623
62696
  import { PNG as PNG3 } from "pngjs";
62624
- function cropPngBuffer(srcBuffer, box) {
62697
+ function cropPngBuffer(srcBuffer, box, scale = 1) {
62625
62698
  const src = PNG3.sync.read(srcBuffer);
62626
- const x = Math.max(0, Math.floor(box.x));
62627
- const y = Math.max(0, Math.floor(box.y));
62628
- const w = Math.max(0, Math.min(Math.ceil(box.width), src.width - x));
62629
- const h = Math.max(0, Math.min(Math.ceil(box.height), src.height - y));
62699
+ const x = Math.max(0, Math.floor(box.x * scale));
62700
+ const y = Math.max(0, Math.floor(box.y * scale));
62701
+ const w = Math.max(0, Math.min(Math.ceil(box.width * scale), src.width - x));
62702
+ const h = Math.max(0, Math.min(Math.ceil(box.height * scale), src.height - y));
62630
62703
  if (w === 0 || h === 0) {
62631
62704
  throw new Error(`cropPngBuffer: bounding box has zero area after clamp (box=${JSON.stringify(box)} src=${src.width}x${src.height})`);
62632
62705
  }
@@ -62844,7 +62917,8 @@ async function captureSectionScreenshot(page, selector, outPath, preCapturedFull
62844
62917
  if (!box || box.width <= 0 || box.height <= 0) {
62845
62918
  return `seletor '${selector}' não tem boundingBox visível`;
62846
62919
  }
62847
- const cropped = cropPngBuffer(fullPng, box);
62920
+ const dpr = await page.evaluate(() => window.devicePixelRatio).catch(() => 1);
62921
+ const cropped = cropPngBuffer(fullPng, box, dpr);
62848
62922
  await writeFile(outPath, cropped);
62849
62923
  return null;
62850
62924
  } catch (err) {
@@ -63637,6 +63711,483 @@ function capDiff(diff, maxLines) {
63637
63711
  `);
63638
63712
  }
63639
63713
 
63714
+ // src/migrate/plan.ts
63715
+ import { existsSync as existsSync16, readFileSync as readFileSync21, writeFileSync as writeFileSync21 } from "node:fs";
63716
+ import { join as join25 } from "node:path";
63717
+ function dedupe(names) {
63718
+ return [...new Set(names)];
63719
+ }
63720
+ function key(name) {
63721
+ return name.toLowerCase().replace(/[\s_/-]+/g, "");
63722
+ }
63723
+ function buildMigrationPlan(input) {
63724
+ const { bundle, source, inventory } = input;
63725
+ const liveByKey = new Map;
63726
+ for (const c of bundle.components) {
63727
+ liveByKey.set(key(c.role), { role: c.role, scope: c.scope, selector: c.selector });
63728
+ }
63729
+ const srcByKey = new Map;
63730
+ for (const c of inventory.components)
63731
+ srcByKey.set(key(c.name), c);
63732
+ const components = [];
63733
+ for (const [k, c] of srcByKey) {
63734
+ components.push({
63735
+ name: c.name,
63736
+ role: c.role,
63737
+ scope: c.scope,
63738
+ origin: liveByKey.has(k) ? "both" : "source-only",
63739
+ status: "pending",
63740
+ file: c.file,
63741
+ selector: liveByKey.get(k)?.selector ?? null,
63742
+ reference: null,
63743
+ verified: null
63744
+ });
63745
+ }
63746
+ for (const [k, c] of liveByKey) {
63747
+ if (srcByKey.has(k))
63748
+ continue;
63749
+ components.push({
63750
+ name: c.role,
63751
+ role: c.role,
63752
+ scope: c.scope,
63753
+ origin: "live-only",
63754
+ status: "pending",
63755
+ file: null,
63756
+ selector: c.selector,
63757
+ reference: null,
63758
+ verified: null
63759
+ });
63760
+ }
63761
+ return {
63762
+ url: bundle.url,
63763
+ timestamp: bundle.timestamp,
63764
+ source: {
63765
+ kind: source.kind,
63766
+ label: source.label,
63767
+ dir: source.dir,
63768
+ notes: inventory.notes,
63769
+ ...input.searched ? { searched: input.searched } : {},
63770
+ ...input.project ? { project: input.project } : {}
63771
+ },
63772
+ target: { name: bundle.target ?? null },
63773
+ pages: bundle.pages.map((p) => ({
63774
+ path: p.path,
63775
+ kind: p.kind,
63776
+ status: "pending",
63777
+ components: dedupe((p.components ?? []).map((c) => components.find((row) => key(row.name) === key(c.role))?.name ?? c.role))
63778
+ })),
63779
+ components
63780
+ };
63781
+ }
63782
+ function mergePlanDecisions(fresh, previous) {
63783
+ if (!previous)
63784
+ return { plan: fresh, carried: [], keptUncaptured: [], droppedWithDecisions: [] };
63785
+ const prevByKey = new Map(previous.components.map((c) => [key(c.name), c]));
63786
+ const carried = [];
63787
+ for (const row of fresh.components) {
63788
+ const prev = prevByKey.get(key(row.name));
63789
+ if (!prev)
63790
+ continue;
63791
+ if (prev.status !== "pending")
63792
+ row.status = prev.status;
63793
+ if (prev.reference)
63794
+ row.reference = prev.reference;
63795
+ if (prev.verified)
63796
+ row.verified = prev.verified;
63797
+ if (prev.provenance)
63798
+ row.provenance = prev.provenance;
63799
+ if (prev.status !== "pending" || prev.reference || prev.verified)
63800
+ carried.push(row.name);
63801
+ }
63802
+ const freshKeys = new Set(fresh.components.map((c) => key(c.name)));
63803
+ const keptUncaptured = [];
63804
+ for (const prev of previous.components) {
63805
+ if (freshKeys.has(key(prev.name)))
63806
+ continue;
63807
+ const hasDecision = prev.status !== "pending" || Boolean(prev.reference) || Boolean(prev.verified);
63808
+ if (prev.origin !== "manual" && !hasDecision)
63809
+ continue;
63810
+ fresh.components.push(prev);
63811
+ keptUncaptured.push(prev.name);
63812
+ }
63813
+ const prevPages = new Map(previous.pages.map((p) => [p.path, p]));
63814
+ for (const page of fresh.pages) {
63815
+ const prev = prevPages.get(page.path);
63816
+ if (prev?.status && prev.status !== "pending")
63817
+ page.status = prev.status;
63818
+ if (prev?.boardItemId)
63819
+ page.boardItemId = prev.boardItemId;
63820
+ }
63821
+ const freshPaths = new Set(fresh.pages.map((p) => p.path));
63822
+ for (const prev of previous.pages) {
63823
+ if (freshPaths.has(prev.path))
63824
+ continue;
63825
+ if (prev.status === "pending")
63826
+ continue;
63827
+ fresh.pages.push(prev);
63828
+ keptUncaptured.push(prev.path);
63829
+ }
63830
+ if (previous.telemetry)
63831
+ fresh.telemetry = previous.telemetry;
63832
+ return { plan: fresh, carried, keptUncaptured, droppedWithDecisions: [] };
63833
+ }
63834
+ var PLAN_FILE = "migration-plan.json";
63835
+ var SETTLED = new Set(["done", "as-is", "upgrade", "skipped"]);
63836
+ function loadPlan(dir) {
63837
+ const p = join25(dir, PLAN_FILE);
63838
+ if (!existsSync16(p))
63839
+ return null;
63840
+ return JSON.parse(readFileSync21(p, "utf8"));
63841
+ }
63842
+ function savePlan(dir, plan) {
63843
+ writeFileSync21(join25(dir, PLAN_FILE), `${JSON.stringify(plan, null, 2)}
63844
+ `, "utf8");
63845
+ }
63846
+ function setComponentStatus(plan, name, status, opts = {}) {
63847
+ const k = key(name);
63848
+ const component = plan.components.find((c) => key(c.name) === k);
63849
+ if (component) {
63850
+ component.status = status;
63851
+ return component;
63852
+ }
63853
+ if (!opts.create)
63854
+ return null;
63855
+ const created = {
63856
+ name,
63857
+ role: opts.create.role ?? name,
63858
+ scope: opts.create.scope,
63859
+ origin: "manual",
63860
+ status,
63861
+ file: null,
63862
+ selector: null,
63863
+ reference: null,
63864
+ verified: null
63865
+ };
63866
+ plan.components.push(created);
63867
+ return created;
63868
+ }
63869
+ function setComponentProvenance(plan, name, provenance) {
63870
+ const k = key(name);
63871
+ const component = plan.components.find((c) => key(c.name) === k);
63872
+ if (!component)
63873
+ return null;
63874
+ component.provenance = provenance;
63875
+ return component;
63876
+ }
63877
+ function recordTouch(plan, path) {
63878
+ const page = findPage(plan, path);
63879
+ const kk = page?.path ?? path;
63880
+ plan.telemetry ??= {};
63881
+ plan.telemetry.touches ??= {};
63882
+ const next = (plan.telemetry.touches[kk] ?? 0) + 1;
63883
+ plan.telemetry.touches[kk] = next;
63884
+ return next;
63885
+ }
63886
+ function totalTouches(plan) {
63887
+ return Object.values(plan.telemetry?.touches ?? {}).reduce((a, b) => a + b, 0);
63888
+ }
63889
+ function provenanceCounts(plan) {
63890
+ let library = 0;
63891
+ let built = 0;
63892
+ let unrecorded = 0;
63893
+ for (const c of plan.components) {
63894
+ if (c.provenance === "library")
63895
+ library++;
63896
+ else if (c.provenance === "built")
63897
+ built++;
63898
+ else
63899
+ unrecorded++;
63900
+ }
63901
+ return { library, built, unrecorded };
63902
+ }
63903
+ function setPageStatus(plan, path, status) {
63904
+ const page = findPage(plan, path);
63905
+ if (!page)
63906
+ return null;
63907
+ page.status = status;
63908
+ return page;
63909
+ }
63910
+ function findPage(plan, path) {
63911
+ const norm = (p) => `/${p.trim().replace(/^\/+|\/+$/g, "")}` || "/";
63912
+ const target = norm(path);
63913
+ return plan.pages.find((p) => p.path === path) ?? plan.pages.find((p) => norm(p.path) === target) ?? null;
63914
+ }
63915
+ function setPageBoardItemId(plan, path, boardItemId) {
63916
+ const page = findPage(plan, path);
63917
+ if (!page)
63918
+ return null;
63919
+ page.boardItemId = boardItemId;
63920
+ return page;
63921
+ }
63922
+ function planProgress(plan) {
63923
+ const compByStatus = {
63924
+ pending: 0,
63925
+ partial: 0,
63926
+ done: 0,
63927
+ "as-is": 0,
63928
+ upgrade: 0,
63929
+ skipped: 0
63930
+ };
63931
+ const settled = [];
63932
+ const settledByStatus = { done: [], skipped: [] };
63933
+ const accepted = { asIs: [], upgrade: [] };
63934
+ const remaining = [];
63935
+ for (const c of plan.components) {
63936
+ compByStatus[c.status] = (compByStatus[c.status] ?? 0) + 1;
63937
+ if (c.status === "as-is")
63938
+ accepted.asIs.push(c.name);
63939
+ if (c.status === "upgrade")
63940
+ accepted.upgrade.push(c.name);
63941
+ if (c.status === "done")
63942
+ settledByStatus.done.push(c.name);
63943
+ if (c.status === "skipped")
63944
+ settledByStatus.skipped.push(c.name);
63945
+ if (SETTLED.has(c.status))
63946
+ settled.push(c.name);
63947
+ else
63948
+ remaining.push({
63949
+ name: c.name,
63950
+ status: c.status,
63951
+ scope: c.scope ?? "page",
63952
+ origin: c.origin
63953
+ });
63954
+ }
63955
+ const pageByStatus = { pending: 0, code: 0, done: 0, skipped: 0 };
63956
+ const awaitingContent = [];
63957
+ const pagesRemaining = [];
63958
+ for (const p of plan.pages) {
63959
+ const status = p.status ?? "pending";
63960
+ pageByStatus[status] = (pageByStatus[status] ?? 0) + 1;
63961
+ if (status === "code")
63962
+ awaitingContent.push(p.path);
63963
+ if (status !== "done" && status !== "skipped") {
63964
+ pagesRemaining.push({ path: p.path, kind: p.kind, status });
63965
+ }
63966
+ }
63967
+ return {
63968
+ components: {
63969
+ total: plan.components.length,
63970
+ byStatus: compByStatus,
63971
+ settled,
63972
+ settledByStatus,
63973
+ accepted,
63974
+ remaining
63975
+ },
63976
+ pages: {
63977
+ total: plan.pages.length,
63978
+ byStatus: pageByStatus,
63979
+ awaitingContent,
63980
+ remaining: pagesRemaining
63981
+ }
63982
+ };
63983
+ }
63984
+ function joinUrl(base, path) {
63985
+ return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`.replace(/\/$/, "") || base;
63986
+ }
63987
+ function shellQuote(value) {
63988
+ return /^[\w./:=-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
63989
+ }
63990
+ function disposition(c) {
63991
+ if (c.status === "pending" || c.status === "partial")
63992
+ return "build";
63993
+ if (c.status === "skipped")
63994
+ return "settled";
63995
+ if (c.status === "as-is")
63996
+ return "as-is";
63997
+ if (c.verified)
63998
+ return "settled";
63999
+ if (c.status === "upgrade")
64000
+ return c.reference ? "validate" : "upgrade";
64001
+ return "validate";
64002
+ }
64003
+ function pagePlan(plan, path, candUrl) {
64004
+ const page = findPage(plan, path);
64005
+ if (!page)
64006
+ return null;
64007
+ const counts = {
64008
+ build: 0,
64009
+ validate: 0,
64010
+ upgrade: 0,
64011
+ "as-is": 0,
64012
+ settled: 0
64013
+ };
64014
+ let tasks = null;
64015
+ if (page.components) {
64016
+ tasks = [];
64017
+ for (const name of page.components) {
64018
+ const c = plan.components.find((row) => key(row.name) === key(name));
64019
+ if (!c)
64020
+ continue;
64021
+ const d = disposition(c);
64022
+ counts[d] += 1;
64023
+ const selector = c.reference?.selector ?? c.selector ?? null;
64024
+ const refUrl = c.reference?.url ?? plan.url;
64025
+ const kind = c.reference ? "reference" : "prod";
64026
+ const checkable = d === "validate" && Boolean(selector) && Boolean(candUrl);
64027
+ tasks.push({
64028
+ name: c.name,
64029
+ disposition: d,
64030
+ status: c.status,
64031
+ scope: c.scope ?? "page",
64032
+ origin: c.origin,
64033
+ selector,
64034
+ against: d === "validate" ? { url: refUrl, kind } : null,
64035
+ command: checkable && candUrl && selector ? `parity section --prod ${shellQuote(joinUrl(refUrl, page.path))} --cand ${shellQuote(joinUrl(candUrl, page.path))} --selector ${shellQuote(selector)}` : null,
64036
+ note: c.reference?.note ?? null
64037
+ });
64038
+ }
64039
+ }
64040
+ return {
64041
+ path: page.path,
64042
+ kind: page.kind,
64043
+ status: page.status ?? "pending",
64044
+ tasks,
64045
+ counts,
64046
+ ready: counts.build === 0 && counts.validate === 0
64047
+ };
64048
+ }
64049
+ function pageColumn(page) {
64050
+ if (page.status === "skipped")
64051
+ return "skipped";
64052
+ if (page.status === "done")
64053
+ return "done";
64054
+ if (page.tasks === null || page.tasks.length === 0)
64055
+ return "triage";
64056
+ if (page.ready)
64057
+ return "review";
64058
+ const started = page.counts.settled + page.counts.validate + page.counts["as-is"] + page.counts.upgrade;
64059
+ return started > 0 ? "building" : "backlog";
64060
+ }
64061
+ function planBoard(plan, candUrl) {
64062
+ const columns = {
64063
+ triage: [],
64064
+ backlog: [],
64065
+ building: [],
64066
+ review: [],
64067
+ done: [],
64068
+ skipped: []
64069
+ };
64070
+ for (const p of plan.pages) {
64071
+ const page = pagePlan(plan, p.path, candUrl);
64072
+ if (!page)
64073
+ continue;
64074
+ const column = pageColumn(page);
64075
+ columns[column].push({
64076
+ path: page.path,
64077
+ kind: page.kind,
64078
+ column,
64079
+ blockers: (page.tasks ?? []).filter((t) => t.disposition === "build" && t.scope !== "global").map((t) => t.name),
64080
+ counts: page.counts,
64081
+ ready: page.ready,
64082
+ boardItemId: p.boardItemId
64083
+ });
64084
+ }
64085
+ const onAnyPage = new Set(plan.pages.flatMap((p) => (p.components ?? []).map(key)));
64086
+ const shell = [];
64087
+ const unassigned = [];
64088
+ for (const c of plan.components) {
64089
+ if (c.scope === "global") {
64090
+ if (disposition(c) === "build")
64091
+ shell.push(c.name);
64092
+ } else if (!onAnyPage.has(key(c.name))) {
64093
+ unassigned.push(c.name);
64094
+ }
64095
+ }
64096
+ return { url: plan.url, columns, shell, unassigned, sampled: plan.pages.length };
64097
+ }
64098
+ function setComponentVerified(plan, name, verdict, at, note) {
64099
+ const k = key(name);
64100
+ const component = plan.components.find((c) => key(c.name) === k);
64101
+ if (!component)
64102
+ return null;
64103
+ const against = component.reference ? "reference" : "prod";
64104
+ component.verified = { at, verdict, against, ...note ? { note } : {} };
64105
+ return component;
64106
+ }
64107
+ function setComponentReference(plan, name, reference) {
64108
+ const k = key(name);
64109
+ const component = plan.components.find((c) => key(c.name) === k);
64110
+ if (!component)
64111
+ return null;
64112
+ component.reference = reference;
64113
+ return component;
64114
+ }
64115
+ function syntheticSourceComponents(plan) {
64116
+ return plan.components.filter((c) => c.origin === "source-only").map((c) => ({
64117
+ role: c.name,
64118
+ selector: "",
64119
+ html: "",
64120
+ computedStyles: null,
64121
+ screenshotPath: "",
64122
+ assets: { images: [], backgroundImages: [], fonts: [] },
64123
+ links: [],
64124
+ textContent: [],
64125
+ tailwind: [],
64126
+ interactions: [],
64127
+ scope: c.scope ?? "page",
64128
+ synthetic: true
64129
+ }));
64130
+ }
64131
+
64132
+ // src/migrate/aliases.ts
64133
+ var DIR_NOISE = new Set(["site", "src", "app", "components", "sections", "islands", "blocks"]);
64134
+ function fileSpellings(file) {
64135
+ const clean = file.replace(/^\.?\//, "");
64136
+ const segs = clean.split("/").filter(Boolean);
64137
+ const meaningful = segs.filter((s, i) => i === segs.length - 1 || !DIR_NOISE.has(s));
64138
+ const base = segs[segs.length - 1] ?? "";
64139
+ const stem = base.replace(/\.[jt]sx?$/, "");
64140
+ const out = [clean, meaningful.join("/"), base, stem];
64141
+ if (meaningful.length > 1)
64142
+ out.push(meaningful.slice(-2).join("/"));
64143
+ return out.filter(Boolean);
64144
+ }
64145
+ function buildLabelAliases(plan) {
64146
+ const claims = new Map;
64147
+ const claim = (spelling, canonical) => {
64148
+ if (!spelling || spelling === canonical)
64149
+ return;
64150
+ const set = claims.get(spelling) ?? new Set;
64151
+ set.add(canonical);
64152
+ claims.set(spelling, set);
64153
+ };
64154
+ for (const c of plan.components) {
64155
+ if (!c.name)
64156
+ continue;
64157
+ if (c.file)
64158
+ for (const s of fileSpellings(c.file))
64159
+ claim(s, c.name);
64160
+ if (c.selector)
64161
+ claim(c.selector.replace(/^\[data-[a-z-]+=["']?|["']?\]$/g, ""), c.name);
64162
+ }
64163
+ const out = new Map;
64164
+ for (const [spelling, canonicals] of claims) {
64165
+ const only = canonicals.size === 1 ? [...canonicals][0] : undefined;
64166
+ if (only)
64167
+ out.set(spelling, only);
64168
+ }
64169
+ return out;
64170
+ }
64171
+ function canonicalLabel(aliases, label) {
64172
+ return aliases?.get(label) ?? label;
64173
+ }
64174
+ function loadLabelAliases(dir) {
64175
+ const plan = loadPlan(dir);
64176
+ return { aliases: plan ? buildLabelAliases(plan) : new Map, plan };
64177
+ }
64178
+ function resolveAliases(planDir) {
64179
+ if (!planDir)
64180
+ return { aliases: new Map, note: null };
64181
+ const { aliases, plan } = loadLabelAliases(planDir);
64182
+ if (!plan) {
64183
+ return { aliases, note: `no migration-plan.json in ${planDir} — label pairing unchanged` };
64184
+ }
64185
+ return {
64186
+ aliases,
64187
+ note: `plan aliases: ${aliases.size} spelling${aliases.size === 1 ? "" : "s"} from ${plan.components.length} component rows`
64188
+ };
64189
+ }
64190
+
63640
64191
  // src/diff/box-tree.ts
63641
64192
  var STRUCTURAL_PROPS = new Set([
63642
64193
  "display",
@@ -63654,8 +64205,24 @@ var STRUCTURAL_PROPS = new Set([
63654
64205
  "grid-template-columns",
63655
64206
  "grid-template-rows"
63656
64207
  ]);
64208
+ var TYPE_PROPS = new Set([
64209
+ "font-size",
64210
+ "font-weight",
64211
+ "line-height",
64212
+ "letter-spacing",
64213
+ "text-transform",
64214
+ "text-align"
64215
+ ]);
64216
+ var TYPE_CHANGE_WEIGHT = 2000;
64217
+ var STRUCTURAL_CHANGE_WEIGHT = 1000;
63657
64218
  var VALUE_CHANGE_WEIGHT = 8;
63658
- var STRUCTURAL_CHANGE_WEIGHT = 40;
64219
+ var PX_WEIGHT_CEILING = 999;
64220
+ function pxWeight(deltaPx) {
64221
+ return Math.min(Math.abs(deltaPx), PX_WEIGHT_CEILING);
64222
+ }
64223
+ function isTypeChange(prop, node) {
64224
+ return TYPE_PROPS.has(prop) && Boolean(node.text);
64225
+ }
63659
64226
  function parsePx(value) {
63660
64227
  const v = value.trim();
63661
64228
  if (!v)
@@ -63673,49 +64240,215 @@ function indexByKey(nodes) {
63673
64240
  out.set(n.key, n);
63674
64241
  return out;
63675
64242
  }
63676
- function uniqueLabelIndex(nodes) {
63677
- const seen = new Map;
64243
+ function parentKey(key) {
64244
+ const i = key.lastIndexOf(">");
64245
+ return i < 0 ? null : key.slice(0, i);
64246
+ }
64247
+ var isHidden = (n) => n.styles.display === "none" || n.rect.width * n.rect.height === 0;
64248
+ var substantial = (n) => n.rect.width >= 8 && n.rect.height >= 8;
64249
+ function isVisuallyHidden(n) {
64250
+ const pos = n.styles.position;
64251
+ if (pos !== "absolute" && pos !== "fixed")
64252
+ return false;
64253
+ return n.rect.width <= 1 || n.rect.height <= 1;
64254
+ }
64255
+ function sameKindOfBox(p, c) {
64256
+ if (isHidden(p) !== isHidden(c) && (substantial(p) || substantial(c)))
64257
+ return false;
64258
+ if (Boolean(p.text) !== Boolean(c.text))
64259
+ return false;
64260
+ if (textsDisagree(p, c))
64261
+ return false;
64262
+ return true;
64263
+ }
64264
+ function contentTokens(n) {
64265
+ const out = new Set;
64266
+ for (const w of (n.text ?? "").toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
64267
+ if (w.length >= 3)
64268
+ out.add(w);
64269
+ }
64270
+ return out;
64271
+ }
64272
+ function textsDisagree(p, c) {
64273
+ const pt = contentTokens(p);
64274
+ if (pt.size === 0)
64275
+ return false;
64276
+ const ct = contentTokens(c);
64277
+ if (ct.size === 0)
64278
+ return false;
64279
+ for (const w of pt)
64280
+ if (ct.has(w))
64281
+ return false;
64282
+ return true;
64283
+ }
64284
+ function textAnchor(n) {
64285
+ const t = n.text?.trim();
64286
+ return t && t.length >= 3 ? t : null;
64287
+ }
64288
+ function uniqueIndex(nodes, keyOf) {
64289
+ const groups = new Map;
63678
64290
  for (const n of nodes) {
63679
- if (!n.label)
64291
+ const k = keyOf(n);
64292
+ if (!k)
63680
64293
  continue;
63681
- seen.set(n.label, seen.has(n.label) ? null : n);
64294
+ const list = groups.get(k) ?? [];
64295
+ list.push(n);
64296
+ groups.set(k, list);
63682
64297
  }
63683
64298
  const out = new Map;
63684
- for (const [k, v] of seen)
63685
- if (v)
63686
- out.set(k, v);
64299
+ for (const [k, list] of groups) {
64300
+ const innermost = list.filter((n) => !list.some((o) => o !== n && o.key.startsWith(`${n.key}>`)));
64301
+ const only = innermost.length === 1 ? innermost[0] : undefined;
64302
+ if (only)
64303
+ out.set(k, only);
64304
+ }
63687
64305
  return out;
63688
64306
  }
63689
- function alignBoxTrees(prod, cand) {
63690
- const candByKey = indexByKey(cand);
64307
+ function anchorPairs(prod, cand, aliases, usedP, usedC) {
64308
+ const keys = [
64309
+ (n) => parentKey(n.key) ? null : VIRTUAL_ROOT,
64310
+ (n) => n.label ? canonicalLabel(aliases, n.label) : null,
64311
+ textAnchor
64312
+ ];
63691
64313
  const pairs = [];
63692
- const usedCand = new Set;
63693
- const leftoverProd = [];
63694
- for (const p of prod) {
63695
- const c = candByKey.get(p.key);
63696
- if (c && !usedCand.has(c)) {
64314
+ for (const keyOf of keys) {
64315
+ const pi = uniqueIndex(prod.filter((n) => !usedP.has(n)), keyOf);
64316
+ const ci = uniqueIndex(cand.filter((n) => !usedC.has(n)), keyOf);
64317
+ for (const [k, p] of pi) {
64318
+ const c = ci.get(k);
64319
+ if (!c || usedC.has(c))
64320
+ continue;
63697
64321
  pairs.push([p, c]);
63698
- usedCand.add(c);
63699
- } else {
63700
- leftoverProd.push(p);
64322
+ usedP.add(p);
64323
+ usedC.add(c);
63701
64324
  }
63702
64325
  }
63703
- const leftoverCand = cand.filter((c) => !usedCand.has(c));
63704
- const candByLabel = uniqueLabelIndex(leftoverCand);
63705
- const stillProd = [];
63706
- for (const p of leftoverProd) {
63707
- const c = p.label ? candByLabel.get(p.label) : undefined;
63708
- if (c && !usedCand.has(c)) {
63709
- pairs.push([p, c]);
63710
- usedCand.add(c);
63711
- } else {
63712
- stillProd.push(p);
64326
+ return pairs;
64327
+ }
64328
+ var VIRTUAL_ROOT = "\x00root";
64329
+ function childIndex(nodes) {
64330
+ const present = new Set(nodes.map((n) => n.key));
64331
+ const out = new Map;
64332
+ for (const n of nodes) {
64333
+ const parent = parentKey(n.key);
64334
+ const pk = parent && present.has(parent) ? parent : VIRTUAL_ROOT;
64335
+ const list = out.get(pk) ?? [];
64336
+ list.push(n);
64337
+ out.set(pk, list);
64338
+ }
64339
+ return out;
64340
+ }
64341
+ function propagateAnchors(anchors, prodByKey, candByKey, usedP, usedC) {
64342
+ const prodKids = childIndex([...prodByKey.values()]);
64343
+ const candKids = childIndex([...candByKey.values()]);
64344
+ const claims = [];
64345
+ for (const [ap, ac] of anchors) {
64346
+ let p = ap;
64347
+ let c = ac;
64348
+ for (let dist = 1;; dist++) {
64349
+ const pk = parentKey(p.key);
64350
+ const ck = parentKey(c.key);
64351
+ if (!pk || !ck)
64352
+ break;
64353
+ const pp = prodByKey.get(pk);
64354
+ const cc = candByKey.get(ck);
64355
+ if (!pp || !cc || pp.tag !== cc.tag || !sameKindOfBox(pp, cc))
64356
+ break;
64357
+ claims.push({ p: pp, c: cc, dist });
64358
+ p = pp;
64359
+ c = cc;
64360
+ }
64361
+ p = ap;
64362
+ c = ac;
64363
+ for (let dist = 1;; dist++) {
64364
+ const pp = prodKids.get(p.key);
64365
+ const cc = candKids.get(c.key);
64366
+ if (pp?.length !== 1 || cc?.length !== 1)
64367
+ break;
64368
+ const [pn] = pp;
64369
+ const [cn] = cc;
64370
+ if (!pn || !cn || pn.tag !== cn.tag || !sameKindOfBox(pn, cn))
64371
+ break;
64372
+ claims.push({ p: pn, c: cn, dist });
64373
+ p = pn;
64374
+ c = cn;
64375
+ }
64376
+ }
64377
+ const disputed = new Set;
64378
+ const partners = new Map;
64379
+ for (const { p, c, dist } of claims) {
64380
+ for (const [a, b] of [
64381
+ [`p:${p.key}:${dist}`, c.key],
64382
+ [`c:${c.key}:${dist}`, p.key]
64383
+ ]) {
64384
+ const set = partners.get(a) ?? new Set;
64385
+ set.add(b);
64386
+ partners.set(a, set);
64387
+ if (set.size > 1)
64388
+ disputed.add(a);
64389
+ }
64390
+ }
64391
+ claims.sort((a, b) => a.dist - b.dist);
64392
+ const pairs = [];
64393
+ for (const { p, c, dist } of claims) {
64394
+ if (usedP.has(p) || usedC.has(c))
64395
+ continue;
64396
+ if (disputed.has(`p:${p.key}:${dist}`) || disputed.has(`c:${c.key}:${dist}`))
64397
+ continue;
64398
+ pairs.push([p, c]);
64399
+ usedP.add(p);
64400
+ usedC.add(c);
64401
+ }
64402
+ return pairs;
64403
+ }
64404
+ function alignBoxTrees(prod, cand, aliases) {
64405
+ const prodByKey = indexByKey(prod);
64406
+ const candByKey = indexByKey(cand);
64407
+ const usedP = new Set;
64408
+ const usedC = new Set;
64409
+ const anchors = anchorPairs(prod, cand, aliases, usedP, usedC);
64410
+ const pairs = [
64411
+ ...anchors,
64412
+ ...propagateAnchors(anchors, prodByKey, candByKey, usedP, usedC)
64413
+ ];
64414
+ const lastSegment = (key) => key.slice(key.lastIndexOf(">") + 1);
64415
+ const prodKids = childIndex(prod);
64416
+ const candKids = childIndex(cand);
64417
+ const queue = [
64418
+ [VIRTUAL_ROOT, VIRTUAL_ROOT],
64419
+ ...pairs.map(([p, c]) => [p.key, c.key])
64420
+ ];
64421
+ for (let i = 0;i < queue.length; i++) {
64422
+ const at = queue[i];
64423
+ if (!at)
64424
+ continue;
64425
+ const [pKey, cKey] = at;
64426
+ const kids = prodKids.get(pKey);
64427
+ const candSiblings = candKids.get(cKey);
64428
+ if (!kids || !candSiblings)
64429
+ continue;
64430
+ const bySegment = new Map;
64431
+ for (const n of candSiblings)
64432
+ if (!usedC.has(n))
64433
+ bySegment.set(lastSegment(n.key), n);
64434
+ for (const pn of kids) {
64435
+ if (usedP.has(pn))
64436
+ continue;
64437
+ const cn = bySegment.get(lastSegment(pn.key));
64438
+ if (!cn || usedC.has(cn))
64439
+ continue;
64440
+ if (!sameKindOfBox(pn, cn))
64441
+ continue;
64442
+ pairs.push([pn, cn]);
64443
+ usedP.add(pn);
64444
+ usedC.add(cn);
64445
+ queue.push([pn.key, cn.key]);
63713
64446
  }
63714
64447
  }
63715
64448
  return {
63716
64449
  pairs,
63717
- onlyInProd: stillProd,
63718
- onlyInCand: cand.filter((c) => !usedCand.has(c))
64450
+ onlyInProd: prod.filter((p) => !usedP.has(p)),
64451
+ onlyInCand: cand.filter((c) => !usedC.has(c))
63719
64452
  };
63720
64453
  }
63721
64454
  function rectProps(n) {
@@ -63729,9 +64462,22 @@ function rectProps(n) {
63729
64462
  function diffBoxTrees(prod, cand, opts = {}) {
63730
64463
  const tolerancePx = opts.tolerancePx ?? 1;
63731
64464
  const maxDeltas = opts.maxDeltas ?? 200;
63732
- const { pairs, onlyInProd, onlyInCand } = alignBoxTrees(prod, cand);
64465
+ const { pairs, onlyInProd, onlyInCand } = alignBoxTrees(prod, cand, opts.aliases);
63733
64466
  const deltas = [];
63734
64467
  for (const [p, c] of pairs) {
64468
+ if (isVisuallyHidden(p) !== isVisuallyHidden(c)) {
64469
+ const hiddenOnProd = isVisuallyHidden(p);
64470
+ deltas.push({
64471
+ key: p.key,
64472
+ label: p.label,
64473
+ prop: "visually-hidden",
64474
+ prod: hiddenOnProd ? "yes" : "no",
64475
+ cand: hiddenOnProd ? "no" : "yes",
64476
+ deltaPx: null,
64477
+ weight: STRUCTURAL_CHANGE_WEIGHT
64478
+ });
64479
+ continue;
64480
+ }
63735
64481
  const pAll = { ...p.styles, ...rectProps(p) };
63736
64482
  const cAll = { ...c.styles, ...rectProps(c) };
63737
64483
  for (const prop of Object.keys(pAll)) {
@@ -63752,10 +64498,11 @@ function diffBoxTrees(prod, cand, opts = {}) {
63752
64498
  prod: a,
63753
64499
  cand: b,
63754
64500
  deltaPx: d,
63755
- weight: Math.abs(d)
64501
+ weight: isTypeChange(prop, p) ? TYPE_CHANGE_WEIGHT + pxWeight(d) : pxWeight(d)
63756
64502
  });
63757
64503
  continue;
63758
64504
  }
64505
+ const weight = isTypeChange(prop, p) ? TYPE_CHANGE_WEIGHT : STRUCTURAL_PROPS.has(prop) ? STRUCTURAL_CHANGE_WEIGHT : VALUE_CHANGE_WEIGHT;
63759
64506
  deltas.push({
63760
64507
  key: p.key,
63761
64508
  label: p.label,
@@ -63763,25 +64510,39 @@ function diffBoxTrees(prod, cand, opts = {}) {
63763
64510
  prod: a || "(empty)",
63764
64511
  cand: b || "(empty)",
63765
64512
  deltaPx: null,
63766
- weight: STRUCTURAL_PROPS.has(prop) ? STRUCTURAL_CHANGE_WEIGHT : VALUE_CHANGE_WEIGHT
64513
+ weight
63767
64514
  });
63768
64515
  }
63769
64516
  }
63770
64517
  deltas.sort((x, y) => y.weight - x.weight || x.key.localeCompare(y.key) || x.prop.localeCompare(y.prop));
63771
- const brief = (n) => ({ key: n.key, label: n.label, tag: n.tag });
64518
+ const pairedKeys = { prod: pairs.map(([p]) => p.key), cand: pairs.map(([, c]) => c.key) };
64519
+ const brief = (side) => (n) => ({
64520
+ key: n.key,
64521
+ label: n.label,
64522
+ tag: n.tag,
64523
+ contentsPaired: pairedKeys[side].some((k) => k.startsWith(`${n.key}>`))
64524
+ });
63772
64525
  return {
63773
64526
  matched: pairs.length,
63774
- onlyInProd: onlyInProd.map(brief),
63775
- onlyInCand: onlyInCand.map(brief),
64527
+ onlyInProd: onlyInProd.map(brief("prod")),
64528
+ onlyInCand: onlyInCand.map(brief("cand")),
63776
64529
  deltas: deltas.slice(0, maxDeltas),
63777
64530
  truncated: opts.truncated ?? false
63778
64531
  };
63779
64532
  }
64533
+ function isBoxTreeInconclusive(diff) {
64534
+ const prodNodes = diff.matched + diff.onlyInProd.length;
64535
+ const candNodes = diff.matched + diff.onlyInCand.length;
64536
+ return prodNodes <= 1 && candNodes <= 1 && diff.deltas.length === 0;
64537
+ }
63780
64538
  function isGeometryClean(diff) {
63781
- return diff.deltas.length === 0 && diff.onlyInProd.length === 0 && diff.onlyInCand.length === 0;
64539
+ return !isBoxTreeInconclusive(diff) && diff.deltas.length === 0 && diff.onlyInProd.length === 0 && diff.onlyInCand.length === 0;
63782
64540
  }
63783
64541
  function formatBoxTreeDiff(diff, opts = {}) {
63784
64542
  const limit = opts.limit ?? 40;
64543
+ if (isBoxTreeInconclusive(diff)) {
64544
+ return `geometry: INCONCLUSIVE — ${diff.matched} node(s) paired, so nothing was compared. Check that both selectors match something with content.`;
64545
+ }
63785
64546
  if (isGeometryClean(diff)) {
63786
64547
  return `geometry: clean (${diff.matched} nodes matched)${diff.truncated ? " — TRUNCATED, absence is not proof" : ""}`;
63787
64548
  }
@@ -63797,12 +64558,11 @@ function formatBoxTreeDiff(diff, opts = {}) {
63797
64558
  if (diff.deltas.length > shown.length) {
63798
64559
  lines.push(`… ${diff.deltas.length - shown.length} more`);
63799
64560
  }
63800
- for (const n of diff.onlyInProd) {
63801
- lines.push(`${n.key.padEnd(keyW)} ${"—".padEnd(propW)} only in prod${n.label ? ` (${n.label})` : ""}`);
63802
- }
63803
- for (const n of diff.onlyInCand) {
63804
- lines.push(`${n.key.padEnd(keyW)} ${"—".padEnd(propW)} only in cand${n.label ? ` (${n.label})` : ""}`);
63805
- }
64561
+ const unmatched = (n, side) => `${n.key.padEnd(keyW)} ${"—".padEnd(propW)} ${n.contentsPaired ? `wrapper only in ${side} — its contents paired` : `only in ${side}`}${n.label ? ` (${n.label})` : ""}`;
64562
+ for (const n of diff.onlyInProd)
64563
+ lines.push(unmatched(n, "prod"));
64564
+ for (const n of diff.onlyInCand)
64565
+ lines.push(unmatched(n, "cand"));
63806
64566
  if (diff.truncated)
63807
64567
  lines.push("TRUNCATED — node cap hit; absence of a delta is not proof");
63808
64568
  return lines.join(`
@@ -63858,6 +64618,8 @@ var BOX_TREE_KEYS = [
63858
64618
  "transform"
63859
64619
  ];
63860
64620
  var LABEL_ATTRS = ["data-section", "data-testid", "data-fs-section", "data-manifest-key", "id"];
64621
+ var GENERATED_ID = /^(?::[rR][0-9a-zA-Z]*:|_[rR]_[0-9a-zA-Z_]*_)$/;
64622
+ var NON_RENDERED = ["script", "style", "link", "meta", "template", "noscript", "title", "head"];
63861
64623
  async function readBoxTree(page, selector, opts = {}) {
63862
64624
  const maxDepth = opts.maxDepth ?? 12;
63863
64625
  const maxNodes = opts.maxNodes ?? 400;
@@ -63874,7 +64636,7 @@ async function readBoxTree(page, selector, opts = {}) {
63874
64636
  }
63875
64637
  let got;
63876
64638
  try {
63877
- got = await page.evaluate(({ sel, keys, maxDepth, maxNodes, skipZeroArea, labelAttrs }) => {
64639
+ got = await page.evaluate(({ sel, keys, maxDepth, maxNodes, skipZeroArea, labelAttrs, skipTags, generatedIdPattern }) => {
63878
64640
  try {
63879
64641
  const root = document.querySelector(sel);
63880
64642
  if (!root || !(root instanceof HTMLElement)) {
@@ -63883,14 +64645,19 @@ async function readBoxTree(page, selector, opts = {}) {
63883
64645
  const origin = root.getBoundingClientRect();
63884
64646
  const nodes = [];
63885
64647
  let truncated = false;
64648
+ const generatedId = new RegExp(generatedIdPattern);
63886
64649
  const labelOf = (el) => {
63887
64650
  for (const a of labelAttrs) {
63888
64651
  const v = el.getAttribute(a);
63889
- if (v)
63890
- return v;
64652
+ if (!v)
64653
+ continue;
64654
+ if (a === "id" && generatedId.test(v))
64655
+ continue;
64656
+ return v;
63891
64657
  }
63892
64658
  return null;
63893
64659
  };
64660
+ const skip = new Set(skipTags);
63894
64661
  const walk = (el, path, depth) => {
63895
64662
  if (nodes.length >= maxNodes) {
63896
64663
  truncated = true;
@@ -63927,6 +64694,8 @@ async function readBoxTree(page, selector, opts = {}) {
63927
64694
  const perTag = {};
63928
64695
  for (const child of Array.from(el.children)) {
63929
64696
  const t = child.tagName.toLowerCase();
64697
+ if (skip.has(t))
64698
+ continue;
63930
64699
  const i = perTag[t] ?? 0;
63931
64700
  perTag[t] = i + 1;
63932
64701
  walk(child, `${path}>${t}[${i}]`, depth + 1);
@@ -63940,7 +64709,16 @@ async function readBoxTree(page, selector, opts = {}) {
63940
64709
  reason: `walk falhou em '${sel}': ${err.message ?? "unknown"}`
63941
64710
  };
63942
64711
  }
63943
- }, { sel: selector, keys, maxDepth, maxNodes, skipZeroArea, labelAttrs: LABEL_ATTRS });
64712
+ }, {
64713
+ sel: selector,
64714
+ keys,
64715
+ maxDepth,
64716
+ maxNodes,
64717
+ skipZeroArea,
64718
+ labelAttrs: LABEL_ATTRS,
64719
+ skipTags: NON_RENDERED,
64720
+ generatedIdPattern: GENERATED_ID.source
64721
+ });
63944
64722
  } catch (err) {
63945
64723
  return {
63946
64724
  found: false,
@@ -63994,6 +64772,9 @@ async function sectionCommand(opts) {
63994
64772
  cand: resolve3(opts.outDir, `${filePrefix}-cand.png`)
63995
64773
  };
63996
64774
  const heatmapPath = resolve3(opts.outDir, `${filePrefix}-heatmap.png`);
64775
+ const { aliases, note: aliasNote } = resolveAliases(opts.planDir);
64776
+ if (aliasNote)
64777
+ console.log(chalk14.dim(` ${aliasNote}`));
63997
64778
  const browser = await launchBrowser({ headless: true });
63998
64779
  try {
63999
64780
  const [prodSide, candSide] = await Promise.all([
@@ -64023,7 +64804,7 @@ async function sectionCommand(opts) {
64023
64804
  })
64024
64805
  ]);
64025
64806
  const heatmap = want.heatmap ? computeHeatmap(prodSide, candSide, screenshotPaths, heatmapPath) : null;
64026
- const boxTree = computeBoxTreeDiff(prodSide, candSide);
64807
+ const boxTree = computeBoxTreeDiff(prodSide, candSide, aliases);
64027
64808
  const bundlePaths = want.prompt ? await buildPromptBundle({
64028
64809
  opts,
64029
64810
  viewport,
@@ -64064,6 +64845,14 @@ async function sectionCommand(opts) {
64064
64845
  await printResults2({ opts, viewport, candSelector, prodSide, candSide, screenshotPaths, want });
64065
64846
  if (boxTree)
64066
64847
  printBoxTree(boxTree);
64848
+ for (const [side, data] of [
64849
+ ["prod", prodSide],
64850
+ ["cand", candSide]
64851
+ ]) {
64852
+ const caveat = data.settle && formatSettleCaveat(side, data.settle);
64853
+ if (caveat)
64854
+ console.log(chalk14.yellow(` ${caveat}`));
64855
+ }
64067
64856
  if (heatmap)
64068
64857
  printHeatmap(heatmap, heatmapPath);
64069
64858
  if (bundlePaths)
@@ -64077,7 +64866,7 @@ async function sectionCommand(opts) {
64077
64866
  });
64078
64867
  }
64079
64868
  }
64080
- function computeBoxTreeDiff(prodSide, candSide) {
64869
+ function computeBoxTreeDiff(prodSide, candSide, aliases) {
64081
64870
  const p = prodSide.boxTree;
64082
64871
  const c = candSide.boxTree;
64083
64872
  if (!p || !c)
@@ -64086,7 +64875,7 @@ function computeBoxTreeDiff(prodSide, candSide) {
64086
64875
  return { error: `prod: ${p.error}` };
64087
64876
  if (!c.found)
64088
64877
  return { error: `cand: ${c.error}` };
64089
- return diffBoxTrees(p.nodes, c.nodes, { truncated: p.truncated || c.truncated });
64878
+ return diffBoxTrees(p.nodes, c.nodes, { truncated: p.truncated || c.truncated, aliases });
64090
64879
  }
64091
64880
  function printBoxTree(result) {
64092
64881
  console.log("");
@@ -64115,6 +64904,8 @@ async function gatherSide(browser, opts) {
64115
64904
  });
64116
64905
  if (opts.waitMs > 0)
64117
64906
  await page.waitForTimeout(opts.waitMs);
64907
+ await reloadIfOptionalFonts(page, opts.waitMs);
64908
+ result.settle = await waitForLayoutStable(page);
64118
64909
  await Promise.race([
64119
64910
  stabilizeCarousels(page).catch(() => {
64120
64911
  return;
@@ -64955,8 +65746,8 @@ function formatPatch(patch) {
64955
65746
  }
64956
65747
 
64957
65748
  // src/commands/journey.ts
64958
- import { writeFileSync as writeFileSync21 } from "node:fs";
64959
- import { join as join25 } from "node:path";
65749
+ import { writeFileSync as writeFileSync22 } from "node:fs";
65750
+ import { join as join26 } from "node:path";
64960
65751
  import chalk17 from "chalk";
64961
65752
  import ora7 from "ora";
64962
65753
  init_client();
@@ -65026,7 +65817,7 @@ async function journeyCommand(opts) {
65026
65817
  };
65027
65818
  async function runOneSide(browserInstance, viewport, side) {
65028
65819
  const baseUrl = side === "prod" ? opts.prod : opts.cand;
65029
- const tracePath = join25(paths.tracesDir, `${viewport}-${side}.zip`);
65820
+ const tracePath = join26(paths.tracesDir, `${viewport}-${side}.zip`);
65030
65821
  const ctx = await newContext(browserInstance, {
65031
65822
  viewport,
65032
65823
  tracesDir: paths.tracesDir,
@@ -65118,7 +65909,7 @@ async function journeyCommand(opts) {
65118
65909
  if (opts.github)
65119
65910
  emitGithubAnnotations(failures);
65120
65911
  if (opts.junit) {
65121
- writeFileSync21(opts.junit, buildJUnit(rows, failures), "utf8");
65912
+ writeFileSync22(opts.junit, buildJUnit(rows, failures), "utf8");
65122
65913
  if (!opts.json)
65123
65914
  console.log(chalk17.dim(` → JUnit XML: ${opts.junit}`));
65124
65915
  }
@@ -65666,19 +66457,19 @@ async function nodeFetchText(url) {
65666
66457
  }
65667
66458
 
65668
66459
  // src/migrate/exporters/json.ts
65669
- import { writeFileSync as writeFileSync22 } from "node:fs";
65670
- import { join as join26 } from "node:path";
66460
+ import { writeFileSync as writeFileSync23 } from "node:fs";
66461
+ import { join as join27 } from "node:path";
65671
66462
  var jsonExporter2 = {
65672
66463
  name: "json",
65673
66464
  async export(bundle, outDir) {
65674
- writeFileSync22(join26(outDir, "manifest.json"), `${JSON.stringify(bundle, null, 2)}
66465
+ writeFileSync23(join27(outDir, "manifest.json"), `${JSON.stringify(bundle, null, 2)}
65675
66466
  `, "utf8");
65676
66467
  }
65677
66468
  };
65678
66469
 
65679
66470
  // src/migrate/exporters/markdown.ts
65680
- import { mkdirSync as mkdirSync16, writeFileSync as writeFileSync23 } from "node:fs";
65681
- import { join as join27 } from "node:path";
66471
+ import { mkdirSync as mkdirSync16, writeFileSync as writeFileSync24 } from "node:fs";
66472
+ import { join as join28 } from "node:path";
65682
66473
  var markdownExporter2 = {
65683
66474
  name: "markdown",
65684
66475
  async export(bundle, outDir) {
@@ -65686,16 +66477,16 @@ var markdownExporter2 = {
65686
66477
  const notes = [];
65687
66478
  bundle.components.forEach((component, i) => {
65688
66479
  const dirName = dirNames[i];
65689
- const componentDir = join27(outDir, "components", dirName);
66480
+ const componentDir = join28(outDir, "components", dirName);
65690
66481
  mkdirSync16(componentDir, { recursive: true });
65691
66482
  const compact = compactComponentHtml(component.html);
65692
66483
  if (compact.collapsed > 0)
65693
66484
  notes.push(`\`${dirName}\`: collapsed ${compact.collapsed} repeated child element(s)`);
65694
66485
  if (compact.truncated)
65695
66486
  notes.push(`\`${dirName}\`: HTML truncated to fit the per-component token ceiling`);
65696
- writeFileSync23(join27(componentDir, "README.md"), renderComponentReadme2(bundle.url, component, compact.html), "utf8");
66487
+ writeFileSync24(join28(componentDir, "README.md"), renderComponentReadme2(bundle.url, component, compact.html), "utf8");
65697
66488
  });
65698
- writeFileSync23(join27(outDir, "index.md"), renderIndex2(bundle, notes), "utf8");
66489
+ writeFileSync24(join28(outDir, "index.md"), renderIndex2(bundle, notes), "utf8");
65699
66490
  }
65700
66491
  };
65701
66492
  function renderIndex2(bundle, notes) {
@@ -65897,8 +66688,8 @@ function escapePipes2(s) {
65897
66688
  }
65898
66689
 
65899
66690
  // src/migrate/exporters/html.ts
65900
- import { readFileSync as readFileSync21, writeFileSync as writeFileSync24 } from "node:fs";
65901
- import { join as join28 } from "node:path";
66691
+ import { readFileSync as readFileSync22, writeFileSync as writeFileSync25 } from "node:fs";
66692
+ import { join as join29 } from "node:path";
65902
66693
 
65903
66694
  // src/migrate/targets/faststore-v4.ts
65904
66695
  function pickBreakpointTiers(breakpoints) {
@@ -66218,9 +67009,9 @@ var TARGET_NAMES = Object.keys(TARGETS);
66218
67009
  var htmlExporter = {
66219
67010
  name: "html",
66220
67011
  async export(bundle, outDir) {
66221
- writeFileSync24(join28(outDir, "index.html"), renderHtml(bundle, (p) => p ?? null), "utf8");
66222
- const inline = (p) => p ? dataUri2(join28(outDir, p)) ?? p : null;
66223
- writeFileSync24(join28(outDir, "report.html"), renderHtml(bundle, inline), "utf8");
67012
+ writeFileSync25(join29(outDir, "index.html"), renderHtml(bundle, (p) => p ?? null), "utf8");
67013
+ const inline = (p) => p ? dataUri2(join29(outDir, p)) ?? p : null;
67014
+ writeFileSync25(join29(outDir, "report.html"), renderHtml(bundle, inline), "utf8");
66224
67015
  }
66225
67016
  };
66226
67017
  var MIME2 = {
@@ -66238,7 +67029,7 @@ function dataUri2(absPath) {
66238
67029
  const mime = MIME2[ext];
66239
67030
  if (!mime)
66240
67031
  return null;
66241
- return `data:${mime};base64,${readFileSync21(absPath).toString("base64")}`;
67032
+ return `data:${mime};base64,${readFileSync22(absPath).toString("base64")}`;
66242
67033
  } catch {
66243
67034
  return null;
66244
67035
  }
@@ -66486,353 +67277,6 @@ function buildMigrationPrompt(bundle, playbook, source) {
66486
67277
  `);
66487
67278
  }
66488
67279
 
66489
- // src/migrate/plan.ts
66490
- import { existsSync as existsSync16, readFileSync as readFileSync22, writeFileSync as writeFileSync25 } from "node:fs";
66491
- import { join as join29 } from "node:path";
66492
- function dedupe(names) {
66493
- return [...new Set(names)];
66494
- }
66495
- function key(name) {
66496
- return name.toLowerCase().replace(/[\s_/-]+/g, "");
66497
- }
66498
- function buildMigrationPlan(input) {
66499
- const { bundle, source, inventory } = input;
66500
- const liveByKey = new Map;
66501
- for (const c of bundle.components) {
66502
- liveByKey.set(key(c.role), { role: c.role, scope: c.scope, selector: c.selector });
66503
- }
66504
- const srcByKey = new Map;
66505
- for (const c of inventory.components)
66506
- srcByKey.set(key(c.name), c);
66507
- const components = [];
66508
- for (const [k, c] of srcByKey) {
66509
- components.push({
66510
- name: c.name,
66511
- role: c.role,
66512
- scope: c.scope,
66513
- origin: liveByKey.has(k) ? "both" : "source-only",
66514
- status: "pending",
66515
- file: c.file,
66516
- selector: liveByKey.get(k)?.selector ?? null,
66517
- reference: null,
66518
- verified: null
66519
- });
66520
- }
66521
- for (const [k, c] of liveByKey) {
66522
- if (srcByKey.has(k))
66523
- continue;
66524
- components.push({
66525
- name: c.role,
66526
- role: c.role,
66527
- scope: c.scope,
66528
- origin: "live-only",
66529
- status: "pending",
66530
- file: null,
66531
- selector: c.selector,
66532
- reference: null,
66533
- verified: null
66534
- });
66535
- }
66536
- return {
66537
- url: bundle.url,
66538
- timestamp: bundle.timestamp,
66539
- source: {
66540
- kind: source.kind,
66541
- label: source.label,
66542
- dir: source.dir,
66543
- notes: inventory.notes,
66544
- ...input.searched ? { searched: input.searched } : {},
66545
- ...input.project ? { project: input.project } : {}
66546
- },
66547
- target: { name: bundle.target ?? null },
66548
- pages: bundle.pages.map((p) => ({
66549
- path: p.path,
66550
- kind: p.kind,
66551
- status: "pending",
66552
- components: dedupe((p.components ?? []).map((c) => components.find((row) => key(row.name) === key(c.role))?.name ?? c.role))
66553
- })),
66554
- components
66555
- };
66556
- }
66557
- function mergePlanDecisions(fresh, previous) {
66558
- if (!previous)
66559
- return { plan: fresh, carried: [], droppedWithDecisions: [] };
66560
- const prevByKey = new Map(previous.components.map((c) => [key(c.name), c]));
66561
- const carried = [];
66562
- for (const row of fresh.components) {
66563
- const prev = prevByKey.get(key(row.name));
66564
- if (!prev)
66565
- continue;
66566
- if (prev.status !== "pending")
66567
- row.status = prev.status;
66568
- if (prev.reference)
66569
- row.reference = prev.reference;
66570
- if (prev.verified)
66571
- row.verified = prev.verified;
66572
- if (prev.status !== "pending" || prev.reference || prev.verified)
66573
- carried.push(row.name);
66574
- }
66575
- const freshKeys = new Set(fresh.components.map((c) => key(c.name)));
66576
- const droppedWithDecisions = previous.components.filter((c) => !freshKeys.has(key(c.name))).filter((c) => c.status !== "pending" || Boolean(c.reference) || Boolean(c.verified)).map((c) => c.name);
66577
- const prevPages = new Map(previous.pages.map((p) => [p.path, p]));
66578
- for (const page of fresh.pages) {
66579
- const prev = prevPages.get(page.path);
66580
- if (prev?.status && prev.status !== "pending")
66581
- page.status = prev.status;
66582
- if (prev?.boardItemId)
66583
- page.boardItemId = prev.boardItemId;
66584
- }
66585
- return { plan: fresh, carried, droppedWithDecisions };
66586
- }
66587
- var PLAN_FILE = "migration-plan.json";
66588
- var SETTLED = new Set(["done", "as-is", "upgrade", "skipped"]);
66589
- function loadPlan(dir) {
66590
- const p = join29(dir, PLAN_FILE);
66591
- if (!existsSync16(p))
66592
- return null;
66593
- return JSON.parse(readFileSync22(p, "utf8"));
66594
- }
66595
- function savePlan(dir, plan) {
66596
- writeFileSync25(join29(dir, PLAN_FILE), `${JSON.stringify(plan, null, 2)}
66597
- `, "utf8");
66598
- }
66599
- function setComponentStatus(plan, name, status) {
66600
- const k = key(name);
66601
- const component = plan.components.find((c) => key(c.name) === k);
66602
- if (!component)
66603
- return null;
66604
- component.status = status;
66605
- return component;
66606
- }
66607
- function setPageStatus(plan, path, status) {
66608
- const page = findPage(plan, path);
66609
- if (!page)
66610
- return null;
66611
- page.status = status;
66612
- return page;
66613
- }
66614
- function findPage(plan, path) {
66615
- const norm = (p) => `/${p.trim().replace(/^\/+|\/+$/g, "")}` || "/";
66616
- const target = norm(path);
66617
- return plan.pages.find((p) => p.path === path) ?? plan.pages.find((p) => norm(p.path) === target) ?? null;
66618
- }
66619
- function setPageBoardItemId(plan, path, boardItemId) {
66620
- const page = findPage(plan, path);
66621
- if (!page)
66622
- return null;
66623
- page.boardItemId = boardItemId;
66624
- return page;
66625
- }
66626
- function planProgress(plan) {
66627
- const compByStatus = {
66628
- pending: 0,
66629
- partial: 0,
66630
- done: 0,
66631
- "as-is": 0,
66632
- upgrade: 0,
66633
- skipped: 0
66634
- };
66635
- const settled = [];
66636
- const settledByStatus = { done: [], skipped: [] };
66637
- const accepted = { asIs: [], upgrade: [] };
66638
- const remaining = [];
66639
- for (const c of plan.components) {
66640
- compByStatus[c.status] = (compByStatus[c.status] ?? 0) + 1;
66641
- if (c.status === "as-is")
66642
- accepted.asIs.push(c.name);
66643
- if (c.status === "upgrade")
66644
- accepted.upgrade.push(c.name);
66645
- if (c.status === "done")
66646
- settledByStatus.done.push(c.name);
66647
- if (c.status === "skipped")
66648
- settledByStatus.skipped.push(c.name);
66649
- if (SETTLED.has(c.status))
66650
- settled.push(c.name);
66651
- else
66652
- remaining.push({
66653
- name: c.name,
66654
- status: c.status,
66655
- scope: c.scope ?? "page",
66656
- origin: c.origin
66657
- });
66658
- }
66659
- const pageByStatus = { pending: 0, code: 0, done: 0, skipped: 0 };
66660
- const awaitingContent = [];
66661
- const pagesRemaining = [];
66662
- for (const p of plan.pages) {
66663
- const status = p.status ?? "pending";
66664
- pageByStatus[status] = (pageByStatus[status] ?? 0) + 1;
66665
- if (status === "code")
66666
- awaitingContent.push(p.path);
66667
- if (status !== "done" && status !== "skipped") {
66668
- pagesRemaining.push({ path: p.path, kind: p.kind, status });
66669
- }
66670
- }
66671
- return {
66672
- components: {
66673
- total: plan.components.length,
66674
- byStatus: compByStatus,
66675
- settled,
66676
- settledByStatus,
66677
- accepted,
66678
- remaining
66679
- },
66680
- pages: {
66681
- total: plan.pages.length,
66682
- byStatus: pageByStatus,
66683
- awaitingContent,
66684
- remaining: pagesRemaining
66685
- }
66686
- };
66687
- }
66688
- function joinUrl(base, path) {
66689
- return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`.replace(/\/$/, "") || base;
66690
- }
66691
- function shellQuote(value) {
66692
- return /^[\w./:=-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
66693
- }
66694
- function disposition(c) {
66695
- if (c.status === "pending" || c.status === "partial")
66696
- return "build";
66697
- if (c.status === "skipped")
66698
- return "settled";
66699
- if (c.status === "as-is")
66700
- return "as-is";
66701
- if (c.verified)
66702
- return "settled";
66703
- if (c.status === "upgrade")
66704
- return c.reference ? "validate" : "upgrade";
66705
- return "validate";
66706
- }
66707
- function pagePlan(plan, path, candUrl) {
66708
- const page = findPage(plan, path);
66709
- if (!page)
66710
- return null;
66711
- const counts = {
66712
- build: 0,
66713
- validate: 0,
66714
- upgrade: 0,
66715
- "as-is": 0,
66716
- settled: 0
66717
- };
66718
- let tasks = null;
66719
- if (page.components) {
66720
- tasks = [];
66721
- for (const name of page.components) {
66722
- const c = plan.components.find((row) => key(row.name) === key(name));
66723
- if (!c)
66724
- continue;
66725
- const d = disposition(c);
66726
- counts[d] += 1;
66727
- const selector = c.reference?.selector ?? c.selector ?? null;
66728
- const refUrl = c.reference?.url ?? plan.url;
66729
- const kind = c.reference ? "reference" : "prod";
66730
- const checkable = d === "validate" && Boolean(selector) && Boolean(candUrl);
66731
- tasks.push({
66732
- name: c.name,
66733
- disposition: d,
66734
- status: c.status,
66735
- scope: c.scope ?? "page",
66736
- origin: c.origin,
66737
- selector,
66738
- against: d === "validate" ? { url: refUrl, kind } : null,
66739
- command: checkable && candUrl && selector ? `parity section --prod ${shellQuote(joinUrl(refUrl, page.path))} --cand ${shellQuote(joinUrl(candUrl, page.path))} --selector ${shellQuote(selector)}` : null,
66740
- note: c.reference?.note ?? null
66741
- });
66742
- }
66743
- }
66744
- return {
66745
- path: page.path,
66746
- kind: page.kind,
66747
- status: page.status ?? "pending",
66748
- tasks,
66749
- counts,
66750
- ready: counts.build === 0 && counts.validate === 0
66751
- };
66752
- }
66753
- function pageColumn(page) {
66754
- if (page.status === "skipped")
66755
- return "skipped";
66756
- if (page.status === "done")
66757
- return "done";
66758
- if (page.tasks === null || page.tasks.length === 0)
66759
- return "triage";
66760
- if (page.ready)
66761
- return "review";
66762
- const started = page.counts.settled + page.counts.validate + page.counts["as-is"] + page.counts.upgrade;
66763
- return started > 0 ? "building" : "backlog";
66764
- }
66765
- function planBoard(plan, candUrl) {
66766
- const columns = {
66767
- triage: [],
66768
- backlog: [],
66769
- building: [],
66770
- review: [],
66771
- done: [],
66772
- skipped: []
66773
- };
66774
- for (const p of plan.pages) {
66775
- const page = pagePlan(plan, p.path, candUrl);
66776
- if (!page)
66777
- continue;
66778
- const column = pageColumn(page);
66779
- columns[column].push({
66780
- path: page.path,
66781
- kind: page.kind,
66782
- column,
66783
- blockers: (page.tasks ?? []).filter((t) => t.disposition === "build" && t.scope !== "global").map((t) => t.name),
66784
- counts: page.counts,
66785
- ready: page.ready,
66786
- boardItemId: p.boardItemId
66787
- });
66788
- }
66789
- const onAnyPage = new Set(plan.pages.flatMap((p) => (p.components ?? []).map(key)));
66790
- const shell = [];
66791
- const unassigned = [];
66792
- for (const c of plan.components) {
66793
- if (c.scope === "global") {
66794
- if (disposition(c) === "build")
66795
- shell.push(c.name);
66796
- } else if (!onAnyPage.has(key(c.name))) {
66797
- unassigned.push(c.name);
66798
- }
66799
- }
66800
- return { url: plan.url, columns, shell, unassigned, sampled: plan.pages.length };
66801
- }
66802
- function setComponentVerified(plan, name, verdict, at, note) {
66803
- const k = key(name);
66804
- const component = plan.components.find((c) => key(c.name) === k);
66805
- if (!component)
66806
- return null;
66807
- const against = component.reference ? "reference" : "prod";
66808
- component.verified = { at, verdict, against, ...note ? { note } : {} };
66809
- return component;
66810
- }
66811
- function setComponentReference(plan, name, reference) {
66812
- const k = key(name);
66813
- const component = plan.components.find((c) => key(c.name) === k);
66814
- if (!component)
66815
- return null;
66816
- component.reference = reference;
66817
- return component;
66818
- }
66819
- function syntheticSourceComponents(plan) {
66820
- return plan.components.filter((c) => c.origin === "source-only").map((c) => ({
66821
- role: c.name,
66822
- selector: "",
66823
- html: "",
66824
- computedStyles: null,
66825
- screenshotPath: "",
66826
- assets: { images: [], backgroundImages: [], fonts: [] },
66827
- links: [],
66828
- textContent: [],
66829
- tailwind: [],
66830
- interactions: [],
66831
- scope: c.scope ?? "page",
66832
- synthetic: true
66833
- }));
66834
- }
66835
-
66836
67280
  // src/migrate/sources/deco-fresh.ts
66837
67281
  import { existsSync as existsSync17, readFileSync as readFileSync23 } from "node:fs";
66838
67282
  import { join as join31 } from "node:path";
@@ -68103,8 +68547,8 @@ async function migrateCommand(opts) {
68103
68547
  if (merged.carried.length) {
68104
68548
  console.log(chalk20.gray(` plan: carried ${merged.carried.length} recorded decision(s) forward`));
68105
68549
  }
68106
- if (merged.droppedWithDecisions.length) {
68107
- console.log(chalk20.yellow(` plan: ${merged.droppedWithDecisions.length} component(s) with recorded decisions are no longer in the capture — ${merged.droppedWithDecisions.join(", ")}`));
68550
+ if (merged.keptUncaptured.length) {
68551
+ console.log(chalk20.yellow(` plan: ${merged.keptUncaptured.length} row(s) kept although this capture no longer sees them — ${merged.keptUncaptured.join(", ")}. They carry a decision or were added by hand; the capture owns the captured row set, not rows it cannot see.`));
68108
68552
  }
68109
68553
  bundle.components.push(...syntheticSourceComponents(plan));
68110
68554
  if (format === "json" || format === "both")
@@ -68586,7 +69030,7 @@ function fixDescription(fix) {
68586
69030
  // src/commands/plan.ts
68587
69031
  var STATUSES = ["pending", "partial", "done", "as-is", "upgrade", "skipped"];
68588
69032
  var PAGE_STATUSES = ["pending", "code", "done", "skipped"];
68589
- function planSetStatusCommand(dir, name, status) {
69033
+ function planSetStatusCommand(dir, name, status, opts = {}) {
68590
69034
  if (!STATUSES.includes(status)) {
68591
69035
  console.error(chalk21.red(`Invalid status "${status}". Use one of: ${STATUSES.join(", ")}`));
68592
69036
  return 1;
@@ -68596,11 +69040,16 @@ function planSetStatusCommand(dir, name, status) {
68596
69040
  console.error(chalk21.red(`No migration-plan.json found in ${dir}`));
68597
69041
  return 1;
68598
69042
  }
68599
- const component = setComponentStatus(plan, name, status);
69043
+ const existed = plan.components.length;
69044
+ const component = setComponentStatus(plan, name, status, opts.create ? { create: { scope: opts.create } } : {});
68600
69045
  if (!component) {
68601
69046
  console.error(chalk21.red(`No component matching "${name}" in the plan`));
69047
+ console.error(chalk21.yellow("A capture can miss a component that exists — a zero-height overlay header, a portal-rendered panel. Add it with --create global|page if this is one of those, so the plan can hold a decision about it."));
68602
69048
  return 1;
68603
69049
  }
69050
+ if (plan.components.length > existed) {
69051
+ console.log(chalk21.yellow(` + created ${component.name} (${opts.create}, origin: manual) — not from the capture`));
69052
+ }
68604
69053
  savePlan(dir, plan);
68605
69054
  console.log(`${chalk21.green("✓")} ${component.name} → ${status}`);
68606
69055
  if ((status === "upgrade" || status === "as-is") && !component.reference) {
@@ -68680,15 +69129,15 @@ function planMergeCommand(dir, sourceDir) {
68680
69129
  return 1;
68681
69130
  }
68682
69131
  const existing = loadPlan(dir);
68683
- const { plan, carried, droppedWithDecisions } = mergePlanDecisions(fresh, existing);
69132
+ const { plan, carried, keptUncaptured } = mergePlanDecisions(fresh, existing);
68684
69133
  savePlan(dir, plan);
68685
69134
  if (!existing) {
68686
69135
  console.log(`${chalk21.green("✓")} plan written to ${dir} (nothing to merge)`);
68687
69136
  return 0;
68688
69137
  }
68689
69138
  console.log(`${chalk21.green("✓")} merged into ${dir} — ${carried.length} decision(s) kept`);
68690
- if (droppedWithDecisions.length) {
68691
- console.log(chalk21.yellow(` no longer in the capture, decisions lost: ${droppedWithDecisions.join(", ")}`));
69139
+ if (keptUncaptured.length) {
69140
+ console.log(chalk21.yellow(` kept although no longer in the capture: ${keptUncaptured.join(", ")}`));
68692
69141
  }
68693
69142
  return 0;
68694
69143
  }
@@ -68752,8 +69201,10 @@ function planStatusCommand(dir, asJson) {
68752
69201
  return 1;
68753
69202
  }
68754
69203
  const p = planProgress(plan);
69204
+ const provenance = provenanceCounts(plan);
69205
+ const touches = totalTouches(plan);
68755
69206
  if (asJson) {
68756
- console.log(JSON.stringify({ url: plan.url, target: plan.target.name, ...p }, null, 2));
69207
+ console.log(JSON.stringify({ url: plan.url, target: plan.target.name, ...p, provenance, touches }, null, 2));
68757
69208
  return 0;
68758
69209
  }
68759
69210
  const c = p.components;
@@ -68767,6 +69218,13 @@ ${chalk21.bold("Components")} (${c.total}): ` + `${chalk21.green(`${c.byStatus.d
68767
69218
  if (c.accepted.asIs.length) {
68768
69219
  console.log(chalk21.gray(` divergence accepted: ${c.accepted.asIs.join(", ")}`));
68769
69220
  }
69221
+ if (provenance.library > 0 || provenance.built > 0) {
69222
+ const unrecorded = provenance.unrecorded > 0 ? chalk21.dim(`, ${provenance.unrecorded} unrecorded`) : "";
69223
+ console.log(` reuse: ${chalk21.green(`${provenance.library} from the library`)}, ${provenance.built} written here${unrecorded}`);
69224
+ }
69225
+ if (touches > 0) {
69226
+ console.log(chalk21.dim(` human touches: ${touches} across this migration`));
69227
+ }
68770
69228
  if (c.settledByStatus.done.length) {
68771
69229
  console.log(chalk21.green(` ported and validated: ${c.settledByStatus.done.join(", ")}`));
68772
69230
  }
@@ -68916,6 +69374,41 @@ Client notes (${notes.length})`));
68916
69374
  console.log(chalk21.gray('\nThese are PROPOSALS. Apply with `parity plan set-reference` / `set-status`, then confirm with `parity plan notes --page <path> --post "<what you did>"`.\n'));
68917
69375
  return 0;
68918
69376
  }
69377
+ var PROVENANCES = ["library", "built"];
69378
+ function planSetProvenanceCommand(dir, name, provenance) {
69379
+ if (!PROVENANCES.includes(provenance)) {
69380
+ console.error(chalk21.red(`Invalid provenance "${provenance}". Use one of: ${PROVENANCES.join(", ")}`));
69381
+ return 1;
69382
+ }
69383
+ const plan = loadPlan(dir);
69384
+ if (!plan) {
69385
+ console.error(chalk21.red(`No migration-plan.json found in ${dir}`));
69386
+ return 1;
69387
+ }
69388
+ const component = setComponentProvenance(plan, name, provenance);
69389
+ if (!component) {
69390
+ console.error(chalk21.red(`No component matching "${name}" in the plan`));
69391
+ return 1;
69392
+ }
69393
+ savePlan(dir, plan);
69394
+ console.log(`${chalk21.green("✓")} ${component.name} → ${provenance}`);
69395
+ return 0;
69396
+ }
69397
+ function planTouchCommand(dir, page, opts) {
69398
+ const plan = loadPlan(dir);
69399
+ if (!plan) {
69400
+ console.error(chalk21.red(`No migration-plan.json found in ${dir}`));
69401
+ return 1;
69402
+ }
69403
+ const count = recordTouch(plan, page);
69404
+ savePlan(dir, plan);
69405
+ if (opts.json) {
69406
+ console.log(JSON.stringify({ page, touches: count, total: totalTouches(plan) }));
69407
+ } else {
69408
+ console.log(`${chalk21.green("✓")} ${page} → ${count} human touch(es); ${totalTouches(plan)} in this migration`);
69409
+ }
69410
+ return 0;
69411
+ }
68919
69412
 
68920
69413
  // src/commands/pr.ts
68921
69414
  import { existsSync as existsSync25, readFileSync as readFileSync30, writeFileSync as writeFileSync27 } from "node:fs";
@@ -68928,6 +69421,57 @@ import { join as join36 } from "node:path";
68928
69421
  import chalk23 from "chalk";
68929
69422
  import ora8 from "ora";
68930
69423
 
69424
+ // src/diff/score-band.ts
69425
+ var uniq = (xs) => [...new Set(xs)];
69426
+ function computeScoreBand(current, priors, opts = {}) {
69427
+ const threshold = opts.showThreshold ?? 3;
69428
+ const scores = [current.verdict.score, ...priors.map((p) => p.score)];
69429
+ const spread = Math.round((Math.max(...scores) - Math.min(...scores)) * 100) / 100;
69430
+ const byName = new Map;
69431
+ for (const c of current.checks)
69432
+ byName.set(c.name, [c.status]);
69433
+ for (const p of priors) {
69434
+ for (const c of p.checks) {
69435
+ const seen = byName.get(c.name);
69436
+ if (seen)
69437
+ seen.push(c.status);
69438
+ }
69439
+ }
69440
+ const flipping = [];
69441
+ for (const [name, statuses] of byName) {
69442
+ if (statuses.length !== priors.length + 1)
69443
+ continue;
69444
+ const distinct = uniq(statuses);
69445
+ if (distinct.length > 1)
69446
+ flipping.push({ name, statuses: distinct.sort() });
69447
+ }
69448
+ flipping.sort((a, b) => a.name.localeCompare(b.name));
69449
+ return {
69450
+ scores,
69451
+ spread,
69452
+ priorRuns: priors.length,
69453
+ flipping,
69454
+ worthShowing: priors.length > 0 && (spread >= threshold || flipping.length > 0)
69455
+ };
69456
+ }
69457
+ function formatScoreBand(band) {
69458
+ if (!band.worthShowing)
69459
+ return null;
69460
+ const lo = Math.min(...band.scores);
69461
+ const hi = Math.max(...band.scores);
69462
+ const n = band.priorRuns + 1;
69463
+ const range = `last ${n} comparable runs: ${lo}–${hi} (spread ${band.spread})`;
69464
+ if (band.flipping.length === 0)
69465
+ return range;
69466
+ const names = band.flipping.map((f) => `${f.name} (${f.statuses.join("/")})`).join(", ");
69467
+ return `${range} — ${band.flipping.length} check(s) reported differently across them: ${names}`;
69468
+ }
69469
+ function scoreBandCaveat(band) {
69470
+ if (band.flipping.length === 0)
69471
+ return null;
69472
+ return `a check that reports differently across runs contributes points that do not track the code — read this score as ±${Math.max(band.spread, 1)} until it is stable (\`parity variance\` on two runs of unchanged code isolates it)`;
69473
+ }
69474
+
68931
69475
  // src/engine/interactive-module-prompt.ts
68932
69476
  import { createInterface as createInterface2 } from "node:readline";
68933
69477
  var ALL_MODULE_NAMES2 = Object.keys(MODULES);
@@ -69890,6 +70434,15 @@ function evaluateFailOnGate(allIssues, failOn, verdictStatus) {
69890
70434
  ✖ ${blocking.length} issue(s) bloqueante(s) [${failOn.join(", ")}] — exit 1`
69891
70435
  };
69892
70436
  }
70437
+ var SCORE_BAND_RUNS = 4;
70438
+ function readRunChecks(reportPath) {
70439
+ try {
70440
+ const raw = JSON.parse(readFileSync29(reportPath, "utf8"));
70441
+ return (raw.checks ?? []).filter((c) => typeof c.name === "string" && typeof c.status === "string").map((c) => ({ name: c.name, status: c.status }));
70442
+ } catch {
70443
+ return [];
70444
+ }
70445
+ }
69893
70446
  async function runCommand(rawOpts) {
69894
70447
  if (!rawOpts.prod) {
69895
70448
  const target = rawOpts.cand ?? "<url>";
@@ -70583,6 +71136,17 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
70583
71136
  modulesRun: verdict.modulesRun
70584
71137
  });
70585
71138
  const previousRun = prevRun ? { ...prevRun, scoreDelta: verdict.score - prevRun.score } : undefined;
71139
+ const bandRuns = findComparableRuns(opts.output, {
71140
+ prodUrl: opts.prod,
71141
+ candUrl: opts.cand,
71142
+ excludeRunId: runId,
71143
+ scoreVersion: verdict.scoreVersion,
71144
+ modulesRun: verdict.modulesRun
71145
+ }, SCORE_BAND_RUNS);
71146
+ const scoreBand = computeScoreBand({ verdict, checks }, bandRuns.map((r) => ({
71147
+ score: r.score,
71148
+ checks: readRunChecks(r.reportPath)
71149
+ })));
70586
71150
  let baselineSection;
70587
71151
  if (opts.baseline) {
70588
71152
  try {
@@ -70620,6 +71184,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
70620
71184
  durationMs: Date.now() - startedAt,
70621
71185
  verdict,
70622
71186
  previousRun,
71187
+ scoreBand,
70623
71188
  topIssues,
70624
71189
  issues: allIssues,
70625
71190
  checks,
@@ -70900,6 +71465,14 @@ function printSummary7(run, htmlPath, meta) {
70900
71465
  }
70901
71466
  console.log(` checks: ${chalk23.green(verdict.checksPassed)} pass · ${chalk23.red(verdict.checksFailed)} fail · ${chalk23.dim(`${verdict.checksSkipped} skipped`)}`);
70902
71467
  console.log(` issues: ${chalk23.red(verdict.critical)} critical · ${chalk23.yellow(verdict.high)} high · ${verdict.medium} medium · ${chalk23.dim(`${verdict.low} low`)}`);
71468
+ const band = run.scoreBand;
71469
+ const bandLine = band ? formatScoreBand(band) : null;
71470
+ if (band && bandLine) {
71471
+ console.log(` ${chalk23.dim(bandLine)}`);
71472
+ const caveat = scoreBandCaveat(band);
71473
+ if (caveat)
71474
+ console.log(` ${chalk23.yellow("⚠")} ${caveat}`);
71475
+ }
70903
71476
  for (const c of run.caveats ?? []) {
70904
71477
  const mark = c.level === "warn" ? chalk23.yellow("⚠") : chalk23.dim("ℹ");
70905
71478
  console.log(` ${mark} ${c.summary}`);
@@ -71731,6 +72304,7 @@ import chalk27 from "chalk";
71731
72304
 
71732
72305
  // src/diff/motion.ts
71733
72306
  var WEIGHT = {
72307
+ "moved-to-descendant": 45,
71734
72308
  "missing-transition": 100,
71735
72309
  "missing-animation": 100,
71736
72310
  "extra-transition": 70,
@@ -71743,8 +72317,15 @@ var WEIGHT = {
71743
72317
  easing: 15,
71744
72318
  delay: 10
71745
72319
  };
71746
- function finding(node, kind, detail) {
71747
- return { key: node.key, label: node.label, kind, detail, weight: WEIGHT[kind] };
72320
+ function finding(node, kind, detail, candKey) {
72321
+ return {
72322
+ key: node.key,
72323
+ ...candKey && candKey !== node.key ? { candKey } : {},
72324
+ label: node.label,
72325
+ kind,
72326
+ detail,
72327
+ weight: WEIGHT[kind]
72328
+ };
71748
72329
  }
71749
72330
  function sameSet(a, b) {
71750
72331
  if (a.length !== b.length)
@@ -71754,35 +72335,53 @@ function sameSet(a, b) {
71754
72335
  return sa.every((v, i) => v === sb[i]);
71755
72336
  }
71756
72337
  var list = (v) => v.length ? v.join(", ") : "none";
71757
- function diffTransitions(p, c) {
72338
+ function descendantWithTransition(nodes, ancestorKey, props) {
72339
+ const wanted = new Set(props);
72340
+ for (const n of nodes) {
72341
+ if (!n.key.startsWith(`${ancestorKey}>`))
72342
+ continue;
72343
+ if (!n.transition.durationsMs.some((d) => d > 0))
72344
+ continue;
72345
+ if (n.transition.properties.some((x) => wanted.has(x) || x === "all"))
72346
+ return n;
72347
+ }
72348
+ return null;
72349
+ }
72350
+ function diffTransitions(p, c, candNodes) {
71758
72351
  const out = [];
72352
+ const at = c.key;
71759
72353
  const pOn = p.transition.properties.length > 0 && p.transition.durationsMs.some((d) => d > 0);
71760
72354
  const cOn = c.transition.properties.length > 0 && c.transition.durationsMs.some((d) => d > 0);
71761
72355
  if (pOn && !cOn) {
71762
- out.push(finding(p, "missing-transition", `prod transitions ${list(p.transition.properties)} over ${Math.max(...p.transition.durationsMs)}ms; cand has no transition (the change is instant)`));
72356
+ const inner = descendantWithTransition(candNodes, c.key, p.transition.properties);
72357
+ if (inner) {
72358
+ out.push(finding(p, "moved-to-descendant", `prod transitions ${list(p.transition.properties)} over ${Math.max(...p.transition.durationsMs)}ms on this node; cand declares it on a DESCENDANT instead (${inner.key}: ${list(inner.transition.properties)} over ${Math.max(...inner.transition.durationsMs)}ms). The effect exists — the node carrying it differs, which is a structural difference, not a lost transition.`, at));
72359
+ return out;
72360
+ }
72361
+ out.push(finding(p, "missing-transition", `prod transitions ${list(p.transition.properties)} over ${Math.max(...p.transition.durationsMs)}ms; cand's node ${c.key} has no transition, and no descendant of it declares one either (the change is instant)`, at));
71763
72362
  return out;
71764
72363
  }
71765
72364
  if (!pOn && cOn) {
71766
- out.push(finding(p, "extra-transition", `cand transitions ${list(c.transition.properties)}; prod does not (the migration added motion)`));
72365
+ out.push(finding(p, "extra-transition", `cand transitions ${list(c.transition.properties)}; prod does not (the migration added motion)`, at));
71767
72366
  return out;
71768
72367
  }
71769
72368
  if (!pOn && !cOn)
71770
72369
  return out;
71771
72370
  if (!sameSet(p.transition.properties, c.transition.properties)) {
71772
- out.push(finding(p, "property-set", `transitioned properties differ: prod [${list(p.transition.properties)}] vs cand [${list(c.transition.properties)}]`));
72371
+ out.push(finding(p, "property-set", `transitioned properties differ: prod [${list(p.transition.properties)}] vs cand [${list(c.transition.properties)}]`, at));
71773
72372
  }
71774
72373
  const pd = Math.max(...p.transition.durationsMs);
71775
72374
  const cd = Math.max(...c.transition.durationsMs);
71776
72375
  if (pd !== cd) {
71777
- out.push(finding(p, "duration", `transition duration ${pd}ms → ${cd}ms`));
72376
+ out.push(finding(p, "duration", `transition duration ${pd}ms → ${cd}ms`, at));
71778
72377
  }
71779
72378
  if (!sameSet(p.transition.easings, c.transition.easings)) {
71780
- out.push(finding(p, "easing", `transition easing [${list(p.transition.easings)}] → [${list(c.transition.easings)}]`));
72379
+ out.push(finding(p, "easing", `transition easing [${list(p.transition.easings)}] → [${list(c.transition.easings)}]`, at));
71781
72380
  }
71782
72381
  const pdel = Math.max(0, ...p.transition.delaysMs);
71783
72382
  const cdel = Math.max(0, ...c.transition.delaysMs);
71784
72383
  if (pdel !== cdel) {
71785
- out.push(finding(p, "delay", `transition delay ${pdel}ms → ${cdel}ms`));
72384
+ out.push(finding(p, "delay", `transition delay ${pdel}ms → ${cdel}ms`, at));
71786
72385
  }
71787
72386
  return out;
71788
72387
  }
@@ -71791,14 +72390,15 @@ function keyframesFingerprint(k) {
71791
72390
  }
71792
72391
  function diffAnimations(p, c) {
71793
72392
  const out = [];
72393
+ const at = c.key;
71794
72394
  const pNames = p.animation.names.filter((n) => n && n !== "none");
71795
72395
  const cNames = c.animation.names.filter((n) => n && n !== "none");
71796
72396
  if (pNames.length > 0 && cNames.length === 0) {
71797
- out.push(finding(p, "missing-animation", `prod animates [${list(pNames)}]; cand has no animation`));
72397
+ out.push(finding(p, "missing-animation", `prod animates [${list(pNames)}]; cand has no animation`, at));
71798
72398
  return out;
71799
72399
  }
71800
72400
  if (pNames.length === 0 && cNames.length > 0) {
71801
- out.push(finding(p, "extra-animation", `cand animates [${list(cNames)}]; prod does not`));
72401
+ out.push(finding(p, "extra-animation", `cand animates [${list(cNames)}]; prod does not`, at));
71802
72402
  return out;
71803
72403
  }
71804
72404
  if (pNames.length === 0)
@@ -71806,7 +72406,7 @@ function diffAnimations(p, c) {
71806
72406
  const pd = Math.max(...p.animation.durationsMs);
71807
72407
  const cd = Math.max(...c.animation.durationsMs);
71808
72408
  if (pd !== cd)
71809
- out.push(finding(p, "duration", `animation duration ${pd}ms → ${cd}ms`));
72409
+ out.push(finding(p, "duration", `animation duration ${pd}ms → ${cd}ms`, at));
71810
72410
  for (const [i, name] of pNames.entries()) {
71811
72411
  const pk = p.keyframes[name];
71812
72412
  const cname = cNames[i];
@@ -71814,11 +72414,11 @@ function diffAnimations(p, c) {
71814
72414
  if (!pk)
71815
72415
  continue;
71816
72416
  if (!ck) {
71817
- out.push(finding(p, "keyframes", `prod's @keyframes ${name} has no counterpart on the cand side`));
72417
+ out.push(finding(p, "keyframes", `prod's @keyframes ${name} has no counterpart on the cand side`, at));
71818
72418
  continue;
71819
72419
  }
71820
72420
  if (keyframesFingerprint(pk) !== keyframesFingerprint(ck)) {
71821
- out.push(finding(p, "keyframes", `@keyframes differ (prod ${name}: ${pk.steps.length} steps, cand ${cname}: ${ck.steps.length} steps)`));
72421
+ out.push(finding(p, "keyframes", `@keyframes differ (prod ${name}: ${pk.steps.length} steps, cand ${cname}: ${ck.steps.length} steps)`, at));
71822
72422
  }
71823
72423
  }
71824
72424
  return out;
@@ -71829,7 +72429,8 @@ function diffMotion(prod, cand, opts = {}) {
71829
72429
  for (const n of cand.nodes) {
71830
72430
  if (!n.label)
71831
72431
  continue;
71832
- labelSeen.set(n.label, labelSeen.has(n.label) ? null : n);
72432
+ const k = canonicalLabel(opts.aliases, n.label);
72433
+ labelSeen.set(k, labelSeen.has(k) ? null : n);
71833
72434
  }
71834
72435
  const byLabel = new Map;
71835
72436
  for (const [k, v] of labelSeen)
@@ -71839,14 +72440,14 @@ function diffMotion(prod, cand, opts = {}) {
71839
72440
  const used = new Set;
71840
72441
  let matched = 0;
71841
72442
  for (const p of prod.nodes) {
71842
- const c = byKey.get(p.key) ?? (p.label ? byLabel.get(p.label) : undefined);
72443
+ const c = (p.label ? byLabel.get(canonicalLabel(opts.aliases, p.label)) : undefined) ?? byKey.get(p.key);
71843
72444
  if (!c || used.has(c)) {
71844
72445
  findings.push(finding(p, "only-in-prod", `${p.tag}${p.label ? ` (${p.label})` : ""} has no counterpart`));
71845
72446
  continue;
71846
72447
  }
71847
72448
  used.add(c);
71848
72449
  matched++;
71849
- findings.push(...diffTransitions(p, c), ...diffAnimations(p, c));
72450
+ findings.push(...diffTransitions(p, c, cand.nodes), ...diffAnimations(p, c));
71850
72451
  }
71851
72452
  findings.sort((a, b) => b.weight - a.weight || a.key.localeCompare(b.key) || a.kind.localeCompare(b.kind));
71852
72453
  return {
@@ -71858,25 +72459,63 @@ function diffMotion(prod, cand, opts = {}) {
71858
72459
  function isMotionClean(diff) {
71859
72460
  return diff.findings.length === 0;
71860
72461
  }
72462
+ function groupMotionFindings(findings) {
72463
+ const groups = new Map;
72464
+ for (const f of findings) {
72465
+ const id = `${f.kind}\x00${f.detail}`;
72466
+ const g = groups.get(id);
72467
+ if (g)
72468
+ g.keys.push(f.key);
72469
+ else
72470
+ groups.set(id, {
72471
+ kind: f.kind,
72472
+ detail: f.detail,
72473
+ keys: [f.key],
72474
+ ...f.candKey ? { candKey: f.candKey } : {},
72475
+ weight: f.weight
72476
+ });
72477
+ }
72478
+ return [...groups.values()].sort((a, b) => b.weight - a.weight || b.keys.length - a.keys.length || a.keys[0].localeCompare(b.keys[0]));
72479
+ }
71861
72480
  function formatMotionDiff(diff, opts = {}) {
71862
72481
  if (isMotionClean(diff)) {
71863
- return `motion: clean (${diff.matched} interactive elements matched)${diff.truncated ? " — TRUNCATED" : ""}`;
72482
+ const caveat = diff.truncated ? " — TRUNCATED" : "";
72483
+ return diff.matched === 0 ? `motion: nothing to compare — no interactive element paired inside the selector${caveat}` : `motion: clean (${diff.matched} interactive elements matched)${caveat}`;
71864
72484
  }
71865
72485
  const limit = opts.limit ?? 30;
71866
- const shown = diff.findings.slice(0, limit);
71867
- const keyW = Math.max(4, ...shown.map((f) => f.key.length));
71868
- const lines = shown.map((f) => `${f.key.padEnd(keyW)} ${f.kind.padEnd(20)} ${f.detail}`);
71869
- if (diff.findings.length > shown.length) {
71870
- lines.push(`… ${diff.findings.length - shown.length} more`);
72486
+ const groups = groupMotionFindings(diff.findings);
72487
+ const structural = groups.filter((g) => g.kind === "only-in-prod" || g.kind === "only-in-cand");
72488
+ const real = groups.filter((g) => g.kind !== "only-in-prod" && g.kind !== "only-in-cand");
72489
+ const shown = real.slice(0, limit);
72490
+ const lines = [];
72491
+ for (const g of shown) {
72492
+ const head = g.keys.length > 1 ? `${g.keys[0]} (+${g.keys.length - 1} more)` : g.keys[0];
72493
+ lines.push(`${head} ${g.kind} ${g.detail}`);
72494
+ if (g.candKey)
72495
+ lines.push(` cand node: ${g.candKey}`);
72496
+ if (g.keys.length > 1) {
72497
+ for (const k of g.keys.slice(1))
72498
+ lines.push(` also: ${k}`);
72499
+ }
72500
+ }
72501
+ if (real.length > shown.length)
72502
+ lines.push(`… ${real.length - shown.length} more`);
72503
+ if (real.length === 0)
72504
+ lines.push("no motion differences on paired elements");
72505
+ const structuralCount = structural.reduce((n, g) => n + g.keys.length, 0);
72506
+ if (structuralCount > 0) {
72507
+ lines.push(`${structuralCount} element(s) had no counterpart on the other side — structural, not motion; see the box-tree diff`);
72508
+ }
72509
+ if (diff.truncated) {
72510
+ lines.push("TRUNCATED — element cap hit; absence of a finding is not proof, and a declaration reported on N elements may sit on more");
71871
72511
  }
71872
- if (diff.truncated)
71873
- lines.push("TRUNCATED — element cap hit; absence of a finding is not proof");
71874
72512
  return lines.join(`
71875
72513
  `);
71876
72514
  }
71877
72515
 
71878
72516
  // src/engine/motion.ts
71879
72517
  var LABEL_ATTRS2 = ["data-section", "data-testid", "data-fs-section", "data-manifest-key", "id"];
72518
+ var GENERATED_ID2 = /^(?::[rR][0-9a-zA-Z]*:|_[rR]_[0-9a-zA-Z_]*_)$/;
71880
72519
  async function readMotion(page, selector, opts = {}) {
71881
72520
  const maxNodes = opts.maxNodes ?? 80;
71882
72521
  const maxDepth = opts.maxDepth ?? 12;
@@ -71891,7 +72530,7 @@ async function readMotion(page, selector, opts = {}) {
71891
72530
  }
71892
72531
  let got;
71893
72532
  try {
71894
- got = await page.evaluate(({ sel, maxNodes, maxDepth, labelAttrs }) => {
72533
+ got = await page.evaluate(({ sel, maxNodes, maxDepth, labelAttrs, generatedIdPattern }) => {
71895
72534
  try {
71896
72535
  const root = document.querySelector(sel);
71897
72536
  if (!root || !(root instanceof HTMLElement)) {
@@ -71936,11 +72575,15 @@ async function readMotion(page, selector, opts = {}) {
71936
72575
  collect(sheet.cssRules);
71937
72576
  } catch {}
71938
72577
  }
72578
+ const generatedId = new RegExp(generatedIdPattern);
71939
72579
  const labelOf = (el) => {
71940
72580
  for (const a of labelAttrs) {
71941
72581
  const v = el.getAttribute(a);
71942
- if (v)
71943
- return v;
72582
+ if (!v)
72583
+ continue;
72584
+ if (a === "id" && generatedId.test(v))
72585
+ continue;
72586
+ return v;
71944
72587
  }
71945
72588
  return null;
71946
72589
  };
@@ -72006,7 +72649,13 @@ async function readMotion(page, selector, opts = {}) {
72006
72649
  reason: `leitura de motion falhou em '${sel}': ${err.message ?? "unknown"}`
72007
72650
  };
72008
72651
  }
72009
- }, { sel: selector, maxNodes, maxDepth, labelAttrs: LABEL_ATTRS2 });
72652
+ }, {
72653
+ sel: selector,
72654
+ maxNodes,
72655
+ maxDepth,
72656
+ labelAttrs: LABEL_ATTRS2,
72657
+ generatedIdPattern: GENERATED_ID2.source
72658
+ });
72010
72659
  } catch (err) {
72011
72660
  return {
72012
72661
  found: false,
@@ -72052,6 +72701,8 @@ async function gatherBenchSide(browser, opts) {
72052
72701
  });
72053
72702
  if (opts.waitMs > 0)
72054
72703
  await page.waitForTimeout(opts.waitMs);
72704
+ await reloadIfOptionalFonts(page, opts.waitMs);
72705
+ side.settle = await waitForLayoutStable(page);
72055
72706
  side.boxNodes = await readBoxTree(page, opts.selector);
72056
72707
  side.motion = await readMotion(page, opts.selector);
72057
72708
  if (opts.screenshotPath && side.boxNodes.found) {
@@ -72103,6 +72754,9 @@ async function benchCommand(opts) {
72103
72754
  mkdirSync18(opts.outDir, { recursive: true });
72104
72755
  const slug = opts.component.replace(/[^a-zA-Z0-9]+/g, "-").toLowerCase();
72105
72756
  const prefix = `bench-${slug}-${viewport}`;
72757
+ const { aliases, note: aliasNote } = resolveAliases(opts.planDir);
72758
+ if (aliasNote)
72759
+ console.log(chalk27.dim(` ${aliasNote}`));
72106
72760
  const browser = await launchBrowser({ headless: true });
72107
72761
  try {
72108
72762
  const [prodSide, candSide] = await Promise.all([
@@ -72131,10 +72785,12 @@ async function benchCommand(opts) {
72131
72785
  return 2;
72132
72786
  }
72133
72787
  const geometry = diffBoxTrees(prodSide.boxNodes.nodes, candSide.boxNodes.nodes, {
72134
- truncated: prodSide.boxNodes.truncated || candSide.boxNodes.truncated
72788
+ truncated: prodSide.boxNodes.truncated || candSide.boxNodes.truncated,
72789
+ aliases
72135
72790
  });
72136
- const motion = prodSide.motion.found && candSide.motion.found ? diffMotion(prodSide.motion, candSide.motion) : null;
72791
+ const motion = prodSide.motion.found && candSide.motion.found ? diffMotion(prodSide.motion, candSide.motion, { aliases }) : null;
72137
72792
  const clean = isGeometryClean(geometry) && (motion?.findings.length ?? 0) === 0;
72793
+ const inconclusive = isBoxTreeInconclusive(geometry);
72138
72794
  const result = {
72139
72795
  component: opts.component,
72140
72796
  viewport,
@@ -72142,9 +72798,11 @@ async function benchCommand(opts) {
72142
72798
  candUrl,
72143
72799
  propsFile: opts.props ?? null,
72144
72800
  clean,
72801
+ inconclusive,
72145
72802
  geometry,
72146
72803
  motion,
72147
- screenshots: { prod: prodSide.screenshotPath ?? null, cand: candSide.screenshotPath ?? null }
72804
+ screenshots: { prod: prodSide.screenshotPath ?? null, cand: candSide.screenshotPath ?? null },
72805
+ settle: { prod: prodSide.settle ?? null, cand: candSide.settle ?? null }
72148
72806
  };
72149
72807
  const resultPath = resolve8(opts.outDir, `${prefix}.json`);
72150
72808
  writeFileSync30(resultPath, `${JSON.stringify(result, null, 2)}
@@ -72160,6 +72818,14 @@ async function benchCommand(opts) {
72160
72818
  for (const line of formatBoxTreeDiff(geometry).split(`
72161
72819
  `))
72162
72820
  console.log(` ${line}`);
72821
+ for (const [name, data] of [
72822
+ ["prod", prodSide],
72823
+ ["cand", candSide]
72824
+ ]) {
72825
+ const caveat = data.settle && formatSettleCaveat(name, data.settle);
72826
+ if (caveat)
72827
+ console.log(chalk27.yellow(` ${caveat}`));
72828
+ }
72163
72829
  if (motion) {
72164
72830
  console.log("");
72165
72831
  for (const line of formatMotionDiff(motion).split(`
@@ -72177,10 +72843,1375 @@ async function benchCommand(opts) {
72177
72843
  }
72178
72844
  }
72179
72845
 
72180
- // src/commands/states.ts
72846
+ // src/commands/locate.ts
72181
72847
  import chalk28 from "chalk";
72848
+ var hitOf = (n, nodes) => ({
72849
+ key: n.key,
72850
+ label: n.label,
72851
+ tag: n.tag,
72852
+ rect: n.rect,
72853
+ fontSize: n.styles["font-size"] ?? "?",
72854
+ fontWeight: n.styles["font-weight"] ?? "?",
72855
+ textAlign: n.styles["text-align"] ?? "?",
72856
+ contributesBox: !addsNoBoxOfItsOwn(n, nodes)
72857
+ });
72858
+ var isZeroPx = (v) => !v || v === "0px";
72859
+ function addsNoBoxOfItsOwn(n, nodes) {
72860
+ const pads = ["padding-top", "padding-right", "padding-bottom", "padding-left"];
72861
+ if (!pads.every((k) => isZeroPx(n.styles[k])))
72862
+ return false;
72863
+ return nodes.some((o) => o !== n && o.key.startsWith(`${n.key}>`) && Math.abs(o.rect.height - n.rect.height) <= 1);
72864
+ }
72865
+ function pairingNotes(prod, cand) {
72866
+ const notes = [];
72867
+ if (prod.contributesBox !== cand.contributesBox) {
72868
+ const bare = prod.contributesBox ? "cand" : "prod";
72869
+ const other = bare === "prod" ? "cand" : "prod";
72870
+ notes.push(`${bare}'s match adds no box of its own (no padding, and something inside it exactly as tall) while ${other}'s does — the label may have collapsed one level too far on that side, and the difference below may be ${other}'s padding. Re-run against the outer element's own id to check.`);
72871
+ }
72872
+ for (const [name, hit] of [
72873
+ ["prod", prod],
72874
+ ["cand", cand]
72875
+ ]) {
72876
+ if (isImplausiblyShort(hit)) {
72877
+ notes.push(`${name}'s match is ${hit.rect.height}px tall with a ${hit.fontSize} font — that is an inline box reporting its line box, not the control the label belongs to. The label likely descended into an inner element on that side.`);
72878
+ }
72879
+ }
72880
+ if (prod.tag !== cand.tag && Math.abs(prod.rect.width - cand.rect.width) > 1 && Math.abs(prod.rect.height - cand.rect.height) > 1) {
72881
+ notes.push(`tag, width and height all differ (${prod.tag} ${prod.rect.width}×${prod.rect.height} vs ${cand.tag} ${cand.rect.width}×${cand.rect.height}) — two elements that are genuinely the same one rarely disagree on all three at once.`);
72882
+ }
72883
+ return notes;
72884
+ }
72885
+ function isImplausiblyShort(hit) {
72886
+ const size = Number.parseFloat(hit.fontSize);
72887
+ if (!Number.isFinite(size) || size <= 0)
72888
+ return false;
72889
+ return hit.rect.height > 0 && hit.rect.height < size * 0.9;
72890
+ }
72891
+ function findByLabel(nodes, label, aliases) {
72892
+ const wanted = canonicalLabel(aliases, label).toLowerCase();
72893
+ const byAttr = nodes.filter((n) => n.label && canonicalLabel(aliases, n.label).toLowerCase() === wanted);
72894
+ const pool = byAttr.length > 0 ? byAttr : nodes.filter((n) => matchesText(n, label));
72895
+ return pool.filter((n) => !pool.some((o) => o !== n && o.key.startsWith(`${n.key}>`)));
72896
+ }
72897
+ function matchesText(n, label) {
72898
+ const t = n.text?.toLowerCase();
72899
+ return Boolean(t?.startsWith(label.trim().toLowerCase()));
72900
+ }
72901
+ function answer(nodes, label, aliases) {
72902
+ const hits = findByLabel(nodes, label, aliases);
72903
+ const only = hits.length === 1 ? hits[0] : undefined;
72904
+ if (only)
72905
+ return { found: true, hit: hitOf(only, nodes) };
72906
+ if (hits.length === 0)
72907
+ return { found: false, reason: "no element carries this label" };
72908
+ return {
72909
+ found: false,
72910
+ reason: `${hits.length} elements carry this label — cannot tell which`,
72911
+ candidates: hits.slice(0, 4).map((n) => n.key)
72912
+ };
72913
+ }
72914
+ async function readSide(browser, opts) {
72915
+ const ctx = await newContext(browser, { viewport: opts.viewport });
72916
+ const page = await ctx.newPage();
72917
+ try {
72918
+ const res = await page.goto(opts.url, { waitUntil: "domcontentloaded", timeout: 30000 }).catch((err) => err);
72919
+ if (res instanceof Error)
72920
+ return { nodes: null, error: `${opts.url} — ${res.message.split(`
72921
+ `)[0]}` };
72922
+ if (res && res.status() >= 400)
72923
+ return { nodes: null, error: `${opts.url} — HTTP ${res.status()}` };
72924
+ await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
72925
+ return;
72926
+ });
72927
+ if (opts.waitMs > 0)
72928
+ await page.waitForTimeout(opts.waitMs);
72929
+ const warmed = await reloadIfOptionalFonts(page, opts.waitMs);
72930
+ await scrollFullPage(page, 15000).catch(() => {
72931
+ return;
72932
+ });
72933
+ const settle = await waitForLayoutStable(page);
72934
+ const box = await readBoxTree(page, opts.selector, { maxNodes: 6000, maxDepth: 30 });
72935
+ if (!box.found)
72936
+ return { nodes: null, error: box.error, settle, warmed };
72937
+ return { nodes: box.nodes, settle, warmed };
72938
+ } finally {
72939
+ await page.context().close().catch(() => {
72940
+ return;
72941
+ });
72942
+ }
72943
+ }
72944
+ function formatDelta(prod, cand) {
72945
+ const parts = [];
72946
+ const px = (name, a, b) => {
72947
+ const pa = Number.parseFloat(a);
72948
+ const pb = Number.parseFloat(b);
72949
+ if (!Number.isFinite(pa) || !Number.isFinite(pb) || pa === pb)
72950
+ return;
72951
+ const d = Math.round((pb - pa) * 100) / 100;
72952
+ parts.push(`${name} ${d > 0 ? "+" : ""}${d}`);
72953
+ };
72954
+ px("font-size", prod.fontSize, cand.fontSize);
72955
+ px("font-weight", prod.fontWeight, cand.fontWeight);
72956
+ if (prod.textAlign !== cand.textAlign) {
72957
+ parts.push(`text-align ${prod.textAlign} → ${cand.textAlign}`);
72958
+ }
72959
+ for (const k of ["x", "y", "width", "height"]) {
72960
+ px(k, String(prod.rect[k]), String(cand.rect[k]));
72961
+ }
72962
+ return parts.length > 0 ? parts.join(" ") : null;
72963
+ }
72964
+ function formatHit(h) {
72965
+ const { x, y, width, height } = h.rect;
72966
+ return `x${x} y${y} w${width} h${height} ${h.fontSize}/${h.fontWeight} ${h.textAlign}`;
72967
+ }
72968
+ function printResult3(r) {
72969
+ const side = (name, a) => {
72970
+ if (a.found) {
72971
+ console.log(` ${name.padEnd(5)} ${a.hit.tag.padEnd(8)} ${formatHit(a.hit)}`);
72972
+ console.log(chalk28.dim(` node: ${a.hit.key}${a.hit.label ? ` (${a.hit.label})` : ""}`));
72973
+ return;
72974
+ }
72975
+ console.log(chalk28.yellow(` ${name.padEnd(5)} ${a.reason}`));
72976
+ for (const c of a.candidates ?? [])
72977
+ console.log(chalk28.dim(` candidate: ${c}`));
72978
+ };
72979
+ console.log("");
72980
+ console.log(chalk28.bold(` ${r.label} — ${r.viewport}`));
72981
+ side("prod", r.prod);
72982
+ side("cand", r.cand);
72983
+ if (r.prod.found && r.cand.found) {
72984
+ const delta = formatDelta(r.prod.hit, r.cand.hit);
72985
+ console.log(` ${"diff".padEnd(5)} ${delta ?? "identical box and type"}`);
72986
+ for (const note of pairingNotes(r.prod.hit, r.cand.hit)) {
72987
+ console.log(chalk28.yellow(` note ${note}`));
72988
+ }
72989
+ }
72990
+ }
72991
+ async function locateCommand(opts) {
72992
+ const selector = opts.selector ?? "body";
72993
+ const waitMs = Number.parseInt(opts.wait, 10);
72994
+ if (!Number.isFinite(waitMs) || waitMs < 0) {
72995
+ console.error(chalk28.red(`--wait inválido: ${opts.wait}`));
72996
+ return 2;
72997
+ }
72998
+ if (opts.labels.length === 0) {
72999
+ console.error(chalk28.red("nenhum --label passado — o comando procura por label, não por seletor"));
73000
+ return 2;
73001
+ }
73002
+ const viewports = opts.viewports.split(",").map((v) => v.trim());
73003
+ const bad = viewports.find((v) => parseViewport3(v) === null);
73004
+ if (bad) {
73005
+ console.error(chalk28.red(`viewport inválido: ${bad} (mobile | tablet | desktop)`));
73006
+ return 2;
73007
+ }
73008
+ const { aliases, note } = resolveAliases(opts.planDir);
73009
+ if (note && !opts.json)
73010
+ console.log(chalk28.dim(` ${note}`));
73011
+ const results = [];
73012
+ const caveats = [];
73013
+ const browser = await launchBrowser({ headless: true });
73014
+ try {
73015
+ for (const raw of viewports) {
73016
+ const viewport = parseViewport3(raw);
73017
+ if (!viewport)
73018
+ continue;
73019
+ const [prod, cand] = await Promise.all([
73020
+ readSide(browser, { url: opts.prod, viewport, selector, waitMs }),
73021
+ readSide(browser, { url: opts.cand, viewport, selector, waitMs })
73022
+ ]);
73023
+ for (const [name, side] of [
73024
+ ["prod", prod],
73025
+ ["cand", cand]
73026
+ ]) {
73027
+ const caveat = side.settle && formatSettleCaveat(`${name} @ ${raw}`, side.settle);
73028
+ if (caveat)
73029
+ caveats.push(caveat);
73030
+ if (side.warmed) {
73031
+ caveats.push(`${name} @ ${raw}: declares font-display: optional, so the first view paints the fallback face and never swaps — measured on a second visit with the font cached`);
73032
+ }
73033
+ }
73034
+ for (const label of opts.labels) {
73035
+ results.push({
73036
+ label,
73037
+ viewport: raw,
73038
+ prod: prod.nodes ? answer(prod.nodes, label, aliases) : { found: false, reason: prod.error ?? "prod unreadable" },
73039
+ cand: cand.nodes ? answer(cand.nodes, label, aliases) : { found: false, reason: cand.error ?? "cand unreadable" }
73040
+ });
73041
+ }
73042
+ }
73043
+ } finally {
73044
+ await browser.close().catch(() => {
73045
+ return;
73046
+ });
73047
+ }
73048
+ const unresolved = results.filter((r) => !r.prod.found || !r.cand.found);
73049
+ if (opts.json) {
73050
+ console.log(JSON.stringify({
73051
+ selector,
73052
+ results: results.map((r) => ({
73053
+ ...r,
73054
+ delta: r.prod.found && r.cand.found ? formatDelta(r.prod.hit, r.cand.hit) : null,
73055
+ notes: r.prod.found && r.cand.found ? pairingNotes(r.prod.hit, r.cand.hit) : []
73056
+ })),
73057
+ caveats,
73058
+ unresolved: unresolved.length
73059
+ }));
73060
+ return unresolved.length > 0 ? 1 : 0;
73061
+ }
73062
+ for (const r of results)
73063
+ printResult3(r);
73064
+ for (const c of caveats)
73065
+ console.log(chalk28.yellow(` ${c}`));
73066
+ console.log("");
73067
+ if (unresolved.length > 0) {
73068
+ console.log(chalk28.yellow(` ${unresolved.length} of ${results.length} label×viewport pair${results.length === 1 ? "" : "s"} unresolved — those rows are not a measurement`));
73069
+ } else {
73070
+ console.log(chalk28.green(` ${results.length} label×viewport pair${results.length === 1 ? "" : "s"} located on both sides`));
73071
+ }
73072
+ return unresolved.length > 0 ? 1 : 0;
73073
+ }
73074
+
73075
+ // src/commands/cockpit.ts
73076
+ import { resolve as resolve9 } from "node:path";
73077
+ import chalk29 from "chalk";
73078
+
73079
+ // src/server/cockpit.ts
73080
+ import { createServer as createServer2 } from "node:http";
73081
+
73082
+ // src/server/cockpit-api.ts
73083
+ import { existsSync as existsSync29, readFileSync as readFileSync33, readdirSync as readdirSync7 } from "node:fs";
73084
+ import { join as join39 } from "node:path";
73085
+ var notFound = (what) => ({ status: 404, body: { error: what } });
73086
+ function readJson2(path) {
73087
+ if (!existsSync29(path))
73088
+ return null;
73089
+ try {
73090
+ return JSON.parse(readFileSync33(path, "utf8"));
73091
+ } catch {
73092
+ return null;
73093
+ }
73094
+ }
73095
+ function withPlan(ctx) {
73096
+ return loadPlan(ctx.planDir);
73097
+ }
73098
+ function listBenchResults(benchDir) {
73099
+ if (!existsSync29(benchDir))
73100
+ return [];
73101
+ let files;
73102
+ try {
73103
+ files = readdirSync7(benchDir).filter((f) => f.startsWith("bench-") && f.endsWith(".json"));
73104
+ } catch {
73105
+ return [];
73106
+ }
73107
+ const out = [];
73108
+ for (const file of files) {
73109
+ const raw = readJson2(join39(benchDir, file));
73110
+ if (!raw?.component)
73111
+ continue;
73112
+ out.push({
73113
+ file,
73114
+ component: raw.component,
73115
+ viewport: raw.viewport ?? "?",
73116
+ clean: Boolean(raw.clean),
73117
+ deltas: raw.geometry?.deltas?.length ?? 0,
73118
+ motionFindings: raw.motion?.findings?.length ?? 0
73119
+ });
73120
+ }
73121
+ return out.sort((a, b) => Number(a.clean) - Number(b.clean) || b.deltas - a.deltas || a.component.localeCompare(b.component));
73122
+ }
73123
+ function cockpitApi(path, params, ctx) {
73124
+ switch (path) {
73125
+ case "/api/context":
73126
+ return {
73127
+ status: 200,
73128
+ body: {
73129
+ planDir: ctx.planDir,
73130
+ output: ctx.output,
73131
+ benchDir: ctx.benchDir,
73132
+ prodUrl: ctx.prodUrl ?? null,
73133
+ candUrl: ctx.candUrl ?? null,
73134
+ hasPlan: existsSync29(join39(ctx.planDir, "migration-plan.json"))
73135
+ }
73136
+ };
73137
+ case "/api/state": {
73138
+ const state = readJson2(join39(ctx.planDir, "migration.json"));
73139
+ return state ? { status: 200, body: state } : notFound("no migration.json — no migration has been started here");
73140
+ }
73141
+ case "/api/plan": {
73142
+ const plan = withPlan(ctx);
73143
+ if (!plan)
73144
+ return notFound("no migration-plan.json — run `parity migrate --url <prod>` first");
73145
+ return {
73146
+ status: 200,
73147
+ body: {
73148
+ url: plan.url,
73149
+ target: plan.target.name,
73150
+ source: plan.source,
73151
+ ...planProgress(plan),
73152
+ provenance: provenanceCounts(plan),
73153
+ touches: totalTouches(plan)
73154
+ }
73155
+ };
73156
+ }
73157
+ case "/api/board": {
73158
+ const plan = withPlan(ctx);
73159
+ if (!plan)
73160
+ return notFound("no migration-plan.json");
73161
+ return { status: 200, body: planBoard(plan, params.get("candUrl") ?? ctx.candUrl) };
73162
+ }
73163
+ case "/api/page": {
73164
+ const plan = withPlan(ctx);
73165
+ if (!plan)
73166
+ return notFound("no migration-plan.json");
73167
+ const pagePath = params.get("path");
73168
+ if (!pagePath)
73169
+ return { status: 400, body: { error: "missing ?path=" } };
73170
+ const sheet = pagePlan(plan, pagePath, params.get("candUrl") ?? ctx.candUrl);
73171
+ return sheet ? { status: 200, body: sheet } : notFound(`the plan has no page at ${pagePath}`);
73172
+ }
73173
+ case "/api/runs":
73174
+ return { status: 200, body: listRuns(ctx.output).slice(0, 30) };
73175
+ case "/api/run": {
73176
+ const id = params.get("id") ?? listRuns(ctx.output)[0]?.id;
73177
+ if (!id)
73178
+ return notFound("no runs found");
73179
+ try {
73180
+ const run = loadRun(ctx.output, id);
73181
+ return {
73182
+ status: 200,
73183
+ body: {
73184
+ id: run.id,
73185
+ timestamp: run.timestamp,
73186
+ prodUrl: run.prodUrl,
73187
+ candUrl: run.candUrl,
73188
+ verdict: run.verdict,
73189
+ previousRun: run.previousRun ?? null,
73190
+ topIssues: run.topIssues,
73191
+ checks: run.checks.map((c) => ({
73192
+ name: c.name,
73193
+ status: c.status,
73194
+ severity: c.severity,
73195
+ summary: c.summary,
73196
+ issues: c.issues.length
73197
+ }))
73198
+ }
73199
+ };
73200
+ } catch (err) {
73201
+ return notFound(err.message);
73202
+ }
73203
+ }
73204
+ case "/api/bench":
73205
+ return { status: 200, body: listBenchResults(ctx.benchDir) };
73206
+ case "/api/bench/result": {
73207
+ const file = params.get("file");
73208
+ if (!file)
73209
+ return { status: 400, body: { error: "missing ?file=" } };
73210
+ if (file.includes("/") || file.includes("\\") || !/^bench-[\w.-]+\.json$/.test(file)) {
73211
+ return { status: 400, body: { error: "bad file name" } };
73212
+ }
73213
+ const raw = readJson2(join39(ctx.benchDir, file));
73214
+ return raw ? { status: 200, body: raw } : notFound(`no bench result ${file}`);
73215
+ }
73216
+ default:
73217
+ return null;
73218
+ }
73219
+ }
73220
+
73221
+ // src/server/cockpit-html.ts
73222
+ var COCKPIT_HTML = `<!doctype html>
73223
+ <html lang="en">
73224
+ <head>
73225
+ <meta charset="utf-8" />
73226
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
73227
+ <title>parity cockpit</title>
73228
+ <style>
73229
+ :root{
73230
+ --bg:#0e0f11; --panel:#16181c; --panel-2:#1c1f24; --line:#292d34;
73231
+ --ink:#e8eaed; --dim:#9aa0a8; --faint:#6b7280;
73232
+ --ok:#8CAA25; --warn:#FFC116; --bad:#e5534b; --accent:#A595FF;
73233
+ --mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace;
73234
+ }
73235
+ @media (prefers-color-scheme: light){
73236
+ :root{--bg:#fbfbfc;--panel:#fff;--panel-2:#f4f5f7;--line:#e3e5e9;--ink:#16181c;--dim:#5c636e;--faint:#8b929c}
73237
+ }
73238
+ *{box-sizing:border-box}
73239
+ body{margin:0;background:var(--bg);color:var(--ink);
73240
+ font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif}
73241
+ a{color:inherit}
73242
+ header.top{display:flex;align-items:center;gap:16px;padding:12px 20px;border-bottom:1px solid var(--line);
73243
+ position:sticky;top:0;background:var(--bg);z-index:10;flex-wrap:wrap}
73244
+ .brand{font-weight:600;letter-spacing:-.01em}
73245
+ .brand span{color:var(--faint);font-weight:400}
73246
+ nav.tabs{display:flex;gap:4px;margin-left:8px}
73247
+ nav.tabs button{background:none;border:1px solid transparent;color:var(--dim);padding:5px 11px;
73248
+ border-radius:7px;cursor:pointer;font:inherit}
73249
+ nav.tabs button[aria-selected="true"]{background:var(--panel-2);border-color:var(--line);color:var(--ink)}
73250
+ .spacer{flex:1}
73251
+ .meta{color:var(--faint);font:12px/1.4 var(--mono)}
73252
+ main{padding:20px;max-width:1600px;margin:0 auto}
73253
+ .view[hidden]{display:none}
73254
+ h2{font-size:15px;margin:0 0 12px;font-weight:600}
73255
+ .sub{color:var(--dim);margin:-8px 0 16px}
73256
+
73257
+ /* stat strip */
73258
+ .stats{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:20px}
73259
+ .stat{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:11px 14px;min-width:120px}
73260
+ .stat b{display:block;font-size:20px;font-variant-numeric:tabular-nums;letter-spacing:-.02em}
73261
+ .stat small{color:var(--faint);font-size:11px;text-transform:uppercase;letter-spacing:.05em}
73262
+
73263
+ /* board */
73264
+ .lanes{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:14px;align-items:start}
73265
+ .lane{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px}
73266
+ .lane h3{margin:0 0 10px;font-size:12px;text-transform:uppercase;letter-spacing:.06em;color:var(--dim);
73267
+ display:flex;justify-content:space-between;align-items:center}
73268
+ .lane h3 em{font-style:normal;color:var(--faint);font-variant-numeric:tabular-nums}
73269
+ .card{background:var(--panel-2);border:1px solid var(--line);border-radius:9px;padding:10px;margin-bottom:8px;
73270
+ cursor:pointer;text-align:left;width:100%;color:inherit;font:inherit;display:block}
73271
+ .card:hover{border-color:var(--accent)}
73272
+ .card:last-child{margin-bottom:0}
73273
+ .card .path{font-family:var(--mono);font-size:12px}
73274
+ .card .why{color:var(--dim);font-size:12px;margin-top:5px}
73275
+ .empty{color:var(--faint);font-size:12px;font-style:italic}
73276
+
73277
+ .chip{display:inline-block;padding:1px 7px;border-radius:999px;font-size:11px;border:1px solid var(--line);
73278
+ color:var(--dim);font-family:var(--mono)}
73279
+ .chip.ok{color:var(--ok);border-color:color-mix(in srgb,var(--ok) 40%,transparent)}
73280
+ .chip.warn{color:var(--warn);border-color:color-mix(in srgb,var(--warn) 40%,transparent)}
73281
+ .chip.bad{color:var(--bad);border-color:color-mix(in srgb,var(--bad) 40%,transparent)}
73282
+
73283
+ /* diff */
73284
+ .diffgrid{display:grid;grid-template-columns:280px 1fr;gap:14px;align-items:start}
73285
+ .list{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:8px;
73286
+ max-height:75vh;overflow:auto}
73287
+ .list button{display:block;width:100%;text-align:left;background:none;border:0;color:inherit;font:inherit;
73288
+ padding:8px 9px;border-radius:7px;cursor:pointer}
73289
+ .list button:hover{background:var(--panel-2)}
73290
+ .list button[aria-selected="true"]{background:var(--panel-2);box-shadow:inset 2px 0 0 var(--accent)}
73291
+ .list .name{font-family:var(--mono);font-size:12px}
73292
+ .list .row2{display:flex;gap:6px;align-items:center;margin-top:4px}
73293
+
73294
+ table{width:100%;border-collapse:collapse;font-family:var(--mono);font-size:12px}
73295
+ th{text-align:left;color:var(--faint);font-weight:500;padding:6px 10px;border-bottom:1px solid var(--line);
73296
+ position:sticky;top:0;background:var(--panel);text-transform:uppercase;font-size:10px;letter-spacing:.06em}
73297
+ td{padding:6px 10px;border-bottom:1px solid color-mix(in srgb,var(--line) 55%,transparent);vertical-align:top}
73298
+ tr:last-child td{border-bottom:0}
73299
+ td.sel{color:var(--dim);word-break:break-all}
73300
+ td.prop{color:var(--ink)}
73301
+ td.num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
73302
+ .delta{font-weight:600}
73303
+ .delta.neg{color:var(--bad)}
73304
+ .delta.pos{color:var(--warn)}
73305
+ .panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;overflow:hidden}
73306
+ .panel .hd{padding:11px 14px;border-bottom:1px solid var(--line);display:flex;gap:10px;align-items:center;
73307
+ flex-wrap:wrap}
73308
+ .panel .hd b{font-size:13px}
73309
+ .panel .bd{max-height:60vh;overflow:auto}
73310
+ .motion{padding:0}
73311
+ .motion li{list-style:none;padding:8px 14px;border-bottom:1px solid color-mix(in srgb,var(--line) 55%,transparent);
73312
+ display:grid;grid-template-columns:200px 150px 1fr;gap:10px;font-size:12px}
73313
+ .motion li:last-child{border-bottom:0}
73314
+ .motion .k{font-family:var(--mono);color:var(--dim);word-break:break-all}
73315
+
73316
+ /* panes */
73317
+ .panes{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:14px}
73318
+ .pane{background:var(--panel);border:1px solid var(--line);border-radius:12px;overflow:hidden}
73319
+ .pane .hd{padding:8px 12px;border-bottom:1px solid var(--line);font:11px/1.4 var(--mono);color:var(--dim);
73320
+ display:flex;justify-content:space-between;gap:8px}
73321
+ .pane iframe{width:100%;height:52vh;border:0;background:#fff;display:block}
73322
+ .note{background:var(--panel);border:1px dashed var(--line);border-radius:12px;padding:16px;color:var(--dim)}
73323
+ .note code{font-family:var(--mono);color:var(--ink);background:var(--panel-2);padding:1px 5px;border-radius:4px}
73324
+ .err{color:var(--bad)}
73325
+ </style>
73326
+ </head>
73327
+ <body>
73328
+ <header class="top">
73329
+ <div class="brand">parity <span id="ver"></span></div>
73330
+ <nav class="tabs" role="tablist">
73331
+ <button role="tab" data-view="board" aria-selected="true">Board</button>
73332
+ <button role="tab" data-view="diff" aria-selected="false">Diff</button>
73333
+ <button role="tab" data-view="run" aria-selected="false">Run</button>
73334
+ </nav>
73335
+ <div class="spacer"></div>
73336
+ <div class="meta" id="ctx"></div>
73337
+ </header>
73338
+
73339
+ <main>
73340
+ <section class="view" id="view-board">
73341
+ <div class="stats" id="stats"></div>
73342
+ <h2 id="board-title">Pages</h2>
73343
+ <p class="sub" id="board-sub"></p>
73344
+ <div class="lanes" id="lanes"></div>
73345
+ <div id="shell"></div>
73346
+ </section>
73347
+
73348
+ <section class="view" id="view-diff" hidden>
73349
+ <h2>Component diffs</h2>
73350
+ <p class="sub">From <code>parity bench</code> results on disk. Dirty first.</p>
73351
+ <div class="diffgrid">
73352
+ <div class="list" id="bench-list"></div>
73353
+ <div id="bench-detail"></div>
73354
+ </div>
73355
+ </section>
73356
+
73357
+ <section class="view" id="view-run" hidden>
73358
+ <h2>Latest run</h2>
73359
+ <div id="run-detail"></div>
73360
+ </section>
73361
+ </main>
73362
+
73363
+ <script>
73364
+ const $ = (s, r = document) => r.querySelector(s);
73365
+ const el = (t, props = {}, kids = []) => {
73366
+ const n = Object.assign(document.createElement(t), props);
73367
+ for (const k of [].concat(kids)) n.append(k);
73368
+ return n;
73369
+ };
73370
+ // Every value from the API lands in the DOM as TEXT, never as HTML. The server
73371
+ // reads a client's repo — component names, page paths and CSS selectors are
73372
+ // their content, not ours.
73373
+ const txt = (v) => document.createTextNode(String(v ?? ""));
73374
+
73375
+ const api = async (path) => {
73376
+ const r = await fetch(path);
73377
+ const body = await r.json().catch(() => ({ error: "unreadable response" }));
73378
+ return { ok: r.ok, body };
73379
+ };
73380
+
73381
+ let CTX = {};
73382
+
73383
+ function show(view) {
73384
+ for (const b of document.querySelectorAll("nav.tabs button"))
73385
+ b.setAttribute("aria-selected", String(b.dataset.view === view));
73386
+ for (const s of document.querySelectorAll(".view")) s.hidden = s.id !== \`view-\${view}\`;
73387
+ if (view === "diff") loadBench();
73388
+ if (view === "run") loadRun();
73389
+ }
73390
+ for (const b of document.querySelectorAll("nav.tabs button"))
73391
+ b.addEventListener("click", () => show(b.dataset.view));
73392
+
73393
+ function note(parent, msg, hint) {
73394
+ parent.replaceChildren(
73395
+ el("div", { className: "note" }, [el("div", {}, txt(msg)), hint ? el("p", {}, hint) : ""]),
73396
+ );
73397
+ }
73398
+
73399
+ const LANES = [
73400
+ ["backlog", "Backlog"],
73401
+ ["building", "Building"],
73402
+ ["triage", "Triage"],
73403
+ ["review", "Review"],
73404
+ ["done", "Done"],
73405
+ ["skipped", "Skipped"],
73406
+ ];
73407
+
73408
+ async function loadBoard() {
73409
+ const [plan, board] = await Promise.all([api("/api/plan"), api("/api/board")]);
73410
+ const stats = $("#stats");
73411
+ if (!plan.ok) {
73412
+ stats.replaceChildren();
73413
+ note(
73414
+ $("#lanes"),
73415
+ plan.body.error || "no plan",
73416
+ el("span", {}, [
73417
+ txt("Run "),
73418
+ el("code", {}, txt("parity migrate --url <prod>")),
73419
+ txt(" first — without a plan there is no inventory, and a survey without one silently reports zero missing components."),
73420
+ ]),
73421
+ );
73422
+ return;
73423
+ }
73424
+ const p = plan.body;
73425
+ const stat = (n, label) => el("div", { className: "stat" }, [el("b", {}, txt(n)), el("small", {}, txt(label))]);
73426
+ const c = p.components || {};
73427
+ stats.replaceChildren(
73428
+ stat(\`\${c.byStatus?.done ?? 0}/\${c.total ?? 0}\`, "components done"),
73429
+ stat(c.byStatus?.pending ?? 0, "pending"),
73430
+ stat(\`\${p.provenance?.library ?? 0}/\${(p.provenance?.library ?? 0) + (p.provenance?.built ?? 0)}\`, "from library"),
73431
+ stat(p.touches ?? 0, "human touches"),
73432
+ );
73433
+ $("#board-sub").replaceChildren(
73434
+ txt(\`\${p.url}\${p.target ? \` → \${p.target}\` : ""} · \${board.ok ? board.body.sampled : 0} pages sampled\`),
73435
+ );
73436
+
73437
+ if (!board.ok) return note($("#lanes"), board.body.error || "no board");
73438
+ const lanes = $("#lanes");
73439
+ lanes.replaceChildren();
73440
+ const cards = board.body.columns || {};
73441
+ for (const [key, label] of LANES) {
73442
+ const items = cards[key] || [];
73443
+ if (!items.length && (key === "skipped" || key === "triage")) continue;
73444
+ const lane = el("div", { className: "lane" }, [
73445
+ el("h3", {}, [txt(label), el("em", {}, txt(items.length))]),
73446
+ ]);
73447
+ if (!items.length) lane.append(el("div", { className: "empty" }, txt("nothing here")));
73448
+ for (const item of items) {
73449
+ const btn = el("button", { className: "card", type: "button" }, [
73450
+ el("div", { className: "path" }, txt(item.path)),
73451
+ ]);
73452
+ const counts = item.counts || {};
73453
+ // blockers is page-scope only, by design: globals block every page, so
73454
+ // repeating them per card is noise. They show in the Shell strip instead.
73455
+ const why = item.blockers?.length
73456
+ ? \`blocked by \${item.blockers.join(", ")}\`
73457
+ : counts.validate
73458
+ ? \`\${counts.validate} to validate\`
73459
+ : item.ready
73460
+ ? "nothing left to build or validate"
73461
+ : "";
73462
+ const meta = el("div", { className: "row2", style: "margin-top:6px" }, [
73463
+ el("span", { className: "chip" }, txt(item.kind)),
73464
+ ]);
73465
+ if (counts.build) meta.append(el("span", { className: "chip bad" }, txt(\`\${counts.build} to build\`)));
73466
+ if (counts["as-is"]) meta.append(el("span", { className: "chip" }, txt(\`\${counts["as-is"]} as-is\`)));
73467
+ if (counts.upgrade) meta.append(el("span", { className: "chip warn" }, txt(\`\${counts.upgrade} upgrade\`)));
73468
+ if (why) btn.append(el("div", { className: "why" }, txt(why)));
73469
+ btn.append(meta);
73470
+ btn.addEventListener("click", () => loadPage(item.path));
73471
+ lane.append(btn);
73472
+ }
73473
+ lanes.append(lane);
73474
+ }
73475
+
73476
+ const shellItems = board.body.shell || [];
73477
+ const noPage = board.body.unassigned || [];
73478
+ const extra = $("#shell");
73479
+ extra.replaceChildren();
73480
+ const strip = (title, list, hint) => {
73481
+ if (!list.length) return;
73482
+ const box = el("div", { className: "lane", style: "margin-top:14px" }, [
73483
+ el("h3", {}, [txt(title), el("em", {}, txt(list.length))]),
73484
+ el("p", { className: "why", style: "margin:0 0 8px" }, txt(hint)),
73485
+ ]);
73486
+ for (const s of list)
73487
+ box.append(el("span", { className: "chip", style: "margin:0 4px 4px 0" }, txt(s.name ?? s)));
73488
+ extra.append(box);
73489
+ };
73490
+ strip("Shell", shellItems, "Globals. They block every page at once, so they are reported once instead of on each card.");
73491
+ strip("No page", noPage, "Components the code defines that no sampled page uses. Listed rather than hidden: real work with no lane.");
73492
+ }
73493
+
73494
+ async function loadPage(path) {
73495
+ const r = await api(\`/api/page?path=\${encodeURIComponent(path)}\`);
73496
+ show("diff");
73497
+ const box = $("#bench-detail");
73498
+ if (!r.ok) return note(box, r.body.error || "no worksheet");
73499
+ const w = r.body;
73500
+ const DISP = { build: "bad", validate: "warn", upgrade: "warn", "as-is": "", settled: "ok" };
73501
+ const rows = (w.tasks || []).map((t) =>
73502
+ el("tr", {}, [
73503
+ el("td", { className: "prop" }, txt(t.name)),
73504
+ el("td", {}, el("span", { className: \`chip \${DISP[t.disposition] ?? ""}\`}, txt(t.disposition))),
73505
+ el("td", { className: "sel" }, txt(t.against ? \`\${t.against.kind}: \${t.against.url}\` : "")),
73506
+ // The worksheet already built the command; showing it is what makes this
73507
+ // a place to work from rather than a status page.
73508
+ el("td", { className: "sel" }, txt(t.command || t.note || "")),
73509
+ ]),
73510
+ );
73511
+ box.replaceChildren(
73512
+ el("div", { className: "panel" }, [
73513
+ el("div", { className: "hd" }, [
73514
+ el("b", {}, txt(path)),
73515
+ el("span", { className: \`chip \${w.ready ? "ok" : "warn"}\` }, txt(w.ready ? "ready" : "not ready")),
73516
+ ]),
73517
+ el("div", { className: "bd" }, [
73518
+ el("table", {}, [
73519
+ el("thead", {}, el("tr", {}, [
73520
+ el("th", {}, txt("component")),
73521
+ el("th", {}, txt("disposition")),
73522
+ el("th", {}, txt("measured against")),
73523
+ el("th", {}, txt("command")),
73524
+ ])),
73525
+ el("tbody", {}, rows.length ? rows : el("tr", {}, el("td", { colSpan: 4 },
73526
+ // Not the same as "nothing to do": the capture saw no components on
73527
+ // this page, so its scope is unconfirmed. That is the triage lane.
73528
+ txt("the capture recorded no components for this page — scope unconfirmed, not done")))),
73529
+ ]),
73530
+ ]),
73531
+ ]),
73532
+ );
73533
+ }
73534
+
73535
+ async function loadBench() {
73536
+ const list = $("#bench-list");
73537
+ const r = await api("/api/bench");
73538
+ if (!r.ok || !r.body.length) {
73539
+ list.replaceChildren(el("div", { className: "empty", style: "padding:10px" }, txt("no bench results yet")));
73540
+ note(
73541
+ $("#bench-detail"),
73542
+ "Nothing benched yet.",
73543
+ el("span", {}, [
73544
+ txt("Run "),
73545
+ el("code", {}, txt("parity bench --component <Name> --prod <ref> --cand <target>")),
73546
+ txt(" — it writes one JSON per component into the bench dir this cockpit is watching."),
73547
+ ]),
73548
+ );
73549
+ return;
73550
+ }
73551
+ list.replaceChildren();
73552
+ for (const b of r.body) {
73553
+ const btn = el("button", { type: "button", "aria-selected": "false" }, [
73554
+ el("div", { className: "name" }, txt(b.component)),
73555
+ el("div", { className: "row2" }, [
73556
+ el("span", { className: \`chip \${b.clean ? "ok" : "bad"}\` }, txt(b.clean ? "clean" : \`\${b.deltas} deltas\`)),
73557
+ b.motionFindings ? el("span", { className: "chip warn" }, txt(\`\${b.motionFindings} motion\`)) : "",
73558
+ el("span", { className: "chip" }, txt(b.viewport)),
73559
+ ]),
73560
+ ]);
73561
+ btn.addEventListener("click", () => {
73562
+ for (const o of list.querySelectorAll("button")) o.setAttribute("aria-selected", "false");
73563
+ btn.setAttribute("aria-selected", "true");
73564
+ loadBenchResult(b.file);
73565
+ });
73566
+ list.append(btn);
73567
+ }
73568
+ list.querySelector("button")?.click();
73569
+ }
73570
+
73571
+ async function loadBenchResult(file) {
73572
+ const box = $("#bench-detail");
73573
+ const r = await api(\`/api/bench/result?file=\${encodeURIComponent(file)}\`);
73574
+ if (!r.ok) return note(box, r.body.error || "unreadable");
73575
+ const d = r.body;
73576
+ const deltas = d.geometry?.deltas || [];
73577
+ const rows = deltas.map((x) =>
73578
+ el("tr", {}, [
73579
+ el("td", { className: "sel" }, txt(x.key)),
73580
+ el("td", { className: "prop" }, txt(x.prop)),
73581
+ el("td", { className: "num" }, txt(x.prod)),
73582
+ el("td", { className: "num" }, txt(x.cand)),
73583
+ el("td", {
73584
+ className: \`num delta \${x.deltaPx == null ? "" : x.deltaPx < 0 ? "neg" : "pos"}\`,
73585
+ }, txt(x.deltaPx == null ? "—" : (x.deltaPx > 0 ? \`+\${x.deltaPx}\` : x.deltaPx))),
73586
+ ]),
73587
+ );
73588
+
73589
+ const kids = [
73590
+ el("div", { className: "panel" }, [
73591
+ el("div", { className: "hd" }, [
73592
+ el("b", {}, txt(\`Component \${d.component}\`)),
73593
+ el("span", { className: \`chip \${d.clean ? "ok" : "bad"}\` }, txt(d.clean ? "clean" : \`\${deltas.length} deltas left\`)),
73594
+ el("span", { className: "chip" }, txt(d.viewport)),
73595
+ d.geometry?.truncated ? el("span", { className: "chip warn" }, txt("truncated — absence is not proof")) : "",
73596
+ ]),
73597
+ el("div", { className: "bd" }, [
73598
+ el("table", {}, [
73599
+ el("thead", {}, el("tr", {}, [
73600
+ el("th", {}, txt("selector")),
73601
+ el("th", {}, txt("property")),
73602
+ el("th", { style: "text-align:right" }, txt("prod")),
73603
+ el("th", { style: "text-align:right" }, txt("cand")),
73604
+ el("th", { style: "text-align:right" }, txt("Δ")),
73605
+ ])),
73606
+ el("tbody", {}, rows.length ? rows : el("tr", {}, el("td", { colSpan: 5 }, txt("geometry clean")))),
73607
+ ]),
73608
+ ]),
73609
+ ]),
73610
+ ];
73611
+
73612
+ const findings = d.motion?.findings || [];
73613
+ if (findings.length) {
73614
+ const ul = el("ul", { className: "motion" });
73615
+ for (const f of findings)
73616
+ ul.append(el("li", {}, [
73617
+ el("span", { className: "k" }, txt(f.key)),
73618
+ el("span", { className: \`chip \${f.kind.startsWith("missing") ? "bad" : "warn"}\` }, txt(f.kind)),
73619
+ el("span", {}, txt(f.detail)),
73620
+ ]));
73621
+ kids.push(el("div", { className: "panel", style: "margin-top:14px" }, [
73622
+ el("div", { className: "hd" }, [el("b", {}, txt("Motion")), el("span", { className: "chip bad" }, txt(\`\${findings.length} findings\`))]),
73623
+ ul,
73624
+ ]));
73625
+ }
73626
+
73627
+ // Side-by-side only when both URLs are known: an iframe pointed at nothing
73628
+ // renders a browser error page that reads like a broken candidate.
73629
+ if (CTX.prodUrl && CTX.candUrl) {
73630
+ const pane = (label, url) =>
73631
+ el("div", { className: "pane" }, [
73632
+ el("div", { className: "hd" }, [el("span", {}, txt(label)), el("span", {}, txt(url))]),
73633
+ el("iframe", { src: \`/proxy?url=\${encodeURIComponent(url)}\`, loading: "lazy", referrerPolicy: "no-referrer" }),
73634
+ ]);
73635
+ kids.push(el("div", { className: "panes" }, [pane("prod", CTX.prodUrl), pane("cand", CTX.candUrl)]));
73636
+ }
73637
+ box.replaceChildren(...kids);
73638
+ }
73639
+
73640
+ async function loadRun() {
73641
+ const box = $("#run-detail");
73642
+ const r = await api("/api/run");
73643
+ if (!r.ok) {
73644
+ return note(box, r.body.error || "no runs", el("span", {}, [
73645
+ txt("Run "), el("code", {}, txt("parity run --prod <url> --cand <url>")), txt(" to produce one."),
73646
+ ]));
73647
+ }
73648
+ const run = r.body;
73649
+ const v = run.verdict || {};
73650
+ const cls = v.status === "pass" ? "ok" : v.status === "fail" ? "bad" : "warn";
73651
+ const trend = run.previousRun ? \` (\${run.previousRun.scoreDelta >= 0 ? "+" : ""}\${run.previousRun.scoreDelta} vs previous)\` : "";
73652
+ const checkRows = (run.checks || []).map((c) =>
73653
+ el("tr", {}, [
73654
+ el("td", { className: "prop" }, txt(c.name)),
73655
+ el("td", {}, el("span", { className: \`chip \${c.status === "pass" ? "ok" : c.status === "fail" ? "bad" : "warn"}\` }, txt(c.status))),
73656
+ el("td", { className: "num" }, txt(c.issues)),
73657
+ el("td", { className: "sel" }, txt(c.summary)),
73658
+ ]),
73659
+ );
73660
+ box.replaceChildren(
73661
+ el("div", { className: "stats" }, [
73662
+ el("div", { className: "stat" }, [el("b", {}, txt(\`\${v.score ?? "?"}\${trend}\`)), el("small", {}, txt("score"))]),
73663
+ el("div", { className: "stat" }, [el("b", {}, txt(v.critical ?? 0)), el("small", {}, txt("critical"))]),
73664
+ el("div", { className: "stat" }, [el("b", {}, txt(v.high ?? 0)), el("small", {}, txt("high"))]),
73665
+ el("div", { className: "stat" }, [el("b", {}, txt(\`\${v.checksPassed ?? 0}/\${v.checksRun ?? 0}\`)), el("small", {}, txt("checks passed"))]),
73666
+ ]),
73667
+ el("div", { className: "panel" }, [
73668
+ el("div", { className: "hd" }, [
73669
+ el("b", {}, txt(run.id)),
73670
+ el("span", { className: \`chip \${cls}\` }, txt(v.status ?? "?")),
73671
+ el("span", { className: "chip" }, txt(new Date(run.timestamp).toLocaleString())),
73672
+ ]),
73673
+ el("div", { className: "bd" }, [
73674
+ el("table", {}, [
73675
+ el("thead", {}, el("tr", {}, [
73676
+ el("th", {}, txt("check")), el("th", {}, txt("status")),
73677
+ el("th", { style: "text-align:right" }, txt("issues")), el("th", {}, txt("summary")),
73678
+ ])),
73679
+ el("tbody", {}, checkRows),
73680
+ ]),
73681
+ ]),
73682
+ ]),
73683
+ );
73684
+ }
73685
+
73686
+ (async () => {
73687
+ const r = await api("/api/context");
73688
+ CTX = r.ok ? r.body : {};
73689
+ $("#ctx").replaceChildren(txt(\`\${CTX.planDir ?? ""}\`));
73690
+ const s = await api("/api/state");
73691
+ if (s.ok) $("#ver").replaceChildren(txt(\`· \${s.body.phase ?? ""}\${s.body.stage ? \` / \${s.body.stage}\` : ""}\`));
73692
+ loadBoard();
73693
+ })();
73694
+ </script>
73695
+ </body>
73696
+ </html>
73697
+ `;
73698
+
73699
+ // src/server/cockpit.ts
73700
+ async function startCockpit(ctx, opts = {}) {
73701
+ const server = createServer2((req, res) => {
73702
+ handle(req, res, ctx).catch((err) => {
73703
+ try {
73704
+ res.statusCode = 500;
73705
+ res.setHeader("content-type", "application/json");
73706
+ res.end(JSON.stringify({ error: err.message }));
73707
+ } catch {}
73708
+ });
73709
+ });
73710
+ await new Promise((ready, reject) => {
73711
+ server.once("error", reject);
73712
+ server.listen(opts.port ?? 0, opts.host ?? "127.0.0.1", () => ready());
73713
+ });
73714
+ const addr = server.address();
73715
+ const port = typeof addr === "object" && addr ? addr.port : 0;
73716
+ const host = opts.host ?? "127.0.0.1";
73717
+ return {
73718
+ port,
73719
+ url: `http://${host}:${port}/`,
73720
+ close: () => new Promise((done) => {
73721
+ try {
73722
+ server.closeAllConnections?.();
73723
+ server.closeIdleConnections?.();
73724
+ } catch {}
73725
+ server.close(() => done());
73726
+ setTimeout(() => done(), 1000);
73727
+ })
73728
+ };
73729
+ }
73730
+ async function handle(req, res, ctx) {
73731
+ const url = new URL(req.url ?? "/", "http://placeholder");
73732
+ const path = decodeURIComponent(url.pathname);
73733
+ const api = cockpitApi(path, url.searchParams, ctx);
73734
+ if (api) {
73735
+ res.statusCode = api.status;
73736
+ res.setHeader("content-type", "application/json; charset=utf-8");
73737
+ res.setHeader("cache-control", "no-store");
73738
+ res.end(JSON.stringify(api.body));
73739
+ return;
73740
+ }
73741
+ if (path === "/proxy") {
73742
+ const target = url.searchParams.get("url");
73743
+ if (!target) {
73744
+ res.statusCode = 400;
73745
+ res.end("missing ?url=");
73746
+ return;
73747
+ }
73748
+ return proxyRequest(req, res, target, {
73749
+ forceMobile: url.searchParams.get("viewport") === "mobile"
73750
+ });
73751
+ }
73752
+ if (path === "/" || path === "/index.html") {
73753
+ res.statusCode = 200;
73754
+ res.setHeader("content-type", "text/html; charset=utf-8");
73755
+ res.setHeader("cache-control", "no-store");
73756
+ res.end(COCKPIT_HTML);
73757
+ return;
73758
+ }
73759
+ res.statusCode = 404;
73760
+ res.setHeader("content-type", "application/json");
73761
+ res.end(JSON.stringify({ error: `no route ${path}` }));
73762
+ }
73763
+
73764
+ // src/commands/cockpit.ts
73765
+ async function cockpitCommand(opts) {
73766
+ const ctx = {
73767
+ planDir: resolve9(opts.dir),
73768
+ output: resolve9(opts.output),
73769
+ benchDir: resolve9(opts.benchDir),
73770
+ prodUrl: opts.prodUrl,
73771
+ candUrl: opts.candUrl
73772
+ };
73773
+ let handle;
73774
+ try {
73775
+ handle = await startCockpit(ctx, {
73776
+ port: opts.port ? Number.parseInt(opts.port, 10) : undefined,
73777
+ host: opts.host
73778
+ });
73779
+ } catch (err) {
73780
+ console.error(chalk29.red(` ✖ could not start the cockpit: ${err.message}`));
73781
+ return 2;
73782
+ }
73783
+ console.log("");
73784
+ console.log(chalk29.bold(" parity cockpit"));
73785
+ console.log(` ${chalk29.green("●")} ${handle.url}`);
73786
+ console.log(chalk29.dim(` plan ${ctx.planDir}`));
73787
+ console.log(chalk29.dim(` runs ${ctx.output}`));
73788
+ console.log(chalk29.dim(` bench ${ctx.benchDir}`));
73789
+ if (opts.host && opts.host !== "127.0.0.1" && opts.host !== "localhost") {
73790
+ console.log(chalk29.yellow(` ⚠ bound to ${opts.host} — this server is unauthenticated, reads the repo, and proxies arbitrary URLs`));
73791
+ }
73792
+ console.log(chalk29.dim(` Ctrl+C to stop.
73793
+ `));
73794
+ if (opts.open !== false) {
73795
+ const { default: openUrl } = await import("open");
73796
+ await openUrl(handle.url).catch(() => {
73797
+ return;
73798
+ });
73799
+ }
73800
+ await new Promise((done) => {
73801
+ const stop = () => {
73802
+ handle.close().finally(() => done());
73803
+ };
73804
+ process.once("SIGINT", stop);
73805
+ process.once("SIGTERM", stop);
73806
+ });
73807
+ return 0;
73808
+ }
73809
+
73810
+ // src/commands/mcp.ts
73811
+ import { createInterface as createInterface3 } from "node:readline";
73812
+ import { resolve as resolve11 } from "node:path";
73813
+
73814
+ // src/util/version.ts
73815
+ import { readFileSync as readFileSync34 } from "node:fs";
73816
+ import { dirname as dirname6, resolve as resolve10 } from "node:path";
73817
+ import { fileURLToPath } from "node:url";
73818
+ function getPackageVersion() {
73819
+ try {
73820
+ const here = dirname6(fileURLToPath(import.meta.url));
73821
+ for (const up of ["..", "../..", "../../.."]) {
73822
+ try {
73823
+ const pkgPath = resolve10(here, up, "package.json");
73824
+ const raw = readFileSync34(pkgPath, "utf8");
73825
+ const parsed = JSON.parse(raw);
73826
+ if (parsed.name === "@decocms/parity" && typeof parsed.version === "string") {
73827
+ return parsed.version;
73828
+ }
73829
+ } catch {}
73830
+ }
73831
+ } catch {}
73832
+ return "0.0.0";
73833
+ }
73834
+
73835
+ // src/mcp/rpc.ts
73836
+ var MCP_PROTOCOL_VERSION = "2024-11-05";
73837
+ var RpcError = {
73838
+ parse: -32700,
73839
+ invalidRequest: -32600,
73840
+ methodNotFound: -32601,
73841
+ invalidParams: -32602,
73842
+ internal: -32603
73843
+ };
73844
+ var ok = (text) => ({ content: [{ type: "text", text }] });
73845
+ var fail2 = (text) => ({
73846
+ content: [{ type: "text", text }],
73847
+ isError: true
73848
+ });
73849
+ var json = (value) => ok(JSON.stringify(value, null, 2));
73850
+ async function dispatch(req, opts) {
73851
+ const isNotification = req.id === undefined;
73852
+ const id = req.id ?? null;
73853
+ const reply = (result) => isNotification ? null : { jsonrpc: "2.0", id, result };
73854
+ const error = (code, message) => isNotification ? null : { jsonrpc: "2.0", id, error: { code, message } };
73855
+ switch (req.method) {
73856
+ case "initialize":
73857
+ return reply({
73858
+ protocolVersion: MCP_PROTOCOL_VERSION,
73859
+ capabilities: { tools: {} },
73860
+ serverInfo: opts.serverInfo
73861
+ });
73862
+ case "notifications/initialized":
73863
+ case "initialized":
73864
+ return null;
73865
+ case "ping":
73866
+ return reply({});
73867
+ case "tools/list":
73868
+ return reply({
73869
+ tools: opts.tools.map((t) => ({
73870
+ name: t.name,
73871
+ description: t.description,
73872
+ inputSchema: t.inputSchema
73873
+ }))
73874
+ });
73875
+ case "tools/call": {
73876
+ const name = typeof req.params?.name === "string" ? req.params.name : null;
73877
+ if (!name)
73878
+ return error(RpcError.invalidParams, "tools/call requires params.name");
73879
+ const tool = opts.tools.find((t) => t.name === name);
73880
+ if (!tool)
73881
+ return error(RpcError.invalidParams, `unknown tool: ${name}`);
73882
+ if (tool.writes && !opts.allowWrites) {
73883
+ return reply(fail2(`${name} mutates the migration plan and this server is read-only. Restart it with --allow-writes.`));
73884
+ }
73885
+ const args = typeof req.params?.arguments === "object" && req.params.arguments !== null ? req.params.arguments : {};
73886
+ try {
73887
+ return reply(await tool.handler(args));
73888
+ } catch (err) {
73889
+ return reply(fail2(`${name} failed: ${err.message}`));
73890
+ }
73891
+ }
73892
+ default:
73893
+ return error(RpcError.methodNotFound, `method not found: ${req.method}`);
73894
+ }
73895
+ }
73896
+ function parseLine(line) {
73897
+ const trimmed = line.trim();
73898
+ if (!trimmed)
73899
+ return null;
73900
+ let parsed;
73901
+ try {
73902
+ parsed = JSON.parse(trimmed);
73903
+ } catch {
73904
+ return {
73905
+ res: {
73906
+ jsonrpc: "2.0",
73907
+ id: null,
73908
+ error: { code: RpcError.parse, message: "invalid JSON" }
73909
+ }
73910
+ };
73911
+ }
73912
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
73913
+ return {
73914
+ res: {
73915
+ jsonrpc: "2.0",
73916
+ id: null,
73917
+ error: { code: RpcError.invalidRequest, message: "expected a JSON-RPC object" }
73918
+ }
73919
+ };
73920
+ }
73921
+ const obj = parsed;
73922
+ if (typeof obj.method !== "string") {
73923
+ return {
73924
+ res: {
73925
+ jsonrpc: "2.0",
73926
+ id: obj.id ?? null,
73927
+ error: { code: RpcError.invalidRequest, message: "missing method" }
73928
+ }
73929
+ };
73930
+ }
73931
+ return { req: obj };
73932
+ }
73933
+
73934
+ // src/mcp/tools.ts
73935
+ import { existsSync as existsSync30, readFileSync as readFileSync35 } from "node:fs";
73936
+ import { join as join40 } from "node:path";
73937
+ var STR = { type: "string" };
73938
+ var NONE = { type: "object", properties: {}, additionalProperties: false };
73939
+ function withPlan2(ctx, fn) {
73940
+ const plan = loadPlan(ctx.planDir);
73941
+ if (!plan) {
73942
+ return {
73943
+ missing: `no migration-plan.json in ${ctx.planDir}. Run \`parity migrate --url <prod>\` first — without a plan there is no inventory, and a survey without one silently reports zero missing components.`
73944
+ };
73945
+ }
73946
+ return fn(plan);
73947
+ }
73948
+ var planOrFail = (ctx, fn) => {
73949
+ const out = withPlan2(ctx, fn);
73950
+ if (out && typeof out === "object" && "missing" in out)
73951
+ return fail2(String(out.missing));
73952
+ return json(out);
73953
+ };
73954
+ function mutate(ctx, fn) {
73955
+ const plan = loadPlan(ctx.planDir);
73956
+ if (!plan)
73957
+ return fail2(`no migration-plan.json in ${ctx.planDir}`);
73958
+ const message = fn(plan);
73959
+ if (message === null)
73960
+ return fail2("no matching row in the plan");
73961
+ savePlan(ctx.planDir, plan);
73962
+ return ok(message);
73963
+ }
73964
+ var str = (args, key) => typeof args[key] === "string" && args[key] ? args[key] : null;
73965
+ function createTools(ctx) {
73966
+ return [
73967
+ {
73968
+ name: "MIGRATION_STATE",
73969
+ description: "The orchestrator's own state: phase, stage, round, current page, score and trend, budget. Read this first — it says what the run is doing and what it is allowed to care about.",
73970
+ inputSchema: NONE,
73971
+ handler: () => {
73972
+ const p = join40(ctx.planDir, "migration.json");
73973
+ if (!existsSync30(p)) {
73974
+ return fail2(`no migration.json in ${ctx.planDir} — no migration has been started here`);
73975
+ }
73976
+ try {
73977
+ return json(JSON.parse(readFileSync35(p, "utf8")));
73978
+ } catch (err) {
73979
+ return fail2(`migration.json is not valid JSON: ${err.message}`);
73980
+ }
73981
+ }
73982
+ },
73983
+ {
73984
+ name: "PLAN_STATUS",
73985
+ description: "The inventory: components settled vs remaining, pages awaiting content, plus the two run-level numbers — reuse (library vs written here) and human touches. `as-is` and `upgrade` are reported apart from settled, because 'we tolerated a difference' and 'we did it better' are the two lines a stakeholder asks about and both look identical to a visual diff.",
73986
+ inputSchema: NONE,
73987
+ handler: () => planOrFail(ctx, (plan) => ({
73988
+ url: plan.url,
73989
+ target: plan.target.name,
73990
+ ...planProgress(plan),
73991
+ provenance: provenanceCounts(plan),
73992
+ touches: totalTouches(plan)
73993
+ }))
73994
+ },
73995
+ {
73996
+ name: "PLAN_BOARD",
73997
+ description: "Every sampled page in a lane (triage/backlog/building/review/done) with what blocks it, plus `shell` (globals, which block every page) and `no page` (components no sampled page uses). Lanes are DERIVED from the page's components, so a page cannot read as done while something it needs is missing.",
73998
+ inputSchema: {
73999
+ type: "object",
74000
+ properties: { candUrl: STR },
74001
+ additionalProperties: false
74002
+ },
74003
+ handler: (args) => planOrFail(ctx, (plan) => planBoard(plan, str(args, "candUrl") ?? ctx.candUrl))
74004
+ },
74005
+ {
74006
+ name: "PAGE_WORKSHEET",
74007
+ description: "One page's components grouped by what to do about them (build | validate | upgrade | as-is | settled), each with a runnable command. `ready: true` means nothing is left to build or validate. Note that GLOBAL components (header, footer, nav) are not page members in the capture, so they never appear here — settle them first or a global fix reopens closed pages.",
74008
+ inputSchema: {
74009
+ type: "object",
74010
+ properties: { path: STR, candUrl: STR },
74011
+ required: ["path"],
74012
+ additionalProperties: false
74013
+ },
74014
+ handler: (args) => {
74015
+ const path = str(args, "path");
74016
+ if (!path)
74017
+ return fail2("path is required");
74018
+ const out = withPlan2(ctx, (plan) => pagePlan(plan, path, str(args, "candUrl") ?? ctx.candUrl));
74019
+ if (out && typeof out === "object" && "missing" in out)
74020
+ return fail2(String(out.missing));
74021
+ if (out === null)
74022
+ return fail2(`the plan has no page at ${path}`);
74023
+ return json(out);
74024
+ }
74025
+ },
74026
+ {
74027
+ name: "RUN_LIST",
74028
+ description: "Saved parity runs, newest first: id, timestamp, report path.",
74029
+ inputSchema: {
74030
+ type: "object",
74031
+ properties: { limit: { type: "number" } },
74032
+ additionalProperties: false
74033
+ },
74034
+ handler: (args) => {
74035
+ const limit = typeof args.limit === "number" ? args.limit : 20;
74036
+ return json(listRuns(ctx.output).slice(0, limit));
74037
+ }
74038
+ },
74039
+ {
74040
+ name: "RUN_REPORT",
74041
+ description: "One run's verdict, top issues and per-check results — the score with its receipts. Pass no id for the most recent run.",
74042
+ inputSchema: {
74043
+ type: "object",
74044
+ properties: { runId: STR },
74045
+ additionalProperties: false
74046
+ },
74047
+ handler: (args) => {
74048
+ const id = str(args, "runId") ?? listRuns(ctx.output)[0]?.id;
74049
+ if (!id)
74050
+ return fail2(`no runs found under ${ctx.output}`);
74051
+ try {
74052
+ const run = loadRun(ctx.output, id);
74053
+ return json({
74054
+ id: run.id,
74055
+ timestamp: run.timestamp,
74056
+ prodUrl: run.prodUrl,
74057
+ candUrl: run.candUrl,
74058
+ verdict: run.verdict,
74059
+ previousRun: run.previousRun ?? null,
74060
+ topIssues: run.topIssues,
74061
+ checks: run.checks.map((c) => ({
74062
+ name: c.name,
74063
+ status: c.status,
74064
+ severity: c.severity,
74065
+ summary: c.summary,
74066
+ issues: c.issues.length
74067
+ }))
74068
+ });
74069
+ } catch (err) {
74070
+ return fail2(err.message);
74071
+ }
74072
+ }
74073
+ },
74074
+ {
74075
+ name: "SET_STATUS",
74076
+ description: "Flip a component's porting status: pending | partial | done | as-is | upgrade | skipped. `as-is` and `upgrade` mean 'stop opening work for this' and are the USER's call — an agent setting them itself is how a real gap disappears from view.",
74077
+ inputSchema: {
74078
+ type: "object",
74079
+ properties: { name: STR, status: STR },
74080
+ required: ["name", "status"],
74081
+ additionalProperties: false
74082
+ },
74083
+ writes: true,
74084
+ handler: (args) => {
74085
+ const name = str(args, "name");
74086
+ const status = str(args, "status");
74087
+ if (!name || !status)
74088
+ return fail2("name and status are required");
74089
+ const allowed = ["pending", "partial", "done", "as-is", "upgrade", "skipped"];
74090
+ if (!allowed.includes(status)) {
74091
+ return fail2(`invalid status "${status}". Use one of: ${allowed.join(", ")}`);
74092
+ }
74093
+ return mutate(ctx, (plan) => {
74094
+ const c = setComponentStatus(plan, name, status);
74095
+ return c ? `${c.name} → ${status}` : null;
74096
+ });
74097
+ }
74098
+ },
74099
+ {
74100
+ name: "SET_PAGE_STATUS",
74101
+ description: "Flip a page's readiness: pending (no route yet) | code (route + sections exist but the CMS has nothing published, so it renders empty — the most common real state) | done (code AND content) | skipped.",
74102
+ inputSchema: {
74103
+ type: "object",
74104
+ properties: { path: STR, status: STR },
74105
+ required: ["path", "status"],
74106
+ additionalProperties: false
74107
+ },
74108
+ writes: true,
74109
+ handler: (args) => {
74110
+ const path = str(args, "path");
74111
+ const status = str(args, "status");
74112
+ if (!path || !status)
74113
+ return fail2("path and status are required");
74114
+ const allowed = ["pending", "code", "done", "skipped"];
74115
+ if (!allowed.includes(status)) {
74116
+ return fail2(`invalid status "${status}". Use one of: ${allowed.join(", ")}`);
74117
+ }
74118
+ return mutate(ctx, (plan) => {
74119
+ const p = setPageStatus(plan, path, status);
74120
+ return p ? `${p.path} → ${status}` : null;
74121
+ });
74122
+ }
74123
+ },
74124
+ {
74125
+ name: "SET_PROVENANCE",
74126
+ description: "Record where a shipped component came from: `library` (reused from the shared target template) or `built` (written for this migration). Rollouts are priced on store N costing less than store N-1, and reuse is the only mechanism that delivers that.",
74127
+ inputSchema: {
74128
+ type: "object",
74129
+ properties: { name: STR, provenance: STR },
74130
+ required: ["name", "provenance"],
74131
+ additionalProperties: false
74132
+ },
74133
+ writes: true,
74134
+ handler: (args) => {
74135
+ const name = str(args, "name");
74136
+ const provenance = str(args, "provenance");
74137
+ if (!name || provenance !== "library" && provenance !== "built") {
74138
+ return fail2("name is required and provenance must be `library` or `built`");
74139
+ }
74140
+ return mutate(ctx, (plan) => {
74141
+ const c = setComponentProvenance(plan, name, provenance);
74142
+ return c ? `${c.name} → ${provenance}` : null;
74143
+ });
74144
+ }
74145
+ },
74146
+ {
74147
+ name: "TOUCH",
74148
+ description: "Count one occasion where a PERSON pointed at a defect the tooling did not surface. This is the metric that says whether the loop is converging — one real page took fourteen. Do not call it for the tool's own findings; padding it destroys the signal it carries.",
74149
+ inputSchema: {
74150
+ type: "object",
74151
+ properties: { page: STR },
74152
+ required: ["page"],
74153
+ additionalProperties: false
74154
+ },
74155
+ writes: true,
74156
+ handler: (args) => {
74157
+ const page = str(args, "page");
74158
+ if (!page)
74159
+ return fail2("page is required");
74160
+ return mutate(ctx, (plan) => {
74161
+ const n = recordTouch(plan, page);
74162
+ return `${page} → ${n} human touch(es); ${totalTouches(plan)} in this migration`;
74163
+ });
74164
+ }
74165
+ }
74166
+ ];
74167
+ }
74168
+
74169
+ // src/commands/mcp.ts
74170
+ async function mcpCommand(opts) {
74171
+ const version = getPackageVersion();
74172
+ const tools = createTools({
74173
+ planDir: resolve11(opts.dir),
74174
+ output: resolve11(opts.output),
74175
+ candUrl: opts.candUrl
74176
+ });
74177
+ const write = (res) => process.stdout.write(`${JSON.stringify(res)}
74178
+ `);
74179
+ process.stderr.write(`parity mcp ${version} — ${tools.length} tools, ${opts.allowWrites ? "writes ALLOWED" : "read-only"}
74180
+ `);
74181
+ const rl = createInterface3({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });
74182
+ let queue = Promise.resolve();
74183
+ for await (const line of rl) {
74184
+ const parsed = parseLine(line);
74185
+ if (!parsed)
74186
+ continue;
74187
+ if ("res" in parsed) {
74188
+ write(parsed.res);
74189
+ continue;
74190
+ }
74191
+ const req = parsed.req;
74192
+ queue = queue.then(async () => {
74193
+ const res = await dispatch(req, {
74194
+ tools,
74195
+ serverInfo: { name: "parity", version },
74196
+ allowWrites: Boolean(opts.allowWrites)
74197
+ });
74198
+ if (res)
74199
+ write(res);
74200
+ });
74201
+ }
74202
+ await queue;
74203
+ return 0;
74204
+ }
74205
+
74206
+ // src/commands/states.ts
74207
+ import chalk30 from "chalk";
72182
74208
  var HOVERABLE = "a,button,summary,[role='button'],[role='menuitem'],label";
72183
- async function readStateEffects(page, selector, base, max) {
74209
+ var SETTLE_RETRY_FACTOR = 4;
74210
+ async function readStateEffects(page, opts) {
74211
+ const { selector, base, max, settleMs } = opts;
74212
+ await page.waitForTimeout(settleMs);
74213
+ const control = await readDelta(page, selector, base);
74214
+ const ambient = new Set((control?.deltas ?? []).map((d) => `${d.key}\x00${d.prop}`));
72184
74215
  const root = page.locator(selector).first();
72185
74216
  const targets = root.locator(HOVERABLE);
72186
74217
  const total = await targets.count().catch(() => 0);
@@ -72188,61 +74219,123 @@ async function readStateEffects(page, selector, base, max) {
72188
74219
  const effects = [];
72189
74220
  for (let i = 0;i < take; i++) {
72190
74221
  const el = targets.nth(i);
72191
- const meta = await el.evaluate((node) => {
74222
+ const meta = await el.evaluate((node, sel) => {
74223
+ const root = document.querySelector(sel);
72192
74224
  const parts = [];
72193
74225
  let cur = node;
72194
- while (cur?.parentElement) {
74226
+ while (cur && cur !== root) {
74227
+ const parent = cur.parentElement;
74228
+ if (!parent)
74229
+ break;
72195
74230
  const t = cur.tagName.toLowerCase();
72196
74231
  let idx = 0;
72197
- for (const sib of Array.from(cur.parentElement.children)) {
74232
+ for (const sib of Array.from(parent.children)) {
72198
74233
  if (sib === cur)
72199
74234
  break;
72200
74235
  if (sib.tagName.toLowerCase() === t)
72201
74236
  idx++;
72202
74237
  }
72203
74238
  parts.unshift(`${t}[${idx}]`);
72204
- cur = cur.parentElement;
74239
+ cur = parent;
72205
74240
  }
74241
+ const rootTag = root?.tagName.toLowerCase();
72206
74242
  return {
72207
- path: parts.join(">"),
74243
+ path: rootTag ? [rootTag, ...parts].join(">") : parts.join(">"),
72208
74244
  label: node.getAttribute("data-testid") ?? node.getAttribute("aria-label") ?? ((node.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 30) || null)
72209
74245
  };
72210
- }).catch(() => null);
74246
+ }, opts.selector).catch(() => null);
72211
74247
  if (!meta)
72212
74248
  continue;
72213
74249
  const hovered = await el.hover({ timeout: 2000 }).then(() => true).catch(() => false);
72214
74250
  if (!hovered)
72215
74251
  continue;
72216
- await page.waitForTimeout(60);
72217
- const after = await readBoxTree(page, selector);
74252
+ await page.waitForTimeout(settleMs);
74253
+ let delta = await readDelta(page, selector, base);
74254
+ if (delta && delta.deltas.length === 0) {
74255
+ await page.waitForTimeout(settleMs * SETTLE_RETRY_FACTOR);
74256
+ delta = await readDelta(page, selector, base);
74257
+ }
72218
74258
  await page.mouse.move(0, 0).catch(() => {
72219
74259
  return;
72220
74260
  });
72221
- if (!after.found)
74261
+ if (!delta)
72222
74262
  continue;
72223
- const delta = diffBoxTrees(base, after.nodes, { tolerancePx: 0 });
72224
- if (delta.deltas.length === 0)
74263
+ const attributable = delta.deltas.filter((d) => !ambient.has(`${d.key}\x00${d.prop}`));
74264
+ const changes = attributable.map((d) => ({
74265
+ node: d.key,
74266
+ prop: d.prop,
74267
+ comparable: d.key === meta.path || delta.stable(d.key)
74268
+ }));
74269
+ if (changes.length === 0) {
74270
+ effects.push({
74271
+ target: meta.path,
74272
+ label: meta.label,
74273
+ changedProps: 0,
74274
+ properties: [],
74275
+ changes: [],
74276
+ renumberedNodes: 0
74277
+ });
72225
74278
  continue;
74279
+ }
72226
74280
  effects.push({
72227
74281
  target: meta.path,
72228
74282
  label: meta.label,
72229
- changedProps: delta.deltas.length,
72230
- properties: [...new Set(delta.deltas.map((d) => d.prop))].sort()
74283
+ changedProps: changes.length,
74284
+ properties: [...new Set(changes.map((c) => c.prop))].sort(),
74285
+ changes,
74286
+ renumberedNodes: delta.renumbered
72231
74287
  });
72232
74288
  }
72233
- return { effects, truncated: total > take };
74289
+ return { effects, truncated: total > take, ambient: ambient.size };
74290
+ }
74291
+ var fingerprint = (n) => `${n.tag}\x00${n.label ?? ""}\x00${n.text ?? ""}`;
74292
+ async function readDelta(page, selector, base) {
74293
+ const after = await readBoxTree(page, selector);
74294
+ if (!after.found)
74295
+ return null;
74296
+ const diff = diffBoxTrees(base, after.nodes, { tolerancePx: 0 });
74297
+ const beforeAt = new Map(base.map((n) => [n.key, fingerprint(n)]));
74298
+ const afterAt = new Map(after.nodes.map((n) => [n.key, fingerprint(n)]));
74299
+ const stable = (key) => {
74300
+ const b = beforeAt.get(key);
74301
+ const a = afterAt.get(key);
74302
+ return b !== undefined && a !== undefined && b === a;
74303
+ };
74304
+ return {
74305
+ deltas: diff.deltas,
74306
+ stable,
74307
+ renumbered: diff.deltas.filter((d) => !stable(d.key)).length,
74308
+ truncated: after.truncated
74309
+ };
72234
74310
  }
72235
74311
  async function gatherStates(browser, opts) {
72236
74312
  const ctx = await newContext(browser, { viewport: opts.viewport });
72237
74313
  const page = await ctx.newPage();
72238
- const out = { motion: { found: false, error: "not read" }, base: null, effects: [], truncated: false };
74314
+ const out = {
74315
+ motion: { found: false, error: "not read" },
74316
+ base: null,
74317
+ effects: [],
74318
+ truncated: false,
74319
+ ambient: 0
74320
+ };
72239
74321
  try {
72240
- await page.goto(opts.url, { waitUntil: "domcontentloaded", timeout: 30000 });
74322
+ const res = await page.goto(opts.url, { waitUntil: "domcontentloaded", timeout: 30000 }).catch((err) => err);
74323
+ if (res instanceof Error) {
74324
+ out.baseError = `${opts.url} não respondeu — ${res.message.split(`
74325
+ `)[0]}`;
74326
+ return out;
74327
+ }
74328
+ if (res && res.status() >= 400) {
74329
+ out.baseError = `${opts.url} respondeu HTTP ${res.status()}`;
74330
+ return out;
74331
+ }
72241
74332
  await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
72242
74333
  return;
72243
74334
  });
72244
74335
  if (opts.waitMs > 0)
72245
74336
  await page.waitForTimeout(opts.waitMs);
74337
+ await reloadIfOptionalFonts(page, opts.waitMs);
74338
+ out.settle = await waitForLayoutStable(page);
72246
74339
  await Promise.race([
72247
74340
  stabilizeCarousels(page).catch(() => {
72248
74341
  return;
@@ -72256,8 +74349,14 @@ async function gatherStates(browser, opts) {
72256
74349
  return out;
72257
74350
  }
72258
74351
  out.base = base.nodes;
72259
- const { effects, truncated } = await readStateEffects(page, opts.selector, base.nodes, opts.maxStates);
74352
+ const { effects, truncated, ambient } = await readStateEffects(page, {
74353
+ selector: opts.selector,
74354
+ base: base.nodes,
74355
+ max: opts.maxStates,
74356
+ settleMs: opts.settleMs
74357
+ });
72260
74358
  out.effects = effects;
74359
+ out.ambient = ambient;
72261
74360
  out.truncated = truncated || base.truncated;
72262
74361
  } finally {
72263
74362
  await page.close().catch(() => {
@@ -72271,50 +74370,117 @@ async function gatherStates(browser, opts) {
72271
74370
  }
72272
74371
  function diffEffects(prod, cand) {
72273
74372
  const byTarget = new Map(cand.map((e) => [e.target, e]));
74373
+ const labelSeen = new Map;
74374
+ for (const c of cand) {
74375
+ if (!c.label)
74376
+ continue;
74377
+ labelSeen.set(c.label, labelSeen.has(c.label) ? null : c);
74378
+ }
74379
+ const byLabel = new Map;
74380
+ for (const [k, v] of labelSeen)
74381
+ if (v)
74382
+ byLabel.set(k, v);
72274
74383
  const lost = [];
74384
+ const unpaired = [];
72275
74385
  const changed = [];
72276
- const seen = new Set;
74386
+ const used = new Set;
72277
74387
  for (const p of prod) {
72278
- const c = byTarget.get(p.target);
72279
- if (!c) {
74388
+ if (p.properties.length === 0)
74389
+ continue;
74390
+ const c = byTarget.get(p.target) ?? (p.label ? byLabel.get(p.label) : undefined);
74391
+ if (!c || used.has(c)) {
74392
+ unpaired.push(p);
74393
+ continue;
74394
+ }
74395
+ used.add(c);
74396
+ if (c.properties.length === 0) {
72280
74397
  lost.push(p);
72281
74398
  continue;
72282
74399
  }
72283
- seen.add(p.target);
72284
- if (p.properties.join(",") !== c.properties.join(","))
72285
- changed.push({ prod: p, cand: c });
74400
+ const missing = p.properties.filter((x) => !c.properties.includes(x));
74401
+ const extra = c.properties.filter((x) => !p.properties.includes(x));
74402
+ if (missing.length === 0 && extra.length === 0)
74403
+ continue;
74404
+ const comparableProps = new Set(p.changes.filter((ch) => ch.comparable).map((ch) => ch.prop));
74405
+ changed.push({
74406
+ prod: p,
74407
+ cand: c,
74408
+ missing,
74409
+ extra,
74410
+ notComparable: missing.filter((x) => !comparableProps.has(x)),
74411
+ onElement: missing.filter((x) => comparableProps.has(x))
74412
+ });
72286
74413
  }
72287
- return { lost, added: cand.filter((c) => !seen.has(c.target)), changed };
74414
+ return {
74415
+ lost,
74416
+ unpaired,
74417
+ added: cand.filter((c) => !used.has(c) && c.properties.length > 0),
74418
+ changed
74419
+ };
74420
+ }
74421
+ function statesVerdict(counts) {
74422
+ const exercised = counts.prodEffects > 0 || counts.candEffects > 0;
74423
+ return { exercised, inconclusive: !exercised && counts.motionMatched === 0 };
72288
74424
  }
72289
74425
  async function statesCommand(opts) {
72290
74426
  const viewport = parseViewport3(opts.viewport);
72291
74427
  if (!viewport) {
72292
- console.error(chalk28.red(`--viewport inválido: ${opts.viewport}`));
74428
+ console.error(chalk30.red(`--viewport inválido: ${opts.viewport}`));
72293
74429
  return 2;
72294
74430
  }
72295
74431
  const waitMs = Number.parseInt(opts.wait, 10) || 0;
72296
74432
  const maxStates = Math.max(1, Number.parseInt(opts.maxStates ?? "12", 10) || 12);
72297
- const candSelector = opts.candSelector?.trim() || opts.selector;
74433
+ const settleMs = Math.max(0, Number.parseInt(opts.hoverSettle ?? "250", 10) || 250);
74434
+ const prodSelector = opts.prodSelector?.trim() || opts.selector?.trim();
74435
+ const candSelector = opts.candSelector?.trim() || opts.selector?.trim();
74436
+ if (!prodSelector || !candSelector) {
74437
+ console.error(chalk30.red(" informe --selector (ambos os lados) ou --prod-selector e --cand-selector"));
74438
+ return 2;
74439
+ }
74440
+ const { aliases, note: aliasNote } = resolveAliases(opts.planDir);
74441
+ if (aliasNote)
74442
+ console.log(chalk30.dim(` ${aliasNote}`));
72298
74443
  const browser = await launchBrowser({ headless: true });
72299
74444
  try {
72300
74445
  const [prodSide, candSide] = await Promise.all([
72301
- gatherStates(browser, { url: opts.prod, selector: opts.selector, viewport, waitMs, maxStates }),
72302
- gatherStates(browser, { url: opts.cand, selector: candSelector, viewport, waitMs, maxStates })
74446
+ gatherStates(browser, {
74447
+ url: opts.prod,
74448
+ selector: prodSelector,
74449
+ viewport,
74450
+ waitMs,
74451
+ maxStates,
74452
+ settleMs
74453
+ }),
74454
+ gatherStates(browser, {
74455
+ url: opts.cand,
74456
+ selector: candSelector,
74457
+ viewport,
74458
+ waitMs,
74459
+ maxStates,
74460
+ settleMs
74461
+ })
72303
74462
  ]);
72304
74463
  if (prodSide.baseError || candSide.baseError) {
72305
74464
  const which = prodSide.baseError ? `prod: ${prodSide.baseError}` : `cand: ${candSide.baseError}`;
72306
- console.error(chalk28.red(` não foi possível ler o componente — ${which}`));
74465
+ console.error(chalk30.red(` não foi possível ler o componente — ${which}`));
72307
74466
  return 2;
72308
74467
  }
72309
74468
  const motion = prodSide.motion.found && candSide.motion.found ? diffMotion(prodSide.motion, candSide.motion, {
72310
- truncated: prodSide.truncated || candSide.truncated
74469
+ truncated: prodSide.truncated || candSide.truncated,
74470
+ aliases
72311
74471
  }) : null;
72312
74472
  const effects = diffEffects(prodSide.effects, candSide.effects);
74473
+ const { exercised, inconclusive } = statesVerdict({
74474
+ prodEffects: prodSide.effects.length,
74475
+ candEffects: candSide.effects.length,
74476
+ motionMatched: motion?.matched ?? 0
74477
+ });
72313
74478
  if (opts.json) {
72314
74479
  console.log(JSON.stringify({
72315
74480
  prod: opts.prod,
72316
74481
  cand: opts.cand,
72317
- selector: opts.selector,
74482
+ inconclusive,
74483
+ prodSelector,
72318
74484
  candSelector,
72319
74485
  viewport,
72320
74486
  motion,
@@ -72322,38 +74488,71 @@ async function statesCommand(opts) {
72322
74488
  effects,
72323
74489
  prodEffects: prodSide.effects,
72324
74490
  candEffects: candSide.effects,
72325
- truncated: prodSide.truncated || candSide.truncated
74491
+ truncated: prodSide.truncated || candSide.truncated,
74492
+ settle: { prod: prodSide.settle, cand: candSide.settle }
72326
74493
  }));
72327
- return effects.lost.length > 0 || (motion?.findings.length ?? 0) > 0 ? 1 : 0;
74494
+ return inconclusive || effects.lost.length > 0 || (motion?.findings.length ?? 0) > 0 ? 1 : 0;
74495
+ }
74496
+ for (const [name, data] of [
74497
+ ["prod", prodSide],
74498
+ ["cand", candSide]
74499
+ ]) {
74500
+ const caveat = data.settle && formatSettleCaveat(name, data.settle);
74501
+ if (caveat)
74502
+ console.log(chalk30.yellow(` ${caveat}`));
72328
74503
  }
72329
74504
  console.log("");
72330
- console.log(chalk28.bold(" Declared motion"));
74505
+ console.log(chalk30.bold(" Declared motion"));
72331
74506
  if (!motion) {
72332
74507
  const err = prodSide.motion.found ? candSide.motion : prodSide.motion;
72333
- console.log(chalk28.yellow(` não foi possível comparar — ${"error" in err ? err.error : "?"}`));
74508
+ console.log(chalk30.yellow(` não foi possível comparar — ${"error" in err ? err.error : "?"}`));
72334
74509
  } else {
72335
74510
  for (const line of formatMotionDiff(motion).split(`
72336
74511
  `))
72337
74512
  console.log(` ${line}`);
72338
74513
  }
72339
74514
  console.log("");
72340
- console.log(chalk28.bold(` Hover effects (${prodSide.effects.length} prod / ${candSide.effects.length} cand)`));
72341
- if (effects.lost.length === 0 && effects.changed.length === 0 && effects.added.length === 0) {
74515
+ console.log(chalk30.bold(` Hover effects (${prodSide.effects.length} prod / ${candSide.effects.length} cand)`));
74516
+ const nothing = effects.lost.length === 0 && effects.changed.length === 0 && effects.added.length === 0 && effects.unpaired.length === 0;
74517
+ if (nothing && !exercised) {
74518
+ console.log(chalk30.yellow(" INCONCLUSIVE — no hover changed anything on either side, so nothing was exercised. Check the selector holds an interactive element."));
74519
+ } else if (nothing) {
72342
74520
  console.log(" clean — every hover that changes something in prod changes the same in cand");
72343
74521
  }
72344
74522
  for (const e of effects.lost) {
72345
- console.log(chalk28.red(` LOST ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}] on hover; cand moves nothing`));
74523
+ console.log(chalk30.red(` LOST ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; cand's element was hovered and moved nothing`));
72346
74524
  }
72347
- for (const { prod, cand } of effects.changed) {
72348
- console.log(` DIFFERS ${prod.target} — prod [${prod.properties.join(", ")}] vs cand [${cand.properties.join(", ")}]`);
74525
+ for (const { prod, extra, notComparable, onElement } of effects.changed) {
74526
+ console.log(` DIFFERS ${prod.target}${prod.label ? ` (${prod.label})` : ""}`);
74527
+ if (onElement.length) {
74528
+ console.log(chalk30.yellow(` prod also moves [${onElement.join(", ")}] on the element itself`));
74529
+ }
74530
+ if (extra.length)
74531
+ console.log(` cand also moves [${extra.join(", ")}]`);
74532
+ if (notComparable.length) {
74533
+ console.log(chalk30.dim(` not comparable: [${notComparable.join(", ")}] — prod's hover renumbered ${prod.renumberedNodes} of the changed paths, so these were read on elements that are not the same ones before and after. Bench the component, or pick a selector whose subtree the hover does not restructure.`));
74534
+ }
74535
+ if (onElement.length === 0 && extra.length === 0) {
74536
+ console.log(chalk30.dim(" nothing comparable differs."));
74537
+ }
74538
+ }
74539
+ for (const e of effects.unpaired) {
74540
+ console.log(chalk30.dim(` UNPAIRED ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; no matching element found on the cand side (not a defect — the port may have changed the element, or it is outside --selector)`));
72349
74541
  }
72350
74542
  for (const e of effects.added) {
72351
- console.log(` ADDED ${e.target} — cand moves [${e.properties.join(", ")}]; prod does not`);
74543
+ console.log(` ADDED ${e.target} — cand moves [${e.properties.join(", ")}]; prod does not`);
74544
+ }
74545
+ if (effects.unpaired.length > 0 && effects.lost.length === 0 && effects.changed.length === 0) {
74546
+ console.log("");
74547
+ console.log(chalk30.yellow(` ${effects.unpaired.length} prod effect(s) had no counterpart and NOTHING paired. That is a pairing failure, not a set of defects — check --selector contains the same component on both sides, and that ported roots carry data-section.`));
74548
+ }
74549
+ if (prodSide.ambient > 0 || candSide.ambient > 0) {
74550
+ console.log(chalk30.dim(` ${prodSide.ambient} prod / ${candSide.ambient} cand node+property pair(s) were moving with no interaction (carousel, autoplaying video, anything on a timer) and were subtracted. A large count means --selector contains something animating on its own; narrow it.`));
72352
74551
  }
72353
74552
  if (prodSide.truncated || candSide.truncated) {
72354
- console.log(chalk28.dim(" TRUNCATED — element cap hit; absence of a finding is not proof"));
74553
+ console.log(chalk30.dim(" TRUNCATED — element cap hit; absence of a finding is not proof"));
72355
74554
  }
72356
- return effects.lost.length > 0 || (motion?.findings.length ?? 0) > 0 ? 1 : 0;
74555
+ return inconclusive || effects.lost.length > 0 || (motion?.findings.length ?? 0) > 0 ? 1 : 0;
72357
74556
  } finally {
72358
74557
  await browser.close().catch(() => {
72359
74558
  return;
@@ -72361,11 +74560,145 @@ async function statesCommand(opts) {
72361
74560
  }
72362
74561
  }
72363
74562
 
74563
+ // src/commands/variance.ts
74564
+ import chalk31 from "chalk";
74565
+
74566
+ // src/diff/variance.ts
74567
+ var uniq2 = (xs) => [...new Set(xs)];
74568
+ var host = (url) => {
74569
+ try {
74570
+ return new URL(url).host;
74571
+ } catch {
74572
+ return url;
74573
+ }
74574
+ };
74575
+ function computeVariance(runs) {
74576
+ const runIds = runs.map((r) => r.id);
74577
+ const base = {
74578
+ runIds,
74579
+ comparable: true,
74580
+ scores: runs.map((r) => r.verdict.score),
74581
+ scoreSpread: 0,
74582
+ unstable: [],
74583
+ inconsistentlyRun: []
74584
+ };
74585
+ if (runs.length < 2) {
74586
+ return {
74587
+ ...base,
74588
+ comparable: false,
74589
+ incomparableReason: "need at least two runs to measure variance"
74590
+ };
74591
+ }
74592
+ const pairs = uniq2(runs.map((r) => `${host(r.prodUrl)} × ${host(r.candUrl)}`));
74593
+ if (pairs.length > 1) {
74594
+ return {
74595
+ ...base,
74596
+ comparable: false,
74597
+ incomparableReason: `runs compare different host pairs (${pairs.join(", ")}) — that is not variance`
74598
+ };
74599
+ }
74600
+ const versions = uniq2(runs.map((r) => r.verdict.scoreVersion ?? 1));
74601
+ if (versions.length > 1) {
74602
+ return {
74603
+ ...base,
74604
+ comparable: false,
74605
+ incomparableReason: `runs used different score versions (${versions.join(", ")}) — scores are not on the same scale`
74606
+ };
74607
+ }
74608
+ const scores = runs.map((r) => r.verdict.score);
74609
+ const scoreSpread = Math.round((Math.max(...scores) - Math.min(...scores)) * 100) / 100;
74610
+ const perRun = runs.map((r) => new Map(r.checks.map((c) => [c.name, c])));
74611
+ const allNames = uniq2(runs.flatMap((r) => r.checks.map((c) => c.name))).sort();
74612
+ const unstable = [];
74613
+ const inconsistentlyRun = [];
74614
+ for (const name of allNames) {
74615
+ const seen = perRun.filter((m) => m.has(name));
74616
+ if (seen.length !== runs.length) {
74617
+ inconsistentlyRun.push(name);
74618
+ continue;
74619
+ }
74620
+ const statuses = uniq2(seen.map((m) => m.get(name)?.status ?? "?"));
74621
+ const issueCounts = seen.map((m) => m.get(name)?.issues.length ?? 0);
74622
+ const countsDiffer = uniq2(issueCounts).length > 1;
74623
+ if (statuses.length > 1 || countsDiffer) {
74624
+ unstable.push({
74625
+ name,
74626
+ statuses,
74627
+ runsSeen: seen.length,
74628
+ issueCounts,
74629
+ flipsStatus: statuses.length > 1
74630
+ });
74631
+ }
74632
+ }
74633
+ unstable.sort((a, b) => Number(b.flipsStatus) - Number(a.flipsStatus) || Math.max(...b.issueCounts) - Math.min(...b.issueCounts) - (Math.max(...a.issueCounts) - Math.min(...a.issueCounts)) || a.name.localeCompare(b.name));
74634
+ return { ...base, scores, scoreSpread, unstable, inconsistentlyRun };
74635
+ }
74636
+ function isStable(report, scoreBudget = 1) {
74637
+ return report.comparable && report.scoreSpread <= scoreBudget && report.unstable.every((u) => !u.flipsStatus);
74638
+ }
74639
+ function formatVariance(report, opts = {}) {
74640
+ const budget = opts.scoreBudget ?? 1;
74641
+ if (!report.comparable) {
74642
+ return `variance: cannot compare — ${report.incomparableReason}`;
74643
+ }
74644
+ const lines = [
74645
+ `runs ${report.runIds.join(", ")}`,
74646
+ `scores ${report.scores.join(", ")} (spread ${report.scoreSpread}, budget ${budget})`
74647
+ ];
74648
+ if (report.unstable.length === 0) {
74649
+ lines.push("checks every check reported identically across all runs");
74650
+ } else {
74651
+ lines.push("", "unstable checks (identical code, different result):");
74652
+ for (const u of report.unstable) {
74653
+ const what = u.flipsStatus ? `status flips ${u.statuses.join(" / ")}` : `issue count varies ${u.issueCounts.join(", ")}`;
74654
+ lines.push(` ${u.flipsStatus ? "FLIP" : "wobble"} ${u.name} — ${what}`);
74655
+ }
74656
+ }
74657
+ if (report.inconsistentlyRun.length > 0) {
74658
+ lines.push("", "ran in some runs and not others (module selection or a precondition, not noise):", ...report.inconsistentlyRun.map((n) => ` ${n}`));
74659
+ }
74660
+ lines.push("", isStable(report, budget) ? "STABLE — a score change on this pair can be attributed to the code" : "UNSTABLE — a score change on this pair cannot yet be attributed to the code");
74661
+ return lines.join(`
74662
+ `);
74663
+ }
74664
+
74665
+ // src/commands/variance.ts
74666
+ function varianceCommand(opts) {
74667
+ if (opts.runIds.length < 2) {
74668
+ console.error(chalk31.red(" informe pelo menos 2 runs: parity variance <runIdA> <runIdB> [...]"));
74669
+ return 2;
74670
+ }
74671
+ const budget = Number.parseFloat(opts.scoreBudget ?? "1");
74672
+ const runs = [];
74673
+ for (const id of opts.runIds) {
74674
+ try {
74675
+ runs.push(loadRun(opts.output, id));
74676
+ } catch (err) {
74677
+ console.error(chalk31.red(` ✖ ${err.message}`));
74678
+ return 2;
74679
+ }
74680
+ }
74681
+ const report = computeVariance(runs);
74682
+ if (opts.json) {
74683
+ console.log(JSON.stringify({ ...report, stable: isStable(report, budget), scoreBudget: budget }));
74684
+ } else {
74685
+ console.log("");
74686
+ console.log(chalk31.bold(" Score variance"));
74687
+ for (const line of formatVariance(report, { scoreBudget: budget }).split(`
74688
+ `)) {
74689
+ console.log(` ${line}`);
74690
+ }
74691
+ }
74692
+ if (!report.comparable)
74693
+ return 2;
74694
+ return isStable(report, budget) ? 0 : 1;
74695
+ }
74696
+
72364
74697
  // src/commands/vitals.ts
72365
- import { existsSync as existsSync29, readFileSync as readFileSync33, writeFileSync as writeFileSync31 } from "node:fs";
74698
+ import { existsSync as existsSync31, readFileSync as readFileSync36, writeFileSync as writeFileSync31 } from "node:fs";
72366
74699
  import { availableParallelism } from "node:os";
72367
- import { join as join39 } from "node:path";
72368
- import chalk29 from "chalk";
74700
+ import { join as join41 } from "node:path";
74701
+ import chalk32 from "chalk";
72369
74702
  import ora9 from "ora";
72370
74703
 
72371
74704
  // src/checks/agentic-nav.ts
@@ -72663,10 +74996,10 @@ async function vitalsCommand(opts) {
72663
74996
  const runId = newRunId();
72664
74997
  const paths = createRunDir(opts.output, runId);
72665
74998
  const t0 = Date.now();
72666
- console.log(chalk29.bold(`
74999
+ console.log(chalk32.bold(`
72667
75000
  parity vitals ${runId}`));
72668
- console.log(chalk29.dim(` prod: ${opts.prod}`));
72669
- console.log(chalk29.dim(` cand: ${opts.cand}`));
75001
+ console.log(chalk32.dim(` prod: ${opts.prod}`));
75002
+ console.log(chalk32.dim(` cand: ${opts.cand}`));
72670
75003
  const discoverSpinner = ora9("Descobrindo páginas…").start();
72671
75004
  const pagePaths = await discoverPagePaths2(opts.prod, opts);
72672
75005
  if (pagePaths.length === 0) {
@@ -72698,12 +75031,12 @@ async function vitalsCommand(opts) {
72698
75031
  completed++;
72699
75032
  const elapsed = ((Date.now() - t0) / 1000).toFixed(0);
72700
75033
  const etaSec = completed > 0 ? Math.round((Date.now() - t0) / completed * (total - completed) / 1000) : 0;
72701
- progress.text = `${completed}/${total} · ${elapsed}s · ETA ${etaSec}s · ${task.side === "prod" ? chalk29.cyan("prod") : chalk29.magenta("cand")} ${task.path} (${task.viewport})`;
75034
+ progress.text = `${completed}/${total} · ${elapsed}s · ETA ${etaSec}s · ${task.side === "prod" ? chalk32.cyan("prod") : chalk32.magenta("cand")} ${task.path} (${task.viewport})`;
72702
75035
  }
72703
75036
  });
72704
75037
  progress.succeed(`${total} capture(s) em ${((Date.now() - t0) / 1000).toFixed(1)}s`);
72705
75038
  if (opts.lighthouse !== false) {
72706
- const lhDir = join39(paths.runDir, "lighthouse");
75039
+ const lhDir = join41(paths.runDir, "lighthouse");
72707
75040
  const lhCap = opts.lighthouseConcurrency ?? Math.max(1, Math.min(2, Math.floor(availableParallelism() / 2)));
72708
75041
  const done = tasks.filter((t) => !!t.capture);
72709
75042
  const lhT0 = Date.now();
@@ -72727,7 +75060,7 @@ async function vitalsCommand(opts) {
72727
75060
  }
72728
75061
  lhCompleted++;
72729
75062
  const elapsed = ((Date.now() - lhT0) / 1000).toFixed(0);
72730
- lhProgress.text = `Lighthouse ${lhCompleted}/${done.length} · ${elapsed}s · ${task.side === "prod" ? chalk29.cyan("prod") : chalk29.magenta("cand")} ${task.path} (${task.viewport})`;
75063
+ lhProgress.text = `Lighthouse ${lhCompleted}/${done.length} · ${elapsed}s · ${task.side === "prod" ? chalk32.cyan("prod") : chalk32.magenta("cand")} ${task.path} (${task.viewport})`;
72731
75064
  });
72732
75065
  lhProgress.succeed(`Lighthouse ${done.length} página(s) em ${((Date.now() - lhT0) / 1000).toFixed(1)}s`);
72733
75066
  }
@@ -72792,7 +75125,7 @@ async function vitalsCommand(opts) {
72792
75125
  writeRunReportJson(paths.runDir, run);
72793
75126
  const html = renderHtmlReport(run, paths.runDir);
72794
75127
  writeRunReportHtml(paths.runDir, html);
72795
- writeFileSync31(join39(paths.runDir, "vitals.json"), `${JSON.stringify({
75128
+ writeFileSync31(join41(paths.runDir, "vitals.json"), `${JSON.stringify({
72796
75129
  schemaVersion: "0.1",
72797
75130
  prodUrl: opts.prod,
72798
75131
  candUrl: opts.cand,
@@ -72805,8 +75138,8 @@ async function vitalsCommand(opts) {
72805
75138
  `, "utf8");
72806
75139
  printSummary8(vitalsResult, cacheResult, scoresResult, oppsResult, agenticResult);
72807
75140
  console.log("");
72808
- console.log(chalk29.dim(` → ${paths.reportHtml}`));
72809
- console.log(chalk29.dim(` \uD83D\uDCA1 use 'parity serve ${runId}' pra preview iframe`));
75141
+ console.log(chalk32.dim(` → ${paths.reportHtml}`));
75142
+ console.log(chalk32.dim(` \uD83D\uDCA1 use 'parity serve ${runId}' pra preview iframe`));
72810
75143
  console.log("");
72811
75144
  if (opts.open) {
72812
75145
  const { default: open } = await import("open");
@@ -72896,15 +75229,15 @@ async function discoverPagePaths2(prodUrl, opts) {
72896
75229
  function parseUrlList(input) {
72897
75230
  if (input.startsWith("file:") || input.endsWith(".txt") || input.endsWith(".list")) {
72898
75231
  const path = input.replace(/^file:\/\//, "");
72899
- if (existsSync29(path)) {
72900
- return readFileSync33(path, "utf8").split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith("#")).map((s) => s.startsWith("/") ? s : `/${s}`);
75232
+ if (existsSync31(path)) {
75233
+ return readFileSync36(path, "utf8").split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith("#")).map((s) => s.startsWith("/") ? s : `/${s}`);
72901
75234
  }
72902
75235
  }
72903
75236
  return input.split(",").map((s) => s.trim()).filter(Boolean).map((s) => s.startsWith("/") || s.startsWith("http") ? s : `/${s}`);
72904
75237
  }
72905
75238
  function printSummary8(vitals, cache, scores, opportunities, agentic) {
72906
75239
  console.log("");
72907
- console.log(chalk29.bold(" Summary:"));
75240
+ console.log(chalk32.bold(" Summary:"));
72908
75241
  console.log(` ${vitals.summary}`);
72909
75242
  console.log(` ${cache.summary}`);
72910
75243
  if (scores.status !== "skipped")
@@ -72915,27 +75248,6 @@ function printSummary8(vitals, cache, scores, opportunities, agentic) {
72915
75248
  console.log(` ${agentic.summary}`);
72916
75249
  }
72917
75250
 
72918
- // src/util/version.ts
72919
- import { readFileSync as readFileSync34 } from "node:fs";
72920
- import { dirname as dirname6, resolve as resolve9 } from "node:path";
72921
- import { fileURLToPath } from "node:url";
72922
- function getPackageVersion() {
72923
- try {
72924
- const here = dirname6(fileURLToPath(import.meta.url));
72925
- for (const up of ["..", "../..", "../../.."]) {
72926
- try {
72927
- const pkgPath = resolve9(here, up, "package.json");
72928
- const raw = readFileSync34(pkgPath, "utf8");
72929
- const parsed = JSON.parse(raw);
72930
- if (parsed.name === "@decocms/parity" && typeof parsed.version === "string") {
72931
- return parsed.version;
72932
- }
72933
- } catch {}
72934
- }
72935
- } catch {}
72936
- return "0.0.0";
72937
- }
72938
-
72939
75251
  // src/cli.ts
72940
75252
  var program = new Command;
72941
75253
  function deprecatedNotice(oldCmd, newCmd) {
@@ -72988,8 +75300,14 @@ program.command("list").description("List saved runs").option("--output <dir>",
72988
75300
  }).addCommand(new Command("modules").description("List the 8 selectable check modules (M3 module selection) with their descriptions, checks, and flows — see --only/--skip on `parity run`.").option("--json", "Emit structured JSON instead of human-readable text", false).action((opts) => {
72989
75301
  process.exit(listModulesCommand(Boolean(opts.json)));
72990
75302
  }));
72991
- program.command("plan").description("Inspect/update the migration-plan.json component contract").addCommand(new Command("set-status").description("Mark a component's outcome as the orchestrator works. `as-is` = divergence accepted (prod is still the reference); `upgrade` = the target is deliberately ahead, so prod is NOT the reference — pair it with `plan set-reference`.").argument("<name>", "Component name (case- and separator-insensitive)").argument("<status>", "pending | partial | done | as-is | upgrade | skipped").option("--dir <path>", "Directory holding migration-plan.json (default: the target repo's .parity/)", ".parity").action((name, status, opts) => {
72992
- process.exit(planSetStatusCommand(opts.dir, name, status));
75303
+ program.command("plan").description("Inspect/update the migration-plan.json component contract").addCommand(new Command("set-status").description("Mark a component's outcome as the orchestrator works. `as-is` = divergence accepted (prod is still the reference); `upgrade` = the target is deliberately ahead, so prod is NOT the reference — pair it with `plan set-reference`.").argument("<name>", "Component name (case- and separator-insensitive)").argument("<status>", "pending | partial | done | as-is | upgrade | skipped").option("--create <scope>", "Create the row when the capture never found this component — `global` or `page`. A zero-height overlay header or a portal-rendered panel can be missed by detection, which leaves the plan unable to hold a decision about it. Recorded as origin `manual`, so it stays visible that somebody added it rather than the capture observing it.").option("--dir <path>", "Directory holding migration-plan.json (default: the target repo's .parity/)", ".parity").action((name, status, opts) => {
75304
+ if (opts.create && opts.create !== "global" && opts.create !== "page") {
75305
+ console.error("--create must be `global` or `page`");
75306
+ process.exit(2);
75307
+ }
75308
+ process.exit(planSetStatusCommand(opts.dir, name, status, {
75309
+ create: opts.create
75310
+ }));
72993
75311
  })).addCommand(new Command("set-page-status").description("Mark a page pending|code|done|skipped (code = route built, content missing)").argument("<path>", "Page path, e.g. / or /refrigeracion").argument("<status>", "pending | code | done | skipped").option("--dir <path>", "Directory holding migration-plan.json (default: the target repo's .parity/)", ".parity").action((path, status, opts) => {
72994
75312
  process.exit(planSetPageStatusCommand(opts.dir, path, status));
72995
75313
  })).addCommand(new Command("status").description("Migration inventory: components settled vs remaining, pages done vs awaiting CMS content").option("--dir <path>", "Directory holding migration-plan.json (default: the target repo's .parity/)", ".parity").option("--json", "Emit structured JSON instead of human-readable text", false).action((opts) => {
@@ -73010,7 +75328,7 @@ program.command("plan").description("Inspect/update the migration-plan.json comp
73010
75328
  page: opts.page,
73011
75329
  post: opts.post
73012
75330
  }));
73013
- })).addCommand(new Command("set-reference").description("Point a component's comparison at something other than prod (a site the better component came from), and record WHY it diverges. Without this, an intentional improvement is reported as a defect on every run.").argument("<name>", "Component name (case- and separator-insensitive)").requiredOption("--note <why>", "Why this component diverges — required, not decoration").option("--url <url>", "Reference site base URL (default: the plan's prod URL)").option("--selector <sel>", "Selector on the reference site, when it differs").option("--dir <path>", "Directory holding migration-plan.json (default: the target repo's .parity/)", ".parity").action((name, opts) => {
75331
+ })).addCommand(new Command("set-provenance").description("Record where a shipped component came from: `library` (reused from the shared target template) or `built` (written for this migration). A multi-store rollout is priced on store N costing less than store N-1, and reuse is the only mechanism that delivers that — unrecorded, 'the next one is cheaper' stays an assertion.").argument("<name>", "Component name (case- and separator-insensitive)").argument("<provenance>", "library | built").option("--dir <dir>", "Directory holding migration-plan.json (default: the target repo's .parity/)", ".parity").action((name, provenance, o) => process.exit(planSetProvenanceCommand(o.dir, name, provenance)))).addCommand(new Command("touch").description("Count one human intervention against a page — a person pointing at a defect the tooling did not surface. This is the metric that says whether the loop is converging: one real page took fourteen rounds of pasted screenshots. A counter, not a log; the magnitude is the signal.").argument("<page>", "Page path, e.g. /").option("--dir <dir>", "Directory holding migration-plan.json (default: the target repo's .parity/)", ".parity").option("--json", "Emit one-line JSON instead of pretty text", false).action((page, o) => process.exit(planTouchCommand(o.dir, page, { json: o.json })))).addCommand(new Command("set-reference").description("Point a component's comparison at something other than prod (a site the better component came from), and record WHY it diverges. Without this, an intentional improvement is reported as a defect on every run.").argument("<name>", "Component name (case- and separator-insensitive)").requiredOption("--note <why>", "Why this component diverges — required, not decoration").option("--url <url>", "Reference site base URL (default: the plan's prod URL)").option("--selector <sel>", "Selector on the reference site, when it differs").option("--dir <path>", "Directory holding migration-plan.json (default: the target repo's .parity/)", ".parity").action((name, opts) => {
73014
75332
  process.exit(planSetReferenceCommand(opts.dir, name, {
73015
75333
  url: opts.url,
73016
75334
  selector: opts.selector,
@@ -73211,8 +75529,9 @@ program.command("check").argument("<name>", "check name (kebab-case, e.g. consol
73211
75529
  json: opts.json
73212
75530
  }));
73213
75531
  });
73214
- program.command("section").description("Focused prod×cand comparison of one section: HTML diff + screenshot + computed-styles diff, plus an opt-in numeric box-tree diff (--box-tree). No flags = all 3 facets. Designed for the 'in DOM but invisible' debug loop (issue #31).").requiredOption("--prod <url>", "Production URL (base, e.g. https://www.example.com)").requiredOption("--cand <url>", "Candidate URL (base, e.g. https://example.deco-cx.workers.dev)").requiredOption("--selector <sel>", "CSS selector for the section to compare").option("--cand-selector <sel>", "CSS selector on the CANDIDATE side, when the ported component no longer matches --selector (VTEX IO class names → hashed CSS Modules, data-fs-* attributes, …). Defaults to --selector.").option("--output-html", "Include the HTML diff facet (default: on if no facet flag passed)", false).option("--screenshot", "Include the screenshot facet (locator screenshot per side)", false).option("--computed-styles", "Include the computed-styles diff facet", false).option("--heatmap", "Run pixelmatch on the two screenshots and analyze diff regions (bounding box + hotspots). Implies --screenshot.", false).option("--box-tree", "Walk the selector's whole subtree on both sides and report numeric box deltas, biggest first (`margin-top: 32px → 24px -8`). Deterministic, no LLM — this is the answer to 'everything is a little off', which a pixelmatch percentage and a vision paragraph cannot give.", false).option("--css-source", "For each divergent computed-style property, resolve which CSS rule (stylesheet + selector) produced it via CDP. Useful when the LLM needs to know which file to edit.", false).option("--prompt", "Emit an LLM-ready bundle: <prefix>-bundle.json (machine-readable) + <prefix>-prompt.md (opinionated Markdown with embedded images). Implies all signals.", false).option("--llm-summary", "After building the bundle, invoke Claude (needs ANTHROPIC_API_KEY) and print a 1-paragraph 'what I understood' summary. Does NOT generate a patch. Implies --prompt.", false).option("--all", "Turn on every diagnostic facet at once (html + screenshot + computed-styles + heatmap + css-source + prompt + llm-summary) — the pixel-perfect debug shortcut formerly known as `parity fix`. Issue #415.", false).option("--no-llm", "With --all, skip the LLM call (still writes the markdown bundle). Use when offline or to avoid API costs.").option("--viewport <viewport>", "mobile | desktop | tablet", "mobile").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").option("--out-dir <dir>", "Where to write the screenshots", "./parity-output/sections").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
75532
+ program.command("section").description("Focused prod×cand comparison of one section: HTML diff + screenshot + computed-styles diff, plus an opt-in numeric box-tree diff (--box-tree). No flags = all 3 facets. Designed for the 'in DOM but invisible' debug loop (issue #31).").requiredOption("--prod <url>", "Production URL (base, e.g. https://www.example.com)").requiredOption("--cand <url>", "Candidate URL (base, e.g. https://example.deco-cx.workers.dev)").requiredOption("--selector <sel>", "CSS selector for the section to compare").option("--cand-selector <sel>", "CSS selector on the CANDIDATE side, when the ported component no longer matches --selector (VTEX IO class names → hashed CSS Modules, data-fs-* attributes, …). Defaults to --selector.").option("--output-html", "Include the HTML diff facet (default: on if no facet flag passed)", false).option("--screenshot", "Include the screenshot facet (locator screenshot per side)", false).option("--computed-styles", "Include the computed-styles diff facet", false).option("--heatmap", "Run pixelmatch on the two screenshots and analyze diff regions (bounding box + hotspots). Implies --screenshot.", false).option("--box-tree", "Walk the selector's whole subtree on both sides and report numeric box deltas, biggest first (`margin-top: 32px → 24px -8`). Deterministic, no LLM — this is the answer to 'everything is a little off', which a pixelmatch percentage and a vision paragraph cannot give.", false).option("--css-source", "For each divergent computed-style property, resolve which CSS rule (stylesheet + selector) produced it via CDP. Useful when the LLM needs to know which file to edit.", false).option("--prompt", "Emit an LLM-ready bundle: <prefix>-bundle.json (machine-readable) + <prefix>-prompt.md (opinionated Markdown with embedded images). Implies all signals.", false).option("--llm-summary", "After building the bundle, invoke Claude (needs ANTHROPIC_API_KEY) and print a 1-paragraph 'what I understood' summary. Does NOT generate a patch. Implies --prompt.", false).option("--all", "Turn on every diagnostic facet at once (html + screenshot + computed-styles + heatmap + css-source + prompt + llm-summary) — the pixel-perfect debug shortcut formerly known as `parity fix`. Issue #415.", false).option("--no-llm", "With --all, skip the LLM call (still writes the markdown bundle). Use when offline or to avoid API costs.").option("--viewport <viewport>", "mobile | desktop | tablet", "mobile").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").option("--out-dir <dir>", "Where to write the screenshots", "./parity-output/sections").option("--plan-dir <dir>", "Run dir holding migration-plan.json. Its component rows are the only place the prod-side spelling of a component (`site/sections/Hero/HeroBannerV2.tsx`) and the cand-side one (`HeroSlideshow`) are written down together, so reading it lets the label pass pair nodes whose markup does not agree. Without it, unlabelled nodes fall back to the structural path.").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
73215
75533
  process.exit(await sectionCommand({
75534
+ planDir: opts.planDir,
73216
75535
  prod: opts.prod,
73217
75536
  cand: opts.cand,
73218
75537
  selector: opts.selector,
@@ -73231,7 +75550,47 @@ program.command("section").description("Focused prod×cand comparison of one sec
73231
75550
  json: opts.json
73232
75551
  }));
73233
75552
  });
73234
- program.command("bench").description("Compare ONE component in ISOLATION. Both sides mount it at a harness route (/__parity/bench?component=X&props=<base64>) with the same props, so the page stops being a confounder: no lazy-load timing, no carousel position, no cookie banner, no A/B flag. Seconds per run instead of a full-page capture, so many components can converge concurrently. Pass --prod-selector to compare against a live page instead of a second harness.").requiredOption("--component <name>", "Component name the harness route resolves").requiredOption("--cand <url>", "Candidate harness base URL (e.g. http://localhost:3000)").requiredOption("--prod <url>", "Reference: a second harness base (the source repo's dev server), or a live page when --prod-selector is given").option("--props <file>", "JSON file of props to mount with. Prefer the real values from the source CMS over invented ones — a component fed placeholder content converges on placeholder layout.").option("--selector <sel>", "Component root inside the harness", "[data-parity-bench]").option("--prod-selector <sel>", "Treat --prod as a live PAGE and find the component at this selector. Use before a source dev server exists.").option("--cand-selector <sel>", "Same, for the candidate side").option("--viewport <viewport>", "mobile | desktop | tablet", "desktop").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "1000").option("--out-dir <dir>", "Where to write screenshots + the result JSON", "./parity-output/bench").option("--fail-on-diff", "Exit 1 when geometry or motion is not clean (for a convergence loop)", false).option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
75553
+ program.command("cockpit").description("Serve the migration on a local page: the per-page board, a page worksheet, the box-tree and motion deltas from `parity bench`, and the latest run's verdict. Reads artifacts already on disk — nothing new is computed, and the lane rules stay in the plan so the page cannot disagree with the CLI. Local, single-user, read-only.").option("--dir <dir>", "Directory holding migration-plan.json + migration.json (default: the target repo's .parity/)", ".parity").option("--output <dir>", "Directory holding runs/", "./parity-output").option("--bench-dir <dir>", "Directory holding bench-*.json", "./parity-output/bench").option("--prod <url>", "Production URL, to show the side-by-side panes").option("--cand <url>", "Candidate URL, to show the side-by-side panes").option("--port <port>", "Port to bind (default: an open one)").option("--host <host>", "Interface to bind. Defaults to loopback: the server is unauthenticated, reads the repo, and proxies arbitrary URLs with frame protections stripped.", "127.0.0.1").option("--no-open", "Do not open a browser").action(async (opts) => {
75554
+ process.exit(await cockpitCommand({
75555
+ dir: opts.dir,
75556
+ output: opts.output,
75557
+ benchDir: opts.benchDir,
75558
+ prodUrl: opts.prod,
75559
+ candUrl: opts.cand,
75560
+ port: opts.port,
75561
+ host: opts.host,
75562
+ open: opts.open
75563
+ }));
75564
+ });
75565
+ program.command("mcp").description("Expose the migration over MCP on stdio: state, plan status, the per-page board, a page worksheet, saved run verdicts, and (with --allow-writes) the status/provenance/touch verbs. Thin wrappers over what the CLI already computes — no second brain. This is a server, not a UI: rendering a board is a job for whatever host consumes MCP, and keeping the lane rules here is what stops a second implementation of them drifting somewhere else.").option("--dir <dir>", "Directory holding migration-plan.json + migration.json (default: the target repo's .parity/)", ".parity").option("--output <dir>", "Directory holding runs/", "./parity-output").option("--cand-url <url>", "Candidate base URL, so worksheets and boards can build runnable commands").option("--allow-writes", "Let the mutating tools run. Off by default: an MCP client can call anything the server lists, and the plan is committed state.", false).action(async (opts) => {
75566
+ process.exit(await mcpCommand({
75567
+ dir: opts.dir,
75568
+ output: opts.output,
75569
+ candUrl: opts.candUrl,
75570
+ allowWrites: opts.allowWrites
75571
+ }));
75572
+ });
75573
+ program.command("variance").description("Measure whether a score change is attributable to the code. Run `parity run` twice against UNCHANGED code, then pass both run ids: this reports the score spread and, more usefully, WHICH checks reported differently. A check whose status flips between two runs of the same code is not measuring the code, and every score it contributes to is unfalsifiable until it is named. Exits 1 when unstable, 2 when the runs are not comparable.").argument("<runIds...>", "Two or more saved run ids of the same host pair").option("--score-budget <points>", "Score spread tolerated before calling it unstable", "1").option("--output <dir>", "Output directory holding the runs", "./parity-output").option("--json", "Emit one-line JSON instead of pretty text", false).action((runIds, opts) => {
75574
+ process.exit(varianceCommand({
75575
+ runIds,
75576
+ output: opts.output,
75577
+ scoreBudget: opts.scoreBudget,
75578
+ json: opts.json
75579
+ }));
75580
+ });
75581
+ program.command("locate").description("Where is this element on each side? Give it a label — a data-section value or the text the element starts with — and it reports the node it matched on each side, its box and its type, at one or more viewports. It REFUSES when either side has more than one candidate instead of taking the first, which is the mistake every hand-written version of this makes. Exits 1 when any label could not be located on both sides.").requiredOption("--prod <url>", "Reference URL").requiredOption("--cand <url>", "Candidate URL").option("--label <text...>", "A data-section/data-testid value, or the text the element starts with. Repeatable.").option("--selector <sel>", "Root to search inside", "body").option("--viewports <list>", "Comma-separated: mobile, tablet, desktop. A type defect is often one breakpoint, so measuring three is how you tell a responsive rule from a broken one.", "mobile,desktop").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").option("--plan-dir <dir>", "Run dir holding migration-plan.json, so a source-side spelling of a component resolves to the cand-side name.").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
75582
+ process.exit(await locateCommand({
75583
+ prod: opts.prod,
75584
+ cand: opts.cand,
75585
+ labels: opts.label ?? [],
75586
+ selector: opts.selector,
75587
+ viewports: opts.viewports,
75588
+ wait: opts.wait,
75589
+ planDir: opts.planDir,
75590
+ json: opts.json
75591
+ }));
75592
+ });
75593
+ program.command("bench").description("Compare ONE component in ISOLATION. Both sides mount it at a harness route (/__parity/bench?component=X&props=<base64>) with the same props, so the page stops being a confounder: no lazy-load timing, no carousel position, no cookie banner, no A/B flag. Seconds per run instead of a full-page capture, so many components can converge concurrently. Pass --prod-selector to compare against a live page instead of a second harness.").requiredOption("--component <name>", "Component name the harness route resolves").requiredOption("--cand <url>", "Candidate harness base URL (e.g. http://localhost:3000)").requiredOption("--prod <url>", "Reference: a second harness base (the source repo's dev server), or a live page when --prod-selector is given").option("--props <file>", "JSON file of props to mount with. Prefer the real values from the source CMS over invented ones — a component fed placeholder content converges on placeholder layout.").option("--selector <sel>", "Component root inside the harness", "[data-parity-bench]").option("--prod-selector <sel>", "Treat --prod as a live PAGE and find the component at this selector. Use before a source dev server exists.").option("--cand-selector <sel>", "Same, for the candidate side").option("--viewport <viewport>", "mobile | desktop | tablet", "desktop").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "1000").option("--out-dir <dir>", "Where to write screenshots + the result JSON", "./parity-output/bench").option("--fail-on-diff", "Exit 1 when geometry or motion is not clean (for a convergence loop)", false).option("--plan-dir <dir>", "Run dir holding migration-plan.json — its component rows carry both sides' spellings of a component, so the label pass can pair nodes whose markup does not agree.").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
73235
75594
  process.exit(await benchCommand({
73236
75595
  component: opts.component,
73237
75596
  prod: opts.prod,
@@ -73244,16 +75603,20 @@ program.command("bench").description("Compare ONE component in ISOLATION. Both s
73244
75603
  wait: opts.wait,
73245
75604
  outDir: opts.outDir,
73246
75605
  failOnDiff: opts.failOnDiff,
75606
+ planDir: opts.planDir,
73247
75607
  json: opts.json
73248
75608
  }));
73249
75609
  });
73250
- program.command("states").description("Compare a component's INTERACTIVE states, not just its resting frame. Two deterministic signals: declared motion (transitions, animations and the @keyframes bodies they point at, per interactive element) and hover effects (hover each element in turn, re-read the box tree, and report which effects prod has that cand lost). This is the instrument behind 'the hover effects are not the same' — no LLM, no screenshots to eyeball.").requiredOption("--prod <url>", "Production URL (source of truth)").requiredOption("--cand <url>", "Candidate URL (migrated)").requiredOption("--selector <sel>", "CSS selector for the component to compare").option("--cand-selector <sel>", "CSS selector on the CANDIDATE side, when the ported component no longer matches --selector. Defaults to --selector.").option("--max-states <n>", "How many interactive elements to hover per side. A mega-nav has hundreds of links sharing one hover rule; N distinct effects is the signal.", "12").option("--viewport <viewport>", "mobile | desktop | tablet", "desktop").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) => {
75610
+ program.command("states").description("Compare a component's INTERACTIVE states, not just its resting frame. Two deterministic signals: declared motion (transitions, animations and the @keyframes bodies they point at, per interactive element) and hover effects (hover each element in turn, re-read the box tree, and report which effects prod has that cand lost). This is the instrument behind 'the hover effects are not the same' — no LLM, no screenshots to eyeball.").requiredOption("--prod <url>", "Production URL (source of truth)").requiredOption("--cand <url>", "Candidate URL (migrated)").option("--selector <sel>", "CSS selector for the component, on both sides. Shorthand for passing --prod-selector and --cand-selector the same value.").option("--prod-selector <sel>", "CSS selector on the PRODUCTION side. On a legacy-to-modern migration the two sides frequently share no selector at all — a prod PDP with no <main>, a header nine levels deeper than the port's — and widening to `body` to find one string that resolves on both is the worst place to run this. Give each side its own.").option("--cand-selector <sel>", "CSS selector on the CANDIDATE side. Defaults to --selector.").option("--max-states <n>", "How many interactive elements to hover per side. A mega-nav has hundreds of links sharing one hover rule; N distinct effects is the signal.", "12").option("--hover-settle <ms>", "Wait after hovering before re-reading. A pure CSS transition needs none — its end state is already in the computed style on the first frame — but anything gated on a JS timer (hover intent, a debounce) needs the whole timer, and 'moves nothing' measured too early reads exactly like a broken hover. When the first read finds nothing, a second is taken at 4x this before concluding, so a site without hover-intent never pays for one.", "250").option("--viewport <viewport>", "mobile | desktop | tablet", "desktop").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").option("--plan-dir <dir>", "Run dir holding migration-plan.json. Its component rows are the only place the prod-side spelling of a component (`site/sections/Hero/HeroBannerV2.tsx`) and the cand-side one (`HeroSlideshow`) are written down together, so reading it lets the label pass pair nodes whose markup does not agree. Without it, unlabelled nodes fall back to the structural path.").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
73251
75611
  process.exit(await statesCommand({
75612
+ planDir: opts.planDir,
73252
75613
  prod: opts.prod,
73253
75614
  cand: opts.cand,
73254
75615
  selector: opts.selector,
75616
+ prodSelector: opts.prodSelector,
73255
75617
  candSelector: opts.candSelector,
73256
75618
  maxStates: opts.maxStates,
75619
+ hoverSettle: opts.hoverSettle,
73257
75620
  viewport: opts.viewport,
73258
75621
  wait: opts.wait,
73259
75622
  json: opts.json