@testsprite/testsprite-cli 0.11.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.
@@ -16,10 +16,11 @@ 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';
@@ -4100,11 +4101,13 @@ export async function runResultHistory(opts, deps = {}) {
4100
4101
  const client = makeClient(opts, deps);
4101
4102
  const pageSize = opts.pageSize ?? 20;
4102
4103
  const sinceIso = opts.since !== undefined ? parseDuration(opts.since) : undefined;
4104
+ const environment = normalizeEnvironmentName(opts.environment);
4103
4105
  const resp = await client.listTestRuns(opts.testId, {
4104
4106
  cursor: opts.cursor,
4105
4107
  pageSize,
4106
4108
  source: opts.source,
4107
4109
  since: sinceIso,
4110
+ ...(environment !== undefined ? { environment } : {}),
4108
4111
  });
4109
4112
  // Client-side rerun filter (--rerun / --no-rerun). isRerun is on every row;
4110
4113
  // the backend has no rerun filter. Undefined → no filter. Like --source, a
@@ -4162,10 +4165,25 @@ export async function runResultHistory(opts, deps = {}) {
4162
4165
  }
4163
4166
  return { ...resp, runs };
4164
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
+ }
4165
4178
  const RUN_HISTORY_TABLE_COLUMNS = [
4166
4179
  { header: 'RUN ID', width: 36, render: run => run.runId },
4167
4180
  { header: 'STATUS', width: 10, render: run => run.status },
4168
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
+ },
4169
4187
  { header: 'RERUN?', width: 6, render: run => (run.isRerun ? 'yes' : 'no') },
4170
4188
  { header: 'WHEN', width: 25, render: run => run.createdAt },
4171
4189
  {
@@ -4659,6 +4677,8 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
4659
4677
  ];
4660
4678
  if (run.codeVersion !== null)
4661
4679
  lines.push(`codeVersion ${run.codeVersion}`);
4680
+ if (run.environment)
4681
+ lines.push(`environment ${describeEnvironmentLine(run)}`);
4662
4682
  if (run.targetUrl !== null)
4663
4683
  lines.push(`targetUrl ${run.targetUrl}`);
4664
4684
  lines.push(`createdAt ${run.createdAt}`);
@@ -4684,9 +4704,18 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
4684
4704
  // confusing "0/0 (passed=0, failed=0)" which reads like a broken no-op.
4685
4705
  lines.push(`steps n/a (backend)`);
4686
4706
  }
4687
- else if (run.stepSummary) {
4707
+ else if (run.stepSummary && run.stepSummary.total > 0) {
4688
4708
  lines.push(`steps ${run.stepSummary.completed}/${run.stepSummary.total} (passed=${run.stepSummary.passedCount}, failed=${run.stepSummary.failedCount})`);
4689
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
+ }
4690
4719
  // Closing pointer: where to inspect this run in the Portal (video, steps,
4691
4720
  // screenshots). Present only when withRunDashboardUrl could resolve it.
4692
4721
  if (run.dashboardUrl)
@@ -4732,6 +4761,8 @@ function renderTriggerRunText(r) {
4732
4761
  ];
4733
4762
  if (r.codeVersion !== null)
4734
4763
  lines.push(`codeVersion ${r.codeVersion}`);
4764
+ if (r.environment)
4765
+ lines.push(`environment ${describeEnvironmentLine(r)}`);
4735
4766
  if (r.targetUrl !== null)
4736
4767
  lines.push(`targetUrl ${r.targetUrl}`);
4737
4768
  // Same line the run card prints after `--wait` (`renderRunResponseText`), so a
@@ -4741,6 +4772,31 @@ function renderTriggerRunText(r) {
4741
4772
  lines.push(`dashboard ${r.dashboardUrl}`);
4742
4773
  return lines.join('\n');
4743
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
+ }
4744
4800
  /**
4745
4801
  * Validate the `--timeout` flag value. Returns a clamped integer in
4746
4802
  * range [1, 3600], or the default when absent.
@@ -4777,6 +4833,7 @@ function parseStepTimeoutFlag(raw, flagName) {
4777
4833
  */
4778
4834
  export async function runTestRun(opts, deps = {}) {
4779
4835
  assertIdempotencyKey(opts.idempotencyKey);
4836
+ const environment = normalizeEnvironmentName(opts.environment);
4780
4837
  // --local resolution runs FIRST and touches nothing: every refusal below
4781
4838
  // must happen before a client is even constructed, because the guarantee
4782
4839
  // this feature sells is that a doomed `--local` run never gets a run row,
@@ -4834,6 +4891,7 @@ export async function runTestRun(opts, deps = {}) {
4834
4891
  // handle, the same reason `dashboardUrl` is suppressed under
4835
4892
  // --dry-run rather than pointing at the canned sample id.
4836
4893
  ...(isTunnelRun ? { tunnelClientId: '<minted at run time>' } : {}),
4894
+ ...(environment !== undefined ? { environment } : {}),
4837
4895
  },
4838
4896
  idempotencyKey,
4839
4897
  ...(isTunnelRun
@@ -4865,6 +4923,7 @@ export async function runTestRun(opts, deps = {}) {
4865
4923
  const out = makeOutput(opts.output, deps);
4866
4924
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4867
4925
  const shutdown = shutdownOf(deps);
4926
+ // `--env` is feature-gated per workspace. Refuse here — one read-only `/me`,
4868
4927
  // Pre-charge reachability preflight — real path only (dry-run
4869
4928
  // makes zero network calls by convention), after `assertNotLocal` and
4870
4929
  // before the trigger POST so a doomed run never gets a run row or charge.
@@ -4943,6 +5002,9 @@ export async function runTestRun(opts, deps = {}) {
4943
5002
  // The client ID only. The secret stays in this process and never
4944
5003
  // reaches a request body, an idempotency row, or an audit line.
4945
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 } : {}),
4946
5008
  };
4947
5009
  const result = isTunnelRun
4948
5010
  ? await withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, triggerClient => triggerClient.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey }))
