@testsprite/testsprite-cli 0.3.0 → 0.5.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 (63) hide show
  1. package/README.md +55 -29
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +51 -0
  4. package/dist/commands/auth.js +46 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +56 -16
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +102 -4
  11. package/dist/commands/project.js +250 -47
  12. package/dist/commands/test.d.ts +253 -11
  13. package/dist/commands/test.js +1822 -390
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +172 -29
  17. package/dist/lib/browser.d.ts +6 -0
  18. package/dist/lib/browser.js +54 -0
  19. package/dist/lib/bundle.d.ts +32 -31
  20. package/dist/lib/bundle.js +144 -84
  21. package/dist/lib/client-factory.d.ts +29 -0
  22. package/dist/lib/client-factory.js +49 -1
  23. package/dist/lib/config.js +7 -3
  24. package/dist/lib/credentials.d.ts +17 -1
  25. package/dist/lib/credentials.js +175 -16
  26. package/dist/lib/dry-run/samples.js +51 -1
  27. package/dist/lib/errors.d.ts +33 -1
  28. package/dist/lib/errors.js +110 -19
  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 +12 -1
  32. package/dist/lib/flaky.js +7 -12
  33. package/dist/lib/gh-output.d.ts +62 -0
  34. package/dist/lib/gh-output.js +99 -0
  35. package/dist/lib/http.d.ts +86 -16
  36. package/dist/lib/http.js +181 -11
  37. package/dist/lib/interrupt.d.ts +65 -10
  38. package/dist/lib/interrupt.js +94 -9
  39. package/dist/lib/org-render.d.ts +52 -0
  40. package/dist/lib/org-render.js +59 -0
  41. package/dist/lib/poll.d.ts +11 -0
  42. package/dist/lib/poll.js +71 -6
  43. package/dist/lib/render-error.d.ts +14 -0
  44. package/dist/lib/render-error.js +30 -0
  45. package/dist/lib/response-schemas.d.ts +83 -0
  46. package/dist/lib/response-schemas.js +272 -0
  47. package/dist/lib/runs.types.d.ts +62 -8
  48. package/dist/lib/skill-nudge.d.ts +17 -0
  49. package/dist/lib/skill-nudge.js +19 -0
  50. package/dist/lib/telemetry.d.ts +90 -0
  51. package/dist/lib/telemetry.js +171 -0
  52. package/dist/lib/text-table.d.ts +14 -0
  53. package/dist/lib/text-table.js +45 -0
  54. package/dist/lib/v3-advisory.d.ts +22 -0
  55. package/dist/lib/v3-advisory.js +32 -0
  56. package/dist/lib/version-notice.d.ts +37 -0
  57. package/dist/lib/version-notice.js +87 -0
  58. package/dist/version.d.ts +1 -1
  59. package/dist/version.js +1 -1
  60. package/package.json +16 -5
  61. package/schemas/plan.schema.json +61 -0
  62. package/skills/testsprite-verify.codex.md +8 -2
  63. package/skills/testsprite-verify.skill.md +18 -7
