@testsprite/testsprite-cli 0.6.0 → 0.8.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 (96) hide show
  1. package/README.md +52 -31
  2. package/dist/commands/agent.js +91 -45
  3. package/dist/commands/ci.d.ts +88 -0
  4. package/dist/commands/ci.js +429 -0
  5. package/dist/commands/doctor.d.ts +1 -1
  6. package/dist/commands/doctor.js +104 -8
  7. package/dist/commands/init.js +8 -0
  8. package/dist/commands/project.d.ts +78 -0
  9. package/dist/commands/project.js +429 -5
  10. package/dist/commands/schedule.d.ts +120 -0
  11. package/dist/commands/schedule.js +487 -0
  12. package/dist/commands/test.d.ts +176 -2
  13. package/dist/commands/test.js +2235 -609
  14. package/dist/commands/testlist.d.ts +88 -0
  15. package/dist/commands/testlist.js +753 -0
  16. package/dist/commands/tunnel.d.ts +72 -0
  17. package/dist/commands/tunnel.js +367 -0
  18. package/dist/index.js +113 -40
  19. package/dist/lib/agent-targets.d.ts +13 -4
  20. package/dist/lib/agent-targets.js +11 -2
  21. package/dist/lib/conflict-reason.d.ts +30 -0
  22. package/dist/lib/conflict-reason.js +45 -0
  23. package/dist/lib/credentials.js +42 -1
  24. package/dist/lib/cron.d.ts +40 -0
  25. package/dist/lib/cron.js +190 -0
  26. package/dist/lib/dry-run/samples.d.ts +9 -0
  27. package/dist/lib/dry-run/samples.js +293 -55
  28. package/dist/lib/errors.d.ts +9 -0
  29. package/dist/lib/errors.js +11 -0
  30. package/dist/lib/gh-output.d.ts +33 -1
  31. package/dist/lib/gh-output.js +97 -27
  32. package/dist/lib/http.d.ts +119 -0
  33. package/dist/lib/http.js +243 -2
  34. package/dist/lib/interrupt.d.ts +38 -13
  35. package/dist/lib/interrupt.js +130 -15
  36. package/dist/lib/junit-report.d.ts +20 -2
  37. package/dist/lib/junit-report.js +38 -5
  38. package/dist/lib/local-target.d.ts +95 -0
  39. package/dist/lib/local-target.js +184 -0
  40. package/dist/lib/plan-poll.d.ts +171 -0
  41. package/dist/lib/plan-poll.js +442 -0
  42. package/dist/lib/plans.types.d.ts +130 -0
  43. package/dist/lib/plans.types.js +31 -0
  44. package/dist/lib/poll-support.d.ts +26 -0
  45. package/dist/lib/poll-support.js +65 -0
  46. package/dist/lib/poll.d.ts +1 -0
  47. package/dist/lib/poll.js +2 -40
  48. package/dist/lib/proxy.d.ts +16 -0
  49. package/dist/lib/proxy.js +19 -1
  50. package/dist/lib/response-schemas.d.ts +20 -0
  51. package/dist/lib/response-schemas.js +55 -1
  52. package/dist/lib/run-progress.d.ts +41 -0
  53. package/dist/lib/run-progress.js +56 -0
  54. package/dist/lib/runs.types.d.ts +32 -3
  55. package/dist/lib/secret-file.d.ts +15 -0
  56. package/dist/lib/secret-file.js +82 -0
  57. package/dist/lib/target-url-preflight.d.ts +91 -0
  58. package/dist/lib/target-url-preflight.js +259 -0
  59. package/dist/lib/target-url.d.ts +63 -9
  60. package/dist/lib/target-url.js +283 -62
  61. package/dist/lib/telemetry.d.ts +11 -0
  62. package/dist/lib/telemetry.js +1 -0
  63. package/dist/lib/testlist.types.d.ts +77 -0
  64. package/dist/lib/testlist.types.js +9 -0
  65. package/dist/lib/ticker.d.ts +8 -0
  66. package/dist/lib/ticker.js +3 -0
  67. package/dist/lib/tunnel-session.d.ts +129 -0
  68. package/dist/lib/tunnel-session.js +232 -0
  69. package/dist/lib/tunnel.types.d.ts +54 -0
  70. package/dist/lib/tunnel.types.js +8 -0
  71. package/dist/lib/v3-advisory.d.ts +35 -22
  72. package/dist/lib/v3-advisory.js +44 -24
  73. package/dist/lib/wait-exit.d.ts +29 -0
  74. package/dist/lib/wait-exit.js +103 -0
  75. package/dist/vendor/tunnel-client/client.d.ts +83 -0
  76. package/dist/vendor/tunnel-client/client.js +871 -0
  77. package/dist/vendor/tunnel-client/config.d.ts +41 -0
  78. package/dist/vendor/tunnel-client/config.js +42 -0
  79. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  80. package/dist/vendor/tunnel-client/index.js +9 -0
  81. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  82. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  83. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  84. package/dist/vendor/tunnel-client/protocol.js +143 -0
  85. package/dist/vendor/tunnel-client/types.d.ts +96 -0
  86. package/dist/vendor/tunnel-client/types.js +10 -0
  87. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  88. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  89. package/dist/version-guard.d.ts +10 -7
  90. package/dist/version-guard.js +37 -9
  91. package/dist/version.d.ts +1 -1
  92. package/dist/version.js +1 -1
  93. package/package.json +2 -1
  94. package/skills/testsprite-onboard.skill.md +60 -4
  95. package/skills/testsprite-verify.codex.md +22 -16
  96. package/skills/testsprite-verify.skill.md +27 -18
@@ -1,29 +1,38 @@
1
- import { appendFileSync, createWriteStream, existsSync, readFileSync, readdirSync, statSync, writeFileSync, } from 'node:fs';
1
+ import { createWriteStream, existsSync, readFileSync, readdirSync, statSync, } from 'node:fs';
2
2
  import { rename, stat, unlink } from 'node:fs/promises';
3
3
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { Command } from 'commander';
6
6
  import { openInBrowser } from '../lib/browser.js';
