@piwitests/reporter 0.64.0 → 0.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -602,8 +602,14 @@ function hasBlockingFindings(findings) {
602
602
  var import_node_child_process = require("child_process");
603
603
  var fs3 = __toESM(require("fs"));
604
604
  var import_node_module = require("module");
605
+ var os = __toESM(require("os"));
605
606
  var path5 = __toESM(require("path"));
606
607
  var COULD_NOT_START = 2;
608
+ function childExitCode(code, signal) {
609
+ if (code !== null) return code;
610
+ const number = signal ? os.constants.signals[signal] : void 0;
611
+ return number === void 0 ? COULD_NOT_START : 128 + number;
612
+ }
607
613
  function resolvePlaywrightCli(cwd = process.cwd()) {
608
614
  const require2 = (0, import_node_module.createRequire)(path5.join(cwd, "noop.js"));
609
615
  for (const id of ["playwright/cli", "@playwright/test/cli", "playwright/lib/cli/cli"]) {
@@ -658,7 +664,10 @@ function spawnPlaywright(playwrightArgs2, env, options = {}) {
658
664
  console.error(`${label}: could not start Playwright \u2014 ${err.message}`);
659
665
  done(COULD_NOT_START);
660
666
  });
661
- child.on("exit", (code) => done(code ?? COULD_NOT_START));
667
+ child.on("exit", (code, signal) => {
668
+ if (signal) console.error(`${label}: Playwright was stopped by ${signal}`);
669
+ done(childExitCode(code, signal));
670
+ });
662
671
  });
663
672
  }
