@testsprite/testsprite-cli 0.11.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 (99) hide show
  1. package/README.md +52 -44
  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 +470 -9
  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.d.ts +90 -0
  11. package/dist/commands/project-env.js +486 -0
  12. package/dist/commands/project.d.ts +15 -5
  13. package/dist/commands/project.js +88 -92
  14. package/dist/commands/schedule.d.ts +2 -0
  15. package/dist/commands/schedule.js +18 -10
  16. package/dist/commands/test.d.ts +102 -30
  17. package/dist/commands/test.js +1949 -419
  18. package/dist/commands/testlist.js +77 -21
  19. package/dist/commands/tunnel.d.ts +26 -3
  20. package/dist/commands/tunnel.js +211 -14
  21. package/dist/commands/usage.d.ts +3 -0
  22. package/dist/commands/usage.js +12 -5
  23. package/dist/index.js +47 -23
  24. package/dist/lib/agent-targets.d.ts +3 -3
  25. package/dist/lib/agent-targets.js +2 -2
  26. package/dist/lib/billing-refusal.d.ts +43 -0
  27. package/dist/lib/billing-refusal.js +171 -0
  28. package/dist/lib/bundle.d.ts +5 -0
  29. package/dist/lib/bundle.js +43 -13
  30. package/dist/lib/ci-linkage.d.ts +90 -0
  31. package/dist/lib/ci-linkage.js +181 -0
  32. package/dist/lib/client-factory.d.ts +4 -1
  33. package/dist/lib/client-factory.js +25 -2
  34. package/dist/lib/client-tag.d.ts +13 -0
  35. package/dist/lib/client-tag.js +44 -0
  36. package/dist/lib/config.d.ts +17 -0
  37. package/dist/lib/config.js +20 -1
  38. package/dist/lib/conflict-reason.d.ts +67 -2
  39. package/dist/lib/conflict-reason.js +148 -13
  40. package/dist/lib/credentials.js +56 -14
  41. package/dist/lib/cron.js +8 -1
  42. package/dist/lib/dry-run/samples.d.ts +13 -1
  43. package/dist/lib/dry-run/samples.js +51 -7
  44. package/dist/lib/errors.d.ts +62 -12
  45. package/dist/lib/errors.js +180 -25
  46. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  47. package/dist/lib/failing-fe-resolver.js +3 -3
  48. package/dist/lib/gh-output.d.ts +26 -11
  49. package/dist/lib/gh-output.js +47 -15
  50. package/dist/lib/history-retention.d.ts +8 -0
  51. package/dist/lib/history-retention.js +24 -0
  52. package/dist/lib/http.d.ts +44 -19
  53. package/dist/lib/http.js +53 -26
  54. package/dist/lib/interrupt.d.ts +21 -13
  55. package/dist/lib/interrupt.js +32 -21
  56. package/dist/lib/junit-report.d.ts +11 -1
  57. package/dist/lib/junit-report.js +15 -3
  58. package/dist/lib/local-target.d.ts +33 -1
  59. package/dist/lib/local-target.js +78 -1
  60. package/dist/lib/output.d.ts +27 -1
  61. package/dist/lib/output.js +22 -3
  62. package/dist/lib/plan-poll.d.ts +11 -11
  63. package/dist/lib/plan-poll.js +12 -12
  64. package/dist/lib/plans.types.d.ts +9 -9
  65. package/dist/lib/plans.types.js +3 -3
  66. package/dist/lib/poll.d.ts +2 -2
  67. package/dist/lib/poll.js +9 -3
  68. package/dist/lib/render-error.d.ts +2 -0
  69. package/dist/lib/render-error.js +13 -0
  70. package/dist/lib/response-schemas.d.ts +54 -12
  71. package/dist/lib/response-schemas.js +106 -7
  72. package/dist/lib/runs.types.d.ts +92 -6
  73. package/dist/lib/secret-file.js +72 -14
  74. package/dist/lib/skill-nudge.d.ts +6 -1
  75. package/dist/lib/skill-nudge.js +32 -5
  76. package/dist/lib/target-url-preflight.d.ts +6 -4
  77. package/dist/lib/target-url-preflight.js +64 -51
  78. package/dist/lib/target-url.js +31 -12
  79. package/dist/lib/telemetry.d.ts +172 -3
  80. package/dist/lib/telemetry.js +276 -15
  81. package/dist/lib/ticker.js +93 -4
  82. package/dist/lib/tunnel-session.d.ts +13 -0
  83. package/dist/lib/tunnel-session.js +4 -1
  84. package/dist/lib/tunnel.types.d.ts +12 -2
  85. package/dist/lib/tunnel.types.js +2 -2
  86. package/dist/lib/version-notice.d.ts +20 -1
  87. package/dist/lib/version-notice.js +59 -12
  88. package/dist/lib/wait-exit.d.ts +8 -0
  89. package/dist/lib/wait-exit.js +76 -4
  90. package/dist/lib/workspace-status.d.ts +23 -0
  91. package/dist/lib/workspace-status.js +15 -0
  92. package/dist/version-guard.d.ts +7 -1
  93. package/dist/version-guard.js +19 -1
  94. package/dist/version.d.ts +1 -1
  95. package/dist/version.js +1 -1
  96. package/package.json +4 -4
  97. package/skills/testsprite-onboard.skill.md +4 -4
  98. package/skills/testsprite-verify.codex.md +59 -57
  99. package/skills/testsprite-verify.skill.md +53 -36
