@testsprite/testsprite-cli 0.7.0 → 0.9.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 (74) hide show
  1. package/README.md +62 -45
  2. package/dist/commands/agent.d.ts +3 -0
  3. package/dist/commands/agent.js +79 -10
  4. package/dist/commands/ci.d.ts +88 -0
  5. package/dist/commands/ci.js +432 -0
  6. package/dist/commands/doctor.js +100 -1
  7. package/dist/commands/init.d.ts +45 -2
  8. package/dist/commands/init.js +198 -29
  9. package/dist/commands/project.d.ts +78 -0
  10. package/dist/commands/project.js +439 -5
  11. package/dist/commands/test.d.ts +193 -4
  12. package/dist/commands/test.js +1948 -398
  13. package/dist/commands/testlist.js +15 -9
  14. package/dist/commands/tunnel.d.ts +72 -0
  15. package/dist/commands/tunnel.js +367 -0
  16. package/dist/index.js +107 -38
  17. package/dist/lib/agent-detect.d.ts +53 -0
  18. package/dist/lib/agent-detect.js +198 -0
  19. package/dist/lib/dry-run/samples.d.ts +9 -0
  20. package/dist/lib/dry-run/samples.js +116 -0
  21. package/dist/lib/gh-output.d.ts +7 -0
  22. package/dist/lib/gh-output.js +50 -7
  23. package/dist/lib/http.d.ts +104 -0
  24. package/dist/lib/http.js +126 -7
  25. package/dist/lib/interrupt.d.ts +38 -13
  26. package/dist/lib/interrupt.js +130 -15
  27. package/dist/lib/local-target.d.ts +95 -0
  28. package/dist/lib/local-target.js +184 -0
  29. package/dist/lib/plan-poll.d.ts +171 -0
  30. package/dist/lib/plan-poll.js +442 -0
  31. package/dist/lib/plans.types.d.ts +130 -0
  32. package/dist/lib/plans.types.js +31 -0
  33. package/dist/lib/poll-support.d.ts +26 -0
  34. package/dist/lib/poll-support.js +65 -0
  35. package/dist/lib/poll.d.ts +1 -0
  36. package/dist/lib/poll.js +2 -40
  37. package/dist/lib/response-schemas.d.ts +13 -0
  38. package/dist/lib/response-schemas.js +46 -0
  39. package/dist/lib/run-progress.d.ts +41 -0
  40. package/dist/lib/run-progress.js +56 -0
  41. package/dist/lib/runs.types.d.ts +50 -0
  42. package/dist/lib/skill-nudge.d.ts +13 -5
  43. package/dist/lib/skill-nudge.js +40 -14
  44. package/dist/lib/target-url-preflight.js +3 -3
  45. package/dist/lib/target-url.d.ts +54 -8
  46. package/dist/lib/target-url.js +274 -68
  47. package/dist/lib/telemetry.d.ts +11 -0
  48. package/dist/lib/telemetry.js +1 -0
  49. package/dist/lib/ticker.d.ts +8 -0
  50. package/dist/lib/ticker.js +3 -0
  51. package/dist/lib/tunnel-session.d.ts +138 -0
  52. package/dist/lib/tunnel-session.js +249 -0
  53. package/dist/lib/tunnel.types.d.ts +54 -0
  54. package/dist/lib/tunnel.types.js +8 -0
  55. package/dist/vendor/tunnel-client/client.d.ts +82 -0
  56. package/dist/vendor/tunnel-client/client.js +924 -0
  57. package/dist/vendor/tunnel-client/config.d.ts +49 -0
  58. package/dist/vendor/tunnel-client/config.js +50 -0
  59. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  60. package/dist/vendor/tunnel-client/index.js +9 -0
  61. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  62. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  63. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  64. package/dist/vendor/tunnel-client/protocol.js +143 -0
  65. package/dist/vendor/tunnel-client/types.d.ts +101 -0
  66. package/dist/vendor/tunnel-client/types.js +10 -0
  67. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  68. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. package/package.json +2 -1
  72. package/skills/testsprite-onboard.skill.md +60 -4
  73. package/skills/testsprite-verify.codex.md +22 -16
  74. package/skills/testsprite-verify.skill.md +27 -18
@@ -4,9 +4,9 @@ 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';
9
+ import { findSample, findSampleOrThrow, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
10
10
  import { assertJUnitReportOptions, buildJUnitReport, durationSecondsBetween, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
11
11
  import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, isAuthCode, localValidationError, } from '../lib/errors.js';
12
12
  import { globalShutdown } from '../lib/interrupt.js';
@@ -15,19 +15,24 @@ import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.
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';
19
20
  import { resolveWaitFailure } from '../lib/wait-exit.js';
20
21
  import { RUN_SOURCES } from '../lib/runs.types.js';
21
22
  import { summarizeConflicts } from '../lib/conflict-reason.js';
22
23
  import { isProxyAgentActive } from '../lib/proxy.js';
23
24
  import { assertNotLocal } from '../lib/target-url.js';
24
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';
25
29
  import { formatTextTableRow, measureTextColumns, renderTextTable, resolveTextColumns, } from '../lib/text-table.js';
30
+ import { createLiveRunProgress, formatRunProgressLine } from '../lib/run-progress.js';
26
31
  import { createTicker } from '../lib/ticker.js';
27
32
  import { RateThrottle } from '../lib/rate-throttle.js';
28
33
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
29
34
  import { emitTargetUrlMismatchAdvisory } from '../lib/v3-advisory.js';
30
- import { emitCiArtifacts, summarizeAcceptedPayload, summarizeSingleRun } from '../lib/gh-output.js';
35
+ import { emitCiArtifacts, summarizeAcceptedPayload, summarizeSingleRun, } from '../lib/gh-output.js';
31
36
  import { loadConfig } from '../lib/config.js';
32
37
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
33
38
  /** The effective shutdown handle for a command invocation (DEV-331). */
@@ -88,6 +93,185 @@ function stillRunningAndBillingSubject(runIds) {
88
93
  ? `Run ${ids[0]} is still executing on the server and will keep running (and billing) until it finishes.`
89
94
  : `${ids.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
90
95
  }
96
+ const TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE = 'Passing --no-cancel-on-interrupt keeps the run executing without its tunnel; it cannot ' +
97
+ 'reach your app and is still billed.';
98
+ function tunnelRerunCommand(detach) {
99
+ return `testsprite test run ${detach.testId} --local ${detach.localPort}`;
100
+ }
101
+ /** Minimum wall-clock gap between adopted-client liveness reads. */
102
+ const BORROWED_TUNNEL_LIVENESS_INTERVAL_MS = 15_000;
103
+ /**
104
+ * Build the adopted-tunnel liveness observation that runs on non-terminal
105
+ * poll ticks. The first tick reads immediately; later ticks share one
106
+ * wall-clock cadence regardless of how hot the run-poll loop is.
107
+ *
108
+ * Only two observations are conclusive: an explicit offline response and a
109
+ * 404. Every inability to read the state is unknown rather than dead, because
110
+ * declaring a borrowed tunnel lost on our own network/backend failure would
111
+ * turn an observation outage into a false run failure.
112
+ */
113
+ function makeBorrowedTunnelLivenessCheck(args) {
114
+ let lastCheckAtMs;
115
+ return async (signal) => {
116
+ const now = Date.now();
117
+ if (lastCheckAtMs !== undefined && now - lastCheckAtMs < BORROWED_TUNNEL_LIVENESS_INTERVAL_MS) {
118
+ return;
119
+ }
120
+ // Record the attempt before awaiting it so retries belong to the next
121
+ // interval even when this read fails or stalls until its deadline.
122
+ lastCheckAtMs = now;
123
+ let dead;
124
+ try {
125
+ const observed = await args.client.getTunnelStatus(args.clientId, {
126
+ signal,
127
+ // This observation owns its 15-second cadence. A 5xx, 429, timeout,
128
+ // or network failure is unknown and must wait for the next interval.
129
+ retry: false,
130
+ });
131
+ // The Rust service has emitted title-cased values (notably "Online")
132
+ // in production before; status comparisons must therefore ignore case.
133
+ dead = observed.status.toLowerCase() === 'offline';
134
+ }
135
+ catch (err) {
136
+ // The HTTP observation is authoritative here. Even a malformed 5xx
137
+ // envelope carrying NOT_FOUND is still an unknown server-side read.
138
+ dead = err instanceof ApiError && err.httpStatus === 404;
139
+ }
140
+ if (dead)
141
+ throw new TunnelLostError('owner-gone', args.runId);
142
+ };
143
+ }
144
+ /**
145
+ * Stop a tunnel run that can no longer succeed.
146
+ *
147
+ * Called on every path where this process stops waiting while the run is
148
+ * non-terminal. Unlike an ordinary run — where DEV-331 deliberately decided a
149
+ * Ctrl-C detaches and leaves the run to finish — a tunnel run's target lives
150
+ * behind a tunnel this process is holding open, so the moment we exit the
151
+ * Lambda's browser can start getting connection failures. The run may already
152
+ * have completed or been billed, so the cancellation message states only the
153
+ * observed cancel outcome and the cancelled-verdict semantics.
154
+ *
155
+ * The cancel is issued through a DETACHED client: the normal one composes the
156
+ * process shutdown signal into every fetch, and on the interrupt path that
157
+ * signal has already fired, so the request would abort before leaving the
158
+ * machine.
159
+ */
160
+ async function cancelDoomedTunnelRun(args) {
161
+ if (!args.enabled)
162
+ return { outcome: 'skipped' };
163
+ try {
164
+ await withTeardownDeadline(args.opts, args.deps, client => client.post(`/runs/${encodeURIComponent(args.runId)}/cancel`));
165
+ return { outcome: 'cancelled' };
166
+ }
167
+ catch (err) {
168
+ // 409 = already terminal. Not a failure: the requested end state holds.
169
+ if (err instanceof ApiError && err.code === 'CONFLICT') {
170
+ const terminalStatus = err.getDetail('status', (value) => typeof value === 'string' && isTerminalStatus(value));
171
+ return {
172
+ outcome: 'already-terminal',
173
+ ...(terminalStatus !== undefined ? { terminalStatus } : {}),
174
+ };
175
+ }
176
+ return { outcome: 'failed' };
177
+ }
178
+ }
179
+ /**
180
+ * The stderr line for a tunnel run whose wait is ending.
181
+ *
182
+ * Deliberately NOT built from `stillRunningAndBillingSubject`: that sentence
183
+ * is true for an ordinary run and false here, and the whole point of D1 (a)
184
+ * is that the four detach paths stop telling a tunnel user something untrue.
185
+ */
186
+ export function tunnelDetachMessage(detach, interrupt) {
187
+ const { runId, reason, cancel } = detach;
188
+ if (reason === 'interrupt' && cancel === 'cancelled') {
189
+ return (`Interrupted${interrupt ? ` by ${interrupt.signal}` : ''}. Run ${runId} was reaching your ` +
190
+ `machine through a tunnel that closes with this process, so it was cancelled (exit ` +
191
+ `${interrupt?.exitCode ?? 130}). The run may already have been billed; a cancelled run's ` +
192
+ `verdict is discarded. Start a new run with: ${tunnelRerunCommand(detach)}. ` +
193
+ TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE);
194
+ }
195
+ const cause = {
196
+ interrupt: `Interrupted${interrupt ? ` by ${interrupt.signal}` : ''}`,
197
+ timeout: `Timed out waiting for run ${runId}`,
198
+ 'request-timeout': 'Request timed out',
199
+ 'rate-limited': 'Rate limited by the server (HTTP 429)',
200
+ 'tunnel-lost': 'The tunnel was disconnected by the tunnel service',
201
+ 'poll-error': 'Polling stopped because the run status could not be read',
202
+ };
203
+ const doom = reason === 'tunnel-lost'
204
+ ? `Run ${runId} was reaching your machine through that tunnel, and the run's proxy credential ` +
205
+ `names the client that just went away, so it cannot be restored for this run.`
206
+ : `Run ${runId} was reaching your machine through a tunnel that closes with this process.`;
207
+ const outcome = {
208
+ cancelled: " Cancelled it. The run may already have been billed; a cancelled run's verdict is discarded.",
209
+ 'already-terminal': ' It had already finished server-side; there was nothing to cancel.',
210
+ failed: ` Could NOT cancel it from here — stop it with: testsprite test cancel ${runId}`,
211
+ skipped: ` It was not cancelled — stop it now with: testsprite test cancel ${runId}`,
212
+ };
213
+ const message = `${cause[reason]}. ${doom}\n` +
214
+ `${outcome[cancel]}\n` +
215
+ ` Start a new run with: ${tunnelRerunCommand(detach)}.`;
216
+ return cancel === 'cancelled' || cancel === 'skipped'
217
+ ? `${message}\n ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`
218
+ : message;
219
+ }
220
+ /**
221
+ * The `hint` lines under a partial run envelope.
222
+ *
223
+ * For an ordinary run these point at `test wait` / `test cancel`, which is
224
+ * right: the run is still going. For a tunnel run `test wait` is actively
225
+ * misleading — re-attaching cannot revive a tunnel that closed with the
226
+ * process that owned it — so it is never offered.
227
+ */
228
+ function detachHintLines(runId, detach) {
229
+ if (detach === undefined) {
230
+ return [
231
+ `hint Re-attach with: testsprite test wait ${runId}`,
232
+ `hint Cancel with: testsprite test cancel ${runId}`,
233
+ ];
234
+ }
235
+ return detach.cancel === 'cancelled' || detach.cancel === 'already-terminal'
236
+ ? ['hint The tunnel closed with this process, so the run was stopped.']
237
+ : [`hint Stop the run with: testsprite test cancel ${runId}`];
238
+ }
239
+ /** Status to report in a partial envelope once a doomed tunnel run was stopped. */
240
+ function detachPartialStatus(detach) {
241
+ if (detach === undefined)
242
+ return 'running';
243
+ if (detach.cancel === 'cancelled')
244
+ return 'cancelled';
245
+ return detach.terminalStatus ?? 'running';
246
+ }
247
+ export function tunnelInterruptNextAction(detach, err) {
248
+ const rerun = tunnelRerunCommand(detach);
249
+ if (detach.cancel === 'cancelled') {
250
+ return (`Run ${detach.runId} was cancelled after ${err.signal} (exit ${err.exitCode}) and its ` +
251
+ `tunnel was closed. ` +
252
+ "The run may already have been billed; a cancelled run's verdict is discarded. " +
253
+ `Start a new run with: ${rerun}. ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`);
254
+ }
255
+ if (detach.cancel === 'already-terminal') {
256
+ return (`Run ${detach.runId} had already finished` +
257
+ (detach.terminalStatus ? ` with status ${detach.terminalStatus}` : '') +
258
+ ` when ${err.signal} interrupted the wait; its tunnel was closed. Start a new run with: ` +
259
+ `${rerun}.`);
260
+ }
261
+ if (detach.cancel === 'skipped') {
262
+ return (`Start a new run with: ${rerun}, after stopping run ${detach.runId} with: testsprite test ` +
263
+ `cancel ${detach.runId}. ${TUNNEL_INTERRUPT_OPT_OUT_CONSEQUENCE}`);
264
+ }
265
+ return (`Start a new run with: ${rerun}, after stopping run ${detach.runId} with: testsprite test ` +
266
+ `cancel ${detach.runId}; automatic cancellation after ${err.signal} failed.`);
267
+ }
268
+ function attachTunnelInterruptDetach(err, detach) {
269
+ err.tunnelDetach = {
270
+ runId: detach.runId,
271
+ cancel: detach.cancel,
272
+ nextAction: tunnelInterruptNextAction(detach, err),
273
+ };
274
+ }
91
275
  const TEST_TYPES = ['frontend', 'backend'];
92
276
  // 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
93
277
  // tests created via `testsprite test create`, so the `--created-from cli`
@@ -367,6 +551,9 @@ export async function runCreate(opts, deps = {}) {
367
551
  priority: opts.priority,
368
552
  code,
369
553
  };
554
+ if (opts.stepTimeoutMs !== undefined) {
555
+ body.stepTimeoutMs = opts.stepTimeoutMs;
556
+ }
370
557
  // M4 piece-2: thread BE dependency fields into the POST body.
371
558
  // Only include when non-empty so the wire stays clean for tests that
372
559
  // don't declare any dependencies (undefined is omitted by JSON.stringify).
@@ -380,7 +567,11 @@ export async function runCreate(opts, deps = {}) {
380
567
  body.category = opts.category;
381
568
  }
382
569
  if (opts.targetUrl !== undefined) {
383
- assertNotLocal(opts.targetUrl);
570
+ assertNotLocal(opts.targetUrl, {
571
+ field: 'target-url',
572
+ helpCommand: 'testsprite test create',
573
+ hintContext: 'bootstrap',
574
+ });
384
575
  }
385
576
  // C1: --target-url is inert for backend tests (base URL is baked into the
386
577
  // test code; the backend sandbox never receives targetUrl). Emit a
