@testsprite/testsprite-cli 0.10.0 → 0.12.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 (61) hide show
  1. package/README.md +65 -41
  2. package/dist/commands/auth.d.ts +5 -1
  3. package/dist/commands/auth.js +17 -5
  4. package/dist/commands/ci.js +34 -4
  5. package/dist/commands/init.d.ts +6 -1
  6. package/dist/commands/init.js +13 -5
  7. package/dist/commands/project-env.d.ts +90 -0
  8. package/dist/commands/project-env.js +486 -0
  9. package/dist/commands/project.d.ts +19 -0
  10. package/dist/commands/project.js +92 -25
  11. package/dist/commands/test.d.ts +42 -4
  12. package/dist/commands/test.js +344 -49
  13. package/dist/commands/testlist.js +29 -3
  14. package/dist/commands/tunnel.d.ts +2 -2
  15. package/dist/commands/tunnel.js +139 -31
  16. package/dist/index.js +42 -14
  17. package/dist/lib/client-factory.d.ts +4 -1
  18. package/dist/lib/client-factory.js +14 -4
  19. package/dist/lib/client-tag.d.ts +13 -0
  20. package/dist/lib/client-tag.js +44 -0
  21. package/dist/lib/conflict-reason.d.ts +43 -2
  22. package/dist/lib/conflict-reason.js +100 -14
  23. package/dist/lib/credentials.d.ts +4 -0
  24. package/dist/lib/credentials.js +43 -4
  25. package/dist/lib/cron.js +8 -1
  26. package/dist/lib/errors.d.ts +44 -1
  27. package/dist/lib/errors.js +69 -12
  28. package/dist/lib/gh-output.d.ts +25 -11
  29. package/dist/lib/gh-output.js +36 -13
  30. package/dist/lib/http.d.ts +21 -2
  31. package/dist/lib/http.js +45 -8
  32. package/dist/lib/local-target.d.ts +32 -0
  33. package/dist/lib/local-target.js +77 -0
  34. package/dist/lib/output.d.ts +27 -1
  35. package/dist/lib/output.js +22 -3
  36. package/dist/lib/response-schemas.d.ts +5 -2
  37. package/dist/lib/response-schemas.js +39 -1
  38. package/dist/lib/runs.types.d.ts +50 -2
  39. package/dist/lib/target-url.d.ts +1 -1
  40. package/dist/lib/target-url.js +35 -12
  41. package/dist/lib/telemetry.d.ts +174 -4
  42. package/dist/lib/telemetry.js +286 -13
  43. package/dist/lib/tunnel-session.d.ts +13 -2
  44. package/dist/lib/tunnel-session.js +92 -23
  45. package/dist/lib/tunnel.types.d.ts +3 -1
  46. package/dist/lib/version-notice.d.ts +20 -1
  47. package/dist/lib/version-notice.js +59 -12
  48. package/dist/vendor/tunnel-client/client.d.ts +11 -0
  49. package/dist/vendor/tunnel-client/client.js +383 -56
  50. package/dist/vendor/tunnel-client/config.d.ts +11 -3
  51. package/dist/vendor/tunnel-client/config.js +11 -3
  52. package/dist/vendor/tunnel-client/types.d.ts +26 -1
  53. package/dist/vendor/tunnel-client/types.js +1 -0
  54. package/dist/vendor/tunnel-client/ws-compat.d.ts +3 -2
  55. package/dist/vendor/tunnel-client/ws-compat.js +3 -2
  56. package/dist/version.d.ts +1 -1
  57. package/dist/version.js +1 -1
  58. package/package.json +2 -1
  59. package/skills/testsprite-onboard.skill.md +74 -59
  60. package/skills/testsprite-verify.codex.md +82 -97
  61. package/skills/testsprite-verify.skill.md +64 -15
@@ -11,20 +11,21 @@ import { assertJUnitReportOptions, buildJUnitReport, durationSecondsBetween, res
11
11
  import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, isAuthCode, localValidationError, } from '../lib/errors.js';
12
12
  import { globalShutdown } from '../lib/interrupt.js';
13
13
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
14
- import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.js';
14
+ import { isStandingRateLimit, REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, } from '../lib/http.js';
15
15
  import { VERSION } from '../version.js';