664
673
  function runPackageManager(command, args, cwd) {
@@ -797,10 +806,10 @@ var path8 = __toESM(require("path"));
797
806
 
798
807
  // src/internal/config/desktop.ts
799
808
  var fs4 = __toESM(require("fs"));
800
- var os = __toESM(require("os"));
809
+ var os2 = __toESM(require("os"));
801
810
  var path7 = __toESM(require("path"));
802
811
  function defaultDesktopConfigPath() {
803
- return path7.join(os.homedir(), ".piwi", "desktop.json");
812
+ return path7.join(os2.homedir(), ".piwi", "desktop.json");
804
813
  }
805
814
  function processAlive(pid) {
806
815
  try {
@@ -877,6 +886,35 @@ function detectCi(env) {
877
886
  );
878
887
  }
879
888
 
889
+ // ../core/src/rerun-args.ts
890
+ var RERUN_ARGS_ENV = "PIWI_RERUN_ARGS";
891
+ var WHITESPACE = /[ \t\r\n]/;
892
+ function splitRerunArgs(text) {
893
+ const words = [];
894
+ let word = "";
895
+ let inWord = false;
896
+ let quoted2 = false;
897
+ for (const ch of text) {
898
+ if (quoted2) {
899
+ if (ch === '"') quoted2 = false;
900
+ else word += ch;
901
+ } else if (ch === '"') {
902
+ quoted2 = true;
903
+ inWord = true;
904
+ } else if (WHITESPACE.test(ch)) {
905
+ if (inWord) words.push(word);
906
+ word = "";
907
+ inWord = false;
908
+ } else {
909
+ word += ch;
910
+ inWord = true;
911
+ }
912
+ }
913
+ if (quoted2) throw new Error("a double quote is not closed");
914
+ if (inWord) words.push(word);
915
+ return words;
916
+ }
917
+
880
918
  // src/internal/config/env.ts
881
919
  var DEFAULTS = {
882
920
  projectName: "default-project",
@@ -1022,6 +1060,26 @@ function desktopAppMode(option, envValue) {
1022
1060
  return "fallback";
1023
1061
  }
1024
1062
 
1063
+ // src/internal/transport/http-client.ts
1064
+ var https = __toESM(require("https"));
1065
+ var http = __toESM(require("http"));
1066
+ var import_node_url2 = require("url");
1067
+ var import_form_data = __toESM(require("form-data"));
1068
+ var FAILURE_DETAIL_MAX = 500;
1069
+ function failureDetail(res) {
1070
+ let text = null;
1071
+ try {
1072
+ const body = JSON.parse(res.text);
1073
+ text = typeof body?.message === "string" ? body.message : body?.statusMessage;
1074
+ } catch {
1075
+ if (/^text\/plain\b/i.test(res.headers["content-type"] ?? "")) text = res.text;
1076
+ }
1077
+ if (typeof text !== "string") return null;
1078
+ const line = text.replace(/[\p{Cc}\s]+/gu, " ").trim();
1079
+ if (!line) return null;
1080
+ return line.length > FAILURE_DETAIL_MAX ? `${line.slice(0, FAILURE_DETAIL_MAX - 1)}\u2026` : line;
1081
+ }
1082
+
1025
1083
  // src/internal/support/connection.ts
1026
1084
  var fs6 = __toESM(require("fs"));
1027
1085
  var path9 = __toESM(require("path"));
@@ -1095,6 +1153,7 @@ function resolveCliConnection(flags, env, dirs, command = "piwi") {
1095
1153
  var EXIT_OK2 = 0;
1096
1154
  var EXIT_RUN_FAILED = 1;
1097
1155
  var EXIT_ERROR2 = 2;
1156
+ var STOPPED_BY_SIGNAL = 128;
1098
1157
  var REQUEST_TIMEOUT_MS = 3e4;
1099
1158
  var USAGE2 = `
1100
1159
  piwi bug \u2014 a bug report's failing test, from the dashboard
@@ -1117,8 +1176,9 @@ Options:
1117
1176
 
1118
1177
  Exit codes: 0 printed or written (and, when run, the test behaved as its
1119
1178
  test.fail() expects: the bug reproduces), 1 the run did not (the bug may be
1120
- fixed, or a step no longer matches the page), 2 the report could not be read
1121
- or the file could not be written.
1179
+ fixed, or a step no longer matches the page), 2 the report could not be read,
1180
+ the file could not be written, or Playwright could not start or was stopped
1181
+ by a signal.
1122
1182
  `.trim();
1123
1183
  var VALUE_FLAGS = /* @__PURE__ */ new Set(["--out", "--server-url", "--api-key"]);
1124
1184
  function readOption2(argv, name) {
@@ -1176,7 +1236,12 @@ async function fetchBugSpec(args, specDir) {
1176
1236
  throw new Error(`could not reach ${args.serverUrl} (${e.message})`);
1177
1237
  }
1178
1238
  if (res.status === 404) throw new Error(`no bug report #${args.id} on ${args.serverUrl}`);
1179
- if (res.status === 401 || res.status === 403) throw new Error(`the dashboard refused the API key (${res.status})`);
1239
+ if (res.status === 401) throw new Error("the dashboard refused the API key (401)");
1240
+ if (res.status === 403) {
1241
+ const contentType = res.headers.get("content-type") ?? void 0;
1242
+ const detail = failureDetail({ text: await res.text().catch(() => ""), headers: { "content-type": contentType } });
1243
+ throw new Error(`the dashboard refused the request (403)${detail ? `: ${detail}` : ""}`);
1244
+ }
1180
1245
  if (!res.ok) throw new Error(`the dashboard answered ${res.status}`);
1181
1246
  const body = await res.json();
1182
1247
  if (typeof body.code !== "string" || typeof body.path !== "string") throw new Error("the dashboard sent no spec");
@@ -1192,9 +1257,9 @@ function realFolder(dir) {
1192
1257
  return path10.join(fs7.realpathSync(current), ...rest);
1193
1258
  }
1194
1259
  function folderInRepository(root, dir) {
1195
- const relative8 = path10.relative(realFolder(root), realFolder(dir));
1196
- if (relative8.startsWith("..") || path10.isAbsolute(relative8)) return void 0;
1197
- return relative8.split(path10.sep).join("/");
1260
+ const relative9 = path10.relative(realFolder(root), realFolder(dir));
1261
+ if (relative9.startsWith("..") || path10.isAbsolute(relative9)) return void 0;
1262
+ return relative9.split(path10.sep).join("/");
1198
1263
  }
1199
1264
  function fileFilter(file) {
1200
1265
  const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -1250,6 +1315,7 @@ ${USAGE2}`);
1250
1315
  if (!args.run) return EXIT_OK2;
1251
1316
  const code = await runPlaywright(file, cwd, args.id, env);
1252
1317
  if (code === EXIT_ERROR2 && !resolvePlaywrightCli(cwd)) return EXIT_ERROR2;
1318
+ if (code >= STOPPED_BY_SIGNAL) return EXIT_ERROR2;
1253
1319
  if (code === 0) {
1254
1320
  console.error(
1255
1321
  args.mode === "commit" ? `piwi bug: the bug reproduces \u2014 the spec fails on it, as test.fail() expects. Commit ${shown}; remove test.fail() with the fix.` : "piwi bug: the spec passed \u2014 the bug does not show here."
@@ -1289,21 +1355,73 @@ var VALUE_MATCHERS = /* @__PURE__ */ new Set([
1289
1355
  "toHaveCount"
1290
1356
  ]);
1291
1357
 
1358
+ // ../core/src/glob.ts
1359
+ function dotTakes(char) {
1360
+ return char !== "\n" && char !== "\r" && char !== "\u2028" && char !== "\u2029";
1361
+ }
1362
+ function canonicalize(char) {
1363
+ const upper = char.toUpperCase();
1364
+ if (upper.length !== 1) return char;
1365
+ return char.charCodeAt(0) >= 128 && upper.charCodeAt(0) < 128 ? char : upper;
1366
+ }
1367
+ function globTokens(pattern, syntax) {
1368
+ const tokens = [];
1369
+ for (let i = 0; i < pattern.length; i++) {
1370
+ const char = pattern[i];
1371
+ if (char === "*") {
1372
+ const globstar = !!syntax.segments && pattern[i + 1] === "*";
1373
+ if (globstar) i++;
1374
+ tokens.push({ kind: "run", slash: !syntax.segments || globstar });
1375
+ } else if (char === "?" && syntax.questionMark) {
1376
+ tokens.push({ kind: "one", slash: !syntax.segments });
1377
+ } else {
1378
+ tokens.push({ kind: "char", char });
1379
+ }
1380
+ }
1381
+ return tokens;
1382
+ }
1383
+ function compileGlob(tokens, ignoreCase = false) {
1384
+ const steps = ignoreCase ? tokens.map((token) => token.kind === "char" ? { ...token, char: canonicalize(token.char) } : token) : tokens;
1385
+ const end = steps.length;
1386
+ return (text) => {
1387
+ const seen = new Int32Array(end + 1).fill(-1);
1388
+ let current = [];
1389
+ let next = [];
1390
+ const reach = (list, from, step) => {
1391
+ for (let state = from; seen[state] !== step; state++) {
1392
+ seen[state] = step;
1393
+ list.push(state);
1394
+ if (state === end || steps[state].kind !== "run") break;
1395
+ }
1396
+ };
1397
+ reach(current, 0, 0);
1398
+ for (let i = 0; i < text.length; i++) {
1399
+ const char = ignoreCase ? canonicalize(text[i]) : text[i];
1400
+ const dot = dotTakes(char);
1401
+ for (const state of current) {
1402
+ if (state === end) continue;
1403
+ const token = steps[state];
1404
+ const takes = token.kind === "char" ? token.char === char : token.slash ? dot : char !== "/";
1405
+ if (takes) reach(next, token.kind === "run" ? state : state + 1, i + 1);
1406
+ }
1407
+ if (next.length === 0) return false;
1408
+ [current, next] = [next, current];
1409
+ next.length = 0;
1410
+ }
1411
+ return seen[end] === text.length;
1412
+ };
1413
+ }
1414
+ function globMatcher(pattern, syntax = {}) {
1415
+ return compileGlob(globTokens(pattern, syntax), syntax.ignoreCase);
1416
+ }
1417
+
1292
1418
  // ../core/src/function-match.ts
1293
1419
  function paramArgKey(source) {
1294
1420
  return source.path ? `${source.param}.${source.path}` : source.param;
1295
1421
  }
1296
- function globToRegExp(glob) {
1297
- const escaped = glob.split("**").map((part) => part.replace(/[.?+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*")).join(".*");
1298
- return new RegExp(`^${escaped}$`);
1299
- }
1300
1422
  function urlMatches(pattern, url) {
1301
1423
  if (!pattern) return true;
1302
- try {
1303
- return globToRegExp(pattern).test(url);
1304
- } catch {
1305
- return true;
1306
- }
1424
+ return globMatcher(pattern, { segments: true })(url);
1307
1425
  }
1308
1426
  function scoreTargetMatch(pattern, candidate) {
1309
1427
  if (!candidate) return pattern.role || pattern.testId || pattern.name ? 0 : 0.3;
@@ -3150,28 +3268,45 @@ function segmentMatches(pattern, segment) {
3150
3268
  while (pattern[p] === "*") p++;
3151
3269
  return p === pattern.length;
3152
3270
  }
3271
+ var LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
3272
+ function cleanTails(parts) {
3273
+ const clean = new Uint8Array(parts.length + 1);
3274
+ clean[parts.length] = 1;
3275
+ for (let j = parts.length - 1; j >= 0; j--) clean[j] = clean[j + 1] && !LINE_TERMINATOR.test(parts[j]) ? 1 : 0;
3276
+ return clean;
3277
+ }
3153
3278
  function pathPatternMatcher(pattern) {
3154
3279
  const { segments, floating } = patternParts(pattern);
3155
3280
  if (floating) {
3156
3281
  const only = segments[0];
3157
- return (path25) => path25.split("/").some((part) => segmentMatches(only, part));
3282
+ if (only === "**") return (path25) => !LINE_TERMINATOR.test(path25);
3283
+ return (path25) => {
3284
+ const parts = path25.split("/");
3285
+ const clean = cleanTails(parts);
3286
+ for (let j = 0; j < parts.length; j++) {
3287
+ if (segmentMatches(only, parts[j]) && clean[j + 1]) return true;
3288
+ if (LINE_TERMINATOR.test(parts[j])) return false;
3289
+ }
3290
+ return false;
3291
+ };
3158
3292
  }
3159
3293
  return (path25) => {
3160
3294
  const parts = path25.split("/");
3295
+ const clean = cleanTails(parts);
3161
3296
  let at = new Uint8Array(parts.length);
3162
3297
  at[0] = 1;
3163
3298
  for (let i = 0; i < segments.length; i++) {
3164
3299
  const segment = segments[i];
3165
3300
  const isLast = i === segments.length - 1;
3166
3301
  if (segment === "**") {
3167
- if (isLast) return at.includes(1);
3302
+ if (isLast) return at.some((reached, j) => reached === 1 && clean[j] === 1);
3168
3303
  for (let j = 1; j < parts.length; j++) if (at[j - 1] && parts[j - 1] !== "") at[j] = 1;
3169
3304
  continue;
3170
3305
  }
3171
3306
  const next = new Uint8Array(parts.length);
3172
3307
  for (let j = 0; j < parts.length; j++) {
3173
3308
  if (!at[j] || !segmentMatches(segment, parts[j])) continue;
3174
- if (isLast) return true;
3309
+ if (isLast && clean[j + 1]) return true;
3175
3310
  if (j + 1 < parts.length) next[j + 1] = 1;
3176
3311
  }
3177
3312
  at = next;
@@ -3241,6 +3376,7 @@ function compileCoverageScope(scope) {
3241
3376
 
3242
3377
  // src/internal/collect/metadata-collector.ts
3243
3378
  var import_node_child_process3 = require("child_process");
3379
+ var import_node_util = require("util");
3244
3380
 
3245
3381
  // src/internal/support/errors.ts
3246
3382
  function errorMessage(error) {
@@ -3248,6 +3384,31 @@ function errorMessage(error) {
3248
3384
  return String(error);
3249
3385
  }
3250
3386
 
3387
+ // ../core/src/run-view.ts
3388
+ var MAX_VIEW_FRAME = 384 * 1024;
3389
+ var MAX_VIEW_FRAME_BASE64 = 4 * Math.ceil(MAX_VIEW_FRAME / 3);
3390
+
3391
+ // ../core/src/run-channel.ts
3392
+ var RUN_INTENTS = ["pick", "record", "assert", "assert-region"];
3393
+ var RUN_TAKES = [
3394
+ ...RUN_INTENTS,
3395
+ "requests",
3396
+ "mock",
3397
+ "locator",
3398
+ "view",
3399
+ "input",
3400
+ "input-clicks",
3401
+ "pick-at",
3402
+ "agent",
3403
+ "events",
3404
+ "bind",
3405
+ "end",
3406
+ "share"
3407
+ ];
3408
+ var MAX_KEPT_BODY = 256 * 1024;
3409
+ var MAX_REGION_SNAPSHOT = 1024 * 1024;
3410
+ var MAX_AGENT_SNAPSHOT = 1024 * 1024;
3411
+
3251
3412
  // src/internal/support/test-paths.ts
3252
3413
  var path12 = __toESM(require("path"));
3253
3414
 
@@ -3844,8 +4005,8 @@ function relativeTo(path25, root) {
3844
4005
  const head = path25.slice(0, base.length);
3845
4006
  const inside = drive ? head.toLowerCase() === base.toLowerCase() : head === base;
3846
4007
  if (!inside) return null;
3847
- const relative8 = path25.slice(base.length);
3848
- return relative8 || null;
4008
+ const relative9 = path25.slice(base.length);
4009
+ return relative9 || null;
3849
4010
  }
3850
4011
  function reportPathCandidates(raw, { repoRoot, bases }) {
3851
4012
  const slash = (value) => value.replace(/\\/g, "/");
@@ -3856,8 +4017,8 @@ function reportPathCandidates(raw, { repoRoot, bases }) {
3856
4017
  const add = (absolute) => {
3857
4018
  const normalized = normalizeSlashPath(absolute);
3858
4019
  if (!normalized) return;
3859
- const relative8 = normalized.startsWith("/_/") ? normalized.slice(3) : relativeTo(normalized, root);
3860
- if (relative8 && !out.includes(relative8)) out.push(relative8);
4020
+ const relative9 = normalized.startsWith("/_/") ? normalized.slice(3) : relativeTo(normalized, root);
4021
+ if (relative9 && !out.includes(relative9)) out.push(relative9);
3861
4022
  };
3862
4023
  if (isAbsolutePath(path25)) {
3863
4024
  add(path25);
@@ -4268,7 +4429,7 @@ ${USAGE4}`);
4268
4429
  // src/cli/flake.ts
4269
4430
  var import_node_child_process6 = require("child_process");
4270
4431
  var fs12 = __toESM(require("fs"));
4271
- var os2 = __toESM(require("os"));
4432
+ var os3 = __toESM(require("os"));
4272
4433
  var path17 = __toESM(require("path"));
4273
4434
 
4274
4435
  // ../core/src/error-parse.ts
@@ -4636,21 +4797,21 @@ function formatP(p) {
4636
4797
  }
4637
4798
  var FlakeError = class extends Error {
4638
4799
  };
4639
- async function getJson(http, url) {
4640
- const res = await fetch(`${http.serverUrl}${url}`, { headers: http.headers });
4800
+ async function getJson(http2, url) {
4801
+ const res = await fetch(`${http2.serverUrl}${url}`, { headers: http2.headers });
4641
4802
  if (!res.ok) {
4642
4803
  const body = await res.json().catch(() => ({}));
4643
4804
  throw new FlakeError(body.message || `the dashboard returned ${res.status} for ${url.split("?")[0]}`);
4644
4805
  }
4645
4806
  return await res.json();
4646
4807
  }
4647
- async function resolveTestCase(http, test, project, apiKey) {
4808
+ async function resolveTestCase(http2, test, project, apiKey) {
4648
4809
  if (/^\d+$/.test(test)) return Number(test);
4649
4810
  const m = /^(.+):(\d+)$/.exec(test);
4650
4811
  if (!m) throw new FlakeError(`"${test}" is neither a test case id nor file:line`);
4651
- const projectId = await resolveProjectId({ serverUrl: http.serverUrl, apiKey, project, key: "" });
4812
+ const projectId = await resolveProjectId({ serverUrl: http2.serverUrl, apiKey, project, key: "" });
4652
4813
  const found = await getJson(
4653
- http,
4814
+ http2,
4654
4815
  `/api/projects/${projectId}/flake-lab/test?location=${encodeURIComponent(`${m[1].replace(/\\/g, "/")}:${m[2]}`)}`
4655
4816
  );
4656
4817
  return found.testCaseId;
@@ -4848,7 +5009,7 @@ function printHeader(plan, commit, estimate, budgetMs) {
4848
5009
  out.push("");
4849
5010
  const estimateText = estimate != null ? `up to ${formatDuration(estimate)}` : "unknown (no passing run on record)";
4850
5011
  out.push(`Estimate: ${estimateText} \xB7 budget ${formatDuration(budgetMs)}`);
4851
- out.push(`Lab \xB7 ${os2.hostname()} \xB7 HEAD ${short(commit)} \xB7 ${plan.test.project ?? "default project"} \xB7 retries off`);
5012
+ out.push(`Lab \xB7 ${os3.hostname()} \xB7 HEAD ${short(commit)} \xB7 ${plan.test.project ?? "default project"} \xB7 retries off`);
4852
5013
  if (commitsDiffer(commit, plan.failureCommit)) {
4853
5014
  out.push(`warning: this checkout is ${short(commit)}; the latest failure ran on ${short(plan.failureCommit)}.`);
4854
5015
  }
@@ -4880,21 +5041,21 @@ async function loadPlan(args, commit) {
4880
5041
  "no dashboard to read the plan from: pass --server-url or set PIWI_DASHBOARD_URL (or run it offline with --plan <file>)"
4881
5042
  );
4882
5043
  }
4883
- const http = {
5044
+ const http2 = {
4884
5045
  serverUrl: connection.serverUrl,
4885
5046
  headers: connection.apiKey ? { "X-API-Key": connection.apiKey } : {}
4886
5047
  };
4887
5048
  try {
4888
- const testCaseId = await resolveTestCase(http, args.test, connection.project, connection.apiKey);
5049
+ const testCaseId = await resolveTestCase(http2, args.test, connection.project, connection.apiKey);
4889
5050
  const params = new URLSearchParams({
4890
5051
  kind: args.verify ? "verify" : "reproduce",
4891
5052
  source: args.source ?? (process.env.CI ? "ci" : "cli"),
4892
- machine: os2.hostname(),
5053
+ machine: os3.hostname(),
4893
5054
  record: String(args.upload)
4894
5055
  });
4895
5056
  if (commit) params.set("commit", commit);
4896
5057
  if (args.runs) params.set("runs", String(args.runs));
4897
- return { plan: await getJson(http, `/api/test-cases/${testCaseId}/flake-plan?${params}`), http };
5058
+ return { plan: await getJson(http2, `/api/test-cases/${testCaseId}/flake-plan?${params}`), http: http2 };
4898
5059
  } catch (error) {
4899
5060
  if (error instanceof FlakeError) throw error;
4900
5061
  throw new FlakeError(
@@ -4927,9 +5088,9 @@ async function runFlake(argv, runner) {
4927
5088
  }
4928
5089
  const commit = gitHead();
4929
5090
  let plan;
4930
- let http;
5091
+ let http2;
4931
5092
  try {
4932
- ({ plan, http } = await loadPlan(args, commit));
5093
+ ({ plan, http: http2 } = await loadPlan(args, commit));
4933
5094
  } catch (error) {
4934
5095
  console.error(`piwi flake: ${error.message}`);
4935
5096
  return EXIT_ERROR5;
@@ -4952,7 +5113,7 @@ async function runFlake(argv, runner) {
4952
5113
  if (!args.json) {
4953
5114
  printHeader(plan, commit, estimate, args.budgetMs);
4954
5115
  }
4955
- const dir = fs12.mkdtempSync(path17.join(os2.tmpdir(), "piwi-flake-"));
5116
+ const dir = fs12.mkdtempSync(path17.join(os3.tmpdir(), "piwi-flake-"));
4956
5117
  const log = path17.join(dir, "playwright.log");
4957
5118
  let session;
4958
5119
  try {
@@ -4976,11 +5137,11 @@ ${tail}`);
4976
5137
  const { verdict, reproducingArm } = sessionVerdict(plan.kind, session.arms);
4977
5138
  const ran = [session.control, ...session.arms.filter((a) => !a.skipped)];
4978
5139
  let uploaded = false;
4979
- if (args.upload && http && plan.experimentId) {
5140
+ if (args.upload && http2 && plan.experimentId) {
4980
5141
  try {
4981
- const res = await fetch(`${http.serverUrl}/api/projects/${plan.projectId}/flake-lab/results`, {
5142
+ const res = await fetch(`${http2.serverUrl}/api/projects/${plan.projectId}/flake-lab/results`, {
4982
5143
  method: "POST",
4983
- headers: { "Content-Type": "application/json", ...http.headers },
5144
+ headers: { "Content-Type": "application/json", ...http2.headers },
4984
5145
  body: JSON.stringify({
4985
5146
  experimentId: plan.experimentId,
4986
5147
  commit,
@@ -5236,15 +5397,20 @@ async function runGate(argv, env = process.env, cwd = process.cwd()) {
5236
5397
  if (argv.includes("--json")) {
5237
5398
  console.log(JSON.stringify(result, null, 2));
5238
5399
  } else {
5239
- console.log(formatGateResult(result));
5400
+ const { runUrl } = result.facts;
5401
+ const link = runUrl.startsWith("/") ? `${args.serverUrl}${runUrl}` : runUrl;
5402
+ console.log(formatGateResult({ ...result, facts: { ...result.facts, runUrl: link } }));
5240
5403
  }
5241
5404
  if (result.verdict === "inconclusive") return EXIT_INCONCLUSIVE;
5242
5405
  return result.passed ? EXIT_OK5 : EXIT_VIOLATED;
5243
5406
  }
5244
5407
 
5245
5408
  // src/cli/init.ts
5409
+ var import_node_child_process7 = require("child_process");
5246
5410
  var fs16 = __toESM(require("fs"));
5247
5411
  var path20 = __toESM(require("path"));
5412
+ var readline = __toESM(require("readline"));
5413
+ var tty = __toESM(require("tty"));
5248
5414
 
5249
5415
  // src/cli/report.ts
5250
5416
  var STATUS_MARK = {
@@ -5287,13 +5453,25 @@ function readPackageJson(root) {
5287
5453
  return { pkg: null, pkgPath: null };
5288
5454
  }
5289
5455
  }
5290
- function detectPackageManager(root, pkg) {
5456
+ function declaredPackageManager(dir, pkg) {
5291
5457
  const declared = pkg?.packageManager?.split("@")[0];
5292
5458
  if (declared === "pnpm" || declared === "yarn" || declared === "bun" || declared === "npm") return declared;
5293
5459
  for (const [file, manager] of LOCKFILES) {
5294
- if (fs14.existsSync(path18.join(root, file))) return manager;
5460
+ if (fs14.existsSync(path18.join(dir, file))) return manager;
5461
+ }
5462
+ return null;
5463
+ }
5464
+ function detectPackageManager(root, pkg) {
5465
+ let dir = root;
5466
+ let dirPkg = pkg;
5467
+ for (; ; ) {
5468
+ const manager = declaredPackageManager(dir, dirPkg);
5469
+ if (manager) return manager;
5470
+ const parent = path18.dirname(dir);
5471
+ if (parent === dir || fs14.existsSync(path18.join(dir, ".git"))) return "npm";
5472
+ dir = parent;
5473
+ dirPkg = readPackageJson(dir).pkg;
5295
5474
  }
5296
- return "npm";
5297
5475
  }
5298
5476
  function findConfig(root) {
5299
5477
  for (const name of CONFIG_NAMES2) {
@@ -5314,6 +5492,91 @@ function hasReporter(pkg) {
5314
5492
  if (!pkg) return false;
5315
5493
  return Boolean(pkg.dependencies?.[REPORTER_PACKAGE] || pkg.devDependencies?.[REPORTER_PACKAGE]);
5316
5494
  }
5495
+ function stringList(value) {
5496
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
5497
+ }
5498
+ function yamlScalar(text) {
5499
+ const value = text.trim();
5500
+ const quoted2 = /^(['"])(.*?)\1/.exec(value);
5501
+ return quoted2 ? quoted2[2] : value.replace(/\s+#.*$/, "").trim();
5502
+ }
5503
+ function pnpmWorkspaceGlobs(yaml) {
5504
+ const flow = /^packages\s*:\s*\[([^\]]*)\]/m.exec(yaml);
5505
+ if (flow) return flow[1].split(",").map(yamlScalar).filter(Boolean);
5506
+ const lines = yaml.split(/\r?\n/);
5507
+ const start = lines.findIndex((line) => /^packages\s*:\s*(#.*)?$/.test(line));
5508
+ if (start === -1) return [];
5509
+ const globs = [];
5510
+ for (const line of lines.slice(start + 1)) {
5511
+ if (/^\s*(#.*)?$/.test(line)) continue;
5512
+ const item = /^\s*-\s+(.*)$/.exec(line);
5513
+ if (!item) break;
5514
+ globs.push(yamlScalar(item[1]));
5515
+ }
5516
+ return globs.filter(Boolean);
5517
+ }
5518
+ function workspaceGlobs(root, pkg) {
5519
+ const declared = pkg?.workspaces;
5520
+ const globs = stringList(
5521
+ typeof declared === "object" && declared !== null && "packages" in declared ? declared.packages : declared
5522
+ );
5523
+ try {
5524
+ globs.push(...pnpmWorkspaceGlobs(fs14.readFileSync(path18.join(root, "pnpm-workspace.yaml"), "utf-8")));
5525
+ } catch {
5526
+ }
5527
+ return globs;
5528
+ }
5529
+ function isDirectory(dir) {
5530
+ try {
5531
+ return fs14.statSync(dir).isDirectory();
5532
+ } catch {
5533
+ return false;
5534
+ }
5535
+ }
5536
+ function subfolders(dir) {
5537
+ try {
5538
+ return fs14.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "node_modules" && !entry.name.startsWith(".")).map((entry) => path18.join(dir, entry.name));
5539
+ } catch {
5540
+ return [];
5541
+ }
5542
+ }
5543
+ function namePattern(segment) {
5544
+ const source = segment.split(/([*?])/).map((part) => part === "*" ? ".*" : part === "?" ? "." : part.replace(/[.+^${}()|[\]\\]/g, "\\$&")).join("");
5545
+ return new RegExp(`^${source}$`);
5546
+ }
5547
+ function expandGlob(root, glob) {
5548
+ const segments = glob.split("/").filter((segment) => segment !== "" && segment !== ".");
5549
+ const found = [];
5550
+ const walk = (dir, index) => {
5551
+ if (index === segments.length) {
5552
+ found.push(dir);
5553
+ return;
5554
+ }
5555
+ const segment = segments[index];
5556
+ if (segment === "**") {
5557
+ walk(dir, index + 1);
5558
+ for (const child of subfolders(dir)) walk(child, index);
5559
+ } else if (/[*?]/.test(segment)) {
5560
+ const pattern = namePattern(segment);
5561
+ for (const child of subfolders(dir)) if (pattern.test(path18.basename(child))) walk(child, index + 1);
5562
+ } else if (isDirectory(path18.join(dir, segment))) {
5563
+ walk(path18.join(dir, segment), index + 1);
5564
+ }
5565
+ };
5566
+ walk(root, 0);
5567
+ return found;
5568
+ }
5569
+ function workspacePackagesWithConfig(root) {
5570
+ const absRoot = path18.resolve(root);
5571
+ const globs = workspaceGlobs(absRoot, readPackageJson(absRoot).pkg);
5572
+ const excluded = new Set(
5573
+ globs.filter((glob) => glob.startsWith("!")).flatMap((glob) => expandGlob(absRoot, glob.slice(1)))
5574
+ );
5575
+ const packages = new Set(
5576
+ globs.filter((glob) => !glob.startsWith("!")).flatMap((glob) => expandGlob(absRoot, glob)).filter((dir) => dir !== absRoot && !excluded.has(dir) && fs14.existsSync(path18.join(dir, "package.json")))
5577
+ );
5578
+ return [...packages].filter((dir) => findConfig(dir) !== null).map((dir) => path18.relative(absRoot, dir).split(path18.sep).join("/")).sort();
5579
+ }
5317
5580
  function detectProject(root) {
5318
5581
  const absRoot = path18.resolve(root);
5319
5582
  const { pkg, pkgPath } = readPackageJson(absRoot);
@@ -5384,7 +5647,7 @@ function matchClosingParen(src, openIndex) {
5384
5647
  }
5385
5648
  function optionsLiteral(opts) {
5386
5649
  const lines = [];
5387
- if (opts.serverUrl) lines.push(` serverUrl: ${quote2(opts.serverUrl)},`);
5650
+ if (opts.serverUrl) lines.push(` serverUrl: process.env.PIWI_DASHBOARD_URL || ${quote2(opts.serverUrl)},`);
5388
5651
  lines.push(` projectName: ${quote2(opts.projectName)},`);
5389
5652
  if (opts.desktopApp) lines.push(` desktopApp: ${quote2(opts.desktopApp)},`);
5390
5653
  return `{
@@ -5440,7 +5703,7 @@ function upsertEnvKeys(existing, entries) {
5440
5703
  let text = existing;
5441
5704
  const added = [];
5442
5705
  for (const [key, value] of entries) {
5443
- if (new RegExp(`^\\s*${key}=`, "m").test(text)) continue;
5706
+ if (new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`, "m").test(text)) continue;
5444
5707
  if (text.length && !text.endsWith("\n")) text += "\n";
5445
5708
  text += `${key}=${value}
5446
5709
  `;
@@ -5448,6 +5711,28 @@ function upsertEnvKeys(existing, entries) {
5448
5711
  }
5449
5712
  return { text, added };
5450
5713
  }
5714
+ function recordDevDependency(source, name, range) {
5715
+ let pkg;
5716
+ try {
5717
+ pkg = JSON.parse(source);
5718
+ } catch {
5719
+ return { text: source, status: "manual" };
5720
+ }
5721
+ if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return { text: source, status: "manual" };
5722
+ const record = pkg;
5723
+ const listed = (field) => {
5724
+ const value = record[field];
5725
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
5726
+ };
5727
+ if (name in listed("dependencies") || name in listed("devDependencies")) return { text: source, status: "already" };
5728
+ record.devDependencies = Object.fromEntries(
5729
+ Object.entries({ ...listed("devDependencies"), [name]: range }).sort(([a], [b]) => a.localeCompare(b, "en"))
5730
+ );
5731
+ const indent = /^[ \t]+(?=")/m.exec(source)?.[0] ?? " ";
5732
+ const eol = source.includes("\r\n") ? "\r\n" : "\n";
5733
+ const text = JSON.stringify(record, null, indent).replace(/\n/g, eol) + (source.endsWith("\n") ? eol : "");
5734
+ return { text, status: "updated" };
5735
+ }
5451
5736
  function ensureGitignoreEntry(existing, entry = ".env") {
5452
5737
  const present = existing.split(/\r?\n/).some((line) => line.trim() === entry);
5453
5738
  if (present) return { text: existing, added: false };
@@ -5462,11 +5747,8 @@ function ensureGitignoreEntry(existing, entry = ".env") {
5462
5747
  var fs15 = __toESM(require("fs"));
5463
5748
  var path19 = __toESM(require("path"));
5464
5749
 
5465
- // ../core/src/skill-stamp.ts
5466
- var SKILL_VERSION_KEY = "piwi-version";
5467
- var SKILL_HASH_KEY = "piwi-hash";
5468
- var FRONT_MATTER = /^---\r?\n([\s\S]*?)\r?\n---/;
5469
- function fnv32(input, seed) {
5750
+ // ../core/src/hash.ts
5751
+ function fnv1a32(input, seed = 2166136261) {
5470
5752
  let h = seed >>> 0;
5471
5753
  for (let i = 0; i < input.length; i++) {
5472
5754
  h ^= input.charCodeAt(i);
@@ -5474,8 +5756,13 @@ function fnv32(input, seed) {
5474
5756
  }
5475
5757
  return (h >>> 0).toString(16).padStart(8, "0");
5476
5758
  }
5759
+
5760
+ // ../core/src/skill-stamp.ts
5761
+ var SKILL_VERSION_KEY = "piwi-version";
5762
+ var SKILL_HASH_KEY = "piwi-hash";
5763
+ var FRONT_MATTER = /^---\r?\n([\s\S]*?)\r?\n---/;
5477
5764
  function hash16(input) {
5478
- return fnv32(input, 2166136261) + fnv32(input, 16777619);
5765
+ return fnv1a32(input) + fnv1a32(input, 16777619);
5479
5766
  }
5480
5767
  function withoutHashLine(markdown) {
5481
5768
  return markdown.replace(new RegExp(`^${SKILL_HASH_KEY}:.*\\r?\\n`, "m"), "");
@@ -5712,6 +5999,12 @@ What it does (each step is idempotent and safe to re-run):
5712
5999
  - records PIWI_* connection settings in .env / .env.example and .gitignore
5713
6000
  - installs the Piwi agent skills so your coding agent can use them
5714
6001
 
6002
+ In a monorepo, run it in the package that holds the playwright.config, or pass
6003
+ --cwd <package>. At a workspace root with no playwright.config of its own
6004
+ ("workspaces" in package.json, or pnpm-workspace.yaml), it wires the workspace
6005
+ package that has one. When several have one, it asks which in a terminal; in CI,
6006
+ without a terminal or with --json, it wires none and lists them.
6007
+
5715
6008
  Options:
5716
6009
  --server-url <url> Dashboard URL to write into the config (env PIWI_DASHBOARD_URL,
5717
6010
  default ${DEFAULT_SERVER_URL})
@@ -5721,8 +6014,9 @@ Options:
5721
6014
  --desktop-app <mode> Write desktopApp into the config: "prefer" sends local runs to the
5722
6015
  Piwi desktop app while it runs, and CI runs to --server-url
5723
6016
  --api-key <key> API key to write into .env (env PIWI_API_KEY), where the reporter
5724
- reads it. Omit to keep it a .env.example placeholder you fill in
5725
- yourself.
6017
+ reads it; never into a .env git tracks or cannot say it does not,
6018
+ nor through a link. Omit to keep it a .env.example placeholder you
6019
+ fill in yourself.
5726
6020
  --cwd <path> Project root to operate on (default: current directory)
5727
6021
  --skills <list> Comma-separated skills to install, or "all" / "none"
5728
6022
  (default: ${WORKFLOW_SKILLS.join(", ")})
@@ -5753,15 +6047,18 @@ function resolveSkillSlugs(raw) {
5753
6047
  return raw.split(",").map((slug) => slug.trim()).filter(Boolean);
5754
6048
  }
5755
6049
  function parseInitArgs(argv, env, cwd) {
5756
- const root = path20.resolve(readOption6(argv, "--cwd") ?? cwd);
6050
+ const root = path20.resolve(cwd, readOption6(argv, "--cwd") ?? ".");
5757
6051
  const detected = detectProject(root);
6052
+ const noServerUrl = argv.includes("--no-server-url");
6053
+ const flagKey = readOption6(argv, "--api-key");
5758
6054
  return {
5759
6055
  root,
5760
- serverUrl: argv.includes("--no-server-url") ? "" : (readOption6(argv, "--server-url") ?? env.PIWI_DASHBOARD_URL ?? DEFAULT_SERVER_URL).replace(/\/$/, ""),
6056
+ serverUrl: noServerUrl ? "" : (readOption6(argv, "--server-url") ?? env.PIWI_DASHBOARD_URL ?? DEFAULT_SERVER_URL).replace(/\/$/, ""),
5761
6057
  projectName: readOption6(argv, "--project") ?? detected.suggestedProjectName,
5762
6058
  desktopApp: argv.includes("--desktop-app") ? readOption6(argv, "--desktop-app") ?? "" : null,
5763
6059
  // The desktop app needs no key, and a key with no URL keeps the reporter from finding it.
5764
- apiKey: argv.includes("--no-server-url") ? null : readOption6(argv, "--api-key") ?? env.PIWI_API_KEY ?? null,
6060
+ apiKey: noServerUrl ? null : flagKey ?? env.PIWI_API_KEY ?? null,
6061
+ apiKeyFromEnv: !noServerUrl && flagKey === void 0 && Boolean(env.PIWI_API_KEY),
5765
6062
  skillsDir: readOption6(argv, "--skills-dir") ?? DEFAULT_SKILLS_DIR,
5766
6063
  skillSlugs: resolveSkillSlugs(readOption6(argv, "--skills")),
5767
6064
  install: !argv.includes("--no-install"),
@@ -5801,8 +6098,8 @@ function stepInstallReporter(project, opts) {
5801
6098
  status: "manual",
5802
6099
  detail: `No package.json here \u2014 run \`npm init\`, then \`${installCommand(project.packageManager)}\``
5803
6100
  };
5804
- if (opts.dryRun || !opts.install)
5805
- return { step, status: "manual", detail: `Run \`${installCommand(project.packageManager)}\`` };
6101
+ if (!opts.install) return stepRecordReporter(project, opts);
6102
+ if (opts.dryRun) return { step, status: "manual", detail: `Run \`${installCommand(project.packageManager)}\`` };
5806
6103
  const [command, args] = installArgv(project.packageManager);
5807
6104
  const status = runPackageManager(command, args, opts.root);
5808
6105
  if (status === 0) return { step, status: "updated", detail: `Installed ${REPORTER_PACKAGE}` };
@@ -5812,6 +6109,28 @@ function stepInstallReporter(project, opts) {
5812
6109
  detail: `\`${installCommand(project.packageManager)}\` failed (exit ${status ?? "unknown"}) \u2014 install it by hand`
5813
6110
  };
5814
6111
  }
6112
+ function stepRecordReporter(project, opts) {
6113
+ const step = "dependency";
6114
+ const file = "package.json";
6115
+ const version = readTemplatesVersion(findTemplatesDir(__dirname));
6116
+ const range = version === "0.0.0" ? "latest" : `^${version}`;
6117
+ const pkgPath = project.packageJsonPath ?? path20.join(project.root, file);
6118
+ const edit = recordDevDependency(readFileOr(pkgPath, ""), REPORTER_PACKAGE, range);
6119
+ if (edit.status === "manual")
6120
+ return {
6121
+ step,
6122
+ file,
6123
+ status: "manual",
6124
+ detail: `Could not read package.json \u2014 run \`${installCommand(project.packageManager)}\``
6125
+ };
6126
+ if (edit.status === "updated" && !opts.dryRun) fs16.writeFileSync(pkgPath, edit.text);
6127
+ return {
6128
+ step,
6129
+ file,
6130
+ status: edit.status,
6131
+ detail: edit.status === "updated" ? `Recorded ${REPORTER_PACKAGE} ${range} in devDependencies \u2014 run \`${project.packageManager} install\` to install it` : `${REPORTER_PACKAGE} is already a dependency`
6132
+ };
6133
+ }
5815
6134
  function stepConfig(project, opts) {
5816
6135
  const step = "config";
5817
6136
  if (!project.configPath)
@@ -5865,7 +6184,44 @@ function stepFixtures(project, opts) {
5865
6184
  detail: "Created capture fixtures \u2014 import `test` from here in your specs"
5866
6185
  };
5867
6186
  }
5868
- function stepEnv(project, opts) {
6187
+ function gitTracking(root, file) {
6188
+ const { status } = (0, import_node_child_process7.spawnSync)("git", ["ls-files", "--error-unmatch", "--", file], {
6189
+ cwd: root,
6190
+ stdio: "ignore",
6191
+ windowsHide: true
6192
+ });
6193
+ if (status === 0) return "tracked";
6194
+ if (status === 1) return "untracked";
6195
+ return inRepository(root) ? "unknown" : "untracked";
6196
+ }
6197
+ function inRepository(dir) {
6198
+ for (let current = path20.resolve(dir); ; current = path20.dirname(current)) {
6199
+ if (fs16.existsSync(path20.join(current, ".git"))) return true;
6200
+ if (path20.dirname(current) === current) return false;
6201
+ }
6202
+ }
6203
+ var KEY_IN_ENVIRONMENT = "set PIWI_API_KEY in the environment (in CI, as a secret)";
6204
+ function envKeyBlock(root) {
6205
+ const tracking = gitTracking(root, ".env");
6206
+ if (tracking === "tracked") {
6207
+ return {
6208
+ why: "git tracks .env",
6209
+ instead: `${KEY_IN_ENVIRONMENT}, or untrack the file with \`git rm --cached .env\``
6210
+ };
6211
+ }
6212
+ if (tracking === "unknown") {
6213
+ return {
6214
+ why: "git did not say whether it tracks .env",
6215
+ instead: `${KEY_IN_ENVIRONMENT}, or make \`git ls-files .env\` work here`
6216
+ };
6217
+ }
6218
+ const env = fs16.lstatSync(path20.join(root, ".env"), { throwIfNoEntry: false });
6219
+ if (env && (env.isSymbolicLink() || env.nlink > 1)) {
6220
+ return { why: ".env is a link", instead: `${KEY_IN_ENVIRONMENT}, or put a file of its own in place of the link` };
6221
+ }
6222
+ return null;
6223
+ }
6224
+ function stepEnv(project, opts, envBlock) {
5869
6225
  const results = [];
5870
6226
  const examplePath = path20.join(project.root, ".env.example");
5871
6227
  const example = upsertEnvKeys(readFileOr(examplePath, ""), [
@@ -5879,7 +6235,21 @@ function stepEnv(project, opts) {
5879
6235
  status: example.added.length ? "updated" : "already",
5880
6236
  detail: example.added.length ? `Recorded ${example.added.join(", ")}` : "connection template already present"
5881
6237
  });
5882
- if (opts.apiKey) {
6238
+ if (opts.apiKey && envBlock && opts.apiKeyFromEnv) {
6239
+ results.push({
6240
+ step: "env",
6241
+ file: ".env",
6242
+ status: "already",
6243
+ detail: `PIWI_API_KEY is set in the environment, where the reporter reads it; ${envBlock.why}, so no key is written into it`
6244
+ });
6245
+ } else if (opts.apiKey && envBlock) {
6246
+ results.push({
6247
+ step: "env",
6248
+ file: ".env",
6249
+ status: "manual",
6250
+ detail: `${envBlock.why}, so the API key is not written into it \u2014 ${envBlock.instead} and run init again`
6251
+ });
6252
+ } else if (opts.apiKey) {
5883
6253
  const envPath = path20.join(project.root, ".env");
5884
6254
  const entries = [["PIWI_API_KEY", opts.apiKey]];
5885
6255
  if (opts.serverUrl) entries.unshift(["PIWI_DASHBOARD_URL", opts.serverUrl]);
@@ -5903,9 +6273,13 @@ function stepEnv(project, opts) {
5903
6273
  }
5904
6274
  return results;
5905
6275
  }
5906
- function nextSteps(opts, steps) {
6276
+ function nextSteps(opts, steps, envBlock) {
5907
6277
  const out = [];
5908
- if (!opts.apiKey && opts.serverUrl) {
6278
+ if (!opts.apiKey && opts.serverUrl && envBlock) {
6279
+ out.push(
6280
+ `If your dashboard has authentication on, create an API key (Settings \u2192 Account \u2192 API keys). ${envBlock.why}, so keep the key out of it: ${envBlock.instead}.`
6281
+ );
6282
+ } else if (!opts.apiKey && opts.serverUrl) {
5909
6283
  out.push(
5910
6284
  "If your dashboard has authentication on, create an API key (Settings \u2192 Account \u2192 API keys) and put it in .env as PIWI_API_KEY: the reporter reads it from the .env next to your Playwright config. Keep .env out of git; in CI, set PIWI_API_KEY as a secret."
5911
6285
  );
@@ -5930,23 +6304,125 @@ function nextSteps(opts, steps) {
5930
6304
  );
5931
6305
  return out;
5932
6306
  }
5933
- async function runInit(argv, env = process.env, cwd = process.cwd()) {
6307
+ function askLine(question, input, output) {
6308
+ return new Promise((resolve11) => {
6309
+ const rl = readline.createInterface({ input, output });
6310
+ rl.once("close", () => resolve11(null));
6311
+ rl.once("SIGINT", () => rl.close());
6312
+ rl.question(question, (answer) => {
6313
+ resolve11(answer);
6314
+ rl.close();
6315
+ });
6316
+ });
6317
+ }
6318
+ function terminalAsk(env, isTerminal = tty.isatty) {
6319
+ if (detectCi(env) || !isTerminal(0) || !isTerminal(1)) return null;
6320
+ return (question) => askLine(question, process.stdin, process.stdout);
6321
+ }
6322
+ async function choosePackage(packages, ask) {
6323
+ console.log(`
6324
+ No playwright.config here, and ${packages.length} workspace packages have one:
6325
+ `);
6326
+ packages.forEach((pkg, index) => console.log(` ${index + 1}. ${pkg}`));
6327
+ console.log("");
6328
+ for (; ; ) {
6329
+ const answer = (await ask(`Which one should init wire? [1-${packages.length}, Enter for none] `))?.trim();
6330
+ if (!answer) return null;
6331
+ const choice = Number(answer);
6332
+ if (Number.isInteger(choice) && choice >= 1 && choice <= packages.length) return packages[choice - 1];
6333
+ }
6334
+ }
6335
+ async function chooseWorkspacePackage(root, ask) {
6336
+ const packages = workspacePackagesWithConfig(root);
6337
+ if (!packages.length) return null;
6338
+ if (packages.length === 1) return { root, packages, wired: packages[0] };
6339
+ return { root, packages, wired: ask ? await choosePackage(packages, ask) : null };
6340
+ }
6341
+ function inPackage(opts, argv, root) {
6342
+ return { ...opts, root, projectName: readOption6(argv, "--project") ?? detectProject(root).suggestedProjectName };
6343
+ }
6344
+ function unwiredWorkspace(workspace, cwd) {
6345
+ const flags = workspace.packages.map(
6346
+ (pkg) => `\`--cwd ${path20.relative(cwd, path20.join(workspace.root, pkg)) || "."}\``
6347
+ );
6348
+ return {
6349
+ step: {
6350
+ step: "config",
6351
+ status: "manual",
6352
+ detail: `No playwright.config here; ${workspace.packages.length} workspace packages have one (${workspace.packages.join(", ")}) \u2014 run init again with \`--cwd <package>\` for the one to wire`
6353
+ },
6354
+ guidance: [
6355
+ `Run the same command again with ${flags.slice(0, -1).join(", ")} or ${flags[flags.length - 1]}, for the package to wire.`
6356
+ ]
6357
+ };
6358
+ }
6359
+ function printOutcome(opts, project, workspace, steps, guidance) {
6360
+ if (opts.json) {
6361
+ console.log(
6362
+ JSON.stringify(
6363
+ {
6364
+ dryRun: opts.dryRun,
6365
+ project: {
6366
+ root: project.root,
6367
+ packageManager: project.packageManager,
6368
+ configPath: project.configPath ? path20.relative(project.root, project.configPath) : null,
6369
+ projectName: opts.projectName,
6370
+ serverUrl: opts.serverUrl,
6371
+ desktopApp: opts.desktopApp
6372
+ },
6373
+ ...workspace ? { workspace } : {},
6374
+ steps,
6375
+ nextSteps: guidance
6376
+ },
6377
+ null,
6378
+ 2
6379
+ )
6380
+ );
6381
+ return;
6382
+ }
6383
+ if (workspace?.wired && workspace.packages.length === 1) {
6384
+ console.log(
6385
+ `
6386
+ No playwright.config here, so init wires ${workspace.wired}, the one workspace package that has one.`
6387
+ );
6388
+ }
6389
+ const where = workspace?.wired ? ` in ${workspace.wired}` : "";
6390
+ console.log(`
6391
+ Piwi setup${opts.dryRun ? " (dry run \u2014 nothing written)" : ""} for "${opts.projectName}"${where}:
6392
+ `);
6393
+ for (const step of steps) console.log(formatStep(step));
6394
+ console.log("\nNext:");
6395
+ for (const line of guidance) console.log(` \u2022 ${line}`);
6396
+ console.log("");
6397
+ }
6398
+ async function runInit(argv, env = process.env, cwd = process.cwd(), ask = terminalAsk(env)) {
5934
6399
  if (argv.includes("-h") || argv.includes("--help")) {
5935
6400
  console.log(USAGE8);
5936
6401
  return 0;
5937
6402
  }
5938
- const opts = parseInitArgs(argv, env, cwd);
6403
+ let opts = parseInitArgs(argv, env, cwd);
5939
6404
  if (opts.desktopApp !== null && !DESKTOP_APP_MODES2.includes(opts.desktopApp)) {
5940
6405
  console.error(`--desktop-app must be one of ${DESKTOP_APP_MODES2.join(", ")} (got "${opts.desktopApp}")`);
5941
6406
  return 1;
5942
6407
  }
5943
- const project = detectProject(opts.root);
6408
+ let project = detectProject(opts.root);
6409
+ const workspace = opts.skillsOnly || project.configPath ? null : await chooseWorkspacePackage(project.root, opts.json ? null : ask);
6410
+ if (workspace && !workspace.wired) {
6411
+ const { step, guidance } = unwiredWorkspace(workspace, cwd);
6412
+ printOutcome(opts, project, workspace, [step], guidance);
6413
+ return 0;
6414
+ }
6415
+ if (workspace?.wired) {
6416
+ opts = inPackage(opts, argv, path20.join(workspace.root, workspace.wired));
6417
+ project = detectProject(opts.root);
6418
+ }
5944
6419
  const steps = [];
6420
+ const envBlock = envKeyBlock(project.root);
5945
6421
  if (!opts.skillsOnly) {
5946
6422
  steps.push(stepInstallReporter(project, opts));
5947
6423
  steps.push(stepConfig(project, opts));
5948
6424
  steps.push(stepFixtures(project, opts));
5949
- steps.push(...stepEnv(project, opts));
6425
+ steps.push(...stepEnv(project, opts, envBlock));
5950
6426
  }
5951
6427
  if (!opts.noSkills && opts.skillSlugs.length) {
5952
6428
  steps.push(
@@ -5960,43 +6436,14 @@ async function runInit(argv, env = process.env, cwd = process.cwd()) {
5960
6436
  })
5961
6437
  );
5962
6438
  }
5963
- const guidance = nextSteps(opts, steps);
5964
- if (opts.json) {
5965
- console.log(
5966
- JSON.stringify(
5967
- {
5968
- dryRun: opts.dryRun,
5969
- project: {
5970
- root: project.root,
5971
- packageManager: project.packageManager,
5972
- configPath: project.configPath ? path20.relative(project.root, project.configPath) : null,
5973
- projectName: opts.projectName,
5974
- serverUrl: opts.serverUrl,
5975
- desktopApp: opts.desktopApp
5976
- },
5977
- steps,
5978
- nextSteps: guidance
5979
- },
5980
- null,
5981
- 2
5982
- )
5983
- );
5984
- } else {
5985
- console.log(`
5986
- Piwi setup${opts.dryRun ? " (dry run \u2014 nothing written)" : ""} for "${opts.projectName}":
5987
- `);
5988
- for (const step of steps) console.log(formatStep(step));
5989
- console.log("\nNext:");
5990
- for (const line of guidance) console.log(` \u2022 ${line}`);
5991
- console.log("");
5992
- }
6439
+ printOutcome(opts, project, workspace, steps, nextSteps(opts, steps, envBlock));
5993
6440
  return steps.some((s) => s.status === "error") ? 1 : 0;
5994
6441
  }
5995
6442
 
5996
6443
  // src/cli/select.ts
5997
6444
  var fs18 = __toESM(require("fs"));
5998
6445
  var path22 = __toESM(require("path"));
5999
- var import_node_child_process7 = require("child_process");
6446
+ var import_node_child_process8 = require("child_process");
6000
6447
 
6001
6448
  // ../core/src/diff-anchors.ts
6002
6449
  var RENAME_FROM = `rename from `;
@@ -6943,7 +7390,9 @@ Behavior:
6943
7390
  --json Print the full resolution as JSON (select only)
6944
7391
  -h, --help Show this help
6945
7392
 
6946
- Exit codes: 0 ok, 1 the test run failed (run only), 2 could not resolve.
7393
+ Exit codes: 0 ok, 1 the test run failed (run only), 128 plus the signal's
7394
+ number when the runner stops Playwright (run only; 143 for SIGTERM),
7395
+ 2 could not resolve or Playwright could not start.
6947
7396
  `.trim();
6948
7397
  var IMPACT_KEY = "impact";
6949
7398
  var NOTHING_TO_RUN_ARGS = ["--pass-with-no-tests", "--grep-invert", "."];
@@ -7074,7 +7523,7 @@ function printWarnings(resolution) {
7074
7523
  for (const w of resolution.warnings) console.error(`piwi: warning [${w.code}] ${w.message}`);
7075
7524
  }
7076
7525
  function git2(args) {
7077
- return (0, import_node_child_process7.execFileSync)("git", ["-c", "core.quotePath=false", ...args], {
7526
+ return (0, import_node_child_process8.execFileSync)("git", ["-c", "core.quotePath=false", ...args], {
7078
7527
  encoding: "utf-8",
7079
7528
  stdio: ["ignore", "pipe", "ignore"],
7080
7529
  maxBuffer: 256 * 1024 * 1024
@@ -7285,7 +7734,7 @@ async function runRun(argv, env = process.env) {
7285
7734
  // src/cli/preflight.ts
7286
7735
  var fs19 = __toESM(require("fs"));
7287
7736
  var path23 = __toESM(require("path"));
7288
- var import_node_child_process8 = require("child_process");
7737
+ var import_node_child_process9 = require("child_process");
7289
7738
 
7290
7739
  // ../core/src/locator-edit.ts
7291
7740
  function escapeForQuote(value, quote3) {
@@ -7408,7 +7857,7 @@ function parsePreflightArgs(argv) {
7408
7857
  };
7409
7858
  }
7410
7859
  function git3(cwd, args) {
7411
- return (0, import_node_child_process8.execFileSync)("git", args, {
7860
+ return (0, import_node_child_process9.execFileSync)("git", args, {
7412
7861
  cwd,
7413
7862
  encoding: "utf-8",
7414
7863
  stdio: ["ignore", "pipe", "pipe"],
@@ -7790,7 +8239,7 @@ async function runPreflight(argv, env = process.env, cwd = process.cwd()) {
7790
8239
 
7791
8240
  // src/cli/probe.ts
7792
8241
  var fs20 = __toESM(require("fs"));
7793
- var os3 = __toESM(require("os"));
8242
+ var os4 = __toESM(require("os"));
7794
8243
  var path24 = __toESM(require("path"));
7795
8244
  var EXIT_OK8 = 0;
7796
8245
  var EXIT_ERROR9 = 2;
@@ -7825,9 +8274,9 @@ function probePlaywrightArgs(playwrightArgs2, testTitles) {
7825
8274
  return args;
7826
8275
  }
7827
8276
  async function runProbe(argv) {
7828
- const sep6 = argv.indexOf("--");
7829
- const own = sep6 < 0 ? argv : argv.slice(0, sep6);
7830
- const playwrightArgs2 = sep6 < 0 ? [] : argv.slice(sep6 + 1);
8277
+ const sep7 = argv.indexOf("--");
8278
+ const own = sep7 < 0 ? argv : argv.slice(0, sep7);
8279
+ const playwrightArgs2 = sep7 < 0 ? [] : argv.slice(sep7 + 1);
7831
8280
  if (own.includes("-h") || own.includes("--help")) {
7832
8281
  console.log(USAGE11);
7833
8282
  return EXIT_OK8;
@@ -7872,7 +8321,7 @@ async function runProbe(argv) {
7872
8321
  return EXIT_OK8;
7873
8322
  }
7874
8323
  console.error(`piwi probe: ${plan.items.length} pair(s) to probe (budget ${plan.budget}).`);
7875
- const dir = fs20.mkdtempSync(path24.join(os3.tmpdir(), "piwi-probe-"));
8324
+ const dir = fs20.mkdtempSync(path24.join(os4.tmpdir(), "piwi-probe-"));
7876
8325
  const planFile = path24.join(dir, "plan.json");
7877
8326
  const resultsFile = path24.join(dir, "results.jsonl");
7878
8327
  const runOutputFile = path24.join(dir, "run.json");
@@ -8072,8 +8521,51 @@ async function runQualityReport(argv) {
8072
8521
  }
8073
8522
  }
8074
8523
 
8075
- // src/cli/index.ts
8524
+ // src/cli/rerun.ts
8525
+ var EXIT_ERROR11 = 2;
8076
8526
  var USAGE13 = `
8527
+ piwi rerun \u2014 run the tests a CI re-run from the dashboard asked for
8528
+
8529
+ Usage:
8530
+ npx @piwitests/reporter rerun [--] [playwright args]
8531
+
8532
+ Runs playwright test with the arguments of ${RERUN_ARGS_ENV}, split as the
8533
+ dashboard quoted them and never read by a shell, followed by the arguments
8534
+ given here (after an optional --). Declare ${RERUN_ARGS_ENV} in the CI job: set and empty, the whole
8535
+ suite runs; unset, the command fails rather than run it.
8536
+
8537
+ Options:
8538
+ -h, --help Show this help (as the first argument only)
8539
+
8540
+ Exit codes: Playwright's own, 128 plus the signal's number when the runner
8541
+ stops Playwright (143 for SIGTERM), or 2 when ${RERUN_ARGS_ENV} is unset or
8542
+ cannot be read, or Playwright cannot start.
8543
+ `.trim();
8544
+ async function runRerun(argv, env = process.env) {
8545
+ if (argv[0] === "-h" || argv[0] === "--help") {
8546
+ console.log(USAGE13);
8547
+ return 0;
8548
+ }
8549
+ const text = env[RERUN_ARGS_ENV];
8550
+ if (text === void 0) {
8551
+ console.error(
8552
+ `piwi rerun: ${RERUN_ARGS_ENV} is not set. Declare it in the job (a pipeline variable or build parameter) so the dashboard's arguments reach it.`
8553
+ );
8554
+ return EXIT_ERROR11;
8555
+ }
8556
+ let words;
8557
+ try {
8558
+ words = splitRerunArgs(text);
8559
+ } catch (e) {
8560
+ console.error(`piwi rerun: ${RERUN_ARGS_ENV} cannot be read: ${e.message}.`);
8561
+ return EXIT_ERROR11;
8562
+ }
8563
+ const extra = argv[0] === "--" ? argv.slice(1) : argv;
8564
+ return spawnPlaywright([...words, ...extra], env, { command: "piwi rerun" });
8565
+ }
8566
+
8567
+ // src/cli/index.ts
8568
+ var USAGE14 = `
8077
8569
  piwi \u2014 companion commands for the Piwi Dashboard reporter
8078
8570
 
8079
8571
  Usage:
@@ -8087,6 +8579,7 @@ Commands:
8087
8579
  coverage Upload a unit-test (or other) coverage report of a commit (coverage upload)
8088
8580
  select Print the Playwright args for a saved test selection
8089
8581
  run Run a saved test selection with playwright test
8582
+ rerun Run the tests a CI re-run from the dashboard asked for (PIWI_RERUN_ARGS)
8090
8583
  probe Run the dashboard's probe plan and record what the suite noticed
8091
8584
  flake Make a flaky test fail on demand under its suspects' conditions, then verify the fix
8092
8585
  ai Manage committed natural-language AI-step artifacts
@@ -8115,6 +8608,8 @@ async function main() {
8115
8608
  return runSelect(rest);
8116
8609
  case "run":
8117
8610
  return runRun(rest);
8611
+ case "rerun":
8612
+ return runRerun(rest);
8118
8613
  case "probe":
8119
8614
  return runProbe(rest);
8120
8615
  case "flake":
@@ -8130,12 +8625,12 @@ async function main() {
8130
8625
  case void 0:
8131
8626
  case "-h":
8132
8627
  case "--help":
8133
- console.log(USAGE13);
8628
+ console.log(USAGE14);
8134
8629
  return 0;
8135
8630
  default:
8136
8631
  console.error(`piwi: unknown command "${command}"
8137
8632
  `);
8138
- console.error(USAGE13);
8633
+ console.error(USAGE14);
8139
8634
  return 2;
8140
8635
  }
8141
8636
  }