@@ -424,6 +615,9 @@ export async function runCreate(opts, deps = {}) {
424
615
  // tests) on stderr so they reach the agent without polluting stdout JSON.
425
616
  // Emitted before the --run early return so they always show.
426
617
  emitResponseWarnings(response.warnings, deps);
618
+ if (!opts.dryRun) {
619
+ emitStepTimeoutRunWarning(opts.stepTimeoutMs, deps);
620
+ }
427
621
  // --run chain (M3.3 piece-3). Per codex round-1 P1: suppress the
428
622
  // create's own print when chaining; `runTestRun` emits a single
429
623
  // merged envelope `{ ...createResponse, run: <trigger|final> }` so
@@ -615,6 +809,19 @@ function emitResponseWarnings(warnings, deps) {
615
809
  for (const w of warnings)
616
810
  stderrFn(`[warn] ${w}`);
617
811
  }
812
+ /**
813
+ * A per-step timeout can make the overall run exceed the CLI's independent
814
+ * client-side poll deadline. Keep the two timeout concepts explicit and make
815
+ * clear that detaching the client never cancels server-side execution.
816
+ */
817
+ function emitStepTimeoutRunWarning(stepTimeoutMs, deps) {
818
+ if (stepTimeoutMs === undefined)
819
+ return;
820
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
821
+ stderrFn(`[warn] Runs of this test may take longer with a ${stepTimeoutMs} ms per-step timeout. ` +
822
+ `\`test run --wait\` polls for up to ${DEFAULT_RUN_TIMEOUT_SECONDS}s by default; ` +
823
+ 'raise it with `--timeout <s>` if needed. A client-side timeout never stops the server-side run.');
824
+ }
618
825
  /**
619
826
  * piece-6 cap for the `PUT /tests/{id}/plan-steps` body. Distinct from
620
827
  * piece-5's `MAX_PLAN_BODY_BYTES` because the wire shape differs
@@ -887,8 +1094,11 @@ export async function runUpdate(opts, deps = {}) {
887
1094
  ...CLI_CREATE_PRIORITIES,
888
1095
  ]);
889
1096
  }
890
- // No-op rejection: requires at least one of the three patchable
891
- // fields. Caught before fetching credentials or building the
1097
+ if (opts.stepTimeoutMs !== undefined && opts.clearStepTimeout === true) {
1098
+ throw localValidationError('step-timeout', '--step-timeout and --clear-step-timeout are mutually exclusive');
1099
+ }
1100
+ // No-op rejection: requires at least one patchable field. Caught before
1101
+ // fetching credentials or building the
892
1102
  // request so the user gets the cheapest possible error.
893
1103
  const hasName = opts.name !== undefined;
894
1104
  const hasDescription = opts.description !== undefined;
@@ -896,8 +1106,26 @@ export async function runUpdate(opts, deps = {}) {
896
1106
  const hasProduces = opts.produces !== undefined && opts.produces.length > 0;
897
1107
  const hasNeeds = opts.needs !== undefined && opts.needs.length > 0;
898
1108
  const hasCategory = opts.category !== undefined;
899
- if (!hasName && !hasDescription && !hasPriority && !hasProduces && !hasNeeds && !hasCategory) {
900
- throw localValidationError('fields', 'at least one of --name / --description / --priority / --produces / --needs / --category must be set', ['name', 'description', 'priority', 'produces', 'needs', 'category']);
1109
+ const hasStepTimeout = opts.stepTimeoutMs !== undefined;
1110
+ const hasClearStepTimeout = opts.clearStepTimeout === true;
1111
+ if (!hasName &&
1112
+ !hasDescription &&
1113
+ !hasPriority &&
1114
+ !hasProduces &&
1115
+ !hasNeeds &&
1116
+ !hasCategory &&
1117
+ !hasStepTimeout &&
1118
+ !hasClearStepTimeout) {
1119
+ throw localValidationError('fields', 'at least one of --name / --description / --priority / --produces / --needs / --category / --step-timeout / --clear-step-timeout must be set', [
1120
+ 'name',
1121
+ 'description',
1122
+ 'priority',
1123
+ 'produces',
1124
+ 'needs',
1125
+ 'category',
1126
+ 'step-timeout',
1127
+ 'clear-step-timeout',
1128
+ ]);
901
1129
  }
902
1130
  const idempotencyKey = opts.idempotencyKey ?? `cli-update-${randomUUID()}`;
903
1131
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
@@ -922,12 +1150,19 @@ export async function runUpdate(opts, deps = {}) {
922
1150
  body.consumes = opts.needs;
923
1151
  if (hasCategory)
924
1152
  body.category = opts.category;
1153
+ if (hasStepTimeout)
1154
+ body.stepTimeoutMs = opts.stepTimeoutMs;
1155
+ if (hasClearStepTimeout)
1156
+ body.stepTimeoutMs = null;
925
1157
  const client = makeClient(opts, deps);
926
1158
  const out = makeOutput(opts.output, deps);
927
1159
  const response = await client.put(`/tests/${encodeURIComponent(opts.testId)}`, {
928
1160
  body,
929
1161
  headers: { 'idempotency-key': idempotencyKey },
930
1162
  });
1163
+ if (!opts.dryRun && hasStepTimeout) {
1164
+ emitStepTimeoutRunWarning(opts.stepTimeoutMs, deps);
1165
+ }
931
1166
  out.print(response, data => renderUpdateText(data));
932
1167
  return response;
933
1168
  }
@@ -1520,7 +1755,11 @@ export async function runCreateFromPlan(opts, deps = {}) {
1520
1755
  assertChainedRunKeyFits(opts.run, opts.idempotencyKey);
1521
1756
  requireNonEmpty('plan-from', opts.planFrom);
1522
1757
  if (opts.targetUrl !== undefined) {
1523
- assertNotLocal(opts.targetUrl);
1758
+ assertNotLocal(opts.targetUrl, {
1759
+ field: 'target-url',
1760
+ helpCommand: 'testsprite test create',
1761
+ hintContext: 'bootstrap',
1762
+ });
1524
1763
  }
1525
1764
  const plan = readPlanFromGuarded(opts.planFrom, { ignoredFlags: opts.ignoredFlags });
1526
1765
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
@@ -1917,7 +2156,11 @@ export async function runCreateBatch(opts, deps = {}) {
1917
2156
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
1918
2157
  }
1919
2158
  if (opts.targetUrl !== undefined) {
1920
- assertNotLocal(opts.targetUrl);
2159
+ assertNotLocal(opts.targetUrl, {
2160
+ field: 'target-url',
2161
+ helpCommand: 'testsprite test create-batch',
2162
+ hintContext: 'bootstrap',
2163
+ });
1921
2164
  }
1922
2165
  const stderrFnEarly = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1923
2166
  const specs = opts.planFromDir !== undefined && opts.planFromDir !== ''
@@ -4106,7 +4349,7 @@ function isTerminalPublicStatus(status) {
4106
4349
  * only the verdict/result fields are taken from the test record (codex
4107
4350
  * round-2: don't fabricate blank correlation fields).
4108
4351
  */
4109
- function backendResultToRunResponse(result, run) {
4352
+ export function backendResultToRunResponse(result, run, testTitle) {
4110
4353
  // `result.summary` is now a semantic string, not a count object.
4111
4354
  // Reconstruct the synthetic 1-test stepSummary from the verdict (byte-identical
4112
4355
  // to the prior status-derived counts: passed→1/0, failed→0/1, else→0/0).
@@ -4116,6 +4359,12 @@ function backendResultToRunResponse(result, run) {
4116
4359
  return {
4117
4360
  ...run,
4118
4361
  status: result.status,
4362
+ // The backend only resolves `testTitle` on a TERMINAL run read; this fallback
4363
+ // synthesizes a terminal response from a NON-terminal poll (`run.testTitle` is
4364
+ // null there by contract), so overlay the name the type-probe already fetched
4365
+ // — zero extra request. `.trim() ||` matches the empty-title→id fallback the
4366
+ // summary/JUnit renderers use, so a blank name never renders an empty cell.
4367
+ testTitle: testTitle?.trim() ? testTitle : (run.testTitle ?? null),
4119
4368
  // Drop the polling hint — it's meaningless on a terminal response
4120
4369
  // (JSON.stringify omits undefined keys).
4121
4370
  retryAfterSeconds: undefined,
@@ -4178,8 +4427,13 @@ export function backendResultIsForThisRun(result, runId, notBefore) {
4178
4427
  * - Every lookup is best-effort: any error → "keep polling the run row", so
4179
4428
  * the fallback can never make either path worse than the prior timeout.
4180
4429
  */
4181
- function makeBackendWaitFallback(args) {
4430
+ export function makeBackendWaitFallback(args) {
4182
4431
  let detection = 'pending';
4432
+ // Cached alongside `detection` from the same one-time type-probe: the human
4433
+ // name, used to overlay `testTitle` onto the synthesized terminal response
4434
+ // (the backend never sends a title on the non-terminal poll this fallback
4435
+ // reads). Null until the probe succeeds, or if the test has no/blank name.
4436
+ let testName = null;
4183
4437
  return async (run, _elapsedMs, signal) => {
4184
4438
  const testId = args.resolveTestId(run);
4185
4439
  if (!testId)
@@ -4196,6 +4450,7 @@ function makeBackendWaitFallback(args) {
4196
4450
  // non-terminal tick retries; the FE path is unaffected because its run
4197
4451
  // row finalizes and `resolveAlternate` stops being called.
4198
4452
  detection = test.type === 'backend' ? 'backend' : 'frontend';
4453
+ testName = test.name?.trim() ? test.name : null;
4199
4454
  }
4200
4455
  catch {
4201
4456
  return null; // transient — keep polling the run row, retry the probe next tick.
@@ -4215,8 +4470,9 @@ function makeBackendWaitFallback(args) {
4215
4470
  }
4216
4471
  args.onResolved?.(testId, result.status);
4217
4472
  // Overlay the verdict onto the polled run row (preserves real correlation
4218
- // metadata; codex round-2).
4219
- return backendResultToRunResponse(result, run);
4473
+ // metadata; codex round-2) plus the probe-cached name so the CI title is
4474
+ // populated even on a run row that never finalizes on its own.
4475
+ return backendResultToRunResponse(result, run, testName);
4220
4476
  };
4221
4477
  }
4222
4478
  /**
@@ -4429,6 +4685,11 @@ function renderTriggerRunText(r) {
4429
4685
  lines.push(`codeVersion ${r.codeVersion}`);
4430
4686
  if (r.targetUrl !== null)
4431
4687
  lines.push(`targetUrl ${r.targetUrl}`);
4688
+ // Same line the run card prints after `--wait` (`renderRunResponseText`), so a
4689
+ // bare `test run <id>` shows where to look without a second command. Only
4690
+ // when the server sent one — absent means it had no correct link to give.
4691
+ if (r.dashboardUrl)
4692
+ lines.push(`dashboard ${r.dashboardUrl}`);
4432
4693
  return lines.join('\n');
4433
4694
  }
4434
4695
  /**
@@ -4447,6 +4708,16 @@ function parseTimeoutFlag(raw, flagName) {
4447
4708
  }
4448
4709
  return n;
4449
4710
  }
4711
+ /** Validate the per-test timeout that the execution engine applies to every step. */
4712
+ function parseStepTimeoutFlag(raw, flagName) {
4713
+ if (raw === undefined)
4714
+ return undefined;
4715
+ const n = Number(raw);
4716
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 60_000) {
4717
+ throw localValidationError(flagName, 'must be an integer between 1 and 60000 milliseconds');
4718
+ }
4719
+ return n;
4720
+ }
4450
4721
  /**
4451
4722
  * `test run <test-id>` — M3.3 piece-3.
4452
4723
  *
@@ -4457,9 +4728,33 @@ function parseTimeoutFlag(raw, flagName) {
4457
4728
  */
4458
4729
  export async function runTestRun(opts, deps = {}) {
4459
4730
  assertIdempotencyKey(opts.idempotencyKey);
4731
+ // --local resolution runs FIRST and touches nothing: every refusal below
4732
+ // must happen before a client is even constructed, because the guarantee
4733
+ // this feature sells is that a doomed `--local` run never gets a run row,
4734
+ // a credit spend, or a tunnel credential.
4735
+ const isTunnelRun = opts.localPort !== undefined;
4736
+ if (isTunnelRun && opts.targetUrl !== undefined) {
4737
+ throw localValidationError('local', '--local and --target-url are mutually exclusive: --local runs against your own machine ' +
4738
+ 'through a tunnel, --target-url runs against an address the test runner can already ' +
4739
+ 'reach. Pass one');
4740
+ }
4741
+ if (isTunnelRun && !opts.wait) {
4742
+ // The tunnel's lifetime IS this process's lifetime, so a no-wait tunnel
4743
+ // run dooms itself the instant the command returns. The command wiring
4744
+ // forces --wait; this covers a programmatic caller that did not.
4745
+ throw localValidationError('local', '--local runs cannot detach: the tunnel closes when this command exits, so the run would ' +
4746
+ 'fail. Remove --local, or let the command wait');
4747
+ }
4460
4748
  if (opts.targetUrl !== undefined) {
4461
- assertNotLocal(opts.targetUrl);
4749
+ assertNotLocal(opts.targetUrl, {
4750
+ field: 'target-url',
4751
+ helpCommand: 'testsprite test run',
4752
+ hintContext: 'runtime',
4753
+ });
4462
4754
  }
4755
+ const localHost = opts.localHost ?? DEFAULT_LOCAL_HOST;
4756
+ const localTargetUrl = opts.localPort !== undefined ? buildLocalTargetUrl(localHost, opts.localPort) : undefined;
4757
+ const effectiveTargetUrl = localTargetUrl ?? opts.targetUrl;
4463
4758
  if (opts.dryRun) {
4464
4759
  const client = makeClient(opts, deps);
4465
4760
  const out = makeOutput(opts.output, deps);
@@ -4482,8 +4777,22 @@ export async function runTestRun(opts, deps = {}) {
4482
4777
  const envelope = {
4483
4778
  method: 'POST',
4484
4779
  path: `/api/cli/v1/tests/${opts.testId}/runs`,
4485
- body: { source: 'cli', ...(opts.targetUrl ? { targetUrl: opts.targetUrl } : {}) },
4780
+ body: {
4781
+ source: 'cli',
4782
+ ...(effectiveTargetUrl ? { targetUrl: effectiveTargetUrl } : {}),
4783
+ // A dry run mints nothing, so there is no real client id to show —
4784
+ // and inventing a UUID-shaped one would read as a live credential
4785
+ // handle, the same reason `dashboardUrl` is suppressed under
4786
+ // --dry-run rather than pointing at the canned sample id.
4787
+ ...(isTunnelRun ? { tunnelClientId: '<minted at run time>' } : {}),
4788
+ },
4486
4789
  idempotencyKey,
4790
+ ...(isTunnelRun
4791
+ ? {
4792
+ precededBy: 'POST /api/cli/v1/tunnel',
4793
+ followedBy: 'DELETE /api/cli/v1/tunnel/<client-id>',
4794
+ }
4795
+ : {}),
4487
4796
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
4488
4797
  };
4489
4798
  printRunOrChain(out, envelope, opts.createContext);
@@ -4498,9 +4807,15 @@ export async function runTestRun(opts, deps = {}) {
4498
4807
  }
4499
4808
  // D4: under --wait, raise the per-request timeout to cover --timeout so a
4500
4809
  // slow trigger/long-poll under load isn't falsely cut at the 120s default.
4501
- const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
4810
+ const requestTimeoutMs = resolveWaitRequestTimeoutMs(opts);
4811
+ const clientOpts = { ...opts, requestTimeoutMs };
4812
+ const client = makeClient(clientOpts, deps);
4813
+ const tunnelRequestTimeoutMs = isTunnelRun
4814
+ ? resolveRequestTimeoutMs(clientOpts, deps.env ?? process.env)
4815
+ : undefined;
4502
4816
  const out = makeOutput(opts.output, deps);
4503
4817
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4818
+ const shutdown = shutdownOf(deps);
4504
4819
  // Pre-charge reachability preflight — real path only (dry-run
4505
4820
  // makes zero network calls by convention), after `assertNotLocal` and
4506
4821
  // before the trigger POST so a doomed run never gets a run row or charge.
@@ -4508,350 +4823,566 @@ export async function runTestRun(opts, deps = {}) {
4508
4823
  // delegating caller (`runCreate`/`runCreateFromPlan` chaining `--run`)
4509
4824
  // already ran this exact check against the same URL before its own
4510
4825
  // create POST and sets `skipPreflight: true` here to avoid probing twice.
4511
- if (opts.targetUrl !== undefined) {
4826
+ if (isTunnelRun) {
4827
+ // The tunnel-run equivalent of the --target-url probe, and the reason
4828
+ // DEV-868 exists: a dev server that is not running is the single most
4829
+ // likely `--local` mistake, and this is the last moment it costs nothing.
4830
+ // Unlike the --target-url probe this one is conclusive — the dial it
4831
+ // performs is the same raw loopback connect the tunnel client will make
4832
+ // from this same process — so it refuses rather than advises.
4833
+ await assertLocalPortListening(localHost, opts.localPort, { skipPreflight: opts.skipPreflight }, stderrFn);
4834
+ if (isProxyAgentActive()) {
4835
+ stderrFn('[advisory] An HTTP proxy is configured for this process. The tunnel control channel ' +
4836
+ 'honours it, but the tunnel data plane is a raw TCP connection that does not — if the ' +
4837
+ 'run cannot reach your machine, an egress proxy is the first thing to rule out.');
4838
+ }
4839
+ }
4840
+ else if (opts.targetUrl !== undefined) {
4512
4841
  await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
4513
4842
  }
4514
- let triggerResponse;
4515
- let triggerRequestId;
4516
- let resumedFromConflict = false;
4843
+ // Nothing above this line has spent money or minted a credential. Everything
4844
+ // below it must be unwound on every exit path, which is what the `finally`
4845
+ // at the end of this function is for.
4846
+ let tunnelSession;
4847
+ // Arm before minting and keep the scope armed until close/delete finishes.
4848
+ // The nested poll arm is intentionally re-entrant; when it disarms, this
4849
+ // outer lifecycle scope still protects cancellation and binding teardown.
4850
+ const disarmTunnelLifecycle = isTunnelRun ? shutdown.arm() : undefined;
4517
4851
  try {
4518
- const result = await client.triggerRunWithMeta(opts.testId, { source: 'cli', ...(opts.targetUrl ? { targetUrl: opts.targetUrl } : {}) }, { idempotencyKey });
4519
- triggerResponse = result.body;
4520
- triggerRequestId = result.requestId;
4521
- }
4522
- catch (err) {
4523
- // CONFLICT (409) can arise from two different causes:
4524
- // 1. reason === 'run_in_flight' — another run is currently executing for
4525
- // this test. Auto-resume polling is valid ONLY for this reason and ONLY
4526
- // when --wait is set. Any other reason (snapshot_in_flight, etc.) or
4527
- // IDEMPOTENCY_BODY_MISMATCH must propagate to exit 6 so callers can
4528
- // decide what to do.
4529
- // 2. reason !== 'run_in_flight' — snapshot mid-mutation or body-hash
4530
- // mismatch. Always propagate.
4531
- if (opts.wait && err instanceof ApiError && err.code === 'CONFLICT') {
4532
- const conflictReason = err.getDetail('reason', (v) => typeof v === 'string' && v.length > 0);
4533
- const currentRunId = err.getDetail('currentRunId', (v) => typeof v === 'string' && v.length > 0);
4534
- // Only the genuine "another run currently executing" race qualifies for
4535
- // auto-resume. Other CONFLICT reasons (snapshot_in_flight, etc.) exit 6.
4536
- if (conflictReason === 'run_in_flight' && currentRunId !== undefined) {
4537
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4538
- // If the caller supplied --target-url, verify the in-flight run targets
4539
- // the same URL. A mismatch means we would be reporting a different
4540
- // environment's results as if our requested environment was tested.
4541
- if (opts.targetUrl !== undefined) {
4542
- const inFlightRun = await client.getRun(currentRunId);
4543
- if (inFlightRun.targetUrl !== opts.targetUrl) {
4544
- throw new ApiError({
4545
- code: 'CONFLICT',
4546
- message: `Conflict: another run for this test is in flight against a different ` +
4547
- `target URL (${inFlightRun.targetUrl ?? 'not reported'}). Your --target-url ${opts.targetUrl} ` +
4548
- `cannot attach to that run. Wait for it to finish ` +
4549
- `(\`testsprite test wait ${currentRunId}\`) or retry your trigger when ` +
4550
- `the test is free.`,
4551
- nextAction: `testsprite test wait ${currentRunId}`,
4552
- requestId: err.requestId,
4553
- details: {
4554
- reason: 'run_in_flight',
4555
- currentRunId,
4556
- inFlightTargetUrl: inFlightRun.targetUrl,
4557
- requestedTargetUrl: opts.targetUrl,
4558
- },
4559
- });
4560
- }
4561
- stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}, ` +
4562
- `target: ${inFlightRun.targetUrl}). ` +
4563
- `Attaching to that run's --wait poll instead of creating a new one. ` +
4564
- `To stop it instead: testsprite test cancel ${currentRunId}`);
4565
- triggerResponse = {
4566
- runId: currentRunId,
4567
- status: 'queued',
4568
- enqueuedAt: new Date().toISOString(),
4569
- codeVersion: inFlightRun.codeVersion ?? '',
4570
- // The check above proved the in-flight run targets exactly this URL.
4571
- targetUrl: opts.targetUrl,
4572
- };
4852
+ if (isTunnelRun) {
4853
+ try {
4854
+ tunnelSession = await openTunnelSession({
4855
+ log: stderrFn,
4856
+ logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
4857
+ onFatal: () => {
4858
+ // Surfaced to the poll loop through `onTick` below; a remint cannot
4859
+ // rescue this run (see `lib/tunnel-session.ts`).
4860
+ },
4861
+ ...(opts.tunnelClientId !== undefined
4862
+ ? { adopt: { clientId: opts.tunnelClientId, expiresAt: '' } }
4863
+ : {}),
4864
+ }, {
4865
+ mint: async (ttlSeconds) => withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, mintClient => mintClient.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
4866
+ destroy: async (clientId) => deleteTunnelForCleanup(opts, deps, clientId),
4867
+ createClient: shutdownAwareTunnelClientFactory(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
4868
+ });
4869
+ }
4870
+ catch (err) {
4871
+ // `openTunnelSession` converts a client-start rejection to UNAVAILABLE
4872
+ // after it has stopped the client and deleted the binding. Restore the
4873
+ // initiating signal so the documented interrupt exit code is retained.
4874
+ if (shutdown.signal.aborted)
4875
+ throw shutdown.signal.reason;
4876
+ throw err;
4877
+ }
4878
+ if (!tunnelSession.adopted) {
4879
+ stderrFn(`[tunnel] Reaching ${localTargetUrl} through TestSprite (client ${tunnelSession.clientId}).`);
4880
+ }
4881
+ }
4882
+ let triggerResponse;
4883
+ let triggerRequestId;
4884
+ let resumedFromConflict = false;
4885
+ try {
4886
+ // A signal received before the POST begins is still free to stop here.
4887
+ // Once the request has begun, however, it must finish under its own
4888
+ // bounded deadline so we can learn the runId if the server charged it.
4889
+ if (isTunnelRun && shutdown.signal.aborted)
4890
+ throw shutdown.signal.reason;
4891
+ const triggerBody = {
4892
+ source: 'cli',
4893
+ ...(effectiveTargetUrl ? { targetUrl: effectiveTargetUrl } : {}),
4894
+ // The client ID only. The secret stays in this process and never
4895
+ // reaches a request body, an idempotency row, or an audit line.
4896
+ ...(tunnelSession ? { tunnelClientId: tunnelSession.clientId } : {}),
4897
+ };
4898
+ const result = isTunnelRun
4899
+ ? await withUninterruptibleRequest(clientOpts, deps, tunnelRequestTimeoutMs, triggerClient => triggerClient.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey }))
4900
+ : await client.triggerRunWithMeta(opts.testId, triggerBody, { idempotencyKey });
4901
+ triggerResponse = result.body;
4902
+ triggerRequestId = result.requestId;
4903
+ }
4904
+ catch (err) {
4905
+ // CONFLICT (409) can arise from two different causes:
4906
+ // 1. reason === 'run_in_flight' — another run is currently executing for
4907
+ // this test. Auto-resume polling is valid ONLY for this reason and ONLY
4908
+ // when --wait is set. Any other reason (snapshot_in_flight, etc.) or
4909
+ // IDEMPOTENCY_BODY_MISMATCH must propagate to exit 6 so callers can
4910
+ // decide what to do.
4911
+ // 2. reason !== 'run_in_flight' — snapshot mid-mutation or body-hash
4912
+ // mismatch. Always propagate.
4913
+ if (opts.wait && err instanceof ApiError && err.code === 'CONFLICT') {
4914
+ const conflictReason = err.getDetail('reason', (v) => typeof v === 'string' && v.length > 0);
4915
+ const currentRunId = err.getDetail('currentRunId', (v) => typeof v === 'string' && v.length > 0);
4916
+ // Auto-resume is wrong for a tunnel run: the in-flight run was
4917
+ // triggered without OUR client id, so it is not routed through this
4918
+ // tunnel and is testing something else entirely. Attaching to its poll
4919
+ // would report a different environment's verdict as if it were the
4920
+ // local one — the exact substitution `--local` exists to prevent.
4921
+ if (isTunnelRun) {
4922
+ throw err;
4573
4923
  }
4574
- else {
4575
- // D: No --target-url supplied — fetch the in-flight run so the
4576
- // synthesised triggerResponse.targetUrl is the REAL environment being
4577
- // tested, not an empty string that would propagate into the timeout
4578
- // partial (Finding D). Fall back to null (not '') if the lookup fails.
4579
- let inFlightTargetUrl = null;
4580
- let inFlightCodeVersion = '';
4581
- try {
4924
+ // Only the genuine "another run currently executing" race qualifies for
4925
+ // auto-resume. Other CONFLICT reasons (snapshot_in_flight, etc.) exit 6.
4926
+ if (conflictReason === 'run_in_flight' && currentRunId !== undefined) {
4927
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4928
+ // If the caller supplied --target-url, verify the in-flight run targets
4929
+ // the same URL. A mismatch means we would be reporting a different
4930
+ // environment's results as if our requested environment was tested.
4931
+ if (opts.targetUrl !== undefined) {
4582
4932
  const inFlightRun = await client.getRun(currentRunId);
4583
- inFlightTargetUrl = inFlightRun.targetUrl ?? null;
4584
- inFlightCodeVersion = inFlightRun.codeVersion ?? '';
4933
+ if (inFlightRun.targetUrl !== opts.targetUrl) {
4934
+ throw new ApiError({
4935
+ code: 'CONFLICT',
4936
+ message: `Conflict: another run for this test is in flight against a different ` +
4937
+ `target URL (${inFlightRun.targetUrl ?? 'not reported'}). Your --target-url ${opts.targetUrl} ` +
4938
+ `cannot attach to that run. Wait for it to finish ` +
4939
+ `(\`testsprite test wait ${currentRunId}\`) or retry your trigger when ` +
4940
+ `the test is free.`,
4941
+ nextAction: `testsprite test wait ${currentRunId}`,
4942
+ requestId: err.requestId,
4943
+ details: {
4944
+ reason: 'run_in_flight',
4945
+ currentRunId,
4946
+ inFlightTargetUrl: inFlightRun.targetUrl,
4947
+ requestedTargetUrl: opts.targetUrl,
4948
+ },
4949
+ });
4950
+ }
4951
+ stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}, ` +
4952
+ `target: ${inFlightRun.targetUrl}). ` +
4953
+ `Attaching to that run's --wait poll instead of creating a new one. ` +
4954
+ `To stop it instead: testsprite test cancel ${currentRunId}`);
4955
+ triggerResponse = {
4956
+ runId: currentRunId,
4957
+ status: 'queued',
4958
+ enqueuedAt: new Date().toISOString(),
4959
+ codeVersion: inFlightRun.codeVersion ?? '',
4960
+ // The check above proved the in-flight run targets exactly this URL.
4961
+ targetUrl: opts.targetUrl,
4962
+ };
4585
4963
  }
4586
- catch {
4587
- // Best-effort — if the lookup fails, proceed with null targetUrl.
4964
+ else {
4965
+ // D: No --target-url supplied — fetch the in-flight run so the
4966
+ // synthesised triggerResponse.targetUrl is the REAL environment being
4967
+ // tested, not an empty string that would propagate into the timeout
4968
+ // partial (Finding D). Fall back to null (not '') if the lookup fails.
4969
+ let inFlightTargetUrl = null;
4970
+ let inFlightCodeVersion = '';
4971
+ try {
4972
+ const inFlightRun = await client.getRun(currentRunId);
4973
+ inFlightTargetUrl = inFlightRun.targetUrl ?? null;
4974
+ inFlightCodeVersion = inFlightRun.codeVersion ?? '';
4975
+ }
4976
+ catch {
4977
+ // Best-effort — if the lookup fails, proceed with null targetUrl.
4978
+ }
4979
+ // Auto-resume but emit a stronger advisory so the caller is aware
4980
+ // they are attaching to the project default.
4981
+ // SIG-9 (DEV-331 final): the in-flight run is NOT auto-cancelled —
4982
+ // name the real `test cancel` command instead of the old (false)
4983
+ // "cancel with Ctrl-C" claim.
4984
+ stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
4985
+ (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
4986
+ `). Auto-resuming wait on in-flight run. ` +
4987
+ `If you needed a specific target URL, cancel it with ` +
4988
+ `testsprite test cancel ${currentRunId}, or re-trigger with ` +
4989
+ `--target-url after it finishes.`);
4990
+ triggerResponse = {
4991
+ runId: currentRunId,
4992
+ status: 'queued',
4993
+ enqueuedAt: new Date().toISOString(),
4994
+ codeVersion: inFlightCodeVersion,
4995
+ // Use the real targetUrl from the in-flight run (or null if unknown),
4996
+ // never '' — the timeout partial inherits this value.
4997
+ targetUrl: inFlightTargetUrl ?? '',
4998
+ };
4588
4999
  }
4589
- // Auto-resume but emit a stronger advisory so the caller is aware
4590
- // they are attaching to the project default.
4591
- // SIG-9 (DEV-331 final): the in-flight run is NOT auto-cancelled —
4592
- // name the real `test cancel` command instead of the old (false)
4593
- // "cancel with Ctrl-C" claim.
4594
- stderrFn(`[advisory] Run already in flight (runId: ${currentRunId}` +
4595
- (inFlightTargetUrl ? `, target: ${inFlightTargetUrl}` : '') +
4596
- `). Auto-resuming wait on in-flight run. ` +
4597
- `If you needed a specific target URL, cancel it with ` +
4598
- `testsprite test cancel ${currentRunId}, or re-trigger with ` +
4599
- `--target-url after it finishes.`);
4600
- triggerResponse = {
4601
- runId: currentRunId,
4602
- status: 'queued',
4603
- enqueuedAt: new Date().toISOString(),
4604
- codeVersion: inFlightCodeVersion,
4605
- // Use the real targetUrl from the in-flight run (or null if unknown),
4606
- // never '' — the timeout partial inherits this value.
4607
- targetUrl: inFlightTargetUrl ?? '',
4608
- };
5000
+ resumedFromConflict = true;
5001
+ }
5002
+ else {
5003
+ throw err;
4609
5004
  }
4610
- resumedFromConflict = true;
4611
5005
  }
4612
5006
  else {
4613
5007
  throw err;
4614
5008
  }
4615
5009
  }
4616
- else {
4617
- throw err;
5010
+ // Response-driven, not assumption-driven: the backend is the ground
5011
+ // truth for whether --target-url was actually applied — V3
5012
+ // deliberately returns `targetUrl: ''` rather than echoing an override it
5013
+ // did not apply ("so the response doesn't claim a target we didn't use"),
5014
+ // while V2 echoes the real applied value. Comparing what we asked for
5015
+ // against what the trigger response reports self-corrects the day the
5016
+ // backend applies the override, with no `v3Enabled` assumption at all.
5017
+ // Skipped for a known-backend caller (`opts.type` threaded from the
5018
+ // `test create --run` chain): a backend trigger response's `targetUrl`
5019
+ // is an unconditional echo of the request body (verified against
5020
+ // backend-v2.0's `CliTestsController.createRun` — `targetUrl: body.targetUrl
5021
+ // ?? ''` on both the V2 and V3 backend branches), so it can never mismatch
5022
+ // and the existing, more specific C1 advisory ("--target-url has no effect
5023
+ // for backend tests") already covers this case at create time.
5024
+ if (effectiveTargetUrl !== undefined &&
5025
+ opts.type !== 'backend' &&
5026
+ triggerResponse.targetUrl !== effectiveTargetUrl) {
5027
+ emitTargetUrlMismatchAdvisory(stderrFn, effectiveTargetUrl, triggerResponse.targetUrl);
4618
5028
  }
4619
- }
4620
- // Response-driven, not assumption-driven: the backend is the ground
4621
- // truth for whether --target-url was actually applied — V3
4622
- // deliberately returns `targetUrl: ''` rather than echoing an override it
4623
- // did not apply ("so the response doesn't claim a target we didn't use"),
4624
- // while V2 echoes the real applied value. Comparing what we asked for
4625
- // against what the trigger response reports self-corrects the day the
4626
- // backend applies the override, with no `v3Enabled` assumption at all.
4627
- // Skipped for a known-backend caller (`opts.type` threaded from the
4628
- // `test create --run` chain): a backend trigger response's `targetUrl`
4629
- // is an unconditional echo of the request body (verified against
4630
- // backend-v2.0's `CliTestsController.createRun` — `targetUrl: body.targetUrl
4631
- // ?? ''` on both the V2 and V3 backend branches), so it can never mismatch
4632
- // and the existing, more specific C1 advisory ("--target-url has no effect
4633
- // for backend tests") already covers this case at create time.
4634
- if (opts.targetUrl !== undefined &&
4635
- opts.type !== 'backend' &&
4636
- triggerResponse.targetUrl !== opts.targetUrl) {
4637
- emitTargetUrlMismatchAdvisory(stderrFn, opts.targetUrl, triggerResponse.targetUrl);
4638
- }
4639
- if (!opts.wait) {
4640
- printRunOrChain(out, triggerResponse, opts.createContext, data => renderTriggerRunText(data));
4641
- if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
4642
- stderrFn(`requestId: ${triggerRequestId}`);
4643
- return triggerResponse;
4644
- }
4645
- // --wait path: poll until terminal.
4646
- const startMs = Date.now();
4647
- void resumedFromConflict; // used above; suppress unused-variable lint
4648
- const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
4649
- // B2(c): emit a one-time hint when the user did not explicitly set --timeout
4650
- // (i.e. the default is in effect). First runs can take several minutes;
4651
- // skipped when --output json (non-interactive consumers don't need the hint).
4652
- if (opts.timeoutIsDefault === true && opts.output !== 'json') {
4653
- stderrFn(`[hint] First runs can take several minutes; raise --timeout if this run is cut short.`);
4654
- }
4655
- // Backend-test fallback (dogfood L1888): BE run rows never finalize, so
4656
- // resolve the verdict from the testId record once it's terminal.
4657
- let beFallbackUsed = false;
4658
- const resolveAlternate = makeBackendWaitFallback({
4659
- client,
4660
- resolveTestId: () => opts.testId,
4661
- resolveNotBefore: () => triggerResponse.enqueuedAt,
4662
- onResolved: testId => {
4663
- beFallbackUsed = true;
4664
- stderrFn(`[advisory] Backend run-surface row is not finalized server-side (dogfood L1888); ` +
4665
- `resolved the verdict from the test record (testId=${testId}). ` +
4666
- `Read full detail with: testsprite test result ${testId}`);
4667
- },
4668
- });
4669
- let finalRun;
4670
- try {
4671
- finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
4672
- timeoutSeconds: opts.timeoutSeconds,
4673
- sleep: deps.sleep,
4674
- shutdown: shutdownOf(deps),
4675
- onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4676
- onTick: (run, elapsedMs) => {
4677
- const elapsed = Math.round(elapsedMs / 1000);
4678
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
4679
- ticker.update(`Run ${run.runId} — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
5029
+ if (!opts.wait) {
5030
+ printRunOrChain(out, triggerResponse, opts.createContext, data => renderTriggerRunText(data));
5031
+ if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
5032
+ stderrFn(`requestId: ${triggerRequestId}`);
5033
+ return triggerResponse;
5034
+ }
5035
+ // --wait path: poll until terminal.
5036
+ const startMs = Date.now();
5037
+ void resumedFromConflict; // used above; suppress unused-variable lint
5038
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
5039
+ // B2(c): emit a one-time hint when the user did not explicitly set --timeout
5040
+ // (i.e. the default is in effect). First runs can take several minutes;
5041
+ // skipped when --output json (non-interactive consumers don't need the hint).
5042
+ if (opts.timeoutIsDefault === true && opts.output !== 'json') {
5043
+ stderrFn(`[hint] First runs can take several minutes; raise --timeout if this run is cut short.`);
5044
+ }
5045
+ // Backend-test fallback (dogfood L1888): BE run rows never finalize, so
5046
+ // resolve the verdict from the testId record once it's terminal.
5047
+ let beFallbackUsed = false;
5048
+ const resolveBackendAlternate = makeBackendWaitFallback({
5049
+ client,
5050
+ resolveTestId: () => opts.testId,
5051
+ resolveNotBefore: () => triggerResponse.enqueuedAt,
5052
+ onResolved: testId => {
5053
+ beFallbackUsed = true;
5054
+ stderrFn(`[advisory] Backend run-surface row is not finalized server-side (dogfood L1888); ` +
5055
+ `resolved the verdict from the test record (testId=${testId}). ` +
5056
+ `Read full detail with: testsprite test result ${testId}`);
4680
5057
  },
4681
- resolveAlternate,
4682
5058
  });
4683
- }
4684
- catch (err) {
4685
- if (err instanceof TimeoutError) {
4686
- ticker.finalize(`Run ${triggerResponse.runId} — timed out after ${opts.timeoutSeconds}s`);
4687
- // Mirror the RequestTimeoutError path: emit a partial run to stdout so
4688
- // JSON consumers and AI agents can grab the runId and chain into
4689
- // `testsprite test wait <runId>` without parsing the stderr error envelope.
4690
- const timeoutPartial = {
5059
+ const checkBorrowedTunnelLiveness = tunnelSession?.adopted
5060
+ ? makeBorrowedTunnelLivenessCheck({
5061
+ // Liveness failures are deliberately silent even under --verbose or
5062
+ // --debug: they are unknown observations, not user-facing events.
5063
+ client: makeClient({ ...clientOpts, debug: false, verbose: false }, { ...deps, stderr: () => { } }),
5064
+ clientId: tunnelSession.clientId,
4691
5065
  runId: triggerResponse.runId,
4692
- status: 'running',
4693
- enqueuedAt: triggerResponse.enqueuedAt,
4694
- codeVersion: triggerResponse.codeVersion,
4695
- targetUrl: triggerResponse.targetUrl || null,
5066
+ })
5067
+ : undefined;
5068
+ // `resolveAlternate` is called only after a non-terminal run tick. Keeping
5069
+ // the async borrowed-client read here prevents terminal runs from paying an
5070
+ // extra GET and ensures any conclusive loss is caught by this command's
5071
+ // normal detach/teardown path. Owned runs receive the original callback
5072
+ // object unchanged and issue no liveness request.
5073
+ const resolveAlternate = checkBorrowedTunnelLiveness === undefined
5074
+ ? resolveBackendAlternate
5075
+ : async (run, elapsedMs, signal) => {
5076
+ await checkBorrowedTunnelLiveness(signal);
5077
+ return resolveBackendAlternate(run, elapsedMs, signal);
4696
5078
  };
4697
- printRunOrChain(out, timeoutPartial, opts.createContext, data => {
4698
- const p = data;
4699
- const lines = [
4700
- `runId ${p.runId}`,
4701
- `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
4702
- ];
4703
- if (p.targetUrl)
4704
- lines.push(`targetUrl ${p.targetUrl}`);
4705
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4706
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4707
- return lines.join('\n');
4708
- });
4709
- throw ApiError.fromEnvelope({
4710
- error: {
4711
- code: 'UNSUPPORTED', // exit 7 per errors.md
4712
- message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}. ` +
4713
- stillRunningAndBillingSubject(triggerResponse.runId),
4714
- nextAction: `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
4715
- requestId: 'local',
4716
- details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
5079
+ // Keeps the elapsed counter moving between long-poll returns (~25s apart).
5080
+ // Armed only when the ticker redraws in place (its own TTY / NO_COLOR call).
5081
+ const live = createLiveRunProgress(ticker);
5082
+ let finalRun;
5083
+ try {
5084
+ finalRun = await pollRunUntilTerminal(client, triggerResponse.runId, {
5085
+ timeoutSeconds: opts.timeoutSeconds,
5086
+ sleep: deps.sleep,
5087
+ shutdown,
5088
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5089
+ onTick: (run, elapsedMs) => {
5090
+ // The tunnel is checked on every tick rather than through an abort
5091
+ // signal because there is nothing to race: once the control channel
5092
+ // is terminally closed the run is already doomed, and one long-poll
5093
+ // cycle of latency costs far less than plumbing a second abort
5094
+ // source through the shared poll loop for every ordinary run.
5095
+ if (!isTerminalStatus(run.status)) {
5096
+ const fatal = tunnelSession?.fatalReason();
5097
+ if (fatal !== undefined)
5098
+ throw new TunnelLostError(fatal, triggerResponse.runId);
5099
+ }
5100
+ live.onTick(run, elapsedMs);
4717
5101
  },
5102
+ resolveAlternate,
4718
5103
  });
4719
5104
  }
4720
- // C+D: RequestTimeoutError during polling — emit a partial object to stdout
4721
- // routed through printRunOrChain so:
4722
- // TEXT mode: renders human-readable (not raw JSON)
4723
- // JSON mode: preserves the merged create-chain envelope
4724
- // { ...createContext, run: { runId, status, targetUrl } }
4725
- // targetUrl is taken from triggerResponse, which is already bound to
4726
- // the real in-flight URL (see Finding D fix in the 409 resume path).
4727
- if (err instanceof RequestTimeoutError) {
4728
- ticker.finalize(`Run ${triggerResponse.runId} — request timed out`);
4729
- const partial = {
4730
- runId: triggerResponse.runId,
4731
- status: 'running',
4732
- enqueuedAt: triggerResponse.enqueuedAt,
4733
- codeVersion: triggerResponse.codeVersion,
4734
- targetUrl: triggerResponse.targetUrl || null,
4735
- };
4736
- printRunOrChain(out, partial, opts.createContext, data => {
4737
- const p = data;
4738
- const lines = [`runId ${p.runId}`, `status ${p.status} (request timed out)`];
4739
- if (p.targetUrl)
4740
- lines.push(`targetUrl ${p.targetUrl}`);
4741
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4742
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4743
- return lines.join('\n');
4744
- });
4745
- stderrFn(`Request timed out. ${stillRunningAndBillingSubject(triggerResponse.runId)} ` +
4746
- `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
4747
- throw err;
4748
- }
4749
- // RATE_LIMITED during polling — the backend's pre-auth rate limiter can
4750
- // trip on a shared egress IP (CI runner, NAT) and 429 an otherwise-valid
4751
- // key for its window; the HTTP layer already retried internally and gave
4752
- // up. The run was already triggered (and billed) and keeps executing
4753
- // server-side, so this must not be a silent, runId-less death: same
4754
- // partial-envelope contract as the RequestTimeoutError branch above, and
4755
- // the SAME thrown ApiError is rethrown unchanged so its native exit code
4756
- // (11) is preserved — never reclassified to 7.
4757
- if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
4758
- ticker.finalize(`Run ${triggerResponse.runId} — rate limited by the server`);
4759
- const partial = {
4760
- runId: triggerResponse.runId,
4761
- status: 'running',
4762
- enqueuedAt: triggerResponse.enqueuedAt,
4763
- codeVersion: triggerResponse.codeVersion,
4764
- targetUrl: triggerResponse.targetUrl || null,
5105
+ catch (err) {
5106
+ // Stop redrawing BEFORE any final line below is written, so a stale
5107
+ // "running · Ns" can never land after "timed out" / "interrupted".
5108
+ live.stop();
5109
+ // A tunnel run that stops being waited on is a tunnel run that is about
5110
+ // to lose its tunnel, on ALL of these paths. `cancelOnInterrupt` defaults
5111
+ // ON here and only here — for an ordinary run, detaching leaves something
5112
+ // that can still pass, which is why DEV-331 deliberately did not cancel.
5113
+ const settleTunnelDetach = async (reason) => {
5114
+ if (tunnelSession === undefined || tunnelSession.adopted)
5115
+ return undefined;
5116
+ const cancel = await cancelDoomedTunnelRun({
5117
+ runId: triggerResponse.runId,
5118
+ enabled: opts.cancelOnInterrupt !== false,
5119
+ opts,
5120
+ deps,
5121
+ });
5122
+ return {
5123
+ runId: triggerResponse.runId,
5124
+ testId: opts.testId,
5125
+ localPort: opts.localPort,
5126
+ reason,
5127
+ cancel: cancel.outcome,
5128
+ ...(cancel.terminalStatus !== undefined ? { terminalStatus: cancel.terminalStatus } : {}),
5129
+ };
4765
5130
  };
4766
- printRunOrChain(out, partial, opts.createContext, data => {
4767
- const p = data;
4768
- const lines = [
4769
- `runId ${p.runId}`,
4770
- `status ${p.status} (rate limited by the server)`,
4771
- ];
4772
- if (p.targetUrl)
4773
- lines.push(`targetUrl ${p.targetUrl}`);
4774
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4775
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4776
- return lines.join('\n');
4777
- });
4778
- stderrFn(rateLimitedDetachMessage(err, [triggerResponse.runId]));
5131
+ if (err instanceof TunnelLostError) {
5132
+ ticker.finalize(`Run ${triggerResponse.runId} — tunnel disconnected`);
5133
+ const detach = await settleTunnelDetach('tunnel-lost');
5134
+ const partial = {
5135
+ runId: triggerResponse.runId,
5136
+ status: detachPartialStatus(detach),
5137
+ enqueuedAt: triggerResponse.enqueuedAt,
5138
+ codeVersion: triggerResponse.codeVersion,
5139
+ targetUrl: triggerResponse.targetUrl || null,
5140
+ };
5141
+ printRunOrChain(out, partial, opts.createContext, data => {
5142
+ const pr = data;
5143
+ const lines = [
5144
+ `runId ${pr.runId}`,
5145
+ `status ${pr.status} (tunnel disconnected)`,
5146
+ ];
5147
+ if (pr.targetUrl)
5148
+ lines.push(`targetUrl ${pr.targetUrl}`);
5149
+ lines.push(...detachHintLines(pr.runId, detach));
5150
+ return lines.join('\n');
5151
+ });
5152
+ if (detach)
5153
+ stderrFn(tunnelDetachMessage(detach));
5154
+ throw err;
5155
+ }
5156
+ if (err instanceof TimeoutError) {
5157
+ ticker.finalize(`Run ${triggerResponse.runId} — timed out after ${opts.timeoutSeconds}s`);
5158
+ // Mirror the RequestTimeoutError path: emit a partial run to stdout so
5159
+ // JSON consumers and AI agents can grab the runId and chain into
5160
+ // `testsprite test wait <runId>` without parsing the stderr error envelope.
5161
+ const detach = await settleTunnelDetach('timeout');
5162
+ const timeoutPartial = {
5163
+ runId: triggerResponse.runId,
5164
+ status: detachPartialStatus(detach),
5165
+ enqueuedAt: triggerResponse.enqueuedAt,
5166
+ codeVersion: triggerResponse.codeVersion,
5167
+ targetUrl: triggerResponse.targetUrl || null,
5168
+ };
5169
+ printRunOrChain(out, timeoutPartial, opts.createContext, data => {
5170
+ const p = data;
5171
+ const lines = [
5172
+ `runId ${p.runId}`,
5173
+ `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
5174
+ ];
5175
+ if (p.targetUrl)
5176
+ lines.push(`targetUrl ${p.targetUrl}`);
5177
+ lines.push(...detachHintLines(p.runId, detach));
5178
+ return lines.join('\n');
5179
+ });
5180
+ if (detach)
5181
+ stderrFn(tunnelDetachMessage(detach));
5182
+ throw ApiError.fromEnvelope({
5183
+ error: {
5184
+ code: 'UNSUPPORTED', // exit 7 per errors.md
5185
+ message: detach
5186
+ ? `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}, ` +
5187
+ `which could not have finished without this process holding its tunnel open.`
5188
+ : `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}. ` +
5189
+ stillRunningAndBillingSubject(triggerResponse.runId),
5190
+ nextAction: detach
5191
+ ? `Start it again with --local and a longer --timeout; a retry mints a fresh tunnel.`
5192
+ : `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
5193
+ requestId: 'local',
5194
+ details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
5195
+ },
5196
+ });
5197
+ }
5198
+ // C+D: RequestTimeoutError during polling — emit a partial object to stdout
5199
+ // routed through printRunOrChain so:
5200
+ // TEXT mode: renders human-readable (not raw JSON)
5201
+ // JSON mode: preserves the merged create-chain envelope
5202
+ // { ...createContext, run: { runId, status, targetUrl } }
5203
+ // targetUrl is taken from triggerResponse, which is already bound to
5204
+ // the real in-flight URL (see Finding D fix in the 409 resume path).
5205
+ if (err instanceof RequestTimeoutError) {
5206
+ ticker.finalize(`Run ${triggerResponse.runId} — request timed out`);
5207
+ const detach = await settleTunnelDetach('request-timeout');
5208
+ const partial = {
5209
+ runId: triggerResponse.runId,
5210
+ status: detachPartialStatus(detach),
5211
+ enqueuedAt: triggerResponse.enqueuedAt,
5212
+ codeVersion: triggerResponse.codeVersion,
5213
+ targetUrl: triggerResponse.targetUrl || null,
5214
+ };
5215
+ printRunOrChain(out, partial, opts.createContext, data => {
5216
+ const p = data;
5217
+ const lines = [`runId ${p.runId}`, `status ${p.status} (request timed out)`];
5218
+ if (p.targetUrl)
5219
+ lines.push(`targetUrl ${p.targetUrl}`);
5220
+ lines.push(...detachHintLines(p.runId, detach));
5221
+ return lines.join('\n');
5222
+ });
5223
+ stderrFn(detach
5224
+ ? tunnelDetachMessage(detach)
5225
+ : `Request timed out. ${stillRunningAndBillingSubject(triggerResponse.runId)} ` +
5226
+ `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
5227
+ throw err;
5228
+ }
5229
+ // RATE_LIMITED during polling — the backend's pre-auth rate limiter can
5230
+ // trip on a shared egress IP (CI runner, NAT) and 429 an otherwise-valid
5231
+ // key for its window; the HTTP layer already retried internally and gave
5232
+ // up. The run was already triggered (and billed) and keeps executing
5233
+ // server-side, so this must not be a silent, runId-less death: same
5234
+ // partial-envelope contract as the RequestTimeoutError branch above, and
5235
+ // the SAME thrown ApiError is rethrown unchanged so its native exit code
5236
+ // (11) is preserved — never reclassified to 7.
5237
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
5238
+ ticker.finalize(`Run ${triggerResponse.runId} — rate limited by the server`);
5239
+ // The cancel this issues is itself a request to the same rate-limited
5240
+ // API, so it may well be refused. `cancelDoomedTunnelRun` reports that
5241
+ // honestly and the message names `test cancel` rather than claiming a
5242
+ // cancel that did not happen.
5243
+ const detach = await settleTunnelDetach('rate-limited');
5244
+ const partial = {
5245
+ runId: triggerResponse.runId,
5246
+ status: detachPartialStatus(detach),
5247
+ enqueuedAt: triggerResponse.enqueuedAt,
5248
+ codeVersion: triggerResponse.codeVersion,
5249
+ targetUrl: triggerResponse.targetUrl || null,
5250
+ };
5251
+ printRunOrChain(out, partial, opts.createContext, data => {
5252
+ const p = data;
5253
+ const lines = [
5254
+ `runId ${p.runId}`,
5255
+ `status ${p.status} (rate limited by the server)`,
5256
+ ];
5257
+ if (p.targetUrl)
5258
+ lines.push(`targetUrl ${p.targetUrl}`);
5259
+ lines.push(...detachHintLines(p.runId, detach));
5260
+ return lines.join('\n');
5261
+ });
5262
+ stderrFn(detach
5263
+ ? tunnelDetachMessage(detach)
5264
+ : rateLimitedDetachMessage(err, [triggerResponse.runId]));
5265
+ throw err;
5266
+ }
5267
+ // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
5268
+ // envelope shape as the timeout paths so stdout stays parseable, plus the
5269
+ // honest "keeps running and billing" stderr line. Rethrow → index.ts
5270
+ // renders the INTERRUPTED envelope and exits 128+signum.
5271
+ if (err instanceof InterruptError) {
5272
+ ticker.finalize(`Run ${triggerResponse.runId} — interrupted (${err.signal})`);
5273
+ const detach = await settleTunnelDetach('interrupt');
5274
+ const partial = {
5275
+ runId: triggerResponse.runId,
5276
+ status: detachPartialStatus(detach),
5277
+ enqueuedAt: triggerResponse.enqueuedAt,
5278
+ codeVersion: triggerResponse.codeVersion,
5279
+ targetUrl: triggerResponse.targetUrl || null,
5280
+ };
5281
+ printRunOrChain(out, partial, opts.createContext, data => {
5282
+ const p = data;
5283
+ const lines = [`runId ${p.runId}`, `status ${p.status} (interrupted)`];
5284
+ if (p.targetUrl)
5285
+ lines.push(`targetUrl ${p.targetUrl}`);
5286
+ lines.push(...detachHintLines(p.runId, detach));
5287
+ return lines.join('\n');
5288
+ });
5289
+ stderrFn(detach
5290
+ ? tunnelDetachMessage(detach, err)
5291
+ : interruptDetachMessage(err, [triggerResponse.runId]));
5292
+ if (detach !== undefined)
5293
+ attachTunnelInterruptDetach(err, detach);
5294
+ throw err;
5295
+ }
5296
+ // Any other poll failure still leaves us holding a known, charged runId.
5297
+ // An owned tunnel is about to close in the outer finally, so settle the
5298
+ // run exactly like the classified detach paths before preserving the
5299
+ // original error object/type/code/message for the caller.
5300
+ const detach = await settleTunnelDetach('poll-error');
5301
+ if (detach !== undefined) {
5302
+ ticker.finalize(`Run ${triggerResponse.runId} — polling stopped`);
5303
+ const partial = {
5304
+ runId: triggerResponse.runId,
5305
+ status: detachPartialStatus(detach),
5306
+ enqueuedAt: triggerResponse.enqueuedAt,
5307
+ codeVersion: triggerResponse.codeVersion,
5308
+ targetUrl: triggerResponse.targetUrl || null,
5309
+ };
5310
+ printRunOrChain(out, partial, opts.createContext, data => {
5311
+ const p = data;
5312
+ const lines = [`runId ${p.runId}`, `status ${p.status} (polling stopped)`];
5313
+ if (p.targetUrl)
5314
+ lines.push(`targetUrl ${p.targetUrl}`);
5315
+ lines.push(...detachHintLines(p.runId, detach));
5316
+ return lines.join('\n');
5317
+ });
5318
+ stderrFn(tunnelDetachMessage(detach));
5319
+ }
5320
+ else {
5321
+ ticker.finalize();
5322
+ }
4779
5323
  throw err;
4780
5324
  }
4781
- // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
4782
- // envelope shape as the timeout paths so stdout stays parseable, plus the
4783
- // honest "keeps running and billing" stderr line. Rethrow → index.ts
4784
- // renders the INTERRUPTED envelope and exits 128+signum.
4785
- if (err instanceof InterruptError) {
4786
- ticker.finalize(`Run ${triggerResponse.runId} — interrupted (${err.signal})`);
4787
- const partial = {
4788
- runId: triggerResponse.runId,
4789
- status: 'running',
4790
- enqueuedAt: triggerResponse.enqueuedAt,
4791
- codeVersion: triggerResponse.codeVersion,
4792
- targetUrl: triggerResponse.targetUrl || null,
4793
- };
4794
- printRunOrChain(out, partial, opts.createContext, data => {
4795
- const p = data;
4796
- const lines = [`runId ${p.runId}`, `status ${p.status} (interrupted)`];
4797
- if (p.targetUrl)
4798
- lines.push(`targetUrl ${p.targetUrl}`);
4799
- lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4800
- lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4801
- return lines.join('\n');
4802
- });
4803
- stderrFn(interruptDetachMessage(err, [triggerResponse.runId]));
4804
- throw err;
5325
+ finally {
5326
+ live.stop();
5327
+ }
5328
+ ticker.finalize(formatRunProgressLine(finalRun, Date.now() - startMs));
5329
+ // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs); on
5330
+ // the standalone `test run <id>` path neither is set, so probe the test type
5331
+ // once (text mode only, best-effort) — DEV-282.
5332
+ const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
5333
+ const finalRunWithUrl = withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps));
5334
+ printRunOrChain(out, finalRunWithUrl, opts.createContext, data => renderRunResponseText(data, { isBackend }));
5335
+ // Surface the trigger requestId under --verbose/--debug or JSON mode so
5336
+ // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
5337
+ // JSON mode always emits to stderr — it never pollutes stdout).
5338
+ if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
5339
+ stderrFn(`requestId: ${triggerRequestId}`);
5340
+ if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
5341
+ // BE runs have no run-scoped artifact bundle — their failure bundle is
5342
+ // addressed by testId, not runId.
5343
+ stderrFn(isBackend
5344
+ ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
5345
+ : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
4805
5346
  }
4806
- ticker.finalize();
4807
- throw err;
4808
- }
4809
- const elapsed = Math.round((Date.now() - startMs) / 1000);
4810
- const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
4811
- ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
4812
- // BE detection: type hint (create-chain) OR beFallbackUsed (slow runs); on
4813
- // the standalone `test run <id>` path neither is set, so probe the test type
4814
- // once (text mode only, best-effort) — DEV-282.
4815
- const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
4816
- const finalRunWithUrl = withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps));
4817
- printRunOrChain(out, finalRunWithUrl, opts.createContext, data => renderRunResponseText(data, { isBackend }));
4818
- // Surface the trigger requestId under --verbose/--debug or JSON mode so
4819
- // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
4820
- // JSON mode always emits to stderr — it never pollutes stdout).
4821
- if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
4822
- stderrFn(`requestId: ${triggerRequestId}`);
4823
- if (finalRun.status === 'failed' || finalRun.status === 'blocked') {
4824
- // BE runs have no run-scoped artifact bundle — their failure bundle is
4825
- // addressed by testId, not runId.
4826
- stderrFn(isBackend
4827
- ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
4828
- : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
4829
- }
4830
- // CI-native output layer (issue #99): single-test parity with the --all batch.
4831
- // Emitted before the exit-code gate throws below so the summary file and
4832
- // annotations land even when the run exits non-zero (mirrors the batch path).
4833
- // The summary file is a machine artifact written regardless of --output mode;
4834
- // under --output json the run envelope above owns stdout, so ::error::
4835
- // workflow commands are routed to stderr (the Actions runner parses both).
4836
- // Best-effort: a sink write throwing (e.g. EPIPE) must never skip the
4837
- // exit-code gate below or change the command's exit status.
4838
- try {
4839
- emitCiArtifacts(summarizeSingleRun(finalRunWithUrl), opts, {
4840
- env: deps.env ?? process.env,
4841
- stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
4842
- stderr: stderrFn,
4843
- }, 'run');
4844
- }
4845
- catch (ciErr) {
4846
- stderrFn(`[run] CI output emission failed; continuing: ${ciErr.message}`);
5347
+ // CI-native output layer (issue #99): single-test parity with the --all batch.
5348
+ // Emitted before the exit-code gate throws below so the summary file and
5349
+ // annotations land even when the run exits non-zero (mirrors the batch path).
5350
+ // The summary file is a machine artifact written regardless of --output mode;
5351
+ // under --output json the run envelope above owns stdout, so ::error::
5352
+ // workflow commands are routed to stderr (the Actions runner parses both).
5353
+ // Best-effort: a sink write throwing (e.g. EPIPE) must never skip the
5354
+ // exit-code gate below or change the command's exit status.
5355
+ try {
5356
+ emitCiArtifacts(summarizeSingleRun(finalRunWithUrl), opts, {
5357
+ env: deps.env ?? process.env,
5358
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
5359
+ stderr: stderrFn,
5360
+ }, 'run');
5361
+ }
5362
+ catch (ciErr) {
5363
+ stderrFn(`[run] CI output emission failed; continuing: ${ciErr.message}`);
5364
+ }
5365
+ const exitCode = exitCodeForRunStatus(finalRun.status);
5366
+ if (exitCode !== 0) {
5367
+ // Throw a CLIError so index.ts exits with the right code without
5368
+ // printing an error envelope — the result was already printed above.
5369
+ throw new CLIError(`Run ${finalRun.runId} finished with status: ${finalRun.status}`, exitCode);
5370
+ }
5371
+ return finalRun;
4847
5372
  }
4848
- const exitCode = exitCodeForRunStatus(finalRun.status);
4849
- if (exitCode !== 0) {
4850
- // Throw a CLIError so index.ts exits with the right code without
4851
- // printing an error envelope — the result was already printed above.
4852
- throw new CLIError(`Run ${finalRun.runId} finished with status: ${finalRun.status}`, exitCode);
5373
+ finally {
5374
+ // Every exit path — success, run failure, timeout, signal, a throw from
5375
+ // the trigger itself — releases the tunnel and deletes the binding.
5376
+ // Skipping this on any one of them leaves a live inbound credential and a
5377
+ // client whose ref'd heartbeat timer keeps the process alive after the
5378
+ // command has printed its last line.
5379
+ try {
5380
+ await tunnelSession?.close();
5381
+ }
5382
+ finally {
5383
+ disarmTunnelLifecycle?.();
5384
+ }
4853
5385
  }
4854
- return finalRun;
4855
5386
  }
4856
5387
  /**
4857
5388
  * `test wait <run-id...>` with two or more ids: attach to N already-dispatched
@@ -5292,6 +5823,9 @@ export async function runTestWait(opts, deps = {}) {
5292
5823
  `Read full detail with: testsprite test result ${testId}`);
5293
5824
  },
5294
5825
  });
5826
+ // Keeps the elapsed counter moving between long-poll returns (~25s apart).
5827
+ // Armed only when the ticker redraws in place (its own TTY / NO_COLOR call).
5828
+ const live = createLiveRunProgress(ticker);
5295
5829
  let finalRun;
5296
5830
  try {
5297
5831
  finalRun = await pollRunUntilTerminal(client, opts.runId, {
@@ -5299,15 +5833,14 @@ export async function runTestWait(opts, deps = {}) {
5299
5833
  sleep: deps.sleep,
5300
5834
  shutdown: shutdownOf(deps),
5301
5835
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5302
- onTick: (run, elapsedMs) => {
5303
- const elapsed = Math.round(elapsedMs / 1000);
5304
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5305
- ticker.update(`Run ${run.runId} — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
5306
- },
5836
+ onTick: live.onTick,
5307
5837
  resolveAlternate,
5308
5838
  });
5309
5839
  }
5310
5840
  catch (err) {
5841
+ // Stop redrawing BEFORE any final line below is written, so a stale
5842
+ // "running · Ns" can never land after "timed out" / "interrupted".
5843
+ live.stop();
5311
5844
  if (err instanceof TimeoutError) {
5312
5845
  ticker.finalize(`Run ${opts.runId} — timed out after ${opts.timeoutSeconds}s`);
5313
5846
  // Mirror the RequestTimeoutError path: emit a partial run to stdout so
@@ -5392,9 +5925,10 @@ export async function runTestWait(opts, deps = {}) {
5392
5925
  ticker.finalize();
5393
5926
  throw err;
5394
5927
  }
5395
- const elapsed = Math.round((Date.now() - startMs) / 1000);
5396
- const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5397
- ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
5928
+ finally {
5929
+ live.stop();
5930
+ }
5931
+ ticker.finalize(formatRunProgressLine(finalRun, Date.now() - startMs));
5398
5932
  // `test wait` has no type hint; probe the test type once (text mode only,
5399
5933
  // best-effort) so a backend run's card reads `n/a (backend)` — DEV-282.
5400
5934
  const isBackend = await resolveRunCardIsBackend(client, finalRun.testId, opts.output, beFallbackUsed);
@@ -5447,16 +5981,20 @@ async function buildTestNameMap(client, projectId) {
5447
5981
  }
5448
5982
  return map;
5449
5983
  }
5450
- async function writeBatchJUnitReportIfRequested(opts, results, nameByTestId) {
5984
+ export async function writeBatchJUnitReportIfRequested(opts, results, nameByTestId) {
5451
5985
  if (opts.report !== 'junit' || opts.reportFile === undefined)
5452
5986
  return;
5453
5987
  const projectId = resolveBatchReportProjectId(opts, results);
5454
5988
  const suiteName = opts.reportSuiteName ?? `testsprite:${projectId}`;
5455
5989
  // Enrich each row with the human name (from the map) and the run duration
5456
5990
  // (from poll timing) — the two fields whose absence made the report unreadable.
5991
+ // Name precedence: the sweep map wins (it's a full page scan), then the poll
5992
+ // response's own `testTitle` (same source the summary table uses — this keeps
5993
+ // the two surfaces on the same name when the sweep over-pages / times out),
5994
+ // then the row's fallback name. `.trim() ||` so a blank title never shadows it.
5457
5995
  const enriched = results.map(r => ({
5458
5996
  ...r,
5459
- name: nameByTestId?.get(r.testId) ?? r.name,
5997
+ name: nameByTestId?.get(r.testId) ?? (r.testTitle?.trim() ? r.testTitle : undefined) ?? r.name,
5460
5998
  durationSeconds: r.durationSeconds ?? durationSecondsBetween(r.startedAt, r.finishedAt),
5461
5999
  }));
5462
6000
  const xml = buildJUnitReport({
@@ -5466,6 +6004,70 @@ async function writeBatchJUnitReportIfRequested(opts, results, nameByTestId) {
5466
6004
  });
5467
6005
  await writeJUnitReportFile(opts.reportFile, xml);
5468
6006
  }
6007
+ /** Human explanation for a zero-dispatch batch, from what the engine skipped. */
6008
+ function zeroDispatchReason(skippedFrontend, skippedIntegration) {
6009
+ const parts = [];
6010
+ if (skippedFrontend.length > 0) {
6011
+ 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>')`);
6012
+ }
6013
+ if (skippedIntegration.length > 0) {
6014
+ parts.push(`${skippedIntegration.length} assembled integration test${skippedIntegration.length !== 1 ? 's' : ''} skipped (run via the portal)`);
6015
+ }
6016
+ return parts.length > 0
6017
+ ? `all resolved tests were skipped: ${parts.join('; ')}`
6018
+ : 'no runnable tests in the project';
6019
+ }
6020
+ /**
6021
+ * Handle a batch invocation that dispatched ZERO tests — all skipped, an empty
6022
+ * project, or a `--filter` that matched nothing. Left alone this exits 0 with no
6023
+ * artifact, a CI false-green: a gate that greens on zero tests is worse than no
6024
+ * gate (DEV-1046). So it emits the CI artifacts (summary + `::error::` annotation
6025
+ * + JUnit report) so the gate shows WHY, then fails with **exit 5** unless the
6026
+ * caller passed `--allow-empty` (in which case it returns and the caller exits 0).
6027
+ *
6028
+ * `skipped` is the union of skipped FE + integration tests (rendered as
6029
+ * `<skipped/>` JUnit cases and non-passed summary rows so they're visible);
6030
+ * `reason` is the human explanation shown in the annotation and the throw.
6031
+ */
6032
+ async function finishZeroDispatchBatch(params) {
6033
+ const { reason, skipped, allowEmpty, opts, deps, stderrFn, label = 'run' } = params;
6034
+ const runs = skipped.length > 0
6035
+ ? skipped.map(testId => ({ testId, status: 'skipped', error: reason }))
6036
+ : [{ testId: '(no tests)', status: 'no_tests', error: reason }];
6037
+ const summary = {
6038
+ total: runs.length,
6039
+ passed: 0,
6040
+ failed: runs.length,
6041
+ timedOut: 0,
6042
+ runs,
6043
+ };
6044
+ // Emit the in-memory artifacts (summary + `::error::` annotation) FIRST: they
6045
+ // can't fail on I/O, so the "show WHY it's red" diagnostics always land — even
6046
+ // if the JUnit path below is misconfigured. Ordering these after the file write
6047
+ // would let an unwritable --report-file throw (exit 10) preempt both the
6048
+ // diagnostics AND the exit-5 gate, masking the zero-dispatch cause.
6049
+ emitCiArtifacts(summary, opts, {
6050
+ env: deps.env ?? process.env,
6051
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
6052
+ stderr: stderrFn,
6053
+ }, label);
6054
+ // Then the JUnit sidecar (the other half of "no artifact was produced before").
6055
+ // `writeBatchJUnitReportIfRequested` no-ops unless --report junit. Degrade a
6056
+ // write failure to a warning so an unwritable path can't mask the exit-5 intent
6057
+ // with an I/O exit code.
6058
+ try {
6059
+ await writeBatchJUnitReportIfRequested(opts, runs.map(r => ({ testId: r.testId, status: 'skipped' })));
6060
+ }
6061
+ catch (err) {
6062
+ stderrFn(`[${label}] could not write the JUnit report on a zero-dispatch run: ${err instanceof Error ? err.message : String(err)}; continuing`);
6063
+ }
6064
+ if (allowEmpty) {
6065
+ stderrFn(`[${label}] 0 tests dispatched (${reason}); --allow-empty set — exiting 0.`);
6066
+ return;
6067
+ }
6068
+ throw new CLIError(`No tests were dispatched — ${reason}. A CI gate that passes on zero tests is unsafe; ` +
6069
+ `pass --allow-empty to exit 0 intentionally.`, 5);
6070
+ }
5469
6071
  /**
5470
6072
  * `test run --all --project <id>` — M4 piece-2.
5471
6073
  *
@@ -5524,10 +6126,23 @@ export async function runTestRunAll(opts, deps = {}) {
5524
6126
  // Both stay undefined for unknown API hosts (resolvePortalBase contract).
5525
6127
  const batchApiUrl = resolveApiUrl(opts, deps);
5526
6128
  const batchPortalBase = resolvePortalBase(batchApiUrl);
5527
- const projectDashboardUrl = batchPortalBase === undefined
6129
+ // The project-level closing link is resolved AFTER the trigger (below): the
6130
+ // server now carries it for a V3-served batch, and `resolveDashboardUrl`'s
6131
+ // absent-vs-present rule decides whether this legacy template still applies.
6132
+ const legacyProjectDashboardUrl = () => batchPortalBase === undefined
5528
6133
  ? undefined
5529
6134
  : `${batchPortalBase}/dashboard/tests/${encodeURIComponent(projectId)}`;
5530
6135
  const withBatchDashboardUrl = (item) => {
6136
+ // Prefer the SERVER-built link the poll already captured onto the row — only
6137
+ // the server knows which store answered and can resolve a non-prod origin, and
6138
+ // for a V3-native project the client's V2-shaped guess is structurally dead
6139
+ // (the same footgun that 404'd MCP report links for months). Fall back to the
6140
+ // client guess only when the server sent none (older backend). `executionUrl`,
6141
+ // when present, rides through untouched — it is never client-built.
6142
+ // TODO: drop the resolvePortalUrl fallback once the server dashboardUrl has
6143
+ // shipped in every environment — it only serves runs from an older backend.
6144
+ if (typeof item.dashboardUrl === 'string')
6145
+ return item;
5531
6146
  const dashboardUrl = resolvePortalUrl(batchApiUrl, projectId, item.testId);
5532
6147
  return dashboardUrl !== undefined ? { ...item, dashboardUrl } : item;
5533
6148
  };
@@ -5559,6 +6174,17 @@ export async function runTestRunAll(opts, deps = {}) {
5559
6174
  skippedFrontend: [],
5560
6175
  skippedIntegration: [],
5561
6176
  });
6177
+ // Zero-dispatch (a --filter that matched nothing): emit the CI artifacts
6178
+ // and fail unless --allow-empty, so a renamed test can't turn a filtered
6179
+ // gate permanently green (DEV-1046). Returns here only under --allow-empty.
6180
+ await finishZeroDispatchBatch({
6181
+ reason: `--filter "${opts.nameFilter}" matched no tests in project ${projectId}`,
6182
+ skipped: [],
6183
+ allowEmpty: opts.allowEmpty === true,
6184
+ opts,
6185
+ deps,
6186
+ stderrFn,
6187
+ });
5562
6188
  return undefined;
5563
6189
  }
5564
6190
  stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${projectId} for batch run.`);
@@ -5570,6 +6196,13 @@ export async function runTestRunAll(opts, deps = {}) {
5570
6196
  ...(testIds !== undefined ? { testIds } : {}),
5571
6197
  source: 'cli',
5572
6198
  }, { idempotencyKey });
6199
+ // Project-level "watch it here" link. A V3 backend sends it (string, or
6200
+ // `null` when no single page exists — e.g. a `--all` that fanned out over
6201
+ // several sibling projects); an older backend / the V2 engine omits the key,
6202
+ // and only then does the client's legacy `/dashboard/tests/{projectId}`
6203
+ // template apply — for a V3 reader that shape bounced onto a route that does
6204
+ // not exist, which is why the server took it over.
6205
+ const { dashboardUrl: projectDashboardUrl } = resolveDashboardUrl(batchResp, legacyProjectDashboardUrl);
5573
6206
  // Mutable: D3 deferred-retry loop may append to `accepted`, drain `deferred`,
5574
6207
  // and accumulate additional `conflicts` discovered during retries.
5575
6208
  let accepted = batchResp.accepted.slice();
@@ -5642,6 +6275,18 @@ export async function runTestRunAll(opts, deps = {}) {
5642
6275
  },
5643
6276
  });
5644
6277
  }
6278
+ // Zero dispatched, nothing pending (deferred / conflict already threw above):
6279
+ // all tests were skipped, or the project has none. Don't exit 0 (DEV-1046).
6280
+ if (accepted.length === 0) {
6281
+ await finishZeroDispatchBatch({
6282
+ reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
6283
+ skipped: [...skippedFrontend, ...skippedIntegration.map(s => s.testId)],
6284
+ allowEmpty: opts.allowEmpty === true,
6285
+ opts,
6286
+ deps,
6287
+ stderrFn,
6288
+ });
6289
+ }
5645
6290
  // [P2] Return post-retry state so programmatic callers and the create-chain
5646
6291
  // JSON merge reflect what was actually dispatched, not the stale initial resp.
5647
6292
  return { ...batchResp, accepted, deferred, conflicts };
@@ -5791,17 +6436,17 @@ export async function runTestRunAll(opts, deps = {}) {
5791
6436
  skippedIntegration,
5792
6437
  };
5793
6438
  out.print(finalResp);
5794
- // Nothing was dispatched, but a --wait CI run still needs the exit-6/7 to be
5795
- // visible: emit annotations + summary before the throw below (conflicts /
5796
- // deferred fold into the summary as non-passed rows; skipped* are not folded).
5797
- // Without this an all-in-flight or all-deferred batch fails CI silently.
5798
- emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(finalResp)), opts, {
5799
- env: deps.env ?? process.env,
5800
- stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
5801
- stderr: stderrFn,
5802
- }, 'run');
5803
6439
  // Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
5804
6440
  // mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
6441
+ // Emit the deferred/conflict summary + annotations first so CI shows them (the
6442
+ // pure zero-dispatch fall-through emits its OWN skipped-rows summary below).
6443
+ if (deferred.length > 0 || conflicts.length > 0) {
6444
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(finalResp)), opts, {
6445
+ env: deps.env ?? process.env,
6446
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
6447
+ stderr: stderrFn,
6448
+ }, 'run');
6449
+ }
5805
6450
  if (deferred.length > 0) {
5806
6451
  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);
5807
6452
  }
@@ -5816,7 +6461,18 @@ export async function runTestRunAll(opts, deps = {}) {
5816
6461
  },
5817
6462
  });
5818
6463
  }
5819
- // [P2] Return post-retry state.
6464
+ // Reached only when nothing was queued and nothing is pending: all tests were
6465
+ // skipped, or the project has none. Emit a skipped-rows summary + JUnit and
6466
+ // fail unless --allow-empty — never a silent exit 0 (DEV-1046).
6467
+ await finishZeroDispatchBatch({
6468
+ reason: zeroDispatchReason(skippedFrontend, skippedIntegration),
6469
+ skipped: [...skippedFrontend, ...skippedIntegration.map(s => s.testId)],
6470
+ allowEmpty: opts.allowEmpty === true,
6471
+ opts,
6472
+ deps,
6473
+ stderrFn,
6474
+ });
6475
+ // [P2] Return post-retry state (reached only under --allow-empty).
5820
6476
  return { ...batchResp, accepted, deferred, conflicts };
5821
6477
  }
5822
6478
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
@@ -5855,9 +6511,16 @@ export async function runTestRunAll(opts, deps = {}) {
5855
6511
  });
5856
6512
  return {
5857
6513
  testId: entry.testId,
6514
+ testTitle: finalRun.testTitle ?? null,
5858
6515
  runId,
5859
6516
  projectId: finalRun.projectId,
5860
6517
  status: finalRun.status,
6518
+ ...(typeof finalRun.dashboardUrl === 'string'
6519
+ ? { dashboardUrl: finalRun.dashboardUrl }
6520
+ : {}),
6521
+ ...(typeof finalRun.executionUrl === 'string'
6522
+ ? { executionUrl: finalRun.executionUrl }
6523
+ : {}),
5861
6524
  };
5862
6525
  }
5863
6526
  catch {
@@ -5887,18 +6550,21 @@ export async function runTestRunAll(opts, deps = {}) {
5887
6550
  sleep: deps.sleep,
5888
6551
  shutdown: shutdownOf(deps),
5889
6552
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
5890
- onTick: (run, elapsedMs) => {
5891
- const elapsed = Math.round(elapsedMs / 1000);
5892
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
5893
- ticker.update(`Run ${run.runId} (${entry.testId}) — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
5894
- },
6553
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
5895
6554
  resolveAlternate,
5896
6555
  });
5897
6556
  return {
5898
6557
  testId: entry.testId,
6558
+ testTitle: finalRun.testTitle ?? null,
5899
6559
  runId,
5900
6560
  projectId: finalRun.projectId,
5901
6561
  status: finalRun.status,
6562
+ ...(typeof finalRun.dashboardUrl === 'string'
6563
+ ? { dashboardUrl: finalRun.dashboardUrl }
6564
+ : {}),
6565
+ ...(typeof finalRun.executionUrl === 'string'
6566
+ ? { executionUrl: finalRun.executionUrl }
6567
+ : {}),
5902
6568
  startedAt: finalRun.startedAt,
5903
6569
  finishedAt: finalRun.finishedAt,
5904
6570
  };
@@ -6336,6 +7002,8 @@ export async function runTestRerun(opts, deps = {}) {
6336
7002
  if (r.closure) {
6337
7003
  lines.push(`closure ${r.closure.members.length} members (${r.closure.addedProducers.length} producers added)`);
6338
7004
  }
7005
+ if (r.dashboardUrl)
7006
+ lines.push(`dashboard ${r.dashboardUrl}`);
6339
7007
  return lines.join('\n');
6340
7008
  });
6341
7009
  return rerunResp;
@@ -6362,16 +7030,7 @@ export async function runTestRerun(opts, deps = {}) {
6362
7030
  sleep: deps.sleep,
6363
7031
  shutdown: shutdownOf(deps),
6364
7032
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6365
- onTick: (run, elapsedMs) => {
6366
- const elapsed = Math.round(elapsedMs / 1000);
6367
- const s = run.stepSummary ?? {
6368
- total: 0,
6369
- completed: 0,
6370
- passedCount: 0,
6371
- failedCount: 0,
6372
- };
6373
- ticker.update(`Run ${run.runId} [${member.role}] — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
6374
- },
7033
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `[${member.role}]`)),
6375
7034
  resolveAlternate,
6376
7035
  });
6377
7036
  return { kind: 'terminal', run: finalRun };
@@ -6636,6 +7295,7 @@ export async function runTestRerun(opts, deps = {}) {
6636
7295
  `resolved the verdict from the test record (testId=${tid}).`);
6637
7296
  },
6638
7297
  });
7298
+ const replayStartMs = Date.now();
6639
7299
  let finalRun;
6640
7300
  try {
6641
7301
  finalRun = await pollRunUntilTerminal(client, rerunResp.runId, {
@@ -6643,11 +7303,7 @@ export async function runTestRerun(opts, deps = {}) {
6643
7303
  sleep: deps.sleep,
6644
7304
  shutdown: shutdownOf(deps),
6645
7305
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6646
- onTick: (run, elapsedMs) => {
6647
- const elapsed = Math.round(elapsedMs / 1000);
6648
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
6649
- ticker.update(`Run ${run.runId} — ${run.status} (${s.completed}/${s.total} steps replay elapsed=${elapsed}s)`);
6650
- },
7306
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, '(replay)')),
6651
7307
  resolveAlternate,
6652
7308
  });
6653
7309
  }
@@ -6732,10 +7388,7 @@ export async function runTestRerun(opts, deps = {}) {
6732
7388
  ticker.finalize();
6733
7389
  throw err;
6734
7390
  }
6735
- const elapsed = Math.round(Date.now() / 1000);
6736
- void elapsed;
6737
- const s = finalRun.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
6738
- ticker.finalize(`Run ${finalRun.runId} — ${finalRun.status} (${s.completed}/${s.total} steps replay)`);
7391
+ ticker.finalize(formatRunProgressLine(finalRun, Date.now() - replayStartMs, '(replay)'));
6739
7392
  // Probe the test type once (text mode only, best-effort) so a backend
6740
7393
  // rerun's card reads `n/a (backend)` even when the fallback never fired
6741
7394
  // (BE run rows finalize server-side now) — DEV-282.
@@ -7166,18 +7819,21 @@ export async function runTestRerun(opts, deps = {}) {
7166
7819
  sleep: deps.sleep,
7167
7820
  shutdown: shutdownOf(deps),
7168
7821
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
7169
- onTick: (run, elapsedMs) => {
7170
- const elapsed = Math.round(elapsedMs / 1000);
7171
- const s = run.stepSummary ?? { total: 0, completed: 0, passedCount: 0, failedCount: 0 };
7172
- ticker.update(`Run ${run.runId} (${entry.testId}) — ${run.status} (${s.completed}/${s.total} steps elapsed=${elapsed}s)`);
7173
- },
7822
+ onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
7174
7823
  resolveAlternate,
7175
7824
  });
7176
7825
  return {
7177
7826
  testId: entry.testId,
7827
+ testTitle: finalRun.testTitle ?? null,
7178
7828
  runId: entry.runId,
7179
7829
  projectId: finalRun.projectId,
7180
7830
  status: finalRun.status,
7831
+ ...(typeof finalRun.dashboardUrl === 'string'
7832
+ ? { dashboardUrl: finalRun.dashboardUrl }
7833
+ : {}),
7834
+ ...(typeof finalRun.executionUrl === 'string'
7835
+ ? { executionUrl: finalRun.executionUrl }
7836
+ : {}),
7181
7837
  };
7182
7838
  }
7183
7839
  catch (err) {
@@ -7617,9 +8273,10 @@ export function createTestCommand(deps = {}) {
7617
8273
  .option('--name <name>', 'human-readable test name (becomes `title` in storage)')
7618
8274
  .option('--description <text>', 'optional human description (≤ 2000 chars)')
7619
8275
  .option('--priority <prio>', 'optional priority — one of: p0, p1, p2, p3')
8276
+ .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
7620
8277
  .option('--code-file <path>', 'file containing the test code (≤ 350 KB)')
7621
8278
  .option('--plan-from <path>', 'JSON file with the full FE test definition — projectId, type, name, planSteps[] all live in the file ' +
7622
- '(≤ 256 KB; mutually exclusive with --code-file). In this mode --project/--type/--name/--description/--priority are ignored.')
8279
+ '(≤ 256 KB; mutually exclusive with --code-file). In this mode --project/--type/--name/--description/--priority/--step-timeout are ignored.')
7623
8280
  .option('--plan-template', 'print a minimal valid plan-file skeleton to stdout and exit (pure-local: no network, no credentials, ' +
7624
8281
  'ignores every other flag). Pipe to a file and edit: `--plan-template > plan.json`.', false)
7625
8282
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
@@ -7684,6 +8341,8 @@ export function createTestCommand(deps = {}) {
7684
8341
  ignored.push('--description');
7685
8342
  if (cmdOpts.priority !== undefined)
7686
8343
  ignored.push('--priority');
8344
+ if (cmdOpts.stepTimeout !== undefined)
8345
+ ignored.push('--step-timeout');
7687
8346
  await runCreateFromPlan({
7688
8347
  ...resolveCommonOptions(command),
7689
8348
  planFrom: cmdOpts.planFrom,
@@ -7706,6 +8365,7 @@ export function createTestCommand(deps = {}) {
7706
8365
  name: cmdOpts.name,
7707
8366
  description: cmdOpts.description,
7708
8367
  priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
8368
+ stepTimeoutMs: parseStepTimeoutFlag(cmdOpts.stepTimeout, 'step-timeout'),
7709
8369
  codeFile: cmdOpts.codeFile,
7710
8370
  idempotencyKey: cmdOpts.idempotencyKey,
7711
8371
  // M3.3 chain flags:
@@ -7873,22 +8533,29 @@ export function createTestCommand(deps = {}) {
7873
8533
  });
7874
8534
  test
7875
8535
  .command('update <test-id>')
7876
- .description('Update test metadata — name, description, priority')
8536
+ .description('Update test metadata — name, description, priority, step timeout')
7877
8537
  .option('--name <name>', 'new human-readable test name')
7878
8538
  .option('--description <text>', 'new human description (≤ 2000 chars)')
7879
8539
  .option('--priority <prio>', 'new priority — one of: p0, p1, p2, p3')
8540
+ .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
8541
+ .option('--clear-step-timeout', 'clear the per-test step timeout and restore execution engine defaults', false)
7880
8542
  .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering.', (val, prev) => [...(prev ?? []), val], [])
7881
8543
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Declares an upstream producer dependency.', (val, prev) => [...(prev ?? []), val], [])
7882
8544
  .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
7883
8545
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
7884
8546
  .addHelpText('after', GLOBAL_OPTS_HINT)
7885
8547
  .action(async (testId, cmdOpts, command) => {
8548
+ if (cmdOpts.stepTimeout !== undefined && cmdOpts.clearStepTimeout === true) {
8549
+ throw localValidationError('step-timeout', '--step-timeout and --clear-step-timeout are mutually exclusive');
8550
+ }
7886
8551
  await runUpdate({
7887
8552
  ...resolveCommonOptions(command),
7888
8553
  testId,
7889
8554
  name: cmdOpts.name,
7890
8555
  description: cmdOpts.description,
7891
8556
  priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
8557
+ stepTimeoutMs: parseStepTimeoutFlag(cmdOpts.stepTimeout, 'step-timeout'),
8558
+ clearStepTimeout: cmdOpts.clearStepTimeout === true,
7892
8559
  produces: cmdOpts.produces,
7893
8560
  needs: cmdOpts.needs,
7894
8561
  category: cmdOpts.category,
@@ -7967,6 +8634,20 @@ export function createTestCommand(deps = {}) {
7967
8634
  "`run` command has no way to know a test's type before triggering it, so the preflight " +
7968
8635
  'still runs and can still refuse; use --skip-preflight if that surprises you.')
7969
8636
  .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
8637
+ .option('--local <port>', 'run against an app on THIS machine, reached through a TestSprite tunnel. The test runner ' +
8638
+ 'navigates to http://127.0.0.1:<port> and its traffic is proxied back to you for as long ' +
8639
+ 'as this command runs. Implies --wait (the tunnel closes when the command exits, so a ' +
8640
+ 'detached run could not finish) and cannot be combined with --target-url. Frontend tests ' +
8641
+ 'only. Before anything is minted or billed, the port is probed and a dead one is refused.')
8642
+ .option('--local-host <host>', `with --local, which loopback address to name in the run's target URL — one of ` +
8643
+ `${LOOPBACK_HOSTS.join(', ')} (default ${DEFAULT_LOCAL_HOST}). Use localhost if your app ` +
8644
+ `only answers on that name, or ::1 for an IPv6-only listener.`)
8645
+ .option('--tunnel-client <id>', 'with --local, attach to a tunnel already running under `testsprite tunnel start` instead ' +
8646
+ 'of opening a new one. The id is the non-secret handle that command prints; the tunnel ' +
8647
+ 'stays owned by that process and is not closed when this run finishes.')
8648
+ .option('--no-cancel-on-interrupt', 'with --local, leave the run executing (and billing) when this command stops waiting. By ' +
8649
+ 'default a --local run is cancelled at that point, because its tunnel closes with this ' +
8650
+ 'process and the run could then only fail.')
7970
8651
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
7971
8652
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
7972
8653
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
@@ -7979,6 +8660,7 @@ export function createTestCommand(deps = {}) {
7979
8660
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
7980
8661
  .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')
7981
8662
  .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')
8663
+ .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')
7982
8664
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
7983
8665
  ' testsprite test run --all --project <id> run all project tests in wave order\n' +
7984
8666
  ' TESTSPRITE_PROJECT_ID=<id> testsprite test run --all use env default project\n' +
@@ -8006,12 +8688,45 @@ export function createTestCommand(deps = {}) {
8006
8688
  if (cmdOpts.filter !== undefined && cmdOpts.filter !== '' && !isAll) {
8007
8689
  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.');
8008
8690
  }
8691
+ // --local resolution. Every one of these refuses BEFORE any network
8692
+ // call, which is the contract `--local` is sold on: a mistake in the
8693
+ // invocation must never reach a run row, a credit spend, or a minted
8694
+ // tunnel credential.
8695
+ const localPort = cmdOpts.local !== undefined ? parseLocalPort(cmdOpts.local) : undefined;
8696
+ const usingLocal = localPort !== undefined;
8697
+ const effectiveWait = usingLocal || cmdOpts.wait === true;
8698
+ if (usingLocal && isAll) {
8699
+ throw localValidationError('local', '--local runs one test through one tunnel; --all fans out across a project. Run the ' +
8700
+ 'tests you want against your machine one at a time, or drop --local');
8701
+ }
8702
+ if (usingLocal && cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
8703
+ throw localValidationError('local', '--local and --target-url are mutually exclusive: --local runs against your own ' +
8704
+ 'machine through a tunnel, --target-url runs against an address the test runner can ' +
8705
+ 'already reach. Pass one');
8706
+ }
8707
+ // The three flags below are inert without --local. Silently ignoring
8708
+ // them would leave the caller believing something is in effect that is
8709
+ // not — the same rule --filter and the JUnit flags already follow.
8710
+ if (!usingLocal && cmdOpts.localHost !== undefined) {
8711
+ throw localValidationError('local-host', '--local-host only applies with --local (it names the loopback address the tunnel run ' +
8712
+ 'targets). Add --local <port>, or remove --local-host');
8713
+ }
8714
+ if (!usingLocal && cmdOpts.tunnelClient !== undefined) {
8715
+ throw localValidationError('tunnel-client', '--tunnel-client only applies with --local (it attaches the run to an already-running ' +
8716
+ 'tunnel). Add --local <port>, or remove --tunnel-client');
8717
+ }
8718
+ if (!usingLocal && cmdOpts.cancelOnInterrupt === false) {
8719
+ throw localValidationError('cancel-on-interrupt', '--no-cancel-on-interrupt only applies with --local. An ordinary run is never ' +
8720
+ 'cancelled when this command stops waiting — Ctrl-C detaches, and `testsprite test ' +
8721
+ 'cancel <run-id>` is the way to stop one');
8722
+ }
8723
+ const localHost = usingLocal ? normalizeLocalHost(cmdOpts.localHost) : undefined;
8009
8724
  const report = parseJUnitReportFormat(cmdOpts.report);
8010
8725
  assertJUnitReportOptions({
8011
8726
  report,
8012
8727
  reportFile: cmdOpts.reportFile,
8013
8728
  reportSuiteName: cmdOpts.reportSuiteName,
8014
- wait: cmdOpts.wait === true,
8729
+ wait: effectiveWait,
8015
8730
  batchPath: isAll,
8016
8731
  });
8017
8732
  // --gh-output / --summary-file reduce a --wait run's terminal result into
@@ -8019,10 +8734,10 @@ export function createTestCommand(deps = {}) {
8019
8734
  // enqueueing, before any terminal result exists) but apply to BOTH a single
8020
8735
  // <test-id> run and the --all batch. Without --wait they would silently
8021
8736
  // no-op — reject loudly (same rule as --filter and the JUnit report flags).
8022
- if (cmdOpts.ghOutput === true && cmdOpts.wait !== true) {
8737
+ if (cmdOpts.ghOutput === true && !effectiveWait) {
8023
8738
  throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
8024
8739
  }
8025
- if (cmdOpts.summaryFile !== undefined && cmdOpts.wait !== true) {
8740
+ if (cmdOpts.summaryFile !== undefined && !effectiveWait) {
8026
8741
  throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
8027
8742
  }
8028
8743
  if (isAll) {
@@ -8042,7 +8757,7 @@ export function createTestCommand(deps = {}) {
8042
8757
  ...resolveCommonOptions(command),
8043
8758
  projectId,
8044
8759
  nameFilter: cmdOpts.filter,
8045
- wait: cmdOpts.wait === true,
8760
+ wait: effectiveWait,
8046
8761
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
8047
8762
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
8048
8763
  DEFAULT_BATCH_RUN_CONCURRENCY,
@@ -8052,16 +8767,40 @@ export function createTestCommand(deps = {}) {
8052
8767
  reportSuiteName: cmdOpts.reportSuiteName,
8053
8768
  ghOutput: cmdOpts.ghOutput === true,
8054
8769
  summaryFile: cmdOpts.summaryFile,
8770
+ allowEmpty: cmdOpts.allowEmpty === true,
8055
8771
  }, deps);
8056
8772
  return;
8057
8773
  }
8774
+ // `--local` implies `--wait`: for a self-minted tunnel the tunnel's
8775
+ // lifetime is this process's lifetime, so returning early would doom the
8776
+ // run it just started. Announced rather than assumed — a caller who did
8777
+ // not type --wait should learn why the command is now blocking.
8778
+ //
8779
+ // The reason splits on how the tunnel was obtained. An adopted one
8780
+ // (--tunnel-client) outlives this process, so "the tunnel closes when
8781
+ // this command exits" is simply false there, and it is the sentence a
8782
+ // reader would act on: told that, someone deciding whether to background
8783
+ // this command concludes the wrong thing about their own tunnel.
8784
+ const commonOpts = resolveCommonOptions(command);
8785
+ if (usingLocal && cmdOpts.wait !== true && commonOpts.output !== 'json') {
8786
+ const adopted = cmdOpts.tunnelClient !== undefined;
8787
+ (deps.stderr ?? ((line) => process.stderr.write(`${line}\n`)))(adopted
8788
+ ? '[advisory] --local implies --wait: the run is followed to a verdict rather than ' +
8789
+ 'detached. The tunnel you attached to stays open — this command does not close it.'
8790
+ : '[advisory] --local implies --wait: the tunnel closes when this command exits, so ' +
8791
+ 'the run is followed to a verdict rather than detached.');
8792
+ }
8058
8793
  // Single test-id path (unchanged M3.3 behavior).
8059
8794
  await runTestRun({
8060
- ...resolveCommonOptions(command),
8795
+ ...commonOpts,
8061
8796
  testId: testIdArg,
8062
8797
  targetUrl: cmdOpts.targetUrl,
8063
8798
  skipPreflight: cmdOpts.skipPreflight === true,
8064
- wait: cmdOpts.wait === true,
8799
+ ...(localPort !== undefined ? { localPort } : {}),
8800
+ ...(localHost !== undefined ? { localHost } : {}),
8801
+ ...(cmdOpts.tunnelClient !== undefined ? { tunnelClientId: cmdOpts.tunnelClient } : {}),
8802
+ cancelOnInterrupt: cmdOpts.cancelOnInterrupt !== false,
8803
+ wait: effectiveWait,
8065
8804
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
8066
8805
  // B2(c): tell runTestRun whether --timeout was explicitly provided.
8067
8806
  timeoutIsDefault: cmdOpts.timeout === undefined,
@@ -8524,15 +9263,118 @@ export function resolveWaitRequestTimeoutMs(opts) {
8524
9263
  const cover = Math.min(opts.timeoutSeconds * 1000 + WAIT_REQUEST_TIMEOUT_CUSHION_MS, REQUEST_TIMEOUT_MAX_MS);
8525
9264
  return Math.max(base, cover);
8526
9265
  }
8527
- function makeClient(opts, deps) {
9266
+ function makeClient(opts, deps, shutdownSignal = shutdownOf(deps).signal) {
8528
9267
  return makeHttpClient(opts, {
8529
9268
  env: deps.env,
8530
9269
  credentialsPath: deps.credentialsPath,
8531
9270
  fetchImpl: deps.fetchImpl,
8532
9271
  stderr: deps.stderr,
8533
- shutdownSignal: shutdownOf(deps).signal,
9272
+ shutdownSignal,
9273
+ });
9274
+ }
9275
+ /**
9276
+ * Run one request under a total deadline that is independent of Ctrl-C.
9277
+ *
9278
+ * Mint and trigger responses carry the only handles that let us undo the
9279
+ * server-side effects they may already have committed. A first signal is
9280
+ * therefore allowed to request shutdown, but cannot tear either response down
9281
+ * before we learn the clientId/runId needed for cleanup. The total deadline
9282
+ * still bounds all HTTP retries and their sleeps end to end.
9283
+ */
9284
+ async function withUninterruptibleRequest(opts, deps, timeoutMs, operation) {
9285
+ const deadline = new AbortController();
9286
+ const timer = setTimeout(() => {
9287
+ deadline.abort(new RequestTimeoutError(timeoutMs));
9288
+ }, timeoutMs);
9289
+ timer.unref?.();
9290
+ try {
9291
+ return await operation(makeClient({ ...opts, requestTimeoutMs: timeoutMs }, deps, deadline.signal));
9292
+ }
9293
+ finally {
9294
+ clearTimeout(timer);
9295
+ }
9296
+ }
9297
+ /** Make `start()` reject promptly when the armed lifecycle receives a signal. */
9298
+ function shutdownAwareTunnelClientFactory(createClient, signal) {
9299
+ return options => {
9300
+ const client = createClient(options);
9301
+ return {
9302
+ start: async () => {
9303
+ if (signal.aborted)
9304
+ throw signal.reason;
9305
+ await new Promise((resolve, reject) => {
9306
+ const onAbort = () => reject(signal.reason);
9307
+ signal.addEventListener('abort', onAbort, { once: true });
9308
+ client.start().then(() => {
9309
+ signal.removeEventListener('abort', onAbort);
9310
+ resolve();
9311
+ }, err => {
9312
+ signal.removeEventListener('abort', onAbort);
9313
+ reject(err);
9314
+ });
9315
+ });
9316
+ },
9317
+ stop: () => {
9318
+ const stopping = client.stop();
9319
+ if (!signal.aborted)
9320
+ return stopping;
9321
+ // `TunnelClient.stop()` synchronously flips its running flag before
9322
+ // its first await. Do not let a still-CONNECTING WebSocket delay the
9323
+ // binding DELETE after Ctrl-C; observe the eventual rejection only to
9324
+ // avoid an unhandled promise.
9325
+ void stopping.catch(() => { });
9326
+ return Promise.resolve();
9327
+ },
9328
+ };
9329
+ };
9330
+ }
9331
+ /**
9332
+ * A client for teardown work that must survive an interrupt.
9333
+ *
9334
+ * `makeClient` composes the process shutdown signal into every request, which
9335
+ * is right for the work a Ctrl-C is meant to abandon — and wrong for the two
9336
+ * calls that only exist BECAUSE of the Ctrl-C: deleting the tunnel binding and
9337
+ * cancelling the doomed run. Composed with an already-aborted signal, those
9338
+ * requests never leave the machine, and the user is left holding a live
9339
+ * credential and a burning run.
9340
+ *
9341
+ * The timeout is deliberately short and fixed rather than inherited: teardown
9342
+ * happens while the user is waiting for their prompt back, and a stalled
9343
+ * cleanup call must not out-live their patience.
9344
+ */
9345
+ function makeDetachedClient(opts, deps, operationSignal) {
9346
+ return makeHttpClient({ ...opts, requestTimeoutMs: TEARDOWN_OPERATION_TIMEOUT_MS }, {
9347
+ env: deps.env,
9348
+ credentialsPath: deps.credentialsPath,
9349
+ fetchImpl: deps.fetchImpl,
9350
+ stderr: deps.stderr,
9351
+ // Detached from the process signal, but still bounded end to end. The
9352
+ // HTTP retry sleeper listens to shutdownSignal, so this operation signal
9353
+ // cuts both in-flight attempts and the backoff between them.
9354
+ shutdownSignal: operationSignal,
8534
9355
  });
8535
9356
  }
9357
+ async function withTeardownDeadline(opts, deps, operation) {
9358
+ const deadline = new AbortController();
9359
+ const timer = setTimeout(() => {
9360
+ deadline.abort(new RequestTimeoutError(TEARDOWN_OPERATION_TIMEOUT_MS));
9361
+ }, TEARDOWN_OPERATION_TIMEOUT_MS);
9362
+ timer.unref?.();
9363
+ const shutdown = deps.shutdown ?? globalShutdown;
9364
+ try {
9365
+ return await shutdown.runCriticalOperation(() => operation(makeDetachedClient(opts, deps, deadline.signal)));
9366
+ }
9367
+ finally {
9368
+ clearTimeout(timer);
9369
+ }
9370
+ }
9371
+ async function deleteTunnelForCleanup(opts, deps, clientId) {
9372
+ await withTeardownDeadline(opts, deps, client => client.delete(`/tunnel/${encodeURIComponent(clientId)}`, {
9373
+ allowNoContent: true,
9374
+ }));
9375
+ }
9376
+ /** See {@link makeDetachedClient}. */
9377
+ const TEARDOWN_OPERATION_TIMEOUT_MS = 10_000;
8536
9378
  function makeOutput(mode, deps) {
8537
9379
  return new Output(mode, {
8538
9380
  stdout: deps.stdout,
@@ -8804,8 +9646,23 @@ function renderTestText(t) {
8804
9646
  // M3.4: surface plan-step count when the facade ships it (FE tests).
8805
9647
  // Lets an operator read the current count — e.g. to recover after a
8806
9648
  // `test plan put --expected-step-count` 412 — without a JSON round-trip.
8807
- if (typeof t.planStepCount === 'number') {
8808
- lines.push(`planSteps: ${t.planStepCount}`);
9649
+ const planSteps = Array.isArray(t.planSteps) ? t.planSteps : undefined;
9650
+ const planStepCount = typeof t.planStepCount === 'number' ? t.planStepCount : planSteps?.length;
9651
+ if (typeof planStepCount === 'number') {
9652
+ lines.push(`planSteps: ${planStepCount}`);
9653
+ }
9654
+ if (planSteps) {
9655
+ planSteps.forEach((step, index) => {
9656
+ if (typeof step !== 'object' || step === null)
9657
+ return;
9658
+ const fields = step;
9659
+ const type = typeof fields.type === 'string' ? fields.type : 'step';
9660
+ const description = typeof fields.description === 'string' ? fields.description : '(no description)';
9661
+ lines.push(` ${index + 1}. [${type}] ${description}`);
9662
+ });
9663
+ }
9664
+ if (typeof t.stepTimeoutMs === 'number') {
9665
+ lines.push(`stepTimeout: ${t.stepTimeoutMs} ms (applies to every step)`);
8809
9666
  }
8810
9667
  // Surface backend dependency declarations when present.
8811
9668
  if (Array.isArray(t.produces) && t.produces.length > 0) {
@@ -9214,8 +10071,645 @@ function createTestCodeCommand(deps) {
9214
10071
  });
9215
10072
  return code;
9216
10073
  }
10074
+ // ---------------------------------------------------------------------------
10075
+ // `test plan generate` / `test plan accept` — DEV-384 V3-B
10076
+ // ---------------------------------------------------------------------------
10077
+ /** Default `--timeout` for `test plan generate` (design-doc §3.1): a fresh
10078
+ * frontend project runs browser exploration, which takes minutes — the runs
10079
+ * default (600s) would routinely cut it short. */
10080
+ const PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS = 1800;
10081
+ /** Cap on the F1 pre-trigger baseline read — best-effort display data must
10082
+ * never hold up the real work (review follow-up). */
10083
+ const PLAN_BASELINE_READ_TIMEOUT_MS = 10_000;
10084
+ /** `--project` is a flag (not a positional) on both plan-generation leaves —
10085
+ * route through the house helpers so `TESTSPRITE_PROJECT_ID` works here the
10086
+ * same as on every other command (DEV-384 review F5). */
10087
+ function requirePlanProjectId(projectId, deps) {
10088
+ const resolved = resolveProjectId(projectId, deps);
10089
+ requireProjectId(resolved);
10090
+ return resolved;
10091
+ }
10092
+ /**
10093
+ * Normalize `--only` tokens: split comma-separated entries, trim, drop
10094
+ * empties, dedupe (order-preserving). Returns `undefined` when the flag was
10095
+ * absent; throws when the flag was supplied but named no usable id.
10096
+ */
10097
+ function normalizePlanOnlyIds(raw) {
10098
+ if (raw === undefined)
10099
+ return undefined;
10100
+ const ids = [];
10101
+ const seen = new Set();
10102
+ for (const token of raw) {
10103
+ for (const piece of token.split(',')) {
10104
+ const id = piece.trim();
10105
+ if (id.length === 0 || seen.has(id))
10106
+ continue;
10107
+ seen.add(id);
10108
+ ids.push(id);
10109
+ }
10110
+ }
10111
+ if (ids.length === 0) {
10112
+ throw localValidationError('only', 'requires at least one proposal id');
10113
+ }
10114
+ return ids;
10115
+ }
10116
+ /**
10117
+ * Fallback `nextAction` texts for the plan-generation error reasons
10118
+ * (design-doc §7/§8: every precondition failure names its exact fix). The
10119
+ * backend facade already ships these texts; this map is the CLI-side
10120
+ * FALLBACK applied only when the envelope's `nextAction` is empty (same
10121
+ * convention as the FEATURE_GATED `/pricing` fallback) — backend-supplied
10122
+ * text always passes through unchanged.
10123
+ */
10124
+ function planFixNextAction(reason, projectId, categoryCount) {
10125
+ switch (reason) {
10126
+ case 'v3_required':
10127
+ return ('Plan generation runs on the V3 platform and your account has not been migrated yet ' +
10128
+ '(it will be soon). Until then, generate test plans in the Portal.');
10129
+ case 'environment_url_missing':
10130
+ return `Set the app URL first: testsprite project update ${projectId} --url https://staging.your-app.com`;
10131
+ case 'no_processed_inputs':
10132
+ return (`Upload your API documentation: testsprite project docs upload <file> --project ${projectId} --role api-doc ` +
10133
+ '(or add sources in the Portal — upload a document, give the assistant a link, or paste it). ' +
10134
+ 'If you just added a source, it may still be processing — retry shortly.');
10135
+ case 'no_plannable_categories':
10136
+ // Mirrors the server's own 0 / 1 / n split: zero categories is
10137
+ // reachable on a frontend project too, where "upload a fuller API
10138
+ // document" cannot apply.
10139
+ if (categoryCount === 0) {
10140
+ return ('The strategy is ready but has no categories, so there is nothing to plan test cases ' +
10141
+ 'against. Retrying will not change this. Regenerate the strategy in the Portal, then run ' +
10142
+ 'this again.');
10143
+ }
10144
+ return ((categoryCount === 1
10145
+ ? 'The strategy is ready, but its only category has no endpoint to attach a test to, so '
10146
+ : 'The strategy is ready, but none of its categories has an endpoint to attach a test to, so ') +
10147
+ 'there is nothing to plan against. Retrying will not change this. Review the strategy in the ' +
10148
+ 'Portal; if your API documentation does not describe the endpoints, upload a fuller document ' +
10149
+ `(testsprite project docs upload <file> --project ${projectId} --role api-doc) and regenerate ` +
10150
+ 'the strategy there, then run this again.');
10151
+ case 'nothing_staged':
10152
+ return `Generate proposals first: testsprite test plan generate --project ${projectId}`;
10153
+ default:
10154
+ return undefined;
10155
+ }
10156
+ }
10157
+ /** Apply {@link planFixNextAction} to an ApiError whose envelope lacks a
10158
+ * `nextAction`; every other error passes through untouched. */
10159
+ function withPlanFixNextAction(err, projectId) {
10160
+ if (!(err instanceof ApiError))
10161
+ return err;
10162
+ if (err.nextAction !== '')
10163
+ return err;
10164
+ const reason = err.getDetail('reason', (v) => typeof v === 'string');
10165
+ if (reason === undefined)
10166
+ return err;
10167
+ const categoryCount = err.getDetail('categoryCount', (v) => typeof v === 'number');
10168
+ const nextAction = planFixNextAction(reason, projectId, categoryCount);
10169
+ if (nextAction === undefined)
10170
+ return err;
10171
+ return new ApiError({
10172
+ code: err.code,
10173
+ message: err.message,
10174
+ nextAction,
10175
+ requestId: err.requestId,
10176
+ details: err.details,
10177
+ }, err.httpStatus, err.retryAfterMs);
10178
+ }
10179
+ /** Local envelope for "accept with nothing staged" — same shape/reason the
10180
+ * server emits (412 `nothing_staged`, exit 6) so scripts can't tell whether
10181
+ * the CLI or the facade caught it first. */
10182
+ function planNothingStagedError(projectId) {
10183
+ return ApiError.fromEnvelope({
10184
+ error: {
10185
+ code: 'PRECONDITION_FAILED',
10186
+ message: 'No proposals are staged for this project — there is nothing to accept.',
10187
+ nextAction: planFixNextAction('nothing_staged', projectId),
10188
+ requestId: 'local',
10189
+ details: { projectId, reason: 'nothing_staged' },
10190
+ },
10191
+ });
10192
+ }
10193
+ /** `52s` under a minute, `4m10s` above (design §3.1 ticker examples). */
10194
+ function formatPlanElapsed(elapsedMs) {
10195
+ const totalSeconds = Math.max(0, Math.round(elapsedMs / 1000));
10196
+ if (totalSeconds < 60)
10197
+ return `${totalSeconds}s`;
10198
+ const minutes = Math.floor(totalSeconds / 60);
10199
+ const seconds = totalSeconds % 60;
10200
+ return `${minutes}m${String(seconds).padStart(2, '0')}s`;
10201
+ }
10202
+ /** One in-place ticker line per generation status (design §3.2). */
10203
+ function planTickerLine(plans, elapsedMs) {
10204
+ const elapsed = formatPlanElapsed(elapsedMs);
10205
+ const generation = plans.generation;
10206
+ switch (generation.status) {
10207
+ case 'exploring': {
10208
+ const progress = generation.progress;
10209
+ return progress !== undefined
10210
+ ? `exploring app… (resources ${progress.resourcesReady}/${progress.resourcesTotal}, ${elapsed})`
10211
+ : `exploring app… (${elapsed})`;
10212
+ }
10213
+ case 'strategizing':
10214
+ return `generating strategy… (${elapsed})`;
10215
+ case 'proposing':
10216
+ return `proposing tests… (${elapsed})`;
10217
+ case 'failed':
10218
+ return `generation failed (${elapsed})`;
10219
+ case 'idle':
10220
+ return plans.proposals.length > 0
10221
+ ? `proposals staged (${elapsed})`
10222
+ : `starting next stage… (${elapsed})`;
10223
+ }
10224
+ }
10225
+ /** Sum of the best-effort `credits.charged` amounts (0 when absent). */
10226
+ function planCreditsUsed(plans) {
10227
+ return (plans.credits?.charged ?? []).reduce((sum, c) => sum + c.amount, 0);
10228
+ }
10229
+ /**
10230
+ * THIS invocation's spend: the settled read's per-action charged totals minus
10231
+ * the pre-trigger baseline's (DEV-935 / review F1 — the wire block is a
10232
+ * LIFETIME project total, so printing its sum as "credits used" reported
10233
+ * all-time spend on re-runs that charged nothing). `null` = unknown (no
10234
+ * baseline snapshot, or either read lacks the best-effort block) — the
10235
+ * caller omits the figure rather than printing a lifetime number.
10236
+ */
10237
+ function planCreditsDelta(baseline, settled) {
10238
+ if (baseline?.credits?.charged === undefined || settled.credits?.charged === undefined) {
10239
+ return null;
10240
+ }
10241
+ // DEV-935: a facade-side billing failure degrades the block to
10242
+ // `{charged: [], balance: null}` — `charged` is DEFINED there, so without
10243
+ // this guard a degraded read makes the other read's lifetime totals print
10244
+ // as this run's spend (the F1 misreport, back through the degrade window).
10245
+ // A healthy block always carries a numeric balance.
10246
+ if (baseline.credits.balance === null || settled.credits.balance === null) {
10247
+ return null;
10248
+ }
10249
+ const before = new Map(baseline.credits.charged.map(c => [c.action, c.amount]));
10250
+ let delta = 0;
10251
+ for (const c of settled.credits.charged) {
10252
+ delta += Math.max(0, c.amount - (before.get(c.action) ?? 0));
10253
+ }
10254
+ return delta;
10255
+ }
10256
+ /** ` (credits used: N, balance: M)` — `creditsUsed` is this invocation's
10257
+ * delta (omitted when 0 or unknown); balance is the settled read's current
10258
+ * figure. Empty string when the facade couldn't fill either. */
10259
+ function planCreditsSuffix(plans, creditsUsed) {
10260
+ const parts = [];
10261
+ if (creditsUsed !== null && creditsUsed > 0)
10262
+ parts.push(`credits used: ${creditsUsed}`);
10263
+ const balance = plans.credits?.balance;
10264
+ if (balance !== undefined && balance !== null)
10265
+ parts.push(`balance: ${balance}`);
10266
+ return parts.length > 0 ? ` (${parts.join(', ')})` : '';
10267
+ }
10268
+ /** Auto-width column helper for the proposals table. */
10269
+ function planTableColumn(header, render) {
10270
+ return {
10271
+ header,
10272
+ width: rows => Math.max(header.length, ...rows.map(r => render(r.proposal, r.index).length), 1),
10273
+ render: r => render(r.proposal, r.index),
10274
+ };
10275
+ }
10276
+ /** The staged-proposals table. Every row prints its stable `proposalId` —
10277
+ * that id is what `accept --only` consumes (design §3.3). */
10278
+ function renderPlanProposalsTable(proposals) {
10279
+ const rows = proposals.map((proposal, index) => ({ proposal, index }));
10280
+ const columns = [
10281
+ planTableColumn('#', (_p, i) => String(i + 1)),
10282
+ planTableColumn('ID', p => p.proposalId),
10283
+ planTableColumn('TITLE', p => (p.title.length > 48 ? `${p.title.slice(0, 47)}…` : p.title)),
10284
+ planTableColumn('FEATURE', p => `${p.category}/${p.feature}`),
10285
+ planTableColumn('PRIORITY', p => p.priority),
10286
+ planTableColumn('TYPE', p => p.type),
10287
+ ];
10288
+ return renderTextTable(rows, columns);
10289
+ }
10290
+ /** Text card for a settled successful generate (or `--dry-run`). */
10291
+ /** Exported for the renderer-level spec: the zero-proposals branch is not
10292
+ * reachable through `runGenerationLadder` today (after the proposals rung it
10293
+ * polls until staged/failed/timeout), so it is pinned directly. */
10294
+ export function renderPlanGenerateResultText(plans, projectId, creditsUsed, skippedCategories = null) {
10295
+ const count = plans.proposals.length;
10296
+ if (count === 0) {
10297
+ return [
10298
+ `0 test-case proposals staged${planCreditsSuffix(plans, creditsUsed)}`,
10299
+ // The skip count matters MOST here: a batch already narrowed to the
10300
+ // plannable categories that still settled at zero points at the
10301
+ // strategy, not at a re-run (which would bill again for the same result).
10302
+ ...renderSkippedCategoriesLine(skippedCategories, { staged: false }),
10303
+ `hint: nothing is staged for review — run: testsprite test plan generate --project ${projectId}`,
10304
+ ].join('\n');
10305
+ }
10306
+ const noun = count === 1 ? 'proposal' : 'proposals';
10307
+ return [
10308
+ `${count} test-case ${noun} staged for review${planCreditsSuffix(plans, creditsUsed)}`,
10309
+ ...renderSkippedCategoriesLine(skippedCategories, { staged: true }),
10310
+ '',
10311
+ renderPlanProposalsTable(plans.proposals),
10312
+ '',
10313
+ 'next',
10314
+ ` review the list above, then: testsprite test plan accept --project ${projectId}`,
10315
+ ` accept a subset with: testsprite test plan accept --project ${projectId} --only <id ...>`,
10316
+ ' (or review visually in the Portal before accepting)',
10317
+ ].join('\n');
10318
+ }
10319
+ /** DEV-1008 — one line when the proposals stage left strategy categories out
10320
+ * because they have no endpoint to attach a test to. The stage is charged
10321
+ * flat, so without this the caller cannot tell a partial plan from a full
10322
+ * one. Empty when nothing was skipped (the common case). */
10323
+ function renderSkippedCategoriesLine(skippedCategories, opts) {
10324
+ if (skippedCategories === null || skippedCategories <= 0)
10325
+ return [];
10326
+ const noun = skippedCategories === 1 ? 'category' : 'categories';
10327
+ const head = `note: ${skippedCategories} strategy ${noun} skipped — no endpoint to attach a test to ` +
10328
+ '(cross-cutting themes such as authorization or pagination)';
10329
+ return [
10330
+ opts.staged
10331
+ ? `${head}; the proposals above cover the rest.`
10332
+ : `${head}; the remaining categories produced nothing. Review the strategy in the Portal ` +
10333
+ 'before re-running — a re-run is charged again and will give the same result.',
10334
+ ];
10335
+ }
10336
+ /** Text card for a server-side stage failure (exit 1 follows via the thrown
10337
+ * INTERNAL envelope; earlier completed stages stay done — a re-run resumes). */
10338
+ function renderPlanGenerateFailedText(plans, projectId) {
10339
+ const generation = plans.generation;
10340
+ const lines = [`generation failed${generation.errorCode ? ` (${generation.errorCode})` : ''}`];
10341
+ if (generation.errorMessage)
10342
+ lines.push(` ${generation.errorMessage}`);
10343
+ lines.push(` completed stages stay done — retry with: testsprite test plan generate --project ${projectId}`);
10344
+ return lines.join('\n');
10345
+ }
10346
+ function makePlanGeneratePartial(projectId, lastSeen) {
10347
+ return {
10348
+ projectId,
10349
+ status: 'running',
10350
+ generationStatus: lastSeen?.generation.status ?? null,
10351
+ proposalsStaged: lastSeen?.proposals.length ?? 0,
10352
+ };
10353
+ }
10354
+ function renderPlanGeneratePartialText(partial, reason) {
10355
+ const lines = [`projectId ${partial.projectId}`, `status running (${reason})`];
10356
+ if (partial.generationStatus !== null) {
10357
+ lines.push(`stage ${partial.generationStatus}`);
10358
+ }
10359
+ lines.push(`hint Re-attach with: testsprite test plan generate --project ${partial.projectId}`);
10360
+ return lines.join('\n');
10361
+ }
10362
+ /**
10363
+ * `test plan generate --project <id>` — DEV-384 V3-B.
10364
+ *
10365
+ * Drives the server's generation ladder (exploration → strategy →
10366
+ * proposals) through `runGenerationLadder` and renders the staged
10367
+ * proposals. Exit 0 on staged proposals, 1 on a server-side stage failure,
10368
+ * 7 on timeout (typed `UNSUPPORTED` envelope — the raw ladder timeout is
10369
+ * not a CLI error), 130/143 on Ctrl-C detach (honest: work and charges
10370
+ * continue server-side), plus the usual catalog exits for trigger errors
10371
+ * (412 → 6 with the exact fix command, 402 → 12, 404 → 4, 429 → 11).
10372
+ */
10373
+ export async function runPlanGenerate(opts, deps = {}) {
10374
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
10375
+ const out = makeOutput(opts.output, deps);
10376
+ const projectId = requirePlanProjectId(opts.projectId, deps);
10377
+ assertIdempotencyKey(opts.idempotencyKey);
10378
+ if (opts.dryRun) {
10379
+ // Zero network, zero charges: resolve both canned samples directly
10380
+ // (no fetch — even the canned dry-run fetch is bypassed, matching the
10381
+ // `test run --dry-run` convention) and render the settled success shape.
10382
+ const client = makeClient(opts, deps);
10383
+ const plans = findSampleOrThrow('GET', `/api/cli/v1/projects/${encodeURIComponent(projectId)}/plans`).body();
10384
+ // Dry-run has no baseline to diff; teach the credits line from the
10385
+ // canned block's sum (everything here is canned anyway).
10386
+ const canned = planCreditsUsed(plans);
10387
+ const payload = { projectId, creditsUsedThisInvocation: canned, ...plans };
10388
+ out.print(payload, () => renderPlanGenerateResultText(plans, projectId, canned));
10389
+ void client; // constructed so dry-run still validates --endpoint-url etc.
10390
+ return payload;
10391
+ }
10392
+ const idempotencyKey = opts.idempotencyKey ?? `cli-plan-gen-${randomUUID()}`;
10393
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
10394
+ stderrFn(`idempotency-key: ${idempotencyKey}`);
10395
+ }
10396
+ // D4: the ladder is a long wait bounded by --timeout — raise the
10397
+ // per-request window to cover it (same as every `--wait` path).
10398
+ const client = makeClient({
10399
+ ...opts,
10400
+ requestTimeoutMs: resolveWaitRequestTimeoutMs({
10401
+ wait: true,
10402
+ timeoutSeconds: opts.timeoutSeconds,
10403
+ requestTimeoutMs: opts.requestTimeoutMs,
10404
+ }),
10405
+ }, deps);
10406
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
10407
+ // Upgraded to the server-resolved V3 id by the first ACCEPTED trigger
10408
+ // response. KNOWN LIMITATION (DEV-384 review F8): when the very first
10409
+ // trigger 409-attaches, no trigger response ever arrives and neither the
10410
+ // 409 envelope nor the `GET /plans` read carries the resolved id, so the
10411
+ // output keeps the caller's input id (a V2 id still polls fine through the
10412
+ // migration bridge). Closing it needs the id on one of those wires.
10413
+ let resolvedProjectId = projectId;
10414
+ let lastSeen = null;
10415
+ try {
10416
+ // Pre-trigger baseline snapshot (review F1 / DEV-935): one plain GET
10417
+ // BEFORE any POST, so the settled read's lifetime `credits.charged`
10418
+ // block can be diffed into "what THIS invocation spent" (the first
10419
+ // stage's charge lands before the ladder's own first read, so first
10420
+ // in-ladder read vs last would undercount). Best-effort: a failure only
10421
+ // costs the credits line, never the command. Bounded by its own short
10422
+ // signal — without it the read inherits the D4-raised per-request window
10423
+ // (up to 600s under --wait semantics), all outside the --timeout budget.
10424
+ let baselinePlans = null;
10425
+ try {
10426
+ baselinePlans = await client.getPlans(projectId, {
10427
+ signal: AbortSignal.timeout(PLAN_BASELINE_READ_TIMEOUT_MS),
10428
+ });
10429
+ }
10430
+ catch (err) {
10431
+ if (err instanceof InterruptError)
10432
+ throw err;
10433
+ baselinePlans = null;
10434
+ }
10435
+ const result = await runGenerationLadder(client, projectId, {
10436
+ timeoutSeconds: opts.timeoutSeconds,
10437
+ idempotencyKey,
10438
+ sleep: deps.sleep,
10439
+ shutdown: shutdownOf(deps),
10440
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
10441
+ onTick: (plans, elapsedMs) => {
10442
+ lastSeen = plans;
10443
+ ticker.update(planTickerLine(plans, elapsedMs));
10444
+ },
10445
+ onAttach: () => {
10446
+ stderrFn('[advisory] a generation stage is already running for this project (possibly ' +
10447
+ 'started from the Portal) — attaching to it and polling.');
10448
+ },
10449
+ onTrigger: (response, acceptedPosts) => {
10450
+ resolvedProjectId = response.projectId;
10451
+ if (response.status === 'nothing_to_start') {
10452
+ if (acceptedPosts === 0) {
10453
+ // The FIRST trigger found the batch already staged: nothing ran,
10454
+ // nothing was charged. Regenerating on purpose is a Portal action
10455
+ // for now (design §11) — say so instead of silently no-opping.
10456
+ stderrFn('[advisory] proposals are already staged for this project — showing the ' +
10457
+ 'existing batch (nothing new was started or charged). To regenerate, ' +
10458
+ 'review and accept or discard the staged batch in the Portal first.');
10459
+ }
10460
+ return;
10461
+ }
10462
+ if (acceptedPosts === 1) {
10463
+ // First accepted trigger: state which stages will run (text mode
10464
+ // only — JSON pipelines get just the result object). Deliberately
10465
+ // does NOT quote a price up front: the surface matches `test run`,
10466
+ // which announces no cost either. Actual spend IS reported after
10467
+ // the fact, on the result line (`credits used: N, balance: M`) —
10468
+ // N is THIS invocation's settled−baseline delta (review F1), not
10469
+ // the wire block's lifetime total, and never a local price table.
10470
+ if (opts.output !== 'json') {
10471
+ const stages = [
10472
+ ...(response.stage !== null ? [response.stage] : []),
10473
+ ...response.stagesRemaining,
10474
+ ];
10475
+ const label = stages.join(' + ');
10476
+ stderrFn(stages.includes('exploration')
10477
+ ? `[hint] this project hasn't been explored yet — the full pipeline will run ` +
10478
+ `(${label}). Ctrl-C detaches safely; work continues server-side.`
10479
+ : `[hint] running the missing pipeline stages (${label}). ` +
10480
+ `Ctrl-C detaches safely; work continues server-side.`);
10481
+ }
10482
+ // …and, when browser exploration is about to run, warn about
10483
+ // missing test-account sign-in (design §3.1). The wire carries no
10484
+ // credential-presence signal, so the warning is hedged ("if …") —
10485
+ // it never blocks and never prompts; the CLI cannot know whether
10486
+ // the app actually requires login. Both output modes: stderr only.
10487
+ if (response.stage === 'exploration') {
10488
+ stderrFn('[warn] exploration signs in only with the test account stored on the ' +
10489
+ "project's default environment. If your app requires login and no test " +
10490
+ 'account is configured, the agents will explore only the public pages — ' +
10491
+ 'a shallow result from a stage that still runs and still bills. For ' +
10492
+ 'signed-in coverage, store a test account first: ' +
10493
+ `testsprite project update ${projectId} --username <user> --password-file <path>`);
10494
+ }
10495
+ }
10496
+ },
10497
+ });
10498
+ const plans = result.plans;
10499
+ if (plans.generation.status === 'failed') {
10500
+ ticker.finalize(planTickerLine(plans, 0).replace(/ \(0s\)$/, ''));
10501
+ const payload = { projectId: resolvedProjectId, ...plans };
10502
+ out.print(payload, () => renderPlanGenerateFailedText(plans, resolvedProjectId));
10503
+ throw ApiError.fromEnvelope({
10504
+ error: {
10505
+ code: 'INTERNAL', // exit 1 — "a pipeline stage failed server-side" (§8)
10506
+ message: `Plan generation failed: ${plans.generation.errorMessage ??
10507
+ plans.generation.errorCode ??
10508
+ 'a pipeline stage failed server-side'}`,
10509
+ nextAction: `Completed stages stay done — re-run \`testsprite test plan generate --project ${resolvedProjectId}\` ` +
10510
+ 'to retry the failed stage, or check the project in the Portal.',
10511
+ requestId: 'local',
10512
+ details: {
10513
+ projectId: resolvedProjectId,
10514
+ errorCode: plans.generation.errorCode,
10515
+ },
10516
+ },
10517
+ });
10518
+ }
10519
+ const count = plans.proposals.length;
10520
+ ticker.finalize(`${count} ${count === 1 ? 'proposal' : 'proposals'} staged`);
10521
+ // This invocation's spend (settled − baseline; null = unknown) — the
10522
+ // wire block alone is a lifetime total (DEV-935 / review F1).
10523
+ const creditsUsed = planCreditsDelta(baselinePlans, plans);
10524
+ const skippedCategories = result.skippedCategories;
10525
+ const payload = {
10526
+ projectId: resolvedProjectId,
10527
+ creditsUsedThisInvocation: creditsUsed,
10528
+ // DEV-1008: present only when the proposals stage skipped endpoint-less
10529
+ // categories, so every other JSON payload is byte-identical.
10530
+ ...(skippedCategories !== null ? { skippedCategories } : {}),
10531
+ ...plans,
10532
+ };
10533
+ out.print(payload, () => renderPlanGenerateResultText(plans, resolvedProjectId, creditsUsed, skippedCategories));
10534
+ return payload;
10535
+ }
10536
+ catch (err) {
10537
+ // Typed exit-7 conversion (the design's hard rule): the ladder's raw
10538
+ // timeout is NOT a CLI error and would otherwise exit 1. Mirror the
10539
+ // wait-site template — partial to stdout, typed envelope thrown.
10540
+ if (err instanceof PlanGenerationTimeoutError) {
10541
+ ticker.finalize(`timed out after ${opts.timeoutSeconds}s`);
10542
+ const partial = makePlanGeneratePartial(resolvedProjectId, err.lastPlans ?? lastSeen);
10543
+ out.print(partial, () => renderPlanGeneratePartialText(partial, `timed out after ${opts.timeoutSeconds}s`));
10544
+ throw ApiError.fromEnvelope({
10545
+ error: {
10546
+ code: 'UNSUPPORTED', // exit 7 per errors.md
10547
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for plan generation on project ${resolvedProjectId}.`,
10548
+ nextAction: `Generation continues server-side; re-running the same command re-attaches: ` +
10549
+ `testsprite test plan generate --project ${resolvedProjectId} ` +
10550
+ `(raise --timeout for exploration-heavy first runs).`,
10551
+ requestId: 'local',
10552
+ details: { projectId: resolvedProjectId, timeoutSeconds: opts.timeoutSeconds },
10553
+ },
10554
+ });
10555
+ }
10556
+ if (err instanceof RequestTimeoutError) {
10557
+ ticker.finalize('request timed out');
10558
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10559
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'request timed out'));
10560
+ stderrFn(`Plan generation is still in progress (request timed out). ` +
10561
+ `Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
10562
+ throw err;
10563
+ }
10564
+ if (err instanceof InterruptError) {
10565
+ ticker.finalize(`interrupted (${err.signal})`);
10566
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10567
+ out.print(partial, () => renderPlanGeneratePartialText(partial, `interrupted (${err.signal})`));
10568
+ stderrFn(`Interrupted (${err.signal}). Plan generation keeps running (and billing) on the ` +
10569
+ `server until the current stage finishes.\n` +
10570
+ ` Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
10571
+ throw err;
10572
+ }
10573
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
10574
+ // Same partial-envelope family as the timeout/interrupt branches
10575
+ // (DEV-384 review): a redirected stdout file must never be 0-byte.
10576
+ // The original ApiError is rethrown unchanged so exit stays 11.
10577
+ ticker.finalize('rate limited by the server');
10578
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10579
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'rate limited'));
10580
+ stderrFn(`Rate limited by the server (HTTP 429). Any started generation stage keeps running ` +
10581
+ `server-side.\n Re-attach with: testsprite test plan generate --project ${resolvedProjectId}`);
10582
+ throw err;
10583
+ }
10584
+ if (err instanceof ApiError &&
10585
+ err.code === 'INTERNAL' &&
10586
+ typeof err.details?.acceptedPosts === 'number') {
10587
+ // The ladder's cap-exhaustion "appears stuck" fuse (DEV-384 review F7)
10588
+ // joins the partial-envelope family too — it is a terminal outcome of a
10589
+ // long wait, exactly like the branches above, so redirected stdout must
10590
+ // carry the partial. Keyed on the fuse's own `acceptedPosts` detail so
10591
+ // the stage-failed INTERNAL (which already printed its card) never
10592
+ // double-prints. Rethrown unchanged.
10593
+ ticker.finalize('generation appears stuck');
10594
+ const partial = makePlanGeneratePartial(resolvedProjectId, lastSeen);
10595
+ out.print(partial, () => renderPlanGeneratePartialText(partial, 'appears stuck'));
10596
+ throw err;
10597
+ }
10598
+ throw withPlanFixNextAction(err, resolvedProjectId);
10599
+ }
10600
+ }
10601
+ function renderPlanAcceptText(result, includesBackend) {
10602
+ const proposalNoun = result.acceptedCount === 1 ? 'proposal' : 'proposals';
10603
+ const caseNoun = result.acceptedCount === 1 ? 'test case' : 'test cases';
10604
+ const discarded = result.discardedCount > 0
10605
+ ? ` (${result.discardedCount} remaining ${result.discardedCount === 1 ? 'proposal' : 'proposals'} discarded)`
10606
+ : '';
10607
+ const lines = [
10608
+ `${result.acceptedCount} ${proposalNoun} accepted — ${result.acceptedCount} ${caseNoun} created${discarded}`,
10609
+ ];
10610
+ if (includesBackend) {
10611
+ // Only when API cases were among the accepted set (design §3.3) — keyed
10612
+ // on the project/proposal type, which IS reliable at that granularity.
10613
+ lines.push('note: API test code is generated when the tests first run');
10614
+ }
10615
+ lines.push('', 'next', ` testsprite test list --project ${result.projectId}`, ` testsprite test run --all --project ${result.projectId} --wait`);
10616
+ return lines.join('\n');
10617
+ }
10618
+ /**
10619
+ * Select the proposals to accept. Enforces the §3.3 safety rules:
10620
+ * the returned list is EXPLICIT and NEVER EMPTY — `--only` matching zero
10621
+ * staged ids (or naming unknown ids) is a local validation error and the
10622
+ * request is never sent, because an empty `only` list is server-destructive
10623
+ * (it means "reject everything" and clears the staged batch).
10624
+ */
10625
+ function selectPlanProposals(staged, onlyIds) {
10626
+ if (onlyIds === undefined)
10627
+ return staged;
10628
+ const byId = new Map(staged.map(p => [p.proposalId, p]));
10629
+ const unknown = onlyIds.filter(id => !byId.has(id));
10630
+ if (unknown.length > 0) {
10631
+ throw localValidationError('only', `no staged proposal matches id(s): ${unknown.join(', ')}. ` +
10632
+ `Staged proposal ids: ${staged.map(p => p.proposalId).join(', ')}. ` +
10633
+ `The accept request was not sent`);
10634
+ }
10635
+ return onlyIds.map(id => byId.get(id));
10636
+ }
10637
+ /**
10638
+ * `test plan accept --project <id> [--only <ids...>]` — DEV-384 V3-B.
10639
+ *
10640
+ * Reads the staged batch, selects all of it (or the `--only` subset),
10641
+ * and POSTs an EXPLICIT id list. Free — the generation charge already
10642
+ * covered it. Exit 0 on success, 5 on a bad `--only` selection (request
10643
+ * never sent), 6 when nothing is staged (pointer at `test plan generate`).
10644
+ */
10645
+ export async function runPlanAccept(opts, deps = {}) {
10646
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
10647
+ const out = makeOutput(opts.output, deps);
10648
+ const projectId = requirePlanProjectId(opts.projectId, deps);
10649
+ assertIdempotencyKey(opts.idempotencyKey);
10650
+ const onlyIds = normalizePlanOnlyIds(opts.only);
10651
+ if (opts.dryRun) {
10652
+ // Zero network, zero charges: run the real selection logic against the
10653
+ // canned staged batch so `--only` behavior (subset counts, unknown-id
10654
+ // validation) is learnable offline, then echo the input-derived sample.
10655
+ const client = makeClient(opts, deps);
10656
+ const plans = findSampleOrThrow('GET', `/api/cli/v1/projects/${encodeURIComponent(projectId)}/plans`).body();
10657
+ const staged = plans.proposals;
10658
+ const selected = selectPlanProposals(staged, onlyIds);
10659
+ const ids = selected.map(p => p.proposalId);
10660
+ const response = findSampleOrThrow('POST', `/api/cli/v1/projects/${encodeURIComponent(projectId)}/plans/accept`, { only: ids }).body();
10661
+ const result = {
10662
+ projectId,
10663
+ acceptedCount: response.acceptedCount,
10664
+ caseKeys: response.caseKeys,
10665
+ discardedCount: staged.length - selected.length,
10666
+ };
10667
+ out.print(result, () => renderPlanAcceptText(result, selected.some(p => p.type === 'backend')));
10668
+ void client;
10669
+ return result;
10670
+ }
10671
+ const idempotencyKey = opts.idempotencyKey ?? `cli-plan-accept-${randomUUID()}`;
10672
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
10673
+ stderrFn(`idempotency-key: ${idempotencyKey}`);
10674
+ }
10675
+ const client = makeClient(opts, deps);
10676
+ // The staged batch is read first because the CLI ALWAYS sends an explicit
10677
+ // id list (full list when --only is absent) — never the omitted form and
10678
+ // never an empty one (§3.3). Nothing staged → the same 412 nothing_staged
10679
+ // answer the server would give, without a request.
10680
+ let plans;
10681
+ try {
10682
+ plans = await client.getPlans(projectId);
10683
+ }
10684
+ catch (err) {
10685
+ throw withPlanFixNextAction(err, projectId);
10686
+ }
10687
+ const staged = plans.proposals;
10688
+ if (staged.length === 0) {
10689
+ throw planNothingStagedError(projectId);
10690
+ }
10691
+ const selected = selectPlanProposals(staged, onlyIds);
10692
+ const ids = selected.map(p => p.proposalId);
10693
+ let response;
10694
+ try {
10695
+ response = await client.acceptPlans(projectId, ids, { idempotencyKey });
10696
+ }
10697
+ catch (err) {
10698
+ // Covers the read-then-accept race too (another client accepted or
10699
+ // discarded the batch in between → server 412 nothing_staged).
10700
+ throw withPlanFixNextAction(err, projectId);
10701
+ }
10702
+ const result = {
10703
+ projectId,
10704
+ acceptedCount: response.acceptedCount,
10705
+ caseKeys: response.caseKeys,
10706
+ discardedCount: staged.length - selected.length,
10707
+ };
10708
+ out.print(result, () => renderPlanAcceptText(result, selected.some(p => p.type === 'backend')));
10709
+ return result;
10710
+ }
9217
10711
  function createTestPlanCommand(deps) {
9218
- const plan = new Command('plan').description('Manage FE test plan-steps (FE-only)');
10712
+ const plan = new Command('plan').description('Generate + accept AI test plans (V3), and manage FE plan-steps');
9219
10713
  plan
9220
10714
  .command('put <test-id>')
9221
10715
  .description("Replace an FE test's planSteps[] (BE tests return 400 → use 'test code put')")
@@ -9241,6 +10735,62 @@ function createTestPlanCommand(deps) {
9241
10735
  dryRunSimulateError: simulateError === 'PRECONDITION_FAILED' ? 'PRECONDITION_FAILED' : undefined,
9242
10736
  }, deps);
9243
10737
  });
10738
+ plan
10739
+ .command('generate')
10740
+ .description('Generate AI test-case proposals for a project — runs only the missing pipeline ' +
10741
+ 'stages and stages the results server-side for review (nothing is written locally)')
10742
+ .option('--project <id>', 'project id (V3-native; V2 ids resolve through the migration bridge)')
10743
+ .option('--timeout <seconds>', `total wait budget in seconds (1-3600, default ${PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS}; ` +
10744
+ 'exploration takes minutes on a fresh frontend project)')
10745
+ .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
10746
+ .addHelpText('after', '\nBehavior:\n' +
10747
+ ' - Only the stages the project is missing actually run; a second call\n' +
10748
+ ' resumes rather than starting over.\n' +
10749
+ ' - Proposals are STAGED on the server for review; nothing is written to disk.\n' +
10750
+ ' - Re-running the command re-attaches to an in-flight stage (409 attaches).\n' +
10751
+ ' - Ctrl-C detaches locally; server-side work and charges continue.\n' +
10752
+ ' - Exit 7 on --timeout: re-run the same command to re-attach.\n' +
10753
+ ' - Workspace credits are spent per stage that runs; the result line reports\n' +
10754
+ ' what THIS run charged (omitted when nothing new was charged).\n' +
10755
+ ' `testsprite usage` shows your balance.\n' +
10756
+ '\n' +
10757
+ 'Next step: review the printed table, then `testsprite test plan accept`.\n' +
10758
+ '\n' +
10759
+ GLOBAL_OPTS_HINT)
10760
+ .action(async (cmdOpts, command) => {
10761
+ await runPlanGenerate({
10762
+ ...resolveCommonOptions(command),
10763
+ projectId: cmdOpts.project,
10764
+ timeoutSeconds: cmdOpts.timeout === undefined
10765
+ ? PLAN_GENERATE_DEFAULT_TIMEOUT_SECONDS
10766
+ : parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
10767
+ idempotencyKey: cmdOpts.idempotencyKey,
10768
+ }, deps);
10769
+ });
10770
+ plan
10771
+ .command('accept')
10772
+ .description('Convert staged proposals into real test cases (free) — all of them, or a subset with --only')
10773
+ .option('--project <id>', 'project id (V3-native; V2 ids resolve through the migration bridge)')
10774
+ .option('--only <ids...>', 'accept only these proposal ids (space- or comma-separated; the ids come from the ' +
10775
+ '`test plan generate` table). Accepting a subset discards the rest. ANY id that ' +
10776
+ 'matches no staged proposal is a validation error — the request is never sent.')
10777
+ .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
10778
+ .addHelpText('after', '\nNotes:\n' +
10779
+ ' - Accepting adds no charge of its own; generation already did the work.\n' +
10780
+ ' - API test code is generated when the tests first run, not at accept.\n' +
10781
+ ' - Accepting a subset discards the remaining staged proposals (the staging\n' +
10782
+ ' area is cleared either way) — the output says how many were discarded.\n' +
10783
+ ' - Nothing staged → exit 6 with a pointer at `test plan generate`.\n' +
10784
+ '\n' +
10785
+ GLOBAL_OPTS_HINT)
10786
+ .action(async (cmdOpts, command) => {
10787
+ await runPlanAccept({
10788
+ ...resolveCommonOptions(command),
10789
+ projectId: cmdOpts.project,
10790
+ only: cmdOpts.only,
10791
+ idempotencyKey: cmdOpts.idempotencyKey,
10792
+ }, deps);
10793
+ });
9244
10794
  return plan;
9245
10795
  }
9246
10796
  export function createTestArtifactCommand(deps) {