16
16
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
17
17
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
18
18
  import { isTerminalStatus, pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
19
+ import { batchOutcomeCounts, recordBatchOutcome, recordTelemetryExtras, } from '../lib/telemetry.js';
19
20
  import { PlanGenerationTimeoutError, runGenerationLadder } from '../lib/plan-poll.js';
20
21
  import { resolveWaitFailure } from '../lib/wait-exit.js';
21
22
  import { RUN_SOURCES } from '../lib/runs.types.js';
22
- import { summarizeConflicts } from '../lib/conflict-reason.js';
23
+ import { insufficientCreditsConflictError, isAllCreditsRefusal, summarizeConflicts, } from '../lib/conflict-reason.js';
23
24
  import { isProxyAgentActive } from '../lib/proxy.js';
24
25
  import { assertNotLocal } from '../lib/target-url.js';
25
26
  import { assertTargetUrlReachable } from '../lib/target-url-preflight.js';
26
27
  import { assertLocalPortListening, buildLocalTargetUrl, DEFAULT_LOCAL_HOST, LOOPBACK_HOSTS, normalizeLocalHost, parseLocalPort, } from '../lib/local-target.js';
27
- import { openTunnelSession, TunnelLostError, } from '../lib/tunnel-session.js';
28
+ import { openTunnelSession, TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION, TunnelLostError, } from '../lib/tunnel-session.js';
28
29
  import { TunnelClient } from '../vendor/tunnel-client/index.js';
29
30
  import { formatTextTableRow, measureTextColumns, renderTextTable, resolveTextColumns, } from '../lib/text-table.js';
30
31
  import { createLiveRunProgress, formatRunProgressLine } from '../lib/run-progress.js';
@@ -96,7 +97,9 @@ function stillRunningAndBillingSubject(runIds) {
96
97
  const TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE = 'Passing --no-cancel-on-interrupt keeps the run executing without its tunnel; it cannot ' +
97
98
  'reach your app and is still billed.';
98
99
  function tunnelRerunCommand(detach) {
99
- return `testsprite test run ${detach.testId} --local ${detach.localPort}`;
100
+ return (`testsprite test run ${detach.testId} --local ${detach.localPort}` +
101
+ (detach.localHost !== DEFAULT_LOCAL_HOST ? ` --local-host ${detach.localHost}` : '') +
102
+ (detach.reason === 'timeout' ? ' --timeout 1800' : ''));
100
103
  }
101
104
  /** Minimum wall-clock gap between adopted-client liveness reads. */
102
105
  const BORROWED_TUNNEL_LIVENESS_INTERVAL_MS = 15_000;
@@ -185,6 +188,20 @@ async function cancelDoomedTunnelRun(args) {
185
188
  */
186
189
  export function tunnelDetachMessage(detach, interrupt) {
187
190
  const { runId, reason, cancel } = detach;
191
+ if (detach.ownerGone === true) {
192
+ const cause = `The borrowed tunnel for run ${runId} is no longer registered.`;
193
+ const outcome = {
194
+ cancelled: `Run ${runId} was cancelled. A run cancelled before it finished is not charged ` +
195
+ '(the server refunds it).',
196
+ 'already-terminal': `Run ${runId} had already finished, so there was nothing to cancel.`,
197
+ failed: `Run ${runId} could NOT be cancelled from here — stop it with: ` +
198
+ `testsprite test cancel ${runId}.`,
199
+ skipped: `Run ${runId} cancellation was skipped because --no-cancel-on-interrupt was passed. ` +
200
+ 'It may still be executing and billed.',
201
+ };
202
+ return (`${cause} ${outcome[cancel]}\n` +
203
+ ` Check the run before re-running: testsprite test wait ${runId}.`);
204
+ }
188
205
  if (reason === 'interrupt' && cancel === 'cancelled') {
189
206
  return (`Interrupted${interrupt ? ` by ${interrupt.signal}` : ''}. Run ${runId} was reaching your ` +
190
207
  `machine through a tunnel that closes with this process, so it was cancelled (exit ` +
@@ -232,6 +249,9 @@ function detachHintLines(runId, detach) {
232
249
  `hint Cancel with: testsprite test cancel ${runId}`,
233
250
  ];
234
251
  }
252
+ if (detach.ownerGone === true) {
253
+ return [`hint Check before re-running: testsprite test wait ${runId}`];
254
+ }
235
255
  return detach.cancel === 'cancelled' || detach.cancel === 'already-terminal'
236
256
  ? ['hint The tunnel closed with this process, so the run was stopped.']
237
257
  : [`hint Stop the run with: testsprite test cancel ${runId}`];
@@ -1663,8 +1683,14 @@ export const DEFERRED_RETRY_DEFAULT_SLEEP_MS = 61_000;
1663
1683
  * a secondary guard. If both fields are absent we treat the error as permanent
1664
1684
  * to avoid silently burning the entire retry budget on a non-recoverable state.
1665
1685
  *
1686
+ * A 429 whose `details.reason` names a standing condition (see
1687
+ * `STANDING_RATE_LIMIT_REASONS` in `lib/http.ts` — e.g. the live
1688
+ * tunnel-binding cap) is also permanent, even though it now carries a real
1689
+ * `Retry-After`: that header says when a retry COULD first succeed if the
1690
+ * caller frees the resource, not that the condition clears on its own.
1691
+ *
1666
1692
  * Limitation: a hypothetical future backend that emits `RATE_LIMITED` for a
1667
- * third reason without a `Retry-After` header AND without the per-minute
1693
+ * new reason without a `Retry-After` header AND without the per-minute
1668
1694
  * wording would be classified as permanent here. Document this if it occurs.
1669
1695
  */
1670
1696
  export function isTransientRateLimit(err) {
@@ -1673,6 +1699,9 @@ export function isTransientRateLimit(err) {
1673
1699
  // so a credits-429 with a stray Retry-After header is never retried.
1674
1700
  if (/insufficient credits/i.test(err.message))
1675
1701
  return false;
1702
+ // Standing-condition 429s are permanent regardless of Retry-After too.
1703
+ if (isStandingRateLimit(err))
1704
+ return false;
1676
1705
  // Primary transient signal: Retry-After header was present and parsed (set on
1677
1706
  // the error by HttpClient when retryOnRateLimit: false is used and the HTTP
1678
1707
  // layer throws after a single 429).
@@ -2715,6 +2744,7 @@ testIdToDashboardState) {
2715
2744
  if (err instanceof InterruptError)
2716
2745
  throw err;
2717
2746
  if (err instanceof TimeoutError) {
2747
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
2718
2748
  if (opts.output !== 'json') {
2719
2749
  stderrFn(`[batch-run] ${testId} (runId: ${triggerResponse.runId}) — timed out after ${timeoutSeconds}s`);
2720
2750
  }
@@ -3936,8 +3966,8 @@ export async function runSteps(opts, deps = {}) {
3936
3966
  out.print(page, data => renderStepsText(data));
3937
3967
  return page;
3938
3968
  }
3939
- // Bare `test steps <id>` (no --run-id): cumulative path — byte-identical to
3940
- // the original behavior. Pagination flags are honored here.
3969
+ // Bare `test steps <id>` reads the latest run on V3. Older backends may
3970
+ // return a cumulative log; pagination and the page shape stay unchanged.
3941
3971
  const paginationFlags = validatePaginationFlags({
3942
3972
  pageSize: opts.pageSize,
3943
3973
  startingToken: opts.startingToken,
@@ -3952,6 +3982,25 @@ export async function runSteps(opts, deps = {}) {
3952
3982
  else {
3953
3983
  page = await paginate(async ({ pageSize, cursor }) => client.get(path, { query: { pageSize, cursor } }), paginationFlags);
3954
3984
  }
3985
+ if (page.items.length === 0 && opts.startingToken === undefined && !opts.dryRun) {
3986
+ // One history page and a short total deadline keep this advisory best-effort.
3987
+ const deadline = new AbortController();
3988
+ const timer = setTimeout(() => deadline.abort(), 5_000);
3989
+ try {
3990
+ const historyClient = makeClient(opts, deps, AbortSignal.any([shutdownOf(deps).signal, deadline.signal]));
3991
+ const history = await historyClient.listTestRuns(opts.testId, { pageSize: 20 }, { retry: false });
3992
+ const earlier = history.runs.slice(1).find(run => isTerminalStatus(run.status));
3993
+ stderrFn(earlier
3994
+ ? `Latest run has no steps; inspect an earlier run: testsprite test steps ${opts.testId} --run-id ${earlier.runId}`
3995
+ : `Latest run has no steps; inspect run history: testsprite test result ${opts.testId} --history`);
3996
+ }
3997
+ catch {
3998
+ // Missing history must not change the steps page or the command's exit code.
3999
+ }
4000
+ finally {
4001
+ clearTimeout(timer);
4002
+ }
4003
+ }
3955
4004
  // Bare cumulative path: when the returned items span multiple runIds,
3956
4005
  // print a stderr advisory pointing at --run-id so the next invocation
3957
4006
  // can scope. Stdout is unchanged (still the full §6.4 wire shape), so
@@ -4052,11 +4101,13 @@ export async function runResultHistory(opts, deps = {}) {
4052
4101
  const client = makeClient(opts, deps);
4053
4102
  const pageSize = opts.pageSize ?? 20;
4054
4103
  const sinceIso = opts.since !== undefined ? parseDuration(opts.since) : undefined;
4104
+ const environment = normalizeEnvironmentName(opts.environment);
4055
4105
  const resp = await client.listTestRuns(opts.testId, {
4056
4106
  cursor: opts.cursor,
4057
4107
  pageSize,
4058
4108
  source: opts.source,
4059
4109
  since: sinceIso,
4110
+ ...(environment !== undefined ? { environment } : {}),
4060
4111
  });
4061
4112
  // Client-side rerun filter (--rerun / --no-rerun). isRerun is on every row;
4062
4113
  // the backend has no rerun filter. Undefined → no filter. Like --source, a
@@ -4114,10 +4165,25 @@ export async function runResultHistory(opts, deps = {}) {
4114
4165
  }
4115
4166
  return { ...resp, runs };
4116
4167
  }
4168
+ /**
4169
+ * The ENV cell of a history row: the name of the environment the run resolved
4170
+ * to, or `—` when the row names none. There is no second case — a `--local`
4171
+ * port or a `--target-url` names an environment (matched by origin, created
4172
+ * when nothing matches), so the address a run went to is always its
4173
+ * environment's own.
4174
+ */
4175
+ function describeRunEnv(run) {
4176
+ return run.environment?.name ?? '—';
4177
+ }
4117
4178
  const RUN_HISTORY_TABLE_COLUMNS = [
4118
4179
  { header: 'RUN ID', width: 36, render: run => run.runId },
4119
4180
  { header: 'STATUS', width: 10, render: run => run.status },
4120
4181
  { header: 'SOURCE', width: 18, render: run => run.source },
4182
+ {
4183
+ header: 'ENV',
4184
+ width: rows => Math.max(3, ...rows.map(run => describeRunEnv(run).length)),
4185
+ render: describeRunEnv,
4186
+ },
4121
4187
  { header: 'RERUN?', width: 6, render: run => (run.isRerun ? 'yes' : 'no') },
4122
4188
  { header: 'WHEN', width: 25, render: run => run.createdAt },
4123
4189
  {
@@ -4311,6 +4377,7 @@ export async function runFailureGet(opts, deps = {}) {
4311
4377
  * Default timeout in seconds for `--wait`. Range 1..3600.
4312
4378
  */
4313
4379
  const DEFAULT_RUN_TIMEOUT_SECONDS = 600;
4380
+ const DEFAULT_LOCAL_RUN_TIMEOUT_SECONDS = 1200;
4314
4381
  const MAX_RUN_TIMEOUT_SECONDS = 3600;
4315
4382
  /**
4316
4383
  * Map a terminal `RunResponse.status` to the CLI exit code.
@@ -4610,6 +4677,8 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
4610
4677
  ];
4611
4678
  if (run.codeVersion !== null)
4612
4679
  lines.push(`codeVersion ${run.codeVersion}`);
4680
+ if (run.environment)
4681
+ lines.push(`environment ${describeEnvironmentLine(run)}`);
4613
4682
  if (run.targetUrl !== null)
4614
4683
  lines.push(`targetUrl ${run.targetUrl}`);
4615
4684
  lines.push(`createdAt ${run.createdAt}`);
@@ -4635,9 +4704,18 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
4635
4704
  // confusing "0/0 (passed=0, failed=0)" which reads like a broken no-op.
4636
4705
  lines.push(`steps n/a (backend)`);
4637
4706
  }
4638
- else if (run.stepSummary) {
4707
+ else if (run.stepSummary && run.stepSummary.total > 0) {
4639
4708
  lines.push(`steps ${run.stepSummary.completed}/${run.stepSummary.total} (passed=${run.stepSummary.passedCount}, failed=${run.stepSummary.failedCount})`);
4640
4709
  }
4710
+ else if (run.stepSummary) {
4711
+ // Same reasoning as the backend branch above, for the case the type check
4712
+ // cannot catch: a frontend run whose summary comes back with `total: 0`.
4713
+ // Rendering it verbatim prints `0/0 (passed=0, failed=0)` beside a
4714
+ // `passed` status, which reads as "nothing executed, and it passed" — the
4715
+ // exact no-op wording the backend branch exists to avoid. A zeroed summary
4716
+ // is an absent breakdown, not a breakdown of zero steps, so say that.
4717
+ lines.push(`steps n/a (no per-step breakdown reported)`);
4718
+ }
4641
4719
  // Closing pointer: where to inspect this run in the Portal (video, steps,
4642
4720
  // screenshots). Present only when withRunDashboardUrl could resolve it.
4643
4721
  if (run.dashboardUrl)
@@ -4683,6 +4761,8 @@ function renderTriggerRunText(r) {
4683
4761
  ];
4684
4762
  if (r.codeVersion !== null)
4685
4763
  lines.push(`codeVersion ${r.codeVersion}`);
4764
+ if (r.environment)
4765
+ lines.push(`environment ${describeEnvironmentLine(r)}`);
4686
4766
  if (r.targetUrl !== null)
4687
4767
  lines.push(`targetUrl ${r.targetUrl}`);
4688
4768
  // Same line the run card prints after `--wait` (`renderRunResponseText`), so a
@@ -4692,6 +4772,31 @@ function renderTriggerRunText(r) {
4692
4772
  lines.push(`dashboard ${r.dashboardUrl}`);
4693
4773
  return lines.join('\n');
4694
4774
  }
4775
+ /**
4776
+ * The `environment` line shared by the run card and the trigger card: the
4777
+ * name of the environment the run resolved to. A `--local` port or a
4778
+ * `--target-url` names an environment rather than sending the browser
4779
+ * somewhere else, so there is no "ran against the tunnel" suffix — the
4780
+ * address is the environment's own and prints on its own line.
4781
+ */
4782
+ function describeEnvironmentLine(r) {
4783
+ return r.environment?.name ?? '—';
4784
+ }
4785
+ /**
4786
+ * Validate `--env <name>` (DEV-1305). The name is passed to the server
4787
+ * verbatim (it resolves `unique(project_id, name)` and lists the valid names
4788
+ * on a miss); the only local rule is that an empty/whitespace value is a typo,
4789
+ * not a request for the default environment — omitting the flag is.
4790
+ */
4791
+ function normalizeEnvironmentName(raw) {
4792
+ if (raw === undefined)
4793
+ return undefined;
4794
+ const name = raw.trim();
4795
+ if (name.length === 0) {
4796
+ 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');
4797
+ }
4798
+ return name;
4799
+ }
4695
4800
  /**
4696
4801
  * Validate the `--timeout` flag value. Returns a clamped integer in
4697
4802
  * range [1, 3600], or the default when absent.
@@ -4728,6 +4833,7 @@ function parseStepTimeoutFlag(raw, flagName) {
4728
4833
  */
4729
4834
  export async function runTestRun(opts, deps = {}) {
4730
4835
  assertIdempotencyKey(opts.idempotencyKey);
4836
+ const environment = normalizeEnvironmentName(opts.environment);
4731
4837
  // --local resolution runs FIRST and touches nothing: every refusal below
4732
4838
  // must happen before a client is even constructed, because the guarantee
4733
4839
  // this feature sells is that a doomed `--local` run never gets a run row,
@@ -4785,6 +4891,7 @@ export async function runTestRun(opts, deps = {}) {
4785
4891
  // handle, the same reason `dashboardUrl` is suppressed under
4786
4892
  // --dry-run rather than pointing at the canned sample id.
4787
4893
  ...(isTunnelRun ? { tunnelClientId: '<minted at run time>' } : {}),
4894
+ ...(environment !== undefined ? { environment } : {}),
4788
4895
  },
4789
4896
  idempotencyKey,
4790
4897
  ...(isTunnelRun
@@ -4816,6 +4923,7 @@ export async function runTestRun(opts, deps = {}) {
4816
4923
  const out = makeOutput(opts.output, deps);
4817
4924
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4818
4925
  const shutdown = shutdownOf(deps);
4926
+ // `--env` is feature-gated per workspace. Refuse here — one read-only `/me`,
4819
4927
  // Pre-charge reachability preflight — real path only (dry-run
4820
4928
  // makes zero network calls by convention), after `assertNotLocal` and
4821
4929
  // before the trigger POST so a doomed run never gets a run row or charge.
@@ -4833,7 +4941,7 @@ export async function runTestRun(opts, deps = {}) {
4833
4941
  await assertLocalPortListening(localHost, opts.localPort, { skipPreflight: opts.skipPreflight }, stderrFn);
4834
4942
  if (isProxyAgentActive()) {
4835
4943
  stderrFn('[advisory] An HTTP proxy is configured for this process. The tunnel control channel ' +
4836
- 'honours it, but the tunnel data plane is a raw TCP connection that does not — if the ' +
4944
+ `honours it, but ${TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION} — if the ` +
4837
4945
  'run cannot reach your machine, an egress proxy is the first thing to rule out.');
4838
4946
  }
4839
4947
  }
@@ -4894,6 +5002,9 @@ export async function runTestRun(opts, deps = {}) {
4894
5002
  // The client ID only. The secret stays in this process and never
4895
5003
  // reaches a request body, an idempotency row, or an audit line.
4896
5004
  ...(tunnelSession ? { tunnelClientId: tunnelSession.clientId } : {}),
5005
+ // Whose credentials to log in with (DEV-1305); the two fields above
5006
+ // say where the browser goes. Absent → the project's default env.
5007
+ ...(environment !== undefined ? { environment } : {}),
4897
5008
  };
4898
5009
  const result = isTunnelRun
4899
5010
  ? await withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, triggerClient => triggerClient.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey }))
@@ -5007,6 +5118,10 @@ export async function runTestRun(opts, deps = {}) {
5007
5118
  throw err;
5008
5119
  }
5009
5120
  }
5121
+ stderrFn(`Run ${triggerResponse.runId}`);
5122
+ const receiptUrl = triggerResponse.dashboardUrl ?? triggerResponse.executionUrl;
5123
+ if (receiptUrl)
5124
+ stderrFn(`Dashboard: ${receiptUrl}`);
5010
5125
  // Response-driven, not assumption-driven: the backend is the ground
5011
5126
  // truth for whether --target-url was actually applied — V3
5012
5127
  // deliberately returns `targetUrl: ''` rather than echoing an override it
@@ -5094,8 +5209,9 @@ export async function runTestRun(opts, deps = {}) {
5094
5209
  // source through the shared poll loop for every ordinary run.
5095
5210
  if (!isTerminalStatus(run.status)) {
5096
5211
  const fatal = tunnelSession?.fatalReason();
5097
- if (fatal !== undefined)
5098
- throw new TunnelLostError(fatal, triggerResponse.runId);
5212
+ if (fatal !== undefined) {
5213
+ throw new TunnelLostError(fatal, triggerResponse.runId, tunnelSession?.fatalMessage());
5214
+ }
5099
5215
  }
5100
5216
  live.onTick(run, elapsedMs);
5101
5217
  },
@@ -5106,13 +5222,14 @@ export async function runTestRun(opts, deps = {}) {
5106
5222
  // Stop redrawing BEFORE any final line below is written, so a stale
5107
5223
  // "running · Ns" can never land after "timed out" / "interrupted".
5108
5224
  live.stop();
5109
- // A tunnel run that stops being waited on is a tunnel run that is about
5110
- // to lose its tunnel, on ALL of these paths. `cancelOnInterrupt` defaults
5111
- // ON here and only here — for an ordinary run, detaching leaves something
5112
- // that can still pass, which is why DEV-331 deliberately did not cancel.
5113
- const settleTunnelDetach = async (reason) => {
5114
- if (tunnelSession === undefined || tunnelSession.adopted)
5225
+ // An owned tunnel closes on every non-terminal exit, so its run is doomed.
5226
+ // An adopted tunnel survives this process and normally detaches; only an
5227
+ // owner-gone observation proves that the borrowed run has lost its route.
5228
+ // `cancelOnInterrupt` defaults on for both doomed cases.
5229
+ const settleTunnelDetach = async (reason, ownerGone = false) => {
5230
+ if (tunnelSession === undefined || (tunnelSession.adopted && !ownerGone))
5115
5231
  return undefined;
5232
+ const borrowedOwnerGone = tunnelSession.adopted && ownerGone;
5116
5233
  const cancel = await cancelDoomedTunnelRun({
5117
5234
  runId: triggerResponse.runId,
5118
5235
  enabled: opts.cancelOnInterrupt !== false,
@@ -5123,14 +5240,16 @@ export async function runTestRun(opts, deps = {}) {
5123
5240
  runId: triggerResponse.runId,
5124
5241
  testId: opts.testId,
5125
5242
  localPort: opts.localPort,
5243
+ localHost,
5126
5244
  reason,
5245
+ ...(borrowedOwnerGone ? { ownerGone: true } : {}),
5127
5246
  cancel: cancel.outcome,
5128
5247
  ...(cancel.terminalStatus !== undefined ? { terminalStatus: cancel.terminalStatus } : {}),
5129
5248
  };
5130
5249
  };
5131
5250
  if (err instanceof TunnelLostError) {
5132
5251
  ticker.finalize(`Run ${triggerResponse.runId} — tunnel disconnected`);
5133
- const detach = await settleTunnelDetach('tunnel-lost');
5252
+ const detach = await settleTunnelDetach('tunnel-lost', err.getDetail('reason') === 'owner-gone');
5134
5253
  const partial = {
5135
5254
  runId: triggerResponse.runId,
5136
5255
  status: detachPartialStatus(detach),
@@ -5159,6 +5278,17 @@ export async function runTestRun(opts, deps = {}) {
5159
5278
  // JSON consumers and AI agents can grab the runId and chain into
5160
5279
  // `testsprite test wait <runId>` without parsing the stderr error envelope.
5161
5280
  const detach = await settleTunnelDetach('timeout');
5281
+ recordTelemetryExtras({ passed: 0, failed: 0, blocked: 0, timedOut: 1 });
5282
+ deps.onWaitTimeout?.({
5283
+ reason: 'wait_timeout',
5284
+ ...(tunnelSession
5285
+ ? {
5286
+ cancelOutcome: detach?.cancel === 'already-terminal'
5287
+ ? 'already_terminal'
5288
+ : (detach?.cancel ?? 'skipped'),
5289
+ }
5290
+ : {}),
5291
+ });
5162
5292
  const timeoutPartial = {
5163
5293
  runId: triggerResponse.runId,
5164
5294
  status: detachPartialStatus(detach),
@@ -5188,7 +5318,7 @@ export async function runTestRun(opts, deps = {}) {
5188
5318
  : `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}. ` +
5189
5319
  stillRunningAndBillingSubject(triggerResponse.runId),
5190
5320
  nextAction: detach
5191
- ? `Start it again with --local and a longer --timeout; a retry mints a fresh tunnel.`
5321
+ ? `Start a new run with: ${tunnelRerunCommand(detach)} (or raise --timeout up to 3600); a retry mints a fresh tunnel.`
5192
5322
  : `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
5193
5323
  requestId: 'local',
5194
5324
  details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
@@ -5344,6 +5474,9 @@ export async function runTestRun(opts, deps = {}) {
5344
5474
  ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
5345
5475
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
5346
5476
  }
5477
+ // One-run verdict counts (0/1 each) — the single-run analogue of the batch
5478
+ // accounting, so a CI job that runs one test is measurable the same way.
5479
+ recordTelemetryExtras(batchOutcomeCounts([finalRun]));
5347
5480
  // CI-native output layer (issue #99): single-test parity with the --all batch.
5348
5481
  // Emitted before the exit-code gate throws below so the summary file and
5349
5482
  // annotations land even when the run exits non-zero (mirrors the batch path).
@@ -5444,8 +5577,10 @@ export async function runTestWaitMany(opts, deps = {}) {
5444
5577
  // would extend the invocation by ~1s per queued run past --timeout).
5445
5578
  // Re-evaluated on every iteration so a retry obeys the same rule.
5446
5579
  const remainingSeconds = Math.ceil((deadlineMs - Date.now()) / 1000);
5447
- if (remainingSeconds <= 0)
5580
+ if (remainingSeconds <= 0) {
5581
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
5448
5582
  return { kind: 'timeout' };
5583
+ }
5449
5584
  try {
5450
5585
  const run = await pollRunUntilTerminal(client, runId, {
5451
5586
  timeoutSeconds: remainingSeconds,
@@ -5461,8 +5596,10 @@ export async function runTestWaitMany(opts, deps = {}) {
5461
5596
  return { kind: 'result', run };
5462
5597
  }
5463
5598
  catch (err) {
5464
- if (err instanceof TimeoutError)
5599
+ if (err instanceof TimeoutError) {
5600
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
5465
5601
  return { kind: 'timeout' };
5602
+ }
5466
5603
  if (err instanceof RequestTimeoutError)
5467
5604
  throw err;
5468
5605
  // Interrupt must reject the fan-out (handled at the collect point), not
@@ -5487,8 +5624,10 @@ export async function runTestWaitMany(opts, deps = {}) {
5487
5624
  // makes ("Timed out … during rate-limit backoff"). Reporting the 429
5488
5625
  // instead would let the exit-11 escalation below claim "nothing else
5489
5626
  // went wrong" for an invocation that in fact exhausted `--timeout`.
5490
- if (clampedRetryMs <= 0)
5627
+ if (clampedRetryMs <= 0) {
5628
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
5491
5629
  return { kind: 'timeout' };
5630
+ }
5492
5631
  stderrFn(`[wait] ${runId} — rate limited (attempt ${rateLimitAttempt}/${WAIT_POLL_RATE_MAX_OUTER_RETRIES}): retrying in ${Math.ceil(clampedRetryMs / 1000)}s`);
5493
5632
  // Arm the graceful-detach scope across the backoff. `pollRunUntilTerminal`
5494
5633
  // disarms in its own `finally`, so without this the sleep is a window
@@ -5676,7 +5815,7 @@ export async function runTestCancel(opts, deps = {}) {
5676
5815
  const result = await client.cancelRun(runId);
5677
5816
  out.print(result, data => {
5678
5817
  const r = data;
5679
- return renderRunResponseText(r);
5818
+ return renderCancelResponseText(r);
5680
5819
  });
5681
5820
  if (result.alreadyCancelled) {
5682
5821
  stderrFn(`[advisory] run ${runId} was already cancelled`);
@@ -5757,15 +5896,40 @@ function renderCancelSummaryText(summary) {
5757
5896
  lines.push(`${e.runId} error (${e.message})`);
5758
5897
  return lines.join('\n');
5759
5898
  }
5899
+ function renderCancelResponseText(response) {
5900
+ const runCard = renderRunResponseText(response);
5901
+ if (!response.refund)
5902
+ return runCard;
5903
+ let refundLine;
5904
+ switch (response.refund.status) {
5905
+ case 'refunded':
5906
+ refundLine =
5907
+ response.refund.amount === undefined
5908
+ ? 'refund credits returned'
5909
+ : `refund credits returned: ${response.refund.amount}`;
5910
+ break;
5911
+ case 'not_charged':
5912
+ refundLine = 'refund run was never charged; nothing to return';
5913
+ break;
5914
+ case 'failed':
5915
+ refundLine =
5916
+ 'refund failed — cancellation succeeded, but credits were not returned; contact TestSprite support';
5917
+ break;
5918
+ default:
5919
+ refundLine = `refund ${String(response.refund.status)}`;
5920
+ }
5921
+ return `${runCard}\n${refundLine}`;
5922
+ }
5760
5923
  export function createTestCancelCommand(deps) {
5761
5924
  const cancel = new Command('cancel');
5762
5925
  cancel
5763
5926
  .argument('<run-id...>', 'one or more run ids to cancel')
5764
5927
  .description('Cancel one or more queued/running runs.\n' +
5765
5928
  '\nCtrl-C during --wait only detaches — it does NOT cancel the server-side\n' +
5766
- 'run. This is the real stop button. No refund is issued for the credits\n' +
5767
- 'already charged at trigger time (D3); an in-flight Lambda finishes on its\n' +
5768
- 'own and its result is discarded once cancelled.\n' +
5929
+ 'run. This is the real stop button. A frontend V3 run cancelled before a\n' +
5930
+ 'terminal state has its original charge returned; an uncharged run says so.\n' +
5931
+ 'Backend and V2 runs keep their existing billing behavior; an in-flight Lambda\n' +
5932
+ 'finishes on its own and its result is discarded once cancelled.\n' +
5769
5933
  '\nExit codes:\n' +
5770
5934
  ' 0 cancelled (fresh or already-cancelled — naturally idempotent)\n' +
5771
5935
  ' 4 run id not found (single id), or ANY id not found (multi-id — outranks conflict)\n' +
@@ -5842,6 +6006,7 @@ export async function runTestWait(opts, deps = {}) {
5842
6006
  // "running · Ns" can never land after "timed out" / "interrupted".
5843
6007
  live.stop();
5844
6008
  if (err instanceof TimeoutError) {
6009
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
5845
6010
  ticker.finalize(`Run ${opts.runId} — timed out after ${opts.timeoutSeconds}s`);
5846
6011
  // Mirror the RequestTimeoutError path: emit a partial run to stdout so
5847
6012
  // JSON consumers and AI agents can grab the runId and chain into
@@ -6021,9 +6186,10 @@ function zeroDispatchReason(skippedFrontend, skippedIntegration) {
6021
6186
  * Handle a batch invocation that dispatched ZERO tests — all skipped, an empty
6022
6187
  * project, or a `--filter` that matched nothing. Left alone this exits 0 with no
6023
6188
  * artifact, a CI false-green: a gate that greens on zero tests is worse than no
6024
- * gate (DEV-1046). So it emits the CI artifacts (summary + `::error::` annotation
6025
- * + JUnit report) so the gate shows WHY, then fails with **exit 5** unless the
6026
- * caller passed `--allow-empty` (in which case it returns and the caller exits 0).
6189
+ * gate. So it emits the CI artifacts (summary with `skipped` rows +
6190
+ * `::warning::` annotations + JUnit report) so the gate shows WHY, then fails
6191
+ * with **exit 5** unless the caller passed `--allow-empty` (in which case it
6192
+ * returns and the caller exits 0).
6027
6193
  *
6028
6194
  * `skipped` is the union of skipped FE + integration tests (rendered as
6029
6195
  * `<skipped/>` JUnit cases and non-passed summary rows so they're visible);
@@ -6034,14 +6200,18 @@ async function finishZeroDispatchBatch(params) {
6034
6200
  const runs = skipped.length > 0
6035
6201
  ? skipped.map(testId => ({ testId, status: 'skipped', error: reason }))
6036
6202
  : [{ testId: '(no tests)', status: 'no_tests', error: reason }];
6203
+ // Counted as `skipped`, not `failed`: nothing ran, so nothing
6204
+ // failed — the exit-5 gate below is what makes the job red, and the summary
6205
+ // must agree with it rather than claim failures the gates don't see.
6037
6206
  const summary = {
6038
6207
  total: runs.length,
6039
6208
  passed: 0,
6040
- failed: runs.length,
6209
+ failed: 0,
6210
+ skipped: runs.length,
6041
6211
  timedOut: 0,
6042
6212
  runs,
6043
6213
  };
6044
- // Emit the in-memory artifacts (summary + `::error::` annotation) FIRST: they
6214
+ // Emit the in-memory artifacts (summary + `::warning::` annotation) FIRST: they
6045
6215
  // can't fail on I/O, so the "show WHY it's red" diagnostics always land — even
6046
6216
  // if the JUnit path below is misconfigured. Ordering these after the file write
6047
6217
  // would let an unwritable --report-file throw (exit 10) preempt both the
@@ -6077,6 +6247,7 @@ async function finishZeroDispatchBatch(params) {
6077
6247
  */
6078
6248
  export async function runTestRunAll(opts, deps = {}) {
6079
6249
  assertIdempotencyKey(opts.idempotencyKey);
6250
+ const environment = normalizeEnvironmentName(opts.environment);
6080
6251
  const projectId = resolveProjectId(opts.projectId, deps);
6081
6252
  requireProjectId(projectId);
6082
6253
  if (!Number.isInteger(opts.maxConcurrency) ||
@@ -6108,6 +6279,7 @@ export async function runTestRunAll(opts, deps = {}) {
6108
6279
  projectId,
6109
6280
  testIds: opts.nameFilter ? ['<filtered by --filter>'] : undefined,
6110
6281
  source: 'cli',
6282
+ ...(environment !== undefined ? { environment } : {}),
6111
6283
  },
6112
6284
  idempotencyKey,
6113
6285
  ...(opts.wait ? { thenPoll: '/api/cli/v1/runs/<run-id>?waitSeconds=25' } : {}),
@@ -6120,6 +6292,8 @@ export async function runTestRunAll(opts, deps = {}) {
6120
6292
  }
6121
6293
  // D4: under --wait, raise per-request timeout to cover --timeout.
6122
6294
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
6295
+ // `--env` gate — see `runTestRun`. Before the test-set enumeration so a
6296
+ // gated batch makes no billable call at all.
6123
6297
  // Portal deep links for batch output: every test in the batch belongs to
6124
6298
  // opts.projectId, so per-item dashboardUrl needs no extra wire data. The
6125
6299
  // project-level URL closes out text-mode output ("watch the wave here").
@@ -6176,7 +6350,7 @@ export async function runTestRunAll(opts, deps = {}) {
6176
6350
  });
6177
6351
  // Zero-dispatch (a --filter that matched nothing): emit the CI artifacts
6178
6352
  // and fail unless --allow-empty, so a renamed test can't turn a filtered
6179
- // gate permanently green (DEV-1046). Returns here only under --allow-empty.
6353
+ // gate permanently green. Returns here only under --allow-empty.
6180
6354
  await finishZeroDispatchBatch({
6181
6355
  reason: `--filter "${opts.nameFilter}" matched no tests in project ${projectId}`,
6182
6356
  skipped: [],
@@ -6195,6 +6369,7 @@ export async function runTestRunAll(opts, deps = {}) {
6195
6369
  projectId,
6196
6370
  ...(testIds !== undefined ? { testIds } : {}),
6197
6371
  source: 'cli',
6372
+ ...(environment !== undefined ? { environment } : {}),
6198
6373
  }, { idempotencyKey });
6199
6374
  // Project-level "watch it here" link. A V3 backend sends it (string, or
6200
6375
  // `null` when no single page exists — e.g. a `--all` that fanned out over
@@ -6258,11 +6433,22 @@ export async function runTestRunAll(opts, deps = {}) {
6258
6433
  }
6259
6434
  return lines.join('\n');
6260
6435
  });
6436
+ recordBatchOutcome({
6437
+ accepted: accepted.length,
6438
+ conflicts,
6439
+ deferred: deferred.length,
6440
+ skipped: skippedFrontend.length + skippedIntegration.length,
6441
+ });
6261
6442
  // Rate-deferred tests were NOT dispatched → signal incomplete (exit 7),
6262
6443
  // mirroring `test rerun --all`. The user retries with a fresh invocation.
6263
6444
  if (deferred.length > 0) {
6264
6445
  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);
6265
6446
  }
6447
+ // Nothing queued because the wallet refused every case → the same exit-12
6448
+ // INSUFFICIENT_CREDITS the single-run route answers, not an in-flight CONFLICT.
6449
+ if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
6450
+ throw insufficientCreditsConflictError(conflicts, batchApiUrl);
6451
+ }
6266
6452
  // Nothing queued and everything was an in-flight conflict → surface CONFLICT (exit 6).
6267
6453
  if (accepted.length === 0 && conflicts.length > 0) {
6268
6454
  throw ApiError.fromEnvelope({
@@ -6276,7 +6462,7 @@ export async function runTestRunAll(opts, deps = {}) {
6276
6462
  });
6277
6463
  }
6278
6464
  // Zero dispatched, nothing pending (deferred / conflict already threw above):
6279
- // all tests were skipped, or the project has none. Don't exit 0 (DEV-1046).
6465
+ // all tests were skipped, or the project has none. Don't exit 0.
6280
6466
  if (accepted.length === 0) {
6281
6467
  await finishZeroDispatchBatch({
6282
6468
  reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
@@ -6436,6 +6622,12 @@ export async function runTestRunAll(opts, deps = {}) {
6436
6622
  skippedIntegration,
6437
6623
  };
6438
6624
  out.print(finalResp);
6625
+ recordBatchOutcome({
6626
+ accepted: accepted.length,
6627
+ conflicts,
6628
+ deferred: deferred.length,
6629
+ skipped: skippedFrontend.length + skippedIntegration.length,
6630
+ });
6439
6631
  // Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
6440
6632
  // mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
6441
6633
  // Emit the deferred/conflict summary + annotations first so CI shows them (the
@@ -6450,6 +6642,11 @@ export async function runTestRunAll(opts, deps = {}) {
6450
6642
  if (deferred.length > 0) {
6451
6643
  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);
6452
6644
  }
6645
+ // Every case refused for credits → exit 12 (same envelope as the single-run
6646
+ // route), checked before the generic all-conflict exit 6.
6647
+ if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
6648
+ throw insufficientCreditsConflictError(conflicts, batchApiUrl);
6649
+ }
6453
6650
  if (conflicts.length > 0) {
6454
6651
  throw ApiError.fromEnvelope({
6455
6652
  error: {
@@ -6463,7 +6660,7 @@ export async function runTestRunAll(opts, deps = {}) {
6463
6660
  }
6464
6661
  // Reached only when nothing was queued and nothing is pending: all tests were
6465
6662
  // skipped, or the project has none. Emit a skipped-rows summary + JUnit and
6466
- // fail unless --allow-empty — never a silent exit 0 (DEV-1046).
6663
+ // fail unless --allow-empty — never a silent exit 0.
6467
6664
  await finishZeroDispatchBatch({
6468
6665
  reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
6469
6666
  skipped: [...skippedFrontend, ...skippedIntegration.map(s => s.testId)],
@@ -6523,7 +6720,9 @@ export async function runTestRunAll(opts, deps = {}) {
6523
6720
  : {}),
6524
6721
  };
6525
6722
  }
6526
- catch {
6723
+ catch (err) {
6724
+ if (err instanceof TimeoutError)
6725
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
6527
6726
  // fall through to the timeout result below
6528
6727
  }
6529
6728
  return {
@@ -6571,6 +6770,7 @@ export async function runTestRunAll(opts, deps = {}) {
6571
6770
  }
6572
6771
  catch (err) {
6573
6772
  if (err instanceof TimeoutError) {
6773
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
6574
6774
  return {
6575
6775
  testId: entry.testId,
6576
6776
  runId,
@@ -6685,6 +6885,13 @@ export async function runTestRunAll(opts, deps = {}) {
6685
6885
  : undefined;
6686
6886
  await writeBatchJUnitReportIfRequested(opts, freshRunResults, freshNameMap);
6687
6887
  out.print(jsonPayload);
6888
+ recordBatchOutcome({
6889
+ accepted: accepted.length,
6890
+ conflicts,
6891
+ deferred: deferred.length,
6892
+ skipped: skippedFrontend.length + skippedIntegration.length,
6893
+ results: freshRunResults,
6894
+ });
6688
6895
  // CI-native output layer (issue #99): emitted before the gate throws below so
6689
6896
  // the artifacts land even when the batch exits non-zero. The summary file is a
6690
6897
  // machine artifact written regardless of --output mode; stdout stays owned by
@@ -6707,6 +6914,12 @@ export async function runTestRunAll(opts, deps = {}) {
6707
6914
  const failure = resolveWaitFailure(freshRunResults, { timeoutSeconds: opts.timeoutSeconds });
6708
6915
  if (failure)
6709
6916
  throw failure;
6917
+ // Nothing of ours dispatched (the poll set was auto-resumed in-flight runs
6918
+ // only) and every remaining conflict is a credits refusal → exit 12, the same
6919
+ // shape the single-run route answers.
6920
+ if (isAllCreditsRefusal({ accepted, deferred, conflicts })) {
6921
+ throw insufficientCreditsConflictError(conflicts, batchApiUrl);
6922
+ }
6710
6923
  // Hard conflicts (a run already in flight for the test that we could NOT
6711
6924
  // auto-resume — no `currentRunId` to poll) mean those tests never ran. In a
6712
6925
  // MIXED batch, the accepted/resumed runs above already made `pollable`
@@ -6750,6 +6963,7 @@ export async function runTestRunAll(opts, deps = {}) {
6750
6963
  */
6751
6964
  export async function runTestRerun(opts, deps = {}) {
6752
6965
  assertIdempotencyKey(opts.idempotencyKey);
6966
+ const environment = normalizeEnvironmentName(opts.environment);
6753
6967
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
6754
6968
  const out = makeOutput(opts.output, deps);
6755
6969
  // -------------------------------------------------------------------------
@@ -6791,6 +7005,13 @@ export async function runTestRerun(opts, deps = {}) {
6791
7005
  throw localValidationError('skip-terminal', '--skip-terminal only applies with --all (it narrows which project tests get reran). ' +
6792
7006
  'Remove --skip-terminal, or add --all --project <id>.');
6793
7007
  }
7008
+ // --allow-empty only softens the --all zero-dispatch gate; anywhere else it
7009
+ // would be silently ignored — reject loudly, matching the sibling --all-only
7010
+ // flag guards above.
7011
+ if (opts.allowEmpty === true && !opts.all) {
7012
+ throw localValidationError('allow-empty', '--allow-empty only applies with --all (it permits an empty resolved rerun set). ' +
7013
+ 'Remove --allow-empty, or add --all --project <id>.');
7014
+ }
6794
7015
  if (!Number.isInteger(opts.maxConcurrency) ||
6795
7016
  opts.maxConcurrency < 1 ||
6796
7017
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
@@ -6821,6 +7042,7 @@ export async function runTestRerun(opts, deps = {}) {
6821
7042
  source: 'cli',
6822
7043
  autoHeal: effectiveAutoHeal,
6823
7044
  skipDependencies: opts.skipDependencies,
7045
+ ...(environment !== undefined ? { environment } : {}),
6824
7046
  },
6825
7047
  idempotencyKey,
6826
7048
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
@@ -6838,6 +7060,7 @@ export async function runTestRerun(opts, deps = {}) {
6838
7060
  testIds,
6839
7061
  autoHeal: effectiveAutoHeal,
6840
7062
  skipDependencies: opts.skipDependencies,
7063
+ ...(environment !== undefined ? { environment } : {}),
6841
7064
  },
6842
7065
  idempotencyKey,
6843
7066
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
@@ -6854,6 +7077,7 @@ export async function runTestRerun(opts, deps = {}) {
6854
7077
  // D4: under --wait, raise the per-request timeout to cover --timeout so a
6855
7078
  // slow rerun trigger / long-poll under load isn't cut at the 120s default.
6856
7079
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
7080
+ // `--env` gate — see `runTestRun`. Before the type probe and every dispatch.
6857
7081
  const idempotencyKey = opts.idempotencyKey ?? `cli-rerun-${randomUUID()}`;
6858
7082
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
6859
7083
  stderrFn(`idempotency-key: ${idempotencyKey}`);
@@ -6894,6 +7118,7 @@ export async function runTestRerun(opts, deps = {}) {
6894
7118
  // omitting the key on opt-out silently discarded --no-auto-heal.
6895
7119
  autoHeal: effectiveAutoHeal,
6896
7120
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
7121
+ ...(environment !== undefined ? { environment } : {}),
6897
7122
  }, { idempotencyKey });
6898
7123
  }
6899
7124
  catch (err) {
@@ -7036,8 +7261,10 @@ export async function runTestRerun(opts, deps = {}) {
7036
7261
  return { kind: 'terminal', run: finalRun };
7037
7262
  }
7038
7263
  catch (err) {
7039
- if (err instanceof TimeoutError)
7264
+ if (err instanceof TimeoutError) {
7265
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
7040
7266
  return { kind: 'timeout' };
7267
+ }
7041
7268
  // Preserve the two intentional whole-fan-out aborts: each has a
7042
7269
  // dedicated outer-catch branch (RequestTimeoutError → all-running
7043
7270
  // partial + re-attach hints + exit 7; InterruptError → DEV-331
@@ -7309,6 +7536,7 @@ export async function runTestRerun(opts, deps = {}) {
7309
7536
  }
7310
7537
  catch (err) {
7311
7538
  if (err instanceof TimeoutError) {
7539
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
7312
7540
  ticker.finalize(`Run ${rerunResp.runId} — timed out after ${opts.timeoutSeconds}s`);
7313
7541
  // Mirror the RequestTimeoutError path: emit a partial run to stdout so
7314
7542
  // JSON consumers and AI agents can grab the runId and chain into
@@ -7460,6 +7688,20 @@ export async function runTestRerun(opts, deps = {}) {
7460
7688
  if (testIds.length === 0) {
7461
7689
  stderrFn(`No tests found in project ${opts.projectId} matching filters — nothing to rerun.`);
7462
7690
  out.print({ accepted: [], deferred: [], conflicts: [], closure: { byProject: [] } });
7691
+ // Zero-dispatch: emit the CI artifacts and fail with exit 5 unless
7692
+ // --allow-empty, so a filter that matches nothing (or an empty project)
7693
+ // can't turn a rerun gate permanently green — same contract as
7694
+ // `test run --all`. Returns here only under
7695
+ // --allow-empty.
7696
+ await finishZeroDispatchBatch({
7697
+ reason: `no tests in project ${opts.projectId} match the requested filters`,
7698
+ skipped: [],
7699
+ allowEmpty: opts.allowEmpty === true,
7700
+ opts,
7701
+ deps,
7702
+ stderrFn,
7703
+ label: 'rerun',
7704
+ });
7463
7705
  return undefined;
7464
7706
  }
7465
7707
  stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${opts.projectId} for batch rerun.`);
@@ -7503,6 +7745,7 @@ export async function runTestRerun(opts, deps = {}) {
7503
7745
  // opt-out — see the matching comment on the single-rerun call site.
7504
7746
  autoHeal: effectiveAutoHeal,
7505
7747
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
7748
+ ...(environment !== undefined ? { environment } : {}),
7506
7749
  }, { idempotencyKey: chunkKey });
7507
7750
  chunkResponses.push(chunkResp);
7508
7751
  }
@@ -7727,6 +7970,21 @@ export async function runTestRerun(opts, deps = {}) {
7727
7970
  }
7728
7971
  }
7729
7972
  }
7973
+ /**
7974
+ * Every requested id landed in `notFound` and nothing was queued. A rerun
7975
+ * where every id was unusable is not a success: exit 4 (NOT_FOUND), the same
7976
+ * code `testlist run` uses for a `--case` miss, instead of the silent exit 0
7977
+ * that made a CI gate pass green on zero dispatched runs.
7978
+ */
7979
+ const rerunAllNotFoundError = (ids) => ApiError.fromEnvelope({
7980
+ error: {
7981
+ code: 'NOT_FOUND',
7982
+ message: `Batch rerun: nothing was queued — ${ids.length} test id${ids.length !== 1 ? 's have' : ' has'} no replayable run.`,
7983
+ nextAction: `Trigger a first (fresh) run instead: testsprite test run <id> — ids: ${ids.join(' ')}`,
7984
+ requestId: 'local',
7985
+ details: { notFound: [...ids] },
7986
+ },
7987
+ });
7730
7988
  // Print the (deduped) advisory set once, after any D3 retries have
7731
7989
  // had a chance to contribute one, not once per chunk/attempt.
7732
7990
  emitRerunAdvisories(stderrFn, advisories);
@@ -7755,6 +8013,12 @@ export async function runTestRerun(opts, deps = {}) {
7755
8013
  },
7756
8014
  });
7757
8015
  }
8016
+ // All-notFound no-op: every id was unusable (no replayable run), nothing
8017
+ // was queued — exit 4, matching `testlist run`'s not-found gate, instead of
8018
+ // the silent exit 0 that let a rerun gate pass green on zero runs.
8019
+ if (accepted.length === 0 && notFound.length > 0) {
8020
+ throw rerunAllNotFoundError(notFound);
8021
+ }
7758
8022
  // [P2] Return post-retry state including merged notFound.
7759
8023
  return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
7760
8024
  }
@@ -7793,6 +8057,12 @@ export async function runTestRerun(opts, deps = {}) {
7793
8057
  },
7794
8058
  });
7795
8059
  }
8060
+ // All-notFound no-op (--wait path): the CI artifacts above already carry the
8061
+ // not_found rows as `skipped`; the exit code must agree that nothing ran —
8062
+ // exit 4 instead of the silent exit 0 measured before this fix.
8063
+ if (notFound.length > 0) {
8064
+ throw rerunAllNotFoundError(notFound);
8065
+ }
7796
8066
  // [P2] Return post-retry state including merged notFound.
7797
8067
  return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
7798
8068
  }
@@ -7838,6 +8108,7 @@ export async function runTestRerun(opts, deps = {}) {
7838
8108
  }
7839
8109
  catch (err) {
7840
8110
  if (err instanceof TimeoutError) {
8111
+ deps.onWaitTimeout?.({ reason: 'wait_timeout' });
7841
8112
  return {
7842
8113
  testId: entry.testId,
7843
8114
  runId: entry.runId,
@@ -8446,11 +8717,11 @@ export function createTestCommand(deps = {}) {
8446
8717
  });
8447
8718
  test
8448
8719
  .command('steps <test-id>')
8449
- .description('List the steps for a test (server returns the cumulative log across every run; use --run-id to scope to one run)')
8720
+ .description('List the steps of the latest run (use --run-id for a specific run)')
8450
8721
  .option('--page-size <n>', 'service page size hint (1-100, default 25)')
8451
8722
  .option('--max-items <n>', 'stop after this many items across auto-paged pages')
8452
8723
  .option('--starting-token <token>', 'opaque cursor from a previous response')
8453
- .option('--run-id <id>', "Filter steps to those belonging to the specified runId. Useful for tests that have been run multiple times — by default 'test steps' returns the cumulative log across every run. Note: legacy step records (pre-M3.1) with null runIdIfAvailable are excluded when this flag is set.")
8724
+ .option('--run-id <id>', 'Show steps of the specified run instead of the latest run.')
8454
8725
  .addHelpText('after', GLOBAL_OPTS_HINT)
8455
8726
  .action(async (testId, cmdOpts, command) => {
8456
8727
  await runSteps({
@@ -8502,10 +8773,16 @@ export function createTestCommand(deps = {}) {
8502
8773
  .option('--cursor <token>', 'with --history: opaque cursor from a prior page')
8503
8774
  .option('--rerun', 'with --history: show only reruns')
8504
8775
  .option('--no-rerun', 'with --history: show only fresh (non-rerun) runs')
8776
+ .option('--env <name>', 'with --history: only runs whose credentials came from this project environment')
8505
8777
  .option('--columns <list>', 'with --history: select/reorder text table columns')
8506
8778
  .option('--no-header', 'with --history: suppress the text table header row')
8507
8779
  .addHelpText('after', GLOBAL_OPTS_HINT)
8508
8780
  .action(async (testId, cmdOpts, command) => {
8781
+ // `--env` narrows the history list; on the latest-result path it would be
8782
+ // silently ignored (same rule as `test run --filter` without `--all`).
8783
+ if (cmdOpts.env !== undefined && !cmdOpts.history) {
8784
+ throw localValidationError('env', '--env only applies with --history (it filters the run list by environment). Add --history, or remove --env');
8785
+ }
8509
8786
  if (cmdOpts.history) {
8510
8787
  // M3.4 piece-5: --history mode — list prior runs.
8511
8788
  await runResultHistory({
@@ -8513,6 +8790,7 @@ export function createTestCommand(deps = {}) {
8513
8790
  testId,
8514
8791
  source: parseEnumFlag(cmdOpts.source, 'source', RUN_SOURCES),
8515
8792
  since: cmdOpts.since,
8793
+ environment: cmdOpts.env,
8516
8794
  pageSize: cmdOpts.pageSize !== undefined
8517
8795
  ? parseNumericFlag(cmdOpts.pageSize, 'page-size')
8518
8796
  : undefined,
@@ -8645,11 +8923,16 @@ export function createTestCommand(deps = {}) {
8645
8923
  .option('--tunnel-client <id>', 'with --local, attach to a tunnel already running under `testsprite tunnel start` instead ' +
8646
8924
  'of opening a new one. The id is the non-secret handle that command prints; the tunnel ' +
8647
8925
  'stays owned by that process and is not closed when this run finishes.')
8648
- .option('--no-cancel-on-interrupt', 'with --local, leave the run executing (and billing) when this command stops waiting. By ' +
8649
- 'default a --local run is cancelled at that point, because its tunnel closes with this ' +
8650
- 'process and the run could then only fail.')
8926
+ .option('--no-cancel-on-interrupt', 'with --local, skip automatic cancellation when an owned tunnel is about to close or a ' +
8927
+ "borrowed tunnel's owner disappears. An ordinary interrupt of a borrowed run never " +
8928
+ 'cancels it because its tunnel remains alive.')
8929
+ .option('--env <name>', 'run against the named project environment — its test-account credentials, auto-auth and ' +
8930
+ 'OTP settings (names: `testsprite project env list <project-id>`). Combine with --local ' +
8931
+ 'to use those credentials against your own machine, or with --target-url against another ' +
8932
+ "address; without either, the run opens that environment's URL. Omit --env to keep using " +
8933
+ "the project's default environment. Also applies with --all.")
8651
8934
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
8652
- .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
8935
+ .option('--timeout <s>', 'with --wait, max seconds to wait (1–3600; default 600, or 1200 with --local)')
8653
8936
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
8654
8937
  .option('--all', 'run all tests in the project (wave-ordered fresh run; uses --project or TESTSPRITE_PROJECT_ID). Mutually exclusive with <test-id>.', false)
8655
8938
  .option('--project <id>', 'project id (with --all, overrides TESTSPRITE_PROJECT_ID; returned by `testsprite project list`)')
@@ -8658,8 +8941,8 @@ export function createTestCommand(deps = {}) {
8658
8941
  .option('--report <format>', 'with --all --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
8659
8942
  .option('--report-file <path>', 'output path for --report (atomic write)')
8660
8943
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
8661
- .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')
8662
- .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')
8944
+ .option('--gh-output', 'with --wait (single test or --all): emit GitHub-native output (::error:: annotations for failed/timed-out runs, ::warning:: for never-dispatched tests; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
8945
+ .option('--summary-file <path>', 'with --wait (single test or --all): also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
8663
8946
  .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')
8664
8947
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
8665
8948
  ' testsprite test run --all --project <id> run all project tests in wave order\n' +
@@ -8768,6 +9051,7 @@ export function createTestCommand(deps = {}) {
8768
9051
  ghOutput: cmdOpts.ghOutput === true,
8769
9052
  summaryFile: cmdOpts.summaryFile,
8770
9053
  allowEmpty: cmdOpts.allowEmpty === true,
9054
+ environment: cmdOpts.env,
8771
9055
  }, deps);
8772
9056
  return;
8773
9057
  }
@@ -8801,12 +9085,15 @@ export function createTestCommand(deps = {}) {
8801
9085
  ...(cmdOpts.tunnelClient !== undefined ? { tunnelClientId: cmdOpts.tunnelClient } : {}),
8802
9086
  cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
8803
9087
  wait: effectiveWait,
8804
- timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
9088
+ timeoutSeconds: usingLocal && cmdOpts.timeout === undefined
9089
+ ? DEFAULT_LOCAL_RUN_TIMEOUT_SECONDS
9090
+ : parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
8805
9091
  // B2(c): tell runTestRun whether --timeout was explicitly provided.
8806
9092
  timeoutIsDefault: cmdOpts.timeout === undefined,
8807
9093
  idempotencyKey: cmdOpts.idempotencyKey,
8808
9094
  ghOutput: cmdOpts.ghOutput === true,
8809
9095
  summaryFile: cmdOpts.summaryFile,
9096
+ environment: cmdOpts.env,
8810
9097
  }, deps);
8811
9098
  });
8812
9099
  test
@@ -8868,8 +9155,8 @@ export function createTestCommand(deps = {}) {
8868
9155
  ' 0 passed (or queued without --wait)\n' +
8869
9156
  ' 1 failed / blocked / cancelled\n' +
8870
9157
  ' 3 auth error\n' +
8871
- ' 4 test not found\n' +
8872
- ' 5 validation error\n' +
9158
+ ' 4 test not found (single), or batch: nothing queued — every id had no replayable run\n' +
9159
+ ' 5 validation error, or --all resolved zero tests (pass --allow-empty to exit 0)\n' +
8873
9160
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
8874
9161
  ' 7 timeout or deferred — resume with: testsprite test wait <run-id>, ' +
8875
9162
  'or stop it with: testsprite test cancel <run-id>\n' +
@@ -8886,13 +9173,17 @@ export function createTestCommand(deps = {}) {
8886
9173
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
8887
9174
  .option('--no-auto-heal', 'opt out of AI heal-on-drift for this FE rerun (default: auto-heal is ON). Costs 0.2 credits per engage when a step has drifted. Ignored for backend tests.')
8888
9175
  .option('--skip-dependencies', 'BE only: rerun only the named test without expanding the producer/teardown closure', false)
9176
+ .option('--env <name>', 'replay against the named project environment — its test-account credentials, auto-auth and ' +
9177
+ 'OTP settings (names: `testsprite project env list <project-id>`). Omit to keep using the ' +
9178
+ "project's default environment. Applies to every test of a batch rerun.")
8889
9179
  .option('--max-concurrency <n>', `with --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
8890
9180
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --verbose if auto-generated.')
8891
9181
  .option('--report <format>', 'with batch --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
8892
9182
  .option('--report-file <path>', 'output path for --report (atomic write)')
8893
9183
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
8894
- .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')
8895
- .option('--summary-file <path>', 'with batch --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
9184
+ .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')
9185
+ .option('--summary-file <path>', 'with batch --wait: also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
9186
+ .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')
8896
9187
  .addHelpText('after', '\nNotes:\n' +
8897
9188
  ' • rerun replays a saved run/script and is MORE LENIENT than a fresh `test run`\n' +
8898
9189
  ' (auto-heal can pass steps that have drifted) — for strict scoring/regression,\n' +
@@ -8946,6 +9237,7 @@ export function createTestCommand(deps = {}) {
8946
9237
  autoHeal: cmdOpts.autoHeal !== false,
8947
9238
  autoHealExplicit: false,
8948
9239
  skipDependencies: cmdOpts.skipDependencies === true,
9240
+ environment: cmdOpts.env,
8949
9241
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
8950
9242
  DEFAULT_BATCH_RUN_CONCURRENCY,
8951
9243
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -8954,6 +9246,7 @@ export function createTestCommand(deps = {}) {
8954
9246
  reportSuiteName: cmdOpts.reportSuiteName,
8955
9247
  ghOutput: cmdOpts.ghOutput === true,
8956
9248
  summaryFile: cmdOpts.summaryFile,
9249
+ allowEmpty: cmdOpts.allowEmpty === true,
8957
9250
  }, deps);
8958
9251
  });
8959
9252
  // -------------------------------------------------------------------------
@@ -9920,6 +10213,8 @@ function renderResultText(r) {
9920
10213
  lines.push(`runId: ${r.runIdIfAvailable}`);
9921
10214
  if (r.codeVersion !== null)
9922
10215
  lines.push(`codeVersion: ${r.codeVersion}`);
10216
+ if (r.environment)
10217
+ lines.push(`environment: ${describeEnvironmentLine(r)}`);
9923
10218
  if (r.targetUrl !== null)
9924
10219
  lines.push(`targetUrl: ${r.targetUrl}`);
9925
10220
  lines.push(`summary: ${r.summary}`);