7
- import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
7
+ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
8
8
  import { assertContextIntegrity, buildMeta, pickCodeExtension, pickVideoExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
9
- import { findSample, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
10
- import { assertJUnitReportOptions, buildJUnitReport, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
11
- import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
9
+ import { findSample, findSampleOrThrow, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
10
+ import { assertJUnitReportOptions, buildJUnitReport, durationSecondsBetween, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
11
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, isAuthCode, localValidationError, } from '../lib/errors.js';
12
12
  import { globalShutdown } from '../lib/interrupt.js';
13
13
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
14
14
  import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.js';
15
15
  import { VERSION } from '../version.js';
16
16
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
17
17
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
18
- import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
18
+ import { isTerminalStatus, pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
19
+ import { PlanGenerationTimeoutError, runGenerationLadder } from '../lib/plan-poll.js';
20
+ import { resolveWaitFailure } from '../lib/wait-exit.js';
19
21
  import { RUN_SOURCES } from '../lib/runs.types.js';
22
+ import { summarizeConflicts } from '../lib/conflict-reason.js';
23
+ import { isProxyAgentActive } from '../lib/proxy.js';
20
24
  import { assertNotLocal } from '../lib/target-url.js';
25
+ import { assertTargetUrlReachable } from '../lib/target-url-preflight.js';
26
+ import { assertLocalPortListening, buildLocalTargetUrl, DEFAULT_LOCAL_HOST, LOOPBACK_HOSTS, normalizeLocalHost, parseLocalPort, } from '../lib/local-target.js';
27
+ import { openTunnelSession, TunnelLostError, } from '../lib/tunnel-session.js';
28
+ import { TunnelClient } from '../vendor/tunnel-client/index.js';
21
29
  import { formatTextTableRow, measureTextColumns, renderTextTable, resolveTextColumns, } from '../lib/text-table.js';
30
+ import { createLiveRunProgress, formatRunProgressLine } from '../lib/run-progress.js';
22
31
  import { createTicker } from '../lib/ticker.js';
23
32
  import { RateThrottle } from '../lib/rate-throttle.js';
24
33
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
25
- import { emitTargetUrlV3Advisory } from '../lib/v3-advisory.js';
26
- import { emitGithubOutputs, summarizeAcceptedPayload, summarizeSingleRun, } from '../lib/gh-output.js';
34
+ import { emitTargetUrlMismatchAdvisory } from '../lib/v3-advisory.js';
35
+ import { emitCiArtifacts, summarizeAcceptedPayload, summarizeSingleRun, } from '../lib/gh-output.js';
27
36
  import { loadConfig } from '../lib/config.js';
28
37
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
29
38
  /** The effective shutdown handle for a command invocation (DEV-331). */
@@ -65,6 +74,143 @@ function rateLimitedDetachMessage(err, runIds) {
65
74
  ` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
66
75
  ` Cancel with: testsprite test cancel ${runIds.join(' ')}`);
67
76
  }
77
+ /**
78
+ * The same honest "keeps running (and billing)" subject sentence
79
+ * `interruptDetachMessage`/`rateLimitedDetachMessage` already use, for the
80
+ * two detach paths that build their own text inline instead of going
81
+ * through one of those two helpers: a plain `--timeout` expiry
82
+ * (`TimeoutError`) and a client-side `RequestTimeoutError`. Both used to
83
+ * omit "(and billing)" — the honesty gap this closes — even though a
84
+ * `--timeout` expiry is the single most common of the four detach reasons
85
+ * in practice. Kept as a standalone string helper (not a shared code path
86
+ * for all four branches) deliberately: the four branches differ in how
87
+ * they render the partial envelope and in their exit code, and unifying
88
+ * that shape is out of scope here — see the PR notes.
89
+ */
90
+ function stillRunningAndBillingSubject(runIds) {
91
+ const ids = Array.isArray(runIds) ? runIds : [runIds];
92
+ return ids.length === 1
93
+ ? `Run ${ids[0]} is still executing on the server and will keep running (and billing) until it finishes.`
94
+ : `${ids.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
95
+ }
96
+ /**
97
+ * Stop a tunnel run that can no longer succeed.
98
+ *
99
+ * Called on every path where this process stops waiting while the run is
100
+ * non-terminal. Unlike an ordinary run — where DEV-331 deliberately decided a
101
+ * Ctrl-C detaches and leaves the run to finish — a tunnel run's target lives
102
+ * behind a tunnel this process is holding open, so the moment we exit the
103
+ * Lambda's browser starts getting connection failures. Leaving it running
104
+ * bills the user for a guaranteed failure, which is exactly the case
105
+ * `--cancel-on-interrupt` was scoped for.
106
+ *
107
+ * The cancel is issued through a DETACHED client: the normal one composes the
108
+ * process shutdown signal into every fetch, and on the interrupt path that
109
+ * signal has already fired, so the request would abort before leaving the
110
+ * machine.
111
+ */
112
+ async function cancelDoomedTunnelRun(args) {
113
+ if (!args.enabled)
114
+ return { outcome: 'skipped' };
115
+ try {
116
+ await withTeardownDeadline(args.opts, args.deps, client => client.post(`/runs/${encodeURIComponent(args.runId)}/cancel`));
117
+ return { outcome: 'cancelled' };
118
+ }
119
+ catch (err) {
120
+ // 409 = already terminal. Not a failure: the requested end state holds.
121
+ if (err instanceof ApiError && err.code === 'CONFLICT') {
122
+ const terminalStatus = err.getDetail('status', (value) => typeof value === 'string' && isTerminalStatus(value));
123
+ return {
124
+ outcome: 'already-terminal',
125
+ ...(terminalStatus !== undefined ? { terminalStatus } : {}),
126
+ };
127
+ }
128
+ return { outcome: 'failed' };
129
+ }
130
+ }
131
+ /**
132
+ * The stderr line for a tunnel run whose wait is ending.
133
+ *
134
+ * Deliberately NOT built from `stillRunningAndBillingSubject`: that sentence
135
+ * is true for an ordinary run and false here, and the whole point of D1 (a)
136
+ * is that the four detach paths stop telling a tunnel user something untrue.
137
+ */
138
+ function tunnelDetachMessage(detach) {
139
+ const { runId, reason, cancel } = detach;
140
+ const cause = {
141
+ interrupt: 'Interrupted',
142
+ timeout: `Timed out waiting for run ${runId}`,
143
+ 'request-timeout': 'Request timed out',
144
+ 'rate-limited': 'Rate limited by the server (HTTP 429)',
145
+ 'tunnel-lost': 'The tunnel was disconnected by the tunnel service',
146
+ 'poll-error': 'Polling stopped because the run status could not be read',
147
+ };
148
+ const doom = reason === 'tunnel-lost'
149
+ ? `Run ${runId} was reaching your machine through that tunnel, and the run's proxy credential ` +
150
+ `names the client that just went away, so it cannot be restored for this run.`
151
+ : `Run ${runId} was reaching your machine through a tunnel that closes with this process, so ` +
152
+ `it cannot finish.`;
153
+ const outcome = {
154
+ cancelled: ' Cancelled it, so no further credits are spent on a guaranteed failure.',
155
+ 'already-terminal': ' It had already finished server-side; there was nothing to cancel.',
156
+ failed: ` Could NOT cancel it from here — stop it with: testsprite test cancel ${runId}`,
157
+ skipped: ` Left it running (--no-cancel-on-interrupt); stop it with: testsprite test cancel ${runId}`,
158
+ };
159
+ return (`${cause[reason]}. ${doom}\n` +
160
+ `${outcome[cancel]}\n` +
161
+ ` Start it again with --local when you're ready; a retry mints a fresh tunnel.`);
162
+ }
163
+ /**
164
+ * The `hint` lines under a partial run envelope.
165
+ *
166
+ * For an ordinary run these point at `test wait` / `test cancel`, which is
167
+ * right: the run is still going. For a tunnel run `test wait` is actively
168
+ * misleading — re-attaching cannot revive a tunnel that closed with the
169
+ * process that owned it — so it is never offered.
170
+ */
171
+ function detachHintLines(runId, detach) {
172
+ if (detach === undefined) {
173
+ return [
174
+ `hint Re-attach with: testsprite test wait ${runId}`,
175
+ `hint Cancel with: testsprite test cancel ${runId}`,
176
+ ];
177
+ }
178
+ return detach.cancel === 'cancelled' || detach.cancel === 'already-terminal'
179
+ ? ['hint The tunnel closed with this process, so the run was stopped.']
180
+ : [`hint Stop the run with: testsprite test cancel ${runId}`];
181
+ }
182
+ /** Status to report in a partial envelope once a doomed tunnel run was stopped. */
183
+ function detachPartialStatus(detach) {
184
+ if (detach === undefined)
185
+ return 'running';
186
+ if (detach.cancel === 'cancelled')
187
+ return 'cancelled';
188
+ return detach.terminalStatus ?? 'running';
189
+ }
190
+ function tunnelInterruptNextAction(detach) {
191
+ if (detach.cancel === 'cancelled') {
192
+ return (`Run ${detach.runId} was cancelled and its tunnel was closed. ` +
193
+ 'Start it again with --local when you are ready.');
194
+ }
195
+ if (detach.cancel === 'already-terminal') {
196
+ return (`Run ${detach.runId} had already finished` +
197
+ (detach.terminalStatus ? ` with status ${detach.terminalStatus}` : '') +
198
+ '; its tunnel was closed. Start a new --local run if you need to test again.');
199
+ }
200
+ if (detach.cancel === 'skipped') {
201
+ return (`The tunnel for run ${detach.runId} was closed, but cancellation was disabled. ` +
202
+ `Stop the run with: testsprite test cancel ${detach.runId}; then start it again with --local.`);
203
+ }
204
+ return (`The tunnel for run ${detach.runId} was closed and automatic cancellation failed. ` +
205
+ `Stop the run with: testsprite test cancel ${detach.runId}; then start it again with --local.`);
206
+ }
207
+ function attachTunnelInterruptDetach(err, detach) {
208
+ err.tunnelDetach = {
209
+ runId: detach.runId,
210
+ cancel: detach.cancel,
211
+ nextAction: tunnelInterruptNextAction(detach),
212
+ };
213
+ }
68
214
  const TEST_TYPES = ['frontend', 'backend'];
69
215
  // 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
70
216
  // tests created via `testsprite test create`, so the `--created-from cli`
@@ -344,6 +490,9 @@ export async function runCreate(opts, deps = {}) {
344
490
  priority: opts.priority,
345
491
  code,
346
492
  };
493
+ if (opts.stepTimeoutMs !== undefined) {
494
+ body.stepTimeoutMs = opts.stepTimeoutMs;
495
+ }
347
496
  // M4 piece-2: thread BE dependency fields into the POST body.
348
497
  // Only include when non-empty so the wire stays clean for tests that
349
498
  // don't declare any dependencies (undefined is omitted by JSON.stringify).
@@ -369,6 +518,23 @@ export async function runCreate(opts, deps = {}) {
369
518
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
370
519
  stderrFn("[advisory] --target-url has no effect for backend tests (a backend test's base URL is defined inside its code).");
371
520
  }
521
+ // Pre-charge reachability preflight — deliberately BEFORE the
522
+ // create POST below (not after), so a doomed --target-url refuses before
523
+ // this leaves behind a created-but-never-run orphan test row (the same
524
+ // "fail before I/O" idiom `assertChainedRunKeyFits` above already applies
525
+ // to the run idempotency key). Only meaningful when it will actually
526
+ // reach a trigger: skipped for a known-backend test (the advisory just
527
+ // above already covers why --target-url is inert there) and skipped
528
+ // entirely under --dry-run (zero network calls). The delegated
529
+ // `runTestRun` call in the --run chain below sets `skipPreflight: true`
530
+ // so this exact URL is never probed twice.
531
+ if (opts.type !== 'backend' &&
532
+ opts.targetUrl !== undefined &&
533
+ opts.run === true &&
534
+ !opts.dryRun) {
535
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
536
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
537
+ }
372
538
  const client = makeClient(opts, deps);
373
539
  const out = makeOutput(opts.output, deps);
374
540
  // B3: best-effort duplicate-name advisory. Skip under --dry-run.
@@ -384,6 +550,9 @@ export async function runCreate(opts, deps = {}) {
384
550
  // tests) on stderr so they reach the agent without polluting stdout JSON.
385
551
  // Emitted before the --run early return so they always show.
386
552
  emitResponseWarnings(response.warnings, deps);
553
+ if (!opts.dryRun) {
554
+ emitStepTimeoutRunWarning(opts.stepTimeoutMs, deps);
555
+ }
387
556
  // --run chain (M3.3 piece-3). Per codex round-1 P1: suppress the
388
557
  // create's own print when chaining; `runTestRun` emits a single
389
558
  // merged envelope `{ ...createResponse, run: <trigger|final> }` so
@@ -434,6 +603,10 @@ export async function runCreate(opts, deps = {}) {
434
603
  // Thread the known type so fast BE runs (terminal on first poll, where
435
604
  // beFallbackUsed would be false) still render `steps: n/a (backend)`.
436
605
  type: opts.type,
606
+ // The preflight above (or its explicit --skip-preflight opt-out)
607
+ // already ran against this exact URL before the create POST — never
608
+ // probe it a second time here.
609
+ skipPreflight: true,
437
610
  }, deps);
438
611
  return response;
439
612
  }
@@ -571,6 +744,19 @@ function emitResponseWarnings(warnings, deps) {
571
744
  for (const w of warnings)
572
745
  stderrFn(`[warn] ${w}`);
573
746
  }
747
+ /**
748
+ * A per-step timeout can make the overall run exceed the CLI's independent
749
+ * client-side poll deadline. Keep the two timeout concepts explicit and make
750
+ * clear that detaching the client never cancels server-side execution.
751
+ */
752
+ function emitStepTimeoutRunWarning(stepTimeoutMs, deps) {
753
+ if (stepTimeoutMs === undefined)
754
+ return;
755
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
756
+ stderrFn(`[warn] Runs of this test may take longer with a ${stepTimeoutMs} ms per-step timeout. ` +
757
+ `\`test run --wait\` polls for up to ${DEFAULT_RUN_TIMEOUT_SECONDS}s by default; ` +
758
+ 'raise it with `--timeout <s>` if needed. A client-side timeout never stops the server-side run.');
759
+ }
574
760
  /**
575
761
  * piece-6 cap for the `PUT /tests/{id}/plan-steps` body. Distinct from
576
762
  * piece-5's `MAX_PLAN_BODY_BYTES` because the wire shape differs
@@ -843,8 +1029,11 @@ export async function runUpdate(opts, deps = {}) {
843
1029
  ...CLI_CREATE_PRIORITIES,
844
1030
  ]);
845
1031
  }
846
- // No-op rejection: requires at least one of the three patchable
847
- // fields. Caught before fetching credentials or building the
1032
+ if (opts.stepTimeoutMs !== undefined && opts.clearStepTimeout === true) {
1033
+ throw localValidationError('step-timeout', '--step-timeout and --clear-step-timeout are mutually exclusive');
1034
+ }
1035
+ // No-op rejection: requires at least one patchable field. Caught before
1036
+ // fetching credentials or building the
848
1037
  // request so the user gets the cheapest possible error.
849
1038
  const hasName = opts.name !== undefined;
850
1039
  const hasDescription = opts.description !== undefined;
@@ -852,8 +1041,26 @@ export async function runUpdate(opts, deps = {}) {
852
1041
  const hasProduces = opts.produces !== undefined && opts.produces.length > 0;
853
1042
  const hasNeeds = opts.needs !== undefined && opts.needs.length > 0;
854
1043
  const hasCategory = opts.category !== undefined;
855
- if (!hasName && !hasDescription && !hasPriority && !hasProduces && !hasNeeds && !hasCategory) {
856
- throw localValidationError('fields', 'at least one of --name / --description / --priority / --produces / --needs / --category must be set', ['name', 'description', 'priority', 'produces', 'needs', 'category']);
1044
+ const hasStepTimeout = opts.stepTimeoutMs !== undefined;
1045
+ const hasClearStepTimeout = opts.clearStepTimeout === true;
1046
+ if (!hasName &&
1047
+ !hasDescription &&
1048
+ !hasPriority &&
1049
+ !hasProduces &&
1050
+ !hasNeeds &&
1051
+ !hasCategory &&
1052
+ !hasStepTimeout &&
1053
+ !hasClearStepTimeout) {
1054
+ throw localValidationError('fields', 'at least one of --name / --description / --priority / --produces / --needs / --category / --step-timeout / --clear-step-timeout must be set', [
1055
+ 'name',
1056
+ 'description',
1057
+ 'priority',
1058
+ 'produces',
1059
+ 'needs',
1060
+ 'category',
1061
+ 'step-timeout',
1062
+ 'clear-step-timeout',
1063
+ ]);
857
1064
  }
858
1065
  const idempotencyKey = opts.idempotencyKey ?? `cli-update-${randomUUID()}`;
859
1066
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
@@ -878,12 +1085,19 @@ export async function runUpdate(opts, deps = {}) {
878
1085
  body.consumes = opts.needs;
879
1086
  if (hasCategory)
880
1087
  body.category = opts.category;
1088
+ if (hasStepTimeout)
1089
+ body.stepTimeoutMs = opts.stepTimeoutMs;
1090
+ if (hasClearStepTimeout)
1091
+ body.stepTimeoutMs = null;
881
1092
  const client = makeClient(opts, deps);
882
1093
  const out = makeOutput(opts.output, deps);
883
1094
  const response = await client.put(`/tests/${encodeURIComponent(opts.testId)}`, {
884
1095
  body,
885
1096
  headers: { 'idempotency-key': idempotencyKey },
886
1097
  });
1098
+ if (!opts.dryRun && hasStepTimeout) {
1099
+ emitStepTimeoutRunWarning(opts.stepTimeoutMs, deps);
1100
+ }
887
1101
  out.print(response, data => renderUpdateText(data));
888
1102
  return response;
889
1103
  }
@@ -1520,6 +1734,15 @@ export async function runCreateFromPlan(opts, deps = {}) {
1520
1734
  priority: plan.priority,
1521
1735
  planSteps: plan.planSteps,
1522
1736
  };
1737
+ // Pre-charge reachability preflight — before the create POST
1738
+ // (same "fail before I/O, not after an orphan row" placement as
1739
+ // runCreate). `plan.type` is unconditionally 'frontend' here (backend
1740
+ // plans already threw above), so no type gate is needed. The delegated
1741
+ // `runTestRun` call in the --run chain below sets `skipPreflight: true`
1742
+ // so this exact URL is never probed twice.
1743
+ if (opts.targetUrl !== undefined && opts.run === true && !opts.dryRun) {
1744
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
1745
+ }
1523
1746
  const client = makeClient(opts, deps);
1524
1747
  const out = makeOutput(opts.output, deps);
1525
1748
  // Fix 4: best-effort duplicate-name advisory — same semantics as runCreate.
@@ -1563,6 +1786,9 @@ export async function runCreateFromPlan(opts, deps = {}) {
1563
1786
  timeoutIsDefault: opts.timeoutIsDefault ?? false,
1564
1787
  wait: opts.wait === true,
1565
1788
  createContext: responseWithDashboardUrl,
1789
+ // Already preflighted above (or explicitly skipped) — don't probe
1790
+ // the same URL twice.
1791
+ skipPreflight: true,
1566
1792
  }, deps).then(() => response);
1567
1793
  }
1568
1794
  if (opts.output === 'json') {
@@ -2080,20 +2306,6 @@ testIdToDashboardState) {
2080
2306
  // All specs failed at create time — already threw above; unreachable.
2081
2307
  return;
2082
2308
  }
2083
- // Finding 2 (dogfood 2026-08-09): this fan-out calls `triggerRunWithMeta`
2084
- // directly (below), bypassing `runTestRun` entirely — so `runTestRun`'s own
2085
- // `--target-url` V3 advisory (`emitTargetUrlV3AdvisoryIfNeeded`) never fired
2086
- // here, even though every triggered run in the batch ignores `--target-url`
2087
- // exactly like a single V3-routed `test run` does. Reuses the same helper
2088
- // and advisory text (no duplicated probe logic or copy) and fires exactly
2089
- // ONCE for the whole batch, before the fan-out — not per item. Mirrors
2090
- // `runTestRun`'s own gating (only pay the extra `/me` round trip when
2091
- // `--target-url` was actually supplied) and its "fires under --dry-run too"
2092
- // behavior (the dry-run client's canned `/me` sample demonstrates the same
2093
- // advisory at zero real-network cost).
2094
- if (opts.targetUrl !== undefined) {
2095
- await emitTargetUrlV3AdvisoryIfNeeded(client, stderrFn);
2096
- }
2097
2309
  // Dry-run: print a descriptor envelope and return without real triggers.
2098
2310
  if (opts.dryRun) {
2099
2311
  const dryRunResults = testIds.map(testId => ({
@@ -2116,8 +2328,25 @@ testIdToDashboardState) {
2116
2328
  out.print(envelope);
2117
2329
  return;
2118
2330
  }
2331
+ // Pre-charge reachability preflight, ONCE for the whole batch
2332
+ // before the fan-out — not once per item (mirrors the "fire once per
2333
+ // invocation" contract Finding 2 already established for the target-url
2334
+ // advisory below). Real path only (dry-run already returned above); no
2335
+ // type gate is needed here — batch specs are FE-only by construction (a
2336
+ // `type: "backend"` spec always fails create-time server validation, so
2337
+ // it never reaches this fan-out at all — see the `beIndexes` warning in
2338
+ // `runCreateBatch`).
2339
+ if (opts.targetUrl !== undefined) {
2340
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
2341
+ }
2119
2342
  const batchRunResults = [];
2120
2343
  const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
2344
+ // Response-driven --target-url advisory, fired at most ONCE for the whole
2345
+ // batch (Finding 2's contract) the first time any member's trigger
2346
+ // response reports a target different from what was requested — see the
2347
+ // matching comment in `runTestRun` for why this replaced the old
2348
+ // `v3Enabled`-assumption probe.
2349
+ let targetUrlAdvisoryPrinted = false;
2121
2350
  /**
2122
2351
  * Client-side sliding-window throttle: caps outgoing triggers at
2123
2352
  * BATCH_RUN_RATE_LIMIT (50) per BATCH_RUN_RATE_WINDOW_MS (60 s), sitting
@@ -2222,6 +2451,16 @@ testIdToDashboardState) {
2222
2451
  // POSTs per spec (e.g. 50×3 = 150/min), blowing the server's 60/min cap.
2223
2452
  { idempotencyKey: runIdempotencyKey, retryOnRateLimit: false });
2224
2453
  triggerResponse = result.body;
2454
+ // Fire the response-driven mismatch advisory at most once for the
2455
+ // whole batch. Synchronous check-and-set (no `await` between the
2456
+ // two) so two members whose triggers resolve in the same tick
2457
+ // can't both slip past the flag and print twice.
2458
+ if (!targetUrlAdvisoryPrinted &&
2459
+ opts.targetUrl !== undefined &&
2460
+ triggerResponse.targetUrl !== opts.targetUrl) {
2461
+ targetUrlAdvisoryPrinted = true;
2462
+ emitTargetUrlMismatchAdvisory(stderrFn, opts.targetUrl, triggerResponse.targetUrl);
2463
+ }
2225
2464
  break; // success — exit the outer retry loop
2226
2465
  }
2227
2466
  catch (err) {
@@ -4037,7 +4276,7 @@ function isTerminalPublicStatus(status) {
4037
4276
  * only the verdict/result fields are taken from the test record (codex
4038
4277
  * round-2: don't fabricate blank correlation fields).
4039
4278
  */
4040
- function backendResultToRunResponse(result, run) {
4279
+ export function backendResultToRunResponse(result, run, testTitle) {
4041
4280
  // `result.summary` is now a semantic string, not a count object.
4042
4281
  // Reconstruct the synthetic 1-test stepSummary from the verdict (byte-identical
4043
4282
  // to the prior status-derived counts: passed→1/0, failed→0/1, else→0/0).
@@ -4047,6 +4286,12 @@ function backendResultToRunResponse(result, run) {
4047
4286
  return {
4048
4287
  ...run,
4049
4288
  status: result.status,
4289
+ // The backend only resolves `testTitle` on a TERMINAL run read; this fallback
4290
+ // synthesizes a terminal response from a NON-terminal poll (`run.testTitle` is
4291
+ // null there by contract), so overlay the name the type-probe already fetched
4292
+ // — zero extra request. `.trim() ||` matches the empty-title→id fallback the
4293
+ // summary/JUnit renderers use, so a blank name never renders an empty cell.
4294
+ testTitle: testTitle?.trim() ? testTitle : (run.testTitle ?? null),
4050
4295
  // Drop the polling hint — it's meaningless on a terminal response
4051
4296
  // (JSON.stringify omits undefined keys).
4052
4297
  retryAfterSeconds: undefined,
@@ -4109,8 +4354,13 @@ export function backendResultIsForThisRun(result, runId, notBefore) {
4109
4354
  * - Every lookup is best-effort: any error → "keep polling the run row", so
4110
4355
  * the fallback can never make either path worse than the prior timeout.
4111
4356
  */
4112
- function makeBackendWaitFallback(args) {
4357
+ export function makeBackendWaitFallback(args) {
4113
4358
  let detection = 'pending';
4359
+ // Cached alongside `detection` from the same one-time type-probe: the human
4360
+ // name, used to overlay `testTitle` onto the synthesized terminal response
4361
+ // (the backend never sends a title on the non-terminal poll this fallback
4362
+ // reads). Null until the probe succeeds, or if the test has no/blank name.
4363
+ let testName = null;
4114
4364
  return async (run, _elapsedMs, signal) => {
4115
4365
  const testId = args.resolveTestId(run);
4116
4366
  if (!testId)
@@ -4127,6 +4377,7 @@ function makeBackendWaitFallback(args) {
4127
4377
  // non-terminal tick retries; the FE path is unaffected because its run
4128
4378
  // row finalizes and `resolveAlternate` stops being called.
4129
4379
  detection = test.type === 'backend' ? 'backend' : 'frontend';
4380
+ testName = test.name?.trim() ? test.name : null;
4130
4381
  }
4131
4382
  catch {
4132
4383
  return null; // transient — keep polling the run row, retry the probe next tick.
@@ -4146,8 +4397,9 @@ function makeBackendWaitFallback(args) {
4146
4397
  }
4147
4398
  args.onResolved?.(testId, result.status);
4148
4399
  // Overlay the verdict onto the polled run row (preserves real correlation
4149
- // metadata; codex round-2).
4150
- return backendResultToRunResponse(result, run);
4400
+ // metadata; codex round-2) plus the probe-cached name so the CI title is
4401
+ // populated even on a run row that never finalizes on its own.
4402
+ return backendResultToRunResponse(result, run, testName);
4151
4403
  };
4152
4404
  }
4153
4405
  /**
@@ -4378,77 +4630,15 @@ function parseTimeoutFlag(raw, flagName) {
4378
4630
  }
4379
4631
  return n;
4380
4632
  }
4381
- /**
4382
- * Short deadline for the best-effort `v3Enabled` lookup behind the
4383
- * `--target-url` advisory (DEV-749). Mirrors `DUP_NAME_ADVISORY_TIMEOUT_MS`
4384
- * — a stalled `/me` must never meaningfully delay a run trigger.
4385
- */
4386
- const TARGET_URL_ADVISORY_TIMEOUT_MS = 5_000;
4387
- /**
4388
- * DEV-749 (client half): `--target-url` is silently dropped on the V3
4389
- * execution path — the backend validates it (SSRF guard, defence in depth)
4390
- * and then discards it, because V3 resolves the run's environment from
4391
- * `test_environment` at execution time; there is no injection point for a
4392
- * per-run override. This is a client-side advisory only — the real fix
4393
- * (an actual per-run override on V3) needs a product decision and is out
4394
- * of scope here.
4395
- *
4396
- * Gated on `v3Enabled`, the same authoritative per-user routing bit
4397
- * `auth status`/`doctor` already render (`GET /me`, `src/lib/v3-advisory.ts`).
4398
- * Best-effort: a single bounded lookup (mirrors `emitDupNameAdvisoryIfNeeded`'s
4399
- * `AbortController` + 5 s deadline), swallows every error, and must never
4400
- * block or fail the actual run trigger — a broken/slow `/me` degrades to
4401
- * "no advisory printed", not a failed `test run`.
4402
- */
4403
- /**
4404
- * `X-CLI-Command` tag for this probe's `GET /me` — same advisory-header
4405
- * mechanism `runInit` uses (`toAuthDeps`'s `commandTag: 'init'` in
4406
- * `commands/init.ts`, sent via `AuthDeps.commandTag` in `auth.ts`), reused
4407
- * directly here rather than invented fresh. The backend's CLI-audit
4408
- * allowlist (`KNOWN_CLI_COMMANDS` + `resolveCliEvent`'s `/me` branch) maps this
4409
- * exact string to `null` — no PostHog event at all, not `cli.session_started`
4410
- * and not `cli.initialized` (init's tag would be a MORE specific, and equally
4411
- * wrong, misattribution of a probe that is neither a session start nor an
4412
- * onboarding run).
4413
- *
4414
- * Forward-compatible by construction: an unlisted `X-CLI-Command` value is
4415
- * dropped by the backend before event selection (see
4416
- * `capturePostHogEvent`/`KNOWN_CLI_COMMANDS` in the interceptor above), so
4417
- * against a backend that predates this allowlist entry the header is a no-op
4418
- * and behavior is exactly what it was before this fix — the CLI can ship
4419
- * this independently of backend deploy order in either direction.
4420
- */
4421
- const TARGET_URL_ADVISORY_CLI_COMMAND = 'run-target-url-probe';
4422
- async function emitTargetUrlV3AdvisoryIfNeeded(client, stderrFn) {
4423
- const ac = new AbortController();
4424
- const timer = setTimeout(() => ac.abort(), TARGET_URL_ADVISORY_TIMEOUT_MS);
4425
- try {
4426
- const me = await client.get('/me', {
4427
- signal: ac.signal,
4428
- headers: { 'x-cli-command': TARGET_URL_ADVISORY_CLI_COMMAND },
4429
- // Finding 1 (dogfood 2026-08-09): `HttpClient.sleepBeforeRetry` (src/lib/http.ts)
4430
- // only observes the process-lifetime shutdown signal, never a per-request
4431
- // `options.signal` — the abort controller above bounds the FETCH itself but
4432
- // not a post-response retry sleep. A retryable 429 carrying a real
4433
- // `Retry-After` (e.g. 60s, a live `inflight_cap` response) would put this
4434
- // best-effort probe into a retry sleep this 5s deadline cannot interrupt,
4435
- // stalling the real run trigger behind it. `retryOnRateLimit: false` makes
4436
- // the HTTP layer throw on the first 429 instead of sleeping — the existing,
4437
- // already-used-elsewhere knob (see the batch-run trigger site above) rather
4438
- // than changing `sleepBeforeRetry` itself, which every other caller (e.g.
4439
- // the polling path) relies on to keep sleeping through a caller signal.
4440
- retryOnRateLimit: false,
4441
- });
4442
- if (me.v3Enabled === true) {
4443
- emitTargetUrlV3Advisory(stderrFn);
4444
- }
4445
- }
4446
- catch {
4447
- // Swallow — this is best-effort; must not block or fail the run trigger.
4448
- }
4449
- finally {
4450
- clearTimeout(timer);
4633
+ /** Validate the per-test timeout that the execution engine applies to every step. */
4634
+ function parseStepTimeoutFlag(raw, flagName) {
4635
+ if (raw === undefined)
4636
+ return undefined;
4637
+ const n = Number(raw);
4638
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 60_000) {
4639
+ throw localValidationError(flagName, 'must be an integer between 1 and 60000 milliseconds');
4451
4640
  }
4641
+ return n;
4452
4642
  }
4453
4643
  /**
4454
4644
  * `test run <test-id>` — M3.3 piece-3.
@@ -4460,18 +4650,29 @@ async function emitTargetUrlV3AdvisoryIfNeeded(client, stderrFn) {
4460
4650
  */
4461
4651
  export async function runTestRun(opts, deps = {}) {
4462
4652
  assertIdempotencyKey(opts.idempotencyKey);
4463
- if (opts.targetUrl !== undefined) {
4464
- assertNotLocal(opts.targetUrl);
4653
+ // --local resolution runs FIRST and touches nothing: every refusal below
4654
+ // must happen before a client is even constructed, because the guarantee
4655
+ // this feature sells is that a doomed `--local` run never gets a run row,
4656
+ // a credit spend, or a tunnel credential.
4657
+ const isTunnelRun = opts.localPort !== undefined;
4658
+ if (isTunnelRun && opts.targetUrl !== undefined) {
4659
+ throw localValidationError('local', '--local and --target-url are mutually exclusive: --local runs against your own machine ' +
4660
+ 'through a tunnel, --target-url runs against an address the test runner can already ' +
4661
+ 'reach. Pass one');
4662
+ }
4663
+ if (isTunnelRun && !opts.wait) {
4664
+ // The tunnel's lifetime IS this process's lifetime, so a no-wait tunnel
4665
+ // run dooms itself the instant the command returns. The command wiring
4666
+ // forces --wait; this covers a programmatic caller that did not.
4667
+ throw localValidationError('local', '--local runs cannot detach: the tunnel closes when this command exits, so the run would ' +
4668
+ 'fail. Remove --local, or let the command wait');
4465
4669
  }
4466
- // DEV-749: only spend the extra `/me` round trip when --target-url was
4467
- // actually supplied — the common case (no override) pays nothing. Fires
4468
- // in both the dry-run and real paths below (the dry-run `/me` sample sets
4469
- // `v3Enabled: true`, so `--dry-run --target-url` demonstrates the same
4470
- // advisory a real V3-routed caller would see, at zero real-network cost).
4471
4670
  if (opts.targetUrl !== undefined) {
4472
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4473
- await emitTargetUrlV3AdvisoryIfNeeded(makeClient(opts, deps), stderrFn);
4671
+ assertNotLocal(opts.targetUrl);
4474
4672
  }
4673
+ const localHost = opts.localHost ?? DEFAULT_LOCAL_HOST;
4674
+ const localTargetUrl = opts.localPort !== undefined ? buildLocalTargetUrl(localHost, opts.localPort) : undefined;
4675
+ const effectiveTargetUrl = localTargetUrl ?? opts.targetUrl;
4475
4676
  if (opts.dryRun) {
4476
4677
  const client = makeClient(opts, deps);
4477
4678
  const out = makeOutput(opts.output, deps);
@@ -4494,8 +4695,22 @@ export async function runTestRun(opts, deps = {}) {
4494
4695
  const envelope = {
4495
4696
  method: 'POST',
4496
4697
  path: `/api/cli/v1/tests/${opts.testId}/runs`,
4497
- body: { source: 'cli', ...(opts.targetUrl ? { targetUrl: opts.targetUrl } : {}) },
4698
+ body: {
4699
+ source: 'cli',
4700
+ ...(effectiveTargetUrl ? { targetUrl: effectiveTargetUrl } : {}),
4701
+ // A dry run mints nothing, so there is no real client id to show —
4702
+ // and inventing a UUID-shaped one would read as a live credential
4703
+ // handle, the same reason `dashboardUrl` is suppressed under
4704
+ // --dry-run rather than pointing at the canned sample id.
4705
+ ...(isTunnelRun ? { tunnelClientId: '<minted at run time>' } : {}),
4706
+ },
4498
4707
  idempotencyKey,
4708
+ ...(isTunnelRun
4709
+ ? {
4710
+ precededBy: 'POST /api/cli/v1/tunnel',
4711
+ followedBy: 'DELETE /api/cli/v1/tunnel/<client-id>',
4712
+ }
4713
+ : {}),
4499
4714
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
4500
4715
  };
4501
4716
  printRunOrChain(out, envelope, opts.createContext);
@@ -4510,347 +4725,560 @@ export async function runTestRun(opts, deps = {}) {
4510
4725
  }
4511
4726
  // D4: under --wait, raise the per-request timeout to cover --timeout so a
4512
4727
  // slow trigger/long-poll under load isn't falsely cut at the 120s default.
4513
- const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
4728
+ const requestTimeoutMs = resolveWaitRequestTimeoutMs(opts);
4729
+ const clientOpts = { ...opts, requestTimeoutMs };
4730
+ const client = makeClient(clientOpts, deps);
4731
+ const tunnelRequestTimeoutMs = isTunnelRun
4732
+ ? resolveRequestTimeoutMs(clientOpts, deps.env ?? process.env)
4733
+ : undefined;
4514
4734
  const out = makeOutput(opts.output, deps);
4515
4735
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4516
- let triggerResponse;
4517
- let triggerRequestId;
4518
- let resumedFromConflict = false;
4736
+ const shutdown = shutdownOf(deps);
4737
+ // Pre-charge reachability preflight — real path only (dry-run
4738
+ // makes zero network calls by convention), after `assertNotLocal` and
4739
+ // before the trigger POST so a doomed run never gets a run row or charge.
4740
+ // `opts.skipPreflight` is threaded straight to a zero-network no-op; a
4741
+ // delegating caller (`runCreate`/`runCreateFromPlan` chaining `--run`)
4742
+ // already ran this exact check against the same URL before its own
4743
+ // create POST and sets `skipPreflight: true` here to avoid probing twice.
4744
+ if (isTunnelRun) {
4745
+ // The tunnel-run equivalent of the --target-url probe, and the reason
4746
+ // DEV-868 exists: a dev server that is not running is the single most
4747
+ // likely `--local` mistake, and this is the last moment it costs nothing.
4748
+ // Unlike the --target-url probe this one is conclusive — the dial it
4749
+ // performs is the same raw loopback connect the tunnel client will make
4750
+ // from this same process — so it refuses rather than advises.
4751
+ await assertLocalPortListening(localHost, opts.localPort, { skipPreflight: opts.skipPreflight }, stderrFn);
4752
+ if (isProxyAgentActive()) {
4753
+ stderrFn('[advisory] An HTTP proxy is configured for this process. The tunnel control channel ' +
4754
+ 'honours it, but the tunnel data plane is a raw TCP connection that does not — if the ' +
4755
+ 'run cannot reach your machine, an egress proxy is the first thing to rule out.');
4756
+ }
4757
+ }
4758
+ else if (opts.targetUrl !== undefined) {
4759
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
4760
+ }
4761
+ // Nothing above this line has spent money or minted a credential. Everything
4762
+ // below it must be unwound on every exit path, which is what the `finally`
4763
+ // at the end of this function is for.
4764
+ let tunnelSession;
4765
+ // Arm before minting and keep the scope armed until close/delete finishes.
4766
+ // The nested poll arm is intentionally re-entrant; when it disarms, this
4767
+ // outer lifecycle scope still protects cancellation and binding teardown.
4768
+ const disarmTunnelLifecycle = isTunnelRun ? shutdown.arm() : undefined;
4519
4769
  try {
4520
- const result = await client.triggerRunWithMeta(opts.testId, { source: 'cli', ...(opts.targetUrl ? { targetUrl: opts.targetUrl } : {}) }, { idempotencyKey });
4521
- triggerResponse = result.body;
4522
- triggerRequestId = result.requestId;
4523
- }
4524
- catch (err) {
4525
- // CONFLICT (409) can arise from two different causes:
4526
- // 1. reason === 'run_in_flight' — another run is currently executing for
4527
- // this test. Auto-resume polling is valid ONLY for this reason and ONLY
4528
- // when --wait is set. Any other reason (snapshot_in_flight, etc.) or
4529
- // IDEMPOTENCY_BODY_MISMATCH must propagate to exit 6 so callers can
4530
- // decide what to do.
4531
- // 2. reason !== 'run_in_flight' — snapshot mid-mutation or body-hash
4532
- // mismatch. Always propagate.
4533
- if (opts.wait && err instanceof ApiError && err.code === 'CONFLICT') {
4534
- const conflictReason = err.getDetail('reason', (v) => typeof v === 'string' && v.length > 0);
4535
- const currentRunId = err.getDetail('currentRunId', (v) => typeof v === 'string' && v.length > 0);
4536
- // Only the genuine "another run currently executing" race qualifies for
4537
- // auto-resume. Other CONFLICT reasons (snapshot_in_flight, etc.) exit 6.
4538
- if (conflictReason === 'run_in_flight' && currentRunId !== undefined) {
4539
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4540
- // If the caller supplied --target-url, verify the in-flight run targets
4541
- // the same URL. A mismatch means we would be reporting a different
4542
- // environment's results as if our requested environment was tested.
4543
- if (opts.targetUrl !== undefined) {
4544
- const inFlightRun = await client.getRun(currentRunId);
4545
- if (inFlightRun.targetUrl !== opts.targetUrl) {
4546
- throw new ApiError({
4547
- code: 'CONFLICT',
4548
- message: `Conflict: another run for this test is in flight against a different ` +
4549
- `target URL (${inFlightRun.targetUrl ?? 'not reported'}). Your --target-url ${opts.targetUrl} ` +
4550
- `cannot attach to that run. Wait for it to finish ` +
4551
- `(\`testsprite test wait ${currentRunId}\`) or retry your trigger when ` +
4552
- `the test is free.`,
4553
- nextAction: `testsprite test wait ${currentRunId}`,
4554
- requestId: err.requestId,
4555
- details: {
4556
- reason: 'run_in_flight',
4557
- currentRunId,
4558
- inFlightTargetUrl: inFlightRun.targetUrl,
4559
- requestedTargetUrl: opts.targetUrl,
4560
- },
4561
- });
4562
- }
4563
- stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}, ` +
4564
- `target: ${inFlightRun.targetUrl}). ` +
4565
- `Attaching to that run's --wait poll instead of creating a new one. ` +
4566
- `To stop it instead: testsprite test cancel ${currentRunId}`);
4567
- triggerResponse = {
4568
- runId: currentRunId,
4569
- status: 'queued',
4570
- enqueuedAt: new Date().toISOString(),
4571
- codeVersion: inFlightRun.codeVersion ?? '',
4572
- // The check above proved the in-flight run targets exactly this URL.
4573
- targetUrl: opts.targetUrl,
4574
- };
4770
+ if (isTunnelRun) {
4771
+ try {
4772
+ tunnelSession = await openTunnelSession({
4773
+ log: stderrFn,
4774
+ logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
4775
+ onFatal: () => {
4776
+ // Surfaced to the poll loop through `onTick` below; a remint cannot
4777
+ // rescue this run (see `lib/tunnel-session.ts`).
4778
+ },
4779
+ ...(opts.tunnelClientId !== undefined
4780
+ ? { adopt: { clientId: opts.tunnelClientId, expiresAt: '' } }
4781
+ : {}),
4782
+ }, {
4783
+ mint: async (ttlSeconds) => withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, mintClient => mintClient.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
4784
+ destroy: async (clientId) => deleteTunnelForCleanup(opts, deps, clientId),
4785
+ createClient: shutdownAwareTunnelClientFactory(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
4786
+ });
4787
+ }
4788
+ catch (err) {
4789
+ // `openTunnelSession` converts a client-start rejection to UNAVAILABLE
4790
+ // after it has stopped the client and deleted the binding. Restore the
4791
+ // initiating signal so the documented interrupt exit code is retained.
4792
+ if (shutdown.signal.aborted)
4793
+ throw shutdown.signal.reason;
4794
+ throw err;
4795
+ }
4796
+ if (!tunnelSession.adopted) {
4797
+ stderrFn(`[tunnel] Reaching ${localTargetUrl} through TestSprite (client ${tunnelSession.clientId}).`);
4798
+ }
4799
+ }
4800
+ let triggerResponse;
4801
+ let triggerRequestId;
4802
+ let resumedFromConflict = false;
4803
+ try {
4804
+ // A signal received before the POST begins is still free to stop here.
4805
+ // Once the request has begun, however, it must finish under its own
4806
+ // bounded deadline so we can learn the runId if the server charged it.
4807
+ if (isTunnelRun && shutdown.signal.aborted)
4808
+ throw shutdown.signal.reason;
4809
+ const triggerBody = {
4810
+ source: 'cli',
4811
+ ...(effectiveTargetUrl ? { targetUrl: effectiveTargetUrl } : {}),
4812
+ // The client ID only. The secret stays in this process and never
4813
+ // reaches a request body, an idempotency row, or an audit line.
4814
+ ...(tunnelSession ? { tunnelClientId: tunnelSession.clientId } : {}),
4815
+ };
4816
+ const result = isTunnelRun
4817
+ ? await withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, triggerClient => triggerClient.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey }))
4818
+ : await client.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey });
4819
+ triggerResponse = result.body;
4820
+ triggerRequestId = result.requestId;
4821
+ }
4822
+ catch (err) {
4823
+ // CONFLICT (409) can arise from two different causes:
4824
+ // 1. reason === 'run_in_flight' — another run is currently executing for
4825
+ // this test. Auto-resume polling is valid ONLY for this reason and ONLY
4826
+ // when --wait is set. Any other reason (snapshot_in_flight, etc.) or
4827
+ // IDEMPOTENCY_BODY_MISMATCH must propagate to exit 6 so callers can
4828
+ // decide what to do.
4829
+ // 2. reason !== 'run_in_flight' — snapshot mid-mutation or body-hash
4830
+ // mismatch. Always propagate.
4831
+ if (opts.wait && err instanceof ApiError && err.code === 'CONFLICT') {
4832
+ const conflictReason = err.getDetail('reason', (v) => typeof v === 'string' && v.length > 0);
4833
+ const currentRunId = err.getDetail('currentRunId', (v) => typeof v === 'string' && v.length > 0);
4834
+ // Auto-resume is wrong for a tunnel run: the in-flight run was
4835
+ // triggered without OUR client id, so it is not routed through this
4836
+ // tunnel and is testing something else entirely. Attaching to its poll
4837
+ // would report a different environment's verdict as if it were the
4838
+ // local one — the exact substitution `--local` exists to prevent.
4839
+ if (isTunnelRun) {
4840
+ throw err;
4575
4841
  }
4576
- else {
4577
- // D: No --target-url supplied — fetch the in-flight run so the
4578
- // synthesised triggerResponse.targetUrl is the REAL environment being
4579
- // tested, not an empty string that would propagate into the timeout
4580
- // partial (Finding D). Fall back to null (not '') if the lookup fails.
4581
- let inFlightTargetUrl = null;
4582
- let inFlightCodeVersion = '';
4583
- try {
4842
+ // Only the genuine "another run currently executing" race qualifies for
4843
+ // auto-resume. Other CONFLICT reasons (snapshot_in_flight, etc.) exit 6.
4844
+ if (conflictReason === 'run_in_flight' && currentRunId !== undefined) {
4845
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4846
+ // If the caller supplied --target-url, verify the in-flight run targets
4847
+ // the same URL. A mismatch means we would be reporting a different
4848
+ // environment's results as if our requested environment was tested.
4849
+ if (opts.targetUrl !== undefined) {
4584
4850
  const inFlightRun = await client.getRun(currentRunId);
4585
- inFlightTargetUrl = inFlightRun.targetUrl ?? null;
4586
- inFlightCodeVersion = inFlightRun.codeVersion ?? '';
4851
+ if (inFlightRun.targetUrl !== opts.targetUrl) {
4852
+ throw new ApiError({
4853
+ code: 'CONFLICT',
4854
+ message: `Conflict: another run for this test is in flight against a different ` +
4855
+ `target URL (${inFlightRun.targetUrl ?? 'not reported'}). Your --target-url ${opts.targetUrl} ` +
4856
+ `cannot attach to that run. Wait for it to finish ` +
4857
+ `(\`testsprite test wait ${currentRunId}\`) or retry your trigger when ` +
4858
+ `the test is free.`,
4859
+ nextAction: `testsprite test wait ${currentRunId}`,
4860
+ requestId: err.requestId,
4861
+ details: {
4862
+ reason: 'run_in_flight',
4863
+ currentRunId,
4864
+ inFlightTargetUrl: inFlightRun.targetUrl,
4865
+ requestedTargetUrl: opts.targetUrl,
4866
+ },
4867
+ });
4868
+ }
4869
+ stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}, ` +
4870
+ `target: ${inFlightRun.targetUrl}). ` +
4871
+ `Attaching to that run's --wait poll instead of creating a new one. ` +
4872
+ `To stop it instead: testsprite test cancel ${currentRunId}`);
4873
+ triggerResponse = {
4874
+ runId: currentRunId,
4875
+ status: 'queued',
4876
+ enqueuedAt: new Date().toISOString(),
4877
+ codeVersion: inFlightRun.codeVersion ?? '',
4878
+ // The check above proved the in-flight run targets exactly this URL.
4879
+ targetUrl: opts.targetUrl,
4880
+ };
4587
4881
  }
4588
- catch {
4589
- // Best-effort — if the lookup fails, proceed with null targetUrl.
4882
+ else {
4883
+ // D: No --target-url supplied — fetch the in-flight run so the
4884
+ // synthesised triggerResponse.targetUrl is the REAL environment being
4885
+ // tested, not an empty string that would propagate into the timeout
4886
+ // partial (Finding D). Fall back to null (not '') if the lookup fails.
4887
+ let inFlightTargetUrl = null;
4888
+ let inFlightCodeVersion = '';
4889
+ try {
4890
+ const inFlightRun = await client.getRun(currentRunId);
4891
+ inFlightTargetUrl = inFlightRun.targetUrl ?? null;
4892
+ inFlightCodeVersion = inFlightRun.codeVersion ?? '';
4893
+ }
4894
+ catch {
4895
+ // Best-effort — if the lookup fails, proceed with null targetUrl.
4896
+ }
4897
+ // Auto-resume but emit a stronger advisory so the caller is aware
4898
+ // they are attaching to the project default.
4899
+ // SIG-9 (DEV-331 final): the in-flight run is NOT auto-cancelled —
4900
+ // name the real `test cancel` command instead of the old (false)
4901
+ // "cancel with Ctrl-C" claim.
4902
+ stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
4903
+ (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
4904
+ `). Auto-resuming wait on in-flight run. ` +
4905
+ `If you needed a specific target URL, cancel it with ` +
4906
+ `testsprite test cancel ${currentRunId}, or re-trigger with ` +
4907
+ `--target-url after it finishes.`);
4908
+ triggerResponse = {
4909
+ runId: currentRunId,
4910
+ status: 'queued',
4911
+ enqueuedAt: new Date().toISOString(),
4912
+ codeVersion: inFlightCodeVersion,
4913
+ // Use the real targetUrl from the in-flight run (or null if unknown),
4914
+ // never '' — the timeout partial inherits this value.
4915
+ targetUrl: inFlightTargetUrl ?? '',
4916
+ };
4590
4917
  }
4591
- // Auto-resume but emit a stronger advisory so the caller is aware
4592
- // they are attaching to the project default.
4593
- // SIG-9 (DEV-331 final): the in-flight run is NOT auto-cancelled —
4594
- // name the real `test cancel` command instead of the old (false)
4595
- // "cancel with Ctrl-C" claim.
4596
- stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
4597
- (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
4598
- `). Auto-resuming wait on in-flight run. ` +
4599
- `If you needed a specific target URL, cancel it with ` +
4600
- `testsprite test cancel ${currentRunId}, or re-trigger with ` +
4601
- `--target-url after it finishes.`);
4602
- triggerResponse = {
4603
- runId: currentRunId,
4604
- status: 'queued',
4605
- enqueuedAt: new Date().toISOString(),
4606
- codeVersion: inFlightCodeVersion,
4607
- // Use the real targetUrl from the in-flight run (or null if unknown),
4608
- // never '' — the timeout partial inherits this value.
4609
- targetUrl: inFlightTargetUrl ?? '',
4610
- };
4918
+ resumedFromConflict = true;
4919
+ }
4920
+ else {
4921
+ throw err;
4611
4922
  }
4612
- resumedFromConflict = true;
4613
4923
  }
4614
4924
  else {
4615
4925
  throw err;
4616
4926
  }
4617
4927
  }
4618
- else {
4619
- throw err;
4928
+ // Response-driven, not assumption-driven: the backend is the ground
4929
+ // truth for whether --target-url was actually applied — V3
4930
+ // deliberately returns `targetUrl: ''` rather than echoing an override it
4931
+ // did not apply ("so the response doesn't claim a target we didn't use"),
4932
+ // while V2 echoes the real applied value. Comparing what we asked for
4933
+ // against what the trigger response reports self-corrects the day the
4934
+ // backend applies the override, with no `v3Enabled` assumption at all.
4935
+ // Skipped for a known-backend caller (`opts.type` threaded from the
4936
+ // `test create --run` chain): a backend trigger response's `targetUrl`
4937
+ // is an unconditional echo of the request body (verified against
4938
+ // backend-v2.0's `CliTestsController.createRun` — `targetUrl: body.targetUrl
4939
+ // ?? ''` on both the V2 and V3 backend branches), so it can never mismatch
4940
+ // and the existing, more specific C1 advisory ("--target-url has no effect
4941
+ // for backend tests") already covers this case at create time.
4942
+ if (effectiveTargetUrl !== undefined &&
4943
+ opts.type !== 'backend' &&
4944
+ triggerResponse.targetUrl !== effectiveTargetUrl) {
4945
+ emitTargetUrlMismatchAdvisory(stderrFn, effectiveTargetUrl, triggerResponse.targetUrl);
4620
4946
  }
4621
- }
4622
- if (!opts.wait) {
4623
- printRunOrChain(out, triggerResponse, opts.createContext, data => renderTriggerRunText(data));
4624
- if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
4625
- stderrFn(`requestId: ${triggerRequestId}`);
4626
- return triggerResponse;
4627
- }
4628
- // --wait path: poll until terminal.
4629
- const startMs = Date.now();
4630
- void resumedFromConflict; // used above; suppress unused-variable lint
4631
- const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
4632
- // B2(c): emit a one-time hint when the user did not explicitly set --timeout
4633
- // (i.e. the default is in effect). First runs can take several minutes;
4634
- // skipped when --output json (non-interactive consumers don't need the hint).
4635
- if (opts.timeoutIsDefault === true && opts.output !== 'json') {
4636
- stderrFn(`[hint] First runs can take several minutes; raise --timeout if this run is cut short.`);
4637
- }
4638
- // Backend-test fallback (dogfood L1888): BE run rows never finalize, so
4639
- // resolve the verdict from the testId record once it's terminal.
4640
- let beFallbackUsed = false;
4641
- const resolveAlternate = makeBackendWaitFallback({
4642
- client,
4643
- resolveTestId: () => opts.testId,
4644
- resolveNotBefore: () => triggerResponse.enqueuedAt,
4645
- onResolved: testId => {
4646
- beFallbackUsed = true;
4647
- stderrFn(`[advisory] Backend run-surface row is not finalized server-side (dogfood L1888); ` +
4648
- `resolved the verdict from the test record (testId=${testId}). ` +
4649
- `Read full detail with: testsprite test result ${testId}`);
4650
- },
4651
- });
4652
- let finalRun;
4653
- try {
4654
- finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
4655
- timeoutSeconds: opts.timeoutSeconds,
4656
- sleep: deps.sleep,
4657
- shutdown: shutdownOf(deps),
4658
- onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4659
- onTick: (run, elapsedMs) => {
4660
- const elapsed = Math.round(elapsedMs / 1000);
4661
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
4662
- ticker.update(`Run ${run.runId} — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
4947
+ if (!opts.wait) {
4948
+ printRunOrChain(out, triggerResponse, opts.createContext, data => renderTriggerRunText(data));
4949
+ if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
4950
+ stderrFn(`requestId: ${triggerRequestId}`);
4951
+ return triggerResponse;
4952
+ }
4953
+ // --wait path: poll until terminal.
4954
+ const startMs = Date.now();
4955
+ void resumedFromConflict; // used above; suppress unused-variable lint
4956
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
4957
+ // B2(c): emit a one-time hint when the user did not explicitly set --timeout
4958
+ // (i.e. the default is in effect). First runs can take several minutes;
4959
+ // skipped when --output json (non-interactive consumers don't need the hint).
4960
+ if (opts.timeoutIsDefault === true && opts.output !== 'json') {
4961
+ stderrFn(`[hint] First runs can take several minutes; raise --timeout if this run is cut short.`);
4962
+ }
4963
+ // Backend-test fallback (dogfood L1888): BE run rows never finalize, so
4964
+ // resolve the verdict from the testId record once it's terminal.
4965
+ let beFallbackUsed = false;
4966
+ const resolveAlternate = makeBackendWaitFallback({
4967
+ client,
4968
+ resolveTestId: () => opts.testId,
4969
+ resolveNotBefore: () => triggerResponse.enqueuedAt,
4970
+ onResolved: testId => {
4971
+ beFallbackUsed = true;
4972
+ stderrFn(`[advisory] Backend run-surface row is not finalized server-side (dogfood L1888); ` +
4973
+ `resolved the verdict from the test record (testId=${testId}). ` +
4974
+ `Read full detail with: testsprite test result ${testId}`);
4663
4975
  },
4664
- resolveAlternate,
4665
4976
  });
4666
- }
4667
- catch (err) {
4668
- if (err instanceof TimeoutError) {
4669
- ticker.finalize(`Run ${triggerResponse.runId} — timed out after ${opts.timeoutSeconds}s`);
4670
- // Mirror the RequestTimeoutError path: emit a partial run to stdout so
4671
- // JSON consumers and AI agents can grab the runId and chain into
4672
- // `testsprite test wait <runId>` without parsing the stderr error envelope.
4673
- const timeoutPartial = {
4674
- runId: triggerResponse.runId,
4675
- status: 'running',
4676
- enqueuedAt: triggerResponse.enqueuedAt,
4677
- codeVersion: triggerResponse.codeVersion,
4678
- targetUrl: triggerResponse.targetUrl || null,
4679
- };
4680
- printRunOrChain(out, timeoutPartial, opts.createContext, data => {
4681
- const p = data;
4682
- const lines = [
4683
- `runId ${p.runId}`,
4684
- `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
4685
- ];
4686
- if (p.targetUrl)
4687
- lines.push(`targetUrl ${p.targetUrl}`);
4688
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4689
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4690
- return lines.join('\n');
4691
- });
4692
- throw ApiError.fromEnvelope({
4693
- error: {
4694
- code: 'UNSUPPORTED', // exit 7 per errors.md
4695
- message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}.`,
4696
- nextAction: `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
4697
- requestId: 'local',
4698
- details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
4977
+ // Keeps the elapsed counter moving between long-poll returns (~25s apart).
4978
+ // Armed only when the ticker redraws in place (its own TTY / NO_COLOR call).
4979
+ const live = createLiveRunProgress(ticker);
4980
+ let finalRun;
4981
+ try {
4982
+ finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
4983
+ timeoutSeconds: opts.timeoutSeconds,
4984
+ sleep: deps.sleep,
4985
+ shutdown,
4986
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4987
+ onTick: (run, elapsedMs) => {
4988
+ // The tunnel is checked on every tick rather than through an abort
4989
+ // signal because there is nothing to race: once the control channel
4990
+ // is terminally closed the run is already doomed, and one long-poll
4991
+ // cycle of latency costs far less than plumbing a second abort
4992
+ // source through the shared poll loop for every ordinary run.
4993
+ if (!isTerminalStatus(run.status)) {
4994
+ const fatal = tunnelSession?.fatalReason();
4995
+ if (fatal !== undefined)
4996
+ throw new TunnelLostError(fatal, triggerResponse.runId);
4997
+ }
4998
+ live.onTick(run, elapsedMs);
4699
4999
  },
5000
+ resolveAlternate,
4700
5001
  });
4701
5002
  }
4702
- // C+D: RequestTimeoutError during polling — emit a partial object to stdout
4703
- // routed through printRunOrChain so:
4704
- // TEXT mode: renders human-readable (not raw JSON)
4705
- // JSON mode: preserves the merged create-chain envelope
4706
- // { ...createContext, run: { runId, status, targetUrl } }
4707
- // targetUrl is taken from triggerResponse, which is already bound to
4708
- // the real in-flight URL (see Finding D fix in the 409 resume path).
4709
- if (err instanceof RequestTimeoutError) {
4710
- ticker.finalize(`Run ${triggerResponse.runId} — request timed out`);
4711
- const partial = {
4712
- runId: triggerResponse.runId,
4713
- status: 'running',
4714
- enqueuedAt: triggerResponse.enqueuedAt,
4715
- codeVersion: triggerResponse.codeVersion,
4716
- targetUrl: triggerResponse.targetUrl || null,
4717
- };
4718
- printRunOrChain(out, partial, opts.createContext, data => {
4719
- const p = data;
4720
- const lines = [`runId ${p.runId}`, `status ${p.status} (request timed out)`];
4721
- if (p.targetUrl)
4722
- lines.push(`targetUrl ${p.targetUrl}`);
4723
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4724
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4725
- return lines.join('\n');
4726
- });
4727
- stderrFn(`Run ${triggerResponse.runId} is still in progress (request timed out). ` +
4728
- `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
4729
- throw err;
4730
- }
4731
- // RATE_LIMITED during polling — the backend's pre-auth rate limiter can
4732
- // trip on a shared egress IP (CI runner, NAT) and 429 an otherwise-valid
4733
- // key for its window; the HTTP layer already retried internally and gave
4734
- // up. The run was already triggered (and billed) and keeps executing
4735
- // server-side, so this must not be a silent, runId-less death: same
4736
- // partial-envelope contract as the RequestTimeoutError branch above, and
4737
- // the SAME thrown ApiError is rethrown unchanged so its native exit code
4738
- // (11) is preserved — never reclassified to 7.
4739
- if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
4740
- ticker.finalize(`Run ${triggerResponse.runId} — rate limited by the server`);
4741
- const partial = {
4742
- runId: triggerResponse.runId,
4743
- status: 'running',
4744
- enqueuedAt: triggerResponse.enqueuedAt,
4745
- codeVersion: triggerResponse.codeVersion,
4746
- targetUrl: triggerResponse.targetUrl || null,
4747
- };
4748
- printRunOrChain(out, partial, opts.createContext, data => {
4749
- const p = data;
4750
- const lines = [
4751
- `runId ${p.runId}`,
4752
- `status ${p.status} (rate limited by the server)`,
4753
- ];
4754
- if (p.targetUrl)
4755
- lines.push(`targetUrl ${p.targetUrl}`);
4756
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4757
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4758
- return lines.join('\n');
4759
- });
4760
- stderrFn(rateLimitedDetachMessage(err, [triggerResponse.runId]));
4761
- throw err;
4762
- }
4763
- // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
4764
- // envelope shape as the timeout paths so stdout stays parseable, plus the
4765
- // honest "keeps running and billing" stderr line. Rethrow → index.ts
4766
- // renders the INTERRUPTED envelope and exits 128+signum.
4767
- if (err instanceof InterruptError) {
4768
- ticker.finalize(`Run ${triggerResponse.runId} — interrupted (${err.signal})`);
4769
- const partial = {
4770
- runId: triggerResponse.runId,
4771
- status: 'running',
4772
- enqueuedAt: triggerResponse.enqueuedAt,
4773
- codeVersion: triggerResponse.codeVersion,
4774
- targetUrl: triggerResponse.targetUrl || null,
5003
+ catch (err) {
5004
+ // Stop redrawing BEFORE any final line below is written, so a stale
5005
+ // "running · Ns" can never land after "timed out" / "interrupted".
5006
+ live.stop();
5007
+ // A tunnel run that stops being waited on is a tunnel run that is about
5008
+ // to lose its tunnel, on ALL of these paths. `cancelOnInterrupt` defaults
5009
+ // ON here and only here — for an ordinary run, detaching leaves something
5010
+ // that can still pass, which is why DEV-331 deliberately did not cancel.
5011
+ const settleTunnelDetach = async (reason) => {
5012
+ if (tunnelSession === undefined || tunnelSession.adopted)
5013
+ return undefined;
5014
+ const cancel = await cancelDoomedTunnelRun({
5015
+ runId: triggerResponse.runId,
5016
+ enabled: opts.cancelOnInterrupt !== false,
5017
+ opts,
5018
+ deps,
5019
+ });
5020
+ return {
5021
+ runId: triggerResponse.runId,
5022
+ reason,
5023
+ cancel: cancel.outcome,
5024
+ ...(cancel.terminalStatus !== undefined ? { terminalStatus: cancel.terminalStatus } : {}),
5025
+ };
4775
5026
  };
4776
- printRunOrChain(out, partial, opts.createContext, data => {
4777
- const p = data;
4778
- const lines = [`runId ${p.runId}`, `status ${p.status} (interrupted)`];
4779
- if (p.targetUrl)
4780
- lines.push(`targetUrl ${p.targetUrl}`);
4781
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4782
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4783
- return lines.join('\n');
4784
- });
4785
- stderrFn(interruptDetachMessage(err, [triggerResponse.runId]));
4786
- throw err;
4787
- }
4788
- ticker.finalize();
4789
- throw err;
4790
- }
4791
- const elapsed = Math.round((Date.now() - startMs) / 1000);
4792
- const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
4793
- ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
4794
- // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs); on
4795
- // the standalone `test run <id>` path neither is set, so probe the test type
4796
- // once (text mode only, best-effort) — DEV-282.
4797
- const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
4798
- const finalRunWithUrl = withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps));
4799
- printRunOrChain(out, finalRunWithUrl, opts.createContext, data => renderRunResponseText(data, { isBackend }));
4800
- // Surface the trigger requestId under --verbose/--debug or JSON mode so
4801
- // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
4802
- // JSON mode always emits to stderr — it never pollutes stdout).
4803
- if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
4804
- stderrFn(`requestId: ${triggerRequestId}`);
4805
- if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
4806
- // BE runs have no run-scoped artifact bundle — their failure bundle is
4807
- // addressed by testId, not runId.
4808
- stderrFn(isBackend
4809
- ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
4810
- : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
4811
- }
4812
- // CI-native output layer (issue #99): single-test parity with the --all batch.
4813
- // Emitted before the exit-code gate throws below so the summary file and
4814
- // annotations land even when the run exits non-zero (mirrors the batch path).
4815
- // The summary file is a machine artifact written regardless of --output mode;
4816
- // under --output json the run envelope above owns stdout, so ::error::
4817
- // workflow commands are routed to stderr (the Actions runner parses both).
4818
- // Best-effort: a sink write throwing (e.g. EPIPE) must never skip the
4819
- // exit-code gate below or change the command's exit status.
4820
- try {
4821
- const env = deps.env ?? process.env;
4822
- const ghEnabled = opts.ghOutput === true || env.GITHUB_ACTIONS === 'true';
4823
- if (ghEnabled || opts.summaryFile !== undefined) {
4824
- const ciSummary = summarizeSingleRun(finalRunWithUrl);
4825
- if (opts.summaryFile !== undefined) {
4826
- try {
4827
- writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
4828
- }
4829
- catch {
4830
- stderrFn(`[run] could not write --summary-file ${opts.summaryFile}; continuing`);
4831
- }
5027
+ if (err instanceof TunnelLostError) {
5028
+ ticker.finalize(`Run ${triggerResponse.runId} — tunnel disconnected`);
5029
+ const detach = await settleTunnelDetach('tunnel-lost');
5030
+ const partial = {
5031
+ runId: triggerResponse.runId,
5032
+ status: detachPartialStatus(detach),
5033
+ enqueuedAt: triggerResponse.enqueuedAt,
5034
+ codeVersion: triggerResponse.codeVersion,
5035
+ targetUrl: triggerResponse.targetUrl || null,
5036
+ };
5037
+ printRunOrChain(out, partial, opts.createContext, data => {
5038
+ const pr = data;
5039
+ const lines = [
5040
+ `runId ${pr.runId}`,
5041
+ `status ${pr.status} (tunnel disconnected)`,
5042
+ ];
5043
+ if (pr.targetUrl)
5044
+ lines.push(`targetUrl ${pr.targetUrl}`);
5045
+ lines.push(...detachHintLines(pr.runId, detach));
5046
+ return lines.join('\n');
5047
+ });
5048
+ if (detach)
5049
+ stderrFn(tunnelDetachMessage(detach));
5050
+ throw err;
4832
5051
  }
4833
- if (ghEnabled) {
4834
- const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
4835
- emitGithubOutputs(ciSummary, env, {
4836
- stdout: stdoutFn,
4837
- stderr: stderrFn,
4838
- appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
4839
- annotations: opts.output === 'json' ? stderrFn : stdoutFn,
4840
- }, { force: opts.ghOutput === true });
5052
+ if (err instanceof TimeoutError) {
5053
+ ticker.finalize(`Run ${triggerResponse.runId} — timed out after ${opts.timeoutSeconds}s`);
5054
+ // Mirror the RequestTimeoutError path: emit a partial run to stdout so
5055
+ // JSON consumers and AI agents can grab the runId and chain into
5056
+ // `testsprite test wait <runId>` without parsing the stderr error envelope.
5057
+ const detach = await settleTunnelDetach('timeout');
5058
+ const timeoutPartial = {
5059
+ runId: triggerResponse.runId,
5060
+ status: detachPartialStatus(detach),
5061
+ enqueuedAt: triggerResponse.enqueuedAt,
5062
+ codeVersion: triggerResponse.codeVersion,
5063
+ targetUrl: triggerResponse.targetUrl || null,
5064
+ };
5065
+ printRunOrChain(out, timeoutPartial, opts.createContext, data => {
5066
+ const p = data;
5067
+ const lines = [
5068
+ `runId ${p.runId}`,
5069
+ `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
5070
+ ];
5071
+ if (p.targetUrl)
5072
+ lines.push(`targetUrl ${p.targetUrl}`);
5073
+ lines.push(...detachHintLines(p.runId, detach));
5074
+ return lines.join('\n');
5075
+ });
5076
+ if (detach)
5077
+ stderrFn(tunnelDetachMessage(detach));
5078
+ throw ApiError.fromEnvelope({
5079
+ error: {
5080
+ code: 'UNSUPPORTED', // exit 7 per errors.md
5081
+ message: detach
5082
+ ? `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}, ` +
5083
+ `which could not have finished without this process holding its tunnel open.`
5084
+ : `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}. ` +
5085
+ stillRunningAndBillingSubject(triggerResponse.runId),
5086
+ nextAction: detach
5087
+ ? `Start it again with --local and a longer --timeout; a retry mints a fresh tunnel.`
5088
+ : `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
5089
+ requestId: 'local',
5090
+ details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
5091
+ },
5092
+ });
4841
5093
  }
4842
- }
4843
- }
4844
- catch (ciErr) {
4845
- stderrFn(`[run] CI output emission failed; continuing: ${ciErr.message}`);
4846
- }
4847
- const exitCode = exitCodeForRunStatus(finalRun.status);
4848
- if (exitCode !== 0) {
4849
- // Throw a CLIError so index.ts exits with the right code without
4850
- // printing an error envelope — the result was already printed above.
4851
- throw new CLIError(`Run ${finalRun.runId} finished with status: ${finalRun.status}`, exitCode);
5094
+ // C+D: RequestTimeoutError during polling — emit a partial object to stdout
5095
+ // routed through printRunOrChain so:
5096
+ // TEXT mode: renders human-readable (not raw JSON)
5097
+ // JSON mode: preserves the merged create-chain envelope
5098
+ // { ...createContext, run: { runId, status, targetUrl } }
5099
+ // targetUrl is taken from triggerResponse, which is already bound to
5100
+ // the real in-flight URL (see Finding D fix in the 409 resume path).
5101
+ if (err instanceof RequestTimeoutError) {
5102
+ ticker.finalize(`Run ${triggerResponse.runId} — request timed out`);
5103
+ const detach = await settleTunnelDetach('request-timeout');
5104
+ const partial = {
5105
+ runId: triggerResponse.runId,
5106
+ status: detachPartialStatus(detach),
5107
+ enqueuedAt: triggerResponse.enqueuedAt,
5108
+ codeVersion: triggerResponse.codeVersion,
5109
+ targetUrl: triggerResponse.targetUrl || null,
5110
+ };
5111
+ printRunOrChain(out, partial, opts.createContext, data => {
5112
+ const p = data;
5113
+ const lines = [`runId ${p.runId}`, `status ${p.status} (request timed out)`];
5114
+ if (p.targetUrl)
5115
+ lines.push(`targetUrl ${p.targetUrl}`);
5116
+ lines.push(...detachHintLines(p.runId, detach));
5117
+ return lines.join('\n');
5118
+ });
5119
+ stderrFn(detach
5120
+ ? tunnelDetachMessage(detach)
5121
+ : `Request timed out. ${stillRunningAndBillingSubject(triggerResponse.runId)} ` +
5122
+ `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
5123
+ throw err;
5124
+ }
5125
+ // RATE_LIMITED during polling — the backend's pre-auth rate limiter can
5126
+ // trip on a shared egress IP (CI runner, NAT) and 429 an otherwise-valid
5127
+ // key for its window; the HTTP layer already retried internally and gave
5128
+ // up. The run was already triggered (and billed) and keeps executing
5129
+ // server-side, so this must not be a silent, runId-less death: same
5130
+ // partial-envelope contract as the RequestTimeoutError branch above, and
5131
+ // the SAME thrown ApiError is rethrown unchanged so its native exit code
5132
+ // (11) is preserved — never reclassified to 7.
5133
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
5134
+ ticker.finalize(`Run ${triggerResponse.runId} — rate limited by the server`);
5135
+ // The cancel this issues is itself a request to the same rate-limited
5136
+ // API, so it may well be refused. `cancelDoomedTunnelRun` reports that
5137
+ // honestly and the message names `test cancel` rather than claiming a
5138
+ // cancel that did not happen.
5139
+ const detach = await settleTunnelDetach('rate-limited');
5140
+ const partial = {
5141
+ runId: triggerResponse.runId,
5142
+ status: detachPartialStatus(detach),
5143
+ enqueuedAt: triggerResponse.enqueuedAt,
5144
+ codeVersion: triggerResponse.codeVersion,
5145
+ targetUrl: triggerResponse.targetUrl || null,
5146
+ };
5147
+ printRunOrChain(out, partial, opts.createContext, data => {
5148
+ const p = data;
5149
+ const lines = [
5150
+ `runId ${p.runId}`,
5151
+ `status ${p.status} (rate limited by the server)`,
5152
+ ];
5153
+ if (p.targetUrl)
5154
+ lines.push(`targetUrl ${p.targetUrl}`);
5155
+ lines.push(...detachHintLines(p.runId, detach));
5156
+ return lines.join('\n');
5157
+ });
5158
+ stderrFn(detach
5159
+ ? tunnelDetachMessage(detach)
5160
+ : rateLimitedDetachMessage(err, [triggerResponse.runId]));
5161
+ throw err;
5162
+ }
5163
+ // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
5164
+ // envelope shape as the timeout paths so stdout stays parseable, plus the
5165
+ // honest "keeps running and billing" stderr line. Rethrow → index.ts
5166
+ // renders the INTERRUPTED envelope and exits 128+signum.
5167
+ if (err instanceof InterruptError) {
5168
+ ticker.finalize(`Run ${triggerResponse.runId} — interrupted (${err.signal})`);
5169
+ const detach = await settleTunnelDetach('interrupt');
5170
+ const partial = {
5171
+ runId: triggerResponse.runId,
5172
+ status: detachPartialStatus(detach),
5173
+ enqueuedAt: triggerResponse.enqueuedAt,
5174
+ codeVersion: triggerResponse.codeVersion,
5175
+ targetUrl: triggerResponse.targetUrl || null,
5176
+ };
5177
+ printRunOrChain(out, partial, opts.createContext, data => {
5178
+ const p = data;
5179
+ const lines = [`runId ${p.runId}`, `status ${p.status} (interrupted)`];
5180
+ if (p.targetUrl)
5181
+ lines.push(`targetUrl ${p.targetUrl}`);
5182
+ lines.push(...detachHintLines(p.runId, detach));
5183
+ return lines.join('\n');
5184
+ });
5185
+ stderrFn(detach
5186
+ ? tunnelDetachMessage(detach)
5187
+ : interruptDetachMessage(err, [triggerResponse.runId]));
5188
+ if (detach !== undefined)
5189
+ attachTunnelInterruptDetach(err, detach);
5190
+ throw err;
5191
+ }
5192
+ // Any other poll failure still leaves us holding a known, charged runId.
5193
+ // An owned tunnel is about to close in the outer finally, so settle the
5194
+ // run exactly like the classified detach paths before preserving the
5195
+ // original error object/type/code/message for the caller.
5196
+ const detach = await settleTunnelDetach('poll-error');
5197
+ if (detach !== undefined) {
5198
+ ticker.finalize(`Run ${triggerResponse.runId} — polling stopped`);
5199
+ const partial = {
5200
+ runId: triggerResponse.runId,
5201
+ status: detachPartialStatus(detach),
5202
+ enqueuedAt: triggerResponse.enqueuedAt,
5203
+ codeVersion: triggerResponse.codeVersion,
5204
+ targetUrl: triggerResponse.targetUrl || null,
5205
+ };
5206
+ printRunOrChain(out, partial, opts.createContext, data => {
5207
+ const p = data;
5208
+ const lines = [`runId ${p.runId}`, `status ${p.status} (polling stopped)`];
5209
+ if (p.targetUrl)
5210
+ lines.push(`targetUrl ${p.targetUrl}`);
5211
+ lines.push(...detachHintLines(p.runId, detach));
5212
+ return lines.join('\n');
5213
+ });
5214
+ stderrFn(tunnelDetachMessage(detach));
5215
+ }
5216
+ else {
5217
+ ticker.finalize();
5218
+ }
5219
+ throw err;
5220
+ }
5221
+ finally {
5222
+ live.stop();
5223
+ }
5224
+ ticker.finalize(formatRunProgressLine(finalRun, Date.now() - startMs));
5225
+ // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs); on
5226
+ // the standalone `test run <id>` path neither is set, so probe the test type
5227
+ // once (text mode only, best-effort) — DEV-282.
5228
+ const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
5229
+ const finalRunWithUrl = withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps));
5230
+ printRunOrChain(out, finalRunWithUrl, opts.createContext, data => renderRunResponseText(data, { isBackend }));
5231
+ // Surface the trigger requestId under --verbose/--debug or JSON mode so
5232
+ // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
5233
+ // JSON mode always emits to stderr — it never pollutes stdout).
5234
+ if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
5235
+ stderrFn(`requestId: ${triggerRequestId}`);
5236
+ if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
5237
+ // BE runs have no run-scoped artifact bundle — their failure bundle is
5238
+ // addressed by testId, not runId.
5239
+ stderrFn(isBackend
5240
+ ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
5241
+ : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
5242
+ }
5243
+ // CI-native output layer (issue #99): single-test parity with the --all batch.
5244
+ // Emitted before the exit-code gate throws below so the summary file and
5245
+ // annotations land even when the run exits non-zero (mirrors the batch path).
5246
+ // The summary file is a machine artifact written regardless of --output mode;
5247
+ // under --output json the run envelope above owns stdout, so ::error::
5248
+ // workflow commands are routed to stderr (the Actions runner parses both).
5249
+ // Best-effort: a sink write throwing (e.g. EPIPE) must never skip the
5250
+ // exit-code gate below or change the command's exit status.
5251
+ try {
5252
+ emitCiArtifacts(summarizeSingleRun(finalRunWithUrl), opts, {
5253
+ env: deps.env ?? process.env,
5254
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
5255
+ stderr: stderrFn,
5256
+ }, 'run');
5257
+ }
5258
+ catch (ciErr) {
5259
+ stderrFn(`[run] CI output emission failed; continuing: ${ciErr.message}`);
5260
+ }
5261
+ const exitCode = exitCodeForRunStatus(finalRun.status);
5262
+ if (exitCode !== 0) {
5263
+ // Throw a CLIError so index.ts exits with the right code without
5264
+ // printing an error envelope — the result was already printed above.
5265
+ throw new CLIError(`Run ${finalRun.runId} finished with status: ${finalRun.status}`, exitCode);
5266
+ }
5267
+ return finalRun;
5268
+ }
5269
+ finally {
5270
+ // Every exit path — success, run failure, timeout, signal, a throw from
5271
+ // the trigger itself — releases the tunnel and deletes the binding.
5272
+ // Skipping this on any one of them leaves a live inbound credential and a
5273
+ // client whose ref'd heartbeat timer keeps the process alive after the
5274
+ // command has printed its last line.
5275
+ try {
5276
+ await tunnelSession?.close();
5277
+ }
5278
+ finally {
5279
+ disarmTunnelLifecycle?.();
5280
+ }
4852
5281
  }
4853
- return finalRun;
4854
5282
  }
4855
5283
  /**
4856
5284
  * `test wait <run-id...>` with two or more ids: attach to N already-dispatched
@@ -5035,7 +5463,8 @@ export async function runTestWaitMany(opts, deps = {}) {
5035
5463
  stderrFn(interruptDetachMessage(fanOutErr, unfinished));
5036
5464
  }
5037
5465
  else {
5038
- stderrFn(`Re-attach with: testsprite test wait ${unfinished.join(' ')}, or cancel with: testsprite test cancel ${unfinished.join(' ')}`);
5466
+ stderrFn(`Request timed out. ${stillRunningAndBillingSubject(unfinished)} ` +
5467
+ `Re-attach with: testsprite test wait ${unfinished.join(' ')}, or cancel with: testsprite test cancel ${unfinished.join(' ')}`);
5039
5468
  }
5040
5469
  }
5041
5470
  }
@@ -5290,6 +5719,9 @@ export async function runTestWait(opts, deps = {}) {
5290
5719
  `Read full detail with: testsprite test result ${testId}`);
5291
5720
  },
5292
5721
  });
5722
+ // Keeps the elapsed counter moving between long-poll returns (~25s apart).
5723
+ // Armed only when the ticker redraws in place (its own TTY / NO_COLOR call).
5724
+ const live = createLiveRunProgress(ticker);
5293
5725
  let finalRun;
5294
5726
  try {
5295
5727
  finalRun = await pollRunUntilTerminal(client, opts.runId, {
@@ -5297,15 +5729,14 @@ export async function runTestWait(opts, deps = {}) {
5297
5729
  sleep: deps.sleep,
5298
5730
  shutdown: shutdownOf(deps),
5299
5731
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5300
- onTick: (run, elapsedMs) => {
5301
- const elapsed = Math.round(elapsedMs / 1000);
5302
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5303
- ticker.update(`Run ${run.runId} — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
5304
- },
5732
+ onTick: live.onTick,
5305
5733
  resolveAlternate,
5306
5734
  });
5307
5735
  }
5308
5736
  catch (err) {
5737
+ // Stop redrawing BEFORE any final line below is written, so a stale
5738
+ // "running · Ns" can never land after "timed out" / "interrupted".
5739
+ live.stop();
5309
5740
  if (err instanceof TimeoutError) {
5310
5741
  ticker.finalize(`Run ${opts.runId} — timed out after ${opts.timeoutSeconds}s`);
5311
5742
  // Mirror the RequestTimeoutError path: emit a partial run to stdout so
@@ -5324,7 +5755,8 @@ export async function runTestWait(opts, deps = {}) {
5324
5755
  throw ApiError.fromEnvelope({
5325
5756
  error: {
5326
5757
  code: 'UNSUPPORTED', // exit 7 per errors.md
5327
- message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${opts.runId}.`,
5758
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${opts.runId}. ` +
5759
+ stillRunningAndBillingSubject(opts.runId),
5328
5760
  nextAction: `Resume polling: testsprite test wait ${opts.runId}, or cancel it: testsprite test cancel ${opts.runId}`,
5329
5761
  requestId: 'local',
5330
5762
  details: { runId: opts.runId, timeoutSeconds: opts.timeoutSeconds },
@@ -5346,7 +5778,7 @@ export async function runTestWait(opts, deps = {}) {
5346
5778
  `hint Cancel with: testsprite test cancel ${p.runId}`,
5347
5779
  ].join('\n');
5348
5780
  });
5349
- stderrFn(`Run ${opts.runId} is still in progress (request timed out). ` +
5781
+ stderrFn(`Request timed out. ${stillRunningAndBillingSubject(opts.runId)} ` +
5350
5782
  `Re-attach with: testsprite test wait ${opts.runId}, or cancel with: testsprite test cancel ${opts.runId}`);
5351
5783
  throw err;
5352
5784
  }
@@ -5389,9 +5821,10 @@ export async function runTestWait(opts, deps = {}) {
5389
5821
  ticker.finalize();
5390
5822
  throw err;
5391
5823
  }
5392
- const elapsed = Math.round((Date.now() - startMs) / 1000);
5393
- const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5394
- ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
5824
+ finally {
5825
+ live.stop();
5826
+ }
5827
+ ticker.finalize(formatRunProgressLine(finalRun, Date.now() - startMs));
5395
5828
  // `test wait` has no type hint; probe the test type once (text mode only,
5396
5829
  // best-effort) so a backend run's card reads `n/a (backend)` — DEV-282.
5397
5830
  const isBackend = await resolveRunCardIsBackend(client, finalRun.testId, opts.output, beFallbackUsed);
@@ -5409,18 +5842,128 @@ export async function runTestWait(opts, deps = {}) {
5409
5842
  }
5410
5843
  return finalRun;
5411
5844
  }
5412
- async function writeBatchJUnitReportIfRequested(opts, results) {
5845
+ /**
5846
+ * Best-effort `testId → test name` map for the JUnit report, so a CI test tab
5847
+ * shows names instead of UUIDs. One paginated `GET /tests?projectId=` sweep,
5848
+ * bounded by a 5 s deadline and swallowed on any error — a missing/partial map
5849
+ * just falls back to ids, never blocks or fails the report.
5850
+ */
5851
+ async function buildTestNameMap(client, projectId) {
5852
+ const map = new Map();
5853
+ if (!projectId)
5854
+ return map;
5855
+ const ac = new AbortController();
5856
+ const timer = setTimeout(() => ac.abort(), DUP_NAME_ADVISORY_TIMEOUT_MS);
5857
+ try {
5858
+ let cursor;
5859
+ for (let pageN = 0; pageN < 20; pageN++) {
5860
+ const page = await client.get('/tests', {
5861
+ query: { projectId, pageSize: 100, ...(cursor ? { cursor } : {}) },
5862
+ signal: ac.signal,
5863
+ retryOnRateLimit: false,
5864
+ });
5865
+ for (const t of page.items ?? [])
5866
+ map.set(t.id, t.name);
5867
+ cursor = page.nextToken ?? undefined;
5868
+ if (!cursor)
5869
+ break;
5870
+ }
5871
+ }
5872
+ catch {
5873
+ // best-effort — a partial/empty map simply falls back to ids in the report.
5874
+ }
5875
+ finally {
5876
+ clearTimeout(timer);
5877
+ }
5878
+ return map;
5879
+ }
5880
+ export async function writeBatchJUnitReportIfRequested(opts, results, nameByTestId) {
5413
5881
  if (opts.report !== 'junit' || opts.reportFile === undefined)
5414
5882
  return;
5415
5883
  const projectId = resolveBatchReportProjectId(opts, results);
5416
5884
  const suiteName = opts.reportSuiteName ?? `testsprite:${projectId}`;
5885
+ // Enrich each row with the human name (from the map) and the run duration
5886
+ // (from poll timing) — the two fields whose absence made the report unreadable.
5887
+ // Name precedence: the sweep map wins (it's a full page scan), then the poll
5888
+ // response's own `testTitle` (same source the summary table uses — this keeps
5889
+ // the two surfaces on the same name when the sweep over-pages / times out),
5890
+ // then the row's fallback name. `.trim() ||` so a blank title never shadows it.
5891
+ const enriched = results.map(r => ({
5892
+ ...r,
5893
+ name: nameByTestId?.get(r.testId) ?? (r.testTitle?.trim() ? r.testTitle : undefined) ?? r.name,
5894
+ durationSeconds: r.durationSeconds ?? durationSecondsBetween(r.startedAt, r.finishedAt),
5895
+ }));
5417
5896
  const xml = buildJUnitReport({
5418
5897
  suiteName,
5419
5898
  classname: projectId,
5420
- results,
5899
+ results: enriched,
5421
5900
  });
5422
5901
  await writeJUnitReportFile(opts.reportFile, xml);
5423
5902
  }
5903
+ /** Human explanation for a zero-dispatch batch, from what the engine skipped. */
5904
+ function zeroDispatchReason(skippedFrontend, skippedIntegration) {
5905
+ const parts = [];
5906
+ if (skippedFrontend.length > 0) {
5907
+ parts.push(`${skippedFrontend.length} frontend test${skippedFrontend.length !== 1 ? 's' : ''} skipped (the batch engine is BE-only for FE tests — run them with 'test run <id>')`);
5908
+ }
5909
+ if (skippedIntegration.length > 0) {
5910
+ parts.push(`${skippedIntegration.length} assembled integration test${skippedIntegration.length !== 1 ? 's' : ''} skipped (run via the portal)`);
5911
+ }
5912
+ return parts.length > 0
5913
+ ? `all resolved tests were skipped: ${parts.join('; ')}`
5914
+ : 'no runnable tests in the project';
5915
+ }
5916
+ /**
5917
+ * Handle a batch invocation that dispatched ZERO tests — all skipped, an empty
5918
+ * project, or a `--filter` that matched nothing. Left alone this exits 0 with no
5919
+ * artifact, a CI false-green: a gate that greens on zero tests is worse than no
5920
+ * gate (DEV-1046). So it emits the CI artifacts (summary + `::error::` annotation
5921
+ * + JUnit report) so the gate shows WHY, then fails with **exit 5** unless the
5922
+ * caller passed `--allow-empty` (in which case it returns and the caller exits 0).
5923
+ *
5924
+ * `skipped` is the union of skipped FE + integration tests (rendered as
5925
+ * `<skipped/>` JUnit cases and non-passed summary rows so they're visible);
5926
+ * `reason` is the human explanation shown in the annotation and the throw.
5927
+ */
5928
+ async function finishZeroDispatchBatch(params) {
5929
+ const { reason, skipped, allowEmpty, opts, deps, stderrFn, label = 'run' } = params;
5930
+ const runs = skipped.length > 0
5931
+ ? skipped.map(testId => ({ testId, status: 'skipped', error: reason }))
5932
+ : [{ testId: '(no tests)', status: 'no_tests', error: reason }];
5933
+ const summary = {
5934
+ total: runs.length,
5935
+ passed: 0,
5936
+ failed: runs.length,
5937
+ timedOut: 0,
5938
+ runs,
5939
+ };
5940
+ // Emit the in-memory artifacts (summary + `::error::` annotation) FIRST: they
5941
+ // can't fail on I/O, so the "show WHY it's red" diagnostics always land — even
5942
+ // if the JUnit path below is misconfigured. Ordering these after the file write
5943
+ // would let an unwritable --report-file throw (exit 10) preempt both the
5944
+ // diagnostics AND the exit-5 gate, masking the zero-dispatch cause.
5945
+ emitCiArtifacts(summary, opts, {
5946
+ env: deps.env ?? process.env,
5947
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
5948
+ stderr: stderrFn,
5949
+ }, label);
5950
+ // Then the JUnit sidecar (the other half of "no artifact was produced before").
5951
+ // `writeBatchJUnitReportIfRequested` no-ops unless --report junit. Degrade a
5952
+ // write failure to a warning so an unwritable path can't mask the exit-5 intent
5953
+ // with an I/O exit code.
5954
+ try {
5955
+ await writeBatchJUnitReportIfRequested(opts, runs.map(r => ({ testId: r.testId, status: 'skipped' })));
5956
+ }
5957
+ catch (err) {
5958
+ stderrFn(`[${label}] could not write the JUnit report on a zero-dispatch run: ${err instanceof Error ? err.message : String(err)}; continuing`);
5959
+ }
5960
+ if (allowEmpty) {
5961
+ stderrFn(`[${label}] 0 tests dispatched (${reason}); --allow-empty set — exiting 0.`);
5962
+ return;
5963
+ }
5964
+ throw new CLIError(`No tests were dispatched — ${reason}. A CI gate that passes on zero tests is unsafe; ` +
5965
+ `pass --allow-empty to exit 0 intentionally.`, 5);
5966
+ }
5424
5967
  /**
5425
5968
  * `test run --all --project <id>` — M4 piece-2.
5426
5969
  *
@@ -5483,6 +6026,16 @@ export async function runTestRunAll(opts, deps = {}) {
5483
6026
  ? undefined
5484
6027
  : `${batchPortalBase}/dashboard/tests/${encodeURIComponent(projectId)}`;
5485
6028
  const withBatchDashboardUrl = (item) => {
6029
+ // Prefer the SERVER-built link the poll already captured onto the row — only
6030
+ // the server knows which store answered and can resolve a non-prod origin, and
6031
+ // for a V3-native project the client's V2-shaped guess is structurally dead
6032
+ // (the same footgun that 404'd MCP report links for months). Fall back to the
6033
+ // client guess only when the server sent none (older backend). `executionUrl`,
6034
+ // when present, rides through untouched — it is never client-built.
6035
+ // TODO: drop the resolvePortalUrl fallback once the server dashboardUrl has
6036
+ // shipped in every environment — it only serves runs from an older backend.
6037
+ if (typeof item.dashboardUrl === 'string')
6038
+ return item;
5486
6039
  const dashboardUrl = resolvePortalUrl(batchApiUrl, projectId, item.testId);
5487
6040
  return dashboardUrl !== undefined ? { ...item, dashboardUrl } : item;
5488
6041
  };
@@ -5514,6 +6067,17 @@ export async function runTestRunAll(opts, deps = {}) {
5514
6067
  skippedFrontend: [],
5515
6068
  skippedIntegration: [],
5516
6069
  });
6070
+ // Zero-dispatch (a --filter that matched nothing): emit the CI artifacts
6071
+ // and fail unless --allow-empty, so a renamed test can't turn a filtered
6072
+ // gate permanently green (DEV-1046). Returns here only under --allow-empty.
6073
+ await finishZeroDispatchBatch({
6074
+ reason: `--filter "${opts.nameFilter}" matched no tests in project ${projectId}`,
6075
+ skipped: [],
6076
+ allowEmpty: opts.allowEmpty === true,
6077
+ opts,
6078
+ deps,
6079
+ stderrFn,
6080
+ });
5517
6081
  return undefined;
5518
6082
  }
5519
6083
  stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${projectId} for batch run.`);
@@ -5540,14 +6104,16 @@ export async function runTestRunAll(opts, deps = {}) {
5540
6104
  stderrFn(`[advisory] ${skippedIntegration.length} assembled integration test${skippedIntegration.length !== 1 ? 's' : ''} skipped — not runnable via the CLI wave path. Run them from the portal.`);
5541
6105
  }
5542
6106
  if (conflicts.length > 0) {
5543
- stderrFn(`[advisory] ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight, skipped: ${conflicts.map(c => c.testId).join(' ')}`);
6107
+ // Reason-aware advisory: a view-only / un-runnable / not-found case is not
6108
+ // "already in flight" — summarizeConflicts names the actual causes.
6109
+ stderrFn(`[advisory] ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} not dispatched (${summarizeConflicts(conflicts)}), skipped: ${conflicts.map(c => c.testId).join(' ')}`);
5544
6110
  }
5545
6111
  if (deferred.length > 0) {
5546
6112
  stderrFn(`Rate-deferred testIds (retry later): ${deferred.map(d => d.testId).join(' ')}`);
5547
6113
  }
5548
6114
  stderrFn(`Dispatched ${accepted.length} test${accepted.length !== 1 ? 's' : ''}` +
5549
6115
  `${skippedFrontend.length > 0 ? ` (${skippedFrontend.length} FE skipped)` : ''}` +
5550
- `${conflicts.length > 0 ? ` (${conflicts.length} in flight)` : ''}` +
6116
+ `${conflicts.length > 0 ? ` (${conflicts.length} conflict${conflicts.length !== 1 ? 's' : ''})` : ''}` +
5551
6117
  `${deferred.length > 0 ? ` (${deferred.length} rate-deferred)` : ''}.`);
5552
6118
  if (!opts.wait) {
5553
6119
  const printResp = {
@@ -5561,7 +6127,7 @@ export async function runTestRunAll(opts, deps = {}) {
5561
6127
  const r = data;
5562
6128
  const lines = [`accepted ${r.accepted.length}`];
5563
6129
  if (r.conflicts.length > 0)
5564
- lines.push(`conflicts ${r.conflicts.length} (already in flight)`);
6130
+ lines.push(`conflicts ${r.conflicts.length} (${summarizeConflicts(r.conflicts)})`);
5565
6131
  if (r.deferred.length > 0)
5566
6132
  lines.push(`deferred ${r.deferred.length} (rate-limited — retry)`);
5567
6133
  if (r.skippedFrontend.length > 0) {
@@ -5595,30 +6161,55 @@ export async function runTestRunAll(opts, deps = {}) {
5595
6161
  },
5596
6162
  });
5597
6163
  }
6164
+ // Zero dispatched, nothing pending (deferred / conflict already threw above):
6165
+ // all tests were skipped, or the project has none. Don't exit 0 (DEV-1046).
6166
+ if (accepted.length === 0) {
6167
+ await finishZeroDispatchBatch({
6168
+ reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
6169
+ skipped: [...skippedFrontend, ...skippedIntegration.map(s => s.testId)],
6170
+ allowEmpty: opts.allowEmpty === true,
6171
+ opts,
6172
+ deps,
6173
+ stderrFn,
6174
+ });
6175
+ }
5598
6176
  // [P2] Return post-retry state so programmatic callers and the create-chain
5599
6177
  // JSON merge reflect what was actually dispatched, not the stale initial resp.
5600
6178
  return { ...batchResp, accepted, deferred, conflicts };
5601
6179
  }
5602
- // D3: bounded deferred-retry loop (only under --wait).
5603
- // Up to MAX_DEFERRED_RETRIES attempts to re-dispatch still-deferred tests.
5604
- // Each attempt sleeps for Retry-After (if server provided it) or the default
5605
- // 61s, clamped to the remaining --timeout budget. Newly-accepted runs are
5606
- // merged into `accepted`; if still deferred after all attempts, fall through
5607
- // to the existing exit-7 path.
6180
+ // D3: budget-driven deferred-retry loop (only under --wait).
6181
+ // Re-dispatches still-deferred tests until they all clear OR the --timeout
6182
+ // budget is exhausted — a busy pool (the in-flight concurrency cap folds
6183
+ // overflow into `deferred[]`) drains within the user's own timeout instead of
6184
+ // giving up after a fixed few tries and failing the run. Each attempt sleeps
6185
+ // 61s (clamped to the remaining budget); newly-accepted runs merge into
6186
+ // `accepted`; if still deferred when the budget runs out, fall through to the
6187
+ // existing exit-7 path. `maxDeferredAttempts` is a pure runaway backstop (the
6188
+ // deadline check below is the real stop), scaled to the timeout so it never
6189
+ // caps a legitimate long wait.
5608
6190
  const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
5609
6191
  const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
5610
- for (let attempt = 1; attempt <= MAX_DEFERRED_RETRIES && deferred.length > 0; attempt++) {
6192
+ // finding 1: reserve a poll window so the deferred-retry loop can't consume the
6193
+ // ENTIRE --timeout and leave the fan-out poll with nothing — which would report
6194
+ // already-finished runs as timeouts (exit 7) instead of their real verdicts
6195
+ // (a genuine failure is exit 1, not 7). One third of the budget, capped at 60s.
6196
+ const POLL_RESERVE_MS = Math.min(60_000, Math.floor((opts.timeoutSeconds * 1000) / 3));
6197
+ const maxDeferredAttempts = Math.max(MAX_DEFERRED_RETRIES, Math.ceil(opts.timeoutSeconds / 60) + 2);
6198
+ for (let attempt = 1; attempt <= maxDeferredAttempts && deferred.length > 0; attempt++) {
5611
6199
  const remainingMs = batchDeadlineMs - Date.now();
5612
- if (remainingMs <= 0) {
5613
- stderrFn(`[deferred-retry] timeout budget exhausted before attempt ${attempt}/${MAX_DEFERRED_RETRIES} — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
6200
+ if (remainingMs <= POLL_RESERVE_MS) {
6201
+ stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
5614
6202
  break;
5615
6203
  }
5616
- const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs);
5617
- stderrFn(`[deferred-retry] attempt ${attempt}/${MAX_DEFERRED_RETRIES} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
6204
+ // §1: clamp to what's left ABOVE the reserve so the sleep itself can't run
6205
+ // the budget to zero (the loop only reaches here when remainingMs >
6206
+ // POLL_RESERVE_MS, so the difference is always positive).
6207
+ const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs - POLL_RESERVE_MS);
6208
+ stderrFn(`[deferred-retry] attempt ${attempt} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
5618
6209
  await sleepFn(sleepMs);
5619
6210
  const remainingAfterSleep = batchDeadlineMs - Date.now();
5620
- if (remainingAfterSleep <= 0) {
5621
- stderrFn(`[deferred-retry] timeout budget exhausted during sleep — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
6211
+ if (remainingAfterSleep <= POLL_RESERVE_MS) {
6212
+ stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
5622
6213
  break;
5623
6214
  }
5624
6215
  const retryIds = deferred.map(d => d.testId);
@@ -5633,6 +6224,16 @@ export async function runTestRunAll(opts, deps = {}) {
5633
6224
  const retryKey = `${retryBase}${retrySuffix}`;
5634
6225
  let retryResp;
5635
6226
  try {
6227
+ // The retry dispatch POST is deliberately NOT bound to the batch deadline
6228
+ // via an AbortSignal. It is a state-CREATING call (it seeds runs); if the
6229
+ // deadline fired mid-flight the abort would only cancel the CLIENT wait,
6230
+ // leaving the server having possibly created the runs while this loop
6231
+ // reports them as still-deferred — the user then retries with a fresh
6232
+ // idempotency key and DUPLICATES the execution + charge. The per-request
6233
+ // timeout (`--request-timeout`, default 120s) still bounds the call, and
6234
+ // the sleeps + fan-out poll below remain deadline-aware; only this single
6235
+ // dispatch may overrun the budget slightly, which is strictly safer than
6236
+ // an indeterminate aborted-but-maybe-dispatched batch.
5636
6237
  retryResp = await client.triggerBatchRunFresh({
5637
6238
  projectId,
5638
6239
  testIds: retryIds,
@@ -5640,7 +6241,7 @@ export async function runTestRunAll(opts, deps = {}) {
5640
6241
  }, { idempotencyKey: retryKey });
5641
6242
  }
5642
6243
  catch (err) {
5643
- // If the retry itself errors, surface the error and stop retrying.
6244
+ // If the retry itself errors, surface it and stop retrying.
5644
6245
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
5645
6246
  break;
5646
6247
  }
@@ -5664,11 +6265,53 @@ export async function runTestRunAll(opts, deps = {}) {
5664
6265
  stderrFn(`[deferred-retry] attempt ${attempt}: all previously-deferred tests accepted.`);
5665
6266
  }
5666
6267
  }
5667
- // --wait: fan-out poll each accepted run by its runId. Every accepted entry
5668
- // carries a real runId (the backend routes slot-claim failures to conflicts[]),
5669
- // so there is no "draft, no runId" subset to silently skip — polling all of
5670
- // them is the only way `--wait` can report a faithful (not false-green) verdict.
5671
- const pollable = accepted;
6268
+ // Gap B: an already-running case is not a dead end under --wait. A conflict
6269
+ // carrying `currentRunId` has an EXISTING run we can poll to a verdict
6270
+ // (auto-resume) — the "concurrent job already started this test" case should
6271
+ // wait for that run's result, not fail the batch. Conflicts without a
6272
+ // resolvable in-flight run stay hard (nothing to wait on).
6273
+ const resumableConflicts = conflicts.filter(c => c.currentRunId);
6274
+ const hardConflicts = conflicts.filter(c => !c.currentRunId);
6275
+ // Only hard conflicts remain "conflicts" for the final accounting/exit; the
6276
+ // resumable ones become polled results below.
6277
+ conflicts = hardConflicts;
6278
+ // finding 2: resolve each in-flight run's createdAt to floor the BE wait
6279
+ // fallback's "not before" filter. An epoch sentinel let the fallback accept
6280
+ // ANY terminal result for the test — including the PREVIOUS run's — whenever
6281
+ // the row lacks `runIdIfAvailable` (the orphaned-row case the fallback exists
6282
+ // for, and the EXPECTED path for MCP-backend-triggered runs whose TestRun rows
6283
+ // never leave `queued`). Flooring to the run's own createdAt stops an
6284
+ // auto-resume from resolving to a stale prior verdict (a false green). The
6285
+ // fetch also yields source/createdFrom so we can name who started the run.
6286
+ // §5: resolve the in-flight runs' createdAt in PARALLEL, bounded by a signal
6287
+ // capped at the remaining batch budget. This runs in exactly the busy-pool /
6288
+ // many-in-flight-conflicts scenario finding 1 is about, so a serial N round-trip
6289
+ // fetch (with no deadline bound) would eat the budget finding 1's fix protects.
6290
+ const resolveSignal = AbortSignal.timeout(Math.max(1, batchDeadlineMs - Date.now()));
6291
+ const resumableEntries = await Promise.all(resumableConflicts.map(async (c) => {
6292
+ const inFlightRunId = c.currentRunId;
6293
+ // Conservative default if the run can't be read: floor at NOW (never the
6294
+ // epoch) so the fallback still can't accept an older run's result.
6295
+ let notBefore = new Date().toISOString();
6296
+ let startedBy;
6297
+ try {
6298
+ const inFlight = await client.getRun(inFlightRunId, { signal: resolveSignal });
6299
+ if (inFlight.createdAt)
6300
+ notBefore = inFlight.createdAt;
6301
+ startedBy = inFlight.source || inFlight.createdFrom || undefined;
6302
+ }
6303
+ catch {
6304
+ // keep the conservative now() floor (fetch failed or the signal aborted)
6305
+ }
6306
+ stderrFn(`[auto-resume] ${c.testId} — polling in-flight run ${inFlightRunId}${startedBy ? ` (started by ${startedBy})` : ''} to a verdict instead of failing`);
6307
+ return { testId: c.testId, runId: inFlightRunId, enqueuedAt: notBefore };
6308
+ }));
6309
+ // --wait: fan-out poll each accepted run by its runId, PLUS each auto-resumed
6310
+ // in-flight run. Every accepted entry carries a real runId (the backend routes
6311
+ // slot-claim failures to conflicts[]); the resumed entries reuse the existing
6312
+ // run's id with a real createdAt floor. Polling all of them is the only way
6313
+ // `--wait` reports a faithful (not false-green) verdict.
6314
+ const pollable = [...accepted, ...resumableEntries];
5672
6315
  if (pollable.length === 0) {
5673
6316
  // Build final response with potentially-updated accepted/deferred from D3 retry loop.
5674
6317
  const finalResp = {
@@ -5681,6 +6324,15 @@ export async function runTestRunAll(opts, deps = {}) {
5681
6324
  out.print(finalResp);
5682
6325
  // Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
5683
6326
  // mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
6327
+ // Emit the deferred/conflict summary + annotations first so CI shows them (the
6328
+ // pure zero-dispatch fall-through emits its OWN skipped-rows summary below).
6329
+ if (deferred.length > 0 || conflicts.length > 0) {
6330
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(finalResp)), opts, {
6331
+ env: deps.env ?? process.env,
6332
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
6333
+ stderr: stderrFn,
6334
+ }, 'run');
6335
+ }
5684
6336
  if (deferred.length > 0) {
5685
6337
  throw new CLIError(`Batch run incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} rate-deferred (per-key run budget) — retry these individually after ~60s: ${deferred.map(d => d.testId).join(' ')}`, 7);
5686
6338
  }
@@ -5695,7 +6347,18 @@ export async function runTestRunAll(opts, deps = {}) {
5695
6347
  },
5696
6348
  });
5697
6349
  }
5698
- // [P2] Return post-retry state.
6350
+ // Reached only when nothing was queued and nothing is pending: all tests were
6351
+ // skipped, or the project has none. Emit a skipped-rows summary + JUnit and
6352
+ // fail unless --allow-empty — never a silent exit 0 (DEV-1046).
6353
+ await finishZeroDispatchBatch({
6354
+ reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
6355
+ skipped: [...skippedFrontend, ...skippedIntegration.map(s => s.testId)],
6356
+ allowEmpty: opts.allowEmpty === true,
6357
+ opts,
6358
+ deps,
6359
+ stderrFn,
6360
+ });
6361
+ // [P2] Return post-retry state (reached only under --allow-empty).
5699
6362
  return { ...batchResp, accepted, deferred, conflicts };
5700
6363
  }
5701
6364
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
@@ -5711,6 +6374,44 @@ export async function runTestRunAll(opts, deps = {}) {
5711
6374
  const runId = entry.runId;
5712
6375
  const remainingMs = batchDeadlineMs - Date.now();
5713
6376
  if (remainingMs <= 0) {
6377
+ // §1/§4: the retry loop reserves POLL_RESERVE_MS, but a slow fan-out can
6378
+ // still land here past the deadline. Do ONE bounded poll (1s) THROUGH the
6379
+ // backend wait-fallback before declaring timeout — a run that already
6380
+ // reached a verdict resolves for ~one request instead of a false timeout
6381
+ // (exit 7 when the platform already produced its result; a failure is exit
6382
+ // 1). Going through pollRunUntilTerminal + resolveAlternate — not a bare
6383
+ // getRun — also covers the orphaned-row class finding 2 is about: a backend
6384
+ // TestRun row stuck in `queued` whose verdict only the fallback resolves.
6385
+ const lastResortAlternate = makeBackendWaitFallback({
6386
+ client,
6387
+ resolveTestId: () => entry.testId,
6388
+ resolveNotBefore: () => entry.enqueuedAt,
6389
+ onResolved: () => undefined,
6390
+ });
6391
+ try {
6392
+ const finalRun = await pollRunUntilTerminal(client, runId, {
6393
+ timeoutSeconds: 1,
6394
+ sleep: deps.sleep,
6395
+ shutdown: shutdownOf(deps),
6396
+ resolveAlternate: lastResortAlternate,
6397
+ });
6398
+ return {
6399
+ testId: entry.testId,
6400
+ testTitle: finalRun.testTitle ?? null,
6401
+ runId,
6402
+ projectId: finalRun.projectId,
6403
+ status: finalRun.status,
6404
+ ...(typeof finalRun.dashboardUrl === 'string'
6405
+ ? { dashboardUrl: finalRun.dashboardUrl }
6406
+ : {}),
6407
+ ...(typeof finalRun.executionUrl === 'string'
6408
+ ? { executionUrl: finalRun.executionUrl }
6409
+ : {}),
6410
+ };
6411
+ }
6412
+ catch {
6413
+ // fall through to the timeout result below
6414
+ }
5714
6415
  return {
5715
6416
  testId: entry.testId,
5716
6417
  runId,
@@ -5735,18 +6436,23 @@ export async function runTestRunAll(opts, deps = {}) {
5735
6436
  sleep: deps.sleep,
5736
6437
  shutdown: shutdownOf(deps),
5737
6438
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5738
- onTick: (run, elapsedMs) => {
5739
- const elapsed = Math.round(elapsedMs / 1000);
5740
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5741
- ticker.update(`Run ${run.runId} (${entry.testId}) — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
5742
- },
6439
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
5743
6440
  resolveAlternate,
5744
6441
  });
5745
6442
  return {
5746
6443
  testId: entry.testId,
6444
+ testTitle: finalRun.testTitle ?? null,
5747
6445
  runId,
5748
6446
  projectId: finalRun.projectId,
5749
6447
  status: finalRun.status,
6448
+ ...(typeof finalRun.dashboardUrl === 'string'
6449
+ ? { dashboardUrl: finalRun.dashboardUrl }
6450
+ : {}),
6451
+ ...(typeof finalRun.executionUrl === 'string'
6452
+ ? { executionUrl: finalRun.executionUrl }
6453
+ : {}),
6454
+ startedAt: finalRun.startedAt,
6455
+ finishedAt: finalRun.finishedAt,
5750
6456
  };
5751
6457
  }
5752
6458
  catch (err) {
@@ -5860,74 +6566,53 @@ export async function runTestRunAll(opts, deps = {}) {
5860
6566
  total: pollable.length,
5861
6567
  },
5862
6568
  };
5863
- await writeBatchJUnitReportIfRequested(opts, freshRunResults);
6569
+ const freshNameMap = opts.report === 'junit' && opts.reportFile !== undefined
6570
+ ? await buildTestNameMap(client, opts.projectId)
6571
+ : undefined;
6572
+ await writeBatchJUnitReportIfRequested(opts, freshRunResults, freshNameMap);
5864
6573
  out.print(jsonPayload);
5865
6574
  // CI-native output layer (issue #99): emitted before the gate throws below so
5866
6575
  // the artifacts land even when the batch exits non-zero. The summary file is a
5867
6576
  // machine artifact written regardless of --output mode; stdout stays owned by
5868
6577
  // the envelope above (plus Actions workflow commands, which Actions parses).
5869
- {
5870
- const env = deps.env ?? process.env;
5871
- const ghEnabled = opts.ghOutput === true || env.GITHUB_ACTIONS === 'true';
5872
- if (ghEnabled || opts.summaryFile !== undefined) {
5873
- const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
5874
- if (opts.summaryFile !== undefined) {
5875
- try {
5876
- writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
5877
- }
5878
- catch {
5879
- stderrFn(`[run] could not write --summary-file ${opts.summaryFile}; continuing`);
5880
- }
5881
- }
5882
- if (ghEnabled) {
5883
- const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
5884
- emitGithubOutputs(ciSummary, env, {
5885
- stdout: stdoutFn,
5886
- stderr: stderrFn,
5887
- appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
5888
- // Under --output json the envelope above owns stdout; workflow
5889
- // commands go to stderr instead (the Actions runner parses both
5890
- // streams), keeping the documented machine output parseable.
5891
- annotations: opts.output === 'json' ? stderrFn : stdoutFn,
5892
- }, { force: opts.ghOutput === true });
5893
- }
5894
- }
5895
- }
6578
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(jsonPayload)), opts, {
6579
+ env: deps.env ?? process.env,
6580
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
6581
+ stderr: stderrFn,
6582
+ }, 'run');
5896
6583
  // Rate-deferred tests were never dispatched → the batch is incomplete (exit 7),
5897
6584
  // mirroring `test rerun --all`. Checked before the failed-run throw so the
5898
6585
  // operator learns to retry the deferred set.
5899
6586
  if (deferred.length > 0) {
5900
6587
  throw new CLIError(`Batch run incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} rate-deferred (per-key run budget) — retry these individually after ~60s: ${deferred.map(d => d.testId).join(' ')}`, 7);
5901
6588
  }
5902
- if (timedOut > 0) {
5903
- const timedOutRunIds = freshRunResults
5904
- .filter(r => r.status === 'timeout')
5905
- .map(r => r.runId)
5906
- .filter(Boolean);
6589
+ // Shared exit-code precedence (auth 3 → typed operational ApiError → timeout 7
6590
+ // → generic fail 1) so `test run` and `testlist run` can't drift. This
6591
+ // supersedes the previous "fold every non-auth poll error into exit 1"
6592
+ // behaviour: a NOT_FOUND/RATE_LIMITED/… poll now propagates its real code.
6593
+ const failure = resolveWaitFailure(freshRunResults, { timeoutSeconds: opts.timeoutSeconds });
6594
+ if (failure)
6595
+ throw failure;
6596
+ // Hard conflicts (a run already in flight for the test that we could NOT
6597
+ // auto-resume — no `currentRunId` to poll) mean those tests never ran. In a
6598
+ // MIXED batch, the accepted/resumed runs above already made `pollable`
6599
+ // non-empty, so the all-conflict early-exit-6 branch didn't fire — without
6600
+ // this gate a passing resumable run would mask an unresolved hard conflict and
6601
+ // exit 0. Checked AFTER the failed gate (a real failure is the more actionable
6602
+ // headline; a batch with both still exits 1), matching the exit-6 the
6603
+ // all-conflict path returns. `conflicts` here holds only the hard ones —
6604
+ // resumable conflicts were split into the poll set above.
6605
+ if (conflicts.length > 0) {
5907
6606
  throw ApiError.fromEnvelope({
5908
6607
  error: {
5909
- code: 'UNSUPPORTED',
5910
- message: `${timedOut} run${timedOut !== 1 ? 's' : ''} timed out.`,
5911
- nextAction: [
5912
- ...timedOutRunIds.map(rid => `Resume: testsprite test wait ${rid}`),
5913
- ...timedOutRunIds.map(rid => `Cancel: testsprite test cancel ${rid}`),
5914
- ].join('\n'),
6608
+ code: 'CONFLICT',
6609
+ message: `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight and could not be resumed — not run.`,
6610
+ nextAction: `Wait for the in-flight run(s) to finish, then retry: ${conflicts.map(c => c.testId).join(' ')}`,
5915
6611
  requestId: 'local',
5916
- details: { timedOutRunIds, timeoutSeconds: opts.timeoutSeconds },
6612
+ details: { conflicts: conflicts.map(c => c.testId) },
5917
6613
  },
5918
6614
  });
5919
6615
  }
5920
- if (failed > 0) {
5921
- // An auth failure on any member is a batch-wide condition (the credential is
5922
- // bad, not the test) — propagate exit 3 so the operator fixes auth rather
5923
- // than chasing a "test failed" (exit 1). Other operational codes stay folded
5924
- // into the generic batch-failure exit 1; their per-member envelope is in JSON.
5925
- const authErr = freshRunResults.find(r => r.error?.exitCode === 3);
5926
- if (authErr) {
5927
- throw new CLIError(`${failed} run${failed !== 1 ? 's' : ''} failed — auth error (${authErr.error?.code}): ${authErr.error?.message}`, 3);
5928
- }
5929
- throw new CLIError(`${failed} run${failed !== 1 ? 's' : ''} failed.`, 1);
5930
- }
5931
6616
  // [P2] Return object reconstructed from post-retry mutable state (accepted,
5932
6617
  // deferred, conflicts) so the caller always sees what was actually dispatched,
5933
6618
  // not the stale initial batchResp. accepted here still holds the original
@@ -6229,16 +6914,7 @@ export async function runTestRerun(opts, deps = {}) {
6229
6914
  sleep: deps.sleep,
6230
6915
  shutdown: shutdownOf(deps),
6231
6916
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6232
- onTick: (run, elapsedMs) => {
6233
- const elapsed = Math.round(elapsedMs / 1000);
6234
- const s = run.stepSummary ?? {
6235
- total: 0,
6236
- completed: 0,
6237
- passedCount: 0,
6238
- failedCount: 0,
6239
- };
6240
- ticker.update(`Run ${run.runId} [${member.role}] — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
6241
- },
6917
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `[${member.role}]`)),
6242
6918
  resolveAlternate,
6243
6919
  });
6244
6920
  return { kind: 'terminal', run: finalRun };
@@ -6359,7 +7035,8 @@ export async function runTestRerun(opts, deps = {}) {
6359
7035
  const cancelHints = closureMembers
6360
7036
  .map(m => `testsprite test cancel ${m.runId}`)
6361
7037
  .join('\n');
6362
- stderrFn(`Closure members are still in progress (request timed out). Re-attach with:\n${reattachHints}\n` +
7038
+ stderrFn(`Request timed out. ${stillRunningAndBillingSubject(closureMembers.map(m => m.runId))} ` +
7039
+ `Re-attach with:\n${reattachHints}\n` +
6363
7040
  `Or cancel with:\n${cancelHints}`);
6364
7041
  throw fanOutErr;
6365
7042
  }
@@ -6462,6 +7139,15 @@ export async function runTestRerun(opts, deps = {}) {
6462
7139
  // never confirmed would let --wait exit 0. Observed-failed members are not
6463
7140
  // included; that's the future --fail-on-closure decision.
6464
7141
  const unobservedMembers = closureFailures.filter(f => f.unobserved);
7142
+ // §5 (unify with the batch fan-outs): an auth failure on an unobserved
7143
+ // closure member is batch-wide (a bad credential, not a bad test) and
7144
+ // non-retriable, so it must exit 3 — not be masked as the generic
7145
+ // unobserved-timeout 7. A poll-errored member's `status` holds the error
7146
+ // code; a timed-out member's is `'timeout'` (never an auth code).
7147
+ const authMember = unobservedMembers.find(m => isAuthCode(m.status));
7148
+ if (authMember) {
7149
+ throw new CLIError(`Closure member ${authMember.runId} hit an auth error (${authMember.status}) — the credential is bad, not the test.`, 3);
7150
+ }
6465
7151
  if (unobservedMembers.length > 0) {
6466
7152
  const unobservedIds = unobservedMembers.map(f => f.runId);
6467
7153
  const resumeHints = unobservedIds.map(runId => `testsprite test wait ${runId}`).join('\n') +
@@ -6493,6 +7179,7 @@ export async function runTestRerun(opts, deps = {}) {
6493
7179
  `resolved the verdict from the test record (testId=${tid}).`);
6494
7180
  },
6495
7181
  });
7182
+ const replayStartMs = Date.now();
6496
7183
  let finalRun;
6497
7184
  try {
6498
7185
  finalRun = await pollRunUntilTerminal(client, rerunResp.runId, {
@@ -6500,21 +7187,30 @@ export async function runTestRerun(opts, deps = {}) {
6500
7187
  sleep: deps.sleep,
6501
7188
  shutdown: shutdownOf(deps),
6502
7189
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6503
- onTick: (run, elapsedMs) => {
6504
- const elapsed = Math.round(elapsedMs / 1000);
6505
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
6506
- ticker.update(`Run ${run.runId} — ${run.status} (${s.completed}/${s.total} steps replay elapsed=${elapsed}s)`);
6507
- },
7190
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, '(replay)')),
6508
7191
  resolveAlternate,
6509
7192
  });
6510
7193
  }
6511
7194
  catch (err) {
6512
7195
  if (err instanceof TimeoutError) {
6513
7196
  ticker.finalize(`Run ${rerunResp.runId} — timed out after ${opts.timeoutSeconds}s`);
7197
+ // Mirror the RequestTimeoutError path: emit a partial run to stdout so
7198
+ // JSON consumers and AI agents can grab the runId and chain into
7199
+ // `testsprite test wait <runId>` without parsing the stderr error envelope.
7200
+ const timeoutPartial = { runId: rerunResp.runId, status: 'running' };
7201
+ out.print(timeoutPartial, data => {
7202
+ const p = data;
7203
+ return [
7204
+ `runId ${p.runId}`,
7205
+ `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
7206
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
7207
+ ].join('\n');
7208
+ });
6514
7209
  throw ApiError.fromEnvelope({
6515
7210
  error: {
6516
7211
  code: 'UNSUPPORTED',
6517
- message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${rerunResp.runId}.`,
7212
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${rerunResp.runId}. ` +
7213
+ stillRunningAndBillingSubject(rerunResp.runId),
6518
7214
  nextAction: `Resume polling: testsprite test wait ${rerunResp.runId}, or cancel it: testsprite test cancel ${rerunResp.runId}`,
6519
7215
  requestId: 'local',
6520
7216
  details: { runId: rerunResp.runId, timeoutSeconds: opts.timeoutSeconds },
@@ -6535,7 +7231,7 @@ export async function runTestRerun(opts, deps = {}) {
6535
7231
  `hint Cancel with: testsprite test cancel ${p.runId}`,
6536
7232
  ].join('\n');
6537
7233
  });
6538
- stderrFn(`Run ${rerunResp.runId} is still in progress (request timed out). ` +
7234
+ stderrFn(`Request timed out. ${stillRunningAndBillingSubject(rerunResp.runId)} ` +
6539
7235
  `Re-attach with: testsprite test wait ${rerunResp.runId}, or cancel with: testsprite test cancel ${rerunResp.runId}`);
6540
7236
  throw err;
6541
7237
  }
@@ -6576,10 +7272,7 @@ export async function runTestRerun(opts, deps = {}) {
6576
7272
  ticker.finalize();
6577
7273
  throw err;
6578
7274
  }
6579
- const elapsed = Math.round(Date.now() / 1000);
6580
- void elapsed;
6581
- const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
6582
- ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps replay)`);
7275
+ ticker.finalize(formatRunProgressLine(finalRun, Date.now() - replayStartMs, '(replay)'));
6583
7276
  // Probe the test type once (text mode only, best-effort) so a backend
6584
7277
  // rerun's card reads `n/a (backend)` even when the fallback never fired
6585
7278
  // (BE run rows finalize server-side now) — DEV-282.
@@ -6791,27 +7484,38 @@ export async function runTestRerun(opts, deps = {}) {
6791
7484
  const deferredIds = deferred.map(d => d.testId).join(' ');
6792
7485
  stderrFn(`nextAction: testsprite test rerun ${deferredIds}`);
6793
7486
  }
6794
- // D3: bounded deferred-retry loop for rerun --all (only under --wait).
6795
- // Up to MAX_DEFERRED_RETRIES attempts to re-dispatch still-deferred tests.
6796
- // Each attempt sleeps for Retry-After (if server provided it) or the default
6797
- // 61s, clamped to the remaining --timeout budget. Newly-accepted runs are
6798
- // merged into `accepted`; if still deferred after all attempts, fall through
6799
- // to the existing exit-7 path.
7487
+ // D3: budget-driven deferred-retry loop for rerun --all (only under --wait).
7488
+ // Re-dispatches still-deferred tests until they all clear OR the --timeout
7489
+ // budget is exhausted — a busy pool drains within the user's own timeout
7490
+ // instead of giving up after a fixed few tries and failing the run. Each
7491
+ // attempt sleeps 61s (clamped to the remaining budget); newly-accepted runs
7492
+ // merge into `accepted`; if still deferred when the budget runs out, fall
7493
+ // through to the existing exit-7 path. `maxDeferredAttempts` is a pure runaway
7494
+ // backstop (the deadline check below is the real stop), scaled to the timeout.
6800
7495
  const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
6801
7496
  const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
7497
+ // finding 1: reserve a poll window so the deferred-retry loop can't consume the
7498
+ // ENTIRE --timeout and leave the fan-out poll with nothing — which would report
7499
+ // already-finished runs as timeouts (exit 7) instead of their real verdicts
7500
+ // (a genuine failure is exit 1, not 7). One third of the budget, capped at 60s.
7501
+ const POLL_RESERVE_MS = Math.min(60_000, Math.floor((opts.timeoutSeconds * 1000) / 3));
7502
+ const maxDeferredAttempts = Math.max(MAX_DEFERRED_RETRIES, Math.ceil(opts.timeoutSeconds / 60) + 2);
6802
7503
  if (opts.wait) {
6803
- for (let attempt = 1; attempt <= MAX_DEFERRED_RETRIES && deferred.length > 0; attempt++) {
7504
+ for (let attempt = 1; attempt <= maxDeferredAttempts && deferred.length > 0; attempt++) {
6804
7505
  const remainingMs = batchDeadlineMs - Date.now();
6805
- if (remainingMs <= 0) {
6806
- stderrFn(`[deferred-retry] timeout budget exhausted before attempt ${attempt}/${MAX_DEFERRED_RETRIES} — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
7506
+ if (remainingMs <= POLL_RESERVE_MS) {
7507
+ stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
6807
7508
  break;
6808
7509
  }
6809
- const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs);
6810
- stderrFn(`[deferred-retry] attempt ${attempt}/${MAX_DEFERRED_RETRIES} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
7510
+ // §1: clamp to what's left ABOVE the reserve so the sleep itself can't run
7511
+ // the budget to zero (the loop only reaches here when remainingMs >
7512
+ // POLL_RESERVE_MS, so the difference is always positive).
7513
+ const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs - POLL_RESERVE_MS);
7514
+ stderrFn(`[deferred-retry] attempt ${attempt} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
6811
7515
  await sleepFn(sleepMs);
6812
7516
  const remainingAfterSleep = batchDeadlineMs - Date.now();
6813
- if (remainingAfterSleep <= 0) {
6814
- stderrFn(`[deferred-retry] timeout budget exhausted during sleep — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
7517
+ if (remainingAfterSleep <= POLL_RESERVE_MS) {
7518
+ stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
6815
7519
  break;
6816
7520
  }
6817
7521
  // Chunk the retry ids to stay within MAX_BATCH_RERUN_IDS cap.
@@ -6839,6 +7543,13 @@ export async function runTestRerun(opts, deps = {}) {
6839
7543
  ? idempotencyKey.slice(0, 256 - retrySuffix.length)
6840
7544
  : idempotencyKey;
6841
7545
  const retryKey = `${retryBase}${retrySuffix}`;
7546
+ // The retry chunk POST is deliberately NOT bound to the batch
7547
+ // deadline via an AbortSignal — same reasoning as the fresh-run retry
7548
+ // above: it seeds runs, so a mid-flight abort would leave the server
7549
+ // possibly having dispatched while this loop reports the chunk as
7550
+ // still-deferred, inviting a duplicate rerun on the user's next
7551
+ // invocation. The per-request timeout still bounds it; the sleeps +
7552
+ // poll stay deadline-aware.
6842
7553
  const retryChunkResp = await client.triggerBatchRerun({
6843
7554
  source: 'cli',
6844
7555
  testIds: chunk,
@@ -6935,6 +7646,16 @@ export async function runTestRerun(opts, deps = {}) {
6935
7646
  if (accepted.length === 0) {
6936
7647
  // [P2] Build output from post-retry mutable state including merged notFound.
6937
7648
  out.print({ ...batchResp, accepted, deferred, conflicts, notFound, advisories });
7649
+ // Nothing dispatched, but a --wait CI run still needs the exit-6/7 visible:
7650
+ // emit annotations + summary before the throw below (conflicts / deferred /
7651
+ // notFound fold in as non-passed rows). Without this an all-conflict or
7652
+ // all-deferred rerun fails CI silently. (Default notFound note is correct
7653
+ // here — a rerun not-found id genuinely has no run to replay.)
7654
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify({ accepted: [], deferred, conflicts, notFound })), opts, {
7655
+ env: deps.env ?? process.env,
7656
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
7657
+ stderr: stderrFn,
7658
+ }, 'rerun');
6938
7659
  if (deferred.length > 0) {
6939
7660
  throw new CLIError(`Batch rerun: no tests were accepted (${deferred.length} deferred). ` +
6940
7661
  `Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
@@ -6982,18 +7703,21 @@ export async function runTestRerun(opts, deps = {}) {
6982
7703
  sleep: deps.sleep,
6983
7704
  shutdown: shutdownOf(deps),
6984
7705
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6985
- onTick: (run, elapsedMs) => {
6986
- const elapsed = Math.round(elapsedMs / 1000);
6987
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
6988
- ticker.update(`Run ${run.runId} (${entry.testId}) — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
6989
- },
7706
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
6990
7707
  resolveAlternate,
6991
7708
  });
6992
7709
  return {
6993
7710
  testId: entry.testId,
7711
+ testTitle: finalRun.testTitle ?? null,
6994
7712
  runId: entry.runId,
6995
7713
  projectId: finalRun.projectId,
6996
7714
  status: finalRun.status,
7715
+ ...(typeof finalRun.dashboardUrl === 'string'
7716
+ ? { dashboardUrl: finalRun.dashboardUrl }
7717
+ : {}),
7718
+ ...(typeof finalRun.executionUrl === 'string'
7719
+ ? { executionUrl: finalRun.executionUrl }
7720
+ : {}),
6997
7721
  };
6998
7722
  }
6999
7723
  catch (err) {
@@ -7121,36 +7845,29 @@ export async function runTestRerun(opts, deps = {}) {
7121
7845
  total: accepted.length,
7122
7846
  },
7123
7847
  };
7124
- await writeBatchJUnitReportIfRequested(opts, rerunResults);
7848
+ const rerunNameMap = opts.report === 'junit' && opts.reportFile !== undefined
7849
+ ? await buildTestNameMap(client, opts.projectId)
7850
+ : undefined;
7851
+ await writeBatchJUnitReportIfRequested(opts, rerunResults, rerunNameMap);
7125
7852
  out.print(jsonPayload);
7126
7853
  // CI-native output layer (issue #99): batch-rerun parity with `run --all`.
7127
7854
  // Emitted before the exit-code gates below so the summary file / annotations
7128
7855
  // land even when the batch exits non-zero. Summary-file is a machine artifact
7129
7856
  // written regardless of --output mode; under --output json the envelope above
7130
7857
  // owns stdout, so ::error:: workflow commands go to stderr instead.
7131
- {
7132
- const env = deps.env ?? process.env;
7133
- const ghEnabled = opts.ghOutput === true || env.GITHUB_ACTIONS === 'true';
7134
- if (ghEnabled || opts.summaryFile !== undefined) {
7135
- const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
7136
- if (opts.summaryFile !== undefined) {
7137
- try {
7138
- writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
7139
- }
7140
- catch {
7141
- stderrFn(`[rerun] could not write --summary-file ${opts.summaryFile}; continuing`);
7142
- }
7143
- }
7144
- if (ghEnabled) {
7145
- const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
7146
- emitGithubOutputs(ciSummary, env, {
7147
- stdout: stdoutFn,
7148
- stderr: stderrFn,
7149
- appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
7150
- annotations: opts.output === 'json' ? stderrFn : stdoutFn,
7151
- }, { force: opts.ghOutput === true });
7152
- }
7153
- }
7858
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(jsonPayload)), opts, {
7859
+ env: deps.env ?? process.env,
7860
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
7861
+ stderr: stderrFn,
7862
+ }, 'rerun');
7863
+ // §5 (unify rerun with run --all / testlist run): auth is batch-wide — a bad
7864
+ // credential, not a bad test — and non-retriable, so it must win even over a
7865
+ // concurrent deferred/timeout. Run the shared helper's auth check BEFORE the
7866
+ // combined gate below, which would otherwise mask it as exit 7.
7867
+ if (rerunResults.some(r => r.error?.exitCode === 3)) {
7868
+ const authFailure = resolveWaitFailure(rerunResults, { timeoutSeconds: opts.timeoutSeconds });
7869
+ if (authFailure)
7870
+ throw authFailure;
7154
7871
  }
7155
7872
  // Determine exit code: timeout (deferred or any timeout) → 7; any fail → 1; all pass → 0
7156
7873
  if (deferred.length > 0 || timedOut > 0) {
@@ -7180,17 +7897,14 @@ export async function runTestRerun(opts, deps = {}) {
7180
7897
  },
7181
7898
  });
7182
7899
  }
7183
- if (failed > 0) {
7184
- // Auth failure on any member is a batch-wide condition — the credential is
7185
- // bad, not the test. Propagate exit 3 so the operator fixes auth rather than
7186
- // chasing a "rerun failed" (exit 1). Mirrors the identical logic already
7187
- // applied to runTestRunAll lines 5462-5468.
7188
- const authErr = rerunResults.find(r => r.error?.exitCode === 3);
7189
- if (authErr) {
7190
- throw new CLIError(`${failed} rerun${failed !== 1 ? 's' : ''} failed — auth error (${authErr.error?.code}): ${authErr.error?.message}`, 3);
7191
- }
7192
- throw new CLIError(`${failed} rerun${failed !== 1 ? 's' : ''} failed.`, 1);
7193
- }
7900
+ // Shared exit-code precedence for the failure tail. The combined
7901
+ // deferred/timeout gate above already fired for those, so only auth (3) →
7902
+ // typed operational ApiError → generic fail (1) remain — a NOT_FOUND /
7903
+ // RATE_LIMITED / … poll error now propagates its real code instead of folding
7904
+ // into exit 1 (matches `test run --all` / `testlist run`).
7905
+ const failure = resolveWaitFailure(rerunResults, { timeoutSeconds: opts.timeoutSeconds });
7906
+ if (failure)
7907
+ throw failure;
7194
7908
  // [P2] Return post-retry state including merged notFound so callers see the
7195
7909
  // final accounting (accepted = original BatchRerunAccepted[] dispatch list
7196
7910
  // as required by the BatchRerunResponse type; rerunResults is the polled
@@ -7372,6 +8086,18 @@ function renderArtifactGetWrittenText(data) {
7372
8086
  `files: ${data.files}`,
7373
8087
  ].join('\n');
7374
8088
  }
8089
+ /**
8090
+ * Shared `--skip-preflight` help text across the three commands
8091
+ * that trigger a run with a `--target-url` override (`create`,
8092
+ * `create-batch`, `run`). States the honest limitation up front: this CLI
8093
+ * probes from wherever it runs, not from the Lambda that executes the
8094
+ * test, so the probe is a heuristic, not a guarantee — hence the full
8095
+ * opt-out.
8096
+ */
8097
+ const SKIP_PREFLIGHT_HELP = 'skip the pre-charge --target-url reachability probe. The probe runs from this machine, not ' +
8098
+ 'from the Lambda that executes the test, so it can occasionally be wrong (e.g. an IP allowlist ' +
8099
+ 'that permits the Lambda but not this machine); use this flag when you know better. Zero network ' +
8100
+ 'calls when set.';
7375
8101
  export function createTestCommand(deps = {}) {
7376
8102
  const test = new Command('test').description('Inspect TestSprite tests');
7377
8103
  test
@@ -7431,15 +8157,19 @@ export function createTestCommand(deps = {}) {
7431
8157
  .option('--name <name>', 'human-readable test name (becomes `title` in storage)')
7432
8158
  .option('--description <text>', 'optional human description (≤ 2000 chars)')
7433
8159
  .option('--priority <prio>', 'optional priority — one of: p0, p1, p2, p3')
8160
+ .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
7434
8161
  .option('--code-file <path>', 'file containing the test code (≤ 350 KB)')
7435
8162
  .option('--plan-from <path>', 'JSON file with the full FE test definition — projectId, type, name, planSteps[] all live in the file ' +
7436
- '(≤ 256 KB; mutually exclusive with --code-file). In this mode --project/--type/--name/--description/--priority are ignored.')
8163
+ '(≤ 256 KB; mutually exclusive with --code-file). In this mode --project/--type/--name/--description/--priority/--step-timeout are ignored.')
7437
8164
  .option('--plan-template', 'print a minimal valid plan-file skeleton to stdout and exit (pure-local: no network, no credentials, ' +
7438
8165
  'ignores every other flag). Pipe to a file and edit: `--plan-template > plan.json`.', false)
7439
8166
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
7440
8167
  .option('--wait', 'with --run, poll until terminal status', false)
7441
8168
  .option('--timeout <s>', 'with --run --wait, max seconds to wait')
7442
- .option('--target-url <url>', 'with --run, override the project default env URL')
8169
+ .option('--target-url <url>', 'with --run, override the project default env URL. Before triggering, a reachability ' +
8170
+ 'preflight refuses obviously-dead targets (DNS failure, connection refused, a 502/503/504 ' +
8171
+ 'gateway error) so a doomed run never gets billed — see --skip-preflight.')
8172
+ .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
7443
8173
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
7444
8174
  .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], [])
7445
8175
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Use to declare upstream producer dependencies.', (val, prev) => [...(prev ?? []), val], [])
@@ -7495,6 +8225,8 @@ export function createTestCommand(deps = {}) {
7495
8225
  ignored.push('--description');
7496
8226
  if (cmdOpts.priority !== undefined)
7497
8227
  ignored.push('--priority');
8228
+ if (cmdOpts.stepTimeout !== undefined)
8229
+ ignored.push('--step-timeout');
7498
8230
  await runCreateFromPlan({
7499
8231
  ...resolveCommonOptions(command),
7500
8232
  planFrom: cmdOpts.planFrom,
@@ -7504,6 +8236,7 @@ export function createTestCommand(deps = {}) {
7504
8236
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
7505
8237
  timeoutIsDefault: cmdOpts.timeout === undefined,
7506
8238
  targetUrl: cmdOpts.targetUrl,
8239
+ skipPreflight: cmdOpts.skipPreflight === true,
7507
8240
  idempotencyKey: cmdOpts.idempotencyKey,
7508
8241
  ignoredFlags: ignored,
7509
8242
  }, deps);
@@ -7516,6 +8249,7 @@ export function createTestCommand(deps = {}) {
7516
8249
  name: cmdOpts.name,
7517
8250
  description: cmdOpts.description,
7518
8251
  priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
8252
+ stepTimeoutMs: parseStepTimeoutFlag(cmdOpts.stepTimeout, 'step-timeout'),
7519
8253
  codeFile: cmdOpts.codeFile,
7520
8254
  idempotencyKey: cmdOpts.idempotencyKey,
7521
8255
  // M3.3 chain flags:
@@ -7525,6 +8259,7 @@ export function createTestCommand(deps = {}) {
7525
8259
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
7526
8260
  timeoutIsDefault: cmdOpts.timeout === undefined,
7527
8261
  targetUrl: cmdOpts.targetUrl,
8262
+ skipPreflight: cmdOpts.skipPreflight === true,
7528
8263
  // M4 piece-2: BE dependency authoring flags.
7529
8264
  // Commander variadic collectors initialise to [] — treat empty array as undefined
7530
8265
  // so we don't send an empty array on the wire when no flags were passed.
@@ -7542,7 +8277,10 @@ export function createTestCommand(deps = {}) {
7542
8277
  .option('--max-concurrency <n>', 'with --run, max in-flight triggers at once (1-100, default: 50). The server caps run-triggers at 60/min/key; the CLI throttles to 50/min and auto-retries RATE_LIMITED responses client-side — raising this value does not bypass the server cap.')
7543
8278
  .option('--wait', 'with --run, poll each run until terminal status', false)
7544
8279
  .option('--timeout <s>', 'with --run --wait, per-run max seconds to wait (1-3600, default 600)')
7545
- .option('--target-url <url>', 'with --run, override the project default env URL for each run')
8280
+ .option('--target-url <url>', 'with --run, override the project default env URL for each run. Before the fan-out, a ' +
8281
+ 'reachability preflight refuses an obviously-dead target ONCE for the whole batch (DNS ' +
8282
+ 'failure, connection refused, a 502/503/504 gateway error) — see --skip-preflight.')
8283
+ .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
7546
8284
  .option('--idempotency-key <token>', 'opaque idempotency token for the batch create (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
7547
8285
  .addHelpText('after', GLOBAL_OPTS_HINT)
7548
8286
  .action(async (cmdOpts, command) => {
@@ -7555,6 +8293,7 @@ export function createTestCommand(deps = {}) {
7555
8293
  wait: cmdOpts.wait === true,
7556
8294
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
7557
8295
  targetUrl: cmdOpts.targetUrl,
8296
+ skipPreflight: cmdOpts.skipPreflight === true,
7558
8297
  idempotencyKey: cmdOpts.idempotencyKey,
7559
8298
  }, deps);
7560
8299
  });
@@ -7678,22 +8417,29 @@ export function createTestCommand(deps = {}) {
7678
8417
  });
7679
8418
  test
7680
8419
  .command('update <test-id>')
7681
- .description('Update test metadata — name, description, priority')
8420
+ .description('Update test metadata — name, description, priority, step timeout')
7682
8421
  .option('--name <name>', 'new human-readable test name')
7683
8422
  .option('--description <text>', 'new human description (≤ 2000 chars)')
7684
8423
  .option('--priority <prio>', 'new priority — one of: p0, p1, p2, p3')
8424
+ .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
8425
+ .option('--clear-step-timeout', 'clear the per-test step timeout and restore execution engine defaults', false)
7685
8426
  .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering.', (val, prev) => [...(prev ?? []), val], [])
7686
8427
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Declares an upstream producer dependency.', (val, prev) => [...(prev ?? []), val], [])
7687
8428
  .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
7688
8429
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
7689
8430
  .addHelpText('after', GLOBAL_OPTS_HINT)
7690
8431
  .action(async (testId, cmdOpts, command) => {
8432
+ if (cmdOpts.stepTimeout !== undefined && cmdOpts.clearStepTimeout === true) {
8433
+ throw localValidationError('step-timeout', '--step-timeout and --clear-step-timeout are mutually exclusive');
8434
+ }
7691
8435
  await runUpdate({
7692
8436
  ...resolveCommonOptions(command),
7693
8437
  testId,
7694
8438
  name: cmdOpts.name,
7695
8439
  description: cmdOpts.description,
7696
8440
  priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
8441
+ stepTimeoutMs: parseStepTimeoutFlag(cmdOpts.stepTimeout, 'step-timeout'),
8442
+ clearStepTimeout: cmdOpts.clearStepTimeout === true,
7697
8443
  produces: cmdOpts.produces,
7698
8444
  needs: cmdOpts.needs,
7699
8445
  category: cmdOpts.category,
@@ -7763,7 +8509,29 @@ export function createTestCommand(deps = {}) {
7763
8509
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
7764
8510
  '\nCtrl-C during --wait detaches only (the run keeps executing and billing);\n' +
7765
8511
  'stop it for real with: testsprite test cancel <run-id>')
7766
- .option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private IPs)')
8512
+ .option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private ' +
8513
+ 'IPs). Before triggering, a reachability preflight refuses an obviously-dead target (DNS ' +
8514
+ 'failure, connection refused, a 502/503/504 gateway error) so a doomed run never gets ' +
8515
+ 'billed. This CLI probes from wherever it runs, not from the Lambda that executes the ' +
8516
+ 'test, so it is a heuristic, not a guarantee — see --skip-preflight. Note: for a backend ' +
8517
+ 'test, --target-url itself is inert (its base URL is baked into its code) — but this bare ' +
8518
+ "`run` command has no way to know a test's type before triggering it, so the preflight " +
8519
+ 'still runs and can still refuse; use --skip-preflight if that surprises you.')
8520
+ .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
8521
+ .option('--local <port>', 'run against an app on THIS machine, reached through a TestSprite tunnel. The test runner ' +
8522
+ 'navigates to http://127.0.0.1:<port> and its traffic is proxied back to you for as long ' +
8523
+ 'as this command runs. Implies --wait (the tunnel closes when the command exits, so a ' +
8524
+ 'detached run could not finish) and cannot be combined with --target-url. Frontend tests ' +
8525
+ 'only. Before anything is minted or billed, the port is probed and a dead one is refused.')
8526
+ .option('--local-host <host>', `with --local, which loopback address to name in the run's target URL — one of ` +
8527
+ `${LOOPBACK_HOSTS.join(', ')} (default ${DEFAULT_LOCAL_HOST}). Use localhost if your app ` +
8528
+ `only answers on that name, or ::1 for an IPv6-only listener.`)
8529
+ .option('--tunnel-client <id>', 'with --local, attach to a tunnel already running under `testsprite tunnel start` instead ' +
8530
+ 'of opening a new one. The id is the non-secret handle that command prints; the tunnel ' +
8531
+ 'stays owned by that process and is not closed when this run finishes.')
8532
+ .option('--no-cancel-on-interrupt', 'with --local, leave the run executing (and billing) when this command stops waiting. By ' +
8533
+ 'default a --local run is cancelled at that point, because its tunnel closes with this ' +
8534
+ 'process and the run could then only fail.')
7767
8535
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
7768
8536
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
7769
8537
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
@@ -7776,6 +8544,7 @@ export function createTestCommand(deps = {}) {
7776
8544
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
7777
8545
  .option('--gh-output', 'with --wait (single test or --all): emit GitHub-native output (::error:: annotations per non-passed run; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
7778
8546
  .option('--summary-file <path>', 'with --wait (single test or --all): also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
8547
+ .option('--allow-empty', 'with --all: exit 0 when the run dispatches ZERO tests (all skipped / empty project / --filter matched nothing). Default: fail with exit 5 — a zero-dispatch run is a CI false-green')
7779
8548
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
7780
8549
  ' testsprite test run --all --project <id> run all project tests in wave order\n' +
7781
8550
  ' TESTSPRITE_PROJECT_ID=<id> testsprite test run --all use env default project\n' +
@@ -7803,12 +8572,45 @@ export function createTestCommand(deps = {}) {
7803
8572
  if (cmdOpts.filter !== undefined && cmdOpts.filter !== '' && !isAll) {
7804
8573
  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.');
7805
8574
  }
8575
+ // --local resolution. Every one of these refuses BEFORE any network
8576
+ // call, which is the contract `--local` is sold on: a mistake in the
8577
+ // invocation must never reach a run row, a credit spend, or a minted
8578
+ // tunnel credential.
8579
+ const localPort = cmdOpts.local !== undefined ? parseLocalPort(cmdOpts.local) : undefined;
8580
+ const usingLocal = localPort !== undefined;
8581
+ const effectiveWait = usingLocal || cmdOpts.wait === true;
8582
+ if (usingLocal && isAll) {
8583
+ throw localValidationError('local', '--local runs one test through one tunnel; --all fans out across a project. Run the ' +
8584
+ 'tests you want against your machine one at a time, or drop --local');
8585
+ }
8586
+ if (usingLocal && cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
8587
+ throw localValidationError('local', '--local and --target-url are mutually exclusive: --local runs against your own ' +
8588
+ 'machine through a tunnel, --target-url runs against an address the test runner can ' +
8589
+ 'already reach. Pass one');
8590
+ }
8591
+ // The three flags below are inert without --local. Silently ignoring
8592
+ // them would leave the caller believing something is in effect that is
8593
+ // not — the same rule --filter and the JUnit flags already follow.
8594
+ if (!usingLocal && cmdOpts.localHost !== undefined) {
8595
+ throw localValidationError('local-host', '--local-host only applies with --local (it names the loopback address the tunnel run ' +
8596
+ 'targets). Add --local <port>, or remove --local-host');
8597
+ }
8598
+ if (!usingLocal && cmdOpts.tunnelClient !== undefined) {
8599
+ throw localValidationError('tunnel-client', '--tunnel-client only applies with --local (it attaches the run to an already-running ' +
8600
+ 'tunnel). Add --local <port>, or remove --tunnel-client');
8601
+ }
8602
+ if (!usingLocal && cmdOpts.cancelOnInterrupt === false) {
8603
+ throw localValidationError('cancel-on-interrupt', '--no-cancel-on-interrupt only applies with --local. An ordinary run is never ' +
8604
+ 'cancelled when this command stops waiting — Ctrl-C detaches, and `testsprite test ' +
8605
+ 'cancel <run-id>` is the way to stop one');
8606
+ }
8607
+ const localHost = usingLocal ? normalizeLocalHost(cmdOpts.localHost) : undefined;
7806
8608
  const report = parseJUnitReportFormat(cmdOpts.report);
7807
8609
  assertJUnitReportOptions({
7808
8610
  report,
7809
8611
  reportFile: cmdOpts.reportFile,
7810
8612
  reportSuiteName: cmdOpts.reportSuiteName,
7811
- wait: cmdOpts.wait === true,
8613
+ wait: effectiveWait,
7812
8614
  batchPath: isAll,
7813
8615
  });
7814
8616
  // --gh-output / --summary-file reduce a --wait run's terminal result into
@@ -7816,10 +8618,10 @@ export function createTestCommand(deps = {}) {
7816
8618
  // enqueueing, before any terminal result exists) but apply to BOTH a single
7817
8619
  // <test-id> run and the --all batch. Without --wait they would silently
7818
8620
  // no-op — reject loudly (same rule as --filter and the JUnit report flags).
7819
- if (cmdOpts.ghOutput === true && cmdOpts.wait !== true) {
8621
+ if (cmdOpts.ghOutput === true && !effectiveWait) {
7820
8622
  throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
7821
8623
  }
7822
- if (cmdOpts.summaryFile !== undefined && cmdOpts.wait !== true) {
8624
+ if (cmdOpts.summaryFile !== undefined && !effectiveWait) {
7823
8625
  throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
7824
8626
  }
7825
8627
  if (isAll) {
@@ -7839,7 +8641,7 @@ export function createTestCommand(deps = {}) {
7839
8641
  ...resolveCommonOptions(command),
7840
8642
  projectId,
7841
8643
  nameFilter: cmdOpts.filter,
7842
- wait: cmdOpts.wait === true,
8644
+ wait: effectiveWait,
7843
8645
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
7844
8646
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
7845
8647
  DEFAULT_BATCH_RUN_CONCURRENCY,
@@ -7849,15 +8651,40 @@ export function createTestCommand(deps = {}) {
7849
8651
  reportSuiteName: cmdOpts.reportSuiteName,
7850
8652
  ghOutput: cmdOpts.ghOutput === true,
7851
8653
  summaryFile: cmdOpts.summaryFile,
8654
+ allowEmpty: cmdOpts.allowEmpty === true,
7852
8655
  }, deps);
7853
8656
  return;
7854
8657
  }
8658
+ // `--local` implies `--wait`: for a self-minted tunnel the tunnel's
8659
+ // lifetime is this process's lifetime, so returning early would doom the
8660
+ // run it just started. Announced rather than assumed — a caller who did
8661
+ // not type --wait should learn why the command is now blocking.
8662
+ //
8663
+ // The reason splits on how the tunnel was obtained. An adopted one
8664
+ // (--tunnel-client) outlives this process, so "the tunnel closes when
8665
+ // this command exits" is simply false there, and it is the sentence a
8666
+ // reader would act on: told that, someone deciding whether to background
8667
+ // this command concludes the wrong thing about their own tunnel.
8668
+ const commonOpts = resolveCommonOptions(command);
8669
+ if (usingLocal && cmdOpts.wait !== true && commonOpts.output !== 'json') {
8670
+ const adopted = cmdOpts.tunnelClient !== undefined;
8671
+ (deps.stderr ?? ((line) => process.stderr.write(`${line}\n`)))(adopted
8672
+ ? '[advisory] --local implies --wait: the run is followed to a verdict rather than ' +
8673
+ 'detached. The tunnel you attached to stays open — this command does not close it.'
8674
+ : '[advisory] --local implies --wait: the tunnel closes when this command exits, so ' +
8675
+ 'the run is followed to a verdict rather than detached.');
8676
+ }
7855
8677
  // Single test-id path (unchanged M3.3 behavior).
7856
8678
  await runTestRun({
7857
- ...resolveCommonOptions(command),
8679
+ ...commonOpts,
7858
8680
  testId: testIdArg,
7859
8681
  targetUrl: cmdOpts.targetUrl,
7860
- wait: cmdOpts.wait === true,
8682
+ skipPreflight: cmdOpts.skipPreflight === true,
8683
+ ...(localPort !== undefined ? { localPort } : {}),
8684
+ ...(localHost !== undefined ? { localHost } : {}),
8685
+ ...(cmdOpts.tunnelClient !== undefined ? { tunnelClientId: cmdOpts.tunnelClient } : {}),
8686
+ cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
8687
+ wait: effectiveWait,
7861
8688
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
7862
8689
  // B2(c): tell runTestRun whether --timeout was explicitly provided.
7863
8690
  timeoutIsDefault: cmdOpts.timeout === undefined,
@@ -8320,15 +9147,118 @@ export function resolveWaitRequestTimeoutMs(opts) {
8320
9147
  const cover = Math.min(opts.timeoutSeconds * 1000 + WAIT_REQUEST_TIMEOUT_CUSHION_MS, REQUEST_TIMEOUT_MAX_MS);
8321
9148
  return Math.max(base, cover);
8322
9149
  }
8323
- function makeClient(opts, deps) {
9150
+ function makeClient(opts, deps, shutdownSignal = shutdownOf(deps).signal) {
8324
9151
  return makeHttpClient(opts, {
8325
9152
  env: deps.env,
8326
9153
  credentialsPath: deps.credentialsPath,
8327
9154
  fetchImpl: deps.fetchImpl,
8328
9155
  stderr: deps.stderr,
8329
- shutdownSignal: shutdownOf(deps).signal,
9156
+ shutdownSignal,
8330
9157
  });
8331
9158
  }
9159
+ /**
9160
+ * Run one request under a total deadline that is independent of Ctrl-C.
9161
+ *
9162
+ * Mint and trigger responses carry the only handles that let us undo the
9163
+ * server-side effects they may already have committed. A first signal is
9164
+ * therefore allowed to request shutdown, but cannot tear either response down
9165
+ * before we learn the clientId/runId needed for cleanup. The total deadline
9166
+ * still bounds all HTTP retries and their sleeps end to end.
9167
+ */
9168
+ async function withUninterruptibleRequest(opts, deps, timeoutMs, operation) {
9169
+ const deadline = new AbortController();
9170
+ const timer = setTimeout(() => {
9171
+ deadline.abort(new RequestTimeoutError(timeoutMs));
9172
+ }, timeoutMs);
9173
+ timer.unref?.();
9174
+ try {
9175
+ return await operation(makeClient({ ...opts, requestTimeoutMs: timeoutMs }, deps, deadline.signal));
9176
+ }
9177
+ finally {
9178
+ clearTimeout(timer);
9179
+ }
9180
+ }
9181
+ /** Make `start()` reject promptly when the armed lifecycle receives a signal. */
9182
+ function shutdownAwareTunnelClientFactory(createClient, signal) {
9183
+ return options => {
9184
+ const client = createClient(options);
9185
+ return {
9186
+ start: async () => {
9187
+ if (signal.aborted)
9188
+ throw signal.reason;
9189
+ await new Promise((resolve, reject) => {
9190
+ const onAbort = () => reject(signal.reason);
9191
+ signal.addEventListener('abort', onAbort, { once: true });
9192
+ client.start().then(() => {
9193
+ signal.removeEventListener('abort', onAbort);
9194
+ resolve();
9195
+ }, err => {
9196
+ signal.removeEventListener('abort', onAbort);
9197
+ reject(err);
9198
+ });
9199
+ });
9200
+ },
9201
+ stop: () => {
9202
+ const stopping = client.stop();
9203
+ if (!signal.aborted)
9204
+ return stopping;
9205
+ // `TunnelClient.stop()` synchronously flips its running flag before
9206
+ // its first await. Do not let a still-CONNECTING WebSocket delay the
9207
+ // binding DELETE after Ctrl-C; observe the eventual rejection only to
9208
+ // avoid an unhandled promise.
9209
+ void stopping.catch(() => { });
9210
+ return Promise.resolve();
9211
+ },
9212
+ };
9213
+ };
9214
+ }
9215
+ /**
9216
+ * A client for teardown work that must survive an interrupt.
9217
+ *
9218
+ * `makeClient` composes the process shutdown signal into every request, which
9219
+ * is right for the work a Ctrl-C is meant to abandon — and wrong for the two
9220
+ * calls that only exist BECAUSE of the Ctrl-C: deleting the tunnel binding and
9221
+ * cancelling the doomed run. Composed with an already-aborted signal, those
9222
+ * requests never leave the machine, and the user is left holding a live
9223
+ * credential and a burning run.
9224
+ *
9225
+ * The timeout is deliberately short and fixed rather than inherited: teardown
9226
+ * happens while the user is waiting for their prompt back, and a stalled
9227
+ * cleanup call must not out-live their patience.
9228
+ */
9229
+ function makeDetachedClient(opts, deps, operationSignal) {
9230
+ return makeHttpClient({ ...opts, requestTimeoutMs: TEARDOWN_OPERATION_TIMEOUT_MS }, {
9231
+ env: deps.env,
9232
+ credentialsPath: deps.credentialsPath,
9233
+ fetchImpl: deps.fetchImpl,
9234
+ stderr: deps.stderr,
9235
+ // Detached from the process signal, but still bounded end to end. The
9236
+ // HTTP retry sleeper listens to shutdownSignal, so this operation signal
9237
+ // cuts both in-flight attempts and the backoff between them.
9238
+ shutdownSignal: operationSignal,
9239
+ });
9240
+ }
9241
+ async function withTeardownDeadline(opts, deps, operation) {
9242
+ const deadline = new AbortController();
9243
+ const timer = setTimeout(() => {
9244
+ deadline.abort(new RequestTimeoutError(TEARDOWN_OPERATION_TIMEOUT_MS));
9245
+ }, TEARDOWN_OPERATION_TIMEOUT_MS);
9246
+ timer.unref?.();
9247
+ const shutdown = deps.shutdown ?? globalShutdown;
9248
+ try {
9249
+ return await shutdown.runCriticalOperation(() => operation(makeDetachedClient(opts, deps, deadline.signal)));
9250
+ }
9251
+ finally {
9252
+ clearTimeout(timer);
9253
+ }
9254
+ }
9255
+ async function deleteTunnelForCleanup(opts, deps, clientId) {
9256
+ await withTeardownDeadline(opts, deps, client => client.delete(`/tunnel/${encodeURIComponent(clientId)}`, {
9257
+ allowNoContent: true,
9258
+ }));
9259
+ }
9260
+ /** See {@link makeDetachedClient}. */
9261
+ const TEARDOWN_OPERATION_TIMEOUT_MS = 10_000;
8332
9262
  function makeOutput(mode, deps) {
8333
9263
  return new Output(mode, {
8334
9264
  stdout: deps.stdout,
@@ -8603,6 +9533,9 @@ function renderTestText(t) {
8603
9533
  if (typeof t.planStepCount === 'number') {
8604
9534
  lines.push(`planSteps: ${t.planStepCount}`);
8605
9535
  }
9536
+ if (typeof t.stepTimeoutMs === 'number') {
9537
+ lines.push(`stepTimeout: ${t.stepTimeoutMs} ms (applies to every step)`);
9538
+ }
8606
9539
  // Surface backend dependency declarations when present.
8607
9540
  if (Array.isArray(t.produces) && t.produces.length > 0) {
8608
9541
  lines.push(`produces: ${t.produces.join(', ')}`);
@@ -9010,8 +9943,645 @@ function createTestCodeCommand(deps) {
9010
9943
  });
9011
9944
  return code;
9012
9945
  }
9946
+ // ---------------------------------------------------------------------------
9947
+ // `test plan generate` / `test plan accept` — DEV-384 V3-B
9948
+ // ---------------------------------------------------------------------------
9949
+ /** Default `--timeout` for `test plan generate` (design-doc §3.1): a fresh
9950
+ * frontend project runs browser exploration, which takes minutes — the runs
9951
+ * default (600s) would routinely cut it short. */
9952
+ const PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS = 1800;
9953
+ /** Cap on the F1 pre-trigger baseline read — best-effort display data must
9954
+ * never hold up the real work (review follow-up). */
9955
+ const PLAN_BASELINE_READ_TIMEOUT_MS = 10_000;
9956
+ /** `--project` is a flag (not a positional) on both plan-generation leaves —
9957
+ * route through the house helpers so `TESTSPRITE_PROJECT_ID` works here the
9958
+ * same as on every other command (DEV-384 review F5). */
9959
+ function requirePlanProjectId(projectId, deps) {
9960
+ const resolved = resolveProjectId(projectId, deps);
9961
+ requireProjectId(resolved);
9962
+ return resolved;
9963
+ }
9964
+ /**
9965
+ * Normalize `--only` tokens: split comma-separated entries, trim, drop
9966
+ * empties, dedupe (order-preserving). Returns `undefined` when the flag was
9967
+ * absent; throws when the flag was supplied but named no usable id.
9968
+ */
9969
+ function normalizePlanOnlyIds(raw) {
9970
+ if (raw === undefined)
9971
+ return undefined;
9972
+ const ids = [];
9973
+ const seen = new Set();
9974
+ for (const token of raw) {
9975
+ for (const piece of token.split(',')) {
9976
+ const id = piece.trim();
9977
+ if (id.length === 0 || seen.has(id))
9978
+ continue;
9979
+ seen.add(id);
9980
+ ids.push(id);
9981
+ }
9982
+ }
9983
+ if (ids.length === 0) {
9984
+ throw localValidationError('only', 'requires at least one proposal id');
9985
+ }
9986
+ return ids;
9987
+ }
9988
+ /**
9989
+ * Fallback `nextAction` texts for the plan-generation error reasons
9990
+ * (design-doc §7/§8: every precondition failure names its exact fix). The
9991
+ * backend facade already ships these texts; this map is the CLI-side
9992
+ * FALLBACK applied only when the envelope's `nextAction` is empty (same
9993
+ * convention as the FEATURE_GATED `/pricing` fallback) — backend-supplied
9994
+ * text always passes through unchanged.
9995
+ */
9996
+ function planFixNextAction(reason, projectId, categoryCount) {
9997
+ switch (reason) {
9998
+ case 'v3_required':
9999
+ return ('Plan generation runs on the V3 platform and your account has not been migrated yet ' +
10000
+ '(it will be soon). Until then, generate test plans in the Portal.');
10001
+ case 'environment_url_missing':
10002
+ return `Set the app URL first: testsprite project update ${projectId} --url https://staging.your-app.com`;
10003
+ case 'no_processed_inputs':
10004
+ return (`Upload your API documentation: testsprite project docs upload <file> --project ${projectId} --role api-doc ` +
10005
+ '(or add sources in the Portal — upload a document, give the assistant a link, or paste it). ' +
10006
+ 'If you just added a source, it may still be processing — retry shortly.');
10007
+ case 'no_plannable_categories':
10008
+ // Mirrors the server's own 0 / 1 / n split: zero categories is
10009
+ // reachable on a frontend project too, where "upload a fuller API
10010
+ // document" cannot apply.
10011
+ if (categoryCount === 0) {
10012
+ return ('The strategy is ready but has no categories, so there is nothing to plan test cases ' +
10013
+ 'against. Retrying will not change this. Regenerate the strategy in the Portal, then run ' +
10014
+ 'this again.');
10015
+ }
10016
+ return ((categoryCount === 1
10017
+ ? 'The strategy is ready, but its only category has no endpoint to attach a test to, so '
10018
+ : 'The strategy is ready, but none of its categories has an endpoint to attach a test to, so ') +
10019
+ 'there is nothing to plan against. Retrying will not change this. Review the strategy in the ' +
10020
+ 'Portal; if your API documentation does not describe the endpoints, upload a fuller document ' +
10021
+ `(testsprite project docs upload <file> --project ${projectId} --role api-doc) and regenerate ` +
10022
+ 'the strategy there, then run this again.');
10023
+ case 'nothing_staged':
10024
+ return `Generate proposals first: testsprite test plan generate --project ${projectId}`;
10025
+ default:
10026
+ return undefined;
10027
+ }
10028
+ }
10029
+ /** Apply {@link planFixNextAction} to an ApiError whose envelope lacks a
10030
+ * `nextAction`; every other error passes through untouched. */
10031
+ function withPlanFixNextAction(err, projectId) {
10032
+ if (!(err instanceof ApiError))
10033
+ return err;
10034
+ if (err.nextAction !== '')
10035
+ return err;
10036
+ const reason = err.getDetail('reason', (v) => typeof v === 'string');
10037
+ if (reason === undefined)
10038
+ return err;
10039
+ const categoryCount = err.getDetail('categoryCount', (v) => typeof v === 'number');
10040
+ const nextAction = planFixNextAction(reason, projectId, categoryCount);
10041
+ if (nextAction === undefined)
10042
+ return err;
10043
+ return new ApiError({
10044
+ code: err.code,
10045
+ message: err.message,
10046
+ nextAction,
10047
+ requestId: err.requestId,
10048
+ details: err.details,
10049
+ }, err.httpStatus, err.retryAfterMs);
10050
+ }
10051
+ /** Local envelope for "accept with nothing staged" — same shape/reason the
10052
+ * server emits (412 `nothing_staged`, exit 6) so scripts can't tell whether
10053
+ * the CLI or the facade caught it first. */
10054
+ function planNothingStagedError(projectId) {
10055
+ return ApiError.fromEnvelope({
10056
+ error: {
10057
+ code: 'PRECONDITION_FAILED',
10058
+ message: 'No proposals are staged for this project — there is nothing to accept.',
10059
+ nextAction: planFixNextAction('nothing_staged', projectId),
10060
+ requestId: 'local',
10061
+ details: { projectId, reason: 'nothing_staged' },
10062
+ },
10063
+ });
10064
+ }
10065
+ /** `52s` under a minute, `4m10s` above (design §3.1 ticker examples). */
10066
+ function formatPlanElapsed(elapsedMs) {
10067
+ const totalSeconds = Math.max(0, Math.round(elapsedMs / 1000));
10068
+ if (totalSeconds < 60)
10069
+ return `${totalSeconds}s`;
10070
+ const minutes = Math.floor(totalSeconds / 60);
10071
+ const seconds = totalSeconds % 60;
10072
+ return `${minutes}m${String(seconds).padStart(2, '0')}s`;
10073
+ }
10074
+ /** One in-place ticker line per generation status (design §3.2). */
10075
+ function planTickerLine(plans, elapsedMs) {
10076
+ const elapsed = formatPlanElapsed(elapsedMs);
10077
+ const generation = plans.generation;
10078
+ switch (generation.status) {
10079
+ case 'exploring': {
10080
+ const progress = generation.progress;
10081
+ return progress !== undefined
10082
+ ? `exploring app… (resources ${progress.resourcesReady}/${progress.resourcesTotal}, ${elapsed})`
10083
+ : `exploring app… (${elapsed})`;
10084
+ }
10085
+ case 'strategizing':
10086
+ return `generating strategy… (${elapsed})`;
10087
+ case 'proposing':
10088
+ return `proposing tests… (${elapsed})`;
10089
+ case 'failed':
10090
+ return `generation failed (${elapsed})`;
10091
+ case 'idle':
10092
+ return plans.proposals.length > 0
10093
+ ? `proposals staged (${elapsed})`
10094
+ : `starting next stage… (${elapsed})`;
10095
+ }
10096
+ }
10097
+ /** Sum of the best-effort `credits.charged` amounts (0 when absent). */
10098
+ function planCreditsUsed(plans) {
10099
+ return (plans.credits?.charged ?? []).reduce((sum, c) => sum + c.amount, 0);
10100
+ }
10101
+ /**
10102
+ * THIS invocation's spend: the settled read's per-action charged totals minus
10103
+ * the pre-trigger baseline's (DEV-935 / review F1 — the wire block is a
10104
+ * LIFETIME project total, so printing its sum as "credits used" reported
10105
+ * all-time spend on re-runs that charged nothing). `null` = unknown (no
10106
+ * baseline snapshot, or either read lacks the best-effort block) — the
10107
+ * caller omits the figure rather than printing a lifetime number.
10108
+ */
10109
+ function planCreditsDelta(baseline, settled) {
10110
+ if (baseline?.credits?.charged === undefined || settled.credits?.charged === undefined) {
10111
+ return null;
10112
+ }
10113
+ // DEV-935: a facade-side billing failure degrades the block to
10114
+ // `{charged: [], balance: null}` — `charged` is DEFINED there, so without
10115
+ // this guard a degraded read makes the other read's lifetime totals print
10116
+ // as this run's spend (the F1 misreport, back through the degrade window).
10117
+ // A healthy block always carries a numeric balance.
10118
+ if (baseline.credits.balance === null || settled.credits.balance === null) {
10119
+ return null;
10120
+ }
10121
+ const before = new Map(baseline.credits.charged.map(c => [c.action, c.amount]));
10122
+ let delta = 0;
10123
+ for (const c of settled.credits.charged) {
10124
+ delta += Math.max(0, c.amount - (before.get(c.action) ?? 0));
10125
+ }
10126
+ return delta;
10127
+ }
10128
+ /** ` (credits used: N, balance: M)` — `creditsUsed` is this invocation's
10129
+ * delta (omitted when 0 or unknown); balance is the settled read's current
10130
+ * figure. Empty string when the facade couldn't fill either. */
10131
+ function planCreditsSuffix(plans, creditsUsed) {
10132
+ const parts = [];
10133
+ if (creditsUsed !== null && creditsUsed > 0)
10134
+ parts.push(`credits used: ${creditsUsed}`);
10135
+ const balance = plans.credits?.balance;
10136
+ if (balance !== undefined && balance !== null)
10137
+ parts.push(`balance: ${balance}`);
10138
+ return parts.length > 0 ? ` (${parts.join(', ')})` : '';
10139
+ }
10140
+ /** Auto-width column helper for the proposals table. */
10141
+ function planTableColumn(header, render) {
10142
+ return {
10143
+ header,
10144
+ width: rows => Math.max(header.length, ...rows.map(r => render(r.proposal, r.index).length), 1),
10145
+ render: r => render(r.proposal, r.index),
10146
+ };
10147
+ }
10148
+ /** The staged-proposals table. Every row prints its stable `proposalId` —
10149
+ * that id is what `accept --only` consumes (design §3.3). */
10150
+ function renderPlanProposalsTable(proposals) {
10151
+ const rows = proposals.map((proposal, index) => ({ proposal, index }));
10152
+ const columns = [
10153
+ planTableColumn('#', (_p, i) => String(i + 1)),
10154
+ planTableColumn('ID', p => p.proposalId),
10155
+ planTableColumn('TITLE', p => (p.title.length > 48 ? `${p.title.slice(0, 47)}…` : p.title)),
10156
+ planTableColumn('FEATURE', p => `${p.category}/${p.feature}`),
10157
+ planTableColumn('PRIORITY', p => p.priority),
10158
+ planTableColumn('TYPE', p => p.type),
10159
+ ];
10160
+ return renderTextTable(rows, columns);
10161
+ }
10162
+ /** Text card for a settled successful generate (or `--dry-run`). */
10163
+ /** Exported for the renderer-level spec: the zero-proposals branch is not
10164
+ * reachable through `runGenerationLadder` today (after the proposals rung it
10165
+ * polls until staged/failed/timeout), so it is pinned directly. */
10166
+ export function renderPlanGenerateResultText(plans, projectId, creditsUsed, skippedCategories = null) {
10167
+ const count = plans.proposals.length;
10168
+ if (count === 0) {
10169
+ return [
10170
+ `0 test-case proposals staged${planCreditsSuffix(plans, creditsUsed)}`,
10171
+ // The skip count matters MOST here: a batch already narrowed to the
10172
+ // plannable categories that still settled at zero points at the
10173
+ // strategy, not at a re-run (which would bill again for the same result).
10174
+ ...renderSkippedCategoriesLine(skippedCategories, { staged: false }),
10175
+ `hint: nothing is staged for review — run: testsprite test plan generate --project ${projectId}`,
10176
+ ].join('\n');
10177
+ }
10178
+ const noun = count === 1 ? 'proposal' : 'proposals';
10179
+ return [
10180
+ `${count} test-case ${noun} staged for review${planCreditsSuffix(plans, creditsUsed)}`,
10181
+ ...renderSkippedCategoriesLine(skippedCategories, { staged: true }),
10182
+ '',
10183
+ renderPlanProposalsTable(plans.proposals),
10184
+ '',
10185
+ 'next',
10186
+ ` review the list above, then: testsprite test plan accept --project ${projectId}`,
10187
+ ` accept a subset with: testsprite test plan accept --project ${projectId} --only <id ...>`,
10188
+ ' (or review visually in the Portal before accepting)',
10189
+ ].join('\n');
10190
+ }
10191
+ /** DEV-1008 — one line when the proposals stage left strategy categories out
10192
+ * because they have no endpoint to attach a test to. The stage is charged
10193
+ * flat, so without this the caller cannot tell a partial plan from a full
10194
+ * one. Empty when nothing was skipped (the common case). */
10195
+ function renderSkippedCategoriesLine(skippedCategories, opts) {
10196
+ if (skippedCategories === null || skippedCategories <= 0)
10197
+ return [];
10198
+ const noun = skippedCategories === 1 ? 'category' : 'categories';
10199
+ const head = `note: ${skippedCategories} strategy ${noun} skipped — no endpoint to attach a test to ` +
10200
+ '(cross-cutting themes such as authorization or pagination)';
10201
+ return [
10202
+ opts.staged
10203
+ ? `${head}; the proposals above cover the rest.`
10204
+ : `${head}; the remaining categories produced nothing. Review the strategy in the Portal ` +
10205
+ 'before re-running — a re-run is charged again and will give the same result.',
10206
+ ];
10207
+ }
10208
+ /** Text card for a server-side stage failure (exit 1 follows via the thrown
10209
+ * INTERNAL envelope; earlier completed stages stay done — a re-run resumes). */
10210
+ function renderPlanGenerateFailedText(plans, projectId) {
10211
+ const generation = plans.generation;
10212
+ const lines = [`generation failed${generation.errorCode ? ` (${generation.errorCode})` : ''}`];
10213
+ if (generation.errorMessage)
10214
+ lines.push(` ${generation.errorMessage}`);
10215
+ lines.push(` completed stages stay done — retry with: testsprite test plan generate --project ${projectId}`);
10216
+ return lines.join('\n');
10217
+ }
10218
+ function makePlanGeneratePartial(projectId, lastSeen) {
10219
+ return {
10220
+ projectId,
10221
+ status: 'running',
10222
+ generationStatus: lastSeen?.generation.status ?? null,
10223
+ proposalsStaged: lastSeen?.proposals.length ?? 0,
10224
+ };
10225
+ }
10226
+ function renderPlanGeneratePartialText(partial, reason) {
10227
+ const lines = [`projectId ${partial.projectId}`, `status running (${reason})`];
10228
+ if (partial.generationStatus !== null) {
10229
+ lines.push(`stage ${partial.generationStatus}`);
10230
+ }
10231
+ lines.push(`hint Re-attach with: testsprite test plan generate --project ${partial.projectId}`);
10232
+ return lines.join('\n');
10233
+ }
10234
+ /**
10235
+ * `test plan generate --project <id>` — DEV-384 V3-B.
10236
+ *
10237
+ * Drives the server's generation ladder (exploration → strategy →
10238
+ * proposals) through `runGenerationLadder` and renders the staged
10239
+ * proposals. Exit 0 on staged proposals, 1 on a server-side stage failure,
10240
+ * 7 on timeout (typed `UNSUPPORTED` envelope — the raw ladder timeout is
10241
+ * not a CLI error), 130/143 on Ctrl-C detach (honest: work and charges
10242
+ * continue server-side), plus the usual catalog exits for trigger errors
10243
+ * (412 → 6 with the exact fix command, 402 → 12, 404 → 4, 429 → 11).
10244
+ */
10245
+ export async function runPlanGenerate(opts, deps = {}) {
10246
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
10247
+ const out = makeOutput(opts.output, deps);
10248
+ const projectId = requirePlanProjectId(opts.projectId, deps);
10249
+ assertIdempotencyKey(opts.idempotencyKey);
10250
+ if (opts.dryRun) {
10251
+ // Zero network, zero charges: resolve both canned samples directly
10252
+ // (no fetch — even the canned dry-run fetch is bypassed, matching the
10253
+ // `test run --dry-run` convention) and render the settled success shape.
10254
+ const client = makeClient(opts, deps);
10255
+ const plans = findSampleOrThrow('GET', `/api/cli/v1/projects/${encodeURIComponent(projectId)}/plans`).body();
10256
+ // Dry-run has no baseline to diff; teach the credits line from the
10257
+ // canned block's sum (everything here is canned anyway).
10258
+ const canned = planCreditsUsed(plans);
10259
+ const payload = { projectId, creditsUsedThisInvocation: canned, ...plans };
10260
+ out.print(payload, () => renderPlanGenerateResultText(plans, projectId, canned));
10261
+ void client; // constructed so dry-run still validates --endpoint-url etc.
10262
+ return payload;
10263
+ }
10264
+ const idempotencyKey = opts.idempotencyKey ?? `cli-plan-gen-${randomUUID()}`;
10265
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
10266
+ stderrFn(`idempotency-key: ${idempotencyKey}`);
10267
+ }
10268
+ // D4: the ladder is a long wait bounded by --timeout — raise the
10269
+ // per-request window to cover it (same as every `--wait` path).
10270
+ const client = makeClient({
10271
+ ...opts,
10272
+ requestTimeoutMs: resolveWaitRequestTimeoutMs({
10273
+ wait: true,
10274
+ timeoutSeconds: opts.timeoutSeconds,
10275
+ requestTimeoutMs: opts.requestTimeoutMs,
10276
+ }),
10277
+ }, deps);
10278
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
10279
+ // Upgraded to the server-resolved V3 id by the first ACCEPTED trigger
10280
+ // response. KNOWN LIMITATION (DEV-384 review F8): when the very first
10281
+ // trigger 409-attaches, no trigger response ever arrives and neither the
10282
+ // 409 envelope nor the `GET /plans` read carries the resolved id, so the
10283
+ // output keeps the caller's input id (a V2 id still polls fine through the
10284
+ // migration bridge). Closing it needs the id on one of those wires.
10285
+ let resolvedProjectId = projectId;
10286
+ let lastSeen = null;
10287
+ try {
10288
+ // Pre-trigger baseline snapshot (review F1 / DEV-935): one plain GET
10289
+ // BEFORE any POST, so the settled read's lifetime `credits.charged`
10290
+ // block can be diffed into "what THIS invocation spent" (the first
10291
+ // stage's charge lands before the ladder's own first read, so first
10292
+ // in-ladder read vs last would undercount). Best-effort: a failure only
10293
+ // costs the credits line, never the command. Bounded by its own short
10294
+ // signal — without it the read inherits the D4-raised per-request window
10295
+ // (up to 600s under --wait semantics), all outside the --timeout budget.
10296
+ let baselinePlans = null;
10297
+ try {
10298
+ baselinePlans = await client.getPlans(projectId, {
10299
+ signal: AbortSignal.timeout(PLAN_BASELINE_READ_TIMEOUT_MS),
10300
+ });
10301
+ }
10302
+ catch (err) {
10303
+ if (err instanceof InterruptError)
10304
+ throw err;
10305
+ baselinePlans = null;
10306
+ }
10307
+ const result = await runGenerationLadder(client, projectId, {
10308
+ timeoutSeconds: opts.timeoutSeconds,
10309
+ idempotencyKey,
10310
+ sleep: deps.sleep,
10311
+ shutdown: shutdownOf(deps),
10312
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
10313
+ onTick: (plans, elapsedMs) => {
10314
+ lastSeen = plans;
10315
+ ticker.update(planTickerLine(plans, elapsedMs));
10316
+ },
10317
+ onAttach: () => {
10318
+ stderrFn('[advisory] a generation stage is already running for this project (possibly ' +
10319
+ 'started from the Portal) — attaching to it and polling.');
10320
+ },
10321
+ onTrigger: (response, acceptedPosts) => {
10322
+ resolvedProjectId = response.projectId;
10323
+ if (response.status === 'nothing_to_start') {
10324
+ if (acceptedPosts === 0) {
10325
+ // The FIRST trigger found the batch already staged: nothing ran,
10326
+ // nothing was charged. Regenerating on purpose is a Portal action
10327
+ // for now (design §11) — say so instead of silently no-opping.
10328
+ stderrFn('[advisory] proposals are already staged for this project — showing the ' +
10329
+ 'existing batch (nothing new was started or charged). To regenerate, ' +
10330
+ 'review and accept or discard the staged batch in the Portal first.');
10331
+ }
10332
+ return;
10333
+ }
10334
+ if (acceptedPosts === 1) {
10335
+ // First accepted trigger: state which stages will run (text mode
10336
+ // only — JSON pipelines get just the result object). Deliberately
10337
+ // does NOT quote a price up front: the surface matches `test run`,
10338
+ // which announces no cost either. Actual spend IS reported after
10339
+ // the fact, on the result line (`credits used: N, balance: M`) —
10340
+ // N is THIS invocation's settled−baseline delta (review F1), not
10341
+ // the wire block's lifetime total, and never a local price table.
10342
+ if (opts.output !== 'json') {
10343
+ const stages = [
10344
+ ...(response.stage !== null ? [response.stage] : []),
10345
+ ...response.stagesRemaining,
10346
+ ];
10347
+ const label = stages.join(' + ');
10348
+ stderrFn(stages.includes('exploration')
10349
+ ? `[hint] this project hasn't been explored yet — the full pipeline will run ` +
10350
+ `(${label}). Ctrl-C detaches safely; work continues server-side.`
10351
+ : `[hint] running the missing pipeline stages (${label}). ` +
10352
+ `Ctrl-C detaches safely; work continues server-side.`);
10353
+ }
10354
+ // …and, when browser exploration is about to run, warn about
10355
+ // missing test-account sign-in (design §3.1). The wire carries no
10356
+ // credential-presence signal, so the warning is hedged ("if …") —
10357
+ // it never blocks and never prompts; the CLI cannot know whether
10358
+ // the app actually requires login. Both output modes: stderr only.
10359
+ if (response.stage === 'exploration') {
10360
+ stderrFn('[warn] exploration signs in only with the test account stored on the ' +
10361
+ "project's default environment. If your app requires login and no test " +
10362
+ 'account is configured, the agents will explore only the public pages — ' +
10363
+ 'a shallow result from a stage that still runs and still bills. For ' +
10364
+ 'signed-in coverage, store a test account first: ' +
10365
+ `testsprite project update ${projectId} --username <user> --password-file <path>`);
10366
+ }
10367
+ }
10368
+ },
10369
+ });
10370
+ const plans = result.plans;
10371
+ if (plans.generation.status === 'failed') {
10372
+ ticker.finalize(planTickerLine(plans, 0).replace(/ \(0s\)$/, ''));
10373
+ const payload = { projectId: resolvedProjectId, ...plans };
10374
+ out.print(payload, () => renderPlanGenerateFailedText(plans, resolvedProjectId));
10375
+ throw ApiError.fromEnvelope({
10376
+ error: {
10377
+ code: 'INTERNAL', // exit 1 — "a pipeline stage failed server-side" (§8)
10378
+ message: `Plan generation failed: ${plans.generation.errorMessage ??
10379
+ plans.generation.errorCode ??
10380
+ 'a pipeline stage failed server-side'}`,
10381
+ nextAction: `Completed stages stay done — re-run \`testsprite test plan generate --project ${resolvedProjectId}\` ` +
10382
+ 'to retry the failed stage, or check the project in the Portal.',
10383
+ requestId: 'local',
10384
+ details: {
10385
+ projectId: resolvedProjectId,
10386
+ errorCode: plans.generation.errorCode,
10387
+ },
10388
+ },
10389
+ });
10390
+ }
10391
+ const count = plans.proposals.length;
10392
+ ticker.finalize(`${count} ${count === 1 ? 'proposal' : 'proposals'} staged`);
10393
+ // This invocation's spend (settled − baseline; null = unknown) — the
10394
+ // wire block alone is a lifetime total (DEV-935 / review F1).
10395
+ const creditsUsed = planCreditsDelta(baselinePlans, plans);
10396
+ const skippedCategories = result.skippedCategories;
10397
+ const payload = {
10398
+ projectId: resolvedProjectId,
10399
+ creditsUsedThisInvocation: creditsUsed,
10400
+ // DEV-1008: present only when the proposals stage skipped endpoint-less
10401
+ // categories, so every other JSON payload is byte-identical.
10402
+ ...(skippedCategories !== null ? { skippedCategories } : {}),
10403
+ ...plans,
10404
+ };
10405
+ out.print(payload, () => renderPlanGenerateResultText(plans, resolvedProjectId, creditsUsed, skippedCategories));
10406
+ return payload;
10407
+ }
10408
+ catch (err) {
10409
+ // Typed exit-7 conversion (the design's hard rule): the ladder's raw
10410
+ // timeout is NOT a CLI error and would otherwise exit 1. Mirror the
10411
+ // wait-site template — partial to stdout, typed envelope thrown.
10412
+ if (err instanceof PlanGenerationTimeoutError) {
10413
+ ticker.finalize(`timed out after ${opts.timeoutSeconds}s`);
10414
+ const partial = makePlanGeneratePartial(resolvedProjectId, err.lastPlans ?? lastSeen);
10415
+ out.print(partial, () => renderPlanGeneratePartialText(partial, `timed out after ${opts.timeoutSeconds}s`));
10416
+ throw ApiError.fromEnvelope({
10417
+ error: {
10418
+ code: 'UNSUPPORTED', // exit 7 per errors.md
10419
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for plan generation on project ${resolvedProjectId}.`,
10420
+ nextAction: `Generation continues server-side; re-running the same command re-attaches: ` +
10421
+ `testsprite test plan generate --project ${resolvedProjectId} ` +
10422
+ `(raise --timeout for exploration-heavy first runs).`,
10423
+ requestId: 'local',
10424
+ details: { projectId: resolvedProjectId, timeoutSeconds: opts.timeoutSeconds },
10425
+ },
10426
+ });
10427
+ }
10428
+ if (err instanceof RequestTimeoutError) {
10429
+ ticker.finalize('request timed out');
10430
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10431
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'request timed out'));
10432
+ stderrFn(`Plan generation is still in progress (request timed out). ` +
10433
+ `Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
10434
+ throw err;
10435
+ }
10436
+ if (err instanceof InterruptError) {
10437
+ ticker.finalize(`interrupted (${err.signal})`);
10438
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10439
+ out.print(partial, () => renderPlanGeneratePartialText(partial, `interrupted (${err.signal})`));
10440
+ stderrFn(`Interrupted (${err.signal}). Plan generation keeps running (and billing) on the ` +
10441
+ `server until the current stage finishes.\n` +
10442
+ ` Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
10443
+ throw err;
10444
+ }
10445
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
10446
+ // Same partial-envelope family as the timeout/interrupt branches
10447
+ // (DEV-384 review): a redirected stdout file must never be 0-byte.
10448
+ // The original ApiError is rethrown unchanged so exit stays 11.
10449
+ ticker.finalize('rate limited by the server');
10450
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10451
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'rate limited'));
10452
+ stderrFn(`Rate limited by the server (HTTP 429). Any started generation stage keeps running ` +
10453
+ `server-side.\n Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
10454
+ throw err;
10455
+ }
10456
+ if (err instanceof ApiError &&
10457
+ err.code === 'INTERNAL' &&
10458
+ typeof err.details?.acceptedPosts === 'number') {
10459
+ // The ladder's cap-exhaustion "appears stuck" fuse (DEV-384 review F7)
10460
+ // joins the partial-envelope family too — it is a terminal outcome of a
10461
+ // long wait, exactly like the branches above, so redirected stdout must
10462
+ // carry the partial. Keyed on the fuse's own `acceptedPosts` detail so
10463
+ // the stage-failed INTERNAL (which already printed its card) never
10464
+ // double-prints. Rethrown unchanged.
10465
+ ticker.finalize('generation appears stuck');
10466
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10467
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'appears stuck'));
10468
+ throw err;
10469
+ }
10470
+ throw withPlanFixNextAction(err, resolvedProjectId);
10471
+ }
10472
+ }
10473
+ function renderPlanAcceptText(result, includesBackend) {
10474
+ const proposalNoun = result.acceptedCount === 1 ? 'proposal' : 'proposals';
10475
+ const caseNoun = result.acceptedCount === 1 ? 'test case' : 'test cases';
10476
+ const discarded = result.discardedCount > 0
10477
+ ? ` (${result.discardedCount} remaining ${result.discardedCount === 1 ? 'proposal' : 'proposals'} discarded)`
10478
+ : '';
10479
+ const lines = [
10480
+ `${result.acceptedCount} ${proposalNoun} accepted — ${result.acceptedCount} ${caseNoun} created${discarded}`,
10481
+ ];
10482
+ if (includesBackend) {
10483
+ // Only when API cases were among the accepted set (design §3.3) — keyed
10484
+ // on the project/proposal type, which IS reliable at that granularity.
10485
+ lines.push('note: API test code is generated when the tests first run');
10486
+ }
10487
+ lines.push('', 'next', ` testsprite test list --project ${result.projectId}`, ` testsprite test run --all --project ${result.projectId} --wait`);
10488
+ return lines.join('\n');
10489
+ }
10490
+ /**
10491
+ * Select the proposals to accept. Enforces the §3.3 safety rules:
10492
+ * the returned list is EXPLICIT and NEVER EMPTY — `--only` matching zero
10493
+ * staged ids (or naming unknown ids) is a local validation error and the
10494
+ * request is never sent, because an empty `only` list is server-destructive
10495
+ * (it means "reject everything" and clears the staged batch).
10496
+ */
10497
+ function selectPlanProposals(staged, onlyIds) {
10498
+ if (onlyIds === undefined)
10499
+ return staged;
10500
+ const byId = new Map(staged.map(p => [p.proposalId, p]));
10501
+ const unknown = onlyIds.filter(id => !byId.has(id));
10502
+ if (unknown.length > 0) {
10503
+ throw localValidationError('only', `no staged proposal matches id(s): ${unknown.join(', ')}. ` +
10504
+ `Staged proposal ids: ${staged.map(p => p.proposalId).join(', ')}. ` +
10505
+ `The accept request was not sent`);
10506
+ }
10507
+ return onlyIds.map(id => byId.get(id));
10508
+ }
10509
+ /**
10510
+ * `test plan accept --project <id> [--only <ids...>]` — DEV-384 V3-B.
10511
+ *
10512
+ * Reads the staged batch, selects all of it (or the `--only` subset),
10513
+ * and POSTs an EXPLICIT id list. Free — the generation charge already
10514
+ * covered it. Exit 0 on success, 5 on a bad `--only` selection (request
10515
+ * never sent), 6 when nothing is staged (pointer at `test plan generate`).
10516
+ */
10517
+ export async function runPlanAccept(opts, deps = {}) {
10518
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
10519
+ const out = makeOutput(opts.output, deps);
10520
+ const projectId = requirePlanProjectId(opts.projectId, deps);
10521
+ assertIdempotencyKey(opts.idempotencyKey);
10522
+ const onlyIds = normalizePlanOnlyIds(opts.only);
10523
+ if (opts.dryRun) {
10524
+ // Zero network, zero charges: run the real selection logic against the
10525
+ // canned staged batch so `--only` behavior (subset counts, unknown-id
10526
+ // validation) is learnable offline, then echo the input-derived sample.
10527
+ const client = makeClient(opts, deps);
10528
+ const plans = findSampleOrThrow('GET', `/api/cli/v1/projects/${encodeURIComponent(projectId)}/plans`).body();
10529
+ const staged = plans.proposals;
10530
+ const selected = selectPlanProposals(staged, onlyIds);
10531
+ const ids = selected.map(p => p.proposalId);
10532
+ const response = findSampleOrThrow('POST', `/api/cli/v1/projects/${encodeURIComponent(projectId)}/plans/accept`, { only: ids }).body();
10533
+ const result = {
10534
+ projectId,
10535
+ acceptedCount: response.acceptedCount,
10536
+ caseKeys: response.caseKeys,
10537
+ discardedCount: staged.length - selected.length,
10538
+ };
10539
+ out.print(result, () => renderPlanAcceptText(result, selected.some(p => p.type === 'backend')));
10540
+ void client;
10541
+ return result;
10542
+ }
10543
+ const idempotencyKey = opts.idempotencyKey ?? `cli-plan-accept-${randomUUID()}`;
10544
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
10545
+ stderrFn(`idempotency-key: ${idempotencyKey}`);
10546
+ }
10547
+ const client = makeClient(opts, deps);
10548
+ // The staged batch is read first because the CLI ALWAYS sends an explicit
10549
+ // id list (full list when --only is absent) — never the omitted form and
10550
+ // never an empty one (§3.3). Nothing staged → the same 412 nothing_staged
10551
+ // answer the server would give, without a request.
10552
+ let plans;
10553
+ try {
10554
+ plans = await client.getPlans(projectId);
10555
+ }
10556
+ catch (err) {
10557
+ throw withPlanFixNextAction(err, projectId);
10558
+ }
10559
+ const staged = plans.proposals;
10560
+ if (staged.length === 0) {
10561
+ throw planNothingStagedError(projectId);
10562
+ }
10563
+ const selected = selectPlanProposals(staged, onlyIds);
10564
+ const ids = selected.map(p => p.proposalId);
10565
+ let response;
10566
+ try {
10567
+ response = await client.acceptPlans(projectId, ids, { idempotencyKey });
10568
+ }
10569
+ catch (err) {
10570
+ // Covers the read-then-accept race too (another client accepted or
10571
+ // discarded the batch in between → server 412 nothing_staged).
10572
+ throw withPlanFixNextAction(err, projectId);
10573
+ }
10574
+ const result = {
10575
+ projectId,
10576
+ acceptedCount: response.acceptedCount,
10577
+ caseKeys: response.caseKeys,
10578
+ discardedCount: staged.length - selected.length,
10579
+ };
10580
+ out.print(result, () => renderPlanAcceptText(result, selected.some(p => p.type === 'backend')));
10581
+ return result;
10582
+ }
9013
10583
  function createTestPlanCommand(deps) {
9014
- const plan = new Command('plan').description('Manage FE test plan-steps (FE-only)');
10584
+ const plan = new Command('plan').description('Generate + accept AI test plans (V3), and manage FE plan-steps');
9015
10585
  plan
9016
10586
  .command('put <test-id>')
9017
10587
  .description("Replace an FE test's planSteps[] (BE tests return 400 → use 'test code put')")
@@ -9037,6 +10607,62 @@ function createTestPlanCommand(deps) {
9037
10607
  dryRunSimulateError: simulateError === 'PRECONDITION_FAILED' ? 'PRECONDITION_FAILED' : undefined,
9038
10608
  }, deps);
9039
10609
  });
10610
+ plan
10611
+ .command('generate')
10612
+ .description('Generate AI test-case proposals for a project — runs only the missing pipeline ' +
10613
+ 'stages and stages the results server-side for review (nothing is written locally)')
10614
+ .option('--project <id>', 'project id (V3-native; V2 ids resolve through the migration bridge)')
10615
+ .option('--timeout <seconds>', `total wait budget in seconds (1-3600, default ${PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS}; ` +
10616
+ 'exploration takes minutes on a fresh frontend project)')
10617
+ .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
10618
+ .addHelpText('after', '\nBehavior:\n' +
10619
+ ' - Only the stages the project is missing actually run; a second call\n' +
10620
+ ' resumes rather than starting over.\n' +
10621
+ ' - Proposals are STAGED on the server for review; nothing is written to disk.\n' +
10622
+ ' - Re-running the command re-attaches to an in-flight stage (409 attaches).\n' +
10623
+ ' - Ctrl-C detaches locally; server-side work and charges continue.\n' +
10624
+ ' - Exit 7 on --timeout: re-run the same command to re-attach.\n' +
10625
+ ' - Workspace credits are spent per stage that runs; the result line reports\n' +
10626
+ ' what THIS run charged (omitted when nothing new was charged).\n' +
10627
+ ' `testsprite usage` shows your balance.\n' +
10628
+ '\n' +
10629
+ 'Next step: review the printed table, then `testsprite test plan accept`.\n' +
10630
+ '\n' +
10631
+ GLOBAL_OPTS_HINT)
10632
+ .action(async (cmdOpts, command) => {
10633
+ await runPlanGenerate({
10634
+ ...resolveCommonOptions(command),
10635
+ projectId: cmdOpts.project,
10636
+ timeoutSeconds: cmdOpts.timeout === undefined
10637
+ ? PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS
10638
+ : parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
10639
+ idempotencyKey: cmdOpts.idempotencyKey,
10640
+ }, deps);
10641
+ });
10642
+ plan
10643
+ .command('accept')
10644
+ .description('Convert staged proposals into real test cases (free) — all of them, or a subset with --only')
10645
+ .option('--project <id>', 'project id (V3-native; V2 ids resolve through the migration bridge)')
10646
+ .option('--only <ids...>', 'accept only these proposal ids (space- or comma-separated; the ids come from the ' +
10647
+ '`test plan generate` table). Accepting a subset discards the rest. ANY id that ' +
10648
+ 'matches no staged proposal is a validation error — the request is never sent.')
10649
+ .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
10650
+ .addHelpText('after', '\nNotes:\n' +
10651
+ ' - Accepting adds no charge of its own; generation already did the work.\n' +
10652
+ ' - API test code is generated when the tests first run, not at accept.\n' +
10653
+ ' - Accepting a subset discards the remaining staged proposals (the staging\n' +
10654
+ ' area is cleared either way) — the output says how many were discarded.\n' +
10655
+ ' - Nothing staged → exit 6 with a pointer at `test plan generate`.\n' +
10656
+ '\n' +
10657
+ GLOBAL_OPTS_HINT)
10658
+ .action(async (cmdOpts, command) => {
10659
+ await runPlanAccept({
10660
+ ...resolveCommonOptions(command),
10661
+ projectId: cmdOpts.project,
10662
+ only: cmdOpts.only,
10663
+ idempotencyKey: cmdOpts.idempotencyKey,
10664
+ }, deps);
10665
+ });
9040
10666
  return plan;
9041
10667
  }
9042
10668
  export function createTestArtifactCommand(deps) {