@@ -1,25 +1,69 @@
1
- import { createWriteStream, existsSync, readFileSync, readdirSync, statSync, } from 'node:fs';
1
+ import { appendFileSync, createWriteStream, existsSync, readFileSync, readdirSync, statSync, writeFileSync, } 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 { openInBrowser } from '../lib/browser.js';
6
7
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
7
- import { assertContextIntegrity, buildMeta, pickCodeExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
8
+ import { assertContextIntegrity, buildMeta, pickCodeExtension, pickVideoExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
8
9
  import { findSample, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
9
10
  import { assertJUnitReportOptions, buildJUnitReport, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
10
- import { ApiError, CLIError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
11
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
12
+ import { globalShutdown } from '../lib/interrupt.js';
11
13
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
12
14
  import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.js';
15
+ import { VERSION } from '../version.js';
13
16
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
14
17
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
15
18
  import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
16
19
  import { RUN_SOURCES } from '../lib/runs.types.js';
17
20
  import { assertNotLocal } from '../lib/target-url.js';
21
+ import { formatTextTableRow, measureTextColumns, renderTextTable, resolveTextColumns, } from '../lib/text-table.js';
18
22
  import { createTicker } from '../lib/ticker.js';
19
23
  import { RateThrottle } from '../lib/rate-throttle.js';
20
24
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
25
+ import { emitGithubOutputs, summarizeAcceptedPayload } from '../lib/gh-output.js';
21
26
  import { loadConfig } from '../lib/config.js';
22
27
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
28
+ /** The effective shutdown handle for a command invocation (DEV-331). */
29
+ function shutdownOf(deps) {
30
+ return deps.shutdown ?? globalShutdown;
31
+ }
32
+ /**
33
+ * The honest-detach stderr line (DEV-331 D1 — the heart of the ticket):
34
+ * a Ctrl-C detaches the local wait only; the server-side run keeps executing
35
+ * AND billing. Names both re-attach (`test wait`) and the real cancel
36
+ * (`test cancel`, piece 3) so the user always has a path to actually stop it.
37
+ */
38
+ function interruptDetachMessage(err, runIds) {
39
+ const subject = runIds.length === 1
40
+ ? `Run ${runIds[0]} is still executing on the server and will keep running (and billing) until it finishes.`
41
+ : `${runIds.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
42
+ return (`Interrupted (${err.signal}). ${subject}\n` +
43
+ ` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
44
+ ` Cancel with: testsprite test cancel ${runIds.join(' ')}`);
45
+ }
46
+ /**
47
+ * The honest-detach stderr line for a RATE_LIMITED (429) hit during a
48
+ * `--wait` poll. The backend's pre-auth rate limiter is an in-process LRU
49
+ * keyed on `request.ip`, checked before any DB contact — it can trip on a
50
+ * shared egress IP (a CI runner, a NAT) and then 429 otherwise-valid keys
51
+ * from that IP for its window. The run itself was already triggered (and is
52
+ * already billed) and keeps executing server-side regardless of this local
53
+ * poll giving up — mirrors `interruptDetachMessage` so the re-attach and
54
+ * cancel commands read identically across every detach reason.
55
+ */
56
+ function rateLimitedDetachMessage(err, runIds) {
57
+ const retrySuffix = err.retryAfterMs !== undefined
58
+ ? `; the server asked to retry after ~${Math.ceil(err.retryAfterMs / 1000)}s`
59
+ : '';
60
+ const subject = runIds.length === 1
61
+ ? `Run ${runIds[0]} is still executing on the server and will keep running (and billing) until it finishes.`
62
+ : `${runIds.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
63
+ return (`Rate limited by the server (HTTP 429)${retrySuffix}. ${subject}\n` +
64
+ ` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
65
+ ` Cancel with: testsprite test cancel ${runIds.join(' ')}`);
66
+ }
23
67
  const TEST_TYPES = ['frontend', 'backend'];
24
68
  // 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
25
69
  // tests created via `testsprite test create`, so the `--created-from cli`
@@ -67,7 +111,8 @@ export async function runList(opts, deps = {}) {
67
111
  // (exit 3) when the caller also lacks a configured key. Order matters
68
112
  // for the CLI error spec §2 — bad input is a caller bug, not an auth
69
113
  // gate.
70
- requireProjectId(opts.projectId);
114
+ const projectId = resolveProjectId(opts.projectId, deps);
115
+ requireProjectId(projectId);
71
116
  const paginationFlags = validatePaginationFlags({
72
117
  pageSize: opts.pageSize,
73
118
  startingToken: opts.startingToken,
@@ -79,13 +124,16 @@ export async function runList(opts, deps = {}) {
79
124
  // a round trip.
80
125
  validateStatusFilter(opts.status);
81
126
  const out = makeOutput(opts.output, deps);
127
+ if (opts.output === 'text') {
128
+ resolveTextColumns(opts.columns, TEST_LIST_COLUMNS);
129
+ }
82
130
  const client = makeClient(opts, deps);
83
131
  // Match P2's "explicit pageSize ⇒ single-page" convention so an
84
132
  // operator can grab one slice + cursor without auto-paging through a
85
133
  // huge project.
86
134
  const useSinglePage = opts.pageSize !== undefined && opts.maxItems === undefined;
87
135
  const baseQuery = {
88
- projectId: opts.projectId,
136
+ projectId,
89
137
  type: opts.type,
90
138
  createdFrom: opts.createdFrom,
91
139
  status: opts.status,
@@ -99,7 +147,7 @@ export async function runList(opts, deps = {}) {
99
147
  query: { ...baseQuery, pageSize, cursor },
100
148
  }), paginationFlags);
101
149
  }
102
- out.print(page, data => renderTestListText(data));
150
+ out.print(page, data => renderTestListText(data, { columns: opts.columns, noHeader: opts.noHeader }));
103
151
  return page;
104
152
  }
105
153
  export const CLI_CREATE_PRIORITIES = ['p0', 'p1', 'p2', 'p3'];
@@ -200,7 +248,8 @@ export async function runCreate(opts, deps = {}) {
200
248
  assertChainedRunKeyFits(opts.run, opts.idempotencyKey);
201
249
  // Validate inputs before touching credentials or fs — matches the
202
250
  // M2 read commands' "input gates first, then auth, then I/O" ordering.
203
- requireProjectId(opts.projectId);
251
+ const projectId = resolveProjectId(opts.projectId, deps);
252
+ requireProjectId(projectId);
204
253
  requireNonEmpty('name', opts.name);
205
254
  // P1-3: client-side length checks matching server limits (name ≤200,
206
255
  // description ≤2000) so the user gets instant, actionable errors instead
@@ -276,7 +325,7 @@ export async function runCreate(opts, deps = {}) {
276
325
  stderr(`idempotency-key: ${idempotencyKey}`);
277
326
  }
278
327
  const body = {
279
- projectId: opts.projectId,
328
+ projectId,
280
329
  type: opts.type,
281
330
  name: opts.name,
282
331
  description: opts.description,
@@ -313,7 +362,7 @@ export async function runCreate(opts, deps = {}) {
313
362
  // B3: best-effort duplicate-name advisory. Skip under --dry-run.
314
363
  if (!opts.dryRun) {
315
364
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
316
- await emitDupNameAdvisoryIfNeeded(client, opts.projectId, opts.name, stderrFn);
365
+ await emitDupNameAdvisoryIfNeeded(client, projectId, opts.name, stderrFn);
317
366
  }
318
367
  const response = await client.post('/tests', {
319
368
  body,
@@ -335,7 +384,7 @@ export async function runCreate(opts, deps = {}) {
335
384
  // R1: suppress under --dry-run (fake canned test id).
336
385
  const chainDashboardUrl = opts.dryRun
337
386
  ? undefined
338
- : resolvePortalUrl(resolveApiUrl(opts, deps), opts.projectId, response.testId);
387
+ : resolvePortalUrl(resolveApiUrl(opts, deps), projectId, response.testId);
339
388
  const createContextWithUrl = chainDashboardUrl !== undefined ? { ...response, dashboardUrl: chainDashboardUrl } : response;
340
389
  await runTestRun({
341
390
  ...opts,
@@ -360,7 +409,7 @@ export async function runCreate(opts, deps = {}) {
360
409
  // (e.g. "test_dryrun_create_2026") and a live-looking URL would mislead.
361
410
  const dashboardUrl = opts.dryRun
362
411
  ? undefined
363
- : resolvePortalUrl(resolveApiUrl(opts, deps), opts.projectId, response.testId);
412
+ : resolvePortalUrl(resolveApiUrl(opts, deps), projectId, response.testId);
364
413
  if (opts.output === 'json') {
365
414
  out.print(dashboardUrl !== undefined ? { ...response, dashboardUrl } : response, data => renderCreateText(data));
366
415
  }
@@ -571,6 +620,18 @@ function renderPlanPutText(response) {
571
620
  * 256 KB (vs. 350 KB for code) per the piece-6 spec.
572
621
  */
573
622
  function readPlanStepsFileGuarded(path) {
623
+ return assertPlanStepsShape(parsePlanStepsFile(path));
624
+ }
625
+ /**
626
+ * File I/O + JSON.parse half of `readPlanStepsFileGuarded`, split out so
627
+ * `test lint` can reuse the SAME stat/size/read/parse guards while
628
+ * substituting the collect-all `collectPlanStepsIssues` shape check for the
629
+ * throw-on-first `assertPlanStepsShape` that `test plan put` still uses. A
630
+ * failure here (missing file, oversize, invalid JSON syntax) is always a
631
+ * single fatal issue either way — there is nothing left to validate once the
632
+ * file itself can't be read or parsed.
633
+ */
634
+ function parsePlanStepsFile(path) {
574
635
  const absolute = resolveAbsolute(path);
575
636
  let stat;
576
637
  try {
@@ -610,15 +671,13 @@ function readPlanStepsFileGuarded(path) {
610
671
  const reason = err instanceof Error ? err.message : 'unknown error';
611
672
  throw localValidationError('steps', `cannot read ${path}: ${reason}`);
612
673
  }
613
- let parsed;
614
674
  try {
615
- parsed = JSON.parse(raw);
675
+ return JSON.parse(raw);
616
676
  }
617
677
  catch (err) {
618
678
  const reason = err instanceof Error ? err.message : 'unknown error';
619
679
  throw localValidationError('steps', `not valid JSON: ${reason}`);
620
680
  }
621
- return assertPlanStepsShape(parsed);
622
681
  }
623
682
  /**
624
683
  * Type-narrow + validate a parsed `{ planSteps: [...] }` envelope.
@@ -650,6 +709,59 @@ function assertPlanStepsShape(parsed) {
650
709
  }
651
710
  return stepsRaw;
652
711
  }
712
+ /**
713
+ * Collect-all counterpart to `assertPlanStepsShape` — same field checks
714
+ * (reusing the identical `requireArrayLength`/`requireEnum`/`requireString`
715
+ * helpers so wording never drifts), but continues past the first failing
716
+ * field instead of throwing. Used exclusively by `test lint`: a
717
+ * `--steps` file with several bad steps previously cost one fix-and-rerun
718
+ * cycle per step. `assertPlanStepsShape` itself is UNCHANGED and stays
719
+ * throw-on-first — `test plan put` only needs the first blocking error per
720
+ * network round-trip.
721
+ */
722
+ function collectPlanStepsIssues(parsed) {
723
+ const issues = [];
724
+ const check = (validate) => {
725
+ try {
726
+ validate();
727
+ }
728
+ catch (err) {
729
+ issues.push(toLintIssue(err));
730
+ }
731
+ };
732
+ let stepsRaw;
733
+ if (Array.isArray(parsed)) {
734
+ stepsRaw = parsed;
735
+ }
736
+ else if (typeof parsed === 'object' && parsed !== null) {
737
+ stepsRaw = parsed.planSteps;
738
+ }
739
+ else {
740
+ issues.push({ field: 'steps', reason: 'must be a JSON object with a `planSteps` array' });
741
+ return issues;
742
+ }
743
+ check(() => requireArrayLength('planSteps', stepsRaw, { min: 1, max: MAX_PLAN_STEPS, itemNoun: 'step' }));
744
+ // A length/cap violation (e.g. 201 steps, over
745
+ // MAX_PLAN_STEPS) does NOT mean there's nothing left to check — `stepsRaw`
746
+ // is still a real, iterable array, so per-element problems must be
747
+ // collected too (a 201-step file with a bad step 0 must report the cap
748
+ // issue AND planSteps[0].type/description in the SAME pass, not one or the
749
+ // other). Only bail when `stepsRaw` isn't an array at all — `requireArrayLength`'s
750
+ // structural check failed, so there is genuinely nothing to iterate.
751
+ if (!Array.isArray(stepsRaw))
752
+ return issues;
753
+ for (let i = 0; i < stepsRaw.length; i += 1) {
754
+ const step = stepsRaw[i];
755
+ if (typeof step !== 'object' || step === null || Array.isArray(step)) {
756
+ issues.push({ field: `planSteps[${i}]`, reason: 'must be an object' });
757
+ continue;
758
+ }
759
+ const s = step;
760
+ check(() => requireEnum(`planSteps[${i}].type`, s.type, PLAN_STEP_TYPES));
761
+ check(() => requireString(`planSteps[${i}].description`, s.description));
762
+ }
763
+ return issues;
764
+ }
653
765
  /**
654
766
  * `test update <test-id>` — M3.2 piece-3.
655
767
  *
@@ -695,8 +807,11 @@ export async function runUpdate(opts, deps = {}) {
695
807
  const hasName = opts.name !== undefined;
696
808
  const hasDescription = opts.description !== undefined;
697
809
  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']);
810
+ const hasProduces = opts.produces !== undefined && opts.produces.length > 0;
811
+ const hasNeeds = opts.needs !== undefined && opts.needs.length > 0;
812
+ const hasCategory = opts.category !== undefined;
813
+ if (!hasName && !hasDescription && !hasPriority && !hasProduces && !hasNeeds && !hasCategory) {
814
+ throw localValidationError('fields', 'at least one of --name / --description / --priority / --produces / --needs / --category must be set', ['name', 'description', 'priority', 'produces', 'needs', 'category']);
700
815
  }
701
816
  const idempotencyKey = opts.idempotencyKey ?? `cli-update-${randomUUID()}`;
702
817
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
@@ -715,6 +830,12 @@ export async function runUpdate(opts, deps = {}) {
715
830
  body.description = opts.description;
716
831
  if (hasPriority)
717
832
  body.priority = opts.priority;
833
+ if (hasProduces)
834
+ body.produces = opts.produces;
835
+ if (hasNeeds)
836
+ body.consumes = opts.needs;
837
+ if (hasCategory)
838
+ body.category = opts.category;
718
839
  const client = makeClient(opts, deps);
719
840
  const out = makeOutput(opts.output, deps);
720
841
  const response = await client.put(`/tests/${encodeURIComponent(opts.testId)}`, {
@@ -932,6 +1053,84 @@ function renderBulkDeleteText(bulk) {
932
1053
  return [header, ...rows].join('\n');
933
1054
  }
934
1055
  const PLAN_STEP_TYPES = ['action', 'assertion'];
1056
+ /**
1057
+ * Public raw-content URL for
1058
+ * `schemas/plan.schema.json`, shipped in both the npm package (see
1059
+ * `package.json` `files`) and the repo. Points at the PUBLIC mirror
1060
+ * (`TestSprite/testsprite-cli`) since that's what ships to npm consumers;
1061
+ * the private atlas repo syncs to it via `scripts/make-public-snapshot.sh`.
1062
+ *
1063
+ * Pinned to the running CLI's own `v<VERSION>` git tag (the same `VERSION`
1064
+ * constant `--version` / `doctor` / the update-check registry probe already
1065
+ * read from `src/version.ts`) rather than the mutable `main` branch — a plan
1066
+ * file authored against one CLI version should resolve the SAME schema
1067
+ * forever, not whatever `main` happens to contain when the file is opened
1068
+ * months later (`main` can gain new required fields between versions).
1069
+ *
1070
+ * This is deliberately DIFFERENT from `schemas/plan.schema.json`'s own
1071
+ * internal `$id`, which stays the canonical `main` URL — `$id` is a schema
1072
+ * IDENTITY (what this document calls itself, used for cross-referencing),
1073
+ * not a fetch instruction, so it is intentionally version-independent.
1074
+ * `PLAN_SCHEMA_URL` is the fetch instruction embedded in generated plan
1075
+ * files and is intentionally version-PINNED. See DOCUMENTATION.md's "Plan
1076
+ * file format" section for the same distinction spelled out for humans.
1077
+ *
1078
+ * Caveat: the pinned tag only resolves once that version is actually
1079
+ * released — a locally-built/pre-release checkout may see a 404 until then.
1080
+ */
1081
+ export const PLAN_SCHEMA_URL = `https://raw.githubusercontent.com/TestSprite/testsprite-cli/v${VERSION}/schemas/plan.schema.json`;
1082
+ /**
1083
+ * The SINGLE canonical example plan. This
1084
+ * exact value (via `PLAN_TEMPLATE_TEXT` below) is:
1085
+ * - printed to stdout by `test create --plan-template`
1086
+ * - embedded verbatim in `test create --help` (`PLAN_TEMPLATE_HELP_TEXT`)
1087
+ * - asserted in tests against `schemas/plan.schema.json` and against
1088
+ * `assertPlanShape` so the three surfaces can't drift
1089
+ *
1090
+ * Deliberately minimal (no optional `description`/`priority`) — this is
1091
+ * the smallest shape `assertPlanShape` accepts, not a fully-annotated
1092
+ * showcase (that lives in `skills/testsprite-verify.skill.md`).
1093
+ */
1094
+ export const PLAN_TEMPLATE = {
1095
+ projectId: 'prj_abc123',
1096
+ type: 'frontend',
1097
+ name: 'Login rejects an empty password',
1098
+ planSteps: [
1099
+ {
1100
+ type: 'action',
1101
+ description: 'Navigate to /login and submit the form with an empty password',
1102
+ },
1103
+ {
1104
+ type: 'assertion',
1105
+ description: 'Verify an inline error says the password is required',
1106
+ },
1107
+ ],
1108
+ };
1109
+ /**
1110
+ * `$schema` is an ordinary extra property from `assertPlanShape`'s point of
1111
+ * view (no `additionalProperties` check exists on the plan-from path) — it
1112
+ * validates exactly like a bare `CliPlanInput` while giving editors (VS
1113
+ * Code's JSON language service, and by extension Copilot inline
1114
+ * completions) something to resolve for live validation as the file is
1115
+ * edited.
1116
+ */
1117
+ export const PLAN_TEMPLATE_WITH_SCHEMA = {
1118
+ $schema: PLAN_SCHEMA_URL,
1119
+ ...PLAN_TEMPLATE,
1120
+ };
1121
+ /**
1122
+ * Rendered once from the object above (never hand-formatted separately) so
1123
+ * `test create --plan-template`'s stdout and `test create --help`'s example
1124
+ * are generated from — not merely modeled on — the same source.
1125
+ */
1126
+ export const PLAN_TEMPLATE_TEXT = JSON.stringify(PLAN_TEMPLATE_WITH_SCHEMA, null, 2);
1127
+ /** `test create --help` after-text. Wraps `PLAN_TEMPLATE_TEXT` unmodified. */
1128
+ const PLAN_TEMPLATE_HELP_TEXT = '\nPlan file format (--plan-from <file>) — minimal valid example:\n\n' +
1129
+ `${PLAN_TEMPLATE_TEXT}\n\n` +
1130
+ 'Print this exact skeleton: testsprite test create --plan-template\n' +
1131
+ 'Validate offline (no network): testsprite test create --plan-from <file> --dry-run\n' +
1132
+ 'Multiple tests: test create-batch --plans <file.jsonl> | --plan-from-dir <dir>\n' +
1133
+ 'Full field reference: DOCUMENTATION.md -> "Plan file format"\n';
935
1134
  /**
936
1135
  * 200-step + 256 KB caps on a single plan body. The CLI
937
1136
  * enforces both client-side as a pre-flight guard so an obvious
@@ -962,6 +1161,33 @@ const MAX_BATCH_RERUN_IDS = 50;
962
1161
  * the caller can warn the operator that a shared BE producer/teardown was
963
1162
  * triggered more than once.
964
1163
  */
1164
+ /**
1165
+ * Dedupe `RerunAdvisory[]` by `feature`+`message`. Used to aggregate
1166
+ * `advisories` across chunked batch-rerun dispatch requests (initial dispatch
1167
+ * + D3 deferred-retry attempts) into a single list, and to collapse repeated
1168
+ * per-attempt advisories in `test flaky` into a single summary line.
1169
+ */
1170
+ function dedupeRerunAdvisories(entries) {
1171
+ const seen = new Map();
1172
+ for (const entry of entries) {
1173
+ seen.set(`${entry.feature}|${entry.message}`, entry);
1174
+ }
1175
+ return [...seen.values()];
1176
+ }
1177
+ /**
1178
+ * Print one `[advisory]` stderr line per entry in `advisories`. Mirrors the
1179
+ * existing style of the other rerun advisories (auto-heal engaged / not
1180
+ * applied, BE rerun history). No-op when `advisories` is absent or empty —
1181
+ * this is the common case (every V2 response, every V3 response that did not
1182
+ * request an autoHeal:false opt-out).
1183
+ */
1184
+ function emitRerunAdvisories(stderrFn, advisories) {
1185
+ if (!advisories || advisories.length === 0)
1186
+ return;
1187
+ for (const advisory of advisories) {
1188
+ stderrFn(`[advisory] ${advisory.message}`);
1189
+ }
1190
+ }
965
1191
  function dedupeBatchRerunAccepted(entries) {
966
1192
  const seen = new Map();
967
1193
  let droppedCount = 0;
@@ -1031,6 +1257,60 @@ export const BATCH_RUN_RATE_LIMIT = 50;
1031
1257
  export const BATCH_RUN_RATE_WINDOW_MS = 60_000;
1032
1258
  /** Maximum number of outer RATE_LIMITED retries inside the batch fan-out (beyond HTTP-layer retries). */
1033
1259
  export const BATCH_RUN_RATE_MAX_OUTER_RETRIES = 5;
1260
+ /**
1261
+ * Maximum number of outer RATE_LIMITED retries per member inside the multi-id
1262
+ * `test wait` fan-out (beyond HTTP-layer retries). Lower than the trigger
1263
+ * fan-out's budget on purpose: a throttled *poll* costs nothing but latency and
1264
+ * the run is already executing, so a couple of Retry-After-length backoffs is
1265
+ * enough to ride out one limiter window — burning the whole `--timeout` on
1266
+ * backoff instead of reporting the throttle would be worse than reporting it.
1267
+ */
1268
+ export const WAIT_POLL_RATE_MAX_OUTER_RETRIES = 3;
1269
+ /**
1270
+ * Backoff to honour before retrying a `RATE_LIMITED` response, in ms.
1271
+ *
1272
+ * Precedence: `ApiError.retryAfterMs` (set by `HttpClient` from the HTTP
1273
+ * `Retry-After` header, already clamped to [1s, 300s]) → `details.retryAfterSeconds`
1274
+ * from the envelope body, capped at 120s → 60s. Callers clamp the result to their
1275
+ * own remaining deadline; this function only decides "how long does the server
1276
+ * want us to wait."
1277
+ *
1278
+ * Shared by the `test run --all` trigger fan-out and the multi-id `test wait`
1279
+ * poll fan-out so the two can't drift — they were hand-copies of the same
1280
+ * precedence rule.
1281
+ */
1282
+ /**
1283
+ * Sleep that a termination signal cuts short by rejecting with the signal's
1284
+ * `InterruptError`, so the caller's existing DEV-331 catch owns the detach UX.
1285
+ *
1286
+ * Mirrors `HttpClient.sleepBeforeRetry` — an in-flight backoff must not be a
1287
+ * window where a first Ctrl-C hard-exits with empty stdout. The caller is
1288
+ * responsible for having ARMED the shutdown scope; a disarmed controller never
1289
+ * aborts its signal, so this would otherwise sleep straight through the signal.
1290
+ */
1291
+ export function sleepUntilOrInterrupt(ms, signal, sleep) {
1292
+ if (signal === undefined)
1293
+ return sleep(ms);
1294
+ if (signal.aborted)
1295
+ return Promise.reject(signal.reason);
1296
+ return new Promise((resolve, reject) => {
1297
+ const onAbort = () => reject(signal.reason);
1298
+ signal.addEventListener('abort', onAbort, { once: true });
1299
+ sleep(ms).then(() => {
1300
+ signal.removeEventListener('abort', onAbort);
1301
+ resolve();
1302
+ }, err => {
1303
+ signal.removeEventListener('abort', onAbort);
1304
+ reject(err instanceof Error ? err : new Error(String(err)));
1305
+ });
1306
+ });
1307
+ }
1308
+ export function resolveRateLimitRetryMs(err) {
1309
+ if (err.retryAfterMs !== undefined)
1310
+ return err.retryAfterMs;
1311
+ const retryAfterSec = err.getDetail('retryAfterSeconds', (v) => typeof v === 'number' && v > 0);
1312
+ return Math.min((retryAfterSec ?? 60) * 1000, 120_000);
1313
+ }
1034
1314
  /**
1035
1315
  * D3: max automatic retry attempts for deferred tests under `--wait`.
1036
1316
  * Each attempt is preceded by a Retry-After-aware sleep (server value if
@@ -1087,6 +1367,46 @@ export function isTransientRateLimit(err) {
1087
1367
  // Absent all signals → treat as permanent (credit depletion or unknown).
1088
1368
  return false;
1089
1369
  }
1370
+ /** Matches `{{ANYTHING}}`-style template placeholders in a step description. */
1371
+ const PLACEHOLDER_PATTERN = /\{\{.*?\}\}/;
1372
+ /**
1373
+ * Indices of `planSteps` whose `description` contains a
1374
+ * `{{...}}`-style placeholder. Structurally valid (schema-and-validator
1375
+ * agree these plans pass) — this is a content-quality signal, not a shape
1376
+ * violation, so it's surfaced separately as a non-fatal advisory rather
1377
+ * than folded into `assertPlanShape`.
1378
+ */
1379
+ function findPlaceholderStepIndices(plan) {
1380
+ const indices = [];
1381
+ plan.planSteps.forEach((step, i) => {
1382
+ if (PLACEHOLDER_PATTERN.test(step.description))
1383
+ indices.push(i);
1384
+ });
1385
+ return indices;
1386
+ }
1387
+ /**
1388
+ * Non-fatal `[advisory]` when one or more `planSteps[].description` values
1389
+ * contain a `{{...}}`-style placeholder — the most common false assumption
1390
+ * agent-authored plans make (that the CLI does variable substitution). The
1391
+ * CLI does none: the browser agent types the literal braces into the
1392
+ * field. Points at storing credentials on the project instead, which is
1393
+ * the actual mechanism for injecting auth into a run.
1394
+ */
1395
+ function emitPlaceholderAdvisory(plan, stderrFn) {
1396
+ const indices = findPlaceholderStepIndices(plan);
1397
+ if (indices.length === 0)
1398
+ return;
1399
+ // Each path must read
1400
+ // `planSteps[N].description` on its OWN — appending `.description` once
1401
+ // after a joined `planSteps[0], planSteps[2]` list misattributed it to
1402
+ // only the last entry.
1403
+ const paths = indices.map(i => `planSteps[${i}].description`).join(', ');
1404
+ const verb = indices.length === 1 ? 'contains' : 'contain';
1405
+ stderrFn(`[advisory] ${paths} ${verb} a ` +
1406
+ '`{{...}}`-style placeholder; the CLI does no variable substitution — ' +
1407
+ 'the browser agent will type the literal braces. Store login credentials on the project instead: ' +
1408
+ '`testsprite project update <project-id> --username <user> --password <pw>`, or Portal -> Project Settings.');
1409
+ }
1090
1410
  /**
1091
1411
  * `test create --plan-from <plan.json>` — M3.2 piece-5.
1092
1412
  *
@@ -1116,14 +1436,20 @@ export async function runCreateFromPlan(opts, deps = {}) {
1116
1436
  if (opts.targetUrl !== undefined) {
1117
1437
  assertNotLocal(opts.targetUrl);
1118
1438
  }
1119
- const plan = readPlanFromGuarded(opts.planFrom);
1439
+ const plan = readPlanFromGuarded(opts.planFrom, { ignoredFlags: opts.ignoredFlags });
1440
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1441
+ // Non-fatal advisory for `{{...}}`-style placeholders in step
1442
+ // descriptions. The CLI does no variable substitution — the browser agent
1443
+ // types the literal braces — so this is a content-quality nudge, not a
1444
+ // validation failure. Fires regardless of --dry-run (dry-run still runs
1445
+ // full local validation; this advisory is part of that same offline pass).
1446
+ emitPlaceholderAdvisory(plan, stderrFn);
1120
1447
  // The plan validated (projectId/type/name/planSteps present). Only NOW
1121
1448
  // warn that overlapping `test create` flags were ignored — emitting this
1122
1449
  // before validation made a missing-projectId failure look like the
1123
1450
  // ignored --project flag was the cause (dogfood L1778).
1124
1451
  if (opts.ignoredFlags && opts.ignoredFlags.length > 0) {
1125
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1126
- stderr(`warning: --plan-from supplies the test definition; ignoring ${opts.ignoredFlags.join(', ')}. ` +
1452
+ stderrFn(`warning: --plan-from supplies the test definition; ignoring ${opts.ignoredFlags.join(', ')}. ` +
1127
1453
  `Edit the plan JSON to change these fields.`);
1128
1454
  }
1129
1455
  // FE-only after the 2026-05-13 scope cut. The server also rejects
@@ -1142,8 +1468,7 @@ export async function runCreateFromPlan(opts, deps = {}) {
1142
1468
  }
1143
1469
  const idempotencyKey = opts.idempotencyKey ?? `cli-create-plan-${randomUUID()}`;
1144
1470
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
1145
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1146
- stderr(`idempotency-key: ${idempotencyKey}`);
1471
+ stderrFn(`idempotency-key: ${idempotencyKey}`);
1147
1472
  }
1148
1473
  const body = {
1149
1474
  projectId: plan.projectId,
@@ -1159,7 +1484,6 @@ export async function runCreateFromPlan(opts, deps = {}) {
1159
1484
  // The plan's projectId + name are available after validation above. Skip
1160
1485
  // under dry-run (no network calls); swallow all errors (advisory only).
1161
1486
  if (!opts.dryRun) {
1162
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1163
1487
  await emitDupNameAdvisoryIfNeeded(client, plan.projectId, plan.name, stderrFn);
1164
1488
  }
1165
1489
  const response = await client.post('/tests', {
@@ -1198,7 +1522,6 @@ export async function runCreateFromPlan(opts, deps = {}) {
1198
1522
  else {
1199
1523
  out.print(response, data => renderCreateText(data));
1200
1524
  if (planDashboardUrl !== undefined) {
1201
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1202
1525
  stderrFn(`Dashboard: ${planDashboardUrl}`);
1203
1526
  }
1204
1527
  }
@@ -1213,7 +1536,23 @@ export async function runCreateFromPlan(opts, deps = {}) {
1213
1536
  * obvious oversize files BEFORE loading them into V8's heap. For
1214
1537
  * plans the cap is 256 KB (vs. 350 KB for code).
1215
1538
  */
1216
- function readPlanFromGuarded(path) {
1539
+ function readPlanFromGuarded(path, context = {}) {
1540
+ return assertPlanShape(parsePlanFile(path), context);
1541
+ }
1542
+ /**
1543
+ * File I/O + JSON.parse half of `readPlanFromGuarded`, split out so `test
1544
+ * lint` can reuse the SAME stat/size/read/parse guards while
1545
+ * substituting the collect-all `collectPlanIssues` shape check for the
1546
+ * throw-on-first `assertPlanShape` that `create`/`create-batch` still use. A
1547
+ * failure here (missing file, oversize, invalid JSON syntax) is always a
1548
+ * single fatal issue either way — there is nothing left to validate once the
1549
+ * file itself can't be read or parsed.
1550
+ *
1551
+ * Stat-first guard mirrors piece-2's `readCodeFileGuarded` — reject
1552
+ * obvious oversize files BEFORE loading them into V8's heap. For
1553
+ * plans the cap is 256 KB (vs. 350 KB for code).
1554
+ */
1555
+ function parsePlanFile(path) {
1217
1556
  const absolute = resolveAbsolute(path);
1218
1557
  let stat;
1219
1558
  try {
@@ -1253,15 +1592,45 @@ function readPlanFromGuarded(path) {
1253
1592
  const reason = err instanceof Error ? err.message : 'unknown error';
1254
1593
  throw localValidationError('plan-from', `cannot read ${path}: ${reason}`);
1255
1594
  }
1256
- let parsed;
1257
1595
  try {
1258
- parsed = JSON.parse(raw);
1596
+ return JSON.parse(raw);
1259
1597
  }
1260
1598
  catch (err) {
1261
1599
  const reason = err instanceof Error ? err.message : 'unknown error';
1262
1600
  throw localValidationError('plan-from', `not valid JSON: ${reason}`);
1263
1601
  }
1264
- return assertPlanShape(parsed);
1602
+ }
1603
+ /**
1604
+ * Rethrow a validation error enriched with a note that the
1605
+ * caller's `--project`/`--type`/`--name` flag was ignored, but ONLY when
1606
+ * that flag was actually supplied. Keeps the L1778 ordering intact
1607
+ * (validation still runs, and still throws, before the general
1608
+ * ignored-flags warning in `runCreateFromPlan`) — this only changes the
1609
+ * WORDING of the validation error itself so the one hint that would
1610
+ * explain a missing-field failure lands inside the error the caller
1611
+ * already sees, instead of depending on a separate warning that (per
1612
+ * L1778) deliberately fires after validation succeeds.
1613
+ */
1614
+ function appendIgnoredFlagNote(err, flag) {
1615
+ return new ApiError({
1616
+ code: err.code,
1617
+ message: err.message,
1618
+ nextAction: `${err.nextAction} note: with --plan-from, ${flag} is ignored; all fields live inside the file.`,
1619
+ requestId: err.requestId,
1620
+ details: err.details,
1621
+ });
1622
+ }
1623
+ /** Runs `fn`, enriching any thrown `ApiError` via {@link appendIgnoredFlagNote} when `flag` was ignored. */
1624
+ function requireFieldNotIgnored(fn, flag, ignoredFlags) {
1625
+ try {
1626
+ return fn();
1627
+ }
1628
+ catch (err) {
1629
+ if (err instanceof ApiError && ignoredFlags?.includes(flag)) {
1630
+ throw appendIgnoredFlagNote(err, flag);
1631
+ }
1632
+ throw err;
1633
+ }
1265
1634
  }
1266
1635
  /**
1267
1636
  * Type-narrow + validate a parsed plan input. Pulled out so the same
@@ -1269,26 +1638,55 @@ function readPlanFromGuarded(path) {
1269
1638
  * `create-batch --plans`. Throws `VALIDATION_ERROR` with a typed
1270
1639
  * `details.field` pointer so callers can fix specific issues without
1271
1640
  * re-reading the whole file.
1641
+ *
1642
+ * `context.ignoredFlags` is populated only on the single
1643
+ * `--plan-from` path (`test create --plan-from` also received overlapping
1644
+ * `--project`/`--type`/`--name` flags); batch/dir/JSONL callers never pass
1645
+ * it, so `requireFieldNotIgnored` below is a no-op for them.
1646
+ *
1647
+ * Throw-on-first is intentional here: `create` / `create-batch` POST over
1648
+ * the network, so surfacing the first blocking error per round-trip is the
1649
+ * right cost/detail tradeoff. `test lint`'s collect-all sibling is
1650
+ * `collectPlanIssues` below — do not merge the two; the doc comment on
1651
+ * `collectPlanIssues` explains why they must stay separate.
1272
1652
  */
1273
1653
  function assertPlanShape(parsed, context = {}) {
1274
1654
  const prefix = context.specIndex !== undefined ? `specs[${context.specIndex}].` : '';
1655
+ // A top-level JSON array is the single most common
1656
+ // agent-authored mistake: a plan file holds exactly ONE test. Give it a
1657
+ // dedicated message pointing at the batch surfaces, instead of the
1658
+ // generic "must be a JSON object" (which doesn't say what to do about an
1659
+ // array).
1660
+ if (Array.isArray(parsed)) {
1661
+ throw localValidationError(`${prefix}plan`, `a plan file holds ONE test as a single JSON object (got an array of ${parsed.length}). ` +
1662
+ 'To create many tests use `test create-batch --plans <file.jsonl>` or `--plan-from-dir <dir>`', undefined, 'field');
1663
+ }
1275
1664
  // Every field below is a JSON body path inside the plan file (or
1276
1665
  // JSONL spec), not a CLI flag — pass `'field'` so the error message
1277
1666
  // says `Field \`projectId\` is invalid: ...` instead of inventing a
1278
1667
  // `--projectId` flag the user can't pass.
1279
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
1668
+ if (typeof parsed !== 'object' || parsed === null) {
1280
1669
  throw localValidationError(`${prefix}plan`, 'must be a JSON object', undefined, 'field');
1281
1670
  }
1282
1671
  const obj = parsed;
1283
- requireString(`${prefix}projectId`, obj.projectId);
1284
- requireEnum(`${prefix}type`, obj.type, ['frontend', 'backend']);
1285
- requireString(`${prefix}name`, obj.name);
1672
+ requireFieldNotIgnored(() => requireString(`${prefix}projectId`, obj.projectId), '--project', context.ignoredFlags);
1673
+ requireFieldNotIgnored(() => requireEnum(`${prefix}type`, obj.type, ['frontend', 'backend']), '--type', context.ignoredFlags);
1674
+ requireFieldNotIgnored(() => requireString(`${prefix}name`, obj.name), '--name', context.ignoredFlags);
1286
1675
  if (obj.description !== undefined && typeof obj.description !== 'string') {
1287
1676
  throw localValidationError(`${prefix}description`, 'must be a string when present', undefined, 'field');
1288
1677
  }
1289
1678
  if (obj.priority !== undefined) {
1290
1679
  requireEnum(`${prefix}priority`, obj.priority, CLI_CREATE_PRIORITIES);
1291
1680
  }
1681
+ // `planSteps` missing is the single most common agent
1682
+ // hallucination: LLMs (Copilot included) reliably nest steps under
1683
+ // `plan.steps` or a bare top-level `steps`. Point directly at the fix
1684
+ // instead of falling through to the generic "is required and must be an
1685
+ // array" message, which doesn't say WHERE the steps actually belong.
1686
+ if (obj.planSteps === undefined && (obj.plan !== undefined || obj.steps !== undefined)) {
1687
+ throw localValidationError(`${prefix}planSteps`, 'is required and must be an array. Did you mean `planSteps`? Steps live at the top level: ' +
1688
+ '`"planSteps": [{ "type": "action" | "assertion", "description": "..." }]`', undefined, 'field');
1689
+ }
1292
1690
  requireArrayLength(`${prefix}planSteps`, obj.planSteps, {
1293
1691
  min: 1,
1294
1692
  max: MAX_PLAN_STEPS,
@@ -1305,6 +1703,64 @@ function assertPlanShape(parsed, context = {}) {
1305
1703
  }
1306
1704
  return obj;
1307
1705
  }
1706
+ /**
1707
+ * Collect-all counterpart to `assertPlanShape` — same field checks (reusing
1708
+ * the identical `requireString`/`requireEnum`/`requireArrayLength` helpers
1709
+ * so wording never drifts), but continues past the first failing field
1710
+ * instead of throwing. Used exclusively by `test lint` (issue #98
1711
+ * follow-up): the throw-on-first
1712
+ * `assertPlanShape` meant a plan with 6 independent problems reported one at
1713
+ * a time across 6 fix-and-rerun cycles. `assertPlanShape` itself is
1714
+ * UNCHANGED — `create`/`create-batch` only need the first blocking error per
1715
+ * network round-trip, and duplicating the field checks here (rather than
1716
+ * threading a "collect" flag through the throw-on-first assert) keeps both
1717
+ * functions simple and matches the existing sibling-validator convention
1718
+ * already used between `assertPlanShape` and `assertPlanStepsShape`.
1719
+ */
1720
+ function collectPlanIssues(parsed, context = {}) {
1721
+ const prefix = context.specIndex !== undefined ? `specs[${context.specIndex}].` : '';
1722
+ const issues = [];
1723
+ const check = (validate) => {
1724
+ try {
1725
+ validate();
1726
+ }
1727
+ catch (err) {
1728
+ issues.push(toLintIssue(err));
1729
+ }
1730
+ };
1731
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
1732
+ issues.push({ field: `${prefix}plan`, reason: 'must be a JSON object' });
1733
+ return issues;
1734
+ }
1735
+ const obj = parsed;
1736
+ check(() => requireString(`${prefix}projectId`, obj.projectId));
1737
+ check(() => requireEnum(`${prefix}type`, obj.type, ['frontend', 'backend']));
1738
+ check(() => requireString(`${prefix}name`, obj.name));
1739
+ if (obj.description !== undefined && typeof obj.description !== 'string') {
1740
+ issues.push({ field: `${prefix}description`, reason: 'must be a string when present' });
1741
+ }
1742
+ if (obj.priority !== undefined) {
1743
+ check(() => requireEnum(`${prefix}priority`, obj.priority, CLI_CREATE_PRIORITIES));
1744
+ }
1745
+ check(() => requireArrayLength(`${prefix}planSteps`, obj.planSteps, {
1746
+ min: 1,
1747
+ max: MAX_PLAN_STEPS,
1748
+ itemNoun: 'step',
1749
+ }));
1750
+ if (Array.isArray(obj.planSteps)) {
1751
+ for (let i = 0; i < obj.planSteps.length; i += 1) {
1752
+ const step = obj.planSteps[i];
1753
+ if (typeof step !== 'object' || step === null || Array.isArray(step)) {
1754
+ issues.push({ field: `${prefix}planSteps[${i}]`, reason: 'must be an object' });
1755
+ continue;
1756
+ }
1757
+ const s = step;
1758
+ check(() => requireEnum(`${prefix}planSteps[${i}].type`, s.type, PLAN_STEP_TYPES));
1759
+ check(() => requireString(`${prefix}planSteps[${i}].description`, s.description));
1760
+ }
1761
+ }
1762
+ return issues;
1763
+ }
1308
1764
  /**
1309
1765
  * `test create-batch --plans <plans.jsonl>` — M3.2 piece-5.
1310
1766
  *
@@ -1580,7 +2036,13 @@ apiUrlForDashboard) {
1580
2036
  *
1581
2037
  * Returns a CliBatchRunResult. Never throws — errors are captured
1582
2038
  * into the result's `error` field so one failure doesn't abort siblings.
2039
+ * (Exception: InterruptError rethrows so the collect point can print the
2040
+ * partial — DEV-331.)
1583
2041
  */
2042
+ // testId → dispatched runId for members still mid-poll; the interrupt
2043
+ // partial reads it because a member's runId is local to triggerOne until
2044
+ // the poll settles (DEV-331, codex finding 2).
2045
+ const dispatchedRunIds = new Map();
1584
2046
  async function triggerOne(testId) {
1585
2047
  // Mint a fresh idempotency key per run — MUST NOT reuse the create key.
1586
2048
  const runIdempotencyKey = `cli-batch-run-${randomUUID()}`;
@@ -1661,6 +2123,11 @@ apiUrlForDashboard) {
1661
2123
  break; // success — exit the outer retry loop
1662
2124
  }
1663
2125
  catch (err) {
2126
+ // Interrupt must reject the fan-out (the collect point prints the
2127
+ // partial for every spec), never flatten into a per-member outcome
2128
+ // that would swallow the 128+signum exit (DEV-331).
2129
+ if (err instanceof InterruptError)
2130
+ throw err;
1664
2131
  // RATE_LIMITED outer retry. Since the HTTP layer no longer retries
1665
2132
  // RATE_LIMITED (retryOnRateLimit: false above), every 429 reaches here
1666
2133
  // on the first attempt.
@@ -1690,14 +2157,9 @@ apiUrlForDashboard) {
1690
2157
  // MAJOR 3: use retryAfterMs from the thrown ApiError when available
1691
2158
  // (set by HttpClient from the HTTP Retry-After header, clamped to
1692
2159
  // [1s, 300s]). Fall back to details.retryAfterSeconds, then 60 s.
1693
- let retryAfterMs;
1694
- if (err.retryAfterMs !== undefined) {
1695
- retryAfterMs = err.retryAfterMs;
1696
- }
1697
- else {
1698
- const retryAfterSec = err.getDetail('retryAfterSeconds', (v) => typeof v === 'number' && v > 0);
1699
- retryAfterMs = Math.min((retryAfterSec ?? 60) * 1000, 120_000);
1700
- }
2160
+ // Extracted to `resolveRateLimitRetryMs` so the multi-id `test wait`
2161
+ // poll fan-out applies the identical precedence.
2162
+ const retryAfterMs = resolveRateLimitRetryMs(err);
1701
2163
  // MAJOR 2: clamp to remaining deadline so we don't overshoot the
1702
2164
  // --wait budget.
1703
2165
  const clampedRetryMs = Math.min(retryAfterMs, remainingMs());
@@ -1784,6 +2246,12 @@ apiUrlForDashboard) {
1784
2246
  }
1785
2247
  }
1786
2248
  }
2249
+ // Record the dispatched runId (fresh trigger OR conflict-resume) so the
2250
+ // interrupt partial at the collect point can name every in-flight run —
2251
+ // a member's runId is otherwise local until its poll settles (DEV-331,
2252
+ // codex finding 2).
2253
+ if (triggerResponse.runId)
2254
+ dispatchedRunIds.set(testId, triggerResponse.runId);
1787
2255
  if (!opts.wait) {
1788
2256
  // No-wait path: return the trigger response as-is.
1789
2257
  if (opts.output !== 'json') {
@@ -1822,12 +2290,16 @@ apiUrlForDashboard) {
1822
2290
  finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
1823
2291
  timeoutSeconds: remainingSeconds,
1824
2292
  sleep: deps.sleep,
2293
+ shutdown: shutdownOf(deps),
1825
2294
  onTransition: opts.verbose
1826
2295
  ? (msg) => stderrFn(`[batch-run][verbose] ${testId}: ${msg}`)
1827
2296
  : undefined,
1828
2297
  });
1829
2298
  }
1830
2299
  catch (err) {
2300
+ // Interrupt rejects the fan-out — see the trigger-stage catch above.
2301
+ if (err instanceof InterruptError)
2302
+ throw err;
1831
2303
  if (err instanceof TimeoutError) {
1832
2304
  if (opts.output !== 'json') {
1833
2305
  stderrFn(`[batch-run] ${testId} (runId: ${triggerResponse.runId}) — timed out after ${timeoutSeconds}s`);
@@ -1875,7 +2347,9 @@ apiUrlForDashboard) {
1875
2347
  testId: finalRun.testId,
1876
2348
  runId: finalRun.runId,
1877
2349
  status: finalRun.status,
1878
- codeVersion: finalRun.codeVersion,
2350
+ // Runs without a stored code body report `codeVersion: null`; the batch
2351
+ // envelope uses '' for "unknown", as the trigger-error paths above do.
2352
+ codeVersion: finalRun.codeVersion ?? '',
1879
2353
  videoUrl: finalRun.videoUrl,
1880
2354
  failureKind: finalRun.failureKind,
1881
2355
  };
@@ -1885,26 +2359,56 @@ apiUrlForDashboard) {
1885
2359
  // used by the other fan-outs in this file (e.g. pollFreshAccepted below).
1886
2360
  let nextIdx = 0;
1887
2361
  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);
2362
+ try {
2363
+ await new Promise((resolve, reject) => {
2364
+ function startNext() {
2365
+ while (inFlight < concurrencyLimit && nextIdx < testIds.length) {
2366
+ const testId = testIds[nextIdx++];
2367
+ inFlight++;
2368
+ triggerOne(testId)
2369
+ .then(result => {
2370
+ batchRunResults.push(result);
2371
+ inFlight--;
2372
+ startNext();
2373
+ if (inFlight === 0 && nextIdx >= testIds.length)
2374
+ resolve();
2375
+ })
2376
+ .catch(reject);
2377
+ }
2378
+ }
2379
+ startNext();
2380
+ if (testIds.length === 0)
2381
+ resolve();
2382
+ });
2383
+ }
2384
+ catch (fanOutErr) {
2385
+ // Graceful detach (DEV-331): leave stdout parseable — settled members keep
2386
+ // their real status, unfinished ones are marked running — then rethrow so
2387
+ // index.ts exits 128+signum.
2388
+ if (fanOutErr instanceof InterruptError) {
2389
+ const settled = new Map(batchRunResults.map(r => [r.testId, r]));
2390
+ // Members mid-poll have no settled result yet — their runId comes from
2391
+ // the dispatchedRunIds map recorded at trigger time (codex finding 2).
2392
+ const partialResults = testIds.map((testId) => settled.get(testId) ?? {
2393
+ testId,
2394
+ runId: dispatchedRunIds.get(testId) ?? '',
2395
+ status: dispatchedRunIds.has(testId) ? 'running' : 'not_dispatched',
2396
+ codeVersion: '',
2397
+ });
2398
+ out.print({ results: partialResults }, () => partialResults.map(r => `${r.testId} ${r.runId || '-'} ${r.status}`).join('\n'));
2399
+ const unfinished = partialResults
2400
+ .filter(r => r.status === 'running' && r.runId)
2401
+ .map(r => r.runId);
2402
+ if (unfinished.length > 0) {
2403
+ stderrFn(interruptDetachMessage(fanOutErr, unfinished));
2404
+ }
2405
+ else {
2406
+ stderrFn(`Interrupted (${fanOutErr.signal}). Already-triggered runs keep executing (and billing) server-side; ` +
2407
+ `check them with: testsprite test list`);
1902
2408
  }
1903
2409
  }
1904
- startNext();
1905
- if (testIds.length === 0)
1906
- resolve();
1907
- });
2410
+ throw fanOutErr;
2411
+ }
1908
2412
  // Sort by testId order (same as input order for stable output).
1909
2413
  batchRunResults.sort((a, b) => testIds.indexOf(a.testId) - testIds.indexOf(b.testId));
1910
2414
  // Emit output.
@@ -1923,6 +2427,18 @@ apiUrlForDashboard) {
1923
2427
  : batchRunResults;
1924
2428
  out.print({ results: enrichedResults });
1925
2429
  }
2430
+ else if (!opts.wait) {
2431
+ // Text mode, no --wait: statuses are non-terminal by design ('queued'),
2432
+ // so a pass/fail summary would misread a successful dispatch as
2433
+ // "0/N passed". Report what actually happened: triggers.
2434
+ const total = batchRunResults.length;
2435
+ const erroredCount = batchRunResults.filter(r => r.error !== undefined).length;
2436
+ const parts = [`${total - erroredCount}/${total} triggered`];
2437
+ if (erroredCount > 0) {
2438
+ parts.push(`${erroredCount} trigger error${erroredCount !== 1 ? 's' : ''}`);
2439
+ }
2440
+ stderrFn(`batch-run summary: ${parts.join(', ')}`);
2441
+ }
1926
2442
  else {
1927
2443
  // Text mode: print summary line.
1928
2444
  const passed = batchRunResults.filter(r => r.status === 'passed').length;
@@ -1942,35 +2458,40 @@ apiUrlForDashboard) {
1942
2458
  parts.push(`${errored} error/timeout`);
1943
2459
  stderrFn(`batch-run summary: ${parts.join(', ')}`);
1944
2460
  }
1945
- // Determine exit code.
1946
- const allPassed = batchRunResults.every(r => r.status === 'passed');
1947
- if (allPassed)
2461
+ // Determine exit code. With --wait, success means every run reached the
2462
+ // terminal status 'passed'. Without --wait, statuses are non-terminal by
2463
+ // design ('queued' per CliBatchRunResult), so success means every trigger
2464
+ // dispatched without error — mirroring single `test run` (no --wait),
2465
+ // which exits 0 on a successful queued dispatch.
2466
+ const failing = opts.wait
2467
+ ? batchRunResults.filter(r => r.status !== 'passed')
2468
+ : batchRunResults.filter(r => r.error !== undefined);
2469
+ if (failing.length === 0)
1948
2470
  return; // exit 0
1949
- // Check for a uniform non-pass exit code across all non-passed results.
1950
- const errorExitCodes = batchRunResults
1951
- .filter(r => r.error !== undefined)
1952
- .map(r => r.error.exitCode);
1953
- const nonPassedStatuses = batchRunResults.filter(r => r.status !== 'passed');
2471
+ // Check for a uniform non-pass exit code across all failing results.
2472
+ const errorExitCodes = failing.filter(r => r.error !== undefined).map(r => r.error.exitCode);
1954
2473
  // Exit 7 only when EVERY run timed out — a mix of pass + timeout is "mixed
1955
- // outcomes" (exit 1), not "all timed out". `nonPassedStatuses.every(...)`
2474
+ // outcomes" (exit 1), not "all timed out". `failing.every(...)` alone
1956
2475
  // would incorrectly fire exit 7 when 1 of N passed and the rest timed out.
1957
- const allTimeout = batchRunResults.length > 0 &&
2476
+ const allTimeout = failing.length === batchRunResults.length &&
1958
2477
  batchRunResults.every(r => r.status === 'timeout' || r.error?.exitCode === 7);
1959
2478
  if (allTimeout) {
1960
2479
  throw new CLIError(`All ${batchRunResults.length} batch run(s) timed out after ${timeoutSeconds}s.`, 7);
1961
2480
  }
1962
- // If all non-passed results share the same specific exit code (6 or 11), use it.
1963
- if (errorExitCodes.length > 0 && errorExitCodes.length === nonPassedStatuses.length) {
2481
+ // If all failing results share the same specific exit code (6 or 11), use it.
2482
+ if (errorExitCodes.length > 0 && errorExitCodes.length === failing.length) {
1964
2483
  const uniformCode = errorExitCodes[0];
1965
2484
  if (uniformCode !== undefined &&
1966
2485
  errorExitCodes.every(c => c === uniformCode) &&
1967
2486
  uniformCode !== 1 &&
1968
2487
  uniformCode !== 7) {
1969
- throw new CLIError(`Batch run finished: ${nonPassedStatuses.length} run(s) failed with exit code ${uniformCode}.`, uniformCode);
2488
+ throw new CLIError(`Batch run finished: ${failing.length} run(s) failed with exit code ${uniformCode}.`, uniformCode);
1970
2489
  }
1971
2490
  }
1972
2491
  // Default: mixed outcomes or generic failure → exit 1.
1973
- throw new CLIError(`Batch run finished: ${batchRunResults.filter(r => r.status !== 'passed').length} of ${batchRunResults.length} run(s) did not pass.`, 1);
2492
+ throw new CLIError(opts.wait
2493
+ ? `Batch run finished: ${failing.length} of ${batchRunResults.length} run(s) did not pass.`
2494
+ : `Batch run trigger finished: ${failing.length} of ${batchRunResults.length} trigger(s) failed.`, 1);
1974
2495
  }
1975
2496
  /**
1976
2497
  * Read + parse a JSONL plans file. Per-line validation; spec-level
@@ -2518,13 +3039,33 @@ function mapRunStepToCliTestStep(step, run) {
2518
3039
  stepType: step.type,
2519
3040
  };
2520
3041
  }
3042
+ /**
3043
+ * The `test diff` exit-code contract, applied identically to a real
3044
+ * two-run comparison and the `--dry-run` canned sample: the
3045
+ * result is always printed first (`out.print` already ran by the time this
3046
+ * is called), then a `verdictChanged` diff throws so the process exits 1.
3047
+ * Before this helper existed, `--dry-run`'s early `return sample` bypassed
3048
+ * the check entirely — the canned sample has `verdictChanged: true`, so
3049
+ * `test diff --dry-run` always exited 0 even though the documented contract
3050
+ * ("Exit 0 when verdicts match, 1 when they differ") makes no dry-run
3051
+ * exception. That made the command useless for its stated CI-gate
3052
+ * pre-verification purpose.
3053
+ */
3054
+ function enforceDiffExitContract(diff) {
3055
+ if (diff.verdictChanged) {
3056
+ throw new CLIError(`verdicts differ: ${diff.runA.runId}=${diff.runA.status} vs ${diff.runB.runId}=${diff.runB.status}`, 1);
3057
+ }
3058
+ }
2521
3059
  /**
2522
3060
  * `test diff <runA> <runB>` (issue #124): isolate what regressed between two
2523
3061
  * runs, the first question when CI goes red ("what changed since the last
2524
3062
  * green run?"). Pure client-side composition of the existing per-run read
2525
3063
  * (`GET /runs/{id}?includeSteps=true`); the endpoint accepts any two run-ids,
2526
3064
  * so a cross-test pair is a WARNING, not an error. Exit 0 when the verdicts
2527
- * match, exit 1 when they differ, so the command is CI-scriptable.
3065
+ * match, exit 1 when they differ, so the command is CI-scriptable —
3066
+ * `--dry-run` honors the same contract: the canned sample has a
3067
+ * changed verdict, so `test diff --dry-run` (with no overrides) exits 1,
3068
+ * same as a real regressed pair would.
2528
3069
  */
2529
3070
  export async function runDiff(opts, deps = {}) {
2530
3071
  const out = makeOutput(opts.output, deps);
@@ -2556,6 +3097,7 @@ export async function runDiff(opts, deps = {}) {
2556
3097
  changedSteps: [{ stepIndex: 2, statusA: 'passed', statusB: 'failed' }],
2557
3098
  };
2558
3099
  out.print(sample, () => renderRunDiffText(sample));
3100
+ enforceDiffExitContract(sample);
2559
3101
  return sample;
2560
3102
  }
2561
3103
  const client = makeClient(opts, deps);
@@ -2614,10 +3156,8 @@ export async function runDiff(opts, deps = {}) {
2614
3156
  changedSteps,
2615
3157
  };
2616
3158
  out.print(diff, () => renderRunDiffText(diff));
2617
- if (diff.verdictChanged) {
2618
- // Result already printed; the typed exit makes `test diff` a CI gate.
2619
- throw new CLIError(`verdicts differ: ${runA.runId}=${runA.status} vs ${runB.runId}=${runB.status}`, 1);
2620
- }
3159
+ // Result already printed; the typed exit makes `test diff` a CI gate.
3160
+ enforceDiffExitContract(diff);
2621
3161
  return diff;
2622
3162
  }
2623
3163
  function renderRunDiffText(diff) {
@@ -2645,6 +3185,25 @@ function renderRunDiffText(diff) {
2645
3185
  }
2646
3186
  return lines.join('\n');
2647
3187
  }
3188
+ /**
3189
+ * Turn a thrown validation error into a lint issue's `field`+`reason` pair.
3190
+ * Shared by `runLint`'s file-level failures (bad path, oversize, invalid JSON
3191
+ * syntax — always a single issue, there's nothing left to validate) and the
3192
+ * collect-all `collectPlanIssues` / `collectPlanStepsIssues` helpers above
3193
+ * (one call per field, so every problem in a file is captured, not just the
3194
+ * first). Preserves the typed envelope's `details.field` / `details.reason`
3195
+ * verbatim (e.g. `planSteps[2].type`) so a caller sees the exact same pointer
3196
+ * whether the error surfaced via lint or via `create`.
3197
+ */
3198
+ function toLintIssue(err) {
3199
+ if (err instanceof ApiError) {
3200
+ return {
3201
+ field: String(err.getDetail('field') ?? '(file)'),
3202
+ reason: String(err.getDetail('reason') ?? err.nextAction ?? err.message),
3203
+ };
3204
+ }
3205
+ return { field: '(file)', reason: err instanceof Error ? err.message : String(err) };
3206
+ }
2648
3207
  /**
2649
3208
  * `test lint` (issue #98): validate plan/steps files fully OFFLINE with the
2650
3209
  * SAME validators the create paths run, but collecting EVERY problem instead
@@ -2653,6 +3212,15 @@ function renderRunDiffText(diff) {
2653
3212
  * so authoring a 12-plan directory meant one error per paid round-trip. Zero
2654
3213
  * network, zero credentials: exit 0 when everything is valid, 5 otherwise, so
2655
3214
  * it drops into a pre-commit hook or CI step before `create-batch`.
3215
+ *
3216
+ * The collection granularity used to be per-FILE, not per-PROBLEM — a single
3217
+ * plan with 6 independent field errors reported one at a time across 6
3218
+ * fix-and-rerun cycles, because each file was validated through the
3219
+ * throw-on-first `assertPlanShape`/`assertPlanStepsShape`. Every branch below
3220
+ * now separates "parse the file" (still a single fatal issue on I/O/JSON
3221
+ * failure — there's nothing left to validate) from "check the parsed shape"
3222
+ * (routed through `collectPlanIssues` / `collectPlanStepsIssues`, which
3223
+ * report every failing field in one pass).
2656
3224
  */
2657
3225
  export async function runLint(opts, deps = {}) {
2658
3226
  const out = makeOutput(opts.output, deps);
@@ -2662,38 +3230,39 @@ export async function runLint(opts, deps = {}) {
2662
3230
  }
2663
3231
  const issues = [];
2664
3232
  let checked = 0;
2665
- // Run one existing validator, converting its typed throw into a report row
2666
- // (same envelopes, so `details.field` pointers like planSteps[2].type
2667
- // survive verbatim).
2668
- const collect = (file, validate) => {
3233
+ const lintPlanFile = (file, path, specIndex) => {
2669
3234
  checked += 1;
3235
+ let parsed;
2670
3236
  try {
2671
- validate();
3237
+ parsed = parsePlanFile(path);
2672
3238
  }
2673
3239
  catch (err) {
2674
- if (err instanceof ApiError) {
2675
- issues.push({
2676
- file,
2677
- field: String(err.getDetail('field') ?? '(file)'),
2678
- reason: String(err.getDetail('reason') ?? err.nextAction ?? err.message),
2679
- });
2680
- }
2681
- else {
2682
- issues.push({
2683
- file,
2684
- field: '(file)',
2685
- reason: err instanceof Error ? err.message : String(err),
2686
- });
2687
- }
3240
+ issues.push({ file, ...toLintIssue(err) });
3241
+ return;
3242
+ }
3243
+ for (const issue of collectPlanIssues(parsed, { specIndex })) {
3244
+ issues.push({ file, ...issue });
3245
+ }
3246
+ };
3247
+ const lintStepsFile = (file, path) => {
3248
+ checked += 1;
3249
+ let parsed;
3250
+ try {
3251
+ parsed = parsePlanStepsFile(path);
3252
+ }
3253
+ catch (err) {
3254
+ issues.push({ file, ...toLintIssue(err) });
3255
+ return;
3256
+ }
3257
+ for (const issue of collectPlanStepsIssues(parsed)) {
3258
+ issues.push({ file, ...issue });
2688
3259
  }
2689
3260
  };
2690
3261
  if (opts.planFrom !== undefined) {
2691
- const planFrom = opts.planFrom;
2692
- collect(planFrom, () => void readPlanFromGuarded(planFrom));
3262
+ lintPlanFile(opts.planFrom, opts.planFrom);
2693
3263
  }
2694
3264
  else if (opts.steps !== undefined) {
2695
- const steps = opts.steps;
2696
- collect(steps, () => void readPlanStepsFileGuarded(steps));
3265
+ lintStepsFile(opts.steps, opts.steps);
2697
3266
  }
2698
3267
  else if (opts.planFromDir !== undefined) {
2699
3268
  const dir = resolveAbsolute(opts.planFromDir);
@@ -2710,12 +3279,13 @@ export async function runLint(opts, deps = {}) {
2710
3279
  throw localValidationError('plan-from-dir', 'contains no *.json plan files');
2711
3280
  }
2712
3281
  for (const entry of entries) {
2713
- collect(entry, () => void readPlanFromGuarded(join(dir, entry)));
3282
+ lintPlanFile(entry, join(dir, entry));
2714
3283
  }
2715
3284
  }
2716
3285
  else if (opts.plans !== undefined) {
2717
- // JSONL: validate PER LINE so every bad line reports (the create path's
2718
- // reader stays throw-on-first; this is the collecting counterpart).
3286
+ // JSONL: validate PER LINE, and every problem WITHIN each line (the
3287
+ // create path's reader stays throw-on-first; this is the collecting
3288
+ // counterpart, both per-line and per-field).
2719
3289
  const absolute = resolveAbsolute(opts.plans);
2720
3290
  let content;
2721
3291
  try {
@@ -2734,16 +3304,20 @@ export async function runLint(opts, deps = {}) {
2734
3304
  if (numberedLines.length === 0)
2735
3305
  throw localValidationError('plans', 'contains no plan lines');
2736
3306
  for (const { line, lineNo } of numberedLines) {
2737
- collect(`${opts.plans}:${lineNo}`, () => {
2738
- let parsed;
2739
- try {
2740
- parsed = JSON.parse(line);
2741
- }
2742
- catch {
2743
- throw localValidationError('plans', `line ${lineNo} is not valid JSON`, undefined, 'field');
2744
- }
2745
- assertPlanShape(parsed, { specIndex: lineNo - 1 });
2746
- });
3307
+ const file = `${opts.plans}:${lineNo}`;
3308
+ checked += 1;
3309
+ let parsed;
3310
+ try {
3311
+ parsed = JSON.parse(line);
3312
+ }
3313
+ catch {
3314
+ const err = localValidationError('plans', `line ${lineNo} is not valid JSON`, undefined, 'field');
3315
+ issues.push({ file, ...toLintIssue(err) });
3316
+ continue;
3317
+ }
3318
+ for (const issue of collectPlanIssues(parsed, { specIndex: lineNo - 1 })) {
3319
+ issues.push({ file, ...issue });
3320
+ }
2747
3321
  }
2748
3322
  }
2749
3323
  const filesWithIssues = new Set(issues.map(issue => issue.file)).size;
@@ -2838,6 +3412,70 @@ export async function runScaffold(opts, deps = {}) {
2838
3412
  out.print(payload, () => body.trimEnd());
2839
3413
  return payload;
2840
3414
  }
3415
+ /**
3416
+ * `test create --plan-template` — prints the canonical minimal
3417
+ * valid plan file (`PLAN_TEMPLATE_WITH_SCHEMA` / `PLAN_TEMPLATE_TEXT`,
3418
+ * defined above near `CliPlanInput`) to stdout and exits — before any of
3419
+ * `test create`'s other flag handling runs. Pure-local: no network, no
3420
+ * credentials, no filesystem I/O.
3421
+ *
3422
+ * Deliberately simpler than `test scaffold --type frontend` (which
3423
+ * substitutes a live `TESTSPRITE_PROJECT_ID` when set, and supports
3424
+ * `--out`): `--plan-template`'s job is a single deterministic ground-truth
3425
+ * document that is BYTE-IDENTICAL every invocation, because it doubles as
3426
+ * the literal example embedded in `test create --help` and the
3427
+ * fixture asserted against `schemas/plan.schema.json` in tests.
3428
+ */
3429
+ export function runPlanTemplate(opts, deps = {}) {
3430
+ const out = makeOutput(opts.output, deps);
3431
+ out.print(PLAN_TEMPLATE_WITH_SCHEMA, () => PLAN_TEMPLATE_TEXT);
3432
+ return PLAN_TEMPLATE_WITH_SCHEMA;
3433
+ }
3434
+ /**
3435
+ * `test open <test-id>` (issue #121): jump from the terminal to the test's
3436
+ * dashboard page. The CLI already computes this deep-link and prints it as
3437
+ * text on other commands; this closes the last inch (the `gh browse` /
3438
+ * `cypress open` hop). The URL is ALWAYS printed to stdout (so `--no-browser`
3439
+ * and headless use still compose), then the OS browser is spawned unless
3440
+ * --no-browser. An endpoint with no known portal mapping is a hard error
3441
+ * rather than a silent no-op.
3442
+ */
3443
+ export async function runOpen(opts, deps = {}, opener = openInBrowser) {
3444
+ const out = makeOutput(opts.output, deps);
3445
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
3446
+ if (opts.dryRun) {
3447
+ emitDryRunBanner(stderrFn);
3448
+ // Derive the sample through the SAME resolver as the live path (against
3449
+ // the canonical prod endpoint and the dry-run project id) so the two can
3450
+ // never drift; the ?? arm is unreachable for the prod mapping but keeps
3451
+ // the type total.
3452
+ const sample = {
3453
+ dashboardUrl: resolvePortalUrl('https://api.testsprite.com', 'p_dryrun_2026', opts.testId) ??
3454
+ `https://www.testsprite.com/dashboard/tests/p_dryrun_2026/test/${encodeURIComponent(opts.testId)}`,
3455
+ };
3456
+ out.print(sample, data => data.dashboardUrl);
3457
+ return sample;
3458
+ }
3459
+ const client = makeClient(opts, deps);
3460
+ // The deep-link needs the projectId; the test record is the source of truth.
3461
+ const test = await client.get(`/tests/${encodeURIComponent(opts.testId)}`);
3462
+ const dashboardUrl = resolvePortalUrl(resolveApiUrl(opts, deps), test.projectId, opts.testId);
3463
+ if (dashboardUrl === undefined) {
3464
+ throw new CLIError(`no dashboard mapping for this API endpoint; set TESTSPRITE_PORTAL_URL to your Portal origin`, 1);
3465
+ }
3466
+ out.print({ dashboardUrl }, () => dashboardUrl);
3467
+ if (!opts.noBrowser) {
3468
+ try {
3469
+ opener(dashboardUrl);
3470
+ }
3471
+ catch {
3472
+ // The URL is already on stdout; a missing opener (containers, minimal
3473
+ // hosts) downgrades to "open it yourself" instead of a hard failure.
3474
+ stderrFn('could not launch a browser; open the URL above manually (or use --no-browser)');
3475
+ }
3476
+ }
3477
+ return { dashboardUrl };
3478
+ }
2841
3479
  export async function runSteps(opts, deps = {}) {
2842
3480
  const out = makeOutput(opts.output, deps);
2843
3481
  const client = makeClient(opts, deps);
@@ -2991,6 +3629,9 @@ export async function runResultHistory(opts, deps = {}) {
2991
3629
  throw localValidationError('page-size', 'must be between 1 and 100');
2992
3630
  }
2993
3631
  }
3632
+ if (opts.output === 'text') {
3633
+ resolveTextColumns(opts.columns, RUN_HISTORY_TABLE_COLUMNS);
3634
+ }
2994
3635
  const client = makeClient(opts, deps);
2995
3636
  const pageSize = opts.pageSize ?? 20;
2996
3637
  const sinceIso = opts.since !== undefined ? parseDuration(opts.since) : undefined;
@@ -3000,9 +3641,14 @@ export async function runResultHistory(opts, deps = {}) {
3000
3641
  source: opts.source,
3001
3642
  since: sinceIso,
3002
3643
  });
3003
- if (opts.output === 'json') {
3004
- out.print({ runs: resp.runs, nextCursor: resp.nextCursor }, data => JSON.stringify(data));
3005
- return resp;
3644
+ // Client-side rerun filter (--rerun / --no-rerun). isRerun is on every row;
3645
+ // the backend has no rerun filter. Undefined → no filter. Like --source, a
3646
+ // filtered page can be short/empty while more history exists — the empty-page
3647
+ // and short-page hints below cover that.
3648
+ const runs = opts.rerun === undefined ? resp.runs : resp.runs.filter(r => r.isRerun === opts.rerun);
3649
+ if (opts.output !== 'text') {
3650
+ out.print({ runs, nextCursor: resp.nextCursor }, data => JSON.stringify(data));
3651
+ return { ...resp, runs };
3006
3652
  }
3007
3653
  // Text mode rendering
3008
3654
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
@@ -3011,7 +3657,7 @@ export async function runResultHistory(opts, deps = {}) {
3011
3657
  // backend filters AFTER limiting rows (limit-before-filter). Matching runs
3012
3658
  // may exist on later pages — surface the cursor instead of reporting
3013
3659
  // "no history".
3014
- if (resp.runs.length === 0) {
3660
+ if (runs.length === 0) {
3015
3661
  if (resp.nextCursor !== null) {
3016
3662
  // Filtered-empty page, but more pages exist: prompt user to paginate.
3017
3663
  const msg = `No matching runs on this page (filters skipped all entries), but more history exists.\n` +
@@ -3032,7 +3678,7 @@ export async function runResultHistory(opts, deps = {}) {
3032
3678
  return resp;
3033
3679
  }
3034
3680
  const lines = [];
3035
- lines.push(renderRunHistoryTable(resp.runs));
3681
+ lines.push(renderRunHistoryTable(runs, { columns: opts.columns, noHeader: opts.noHeader }));
3036
3682
  // Footer: pointer to per-run detail commands.
3037
3683
  lines.push('');
3038
3684
  lines.push('Per-run detail: testsprite test wait <run-id>');
@@ -3045,19 +3691,24 @@ export async function runResultHistory(opts, deps = {}) {
3045
3691
  out.print(lines.join('\n'), d => d);
3046
3692
  // Short-filtered-page hint: non-null nextCursor even though this page was
3047
3693
  // shorter than requested — "none in THIS window" does not mean end-of-history.
3048
- if (resp.nextCursor !== null && resp.runs.length < pageSize) {
3694
+ if (resp.nextCursor !== null && runs.length < pageSize) {
3049
3695
  stderr(`[hint] Fewer than ${pageSize} rows returned but more may exist — ` +
3050
- `source filter skipped some entries. Pass --cursor ${resp.nextCursor} to continue.`);
3696
+ `a source/rerun filter skipped some entries. Pass --cursor ${resp.nextCursor} to continue.`);
3051
3697
  }
3052
- return resp;
3698
+ return { ...resp, runs };
3053
3699
  }
3054
- const RUN_HISTORY_TABLE_COL_WIDTHS = {
3055
- runId: 36,
3056
- status: 10,
3057
- source: 18,
3058
- rerun: 6,
3059
- when: 25,
3060
- };
3700
+ const RUN_HISTORY_TABLE_COLUMNS = [
3701
+ { header: 'RUN ID', width: 36, render: run => run.runId },
3702
+ { header: 'STATUS', width: 10, render: run => run.status },
3703
+ { header: 'SOURCE', width: 18, render: run => run.source },
3704
+ { header: 'RERUN?', width: 6, render: run => (run.isRerun ? 'yes' : 'no') },
3705
+ { header: 'WHEN', width: 25, render: run => run.createdAt },
3706
+ {
3707
+ header: 'DURATION',
3708
+ width: 0,
3709
+ render: run => formatDurationMs(run.startedAt ?? run.createdAt, run.finishedAt),
3710
+ },
3711
+ ];
3061
3712
  /**
3062
3713
  * Max width of the `test steps` DESCRIPTION column in text mode. Long /
3063
3714
  * multi-line step descriptions are collapsed to one line and truncated to
@@ -3089,56 +3740,29 @@ const HISTORY_TARGET_URL_MAX = 80;
3089
3740
  * run row (truncated to `HISTORY_TARGET_URL_MAX` chars). The table columns
3090
3741
  * are left intact to avoid width blow-out on terminals.
3091
3742
  */
3092
- function renderRunHistoryTable(runs) {
3093
- const cols = RUN_HISTORY_TABLE_COL_WIDTHS;
3094
- const header = [
3095
- padEnd('RUN ID', cols.runId),
3096
- padEnd('STATUS', cols.status),
3097
- padEnd('SOURCE', cols.source),
3098
- padEnd('RERUN?', cols.rerun),
3099
- padEnd('WHEN', cols.when),
3100
- 'DURATION',
3101
- ].join(' ');
3102
- const sep = '-'.repeat(header.length);
3103
- const rows = runs.flatMap(r => {
3104
- // FE runs never populate `startedAt` today — the RUNNING heartbeat
3105
- // that would set it doesn't fire on the legacy/sync execution path
3106
- // (dogfood 2026-06-04), so without a fallback DURATION was always
3107
- // "—" for every FE run. Fall back to `createdAt` so the column shows
3108
- // wall-clock from trigger to finish; on sync dev the queue gap is
3109
- // ~0, and `--output json` still exposes raw startedAt/finishedAt for
3110
- // consumers that need to exclude queue time.
3111
- const duration = formatDurationMs(r.startedAt ?? r.createdAt, r.finishedAt);
3112
- const mainRow = [
3113
- padEnd(r.runId, cols.runId),
3114
- padEnd(r.status, cols.status),
3115
- padEnd(r.source, cols.source),
3116
- padEnd(r.isRerun ? 'yes' : 'no', cols.rerun),
3117
- padEnd(r.createdAt, cols.when),
3118
- duration,
3119
- ].join(' ');
3120
- // G1b: surface per-run targetUrl as an indented sub-line.
3121
- // Render only when truthy (skip null, undefined, empty) and when the
3122
- // source is not 'unresolved' (that would mean "backend couldn't resolve
3123
- // a URL" — printing "—" is less informative than omitting the line).
3743
+ function renderRunHistoryTable(runs, options = {}) {
3744
+ const selectedColumns = resolveTextColumns(options.columns, RUN_HISTORY_TABLE_COLUMNS);
3745
+ const widths = measureTextColumns(runs, selectedColumns);
3746
+ const customColumns = options.columns !== undefined && options.columns.trim() !== '';
3747
+ const includeDetailLines = !customColumns;
3748
+ const header = formatTextTableRow(selectedColumns.map(column => column.header), widths);
3749
+ const rows = runs.flatMap(run => {
3750
+ const mainRow = formatTextTableRow(selectedColumns.map(column => column.render(run)), widths);
3124
3751
  const lines = [mainRow];
3125
- if (r.targetUrl && r.targetUrlSource !== 'unresolved') {
3126
- const url = r.targetUrl.length > HISTORY_TARGET_URL_MAX
3127
- ? `${r.targetUrl.slice(0, HISTORY_TARGET_URL_MAX - 1)}…`
3128
- : r.targetUrl;
3752
+ if (includeDetailLines && run.targetUrl && run.targetUrlSource !== 'unresolved') {
3753
+ const url = run.targetUrl.length > HISTORY_TARGET_URL_MAX
3754
+ ? `${run.targetUrl.slice(0, HISTORY_TARGET_URL_MAX - 1)}…`
3755
+ : run.targetUrl;
3129
3756
  lines.push(` targetUrl: ${url}`);
3130
3757
  }
3131
- else if (r.targetUrlSource === 'unresolved') {
3758
+ else if (includeDetailLines && run.targetUrlSource === 'unresolved') {
3132
3759
  lines.push(` targetUrl: —`);
3133
3760
  }
3134
3761
  return lines;
3135
3762
  });
3136
- return [header, sep, ...rows].join('\n');
3137
- }
3138
- function padEnd(s, width) {
3139
- if (s.length >= width)
3140
- return s;
3141
- return s + ' '.repeat(width - s.length);
3763
+ if (options.noHeader === true)
3764
+ return rows.join('\n');
3765
+ return [header, '-'.repeat(header.length), ...rows].join('\n');
3142
3766
  }
3143
3767
  function formatDurationMs(startedAt, finishedAt) {
3144
3768
  if (!startedAt || !finishedAt)
@@ -3323,8 +3947,11 @@ function backendResultToRunResponse(result, run) {
3323
3947
  retryAfterSeconds: undefined,
3324
3948
  startedAt: result.startedAt ?? run.startedAt,
3325
3949
  finishedAt: result.finishedAt ?? run.finishedAt,
3326
- codeVersion: run.codeVersion || (result.codeVersion ?? ''),
3327
- targetUrl: run.targetUrl || (result.targetUrl ?? ''),
3950
+ // Neither side having a value stays null (not ''), so the text renderer
3951
+ // omits the line instead of printing a label with nothing after it. A
3952
+ // backend run legitimately has no target URL at all.
3953
+ codeVersion: run.codeVersion || result.codeVersion || null,
3954
+ targetUrl: run.targetUrl || result.targetUrl || null,
3328
3955
  // createdFrom / projectId / userId / runId / testId / source / createdAt
3329
3956
  // inherited from the polled run row via the spread above.
3330
3957
  failedStepIndex: result.failedStepIndex,
@@ -3442,13 +4069,34 @@ function printRunOrChain(out, payload, createContext, textRenderer) {
3442
4069
  });
3443
4070
  }
3444
4071
  /**
3445
- * Enrich a terminal RunResponse with a client-synthesized Portal deep link.
3446
- * Emitted only when the wire row carries both projectId and testId (the BE
3447
- * testId-fallback path synthesizes rows with an empty projectId — those stay
3448
- * unenriched) and the API endpoint maps to a known portal host
3449
- * (`resolvePortalUrl` returns undefined otherwise).
4072
+ * Attach the Portal deep link to a terminal RunResponse.
4073
+ *
4074
+ * **A server-provided `dashboardUrl` always wins.** The backend knows two
4075
+ * things this process cannot:
4076
+ *
4077
+ * - **Which store answered.** For a run served from V3 Postgres the
4078
+ * `/dashboard/tests/…` route we would template reads DynamoDB only, and a
4079
+ * CLI-created project under the V3-native write path has no DynamoDB row at
4080
+ * all — so our link is not merely org-less, it cannot render. The server
4081
+ * sends the V3 test-case page instead, scoped to the workspace that owns the
4082
+ * run.
4083
+ * - **The portal origin for this environment.** `resolvePortalUrl` maps only
4084
+ * the prod host, so against any other endpoint it returns undefined and we
4085
+ * print nothing. The server reads its own `PORTAL_URL`.
4086
+ *
4087
+ * The client computation stays as the fallback so an older backend (no field)
4088
+ * behaves exactly as before, and so does a V2-served run whose server link the
4089
+ * backend chose not to emit.
3450
4090
  */
3451
4091
  function withRunDashboardUrl(run, apiUrl) {
4092
+ // A server value of `null` is meaningful, not missing: it says "there is no
4093
+ // correct link for this run" (e.g. a workspace-scoped page the environment's
4094
+ // portal build does not serve yet). Falling back to our own guess there would
4095
+ // reintroduce exactly the wrong link the server declined to send — so only an
4096
+ // ABSENT field (older backend) reopens the client path.
4097
+ if ('dashboardUrl' in run) {
4098
+ return run.dashboardUrl ? run : { ...run, dashboardUrl: undefined };
4099
+ }
3452
4100
  if (!run.projectId || !run.testId)
3453
4101
  return run;
3454
4102
  const dashboardUrl = resolvePortalUrl(apiUrl, run.projectId, run.testId);
@@ -3506,6 +4154,33 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
3506
4154
  lines.push(`dashboard ${run.dashboardUrl}`);
3507
4155
  return lines.join('\n');
3508
4156
  }
4157
+ /**
4158
+ * Best-effort resolve whether a finished run's test is a backend test, for the
4159
+ * text run-card's step line + failure hint only (DEV-282). Returns true with no
4160
+ * network call when already known (create-chain `--type`, or the BE wait
4161
+ * fallback fired). Otherwise, in TEXT mode only, issues one `GET /tests/{id}`;
4162
+ * any error → false (render the numeric step summary as before). JSON mode
4163
+ * never probes — its envelope carries `stepSummary` verbatim and has no
4164
+ * "n/a (backend)" concept, so it is already correct.
4165
+ *
4166
+ * This closes the standalone-path gap: `test run <id>` / `test wait <run-id>`
4167
+ * never supply a type hint, and now that BE run rows finalize server-side
4168
+ * (backend-v2.0 #551/#555) the wait fallback rarely fires — so a backend run
4169
+ * card would otherwise show a misleading `steps 0/0 (passed=0, failed=0)`.
4170
+ */
4171
+ async function resolveRunCardIsBackend(client, testId, output, alreadyKnown) {
4172
+ if (alreadyKnown)
4173
+ return true;
4174
+ if (output === 'json' || !testId)
4175
+ return false;
4176
+ try {
4177
+ const test = await client.get(`/tests/${encodeURIComponent(testId)}`);
4178
+ return test.type === 'backend';
4179
+ }
4180
+ catch {
4181
+ return false; // best-effort — fall back to the numeric step summary.
4182
+ }
4183
+ }
3509
4184
  /**
3510
4185
  * Render a `TriggerRunResponse` (no-wait path) to human-readable text.
3511
4186
  */
@@ -3625,7 +4300,7 @@ export async function runTestRun(opts, deps = {}) {
3625
4300
  throw new ApiError({
3626
4301
  code: 'CONFLICT',
3627
4302
  message: `Conflict: another run for this test is in flight against a different ` +
3628
- `target URL (${inFlightRun.targetUrl}). Your --target-url ${opts.targetUrl} ` +
4303
+ `target URL (${inFlightRun.targetUrl ?? 'not reported'}). Your --target-url ${opts.targetUrl} ` +
3629
4304
  `cannot attach to that run. Wait for it to finish ` +
3630
4305
  `(\`testsprite test wait ${currentRunId}\`) or retry your trigger when ` +
3631
4306
  `the test is free.`,
@@ -3641,13 +4316,15 @@ export async function runTestRun(opts, deps = {}) {
3641
4316
  }
3642
4317
  stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}, ` +
3643
4318
  `target: ${inFlightRun.targetUrl}). ` +
3644
- `Attaching to that run's --wait poll instead of creating a new one.`);
4319
+ `Attaching to that run's --wait poll instead of creating a new one. ` +
4320
+ `To stop it instead: testsprite test cancel ${currentRunId}`);
3645
4321
  triggerResponse = {
3646
4322
  runId: currentRunId,
3647
4323
  status: 'queued',
3648
4324
  enqueuedAt: new Date().toISOString(),
3649
- codeVersion: inFlightRun.codeVersion,
3650
- targetUrl: inFlightRun.targetUrl,
4325
+ codeVersion: inFlightRun.codeVersion ?? '',
4326
+ // The check above proved the in-flight run targets exactly this URL.
4327
+ targetUrl: opts.targetUrl,
3651
4328
  };
3652
4329
  }
3653
4330
  else {
@@ -3667,11 +4344,15 @@ export async function runTestRun(opts, deps = {}) {
3667
4344
  }
3668
4345
  // Auto-resume but emit a stronger advisory so the caller is aware
3669
4346
  // they are attaching to the project default.
4347
+ // SIG-9 (DEV-331 final): the in-flight run is NOT auto-cancelled —
4348
+ // name the real `test cancel` command instead of the old (false)
4349
+ // "cancel with Ctrl-C" claim.
3670
4350
  stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
3671
4351
  (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
3672
4352
  `). 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.`);
4353
+ `If you needed a specific target URL, cancel it with ` +
4354
+ `testsprite test cancel ${currentRunId}, or re-trigger with ` +
4355
+ `--target-url after it finishes.`);
3675
4356
  triggerResponse = {
3676
4357
  runId: currentRunId,
3677
4358
  status: 'queued',
@@ -3727,6 +4408,7 @@ export async function runTestRun(opts, deps = {}) {
3727
4408
  finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
3728
4409
  timeoutSeconds: opts.timeoutSeconds,
3729
4410
  sleep: deps.sleep,
4411
+ shutdown: shutdownOf(deps),
3730
4412
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
3731
4413
  onTick: (run, elapsedMs) => {
3732
4414
  const elapsed = Math.round(elapsedMs / 1000);
@@ -3758,13 +4440,14 @@ export async function runTestRun(opts, deps = {}) {
3758
4440
  if (p.targetUrl)
3759
4441
  lines.push(`targetUrl ${p.targetUrl}`);
3760
4442
  lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4443
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
3761
4444
  return lines.join('\n');
3762
4445
  });
3763
4446
  throw ApiError.fromEnvelope({
3764
4447
  error: {
3765
4448
  code: 'UNSUPPORTED', // exit 7 per errors.md
3766
4449
  message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}.`,
3767
- nextAction: `Resume polling: testsprite test wait ${triggerResponse.runId}`,
4450
+ nextAction: `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
3768
4451
  requestId: 'local',
3769
4452
  details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
3770
4453
  },
@@ -3788,14 +4471,72 @@ export async function runTestRun(opts, deps = {}) {
3788
4471
  };
3789
4472
  printRunOrChain(out, partial, opts.createContext, data => {
3790
4473
  const p = data;
3791
- const lines = [`runId ${p.runId}`, `status ${p.status} (request timed out)`];
4474
+ const lines = [`runId ${p.runId}`, `status ${p.status} (request timed out)`];
4475
+ if (p.targetUrl)
4476
+ lines.push(`targetUrl ${p.targetUrl}`);
4477
+ lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4478
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4479
+ return lines.join('\n');
4480
+ });
4481
+ stderrFn(`Run ${triggerResponse.runId} is still in progress (request timed out). ` +
4482
+ `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
4483
+ throw err;
4484
+ }
4485
+ // RATE_LIMITED during polling — the backend's pre-auth rate limiter can
4486
+ // trip on a shared egress IP (CI runner, NAT) and 429 an otherwise-valid
4487
+ // key for its window; the HTTP layer already retried internally and gave
4488
+ // up. The run was already triggered (and billed) and keeps executing
4489
+ // server-side, so this must not be a silent, runId-less death: same
4490
+ // partial-envelope contract as the RequestTimeoutError branch above, and
4491
+ // the SAME thrown ApiError is rethrown unchanged so its native exit code
4492
+ // (11) is preserved — never reclassified to 7.
4493
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
4494
+ ticker.finalize(`Run ${triggerResponse.runId} — rate limited by the server`);
4495
+ const partial = {
4496
+ runId: triggerResponse.runId,
4497
+ status: 'running',
4498
+ enqueuedAt: triggerResponse.enqueuedAt,
4499
+ codeVersion: triggerResponse.codeVersion,
4500
+ targetUrl: triggerResponse.targetUrl || null,
4501
+ };
4502
+ printRunOrChain(out, partial, opts.createContext, data => {
4503
+ const p = data;
4504
+ const lines = [
4505
+ `runId ${p.runId}`,
4506
+ `status ${p.status} (rate limited by the server)`,
4507
+ ];
4508
+ if (p.targetUrl)
4509
+ lines.push(`targetUrl ${p.targetUrl}`);
4510
+ lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4511
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4512
+ return lines.join('\n');
4513
+ });
4514
+ stderrFn(rateLimitedDetachMessage(err, [triggerResponse.runId]));
4515
+ throw err;
4516
+ }
4517
+ // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
4518
+ // envelope shape as the timeout paths so stdout stays parseable, plus the
4519
+ // honest "keeps running and billing" stderr line. Rethrow → index.ts
4520
+ // renders the INTERRUPTED envelope and exits 128+signum.
4521
+ if (err instanceof InterruptError) {
4522
+ ticker.finalize(`Run ${triggerResponse.runId} — interrupted (${err.signal})`);
4523
+ const partial = {
4524
+ runId: triggerResponse.runId,
4525
+ status: 'running',
4526
+ enqueuedAt: triggerResponse.enqueuedAt,
4527
+ codeVersion: triggerResponse.codeVersion,
4528
+ targetUrl: triggerResponse.targetUrl || null,
4529
+ };
4530
+ printRunOrChain(out, partial, opts.createContext, data => {
4531
+ const p = data;
4532
+ const lines = [`runId ${p.runId}`, `status ${p.status} (interrupted)`];
3792
4533
  if (p.targetUrl)
3793
4534
  lines.push(`targetUrl ${p.targetUrl}`);
3794
4535
  lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4536
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
3795
4537
  return lines.join('\n');
3796
4538
  });
3797
- stderrFn(`Run ${triggerResponse.runId} is still in progress (request timed out). ` +
3798
- `Re-attach with: testsprite test wait ${triggerResponse.runId}`);
4539
+ stderrFn(interruptDetachMessage(err, [triggerResponse.runId]));
3799
4540
  throw err;
3800
4541
  }
3801
4542
  ticker.finalize();
@@ -3804,20 +4545,20 @@ export async function runTestRun(opts, deps = {}) {
3804
4545
  const elapsed = Math.round((Date.now() - startMs) / 1000);
3805
4546
  const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
3806
4547
  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
- }));
4548
+ // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs); on
4549
+ // the standalone `test run <id>` path neither is set, so probe the test type
4550
+ // once (text mode only, best-effort) — DEV-282.
4551
+ const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
4552
+ printRunOrChain(out, withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), opts.createContext, data => renderRunResponseText(data, { isBackend }));
3812
4553
  // Surface the trigger requestId under --verbose/--debug or JSON mode so
3813
4554
  // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
3814
4555
  // JSON mode always emits to stderr — it never pollutes stdout).
3815
4556
  if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
3816
4557
  stderrFn(`requestId: ${triggerRequestId}`);
3817
4558
  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
4559
+ // BE runs have no run-scoped artifact bundle — their failure bundle is
4560
+ // addressed by testId, not runId.
4561
+ stderrFn(isBackend
3821
4562
  ? `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
4563
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
3823
4564
  }
@@ -3859,44 +4600,100 @@ export async function runTestWaitMany(opts, deps = {}) {
3859
4600
  }
3860
4601
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
3861
4602
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
4603
+ const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
3862
4604
  // One shared deadline across every member (the whole point of the shared
3863
4605
  // pool: `--timeout 600` means the invocation ends within ~600s, not
3864
4606
  // 600s x ceil(N/concurrency)).
3865
4607
  const deadlineMs = Date.now() + opts.timeoutSeconds * 1000;
3866
4608
  const pollOne = async (runId) => {
3867
- // A member dequeued AFTER the shared deadline has passed must not be
3868
- // granted a fresh minimum poll window (with --max-concurrency 1 that
3869
- // would extend the invocation by ~1s per queued run past --timeout).
3870
- const remainingSeconds = Math.ceil((deadlineMs - Date.now()) / 1000);
3871
- if (remainingSeconds <= 0)
3872
- return { kind: 'timeout' };
3873
4609
  const resolveAlternate = makeBackendWaitFallback({
3874
4610
  client,
3875
4611
  resolveTestId: run => run.testId,
3876
4612
  resolveNotBefore: run => run.createdAt,
3877
4613
  onResolved: () => undefined,
3878
4614
  });
3879
- try {
3880
- const run = await pollRunUntilTerminal(client, runId, {
3881
- timeoutSeconds: remainingSeconds,
3882
- sleep: deps.sleep,
3883
- onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
3884
- onTick: (run, elapsedMs) => {
3885
- const elapsed = Math.round(elapsedMs / 1000);
3886
- ticker.update(`Run ${run.runId} — ${run.status} (elapsed=${elapsed}s)`);
3887
- },
3888
- resolveAlternate,
3889
- });
3890
- return { kind: 'result', run };
3891
- }
3892
- catch (err) {
3893
- if (err instanceof TimeoutError)
4615
+ // Outer RATE_LIMITED retry, per member. `http.ts` already retries a 429
4616
+ // internally (`MAX_ATTEMPTS_RATE_LIMITED`), so reaching this catch means the
4617
+ // transport gave up — but a shared-egress 429 (CI runner / NAT tripping the
4618
+ // backend's ip-keyed pre-auth limiter) is a property of the *window*, not of
4619
+ // this run, and the run is still executing. Without this loop a single 429
4620
+ // ended the whole member's wait, which is what made a healthy run report as
4621
+ // a poll error. Mirrors the `test run --all` trigger fan-out's outer loop
4622
+ // (`BATCH_RUN_RATE_MAX_OUTER_RETRIES`), including its two invariants: the
4623
+ // sleep is clamped to the SHARED deadline (so a retry can never stretch
4624
+ // `--timeout`), and the retry is per member — one throttled run does not
4625
+ // stall the pool, because each lane runs this loop inside its own task.
4626
+ let rateLimitAttempt = 0;
4627
+ for (;;) {
4628
+ // A member dequeued AFTER the shared deadline has passed must not be
4629
+ // granted a fresh minimum poll window (with --max-concurrency 1 that
4630
+ // would extend the invocation by ~1s per queued run past --timeout).
4631
+ // Re-evaluated on every iteration so a retry obeys the same rule.
4632
+ const remainingSeconds = Math.ceil((deadlineMs - Date.now()) / 1000);
4633
+ if (remainingSeconds <= 0)
3894
4634
  return { kind: 'timeout' };
3895
- if (err instanceof RequestTimeoutError)
3896
- throw err;
3897
- if (err instanceof ApiError)
3898
- return { kind: 'error', code: err.code, exitCode: err.exitCode };
3899
- return { kind: 'error', code: 'TRANSPORT', exitCode: 10 };
4635
+ try {
4636
+ const run = await pollRunUntilTerminal(client, runId, {
4637
+ timeoutSeconds: remainingSeconds,
4638
+ sleep: deps.sleep,
4639
+ shutdown: shutdownOf(deps),
4640
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4641
+ onTick: (run, elapsedMs) => {
4642
+ const elapsed = Math.round(elapsedMs / 1000);
4643
+ ticker.update(`Run ${run.runId} — ${run.status} (elapsed=${elapsed}s)`);
4644
+ },
4645
+ resolveAlternate,
4646
+ });
4647
+ return { kind: 'result', run };
4648
+ }
4649
+ catch (err) {
4650
+ if (err instanceof TimeoutError)
4651
+ return { kind: 'timeout' };
4652
+ if (err instanceof RequestTimeoutError)
4653
+ throw err;
4654
+ // Interrupt must reject the fan-out (handled at the collect point), not
4655
+ // be flattened into a per-member 'error' outcome that would swallow the
4656
+ // 128+signum exit (DEV-331).
4657
+ if (err instanceof InterruptError)
4658
+ throw err;
4659
+ if (err instanceof ApiError) {
4660
+ // `isTransientRateLimit` is the second gate, for an "unknown" 429 that
4661
+ // carries neither a Retry-After nor the per-minute wording: treat it as
4662
+ // permanent rather than burn the budget on it. (The credit-depletion
4663
+ // 429 never reaches here at all — `errors.ts` re-maps that envelope to
4664
+ // INSUFFICIENT_CREDITS before this catch sees it.)
4665
+ if (err.code === 'RATE_LIMITED' &&
4666
+ isTransientRateLimit(err) &&
4667
+ rateLimitAttempt < WAIT_POLL_RATE_MAX_OUTER_RETRIES) {
4668
+ rateLimitAttempt++;
4669
+ const retryAfterMs = resolveRateLimitRetryMs(err);
4670
+ const clampedRetryMs = Math.min(retryAfterMs, deadlineMs - Date.now());
4671
+ // Deadline already reached: the wait budget genuinely ran out, so the
4672
+ // honest outcome is `timeout` — the same call the trigger fan-out
4673
+ // makes ("Timed out … during rate-limit backoff"). Reporting the 429
4674
+ // instead would let the exit-11 escalation below claim "nothing else
4675
+ // went wrong" for an invocation that in fact exhausted `--timeout`.
4676
+ if (clampedRetryMs <= 0)
4677
+ return { kind: 'timeout' };
4678
+ stderrFn(`[wait] ${runId} — rate limited (attempt ${rateLimitAttempt}/${WAIT_POLL_RATE_MAX_OUTER_RETRIES}): retrying in ${Math.ceil(clampedRetryMs / 1000)}s`);
4679
+ // Arm the graceful-detach scope across the backoff. `pollRunUntilTerminal`
4680
+ // disarms in its own `finally`, so without this the sleep is a window
4681
+ // where a first Ctrl-C hard-exits instead of taking the DEV-331 detach
4682
+ // path (partial `{runId, status:'running'}` on stdout + honest hint).
4683
+ const shutdown = shutdownOf(deps);
4684
+ const disarm = shutdown.arm();
4685
+ try {
4686
+ await sleepUntilOrInterrupt(clampedRetryMs, shutdown.signal, sleepFn);
4687
+ }
4688
+ finally {
4689
+ disarm();
4690
+ }
4691
+ continue;
4692
+ }
4693
+ return { kind: 'error', code: err.code, exitCode: err.exitCode };
4694
+ }
4695
+ return { kind: 'error', code: 'TRANSPORT', exitCode: 10 };
4696
+ }
3900
4697
  }
3901
4698
  };
3902
4699
  const outcomes = new Map();
@@ -3926,12 +4723,14 @@ export async function runTestWaitMany(opts, deps = {}) {
3926
4723
  });
3927
4724
  }
3928
4725
  catch (fanOutErr) {
3929
- if (fanOutErr instanceof RequestTimeoutError) {
4726
+ if (fanOutErr instanceof RequestTimeoutError || fanOutErr instanceof InterruptError) {
3930
4727
  // Same contract as the batch pollers: leave stdout parseable before
3931
- // exiting 7. Members that already settled keep their real status; only
4728
+ // exiting. Members that already settled keep their real status; only
3932
4729
  // the still-unfinished ids are marked running and named in the hint
3933
4730
  // (re-attaching to an already-terminal run would be a wasted command).
3934
- ticker.finalize('Multi-run wait — request timed out');
4731
+ ticker.finalize(fanOutErr instanceof InterruptError
4732
+ ? `Multi-run wait — interrupted (${fanOutErr.signal})`
4733
+ : 'Multi-run wait — request timed out');
3935
4734
  const partial = {
3936
4735
  results: opts.runIds.map((runId) => {
3937
4736
  const outcome = outcomes.get(runId);
@@ -3950,7 +4749,12 @@ export async function runTestWaitMany(opts, deps = {}) {
3950
4749
  .filter(r => r.status === 'running' || r.status === 'timeout')
3951
4750
  .map(r => r.runId);
3952
4751
  if (unfinished.length > 0) {
3953
- stderrFn(`Re-attach with: testsprite test wait ${unfinished.join(' ')}`);
4752
+ if (fanOutErr instanceof InterruptError) {
4753
+ stderrFn(interruptDetachMessage(fanOutErr, unfinished));
4754
+ }
4755
+ else {
4756
+ stderrFn(`Re-attach with: testsprite test wait ${unfinished.join(' ')}, or cancel with: testsprite test cancel ${unfinished.join(' ')}`);
4757
+ }
3954
4758
  }
3955
4759
  }
3956
4760
  throw fanOutErr;
@@ -3984,7 +4788,7 @@ export async function runTestWaitMany(opts, deps = {}) {
3984
4788
  .filter(r => r.status === 'timeout' || r.status.startsWith('error:'))
3985
4789
  .map(r => r.runId);
3986
4790
  if (unfinishedIds.length > 0) {
3987
- stderrFn(`Re-attach with: testsprite test wait ${unfinishedIds.join(' ')}`);
4791
+ stderrFn(`Re-attach with: testsprite test wait ${unfinishedIds.join(' ')}, or cancel with: testsprite test cancel ${unfinishedIds.join(' ')}`);
3988
4792
  }
3989
4793
  // Worst-status exit: auth escalates (a rejected key fails every member the
3990
4794
  // same way), then timeout/poll-error (7, resumable), then plain failure (1).
@@ -3993,6 +4797,32 @@ export async function runTestWaitMany(opts, deps = {}) {
3993
4797
  if (authError !== undefined && authError.kind === 'error') {
3994
4798
  throw new CLIError(`Multi-run wait: authentication failed (${authError.code})`, authError.exitCode);
3995
4799
  }
4800
+ // Rate limiting escalates the same way auth does, for the same reason: when it
4801
+ // is the ONLY thing that went wrong, exit 7 ("timeout or per-member poll
4802
+ // error") is actively misleading — nothing timed out and no run misbehaved, the
4803
+ // client was throttled — and 7 tells an automated caller to re-attach
4804
+ // immediately, which walks straight back into the limiter. Exit 11 says "back
4805
+ // off, then re-attach", which is the correct action. Deliberately narrow: it
4806
+ // requires that EVERY non-passed member is a rate-limited poll error, so a real
4807
+ // timeout or a genuinely failed run is never masked (those keep 7 / 1). By this
4808
+ // point each member has already spent its `WAIT_POLL_RATE_MAX_OUTER_RETRIES`
4809
+ // Retry-After backoffs, so this is a persistently throttled window, not a blip.
4810
+ // `outcomes` is keyed by runId, so a REPEATED id has one shared entry that the
4811
+ // last lane to finish overwrites — a genuine `failed` can be replaced by a
4812
+ // later RATE_LIMITED, which would make the counts below claim "nothing else
4813
+ // went wrong" for an invocation that observed a failure. Rather than change the
4814
+ // long-standing one-row-per-input-id output shape, the escalation simply
4815
+ // declines to fire when the caller passed a duplicate; exit 7 is then the same
4816
+ // answer as before this change.
4817
+ const idsAreUnique = new Set(opts.runIds).size === opts.runIds.length;
4818
+ const rateLimitedOnly = idsAreUnique &&
4819
+ errors > 0 &&
4820
+ timedOut === 0 &&
4821
+ failed === 0 &&
4822
+ [...outcomes.values()].every(o => o.kind !== 'error' || o.code === 'RATE_LIMITED');
4823
+ if (rateLimitedOnly) {
4824
+ throw new CLIError(`Multi-run wait: rate limited on ${errors} of ${results.length} runs — back off and re-attach with: testsprite test wait ${unfinishedIds.join(' ')}`, 11);
4825
+ }
3996
4826
  if (timedOut > 0 || errors > 0) {
3997
4827
  throw new CLIError(`Multi-run wait: ${timedOut} timed out, ${errors} poll error(s) out of ${results.length} runs`, 7);
3998
4828
  }
@@ -4001,6 +4831,140 @@ export async function runTestWaitMany(opts, deps = {}) {
4001
4831
  }
4002
4832
  return payload;
4003
4833
  }
4834
+ /**
4835
+ * `test cancel <run-id...>` — DEV-331 piece 3.
4836
+ *
4837
+ * User-initiated cancel of one or more queued/running runs via
4838
+ * `POST /api/cli/v1/runs/{runId}/cancel`. Naturally idempotent (D10): a
4839
+ * repeat cancel of the same run is a 200 `alreadyCancelled` success, not an
4840
+ * error. Dispatches serially (per-id volume is tiny — no batch endpoint,
4841
+ * D8 "Batch-level cancel endpoint... YAGNI").
4842
+ *
4843
+ * Single id: renders the returned run card (`status cancelled`); an
4844
+ * `alreadyCancelled` response adds an `[advisory]` line. Exit code mirrors
4845
+ * the server response directly — 0 on success (fresh or already-cancelled),
4846
+ * 4 on 404 (unknown/cross-tenant), 6 on 409 (already terminal).
4847
+ *
4848
+ * Multi-id: prints a `{cancelled, alreadyCancelled, conflicts, notFound}`
4849
+ * summary. Exit precedence (CXL-11): any `notFound` → 4 (outranks conflict —
4850
+ * it signals a caller bug, wrong id/tenant); else any `conflicts` → 6; else 0.
4851
+ */
4852
+ export async function runTestCancel(opts, deps = {}) {
4853
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4854
+ const out = makeOutput(opts.output, deps);
4855
+ const client = makeClient(opts, deps);
4856
+ if (opts.dryRun) {
4857
+ emitDryRunBanner(stderrFn);
4858
+ }
4859
+ if (opts.runIds.length === 1) {
4860
+ const runId = opts.runIds[0];
4861
+ const result = await client.cancelRun(runId);
4862
+ out.print(result, data => {
4863
+ const r = data;
4864
+ return renderRunResponseText(r);
4865
+ });
4866
+ if (result.alreadyCancelled) {
4867
+ stderrFn(`[advisory] run ${runId} was already cancelled`);
4868
+ }
4869
+ return result;
4870
+ }
4871
+ const rows = [];
4872
+ for (const runId of opts.runIds) {
4873
+ try {
4874
+ const result = await client.cancelRun(runId);
4875
+ rows.push({
4876
+ runId,
4877
+ status: result.alreadyCancelled ? 'alreadyCancelled' : 'cancelled',
4878
+ });
4879
+ }
4880
+ catch (err) {
4881
+ if (err instanceof ApiError && err.code === 'NOT_FOUND') {
4882
+ rows.push({ runId, status: 'notFound' });
4883
+ continue;
4884
+ }
4885
+ if (err instanceof ApiError && err.code === 'CONFLICT') {
4886
+ const conflictStatus = err.getDetail('status', (v) => typeof v === 'string') ?? 'unknown';
4887
+ rows.push({ runId, status: 'conflict', conflictStatus });
4888
+ continue;
4889
+ }
4890
+ const message = err instanceof Error ? err.message : String(err);
4891
+ rows.push({ runId, status: 'error', error: message });
4892
+ }
4893
+ }
4894
+ const errorRows = rows.filter(r => r.status === 'error');
4895
+ const summary = {
4896
+ cancelled: rows.filter(r => r.status === 'cancelled').map(r => r.runId),
4897
+ alreadyCancelled: rows.filter(r => r.status === 'alreadyCancelled').map(r => r.runId),
4898
+ conflicts: rows
4899
+ .filter(r => r.status === 'conflict')
4900
+ .map(r => ({ runId: r.runId, status: r.conflictStatus ?? 'unknown' })),
4901
+ notFound: rows.filter(r => r.status === 'notFound').map(r => r.runId),
4902
+ errors: errorRows.map(r => ({ runId: r.runId, message: r.error ?? 'unknown error' })),
4903
+ };
4904
+ out.print(summary, data => renderCancelSummaryText(data));
4905
+ const parts = [
4906
+ `${summary.cancelled.length} cancelled`,
4907
+ `${summary.alreadyCancelled.length} already cancelled`,
4908
+ ];
4909
+ if (summary.conflicts.length > 0)
4910
+ parts.push(`${summary.conflicts.length} conflict`);
4911
+ if (summary.notFound.length > 0)
4912
+ parts.push(`${summary.notFound.length} not found`);
4913
+ if (errorRows.length > 0)
4914
+ parts.push(`${errorRows.length} error`);
4915
+ stderrFn(`Cancel summary: ${parts.join(', ')}.`);
4916
+ // Exit precedence (CXL-11): notFound outranks conflict — a caller-side bug
4917
+ // (wrong id / wrong tenant) is more actionable to surface than "it already
4918
+ // finished". A bare transport/auth error on any member also fails loudly
4919
+ // rather than being silently absorbed into a 0 exit.
4920
+ if (summary.notFound.length > 0) {
4921
+ throw new CLIError(`${summary.notFound.length} run id${summary.notFound.length !== 1 ? 's' : ''} not found: ${summary.notFound.join(' ')}`, 4);
4922
+ }
4923
+ if (errorRows.length > 0) {
4924
+ throw new CLIError(`${errorRows.length} cancel request${errorRows.length !== 1 ? 's' : ''} failed: ${errorRows.map(r => r.runId).join(' ')}`, 1);
4925
+ }
4926
+ if (summary.conflicts.length > 0) {
4927
+ throw new CLIError(`${summary.conflicts.length} run${summary.conflicts.length !== 1 ? 's' : ''} already terminal: ${summary.conflicts.map(c => `${c.runId} (${c.status})`).join(', ')}`, 6);
4928
+ }
4929
+ return summary;
4930
+ }
4931
+ function renderCancelSummaryText(summary) {
4932
+ const lines = [];
4933
+ for (const runId of summary.cancelled)
4934
+ lines.push(`${runId} cancelled`);
4935
+ for (const runId of summary.alreadyCancelled)
4936
+ lines.push(`${runId} alreadyCancelled`);
4937
+ for (const c of summary.conflicts)
4938
+ lines.push(`${c.runId} conflict (${c.status})`);
4939
+ for (const runId of summary.notFound)
4940
+ lines.push(`${runId} notFound`);
4941
+ for (const e of summary.errors ?? [])
4942
+ lines.push(`${e.runId} error (${e.message})`);
4943
+ return lines.join('\n');
4944
+ }
4945
+ export function createTestCancelCommand(deps) {
4946
+ const cancel = new Command('cancel');
4947
+ cancel
4948
+ .argument('<run-id...>', 'one or more run ids to cancel')
4949
+ .description('Cancel one or more queued/running runs.\n' +
4950
+ '\nCtrl-C during --wait only detaches — it does NOT cancel the server-side\n' +
4951
+ 'run. This is the real stop button. No refund is issued for the credits\n' +
4952
+ 'already charged at trigger time (D3); an in-flight Lambda finishes on its\n' +
4953
+ 'own and its result is discarded once cancelled.\n' +
4954
+ '\nExit codes:\n' +
4955
+ ' 0 cancelled (fresh or already-cancelled — naturally idempotent)\n' +
4956
+ ' 4 run id not found (single id), or ANY id not found (multi-id — outranks conflict)\n' +
4957
+ ' 6 run already terminal (passed/failed/blocked) — single id: 409; multi-id: any conflict\n' +
4958
+ '\nMulti-id output is a summary: {cancelled, alreadyCancelled, conflicts, notFound}.')
4959
+ .addHelpText('after', GLOBAL_OPTS_HINT)
4960
+ .action(async (runIds, _cmdOpts, command) => {
4961
+ await runTestCancel({
4962
+ ...resolveCommonOptions(command),
4963
+ runIds,
4964
+ }, deps);
4965
+ });
4966
+ return cancel;
4967
+ }
4004
4968
  /**
4005
4969
  * `test wait <run-id>` — M3.3 piece-3.
4006
4970
  *
@@ -4049,6 +5013,7 @@ export async function runTestWait(opts, deps = {}) {
4049
5013
  finalRun = await pollRunUntilTerminal(client, opts.runId, {
4050
5014
  timeoutSeconds: opts.timeoutSeconds,
4051
5015
  sleep: deps.sleep,
5016
+ shutdown: shutdownOf(deps),
4052
5017
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4053
5018
  onTick: (run, elapsedMs) => {
4054
5019
  const elapsed = Math.round(elapsedMs / 1000);
@@ -4071,13 +5036,14 @@ export async function runTestWait(opts, deps = {}) {
4071
5036
  `runId ${p.runId}`,
4072
5037
  `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
4073
5038
  `hint Re-attach with: testsprite test wait ${p.runId}`,
5039
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
4074
5040
  ].join('\n');
4075
5041
  });
4076
5042
  throw ApiError.fromEnvelope({
4077
5043
  error: {
4078
5044
  code: 'UNSUPPORTED', // exit 7 per errors.md
4079
5045
  message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${opts.runId}.`,
4080
- nextAction: `Resume polling: testsprite test wait ${opts.runId}`,
5046
+ nextAction: `Resume polling: testsprite test wait ${opts.runId}, or cancel it: testsprite test cancel ${opts.runId}`,
4081
5047
  requestId: 'local',
4082
5048
  details: { runId: opts.runId, timeoutSeconds: opts.timeoutSeconds },
4083
5049
  },
@@ -4095,10 +5061,47 @@ export async function runTestWait(opts, deps = {}) {
4095
5061
  `runId ${p.runId}`,
4096
5062
  `status ${p.status} (request timed out)`,
4097
5063
  `hint Re-attach with: testsprite test wait ${p.runId}`,
5064
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
4098
5065
  ].join('\n');
4099
5066
  });
4100
5067
  stderrFn(`Run ${opts.runId} is still in progress (request timed out). ` +
4101
- `Re-attach with: testsprite test wait ${opts.runId}`);
5068
+ `Re-attach with: testsprite test wait ${opts.runId}, or cancel with: testsprite test cancel ${opts.runId}`);
5069
+ throw err;
5070
+ }
5071
+ // RATE_LIMITED during polling — see the matching comment in runTestRun.
5072
+ // The HTTP layer already retried internally and gave up; the run keeps
5073
+ // executing (and billing) server-side, so this must emit the same
5074
+ // partial-envelope + honest hint as the timeout/interrupt paths. The SAME
5075
+ // ApiError is rethrown unchanged so its native exit code (11) is kept.
5076
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
5077
+ ticker.finalize(`Run ${opts.runId} — rate limited by the server`);
5078
+ const partial = { runId: opts.runId, status: 'running' };
5079
+ out.print(partial, data => {
5080
+ const p = data;
5081
+ return [
5082
+ `runId ${p.runId}`,
5083
+ `status ${p.status} (rate limited by the server)`,
5084
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
5085
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
5086
+ ].join('\n');
5087
+ });
5088
+ stderrFn(rateLimitedDetachMessage(err, [opts.runId]));
5089
+ throw err;
5090
+ }
5091
+ // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
5092
+ if (err instanceof InterruptError) {
5093
+ ticker.finalize(`Run ${opts.runId} — interrupted (${err.signal})`);
5094
+ const partial = { runId: opts.runId, status: 'running' };
5095
+ out.print(partial, data => {
5096
+ const p = data;
5097
+ return [
5098
+ `runId ${p.runId}`,
5099
+ `status ${p.status} (interrupted)`,
5100
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
5101
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
5102
+ ].join('\n');
5103
+ });
5104
+ stderrFn(interruptDetachMessage(err, [opts.runId]));
4102
5105
  throw err;
4103
5106
  }
4104
5107
  ticker.finalize();
@@ -4107,11 +5110,14 @@ export async function runTestWait(opts, deps = {}) {
4107
5110
  const elapsed = Math.round((Date.now() - startMs) / 1000);
4108
5111
  const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
4109
5112
  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 }));
5113
+ // `test wait` has no type hint; probe the test type once (text mode only,
5114
+ // best-effort) so a backend run's card reads `n/a (backend)` — DEV-282.
5115
+ const isBackend = await resolveRunCardIsBackend(client, finalRun.testId, opts.output, beFallbackUsed);
5116
+ out.print(withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), data => renderRunResponseText(data, { isBackend }));
4111
5117
  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
5118
+ // BE runs have no run-scoped artifact bundle — their failure bundle is
5119
+ // addressed by testId, not runId.
5120
+ stderrFn(isBackend
4115
5121
  ? `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
5122
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
4117
5123
  }
@@ -4142,7 +5148,8 @@ async function writeBatchJUnitReportIfRequested(opts, results) {
4142
5148
  */
4143
5149
  export async function runTestRunAll(opts, deps = {}) {
4144
5150
  assertIdempotencyKey(opts.idempotencyKey);
4145
- requireProjectId(opts.projectId);
5151
+ const projectId = resolveProjectId(opts.projectId, deps);
5152
+ requireProjectId(projectId);
4146
5153
  if (!Number.isInteger(opts.maxConcurrency) ||
4147
5154
  opts.maxConcurrency < 1 ||
4148
5155
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
@@ -4169,7 +5176,7 @@ export async function runTestRunAll(opts, deps = {}) {
4169
5176
  method: 'POST',
4170
5177
  path: '/api/cli/v1/tests/batch/run',
4171
5178
  body: {
4172
- projectId: opts.projectId,
5179
+ projectId,
4173
5180
  testIds: opts.nameFilter ? ['<filtered by --filter>'] : undefined,
4174
5181
  source: 'cli',
4175
5182
  },
@@ -4192,9 +5199,9 @@ export async function runTestRunAll(opts, deps = {}) {
4192
5199
  const batchPortalBase = resolvePortalBase(batchApiUrl);
4193
5200
  const projectDashboardUrl = batchPortalBase === undefined
4194
5201
  ? undefined
4195
- : `${batchPortalBase}/dashboard/tests/${encodeURIComponent(opts.projectId)}`;
5202
+ : `${batchPortalBase}/dashboard/tests/${encodeURIComponent(projectId)}`;
4196
5203
  const withBatchDashboardUrl = (item) => {
4197
- const dashboardUrl = resolvePortalUrl(batchApiUrl, opts.projectId, item.testId);
5204
+ const dashboardUrl = resolvePortalUrl(batchApiUrl, projectId, item.testId);
4198
5205
  return dashboardUrl !== undefined ? { ...item, dashboardUrl } : item;
4199
5206
  };
4200
5207
  const idempotencyKey = opts.idempotencyKey ?? `cli-batch-run-fresh-${randomUUID()}`;
@@ -4206,7 +5213,7 @@ export async function runTestRunAll(opts, deps = {}) {
4206
5213
  if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
4207
5214
  // We need to resolve the full test set to apply the name filter.
4208
5215
  const allPage = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
4209
- query: { projectId: opts.projectId, pageSize, cursor },
5216
+ query: { projectId, pageSize, cursor },
4210
5217
  }), {});
4211
5218
  const needle = opts.nameFilter.toLowerCase();
4212
5219
  const filtered = allPage.items.filter(t => t.name.toLowerCase().includes(needle));
@@ -4217,7 +5224,7 @@ export async function runTestRunAll(opts, deps = {}) {
4217
5224
  }
4218
5225
  testIds = filtered.map(t => t.id);
4219
5226
  if (testIds.length === 0) {
4220
- stderrFn(`No tests found in project ${opts.projectId} matching --filter "${opts.nameFilter}" — nothing to run.`);
5227
+ stderrFn(`No tests found in project ${projectId} matching --filter "${opts.nameFilter}" — nothing to run.`);
4221
5228
  out.print({
4222
5229
  accepted: [],
4223
5230
  conflicts: [],
@@ -4227,12 +5234,12 @@ export async function runTestRunAll(opts, deps = {}) {
4227
5234
  });
4228
5235
  return undefined;
4229
5236
  }
4230
- stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${opts.projectId} for batch run.`);
5237
+ stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${projectId} for batch run.`);
4231
5238
  }
4232
5239
  // When no --filter, omit testIds → server runs ALL tests in the project
4233
5240
  // (BE tests on the legacy V2 wave engine; FE + BE on the V3 unified engine).
4234
5241
  const batchResp = await client.triggerBatchRunFresh({
4235
- projectId: opts.projectId,
5242
+ projectId,
4236
5243
  ...(testIds !== undefined ? { testIds } : {}),
4237
5244
  source: 'cli',
4238
5245
  }, { idempotencyKey });
@@ -4345,7 +5352,7 @@ export async function runTestRunAll(opts, deps = {}) {
4345
5352
  let retryResp;
4346
5353
  try {
4347
5354
  retryResp = await client.triggerBatchRunFresh({
4348
- projectId: opts.projectId,
5355
+ projectId,
4349
5356
  testIds: retryIds,
4350
5357
  source: 'cli',
4351
5358
  }, { idempotencyKey: retryKey });
@@ -4444,6 +5451,7 @@ export async function runTestRunAll(opts, deps = {}) {
4444
5451
  const finalRun = await pollRunUntilTerminal(client, runId, {
4445
5452
  timeoutSeconds: remainingSeconds,
4446
5453
  sleep: deps.sleep,
5454
+ shutdown: shutdownOf(deps),
4447
5455
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4448
5456
  onTick: (run, elapsedMs) => {
4449
5457
  const elapsed = Math.round(elapsedMs / 1000);
@@ -4472,6 +5480,11 @@ export async function runTestRunAll(opts, deps = {}) {
4472
5480
  },
4473
5481
  };
4474
5482
  }
5483
+ // Interrupt must reject the fan-out (the collect point below prints the
5484
+ // partial for every dispatched run), never flatten into a per-member
5485
+ // outcome that would swallow the 128+signum exit (DEV-331).
5486
+ if (err instanceof InterruptError)
5487
+ throw err;
4475
5488
  if (err instanceof RequestTimeoutError) {
4476
5489
  // Client-side per-request timeout during polling — classify as timeout
4477
5490
  // (exit 7) so the fan-out completes and stdout carries every runId.
@@ -4505,26 +5518,43 @@ export async function runTestRunAll(opts, deps = {}) {
4505
5518
  // Bounded concurrency fan-out
4506
5519
  let pollIdx = 0;
4507
5520
  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);
5521
+ try {
5522
+ await new Promise((resolve, reject) => {
5523
+ function startNext() {
5524
+ while (inFlight < concurrencyLimit && pollIdx < pollable.length) {
5525
+ const entry = pollable[pollIdx++];
5526
+ inFlight++;
5527
+ pollFreshAccepted(entry)
5528
+ .then(result => {
5529
+ freshRunResults.push(result);
5530
+ inFlight--;
5531
+ startNext();
5532
+ if (inFlight === 0 && pollIdx >= pollable.length)
5533
+ resolve();
5534
+ })
5535
+ .catch(reject);
5536
+ }
4522
5537
  }
5538
+ startNext();
5539
+ if (pollable.length === 0)
5540
+ resolve();
5541
+ });
5542
+ }
5543
+ catch (fanOutErr) {
5544
+ // Graceful detach (DEV-331): stdout stays parseable — settled members
5545
+ // keep their real status, unfinished ones are marked running — and the
5546
+ // honest stderr line names every runId still executing (and billing).
5547
+ if (fanOutErr instanceof InterruptError) {
5548
+ ticker.finalize(`Batch run — interrupted (${fanOutErr.signal})`);
5549
+ const settled = new Map(freshRunResults.map(r => [r.runId, r]));
5550
+ const partialResults = pollable.map((e) => settled.get(e.runId) ?? { testId: e.testId, runId: e.runId, status: 'running' });
5551
+ out.print({ accepted: partialResults, conflicts, deferred, skippedFrontend, skippedIntegration }, () => partialResults.map(r => `${r.runId} ${r.status}`).join('\n'));
5552
+ const unfinished = pollable.filter(e => !settled.has(e.runId)).map(e => e.runId);
5553
+ if (unfinished.length > 0)
5554
+ stderrFn(interruptDetachMessage(fanOutErr, unfinished));
4523
5555
  }
4524
- startNext();
4525
- if (pollable.length === 0)
4526
- resolve();
4527
- });
5556
+ throw fanOutErr;
5557
+ }
4528
5558
  ticker.finalize();
4529
5559
  const passed = freshRunResults.filter(r => r.status === 'passed').length;
4530
5560
  const failed = freshRunResults.filter(r => r.status !== 'passed' && r.status !== 'timeout').length;
@@ -4550,6 +5580,37 @@ export async function runTestRunAll(opts, deps = {}) {
4550
5580
  };
4551
5581
  await writeBatchJUnitReportIfRequested(opts, freshRunResults);
4552
5582
  out.print(jsonPayload);
5583
+ // CI-native output layer (issue #99): emitted before the gate throws below so
5584
+ // the artifacts land even when the batch exits non-zero. The summary file is a
5585
+ // machine artifact written regardless of --output mode; stdout stays owned by
5586
+ // the envelope above (plus Actions workflow commands, which Actions parses).
5587
+ {
5588
+ const env = deps.env ?? process.env;
5589
+ const ghEnabled = opts.ghOutput === true || env.GITHUB_ACTIONS === 'true';
5590
+ if (ghEnabled || opts.summaryFile !== undefined) {
5591
+ const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
5592
+ if (opts.summaryFile !== undefined) {
5593
+ try {
5594
+ writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
5595
+ }
5596
+ catch {
5597
+ stderrFn(`[run] could not write --summary-file ${opts.summaryFile}; continuing`);
5598
+ }
5599
+ }
5600
+ if (ghEnabled) {
5601
+ const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
5602
+ emitGithubOutputs(ciSummary, env, {
5603
+ stdout: stdoutFn,
5604
+ stderr: stderrFn,
5605
+ appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
5606
+ // Under --output json the envelope above owns stdout; workflow
5607
+ // commands go to stderr instead (the Actions runner parses both
5608
+ // streams), keeping the documented machine output parseable.
5609
+ annotations: opts.output === 'json' ? stderrFn : stdoutFn,
5610
+ }, { force: opts.ghOutput === true });
5611
+ }
5612
+ }
5613
+ }
4553
5614
  // Rate-deferred tests were never dispatched → the batch is incomplete (exit 7),
4554
5615
  // mirroring `test rerun --all`. Checked before the failed-run throw so the
4555
5616
  // operator learns to retry the deferred set.
@@ -4565,7 +5626,10 @@ export async function runTestRunAll(opts, deps = {}) {
4565
5626
  error: {
4566
5627
  code: 'UNSUPPORTED',
4567
5628
  message: `${timedOut} run${timedOut !== 1 ? 's' : ''} timed out.`,
4568
- nextAction: timedOutRunIds.map(rid => `Resume: testsprite test wait ${rid}`).join('\n'),
5629
+ nextAction: [
5630
+ ...timedOutRunIds.map(rid => `Resume: testsprite test wait ${rid}`),
5631
+ ...timedOutRunIds.map(rid => `Cancel: testsprite test cancel ${rid}`),
5632
+ ].join('\n'),
4569
5633
  requestId: 'local',
4570
5634
  details: { timedOutRunIds, timeoutSeconds: opts.timeoutSeconds },
4571
5635
  },
@@ -4592,8 +5656,9 @@ export async function runTestRunAll(opts, deps = {}) {
4592
5656
  /**
4593
5657
  * `test rerun` — M3.4 piece-3.
4594
5658
  *
4595
- * FE: `POST /tests/{id}/runs/rerun` → verbatim replay (no credit). With
4596
- * `--wait`, polls `GET /runs/{runId}` until terminal.
5659
+ * FE: `POST /tests/{id}/runs/rerun` → verbatim replay, billed at 0.5 credits
5660
+ * (same as a fresh run; legacy V2 accounts: free). With `--wait`, polls
5661
+ * `GET /runs/{runId}` until terminal.
4597
5662
  *
4598
5663
  * BE: same route → closure + per-member runIds. With `--wait`, polls every
4599
5664
  * closure-member runId; exits on the named test's verdict; failed closure
@@ -4743,7 +5808,10 @@ export async function runTestRerun(opts, deps = {}) {
4743
5808
  try {
4744
5809
  rerunResp = await client.triggerRerun(testId, {
4745
5810
  source: 'cli',
4746
- ...(effectiveAutoHeal ? { autoHeal: true } : {}),
5811
+ // Always send the effective boolean, including an explicit `false`
5812
+ // opt-out — the server defaults an ABSENT field to heal-on, so
5813
+ // omitting the key on opt-out silently discarded --no-auto-heal.
5814
+ autoHeal: effectiveAutoHeal,
4747
5815
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
4748
5816
  }, { idempotencyKey });
4749
5817
  }
@@ -4783,8 +5851,11 @@ export async function runTestRerun(opts, deps = {}) {
4783
5851
  // Print auto-heal advisory.
4784
5852
  // CLI path: auto-heal is default-on for FE reruns (--no-auto-heal to opt
4785
5853
  // out). Free and paid CLI callers both get auto-heal; backend no longer
4786
- // tier-gates for source='cli'. Cost: 0.2 credits per engage (charged only
4787
- // when Phase-2 heal actually runs; verbatim replay passes are free).
5854
+ // tier-gates for source='cli'. The rerun itself is billed at 0.5 credits
5855
+ // regardless of whether heal engages (same as a fresh run; legacy V2
5856
+ // accounts: a verbatim replay pass is free). A heal engage costs an
5857
+ // additional 0.2 credits on top of that, charged only when Phase-2 heal
5858
+ // actually runs.
4788
5859
  //
4789
5860
  // Defensive branch: if the server still echoes autoHeal:false after we sent
4790
5861
  // autoHeal:true, the server did not apply it (unexpected; may happen on
@@ -4798,17 +5869,21 @@ export async function runTestRerun(opts, deps = {}) {
4798
5869
  // default-on `true`, so opts.autoHeal && !rerunResp.autoHeal would
4799
5870
  // fire spuriously for every BE rerun).
4800
5871
  if (effectiveAutoHeal && !rerunResp.autoHeal) {
4801
- // Env-correct billing link (dev/prod portals differ); route-only when
4802
- // the API host is unknown.
4803
- const advisoryPortalBase = resolvePortalBase(resolveApiUrl(opts, deps));
5872
+ // Points at `testsprite usage`, not a hardcoded billing URL: this CLI
5873
+ // path has no per-request org context (no backend nextAction feeds
5874
+ // this advisory, and a personal-vs-org-bound key can't be told apart
5875
+ // here), while `usage` already renders whichever wallet (personal or
5876
+ // organization) actually governs this key's balance.
4804
5877
  stderrFn(`[advisory] auto-heal was not applied by the server (verbatim replay).` +
4805
- ` If this was unexpected, check your balance at ${advisoryPortalBase !== undefined
4806
- ? `${advisoryPortalBase}/dashboard/settings/billing`
4807
- : 'the portal Billing page (/dashboard/settings/billing)'}.`);
5878
+ ` If this was unexpected, check your balance with \`testsprite usage\`.`);
4808
5879
  }
4809
5880
  else if (rerunResp.autoHeal) {
4810
5881
  stderrFn(`[advisory] auto-heal on (FE rerun default). If a step has drifted, healing runs and costs 0.2 credit. Disable with --no-auto-heal.`);
4811
5882
  }
5883
+ // Server advisory: the autoHeal opt-out was forwarded to the execution
5884
+ // engine but is not yet enforced there. Present only on a V3-routed
5885
+ // rerun with an explicit autoHeal:false request; absent everywhere else.
5886
+ emitRerunAdvisories(stderrFn, rerunResp.advisories);
4812
5887
  const isBERerun = !!rerunResp.closure;
4813
5888
  if (isBERerun && rerunResp.closure) {
4814
5889
  const totalCount = rerunResp.closure.members.length;
@@ -4856,6 +5931,8 @@ export async function runTestRerun(opts, deps = {}) {
4856
5931
  // BE rerun: poll every closure-member runId, exit on named test's verdict.
4857
5932
  const namedRunId = rerunResp.runId;
4858
5933
  const closureMembers = rerunResp.closure.members;
5934
+ // `unobserved`: member never reached a terminal verdict (timed out or its
5935
+ // poll errored). Distinct from an observed non-passed run (failed/blocked).
4859
5936
  const closureFailures = [];
4860
5937
  const pollMember = async (member) => {
4861
5938
  const resolveAlternate = makeBackendWaitFallback({
@@ -4865,9 +5942,10 @@ export async function runTestRerun(opts, deps = {}) {
4865
5942
  onResolved: () => undefined,
4866
5943
  });
4867
5944
  try {
4868
- return await pollRunUntilTerminal(client, member.runId, {
5945
+ const finalRun = await pollRunUntilTerminal(client, member.runId, {
4869
5946
  timeoutSeconds: opts.timeoutSeconds,
4870
5947
  sleep: deps.sleep,
5948
+ shutdown: shutdownOf(deps),
4871
5949
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4872
5950
  onTick: (run, elapsedMs) => {
4873
5951
  const elapsed = Math.round(elapsedMs / 1000);
@@ -4881,12 +5959,22 @@ export async function runTestRerun(opts, deps = {}) {
4881
5959
  },
4882
5960
  resolveAlternate,
4883
5961
  });
5962
+ return { kind: 'terminal', run: finalRun };
4884
5963
  }
4885
5964
  catch (err) {
4886
- if (err instanceof TimeoutError) {
4887
- return null;
4888
- }
4889
- throw err;
5965
+ if (err instanceof TimeoutError)
5966
+ return { kind: 'timeout' };
5967
+ // Preserve the two intentional whole-fan-out aborts: each has a
5968
+ // dedicated outer-catch branch (RequestTimeoutError → all-running
5969
+ // partial + re-attach hints + exit 7; InterruptError → DEV-331
5970
+ // graceful detach). Re-throw so the fan-out's `.catch(reject)` fires.
5971
+ if (err instanceof RequestTimeoutError || err instanceof InterruptError)
5972
+ throw err;
5973
+ // Any other member error (ApiError, transient 5xx, malformed
5974
+ // response) is classified per-member instead of rejecting the whole
5975
+ // fan-out and discarding every already-collected sibling result.
5976
+ const status = err instanceof ApiError ? err.code : 'error';
5977
+ return { kind: 'error', status, error: err };
4890
5978
  }
4891
5979
  };
4892
5980
  // Fan-out poll with concurrency limit
@@ -4895,6 +5983,10 @@ export async function runTestRerun(opts, deps = {}) {
4895
5983
  const concurrencyLimit = opts.maxConcurrency;
4896
5984
  let inFlight = 0;
4897
5985
  let memberIdx = 0;
5986
+ // Set when the NAMED test's own poll errors (not a timeout). Re-thrown
5987
+ // after the payload is printed so its real error/exit code is preserved
5988
+ // without discarding the sibling results collected alongside it.
5989
+ let namedPollError;
4898
5990
  try {
4899
5991
  await new Promise((resolve, reject) => {
4900
5992
  function startNext() {
@@ -4902,27 +5994,51 @@ export async function runTestRerun(opts, deps = {}) {
4902
5994
  const member = members[memberIdx++];
4903
5995
  inFlight++;
4904
5996
  pollMember(member)
4905
- .then(result => {
4906
- memberResults.set(member.runId, result);
4907
- if (member.runId !== namedRunId) {
4908
- if (result === null) {
4909
- // Timed-out closure member: treat as incomplete/failed so
4910
- // the exit-code path fires exit 7 rather than silently
4911
- // succeeding with an unobserved member.
5997
+ .then(outcome => {
5998
+ if (outcome.kind === 'terminal') {
5999
+ memberResults.set(member.runId, outcome.run);
6000
+ if (member.runId !== namedRunId && outcome.run.status !== 'passed') {
6001
+ closureFailures.push({
6002
+ testId: member.testId,
6003
+ runId: member.runId,
6004
+ status: outcome.run.status,
6005
+ });
6006
+ stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) finished with status: ${outcome.run.status}`);
6007
+ }
6008
+ }
6009
+ else if (outcome.kind === 'timeout') {
6010
+ // Timed-out closure member: treat as incomplete/failed so
6011
+ // the exit-code path fires exit 7 rather than silently
6012
+ // succeeding with an unobserved member.
6013
+ memberResults.set(member.runId, null);
6014
+ if (member.runId !== namedRunId) {
4912
6015
  closureFailures.push({
4913
6016
  testId: member.testId,
4914
6017
  runId: member.runId,
4915
6018
  status: 'timeout',
6019
+ unobserved: true,
4916
6020
  });
4917
6021
  stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) timed out — rerun did not reach terminal within --timeout`);
4918
6022
  }
4919
- else if (result.status !== 'passed') {
6023
+ }
6024
+ else {
6025
+ // Classified per-member error — recorded, never aborts the
6026
+ // fan-out. The named test's error is stashed for re-throw;
6027
+ // sibling errors surface in closureFailures[].
6028
+ memberResults.set(member.runId, null);
6029
+ if (member.runId === namedRunId) {
6030
+ namedPollError = outcome.error;
6031
+ }
6032
+ else {
6033
+ // A poll error means we never saw a terminal verdict — the
6034
+ // run may still be in flight — so it's unobserved too.
4920
6035
  closureFailures.push({
4921
6036
  testId: member.testId,
4922
6037
  runId: member.runId,
4923
- status: result.status,
6038
+ status: outcome.status,
6039
+ unobserved: true,
4924
6040
  });
4925
- stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) finished with status: ${result.status}`);
6041
+ stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) could not be confirmed terminal — poll error: ${outcome.status}`);
4926
6042
  }
4927
6043
  }
4928
6044
  inFlight--;
@@ -4958,7 +6074,48 @@ export async function runTestRerun(opts, deps = {}) {
4958
6074
  const reattachHints = closureMembers
4959
6075
  .map(m => `testsprite test wait ${m.runId}`)
4960
6076
  .join('\n');
4961
- stderrFn(`Closure members are still in progress (request timed out). Re-attach with:\n${reattachHints}`);
6077
+ const cancelHints = closureMembers
6078
+ .map(m => `testsprite test cancel ${m.runId}`)
6079
+ .join('\n');
6080
+ stderrFn(`Closure members are still in progress (request timed out). Re-attach with:\n${reattachHints}\n` +
6081
+ `Or cancel with:\n${cancelHints}`);
6082
+ throw fanOutErr;
6083
+ }
6084
+ // RATE_LIMITED from any member's poll (pollMember only swallows
6085
+ // TimeoutError into a null return — see above; every other error,
6086
+ // including a RATE_LIMITED ApiError, propagates through .catch(reject)
6087
+ // exactly like RequestTimeoutError). Same partial shape as the
6088
+ // timeout path so the caller always has every closure-member runId on
6089
+ // stdout; the SAME thrown ApiError is rethrown unchanged so its
6090
+ // native exit code (11) is preserved.
6091
+ if (fanOutErr instanceof ApiError && fanOutErr.code === 'RATE_LIMITED') {
6092
+ ticker.finalize(`Closure fan-out — rate limited by the server`);
6093
+ const dispatchedRunIds = closureMembers.map(m => ({
6094
+ runId: m.runId,
6095
+ testId: m.testId,
6096
+ role: m.role,
6097
+ status: 'running',
6098
+ }));
6099
+ out.print({ runId: namedRunId, status: 'running', closure: dispatchedRunIds }, () => dispatchedRunIds
6100
+ .map(m => `${m.role.padEnd(9)} ${m.testId} (runId: ${m.runId}) — running`)
6101
+ .join('\n'));
6102
+ stderrFn(rateLimitedDetachMessage(fanOutErr, closureMembers.map(m => m.runId)));
6103
+ throw fanOutErr;
6104
+ }
6105
+ // Graceful detach (DEV-331): same partial shape as the timeout path —
6106
+ // SIG-6 requires the partial to list ALL dispatched runIds.
6107
+ if (fanOutErr instanceof InterruptError) {
6108
+ ticker.finalize(`Closure fan-out — interrupted (${fanOutErr.signal})`);
6109
+ const dispatchedRunIds = closureMembers.map(m => ({
6110
+ runId: m.runId,
6111
+ testId: m.testId,
6112
+ role: m.role,
6113
+ status: 'running',
6114
+ }));
6115
+ out.print({ runId: namedRunId, status: 'running', closure: dispatchedRunIds }, () => dispatchedRunIds
6116
+ .map(m => `${m.role.padEnd(9)} ${m.testId} (runId: ${m.runId}) — running`)
6117
+ .join('\n'));
6118
+ stderrFn(interruptDetachMessage(fanOutErr, closureMembers.map(m => m.runId)));
4962
6119
  throw fanOutErr;
4963
6120
  }
4964
6121
  throw fanOutErr;
@@ -4990,12 +6147,25 @@ export async function runTestRerun(opts, deps = {}) {
4990
6147
  return lines.join('\n');
4991
6148
  });
4992
6149
  if (!namedResult) {
6150
+ // Named test's own poll errored (not a timeout): re-throw its real
6151
+ // error now that the payload (incl. sibling closureFailures) is
6152
+ // printed, preserving the true exit code instead of masking it as a
6153
+ // timeout.
6154
+ if (namedPollError !== undefined) {
6155
+ // Every dispatched member is still executing (and billing), so a
6156
+ // rate-limited named poll owes the same detach hints the fan-out's
6157
+ // own branch emits — which this re-throw bypasses.
6158
+ if (namedPollError instanceof ApiError && namedPollError.code === 'RATE_LIMITED') {
6159
+ stderrFn(rateLimitedDetachMessage(namedPollError, closureMembers.map(m => m.runId)));
6160
+ }
6161
+ throw namedPollError;
6162
+ }
4993
6163
  // timeout
4994
6164
  throw ApiError.fromEnvelope({
4995
6165
  error: {
4996
6166
  code: 'UNSUPPORTED',
4997
6167
  message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${namedRunId}.`,
4998
- nextAction: `Resume polling: testsprite test wait ${namedRunId}`,
6168
+ nextAction: `Resume polling: testsprite test wait ${namedRunId}, or cancel it: testsprite test cancel ${namedRunId}`,
4999
6169
  requestId: 'local',
5000
6170
  details: { runId: namedRunId, timeoutSeconds: opts.timeoutSeconds },
5001
6171
  },
@@ -5005,21 +6175,23 @@ export async function runTestRerun(opts, deps = {}) {
5005
6175
  stderrFn(`Run finished with status: ${namedResult.status}. Use 'testsprite test artifact get ${namedRunId}' to download the failure bundle.`);
5006
6176
  throw new CLIError(`Run ${namedRunId} finished with status: ${namedResult.status}`, 1);
5007
6177
  }
5008
- // Fix B: timed-out closure members (non-named) are recorded in
5009
- // closureFailures with status 'timeout'. Even when the named run passes,
5010
- // we must exit 7 so --wait does not silently succeed when the closure
5011
- // as a whole was never observed to reach terminal.
5012
- const timedOutMembers = closureFailures.filter(f => f.status === 'timeout');
5013
- if (timedOutMembers.length > 0) {
5014
- const resumeHints = timedOutMembers.map(f => `testsprite test wait ${f.runId}`).join('\n');
6178
+ // Any unobserved member (timed out OR poll-errored) flips --wait to exit 7,
6179
+ // even when the named run passes — otherwise a dependency whose status was
6180
+ // never confirmed would let --wait exit 0. Observed-failed members are not
6181
+ // included; that's the future --fail-on-closure decision.
6182
+ const unobservedMembers = closureFailures.filter(f => f.unobserved);
6183
+ if (unobservedMembers.length > 0) {
6184
+ const unobservedIds = unobservedMembers.map(f => f.runId);
6185
+ const resumeHints = unobservedIds.map(runId => `testsprite test wait ${runId}`).join('\n') +
6186
+ `\nCancel instead: testsprite test cancel ${unobservedIds.join(' ')}`;
5015
6187
  throw ApiError.fromEnvelope({
5016
6188
  error: {
5017
6189
  code: 'UNSUPPORTED',
5018
- message: `${timedOutMembers.length} closure member${timedOutMembers.length !== 1 ? 's' : ''} timed out before reaching terminal status.`,
6190
+ message: `${unobservedMembers.length} closure member${unobservedMembers.length !== 1 ? 's' : ''} did not reach an observed terminal status (timed out or errored during polling).`,
5019
6191
  nextAction: resumeHints,
5020
6192
  requestId: 'local',
5021
6193
  details: {
5022
- timedOutRunIds: timedOutMembers.map(f => f.runId),
6194
+ unobservedRunIds: unobservedIds,
5023
6195
  timeoutSeconds: opts.timeoutSeconds,
5024
6196
  },
5025
6197
  },
@@ -5044,6 +6216,7 @@ export async function runTestRerun(opts, deps = {}) {
5044
6216
  finalRun = await pollRunUntilTerminal(client, rerunResp.runId, {
5045
6217
  timeoutSeconds: opts.timeoutSeconds,
5046
6218
  sleep: deps.sleep,
6219
+ shutdown: shutdownOf(deps),
5047
6220
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5048
6221
  onTick: (run, elapsedMs) => {
5049
6222
  const elapsed = Math.round(elapsedMs / 1000);
@@ -5060,7 +6233,7 @@ export async function runTestRerun(opts, deps = {}) {
5060
6233
  error: {
5061
6234
  code: 'UNSUPPORTED',
5062
6235
  message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${rerunResp.runId}.`,
5063
- nextAction: `Resume polling: testsprite test wait ${rerunResp.runId}`,
6236
+ nextAction: `Resume polling: testsprite test wait ${rerunResp.runId}, or cancel it: testsprite test cancel ${rerunResp.runId}`,
5064
6237
  requestId: 'local',
5065
6238
  details: { runId: rerunResp.runId, timeoutSeconds: opts.timeoutSeconds },
5066
6239
  },
@@ -5077,10 +6250,45 @@ export async function runTestRerun(opts, deps = {}) {
5077
6250
  `runId ${p.runId}`,
5078
6251
  `status ${p.status} (request timed out)`,
5079
6252
  `hint Re-attach with: testsprite test wait ${p.runId}`,
6253
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
5080
6254
  ].join('\n');
5081
6255
  });
5082
6256
  stderrFn(`Run ${rerunResp.runId} is still in progress (request timed out). ` +
5083
- `Re-attach with: testsprite test wait ${rerunResp.runId}`);
6257
+ `Re-attach with: testsprite test wait ${rerunResp.runId}, or cancel with: testsprite test cancel ${rerunResp.runId}`);
6258
+ throw err;
6259
+ }
6260
+ // RATE_LIMITED during polling — see the matching comment in runTestRun.
6261
+ // Same partial-envelope contract; the SAME thrown ApiError is rethrown
6262
+ // unchanged so its native exit code (11) is preserved.
6263
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
6264
+ ticker.finalize(`Run ${rerunResp.runId} — rate limited by the server`);
6265
+ const partial = { runId: rerunResp.runId, status: 'running' };
6266
+ out.print(partial, data => {
6267
+ const p = data;
6268
+ return [
6269
+ `runId ${p.runId}`,
6270
+ `status ${p.status} (rate limited by the server)`,
6271
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
6272
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
6273
+ ].join('\n');
6274
+ });
6275
+ stderrFn(rateLimitedDetachMessage(err, [rerunResp.runId]));
6276
+ throw err;
6277
+ }
6278
+ // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
6279
+ if (err instanceof InterruptError) {
6280
+ ticker.finalize(`Run ${rerunResp.runId} — interrupted (${err.signal})`);
6281
+ const partial = { runId: rerunResp.runId, status: 'running' };
6282
+ out.print(partial, data => {
6283
+ const p = data;
6284
+ return [
6285
+ `runId ${p.runId}`,
6286
+ `status ${p.status} (interrupted)`,
6287
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
6288
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
6289
+ ].join('\n');
6290
+ });
6291
+ stderrFn(interruptDetachMessage(err, [rerunResp.runId]));
5084
6292
  throw err;
5085
6293
  }
5086
6294
  ticker.finalize();
@@ -5090,9 +6298,16 @@ export async function runTestRerun(opts, deps = {}) {
5090
6298
  void elapsed;
5091
6299
  const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5092
6300
  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 }));
6301
+ // Probe the test type once (text mode only, best-effort) so a backend
6302
+ // rerun's card reads `n/a (backend)` even when the fallback never fired
6303
+ // (BE run rows finalize server-side now) — DEV-282.
6304
+ const isBackend = await resolveRunCardIsBackend(client, testId, opts.output, beFallbackUsed);
6305
+ out.print(withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), data => renderRunResponseText(data, { isBackend }));
5094
6306
  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.`);
6307
+ // BE reruns have no run-scoped artifact bundle — address by testId.
6308
+ stderrFn(isBackend
6309
+ ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${testId}' to download the bundle.`
6310
+ : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
5096
6311
  }
5097
6312
  const exitCode = exitCodeForRunStatus(finalRun.status);
5098
6313
  if (exitCode !== 0) {
@@ -5193,7 +6408,9 @@ export async function runTestRerun(opts, deps = {}) {
5193
6408
  const chunkResp = await client.triggerBatchRerun({
5194
6409
  source: 'cli',
5195
6410
  testIds: chunk,
5196
- ...(effectiveAutoHeal ? { autoHeal: true } : {}),
6411
+ // Always send the effective boolean, including an explicit `false`
6412
+ // opt-out — see the matching comment on the single-rerun call site.
6413
+ autoHeal: effectiveAutoHeal,
5197
6414
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
5198
6415
  }, { idempotencyKey: chunkKey });
5199
6416
  chunkResponses.push(chunkResp);
@@ -5237,10 +6454,17 @@ export async function runTestRerun(opts, deps = {}) {
5237
6454
  byProject: mergeBatchRerunClosureByProject(chunkResponses.flatMap(r => r.closure.byProject)),
5238
6455
  },
5239
6456
  notFound: chunkResponses.flatMap(r => r.notFound ?? []),
6457
+ // Absent on every response except a V3-routed batch containing
6458
+ // at least one FE test with an explicit autoHeal:false opt-out. Dedupe
6459
+ // across chunks — every chunk in the same invocation carries the same
6460
+ // autoHeal request, so the same advisory would otherwise repeat per chunk.
6461
+ advisories: dedupeRerunAdvisories(chunkResponses.flatMap(r => r.advisories ?? [])),
5240
6462
  };
5241
6463
  // Print dispatch summary
5242
6464
  // Mutable: D3 deferred-retry loop may append to `accepted`/`conflicts` and
5243
- // drain `deferred` under --wait.
6465
+ // drain `deferred` under --wait. `advisories` may also grow if a D3 retry
6466
+ // response carries an advisory the initial dispatch didn't (defensive —
6467
+ // in practice the same request shape produces the same advisory set).
5244
6468
  let accepted = batchResp.accepted.slice();
5245
6469
  let deferred = batchResp.deferred.slice();
5246
6470
  let conflicts = batchResp.conflicts.slice();
@@ -5248,6 +6472,9 @@ export async function runTestRerun(opts, deps = {}) {
5248
6472
  // the retry window; the retry response's notFound[] is merged into this set so
5249
6473
  // the test is never reported as "resolved" when it actually vanished.
5250
6474
  let notFound = (batchResp.notFound ?? []).slice();
6475
+ // Mutable so a D3 deferred-retry response can contribute an
6476
+ // advisory the initial dispatch didn't carry (defensive; see comment above).
6477
+ let advisories = (batchResp.advisories ?? []).slice();
5251
6478
  const closureByProject = batchResp.closure.byProject;
5252
6479
  const addedProducersTotal = closureByProject.reduce((n, p) => n + p.addedProducers.length, 0);
5253
6480
  const summaryParts = [
@@ -5333,7 +6560,10 @@ export async function runTestRerun(opts, deps = {}) {
5333
6560
  const retryChunkResp = await client.triggerBatchRerun({
5334
6561
  source: 'cli',
5335
6562
  testIds: chunk,
5336
- ...(effectiveAutoHeal ? { autoHeal: true } : {}),
6563
+ // Always send the effective boolean, including an explicit
6564
+ // `false` opt-out — see the matching comment on the initial
6565
+ // dispatch call site above.
6566
+ autoHeal: effectiveAutoHeal,
5337
6567
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
5338
6568
  }, { idempotencyKey: retryKey });
5339
6569
  retryChunkResponses.push(retryChunkResp);
@@ -5351,6 +6581,12 @@ export async function runTestRerun(opts, deps = {}) {
5351
6581
  // into the running notFound set and remove from deferred so it isn't
5352
6582
  // reported as "resolved" in the final output.
5353
6583
  const newlyNotFound = retryChunkResponses.flatMap(r => r.notFound ?? []);
6584
+ // Merge any advisories the retry response carries into the
6585
+ // running set (deduped — see the initial-dispatch comment above).
6586
+ const newlyAdvisories = retryChunkResponses.flatMap(r => r.advisories ?? []);
6587
+ if (newlyAdvisories.length > 0) {
6588
+ advisories = dedupeRerunAdvisories(advisories.concat(newlyAdvisories));
6589
+ }
5354
6590
  if (newlyDuplicateCount > 0) {
5355
6591
  stderrFn(`[warn] ${newlyDuplicateCount} test${newlyDuplicateCount !== 1 ? 's were' : ' was'} triggered more than once across deferred-retry chunked requests (shared BE producer/teardown); kept the first run, ignored the rest.`);
5356
6592
  }
@@ -5382,10 +6618,13 @@ export async function runTestRerun(opts, deps = {}) {
5382
6618
  }
5383
6619
  }
5384
6620
  }
6621
+ // Print the (deduped) advisory set once, after any D3 retries have
6622
+ // had a chance to contribute one, not once per chunk/attempt.
6623
+ emitRerunAdvisories(stderrFn, advisories);
5385
6624
  if (!opts.wait) {
5386
6625
  // [P2] Build output from post-retry mutable state so deferred/conflicts/notFound
5387
6626
  // reflect what the D3 loop discovered, not just the initial batchResp.
5388
- out.print({ ...batchResp, accepted, deferred, conflicts, notFound });
6627
+ out.print({ ...batchResp, accepted, deferred, conflicts, notFound, advisories });
5389
6628
  if (deferred.length > 0) {
5390
6629
  throw new CLIError(`Batch rerun incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} were rate-deferred. Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
5391
6630
  }
@@ -5408,12 +6647,12 @@ export async function runTestRerun(opts, deps = {}) {
5408
6647
  });
5409
6648
  }
5410
6649
  // [P2] Return post-retry state including merged notFound.
5411
- return { ...batchResp, accepted, deferred, conflicts, notFound };
6650
+ return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
5412
6651
  }
5413
6652
  // --wait: fan-out poll each accepted run by its runId
5414
6653
  if (accepted.length === 0) {
5415
6654
  // [P2] Build output from post-retry mutable state including merged notFound.
5416
- out.print({ ...batchResp, accepted, deferred, conflicts, notFound });
6655
+ out.print({ ...batchResp, accepted, deferred, conflicts, notFound, advisories });
5417
6656
  if (deferred.length > 0) {
5418
6657
  throw new CLIError(`Batch rerun: no tests were accepted (${deferred.length} deferred). ` +
5419
6658
  `Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
@@ -5436,7 +6675,7 @@ export async function runTestRerun(opts, deps = {}) {
5436
6675
  });
5437
6676
  }
5438
6677
  // [P2] Return post-retry state including merged notFound.
5439
- return { ...batchResp, accepted, deferred, conflicts, notFound };
6678
+ return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
5440
6679
  }
5441
6680
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
5442
6681
  const concurrencyLimit = opts.maxConcurrency;
@@ -5459,6 +6698,7 @@ export async function runTestRerun(opts, deps = {}) {
5459
6698
  const finalRun = await pollRunUntilTerminal(client, entry.runId, {
5460
6699
  timeoutSeconds: remainingSeconds,
5461
6700
  sleep: deps.sleep,
6701
+ shutdown: shutdownOf(deps),
5462
6702
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5463
6703
  onTick: (run, elapsedMs) => {
5464
6704
  const elapsed = Math.round(elapsedMs / 1000);
@@ -5487,6 +6727,11 @@ export async function runTestRerun(opts, deps = {}) {
5487
6727
  },
5488
6728
  };
5489
6729
  }
6730
+ // Interrupt must reject the fan-out (the collect point below prints the
6731
+ // partial for every dispatched run), never flatten into a per-member
6732
+ // outcome that would swallow the 128+signum exit (DEV-331).
6733
+ if (err instanceof InterruptError)
6734
+ throw err;
5490
6735
  if (err instanceof RequestTimeoutError) {
5491
6736
  // Client-side per-request timeout during polling — classify as timeout
5492
6737
  // (exit 7) so the fan-out completes and stdout carries every runId.
@@ -5520,26 +6765,43 @@ export async function runTestRerun(opts, deps = {}) {
5520
6765
  // Bounded concurrency fan-out
5521
6766
  let acceptedIdx = 0;
5522
6767
  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);
6768
+ try {
6769
+ await new Promise((resolve, reject) => {
6770
+ function startNext() {
6771
+ while (inFlight < concurrencyLimit && acceptedIdx < accepted.length) {
6772
+ const entry = accepted[acceptedIdx++];
6773
+ inFlight++;
6774
+ pollAccepted(entry)
6775
+ .then(result => {
6776
+ rerunResults.push(result);
6777
+ inFlight--;
6778
+ startNext();
6779
+ if (inFlight === 0 && acceptedIdx >= accepted.length)
6780
+ resolve();
6781
+ })
6782
+ .catch(reject);
6783
+ }
5537
6784
  }
6785
+ startNext();
6786
+ if (accepted.length === 0)
6787
+ resolve();
6788
+ });
6789
+ }
6790
+ catch (fanOutErr) {
6791
+ // Graceful detach (DEV-331): stdout stays parseable — settled members
6792
+ // keep their real status, unfinished ones are marked running — and the
6793
+ // honest stderr line names every runId still executing (and billing).
6794
+ if (fanOutErr instanceof InterruptError) {
6795
+ ticker.finalize(`Batch rerun — interrupted (${fanOutErr.signal})`);
6796
+ const settled = new Map(rerunResults.map(r => [r.runId, r]));
6797
+ const partialResults = accepted.map((e) => settled.get(e.runId) ?? { testId: e.testId, runId: e.runId, status: 'running' });
6798
+ out.print({ accepted: partialResults, deferred, conflicts, notFound }, () => partialResults.map(r => `${r.runId} ${r.status}`).join('\n'));
6799
+ const unfinished = accepted.filter(e => !settled.has(e.runId)).map(e => e.runId);
6800
+ if (unfinished.length > 0)
6801
+ stderrFn(interruptDetachMessage(fanOutErr, unfinished));
5538
6802
  }
5539
- startNext();
5540
- if (accepted.length === 0)
5541
- resolve();
5542
- });
6803
+ throw fanOutErr;
6804
+ }
5543
6805
  ticker.finalize();
5544
6806
  const passed = rerunResults.filter(r => r.status === 'passed').length;
5545
6807
  const failed = rerunResults.filter(r => r.status !== 'passed' && r.status !== 'timeout').length;
@@ -5559,6 +6821,9 @@ export async function runTestRerun(opts, deps = {}) {
5559
6821
  // report the partial run as fully successful. Mirrors the non-wait
5560
6822
  // `out.print(batchResp)` path.
5561
6823
  notFound,
6824
+ // Mirrors the non-wait `out.print(batchResp)` path — carry the
6825
+ // (deduped, post-retry) advisory set into the --wait JSON payload too.
6826
+ advisories,
5562
6827
  closure: batchResp.closure,
5563
6828
  summary: {
5564
6829
  passed,
@@ -5595,6 +6860,7 @@ export async function runTestRerun(opts, deps = {}) {
5595
6860
  // `test wait` accepts exactly one run id — emit one command per
5596
6861
  // timed-out run so the hint is always valid.
5597
6862
  ...(timedOut > 0 ? stillRunning.map(rid => `Resume: testsprite test wait ${rid}`) : []),
6863
+ ...(timedOut > 0 ? stillRunning.map(rid => `Cancel: testsprite test cancel ${rid}`) : []),
5598
6864
  ]
5599
6865
  .filter(Boolean)
5600
6866
  .join('\n'),
@@ -5618,7 +6884,7 @@ export async function runTestRerun(opts, deps = {}) {
5618
6884
  // final accounting (accepted = original BatchRerunAccepted[] dispatch list
5619
6885
  // as required by the BatchRerunResponse type; rerunResults is the polled
5620
6886
  // outcome printed to stdout and is not part of the returned shape).
5621
- return { ...batchResp, accepted, deferred, conflicts, notFound };
6887
+ return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
5622
6888
  }
5623
6889
  export function resolveDefaultArtifactDir(runId, cwd = process.cwd()) {
5624
6890
  requireNonEmpty('run-id', runId);
@@ -5814,6 +7080,8 @@ export function createTestCommand(deps = {}) {
5814
7080
  .option('--starting-token <token>', 'opaque cursor from a previous list response')
5815
7081
  .option('--cursor <token>', 'alias for --starting-token; accepted for parity with `test result --history`')
5816
7082
  .option('--max-items <n>', 'stop after this many items across auto-paged pages')
7083
+ .option('--columns <list>', 'select/reorder text table columns (comma-separated keys)')
7084
+ .option('--no-header', 'suppress the text table header row')
5817
7085
  .addHelpText('after', GLOBAL_OPTS_HINT)
5818
7086
  .action(async (cmdOpts, command) => {
5819
7087
  // Same parser strategy as `project list`: skip Commander's number
@@ -5833,6 +7101,8 @@ export function createTestCommand(deps = {}) {
5833
7101
  pageSize: parseNumericFlag(cmdOpts.pageSize, 'page-size'),
5834
7102
  startingToken: cmdOpts.startingToken ?? cmdOpts.cursor,
5835
7103
  maxItems: parseNumericFlag(cmdOpts.maxItems, 'max-items'),
7104
+ columns: cmdOpts.columns,
7105
+ noHeader: cmdOpts.header === false,
5836
7106
  }, deps);
5837
7107
  });
5838
7108
  test
@@ -5853,6 +7123,8 @@ export function createTestCommand(deps = {}) {
5853
7123
  .option('--code-file <path>', 'file containing the test code (≤ 350 KB)')
5854
7124
  .option('--plan-from <path>', 'JSON file with the full FE test definition — projectId, type, name, planSteps[] all live in the file ' +
5855
7125
  '(≤ 256 KB; mutually exclusive with --code-file). In this mode --project/--type/--name/--description/--priority are ignored.')
7126
+ .option('--plan-template', 'print a minimal valid plan-file skeleton to stdout and exit (pure-local: no network, no credentials, ' +
7127
+ 'ignores every other flag). Pipe to a file and edit: `--plan-template > plan.json`.', false)
5856
7128
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
5857
7129
  .option('--wait', 'with --run, poll until terminal status', false)
5858
7130
  .option('--timeout <s>', 'with --run --wait, max seconds to wait')
@@ -5861,12 +7133,20 @@ export function createTestCommand(deps = {}) {
5861
7133
  .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering on `test rerun` and `test run --all`.', (val, prev) => [...(prev ?? []), val], [])
5862
7134
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Use to declare upstream producer dependencies.', (val, prev) => [...(prev ?? []), val], [])
5863
7135
  .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
7136
+ .addHelpText('after', PLAN_TEMPLATE_HELP_TEXT)
5864
7137
  .addHelpText('after', '\nBE dependency authoring (M4):\n' +
5865
7138
  ' --produces/--needs drive wave ordering on `test rerun` + `test run --all`.\n' +
5866
7139
  ' --category teardown marks a final-wave cleanup test.\n' +
5867
7140
  ' These flags are backend-only; supplying with --type frontend is an error (exit 5).')
5868
7141
  .addHelpText('after', GLOBAL_OPTS_HINT)
5869
7142
  .action(async (cmdOpts, command) => {
7143
+ // Pure-local, no network/credentials, no other flag is
7144
+ // consulted. Checked first so `--plan-template` never trips the
7145
+ // --plan-from/--code-file mutual-exclusivity guard below.
7146
+ if (cmdOpts.planTemplate === true) {
7147
+ runPlanTemplate(resolveCommonOptions(command), deps);
7148
+ return;
7149
+ }
5870
7150
  // --plan-from and --code-file are mutually exclusive. Dispatch
5871
7151
  // here so each `run*` function stays single-purpose. If neither
5872
7152
  // is set, the existing runCreate path enforces --code-file.
@@ -5986,6 +7266,18 @@ export function createTestCommand(deps = {}) {
5986
7266
  force: cmdOpts.force === true,
5987
7267
  }, deps);
5988
7268
  });
7269
+ test
7270
+ .command('open <test-id>')
7271
+ .description('Open the test in the TestSprite dashboard: prints the deep-link URL, then spawns your default browser unless --no-browser.')
7272
+ .option('--no-browser', 'print the URL only (SSH, headless, CI, agents)')
7273
+ .addHelpText('after', GLOBAL_OPTS_HINT)
7274
+ .action(async (testId, cmdOpts, command) => {
7275
+ await runOpen({
7276
+ ...resolveCommonOptions(command),
7277
+ testId,
7278
+ noBrowser: cmdOpts.browser === false,
7279
+ }, deps);
7280
+ });
5989
7281
  test
5990
7282
  .command('steps <test-id>')
5991
7283
  .description('List the steps for a test (server returns the cumulative log across every run; use --run-id to scope to one run)')
@@ -6042,6 +7334,10 @@ export function createTestCommand(deps = {}) {
6042
7334
  .option('--since <dur>', 'with --history: lower bound on createdAt — 24h, 7d, or ISO timestamp (client-side translated)')
6043
7335
  .option('--page-size <n>', 'with --history: number of runs per page (1–100, default 20)')
6044
7336
  .option('--cursor <token>', 'with --history: opaque cursor from a prior page')
7337
+ .option('--rerun', 'with --history: show only reruns')
7338
+ .option('--no-rerun', 'with --history: show only fresh (non-rerun) runs')
7339
+ .option('--columns <list>', 'with --history: select/reorder text table columns')
7340
+ .option('--no-header', 'with --history: suppress the text table header row')
6045
7341
  .addHelpText('after', GLOBAL_OPTS_HINT)
6046
7342
  .action(async (testId, cmdOpts, command) => {
6047
7343
  if (cmdOpts.history) {
@@ -6055,6 +7351,9 @@ export function createTestCommand(deps = {}) {
6055
7351
  ? parseNumericFlag(cmdOpts.pageSize, 'page-size')
6056
7352
  : undefined,
6057
7353
  cursor: cmdOpts.cursor,
7354
+ rerun: cmdOpts.rerun,
7355
+ columns: cmdOpts.columns,
7356
+ noHeader: cmdOpts.header === false,
6058
7357
  }, deps);
6059
7358
  }
6060
7359
  else {
@@ -6072,6 +7371,9 @@ export function createTestCommand(deps = {}) {
6072
7371
  .option('--name <name>', 'new human-readable test name')
6073
7372
  .option('--description <text>', 'new human description (≤ 2000 chars)')
6074
7373
  .option('--priority <prio>', 'new priority — one of: p0, p1, p2, p3')
7374
+ .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering.', (val, prev) => [...(prev ?? []), val], [])
7375
+ .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Declares an upstream producer dependency.', (val, prev) => [...(prev ?? []), val], [])
7376
+ .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
6075
7377
  .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
7378
  .addHelpText('after', GLOBAL_OPTS_HINT)
6077
7379
  .action(async (testId, cmdOpts, command) => {
@@ -6081,6 +7383,9 @@ export function createTestCommand(deps = {}) {
6081
7383
  name: cmdOpts.name,
6082
7384
  description: cmdOpts.description,
6083
7385
  priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
7386
+ produces: cmdOpts.produces,
7387
+ needs: cmdOpts.needs,
7388
+ category: cmdOpts.category,
6084
7389
  idempotencyKey: cmdOpts.idempotencyKey,
6085
7390
  }, deps);
6086
7391
  });
@@ -6140,25 +7445,32 @@ export function createTestCommand(deps = {}) {
6140
7445
  ' 4 test not found\n' +
6141
7446
  ' 5 validation error (e.g., bad --target-url, or positional + --all both set)\n' +
6142
7447
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
6143
- ' 7 timeout — resume with: testsprite test wait <run-id>\n' +
7448
+ ' 7 timeout — resume with: testsprite test wait <run-id>, ' +
7449
+ 'or stop it with: testsprite test cancel <run-id>\n' +
6144
7450
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
6145
7451
  ' 11 rate limited — honor Retry-After\n' +
6146
- '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>')
7452
+ '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
7453
+ '\nCtrl-C during --wait detaches only (the run keeps executing and billing);\n' +
7454
+ 'stop it for real with: testsprite test cancel <run-id>')
6147
7455
  .option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private IPs)')
6148
7456
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
6149
7457
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6150
7458
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
6151
- .option('--all', 'run all tests in the project (wave-ordered fresh run; requires --project). Mutually exclusive with <test-id>.', false)
6152
- .option('--project <id>', 'project id (required with --all; returned by `testsprite project list`)')
7459
+ .option('--all', 'run all tests in the project (wave-ordered fresh run; uses --project or TESTSPRITE_PROJECT_ID). Mutually exclusive with <test-id>.', false)
7460
+ .option('--project <id>', 'project id (with --all, overrides TESTSPRITE_PROJECT_ID; returned by `testsprite project list`)')
6153
7461
  .option('--filter <substr>', 'with --all: only run tests whose name contains this substring (case-insensitive)')
6154
7462
  .option('--max-concurrency <n>', `with --all --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
6155
7463
  .option('--report <format>', 'with --all --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
6156
7464
  .option('--report-file <path>', 'output path for --report (atomic write)')
6157
7465
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
7466
+ .option('--gh-output', 'with --all --wait: emit GitHub-native output (::error:: annotations per non-passed run; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
7467
+ .option('--summary-file <path>', 'with --all --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
6158
7468
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
6159
- ' testsprite test run --all --project <id> run all project tests in wave order\n' +
6160
- ' testsprite test run --all --project <id> --filter <substr> name-glob subset\n' +
6161
- ' testsprite test run --all --project <id> --wait --report junit --report-file ./results.xml\n' +
7469
+ ' testsprite test run --all --project <id> run all project tests in wave order\n' +
7470
+ ' TESTSPRITE_PROJECT_ID=<id> testsprite test run --all use env default project\n' +
7471
+ ' testsprite test run --all --filter <substr> name-glob subset (uses --project/env)\n' +
7472
+ ' testsprite test run --all --wait --report junit --report-file ./results.xml\n' +
7473
+ ' project id precedence: --project wins over TESTSPRITE_PROJECT_ID\n' +
6162
7474
  '\nBE tests can declare --produces/--needs at create time to drive wave ordering\n' +
6163
7475
  '(see `testsprite test create --help` for details).\n' +
6164
7476
  '\nFrontend tests: the current unified engine runs FE tests too (they are billed\n' +
@@ -6172,13 +7484,13 @@ export function createTestCommand(deps = {}) {
6172
7484
  throw localValidationError('test-id', 'positional <test-id> and --all are mutually exclusive; use one or the other');
6173
7485
  }
6174
7486
  if (testIdArg === undefined && !isAll) {
6175
- throw localValidationError('test-id', 'provide a <test-id>, or use --all --project <id> to run all tests in a project');
7487
+ throw localValidationError('test-id', 'provide a <test-id>, or use --all with --project <id> or TESTSPRITE_PROJECT_ID');
6176
7488
  }
6177
7489
  // --filter is an --all-only narrowing flag (mirrors `test rerun --filter`).
6178
7490
  // Without --all it would be SILENTLY ignored while the explicit <test-id>
6179
7491
  // still runs — defeating the caller's narrowing intent. Reject early.
6180
7492
  if (cmdOpts.filter !== undefined && cmdOpts.filter !== '' && !isAll) {
6181
- throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests run). Remove --filter, or add --all --project <id>.');
7493
+ throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests run). Remove --filter, or add --all with --project <id> or TESTSPRITE_PROJECT_ID.');
6182
7494
  }
6183
7495
  const report = parseJUnitReportFormat(cmdOpts.report);
6184
7496
  assertJUnitReportOptions({
@@ -6188,23 +7500,32 @@ export function createTestCommand(deps = {}) {
6188
7500
  wait: cmdOpts.wait === true,
6189
7501
  batchPath: isAll,
6190
7502
  });
7503
+ // --gh-output / --summary-file reduce the terminal batch envelope, which
7504
+ // only exists on the --all --wait path (without --wait the command returns
7505
+ // after enqueueing). Anywhere else they would silently no-op — reject
7506
+ // loudly (same rule as --filter and the JUnit report flags).
7507
+ if (cmdOpts.ghOutput === true && (!isAll || cmdOpts.wait !== true)) {
7508
+ throw localValidationError('gh-output', '--gh-output only applies with --all --wait (it reduces the terminal batch envelope). Remove --gh-output, or add --all --wait.');
7509
+ }
7510
+ if (cmdOpts.summaryFile !== undefined && (!isAll || cmdOpts.wait !== true)) {
7511
+ throw localValidationError('summary-file', '--summary-file only applies with --all --wait (it reduces the terminal batch envelope). Remove --summary-file, or add --all --wait.');
7512
+ }
6191
7513
  if (isAll) {
6192
7514
  // --all path: wave-ordered fresh batch run.
6193
- if (!cmdOpts.project) {
6194
- throw localValidationError('project', '--all requires a project id — pass --project <id>');
6195
- }
7515
+ const projectId = resolveProjectId(cmdOpts.project, deps);
7516
+ requireProjectId(projectId, '--all requires a project id - pass --project <id> or set TESTSPRITE_PROJECT_ID');
6196
7517
  // --target-url has no effect on the --all batch path: a BE test's base
6197
7518
  // URL is baked into its code, and the unified engine resolves each
6198
7519
  // project's configured environment server-side (per-run URL overrides
6199
7520
  // are not applied to batch FE runs either). Silently dropping it could
6200
- // run the suite against an unintended environment in the caller's mind
6201
- // — reject loudly instead.
7521
+ // run the suite against an unintended environment in the caller's mind,
7522
+ // so reject loudly.
6202
7523
  if (cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
6203
7524
  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.');
6204
7525
  }
6205
7526
  await runTestRunAll({
6206
7527
  ...resolveCommonOptions(command),
6207
- projectId: cmdOpts.project,
7528
+ projectId,
6208
7529
  nameFilter: cmdOpts.filter,
6209
7530
  wait: cmdOpts.wait === true,
6210
7531
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
@@ -6214,6 +7535,8 @@ export function createTestCommand(deps = {}) {
6214
7535
  report,
6215
7536
  reportFile: cmdOpts.reportFile,
6216
7537
  reportSuiteName: cmdOpts.reportSuiteName,
7538
+ ghOutput: cmdOpts.ghOutput === true,
7539
+ summaryFile: cmdOpts.summaryFile,
6217
7540
  }, deps);
6218
7541
  return;
6219
7542
  }
@@ -6244,7 +7567,14 @@ export function createTestCommand(deps = {}) {
6244
7567
  ' is recorded as error:<CODE> in its row and folded into exit 7)\n' +
6245
7568
  ' 7 timeout or per-member poll error — resume with: testsprite test wait <run-id...>\n' +
6246
7569
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
6247
- '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>')
7570
+ ' 11 rate limited, and nothing else went wrong — polls are retried\n' +
7571
+ ' automatically honoring Retry-After first, so this means the throttle\n' +
7572
+ ' outlasted that budget while the runs were still fine. Back off, then\n' +
7573
+ ' re-attach with test wait. (A throttle that instead consumes the whole\n' +
7574
+ ' --timeout reports 7, and any real timeout or failure keeps 7 / 1.)\n' +
7575
+ '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
7576
+ '\nCtrl-C detaches only (the run keeps executing and billing); stop it for\n' +
7577
+ 'real with: testsprite test cancel <run-id...>')
6248
7578
  .option('--timeout <s>', `max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6249
7579
  .option('--max-concurrency <n>', 'with several run-ids, max concurrent polls (1-100, default: 10)')
6250
7580
  .addHelpText('after', GLOBAL_OPTS_HINT)
@@ -6275,7 +7605,8 @@ export function createTestCommand(deps = {}) {
6275
7605
  // -------------------------------------------------------------------------
6276
7606
  test
6277
7607
  .command('rerun [test-ids...]')
6278
- .description('Re-execute a test (or multiple) as a cheap replay — FE replays the saved script (no credit), BE re-runs the dependency closure.\n' +
7608
+ .description('Re-execute a test (or multiple) as a replay — FE replays the saved script, BE re-runs the dependency closure. ' +
7609
+ 'Billed the same as a fresh run: 0.5 credits per FE rerun / 0.2 credits per BE rerun (legacy V2 accounts: FE rerun remains free).\n' +
6279
7610
  '\nExit codes:\n' +
6280
7611
  ' 0 passed (or queued without --wait)\n' +
6281
7612
  ' 1 failed / blocked / cancelled\n' +
@@ -6283,9 +7614,12 @@ export function createTestCommand(deps = {}) {
6283
7614
  ' 4 test not found\n' +
6284
7615
  ' 5 validation error\n' +
6285
7616
  ' 6 conflict (already running — see nextAction for the active runId)\n' +
6286
- ' 7 timeout or deferred — resume with: testsprite test wait <run-id>\n' +
7617
+ ' 7 timeout or deferred — resume with: testsprite test wait <run-id>, ' +
7618
+ 'or stop it with: testsprite test cancel <run-id>\n' +
6287
7619
  ' 11 rate limited — honor Retry-After\n' +
6288
- '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>')
7620
+ '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
7621
+ '\nCtrl-C during --wait detaches only (the run keeps executing and billing);\n' +
7622
+ 'stop it for real with: testsprite test cancel <run-id>')
6289
7623
  .option('--all', 'rerun all tests in the resolved project (requires --project)', false)
6290
7624
  .option('--project <id>', 'project id (required with --all; returned by `testsprite project list`)')
6291
7625
  .option('--skip-terminal', 'with --all: skip tests already in a terminal status (passed|failed|blocked|cancelled)', false)
@@ -6307,7 +7641,9 @@ export function createTestCommand(deps = {}) {
6307
7641
  ' • Under --wait the per-request HTTP timeout is auto-raised to cover --timeout so a\n' +
6308
7642
  ' slow trigger/poll under load is not cut at the 120s default (see --request-timeout).\n' +
6309
7643
  ' • Batch --wait: rate-deferred tests appear in `deferred[]` and `summary.deferred`,\n' +
6310
- ' and force a non-zero exit — they are NOT counted in `summary.total` (dispatched only).')
7644
+ ' and force a non-zero exit — they are NOT counted in `summary.total` (dispatched only).\n' +
7645
+ ' • On V3-routed accounts, --no-auto-heal is still rolling out and may not yet be\n' +
7646
+ ' honored server-side — check `auth status` for your routing.')
6311
7647
  .addHelpText('after', '\nDry-run shape notes:\n' +
6312
7648
  ' • --dry-run shows the BE rerun wire shape (includes `closure{}`); FE rerun responses\n' +
6313
7649
  ' omit `closure` (or return it as null) since there is no dependency expansion.\n' +
@@ -6367,8 +7703,11 @@ export function createTestCommand(deps = {}) {
6367
7703
  .option('--until-fail', 'stop at the first non-passing attempt (fast "is it flaky at all?" check)', false)
6368
7704
  .option('--timeout <s>', `per-attempt max seconds to wait (1-${MAX_RUN_TIMEOUT_SECONDS}, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6369
7705
  .addHelpText('after', '\nNotes:\n' +
6370
- ' • Frontend replays are free verbatim script replays (no credit); backend replays\n' +
6371
- ' re-run the dependency closure and may cost credits — a one-line advisory is printed.\n' +
7706
+ ' • Each replay is billed as a rerun — 0.5 credits for a frontend replay (verbatim\n' +
7707
+ ' script), 0.2 credits for a backend replay (re-runs the dependency closure) —\n' +
7708
+ ' same price as a fresh run, so `--runs N` costs roughly N×0.5 credits for a\n' +
7709
+ ' frontend test (legacy V2 accounts: FE rerun remains free). A one-line advisory\n' +
7710
+ ' is printed before a backend replay.\n' +
6372
7711
  ' • Replays use auto-heal OFF so a flaky test is not silently "healed" into a pass;\n' +
6373
7712
  ' this measures replay stability of the saved script against the configured URL.\n' +
6374
7713
  ' • `--output json` emits a machine-readable stability report for CI gating.')
@@ -6386,22 +7725,36 @@ export function createTestCommand(deps = {}) {
6386
7725
  test.addCommand(createTestPlanCommand(deps));
6387
7726
  test.addCommand(createTestFailureCommand(deps));
6388
7727
  test.addCommand(createTestArtifactCommand(deps));
7728
+ test.addCommand(createTestCancelCommand(deps));
6389
7729
  return test;
6390
7730
  }
6391
7731
  // ---------------------------------------------------------------------------
6392
7732
  // `test flaky` — repeat-run flaky-test detector
6393
7733
  // ---------------------------------------------------------------------------
6394
- /** Upper bound on `--runs` so a repeat-runner can't amplify free FE replays. */
7734
+ /** Upper bound on `--runs` so a repeat-runner can't rack up unbounded rerun charges. */
6395
7735
  const MAX_FLAKY_RUNS = 10;
6396
7736
  /** Default replay count when `--runs` is omitted. */
6397
7737
  const DEFAULT_FLAKY_RUNS = 5;
7738
+ function isFlakyFatalTriggerError(err) {
7739
+ if (!(err instanceof ApiError))
7740
+ return false;
7741
+ switch (err.code) {
7742
+ case 'AUTH_REQUIRED':
7743
+ case 'AUTH_INVALID':
7744
+ case 'AUTH_FORBIDDEN':
7745
+ return true;
7746
+ default:
7747
+ return false;
7748
+ }
7749
+ }
6398
7750
  /**
6399
7751
  * `test flaky <test-id>` — replay a test N times and report a stability score.
6400
7752
  *
6401
7753
  * Each attempt is a `POST /tests/{id}/runs/rerun` with auto-heal OFF (a strict
6402
- * verbatim replay) followed by `pollRunUntilTerminal`. Frontend replays are
6403
- * free verbatim script replays; backend replays re-run the dependency closure
6404
- * (a one-line credit advisory is printed). The pure scoring lives in
7754
+ * verbatim replay) followed by `pollRunUntilTerminal`. Each replay is billed
7755
+ * as a rerun (0.5 credits FE / 0.2 credits BE, same as a fresh run; legacy V2
7756
+ * accounts: FE rerun remains free) — a one-line credit advisory is printed
7757
+ * for backend tests. The pure scoring lives in
6405
7758
  * `lib/flaky.ts`; this function is the I/O orchestrator.
6406
7759
  *
6407
7760
  * Exit code: 0 when every observed attempt passed (stable), else 1 — so CI can
@@ -6444,17 +7797,25 @@ export async function runFlaky(opts, deps = {}) {
6444
7797
  }
6445
7798
  if (isBackend) {
6446
7799
  stderrFn(`[advisory] ${opts.testId} is a backend test — each replay re-runs its dependency closure ` +
6447
- `and may cost credits. Frontend replays are free verbatim script replays; backend replays are not.`);
7800
+ `and is billed at 0.2 credits per rerun, same as a fresh run (frontend reruns are 0.5 credits).`);
6448
7801
  }
6449
7802
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
6450
7803
  const attempts = [];
7804
+ // Collected across attempts and deduped — same request shape every
7805
+ // attempt, so the server would otherwise repeat the identical advisory once
7806
+ // per replay. Surfaced ONCE in the final report/summary, not N times.
7807
+ let advisories = [];
6451
7808
  for (let i = 1; i <= opts.runs; i++) {
6452
7809
  const idempotencyKey = `cli-flaky-${randomUUID()}`;
6453
7810
  let rerunResp;
6454
7811
  try {
6455
7812
  // auto-heal is intentionally OFF: flaky detection needs a strict verbatim
6456
- // replay so healed drift cannot mask a nondeterministic pass/fail.
6457
- rerunResp = await client.triggerRerun(opts.testId, { source: 'cli' }, { idempotencyKey });
7813
+ // replay so healed drift cannot mask a nondeterministic pass/fail. Sent
7814
+ // explicitly (not omitted) — an absent field defaults to heal-on server-side.
7815
+ rerunResp = await client.triggerRerun(opts.testId, { source: 'cli', autoHeal: false }, { idempotencyKey });
7816
+ if (rerunResp.advisories && rerunResp.advisories.length > 0) {
7817
+ advisories = dedupeRerunAdvisories(advisories.concat(rerunResp.advisories));
7818
+ }
6458
7819
  }
6459
7820
  catch (err) {
6460
7821
  // A missing replayable run is fatal for the whole command (mirror rerun):
@@ -6470,6 +7831,9 @@ export async function runFlaky(opts, deps = {}) {
6470
7831
  },
6471
7832
  });
6472
7833
  }
7834
+ if (isFlakyFatalTriggerError(err)) {
7835
+ throw err;
7836
+ }
6473
7837
  // Any other trigger error is recorded as an errored attempt so a single
6474
7838
  // transient blip doesn't abort a long stability probe.
6475
7839
  const code = err instanceof ApiError ? err.code : 'ERROR';
@@ -6493,6 +7857,7 @@ export async function runFlaky(opts, deps = {}) {
6493
7857
  const finalRun = await pollRunUntilTerminal(client, runId, {
6494
7858
  timeoutSeconds: opts.timeoutSeconds,
6495
7859
  sleep: deps.sleep,
7860
+ shutdown: shutdownOf(deps),
6496
7861
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6497
7862
  resolveAlternate,
6498
7863
  });
@@ -6500,6 +7865,23 @@ export async function runFlaky(opts, deps = {}) {
6500
7865
  failureKind = finalRun.failureKind;
6501
7866
  }
6502
7867
  catch (err) {
7868
+ // Graceful detach (DEV-331): clean up the ticker line, name the run
7869
+ // still executing server-side, and let index.ts exit 128+signum.
7870
+ if (err instanceof InterruptError) {
7871
+ ticker.finalize(`Attempt ${i}/${opts.runs} — interrupted (${err.signal})`);
7872
+ stderrFn(interruptDetachMessage(err, [runId]));
7873
+ throw err;
7874
+ }
7875
+ // RATE_LIMITED during polling (same defect class as the InterruptError
7876
+ // branch above): the HTTP layer already retried and gave up, but this
7877
+ // attempt's run keeps executing (and billing) server-side. Name it on
7878
+ // stderr before rethrowing so the runId is never silently dropped;
7879
+ // rethrow the SAME ApiError unchanged so its exit code (11) is kept.
7880
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
7881
+ ticker.finalize(`Attempt ${i}/${opts.runs} — rate limited by the server`);
7882
+ stderrFn(rateLimitedDetachMessage(err, [runId]));
7883
+ throw err;
7884
+ }
6503
7885
  // A per-attempt deadline (poll TimeoutError) or a client-side request
6504
7886
  // timeout both count as a non-passing "timeout" outcome for this attempt.
6505
7887
  if (err instanceof TimeoutError || err instanceof RequestTimeoutError) {
@@ -6516,7 +7898,10 @@ export async function runFlaky(opts, deps = {}) {
6516
7898
  break;
6517
7899
  }
6518
7900
  ticker.finalize();
6519
- const report = summarizeFlaky(opts.testId, attempts);
7901
+ // Print the deduped advisory set once for the whole probe, not
7902
+ // once per replay attempt (mirrors the `test rerun` advisory rendering).
7903
+ emitRerunAdvisories(stderrFn, advisories);
7904
+ const report = summarizeFlaky(opts.testId, attempts, advisories);
6520
7905
  out.print(report, data => renderFlakyText(data));
6521
7906
  const exitCode = flakyExitCode(report);
6522
7907
  if (exitCode !== 0) {
@@ -6524,9 +7909,17 @@ export async function runFlaky(opts, deps = {}) {
6524
7909
  }
6525
7910
  return report;
6526
7911
  }
6527
- function requireProjectId(projectId) {
7912
+ function resolveProjectId(projectId, deps) {
7913
+ const explicit = projectId?.trim();
7914
+ if (explicit && explicit.length > 0)
7915
+ return explicit;
7916
+ const envValue = (deps.env ?? process.env).TESTSPRITE_PROJECT_ID;
7917
+ const trimmed = envValue?.trim();
7918
+ return trimmed && trimmed.length > 0 ? trimmed : undefined;
7919
+ }
7920
+ function requireProjectId(projectId, message = 'is required; pass --project <id> or set TESTSPRITE_PROJECT_ID') {
6528
7921
  if (typeof projectId !== 'string' || projectId.length === 0) {
6529
- throw localValidationError('project', 'is required');
7922
+ throw localValidationError('project', message);
6530
7923
  }
6531
7924
  }
6532
7925
  /**
@@ -6606,6 +7999,7 @@ function makeClient(opts, deps) {
6606
7999
  credentialsPath: deps.credentialsPath,
6607
8000
  fetchImpl: deps.fetchImpl,
6608
8001
  stderr: deps.stderr,
8002
+ shutdownSignal: shutdownOf(deps).signal,
6609
8003
  });
6610
8004
  }
6611
8005
  function makeOutput(mode, deps) {
@@ -6825,38 +8219,32 @@ async function streamPresignedBody(url, out, deps) {
6825
8219
  throw new TransportError(`Failed mid-download of presigned code body: ${message}`);
6826
8220
  }
6827
8221
  }
6828
- function renderTestListText(page) {
8222
+ const TEST_LIST_COLUMNS = [
8223
+ {
8224
+ header: 'ID',
8225
+ width: rows => Math.max(2, ...rows.map(test => test.id.length)),
8226
+ render: test => test.id,
8227
+ },
8228
+ {
8229
+ header: 'NAME',
8230
+ width: rows => Math.max(4, ...rows.map(test => test.name.length)),
8231
+ render: test => test.name,
8232
+ },
8233
+ { header: 'TYPE', width: 8, render: test => test.type },
8234
+ { header: 'FROM', width: 6, render: test => test.createdFrom },
8235
+ { header: 'STATUS', width: 9, render: test => test.status },
8236
+ { header: 'UPDATED', width: 0, render: test => test.updatedAt },
8237
+ ];
8238
+ function renderTestListText(page, options = {}) {
6829
8239
  if (page.items.length === 0) {
6830
8240
  return page.nextToken ? `No tests on this page.\nnextToken: ${page.nextToken}` : 'No tests.';
6831
8241
  }
6832
- const idWidth = Math.max(2, ...page.items.map(t => t.id.length));
6833
- const nameWidth = Math.max(4, ...page.items.map(t => t.name.length));
6834
- const typeWidth = 8;
6835
- const fromWidth = 6;
6836
- const statusWidth = 9;
6837
- const header = pad('ID', idWidth) +
6838
- ' ' +
6839
- pad('NAME', nameWidth) +
6840
- ' ' +
6841
- pad('TYPE', typeWidth) +
6842
- ' ' +
6843
- pad('FROM', fromWidth) +
6844
- ' ' +
6845
- pad('STATUS', statusWidth) +
6846
- ' ' +
6847
- 'UPDATED';
6848
- const rows = page.items.map(t => pad(t.id, idWidth) +
6849
- ' ' +
6850
- pad(t.name, nameWidth) +
6851
- ' ' +
6852
- pad(t.type, typeWidth) +
6853
- ' ' +
6854
- pad(t.createdFrom, fromWidth) +
6855
- ' ' +
6856
- pad(t.status, statusWidth) +
6857
- ' ' +
6858
- t.updatedAt);
6859
- const lines = [header, ...rows];
8242
+ const lines = [
8243
+ renderTextTable(page.items, TEST_LIST_COLUMNS, {
8244
+ columns: options.columns,
8245
+ noHeader: options.noHeader,
8246
+ }),
8247
+ ];
6860
8248
  if (page.nextToken)
6861
8249
  lines.push('', `nextToken: ${page.nextToken}`);
6862
8250
  return lines.join('\n');
@@ -6888,6 +8276,16 @@ function renderTestText(t) {
6888
8276
  if (typeof t.planStepCount === 'number') {
6889
8277
  lines.push(`planSteps: ${t.planStepCount}`);
6890
8278
  }
8279
+ // Surface backend dependency declarations when present.
8280
+ if (Array.isArray(t.produces) && t.produces.length > 0) {
8281
+ lines.push(`produces: ${t.produces.join(', ')}`);
8282
+ }
8283
+ if (Array.isArray(t.consumes) && t.consumes.length > 0) {
8284
+ lines.push(`consumes: ${t.consumes.join(', ')}`);
8285
+ }
8286
+ if (t.category) {
8287
+ lines.push(`category: ${t.category}`);
8288
+ }
6891
8289
  lines.push(`createdAt: ${t.createdAt}`, `updatedAt: ${t.updatedAt}`);
6892
8290
  return lines.join('\n');
6893
8291
  }
@@ -7018,6 +8416,10 @@ function renderFailureContextText(ctx) {
7018
8416
  }
7019
8417
  if (ctx.result.videoUrl !== null)
7020
8418
  lines.push(`videoUrl: ${ctx.result.videoUrl}`);
8419
+ // backend stdout + traceback (prefer the failure block, falling
8420
+ // back to the embedded result; identical values). Bounded tail; full content
8421
+ // in --output json / the written failure.json.
8422
+ appendBackendArtifactLines(lines, ctx.failure.apiOutput ?? ctx.result.apiOutput, ctx.failure.trace ?? ctx.result.trace);
7021
8423
  return lines.join('\n');
7022
8424
  }
7023
8425
  function renderBundleWrittenText(data) {
@@ -7041,7 +8443,7 @@ function plannedBundleFiles(ctx, failedOnly) {
7041
8443
  files.push('failure.json');
7042
8444
  files.push(`code.${pickCodeExtension(ctx.code.language, ctx.code.framework)}`);
7043
8445
  if (ctx.result.videoUrl)
7044
- files.push('video.mp4');
8446
+ files.push(`video.${pickVideoExtension(ctx.result.videoUrl)}`);
7045
8447
  const stepsToInclude = failedOnly
7046
8448
  ? ctx.steps.filter(s => {
7047
8449
  if (ctx.result.failedStepIndex === null)
@@ -7137,6 +8539,9 @@ function renderResultText(r) {
7137
8539
  lines.push(`videoUrl: ${r.videoUrl}`);
7138
8540
  if (r.failureAnalysisUrl !== null)
7139
8541
  lines.push(`failureAnalysisUrl: ${r.failureAnalysisUrl}`);
8542
+ // backend stdout + traceback (null/absent for FE, passed, and
8543
+ // older backends). Full content always available via `--output json`.
8544
+ appendBackendArtifactLines(lines, r.apiOutput, r.trace);
7140
8545
  if (r.analysis !== undefined) {
7141
8546
  // §6.5.1 (M2.1 piece 3) — render the inline analysis block under
7142
8547
  // the result summary. Only fires when the caller passed
@@ -7159,6 +8564,33 @@ function renderResultText(r) {
7159
8564
  * level null. Non-null wrappers render `kind=...` plus an optional
7160
8565
  * reference and indented rationale.
7161
8566
  */
8567
+ /**
8568
+ * Render backend-test stdout + traceback in text mode. Shared by
8569
+ * `renderResultText` and `renderFailureContextText`. Both are bounded to a
8570
+ * tail (last {@link BACKEND_ARTIFACT_TAIL_LINES} lines) so a large stdout can't
8571
+ * flood the terminal; the full, untruncated content is always in the
8572
+ * `--output json` envelope. No-op when both are null/absent (FE / passed /
8573
+ * older backends), so non-backend output stays byte-identical.
8574
+ */
8575
+ const BACKEND_ARTIFACT_TAIL_LINES = 20;
8576
+ function appendArtifactTail(lines, label, value) {
8577
+ if (value == null || value === '')
8578
+ return;
8579
+ const allLines = value.replace(/\n+$/, '').split('\n');
8580
+ const dropped = Math.max(0, allLines.length - BACKEND_ARTIFACT_TAIL_LINES);
8581
+ const tail = dropped > 0 ? allLines.slice(-BACKEND_ARTIFACT_TAIL_LINES) : allLines;
8582
+ const bytes = Buffer.byteLength(value, 'utf8');
8583
+ lines.push('');
8584
+ lines.push(`${label} (${bytes} bytes${dropped > 0 ? `, showing last ${tail.length} lines` : ''}):`);
8585
+ for (const l of tail)
8586
+ lines.push(` ${l}`);
8587
+ if (dropped > 0)
8588
+ lines.push(` … ${dropped} earlier line(s) omitted — full content in --output json`);
8589
+ }
8590
+ function appendBackendArtifactLines(lines, apiOutput, trace) {
8591
+ appendArtifactTail(lines, 'stdout', apiOutput);
8592
+ appendArtifactTail(lines, 'trace', trace);
8593
+ }
7162
8594
  function appendFixTargetLines(lines, fix, label) {
7163
8595
  if (fix === null) {
7164
8596
  lines.push(`${label}— (analysis pipeline did not propose one)`);