@testsprite/testsprite-cli 0.15.0 → 0.16.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 (38) hide show
  1. package/README.md +24 -16
  2. package/dist/commands/agent.js +7 -2
  3. package/dist/commands/auth.js +7 -3
  4. package/dist/commands/ci.js +20 -18
  5. package/dist/commands/completion.js +2 -1
  6. package/dist/commands/doctor.js +2 -1
  7. package/dist/commands/init.js +8 -2
  8. package/dist/commands/project-env.js +39 -17
  9. package/dist/commands/project-sign-in.js +9 -4
  10. package/dist/commands/project.js +28 -21
  11. package/dist/commands/schedule.js +24 -15
  12. package/dist/commands/test.d.ts +32 -26
  13. package/dist/commands/test.js +949 -769
  14. package/dist/commands/testlist.js +13 -3
  15. package/dist/commands/tunnel.js +23 -25
  16. package/dist/commands/usage.js +1 -0
  17. package/dist/index.js +9 -6
  18. package/dist/lib/conflict-reason.d.ts +24 -3
  19. package/dist/lib/conflict-reason.js +33 -2
  20. package/dist/lib/deprecate.d.ts +22 -0
  21. package/dist/lib/deprecate.js +26 -0
  22. package/dist/lib/dry-run/samples.js +14 -4
  23. package/dist/lib/environment-tunnel.d.ts +2 -1
  24. package/dist/lib/environment-tunnel.js +1 -4
  25. package/dist/lib/http.js +20 -2
  26. package/dist/lib/junit-report.d.ts +3 -0
  27. package/dist/lib/junit-report.js +8 -1
  28. package/dist/lib/output.d.ts +11 -1
  29. package/dist/lib/output.js +17 -2
  30. package/dist/lib/response-schemas.js +3 -0
  31. package/dist/lib/runs.types.d.ts +16 -0
  32. package/dist/lib/telemetry.d.ts +1 -1
  33. package/dist/lib/telemetry.js +2 -0
  34. package/dist/version.d.ts +1 -1
  35. package/dist/version.js +1 -1
  36. package/package.json +3 -3
  37. package/skills/testsprite-verify.codex.md +7 -7
  38. package/skills/testsprite-verify.skill.md +24 -21
@@ -1,10 +1,10 @@
1
1
  import { recordTelemetryTunnelOpened } from '../lib/telemetry.js';
2
2
  import { parseLoopbackTargetUrl } from '../lib/local-target.js';
3
- import { resolveEnvironmentRunTarget, readEnvironmentPreflight, ENVIRONMENT_PREFLIGHT_TIMEOUT_MS, assertNoTunnelOptions, severalIdsWithoutTunnel, quoteEnvironmentName, groupEnvironmentTargets, emitEnvironmentDispatchPartial, tunnelScopeError, withEnvironmentTunnel, } from '../lib/environment-tunnel.js';
3
+ import { resolveEnvironmentRunTarget, readEnvironmentPreflight, ENVIRONMENT_PREFLIGHT_TIMEOUT_MS, assertNoTunnelOptions, quoteEnvironmentName, groupEnvironmentTargets, emitEnvironmentDispatchPartial, tunnelScopeError, withEnvironmentTunnel, } from '../lib/environment-tunnel.js';
4
4
  import { closeSync, createWriteStream, existsSync, fstatSync, openSync, readFileSync, readSync, readdirSync, statSync, } from 'node:fs';
5
5
  import { rename, stat, unlink } from 'node:fs/promises';
6
6
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
7
- import { randomUUID } from 'node:crypto';
7
+ import { createHash, randomUUID } from 'node:crypto';
8
8
  import { Command } from 'commander';
9
9
  import { openInBrowser } from '../lib/browser.js';
10
10
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
@@ -18,6 +18,7 @@ import { defaultSleep, sleepUnlessInterrupted } from '../lib/poll-support.js';
18
18
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
19
19
  import { isStandingRateLimit, REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, } from '../lib/http.js';
20
20
  import { VERSION } from '../version.js';
