@decocms/parity 0.33.44 → 0.33.46

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 +2514 -223
  2. package/package.json +3 -2
package/dist/cli.js CHANGED
@@ -63906,6 +63906,10 @@ function mergePlanDecisions(fresh, previous) {
63906
63906
  row.verified = prev.verified;
63907
63907
  if (prev.provenance)
63908
63908
  row.provenance = prev.provenance;
63909
+ if (prev.selectorPinned && prev.selector) {
63910
+ row.selector = prev.selector;
63911
+ row.selectorPinned = true;
63912
+ }
63909
63913
  if (prev.status !== "pending" || prev.reference || prev.verified)
63910
63914
  carried.push(row.name);
63911
63915
  }
@@ -64107,7 +64111,7 @@ function disposition(c) {
64107
64111
  if (c.verified && c.verified.verdict !== "inconclusive")
64108
64112
  return "settled";
64109
64113
  if (c.status === "upgrade")
64110
- return c.reference ? "validate" : "upgrade";
64114
+ return c.reference?.url ? "validate" : "upgrade";
64111
64115
  return "validate";
64112
64116
  }
64113
64117
  function pagePlan(plan, path, candUrl) {
@@ -64131,8 +64135,8 @@ function pagePlan(plan, path, candUrl) {
64131
64135
  const d = disposition(c);
64132
64136
  counts[d] += 1;
64133
64137
  const selector = c.reference?.selector ?? c.selector ?? null;
64134
- const refUrl = c.reference?.url ?? plan.url;
64135
- const kind = c.reference ? "reference" : "prod";
64138
+ const refUrl = c.reference?.url || plan.url;
64139
+ const kind = c.reference?.url ? "reference" : "prod";
64136
64140
  const checkable = d === "validate" && Boolean(selector) && Boolean(candUrl);
64137
64141
  tasks.push({
64138
64142
  name: c.name,
@@ -64210,7 +64214,7 @@ function setComponentVerified(plan, name, verdict, at, note) {
64210
64214
  const component = plan.components.find((c) => key(c.name) === k);
64211
64215
  if (!component)
64212
64216
  return null;
64213
- const against = component.reference ? "reference" : "prod";
64217
+ const against = component.reference?.url ? "reference" : "prod";
64214
64218
  component.verified = { at, verdict, against, ...note ? { note } : {} };
64215
64219
  return component;
64216
64220
  }
@@ -64891,6 +64895,7 @@ async function sectionCommand(opts) {
64891
64895
  gatherSide(browser, {
64892
64896
  url: opts.prod,
64893
64897
  viewport,
64898
+ viewportSize: opts.viewportSize,
64894
64899
  waitMs,
64895
64900
  selector: opts.selector,
64896
64901
  wantScreenshot: want.screenshot,
@@ -64903,6 +64908,7 @@ async function sectionCommand(opts) {
64903
64908
  gatherSide(browser, {
64904
64909
  url: opts.cand,
64905
64910
  viewport,
64911
+ viewportSize: opts.viewportSize,
64906
64912
  waitMs,
64907
64913
  selector: candSelector,
64908
64914
  wantScreenshot: want.screenshot,
@@ -65000,7 +65006,10 @@ function printBoxTree(result) {
65000
65006
  }
65001
65007
  }
65002
65008
  async function gatherSide(browser, opts) {
65003
- const ctx = await newContext(browser, { viewport: opts.viewport });
65009
+ const ctx = await newContext(browser, {
65010
+ viewport: opts.viewport,
65011
+ ...opts.viewportSize ? { viewportSize: opts.viewportSize } : {}
65012
+ });
65004
65013
  const page = await ctx.newPage();
65005
65014
  const result = {
65006
65015
  html: null,
@@ -70113,6 +70122,7 @@ var STRIPPED_REQUEST_HEADERS = new Set([
70113
70122
  "referer",
70114
70123
  "origin"
70115
70124
  ]);
70125
+ var scrollBeacons = [];
70116
70126
  async function startProxyServer(runDir, opts = {}) {
70117
70127
  const absRunDir = resolve7(runDir);
70118
70128
  if (!existsSync22(absRunDir)) {
@@ -70158,7 +70168,20 @@ async function handleRequest(req, res, runDir) {
70158
70168
  }
70159
70169
  const viewport = reqUrl.searchParams.get("viewport");
70160
70170
  const forceMobile = viewport === "mobile";
70161
- return proxyRequest(req, res, target, { forceMobile });
70171
+ return proxyRequest(req, res, target, {
70172
+ forceMobile,
70173
+ scrollTo: reqUrl.searchParams.get("scrollTo") ?? undefined
70174
+ });
70175
+ }
70176
+ if (path === "/__parity/scrolled") {
70177
+ scrollBeacons.push({
70178
+ ok: reqUrl.searchParams.get("ok") === "1",
70179
+ selector: reqUrl.searchParams.get("sel") ?? "",
70180
+ rect: reqUrl.searchParams.get("rect")
70181
+ });
70182
+ res.statusCode = 204;
70183
+ res.end();
70184
+ return;
70162
70185
  }
70163
70186
  if (path === "/__parity/health") {
70164
70187
  res.statusCode = 200;
@@ -70241,11 +70264,21 @@ async function proxyRequest(req, res, targetUrl, opts = {}) {
70241
70264
  headers["user-agent"] = headers["user-agent"] ?? "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36";
70242
70265
  }
70243
70266
  headers.host = target.host;
70267
+ const method = req.method ?? "GET";
70268
+ let reqBody;
70269
+ if (method !== "GET" && method !== "HEAD") {
70270
+ const chunks = [];
70271
+ for await (const c of req)
70272
+ chunks.push(c);
70273
+ const buf = Buffer.concat(chunks);
70274
+ reqBody = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
70275
+ }
70244
70276
  let upstream;
70245
70277
  try {
70246
70278
  upstream = await fetch(target.toString(), {
70247
- method: req.method ?? "GET",
70279
+ method,
70248
70280
  headers,
70281
+ body: reqBody,
70249
70282
  redirect: "follow"
70250
70283
  });
70251
70284
  } catch (err) {
@@ -70269,7 +70302,7 @@ async function proxyRequest(req, res, targetUrl, opts = {}) {
70269
70302
  const contentType = upstream.headers.get("content-type") ?? "";
70270
70303
  if (contentType.includes("text/html")) {
70271
70304
  const buf = await upstream.text();
70272
- const baseTag = `<base href="${escapeAttr(target.toString())}">`;
70305
+ const baseTag = `<base href="${escapeAttr(target.toString())}">${originShim(target)}${opts.scrollTo ? scrollToShim(opts.scrollTo) : ""}`;
70273
70306
  let html = buf;
70274
70307
  if (opts.forceMobile) {
70275
70308
  const viewportMeta = `<meta name="viewport" content="width=375, initial-scale=1">`;
@@ -70297,6 +70330,21 @@ async function proxyRequest(req, res, targetUrl, opts = {}) {
70297
70330
  } catch {}
70298
70331
  res.end();
70299
70332
  }
70333
+ function originShim(target) {
70334
+ const o = JSON.stringify(target.origin);
70335
+ const here = JSON.stringify(target.pathname + target.search + target.hash);
70336
+ return `<script>(function(){var O=${o},L=location.origin,V=new URLSearchParams(location.search).get("viewport");
70337
+ try{history.replaceState(history.state,"",L+${here})}catch(e){}function x(u){try{return new URL(u,document.baseURI).origin!==L}catch(e){return false}}
70338
+ ["pushState","replaceState"].forEach(function(k){var f=history[k];history[k]=function(s,t,u){return u!=null&&x(u)?f.call(this,s,t):f.apply(this,arguments)}});
70339
+ function r(u){try{if(/^(data|blob):/.test(u))return u;var p=new URL(u,document.baseURI);if(p.origin===L&&p.pathname!=="/proxy")p=new URL(p.pathname+p.search,O);return p.origin===O?L+"/proxy?url="+encodeURIComponent(p.href):u}catch(e){return u}}
70340
+ var F=window.fetch;if(F)window.fetch=function(i,n){return F.call(this,typeof i==="string"||i instanceof URL?r(String(i)):i,n)};
70341
+ var X=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(m,u){arguments[1]=r(String(u));return X.apply(this,arguments)};
70342
+ document.addEventListener("click",function(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey)return;var a=e.target&&e.target.closest&&e.target.closest("a[href]");if(!a||a.target==="_blank")return;var h=a.href;if(!/^https?:/.test(h)||h.split("#")[0]===document.baseURI.split("#")[0])return;e.preventDefault();location.href="/proxy?url="+encodeURIComponent(h)+(V?"&viewport="+V:"")})})()</script>`;
70343
+ }
70344
+ function scrollToShim(selector) {
70345
+ const sel = JSON.stringify(selector).replace(/</g, "\\u003c");
70346
+ return `<script>addEventListener("load",function(){var S=${sel},t0=Date.now(),y=0;function f(){var e=null;try{e=document.querySelector(S)}catch(x){return}function b(ok,r){try{navigator.sendBeacon(location.origin+"/__parity/scrolled?ok="+ok+"&sel="+encodeURIComponent(S)+(r?"&rect="+[r.left,r.top,r.width,r.height,devicePixelRatio].map(Math.round).join(","):""))}catch(x){}}if(e){var r=e.getBoundingClientRect();scrollTo(0,scrollY+r.top-Math.max(0,(innerHeight-r.height)/2));e.style.outline="3px solid #A595FF";e.style.outlineOffset="-2px";setTimeout(function(){b(1,e.getBoundingClientRect())},300);return}if(Date.now()-t0>15000){scrollTo(0,0);b(0);return}y+=innerHeight*0.8;scrollTo(0,y);setTimeout(f,250)}setTimeout(f,500)})</script>`;
70347
+ }
70300
70348
  function escapeAttr(s) {
70301
70349
  return s.replace(/"/g, "&quot;").replace(/&/g, "&amp;");
70302
70350
  }
@@ -72363,11 +72411,51 @@ async function reportCommand(runId, opts) {
72363
72411
  return 0;
72364
72412
  }
72365
72413
 
72366
- // src/commands/bench.ts
72367
- import { existsSync as existsSync28, mkdirSync as mkdirSync18, readFileSync as readFileSync32, writeFileSync as writeFileSync30 } from "node:fs";
72414
+ // src/commands/event.ts
72368
72415
  import { resolve as resolve8 } from "node:path";
72369
72416
  import chalk27 from "chalk";
72370
72417
 
72418
+ // src/events.ts
72419
+ import { appendFileSync, mkdirSync as mkdirSync18 } from "node:fs";
72420
+ import { dirname as dirname6, join as join39 } from "node:path";
72421
+ function emitEvent(dir, type, data = {}) {
72422
+ try {
72423
+ const file = join39(dir, "events.jsonl");
72424
+ mkdirSync18(dirname6(file), { recursive: true });
72425
+ const event = { ts: new Date().toISOString(), type, ...data };
72426
+ appendFileSync(file, `${JSON.stringify(event)}
72427
+ `);
72428
+ } catch {}
72429
+ }
72430
+
72431
+ // src/commands/event.ts
72432
+ function eventCommand(type, opts) {
72433
+ let data = {};
72434
+ if (opts.data) {
72435
+ try {
72436
+ const parsed = JSON.parse(opts.data);
72437
+ if (parsed && typeof parsed === "object")
72438
+ data = parsed;
72439
+ else {
72440
+ console.error(chalk27.red("--data must be a JSON object"));
72441
+ return 1;
72442
+ }
72443
+ } catch {
72444
+ console.error(chalk27.red(`--data is not valid JSON: ${opts.data}`));
72445
+ return 1;
72446
+ }
72447
+ }
72448
+ const dir = resolve8(opts.dir);
72449
+ emitEvent(dir, type, data);
72450
+ console.log(`${chalk27.green("✓")} ${type} → ${dir}/events.jsonl`);
72451
+ return 0;
72452
+ }
72453
+
72454
+ // src/commands/bench.ts
72455
+ import { existsSync as existsSync28, mkdirSync as mkdirSync19, readFileSync as readFileSync32, writeFileSync as writeFileSync30 } from "node:fs";
72456
+ import { resolve as resolve9 } from "node:path";
72457
+ import chalk28 from "chalk";
72458
+
72371
72459
  // src/diff/motion.ts
72372
72460
  var WEIGHT = {
72373
72461
  "moved-to-descendant": 45,
@@ -72794,20 +72882,20 @@ async function gatherBenchSide(browser, opts) {
72794
72882
  async function benchCommand(opts) {
72795
72883
  const viewport = parseViewport3(opts.viewport);
72796
72884
  if (!viewport) {
72797
- console.error(chalk27.red(`--viewport inválido: ${opts.viewport}`));
72885
+ console.error(chalk28.red(`--viewport inválido: ${opts.viewport}`));
72798
72886
  return 2;
72799
72887
  }
72800
72888
  const waitMs = Number.parseInt(opts.wait, 10) || 0;
72801
72889
  let props;
72802
72890
  if (opts.props) {
72803
72891
  if (!existsSync28(opts.props)) {
72804
- console.error(chalk27.red(`--props não encontrado: ${opts.props}`));
72892
+ console.error(chalk28.red(`--props não encontrado: ${opts.props}`));
72805
72893
  return 2;
72806
72894
  }
72807
72895
  try {
72808
72896
  props = JSON.parse(readFileSync32(opts.props, "utf8"));
72809
72897
  } catch (err) {
72810
- console.error(chalk27.red(`--props não é JSON válido: ${err.message}`));
72898
+ console.error(chalk28.red(`--props não é JSON válido: ${err.message}`));
72811
72899
  return 2;
72812
72900
  }
72813
72901
  }
@@ -72817,12 +72905,12 @@ async function benchCommand(opts) {
72817
72905
  const candUrl = candIsHarness ? benchUrl(opts.cand, opts.component, props) : opts.cand;
72818
72906
  const prodSelector = opts.prodSelector ?? opts.selector ?? BENCH_SELECTOR;
72819
72907
  const candSelector = opts.candSelector ?? opts.selector ?? BENCH_SELECTOR;
72820
- mkdirSync18(opts.outDir, { recursive: true });
72908
+ mkdirSync19(opts.outDir, { recursive: true });
72821
72909
  const slug = opts.component.replace(/[^a-zA-Z0-9]+/g, "-").toLowerCase();
72822
72910
  const prefix = `bench-${slug}-${viewport}`;
72823
72911
  const { aliases, note: aliasNote } = resolveAliases(opts.planDir);
72824
72912
  if (aliasNote)
72825
- console.log(chalk27.dim(` ${aliasNote}`));
72913
+ console.log(chalk28.dim(` ${aliasNote}`));
72826
72914
  const browser = await launchBrowser({ headless: true });
72827
72915
  try {
72828
72916
  const [prodSide, candSide] = await Promise.all([
@@ -72831,14 +72919,14 @@ async function benchCommand(opts) {
72831
72919
  selector: prodSelector,
72832
72920
  viewport,
72833
72921
  waitMs,
72834
- screenshotPath: resolve8(opts.outDir, `${prefix}-prod.png`)
72922
+ screenshotPath: resolve9(opts.outDir, `${prefix}-prod.png`)
72835
72923
  }),
72836
72924
  gatherBenchSide(browser, {
72837
72925
  url: candUrl,
72838
72926
  selector: candSelector,
72839
72927
  viewport,
72840
72928
  waitMs,
72841
- screenshotPath: resolve8(opts.outDir, `${prefix}-cand.png`)
72929
+ screenshotPath: resolve9(opts.outDir, `${prefix}-cand.png`)
72842
72930
  })
72843
72931
  ]);
72844
72932
  const readErr = prodSide.error ?? candSide.error ?? (!prodSide.boxNodes.found ? `prod: ${prodSide.boxNodes.error}` : undefined) ?? (!candSide.boxNodes.found ? `cand: ${candSide.boxNodes.error}` : undefined);
@@ -72847,7 +72935,7 @@ async function benchCommand(opts) {
72847
72935
  if (opts.json)
72848
72936
  console.log(JSON.stringify(payload));
72849
72937
  else
72850
- console.error(chalk27.red(` bench falhou — ${readErr}`));
72938
+ console.error(chalk28.red(` bench falhou — ${readErr}`));
72851
72939
  return 2;
72852
72940
  }
72853
72941
  const geometry = diffBoxTrees(prodSide.boxNodes.nodes, candSide.boxNodes.nodes, {
@@ -72870,16 +72958,16 @@ async function benchCommand(opts) {
72870
72958
  screenshots: { prod: prodSide.screenshotPath ?? null, cand: candSide.screenshotPath ?? null },
72871
72959
  settle: { prod: prodSide.settle ?? null, cand: candSide.settle ?? null }
72872
72960
  };
72873
- const resultPath = resolve8(opts.outDir, `${prefix}.json`);
72961
+ const resultPath = resolve9(opts.outDir, `${prefix}.json`);
72874
72962
  writeFileSync30(resultPath, `${JSON.stringify(result, null, 2)}
72875
72963
  `, "utf8");
72876
72964
  if (opts.json) {
72877
72965
  console.log(JSON.stringify(result));
72878
72966
  } else {
72879
72967
  console.log("");
72880
- console.log(chalk27.bold(` ${opts.component} — isolated (${viewport})`));
72881
- console.log(chalk27.dim(` prod ${prodUrl}`));
72882
- console.log(chalk27.dim(` cand ${candUrl}`));
72968
+ console.log(chalk28.bold(` ${opts.component} — isolated (${viewport})`));
72969
+ console.log(chalk28.dim(` prod ${prodUrl}`));
72970
+ console.log(chalk28.dim(` cand ${candUrl}`));
72883
72971
  console.log("");
72884
72972
  for (const line of formatBoxTreeDiff(geometry).split(`
72885
72973
  `))
@@ -72890,7 +72978,7 @@ async function benchCommand(opts) {
72890
72978
  ]) {
72891
72979
  const caveat = data.settle && formatSettleCaveat(name, data.settle);
72892
72980
  if (caveat)
72893
- console.log(chalk27.yellow(` ${caveat}`));
72981
+ console.log(chalk28.yellow(` ${caveat}`));
72894
72982
  }
72895
72983
  if (motion) {
72896
72984
  console.log("");
@@ -72899,7 +72987,7 @@ async function benchCommand(opts) {
72899
72987
  console.log(` ${line}`);
72900
72988
  }
72901
72989
  console.log("");
72902
- console.log(chalk27.dim(` ${resultPath}`));
72990
+ console.log(chalk28.dim(` ${resultPath}`));
72903
72991
  }
72904
72992
  return clean || !opts.failOnDiff ? 0 : 1;
72905
72993
  } finally {
@@ -72910,7 +72998,7 @@ async function benchCommand(opts) {
72910
72998
  }
72911
72999
 
72912
73000
  // src/commands/locate.ts
72913
- import chalk28 from "chalk";
73001
+ import chalk29 from "chalk";
72914
73002
  var hitOf = (n, nodes) => ({
72915
73003
  key: n.key,
72916
73004
  label: n.label,
@@ -73035,22 +73123,22 @@ function printResult3(r) {
73035
73123
  const side = (name, a) => {
73036
73124
  if (a.found) {
73037
73125
  console.log(` ${name.padEnd(5)} ${a.hit.tag.padEnd(8)} ${formatHit(a.hit)}`);
73038
- console.log(chalk28.dim(` node: ${a.hit.key}${a.hit.label ? ` (${a.hit.label})` : ""}`));
73126
+ console.log(chalk29.dim(` node: ${a.hit.key}${a.hit.label ? ` (${a.hit.label})` : ""}`));
73039
73127
  return;
73040
73128
  }
73041
- console.log(chalk28.yellow(` ${name.padEnd(5)} ${a.reason}`));
73129
+ console.log(chalk29.yellow(` ${name.padEnd(5)} ${a.reason}`));
73042
73130
  for (const c of a.candidates ?? [])
73043
- console.log(chalk28.dim(` candidate: ${c}`));
73131
+ console.log(chalk29.dim(` candidate: ${c}`));
73044
73132
  };
73045
73133
  console.log("");
73046
- console.log(chalk28.bold(` ${r.label} — ${r.viewport}`));
73134
+ console.log(chalk29.bold(` ${r.label} — ${r.viewport}`));
73047
73135
  side("prod", r.prod);
73048
73136
  side("cand", r.cand);
73049
73137
  if (r.prod.found && r.cand.found) {
73050
73138
  const delta = formatDelta(r.prod.hit, r.cand.hit);
73051
73139
  console.log(` ${"diff".padEnd(5)} ${delta ?? "identical box and type"}`);
73052
73140
  for (const note of pairingNotes(r.prod.hit, r.cand.hit)) {
73053
- console.log(chalk28.yellow(` note ${note}`));
73141
+ console.log(chalk29.yellow(` note ${note}`));
73054
73142
  }
73055
73143
  }
73056
73144
  }
@@ -73058,22 +73146,22 @@ async function locateCommand(opts) {
73058
73146
  const selector = opts.selector ?? "body";
73059
73147
  const waitMs = Number.parseInt(opts.wait, 10);
73060
73148
  if (!Number.isFinite(waitMs) || waitMs < 0) {
73061
- console.error(chalk28.red(`--wait inválido: ${opts.wait}`));
73149
+ console.error(chalk29.red(`--wait inválido: ${opts.wait}`));
73062
73150
  return 2;
73063
73151
  }
73064
73152
  if (opts.labels.length === 0) {
73065
- console.error(chalk28.red("nenhum --label passado — o comando procura por label, não por seletor"));
73153
+ console.error(chalk29.red("nenhum --label passado — o comando procura por label, não por seletor"));
73066
73154
  return 2;
73067
73155
  }
73068
73156
  const viewports = opts.viewports.split(",").map((v) => v.trim());
73069
73157
  const bad = viewports.find((v) => parseViewport3(v) === null);
73070
73158
  if (bad) {
73071
- console.error(chalk28.red(`viewport inválido: ${bad} (mobile | tablet | desktop)`));
73159
+ console.error(chalk29.red(`viewport inválido: ${bad} (mobile | tablet | desktop)`));
73072
73160
  return 2;
73073
73161
  }
73074
73162
  const { aliases, note } = resolveAliases(opts.planDir);
73075
73163
  if (note && !opts.json)
73076
- console.log(chalk28.dim(` ${note}`));
73164
+ console.log(chalk29.dim(` ${note}`));
73077
73165
  const results = [];
73078
73166
  const caveats = [];
73079
73167
  const browser = await launchBrowser({ headless: true });
@@ -73128,32 +73216,447 @@ async function locateCommand(opts) {
73128
73216
  for (const r of results)
73129
73217
  printResult3(r);
73130
73218
  for (const c of caveats)
73131
- console.log(chalk28.yellow(` ${c}`));
73219
+ console.log(chalk29.yellow(` ${c}`));
73132
73220
  console.log("");
73133
73221
  if (unresolved.length > 0) {
73134
- console.log(chalk28.yellow(` ${unresolved.length} of ${results.length} label×viewport pair${results.length === 1 ? "" : "s"} unresolved — those rows are not a measurement`));
73222
+ console.log(chalk29.yellow(` ${unresolved.length} of ${results.length} label×viewport pair${results.length === 1 ? "" : "s"} unresolved — those rows are not a measurement`));
73135
73223
  } else {
73136
- console.log(chalk28.green(` ${results.length} label×viewport pair${results.length === 1 ? "" : "s"} located on both sides`));
73224
+ console.log(chalk29.green(` ${results.length} label×viewport pair${results.length === 1 ? "" : "s"} located on both sides`));
73137
73225
  }
73138
73226
  return unresolved.length > 0 ? 1 : 0;
73139
73227
  }
73140
73228
 
73141
73229
  // src/commands/cockpit.ts
73142
- import { resolve as resolve9 } from "node:path";
73143
- import chalk29 from "chalk";
73230
+ import { resolve as resolve14 } from "node:path";
73231
+ import chalk30 from "chalk";
73144
73232
 
73145
73233
  // src/server/cockpit.ts
73234
+ import { readFileSync as readFileSync37 } from "node:fs";
73146
73235
  import { createServer as createServer2 } from "node:http";
73236
+ import { dirname as dirname8, join as join44, resolve as resolve13 } from "node:path";
73237
+
73238
+ // src/server/cockpit-actions.ts
73239
+ import { spawn as spawn3 } from "node:child_process";
73240
+ import { existsSync as existsSync30, mkdirSync as mkdirSync21, readFileSync as readFileSync34, readdirSync as readdirSync7, writeFileSync as writeFileSync32 } from "node:fs";
73241
+ import { join as join41, resolve as resolve11 } from "node:path";
73242
+
73243
+ // src/server/cockpit-settings.ts
73244
+ import { execFileSync as execFileSync2 } from "node:child_process";
73245
+ import { chmodSync, existsSync as existsSync29, mkdirSync as mkdirSync20, readFileSync as readFileSync33, writeFileSync as writeFileSync31 } from "node:fs";
73246
+ import { homedir as homedir4 } from "node:os";
73247
+ import { join as join40, resolve as resolve10 } from "node:path";
73248
+ var FILE = () => join40(process.env.PARITY_HOME ?? join40(homedir4(), ".parity"), "config.json");
73249
+ function readAll() {
73250
+ try {
73251
+ return JSON.parse(readFileSync33(FILE(), "utf8"));
73252
+ } catch {
73253
+ return {};
73254
+ }
73255
+ }
73256
+ function getSettings(planDir) {
73257
+ return readAll().migrations?.[resolve10(planDir)] ?? {};
73258
+ }
73259
+ function saveSettings(planDir, next) {
73260
+ for (const [k, v] of Object.entries(next)) {
73261
+ if (k === "detectedAt")
73262
+ continue;
73263
+ if (v !== undefined && (typeof v !== "string" || v.length > 200 || /[\s;&|`$]/.test(v))) {
73264
+ throw new Error(`invalid ${k}`);
73265
+ }
73266
+ }
73267
+ const all = readAll();
73268
+ all.migrations = {
73269
+ ...all.migrations ?? {},
73270
+ [resolve10(planDir)]: { ...getSettings(planDir), ...next }
73271
+ };
73272
+ mkdirSync20(join40(FILE(), ".."), { recursive: true });
73273
+ writeFileSync31(FILE(), JSON.stringify(all, null, 2));
73274
+ chmodSync(FILE(), 384);
73275
+ return getSettings(planDir);
73276
+ }
73277
+ var run = (cmd, args, env) => {
73278
+ try {
73279
+ return execFileSync2(cmd, args, {
73280
+ encoding: "utf8",
73281
+ timeout: 20000,
73282
+ stdio: ["ignore", "pipe", "pipe"],
73283
+ env: { ...process.env, ...env }
73284
+ }).trim();
73285
+ } catch {
73286
+ return "";
73287
+ }
73288
+ };
73289
+ function remoteRepo(repoDir) {
73290
+ const u = run("git", ["-C", repoDir, "remote", "get-url", "origin"]);
73291
+ const m = u.match(/[:/]([\w.-]+\/[\w.-]+?)(\.git)?$/);
73292
+ return m?.[1] ?? null;
73293
+ }
73294
+ function ghAccounts() {
73295
+ const out = run("gh", ["auth", "status"]) || "";
73296
+ return [...out.matchAll(/account (\S+)/g)].map((m) => m[1]);
73297
+ }
73298
+ function ghEnv(user) {
73299
+ if (!user)
73300
+ return {};
73301
+ const token = run("gh", ["auth", "token", "--user", user]);
73302
+ return token ? { GH_TOKEN: token } : {};
73303
+ }
73304
+ function detectSettings(repoDir) {
73305
+ const repo = remoteRepo(repoDir);
73306
+ const branches = run("git", ["-C", repoDir, "branch", "-r", "--format=%(refname:short)"]).split(`
73307
+ `).filter((b) => b.startsWith("origin/") && b !== "origin/HEAD").map((b) => b.slice("origin/".length));
73308
+ const accounts = ghAccounts().map((user) => ({
73309
+ user,
73310
+ canSee: repo ? Boolean(run("gh", ["repo", "view", repo, "--json", "name"], ghEnv(user))) : false
73311
+ }));
73312
+ const usable = accounts.find((a) => a.canSee)?.user;
73313
+ let prBase = null;
73314
+ let releaseBase = null;
73315
+ let mergeMethod = null;
73316
+ if (repo && usable) {
73317
+ const json = run("gh", [
73318
+ "pr",
73319
+ "list",
73320
+ "--repo",
73321
+ repo,
73322
+ "--state",
73323
+ "merged",
73324
+ "--limit",
73325
+ "40",
73326
+ "--json",
73327
+ "number,baseRefName,headRefName"
73328
+ ], ghEnv(usable));
73329
+ try {
73330
+ const prs = JSON.parse(json || "[]");
73331
+ const counts = new Map;
73332
+ const releases = new Map;
73333
+ for (const p of prs) {
73334
+ if (/^release\//.test(p.headRefName))
73335
+ releases.set(p.baseRefName, (releases.get(p.baseRefName) ?? 0) + 1);
73336
+ if (/^(release|hotfix)\//.test(p.headRefName) || p.headRefName === "main" || p.headRefName === "master")
73337
+ continue;
73338
+ counts.set(p.baseRefName, (counts.get(p.baseRefName) ?? 0) + 1);
73339
+ }
73340
+ prBase = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
73341
+ const sample = prs.filter((p) => p.baseRefName === prBase && !/^(release|hotfix)\//.test(p.headRefName) && p.headRefName !== "main").slice(0, 3);
73342
+ const parents = sample.map((p) => {
73343
+ const oid = run("gh", [
73344
+ "pr",
73345
+ "view",
73346
+ String(p.number),
73347
+ "--repo",
73348
+ repo,
73349
+ "--json",
73350
+ "mergeCommit",
73351
+ "--jq",
73352
+ ".mergeCommit.oid"
73353
+ ], ghEnv(usable));
73354
+ return oid ? Number(run("gh", ["api", `repos/${repo}/commits/${oid}`, "--jq", ".parents | length"], ghEnv(usable))) : 0;
73355
+ });
73356
+ mergeMethod = parents.length && parents.every((n) => n === 2) ? "merge" : parents.some((n) => n === 1) ? "squash" : null;
73357
+ releaseBase = [...releases.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
73358
+ } catch {
73359
+ prBase = null;
73360
+ }
73361
+ }
73362
+ const defaultBranch = run("git", [
73363
+ "-C",
73364
+ repoDir,
73365
+ "symbolic-ref",
73366
+ "--short",
73367
+ "refs/remotes/origin/HEAD"
73368
+ ]).replace(/^origin\//, "");
73369
+ return {
73370
+ repo,
73371
+ branches,
73372
+ accounts,
73373
+ suggested: {
73374
+ githubUser: usable ?? null,
73375
+ prBase: prBase ?? (defaultBranch || null),
73376
+ cutFrom: `origin/${prBase ?? (defaultBranch || "main")}`,
73377
+ releaseBase,
73378
+ mergeMethod
73379
+ }
73380
+ };
73381
+ }
73382
+ function effectiveSettings(planDir, repoDir) {
73383
+ const saved = getSettings(planDir);
73384
+ if (saved.githubUser && saved.prBase && saved.cutFrom && saved.mergeMethod)
73385
+ return saved;
73386
+ const d = detectSettings(repoDir).suggested;
73387
+ return saveSettings(planDir, {
73388
+ githubUser: saved.githubUser ?? d.githubUser ?? undefined,
73389
+ prBase: saved.prBase ?? d.prBase ?? undefined,
73390
+ cutFrom: saved.cutFrom ?? d.cutFrom ?? undefined,
73391
+ releaseBase: saved.releaseBase ?? d.releaseBase ?? undefined,
73392
+ mergeMethod: saved.mergeMethod ?? d.mergeMethod ?? undefined,
73393
+ detectedAt: saved.detectedAt ?? new Date().toISOString()
73394
+ });
73395
+ }
73396
+
73397
+ // src/server/cockpit-actions.ts
73398
+ var COMPONENT_STATUSES = [
73399
+ "pending",
73400
+ "partial",
73401
+ "done",
73402
+ "as-is",
73403
+ "upgrade",
73404
+ "skipped"
73405
+ ];
73406
+ var PAGE_STATUSES2 = ["pending", "code", "done", "skipped"];
73407
+ function readState(planDir) {
73408
+ try {
73409
+ return JSON.parse(readFileSync34(join41(planDir, "migration.json"), "utf8"));
73410
+ } catch {
73411
+ return null;
73412
+ }
73413
+ }
73414
+ var gh = (repo) => typeof repo === "string" && /^[\w.-]+\/[\w.-]+$/.test(repo) ? `https://github.com/${repo}` : null;
73415
+ function migrationOverview(planDir) {
73416
+ const state = readState(planDir);
73417
+ const plan = loadPlan(planDir);
73418
+ if (!state && !plan)
73419
+ return null;
73420
+ const targetRepo = state?.target?.repo ?? null;
73421
+ const sourceRepo = state?.source?.repo ?? null;
73422
+ const stack = Array.isArray(state?.stack) ? state.stack : [];
73423
+ const remote = remoteUrl(state?.target?.dir ?? null);
73424
+ const targetUrl = remote ?? gh(targetRepo);
73425
+ const repoMismatch = Boolean(remote && gh(targetRepo) && remote !== gh(targetRepo));
73426
+ return {
73427
+ source: {
73428
+ kind: state?.source?.kind ?? plan?.source?.kind ?? null,
73429
+ prodUrl: state?.source?.prodUrl ?? plan?.url ?? null,
73430
+ repo: sourceRepo,
73431
+ repoUrl: state?.source?.repoUrl ?? gh(sourceRepo)
73432
+ },
73433
+ target: {
73434
+ name: state?.target?.name ?? plan?.target?.name ?? null,
73435
+ repo: remote ? remote.replace("https://github.com/", "") : targetRepo,
73436
+ repoUrl: targetUrl,
73437
+ declaredRepo: repoMismatch ? targetRepo : null,
73438
+ dir: state?.target?.dir ?? null
73439
+ },
73440
+ phase: state?.phase ?? null,
73441
+ stage: state?.stage ?? null,
73442
+ round: state?.round ?? null,
73443
+ currentPage: state?.currentPage ?? null,
73444
+ budget: state?.budget ?? null,
73445
+ parity: state?.parity ?? null,
73446
+ gates: state?.conventions?.gates ?? [],
73447
+ rules: state?.conventions?.rules?.length ?? 0,
73448
+ stack: stack.map((s) => ({
73449
+ ...s,
73450
+ prUrl: targetUrl && s.pr ? `${targetUrl}/pull/${s.pr}` : null,
73451
+ issueUrl: targetUrl && s.issue ? `${targetUrl}/issues/${s.issue}` : null
73452
+ })),
73453
+ progress: plan ? planProgress(plan) : null,
73454
+ pages: (plan?.pages ?? []).map((p) => ({
73455
+ path: p.path,
73456
+ kind: p.kind,
73457
+ status: p.status ?? "pending"
73458
+ })),
73459
+ components: (plan?.components ?? []).map((c) => ({
73460
+ name: c.name,
73461
+ scope: c.scope,
73462
+ status: c.status,
73463
+ verified: c.verified?.verdict ?? null,
73464
+ provenance: c.provenance ?? null
73465
+ })),
73466
+ capturedAt: plan?.timestamp ?? null,
73467
+ reindex: lastJob(planDir, "reindex")
73468
+ };
73469
+ }
73470
+ function setComponent(planDir, name, status, decision = {}) {
73471
+ if (!COMPONENT_STATUSES.includes(status)) {
73472
+ throw new Error(`status must be one of ${COMPONENT_STATUSES.join(", ")}`);
73473
+ }
73474
+ const url = decision.url?.trim() ?? "";
73475
+ const design = decision.design?.trim() ?? "";
73476
+ for (const u of [url, design]) {
73477
+ if (u && !/^https?:\/\//.test(u))
73478
+ throw new Error(`not a URL: ${u}`);
73479
+ }
73480
+ const plan = loadPlan(planDir);
73481
+ if (!plan)
73482
+ throw new Error("no migration-plan.json");
73483
+ const c = setComponentStatus(plan, name, status);
73484
+ if (!c)
73485
+ throw new Error(`no component "${name}" in the plan`);
73486
+ const note = decision.note?.trim() ?? "";
73487
+ if (note || url || design) {
73488
+ setComponentReference(plan, name, {
73489
+ url,
73490
+ selector: c.reference?.selector ?? null,
73491
+ note,
73492
+ ...design ? { design } : {}
73493
+ });
73494
+ }
73495
+ savePlan(planDir, plan);
73496
+ return c;
73497
+ }
73498
+ function setComponentSelector(planDir, name, selector) {
73499
+ const sel = selector.trim();
73500
+ if (!sel || sel.length > 500)
73501
+ throw new Error("a selector is required");
73502
+ const plan = loadPlan(planDir);
73503
+ if (!plan)
73504
+ throw new Error("no migration-plan.json");
73505
+ const c = plan.components.find((x) => x.name === name);
73506
+ if (!c)
73507
+ throw new Error(`no component "${name}" in the plan`);
73508
+ c.selector = sel;
73509
+ c.selectorPinned = true;
73510
+ savePlan(planDir, plan);
73511
+ return c;
73512
+ }
73513
+ function captured(planDir, host, name) {
73514
+ const file = join41(planDir, host, "capture.json");
73515
+ if (!existsSync30(file))
73516
+ return null;
73517
+ try {
73518
+ const cap = JSON.parse(readFileSync34(file, "utf8"));
73519
+ const rows = Array.isArray(cap.components) ? cap.components : [];
73520
+ return rows.find((r) => r.role === name || r.name === name) ?? null;
73521
+ } catch {
73522
+ return null;
73523
+ }
73524
+ }
73525
+ function componentDetail(planDir, name) {
73526
+ const plan = loadPlan(planDir);
73527
+ if (!plan)
73528
+ return null;
73529
+ const c = plan.components.find((x) => x.name === name);
73530
+ if (!c)
73531
+ return null;
73532
+ const host = (() => {
73533
+ try {
73534
+ return new URL(plan.url).host;
73535
+ } catch {
73536
+ return "";
73537
+ }
73538
+ })();
73539
+ const cap = host ? captured(planDir, host, name) : null;
73540
+ const shot = typeof cap?.screenshotPath === "string" && existsSync30(cap.screenshotPath) ? cap.screenshotPath : null;
73541
+ const styles = cap?.computedStyles ?? {};
73542
+ return {
73543
+ name: c.name,
73544
+ scope: c.scope,
73545
+ status: c.status,
73546
+ reference: c.reference ?? null,
73547
+ verified: c.verified ?? null,
73548
+ prodSelector: c.selector ?? (typeof cap?.selector === "string" ? cap.selector : null),
73549
+ selectorFrom: c.selectorPinned ? "picked" : c.selector ? "plan" : cap?.selector ? "capture" : null,
73550
+ page: "/",
73551
+ hasShot: Boolean(shot),
73552
+ captured: cap ? { width: styles.width ?? null, height: styles.height ?? null } : null
73553
+ };
73554
+ }
73555
+ function componentShot(planDir, name) {
73556
+ const plan = loadPlan(planDir);
73557
+ if (!plan)
73558
+ return null;
73559
+ let host = "";
73560
+ try {
73561
+ host = new URL(plan.url).host;
73562
+ } catch {
73563
+ return null;
73564
+ }
73565
+ const cap = captured(planDir, host, name);
73566
+ const p = typeof cap?.screenshotPath === "string" ? cap.screenshotPath : null;
73567
+ if (!p || !resolve11(p).startsWith(resolve11(join41(planDir, host))))
73568
+ return null;
73569
+ return existsSync30(p) ? readFileSync34(p) : null;
73570
+ }
73571
+ function setPage(planDir, path, status) {
73572
+ if (!PAGE_STATUSES2.includes(status)) {
73573
+ throw new Error(`status must be one of ${PAGE_STATUSES2.join(", ")}`);
73574
+ }
73575
+ const plan = loadPlan(planDir);
73576
+ if (!plan)
73577
+ throw new Error("no migration-plan.json");
73578
+ const p = setPageStatus(plan, path, status);
73579
+ if (!p)
73580
+ throw new Error(`no page "${path}" in the plan`);
73581
+ savePlan(planDir, plan);
73582
+ return p;
73583
+ }
73584
+ var jobsDir = (planDir) => join41(planDir, "jobs");
73585
+ function lastJob(planDir, kind) {
73586
+ const dir = jobsDir(planDir);
73587
+ if (!existsSync30(dir))
73588
+ return null;
73589
+ const id = readdirSync7(dir).filter((d) => d.startsWith(`${kind}-`)).sort().pop();
73590
+ if (!id)
73591
+ return null;
73592
+ const j = join41(dir, id);
73593
+ const read = (f) => existsSync30(join41(j, f)) ? readFileSync34(join41(j, f), "utf8") : null;
73594
+ const exit = read("exit");
73595
+ const pid = Number(read("pid") ?? 0);
73596
+ let alive = false;
73597
+ try {
73598
+ if (pid) {
73599
+ process.kill(pid, 0);
73600
+ alive = true;
73601
+ }
73602
+ } catch {
73603
+ alive = false;
73604
+ }
73605
+ const log = read("log") ?? "";
73606
+ return {
73607
+ id,
73608
+ startedAt: read("started"),
73609
+ status: exit !== null ? Number(exit) === 0 ? "done" : "failed" : alive ? "running" : "failed",
73610
+ exit: exit !== null ? Number(exit) : null,
73611
+ log: log.slice(-3000)
73612
+ };
73613
+ }
73614
+ function startReindex(planDir) {
73615
+ const running = lastJob(planDir, "reindex");
73616
+ if (running?.status === "running")
73617
+ throw new Error("a re-index is already running");
73618
+ const state = readState(planDir);
73619
+ const plan = loadPlan(planDir);
73620
+ const url = state?.source?.prodUrl ?? plan?.url;
73621
+ if (!url)
73622
+ throw new Error("no prod URL in migration.json or the plan");
73623
+ const target = state?.target?.name ?? plan?.target?.name;
73624
+ const id = `reindex-${new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14)}`;
73625
+ const dir = join41(jobsDir(planDir), id);
73626
+ mkdirSync21(dir, { recursive: true });
73627
+ writeFileSync32(join41(jobsDir(planDir), ".gitignore"), `*
73628
+ `);
73629
+ writeFileSync32(join41(dir, "started"), new Date().toISOString());
73630
+ const host = new URL(url).host;
73631
+ const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
73632
+ const cli = `${q(process.execPath)} ${q(resolve11(process.argv[1] ?? ""))}`;
73633
+ const out = join41(dir, "capture");
73634
+ const sh = [
73635
+ `${cli} capture --url ${q(url)}${target ? ` --target ${q(target)}` : ""} --out ${q(out)} --refresh`,
73636
+ `${cli} plan merge ${q(join41(out, host))} --dir ${q(resolve11(planDir))}`
73637
+ ].join(" && ");
73638
+ const child = spawn3("sh", ["-c", `(${sh}) > ${q(join41(dir, "log"))} 2>&1; echo $? > ${q(join41(dir, "exit"))}`], {
73639
+ detached: true,
73640
+ stdio: "ignore"
73641
+ });
73642
+ child.unref();
73643
+ writeFileSync32(join41(dir, "pid"), String(child.pid ?? ""));
73644
+ return lastJob(planDir, "reindex");
73645
+ }
73646
+ function remoteUrl(dir) {
73647
+ const r = dir ? remoteRepo(dir) : null;
73648
+ return r ? `https://github.com/${r}` : null;
73649
+ }
73147
73650
 
73148
73651
  // src/server/cockpit-api.ts
73149
- import { existsSync as existsSync29, readFileSync as readFileSync33, readdirSync as readdirSync7 } from "node:fs";
73150
- import { join as join39 } from "node:path";
73652
+ import { existsSync as existsSync31, readFileSync as readFileSync35, readdirSync as readdirSync8 } from "node:fs";
73653
+ import { join as join42 } from "node:path";
73151
73654
  var notFound = (what) => ({ status: 404, body: { error: what } });
73152
73655
  function readJson2(path) {
73153
- if (!existsSync29(path))
73656
+ if (!existsSync31(path))
73154
73657
  return null;
73155
73658
  try {
73156
- return JSON.parse(readFileSync33(path, "utf8"));
73659
+ return JSON.parse(readFileSync35(path, "utf8"));
73157
73660
  } catch {
73158
73661
  return null;
73159
73662
  }
@@ -73162,17 +73665,17 @@ function withPlan(ctx) {
73162
73665
  return loadPlan(ctx.planDir);
73163
73666
  }
73164
73667
  function listBenchResults(benchDir) {
73165
- if (!existsSync29(benchDir))
73668
+ if (!existsSync31(benchDir))
73166
73669
  return [];
73167
73670
  let files;
73168
73671
  try {
73169
- files = readdirSync7(benchDir).filter((f) => f.startsWith("bench-") && f.endsWith(".json"));
73672
+ files = readdirSync8(benchDir).filter((f) => f.startsWith("bench-") && f.endsWith(".json"));
73170
73673
  } catch {
73171
73674
  return [];
73172
73675
  }
73173
73676
  const out = [];
73174
73677
  for (const file of files) {
73175
- const raw = readJson2(join39(benchDir, file));
73678
+ const raw = readJson2(join42(benchDir, file));
73176
73679
  if (!raw?.component)
73177
73680
  continue;
73178
73681
  out.push({
@@ -73197,11 +73700,11 @@ function cockpitApi(path, params, ctx) {
73197
73700
  benchDir: ctx.benchDir,
73198
73701
  prodUrl: ctx.prodUrl ?? null,
73199
73702
  candUrl: ctx.candUrl ?? null,
73200
- hasPlan: existsSync29(join39(ctx.planDir, "migration-plan.json"))
73703
+ hasPlan: existsSync31(join42(ctx.planDir, "migration-plan.json"))
73201
73704
  }
73202
73705
  };
73203
73706
  case "/api/state": {
73204
- const state = readJson2(join39(ctx.planDir, "migration.json"));
73707
+ const state = readJson2(join42(ctx.planDir, "migration.json"));
73205
73708
  return state ? { status: 200, body: state } : notFound("no migration.json — no migration has been started here");
73206
73709
  }
73207
73710
  case "/api/plan": {
@@ -73276,7 +73779,7 @@ function cockpitApi(path, params, ctx) {
73276
73779
  if (file.includes("/") || file.includes("\\") || !/^bench-[\w.-]+\.json$/.test(file)) {
73277
73780
  return { status: 400, body: { error: "bad file name" } };
73278
73781
  }
73279
- const raw = readJson2(join39(ctx.benchDir, file));
73782
+ const raw = readJson2(join42(ctx.benchDir, file));
73280
73783
  return raw ? { status: 200, body: raw } : notFound(`no bench result ${file}`);
73281
73784
  }
73282
73785
  default:
@@ -73762,100 +74265,1441 @@ async function loadRun() {
73762
74265
  </html>
73763
74266
  `;
73764
74267
 
73765
- // src/server/cockpit.ts
73766
- async function startCockpit(ctx, opts = {}) {
73767
- const server = createServer2((req, res) => {
73768
- handle(req, res, ctx).catch((err) => {
73769
- try {
73770
- res.statusCode = 500;
73771
- res.setHeader("content-type", "application/json");
73772
- res.end(JSON.stringify({ error: err.message }));
73773
- } catch {}
73774
- });
73775
- });
73776
- await new Promise((ready, reject) => {
73777
- server.once("error", reject);
73778
- server.listen(opts.port ?? 0, opts.host ?? "127.0.0.1", () => ready());
73779
- });
73780
- const addr = server.address();
73781
- const port = typeof addr === "object" && addr ? addr.port : 0;
73782
- const host = opts.host ?? "127.0.0.1";
73783
- return {
73784
- port,
73785
- url: `http://${host}:${port}/`,
73786
- close: () => new Promise((done) => {
73787
- try {
73788
- server.closeAllConnections?.();
73789
- server.closeIdleConnections?.();
73790
- } catch {}
73791
- server.close(() => done());
73792
- setTimeout(() => done(), 1000);
73793
- })
73794
- };
74268
+ // src/server/cockpit-tasks.ts
74269
+ import { execFileSync as execFileSync3, spawn as spawn4 } from "node:child_process";
74270
+ import { randomUUID } from "node:crypto";
74271
+ import {
74272
+ appendFileSync as appendFileSync2,
74273
+ existsSync as existsSync32,
74274
+ mkdirSync as mkdirSync22,
74275
+ readFileSync as readFileSync36,
74276
+ readdirSync as readdirSync9,
74277
+ realpathSync,
74278
+ renameSync as renameSync2,
74279
+ rmSync,
74280
+ statSync as statSync3,
74281
+ symlinkSync,
74282
+ unlinkSync as unlinkSync4,
74283
+ writeFileSync as writeFileSync33
74284
+ } from "node:fs";
74285
+ import { dirname as dirname7, join as join43, resolve as resolve12 } from "node:path";
74286
+ import { fileURLToPath } from "node:url";
74287
+ var VIEWPORT = {
74288
+ mobile: { width: 412, height: 839 },
74289
+ tablet: { width: 768, height: 1024 },
74290
+ desktop: { width: 1440, height: 900 }
74291
+ };
74292
+ var MOBILE_UA2 = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1";
74293
+ var STALL_MS = Number(process.env.PARITY_STALL_MS ?? 10 * 60000);
74294
+ var tasksDir = (planDir) => join43(planDir, "tasks");
74295
+ var taskDir = (planDir, id) => join43(tasksDir(planDir), id);
74296
+ function validTaskId(id) {
74297
+ return /^[\w-]{6,64}$/.test(id);
74298
+ }
74299
+ function pluginDir() {
74300
+ const root = resolve12(dirname7(fileURLToPath(import.meta.url)), "../../../..");
74301
+ return existsSync32(join43(root, ".claude-plugin", "plugin.json")) ? root : null;
74302
+ }
74303
+ function targetDir(planDir) {
74304
+ try {
74305
+ const state = JSON.parse(readFileSync36(join43(planDir, "migration.json"), "utf8"));
74306
+ if (typeof state?.target?.dir === "string" && existsSync32(state.target.dir))
74307
+ return state.target.dir;
74308
+ } catch {}
74309
+ return dirname7(resolve12(planDir));
73795
74310
  }
73796
- async function handle(req, res, ctx) {
73797
- const url = new URL(req.url ?? "/", "http://placeholder");
73798
- const path = decodeURIComponent(url.pathname);
73799
- const api = cockpitApi(path, url.searchParams, ctx);
73800
- if (api) {
73801
- res.statusCode = api.status;
73802
- res.setHeader("content-type", "application/json; charset=utf-8");
73803
- res.setHeader("cache-control", "no-store");
73804
- res.end(JSON.stringify(api.body));
73805
- return;
74311
+ function withPath(base, path) {
74312
+ try {
74313
+ return new URL(path, base).toString();
74314
+ } catch {
74315
+ return base;
73806
74316
  }
73807
- if (path === "/proxy") {
73808
- const target = url.searchParams.get("url");
73809
- if (!target) {
73810
- res.statusCode = 400;
73811
- res.end("missing ?url=");
73812
- return;
74317
+ }
74318
+ async function capture(task, dir) {
74319
+ const { chromium } = await import("playwright");
74320
+ const browser = await chromium.launch();
74321
+ const shots = { prod: null, cand: null };
74322
+ const misses = [];
74323
+ try {
74324
+ for (const side of ["prod", "cand"]) {
74325
+ const selector = side === task.side ? task.selector : task.counterpart;
74326
+ if (!selector) {
74327
+ misses.push(`${side}: no counterpart found in the cockpit`);
74328
+ continue;
74329
+ }
74330
+ const seen = task.context?.[side]?.viewport ?? task.context?.[task.side]?.viewport;
74331
+ const ctx = await browser.newContext({
74332
+ viewport: seen ? { width: seen.width, height: seen.height } : VIEWPORT[task.device],
74333
+ deviceScaleFactor: seen?.dpr ?? 1,
74334
+ ...task.device === "desktop" ? {} : { userAgent: MOBILE_UA2, isMobile: true }
74335
+ });
74336
+ try {
74337
+ const page = await ctx.newPage();
74338
+ await page.goto(withPath(side === "prod" ? task.prodUrl : task.candUrl, task.page), {
74339
+ waitUntil: "load",
74340
+ timeout: 45000
74341
+ });
74342
+ await page.waitForTimeout(2500);
74343
+ const el = page.locator(selector).first();
74344
+ await el.scrollIntoViewIfNeeded({ timeout: 8000 });
74345
+ const file = join43(dir, `${side}.png`);
74346
+ await el.screenshot({ path: file, timeout: 1e4 });
74347
+ shots[side] = file;
74348
+ } catch (err) {
74349
+ misses.push(`${side}: ${err.message.split(`
74350
+ `)[0]}`);
74351
+ } finally {
74352
+ await ctx.close();
74353
+ }
73813
74354
  }
73814
- return proxyRequest(req, res, target, {
73815
- forceMobile: url.searchParams.get("viewport") === "mobile"
73816
- });
73817
- }
73818
- if (path === "/" || path === "/index.html") {
73819
- res.statusCode = 200;
73820
- res.setHeader("content-type", "text/html; charset=utf-8");
73821
- res.setHeader("cache-control", "no-store");
73822
- res.end(COCKPIT_HTML);
73823
- return;
74355
+ } finally {
74356
+ await browser.close();
73824
74357
  }
73825
- res.statusCode = 404;
73826
- res.setHeader("content-type", "application/json");
73827
- res.end(JSON.stringify({ error: `no route ${path}` }));
74358
+ return { shots, ...misses.length ? { captureError: misses.join("; ") } : {} };
73828
74359
  }
73829
-
73830
- // src/commands/cockpit.ts
73831
- async function cockpitCommand(opts) {
73832
- const ctx = {
73833
- planDir: resolve9(opts.dir),
73834
- output: resolve9(opts.output),
73835
- benchDir: resolve9(opts.benchDir),
73836
- prodUrl: opts.prodUrl,
73837
- candUrl: opts.candUrl
73838
- };
73839
- let handle;
73840
- try {
73841
- handle = await startCockpit(ctx, {
73842
- port: opts.port ? Number.parseInt(opts.port, 10) : undefined,
73843
- host: opts.host
73844
- });
73845
- } catch (err) {
73846
- console.error(chalk29.red(` ✖ could not start the cockpit: ${err.message}`));
73847
- return 2;
74360
+ var SKIP_DIRS = new Set([
74361
+ "node_modules",
74362
+ ".git",
74363
+ ".next",
74364
+ ".faststore",
74365
+ "dist",
74366
+ "build",
74367
+ ".parity",
74368
+ ".turbo"
74369
+ ]);
74370
+ function locateSource(html, root) {
74371
+ const mods = new Map;
74372
+ for (const m of html.matchAll(/\b([A-Z][A-Za-z0-9]+)_([A-Za-z0-9]+(?:__[A-Za-z0-9-]+)*?)__[A-Za-z0-9_-]{5}\b/g)) {
74373
+ const [, stem, local] = m;
74374
+ if (!stem || !local)
74375
+ continue;
74376
+ if (!mods.has(stem))
74377
+ mods.set(stem, new Set);
74378
+ mods.get(stem)?.add(local);
74379
+ }
74380
+ if (mods.size === 0)
74381
+ return [];
74382
+ const hits = [];
74383
+ const walk = (dir, depth) => {
74384
+ if (depth > 8 || hits.length >= 12)
74385
+ return;
74386
+ let entries;
74387
+ try {
74388
+ entries = readdirSync9(dir, { withFileTypes: true });
74389
+ } catch {
74390
+ return;
74391
+ }
74392
+ for (const e of entries) {
74393
+ if (e.isDirectory()) {
74394
+ if (!SKIP_DIRS.has(e.name) && !e.name.startsWith("."))
74395
+ walk(join43(dir, e.name), depth + 1);
74396
+ continue;
74397
+ }
74398
+ const stem = e.name.split(".")[0] ?? "";
74399
+ if (!mods.has(stem))
74400
+ continue;
74401
+ const file = join43(dir, e.name);
74402
+ if (/\.(s?css|less)$/.test(e.name)) {
74403
+ const lines = readFileSync36(file, "utf8").split(`
74404
+ `);
74405
+ for (const local of mods.get(stem) ?? []) {
74406
+ const leaf = local.split("__").pop() ?? local;
74407
+ const i = lines.findIndex((l) => l.includes(`.${local}`) || l.includes(`&__${leaf}`));
74408
+ hits.push(i >= 0 ? { file, rule: local, line: i + 1 } : { file, rule: local });
74409
+ }
74410
+ } else if (/\.(tsx|jsx|ts|js)$/.test(e.name)) {
74411
+ hits.push({ file });
74412
+ }
74413
+ }
74414
+ };
74415
+ walk(existsSync32(join43(root, "src")) ? join43(root, "src") : root, 0);
74416
+ return hits;
74417
+ }
74418
+ function grid(s) {
74419
+ const kids = s?.children ?? [];
74420
+ if (!kids.length || kids[0]?.y === undefined)
74421
+ return "—";
74422
+ const rows = [];
74423
+ for (const k of kids)
74424
+ if (!rows.some((y) => Math.abs(y - (k.y ?? 0)) <= 2))
74425
+ rows.push(k.y ?? 0);
74426
+ const perRow = rows.map((y) => kids.filter((k) => Math.abs((k.y ?? 0) - y) <= 2).length);
74427
+ return `${rows.length} row${rows.length === 1 ? "" : "s"} (${perRow.join(" + ")})`;
74428
+ }
74429
+ var median3 = (xs) => {
74430
+ const v = [...xs].sort((a, b) => a - b);
74431
+ return v.length ? v[Math.floor(v.length / 2)] : null;
74432
+ };
74433
+ function sizesMarkdown(task, sources) {
74434
+ const { prod, cand } = task.context ?? {};
74435
+ const vp = (prod ?? cand)?.viewport;
74436
+ const cellKid = (s, i) => {
74437
+ const k = s?.children[i ?? 0];
74438
+ return k ? `${k.width} × ${k.height}` : "—";
74439
+ };
74440
+ const med = (s, key) => s?.children.length ? String(median3(s.children.map((c) => c[key]))) : "—";
74441
+ const rows = [
74442
+ [
74443
+ "element box (w × h)",
74444
+ prod ? `${prod.rect.width} × ${prod.rect.height}` : "—",
74445
+ cand ? `${cand.rect.width} × ${cand.rect.height}` : "—"
74446
+ ],
74447
+ ["items", prod ? String(prod.childCount) : "—", cand ? String(cand.childCount) : "—"],
74448
+ ["layout", grid(prod), grid(cand)],
74449
+ ["item width (median)", med(prod, "width"), med(cand, "width")],
74450
+ ["item height (median)", med(prod, "height"), med(cand, "height")]
74451
+ ];
74452
+ const LAYOUT = [
74453
+ "display",
74454
+ "gap",
74455
+ "grid-template-columns",
74456
+ "padding",
74457
+ "margin",
74458
+ "font-size",
74459
+ "line-height",
74460
+ "font-weight",
74461
+ "border-radius",
74462
+ "justify-content"
74463
+ ];
74464
+ const styleRows = prod && cand ? LAYOUT.filter((k) => prod.styles[k] !== cand.styles[k]) : [];
74465
+ const n = Math.max(prod?.children.length ?? 0, cand?.children.length ?? 0, 0);
74466
+ const out = [
74467
+ `# Size adjustments — ${task.page} at ${vp ? `${vp.width}×${vp.height}` : "unknown viewport"} (${task.device})`,
74468
+ "",
74469
+ `Note: ${task.text}`,
74470
+ "",
74471
+ "Make cand's **rendered** sizes match the prod column at this viewport. Prod's markup differs; match the numbers, not its CSS.",
74472
+ "",
74473
+ "| measure | prod (target) | cand (now) |",
74474
+ "| --- | --- | --- |",
74475
+ ...rows.map((r) => `| ${r.join(" | ")} |`),
74476
+ ...styleRows.map((k) => `| \`${k}\` on the element | ${prod?.styles[k]} | ${cand?.styles[k]} |`),
74477
+ ""
74478
+ ];
74479
+ if (n) {
74480
+ out.push("## Items", "", "| # | prod | cand |", "| --- | --- | --- |");
74481
+ for (let i = 0;i < Math.min(n, 12); i++)
74482
+ out.push(`| ${i + 1} | ${cellKid(prod, i)} | ${cellKid(cand, i)} |`);
74483
+ out.push("");
74484
+ }
74485
+ out.push("## Source (cand)", "");
74486
+ if (sources.length) {
74487
+ for (const h of sources)
74488
+ out.push(`- ${h.file}${h.line ? `:${h.line}` : ""}${h.rule ? ` — \`.${h.rule}\`` : ""}`);
74489
+ } else {
74490
+ out.push("- Not located from class names — find it by the element's text.");
74491
+ }
74492
+ if (!prod || !cand) {
74493
+ out.push("", `**Missing side:** ${!prod ? "prod" : "cand"} was not measured — the counterpart was not found. These numbers are one-sided.`);
74494
+ }
74495
+ return `${out.join(`
74496
+ `)}
74497
+ `;
74498
+ }
74499
+ function contextLines(task, dir) {
74500
+ const { prod, cand } = task.context ?? {};
74501
+ const any = prod ?? cand;
74502
+ if (!any)
74503
+ return ["- No measurements were captured."];
74504
+ const box = (s) => s ? `${s.rect.width}×${s.rect.height} at (${s.rect.x}, ${s.rect.y})` : "not found";
74505
+ const kids = (s) => s?.children.length ? `${s.childCount} children, first: ${s.children.slice(0, 6).map((c) => `${c.width}×${c.height}`).join(", ")}` : "no visible children";
74506
+ const out = [
74507
+ `- Viewport the reviewer was looking at: ${any.viewport.width}×${any.viewport.height} CSS px (device "${task.device}", dpr ${any.viewport.dpr}; shown scaled to ${any.viewport.scale} in the cockpit)`,
74508
+ `- Element box — prod: ${box(prod)} · cand: ${box(cand)}`,
74509
+ `- Layout — prod: ${kids(prod)} · cand: ${kids(cand)}`
74510
+ ];
74511
+ if (prod && cand) {
74512
+ const diff = Object.keys(prod.styles).filter((k) => prod.styles[k] !== cand.styles[k]);
74513
+ out.push(diff.length ? `- Computed styles that differ (prod → cand):
74514
+ ${diff.map((k) => ` ${k}: ${prod.styles[k]} → ${cand.styles[k]}`).join(`
74515
+ `)}` : "- Computed styles: no difference in the tracked properties (the difference is in children or content).");
74516
+ }
74517
+ out.push(`- Full measurements (styles, children, HTML of both sides): ${join43(dir, "context.json")}`);
74518
+ return out;
74519
+ }
74520
+ function deliveryRule(planDir, task) {
74521
+ const s = effectiveSettings(planDir, targetDir(planDir));
74522
+ const base = s.prBase ?? "the repo's integration branch";
74523
+ return [
74524
+ `Delivery: when QA passes, have \`runner\` push \`${task.branch ?? `cockpit/${task.id}`}\` and open ONE PR into \`${base}\` with \`gh pr create --base ${base}\` (gh is already authenticated as the account that can reach this repo — do not switch accounts). Use the repo's PR template if it has one; title in the repo's commit convention; body: the reviewer's note (verbatim), what was measured, what changed, what QA verified.`,
74525
+ s.releaseBase && s.releaseBase !== base ? `This repo's flow: work goes into \`${base}\`; \`${s.releaseBase}\` only receives release PRs — never open a task PR into \`${s.releaseBase}\`.` : "",
74526
+ `Then wait for EVERY check on the PR: have \`runner\` run \`gh pr checks <number>\` about once a minute (one call per turn — no \`--watch\`, which outlives a command's time limit) until none is pending. When all passed and at least one ran, merge it: \`gh pr merge <number> --${s.mergeMethod ?? "merge"}\` — this repo's merge method. Never \`--admin\`, never bypass a failing or missing check. Zero checks after 10 minutes is not green: do not merge, report it.`,
74527
+ `A failing check blocks the merge unless it is the base branch's, not yours: it failed on at least 3 of the last 5 PRs merged into \`${s.prBase ?? "the base"}\`, and every spec failing here also failed on the latest of those. Then merge, and first comment on the PR which check you waived and that evidence. If you cannot read the failing specs on both sides, it is not waivable.`,
74528
+ "If a check fails: have `runner` fetch the failing job's log (`gh run view <run-id> --log-failed`), dispatch `fixer` with it on the same branch, push, and wait for all checks again — at most 2 CI rounds, then stop and report which check still fails. Never deploy.",
74529
+ "If QA did not pass, do not open a PR — report why.",
74530
+ 'Final line: PARITY_RESULT: {"ok": boolean, "branch": string|null, "pr_url": string|null, "merged": boolean, "qa": "pass"|"fail"|"not-run", "summary": string}'
74531
+ ].filter(Boolean).join(`
74532
+ `);
74533
+ }
74534
+ function qaCommand(task, dir, cand = `http://localhost:${previewPort(task.id)}`) {
74535
+ if (!task.counterpart)
74536
+ return "(no counterpart — find it with `parity pair` first)";
74537
+ return `parity section --task '${dir}' --cand ${cand} --box-tree --computed-styles --screenshot --json`;
74538
+ }
74539
+ function previewPort(id) {
74540
+ let h = 0;
74541
+ for (const ch of id)
74542
+ h = h * 31 + ch.charCodeAt(0) >>> 0;
74543
+ return 4100 + h % 800;
74544
+ }
74545
+ function prompt(task, planDir, dir) {
74546
+ const other = task.side === "prod" ? "cand" : "prod";
74547
+ return [
74548
+ "You are the parity migration orchestrator. Load the `parity:migration-orchestrator` skill and follow its rules (dispatch, never work inline; shell goes through `runner`).",
74549
+ `The migration state is in ${join43(resolve12(planDir), "migration.json")}.`,
74550
+ "",
74551
+ "A reviewer left this note in the parity cockpit. Treat it as ONE scoped fix round for this element only — not a full migration pass.",
74552
+ `- Note: ${JSON.stringify(task.text)}`,
74553
+ `- Page: ${task.page} (prod ${task.prodUrl} · cand ${task.candUrl}) at the ${task.device} viewport`,
74554
+ `- Clicked on ${task.side}: \`${task.selector}\``,
74555
+ task.counterpart ? `- Counterpart on ${other} (found by ${task.matchedBy}; verify it): \`${task.counterpart}\`` : `- No counterpart was found on ${other}; locate it yourself (\`parity locate\`).`,
74556
+ task.shots.prod ? `- Screenshot, prod: ${task.shots.prod}` : "- No prod screenshot.",
74557
+ task.shots.cand ? `- Screenshot, cand: ${task.shots.cand}` : "- No cand screenshot.",
74558
+ task.captureError ? `- Capture problems: ${task.captureError}` : "",
74559
+ "",
74560
+ "Measured in the cockpit at the moment of the click:",
74561
+ ...contextLines(task, dir),
74562
+ "",
74563
+ "Steps:",
74564
+ `0. Reproduce first, against the DEPLOYED cand (no build needed): have \`runner\` run \`parity section --task '${dir}' --box-tree --computed-styles --screenshot --json\`. If it shows no difference in what the note is about, STOP: report ok:false, qa:"not-run", summary "does not reproduce" plus what was measured — do not dispatch a fixer. Chromium is not Safari: when the note could be engine- or device-specific (icons, SVG sprites, vh, a phone or tablet), also reproduce with \`parity ios --prod … --cand … --selector … --cand-selector … --device "iPad Pro 13-inch (M5)"\` (or an iPhone) before concluding it does not reproduce.`,
74565
+ existsSync32(join43(dir, "sizes.md")) ? `1. The numbers are already measured and written to ${join43(dir, "sizes.md")} (prod = target, cand = now, plus the source file and CSS rule). Dispatch \`fixer\` DIRECTLY with the note, sizes.md, context.json, the screenshots, and the TARGET repo's conventions.rules + gates from migration.json. Do not dispatch \`briefer\` — sizes.md is the brief.` : `1. Nothing was measured. Dispatch \`briefer\` first (note, screenshots, target dir; out: ${join43(dir, "brief.md")}), then \`fixer\` with brief.md and the TARGET repo's conventions.rules + gates.`,
74566
+ " Tell the fixer, verbatim: (a) hit the prod column's numbers at this viewport; do not re-measure from the screenshots; (b) do not start dev servers or browsers — qa verifies the render; (c) if dependencies are missing run the target's install once in the worktree, never look in other directories; (d) run only the configured gates.",
74567
+ `2. ONE preview server for the whole task, at http://localhost:${previewPort(task.id)}: after the fixer commits, have \`runner\` build the worktree once and start it there with the target's own build/start (see its AGENTS.md). Reuse it for every QA round; after a new commit, rebuild and restart that same one — never a second server, never on another port. Each agent building and starting its own cost dozens of commands per round.`,
74568
+ "3. Dispatch `qa` to verify this element against prod at the same viewport, using sizes.md (or brief.md) as the acceptance criteria. Hand it the pair and the command — do not let it rediscover selectors or start servers:",
74569
+ ` ${qaCommand(task, dir)}`,
74570
+ " If QA fails, one more fix+QA cycle at most, then stop and report. Stop the preview server before your final message.",
74571
+ task.worktree && task.base ? `You work in your own git worktree: ${task.worktree}, on branch \`${task.branch ?? `cockpit/${task.id}`}\`, cut from ${task.base.ref} (${task.base.sha.slice(0, 10)}). Every agent works and commits ONLY there; pass that path as target_dir. The reviewer's checkout (${targetDir(planDir)}) is not yours to touch.` : `Commit on a local branch \`cockpit/${task.id}\`.`,
74572
+ deliveryRule(planDir, task)
74573
+ ].filter(Boolean).join(`
74574
+ `);
74575
+ }
74576
+ function prepareWorktree(task, planDir, dir, branch = `cockpit/${task.id}`) {
74577
+ const repo = targetDir(planDir);
74578
+ const git = (...a) => execFileSync3("git", ["-C", repo, ...a], { encoding: "utf8", timeout: 90000 }).trim();
74579
+ try {
74580
+ try {
74581
+ git("fetch", "origin", "--quiet");
74582
+ } catch {}
74583
+ let ref = process.env.PARITY_TASK_BASE ?? effectiveSettings(planDir, repo).cutFrom ?? "";
74584
+ if (!ref) {
74585
+ try {
74586
+ ref = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD");
74587
+ } catch {
74588
+ ref = "HEAD";
74589
+ }
74590
+ }
74591
+ const sha = git("rev-parse", ref);
74592
+ const wt = join43(dir, "wt");
74593
+ git("worktree", "add", "-b", branch, wt, sha);
74594
+ const locks = ["package.json", "yarn.lock", "bun.lock", "package-lock.json", "pnpm-lock.yaml"];
74595
+ const sameDeps = (() => {
74596
+ try {
74597
+ execFileSync3("git", ["-C", repo, "diff", "--quiet", "HEAD", sha, "--", ...locks], {
74598
+ timeout: 1e4
74599
+ });
74600
+ return true;
74601
+ } catch {
74602
+ return false;
74603
+ }
74604
+ })();
74605
+ if (sameDeps && existsSync32(join43(repo, "node_modules")) && !existsSync32(join43(wt, "node_modules"))) {
74606
+ symlinkSync(join43(repo, "node_modules"), join43(wt, "node_modules"));
74607
+ }
74608
+ return { worktree: wt, branch, base: { ref, sha } };
74609
+ } catch (err) {
74610
+ return { worktreeError: err.message.split(`
74611
+ `)[0] };
74612
+ }
74613
+ }
74614
+ function sweepShell(worktree) {
74615
+ const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
74616
+ return `d=$(cd ${q(worktree)} 2>/dev/null && pwd -P); if [ -n "$d" ] && [ "$d" != "/" ]; then lsof -d cwd -Fpn 2>/dev/null | awk -v d="$d/" '/^p/{p=substr($0,2)} /^n/{n=substr($0,2)"/"; if(index(n,d)==1) print p}' | while read p; do kill "$p" 2>/dev/null; done; fi`;
74617
+ }
74618
+ function launch(task, planDir, dir, resume) {
74619
+ const promptFile = resume?.promptFile ?? join43(dir, "prompt.md");
74620
+ if (!resume)
74621
+ writeFileSync33(promptFile, prompt(task, planDir, dir));
74622
+ const plugin = pluginDir();
74623
+ const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
74624
+ const args = [
74625
+ `CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=${Number(process.env.PARITY_TASK_TIMEOUT_MS ?? 2700000)}`,
74626
+ q(process.env.PARITY_CLAUDE_BIN ?? "claude"),
74627
+ "-p",
74628
+ `"$(cat ${q(promptFile)})"`,
74629
+ "--output-format stream-json --verbose",
74630
+ resume ? `--resume ${task.sessionId}` : `--session-id ${task.sessionId}`,
74631
+ `--model ${q(process.env.PARITY_ORCHESTRATOR_MODEL ?? "claude-opus-5-5")}`,
74632
+ "--permission-mode bypassPermissions",
74633
+ `--disallowedTools ${q("Bash(git push --force:*)")} ${q("Bash(git push -f:*)")} ${q("Bash(gh pr merge --admin:*)")}`,
74634
+ plugin ? `--plugin-dir ${q(plugin)}` : ""
74635
+ ].filter(Boolean);
74636
+ const out = resume ? ">>" : ">";
74637
+ const sweep = task.worktree ? `; ${sweepShell(task.worktree)}` : "";
74638
+ const sh = `${args.join(" ")} ${out} ${q(join43(dir, "stream.jsonl"))} 2> ${q(join43(dir, "stderr.log"))}; code=$?${sweep}; echo $code > ${q(join43(dir, "exit"))}`;
74639
+ task.cwd ??= task.worktree ?? targetDir(planDir);
74640
+ const child = spawn4("sh", ["-c", sh], {
74641
+ env: { ...process.env, ...ghEnv(effectiveSettings(planDir, targetDir(planDir)).githubUser) },
74642
+ cwd: task.cwd,
74643
+ detached: true,
74644
+ stdio: "ignore"
74645
+ });
74646
+ child.unref();
74647
+ return child.pid;
74648
+ }
74649
+ function retryTask(planDir, id, note) {
74650
+ const dir = taskDir(planDir, id);
74651
+ const d = readTask(planDir, id);
74652
+ if (!d)
74653
+ throw new Error("no such task");
74654
+ if (d.status === "running" || d.status === "capturing")
74655
+ throw new Error("the task is still running");
74656
+ const task = d.task;
74657
+ const n = (task.attempts?.length ?? 0) + 2;
74658
+ const previousBranch = task.branch ?? d.delivery?.branch ?? null;
74659
+ let moved = false;
74660
+ if (!task.worktree || !existsSync32(task.worktree)) {
74661
+ Object.assign(task, prepareWorktree(task, planDir, dir, `cockpit/${task.id}-r${n}`));
74662
+ if (!task.worktree)
74663
+ throw new Error(`could not create a worktree: ${task.worktreeError}`);
74664
+ moved = true;
74665
+ }
74666
+ const line = (a) => `- ${a.type} (${a.status}${a.result ? "" : a.status === "running" ? ", stopped mid-run" : ", no PARITY_RESULT"}): ${a.result ? JSON.stringify(a.result).slice(0, 600) : (a.summary ?? "").slice(0, 300).replace(/\s+/g, " ")}`;
74667
+ const lines = [
74668
+ `Continue this cockpit task — attempt ${n}. This is the same session: everything you and the agents found before is above.`,
74669
+ `The previous attempt ended: ${d.reason ?? d.status}.`,
74670
+ moved ? `What changed: that attempt did not run in the code the deployed cand runs. You now have your own git worktree at ${task.worktree}, on branch \`${task.branch}\`, cut from ${task.base?.ref} (${task.base?.sha.slice(0, 10)}). All work and commits go there; pass it as target_dir to every agent.${previousBranch ? ` Commits on \`${previousBranch}\` are NOT in it — re-apply only what still applies to this code.` : ""}` : `Work continues in the same worktree (${task.worktree}), on branch \`${task.branch ?? previousBranch}\`.`,
74671
+ "",
74672
+ "Where each agent ended:",
74673
+ ...d.agents.length ? d.agents.map(line) : ["- no agent was dispatched"],
74674
+ "",
74675
+ "Redo only what did not finish; reuse sizes.md / brief.md and every result above that still holds. If the fix stands and QA did not finish, go straight to QA.",
74676
+ note ? `The reviewer adds: ${JSON.stringify(note)}` : "",
74677
+ `Preview: ONE server for this task at http://localhost:${previewPort(task.id)} — reuse it if it is already up, rebuild and restart it only after a new commit; never a second one. QA: ${qaCommand(task, dir)}`,
74678
+ "Before any new fix, if it was never shown that the difference reproduces on the deployed cand, reproduce it first with `parity section --task` (no build); if it does not, stop and say so.",
74679
+ `Same rules as ${join43(dir, "prompt.md")}, and this delivery rule:`,
74680
+ deliveryRule(planDir, task)
74681
+ ].filter(Boolean);
74682
+ const promptFile = join43(dir, `prompt-${n}.md`);
74683
+ writeFileSync33(promptFile, lines.join(`
74684
+ `));
74685
+ if (existsSync32(join43(dir, "stderr.log")))
74686
+ renameSync2(join43(dir, "stderr.log"), join43(dir, `stderr-${n - 1}.log`));
74687
+ if (existsSync32(join43(dir, "exit")))
74688
+ unlinkSync4(join43(dir, "exit"));
74689
+ if (existsSync32(join43(dir, "stopped")))
74690
+ unlinkSync4(join43(dir, "stopped"));
74691
+ task.attempts = [
74692
+ ...task.attempts ?? [],
74693
+ { at: new Date().toISOString(), reason: d.reason ?? d.status, ...note ? { note } : {} }
74694
+ ];
74695
+ task.cwd ??= targetDir(planDir);
74696
+ appendFileSync2(join43(dir, "stream.jsonl"), `${JSON.stringify({ type: "parity", subtype: "attempt", n, at: new Date().toISOString() })}
74697
+ `);
74698
+ task.pid = launch(task, planDir, dir, { promptFile });
74699
+ writeFileSync33(join43(dir, "task.json"), JSON.stringify(task, null, 2));
74700
+ return task;
74701
+ }
74702
+ async function createTask(planDir, note) {
74703
+ const id = `${new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14)}-${randomUUID().slice(0, 6)}`;
74704
+ const dir = taskDir(planDir, id);
74705
+ mkdirSync22(dir, { recursive: true });
74706
+ writeFileSync33(join43(tasksDir(planDir), ".gitignore"), `*
74707
+ `);
74708
+ if (note.context) {
74709
+ writeFileSync33(join43(dir, "context.json"), JSON.stringify(note.context, null, 2));
74710
+ const sources = note.context.cand ? locateSource(note.context.cand.html, targetDir(planDir)) : [];
74711
+ writeFileSync33(join43(dir, "sizes.md"), sizesMarkdown(note, sources));
74712
+ }
74713
+ const task = {
74714
+ ...note,
74715
+ id,
74716
+ createdAt: new Date().toISOString(),
74717
+ sessionId: randomUUID(),
74718
+ shots: { prod: null, cand: null }
74719
+ };
74720
+ const save = () => writeFileSync33(join43(dir, "task.json"), JSON.stringify(task, null, 2));
74721
+ save();
74722
+ (async () => {
74723
+ try {
74724
+ Object.assign(task, await capture(task, dir));
74725
+ } catch (err) {
74726
+ task.captureError = err.message.split(`
74727
+ `)[0];
74728
+ }
74729
+ Object.assign(task, prepareWorktree(task, planDir, dir));
74730
+ save();
74731
+ if (!task.worktree)
74732
+ return;
74733
+ task.pid = launch(task, planDir, dir);
74734
+ save();
74735
+ })();
74736
+ return task;
74737
+ }
74738
+ var procCache = new Map;
74739
+ function taskProcesses(worktree) {
74740
+ if (!worktree || !existsSync32(worktree))
74741
+ return [];
74742
+ const real = realpathSync(worktree);
74743
+ if (!real || real === "/")
74744
+ return [];
74745
+ const hit = procCache.get(worktree);
74746
+ if (hit && Date.now() - hit.at < 5000)
74747
+ return hit.list;
74748
+ const pids = [];
74749
+ try {
74750
+ const out = execFileSync3("lsof", ["-d", "cwd", "-Fpn"], {
74751
+ encoding: "utf8",
74752
+ timeout: 5000,
74753
+ maxBuffer: 33554432
74754
+ });
74755
+ let pid = 0;
74756
+ for (const line of out.split(`
74757
+ `)) {
74758
+ if (line.startsWith("p"))
74759
+ pid = Number(line.slice(1));
74760
+ else if (line.startsWith("n") && `${line.slice(1)}/`.startsWith(`${real}/`) && pid !== process.pid)
74761
+ pids.push(pid);
74762
+ }
74763
+ } catch {}
74764
+ const list = [];
74765
+ for (const pid of [...new Set(pids)]) {
74766
+ try {
74767
+ const [rss, ...cmd] = execFileSync3("ps", ["-o", "rss=,command=", "-p", String(pid)], {
74768
+ encoding: "utf8"
74769
+ }).trim().split(/\s+/);
74770
+ list.push({
74771
+ pid,
74772
+ rssMb: Math.round(Number(rss) / 1024),
74773
+ command: cmd.join(" ").slice(0, 160)
74774
+ });
74775
+ } catch {}
74776
+ }
74777
+ procCache.set(worktree, { at: Date.now(), list });
74778
+ return list;
74779
+ }
74780
+ function stopTask(planDir, id) {
74781
+ const dir = taskDir(planDir, id);
74782
+ const file = join43(dir, "task.json");
74783
+ if (!existsSync32(file))
74784
+ throw new Error("no such task");
74785
+ const task = JSON.parse(readFileSync36(file, "utf8"));
74786
+ let stopped = 0;
74787
+ if (task.pid && alive(task.pid) && !existsSync32(join43(dir, "exit"))) {
74788
+ try {
74789
+ process.kill(-task.pid, "SIGTERM");
74790
+ stopped += 1;
74791
+ } catch {}
74792
+ writeFileSync33(join43(dir, "stopped"), new Date().toISOString());
74793
+ writeFileSync33(join43(dir, "exit"), `143
74794
+ `);
74795
+ }
74796
+ procCache.delete(task.worktree ?? "");
74797
+ for (const p of taskProcesses(task.worktree)) {
74798
+ try {
74799
+ process.kill(p.pid, "SIGTERM");
74800
+ stopped += 1;
74801
+ } catch {}
74802
+ }
74803
+ procCache.delete(task.worktree ?? "");
74804
+ return { stopped };
74805
+ }
74806
+ function alive(pid) {
74807
+ if (!pid)
74808
+ return false;
74809
+ try {
74810
+ process.kill(pid, 0);
74811
+ return true;
74812
+ } catch {
74813
+ return false;
74814
+ }
74815
+ }
74816
+ var SECRET = /(sk-[\w-]{20,}|gh[pousr]_[\w]{20,}|xox[bap]-[\w-]{10,}|Bearer\s+[\w.-]{16,}|eyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,})/g;
74817
+ var redact = (s) => s.replace(SECRET, "[redacted]");
74818
+ var clip = (s, n = 400) => {
74819
+ const r = redact(s);
74820
+ return r.length > n ? `${r.slice(0, n)}…` : r;
74821
+ };
74822
+ function agentText(jsonl) {
74823
+ const out = [];
74824
+ for (const l of jsonl.split(`
74825
+ `)) {
74826
+ try {
74827
+ const m = JSON.parse(l);
74828
+ if (m?.type === "assistant" || m?.message?.role === "assistant")
74829
+ out.push(textOf(m.message?.content));
74830
+ } catch {}
74831
+ }
74832
+ return out.join(`
74833
+ `);
74834
+ }
74835
+ function toolSummary(name, input) {
74836
+ const pick = input.command ?? input.file_path ?? input.pattern ?? input.description ?? input.url ?? input.skill;
74837
+ return `${name}${pick ? ` · ${String(pick)}` : ""}`;
74838
+ }
74839
+ function textOf(content) {
74840
+ if (typeof content === "string")
74841
+ return content;
74842
+ if (Array.isArray(content))
74843
+ return content.map((c) => c?.type === "text" ? c.text : "").join(`
74844
+ `);
74845
+ return "";
74846
+ }
74847
+ function prPlan(planDir, id, baseOverride) {
74848
+ const d = readTask(planDir, id);
74849
+ if (!d)
74850
+ throw new Error("no such task");
74851
+ const task = d.task;
74852
+ const branch = d.delivery?.branch;
74853
+ if (!branch || !task.worktree || !existsSync32(task.worktree))
74854
+ throw new Error("this task has no local branch to push");
74855
+ const eff = effectiveSettings(planDir, targetDir(planDir));
74856
+ const settings = { prBase: eff.prBase, githubUser: eff.githubUser };
74857
+ const detected = eff.detectedAt ? eff : null;
74858
+ const base = baseOverride ?? settings.prBase;
74859
+ if (!base)
74860
+ throw new Error("no PR base configured — set it in the migration settings");
74861
+ const repo = remoteRepo(task.worktree);
74862
+ const cut = task.base?.sha ?? null;
74863
+ const git = (...a) => {
74864
+ try {
74865
+ return execFileSync3("git", ["-C", task.worktree, ...a], {
74866
+ encoding: "utf8",
74867
+ timeout: 1e4
74868
+ }).trim();
74869
+ } catch {
74870
+ return "";
74871
+ }
74872
+ };
74873
+ const commits = git("log", "--format=%h %s", cut ? `${cut}..${branch}` : "-1", ...cut ? [] : [branch]).split(`
74874
+ `).filter(Boolean);
74875
+ return {
74876
+ repo,
74877
+ base,
74878
+ branch,
74879
+ account: settings.githubUser ?? null,
74880
+ fromDetection: Boolean(detected),
74881
+ cutFrom: task.base?.ref ?? null,
74882
+ rebase: Boolean(cut && task.base?.ref !== `origin/${base}`),
74883
+ commits,
74884
+ status: d.status,
74885
+ existing: d.delivery?.prUrl ?? null
74886
+ };
74887
+ }
74888
+ function openPr(planDir, id, baseOverride) {
74889
+ const plan = prPlan(planDir, id, baseOverride);
74890
+ if (plan.existing)
74891
+ return { url: plan.existing, created: false };
74892
+ if (plan.status !== "done")
74893
+ throw new Error(`the task is ${plan.status} — only a done task opens a PR`);
74894
+ if (!plan.commits.length)
74895
+ throw new Error("the branch has no commits of its own");
74896
+ const dir = taskDir(planDir, id);
74897
+ const task = JSON.parse(readFileSync36(join43(dir, "task.json"), "utf8"));
74898
+ const wt = task.worktree;
74899
+ const env = { ...process.env, ...ghEnv(plan.account ?? undefined) };
74900
+ const git = (...a) => execFileSync3("git", ["-C", wt, ...a], { encoding: "utf8", timeout: 120000, env }).trim();
74901
+ git("fetch", "origin", plan.base);
74902
+ if (task.base?.sha && plan.rebase) {
74903
+ try {
74904
+ git("rebase", "--onto", `origin/${plan.base}`, task.base.sha, plan.branch);
74905
+ } catch (err) {
74906
+ try {
74907
+ git("rebase", "--abort");
74908
+ } catch {}
74909
+ throw new Error(`the task's commits conflict with origin/${plan.base} — resolve by hand; nothing was pushed (${err.message.split(`
74910
+ `)[0]})`);
74911
+ }
74912
+ }
74913
+ git("push", "-u", "origin", plan.branch);
74914
+ const d = readTask(planDir, id);
74915
+ const summary = d?.result?.text.match(/"summary":\s*"([^"]+)"/)?.[1] ?? "";
74916
+ const title = plan.commits.length === 1 ? plan.commits[0].replace(/^\w+ /, "") : plan.commits.at(-1)?.replace(/^\w+ /, "") ?? task.text.slice(0, 70);
74917
+ const body = [
74918
+ "## What",
74919
+ summary || "(see commits)",
74920
+ "",
74921
+ "## Why",
74922
+ `Reviewer note from the parity cockpit (verbatim): ${JSON.stringify(task.text)}`,
74923
+ `Page \`${task.page}\` · ${task.device}${task.context?.[task.side]?.viewport ? ` · ${task.context[task.side]?.viewport.width}×${task.context[task.side]?.viewport.height}` : ""}`,
74924
+ "",
74925
+ "## Verified",
74926
+ `QA: ${d?.agents.filter((a) => a.type === "qa").pop()?.result ? "approved" : "see task"} — parity cockpit task \`${id}\`.`,
74927
+ "",
74928
+ "## Commits",
74929
+ ...plan.commits.map((c) => `- ${c}`)
74930
+ ].join(`
74931
+ `);
74932
+ const bodyFile = join43(dir, "pr-body.md");
74933
+ writeFileSync33(bodyFile, body);
74934
+ const out = execFileSync3("gh", [
74935
+ "pr",
74936
+ "create",
74937
+ "--repo",
74938
+ plan.repo ?? "",
74939
+ "--base",
74940
+ plan.base,
74941
+ "--head",
74942
+ plan.branch,
74943
+ "--title",
74944
+ title,
74945
+ "--body-file",
74946
+ bodyFile
74947
+ ], { encoding: "utf8", timeout: 60000, env, cwd: wt }).trim();
74948
+ const url = out.split(`
74949
+ `).find((l) => l.startsWith("https://")) ?? out;
74950
+ writeFileSync33(join43(dir, "pr.json"), JSON.stringify({ checkedAt: Date.now(), url }));
74951
+ return { url, created: true };
74952
+ }
74953
+ function autoOpenPrs(planDir) {
74954
+ for (const t of listTasks(planDir)) {
74955
+ if (t.status !== "done" || t.prUrl)
74956
+ continue;
74957
+ const mark = join43(taskDir(planDir, t.id), "pr-auto.json");
74958
+ if (existsSync32(mark))
74959
+ continue;
74960
+ const at = new Date().toISOString();
74961
+ try {
74962
+ const r = openPr(planDir, t.id);
74963
+ writeFileSync33(mark, JSON.stringify({ at, ok: true, url: r.url }));
74964
+ } catch (err) {
74965
+ writeFileSync33(mark, JSON.stringify({ at, ok: false, error: err.message.split(`
74966
+ `)[0] }));
74967
+ }
74968
+ }
74969
+ }
74970
+ function foldChecks(rollup) {
74971
+ const out = {
74972
+ total: 0,
74973
+ passed: 0,
74974
+ failed: 0,
74975
+ pending: 0,
74976
+ failing: [],
74977
+ waiting: []
74978
+ };
74979
+ for (const c of rollup) {
74980
+ const name = c.name ?? c.context ?? "check";
74981
+ out.total += 1;
74982
+ const verdict = (c.conclusion || c.state || "").toUpperCase();
74983
+ const done = c.status ? c.status.toUpperCase() === "COMPLETED" : verdict !== "PENDING" && verdict !== "EXPECTED";
74984
+ if (!done) {
74985
+ out.pending += 1;
74986
+ out.waiting.push(name);
74987
+ } else if (["SUCCESS", "SKIPPED", "NEUTRAL"].includes(verdict))
74988
+ out.passed += 1;
74989
+ else {
74990
+ out.failed += 1;
74991
+ out.failing.push(name);
74992
+ }
74993
+ }
74994
+ return out;
74995
+ }
74996
+ function parseListOr(raw) {
74997
+ try {
74998
+ const v = JSON.parse(raw);
74999
+ return Array.isArray(v) ? v : [];
75000
+ } catch {
75001
+ return [];
75002
+ }
75003
+ }
75004
+ function failingSpecsFromLog(log) {
75005
+ const clean = log.replace(/\x1b\[[0-9;]*m/g, "").replace(/\^\[\[[0-9;]*m/g, "");
75006
+ const specs = new Set;
75007
+ for (const m of clean.matchAll(/(?:✖|✗|×|FAIL)\s+([\w./-]+\.(?:cy|test|spec)\.[jt]sx?)/g))
75008
+ specs.add(m[1]);
75009
+ return specs.size ? [...specs].sort() : null;
75010
+ }
75011
+ function baselineWaiver(repo, prNumber, base, check, env) {
75012
+ const gh = (...a) => {
75013
+ try {
75014
+ return execFileSync3("gh", a, {
75015
+ encoding: "utf8",
75016
+ timeout: 60000,
75017
+ env,
75018
+ stdio: ["ignore", "pipe", "ignore"]
75019
+ });
75020
+ } catch {
75021
+ return "";
75022
+ }
75023
+ };
75024
+ const runOf = (n) => {
75025
+ const rows = parseListOr(gh("pr", "checks", String(n), "--repo", repo, "--json", "name,state,link") || "[]");
75026
+ const row = rows.find((r) => r.name === check);
75027
+ return row ? { state: row.state, run: row.link.match(/runs\/(\d+)/)?.[1] ?? null } : null;
75028
+ };
75029
+ const merged = parseListOr(gh("pr", "list", "--repo", repo, "--base", base, "--state", "merged", "--limit", "8", "--json", "number,headRefName") || "[]").filter((p) => !/^(release|hotfix)\//.test(p.headRefName) && p.headRefName !== "main").slice(0, 5);
75030
+ const base5 = merged.map((p) => ({ n: p.number, r: runOf(p.number) }));
75031
+ const redOnBase = base5.filter((b) => b.r && b.r.state === "FAILURE");
75032
+ if (redOnBase.length < 3)
75033
+ return {
75034
+ waived: false,
75035
+ why: `${check} failed on ${redOnBase.length}/${base5.length} recent PRs into ${base} — not a known-broken check`
75036
+ };
75037
+ const specsOf = (run) => run ? failingSpecsFromLog(gh("run", "view", run, "--repo", repo, "--log-failed")) : null;
75038
+ const ours = specsOf(runOf(prNumber)?.run);
75039
+ const theirs = specsOf(redOnBase[0]?.r?.run);
75040
+ if (!ours || !theirs)
75041
+ return { waived: false, why: `${check}: could not read the failing specs on both sides` };
75042
+ const extra = ours.filter((x) => !theirs.includes(x));
75043
+ if (extra.length)
75044
+ return { waived: false, why: `${check}: new failures not on ${base}: ${extra.join(", ")}` };
75045
+ return {
75046
+ waived: true,
75047
+ why: `${check} also fails on ${redOnBase.length}/${base5.length} recent PRs into ${base} (${redOnBase.map((b) => `#${b.n}`).join(", ")}), with the same failing specs as #${redOnBase[0]?.n}: ${ours.join(", ")}`
75048
+ };
75049
+ }
75050
+ function autoMergePrs(planDir) {
75051
+ for (const t of listTasks(planDir)) {
75052
+ if (t.status !== "done")
75053
+ continue;
75054
+ const dir = taskDir(planDir, t.id);
75055
+ if (existsSync32(join43(dir, "pr-merge.json")))
75056
+ continue;
75057
+ const d = readTask(planDir, t.id);
75058
+ const branch = d?.delivery?.branch;
75059
+ const wt = d?.task.worktree;
75060
+ if (!d || !branch || !wt || !existsSync32(wt))
75061
+ continue;
75062
+ const pr = prInfo(branch, wt, dir, true, true);
75063
+ if (!pr || pr.state !== "OPEN")
75064
+ continue;
75065
+ const at = new Date().toISOString();
75066
+ const s = effectiveSettings(planDir, targetDir(planDir));
75067
+ const env = { ...process.env, ...ghEnv(s.githubUser) };
75068
+ const waivers = pr.checks.pending === 0 && pr.checks.failed > 0 && s.prBase ? pr.checks.failing.map((c) => ({
75069
+ check: c,
75070
+ ...baselineWaiver(remoteRepo(wt) ?? "", pr.number, s.prBase, c, env)
75071
+ })) : [];
75072
+ const allWaived = waivers.length > 0 && waivers.every((w) => w.waived);
75073
+ if (pr.checks.total > 0 && pr.checks.pending === 0 && (pr.checks.failed === 0 || allWaived)) {
75074
+ try {
75075
+ if (allWaived) {
75076
+ const body = [
75077
+ "Merging with a failing check that is already failing on the base branch — not introduced by this PR:",
75078
+ ...waivers.map((w) => `- ${w.why}`)
75079
+ ].join(`
75080
+ `);
75081
+ execFileSync3("gh", ["pr", "comment", String(pr.number), "--body", body], {
75082
+ cwd: wt,
75083
+ encoding: "utf8",
75084
+ timeout: 60000,
75085
+ env
75086
+ });
75087
+ }
75088
+ execFileSync3("gh", ["pr", "merge", String(pr.number), `--${s.mergeMethod ?? "merge"}`], {
75089
+ cwd: wt,
75090
+ encoding: "utf8",
75091
+ timeout: 60000,
75092
+ env
75093
+ });
75094
+ writeFileSync33(join43(dir, "pr-merge.json"), JSON.stringify({ at, ok: true, number: pr.number, waived: waivers }));
75095
+ } catch (err) {
75096
+ writeFileSync33(join43(dir, "pr-merge.json"), JSON.stringify({ at, ok: false, error: err.message.split(`
75097
+ `)[0] }));
75098
+ }
75099
+ rmSync(join43(dir, "pr.json"), { force: true });
75100
+ } else if (pr.checks.failed > 0 && !existsSync32(join43(dir, "ci-retry.json"))) {
75101
+ writeFileSync33(join43(dir, "ci-retry.json"), JSON.stringify({ at, failing: pr.checks.failing }));
75102
+ retryTask(planDir, t.id, `CI failed on PR #${pr.number}: ${pr.checks.failing.join(", ")}.${waivers.length ? ` Not waivable: ${waivers.filter((w) => !w.waived).map((w) => w.why).join("; ")}.` : ""} Read the failing job logs, fix on the same branch, push, wait for every check, then merge.`);
75103
+ }
75104
+ }
75105
+ }
75106
+ function prInfo(branch, repo, dir, ended, fresh = false) {
75107
+ if (!ended)
75108
+ return null;
75109
+ const cache = join43(dir, "pr.json");
75110
+ try {
75111
+ const c = JSON.parse(readFileSync36(cache, "utf8"));
75112
+ if (!fresh && Date.now() - c.checkedAt < 60000)
75113
+ return c.info ?? (c.url ? { url: c.url } : null);
75114
+ } catch {}
75115
+ let info = null;
75116
+ try {
75117
+ const out = execFileSync3("gh", ["pr", "view", branch, "--json", "url,number,state,mergeable,statusCheckRollup"], {
75118
+ cwd: repo,
75119
+ encoding: "utf8",
75120
+ timeout: 1e4,
75121
+ stdio: ["ignore", "pipe", "ignore"],
75122
+ env: { ...process.env, ...ghEnv(getSettings(dirname7(dirname7(dir))).githubUser) }
75123
+ });
75124
+ const j = JSON.parse(out);
75125
+ info = {
75126
+ url: j.url,
75127
+ number: j.number,
75128
+ state: j.state,
75129
+ mergeable: j.mergeable,
75130
+ checks: foldChecks(j.statusCheckRollup ?? [])
75131
+ };
75132
+ } catch {
75133
+ info = null;
75134
+ }
75135
+ writeFileSync33(cache, JSON.stringify({ checkedAt: Date.now(), url: info?.url ?? null, info }));
75136
+ return info;
75137
+ }
75138
+ function readTask(planDir, id) {
75139
+ const dir = taskDir(planDir, id);
75140
+ const file = join43(dir, "task.json");
75141
+ if (!existsSync32(file))
75142
+ return null;
75143
+ const task = JSON.parse(readFileSync36(file, "utf8"));
75144
+ const streamFile = join43(dir, "stream.jsonl");
75145
+ const exitFile = join43(dir, "exit");
75146
+ const steps = [];
75147
+ const agents = new Map;
75148
+ let result = null;
75149
+ let model;
75150
+ let attempt = 1;
75151
+ let lastTs;
75152
+ let rawResult = "";
75153
+ const actorOf = (parent) => parent && agents.get(parent)?.type || "orchestrator";
75154
+ const lines = existsSync32(streamFile) ? readFileSync36(streamFile, "utf8").split(`
75155
+ `) : [];
75156
+ for (const line of lines) {
75157
+ if (!line.trim())
75158
+ continue;
75159
+ let m;
75160
+ try {
75161
+ m = JSON.parse(line);
75162
+ } catch {
75163
+ continue;
75164
+ }
75165
+ const actor = actorOf(m.parent_tool_use_id);
75166
+ if (typeof m.timestamp === "string")
75167
+ lastTs = m.timestamp;
75168
+ if (m.type === "system" && m.subtype === "init")
75169
+ model = m.model ?? model;
75170
+ if (m.type === "parity" && m.subtype === "attempt") {
75171
+ attempt = Number(m.n) || attempt + 1;
75172
+ steps.push({ actor: "orchestrator", kind: "text", text: `── attempt ${attempt} ──` });
75173
+ }
75174
+ const resolved = m.tool_use_result?.resolvedModel;
75175
+ if (resolved) {
75176
+ for (const c of m.message?.content ?? []) {
75177
+ const a = c?.tool_use_id ? agents.get(c.tool_use_id) : undefined;
75178
+ if (a)
75179
+ a.model = resolved;
75180
+ }
75181
+ }
75182
+ if (m.type === "assistant") {
75183
+ for (const c of m.message?.content ?? []) {
75184
+ if (c.type === "text" && c.text.trim())
75185
+ steps.push({
75186
+ actor,
75187
+ agent: m.parent_tool_use_id ?? undefined,
75188
+ kind: "text",
75189
+ text: clip(c.text, 1200)
75190
+ });
75191
+ if (c.type === "tool_use") {
75192
+ if (c.name === "Agent" || c.name === "Task") {
75193
+ agents.set(c.id, {
75194
+ id: c.id,
75195
+ type: String(c.input?.subagent_type ?? "agent").replace(/^parity:/, ""),
75196
+ description: String(c.input?.description ?? ""),
75197
+ startedAt: m.timestamp ?? lastTs,
75198
+ prompt: clip(String(c.input?.prompt ?? ""), 8000),
75199
+ status: "running",
75200
+ attempt
75201
+ });
75202
+ }
75203
+ steps.push({
75204
+ actor,
75205
+ agent: m.parent_tool_use_id ?? undefined,
75206
+ kind: "tool",
75207
+ text: clip(toolSummary(c.name, c.input ?? {}), 240)
75208
+ });
75209
+ }
75210
+ }
75211
+ } else if (m.type === "user") {
75212
+ for (const c of m.message?.content ?? []) {
75213
+ if (c.type !== "tool_result")
75214
+ continue;
75215
+ const agent = agents.get(c.tool_use_id);
75216
+ if (agent && /Async agent launched|agentId:/i.test(textOf(c.content)))
75217
+ continue;
75218
+ if (agent) {
75219
+ const out = textOf(c.content);
75220
+ const line = out.split(`
75221
+ `).reverse().find((l) => l.startsWith("PARITY_RESULT:"));
75222
+ if (line) {
75223
+ try {
75224
+ agent.result = JSON.parse(line.slice("PARITY_RESULT:".length));
75225
+ } catch {
75226
+ agent.result = { unparseable: clip(line, 200) };
75227
+ }
75228
+ }
75229
+ agent.summary = clip(out, 4000);
75230
+ agent.endedAt = m.timestamp ?? lastTs ?? agent.endedAt;
75231
+ agent.status = c.is_error || !line ? "failed" : "done";
75232
+ }
75233
+ if (c.is_error)
75234
+ steps.push({
75235
+ actor,
75236
+ agent: m.parent_tool_use_id ?? undefined,
75237
+ kind: "tool",
75238
+ text: clip(textOf(c.content), 300),
75239
+ isError: true
75240
+ });
75241
+ }
75242
+ }
75243
+ if (m.type === "system" && m.subtype === "task_notification") {
75244
+ const agent = agents.get(m.tool_use_id);
75245
+ if (agent) {
75246
+ const scan = (t) => [...t.matchAll(/PARITY_RESULT:\s*(\{[^\n]*\})/g)].pop()?.[1];
75247
+ let res = scan(String(m.summary ?? ""));
75248
+ if (!res && typeof m.output_file === "string" && existsSync32(m.output_file)) {
75249
+ res = scan(agentText(readFileSync36(m.output_file, "utf8")));
75250
+ }
75251
+ if (res) {
75252
+ try {
75253
+ agent.result = JSON.parse(res);
75254
+ } catch {
75255
+ agent.result = { unparseable: clip(res, 200) };
75256
+ }
75257
+ }
75258
+ agent.summary = clip(String(m.summary ?? ""), 4000);
75259
+ agent.endedAt = m.timestamp ?? lastTs ?? agent.endedAt;
75260
+ agent.status = m.status === "completed" && res ? "done" : "failed";
75261
+ }
75262
+ }
75263
+ if (m.type === "result") {
75264
+ rawResult = String(m.result ?? "");
75265
+ result = {
75266
+ ok: !m.is_error && m.subtype === "success",
75267
+ text: clip(rawResult, 8000),
75268
+ costUsd: m.total_cost_usd,
75269
+ durationMs: m.duration_ms
75270
+ };
75271
+ steps.push({ actor: "orchestrator", kind: "result", text: result.text, isError: !result.ok });
75272
+ }
75273
+ }
75274
+ const exit = existsSync32(exitFile) ? Number(readFileSync36(exitFile, "utf8").trim()) : null;
75275
+ const stderrRaw = existsSync32(join43(dir, "stderr.log")) ? readFileSync36(join43(dir, "stderr.log"), "utf8") : "";
75276
+ const finalLine = [...rawResult.matchAll(/PARITY_RESULT:\s*(\{[^\n]*\})/g)].pop()?.[1];
75277
+ let verdict = null;
75278
+ try {
75279
+ verdict = finalLine ? JSON.parse(finalLine) : null;
75280
+ } catch {
75281
+ verdict = null;
75282
+ }
75283
+ const unfinished = [...agents.values()].filter((a) => (a.attempt ?? 1) === attempt && a.status !== "done").map((a) => a.type);
75284
+ let reason;
75285
+ let status;
75286
+ if (exit !== null) {
75287
+ if (existsSync32(join43(dir, "stopped"))) {
75288
+ reason = "stopped from the cockpit";
75289
+ } else if (/Background tasks still running .* terminating/.test(stderrRaw)) {
75290
+ reason = `claude stopped waiting for background agents (${unfinished.join(", ") || "?"}) and terminated them`;
75291
+ } else if (!verdict)
75292
+ reason = "the run ended without a final PARITY_RESULT";
75293
+ else if (verdict.ok !== true)
75294
+ reason = verdict.summary ?? "the orchestrator reported ok: false";
75295
+ else if (unfinished.length)
75296
+ reason = `agents did not finish: ${unfinished.join(", ")}`;
75297
+ status = !reason && exit === 0 ? "done" : "failed";
75298
+ } else if (task.worktreeError) {
75299
+ status = "failed";
75300
+ reason = `could not create the run's worktree: ${task.worktreeError}`;
75301
+ } else if (!task.pid)
75302
+ status = "capturing";
75303
+ else if (!alive(task.pid))
75304
+ status = "failed";
75305
+ else {
75306
+ const last = existsSync32(streamFile) ? statSync3(streamFile).mtimeMs : Date.parse(task.createdAt);
75307
+ status = Date.now() - last > STALL_MS ? "stalled" : "running";
75308
+ }
75309
+ const read = (f) => existsSync32(join43(dir, f)) ? readFileSync36(join43(dir, f), "utf8") : null;
75310
+ const stderr = clip(stderrRaw, 1500);
75311
+ const fixer = [...agents.values()].reverse().find((a) => a.type === "fixer" && a.result);
75312
+ const fr = fixer?.result ?? {};
75313
+ const branch = verdict?.branch ?? fr.branch ?? null;
75314
+ let delivery = null;
75315
+ if (branch) {
75316
+ const repo = task.worktree && existsSync32(task.worktree) ? task.worktree : targetDir(dirname7(dirname7(dir)));
75317
+ const baseSha = task.base?.sha ?? fr.base;
75318
+ const git = (...a) => {
75319
+ try {
75320
+ return execFileSync3("git", ["-C", repo, ...a], { encoding: "utf8", timeout: 3000 }).trim();
75321
+ } catch {
75322
+ return "";
75323
+ }
75324
+ };
75325
+ const pr = prInfo(branch, repo, dir, exit !== null);
75326
+ delivery = {
75327
+ branch,
75328
+ base: task.base?.ref ?? fr.base,
75329
+ repo,
75330
+ commits: git("log", "--format=%h %s", baseSha ? `${baseSha}..${branch}` : "-1", ...baseSha ? [] : [branch]).split(`
75331
+ `).filter(Boolean),
75332
+ diffStat: git("diff", "--shortstat", baseSha ? `${baseSha}...${branch}` : `${branch}~1..${branch}`),
75333
+ files: fr.files_changed ?? [],
75334
+ prUrl: verdict?.pr_url ?? fr.pr_url ?? pr?.url ?? null,
75335
+ pr
75336
+ };
75337
+ }
75338
+ return {
75339
+ task,
75340
+ status,
75341
+ attempt,
75342
+ reason,
75343
+ delivery,
75344
+ model,
75345
+ prError: (() => {
75346
+ try {
75347
+ const m = JSON.parse(readFileSync36(join43(dir, "pr-auto.json"), "utf8"));
75348
+ return m.ok ? null : String(m.error);
75349
+ } catch {
75350
+ return null;
75351
+ }
75352
+ })(),
75353
+ processes: taskProcesses(task.worktree),
75354
+ exit,
75355
+ steps,
75356
+ agents: [...agents.values()],
75357
+ result,
75358
+ stderr: stderr || undefined,
75359
+ prompt: read("prompt.md"),
75360
+ brief: read("brief.md"),
75361
+ sizes: read("sizes.md"),
75362
+ context: read("context.json") ? JSON.parse(read("context.json")) : null
75363
+ };
75364
+ }
75365
+ function listTasks(planDir) {
75366
+ const dir = tasksDir(planDir);
75367
+ if (!existsSync32(dir))
75368
+ return [];
75369
+ return readdirSync9(dir).filter(validTaskId).sort().reverse().map((id) => readTask(planDir, id)).filter((t) => t !== null).map(({ task, status, agents, result, delivery }) => ({
75370
+ ...task,
75371
+ status,
75372
+ agents: agents.length,
75373
+ result,
75374
+ prUrl: delivery?.prUrl ?? null,
75375
+ prState: delivery?.pr?.state ?? null
75376
+ }));
75377
+ }
75378
+ function taskShot(planDir, id, side) {
75379
+ if (!validTaskId(id) || side !== "prod" && side !== "cand")
75380
+ return null;
75381
+ const file = join43(taskDir(planDir, id), `${side}.png`);
75382
+ return existsSync32(file) ? readFileSync36(file) : null;
75383
+ }
75384
+
75385
+ // src/server/cockpit.ts
75386
+ async function startCockpit(ctx, opts = {}) {
75387
+ const server = createServer2((req, res) => {
75388
+ handle(req, res, ctx).catch((err) => {
75389
+ try {
75390
+ res.statusCode = 500;
75391
+ res.setHeader("content-type", "application/json");
75392
+ res.end(JSON.stringify({ error: err.message }));
75393
+ } catch {}
75394
+ });
75395
+ });
75396
+ const sweep = () => {
75397
+ try {
75398
+ autoOpenPrs(ctx.planDir);
75399
+ autoMergePrs(ctx.planDir);
75400
+ } catch {}
75401
+ };
75402
+ const tick = setInterval(sweep, 30000);
75403
+ tick.unref();
75404
+ setTimeout(sweep, 5000).unref();
75405
+ await new Promise((ready, reject) => {
75406
+ server.once("error", reject);
75407
+ server.listen(opts.port ?? 0, opts.host ?? "127.0.0.1", () => ready());
75408
+ });
75409
+ const addr = server.address();
75410
+ const port = typeof addr === "object" && addr ? addr.port : 0;
75411
+ const host = opts.host ?? "127.0.0.1";
75412
+ return {
75413
+ port,
75414
+ url: `http://${host}:${port}/`,
75415
+ close: () => new Promise((done) => {
75416
+ try {
75417
+ server.closeAllConnections?.();
75418
+ server.closeIdleConnections?.();
75419
+ } catch {}
75420
+ clearInterval(tick);
75421
+ server.close(() => done());
75422
+ setTimeout(() => done(), 1000);
75423
+ })
75424
+ };
75425
+ }
75426
+ async function handle(req, res, ctx) {
75427
+ const url = new URL(req.url ?? "/", "http://placeholder");
75428
+ const path = decodeURIComponent(url.pathname);
75429
+ if (path.startsWith("/api/tasks"))
75430
+ return tasks(req, res, path, ctx);
75431
+ if (path === "/api/overview" || path === "/api/settings" || path.startsWith("/api/plan/") || path === "/api/reindex" || path.startsWith("/api/jobs/")) {
75432
+ return actions(req, res, path, ctx);
75433
+ }
75434
+ const api = cockpitApi(path, url.searchParams, ctx);
75435
+ if (api) {
75436
+ res.statusCode = api.status;
75437
+ res.setHeader("content-type", "application/json; charset=utf-8");
75438
+ res.setHeader("cache-control", "no-store");
75439
+ res.end(JSON.stringify(api.body));
75440
+ return;
75441
+ }
75442
+ if (path === "/proxy") {
75443
+ const target = url.searchParams.get("url");
75444
+ if (!target) {
75445
+ res.statusCode = 400;
75446
+ res.end("missing ?url=");
75447
+ return;
75448
+ }
75449
+ return proxyRequest(req, res, target, {
75450
+ forceMobile: url.searchParams.get("viewport") === "mobile"
75451
+ });
75452
+ }
75453
+ if (path === "/" || path === "/index.html") {
75454
+ res.statusCode = 200;
75455
+ res.setHeader("content-type", "text/html; charset=utf-8");
75456
+ res.setHeader("cache-control", "no-store");
75457
+ res.end(COCKPIT_HTML);
75458
+ return;
75459
+ }
75460
+ res.statusCode = 404;
75461
+ res.setHeader("content-type", "application/json");
75462
+ res.end(JSON.stringify({ error: `no route ${path}` }));
75463
+ }
75464
+ function json(res, status, body) {
75465
+ res.statusCode = status;
75466
+ res.setHeader("content-type", "application/json; charset=utf-8");
75467
+ res.setHeader("cache-control", "no-store");
75468
+ res.end(JSON.stringify(body));
75469
+ }
75470
+ async function tasks(req, res, path, ctx) {
75471
+ const retry = path.match(/^\/api\/tasks\/([\w-]+)\/retry$/);
75472
+ const stop = path.match(/^\/api\/tasks\/([\w-]+)\/stop$/);
75473
+ const pr = path.match(/^\/api\/tasks\/([\w-]+)\/pr$/);
75474
+ if (pr) {
75475
+ if (!validTaskId(pr[1]))
75476
+ return json(res, 400, { error: "bad task id" });
75477
+ if (req.method === "GET") {
75478
+ try {
75479
+ return json(res, 200, prPlan(ctx.planDir, pr[1]));
75480
+ } catch (err) {
75481
+ return json(res, 409, { error: err.message });
75482
+ }
75483
+ }
75484
+ const body = await jsonBody(req, res);
75485
+ if (!body)
75486
+ return;
75487
+ if (body.confirm !== true)
75488
+ return json(res, 400, { error: "confirm: true is required" });
75489
+ try {
75490
+ const base = typeof body.base === "string" && body.base ? body.base : undefined;
75491
+ return json(res, 201, openPr(ctx.planDir, pr[1], base));
75492
+ } catch (err) {
75493
+ return json(res, 409, { error: err.message });
75494
+ }
75495
+ }
75496
+ if (stop && req.method === "POST") {
75497
+ const body = await jsonBody(req, res);
75498
+ if (!body)
75499
+ return;
75500
+ if (!validTaskId(stop[1]))
75501
+ return json(res, 400, { error: "bad task id" });
75502
+ try {
75503
+ return json(res, 200, stopTask(ctx.planDir, stop[1]));
75504
+ } catch (err) {
75505
+ return json(res, 404, { error: err.message });
75506
+ }
75507
+ }
75508
+ if ((path === "/api/tasks" || retry) && req.method === "POST") {
75509
+ const origin = req.headers.origin;
75510
+ if (origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) {
75511
+ return json(res, 403, { error: "cross-origin" });
75512
+ }
75513
+ if (!String(req.headers["content-type"] ?? "").includes("application/json")) {
75514
+ return json(res, 415, { error: "application/json only" });
75515
+ }
75516
+ let raw = "";
75517
+ for await (const c of req) {
75518
+ raw += c;
75519
+ if (raw.length > 64000)
75520
+ return json(res, 413, { error: "too large" });
75521
+ }
75522
+ if (retry) {
75523
+ if (!validTaskId(retry[1]))
75524
+ return json(res, 400, { error: "bad task id" });
75525
+ let body = {};
75526
+ try {
75527
+ body = raw ? JSON.parse(raw) : {};
75528
+ } catch {
75529
+ return json(res, 400, { error: "bad json" });
75530
+ }
75531
+ try {
75532
+ const note = typeof body.note === "string" && body.note.trim() ? body.note.trim() : undefined;
75533
+ return json(res, 202, retryTask(ctx.planDir, retry[1], note));
75534
+ } catch (err) {
75535
+ return json(res, 409, { error: err.message });
75536
+ }
75537
+ }
75538
+ let note;
75539
+ try {
75540
+ note = JSON.parse(raw);
75541
+ } catch {
75542
+ return json(res, 400, { error: "bad json" });
75543
+ }
75544
+ if (!note?.text?.trim() || !note.selector || !note.page || !note.prodUrl || !note.candUrl) {
75545
+ return json(res, 400, { error: "text, selector, page, prodUrl and candUrl are required" });
75546
+ }
75547
+ return json(res, 201, await createTask(ctx.planDir, note));
75548
+ }
75549
+ if (path === "/api/tasks")
75550
+ return json(res, 200, listTasks(ctx.planDir));
75551
+ const shot = path.match(/^\/api\/tasks\/([\w-]+)\/(prod|cand)\.png$/);
75552
+ if (shot) {
75553
+ const buf = taskShot(ctx.planDir, shot[1], shot[2]);
75554
+ if (!buf)
75555
+ return json(res, 404, { error: "no screenshot" });
75556
+ res.statusCode = 200;
75557
+ res.setHeader("content-type", "image/png");
75558
+ res.setHeader("cache-control", "no-store");
75559
+ res.end(buf);
75560
+ return;
75561
+ }
75562
+ const one = path.match(/^\/api\/tasks\/([\w-]+)$/);
75563
+ if (one && validTaskId(one[1])) {
75564
+ const t = readTask(ctx.planDir, one[1]);
75565
+ return t ? json(res, 200, t) : json(res, 404, { error: "no such task" });
75566
+ }
75567
+ return json(res, 404, { error: `no route ${path}` });
75568
+ }
75569
+ async function jsonBody(req, res) {
75570
+ const origin = req.headers.origin;
75571
+ if (origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)) {
75572
+ json(res, 403, { error: "cross-origin" });
75573
+ return null;
75574
+ }
75575
+ if (!String(req.headers["content-type"] ?? "").includes("application/json")) {
75576
+ json(res, 415, { error: "application/json only" });
75577
+ return null;
75578
+ }
75579
+ let raw = "";
75580
+ for await (const c of req) {
75581
+ raw += c;
75582
+ if (raw.length > 64000) {
75583
+ json(res, 413, { error: "too large" });
75584
+ return null;
75585
+ }
75586
+ }
75587
+ try {
75588
+ const v = raw ? JSON.parse(raw) : {};
75589
+ return v && typeof v === "object" ? v : {};
75590
+ } catch {
75591
+ json(res, 400, { error: "bad json" });
75592
+ return null;
75593
+ }
75594
+ }
75595
+ async function actions(req, res, path, ctx) {
75596
+ if (path === "/api/settings") {
75597
+ const repoDir = targetDirOf(ctx.planDir);
75598
+ if (req.method === "GET") {
75599
+ return json(res, 200, {
75600
+ current: getSettings(ctx.planDir),
75601
+ detected: detectSettings(repoDir)
75602
+ });
75603
+ }
75604
+ const body = await jsonBody(req, res);
75605
+ if (!body)
75606
+ return;
75607
+ const str = (v) => typeof v === "string" && v.trim() ? v.trim() : undefined;
75608
+ try {
75609
+ return json(res, 200, saveSettings(ctx.planDir, {
75610
+ githubUser: str(body.githubUser),
75611
+ prBase: str(body.prBase),
75612
+ cutFrom: str(body.cutFrom)
75613
+ }));
75614
+ } catch (err) {
75615
+ return json(res, 400, { error: err.message });
75616
+ }
75617
+ }
75618
+ if (path === "/api/overview" && req.method === "GET") {
75619
+ const o = migrationOverview(ctx.planDir);
75620
+ return o ? json(res, 200, o) : json(res, 404, { error: "no migration.json or plan in this dir" });
75621
+ }
75622
+ if (path === "/api/jobs/reindex" && req.method === "GET")
75623
+ return json(res, 200, lastJob(ctx.planDir, "reindex"));
75624
+ const q = new URL(req.url ?? "/", "http://x").searchParams;
75625
+ if (path === "/api/plan/component" && req.method === "GET") {
75626
+ const c = componentDetail(ctx.planDir, q.get("name") ?? "");
75627
+ return c ? json(res, 200, c) : json(res, 404, { error: `no component "${q.get("name")}"` });
75628
+ }
75629
+ if (path === "/api/plan/component/shot" && req.method === "GET") {
75630
+ const buf = componentShot(ctx.planDir, q.get("name") ?? "");
75631
+ if (!buf)
75632
+ return json(res, 404, { error: "no captured screenshot" });
75633
+ res.statusCode = 200;
75634
+ res.setHeader("content-type", "image/png");
75635
+ res.setHeader("cache-control", "no-store");
75636
+ res.end(buf);
75637
+ return;
75638
+ }
75639
+ if (req.method !== "POST")
75640
+ return json(res, 405, { error: "POST only" });
75641
+ const body = await jsonBody(req, res);
75642
+ if (!body)
75643
+ return;
75644
+ try {
75645
+ if (path === "/api/plan/component") {
75646
+ return json(res, 200, setComponent(ctx.planDir, String(body.name ?? ""), String(body.status ?? ""), {
75647
+ note: typeof body.note === "string" ? body.note : undefined,
75648
+ url: typeof body.url === "string" ? body.url : undefined,
75649
+ design: typeof body.design === "string" ? body.design : undefined
75650
+ }));
75651
+ }
75652
+ if (path === "/api/plan/component/selector") {
75653
+ return json(res, 200, setComponentSelector(ctx.planDir, String(body.name ?? ""), String(body.selector ?? "")));
75654
+ }
75655
+ if (path === "/api/plan/page") {
75656
+ return json(res, 200, setPage(ctx.planDir, String(body.path ?? ""), String(body.status ?? "")));
75657
+ }
75658
+ if (path === "/api/reindex")
75659
+ return json(res, 202, startReindex(ctx.planDir));
75660
+ } catch (err) {
75661
+ return json(res, 409, { error: err.message });
75662
+ }
75663
+ return json(res, 404, { error: `no route ${path}` });
75664
+ }
75665
+ function targetDirOf(planDir) {
75666
+ try {
75667
+ const st = JSON.parse(readFileSync37(join44(planDir, "migration.json"), "utf8"));
75668
+ if (typeof st?.target?.dir === "string")
75669
+ return st.target.dir;
75670
+ } catch {}
75671
+ return dirname8(resolve13(planDir));
75672
+ }
75673
+
75674
+ // src/commands/cockpit.ts
75675
+ async function cockpitCommand(opts) {
75676
+ const ctx = {
75677
+ planDir: resolve14(opts.dir),
75678
+ output: resolve14(opts.output),
75679
+ benchDir: resolve14(opts.benchDir),
75680
+ prodUrl: opts.prodUrl,
75681
+ candUrl: opts.candUrl
75682
+ };
75683
+ let handle;
75684
+ try {
75685
+ handle = await startCockpit(ctx, {
75686
+ port: opts.port ? Number.parseInt(opts.port, 10) : undefined,
75687
+ host: opts.host
75688
+ });
75689
+ } catch (err) {
75690
+ console.error(chalk30.red(` ✖ could not start the cockpit: ${err.message}`));
75691
+ return 2;
73848
75692
  }
73849
75693
  console.log("");
73850
- console.log(chalk29.bold(" parity cockpit"));
73851
- console.log(` ${chalk29.green("●")} ${handle.url}`);
73852
- console.log(chalk29.dim(` plan ${ctx.planDir}`));
73853
- console.log(chalk29.dim(` runs ${ctx.output}`));
73854
- console.log(chalk29.dim(` bench ${ctx.benchDir}`));
75694
+ console.log(chalk30.bold(" parity cockpit"));
75695
+ console.log(` ${chalk30.green("●")} ${handle.url}`);
75696
+ console.log(chalk30.dim(` plan ${ctx.planDir}`));
75697
+ console.log(chalk30.dim(` runs ${ctx.output}`));
75698
+ console.log(chalk30.dim(` bench ${ctx.benchDir}`));
73855
75699
  if (opts.host && opts.host !== "127.0.0.1" && opts.host !== "localhost") {
73856
- console.log(chalk29.yellow(` ⚠ bound to ${opts.host} — this server is unauthenticated, reads the repo, and proxies arbitrary URLs`));
75700
+ console.log(chalk30.yellow(` ⚠ bound to ${opts.host} — this server is unauthenticated, reads the repo, and proxies arbitrary URLs`));
73857
75701
  }
73858
- console.log(chalk29.dim(` Ctrl+C to stop.
75702
+ console.log(chalk30.dim(` Ctrl+C to stop.
73859
75703
  `));
73860
75704
  if (opts.open !== false) {
73861
75705
  const { default: openUrl } = await import("open");
@@ -73873,21 +75717,436 @@ async function cockpitCommand(opts) {
73873
75717
  return 0;
73874
75718
  }
73875
75719
 
75720
+ // src/commands/ios.ts
75721
+ import { execFileSync as execFileSync4 } from "node:child_process";
75722
+ import { existsSync as existsSync34, mkdirSync as mkdirSync23, readFileSync as readFileSync39, rmSync as rmSync2, writeFileSync as writeFileSync34 } from "node:fs";
75723
+ import { homedir as homedir5, tmpdir as tmpdir2 } from "node:os";
75724
+ import { join as join46, resolve as resolve15 } from "node:path";
75725
+ import chalk32 from "chalk";
75726
+
75727
+ // src/commands/pair.ts
75728
+ import { existsSync as existsSync33, readFileSync as readFileSync38 } from "node:fs";
75729
+ import { join as join45 } from "node:path";
75730
+ import chalk31 from "chalk";
75731
+
75732
+ // src/engine/pair.ts
75733
+ function signatureOf(target, doc = document) {
75734
+ const el = typeof target === "string" ? doc.querySelector(target) : target;
75735
+ if (!el)
75736
+ return null;
75737
+ const win = doc.defaultView;
75738
+ const HASHY = /[0-9a-f]{6,}|\d{4,}|^(css|sc|jsx|emotion)-/i;
75739
+ const nthPath = (n, stop) => {
75740
+ const parts = [];
75741
+ let node = n;
75742
+ while (node && node !== stop && node.tagName !== "BODY" && node.tagName !== "HTML") {
75743
+ const cur = node;
75744
+ const parent = cur.parentElement;
75745
+ const same = parent ? [...parent.children].filter((c) => c.tagName === cur.tagName) : [];
75746
+ const tag = cur.tagName.toLowerCase();
75747
+ parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(cur) + 1})` : tag);
75748
+ node = parent;
75749
+ }
75750
+ return parts.join(" > ");
75751
+ };
75752
+ const stableOf = (n) => {
75753
+ const tag = n.tagName.toLowerCase();
75754
+ const tries = [];
75755
+ if (n.id && /^[A-Za-z][\w-]*$/.test(n.id) && !HASHY.test(n.id))
75756
+ tries.push(`#${n.id}`);
75757
+ for (const a of n.attributes) {
75758
+ if (!a.name.startsWith("data-") || a.value.length > 40 || HASHY.test(a.value))
75759
+ continue;
75760
+ tries.push(a.value ? `${tag}[${a.name}="${a.value}"]` : `${tag}[${a.name}]`);
75761
+ }
75762
+ for (const c of n.classList) {
75763
+ const mod = c.match(/^([A-Z][A-Za-z0-9]+_[A-Za-z0-9_]+?__)[A-Za-z0-9_-]{5}$/);
75764
+ if (mod)
75765
+ tries.push(`${tag}[class*="${mod[1]}"]`);
75766
+ else if (!HASHY.test(c) && c.length < 80 && /^[A-Za-z][\w-]*$/.test(c))
75767
+ tries.push(`${tag}.${c}`);
75768
+ }
75769
+ return tries.find((t) => doc.querySelectorAll(t).length === 1) ?? null;
75770
+ };
75771
+ const selectorFor = (n) => {
75772
+ let node = n;
75773
+ for (let depth = 0;node && node.tagName !== "BODY" && depth < 8; depth++) {
75774
+ const anchor = stableOf(node);
75775
+ if (anchor) {
75776
+ const tail = node === n ? "" : nthPath(n, node);
75777
+ const sel = tail ? `${anchor} > ${tail}` : anchor;
75778
+ if (doc.querySelectorAll(sel).length === 1)
75779
+ return sel;
75780
+ }
75781
+ node = node.parentElement;
75782
+ }
75783
+ return nthPath(n, null);
75784
+ };
75785
+ const STYLE_KEYS = [
75786
+ "display",
75787
+ "position",
75788
+ "box-sizing",
75789
+ "width",
75790
+ "height",
75791
+ "min-width",
75792
+ "max-width",
75793
+ "margin",
75794
+ "padding",
75795
+ "gap",
75796
+ "grid-template-columns",
75797
+ "grid-auto-flow",
75798
+ "flex-direction",
75799
+ "flex-wrap",
75800
+ "justify-content",
75801
+ "align-items",
75802
+ "font-family",
75803
+ "font-size",
75804
+ "font-weight",
75805
+ "line-height",
75806
+ "letter-spacing",
75807
+ "text-transform",
75808
+ "color",
75809
+ "background-color",
75810
+ "border",
75811
+ "border-radius",
75812
+ "overflow"
75813
+ ];
75814
+ const r = el.getBoundingClientRect();
75815
+ const cs = win.getComputedStyle(el);
75816
+ const styles = {};
75817
+ for (const k of STYLE_KEYS)
75818
+ styles[k] = cs.getPropertyValue(k);
75819
+ const visible = (n) => [...n.children].filter((c) => c.getClientRects().length > 0);
75820
+ let holder = el;
75821
+ for (let i = 0;i < 4 && visible(holder).length === 1; i++)
75822
+ holder = visible(holder)[0];
75823
+ const kids = visible(holder);
75824
+ const round = (x) => Math.round(x * 10) / 10;
75825
+ const words = new Set;
75826
+ const walk = doc.createTreeWalker(el, NodeFilter.SHOW_TEXT);
75827
+ for (let t = walk.nextNode();t; t = walk.nextNode()) {
75828
+ const tag = t.parentElement?.tagName;
75829
+ if (tag === "SCRIPT" || tag === "STYLE")
75830
+ continue;
75831
+ for (const w of (t.nodeValue ?? "").toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
75832
+ if (w.length >= 3)
75833
+ words.add(w);
75834
+ }
75835
+ }
75836
+ const img = el.closest("img") ?? el.querySelector("img");
75837
+ const imageKey = img ? (img.getAttribute("alt") ?? "").trim() || ((img.getAttribute("src") ?? "").split("/").pop() ?? "").split("?")[0] || null : null;
75838
+ return {
75839
+ words: [...words].slice(0, 40),
75840
+ size: (el.textContent ?? "").length,
75841
+ imageKey,
75842
+ point: { x: r.left + r.width / 2, y: r.top + Math.min(r.height / 2, 40) },
75843
+ snapshot: {
75844
+ selector: selectorFor(el),
75845
+ viewport: { width: win.innerWidth, height: win.innerHeight, dpr: win.devicePixelRatio },
75846
+ scrollY: Math.round(win.scrollY),
75847
+ rect: {
75848
+ x: round(r.left),
75849
+ y: round(r.top + win.scrollY),
75850
+ width: round(r.width),
75851
+ height: round(r.height)
75852
+ },
75853
+ styles,
75854
+ children: kids.slice(0, 24).map((c) => {
75855
+ const b = c.getBoundingClientRect();
75856
+ return {
75857
+ tag: c.tagName.toLowerCase(),
75858
+ x: round(b.left - r.left),
75859
+ y: round(b.top - r.top),
75860
+ width: round(b.width),
75861
+ height: round(b.height)
75862
+ };
75863
+ }),
75864
+ childCount: kids.length,
75865
+ text: (el.innerText ?? "").replace(/\s+/g, " ").trim().slice(0, 240),
75866
+ html: el.outerHTML.slice(0, 2000)
75867
+ }
75868
+ };
75869
+ }
75870
+ function matchSignature(sig, doc = document, snapshotOf = (el, d) => (globalThis.__paritySignatureOf ?? signatureOf)(el, d)?.snapshot ?? null) {
75871
+ const wordsOf = (root) => {
75872
+ const out = new Set;
75873
+ const w = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT);
75874
+ for (let t = w.nextNode();t; t = w.nextNode()) {
75875
+ const tag = t.parentElement?.tagName;
75876
+ if (tag === "SCRIPT" || tag === "STYLE")
75877
+ continue;
75878
+ for (const x of (t.nodeValue ?? "").toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
75879
+ if (x.length >= 3)
75880
+ out.add(x);
75881
+ }
75882
+ }
75883
+ return out;
75884
+ };
75885
+ const done = (el, by, ambiguous) => {
75886
+ const snapshot = snapshotOf(el, doc);
75887
+ return snapshot ? { by, snapshot, ambiguous } : null;
75888
+ };
75889
+ if (sig.words.length) {
75890
+ const hits = [];
75891
+ const ceiling = sig.size ? sig.size * 3 + 400 : Number.POSITIVE_INFINITY;
75892
+ for (const c of doc.body.querySelectorAll("*")) {
75893
+ if (c.tagName === "SCRIPT" || c.tagName === "STYLE")
75894
+ continue;
75895
+ const len = (c.textContent ?? "").length;
75896
+ if (!len || len > ceiling)
75897
+ continue;
75898
+ const have = wordsOf(c);
75899
+ const cover = sig.words.filter((x) => have.has(x)).length / sig.words.length;
75900
+ if (cover >= 0.8)
75901
+ hits.push({ el: c, cover, len });
75902
+ }
75903
+ if (hits.length) {
75904
+ const top = Math.max(...hits.map((h) => h.cover));
75905
+ const best = hits.filter((h) => h.cover === top).reduce((a, b) => a.el.contains(b.el) ? b : a);
75906
+ const rivals = hits.filter((h) => h.cover === top && h.el !== best.el && !h.el.contains(best.el) && !best.el.contains(h.el) && Math.abs(h.len - best.len) <= best.len * 0.1).length;
75907
+ return done(best.el, "text", rivals);
75908
+ }
75909
+ }
75910
+ if (sig.imageKey) {
75911
+ const imgs = [...doc.images].filter((i) => (i.getAttribute("alt") ?? "").trim() === sig.imageKey || (i.getAttribute("src") ?? "").includes(sig.imageKey ?? "\x00"));
75912
+ if (imgs[0])
75913
+ return done(imgs[0], "image", imgs.length - 1);
75914
+ }
75915
+ const at = doc.elementFromPoint(sig.point.x, sig.point.y);
75916
+ return at && at !== doc.body && at !== doc.documentElement ? done(at, "position", 0) : null;
75917
+ }
75918
+
75919
+ // src/commands/pair.ts
75920
+ async function open3(browser, url, viewport, waitMs) {
75921
+ const ctx = await newContext(browser, { viewport });
75922
+ const page = await ctx.newPage();
75923
+ await page.goto(url, { waitUntil: "load", timeout: 60000 });
75924
+ await settlePage(page, { waitMs, scroll: false });
75925
+ return page;
75926
+ }
75927
+ async function pairCommand(opts) {
75928
+ const viewport = parseViewport3(opts.viewport);
75929
+ if (!viewport) {
75930
+ console.error(chalk31.red(`invalid viewport: ${opts.viewport} (use mobile|tablet|desktop)`));
75931
+ return 2;
75932
+ }
75933
+ const from = opts.side;
75934
+ const to = from === "prod" ? "cand" : "prod";
75935
+ const browser = await launchBrowser();
75936
+ try {
75937
+ const [src, dst] = await Promise.all([
75938
+ open3(browser, opts[from], viewport, Number(opts.wait)),
75939
+ open3(browser, opts[to], viewport, Number(opts.wait))
75940
+ ]);
75941
+ const sig = await src.evaluate(`(${signatureOf.toString()})(${JSON.stringify(opts.selector)})`);
75942
+ if (!sig) {
75943
+ return report(opts, from, null, null, `no element matches ${opts.selector} on ${from}`);
75944
+ }
75945
+ const top = Math.max(0, sig.snapshot.rect.y - 100);
75946
+ await dst.evaluate((y) => window.scrollTo(0, y), top);
75947
+ const point = { x: sig.point.x, y: 100 + Math.min(sig.snapshot.rect.height / 2, 40) };
75948
+ const match = await dst.evaluate(`(() => { globalThis.__paritySignatureOf = ${signatureOf.toString()};
75949
+ return (${matchSignature.toString()})(${JSON.stringify({ words: sig.words, imageKey: sig.imageKey, size: sig.size, point })}); })()`);
75950
+ if (!match)
75951
+ return report(opts, from, sig.snapshot, null, `no counterpart found on ${to}`);
75952
+ if (match.ambiguous > 0) {
75953
+ return report(opts, from, sig.snapshot, match, `${match.ambiguous + 1} elements on ${to} match equally — refusing to pick one`);
75954
+ }
75955
+ return report(opts, from, sig.snapshot, match, null);
75956
+ } finally {
75957
+ await browser.close();
75958
+ }
75959
+ }
75960
+ function report(opts, from, source, match, problem) {
75961
+ const to = from === "prod" ? "cand" : "prod";
75962
+ if (opts.json) {
75963
+ console.log(JSON.stringify({
75964
+ ok: !problem,
75965
+ problem,
75966
+ [from]: source,
75967
+ [to]: match?.snapshot ?? null,
75968
+ matchedBy: match?.by ?? null,
75969
+ ambiguous: match?.ambiguous ?? 0
75970
+ }));
75971
+ } else {
75972
+ const box = (s) => s ? chalk31.dim(`${s.rect.width}×${s.rect.height} at (${s.rect.x}, ${s.rect.y})`) : "";
75973
+ if (source)
75974
+ console.log(`${from} ${source.selector} ${box(source)}`);
75975
+ if (match) {
75976
+ console.log(`${to} ${match.snapshot.selector} ${box(match.snapshot)} ${chalk31.dim(`by ${match.by}`)}`);
75977
+ }
75978
+ if (problem)
75979
+ console.log(chalk31.yellow(problem));
75980
+ else if (match?.by === "position") {
75981
+ console.log(chalk31.yellow("matched by position only — verify it is the same element"));
75982
+ }
75983
+ }
75984
+ return problem ? 2 : 0;
75985
+ }
75986
+ function sectionArgsFromTask(taskDir) {
75987
+ const file = join45(taskDir, "task.json");
75988
+ if (!existsSync33(file))
75989
+ throw new Error(`no task.json in ${taskDir}`);
75990
+ const task = JSON.parse(readFileSync38(file, "utf8"));
75991
+ const ctxFile = join45(taskDir, "context.json");
75992
+ const ctx = existsSync33(ctxFile) ? JSON.parse(readFileSync38(ctxFile, "utf8")) : {};
75993
+ const prodSel = task.side === "prod" ? task.selector : ctx.prod?.selector ?? task.counterpart;
75994
+ const candSel = task.side === "cand" ? task.selector : ctx.cand?.selector ?? task.counterpart;
75995
+ if (!prodSel || !candSel) {
75996
+ throw new Error(`task ${task.id} has no counterpart — run \`parity pair\` to find it first`);
75997
+ }
75998
+ const at = (base) => new URL(task.page, base).toString();
75999
+ const vp = (ctx[task.side] ?? ctx.prod ?? ctx.cand)?.viewport;
76000
+ return {
76001
+ prod: at(task.prodUrl),
76002
+ cand: at(task.candUrl),
76003
+ selector: prodSel,
76004
+ candSelector: candSel,
76005
+ viewport: task.device,
76006
+ ...vp ? { viewportSize: { width: vp.width, height: vp.height } } : {}
76007
+ };
76008
+ }
76009
+
76010
+ // src/commands/ios.ts
76011
+ var LOCK = join46(homedir5(), ".parity", "ios.lock");
76012
+ function simctl(...args) {
76013
+ return execFileSync4("xcrun", ["simctl", ...args], { encoding: "utf8", timeout: 180000 }).trim();
76014
+ }
76015
+ function alive2(pid) {
76016
+ try {
76017
+ process.kill(pid, 0);
76018
+ return true;
76019
+ } catch {
76020
+ return false;
76021
+ }
76022
+ }
76023
+ async function takeLock() {
76024
+ mkdirSync23(join46(homedir5(), ".parity"), { recursive: true });
76025
+ const until = Date.now() + 5 * 60000;
76026
+ for (;; ) {
76027
+ const holder = existsSync34(LOCK) ? Number(readFileSync39(LOCK, "utf8")) : 0;
76028
+ if (!holder || !alive2(holder) || holder === process.pid)
76029
+ break;
76030
+ if (Date.now() > until)
76031
+ throw new Error(`the iOS Simulator is busy (held by pid ${holder}) for over 5 min`);
76032
+ await new Promise((r) => setTimeout(r, 2000));
76033
+ }
76034
+ writeFileSync34(LOCK, String(process.pid));
76035
+ }
76036
+ function findDevice(name) {
76037
+ const list = JSON.parse(simctl("list", "devices", "available", "-j"));
76038
+ const all = Object.entries(list.devices).filter(([runtime]) => runtime.includes("iOS")).flatMap(([, ds]) => ds);
76039
+ const d = all.find((x) => x.name === name) ?? all.find((x) => x.name.startsWith("iPhone"));
76040
+ if (!d)
76041
+ throw new Error("no iOS Simulator device installed — add one in Xcode › Settings › Platforms");
76042
+ return d;
76043
+ }
76044
+ async function iosCommand(opts) {
76045
+ try {
76046
+ execFileSync4("xcrun", ["simctl", "help"], { stdio: "ignore" });
76047
+ } catch {
76048
+ console.error(chalk32.yellow("xcrun simctl is not available — install Xcode to test on iOS Safari. Nothing was measured."));
76049
+ return 2;
76050
+ }
76051
+ let { prod, cand, selector, candSelector } = opts;
76052
+ if (opts.task) {
76053
+ const a = sectionArgsFromTask(opts.task);
76054
+ prod ??= a.prod;
76055
+ cand ??= a.cand;
76056
+ selector ??= a.selector;
76057
+ candSelector ??= a.candSelector;
76058
+ }
76059
+ const sides = opts.url ? [{ side: "page", url: opts.url, sel: selector }] : prod && cand ? [
76060
+ { side: "prod", url: prod, sel: selector },
76061
+ { side: "cand", url: cand, sel: candSelector ?? selector }
76062
+ ] : [];
76063
+ if (!sides.length) {
76064
+ console.error("ios needs --url, or --prod and --cand (or --task <dir>)");
76065
+ return 2;
76066
+ }
76067
+ await takeLock();
76068
+ const out = resolve15(opts.outDir);
76069
+ mkdirSync23(out, { recursive: true });
76070
+ const scratch = join46(tmpdir2(), `parity-ios-${process.pid}`);
76071
+ mkdirSync23(scratch, { recursive: true });
76072
+ let bootedHere = false;
76073
+ const device = findDevice(opts.device);
76074
+ const proxy = await startProxyServer(scratch);
76075
+ const shots = {};
76076
+ const found = {};
76077
+ try {
76078
+ if (device.state !== "Booted") {
76079
+ simctl("boot", device.udid);
76080
+ bootedHere = true;
76081
+ }
76082
+ simctl("bootstatus", device.udid, "-b");
76083
+ simctl("openurl", device.udid, `${proxy.url}__parity/health`);
76084
+ await new Promise((r) => setTimeout(r, 4000));
76085
+ for (const s of sides) {
76086
+ const seen = scrollBeacons.length;
76087
+ const via = `${proxy.url}proxy?url=${encodeURIComponent(s.url)}${s.sel ? `&scrollTo=${encodeURIComponent(s.sel)}` : ""}`;
76088
+ simctl("openurl", device.udid, via);
76089
+ await new Promise((r) => setTimeout(r, Number(opts.wait)));
76090
+ const file = join46(out, `ios-${s.side}.png`);
76091
+ simctl("io", device.udid, "screenshot", "--type=png", file);
76092
+ shots[s.side] = file;
76093
+ if (s.sel) {
76094
+ const b = scrollBeacons.slice(seen).find((x) => x.selector === s.sel);
76095
+ found[s.side] = b ? b.ok : null;
76096
+ }
76097
+ }
76098
+ } finally {
76099
+ await proxy.close();
76100
+ if (bootedHere) {
76101
+ try {
76102
+ simctl("shutdown", device.udid);
76103
+ } catch {}
76104
+ }
76105
+ rmSync2(scratch, { recursive: true, force: true });
76106
+ if (existsSync34(LOCK) && Number(readFileSync39(LOCK, "utf8")) === process.pid)
76107
+ rmSync2(LOCK);
76108
+ }
76109
+ const missing = Object.entries(found).filter(([, v]) => v !== true).map(([k]) => k);
76110
+ let diff = null;
76111
+ if (shots.prod && shots.cand && !missing.length)
76112
+ diff = diffScreenshots(shots.prod, shots.cand, join46(out, "ios-diff.png"));
76113
+ const report = {
76114
+ device: device.name,
76115
+ shots,
76116
+ found,
76117
+ diff: diff ? { pctDiff: diff.pctDiff, diffPixels: diff.diffPixels, heatmap: diff.heatmapPath } : null,
76118
+ note: "full-screen captures in Mobile Safari; the status bar clock differs by a few pixels"
76119
+ };
76120
+ if (opts.json)
76121
+ console.log(JSON.stringify(report));
76122
+ else {
76123
+ console.log(`${chalk32.bold("iOS Safari")} · ${device.name}`);
76124
+ for (const [k, v] of Object.entries(shots))
76125
+ console.log(` ${k.padEnd(5)} ${v}`);
76126
+ for (const side of missing) {
76127
+ console.log(chalk32.yellow(` ${side}: the element was ${found[side] === false ? "not found" : "not reported"} in Safari — no diff (pass a selector that holds, e.g. from \`parity pair\`)`));
76128
+ }
76129
+ if (diff)
76130
+ console.log(` diff ${(diff.pctDiff * 100).toFixed(2)}% (${diff.diffPixels} px) → ${diff.heatmapPath}`);
76131
+ }
76132
+ return missing.length ? 2 : 0;
76133
+ }
76134
+
73876
76135
  // src/commands/mcp.ts
73877
76136
  import { createInterface as createInterface3 } from "node:readline";
73878
- import { resolve as resolve11 } from "node:path";
76137
+ import { resolve as resolve17 } from "node:path";
73879
76138
 
73880
76139
  // src/util/version.ts
73881
- import { readFileSync as readFileSync34 } from "node:fs";
73882
- import { dirname as dirname6, resolve as resolve10 } from "node:path";
73883
- import { fileURLToPath } from "node:url";
76140
+ import { readFileSync as readFileSync40 } from "node:fs";
76141
+ import { dirname as dirname9, resolve as resolve16 } from "node:path";
76142
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
73884
76143
  function getPackageVersion() {
73885
76144
  try {
73886
- const here = dirname6(fileURLToPath(import.meta.url));
76145
+ const here = dirname9(fileURLToPath2(import.meta.url));
73887
76146
  for (const up of ["..", "../..", "../../.."]) {
73888
76147
  try {
73889
- const pkgPath = resolve10(here, up, "package.json");
73890
- const raw = readFileSync34(pkgPath, "utf8");
76148
+ const pkgPath = resolve16(here, up, "package.json");
76149
+ const raw = readFileSync40(pkgPath, "utf8");
73891
76150
  const parsed = JSON.parse(raw);
73892
76151
  if (parsed.name === "@decocms/parity" && typeof parsed.version === "string") {
73893
76152
  return parsed.version;
@@ -73912,7 +76171,7 @@ var fail2 = (text) => ({
73912
76171
  content: [{ type: "text", text }],
73913
76172
  isError: true
73914
76173
  });
73915
- var json = (value) => ok(JSON.stringify(value, null, 2));
76174
+ var json2 = (value) => ok(JSON.stringify(value, null, 2));
73916
76175
  async function dispatch(req, opts) {
73917
76176
  const isNotification = req.id === undefined;
73918
76177
  const id = req.id ?? null;
@@ -73998,8 +76257,8 @@ function parseLine(line) {
73998
76257
  }
73999
76258
 
74000
76259
  // src/mcp/tools.ts
74001
- import { existsSync as existsSync30, readFileSync as readFileSync35 } from "node:fs";
74002
- import { join as join40 } from "node:path";
76260
+ import { existsSync as existsSync35, readFileSync as readFileSync41 } from "node:fs";
76261
+ import { join as join47 } from "node:path";
74003
76262
  var STR = { type: "string" };
74004
76263
  var NONE = { type: "object", properties: {}, additionalProperties: false };
74005
76264
  function withPlan2(ctx, fn) {
@@ -74015,7 +76274,7 @@ var planOrFail = (ctx, fn) => {
74015
76274
  const out = withPlan2(ctx, fn);
74016
76275
  if (out && typeof out === "object" && "missing" in out)
74017
76276
  return fail2(String(out.missing));
74018
- return json(out);
76277
+ return json2(out);
74019
76278
  };
74020
76279
  function mutate(ctx, fn) {
74021
76280
  const plan = loadPlan(ctx.planDir);
@@ -74035,12 +76294,12 @@ function createTools(ctx) {
74035
76294
  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.",
74036
76295
  inputSchema: NONE,
74037
76296
  handler: () => {
74038
- const p = join40(ctx.planDir, "migration.json");
74039
- if (!existsSync30(p)) {
76297
+ const p = join47(ctx.planDir, "migration.json");
76298
+ if (!existsSync35(p)) {
74040
76299
  return fail2(`no migration.json in ${ctx.planDir} — no migration has been started here`);
74041
76300
  }
74042
76301
  try {
74043
- return json(JSON.parse(readFileSync35(p, "utf8")));
76302
+ return json2(JSON.parse(readFileSync41(p, "utf8")));
74044
76303
  } catch (err) {
74045
76304
  return fail2(`migration.json is not valid JSON: ${err.message}`);
74046
76305
  }
@@ -74086,7 +76345,7 @@ function createTools(ctx) {
74086
76345
  return fail2(String(out.missing));
74087
76346
  if (out === null)
74088
76347
  return fail2(`the plan has no page at ${path}`);
74089
- return json(out);
76348
+ return json2(out);
74090
76349
  }
74091
76350
  },
74092
76351
  {
@@ -74099,7 +76358,7 @@ function createTools(ctx) {
74099
76358
  },
74100
76359
  handler: (args) => {
74101
76360
  const limit = typeof args.limit === "number" ? args.limit : 20;
74102
- return json(listRuns(ctx.output).slice(0, limit));
76361
+ return json2(listRuns(ctx.output).slice(0, limit));
74103
76362
  }
74104
76363
  },
74105
76364
  {
@@ -74116,7 +76375,7 @@ function createTools(ctx) {
74116
76375
  return fail2(`no runs found under ${ctx.output}`);
74117
76376
  try {
74118
76377
  const run = loadRun(ctx.output, id);
74119
- return json({
76378
+ return json2({
74120
76379
  id: run.id,
74121
76380
  timestamp: run.timestamp,
74122
76381
  prodUrl: run.prodUrl,
@@ -74236,8 +76495,8 @@ function createTools(ctx) {
74236
76495
  async function mcpCommand(opts) {
74237
76496
  const version = getPackageVersion();
74238
76497
  const tools = createTools({
74239
- planDir: resolve11(opts.dir),
74240
- output: resolve11(opts.output),
76498
+ planDir: resolve17(opts.dir),
76499
+ output: resolve17(opts.output),
74241
76500
  candUrl: opts.candUrl
74242
76501
  });
74243
76502
  const write = (res) => process.stdout.write(`${JSON.stringify(res)}
@@ -74270,9 +76529,9 @@ async function mcpCommand(opts) {
74270
76529
  }
74271
76530
 
74272
76531
  // src/commands/heatmap.ts
74273
- import { mkdirSync as mkdirSync19 } from "node:fs";
74274
- import { resolve as resolve12 } from "node:path";
74275
- import chalk30 from "chalk";
76532
+ import { mkdirSync as mkdirSync24 } from "node:fs";
76533
+ import { resolve as resolve18 } from "node:path";
76534
+ import chalk33 from "chalk";
74276
76535
 
74277
76536
  // src/diff/hotspot-findings.ts
74278
76537
  var TYPOGRAPHY_PROPS = /^(font-family|font-weight|font-size|font-style|line-height|letter-spacing|text-transform)$/;
@@ -74371,13 +76630,13 @@ function describe2(type, hotspot, nodes, imageHostDelta, because) {
74371
76630
  }
74372
76631
 
74373
76632
  // src/diff/noise-mask.ts
74374
- import { readFileSync as readFileSync36, writeFileSync as writeFileSync31 } from "node:fs";
76633
+ import { readFileSync as readFileSync42, writeFileSync as writeFileSync35 } from "node:fs";
74375
76634
  import { PNG as PNG5 } from "pngjs";
74376
76635
  var DEFAULT_DILATE = 2;
74377
76636
  var MAX_MASK_COVERAGE = 0.2;
74378
76637
  function buildNoiseMask(firstPng, secondPng, dilate = DEFAULT_DILATE) {
74379
- const a = PNG5.sync.read(readFileSync36(firstPng));
74380
- const b = PNG5.sync.read(readFileSync36(secondPng));
76638
+ const a = PNG5.sync.read(readFileSync42(firstPng));
76639
+ const b = PNG5.sync.read(readFileSync42(secondPng));
74381
76640
  if (a.width !== b.width || a.height !== b.height)
74382
76641
  return null;
74383
76642
  const { width, height } = a;
@@ -74417,7 +76676,7 @@ function dilateMask(src, width, height, radius) {
74417
76676
  return pass(pass(src, true), false);
74418
76677
  }
74419
76678
  function applyMask(pngPath, mask, outPath) {
74420
- const png = PNG5.sync.read(readFileSync36(pngPath));
76679
+ const png = PNG5.sync.read(readFileSync42(pngPath));
74421
76680
  if (png.width !== mask.width || png.height !== mask.height) {
74422
76681
  throw new Error(`applyMask: image is ${png.width}x${png.height} but the mask is ${mask.width}x${mask.height}`);
74423
76682
  }
@@ -74430,11 +76689,11 @@ function applyMask(pngPath, mask, outPath) {
74430
76689
  png.data[i + 2] = 0;
74431
76690
  png.data[i + 3] = 255;
74432
76691
  }
74433
- writeFileSync31(outPath, PNG5.sync.write(png));
76692
+ writeFileSync35(outPath, PNG5.sync.write(png));
74434
76693
  }
74435
76694
  function readPngSize(pngPath) {
74436
76695
  try {
74437
- const head = readFileSync36(pngPath).subarray(0, 24);
76696
+ const head = readFileSync42(pngPath).subarray(0, 24);
74438
76697
  if (head.length < 24)
74439
76698
  return null;
74440
76699
  return { width: head.readUInt32BE(16), height: head.readUInt32BE(20) };
@@ -74686,22 +76945,22 @@ function exitCodeFor(verdict) {
74686
76945
  async function heatmapCommand(opts) {
74687
76946
  const specs = parseViewports2(opts.viewports);
74688
76947
  if (typeof specs === "string") {
74689
- console.error(chalk30.red(specs));
76948
+ console.error(chalk33.red(specs));
74690
76949
  return EXIT_INCONCLUSIVE;
74691
76950
  }
74692
76951
  const waitMs = Number.parseInt(opts.wait, 10);
74693
76952
  if (!Number.isFinite(waitMs) || waitMs < 0) {
74694
- console.error(chalk30.red(`--wait inválido: ${opts.wait}`));
76953
+ console.error(chalk33.red(`--wait inválido: ${opts.wait}`));
74695
76954
  return EXIT_INCONCLUSIVE;
74696
76955
  }
74697
76956
  if (!isValidUrl5(opts.prod) || !isValidUrl5(opts.cand)) {
74698
- console.error(chalk30.red("--prod ou --cand inválido"));
76957
+ console.error(chalk33.red("--prod ou --cand inválido"));
74699
76958
  return EXIT_INCONCLUSIVE;
74700
76959
  }
74701
76960
  const selector = opts.selector?.trim() || null;
74702
76961
  const candSelector = opts.candSelector?.trim() || selector;
74703
76962
  const mode = selector ? "section" : "page";
74704
- mkdirSync19(opts.outDir, { recursive: true });
76963
+ mkdirSync24(opts.outDir, { recursive: true });
74705
76964
  const prefix = `heatmap-${hashSelector(`${opts.prod}|${opts.cand}|${selector ?? "page"}`)}`;
74706
76965
  const browser = await launchBrowser({ headless: true });
74707
76966
  const results = [];
@@ -74734,7 +76993,7 @@ async function heatmapCommand(opts) {
74734
76993
  };
74735
76994
  if (opts.pr) {
74736
76995
  await postQaComment({ report, pr: opts.pr, repo: opts.repo }).catch((err) => {
74737
- console.error(chalk30.yellow(` aviso: não foi possível publicar no PR — ${err.message}`));
76996
+ console.error(chalk33.yellow(` aviso: não foi possível publicar no PR — ${err.message}`));
74738
76997
  });
74739
76998
  }
74740
76999
  if (opts.json)
@@ -74814,7 +77073,7 @@ function emptyResult2(spec) {
74814
77073
  };
74815
77074
  }
74816
77075
  function artifactPaths(outDir, prefix, label) {
74817
- const at = (suffix) => resolve12(outDir, `${prefix}-${label}-${suffix}.png`);
77076
+ const at = (suffix) => resolve18(outDir, `${prefix}-${label}-${suffix}.png`);
74818
77077
  return {
74819
77078
  prod: at("prod"),
74820
77079
  prodRepeat: at("prod-repeat"),
@@ -75158,35 +77417,35 @@ function isValidUrl5(s) {
75158
77417
  }
75159
77418
  }
75160
77419
  var MARK = {
75161
- identical: chalk30.green("✓"),
75162
- differs: chalk30.red("✗"),
75163
- inconclusive: chalk30.yellow("?")
77420
+ identical: chalk33.green("✓"),
77421
+ differs: chalk33.red("✗"),
77422
+ inconclusive: chalk33.yellow("?")
75164
77423
  };
75165
77424
  function printReport(report) {
75166
77425
  console.log("");
75167
- console.log(chalk30.bold(` parity heatmap — ${report.mode}`));
75168
- console.log(chalk30.dim(` prod: ${report.prodUrl}`));
75169
- console.log(chalk30.dim(` cand: ${report.candUrl}`));
77426
+ console.log(chalk33.bold(` parity heatmap — ${report.mode}`));
77427
+ console.log(chalk33.dim(` prod: ${report.prodUrl}`));
77428
+ console.log(chalk33.dim(` cand: ${report.candUrl}`));
75170
77429
  console.log("");
75171
77430
  for (const v of report.viewports) {
75172
- const detail = v.verdict === "identical" ? chalk30.dim("0 pixels") : v.reason ?? chalk30.dim("no detail");
77431
+ const detail = v.verdict === "identical" ? chalk33.dim("0 pixels") : v.reason ?? chalk33.dim("no detail");
75173
77432
  console.log(` ${MARK[v.verdict]} ${v.label.padEnd(12)} ${detail}`);
75174
77433
  if (v.maskedCoverage != null && v.maskedCoverage > 0) {
75175
- console.log(chalk30.dim(` ${(v.maskedCoverage * 100).toFixed(1)}% of the frame excluded: prod does not reproduce those pixels`));
77434
+ console.log(chalk33.dim(` ${(v.maskedCoverage * 100).toFixed(1)}% of the frame excluded: prod does not reproduce those pixels`));
75176
77435
  }
75177
77436
  for (const f of v.findings.slice(0, 5)) {
75178
- console.log(chalk30.dim(` [${f.type}] ${f.summary}`));
77437
+ console.log(chalk33.dim(` [${f.type}] ${f.summary}`));
75179
77438
  }
75180
77439
  if (v.heatmapPath && v.verdict === "differs") {
75181
- console.log(chalk30.dim(` ${v.heatmapPath}`));
77440
+ console.log(chalk33.dim(` ${v.heatmapPath}`));
75182
77441
  }
75183
77442
  const hosts = imageHostDelta(v.prod.imageHosts, v.cand.imageHosts);
75184
77443
  if (hosts.onlyProd.length > 0 || hosts.onlyCand.length > 0) {
75185
- console.log(chalk30.yellow(` image hosts diverge — ${formatHostDelta(hosts)}`));
77444
+ console.log(chalk33.yellow(` image hosts diverge — ${formatHostDelta(hosts)}`));
75186
77445
  }
75187
77446
  }
75188
77447
  console.log("");
75189
- console.log(` ${MARK[report.verdict]} ${chalk30.bold(report.verdict)}${report.reason ? ` — ${report.reason}` : ""}`);
77448
+ console.log(` ${MARK[report.verdict]} ${chalk33.bold(report.verdict)}${report.reason ? ` — ${report.reason}` : ""}`);
75190
77449
  console.log("");
75191
77450
  }
75192
77451
  function imageHostDelta(prod, cand) {
@@ -75207,7 +77466,7 @@ function formatHostDelta(d) {
75207
77466
  }
75208
77467
 
75209
77468
  // src/commands/states.ts
75210
- import chalk31 from "chalk";
77469
+ import chalk34 from "chalk";
75211
77470
  var HOVERABLE = "a,button,summary,[role='button'],[role='menuitem'],label";
75212
77471
  var SETTLE_RETRY_FACTOR = 4;
75213
77472
  async function readStateEffects(page, opts) {
@@ -75419,7 +77678,7 @@ function statesVerdict(counts) {
75419
77678
  async function statesCommand(opts) {
75420
77679
  const viewport = parseViewport3(opts.viewport);
75421
77680
  if (!viewport) {
75422
- console.error(chalk31.red(`--viewport inválido: ${opts.viewport}`));
77681
+ console.error(chalk34.red(`--viewport inválido: ${opts.viewport}`));
75423
77682
  return 2;
75424
77683
  }
75425
77684
  const waitMs = Number.parseInt(opts.wait, 10) || 0;
@@ -75428,12 +77687,12 @@ async function statesCommand(opts) {
75428
77687
  const prodSelector = opts.prodSelector?.trim() || opts.selector?.trim();
75429
77688
  const candSelector = opts.candSelector?.trim() || opts.selector?.trim();
75430
77689
  if (!prodSelector || !candSelector) {
75431
- console.error(chalk31.red(" informe --selector (ambos os lados) ou --prod-selector e --cand-selector"));
77690
+ console.error(chalk34.red(" informe --selector (ambos os lados) ou --prod-selector e --cand-selector"));
75432
77691
  return 2;
75433
77692
  }
75434
77693
  const { aliases, note: aliasNote } = resolveAliases(opts.planDir);
75435
77694
  if (aliasNote)
75436
- console.log(chalk31.dim(` ${aliasNote}`));
77695
+ console.log(chalk34.dim(` ${aliasNote}`));
75437
77696
  const browser = await launchBrowser({ headless: true });
75438
77697
  try {
75439
77698
  const [prodSide, candSide] = await Promise.all([
@@ -75456,7 +77715,7 @@ async function statesCommand(opts) {
75456
77715
  ]);
75457
77716
  if (prodSide.baseError || candSide.baseError) {
75458
77717
  const which = prodSide.baseError ? `prod: ${prodSide.baseError}` : `cand: ${candSide.baseError}`;
75459
- console.error(chalk31.red(` não foi possível ler o componente — ${which}`));
77718
+ console.error(chalk34.red(` não foi possível ler o componente — ${which}`));
75460
77719
  return 2;
75461
77720
  }
75462
77721
  const motion = prodSide.motion.found && candSide.motion.found ? diffMotion(prodSide.motion, candSide.motion, {
@@ -75493,58 +77752,58 @@ async function statesCommand(opts) {
75493
77752
  ]) {
75494
77753
  const caveat = data.settle && formatSettleCaveat(name, data.settle);
75495
77754
  if (caveat)
75496
- console.log(chalk31.yellow(` ${caveat}`));
77755
+ console.log(chalk34.yellow(` ${caveat}`));
75497
77756
  }
75498
77757
  console.log("");
75499
- console.log(chalk31.bold(" Declared motion"));
77758
+ console.log(chalk34.bold(" Declared motion"));
75500
77759
  if (!motion) {
75501
77760
  const err = prodSide.motion.found ? candSide.motion : prodSide.motion;
75502
- console.log(chalk31.yellow(` não foi possível comparar — ${"error" in err ? err.error : "?"}`));
77761
+ console.log(chalk34.yellow(` não foi possível comparar — ${"error" in err ? err.error : "?"}`));
75503
77762
  } else {
75504
77763
  for (const line of formatMotionDiff(motion).split(`
75505
77764
  `))
75506
77765
  console.log(` ${line}`);
75507
77766
  }
75508
77767
  console.log("");
75509
- console.log(chalk31.bold(` Hover effects (${prodSide.effects.length} prod / ${candSide.effects.length} cand)`));
77768
+ console.log(chalk34.bold(` Hover effects (${prodSide.effects.length} prod / ${candSide.effects.length} cand)`));
75510
77769
  const nothing = effects.lost.length === 0 && effects.changed.length === 0 && effects.added.length === 0 && effects.unpaired.length === 0;
75511
77770
  if (nothing && !exercised) {
75512
- console.log(chalk31.yellow(" INCONCLUSIVE — no hover changed anything on either side, so nothing was exercised. Check the selector holds an interactive element."));
77771
+ console.log(chalk34.yellow(" INCONCLUSIVE — no hover changed anything on either side, so nothing was exercised. Check the selector holds an interactive element."));
75513
77772
  } else if (nothing) {
75514
77773
  console.log(" clean — every hover that changes something in prod changes the same in cand");
75515
77774
  }
75516
77775
  for (const e of effects.lost) {
75517
- console.log(chalk31.red(` LOST ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; cand's element was hovered and moved nothing`));
77776
+ console.log(chalk34.red(` LOST ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; cand's element was hovered and moved nothing`));
75518
77777
  }
75519
77778
  for (const { prod, extra, notComparable, onElement } of effects.changed) {
75520
77779
  console.log(` DIFFERS ${prod.target}${prod.label ? ` (${prod.label})` : ""}`);
75521
77780
  if (onElement.length) {
75522
- console.log(chalk31.yellow(` prod also moves [${onElement.join(", ")}] on the element itself`));
77781
+ console.log(chalk34.yellow(` prod also moves [${onElement.join(", ")}] on the element itself`));
75523
77782
  }
75524
77783
  if (extra.length)
75525
77784
  console.log(` cand also moves [${extra.join(", ")}]`);
75526
77785
  if (notComparable.length) {
75527
- console.log(chalk31.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.`));
77786
+ console.log(chalk34.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.`));
75528
77787
  }
75529
77788
  if (onElement.length === 0 && extra.length === 0) {
75530
- console.log(chalk31.dim(" nothing comparable differs."));
77789
+ console.log(chalk34.dim(" nothing comparable differs."));
75531
77790
  }
75532
77791
  }
75533
77792
  for (const e of effects.unpaired) {
75534
- console.log(chalk31.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)`));
77793
+ console.log(chalk34.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)`));
75535
77794
  }
75536
77795
  for (const e of effects.added) {
75537
77796
  console.log(` ADDED ${e.target} — cand moves [${e.properties.join(", ")}]; prod does not`);
75538
77797
  }
75539
77798
  if (effects.unpaired.length > 0 && effects.lost.length === 0 && effects.changed.length === 0) {
75540
77799
  console.log("");
75541
- console.log(chalk31.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.`));
77800
+ console.log(chalk34.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.`));
75542
77801
  }
75543
77802
  if (prodSide.ambient > 0 || candSide.ambient > 0) {
75544
- console.log(chalk31.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.`));
77803
+ console.log(chalk34.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.`));
75545
77804
  }
75546
77805
  if (prodSide.truncated || candSide.truncated) {
75547
- console.log(chalk31.dim(" TRUNCATED — element cap hit; absence of a finding is not proof"));
77806
+ console.log(chalk34.dim(" TRUNCATED — element cap hit; absence of a finding is not proof"));
75548
77807
  }
75549
77808
  return inconclusive || effects.lost.length > 0 || (motion?.findings.length ?? 0) > 0 ? 1 : 0;
75550
77809
  } finally {
@@ -75555,7 +77814,7 @@ async function statesCommand(opts) {
75555
77814
  }
75556
77815
 
75557
77816
  // src/commands/variance.ts
75558
- import chalk32 from "chalk";
77817
+ import chalk35 from "chalk";
75559
77818
 
75560
77819
  // src/diff/variance.ts
75561
77820
  var uniq2 = (xs) => [...new Set(xs)];
@@ -75659,7 +77918,7 @@ function formatVariance(report, opts = {}) {
75659
77918
  // src/commands/variance.ts
75660
77919
  function varianceCommand(opts) {
75661
77920
  if (opts.runIds.length < 2) {
75662
- console.error(chalk32.red(" informe pelo menos 2 runs: parity variance <runIdA> <runIdB> [...]"));
77921
+ console.error(chalk35.red(" informe pelo menos 2 runs: parity variance <runIdA> <runIdB> [...]"));
75663
77922
  return 2;
75664
77923
  }
75665
77924
  const budget = Number.parseFloat(opts.scoreBudget ?? "1");
@@ -75668,7 +77927,7 @@ function varianceCommand(opts) {
75668
77927
  try {
75669
77928
  runs.push(loadRun(opts.output, id));
75670
77929
  } catch (err) {
75671
- console.error(chalk32.red(` ✖ ${err.message}`));
77930
+ console.error(chalk35.red(` ✖ ${err.message}`));
75672
77931
  return 2;
75673
77932
  }
75674
77933
  }
@@ -75677,7 +77936,7 @@ function varianceCommand(opts) {
75677
77936
  console.log(JSON.stringify({ ...report, stable: isStable(report, budget), scoreBudget: budget }));
75678
77937
  } else {
75679
77938
  console.log("");
75680
- console.log(chalk32.bold(" Score variance"));
77939
+ console.log(chalk35.bold(" Score variance"));
75681
77940
  for (const line of formatVariance(report, { scoreBudget: budget }).split(`
75682
77941
  `)) {
75683
77942
  console.log(` ${line}`);
@@ -75689,10 +77948,10 @@ function varianceCommand(opts) {
75689
77948
  }
75690
77949
 
75691
77950
  // src/commands/vitals.ts
75692
- import { existsSync as existsSync31, readFileSync as readFileSync37, writeFileSync as writeFileSync32 } from "node:fs";
77951
+ import { existsSync as existsSync36, readFileSync as readFileSync43, writeFileSync as writeFileSync36 } from "node:fs";
75693
77952
  import { availableParallelism } from "node:os";
75694
- import { join as join41 } from "node:path";
75695
- import chalk33 from "chalk";
77953
+ import { join as join48 } from "node:path";
77954
+ import chalk36 from "chalk";
75696
77955
  import ora9 from "ora";
75697
77956
 
75698
77957
  // src/checks/agentic-nav.ts
@@ -75990,10 +78249,10 @@ async function vitalsCommand(opts) {
75990
78249
  const runId = newRunId();
75991
78250
  const paths = createRunDir(opts.output, runId);
75992
78251
  const t0 = Date.now();
75993
- console.log(chalk33.bold(`
78252
+ console.log(chalk36.bold(`
75994
78253
  parity vitals ${runId}`));
75995
- console.log(chalk33.dim(` prod: ${opts.prod}`));
75996
- console.log(chalk33.dim(` cand: ${opts.cand}`));
78254
+ console.log(chalk36.dim(` prod: ${opts.prod}`));
78255
+ console.log(chalk36.dim(` cand: ${opts.cand}`));
75997
78256
  const discoverSpinner = ora9("Descobrindo páginas…").start();
75998
78257
  const pagePaths = await discoverPagePaths2(opts.prod, opts);
75999
78258
  if (pagePaths.length === 0) {
@@ -76025,12 +78284,12 @@ async function vitalsCommand(opts) {
76025
78284
  completed++;
76026
78285
  const elapsed = ((Date.now() - t0) / 1000).toFixed(0);
76027
78286
  const etaSec = completed > 0 ? Math.round((Date.now() - t0) / completed * (total - completed) / 1000) : 0;
76028
- progress.text = `${completed}/${total} · ${elapsed}s · ETA ${etaSec}s · ${task.side === "prod" ? chalk33.cyan("prod") : chalk33.magenta("cand")} ${task.path} (${task.viewport})`;
78287
+ progress.text = `${completed}/${total} · ${elapsed}s · ETA ${etaSec}s · ${task.side === "prod" ? chalk36.cyan("prod") : chalk36.magenta("cand")} ${task.path} (${task.viewport})`;
76029
78288
  }
76030
78289
  });
76031
78290
  progress.succeed(`${total} capture(s) em ${((Date.now() - t0) / 1000).toFixed(1)}s`);
76032
78291
  if (opts.lighthouse !== false) {
76033
- const lhDir = join41(paths.runDir, "lighthouse");
78292
+ const lhDir = join48(paths.runDir, "lighthouse");
76034
78293
  const lhCap = opts.lighthouseConcurrency ?? Math.max(1, Math.min(2, Math.floor(availableParallelism() / 2)));
76035
78294
  const done = tasks.filter((t) => !!t.capture);
76036
78295
  const lhT0 = Date.now();
@@ -76054,7 +78313,7 @@ async function vitalsCommand(opts) {
76054
78313
  }
76055
78314
  lhCompleted++;
76056
78315
  const elapsed = ((Date.now() - lhT0) / 1000).toFixed(0);
76057
- lhProgress.text = `Lighthouse ${lhCompleted}/${done.length} · ${elapsed}s · ${task.side === "prod" ? chalk33.cyan("prod") : chalk33.magenta("cand")} ${task.path} (${task.viewport})`;
78316
+ lhProgress.text = `Lighthouse ${lhCompleted}/${done.length} · ${elapsed}s · ${task.side === "prod" ? chalk36.cyan("prod") : chalk36.magenta("cand")} ${task.path} (${task.viewport})`;
76058
78317
  });
76059
78318
  lhProgress.succeed(`Lighthouse ${done.length} página(s) em ${((Date.now() - lhT0) / 1000).toFixed(1)}s`);
76060
78319
  }
@@ -76119,7 +78378,7 @@ async function vitalsCommand(opts) {
76119
78378
  writeRunReportJson(paths.runDir, run);
76120
78379
  const html = renderHtmlReport(run, paths.runDir);
76121
78380
  writeRunReportHtml(paths.runDir, html);
76122
- writeFileSync32(join41(paths.runDir, "vitals.json"), `${JSON.stringify({
78381
+ writeFileSync36(join48(paths.runDir, "vitals.json"), `${JSON.stringify({
76123
78382
  schemaVersion: "0.1",
76124
78383
  prodUrl: opts.prod,
76125
78384
  candUrl: opts.cand,
@@ -76132,8 +78391,8 @@ async function vitalsCommand(opts) {
76132
78391
  `, "utf8");
76133
78392
  printSummary8(vitalsResult, cacheResult, scoresResult, oppsResult, agenticResult);
76134
78393
  console.log("");
76135
- console.log(chalk33.dim(` → ${paths.reportHtml}`));
76136
- console.log(chalk33.dim(` \uD83D\uDCA1 use 'parity serve ${runId}' pra preview iframe`));
78394
+ console.log(chalk36.dim(` → ${paths.reportHtml}`));
78395
+ console.log(chalk36.dim(` \uD83D\uDCA1 use 'parity serve ${runId}' pra preview iframe`));
76137
78396
  console.log("");
76138
78397
  if (opts.open) {
76139
78398
  const { default: open } = await import("open");
@@ -76223,15 +78482,15 @@ async function discoverPagePaths2(prodUrl, opts) {
76223
78482
  function parseUrlList(input) {
76224
78483
  if (input.startsWith("file:") || input.endsWith(".txt") || input.endsWith(".list")) {
76225
78484
  const path = input.replace(/^file:\/\//, "");
76226
- if (existsSync31(path)) {
76227
- return readFileSync37(path, "utf8").split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith("#")).map((s) => s.startsWith("/") ? s : `/${s}`);
78485
+ if (existsSync36(path)) {
78486
+ return readFileSync43(path, "utf8").split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith("#")).map((s) => s.startsWith("/") ? s : `/${s}`);
76228
78487
  }
76229
78488
  }
76230
78489
  return input.split(",").map((s) => s.trim()).filter(Boolean).map((s) => s.startsWith("/") || s.startsWith("http") ? s : `/${s}`);
76231
78490
  }
76232
78491
  function printSummary8(vitals, cache, scores, opportunities, agentic) {
76233
78492
  console.log("");
76234
- console.log(chalk33.bold(" Summary:"));
78493
+ console.log(chalk36.bold(" Summary:"));
76235
78494
  console.log(` ${vitals.summary}`);
76236
78495
  console.log(` ${cache.summary}`);
76237
78496
  if (scores.status !== "skipped")
@@ -76412,6 +78671,9 @@ program.command("cms").description("Read and write VTEX Content Platform entries
76412
78671
  program.command("serve").argument("<runId>", "Run ID to serve").description("Spawns a local HTTP server that serves the report and proxies external iframes (strips X-Frame-Options/CSP), making the Side-by-side tab functional for any site.").option("--output <dir>", "Output directory where runs live", "./parity-output").option("--port <n>", "Fixed port (default: auto-pick free port)", (v) => Number(v)).option("--no-open", "Don't open the browser automatically").action(async (runId, opts) => {
76413
78672
  process.exit(await serveCommand(runId, opts));
76414
78673
  });
78674
+ program.command("event").argument("<type>", "Event type: phase-change | dispatch | bench | score | note | …").description("Record a migration event into <dir>/events.jsonl — the sanctioned emission path for hooks and the orchestrator. The cockpit daemon tails this file into its live activity feed.").option("--dir <dir>", "Directory holding events.jsonl (the target's .parity/)", ".parity").option("--data <json>", `JSON object of event fields, e.g. '{"agent":"porter","component":"hero"}'`).action((type, opts) => {
78675
+ process.exit(eventCommand(type, opts));
78676
+ });
76415
78677
  program.command("report").argument("<runId>", "Run ID to open").description("Open the HTML report for a run in the default browser. With --section, extract a single tab to stdout instead — useful for agents that need just the SEO/Network/Vitals slice without parsing the whole report. Issue #74.").option("--output <dir>", "Output directory", "./parity-output").option("--section <name>", "Extract one tab to stdout instead of opening the report. Valid names: summary, visualdiff, seo, sidebyside, issues, vitals, cache, checks, prompt, pages, console, network, diff.").option("--json", "Pair with --section to emit a normalized JSON projection of the section (from report.json) instead of the raw HTML slice.").option("--deck", "Render the presentation deck instead: one topic per full-viewport page, advanced sideways, in a single self-contained HTML file. For showing the result to someone rather than debugging it. Issue #290.", false).option("--out <path>", "Where to write the deck (default: deck.html in the run dir)").option("--lang <pt|en>", "Initial deck language; the in-page toggle still switches live", "en").option("--open", "Open the rendered deck in the browser", false).action(async (runId, opts) => {
76416
78678
  process.exit(await reportCommand(runId, {
76417
78679
  output: opts.output,
@@ -76537,13 +78799,32 @@ program.command("heatmap").description("Is the candidate PIXEL-IDENTICAL to prod
76537
78799
  json: opts.json
76538
78800
  }));
76539
78801
  });
76540
- 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) => {
78802
+ 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).").option("--prod <url>", "Production URL (base, e.g. https://www.example.com). Required unless --task.").option("--cand <url>", "Candidate URL (base, e.g. https://example.deco-cx.workers.dev). Required unless --task; with --task, pass it to point at a local build.").option("--selector <sel>", "CSS selector for the section to compare. Required unless --task.").option("--task <dir>", "A cockpit task dir (.parity/tasks/<id>): takes the page, the prod/cand pair and the exact frame size the reviewer saw. Explicit flags override it.").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, cmd) => {
78803
+ let fromTask = null;
78804
+ if (opts.task) {
78805
+ try {
78806
+ fromTask = sectionArgsFromTask(opts.task);
78807
+ } catch (err) {
78808
+ console.error(err.message);
78809
+ process.exit(2);
78810
+ }
78811
+ }
78812
+ const pick = (flag, task) => flag ?? task;
78813
+ const prod = pick(opts.prod, fromTask?.prod);
78814
+ const cand = pick(opts.cand, fromTask?.cand);
78815
+ const selector = pick(opts.selector, fromTask?.selector);
78816
+ if (!prod || !cand || !selector) {
78817
+ console.error("section needs --prod, --cand and --selector (or --task <dir>)");
78818
+ process.exit(2);
78819
+ }
78820
+ const viewportTyped = cmd.getOptionValueSource("viewport") === "cli";
76541
78821
  process.exit(await sectionCommand({
76542
78822
  planDir: opts.planDir,
76543
- prod: opts.prod,
76544
- cand: opts.cand,
76545
- selector: opts.selector,
76546
- candSelector: opts.candSelector,
78823
+ prod,
78824
+ cand,
78825
+ selector,
78826
+ candSelector: pick(opts.candSelector, fromTask?.candSelector),
78827
+ ...fromTask?.viewportSize && !viewportTyped ? { viewportSize: fromTask.viewportSize } : {},
76547
78828
  outputHtml: opts.all ? true : opts.outputHtml,
76548
78829
  screenshot: opts.all ? true : opts.screenshot,
76549
78830
  computedStyles: opts.all ? true : opts.computedStyles,
@@ -76552,12 +78833,22 @@ program.command("section").description("Focused prod×cand comparison of one sec
76552
78833
  cssSource: opts.all ? true : opts.cssSource,
76553
78834
  prompt: opts.all ? true : opts.prompt,
76554
78835
  llmSummary: opts.all ? Boolean(opts.llm) : opts.llmSummary,
76555
- viewport: opts.viewport,
78836
+ viewport: viewportTyped || !fromTask ? opts.viewport : fromTask.viewport,
76556
78837
  wait: opts.wait,
76557
78838
  outDir: opts.outDir,
76558
78839
  json: opts.json
76559
78840
  }));
76560
78841
  });
78842
+ program.command("ios").description("Render in REAL Mobile Safari (Xcode iOS Simulator) — one page (--url) or prod × cand (--prod/--cand, or --task <dir>) with a pixel diff. --selector scrolls the element into view first. Boots the Simulator if needed and shuts down what it booted; exit 2 when Xcode is missing (nothing measured).").option("--url <url>", "One page to render").option("--prod <url>", "Production page URL").option("--cand <url>", "Candidate page URL (a local preview works: the Simulator reaches the Mac's localhost)").option("--selector <sel>", "Element to scroll into view (prod side, or the only side)").option("--cand-selector <sel>", "Element on the candidate side, when it differs").option("--task <dir>", "A cockpit task dir: takes the page and the prod/cand pair from it").option("--device <name>", "Simulator device", "iPhone 17").option("--wait <ms>", "Wait after opening each page", "12000").option("--out-dir <dir>", "Where the screenshots go", "./parity-output/ios").option("--json", "Emit one-line JSON", false).action(async (opts) => {
78843
+ process.exit(await iosCommand(opts));
78844
+ });
78845
+ program.command("pair").description("Given one element on one side, find the same element on the other side — the cockpit's click-to-pair, from the CLI. Prints a reload-stable selector for both, the match method (text/image/position) and both boxes. Exit 2 on no match or an ambiguous one; pass the pair to `parity section --selector … --cand-selector …`.").requiredOption("--prod <url>", "Production page URL").requiredOption("--cand <url>", "Candidate page URL").requiredOption("--selector <sel>", "The element you have, on --side").option("--side <side>", "Which side --selector is on: prod | cand", "cand").option("--viewport <viewport>", "mobile | tablet | desktop", "desktop").option("--wait <ms>", "Extra ms after load so hydration settles", "1500").option("--json", "Emit one-line JSON", false).action(async (opts) => {
78846
+ if (opts.side !== "prod" && opts.side !== "cand") {
78847
+ console.error("--side must be prod or cand");
78848
+ process.exit(2);
78849
+ }
78850
+ process.exit(await pairCommand(opts));
78851
+ });
76561
78852
  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) => {
76562
78853
  process.exit(await cockpitCommand({
76563
78854
  dir: opts.dir,