@@ -5216,6 +5278,7 @@ export async function runTestRun(opts, deps = {}) {
5216
5278
  // JSON consumers and AI agents can grab the runId and chain into
5217
5279
  // `testsprite test wait <runId>` without parsing the stderr error envelope.
5218
5280
  const detach = await settleTunnelDetach('timeout');
5281
+ recordTelemetryExtras({ passed: 0, failed: 0, blocked: 0, timedOut: 1 });
5219
5282
  deps.onWaitTimeout?.({
5220
5283
  reason: 'wait_timeout',
5221
5284
  ...(tunnelSession
@@ -5411,6 +5474,9 @@ export async function runTestRun(opts, deps = {}) {
5411
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.`
5412
5475
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
5413
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]));
5414
5480
  // CI-native output layer (issue #99): single-test parity with the --all batch.
5415
5481
  // Emitted before the exit-code gate throws below so the summary file and
5416
5482
  // annotations land even when the run exits non-zero (mirrors the batch path).
@@ -6120,9 +6186,10 @@ function zeroDispatchReason(skippedFrontend, skippedIntegration) {
6120
6186
  * Handle a batch invocation that dispatched ZERO tests — all skipped, an empty
6121
6187
  * project, or a `--filter` that matched nothing. Left alone this exits 0 with no
6122
6188
  * 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).
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).
6126
6193
  *
6127
6194
  * `skipped` is the union of skipped FE + integration tests (rendered as
6128
6195
  * `<skipped/>` JUnit cases and non-passed summary rows so they're visible);
@@ -6133,14 +6200,18 @@ async function finishZeroDispatchBatch(params) {
6133
6200
  const runs = skipped.length > 0
6134
6201
  ? skipped.map(testId => ({ testId, status: 'skipped', error: reason }))
6135
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.
6136
6206
  const summary = {
6137
6207
  total: runs.length,
6138
6208
  passed: 0,
6139
- failed: runs.length,
6209
+ failed: 0,
6210
+ skipped: runs.length,
6140
6211
  timedOut: 0,
6141
6212
  runs,
6142
6213
  };
6143
- // Emit the in-memory artifacts (summary + `::error::` annotation) FIRST: they
6214
+ // Emit the in-memory artifacts (summary + `::warning::` annotation) FIRST: they
6144
6215
  // can't fail on I/O, so the "show WHY it's red" diagnostics always land — even
6145
6216
  // if the JUnit path below is misconfigured. Ordering these after the file write
6146
6217
  // would let an unwritable --report-file throw (exit 10) preempt both the
@@ -6176,6 +6247,7 @@ async function finishZeroDispatchBatch(params) {
6176
6247
  */
6177
6248
  export async function runTestRunAll(opts, deps = {}) {
6178
6249
  assertIdempotencyKey(opts.idempotencyKey);
6250
+ const environment = normalizeEnvironmentName(opts.environment);
6179
6251
  const projectId = resolveProjectId(opts.projectId, deps);
6180
6252
  requireProjectId(projectId);
6181
6253
  if (!Number.isInteger(opts.maxConcurrency) ||
@@ -6207,6 +6279,7 @@ export async function runTestRunAll(opts, deps = {}) {
6207
6279
  projectId,
6208
6280
  testIds: opts.nameFilter ? ['<filtered by --filter>'] : undefined,
6209
6281
  source: 'cli',
6282
+ ...(environment !== undefined ? { environment } : {}),
6210
6283
  },
6211
6284
  idempotencyKey,
6212
6285
  ...(opts.wait ? { thenPoll: '/api/cli/v1/runs/<run-id>?waitSeconds=25' } : {}),
@@ -6219,6 +6292,8 @@ export async function runTestRunAll(opts, deps = {}) {
6219
6292
  }
6220
6293
  // D4: under --wait, raise per-request timeout to cover --timeout.
6221
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.
6222
6297
  // Portal deep links for batch output: every test in the batch belongs to
6223
6298
  // opts.projectId, so per-item dashboardUrl needs no extra wire data. The
6224
6299
  // project-level URL closes out text-mode output ("watch the wave here").
@@ -6275,7 +6350,7 @@ export async function runTestRunAll(opts, deps = {}) {
6275
6350
  });
6276
6351
  // Zero-dispatch (a --filter that matched nothing): emit the CI artifacts
6277
6352
  // 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.
6353
+ // gate permanently green. Returns here only under --allow-empty.
6279
6354
  await finishZeroDispatchBatch({
6280
6355
  reason: `--filter "${opts.nameFilter}" matched no tests in project ${projectId}`,
6281
6356
  skipped: [],
@@ -6294,6 +6369,7 @@ export async function runTestRunAll(opts, deps = {}) {
6294
6369
  projectId,
6295
6370
  ...(testIds !== undefined ? { testIds } : {}),
6296
6371
  source: 'cli',
6372
+ ...(environment !== undefined ? { environment } : {}),
6297
6373
  }, { idempotencyKey });
6298
6374
  // Project-level "watch it here" link. A V3 backend sends it (string, or
6299
6375
  // `null` when no single page exists — e.g. a `--all` that fanned out over
@@ -6357,11 +6433,22 @@ export async function runTestRunAll(opts, deps = {}) {
6357
6433
  }
6358
6434
  return lines.join('\n');
6359
6435
  });
6436
+ recordBatchOutcome({
6437
+ accepted: accepted.length,
6438
+ conflicts,
6439
+ deferred: deferred.length,
6440
+ skipped: skippedFrontend.length + skippedIntegration.length,
6441
+ });
6360
6442
  // Rate-deferred tests were NOT dispatched → signal incomplete (exit 7),
6361
6443
  // mirroring `test rerun --all`. The user retries with a fresh invocation.
6362
6444
  if (deferred.length > 0) {
6363
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);
6364
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
+ }
6365
6452
  // Nothing queued and everything was an in-flight conflict → surface CONFLICT (exit 6).
6366
6453
  if (accepted.length === 0 && conflicts.length > 0) {
6367
6454
  throw ApiError.fromEnvelope({
@@ -6375,7 +6462,7 @@ export async function runTestRunAll(opts, deps = {}) {
6375
6462
  });
6376
6463
  }
6377
6464
  // 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).
6465
+ // all tests were skipped, or the project has none. Don't exit 0.
6379
6466
  if (accepted.length === 0) {
6380
6467
  await finishZeroDispatchBatch({
6381
6468
  reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
@@ -6535,6 +6622,12 @@ export async function runTestRunAll(opts, deps = {}) {
6535
6622
  skippedIntegration,
6536
6623
  };
6537
6624
  out.print(finalResp);
6625
+ recordBatchOutcome({
6626
+ accepted: accepted.length,
6627
+ conflicts,
6628
+ deferred: deferred.length,
6629
+ skipped: skippedFrontend.length + skippedIntegration.length,
6630
+ });
6538
6631
  // Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
6539
6632
  // mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
6540
6633
  // Emit the deferred/conflict summary + annotations first so CI shows them (the
@@ -6549,6 +6642,11 @@ export async function runTestRunAll(opts, deps = {}) {
6549
6642
  if (deferred.length > 0) {
6550
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);
6551
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
+ }
6552
6650
  if (conflicts.length > 0) {
6553
6651
  throw ApiError.fromEnvelope({
6554
6652
  error: {
@@ -6562,7 +6660,7 @@ export async function runTestRunAll(opts, deps = {}) {
6562
6660
  }
6563
6661
  // Reached only when nothing was queued and nothing is pending: all tests were
6564
6662
  // 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).
6663
+ // fail unless --allow-empty — never a silent exit 0.
6566
6664
  await finishZeroDispatchBatch({
6567
6665
  reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
6568
6666
  skipped: [...skippedFrontend, ...skippedIntegration.map(s => s.testId)],
@@ -6787,6 +6885,13 @@ export async function runTestRunAll(opts, deps = {}) {
6787
6885
  : undefined;
6788
6886
  await writeBatchJUnitReportIfRequested(opts, freshRunResults, freshNameMap);
6789
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
+ });
6790
6895
  // CI-native output layer (issue #99): emitted before the gate throws below so
6791
6896
  // the artifacts land even when the batch exits non-zero. The summary file is a
6792
6897
  // machine artifact written regardless of --output mode; stdout stays owned by
@@ -6809,6 +6914,12 @@ export async function runTestRunAll(opts, deps = {}) {
6809
6914
  const failure = resolveWaitFailure(freshRunResults, { timeoutSeconds: opts.timeoutSeconds });
6810
6915
  if (failure)
6811
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
+ }
6812
6923
  // Hard conflicts (a run already in flight for the test that we could NOT
6813
6924
  // auto-resume — no `currentRunId` to poll) mean those tests never ran. In a
6814
6925
  // MIXED batch, the accepted/resumed runs above already made `pollable`
@@ -6852,6 +6963,7 @@ export async function runTestRunAll(opts, deps = {}) {
6852
6963
  */
6853
6964
  export async function runTestRerun(opts, deps = {}) {
6854
6965
  assertIdempotencyKey(opts.idempotencyKey);
6966
+ const environment = normalizeEnvironmentName(opts.environment);
6855
6967
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
6856
6968
  const out = makeOutput(opts.output, deps);
6857
6969
  // -------------------------------------------------------------------------
@@ -6893,6 +7005,13 @@ export async function runTestRerun(opts, deps = {}) {
6893
7005
  throw localValidationError('skip-terminal', '--skip-terminal only applies with --all (it narrows which project tests get reran). ' +
6894
7006
  'Remove --skip-terminal, or add --all --project <id>.');
6895
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
+ }
6896
7015
  if (!Number.isInteger(opts.maxConcurrency) ||
6897
7016
  opts.maxConcurrency < 1 ||
6898
7017
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
@@ -6923,6 +7042,7 @@ export async function runTestRerun(opts, deps = {}) {
6923
7042
  source: 'cli',
6924
7043
  autoHeal: effectiveAutoHeal,
6925
7044
  skipDependencies: opts.skipDependencies,
7045
+ ...(environment !== undefined ? { environment } : {}),
6926
7046
  },
6927
7047
  idempotencyKey,
6928
7048
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
@@ -6940,6 +7060,7 @@ export async function runTestRerun(opts, deps = {}) {
6940
7060
  testIds,
6941
7061
  autoHeal: effectiveAutoHeal,
6942
7062
  skipDependencies: opts.skipDependencies,
7063
+ ...(environment !== undefined ? { environment } : {}),
6943
7064
  },
6944
7065
  idempotencyKey,
6945
7066
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
@@ -6956,6 +7077,7 @@ export async function runTestRerun(opts, deps = {}) {
6956
7077
  // D4: under --wait, raise the per-request timeout to cover --timeout so a
6957
7078
  // slow rerun trigger / long-poll under load isn't cut at the 120s default.
6958
7079
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
7080
+ // `--env` gate — see `runTestRun`. Before the type probe and every dispatch.
6959
7081
  const idempotencyKey = opts.idempotencyKey ?? `cli-rerun-${randomUUID()}`;
6960
7082
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
6961
7083
  stderrFn(`idempotency-key: ${idempotencyKey}`);
@@ -6996,6 +7118,7 @@ export async function runTestRerun(opts, deps = {}) {
6996
7118
  // omitting the key on opt-out silently discarded --no-auto-heal.
6997
7119
  autoHeal: effectiveAutoHeal,
6998
7120
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
7121
+ ...(environment !== undefined ? { environment } : {}),
6999
7122
  }, { idempotencyKey });
7000
7123
  }
7001
7124
  catch (err) {
@@ -7565,6 +7688,20 @@ export async function runTestRerun(opts, deps = {}) {
7565
7688
  if (testIds.length === 0) {
7566
7689
  stderrFn(`No tests found in project ${opts.projectId} matching filters — nothing to rerun.`);
7567
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
+ });
7568
7705
  return undefined;
7569
7706
  }
7570
7707
  stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${opts.projectId} for batch rerun.`);
@@ -7608,6 +7745,7 @@ export async function runTestRerun(opts, deps = {}) {
7608
7745
  // opt-out — see the matching comment on the single-rerun call site.
7609
7746
  autoHeal: effectiveAutoHeal,
7610
7747
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
7748
+ ...(environment !== undefined ? { environment } : {}),
7611
7749
  }, { idempotencyKey: chunkKey });
7612
7750
  chunkResponses.push(chunkResp);
7613
7751
  }
@@ -7832,6 +7970,21 @@ export async function runTestRerun(opts, deps = {}) {
7832
7970
  }
7833
7971
  }
7834
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
+ });
7835
7988
  // Print the (deduped) advisory set once, after any D3 retries have
