@testsprite/testsprite-cli 0.2.0 → 0.4.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 (68) hide show
  1. package/README.md +35 -26
  2. package/dist/commands/agent.d.ts +43 -0
  3. package/dist/commands/agent.js +200 -18
  4. package/dist/commands/auth.d.ts +5 -0
  5. package/dist/commands/auth.js +38 -27
  6. package/dist/commands/doctor.d.ts +49 -0
  7. package/dist/commands/doctor.js +233 -0
  8. package/dist/commands/init.d.ts +1 -1
  9. package/dist/commands/init.js +24 -14
  10. package/dist/commands/project.d.ts +75 -2
  11. package/dist/commands/project.js +326 -47
  12. package/dist/commands/test.d.ts +281 -2
  13. package/dist/commands/test.js +1658 -177
  14. package/dist/commands/usage.js +13 -12
  15. package/dist/index.js +71 -3
  16. package/dist/lib/agent-targets.d.ts +72 -6
  17. package/dist/lib/agent-targets.js +188 -6
  18. package/dist/lib/bundle.d.ts +34 -0
  19. package/dist/lib/bundle.js +63 -11
  20. package/dist/lib/client-factory.d.ts +31 -0
  21. package/dist/lib/client-factory.js +63 -0
  22. package/dist/lib/config.d.ts +2 -0
  23. package/dist/lib/config.js +11 -2
  24. package/dist/lib/credentials.js +10 -1
  25. package/dist/lib/dry-run/samples.d.ts +5 -0
  26. package/dist/lib/dry-run/samples.js +64 -0
  27. package/dist/lib/errors.d.ts +28 -1
  28. package/dist/lib/errors.js +40 -0
  29. package/dist/lib/failing-fe-resolver.d.ts +15 -0
  30. package/dist/lib/failing-fe-resolver.js +49 -1
  31. package/dist/lib/flaky.d.ts +80 -0
  32. package/dist/lib/flaky.js +76 -0
  33. package/dist/lib/http.d.ts +73 -1
  34. package/dist/lib/http.js +327 -135
  35. package/dist/lib/interrupt.d.ts +116 -0
  36. package/dist/lib/interrupt.js +182 -0
  37. package/dist/lib/junit-report.d.ts +58 -0
  38. package/dist/lib/junit-report.js +210 -0
  39. package/dist/lib/output.d.ts +16 -1
  40. package/dist/lib/output.js +24 -2
  41. package/dist/lib/pagination.d.ts +4 -3
  42. package/dist/lib/pagination.js +34 -6
  43. package/dist/lib/poll.d.ts +11 -0
  44. package/dist/lib/poll.js +70 -5
  45. package/dist/lib/prompt.js +52 -8
  46. package/dist/lib/proxy.d.ts +29 -0
  47. package/dist/lib/proxy.js +30 -0
  48. package/dist/lib/render-error.js +3 -1
  49. package/dist/lib/runs.types.d.ts +9 -0
  50. package/dist/lib/skill-nudge.d.ts +2 -2
  51. package/dist/lib/skill-nudge.js +13 -4
  52. package/dist/lib/target-url.js +8 -1
  53. package/dist/lib/ticker.d.ts +11 -1
  54. package/dist/lib/ticker.js +33 -1
  55. package/dist/lib/update-check.d.ts +67 -0
  56. package/dist/lib/update-check.js +246 -0
  57. package/dist/lib/v3-advisory.d.ts +13 -0
  58. package/dist/lib/v3-advisory.js +24 -0
  59. package/dist/lib/version-notice.d.ts +37 -0
  60. package/dist/lib/version-notice.js +87 -0
  61. package/dist/version-guard.d.ts +33 -0
  62. package/dist/version-guard.js +39 -0
  63. package/dist/version.d.ts +1 -1
  64. package/dist/version.js +1 -1
  65. package/package.json +3 -2
  66. package/skills/testsprite-onboard.skill.md +21 -0
  67. package/skills/testsprite-verify.codex.md +6 -0
  68. package/skills/testsprite-verify.skill.md +48 -4
@@ -1,15 +1,17 @@
1
- import { createWriteStream, readFileSync, readdirSync, statSync } from 'node:fs';
1
+ import { createWriteStream, existsSync, readFileSync, readdirSync, statSync, } from 'node:fs';
2
2
  import { rename, stat, unlink } from 'node:fs/promises';