@@ -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,19 +7,22 @@ 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';
16
17
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
17
18
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
18
19
  import { isTerminalStatus, pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
20
+ import { batchOutcomeCounts, recordBatchOutcome, recordTelemetryExtras, } from '../lib/telemetry.js';
19
21
  import { PlanGenerationTimeoutError, runGenerationLadder } from '../lib/plan-poll.js';
20
- import { resolveWaitFailure } from '../lib/wait-exit.js';
22
+ import { resolveWaitFailure, waitMemberError } from '../lib/wait-exit.js';
21
23
  import { RUN_SOURCES } from '../lib/runs.types.js';
22
- import { 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';
23
26
  import { isProxyAgentActive } from '../lib/proxy.js';
24
27
  import { assertNotLocal } from '../lib/target-url.js';
25
28
  import { assertTargetUrlReachable } from '../lib/target-url-preflight.js';
@@ -32,18 +35,19 @@ import { createTicker } from '../lib/ticker.js';
32
35
  import { RateThrottle } from '../lib/rate-throttle.js';
33
36
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
34
37
  import { emitTargetUrlMismatchAdvisory } from '../lib/v3-advisory.js';
35
- import { emitCiArtifacts, summarizeAcceptedPayload, summarizeSingleRun, } from '../lib/gh-output.js';
36
- 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';
37
41
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
38
- /** The effective shutdown handle for a command invocation (DEV-331). */
42
+ /** The effective shutdown handle for a command invocation. */
39
43
  function shutdownOf(deps) {
40
44
  return deps.shutdown ?? globalShutdown;
41
45
  }
42
46
  /**
43
- * The honest-detach stderr line (DEV-331 D1 — the heart of the ticket):
44
- * a Ctrl-C detaches the local wait only; the server-side run keeps executing
45
- * AND billing. Names both re-attach (`test wait`) and the real cancel
46
- * (`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.
47
51
  */
48
52
  function interruptDetachMessage(err, runIds) {
49
53
  const subject = runIds.length === 1
@@ -147,12 +151,12 @@ function makeBorrowedTunnelLivenessCheck(args) {
147
151
  * Stop a tunnel run that can no longer succeed.
148
152
  *
149
153
  * Called on every path where this process stops waiting while the run is
150
- * non-terminal. Unlike an ordinary run — where DEV-331 deliberately decided a
151
- * Ctrl-C detaches and leaves the run to finish — a tunnel run's target lives
152
- * behind a tunnel this process is holding open, so the moment we exit the
153
- * Lambda's browser can start getting connection failures. The run may already
154
- * have completed or been billed, so the cancellation message states only the
155
- * 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.
156
160
  *
157
161
  * The cancel is issued through a DETACHED client: the normal one composes the
158
162
  * process shutdown signal into every fetch, and on the interrupt path that
@@ -333,13 +337,9 @@ function resolveApiUrl(opts, deps = {}) {
333
337
  return config.apiUrl;
334
338
  }
335
339
  export async function runList(opts, deps = {}) {
336
- // Validate inputs before touching credentials so a missing `--project`
337
- // surfaces as `VALIDATION_ERROR` (exit 5) rather than `AUTH_REQUIRED`
338
- // (exit 3) when the caller also lacks a configured key. Order matters
339
- // for the CLI error spec §2 — bad input is a caller bug, not an auth
340
- // 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.
341
342
  const projectId = resolveProjectId(opts.projectId, deps);
342
- requireProjectId(projectId);
343
343
  const paginationFlags = validatePaginationFlags({
344
344
  pageSize: opts.pageSize,
345
345
  startingToken: opts.startingToken,
@@ -355,6 +355,7 @@ export async function runList(opts, deps = {}) {
355
355
  resolveTextColumns(opts.columns, TEST_LIST_COLUMNS);
356
356
  }
357
357
  const client = makeClient(opts, deps);
358
+ requireProjectId(projectId);
358
359
  // Match P2's "explicit pageSize ⇒ single-page" convention so an
359
360
  // operator can grab one slice + cursor without auto-paging through a
360
361
  // huge project.
@@ -421,7 +422,7 @@ const DUP_NAME_ADVISORY_TIMEOUT_MS = 5_000;
421
422
  async function emitDupNameAdvisoryIfNeeded(client, projectId, name, stderrFn) {
422
423
  if (!projectId || !name)
423
424
  return;
424
- // B: the advisory lookup must NEVER block the create critical path.
425
+ // B: ordinary advisory failures must not block the create critical path.
425
426
  // Use an AbortController with a 5 s deadline. When the timer fires it
426
427
  // calls ac.abort(), which causes client.get (via the `signal` option) to
427
428
  // throw an AbortError — caught below and swallowed. This ensures a stalled
@@ -450,8 +451,10 @@ async function emitDupNameAdvisoryIfNeeded(client, projectId, name, stderrFn) {
450
451
  `Use \`testsprite test update ${match.id}\` to modify it, or proceed to create a duplicate.`);
451
452
  }
452
453
  }
453
- catch {
454
- // 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.
455
458
  }
456
459
  finally {
457
460
  clearTimeout(timer);
@@ -476,6 +479,10 @@ async function emitDupNameAdvisoryIfNeeded(client, projectId, name, stderrFn) {
476
479
  * convention; no separate "envelope-only" output mode.
477
480
  */
478
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);
479
486
  // P1-2: validate idempotency key before any I/O — non-ASCII chars cause a
480
487
  // ByteString TypeError at the HTTP transport layer (exit 10 UNAVAILABLE).
481
488
  assertIdempotencyKey(opts.idempotencyKey);
@@ -617,7 +624,12 @@ export async function runCreate(opts, deps = {}) {
617
624
  opts.run === true &&
618
625
  !opts.dryRun) {
619
626
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
620
- 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);
621
633
  }
622
634
  const client = makeClient(opts, deps);
623
635
  const out = makeOutput(opts.output, deps);
@@ -643,11 +655,11 @@ export async function runCreate(opts, deps = {}) {
643
655
  // `--output json` stays parseable for agents and scripts.
644
656
  if (opts.run === true) {
645
657
  const runIdempotencyKey = `${idempotencyKey}:run`;
646
- // R3a: compute dashboardUrl before the early return so it flows into
647
- // the merged { ...createContext, run } envelope in JSON mode and
648
- // appears on the Dashboard: stderr line in text mode.
649
- // R1: suppress under --dry-run (fake canned test id).
650
- // 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
651
663
  // (`withDashboardUrl`/`resolveDashboardUrl` above); when the server
652
664
  // explicitly withheld one, never fall back to the client-computed
653
665
  // V2-shaped link and tell the caller where to find the test instead.
@@ -694,11 +706,11 @@ export async function runCreate(opts, deps = {}) {
694
706
  }, deps);
695
707
  return response;
696
708
  }
697
- // Fix 5: emit dashboard deep-link when projectId + testId are known client-side
698
- // (no extra network call — both come from opts / response).
699
- // R1: suppress under --dry-run — the test id is a fake canned value
700
- // (e.g. "test_dryrun_create_2026") and a live-looking URL would mislead.
701
- // 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;
702
714
  // never fall back when the server explicitly withheld one (see
703
715
  // `withDashboardUrl`/`resolveDashboardUrl` above), and tell the caller
704
716
  // where to find the test instead of printing a link that would 404.
@@ -927,16 +939,15 @@ function renderPlanPutText(response) {
927
939
  * array on success; throws a typed `VALIDATION_ERROR` envelope on any
928
940
  * schema problem with a `details.field` pointer the caller can act on.
929
941
  *
930
- * Stat-first guard mirrors piece-2's `readCodeFileGuarded`: oversize
931
- * payloads fail before we load them into V8's heap. The cap here is
932
- * 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).
933
944
  */
934
945
  function readPlanStepsFileGuarded(path) {
935
946
  return assertPlanStepsShape(parsePlanStepsFile(path));
936
947
  }
937
948
  /**
938
949
  * File I/O + JSON.parse half of `readPlanStepsFileGuarded`, split out so
939
- * `test lint` can reuse the SAME stat/size/read/parse guards while
950
+ * `test lint` can reuse the SAME open/size/read guards while
940
951
  * substituting the collect-all `collectPlanStepsIssues` shape check for the
941
952
  * throw-on-first `assertPlanStepsShape` that `test plan put` still uses. A
942
953
  * failure here (missing file, oversize, invalid JSON syntax) is always a
@@ -944,52 +955,158 @@ function readPlanStepsFileGuarded(path) {
944
955
  * file itself can't be read or parsed.
945
956
  */
946
957
  function parsePlanStepsFile(path) {
947
- const absolute = resolveAbsolute(path);
948
- let stat;
949
- try {
950
- stat = statSync(absolute);
951
- }
952
- catch (err) {
953
- const code = err.code;
954
- if (code === 'ENOENT') {
955
- throw localValidationError('steps', `file does not exist: ${path}`);
956
- }
957
- if (code === 'EACCES') {
958
- throw localValidationError('steps', `permission denied reading ${path}`);
959
- }
960
- const reason = err instanceof Error ? err.message : 'unknown error';
961
- throw localValidationError('steps', `cannot stat ${path}: ${reason}`);
962
- }
963
- if (stat.size > MAX_PLAN_STEPS_BODY_BYTES) {
958
+ const result = readCappedFileGuarded('steps', path, MAX_PLAN_STEPS_BODY_BYTES);
959
+ if (!result.ok) {
964
960
  throw ApiError.fromEnvelope({
965
961
  error: {
966
962
  code: 'PAYLOAD_TOO_LARGE',
967
- 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).`,
968
964
  nextAction: 'Split into multiple smaller tests or trim step descriptions.',
969
965
  requestId: 'local',
970
966
  details: {
971
967
  field: 'steps',
972
- sizeBytes: stat.size,
968
+ sizeBytes: result.sizeBytes,
973
969
  maxBytes: MAX_PLAN_STEPS_BODY_BYTES,
974
970
  },
975
971
  },
976
972
  });
977
973
  }
978
- let raw;
979
974
  try {
980
- raw = stripBom(readFileSync(absolute, 'utf8'));
975
+ return JSON.parse(result.raw);
981
976
  }
982
977
  catch (err) {
983
978
  const reason = err instanceof Error ? err.message : 'unknown error';
984
- throw localValidationError('steps', `cannot read ${path}: ${reason}`);
979
+ throw localValidationError('steps', `not valid JSON: ${reason}`);
985
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;
986
1010
  try {
987
- 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');
988
1013
  }
989
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
+ }
990
1059
  const reason = err instanceof Error ? err.message : 'unknown error';
991
- 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;
992
1108
  }
1109
+ return Buffer.concat(chunks, total);
993
1110
  }
994
1111
  /**
995
1112
  * Type-narrow + validate a parsed `{ planSteps: [...] }` envelope.
@@ -1357,6 +1474,8 @@ export async function runDeleteBatch(opts, deps = {}) {
1357
1474
  });
1358
1475
  }
1359
1476
  catch (err) {
1477
+ if (err instanceof InterruptError)
1478
+ throw err;
1360
1479
  // 404 = already deleted / not found. Surface as 'skipped' so the
1361
1480
  // summary count is accurate and the exit code stays 0.
1362
1481
  if (err instanceof ApiError && err.code === 'NOT_FOUND') {
@@ -1491,16 +1610,6 @@ const MAX_BATCH_BODY_BYTES = 5 * 1024 * 1024;
1491
1610
  * than this, the CLI splits into chunks and aggregates the results.
1492
1611
  */
1493
1612
  const MAX_BATCH_RERUN_IDS = 50;
1494
- /**
1495
- * Drop duplicate `testId` entries from a chunked batch-rerun's aggregated
1496
- * `accepted[]`, keeping the first occurrence. BE producer/teardown closure
1497
- * dedup happens per-request server-side, not across the separate requests
1498
- * one chunk per `MAX_BATCH_RERUN_IDS` window produces, so the same producer
1499
- * can come back accepted (with a different runId) from more than one
1500
- * chunk. Returns the deduped list plus how many entries were dropped, so
1501
- * the caller can warn the operator that a shared BE producer/teardown was
1502
- * triggered more than once.
1503
- */
1504
1613
  /**
1505
1614
  * Dedupe `RerunAdvisory[]` by `feature`+`message`. Used to aggregate
1506
1615
  * `advisories` across chunked batch-rerun dispatch requests (initial dispatch
@@ -1528,17 +1637,62 @@ function emitRerunAdvisories(stderrFn, advisories) {
1528
1637
  stderrFn(`[advisory] ${advisory.message}`);
1529
1638
  }
1530
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
+ */
1531
1649
  function dedupeBatchRerunAccepted(entries) {
1532
1650
  const seen = new Map();
1533
- let droppedCount = 0;
1651
+ const dropped = [];
1534
1652
  for (const entry of entries) {
1535
1653
  if (seen.has(entry.testId)) {
1536
- droppedCount++;
1654
+ dropped.push(entry);
1537
1655
  continue;
1538
1656
  }
1539
1657
  seen.set(entry.testId, entry);
1540
1658
  }
1541
- 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>`);
1542
1696
  }
1543
1697
  /**
1544
1698
  * Merge per-project closure summaries from multiple batch-rerun chunk
@@ -1591,6 +1745,22 @@ function mergeBatchRerunClosureByProject(entries) {
1591
1745
  export const DEFAULT_BATCH_RUN_CONCURRENCY = 50;
1592
1746
  /** Hard upper bound for --max-concurrency. Values above this are rejected with exit 5 (VALIDATION_ERROR). */
1593
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;
1594
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). */
1595
1765
  export const BATCH_RUN_RATE_LIMIT = 50;
1596
1766
  /** Rolling window duration (ms) for the client-side trigger rate throttle. */
@@ -1621,12 +1791,10 @@ export const WAIT_POLL_RATE_MAX_OUTER_RETRIES = 3;
1621
1791
  */
1622
1792
  /**
1623
1793
  * Sleep that a termination signal cuts short by rejecting with the signal's
1624
- * `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.
1625
1795
  *
1626
1796
  * Mirrors `HttpClient.sleepBeforeRetry` — an in-flight backoff must not be a
1627
- * window where a first Ctrl-C hard-exits with empty stdout. The caller is
1628
- * responsible for having ARMED the shutdown scope; a disarmed controller never
1629
- * 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.
1630
1798
  */
1631
1799
  export function sleepUntilOrInterrupt(ms, signal, sleep) {
1632
1800
  if (signal === undefined)
@@ -1634,9 +1802,12 @@ export function sleepUntilOrInterrupt(ms, signal, sleep) {
1634
1802
  if (signal.aborted)
1635
1803
  return Promise.reject(signal.reason);
1636
1804
  return new Promise((resolve, reject) => {
1637
- const onAbort = () => reject(signal.reason);
1805
+ const onAbort = () => {
1806
+ signal.removeEventListener('abort', onAbort);
1807
+ reject(signal.reason);
1808
+ };
1638
1809
  signal.addEventListener('abort', onAbort, { once: true });
1639
- sleep(ms).then(() => {
1810
+ sleep(ms, signal).then(() => {
1640
1811
  signal.removeEventListener('abort', onAbort);
1641
1812
  resolve();
1642
1813
  }, err => {
@@ -1776,6 +1947,10 @@ function emitPlaceholderAdvisory(plan, stderrFn) {
1776
1947
  * when M3.3 lands.
1777
1948
  */
1778
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);
1779
1954
  assertIdempotencyKey(opts.idempotencyKey);
1780
1955
  // codex #128 P2: validate the derived `<key>:run` chain key before the
1781
1956
  // create POST (see runCreate) so a near-limit base key fails fast instead
@@ -1838,7 +2013,12 @@ export async function runCreateFromPlan(opts, deps = {}) {
1838
2013
  // `runTestRun` call in the --run chain below sets `skipPreflight: true`
1839
2014
  // so this exact URL is never probed twice.
1840
2015
  if (opts.targetUrl !== undefined && opts.run === true && !opts.dryRun) {
1841
- 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);
1842
2022
  }
1843
2023
  const client = makeClient(opts, deps);
1844
2024
  const out = makeOutput(opts.output, deps);
@@ -1852,10 +2032,10 @@ export async function runCreateFromPlan(opts, deps = {}) {
1852
2032
  body,
1853
2033
  headers: { 'idempotency-key': idempotencyKey },
1854
2034
  });
1855
- // Fix 5 (plan-from coverage): the projectId for the deep-link comes from
1856
- // 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
1857
2037
  // flag). Same dry-run suppression as runCreate (fake canned test id).
1858
- // DEV-737: prefer a server-provided dashboardUrl over the client guess
2038
+ // Prefer a server-provided dashboardUrl over the client guess
1859
2039
  // (`withDashboardUrl`/`resolveDashboardUrl`, defined near
1860
2040
  // `withRunDashboardUrl`); never fall back when the server explicitly
1861
2041
  // withheld one, and tell the caller where to find the test instead.
@@ -1907,68 +2087,40 @@ export async function runCreateFromPlan(opts, deps = {}) {
1907
2087
  * on success, throws a typed `VALIDATION_ERROR` envelope on any
1908
2088
  * schema problem (missing fields, wrong types, oversize body, etc.).
1909
2089
  *
1910
- * Stat-first guard mirrors piece-2's `readCodeFileGuarded` — reject
1911
- * obvious oversize files BEFORE loading them into V8's heap. For
1912
- * 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).
1913
2092
  */
1914
2093
  function readPlanFromGuarded(path, context = {}) {
1915
2094
  return assertPlanShape(parsePlanFile(path), context);
1916
2095
  }
1917
2096
  /**
1918
2097
  * File I/O + JSON.parse half of `readPlanFromGuarded`, split out so `test
1919
- * lint` can reuse the SAME stat/size/read/parse guards while
2098
+ * lint` can reuse the SAME open/size/read guards while
1920
2099
  * substituting the collect-all `collectPlanIssues` shape check for the
1921
2100
  * throw-on-first `assertPlanShape` that `create`/`create-batch` still use. A
1922
2101
  * failure here (missing file, oversize, invalid JSON syntax) is always a
1923
2102
  * single fatal issue either way — there is nothing left to validate once the
1924
2103
  * file itself can't be read or parsed.
1925
- *
1926
- * Stat-first guard mirrors piece-2's `readCodeFileGuarded` — reject
1927
- * obvious oversize files BEFORE loading them into V8's heap. For
1928
- * plans the cap is 256 KB (vs. 350 KB for code).
1929
2104
  */
1930
2105
  function parsePlanFile(path) {
1931
- const absolute = resolveAbsolute(path);
1932
- let stat;
1933
- try {
1934
- stat = statSync(absolute);
1935
- }
1936
- catch (err) {
1937
- const code = err.code;
1938
- if (code === 'ENOENT') {
1939
- throw localValidationError('plan-from', `file does not exist: ${path}`);
1940
- }
1941
- if (code === 'EACCES') {
1942
- throw localValidationError('plan-from', `permission denied reading ${path}`);
1943
- }
1944
- const reason = err instanceof Error ? err.message : 'unknown error';
1945
- throw localValidationError('plan-from', `cannot stat ${path}: ${reason}`);
1946
- }
1947
- if (stat.size > MAX_PLAN_BODY_BYTES) {
2106
+ const result = readCappedFileGuarded('plan-from', path, MAX_PLAN_BODY_BYTES);
2107
+ if (!result.ok) {
1948
2108
  throw ApiError.fromEnvelope({
1949
2109
  error: {
1950
2110
  code: 'PAYLOAD_TOO_LARGE',
1951
- 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).`,
1952
2112
  nextAction: 'Split into multiple smaller tests or trim step descriptions.',
1953
2113
  requestId: 'local',
1954
2114
  details: {
1955
2115
  field: 'plan-from',
1956
- sizeBytes: stat.size,
2116
+ sizeBytes: result.sizeBytes,
1957
2117
  maxBytes: MAX_PLAN_BODY_BYTES,
1958
2118
  },
1959
2119
  },
1960
2120
  });
1961
2121
  }
1962
- let raw;
1963
- try {
1964
- raw = stripBom(readFileSync(absolute, 'utf8'));
1965
- }
1966
- catch (err) {
1967
- const reason = err instanceof Error ? err.message : 'unknown error';
1968
- throw localValidationError('plan-from', `cannot read ${path}: ${reason}`);
1969
- }
1970
2122
  try {
1971
- return JSON.parse(raw);
2123
+ return JSON.parse(result.raw);
1972
2124
  }
1973
2125
  catch (err) {
1974
2126
  const reason = err instanceof Error ? err.message : 'unknown error';
@@ -2168,6 +2320,10 @@ function collectPlanIssues(parsed, context = {}) {
2168
2320
  * falls back to 1 for mixed outcomes.
2169
2321
  */
2170
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);
2171
2327
  assertIdempotencyKey(opts.idempotencyKey);
2172
2328
  // Exactly one of --plans or --plan-from-dir is required.
2173
2329
  if (opts.planFromDir !== undefined && opts.plans !== undefined && opts.plans !== '') {
@@ -2283,12 +2439,12 @@ export async function runCreateBatch(opts, deps = {}) {
2283
2439
  },
2284
2440
  });
2285
2441
  }
2286
- // Fix 5: enrich results with per-item dashboardUrl.
2287
- // projectId comes from specs[specIndex].projectId; testId from the result row.
2288
- // Only emitted where both are known client-side — no extra network calls.
2289
- // R1: suppress under --dry-run — test ids are fake canned values and a
2290
- // live-looking URL would mislead the caller.
2291
- // 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
2292
2448
  // guess (`withDashboardUrl`/`resolveDashboardUrl`, defined near
2293
2449
  // `withRunDashboardUrl`); never fall back when the server explicitly
2294
2450
  // withheld one for a given item — that would print exactly the dead
@@ -2438,10 +2594,17 @@ testIdToDashboardState) {
2438
2594
  // it never reaches this fan-out at all — see the `beIndexes` warning in
2439
2595
  // `runCreateBatch`).
2440
2596
  if (opts.targetUrl !== undefined) {
2441
- 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);
2442
2603
  }
2443
2604
  const batchRunResults = [];
2444
- 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);
2445
2608
  // Response-driven --target-url advisory, fired at most ONCE for the whole
2446
2609
  // batch (Finding 2's contract) the first time any member's trigger
2447
2610
  // response reports a target different from what was requested — see the
@@ -2469,11 +2632,11 @@ testIdToDashboardState) {
2469
2632
  * Returns a CliBatchRunResult. Never throws — errors are captured
2470
2633
  * into the result's `error` field so one failure doesn't abort siblings.
2471
2634
  * (Exception: InterruptError rethrows so the collect point can print the
2472
- * partial — DEV-331.)
2635
+ * partial.)
2473
2636
  */
2474
2637
  // testId → dispatched runId for members still mid-poll; the interrupt
2475
2638
  // partial reads it because a member's runId is local to triggerOne until
2476
- // the poll settles (DEV-331, codex finding 2).
2639
+ // the poll settles.
2477
2640
  const dispatchedRunIds = new Map();
2478
2641
  async function triggerOne(testId) {
2479
2642
  // Mint a fresh idempotency key per run — MUST NOT reuse the create key.
@@ -2542,10 +2705,14 @@ testIdToDashboardState) {
2542
2705
  if (opts.debug) {
2543
2706
  stderrFn(`[batch-run] ${testId} — rate throttle: waiting ${Math.ceil(clampedWait / 1000)}s before trigger`);
2544
2707
  }
2545
- await sleepFn(clampedWait);
2708
+ await sleepUntilOrInterrupt(clampedWait, shutdown.signal, sleepFn);
2546
2709
  }
2547
2710
  try {
2548
- 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
+ },
2549
2716
  // retryOnRateLimit: false — the outer retry loop is the SOLE owner of
2550
2717
  // rate-limit handling for the batch path. Allowing the HTTP layer to add
2551
2718
  // up to 3 internal retries per outer attempt would multiply trigger
@@ -2567,9 +2734,12 @@ testIdToDashboardState) {
2567
2734
  catch (err) {
2568
2735
  // Interrupt must reject the fan-out (the collect point prints the
2569
2736
  // partial for every spec), never flatten into a per-member outcome
2570
- // that would swallow the 128+signum exit (DEV-331).
2737
+ // that would swallow the 128+signum exit.
2571
2738
  if (err instanceof InterruptError)
2572
2739
  throw err;
2740
+ if (err instanceof ApiError && classifyBillingRefusal(err)) {
2741
+ billingRunErrors.push(err);
2742
+ }
2573
2743
  // RATE_LIMITED outer retry. Since the HTTP layer no longer retries
2574
2744
  // RATE_LIMITED (retryOnRateLimit: false above), every 429 reaches here
2575
2745
  // on the first attempt.
@@ -2619,7 +2789,7 @@ testIdToDashboardState) {
2619
2789
  };
2620
2790
  }
2621
2791
  stderrFn(`[batch-run] ${testId} — RATE_LIMITED (outer attempt ${outerRateLimitAttempt}/${BATCH_RUN_RATE_MAX_OUTER_RETRIES}): waiting ${Math.ceil(clampedRetryMs / 1000)}s before retry`);
2622
- await sleepFn(clampedRetryMs);
2792
+ await sleepUntilOrInterrupt(clampedRetryMs, shutdown.signal, sleepFn);
2623
2793
  continue; // retry the outer loop
2624
2794
  }
2625
2795
  // Exceeded outer retry cap — surface as terminal error.
@@ -2690,8 +2860,7 @@ testIdToDashboardState) {
2690
2860
  }
2691
2861
  // Record the dispatched runId (fresh trigger OR conflict-resume) so the
2692
2862
  // interrupt partial at the collect point can name every in-flight run —
2693
- // a member's runId is otherwise local until its poll settles (DEV-331,
2694
- // codex finding 2).
2863
+ // a member's runId is otherwise local until its poll settles.
2695
2864
  if (triggerResponse.runId)
2696
2865
  dispatchedRunIds.set(testId, triggerResponse.runId);
2697
2866
  if (!opts.wait) {
@@ -2771,6 +2940,8 @@ testIdToDashboardState) {
2771
2940
  };
2772
2941
  }
2773
2942
  const apiErr = err instanceof ApiError ? err : undefined;
2943
+ if (apiErr && classifyBillingRefusal(apiErr))
2944
+ billingRunErrors.push(apiErr);
2774
2945
  return {
2775
2946
  testId,
2776
2947
  runId: triggerResponse.runId,
@@ -2825,13 +2996,13 @@ testIdToDashboardState) {
2825
2996
  });
2826
2997
  }
2827
2998
  catch (fanOutErr) {
2828
- // Graceful detach (DEV-331): leave stdout parseable — settled members keep
2999
+ // Graceful detach: leave stdout parseable — settled members keep
2829
3000
  // their real status, unfinished ones are marked running — then rethrow so
2830
3001
  // index.ts exits 128+signum.
2831
3002
  if (fanOutErr instanceof InterruptError) {
2832
3003
  const settled = new Map(batchRunResults.map(r => [r.testId, r]));
2833
3004
  // Members mid-poll have no settled result yet — their runId comes from
2834
- // the dispatchedRunIds map recorded at trigger time (codex finding 2).
3005
+ // the dispatchedRunIds map recorded at trigger time.
2835
3006
  const partialResults = testIds.map((testId) => settled.get(testId) ?? {
2836
3007
  testId,
2837
3008
  runId: dispatchedRunIds.get(testId) ?? '',
@@ -2843,6 +3014,7 @@ testIdToDashboardState) {
2843
3014
  .filter(r => r.status === 'running' && r.runId)
2844
3015
  .map(r => r.runId);
2845
3016
  if (unfinished.length > 0) {
3017
+ fanOutErr.runWaitContext = true;
2846
3018
  stderrFn(interruptDetachMessage(fanOutErr, unfinished));
2847
3019
  }
2848
3020
  else {
@@ -2924,6 +3096,28 @@ testIdToDashboardState) {
2924
3096
  if (allTimeout) {
2925
3097
  throw new CLIError(`All ${batchRunResults.length} batch run(s) timed out after ${timeoutSeconds}s.`, 7);
2926
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
+ }
2927
3121
  // If all failing results share the same specific exit code (6 or 11), use it.
2928
3122
  if (errorExitCodes.length > 0 && errorExitCodes.length === failing.length) {
2929
3123
  const uniformCode = errorExitCodes[0];
@@ -2946,42 +3140,19 @@ testIdToDashboardState) {
2946
3140
  * specs at 50 before any per-spec work happens.
2947
3141
  */
2948
3142
  function readPlansJsonlGuarded(path) {
2949
- const absolute = resolveAbsolute(path);
2950
- let stat;
2951
- try {
2952
- stat = statSync(absolute);
2953
- }
2954
- catch (err) {
2955
- const code = err.code;
2956
- if (code === 'ENOENT') {
2957
- throw localValidationError('plans', `file does not exist: ${path}`);
2958
- }
2959
- if (code === 'EACCES') {
2960
- throw localValidationError('plans', `permission denied reading ${path}`);
2961
- }
2962
- const reason = err instanceof Error ? err.message : 'unknown error';
2963
- throw localValidationError('plans', `cannot stat ${path}: ${reason}`);
2964
- }
2965
- if (stat.size > MAX_BATCH_BODY_BYTES) {
3143
+ const result = readCappedFileGuarded('plans', path, MAX_BATCH_BODY_BYTES);
3144
+ if (!result.ok) {
2966
3145
  throw ApiError.fromEnvelope({
2967
3146
  error: {
2968
3147
  code: 'PAYLOAD_TOO_LARGE',
2969
- 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).`,
2970
3149
  nextAction: 'Split into multiple --plans files.',
2971
3150
  requestId: 'local',
2972
- details: { field: 'plans', sizeBytes: stat.size, maxBytes: MAX_BATCH_BODY_BYTES },
3151
+ details: { field: 'plans', sizeBytes: result.sizeBytes, maxBytes: MAX_BATCH_BODY_BYTES },
2973
3152
  },
2974
3153
  });
2975
3154
  }
2976
- let raw;
2977
- try {
2978
- raw = stripBom(readFileSync(absolute, 'utf8'));
2979
- }
2980
- catch (err) {
2981
- const reason = err instanceof Error ? err.message : 'unknown error';
2982
- throw localValidationError('plans', `cannot read ${path}: ${reason}`);
2983
- }
2984
- const lines = raw
3155
+ const lines = result.raw
2985
3156
  .split('\n')
2986
3157
  .map(l => l.trim())
2987
3158
  .filter(l => l.length > 0);
@@ -3992,8 +4163,13 @@ export async function runSteps(opts, deps = {}) {
3992
4163
  stderrFn(earlier
3993
4164
  ? `Latest run has no steps; inspect an earlier run: testsprite test steps ${opts.testId} --run-id ${earlier.runId}`
3994
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);
3995
4169
  }
3996
- catch {
4170
+ catch (err) {
4171
+ if (err instanceof InterruptError)
4172
+ throw err;
3997
4173
  // Missing history must not change the steps page or the command's exit code.
3998
4174
  }
3999
4175
  finally {
@@ -4100,11 +4276,13 @@ export async function runResultHistory(opts, deps = {}) {
4100
4276
  const client = makeClient(opts, deps);
4101
4277
  const pageSize = opts.pageSize ?? 20;
4102
4278
  const sinceIso = opts.since !== undefined ? parseDuration(opts.since) : undefined;
4279
+ const environment = normalizeEnvironmentName(opts.environment);
4103
4280
  const resp = await client.listTestRuns(opts.testId, {
4104
4281
  cursor: opts.cursor,
4105
4282
  pageSize,
4106
4283
  source: opts.source,
4107
4284
  since: sinceIso,
4285
+ ...(environment !== undefined ? { environment } : {}),
4108
4286
  });
4109
4287
  // Client-side rerun filter (--rerun / --no-rerun). isRerun is on every row;
4110
4288
  // the backend has no rerun filter. Undefined → no filter. Like --source, a
@@ -4112,11 +4290,16 @@ export async function runResultHistory(opts, deps = {}) {
4112
4290
  // and short-page hints below cover that.
4113
4291
  const runs = opts.rerun === undefined ? resp.runs : resp.runs.filter(r => r.isRerun === opts.rerun);
4114
4292
  if (opts.output !== 'text') {
4115
- out.print({ runs, nextCursor: resp.nextCursor }, data => JSON.stringify(data));
4293
+ out.print({ ...resp, runs }, data => JSON.stringify(data));
4116
4294
  return { ...resp, runs };
4117
4295
  }
4118
4296
  // Text mode rendering
4119
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
+ };
4120
4303
  // Empty / pre-cutover: print the backend meta.note instead of a blank table.
4121
4304
  // EXCEPTION: if nextCursor is non-null this page is empty only because the
4122
4305
  // backend filters AFTER limiting rows (limit-before-filter). Matching runs
@@ -4131,6 +4314,7 @@ export async function runResultHistory(opts, deps = {}) {
4131
4314
  if (resp.meta.portalUrl) {
4132
4315
  stderr(` Portal: ${resp.meta.portalUrl}`);
4133
4316
  }
4317
+ printRetentionNote();
4134
4318
  return resp;
4135
4319
  }
4136
4320
  // Truly empty (nextCursor is null): pre-cutover or genuinely no history.
@@ -4140,6 +4324,7 @@ export async function runResultHistory(opts, deps = {}) {
4140
4324
  if (resp.meta.portalUrl) {
4141
4325
  stderr(` Portal: ${resp.meta.portalUrl}`);
4142
4326
  }
4327
+ printRetentionNote();
4143
4328
  return resp;
4144
4329
  }
4145
4330
  const lines = [];
@@ -4160,12 +4345,28 @@ export async function runResultHistory(opts, deps = {}) {
4160
4345
  stderr(`[hint] Fewer than ${pageSize} rows returned but more may exist — ` +
4161
4346
  `a source/rerun filter skipped some entries. Pass --cursor ${resp.nextCursor} to continue.`);
4162
4347
  }
4348
+ printRetentionNote();
4163
4349
  return { ...resp, runs };
4164
4350
  }
4351
+ /**
4352
+ * The ENV cell of a history row: the name of the environment the run resolved
4353
+ * to, or `—` when the row names none. There is no second case — a `--local`
4354
+ * port or a `--target-url` names an environment (matched by origin, created
4355
+ * when nothing matches), so the address a run went to is always its
4356
+ * environment's own.
4357
+ */
4358
+ function describeRunEnv(run) {
4359
+ return run.environment?.name ?? '—';
4360
+ }
4165
4361
  const RUN_HISTORY_TABLE_COLUMNS = [
4166
4362
  { header: 'RUN ID', width: 36, render: run => run.runId },
4167
4363
  { header: 'STATUS', width: 10, render: run => run.status },
4168
4364
  { header: 'SOURCE', width: 18, render: run => run.source },
4365
+ {
4366
+ header: 'ENV',
4367
+ width: rows => Math.max(3, ...rows.map(run => describeRunEnv(run).length)),
4368
+ render: describeRunEnv,
4369
+ },
4169
4370
  { header: 'RERUN?', width: 6, render: run => (run.isRerun ? 'yes' : 'no') },
4170
4371
  { header: 'WHEN', width: 25, render: run => run.createdAt },
4171
4372
  {
@@ -4332,6 +4533,8 @@ export async function runFailureGet(opts, deps = {}) {
4332
4533
  dir: resolvedDir,
4333
4534
  failedOnly: opts.failedOnly,
4334
4535
  fetchImpl: deps.fetchImpl,
4536
+ shutdownSignal: shutdownOf(deps).signal,
4537
+ shutdown: shutdownOf(deps),
4335
4538
  });
4336
4539
  if (opts.output === 'json') {
4337
4540
  out.print({ ok: true, dir: bundle.dir, meta: bundle.meta, files: bundle.files });
@@ -4551,7 +4754,7 @@ function printRunOrChain(out, payload, createContext, textRenderer) {
4551
4754
  * Server-first precedence for a `dashboardUrl` field on any wire response
4552
4755
  * that can carry one (`RunResponse`, `CliCreateTestResponse`,
4553
4756
  * `CliBatchSpecResult`). Single source of truth for the rule so the create
4554
- * paths (DEV-737) and the run-completion path (`withRunDashboardUrl` below)
4757
+ * paths and the run-completion path (`withRunDashboardUrl` below)
4555
4758
  * can't drift apart.
4556
4759
  *
4557
4760
  * This is a PINNED three-state wire contract — a prior revision let a
@@ -4591,7 +4794,7 @@ function resolveDashboardUrl(wire, computeFallback) {
4591
4794
  * `undefined` so `JSON.stringify` omits the key entirely instead of
4592
4795
  * serializing a literal `"dashboardUrl": null` — the same normalization
4593
4796
  * `withRunDashboardUrl` already did inline for `RunResponse`, generalized
4594
- * 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.
4595
4798
  */
4596
4799
  function withDashboardUrl(wire, computeFallback) {
4597
4800
  const { dashboardUrl, suppressed } = resolveDashboardUrl(wire, computeFallback);
@@ -4600,7 +4803,7 @@ function withDashboardUrl(wire, computeFallback) {
4600
4803
  return { entity: dashboardUrl !== undefined ? { ...wire, dashboardUrl } : wire, suppressed };
4601
4804
  }
4602
4805
  /**
4603
- * DEV-737: advisory printed when the server explicitly withheld a dashboard
4806
+ * Advisory printed when the server explicitly withheld a dashboard
4604
4807
  * link (`resolveDashboardUrl`'s `suppressed: true`) rather than silently
4605
4808
  * omitting the field with no explanation. Fires on stderr regardless of
4606
4809
  * `--output` mode — the field's absence from a JSON envelope carries no
@@ -4659,6 +4862,8 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
4659
4862
  ];
4660
4863
  if (run.codeVersion !== null)
4661
4864
  lines.push(`codeVersion ${run.codeVersion}`);
4865
+ if (run.environment)
4866
+ lines.push(`environment ${describeEnvironmentLine(run)}`);
4662
4867
  if (run.targetUrl !== null)
4663
4868
  lines.push(`targetUrl ${run.targetUrl}`);
4664
4869
  lines.push(`createdAt ${run.createdAt}`);
@@ -4684,9 +4889,18 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
4684
4889
  // confusing "0/0 (passed=0, failed=0)" which reads like a broken no-op.
4685
4890
  lines.push(`steps n/a (backend)`);
4686
4891
  }
4687
- else if (run.stepSummary) {
4892
+ else if (run.stepSummary && run.stepSummary.total > 0) {
4688
4893
  lines.push(`steps ${run.stepSummary.completed}/${run.stepSummary.total} (passed=${run.stepSummary.passedCount}, failed=${run.stepSummary.failedCount})`);
4689
4894
  }
4895
+ else if (run.stepSummary) {
4896
+ // Same reasoning as the backend branch above, for the case the type check
4897
+ // cannot catch: a frontend run whose summary comes back with `total: 0`.
4898
+ // Rendering it verbatim prints `0/0 (passed=0, failed=0)` beside a
4899
+ // `passed` status, which reads as "nothing executed, and it passed" — the
4900
+ // exact no-op wording the backend branch exists to avoid. A zeroed summary
4901
+ // is an absent breakdown, not a breakdown of zero steps, so say that.
4902
+ lines.push(`steps n/a (no per-step breakdown reported)`);
4903
+ }
4690
4904
  // Closing pointer: where to inspect this run in the Portal (video, steps,
4691
4905
  // screenshots). Present only when withRunDashboardUrl could resolve it.
4692
4906
  if (run.dashboardUrl)
@@ -4695,10 +4909,11 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
4695
4909
  }
4696
4910
  /**
4697
4911
  * Best-effort resolve whether a finished run's test is a backend test, for the
4698
- * 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
4699
4913
  * network call when already known (create-chain `--type`, or the BE wait
4700
4914
  * fallback fired). Otherwise, in TEXT mode only, issues one `GET /tests/{id}`;
4701
- * 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
4702
4917
  * never probes — its envelope carries `stepSummary` verbatim and has no
4703
4918
  * "n/a (backend)" concept, so it is already correct.
4704
4919
  *
@@ -4716,7 +4931,9 @@ async function resolveRunCardIsBackend(client, testId, output, alreadyKnown) {
4716
4931
  const test = await client.get(`/tests/${encodeURIComponent(testId)}`);
4717
4932
  return test.type === 'backend';
4718
4933
  }
4719
- catch {
4934
+ catch (err) {
4935
+ if (err instanceof InterruptError)
4936
+ throw err;
4720
4937
  return false; // best-effort — fall back to the numeric step summary.
4721
4938
  }
4722
4939
  }
@@ -4732,6 +4949,8 @@ function renderTriggerRunText(r) {
4732
4949
  ];
4733
4950
  if (r.codeVersion !== null)
4734
4951
  lines.push(`codeVersion ${r.codeVersion}`);
4952
+ if (r.environment)
4953
+ lines.push(`environment ${describeEnvironmentLine(r)}`);
4735
4954
  if (r.targetUrl !== null)
4736
4955
  lines.push(`targetUrl ${r.targetUrl}`);
4737
4956
  // Same line the run card prints after `--wait` (`renderRunResponseText`), so a
@@ -4741,6 +4960,102 @@ function renderTriggerRunText(r) {
4741
4960
  lines.push(`dashboard ${r.dashboardUrl}`);
4742
4961
  return lines.join('\n');
4743
4962
  }
4963
+ /**
4964
+ * The `environment` line shared by the run card and the trigger card: the
4965
+ * name of the environment the run resolved to. A `--local` port or a
4966
+ * `--target-url` names an environment rather than sending the browser
4967
+ * somewhere else, so there is no "ran against the tunnel" suffix — the
4968
+ * address is the environment's own and prints on its own line.
4969
+ */
4970
+ function describeEnvironmentLine(r) {
4971
+ return r.environment?.name ?? '—';
4972
+ }
4973
+ /**
4974
+ * Validate `--env <name>`. The name is passed to the server
4975
+ * verbatim (it resolves `unique(project_id, name)` and lists the valid names
4976
+ * on a miss); the only local rule is that an empty/whitespace value is a typo,
4977
+ * not a request for the default environment — omitting the flag is.
4978
+ */
4979
+ function normalizeEnvironmentName(raw) {
4980
+ if (raw === undefined)
4981
+ return undefined;
4982
+ const name = raw.trim();
4983
+ if (name.length === 0) {
4984
+ throw localValidationError('env', 'must be a non-empty environment name (list them with: testsprite project env list <project-id>); omit --env to use the default environment');
4985
+ }
4986
+ return name;
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
+ }
4744
5059
  /**
4745
5060
  * Validate the `--timeout` flag value. Returns a clamped integer in
4746
5061
  * range [1, 3600], or the default when absent.
@@ -4775,8 +5090,51 @@ function parseStepTimeoutFlag(raw, flagName) {
4775
5090
  * Exit code is 0 on `passed`, 1 on `failed`/`blocked`/`cancelled`,
4776
5091
  * 7 on timeout.
4777
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
+ }
4778
5135
  export async function runTestRun(opts, deps = {}) {
4779
5136
  assertIdempotencyKey(opts.idempotencyKey);
5137
+ const environment = normalizeEnvironmentName(opts.environment);
4780
5138
  // --local resolution runs FIRST and touches nothing: every refusal below
4781
5139
  // must happen before a client is even constructed, because the guarantee
4782
5140
  // this feature sells is that a doomed `--local` run never gets a run row,
@@ -4834,6 +5192,7 @@ export async function runTestRun(opts, deps = {}) {
4834
5192
  // handle, the same reason `dashboardUrl` is suppressed under
4835
5193
  // --dry-run rather than pointing at the canned sample id.
4836
5194
  ...(isTunnelRun ? { tunnelClientId: '<minted at run time>' } : {}),
5195
+ ...(environment !== undefined ? { environment } : {}),
4837
5196
  },
4838
5197
  idempotencyKey,
4839
5198
  ...(isTunnelRun
@@ -4859,12 +5218,23 @@ export async function runTestRun(opts, deps = {}) {
4859
5218
  const requestTimeoutMs = resolveWaitRequestTimeoutMs(opts);
4860
5219
  const clientOpts = { ...opts, requestTimeoutMs };
4861
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
+ }
4862
5231
  const tunnelRequestTimeoutMs = isTunnelRun
4863
5232
  ? resolveRequestTimeoutMs(clientOpts, deps.env ?? process.env)
4864
5233
  : undefined;
4865
5234
  const out = makeOutput(opts.output, deps);
4866
5235
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4867
5236
  const shutdown = shutdownOf(deps);
5237
+ // `--env` is feature-gated per workspace. Refuse here — one read-only `/me`,
4868
5238
  // Pre-charge reachability preflight — real path only (dry-run
4869
5239
  // makes zero network calls by convention), after `assertNotLocal` and
4870
5240
  // before the trigger POST so a doomed run never gets a run row or charge.
@@ -4873,12 +5243,12 @@ export async function runTestRun(opts, deps = {}) {
4873
5243
  // already ran this exact check against the same URL before its own
4874
5244
  // create POST and sets `skipPreflight: true` here to avoid probing twice.
4875
5245
  if (isTunnelRun) {
4876
- // The tunnel-run equivalent of the --target-url probe, and the reason
4877
- // DEV-868 exists: a dev server that is not running is the single most
4878
- // likely `--local` mistake, and this is the last moment it costs nothing.
4879
- // Unlike the --target-url probe this one is conclusive — the dial it
4880
- // performs is the same raw loopback connect the tunnel client will make
4881
- // 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.
4882
5252
  await assertLocalPortListening(localHost, opts.localPort, { skipPreflight: opts.skipPreflight }, stderrFn);
4883
5253
  if (isProxyAgentActive()) {
4884
5254
  stderrFn('[advisory] An HTTP proxy is configured for this process. The tunnel control channel ' +
@@ -4887,7 +5257,12 @@ export async function runTestRun(opts, deps = {}) {
4887
5257
  }
4888
5258
  }
4889
5259
  else if (opts.targetUrl !== undefined) {
4890
- 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);
4891
5266
  }
4892
5267
  // Nothing above this line has spent money or minted a credential. Everything
4893
5268
  // below it must be unwound on every exit path, which is what the `finally`
@@ -4903,6 +5278,7 @@ export async function runTestRun(opts, deps = {}) {
4903
5278
  tunnelSession = await openTunnelSession({
4904
5279
  log: stderrFn,
4905
5280
  logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
5281
+ onMinted: minted => stderrFn(`[tunnel] Minted tunnel client ${minted.clientId}; connecting…`),
4906
5282
  onFatal: () => {
4907
5283
  // Surfaced to the poll loop through `onTick` below; a remint cannot
4908
5284
  // rescue this run (see `lib/tunnel-session.ts`).
@@ -4937,18 +5313,31 @@ export async function runTestRun(opts, deps = {}) {
4937
5313
  // bounded deadline so we can learn the runId if the server charged it.
4938
5314
  if (isTunnelRun && shutdown.signal.aborted)
4939
5315
  throw shutdown.signal.reason;
5316
+ if (isTunnelRun)
5317
+ recordTelemetryExtras({ localConcurrencyLimit: 1, localPeakInFlight: 0 });
4940
5318
  const triggerBody = {
4941
5319
  source: 'cli',
4942
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 } : {}),
4943
5324
  // The client ID only. The secret stays in this process and never
4944
5325
  // reaches a request body, an idempotency row, or an audit line.
4945
5326
  ...(tunnelSession ? { tunnelClientId: tunnelSession.clientId } : {}),
5327
+ // Whose credentials to log in with; the two fields above
5328
+ // say where the browser goes. Absent → the project's default env.
5329
+ ...(environment !== undefined ? { environment } : {}),
4946
5330
  };
4947
5331
  const result = isTunnelRun
4948
5332
  ? await withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, triggerClient => triggerClient.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey }))
4949
5333
  : await client.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey });
4950
5334
  triggerResponse = result.body;
4951
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');
4952
5341
  }
4953
5342
  catch (err) {
4954
5343
  // CONFLICT (409) can arise from two different causes:
@@ -4974,11 +5363,83 @@ export async function runTestRun(opts, deps = {}) {
4974
5363
  // auto-resume. Other CONFLICT reasons (snapshot_in_flight, etc.) exit 6.
4975
5364
  if (conflictReason === 'run_in_flight' && currentRunId !== undefined) {
4976
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
+ }
4977
5439
  // If the caller supplied --target-url, verify the in-flight run targets
4978
5440
  // the same URL. A mismatch means we would be reporting a different
4979
5441
  // environment's results as if our requested environment was tested.
4980
5442
  if (opts.targetUrl !== undefined) {
4981
- const inFlightRun = await client.getRun(currentRunId);
4982
5443
  if (inFlightRun.targetUrl !== opts.targetUrl) {
4983
5444
  throw new ApiError({
4984
5445
  code: 'CONFLICT',
@@ -5011,31 +5472,21 @@ export async function runTestRun(opts, deps = {}) {
5011
5472
  };
5012
5473
  }
5013
5474
  else {
5014
- // D: No --target-url supplied — fetch the in-flight run so the
5015
- // synthesised triggerResponse.targetUrl is the REAL environment being
5016
- // tested, not an empty string that would propagate into the timeout
5017
- // partial (Finding D). Fall back to null (not '') if the lookup fails.
5018
- let inFlightTargetUrl = null;
5019
- let inFlightCodeVersion = '';
5020
- try {
5021
- const inFlightRun = await client.getRun(currentRunId);
5022
- inFlightTargetUrl = inFlightRun.targetUrl ?? null;
5023
- inFlightCodeVersion = inFlightRun.codeVersion ?? '';
5024
- }
5025
- catch {
5026
- // Best-effort — if the lookup fails, proceed with null targetUrl.
5027
- }
5028
- // Auto-resume but emit a stronger advisory so the caller is aware
5029
- // they are attaching to the project default.
5030
- // SIG-9 (DEV-331 final): the in-flight run is NOT auto-cancelled —
5031
- // name the real `test cancel` command instead of the old (false)
5032
- // "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.
5033
5484
  stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
5034
5485
  (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
5035
5486
  `). Auto-resuming wait on in-flight run. ` +
5036
- `If you needed a specific target URL, cancel it with ` +
5037
- `testsprite test cancel ${currentRunId}, or re-trigger with ` +
5038
- `--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}` : ''}.`);
5039
5490
  triggerResponse = {
5040
5491
  runId: currentRunId,
5041
5492
  status: 'queued',
@@ -5216,6 +5667,7 @@ export async function runTestRun(opts, deps = {}) {
5216
5667
  // JSON consumers and AI agents can grab the runId and chain into
5217
5668
  // `testsprite test wait <runId>` without parsing the stderr error envelope.
5218
5669
  const detach = await settleTunnelDetach('timeout');
5670
+ recordTelemetryExtras({ passed: 0, failed: 0, blocked: 0, timedOut: 1 });
5219
5671
  deps.onWaitTimeout?.({
5220
5672
  reason: 'wait_timeout',
5221
5673
  ...(tunnelSession
@@ -5331,7 +5783,7 @@ export async function runTestRun(opts, deps = {}) {
5331
5783
  : rateLimitedDetachMessage(err, [triggerResponse.runId]));
5332
5784
  throw err;
5333
5785
  }
5334
- // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
5786
+ // Graceful detach on SIGINT/SIGTERM: same partial-
5335
5787
  // envelope shape as the timeout paths so stdout stays parseable, plus the
5336
5788
  // honest "keeps running and billing" stderr line. Rethrow → index.ts
5337
5789
  // renders the INTERRUPTED envelope and exits 128+signum.
@@ -5356,6 +5808,7 @@ export async function runTestRun(opts, deps = {}) {
5356
5808
  stderrFn(detach
5357
5809
  ? tunnelDetachMessage(detach, err)
5358
5810
  : interruptDetachMessage(err, [triggerResponse.runId]));
5811
+ err.runWaitContext = true;
5359
5812
  if (detach !== undefined)
5360
5813
  attachTunnelInterruptDetach(err, detach);
5361
5814
  throw err;
@@ -5395,7 +5848,7 @@ export async function runTestRun(opts, deps = {}) {
5395
5848
  ticker.finalize(formatRunProgressLine(finalRun, Date.now() - startMs));
5396
5849
  // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs); on
5397
5850
  // the standalone `test run <id>` path neither is set, so probe the test type
5398
- // once (text mode only, best-effort) — DEV-282.
5851
+ // once (text mode only, best-effort).
5399
5852
  const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
5400
5853
  const finalRunWithUrl = withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps));
5401
5854
  printRunOrChain(out, finalRunWithUrl, opts.createContext, data => renderRunResponseText(data, { isBackend }));
@@ -5411,6 +5864,9 @@ export async function runTestRun(opts, deps = {}) {
5411
5864
  ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
5412
5865
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
5413
5866
  }
5867
+ // One-run verdict counts (0/1 each) — the single-run analogue of the batch
5868
+ // accounting, so a CI job that runs one test is measurable the same way.
5869
+ recordTelemetryExtras(batchOutcomeCounts([finalRun]));
5414
5870
  // CI-native output layer (issue #99): single-test parity with the --all batch.
5415
5871
  // Emitted before the exit-code gate throws below so the summary file and
5416
5872
  // annotations land even when the run exits non-zero (mirrors the batch path).
@@ -5481,7 +5937,7 @@ export async function runTestWaitMany(opts, deps = {}) {
5481
5937
  }
5482
5938
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
5483
5939
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
5484
- const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
5940
+ const sleepFn = deps.sleep ?? defaultSleep;
5485
5941
  // One shared deadline across every member (the whole point of the shared
5486
5942
  // pool: `--timeout 600` means the invocation ends within ~600s, not
5487
5943
  // 600s x ceil(N/concurrency)).
@@ -5538,7 +5994,7 @@ export async function runTestWaitMany(opts, deps = {}) {
5538
5994
  throw err;
5539
5995
  // Interrupt must reject the fan-out (handled at the collect point), not
5540
5996
  // be flattened into a per-member 'error' outcome that would swallow the
5541
- // 128+signum exit (DEV-331).
5997
+ // 128+signum exit.
5542
5998
  if (err instanceof InterruptError)
5543
5999
  throw err;
5544
6000
  if (err instanceof ApiError) {
@@ -5565,7 +6021,7 @@ export async function runTestWaitMany(opts, deps = {}) {
5565
6021
  stderrFn(`[wait] ${runId} — rate limited (attempt ${rateLimitAttempt}/${WAIT_POLL_RATE_MAX_OUTER_RETRIES}): retrying in ${Math.ceil(clampedRetryMs / 1000)}s`);
5566
6022
  // Arm the graceful-detach scope across the backoff. `pollRunUntilTerminal`
5567
6023
  // disarms in its own `finally`, so without this the sleep is a window
5568
- // 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
5569
6025
  // path (partial `{runId, status:'running'}` on stdout + honest hint).
5570
6026
  const shutdown = shutdownOf(deps);
5571
6027
  const disarm = shutdown.arm();
@@ -5611,6 +6067,8 @@ export async function runTestWaitMany(opts, deps = {}) {
5611
6067
  }
5612
6068
  catch (fanOutErr) {
5613
6069
  if (fanOutErr instanceof RequestTimeoutError || fanOutErr instanceof InterruptError) {
6070
+ if (fanOutErr instanceof InterruptError)
6071
+ fanOutErr.runWaitContext = true;
5614
6072
  // Same contract as the batch pollers: leave stdout parseable before
5615
6073
  // exiting. Members that already settled keep their real status; only
5616
6074
  // the still-unfinished ids are marked running and named in the hint
@@ -5720,13 +6178,13 @@ export async function runTestWaitMany(opts, deps = {}) {
5720
6178
  return payload;
5721
6179
  }
5722
6180
  /**
5723
- * `test cancel <run-id...>` — DEV-331 piece 3.
6181
+ * `test cancel <run-id...>`.
5724
6182
  *
5725
6183
  * User-initiated cancel of one or more queued/running runs via
5726
- * `POST /api/cli/v1/runs/{runId}/cancel`. Naturally idempotent (D10): a
6184
+ * `POST /api/cli/v1/runs/{runId}/cancel`. Naturally idempotent: a
5727
6185
  * repeat cancel of the same run is a 200 `alreadyCancelled` success, not an
5728
- * error. Dispatches serially (per-id volume is tiny — no batch endpoint,
5729
- * 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).
5730
6188
  *
5731
6189
  * Single id: renders the returned run card (`status cancelled`); an
5732
6190
  * `alreadyCancelled` response adds an `[advisory]` line. Exit code mirrors
@@ -5766,6 +6224,8 @@ export async function runTestCancel(opts, deps = {}) {
5766
6224
  });
5767
6225
  }
5768
6226
  catch (err) {
6227
+ if (err instanceof InterruptError)
6228
+ throw err;
5769
6229
  if (err instanceof ApiError && err.code === 'NOT_FOUND') {
5770
6230
  rows.push({ runId, status: 'notFound' });
5771
6231
  continue;
@@ -5872,7 +6332,7 @@ export function createTestCancelCommand(deps) {
5872
6332
  .addHelpText('after', GLOBAL_OPTS_HINT)
5873
6333
  .action(async (runIds, _cmdOpts, command) => {
5874
6334
  await runTestCancel({
5875
- ...resolveCommonOptions(command),
6335
+ ...resolveCommonOptions(command, deps.env),
5876
6336
  runIds,
5877
6337
  }, deps);
5878
6338
  });
@@ -6005,7 +6465,7 @@ export async function runTestWait(opts, deps = {}) {
6005
6465
  stderrFn(rateLimitedDetachMessage(err, [opts.runId]));
6006
6466
  throw err;
6007
6467
  }
6008
- // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
6468
+ // Graceful detach on SIGINT/SIGTERM — see runTestRun.
6009
6469
  if (err instanceof InterruptError) {
6010
6470
  ticker.finalize(`Run ${opts.runId} — interrupted (${err.signal})`);
6011
6471
  const partial = { runId: opts.runId, status: 'running' };
@@ -6019,6 +6479,7 @@ export async function runTestWait(opts, deps = {}) {
6019
6479
  ].join('\n');
6020
6480
  });
6021
6481
  stderrFn(interruptDetachMessage(err, [opts.runId]));
6482
+ err.runWaitContext = true;
6022
6483
  throw err;
6023
6484
  }
6024
6485
  ticker.finalize();
@@ -6029,7 +6490,7 @@ export async function runTestWait(opts, deps = {}) {
6029
6490
  }
6030
6491
  ticker.finalize(formatRunProgressLine(finalRun, Date.now() - startMs));
6031
6492
  // `test wait` has no type hint; probe the test type once (text mode only,
6032
- // 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)`.
6033
6494
  const isBackend = await resolveRunCardIsBackend(client, finalRun.testId, opts.output, beFallbackUsed);
6034
6495
  out.print(withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), data => renderRunResponseText(data, { isBackend }));
6035
6496
  if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
@@ -6048,8 +6509,8 @@ export async function runTestWait(opts, deps = {}) {
6048
6509
  /**
6049
6510
  * Best-effort `testId → test name` map for the JUnit report, so a CI test tab
6050
6511
  * shows names instead of UUIDs. One paginated `GET /tests?projectId=` sweep,
6051
- * bounded by a 5 s deadline and swallowed on any error — a missing/partial map
6052
- * 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.
6053
6514
  */
6054
6515
  async function buildTestNameMap(client, projectId) {
6055
6516
  const map = new Map();
@@ -6072,7 +6533,9 @@ async function buildTestNameMap(client, projectId) {
6072
6533
  break;
6073
6534
  }
6074
6535
  }
6075
- catch {
6536
+ catch (err) {
6537
+ if (err instanceof InterruptError)
6538
+ throw err;
6076
6539
  // best-effort — a partial/empty map simply falls back to ids in the report.
6077
6540
  }
6078
6541
  finally {
@@ -6103,6 +6566,31 @@ export async function writeBatchJUnitReportIfRequested(opts, results, nameByTest
6103
6566
  });
6104
6567
  await writeJUnitReportFile(opts.reportFile, xml);
6105
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
+ }
6106
6594
  /** Human explanation for a zero-dispatch batch, from what the engine skipped. */
6107
6595
  function zeroDispatchReason(skippedFrontend, skippedIntegration) {
6108
6596
  const parts = [];
@@ -6120,9 +6608,10 @@ function zeroDispatchReason(skippedFrontend, skippedIntegration) {
6120
6608
  * Handle a batch invocation that dispatched ZERO tests — all skipped, an empty
6121
6609
  * project, or a `--filter` that matched nothing. Left alone this exits 0 with no
6122
6610
  * artifact, a CI false-green: a gate that greens on zero tests is worse than no
6123
- * gate (DEV-1046). So it emits the CI artifacts (summary + `::error::` annotation
6124
- * + JUnit report) so the gate shows WHY, then fails with **exit 5** unless the
6125
- * caller passed `--allow-empty` (in which case it returns and the caller exits 0).
6611
+ * gate. So it emits the CI artifacts (summary with `skipped` rows +
6612
+ * `::warning::` annotations + JUnit report) so the gate shows WHY, then fails
6613
+ * with **exit 5** unless the caller passed `--allow-empty` (in which case it
6614
+ * returns and the caller exits 0).
6126
6615
  *
6127
6616
  * `skipped` is the union of skipped FE + integration tests (rendered as
6128
6617
  * `<skipped/>` JUnit cases and non-passed summary rows so they're visible);
@@ -6133,14 +6622,18 @@ async function finishZeroDispatchBatch(params) {
6133
6622
  const runs = skipped.length > 0
6134
6623
  ? skipped.map(testId => ({ testId, status: 'skipped', error: reason }))
6135
6624
  : [{ testId: '(no tests)', status: 'no_tests', error: reason }];
6625
+ // Counted as `skipped`, not `failed`: nothing ran, so nothing
6626
+ // failed — the exit-5 gate below is what makes the job red, and the summary
6627
+ // must agree with it rather than claim failures the gates don't see.
6136
6628
  const summary = {
6137
6629
  total: runs.length,
6138
6630
  passed: 0,
6139
- failed: runs.length,
6631
+ failed: 0,
6632
+ skipped: runs.length,
6140
6633
  timedOut: 0,
6141
6634
  runs,
6142
6635
  };
6143
- // Emit the in-memory artifacts (summary + `::error::` annotation) FIRST: they
6636
+ // Emit the in-memory artifacts (summary + `::warning::` annotation) FIRST: they
6144
6637
  // can't fail on I/O, so the "show WHY it's red" diagnostics always land — even
6145
6638
  // if the JUnit path below is misconfigured. Ordering these after the file write
6146
6639
  // would let an unwritable --report-file throw (exit 10) preempt both the
@@ -6155,7 +6648,7 @@ async function finishZeroDispatchBatch(params) {
6155
6648
  // write failure to a warning so an unwritable path can't mask the exit-5 intent
6156
6649
  // with an I/O exit code.
6157
6650
  try {
6158
- 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 })));
6159
6652
  }
6160
6653
  catch (err) {
6161
6654
  stderrFn(`[${label}] could not write the JUnit report on a zero-dispatch run: ${err instanceof Error ? err.message : String(err)}; continuing`);
@@ -6176,6 +6669,7 @@ async function finishZeroDispatchBatch(params) {
6176
6669
  */
6177
6670
  export async function runTestRunAll(opts, deps = {}) {
6178
6671
  assertIdempotencyKey(opts.idempotencyKey);
6672
+ const environment = normalizeEnvironmentName(opts.environment);
6179
6673
  const projectId = resolveProjectId(opts.projectId, deps);
6180
6674
  requireProjectId(projectId);
6181
6675
  if (!Number.isInteger(opts.maxConcurrency) ||
@@ -6194,7 +6688,7 @@ export async function runTestRunAll(opts, deps = {}) {
6194
6688
  const out = makeOutput(opts.output, deps);
6195
6689
  // --- Dry-run path ---
6196
6690
  if (opts.dryRun) {
6197
- // 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
6198
6692
  // here — otherwise the canned sample can be mistaken for a live response.
6199
6693
  emitDryRunBanner(stderrFn);
6200
6694
  const idempotencyKey = opts.idempotencyKey ?? `dry-run-${randomUUID()}`;
@@ -6207,6 +6701,9 @@ export async function runTestRunAll(opts, deps = {}) {
6207
6701
  projectId,
6208
6702
  testIds: opts.nameFilter ? ['<filtered by --filter>'] : undefined,
6209
6703
  source: 'cli',
6704
+ ...(opts.autoHeal === false ? { autoHeal: false } : {}),
6705
+ ...(environment !== undefined ? { environment } : {}),
6706
+ ...(opts.targetUrl !== undefined ? { targetUrl: opts.targetUrl } : {}),
6210
6707
  },
6211
6708
  idempotencyKey,
6212
6709
  ...(opts.wait ? { thenPoll: '/api/cli/v1/runs/<run-id>?waitSeconds=25' } : {}),
@@ -6214,11 +6711,18 @@ export async function runTestRunAll(opts, deps = {}) {
6214
6711
  if (opts.report === 'junit' && opts.reportFile !== undefined) {
6215
6712
  await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(opts.projectId, opts.reportSuiteName));
6216
6713
  }
6217
- out.print(batchRunSample ?? envelope);
6714
+ out.print(opts.targetUrl !== undefined ? envelope : (batchRunSample ?? envelope));
6218
6715
  return undefined;
6219
6716
  }
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
+ }
6220
6722
  // D4: under --wait, raise per-request timeout to cover --timeout.
6221
6723
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
6724
+ // `--env` gate — see `runTestRun`. Before the test-set enumeration so a
6725
+ // gated batch makes no billable call at all.
6222
6726
  // Portal deep links for batch output: every test in the batch belongs to
6223
6727
  // opts.projectId, so per-item dashboardUrl needs no extra wire data. The
6224
6728
  // project-level URL closes out text-mode output ("watch the wave here").
@@ -6249,6 +6753,74 @@ export async function runTestRunAll(opts, deps = {}) {
6249
6753
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
6250
6754
  stderrFn(`idempotency-key: ${idempotencyKey}`);
6251
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
+ }
6252
6824
  // Resolve testIds: fetch all tests in the project, apply --filter.
6253
6825
  let testIds;
6254
6826
  if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
@@ -6275,7 +6847,7 @@ export async function runTestRunAll(opts, deps = {}) {
6275
6847
  });
6276
6848
  // Zero-dispatch (a --filter that matched nothing): emit the CI artifacts
6277
6849
  // and fail unless --allow-empty, so a renamed test can't turn a filtered
6278
- // gate permanently green (DEV-1046). Returns here only under --allow-empty.
6850
+ // gate permanently green. Returns here only under --allow-empty.
6279
6851
  await finishZeroDispatchBatch({
6280
6852
  reason: `--filter "${opts.nameFilter}" matched no tests in project ${projectId}`,
6281
6853
  skipped: [],
@@ -6293,8 +6865,12 @@ export async function runTestRunAll(opts, deps = {}) {
6293
6865
  const batchResp = await client.triggerBatchRunFresh({
6294
6866
  projectId,
6295
6867
  ...(testIds !== undefined ? { testIds } : {}),
6296
- source: 'cli',
6868
+ ...dispatchFields,
6297
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, []);
6298
6874
  // Project-level "watch it here" link. A V3 backend sends it (string, or
6299
6875
  // `null` when no single page exists — e.g. a `--all` that fanned out over
6300
6876
  // several sibling projects); an older backend / the V2 engine omits the key,
@@ -6319,7 +6895,7 @@ export async function runTestRunAll(opts, deps = {}) {
6319
6895
  if (conflicts.length > 0) {
6320
6896
  // Reason-aware advisory: a view-only / un-runnable / not-found case is not
6321
6897
  // "already in flight" — summarizeConflicts names the actual causes.
6322
- 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) : ''}`);
6323
6899
  }
6324
6900
  if (deferred.length > 0) {
6325
6901
  stderrFn(`Rate-deferred testIds (retry later): ${deferred.map(d => d.testId).join(' ')}`);
@@ -6328,6 +6904,13 @@ export async function runTestRunAll(opts, deps = {}) {
6328
6904
  `${skippedFrontend.length > 0 ? ` (${skippedFrontend.length} FE skipped)` : ''}` +
6329
6905
  `${conflicts.length > 0 ? ` (${conflicts.length} conflict${conflicts.length !== 1 ? 's' : ''})` : ''}` +
6330
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
+ }
6331
6914
  if (!opts.wait) {
6332
6915
  const printResp = {
6333
6916
  accepted: accepted.map(withBatchDashboardUrl),
@@ -6357,25 +6940,48 @@ export async function runTestRunAll(opts, deps = {}) {
6357
6940
  }
6358
6941
  return lines.join('\n');
6359
6942
  });
6943
+ recordBatchOutcome({
6944
+ accepted: accepted.length,
6945
+ conflicts,
6946
+ deferred: deferred.length,
6947
+ skipped: skippedFrontend.length + skippedIntegration.length,
6948
+ });
6360
6949
  // Rate-deferred tests were NOT dispatched → signal incomplete (exit 7),
6361
6950
  // mirroring `test rerun --all`. The user retries with a fresh invocation.
6362
6951
  if (deferred.length > 0) {
6363
6952
  throw new CLIError(`Batch run incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} rate-deferred (per-key run budget). Retry these individually after ~60s: ${deferred.map(d => d.testId).join(' ')}`, 7);
6364
6953
  }
6954
+ // Nothing queued because the wallet refused every case → the same exit-12
6955
+ // INSUFFICIENT_CREDITS the single-run route answers, not an in-flight CONFLICT.
6956
+ if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
6957
+ throw insufficientCreditsConflictError(conflicts, batchApiUrl);
6958
+ }
6959
+ if (isPausedRefusal({ accepted, deferred, conflicts })) {
6960
+ throw pausedConflictError(conflicts, batchApiUrl);
6961
+ }
6365
6962
  // Nothing queued and everything was an in-flight conflict → surface CONFLICT (exit 6).
6366
6963
  if (accepted.length === 0 && conflicts.length > 0) {
6367
6964
  throw ApiError.fromEnvelope({
6368
6965
  error: {
6369
6966
  code: 'CONFLICT',
6370
- message: `Batch run: nothing was queued — ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight.`,
6371
- 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)}`,
6372
6978
  requestId: 'local',
6373
6979
  details: { conflicts: conflicts.map(c => c.testId) },
6374
6980
  },
6375
6981
  });
6376
6982
  }
6377
6983
  // Zero dispatched, nothing pending (deferred / conflict already threw above):
6378
- // all tests were skipped, or the project has none. Don't exit 0 (DEV-1046).
6984
+ // all tests were skipped, or the project has none. Don't exit 0.
6379
6985
  if (accepted.length === 0) {
6380
6986
  await finishZeroDispatchBatch({
6381
6987
  reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
@@ -6450,20 +7056,35 @@ export async function runTestRunAll(opts, deps = {}) {
6450
7056
  retryResp = await client.triggerBatchRunFresh({
6451
7057
  projectId,
6452
7058
  testIds: retryIds,
6453
- source: 'cli',
7059
+ ...dispatchFields,
6454
7060
  }, { idempotencyKey: retryKey });
6455
7061
  }
6456
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;
6457
7068
  // If the retry itself errors, surface it and stop retrying.
6458
7069
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
6459
7070
  break;
6460
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);
6461
7077
  const newlyAccepted = retryResp.accepted;
6462
7078
  const newlyDeferred = retryResp.deferred;
6463
7079
  const newlyConflicted = retryResp.conflicts;
6464
7080
  if (newlyAccepted.length > 0) {
6465
7081
  stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyAccepted.length} test${newlyAccepted.length !== 1 ? 's' : ''} now accepted.`);
6466
- 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);
6467
7088
  }
6468
7089
  if (newlyConflicted.length > 0) {
6469
7090
  // [P1] Merge retry-returned conflicts into the running conflicts collection
@@ -6513,7 +7134,9 @@ export async function runTestRunAll(opts, deps = {}) {
6513
7134
  notBefore = inFlight.createdAt;
6514
7135
  startedBy = inFlight.source || inFlight.createdFrom || undefined;
6515
7136
  }
6516
- catch {
7137
+ catch (err) {
7138
+ if (err instanceof InterruptError)
7139
+ throw err;
6517
7140
  // keep the conservative now() floor (fetch failed or the signal aborted)
6518
7141
  }
6519
7142
  stderrFn(`[auto-resume] ${c.testId} — polling in-flight run ${inFlightRunId}${startedBy ? ` (started by ${startedBy})` : ''} to a verdict instead of failing`);
@@ -6524,7 +7147,14 @@ export async function runTestRunAll(opts, deps = {}) {
6524
7147
  // slot-claim failures to conflicts[]); the resumed entries reuse the existing
6525
7148
  // run's id with a real createdAt floor. Polling all of them is the only way
6526
7149
  // `--wait` reports a faithful (not false-green) verdict.
6527
- 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);
6528
7158
  if (pollable.length === 0) {
6529
7159
  // Build final response with potentially-updated accepted/deferred from D3 retry loop.
6530
7160
  const finalResp = {
@@ -6535,12 +7165,20 @@ export async function runTestRunAll(opts, deps = {}) {
6535
7165
  skippedIntegration,
6536
7166
  };
6537
7167
  out.print(finalResp);
7168
+ recordBatchOutcome({
7169
+ accepted: accepted.length,
7170
+ conflicts,
7171
+ deferred: deferred.length,
7172
+ skipped: skippedFrontend.length + skippedIntegration.length,
7173
+ });
6538
7174
  // Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
6539
7175
  // mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
6540
7176
  // Emit the deferred/conflict summary + annotations first so CI shows them (the
6541
7177
  // pure zero-dispatch fall-through emits its OWN skipped-rows summary below).
6542
7178
  if (deferred.length > 0 || conflicts.length > 0) {
6543
- emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(finalResp)), opts, {
7179
+ const summary = summarizeAcceptedPayload(JSON.stringify(finalResp));
7180
+ await writeBatchJUnitReportIfRequested(opts, skippedJUnitResultsFromSummary(summary));
7181
+ emitCiArtifacts(summary, opts, {
6544
7182
  env: deps.env ?? process.env,
6545
7183
  stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
6546
7184
  stderr: stderrFn,
@@ -6549,12 +7187,22 @@ export async function runTestRunAll(opts, deps = {}) {
6549
7187
  if (deferred.length > 0) {
6550
7188
  throw new CLIError(`Batch run incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} rate-deferred (per-key run budget) — retry these individually after ~60s: ${deferred.map(d => d.testId).join(' ')}`, 7);
6551
7189
  }
7190
+ // Every case refused for credits → exit 12 (same envelope as the single-run
7191
+ // route), checked before the generic all-conflict exit 6.
7192
+ if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
7193
+ throw insufficientCreditsConflictError(conflicts, batchApiUrl);
7194
+ }
7195
+ if (isPausedRefusal({ accepted, deferred, conflicts })) {
7196
+ throw pausedConflictError(conflicts, batchApiUrl);
7197
+ }
6552
7198
  if (conflicts.length > 0) {
6553
7199
  throw ApiError.fromEnvelope({
6554
7200
  error: {
6555
7201
  code: 'CONFLICT',
6556
- message: `Batch run: nothing was queued — ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight.`,
6557
- 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)}`,
6558
7206
  requestId: 'local',
6559
7207
  details: { conflicts: conflicts.map(c => c.testId) },
6560
7208
  },
@@ -6562,7 +7210,7 @@ export async function runTestRunAll(opts, deps = {}) {
6562
7210
  }
6563
7211
  // Reached only when nothing was queued and nothing is pending: all tests were
6564
7212
  // skipped, or the project has none. Emit a skipped-rows summary + JUnit and
6565
- // fail unless --allow-empty — never a silent exit 0 (DEV-1046).
7213
+ // fail unless --allow-empty — never a silent exit 0.
6566
7214
  await finishZeroDispatchBatch({
6567
7215
  reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
6568
7216
  skipped: [...skippedFrontend, ...skippedIntegration.map(s => s.testId)],
@@ -6623,6 +7271,8 @@ export async function runTestRunAll(opts, deps = {}) {
6623
7271
  };
6624
7272
  }
6625
7273
  catch (err) {
7274
+ if (err instanceof InterruptError)
7275
+ throw err;
6626
7276
  if (err instanceof TimeoutError)
6627
7277
  deps.onWaitTimeout?.({ reason: 'wait_timeout' });
6628
7278
  // fall through to the timeout result below
@@ -6686,7 +7336,7 @@ export async function runTestRunAll(opts, deps = {}) {
6686
7336
  }
6687
7337
  // Interrupt must reject the fan-out (the collect point below prints the
6688
7338
  // partial for every dispatched run), never flatten into a per-member
6689
- // outcome that would swallow the 128+signum exit (DEV-331).
7339
+ // outcome that would swallow the 128+signum exit.
6690
7340
  if (err instanceof InterruptError)
6691
7341
  throw err;
6692
7342
  if (err instanceof RequestTimeoutError) {
@@ -6713,7 +7363,7 @@ export async function runTestRunAll(opts, deps = {}) {
6713
7363
  testId: entry.testId,
6714
7364
  runId,
6715
7365
  status: 'error',
6716
- error: { code: err.code, message: err.message, exitCode: err.exitCode },
7366
+ error: waitMemberError(err),
6717
7367
  };
6718
7368
  }
6719
7369
  throw err;
@@ -6745,7 +7395,7 @@ export async function runTestRunAll(opts, deps = {}) {
6745
7395
  });
6746
7396
  }
6747
7397
  catch (fanOutErr) {
6748
- // Graceful detach (DEV-331): stdout stays parseable — settled members
7398
+ // Graceful detach: stdout stays parseable — settled members
6749
7399
  // keep their real status, unfinished ones are marked running — and the
6750
7400
  // honest stderr line names every runId still executing (and billing).
6751
7401
  if (fanOutErr instanceof InterruptError) {
@@ -6754,8 +7404,10 @@ export async function runTestRunAll(opts, deps = {}) {
6754
7404
  const partialResults = pollable.map((e) => settled.get(e.runId) ?? { testId: e.testId, runId: e.runId, status: 'running' });
6755
7405
  out.print({ accepted: partialResults, conflicts, deferred, skippedFrontend, skippedIntegration }, () => partialResults.map(r => `${r.runId} ${r.status}`).join('\n'));
6756
7406
  const unfinished = pollable.filter(e => !settled.has(e.runId)).map(e => e.runId);
6757
- if (unfinished.length > 0)
7407
+ if (unfinished.length > 0) {
7408
+ fanOutErr.runWaitContext = true;
6758
7409
  stderrFn(interruptDetachMessage(fanOutErr, unfinished));
7410
+ }
6759
7411
  }
6760
7412
  throw fanOutErr;
6761
7413
  }
@@ -6785,13 +7437,21 @@ export async function runTestRunAll(opts, deps = {}) {
6785
7437
  const freshNameMap = opts.report === 'junit' && opts.reportFile !== undefined
6786
7438
  ? await buildTestNameMap(client, opts.projectId)
6787
7439
  : undefined;
6788
- await writeBatchJUnitReportIfRequested(opts, freshRunResults, freshNameMap);
7440
+ const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
7441
+ await writeBatchJUnitReportIfRequested(opts, [...freshRunResults, ...skippedJUnitResultsFromSummary(ciSummary)], freshNameMap);
6789
7442
  out.print(jsonPayload);
7443
+ recordBatchOutcome({
7444
+ accepted: accepted.length,
7445
+ conflicts,
7446
+ deferred: deferred.length,
7447
+ skipped: skippedFrontend.length + skippedIntegration.length,
7448
+ results: freshRunResults,
7449
+ });
6790
7450
  // CI-native output layer (issue #99): emitted before the gate throws below so
6791
7451
  // the artifacts land even when the batch exits non-zero. The summary file is a
6792
7452
  // machine artifact written regardless of --output mode; stdout stays owned by
6793
7453
  // the envelope above (plus Actions workflow commands, which Actions parses).
6794
- emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(jsonPayload)), opts, {
7454
+ emitCiArtifacts(ciSummary, opts, {
6795
7455
  env: deps.env ?? process.env,
6796
7456
  stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
6797
7457
  stderr: stderrFn,
@@ -6809,6 +7469,15 @@ export async function runTestRunAll(opts, deps = {}) {
6809
7469
  const failure = resolveWaitFailure(freshRunResults, { timeoutSeconds: opts.timeoutSeconds });
6810
7470
  if (failure)
6811
7471
  throw failure;
7472
+ // Nothing of ours dispatched (the poll set was auto-resumed in-flight runs
7473
+ // only) and every remaining conflict is a credits refusal → exit 12, the same
7474
+ // shape the single-run route answers.
7475
+ if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
7476
+ throw insufficientCreditsConflictError(conflicts, batchApiUrl);
7477
+ }
7478
+ if (isPausedRefusal({ accepted, deferred, conflicts })) {
7479
+ throw pausedConflictError(conflicts, batchApiUrl);
7480
+ }
6812
7481
  // Hard conflicts (a run already in flight for the test that we could NOT
6813
7482
  // auto-resume — no `currentRunId` to poll) mean those tests never ran. In a
6814
7483
  // MIXED batch, the accepted/resumed runs above already made `pollable`
@@ -6819,11 +7488,22 @@ export async function runTestRunAll(opts, deps = {}) {
6819
7488
  // all-conflict path returns. `conflicts` here holds only the hard ones —
6820
7489
  // resumable conflicts were split into the poll set above.
6821
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) : '';
6822
7500
  throw ApiError.fromEnvelope({
6823
7501
  error: {
6824
7502
  code: 'CONFLICT',
6825
- message: `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight and could not be resumed — not run.`,
6826
- 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}`,
6827
7507
  requestId: 'local',
6828
7508
  details: { conflicts: conflicts.map(c => c.testId) },
6829
7509
  },
@@ -6836,6 +7516,614 @@ export async function runTestRunAll(opts, deps = {}) {
6836
7516
  // fan-out is for exit-code logic only and is not part of the returned type.
6837
7517
  return { ...batchResp, accepted, deferred, conflicts };
6838
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
+ }
6839
8127
  /**
6840
8128
  * `test rerun` — M3.4 piece-3.
6841
8129
  *
@@ -6852,6 +8140,7 @@ export async function runTestRunAll(opts, deps = {}) {
6852
8140
  */
6853
8141
  export async function runTestRerun(opts, deps = {}) {
6854
8142
  assertIdempotencyKey(opts.idempotencyKey);
8143
+ const environment = normalizeEnvironmentName(opts.environment);
6855
8144
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
6856
8145
  const out = makeOutput(opts.output, deps);
6857
8146
  // -------------------------------------------------------------------------
@@ -6893,6 +8182,13 @@ export async function runTestRerun(opts, deps = {}) {
6893
8182
  throw localValidationError('skip-terminal', '--skip-terminal only applies with --all (it narrows which project tests get reran). ' +
6894
8183
  'Remove --skip-terminal, or add --all --project <id>.');
6895
8184
  }
8185
+ // --allow-empty only softens the --all zero-dispatch gate; anywhere else it
8186
+ // would be silently ignored — reject loudly, matching the sibling --all-only
8187
+ // flag guards above.
8188
+ if (opts.allowEmpty === true && !opts.all) {
8189
+ throw localValidationError('allow-empty', '--allow-empty only applies with --all (it permits an empty resolved rerun set). ' +
8190
+ 'Remove --allow-empty, or add --all --project <id>.');
8191
+ }
6896
8192
  if (!Number.isInteger(opts.maxConcurrency) ||
6897
8193
  opts.maxConcurrency < 1 ||
6898
8194
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
@@ -6923,6 +8219,7 @@ export async function runTestRerun(opts, deps = {}) {
6923
8219
  source: 'cli',
6924
8220
  autoHeal: effectiveAutoHeal,
6925
8221
  skipDependencies: opts.skipDependencies,
8222
+ ...(environment !== undefined ? { environment } : {}),
6926
8223
  },
6927
8224
  idempotencyKey,
6928
8225
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
@@ -6940,6 +8237,7 @@ export async function runTestRerun(opts, deps = {}) {
6940
8237
  testIds,
6941
8238
  autoHeal: effectiveAutoHeal,
6942
8239
  skipDependencies: opts.skipDependencies,
8240
+ ...(environment !== undefined ? { environment } : {}),
6943
8241
  },
6944
8242
  idempotencyKey,
6945
8243
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
@@ -6956,6 +8254,7 @@ export async function runTestRerun(opts, deps = {}) {
6956
8254
  // D4: under --wait, raise the per-request timeout to cover --timeout so a
6957
8255
  // slow rerun trigger / long-poll under load isn't cut at the 120s default.
6958
8256
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
8257
+ // `--env` gate — see `runTestRun`. Before the type probe and every dispatch.
6959
8258
  const idempotencyKey = opts.idempotencyKey ?? `cli-rerun-${randomUUID()}`;
6960
8259
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
6961
8260
  stderrFn(`idempotency-key: ${idempotencyKey}`);
@@ -6983,7 +8282,9 @@ export async function runTestRerun(opts, deps = {}) {
6983
8282
  effectiveAutoHeal = false;
6984
8283
  }
6985
8284
  }
6986
- catch {
8285
+ catch (err) {
8286
+ if (err instanceof InterruptError)
8287
+ throw err;
6987
8288
  // Best-effort: don't fail on a lookup error; server will gate anyway.
6988
8289
  }
6989
8290
  }
@@ -6996,6 +8297,7 @@ export async function runTestRerun(opts, deps = {}) {
6996
8297
  // omitting the key on opt-out silently discarded --no-auto-heal.
6997
8298
  autoHeal: effectiveAutoHeal,
6998
8299
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
8300
+ ...(environment !== undefined ? { environment } : {}),
6999
8301
  }, { idempotencyKey });
7000
8302
  }
7001
8303
  catch (err) {
@@ -7034,11 +8336,18 @@ export async function runTestRerun(opts, deps = {}) {
7034
8336
  // Print auto-heal advisory.
7035
8337
  // CLI path: auto-heal is default-on for FE reruns (--no-auto-heal to opt
7036
8338
  // out). Free and paid CLI callers both get auto-heal; backend no longer
7037
- // tier-gates for source='cli'. The rerun itself is billed at 0.5 credits
7038
- // regardless of whether heal engages (same as a fresh run; legacy V2
7039
- // accounts: a verbatim replay pass is free). A heal engage costs an
7040
- // additional 0.2 credits on top of that, charged only when Phase-2 heal
7041
- // 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.
7042
8351
  //
7043
8352
  // Defensive branch: if the server still echoes autoHeal:false after we sent
7044
8353
  // autoHeal:true, the server did not apply it (unexpected; may happen on
@@ -7061,7 +8370,9 @@ export async function runTestRerun(opts, deps = {}) {
7061
8370
  ` If this was unexpected, check your balance with \`testsprite usage\`.`);
7062
8371
  }
7063
8372
  else if (rerunResp.autoHeal) {
7064
- 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\`.`);
7065
8376
  }
7066
8377
  // Server advisory: the autoHeal opt-out was forwarded to the execution
7067
8378
  // engine but is not yet enforced there. Present only on a V3-routed
@@ -7144,7 +8455,7 @@ export async function runTestRerun(opts, deps = {}) {
7144
8455
  }
7145
8456
  // Preserve the two intentional whole-fan-out aborts: each has a
7146
8457
  // dedicated outer-catch branch (RequestTimeoutError → all-running
7147
- // partial + re-attach hints + exit 7; InterruptError → DEV-331
8458
+ // partial + re-attach hints + exit 7; InterruptError →
7148
8459
  // graceful detach). Re-throw so the fan-out's `.catch(reject)` fires.
7149
8460
  if (err instanceof RequestTimeoutError || err instanceof InterruptError)
7150
8461
  throw err;
@@ -7281,8 +8592,8 @@ export async function runTestRerun(opts, deps = {}) {
7281
8592
  stderrFn(rateLimitedDetachMessage(fanOutErr, closureMembers.map(m => m.runId)));
7282
8593
  throw fanOutErr;
7283
8594
  }
7284
- // Graceful detach (DEV-331): same partial shape as the timeout path —
7285
- // 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.
7286
8597
  if (fanOutErr instanceof InterruptError) {
7287
8598
  ticker.finalize(`Closure fan-out — interrupted (${fanOutErr.signal})`);
7288
8599
  const dispatchedRunIds = closureMembers.map(m => ({
@@ -7295,6 +8606,7 @@ export async function runTestRerun(opts, deps = {}) {
7295
8606
  .map(m => `${m.role.padEnd(9)} ${m.testId} (runId: ${m.runId}) — running`)
7296
8607
  .join('\n'));
7297
8608
  stderrFn(interruptDetachMessage(fanOutErr, closureMembers.map(m => m.runId)));
8609
+ fanOutErr.runWaitContext = true;
7298
8610
  throw fanOutErr;
7299
8611
  }
7300
8612
  throw fanOutErr;
@@ -7474,7 +8786,7 @@ export async function runTestRerun(opts, deps = {}) {
7474
8786
  stderrFn(rateLimitedDetachMessage(err, [rerunResp.runId]));
7475
8787
  throw err;
7476
8788
  }
7477
- // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
8789
+ // Graceful detach on SIGINT/SIGTERM — see runTestRun.
7478
8790
  if (err instanceof InterruptError) {
7479
8791
  ticker.finalize(`Run ${rerunResp.runId} — interrupted (${err.signal})`);
7480
8792
  const partial = { runId: rerunResp.runId, status: 'running' };
@@ -7488,6 +8800,7 @@ export async function runTestRerun(opts, deps = {}) {
7488
8800
  ].join('\n');
7489
8801
  });
7490
8802
  stderrFn(interruptDetachMessage(err, [rerunResp.runId]));
8803
+ err.runWaitContext = true;
7491
8804
  throw err;
7492
8805
  }
7493
8806
  ticker.finalize();
@@ -7496,7 +8809,7 @@ export async function runTestRerun(opts, deps = {}) {
7496
8809
  ticker.finalize(formatRunProgressLine(finalRun, Date.now() - replayStartMs, '(replay)'));
7497
8810
  // Probe the test type once (text mode only, best-effort) so a backend
7498
8811
  // rerun's card reads `n/a (backend)` even when the fallback never fired
7499
- // (BE run rows finalize server-side now) — DEV-282.
8812
+ // (BE run rows finalize server-side now).
7500
8813
  const isBackend = await resolveRunCardIsBackend(client, testId, opts.output, beFallbackUsed);
7501
8814
  out.print(withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), data => renderRunResponseText(data, { isBackend }));
7502
8815
  if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
@@ -7565,6 +8878,20 @@ export async function runTestRerun(opts, deps = {}) {
7565
8878
  if (testIds.length === 0) {
7566
8879
  stderrFn(`No tests found in project ${opts.projectId} matching filters — nothing to rerun.`);
7567
8880
  out.print({ accepted: [], deferred: [], conflicts: [], closure: { byProject: [] } });
8881
+ // Zero-dispatch: emit the CI artifacts and fail with exit 5 unless
8882
+ // --allow-empty, so a filter that matches nothing (or an empty project)
8883
+ // can't turn a rerun gate permanently green — same contract as
8884
+ // `test run --all`. Returns here only under
8885
+ // --allow-empty.
8886
+ await finishZeroDispatchBatch({
8887
+ reason: `no tests in project ${opts.projectId} match the requested filters`,
8888
+ skipped: [],
8889
+ allowEmpty: opts.allowEmpty === true,
8890
+ opts,
8891
+ deps,
8892
+ stderrFn,
8893
+ label: 'rerun',
8894
+ });
7568
8895
  return undefined;
7569
8896
  }
7570
8897
  stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${opts.projectId} for batch rerun.`);
@@ -7608,6 +8935,7 @@ export async function runTestRerun(opts, deps = {}) {
7608
8935
  // opt-out — see the matching comment on the single-rerun call site.
7609
8936
  autoHeal: effectiveAutoHeal,
7610
8937
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
8938
+ ...(environment !== undefined ? { environment } : {}),
7611
8939
  }, { idempotencyKey: chunkKey });
7612
8940
  chunkResponses.push(chunkResp);
7613
8941
  }
@@ -7638,10 +8966,8 @@ export async function runTestRerun(opts, deps = {}) {
7638
8966
  // polled under --wait, more than once) and `closure.byProject` entries
7639
8967
  // sharing a projectId are merged rather than left as separate per-chunk
7640
8968
  // entries.
7641
- const { deduped: dedupedAccepted, droppedCount: duplicateAcceptedCount } = dedupeBatchRerunAccepted(chunkResponses.flatMap(r => r.accepted));
7642
- if (duplicateAcceptedCount > 0) {
7643
- 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.`);
7644
- }
8969
+ const { deduped: dedupedAccepted, dropped: duplicateAccepted } = dedupeBatchRerunAccepted(chunkResponses.flatMap(r => r.accepted));
8970
+ warnDroppedDuplicateRuns(dedupedAccepted, duplicateAccepted, stderrFn);
7645
8971
  const batchResp = {
7646
8972
  accepted: dedupedAccepted,
7647
8973
  deferred: chunkResponses.flatMap(r => r.deferred),
@@ -7680,7 +9006,7 @@ export async function runTestRerun(opts, deps = {}) {
7680
9006
  summaryParts[0] += ` (${addedProducersTotal} BE producer${addedProducersTotal !== 1 ? 's' : ''} auto-added)`;
7681
9007
  }
7682
9008
  if (conflicts.length > 0) {
7683
- 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)) : ''}`);
7684
9010
  }
7685
9011
  if (deferred.length > 0) {
7686
9012
  summaryParts.push(`${deferred.length} rate-deferred`);
@@ -7784,10 +9110,12 @@ export async function runTestRerun(opts, deps = {}) {
7784
9110
  }
7785
9111
  }
7786
9112
  catch (err) {
9113
+ if (err instanceof InterruptError)
9114
+ throw err;
7787
9115
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
7788
9116
  break;
7789
9117
  }
7790
- const { deduped: newlyAccepted, droppedCount: newlyDuplicateCount } = dedupeBatchRerunAccepted(retryChunkResponses.flatMap(r => r.accepted));
9118
+ const { deduped: newlyAccepted, dropped: newlyDuplicate } = dedupeBatchRerunAccepted(retryChunkResponses.flatMap(r => r.accepted));
7791
9119
  const newlyDeferred = retryChunkResponses.flatMap(r => r.deferred);
7792
9120
  const newlyConflicted = retryChunkResponses.flatMap(r => r.conflicts);
7793
9121
  // [P2] Collect notFound[] from the retry response. A deferred test may be
@@ -7801,12 +9129,14 @@ export async function runTestRerun(opts, deps = {}) {
7801
9129
  if (newlyAdvisories.length > 0) {
7802
9130
  advisories = dedupeRerunAdvisories(advisories.concat(newlyAdvisories));
7803
9131
  }
7804
- if (newlyDuplicateCount > 0) {
7805
- 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.`);
7806
- }
9132
+ warnDroppedDuplicateRuns(newlyAccepted, newlyDuplicate, stderrFn);
7807
9133
  if (newlyAccepted.length > 0) {
7808
9134
  stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyAccepted.length} test${newlyAccepted.length !== 1 ? 's' : ''} now accepted.`);
7809
- 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);
7810
9140
  }
7811
9141
  if (newlyConflicted.length > 0) {
7812
9142
  // [P1] Merge retry-returned conflicts into the running conflicts collection
@@ -7832,6 +9162,21 @@ export async function runTestRerun(opts, deps = {}) {
7832
9162
  }
7833
9163
  }
7834
9164
  }
9165
+ /**
9166
+ * Every requested id landed in `notFound` and nothing was queued. A rerun
9167
+ * where every id was unusable is not a success: exit 4 (NOT_FOUND), the same
9168
+ * code `testlist run` uses for a `--case` miss, instead of the silent exit 0
9169
+ * that made a CI gate pass green on zero dispatched runs.
9170
+ */
9171
+ const rerunAllNotFoundError = (ids) => ApiError.fromEnvelope({
9172
+ error: {
9173
+ code: 'NOT_FOUND',
9174
+ message: `Batch rerun: nothing was queued — ${ids.length} test id${ids.length !== 1 ? 's have' : ' has'} no replayable run.`,
9175
+ nextAction: `Trigger a first (fresh) run instead: testsprite test run <id> — ids: ${ids.join(' ')}`,
9176
+ requestId: 'local',
9177
+ details: { notFound: [...ids] },
9178
+ },
9179
+ });
7835
9180
  // Print the (deduped) advisory set once, after any D3 retries have
7836
9181
  // had a chance to contribute one, not once per chunk/attempt.
7837
9182
  emitRerunAdvisories(stderrFn, advisories);
@@ -7842,6 +9187,15 @@ export async function runTestRerun(opts, deps = {}) {
7842
9187
  if (deferred.length > 0) {
7843
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);
7844
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
+ }
7845
9199
  // Fix C: all-conflict no-op (no --wait path)
7846
9200
  if (accepted.length === 0 && conflicts.length > 0) {
7847
9201
  // codex P2: don't claim "all in flight" when some ids were also notFound —
@@ -7850,8 +9204,13 @@ export async function runTestRerun(opts, deps = {}) {
7850
9204
  throw ApiError.fromEnvelope({
7851
9205
  error: {
7852
9206
  code: 'CONFLICT',
7853
- message: `Batch rerun: nothing was queued — ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight${notFound.length > 0 ? `, ${notFound.length} not found` : ''}.`,
7854
- 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))}`,
7855
9214
  requestId: 'local',
7856
9215
  details: {
7857
9216
  conflicts: conflicts.map(c => ({ testId: c.testId, currentRunId: c.currentRunId })),
@@ -7860,6 +9219,12 @@ export async function runTestRerun(opts, deps = {}) {
7860
9219
  },
7861
9220
  });
7862
9221
  }
9222
+ // All-notFound no-op: every id was unusable (no replayable run), nothing
9223
+ // was queued — exit 4, matching `testlist run`'s not-found gate, instead of
9224
+ // the silent exit 0 that let a rerun gate pass green on zero runs.
9225
+ if (accepted.length === 0 && notFound.length > 0) {
9226
+ throw rerunAllNotFoundError(notFound);
9227
+ }
7863
9228
  // [P2] Return post-retry state including merged notFound.
7864
9229
  return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
7865
9230
  }
@@ -7881,6 +9246,14 @@ export async function runTestRerun(opts, deps = {}) {
7881
9246
  throw new CLIError(`Batch rerun: no tests were accepted (${deferred.length} deferred). ` +
7882
9247
  `Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
7883
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
+ }
7884
9257
  // Fix C: all-conflict no-op (--wait path)
7885
9258
  if (conflicts.length > 0) {
7886
9259
  // codex P2: mixed conflicts+notFound (no accepted runs) must not be
@@ -7888,8 +9261,10 @@ export async function runTestRerun(opts, deps = {}) {
7888
9261
  throw ApiError.fromEnvelope({
7889
9262
  error: {
7890
9263
  code: 'CONFLICT',
7891
- message: `Batch rerun: nothing was queued — ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight${notFound.length > 0 ? `, ${notFound.length} not found` : ''}.`,
7892
- 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))}`,
7893
9268
  requestId: 'local',
7894
9269
  details: {
7895
9270
  conflicts: conflicts.map(c => ({ testId: c.testId, currentRunId: c.currentRunId })),
@@ -7898,6 +9273,12 @@ export async function runTestRerun(opts, deps = {}) {
7898
9273
  },
7899
9274
  });
7900
9275
  }
9276
+ // All-notFound no-op (--wait path): the CI artifacts above already carry the
9277
+ // not_found rows as `skipped`; the exit code must agree that nothing ran —
9278
+ // exit 4 instead of the silent exit 0 measured before this fix.
9279
+ if (notFound.length > 0) {
9280
+ throw rerunAllNotFoundError(notFound);
9281
+ }
7901
9282
  // [P2] Return post-retry state including merged notFound.
7902
9283
  return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
7903
9284
  }
@@ -7957,7 +9338,7 @@ export async function runTestRerun(opts, deps = {}) {
7957
9338
  }
7958
9339
  // Interrupt must reject the fan-out (the collect point below prints the
7959
9340
  // partial for every dispatched run), never flatten into a per-member
7960
- // outcome that would swallow the 128+signum exit (DEV-331).
9341
+ // outcome that would swallow the 128+signum exit.
7961
9342
  if (err instanceof InterruptError)
7962
9343
  throw err;
7963
9344
  if (err instanceof RequestTimeoutError) {
@@ -7984,7 +9365,7 @@ export async function runTestRerun(opts, deps = {}) {
7984
9365
  testId: entry.testId,
7985
9366
  runId: entry.runId,
7986
9367
  status: 'error',
7987
- error: { code: err.code, message: err.message, exitCode: err.exitCode },
9368
+ error: waitMemberError(err),
7988
9369
  };
7989
9370
  }
7990
9371
  throw err;
@@ -8016,7 +9397,7 @@ export async function runTestRerun(opts, deps = {}) {
8016
9397
  });
8017
9398
  }
8018
9399
  catch (fanOutErr) {
8019
- // Graceful detach (DEV-331): stdout stays parseable — settled members
9400
+ // Graceful detach: stdout stays parseable — settled members
8020
9401
  // keep their real status, unfinished ones are marked running — and the
8021
9402
  // honest stderr line names every runId still executing (and billing).
8022
9403
  if (fanOutErr instanceof InterruptError) {
@@ -8025,8 +9406,10 @@ export async function runTestRerun(opts, deps = {}) {
8025
9406
  const partialResults = accepted.map((e) => settled.get(e.runId) ?? { testId: e.testId, runId: e.runId, status: 'running' });
8026
9407
  out.print({ accepted: partialResults, deferred, conflicts, notFound }, () => partialResults.map(r => `${r.runId} ${r.status}`).join('\n'));
8027
9408
  const unfinished = accepted.filter(e => !settled.has(e.runId)).map(e => e.runId);
8028
- if (unfinished.length > 0)
9409
+ if (unfinished.length > 0) {
9410
+ fanOutErr.runWaitContext = true;
8029
9411
  stderrFn(interruptDetachMessage(fanOutErr, unfinished));
9412
+ }
8030
9413
  }
8031
9414
  throw fanOutErr;
8032
9415
  }
@@ -8263,6 +9646,8 @@ export async function runArtifactGet(opts, deps = {}) {
8263
9646
  dir: resolvedDir,
8264
9647
  failedOnly: opts.failedOnly,
8265
9648
  fetchImpl: deps.fetchImpl,
9649
+ shutdownSignal: shutdownOf(deps).signal,
9650
+ shutdown: shutdownOf(deps),
8266
9651
  });
8267
9652
  if (opts.output === 'json') {
8268
9653
  out.print({
@@ -8316,10 +9701,11 @@ function renderArtifactGetWrittenText(data) {
8316
9701
  * test, so the probe is a heuristic, not a guarantee — hence the full
8317
9702
  * opt-out.
8318
9703
  */
8319
- 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 ' +
8320
9705
  'from the Lambda that executes the test, so it can occasionally be wrong (e.g. an IP allowlist ' +
8321
9706
  'that permits the Lambda but not this machine); use this flag when you know better. Zero network ' +
8322
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";
8323
9709
  export function createTestCommand(deps = {}) {
8324
9710
  const test = new Command('test').description('Inspect TestSprite tests');
8325
9711
  test
@@ -8334,7 +9720,7 @@ export function createTestCommand(deps = {}) {
8334
9720
  .option('--project <id>', 'project id (returned by `testsprite project list`)')
8335
9721
  .option('--type <type>', 'filter by test type (frontend|backend)')
8336
9722
  .option('--created-from <source>', 'filter by where the test was authored (portal|mcp|cli)')
8337
- .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')
8338
9724
  .option('--page-size <n>', 'service page-size hint (1-100, default 25)')
8339
9725
  .option('--starting-token <token>', 'opaque cursor from a previous list response')
8340
9726
  .option('--cursor <token>', 'alias for --starting-token; accepted for parity with `test result --history`')
@@ -8352,7 +9738,7 @@ export function createTestCommand(deps = {}) {
8352
9738
  // `test result --history`). --starting-token takes precedence if
8353
9739
  // both are supplied (prevents accidental override).
8354
9740
  await runList({
8355
- ...resolveCommonOptions(command),
9741
+ ...resolveCommonOptions(command, deps.env),
8356
9742
  projectId: cmdOpts.project,
8357
9743
  type: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES),
8358
9744
  createdFrom: parseEnumFlag(cmdOpts.createdFrom, 'created-from', CREATED_FROMS),
@@ -8369,11 +9755,11 @@ export function createTestCommand(deps = {}) {
8369
9755
  .description('Get a test by id')
8370
9756
  .addHelpText('after', GLOBAL_OPTS_HINT)
8371
9757
  .action(async (testId, _cmdOpts, command) => {
8372
- await runGet({ ...resolveCommonOptions(command), testId }, deps);
9758
+ await runGet({ ...resolveCommonOptions(command, deps.env), testId }, deps);
8373
9759
  });
8374
9760
  test
8375
9761
  .command('create')
8376
- .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)')
8377
9763
  .option('--project <id>', 'project id (returned by `testsprite project list`)')
8378
9764
  .option('--type <type>', 'frontend|backend')
8379
9765
  .option('--name <name>', 'human-readable test name (becomes `title` in storage)')
@@ -8388,26 +9774,28 @@ export function createTestCommand(deps = {}) {
8388
9774
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
8389
9775
  .option('--wait', 'with --run, poll until terminal status', false)
8390
9776
  .option('--timeout <s>', 'with --run --wait, max seconds to wait')
8391
- .option('--target-url <url>', 'with --run, override the project default env URL. Before triggering, a reachability ' +
8392
- 'preflight refuses obviously-dead targets (DNS failure, connection refused, a 502/503/504 ' +
8393
- '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')
8394
9779
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
8395
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.')
8396
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], [])
8397
9782
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Use to declare upstream producer dependencies.', (val, prev) => [...(prev ?? []), val], [])
8398
9783
  .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
8399
9784
  .addHelpText('after', PLAN_TEMPLATE_HELP_TEXT)
8400
- .addHelpText('after', '\nBE dependency authoring (M4):\n' +
9785
+ .addHelpText('after', '\nBE dependency authoring:\n' +
8401
9786
  ' --produces/--needs drive wave ordering on `test rerun` + `test run --all`.\n' +
8402
9787
  ' --category teardown marks a final-wave cleanup test.\n' +
8403
9788
  ' These flags are backend-only; supplying with --type frontend is an error (exit 5).')
8404
9789
  .addHelpText('after', GLOBAL_OPTS_HINT)
8405
9790
  .action(async (cmdOpts, command) => {
9791
+ if (cmdOpts.env !== undefined && cmdOpts.run !== true) {
9792
+ throw localValidationError('env', '--env requires --run');
9793
+ }
8406
9794
  // Pure-local, no network/credentials, no other flag is
8407
9795
  // consulted. Checked first so `--plan-template` never trips the
8408
9796
  // --plan-from/--code-file mutual-exclusivity guard below.
8409
9797
  if (cmdOpts.planTemplate === true) {
8410
- runPlanTemplate(resolveCommonOptions(command), deps);
9798
+ runPlanTemplate(resolveCommonOptions(command, deps.env), deps);
8411
9799
  return;
8412
9800
  }
8413
9801
  // --plan-from and --code-file are mutually exclusive. Dispatch
@@ -8450,7 +9838,7 @@ export function createTestCommand(deps = {}) {
8450
9838
  if (cmdOpts.stepTimeout !== undefined)
8451
9839
  ignored.push('--step-timeout');
8452
9840
  await runCreateFromPlan({
8453
- ...resolveCommonOptions(command),
9841
+ ...resolveCommonOptions(command, deps.env),
8454
9842
  planFrom: cmdOpts.planFrom,
8455
9843
  run: cmdOpts.run === true,
8456
9844
  wait: cmdOpts.wait === true,
@@ -8458,6 +9846,7 @@ export function createTestCommand(deps = {}) {
8458
9846
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
8459
9847
  timeoutIsDefault: cmdOpts.timeout === undefined,
8460
9848
  targetUrl: cmdOpts.targetUrl,
9849
+ environment: cmdOpts.env,
8461
9850
  skipPreflight: cmdOpts.skipPreflight === true,
8462
9851
  idempotencyKey: cmdOpts.idempotencyKey,
8463
9852
  ignoredFlags: ignored,
@@ -8465,7 +9854,7 @@ export function createTestCommand(deps = {}) {
8465
9854
  return;
8466
9855
  }
8467
9856
  await runCreate({
8468
- ...resolveCommonOptions(command),
9857
+ ...resolveCommonOptions(command, deps.env),
8469
9858
  projectId: cmdOpts.project,
8470
9859
  type: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES),
8471
9860
  name: cmdOpts.name,
@@ -8481,6 +9870,7 @@ export function createTestCommand(deps = {}) {
8481
9870
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
8482
9871
  timeoutIsDefault: cmdOpts.timeout === undefined,
8483
9872
  targetUrl: cmdOpts.targetUrl,
9873
+ environment: cmdOpts.env,
8484
9874
  skipPreflight: cmdOpts.skipPreflight === true,
8485
9875
  // M4 piece-2: BE dependency authoring flags.
8486
9876
  // Commander variadic collectors initialise to [] — treat empty array as undefined
@@ -8496,18 +9886,18 @@ export function createTestCommand(deps = {}) {
8496
9886
  .option('--plans <path>', 'JSONL file with one plan-from spec per line (≤ 50 specs, ≤ 5 MB)')
8497
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.')
8498
9888
  .option('--run', 'after create, trigger each created test as a run', false)
8499
- .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.`)
8500
9891
  .option('--wait', 'with --run, poll each run until terminal status', false)
8501
9892
  .option('--timeout <s>', 'with --run --wait, per-run max seconds to wait (1-3600, default 600)')
8502
- .option('--target-url <url>', 'with --run, override the project default env URL for each run. Before the fan-out, a ' +
8503
- 'reachability preflight refuses an obviously-dead target ONCE for the whole batch (DNS ' +
8504
- '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')
8505
9895
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
8506
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.')
8507
9897
  .addHelpText('after', GLOBAL_OPTS_HINT)
8508
9898
  .action(async (cmdOpts, command) => {
8509
9899
  await runCreateBatch({
8510
- ...resolveCommonOptions(command),
9900
+ ...resolveCommonOptions(command, deps.env),
8511
9901
  plans: cmdOpts.plans,
8512
9902
  planFromDir: cmdOpts.planFromDir,
8513
9903
  run: cmdOpts.run === true,
@@ -8515,6 +9905,7 @@ export function createTestCommand(deps = {}) {
8515
9905
  wait: cmdOpts.wait === true,
8516
9906
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
8517
9907
  targetUrl: cmdOpts.targetUrl,
9908
+ environment: cmdOpts.env,
8518
9909
  skipPreflight: cmdOpts.skipPreflight === true,
8519
9910
  idempotencyKey: cmdOpts.idempotencyKey,
8520
9911
  }, deps);
@@ -8532,7 +9923,7 @@ export function createTestCommand(deps = {}) {
8532
9923
  .addHelpText('after', GLOBAL_OPTS_HINT)
8533
9924
  .action(async (cmdOpts, command) => {
8534
9925
  await runScaffold({
8535
- ...resolveCommonOptions(command),
9926
+ ...resolveCommonOptions(command, deps.env),
8536
9927
  scaffoldType: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES) ?? 'frontend',
8537
9928
  out: cmdOpts.out,
8538
9929
  force: cmdOpts.force === true,
@@ -8545,7 +9936,7 @@ export function createTestCommand(deps = {}) {
8545
9936
  .addHelpText('after', GLOBAL_OPTS_HINT)
8546
9937
  .action(async (testId, cmdOpts, command) => {
8547
9938
  await runOpen({
8548
- ...resolveCommonOptions(command),
9939
+ ...resolveCommonOptions(command, deps.env),
8549
9940
  testId,
8550
9941
  noBrowser: cmdOpts.browser === false,
8551
9942
  }, deps);
@@ -8560,7 +9951,7 @@ export function createTestCommand(deps = {}) {
8560
9951
  .addHelpText('after', GLOBAL_OPTS_HINT)
8561
9952
  .action(async (testId, cmdOpts, command) => {
8562
9953
  await runSteps({
8563
- ...resolveCommonOptions(command),
9954
+ ...resolveCommonOptions(command, deps.env),
8564
9955
  testId,
8565
9956
  pageSize: parseNumericFlag(cmdOpts.pageSize, 'page-size'),
8566
9957
  startingToken: cmdOpts.startingToken,
@@ -8573,7 +9964,7 @@ export function createTestCommand(deps = {}) {
8573
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.')
8574
9965
  .addHelpText('after', GLOBAL_OPTS_HINT)
8575
9966
  .action(async (runA, runB, _cmdOpts, command) => {
8576
- await runDiff({ ...resolveCommonOptions(command), runA, runB }, deps);
9967
+ await runDiff({ ...resolveCommonOptions(command, deps.env), runA, runB }, deps);
8577
9968
  });
8578
9969
  test
8579
9970
  .command('lint')
@@ -8585,7 +9976,7 @@ export function createTestCommand(deps = {}) {
8585
9976
  .addHelpText('after', GLOBAL_OPTS_HINT)
8586
9977
  .action(async (cmdOpts, command) => {
8587
9978
  await runLint({
8588
- ...resolveCommonOptions(command),
9979
+ ...resolveCommonOptions(command, deps.env),
8589
9980
  planFrom: cmdOpts.planFrom,
8590
9981
  planFromDir: cmdOpts.planFromDir,
8591
9982
  plans: cmdOpts.plans,
@@ -8597,10 +9988,10 @@ export function createTestCommand(deps = {}) {
8597
9988
  .description('Get the latest result for a test (default) or list prior runs (--history).\n' +
8598
9989
  '\n--output json shape differs by mode:\n' +
8599
9990
  ' (default) single CliLatestResult object\n' +
8600
- ' --history { runs: RunHistoryItem[], nextCursor: string|null }\n' +
9991
+ ' --history { runs: RunHistoryItem[], nextCursor: string|null, meta: RunHistoryMeta }\n' +
8601
9992
  '\nPer-run detail: testsprite test wait <run-id>\n' +
8602
9993
  'Failure bundle: testsprite test artifact get <run-id>')
8603
- .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)
8604
9995
  .option('--history', 'list prior runs for this test instead of showing the latest result')
8605
9996
  .option('--source <src>', `with --history: filter by trigger source (${RUN_SOURCES.join('|')})`)
8606
9997
  .option('--since <dur>', 'with --history: lower bound on createdAt — 24h, 7d, or ISO timestamp (client-side translated)')
@@ -8608,17 +9999,24 @@ export function createTestCommand(deps = {}) {
8608
9999
  .option('--cursor <token>', 'with --history: opaque cursor from a prior page')
8609
10000
  .option('--rerun', 'with --history: show only reruns')
8610
10001
  .option('--no-rerun', 'with --history: show only fresh (non-rerun) runs')
10002
+ .option('--env <name>', 'with --history: only runs whose credentials came from this project environment')
8611
10003
  .option('--columns <list>', 'with --history: select/reorder text table columns')
8612
10004
  .option('--no-header', 'with --history: suppress the text table header row')
8613
10005
  .addHelpText('after', GLOBAL_OPTS_HINT)
8614
10006
  .action(async (testId, cmdOpts, command) => {
10007
+ // `--env` narrows the history list; on the latest-result path it would be
10008
+ // silently ignored (same rule as `test run --filter` without `--all`).
10009
+ if (cmdOpts.env !== undefined && !cmdOpts.history) {
10010
+ throw localValidationError('env', '--env only applies with --history (it filters the run list by environment). Add --history, or remove --env');
10011
+ }
8615
10012
  if (cmdOpts.history) {
8616
10013
  // M3.4 piece-5: --history mode — list prior runs.
8617
10014
  await runResultHistory({
8618
- ...resolveCommonOptions(command),
10015
+ ...resolveCommonOptions(command, deps.env),
8619
10016
  testId,
8620
10017
  source: parseEnumFlag(cmdOpts.source, 'source', RUN_SOURCES),
8621
10018
  since: cmdOpts.since,
10019
+ environment: cmdOpts.env,
8622
10020
  pageSize: cmdOpts.pageSize !== undefined
8623
10021
  ? parseNumericFlag(cmdOpts.pageSize, 'page-size')
8624
10022
  : undefined,
@@ -8631,7 +10029,7 @@ export function createTestCommand(deps = {}) {
8631
10029
  else {
8632
10030
  // M2 mode: latest result (byte-identical to pre-piece-5 behavior).
8633
10031
  await runResult({
8634
- ...resolveCommonOptions(command),
10032
+ ...resolveCommonOptions(command, deps.env),
8635
10033
  testId,
8636
10034
  includeAnalysis: cmdOpts.includeAnalysis === true,
8637
10035
  }, deps);
@@ -8655,7 +10053,7 @@ export function createTestCommand(deps = {}) {
8655
10053
  throw localValidationError('step-timeout', '--step-timeout and --clear-step-timeout are mutually exclusive');
8656
10054
  }
8657
10055
  await runUpdate({
8658
- ...resolveCommonOptions(command),
10056
+ ...resolveCommonOptions(command, deps.env),
8659
10057
  testId,
8660
10058
  name: cmdOpts.name,
8661
10059
  description: cmdOpts.description,
@@ -8670,13 +10068,13 @@ export function createTestCommand(deps = {}) {
8670
10068
  });
8671
10069
  test
8672
10070
  .command('delete <test-id>')
8673
- .description('Permanently delete a test. Requires --confirm. (M3.2 piece-3)')
10071
+ .description('Permanently delete a test. Requires --confirm.')
8674
10072
  .option('--confirm', 'required: explicit confirmation for the destructive operation', false)
8675
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.')
8676
10074
  .addHelpText('after', GLOBAL_OPTS_HINT)
8677
10075
  .action(async (testId, cmdOpts, command) => {
8678
10076
  await runDelete({
8679
- ...resolveCommonOptions(command),
10077
+ ...resolveCommonOptions(command, deps.env),
8680
10078
  testId,
8681
10079
  confirm: cmdOpts.confirm === true,
8682
10080
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -8702,7 +10100,7 @@ export function createTestCommand(deps = {}) {
8702
10100
  .addHelpText('after', GLOBAL_OPTS_HINT)
8703
10101
  .action(async (testIdsArg, cmdOpts, command) => {
8704
10102
  await runDeleteBatch({
8705
- ...resolveCommonOptions(command),
10103
+ ...resolveCommonOptions(command, deps.env),
8706
10104
  testIds: testIdsArg ?? [],
8707
10105
  all: cmdOpts.all === true,
8708
10106
  projectId: cmdOpts.project,
@@ -8714,62 +10112,74 @@ export function createTestCommand(deps = {}) {
8714
10112
  // M3.3 piece-3 — `test run` and `test wait`
8715
10113
  // -------------------------------------------------------------------------
8716
10114
  test
8717
- .command('run [test-id]')
8718
- .description('Trigger a test run. With --wait, polls until terminal status.\n' +
8719
- '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' +
8720
10118
  '\nExit codes:\n' +
8721
10119
  ' 0 passed (or queued without --wait)\n' +
8722
10120
  ' 1 failed / blocked / cancelled\n' +
8723
10121
  ' 3 auth error\n' +
8724
10122
  ' 4 test not found\n' +
8725
- ' 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' +
8726
10124
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
8727
10125
  ' 7 timeout — resume with: testsprite test wait <run-id>, ' +
8728
10126
  'or stop it with: testsprite test cancel <run-id>\n' +
8729
10127
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
8730
- ' 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' +
8731
10130
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
8732
- '\nCtrl-C during --wait detaches only (the run keeps executing and billing);\n' +
8733
- 'stop it for real with: testsprite test cancel <run-id>')
8734
- .option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private ' +
8735
- 'IPs). Before triggering, a reachability preflight refuses an obviously-dead target (DNS ' +
8736
- 'failure, connection refused, a 502/503/504 gateway error) so a doomed run never gets ' +
8737
- 'billed. This CLI probes from wherever it runs, not from the Lambda that executes the ' +
8738
- 'test, so it is a heuristic, not a guarantee — see --skip-preflight. Note: for a backend ' +
8739
- 'test, --target-url itself is inert (its base URL is baked into its code) — but this bare ' +
8740
- "`run` command has no way to know a test's type before triggering it, so the preflight " +
8741
- '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)
8742
10134
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
8743
10135
  .option('--local <port>', 'run against an app on THIS machine, reached through a TestSprite tunnel. The test runner ' +
8744
10136
  'navigates to http://127.0.0.1:<port> and its traffic is proxied back to you for as long ' +
8745
10137
  'as this command runs. Implies --wait (the tunnel closes when the command exits, so a ' +
8746
- 'detached run could not finish) and cannot be combined with --target-url. Frontend tests ' +
8747
- '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.')
8748
10141
  .option('--local-host <host>', `with --local, which loopback address to name in the run's target URL — one of ` +
8749
10142
  `${LOOPBACK_HOSTS.join(', ')} (default ${DEFAULT_LOCAL_HOST}). Use localhost if your app ` +
8750
10143
  `only answers on that name, or ::1 for an IPv6-only listener.`)
8751
10144
  .option('--tunnel-client <id>', 'with --local, attach to a tunnel already running under `testsprite tunnel start` instead ' +
8752
10145
  'of opening a new one. The id is the non-secret handle that command prints; the tunnel ' +
8753
- '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.')
8754
10147
  .option('--no-cancel-on-interrupt', 'with --local, skip automatic cancellation when an owned tunnel is about to close or a ' +
8755
10148
  "borrowed tunnel's owner disappears. An ordinary interrupt of a borrowed run never " +
8756
10149
  'cancels it because its tunnel remains alive.')
10150
+ .option('--env <name>', 'run against the named project environment — its test-account credentials, auto-auth and ' +
10151
+ 'OTP settings (names: `testsprite project env list <project-id>`). Combine with --local ' +
10152
+ 'to use those credentials against your own machine; without --local, the run opens ' +
10153
+ "that environment's URL. Omit --env to keep using " +
10154
+ "the project's default environment. Also applies with --all.")
8757
10155
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
8758
- .option('--timeout <s>', 'with --wait, max seconds to wait (1–3600; default 600, or 1200 with --local)')
8759
- .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.')
8760
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)
8761
10159
  .option('--project <id>', 'project id (with --all, overrides TESTSPRITE_PROJECT_ID; returned by `testsprite project list`)')
8762
10160
  .option('--filter <substr>', 'with --all: only run tests whose name contains this substring (case-insensitive)')
8763
- .option('--max-concurrency <n>', `with --all --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
8764
- .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)')
8765
10163
  .option('--report-file <path>', 'output path for --report (atomic write)')
8766
10164
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
8767
- .option('--gh-output', 'with --wait (single test or --all): emit GitHub-native output (::error:: annotations per non-passed run; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
8768
- .option('--summary-file <path>', 'with --wait (single test or --all): also write the reduced machine summary JSON {total, passed, failed, 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')
8769
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')
8770
- .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' +
8771
10178
  ' testsprite test run --all --project <id> run all project tests in wave order\n' +
8772
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' +
8773
10183
  ' testsprite test run --all --filter <substr> name-glob subset (uses --project/env)\n' +
8774
10184
  ' testsprite test run --all --wait --report junit --report-file ./results.xml\n' +
8775
10185
  ' project id precedence: --project wins over TESTSPRITE_PROJECT_ID\n' +
@@ -8777,15 +10187,30 @@ export function createTestCommand(deps = {}) {
8777
10187
  '(see `testsprite test create --help` for details).\n' +
8778
10188
  '\nFrontend tests: the current unified engine runs FE tests too (they are billed\n' +
8779
10189
  'like any run). On the legacy backend-only engine FE tests cannot run — they are\n' +
8780
- "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.')
8781
10205
  .addHelpText('after', GLOBAL_OPTS_HINT)
8782
- .action(async (testIdArg, cmdOpts, command) => {
10206
+ .action(async (testIdArgs, cmdOpts, command) => {
8783
10207
  const isAll = cmdOpts.all === true;
10208
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
8784
10209
  // Mutual-exclusion: exactly one of positional <test-id> vs --all must be set.
8785
- if (testIdArg !== undefined && isAll) {
10210
+ if (testIdArgs.length > 0 && isAll) {
8786
10211
  throw localValidationError('test-id', 'positional <test-id> and --all are mutually exclusive; use one or the other');
8787
10212
  }
8788
- if (testIdArg === undefined && !isAll) {
10213
+ if (testIdArgs.length === 0 && !isAll) {
8789
10214
  throw localValidationError('test-id', 'provide a <test-id>, or use --all with --project <id> or TESTSPRITE_PROJECT_ID');
8790
10215
  }
8791
10216
  // --filter is an --all-only narrowing flag (mirrors `test rerun --filter`).
@@ -8801,9 +10226,26 @@ export function createTestCommand(deps = {}) {
8801
10226
  const localPort = cmdOpts.local !== undefined ? parseLocalPort(cmdOpts.local) : undefined;
8802
10227
  const usingLocal = localPort !== undefined;
8803
10228
  const effectiveWait = usingLocal || cmdOpts.wait === true;
8804
- if (usingLocal && isAll) {
8805
- throw localValidationError('local', '--local runs one test through one tunnel; --all fans out across a project. Run the ' +
8806
- '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
+ }
8807
10249
  }
8808
10250
  if (usingLocal && cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
8809
10251
  throw localValidationError('local', '--local and --target-url are mutually exclusive: --local runs against your own ' +
@@ -8833,7 +10275,7 @@ export function createTestCommand(deps = {}) {
8833
10275
  reportFile: cmdOpts.reportFile,
8834
10276
  reportSuiteName: cmdOpts.reportSuiteName,
8835
10277
  wait: effectiveWait,
8836
- batchPath: isAll,
10278
+ batchPath: isAll || (usingLocal && testIds.length > 1),
8837
10279
  });
8838
10280
  // --gh-output / --summary-file reduce a --wait run's terminal result into
8839
10281
  // the CI summary. They require --wait (without it the command returns after
@@ -8846,21 +10288,21 @@ export function createTestCommand(deps = {}) {
8846
10288
  if (cmdOpts.summaryFile !== undefined && !effectiveWait) {
8847
10289
  throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
8848
10290
  }
8849
- if (isAll) {
10291
+ if (isAll && !usingLocal) {
8850
10292
  // --all path: wave-ordered fresh batch run.
8851
10293
  const projectId = resolveProjectId(cmdOpts.project, deps);
8852
10294
  requireProjectId(projectId, '--all requires a project id - pass --project <id> or set TESTSPRITE_PROJECT_ID');
8853
- // --target-url has no effect on the --all batch path: a BE test's base
8854
- // URL is baked into its code, and the unified engine resolves each
8855
- // project's configured environment server-side (per-run URL overrides
8856
- // are not applied to batch FE runs either). Silently dropping it could
8857
- // run the suite against an unintended environment in the caller's mind,
8858
- // so reject loudly.
8859
- if (cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
8860
- 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).');
8861
10303
  }
8862
10304
  await runTestRunAll({
8863
- ...resolveCommonOptions(command),
10305
+ ...resolveCommonOptions(command, deps.env),
8864
10306
  projectId,
8865
10307
  nameFilter: cmdOpts.filter,
8866
10308
  wait: effectiveWait,
@@ -8874,6 +10316,18 @@ export function createTestCommand(deps = {}) {
8874
10316
  ghOutput: cmdOpts.ghOutput === true,
8875
10317
  summaryFile: cmdOpts.summaryFile,
8876
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 } : {}),
10326
+ environment: cmdOpts.env,
10327
+ ...(cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== ''
10328
+ ? { targetUrl: cmdOpts.targetUrl }
10329
+ : {}),
10330
+ skipPreflight: cmdOpts.skipPreflight === true,
8877
10331
  }, deps);
8878
10332
  return;
8879
10333
  }
@@ -8887,7 +10341,7 @@ export function createTestCommand(deps = {}) {
8887
10341
  // this command exits" is simply false there, and it is the sentence a
8888
10342
  // reader would act on: told that, someone deciding whether to background
8889
10343
  // this command concludes the wrong thing about their own tunnel.
8890
- const commonOpts = resolveCommonOptions(command);
10344
+ const commonOpts = resolveCommonOptions(command, deps.env);
8891
10345
  if (usingLocal && cmdOpts.wait !== true && commonOpts.output !== 'json') {
8892
10346
  const adopted = cmdOpts.tunnelClient !== undefined;
8893
10347
  (deps.stderr ?? ((line) => process.stderr.write(`${line}\n`)))(adopted
@@ -8896,10 +10350,38 @@ export function createTestCommand(deps = {}) {
8896
10350
  : '[advisory] --local implies --wait: the tunnel closes when this command exits, so ' +
8897
10351
  'the run is followed to a verdict rather than detached.');
8898
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
+ }
8899
10381
  // Single test-id path (unchanged M3.3 behavior).
8900
10382
  await runTestRun({
8901
10383
  ...commonOpts,
8902
- testId: testIdArg,
10384
+ testId: testIds[0],
8903
10385
  targetUrl: cmdOpts.targetUrl,
8904
10386
  skipPreflight: cmdOpts.skipPreflight === true,
8905
10387
  ...(localPort !== undefined ? { localPort } : {}),
@@ -8915,6 +10397,9 @@ export function createTestCommand(deps = {}) {
8915
10397
  idempotencyKey: cmdOpts.idempotencyKey,
8916
10398
  ghOutput: cmdOpts.ghOutput === true,
8917
10399
  summaryFile: cmdOpts.summaryFile,
10400
+ // See the matching comment on the --all path above.
10401
+ ...(cmdOpts.autoHeal === false ? { autoHeal: false } : {}),
10402
+ environment: cmdOpts.env,
8918
10403
  }, deps);
8919
10404
  });
8920
10405
  test
@@ -8948,7 +10433,7 @@ export function createTestCommand(deps = {}) {
8948
10433
  // output shape, same exit codes); two or more fan out.
8949
10434
  if (runIds.length === 1) {
8950
10435
  await runTestWait({
8951
- ...resolveCommonOptions(command),
10436
+ ...resolveCommonOptions(command, deps.env),
8952
10437
  runId: runIds[0],
8953
10438
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
8954
10439
  }, deps);
@@ -8959,7 +10444,7 @@ export function createTestCommand(deps = {}) {
8959
10444
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
8960
10445
  }
8961
10446
  await runTestWaitMany({
8962
- ...resolveCommonOptions(command),
10447
+ ...resolveCommonOptions(command, deps.env),
8963
10448
  runIds,
8964
10449
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
8965
10450
  maxConcurrency,
@@ -8976,8 +10461,8 @@ export function createTestCommand(deps = {}) {
8976
10461
  ' 0 passed (or queued without --wait)\n' +
8977
10462
  ' 1 failed / blocked / cancelled\n' +
8978
10463
  ' 3 auth error\n' +
8979
- ' 4 test not found\n' +
8980
- ' 5 validation error\n' +
10464
+ ' 4 test not found (single), or batch: nothing queued — every id had no replayable run\n' +
10465
+ ' 5 validation error, or --all resolved zero tests (pass --allow-empty to exit 0)\n' +
8981
10466
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
8982
10467
  ' 7 timeout or deferred — resume with: testsprite test wait <run-id>, ' +
8983
10468
  'or stop it with: testsprite test cancel <run-id>\n' +
@@ -8992,25 +10477,33 @@ export function createTestCommand(deps = {}) {
8992
10477
  .option('--filter <substr>', 'with --all: only rerun tests whose name contains this substring (case-insensitive)')
8993
10478
  .option('--wait', 'block until terminal status or --timeout elapses', false)
8994
10479
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
8995
- .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`.')
8996
10484
  .option('--skip-dependencies', 'BE only: rerun only the named test without expanding the producer/teardown closure', false)
10485
+ .option('--env <name>', 'replay against the named project environment — its test-account credentials, auto-auth and ' +
10486
+ 'OTP settings (names: `testsprite project env list <project-id>`). Omit to keep using the ' +
10487
+ "project's default environment. Applies to every test of a batch rerun.")
8997
10488
  .option('--max-concurrency <n>', `with --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
8998
10489
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --verbose if auto-generated.')
8999
10490
  .option('--report <format>', 'with batch --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
9000
10491
  .option('--report-file <path>', 'output path for --report (atomic write)')
9001
10492
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
9002
- .option('--gh-output', 'with batch --wait: emit GitHub-native output (::error:: annotations per non-passed run; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
9003
- .option('--summary-file <path>', 'with batch --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
10493
+ .option('--gh-output', 'with batch --wait: 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')
10494
+ .option('--summary-file <path>', 'with batch --wait: also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
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')
9004
10496
  .addHelpText('after', '\nNotes:\n' +
9005
- ' • rerun replays a saved run/script and is MORE LENIENT than a fresh `test run`\n' +
9006
- ' (auto-heal can pass steps that have drifted) — for strict scoring/regression,\n' +
9007
- ' 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' +
9008
10501
  ' • Under --wait the per-request HTTP timeout is auto-raised to cover --timeout so a\n' +
9009
10502
  ' slow trigger/poll under load is not cut at the 120s default (see --request-timeout).\n' +
9010
10503
  ' • Batch --wait: rate-deferred tests appear in `deferred[]` and `summary.deferred`,\n' +
9011
10504
  ' and force a non-zero exit — they are NOT counted in `summary.total` (dispatched only).\n' +
9012
- ' • On V3-routed accounts, --no-auto-heal is still rolling out and may not yet be\n' +
9013
- ' 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.')
9014
10507
  .addHelpText('after', '\nDry-run shape notes:\n' +
9015
10508
  ' • --dry-run shows the BE rerun wire shape (includes `closure{}`); FE rerun responses\n' +
9016
10509
  ' omit `closure` (or return it as null) since there is no dependency expansion.\n' +
@@ -9042,7 +10535,7 @@ export function createTestCommand(deps = {}) {
9042
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.');
9043
10536
  }
9044
10537
  await runTestRerun({
9045
- ...resolveCommonOptions(command),
10538
+ ...resolveCommonOptions(command, deps.env),
9046
10539
  testIds,
9047
10540
  all: cmdOpts.all === true,
9048
10541
  projectId: cmdOpts.project,
@@ -9054,6 +10547,7 @@ export function createTestCommand(deps = {}) {
9054
10547
  autoHeal: cmdOpts.autoHeal !== false,
9055
10548
  autoHealExplicit: false,
9056
10549
  skipDependencies: cmdOpts.skipDependencies === true,
10550
+ environment: cmdOpts.env,
9057
10551
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
9058
10552
  DEFAULT_BATCH_RUN_CONCURRENCY,
9059
10553
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -9062,6 +10556,7 @@ export function createTestCommand(deps = {}) {
9062
10556
  reportSuiteName: cmdOpts.reportSuiteName,
9063
10557
  ghOutput: cmdOpts.ghOutput === true,
9064
10558
  summaryFile: cmdOpts.summaryFile,
10559
+ allowEmpty: cmdOpts.allowEmpty === true,
9065
10560
  }, deps);
9066
10561
  });
9067
10562
  // -------------------------------------------------------------------------
@@ -9092,7 +10587,7 @@ export function createTestCommand(deps = {}) {
9092
10587
  .addHelpText('after', GLOBAL_OPTS_HINT)
9093
10588
  .action(async (testIdArg, cmdOpts, command) => {
9094
10589
  await runFlaky({
9095
- ...resolveCommonOptions(command),
10590
+ ...resolveCommonOptions(command, deps.env),
9096
10591
  testId: testIdArg,
9097
10592
  runs: parseNumericFlag(cmdOpts.runs, 'runs') ?? DEFAULT_FLAKY_RUNS,
9098
10593
  untilFail: cmdOpts.untilFail === true,
@@ -9163,14 +10658,16 @@ export async function runFlaky(opts, deps = {}) {
9163
10658
  // Under the implicit wait, raise the per-request timeout to cover --timeout
9164
10659
  // so a slow trigger / long-poll under load isn't cut at the 120s default.
9165
10660
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
9166
- // Best-effort test-type detection for the credit advisory. A probe failure
9167
- // 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.
9168
10663
  let isBackend = false;
9169
10664
  try {
9170
10665
  const test = await client.get(`/tests/${encodeURIComponent(opts.testId)}`);
9171
10666
  isBackend = test.type === 'backend';
9172
10667
  }
9173
- catch {
10668
+ catch (err) {
10669
+ if (err instanceof InterruptError)
10670
+ throw err;
9174
10671
  // best-effort — proceed without the advisory.
9175
10672
  }
9176
10673
  if (isBackend) {
@@ -9196,6 +10693,8 @@ export async function runFlaky(opts, deps = {}) {
9196
10693
  }
9197
10694
  }
9198
10695
  catch (err) {
10696
+ if (err instanceof InterruptError)
10697
+ throw err;
9199
10698
  // A missing replayable run is fatal for the whole command (mirror rerun):
9200
10699
  // there is nothing to repeat, so point the user at a fresh `test run`.
9201
10700
  if (err instanceof ApiError && err.code === 'NOT_FOUND') {
@@ -9243,11 +10742,12 @@ export async function runFlaky(opts, deps = {}) {
9243
10742
  failureKind = finalRun.failureKind;
9244
10743
  }
9245
10744
  catch (err) {
9246
- // Graceful detach (DEV-331): clean up the ticker line, name the run
10745
+ // Graceful detach: clean up the ticker line, name the run
9247
10746
  // still executing server-side, and let index.ts exit 128+signum.
9248
10747
  if (err instanceof InterruptError) {
9249
10748
  ticker.finalize(`Attempt ${i}/${opts.runs} — interrupted (${err.signal})`);
9250
10749
  stderrFn(interruptDetachMessage(err, [runId]));
10750
+ err.runWaitContext = true;
9251
10751
  throw err;
9252
10752
  }
9253
10753
  // RATE_LIMITED during polling (same defect class as the InterruptError
@@ -9336,13 +10836,13 @@ function parseNumericFlag(raw, flagName) {
9336
10836
  }
9337
10837
  return n;
9338
10838
  }
9339
- function resolveCommonOptions(command) {
10839
+ function resolveCommonOptions(command, env) {
9340
10840
  const globals = command.optsWithGlobals();
9341
10841
  // P2-8: validate --output before allowing silent fallback to 'text'.
9342
10842
  // An invalid value (e.g. `--output yaml`) must exit 5 with a clear error
9343
10843
  // rather than silently treating the request as text mode.
9344
10844
  return {
9345
- profile: globals.profile ?? 'default',
10845
+ profile: resolveProfileName(globals.profile, env),
9346
10846
  output: resolveOutputMode(globals.output),
9347
10847
  dryRun: globals.dryRun ?? false,
9348
10848
  endpointUrl: globals.endpointUrl,
@@ -9625,7 +11125,7 @@ export function isPresignedCodeUrl(code) {
9625
11125
  /**
9626
11126
  * Stream a presigned URL into the Output's chunk writer using the
9627
11127
  * deps-provided fetch impl, with no API-key headers — presigned URLs
9628
- * carry their own authority. Three failure shapes the caller might
11128
+ * carry their own authority. Network failures the caller might
9629
11129
  * see, all routed through the typed envelope so `index.ts` produces
9630
11130
  * the documented exit code:
9631
11131
  *
@@ -9640,6 +11140,7 @@ export function isPresignedCodeUrl(code) {
9640
11140
  * - The body stream errors mid-read → wrapped as `TransportError`
9641
11141
  * so partial output to stdout never silently truncates without a
9642
11142
  * non-zero exit.
11143
+ * A process interruption propagates as `InterruptError` through either read path.
9643
11144
  *
9644
11145
  * Streaming via `response.body.getReader()` keeps memory bounded for
9645
11146
  * multi-MB code bodies and starts emitting bytes to stdout the moment
@@ -9647,15 +11148,27 @@ export function isPresignedCodeUrl(code) {
9647
11148
  * the reader may want to start indexing before the download finishes.
9648
11149
  */
9649
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;
9650
11157
  const fetchImpl = deps.fetchImpl ?? globalThis.fetch.bind(globalThis);
9651
11158
  let response;
9652
11159
  try {
9653
- response = await fetchImpl(url);
11160
+ response = await fetchImpl(url, { signal: shutdownSignal });
9654
11161
  }
9655
11162
  catch (err) {
11163
+ if (shutdownSignal.aborted)
11164
+ throw shutdownSignal.reason;
11165
+ if (err instanceof InterruptError)
11166
+ throw err;
9656
11167
  const message = err instanceof Error ? err.message : String(err);
9657
11168
  throw new TransportError(`Failed to download presigned code body: ${message}`);
9658
11169
  }
11170
+ if (shutdownSignal.aborted)
11171
+ throw shutdownSignal.reason;
9659
11172
  if (!response.ok) {
9660
11173
  throw ApiError.fromEnvelope({
9661
11174
  error: {
@@ -9670,7 +11183,16 @@ async function streamPresignedBody(url, out, deps) {
9670
11183
  if (!response.body) {
9671
11184
  // No streamable body (some test runtimes / fetch polyfills). Fall
9672
11185
  // back to text() — same correctness, just no streaming benefit.
9673
- 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
+ }
9674
11196
  return;
9675
11197
  }
9676
11198
  const reader = response.body.getReader();
@@ -9694,8 +11216,14 @@ async function streamPresignedBody(url, out, deps) {
9694
11216
  const tail = decoder.decode();
9695
11217
  if (tail.length > 0)
9696
11218
  await out.writeChunk(tail);
11219
+ if (shutdownSignal.aborted)
11220
+ throw shutdownSignal.reason;
9697
11221
  }
9698
11222
  catch (err) {
11223
+ if (shutdownSignal.aborted)
11224
+ throw shutdownSignal.reason;
11225
+ if (err instanceof InterruptError)
11226
+ throw err;
9699
11227
  const message = err instanceof Error ? err.message : String(err);
9700
11228
  throw new TransportError(`Failed mid-download of presigned code body: ${message}`);
9701
11229
  }
@@ -10028,6 +11556,8 @@ function renderResultText(r) {
10028
11556
  lines.push(`runId: ${r.runIdIfAvailable}`);
10029
11557
  if (r.codeVersion !== null)
10030
11558
  lines.push(`codeVersion: ${r.codeVersion}`);
11559
+ if (r.environment)
11560
+ lines.push(`environment: ${describeEnvironmentLine(r)}`);
10031
11561
  if (r.targetUrl !== null)
10032
11562
  lines.push(`targetUrl: ${r.targetUrl}`);
10033
11563
  lines.push(`summary: ${r.summary}`);
@@ -10146,7 +11676,7 @@ function createTestCodeCommand(deps) {
10146
11676
  .option('--out <path>', 'Write the response to this file instead of stdout (text mode: source body; json mode: wire envelope)')
10147
11677
  .addHelpText('after', GLOBAL_OPTS_HINT)
10148
11678
  .action(async (testId, cmdOpts, command) => {
10149
- await runCodeGet({ ...resolveCommonOptions(command), testId, out: cmdOpts.out }, deps);
11679
+ await runCodeGet({ ...resolveCommonOptions(command, deps.env), testId, out: cmdOpts.out }, deps);
10150
11680
  });
10151
11681
  code
10152
11682
  .command('put <test-id>')
@@ -10167,7 +11697,7 @@ function createTestCodeCommand(deps) {
10167
11697
  throw localValidationError('dry-run-simulate-error', `unsupported value "${simulateError}"; only PRECONDITION_FAILED is supported`, ['PRECONDITION_FAILED']);
10168
11698
  }
10169
11699
  await runCodePut({
10170
- ...resolveCommonOptions(command),
11700
+ ...resolveCommonOptions(command, deps.env),
10171
11701
  testId,
10172
11702
  codeFile: cmdOpts.codeFile,
10173
11703
  expectedVersion: cmdOpts.expectedVersion,
@@ -10180,7 +11710,7 @@ function createTestCodeCommand(deps) {
10180
11710
  return code;
10181
11711
  }
10182
11712
  // ---------------------------------------------------------------------------
10183
- // `test plan generate` / `test plan accept` — DEV-384 V3-B
11713
+ // `test plan generate` / `test plan accept`
10184
11714
  // ---------------------------------------------------------------------------
10185
11715
  /** Default `--timeout` for `test plan generate` (design-doc §3.1): a fresh
10186
11716
  * frontend project runs browser exploration, which takes minutes — the runs
@@ -10191,7 +11721,7 @@ const PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS = 1800;
10191
11721
  const PLAN_BASELINE_READ_TIMEOUT_MS = 10_000;
10192
11722
  /** `--project` is a flag (not a positional) on both plan-generation leaves —
10193
11723
  * route through the house helpers so `TESTSPRITE_PROJECT_ID` works here the
10194
- * same as on every other command (DEV-384 review F5). */
11724
+ * same as on every other command. */
10195
11725
  function requirePlanProjectId(projectId, deps) {
10196
11726
  const resolved = resolveProjectId(projectId, deps);
10197
11727
  requireProjectId(resolved);
@@ -10336,20 +11866,20 @@ function planCreditsUsed(plans) {
10336
11866
  }
10337
11867
  /**
10338
11868
  * THIS invocation's spend: the settled read's per-action charged totals minus
10339
- * the pre-trigger baseline's (DEV-935 / review F1 — the wire block is a
10340
- * LIFETIME project total, so printing its sum as "credits used" reported
10341
- * all-time spend on re-runs that charged nothing). `null` = unknown (no
10342
- * baseline snapshot, or either read lacks the best-effort block) — the
10343
- * 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.
10344
11874
  */
10345
11875
  function planCreditsDelta(baseline, settled) {
10346
11876
  if (baseline?.credits?.charged === undefined || settled.credits?.charged === undefined) {
10347
11877
  return null;
10348
11878
  }
10349
- // DEV-935: a facade-side billing failure degrades the block to
11879
+ // A facade-side billing failure degrades the block to
10350
11880
  // `{charged: [], balance: null}` — `charged` is DEFINED there, so without
10351
11881
  // this guard a degraded read makes the other read's lifetime totals print
10352
- // as this run's spend (the F1 misreport, back through the degrade window).
11882
+ // as this run's spend, back through the degrade window.
10353
11883
  // A healthy block always carries a numeric balance.
10354
11884
  if (baseline.credits.balance === null || settled.credits.balance === null) {
10355
11885
  return null;
@@ -10424,7 +11954,7 @@ export function renderPlanGenerateResultText(plans, projectId, creditsUsed, skip
10424
11954
  ' (or review visually in the Portal before accepting)',
10425
11955
  ].join('\n');
10426
11956
  }
10427
- /** DEV-1008 — one line when the proposals stage left strategy categories out
11957
+ /** One line when the proposals stage left strategy categories out
10428
11958
  * because they have no endpoint to attach a test to. The stage is charged
10429
11959
  * flat, so without this the caller cannot tell a partial plan from a full
10430
11960
  * one. Empty when nothing was skipped (the common case). */
@@ -10468,7 +11998,7 @@ function renderPlanGeneratePartialText(partial, reason) {
10468
11998
  return lines.join('\n');
10469
11999
  }
10470
12000
  /**
10471
- * `test plan generate --project <id>` — DEV-384 V3-B.
12001
+ * `test plan generate --project <id>`.
10472
12002
  *
10473
12003
  * Drives the server's generation ladder (exploration → strategy →
10474
12004
  * proposals) through `runGenerationLadder` and renders the staged
@@ -10513,7 +12043,7 @@ export async function runPlanGenerate(opts, deps = {}) {
10513
12043
  }, deps);
10514
12044
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
10515
12045
  // Upgraded to the server-resolved V3 id by the first ACCEPTED trigger
10516
- // response. KNOWN LIMITATION (DEV-384 review F8): when the very first
12046
+ // response. KNOWN LIMITATION: when the very first
10517
12047
  // trigger 409-attaches, no trigger response ever arrives and neither the
10518
12048
  // 409 envelope nor the `GET /plans` read carries the resolved id, so the
10519
12049
  // output keeps the caller's input id (a V2 id still polls fine through the
@@ -10521,13 +12051,13 @@ export async function runPlanGenerate(opts, deps = {}) {
10521
12051
  let resolvedProjectId = projectId;
10522
12052
  let lastSeen = null;
10523
12053
  try {
10524
- // Pre-trigger baseline snapshot (review F1 / DEV-935): one plain GET
10525
- // BEFORE any POST, so the settled read's lifetime `credits.charged`
10526
- // block can be diffed into "what THIS invocation spent" (the first
10527
- // stage's charge lands before the ladder's own first read, so first
10528
- // in-ladder read vs last would undercount). Best-effort: a failure only
10529
- // costs the credits line, never the command. Bounded by its own short
10530
- // 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
10531
12061
  // (up to 600s under --wait semantics), all outside the --timeout budget.
10532
12062
  let baselinePlans = null;
10533
12063
  try {
@@ -10627,13 +12157,13 @@ export async function runPlanGenerate(opts, deps = {}) {
10627
12157
  const count = plans.proposals.length;
10628
12158
  ticker.finalize(`${count} ${count === 1 ? 'proposal' : 'proposals'} staged`);
10629
12159
  // This invocation's spend (settled − baseline; null = unknown) — the
10630
- // wire block alone is a lifetime total (DEV-935 / review F1).
12160
+ // wire block alone is a lifetime total.
10631
12161
  const creditsUsed = planCreditsDelta(baselinePlans, plans);
10632
12162
  const skippedCategories = result.skippedCategories;
10633
12163
  const payload = {
10634
12164
  projectId: resolvedProjectId,
10635
12165
  creditsUsedThisInvocation: creditsUsed,
10636
- // DEV-1008: present only when the proposals stage skipped endpoint-less
12166
+ // Present only when the proposals stage skipped endpoint-less
10637
12167
  // categories, so every other JSON payload is byte-identical.
10638
12168
  ...(skippedCategories !== null ? { skippedCategories } : {}),
10639
12169
  ...plans,
@@ -10679,8 +12209,8 @@ export async function runPlanGenerate(opts, deps = {}) {
10679
12209
  throw err;
10680
12210
  }
10681
12211
  if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
10682
- // Same partial-envelope family as the timeout/interrupt branches
10683
- // (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.
10684
12214
  // The original ApiError is rethrown unchanged so exit stays 11.
10685
12215
  ticker.finalize('rate limited by the server');
10686
12216
  const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
@@ -10692,7 +12222,7 @@ export async function runPlanGenerate(opts, deps = {}) {
10692
12222
  if (err instanceof ApiError &&
10693
12223
  err.code === 'INTERNAL' &&
10694
12224
  typeof err.details?.acceptedPosts === 'number') {
10695
- // The ladder's cap-exhaustion "appears stuck" fuse (DEV-384 review F7)
12225
+ // The ladder's cap-exhaustion "appears stuck" fuse
10696
12226
  // joins the partial-envelope family too — it is a terminal outcome of a
10697
12227
  // long wait, exactly like the branches above, so redirected stdout must
10698
12228
  // carry the partial. Keyed on the fuse's own `acceptedPosts` detail so
@@ -10743,7 +12273,7 @@ function selectPlanProposals(staged, onlyIds) {
10743
12273
  return onlyIds.map(id => byId.get(id));
10744
12274
  }
10745
12275
  /**
10746
- * `test plan accept --project <id> [--only <ids...>]` — DEV-384 V3-B.
12276
+ * `test plan accept --project <id> [--only <ids...>]`.
10747
12277
  *
10748
12278
  * Reads the staged batch, selects all of it (or the `--only` subset),
10749
12279
  * and POSTs an EXPLICIT id list. Free — the generation charge already
@@ -10835,7 +12365,7 @@ function createTestPlanCommand(deps) {
10835
12365
  throw localValidationError('dry-run-simulate-error', `unsupported value "${simulateError}"; only PRECONDITION_FAILED is supported`, ['PRECONDITION_FAILED']);
10836
12366
  }
10837
12367
  await runPlanPut({
10838
- ...resolveCommonOptions(command),
12368
+ ...resolveCommonOptions(command, deps.env),
10839
12369
  testId,
10840
12370
  stepsFile: cmdOpts.steps,
10841
12371
  expectedStepCount: parseNumericFlag(cmdOpts.expectedStepCount, 'expected-step-count'),
@@ -10867,7 +12397,7 @@ function createTestPlanCommand(deps) {
10867
12397
  GLOBAL_OPTS_HINT)
10868
12398
  .action(async (cmdOpts, command) => {
10869
12399
  await runPlanGenerate({
10870
- ...resolveCommonOptions(command),
12400
+ ...resolveCommonOptions(command, deps.env),
10871
12401
  projectId: cmdOpts.project,
10872
12402
  timeoutSeconds: cmdOpts.timeout === undefined
10873
12403
  ? PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS
@@ -10893,7 +12423,7 @@ function createTestPlanCommand(deps) {
10893
12423
  GLOBAL_OPTS_HINT)
10894
12424
  .action(async (cmdOpts, command) => {
10895
12425
  await runPlanAccept({
10896
- ...resolveCommonOptions(command),
12426
+ ...resolveCommonOptions(command, deps.env),
10897
12427
  projectId: cmdOpts.project,
10898
12428
  only: cmdOpts.only,
10899
12429
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -10902,10 +12432,10 @@ function createTestPlanCommand(deps) {
10902
12432
  return plan;
10903
12433
  }
10904
12434
  export function createTestArtifactCommand(deps) {
10905
- 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');
10906
12436
  artifact
10907
12437
  // `isDefault: true` makes `test artifact <run-id>` a pass-through alias for
10908
- // `test artifact get <run-id>` (DEV-230 grammar consistency — bare-noun reads
12438
+ // `test artifact get <run-id>` (grammar consistency — bare-noun reads
10909
12439
  // mirror the flat `test result/steps/get <id>` forms). Run-id semantics are
10910
12440
  // preserved: the positional is still a run-id, not a test-id.
10911
12441
  .command('get <run-id>', { isDefault: true })
@@ -10931,7 +12461,7 @@ export function createTestArtifactCommand(deps) {
10931
12461
  .addHelpText('after', GLOBAL_OPTS_HINT)
10932
12462
  .action(async (runId, cmdOpts, command) => {
10933
12463
  await runArtifactGet({
10934
- ...resolveCommonOptions(command),
12464
+ ...resolveCommonOptions(command, deps.env),
10935
12465
  runId,
10936
12466
  out: cmdOpts.out,
10937
12467
  failedOnly: Boolean(cmdOpts.failedOnly),
@@ -10943,7 +12473,7 @@ function createTestFailureCommand(deps) {
10943
12473
  const failure = new Command('failure').description('Export the latest-failure agent bundle');
10944
12474
  failure
10945
12475
  // `isDefault: true` makes `test failure <test-id>` a pass-through alias for
10946
- // `test failure get <test-id>` (DEV-230 grammar consistency). `failure summary`
12476
+ // `test failure get <test-id>` (grammar consistency). `failure summary`
10947
12477
  // still routes explicitly; only the bare-noun form falls through to `get`.
10948
12478
  .command('get <test-id>', { isDefault: true })
10949
12479
  .description("Write a self-contained failure-context bundle for a test's latest failing run")
@@ -10953,7 +12483,7 @@ function createTestFailureCommand(deps) {
10953
12483
  .addHelpText('after', GLOBAL_OPTS_HINT)
10954
12484
  .action(async (testId, cmdOpts, command) => {
10955
12485
  await runFailureGet({
10956
- ...resolveCommonOptions(command),
12486
+ ...resolveCommonOptions(command, deps.env),
10957
12487
  testId,
10958
12488
  out: cmdOpts.out,
10959
12489
  failedOnly: Boolean(cmdOpts.failedOnly),
@@ -10961,10 +12491,10 @@ function createTestFailureCommand(deps) {
10961
12491
  });
10962
12492
  failure
10963
12493
  .command('summary <test-id>')
10964
- .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)')
10965
12495
  .addHelpText('after', GLOBAL_OPTS_HINT)
10966
12496
  .action(async (testId, _cmdOpts, command) => {
10967
- await runFailureSummary({ ...resolveCommonOptions(command), testId }, deps);
12497
+ await runFailureSummary({ ...resolveCommonOptions(command, deps.env), testId }, deps);
10968
12498
  });
10969
12499
  return failure;
10970
12500
  }