7836
7989
  // had a chance to contribute one, not once per chunk/attempt.
7837
7990
  emitRerunAdvisories(stderrFn, advisories);
@@ -7860,6 +8013,12 @@ export async function runTestRerun(opts, deps = {}) {
7860
8013
  },
7861
8014
  });
7862
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
+ }
7863
8022
  // [P2] Return post-retry state including merged notFound.
7864
8023
  return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
7865
8024
  }
@@ -7898,6 +8057,12 @@ export async function runTestRerun(opts, deps = {}) {
7898
8057
  },
7899
8058
  });
7900
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
+ }
7901
8066
  // [P2] Return post-retry state including merged notFound.
7902
8067
  return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
7903
8068
  }
@@ -8608,10 +8773,16 @@ export function createTestCommand(deps = {}) {
8608
8773
  .option('--cursor <token>', 'with --history: opaque cursor from a prior page')
8609
8774
  .option('--rerun', 'with --history: show only reruns')
8610
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')
8611
8777
  .option('--columns <list>', 'with --history: select/reorder text table columns')
8612
8778
  .option('--no-header', 'with --history: suppress the text table header row')
8613
8779
  .addHelpText('after', GLOBAL_OPTS_HINT)
8614
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
+ }
8615
8786
  if (cmdOpts.history) {
8616
8787
  // M3.4 piece-5: --history mode — list prior runs.
8617
8788
  await runResultHistory({
@@ -8619,6 +8790,7 @@ export function createTestCommand(deps = {}) {
8619
8790
  testId,
8620
8791
  source: parseEnumFlag(cmdOpts.source, 'source', RUN_SOURCES),
8621
8792
  since: cmdOpts.since,
8793
+ environment: cmdOpts.env,
8622
8794
  pageSize: cmdOpts.pageSize !== undefined
8623
8795
  ? parseNumericFlag(cmdOpts.pageSize, 'page-size')
8624
8796
  : undefined,
@@ -8754,6 +8926,11 @@ export function createTestCommand(deps = {}) {
8754
8926
  .option('--no-cancel-on-interrupt', 'with --local, skip automatic cancellation when an owned tunnel is about to close or a ' +
8755
8927
  "borrowed tunnel's owner disappears. An ordinary interrupt of a borrowed run never " +
8756
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.")
8757
8934
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
8758
8935
  .option('--timeout <s>', 'with --wait, max seconds to wait (1–3600; default 600, or 1200 with --local)')
8759
8936
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
@@ -8764,8 +8941,8 @@ export function createTestCommand(deps = {}) {
8764
8941
  .option('--report <format>', 'with --all --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
8765
8942
  .option('--report-file <path>', 'output path for --report (atomic write)')
8766
8943
  .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')
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')
8769
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')
8770
8947
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
8771
8948
  ' testsprite test run --all --project <id> run all project tests in wave order\n' +
@@ -8874,6 +9051,7 @@ export function createTestCommand(deps = {}) {
8874
9051
  ghOutput: cmdOpts.ghOutput === true,
8875
9052
  summaryFile: cmdOpts.summaryFile,
8876
9053
  allowEmpty: cmdOpts.allowEmpty === true,
9054
+ environment: cmdOpts.env,
8877
9055
  }, deps);
8878
9056
  return;
8879
9057
  }
@@ -8915,6 +9093,7 @@ export function createTestCommand(deps = {}) {
8915
9093
  idempotencyKey: cmdOpts.idempotencyKey,
8916
9094
  ghOutput: cmdOpts.ghOutput === true,
8917
9095
  summaryFile: cmdOpts.summaryFile,
9096
+ environment: cmdOpts.env,
8918
9097
  }, deps);
8919
9098
  });
8920
9099
  test
@@ -8976,8 +9155,8 @@ export function createTestCommand(deps = {}) {
8976
9155
  ' 0 passed (or queued without --wait)\n' +
8977
9156
  ' 1 failed / blocked / cancelled\n' +
8978
9157
  ' 3 auth error\n' +
8979
- ' 4 test not found\n' +
8980
- ' 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' +
8981
9160
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
8982
9161
  ' 7 timeout or deferred — resume with: testsprite test wait <run-id>, ' +
8983
9162
  'or stop it with: testsprite test cancel <run-id>\n' +
@@ -8994,13 +9173,17 @@ export function createTestCommand(deps = {}) {
8994
9173
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
8995
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.')
8996
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.")
8997
9179
  .option('--max-concurrency <n>', `with --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
8998
9180
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --verbose if auto-generated.')
8999
9181
  .option('--report <format>', 'with batch --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
9000
9182
  .option('--report-file <path>', 'output path for --report (atomic write)')
9001
9183
  .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')
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')
9004
9187
  .addHelpText('after', '\nNotes:\n' +
9005
9188
  ' • rerun replays a saved run/script and is MORE LENIENT than a fresh `test run`\n' +
9006
9189
  ' (auto-heal can pass steps that have drifted) — for strict scoring/regression,\n' +
@@ -9054,6 +9237,7 @@ export function createTestCommand(deps = {}) {
9054
9237
  autoHeal: cmdOpts.autoHeal !== false,
9055
9238
  autoHealExplicit: false,
9056
9239
  skipDependencies: cmdOpts.skipDependencies === true,
9240
+ environment: cmdOpts.env,
9057
9241
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
9058
9242
  DEFAULT_BATCH_RUN_CONCURRENCY,
9059
9243
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -9062,6 +9246,7 @@ export function createTestCommand(deps = {}) {
9062
9246
  reportSuiteName: cmdOpts.reportSuiteName,
9063
9247
  ghOutput: cmdOpts.ghOutput === true,
9064
9248
  summaryFile: cmdOpts.summaryFile,
9249
+ allowEmpty: cmdOpts.allowEmpty === true,
9065
9250
  }, deps);
9066
9251
  });
9067
9252
  // -------------------------------------------------------------------------
@@ -10028,6 +10213,8 @@ function renderResultText(r) {
10028
10213
  lines.push(`runId: ${r.runIdIfAvailable}`);
10029
10214
  if (r.codeVersion !== null)
10030
10215
  lines.push(`codeVersion: ${r.codeVersion}`);
10216
+ if (r.environment)
10217
+ lines.push(`environment: ${describeEnvironmentLine(r)}`);
10031
10218
  if (r.targetUrl !== null)
10032
10219
  lines.push(`targetUrl: ${r.targetUrl}`);
10033
10220
  lines.push(`summary: ${r.summary}`);