@testsprite/testsprite-cli 0.3.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.
@@ -7,7 +7,8 @@ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../l
7
7
  import { assertContextIntegrity, buildMeta, pickCodeExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
8
8
  import { findSample, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
9
9
  import { assertJUnitReportOptions, buildJUnitReport, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
10
- import { ApiError, CLIError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
10
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
11
+ import { globalShutdown } from '../lib/interrupt.js';
11
12
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
12
13
  import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.js';
13
14
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
@@ -20,6 +21,24 @@ import { RateThrottle } from '../lib/rate-throttle.js';
20
21
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
21
22
  import { loadConfig } from '../lib/config.js';
22
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
+ }
23
42
  const TEST_TYPES = ['frontend', 'backend'];
24
43
  // 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
25
44
  // tests created via `testsprite test create`, so the `--created-from cli`
@@ -695,8 +714,11 @@ export async function runUpdate(opts, deps = {}) {
695
714
  const hasName = opts.name !== undefined;
696
715
  const hasDescription = opts.description !== undefined;
697
716
  const hasPriority = opts.priority !== undefined;
698
- if (!hasName && !hasDescription && !hasPriority) {
699
- 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']);
700
722
  }
701
723
  const idempotencyKey = opts.idempotencyKey ?? `cli-update-${randomUUID()}`;
702
724
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
@@ -715,6 +737,12 @@ export async function runUpdate(opts, deps = {}) {
715
737
  body.description = opts.description;
716
738
  if (hasPriority)
717
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;
718
746
  const client = makeClient(opts, deps);
719
747
  const out = makeOutput(opts.output, deps);
720
748
  const response = await client.put(`/tests/${encodeURIComponent(opts.testId)}`, {
@@ -1580,7 +1608,13 @@ apiUrlForDashboard) {
1580
1608
  *
1581
1609
  * Returns a CliBatchRunResult. Never throws — errors are captured
1582
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.)
1583
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();
1584
1618
  async function triggerOne(testId) {
1585
1619
  // Mint a fresh idempotency key per run — MUST NOT reuse the create key.
1586
1620
  const runIdempotencyKey = `cli-batch-run-${randomUUID()}`;
@@ -1661,6 +1695,11 @@ apiUrlForDashboard) {
1661
1695
  break; // success — exit the outer retry loop
1662
1696
  }
1663
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;
1664
1703
  // RATE_LIMITED outer retry. Since the HTTP layer no longer retries
1665
1704
  // RATE_LIMITED (retryOnRateLimit: false above), every 429 reaches here
1666
1705
  // on the first attempt.
@@ -1784,6 +1823,12 @@ apiUrlForDashboard) {
1784
1823
  }
1785
1824
  }
1786
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);
1787
1832
  if (!opts.wait) {
1788
1833
  // No-wait path: return the trigger response as-is.
1789
1834
  if (opts.output !== 'json') {
@@ -1822,12 +1867,16 @@ apiUrlForDashboard) {
1822
1867
  finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
1823
1868
  timeoutSeconds: remainingSeconds,
1824
1869
  sleep: deps.sleep,
1870
+ shutdown: shutdownOf(deps),
1825
1871
  onTransition: opts.verbose
1826
1872
  ? (msg) => stderrFn(`[batch-run][verbose] ${testId}: ${msg}`)
1827
1873
  : undefined,
1828
1874
  });
1829
1875
  }
1830
1876
  catch (err) {
1877
+ // Interrupt rejects the fan-out — see the trigger-stage catch above.
1878
+ if (err instanceof InterruptError)
1879
+ throw err;
1831
1880
  if (err instanceof TimeoutError) {
1832
1881
  if (opts.output !== 'json') {
1833
1882
  stderrFn(`[batch-run] ${testId} (runId: ${triggerResponse.runId}) — timed out after ${timeoutSeconds}s`);
@@ -1885,26 +1934,56 @@ apiUrlForDashboard) {
1885
1934
  // used by the other fan-outs in this file (e.g. pollFreshAccepted below).
1886
1935
  let nextIdx = 0;
1887
1936
  let inFlight = 0;
1888
- await new Promise((resolve, reject) => {
1889
- function startNext() {
1890
- while (inFlight < concurrencyLimit && nextIdx < testIds.length) {
1891
- const testId = testIds[nextIdx++];
1892
- inFlight++;
1893
- triggerOne(testId)
1894
- .then(result => {
1895
- batchRunResults.push(result);
1896
- inFlight--;
1897
- startNext();
1898
- if (inFlight === 0 && nextIdx >= testIds.length)
1899
- resolve();
1900
- })
1901
- .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`);
1902
1983
  }
1903
1984
  }
1904
- startNext();
1905
- if (testIds.length === 0)
1906
- resolve();
1907
- });
1985
+ throw fanOutErr;
1986
+ }
1908
1987
  // Sort by testId order (same as input order for stable output).
1909
1988
  batchRunResults.sort((a, b) => testIds.indexOf(a.testId) - testIds.indexOf(b.testId));
1910
1989
  // Emit output.
@@ -3506,6 +3585,33 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
3506
3585
  lines.push(`dashboard ${run.dashboardUrl}`);
3507
3586
  return lines.join('\n');
3508
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
+ }
3509
3615
  /**
3510
3616
  * Render a `TriggerRunResponse` (no-wait path) to human-readable text.
3511
3617
  */
@@ -3641,7 +3747,8 @@ export async function runTestRun(opts, deps = {}) {
3641
3747
  }
3642
3748
  stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}, ` +
3643
3749
  `target: ${inFlightRun.targetUrl}). ` +
3644
- `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}`);
3645
3752
  triggerResponse = {
3646
3753
  runId: currentRunId,
3647
3754
  status: 'queued',
@@ -3667,11 +3774,15 @@ export async function runTestRun(opts, deps = {}) {
3667
3774
  }
3668
3775
  // Auto-resume but emit a stronger advisory so the caller is aware
3669
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.
3670
3780
  stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
3671
3781
  (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
3672
3782
  `). Auto-resuming wait on in-flight run. ` +
3673
- `If you needed a specific target URL, cancel with Ctrl-C and ` +
3674
- `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.`);
3675
3786
  triggerResponse = {
3676
3787
  runId: currentRunId,
3677
3788
  status: 'queued',
@@ -3727,6 +3838,7 @@ export async function runTestRun(opts, deps = {}) {
3727
3838
  finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
3728
3839
  timeoutSeconds: opts.timeoutSeconds,
3729
3840
  sleep: deps.sleep,
3841
+ shutdown: shutdownOf(deps),
3730
3842
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
3731
3843
  onTick: (run, elapsedMs) => {
3732
3844
  const elapsed = Math.round(elapsedMs / 1000);
@@ -3758,13 +3870,14 @@ export async function runTestRun(opts, deps = {}) {
3758
3870
  if (p.targetUrl)
3759
3871
  lines.push(`targetUrl ${p.targetUrl}`);
3760
3872
  lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
3873
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
3761
3874
  return lines.join('\n');
3762
3875
  });
3763
3876
  throw ApiError.fromEnvelope({
3764
3877
  error: {
3765
3878
  code: 'UNSUPPORTED', // exit 7 per errors.md
3766
3879
  message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}.`,
3767
- 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}`,
3768
3881
  requestId: 'local',
3769
3882
  details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
3770
3883
  },
@@ -3792,10 +3905,36 @@ export async function runTestRun(opts, deps = {}) {
3792
3905
  if (p.targetUrl)
3793
3906
  lines.push(`targetUrl ${p.targetUrl}`);
3794
3907
  lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
3908
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
3795
3909
  return lines.join('\n');
3796
3910
  });
3797
3911
  stderrFn(`Run ${triggerResponse.runId} is still in progress (request timed out). ` +
3798
- `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]));
3799
3938
  throw err;
3800
3939
  }
3801
3940
  ticker.finalize();
@@ -3804,20 +3943,20 @@ export async function runTestRun(opts, deps = {}) {
3804
3943
  const elapsed = Math.round((Date.now() - startMs) / 1000);
3805
3944
  const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
3806
3945
  ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
3807
- printRunOrChain(out, withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), opts.createContext, data => renderRunResponseText(data, {
3808
- // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs).
3809
- // This ensures fast BE runs terminal on first poll still render n/a.
3810
- isBackend: beFallbackUsed || opts.type === 'backend',
3811
- }));
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 }));
3812
3951
  // Surface the trigger requestId under --verbose/--debug or JSON mode so
3813
3952
  // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
3814
3953
  // JSON mode always emits to stderr — it never pollutes stdout).
3815
3954
  if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
3816
3955
  stderrFn(`requestId: ${triggerRequestId}`);
3817
3956
  if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
3818
- // BE runs (resolved via the testId fallback) have no run-scoped artifact
3819
- // bundle — their failure bundle is addressed by testId, not runId.
3820
- stderrFn(beFallbackUsed
3957
+ // BE runs have no run-scoped artifact bundle — their failure bundle is
3958
+ // addressed by testId, not runId.
3959
+ stderrFn(isBackend
3821
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.`
3822
3961
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
3823
3962
  }
@@ -3880,6 +4019,7 @@ export async function runTestWaitMany(opts, deps = {}) {
3880
4019
  const run = await pollRunUntilTerminal(client, runId, {
3881
4020
  timeoutSeconds: remainingSeconds,
3882
4021
  sleep: deps.sleep,
4022
+ shutdown: shutdownOf(deps),
3883
4023
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
3884
4024
  onTick: (run, elapsedMs) => {
3885
4025
  const elapsed = Math.round(elapsedMs / 1000);
@@ -3894,6 +4034,11 @@ export async function runTestWaitMany(opts, deps = {}) {
3894
4034
  return { kind: 'timeout' };
3895
4035
  if (err instanceof RequestTimeoutError)
3896
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;
3897
4042
  if (err instanceof ApiError)
3898
4043
  return { kind: 'error', code: err.code, exitCode: err.exitCode };
3899
4044
  return { kind: 'error', code: 'TRANSPORT', exitCode: 10 };
@@ -3926,12 +4071,14 @@ export async function runTestWaitMany(opts, deps = {}) {
3926
4071
  });
3927
4072
  }
3928
4073
  catch (fanOutErr) {
3929
- if (fanOutErr instanceof RequestTimeoutError) {
4074
+ if (fanOutErr instanceof RequestTimeoutError || fanOutErr instanceof InterruptError) {
3930
4075
  // Same contract as the batch pollers: leave stdout parseable before
3931
- // exiting 7. Members that already settled keep their real status; only
4076
+ // exiting. Members that already settled keep their real status; only
3932
4077
  // the still-unfinished ids are marked running and named in the hint
3933
4078
  // (re-attaching to an already-terminal run would be a wasted command).
3934
- ticker.finalize('Multi-run wait — request timed out');
4079
+ ticker.finalize(fanOutErr instanceof InterruptError
4080
+ ? `Multi-run wait — interrupted (${fanOutErr.signal})`
4081
+ : 'Multi-run wait — request timed out');
3935
4082
  const partial = {
3936
4083
  results: opts.runIds.map((runId) => {
3937
4084
  const outcome = outcomes.get(runId);
@@ -3950,7 +4097,12 @@ export async function runTestWaitMany(opts, deps = {}) {
3950
4097
  .filter(r => r.status === 'running' || r.status === 'timeout')
3951
4098
  .map(r => r.runId);
3952
4099
  if (unfinished.length > 0) {
3953
- stderrFn(`Re-attach with: testsprite test wait ${unfinished.join(' ')}`);
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
+ }
3954
4106
  }
3955
4107
  }
3956
4108
  throw fanOutErr;
@@ -3984,7 +4136,7 @@ export async function runTestWaitMany(opts, deps = {}) {
3984
4136
  .filter(r => r.status === 'timeout' || r.status.startsWith('error:'))
3985
4137
  .map(r => r.runId);
3986
4138
  if (unfinishedIds.length > 0) {
3987
- stderrFn(`Re-attach with: testsprite test wait ${unfinishedIds.join(' ')}`);
4139
+ stderrFn(`Re-attach with: testsprite test wait ${unfinishedIds.join(' ')}, or cancel with: testsprite test cancel ${unfinishedIds.join(' ')}`);
3988
4140
  }
3989
4141
  // Worst-status exit: auth escalates (a rejected key fails every member the
3990
4142
  // same way), then timeout/poll-error (7, resumable), then plain failure (1).
@@ -4001,6 +4153,140 @@ export async function runTestWaitMany(opts, deps = {}) {
4001
4153
  }
4002
4154
  return payload;
4003
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
+ }
4004
4290
  /**
4005
4291
  * `test wait <run-id>` — M3.3 piece-3.
4006
4292
  *
@@ -4049,6 +4335,7 @@ export async function runTestWait(opts, deps = {}) {
4049
4335
  finalRun = await pollRunUntilTerminal(client, opts.runId, {
4050
4336
  timeoutSeconds: opts.timeoutSeconds,
4051
4337
  sleep: deps.sleep,
4338
+ shutdown: shutdownOf(deps),
4052
4339
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4053
4340
  onTick: (run, elapsedMs) => {
4054
4341
  const elapsed = Math.round(elapsedMs / 1000);
@@ -4071,13 +4358,14 @@ export async function runTestWait(opts, deps = {}) {
4071
4358
  `runId ${p.runId}`,
4072
4359
  `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
4073
4360
  `hint Re-attach with: testsprite test wait ${p.runId}`,
4361
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
4074
4362
  ].join('\n');
4075
4363
  });
4076
4364
  throw ApiError.fromEnvelope({
4077
4365
  error: {
4078
4366
  code: 'UNSUPPORTED', // exit 7 per errors.md
4079
4367
  message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${opts.runId}.`,
4080
- nextAction: `Resume polling: testsprite test wait ${opts.runId}`,
4368
+ nextAction: `Resume polling: testsprite test wait ${opts.runId}, or cancel it: testsprite test cancel ${opts.runId}`,
4081
4369
  requestId: 'local',
4082
4370
  details: { runId: opts.runId, timeoutSeconds: opts.timeoutSeconds },
4083
4371
  },
@@ -4095,10 +4383,27 @@ export async function runTestWait(opts, deps = {}) {
4095
4383
  `runId ${p.runId}`,
4096
4384
  `status ${p.status} (request timed out)`,
4097
4385
  `hint Re-attach with: testsprite test wait ${p.runId}`,
4386
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
4098
4387
  ].join('\n');
4099
4388
  });
4100
4389
  stderrFn(`Run ${opts.runId} is still in progress (request timed out). ` +
4101
- `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]));
4102
4407
  throw err;
4103
4408
  }
4104
4409
  ticker.finalize();
@@ -4107,11 +4412,14 @@ export async function runTestWait(opts, deps = {}) {
4107
4412
  const elapsed = Math.round((Date.now() - startMs) / 1000);
4108
4413
  const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
4109
4414
  ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
4110
- 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 }));
4111
4419
  if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
4112
- // BE runs (resolved via the testId fallback) have no run-scoped artifact
4113
- // bundle — their failure bundle is addressed by testId, not runId.
4114
- stderrFn(beFallbackUsed
4420
+ // BE runs have no run-scoped artifact bundle — their failure bundle is
4421
+ // addressed by testId, not runId.
4422
+ stderrFn(isBackend
4115
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.`
4116
4424
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
4117
4425
  }
@@ -4444,6 +4752,7 @@ export async function runTestRunAll(opts, deps = {}) {
4444
4752
  const finalRun = await pollRunUntilTerminal(client, runId, {
4445
4753
  timeoutSeconds: remainingSeconds,
4446
4754
  sleep: deps.sleep,
4755
+ shutdown: shutdownOf(deps),
4447
4756
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4448
4757
  onTick: (run, elapsedMs) => {
4449
4758
  const elapsed = Math.round(elapsedMs / 1000);
@@ -4472,6 +4781,11 @@ export async function runTestRunAll(opts, deps = {}) {
4472
4781
  },
4473
4782
  };
4474
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;
4475
4789
  if (err instanceof RequestTimeoutError) {
4476
4790
  // Client-side per-request timeout during polling — classify as timeout
4477
4791
  // (exit 7) so the fan-out completes and stdout carries every runId.
@@ -4505,26 +4819,43 @@ export async function runTestRunAll(opts, deps = {}) {
4505
4819
  // Bounded concurrency fan-out
4506
4820
  let pollIdx = 0;
4507
4821
  let inFlight = 0;
4508
- await new Promise((resolve, reject) => {
4509
- function startNext() {
4510
- while (inFlight < concurrencyLimit && pollIdx < pollable.length) {
4511
- const entry = pollable[pollIdx++];
4512
- inFlight++;
4513
- pollFreshAccepted(entry)
4514
- .then(result => {
4515
- freshRunResults.push(result);
4516
- inFlight--;
4517
- startNext();
4518
- if (inFlight === 0 && pollIdx >= pollable.length)
4519
- resolve();
4520
- })
4521
- .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
+ }
4522
4838
  }
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));
4523
4856
  }
4524
- startNext();
4525
- if (pollable.length === 0)
4526
- resolve();
4527
- });
4857
+ throw fanOutErr;
4858
+ }
4528
4859
  ticker.finalize();
4529
4860
  const passed = freshRunResults.filter(r => r.status === 'passed').length;
4530
4861
  const failed = freshRunResults.filter(r => r.status !== 'passed' && r.status !== 'timeout').length;
@@ -4565,7 +4896,10 @@ export async function runTestRunAll(opts, deps = {}) {
4565
4896
  error: {
4566
4897
  code: 'UNSUPPORTED',
4567
4898
  message: `${timedOut} run${timedOut !== 1 ? 's' : ''} timed out.`,
4568
- 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'),
4569
4903
  requestId: 'local',
4570
4904
  details: { timedOutRunIds, timeoutSeconds: opts.timeoutSeconds },
4571
4905
  },
@@ -4868,6 +5202,7 @@ export async function runTestRerun(opts, deps = {}) {
4868
5202
  return await pollRunUntilTerminal(client, member.runId, {
4869
5203
  timeoutSeconds: opts.timeoutSeconds,
4870
5204
  sleep: deps.sleep,
5205
+ shutdown: shutdownOf(deps),
4871
5206
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4872
5207
  onTick: (run, elapsedMs) => {
4873
5208
  const elapsed = Math.round(elapsedMs / 1000);
@@ -4958,7 +5293,27 @@ export async function runTestRerun(opts, deps = {}) {
4958
5293
  const reattachHints = closureMembers
4959
5294
  .map(m => `testsprite test wait ${m.runId}`)
4960
5295
  .join('\n');
4961
- 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)));
4962
5317
  throw fanOutErr;
4963
5318
  }
4964
5319
  throw fanOutErr;
@@ -4995,7 +5350,7 @@ export async function runTestRerun(opts, deps = {}) {
4995
5350
  error: {
4996
5351
  code: 'UNSUPPORTED',
4997
5352
  message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${namedRunId}.`,
4998
- nextAction: `Resume polling: testsprite test wait ${namedRunId}`,
5353
+ nextAction: `Resume polling: testsprite test wait ${namedRunId}, or cancel it: testsprite test cancel ${namedRunId}`,
4999
5354
  requestId: 'local',
5000
5355
  details: { runId: namedRunId, timeoutSeconds: opts.timeoutSeconds },
5001
5356
  },
@@ -5011,7 +5366,9 @@ export async function runTestRerun(opts, deps = {}) {
5011
5366
  // as a whole was never observed to reach terminal.
5012
5367
  const timedOutMembers = closureFailures.filter(f => f.status === 'timeout');
5013
5368
  if (timedOutMembers.length > 0) {
5014
- 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(' ')}`;
5015
5372
  throw ApiError.fromEnvelope({
5016
5373
  error: {
5017
5374
  code: 'UNSUPPORTED',
@@ -5044,6 +5401,7 @@ export async function runTestRerun(opts, deps = {}) {
5044
5401
  finalRun = await pollRunUntilTerminal(client, rerunResp.runId, {
5045
5402
  timeoutSeconds: opts.timeoutSeconds,
5046
5403
  sleep: deps.sleep,
5404
+ shutdown: shutdownOf(deps),
5047
5405
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5048
5406
  onTick: (run, elapsedMs) => {
5049
5407
  const elapsed = Math.round(elapsedMs / 1000);
@@ -5060,7 +5418,7 @@ export async function runTestRerun(opts, deps = {}) {
5060
5418
  error: {
5061
5419
  code: 'UNSUPPORTED',
5062
5420
  message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${rerunResp.runId}.`,
5063
- 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}`,
5064
5422
  requestId: 'local',
5065
5423
  details: { runId: rerunResp.runId, timeoutSeconds: opts.timeoutSeconds },
5066
5424
  },
@@ -5077,10 +5435,27 @@ export async function runTestRerun(opts, deps = {}) {
5077
5435
  `runId ${p.runId}`,
5078
5436
  `status ${p.status} (request timed out)`,
5079
5437
  `hint Re-attach with: testsprite test wait ${p.runId}`,
5438
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
5080
5439
  ].join('\n');
5081
5440
  });
5082
5441
  stderrFn(`Run ${rerunResp.runId} is still in progress (request timed out). ` +
5083
- `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]));
5084
5459
  throw err;
5085
5460
  }
5086
5461
  ticker.finalize();
@@ -5090,9 +5465,16 @@ export async function runTestRerun(opts, deps = {}) {
5090
5465
  void elapsed;
5091
5466
  const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5092
5467
  ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps replay)`);
5093
- 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 }));
5094
5473
  if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
5095
- 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.`);
5096
5478
  }
5097
5479
  const exitCode = exitCodeForRunStatus(finalRun.status);
5098
5480
  if (exitCode !== 0) {
@@ -5459,6 +5841,7 @@ export async function runTestRerun(opts, deps = {}) {
5459
5841
  const finalRun = await pollRunUntilTerminal(client, entry.runId, {
5460
5842
  timeoutSeconds: remainingSeconds,
5461
5843
  sleep: deps.sleep,
5844
+ shutdown: shutdownOf(deps),
5462
5845
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5463
5846
  onTick: (run, elapsedMs) => {
5464
5847
  const elapsed = Math.round(elapsedMs / 1000);
@@ -5487,6 +5870,11 @@ export async function runTestRerun(opts, deps = {}) {
5487
5870
  },
5488
5871
  };
5489
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;
5490
5878
  if (err instanceof RequestTimeoutError) {
5491
5879
  // Client-side per-request timeout during polling — classify as timeout
5492
5880
  // (exit 7) so the fan-out completes and stdout carries every runId.
@@ -5520,26 +5908,43 @@ export async function runTestRerun(opts, deps = {}) {
5520
5908
  // Bounded concurrency fan-out
5521
5909
  let acceptedIdx = 0;
5522
5910
  let inFlight = 0;
5523
- await new Promise((resolve, reject) => {
5524
- function startNext() {
5525
- while (inFlight < concurrencyLimit && acceptedIdx < accepted.length) {
5526
- const entry = accepted[acceptedIdx++];
5527
- inFlight++;
5528
- pollAccepted(entry)
5529
- .then(result => {
5530
- rerunResults.push(result);
5531
- inFlight--;
5532
- startNext();
5533
- if (inFlight === 0 && acceptedIdx >= accepted.length)
5534
- resolve();
5535
- })
5536
- .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
+ }
5537
5927
  }
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));
5538
5945
  }
5539
- startNext();
5540
- if (accepted.length === 0)
5541
- resolve();
5542
- });
5946
+ throw fanOutErr;
5947
+ }
5543
5948
  ticker.finalize();
5544
5949
  const passed = rerunResults.filter(r => r.status === 'passed').length;
5545
5950
  const failed = rerunResults.filter(r => r.status !== 'passed' && r.status !== 'timeout').length;
@@ -5595,6 +6000,7 @@ export async function runTestRerun(opts, deps = {}) {
5595
6000
  // `test wait` accepts exactly one run id — emit one command per
5596
6001
  // timed-out run so the hint is always valid.
5597
6002
  ...(timedOut > 0 ? stillRunning.map(rid => `Resume: testsprite test wait ${rid}`) : []),
6003
+ ...(timedOut > 0 ? stillRunning.map(rid => `Cancel: testsprite test cancel ${rid}`) : []),
5598
6004
  ]
5599
6005
  .filter(Boolean)
5600
6006
  .join('\n'),
@@ -6072,6 +6478,9 @@ export function createTestCommand(deps = {}) {
6072
6478
  .option('--name <name>', 'new human-readable test name')
6073
6479
  .option('--description <text>', 'new human description (≤ 2000 chars)')
6074
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.")
6075
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.')
6076
6485
  .addHelpText('after', GLOBAL_OPTS_HINT)
6077
6486
  .action(async (testId, cmdOpts, command) => {
@@ -6081,6 +6490,9 @@ export function createTestCommand(deps = {}) {
6081
6490
  name: cmdOpts.name,
6082
6491
  description: cmdOpts.description,
6083
6492
  priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
6493
+ produces: cmdOpts.produces,
6494
+ needs: cmdOpts.needs,
6495
+ category: cmdOpts.category,
6084
6496
  idempotencyKey: cmdOpts.idempotencyKey,
6085
6497
  }, deps);
6086
6498
  });
@@ -6140,10 +6552,13 @@ export function createTestCommand(deps = {}) {
6140
6552
  ' 4 test not found\n' +
6141
6553
  ' 5 validation error (e.g., bad --target-url, or positional + --all both set)\n' +
6142
6554
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
6143
- ' 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' +
6144
6557
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
6145
6558
  ' 11 rate limited — honor Retry-After\n' +
6146
- '\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>')
6147
6562
  .option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private IPs)')
6148
6563
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
6149
6564
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
@@ -6244,7 +6659,9 @@ export function createTestCommand(deps = {}) {
6244
6659
  ' is recorded as error:<CODE> in its row and folded into exit 7)\n' +
6245
6660
  ' 7 timeout or per-member poll error — resume with: testsprite test wait <run-id...>\n' +
6246
6661
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
6247
- '\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...>')
6248
6665
  .option('--timeout <s>', `max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6249
6666
  .option('--max-concurrency <n>', 'with several run-ids, max concurrent polls (1-100, default: 10)')
6250
6667
  .addHelpText('after', GLOBAL_OPTS_HINT)
@@ -6283,9 +6700,12 @@ export function createTestCommand(deps = {}) {
6283
6700
  ' 4 test not found\n' +
6284
6701
  ' 5 validation error\n' +
6285
6702
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
6286
- ' 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' +
6287
6705
  ' 11 rate limited — honor Retry-After\n' +
6288
- '\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>')
6289
6709
  .option('--all', 'rerun all tests in the resolved project (requires --project)', false)
6290
6710
  .option('--project <id>', 'project id (required with --all; returned by `testsprite project list`)')
6291
6711
  .option('--skip-terminal', 'with --all: skip tests already in a terminal status (passed|failed|blocked|cancelled)', false)
@@ -6386,6 +6806,7 @@ export function createTestCommand(deps = {}) {
6386
6806
  test.addCommand(createTestPlanCommand(deps));
6387
6807
  test.addCommand(createTestFailureCommand(deps));
6388
6808
  test.addCommand(createTestArtifactCommand(deps));
6809
+ test.addCommand(createTestCancelCommand(deps));
6389
6810
  return test;
6390
6811
  }
6391
6812
  // ---------------------------------------------------------------------------
@@ -6493,6 +6914,7 @@ export async function runFlaky(opts, deps = {}) {
6493
6914
  const finalRun = await pollRunUntilTerminal(client, runId, {
6494
6915
  timeoutSeconds: opts.timeoutSeconds,
6495
6916
  sleep: deps.sleep,
6917
+ shutdown: shutdownOf(deps),
6496
6918
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6497
6919
  resolveAlternate,
6498
6920
  });
@@ -6500,6 +6922,13 @@ export async function runFlaky(opts, deps = {}) {
6500
6922
  failureKind = finalRun.failureKind;
6501
6923
  }
6502
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
+ }
6503
6932
  // A per-attempt deadline (poll TimeoutError) or a client-side request
6504
6933
  // timeout both count as a non-passing "timeout" outcome for this attempt.
6505
6934
  if (err instanceof TimeoutError || err instanceof RequestTimeoutError) {
@@ -6606,6 +7035,7 @@ function makeClient(opts, deps) {
6606
7035
  credentialsPath: deps.credentialsPath,
6607
7036
  fetchImpl: deps.fetchImpl,
6608
7037
  stderr: deps.stderr,
7038
+ shutdownSignal: shutdownOf(deps).signal,
6609
7039
  });
6610
7040
  }
6611
7041
  function makeOutput(mode, deps) {
@@ -6888,6 +7318,16 @@ function renderTestText(t) {
6888
7318
  if (typeof t.planStepCount === 'number') {
6889
7319
  lines.push(`planSteps: ${t.planStepCount}`);
6890
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
+ }
6891
7331
  lines.push(`createdAt: ${t.createdAt}`, `updatedAt: ${t.updatedAt}`);
6892
7332
  return lines.join('\n');
6893
7333
  }
@@ -7018,6 +7458,10 @@ function renderFailureContextText(ctx) {
7018
7458
  }
7019
7459
  if (ctx.result.videoUrl !== null)
7020
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);
7021
7465
  return lines.join('\n');
7022
7466
  }
7023
7467
  function renderBundleWrittenText(data) {
@@ -7137,6 +7581,9 @@ function renderResultText(r) {
7137
7581
  lines.push(`videoUrl: ${r.videoUrl}`);
7138
7582
  if (r.failureAnalysisUrl !== null)
7139
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);
7140
7587
  if (r.analysis !== undefined) {
7141
7588
  // §6.5.1 (M2.1 piece 3) — render the inline analysis block under
7142
7589
  // the result summary. Only fires when the caller passed
@@ -7159,6 +7606,33 @@ function renderResultText(r) {
7159
7606
  * level null. Non-null wrappers render `kind=...` plus an optional
7160
7607
  * reference and indented rationale.
7161
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
+ }
7162
7636
  function appendFixTargetLines(lines, fix, label) {
7163
7637
  if (fix === null) {
7164
7638
  lines.push(`${label}— (analysis pipeline did not propose one)`);