21
+ import { emitDeprecationEntry, REMOVED_IN, TEST_FLAKY_DEPRECATION, TEST_RERUN_DEPRECATION, } from '../lib/deprecate.js';
21
22
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
22
23
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
23
24
  import { isTerminalStatus, pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
@@ -27,7 +28,7 @@ import { resolveWaitFailure, waitMemberError } from '../lib/wait-exit.js';
27
28
  import { resolveCiRunFailure } from '../lib/ci-run.js';
28
29
  import { RUN_SOURCES } from '../lib/runs.types.js';
29
30
  import { classifyBillingRefusal } from '../lib/billing-refusal.js';
30
- import { allConflictsInFlight, billingConflictLink, insufficientCreditsConflictError, isAllCreditsRefusal, isPausedRefusal, pausedConflictError, summarizeConflicts, } from '../lib/conflict-reason.js';
31
+ import { allConflictsInFlight, billingConflictLink, conflictNextAction, insufficientCreditsConflictError, isAllCreditsRefusal, isPausedRefusal, isProducerBlock, pausedConflictError, summarizeConflicts, } from '../lib/conflict-reason.js';
31
32
  import { isProxyAgentActive } from '../lib/proxy.js';
32
33
  import { assertNotLocal } from '../lib/target-url.js';
33
34
  import { assertTargetUrlReachable } from '../lib/target-url-preflight.js';
@@ -370,7 +371,7 @@ export async function runList(opts, deps = {}) {
370
371
  // sending. Friendlier error than waiting for the server's 400 with
371
372
  // a list of accepted tokens — and lets the user fix typos without
372
373
  // a round trip.
373
- validateStatusFilter(opts.status);
374
+ validateListStatusFilter(opts.status);
374
375
  const out = makeOutput(opts.output, deps);
375
376
  if (opts.output === 'text') {
376
377
  resolveTextColumns(opts.columns, TEST_LIST_COLUMNS);
@@ -385,7 +386,7 @@ export async function runList(opts, deps = {}) {
385
386
  projectId,
386
387
  type: opts.type,
387
388
  createdFrom: opts.createdFrom,
388
- status: opts.status,
389
+ status: opts.status === undefined ? undefined : expandNotRun(opts.status),
389
390
  ...(environment !== undefined ? { environment } : {}),
390
391
  };
391
392
  let page;
@@ -402,44 +403,17 @@ export async function runList(opts, deps = {}) {
402
403
  catch (err) {
403
404
  if (err instanceof InterruptError)
404
405
  throw err;
405
- if (err instanceof ApiError &&
406
- err.code === 'VALIDATION_ERROR' &&
407
- err.getDetail('field') === 'environment' &&
408
- Array.isArray(err.getDetail('available')) &&
409
- environment !== undefined) {
410
- const available = err.getDetail('available').filter((name) => typeof name === 'string');
411
- if (available.length > 0 && !err.nextAction.includes(available.join(', '))) {
412
- const hint = `Flag \`--env\` is invalid: unknown environment '${environment}'; use one of: ${available.join(', ')}.`;
413
- throw new ApiError({
414
- code: err.code,
415
- message: err.message,
416
- nextAction: err.nextAction ? `${hint} ${err.nextAction}` : hint,
417
- requestId: err.requestId,
418
- details: err.details,
419
- }, err.httpStatus, err.retryAfterMs);
420
- }
421
- }
422
- throw err;
406
+ throw withUnknownEnvironmentHint(err, environment);
423
407
  }
424
408
  if (environment !== undefined) {
425
409
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
426
410
  if (opts.output === 'text' && opts.noHeader) {
427
411
  stderr(`Frontend test status requested for environment '${environment}'.`);
428
412
  }
429
- if (page.items.length > 0 &&
430
- !page.items.some(test => test.headlineEnvironment !== undefined || test.statusByEnvironment !== undefined)) {
431
- // An older server ignores `environment` and returns unfiltered
432
- // statuses; printing them would look like a filtered answer.
433
- throw ApiError.fromEnvelope({
434
- error: {
435
- code: 'UNSUPPORTED',
436
- message: 'This server does not support `test list --env` yet.',
437
- nextAction: 'Run the command without --env, or retry after the server is upgraded.',
438
- requestId: 'local',
439
- details: {},
440
- },
441
- });
442
- }
413
+ assertEnvironmentStatusesPresent(page.items, {
414
+ message: 'This server does not support `test list --env` yet.',
415
+ nextAction: 'Run the command without --env, or retry after the server is upgraded.',
416
+ });
443
417
  }
444
418
  out.print(page, data => renderTestListText(data, {
445
419
  columns: opts.columns,
@@ -1584,9 +1558,11 @@ export async function runDeleteBatch(opts, deps = {}) {
1584
1558
  throw localValidationError('status', '--status only applies with --all (it filters which project tests get deleted). ' +
1585
1559
  'Remove --status, or add --all --project <id>.');
1586
1560
  }
1587
- // Validate --status filter.
1561
+ // Validate --status filter. An empty value is refused: read as "no filter",
1562
+ // `--status ''` would delete every test in the project.
1588
1563
  if (opts.statusFilter !== undefined) {
1589
- validateStatusFilter(opts.statusFilter);
1564
+ assertStatusSelectorNotEmpty(opts.statusFilter, RUN_STATUS_VALUES);
1565
+ validateListStatusFilter(opts.statusFilter);
1590
1566
  }
1591
1567
  const client = makeClient(opts, deps);
1592
1568
  let testIds = opts.testIds;
@@ -1607,8 +1583,8 @@ export async function runDeleteBatch(opts, deps = {}) {
1607
1583
  }), {});
1608
1584
  let allTests = allPage.items;
1609
1585
  // --status filter.
1610
- if (opts.statusFilter !== undefined && opts.statusFilter !== '') {
1611
- const allowed = new Set(opts.statusFilter
1586
+ if (opts.statusFilter !== undefined) {
1587
+ const allowed = new Set(expandNotRun(opts.statusFilter)
1612
1588
  .split(',')
1613
1589
  .map(s => s.trim())
1614
1590
  .filter(s => s.length > 0));
@@ -1769,10 +1745,8 @@ export const PLAN_TEMPLATE_TEXT = JSON.stringify(PLAN_TEMPLATE_WITH_SCHEMA, null
1769
1745
  /** `test create --help` after-text. Wraps `PLAN_TEMPLATE_TEXT` unmodified. */
1770
1746
  const PLAN_TEMPLATE_HELP_TEXT = '\nPlan file format (--plan-from <file>) — minimal valid example:\n\n' +
1771
1747
  `${PLAN_TEMPLATE_TEXT}\n\n` +
1772
- 'Print this exact skeleton: testsprite test create --plan-template\n' +
1773
- 'Validate offline (no network): testsprite test create --plan-from <file> --dry-run\n' +
1774
- 'Multiple tests: test create-batch --plans <file.jsonl> | --plan-from-dir <dir>\n' +
1775
- 'Full field reference: DOCUMENTATION.md -> "Plan file format"\n';
1748
+ 'Validate offline: testsprite test create --plan-from <file> --dry-run\n' +
1749
+ 'Many tests: testsprite test create-batch --plans <file.jsonl>\n';
1776
1750
  /**
1777
1751
  * 200-step + 256 KB caps on a single plan body. The CLI
1778
1752
  * enforces both client-side as a pre-flight guard so an obvious
@@ -1793,10 +1767,119 @@ const MAX_BATCH_BODY_BYTES = 5 * 1024 * 1024;
1793
1767
  * than this, the CLI splits into chunks and aggregates the results.
1794
1768
  */
1795
1769
  const MAX_BATCH_RERUN_IDS = 50;
1770
+ /**
1771
+ * Maximum testIds per `POST /tests/batch/run` request. A larger selection is
1772
+ * sent as several sequential requests, one project at a time (the endpoint
1773
+ * refuses ids from different projects in one request).
1774
+ */
1775
+ const MAX_BATCH_RUN_IDS = 50;
1776
+ /**
1777
+ * Group `ids` by project in first-seen order and cut each group into windows
1778
+ * of `MAX_BATCH_RUN_IDS`. `chunk: false` keeps one request per project, for a
1779
+ * caller whose contract is a single request (`ci run`).
1780
+ */
1781
+ function planBatchRunUnits(ids, projectOf, chunk) {
1782
+ const byProject = new Map();
1783
+ for (const id of ids) {
1784
+ const project = projectOf(id);
1785
+ const group = byProject.get(project);
1786
+ if (group)
1787
+ group.push(id);
1788
+ else
1789
+ byProject.set(project, [id]);
1790
+ }
1791
+ const units = [];
1792
+ for (const [projectId, group] of byProject) {
1793
+ if (!chunk) {
1794
+ units.push({ projectId, testIds: group });
1795
+ continue;
1796
+ }
1797
+ for (let i = 0; i < group.length; i += MAX_BATCH_RUN_IDS) {
1798
+ units.push({ projectId, testIds: group.slice(i, i + MAX_BATCH_RUN_IDS) });
1799
+ }
1800
+ }
1801
+ return units;
1802
+ }
1803
+ /**
1804
+ * Append `suffix` to an idempotency key within 256 chars. A base that does not
1805
+ * fit is cut and tagged with a digest of the whole key, so two long keys that
1806
+ * differ only in their tail still get different request keys.
1807
+ */
1808
+ function suffixedIdempotencyKey(base, suffix) {
1809
+ const room = 256 - suffix.length;
1810
+ if (base.length <= room)
1811
+ return `${base}${suffix}`;
1812
+ const digest = createHash('sha256').update(base).digest('hex').slice(0, 16);
1813
+ return `${base.slice(0, room - digest.length - 1)}~${digest}${suffix}`;
1814
+ }
1815
+ /**
1816
+ * Fold the responses of a request sequence into the one response the rest of
1817
+ * the command reads. A single response is returned untouched.
1818
+ */
1819
+ function mergeBatchRunResponses(responses, suppressDashboardUrl) {
1820
+ const first = responses[0];
1821
+ if (responses.length === 1 && !suppressDashboardUrl)
1822
+ return first;
1823
+ const integrations = responses.flatMap(r => (r.integration ? [r.integration] : []));
1824
+ return {
1825
+ ...first,
1826
+ accepted: responses.flatMap(r => r.accepted),
1827
+ conflicts: responses.flatMap(r => r.conflicts),
1828
+ deferred: responses.flatMap(r => r.deferred),
1829
+ skippedFrontend: responses.flatMap(r => r.skippedFrontend),
1830
+ skippedIntegration: responses.flatMap(r => r.skippedIntegration),
1831
+ ...(integrations.length > 0
1832
+ ? {
1833
+ integration: {
1834
+ existing: integrations.reduce((n, i) => n + i.existing, 0),
1835
+ runsAfterWave: integrations.some(i => i.runsAfterWave),
1836
+ mayGenerate: integrations.some(i => i.mayGenerate),
1837
+ },
1838
+ }
1839
+ : {}),
1840
+ // A project-level link names one project (and one execution); once the
1841
+ // batch spans several requests or projects no single page is right.
1842
+ ...(suppressDashboardUrl || (responses.length > 1 && 'dashboardUrl' in first)
1843
+ ? { dashboardUrl: null }
1844
+ : {}),
1845
+ };
1846
+ }
1847
+ /**
1848
+ * Resolve the owning project of every id with an authoritative `GET /tests/<id>`
1849
+ * (a handful in flight at a time). An unknown id fails the whole call with its
1850
+ * own NOT_FOUND before anything is dispatched, so an id in a later chunk cannot
1851
+ * be discovered after an earlier chunk already ran.
1852
+ */
1853
+ async function resolveTestProjects(client, ids, known) {
1854
+ const resolved = new Map();
1855
+ const pending = [];
1856
+ for (const id of ids) {
1857
+ const projectId = known?.get(id)?.projectId;
1858
+ if (projectId)
1859
+ resolved.set(id, projectId);
1860
+ else
1861
+ pending.push(id);
1862
+ }
1863
+ let next = 0;
1864
+ const worker = async () => {
1865
+ for (;;) {
1866
+ const id = pending[next++];
1867
+ if (id === undefined)
1868
+ return;
1869
+ const test = await client.get(`/tests/${encodeURIComponent(id)}`);
1870
+ if (!test.projectId) {
1871
+ throw localValidationError('test-id', `could not determine the project of test ${id}`);
1872
+ }
1873
+ resolved.set(id, test.projectId);
1874
+ }
1875
+ };
1876
+ await Promise.all(Array.from({ length: Math.min(8, pending.length) }, worker));
1877
+ return resolved;
1878
+ }
1796
1879
  /**
1797
1880
  * Dedupe `RerunAdvisory[]` by `feature`+`message`. Used to aggregate
1798
1881
  * `advisories` across chunked batch-rerun dispatch requests (initial dispatch
1799
- * + D3 deferred-retry attempts) into a single list, and to collapse repeated
1882
+ * dispatch) into a single list, and to collapse repeated
1800
1883
  * per-attempt advisories in `test flaky` into a single summary line.
1801
1884
  */
1802
1885
  function dedupeRerunAdvisories(entries) {
@@ -1928,22 +2011,6 @@ function mergeBatchRerunClosureByProject(entries) {
1928
2011
  export const DEFAULT_BATCH_RUN_CONCURRENCY = 50;
1929
2012
  /** Hard upper bound for --max-concurrency. Values above this are rejected with exit 5 (VALIDATION_ERROR). */
1930
2013
  export const MAX_BATCH_CONCURRENCY = 100;
1931
- /**
1932
- * The server's DEFAULT in-flight run cap. Runs from every source count
1933
- * toward it (CLI, portal, schedules, CI), but only CLI run triggers are
1934
- * refused on it; a portal or schedule run over the cap is not. Exceeding it
1935
- * answers RATE_LIMITED with `details.reason: "inflight_cap"`, whose details
1936
- * carry the account's real `cap` and `current`.
1937
- *
1938
- * Quoted in help text only — the server owns the real number and rejects on
1939
- * its own value, so this is documentation, never a client-side gate.
1940
- *
1941
- * Distinct from `--max-concurrency`, whose meaning differs per command: on
1942
- * `create --run` it bounds in-flight triggers, and with `--wait` a slot is
1943
- * held until that run finishes, so lowering it there does bound how many runs
1944
- * are in flight. On `run --all` it bounds the `--wait` poll fan-out only.
1945
- */
1946
- export const SERVER_INFLIGHT_RUN_CAP = 50;
1947
2014
  /** Client-side run-trigger throttle: 50 triggers per 60-second rolling window per key (sits just under the server's 60/min/key cap). */
1948
2015
  export const BATCH_RUN_RATE_LIMIT = 50;
1949
2016
  /** Rolling window duration (ms) for the client-side trigger rate throttle. */
@@ -2005,15 +2072,6 @@ export function resolveRateLimitRetryMs(err) {
2005
2072
  const retryAfterSec = err.getDetail('retryAfterSeconds', (v) => typeof v === 'number' && v > 0);
2006
2073
  return Math.min((retryAfterSec ?? 60) * 1000, 120_000);
2007
2074
  }
2008
- /**
2009
- * D3: max automatic retry attempts for deferred tests under `--wait`.
2010
- * Each attempt is preceded by a Retry-After-aware sleep (server value if
2011
- * present, else 61s default), clamped to the remaining `--timeout` budget.
2012
- * Only active under `--wait`; the non-wait path is unchanged.
2013
- */
2014
- export const MAX_DEFERRED_RETRIES = 3;
2015
- /** D3: default deferred-retry sleep when no Retry-After is available (ms). */
2016
- export const DEFERRED_RETRY_DEFAULT_SLEEP_MS = 61_000;
2017
2075
  /**
2018
2076
  * Returns `true` when a `RATE_LIMITED` error is the **transient per-minute**
2019
2077
  * rate limit from `RunRateLimiterGuard` — the one worth retrying.
@@ -5412,13 +5470,10 @@ function parseStepTimeoutFlag(raw, flagName) {
5412
5470
  function warnIfOptOutIgnored(requested, echoed, stderrFn, label,
5413
5471
  /**
5414
5472
  * States already reported by an earlier dispatch in the same invocation.
5415
- * `test run --all` can dispatch more than once — the deferred-retry leg
5416
- * re-sends the opt-out, so it has to be checked too, or the tests a rate
5417
- * limit pushed into the retry would be the only ones running unwarned. Those
5418
- * are also the likeliest to land on a differently-configured instance during a
5419
- * rollout, which is why this dedupes on the OUTCOME rather than firing once:
5420
- * a retry whose echo disagrees with the first attempt's is new information and
5421
- * still warns.
5473
+ * `test run --all` dispatches one request per project and window of ids, and
5474
+ * during a rollout they can land on differently-configured instances, which is
5475
+ * why this dedupes on the OUTCOME rather than firing once: a request whose
5476
+ * echo disagrees with an earlier one is new information and still warns.
5422
5477
  */
5423
5478
  reported) {
5424
5479
  if (requested !== false)
@@ -5588,6 +5643,7 @@ export async function runTestRun(opts, deps = {}) {
5588
5643
  // handle, the same reason `dashboardUrl` is suppressed under
5589
5644
  // --dry-run rather than pointing at the canned sample id.
5590
5645
  ...(isTunnelRun ? { tunnelClientId: '<minted at run time>' } : {}),
5646
+ ...(opts.skipDependencies ? { skipDependencies: true } : {}),
5591
5647
  ...(environment !== undefined ? { environment } : {}),
5592
5648
  },
5593
5649
  idempotencyKey,
@@ -5754,6 +5810,8 @@ export async function runTestRun(opts, deps = {}) {
5754
5810
  // Present ONLY as `false`. Omission is how the protected
5755
5811
  // default is requested — see `TriggerRunBody.autoHeal`.
5756
5812
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
5813
+ // Present only when asked for; an older backend strips it.
5814
+ ...(opts.skipDependencies ? { skipDependencies: true } : {}),
5757
5815
  // The client ID only. The secret stays in this process and never
5758
5816
  // reaches a request body, an idempotency row, or an audit line.
5759
5817
  ...(tunnelSession ? { tunnelClientId: tunnelSession.clientId } : {}),
@@ -5915,6 +5973,15 @@ export async function runTestRun(opts, deps = {}) {
5915
5973
  isSameLoopbackPort(triggerResponse.targetUrl, resolvedTarget?.port ?? opts.localPort))) {
5916
5974
  emitTargetUrlMismatchAdvisory(stderrFn, effectiveTargetUrl, triggerResponse.targetUrl);
5917
5975
  }
5976
+ // Like the target URL above, an unconfirmed field is reported, not fatal: an
5977
+ // older backend strips it and the run goes ahead with the test cases it depends on,
5978
+ // as a Portal run does.
5979
+ // A run joined from a 409 was not started by this request, so it has no echo.
5980
+ if (opts.skipDependencies &&
5981
+ !resumedFromConflict &&
5982
+ triggerResponse.skipDependencies !== true) {
5983
+ stderrFn('[advisory] This backend did not confirm --skip-dependencies, so the run may also include the test cases this one depends on, as a Portal run does.');
5984
+ }
5918
5985
  if (!opts.wait) {
5919
5986
  printRunOrChain(out, triggerResponse, opts.createContext, data => renderTriggerRunText(data));
5920
5987
  if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
@@ -6706,17 +6773,18 @@ export function createTestCancelCommand(deps) {
6706
6773
  const cancel = new Command('cancel');
6707
6774
  cancel
6708
6775
  .argument('<run-id...>', 'one or more run ids to cancel')
6776
+ .summary('Cancel queued/running runs (refunds an unfinished FE V3 run)')
6709
6777
  .description('Cancel one or more queued/running runs.\n' +
6710
- '\nCtrl-C during --wait only detaches — it does NOT cancel the server-side\n' +
6711
- 'run. This is the real stop button. A frontend V3 run cancelled before a\n' +
6712
- 'terminal state has its original charge returned; an uncharged run says so.\n' +
6713
- 'Backend and V2 runs keep their existing billing behavior; an in-flight Lambda\n' +
6714
- 'finishes on its own and its result is discarded once cancelled.\n' +
6778
+ '\nCtrl-C during an ordinary --wait only detaches; it does NOT cancel the run (owned-tunnel\n' +
6779
+ 'runs are cancelled on interrupt, see `test run --help`). This is the real stop button.\n' +
6780
+ 'A frontend V3 run cancelled before a terminal state has its charge returned; backend and\n' +
6781
+ 'V2 runs keep their billing, and an in-flight Lambda finishes with its result discarded.\n' +
6715
6782
  '\nExit codes:\n' +
6716
6783
  ' 0 cancelled (fresh or already-cancelled — naturally idempotent)\n' +
6717
- ' 4 run id not found (single id), or ANY id not found (multi-id — outranks conflict)\n' +
6718
- ' 6 run already terminal (passed/failed/blocked) — single id: 409; multi-id: any conflict\n' +
6719
- '\nMulti-id output is a summary: {cancelled, alreadyCancelled, conflicts, notFound}.')
6784
+ ' 1 multi-id: a cancel request failed (auth/transport/server error; see summary.errors)\n' +
6785
+ ' 4 run id not found (single id), or ANY id not found (multi-id; outranks conflict)\n' +
6786
+ ' 6 run already terminal (passed/failed/blocked); multi-id: any conflict\n' +
6787
+ '\nMulti-id output is a summary: {cancelled, alreadyCancelled, conflicts, notFound, errors}.')
6720
6788
  .addHelpText('after', GLOBAL_OPTS_HINT)
6721
6789
  .action(async (runIds, _cmdOpts, command) => {
6722
6790
  await runTestCancel({
@@ -6945,6 +7013,7 @@ export async function writeBatchJUnitReportIfRequested(opts, results, nameByTest
6945
7013
  const enriched = results.map(r => ({
6946
7014
  ...r,
6947
7015
  name: nameByTestId?.get(r.testId) ?? (r.testTitle?.trim() ? r.testTitle : undefined) ?? r.name,
7016
+ classname: r.classname ?? opts.projectIdByTestId?.get(r.testId),
6948
7017
  durationSeconds: r.durationSeconds ?? durationSecondsBetween(r.startedAt, r.finishedAt, r.createdAt),
6949
7018
  }));
6950
7019
  const xml = buildJUnitReport({
@@ -6954,11 +7023,20 @@ export async function writeBatchJUnitReportIfRequested(opts, results, nameByTest
6954
7023
  });
6955
7024
  await writeJUnitReportFile(opts.reportFile, xml);
6956
7025
  }
7026
+ /** `buildTestNameMap` over several projects, merged. */
7027
+ async function buildTestNameMapForProjects(client, projectIds) {
7028
+ const merged = new Map();
7029
+ for (const projectId of projectIds) {
7030
+ for (const [id, name] of await buildTestNameMap(client, projectId))
7031
+ merged.set(id, name);
7032
+ }
7033
+ return merged;
7034
+ }
6957
7035
  /**
6958
7036
  * Cancel runs the caller can no longer use, without letting the cleanup itself
6959
7037
  * become the failure. Used when a batch dispatched successfully but the CLI
6960
- * then discovered the dispatch was wrong to keep (the backend did not confirm
6961
- * `--target-url`, so accepted runs may use a different target).
7038
+ * then discovered the dispatch was wrong to keep (the backend did not confirm a
7039
+ * field it was sent, such as `--target-url` or `--skip-dependencies`).
6962
7040
  * Leaving them would bill the user for a verdict nobody asked for.
6963
7041
  *
6964
7042
  * Every error is swallowed to a warning on purpose: the caller is already about
@@ -6968,7 +7046,7 @@ export async function writeBatchJUnitReportIfRequested(opts, results, nameByTest
6968
7046
  async function cancelRunsBestEffort(client, runIds, stderrFn, label) {
6969
7047
  if (runIds.length === 0)
6970
7048
  return;
6971
- stderrFn(`[${label}] cancelling ${runIds.length} run${runIds.length !== 1 ? 's' : ''} dispatched against the wrong target…`);
7049
+ stderrFn(`[${label}] cancelling ${runIds.length} run${runIds.length !== 1 ? 's' : ''} the backend did not confirm…`);
6972
7050
  for (const runId of runIds) {
6973
7051
  try {
6974
7052
  const response = await client.cancelRun(runId);
@@ -7215,11 +7293,19 @@ async function finishZeroDispatchBatch(params) {
7215
7293
  */
7216
7294
  export async function runTestRunAll(opts, deps = {}) {
7217
7295
  assertIdempotencyKey(opts.idempotencyKey);
7296
+ validateStatusSelector(opts.statusFilter);
7218
7297
  const environment = normalizeEnvironmentName(opts.environment);
7219
- const projectId = resolveProjectId(opts.projectId, deps);
7220
- requireProjectId(projectId);
7298
+ // Explicit ids carry their own projects, read once the client exists; an
7299
+ // `--all` run needs the one project up front.
7300
+ const explicitIds = (opts.testIds?.length ?? 0) > 0;
7301
+ let projectId = '<resolved per test>';
7302
+ if (!explicitIds) {
7303
+ const resolvedProjectId = resolveProjectId(opts.projectId, deps);
7304
+ requireProjectId(resolvedProjectId);
7305
+ projectId = resolvedProjectId;
7306
+ }
7221
7307
  // Carry the resolved id into reports, including when it came from the env.
7222
- opts = { ...opts, projectId };
7308
+ opts = { ...opts, projectId: explicitIds ? undefined : projectId };
7223
7309
  if (!Number.isInteger(opts.maxConcurrency) ||
7224
7310
  opts.maxConcurrency < 1 ||
7225
7311
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
@@ -7234,7 +7320,7 @@ export async function runTestRunAll(opts, deps = {}) {
7234
7320
  });
7235
7321
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
7236
7322
  const out = makeOutput(opts.output, deps);
7237
- if (opts.dryRun && opts.targetUrl === undefined && !opts.noWait) {
7323
+ if (opts.dryRun && opts.targetUrl === undefined && !opts.noWait && !explicitIds) {
7238
7324
  let target;
7239
7325
  try {
7240
7326
  target = await resolveEnvironmentRunTarget({
@@ -7277,9 +7363,18 @@ export async function runTestRunAll(opts, deps = {}) {
7277
7363
  path: '/api/cli/v1/tests/batch/run',
7278
7364
  body: {
7279
7365
  projectId,
7280
- testIds: opts.nameFilter ? ['<filtered by --filter>'] : undefined,
7366
+ testIds: explicitIds
7367
+ ? [...new Set(opts.testIds)]
7368
+ : opts.nameFilter || opts.statusFilter !== undefined
7369
+ ? [
7370
+ opts.statusFilter !== undefined
7371
+ ? '<filtered by --filter/--status>'
7372
+ : '<filtered by --filter>',
7373
+ ]
7374
+ : undefined,
7281
7375
  source: 'cli',
7282
7376
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
7377
+ ...(opts.skipDependencies ? { skipDependencies: true } : {}),
7283
7378
  ...(environment !== undefined ? { environment } : {}),
7284
7379
  ...(opts.targetUrl !== undefined ? { targetUrl: opts.targetUrl } : {}),
7285
7380
  },
@@ -7289,7 +7384,9 @@ export async function runTestRunAll(opts, deps = {}) {
7289
7384
  if (!opts.ci && opts.report === 'junit' && opts.reportFile !== undefined) {
7290
7385
  await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(opts.projectId, opts.reportSuiteName));
7291
7386
  }
7292
- out.print(opts.ci || opts.targetUrl !== undefined ? envelope : (batchRunSample ?? envelope));
7387
+ out.print(opts.ci || opts.targetUrl !== undefined || explicitIds || opts.skipDependencies
7388
+ ? envelope
7389
+ : (batchRunSample ?? envelope));
7293
7390
  return undefined;
7294
7391
  }
7295
7392
  // Probe once before dispatch. A preview still warming up can use
@@ -7302,7 +7399,7 @@ export async function runTestRunAll(opts, deps = {}) {
7302
7399
  // `--env` gate — see `runTestRun`. Before the test-set enumeration so a
7303
7400
  // gated batch makes no billable call at all.
7304
7401
  const environmentCache = deps.environmentCache ?? new Map();
7305
- const automaticTarget = opts.environmentResolutionComplete
7402
+ const automaticTarget = opts.environmentResolutionComplete || explicitIds
7306
7403
  ? undefined
7307
7404
  : await resolveEnvironmentRunTarget({
7308
7405
  client,
@@ -7334,8 +7431,27 @@ export async function runTestRunAll(opts, deps = {}) {
7334
7431
  }
7335
7432
  assertNoTunnelOptions(opts);
7336
7433
  assertFreshRunWaitOptions(opts, true);
7337
- // Portal deep links for batch output: every test in the batch belongs to
7338
- // opts.projectId, so per-item dashboardUrl needs no extra wire data. The
7434
+ // Explicit ids: read each id's project before anything is dispatched. The
7435
+ // batch endpoint refuses a request whose ids span projects, and refuses it
7436
+ // whole for an unknown id, so grouping and existence have to be settled here.
7437
+ const projectOf = new Map();
7438
+ const explicitTestIds = explicitIds ? [...new Set(opts.testIds)] : [];
7439
+ if (explicitIds) {
7440
+ for (const [id, project] of await resolveTestProjects(client, explicitTestIds, opts.knownTests)) {
7441
+ projectOf.set(id, project);
7442
+ }
7443
+ projectId = projectOf.get(explicitTestIds[0]);
7444
+ const several = new Set(projectOf.values()).size > 1;
7445
+ opts = {
7446
+ ...opts,
7447
+ projectId: several ? undefined : projectId,
7448
+ projectIdByTestId: projectOf,
7449
+ };
7450
+ }
7451
+ const multiProject = new Set(projectOf.values()).size > 1;
7452
+ const projectOfTest = (testId) => projectOf.get(testId) ?? projectId;
7453
+ // Portal deep links for batch output: a test belongs to its own project
7454
+ // (opts.projectId for `--all`), so per-item dashboardUrl needs no extra wire data. The
7339
7455
  // project-level URL closes out text-mode output ("watch the wave here").
7340
7456
  // Both stay undefined for unknown API hosts (resolvePortalBase contract).
7341
7457
  const batchApiUrl = resolveApiUrl(opts, deps);
@@ -7357,18 +7473,19 @@ export async function runTestRunAll(opts, deps = {}) {
7357
7473
  // shipped in every environment — it only serves runs from an older backend.
7358
7474
  if (typeof item.dashboardUrl === 'string')
7359
7475
  return item;
7360
- const dashboardUrl = resolvePortalUrl(batchApiUrl, projectId, item.testId);
7476
+ const dashboardUrl = resolvePortalUrl(batchApiUrl, projectOfTest(item.testId), item.testId);
7361
7477
  return dashboardUrl !== undefined ? { ...item, dashboardUrl } : item;
7362
7478
  };
7363
7479
  const idempotencyKey = opts.idempotencyKey ?? `cli-batch-run-fresh-${randomUUID()}`;
7364
7480
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
7365
7481
  stderrFn(`idempotency-key: ${idempotencyKey}`);
7366
7482
  }
7367
- // Every dispatch leg (first and deferred retries) sends the same fields.
7483
+ // Every dispatch request sends the same fields.
7368
7484
  // `autoHeal` is present ONLY as `false`; omission requests the protected default.
7369
7485
  const dispatchFields = {
7370
7486
  source: 'cli',
7371
7487
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
7488
+ ...(opts.skipDependencies ? { skipDependencies: true } : {}),
7372
7489
  ...(environment !== undefined ? { environment } : {}),
7373
7490
  ...(opts.targetUrl !== undefined ? { targetUrl: opts.targetUrl } : {}),
7374
7491
  ...(opts.admission !== undefined ? { admission: opts.admission } : {}),
@@ -7391,6 +7508,14 @@ export async function runTestRunAll(opts, deps = {}) {
7391
7508
  nextAction: 'Use a backend that supports batch target URL overrides, or retry without --target-url.',
7392
7509
  });
7393
7510
  }
7511
+ if (opts.skipDependencies && response.skipDependencies !== true) {
7512
+ out.push({
7513
+ field: 'skipDependencies',
7514
+ reason: 'skip-dependencies-not-honored',
7515
+ message: 'This backend did not confirm --skip-dependencies, so the accepted runs may also include the test cases they depend on.',
7516
+ nextAction: 'Use a backend that supports --skip-dependencies on batch runs, or retry without --skip-dependencies.',
7517
+ });
7518
+ }
7394
7519
  if (opts.admission !== undefined && response.admission !== opts.admission) {
7395
7520
  out.push({
7396
7521
  field: 'admission',
@@ -7409,7 +7534,9 @@ export async function runTestRunAll(opts, deps = {}) {
7409
7534
  }
7410
7535
  return out;
7411
7536
  }
7412
- async function assertBatchTargetEcho(response, previouslyAccepted) {
7537
+ async function assertBatchTargetEcho(response, previouslyAccepted,
7538
+ /** A later request: the caller reports or awaits the stopped dispatch, so no artifacts are written here. */
7539
+ stoppedDispatch = false) {
7413
7540
  const unhonored = unhonoredDispatchFields(response);
7414
7541
  if (unhonored.length === 0)
7415
7542
  return;
@@ -7424,7 +7551,7 @@ export async function runTestRunAll(opts, deps = {}) {
7424
7551
  const unconfirmedIds = new Set(unconfirmed.map(item => item.runId));
7425
7552
  const confirmed = dedupeBatchRunFreshAccepted([...previouslyAccepted]).deduped.filter(item => !unconfirmedIds.has(item.runId));
7426
7553
  await cancelRunsBestEffort(client, unconfirmed.map(item => item.runId), stderrFn, 'run');
7427
- if (opts.wait) {
7554
+ if (opts.wait && !stoppedDispatch) {
7428
7555
  const notAwaited = `Not awaited: the batch stopped because a later dispatch did not confirm ${field}. ` +
7429
7556
  'This run was confirmed and is still running; read it with testsprite test wait <run-id>.';
7430
7557
  const summary = summarizeAcceptedPayload(JSON.stringify({
@@ -7478,22 +7605,23 @@ export async function runTestRunAll(opts, deps = {}) {
7478
7605
  });
7479
7606
  }
7480
7607
  // Resolve testIds: fetch all tests in the project, apply --filter.
7481
- let testIds;
7482
- if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
7483
- // We need to resolve the full test set to apply the name filter.
7484
- const allPage = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
7485
- query: { projectId, pageSize, cursor },
7486
- }), {});
7487
- const needle = opts.nameFilter.toLowerCase();
7488
- const filtered = allPage.items.filter(t => t.name.toLowerCase().includes(needle));
7489
- const before = allPage.items.length;
7490
- const skipped = before - filtered.length;
7491
- if (skipped > 0) {
7492
- stderrFn(`--filter: skipped ${skipped} test${skipped !== 1 ? 's' : ''} whose name does not contain "${opts.nameFilter}".`);
7493
- }
7608
+ let testIds = explicitIds ? explicitTestIds : undefined;
7609
+ const nameFiltered = opts.nameFilter !== undefined && opts.nameFilter !== '';
7610
+ const statusFiltered = opts.statusFilter !== undefined;
7611
+ if (!explicitIds && (nameFiltered || statusFiltered)) {
7612
+ // The name and status filters are applied here, so the full test set is read.
7613
+ const filtered = await resolveAllProjectTests({
7614
+ client,
7615
+ projectId,
7616
+ statusFilter: opts.statusFilter,
7617
+ nameFilter: opts.nameFilter,
7618
+ stderr: stderrFn,
7619
+ latestStatus: true,
7620
+ });
7494
7621
  testIds = filtered.map(t => t.id);
7495
7622
  if (testIds.length === 0) {
7496
- stderrFn(`No tests found in project ${projectId} matching --filter "${opts.nameFilter}" — nothing to run.`);
7623
+ const selectors = describeRunSelectors(opts);
7624
+ stderrFn(`No tests found in project ${projectId} matching ${selectors} — nothing to run.`);
7497
7625
  const emptyResponse = {
7498
7626
  accepted: [],
7499
7627
  conflicts: [],
@@ -7510,7 +7638,7 @@ export async function runTestRunAll(opts, deps = {}) {
7510
7638
  // and fail unless --allow-empty, so a renamed test can't turn a filtered
7511
7639
  // gate permanently green. Returns here only under --allow-empty.
7512
7640
  await finishZeroDispatchBatch({
7513
- reason: `--filter "${opts.nameFilter}" matched no tests in project ${projectId}`,
7641
+ reason: `${selectors} matched no tests in project ${projectId}`,
7514
7642
  skipped: [],
7515
7643
  allowEmpty: opts.allowEmpty === true,
7516
7644
  opts,
@@ -7523,27 +7651,174 @@ export async function runTestRunAll(opts, deps = {}) {
7523
7651
  }
7524
7652
  // When no --filter, omit testIds → server runs ALL tests in the project
7525
7653
  // (BE tests on the legacy V2 wave engine; FE + BE on the V3 unified engine).
7526
- let batchResp;
7527
- try {
7528
- batchResp = await client.triggerBatchRunFresh({
7529
- projectId,
7530
- ...(testIds !== undefined ? { testIds } : {}),
7531
- ...dispatchFields,
7532
- }, { idempotencyKey });
7654
+ // One request per project and window of MAX_BATCH_RUN_IDS ids, sent one at a
7655
+ // time. `--all` without a filter names no ids and stays a single request, and
7656
+ // `ci run` keeps its one-request contract whatever the filter matched.
7657
+ const dispatchUnits = testIds !== undefined ? planBatchRunUnits(testIds, projectOfTest, !opts.ci) : [{ projectId }];
7658
+ // Shared across every dispatch this invocation makes — see the `reported` param.
7659
+ const optOutReported = new Set();
7660
+ /**
7661
+ * Report a dispatch that stopped part-way and is not awaited: no `--wait`, a
7662
+ * first request that failed, or an interrupt (under `--wait` a later failure
7663
+ * is awaited instead — see `stoppedError`). The runs earlier requests
7664
+ * accepted keep executing (and billing) and nothing polls them from here, so
7665
+ * their ids and the ids never sent are what the caller needs; the error keeps
7666
+ * its own code and so its own exit code.
7667
+ */
7668
+ async function reportStoppedDispatch(err, done, undispatched) {
7669
+ const { deduped: acceptedDone, dropped: droppedDone } = dedupeBatchRunFreshAccepted(done.flatMap(r => r.accepted));
7670
+ // A producer two requests both accepted is polled once elsewhere; here
7671
+ // nothing is polled, but the extra run is still executing and must be named.
7672
+ warnDroppedDuplicateRuns(acceptedDone, droppedDone, stderrFn);
7673
+ const keptRunIds = new Map(acceptedDone.map(r => [r.testId, r.runId]));
7674
+ const extraRunIds = droppedDone
7675
+ .filter(r => r.runId !== keptRunIds.get(r.testId))
7676
+ .map(r => r.runId);
7677
+ const waitRunIds = [...acceptedDone.map(r => r.runId), ...new Set(extraRunIds)];
7678
+ const conflictsDone = done.flatMap(r => r.conflicts);
7679
+ const deferredDone = done.flatMap(r => r.deferred);
7680
+ const skippedFrontendDone = done.flatMap(r => r.skippedFrontend);
7681
+ const skippedIntegrationDone = done.flatMap(r => r.skippedIntegration);
7682
+ const notRunTestIds = undispatched.flatMap(u => u.testIds ?? []);
7683
+ const reason = err instanceof Error ? err.message : String(err);
7684
+ const partial = {
7685
+ accepted: acceptedDone.map(withBatchDashboardUrl),
7686
+ conflicts: conflictsDone,
7687
+ deferred: deferredDone,
7688
+ ...(skippedFrontendDone.length > 0 ? { skippedFrontend: skippedFrontendDone } : {}),
7689
+ ...(skippedIntegrationDone.length > 0 ? { skippedIntegration: skippedIntegrationDone } : {}),
7690
+ notRunTestIds,
7691
+ };
7692
+ if (opts.output === 'json' || acceptedDone.length > 0) {
7693
+ out.print(partial, () => acceptedDone.map(r => `${r.runId} accepted`).join('\n'));
7694
+ }
7695
+ const waitHint = waitRunIds.length > 0
7696
+ ? `${waitRunIds.length} accepted run${waitRunIds.length !== 1 ? 's are' : ' is'} still executing and not awaited: testsprite test wait ${waitRunIds.join(' ')}`
7697
+ : undefined;
7698
+ const notRunHint = `${notRunTestIds.length} test${notRunTestIds.length !== 1 ? 's were' : ' was'} not dispatched: ${notRunTestIds.join(' ')}`;
7699
+ stderrFn(`[run] Dispatch stopped (${reason}). ${[waitHint, notRunHint].join('. ')}.`);
7700
+ if (opts.wait) {
7701
+ // Best effort: the artifacts must never mask the error that stopped the dispatch.
7702
+ try {
7703
+ const notAwaited = 'Not awaited: the dispatch stopped before every test was sent. This run was accepted and is still running; read it with testsprite test wait <run-id>.';
7704
+ const summary = summarizeAcceptedPayload(JSON.stringify({
7705
+ accepted: acceptedDone.map(item => ({
7706
+ ...item,
7707
+ status: 'error',
7708
+ error: { message: notAwaited },
7709
+ })),
7710
+ deferred: deferredDone,
7711
+ conflicts: conflictsDone,
7712
+ skippedFrontend: skippedFrontendDone,
7713
+ skippedIntegration: skippedIntegrationDone,
7714
+ skipped: notRunTestIds.map(testId => ({
7715
+ testId,
7716
+ reason: `not dispatched: ${reason}`,
7717
+ })),
7718
+ }), { foldSkippedBuckets: true });
7719
+ emitCiArtifacts(summary, opts, {
7720
+ env: deps.env ?? process.env,
7721
+ stdout: deps.stdout ?? (line => process.stdout.write(`${line}\n`)),
7722
+ stderr: stderrFn,
7723
+ }, 'run');
7724
+ await writeBatchJUnitReportIfRequested(opts, summary.runs.map(row => ({
7725
+ testId: row.testId,
7726
+ runId: row.runId,
7727
+ status: isNonDispatchedStatus(row.status) ? 'skipped' : 'error',
7728
+ ...(isNonDispatchedStatus(row.status)
7729
+ ? { skipReason: row.error }
7730
+ : { error: { code: 'UNSUPPORTED', message: row.error ?? reason, exitCode: 7 } }),
7731
+ })));
7732
+ }
7733
+ catch (artifactErr) {
7734
+ if (artifactErr instanceof InterruptError)
7735
+ throw artifactErr;
7736
+ stderrFn(`[run] could not write the CI artifacts: ${artifactErr instanceof Error ? artifactErr.message : String(artifactErr)}; continuing`);
7737
+ }
7738
+ }
7739
+ return withDispatchHints(err, [waitHint, notRunHint]);
7533
7740
  }
7534
- catch (err) {
7535
- // A whole-batch refusal under `ci run` is a funnel outcome — every API
7536
- // refusal gets one (validation by the server's `details.reason`, 402/403
7537
- // as billing, the rest as other).
7538
- if (opts.ci && err instanceof ApiError) {
7539
- recordTelemetryExtras({ ciRunOutcome: ciRefusalOutcome(err) });
7741
+ /** The failed request's own error (so its exit code stands), with what the caller needs to do next prepended. */
7742
+ function withDispatchHints(err, hints) {
7743
+ if (!(err instanceof ApiError))
7744
+ return err;
7745
+ return new ApiError({
7746
+ code: err.code,
7747
+ message: err.message,
7748
+ nextAction: [...hints, err.nextAction].filter(Boolean).join('. '),
7749
+ requestId: err.requestId,
7750
+ details: err.details,
7751
+ }, err.httpStatus, err.retryAfterMs, err.apiUrl, err.serverNextAction);
7752
+ }
7753
+ /**
7754
+ * Under --wait, a request that fails once earlier requests were accepted
7755
+ * does not abandon those runs: nothing further is sent, they are polled to
7756
+ * their verdicts, and this error — the failed request's own — is what the
7757
+ * invocation exits with, ahead of any verdict-derived code.
7758
+ */
7759
+ let stoppedError;
7760
+ /** Ids a stopped dispatch never sent (the requests after the failed one). */
7761
+ let notRunTestIds = [];
7762
+ const dispatchResponses = [];
7763
+ for (const [unitIndex, unit] of dispatchUnits.entries()) {
7764
+ let unitResp;
7765
+ try {
7766
+ unitResp = await client.triggerBatchRunFresh({
7767
+ projectId: unit.projectId,
7768
+ ...(unit.testIds !== undefined ? { testIds: unit.testIds } : {}),
7769
+ ...dispatchFields,
7770
+ }, {
7771
+ idempotencyKey: dispatchUnits.length === 1
7772
+ ? idempotencyKey
7773
+ : suffixedIdempotencyKey(idempotencyKey, `:chunk${unitIndex}`),
7774
+ });
7775
+ }
7776
+ catch (err) {
7777
+ // A whole-batch refusal under `ci run` is a funnel outcome — every API
7778
+ // refusal gets one (validation by the server's `details.reason`, 402/403
7779
+ // as billing, the rest as other).
7780
+ if (opts.ci && err instanceof ApiError) {
7781
+ recordTelemetryExtras({ ciRunOutcome: ciRefusalOutcome(err) });
7782
+ }
7783
+ if (opts.wait && dispatchResponses.length > 0 && !(err instanceof InterruptError)) {
7784
+ stoppedError = err;
7785
+ notRunTestIds = dispatchUnits.slice(unitIndex).flatMap(u => u.testIds ?? []);
7786
+ break;
7787
+ }
7788
+ if (dispatchUnits.length > 1) {
7789
+ throw await reportStoppedDispatch(err, dispatchResponses, dispatchUnits.slice(unitIndex));
7790
+ }
7791
+ throw err;
7792
+ }
7793
+ warnIfOptOutIgnored(opts.autoHeal, unitResp.autoHeal, stderrFn, 'these runs', optOutReported);
7794
+ try {
7795
+ await assertBatchTargetEcho(unitResp, dispatchResponses.flatMap(r => r.accepted), unitIndex > 0);
7796
+ }
7797
+ catch (err) {
7798
+ // The unconfirmed chunk is already cancelled; earlier chunks' runs keep
7799
+ // executing and need reporting like any other later-chunk failure.
7800
+ if (unitIndex > 0) {
7801
+ if (opts.wait && !(err instanceof InterruptError)) {
7802
+ stoppedError = err;
7803
+ notRunTestIds = dispatchUnits.slice(unitIndex).flatMap(u => u.testIds ?? []);
7804
+ break;
7805
+ }
7806
+ throw await reportStoppedDispatch(err, dispatchResponses, dispatchUnits.slice(unitIndex));
7807
+ }
7808
+ throw err;
7809
+ }
7810
+ dispatchResponses.push(unitResp);
7811
+ }
7812
+ let batchResp = mergeBatchRunResponses(dispatchResponses, multiProject);
7813
+ if (dispatchResponses.length > 1) {
7814
+ // Producers the server adds per request can land in two requests; the
7815
+ // repeated test is polled once and the extra run is named, as on a retry.
7816
+ const { deduped, dropped } = dedupeBatchRunFreshAccepted(batchResp.accepted);
7817
+ if (dropped.length > 0) {
7818
+ warnDroppedDuplicateRuns(deduped, dropped, stderrFn);
7819
+ batchResp = { ...batchResp, accepted: deduped };
7540
7820
  }
7541
- throw err;
7542
7821
  }
7543
- // Shared across every dispatch this invocation makes — see the `reported` param.
7544
- const optOutReported = new Set();
7545
- warnIfOptOutIgnored(opts.autoHeal, batchResp.autoHeal, stderrFn, 'these runs', optOutReported);
7546
- await assertBatchTargetEcho(batchResp, []);
7547
7822
  if (opts.ci && batchResp.accepted.length > 0) {
7548
7823
  // Recorded as soon as the dispatch is confirmed, not after the wait: a job
7549
7824
  // cancelled mid-wait (a re-push under shape B's concurrency group, a manual
@@ -7564,14 +7839,11 @@ export async function runTestRunAll(opts, deps = {}) {
7564
7839
  // template apply — for a V3 reader that shape bounced onto a route that does
7565
7840
  // not exist, which is why the server took it over.
7566
7841
  const { dashboardUrl: projectDashboardUrl } = resolveDashboardUrl(batchResp, legacyProjectDashboardUrl);
7567
- // Mutable: D3 deferred-retry loop may append to `accepted`, drain `deferred`,
7568
- // and accumulate additional `conflicts` discovered during retries.
7569
- let accepted = batchResp.accepted.slice();
7570
- let deferred = batchResp.deferred.slice();
7842
+ const accepted = batchResp.accepted.slice();
7843
+ const deferred = batchResp.deferred.slice();
7571
7844
  let conflicts = batchResp.conflicts.slice();
7572
7845
  const skippedFrontend = batchResp.skippedFrontend.slice();
7573
7846
  const skippedIntegration = batchResp.skippedIntegration.slice();
7574
- let retryError;
7575
7847
  // Print advisory for skipped FE tests.
7576
7848
  if (skippedFrontend.length > 0) {
7577
7849
  stderrFn(`[advisory] ${skippedFrontend.length} frontend test${skippedFrontend.length !== 1 ? 's' : ''} skipped — the batch run endpoint uses the BE-only wave engine. ` +
@@ -7666,7 +7938,7 @@ export async function runTestRunAll(opts, deps = {}) {
7666
7938
  // replacing it — accepted.length is 0 in this whole branch, so the
7667
7939
  // advisory printed earlier (guarded on accepted.length > 0) never
7668
7940
  // showed the link, and this is the only place it can.
7669
- nextAction: `Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>${billingConflictLink(conflicts, batchApiUrl)}`,
7941
+ nextAction: `${conflictNextAction(conflicts, () => 'Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>')}${billingConflictLink(conflicts, batchApiUrl)}`,
7670
7942
  requestId: 'local',
7671
7943
  details: { conflicts: conflicts.map(c => c.testId) },
7672
7944
  },
@@ -7684,7 +7956,9 @@ export async function runTestRunAll(opts, deps = {}) {
7684
7956
  stderrFn,
7685
7957
  emptyProject: skippedFrontend.length === 0 &&
7686
7958
  skippedIntegration.length === 0 &&
7687
- opts.nameFilter === undefined,
7959
+ opts.nameFilter === undefined &&
7960
+ opts.statusFilter === undefined &&
7961
+ !explicitIds,
7688
7962
  projectId,
7689
7963
  });
7690
7964
  }
@@ -7692,112 +7966,21 @@ export async function runTestRunAll(opts, deps = {}) {
7692
7966
  // JSON merge reflect what was actually dispatched, not the stale initial resp.
7693
7967
  return { ...batchResp, accepted, deferred, conflicts };
7694
7968
  }
7695
- // D3: budget-driven deferred-retry loop (only under --wait).
7696
- // Re-dispatches still-deferred tests until they all clear OR the --timeout
7697
- // budget is exhausted — a busy pool (the in-flight concurrency cap folds
7698
- // overflow into `deferred[]`) drains within the user's own timeout instead of
7699
- // giving up after a fixed few tries and failing the run. Each attempt sleeps
7700
- // 61s (clamped to the remaining budget); newly-accepted runs merge into
7701
- // `accepted`; if still deferred when the budget runs out, fall through to the
7702
- // existing exit-7 path. `maxDeferredAttempts` is a pure runaway backstop (the
7703
- // deadline check below is the real stop), scaled to the timeout so it never
7704
- // caps a legitimate long wait.
7705
- const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
7969
+ // A deferred id (rare: a busy project lock or a case that went in flight) was
7970
+ // not dispatched and is not resent: it is reported below and exits 7.
7706
7971
  const batchDeadlineMs = deps.environmentTunnel?.deadlineMs ?? Date.now() + opts.timeoutSeconds * 1000;
7707
- // finding 1: reserve a poll window so the deferred-retry loop can't consume the
7708
- // ENTIRE --timeout and leave the fan-out poll with nothing — which would report
7709
- // already-finished runs as timeouts (exit 7) instead of their real verdicts
7710
- // (a genuine failure is exit 1, not 7). One third of the budget, capped at 60s.
7711
- const POLL_RESERVE_MS = Math.min(60_000, Math.floor((opts.timeoutSeconds * 1000) / 3));
7712
- const maxDeferredAttempts = Math.max(MAX_DEFERRED_RETRIES, Math.ceil(opts.timeoutSeconds / 60) + 2);
7713
- for (let attempt = 1; attempt <= maxDeferredAttempts && deferred.length > 0; attempt++) {
7714
- const remainingMs = batchDeadlineMs - Date.now();
7715
- if (remainingMs <= POLL_RESERVE_MS) {
7716
- stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
7717
- break;
7718
- }
7719
- // §1: clamp to what's left ABOVE the reserve so the sleep itself can't run
7720
- // the budget to zero (the loop only reaches here when remainingMs >
7721
- // POLL_RESERVE_MS, so the difference is always positive).
7722
- const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs - POLL_RESERVE_MS);
7723
- stderrFn(`[deferred-retry] attempt ${attempt} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
7724
- await sleepFn(sleepMs);
7725
- const remainingAfterSleep = batchDeadlineMs - Date.now();
7726
- if (remainingAfterSleep <= POLL_RESERVE_MS) {
7727
- stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
7728
- break;
7729
- }
7730
- const retryIds = deferred.map(d => d.testId);
7731
- // [P2] Bound the derived key to ≤256 chars. Caller-supplied keys may be up
7732
- // to 256 chars; appending `:deferred-retryN` (≤16 chars) could push past
7733
- // the server's 256-char limit and cause every retry to be rejected. Truncate
7734
- // the base key to leave room for the suffix before concatenating.
7735
- const retrySuffix = `:deferred-retry${attempt}`;
7736
- const retryBase = idempotencyKey.length + retrySuffix.length > 256
7737
- ? idempotencyKey.slice(0, 256 - retrySuffix.length)
7738
- : idempotencyKey;
7739
- const retryKey = `${retryBase}${retrySuffix}`;
7740
- let retryResp;
7741
- try {
7742
- // The retry dispatch POST is deliberately NOT bound to the batch deadline
7743
- // via an AbortSignal. It is a state-CREATING call (it seeds runs); if the
7744
- // deadline fired mid-flight the abort would only cancel the CLIENT wait,
7745
- // leaving the server having possibly created the runs while this loop
7746
- // reports them as still-deferred — the user then retries with a fresh
7747
- // idempotency key and DUPLICATES the execution + charge. The per-request
7748
- // timeout (`--request-timeout`, default 120s) still bounds the call, and
7749
- // the sleeps + fan-out poll below remain deadline-aware; only this single
7750
- // dispatch may overrun the budget slightly, which is strictly safer than
7751
- // an indeterminate aborted-but-maybe-dispatched batch.
7752
- retryResp = await client.triggerBatchRunFresh({
7753
- projectId,
7754
- testIds: retryIds,
7755
- ...dispatchFields,
7756
- }, { idempotencyKey: retryKey });
7757
- }
7758
- catch (err) {
7759
- if (err instanceof InterruptError)
7760
- throw err;
7761
- if (err instanceof ApiError &&
7762
- (err.code === 'UNSUPPORTED' || err.code === 'PRECONDITION_FAILED'))
7763
- throw err;
7764
- if (opts.ci)
7765
- retryError = err;
7766
- // If the retry itself errors, surface it and stop retrying.
7767
- stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
7768
- break;
7769
- }
7770
- await assertBatchTargetEcho(retryResp, accepted);
7771
- // The retry re-sent the opt-out (see the dispatch above), so its echo has to
7772
- // be read as well; otherwise the tests a rate limit pushed into this leg are
7773
- // the only ones that run unwarned.
7774
- warnIfOptOutIgnored(opts.autoHeal, retryResp.autoHeal, stderrFn, 'the retried runs', optOutReported);
7775
- const newlyAccepted = retryResp.accepted;
7776
- const newlyDeferred = retryResp.deferred;
7777
- const newlyConflicted = retryResp.conflicts;
7778
- skippedFrontend.push(...retryResp.skippedFrontend);
7779
- skippedIntegration.push(...retryResp.skippedIntegration);
7780
- if (newlyAccepted.length > 0) {
7781
- stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyAccepted.length} test${newlyAccepted.length !== 1 ? 's' : ''} now accepted.`);
7782
- // A retry asks only for the still-deferred ids but can come back with
7783
- // tests the first dispatch already ran. Keeping both would poll the
7784
- // same test twice and overstate `summary.total`.
7785
- const { deduped, dropped } = dedupeBatchRunFreshAccepted(accepted.concat(newlyAccepted));
7786
- accepted = deduped;
7787
- warnDroppedDuplicateRuns(accepted, dropped, stderrFn);
7788
- }
7789
- if (newlyConflicted.length > 0) {
7790
- // [P1] Merge retry-returned conflicts into the running conflicts collection
7791
- // so the final summary, stderr output, and exit-code logic reflect them.
7792
- // Without this merge, tests deferred-then-conflicted on retry are invisible
7793
- // to the final accounting and can cause a false-zero conflicts count.
7794
- stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyConflicted.length} test${newlyConflicted.length !== 1 ? 's' : ''} in-flight (conflict).`);
7795
- conflicts = conflicts.concat(newlyConflicted);
7796
- }
7797
- deferred = newlyDeferred;
7798
- if (deferred.length === 0) {
7799
- stderrFn(`[deferred-retry] attempt ${attempt}: no tests remain rate-deferred.`);
7800
- }
7972
+ // A stopped dispatch: say what was never sent, then carry on to await what was accepted.
7973
+ const neverSent = stoppedError === undefined
7974
+ ? []
7975
+ : notRunTestIds.length > 0
7976
+ ? notRunTestIds
7977
+ : deferred.map(d => d.testId);
7978
+ const stoppedFailure = () => withDispatchHints(stoppedError, [
7979
+ `${neverSent.length} test${neverSent.length !== 1 ? 's were' : ' was'} not dispatched: ${neverSent.join(' ')}`,
7980
+ ]);
7981
+ if (stoppedError !== undefined) {
7982
+ stderrFn(`[run] Dispatch stopped (${stoppedError instanceof Error ? stoppedError.message : String(stoppedError)}); awaiting the runs already accepted. ` +
7983
+ `${neverSent.length} test${neverSent.length !== 1 ? 's were' : ' was'} not dispatched: ${neverSent.join(' ')}.`);
7801
7984
  }
7802
7985
  // Gap B: an already-running case is not a dead end under --wait. A conflict
7803
7986
  // carrying `currentRunId` has an EXISTING run we can poll to a verdict
@@ -7806,8 +7989,13 @@ export async function runTestRunAll(opts, deps = {}) {
7806
7989
  // resolvable in-flight run stay hard (nothing to wait on).
7807
7990
  // An in-flight run may belong to another deployment/environment. CI can
7808
7991
  // only use runs accepted by this invocation to judge its own change.
7809
- const resumableConflicts = opts.ci ? [] : conflicts.filter(c => c.currentRunId);
7810
- const hardConflicts = opts.ci ? conflicts : conflicts.filter(c => !c.currentRunId);
7992
+ // A `no_producer` / `producer_in_flight` conflict's `currentRunId` is the
7993
+ // result the server seeded BLOCKED before dispatch. It is reported with the
7994
+ // server's reason and exit 6, as a single `test run` reports it, not polled.
7995
+ // Every other conflict with a run id is polled as before.
7996
+ const isResumable = (c) => !opts.ci && Boolean(c.currentRunId) && !isProducerBlock(c);
7997
+ const resumableConflicts = conflicts.filter(isResumable);
7998
+ const hardConflicts = conflicts.filter(c => !isResumable(c));
7811
7999
  // Only hard conflicts remain "conflicts" for the final accounting/exit; the
7812
8000
  // resumable ones become polled results below.
7813
8001
  conflicts = hardConflicts;
@@ -7919,7 +8107,7 @@ export async function runTestRunAll(opts, deps = {}) {
7919
8107
  ]);
7920
8108
  warnDroppedDuplicateRuns(pollable, droppedFromMerge, stderrFn);
7921
8109
  if (pollable.length === 0) {
7922
- // Build final response with potentially-updated accepted/deferred from D3 retry loop.
8110
+ // Build final response from the dispatch result.
7923
8111
  const finalResp = {
7924
8112
  accepted,
7925
8113
  conflicts,
@@ -7928,8 +8116,9 @@ export async function runTestRunAll(opts, deps = {}) {
7928
8116
  skippedIntegration,
7929
8117
  ...(batchResp.integration !== undefined ? { integration: batchResp.integration } : {}),
7930
8118
  };
7931
- if (!opts.ci)
7932
- out.print(finalResp);
8119
+ if (!opts.ci) {
8120
+ out.print(notRunTestIds.length > 0 ? { ...finalResp, notRunTestIds } : finalResp);
8121
+ }
7933
8122
  recordBatchOutcome({
7934
8123
  accepted: accepted.length,
7935
8124
  conflicts,
@@ -7937,15 +8126,21 @@ export async function runTestRunAll(opts, deps = {}) {
7937
8126
  skipped: skippedFrontend.length + skippedIntegration.length,
7938
8127
  });
7939
8128
  if (opts.ci) {
7940
- await finishCiBatch({ ...finalResp, accepted: [] }, opts, deps, undefined, retryError);
8129
+ await finishCiBatch({ ...finalResp, accepted: [] }, opts, deps, undefined);
7941
8130
  return { ...batchResp, ...finalResp };
7942
8131
  }
7943
8132
  // Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
7944
8133
  // mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
7945
8134
  // Emit the deferred/conflict summary + annotations first so CI shows them (the
7946
8135
  // pure zero-dispatch fall-through emits its OWN skipped-rows summary below).
7947
- if (deferred.length > 0 || conflicts.length > 0) {
7948
- const summary = summarizeAcceptedPayload(JSON.stringify(finalResp));
8136
+ if (deferred.length > 0 || conflicts.length > 0 || stoppedError !== undefined) {
8137
+ const summary = summarizeAcceptedPayload(JSON.stringify({
8138
+ ...finalResp,
8139
+ skipped: notRunTestIds.map(testId => ({
8140
+ testId,
8141
+ reason: 'not dispatched: the dispatch stopped before this test was sent',
8142
+ })),
8143
+ }), { foldSkippedBuckets: explicitIds });
7949
8144
  await writeBatchJUnitReportIfRequested(opts, skippedJUnitResultsFromSummary(summary));
7950
8145
  emitCiArtifacts(summary, opts, {
7951
8146
  env: deps.env ?? process.env,
@@ -7953,6 +8148,8 @@ export async function runTestRunAll(opts, deps = {}) {
7953
8148
  stderr: stderrFn,
7954
8149
  }, 'run');
7955
8150
  }
8151
+ if (stoppedError !== undefined)
8152
+ throw stoppedFailure();
7956
8153
  if (deferred.length > 0) {
7957
8154
  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);
7958
8155
  }
@@ -7971,7 +8168,7 @@ export async function runTestRunAll(opts, deps = {}) {
7971
8168
  message: `Batch run: nothing was queued — ${allConflictsInFlight(conflicts)
7972
8169
  ? `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight`
7973
8170
  : summarizeConflicts(conflicts)}.`,
7974
- nextAction: `Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>${billingConflictLink(conflicts, batchApiUrl)}`,
8171
+ nextAction: `${conflictNextAction(conflicts, () => 'Wait for the in-flight runs to complete, then retry, or use: testsprite test wait <run-id>')}${billingConflictLink(conflicts, batchApiUrl)}`,
7975
8172
  requestId: 'local',
7976
8173
  details: { conflicts: conflicts.map(c => c.testId) },
7977
8174
  },
@@ -7989,7 +8186,9 @@ export async function runTestRunAll(opts, deps = {}) {
7989
8186
  stderrFn,
7990
8187
  emptyProject: skippedFrontend.length === 0 &&
7991
8188
  skippedIntegration.length === 0 &&
7992
- opts.nameFilter === undefined,
8189
+ opts.nameFilter === undefined &&
8190
+ opts.statusFilter === undefined &&
8191
+ !explicitIds,
7993
8192
  projectId,
7994
8193
  });
7995
8194
  // [P2] Return post-retry state (reached only under --allow-empty).
@@ -8004,12 +8203,12 @@ export async function runTestRunAll(opts, deps = {}) {
8004
8203
  // `timeoutSeconds`. Without this, runs that wait behind `--max-concurrency`
8005
8204
  // could push total wall-clock to ~ceil(N/concurrency) × timeout instead of
8006
8205
  // the documented `--timeout` ceiling.
8007
- // NOTE: batchDeadlineMs is set in the D3 deferred-retry loop above and reused here.
8206
+ // NOTE: batchDeadlineMs is set after the dispatch above and reused here.
8008
8207
  async function pollFreshAccepted(entry) {
8009
8208
  const runId = entry.runId;
8010
8209
  const remainingMs = batchDeadlineMs - Date.now();
8011
8210
  if (remainingMs <= 0) {
8012
- // §1/§4: the retry loop reserves POLL_RESERVE_MS, but a slow fan-out can
8211
+ // §1/§4: a slow fan-out can
8013
8212
  // still land here past the deadline. Do ONE bounded poll (1s) THROUGH the
8014
8213
  // backend wait-fallback before declaring timeout — a run that already
8015
8214
  // reached a verdict resolves for ~one request instead of a false timeout
@@ -8224,6 +8423,7 @@ export async function runTestRunAll(opts, deps = {}) {
8224
8423
  skippedFrontend,
8225
8424
  skippedIntegration,
8226
8425
  ...(batchResp.integration !== undefined ? { integration: batchResp.integration } : {}),
8426
+ ...(notRunTestIds.length > 0 ? { notRunTestIds } : {}),
8227
8427
  summary: {
8228
8428
  passed,
8229
8429
  failed,
@@ -8234,9 +8434,18 @@ export async function runTestRunAll(opts, deps = {}) {
8234
8434
  },
8235
8435
  };
8236
8436
  const freshNameMap = opts.report === 'junit' && opts.reportFile !== undefined
8237
- ? await buildTestNameMap(client, opts.projectId)
8437
+ ? explicitIds
8438
+ ? await buildTestNameMapForProjects(client, [...new Set(projectOf.values())])
8439
+ : await buildTestNameMap(client, opts.projectId)
8238
8440
  : undefined;
8239
- const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
8441
+ const ciSummary = summarizeAcceptedPayload(JSON.stringify({
8442
+ ...jsonPayload,
8443
+ // Never-sent ids are rows of their own, so the artifacts do not read as a complete batch.
8444
+ skipped: notRunTestIds.map(testId => ({
8445
+ testId,
8446
+ reason: 'not dispatched: the dispatch stopped before this test was sent',
8447
+ })),
8448
+ }), { foldSkippedBuckets: explicitIds });
8240
8449
  // JUnit rows carry the poll timing the stdout envelope deliberately omits.
8241
8450
  const timedResults = freshRunResults.map(r => ({
8242
8451
  ...r,
@@ -8271,7 +8480,7 @@ export async function runTestRunAll(opts, deps = {}) {
8271
8480
  }
8272
8481
  let gateError;
8273
8482
  try {
8274
- await finishCiBatch(jsonPayload, opts, deps, freshNameMap, retryError, timedResults, executionReport);
8483
+ await finishCiBatch(jsonPayload, opts, deps, freshNameMap, undefined, timedResults, executionReport);
8275
8484
  }
8276
8485
  catch (err) {
8277
8486
  gateError = err;
@@ -8294,6 +8503,10 @@ export async function runTestRunAll(opts, deps = {}) {
8294
8503
  stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
8295
8504
  stderr: stderrFn,
8296
8505
  }, 'run');
8506
+ // The failed request outranks every code below (deferred 7, failed verdict 1,
8507
+ // credits 12, conflict 6): the runs it left behind have been awaited and reported.
8508
+ if (stoppedError !== undefined)
8509
+ throw stoppedFailure();
8297
8510
  // Rate-deferred tests were never dispatched → the batch is incomplete (exit 7),
8298
8511
  // mirroring `test rerun --all`. Checked before the failed-run throw so the
8299
8512
  // operator learns to retry the deferred set.
@@ -8329,7 +8542,6 @@ export async function runTestRunAll(opts, deps = {}) {
8329
8542
  // Pure unresumed in-flight keeps the original "already in flight and could
8330
8543
  // not be resumed" wording; a paused-workspace refusal mixed in here isn't
8331
8544
  // something that "could not be resumed" — it was never resumable to begin with.
8332
- const ids = conflicts.map(c => c.testId).join(' ');
8333
8545
  // This is the one CONFLICT throw where `accepted` can be non-empty (a
8334
8546
  // mixed batch with some runs dispatched/resumed) — the advisory printed
8335
8547
  // earlier already showed the link in that case (guarded the same way), so
@@ -8340,16 +8552,16 @@ export async function runTestRunAll(opts, deps = {}) {
8340
8552
  code: 'CONFLICT',
8341
8553
  message: allConflictsInFlight(conflicts)
8342
8554
  ? `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight and could not be resumed — not run.`
8343
- : `${summarizeConflicts(conflicts)} — not run.`,
8344
- nextAction: `Wait for the in-flight run(s) to finish, then retry: ${ids}${link}`,
8555
+ : `${summarizeConflicts(conflicts)} — ${conflicts.every(isProducerBlock) ? 'blocked before dispatch' : 'not run'}.`,
8556
+ nextAction: `${conflictNextAction(conflicts, ids => `Wait for the in-flight run(s) to finish, then retry: ${ids.join(' ')}`)}${link}`,
8345
8557
  requestId: 'local',
8346
8558
  details: { conflicts: conflicts.map(c => c.testId) },
8347
8559
  },
8348
8560
  });
8349
8561
  }
8350
- // [P2] Return object reconstructed from post-retry mutable state (accepted,
8351
- // deferred, conflicts) so the caller always sees what was actually dispatched,
8352
- // not the stale initial batchResp. accepted here still holds the original
8562
+ // Return object reconstructed from the dispatch result (accepted, deferred,
8563
+ // conflicts) so the caller always sees what was actually dispatched.
8564
+ // accepted here still holds the original
8353
8565
  // BatchRunFreshAccepted entries (with runId + enqueuedAt); the freshRunResults
8354
8566
  // fan-out is for exit-code logic only and is not part of the returned type.
8355
8567
  return { ...batchResp, accepted, deferred, conflicts };
@@ -8357,6 +8569,7 @@ export async function runTestRunAll(opts, deps = {}) {
8357
8569
  /** One bounded trigger-and-wait pool shares one local tunnel for its full lifetime. */
8358
8570
  export async function runTestRunLocalBatch(opts, deps = {}) {
8359
8571
  assertIdempotencyKey(opts.idempotencyKey);
8572
+ validateStatusSelector(opts.statusFilter);
8360
8573
  const environment = normalizeEnvironmentName(opts.environment);
8361
8574
  if (!Number.isInteger(opts.maxConcurrency) ||
8362
8575
  opts.maxConcurrency < 1 ||
@@ -8377,12 +8590,27 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8377
8590
  const projectId = opts.all ? resolveProjectId(opts.projectId, deps) : opts.projectId;
8378
8591
  if (opts.all)
8379
8592
  requireProjectId(projectId);
8593
+ // Ids the tunnel path cannot carry (public targets, backend tests, no
8594
+ // loopback environment) go out as batch runs. Their tests are read at most
8595
+ // once here, so the batch resolver is handed what is already known.
8596
+ const preflightKnown = new Map();
8597
+ const batchRunOptions = () => ({
8598
+ ...opts,
8599
+ projectId,
8600
+ wait: opts.wait === true,
8601
+ // The tunnel default (longer) only applies when a tunnel carries the runs.
8602
+ ...(!opts.all && opts.timeoutIsDefault ? { timeoutSeconds: DEFAULT_RUN_TIMEOUT_SECONDS } : {}),
8603
+ environmentResolutionComplete: true,
8604
+ testIds: opts.all ? undefined : opts.testIds,
8605
+ knownTests: preflightKnown,
8606
+ });
8380
8607
  if (opts.localPort === undefined &&
8381
8608
  targetUrl !== undefined &&
8382
8609
  !parseLoopbackTargetUrl(targetUrl)) {
8383
- if (!opts.all)
8384
- severalIdsWithoutTunnel();
8385
8610
  assertNoTunnelOptions(opts);
8611
+ // A public --target-url needs no tunnel, so the ids go out as one batch run.
8612
+ if (!opts.all)
8613
+ return void (await runTestRunAll(batchRunOptions(), deps));
8386
8614
  }
8387
8615
  const dryRunTargets = new Map();
8388
8616
  const automaticDryRun = opts.dryRun && targetUrl === undefined;
@@ -8429,7 +8657,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8429
8657
  }
8430
8658
  if (!targets.length) {
8431
8659
  assertNoTunnelOptions(opts);
8432
- severalIdsWithoutTunnel();
8660
+ return void (await runTestRunAll(batchRunOptions(), deps));
8433
8661
  }
8434
8662
  targetUrl = targets[0].targetUrl;
8435
8663
  }
@@ -8447,6 +8675,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8447
8675
  tunnelClientId: opts.tunnelClientId ?? '<minted at run time>',
8448
8676
  }),
8449
8677
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
8678
+ ...(opts.skipDependencies ? { skipDependencies: true } : {}),
8450
8679
  ...(environment !== undefined ? { environment } : {}),
8451
8680
  },
8452
8681
  }));
@@ -8471,16 +8700,14 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8471
8700
  let tests = opts.testIds.map(id => ({ id }));
8472
8701
  const knownTests = new Map();
8473
8702
  if (opts.all) {
8474
- const page = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
8475
- query: { projectId, pageSize, cursor },
8476
- }), {});
8477
- const needle = opts.nameFilter?.toLowerCase();
8478
- const filtered = needle
8479
- ? page.items.filter(t => t.name.toLowerCase().includes(needle))
8480
- : page.items;
8481
- const omitted = page.items.length - filtered.length;
8482
- if (omitted > 0)
8483
- stderrFn(`--filter: skipped ${omitted} test${omitted !== 1 ? 's' : ''} whose name does not contain "${opts.nameFilter}".`);
8703
+ const filtered = await resolveAllProjectTests({
8704
+ client,
8705
+ projectId: projectId,
8706
+ statusFilter: opts.statusFilter,
8707
+ nameFilter: opts.nameFilter,
8708
+ stderr: stderrFn,
8709
+ latestStatus: true,
8710
+ });
8484
8711
  tests = filtered.map(t => {
8485
8712
  knownTests.set(t.id, { type: t.type, projectId: t.projectId ?? projectId });
8486
8713
  return { id: t.id, name: t.name };
@@ -8500,6 +8727,8 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8500
8727
  if (opts.localPort !== undefined)
8501
8728
  throw err;
8502
8729
  }
8730
+ if (known?.projectId !== undefined)
8731
+ preflightKnown.set(test.id, known);
8503
8732
  }
8504
8733
  const target = (known?.projectId === projectId && known?.type !== 'backend'
8505
8734
  ? opts.resolvedTarget
@@ -8527,16 +8756,12 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8527
8756
  targets.set(test.id, target);
8528
8757
  }
8529
8758
  const firstTarget = targets.values().next().value;
8530
- if (!firstTarget && !(opts.all && tests.length === 0) && skipped.length === 0) {
8759
+ // Several ids with no tunnel target at all (public environment, or backend
8760
+ // tests that never use one) are an ordinary batch run, skipped backend tests
8761
+ // included.
8762
+ if (!firstTarget && (!opts.all || (tests.length > 0 && skipped.length === 0))) {
8531
8763
  assertNoTunnelOptions(opts);
8532
- if (!opts.all)
8533
- severalIdsWithoutTunnel();
8534
- return void (await runTestRunAll({
8535
- ...opts,
8536
- projectId: projectId,
8537
- wait: opts.wait === true,
8538
- environmentResolutionComplete: true,
8539
- }, deps));
8764
+ return void (await runTestRunAll(batchRunOptions(), deps));
8540
8765
  }
8541
8766
  if (skipped.length)
8542
8767
  stderrFn(`[advisory] ${skipped.length} backend test(s) skipped — tunnel runs frontend tests only.`);
@@ -8655,8 +8880,8 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8655
8880
  if (results.length === 0) {
8656
8881
  printResults();
8657
8882
  await finishZeroDispatchBatch({
8658
- reason: opts.nameFilter
8659
- ? `--filter "${opts.nameFilter}" matched no frontend tests in project ${projectId}`
8883
+ reason: opts.nameFilter || opts.statusFilter !== undefined
8884
+ ? `${describeRunSelectors(opts)} matched no frontend tests in project ${projectId}`
8660
8885
  : 'no runnable frontend tests in the project',
8661
8886
  skipped: skipped.map(s => s.testId),
8662
8887
  allowEmpty: opts.allowEmpty,
@@ -8664,7 +8889,10 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8664
8889
  deps,
8665
8890
  stderrFn,
8666
8891
  // A project with only backend tests is not empty: they were skipped, not absent.
8667
- emptyProject: opts.all && skipped.length === 0 && opts.nameFilter === undefined,
8892
+ emptyProject: opts.all &&
8893
+ skipped.length === 0 &&
8894
+ opts.nameFilter === undefined &&
8895
+ opts.statusFilter === undefined,
8668
8896
  projectId,
8669
8897
  local: {
8670
8898
  // An automatic target was resolved from a saved environment; its port
@@ -8702,6 +8930,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8702
8930
  // Trigger requests are uninterruptible (the server may already have charged
8703
8931
  // the run), so an abort waits for them before cancelling and closing.
8704
8932
  const pendingTriggers = new Set();
8933
+ let skipDependenciesUnconfirmedShown = false;
8705
8934
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
8706
8935
  const setAbort = (reason, lost) => {
8707
8936
  if (abortReason === undefined) {
@@ -8776,6 +9005,7 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8776
9005
  }
8777
9006
  : {}),
8778
9007
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
9008
+ ...(opts.skipDependencies ? { skipDependencies: true } : {}),
8779
9009
  ...(environment !== undefined ? { environment } : {}),
8780
9010
  }, { idempotencyKey: key }));
8781
9011
  pendingTriggers.add(triggering);
@@ -8785,6 +9015,12 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8785
9015
  finally {
8786
9016
  pendingTriggers.delete(triggering);
8787
9017
  }
9018
+ if (opts.skipDependencies &&
9019
+ response.skipDependencies !== true &&
9020
+ !skipDependenciesUnconfirmedShown) {
9021
+ skipDependenciesUnconfirmedShown = true;
9022
+ stderrFn('[advisory] This backend did not confirm --skip-dependencies, so the runs may also include the test cases they depend on, as a Portal run does.');
9023
+ }
8788
9024
  row.runId = response.runId;
8789
9025
  row.status = 'running';
8790
9026
  activeRows.add(index);
@@ -9146,6 +9382,7 @@ function validateRerunOptions(opts) {
9146
9382
  throw localValidationError('status', '--status only applies with --all (it narrows which project tests get reran). ' +
9147
9383
  'Remove --status, or add --all --project <id>.');
9148
9384
  }
9385
+ assertStatusSelectorNotEmpty(opts.statusFilter);
9149
9386
  if (opts.skipTerminal && !opts.all) {
9150
9387
  throw localValidationError('skip-terminal', '--skip-terminal only applies with --all (it narrows which project tests get reran). ' +
9151
9388
  'Remove --skip-terminal, or add --all --project <id>.');
@@ -9913,47 +10150,16 @@ async function runTestRerunCore(opts, deps = {}) {
9913
10150
  if (opts.statusFilter !== undefined) {
9914
10151
  validateStatusFilter(opts.statusFilter);
9915
10152
  }
9916
- // Resolve all tests in the project — follow nextToken until exhausted so
9917
- // projects with >1 service page (>25 tests) are fully covered.
9918
- const allPage = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
9919
- query: { projectId: opts.projectId, pageSize, cursor },
9920
- }), {});
9921
- let allTests = allPage.items;
9922
- // --skip-terminal: exclude tests already in a terminal status so an
9923
- // interrupted sweep doesn't re-replay finished tests.
9924
- if (opts.skipTerminal) {
9925
- const before = allTests.length;
9926
- allTests = allTests.filter(t => !TERMINAL_PUBLIC_STATUSES.has(t.status));
9927
- const skipped = before - allTests.length;
9928
- if (skipped > 0) {
9929
- stderrFn(`--skip-terminal: skipped ${skipped} already-terminal test${skipped !== 1 ? 's' : ''} (passed|failed|blocked|cancelled).`);
9930
- }
9931
- }
9932
- // --status <list>: only dispatch tests whose status matches one of the
9933
- // listed values. Tokens are already validated above.
9934
- if (opts.statusFilter !== undefined && opts.statusFilter !== '') {
9935
- const allowed = new Set(opts.statusFilter
9936
- .split(',')
9937
- .map(s => s.trim())
9938
- .filter(s => s.length > 0));
9939
- const before = allTests.length;
9940
- allTests = allTests.filter(t => allowed.has(t.status));
9941
- const skipped = before - allTests.length;
9942
- if (skipped > 0) {
9943
- stderrFn(`--status filter: skipped ${skipped} test${skipped !== 1 ? 's' : ''} not matching status=${opts.statusFilter}.`);
9944
- }
9945
- }
9946
- // --filter <substr>: only dispatch tests whose name contains the
9947
- // substring (case-insensitive). Applied after --skip-terminal and --status.
9948
- if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
9949
- const needle = opts.nameFilter.toLowerCase();
9950
- const before = allTests.length;
9951
- allTests = allTests.filter(t => t.name.toLowerCase().includes(needle));
9952
- const skipped = before - allTests.length;
9953
- if (skipped > 0) {
9954
- stderrFn(`--filter: skipped ${skipped} test${skipped !== 1 ? 's' : ''} whose name does not contain "${opts.nameFilter}".`);
9955
- }
9956
- }
10153
+ // Follows nextToken until exhausted so projects with >1 service page
10154
+ // (>25 tests) are fully covered.
10155
+ const allTests = await resolveAllProjectTests({
10156
+ client,
10157
+ projectId: opts.projectId,
10158
+ statusFilter: opts.statusFilter,
10159
+ skipTerminal: opts.skipTerminal,
10160
+ nameFilter: opts.nameFilter,
10161
+ stderr: stderrFn,
10162
+ });
9957
10163
  testIds = allTests.map(t => t.id);
9958
10164
  knownTests = new Map(allTests.map(t => [t.id, { type: t.type, projectId: t.projectId ?? opts.projectId }]));
9959
10165
  if (testIds.length === 0) {
@@ -10100,20 +10306,11 @@ async function runTestRerunCore(opts, deps = {}) {
10100
10306
  advisories: dedupeRerunAdvisories(chunkResponses.flatMap(r => r.advisories ?? [])),
10101
10307
  };
10102
10308
  // Print dispatch summary
10103
- // Mutable: D3 deferred-retry loop may append to `accepted`/`conflicts` and
10104
- // drain `deferred` under --wait. `advisories` may also grow if a D3 retry
10105
- // response carries an advisory the initial dispatch didn't (defensive —
10106
- // in practice the same request shape produces the same advisory set).
10107
- let accepted = batchResp.accepted.slice();
10108
- let deferred = batchResp.deferred.slice();
10109
- let conflicts = batchResp.conflicts.slice();
10110
- // [P2] `notFound` is mutable: a deferred test may become un-replayable during
10111
- // the retry window; the retry response's notFound[] is merged into this set so
10112
- // the test is never reported as "resolved" when it actually vanished.
10113
- let notFound = (batchResp.notFound ?? []).slice();
10114
- // Mutable so a D3 deferred-retry response can contribute an
10115
- // advisory the initial dispatch didn't carry (defensive; see comment above).
10116
- let advisories = (batchResp.advisories ?? []).slice();
10309
+ const accepted = batchResp.accepted.slice();
10310
+ const deferred = batchResp.deferred.slice();
10311
+ const conflicts = batchResp.conflicts.slice();
10312
+ const notFound = (batchResp.notFound ?? []).slice();
10313
+ const advisories = (batchResp.advisories ?? []).slice();
10117
10314
  const closureByProject = batchResp.closure.byProject;
10118
10315
  const addedProducersTotal = closureByProject.reduce((n, p) => n + p.addedProducers.length, 0);
10119
10316
  const summaryParts = [
@@ -10148,180 +10345,9 @@ async function runTestRerunCore(opts, deps = {}) {
10148
10345
  const deferredIds = deferred.map(d => d.testId).join(' ');
10149
10346
  stderrFn(`nextAction: testsprite test rerun ${deferredIds}`);
10150
10347
  }
10151
- const emitRetryPartial = async (error, responses = []) => {
10152
- if (!deps.environmentTunnel)
10153
- return;
10154
- const retried = new Set(responses
10155
- .flatMap(response => [...response.accepted, ...response.conflicts, ...response.deferred])
10156
- .map(row => row.testId));
10157
- await emitEnvironmentDispatchPartial([
10158
- {
10159
- accepted,
10160
- conflicts,
10161
- deferred: deferred.filter(row => !retried.has(row.testId)),
10162
- notFound,
10163
- },
10164
- ...responses,
10165
- ], testIds, opts, deps, 'rerun', error, deps.environmentTunnel);
10166
- };
10167
- // D3: budget-driven deferred-retry loop for rerun --all (only under --wait).
10168
- // Re-dispatches still-deferred tests until they all clear OR the --timeout
10169
- // budget is exhausted — a busy pool drains within the user's own timeout
10170
- // instead of giving up after a fixed few tries and failing the run. Each
10171
- // attempt sleeps 61s (clamped to the remaining budget); newly-accepted runs
10172
- // merge into `accepted`; if still deferred when the budget runs out, fall
10173
- // through to the existing exit-7 path. `maxDeferredAttempts` is a pure runaway
10174
- // backstop (the deadline check below is the real stop), scaled to the timeout.
10175
- const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
10348
+ // A deferred id (rare: a busy project lock or a case that went in flight) was
10349
+ // not dispatched and is not resent: it is reported below and exits 7.
10176
10350
  const batchDeadlineMs = deps.environmentTunnel?.deadlineMs ?? Date.now() + opts.timeoutSeconds * 1000;
10177
- // finding 1: reserve a poll window so the deferred-retry loop can't consume the
10178
- // ENTIRE --timeout and leave the fan-out poll with nothing — which would report
10179
- // already-finished runs as timeouts (exit 7) instead of their real verdicts
10180
- // (a genuine failure is exit 1, not 7). One third of the budget, capped at 60s.
10181
- const POLL_RESERVE_MS = Math.min(60_000, Math.floor((opts.timeoutSeconds * 1000) / 3));
10182
- const maxDeferredAttempts = Math.max(MAX_DEFERRED_RETRIES, Math.ceil(opts.timeoutSeconds / 60) + 2);
10183
- if (opts.wait) {
10184
- for (let attempt = 1; attempt <= maxDeferredAttempts && deferred.length > 0; attempt++) {
10185
- const remainingMs = batchDeadlineMs - Date.now();
10186
- if (remainingMs <= POLL_RESERVE_MS) {
10187
- stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
10188
- break;
10189
- }
10190
- // §1: clamp to what's left ABOVE the reserve so the sleep itself can't run
10191
- // the budget to zero (the loop only reaches here when remainingMs >
10192
- // POLL_RESERVE_MS, so the difference is always positive).
10193
- const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs - POLL_RESERVE_MS);
10194
- stderrFn(`[deferred-retry] attempt ${attempt} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
10195
- try {
10196
- if (deps.environmentTunnel)
10197
- await sleepUntilOrInterrupt(sleepMs, shutdownOf(deps).signal, sleepFn);
10198
- else
10199
- await sleepFn(sleepMs);
10200
- }
10201
- catch (err) {
10202
- await emitRetryPartial(err);
10203
- throw err;
10204
- }
10205
- const remainingAfterSleep = batchDeadlineMs - Date.now();
10206
- if (remainingAfterSleep <= POLL_RESERVE_MS) {
10207
- stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
10208
- break;
10209
- }
10210
- // Chunk the retry ids to stay within MAX_BATCH_RERUN_IDS cap.
10211
- const retryIds = deferred.map(d => d.testId);
10212
- const retryChunks = [];
10213
- for (let i = 0; i < retryIds.length; i += MAX_BATCH_RERUN_IDS) {
10214
- retryChunks.push(retryIds.slice(i, i + MAX_BATCH_RERUN_IDS));
10215
- }
10216
- if (deps.environmentTunnel?.targets) {
10217
- const grouped = retryChunks.flatMap(chunk => groupEnvironmentTargets(chunk, deps.environmentTunnel.targets, deps.environmentTunnel.maxConcurrency));
10218
- retryChunks.splice(0, retryChunks.length, ...grouped);
10219
- }
10220
- const retryChunkResponses = [];
10221
- try {
10222
- // Sequential, same reason as the initial dispatch above: concurrent
10223
- // chunks racing on per-request server-side closure dedup can
10224
- // double-trigger a shared BE producer/teardown.
10225
- for (let idx = 0; idx < retryChunks.length; idx++) {
10226
- const chunk = retryChunks[idx];
10227
- // [P2] Bound the derived key to ≤256 chars. Caller-supplied keys may
10228
- // be up to 256 chars; appending the suffix could exceed the server
10229
- // limit and cause every retry to be rejected. Truncate the base key
10230
- // to leave room for the longest possible suffix before concatenating.
10231
- const retrySuffix = retryChunks.length === 1
10232
- ? `:deferred-retry${attempt}`
10233
- : `:deferred-retry${attempt}:chunk${idx}`;
10234
- const retryBase = idempotencyKey.length + retrySuffix.length > 256
10235
- ? idempotencyKey.slice(0, 256 - retrySuffix.length)
10236
- : idempotencyKey;
10237
- const retryKey = `${retryBase}${retrySuffix}`;
10238
- // The retry chunk POST is deliberately NOT bound to the batch
10239
- // deadline via an AbortSignal — same reasoning as the fresh-run retry
10240
- // above: it seeds runs, so a mid-flight abort would leave the server
10241
- // possibly having dispatched while this loop reports the chunk as
10242
- // still-deferred, inviting a duplicate rerun on the user's next
10243
- // invocation. The per-request timeout still bounds it; the sleeps +
10244
- // poll stay deadline-aware.
10245
- if (deps.environmentTunnel?.targets?.has(chunk[0]))
10246
- await deps.environmentTunnel.waitForCapacity(chunk.length);
10247
- const retryChunkResp = await client.triggerBatchRerun({
10248
- source: 'cli',
10249
- testIds: chunk,
10250
- ...(environment !== undefined ? { environment } : {}),
10251
- ...(deps.environmentTunnel?.targets?.has(chunk[0])
10252
- ? {
10253
- tunnelClientId: deps.environmentTunnel.clientId,
10254
- targetUrl: deps.environmentTunnel.targets.get(chunk[0]).targetUrl,
10255
- }
10256
- : {}),
10257
- // Always send the effective boolean, including an explicit
10258
- // `false` opt-out — see the matching comment on the initial
10259
- // dispatch call site above.
10260
- autoHeal: effectiveAutoHeal,
10261
- ...(opts.skipDependencies ? { skipDependencies: true } : {}),
10262
- }, { idempotencyKey: retryKey });
10263
- retryChunkResponses.push(retryChunkResp);
10264
- if (deps.environmentTunnel?.targets?.has(chunk[0]))
10265
- await deps.environmentTunnel.confirm(retryChunkResp, retryChunkResp.accepted.map(row => row.runId));
10266
- }
10267
- }
10268
- catch (err) {
10269
- if (deps.environmentTunnel) {
10270
- await emitRetryPartial(err, retryChunkResponses);
10271
- throw err;
10272
- }
10273
- if (err instanceof InterruptError)
10274
- throw err;
10275
- stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
10276
- break;
10277
- }
10278
- const { deduped: newlyAccepted, dropped: newlyDuplicate } = dedupeBatchRerunAccepted(retryChunkResponses.flatMap(r => r.accepted));
10279
- const newlyDeferred = retryChunkResponses.flatMap(r => r.deferred);
10280
- const newlyConflicted = retryChunkResponses.flatMap(r => r.conflicts);
10281
- // [P2] Collect notFound[] from the retry response. A deferred test may be
10282
- // un-replayable by the time we retry (e.g. the test was deleted). Merge
10283
- // into the running notFound set and remove from deferred so it isn't
10284
- // reported as "resolved" in the final output.
10285
- const newlyNotFound = retryChunkResponses.flatMap(r => r.notFound ?? []);
10286
- // Merge any advisories the retry response carries into the
10287
- // running set (deduped — see the initial-dispatch comment above).
10288
- const newlyAdvisories = retryChunkResponses.flatMap(r => r.advisories ?? []);
10289
- if (newlyAdvisories.length > 0) {
10290
- advisories = dedupeRerunAdvisories(advisories.concat(newlyAdvisories));
10291
- }
10292
- warnDroppedDuplicateRuns(newlyAccepted, newlyDuplicate, stderrFn);
10293
- if (newlyAccepted.length > 0) {
10294
- stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyAccepted.length} test${newlyAccepted.length !== 1 ? 's' : ''} now accepted.`);
10295
- // A retry asks only for the still-deferred ids but can come back with
10296
- // a test an earlier attempt already ran; the extra run is reported.
10297
- const { deduped: mergedAccepted, dropped: droppedAcrossAttempts } = dedupeBatchRerunAccepted(accepted.concat(newlyAccepted));
10298
- accepted = mergedAccepted;
10299
- warnDroppedDuplicateRuns(accepted, droppedAcrossAttempts, stderrFn);
10300
- }
10301
- if (newlyConflicted.length > 0) {
10302
- // [P1] Merge retry-returned conflicts into the running conflicts collection
10303
- // so the final summary, stderr output, and exit-code logic reflect them.
10304
- stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyConflicted.length} test${newlyConflicted.length !== 1 ? 's' : ''} in-flight (conflict).`);
10305
- conflicts = conflicts.concat(newlyConflicted);
10306
- }
10307
- if (newlyNotFound.length > 0) {
10308
- // [P2] Merge retry-discovered notFound ids and warn so the operator knows
10309
- // which tests vanished. Remove the now-un-replayable ids from `deferred`
10310
- // (newlyDeferred is the authoritative post-retry deferred set — it won't
10311
- // include these ids — but be explicit so the logic is clear).
10312
- stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyNotFound.length} test id${newlyNotFound.length !== 1 ? 's' : ''} not found on retry (deleted or never ran cleanly): ${newlyNotFound.join(' ')}`);
10313
- notFound = notFound.concat(newlyNotFound);
10314
- // Warn via the standard notFound stderr block (mirrors the initial dispatch).
10315
- for (const id of newlyNotFound)
10316
- stderrFn(` ${id}`);
10317
- stderrFn(` Skipped ids have no replayable run. Use 'testsprite test run <id>' for a first (fresh) run.`);
10318
- }
10319
- deferred = newlyDeferred;
10320
- if (deferred.length === 0) {
10321
- stderrFn(`[deferred-retry] attempt ${attempt}: all previously-deferred tests accepted.`);
10322
- }
10323
- }
10324
- }
10325
10351
  /**
10326
10352
  * Every requested id landed in `notFound` and nothing was queued. A rerun
10327
10353
  * where every id was unusable is not a success: exit 4 (NOT_FOUND), the same
@@ -10341,8 +10367,6 @@ async function runTestRerunCore(opts, deps = {}) {
10341
10367
  // had a chance to contribute one, not once per chunk/attempt.
10342
10368
  emitRerunAdvisories(stderrFn, advisories);
10343
10369
  if (!opts.wait) {
10344
- // [P2] Build output from post-retry mutable state so deferred/conflicts/notFound
10345
- // reflect what the D3 loop discovered, not just the initial batchResp.
10346
10370
  out.print({ ...batchResp, accepted, deferred, conflicts, notFound, advisories });
10347
10371
  if (deferred.length > 0) {
10348
10372
  throw new CLIError(`Batch rerun incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} were rate-deferred. Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
@@ -10446,7 +10470,6 @@ async function runTestRerunCore(opts, deps = {}) {
10446
10470
  const concurrencyLimit = opts.maxConcurrency;
10447
10471
  const rerunResults = [];
10448
10472
  const reportTiming = new Map();
10449
- // sleepFn is declared above in the D3 deferred-retry section (shared by fan-out).
10450
10473
  async function pollAccepted(entry) {
10451
10474
  const resolveAlternate = makeBackendWaitFallback({
10452
10475
  client,
@@ -10881,13 +10904,11 @@ function renderArtifactGetWrittenText(data) {
10881
10904
  * test, so the probe is a heuristic, not a guarantee — hence the full
10882
10905
  * opt-out.
10883
10906
  */
10884
- const SKIP_PREFLIGHT_HELP = 'skip the pre-charge reachability probe for a target URL. The probe runs from this machine, not ' +
10885
- 'from the Lambda that executes the test, so it can occasionally be wrong (e.g. an IP allowlist ' +
10886
- 'that permits the Lambda but not this machine); use this flag when you know better. Zero network ' +
10887
- 'calls when set.';
10888
- const TARGET_URL_HELP = "frontend tests only: use the environment already pointing at this URL's origin, or a temporary one TestSprite deletes when the run finishes; with --env, use its settings against this URL; loopback URLs open a tunnel automatically";
10907
+ const SKIP_PREFLIGHT_HELP = 'skip the pre-charge reachability probe of the target URL (it runs from this machine, not the ' +
10908
+ 'cloud, so it can be wrong, e.g. behind an IP allowlist)';
10909
+ const TARGET_URL_HELP = "frontend tests only: run against this URL, using the environment for its origin (else a temporary one deleted after the run); with --env, that environment's settings; loopback URLs open a tunnel";
10889
10910
  export function createTestCommand(deps = {}) {
10890
- const test = new Command('test').description('Inspect TestSprite tests');
10911
+ const test = new Command('test').description('Create, run and inspect tests');
10891
10912
  test
10892
10913
  .command('list')
10893
10914
  .description('List tests in a project')
@@ -10897,12 +10918,12 @@ export function createTestCommand(deps = {}) {
10897
10918
  // the CLI error spec §2 ("missing required field"). `requireProjectId`
10898
10919
  // below raises `ApiError(VALIDATION_ERROR)` so JSON consumers can read
10899
10920
  // `error.code` and the exit code matches the catalog.
10900
- .option('--project <id>', 'project id (returned by `testsprite project list`)')
10921
+ .option('--project <id>', 'project id (required unless TESTSPRITE_PROJECT_ID is set)')
10901
10922
  .option('--env <name>', 'show frontend test statuses for the named project environment')
10902
10923
  .option('--type <type>', 'filter by test type (frontend|backend)')
10903
10924
  .option('--created-from <source>', 'filter by where the test was authored (portal|mcp|cli)')
10904
- .option('--status <list>', 'filter by normalized status (comma-separated). One of: draft, ready, queued, running, passed, failed, blocked, cancelled, unknown')
10905
- .option('--page-size <n>', 'service page-size hint (1-100, default 25)')
10925
+ .option('--status <list>', `filter by the status of each test case's latest result (comma-separated; accepted: ${RUN_STATUS_VALUES.join('|')}; not_run = never ran)`)
10926
+ .option('--page-size <n>', 'fetch ONE page of N items (1-100) and print the next token (default: follow every page; --max-items caps that)')
10906
10927
  .option('--starting-token <token>', 'opaque cursor from a previous list response')
10907
10928
  .option('--cursor <token>', 'alias for --starting-token; accepted for parity with `test result --history`')
10908
10929
  .option('--max-items <n>', 'stop after this many items across auto-paged pages')
@@ -10941,34 +10962,30 @@ export function createTestCommand(deps = {}) {
10941
10962
  });
10942
10963
  test
10943
10964
  .command('create')
10965
+ .summary('Create a test from code (--code-file) or a plan (--plan-from)')
10944
10966
  .description('Create a test from saved code (--code-file) or an agent-supplied plan (--plan-from, FE-only)')
10945
- .option('--project <id>', 'project id (returned by `testsprite project list`)')
10967
+ .option('--project <id>', 'project id (see `testsprite project list`)')
10946
10968
  .option('--type <type>', 'frontend|backend')
10947
- .option('--name <name>', 'human-readable test name (becomes `title` in storage)')
10969
+ .option('--name <name>', 'human-readable test name')
10948
10970
  .option('--description <text>', 'optional human description (≤ 2000 chars)')
10949
10971
  .option('--priority <prio>', 'optional priority: p0/high, p1/medium, p2/low (p3 = low)')
10950
- .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
10972
+ .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000)')
10951
10973
  .option('--code-file <path>', 'file containing the test code (≤ 350 KB)')
10952
- .option('--plan-from <path>', 'JSON file with the full FE test definition — projectId, type, name, planSteps[] all live in the file ' +
10953
- '(≤ 256 KB; mutually exclusive with --code-file). In this mode --project/--type/--name/--description/--priority/--step-timeout are ignored.')
10954
- .option('--plan-template', 'print a minimal valid plan-file skeleton to stdout and exit (pure-local: no network, no credentials, ' +
10955
- 'ignores every other flag). Pipe to a file and edit: `--plan-template > plan.json`.', false)
10956
- .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
10974
+ .option('--plan-from <path>', 'JSON file with the full FE test definition (≤ 256 KB; excludes --code-file); ' +
10975
+ '--project/--type/--name/--description/--priority/--step-timeout are ignored')
10976
+ .option('--plan-template', 'print a plan-file skeleton to stdout and exit (local; ignores every other flag)', false)
10977
+ .option('--run', 'after create, trigger the test', false)
10957
10978
  .option('--wait', 'with --run, poll until terminal status', false)
10958
- .option('--no-wait', 'detach without opening an automatic environment tunnel')
10959
- .option('--timeout <s>', 'with --run --wait, max seconds to wait')
10979
+ .option('--no-wait', 'with --run, detach: no waiting and no automatic tunnel (a loopback target is unreachable from the cloud)')
10980
+ .option('--timeout <s>', 'with --run --wait, max seconds to wait (1-3600; default 600, or 1200 through a tunnel)')
10960
10981
  .option('--target-url <url>', TARGET_URL_HELP)
10961
10982
  .option('--env <name>', 'with --run, select the named project environment; loopback URLs open a tunnel automatically')
10962
10983
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
10963
- .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
10964
- .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering on `test rerun` and `test run --all`.', (val, prev) => [...(prev ?? []), val], [])
10965
- .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Use to declare upstream producer dependencies.', (val, prev) => [...(prev ?? []), val], [])
10966
- .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
10984
+ .option('--idempotency-key <token>', 'idempotency token (1-256 ASCII chars; default: random UUID per invocation, pin one for safe retries)')
10985
+ .option('--produces <var>', 'BE only: variable this test captures (repeatable); orders waves in `test run --all`', (val, prev) => [...(prev ?? []), val], [])
10986
+ .option('--needs <var>', 'BE only: variable this test consumes (repeatable); declares the upstream producer', (val, prev) => [...(prev ?? []), val], [])
10987
+ .option('--category <str>', "BE only: test category; 'teardown' or 'cleanup' marks a final-wave cleanup test (BE-only flags with --type frontend exit 5)")
10967
10988
  .addHelpText('after', PLAN_TEMPLATE_HELP_TEXT)
10968
- .addHelpText('after', '\nBE dependency authoring:\n' +
10969
- ' --produces/--needs drive wave ordering on `test rerun` + `test run --all`.\n' +
10970
- ' --category teardown marks a final-wave cleanup test.\n' +
10971
- ' These flags are backend-only; supplying with --type frontend is an error (exit 5).')
10972
10989
  .addHelpText('after', GLOBAL_OPTS_HINT)
10973
10990
  .action(async (cmdOpts, command) => {
10974
10991
  if (cmdOpts.env !== undefined && cmdOpts.run !== true) {
@@ -11067,19 +11084,23 @@ export function createTestCommand(deps = {}) {
11067
11084
  });
11068
11085
  test
11069
11086
  .command('create-batch')
11070
- .description('Create multiple FE tests from a JSONL of plan specs (FE-only)')
11087
+ .summary('Create multiple FE tests from JSONL plan specs')
11088
+ .description('Create multiple FE tests from a JSONL of plan specs (FE-only).\n' +
11089
+ 'Each JSONL line (or --plan-from-dir file) is a `test create --plan-from` plan; see `test scaffold`.')
11071
11090
  .option('--plans <path>', 'JSONL file with one plan-from spec per line (≤ 50 specs, ≤ 5 MB)')
11072
11091
  .option('--plan-from-dir <dir>', 'directory of *.json plan files — each file is one plan spec (≤ 50 files, ≤ 5 MB total). Sorted by filename for determinism. Mutually exclusive with --plans.')
11073
11092
  .option('--run', 'after create, trigger each created test as a run', false)
11074
- .option('--max-concurrency <n>', 'with --run, max in-flight triggers at once (1-100, default: 50). The server caps run-triggers at 60/min/key; the CLI throttles to 50/min and auto-retries RATE_LIMITED responses client-side — raising this value does not bypass the server cap. ' +
11075
- `Separately, CLI run triggers are refused once ${SERVER_INFLIGHT_RUN_CAP} of your runs are already in flight (server default; the refusal reports your account's real cap). Runs from every source count toward it, and a large batch can reach it on its own, so anything already running makes later triggers exit 11 with details.reason "inflight_cap" — not auto-retried, runs have to finish first. With --wait a slot is held until each run finishes, so lowering this flag keeps fewer runs in flight; without --wait it only paces dispatch, and a smaller batch is the lever.`)
11093
+ .option('--max-concurrency <n>', 'with --run: max in-flight triggers (1-100, default 50; through a tunnel 1-10, default 5). ' +
11094
+ 'Triggers are throttled to 50/min (server cap 60/min/key) and retried on rate limits. ' +
11095
+ 'With --wait a slot is held until each run finishes; without --wait this only paces dispatch. Runs beyond what the account executes at once queue on the server.')
11076
11096
  .option('--wait', 'with --run, poll each run until terminal status', false)
11077
11097
  .option('--no-wait', 'detach without opening an automatic environment tunnel')
11078
11098
  .option('--timeout <s>', 'with --run --wait, per-run max seconds to wait (1-3600, default 600)')
11079
- .option('--target-url <url>', TARGET_URL_HELP)
11080
- .option('--env <name>', 'with --run, select the named project environment for each test; loopback URLs open a tunnel automatically')
11081
- .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
11082
- .option('--idempotency-key <token>', 'opaque idempotency token for the batch create (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
11099
+ .option('--target-url <url>', `with --run: ${TARGET_URL_HELP}`)
11100
+ .option('--env <name>', 'with --run, run each test in the named project environment; loopback URLs open a tunnel')
11101
+ .option('--skip-preflight', `with --run: ${SKIP_PREFLIGHT_HELP}`, false)
11102
+ .option('--idempotency-key <token>', 'idempotency token for the batch (1-256 ASCII chars; default: random UUID, pin one for safe retries)')
11103
+ .addHelpText('after', '\nExample:\n testsprite test create-batch --plans plans.jsonl --run --wait')
11083
11104
  .addHelpText('after', GLOBAL_OPTS_HINT)
11084
11105
  .action(async (cmdOpts, command) => {
11085
11106
  await runCreateBatch({
@@ -11099,14 +11120,15 @@ export function createTestCommand(deps = {}) {
11099
11120
  });
11100
11121
  test
11101
11122
  .command('scaffold')
11102
- .description('Emit a schema-correct starter test definition (frontend plan JSON by default, or a backend Python skeleton). Pure-local: no network, no credentials.')
11123
+ .summary('Emit a starter FE plan or BE skeleton (local)')
11124
+ .description('Emit a starter test definition (frontend plan JSON by default, or a backend Python skeleton). Local: no network or credentials.\n' +
11125
+ "The plan's projectId comes from TESTSPRITE_PROJECT_ID if set, else a placeholder to replace.")
11103
11126
  .option('--type <type>', 'frontend|backend (default: frontend)')
11104
11127
  .option('--out <path>', 'write the scaffold to a file instead of stdout')
11105
11128
  .option('--force', 'overwrite an existing --out file', false)
11106
11129
  .addHelpText('after', '\nExamples:\n' +
11107
- ' testsprite test scaffold > first-test.plan.json\n' +
11108
- ' testsprite test scaffold --type backend --out tests/health.py\n' +
11109
- ' testsprite test scaffold --out plan.json # then edit, and create with --plan-from plan.json')
11130
+ ' testsprite test scaffold --out plan.json # edit, then: test create --plan-from plan.json\n' +
11131
+ ' testsprite test scaffold --type backend --out health.py')
11110
11132
  .addHelpText('after', GLOBAL_OPTS_HINT)
11111
11133
  .action(async (cmdOpts, command) => {
11112
11134
  await runScaffold({
@@ -11118,7 +11140,7 @@ export function createTestCommand(deps = {}) {
11118
11140
  });
11119
11141
  test
11120
11142
  .command('open <test-id>')
11121
- .description('Open the test in the TestSprite dashboard: prints the deep-link URL, then spawns your default browser unless --no-browser.')
11143
+ .description('Open the test in the TestSprite dashboard (prints the URL, then opens your browser)')
11122
11144
  .option('--no-browser', 'print the URL only (SSH, headless, CI, agents)')
11123
11145
  .addHelpText('after', GLOBAL_OPTS_HINT)
11124
11146
  .action(async (testId, cmdOpts, command) => {
@@ -11131,9 +11153,9 @@ export function createTestCommand(deps = {}) {
11131
11153
  test
11132
11154
  .command('steps <test-id>')
11133
11155
  .description('List the steps of the latest run (use --run-id for a specific run)')
11134
- .option('--page-size <n>', 'service page size hint (1-100, default 25)')
11135
- .option('--max-items <n>', 'stop after this many items across auto-paged pages')
11136
- .option('--starting-token <token>', 'opaque cursor from a previous response')
11156
+ .option('--page-size <n>', 'fetch ONE page of N steps (1-100) and print the next token (default: follow every page); ignored with --run-id')
11157
+ .option('--max-items <n>', 'stop after this many items across auto-paged pages; ignored with --run-id')
11158
+ .option('--starting-token <token>', 'opaque cursor from a previous response; ignored with --run-id')
11137
11159
  .option('--run-id <id>', 'Show steps of the specified run instead of the latest run.')
11138
11160
  .addHelpText('after', GLOBAL_OPTS_HINT)
11139
11161
  .action(async (testId, cmdOpts, command) => {
@@ -11148,18 +11170,23 @@ export function createTestCommand(deps = {}) {
11148
11170
  });
11149
11171
  test
11150
11172
  .command('diff <run-a> <run-b>')
11151
- .description('Compare two runs and print what regressed: verdict, failureKind, failedStepIndex, per-step status flips, codeVersion drift. Exit 0 when verdicts match, 1 when they differ.')
11173
+ .summary('Compare two runs; exit 1 if their verdicts differ')
11174
+ .description('Compare two runs (run ids, see `test result --history`) and print what regressed: verdict, failureKind, failedStepIndex, per-step status flips, codeVersion drift. ' +
11175
+ 'Exit 0 when verdicts match, 1 when they differ, 3 auth, 4 run not found, 10 transport.')
11152
11176
  .addHelpText('after', GLOBAL_OPTS_HINT)
11153
11177
  .action(async (runA, runB, _cmdOpts, command) => {
11154
11178
  await runDiff({ ...resolveCommonOptions(command, deps.env), runA, runB }, deps);
11155
11179
  });
11156
11180
  test
11157
11181
  .command('lint')
11158
- .description('Validate plan/steps files offline with the same validators `create` runs, collecting EVERY problem. No network, no credentials. Exit 0 when all valid, 5 otherwise.')
11182
+ .summary('Validate plan/steps files offline')
11183
+ .description('Validate plan/steps files offline with the same validators `create` runs, reporting EVERY problem. No network or credentials. Exit 0 when valid, 5 otherwise.\n' +
11184
+ 'Pass exactly one input flag.')
11159
11185
  .option('--plan-from <file>', 'single plan JSON file')
11160
- .option('--plan-from-dir <dir>', 'directory of *.json plan files (each checked, all errors reported)')
11186
+ .option('--plan-from-dir <dir>', 'directory of *.json plan files (non-recursive)')
11161
11187
  .option('--plans <file>', 'JSONL file with one plan spec per line (each line checked)')
11162
11188
  .option('--steps <file>', 'plan-steps JSON file (the shape `test plan put` ingests)')
11189
+ .addHelpText('after', '\nExample:\n testsprite test lint --plan-from plan.json')
11163
11190
  .addHelpText('after', GLOBAL_OPTS_HINT)
11164
11191
  .action(async (cmdOpts, command) => {
11165
11192
  await runLint({
@@ -11172,10 +11199,11 @@ export function createTestCommand(deps = {}) {
11172
11199
  });
11173
11200
  test
11174
11201
  .command('result <test-id>')
11202
+ .summary('Get the latest result, or list prior runs (--history)')
11175
11203
  .description('Get the latest result for a test (default) or list prior runs (--history).\n' +
11176
- '\n--output json shape differs by mode:\n' +
11177
- ' (default) single CliLatestResult object\n' +
11178
- ' --history { runs: RunHistoryItem[], nextCursor: string|null, meta: RunHistoryMeta }\n' +
11204
+ '"with --history" flags are ignored without --history (--env is rejected, exit 5).\n' +
11205
+ '\n--output json: a single CliLatestResult, or with --history\n' +
11206
+ '{ runs: RunHistoryItem[], nextCursor: string|null, meta: RunHistoryMeta }.\n' +
11179
11207
  '\nPer-run detail: testsprite test wait <run-id>\n' +
11180
11208
  'Failure bundle: testsprite test artifact get <run-id>')
11181
11209
  .option('--include-analysis', 'attach the inline `analysis` block (rootCauseHypothesis, recommendedFixTarget, failureKind, snapshotId)', false)
@@ -11224,16 +11252,17 @@ export function createTestCommand(deps = {}) {
11224
11252
  });
11225
11253
  test
11226
11254
  .command('update <test-id>')
11227
- .description('Update test metadata — name, description, priority, step timeout')
11228
- .option('--name <name>', 'new human-readable test name')
11255
+ .summary('Update name, description, priority or step timeout')
11256
+ .description('Update test metadata — name, description, priority, step timeout. At least one field is required.')
11257
+ .option('--name <name>', 'new human-readable test name (≤ 200 chars)')
11229
11258
  .option('--description <text>', 'new human description (≤ 2000 chars)')
11230
11259
  .option('--priority <prio>', 'new priority: p0/high, p1/medium, p2/low (p3 = low)')
11231
- .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
11232
- .option('--clear-step-timeout', 'clear the per-test step timeout and restore execution engine defaults', false)
11260
+ .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000)')
11261
+ .option('--clear-step-timeout', 'clear the per-test step timeout, restoring the default (cannot combine with --step-timeout)', false)
11233
11262
  .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering.', (val, prev) => [...(prev ?? []), val], [])
11234
11263
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Declares an upstream producer dependency.', (val, prev) => [...(prev ?? []), val], [])
11235
11264
  .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
11236
- .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
11265
+ .option('--idempotency-key <token>', 'idempotency token (1-256 ASCII chars; default: random UUID per invocation, pin one for safe retries)')
11237
11266
  .addHelpText('after', GLOBAL_OPTS_HINT)
11238
11267
  .action(async (testId, cmdOpts, command) => {
11239
11268
  if (cmdOpts.stepTimeout !== undefined && cmdOpts.clearStepTimeout === true) {
@@ -11255,9 +11284,11 @@ export function createTestCommand(deps = {}) {
11255
11284
  });
11256
11285
  test
11257
11286
  .command('delete <test-id>')
11258
- .description('Permanently delete a test. Requires --confirm.')
11259
- .option('--confirm', 'required: explicit confirmation for the destructive operation', false)
11260
- .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
11287
+ .summary('Permanently delete a test (requires --confirm)')
11288
+ .description('Permanently delete a test. Requires --confirm.\n' +
11289
+ 'Also removes it from test lists and deletes its steps and stored code; cannot be undone. Exit 4 if it does not exist.')
11290
+ .option('--confirm', 'required: confirm the destructive operation', false)
11291
+ .option('--idempotency-key <token>', 'idempotency token (1-256 ASCII chars; default: random UUID per invocation, pin one for safe retries)')
11261
11292
  .addHelpText('after', GLOBAL_OPTS_HINT)
11262
11293
  .action(async (testId, cmdOpts, command) => {
11263
11294
  await runDelete({
@@ -11272,18 +11303,20 @@ export function createTestCommand(deps = {}) {
11272
11303
  // -------------------------------------------------------------------------
11273
11304
  test
11274
11305
  .command('delete-batch [test-ids...]')
11275
- .description('Permanently delete multiple tests in one command. Requires --confirm.\n' +
11276
- 'Use --all --project <id> to delete all tests in a project (optionally filtered by --status).\n' +
11277
- '\nPrints a per-test summary (Deleted N, Skipped M, Failed K) to stdout.\n' +
11306
+ .summary('Permanently delete several tests (requires --confirm)')
11307
+ .description('Permanently delete multiple tests. Requires --confirm. With --all --project <id>, deletes every test in the project (optionally filtered by --status).\n' +
11308
+ '\nPrints a per-test summary (Deleted N, Skipped M, Failed K); a not-found test counts as skipped.\n' +
11278
11309
  '\nExit codes:\n' +
11279
11310
  ' 0 all targeted tests deleted (or --dry-run)\n' +
11280
- ' 1 one or more deletions failed (server error)\n' +
11281
- ' 5 validation error (missing --confirm, missing --project with --all, etc.)\n' +
11282
- '\nNote: a 404 "not found" response is counted as skipped in the summary, not an error.')
11283
- .option('--confirm', 'required: explicit confirmation for the destructive operation', false)
11311
+ ' 1 one or more deletions failed\n' +
11312
+ ' 5 validation error (e.g. missing --confirm, or --all without --project)')
11313
+ .option('--confirm', 'required: confirm the destructive operation', false)
11284
11314
  .option('--all', 'delete all tests in the resolved project (requires --project)', false)
11285
- .option('--project <id>', 'project id (required with --all; returned by `testsprite project list`)')
11286
- .option('--status <list>', `with --all: only delete tests whose status matches these values (comma-separated; accepted: ${PUBLIC_STATUSES.join('|')})`)
11315
+ .option('--project <id>', 'project id (required with --all)')
11316
+ .option('--status <list>', `with --all: only delete tests whose latest status matches one of these values (comma-separated; accepted: ${RUN_STATUS_VALUES.join('|')}; not_run = never ran)`)
11317
+ .addHelpText('after', '\nExamples:\n' +
11318
+ ' testsprite test delete-batch <id> <id> --confirm\n' +
11319
+ ' testsprite test delete-batch --all --project <id> --status failed --confirm')
11287
11320
  .addHelpText('after', GLOBAL_OPTS_HINT)
11288
11321
  .action(async (testIdsArg, cmdOpts, command) => {
11289
11322
  await runDeleteBatch({
@@ -11300,8 +11333,9 @@ export function createTestCommand(deps = {}) {
11300
11333
  // -------------------------------------------------------------------------
11301
11334
  test
11302
11335
  .command('run [test-id...]')
11303
- .description('Trigger one or several test runs. Saved loopback environments open a tunnel automatically and wait for a verdict.\n' +
11304
- 'Use --all --project <id> for a wave-ordered batch run. Loopback environments share one tunnel.\n' +
11336
+ .summary('Run a test, or a whole project (--all)')
11337
+ .description('Trigger a run of one or more test cases. Saved loopback environments open a tunnel automatically and wait for a verdict.\n' +
11338
+ 'Pass several <test-id>s, or use --all --project <id> [--filter <substr>], for a batch run (ids are grouped per project and sent 50 per request). Loopback environments share one tunnel.\n' +
11305
11339
  '\nExit codes:\n' +
11306
11340
  ' 0 passed (or queued without --wait)\n' +
11307
11341
  ' 1 failed / blocked / cancelled\n' +
@@ -11312,85 +11346,64 @@ export function createTestCommand(deps = {}) {
11312
11346
  ' 7 timeout — resume with: testsprite test wait <run-id>, ' +
11313
11347
  'or stop it with: testsprite test cancel <run-id>\n' +
11314
11348
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
11315
- ' 11 rate limited — honor Retry-After, or the in-flight run cap was hit\n' +
11316
- ' (details.reason "inflight_cap"; see: testsprite test run --help)\n' +
11349
+ ' 11 rate limited — honor Retry-After\n' +
11350
+ ' 12 insufficient credits (non-retriable; top up)\n' +
11351
+ ' 13 feature gated / workspace paused\n' +
11317
11352
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
11318
11353
  '\nCtrl-C during an ordinary --wait detaches; an owned tunnel cancels unfinished runs by default.\n' +
11319
11354
  'Stop a detached run with: testsprite test cancel <run-id>\n' +
11320
- 'Local environments: dev servers can take a minute per page through the tunnel.\n' +
11321
- 'For a heavy dev server, test a built server: npm run build, then your framework preview/start command.')
11355
+ 'Dev servers can take a minute per page through a tunnel; prefer a built server (npm run build, then start).')
11322
11356
  .option('--target-url <url>', TARGET_URL_HELP)
11323
11357
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
11324
- .option('--local <port>', 'run against an app on THIS machine, reached through a TestSprite tunnel. The test runner ' +
11325
- 'navigates to http://localhost:<port> and its traffic is proxied back to you for as long ' +
11326
- 'as this command runs. Implies --wait (the tunnel closes when the command exits, so a ' +
11327
- 'detached run could not finish). Frontend tests ' +
11328
- 'only; a matching saved environment keeps its host spelling; several ids or --all share one tunnel (5 concurrent by default, at most 10). ' +
11329
- 'Before anything is minted or billed, the port is probed and a dead one is refused.')
11330
- .option('--local-host <host>', `with --local, override which loopback address to name in the run's target URL — one of ` +
11331
- `${LOOPBACK_HOSTS.join(', ')} (default: saved matching host, else ${DEFAULT_LOCAL_HOST}). Use localhost if your app ` +
11332
- `only answers on that name, or ::1 for an IPv6-only listener.`)
11333
- .option('--tunnel-client <id>', 'for a loopback environment or --local, attach to a tunnel already running under `testsprite tunnel start` instead ' +
11334
- 'of opening a new one. The id is the non-secret handle that command prints; the tunnel ' +
11335
- 'stays owned by that process and is not closed when this run or batch finishes.')
11336
- .option('--no-cancel-on-interrupt', 'with a tunnel, skip automatic cancellation when an owned tunnel is about to close or a ' +
11337
- "borrowed tunnel's owner disappears. An ordinary interrupt of a borrowed run never " +
11338
- 'cancels it because its tunnel remains alive.')
11339
- .option('--env <name>', 'run against the named project environment — its test-account credentials, auto-auth and ' +
11340
- 'OTP settings (names: `testsprite project env list <project-id>`). A loopback environment opens a tunnel automatically. The run opens ' +
11341
- "that environment's URL. Omit --env to keep using " +
11342
- "the project's default environment. Also applies with --all.")
11358
+ .option('--local <port>', 'run against an app on THIS machine through a TestSprite tunnel (the runner opens ' +
11359
+ 'http://localhost:<port>). Implies --wait. Frontend tests only; several ids or --all share one ' +
11360
+ 'tunnel (5 concurrent, max 10). A dead port is refused before anything is billed.')
11361
+ .option('--local-host <host>', `with --local, loopback address in the target URL: ${LOOPBACK_HOSTS.join(', ')} ` +
11362
+ `(default: saved matching host, else ${DEFAULT_LOCAL_HOST}). Use localhost if your app only answers on that name, ::1 for IPv6-only.`)
11363
+ .option('--tunnel-client <id>', 'for a loopback environment or --local, attach to a tunnel already running under `testsprite tunnel start` ' +
11364
+ '(use the id it prints) instead of opening one; that process keeps the tunnel open afterwards.')
11365
+ .option('--no-cancel-on-interrupt', 'with a tunnel, do not auto-cancel runs when an owned tunnel closes or a ' +
11366
+ "borrowed tunnel's owner disappears")
11367
+ .option('--env <name>', 'run against the named project environment — its credentials, auto-auth and OTP settings ' +
11368
+ '(see `testsprite project env list <project-id>`); a loopback one opens a tunnel. ' +
11369
+ "Default: the project's default environment. Also applies with --all.")
11343
11370
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
11344
11371
  .option('--no-wait', 'detach without opening an automatic environment tunnel')
11345
11372
  .option('--timeout <s>', 'with --wait, max seconds per run (1–3600; default 600, or 1200 through a tunnel)')
11346
- .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars); local batches append each test id. Auto-generated keys print to stderr in JSON, verbose or debug mode.')
11347
- .option('--all', 'run all tests in the project (wave-ordered fresh run; uses --project or TESTSPRITE_PROJECT_ID). Mutually exclusive with <test-id>.', false)
11348
- .option('--project <id>', 'project id (with --all, overrides TESTSPRITE_PROJECT_ID; returned by `testsprite project list`)')
11373
+ .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars); local batches append each test id')
11374
+ .option('--all', 'run all tests in the project in wave order (uses --project or TESTSPRITE_PROJECT_ID); excludes <test-id>', false)
11375
+ .option('--project <id>', 'project id for --all (overrides TESTSPRITE_PROJECT_ID)')
11349
11376
  .option('--filter <substr>', 'with --all: only run tests whose name contains this substring (case-insensitive)')
11350
- .option('--max-concurrency <n>', `with a tunnel, max runs in flight through one tunnel (1-10, default 5); with --all --wait without a tunnel, max polls (1-100, default ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
11377
+ .option('--status <list>', 'with --all: only run tests whose latest status matches one of these values (comma-separated; accepted: passed|failed|blocked|cancelled|not_run; not_run = never ran); --env only picks where to run')
11378
+ .option('--max-concurrency <n>', `with a tunnel, max runs in flight through one tunnel (1-10, default 5); with --all or several ids and --wait without a tunnel, max polls (1-100, default ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
11351
11379
  .option('--report <format>', 'with a --wait batch (--all or several ids): write a JUnit XML sidecar report after polling (accepted: junit)')
11352
11380
  .option('--report-file <path>', 'output path for --report (atomic write)')
11353
11381
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
11354
- .option('--gh-output', 'with --wait (single test or batch): emit GitHub-native output (::error:: annotations for failed/timed-out runs, ::warning:: for never-dispatched tests; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
11355
- .option('--summary-file <path>', 'with --wait (single test or batch): also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
11356
- .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')
11357
- .option('--no-auto-heal', 'ask the server to replay stored test code instead of letting the agent heal it. ' +
11358
- 'The server controls whether fresh runs heal drifted generated code by default; when ' +
11359
- 'healing is enabled, the agent re-authors stale code rather than replaying a script ' +
11360
- 'that can only fail. Use this flag to request a strict replay for a regression gate ' +
11361
- 'or a reproduction you are bisecting. Code you wrote yourself is never re-authored. ' +
11362
- 'Where stored-code replay is unavailable, the server rejects this flag. Where replay ' +
11363
- 'is available but a test has no replayable stored code, the server may refuse the run ' +
11364
- 'instead of authoring it. An older server may ignore the flag; the CLI prints an ' +
11365
- '[advisory] when the server reports that the opt-out did not take.')
11366
- .addHelpText('after', '\nDependency-aware fresh run:\n' +
11367
- ' testsprite test run --all --project <id> run all project tests in wave order\n' +
11368
- ' TESTSPRITE_PROJECT_ID=<id> testsprite test run --all use env default project\n' +
11369
- ' testsprite test run <id> <id> --local 3000 several local tests, one tunnel\n' +
11370
- ' testsprite test run --all --project <id> --local 3000 all frontend tests, one tunnel\n' +
11371
- ' testsprite test run <id> <id> --local 3000 --max-concurrency 3\n' +
11372
- ' testsprite test run --all --filter <substr> name-glob subset (uses --project/env)\n' +
11373
- ' testsprite test run --all --wait --report junit --report-file ./results.xml\n' +
11374
- ' project id precedence: --project wins over TESTSPRITE_PROJECT_ID\n' +
11375
- '\nBE tests can declare --produces/--needs at create time to drive wave ordering\n' +
11376
- '(see `testsprite test create --help` for details).\n' +
11377
- '\nFrontend tests: the current unified engine runs FE tests too (they are billed\n' +
11378
- 'like any run). On the legacy backend-only engine FE tests cannot run — they are\n' +
11379
- "reported under skippedFrontend with an advisory; run those with 'test run <id>'.\n" +
11380
- '\nConcurrency limits:\n' +
11381
- ` - CLI run triggers are refused once ${SERVER_INFLIGHT_RUN_CAP} of your runs are already in\n` +
11382
- ' flight (server default; the refusal reports your real cap). Runs from every\n' +
11383
- ' source count toward it (CLI, portal, schedules, CI), but only CLI triggers\n' +
11384
- ' are refused on it.\n' +
11385
- ' At the cap this command accepts nothing and returns every id deferred,\n' +
11386
- ' which exits 7; resume with the printed ids once runs finish. (A single\n' +
11387
- ' `test run <id>` over the cap exits 11 with details.reason "inflight_cap",\n' +
11388
- ' and is not auto-retried — runs have to finish first.)\n' +
11389
- ' Poll what is already running with: testsprite test wait <run-id...>\n' +
11390
- ' - Separately, run triggers are throttled per minute. That one does clear on\n' +
11391
- ' its own and is retried for you.\n' +
11392
- ' - --max-concurrency here bounds the --wait poll fan-out, not dispatch, so it\n' +
11393
- ' has no effect on the cap. A smaller batch does.')
11382
+ .option('--gh-output', 'with --wait: emit GitHub annotations (::error:: failed/timed-out, ::warning:: never dispatched) and a job-summary table when $GITHUB_STEP_SUMMARY is set; auto-enabled when GITHUB_ACTIONS=true')
11383
+ .option('--summary-file <path>', 'with --wait: also write summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
11384
+ .option('--allow-empty', 'with --all: exit 0 when ZERO test cases are dispatched (default: exit 5, so an empty run is not a CI false-green)')
11385
+ .option('--no-auto-heal', 'request strict replay of stored test code instead of letting the agent heal drifted ' +
11386
+ 'generated code (the server decides the default); use for regression gates and bisects. ' +
11387
+ 'Code you wrote yourself is never re-authored. The server rejects the flag where replay is ' +
11388
+ 'unavailable and may refuse a test with no replayable code; the CLI prints an [advisory] ' +
11389
+ 'if the opt-out did not take.')
11390
+ .option('--skip-dependencies', 'Backend test cases only: run without the test cases they depend on', false)
11391
+ .addHelpText('after', '\nExamples:\n' +
11392
+ ' testsprite test run --all --project <id> all test cases in the project, in wave order\n' +
11393
+ ' testsprite test run <id> <id> <id> several test cases in one run (any number of ids; sent 50 per request)\n' +
11394
+ ' testsprite test run <id> <id> --local 3000 several local test cases, one tunnel\n' +
11395
+ ' testsprite test run --all --status failed --env staging test cases whose latest status is failed, run in staging\n' +
11396
+ ' testsprite test run --all --filter <substr> --wait --report junit --report-file ./results.xml\n' +
11397
+ '\nOn the legacy backend-only engine, FE test cases are skipped (reported under skippedFrontend);\n' +
11398
+ 'run them with `test run <id>`. BE test cases can declare --produces/--needs at create time to order waves.\n' +
11399
+ '\nQueueing and limits:\n' +
11400
+ ' - Each request starts one run; its results show queued until they start,\n' +
11401
+ ' as in the Portal.\n' +
11402
+ ' - A test case that already has a run in flight is a conflict (exit 6), not queued.\n' +
11403
+ ' - Run triggers are limited to 60 per minute per API key; that limit clears on\n' +
11404
+ ' its own and is retried for you. An older backend may still answer with\n' +
11405
+ ' deferred ids: they are reported, not resent, and exit 7.\n' +
11406
+ ' - --max-concurrency here bounds the --wait poll fan-out, not dispatch.')
11394
11407
  .addHelpText('after', GLOBAL_OPTS_HINT)
11395
11408
  .action(async (testIdArgs, cmdOpts, command) => {
11396
11409
  // A literal `testsprite test run list` is someone guessing at a
@@ -11420,6 +11433,12 @@ export function createTestCommand(deps = {}) {
11420
11433
  if (cmdOpts.filter !== undefined && cmdOpts.filter !== '' && !isAll) {
11421
11434
  throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests run). Remove --filter, or add --all with --project <id> or TESTSPRITE_PROJECT_ID.');
11422
11435
  }
11436
+ // --status narrows the --all set exactly as --filter does, with the same
11437
+ // silent-ignore failure mode without --all.
11438
+ if (cmdOpts.status !== undefined && !isAll) {
11439
+ throw localValidationError('status', '--status only applies with --all (it narrows which project tests run). Remove --status, or add --all with --project <id> or TESTSPRITE_PROJECT_ID.');
11440
+ }
11441
+ validateStatusSelector(cmdOpts.status);
11423
11442
  // --local resolution. Every one of these refuses BEFORE any network
11424
11443
  // call, which is the contract `--local` is sold on: a mistake in the
11425
11444
  // invocation must never reach a run row, a credit spend, or a minted
@@ -11437,8 +11456,6 @@ export function createTestCommand(deps = {}) {
11437
11456
  !explicitLoopbackTarget &&
11438
11457
  ((command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false) ||
11439
11458
  cmdOpts.targetUrl !== undefined)) {
11440
- if (!isAll && testIdArgs.length >= 2)
11441
- severalIdsWithoutTunnel();
11442
11459
  assertNoTunnelOptions({
11443
11460
  tunnelClientId: cmdOpts.tunnelClient,
11444
11461
  cancelOnInterrupt: cmdOpts.cancelOnInterrupt,
@@ -11513,6 +11530,7 @@ export function createTestCommand(deps = {}) {
11513
11530
  ...resolveCommonOptions(command, deps.env),
11514
11531
  projectId,
11515
11532
  nameFilter: cmdOpts.filter,
11533
+ statusFilter: cmdOpts.status,
11516
11534
  wait: effectiveWait,
11517
11535
  noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
11518
11536
  concurrencyIsDefault: cmdOpts.maxConcurrency === undefined,
@@ -11540,6 +11558,7 @@ export function createTestCommand(deps = {}) {
11540
11558
  ? { targetUrl: cmdOpts.targetUrl }
11541
11559
  : {}),
11542
11560
  skipPreflight: cmdOpts.skipPreflight === true,
11561
+ ...(cmdOpts.skipDependencies === true ? { skipDependencies: true } : {}),
11543
11562
  }, deps);
11544
11563
  return;
11545
11564
  }
@@ -11570,11 +11589,13 @@ export function createTestCommand(deps = {}) {
11570
11589
  all: isAll,
11571
11590
  projectId: cmdOpts.project,
11572
11591
  nameFilter: cmdOpts.filter,
11592
+ statusFilter: cmdOpts.status,
11573
11593
  localPort,
11574
11594
  localHost,
11575
11595
  targetUrl: cmdOpts.targetUrl,
11576
11596
  noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
11577
11597
  concurrencyIsDefault: cmdOpts.maxConcurrency === undefined,
11598
+ timeoutIsDefault: cmdOpts.timeout === undefined,
11578
11599
  skipPreflight: cmdOpts.skipPreflight === true,
11579
11600
  tunnelClientId: cmdOpts.tunnelClient,
11580
11601
  cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
@@ -11591,6 +11612,7 @@ export function createTestCommand(deps = {}) {
11591
11612
  allowEmpty: cmdOpts.allowEmpty === true,
11592
11613
  ...(cmdOpts.autoHeal === false ? { autoHeal: false } : {}),
11593
11614
  environment: cmdOpts.env,
11615
+ ...(cmdOpts.skipDependencies === true ? { skipDependencies: true } : {}),
11594
11616
  }, deps);
11595
11617
  return;
11596
11618
  }
@@ -11617,28 +11639,25 @@ export function createTestCommand(deps = {}) {
11617
11639
  // See the matching comment on the --all path above.
11618
11640
  ...(cmdOpts.autoHeal === false ? { autoHeal: false } : {}),
11619
11641
  environment: cmdOpts.env,
11642
+ ...(cmdOpts.skipDependencies === true ? { skipDependencies: true } : {}),
11620
11643
  }, deps);
11621
11644
  });
11622
11645
  test
11623
11646
  .command('wait <run-id...>')
11647
+ .summary('Wait for one or more runs to finish')
11624
11648
  .description('Wait for one or more runs to reach a terminal status.\n' +
11625
- '\nWith several run-ids the runs are polled concurrently under one shared\n' +
11626
- '--timeout and a {results, summary} envelope is printed (worst status wins\n' +
11627
- 'the exit code), so every re-attach hint the CLI prints can be pasted as\n' +
11628
- 'ONE command.\n' +
11649
+ '\nSeveral run-ids are polled concurrently under one shared --timeout and a\n' +
11650
+ '{results, summary} envelope is printed (worst status wins the exit code).\n' +
11629
11651
  '\nExit codes:\n' +
11630
11652
  ' 0 passed\n' +
11631
11653
  ' 1 failed / blocked / cancelled\n' +
11632
11654
  ' 3 auth error\n' +
11633
- ' 4 run not found (single run-id; with several ids a per-member poll error\n' +
11655
+ ' 4 run not found (single run-id; with several, a per-member poll error\n' +
11634
11656
  ' is recorded as error:<CODE> in its row and folded into exit 7)\n' +
11635
11657
  ' 7 timeout or per-member poll error — resume with: testsprite test wait <run-id...>\n' +
11636
11658
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
11637
- ' 11 rate limited, and nothing else went wrong — polls are retried\n' +
11638
- ' automatically honoring Retry-After first, so this means the throttle\n' +
11639
- ' outlasted that budget while the runs were still fine. Back off, then\n' +
11640
- ' re-attach with test wait. (A throttle that instead consumes the whole\n' +
11641
- ' --timeout reports 7, and any real timeout or failure keeps 7 / 1.)\n' +
11659
+ ' 11 rate limited past the automatic Retry-After retries, runs still fine — back off,\n' +
11660
+ ' then re-attach (a throttle that consumes the whole --timeout reports 7)\n' +
11642
11661
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
11643
11662
  '\nCtrl-C detaches only (the run keeps executing and billing); stop it for\n' +
11644
11663
  'real with: testsprite test cancel <run-id...>')
@@ -11671,9 +11690,11 @@ export function createTestCommand(deps = {}) {
11671
11690
  // M3.4 piece-3 — `test rerun`
11672
11691
  // -------------------------------------------------------------------------
11673
11692
  test
11674
- .command('rerun [test-ids...]')
11675
- .description('Re-execute a test (or multiple) as a replay — FE replays the saved script, BE re-runs the dependency closure. ' +
11676
- 'Billed the same as a fresh run: 0.5 credits per FE rerun / 0.2 credits per BE rerun (legacy V2 accounts: FE rerun remains free).\n' +
11693
+ .command('rerun [test-ids...]', { hidden: true })
11694
+ .description('[deprecated] Use `testsprite test run` instead; removed in ' +
11695
+ `${REMOVED_IN}. ` +
11696
+ 'Re-execute a test case (or several) as a replay — FE replays the saved script, BE re-runs the dependency closure. ' +
11697
+ 'Billed like a fresh run on V3 workspaces (0.5 credits per FE case, 0.2 per BE case). Legacy V2 accounts: reruns are free.\n' +
11677
11698
  '\nExit codes:\n' +
11678
11699
  ' 0 passed (or queued without --wait)\n' +
11679
11700
  ' 1 failed / blocked / cancelled\n' +
@@ -11688,7 +11709,7 @@ export function createTestCommand(deps = {}) {
11688
11709
  '\nCtrl-C during --wait detaches only (the run keeps executing and billing);\n' +
11689
11710
  'stop it for real with: testsprite test cancel <run-id>')
11690
11711
  .option('--all', 'rerun all tests in the resolved project (requires --project)', false)
11691
- .option('--project <id>', 'project id (required with --all; returned by `testsprite project list`)')
11712
+ .option('--project <id>', 'project id (required with --all)')
11692
11713
  .option('--skip-terminal', 'with --all: skip tests already in a terminal status (passed|failed|blocked|cancelled)', false)
11693
11714
  .option('--status <list>', `with --all: only dispatch tests whose status matches one of these values (comma-separated; accepted: ${PUBLIC_STATUSES.join('|')})`)
11694
11715
  .option('--filter <substr>', 'with --all: only rerun tests whose name contains this substring (case-insensitive)')
@@ -11696,39 +11717,34 @@ export function createTestCommand(deps = {}) {
11696
11717
  .option('--no-wait', 'detach without opening an automatic environment tunnel')
11697
11718
  .option('--skip-preflight', 'skip the loopback port probe before opening a tunnel')
11698
11719
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
11699
- .option('--no-auto-heal', 'replay the saved script verbatim instead of letting the agent repair it (default: ' +
11700
- 'auto-heal is ON for FE reruns). When heal engages, the agent re-authors the test and ' +
11701
- 'the new code replaces the stored version. Ignored for backend reruns. ' +
11702
- 'Costs: `testsprite usage`.')
11720
+ .option('--no-auto-heal', 'replay the saved script verbatim instead of letting the agent repair it (default: auto-heal ' +
11721
+ 'is ON for FE reruns; a heal replaces the stored code). Ignored for backend reruns.')
11703
11722
  .option('--skip-dependencies', 'BE only: rerun only the named test without expanding the producer/teardown closure', false)
11704
- .option('--env <name>', 'replay against the named project environment — its test-account credentials, auto-auth and ' +
11705
- 'OTP settings (names: `testsprite project env list <project-id>`). Omit to keep using the ' +
11706
- "project's default environment. Loopback URLs open a tunnel automatically. Applies to every test of a batch rerun.")
11723
+ .option('--env <name>', 'replay against the named project environment — its credentials, auto-auth and OTP settings ' +
11724
+ '(see `testsprite project env list <project-id>`); loopback URLs open a tunnel. ' +
11725
+ "Default: the project's default environment. Applies to every test of a batch.")
11707
11726
  .option('--max-concurrency <n>', `with a tunnel, max runs in flight (1-10, default 5); otherwise with --wait, max polls (1-100, default ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
11708
- .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --verbose if auto-generated.')
11727
+ .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars)')
11709
11728
  .option('--report <format>', 'with batch --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
11710
11729
  .option('--report-file <path>', 'output path for --report (atomic write)')
11711
11730
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
11712
- .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')
11713
- .option('--summary-file <path>', 'with batch --wait: also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
11714
- .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')
11731
+ .option('--gh-output', 'with batch --wait: emit GitHub annotations (::error:: failed/timed-out, ::warning:: never dispatched) and a job-summary table when $GITHUB_STEP_SUMMARY is set; auto-enabled when GITHUB_ACTIONS=true')
11732
+ .option('--summary-file <path>', 'with batch --wait: also write summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
11733
+ .option('--allow-empty', 'with --all: exit 0 when no tests match (default: exit 5, so an empty rerun is not a CI false-green)')
11715
11734
  .addHelpText('after', '\nNotes:\n' +
11716
- ' • Frontend reruns default to auto-heal; the server controls the default for a\n' +
11717
- ' fresh `test run`. Use --no-auto-heal to request a strict replay where supported.\n' +
11718
- ' • What still differs: rerun replays a SAVED run/script, so one has to exist;\n' +
11719
- ' `test run` starts fresh. A BE rerun also expands the dependency closure.\n' +
11720
- ' • Under --wait the per-request HTTP timeout is auto-raised to cover --timeout so a\n' +
11721
- ' slow trigger/poll under load is not cut at the 120s default (see --request-timeout).\n' +
11722
- ' • Batch --wait: rate-deferred tests appear in `deferred[]` and `summary.deferred`,\n' +
11723
- ' and force a non-zero exit — they are NOT counted in `summary.total` (dispatched only).\n' +
11724
- ' • rerun gets no server echo of the effective auto-heal decision, so a dropped\n' +
11725
- ' opt-out cannot be detected here the way `test run --no-auto-heal` detects it.')
11726
- .addHelpText('after', '\nDry-run shape notes:\n' +
11727
- ' • --dry-run shows the BE rerun wire shape (includes `closure{}`); FE rerun responses\n' +
11728
- ' omit `closure` (or return it as null) since there is no dependency expansion.\n' +
11729
- ' • `autoHeal` defaults true for FE reruns; BE reruns ignore the field entirely.')
11735
+ ' • A rerun replays a SAVED run/script, so one must exist; `test run` starts fresh.\n' +
11736
+ ' A BE rerun also expands the dependency closure.\n' +
11737
+ ' • Batch --wait: rate-deferred tests appear in `deferred[]` / `summary.deferred` and force a\n' +
11738
+ ' non-zero exit; they are not counted in `summary.total`.')
11730
11739
  .addHelpText('after', GLOBAL_OPTS_HINT)
11731
11740
  .action(async (testIdsArg, cmdOpts, command) => {
11741
+ // First statement, before any validation, so the notice precedes a usage error and
11742
+ // appears exactly once per invocation (also under --dry-run and in both output modes).
11743
+ const rerunDeprecation = TEST_RERUN_DEPRECATION;
11744
+ emitDeprecationEntry(rerunDeprecation, deps.stderr, 'Use `testsprite test run` with the same ids and flags, except: ' +
11745
+ '--skip-terminal becomes --status not_run, and --status takes only ' +
11746
+ `${RUN_STATUS_VALUES.join(', ')}.`);
11747
+ const rerunDeps = { ...deps, deprecations: [rerunDeprecation] };
11732
11748
  // Commander's `--no-auto-heal` pattern makes `cmdOpts.autoHeal` default
11733
11749
  // `true` (unchanged by the user) and `false` when the user passes
11734
11750
  // `--no-auto-heal`. There is no explicit `--auto-heal` flag, so
@@ -11782,15 +11798,17 @@ export function createTestCommand(deps = {}) {
11782
11798
  ghOutput: cmdOpts.ghOutput === true,
11783
11799
  summaryFile: cmdOpts.summaryFile,
11784
11800
  allowEmpty: cmdOpts.allowEmpty === true,
11785
- }, deps);
11801
+ }, rerunDeps);
11786
11802
  });
11787
11803
  // -------------------------------------------------------------------------
11788
11804
  // `test flaky` — repeat-run flaky-test detector
11789
11805
  // -------------------------------------------------------------------------
11790
11806
  test
11791
- .command('flaky <test-id>')
11792
- .description('Repeatedly replay a test to measure stability and surface flakiness.\n' +
11793
- 'Replays run with auto-heal OFF (strict verbatim) so healed drift cannot mask nondeterministic pass/fail.\n' +
11807
+ .command('flaky <test-id>', { hidden: true })
11808
+ .description('[deprecated] No replacement; run `testsprite test run <test-id>` again to sample a test case; ' +
11809
+ `removed in ${REMOVED_IN}.\n` +
11810
+ 'Repeatedly replay a test case to measure stability.\n' +
11811
+ 'Replays run with auto-heal OFF (strict verbatim) so healing cannot mask a flaky pass/fail.\n' +
11794
11812
  '\nExit codes:\n' +
11795
11813
  ' 0 stable (every attempt passed)\n' +
11796
11814
  ' 1 flaky or failing (at least one attempt did not pass)\n' +
@@ -11801,23 +11819,21 @@ export function createTestCommand(deps = {}) {
11801
11819
  .option('--until-fail', 'stop at the first non-passing attempt (fast "is it flaky at all?" check)', false)
11802
11820
  .option('--timeout <s>', `per-attempt max seconds to wait (1-${MAX_RUN_TIMEOUT_SECONDS}, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
11803
11821
  .addHelpText('after', '\nNotes:\n' +
11804
- ' • Each replay is billed as a rerun — 0.5 credits for a frontend replay (verbatim\n' +
11805
- ' script), 0.2 credits for a backend replay (re-runs the dependency closure) —\n' +
11806
- ' same price as a fresh run, so `--runs N` costs roughly N×0.5 credits for a\n' +
11807
- ' frontend test (legacy V2 accounts: FE rerun remains free). A one-line advisory\n' +
11808
- ' is printed before a backend replay.\n' +
11809
- ' • Replays use auto-heal OFF so a flaky test is not silently "healed" into a pass;\n' +
11810
- ' this measures replay stability of the saved script against the configured URL.\n' +
11811
- ' • `--output json` emits a machine-readable stability report for CI gating.')
11822
+ ' • Each replay is billed as a rerun (0.5 credits per FE replay, 0.2 per BE replay), so\n' +
11823
+ ' `--runs N` costs about N×0.5 for a frontend test (legacy V2 accounts: FE rerun is free).\n' +
11824
+ ' • `--output json` emits a stability report for CI gating.')
11812
11825
  .addHelpText('after', GLOBAL_OPTS_HINT)
11813
11826
  .action(async (testIdArg, cmdOpts, command) => {
11827
+ const flakyDeprecation = TEST_FLAKY_DEPRECATION;
11828
+ emitDeprecationEntry(flakyDeprecation, deps.stderr, `To sample a test again, run \`testsprite test run ${testIdArg}\`.`, true);
11829
+ const flakyDeps = { ...deps, deprecations: [flakyDeprecation] };
11814
11830
  await runFlaky({
11815
11831
  ...resolveCommonOptions(command, deps.env),
11816
11832
  testId: testIdArg,
11817
11833
  runs: parseNumericFlag(cmdOpts.runs, 'runs') ?? DEFAULT_FLAKY_RUNS,
11818
11834
  untilFail: cmdOpts.untilFail === true,
11819
11835
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
11820
- }, deps);
11836
+ }, flakyDeps);
11821
11837
  });
11822
11838
  test.addCommand(createTestCodeCommand(deps));
11823
11839
  test.addCommand(createTestPlanCommand(deps));
@@ -12044,6 +12060,166 @@ function validateStatusFilter(raw) {
12044
12060
  }
12045
12061
  }
12046
12062
  }
12063
+ /**
12064
+ * `--status` for `test list` and `test delete-batch`: the five latest-status
12065
+ * values of `test run`, where `not_run` is the test cases that never ran. The
12066
+ * older public values still work but are no longer advertised.
12067
+ */
12068
+ function validateListStatusFilter(raw) {
12069
+ if (raw === undefined || raw === '')
12070
+ return;
12071
+ for (const token of raw.split(',')) {
12072
+ const trimmed = token.trim();
12073
+ if (trimmed === '' || trimmed === 'not_run')
12074
+ continue;
12075
+ if (!PUBLIC_STATUSES.includes(trimmed)) {
12076
+ throw localValidationError('status', `must be one of: ${RUN_STATUS_VALUES.join(', ')} (comma-separated for multiple)`, [...RUN_STATUS_VALUES]);
12077
+ }
12078
+ }
12079
+ }
12080
+ /**
12081
+ * A `--status` list with `not_run` spelled as the server's draft and ready.
12082
+ * A list without `not_run` is returned unchanged.
12083
+ */
12084
+ function expandNotRun(raw) {
12085
+ const tokens = raw.split(',').map(s => s.trim());
12086
+ if (!tokens.includes('not_run'))
12087
+ return raw;
12088
+ const expanded = tokens
12089
+ .filter(s => s.length > 0)
12090
+ .flatMap(s => (s === 'not_run' ? ['draft', 'ready'] : [s]));
12091
+ return [...new Set(expanded)].join(',');
12092
+ }
12093
+ /**
12094
+ * Strict `--status` selector for the run family. `validateStatusFilter` reads
12095
+ * an empty value as "no filter", which is right for `test list`, but a run
12096
+ * selector that selects nothing would silently dispatch the whole project (or
12097
+ * filter every test out), so an empty or commas-only value is a usage error.
12098
+ */
12099
+ function assertStatusSelectorNotEmpty(raw, accepted = PUBLIC_STATUSES) {
12100
+ if (raw === undefined)
12101
+ return;
12102
+ if (raw.split(',').every(token => token.trim() === '')) {
12103
+ throw localValidationError('status', `--status needs at least one status (accepted: ${accepted.join(', ')}); remove --status to select every test`, [...accepted]);
12104
+ }
12105
+ }
12106
+ /**
12107
+ * `test run --status` selects test cases by the status of their latest result.
12108
+ * `not_run` is the test cases that never produced one (draft or ready).
12109
+ */
12110
+ const RUN_STATUS_VALUES = ['passed', 'failed', 'blocked', 'cancelled', 'not_run'];
12111
+ function validateStatusSelector(raw) {
12112
+ assertStatusSelectorNotEmpty(raw, RUN_STATUS_VALUES);
12113
+ if (raw === undefined)
12114
+ return;
12115
+ for (const token of raw.split(',')) {
12116
+ const trimmed = token.trim();
12117
+ if (trimmed === '')
12118
+ continue;
12119
+ if (!RUN_STATUS_VALUES.includes(trimmed)) {
12120
+ throw localValidationError('status', `--status selects test cases by the status of their latest result, so '${trimmed}' is not accepted; ` +
12121
+ `use one of: ${RUN_STATUS_VALUES.join(', ')} (comma-separated for multiple). ` +
12122
+ 'Use not_run for test cases that never ran; queued and running are not a latest status.', [...RUN_STATUS_VALUES]);
12123
+ }
12124
+ }
12125
+ }
12126
+ /** Add the available environment names to an unknown-environment rejection. */
12127
+ function withUnknownEnvironmentHint(err, environment) {
12128
+ if (err instanceof ApiError &&
12129
+ err.code === 'VALIDATION_ERROR' &&
12130
+ err.getDetail('field') === 'environment' &&
12131
+ Array.isArray(err.getDetail('available')) &&
12132
+ environment !== undefined) {
12133
+ const available = err.getDetail('available').filter((name) => typeof name === 'string');
12134
+ if (available.length > 0 && !err.nextAction.includes(available.join(', '))) {
12135
+ const hint = `Flag \`--env\` is invalid: unknown environment '${environment}'; use one of: ${available.join(', ')}.`;
12136
+ return new ApiError({
12137
+ code: err.code,
12138
+ message: err.message,
12139
+ nextAction: err.nextAction ? `${hint} ${err.nextAction}` : hint,
12140
+ requestId: err.requestId,
12141
+ details: err.details,
12142
+ }, err.httpStatus, err.retryAfterMs);
12143
+ }
12144
+ }
12145
+ return err;
12146
+ }
12147
+ /**
12148
+ * An older server ignores `environment` and returns unfiltered statuses;
12149
+ * acting on them would look like an environment-scoped answer.
12150
+ */
12151
+ function assertEnvironmentStatusesPresent(items, copy) {
12152
+ if (items.length > 0 &&
12153
+ !items.some(test => test.headlineEnvironment !== undefined || test.statusByEnvironment !== undefined)) {
12154
+ throw ApiError.fromEnvelope({
12155
+ error: {
12156
+ code: 'UNSUPPORTED',
12157
+ message: copy.message,
12158
+ nextAction: copy.nextAction,
12159
+ requestId: 'local',
12160
+ details: {},
12161
+ },
12162
+ });
12163
+ }
12164
+ }
12165
+ /**
12166
+ * Every test of one project, narrowed client-side by `--skip-terminal`,
12167
+ * `--status` and `--filter` in that order. The status of a test case is its
12168
+ * headline `status` from an environment-free listing; `--env` only picks where
12169
+ * a run goes. `latestStatus` reads `--status` as the run selector does
12170
+ * (`not_run` = draft or ready); otherwise it is the public status set.
12171
+ */
12172
+ async function resolveAllProjectTests(args) {
12173
+ const { client, projectId, statusFilter, nameFilter, stderr } = args;
12174
+ const statusSelected = statusFilter !== undefined && statusFilter !== '';
12175
+ let items = (await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
12176
+ query: { projectId, pageSize, cursor },
12177
+ }), {})).items;
12178
+ const statusOf = (test) => test.status;
12179
+ if (args.skipTerminal) {
12180
+ const before = items.length;
12181
+ items = items.filter(t => !TERMINAL_PUBLIC_STATUSES.has(statusOf(t)));
12182
+ const skipped = before - items.length;
12183
+ if (skipped > 0) {
12184
+ stderr(`--skip-terminal: skipped ${skipped} already-terminal test${skipped !== 1 ? 's' : ''} (passed|failed|blocked|cancelled).`);
12185
+ }
12186
+ }
12187
+ if (statusSelected) {
12188
+ const allowed = new Set(statusFilter
12189
+ .split(',')
12190
+ .map(s => s.trim())
12191
+ .filter(s => s.length > 0)
12192
+ .flatMap(s => (args.latestStatus && s === 'not_run' ? ['draft', 'ready'] : [s])));
12193
+ const before = items.length;
12194
+ items = items.filter(t => allowed.has(statusOf(t)));
12195
+ const skipped = before - items.length;
12196
+ if (skipped > 0) {
12197
+ stderr(args.latestStatus
12198
+ ? `--status filter: skipped ${skipped} test${skipped !== 1 ? 's' : ''} whose latest status is not ${statusFilter}.`
12199
+ : `--status filter: skipped ${skipped} test${skipped !== 1 ? 's' : ''} not matching status=${statusFilter}.`);
12200
+ }
12201
+ }
12202
+ if (nameFilter !== undefined && nameFilter !== '') {
12203
+ const needle = nameFilter.toLowerCase();
12204
+ const before = items.length;
12205
+ items = items.filter(t => t.name.toLowerCase().includes(needle));
12206
+ const skipped = before - items.length;
12207
+ if (skipped > 0) {
12208
+ stderr(`--filter: skipped ${skipped} test${skipped !== 1 ? 's' : ''} whose name does not contain "${nameFilter}".`);
12209
+ }
12210
+ }
12211
+ return items;
12212
+ }
12213
+ /** The selectors a zero-match message names, in the order they are applied. */
12214
+ function describeRunSelectors(opts) {
12215
+ const parts = [];
12216
+ if (opts.statusFilter !== undefined)
12217
+ parts.push(`--status ${opts.statusFilter}`);
12218
+ if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
12219
+ parts.push(`--filter "${opts.nameFilter}"`);
12220
+ }
12221
+ return parts.join(' ');
12222
+ }
12047
12223
  function parseEnumFlag(raw, flagName, accepted) {
12048
12224
  if (raw === undefined)
12049
12225
  return undefined;
@@ -12219,7 +12395,7 @@ function makeOutput(mode, deps) {
12219
12395
  stdout: deps.stdout,
12220
12396
  stderr: deps.stderr,
12221
12397
  rawStdout: deps.rawStdout,
12222
- });
12398
+ }, { deprecations: deps.deprecations });
12223
12399
  }
12224
12400
  /**
12225
12401
  * Open a temp file next to the `--out` target before any network I/O so
@@ -12943,16 +13119,14 @@ function createTestCodeCommand(deps) {
12943
13119
  code
12944
13120
  .command('put <test-id>')
12945
13121
  .description('Replace test code with etag-guarded optimistic concurrency')
12946
- .option('--code-file <path>', 'file containing the new test code (≤ 350 KB)')
12947
- .option('--expected-version <v>', 'expected current codeVersion (e.g. v3); sent as `If-Match`. Mutually exclusive with --force.')
12948
- .option('--force', 'send `If-Match: *` to skip the etag check (audit-logged with force: true). Mutually exclusive with --expected-version.', false)
12949
- .option('--language <lang>', 'set the stored code language; only "python" is supported (TestSprite executes test code as Python). Defaults to the existing language.')
12950
- .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
12951
- .option('--dry-run-simulate-error <code>', 'With --dry-run: synthesise an error envelope to preview the error path. Supported: PRECONDITION_FAILED (412).')
12952
- .addHelpText('after', '\nDry-run note: --dry-run always returns the happy response shape.\n' +
12953
- 'To preview the 412 retry-hint path, combine with --dry-run-simulate-error PRECONDITION_FAILED.\n' +
12954
- '\n' +
12955
- GLOBAL_OPTS_HINT)
13122
+ .option('--code-file <path>', 'new test code: required, a .py file, ≤ 350 KB')
13123
+ .option('--expected-version <v>', 'expected current codeVersion (e.g. v3), sent as `If-Match`; excludes --force. ' +
13124
+ 'Omit both to auto-fetch the current version (no protection against concurrent edits; pass it in scripts).')
13125
+ .option('--force', 'send `If-Match: *` to skip the etag check (audit-logged); excludes --expected-version', false)
13126
+ .option('--language <lang>', 'stored code language; only "python" is supported (default: the existing language)')
13127
+ .option('--idempotency-key <token>', 'idempotency token (1-256 ASCII chars; default: random UUID per invocation, pin one for safe retries)')
13128
+ .option('--dry-run-simulate-error <code>', 'with --dry-run: preview the 412 error path (supported: PRECONDITION_FAILED); without it --dry-run shows the success shape')
13129
+ .addHelpText('after', GLOBAL_OPTS_HINT)
12956
13130
  .action(async (testId, cmdOpts, command) => {
12957
13131
  const simulateError = cmdOpts.dryRunSimulateError;
12958
13132
  if (simulateError !== undefined && simulateError !== 'PRECONDITION_FAILED') {
@@ -13829,13 +14003,17 @@ function createTestPlanCommand(deps) {
13829
14003
  plan
13830
14004
  .command('put <test-id>')
13831
14005
  .description("Replace an FE test's planSteps[] (BE tests return 400 → use 'test code put')")
13832
- .option('--steps <path>', 'JSON file with { planSteps: [...] } (FE-only, ≤ 200 steps, ≤ 256 KB)')
14006
+ .option('--steps <path>', 'required: JSON file with { planSteps: [...] } (FE-only, ≤ 200 steps, ≤ 256 KB)')
13833
14007
  .option('--expected-step-count <n>', 'pin the step count the server must still have; 412 when it differs')
13834
14008
  .option('--force', 'replace even if steps edited in the Portal would lose their structured fields')
13835
- .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
13836
- .option('--dry-run-simulate-error <code>', 'With --dry-run: synthesise an error envelope to preview the error path. Supported: PRECONDITION_FAILED (412).')
13837
- .addHelpText('after', '\nDry-run note: --dry-run always returns the happy response shape.\n' +
13838
- 'To preview the 412 retry-hint path, combine with --dry-run-simulate-error PRECONDITION_FAILED.\n' +
14009
+ .option('--idempotency-key <token>', 'idempotency token (1-256 ASCII chars; default: random UUID per invocation, pin one for safe retries)')
14010
+ .option('--dry-run-simulate-error <code>', 'with --dry-run: preview the 412 error path (supported: PRECONDITION_FAILED); without it --dry-run shows the success shape')
14011
+ .addHelpText('after', '\nExit codes:\n' +
14012
+ ' 0 steps replaced\n' +
14013
+ ' 3 authentication error\n' +
14014
+ ' 4 test not found\n' +
14015
+ ' 5 validation error (e.g. missing --steps, unreadable or invalid file)\n' +
14016
+ ' 6 step-count mismatch with --expected-step-count (HTTP 412)\n' +
13839
14017
  '\n' +
13840
14018
  GLOBAL_OPTS_HINT)
13841
14019
  .action(async (testId, cmdOpts, command) => {
@@ -13855,25 +14033,26 @@ function createTestPlanCommand(deps) {
13855
14033
  });
13856
14034
  plan
13857
14035
  .command('generate')
13858
- .description('Generate AI test-case proposals for a project — runs only the missing pipeline ' +
14036
+ .summary('Generate AI test-case proposals for review')
14037
+ .description('Generate AI test-case proposals for a project: runs only the missing pipeline ' +
13859
14038
  'stages and stages the results server-side for review (nothing is written locally)')
13860
- .option('--project <id>', 'project id (V3-native; V2 ids resolve through the migration bridge)')
14039
+ .option('--project <id>', 'project id (or set TESTSPRITE_PROJECT_ID)')
13861
14040
  .option('--timeout <seconds>', `total wait budget in seconds (1-3600, default ${PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS}; ` +
13862
- 'exploration takes minutes on a fresh frontend project)')
13863
- .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
13864
- .addHelpText('after', '\nBehavior:\n' +
13865
- ' - Runs the stages the project still needs (exploration for frontend,\n' +
13866
- ' strategy, proposals) and stops when proposals are staged for review.\n' +
13867
- ' Nothing is written to disk.\n' +
13868
- ' - Interrupt (exit 130/143/129) or timeout (exit 7): the stage in\n' +
13869
- ' progress finishes on its own, the rest wait. Run the same command\n' +
13870
- ' again to continue; it picks up where it left off. A stage that\n' +
13871
- ' already completed is never charged again.\n' +
13872
- ' - Workspace credits are spent per stage that runs; the result line reports\n' +
13873
- ' what THIS run charged (omitted when nothing new was charged).\n' +
13874
- ' `testsprite usage` shows your balance.\n' +
13875
- '\n' +
13876
- 'Next step: review the printed table, then `testsprite test plan accept`.\n' +
14041
+ 'exploration of a fresh frontend project takes minutes)')
14042
+ .option('--idempotency-key <token>', 'idempotency token (1-256 ASCII chars; default: random UUID per invocation, pin one for safe retries)')
14043
+ .addHelpText('after', '\nStages that run: exploration (frontend), strategy, proposals. On interrupt (exit 130/143/129)\n' +
14044
+ 'or timeout (exit 7) the running stage finishes on its own; re-run the same command to continue.\n' +
14045
+ 'A completed stage is never charged again. Workspace credits are spent per stage that runs;\n' +
14046
+ 'the result line reports what THIS run charged. `testsprite usage` shows your balance.\n' +
14047
+ '\nNext: review the printed table, then `testsprite test plan accept`.\n' +
14048
+ '\nExit codes:\n' +
14049
+ ' 0 proposals staged for review\n' +
14050
+ ' 1 a pipeline stage failed server-side (re-run to retry it)\n' +
14051
+ ' 3 authentication error\n' +
14052
+ ' 5 validation error\n' +
14053
+ ' 7 timeout (re-run to continue)\n' +
14054
+ ' 11 rate limited\n' +
14055
+ ' 12 insufficient credits\n' +
13877
14056
  '\n' +
13878
14057
  GLOBAL_OPTS_HINT)
13879
14058
  .action(async (cmdOpts, command) => {
@@ -13888,18 +14067,15 @@ function createTestPlanCommand(deps) {
13888
14067
  });
13889
14068
  plan
13890
14069
  .command('accept')
14070
+ .summary('Turn staged proposals into test cases (free)')
13891
14071
  .description('Convert staged proposals into real test cases (free) — all of them, or a subset with --only')
13892
- .option('--project <id>', 'project id (V3-native; V2 ids resolve through the migration bridge)')
13893
- .option('--only <ids...>', 'accept only these proposal ids (space- or comma-separated; the ids come from the ' +
13894
- '`test plan generate` table). Accepting a subset discards the rest. ANY id that ' +
13895
- 'matches no staged proposal is a validation error — the request is never sent.')
13896
- .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
13897
- .addHelpText('after', '\nNotes:\n' +
13898
- ' - Accepting adds no charge of its own; generation already did the work.\n' +
13899
- ' - API test code is generated when the tests first run, not at accept.\n' +
13900
- ' - Accepting a subset discards the remaining staged proposals (the staging\n' +
13901
- ' area is cleared either way) — the output says how many were discarded.\n' +
13902
- ' - Nothing staged → exit 6 with a pointer at `test plan generate`.\n' +
14072
+ .option('--project <id>', 'project id (or set TESTSPRITE_PROJECT_ID)')
14073
+ .option('--only <ids...>', 'accept only these proposal ids from the `test plan generate` table (space- or comma-separated); ' +
14074
+ 'the rest are discarded. Any id matching no staged proposal is a validation error.')
14075
+ .option('--idempotency-key <token>', 'idempotency token (1-256 ASCII chars; default: random UUID per invocation, pin one for safe retries)')
14076
+ .addHelpText('after', '\nAccepting adds no charge. API test code is generated when the tests first run. The staging\n' +
14077
+ 'area is cleared either way (the output says how many proposals were discarded).\n' +
14078
+ 'Nothing staged: exit 6, pointing at `test plan generate`.\n' +
13903
14079
  '\n' +
13904
14080
  GLOBAL_OPTS_HINT)
13905
14081
  .action(async (cmdOpts, command) => {
@@ -13920,10 +14096,9 @@ export function createTestArtifactCommand(deps) {
13920
14096
  // mirror the flat `test result/steps/get <id>` forms). Run-id semantics are
13921
14097
  // preserved: the positional is still a run-id, not a test-id.
13922
14098
  .command('get <run-id>', { isDefault: true })
14099
+ .summary('Download the failure bundle for a run')
13923
14100
  .description([
13924
- 'Download the §7 failure-context bundle for a specific run.',
13925
- '',
13926
- 'Default <dir>: ./.testsprite/runs/<run-id>/',
14101
+ 'Download the failure bundle for a run (result.json, failure.json, code, video, steps/, meta.json).',
13927
14102
  '',
13928
14103
  'Exit codes:',
13929
14104
  ' 0 bundle written successfully',
@@ -13933,12 +14108,8 @@ export function createTestArtifactCommand(deps) {
13933
14108
  ' 6 conflict — snapshot in flight (retried once)',
13934
14109
  ' 10 transport failure (.partial left on disk)',
13935
14110
  ].join('\n'))
13936
- .option('--out <dir>', [
13937
- 'Directory to write the §7 disk layout (default: ./.testsprite/runs/<run-id>/).',
13938
- 'Parent must exist. The bundle dir itself is created if absent.',
13939
- ].join(' '))
13940
- .option('--failed-only', 'Trim to the failed step ±1. The bundle is already failure-focused server-side, ' +
13941
- 'so this is usually a no-op; use `test steps <id>` for the full run trail.')
14111
+ .option('--out <dir>', 'directory to write the bundle into (default: ./.testsprite/runs/<run-id>/); the parent must exist')
14112
+ .option('--failed-only', 'trim to the failed step ±1 (usually a no-op; `test steps <id>` has the full trail)')
13942
14113
  .addHelpText('after', GLOBAL_OPTS_HINT)
13943
14114
  .action(async (runId, cmdOpts, command) => {
13944
14115
  await runArtifactGet({
@@ -13957,10 +14128,19 @@ function createTestFailureCommand(deps) {
13957
14128
  // `test failure get <test-id>` (grammar consistency). `failure summary`
13958
14129
  // still routes explicitly; only the bare-noun form falls through to `get`.
13959
14130
  .command('get <test-id>', { isDefault: true })
13960
- .description("Write a self-contained failure-context bundle for a test's latest failing run")
13961
- .option('--out <dir>', 'Directory to write the §7 disk layout into (default: print wire envelope to stdout)')
13962
- .option('--failed-only', 'Trim to the failed step ±1. The bundle is already failure-focused server-side, ' +
13963
- 'so this is usually a no-op; use `test steps <id>` for the full run trail.')
14131
+ .summary("Write the failure bundle for a test's latest failing run")
14132
+ .description([
14133
+ "Write the failure bundle for a test's latest failing run (same layout as `test artifact get`).",
14134
+ '',
14135
+ 'Exit codes:',
14136
+ ' 0 success',
14137
+ ' 3 authentication error',
14138
+ ' 4 test not found, or it has no failing run',
14139
+ ' 5 validation error (bad --out)',
14140
+ ' 10 transport failure',
14141
+ ].join('\n'))
14142
+ .option('--out <dir>', 'directory to write the bundle into (default: print the envelope to stdout)')
14143
+ .option('--failed-only', 'with --out: trim to the failed step ±1 (usually a no-op; `test steps <id>` has the full trail)')
13964
14144
  .addHelpText('after', GLOBAL_OPTS_HINT)
13965
14145
  .action(async (testId, cmdOpts, command) => {
13966
14146
  await runFailureGet({