@testsprite/testsprite-cli 0.12.0 → 0.13.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.
Files changed (91) hide show
  1. package/README.md +11 -4
  2. package/dist/commands/agent.js +16 -13
  3. package/dist/commands/auth.d.ts +19 -0
  4. package/dist/commands/auth.js +60 -24
  5. package/dist/commands/ci.d.ts +86 -1
  6. package/dist/commands/ci.js +436 -5
  7. package/dist/commands/doctor.d.ts +2 -0
  8. package/dist/commands/doctor.js +22 -9
  9. package/dist/commands/init.js +14 -11
  10. package/dist/commands/project-env.js +9 -9
  11. package/dist/commands/project.d.ts +5 -5
  12. package/dist/commands/project.js +42 -42
  13. package/dist/commands/schedule.d.ts +2 -0
  14. package/dist/commands/schedule.js +18 -10
  15. package/dist/commands/test.d.ts +73 -27
  16. package/dist/commands/test.js +1756 -413
  17. package/dist/commands/testlist.js +49 -19
  18. package/dist/commands/tunnel.d.ts +26 -3
  19. package/dist/commands/tunnel.js +211 -14
  20. package/dist/commands/usage.d.ts +3 -0
  21. package/dist/commands/usage.js +12 -5
  22. package/dist/index.js +34 -20
  23. package/dist/lib/agent-targets.d.ts +3 -3
  24. package/dist/lib/agent-targets.js +2 -2
  25. package/dist/lib/billing-refusal.d.ts +43 -0
  26. package/dist/lib/billing-refusal.js +171 -0
  27. package/dist/lib/bundle.d.ts +5 -0
  28. package/dist/lib/bundle.js +43 -13
  29. package/dist/lib/ci-linkage.d.ts +90 -0
  30. package/dist/lib/ci-linkage.js +181 -0
  31. package/dist/lib/client-factory.d.ts +4 -1
  32. package/dist/lib/client-factory.js +23 -2
  33. package/dist/lib/config.d.ts +17 -0
  34. package/dist/lib/config.js +20 -1
  35. package/dist/lib/conflict-reason.d.ts +27 -3
  36. package/dist/lib/conflict-reason.js +53 -4
  37. package/dist/lib/credentials.js +56 -14
  38. package/dist/lib/dry-run/samples.d.ts +13 -1
  39. package/dist/lib/dry-run/samples.js +51 -7
  40. package/dist/lib/errors.d.ts +18 -11
  41. package/dist/lib/errors.js +111 -13
  42. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  43. package/dist/lib/failing-fe-resolver.js +3 -3
  44. package/dist/lib/gh-output.d.ts +1 -0
  45. package/dist/lib/gh-output.js +13 -4
  46. package/dist/lib/history-retention.d.ts +8 -0
  47. package/dist/lib/history-retention.js +24 -0
  48. package/dist/lib/http.d.ts +37 -19
  49. package/dist/lib/http.js +46 -24
  50. package/dist/lib/interrupt.d.ts +21 -13
  51. package/dist/lib/interrupt.js +32 -21
  52. package/dist/lib/junit-report.d.ts +11 -1
  53. package/dist/lib/junit-report.js +15 -3
  54. package/dist/lib/local-target.d.ts +1 -1
  55. package/dist/lib/local-target.js +1 -1
  56. package/dist/lib/plan-poll.d.ts +11 -11
  57. package/dist/lib/plan-poll.js +12 -12
  58. package/dist/lib/plans.types.d.ts +9 -9
  59. package/dist/lib/plans.types.js +3 -3
  60. package/dist/lib/poll.d.ts +2 -2
  61. package/dist/lib/poll.js +9 -3
  62. package/dist/lib/render-error.d.ts +2 -0
  63. package/dist/lib/render-error.js +13 -0
  64. package/dist/lib/response-schemas.d.ts +54 -12
  65. package/dist/lib/response-schemas.js +88 -7
  66. package/dist/lib/runs.types.d.ts +59 -10
  67. package/dist/lib/secret-file.js +72 -14
  68. package/dist/lib/skill-nudge.d.ts +6 -1
  69. package/dist/lib/skill-nudge.js +32 -5
  70. package/dist/lib/target-url-preflight.d.ts +6 -4
  71. package/dist/lib/target-url-preflight.js +64 -51
  72. package/dist/lib/target-url.js +6 -6
  73. package/dist/lib/telemetry.d.ts +4 -1
  74. package/dist/lib/telemetry.js +13 -13
  75. package/dist/lib/ticker.js +93 -4
  76. package/dist/lib/tunnel-session.d.ts +13 -0
  77. package/dist/lib/tunnel-session.js +4 -1
  78. package/dist/lib/tunnel.types.d.ts +12 -2
  79. package/dist/lib/tunnel.types.js +2 -2
  80. package/dist/lib/wait-exit.d.ts +8 -0
  81. package/dist/lib/wait-exit.js +76 -4
  82. package/dist/lib/workspace-status.d.ts +23 -0
  83. package/dist/lib/workspace-status.js +15 -0
  84. package/dist/version-guard.d.ts +7 -1
  85. package/dist/version-guard.js +19 -1
  86. package/dist/version.d.ts +1 -1
  87. package/dist/version.js +1 -1
  88. package/package.json +4 -4
  89. package/skills/testsprite-onboard.skill.md +4 -4
  90. package/skills/testsprite-verify.codex.md +59 -57
  91. package/skills/testsprite-verify.skill.md +53 -38
@@ -1,4 +1,4 @@
1
- import { createWriteStream, existsSync, readFileSync, readdirSync, statSync, } from 'node:fs';
1
+ import { closeSync, createWriteStream, existsSync, fstatSync, openSync, readFileSync, readSync, readdirSync, statSync, } from 'node:fs';
2
2
  import { rename, stat, unlink } from 'node:fs/promises';