3
3
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { Command } from 'commander';
6
- import { emitDryRunBanner, makeHttpClient, } from '../lib/client-factory.js';
6
+ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
7
7
  import { assertContextIntegrity, buildMeta, pickCodeExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
8
- import { findSample } from '../lib/dry-run/samples.js';
9
- import { ApiError, CLIError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
8
+ import { findSample, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
9
+ import { assertJUnitReportOptions, buildJUnitReport, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
10
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
11
+ import { globalShutdown } from '../lib/interrupt.js';
10
12
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
11
13
  import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.js';
12
- import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
14
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
13
15
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
14
16
  import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
15
17
  import { RUN_SOURCES } from '../lib/runs.types.js';
@@ -18,6 +20,25 @@ import { createTicker } from '../lib/ticker.js';
18
20
  import { RateThrottle } from '../lib/rate-throttle.js';
19
21
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
20
22
  import { loadConfig } from '../lib/config.js';
23
+ import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
24
+ /** The effective shutdown handle for a command invocation (DEV-331). */
25
+ function shutdownOf(deps) {
26
+ return deps.shutdown ?? globalShutdown;
27
+ }
28
+ /**
29
+ * The honest-detach stderr line (DEV-331 D1 — the heart of the ticket):
30
+ * a Ctrl-C detaches the local wait only; the server-side run keeps executing
31
+ * AND billing. Names both re-attach (`test wait`) and the real cancel
32
+ * (`test cancel`, piece 3) so the user always has a path to actually stop it.
33
+ */
34
+ function interruptDetachMessage(err, runIds) {
35
+ const subject = runIds.length === 1
36
+ ? `Run ${runIds[0]} is still executing on the server and will keep running (and billing) until it finishes.`
37
+ : `${runIds.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
38
+ return (`Interrupted (${err.signal}). ${subject}\n` +
39
+ ` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
40
+ ` Cancel with: testsprite test cancel ${runIds.join(' ')}`);
41
+ }
21
42
  const TEST_TYPES = ['frontend', 'backend'];
22
43
  // 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
23
44
  // tests created via `testsprite test create`, so the `--created-from cli`
@@ -71,17 +92,17 @@ export async function runList(opts, deps = {}) {
71
92
  startingToken: opts.startingToken,
72
93
  maxItems: opts.maxItems,
73
94
  });
95
+ // M2.1 piece 2: validate `--status` tokens client-side before
96
+ // sending. Friendlier error than waiting for the server's 400 with
97
+ // a list of accepted tokens — and lets the user fix typos without
98
+ // a round trip.
99
+ validateStatusFilter(opts.status);
74
100
  const out = makeOutput(opts.output, deps);
75
101
  const client = makeClient(opts, deps);
76
102
  // Match P2's "explicit pageSize ⇒ single-page" convention so an
77
103
  // operator can grab one slice + cursor without auto-paging through a
78
104
  // huge project.
79
105
  const useSinglePage = opts.pageSize !== undefined && opts.maxItems === undefined;
80
- // M2.1 piece 2: validate `--status` tokens client-side before
81
- // sending. Friendlier error than waiting for the server's 400 with
82
- // a list of accepted tokens — and lets the user fix typos without
83
- // a round trip.
84
- validateStatusFilter(opts.status);
85
106
  const baseQuery = {
86
107
  projectId: opts.projectId,
87
108
  type: opts.type,
@@ -241,14 +262,19 @@ export async function runCreate(opts, deps = {}) {
241
262
  if (opts.type === 'frontend') {
242
263
  const depFlags = [];
243
264
  if (opts.produces !== undefined && opts.produces.length > 0)
244
- depFlags.push('--produces');
265
+ depFlags.push('produces');
245
266
  if (opts.needs !== undefined && opts.needs.length > 0)
246
- depFlags.push('--needs');
267
+ depFlags.push('needs');
247
268
  if (opts.category !== undefined)
248
- depFlags.push('--category');
269
+ depFlags.push('category');
249
270
  if (depFlags.length > 0) {
250
- throw localValidationError(depFlags[0], `${depFlags.join(', ')} are backend-only flags; frontend plans have no wave model. ` +
251
- `Remove ${depFlags.join('/')} or use --type backend.`);
271
+ // Pass the BARE flag name to localValidationError — its kind:'flag' branch
272
+ // adds the `--` prefix, so '--produces' would render as '----produces'.
273
+ const flagList = depFlags.map(f => `--${f}`);
274
+ const verb = depFlags.length === 1 ? 'is a backend-only flag' : 'are backend-only flags';
275
+ // No trailing period: localValidationError appends one after the reason.
276
+ throw localValidationError(depFlags[0], `${flagList.join(', ')} ${verb}; frontend plans have no wave model. ` +
277
+ `Remove ${flagList.join('/')} or use --type backend`);
252
278
  }
253
279
  }
254
280
  // Dry-run path skips fs entirely so the operator can shake out the
@@ -312,6 +338,10 @@ export async function runCreate(opts, deps = {}) {
312
338
  body,
313
339
  headers: { 'idempotency-key': idempotencyKey },
314
340
  });
341
+ // Surface backend advisories (e.g. a hardcoded-credential warning for BE
342
+ // tests) on stderr so they reach the agent without polluting stdout JSON.
343
+ // Emitted before the --run early return so they always show.
344
+ emitResponseWarnings(response.warnings, deps);
315
345
  // --run chain (M3.3 piece-3). Per codex round-1 P1: suppress the
316
346
  // create's own print when chaining; `runTestRun` emits a single
317
347
  // merged envelope `{ ...createResponse, run: <trigger|final> }` so
@@ -413,7 +443,7 @@ function readCodeFileGuarded(path) {
413
443
  }
414
444
  function readCodeFile(path) {
415
445
  try {
416
- return readFileSync(resolveAbsolute(path), 'utf8');
446
+ return stripBom(readFileSync(resolveAbsolute(path), 'utf8'));
417
447
  }
418
448
  catch (err) {
419
449
  const code = err.code;
@@ -458,6 +488,17 @@ function renderCreateText(response) {
458
488
  `createdAt ${response.createdAt}`,
459
489
  ].join('\n');
460
490
  }
491
+ /**
492
+ * Emit backend `warnings[]` advisories to stderr (one `[warn]` line each),
493
+ * keeping stdout — JSON or text — uncluttered. No-op when absent/empty.
494
+ */
495
+ function emitResponseWarnings(warnings, deps) {
496
+ if (!warnings || warnings.length === 0)
497
+ return;
498
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
499
+ for (const w of warnings)
500
+ stderrFn(`[warn] ${w}`);
501
+ }
461
502
  /**
462
503
  * piece-6 cap for the `PUT /tests/{id}/plan-steps` body. Distinct from
463
504
  * piece-5's `MAX_PLAN_BODY_BYTES` because the wire shape differs
@@ -653,6 +694,9 @@ export async function runUpdate(opts, deps = {}) {
653
694
  assertIdempotencyKey(opts.idempotencyKey);
654
695
  requireNonEmpty('test-id', opts.testId);
655
696
  // P1-3: client-side length checks matching server limits.
697
+ if (opts.name !== undefined && opts.name.trim().length === 0) {
698
+ throw localValidationError('name', 'must be a non-empty string (whitespace-only is not allowed)');
699
+ }
656
700
  if (opts.name !== undefined && opts.name.length > 200) {
657
701
  throw localValidationError('name', 'must be at most 200 characters');
658
702
  }
@@ -670,8 +714,11 @@ export async function runUpdate(opts, deps = {}) {
670
714
  const hasName = opts.name !== undefined;
671
715
  const hasDescription = opts.description !== undefined;
672
716
  const hasPriority = opts.priority !== undefined;
673
- if (!hasName && !hasDescription && !hasPriority) {
674
- throw localValidationError('fields', 'at least one of --name / --description / --priority must be set', ['name', 'description', 'priority']);
717
+ const hasProduces = opts.produces !== undefined && opts.produces.length > 0;
718
+ const hasNeeds = opts.needs !== undefined && opts.needs.length > 0;
719
+ const hasCategory = opts.category !== undefined;
720
+ if (!hasName && !hasDescription && !hasPriority && !hasProduces && !hasNeeds && !hasCategory) {
721
+ throw localValidationError('fields', 'at least one of --name / --description / --priority / --produces / --needs / --category must be set', ['name', 'description', 'priority', 'produces', 'needs', 'category']);
675
722
  }
676
723
  const idempotencyKey = opts.idempotencyKey ?? `cli-update-${randomUUID()}`;
677
724
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
@@ -690,6 +737,12 @@ export async function runUpdate(opts, deps = {}) {
690
737
  body.description = opts.description;
691
738
  if (hasPriority)
692
739
  body.priority = opts.priority;
740
+ if (hasProduces)
741
+ body.produces = opts.produces;
742
+ if (hasNeeds)
743
+ body.consumes = opts.needs;
744
+ if (hasCategory)
745
+ body.category = opts.category;
693
746
  const client = makeClient(opts, deps);
694
747
  const out = makeOutput(opts.output, deps);
695
748
  const response = await client.put(`/tests/${encodeURIComponent(opts.testId)}`, {
@@ -1555,7 +1608,13 @@ apiUrlForDashboard) {
1555
1608
  *
1556
1609
  * Returns a CliBatchRunResult. Never throws — errors are captured
1557
1610
  * into the result's `error` field so one failure doesn't abort siblings.
1611
+ * (Exception: InterruptError rethrows so the collect point can print the
1612
+ * partial — DEV-331.)
1558
1613
  */
1614
+ // testId → dispatched runId for members still mid-poll; the interrupt
1615
+ // partial reads it because a member's runId is local to triggerOne until
1616
+ // the poll settles (DEV-331, codex finding 2).
1617
+ const dispatchedRunIds = new Map();
1559
1618
  async function triggerOne(testId) {
1560
1619
  // Mint a fresh idempotency key per run — MUST NOT reuse the create key.
1561
1620
  const runIdempotencyKey = `cli-batch-run-${randomUUID()}`;
@@ -1636,6 +1695,11 @@ apiUrlForDashboard) {
1636
1695
  break; // success — exit the outer retry loop
1637
1696
  }
1638
1697
  catch (err) {
1698
+ // Interrupt must reject the fan-out (the collect point prints the
1699
+ // partial for every spec), never flatten into a per-member outcome
1700
+ // that would swallow the 128+signum exit (DEV-331).
1701
+ if (err instanceof InterruptError)
1702
+ throw err;
1639
1703
  // RATE_LIMITED outer retry. Since the HTTP layer no longer retries
1640
1704
  // RATE_LIMITED (retryOnRateLimit: false above), every 429 reaches here
1641
1705
  // on the first attempt.
@@ -1759,6 +1823,12 @@ apiUrlForDashboard) {
1759
1823
  }
1760
1824
  }
1761
1825
  }
1826
+ // Record the dispatched runId (fresh trigger OR conflict-resume) so the
1827
+ // interrupt partial at the collect point can name every in-flight run —
1828
+ // a member's runId is otherwise local until its poll settles (DEV-331,
1829
+ // codex finding 2).
1830
+ if (triggerResponse.runId)
1831
+ dispatchedRunIds.set(testId, triggerResponse.runId);
1762
1832
  if (!opts.wait) {
1763
1833
  // No-wait path: return the trigger response as-is.
1764
1834
  if (opts.output !== 'json') {
@@ -1797,12 +1867,16 @@ apiUrlForDashboard) {
1797
1867
  finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
1798
1868
  timeoutSeconds: remainingSeconds,
1799
1869
  sleep: deps.sleep,
1870
+ shutdown: shutdownOf(deps),
1800
1871
  onTransition: opts.verbose
1801
1872
  ? (msg) => stderrFn(`[batch-run][verbose] ${testId}: ${msg}`)
1802
1873
  : undefined,
1803
1874
  });
1804
1875
  }
1805
1876
  catch (err) {
1877
+ // Interrupt rejects the fan-out — see the trigger-stage catch above.
1878
+ if (err instanceof InterruptError)
1879
+ throw err;
1806
1880
  if (err instanceof TimeoutError) {
1807
1881
  if (opts.output !== 'json') {
1808
1882
  stderrFn(`[batch-run] ${testId} (runId: ${triggerResponse.runId}) — timed out after ${timeoutSeconds}s`);
@@ -1860,26 +1934,56 @@ apiUrlForDashboard) {
1860
1934
  // used by the other fan-outs in this file (e.g. pollFreshAccepted below).
1861
1935
  let nextIdx = 0;
1862
1936
  let inFlight = 0;
1863
- await new Promise((resolve, reject) => {
1864
- function startNext() {
1865
- while (inFlight < concurrencyLimit && nextIdx < testIds.length) {
1866
- const testId = testIds[nextIdx++];
1867
- inFlight++;
1868
- triggerOne(testId)
1869
- .then(result => {
1870
- batchRunResults.push(result);
1871
- inFlight--;
1872
- startNext();
1873
- if (inFlight === 0 && nextIdx >= testIds.length)
1874
- resolve();
1875
- })
1876
- .catch(reject);
1937
+ try {
1938
+ await new Promise((resolve, reject) => {
1939
+ function startNext() {
1940
+ while (inFlight < concurrencyLimit && nextIdx < testIds.length) {
1941
+ const testId = testIds[nextIdx++];
1942
+ inFlight++;
1943
+ triggerOne(testId)
1944
+ .then(result => {
1945
+ batchRunResults.push(result);
1946
+ inFlight--;
1947
+ startNext();
1948
+ if (inFlight === 0 && nextIdx >= testIds.length)
1949
+ resolve();
1950
+ })
1951
+ .catch(reject);
1952
+ }
1953
+ }
1954
+ startNext();
1955
+ if (testIds.length === 0)
1956
+ resolve();
1957
+ });
1958
+ }
1959
+ catch (fanOutErr) {
1960
+ // Graceful detach (DEV-331): leave stdout parseable — settled members keep
1961
+ // their real status, unfinished ones are marked running — then rethrow so
1962
+ // index.ts exits 128+signum.
1963
+ if (fanOutErr instanceof InterruptError) {
1964
+ const settled = new Map(batchRunResults.map(r => [r.testId, r]));
1965
+ // Members mid-poll have no settled result yet — their runId comes from
1966
+ // the dispatchedRunIds map recorded at trigger time (codex finding 2).
1967
+ const partialResults = testIds.map((testId) => settled.get(testId) ?? {
1968
+ testId,
1969
+ runId: dispatchedRunIds.get(testId) ?? '',
1970
+ status: dispatchedRunIds.has(testId) ? 'running' : 'not_dispatched',
1971
+ codeVersion: '',
1972
+ });
1973
+ out.print({ results: partialResults }, () => partialResults.map(r => `${r.testId} ${r.runId || '-'} ${r.status}`).join('\n'));
1974
+ const unfinished = partialResults
1975
+ .filter(r => r.status === 'running' && r.runId)
1976
+ .map(r => r.runId);
1977
+ if (unfinished.length > 0) {
1978
+ stderrFn(interruptDetachMessage(fanOutErr, unfinished));
1979
+ }
1980
+ else {
1981
+ stderrFn(`Interrupted (${fanOutErr.signal}). Already-triggered runs keep executing (and billing) server-side; ` +
1982
+ `check them with: testsprite test list`);
1877
1983
  }
1878
1984
  }
1879
- startNext();
1880
- if (testIds.length === 0)
1881
- resolve();
1882
- });
1985
+ throw fanOutErr;
1986
+ }
1883
1987
  // Sort by testId order (same as input order for stable output).
1884
1988
  batchRunResults.sort((a, b) => testIds.indexOf(a.testId) - testIds.indexOf(b.testId));
1885
1989
  // Emit output.
@@ -2239,7 +2343,7 @@ export async function runCodeGet(opts, deps = {}) {
2239
2343
  }
2240
2344
  return code;
2241
2345
  }
2242
- const fileSink = opts.out !== undefined ? openOutputFile(opts.out) : null;
2346
+ let fileSink = opts.out !== undefined ? openOutputFile(opts.out) : null;
2243
2347
  const out = fileSink ? makeFileOutput(opts.output, fileSink) : makeOutput(opts.output, deps);
2244
2348
  const client = makeClient(opts, deps);
2245
2349
  try {
@@ -2264,9 +2368,17 @@ export async function runCodeGet(opts, deps = {}) {
2264
2368
  else if (code.code === '' || code.code === null) {
2265
2369
  // P2-10: draft test with no code yet — empty body would produce
2266
2370
  // silent empty stdout. Print a friendly hint to stderr instead so
2267
- // the operator knows what happened, and keep exit 0. Nothing was
2268
- // written, so the temp file is discarded below without touching
2269
- // a pre-existing `--out` file.
2371
+ // the operator knows what happened, and keep exit 0 when no `--out`.
2372
+ //
2373
+ // With `--out`, refuse to leave a zero-byte artifact behind: agents
2374
+ // and scripts that check file size would otherwise treat exit 0 as
2375
+ // a successful download. Discard the temp sink without touching a
2376
+ // pre-existing destination file.
2377
+ if (fileSink) {
2378
+ await abortOutputFile(fileSink);
2379
+ fileSink = null;
2380
+ throw localValidationError('out', 'test has no generated code yet — run the test first (refusing to write an empty --out file)');
2381
+ }
2270
2382
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2271
2383
  stderrFn('(no code generated yet — run the test first)');
2272
2384
  }
@@ -2412,6 +2524,7 @@ export async function runCodePut(opts, deps = {}) {
2412
2524
  'if-match': ifMatch,
2413
2525
  },
2414
2526
  });
2527
+ emitResponseWarnings(response.warnings, deps);
2415
2528
  out.print(response, data => renderCodePutText(data));
2416
2529
  return response;
2417
2530
  }
@@ -2476,7 +2589,333 @@ function mapRunStepToCliTestStep(step, run) {
2476
2589
  // concrete boolean — `true` for the failing step, `false` for the known
2477
2590
  // non-contributors. (Per the CliTestStep contract: null ≠ false.)
2478
2591
  outcomeContributesToFailure: run.failedStepIndex === null ? null : numericIndex === run.failedStepIndex,
2592
+ // Carry the per-step failure text and the wire step kind through instead
2593
+ // of dropping them: the agent asking "why did this step fail?" would
2594
+ // otherwise have to download the whole artifact bundle to read a string
2595
+ // this very response already contained.
2596
+ error: step.error,
2597
+ stepType: step.type,
2598
+ };
2599
+ }
2600
+ /**
2601
+ * `test diff <runA> <runB>` (issue #124): isolate what regressed between two
2602
+ * runs, the first question when CI goes red ("what changed since the last
2603
+ * green run?"). Pure client-side composition of the existing per-run read
2604
+ * (`GET /runs/{id}?includeSteps=true`); the endpoint accepts any two run-ids,
2605
+ * so a cross-test pair is a WARNING, not an error. Exit 0 when the verdicts
2606
+ * match, exit 1 when they differ, so the command is CI-scriptable.
2607
+ */
2608
+ export async function runDiff(opts, deps = {}) {
2609
+ const out = makeOutput(opts.output, deps);
2610
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2611
+ if (opts.dryRun) {
2612
+ emitDryRunBanner(stderrFn);
2613
+ const sample = {
2614
+ runA: {
2615
+ runId: opts.runA,
2616
+ testId: 'test_dryrun',
2617
+ status: 'passed',
2618
+ failureKind: null,
2619
+ failedStepIndex: null,
2620
+ codeVersion: 'v1',
2621
+ },
2622
+ runB: {
2623
+ runId: opts.runB,
2624
+ testId: 'test_dryrun',
2625
+ status: 'failed',
2626
+ failureKind: 'assertion',
2627
+ failedStepIndex: 2,
2628
+ codeVersion: 'v1',
2629
+ },
2630
+ verdictChanged: true,
2631
+ failedStepIndexChanged: true,
2632
+ failureKindChanged: true,
2633
+ codeVersionChanged: false,
2634
+ crossTest: false,
2635
+ changedSteps: [{ stepIndex: 2, statusA: 'passed', statusB: 'failed' }],
2636
+ };
2637
+ out.print(sample, () => renderRunDiffText(sample));
2638
+ return sample;
2639
+ }
2640
+ const client = makeClient(opts, deps);
2641
+ const [runA, runB] = await Promise.all([
2642
+ client.getRun(opts.runA, { includeSteps: true }),
2643
+ client.getRun(opts.runB, { includeSteps: true }),
2644
+ ]);
2645
+ const crossTest = runA.testId !== runB.testId;
2646
+ if (crossTest) {
2647
+ stderrFn(`⚠ the two runs belong to different tests (${runA.testId} vs ${runB.testId}) — step deltas may be meaningless`);
2648
+ }
2649
+ const stepsByIndex = (run) => {
2650
+ const map = new Map();
2651
+ for (const step of run.steps ?? []) {
2652
+ const index = parseInt(step.stepIndex, 10);
2653
+ if (Number.isInteger(index))
2654
+ map.set(index, { status: step.status ?? 'unknown', error: step.error });
2655
+ }
2656
+ return map;
2657
+ };
2658
+ const stepsA = stepsByIndex(runA);
2659
+ const stepsB = stepsByIndex(runB);
2660
+ const allIndexes = [...new Set([...stepsA.keys(), ...stepsB.keys()])].sort((left, right) => left - right);
2661
+ const changedSteps = [];
2662
+ for (const index of allIndexes) {
2663
+ const sideA = stepsA.get(index);
2664
+ const sideB = stepsB.get(index);
2665
+ const statusA = sideA?.status ?? 'absent';
2666
+ const statusB = sideB?.status ?? 'absent';
2667
+ if (statusA === statusB)
2668
+ continue;
2669
+ changedSteps.push({
2670
+ stepIndex: index,
2671
+ statusA,
2672
+ statusB,
2673
+ ...(sideA?.error ? { errorA: sideA.error } : {}),
2674
+ ...(sideB?.error ? { errorB: sideB.error } : {}),
2675
+ });
2676
+ }
2677
+ const summarize = (run) => ({
2678
+ runId: run.runId,
2679
+ testId: run.testId,
2680
+ status: run.status,
2681
+ failureKind: run.failureKind ?? null,
2682
+ failedStepIndex: run.failedStepIndex,
2683
+ codeVersion: run.codeVersion ?? null,
2684
+ });
2685
+ const diff = {
2686
+ runA: summarize(runA),
2687
+ runB: summarize(runB),
2688
+ verdictChanged: runA.status !== runB.status,
2689
+ failedStepIndexChanged: runA.failedStepIndex !== runB.failedStepIndex,
2690
+ failureKindChanged: (runA.failureKind ?? null) !== (runB.failureKind ?? null),
2691
+ codeVersionChanged: (runA.codeVersion ?? null) !== (runB.codeVersion ?? null),
2692
+ crossTest,
2693
+ changedSteps,
2694
+ };
2695
+ out.print(diff, () => renderRunDiffText(diff));
2696
+ if (diff.verdictChanged) {
2697
+ // Result already printed; the typed exit makes `test diff` a CI gate.
2698
+ throw new CLIError(`verdicts differ: ${runA.runId}=${runA.status} vs ${runB.runId}=${runB.status}`, 1);
2699
+ }
2700
+ return diff;
2701
+ }
2702
+ function renderRunDiffText(diff) {
2703
+ const lines = [];
2704
+ lines.push(`runA: ${diff.runA.runId} ${diff.runA.status} (test ${diff.runA.testId})`);
2705
+ lines.push(`runB: ${diff.runB.runId} ${diff.runB.status} (test ${diff.runB.testId})`);
2706
+ lines.push(`verdict: ${diff.verdictChanged ? `${diff.runA.status} -> ${diff.runB.status}` : `unchanged (${diff.runA.status})`}`);
2707
+ if (diff.failureKindChanged)
2708
+ lines.push(`failureKind: ${diff.runA.failureKind ?? '(none)'} -> ${diff.runB.failureKind ?? '(none)'}`);
2709
+ if (diff.failedStepIndexChanged)
2710
+ lines.push(`failedStepIndex: ${diff.runA.failedStepIndex ?? '(none)'} -> ${diff.runB.failedStepIndex ?? '(none)'}`);
2711
+ lines.push(`codeVersion: ${diff.codeVersionChanged ? `${diff.runA.codeVersion ?? '(none)'} -> ${diff.runB.codeVersion ?? '(none)'} (code drift)` : 'unchanged'}`);
2712
+ if (diff.changedSteps.length === 0) {
2713
+ lines.push('steps: no per-step status changes');
2714
+ }
2715
+ else {
2716
+ lines.push(`steps changed: ${diff.changedSteps.length}`);
2717
+ for (const step of diff.changedSteps) {
2718
+ lines.push(` #${step.stepIndex} ${step.statusA} -> ${step.statusB}`);
2719
+ if (step.errorB)
2720
+ lines.push(` error(B): ${step.errorB.replace(/\s+/g, ' ').trim()}`);
2721
+ else if (step.errorA)
2722
+ lines.push(` error(A): ${step.errorA.replace(/\s+/g, ' ').trim()}`);
2723
+ }
2724
+ }
2725
+ return lines.join('\n');
2726
+ }
2727
+ /**
2728
+ * `test lint` (issue #98): validate plan/steps files fully OFFLINE with the
2729
+ * SAME validators the create paths run, but collecting EVERY problem instead
2730
+ * of dying on the first one, and without any network write. The create-batch
2731
+ * reader is first-error-fatal and only reachable through a command that POSTs,
2732
+ * so authoring a 12-plan directory meant one error per paid round-trip. Zero
2733
+ * network, zero credentials: exit 0 when everything is valid, 5 otherwise, so
2734
+ * it drops into a pre-commit hook or CI step before `create-batch`.
2735
+ */
2736
+ export async function runLint(opts, deps = {}) {
2737
+ const out = makeOutput(opts.output, deps);
2738
+ const sources = [opts.planFrom, opts.planFromDir, opts.plans, opts.steps].filter(source => source !== undefined);
2739
+ if (sources.length !== 1) {
2740
+ throw localValidationError('plan-from', 'exactly one of --plan-from, --plan-from-dir, --plans, or --steps is required');
2741
+ }
2742
+ const issues = [];
2743
+ let checked = 0;
2744
+ // Run one existing validator, converting its typed throw into a report row
2745
+ // (same envelopes, so `details.field` pointers like planSteps[2].type
2746
+ // survive verbatim).
2747
+ const collect = (file, validate) => {
2748
+ checked += 1;
2749
+ try {
2750
+ validate();
2751
+ }
2752
+ catch (err) {
2753
+ if (err instanceof ApiError) {
2754
+ issues.push({
2755
+ file,
2756
+ field: String(err.getDetail('field') ?? '(file)'),
2757
+ reason: String(err.getDetail('reason') ?? err.nextAction ?? err.message),
2758
+ });
2759
+ }
2760
+ else {
2761
+ issues.push({
2762
+ file,
2763
+ field: '(file)',
2764
+ reason: err instanceof Error ? err.message : String(err),
2765
+ });
2766
+ }
2767
+ }
2479
2768
  };
2769
+ if (opts.planFrom !== undefined) {
2770
+ const planFrom = opts.planFrom;
2771
+ collect(planFrom, () => void readPlanFromGuarded(planFrom));
2772
+ }
2773
+ else if (opts.steps !== undefined) {
2774
+ const steps = opts.steps;
2775
+ collect(steps, () => void readPlanStepsFileGuarded(steps));
2776
+ }
2777
+ else if (opts.planFromDir !== undefined) {
2778
+ const dir = resolveAbsolute(opts.planFromDir);
2779
+ let entries;
2780
+ try {
2781
+ entries = readdirSync(dir)
2782
+ .filter(name => name.endsWith('.json'))
2783
+ .sort();
2784
+ }
2785
+ catch {
2786
+ throw localValidationError('plan-from-dir', `cannot read directory: ${dir}`);
2787
+ }
2788
+ if (entries.length === 0) {
2789
+ throw localValidationError('plan-from-dir', 'contains no *.json plan files');
2790
+ }
2791
+ for (const entry of entries) {
2792
+ collect(entry, () => void readPlanFromGuarded(join(dir, entry)));
2793
+ }
2794
+ }
2795
+ else if (opts.plans !== undefined) {
2796
+ // JSONL: validate PER LINE so every bad line reports (the create path's
2797
+ // reader stays throw-on-first; this is the collecting counterpart).
2798
+ const absolute = resolveAbsolute(opts.plans);
2799
+ let content;
2800
+ try {
2801
+ content = readFileSync(absolute, 'utf8');
2802
+ }
2803
+ catch {
2804
+ throw localValidationError('plans', `cannot read file: ${absolute}`);
2805
+ }
2806
+ // Index lines BEFORE dropping blanks so every reported `file:N` points at
2807
+ // the PHYSICAL line in the file (a blank separator line must not shift all
2808
+ // subsequent line numbers).
2809
+ const numberedLines = content
2810
+ .split('\n')
2811
+ .map((rawLine, physicalIndex) => ({ line: rawLine.trim(), lineNo: physicalIndex + 1 }))
2812
+ .filter(entry => entry.line.length > 0);
2813
+ if (numberedLines.length === 0)
2814
+ throw localValidationError('plans', 'contains no plan lines');
2815
+ for (const { line, lineNo } of numberedLines) {
2816
+ collect(`${opts.plans}:${lineNo}`, () => {
2817
+ let parsed;
2818
+ try {
2819
+ parsed = JSON.parse(line);
2820
+ }
2821
+ catch {
2822
+ throw localValidationError('plans', `line ${lineNo} is not valid JSON`, undefined, 'field');
2823
+ }
2824
+ assertPlanShape(parsed, { specIndex: lineNo - 1 });
2825
+ });
2826
+ }
2827
+ }
2828
+ const filesWithIssues = new Set(issues.map(issue => issue.file)).size;
2829
+ const report = { checked, valid: checked - filesWithIssues, issues };
2830
+ out.print(report, () => [
2831
+ ...issues.map(issue => `${issue.file}: ${issue.field}: ${issue.reason}`),
2832
+ `${report.valid}/${report.checked} valid, ${issues.length} problem(s)`,
2833
+ ].join('\n'));
2834
+ if (issues.length > 0) {
2835
+ throw new CLIError(`lint: ${issues.length} problem(s) across ${report.checked} file(s)`, 5);
2836
+ }
2837
+ return report;
2838
+ }
2839
+ /**
2840
+ * `test scaffold` — emit a schema-correct starter test definition so a first
2841
+ * test never starts from hand-copied JSON. Pure-local: no network, no
2842
+ * credentials, no filesystem reads. The frontend template is a `CliPlanInput`
2843
+ * (the exact shape `--plan-from` ingests; sourceRef: CliPlanInput /
2844
+ * PLAN_STEP_TYPES above), so `scaffold | create --plan-from -`-style flows
2845
+ * validate out of the box. The backend template is the minimal `requests`
2846
+ * script the onboarding skill mandates: define a test function with a
2847
+ * concrete status assertion, then CALL it (a defined-but-never-called test
2848
+ * would pass without asserting anything).
2849
+ */
2850
+ export async function runScaffold(opts, deps = {}) {
2851
+ const out = makeOutput(opts.output, deps);
2852
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2853
+ const env = deps.env ?? process.env;
2854
+ // Pre-fill the project id from TESTSPRITE_PROJECT_ID when the caller's
2855
+ // environment carries one; otherwise a clearly-marked placeholder the user
2856
+ // swaps after running `testsprite project list`.
2857
+ const projectId = typeof env.TESTSPRITE_PROJECT_ID === 'string' && env.TESTSPRITE_PROJECT_ID.length > 0
2858
+ ? env.TESTSPRITE_PROJECT_ID
2859
+ : '<run: testsprite project list>';
2860
+ let payload;
2861
+ let body;
2862
+ if (opts.scaffoldType === 'frontend') {
2863
+ const plan = {
2864
+ projectId,
2865
+ type: 'frontend',
2866
+ name: 'My first frontend test',
2867
+ description: 'Replace with one sentence describing what this test verifies.',
2868
+ priority: 'p2',
2869
+ planSteps: [
2870
+ {
2871
+ type: 'action',
2872
+ description: 'Navigate to /login and sign in with a seeded test account',
2873
+ },
2874
+ { type: 'action', description: 'Open the first product page and click "Add to cart"' },
2875
+ { type: 'assertion', description: 'Assert that the cart badge shows 1 item' },
2876
+ ],
2877
+ };
2878
+ payload = plan;
2879
+ body = `${JSON.stringify(plan, null, 2)}\n`;
2880
+ }
2881
+ else {
2882
+ const code = [
2883
+ 'import requests',
2884
+ '',
2885
+ '# Replace with your API base URL (must be reachable from the internet).',
2886
+ 'BASE_URL = "https://staging.example.com"',
2887
+ '',
2888
+ '',
2889
+ 'def test_health_endpoint() -> None:',
2890
+ ' response = requests.get(f"{BASE_URL}/health", timeout=30)',
2891
+ ' assert response.status_code == 200, f"expected 200, got {response.status_code}"',
2892
+ '',
2893
+ '',
2894
+ '# The test function MUST be called: TestSprite executes this file top to',
2895
+ '# bottom, so a defined-but-never-called function would pass vacuously.',
2896
+ 'test_health_endpoint()',
2897
+ '',
2898
+ ].join('\n');
2899
+ payload = { type: 'backend', language: 'python', code };
2900
+ body = code;
2901
+ }
2902
+ if (opts.out !== undefined) {
2903
+ const resolved = isAbsolute(opts.out) ? opts.out : resolve(process.cwd(), opts.out);
2904
+ // Never clobber silently: scaffolds are starting points the user edits, so
2905
+ // an accidental re-run must not erase their work. --force opts in.
2906
+ if (!opts.force && existsSync(resolved)) {
2907
+ throw localValidationError('out', `already exists: ${resolved}. Pass --force to overwrite`);
2908
+ }
2909
+ const sink = openOutputFile(opts.out); // reuses the directory/parent guards
2910
+ const fileOut = makeFileOutput(opts.output, sink);
2911
+ await fileOut.writeChunk(body);
2912
+ await closeOutputFile(sink, true);
2913
+ stderrFn(`Scaffold written to ${resolved}`);
2914
+ return payload;
2915
+ }
2916
+ // No --out: the scaffold body IS the stdout payload (`> plan.json` works).
2917
+ out.print(payload, () => body.trimEnd());
2918
+ return payload;
2480
2919
  }
2481
2920
  export async function runSteps(opts, deps = {}) {
2482
2921
  const out = makeOutput(opts.output, deps);
@@ -2591,12 +3030,20 @@ export function parseDuration(raw, now = new Date()) {
2591
3030
  const hourMatch = /^(\d+)h$/i.exec(raw);
2592
3031
  if (hourMatch) {
2593
3032
  const hours = Number(hourMatch[1]);
2594
- return new Date(now.getTime() - hours * 60 * 60 * 1000).toISOString();
3033
+ const result = new Date(now.getTime() - hours * 60 * 60 * 1000);
3034
+ if (!Number.isFinite(result.getTime())) {
3035
+ throw localValidationError('since', 'duration is too large; maximum is ~1141552511h');
3036
+ }
3037
+ return result.toISOString();
2595
3038
  }
2596
3039
  const dayMatch = /^(\d+)d$/i.exec(raw);
2597
3040
  if (dayMatch) {
2598
3041
  const days = Number(dayMatch[1]);
2599
- return new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString();
3042
+ const result = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
3043
+ if (!Number.isFinite(result.getTime())) {
3044
+ throw localValidationError('since', 'duration is too large; maximum is ~47564688d');
3045
+ }
3046
+ return result.toISOString();
2600
3047
  }
2601
3048
  // Pass-through: ISO timestamp or epoch value — server validates.
2602
3049
  return raw;
@@ -2616,7 +3063,10 @@ export async function runResultHistory(opts, deps = {}) {
2616
3063
  // configured (codex round-2), matching validatePaginationFlags ordering
2617
3064
  // in `test list` / `project list`.
2618
3065
  if (opts.pageSize !== undefined) {
2619
- if (!Number.isFinite(opts.pageSize) || opts.pageSize < 1 || opts.pageSize > 100) {
3066
+ if (!Number.isFinite(opts.pageSize) || !Number.isInteger(opts.pageSize)) {
3067
+ throw localValidationError('page-size', 'must be an integer between 1 and 100');
3068
+ }
3069
+ if (opts.pageSize < 1 || opts.pageSize > 100) {
2620
3070
  throw localValidationError('page-size', 'must be between 1 and 100');
2621
3071
  }
2622
3072
  }
@@ -2694,6 +3144,13 @@ const RUN_HISTORY_TABLE_COL_WIDTHS = {
2694
3144
  * out (dogfood 2026-06-04). `--output json` carries the full text.
2695
3145
  */
2696
3146
  const DESC_COL_MAX = 60;
3147
+ /**
3148
+ * Cap, in chars, for the one-line `error:` sub-line under a failed step row
3149
+ * in `renderStepsText`. Long enough for a full assertion message, short
3150
+ * enough that a stack-trace blob can't flood the table. Full text is in
3151
+ * `--output json`.
3152
+ */
3153
+ const ERROR_SUBLINE_MAX = 200;
2697
3154
  /** Max chars to show in the TARGETURL sub-line (excess truncated with …). */
2698
3155
  const HISTORY_TARGET_URL_MAX = 80;
2699
3156
  /**
@@ -3128,6 +3585,33 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
3128
3585
  lines.push(`dashboard ${run.dashboardUrl}`);
3129
3586
  return lines.join('\n');
3130
3587
  }
3588
+ /**
3589
+ * Best-effort resolve whether a finished run's test is a backend test, for the
3590
+ * text run-card's step line + failure hint only (DEV-282). Returns true with no
3591
+ * network call when already known (create-chain `--type`, or the BE wait
3592
+ * fallback fired). Otherwise, in TEXT mode only, issues one `GET /tests/{id}`;
3593
+ * any error → false (render the numeric step summary as before). JSON mode
3594
+ * never probes — its envelope carries `stepSummary` verbatim and has no
3595
+ * "n/a (backend)" concept, so it is already correct.
3596
+ *
3597
+ * This closes the standalone-path gap: `test run <id>` / `test wait <run-id>`
3598
+ * never supply a type hint, and now that BE run rows finalize server-side
3599
+ * (backend-v2.0 #551/#555) the wait fallback rarely fires — so a backend run
3600
+ * card would otherwise show a misleading `steps 0/0 (passed=0, failed=0)`.
3601
+ */
3602
+ async function resolveRunCardIsBackend(client, testId, output, alreadyKnown) {
3603
+ if (alreadyKnown)
3604
+ return true;
3605
+ if (output === 'json' || !testId)
3606
+ return false;
3607
+ try {
3608
+ const test = await client.get(`/tests/${encodeURIComponent(testId)}`);
3609
+ return test.type === 'backend';
3610
+ }
3611
+ catch {
3612
+ return false; // best-effort — fall back to the numeric step summary.
3613
+ }
3614
+ }
3131
3615
  /**
3132
3616
  * Render a `TriggerRunResponse` (no-wait path) to human-readable text.
3133
3617
  */
@@ -3263,7 +3747,8 @@ export async function runTestRun(opts, deps = {}) {
3263
3747
  }
3264
3748
  stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}, ` +
3265
3749
  `target: ${inFlightRun.targetUrl}). ` +
3266
- `Attaching to that run's --wait poll instead of creating a new one.`);
3750
+ `Attaching to that run's --wait poll instead of creating a new one. ` +
3751
+ `To stop it instead: testsprite test cancel ${currentRunId}`);
3267
3752
  triggerResponse = {
3268
3753
  runId: currentRunId,
3269
3754
  status: 'queued',
@@ -3289,11 +3774,15 @@ export async function runTestRun(opts, deps = {}) {
3289
3774
  }
3290
3775
  // Auto-resume but emit a stronger advisory so the caller is aware
3291
3776
  // they are attaching to the project default.
3777
+ // SIG-9 (DEV-331 final): the in-flight run is NOT auto-cancelled —
3778
+ // name the real `test cancel` command instead of the old (false)
3779
+ // "cancel with Ctrl-C" claim.
3292
3780
  stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
3293
3781
  (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
3294
3782
  `). Auto-resuming wait on in-flight run. ` +
3295
- `If you needed a specific target URL, cancel with Ctrl-C and ` +
3296
- `re-trigger with --target-url.`);
3783
+ `If you needed a specific target URL, cancel it with ` +
3784
+ `testsprite test cancel ${currentRunId}, or re-trigger with ` +
3785
+ `--target-url after it finishes.`);
3297
3786
  triggerResponse = {
3298
3787
  runId: currentRunId,
3299
3788
  status: 'queued',
@@ -3349,6 +3838,7 @@ export async function runTestRun(opts, deps = {}) {
3349
3838
  finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
3350
3839
  timeoutSeconds: opts.timeoutSeconds,
3351
3840
  sleep: deps.sleep,
3841
+ shutdown: shutdownOf(deps),
3352
3842
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
3353
3843
  onTick: (run, elapsedMs) => {
3354
3844
  const elapsed = Math.round(elapsedMs / 1000);
@@ -3361,11 +3851,33 @@ export async function runTestRun(opts, deps = {}) {
3361
3851
  catch (err) {
3362
3852
  if (err instanceof TimeoutError) {
3363
3853
  ticker.finalize(`Run ${triggerResponse.runId} — timed out after ${opts.timeoutSeconds}s`);
3854
+ // Mirror the RequestTimeoutError path: emit a partial run to stdout so
3855
+ // JSON consumers and AI agents can grab the runId and chain into
3856
+ // `testsprite test wait <runId>` without parsing the stderr error envelope.
3857
+ const timeoutPartial = {
3858
+ runId: triggerResponse.runId,
3859
+ status: 'running',
3860
+ enqueuedAt: triggerResponse.enqueuedAt,
3861
+ codeVersion: triggerResponse.codeVersion,
3862
+ targetUrl: triggerResponse.targetUrl || null,
3863
+ };
3864
+ printRunOrChain(out, timeoutPartial, opts.createContext, data => {
3865
+ const p = data;
3866
+ const lines = [
3867
+ `runId ${p.runId}`,
3868
+ `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
3869
+ ];
3870
+ if (p.targetUrl)
3871
+ lines.push(`targetUrl ${p.targetUrl}`);
3872
+ lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
3873
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
3874
+ return lines.join('\n');
3875
+ });
3364
3876
  throw ApiError.fromEnvelope({
3365
3877
  error: {
3366
3878
  code: 'UNSUPPORTED', // exit 7 per errors.md
3367
3879
  message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}.`,
3368
- nextAction: `Resume polling: testsprite test wait ${triggerResponse.runId}`,
3880
+ nextAction: `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
3369
3881
  requestId: 'local',
3370
3882
  details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
3371
3883
  },
@@ -3393,10 +3905,36 @@ export async function runTestRun(opts, deps = {}) {
3393
3905
  if (p.targetUrl)
3394
3906
  lines.push(`targetUrl ${p.targetUrl}`);
3395
3907
  lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
3908
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
3396
3909
  return lines.join('\n');
3397
3910
  });
3398
3911
  stderrFn(`Run ${triggerResponse.runId} is still in progress (request timed out). ` +
3399
- `Re-attach with: testsprite test wait ${triggerResponse.runId}`);
3912
+ `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
3913
+ throw err;
3914
+ }
3915
+ // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
3916
+ // envelope shape as the timeout paths so stdout stays parseable, plus the
3917
+ // honest "keeps running and billing" stderr line. Rethrow → index.ts
3918
+ // renders the INTERRUPTED envelope and exits 128+signum.
3919
+ if (err instanceof InterruptError) {
3920
+ ticker.finalize(`Run ${triggerResponse.runId} — interrupted (${err.signal})`);
3921
+ const partial = {
3922
+ runId: triggerResponse.runId,
3923
+ status: 'running',
3924
+ enqueuedAt: triggerResponse.enqueuedAt,
3925
+ codeVersion: triggerResponse.codeVersion,
3926
+ targetUrl: triggerResponse.targetUrl || null,
3927
+ };
3928
+ printRunOrChain(out, partial, opts.createContext, data => {
3929
+ const p = data;
3930
+ const lines = [`runId ${p.runId}`, `status ${p.status} (interrupted)`];
3931
+ if (p.targetUrl)
3932
+ lines.push(`targetUrl ${p.targetUrl}`);
3933
+ lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
3934
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
3935
+ return lines.join('\n');
3936
+ });
3937
+ stderrFn(interruptDetachMessage(err, [triggerResponse.runId]));
3400
3938
  throw err;
3401
3939
  }
3402
3940
  ticker.finalize();
@@ -3405,20 +3943,20 @@ export async function runTestRun(opts, deps = {}) {
3405
3943
  const elapsed = Math.round((Date.now() - startMs) / 1000);
3406
3944
  const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
3407
3945
  ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
3408
- printRunOrChain(out, withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), opts.createContext, data => renderRunResponseText(data, {
3409
- // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs).
3410
- // This ensures fast BE runs terminal on first poll still render n/a.
3411
- isBackend: beFallbackUsed || opts.type === 'backend',
3412
- }));
3946
+ // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs); on
3947
+ // the standalone `test run <id>` path neither is set, so probe the test type
3948
+ // once (text mode only, best-effort) — DEV-282.
3949
+ const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
3950
+ printRunOrChain(out, withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), opts.createContext, data => renderRunResponseText(data, { isBackend }));
3413
3951
  // Surface the trigger requestId under --verbose/--debug or JSON mode so
3414
3952
  // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
3415
3953
  // JSON mode always emits to stderr — it never pollutes stdout).
3416
3954
  if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
3417
3955
  stderrFn(`requestId: ${triggerRequestId}`);
3418
3956
  if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
3419
- // BE runs (resolved via the testId fallback) have no run-scoped artifact
3420
- // bundle — their failure bundle is addressed by testId, not runId.
3421
- stderrFn(beFallbackUsed
3957
+ // BE runs have no run-scoped artifact bundle — their failure bundle is
3958
+ // addressed by testId, not runId.
3959
+ stderrFn(isBackend
3422
3960
  ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
3423
3961
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
3424
3962
  }
@@ -3430,6 +3968,325 @@ export async function runTestRun(opts, deps = {}) {
3430
3968
  }
3431
3969
  return finalRun;
3432
3970
  }
3971
+ /**
3972
+ * `test wait <run-id...>` with two or more ids: attach to N already-dispatched
3973
+ * runs in ONE invocation. This closes the loop the CLI itself opens: every
3974
+ * batch/closure timeout prints one `testsprite test wait <runId>` hint PER
3975
+ * member, which previously meant N sequential blocking invocations. The runs
3976
+ * are polled concurrently under a bounded pool with ONE shared deadline
3977
+ * (`--timeout` bounds the whole invocation, not each member), each member's
3978
+ * poll is total (a transient error on one run never discards the others), and
3979
+ * the exit code is the worst status across members: auth errors escalate to
3980
+ * exit 3, any timeout or poll error exits 7, any non-passed terminal exits 1.
3981
+ * Distinct from a run journal (issue #80): no persistence, just N known ids.
3982
+ */
3983
+ export async function runTestWaitMany(opts, deps = {}) {
3984
+ const out = makeOutput(opts.output, deps);
3985
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
3986
+ if (opts.dryRun) {
3987
+ emitDryRunBanner(stderrFn);
3988
+ const results = opts.runIds.map(runId => ({
3989
+ runId,
3990
+ status: 'passed',
3991
+ }));
3992
+ const payload = {
3993
+ results,
3994
+ summary: { total: results.length, passed: results.length, failed: 0, timedOut: 0, errors: 0 },
3995
+ };
3996
+ out.print(payload, () => results.map(r => `${r.runId} ${r.status}`).join('\n'));
3997
+ return payload;
3998
+ }
3999
+ const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
4000
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
4001
+ // One shared deadline across every member (the whole point of the shared
4002
+ // pool: `--timeout 600` means the invocation ends within ~600s, not
4003
+ // 600s x ceil(N/concurrency)).
4004
+ const deadlineMs = Date.now() + opts.timeoutSeconds * 1000;
4005
+ const pollOne = async (runId) => {
4006
+ // A member dequeued AFTER the shared deadline has passed must not be
4007
+ // granted a fresh minimum poll window (with --max-concurrency 1 that
4008
+ // would extend the invocation by ~1s per queued run past --timeout).
4009
+ const remainingSeconds = Math.ceil((deadlineMs - Date.now()) / 1000);
4010
+ if (remainingSeconds <= 0)
4011
+ return { kind: 'timeout' };
4012
+ const resolveAlternate = makeBackendWaitFallback({
4013
+ client,
4014
+ resolveTestId: run => run.testId,
4015
+ resolveNotBefore: run => run.createdAt,
4016
+ onResolved: () => undefined,
4017
+ });
4018
+ try {
4019
+ const run = await pollRunUntilTerminal(client, runId, {
4020
+ timeoutSeconds: remainingSeconds,
4021
+ sleep: deps.sleep,
4022
+ shutdown: shutdownOf(deps),
4023
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4024
+ onTick: (run, elapsedMs) => {
4025
+ const elapsed = Math.round(elapsedMs / 1000);
4026
+ ticker.update(`Run ${run.runId} — ${run.status} (elapsed=${elapsed}s)`);
4027
+ },
4028
+ resolveAlternate,
4029
+ });
4030
+ return { kind: 'result', run };
4031
+ }
4032
+ catch (err) {
4033
+ if (err instanceof TimeoutError)
4034
+ return { kind: 'timeout' };
4035
+ if (err instanceof RequestTimeoutError)
4036
+ throw err;
4037
+ // Interrupt must reject the fan-out (handled at the collect point), not
4038
+ // be flattened into a per-member 'error' outcome that would swallow the
4039
+ // 128+signum exit (DEV-331).
4040
+ if (err instanceof InterruptError)
4041
+ throw err;
4042
+ if (err instanceof ApiError)
4043
+ return { kind: 'error', code: err.code, exitCode: err.exitCode };
4044
+ return { kind: 'error', code: 'TRANSPORT', exitCode: 10 };
4045
+ }
4046
+ };
4047
+ const outcomes = new Map();
4048
+ let inFlight = 0;
4049
+ let nextIdx = 0;
4050
+ try {
4051
+ await new Promise((resolve, reject) => {
4052
+ const startNext = () => {
4053
+ while (inFlight < opts.maxConcurrency && nextIdx < opts.runIds.length) {
4054
+ const runId = opts.runIds[nextIdx++];
4055
+ inFlight++;
4056
+ pollOne(runId)
4057
+ .then(outcome => {
4058
+ outcomes.set(runId, outcome);
4059
+ inFlight--;
4060
+ startNext();
4061
+ if (inFlight === 0 && nextIdx >= opts.runIds.length)
4062
+ resolve();
4063
+ })
4064
+ // pollOne is total except for RequestTimeoutError (handled below).
4065
+ .catch(reject);
4066
+ }
4067
+ };
4068
+ startNext();
4069
+ if (opts.runIds.length === 0)
4070
+ resolve();
4071
+ });
4072
+ }
4073
+ catch (fanOutErr) {
4074
+ if (fanOutErr instanceof RequestTimeoutError || fanOutErr instanceof InterruptError) {
4075
+ // Same contract as the batch pollers: leave stdout parseable before
4076
+ // exiting. Members that already settled keep their real status; only
4077
+ // the still-unfinished ids are marked running and named in the hint
4078
+ // (re-attaching to an already-terminal run would be a wasted command).
4079
+ ticker.finalize(fanOutErr instanceof InterruptError
4080
+ ? `Multi-run wait — interrupted (${fanOutErr.signal})`
4081
+ : 'Multi-run wait — request timed out');
4082
+ const partial = {
4083
+ results: opts.runIds.map((runId) => {
4084
+ const outcome = outcomes.get(runId);
4085
+ if (outcome === undefined)
4086
+ return { runId, status: 'running' };
4087
+ if (outcome.kind === 'timeout')
4088
+ return { runId, status: 'timeout' };
4089
+ if (outcome.kind === 'error')
4090
+ return { runId, status: `error:${outcome.code}` };
4091
+ return { runId, status: outcome.run.status, testId: outcome.run.testId };
4092
+ }),
4093
+ summary: { total: opts.runIds.length },
4094
+ };
4095
+ out.print(partial, () => partial.results.map(r => `${r.runId} ${r.status}`).join('\n'));
4096
+ const unfinished = partial.results
4097
+ .filter(r => r.status === 'running' || r.status === 'timeout')
4098
+ .map(r => r.runId);
4099
+ if (unfinished.length > 0) {
4100
+ if (fanOutErr instanceof InterruptError) {
4101
+ stderrFn(interruptDetachMessage(fanOutErr, unfinished));
4102
+ }
4103
+ else {
4104
+ stderrFn(`Re-attach with: testsprite test wait ${unfinished.join(' ')}, or cancel with: testsprite test cancel ${unfinished.join(' ')}`);
4105
+ }
4106
+ }
4107
+ }
4108
+ throw fanOutErr;
4109
+ }
4110
+ ticker.finalize();
4111
+ const results = opts.runIds.map(runId => {
4112
+ const outcome = outcomes.get(runId);
4113
+ if (outcome === undefined || outcome.kind === 'timeout')
4114
+ return { runId, status: 'timeout' };
4115
+ if (outcome.kind === 'error')
4116
+ return { runId, status: `error:${outcome.code}` };
4117
+ return { runId, status: outcome.run.status, testId: outcome.run.testId };
4118
+ });
4119
+ const passed = results.filter(r => r.status === 'passed').length;
4120
+ const timedOut = results.filter(r => r.status === 'timeout').length;
4121
+ const errors = results.filter(r => r.status.startsWith('error:')).length;
4122
+ const failed = results.length - passed - timedOut - errors;
4123
+ const payload = {
4124
+ results,
4125
+ summary: { total: results.length, passed, failed, timedOut, errors },
4126
+ };
4127
+ out.print(payload, () => [
4128
+ ...results.map(r => `${r.runId} ${r.status}`),
4129
+ '',
4130
+ `${passed}/${results.length} passed, ${failed} failed/blocked, ${timedOut} timed out, ${errors} poll errors`,
4131
+ ].join('\n'));
4132
+ // Every member that did not reach a terminal verdict is re-attachable:
4133
+ // timeouts (still running server-side) and poll errors (e.g. a transient
4134
+ // transport failure) both belong in the hint; terminal runs do not.
4135
+ const unfinishedIds = results
4136
+ .filter(r => r.status === 'timeout' || r.status.startsWith('error:'))
4137
+ .map(r => r.runId);
4138
+ if (unfinishedIds.length > 0) {
4139
+ stderrFn(`Re-attach with: testsprite test wait ${unfinishedIds.join(' ')}, or cancel with: testsprite test cancel ${unfinishedIds.join(' ')}`);
4140
+ }
4141
+ // Worst-status exit: auth escalates (a rejected key fails every member the
4142
+ // same way), then timeout/poll-error (7, resumable), then plain failure (1).
4143
+ const authError = [...outcomes.values()].find(o => o.kind === 'error' &&
4144
+ (o.code === 'AUTH_REQUIRED' || o.code === 'AUTH_INVALID' || o.code === 'AUTH_FORBIDDEN'));
4145
+ if (authError !== undefined && authError.kind === 'error') {
4146
+ throw new CLIError(`Multi-run wait: authentication failed (${authError.code})`, authError.exitCode);
4147
+ }
4148
+ if (timedOut > 0 || errors > 0) {
4149
+ throw new CLIError(`Multi-run wait: ${timedOut} timed out, ${errors} poll error(s) out of ${results.length} runs`, 7);
4150
+ }
4151
+ if (failed > 0) {
4152
+ throw new CLIError(`Multi-run wait: ${failed} run(s) finished non-passed`, 1);
4153
+ }
4154
+ return payload;
4155
+ }
4156
+ /**
4157
+ * `test cancel <run-id...>` — DEV-331 piece 3.
4158
+ *
4159
+ * User-initiated cancel of one or more queued/running runs via
4160
+ * `POST /api/cli/v1/runs/{runId}/cancel`. Naturally idempotent (D10): a
4161
+ * repeat cancel of the same run is a 200 `alreadyCancelled` success, not an
4162
+ * error. Dispatches serially (per-id volume is tiny — no batch endpoint,
4163
+ * D8 "Batch-level cancel endpoint... YAGNI").
4164
+ *
4165
+ * Single id: renders the returned run card (`status cancelled`); an
4166
+ * `alreadyCancelled` response adds an `[advisory]` line. Exit code mirrors
4167
+ * the server response directly — 0 on success (fresh or already-cancelled),
4168
+ * 4 on 404 (unknown/cross-tenant), 6 on 409 (already terminal).
4169
+ *
4170
+ * Multi-id: prints a `{cancelled, alreadyCancelled, conflicts, notFound}`
4171
+ * summary. Exit precedence (CXL-11): any `notFound` → 4 (outranks conflict —
4172
+ * it signals a caller bug, wrong id/tenant); else any `conflicts` → 6; else 0.
4173
+ */
4174
+ export async function runTestCancel(opts, deps = {}) {
4175
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4176
+ const out = makeOutput(opts.output, deps);
4177
+ const client = makeClient(opts, deps);
4178
+ if (opts.dryRun) {
4179
+ emitDryRunBanner(stderrFn);
4180
+ }
4181
+ if (opts.runIds.length === 1) {
4182
+ const runId = opts.runIds[0];
4183
+ const result = await client.cancelRun(runId);
4184
+ out.print(result, data => {
4185
+ const r = data;
4186
+ return renderRunResponseText(r);
4187
+ });
4188
+ if (result.alreadyCancelled) {
4189
+ stderrFn(`[advisory] run ${runId} was already cancelled`);
4190
+ }
4191
+ return result;
4192
+ }
4193
+ const rows = [];
4194
+ for (const runId of opts.runIds) {
4195
+ try {
4196
+ const result = await client.cancelRun(runId);
4197
+ rows.push({
4198
+ runId,
4199
+ status: result.alreadyCancelled ? 'alreadyCancelled' : 'cancelled',
4200
+ });
4201
+ }
4202
+ catch (err) {
4203
+ if (err instanceof ApiError && err.code === 'NOT_FOUND') {
4204
+ rows.push({ runId, status: 'notFound' });
4205
+ continue;
4206
+ }
4207
+ if (err instanceof ApiError && err.code === 'CONFLICT') {
4208
+ const conflictStatus = err.getDetail('status', (v) => typeof v === 'string') ?? 'unknown';
4209
+ rows.push({ runId, status: 'conflict', conflictStatus });
4210
+ continue;
4211
+ }
4212
+ const message = err instanceof Error ? err.message : String(err);
4213
+ rows.push({ runId, status: 'error', error: message });
4214
+ }
4215
+ }
4216
+ const errorRows = rows.filter(r => r.status === 'error');
4217
+ const summary = {
4218
+ cancelled: rows.filter(r => r.status === 'cancelled').map(r => r.runId),
4219
+ alreadyCancelled: rows.filter(r => r.status === 'alreadyCancelled').map(r => r.runId),
4220
+ conflicts: rows
4221
+ .filter(r => r.status === 'conflict')
4222
+ .map(r => ({ runId: r.runId, status: r.conflictStatus ?? 'unknown' })),
4223
+ notFound: rows.filter(r => r.status === 'notFound').map(r => r.runId),
4224
+ errors: errorRows.map(r => ({ runId: r.runId, message: r.error ?? 'unknown error' })),
4225
+ };
4226
+ out.print(summary, data => renderCancelSummaryText(data));
4227
+ const parts = [
4228
+ `${summary.cancelled.length} cancelled`,
4229
+ `${summary.alreadyCancelled.length} already cancelled`,
4230
+ ];
4231
+ if (summary.conflicts.length > 0)
4232
+ parts.push(`${summary.conflicts.length} conflict`);
4233
+ if (summary.notFound.length > 0)
4234
+ parts.push(`${summary.notFound.length} not found`);
4235
+ if (errorRows.length > 0)
4236
+ parts.push(`${errorRows.length} error`);
4237
+ stderrFn(`Cancel summary: ${parts.join(', ')}.`);
4238
+ // Exit precedence (CXL-11): notFound outranks conflict — a caller-side bug
4239
+ // (wrong id / wrong tenant) is more actionable to surface than "it already
4240
+ // finished". A bare transport/auth error on any member also fails loudly
4241
+ // rather than being silently absorbed into a 0 exit.
4242
+ if (summary.notFound.length > 0) {
4243
+ throw new CLIError(`${summary.notFound.length} run id${summary.notFound.length !== 1 ? 's' : ''} not found: ${summary.notFound.join(' ')}`, 4);
4244
+ }
4245
+ if (errorRows.length > 0) {
4246
+ throw new CLIError(`${errorRows.length} cancel request${errorRows.length !== 1 ? 's' : ''} failed: ${errorRows.map(r => r.runId).join(' ')}`, 1);
4247
+ }
4248
+ if (summary.conflicts.length > 0) {
4249
+ throw new CLIError(`${summary.conflicts.length} run${summary.conflicts.length !== 1 ? 's' : ''} already terminal: ${summary.conflicts.map(c => `${c.runId} (${c.status})`).join(', ')}`, 6);
4250
+ }
4251
+ return summary;
4252
+ }
4253
+ function renderCancelSummaryText(summary) {
4254
+ const lines = [];
4255
+ for (const runId of summary.cancelled)
4256
+ lines.push(`${runId} cancelled`);
4257
+ for (const runId of summary.alreadyCancelled)
4258
+ lines.push(`${runId} alreadyCancelled`);
4259
+ for (const c of summary.conflicts)
4260
+ lines.push(`${c.runId} conflict (${c.status})`);
4261
+ for (const runId of summary.notFound)
4262
+ lines.push(`${runId} notFound`);
4263
+ for (const e of summary.errors ?? [])
4264
+ lines.push(`${e.runId} error (${e.message})`);
4265
+ return lines.join('\n');
4266
+ }
4267
+ export function createTestCancelCommand(deps) {
4268
+ const cancel = new Command('cancel');
4269
+ cancel
4270
+ .argument('<run-id...>', 'one or more run ids to cancel')
4271
+ .description('Cancel one or more queued/running runs.\n' +
4272
+ '\nCtrl-C during --wait only detaches — it does NOT cancel the server-side\n' +
4273
+ 'run. This is the real stop button. No refund is issued for the credits\n' +
4274
+ 'already charged at trigger time (D3); an in-flight Lambda finishes on its\n' +
4275
+ 'own and its result is discarded once cancelled.\n' +
4276
+ '\nExit codes:\n' +
4277
+ ' 0 cancelled (fresh or already-cancelled — naturally idempotent)\n' +
4278
+ ' 4 run id not found (single id), or ANY id not found (multi-id — outranks conflict)\n' +
4279
+ ' 6 run already terminal (passed/failed/blocked) — single id: 409; multi-id: any conflict\n' +
4280
+ '\nMulti-id output is a summary: {cancelled, alreadyCancelled, conflicts, notFound}.')
4281
+ .addHelpText('after', GLOBAL_OPTS_HINT)
4282
+ .action(async (runIds, _cmdOpts, command) => {
4283
+ await runTestCancel({
4284
+ ...resolveCommonOptions(command),
4285
+ runIds,
4286
+ }, deps);
4287
+ });
4288
+ return cancel;
4289
+ }
3433
4290
  /**
3434
4291
  * `test wait <run-id>` — M3.3 piece-3.
3435
4292
  *
@@ -3478,6 +4335,7 @@ export async function runTestWait(opts, deps = {}) {
3478
4335
  finalRun = await pollRunUntilTerminal(client, opts.runId, {
3479
4336
  timeoutSeconds: opts.timeoutSeconds,
3480
4337
  sleep: deps.sleep,
4338
+ shutdown: shutdownOf(deps),
3481
4339
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
3482
4340
  onTick: (run, elapsedMs) => {
3483
4341
  const elapsed = Math.round(elapsedMs / 1000);
@@ -3490,12 +4348,25 @@ export async function runTestWait(opts, deps = {}) {
3490
4348
  catch (err) {
3491
4349
  if (err instanceof TimeoutError) {
3492
4350
  ticker.finalize(`Run ${opts.runId} — timed out after ${opts.timeoutSeconds}s`);
3493
- throw ApiError.fromEnvelope({
3494
- error: {
3495
- code: 'UNSUPPORTED', // exit 7 per errors.md
3496
- message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${opts.runId}.`,
3497
- nextAction: `Resume polling: testsprite test wait ${opts.runId}`,
3498
- requestId: 'local',
4351
+ // Mirror the RequestTimeoutError path: emit a partial run to stdout so
4352
+ // JSON consumers and AI agents can grab the runId and chain into
4353
+ // `testsprite test wait <runId>` without parsing the stderr error envelope.
4354
+ const timeoutPartial = { runId: opts.runId, status: 'running' };
4355
+ out.print(timeoutPartial, data => {
4356
+ const p = data;
4357
+ return [
4358
+ `runId ${p.runId}`,
4359
+ `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
4360
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
4361
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
4362
+ ].join('\n');
4363
+ });
4364
+ throw ApiError.fromEnvelope({
4365
+ error: {
4366
+ code: 'UNSUPPORTED', // exit 7 per errors.md
4367
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${opts.runId}.`,
4368
+ nextAction: `Resume polling: testsprite test wait ${opts.runId}, or cancel it: testsprite test cancel ${opts.runId}`,
4369
+ requestId: 'local',
3499
4370
  details: { runId: opts.runId, timeoutSeconds: opts.timeoutSeconds },
3500
4371
  },
3501
4372
  });
@@ -3512,10 +4383,27 @@ export async function runTestWait(opts, deps = {}) {
3512
4383
  `runId ${p.runId}`,
3513
4384
  `status ${p.status} (request timed out)`,
3514
4385
  `hint Re-attach with: testsprite test wait ${p.runId}`,
4386
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
3515
4387
  ].join('\n');
3516
4388
  });
3517
4389
  stderrFn(`Run ${opts.runId} is still in progress (request timed out). ` +
3518
- `Re-attach with: testsprite test wait ${opts.runId}`);
4390
+ `Re-attach with: testsprite test wait ${opts.runId}, or cancel with: testsprite test cancel ${opts.runId}`);
4391
+ throw err;
4392
+ }
4393
+ // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
4394
+ if (err instanceof InterruptError) {
4395
+ ticker.finalize(`Run ${opts.runId} — interrupted (${err.signal})`);
4396
+ const partial = { runId: opts.runId, status: 'running' };
4397
+ out.print(partial, data => {
4398
+ const p = data;
4399
+ return [
4400
+ `runId ${p.runId}`,
4401
+ `status ${p.status} (interrupted)`,
4402
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
4403
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
4404
+ ].join('\n');
4405
+ });
4406
+ stderrFn(interruptDetachMessage(err, [opts.runId]));
3519
4407
  throw err;
3520
4408
  }
3521
4409
  ticker.finalize();
@@ -3524,11 +4412,14 @@ export async function runTestWait(opts, deps = {}) {
3524
4412
  const elapsed = Math.round((Date.now() - startMs) / 1000);
3525
4413
  const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
3526
4414
  ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
3527
- out.print(withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), data => renderRunResponseText(data, { isBackend: beFallbackUsed }));
4415
+ // `test wait` has no type hint; probe the test type once (text mode only,
4416
+ // best-effort) so a backend run's card reads `n/a (backend)` — DEV-282.
4417
+ const isBackend = await resolveRunCardIsBackend(client, finalRun.testId, opts.output, beFallbackUsed);
4418
+ out.print(withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), data => renderRunResponseText(data, { isBackend }));
3528
4419
  if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
3529
- // BE runs (resolved via the testId fallback) have no run-scoped artifact
3530
- // bundle — their failure bundle is addressed by testId, not runId.
3531
- stderrFn(beFallbackUsed
4420
+ // BE runs have no run-scoped artifact bundle — their failure bundle is
4421
+ // addressed by testId, not runId.
4422
+ stderrFn(isBackend
3532
4423
  ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
3533
4424
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
3534
4425
  }
@@ -3538,6 +4429,18 @@ export async function runTestWait(opts, deps = {}) {
3538
4429
  }
3539
4430
  return finalRun;
3540
4431
  }
4432
+ async function writeBatchJUnitReportIfRequested(opts, results) {
4433
+ if (opts.report !== 'junit' || opts.reportFile === undefined)
4434
+ return;
4435
+ const projectId = resolveBatchReportProjectId(opts, results);
4436
+ const suiteName = opts.reportSuiteName ?? `testsprite:${projectId}`;
4437
+ const xml = buildJUnitReport({
4438
+ suiteName,
4439
+ classname: projectId,
4440
+ results,
4441
+ });
4442
+ await writeJUnitReportFile(opts.reportFile, xml);
4443
+ }
3541
4444
  /**
3542
4445
  * `test run --all --project <id>` — M4 piece-2.
3543
4446
  *
@@ -3553,6 +4456,13 @@ export async function runTestRunAll(opts, deps = {}) {
3553
4456
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
3554
4457
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
3555
4458
  }
4459
+ assertJUnitReportOptions({
4460
+ report: opts.report,
4461
+ reportFile: opts.reportFile,
4462
+ reportSuiteName: opts.reportSuiteName,
4463
+ wait: opts.wait,
4464
+ batchPath: true,
4465
+ });
3556
4466
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
3557
4467
  const out = makeOutput(opts.output, deps);
3558
4468
  // --- Dry-run path ---
@@ -3574,6 +4484,9 @@ export async function runTestRunAll(opts, deps = {}) {
3574
4484
  idempotencyKey,
3575
4485
  ...(opts.wait ? { thenPoll: '/api/cli/v1/runs/<run-id>?waitSeconds=25' } : {}),
3576
4486
  };
4487
+ if (opts.report === 'junit' && opts.reportFile !== undefined) {
4488
+ await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(opts.projectId, opts.reportSuiteName));
4489
+ }
3577
4490
  out.print(batchRunSample ?? envelope);
3578
4491
  return undefined;
3579
4492
  }
@@ -3593,13 +4506,10 @@ export async function runTestRunAll(opts, deps = {}) {
3593
4506
  return dashboardUrl !== undefined ? { ...item, dashboardUrl } : item;
3594
4507
  };
3595
4508
  const idempotencyKey = opts.idempotencyKey ?? `cli-batch-run-fresh-${randomUUID()}`;
3596
- if (opts.idempotencyKey === undefined && opts.debug) {
4509
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
3597
4510
  stderrFn(`idempotency-key: ${idempotencyKey}`);
3598
4511
  }
3599
- if (opts.idempotencyKey === undefined && opts.verbose) {
3600
- stderrFn(`[verbose] auto-minted idempotency-key: ${idempotencyKey}`);
3601
- }
3602
- // Resolve testIds: fetch all BE tests in the project, apply --filter.
4512
+ // Resolve testIds: fetch all tests in the project, apply --filter.
3603
4513
  let testIds;
3604
4514
  if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
3605
4515
  // We need to resolve the full test set to apply the name filter.
@@ -3627,7 +4537,8 @@ export async function runTestRunAll(opts, deps = {}) {
3627
4537
  }
3628
4538
  stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${opts.projectId} for batch run.`);
3629
4539
  }
3630
- // When no --filter, omit testIds → server runs ALL BE tests in the project.
4540
+ // When no --filter, omit testIds → server runs ALL tests in the project
4541
+ // (BE tests on the legacy V2 wave engine; FE + BE on the V3 unified engine).
3631
4542
  const batchResp = await client.triggerBatchRunFresh({
3632
4543
  projectId: opts.projectId,
3633
4544
  ...(testIds !== undefined ? { testIds } : {}),
@@ -3817,7 +4728,20 @@ export async function runTestRunAll(opts, deps = {}) {
3817
4728
  // NOTE: batchDeadlineMs is set in the D3 deferred-retry loop above and reused here.
3818
4729
  async function pollFreshAccepted(entry) {
3819
4730
  const runId = entry.runId;
3820
- const remainingSeconds = Math.max(1, Math.ceil((batchDeadlineMs - Date.now()) / 1000));
4731
+ const remainingMs = batchDeadlineMs - Date.now();
4732
+ if (remainingMs <= 0) {
4733
+ return {
4734
+ testId: entry.testId,
4735
+ runId,
4736
+ status: 'timeout',
4737
+ error: {
4738
+ code: 'UNSUPPORTED',
4739
+ message: `Timed out after ${opts.timeoutSeconds}s`,
4740
+ exitCode: 7,
4741
+ },
4742
+ };
4743
+ }
4744
+ const remainingSeconds = Math.ceil(remainingMs / 1000);
3821
4745
  const resolveAlternate = makeBackendWaitFallback({
3822
4746
  client,
3823
4747
  resolveTestId: () => entry.testId,
@@ -3828,6 +4752,7 @@ export async function runTestRunAll(opts, deps = {}) {
3828
4752
  const finalRun = await pollRunUntilTerminal(client, runId, {
3829
4753
  timeoutSeconds: remainingSeconds,
3830
4754
  sleep: deps.sleep,
4755
+ shutdown: shutdownOf(deps),
3831
4756
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
3832
4757
  onTick: (run, elapsedMs) => {
3833
4758
  const elapsed = Math.round(elapsedMs / 1000);
@@ -3836,7 +4761,12 @@ export async function runTestRunAll(opts, deps = {}) {
3836
4761
  },
3837
4762
  resolveAlternate,
3838
4763
  });
3839
- return { testId: entry.testId, runId, status: finalRun.status };
4764
+ return {
4765
+ testId: entry.testId,
4766
+ runId,
4767
+ projectId: finalRun.projectId,
4768
+ status: finalRun.status,
4769
+ };
3840
4770
  }
3841
4771
  catch (err) {
3842
4772
  if (err instanceof TimeoutError) {
@@ -3851,6 +4781,27 @@ export async function runTestRunAll(opts, deps = {}) {
3851
4781
  },
3852
4782
  };
3853
4783
  }
4784
+ // Interrupt must reject the fan-out (the collect point below prints the
4785
+ // partial for every dispatched run), never flatten into a per-member
4786
+ // outcome that would swallow the 128+signum exit (DEV-331).
4787
+ if (err instanceof InterruptError)
4788
+ throw err;
4789
+ if (err instanceof RequestTimeoutError) {
4790
+ // Client-side per-request timeout during polling — classify as timeout
4791
+ // (exit 7) so the fan-out completes and stdout carries every runId.
4792
+ // Without this, RequestTimeoutError rejects the fan-out before out.print(),
4793
+ // leaving JSON consumers with empty stdout (mirrors create-batch --run).
4794
+ return {
4795
+ testId: entry.testId,
4796
+ runId,
4797
+ status: 'timeout',
4798
+ error: {
4799
+ code: 'UNSUPPORTED',
4800
+ message: err.message,
4801
+ exitCode: err.exitCode,
4802
+ },
4803
+ };
4804
+ }
3854
4805
  if (err instanceof ApiError) {
3855
4806
  // Preserve the real exit code + envelope (AUTH_INVALID=3, NOT_FOUND=4,
3856
4807
  // RATE_LIMITED=11, …) instead of flattening every member failure to 1
@@ -3868,26 +4819,43 @@ export async function runTestRunAll(opts, deps = {}) {
3868
4819
  // Bounded concurrency fan-out
3869
4820
  let pollIdx = 0;
3870
4821
  let inFlight = 0;
3871
- await new Promise((resolve, reject) => {
3872
- function startNext() {
3873
- while (inFlight < concurrencyLimit && pollIdx < pollable.length) {
3874
- const entry = pollable[pollIdx++];
3875
- inFlight++;
3876
- pollFreshAccepted(entry)
3877
- .then(result => {
3878
- freshRunResults.push(result);
3879
- inFlight--;
3880
- startNext();
3881
- if (inFlight === 0 && pollIdx >= pollable.length)
3882
- resolve();
3883
- })
3884
- .catch(reject);
4822
+ try {
4823
+ await new Promise((resolve, reject) => {
4824
+ function startNext() {
4825
+ while (inFlight < concurrencyLimit && pollIdx < pollable.length) {
4826
+ const entry = pollable[pollIdx++];
4827
+ inFlight++;
4828
+ pollFreshAccepted(entry)
4829
+ .then(result => {
4830
+ freshRunResults.push(result);
4831
+ inFlight--;
4832
+ startNext();
4833
+ if (inFlight === 0 && pollIdx >= pollable.length)
4834
+ resolve();
4835
+ })
4836
+ .catch(reject);
4837
+ }
3885
4838
  }
3886
- }
3887
- startNext();
3888
- if (pollable.length === 0)
3889
- resolve();
3890
- });
4839
+ startNext();
4840
+ if (pollable.length === 0)
4841
+ resolve();
4842
+ });
4843
+ }
4844
+ catch (fanOutErr) {
4845
+ // Graceful detach (DEV-331): stdout stays parseable — settled members
4846
+ // keep their real status, unfinished ones are marked running — and the
4847
+ // honest stderr line names every runId still executing (and billing).
4848
+ if (fanOutErr instanceof InterruptError) {
4849
+ ticker.finalize(`Batch run — interrupted (${fanOutErr.signal})`);
4850
+ const settled = new Map(freshRunResults.map(r => [r.runId, r]));
4851
+ const partialResults = pollable.map((e) => settled.get(e.runId) ?? { testId: e.testId, runId: e.runId, status: 'running' });
4852
+ out.print({ accepted: partialResults, conflicts, deferred, skippedFrontend, skippedIntegration }, () => partialResults.map(r => `${r.runId} ${r.status}`).join('\n'));
4853
+ const unfinished = pollable.filter(e => !settled.has(e.runId)).map(e => e.runId);
4854
+ if (unfinished.length > 0)
4855
+ stderrFn(interruptDetachMessage(fanOutErr, unfinished));
4856
+ }
4857
+ throw fanOutErr;
4858
+ }
3891
4859
  ticker.finalize();
3892
4860
  const passed = freshRunResults.filter(r => r.status === 'passed').length;
3893
4861
  const failed = freshRunResults.filter(r => r.status !== 'passed' && r.status !== 'timeout').length;
@@ -3911,6 +4879,7 @@ export async function runTestRunAll(opts, deps = {}) {
3911
4879
  total: pollable.length,
3912
4880
  },
3913
4881
  };
4882
+ await writeBatchJUnitReportIfRequested(opts, freshRunResults);
3914
4883
  out.print(jsonPayload);
3915
4884
  // Rate-deferred tests were never dispatched → the batch is incomplete (exit 7),
3916
4885
  // mirroring `test rerun --all`. Checked before the failed-run throw so the
@@ -3927,7 +4896,10 @@ export async function runTestRunAll(opts, deps = {}) {
3927
4896
  error: {
3928
4897
  code: 'UNSUPPORTED',
3929
4898
  message: `${timedOut} run${timedOut !== 1 ? 's' : ''} timed out.`,
3930
- nextAction: timedOutRunIds.map(rid => `Resume: testsprite test wait ${rid}`).join('\n'),
4899
+ nextAction: [
4900
+ ...timedOutRunIds.map(rid => `Resume: testsprite test wait ${rid}`),
4901
+ ...timedOutRunIds.map(rid => `Cancel: testsprite test cancel ${rid}`),
4902
+ ].join('\n'),
3931
4903
  requestId: 'local',
3932
4904
  details: { timedOutRunIds, timeoutSeconds: opts.timeoutSeconds },
3933
4905
  },
@@ -3974,6 +4946,15 @@ export async function runTestRerun(opts, deps = {}) {
3974
4946
  if (opts.testIds.length === 0 && !opts.all) {
3975
4947
  throw localValidationError('test-ids', 'provide at least one <test-id>, or use --all to rerun all tests in the project');
3976
4948
  }
4949
+ // Explicit ids + --all is ambiguous: the --all branch resolves the FULL
4950
+ // project test set and overwrites the listed ids, so the user's narrowing
4951
+ // intent would be silently replaced by a whole-project batch rerun —
4952
+ // burning rerun/auto-heal credits. Reject early. (Mirrors `test run`'s
4953
+ // positional+--all guard and delete-batch's ids+--all data-loss guard.)
4954
+ if (opts.all && opts.testIds.length > 0) {
4955
+ throw localValidationError('test-ids', 'pass either explicit test IDs or --all, not both — --all reruns every test in the ' +
4956
+ 'project and would ignore the listed IDs. Drop the IDs, or drop --all.');
4957
+ }
3977
4958
  if (opts.all && !opts.projectId) {
3978
4959
  throw localValidationError('project', '--all requires a project context — pass --project <id> or configure a default');
3979
4960
  }
@@ -3986,12 +4967,31 @@ export async function runTestRerun(opts, deps = {}) {
3986
4967
  throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests get reran). ' +
3987
4968
  'Remove --filter, or add --all --project <id>.');
3988
4969
  }
4970
+ // --status and --skip-terminal are --all-only narrowing filters with the
4971
+ // same silent-ignore failure mode as --filter above: without --all the
4972
+ // explicit ids get reran unfiltered (and an invalid --status value is
4973
+ // never even validated). Reject both, mirroring the --filter guard.
4974
+ if (opts.statusFilter !== undefined && !opts.all) {
4975
+ throw localValidationError('status', '--status only applies with --all (it narrows which project tests get reran). ' +
4976
+ 'Remove --status, or add --all --project <id>.');
4977
+ }
4978
+ if (opts.skipTerminal && !opts.all) {
4979
+ throw localValidationError('skip-terminal', '--skip-terminal only applies with --all (it narrows which project tests get reran). ' +
4980
+ 'Remove --skip-terminal, or add --all --project <id>.');
4981
+ }
3989
4982
  if (!Number.isInteger(opts.maxConcurrency) ||
3990
4983
  opts.maxConcurrency < 1 ||
3991
4984
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
3992
4985
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
3993
4986
  }
3994
4987
  const isSingle = !opts.all && opts.testIds.length === 1;
4988
+ assertJUnitReportOptions({
4989
+ report: opts.report,
4990
+ reportFile: opts.reportFile,
4991
+ reportSuiteName: opts.reportSuiteName,
4992
+ wait: opts.wait,
4993
+ batchPath: !isSingle,
4994
+ });
3995
4995
  // -------------------------------------------------------------------------
3996
4996
  // Pre-flight: auto-heal + Free-tier hint (best-effort, non-blocking)
3997
4997
  // -------------------------------------------------------------------------
@@ -4030,6 +5030,10 @@ export async function runTestRerun(opts, deps = {}) {
4030
5030
  idempotencyKey,
4031
5031
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
4032
5032
  };
5033
+ if (opts.report === 'junit' && opts.reportFile !== undefined) {
5034
+ const projectKey = resolveBatchReportProjectId(opts, []);
5035
+ await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(projectKey, opts.reportSuiteName));
5036
+ }
4033
5037
  out.print(findSample('POST', '/api/cli/v1/tests/batch/rerun')?.body() ?? envelope);
4034
5038
  }
4035
5039
  void client;
@@ -4039,12 +5043,9 @@ export async function runTestRerun(opts, deps = {}) {
4039
5043
  // slow rerun trigger / long-poll under load isn't cut at the 120s default.
4040
5044
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
4041
5045
  const idempotencyKey = opts.idempotencyKey ?? `cli-rerun-${randomUUID()}`;
4042
- if (opts.idempotencyKey === undefined && opts.debug) {
5046
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
4043
5047
  stderrFn(`idempotency-key: ${idempotencyKey}`);
4044
5048
  }
4045
- if (opts.idempotencyKey === undefined && opts.verbose) {
4046
- stderrFn(`[verbose] auto-minted idempotency-key: ${idempotencyKey}`);
4047
- }
4048
5049
  // -------------------------------------------------------------------------
4049
5050
  // Single rerun path
4050
5051
  // -------------------------------------------------------------------------
@@ -4201,6 +5202,7 @@ export async function runTestRerun(opts, deps = {}) {
4201
5202
  return await pollRunUntilTerminal(client, member.runId, {
4202
5203
  timeoutSeconds: opts.timeoutSeconds,
4203
5204
  sleep: deps.sleep,
5205
+ shutdown: shutdownOf(deps),
4204
5206
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4205
5207
  onTick: (run, elapsedMs) => {
4206
5208
  const elapsed = Math.round(elapsedMs / 1000);
@@ -4291,7 +5293,27 @@ export async function runTestRerun(opts, deps = {}) {
4291
5293
  const reattachHints = closureMembers
4292
5294
  .map(m => `testsprite test wait ${m.runId}`)
4293
5295
  .join('\n');
4294
- stderrFn(`Closure members are still in progress (request timed out). Re-attach with:\n${reattachHints}`);
5296
+ const cancelHints = closureMembers
5297
+ .map(m => `testsprite test cancel ${m.runId}`)
5298
+ .join('\n');
5299
+ stderrFn(`Closure members are still in progress (request timed out). Re-attach with:\n${reattachHints}\n` +
5300
+ `Or cancel with:\n${cancelHints}`);
5301
+ throw fanOutErr;
5302
+ }
5303
+ // Graceful detach (DEV-331): same partial shape as the timeout path —
5304
+ // SIG-6 requires the partial to list ALL dispatched runIds.
5305
+ if (fanOutErr instanceof InterruptError) {
5306
+ ticker.finalize(`Closure fan-out — interrupted (${fanOutErr.signal})`);
5307
+ const dispatchedRunIds = closureMembers.map(m => ({
5308
+ runId: m.runId,
5309
+ testId: m.testId,
5310
+ role: m.role,
5311
+ status: 'running',
5312
+ }));
5313
+ out.print({ runId: namedRunId, status: 'running', closure: dispatchedRunIds }, () => dispatchedRunIds
5314
+ .map(m => `${m.role.padEnd(9)} ${m.testId} (runId: ${m.runId}) — running`)
5315
+ .join('\n'));
5316
+ stderrFn(interruptDetachMessage(fanOutErr, closureMembers.map(m => m.runId)));
4295
5317
  throw fanOutErr;
4296
5318
  }
4297
5319
  throw fanOutErr;
@@ -4328,7 +5350,7 @@ export async function runTestRerun(opts, deps = {}) {
4328
5350
  error: {
4329
5351
  code: 'UNSUPPORTED',
4330
5352
  message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${namedRunId}.`,
4331
- nextAction: `Resume polling: testsprite test wait ${namedRunId}`,
5353
+ nextAction: `Resume polling: testsprite test wait ${namedRunId}, or cancel it: testsprite test cancel ${namedRunId}`,
4332
5354
  requestId: 'local',
4333
5355
  details: { runId: namedRunId, timeoutSeconds: opts.timeoutSeconds },
4334
5356
  },
@@ -4344,7 +5366,9 @@ export async function runTestRerun(opts, deps = {}) {
4344
5366
  // as a whole was never observed to reach terminal.
4345
5367
  const timedOutMembers = closureFailures.filter(f => f.status === 'timeout');
4346
5368
  if (timedOutMembers.length > 0) {
4347
- const resumeHints = timedOutMembers.map(f => `testsprite test wait ${f.runId}`).join('\n');
5369
+ const timedOutIds = timedOutMembers.map(f => f.runId);
5370
+ const resumeHints = timedOutIds.map(runId => `testsprite test wait ${runId}`).join('\n') +
5371
+ `\nCancel instead: testsprite test cancel ${timedOutIds.join(' ')}`;
4348
5372
  throw ApiError.fromEnvelope({
4349
5373
  error: {
4350
5374
  code: 'UNSUPPORTED',
@@ -4377,6 +5401,7 @@ export async function runTestRerun(opts, deps = {}) {
4377
5401
  finalRun = await pollRunUntilTerminal(client, rerunResp.runId, {
4378
5402
  timeoutSeconds: opts.timeoutSeconds,
4379
5403
  sleep: deps.sleep,
5404
+ shutdown: shutdownOf(deps),
4380
5405
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4381
5406
  onTick: (run, elapsedMs) => {
4382
5407
  const elapsed = Math.round(elapsedMs / 1000);
@@ -4393,7 +5418,7 @@ export async function runTestRerun(opts, deps = {}) {
4393
5418
  error: {
4394
5419
  code: 'UNSUPPORTED',
4395
5420
  message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${rerunResp.runId}.`,
4396
- nextAction: `Resume polling: testsprite test wait ${rerunResp.runId}`,
5421
+ nextAction: `Resume polling: testsprite test wait ${rerunResp.runId}, or cancel it: testsprite test cancel ${rerunResp.runId}`,
4397
5422
  requestId: 'local',
4398
5423
  details: { runId: rerunResp.runId, timeoutSeconds: opts.timeoutSeconds },
4399
5424
  },
@@ -4410,10 +5435,27 @@ export async function runTestRerun(opts, deps = {}) {
4410
5435
  `runId ${p.runId}`,
4411
5436
  `status ${p.status} (request timed out)`,
4412
5437
  `hint Re-attach with: testsprite test wait ${p.runId}`,
5438
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
4413
5439
  ].join('\n');
4414
5440
  });
4415
5441
  stderrFn(`Run ${rerunResp.runId} is still in progress (request timed out). ` +
4416
- `Re-attach with: testsprite test wait ${rerunResp.runId}`);
5442
+ `Re-attach with: testsprite test wait ${rerunResp.runId}, or cancel with: testsprite test cancel ${rerunResp.runId}`);
5443
+ throw err;
5444
+ }
5445
+ // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
5446
+ if (err instanceof InterruptError) {
5447
+ ticker.finalize(`Run ${rerunResp.runId} — interrupted (${err.signal})`);
5448
+ const partial = { runId: rerunResp.runId, status: 'running' };
5449
+ out.print(partial, data => {
5450
+ const p = data;
5451
+ return [
5452
+ `runId ${p.runId}`,
5453
+ `status ${p.status} (interrupted)`,
5454
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
5455
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
5456
+ ].join('\n');
5457
+ });
5458
+ stderrFn(interruptDetachMessage(err, [rerunResp.runId]));
4417
5459
  throw err;
4418
5460
  }
4419
5461
  ticker.finalize();
@@ -4423,9 +5465,16 @@ export async function runTestRerun(opts, deps = {}) {
4423
5465
  void elapsed;
4424
5466
  const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
4425
5467
  ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps replay)`);
4426
- out.print(withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), data => renderRunResponseText(data, { isBackend: beFallbackUsed }));
5468
+ // Probe the test type once (text mode only, best-effort) so a backend
5469
+ // rerun's card reads `n/a (backend)` even when the fallback never fired
5470
+ // (BE run rows finalize server-side now) — DEV-282.
5471
+ const isBackend = await resolveRunCardIsBackend(client, testId, opts.output, beFallbackUsed);
5472
+ out.print(withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), data => renderRunResponseText(data, { isBackend }));
4427
5473
  if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
4428
- stderrFn(`Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
5474
+ // BE reruns have no run-scoped artifact bundle — address by testId.
5475
+ stderrFn(isBackend
5476
+ ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${testId}' to download the bundle.`
5477
+ : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
4429
5478
  }
4430
5479
  const exitCode = exitCodeForRunStatus(finalRun.status);
4431
5480
  if (exitCode !== 0) {
@@ -4515,7 +5564,14 @@ export async function runTestRerun(opts, deps = {}) {
4515
5564
  chunkResponses = [];
4516
5565
  for (let idx = 0; idx < chunks.length; idx++) {
4517
5566
  const chunk = chunks[idx];
4518
- const chunkKey = chunks.length === 1 ? idempotencyKey : `${idempotencyKey}:chunk${idx}`;
5567
+ // Bound the per-chunk idempotency key to <=256 chars (mirrors the retry
5568
+ // path). A long base key plus the `:chunkN` suffix could otherwise exceed
5569
+ // the server cap and be rejected or truncated inconsistently.
5570
+ const chunkSuffix = chunks.length === 1 ? '' : `:chunk${idx}`;
5571
+ const chunkBase = chunkSuffix.length > 0 && idempotencyKey.length + chunkSuffix.length > 256
5572
+ ? idempotencyKey.slice(0, 256 - chunkSuffix.length)
5573
+ : idempotencyKey;
5574
+ const chunkKey = `${chunkBase}${chunkSuffix}`;
4519
5575
  const chunkResp = await client.triggerBatchRerun({
4520
5576
  source: 'cli',
4521
5577
  testIds: chunk,
@@ -4785,6 +5841,7 @@ export async function runTestRerun(opts, deps = {}) {
4785
5841
  const finalRun = await pollRunUntilTerminal(client, entry.runId, {
4786
5842
  timeoutSeconds: remainingSeconds,
4787
5843
  sleep: deps.sleep,
5844
+ shutdown: shutdownOf(deps),
4788
5845
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4789
5846
  onTick: (run, elapsedMs) => {
4790
5847
  const elapsed = Math.round(elapsedMs / 1000);
@@ -4793,7 +5850,12 @@ export async function runTestRerun(opts, deps = {}) {
4793
5850
  },
4794
5851
  resolveAlternate,
4795
5852
  });
4796
- return { testId: entry.testId, runId: entry.runId, status: finalRun.status };
5853
+ return {
5854
+ testId: entry.testId,
5855
+ runId: entry.runId,
5856
+ projectId: finalRun.projectId,
5857
+ status: finalRun.status,
5858
+ };
4797
5859
  }
4798
5860
  catch (err) {
4799
5861
  if (err instanceof TimeoutError) {
@@ -4808,12 +5870,36 @@ export async function runTestRerun(opts, deps = {}) {
4808
5870
  },
4809
5871
  };
4810
5872
  }
5873
+ // Interrupt must reject the fan-out (the collect point below prints the
5874
+ // partial for every dispatched run), never flatten into a per-member
5875
+ // outcome that would swallow the 128+signum exit (DEV-331).
5876
+ if (err instanceof InterruptError)
5877
+ throw err;
5878
+ if (err instanceof RequestTimeoutError) {
5879
+ // Client-side per-request timeout during polling — classify as timeout
5880
+ // (exit 7) so the fan-out completes and stdout carries every runId.
5881
+ // Without this, RequestTimeoutError rejects the fan-out before out.print(),
5882
+ // leaving JSON consumers with empty stdout (mirrors create-batch --run).
5883
+ return {
5884
+ testId: entry.testId,
5885
+ runId: entry.runId,
5886
+ status: 'timeout',
5887
+ error: {
5888
+ code: 'UNSUPPORTED',
5889
+ message: err.message,
5890
+ exitCode: err.exitCode,
5891
+ },
5892
+ };
5893
+ }
4811
5894
  if (err instanceof ApiError) {
5895
+ // Preserve the real exit code (AUTH_INVALID=3, RATE_LIMITED=11, …) so the
5896
+ // batch exit-code aggregator can escalate auth failures correctly. Mirroring
5897
+ // the identical fix already applied to runTestRunAll's pollFreshAccepted.
4812
5898
  return {
4813
5899
  testId: entry.testId,
4814
5900
  runId: entry.runId,
4815
5901
  status: 'error',
4816
- error: { code: err.code, message: err.message, exitCode: 1 },
5902
+ error: { code: err.code, message: err.message, exitCode: err.exitCode },
4817
5903
  };
4818
5904
  }
4819
5905
  throw err;
@@ -4822,26 +5908,43 @@ export async function runTestRerun(opts, deps = {}) {
4822
5908
  // Bounded concurrency fan-out
4823
5909
  let acceptedIdx = 0;
4824
5910
  let inFlight = 0;
4825
- await new Promise((resolve, reject) => {
4826
- function startNext() {
4827
- while (inFlight < concurrencyLimit && acceptedIdx < accepted.length) {
4828
- const entry = accepted[acceptedIdx++];
4829
- inFlight++;
4830
- pollAccepted(entry)
4831
- .then(result => {
4832
- rerunResults.push(result);
4833
- inFlight--;
4834
- startNext();
4835
- if (inFlight === 0 && acceptedIdx >= accepted.length)
4836
- resolve();
4837
- })
4838
- .catch(reject);
5911
+ try {
5912
+ await new Promise((resolve, reject) => {
5913
+ function startNext() {
5914
+ while (inFlight < concurrencyLimit && acceptedIdx < accepted.length) {
5915
+ const entry = accepted[acceptedIdx++];
5916
+ inFlight++;
5917
+ pollAccepted(entry)
5918
+ .then(result => {
5919
+ rerunResults.push(result);
5920
+ inFlight--;
5921
+ startNext();
5922
+ if (inFlight === 0 && acceptedIdx >= accepted.length)
5923
+ resolve();
5924
+ })
5925
+ .catch(reject);
5926
+ }
4839
5927
  }
4840
- }
4841
- startNext();
4842
- if (accepted.length === 0)
4843
- resolve();
4844
- });
5928
+ startNext();
5929
+ if (accepted.length === 0)
5930
+ resolve();
5931
+ });
5932
+ }
5933
+ catch (fanOutErr) {
5934
+ // Graceful detach (DEV-331): stdout stays parseable — settled members
5935
+ // keep their real status, unfinished ones are marked running — and the
5936
+ // honest stderr line names every runId still executing (and billing).
5937
+ if (fanOutErr instanceof InterruptError) {
5938
+ ticker.finalize(`Batch rerun — interrupted (${fanOutErr.signal})`);
5939
+ const settled = new Map(rerunResults.map(r => [r.runId, r]));
5940
+ const partialResults = accepted.map((e) => settled.get(e.runId) ?? { testId: e.testId, runId: e.runId, status: 'running' });
5941
+ out.print({ accepted: partialResults, deferred, conflicts, notFound }, () => partialResults.map(r => `${r.runId} ${r.status}`).join('\n'));
5942
+ const unfinished = accepted.filter(e => !settled.has(e.runId)).map(e => e.runId);
5943
+ if (unfinished.length > 0)
5944
+ stderrFn(interruptDetachMessage(fanOutErr, unfinished));
5945
+ }
5946
+ throw fanOutErr;
5947
+ }
4845
5948
  ticker.finalize();
4846
5949
  const passed = rerunResults.filter(r => r.status === 'passed').length;
4847
5950
  const failed = rerunResults.filter(r => r.status !== 'passed' && r.status !== 'timeout').length;
@@ -4876,6 +5979,7 @@ export async function runTestRerun(opts, deps = {}) {
4876
5979
  total: accepted.length,
4877
5980
  },
4878
5981
  };
5982
+ await writeBatchJUnitReportIfRequested(opts, rerunResults);
4879
5983
  out.print(jsonPayload);
4880
5984
  // Determine exit code: timeout (deferred or any timeout) → 7; any fail → 1; all pass → 0
4881
5985
  if (deferred.length > 0 || timedOut > 0) {
@@ -4896,6 +6000,7 @@ export async function runTestRerun(opts, deps = {}) {
4896
6000
  // `test wait` accepts exactly one run id — emit one command per
4897
6001
  // timed-out run so the hint is always valid.
4898
6002
  ...(timedOut > 0 ? stillRunning.map(rid => `Resume: testsprite test wait ${rid}`) : []),
6003
+ ...(timedOut > 0 ? stillRunning.map(rid => `Cancel: testsprite test cancel ${rid}`) : []),
4899
6004
  ]
4900
6005
  .filter(Boolean)
4901
6006
  .join('\n'),
@@ -4905,6 +6010,14 @@ export async function runTestRerun(opts, deps = {}) {
4905
6010
  });
4906
6011
  }
4907
6012
  if (failed > 0) {
6013
+ // Auth failure on any member is a batch-wide condition — the credential is
6014
+ // bad, not the test. Propagate exit 3 so the operator fixes auth rather than
6015
+ // chasing a "rerun failed" (exit 1). Mirrors the identical logic already
6016
+ // applied to runTestRunAll lines 5462-5468.
6017
+ const authErr = rerunResults.find(r => r.error?.exitCode === 3);
6018
+ if (authErr) {
6019
+ throw new CLIError(`${failed} rerun${failed !== 1 ? 's' : ''} failed — auth error (${authErr.error?.code}): ${authErr.error?.message}`, 3);
6020
+ }
4908
6021
  throw new CLIError(`${failed} rerun${failed !== 1 ? 's' : ''} failed.`, 1);
4909
6022
  }
4910
6023
  // [P2] Return post-retry state including merged notFound so callers see the
@@ -4913,6 +6026,19 @@ export async function runTestRerun(opts, deps = {}) {
4913
6026
  // outcome printed to stdout and is not part of the returned shape).
4914
6027
  return { ...batchResp, accepted, deferred, conflicts, notFound };
4915
6028
  }
6029
+ export function resolveDefaultArtifactDir(runId, cwd = process.cwd()) {
6030
+ requireNonEmpty('run-id', runId);
6031
+ const windowsNormalizedSegment = runId.replace(/[ .]+$/u, '');
6032
+ if (windowsNormalizedSegment === '' ||
6033
+ windowsNormalizedSegment === '.' ||
6034
+ windowsNormalizedSegment === '..' ||
6035
+ runId.includes('/') ||
6036
+ runId.includes('\\') ||
6037
+ runId.includes('\0')) {
6038
+ throw localValidationError('run-id', 'must be a single path-safe segment for the default output directory; pass --out <dir> to choose a custom path');
6039
+ }
6040
+ return join(cwd, '.testsprite', 'runs', runId);
6041
+ }
4916
6042
  /**
4917
6043
  * Validate that the parent directory of `resolvedDir` exists and is a
4918
6044
  * directory. Surfaces `VALIDATION_ERROR` (exit 5) — matches the convention
@@ -4960,12 +6086,9 @@ export async function assertOutDirParentExists(resolvedDir) {
4960
6086
  */
4961
6087
  export async function runArtifactGet(opts, deps = {}) {
4962
6088
  const out = makeOutput(opts.output, deps);
4963
- const client = makeClient(opts, deps);
4964
6089
  const { runId } = opts;
4965
6090
  // Resolve output dir: explicit --out or the default .testsprite/runs/<runId>/
4966
- const resolvedDir = opts.out !== undefined
4967
- ? resolveBundleDir(opts.out)
4968
- : join(process.cwd(), '.testsprite', 'runs', runId);
6091
+ const resolvedDir = opts.out !== undefined ? resolveBundleDir(opts.out) : resolveDefaultArtifactDir(runId);
4969
6092
  // --dry-run: no network, no disk write.
4970
6093
  // The client (makeClient) is already wired with createDryRunFetch() when
4971
6094
  // dryRun: true, so a real call to client.get() would return the canned
@@ -5004,6 +6127,7 @@ export async function runArtifactGet(opts, deps = {}) {
5004
6127
  if (opts.out !== undefined) {
5005
6128
  await assertOutDirParentExists(resolvedDir);
5006
6129
  }
6130
+ const client = makeClient(opts, deps);
5007
6131
  // Fetch the run-scoped failure bundle.
5008
6132
  const { body: context, requestId: fetchRequestId } = await client.getWithMeta(`/runs/${encodeURIComponent(runId)}/failure`);
5009
6133
  // §3 atomicity invariants — run-scoped path requires runId to be present.
@@ -5249,6 +6373,25 @@ export function createTestCommand(deps = {}) {
5249
6373
  idempotencyKey: cmdOpts.idempotencyKey,
5250
6374
  }, deps);
5251
6375
  });
6376
+ test
6377
+ .command('scaffold')
6378
+ .description('Emit a schema-correct starter test definition (frontend plan JSON by default, or a backend Python skeleton). Pure-local: no network, no credentials.')
6379
+ .option('--type <type>', 'frontend|backend (default: frontend)')
6380
+ .option('--out <path>', 'write the scaffold to a file instead of stdout')
6381
+ .option('--force', 'overwrite an existing --out file', false)
6382
+ .addHelpText('after', '\nExamples:\n' +
6383
+ ' testsprite test scaffold > first-test.plan.json\n' +
6384
+ ' testsprite test scaffold --type backend --out tests/health.py\n' +
6385
+ ' testsprite test scaffold --out plan.json # then edit, and create with --plan-from plan.json')
6386
+ .addHelpText('after', GLOBAL_OPTS_HINT)
6387
+ .action(async (cmdOpts, command) => {
6388
+ await runScaffold({
6389
+ ...resolveCommonOptions(command),
6390
+ scaffoldType: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES) ?? 'frontend',
6391
+ out: cmdOpts.out,
6392
+ force: cmdOpts.force === true,
6393
+ }, deps);
6394
+ });
5252
6395
  test
5253
6396
  .command('steps <test-id>')
5254
6397
  .description('List the steps for a test (server returns the cumulative log across every run; use --run-id to scope to one run)')
@@ -5267,6 +6410,30 @@ export function createTestCommand(deps = {}) {
5267
6410
  runId: cmdOpts.runId,
5268
6411
  }, deps);
5269
6412
  });
6413
+ test
6414
+ .command('diff <run-a> <run-b>')
6415
+ .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.')
6416
+ .addHelpText('after', GLOBAL_OPTS_HINT)
6417
+ .action(async (runA, runB, _cmdOpts, command) => {
6418
+ await runDiff({ ...resolveCommonOptions(command), runA, runB }, deps);
6419
+ });
6420
+ test
6421
+ .command('lint')
6422
+ .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.')
6423
+ .option('--plan-from <file>', 'single plan JSON file')
6424
+ .option('--plan-from-dir <dir>', 'directory of *.json plan files (each checked, all errors reported)')
6425
+ .option('--plans <file>', 'JSONL file with one plan spec per line (each line checked)')
6426
+ .option('--steps <file>', 'plan-steps JSON file (the shape `test plan put` ingests)')
6427
+ .addHelpText('after', GLOBAL_OPTS_HINT)
6428
+ .action(async (cmdOpts, command) => {
6429
+ await runLint({
6430
+ ...resolveCommonOptions(command),
6431
+ planFrom: cmdOpts.planFrom,
6432
+ planFromDir: cmdOpts.planFromDir,
6433
+ plans: cmdOpts.plans,
6434
+ steps: cmdOpts.steps,
6435
+ }, deps);
6436
+ });
5270
6437
  test
5271
6438
  .command('result <test-id>')
5272
6439
  .description('Get the latest result for a test (default) or list prior runs (--history).\n' +
@@ -5311,6 +6478,9 @@ export function createTestCommand(deps = {}) {
5311
6478
  .option('--name <name>', 'new human-readable test name')
5312
6479
  .option('--description <text>', 'new human description (≤ 2000 chars)')
5313
6480
  .option('--priority <prio>', 'new priority — one of: p0, p1, p2, p3')
6481
+ .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering.', (val, prev) => [...(prev ?? []), val], [])
6482
+ .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Declares an upstream producer dependency.', (val, prev) => [...(prev ?? []), val], [])
6483
+ .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
5314
6484
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
5315
6485
  .addHelpText('after', GLOBAL_OPTS_HINT)
5316
6486
  .action(async (testId, cmdOpts, command) => {
@@ -5320,6 +6490,9 @@ export function createTestCommand(deps = {}) {
5320
6490
  name: cmdOpts.name,
5321
6491
  description: cmdOpts.description,
5322
6492
  priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
6493
+ produces: cmdOpts.produces,
6494
+ needs: cmdOpts.needs,
6495
+ category: cmdOpts.category,
5323
6496
  idempotencyKey: cmdOpts.idempotencyKey,
5324
6497
  }, deps);
5325
6498
  });
@@ -5371,7 +6544,7 @@ export function createTestCommand(deps = {}) {
5371
6544
  test
5372
6545
  .command('run [test-id]')
5373
6546
  .description('Trigger a test run. With --wait, polls until terminal status.\n' +
5374
- 'Use --all --project <id> for a wave-ordered batch run of all BE tests (M4).\n' +
6547
+ 'Use --all --project <id> for a wave-ordered batch run of all tests in a project (M4).\n' +
5375
6548
  '\nExit codes:\n' +
5376
6549
  ' 0 passed (or queued without --wait)\n' +
5377
6550
  ' 1 failed / blocked / cancelled\n' +
@@ -5379,23 +6552,33 @@ export function createTestCommand(deps = {}) {
5379
6552
  ' 4 test not found\n' +
5380
6553
  ' 5 validation error (e.g., bad --target-url, or positional + --all both set)\n' +
5381
6554
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
5382
- ' 7 timeout — resume with: testsprite test wait <run-id>\n' +
6555
+ ' 7 timeout — resume with: testsprite test wait <run-id>, ' +
6556
+ 'or stop it with: testsprite test cancel <run-id>\n' +
5383
6557
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
5384
6558
  ' 11 rate limited — honor Retry-After\n' +
5385
- '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>')
6559
+ '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
6560
+ '\nCtrl-C during --wait detaches only (the run keeps executing and billing);\n' +
6561
+ 'stop it for real with: testsprite test cancel <run-id>')
5386
6562
  .option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private IPs)')
5387
6563
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
5388
6564
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
5389
6565
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
5390
- .option('--all', 'run all BE tests in the project (wave-ordered fresh run; requires --project). Mutually exclusive with <test-id>.', false)
6566
+ .option('--all', 'run all tests in the project (wave-ordered fresh run; requires --project). Mutually exclusive with <test-id>.', false)
5391
6567
  .option('--project <id>', 'project id (required with --all; returned by `testsprite project list`)')
5392
6568
  .option('--filter <substr>', 'with --all: only run tests whose name contains this substring (case-insensitive)')
5393
6569
  .option('--max-concurrency <n>', `with --all --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
6570
+ .option('--report <format>', 'with --all --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
6571
+ .option('--report-file <path>', 'output path for --report (atomic write)')
6572
+ .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
5394
6573
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
5395
- ' testsprite test run --all --project <id> run all BE tests in wave order\n' +
6574
+ ' testsprite test run --all --project <id> run all project tests in wave order\n' +
5396
6575
  ' testsprite test run --all --project <id> --filter <substr> name-glob subset\n' +
6576
+ ' testsprite test run --all --project <id> --wait --report junit --report-file ./results.xml\n' +
5397
6577
  '\nBE tests can declare --produces/--needs at create time to drive wave ordering\n' +
5398
- '(see `testsprite test create --help` for details).')
6578
+ '(see `testsprite test create --help` for details).\n' +
6579
+ '\nFrontend tests: the current unified engine runs FE tests too (they are billed\n' +
6580
+ 'like any run). On the legacy backend-only engine FE tests cannot run — they are\n' +
6581
+ "reported under skippedFrontend with an advisory; run those with 'test run <id>'.")
5399
6582
  .addHelpText('after', GLOBAL_OPTS_HINT)
5400
6583
  .action(async (testIdArg, cmdOpts, command) => {
5401
6584
  const isAll = cmdOpts.all === true;
@@ -5404,7 +6587,7 @@ export function createTestCommand(deps = {}) {
5404
6587
  throw localValidationError('test-id', 'positional <test-id> and --all are mutually exclusive; use one or the other');
5405
6588
  }
5406
6589
  if (testIdArg === undefined && !isAll) {
5407
- throw localValidationError('test-id', 'provide a <test-id>, or use --all --project <id> to run all BE tests in a project');
6590
+ throw localValidationError('test-id', 'provide a <test-id>, or use --all --project <id> to run all tests in a project');
5408
6591
  }
5409
6592
  // --filter is an --all-only narrowing flag (mirrors `test rerun --filter`).
5410
6593
  // Without --all it would be SILENTLY ignored while the explicit <test-id>
@@ -5412,17 +6595,27 @@ export function createTestCommand(deps = {}) {
5412
6595
  if (cmdOpts.filter !== undefined && cmdOpts.filter !== '' && !isAll) {
5413
6596
  throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests run). Remove --filter, or add --all --project <id>.');
5414
6597
  }
6598
+ const report = parseJUnitReportFormat(cmdOpts.report);
6599
+ assertJUnitReportOptions({
6600
+ report,
6601
+ reportFile: cmdOpts.reportFile,
6602
+ reportSuiteName: cmdOpts.reportSuiteName,
6603
+ wait: cmdOpts.wait === true,
6604
+ batchPath: isAll,
6605
+ });
5415
6606
  if (isAll) {
5416
6607
  // --all path: wave-ordered fresh batch run.
5417
6608
  if (!cmdOpts.project) {
5418
6609
  throw localValidationError('project', '--all requires a project id — pass --project <id>');
5419
6610
  }
5420
- // --target-url has no effect on the --all batch path: it is BE-only
5421
- // (FE tests are skipped server-side) and a BE test's base URL is baked
5422
- // into its code. Silently dropping it could run the suite against an
5423
- // unintended environment in the caller's mind — reject loudly instead.
6611
+ // --target-url has no effect on the --all batch path: a BE test's base
6612
+ // URL is baked into its code, and the unified engine resolves each
6613
+ // project's configured environment server-side (per-run URL overrides
6614
+ // are not applied to batch FE runs either). Silently dropping it could
6615
+ // run the suite against an unintended environment in the caller's mind
6616
+ // — reject loudly instead.
5424
6617
  if (cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
5425
- throw localValidationError('target-url', '--target-url has no effect with --all (the batch path is the BE-only wave engine; a BE test’s URL is baked into its code). Remove --target-url.');
6618
+ throw localValidationError('target-url', '--target-url has no effect with --all (the batch path does not apply a per-run URL override — BE test URLs are baked into their code and the unified engine resolves the project environment server-side). Remove --target-url.');
5426
6619
  }
5427
6620
  await runTestRunAll({
5428
6621
  ...resolveCommonOptions(command),
@@ -5433,6 +6626,9 @@ export function createTestCommand(deps = {}) {
5433
6626
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
5434
6627
  DEFAULT_BATCH_RUN_CONCURRENCY,
5435
6628
  idempotencyKey: cmdOpts.idempotencyKey,
6629
+ report,
6630
+ reportFile: cmdOpts.reportFile,
6631
+ reportSuiteName: cmdOpts.reportSuiteName,
5436
6632
  }, deps);
5437
6633
  return;
5438
6634
  }
@@ -5449,23 +6645,46 @@ export function createTestCommand(deps = {}) {
5449
6645
  }, deps);
5450
6646
  });
5451
6647
  test
5452
- .command('wait <run-id>')
5453
- .description('Wait for a run to reach a terminal status.\n' +
6648
+ .command('wait <run-id...>')
6649
+ .description('Wait for one or more runs to reach a terminal status.\n' +
6650
+ '\nWith several run-ids the runs are polled concurrently under one shared\n' +
6651
+ '--timeout and a {results, summary} envelope is printed (worst status wins\n' +
6652
+ 'the exit code), so every re-attach hint the CLI prints can be pasted as\n' +
6653
+ 'ONE command.\n' +
5454
6654
  '\nExit codes:\n' +
5455
6655
  ' 0 passed\n' +
5456
6656
  ' 1 failed / blocked / cancelled\n' +
5457
6657
  ' 3 auth error\n' +
5458
- ' 4 run not found\n' +
5459
- ' 7 timeout — resume with: testsprite test wait <run-id>\n' +
6658
+ ' 4 run not found (single run-id; with several ids a per-member poll error\n' +
6659
+ ' is recorded as error:<CODE> in its row and folded into exit 7)\n' +
6660
+ ' 7 timeout or per-member poll error — resume with: testsprite test wait <run-id...>\n' +
5460
6661
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
5461
- '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>')
6662
+ '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
6663
+ '\nCtrl-C detaches only (the run keeps executing and billing); stop it for\n' +
6664
+ 'real with: testsprite test cancel <run-id...>')
5462
6665
  .option('--timeout <s>', `max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6666
+ .option('--max-concurrency <n>', 'with several run-ids, max concurrent polls (1-100, default: 10)')
5463
6667
  .addHelpText('after', GLOBAL_OPTS_HINT)
5464
- .action(async (runId, cmdOpts, command) => {
5465
- await runTestWait({
6668
+ .action(async (runIds, cmdOpts, command) => {
6669
+ // One id keeps the historical single-run path byte-identical (same
6670
+ // output shape, same exit codes); two or more fan out.
6671
+ if (runIds.length === 1) {
6672
+ await runTestWait({
6673
+ ...resolveCommonOptions(command),
6674
+ runId: runIds[0],
6675
+ timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
6676
+ }, deps);
6677
+ return;
6678
+ }
6679
+ const maxConcurrency = parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ?? 10;
6680
+ if (!Number.isInteger(maxConcurrency) || maxConcurrency < 1 || maxConcurrency > 100) {
6681
+ throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
6682
+ }
6683
+ await runTestWaitMany({
5466
6684
  ...resolveCommonOptions(command),
5467
- runId,
6685
+ runIds,
5468
6686
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
6687
+ maxConcurrency,
5469
6688
  }, deps);
5470
6689
  });
5471
6690
  // -------------------------------------------------------------------------
@@ -5481,9 +6700,12 @@ export function createTestCommand(deps = {}) {
5481
6700
  ' 4 test not found\n' +
5482
6701
  ' 5 validation error\n' +
5483
6702
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
5484
- ' 7 timeout or deferred — resume with: testsprite test wait <run-id>\n' +
6703
+ ' 7 timeout or deferred — resume with: testsprite test wait <run-id>, ' +
6704
+ 'or stop it with: testsprite test cancel <run-id>\n' +
5485
6705
  ' 11 rate limited — honor Retry-After\n' +
5486
- '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>')
6706
+ '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
6707
+ '\nCtrl-C during --wait detaches only (the run keeps executing and billing);\n' +
6708
+ 'stop it for real with: testsprite test cancel <run-id>')
5487
6709
  .option('--all', 'rerun all tests in the resolved project (requires --project)', false)
5488
6710
  .option('--project <id>', 'project id (required with --all; returned by `testsprite project list`)')
5489
6711
  .option('--skip-terminal', 'with --all: skip tests already in a terminal status (passed|failed|blocked|cancelled)', false)
@@ -5495,6 +6717,9 @@ export function createTestCommand(deps = {}) {
5495
6717
  .option('--skip-dependencies', 'BE only: rerun only the named test without expanding the producer/teardown closure', false)
5496
6718
  .option('--max-concurrency <n>', `with --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
5497
6719
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --verbose if auto-generated.')
6720
+ .option('--report <format>', 'with batch --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
6721
+ .option('--report-file <path>', 'output path for --report (atomic write)')
6722
+ .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
5498
6723
  .addHelpText('after', '\nNotes:\n' +
5499
6724
  ' • rerun replays a saved run/script and is MORE LENIENT than a fresh `test run`\n' +
5500
6725
  ' (auto-heal can pass steps that have drifted) — for strict scoring/regression,\n' +
@@ -5514,9 +6739,19 @@ export function createTestCommand(deps = {}) {
5514
6739
  // `--no-auto-heal`. There is no explicit `--auto-heal` flag, so
5515
6740
  // autoHealExplicit is always false in this design — the default-on value
5516
6741
  // is never a deliberate user choice to opt in.
6742
+ const testIds = testIdsArg ?? [];
6743
+ const isBatch = cmdOpts.all === true || testIds.length !== 1;
6744
+ const report = parseJUnitReportFormat(cmdOpts.report);
6745
+ assertJUnitReportOptions({
6746
+ report,
6747
+ reportFile: cmdOpts.reportFile,
6748
+ reportSuiteName: cmdOpts.reportSuiteName,
6749
+ wait: cmdOpts.wait === true,
6750
+ batchPath: isBatch,
6751
+ });
5517
6752
  await runTestRerun({
5518
6753
  ...resolveCommonOptions(command),
5519
- testIds: testIdsArg ?? [],
6754
+ testIds,
5520
6755
  all: cmdOpts.all === true,
5521
6756
  projectId: cmdOpts.project,
5522
6757
  skipTerminal: cmdOpts.skipTerminal === true,
@@ -5530,14 +6765,194 @@ export function createTestCommand(deps = {}) {
5530
6765
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
5531
6766
  DEFAULT_BATCH_RUN_CONCURRENCY,
5532
6767
  idempotencyKey: cmdOpts.idempotencyKey,
6768
+ report,
6769
+ reportFile: cmdOpts.reportFile,
6770
+ reportSuiteName: cmdOpts.reportSuiteName,
6771
+ }, deps);
6772
+ });
6773
+ // -------------------------------------------------------------------------
6774
+ // `test flaky` — repeat-run flaky-test detector
6775
+ // -------------------------------------------------------------------------
6776
+ test
6777
+ .command('flaky <test-id>')
6778
+ .description('Repeatedly replay a test to measure stability and surface flakiness.\n' +
6779
+ 'Replays run with auto-heal OFF (strict verbatim) so healed drift cannot mask nondeterministic pass/fail.\n' +
6780
+ '\nExit codes:\n' +
6781
+ ' 0 stable (every attempt passed)\n' +
6782
+ ' 1 flaky or failing (at least one attempt did not pass)\n' +
6783
+ ' 3 auth error\n' +
6784
+ ' 4 test not found (no replayable run — trigger `testsprite test run <id>` first)\n' +
6785
+ ' 5 validation error')
6786
+ .option('--runs <n>', `number of replays to run (1-${MAX_FLAKY_RUNS}, default ${DEFAULT_FLAKY_RUNS})`)
6787
+ .option('--until-fail', 'stop at the first non-passing attempt (fast "is it flaky at all?" check)', false)
6788
+ .option('--timeout <s>', `per-attempt max seconds to wait (1-${MAX_RUN_TIMEOUT_SECONDS}, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6789
+ .addHelpText('after', '\nNotes:\n' +
6790
+ ' • Frontend replays are free verbatim script replays (no credit); backend replays\n' +
6791
+ ' re-run the dependency closure and may cost credits — a one-line advisory is printed.\n' +
6792
+ ' • Replays use auto-heal OFF so a flaky test is not silently "healed" into a pass;\n' +
6793
+ ' this measures replay stability of the saved script against the configured URL.\n' +
6794
+ ' • `--output json` emits a machine-readable stability report for CI gating.')
6795
+ .addHelpText('after', GLOBAL_OPTS_HINT)
6796
+ .action(async (testIdArg, cmdOpts, command) => {
6797
+ await runFlaky({
6798
+ ...resolveCommonOptions(command),
6799
+ testId: testIdArg,
6800
+ runs: parseNumericFlag(cmdOpts.runs, 'runs') ?? DEFAULT_FLAKY_RUNS,
6801
+ untilFail: cmdOpts.untilFail === true,
6802
+ timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
5533
6803
  }, deps);
5534
6804
  });
5535
6805
  test.addCommand(createTestCodeCommand(deps));
5536
6806
  test.addCommand(createTestPlanCommand(deps));
5537
6807
  test.addCommand(createTestFailureCommand(deps));
5538
6808
  test.addCommand(createTestArtifactCommand(deps));
6809
+ test.addCommand(createTestCancelCommand(deps));
5539
6810
  return test;
5540
6811
  }
6812
+ // ---------------------------------------------------------------------------
6813
+ // `test flaky` — repeat-run flaky-test detector
6814
+ // ---------------------------------------------------------------------------
6815
+ /** Upper bound on `--runs` so a repeat-runner can't amplify free FE replays. */
6816
+ const MAX_FLAKY_RUNS = 10;
6817
+ /** Default replay count when `--runs` is omitted. */
6818
+ const DEFAULT_FLAKY_RUNS = 5;
6819
+ /**
6820
+ * `test flaky <test-id>` — replay a test N times and report a stability score.
6821
+ *
6822
+ * Each attempt is a `POST /tests/{id}/runs/rerun` with auto-heal OFF (a strict
6823
+ * verbatim replay) followed by `pollRunUntilTerminal`. Frontend replays are
6824
+ * free verbatim script replays; backend replays re-run the dependency closure
6825
+ * (a one-line credit advisory is printed). The pure scoring lives in
6826
+ * `lib/flaky.ts`; this function is the I/O orchestrator.
6827
+ *
6828
+ * Exit code: 0 when every observed attempt passed (stable), else 1 — so CI can
6829
+ * gate a merge on flakiness.
6830
+ */
6831
+ export async function runFlaky(opts, deps = {}) {
6832
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
6833
+ const out = makeOutput(opts.output, deps);
6834
+ if (typeof opts.testId !== 'string' || opts.testId.length === 0) {
6835
+ throw localValidationError('test-id', 'is required');
6836
+ }
6837
+ if (!Number.isInteger(opts.runs) || opts.runs < 1 || opts.runs > MAX_FLAKY_RUNS) {
6838
+ throw localValidationError('runs', `must be an integer between 1 and ${MAX_FLAKY_RUNS}`);
6839
+ }
6840
+ if (opts.dryRun) {
6841
+ out.print({
6842
+ dryRun: true,
6843
+ command: 'test flaky',
6844
+ testId: opts.testId,
6845
+ runs: opts.runs,
6846
+ untilFail: opts.untilFail,
6847
+ method: 'POST',
6848
+ path: `/api/cli/v1/tests/${opts.testId}/runs/rerun`,
6849
+ note: `Would replay the test up to ${opts.runs}x with auto-heal OFF and report a stability score.`,
6850
+ });
6851
+ return undefined;
6852
+ }
6853
+ // Under the implicit wait, raise the per-request timeout to cover --timeout
6854
+ // so a slow trigger / long-poll under load isn't cut at the 120s default.
6855
+ const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
6856
+ // Best-effort test-type detection for the credit advisory. A probe failure
6857
+ // never blocks the run — we just skip the advisory.
6858
+ let isBackend = false;
6859
+ try {
6860
+ const test = await client.get(`/tests/${encodeURIComponent(opts.testId)}`);
6861
+ isBackend = test.type === 'backend';
6862
+ }
6863
+ catch {
6864
+ // best-effort — proceed without the advisory.
6865
+ }
6866
+ if (isBackend) {
6867
+ stderrFn(`[advisory] ${opts.testId} is a backend test — each replay re-runs its dependency closure ` +
6868
+ `and may cost credits. Frontend replays are free verbatim script replays; backend replays are not.`);
6869
+ }
6870
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
6871
+ const attempts = [];
6872
+ for (let i = 1; i <= opts.runs; i++) {
6873
+ const idempotencyKey = `cli-flaky-${randomUUID()}`;
6874
+ let rerunResp;
6875
+ try {
6876
+ // auto-heal is intentionally OFF: flaky detection needs a strict verbatim
6877
+ // replay so healed drift cannot mask a nondeterministic pass/fail.
6878
+ rerunResp = await client.triggerRerun(opts.testId, { source: 'cli' }, { idempotencyKey });
6879
+ }
6880
+ catch (err) {
6881
+ // A missing replayable run is fatal for the whole command (mirror rerun):
6882
+ // there is nothing to repeat, so point the user at a fresh `test run`.
6883
+ if (err instanceof ApiError && err.code === 'NOT_FOUND') {
6884
+ throw ApiError.fromEnvelope({
6885
+ error: {
6886
+ code: 'NOT_FOUND',
6887
+ message: `Test ${opts.testId} has no replayable run (unknown/cross-tenant id, or it has never completed a clean run).`,
6888
+ nextAction: `Trigger a fresh run first: testsprite test run ${opts.testId}`,
6889
+ requestId: err.requestId ?? 'local',
6890
+ details: { testId: opts.testId, reason: 'no_replayable_run' },
6891
+ },
6892
+ });
6893
+ }
6894
+ // Any other trigger error is recorded as an errored attempt so a single
6895
+ // transient blip doesn't abort a long stability probe.
6896
+ const code = err instanceof ApiError ? err.code : 'ERROR';
6897
+ attempts.push({ attempt: i, runId: null, outcome: 'error', failureKind: code });
6898
+ ticker.update(`Attempt ${i}/${opts.runs} — error (${code})`);
6899
+ if (opts.untilFail)
6900
+ break;
6901
+ continue;
6902
+ }
6903
+ const runId = rerunResp.runId;
6904
+ // Backend run rows never finalize server-side; resolve the verdict from the
6905
+ // testId-scoped result on non-terminal ticks (same fallback as `test rerun`).
6906
+ const resolveAlternate = makeBackendWaitFallback({
6907
+ client,
6908
+ resolveTestId: () => opts.testId,
6909
+ resolveNotBefore: () => rerunResp.enqueuedAt,
6910
+ });
6911
+ let outcome;
6912
+ let failureKind = null;
6913
+ try {
6914
+ const finalRun = await pollRunUntilTerminal(client, runId, {
6915
+ timeoutSeconds: opts.timeoutSeconds,
6916
+ sleep: deps.sleep,
6917
+ shutdown: shutdownOf(deps),
6918
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6919
+ resolveAlternate,
6920
+ });
6921
+ outcome = finalRun.status;
6922
+ failureKind = finalRun.failureKind;
6923
+ }
6924
+ catch (err) {
6925
+ // Graceful detach (DEV-331): clean up the ticker line, name the run
6926
+ // still executing server-side, and let index.ts exit 128+signum.
6927
+ if (err instanceof InterruptError) {
6928
+ ticker.finalize(`Attempt ${i}/${opts.runs} — interrupted (${err.signal})`);
6929
+ stderrFn(interruptDetachMessage(err, [runId]));
6930
+ throw err;
6931
+ }
6932
+ // A per-attempt deadline (poll TimeoutError) or a client-side request
6933
+ // timeout both count as a non-passing "timeout" outcome for this attempt.
6934
+ if (err instanceof TimeoutError || err instanceof RequestTimeoutError) {
6935
+ outcome = 'timeout';
6936
+ }
6937
+ else {
6938
+ throw err;
6939
+ }
6940
+ }
6941
+ attempts.push({ attempt: i, runId, outcome, failureKind });
6942
+ const passedSoFar = attempts.filter(a => a.outcome === 'passed').length;
6943
+ ticker.update(`Attempt ${i}/${opts.runs} — ${outcome} (${passedSoFar} passed so far)`);
6944
+ if (opts.untilFail && outcome !== 'passed')
6945
+ break;
6946
+ }
6947
+ ticker.finalize();
6948
+ const report = summarizeFlaky(opts.testId, attempts);
6949
+ out.print(report, data => renderFlakyText(data));
6950
+ const exitCode = flakyExitCode(report);
6951
+ if (exitCode !== 0) {
6952
+ throw new CLIError(`Test ${opts.testId} is ${report.verdict} — ${report.passed}/${report.runs} attempts passed`, exitCode);
6953
+ }
6954
+ return report;
6955
+ }
5541
6956
  function requireProjectId(projectId) {
5542
6957
  if (typeof projectId !== 'string' || projectId.length === 0) {
5543
6958
  throw localValidationError('project', 'is required');
@@ -5584,13 +6999,9 @@ function resolveCommonOptions(command) {
5584
6999
  // P2-8: validate --output before allowing silent fallback to 'text'.
5585
7000
  // An invalid value (e.g. `--output yaml`) must exit 5 with a clear error
5586
7001
  // rather than silently treating the request as text mode.
5587
- const rawOutput = globals.output;
5588
- if (rawOutput !== undefined && rawOutput !== 'json' && rawOutput !== 'text') {
5589
- throw localValidationError('output', 'must be one of: json, text', ['json', 'text']);
5590
- }
5591
7002
  return {
5592
7003
  profile: globals.profile ?? 'default',
5593
- output: globals.output ?? 'text',
7004
+ output: resolveOutputMode(globals.output),
5594
7005
  dryRun: globals.dryRun ?? false,
5595
7006
  endpointUrl: globals.endpointUrl,
5596
7007
  debug: globals.debug ?? false,
@@ -5598,19 +7009,6 @@ function resolveCommonOptions(command) {
5598
7009
  requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
5599
7010
  };
5600
7011
  }
5601
- /**
5602
- * Parse the `--request-timeout <seconds>` flag value into milliseconds.
5603
- * Returns `undefined` when the flag was not supplied (factory falls back to
5604
- * the env var / default). Silently clamps out-of-range values.
5605
- */
5606
- function parseRequestTimeoutFlag(raw) {
5607
- if (raw === undefined)
5608
- return undefined;
5609
- const n = Number(raw);
5610
- if (!Number.isFinite(n) || n <= 0)
5611
- return undefined;
5612
- return Math.round(n * 1000); // seconds → milliseconds
5613
- }
5614
7012
  /** D4: headroom added on top of `--timeout` when deriving the per-request window under `--wait`. */
5615
7013
  const WAIT_REQUEST_TIMEOUT_CUSHION_MS = 5_000;
5616
7014
  /**
@@ -5637,6 +7035,7 @@ function makeClient(opts, deps) {
5637
7035
  credentialsPath: deps.credentialsPath,
5638
7036
  fetchImpl: deps.fetchImpl,
5639
7037
  stderr: deps.stderr,
7038
+ shutdownSignal: shutdownOf(deps).signal,
5640
7039
  });
5641
7040
  }
5642
7041
  function makeOutput(mode, deps) {
@@ -5686,6 +7085,18 @@ function openOutputFile(rawPath) {
5686
7085
  if (!parentStat.isDirectory()) {
5687
7086
  throw localValidationError('out', `parent path is not a directory: ${parent}`);
5688
7087
  }
7088
+ let targetStat;
7089
+ try {
7090
+ targetStat = statSync(resolved);
7091
+ }
7092
+ catch (err) {
7093
+ if (err.code !== 'ENOENT') {
7094
+ throw localValidationError('out', `cannot stat output path: ${resolved}`);
7095
+ }
7096
+ }
7097
+ if (targetStat?.isDirectory()) {
7098
+ throw localValidationError('out', `must point to a file, not a directory: ${resolved}`);
7099
+ }
5689
7100
  const tmpPath = join(parent, `.${basename(resolved)}.tmp-${randomUUID()}`);
5690
7101
  const stream = createWriteStream(tmpPath, { encoding: 'utf8' });
5691
7102
  const sink = { stream, path: resolved, tmpPath, error: null };
@@ -5750,6 +7161,18 @@ async function closeOutputFile(sink, commit) {
5750
7161
  }
5751
7162
  await rename(sink.tmpPath, sink.path);
5752
7163
  }
7164
+ /** Tear down an opened `--out` sink without leaving a zero-byte artifact. */
7165
+ async function abortOutputFile(sink) {
7166
+ await new Promise(resolve => {
7167
+ if (sink.stream.destroyed) {
7168
+ resolve();
7169
+ return;
7170
+ }
7171
+ sink.stream.once('close', () => resolve());
7172
+ sink.stream.destroy();
7173
+ });
7174
+ await unlink(sink.tmpPath).catch(() => undefined);
7175
+ }
5753
7176
  /** A presigned `code` body is any `https://` URL — never anything else. */
5754
7177
  export function isPresignedCodeUrl(code) {
5755
7178
  return code.startsWith('https://');
@@ -5895,6 +7318,16 @@ function renderTestText(t) {
5895
7318
  if (typeof t.planStepCount === 'number') {
5896
7319
  lines.push(`planSteps: ${t.planStepCount}`);
5897
7320
  }
7321
+ // Surface backend dependency declarations when present.
7322
+ if (Array.isArray(t.produces) && t.produces.length > 0) {
7323
+ lines.push(`produces: ${t.produces.join(', ')}`);
7324
+ }
7325
+ if (Array.isArray(t.consumes) && t.consumes.length > 0) {
7326
+ lines.push(`consumes: ${t.consumes.join(', ')}`);
7327
+ }
7328
+ if (t.category) {
7329
+ lines.push(`category: ${t.category}`);
7330
+ }
5898
7331
  lines.push(`createdAt: ${t.createdAt}`, `updatedAt: ${t.updatedAt}`);
5899
7332
  return lines.join('\n');
5900
7333
  }
@@ -5939,9 +7372,9 @@ function renderStepsText(page) {
5939
7372
  pad('DESCRIPTION', descWidth) +
5940
7373
  ' ' +
5941
7374
  'UPDATED';
5942
- const rows = page.items.map(s => {
7375
+ const rows = page.items.flatMap(s => {
5943
7376
  const marker = s.outcomeContributesToFailure === true ? '* ' : ' ';
5944
- return [
7377
+ const row = [
5945
7378
  marker,
5946
7379
  pad(String(s.stepIndex), indexWidth),
5947
7380
  pad(s.action, actionWidth),
@@ -5949,6 +7382,18 @@ function renderStepsText(page) {
5949
7382
  pad(descOf(s), descWidth),
5950
7383
  s.updatedAt,
5951
7384
  ].join(' ');
7385
+ // Run-scoped rows carry the per-step failure text; surface it as an
7386
+ // indented sub-line under failed rows (mirrors the history table's
7387
+ // `targetUrl:` sub-line). Collapsed to one line and capped so a huge
7388
+ // stack blob can't wreck the table; full text ships in --output json.
7389
+ if (s.status === 'failed' && typeof s.error === 'string' && s.error.length > 0) {
7390
+ const oneLine = s.error.replace(/\s+/g, ' ').trim();
7391
+ const shown = oneLine.length > ERROR_SUBLINE_MAX
7392
+ ? `${oneLine.slice(0, ERROR_SUBLINE_MAX - 1)}…`
7393
+ : oneLine;
7394
+ return [row, ` error: ${shown}`];
7395
+ }
7396
+ return [row];
5952
7397
  });
5953
7398
  const lines = [header, ...rows, ''];
5954
7399
  // §6.4: all steps in one response share `runIdIfAvailable` and
@@ -6013,6 +7458,10 @@ function renderFailureContextText(ctx) {
6013
7458
  }
6014
7459
  if (ctx.result.videoUrl !== null)
6015
7460
  lines.push(`videoUrl: ${ctx.result.videoUrl}`);
7461
+ // backend stdout + traceback (prefer the failure block, falling
7462
+ // back to the embedded result; identical values). Bounded tail; full content
7463
+ // in --output json / the written failure.json.
7464
+ appendBackendArtifactLines(lines, ctx.failure.apiOutput ?? ctx.result.apiOutput, ctx.failure.trace ?? ctx.result.trace);
6016
7465
  return lines.join('\n');
6017
7466
  }
6018
7467
  function renderBundleWrittenText(data) {
@@ -6132,6 +7581,9 @@ function renderResultText(r) {
6132
7581
  lines.push(`videoUrl: ${r.videoUrl}`);
6133
7582
  if (r.failureAnalysisUrl !== null)
6134
7583
  lines.push(`failureAnalysisUrl: ${r.failureAnalysisUrl}`);
7584
+ // backend stdout + traceback (null/absent for FE, passed, and
7585
+ // older backends). Full content always available via `--output json`.
7586
+ appendBackendArtifactLines(lines, r.apiOutput, r.trace);
6135
7587
  if (r.analysis !== undefined) {
6136
7588
  // §6.5.1 (M2.1 piece 3) — render the inline analysis block under
6137
7589
  // the result summary. Only fires when the caller passed
@@ -6154,6 +7606,33 @@ function renderResultText(r) {
6154
7606
  * level null. Non-null wrappers render `kind=...` plus an optional
6155
7607
  * reference and indented rationale.
6156
7608
  */
7609
+ /**
7610
+ * Render backend-test stdout + traceback in text mode. Shared by
7611
+ * `renderResultText` and `renderFailureContextText`. Both are bounded to a
7612
+ * tail (last {@link BACKEND_ARTIFACT_TAIL_LINES} lines) so a large stdout can't
7613
+ * flood the terminal; the full, untruncated content is always in the
7614
+ * `--output json` envelope. No-op when both are null/absent (FE / passed /
7615
+ * older backends), so non-backend output stays byte-identical.
7616
+ */
7617
+ const BACKEND_ARTIFACT_TAIL_LINES = 20;
7618
+ function appendArtifactTail(lines, label, value) {
7619
+ if (value == null || value === '')
7620
+ return;
7621
+ const allLines = value.replace(/\n+$/, '').split('\n');
7622
+ const dropped = Math.max(0, allLines.length - BACKEND_ARTIFACT_TAIL_LINES);
7623
+ const tail = dropped > 0 ? allLines.slice(-BACKEND_ARTIFACT_TAIL_LINES) : allLines;
7624
+ const bytes = Buffer.byteLength(value, 'utf8');
7625
+ lines.push('');
7626
+ lines.push(`${label} (${bytes} bytes${dropped > 0 ? `, showing last ${tail.length} lines` : ''}):`);
7627
+ for (const l of tail)
7628
+ lines.push(` ${l}`);
7629
+ if (dropped > 0)
7630
+ lines.push(` … ${dropped} earlier line(s) omitted — full content in --output json`);
7631
+ }
7632
+ function appendBackendArtifactLines(lines, apiOutput, trace) {
7633
+ appendArtifactTail(lines, 'stdout', apiOutput);
7634
+ appendArtifactTail(lines, 'trace', trace);
7635
+ }
6157
7636
  function appendFixTargetLines(lines, fix, label) {
6158
7637
  if (fix === null) {
6159
7638
  lines.push(`${label}— (analysis pipeline did not propose one)`);
@@ -6300,7 +7779,8 @@ export function createTestArtifactCommand(deps) {
6300
7779
  'Directory to write the §7 disk layout (default: ./.testsprite/runs/<run-id>/).',
6301
7780
  'Parent must exist. The bundle dir itself is created if absent.',
6302
7781
  ].join(' '))
6303
- .option('--failed-only', 'Keep only the failed step plus its immediate neighbors (±1)')
7782
+ .option('--failed-only', 'Trim to the failed step ±1. The bundle is already failure-focused server-side, ' +
7783
+ 'so this is usually a no-op; use `test steps <id>` for the full run trail.')
6304
7784
  .addHelpText('after', GLOBAL_OPTS_HINT)
6305
7785
  .action(async (runId, cmdOpts, command) => {
6306
7786
  await runArtifactGet({
@@ -6321,7 +7801,8 @@ function createTestFailureCommand(deps) {
6321
7801
  .command('get <test-id>', { isDefault: true })
6322
7802
  .description("Write a self-contained failure-context bundle for a test's latest failing run")
6323
7803
  .option('--out <dir>', 'Directory to write the §7 disk layout into (default: print wire envelope to stdout)')
6324
- .option('--failed-only', 'Keep only the failed step plus its immediate neighbors (±1)')
7804
+ .option('--failed-only', 'Trim to the failed step ±1. The bundle is already failure-focused server-side, ' +
7805
+ 'so this is usually a no-op; use `test steps <id>` for the full run trail.')
6325
7806
  .addHelpText('after', GLOBAL_OPTS_HINT)
6326
7807
  .action(async (testId, cmdOpts, command) => {
6327
7808
  await runFailureGet({