3
3
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
@@ -7,9 +7,10 @@ import { openInBrowser } from '../lib/browser.js';
7
7
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
8
8
  import { assertContextIntegrity, buildMeta, pickCodeExtension, pickVideoExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
9
9
  import { findSample, findSampleOrThrow, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
10
- import { assertJUnitReportOptions, buildJUnitReport, durationSecondsBetween, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
10
+ import { assertJUnitReportOptions, buildJUnitReport, durationSecondsBetween, resolveBatchReportProjectId, skippedJUnitResultsFromSummary, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
11
11
  import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, isAuthCode, localValidationError, } from '../lib/errors.js';
12
12
  import { globalShutdown } from '../lib/interrupt.js';
13
+ import { defaultSleep } from '../lib/poll-support.js';
13
14
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
14
15
  import { isStandingRateLimit, REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, } from '../lib/http.js';
15
16
  import { VERSION } from '../version.js';
@@ -18,9 +19,10 @@ import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagi
18
19
  import { isTerminalStatus, pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
19
20
  import { batchOutcomeCounts, recordBatchOutcome, recordTelemetryExtras, } from '../lib/telemetry.js';
20
21
  import { PlanGenerationTimeoutError, runGenerationLadder } from '../lib/plan-poll.js';
21
- import { resolveWaitFailure } from '../lib/wait-exit.js';
22
+ import { resolveWaitFailure, waitMemberError } from '../lib/wait-exit.js';
22
23
  import { RUN_SOURCES } from '../lib/runs.types.js';
23
- import { insufficientCreditsConflictError, isAllCreditsRefusal, summarizeConflicts, } from '../lib/conflict-reason.js';
24
+ import { classifyBillingRefusal } from '../lib/billing-refusal.js';
25
+ import { allConflictsInFlight, billingConflictLink, insufficientCreditsConflictError, isAllCreditsRefusal, isPausedRefusal, pausedConflictError, summarizeConflicts, } from '../lib/conflict-reason.js';
24
26
  import { isProxyAgentActive } from '../lib/proxy.js';
25
27
  import { assertNotLocal } from '../lib/target-url.js';
26
28
  import { assertTargetUrlReachable } from '../lib/target-url-preflight.js';
@@ -33,18 +35,19 @@ import { createTicker } from '../lib/ticker.js';
33
35
  import { RateThrottle } from '../lib/rate-throttle.js';
34
36
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
35
37
  import { emitTargetUrlMismatchAdvisory } from '../lib/v3-advisory.js';
36
- import { emitCiArtifacts, summarizeAcceptedPayload, summarizeSingleRun, } from '../lib/gh-output.js';
37
- import { loadConfig } from '../lib/config.js';
38
+ import { emitCiArtifacts, isNonDispatchedStatus, summarizeAcceptedPayload, summarizeSingleRun, } from '../lib/gh-output.js';
39
+ import { loadConfig, resolveProfileName } from '../lib/config.js';
40
+ import { historyRetentionNote } from '../lib/history-retention.js';
38
41
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
39
- /** The effective shutdown handle for a command invocation (DEV-331). */
42
+ /** The effective shutdown handle for a command invocation. */
40
43
  function shutdownOf(deps) {
41
44
  return deps.shutdown ?? globalShutdown;
42
45
  }
43
46
  /**
44
- * The honest-detach stderr line (DEV-331 D1 — the heart of the ticket):
45
- * a Ctrl-C detaches the local wait only; the server-side run keeps executing
46
- * AND billing. Names both re-attach (`test wait`) and the real cancel
47
- * (`test cancel`, piece 3) so the user always has a path to actually stop it.
47
+ * The honest-detach stderr line: a Ctrl-C detaches the local wait only;
48
+ * the server-side run keeps executing AND billing. Names both re-attach
49
+ * (`test wait`) and the real cancel (`test cancel`) so the user always has
50
+ * a path to actually stop it.
48
51
  */
49
52
  function interruptDetachMessage(err, runIds) {
50
53
  const subject = runIds.length === 1
@@ -148,12 +151,12 @@ function makeBorrowedTunnelLivenessCheck(args) {
148
151
  * Stop a tunnel run that can no longer succeed.
149
152
  *
150
153
  * Called on every path where this process stops waiting while the run is
151
- * non-terminal. Unlike an ordinary run — where DEV-331 deliberately decided a
152
- * Ctrl-C detaches and leaves the run to finish — a tunnel run's target lives
153
- * behind a tunnel this process is holding open, so the moment we exit the
154
- * Lambda's browser can start getting connection failures. The run may already
155
- * have completed or been billed, so the cancellation message states only the
156
- * observed cancel outcome and the cancelled-verdict semantics.
154
+ * non-terminal. Unlike an ordinary run, where a Ctrl-C deliberately detaches
155
+ * and leaves the run to finish, a tunnel run's target lives behind a tunnel
156
+ * this process is holding open, so the moment we exit the Lambda's browser
157
+ * can start getting connection failures. The run may already have completed
158
+ * or been billed, so the cancellation message states only the observed
159
+ * cancel outcome and the cancelled-verdict semantics.
157
160
  *
158
161
  * The cancel is issued through a DETACHED client: the normal one composes the
159
162
  * process shutdown signal into every fetch, and on the interrupt path that
@@ -334,13 +337,9 @@ function resolveApiUrl(opts, deps = {}) {
334
337
  return config.apiUrl;
335
338
  }
336
339
  export async function runList(opts, deps = {}) {
337
- // Validate inputs before touching credentials so a missing `--project`
338
- // surfaces as `VALIDATION_ERROR` (exit 5) rather than `AUTH_REQUIRED`
339
- // (exit 3) when the caller also lacks a configured key. Order matters
340
- // for the CLI error spec §2 — bad input is a caller bug, not an auth
341
- // gate.
340
+ // Keep malformed filters ahead of authentication, but check credentials
341
+ // before the required project so a first-time caller sees the setup action.
342
342
  const projectId = resolveProjectId(opts.projectId, deps);
343
- requireProjectId(projectId);
344
343
  const paginationFlags = validatePaginationFlags({
345
344
  pageSize: opts.pageSize,
346
345
  startingToken: opts.startingToken,
@@ -356,6 +355,7 @@ export async function runList(opts, deps = {}) {
356
355
  resolveTextColumns(opts.columns, TEST_LIST_COLUMNS);
357
356
  }
358
357
  const client = makeClient(opts, deps);
358
+ requireProjectId(projectId);
359
359
  // Match P2's "explicit pageSize ⇒ single-page" convention so an
360
360
  // operator can grab one slice + cursor without auto-paging through a
361
361
  // huge project.
@@ -422,7 +422,7 @@ const DUP_NAME_ADVISORY_TIMEOUT_MS = 5_000;
422
422
  async function emitDupNameAdvisoryIfNeeded(client, projectId, name, stderrFn) {
423
423
  if (!projectId || !name)
424
424
  return;
425
- // B: the advisory lookup must NEVER block the create critical path.
425
+ // B: ordinary advisory failures must not block the create critical path.
426
426
  // Use an AbortController with a 5 s deadline. When the timer fires it
427
427
  // calls ac.abort(), which causes client.get (via the `signal` option) to
428
428
  // throw an AbortError — caught below and swallowed. This ensures a stalled
@@ -451,8 +451,10 @@ async function emitDupNameAdvisoryIfNeeded(client, projectId, name, stderrFn) {
451
451
  `Use \`testsprite test update ${match.id}\` to modify it, or proceed to create a duplicate.`);
452
452
  }
453
453
  }
454
- catch {
455
- // Swallow — this is best-effort; must not block the create.
454
+ catch (err) {
455
+ if (err instanceof InterruptError)
456
+ throw err;
457
+ // Other lookup failures are best-effort and must not block the create.
456
458
  }
457
459
  finally {
458
460
  clearTimeout(timer);
@@ -477,6 +479,10 @@ async function emitDupNameAdvisoryIfNeeded(client, projectId, name, stderrFn) {
477
479
  * convention; no separate "envelope-only" output mode.
478
480
  */
479
481
  export async function runCreate(opts, deps = {}) {
482
+ if (opts.environment !== undefined && opts.run !== true) {
483
+ throw localValidationError('env', '--env requires --run');
484
+ }
485
+ normalizeEnvironmentName(opts.environment);
480
486
  // P1-2: validate idempotency key before any I/O — non-ASCII chars cause a
481
487
  // ByteString TypeError at the HTTP transport layer (exit 10 UNAVAILABLE).
482
488
  assertIdempotencyKey(opts.idempotencyKey);
@@ -618,7 +624,12 @@ export async function runCreate(opts, deps = {}) {
618
624
  opts.run === true &&
619
625
  !opts.dryRun) {
620
626
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
621
- await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
627
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, {
628
+ fetchImpl: deps.fetchImpl,
629
+ proxyActive: isProxyAgentActive(),
630
+ shutdownSignal: shutdownOf(deps).signal,
631
+ shutdown: shutdownOf(deps),
632
+ }, stderrFn);
622
633
  }
623
634
  const client = makeClient(opts, deps);
624
635
  const out = makeOutput(opts.output, deps);
@@ -644,11 +655,11 @@ export async function runCreate(opts, deps = {}) {
644
655
  // `--output json` stays parseable for agents and scripts.
645
656
  if (opts.run === true) {
646
657
  const runIdempotencyKey = `${idempotencyKey}:run`;
647
- // R3a: compute dashboardUrl before the early return so it flows into
648
- // the merged { ...createContext, run } envelope in JSON mode and
649
- // appears on the Dashboard: stderr line in text mode.
650
- // R1: suppress under --dry-run (fake canned test id).
651
- // DEV-737: prefer a server-provided dashboardUrl over the client guess
658
+ // Compute dashboardUrl before the early return so it flows into the
659
+ // merged { ...createContext, run } envelope in JSON mode and appears on
660
+ // the Dashboard: stderr line in text mode. Suppressed under --dry-run
661
+ // (fake canned test id).
662
+ // Prefer a server-provided dashboardUrl over the client guess
652
663
  // (`withDashboardUrl`/`resolveDashboardUrl` above); when the server
653
664
  // explicitly withheld one, never fall back to the client-computed
654
665
  // V2-shaped link and tell the caller where to find the test instead.
@@ -695,11 +706,11 @@ export async function runCreate(opts, deps = {}) {
695
706
  }, deps);
696
707
  return response;
697
708
  }
698
- // Fix 5: emit dashboard deep-link when projectId + testId are known client-side
699
- // (no extra network call — both come from opts / response).
700
- // R1: suppress under --dry-run — the test id is a fake canned value
701
- // (e.g. "test_dryrun_create_2026") and a live-looking URL would mislead.
702
- // DEV-737: prefer a server-provided dashboardUrl over the client guess;
709
+ // Emit dashboard deep-link when projectId + testId are known client-side
710
+ // (no extra network call — both come from opts / response). Suppressed
711
+ // under --dry-run — the test id is a fake canned value (e.g.
712
+ // "test_dryrun_create_2026") and a live-looking URL would mislead.
713
+ // Prefer a server-provided dashboardUrl over the client guess;
703
714
  // never fall back when the server explicitly withheld one (see
704
715
  // `withDashboardUrl`/`resolveDashboardUrl` above), and tell the caller
705
716
  // where to find the test instead of printing a link that would 404.
@@ -928,16 +939,15 @@ function renderPlanPutText(response) {
928
939
  * array on success; throws a typed `VALIDATION_ERROR` envelope on any
929
940
  * schema problem with a `details.field` pointer the caller can act on.
930
941
  *
931
- * Stat-first guard mirrors piece-2's `readCodeFileGuarded`: oversize
932
- * payloads fail before we load them into V8's heap. The cap here is
933
- * 256 KB (vs. 350 KB for code) per the piece-6 spec.
942
+ * Size-capped guard: oversize payloads fail before we load them into
943
+ * V8's heap. The cap here is 256 KB (vs. 350 KB for code).
934
944
  */
935
945
  function readPlanStepsFileGuarded(path) {
936
946
  return assertPlanStepsShape(parsePlanStepsFile(path));
937
947
  }
938
948
  /**
939
949
  * File I/O + JSON.parse half of `readPlanStepsFileGuarded`, split out so
940
- * `test lint` can reuse the SAME stat/size/read/parse guards while
950
+ * `test lint` can reuse the SAME open/size/read guards while
941
951
  * substituting the collect-all `collectPlanStepsIssues` shape check for the
942
952
  * throw-on-first `assertPlanStepsShape` that `test plan put` still uses. A
943
953
  * failure here (missing file, oversize, invalid JSON syntax) is always a
@@ -945,52 +955,158 @@ function readPlanStepsFileGuarded(path) {
945
955
  * file itself can't be read or parsed.
946
956
  */
947
957
  function parsePlanStepsFile(path) {
948
- const absolute = resolveAbsolute(path);
949
- let stat;
950
- try {
951
- stat = statSync(absolute);
952
- }
953
- catch (err) {
954
- const code = err.code;
955
- if (code === 'ENOENT') {
956
- throw localValidationError('steps', `file does not exist: ${path}`);
957
- }
958
- if (code === 'EACCES') {
959
- throw localValidationError('steps', `permission denied reading ${path}`);
960
- }
961
- const reason = err instanceof Error ? err.message : 'unknown error';
962
- throw localValidationError('steps', `cannot stat ${path}: ${reason}`);
963
- }
964
- if (stat.size > MAX_PLAN_STEPS_BODY_BYTES) {
958
+ const result = readCappedFileGuarded('steps', path, MAX_PLAN_STEPS_BODY_BYTES);
959
+ if (!result.ok) {
965
960
  throw ApiError.fromEnvelope({
966
961
  error: {
967
962
  code: 'PAYLOAD_TOO_LARGE',
968
- message: `Plan-steps body exceeds the 256 KB CLI cap (${stat.size} bytes).`,
963
+ message: `Plan-steps body exceeds the 256 KB CLI cap (${result.sizeBytes} bytes).`,
969
964
  nextAction: 'Split into multiple smaller tests or trim step descriptions.',
970
965
  requestId: 'local',
971
966
  details: {
972
967
  field: 'steps',
973
- sizeBytes: stat.size,
968
+ sizeBytes: result.sizeBytes,
974
969
  maxBytes: MAX_PLAN_STEPS_BODY_BYTES,
975
970
  },
976
971
  },
977
972
  });
978
973
  }
979
- let raw;
980
974
  try {
981
- raw = stripBom(readFileSync(absolute, 'utf8'));
975
+ return JSON.parse(result.raw);
982
976
  }
983
977
  catch (err) {
984
978
  const reason = err instanceof Error ? err.message : 'unknown error';
985
- throw localValidationError('steps', `cannot read ${path}: ${reason}`);
979
+ throw localValidationError('steps', `not valid JSON: ${reason}`);
986
980
  }
981
+ }
982
+ /**
983
+ * Open `path` exactly once, size-check and read it through that SAME file
984
+ * descriptor, and close it in a `finally`. A separate `statSync` followed by
985
+ * a separate `readFileSync` against the same path string leaves a
986
+ * check-then-use window open: whatever is at that path when the read
987
+ * actually happens is what gets read, not what the stat measured, so an
988
+ * oversize-cap check can be bypassed by a file swapped in between the two
989
+ * calls. Binding the size check and the read to one open file handle closes
990
+ * that window, since a swap of the path afterward can no longer change what
991
+ * gets read.
992
+ *
993
+ * Returns `{ ok: true, raw }` on success (BOM already stripped) or
994
+ * `{ ok: false, sizeBytes }` when the file is over `maxBytes` — the
995
+ * oversize case is handed back rather than turned into an error here
996
+ * because each caller throws its own `PAYLOAD_TOO_LARGE` envelope (distinct
997
+ * message, `nextAction`, and `details.field`/`maxBytes` per flag). Every
998
+ * other failure (missing file, permission denied, any other I/O error)
999
+ * throws a `VALIDATION_ERROR` built from `field` directly.
1000
+ *
1001
+ * Platform note: opening a directory throws `EISDIR` (or, on some Windows
1002
+ * builds, `EPERM`) at `openSync` time; POSIX instead lets the open succeed
1003
+ * and only fails later, when the first read actually tries to read the
1004
+ * directory's contents. Both cases are folded into the same "cannot read"
1005
+ * wording so the message text does not depend on which platform raised it.
1006
+ */
1007
+ function readCappedFileGuarded(field, path, maxBytes) {
1008
+ const absolute = resolveAbsolute(path);
1009
+ let fd;
987
1010
  try {
988
- return JSON.parse(raw);
1011
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- this is the guard itself: `absolute` is the user-supplied --steps/--plan-from/--plans path after resolve(), and opening it once, then fstat-checking and reading through that descriptor, is the mitigation for a non-literal path here.
1012
+ fd = openSync(absolute, 'r');
989
1013
  }
990
1014
  catch (err) {
1015
+ const code = err.code;
1016
+ if (code === 'ENOENT') {
1017
+ throw localValidationError(field, `file does not exist: ${path}`);
1018
+ }
1019
+ if (code === 'EACCES') {
1020
+ // The old stat-then-read code only produced "permission denied
1021
+ // reading" when the STAT call itself failed with EACCES — a parent
1022
+ // directory lacking search permission. stat() needs no permission on
1023
+ // the target file's own mode bits, so a file merely made unreadable
1024
+ // (e.g. chmod 000) still passed stat() there and only failed later,
1025
+ // at readFileSync, landing in the generic "cannot read" wording
1026
+ // below. openSync collapses both into one EACCES here, so a
1027
+ // diagnostic re-stat (nothing is read as a result — this cannot
1028
+ // reintroduce the check-then-use race the fd-based read closes)
1029
+ // recovers which of the two the old code would have hit.
1030
+ let statAlsoFails = false;
1031
+ try {
1032
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- diagnostic only, to choose the error message for the open() failure above; nothing is read from `absolute` here or afterward.
1033
+ statSync(absolute);
1034
+ }
1035
+ catch {
1036
+ statAlsoFails = true;
1037
+ }
1038
+ if (statAlsoFails) {
1039
+ throw localValidationError(field, `permission denied reading ${path}`);
1040
+ }
1041
+ const reason = err instanceof Error ? err.message : 'unknown error';
1042
+ throw localValidationError(field, `cannot read ${path}: ${reason}`);
1043
+ }
1044
+ if (code === 'EISDIR' || code === 'EPERM') {
1045
+ const reason = err instanceof Error ? err.message : 'unknown error';
1046
+ throw localValidationError(field, `cannot read ${path}: ${reason}`);
1047
+ }
1048
+ if (code === 'EMFILE' || code === 'ENFILE') {
1049
+ // The old stat-then-read code's statSync() opens no file descriptor,
1050
+ // so it always succeeded even with the process's fd table exhausted;
1051
+ // only the later readFileSync (which does open one) could hit
1052
+ // EMFILE/ENFILE, landing in "cannot read". The fd-based guard's
1053
+ // openSync is the first fs call here, so route the same exhaustion
1054
+ // to the same "cannot read" wording regardless of which syscall hit
1055
+ // the ceiling.
1056
+ const reason = err instanceof Error ? err.message : 'unknown error';
1057
+ throw localValidationError(field, `cannot read ${path}: ${reason}`);
1058
+ }
991
1059
  const reason = err instanceof Error ? err.message : 'unknown error';
992
- throw localValidationError('steps', `not valid JSON: ${reason}`);
1060
+ throw localValidationError(field, `cannot stat ${path}: ${reason}`);
1061
+ }
1062
+ try {
1063
+ let stat;
1064
+ try {
1065
+ stat = fstatSync(fd);
1066
+ }
1067
+ catch (err) {
1068
+ const reason = err instanceof Error ? err.message : 'unknown error';
1069
+ throw localValidationError(field, `cannot stat ${path}: ${reason}`);
1070
+ }
1071
+ if (stat.size > maxBytes) {
1072
+ return { ok: false, sizeBytes: stat.size };
1073
+ }
1074
+ // fstat's size is not the whole story: a pipe (e.g. `--plans <(gen)`)
1075
+ // reports 0, and a regular file can grow after the fstat above. Reading
1076
+ // at most one byte past the cap and checking what actually arrived
1077
+ // enforces the cap on the bytes read, without buffering an unbounded
1078
+ // stream to find out.
1079
+ let bytes;
1080
+ try {
1081
+ bytes = readAtMostSync(fd, maxBytes + 1);
1082
+ }
1083
+ catch (err) {
1084
+ const reason = err instanceof Error ? err.message : 'unknown error';
1085
+ throw localValidationError(field, `cannot read ${path}: ${reason}`);
1086
+ }
1087
+ if (bytes.length > maxBytes) {
1088
+ // A lower bound for a pipe or a growing file: reading stopped here.
1089
+ return { ok: false, sizeBytes: bytes.length };
1090
+ }
1091
+ return { ok: true, raw: stripBom(bytes.toString('utf8')) };
1092
+ }
1093
+ finally {
1094
+ closeSync(fd);
1095
+ }
1096
+ }
1097
+ /** Read from `fd` until EOF or until `limit` bytes have arrived, whichever comes first. */
1098
+ function readAtMostSync(fd, limit) {
1099
+ const chunks = [];
1100
+ let total = 0;
1101
+ while (total < limit) {
1102
+ const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, limit - total));
1103
+ const n = readSync(fd, chunk, 0, chunk.length, null);
1104
+ if (n === 0)
1105
+ break;
1106
+ chunks.push(n === chunk.length ? chunk : chunk.subarray(0, n));
1107
+ total += n;
993
1108
  }
1109
+ return Buffer.concat(chunks, total);
994
1110
  }
995
1111
  /**
996
1112
  * Type-narrow + validate a parsed `{ planSteps: [...] }` envelope.
@@ -1358,6 +1474,8 @@ export async function runDeleteBatch(opts, deps = {}) {
1358
1474
  });
1359
1475
  }
1360
1476
  catch (err) {
1477
+ if (err instanceof InterruptError)
1478
+ throw err;
1361
1479
  // 404 = already deleted / not found. Surface as 'skipped' so the
1362
1480
  // summary count is accurate and the exit code stays 0.
1363
1481
  if (err instanceof ApiError && err.code === 'NOT_FOUND') {
@@ -1492,16 +1610,6 @@ const MAX_BATCH_BODY_BYTES = 5 * 1024 * 1024;
1492
1610
  * than this, the CLI splits into chunks and aggregates the results.
1493
1611
  */
1494
1612
  const MAX_BATCH_RERUN_IDS = 50;
1495
- /**
1496
- * Drop duplicate `testId` entries from a chunked batch-rerun's aggregated
1497
- * `accepted[]`, keeping the first occurrence. BE producer/teardown closure
1498
- * dedup happens per-request server-side, not across the separate requests
1499
- * one chunk per `MAX_BATCH_RERUN_IDS` window produces, so the same producer
1500
- * can come back accepted (with a different runId) from more than one
1501
- * chunk. Returns the deduped list plus how many entries were dropped, so
1502
- * the caller can warn the operator that a shared BE producer/teardown was
1503
- * triggered more than once.
1504
- */
1505
1613
  /**
1506
1614
  * Dedupe `RerunAdvisory[]` by `feature`+`message`. Used to aggregate
1507
1615
  * `advisories` across chunked batch-rerun dispatch requests (initial dispatch
@@ -1529,17 +1637,62 @@ function emitRerunAdvisories(stderrFn, advisories) {
1529
1637
  stderrFn(`[advisory] ${advisory.message}`);
1530
1638
  }
1531
1639
  }
1640
+ /**
1641
+ * Drop duplicate `testId` entries from a chunked batch-rerun's aggregated
1642
+ * `accepted[]`, keeping the first occurrence. BE producer/teardown closure
1643
+ * dedup happens per-request server-side, not across the separate requests
1644
+ * one chunk per `MAX_BATCH_RERUN_IDS` window produces, so the same producer
1645
+ * can come back accepted (with a different runId) from more than one
1646
+ * chunk. Returns the kept list plus the dropped entries, which name real
1647
+ * runs that are executing unpolled.
1648
+ */
1532
1649
  function dedupeBatchRerunAccepted(entries) {
1533
1650
  const seen = new Map();
1534
- let droppedCount = 0;
1651
+ const dropped = [];
1535
1652
  for (const entry of entries) {
1536
1653
  if (seen.has(entry.testId)) {
1537
- droppedCount++;
1654
+ dropped.push(entry);
1538
1655
  continue;
1539
1656
  }
1540
1657
  seen.set(entry.testId, entry);
1541
1658
  }
1542
- return { deduped: [...seen.values()], droppedCount };
1659
+ return { deduped: [...seen.values()], dropped };
1660
+ }
1661
+ /**
1662
+ * Drop duplicate `testId` entries from a fresh batch run's aggregated
1663
+ * `accepted[]`, keeping the first. Returns the kept list plus the dropped
1664
+ * entries, which name real runs that are executing unpolled.
1665
+ */
1666
+ function dedupeBatchRunFreshAccepted(entries) {
1667
+ const seen = new Map();
1668
+ const dropped = [];
1669
+ for (const entry of entries) {
1670
+ if (seen.has(entry.testId)) {
1671
+ dropped.push(entry);
1672
+ continue;
1673
+ }
1674
+ seen.set(entry.testId, entry);
1675
+ }
1676
+ return { deduped: [...seen.values()], dropped };
1677
+ }
1678
+ /**
1679
+ * Name the runs a dedupe dropped. Each one is executing and billing while
1680
+ * nothing polls it, so its id has to reach the caller to be cancelled or
1681
+ * looked up later. An entry repeating the kept run's own id is that same run
1682
+ * echoed back, not a second one, and is not reported.
1683
+ */
1684
+ function warnDroppedDuplicateRuns(kept, dropped, stderrFn) {
1685
+ const keptById = new Map(kept.map(e => [e.testId, e.runId]));
1686
+ const extraRuns = dropped.filter(e => e.runId !== keptById.get(e.testId));
1687
+ if (extraRuns.length === 0)
1688
+ return;
1689
+ stderrFn(`[warn] ${extraRuns.length} duplicate dispatch${extraRuns.length !== 1 ? 'es' : ''} — ` +
1690
+ `these runs are executing and are not being polled:`);
1691
+ for (const entry of extraRuns) {
1692
+ stderrFn(`[warn] test ${entry.testId}: polling ${keptById.get(entry.testId) ?? '(unknown)'}, ` +
1693
+ `not polling ${entry.runId}`);
1694
+ }
1695
+ stderrFn(`[warn] Stop an unpolled run with: testsprite test cancel <run-id>`);
1543
1696
  }
1544
1697
  /**
1545
1698
  * Merge per-project closure summaries from multiple batch-rerun chunk
@@ -1592,6 +1745,22 @@ function mergeBatchRerunClosureByProject(entries) {
1592
1745
  export const DEFAULT_BATCH_RUN_CONCURRENCY = 50;
1593
1746
  /** Hard upper bound for --max-concurrency. Values above this are rejected with exit 5 (VALIDATION_ERROR). */
1594
1747
  export const MAX_BATCH_CONCURRENCY = 100;
1748
+ /**
1749
+ * The server's DEFAULT in-flight run cap. Runs from every source count
1750
+ * toward it (CLI, portal, schedules, CI), but only CLI run triggers are
1751
+ * refused on it; a portal or schedule run over the cap is not. Exceeding it
1752
+ * answers RATE_LIMITED with `details.reason: "inflight_cap"`, whose details
1753
+ * carry the account's real `cap` and `current`.
1754
+ *
1755
+ * Quoted in help text only — the server owns the real number and rejects on
1756
+ * its own value, so this is documentation, never a client-side gate.
1757
+ *
1758
+ * Distinct from `--max-concurrency`, whose meaning differs per command: on
1759
+ * `create --run` it bounds in-flight triggers, and with `--wait` a slot is
1760
+ * held until that run finishes, so lowering it there does bound how many runs
1761
+ * are in flight. On `run --all` it bounds the `--wait` poll fan-out only.
1762
+ */
1763
+ export const SERVER_INFLIGHT_RUN_CAP = 50;
1595
1764
  /** Client-side run-trigger throttle: 50 triggers per 60-second rolling window per key (sits just under the server's 60/min/key cap). */
1596
1765
  export const BATCH_RUN_RATE_LIMIT = 50;
1597
1766
  /** Rolling window duration (ms) for the client-side trigger rate throttle. */
@@ -1622,12 +1791,10 @@ export const WAIT_POLL_RATE_MAX_OUTER_RETRIES = 3;
1622
1791
  */
1623
1792
  /**
1624
1793
  * Sleep that a termination signal cuts short by rejecting with the signal's
1625
- * `InterruptError`, so the caller's existing DEV-331 catch owns the detach UX.
1794
+ * `InterruptError`, so the caller's existing catch owns the detach UX.
1626
1795
  *
1627
1796
  * Mirrors `HttpClient.sleepBeforeRetry` — an in-flight backoff must not be a
1628
- * window where a first Ctrl-C hard-exits with empty stdout. The caller is
1629
- * responsible for having ARMED the shutdown scope; a disarmed controller never
1630
- * aborts its signal, so this would otherwise sleep straight through the signal.
1797
+ * window where a first Ctrl-C waits for a timer before the command exits.
1631
1798
  */
1632
1799
  export function sleepUntilOrInterrupt(ms, signal, sleep) {
1633
1800
  if (signal === undefined)
@@ -1635,9 +1802,12 @@ export function sleepUntilOrInterrupt(ms, signal, sleep) {
1635
1802
  if (signal.aborted)
1636
1803
  return Promise.reject(signal.reason);
1637
1804
  return new Promise((resolve, reject) => {
1638
- const onAbort = () => reject(signal.reason);
1805
+ const onAbort = () => {
1806
+ signal.removeEventListener('abort', onAbort);
1807
+ reject(signal.reason);
1808
+ };
1639
1809
  signal.addEventListener('abort', onAbort, { once: true });
1640
- sleep(ms).then(() => {
1810
+ sleep(ms, signal).then(() => {
1641
1811
  signal.removeEventListener('abort', onAbort);
1642
1812
  resolve();
1643
1813
  }, err => {
@@ -1777,6 +1947,10 @@ function emitPlaceholderAdvisory(plan, stderrFn) {
1777
1947
  * when M3.3 lands.
1778
1948
  */
1779
1949
  export async function runCreateFromPlan(opts, deps = {}) {
1950
+ if (opts.environment !== undefined && opts.run !== true) {
1951
+ throw localValidationError('env', '--env requires --run');
1952
+ }
1953
+ normalizeEnvironmentName(opts.environment);
1780
1954
  assertIdempotencyKey(opts.idempotencyKey);
1781
1955
  // codex #128 P2: validate the derived `<key>:run` chain key before the
1782
1956
  // create POST (see runCreate) so a near-limit base key fails fast instead
@@ -1839,7 +2013,12 @@ export async function runCreateFromPlan(opts, deps = {}) {
1839
2013
  // `runTestRun` call in the --run chain below sets `skipPreflight: true`
1840
2014
  // so this exact URL is never probed twice.
1841
2015
  if (opts.targetUrl !== undefined && opts.run === true && !opts.dryRun) {
1842
- await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
2016
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, {
2017
+ fetchImpl: deps.fetchImpl,
2018
+ proxyActive: isProxyAgentActive(),
2019
+ shutdownSignal: shutdownOf(deps).signal,
2020
+ shutdown: shutdownOf(deps),
2021
+ }, stderrFn);
1843
2022
  }
1844
2023
  const client = makeClient(opts, deps);
1845
2024
  const out = makeOutput(opts.output, deps);
@@ -1853,10 +2032,10 @@ export async function runCreateFromPlan(opts, deps = {}) {
1853
2032
  body,
1854
2033
  headers: { 'idempotency-key': idempotencyKey },
1855
2034
  });
1856
- // Fix 5 (plan-from coverage): the projectId for the deep-link comes from
1857
- // the validated PLAN body (not opts — `--plan-from` has no --project-id
2035
+ // For plan-from coverage, the projectId for the deep-link comes from the
2036
+ // validated PLAN body (not opts — `--plan-from` has no --project-id
1858
2037
  // flag). Same dry-run suppression as runCreate (fake canned test id).
1859
- // DEV-737: prefer a server-provided dashboardUrl over the client guess
2038
+ // Prefer a server-provided dashboardUrl over the client guess
1860
2039
  // (`withDashboardUrl`/`resolveDashboardUrl`, defined near
1861
2040
  // `withRunDashboardUrl`); never fall back when the server explicitly
1862
2041
  // withheld one, and tell the caller where to find the test instead.
@@ -1908,68 +2087,40 @@ export async function runCreateFromPlan(opts, deps = {}) {
1908
2087
  * on success, throws a typed `VALIDATION_ERROR` envelope on any
1909
2088
  * schema problem (missing fields, wrong types, oversize body, etc.).
1910
2089
  *
1911
- * Stat-first guard mirrors piece-2's `readCodeFileGuarded` — reject
1912
- * obvious oversize files BEFORE loading them into V8's heap. For
1913
- * plans the cap is 256 KB (vs. 350 KB for code).
2090
+ * Size-capped guard: reject obvious oversize files BEFORE loading them
2091
+ * into V8's heap. For plans the cap is 256 KB (vs. 350 KB for code).
1914
2092
  */
1915
2093
  function readPlanFromGuarded(path, context = {}) {
1916
2094
  return assertPlanShape(parsePlanFile(path), context);
1917
2095
  }
1918
2096
  /**
1919
2097
  * File I/O + JSON.parse half of `readPlanFromGuarded`, split out so `test
1920
- * lint` can reuse the SAME stat/size/read/parse guards while
2098
+ * lint` can reuse the SAME open/size/read guards while
1921
2099
  * substituting the collect-all `collectPlanIssues` shape check for the
1922
2100
  * throw-on-first `assertPlanShape` that `create`/`create-batch` still use. A
1923
2101
  * failure here (missing file, oversize, invalid JSON syntax) is always a
1924
2102
  * single fatal issue either way — there is nothing left to validate once the
1925
2103
  * file itself can't be read or parsed.
1926
- *
1927
- * Stat-first guard mirrors piece-2's `readCodeFileGuarded` — reject
1928
- * obvious oversize files BEFORE loading them into V8's heap. For
1929
- * plans the cap is 256 KB (vs. 350 KB for code).
1930
2104
  */
1931
2105
  function parsePlanFile(path) {
1932
- const absolute = resolveAbsolute(path);
1933
- let stat;
1934
- try {
1935
- stat = statSync(absolute);
1936
- }
1937
- catch (err) {
1938
- const code = err.code;
1939
- if (code === 'ENOENT') {
1940
- throw localValidationError('plan-from', `file does not exist: ${path}`);
1941
- }
1942
- if (code === 'EACCES') {
1943
- throw localValidationError('plan-from', `permission denied reading ${path}`);
1944
- }
1945
- const reason = err instanceof Error ? err.message : 'unknown error';
1946
- throw localValidationError('plan-from', `cannot stat ${path}: ${reason}`);
1947
- }
1948
- if (stat.size > MAX_PLAN_BODY_BYTES) {
2106
+ const result = readCappedFileGuarded('plan-from', path, MAX_PLAN_BODY_BYTES);
2107
+ if (!result.ok) {
1949
2108
  throw ApiError.fromEnvelope({
1950
2109
  error: {
1951
2110
  code: 'PAYLOAD_TOO_LARGE',
1952
- message: `Plan body exceeds the 256 KB CLI cap (${stat.size} bytes).`,
2111
+ message: `Plan body exceeds the 256 KB CLI cap (${result.sizeBytes} bytes).`,
1953
2112
  nextAction: 'Split into multiple smaller tests or trim step descriptions.',
1954
2113
  requestId: 'local',
1955
2114
  details: {
1956
2115
  field: 'plan-from',
1957
- sizeBytes: stat.size,
2116
+ sizeBytes: result.sizeBytes,
1958
2117
  maxBytes: MAX_PLAN_BODY_BYTES,
1959
2118
  },
1960
2119
  },
1961
2120
  });
1962
2121
  }
1963
- let raw;
1964
- try {
1965
- raw = stripBom(readFileSync(absolute, 'utf8'));
1966
- }
1967
- catch (err) {
1968
- const reason = err instanceof Error ? err.message : 'unknown error';
1969
- throw localValidationError('plan-from', `cannot read ${path}: ${reason}`);
1970
- }
1971
2122
  try {
1972
- return JSON.parse(raw);
2123
+ return JSON.parse(result.raw);
1973
2124
  }
1974
2125
  catch (err) {
1975
2126
  const reason = err instanceof Error ? err.message : 'unknown error';
@@ -2169,6 +2320,10 @@ function collectPlanIssues(parsed, context = {}) {
2169
2320
  * falls back to 1 for mixed outcomes.
2170
2321
  */
2171
2322
  export async function runCreateBatch(opts, deps = {}) {
2323
+ if (opts.environment !== undefined && opts.run !== true) {
2324
+ throw localValidationError('env', '--env requires --run');
2325
+ }
2326
+ normalizeEnvironmentName(opts.environment);
2172
2327
  assertIdempotencyKey(opts.idempotencyKey);
2173
2328
  // Exactly one of --plans or --plan-from-dir is required.
2174
2329
  if (opts.planFromDir !== undefined && opts.plans !== undefined && opts.plans !== '') {
@@ -2284,12 +2439,12 @@ export async function runCreateBatch(opts, deps = {}) {
2284
2439
  },
2285
2440
  });
2286
2441
  }
2287
- // Fix 5: enrich results with per-item dashboardUrl.
2288
- // projectId comes from specs[specIndex].projectId; testId from the result row.
2289
- // Only emitted where both are known client-side — no extra network calls.
2290
- // R1: suppress under --dry-run — test ids are fake canned values and a
2291
- // live-looking URL would mislead the caller.
2292
- // DEV-737: prefer a server-provided per-item dashboardUrl over the client
2442
+ // Enrich results with per-item dashboardUrl. projectId comes from
2443
+ // specs[specIndex].projectId; testId from the result row. Only emitted
2444
+ // where both are known client-side — no extra network calls. Suppressed
2445
+ // under --dry-run — test ids are fake canned values and a live-looking URL
2446
+ // would mislead the caller.
2447
+ // Prefer a server-provided per-item dashboardUrl over the client
2293
2448
  // guess (`withDashboardUrl`/`resolveDashboardUrl`, defined near
2294
2449
  // `withRunDashboardUrl`); never fall back when the server explicitly
2295
2450
  // withheld one for a given item — that would print exactly the dead
@@ -2439,10 +2594,17 @@ testIdToDashboardState) {
2439
2594
  // it never reaches this fan-out at all — see the `beIndexes` warning in
2440
2595
  // `runCreateBatch`).
2441
2596
  if (opts.targetUrl !== undefined) {
2442
- await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
2597
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, {
2598
+ fetchImpl: deps.fetchImpl,
2599
+ proxyActive: isProxyAgentActive(),
2600
+ shutdownSignal: shutdownOf(deps).signal,
2601
+ shutdown: shutdownOf(deps),
2602
+ }, stderrFn);
2443
2603
  }
2444
2604
  const batchRunResults = [];
2445
- const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
2605
+ const billingRunErrors = [];
2606
+ const sleepFn = deps.sleep ?? defaultSleep;
2607
+ const shutdown = shutdownOf(deps);
2446
2608
  // Response-driven --target-url advisory, fired at most ONCE for the whole
2447
2609
  // batch (Finding 2's contract) the first time any member's trigger
2448
2610
  // response reports a target different from what was requested — see the
@@ -2470,11 +2632,11 @@ testIdToDashboardState) {
2470
2632
  * Returns a CliBatchRunResult. Never throws — errors are captured
2471
2633
  * into the result's `error` field so one failure doesn't abort siblings.
2472
2634
  * (Exception: InterruptError rethrows so the collect point can print the
2473
- * partial — DEV-331.)
2635
+ * partial.)
2474
2636
  */
2475
2637
  // testId → dispatched runId for members still mid-poll; the interrupt
2476
2638
  // partial reads it because a member's runId is local to triggerOne until
2477
- // the poll settles (DEV-331, codex finding 2).
2639
+ // the poll settles.
2478
2640
  const dispatchedRunIds = new Map();
2479
2641
  async function triggerOne(testId) {
2480
2642
  // Mint a fresh idempotency key per run — MUST NOT reuse the create key.
@@ -2543,10 +2705,14 @@ testIdToDashboardState) {
2543
2705
  if (opts.debug) {
2544
2706
  stderrFn(`[batch-run] ${testId} — rate throttle: waiting ${Math.ceil(clampedWait / 1000)}s before trigger`);
2545
2707
  }
2546
- await sleepFn(clampedWait);
2708
+ await sleepUntilOrInterrupt(clampedWait, shutdown.signal, sleepFn);
2547
2709
  }
2548
2710
  try {
2549
- const result = await client.triggerRunWithMeta(testId, { source: 'cli', ...(opts.targetUrl ? { targetUrl: opts.targetUrl } : {}) },
2711
+ const result = await client.triggerRunWithMeta(testId, {
2712
+ source: 'cli',
2713
+ ...(opts.targetUrl ? { targetUrl: opts.targetUrl } : {}),
2714
+ ...(opts.environment !== undefined ? { environment: opts.environment.trim() } : {}),
2715
+ },
2550
2716
  // retryOnRateLimit: false — the outer retry loop is the SOLE owner of
2551
2717
  // rate-limit handling for the batch path. Allowing the HTTP layer to add
2552
2718
  // up to 3 internal retries per outer attempt would multiply trigger
@@ -2568,9 +2734,12 @@ testIdToDashboardState) {
2568
2734
  catch (err) {
2569
2735
  // Interrupt must reject the fan-out (the collect point prints the
2570
2736
  // partial for every spec), never flatten into a per-member outcome
2571
- // that would swallow the 128+signum exit (DEV-331).
2737
+ // that would swallow the 128+signum exit.
2572
2738
  if (err instanceof InterruptError)
2573
2739
  throw err;
2740
+ if (err instanceof ApiError && classifyBillingRefusal(err)) {
2741
+ billingRunErrors.push(err);
2742
+ }
2574
2743
  // RATE_LIMITED outer retry. Since the HTTP layer no longer retries
2575
2744
  // RATE_LIMITED (retryOnRateLimit: false above), every 429 reaches here
2576
2745
  // on the first attempt.
@@ -2620,7 +2789,7 @@ testIdToDashboardState) {
2620
2789
  };
2621
2790
  }
2622
2791
  stderrFn(`[batch-run] ${testId} — RATE_LIMITED (outer attempt ${outerRateLimitAttempt}/${BATCH_RUN_RATE_MAX_OUTER_RETRIES}): waiting ${Math.ceil(clampedRetryMs / 1000)}s before retry`);
2623
- await sleepFn(clampedRetryMs);
2792
+ await sleepUntilOrInterrupt(clampedRetryMs, shutdown.signal, sleepFn);
2624
2793
  continue; // retry the outer loop
2625
2794
  }
2626
2795
  // Exceeded outer retry cap — surface as terminal error.
@@ -2691,8 +2860,7 @@ testIdToDashboardState) {
2691
2860
  }
2692
2861
  // Record the dispatched runId (fresh trigger OR conflict-resume) so the
2693
2862
  // interrupt partial at the collect point can name every in-flight run —
2694
- // a member's runId is otherwise local until its poll settles (DEV-331,
2695
- // codex finding 2).
2863
+ // a member's runId is otherwise local until its poll settles.
2696
2864
  if (triggerResponse.runId)
2697
2865
  dispatchedRunIds.set(testId, triggerResponse.runId);
2698
2866
  if (!opts.wait) {
@@ -2772,6 +2940,8 @@ testIdToDashboardState) {
2772
2940
  };
2773
2941
  }
2774
2942
  const apiErr = err instanceof ApiError ? err : undefined;
2943
+ if (apiErr && classifyBillingRefusal(apiErr))
2944
+ billingRunErrors.push(apiErr);
2775
2945
  return {
2776
2946
  testId,
2777
2947
  runId: triggerResponse.runId,
@@ -2826,13 +2996,13 @@ testIdToDashboardState) {
2826
2996
  });
2827
2997
  }
2828
2998
  catch (fanOutErr) {
2829
- // Graceful detach (DEV-331): leave stdout parseable — settled members keep
2999
+ // Graceful detach: leave stdout parseable — settled members keep
2830
3000
  // their real status, unfinished ones are marked running — then rethrow so
2831
3001
  // index.ts exits 128+signum.
2832
3002
  if (fanOutErr instanceof InterruptError) {
2833
3003
  const settled = new Map(batchRunResults.map(r => [r.testId, r]));
2834
3004
  // Members mid-poll have no settled result yet — their runId comes from
2835
- // the dispatchedRunIds map recorded at trigger time (codex finding 2).
3005
+ // the dispatchedRunIds map recorded at trigger time.
2836
3006
  const partialResults = testIds.map((testId) => settled.get(testId) ?? {
2837
3007
  testId,
2838
3008
  runId: dispatchedRunIds.get(testId) ?? '',
@@ -2844,6 +3014,7 @@ testIdToDashboardState) {
2844
3014
  .filter(r => r.status === 'running' && r.runId)
2845
3015
  .map(r => r.runId);
2846
3016
  if (unfinished.length > 0) {
3017
+ fanOutErr.runWaitContext = true;
2847
3018
  stderrFn(interruptDetachMessage(fanOutErr, unfinished));
2848
3019
  }
2849
3020
  else {
@@ -2925,6 +3096,28 @@ testIdToDashboardState) {
2925
3096
  if (allTimeout) {
2926
3097
  throw new CLIError(`All ${batchRunResults.length} batch run(s) timed out after ${timeoutSeconds}s.`, 7);
2927
3098
  }
3099
+ if (failing.length === batchRunResults.length && billingRunErrors.length === failing.length) {
3100
+ // Narrow exception to the uniform-reason check below (mirrors the same
3101
+ // rule in `resolveWaitFailure` / `isPausedRefusal`): a paused+credits
3102
+ // MIX is still every failure being a billing refusal, and paused wins —
3103
+ // paying credits cannot resume the workspace. Checked first so it isn't
3104
+ // masked by the stricter "every reason identical" gate right after it.
3105
+ const paused = billingRunErrors.filter(e => classifyBillingRefusal(e)?.reason === 'paused');
3106
+ if (paused.length > 0 &&
3107
+ billingRunErrors.every(e => {
3108
+ const r = classifyBillingRefusal(e)?.reason;
3109
+ return r === 'paused' || r === 'insufficient_credits';
3110
+ })) {
3111
+ throw paused[0];
3112
+ }
3113
+ const first = billingRunErrors[0];
3114
+ const reason = first && classifyBillingRefusal(first)?.reason;
3115
+ if (first &&
3116
+ reason &&
3117
+ billingRunErrors.every(e => e.code === first.code && classifyBillingRefusal(e)?.reason === reason)) {
3118
+ throw first;
3119
+ }
3120
+ }
2928
3121
  // If all failing results share the same specific exit code (6 or 11), use it.
2929
3122
  if (errorExitCodes.length > 0 && errorExitCodes.length === failing.length) {
2930
3123
  const uniformCode = errorExitCodes[0];
@@ -2947,42 +3140,19 @@ testIdToDashboardState) {
2947
3140
  * specs at 50 before any per-spec work happens.
2948
3141
  */
2949
3142
  function readPlansJsonlGuarded(path) {
2950
- const absolute = resolveAbsolute(path);
2951
- let stat;
2952
- try {
2953
- stat = statSync(absolute);
2954
- }
2955
- catch (err) {
2956
- const code = err.code;
2957
- if (code === 'ENOENT') {
2958
- throw localValidationError('plans', `file does not exist: ${path}`);
2959
- }
2960
- if (code === 'EACCES') {
2961
- throw localValidationError('plans', `permission denied reading ${path}`);
2962
- }
2963
- const reason = err instanceof Error ? err.message : 'unknown error';
2964
- throw localValidationError('plans', `cannot stat ${path}: ${reason}`);
2965
- }
2966
- if (stat.size > MAX_BATCH_BODY_BYTES) {
3143
+ const result = readCappedFileGuarded('plans', path, MAX_BATCH_BODY_BYTES);
3144
+ if (!result.ok) {
2967
3145
  throw ApiError.fromEnvelope({
2968
3146
  error: {
2969
3147
  code: 'PAYLOAD_TOO_LARGE',
2970
- message: `Batch file exceeds the 5 MB CLI cap (${stat.size} bytes).`,
3148
+ message: `Batch file exceeds the 5 MB CLI cap (${result.sizeBytes} bytes).`,
2971
3149
  nextAction: 'Split into multiple --plans files.',
2972
3150
  requestId: 'local',
2973
- details: { field: 'plans', sizeBytes: stat.size, maxBytes: MAX_BATCH_BODY_BYTES },
3151
+ details: { field: 'plans', sizeBytes: result.sizeBytes, maxBytes: MAX_BATCH_BODY_BYTES },
2974
3152
  },
2975
3153
  });
2976
3154
  }
2977
- let raw;
2978
- try {
2979
- raw = stripBom(readFileSync(absolute, 'utf8'));
2980
- }
2981
- catch (err) {
2982
- const reason = err instanceof Error ? err.message : 'unknown error';
2983
- throw localValidationError('plans', `cannot read ${path}: ${reason}`);
2984
- }
2985
- const lines = raw
3155
+ const lines = result.raw
2986
3156
  .split('\n')
2987
3157
  .map(l => l.trim())
2988
3158
  .filter(l => l.length > 0);
@@ -3993,8 +4163,13 @@ export async function runSteps(opts, deps = {}) {
3993
4163
  stderrFn(earlier
3994
4164
  ? `Latest run has no steps; inspect an earlier run: testsprite test steps ${opts.testId} --run-id ${earlier.runId}`
3995
4165
  : `Latest run has no steps; inspect run history: testsprite test result ${opts.testId} --history`);
4166
+ const note = historyRetentionNote(history.meta, historyClient.resolvedBaseUrl, true);
4167
+ if (note)
4168
+ stderrFn(note);
3996
4169
  }
3997
- catch {
4170
+ catch (err) {
4171
+ if (err instanceof InterruptError)
4172
+ throw err;
3998
4173
  // Missing history must not change the steps page or the command's exit code.
3999
4174
  }
4000
4175
  finally {
@@ -4115,11 +4290,16 @@ export async function runResultHistory(opts, deps = {}) {
4115
4290
  // and short-page hints below cover that.
4116
4291
  const runs = opts.rerun === undefined ? resp.runs : resp.runs.filter(r => r.isRerun === opts.rerun);
4117
4292
  if (opts.output !== 'text') {
4118
- out.print({ runs, nextCursor: resp.nextCursor }, data => JSON.stringify(data));
4293
+ out.print({ ...resp, runs }, data => JSON.stringify(data));
4119
4294
  return { ...resp, runs };
4120
4295
  }
4121
4296
  // Text mode rendering
4122
4297
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4298
+ const retentionNote = historyRetentionNote(resp.meta, client.resolvedBaseUrl);
4299
+ const printRetentionNote = () => {
4300
+ if (retentionNote)
4301
+ stderr(retentionNote);
4302
+ };
4123
4303
  // Empty / pre-cutover: print the backend meta.note instead of a blank table.
4124
4304
  // EXCEPTION: if nextCursor is non-null this page is empty only because the
4125
4305
  // backend filters AFTER limiting rows (limit-before-filter). Matching runs
@@ -4134,6 +4314,7 @@ export async function runResultHistory(opts, deps = {}) {
4134
4314
  if (resp.meta.portalUrl) {
4135
4315
  stderr(` Portal: ${resp.meta.portalUrl}`);
4136
4316
  }
4317
+ printRetentionNote();
4137
4318
  return resp;
4138
4319
  }
4139
4320
  // Truly empty (nextCursor is null): pre-cutover or genuinely no history.
@@ -4143,6 +4324,7 @@ export async function runResultHistory(opts, deps = {}) {
4143
4324
  if (resp.meta.portalUrl) {
4144
4325
  stderr(` Portal: ${resp.meta.portalUrl}`);
4145
4326
  }
4327
+ printRetentionNote();
4146
4328
  return resp;
4147
4329
  }
4148
4330
  const lines = [];
@@ -4163,6 +4345,7 @@ export async function runResultHistory(opts, deps = {}) {
4163
4345
  stderr(`[hint] Fewer than ${pageSize} rows returned but more may exist — ` +
4164
4346
  `a source/rerun filter skipped some entries. Pass --cursor ${resp.nextCursor} to continue.`);
4165
4347
  }
4348
+ printRetentionNote();
4166
4349
  return { ...resp, runs };
4167
4350
  }
4168
4351
  /**
@@ -4350,6 +4533,8 @@ export async function runFailureGet(opts, deps = {}) {
4350
4533
  dir: resolvedDir,
4351
4534
  failedOnly: opts.failedOnly,
4352
4535
  fetchImpl: deps.fetchImpl,
4536
+ shutdownSignal: shutdownOf(deps).signal,
4537
+ shutdown: shutdownOf(deps),
4353
4538
  });
4354
4539
  if (opts.output === 'json') {
4355
4540
  out.print({ ok: true, dir: bundle.dir, meta: bundle.meta, files: bundle.files });
@@ -4569,7 +4754,7 @@ function printRunOrChain(out, payload, createContext, textRenderer) {
4569
4754
  * Server-first precedence for a `dashboardUrl` field on any wire response
4570
4755
  * that can carry one (`RunResponse`, `CliCreateTestResponse`,
4571
4756
  * `CliBatchSpecResult`). Single source of truth for the rule so the create
4572
- * paths (DEV-737) and the run-completion path (`withRunDashboardUrl` below)
4757
+ * paths and the run-completion path (`withRunDashboardUrl` below)
4573
4758
  * can't drift apart.
4574
4759
  *
4575
4760
  * This is a PINNED three-state wire contract — a prior revision let a
@@ -4609,7 +4794,7 @@ function resolveDashboardUrl(wire, computeFallback) {
4609
4794
  * `undefined` so `JSON.stringify` omits the key entirely instead of
4610
4795
  * serializing a literal `"dashboardUrl": null` — the same normalization
4611
4796
  * `withRunDashboardUrl` already did inline for `RunResponse`, generalized
4612
- * here so the create paths (DEV-737) can share it byte-for-byte.
4797
+ * here so the create paths can share it byte-for-byte.
4613
4798
  */
4614
4799
  function withDashboardUrl(wire, computeFallback) {
4615
4800
  const { dashboardUrl, suppressed } = resolveDashboardUrl(wire, computeFallback);
@@ -4618,7 +4803,7 @@ function withDashboardUrl(wire, computeFallback) {
4618
4803
  return { entity: dashboardUrl !== undefined ? { ...wire, dashboardUrl } : wire, suppressed };
4619
4804
  }
4620
4805
  /**
4621
- * DEV-737: advisory printed when the server explicitly withheld a dashboard
4806
+ * Advisory printed when the server explicitly withheld a dashboard
4622
4807
  * link (`resolveDashboardUrl`'s `suppressed: true`) rather than silently
4623
4808
  * omitting the field with no explanation. Fires on stderr regardless of
4624
4809
  * `--output` mode — the field's absence from a JSON envelope carries no
@@ -4724,10 +4909,11 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
4724
4909
  }
4725
4910
  /**
4726
4911
  * Best-effort resolve whether a finished run's test is a backend test, for the
4727
- * text run-card's step line + failure hint only (DEV-282). Returns true with no
4912
+ * text run-card's step line + failure hint only. Returns true with no
4728
4913
  * network call when already known (create-chain `--type`, or the BE wait
4729
4914
  * fallback fired). Otherwise, in TEXT mode only, issues one `GET /tests/{id}`;
4730
- * any error → false (render the numeric step summary as before). JSON mode
4915
+ * ordinary lookup errors → false (render the numeric step summary as before).
4916
+ * Interrupts propagate. JSON mode
4731
4917
  * never probes — its envelope carries `stepSummary` verbatim and has no
4732
4918
  * "n/a (backend)" concept, so it is already correct.
4733
4919
  *
@@ -4745,7 +4931,9 @@ async function resolveRunCardIsBackend(client, testId, output, alreadyKnown) {
4745
4931
  const test = await client.get(`/tests/${encodeURIComponent(testId)}`);
4746
4932
  return test.type === 'backend';
4747
4933
  }
4748
- catch {
4934
+ catch (err) {
4935
+ if (err instanceof InterruptError)
4936
+ throw err;
4749
4937
  return false; // best-effort — fall back to the numeric step summary.
4750
4938
  }
4751
4939
  }
@@ -4783,7 +4971,7 @@ function describeEnvironmentLine(r) {
4783
4971
  return r.environment?.name ?? '—';
4784
4972
  }
4785
4973
  /**
4786
- * Validate `--env <name>` (DEV-1305). The name is passed to the server
4974
+ * Validate `--env <name>`. The name is passed to the server
4787
4975
  * verbatim (it resolves `unique(project_id, name)` and lists the valid names
4788
4976
  * on a miss); the only local rule is that an empty/whitespace value is a typo,
4789
4977
  * not a request for the default environment — omitting the flag is.
@@ -4797,6 +4985,77 @@ function normalizeEnvironmentName(raw) {
4797
4985
  }
4798
4986
  return name;
4799
4987
  }
4988
+ /** Check a local run's test type and named environment before minting a tunnel. */
4989
+ async function preflightLocalRunTest(args) {
4990
+ const { client, testId, environment, localPort, opts, deps } = args;
4991
+ let test = args.knownTest;
4992
+ if (test === undefined) {
4993
+ try {
4994
+ test = await client.get(`/tests/${encodeURIComponent(testId)}`);
4995
+ }
4996
+ catch (err) {
4997
+ if (err instanceof InterruptError)
4998
+ throw err;
4999
+ const message = `Cannot read test ${testId} for --local preflight.`;
5000
+ if (err instanceof ApiError) {
5001
+ if (err.httpStatus !== 403 && err.httpStatus !== 404 && !(err instanceof TransportError)) {
5002
+ throw err;
5003
+ }
5004
+ throw new ApiError({
5005
+ code: err.code,
5006
+ message,
5007
+ nextAction: 'Check the test ID and read:tests permission, then retry.',
5008
+ requestId: err.requestId,
5009
+ details: {},
5010
+ }, err.httpStatus);
5011
+ }
5012
+ if (err instanceof RequestTimeoutError)
5013
+ throw err;
5014
+ throw new CLIError(message);
5015
+ }
5016
+ }
5017
+ if (test.type === 'backend') {
5018
+ throw localValidationError('local', `backend tests don't open a browser; the tunnel is not used. Run: testsprite test run ${testId}`);
5019
+ }
5020
+ if (environment === undefined)
5021
+ return;
5022
+ let listing;
5023
+ try {
5024
+ listing = await client.get(`/projects/${encodeURIComponent(test.projectId)}/env`);
5025
+ }
5026
+ catch (err) {
5027
+ if (err instanceof InterruptError)
5028
+ throw err;
5029
+ if (!(err instanceof TransportError) &&
5030
+ !(err instanceof RequestTimeoutError) &&
5031
+ !(err instanceof ApiError &&
5032
+ (err.httpStatus === 403 || err.httpStatus === 404 || (err.httpStatus ?? 0) >= 500))) {
5033
+ throw err;
5034
+ }
5035
+ if (opts.verbose || opts.debug) {
5036
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
5037
+ stderr('[verbose] environment preflight skipped: project environments unavailable; the server will validate this run.');
5038
+ }
5039
+ }
5040
+ if (listing === undefined)
5041
+ return;
5042
+ const selected = listing.environments.find(row => row.name === environment);
5043
+ if (selected === undefined) {
5044
+ const available = listing.environments.map(row => row.name).sort();
5045
+ throw localValidationError('env', `unknown environment '${environment}'; use one of: ${available.join(', ')}`, available);
5046
+ }
5047
+ let isLoopback = false;
5048
+ try {
5049
+ normalizeLocalHost(new URL(selected.url).hostname);
5050
+ isLoopback = true;
5051
+ }
5052
+ catch {
5053
+ // A public environment cannot be reached through this local tunnel.
5054
+ }
5055
+ if (!isLoopback) {
5056
+ throw localValidationError('local', `This environment has a public URL. Run testsprite test run ${testId} --env ${environment} without --local, or testsprite test run ${testId} --local ${localPort} without --env.`);
5057
+ }
5058
+ }
4800
5059
  /**
4801
5060
  * Validate the `--timeout` flag value. Returns a clamped integer in
4802
5061
  * range [1, 3600], or the default when absent.
@@ -4831,6 +5090,48 @@ function parseStepTimeoutFlag(raw, flagName) {
4831
5090
  * Exit code is 0 on `passed`, 1 on `failed`/`blocked`/`cancelled`,
4832
5091
  * 7 on timeout.
4833
5092
  */
5093
+ /**
5094
+ * Say something when `--no-auto-heal` did not take.
5095
+ *
5096
+ * The opt-out was unfalsifiable before the server started echoing its effective
5097
+ * decision: the backend runs `whitelist: true`, so a CLI sending `autoHeal` to a
5098
+ * server that predates the field has it silently stripped, the run heals, and
5099
+ * every surface reports success. Two distinguishable failures, and the remedies
5100
+ * differ, so they get different messages:
5101
+ *
5102
+ * - echo ABSENT → the server does not know the option at all (older backend).
5103
+ * - echo `true` → the server knows it and declined it.
5104
+ *
5105
+ * Silent on the happy path and on every run that did not ask for the opt-out.
5106
+ * Never throws: an advisory must not be able to fail a run that was accepted.
5107
+ */
5108
+ function warnIfOptOutIgnored(requested, echoed, stderrFn, label,
5109
+ /**
5110
+ * States already reported by an earlier dispatch in the same invocation.
5111
+ * `test run --all` can dispatch more than once — the deferred-retry leg
5112
+ * re-sends the opt-out, so it has to be checked too, or the tests a rate
5113
+ * limit pushed into the retry would be the only ones running unwarned. Those
5114
+ * are also the likeliest to land on a differently-configured instance during a
5115
+ * rollout, which is why this dedupes on the OUTCOME rather than firing once:
5116
+ * a retry whose echo disagrees with the first attempt's is new information and
5117
+ * still warns.
5118
+ */
5119
+ reported) {
5120
+ if (requested !== false)
5121
+ return;
5122
+ if (echoed === false)
5123
+ return;
5124
+ const outcome = echoed === undefined ? 'unsupported' : 'declined';
5125
+ if (reported?.has(outcome))
5126
+ return;
5127
+ reported?.add(outcome);
5128
+ if (echoed === undefined) {
5129
+ stderrFn(`[advisory] --no-auto-heal was sent but this backend does not support it yet, so it was ` +
5130
+ `ignored — ${label} may re-author drifted code. Check your endpoint with \`testsprite auth status\`.`);
5131
+ return;
5132
+ }
5133
+ stderrFn(`[advisory] --no-auto-heal was not applied by the server — ${label} may re-author drifted code.`);
5134
+ }
4834
5135
  export async function runTestRun(opts, deps = {}) {
4835
5136
  assertIdempotencyKey(opts.idempotencyKey);
4836
5137
  const environment = normalizeEnvironmentName(opts.environment);
@@ -4917,6 +5218,16 @@ export async function runTestRun(opts, deps = {}) {
4917
5218
  const requestTimeoutMs = resolveWaitRequestTimeoutMs(opts);
4918
5219
  const clientOpts = { ...opts, requestTimeoutMs };
4919
5220
  const client = makeClient(clientOpts, deps);
5221
+ if (isTunnelRun) {
5222
+ await preflightLocalRunTest({
5223
+ client,
5224
+ testId: opts.testId,
5225
+ environment,
5226
+ localPort: opts.localPort,
5227
+ opts,
5228
+ deps,
5229
+ });
5230
+ }
4920
5231
  const tunnelRequestTimeoutMs = isTunnelRun
4921
5232
  ? resolveRequestTimeoutMs(clientOpts, deps.env ?? process.env)
4922
5233
  : undefined;
@@ -4932,12 +5243,12 @@ export async function runTestRun(opts, deps = {}) {
4932
5243
  // already ran this exact check against the same URL before its own
4933
5244
  // create POST and sets `skipPreflight: true` here to avoid probing twice.
4934
5245
  if (isTunnelRun) {
4935
- // The tunnel-run equivalent of the --target-url probe, and the reason
4936
- // DEV-868 exists: a dev server that is not running is the single most
4937
- // likely `--local` mistake, and this is the last moment it costs nothing.
4938
- // Unlike the --target-url probe this one is conclusive — the dial it
4939
- // performs is the same raw loopback connect the tunnel client will make
4940
- // from this same process — so it refuses rather than advises.
5246
+ // The tunnel-run equivalent of the --target-url probe: a dev server that
5247
+ // is not running is the single most likely `--local` mistake, and this is
5248
+ // the last moment it costs nothing to catch. Unlike the --target-url probe
5249
+ // this one is conclusive — the dial it performs is the same raw loopback
5250
+ // connect the tunnel client will make from this same process — so it
5251
+ // refuses rather than advises.
4941
5252
  await assertLocalPortListening(localHost, opts.localPort, { skipPreflight: opts.skipPreflight }, stderrFn);
4942
5253
  if (isProxyAgentActive()) {
4943
5254
  stderrFn('[advisory] An HTTP proxy is configured for this process. The tunnel control channel ' +
@@ -4946,7 +5257,12 @@ export async function runTestRun(opts, deps = {}) {
4946
5257
  }
4947
5258
  }
4948
5259
  else if (opts.targetUrl !== undefined) {
4949
- await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
5260
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, {
5261
+ fetchImpl: deps.fetchImpl,
5262
+ proxyActive: isProxyAgentActive(),
5263
+ shutdownSignal: shutdownOf(deps).signal,
5264
+ shutdown: shutdownOf(deps),
5265
+ }, stderrFn);
4950
5266
  }
4951
5267
  // Nothing above this line has spent money or minted a credential. Everything
4952
5268
  // below it must be unwound on every exit path, which is what the `finally`
@@ -4962,6 +5278,7 @@ export async function runTestRun(opts, deps = {}) {
4962
5278
  tunnelSession = await openTunnelSession({
4963
5279
  log: stderrFn,
4964
5280
  logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
5281
+ onMinted: minted => stderrFn(`[tunnel] Minted tunnel client ${minted.clientId}; connecting…`),
4965
5282
  onFatal: () => {
4966
5283
  // Surfaced to the poll loop through `onTick` below; a remint cannot
4967
5284
  // rescue this run (see `lib/tunnel-session.ts`).
@@ -4996,13 +5313,18 @@ export async function runTestRun(opts, deps = {}) {
4996
5313
  // bounded deadline so we can learn the runId if the server charged it.
4997
5314
  if (isTunnelRun && shutdown.signal.aborted)
4998
5315
  throw shutdown.signal.reason;
5316
+ if (isTunnelRun)
5317
+ recordTelemetryExtras({ localConcurrencyLimit: 1, localPeakInFlight: 0 });
4999
5318
  const triggerBody = {
5000
5319
  source: 'cli',
5001
5320
  ...(effectiveTargetUrl ? { targetUrl: effectiveTargetUrl } : {}),
5321
+ // Present ONLY as `false`. Omission is how the protected
5322
+ // default is requested — see `TriggerRunBody.autoHeal`.
5323
+ ...(opts.autoHeal === false ? { autoHeal: false } : {}),
5002
5324
  // The client ID only. The secret stays in this process and never
5003
5325
  // reaches a request body, an idempotency row, or an audit line.
5004
5326
  ...(tunnelSession ? { tunnelClientId: tunnelSession.clientId } : {}),
5005
- // Whose credentials to log in with (DEV-1305); the two fields above
5327
+ // Whose credentials to log in with; the two fields above
5006
5328
  // say where the browser goes. Absent → the project's default env.
5007
5329
  ...(environment !== undefined ? { environment } : {}),
5008
5330
  };
@@ -5011,6 +5333,11 @@ export async function runTestRun(opts, deps = {}) {
5011
5333
  : await client.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey });
5012
5334
  triggerResponse = result.body;
5013
5335
  triggerRequestId = result.requestId;
5336
+ // Counted once the server accepted the run: a refused trigger carried
5337
+ // nothing through the tunnel.
5338
+ if (isTunnelRun)
5339
+ recordTelemetryExtras({ localPeakInFlight: 1 });
5340
+ warnIfOptOutIgnored(opts.autoHeal, triggerResponse.autoHeal, stderrFn, 'this run');
5014
5341
  }
5015
5342
  catch (err) {
5016
5343
  // CONFLICT (409) can arise from two different causes:
@@ -5036,11 +5363,83 @@ export async function runTestRun(opts, deps = {}) {
5036
5363
  // auto-resume. Other CONFLICT reasons (snapshot_in_flight, etc.) exit 6.
5037
5364
  if (conflictReason === 'run_in_flight' && currentRunId !== undefined) {
5038
5365
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
5366
+ // Set only when a verified environment names a concrete retry — the
5367
+ // no-environment-recorded attach path has nothing to name.
5368
+ let retryFlags;
5369
+ const incompatibleRun = (reason) => new ApiError({
5370
+ code: 'CONFLICT',
5371
+ message: `Conflict: run ${currentRunId} is already in flight; ${reason}. This invocation cannot attach to it.`,
5372
+ nextAction: `Wait with testsprite test wait ${currentRunId}, or retry this run after it finishes.`,
5373
+ requestId: err.requestId,
5374
+ details: { reason: 'run_in_flight', currentRunId },
5375
+ });
5376
+ let inFlightRun;
5377
+ try {
5378
+ inFlightRun = await client.getRun(currentRunId);
5379
+ }
5380
+ catch (readErr) {
5381
+ if (readErr instanceof InterruptError)
5382
+ throw readErr;
5383
+ throw incompatibleRun('its environment could not be verified');
5384
+ }
5385
+ const inFlightEnvironment = inFlightRun.environment;
5386
+ // `undefined` (no key at all) is a V2 run or a backend that predates
5387
+ // environments on run reads; `null` is a V3 row that explicitly names no
5388
+ // environment, OR one whose environment lookup failed and was
5389
+ // swallowed server-side. Only the former may attach unverified —
5390
+ // treating `null` the same way would let a failed lookup slip
5391
+ // through the gate it exists to enforce.
5392
+ if (inFlightEnvironment === undefined) {
5393
+ if (environment !== undefined) {
5394
+ // --env was requested but this in-flight run has nothing
5395
+ // recorded to verify it against.
5396
+ throw incompatibleRun('its environment could not be verified');
5397
+ }
5398
+ // Restored 0.12.0 path: no environment recorded, none requested — attach.
5399
+ }
5400
+ else if (inFlightEnvironment === null ||
5401
+ typeof inFlightEnvironment.id !== 'string' ||
5402
+ inFlightEnvironment.id.length === 0) {
5403
+ throw incompatibleRun('its environment could not be verified');
5404
+ }
5405
+ else {
5406
+ let currentEnvironment;
5407
+ try {
5408
+ const listing = await client.get(`/projects/${encodeURIComponent(inFlightRun.projectId)}/env`);
5409
+ currentEnvironment = listing.environments.find(row => environment === undefined ? row.isDefault : row.name === environment);
5410
+ }
5411
+ catch (listErr) {
5412
+ if (listErr instanceof InterruptError)
5413
+ throw listErr;
5414
+ throw incompatibleRun('its environment could not be verified');
5415
+ }
5416
+ if (typeof currentEnvironment?.id !== 'string' || currentEnvironment.id.length === 0) {
5417
+ // The listing succeeded but named nothing we can compare against —
5418
+ // that is unverified, not a proven mismatch.
5419
+ throw incompatibleRun('its environment could not be verified');
5420
+ }
5421
+ if (currentEnvironment.id !== inFlightEnvironment.id) {
5422
+ throw incompatibleRun('its environment does not match the requested environment');
5423
+ }
5424
+ retryFlags = `--env ${currentEnvironment.name}`;
5425
+ try {
5426
+ const target = new URL(currentEnvironment.url);
5427
+ const host = normalizeLocalHost(target.hostname);
5428
+ if (target.protocol === 'http:' || target.protocol === 'https:') {
5429
+ const port = target.port || (target.protocol === 'https:' ? '443' : '80');
5430
+ retryFlags += ` --local ${port}`;
5431
+ if (host !== DEFAULT_LOCAL_HOST)
5432
+ retryFlags += ` --local-host ${host}`;
5433
+ }
5434
+ }
5435
+ catch {
5436
+ // Public environments need only --env on a later run.
5437
+ }
5438
+ }
5039
5439
  // If the caller supplied --target-url, verify the in-flight run targets
5040
5440
  // the same URL. A mismatch means we would be reporting a different
5041
5441
  // environment's results as if our requested environment was tested.
5042
5442
  if (opts.targetUrl !== undefined) {
5043
- const inFlightRun = await client.getRun(currentRunId);
5044
5443
  if (inFlightRun.targetUrl !== opts.targetUrl) {
5045
5444
  throw new ApiError({
5046
5445
  code: 'CONFLICT',
@@ -5073,31 +5472,21 @@ export async function runTestRun(opts, deps = {}) {
5073
5472
  };
5074
5473
  }
5075
5474
  else {
5076
- // D: No --target-url supplied — fetch the in-flight run so the
5077
- // synthesised triggerResponse.targetUrl is the REAL environment being
5078
- // tested, not an empty string that would propagate into the timeout
5079
- // partial (Finding D). Fall back to null (not '') if the lookup fails.
5080
- let inFlightTargetUrl = null;
5081
- let inFlightCodeVersion = '';
5082
- try {
5083
- const inFlightRun = await client.getRun(currentRunId);
5084
- inFlightTargetUrl = inFlightRun.targetUrl ?? null;
5085
- inFlightCodeVersion = inFlightRun.codeVersion ?? '';
5086
- }
5087
- catch {
5088
- // Best-effort — if the lookup fails, proceed with null targetUrl.
5089
- }
5090
- // Auto-resume but emit a stronger advisory so the caller is aware
5091
- // they are attaching to the project default.
5092
- // SIG-9 (DEV-331 final): the in-flight run is NOT auto-cancelled —
5093
- // name the real `test cancel` command instead of the old (false)
5094
- // "cancel with Ctrl-C" claim.
5475
+ // No --target-url supplied — use the verified in-flight run's real
5476
+ // target URL in the timeout partial instead of an empty string.
5477
+ const inFlightTargetUrl = inFlightRun.targetUrl ?? null;
5478
+ const inFlightCodeVersion = inFlightRun.codeVersion ?? '';
5479
+ // Auto-resume but name the verified environment for a later run,
5480
+ // when there is one to name — a run with no environment recorded
5481
+ // has nothing for `--env` to repeat. Either way, the in-flight run
5482
+ // is NOT auto-cancelled: name the real `test cancel` command
5483
+ // instead of a false "cancel with Ctrl-C" claim.
5095
5484
  stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
5096
5485
  (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
5097
5486
  `). Auto-resuming wait on in-flight run. ` +
5098
- `If you needed a specific target URL, cancel it with ` +
5099
- `testsprite test cancel ${currentRunId}, or re-trigger with ` +
5100
- `--target-url after it finishes.`);
5487
+ `To run it again, cancel it with ` +
5488
+ `testsprite test cancel ${currentRunId}, or wait for it to finish; ` +
5489
+ `then re-trigger${retryFlags ? ` with ${retryFlags}` : ''}.`);
5101
5490
  triggerResponse = {
5102
5491
  runId: currentRunId,
5103
5492
  status: 'queued',
@@ -5394,7 +5783,7 @@ export async function runTestRun(opts, deps = {}) {
5394
5783
  : rateLimitedDetachMessage(err, [triggerResponse.runId]));
5395
5784
  throw err;
5396
5785
  }
5397
- // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
5786
+ // Graceful detach on SIGINT/SIGTERM: same partial-
5398
5787
  // envelope shape as the timeout paths so stdout stays parseable, plus the
5399
5788
  // honest "keeps running and billing" stderr line. Rethrow → index.ts
5400
5789
  // renders the INTERRUPTED envelope and exits 128+signum.
@@ -5419,6 +5808,7 @@ export async function runTestRun(opts, deps = {}) {
5419
5808
  stderrFn(detach
5420
5809
  ? tunnelDetachMessage(detach, err)
5421
5810
  : interruptDetachMessage(err, [triggerResponse.runId]));
5811
+ err.runWaitContext = true;
5422
5812
  if (detach !== undefined)
5423
5813
  attachTunnelInterruptDetach(err, detach);
5424
5814
  throw err;
@@ -5458,7 +5848,7 @@ export async function runTestRun(opts, deps = {}) {
5458
5848
  ticker.finalize(formatRunProgressLine(finalRun, Date.now() - startMs));
5459
5849
  // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs); on
5460
5850
  // the standalone `test run <id>` path neither is set, so probe the test type
5461
- // once (text mode only, best-effort) — DEV-282.
5851
+ // once (text mode only, best-effort).
5462
5852
  const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
5463
5853
  const finalRunWithUrl = withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps));
5464
5854
  printRunOrChain(out, finalRunWithUrl, opts.createContext, data => renderRunResponseText(data, { isBackend }));
@@ -5547,7 +5937,7 @@ export async function runTestWaitMany(opts, deps = {}) {
5547
5937
  }
5548
5938
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
5549
5939
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
5550
- const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
5940
+ const sleepFn = deps.sleep ?? defaultSleep;
5551
5941
  // One shared deadline across every member (the whole point of the shared
5552
5942
  // pool: `--timeout 600` means the invocation ends within ~600s, not
5553
5943
  // 600s x ceil(N/concurrency)).
@@ -5604,7 +5994,7 @@ export async function runTestWaitMany(opts, deps = {}) {
5604
5994
  throw err;
5605
5995
  // Interrupt must reject the fan-out (handled at the collect point), not
5606
5996
  // be flattened into a per-member 'error' outcome that would swallow the
5607
- // 128+signum exit (DEV-331).
5997
+ // 128+signum exit.
5608
5998
  if (err instanceof InterruptError)
5609
5999
  throw err;
5610
6000
  if (err instanceof ApiError) {
@@ -5631,7 +6021,7 @@ export async function runTestWaitMany(opts, deps = {}) {
5631
6021
  stderrFn(`[wait] ${runId} — rate limited (attempt ${rateLimitAttempt}/${WAIT_POLL_RATE_MAX_OUTER_RETRIES}): retrying in ${Math.ceil(clampedRetryMs / 1000)}s`);
5632
6022
  // Arm the graceful-detach scope across the backoff. `pollRunUntilTerminal`
5633
6023
  // disarms in its own `finally`, so without this the sleep is a window
5634
- // where a first Ctrl-C hard-exits instead of taking the DEV-331 detach
6024
+ // where a first Ctrl-C hard-exits instead of taking the graceful-detach
5635
6025
  // path (partial `{runId, status:'running'}` on stdout + honest hint).
5636
6026
  const shutdown = shutdownOf(deps);
5637
6027
  const disarm = shutdown.arm();
@@ -5677,6 +6067,8 @@ export async function runTestWaitMany(opts, deps = {}) {
5677
6067
  }
5678
6068
  catch (fanOutErr) {
5679
6069
  if (fanOutErr instanceof RequestTimeoutError || fanOutErr instanceof InterruptError) {
6070
+ if (fanOutErr instanceof InterruptError)
6071
+ fanOutErr.runWaitContext = true;
5680
6072
  // Same contract as the batch pollers: leave stdout parseable before
5681
6073
  // exiting. Members that already settled keep their real status; only
5682
6074
  // the still-unfinished ids are marked running and named in the hint
@@ -5786,13 +6178,13 @@ export async function runTestWaitMany(opts, deps = {}) {
5786
6178
  return payload;
5787
6179
  }
5788
6180
  /**
5789
- * `test cancel <run-id...>` — DEV-331 piece 3.
6181
+ * `test cancel <run-id...>`.
5790
6182
  *
5791
6183
  * User-initiated cancel of one or more queued/running runs via
5792
- * `POST /api/cli/v1/runs/{runId}/cancel`. Naturally idempotent (D10): a
6184
+ * `POST /api/cli/v1/runs/{runId}/cancel`. Naturally idempotent: a
5793
6185
  * repeat cancel of the same run is a 200 `alreadyCancelled` success, not an
5794
- * error. Dispatches serially (per-id volume is tiny — no batch endpoint,
5795
- * D8 "Batch-level cancel endpoint... YAGNI").
6186
+ * error. Dispatches serially (per-id volume is tiny — no batch endpoint;
6187
+ * a batch-level cancel endpoint would be YAGNI).
5796
6188
  *
5797
6189
  * Single id: renders the returned run card (`status cancelled`); an
5798
6190
  * `alreadyCancelled` response adds an `[advisory]` line. Exit code mirrors
@@ -5832,6 +6224,8 @@ export async function runTestCancel(opts, deps = {}) {
5832
6224
  });
5833
6225
  }
5834
6226
  catch (err) {
6227
+ if (err instanceof InterruptError)
6228
+ throw err;
5835
6229
  if (err instanceof ApiError && err.code === 'NOT_FOUND') {
5836
6230
  rows.push({ runId, status: 'notFound' });
5837
6231
  continue;
@@ -5938,7 +6332,7 @@ export function createTestCancelCommand(deps) {
5938
6332
  .addHelpText('after', GLOBAL_OPTS_HINT)
5939
6333
  .action(async (runIds, _cmdOpts, command) => {
5940
6334
  await runTestCancel({
5941
- ...resolveCommonOptions(command),
6335
+ ...resolveCommonOptions(command, deps.env),
5942
6336
  runIds,
5943
6337
  }, deps);
5944
6338
  });
@@ -6071,7 +6465,7 @@ export async function runTestWait(opts, deps = {}) {
6071
6465
  stderrFn(rateLimitedDetachMessage(err, [opts.runId]));
6072
6466
  throw err;
6073
6467
  }
6074
- // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
6468
+ // Graceful detach on SIGINT/SIGTERM — see runTestRun.
6075
6469
  if (err instanceof InterruptError) {
6076
6470
  ticker.finalize(`Run ${opts.runId} — interrupted (${err.signal})`);
6077
6471
  const partial = { runId: opts.runId, status: 'running' };
@@ -6085,6 +6479,7 @@ export async function runTestWait(opts, deps = {}) {
6085
6479
  ].join('\n');
6086
6480
  });
6087
6481
  stderrFn(interruptDetachMessage(err, [opts.runId]));
6482
+ err.runWaitContext = true;
6088
6483
  throw err;
6089
6484
  }
6090
6485
  ticker.finalize();
@@ -6095,7 +6490,7 @@ export async function runTestWait(opts, deps = {}) {
6095
6490
  }
6096
6491
  ticker.finalize(formatRunProgressLine(finalRun, Date.now() - startMs));
6097
6492
  // `test wait` has no type hint; probe the test type once (text mode only,
6098
- // best-effort) so a backend run's card reads `n/a (backend)` — DEV-282.
6493
+ // best-effort) so a backend run's card reads `n/a (backend)`.
6099
6494
  const isBackend = await resolveRunCardIsBackend(client, finalRun.testId, opts.output, beFallbackUsed);
6100
6495
  out.print(withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), data => renderRunResponseText(data, { isBackend }));
6101
6496
  if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
@@ -6114,8 +6509,8 @@ export async function runTestWait(opts, deps = {}) {
6114
6509
  /**
6115
6510
  * Best-effort `testId → test name` map for the JUnit report, so a CI test tab
6116
6511
  * shows names instead of UUIDs. One paginated `GET /tests?projectId=` sweep,
6117
- * bounded by a 5 s deadline and swallowed on any error — a missing/partial map
6118
- * just falls back to ids, never blocks or fails the report.
6512
+ * bounded by a 5 s deadline. Ordinary lookup errors leave a missing/partial
6513
+ * map that falls back to ids; interrupts propagate.
6119
6514
  */
6120
6515
  async function buildTestNameMap(client, projectId) {
6121
6516
  const map = new Map();
@@ -6138,7 +6533,9 @@ async function buildTestNameMap(client, projectId) {
6138
6533
  break;
6139
6534
  }
6140
6535
  }
6141
- catch {
6536
+ catch (err) {
6537
+ if (err instanceof InterruptError)
6538
+ throw err;
6142
6539
  // best-effort — a partial/empty map simply falls back to ids in the report.
6143
6540
  }
6144
6541
  finally {
@@ -6169,6 +6566,31 @@ export async function writeBatchJUnitReportIfRequested(opts, results, nameByTest
6169
6566
  });
6170
6567
  await writeJUnitReportFile(opts.reportFile, xml);
6171
6568
  }
6569
+ /**
6570
+ * Cancel runs the caller can no longer use, without letting the cleanup itself
6571
+ * become the failure. Used when a batch dispatched successfully but the CLI
6572
+ * then discovered the dispatch was wrong to keep (the backend did not confirm
6573
+ * `--target-url`, so accepted runs may use a different target).
6574
+ * Leaving them would bill the user for a verdict nobody asked for.
6575
+ *
6576
+ * Every error is swallowed to a warning on purpose: the caller is already about
6577
+ * to throw the REAL error, and a cancel that 404s / conflicts (already terminal)
6578
+ * must not replace that error with a less useful one.
6579
+ */
6580
+ async function cancelRunsBestEffort(client, runIds, stderrFn, label) {
6581
+ if (runIds.length === 0)
6582
+ return;
6583
+ stderrFn(`[${label}] cancelling ${runIds.length} run${runIds.length !== 1 ? 's' : ''} dispatched against the wrong target…`);
6584
+ for (const runId of runIds) {
6585
+ try {
6586
+ const response = await client.cancelRun(runId);
6587
+ stderrFn(`[${label}] cancelled ${runId}; refund: ${response.refund?.status ?? 'not reported'}.`);
6588
+ }
6589
+ catch (err) {
6590
+ stderrFn(`[${label}] could not cancel ${runId}: ${err instanceof Error ? err.message : String(err)}; continuing`);
6591
+ }
6592
+ }
6593
+ }
6172
6594
  /** Human explanation for a zero-dispatch batch, from what the engine skipped. */
6173
6595
  function zeroDispatchReason(skippedFrontend, skippedIntegration) {
6174
6596
  const parts = [];
@@ -6226,7 +6648,7 @@ async function finishZeroDispatchBatch(params) {
6226
6648
  // write failure to a warning so an unwritable path can't mask the exit-5 intent
6227
6649
  // with an I/O exit code.
6228
6650
  try {
6229
- await writeBatchJUnitReportIfRequested(opts, runs.map(r => ({ testId: r.testId, status: 'skipped' })));
6651
+ await writeBatchJUnitReportIfRequested(opts, runs.map(r => ({ testId: r.testId, status: 'skipped', skipReason: r.error })));
6230
6652
  }
6231
6653
  catch (err) {
6232
6654
  stderrFn(`[${label}] could not write the JUnit report on a zero-dispatch run: ${err instanceof Error ? err.message : String(err)}; continuing`);
@@ -6266,7 +6688,7 @@ export async function runTestRunAll(opts, deps = {}) {
6266
6688
  const out = makeOutput(opts.output, deps);
6267
6689
  // --- Dry-run path ---
6268
6690
  if (opts.dryRun) {
6269
- // DEV-247: this path returns before makeClient() fires the banner, so emit it
6691
+ // This path returns before makeClient() fires the banner, so emit it
6270
6692
  // here — otherwise the canned sample can be mistaken for a live response.
6271
6693
  emitDryRunBanner(stderrFn);
6272
6694
  const idempotencyKey = opts.idempotencyKey ?? `dry-run-${randomUUID()}`;
@@ -6279,7 +6701,9 @@ export async function runTestRunAll(opts, deps = {}) {
6279
6701
  projectId,
6280
6702
  testIds: opts.nameFilter ? ['<filtered by --filter>'] : undefined,
6281
6703
  source: 'cli',
6704
+ ...(opts.autoHeal === false ? { autoHeal: false } : {}),
6282
6705
  ...(environment !== undefined ? { environment } : {}),
6706
+ ...(opts.targetUrl !== undefined ? { targetUrl: opts.targetUrl } : {}),
6283
6707
  },
6284
6708
  idempotencyKey,
6285
6709
  ...(opts.wait ? { thenPoll: '/api/cli/v1/runs/<run-id>?waitSeconds=25' } : {}),
@@ -6287,11 +6711,16 @@ export async function runTestRunAll(opts, deps = {}) {
6287
6711
  if (opts.report === 'junit' && opts.reportFile !== undefined) {
6288
6712
  await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(opts.projectId, opts.reportSuiteName));
6289
6713
  }
6290
- out.print(batchRunSample ?? envelope);
6714
+ out.print(opts.targetUrl !== undefined ? envelope : (batchRunSample ?? envelope));
6291
6715
  return undefined;
6292
6716
  }
6293
- // D4: under --wait, raise per-request timeout to cover --timeout.
6294
- const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
6717
+ // Probe once before dispatch. A preview still warming up can use
6718
+ // --skip-preflight; ambiguous probe results warn without blocking.
6719
+ if (opts.targetUrl !== undefined) {
6720
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
6721
+ }
6722
+ // D4: under --wait, raise per-request timeout to cover --timeout.
6723
+ const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
6295
6724
  // `--env` gate — see `runTestRun`. Before the test-set enumeration so a
6296
6725
  // gated batch makes no billable call at all.
6297
6726
  // Portal deep links for batch output: every test in the batch belongs to
@@ -6324,6 +6753,74 @@ export async function runTestRunAll(opts, deps = {}) {
6324
6753
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
6325
6754
  stderrFn(`idempotency-key: ${idempotencyKey}`);
6326
6755
  }
6756
+ // Every dispatch leg (first and deferred retries) sends the same fields.
6757
+ // `autoHeal` is present ONLY as `false`; omission requests the protected default.
6758
+ const dispatchFields = {
6759
+ source: 'cli',
6760
+ ...(opts.autoHeal === false ? { autoHeal: false } : {}),
6761
+ ...(environment !== undefined ? { environment } : {}),
6762
+ ...(opts.targetUrl !== undefined ? { targetUrl: opts.targetUrl } : {}),
6763
+ };
6764
+ async function assertBatchTargetEcho(response, previouslyAccepted) {
6765
+ if (opts.targetUrl === undefined || response.targetUrl === opts.targetUrl)
6766
+ return;
6767
+ const message = 'This backend did not confirm --target-url on the batch run; the accepted runs may have used another URL.';
6768
+ // Only this response's runs are unconfirmed. Runs an earlier leg confirmed
6769
+ // keep running against the right URL; they are reported as not awaited,
6770
+ // never cancelled.
6771
+ const unconfirmed = dedupeBatchRunFreshAccepted([...response.accepted]).deduped;
6772
+ const unconfirmedIds = new Set(unconfirmed.map(item => item.runId));
6773
+ const confirmed = dedupeBatchRunFreshAccepted([...previouslyAccepted]).deduped.filter(item => !unconfirmedIds.has(item.runId));
6774
+ await cancelRunsBestEffort(client, unconfirmed.map(item => item.runId), stderrFn, 'run');
6775
+ if (opts.wait) {
6776
+ const notAwaited = 'Not awaited: the batch stopped because a later dispatch did not confirm --target-url. ' +
6777
+ 'This run was confirmed and is still running; read it with testsprite test wait <run-id>.';
6778
+ const summary = summarizeAcceptedPayload(JSON.stringify({
6779
+ accepted: [
6780
+ ...confirmed.map(item => ({
6781
+ ...item,
6782
+ status: 'error',
6783
+ error: { message: notAwaited },
6784
+ })),
6785
+ ...unconfirmed.map(item => ({ ...item, status: 'error', error: { message } })),
6786
+ ],
6787
+ deferred: response.deferred,
6788
+ conflicts: response.conflicts,
6789
+ }));
6790
+ if (summary.total === 0) {
6791
+ summary.total = 1;
6792
+ summary.failed = 1;
6793
+ summary.runs.push({ testId: '(batch)', status: 'error', error: message });
6794
+ }
6795
+ emitCiArtifacts(summary, opts, {
6796
+ env: deps.env ?? process.env,
6797
+ stdout: deps.stdout ?? (line => process.stdout.write(`${line}\n`)),
6798
+ stderr: stderrFn,
6799
+ }, 'run');
6800
+ try {
6801
+ await writeBatchJUnitReportIfRequested(opts, summary.runs.map(row => ({
6802
+ testId: row.testId,
6803
+ runId: row.runId,
6804
+ status: isNonDispatchedStatus(row.status) ? 'skipped' : 'error',
6805
+ ...(isNonDispatchedStatus(row.status)
6806
+ ? { skipReason: row.error }
6807
+ : { error: { code: 'UNSUPPORTED', message: row.error ?? message, exitCode: 7 } }),
6808
+ })));
6809
+ }
6810
+ catch (err) {
6811
+ stderrFn(`[run] could not write the JUnit report: ${err instanceof Error ? err.message : String(err)}; continuing`);
6812
+ }
6813
+ }
6814
+ throw ApiError.fromEnvelope({
6815
+ error: {
6816
+ code: 'UNSUPPORTED',
6817
+ message,
6818
+ nextAction: 'Use a backend that supports batch target URL overrides, or retry without --target-url.',
6819
+ requestId: 'local',
6820
+ details: { field: 'targetUrl', reason: 'target-url-not-honored' },
6821
+ },
6822
+ });
6823
+ }
6327
6824
  // Resolve testIds: fetch all tests in the project, apply --filter.
6328
6825
  let testIds;
6329
6826
  if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
@@ -6368,9 +6865,12 @@ export async function runTestRunAll(opts, deps = {}) {
6368
6865
  const batchResp = await client.triggerBatchRunFresh({
6369
6866
  projectId,
6370
6867
  ...(testIds !== undefined ? { testIds } : {}),
6371
- source: 'cli',
6372
- ...(environment !== undefined ? { environment } : {}),
6868
+ ...dispatchFields,
6373
6869
  }, { idempotencyKey });
6870
+ // Shared across every dispatch this invocation makes — see the `reported` param.
6871
+ const optOutReported = new Set();
6872
+ warnIfOptOutIgnored(opts.autoHeal, batchResp.autoHeal, stderrFn, 'these runs', optOutReported);
6873
+ await assertBatchTargetEcho(batchResp, []);
6374
6874
  // Project-level "watch it here" link. A V3 backend sends it (string, or
6375
6875
  // `null` when no single page exists — e.g. a `--all` that fanned out over
6376
6876
  // several sibling projects); an older backend / the V2 engine omits the key,
@@ -6395,7 +6895,7 @@ export async function runTestRunAll(opts, deps = {}) {
6395
6895
  if (conflicts.length > 0) {
6396
6896
  // Reason-aware advisory: a view-only / un-runnable / not-found case is not
6397
6897
  // "already in flight" — summarizeConflicts names the actual causes.
6398
- stderrFn(`[advisory] ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} not dispatched (${summarizeConflicts(conflicts)}), skipped: ${conflicts.map(c => c.testId).join(' ')}`);
6898
+ stderrFn(`[advisory] ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} not dispatched (${summarizeConflicts(conflicts)}), skipped: ${conflicts.map(c => c.testId).join(' ')}${accepted.length > 0 ? billingConflictLink(conflicts, batchApiUrl) : ''}`);
6399
6899
  }
6400
6900
  if (deferred.length > 0) {
6401
6901
  stderrFn(`Rate-deferred testIds (retry later): ${deferred.map(d => d.testId).join(' ')}`);
@@ -6404,6 +6904,13 @@ export async function runTestRunAll(opts, deps = {}) {
6404
6904
  `${skippedFrontend.length > 0 ? ` (${skippedFrontend.length} FE skipped)` : ''}` +
6405
6905
  `${conflicts.length > 0 ? ` (${conflicts.length} conflict${conflicts.length !== 1 ? 's' : ''})` : ''}` +
6406
6906
  `${deferred.length > 0 ? ` (${deferred.length} rate-deferred)` : ''}.`);
6907
+ if (opts.targetUrl !== undefined) {
6908
+ // Say what the override did and did NOT cover. A backend test's base URL is
6909
+ // baked into its generated code, so it runs against its own target no
6910
+ // matter what — stating it here beats a caller inferring from a verdict.
6911
+ stderrFn(`[advisory] --target-url applies to frontend tests in this batch (${opts.targetUrl}); ` +
6912
+ `backend tests run against the URL baked into their generated code.`);
6913
+ }
6407
6914
  if (!opts.wait) {
6408
6915
  const printResp = {
6409
6916
  accepted: accepted.map(withBatchDashboardUrl),
@@ -6449,13 +6956,25 @@ export async function runTestRunAll(opts, deps = {}) {
6449
6956
  if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
6450
6957
  throw insufficientCreditsConflictError(conflicts, batchApiUrl);
6451
6958
  }
6959
+ if (isPausedRefusal({ accepted, deferred, conflicts })) {
6960
+ throw pausedConflictError(conflicts, batchApiUrl);
6961
+ }
6452
6962
  // Nothing queued and everything was an in-flight conflict → surface CONFLICT (exit 6).
6453
6963
  if (accepted.length === 0 && conflicts.length > 0) {
6454
6964
  throw ApiError.fromEnvelope({
6455
6965
  error: {
6456
6966
  code: 'CONFLICT',
6457
- message: `Batch run: nothing was queued — ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight.`,
6458
- nextAction: `Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>`,
6967
+ // Pure in-flight (the common case, no other reason present) keeps
6968
+ // the exact original wording; any other reason mixed in (billing or
6969
+ // not) uses the reason-aware summary instead of a blanket "in flight".
6970
+ message: `Batch run: nothing was queued — ${allConflictsInFlight(conflicts)
6971
+ ? `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight`
6972
+ : summarizeConflicts(conflicts)}.`,
6973
+ // The billing link is APPENDED to the standard wait hint, never
6974
+ // replacing it — accepted.length is 0 in this whole branch, so the
6975
+ // advisory printed earlier (guarded on accepted.length > 0) never
6976
+ // showed the link, and this is the only place it can.
6977
+ nextAction: `Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>${billingConflictLink(conflicts, batchApiUrl)}`,
6459
6978
  requestId: 'local',
6460
6979
  details: { conflicts: conflicts.map(c => c.testId) },
6461
6980
  },
@@ -6537,20 +7056,35 @@ export async function runTestRunAll(opts, deps = {}) {
6537
7056
  retryResp = await client.triggerBatchRunFresh({
6538
7057
  projectId,
6539
7058
  testIds: retryIds,
6540
- source: 'cli',
7059
+ ...dispatchFields,
6541
7060
  }, { idempotencyKey: retryKey });
6542
7061
  }
6543
7062
  catch (err) {
7063
+ if (err instanceof InterruptError)
7064
+ throw err;
7065
+ if (err instanceof ApiError &&
7066
+ (err.code === 'UNSUPPORTED' || err.code === 'PRECONDITION_FAILED'))
7067
+ throw err;
6544
7068
  // If the retry itself errors, surface it and stop retrying.
6545
7069
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
6546
7070
  break;
6547
7071
  }
7072
+ await assertBatchTargetEcho(retryResp, accepted);
7073
+ // The retry re-sent the opt-out (see the dispatch above), so its echo has to
7074
+ // be read as well; otherwise the tests a rate limit pushed into this leg are
7075
+ // the only ones that run unwarned.
7076
+ warnIfOptOutIgnored(opts.autoHeal, retryResp.autoHeal, stderrFn, 'the retried runs', optOutReported);
6548
7077
  const newlyAccepted = retryResp.accepted;
6549
7078
  const newlyDeferred = retryResp.deferred;
6550
7079
  const newlyConflicted = retryResp.conflicts;
6551
7080
  if (newlyAccepted.length > 0) {
6552
7081
  stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyAccepted.length} test${newlyAccepted.length !== 1 ? 's' : ''} now accepted.`);
6553
- accepted = accepted.concat(newlyAccepted);
7082
+ // A retry asks only for the still-deferred ids but can come back with
7083
+ // tests the first dispatch already ran. Keeping both would poll the
7084
+ // same test twice and overstate `summary.total`.
7085
+ const { deduped, dropped } = dedupeBatchRunFreshAccepted(accepted.concat(newlyAccepted));
7086
+ accepted = deduped;
7087
+ warnDroppedDuplicateRuns(accepted, dropped, stderrFn);
6554
7088
  }
6555
7089
  if (newlyConflicted.length > 0) {
6556
7090
  // [P1] Merge retry-returned conflicts into the running conflicts collection
@@ -6600,7 +7134,9 @@ export async function runTestRunAll(opts, deps = {}) {
6600
7134
  notBefore = inFlight.createdAt;
6601
7135
  startedBy = inFlight.source || inFlight.createdFrom || undefined;
6602
7136
  }
6603
- catch {
7137
+ catch (err) {
7138
+ if (err instanceof InterruptError)
7139
+ throw err;
6604
7140
  // keep the conservative now() floor (fetch failed or the signal aborted)
6605
7141
  }
6606
7142
  stderrFn(`[auto-resume] ${c.testId} — polling in-flight run ${inFlightRunId}${startedBy ? ` (started by ${startedBy})` : ''} to a verdict instead of failing`);
@@ -6611,7 +7147,14 @@ export async function runTestRunAll(opts, deps = {}) {
6611
7147
  // slot-claim failures to conflicts[]); the resumed entries reuse the existing
6612
7148
  // run's id with a real createdAt floor. Polling all of them is the only way
6613
7149
  // `--wait` reports a faithful (not false-green) verdict.
6614
- const pollable = [...accepted, ...resumableEntries];
7150
+ // A case can reach both buckets in one invocation (a retried id the server
7151
+ // refuses comes back as a resumable conflict), so the merge is deduped too —
7152
+ // otherwise the surviving run is polled twice and `summary.total` overstates.
7153
+ const { deduped: pollable, dropped: droppedFromMerge } = dedupeBatchRunFreshAccepted([
7154
+ ...accepted,
7155
+ ...resumableEntries,
7156
+ ]);
7157
+ warnDroppedDuplicateRuns(pollable, droppedFromMerge, stderrFn);
6615
7158
  if (pollable.length === 0) {
6616
7159
  // Build final response with potentially-updated accepted/deferred from D3 retry loop.
6617
7160
  const finalResp = {
@@ -6633,7 +7176,9 @@ export async function runTestRunAll(opts, deps = {}) {
6633
7176
  // Emit the deferred/conflict summary + annotations first so CI shows them (the
6634
7177
  // pure zero-dispatch fall-through emits its OWN skipped-rows summary below).
6635
7178
  if (deferred.length > 0 || conflicts.length > 0) {
6636
- emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(finalResp)), opts, {
7179
+ const summary = summarizeAcceptedPayload(JSON.stringify(finalResp));
7180
+ await writeBatchJUnitReportIfRequested(opts, skippedJUnitResultsFromSummary(summary));
7181
+ emitCiArtifacts(summary, opts, {
6637
7182
  env: deps.env ?? process.env,
6638
7183
  stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
6639
7184
  stderr: stderrFn,
@@ -6647,12 +7192,17 @@ export async function runTestRunAll(opts, deps = {}) {
6647
7192
  if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
6648
7193
  throw insufficientCreditsConflictError(conflicts, batchApiUrl);
6649
7194
  }
7195
+ if (isPausedRefusal({ accepted, deferred, conflicts })) {
7196
+ throw pausedConflictError(conflicts, batchApiUrl);
7197
+ }
6650
7198
  if (conflicts.length > 0) {
6651
7199
  throw ApiError.fromEnvelope({
6652
7200
  error: {
6653
7201
  code: 'CONFLICT',
6654
- message: `Batch run: nothing was queued — ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight.`,
6655
- nextAction: `Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>`,
7202
+ message: `Batch run: nothing was queued — ${allConflictsInFlight(conflicts)
7203
+ ? `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight`
7204
+ : summarizeConflicts(conflicts)}.`,
7205
+ nextAction: `Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>${billingConflictLink(conflicts, batchApiUrl)}`,
6656
7206
  requestId: 'local',
6657
7207
  details: { conflicts: conflicts.map(c => c.testId) },
6658
7208
  },
@@ -6721,6 +7271,8 @@ export async function runTestRunAll(opts, deps = {}) {
6721
7271
  };
6722
7272
  }
6723
7273
  catch (err) {
7274
+ if (err instanceof InterruptError)
7275
+ throw err;
6724
7276
  if (err instanceof TimeoutError)
6725
7277
  deps.onWaitTimeout?.({ reason: 'wait_timeout' });
6726
7278
  // fall through to the timeout result below
@@ -6784,7 +7336,7 @@ export async function runTestRunAll(opts, deps = {}) {
6784
7336
  }
6785
7337
  // Interrupt must reject the fan-out (the collect point below prints the
6786
7338
  // partial for every dispatched run), never flatten into a per-member
6787
- // outcome that would swallow the 128+signum exit (DEV-331).
7339
+ // outcome that would swallow the 128+signum exit.
6788
7340
  if (err instanceof InterruptError)
6789
7341
  throw err;
6790
7342
  if (err instanceof RequestTimeoutError) {
@@ -6811,7 +7363,7 @@ export async function runTestRunAll(opts, deps = {}) {
6811
7363
  testId: entry.testId,
6812
7364
  runId,
6813
7365
  status: 'error',
6814
- error: { code: err.code, message: err.message, exitCode: err.exitCode },
7366
+ error: waitMemberError(err),
6815
7367
  };
6816
7368
  }
6817
7369
  throw err;
@@ -6843,7 +7395,7 @@ export async function runTestRunAll(opts, deps = {}) {
6843
7395
  });
6844
7396
  }
6845
7397
  catch (fanOutErr) {
6846
- // Graceful detach (DEV-331): stdout stays parseable — settled members
7398
+ // Graceful detach: stdout stays parseable — settled members
6847
7399
  // keep their real status, unfinished ones are marked running — and the
6848
7400
  // honest stderr line names every runId still executing (and billing).
6849
7401
  if (fanOutErr instanceof InterruptError) {
@@ -6852,8 +7404,10 @@ export async function runTestRunAll(opts, deps = {}) {
6852
7404
  const partialResults = pollable.map((e) => settled.get(e.runId) ?? { testId: e.testId, runId: e.runId, status: 'running' });
6853
7405
  out.print({ accepted: partialResults, conflicts, deferred, skippedFrontend, skippedIntegration }, () => partialResults.map(r => `${r.runId} ${r.status}`).join('\n'));
6854
7406
  const unfinished = pollable.filter(e => !settled.has(e.runId)).map(e => e.runId);
6855
- if (unfinished.length > 0)
7407
+ if (unfinished.length > 0) {
7408
+ fanOutErr.runWaitContext = true;
6856
7409
  stderrFn(interruptDetachMessage(fanOutErr, unfinished));
7410
+ }
6857
7411
  }
6858
7412
  throw fanOutErr;
6859
7413
  }
@@ -6883,7 +7437,8 @@ export async function runTestRunAll(opts, deps = {}) {
6883
7437
  const freshNameMap = opts.report === 'junit' && opts.reportFile !== undefined
6884
7438
  ? await buildTestNameMap(client, opts.projectId)
6885
7439
  : undefined;
6886
- await writeBatchJUnitReportIfRequested(opts, freshRunResults, freshNameMap);
7440
+ const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
7441
+ await writeBatchJUnitReportIfRequested(opts, [...freshRunResults, ...skippedJUnitResultsFromSummary(ciSummary)], freshNameMap);
6887
7442
  out.print(jsonPayload);
6888
7443
  recordBatchOutcome({
6889
7444
  accepted: accepted.length,
@@ -6896,7 +7451,7 @@ export async function runTestRunAll(opts, deps = {}) {
6896
7451
  // the artifacts land even when the batch exits non-zero. The summary file is a
6897
7452
  // machine artifact written regardless of --output mode; stdout stays owned by
6898
7453
  // the envelope above (plus Actions workflow commands, which Actions parses).
6899
- emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(jsonPayload)), opts, {
7454
+ emitCiArtifacts(ciSummary, opts, {
6900
7455
  env: deps.env ?? process.env,
6901
7456
  stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
6902
7457
  stderr: stderrFn,
@@ -6920,6 +7475,9 @@ export async function runTestRunAll(opts, deps = {}) {
6920
7475
  if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
6921
7476
  throw insufficientCreditsConflictError(conflicts, batchApiUrl);
6922
7477
  }
7478
+ if (isPausedRefusal({ accepted, deferred, conflicts })) {
7479
+ throw pausedConflictError(conflicts, batchApiUrl);
7480
+ }
6923
7481
  // Hard conflicts (a run already in flight for the test that we could NOT
6924
7482
  // auto-resume — no `currentRunId` to poll) mean those tests never ran. In a
6925
7483
  // MIXED batch, the accepted/resumed runs above already made `pollable`
@@ -6930,11 +7488,22 @@ export async function runTestRunAll(opts, deps = {}) {
6930
7488
  // all-conflict path returns. `conflicts` here holds only the hard ones —
6931
7489
  // resumable conflicts were split into the poll set above.
6932
7490
  if (conflicts.length > 0) {
7491
+ // Pure unresumed in-flight keeps the original "already in flight and could
7492
+ // not be resumed" wording; a paused-workspace refusal mixed in here isn't
7493
+ // something that "could not be resumed" — it was never resumable to begin with.
7494
+ const ids = conflicts.map(c => c.testId).join(' ');
7495
+ // This is the one CONFLICT throw where `accepted` can be non-empty (a
7496
+ // mixed batch with some runs dispatched/resumed) — the advisory printed
7497
+ // earlier already showed the link in that case (guarded the same way), so
7498
+ // only add it here when it didn't: nothing else dispatched.
7499
+ const link = accepted.length === 0 ? billingConflictLink(conflicts, batchApiUrl) : '';
6933
7500
  throw ApiError.fromEnvelope({
6934
7501
  error: {
6935
7502
  code: 'CONFLICT',
6936
- message: `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight and could not be resumed — not run.`,
6937
- nextAction: `Wait for the in-flight run(s) to finish, then retry: ${conflicts.map(c => c.testId).join(' ')}`,
7503
+ message: allConflictsInFlight(conflicts)
7504
+ ? `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight and could not be resumed — not run.`
7505
+ : `${summarizeConflicts(conflicts)} — not run.`,
7506
+ nextAction: `Wait for the in-flight run(s) to finish, then retry: ${ids}${link}`,
6938
7507
  requestId: 'local',
6939
7508
  details: { conflicts: conflicts.map(c => c.testId) },
6940
7509
  },
@@ -6947,6 +7516,614 @@ export async function runTestRunAll(opts, deps = {}) {
6947
7516
  // fan-out is for exit-code logic only and is not part of the returned type.
6948
7517
  return { ...batchResp, accepted, deferred, conflicts };
6949
7518
  }
7519
+ /** One bounded trigger-and-wait pool shares one local tunnel for its full lifetime. */
7520
+ export async function runTestRunLocalBatch(opts, deps = {}) {
7521
+ assertIdempotencyKey(opts.idempotencyKey);
7522
+ const environment = normalizeEnvironmentName(opts.environment);
7523
+ if (!Number.isInteger(opts.maxConcurrency) ||
7524
+ opts.maxConcurrency < 1 ||
7525
+ opts.maxConcurrency > 10) {
7526
+ throw localValidationError('max-concurrency', 'with --local, --max-concurrency must be between 1 and 10 (every run shares this machine and its one tunnel; the default is 5)');
7527
+ }
7528
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
7529
+ const out = makeOutput(opts.output, deps);
7530
+ const targetUrl = buildLocalTargetUrl(opts.localHost, opts.localPort);
7531
+ const projectId = opts.all ? resolveProjectId(opts.projectId, deps) : opts.projectId;
7532
+ if (opts.all)
7533
+ requireProjectId(projectId);
7534
+ if (opts.dryRun) {
7535
+ emitDryRunBanner(stderrFn);
7536
+ const runs = (opts.all ? ['<each frontend test in the project>'] : opts.testIds).map(testId => ({
7537
+ method: 'POST',
7538
+ path: `/api/cli/v1/tests/${testId}/runs`,
7539
+ body: {
7540
+ source: 'cli',
7541
+ targetUrl,
7542
+ tunnelClientId: opts.tunnelClientId ?? '<minted at run time>',
7543
+ ...(opts.autoHeal === false ? { autoHeal: false } : {}),
7544
+ ...(environment !== undefined ? { environment } : {}),
7545
+ },
7546
+ }));
7547
+ out.print({
7548
+ dryRun: true,
7549
+ ...(opts.tunnelClientId === undefined ? { precededBy: 'POST /api/cli/v1/tunnel' } : {}),
7550
+ runs,
7551
+ maxConcurrency: opts.maxConcurrency,
7552
+ ...(opts.tunnelClientId === undefined
7553
+ ? { followedBy: 'DELETE /api/cli/v1/tunnel/<client-id>' }
7554
+ : {}),
7555
+ });
7556
+ return;
7557
+ }
7558
+ const clientOpts = {
7559
+ ...opts,
7560
+ requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }),
7561
+ };
7562
+ const client = makeClient(clientOpts, deps);
7563
+ const tunnelRequestTimeoutMs = resolveRequestTimeoutMs(clientOpts, deps.env ?? process.env);
7564
+ const probeLocalPort = async () => {
7565
+ await assertLocalPortListening(opts.localHost, opts.localPort, { skipPreflight: opts.skipPreflight }, stderrFn);
7566
+ if (isProxyAgentActive())
7567
+ stderrFn('[advisory] An HTTP proxy is configured for this process. The tunnel control channel ' +
7568
+ `honours it, but ${TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION} — if the ` +
7569
+ 'run cannot reach your machine, an egress proxy is the first thing to rule out.');
7570
+ };
7571
+ // The local port is probed before anything leaves this machine — before the
7572
+ // project's test list is even read — so a dead dev server costs nothing.
7573
+ // `--all --allow-empty` is the exception: it explicitly accepts a project
7574
+ // with nothing to run, and that answer must not depend on a server this
7575
+ // invocation may never use, so its probe waits until there is a test to run.
7576
+ const probeAfterListing = opts.all && opts.allowEmpty;
7577
+ if (!probeAfterListing)
7578
+ await probeLocalPort();
7579
+ const skipped = [];
7580
+ let tests = opts.testIds.map(id => ({ id }));
7581
+ const knownTests = new Map();
7582
+ if (opts.all) {
7583
+ const page = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
7584
+ query: { projectId, pageSize, cursor },
7585
+ }), {});
7586
+ const needle = opts.nameFilter?.toLowerCase();
7587
+ const filtered = needle
7588
+ ? page.items.filter(t => t.name.toLowerCase().includes(needle))
7589
+ : page.items;
7590
+ const omitted = page.items.length - filtered.length;
7591
+ if (omitted > 0)
7592
+ stderrFn(`--filter: skipped ${omitted} test${omitted !== 1 ? 's' : ''} whose name does not contain "${opts.nameFilter}".`);
7593
+ skipped.push(...filtered
7594
+ .filter(t => t.type !== 'frontend')
7595
+ .map(t => ({ testId: t.id, reason: 'backend-test' })));
7596
+ if (skipped.length > 0)
7597
+ stderrFn(`[advisory] ${skipped.length} backend test(s) skipped — --local runs frontend tests only.`);
7598
+ tests = filtered
7599
+ .filter(t => t.type === 'frontend')
7600
+ .map(t => {
7601
+ knownTests.set(t.id, { type: t.type, projectId: t.projectId ?? projectId });
7602
+ return { id: t.id, name: t.name };
7603
+ });
7604
+ }
7605
+ const results = tests.map(t => ({
7606
+ testId: t.id,
7607
+ ...(t.name !== undefined ? { testTitle: t.name } : {}),
7608
+ status: 'not-run',
7609
+ }));
7610
+ // Seconds from each run's trigger to the moment this process saw it settle.
7611
+ // The table falls back to it because a V3 run card may carry no server
7612
+ // start/finish timestamps; it stays out of the JSON, which only reports what
7613
+ // the server said.
7614
+ const clientSeconds = new WeakMap();
7615
+ const batchSummary = () => {
7616
+ const passed = results.filter(r => r.status === 'passed').length;
7617
+ const timedOut = results.filter(r => r.status === 'timeout').length;
7618
+ const notRun = results.filter(r => r.status === 'not-run').length;
7619
+ return {
7620
+ total: results.length,
7621
+ passed,
7622
+ failed: results.length - passed - timedOut - notRun,
7623
+ timedOut,
7624
+ notRun,
7625
+ };
7626
+ };
7627
+ const ciSummary = () => {
7628
+ const runs = results.map(r => ({
7629
+ testId: r.testId,
7630
+ ...(r.testTitle ? { title: r.testTitle } : {}),
7631
+ ...(r.runId ? { runId: r.runId } : {}),
7632
+ status: r.runId === undefined ? 'skipped' : r.status,
7633
+ ...(r.dashboardUrl ? { dashboardUrl: r.dashboardUrl } : {}),
7634
+ ...(r.executionUrl ? { executionUrl: r.executionUrl } : {}),
7635
+ ...(r.error ? { error: r.error.message } : {}),
7636
+ }));
7637
+ runs.push(...skipped.map(s => ({ testId: s.testId, status: 'skipped', error: s.reason })));
7638
+ return {
7639
+ total: runs.length,
7640
+ passed: runs.filter(r => r.status === 'passed').length,
7641
+ failed: runs.filter(r => !['passed', 'timeout', 'skipped'].includes(r.status)).length,
7642
+ skipped: runs.filter(r => r.status === 'skipped').length,
7643
+ timedOut: runs.filter(r => r.status === 'timeout').length,
7644
+ runs,
7645
+ };
7646
+ };
7647
+ const emitArtifacts = async () => {
7648
+ const summary = ciSummary();
7649
+ emitCiArtifacts(summary, opts, {
7650
+ env: deps.env ?? process.env,
7651
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
7652
+ stderr: stderrFn,
7653
+ }, 'run');
7654
+ await writeBatchJUnitReportIfRequested(opts, [
7655
+ ...results.map(r => ({ ...r, status: r.runId === undefined ? 'skipped' : r.status })),
7656
+ ...skipped.map(s => ({ testId: s.testId, status: 'skipped' })),
7657
+ ]);
7658
+ };
7659
+ const printResults = (session) => {
7660
+ const summary = batchSummary();
7661
+ const payload = {
7662
+ ...(session ? { tunnel: { clientId: session.clientId, adopted: session.adopted } } : {}),
7663
+ maxConcurrency: opts.maxConcurrency,
7664
+ results,
7665
+ skipped,
7666
+ summary,
7667
+ };
7668
+ out.print(payload, () => [
7669
+ renderTextTable(results, [
7670
+ {
7671
+ header: 'TEST ID',
7672
+ width: rows => Math.max(7, ...rows.map(r => r.testId.length)),
7673
+ render: r => r.testId,
7674
+ },
7675
+ {
7676
+ header: 'RUN ID',
7677
+ width: rows => Math.max(6, ...rows.map(r => (r.runId ?? '-').length)),
7678
+ render: r => r.runId ?? '-',
7679
+ },
7680
+ { header: 'STATUS', width: 9, render: r => r.status },
7681
+ {
7682
+ header: 'DURATION',
7683
+ width: 10,
7684
+ render: r => {
7685
+ const seconds = durationSecondsBetween(r.startedAt, r.finishedAt) ?? clientSeconds.get(r);
7686
+ return seconds === undefined ? '-' : `${seconds}s`;
7687
+ },
7688
+ },
7689
+ ]),
7690
+ ].join('\n'));
7691
+ stderrFn(`Batch run complete: ${summary.passed}/${summary.total} passed, ${summary.failed} failed/blocked, ${summary.timedOut} timed out${summary.notRun ? `, ${summary.notRun} not run` : ''}`);
7692
+ for (const r of results
7693
+ .filter(r => ['failed', 'blocked'].includes(r.status) && r.runId)
7694
+ .slice(0, 10)) {
7695
+ stderrFn(`testsprite test artifact get ${r.runId}`);
7696
+ }
7697
+ if (results.filter(r => ['failed', 'blocked'].includes(r.status) && r.runId).length > 10)
7698
+ stderrFn('…');
7699
+ };
7700
+ if (results.length === 0) {
7701
+ printResults();
7702
+ await finishZeroDispatchBatch({
7703
+ reason: opts.nameFilter
7704
+ ? `--filter "${opts.nameFilter}" matched no frontend tests in project ${projectId}`
7705
+ : 'no runnable frontend tests in the project',
7706
+ skipped: skipped.map(s => s.testId),
7707
+ allowEmpty: opts.allowEmpty,
7708
+ opts,
7709
+ deps,
7710
+ stderrFn,
7711
+ });
7712
+ return;
7713
+ }
7714
+ if (probeAfterListing)
7715
+ await probeLocalPort();
7716
+ for (const test of tests) {
7717
+ await preflightLocalRunTest({
7718
+ client,
7719
+ testId: test.id,
7720
+ environment,
7721
+ localPort: opts.localPort,
7722
+ opts,
7723
+ deps,
7724
+ knownTest: knownTests.get(test.id),
7725
+ });
7726
+ }
7727
+ const shutdown = shutdownOf(deps);
7728
+ const disarm = shutdown.arm();
7729
+ const poolAbort = new AbortController();
7730
+ const pollShutdown = {
7731
+ signal: AbortSignal.any([shutdown.signal, poolAbort.signal]),
7732
+ arm: () => shutdown.arm(),
7733
+ runCriticalOperation: operation => shutdown.runCriticalOperation(operation),
7734
+ };
7735
+ let session;
7736
+ let abortReason;
7737
+ let lostReason;
7738
+ let nextIndex = 0;
7739
+ // Runs the server accepted and this process has not seen settle — the number
7740
+ // the tunnel is actually carrying, which is what the peak telemetry reports.
7741
+ let activeRuns = 0;
7742
+ let peakInFlight = 0;
7743
+ const activeRows = new Set();
7744
+ // Accepted runs this process has not seen reach a verdict (and has not
7745
+ // already settled by cancelling). Whatever their row says — `running`, or
7746
+ // `error` after a failed poll — they are still owned by this tunnel, so an
7747
+ // abort cancels every one of them before the tunnel goes.
7748
+ const unsettled = new Set();
7749
+ // Trigger requests are uninterruptible (the server may already have charged
7750
+ // the run), so an abort waits for them before cancelling and closing.
7751
+ const pendingTriggers = new Set();
7752
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
7753
+ const setAbort = (reason, lost) => {
7754
+ if (abortReason === undefined) {
7755
+ abortReason = reason;
7756
+ lostReason = lost;
7757
+ poolAbort.abort(reason);
7758
+ }
7759
+ };
7760
+ try {
7761
+ try {
7762
+ session = await openTunnelSession({
7763
+ log: stderrFn,
7764
+ logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
7765
+ onMinted: minted => stderrFn(`[tunnel] Minted tunnel client ${minted.clientId}; connecting…`),
7766
+ ...(opts.tunnelClientId
7767
+ ? { adopt: { clientId: opts.tunnelClientId, expiresAt: '' } }
7768
+ : {}),
7769
+ }, {
7770
+ mint: async (ttlSeconds) => withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, mintClient => mintClient.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
7771
+ destroy: async (clientId) => deleteTunnelForCleanup(opts, deps, clientId),
7772
+ createClient: shutdownAwareTunnelClientFactory(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
7773
+ });
7774
+ }
7775
+ catch (err) {
7776
+ // An interrupt while minting or connecting still owes the caller the
7777
+ // partial result (every test `not-run`); the session helper has already
7778
+ // deleted a minted binding.
7779
+ if (!shutdown.signal.aborted)
7780
+ throw err;
7781
+ setAbort(shutdown.signal.reason);
7782
+ }
7783
+ if (session !== undefined) {
7784
+ stderrFn(`[tunnel] Reaching ${targetUrl} through TestSprite (client ${session.clientId}).`);
7785
+ stderrFn(`Running ${results.length} tests through one tunnel, up to ${opts.maxConcurrency} at a time.`);
7786
+ const liveSession = session;
7787
+ const livenessClient = liveSession.adopted
7788
+ ? makeClient({ ...clientOpts, debug: false, verbose: false }, { ...deps, stderr: () => { } })
7789
+ : undefined;
7790
+ let checkBorrowedLiveness;
7791
+ const idempotencyBase = opts.idempotencyKey ?? `cli-run-${randomUUID()}`;
7792
+ if (opts.idempotencyKey === undefined &&
7793
+ (opts.output === 'json' || opts.verbose || opts.debug))
7794
+ stderrFn(`idempotency-key: ${idempotencyBase}`);
7795
+ const runOne = async (index) => {
7796
+ const row = results[index];
7797
+ let triggerStartedAtMs;
7798
+ const suffix = `:${row.testId}`;
7799
+ const key = opts.idempotencyKey
7800
+ ? `${idempotencyBase.slice(0, Math.max(0, 256 - suffix.length))}${suffix}`.slice(-256)
7801
+ : index === 0
7802
+ ? idempotencyBase
7803
+ : `cli-run-${randomUUID()}`;
7804
+ let response;
7805
+ try {
7806
+ if (shutdown.signal.aborted)
7807
+ throw shutdown.signal.reason;
7808
+ if (abortReason !== undefined)
7809
+ return;
7810
+ const fatalBeforeTrigger = liveSession.fatalReason();
7811
+ if (fatalBeforeTrigger) {
7812
+ setAbort(new TunnelLostError(fatalBeforeTrigger, '', liveSession.fatalMessage()), fatalBeforeTrigger);
7813
+ return;
7814
+ }
7815
+ triggerStartedAtMs = Date.now();
7816
+ const triggering = withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, triggerClient => triggerClient.triggerRunWithMeta(row.testId, {
7817
+ source: 'cli',
7818
+ targetUrl,
7819
+ tunnelClientId: liveSession.clientId,
7820
+ ...(opts.autoHeal === false ? { autoHeal: false } : {}),
7821
+ ...(environment !== undefined ? { environment } : {}),
7822
+ }, { idempotencyKey: key }));
7823
+ pendingTriggers.add(triggering);
7824
+ try {
7825
+ response = (await triggering).body;
7826
+ }
7827
+ finally {
7828
+ pendingTriggers.delete(triggering);
7829
+ }
7830
+ row.runId = response.runId;
7831
+ row.status = 'running';
7832
+ activeRows.add(index);
7833
+ unsettled.add(row);
7834
+ activeRuns++;
7835
+ peakInFlight = Math.max(peakInFlight, activeRuns);
7836
+ stderrFn(`[${index + 1}/${results.length}] ${row.testId} → run ${row.runId}`);
7837
+ if (response.dashboardUrl)
7838
+ stderrFn(`Dashboard: ${response.dashboardUrl}`);
7839
+ }
7840
+ catch (err) {
7841
+ if (err instanceof InterruptError) {
7842
+ setAbort(err);
7843
+ return;
7844
+ }
7845
+ if (err instanceof ApiError) {
7846
+ const reason = err.getDetail('reason', (value) => typeof value === 'string');
7847
+ if (isAuthCode(err.code)) {
7848
+ row.status = 'error';
7849
+ row.error = waitMemberError(err);
7850
+ setAbort(err);
7851
+ return;
7852
+ }
7853
+ if ((err.code === 'PRECONDITION_FAILED' && reason === 'tunnel-offline') ||
7854
+ (err.code === 'VALIDATION_ERROR' && reason === 'tunnel-binding-not-found')) {
7855
+ row.status = 'error';
7856
+ row.error = waitMemberError(err);
7857
+ setAbort(err, reason);
7858
+ return;
7859
+ }
7860
+ row.status = 'error';
7861
+ row.error = waitMemberError(err);
7862
+ }
7863
+ else if (err instanceof RequestTimeoutError) {
7864
+ row.status = 'error';
7865
+ row.error = { code: 'UNSUPPORTED', message: err.message, exitCode: err.exitCode };
7866
+ }
7867
+ else {
7868
+ setAbort(err);
7869
+ return;
7870
+ }
7871
+ stderrFn(`[${index + 1}/${results.length}] ${row.testId} ${row.status} (-)`);
7872
+ return;
7873
+ }
7874
+ try {
7875
+ if (abortReason !== undefined)
7876
+ return;
7877
+ if (liveSession.adopted && checkBorrowedLiveness === undefined) {
7878
+ checkBorrowedLiveness = makeBorrowedTunnelLivenessCheck({
7879
+ client: livenessClient,
7880
+ clientId: liveSession.clientId,
7881
+ runId: row.runId,
7882
+ });
7883
+ }
7884
+ const startMs = triggerStartedAtMs;
7885
+ const remainingSeconds = (startMs + opts.timeoutSeconds * 1000 - Date.now()) / 1000;
7886
+ if (remainingSeconds <= 0)
7887
+ throw new TimeoutError(row.runId, opts.timeoutSeconds);
7888
+ const finalRun = await pollRunUntilTerminal(client, row.runId, {
7889
+ timeoutSeconds: remainingSeconds,
7890
+ sleep: deps.sleep,
7891
+ shutdown: pollShutdown,
7892
+ onTransition: opts.verbose ? msg => stderrFn(`[verbose] ${msg}`) : undefined,
7893
+ onTick: (run, elapsedMs) => {
7894
+ if (abortReason !== undefined)
7895
+ throw abortReason;
7896
+ if (!isTerminalStatus(run.status)) {
7897
+ const fatal = liveSession.fatalReason();
7898
+ if (fatal)
7899
+ throw new TunnelLostError(fatal, row.runId, liveSession.fatalMessage());
7900
+ }
7901
+ ticker.update(formatRunProgressLine(run, elapsedMs, `(${row.testId})`));
7902
+ },
7903
+ ...(checkBorrowedLiveness
7904
+ ? {
7905
+ resolveAlternate: async (_run, _elapsed, signal) => {
7906
+ await checkBorrowedLiveness(signal);
7907
+ return null;
7908
+ },
7909
+ }
7910
+ : {}),
7911
+ });
7912
+ row.status = finalRun.status;
7913
+ unsettled.delete(row);
7914
+ row.testTitle = finalRun.testTitle ?? row.testTitle;
7915
+ row.projectId = finalRun.projectId;
7916
+ row.startedAt = finalRun.startedAt;
7917
+ row.finishedAt = finalRun.finishedAt;
7918
+ if (typeof finalRun.dashboardUrl === 'string')
7919
+ row.dashboardUrl = finalRun.dashboardUrl;
7920
+ if (typeof finalRun.executionUrl === 'string')
7921
+ row.executionUrl = finalRun.executionUrl;
7922
+ clientSeconds.set(row, Math.round((Date.now() - startMs) / 1000));
7923
+ stderrFn(`[${index + 1}/${results.length}] ${row.testId} ${row.status} (${clientSeconds.get(row)}s)`);
7924
+ }
7925
+ catch (err) {
7926
+ if (abortReason !== undefined)
7927
+ return;
7928
+ if (err instanceof InterruptError) {
7929
+ setAbort(err);
7930
+ return;
7931
+ }
7932
+ if (err instanceof TunnelLostError) {
7933
+ setAbort(err, err.getDetail('reason', (v) => typeof v === 'string') ??
7934
+ 'tunnel-lost');
7935
+ return;
7936
+ }
7937
+ if (err instanceof TimeoutError || err instanceof RequestTimeoutError) {
7938
+ row.status = 'timeout';
7939
+ row.error = { code: 'UNSUPPORTED', message: err.message, exitCode: 7 };
7940
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
7941
+ }
7942
+ else if (err instanceof ApiError && isAuthCode(err.code)) {
7943
+ // The credential stopped working: every further trigger would fail
7944
+ // the same way, so stop dispatching rather than bill more runs.
7945
+ row.status = 'error';
7946
+ row.error = waitMemberError(err);
7947
+ setAbort(err);
7948
+ return;
7949
+ }
7950
+ else if (err instanceof ApiError) {
7951
+ row.status = 'error';
7952
+ row.error = waitMemberError(err);
7953
+ }
7954
+ else {
7955
+ setAbort(err);
7956
+ return;
7957
+ }
7958
+ // An owned run cannot finish once this process closes its tunnel, so a
7959
+ // run the batch stops waiting for is cancelled — unless the caller
7960
+ // opted out, exactly as the single-run path honours it.
7961
+ if (!liveSession.adopted) {
7962
+ const cancel = await cancelDoomedTunnelRun({
7963
+ runId: row.runId,
7964
+ enabled: opts.cancelOnInterrupt,
7965
+ opts,
7966
+ deps,
7967
+ });
7968
+ row.cancel = cancel.outcome;
7969
+ }
7970
+ unsettled.delete(row);
7971
+ stderrFn(`[${index + 1}/${results.length}] ${row.testId} ${row.status} (-)`);
7972
+ }
7973
+ };
7974
+ const worker = async () => {
7975
+ while (abortReason === undefined &&
7976
+ !shutdown.signal.aborted &&
7977
+ nextIndex < results.length) {
7978
+ const index = nextIndex++;
7979
+ try {
7980
+ await runOne(index);
7981
+ }
7982
+ finally {
7983
+ if (activeRows.delete(index))
7984
+ activeRuns--;
7985
+ }
7986
+ }
7987
+ if (shutdown.signal.aborted)
7988
+ setAbort(shutdown.signal.reason);
7989
+ };
7990
+ const workers = Promise.allSettled(Array.from({ length: Math.min(opts.maxConcurrency, results.length) }, () => worker()));
7991
+ await Promise.race([
7992
+ workers,
7993
+ new Promise(resolve => {
7994
+ if (abortReason !== undefined) {
7995
+ resolve();
7996
+ return;
7997
+ }
7998
+ const timer = setInterval(() => {
7999
+ if (abortReason !== undefined || shutdown.signal.aborted) {
8000
+ clearInterval(timer);
8001
+ resolve();
8002
+ }
8003
+ }, 25);
8004
+ timer.unref?.();
8005
+ void workers.then(() => {
8006
+ clearInterval(timer);
8007
+ resolve();
8008
+ });
8009
+ }),
8010
+ ]);
8011
+ if (abortReason !== undefined || shutdown.signal.aborted) {
8012
+ if (abortReason === undefined)
8013
+ setAbort(shutdown.signal.reason);
8014
+ await Promise.allSettled([...pendingTriggers]);
8015
+ let settleTimer;
8016
+ try {
8017
+ await Promise.race([
8018
+ workers,
8019
+ new Promise(resolve => {
8020
+ settleTimer = setTimeout(resolve, 10_000);
8021
+ }),
8022
+ ]);
8023
+ }
8024
+ finally {
8025
+ if (settleTimer !== undefined)
8026
+ clearTimeout(settleTimer);
8027
+ }
8028
+ await Promise.all([...unsettled].map(async (r) => {
8029
+ if (liveSession.adopted && lostReason === undefined) {
8030
+ r.cancel = 'skipped';
8031
+ return;
8032
+ }
8033
+ const cancel = await cancelDoomedTunnelRun({
8034
+ runId: r.runId,
8035
+ enabled: opts.cancelOnInterrupt,
8036
+ opts,
8037
+ deps,
8038
+ });
8039
+ r.cancel = cancel.outcome;
8040
+ // An `error` row keeps the error that stopped the batch; only a
8041
+ // row still reading `running` takes the cancellation's verdict.
8042
+ if (r.status !== 'running')
8043
+ return;
8044
+ if (cancel.outcome === 'cancelled')
8045
+ r.status = 'cancelled';
8046
+ else if (cancel.outcome === 'already-terminal' && cancel.terminalStatus)
8047
+ r.status = cancel.terminalStatus;
8048
+ }));
8049
+ }
8050
+ }
8051
+ }
8052
+ finally {
8053
+ ticker.finalize();
8054
+ if (session)
8055
+ await session.close();
8056
+ disarm();
8057
+ }
8058
+ printResults(session);
8059
+ recordBatchOutcome({
8060
+ accepted: results.filter(r => r.runId !== undefined).length,
8061
+ conflicts: [],
8062
+ deferred: 0,
8063
+ skipped: skipped.length + results.filter(r => r.status === 'not-run').length,
8064
+ results: results.filter(r => r.status !== 'not-run'),
8065
+ });
8066
+ recordTelemetryExtras({
8067
+ localConcurrencyLimit: opts.maxConcurrency,
8068
+ localPeakInFlight: peakInFlight,
8069
+ });
8070
+ if (abortReason === undefined) {
8071
+ await emitArtifacts();
8072
+ }
8073
+ else {
8074
+ // Best-effort on an abort: a report that cannot be written (say, JUnit
8075
+ // with no --project and no finished run to infer it from) must not
8076
+ // replace the interrupt or tunnel-loss exit the caller is owed.
8077
+ try {
8078
+ await emitArtifacts();
8079
+ }
8080
+ catch (ciErr) {
8081
+ if (ciErr instanceof InterruptError)
8082
+ throw ciErr;
8083
+ stderrFn(`[run] CI output emission failed; continuing: ${ciErr.message}`);
8084
+ }
8085
+ }
8086
+ if (abortReason !== undefined) {
8087
+ const unfinished = results.filter(r => r.runId && (r.status === 'running' || r.status === 'cancelled'));
8088
+ const waits = results.filter(r => r.runId && r.status === 'running').map(r => r.runId);
8089
+ if (waits.length)
8090
+ stderrFn(`Runs may still finish: testsprite test wait ${waits.join(' ')}`);
8091
+ if (session !== undefined)
8092
+ stderrFn(`Tunnel ${session.clientId}: ${unfinished.filter(r => r.cancel === 'cancelled').length} run(s) cancelled, ${waits.length} still running.`);
8093
+ if (lostReason !== undefined)
8094
+ throw ApiError.fromEnvelope({
8095
+ error: {
8096
+ code: 'UNAVAILABLE',
8097
+ message: `Tunnel client ${session?.clientId} was lost; ${results.filter(r => r.cancel === 'cancelled').length} runs were cancelled.`,
8098
+ nextAction: 'Start a new local batch after checking the local app and tunnel.',
8099
+ requestId: 'local',
8100
+ details: {
8101
+ reason: lostReason,
8102
+ clientId: session?.clientId,
8103
+ cancelledRunIds: results.filter(r => r.cancel === 'cancelled').map(r => r.runId),
8104
+ notRunTestIds: results.filter(r => r.status === 'not-run').map(r => r.testId),
8105
+ },
8106
+ },
8107
+ });
8108
+ if (abortReason instanceof InterruptError) {
8109
+ // The top-level JSON renderer otherwise says the run "keeps executing and
8110
+ // billing", which is false for an owned batch whose runs were cancelled.
8111
+ const cancelled = results.filter(r => r.cancel === 'cancelled').length;
8112
+ const notRun = results.filter(r => r.status === 'not-run').length;
8113
+ abortReason.tunnelDetach = {
8114
+ runId: waits[0] ?? results.find(r => r.runId)?.runId ?? '',
8115
+ cancel: waits.length > 0 ? 'skipped' : cancelled > 0 ? 'cancelled' : 'skipped',
8116
+ nextAction: `${cancelled} in-flight run(s) cancelled, ${waits.length} still running` +
8117
+ (waits.length ? ` (re-attach: testsprite test wait ${waits.join(' ')})` : '') +
8118
+ `, ${notRun} test(s) never started. The per-test results are on stdout.`,
8119
+ };
8120
+ }
8121
+ throw abortReason;
8122
+ }
8123
+ const failure = resolveWaitFailure(results, { timeoutSeconds: opts.timeoutSeconds });
8124
+ if (failure)
8125
+ throw failure;
8126
+ }
6950
8127
  /**
6951
8128
  * `test rerun` — M3.4 piece-3.
6952
8129
  *
@@ -7105,7 +8282,9 @@ export async function runTestRerun(opts, deps = {}) {
7105
8282
  effectiveAutoHeal = false;
7106
8283
  }
7107
8284
  }
7108
- catch {
8285
+ catch (err) {
8286
+ if (err instanceof InterruptError)
8287
+ throw err;
7109
8288
  // Best-effort: don't fail on a lookup error; server will gate anyway.
7110
8289
  }
7111
8290
  }
@@ -7157,11 +8336,18 @@ export async function runTestRerun(opts, deps = {}) {
7157
8336
  // Print auto-heal advisory.
7158
8337
  // CLI path: auto-heal is default-on for FE reruns (--no-auto-heal to opt
7159
8338
  // out). Free and paid CLI callers both get auto-heal; backend no longer
7160
- // tier-gates for source='cli'. The rerun itself is billed at 0.5 credits
7161
- // regardless of whether heal engages (same as a fresh run; legacy V2
7162
- // accounts: a verbatim replay pass is free). A heal engage costs an
7163
- // additional 0.2 credits on top of that, charged only when Phase-2 heal
7164
- // actually runs.
8339
+ // tier-gates for source='cli'.
8340
+ //
8341
+ // What a heal COSTS depends on which engine answers, and the CLI cannot
8342
+ // tell from here (this copy used to state the V2 number unconditionally,
8343
+ // and V3 is now the majority of CLI volume):
8344
+ // - V3: heal is a full agent re-authoring run. It is billed as the run
8345
+ // (0.5 FE / 0.2 BE) and nothing extra — `billing-pricing.ts` has no
8346
+ // auto-heal action at all.
8347
+ // - Legacy V2: a verbatim replay pass is free, and a heal ENGAGE spends
8348
+ // `CREDIT_AUTO_HEAL_FRONTEND` (0.2) on top, only when Phase-2 runs.
8349
+ // So the advisory names the consequence rather than a number, and `usage`
8350
+ // is where an exact figure comes from.
7165
8351
  //
7166
8352
  // Defensive branch: if the server still echoes autoHeal:false after we sent
7167
8353
  // autoHeal:true, the server did not apply it (unexpected; may happen on
@@ -7184,7 +8370,9 @@ export async function runTestRerun(opts, deps = {}) {
7184
8370
  ` If this was unexpected, check your balance with \`testsprite usage\`.`);
7185
8371
  }
7186
8372
  else if (rerunResp.autoHeal) {
7187
- stderrFn(`[advisory] auto-heal on (FE rerun default). If a step has drifted, healing runs and costs 0.2 credit. Disable with --no-auto-heal.`);
8373
+ stderrFn(`[advisory] auto-heal on (FE rerun default). If the saved script has drifted, the agent ` +
8374
+ `re-authors this test and the new code replaces the stored version. Use --no-auto-heal ` +
8375
+ `for a verbatim replay. Costs: \`testsprite usage\`.`);
7188
8376
  }
7189
8377
  // Server advisory: the autoHeal opt-out was forwarded to the execution
7190
8378
  // engine but is not yet enforced there. Present only on a V3-routed
@@ -7267,7 +8455,7 @@ export async function runTestRerun(opts, deps = {}) {
7267
8455
  }
7268
8456
  // Preserve the two intentional whole-fan-out aborts: each has a
7269
8457
  // dedicated outer-catch branch (RequestTimeoutError → all-running
7270
- // partial + re-attach hints + exit 7; InterruptError → DEV-331
8458
+ // partial + re-attach hints + exit 7; InterruptError →
7271
8459
  // graceful detach). Re-throw so the fan-out's `.catch(reject)` fires.
7272
8460
  if (err instanceof RequestTimeoutError || err instanceof InterruptError)
7273
8461
  throw err;
@@ -7404,8 +8592,8 @@ export async function runTestRerun(opts, deps = {}) {
7404
8592
  stderrFn(rateLimitedDetachMessage(fanOutErr, closureMembers.map(m => m.runId)));
7405
8593
  throw fanOutErr;
7406
8594
  }
7407
- // Graceful detach (DEV-331): same partial shape as the timeout path —
7408
- // SIG-6 requires the partial to list ALL dispatched runIds.
8595
+ // Graceful detach: same partial shape as the timeout path — the
8596
+ // partial must list ALL dispatched runIds.
7409
8597
  if (fanOutErr instanceof InterruptError) {
7410
8598
  ticker.finalize(`Closure fan-out — interrupted (${fanOutErr.signal})`);
7411
8599
  const dispatchedRunIds = closureMembers.map(m => ({
@@ -7418,6 +8606,7 @@ export async function runTestRerun(opts, deps = {}) {
7418
8606
  .map(m => `${m.role.padEnd(9)} ${m.testId} (runId: ${m.runId}) — running`)
7419
8607
  .join('\n'));
7420
8608
  stderrFn(interruptDetachMessage(fanOutErr, closureMembers.map(m => m.runId)));
8609
+ fanOutErr.runWaitContext = true;
7421
8610
  throw fanOutErr;
7422
8611
  }
7423
8612
  throw fanOutErr;
@@ -7597,7 +8786,7 @@ export async function runTestRerun(opts, deps = {}) {
7597
8786
  stderrFn(rateLimitedDetachMessage(err, [rerunResp.runId]));
7598
8787
  throw err;
7599
8788
  }
7600
- // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
8789
+ // Graceful detach on SIGINT/SIGTERM — see runTestRun.
7601
8790
  if (err instanceof InterruptError) {
7602
8791
  ticker.finalize(`Run ${rerunResp.runId} — interrupted (${err.signal})`);
7603
8792
  const partial = { runId: rerunResp.runId, status: 'running' };
@@ -7611,6 +8800,7 @@ export async function runTestRerun(opts, deps = {}) {
7611
8800
  ].join('\n');
7612
8801
  });
7613
8802
  stderrFn(interruptDetachMessage(err, [rerunResp.runId]));
8803
+ err.runWaitContext = true;
7614
8804
  throw err;
7615
8805
  }
7616
8806
  ticker.finalize();
@@ -7619,7 +8809,7 @@ export async function runTestRerun(opts, deps = {}) {
7619
8809
  ticker.finalize(formatRunProgressLine(finalRun, Date.now() - replayStartMs, '(replay)'));
7620
8810
  // Probe the test type once (text mode only, best-effort) so a backend
7621
8811
  // rerun's card reads `n/a (backend)` even when the fallback never fired
7622
- // (BE run rows finalize server-side now) — DEV-282.
8812
+ // (BE run rows finalize server-side now).
7623
8813
  const isBackend = await resolveRunCardIsBackend(client, testId, opts.output, beFallbackUsed);
7624
8814
  out.print(withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), data => renderRunResponseText(data, { isBackend }));
7625
8815
  if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
@@ -7776,10 +8966,8 @@ export async function runTestRerun(opts, deps = {}) {
7776
8966
  // polled under --wait, more than once) and `closure.byProject` entries
7777
8967
  // sharing a projectId are merged rather than left as separate per-chunk
7778
8968
  // entries.
7779
- const { deduped: dedupedAccepted, droppedCount: duplicateAcceptedCount } = dedupeBatchRerunAccepted(chunkResponses.flatMap(r => r.accepted));
7780
- if (duplicateAcceptedCount > 0) {
7781
- stderrFn(`[warn] ${duplicateAcceptedCount} test${duplicateAcceptedCount !== 1 ? 's were' : ' was'} triggered more than once across chunked batch-rerun requests (shared BE producer/teardown); kept the first run, ignored the rest.`);
7782
- }
8969
+ const { deduped: dedupedAccepted, dropped: duplicateAccepted } = dedupeBatchRerunAccepted(chunkResponses.flatMap(r => r.accepted));
8970
+ warnDroppedDuplicateRuns(dedupedAccepted, duplicateAccepted, stderrFn);
7783
8971
  const batchResp = {
7784
8972
  accepted: dedupedAccepted,
7785
8973
  deferred: chunkResponses.flatMap(r => r.deferred),
@@ -7818,7 +9006,7 @@ export async function runTestRerun(opts, deps = {}) {
7818
9006
  summaryParts[0] += ` (${addedProducersTotal} BE producer${addedProducersTotal !== 1 ? 's' : ''} auto-added)`;
7819
9007
  }
7820
9008
  if (conflicts.length > 0) {
7821
- summaryParts.push(`${conflicts.length} already in flight, skipped`);
9009
+ summaryParts.push(`${conflicts.length} not dispatched (${summarizeConflicts(conflicts)}), skipped${accepted.length > 0 ? billingConflictLink(conflicts, resolveApiUrl(opts, deps)) : ''}`);
7822
9010
  }
7823
9011
  if (deferred.length > 0) {
7824
9012
  summaryParts.push(`${deferred.length} rate-deferred`);
@@ -7922,10 +9110,12 @@ export async function runTestRerun(opts, deps = {}) {
7922
9110
  }
7923
9111
  }
7924
9112
  catch (err) {
9113
+ if (err instanceof InterruptError)
9114
+ throw err;
7925
9115
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
7926
9116
  break;
7927
9117
  }
7928
- const { deduped: newlyAccepted, droppedCount: newlyDuplicateCount } = dedupeBatchRerunAccepted(retryChunkResponses.flatMap(r => r.accepted));
9118
+ const { deduped: newlyAccepted, dropped: newlyDuplicate } = dedupeBatchRerunAccepted(retryChunkResponses.flatMap(r => r.accepted));
7929
9119
  const newlyDeferred = retryChunkResponses.flatMap(r => r.deferred);
7930
9120
  const newlyConflicted = retryChunkResponses.flatMap(r => r.conflicts);
7931
9121
  // [P2] Collect notFound[] from the retry response. A deferred test may be
@@ -7939,12 +9129,14 @@ export async function runTestRerun(opts, deps = {}) {
7939
9129
  if (newlyAdvisories.length > 0) {
7940
9130
  advisories = dedupeRerunAdvisories(advisories.concat(newlyAdvisories));
7941
9131
  }
7942
- if (newlyDuplicateCount > 0) {
7943
- stderrFn(`[warn] ${newlyDuplicateCount} test${newlyDuplicateCount !== 1 ? 's were' : ' was'} triggered more than once across deferred-retry chunked requests (shared BE producer/teardown); kept the first run, ignored the rest.`);
7944
- }
9132
+ warnDroppedDuplicateRuns(newlyAccepted, newlyDuplicate, stderrFn);
7945
9133
  if (newlyAccepted.length > 0) {
7946
9134
  stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyAccepted.length} test${newlyAccepted.length !== 1 ? 's' : ''} now accepted.`);
7947
- accepted = dedupeBatchRerunAccepted(accepted.concat(newlyAccepted)).deduped;
9135
+ // A retry asks only for the still-deferred ids but can come back with
9136
+ // a test an earlier attempt already ran; the extra run is reported.
9137
+ const { deduped: mergedAccepted, dropped: droppedAcrossAttempts } = dedupeBatchRerunAccepted(accepted.concat(newlyAccepted));
9138
+ accepted = mergedAccepted;
9139
+ warnDroppedDuplicateRuns(accepted, droppedAcrossAttempts, stderrFn);
7948
9140
  }
7949
9141
  if (newlyConflicted.length > 0) {
7950
9142
  // [P1] Merge retry-returned conflicts into the running conflicts collection
@@ -7995,6 +9187,15 @@ export async function runTestRerun(opts, deps = {}) {
7995
9187
  if (deferred.length > 0) {
7996
9188
  throw new CLIError(`Batch rerun incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} were rate-deferred. Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
7997
9189
  }
9190
+ // A paused/credits refusal must exit 13/12, the same envelope the single-run
9191
+ // route and `test run --all` answer with — never the generic CONFLICT
9192
+ // (exit 6) an all-in-flight batch gets.
9193
+ if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
9194
+ throw insufficientCreditsConflictError(conflicts, resolveApiUrl(opts, deps));
9195
+ }
9196
+ if (isPausedRefusal({ accepted, deferred, conflicts })) {
9197
+ throw pausedConflictError(conflicts, resolveApiUrl(opts, deps));
9198
+ }
7998
9199
  // Fix C: all-conflict no-op (no --wait path)
7999
9200
  if (accepted.length === 0 && conflicts.length > 0) {
8000
9201
  // codex P2: don't claim "all in flight" when some ids were also notFound —
@@ -8003,8 +9204,13 @@ export async function runTestRerun(opts, deps = {}) {
8003
9204
  throw ApiError.fromEnvelope({
8004
9205
  error: {
8005
9206
  code: 'CONFLICT',
8006
- message: `Batch rerun: nothing was queued — ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight${notFound.length > 0 ? `, ${notFound.length} not found` : ''}.`,
8007
- nextAction: `Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>`,
9207
+ message: `Batch rerun: nothing was queued — ${allConflictsInFlight(conflicts)
9208
+ ? `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight`
9209
+ : summarizeConflicts(conflicts)}${notFound.length > 0 ? `, ${notFound.length} not found` : ''}.`,
9210
+ // accepted.length is 0 in this branch, so the advisory printed
9211
+ // earlier (guarded on accepted.length > 0) never showed the link —
9212
+ // append it to the wait hint here, never replacing it.
9213
+ nextAction: `Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>${billingConflictLink(conflicts, resolveApiUrl(opts, deps))}`,
8008
9214
  requestId: 'local',
8009
9215
  details: {
8010
9216
  conflicts: conflicts.map(c => ({ testId: c.testId, currentRunId: c.currentRunId })),
@@ -8040,6 +9246,14 @@ export async function runTestRerun(opts, deps = {}) {
8040
9246
  throw new CLIError(`Batch rerun: no tests were accepted (${deferred.length} deferred). ` +
8041
9247
  `Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
8042
9248
  }
9249
+ // A paused/credits refusal must exit 13/12, matching the non-wait branch
9250
+ // above and `test run --all` (never the generic exit-6 CONFLICT).
9251
+ if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
9252
+ throw insufficientCreditsConflictError(conflicts, resolveApiUrl(opts, deps));
9253
+ }
9254
+ if (isPausedRefusal({ accepted, deferred, conflicts })) {
9255
+ throw pausedConflictError(conflicts, resolveApiUrl(opts, deps));
9256
+ }
8043
9257
  // Fix C: all-conflict no-op (--wait path)
8044
9258
  if (conflicts.length > 0) {
8045
9259
  // codex P2: mixed conflicts+notFound (no accepted runs) must not be
@@ -8047,8 +9261,10 @@ export async function runTestRerun(opts, deps = {}) {
8047
9261
  throw ApiError.fromEnvelope({
8048
9262
  error: {
8049
9263
  code: 'CONFLICT',
8050
- message: `Batch rerun: nothing was queued — ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight${notFound.length > 0 ? `, ${notFound.length} not found` : ''}.`,
8051
- nextAction: `Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>`,
9264
+ message: `Batch rerun: nothing was queued — ${allConflictsInFlight(conflicts)
9265
+ ? `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight`
9266
+ : summarizeConflicts(conflicts)}${notFound.length > 0 ? `, ${notFound.length} not found` : ''}.`,
9267
+ nextAction: `Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>${billingConflictLink(conflicts, resolveApiUrl(opts, deps))}`,
8052
9268
  requestId: 'local',
8053
9269
  details: {
8054
9270
  conflicts: conflicts.map(c => ({ testId: c.testId, currentRunId: c.currentRunId })),
@@ -8122,7 +9338,7 @@ export async function runTestRerun(opts, deps = {}) {
8122
9338
  }
8123
9339
  // Interrupt must reject the fan-out (the collect point below prints the
8124
9340
  // partial for every dispatched run), never flatten into a per-member
8125
- // outcome that would swallow the 128+signum exit (DEV-331).
9341
+ // outcome that would swallow the 128+signum exit.
8126
9342
  if (err instanceof InterruptError)
8127
9343
  throw err;
8128
9344
  if (err instanceof RequestTimeoutError) {
@@ -8149,7 +9365,7 @@ export async function runTestRerun(opts, deps = {}) {
8149
9365
  testId: entry.testId,
8150
9366
  runId: entry.runId,
8151
9367
  status: 'error',
8152
- error: { code: err.code, message: err.message, exitCode: err.exitCode },
9368
+ error: waitMemberError(err),
8153
9369
  };
8154
9370
  }
8155
9371
  throw err;
@@ -8181,7 +9397,7 @@ export async function runTestRerun(opts, deps = {}) {
8181
9397
  });
8182
9398
  }
8183
9399
  catch (fanOutErr) {
8184
- // Graceful detach (DEV-331): stdout stays parseable — settled members
9400
+ // Graceful detach: stdout stays parseable — settled members
8185
9401
  // keep their real status, unfinished ones are marked running — and the
8186
9402
  // honest stderr line names every runId still executing (and billing).
8187
9403
  if (fanOutErr instanceof InterruptError) {
@@ -8190,8 +9406,10 @@ export async function runTestRerun(opts, deps = {}) {
8190
9406
  const partialResults = accepted.map((e) => settled.get(e.runId) ?? { testId: e.testId, runId: e.runId, status: 'running' });
8191
9407
  out.print({ accepted: partialResults, deferred, conflicts, notFound }, () => partialResults.map(r => `${r.runId} ${r.status}`).join('\n'));
8192
9408
  const unfinished = accepted.filter(e => !settled.has(e.runId)).map(e => e.runId);
8193
- if (unfinished.length > 0)
9409
+ if (unfinished.length > 0) {
9410
+ fanOutErr.runWaitContext = true;
8194
9411
  stderrFn(interruptDetachMessage(fanOutErr, unfinished));
9412
+ }
8195
9413
  }
8196
9414
  throw fanOutErr;
8197
9415
  }
@@ -8428,6 +9646,8 @@ export async function runArtifactGet(opts, deps = {}) {
8428
9646
  dir: resolvedDir,
8429
9647
  failedOnly: opts.failedOnly,
8430
9648
  fetchImpl: deps.fetchImpl,
9649
+ shutdownSignal: shutdownOf(deps).signal,
9650
+ shutdown: shutdownOf(deps),
8431
9651
  });
8432
9652
  if (opts.output === 'json') {
8433
9653
  out.print({
@@ -8481,10 +9701,11 @@ function renderArtifactGetWrittenText(data) {
8481
9701
  * test, so the probe is a heuristic, not a guarantee — hence the full
8482
9702
  * opt-out.
8483
9703
  */
8484
- const SKIP_PREFLIGHT_HELP = 'skip the pre-charge --target-url reachability probe. The probe runs from this machine, not ' +
9704
+ const SKIP_PREFLIGHT_HELP = 'skip the pre-charge reachability probe for a target URL. The probe runs from this machine, not ' +
8485
9705
  'from the Lambda that executes the test, so it can occasionally be wrong (e.g. an IP allowlist ' +
8486
9706
  'that permits the Lambda but not this machine); use this flag when you know better. Zero network ' +
8487
9707
  'calls when set.';
9708
+ const TARGET_URL_HELP = "frontend tests only: use the environment already pointing at this URL's origin, or a temporary one TestSprite deletes when the run finishes; with --env, use its settings against this URL";
8488
9709
  export function createTestCommand(deps = {}) {
8489
9710
  const test = new Command('test').description('Inspect TestSprite tests');
8490
9711
  test
@@ -8499,7 +9720,7 @@ export function createTestCommand(deps = {}) {
8499
9720
  .option('--project <id>', 'project id (returned by `testsprite project list`)')
8500
9721
  .option('--type <type>', 'filter by test type (frontend|backend)')
8501
9722
  .option('--created-from <source>', 'filter by where the test was authored (portal|mcp|cli)')
8502
- .option('--status <list>', 'filter by normalized status (comma-separated). One of: draft, ready, queued, running, passed, failed, blocked, cancelled, unknown — M2.1')
9723
+ .option('--status <list>', 'filter by normalized status (comma-separated). One of: draft, ready, queued, running, passed, failed, blocked, cancelled, unknown')
8503
9724
  .option('--page-size <n>', 'service page-size hint (1-100, default 25)')
8504
9725
  .option('--starting-token <token>', 'opaque cursor from a previous list response')
8505
9726
  .option('--cursor <token>', 'alias for --starting-token; accepted for parity with `test result --history`')
@@ -8517,7 +9738,7 @@ export function createTestCommand(deps = {}) {
8517
9738
  // `test result --history`). --starting-token takes precedence if
8518
9739
  // both are supplied (prevents accidental override).
8519
9740
  await runList({
8520
- ...resolveCommonOptions(command),
9741
+ ...resolveCommonOptions(command, deps.env),
8521
9742
  projectId: cmdOpts.project,
8522
9743
  type: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES),
8523
9744
  createdFrom: parseEnumFlag(cmdOpts.createdFrom, 'created-from', CREATED_FROMS),
@@ -8534,11 +9755,11 @@ export function createTestCommand(deps = {}) {
8534
9755
  .description('Get a test by id')
8535
9756
  .addHelpText('after', GLOBAL_OPTS_HINT)
8536
9757
  .action(async (testId, _cmdOpts, command) => {
8537
- await runGet({ ...resolveCommonOptions(command), testId }, deps);
9758
+ await runGet({ ...resolveCommonOptions(command, deps.env), testId }, deps);
8538
9759
  });
8539
9760
  test
8540
9761
  .command('create')
8541
- .description('Create a test from saved code (--code-file) or an agent-supplied plan (--plan-from, FE-only, M3.2 piece-5)')
9762
+ .description('Create a test from saved code (--code-file) or an agent-supplied plan (--plan-from, FE-only)')
8542
9763
  .option('--project <id>', 'project id (returned by `testsprite project list`)')
8543
9764
  .option('--type <type>', 'frontend|backend')
8544
9765
  .option('--name <name>', 'human-readable test name (becomes `title` in storage)')
@@ -8553,26 +9774,28 @@ export function createTestCommand(deps = {}) {
8553
9774
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
8554
9775
  .option('--wait', 'with --run, poll until terminal status', false)
8555
9776
  .option('--timeout <s>', 'with --run --wait, max seconds to wait')
8556
- .option('--target-url <url>', 'with --run, override the project default env URL. Before triggering, a reachability ' +
8557
- 'preflight refuses obviously-dead targets (DNS failure, connection refused, a 502/503/504 ' +
8558
- 'gateway error) so a doomed run never gets billed — see --skip-preflight.')
9777
+ .option('--target-url <url>', TARGET_URL_HELP)
9778
+ .option('--env <name>', 'with --run, run against the named project environment')
8559
9779
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
8560
9780
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
8561
9781
  .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering on `test rerun` and `test run --all`.', (val, prev) => [...(prev ?? []), val], [])
8562
9782
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Use to declare upstream producer dependencies.', (val, prev) => [...(prev ?? []), val], [])
8563
9783
  .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
8564
9784
  .addHelpText('after', PLAN_TEMPLATE_HELP_TEXT)
8565
- .addHelpText('after', '\nBE dependency authoring (M4):\n' +
9785
+ .addHelpText('after', '\nBE dependency authoring:\n' +
8566
9786
  ' --produces/--needs drive wave ordering on `test rerun` + `test run --all`.\n' +
8567
9787
  ' --category teardown marks a final-wave cleanup test.\n' +
8568
9788
  ' These flags are backend-only; supplying with --type frontend is an error (exit 5).')
8569
9789
  .addHelpText('after', GLOBAL_OPTS_HINT)
8570
9790
  .action(async (cmdOpts, command) => {
9791
+ if (cmdOpts.env !== undefined && cmdOpts.run !== true) {
9792
+ throw localValidationError('env', '--env requires --run');
9793
+ }
8571
9794
  // Pure-local, no network/credentials, no other flag is
8572
9795
  // consulted. Checked first so `--plan-template` never trips the
8573
9796
  // --plan-from/--code-file mutual-exclusivity guard below.
8574
9797
  if (cmdOpts.planTemplate === true) {
8575
- runPlanTemplate(resolveCommonOptions(command), deps);
9798
+ runPlanTemplate(resolveCommonOptions(command, deps.env), deps);
8576
9799
  return;
8577
9800
  }
8578
9801
  // --plan-from and --code-file are mutually exclusive. Dispatch
@@ -8615,7 +9838,7 @@ export function createTestCommand(deps = {}) {
8615
9838
  if (cmdOpts.stepTimeout !== undefined)
8616
9839
  ignored.push('--step-timeout');
8617
9840
  await runCreateFromPlan({
8618
- ...resolveCommonOptions(command),
9841
+ ...resolveCommonOptions(command, deps.env),
8619
9842
  planFrom: cmdOpts.planFrom,
8620
9843
  run: cmdOpts.run === true,
8621
9844
  wait: cmdOpts.wait === true,
@@ -8623,6 +9846,7 @@ export function createTestCommand(deps = {}) {
8623
9846
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
8624
9847
  timeoutIsDefault: cmdOpts.timeout === undefined,
8625
9848
  targetUrl: cmdOpts.targetUrl,
9849
+ environment: cmdOpts.env,
8626
9850
  skipPreflight: cmdOpts.skipPreflight === true,
8627
9851
  idempotencyKey: cmdOpts.idempotencyKey,
8628
9852
  ignoredFlags: ignored,
@@ -8630,7 +9854,7 @@ export function createTestCommand(deps = {}) {
8630
9854
  return;
8631
9855
  }
8632
9856
  await runCreate({
8633
- ...resolveCommonOptions(command),
9857
+ ...resolveCommonOptions(command, deps.env),
8634
9858
  projectId: cmdOpts.project,
8635
9859
  type: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES),
8636
9860
  name: cmdOpts.name,
@@ -8646,6 +9870,7 @@ export function createTestCommand(deps = {}) {
8646
9870
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
8647
9871
  timeoutIsDefault: cmdOpts.timeout === undefined,
8648
9872
  targetUrl: cmdOpts.targetUrl,
9873
+ environment: cmdOpts.env,
8649
9874
  skipPreflight: cmdOpts.skipPreflight === true,
8650
9875
  // M4 piece-2: BE dependency authoring flags.
8651
9876
  // Commander variadic collectors initialise to [] — treat empty array as undefined
@@ -8661,18 +9886,18 @@ export function createTestCommand(deps = {}) {
8661
9886
  .option('--plans <path>', 'JSONL file with one plan-from spec per line (≤ 50 specs, ≤ 5 MB)')
8662
9887
  .option('--plan-from-dir <dir>', 'directory of *.json plan files — each file is one plan spec (≤ 50 files, ≤ 5 MB total). Sorted by filename for determinism. Mutually exclusive with --plans.')
8663
9888
  .option('--run', 'after create, trigger each created test as a run', false)
8664
- .option('--max-concurrency <n>', 'with --run, max in-flight triggers at once (1-100, default: 50). The server caps run-triggers at 60/min/key; the CLI throttles to 50/min and auto-retries RATE_LIMITED responses client-side — raising this value does not bypass the server cap.')
9889
+ .option('--max-concurrency <n>', 'with --run, max in-flight triggers at once (1-100, default: 50). The server caps run-triggers at 60/min/key; the CLI throttles to 50/min and auto-retries RATE_LIMITED responses client-side — raising this value does not bypass the server cap. ' +
9890
+ `Separately, CLI run triggers are refused once ${SERVER_INFLIGHT_RUN_CAP} of your runs are already in flight (server default; the refusal reports your account's real cap). Runs from every source count toward it, and a large batch can reach it on its own, so anything already running makes later triggers exit 11 with details.reason "inflight_cap" — not auto-retried, runs have to finish first. With --wait a slot is held until each run finishes, so lowering this flag keeps fewer runs in flight; without --wait it only paces dispatch, and a smaller batch is the lever.`)
8665
9891
  .option('--wait', 'with --run, poll each run until terminal status', false)
8666
9892
  .option('--timeout <s>', 'with --run --wait, per-run max seconds to wait (1-3600, default 600)')
8667
- .option('--target-url <url>', 'with --run, override the project default env URL for each run. Before the fan-out, a ' +
8668
- 'reachability preflight refuses an obviously-dead target ONCE for the whole batch (DNS ' +
8669
- 'failure, connection refused, a 502/503/504 gateway error) — see --skip-preflight.')
9893
+ .option('--target-url <url>', TARGET_URL_HELP)
9894
+ .option('--env <name>', 'with --run, run each created test against the named project environment')
8670
9895
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
8671
9896
  .option('--idempotency-key <token>', 'opaque idempotency token for the batch create (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
8672
9897
  .addHelpText('after', GLOBAL_OPTS_HINT)
8673
9898
  .action(async (cmdOpts, command) => {
8674
9899
  await runCreateBatch({
8675
- ...resolveCommonOptions(command),
9900
+ ...resolveCommonOptions(command, deps.env),
8676
9901
  plans: cmdOpts.plans,
8677
9902
  planFromDir: cmdOpts.planFromDir,
8678
9903
  run: cmdOpts.run === true,
@@ -8680,6 +9905,7 @@ export function createTestCommand(deps = {}) {
8680
9905
  wait: cmdOpts.wait === true,
8681
9906
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
8682
9907
  targetUrl: cmdOpts.targetUrl,
9908
+ environment: cmdOpts.env,
8683
9909
  skipPreflight: cmdOpts.skipPreflight === true,
8684
9910
  idempotencyKey: cmdOpts.idempotencyKey,
8685
9911
  }, deps);
@@ -8697,7 +9923,7 @@ export function createTestCommand(deps = {}) {
8697
9923
  .addHelpText('after', GLOBAL_OPTS_HINT)
8698
9924
  .action(async (cmdOpts, command) => {
8699
9925
  await runScaffold({
8700
- ...resolveCommonOptions(command),
9926
+ ...resolveCommonOptions(command, deps.env),
8701
9927
  scaffoldType: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES) ?? 'frontend',
8702
9928
  out: cmdOpts.out,
8703
9929
  force: cmdOpts.force === true,
@@ -8710,7 +9936,7 @@ export function createTestCommand(deps = {}) {
8710
9936
  .addHelpText('after', GLOBAL_OPTS_HINT)
8711
9937
  .action(async (testId, cmdOpts, command) => {
8712
9938
  await runOpen({
8713
- ...resolveCommonOptions(command),
9939
+ ...resolveCommonOptions(command, deps.env),
8714
9940
  testId,
8715
9941
  noBrowser: cmdOpts.browser === false,
8716
9942
  }, deps);
@@ -8725,7 +9951,7 @@ export function createTestCommand(deps = {}) {
8725
9951
  .addHelpText('after', GLOBAL_OPTS_HINT)
8726
9952
  .action(async (testId, cmdOpts, command) => {
8727
9953
  await runSteps({
8728
- ...resolveCommonOptions(command),
9954
+ ...resolveCommonOptions(command, deps.env),
8729
9955
  testId,
8730
9956
  pageSize: parseNumericFlag(cmdOpts.pageSize, 'page-size'),
8731
9957
  startingToken: cmdOpts.startingToken,
@@ -8738,7 +9964,7 @@ export function createTestCommand(deps = {}) {
8738
9964
  .description('Compare two runs and print what regressed: verdict, failureKind, failedStepIndex, per-step status flips, codeVersion drift. Exit 0 when verdicts match, 1 when they differ.')
8739
9965
  .addHelpText('after', GLOBAL_OPTS_HINT)
8740
9966
  .action(async (runA, runB, _cmdOpts, command) => {
8741
- await runDiff({ ...resolveCommonOptions(command), runA, runB }, deps);
9967
+ await runDiff({ ...resolveCommonOptions(command, deps.env), runA, runB }, deps);
8742
9968
  });
8743
9969
  test
8744
9970
  .command('lint')
@@ -8750,7 +9976,7 @@ export function createTestCommand(deps = {}) {
8750
9976
  .addHelpText('after', GLOBAL_OPTS_HINT)
8751
9977
  .action(async (cmdOpts, command) => {
8752
9978
  await runLint({
8753
- ...resolveCommonOptions(command),
9979
+ ...resolveCommonOptions(command, deps.env),
8754
9980
  planFrom: cmdOpts.planFrom,
8755
9981
  planFromDir: cmdOpts.planFromDir,
8756
9982
  plans: cmdOpts.plans,
@@ -8762,10 +9988,10 @@ export function createTestCommand(deps = {}) {
8762
9988
  .description('Get the latest result for a test (default) or list prior runs (--history).\n' +
8763
9989
  '\n--output json shape differs by mode:\n' +
8764
9990
  ' (default) single CliLatestResult object\n' +
8765
- ' --history { runs: RunHistoryItem[], nextCursor: string|null }\n' +
9991
+ ' --history { runs: RunHistoryItem[], nextCursor: string|null, meta: RunHistoryMeta }\n' +
8766
9992
  '\nPer-run detail: testsprite test wait <run-id>\n' +
8767
9993
  'Failure bundle: testsprite test artifact get <run-id>')
8768
- .option('--include-analysis', 'attach the inline `analysis` block (rootCauseHypothesis, recommendedFixTarget, failureKind, snapshotId) — M2.1', false)
9994
+ .option('--include-analysis', 'attach the inline `analysis` block (rootCauseHypothesis, recommendedFixTarget, failureKind, snapshotId)', false)
8769
9995
  .option('--history', 'list prior runs for this test instead of showing the latest result')
8770
9996
  .option('--source <src>', `with --history: filter by trigger source (${RUN_SOURCES.join('|')})`)
8771
9997
  .option('--since <dur>', 'with --history: lower bound on createdAt — 24h, 7d, or ISO timestamp (client-side translated)')
@@ -8786,7 +10012,7 @@ export function createTestCommand(deps = {}) {
8786
10012
  if (cmdOpts.history) {
8787
10013
  // M3.4 piece-5: --history mode — list prior runs.
8788
10014
  await runResultHistory({
8789
- ...resolveCommonOptions(command),
10015
+ ...resolveCommonOptions(command, deps.env),
8790
10016
  testId,
8791
10017
  source: parseEnumFlag(cmdOpts.source, 'source', RUN_SOURCES),
8792
10018
  since: cmdOpts.since,
@@ -8803,7 +10029,7 @@ export function createTestCommand(deps = {}) {
8803
10029
  else {
8804
10030
  // M2 mode: latest result (byte-identical to pre-piece-5 behavior).
8805
10031
  await runResult({
8806
- ...resolveCommonOptions(command),
10032
+ ...resolveCommonOptions(command, deps.env),
8807
10033
  testId,
8808
10034
  includeAnalysis: cmdOpts.includeAnalysis === true,
8809
10035
  }, deps);
@@ -8827,7 +10053,7 @@ export function createTestCommand(deps = {}) {
8827
10053
  throw localValidationError('step-timeout', '--step-timeout and --clear-step-timeout are mutually exclusive');
8828
10054
  }
8829
10055
  await runUpdate({
8830
- ...resolveCommonOptions(command),
10056
+ ...resolveCommonOptions(command, deps.env),
8831
10057
  testId,
8832
10058
  name: cmdOpts.name,
8833
10059
  description: cmdOpts.description,
@@ -8842,13 +10068,13 @@ export function createTestCommand(deps = {}) {
8842
10068
  });
8843
10069
  test
8844
10070
  .command('delete <test-id>')
8845
- .description('Permanently delete a test. Requires --confirm. (M3.2 piece-3)')
10071
+ .description('Permanently delete a test. Requires --confirm.')
8846
10072
  .option('--confirm', 'required: explicit confirmation for the destructive operation', false)
8847
10073
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
8848
10074
  .addHelpText('after', GLOBAL_OPTS_HINT)
8849
10075
  .action(async (testId, cmdOpts, command) => {
8850
10076
  await runDelete({
8851
- ...resolveCommonOptions(command),
10077
+ ...resolveCommonOptions(command, deps.env),
8852
10078
  testId,
8853
10079
  confirm: cmdOpts.confirm === true,
8854
10080
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -8874,7 +10100,7 @@ export function createTestCommand(deps = {}) {
8874
10100
  .addHelpText('after', GLOBAL_OPTS_HINT)
8875
10101
  .action(async (testIdsArg, cmdOpts, command) => {
8876
10102
  await runDeleteBatch({
8877
- ...resolveCommonOptions(command),
10103
+ ...resolveCommonOptions(command, deps.env),
8878
10104
  testIds: testIdsArg ?? [],
8879
10105
  all: cmdOpts.all === true,
8880
10106
  projectId: cmdOpts.project,
@@ -8886,67 +10112,74 @@ export function createTestCommand(deps = {}) {
8886
10112
  // M3.3 piece-3 — `test run` and `test wait`
8887
10113
  // -------------------------------------------------------------------------
8888
10114
  test
8889
- .command('run [test-id]')
8890
- .description('Trigger a test run. With --wait, polls until terminal status.\n' +
8891
- 'Use --all --project <id> for a wave-ordered batch run of all tests in a project (M4).\n' +
10115
+ .command('run [test-id...]')
10116
+ .description('Trigger one test run, or several local frontend runs through one tunnel. With --wait, polls until terminal status.\n' +
10117
+ 'Use --all --project <id> for a wave-ordered batch run, or add --local <port> to run its frontend tests through one tunnel.\n' +
8892
10118
  '\nExit codes:\n' +
8893
10119
  ' 0 passed (or queued without --wait)\n' +
8894
10120
  ' 1 failed / blocked / cancelled\n' +
8895
10121
  ' 3 auth error\n' +
8896
10122
  ' 4 test not found\n' +
8897
- ' 5 validation error (e.g., bad --target-url, or positional + --all both set)\n' +
10123
+ ' 5 validation error (e.g., bad URL, or positional + --all both set)\n' +
8898
10124
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
8899
10125
  ' 7 timeout — resume with: testsprite test wait <run-id>, ' +
8900
10126
  'or stop it with: testsprite test cancel <run-id>\n' +
8901
10127
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
8902
- ' 11 rate limited — honor Retry-After\n' +
10128
+ ' 11 rate limited — honor Retry-After, or the in-flight run cap was hit\n' +
10129
+ ' (details.reason "inflight_cap"; see: testsprite test run --help)\n' +
8903
10130
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
8904
- '\nCtrl-C during --wait detaches only (the run keeps executing and billing);\n' +
8905
- 'stop it for real with: testsprite test cancel <run-id>')
8906
- .option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private ' +
8907
- 'IPs). Before triggering, a reachability preflight refuses an obviously-dead target (DNS ' +
8908
- 'failure, connection refused, a 502/503/504 gateway error) so a doomed run never gets ' +
8909
- 'billed. This CLI probes from wherever it runs, not from the Lambda that executes the ' +
8910
- 'test, so it is a heuristic, not a guarantee — see --skip-preflight. Note: for a backend ' +
8911
- 'test, --target-url itself is inert (its base URL is baked into its code) — but this bare ' +
8912
- "`run` command has no way to know a test's type before triggering it, so the preflight " +
8913
- 'still runs and can still refuse; use --skip-preflight if that surprises you.')
10131
+ '\nCtrl-C during an ordinary --wait detaches; an owned --local tunnel cancels unfinished runs by default.\n' +
10132
+ 'Stop a detached run with: testsprite test cancel <run-id>')
10133
+ .option('--target-url <url>', TARGET_URL_HELP)
8914
10134
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
8915
10135
  .option('--local <port>', 'run against an app on THIS machine, reached through a TestSprite tunnel. The test runner ' +
8916
10136
  'navigates to http://127.0.0.1:<port> and its traffic is proxied back to you for as long ' +
8917
10137
  'as this command runs. Implies --wait (the tunnel closes when the command exits, so a ' +
8918
- 'detached run could not finish) and cannot be combined with --target-url. Frontend tests ' +
8919
- 'only. Before anything is minted or billed, the port is probed and a dead one is refused.')
10138
+ 'detached run could not finish). Frontend tests ' +
10139
+ 'only; several ids or --all share one tunnel (5 concurrent by default, at most 10). ' +
10140
+ 'Before anything is minted or billed, the port is probed and a dead one is refused.')
8920
10141
  .option('--local-host <host>', `with --local, which loopback address to name in the run's target URL — one of ` +
8921
10142
  `${LOOPBACK_HOSTS.join(', ')} (default ${DEFAULT_LOCAL_HOST}). Use localhost if your app ` +
8922
10143
  `only answers on that name, or ::1 for an IPv6-only listener.`)
8923
10144
  .option('--tunnel-client <id>', 'with --local, attach to a tunnel already running under `testsprite tunnel start` instead ' +
8924
10145
  'of opening a new one. The id is the non-secret handle that command prints; the tunnel ' +
8925
- 'stays owned by that process and is not closed when this run finishes.')
10146
+ 'stays owned by that process and is not closed when this run or batch finishes.')
8926
10147
  .option('--no-cancel-on-interrupt', 'with --local, skip automatic cancellation when an owned tunnel is about to close or a ' +
8927
10148
  "borrowed tunnel's owner disappears. An ordinary interrupt of a borrowed run never " +
8928
10149
  'cancels it because its tunnel remains alive.')
8929
10150
  .option('--env <name>', 'run against the named project environment — its test-account credentials, auto-auth and ' +
8930
10151
  'OTP settings (names: `testsprite project env list <project-id>`). Combine with --local ' +
8931
- 'to use those credentials against your own machine, or with --target-url against another ' +
8932
- "address; without either, the run opens that environment's URL. Omit --env to keep using " +
10152
+ 'to use those credentials against your own machine; without --local, the run opens ' +
10153
+ "that environment's URL. Omit --env to keep using " +
8933
10154
  "the project's default environment. Also applies with --all.")
8934
10155
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
8935
- .option('--timeout <s>', 'with --wait, max seconds to wait (1–3600; default 600, or 1200 with --local)')
8936
- .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
10156
+ .option('--timeout <s>', 'with --wait, max seconds per run (1–3600; default 600, or 1200 with --local)')
10157
+ .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars); local batches append each test id. Auto-generated keys print to stderr in JSON, verbose or debug mode.')
8937
10158
  .option('--all', 'run all tests in the project (wave-ordered fresh run; uses --project or TESTSPRITE_PROJECT_ID). Mutually exclusive with <test-id>.', false)
8938
10159
  .option('--project <id>', 'project id (with --all, overrides TESTSPRITE_PROJECT_ID; returned by `testsprite project list`)')
8939
10160
  .option('--filter <substr>', 'with --all: only run tests whose name contains this substring (case-insensitive)')
8940
- .option('--max-concurrency <n>', `with --all --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
8941
- .option('--report <format>', 'with --all --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
10161
+ .option('--max-concurrency <n>', `with --local, max runs in flight through one tunnel (1-10, default 5); with --all --wait without --local, max polls (1-100, default ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
10162
+ .option('--report <format>', 'with a --wait batch (--all or several local ids): write a JUnit XML sidecar report after polling (accepted: junit)')
8942
10163
  .option('--report-file <path>', 'output path for --report (atomic write)')
8943
10164
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
8944
- .option('--gh-output', 'with --wait (single test or --all): emit GitHub-native output (::error:: annotations for failed/timed-out runs, ::warning:: for never-dispatched tests; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
8945
- .option('--summary-file <path>', 'with --wait (single test or --all): also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
10165
+ .option('--gh-output', 'with --wait (single test or batch): emit GitHub-native output (::error:: annotations for failed/timed-out runs, ::warning:: for never-dispatched tests; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
10166
+ .option('--summary-file <path>', 'with --wait (single test or batch): also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
8946
10167
  .option('--allow-empty', 'with --all: exit 0 when the run dispatches ZERO tests (all skipped / empty project / --filter matched nothing). Default: fail with exit 5 — a zero-dispatch run is a CI false-green')
8947
- .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
10168
+ .option('--no-auto-heal', 'ask the server to replay stored test code instead of letting the agent heal it. ' +
10169
+ 'The server controls whether fresh runs heal drifted generated code by default; when ' +
10170
+ 'healing is enabled, the agent re-authors stale code rather than replaying a script ' +
10171
+ 'that can only fail. Use this flag to request a strict replay for a regression gate ' +
10172
+ 'or a reproduction you are bisecting. Code you wrote yourself is never re-authored. ' +
10173
+ 'Where stored-code replay is unavailable, the server rejects this flag. Where replay ' +
10174
+ 'is available but a test has no replayable stored code, the server may refuse the run ' +
10175
+ 'instead of authoring it. An older server may ignore the flag; the CLI prints an ' +
10176
+ '[advisory] when the server reports that the opt-out did not take.')
10177
+ .addHelpText('after', '\nDependency-aware fresh run:\n' +
8948
10178
  ' testsprite test run --all --project <id> run all project tests in wave order\n' +
8949
10179
  ' TESTSPRITE_PROJECT_ID=<id> testsprite test run --all use env default project\n' +
10180
+ ' testsprite test run <id> <id> --local 3000 several local tests, one tunnel\n' +
10181
+ ' testsprite test run --all --project <id> --local 3000 all frontend tests, one tunnel\n' +
10182
+ ' testsprite test run <id> <id> --local 3000 --max-concurrency 3\n' +
8950
10183
  ' testsprite test run --all --filter <substr> name-glob subset (uses --project/env)\n' +
8951
10184
  ' testsprite test run --all --wait --report junit --report-file ./results.xml\n' +
8952
10185
  ' project id precedence: --project wins over TESTSPRITE_PROJECT_ID\n' +
@@ -8954,15 +10187,30 @@ export function createTestCommand(deps = {}) {
8954
10187
  '(see `testsprite test create --help` for details).\n' +
8955
10188
  '\nFrontend tests: the current unified engine runs FE tests too (they are billed\n' +
8956
10189
  'like any run). On the legacy backend-only engine FE tests cannot run — they are\n' +
8957
- "reported under skippedFrontend with an advisory; run those with 'test run <id>'.")
10190
+ "reported under skippedFrontend with an advisory; run those with 'test run <id>'.\n" +
10191
+ '\nConcurrency limits:\n' +
10192
+ ` - CLI run triggers are refused once ${SERVER_INFLIGHT_RUN_CAP} of your runs are already in\n` +
10193
+ ' flight (server default; the refusal reports your real cap). Runs from every\n' +
10194
+ ' source count toward it (CLI, portal, schedules, CI), but only CLI triggers\n' +
10195
+ ' are refused on it.\n' +
10196
+ ' At the cap this command accepts nothing and returns every id deferred,\n' +
10197
+ ' which exits 7; resume with the printed ids once runs finish. (A single\n' +
10198
+ ' `test run <id>` over the cap exits 11 with details.reason "inflight_cap",\n' +
10199
+ ' and is not auto-retried — runs have to finish first.)\n' +
10200
+ ' Poll what is already running with: testsprite test wait <run-id...>\n' +
10201
+ ' - Separately, run triggers are throttled per minute. That one does clear on\n' +
10202
+ ' its own and is retried for you.\n' +
10203
+ ' - --max-concurrency here bounds the --wait poll fan-out, not dispatch, so it\n' +
10204
+ ' has no effect on the cap. A smaller batch does.')
8958
10205
  .addHelpText('after', GLOBAL_OPTS_HINT)
8959
- .action(async (testIdArg, cmdOpts, command) => {
10206
+ .action(async (testIdArgs, cmdOpts, command) => {
8960
10207
  const isAll = cmdOpts.all === true;
10208
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
8961
10209
  // Mutual-exclusion: exactly one of positional <test-id> vs --all must be set.
8962
- if (testIdArg !== undefined && isAll) {
10210
+ if (testIdArgs.length > 0 && isAll) {
8963
10211
  throw localValidationError('test-id', 'positional <test-id> and --all are mutually exclusive; use one or the other');
8964
10212
  }
8965
- if (testIdArg === undefined && !isAll) {
10213
+ if (testIdArgs.length === 0 && !isAll) {
8966
10214
  throw localValidationError('test-id', 'provide a <test-id>, or use --all with --project <id> or TESTSPRITE_PROJECT_ID');
8967
10215
  }
8968
10216
  // --filter is an --all-only narrowing flag (mirrors `test rerun --filter`).
@@ -8978,9 +10226,26 @@ export function createTestCommand(deps = {}) {
8978
10226
  const localPort = cmdOpts.local !== undefined ? parseLocalPort(cmdOpts.local) : undefined;
8979
10227
  const usingLocal = localPort !== undefined;
8980
10228
  const effectiveWait = usingLocal || cmdOpts.wait === true;
8981
- if (usingLocal && isAll) {
8982
- throw localValidationError('local', '--local runs one test through one tunnel; --all fans out across a project. Run the ' +
8983
- 'tests you want against your machine one at a time, or drop --local');
10229
+ if (!usingLocal && testIdArgs.length >= 2) {
10230
+ throw localValidationError('test-id', 'several test ids run through one tunnel with --local <port>. For tests the runner can already reach, use `testsprite test run --all --project <id> [--filter <text>]`, or run them one at a time.');
10231
+ }
10232
+ const maxConcurrency = cmdOpts.maxConcurrency === undefined
10233
+ ? usingLocal
10234
+ ? 5
10235
+ : DEFAULT_BATCH_RUN_CONCURRENCY
10236
+ : Number(cmdOpts.maxConcurrency);
10237
+ if (usingLocal &&
10238
+ (!Number.isInteger(maxConcurrency) || maxConcurrency < 1 || maxConcurrency > 10)) {
10239
+ throw localValidationError('max-concurrency', 'with --local, --max-concurrency must be between 1 and 10 (every run shares this machine and its one tunnel; the default is 5)');
10240
+ }
10241
+ const testIds = [...new Set(testIdArgs)];
10242
+ if (usingLocal) {
10243
+ const seen = new Set();
10244
+ for (const id of testIdArgs) {
10245
+ if (seen.has(id))
10246
+ stderrFn(`[advisory] ignoring duplicate test id ${id}`);
10247
+ seen.add(id);
10248
+ }
8984
10249
  }
8985
10250
  if (usingLocal && cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
8986
10251
  throw localValidationError('local', '--local and --target-url are mutually exclusive: --local runs against your own ' +
@@ -9010,7 +10275,7 @@ export function createTestCommand(deps = {}) {
9010
10275
  reportFile: cmdOpts.reportFile,
9011
10276
  reportSuiteName: cmdOpts.reportSuiteName,
9012
10277
  wait: effectiveWait,
9013
- batchPath: isAll,
10278
+ batchPath: isAll || (usingLocal && testIds.length > 1),
9014
10279
  });
9015
10280
  // --gh-output / --summary-file reduce a --wait run's terminal result into
9016
10281
  // the CI summary. They require --wait (without it the command returns after
@@ -9023,21 +10288,21 @@ export function createTestCommand(deps = {}) {
9023
10288
  if (cmdOpts.summaryFile !== undefined && !effectiveWait) {
9024
10289
  throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
9025
10290
  }
9026
- if (isAll) {
10291
+ if (isAll && !usingLocal) {
9027
10292
  // --all path: wave-ordered fresh batch run.
9028
10293
  const projectId = resolveProjectId(cmdOpts.project, deps);
9029
10294
  requireProjectId(projectId, '--all requires a project id - pass --project <id> or set TESTSPRITE_PROJECT_ID');
9030
- // --target-url has no effect on the --all batch path: a BE test's base
9031
- // URL is baked into its code, and the unified engine resolves each
9032
- // project's configured environment server-side (per-run URL overrides
9033
- // are not applied to batch FE runs either). Silently dropping it could
9034
- // run the suite against an unintended environment in the caller's mind,
9035
- // so reject loudly.
9036
- if (cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
9037
- throw localValidationError('target-url', '--target-url has no effect with --all (the batch path does not apply a per-run URL override — BE test URLs are baked into their code and the unified engine resolves the project environment server-side). Remove --target-url.');
10295
+ // A batch target URL applies to frontend tests in the batch.
10296
+ // Server-side it rides the same per-run override field a single fresh
10297
+ // FE run uses, so FE cases honor it; a BE test still ignores it (its
10298
+ // base URL is baked into generated code), which the advisory below
10299
+ // states rather than leaving the caller to infer. An empty value is
10300
+ // the flag with no argument — still a mistake, still rejected.
10301
+ if (cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl === '') {
10302
+ throw localValidationError('target-url', '--target-url needs a URL (e.g. --target-url https://pr-42.preview.example.com).');
9038
10303
  }
9039
10304
  await runTestRunAll({
9040
- ...resolveCommonOptions(command),
10305
+ ...resolveCommonOptions(command, deps.env),
9041
10306
  projectId,
9042
10307
  nameFilter: cmdOpts.filter,
9043
10308
  wait: effectiveWait,
@@ -9051,7 +10316,18 @@ export function createTestCommand(deps = {}) {
9051
10316
  ghOutput: cmdOpts.ghOutput === true,
9052
10317
  summaryFile: cmdOpts.summaryFile,
9053
10318
  allowEmpty: cmdOpts.allowEmpty === true,
10319
+ // Commander's `--no-auto-heal` makes `cmdOpts.autoHeal` default to
10320
+ // `true` and become `false` only when the flag is passed. There is no
10321
+ // explicit `--auto-heal`, deliberately: on the wire `true` means an
10322
+ // UNCONDITIONAL heal that re-authors user-written code, which is not
10323
+ // what a caller who typed nothing asked for. Omission requests the
10324
+ // protected default instead.
10325
+ ...(cmdOpts.autoHeal === false ? { autoHeal: false } : {}),
9054
10326
  environment: cmdOpts.env,
10327
+ ...(cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== ''
10328
+ ? { targetUrl: cmdOpts.targetUrl }
10329
+ : {}),
10330
+ skipPreflight: cmdOpts.skipPreflight === true,
9055
10331
  }, deps);
9056
10332
  return;
9057
10333
  }
@@ -9065,7 +10341,7 @@ export function createTestCommand(deps = {}) {
9065
10341
  // this command exits" is simply false there, and it is the sentence a
9066
10342
  // reader would act on: told that, someone deciding whether to background
9067
10343
  // this command concludes the wrong thing about their own tunnel.
9068
- const commonOpts = resolveCommonOptions(command);
10344
+ const commonOpts = resolveCommonOptions(command, deps.env);
9069
10345
  if (usingLocal && cmdOpts.wait !== true && commonOpts.output !== 'json') {
9070
10346
  const adopted = cmdOpts.tunnelClient !== undefined;
9071
10347
  (deps.stderr ?? ((line) => process.stderr.write(`${line}\n`)))(adopted
@@ -9074,10 +10350,38 @@ export function createTestCommand(deps = {}) {
9074
10350
  : '[advisory] --local implies --wait: the tunnel closes when this command exits, so ' +
9075
10351
  'the run is followed to a verdict rather than detached.');
9076
10352
  }
10353
+ if (usingLocal && (isAll || testIds.length > 1)) {
10354
+ await runTestRunLocalBatch({
10355
+ ...commonOpts,
10356
+ testIds,
10357
+ all: isAll,
10358
+ projectId: cmdOpts.project,
10359
+ nameFilter: cmdOpts.filter,
10360
+ localPort: localPort,
10361
+ localHost: localHost ?? DEFAULT_LOCAL_HOST,
10362
+ skipPreflight: cmdOpts.skipPreflight === true,
10363
+ tunnelClientId: cmdOpts.tunnelClient,
10364
+ cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
10365
+ timeoutSeconds: cmdOpts.timeout === undefined
10366
+ ? DEFAULT_LOCAL_RUN_TIMEOUT_SECONDS
10367
+ : parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
10368
+ maxConcurrency,
10369
+ idempotencyKey: cmdOpts.idempotencyKey,
10370
+ report,
10371
+ reportFile: cmdOpts.reportFile,
10372
+ reportSuiteName: cmdOpts.reportSuiteName,
10373
+ ghOutput: cmdOpts.ghOutput === true,
10374
+ summaryFile: cmdOpts.summaryFile,
10375
+ allowEmpty: cmdOpts.allowEmpty === true,
10376
+ ...(cmdOpts.autoHeal === false ? { autoHeal: false } : {}),
10377
+ environment: cmdOpts.env,
10378
+ }, deps);
10379
+ return;
10380
+ }
9077
10381
  // Single test-id path (unchanged M3.3 behavior).
9078
10382
  await runTestRun({
9079
10383
  ...commonOpts,
9080
- testId: testIdArg,
10384
+ testId: testIds[0],
9081
10385
  targetUrl: cmdOpts.targetUrl,
9082
10386
  skipPreflight: cmdOpts.skipPreflight === true,
9083
10387
  ...(localPort !== undefined ? { localPort } : {}),
@@ -9093,6 +10397,8 @@ export function createTestCommand(deps = {}) {
9093
10397
  idempotencyKey: cmdOpts.idempotencyKey,
9094
10398
  ghOutput: cmdOpts.ghOutput === true,
9095
10399
  summaryFile: cmdOpts.summaryFile,
10400
+ // See the matching comment on the --all path above.
10401
+ ...(cmdOpts.autoHeal === false ? { autoHeal: false } : {}),
9096
10402
  environment: cmdOpts.env,
9097
10403
  }, deps);
9098
10404
  });
@@ -9127,7 +10433,7 @@ export function createTestCommand(deps = {}) {
9127
10433
  // output shape, same exit codes); two or more fan out.
9128
10434
  if (runIds.length === 1) {
9129
10435
  await runTestWait({
9130
- ...resolveCommonOptions(command),
10436
+ ...resolveCommonOptions(command, deps.env),
9131
10437
  runId: runIds[0],
9132
10438
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
9133
10439
  }, deps);
@@ -9138,7 +10444,7 @@ export function createTestCommand(deps = {}) {
9138
10444
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
9139
10445
  }
9140
10446
  await runTestWaitMany({
9141
- ...resolveCommonOptions(command),
10447
+ ...resolveCommonOptions(command, deps.env),
9142
10448
  runIds,
9143
10449
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
9144
10450
  maxConcurrency,
@@ -9171,7 +10477,10 @@ export function createTestCommand(deps = {}) {
9171
10477
  .option('--filter <substr>', 'with --all: only rerun tests whose name contains this substring (case-insensitive)')
9172
10478
  .option('--wait', 'block until terminal status or --timeout elapses', false)
9173
10479
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
9174
- .option('--no-auto-heal', 'opt out of AI heal-on-drift for this FE rerun (default: auto-heal is ON). Costs 0.2 credits per engage when a step has drifted. Ignored for backend tests.')
10480
+ .option('--no-auto-heal', 'replay the saved script verbatim instead of letting the agent repair it (default: ' +
10481
+ 'auto-heal is ON for FE reruns). When heal engages, the agent re-authors the test and ' +
10482
+ 'the new code replaces the stored version. Ignored for backend reruns. ' +
10483
+ 'Costs: `testsprite usage`.')
9175
10484
  .option('--skip-dependencies', 'BE only: rerun only the named test without expanding the producer/teardown closure', false)
9176
10485
  .option('--env <name>', 'replay against the named project environment — its test-account credentials, auto-auth and ' +
9177
10486
  'OTP settings (names: `testsprite project env list <project-id>`). Omit to keep using the ' +
@@ -9185,15 +10494,16 @@ export function createTestCommand(deps = {}) {
9185
10494
  .option('--summary-file <path>', 'with batch --wait: also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
9186
10495
  .option('--allow-empty', 'with --all: exit 0 when the resolved test set is empty (no tests match --filter/--status/--skip-terminal, or the project has none). Default: fail with exit 5 — a zero-dispatch rerun is a CI false-green')
9187
10496
  .addHelpText('after', '\nNotes:\n' +
9188
- ' • rerun replays a saved run/script and is MORE LENIENT than a fresh `test run`\n' +
9189
- ' (auto-heal can pass steps that have drifted) — for strict scoring/regression,\n' +
9190
- ' prefer `test run`. The two are not interchangeable for pass-rate measurement.\n' +
10497
+ ' • Frontend reruns default to auto-heal; the server controls the default for a\n' +
10498
+ ' fresh `test run`. Use --no-auto-heal to request a strict replay where supported.\n' +
10499
+ ' • What still differs: rerun replays a SAVED run/script, so one has to exist;\n' +
10500
+ ' `test run` starts fresh. A BE rerun also expands the dependency closure.\n' +
9191
10501
  ' • Under --wait the per-request HTTP timeout is auto-raised to cover --timeout so a\n' +
9192
10502
  ' slow trigger/poll under load is not cut at the 120s default (see --request-timeout).\n' +
9193
10503
  ' • Batch --wait: rate-deferred tests appear in `deferred[]` and `summary.deferred`,\n' +
9194
10504
  ' and force a non-zero exit — they are NOT counted in `summary.total` (dispatched only).\n' +
9195
- ' • On V3-routed accounts, --no-auto-heal is still rolling out and may not yet be\n' +
9196
- ' honored server-side — check `auth status` for your routing.')
10505
+ ' • rerun gets no server echo of the effective auto-heal decision, so a dropped\n' +
10506
+ ' opt-out cannot be detected here the way `test run --no-auto-heal` detects it.')
9197
10507
  .addHelpText('after', '\nDry-run shape notes:\n' +
9198
10508
  ' • --dry-run shows the BE rerun wire shape (includes `closure{}`); FE rerun responses\n' +
9199
10509
  ' omit `closure` (or return it as null) since there is no dependency expansion.\n' +
@@ -9225,7 +10535,7 @@ export function createTestCommand(deps = {}) {
9225
10535
  throw localValidationError('summary-file', '--summary-file requires a batch rerun with --wait (--all or 2+ test ids). Remove --summary-file, or add --all --wait.');
9226
10536
  }
9227
10537
  await runTestRerun({
9228
- ...resolveCommonOptions(command),
10538
+ ...resolveCommonOptions(command, deps.env),
9229
10539
  testIds,
9230
10540
  all: cmdOpts.all === true,
9231
10541
  projectId: cmdOpts.project,
@@ -9277,7 +10587,7 @@ export function createTestCommand(deps = {}) {
9277
10587
  .addHelpText('after', GLOBAL_OPTS_HINT)
9278
10588
  .action(async (testIdArg, cmdOpts, command) => {
9279
10589
  await runFlaky({
9280
- ...resolveCommonOptions(command),
10590
+ ...resolveCommonOptions(command, deps.env),
9281
10591
  testId: testIdArg,
9282
10592
  runs: parseNumericFlag(cmdOpts.runs, 'runs') ?? DEFAULT_FLAKY_RUNS,
9283
10593
  untilFail: cmdOpts.untilFail === true,
@@ -9348,14 +10658,16 @@ export async function runFlaky(opts, deps = {}) {
9348
10658
  // Under the implicit wait, raise the per-request timeout to cover --timeout
9349
10659
  // so a slow trigger / long-poll under load isn't cut at the 120s default.
9350
10660
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
9351
- // Best-effort test-type detection for the credit advisory. A probe failure
9352
- // never blocks the run — we just skip the advisory.
10661
+ // Best-effort test-type detection for the credit advisory. Ordinary probe
10662
+ // failures skip the advisory; interrupts stop the run.
9353
10663
  let isBackend = false;
9354
10664
  try {
9355
10665
  const test = await client.get(`/tests/${encodeURIComponent(opts.testId)}`);
9356
10666
  isBackend = test.type === 'backend';
9357
10667
  }
9358
- catch {
10668
+ catch (err) {
10669
+ if (err instanceof InterruptError)
10670
+ throw err;
9359
10671
  // best-effort — proceed without the advisory.
9360
10672
  }
9361
10673
  if (isBackend) {
@@ -9381,6 +10693,8 @@ export async function runFlaky(opts, deps = {}) {
9381
10693
  }
9382
10694
  }
9383
10695
  catch (err) {
10696
+ if (err instanceof InterruptError)
10697
+ throw err;
9384
10698
  // A missing replayable run is fatal for the whole command (mirror rerun):
9385
10699
  // there is nothing to repeat, so point the user at a fresh `test run`.
9386
10700
  if (err instanceof ApiError && err.code === 'NOT_FOUND') {
@@ -9428,11 +10742,12 @@ export async function runFlaky(opts, deps = {}) {
9428
10742
  failureKind = finalRun.failureKind;
9429
10743
  }
9430
10744
  catch (err) {
9431
- // Graceful detach (DEV-331): clean up the ticker line, name the run
10745
+ // Graceful detach: clean up the ticker line, name the run
9432
10746
  // still executing server-side, and let index.ts exit 128+signum.
9433
10747
  if (err instanceof InterruptError) {
9434
10748
  ticker.finalize(`Attempt ${i}/${opts.runs} — interrupted (${err.signal})`);
9435
10749
  stderrFn(interruptDetachMessage(err, [runId]));
10750
+ err.runWaitContext = true;
9436
10751
  throw err;
9437
10752
  }
9438
10753
  // RATE_LIMITED during polling (same defect class as the InterruptError
@@ -9521,13 +10836,13 @@ function parseNumericFlag(raw, flagName) {
9521
10836
  }
9522
10837
  return n;
9523
10838
  }
9524
- function resolveCommonOptions(command) {
10839
+ function resolveCommonOptions(command, env) {
9525
10840
  const globals = command.optsWithGlobals();
9526
10841
  // P2-8: validate --output before allowing silent fallback to 'text'.
9527
10842
  // An invalid value (e.g. `--output yaml`) must exit 5 with a clear error
9528
10843
  // rather than silently treating the request as text mode.
9529
10844
  return {
9530
- profile: globals.profile ?? 'default',
10845
+ profile: resolveProfileName(globals.profile, env),
9531
10846
  output: resolveOutputMode(globals.output),
9532
10847
  dryRun: globals.dryRun ?? false,
9533
10848
  endpointUrl: globals.endpointUrl,
@@ -9810,7 +11125,7 @@ export function isPresignedCodeUrl(code) {
9810
11125
  /**
9811
11126
  * Stream a presigned URL into the Output's chunk writer using the
9812
11127
  * deps-provided fetch impl, with no API-key headers — presigned URLs
9813
- * carry their own authority. Three failure shapes the caller might
11128
+ * carry their own authority. Network failures the caller might
9814
11129
  * see, all routed through the typed envelope so `index.ts` produces
9815
11130
  * the documented exit code:
9816
11131
  *
@@ -9825,6 +11140,7 @@ export function isPresignedCodeUrl(code) {
9825
11140
  * - The body stream errors mid-read → wrapped as `TransportError`
9826
11141
  * so partial output to stdout never silently truncates without a
9827
11142
  * non-zero exit.
11143
+ * A process interruption propagates as `InterruptError` through either read path.
9828
11144
  *
9829
11145
  * Streaming via `response.body.getReader()` keeps memory bounded for
9830
11146
  * multi-MB code bodies and starts emitting bytes to stdout the moment
@@ -9832,15 +11148,27 @@ export function isPresignedCodeUrl(code) {
9832
11148
  * the reader may want to start indexing before the download finishes.
9833
11149
  */
9834
11150
  async function streamPresignedBody(url, out, deps) {
11151
+ const shutdown = shutdownOf(deps);
11152
+ return shutdown.runCriticalOperation(() => readPresignedBody(url, out, deps, shutdown.signal));
11153
+ }
11154
+ async function readPresignedBody(url, out, deps, shutdownSignal) {
11155
+ if (shutdownSignal.aborted)
11156
+ throw shutdownSignal.reason;
9835
11157
  const fetchImpl = deps.fetchImpl ?? globalThis.fetch.bind(globalThis);
9836
11158
  let response;
9837
11159
  try {
9838
- response = await fetchImpl(url);
11160
+ response = await fetchImpl(url, { signal: shutdownSignal });
9839
11161
  }
9840
11162
  catch (err) {
11163
+ if (shutdownSignal.aborted)
11164
+ throw shutdownSignal.reason;
11165
+ if (err instanceof InterruptError)
11166
+ throw err;
9841
11167
  const message = err instanceof Error ? err.message : String(err);
9842
11168
  throw new TransportError(`Failed to download presigned code body: ${message}`);
9843
11169
  }
11170
+ if (shutdownSignal.aborted)
11171
+ throw shutdownSignal.reason;
9844
11172
  if (!response.ok) {
9845
11173
  throw ApiError.fromEnvelope({
9846
11174
  error: {
@@ -9855,7 +11183,16 @@ async function streamPresignedBody(url, out, deps) {
9855
11183
  if (!response.body) {
9856
11184
  // No streamable body (some test runtimes / fetch polyfills). Fall
9857
11185
  // back to text() — same correctness, just no streaming benefit.
9858
- await out.writeChunk(await response.text());
11186
+ try {
11187
+ await out.writeChunk(await response.text());
11188
+ if (shutdownSignal.aborted)
11189
+ throw shutdownSignal.reason;
11190
+ }
11191
+ catch (err) {
11192
+ if (shutdownSignal.aborted)
11193
+ throw shutdownSignal.reason;
11194
+ throw err;
11195
+ }
9859
11196
  return;
9860
11197
  }
9861
11198
  const reader = response.body.getReader();
@@ -9879,8 +11216,14 @@ async function streamPresignedBody(url, out, deps) {
9879
11216
  const tail = decoder.decode();
9880
11217
  if (tail.length > 0)
9881
11218
  await out.writeChunk(tail);
11219
+ if (shutdownSignal.aborted)
11220
+ throw shutdownSignal.reason;
9882
11221
  }
9883
11222
  catch (err) {
11223
+ if (shutdownSignal.aborted)
11224
+ throw shutdownSignal.reason;
11225
+ if (err instanceof InterruptError)
11226
+ throw err;
9884
11227
  const message = err instanceof Error ? err.message : String(err);
9885
11228
  throw new TransportError(`Failed mid-download of presigned code body: ${message}`);
9886
11229
  }
@@ -10333,7 +11676,7 @@ function createTestCodeCommand(deps) {
10333
11676
  .option('--out <path>', 'Write the response to this file instead of stdout (text mode: source body; json mode: wire envelope)')
10334
11677
  .addHelpText('after', GLOBAL_OPTS_HINT)
10335
11678
  .action(async (testId, cmdOpts, command) => {
10336
- await runCodeGet({ ...resolveCommonOptions(command), testId, out: cmdOpts.out }, deps);
11679
+ await runCodeGet({ ...resolveCommonOptions(command, deps.env), testId, out: cmdOpts.out }, deps);
10337
11680
  });
10338
11681
  code
10339
11682
  .command('put <test-id>')
@@ -10354,7 +11697,7 @@ function createTestCodeCommand(deps) {
10354
11697
  throw localValidationError('dry-run-simulate-error', `unsupported value "${simulateError}"; only PRECONDITION_FAILED is supported`, ['PRECONDITION_FAILED']);
10355
11698
  }
10356
11699
  await runCodePut({
10357
- ...resolveCommonOptions(command),
11700
+ ...resolveCommonOptions(command, deps.env),
10358
11701
  testId,
10359
11702
  codeFile: cmdOpts.codeFile,
10360
11703
  expectedVersion: cmdOpts.expectedVersion,
@@ -10367,7 +11710,7 @@ function createTestCodeCommand(deps) {
10367
11710
  return code;
10368
11711
  }
10369
11712
  // ---------------------------------------------------------------------------
10370
- // `test plan generate` / `test plan accept` — DEV-384 V3-B
11713
+ // `test plan generate` / `test plan accept`
10371
11714
  // ---------------------------------------------------------------------------
10372
11715
  /** Default `--timeout` for `test plan generate` (design-doc §3.1): a fresh
10373
11716
  * frontend project runs browser exploration, which takes minutes — the runs
@@ -10378,7 +11721,7 @@ const PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS = 1800;
10378
11721
  const PLAN_BASELINE_READ_TIMEOUT_MS = 10_000;
10379
11722
  /** `--project` is a flag (not a positional) on both plan-generation leaves —
10380
11723
  * route through the house helpers so `TESTSPRITE_PROJECT_ID` works here the
10381
- * same as on every other command (DEV-384 review F5). */
11724
+ * same as on every other command. */
10382
11725
  function requirePlanProjectId(projectId, deps) {
10383
11726
  const resolved = resolveProjectId(projectId, deps);
10384
11727
  requireProjectId(resolved);
@@ -10523,20 +11866,20 @@ function planCreditsUsed(plans) {
10523
11866
  }
10524
11867
  /**
10525
11868
  * THIS invocation's spend: the settled read's per-action charged totals minus
10526
- * the pre-trigger baseline's (DEV-935 / review F1 — the wire block is a
10527
- * LIFETIME project total, so printing its sum as "credits used" reported
10528
- * all-time spend on re-runs that charged nothing). `null` = unknown (no
10529
- * baseline snapshot, or either read lacks the best-effort block) — the
10530
- * caller omits the figure rather than printing a lifetime number.
11869
+ * the pre-trigger baseline's (the wire block is a LIFETIME project total, so
11870
+ * printing its sum as "credits used" reported all-time spend on re-runs that
11871
+ * charged nothing). `null` = unknown (no baseline snapshot, or either read
11872
+ * lacks the best-effort block) — the caller omits the figure rather than
11873
+ * printing a lifetime number.
10531
11874
  */
10532
11875
  function planCreditsDelta(baseline, settled) {
10533
11876
  if (baseline?.credits?.charged === undefined || settled.credits?.charged === undefined) {
10534
11877
  return null;
10535
11878
  }
10536
- // DEV-935: a facade-side billing failure degrades the block to
11879
+ // A facade-side billing failure degrades the block to
10537
11880
  // `{charged: [], balance: null}` — `charged` is DEFINED there, so without
10538
11881
  // this guard a degraded read makes the other read's lifetime totals print
10539
- // as this run's spend (the F1 misreport, back through the degrade window).
11882
+ // as this run's spend, back through the degrade window.
10540
11883
  // A healthy block always carries a numeric balance.
10541
11884
  if (baseline.credits.balance === null || settled.credits.balance === null) {
10542
11885
  return null;
@@ -10611,7 +11954,7 @@ export function renderPlanGenerateResultText(plans, projectId, creditsUsed, skip
10611
11954
  ' (or review visually in the Portal before accepting)',
10612
11955
  ].join('\n');
10613
11956
  }
10614
- /** DEV-1008 — one line when the proposals stage left strategy categories out
11957
+ /** One line when the proposals stage left strategy categories out
10615
11958
  * because they have no endpoint to attach a test to. The stage is charged
10616
11959
  * flat, so without this the caller cannot tell a partial plan from a full
10617
11960
  * one. Empty when nothing was skipped (the common case). */
@@ -10655,7 +11998,7 @@ function renderPlanGeneratePartialText(partial, reason) {
10655
11998
  return lines.join('\n');
10656
11999
  }
10657
12000
  /**
10658
- * `test plan generate --project <id>` — DEV-384 V3-B.
12001
+ * `test plan generate --project <id>`.
10659
12002
  *
10660
12003
  * Drives the server's generation ladder (exploration → strategy →
10661
12004
  * proposals) through `runGenerationLadder` and renders the staged
@@ -10700,7 +12043,7 @@ export async function runPlanGenerate(opts, deps = {}) {
10700
12043
  }, deps);
10701
12044
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
10702
12045
  // Upgraded to the server-resolved V3 id by the first ACCEPTED trigger
10703
- // response. KNOWN LIMITATION (DEV-384 review F8): when the very first
12046
+ // response. KNOWN LIMITATION: when the very first
10704
12047
  // trigger 409-attaches, no trigger response ever arrives and neither the
10705
12048
  // 409 envelope nor the `GET /plans` read carries the resolved id, so the
10706
12049
  // output keeps the caller's input id (a V2 id still polls fine through the
@@ -10708,13 +12051,13 @@ export async function runPlanGenerate(opts, deps = {}) {
10708
12051
  let resolvedProjectId = projectId;
10709
12052
  let lastSeen = null;
10710
12053
  try {
10711
- // Pre-trigger baseline snapshot (review F1 / DEV-935): one plain GET
10712
- // BEFORE any POST, so the settled read's lifetime `credits.charged`
10713
- // block can be diffed into "what THIS invocation spent" (the first
10714
- // stage's charge lands before the ladder's own first read, so first
10715
- // in-ladder read vs last would undercount). Best-effort: a failure only
10716
- // costs the credits line, never the command. Bounded by its own short
10717
- // signal — without it the read inherits the D4-raised per-request window
12054
+ // Pre-trigger baseline snapshot: one plain GET BEFORE any POST, so the
12055
+ // settled read's lifetime `credits.charged` block can be diffed into
12056
+ // "what THIS invocation spent" (the first stage's charge lands before
12057
+ // the ladder's own first read, so first in-ladder read vs last would
12058
+ // undercount). Best-effort: a failure only costs the credits line, never
12059
+ // the command. Bounded by its own short signal — without it the read
12060
+ // inherits the per-request window this function already raised above
10718
12061
  // (up to 600s under --wait semantics), all outside the --timeout budget.
10719
12062
  let baselinePlans = null;
10720
12063
  try {
@@ -10814,13 +12157,13 @@ export async function runPlanGenerate(opts, deps = {}) {
10814
12157
  const count = plans.proposals.length;
10815
12158
  ticker.finalize(`${count} ${count === 1 ? 'proposal' : 'proposals'} staged`);
10816
12159
  // This invocation's spend (settled − baseline; null = unknown) — the
10817
- // wire block alone is a lifetime total (DEV-935 / review F1).
12160
+ // wire block alone is a lifetime total.
10818
12161
  const creditsUsed = planCreditsDelta(baselinePlans, plans);
10819
12162
  const skippedCategories = result.skippedCategories;
10820
12163
  const payload = {
10821
12164
  projectId: resolvedProjectId,
10822
12165
  creditsUsedThisInvocation: creditsUsed,
10823
- // DEV-1008: present only when the proposals stage skipped endpoint-less
12166
+ // Present only when the proposals stage skipped endpoint-less
10824
12167
  // categories, so every other JSON payload is byte-identical.
10825
12168
  ...(skippedCategories !== null ? { skippedCategories } : {}),
10826
12169
  ...plans,
@@ -10866,8 +12209,8 @@ export async function runPlanGenerate(opts, deps = {}) {
10866
12209
  throw err;
10867
12210
  }
10868
12211
  if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
10869
- // Same partial-envelope family as the timeout/interrupt branches
10870
- // (DEV-384 review): a redirected stdout file must never be 0-byte.
12212
+ // Same partial-envelope family as the timeout/interrupt branches:
12213
+ // a redirected stdout file must never be 0-byte.
10871
12214
  // The original ApiError is rethrown unchanged so exit stays 11.
10872
12215
  ticker.finalize('rate limited by the server');
10873
12216
  const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
@@ -10879,7 +12222,7 @@ export async function runPlanGenerate(opts, deps = {}) {
10879
12222
  if (err instanceof ApiError &&
10880
12223
  err.code === 'INTERNAL' &&
10881
12224
  typeof err.details?.acceptedPosts === 'number') {
10882
- // The ladder's cap-exhaustion "appears stuck" fuse (DEV-384 review F7)
12225
+ // The ladder's cap-exhaustion "appears stuck" fuse
10883
12226
  // joins the partial-envelope family too — it is a terminal outcome of a
10884
12227
  // long wait, exactly like the branches above, so redirected stdout must
10885
12228
  // carry the partial. Keyed on the fuse's own `acceptedPosts` detail so
@@ -10930,7 +12273,7 @@ function selectPlanProposals(staged, onlyIds) {
10930
12273
  return onlyIds.map(id => byId.get(id));
10931
12274
  }
10932
12275
  /**
10933
- * `test plan accept --project <id> [--only <ids...>]` — DEV-384 V3-B.
12276
+ * `test plan accept --project <id> [--only <ids...>]`.
10934
12277
  *
10935
12278
  * Reads the staged batch, selects all of it (or the `--only` subset),
10936
12279
  * and POSTs an EXPLICIT id list. Free — the generation charge already
@@ -11022,7 +12365,7 @@ function createTestPlanCommand(deps) {
11022
12365
  throw localValidationError('dry-run-simulate-error', `unsupported value "${simulateError}"; only PRECONDITION_FAILED is supported`, ['PRECONDITION_FAILED']);
11023
12366
  }
11024
12367
  await runPlanPut({
11025
- ...resolveCommonOptions(command),
12368
+ ...resolveCommonOptions(command, deps.env),
11026
12369
  testId,
11027
12370
  stepsFile: cmdOpts.steps,
11028
12371
  expectedStepCount: parseNumericFlag(cmdOpts.expectedStepCount, 'expected-step-count'),
@@ -11054,7 +12397,7 @@ function createTestPlanCommand(deps) {
11054
12397
  GLOBAL_OPTS_HINT)
11055
12398
  .action(async (cmdOpts, command) => {
11056
12399
  await runPlanGenerate({
11057
- ...resolveCommonOptions(command),
12400
+ ...resolveCommonOptions(command, deps.env),
11058
12401
  projectId: cmdOpts.project,
11059
12402
  timeoutSeconds: cmdOpts.timeout === undefined
11060
12403
  ? PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS
@@ -11080,7 +12423,7 @@ function createTestPlanCommand(deps) {
11080
12423
  GLOBAL_OPTS_HINT)
11081
12424
  .action(async (cmdOpts, command) => {
11082
12425
  await runPlanAccept({
11083
- ...resolveCommonOptions(command),
12426
+ ...resolveCommonOptions(command, deps.env),
11084
12427
  projectId: cmdOpts.project,
11085
12428
  only: cmdOpts.only,
11086
12429
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -11089,10 +12432,10 @@ function createTestPlanCommand(deps) {
11089
12432
  return plan;
11090
12433
  }
11091
12434
  export function createTestArtifactCommand(deps) {
11092
- const artifact = new Command('artifact').description('Download run-scoped artifact bundles (M3.3 piece-4)');
12435
+ const artifact = new Command('artifact').description('Download run-scoped artifact bundles');
11093
12436
  artifact
11094
12437
  // `isDefault: true` makes `test artifact <run-id>` a pass-through alias for
11095
- // `test artifact get <run-id>` (DEV-230 grammar consistency — bare-noun reads
12438
+ // `test artifact get <run-id>` (grammar consistency — bare-noun reads
11096
12439
  // mirror the flat `test result/steps/get <id>` forms). Run-id semantics are
11097
12440
  // preserved: the positional is still a run-id, not a test-id.
11098
12441
  .command('get <run-id>', { isDefault: true })
@@ -11118,7 +12461,7 @@ export function createTestArtifactCommand(deps) {
11118
12461
  .addHelpText('after', GLOBAL_OPTS_HINT)
11119
12462
  .action(async (runId, cmdOpts, command) => {
11120
12463
  await runArtifactGet({
11121
- ...resolveCommonOptions(command),
12464
+ ...resolveCommonOptions(command, deps.env),
11122
12465
  runId,
11123
12466
  out: cmdOpts.out,
11124
12467
  failedOnly: Boolean(cmdOpts.failedOnly),
@@ -11130,7 +12473,7 @@ function createTestFailureCommand(deps) {
11130
12473
  const failure = new Command('failure').description('Export the latest-failure agent bundle');
11131
12474
  failure
11132
12475
  // `isDefault: true` makes `test failure <test-id>` a pass-through alias for
11133
- // `test failure get <test-id>` (DEV-230 grammar consistency). `failure summary`
12476
+ // `test failure get <test-id>` (grammar consistency). `failure summary`
11134
12477
  // still routes explicitly; only the bare-noun form falls through to `get`.
11135
12478
  .command('get <test-id>', { isDefault: true })
11136
12479
  .description("Write a self-contained failure-context bundle for a test's latest failing run")
@@ -11140,7 +12483,7 @@ function createTestFailureCommand(deps) {
11140
12483
  .addHelpText('after', GLOBAL_OPTS_HINT)
11141
12484
  .action(async (testId, cmdOpts, command) => {
11142
12485
  await runFailureGet({
11143
- ...resolveCommonOptions(command),
12486
+ ...resolveCommonOptions(command, deps.env),
11144
12487
  testId,
11145
12488
  out: cmdOpts.out,
11146
12489
  failedOnly: Boolean(cmdOpts.failedOnly),
@@ -11148,10 +12491,10 @@ function createTestFailureCommand(deps) {
11148
12491
  });
11149
12492
  failure
11150
12493
  .command('summary <test-id>')
11151
- .description('Print a one-screen summary of the latest failing run (status, failureKind, hypothesis, fix target — M2.1)')
12494
+ .description('Print a one-screen summary of the latest failing run (status, failureKind, hypothesis, fix target)')
11152
12495
  .addHelpText('after', GLOBAL_OPTS_HINT)
11153
12496
  .action(async (testId, _cmdOpts, command) => {
11154
- await runFailureSummary({ ...resolveCommonOptions(command), testId }, deps);
12497
+ await runFailureSummary({ ...resolveCommonOptions(command, deps.env), testId }, deps);
11155
12498
  });
11156
12499
  return failure;
11157
12500
  }