@testsprite/testsprite-cli 0.1.2 → 0.3.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 (58) hide show
  1. package/README.md +34 -26
  2. package/dist/commands/agent.d.ts +52 -0
  3. package/dist/commands/agent.js +341 -93
  4. package/dist/commands/auth.js +29 -27
  5. package/dist/commands/doctor.d.ts +49 -0
  6. package/dist/commands/doctor.js +211 -0
  7. package/dist/commands/init.d.ts +7 -1
  8. package/dist/commands/init.js +66 -26
  9. package/dist/commands/project.d.ts +50 -1
  10. package/dist/commands/project.js +257 -43
  11. package/dist/commands/test.d.ts +214 -12
  12. package/dist/commands/test.js +1310 -174
  13. package/dist/commands/usage.js +13 -12
  14. package/dist/index.js +71 -18
  15. package/dist/lib/agent-targets.d.ts +169 -22
  16. package/dist/lib/agent-targets.js +335 -34
  17. package/dist/lib/bundle.d.ts +51 -1
  18. package/dist/lib/bundle.js +146 -55
  19. package/dist/lib/client-factory.d.ts +43 -0
  20. package/dist/lib/client-factory.js +89 -2
  21. package/dist/lib/config.d.ts +2 -0
  22. package/dist/lib/config.js +11 -2
  23. package/dist/lib/credentials.d.ts +7 -0
  24. package/dist/lib/credentials.js +40 -1
  25. package/dist/lib/dry-run/samples.d.ts +5 -0
  26. package/dist/lib/dry-run/samples.js +54 -9
  27. package/dist/lib/flaky.d.ts +80 -0
  28. package/dist/lib/flaky.js +76 -0
  29. package/dist/lib/http.d.ts +20 -0
  30. package/dist/lib/http.js +216 -132
  31. package/dist/lib/interrupt.d.ts +61 -0
  32. package/dist/lib/interrupt.js +97 -0
  33. package/dist/lib/junit-report.d.ts +58 -0
  34. package/dist/lib/junit-report.js +210 -0
  35. package/dist/lib/output.d.ts +16 -1
  36. package/dist/lib/output.js +24 -2
  37. package/dist/lib/pagination.d.ts +4 -3
  38. package/dist/lib/pagination.js +34 -6
  39. package/dist/lib/prompt.js +52 -8
  40. package/dist/lib/proxy.d.ts +29 -0
  41. package/dist/lib/proxy.js +30 -0
  42. package/dist/lib/render-error.d.ts +13 -0
  43. package/dist/lib/render-error.js +30 -7
  44. package/dist/lib/skill-nudge.d.ts +2 -2
  45. package/dist/lib/skill-nudge.js +13 -4
  46. package/dist/lib/target-url.js +8 -1
  47. package/dist/lib/ticker.d.ts +11 -1
  48. package/dist/lib/ticker.js +33 -1
  49. package/dist/lib/update-check.d.ts +67 -0
  50. package/dist/lib/update-check.js +246 -0
  51. package/dist/version-guard.d.ts +33 -0
  52. package/dist/version-guard.js +39 -0
  53. package/dist/version.d.ts +1 -1
  54. package/dist/version.js +1 -1
  55. package/package.json +3 -2
  56. package/skills/testsprite-onboard.skill.md +183 -0
  57. package/skills/testsprite-verify.codex.md +2 -0
  58. package/skills/testsprite-verify.skill.md +52 -1
@@ -1,15 +1,16 @@
1
- import { createWriteStream, readFileSync, readdirSync, statSync } from 'node:fs';
2
- import { stat } from 'node:fs/promises';
3
- import { dirname, extname, isAbsolute, join, resolve } from 'node:path';
1
+ import { createWriteStream, existsSync, readFileSync, readdirSync, statSync, } from 'node:fs';
2
+ import { rename, stat, unlink } from 'node:fs/promises';
3
+ import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { Command } from 'commander';
6
- import { emitDryRunBanner, makeHttpClient, } from '../lib/client-factory.js';
6
+ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
7
7
  import { assertContextIntegrity, buildMeta, pickCodeExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
8
- import { findSample } from '../lib/dry-run/samples.js';
8
+ import { findSample, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
9
+ import { assertJUnitReportOptions, buildJUnitReport, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
9
10
  import { ApiError, CLIError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
10
11
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
11
12
  import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.js';
12
- import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
13
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
13
14
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
14
15
  import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
15
16
  import { RUN_SOURCES } from '../lib/runs.types.js';
@@ -18,6 +19,7 @@ import { createTicker } from '../lib/ticker.js';
18
19
  import { RateThrottle } from '../lib/rate-throttle.js';
19
20
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
20
21
  import { loadConfig } from '../lib/config.js';
22
+ import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
21
23
  const TEST_TYPES = ['frontend', 'backend'];
22
24
  // 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
23
25
  // tests created via `testsprite test create`, so the `--created-from cli`
@@ -71,17 +73,17 @@ export async function runList(opts, deps = {}) {
71
73
  startingToken: opts.startingToken,
72
74
  maxItems: opts.maxItems,
73
75
  });
76
+ // M2.1 piece 2: validate `--status` tokens client-side before
77
+ // sending. Friendlier error than waiting for the server's 400 with
78
+ // a list of accepted tokens — and lets the user fix typos without
79
+ // a round trip.
80
+ validateStatusFilter(opts.status);
74
81
  const out = makeOutput(opts.output, deps);
75
82
  const client = makeClient(opts, deps);
76
83
  // Match P2's "explicit pageSize ⇒ single-page" convention so an
77
84
  // operator can grab one slice + cursor without auto-paging through a
78
85
  // huge project.
79
86
  const useSinglePage = opts.pageSize !== undefined && opts.maxItems === undefined;
80
- // M2.1 piece 2: validate `--status` tokens client-side before
81
- // sending. Friendlier error than waiting for the server's 400 with
82
- // a list of accepted tokens — and lets the user fix typos without
83
- // a round trip.
84
- validateStatusFilter(opts.status);
85
87
  const baseQuery = {
86
88
  projectId: opts.projectId,
87
89
  type: opts.type,
@@ -223,6 +225,7 @@ export async function runCreate(opts, deps = {}) {
223
225
  },
224
226
  });
225
227
  }
228
+ assertPythonCodeFile(opts.codeFile);
226
229
  if (!['frontend', 'backend'].includes(opts.type)) {
227
230
  throw localValidationError('type', 'must be one of: frontend, backend', [
228
231
  'frontend',
@@ -240,14 +243,19 @@ export async function runCreate(opts, deps = {}) {
240
243
  if (opts.type === 'frontend') {
241
244
  const depFlags = [];
242
245
  if (opts.produces !== undefined && opts.produces.length > 0)
243
- depFlags.push('--produces');
246
+ depFlags.push('produces');
244
247
  if (opts.needs !== undefined && opts.needs.length > 0)
245
- depFlags.push('--needs');
248
+ depFlags.push('needs');
246
249
  if (opts.category !== undefined)
247
- depFlags.push('--category');
250
+ depFlags.push('category');
248
251
  if (depFlags.length > 0) {
249
- throw localValidationError(depFlags[0], `${depFlags.join(', ')} are backend-only flags; frontend plans have no wave model. ` +
250
- `Remove ${depFlags.join('/')} or use --type backend.`);
252
+ // Pass the BARE flag name to localValidationError — its kind:'flag' branch
253
+ // adds the `--` prefix, so '--produces' would render as '----produces'.
254
+ const flagList = depFlags.map(f => `--${f}`);
255
+ const verb = depFlags.length === 1 ? 'is a backend-only flag' : 'are backend-only flags';
256
+ // No trailing period: localValidationError appends one after the reason.
257
+ throw localValidationError(depFlags[0], `${flagList.join(', ')} ${verb}; frontend plans have no wave model. ` +
258
+ `Remove ${flagList.join('/')} or use --type backend`);
251
259
  }
252
260
  }
253
261
  // Dry-run path skips fs entirely so the operator can shake out the
@@ -311,6 +319,10 @@ export async function runCreate(opts, deps = {}) {
311
319
  body,
312
320
  headers: { 'idempotency-key': idempotencyKey },
313
321
  });
322
+ // Surface backend advisories (e.g. a hardcoded-credential warning for BE
323
+ // tests) on stderr so they reach the agent without polluting stdout JSON.
324
+ // Emitted before the --run early return so they always show.
325
+ emitResponseWarnings(response.warnings, deps);
314
326
  // --run chain (M3.3 piece-3). Per codex round-1 P1: suppress the
315
327
  // create's own print when chaining; `runTestRun` emits a single
316
328
  // merged envelope `{ ...createResponse, run: <trigger|final> }` so
@@ -367,6 +379,12 @@ export async function runCreate(opts, deps = {}) {
367
379
  * — kept readable for debug-event captures.
368
380
  */
369
381
  const DRY_RUN_PLACEHOLDER_CODE = '// dry-run placeholder code body';
382
+ function assertPythonCodeFile(path) {
383
+ if (!path.toLowerCase().endsWith('.py')) {
384
+ throw localValidationError('code-file', 'must be a Python (.py) file — TestSprite runs all test code as Python ' +
385
+ '(frontend: Playwright for Python; backend: requests + pytest).');
386
+ }
387
+ }
370
388
  /**
371
389
  * Read the code body with a `stat`-first size guard so an oversize
372
390
  * artifact is rejected BEFORE we load + decode the whole thing into
@@ -406,7 +424,7 @@ function readCodeFileGuarded(path) {
406
424
  }
407
425
  function readCodeFile(path) {
408
426
  try {
409
- return readFileSync(resolveAbsolute(path), 'utf8');
427
+ return stripBom(readFileSync(resolveAbsolute(path), 'utf8'));
410
428
  }
411
429
  catch (err) {
412
430
  const code = err.code;
@@ -451,6 +469,17 @@ function renderCreateText(response) {
451
469
  `createdAt ${response.createdAt}`,
452
470
  ].join('\n');
453
471
  }
472
+ /**
473
+ * Emit backend `warnings[]` advisories to stderr (one `[warn]` line each),
474
+ * keeping stdout — JSON or text — uncluttered. No-op when absent/empty.
475
+ */
476
+ function emitResponseWarnings(warnings, deps) {
477
+ if (!warnings || warnings.length === 0)
478
+ return;
479
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
480
+ for (const w of warnings)
481
+ stderrFn(`[warn] ${w}`);
482
+ }
454
483
  /**
455
484
  * piece-6 cap for the `PUT /tests/{id}/plan-steps` body. Distinct from
456
485
  * piece-5's `MAX_PLAN_BODY_BYTES` because the wire shape differs
@@ -646,6 +675,9 @@ export async function runUpdate(opts, deps = {}) {
646
675
  assertIdempotencyKey(opts.idempotencyKey);
647
676
  requireNonEmpty('test-id', opts.testId);
648
677
  // P1-3: client-side length checks matching server limits.
678
+ if (opts.name !== undefined && opts.name.trim().length === 0) {
679
+ throw localValidationError('name', 'must be a non-empty string (whitespace-only is not allowed)');
680
+ }
649
681
  if (opts.name !== undefined && opts.name.length > 200) {
650
682
  throw localValidationError('name', 'must be at most 200 characters');
651
683
  }
@@ -920,6 +952,58 @@ const MAX_BATCH_BODY_BYTES = 5 * 1024 * 1024;
920
952
  * than this, the CLI splits into chunks and aggregates the results.
921
953
  */
922
954
  const MAX_BATCH_RERUN_IDS = 50;
955
+ /**
956
+ * Drop duplicate `testId` entries from a chunked batch-rerun's aggregated
957
+ * `accepted[]`, keeping the first occurrence. BE producer/teardown closure
958
+ * dedup happens per-request server-side, not across the separate requests
959
+ * one chunk per `MAX_BATCH_RERUN_IDS` window produces, so the same producer
960
+ * can come back accepted (with a different runId) from more than one
961
+ * chunk. Returns the deduped list plus how many entries were dropped, so
962
+ * the caller can warn the operator that a shared BE producer/teardown was
963
+ * triggered more than once.
964
+ */
965
+ function dedupeBatchRerunAccepted(entries) {
966
+ const seen = new Map();
967
+ let droppedCount = 0;
968
+ for (const entry of entries) {
969
+ if (seen.has(entry.testId)) {
970
+ droppedCount++;
971
+ continue;
972
+ }
973
+ seen.set(entry.testId, entry);
974
+ }
975
+ return { deduped: [...seen.values()], droppedCount };
976
+ }
977
+ /**
978
+ * Merge per-project closure summaries from multiple batch-rerun chunk
979
+ * responses, combining entries that share a `projectId` rather than
980
+ * leaving one entry per chunk. `testIds` / `addedProducers` /
981
+ * `addedTeardowns` are unioned (a producer present in two chunks' entries
982
+ * for the same project, the closure-dedup race this fixes, must not be
983
+ * counted twice); `clearedCaptured` is summed, each chunk's expansion is a
984
+ * disjoint operation so its count is additive.
985
+ */
986
+ function mergeBatchRerunClosureByProject(entries) {
987
+ const byProject = new Map();
988
+ for (const entry of entries) {
989
+ const existing = byProject.get(entry.projectId);
990
+ if (!existing) {
991
+ byProject.set(entry.projectId, {
992
+ projectId: entry.projectId,
993
+ testIds: [...new Set(entry.testIds)],
994
+ addedProducers: [...new Set(entry.addedProducers)],
995
+ addedTeardowns: [...new Set(entry.addedTeardowns)],
996
+ clearedCaptured: entry.clearedCaptured,
997
+ });
998
+ continue;
999
+ }
1000
+ existing.testIds = [...new Set([...existing.testIds, ...entry.testIds])];
1001
+ existing.addedProducers = [...new Set([...existing.addedProducers, ...entry.addedProducers])];
1002
+ existing.addedTeardowns = [...new Set([...existing.addedTeardowns, ...entry.addedTeardowns])];
1003
+ existing.clearedCaptured += entry.clearedCaptured;
1004
+ }
1005
+ return [...byProject.values()];
1006
+ }
923
1007
  /**
924
1008
  * Default max in-flight run-triggers for `create-batch --run`.
925
1009
  *
@@ -1796,42 +1880,31 @@ apiUrlForDashboard) {
1796
1880
  failureKind: finalRun.failureKind,
1797
1881
  };
1798
1882
  }
1799
- // Bounded concurrency fan-out using a semaphore pattern.
1800
- // We process testIds one slot at a time up to the concurrency limit.
1801
- // This avoids pulling in p-limit; the logic is simple enough inline.
1802
- const remaining = [...testIds];
1803
- const inFlight = new Set();
1804
- async function drainOne() {
1805
- const testId = remaining.shift();
1806
- if (testId === undefined)
1807
- return;
1808
- const p = triggerOne(testId).then(result => {
1809
- batchRunResults.push(result);
1810
- inFlight.delete(p);
1811
- return result;
1812
- });
1813
- inFlight.add(p);
1814
- await p;
1815
- }
1816
- // Fill up to concurrencyLimit slots, then drain one before adding
1817
- // each new testId so we never exceed the limit.
1818
- const initial = Math.min(concurrencyLimit, testIds.length);
1819
- const startPromises = [];
1820
- for (let i = 0; i < initial; i++) {
1821
- startPromises.push(drainOne());
1822
- }
1823
- // Process remaining items as slots free up.
1824
- while (remaining.length > 0) {
1825
- // Wait for any in-flight slot to free up.
1826
- if (inFlight.size > 0) {
1827
- await Promise.race(inFlight);
1828
- }
1829
- if (remaining.length > 0 && inFlight.size < concurrencyLimit) {
1830
- await drainOne();
1883
+ // Bounded concurrency fan-out: launch up to concurrencyLimit jobs, then
1884
+ // launch the next one as each finishes. Mirrors the startNext() pattern
1885
+ // used by the other fan-outs in this file (e.g. pollFreshAccepted below).
1886
+ let nextIdx = 0;
1887
+ let inFlight = 0;
1888
+ await new Promise((resolve, reject) => {
1889
+ function startNext() {
1890
+ while (inFlight < concurrencyLimit && nextIdx < testIds.length) {
1891
+ const testId = testIds[nextIdx++];
1892
+ inFlight++;
1893
+ triggerOne(testId)
1894
+ .then(result => {
1895
+ batchRunResults.push(result);
1896
+ inFlight--;
1897
+ startNext();
1898
+ if (inFlight === 0 && nextIdx >= testIds.length)
1899
+ resolve();
1900
+ })
1901
+ .catch(reject);
1902
+ }
1831
1903
  }
1832
- }
1833
- // Wait for all in-flight to finish.
1834
- await Promise.all([...inFlight, ...startPromises]);
1904
+ startNext();
1905
+ if (testIds.length === 0)
1906
+ resolve();
1907
+ });
1835
1908
  // Sort by testId order (same as input order for stable output).
1836
1909
  batchRunResults.sort((a, b) => testIds.indexOf(a.testId) - testIds.indexOf(b.testId));
1837
1910
  // Emit output.
@@ -2159,11 +2232,14 @@ export async function runGet(opts, deps = {}) {
2159
2232
  * directly; presigned URLs are dereferenced via the same fetch impl
2160
2233
  * (without API-key headers — the URL is the bearer of authority).
2161
2234
  *
2162
- * `--out <path>` redirects the same bytes into a file. We open the file
2163
- * before issuing the network request so a permission/dir error fails
2164
- * fast (exit 5 / VALIDATION_ERROR) without spending an API call. On
2165
- * any error after open we tear down the sink so we don't leak a
2166
- * half-written artifact.
2235
+ * `--out <path>` redirects the same bytes into a file. We validate the
2236
+ * path and open a sibling temp file before issuing the network request
2237
+ * so a permission/dir error fails fast (exit 5 / VALIDATION_ERROR)
2238
+ * without spending an API call. The temp file is renamed onto the real
2239
+ * `--out` path only after a successful, complete write; on any error
2240
+ * (or the "no code generated yet" branch, which writes nothing) the
2241
+ * temp file is discarded and the user's pre-existing `--out` file, if
2242
+ * any, is left untouched.
2167
2243
  */
2168
2244
  export async function runCodeGet(opts, deps = {}) {
2169
2245
  // Dry-run: no fetch, no fs. Print the canned shape to stdout and, if
@@ -2188,13 +2264,15 @@ export async function runCodeGet(opts, deps = {}) {
2188
2264
  }
2189
2265
  return code;
2190
2266
  }
2191
- const fileSink = opts.out !== undefined ? openOutputFile(opts.out) : null;
2267
+ let fileSink = opts.out !== undefined ? openOutputFile(opts.out) : null;
2192
2268
  const out = fileSink ? makeFileOutput(opts.output, fileSink) : makeOutput(opts.output, deps);
2193
2269
  const client = makeClient(opts, deps);
2194
2270
  try {
2195
2271
  const code = await client.get(`/tests/${encodeURIComponent(opts.testId)}/code`);
2272
+ let wroteContent = false;
2196
2273
  if (opts.output === 'json') {
2197
2274
  out.print(code);
2275
+ wroteContent = true;
2198
2276
  }
2199
2277
  else if (isPresignedCodeUrl(code.code)) {
2200
2278
  // Text mode: dump the source body. JSON consumers want the wire
@@ -2206,28 +2284,45 @@ export async function runCodeGet(opts, deps = {}) {
2206
2284
  // or a piped `gzip`) pauses the upstream reader rather than
2207
2285
  // letting chunks accumulate in V8's heap.
2208
2286
  await streamPresignedBody(code.code, out, deps);
2287
+ wroteContent = true;
2209
2288
  }
2210
2289
  else if (code.code === '' || code.code === null) {
2211
2290
  // P2-10: draft test with no code yet — empty body would produce
2212
2291
  // silent empty stdout. Print a friendly hint to stderr instead so
2213
- // the operator knows what happened, and keep exit 0.
2292
+ // the operator knows what happened, and keep exit 0 when no `--out`.
2293
+ //
2294
+ // With `--out`, refuse to leave a zero-byte artifact behind: agents
2295
+ // and scripts that check file size would otherwise treat exit 0 as
2296
+ // a successful download. Discard the temp sink without touching a
2297
+ // pre-existing destination file.
2298
+ if (fileSink) {
2299
+ await abortOutputFile(fileSink);
2300
+ fileSink = null;
2301
+ throw localValidationError('out', 'test has no generated code yet — run the test first (refusing to write an empty --out file)');
2302
+ }
2214
2303
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2215
2304
  stderrFn('(no code generated yet — run the test first)');
2216
2305
  }
2217
2306
  else {
2218
2307
  await out.writeChunk(code.code);
2308
+ wroteContent = true;
2219
2309
  }
2220
2310
  if (fileSink)
2221
- await closeOutputFile(fileSink);
2311
+ await closeOutputFile(fileSink, wroteContent);
2222
2312
  return code;
2223
2313
  }
2224
2314
  catch (err) {
2225
2315
  if (fileSink)
2226
- await closeOutputFile(fileSink).catch(() => undefined);
2316
+ await closeOutputFile(fileSink, false).catch(() => undefined);
2227
2317
  throw err;
2228
2318
  }
2229
2319
  }
2230
- const CODE_PUT_LANGUAGES = ['typescript', 'javascript', 'python'];
2320
+ // Only `python` is accepted as a `--language` INPUT: TestSprite executes
2321
+ // stored test code as Python (FE Playwright `playwright.async_api`, BE
2322
+ // `requests`/pytest), so accepting `typescript`/`javascript` would be a
2323
+ // false promise. The read-side `CliTestCode['language']` union keeps ts/js
2324
+ // for wire fidelity with legacy rows the server may still return.
2325
+ const CODE_PUT_LANGUAGES = ['python'];
2231
2326
  /**
2232
2327
  * `test code put <test-id> --code-file <path>` — M3.2 piece-4.
2233
2328
  *
@@ -2269,6 +2364,7 @@ export async function runCodePut(opts, deps = {}) {
2269
2364
  assertIdempotencyKey(opts.idempotencyKey);
2270
2365
  requireNonEmpty('test-id', opts.testId);
2271
2366
  requireNonEmpty('code-file', opts.codeFile);
2367
+ assertPythonCodeFile(opts.codeFile);
2272
2368
  if (opts.expectedVersion !== undefined && opts.force === true) {
2273
2369
  throw localValidationError('expected-version', 'is mutually exclusive with --force; pass one or the other (or neither for auto-fetch)');
2274
2370
  }
@@ -2349,6 +2445,7 @@ export async function runCodePut(opts, deps = {}) {
2349
2445
  'if-match': ifMatch,
2350
2446
  },
2351
2447
  });
2448
+ emitResponseWarnings(response.warnings, deps);
2352
2449
  out.print(response, data => renderCodePutText(data));
2353
2450
  return response;
2354
2451
  }
@@ -2413,7 +2510,333 @@ function mapRunStepToCliTestStep(step, run) {
2413
2510
  // concrete boolean — `true` for the failing step, `false` for the known
2414
2511
  // non-contributors. (Per the CliTestStep contract: null ≠ false.)
2415
2512
  outcomeContributesToFailure: run.failedStepIndex === null ? null : numericIndex === run.failedStepIndex,
2513
+ // Carry the per-step failure text and the wire step kind through instead
2514
+ // of dropping them: the agent asking "why did this step fail?" would
2515
+ // otherwise have to download the whole artifact bundle to read a string
2516
+ // this very response already contained.
2517
+ error: step.error,
2518
+ stepType: step.type,
2519
+ };
2520
+ }
2521
+ /**
2522
+ * `test diff <runA> <runB>` (issue #124): isolate what regressed between two
2523
+ * runs, the first question when CI goes red ("what changed since the last
2524
+ * green run?"). Pure client-side composition of the existing per-run read
2525
+ * (`GET /runs/{id}?includeSteps=true`); the endpoint accepts any two run-ids,
2526
+ * so a cross-test pair is a WARNING, not an error. Exit 0 when the verdicts
2527
+ * match, exit 1 when they differ, so the command is CI-scriptable.
2528
+ */
2529
+ export async function runDiff(opts, deps = {}) {
2530
+ const out = makeOutput(opts.output, deps);
2531
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2532
+ if (opts.dryRun) {
2533
+ emitDryRunBanner(stderrFn);
2534
+ const sample = {
2535
+ runA: {
2536
+ runId: opts.runA,
2537
+ testId: 'test_dryrun',
2538
+ status: 'passed',
2539
+ failureKind: null,
2540
+ failedStepIndex: null,
2541
+ codeVersion: 'v1',
2542
+ },
2543
+ runB: {
2544
+ runId: opts.runB,
2545
+ testId: 'test_dryrun',
2546
+ status: 'failed',
2547
+ failureKind: 'assertion',
2548
+ failedStepIndex: 2,
2549
+ codeVersion: 'v1',
2550
+ },
2551
+ verdictChanged: true,
2552
+ failedStepIndexChanged: true,
2553
+ failureKindChanged: true,
2554
+ codeVersionChanged: false,
2555
+ crossTest: false,
2556
+ changedSteps: [{ stepIndex: 2, statusA: 'passed', statusB: 'failed' }],
2557
+ };
2558
+ out.print(sample, () => renderRunDiffText(sample));
2559
+ return sample;
2560
+ }
2561
+ const client = makeClient(opts, deps);
2562
+ const [runA, runB] = await Promise.all([
2563
+ client.getRun(opts.runA, { includeSteps: true }),
2564
+ client.getRun(opts.runB, { includeSteps: true }),
2565
+ ]);
2566
+ const crossTest = runA.testId !== runB.testId;
2567
+ if (crossTest) {
2568
+ stderrFn(`⚠ the two runs belong to different tests (${runA.testId} vs ${runB.testId}) — step deltas may be meaningless`);
2569
+ }
2570
+ const stepsByIndex = (run) => {
2571
+ const map = new Map();
2572
+ for (const step of run.steps ?? []) {
2573
+ const index = parseInt(step.stepIndex, 10);
2574
+ if (Number.isInteger(index))
2575
+ map.set(index, { status: step.status ?? 'unknown', error: step.error });
2576
+ }
2577
+ return map;
2416
2578
  };
2579
+ const stepsA = stepsByIndex(runA);
2580
+ const stepsB = stepsByIndex(runB);
2581
+ const allIndexes = [...new Set([...stepsA.keys(), ...stepsB.keys()])].sort((left, right) => left - right);
2582
+ const changedSteps = [];
2583
+ for (const index of allIndexes) {
2584
+ const sideA = stepsA.get(index);
2585
+ const sideB = stepsB.get(index);
2586
+ const statusA = sideA?.status ?? 'absent';
2587
+ const statusB = sideB?.status ?? 'absent';
2588
+ if (statusA === statusB)
2589
+ continue;
2590
+ changedSteps.push({
2591
+ stepIndex: index,
2592
+ statusA,
2593
+ statusB,
2594
+ ...(sideA?.error ? { errorA: sideA.error } : {}),
2595
+ ...(sideB?.error ? { errorB: sideB.error } : {}),
2596
+ });
2597
+ }
2598
+ const summarize = (run) => ({
2599
+ runId: run.runId,
2600
+ testId: run.testId,
2601
+ status: run.status,
2602
+ failureKind: run.failureKind ?? null,
2603
+ failedStepIndex: run.failedStepIndex,
2604
+ codeVersion: run.codeVersion ?? null,
2605
+ });
2606
+ const diff = {
2607
+ runA: summarize(runA),
2608
+ runB: summarize(runB),
2609
+ verdictChanged: runA.status !== runB.status,
2610
+ failedStepIndexChanged: runA.failedStepIndex !== runB.failedStepIndex,
2611
+ failureKindChanged: (runA.failureKind ?? null) !== (runB.failureKind ?? null),
2612
+ codeVersionChanged: (runA.codeVersion ?? null) !== (runB.codeVersion ?? null),
2613
+ crossTest,
2614
+ changedSteps,
2615
+ };
2616
+ out.print(diff, () => renderRunDiffText(diff));
2617
+ if (diff.verdictChanged) {
2618
+ // Result already printed; the typed exit makes `test diff` a CI gate.
2619
+ throw new CLIError(`verdicts differ: ${runA.runId}=${runA.status} vs ${runB.runId}=${runB.status}`, 1);
2620
+ }
2621
+ return diff;
2622
+ }
2623
+ function renderRunDiffText(diff) {
2624
+ const lines = [];
2625
+ lines.push(`runA: ${diff.runA.runId} ${diff.runA.status} (test ${diff.runA.testId})`);
2626
+ lines.push(`runB: ${diff.runB.runId} ${diff.runB.status} (test ${diff.runB.testId})`);
2627
+ lines.push(`verdict: ${diff.verdictChanged ? `${diff.runA.status} -> ${diff.runB.status}` : `unchanged (${diff.runA.status})`}`);
2628
+ if (diff.failureKindChanged)
2629
+ lines.push(`failureKind: ${diff.runA.failureKind ?? '(none)'} -> ${diff.runB.failureKind ?? '(none)'}`);
2630
+ if (diff.failedStepIndexChanged)
2631
+ lines.push(`failedStepIndex: ${diff.runA.failedStepIndex ?? '(none)'} -> ${diff.runB.failedStepIndex ?? '(none)'}`);
2632
+ lines.push(`codeVersion: ${diff.codeVersionChanged ? `${diff.runA.codeVersion ?? '(none)'} -> ${diff.runB.codeVersion ?? '(none)'} (code drift)` : 'unchanged'}`);
2633
+ if (diff.changedSteps.length === 0) {
2634
+ lines.push('steps: no per-step status changes');
2635
+ }
2636
+ else {
2637
+ lines.push(`steps changed: ${diff.changedSteps.length}`);
2638
+ for (const step of diff.changedSteps) {
2639
+ lines.push(` #${step.stepIndex} ${step.statusA} -> ${step.statusB}`);
2640
+ if (step.errorB)
2641
+ lines.push(` error(B): ${step.errorB.replace(/\s+/g, ' ').trim()}`);
2642
+ else if (step.errorA)
2643
+ lines.push(` error(A): ${step.errorA.replace(/\s+/g, ' ').trim()}`);
2644
+ }
2645
+ }
2646
+ return lines.join('\n');
2647
+ }
2648
+ /**
2649
+ * `test lint` (issue #98): validate plan/steps files fully OFFLINE with the
2650
+ * SAME validators the create paths run, but collecting EVERY problem instead
2651
+ * of dying on the first one, and without any network write. The create-batch
2652
+ * reader is first-error-fatal and only reachable through a command that POSTs,
2653
+ * so authoring a 12-plan directory meant one error per paid round-trip. Zero
2654
+ * network, zero credentials: exit 0 when everything is valid, 5 otherwise, so
2655
+ * it drops into a pre-commit hook or CI step before `create-batch`.
2656
+ */
2657
+ export async function runLint(opts, deps = {}) {
2658
+ const out = makeOutput(opts.output, deps);
2659
+ const sources = [opts.planFrom, opts.planFromDir, opts.plans, opts.steps].filter(source => source !== undefined);
2660
+ if (sources.length !== 1) {
2661
+ throw localValidationError('plan-from', 'exactly one of --plan-from, --plan-from-dir, --plans, or --steps is required');
2662
+ }
2663
+ const issues = [];
2664
+ let checked = 0;
2665
+ // Run one existing validator, converting its typed throw into a report row
2666
+ // (same envelopes, so `details.field` pointers like planSteps[2].type
2667
+ // survive verbatim).
2668
+ const collect = (file, validate) => {
2669
+ checked += 1;
2670
+ try {
2671
+ validate();
2672
+ }
2673
+ catch (err) {
2674
+ if (err instanceof ApiError) {
2675
+ issues.push({
2676
+ file,
2677
+ field: String(err.getDetail('field') ?? '(file)'),
2678
+ reason: String(err.getDetail('reason') ?? err.nextAction ?? err.message),
2679
+ });
2680
+ }
2681
+ else {
2682
+ issues.push({
2683
+ file,
2684
+ field: '(file)',
2685
+ reason: err instanceof Error ? err.message : String(err),
2686
+ });
2687
+ }
2688
+ }
2689
+ };
2690
+ if (opts.planFrom !== undefined) {
2691
+ const planFrom = opts.planFrom;
2692
+ collect(planFrom, () => void readPlanFromGuarded(planFrom));
2693
+ }
2694
+ else if (opts.steps !== undefined) {
2695
+ const steps = opts.steps;
2696
+ collect(steps, () => void readPlanStepsFileGuarded(steps));
2697
+ }
2698
+ else if (opts.planFromDir !== undefined) {
2699
+ const dir = resolveAbsolute(opts.planFromDir);
2700
+ let entries;
2701
+ try {
2702
+ entries = readdirSync(dir)
2703
+ .filter(name => name.endsWith('.json'))
2704
+ .sort();
2705
+ }
2706
+ catch {
2707
+ throw localValidationError('plan-from-dir', `cannot read directory: ${dir}`);
2708
+ }
2709
+ if (entries.length === 0) {
2710
+ throw localValidationError('plan-from-dir', 'contains no *.json plan files');
2711
+ }
2712
+ for (const entry of entries) {
2713
+ collect(entry, () => void readPlanFromGuarded(join(dir, entry)));
2714
+ }
2715
+ }
2716
+ else if (opts.plans !== undefined) {
2717
+ // JSONL: validate PER LINE so every bad line reports (the create path's
2718
+ // reader stays throw-on-first; this is the collecting counterpart).
2719
+ const absolute = resolveAbsolute(opts.plans);
2720
+ let content;
2721
+ try {
2722
+ content = readFileSync(absolute, 'utf8');
2723
+ }
2724
+ catch {
2725
+ throw localValidationError('plans', `cannot read file: ${absolute}`);
2726
+ }
2727
+ // Index lines BEFORE dropping blanks so every reported `file:N` points at
2728
+ // the PHYSICAL line in the file (a blank separator line must not shift all
2729
+ // subsequent line numbers).
2730
+ const numberedLines = content
2731
+ .split('\n')
2732
+ .map((rawLine, physicalIndex) => ({ line: rawLine.trim(), lineNo: physicalIndex + 1 }))
2733
+ .filter(entry => entry.line.length > 0);
2734
+ if (numberedLines.length === 0)
2735
+ throw localValidationError('plans', 'contains no plan lines');
2736
+ for (const { line, lineNo } of numberedLines) {
2737
+ collect(`${opts.plans}:${lineNo}`, () => {
2738
+ let parsed;
2739
+ try {
2740
+ parsed = JSON.parse(line);
2741
+ }
2742
+ catch {
2743
+ throw localValidationError('plans', `line ${lineNo} is not valid JSON`, undefined, 'field');
2744
+ }
2745
+ assertPlanShape(parsed, { specIndex: lineNo - 1 });
2746
+ });
2747
+ }
2748
+ }
2749
+ const filesWithIssues = new Set(issues.map(issue => issue.file)).size;
2750
+ const report = { checked, valid: checked - filesWithIssues, issues };
2751
+ out.print(report, () => [
2752
+ ...issues.map(issue => `${issue.file}: ${issue.field}: ${issue.reason}`),
2753
+ `${report.valid}/${report.checked} valid, ${issues.length} problem(s)`,
2754
+ ].join('\n'));
2755
+ if (issues.length > 0) {
2756
+ throw new CLIError(`lint: ${issues.length} problem(s) across ${report.checked} file(s)`, 5);
2757
+ }
2758
+ return report;
2759
+ }
2760
+ /**
2761
+ * `test scaffold` — emit a schema-correct starter test definition so a first
2762
+ * test never starts from hand-copied JSON. Pure-local: no network, no
2763
+ * credentials, no filesystem reads. The frontend template is a `CliPlanInput`
2764
+ * (the exact shape `--plan-from` ingests; sourceRef: CliPlanInput /
2765
+ * PLAN_STEP_TYPES above), so `scaffold | create --plan-from -`-style flows
2766
+ * validate out of the box. The backend template is the minimal `requests`
2767
+ * script the onboarding skill mandates: define a test function with a
2768
+ * concrete status assertion, then CALL it (a defined-but-never-called test
2769
+ * would pass without asserting anything).
2770
+ */
2771
+ export async function runScaffold(opts, deps = {}) {
2772
+ const out = makeOutput(opts.output, deps);
2773
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2774
+ const env = deps.env ?? process.env;
2775
+ // Pre-fill the project id from TESTSPRITE_PROJECT_ID when the caller's
2776
+ // environment carries one; otherwise a clearly-marked placeholder the user
2777
+ // swaps after running `testsprite project list`.
2778
+ const projectId = typeof env.TESTSPRITE_PROJECT_ID === 'string' && env.TESTSPRITE_PROJECT_ID.length > 0
2779
+ ? env.TESTSPRITE_PROJECT_ID
2780
+ : '<run: testsprite project list>';
2781
+ let payload;
2782
+ let body;
2783
+ if (opts.scaffoldType === 'frontend') {
2784
+ const plan = {
2785
+ projectId,
2786
+ type: 'frontend',
2787
+ name: 'My first frontend test',
2788
+ description: 'Replace with one sentence describing what this test verifies.',
2789
+ priority: 'p2',
2790
+ planSteps: [
2791
+ {
2792
+ type: 'action',
2793
+ description: 'Navigate to /login and sign in with a seeded test account',
2794
+ },
2795
+ { type: 'action', description: 'Open the first product page and click "Add to cart"' },
2796
+ { type: 'assertion', description: 'Assert that the cart badge shows 1 item' },
2797
+ ],
2798
+ };
2799
+ payload = plan;
2800
+ body = `${JSON.stringify(plan, null, 2)}\n`;
2801
+ }
2802
+ else {
2803
+ const code = [
2804
+ 'import requests',
2805
+ '',
2806
+ '# Replace with your API base URL (must be reachable from the internet).',
2807
+ 'BASE_URL = "https://staging.example.com"',
2808
+ '',
2809
+ '',
2810
+ 'def test_health_endpoint() -> None:',
2811
+ ' response = requests.get(f"{BASE_URL}/health", timeout=30)',
2812
+ ' assert response.status_code == 200, f"expected 200, got {response.status_code}"',
2813
+ '',
2814
+ '',
2815
+ '# The test function MUST be called: TestSprite executes this file top to',
2816
+ '# bottom, so a defined-but-never-called function would pass vacuously.',
2817
+ 'test_health_endpoint()',
2818
+ '',
2819
+ ].join('\n');
2820
+ payload = { type: 'backend', language: 'python', code };
2821
+ body = code;
2822
+ }
2823
+ if (opts.out !== undefined) {
2824
+ const resolved = isAbsolute(opts.out) ? opts.out : resolve(process.cwd(), opts.out);
2825
+ // Never clobber silently: scaffolds are starting points the user edits, so
2826
+ // an accidental re-run must not erase their work. --force opts in.
2827
+ if (!opts.force && existsSync(resolved)) {
2828
+ throw localValidationError('out', `already exists: ${resolved}. Pass --force to overwrite`);
2829
+ }
2830
+ const sink = openOutputFile(opts.out); // reuses the directory/parent guards
2831
+ const fileOut = makeFileOutput(opts.output, sink);
2832
+ await fileOut.writeChunk(body);
2833
+ await closeOutputFile(sink, true);
2834
+ stderrFn(`Scaffold written to ${resolved}`);
2835
+ return payload;
2836
+ }
2837
+ // No --out: the scaffold body IS the stdout payload (`> plan.json` works).
2838
+ out.print(payload, () => body.trimEnd());
2839
+ return payload;
2417
2840
  }
2418
2841
  export async function runSteps(opts, deps = {}) {
2419
2842
  const out = makeOutput(opts.output, deps);
@@ -2528,12 +2951,20 @@ export function parseDuration(raw, now = new Date()) {
2528
2951
  const hourMatch = /^(\d+)h$/i.exec(raw);
2529
2952
  if (hourMatch) {
2530
2953
  const hours = Number(hourMatch[1]);
2531
- return new Date(now.getTime() - hours * 60 * 60 * 1000).toISOString();
2954
+ const result = new Date(now.getTime() - hours * 60 * 60 * 1000);
2955
+ if (!Number.isFinite(result.getTime())) {
2956
+ throw localValidationError('since', 'duration is too large; maximum is ~1141552511h');
2957
+ }
2958
+ return result.toISOString();
2532
2959
  }
2533
2960
  const dayMatch = /^(\d+)d$/i.exec(raw);
2534
2961
  if (dayMatch) {
2535
2962
  const days = Number(dayMatch[1]);
2536
- return new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString();
2963
+ const result = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
2964
+ if (!Number.isFinite(result.getTime())) {
2965
+ throw localValidationError('since', 'duration is too large; maximum is ~47564688d');
2966
+ }
2967
+ return result.toISOString();
2537
2968
  }
2538
2969
  // Pass-through: ISO timestamp or epoch value — server validates.
2539
2970
  return raw;
@@ -2553,7 +2984,10 @@ export async function runResultHistory(opts, deps = {}) {
2553
2984
  // configured (codex round-2), matching validatePaginationFlags ordering
2554
2985
  // in `test list` / `project list`.
2555
2986
  if (opts.pageSize !== undefined) {
2556
- if (!Number.isFinite(opts.pageSize) || opts.pageSize < 1 || opts.pageSize > 100) {
2987
+ if (!Number.isFinite(opts.pageSize) || !Number.isInteger(opts.pageSize)) {
2988
+ throw localValidationError('page-size', 'must be an integer between 1 and 100');
2989
+ }
2990
+ if (opts.pageSize < 1 || opts.pageSize > 100) {
2557
2991
  throw localValidationError('page-size', 'must be between 1 and 100');
2558
2992
  }
2559
2993
  }
@@ -2631,6 +3065,13 @@ const RUN_HISTORY_TABLE_COL_WIDTHS = {
2631
3065
  * out (dogfood 2026-06-04). `--output json` carries the full text.
2632
3066
  */
2633
3067
  const DESC_COL_MAX = 60;
3068
+ /**
3069
+ * Cap, in chars, for the one-line `error:` sub-line under a failed step row
3070
+ * in `renderStepsText`. Long enough for a full assertion message, short
3071
+ * enough that a stack-trace blob can't flood the table. Full text is in
3072
+ * `--output json`.
3073
+ */
3074
+ const ERROR_SUBLINE_MAX = 200;
2634
3075
  /** Max chars to show in the TARGETURL sub-line (excess truncated with …). */
2635
3076
  const HISTORY_TARGET_URL_MAX = 80;
2636
3077
  /**
@@ -2759,11 +3200,15 @@ export async function runFailureSummary(opts, deps = {}) {
2759
3200
  export async function runFailureGet(opts, deps = {}) {
2760
3201
  const out = makeOutput(opts.output, deps);
2761
3202
  const client = makeClient(opts, deps);
2762
- // We resolve the output dir BEFORE the network call so a missing /
3203
+ // Resolve and validate --out BEFORE the network call so a missing /
2763
3204
  // empty path surfaces as VALIDATION_ERROR (exit 5) without spending
2764
- // an API call. `writeBundle` re-validates internally; this is the
2765
- // fast-fail.
2766
- const requestedDir = opts.out;
3205
+ // an API call. Mirrors `runArtifactGet`; `writeBundle` re-validates
3206
+ // internally as defense-in-depth.
3207
+ let resolvedDir;
3208
+ if (opts.out !== undefined) {
3209
+ resolvedDir = resolveBundleDir(opts.out);
3210
+ await assertOutDirParentExists(resolvedDir);
3211
+ }
2767
3212
  const context = await client.get(`/tests/${encodeURIComponent(opts.testId)}/failure`);
2768
3213
  // Run the §3 atomicity invariants on every path — even when --out is
2769
3214
  // absent. An agent piping the JSON envelope into a vision-LLM
@@ -2771,7 +3216,7 @@ export async function runFailureGet(opts, deps = {}) {
2771
3216
  // guarantees never reaches it. The bundle writer re-runs the check
2772
3217
  // internally; this call is the cheap upfront trap.
2773
3218
  assertContextIntegrity(context, 'local');
2774
- if (requestedDir !== undefined) {
3219
+ if (resolvedDir !== undefined) {
2775
3220
  // Dry-run: do NOT call writeBundle (which would mkdir, fetch
2776
3221
  // presigned URLs, and write files). Print the would-be bundle layout
2777
3222
  // to stderr and emit the wire envelope to stdout so the agent sees
@@ -2779,23 +3224,23 @@ export async function runFailureGet(opts, deps = {}) {
2779
3224
  if (opts.dryRun) {
2780
3225
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2781
3226
  const fileNames = plannedBundleFiles(context, opts.failedOnly);
2782
- stderr(`[dry-run] would write bundle to ${requestedDir} (${fileNames.length} files; meta.json renames last)`);
3227
+ stderr(`[dry-run] would write bundle to ${resolvedDir} (${fileNames.length} files; meta.json renames last)`);
2783
3228
  for (const f of fileNames)
2784
3229
  stderr(`[dry-run] ${f}`);
2785
3230
  if (opts.output === 'json') {
2786
- out.print({ ok: true, dir: requestedDir, dryRun: true, context });
3231
+ out.print({ ok: true, dir: resolvedDir, dryRun: true, context });
2787
3232
  }
2788
3233
  else {
2789
3234
  // Use a dry-run-specific renderer: the real success renderer
2790
3235
  // says "Bundle written to ..." which would be a lie here. Stdout
2791
3236
  // is the success contract automation may parse, so it must not
2792
3237
  // imply the bundle was created.
2793
- out.print({ dir: requestedDir, files: fileNames.length, snapshotId: context.snapshotId }, data => renderBundleDryRunText(data));
3238
+ out.print({ dir: resolvedDir, files: fileNames.length, snapshotId: context.snapshotId }, data => renderBundleDryRunText(data));
2794
3239
  }
2795
3240
  return { context };
2796
3241
  }
2797
3242
  const bundle = await writeBundle(context, {
2798
- dir: requestedDir,
3243
+ dir: resolvedDir,
2799
3244
  failedOnly: opts.failedOnly,
2800
3245
  fetchImpl: deps.fetchImpl,
2801
3246
  });
@@ -2864,7 +3309,12 @@ function isTerminalPublicStatus(status) {
2864
3309
  * round-2: don't fabricate blank correlation fields).
2865
3310
  */
2866
3311
  function backendResultToRunResponse(result, run) {
2867
- const total = result.summary.passed + result.summary.failed + result.summary.skipped;
3312
+ // `result.summary` is now a semantic string, not a count object.
3313
+ // Reconstruct the synthetic 1-test stepSummary from the verdict (byte-identical
3314
+ // to the prior status-derived counts: passed→1/0, failed→0/1, else→0/0).
3315
+ const passedCount = result.status === 'passed' ? 1 : 0;
3316
+ const failedCount = result.status === 'failed' ? 1 : 0;
3317
+ const total = passedCount + failedCount;
2868
3318
  return {
2869
3319
  ...run,
2870
3320
  status: result.status,
@@ -2882,9 +3332,9 @@ function backendResultToRunResponse(result, run) {
2882
3332
  videoUrl: result.videoUrl,
2883
3333
  stepSummary: {
2884
3334
  total,
2885
- completed: result.summary.passed + result.summary.failed,
2886
- passedCount: result.summary.passed,
2887
- failedCount: result.summary.failed,
3335
+ completed: total,
3336
+ passedCount,
3337
+ failedCount,
2888
3338
  },
2889
3339
  };
2890
3340
  }
@@ -3289,6 +3739,27 @@ export async function runTestRun(opts, deps = {}) {
3289
3739
  catch (err) {
3290
3740
  if (err instanceof TimeoutError) {
3291
3741
  ticker.finalize(`Run ${triggerResponse.runId} — timed out after ${opts.timeoutSeconds}s`);
3742
+ // Mirror the RequestTimeoutError path: emit a partial run to stdout so
3743
+ // JSON consumers and AI agents can grab the runId and chain into
3744
+ // `testsprite test wait <runId>` without parsing the stderr error envelope.
3745
+ const timeoutPartial = {
3746
+ runId: triggerResponse.runId,
3747
+ status: 'running',
3748
+ enqueuedAt: triggerResponse.enqueuedAt,
3749
+ codeVersion: triggerResponse.codeVersion,
3750
+ targetUrl: triggerResponse.targetUrl || null,
3751
+ };
3752
+ printRunOrChain(out, timeoutPartial, opts.createContext, data => {
3753
+ const p = data;
3754
+ const lines = [
3755
+ `runId ${p.runId}`,
3756
+ `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
3757
+ ];
3758
+ if (p.targetUrl)
3759
+ lines.push(`targetUrl ${p.targetUrl}`);
3760
+ lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
3761
+ return lines.join('\n');
3762
+ });
3292
3763
  throw ApiError.fromEnvelope({
3293
3764
  error: {
3294
3765
  code: 'UNSUPPORTED', // exit 7 per errors.md
@@ -3358,6 +3829,178 @@ export async function runTestRun(opts, deps = {}) {
3358
3829
  }
3359
3830
  return finalRun;
3360
3831
  }
3832
+ /**
3833
+ * `test wait <run-id...>` with two or more ids: attach to N already-dispatched
3834
+ * runs in ONE invocation. This closes the loop the CLI itself opens: every
3835
+ * batch/closure timeout prints one `testsprite test wait <runId>` hint PER
3836
+ * member, which previously meant N sequential blocking invocations. The runs
3837
+ * are polled concurrently under a bounded pool with ONE shared deadline
3838
+ * (`--timeout` bounds the whole invocation, not each member), each member's
3839
+ * poll is total (a transient error on one run never discards the others), and
3840
+ * the exit code is the worst status across members: auth errors escalate to
3841
+ * exit 3, any timeout or poll error exits 7, any non-passed terminal exits 1.
3842
+ * Distinct from a run journal (issue #80): no persistence, just N known ids.
3843
+ */
3844
+ export async function runTestWaitMany(opts, deps = {}) {
3845
+ const out = makeOutput(opts.output, deps);
3846
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
3847
+ if (opts.dryRun) {
3848
+ emitDryRunBanner(stderrFn);
3849
+ const results = opts.runIds.map(runId => ({
3850
+ runId,
3851
+ status: 'passed',
3852
+ }));
3853
+ const payload = {
3854
+ results,
3855
+ summary: { total: results.length, passed: results.length, failed: 0, timedOut: 0, errors: 0 },
3856
+ };
3857
+ out.print(payload, () => results.map(r => `${r.runId} ${r.status}`).join('\n'));
3858
+ return payload;
3859
+ }
3860
+ const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
3861
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
3862
+ // One shared deadline across every member (the whole point of the shared
3863
+ // pool: `--timeout 600` means the invocation ends within ~600s, not
3864
+ // 600s x ceil(N/concurrency)).
3865
+ const deadlineMs = Date.now() + opts.timeoutSeconds * 1000;
3866
+ const pollOne = async (runId) => {
3867
+ // A member dequeued AFTER the shared deadline has passed must not be
3868
+ // granted a fresh minimum poll window (with --max-concurrency 1 that
3869
+ // would extend the invocation by ~1s per queued run past --timeout).
3870
+ const remainingSeconds = Math.ceil((deadlineMs - Date.now()) / 1000);
3871
+ if (remainingSeconds <= 0)
3872
+ return { kind: 'timeout' };
3873
+ const resolveAlternate = makeBackendWaitFallback({
3874
+ client,
3875
+ resolveTestId: run => run.testId,
3876
+ resolveNotBefore: run => run.createdAt,
3877
+ onResolved: () => undefined,
3878
+ });
3879
+ try {
3880
+ const run = await pollRunUntilTerminal(client, runId, {
3881
+ timeoutSeconds: remainingSeconds,
3882
+ sleep: deps.sleep,
3883
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
3884
+ onTick: (run, elapsedMs) => {
3885
+ const elapsed = Math.round(elapsedMs / 1000);
3886
+ ticker.update(`Run ${run.runId} — ${run.status} (elapsed=${elapsed}s)`);
3887
+ },
3888
+ resolveAlternate,
3889
+ });
3890
+ return { kind: 'result', run };
3891
+ }
3892
+ catch (err) {
3893
+ if (err instanceof TimeoutError)
3894
+ return { kind: 'timeout' };
3895
+ if (err instanceof RequestTimeoutError)
3896
+ throw err;
3897
+ if (err instanceof ApiError)
3898
+ return { kind: 'error', code: err.code, exitCode: err.exitCode };
3899
+ return { kind: 'error', code: 'TRANSPORT', exitCode: 10 };
3900
+ }
3901
+ };
3902
+ const outcomes = new Map();
3903
+ let inFlight = 0;
3904
+ let nextIdx = 0;
3905
+ try {
3906
+ await new Promise((resolve, reject) => {
3907
+ const startNext = () => {
3908
+ while (inFlight < opts.maxConcurrency && nextIdx < opts.runIds.length) {
3909
+ const runId = opts.runIds[nextIdx++];
3910
+ inFlight++;
3911
+ pollOne(runId)
3912
+ .then(outcome => {
3913
+ outcomes.set(runId, outcome);
3914
+ inFlight--;
3915
+ startNext();
3916
+ if (inFlight === 0 && nextIdx >= opts.runIds.length)
3917
+ resolve();
3918
+ })
3919
+ // pollOne is total except for RequestTimeoutError (handled below).
3920
+ .catch(reject);
3921
+ }
3922
+ };
3923
+ startNext();
3924
+ if (opts.runIds.length === 0)
3925
+ resolve();
3926
+ });
3927
+ }
3928
+ catch (fanOutErr) {
3929
+ if (fanOutErr instanceof RequestTimeoutError) {
3930
+ // Same contract as the batch pollers: leave stdout parseable before
3931
+ // exiting 7. Members that already settled keep their real status; only
3932
+ // the still-unfinished ids are marked running and named in the hint
3933
+ // (re-attaching to an already-terminal run would be a wasted command).
3934
+ ticker.finalize('Multi-run wait — request timed out');
3935
+ const partial = {
3936
+ results: opts.runIds.map((runId) => {
3937
+ const outcome = outcomes.get(runId);
3938
+ if (outcome === undefined)
3939
+ return { runId, status: 'running' };
3940
+ if (outcome.kind === 'timeout')
3941
+ return { runId, status: 'timeout' };
3942
+ if (outcome.kind === 'error')
3943
+ return { runId, status: `error:${outcome.code}` };
3944
+ return { runId, status: outcome.run.status, testId: outcome.run.testId };
3945
+ }),
3946
+ summary: { total: opts.runIds.length },
3947
+ };
3948
+ out.print(partial, () => partial.results.map(r => `${r.runId} ${r.status}`).join('\n'));
3949
+ const unfinished = partial.results
3950
+ .filter(r => r.status === 'running' || r.status === 'timeout')
3951
+ .map(r => r.runId);
3952
+ if (unfinished.length > 0) {
3953
+ stderrFn(`Re-attach with: testsprite test wait ${unfinished.join(' ')}`);
3954
+ }
3955
+ }
3956
+ throw fanOutErr;
3957
+ }
3958
+ ticker.finalize();
3959
+ const results = opts.runIds.map(runId => {
3960
+ const outcome = outcomes.get(runId);
3961
+ if (outcome === undefined || outcome.kind === 'timeout')
3962
+ return { runId, status: 'timeout' };
3963
+ if (outcome.kind === 'error')
3964
+ return { runId, status: `error:${outcome.code}` };
3965
+ return { runId, status: outcome.run.status, testId: outcome.run.testId };
3966
+ });
3967
+ const passed = results.filter(r => r.status === 'passed').length;
3968
+ const timedOut = results.filter(r => r.status === 'timeout').length;
3969
+ const errors = results.filter(r => r.status.startsWith('error:')).length;
3970
+ const failed = results.length - passed - timedOut - errors;
3971
+ const payload = {
3972
+ results,
3973
+ summary: { total: results.length, passed, failed, timedOut, errors },
3974
+ };
3975
+ out.print(payload, () => [
3976
+ ...results.map(r => `${r.runId} ${r.status}`),
3977
+ '',
3978
+ `${passed}/${results.length} passed, ${failed} failed/blocked, ${timedOut} timed out, ${errors} poll errors`,
3979
+ ].join('\n'));
3980
+ // Every member that did not reach a terminal verdict is re-attachable:
3981
+ // timeouts (still running server-side) and poll errors (e.g. a transient
3982
+ // transport failure) both belong in the hint; terminal runs do not.
3983
+ const unfinishedIds = results
3984
+ .filter(r => r.status === 'timeout' || r.status.startsWith('error:'))
3985
+ .map(r => r.runId);
3986
+ if (unfinishedIds.length > 0) {
3987
+ stderrFn(`Re-attach with: testsprite test wait ${unfinishedIds.join(' ')}`);
3988
+ }
3989
+ // Worst-status exit: auth escalates (a rejected key fails every member the
3990
+ // same way), then timeout/poll-error (7, resumable), then plain failure (1).
3991
+ const authError = [...outcomes.values()].find(o => o.kind === 'error' &&
3992
+ (o.code === 'AUTH_REQUIRED' || o.code === 'AUTH_INVALID' || o.code === 'AUTH_FORBIDDEN'));
3993
+ if (authError !== undefined && authError.kind === 'error') {
3994
+ throw new CLIError(`Multi-run wait: authentication failed (${authError.code})`, authError.exitCode);
3995
+ }
3996
+ if (timedOut > 0 || errors > 0) {
3997
+ throw new CLIError(`Multi-run wait: ${timedOut} timed out, ${errors} poll error(s) out of ${results.length} runs`, 7);
3998
+ }
3999
+ if (failed > 0) {
4000
+ throw new CLIError(`Multi-run wait: ${failed} run(s) finished non-passed`, 1);
4001
+ }
4002
+ return payload;
4003
+ }
3361
4004
  /**
3362
4005
  * `test wait <run-id>` — M3.3 piece-3.
3363
4006
  *
@@ -3418,6 +4061,18 @@ export async function runTestWait(opts, deps = {}) {
3418
4061
  catch (err) {
3419
4062
  if (err instanceof TimeoutError) {
3420
4063
  ticker.finalize(`Run ${opts.runId} — timed out after ${opts.timeoutSeconds}s`);
4064
+ // Mirror the RequestTimeoutError path: emit a partial run to stdout so
4065
+ // JSON consumers and AI agents can grab the runId and chain into
4066
+ // `testsprite test wait <runId>` without parsing the stderr error envelope.
4067
+ const timeoutPartial = { runId: opts.runId, status: 'running' };
4068
+ out.print(timeoutPartial, data => {
4069
+ const p = data;
4070
+ return [
4071
+ `runId ${p.runId}`,
4072
+ `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
4073
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
4074
+ ].join('\n');
4075
+ });
3421
4076
  throw ApiError.fromEnvelope({
3422
4077
  error: {
3423
4078
  code: 'UNSUPPORTED', // exit 7 per errors.md
@@ -3466,6 +4121,18 @@ export async function runTestWait(opts, deps = {}) {
3466
4121
  }
3467
4122
  return finalRun;
3468
4123
  }
4124
+ async function writeBatchJUnitReportIfRequested(opts, results) {
4125
+ if (opts.report !== 'junit' || opts.reportFile === undefined)
4126
+ return;
4127
+ const projectId = resolveBatchReportProjectId(opts, results);
4128
+ const suiteName = opts.reportSuiteName ?? `testsprite:${projectId}`;
4129
+ const xml = buildJUnitReport({
4130
+ suiteName,
4131
+ classname: projectId,
4132
+ results,
4133
+ });
4134
+ await writeJUnitReportFile(opts.reportFile, xml);
4135
+ }
3469
4136
  /**
3470
4137
  * `test run --all --project <id>` — M4 piece-2.
3471
4138
  *
@@ -3481,10 +4148,20 @@ export async function runTestRunAll(opts, deps = {}) {
3481
4148
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
3482
4149
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
3483
4150
  }
4151
+ assertJUnitReportOptions({
4152
+ report: opts.report,
4153
+ reportFile: opts.reportFile,
4154
+ reportSuiteName: opts.reportSuiteName,
4155
+ wait: opts.wait,
4156
+ batchPath: true,
4157
+ });
3484
4158
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
3485
4159
  const out = makeOutput(opts.output, deps);
3486
4160
  // --- Dry-run path ---
3487
4161
  if (opts.dryRun) {
4162
+ // DEV-247: this path returns before makeClient() fires the banner, so emit it
4163
+ // here — otherwise the canned sample can be mistaken for a live response.
4164
+ emitDryRunBanner(stderrFn);
3488
4165
  const idempotencyKey = opts.idempotencyKey ?? `dry-run-${randomUUID()}`;
3489
4166
  const batchRunSample = findSample('POST', '/api/cli/v1/tests/batch/run')?.body();
3490
4167
  const envelope = {
@@ -3499,6 +4176,9 @@ export async function runTestRunAll(opts, deps = {}) {
3499
4176
  idempotencyKey,
3500
4177
  ...(opts.wait ? { thenPoll: '/api/cli/v1/runs/<run-id>?waitSeconds=25' } : {}),
3501
4178
  };
4179
+ if (opts.report === 'junit' && opts.reportFile !== undefined) {
4180
+ await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(opts.projectId, opts.reportSuiteName));
4181
+ }
3502
4182
  out.print(batchRunSample ?? envelope);
3503
4183
  return undefined;
3504
4184
  }
@@ -3518,13 +4198,10 @@ export async function runTestRunAll(opts, deps = {}) {
3518
4198
  return dashboardUrl !== undefined ? { ...item, dashboardUrl } : item;
3519
4199
  };
3520
4200
  const idempotencyKey = opts.idempotencyKey ?? `cli-batch-run-fresh-${randomUUID()}`;
3521
- if (opts.idempotencyKey === undefined && opts.debug) {
4201
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
3522
4202
  stderrFn(`idempotency-key: ${idempotencyKey}`);
3523
4203
  }
3524
- if (opts.idempotencyKey === undefined && opts.verbose) {
3525
- stderrFn(`[verbose] auto-minted idempotency-key: ${idempotencyKey}`);
3526
- }
3527
- // Resolve testIds: fetch all BE tests in the project, apply --filter.
4204
+ // Resolve testIds: fetch all tests in the project, apply --filter.
3528
4205
  let testIds;
3529
4206
  if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
3530
4207
  // We need to resolve the full test set to apply the name filter.
@@ -3552,7 +4229,8 @@ export async function runTestRunAll(opts, deps = {}) {
3552
4229
  }
3553
4230
  stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${opts.projectId} for batch run.`);
3554
4231
  }
3555
- // When no --filter, omit testIds → server runs ALL BE tests in the project.
4232
+ // When no --filter, omit testIds → server runs ALL tests in the project
4233
+ // (BE tests on the legacy V2 wave engine; FE + BE on the V3 unified engine).
3556
4234
  const batchResp = await client.triggerBatchRunFresh({
3557
4235
  projectId: opts.projectId,
3558
4236
  ...(testIds !== undefined ? { testIds } : {}),
@@ -3742,7 +4420,20 @@ export async function runTestRunAll(opts, deps = {}) {
3742
4420
  // NOTE: batchDeadlineMs is set in the D3 deferred-retry loop above and reused here.
3743
4421
  async function pollFreshAccepted(entry) {
3744
4422
  const runId = entry.runId;
3745
- const remainingSeconds = Math.max(1, Math.ceil((batchDeadlineMs - Date.now()) / 1000));
4423
+ const remainingMs = batchDeadlineMs - Date.now();
4424
+ if (remainingMs <= 0) {
4425
+ return {
4426
+ testId: entry.testId,
4427
+ runId,
4428
+ status: 'timeout',
4429
+ error: {
4430
+ code: 'UNSUPPORTED',
4431
+ message: `Timed out after ${opts.timeoutSeconds}s`,
4432
+ exitCode: 7,
4433
+ },
4434
+ };
4435
+ }
4436
+ const remainingSeconds = Math.ceil(remainingMs / 1000);
3746
4437
  const resolveAlternate = makeBackendWaitFallback({
3747
4438
  client,
3748
4439
  resolveTestId: () => entry.testId,
@@ -3761,7 +4452,12 @@ export async function runTestRunAll(opts, deps = {}) {
3761
4452
  },
3762
4453
  resolveAlternate,
3763
4454
  });
3764
- return { testId: entry.testId, runId, status: finalRun.status };
4455
+ return {
4456
+ testId: entry.testId,
4457
+ runId,
4458
+ projectId: finalRun.projectId,
4459
+ status: finalRun.status,
4460
+ };
3765
4461
  }
3766
4462
  catch (err) {
3767
4463
  if (err instanceof TimeoutError) {
@@ -3776,6 +4472,22 @@ export async function runTestRunAll(opts, deps = {}) {
3776
4472
  },
3777
4473
  };
3778
4474
  }
4475
+ if (err instanceof RequestTimeoutError) {
4476
+ // Client-side per-request timeout during polling — classify as timeout
4477
+ // (exit 7) so the fan-out completes and stdout carries every runId.
4478
+ // Without this, RequestTimeoutError rejects the fan-out before out.print(),
4479
+ // leaving JSON consumers with empty stdout (mirrors create-batch --run).
4480
+ return {
4481
+ testId: entry.testId,
4482
+ runId,
4483
+ status: 'timeout',
4484
+ error: {
4485
+ code: 'UNSUPPORTED',
4486
+ message: err.message,
4487
+ exitCode: err.exitCode,
4488
+ },
4489
+ };
4490
+ }
3779
4491
  if (err instanceof ApiError) {
3780
4492
  // Preserve the real exit code + envelope (AUTH_INVALID=3, NOT_FOUND=4,
3781
4493
  // RATE_LIMITED=11, …) instead of flattening every member failure to 1
@@ -3836,6 +4548,7 @@ export async function runTestRunAll(opts, deps = {}) {
3836
4548
  total: pollable.length,
3837
4549
  },
3838
4550
  };
4551
+ await writeBatchJUnitReportIfRequested(opts, freshRunResults);
3839
4552
  out.print(jsonPayload);
3840
4553
  // Rate-deferred tests were never dispatched → the batch is incomplete (exit 7),
3841
4554
  // mirroring `test rerun --all`. Checked before the failed-run throw so the
@@ -3899,6 +4612,15 @@ export async function runTestRerun(opts, deps = {}) {
3899
4612
  if (opts.testIds.length === 0 && !opts.all) {
3900
4613
  throw localValidationError('test-ids', 'provide at least one <test-id>, or use --all to rerun all tests in the project');
3901
4614
  }
4615
+ // Explicit ids + --all is ambiguous: the --all branch resolves the FULL
4616
+ // project test set and overwrites the listed ids, so the user's narrowing
4617
+ // intent would be silently replaced by a whole-project batch rerun —
4618
+ // burning rerun/auto-heal credits. Reject early. (Mirrors `test run`'s
4619
+ // positional+--all guard and delete-batch's ids+--all data-loss guard.)
4620
+ if (opts.all && opts.testIds.length > 0) {
4621
+ throw localValidationError('test-ids', 'pass either explicit test IDs or --all, not both — --all reruns every test in the ' +
4622
+ 'project and would ignore the listed IDs. Drop the IDs, or drop --all.');
4623
+ }
3902
4624
  if (opts.all && !opts.projectId) {
3903
4625
  throw localValidationError('project', '--all requires a project context — pass --project <id> or configure a default');
3904
4626
  }
@@ -3911,12 +4633,31 @@ export async function runTestRerun(opts, deps = {}) {
3911
4633
  throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests get reran). ' +
3912
4634
  'Remove --filter, or add --all --project <id>.');
3913
4635
  }
4636
+ // --status and --skip-terminal are --all-only narrowing filters with the
4637
+ // same silent-ignore failure mode as --filter above: without --all the
4638
+ // explicit ids get reran unfiltered (and an invalid --status value is
4639
+ // never even validated). Reject both, mirroring the --filter guard.
4640
+ if (opts.statusFilter !== undefined && !opts.all) {
4641
+ throw localValidationError('status', '--status only applies with --all (it narrows which project tests get reran). ' +
4642
+ 'Remove --status, or add --all --project <id>.');
4643
+ }
4644
+ if (opts.skipTerminal && !opts.all) {
4645
+ throw localValidationError('skip-terminal', '--skip-terminal only applies with --all (it narrows which project tests get reran). ' +
4646
+ 'Remove --skip-terminal, or add --all --project <id>.');
4647
+ }
3914
4648
  if (!Number.isInteger(opts.maxConcurrency) ||
3915
4649
  opts.maxConcurrency < 1 ||
3916
4650
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
3917
4651
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
3918
4652
  }
3919
4653
  const isSingle = !opts.all && opts.testIds.length === 1;
4654
+ assertJUnitReportOptions({
4655
+ report: opts.report,
4656
+ reportFile: opts.reportFile,
4657
+ reportSuiteName: opts.reportSuiteName,
4658
+ wait: opts.wait,
4659
+ batchPath: !isSingle,
4660
+ });
3920
4661
  // -------------------------------------------------------------------------
3921
4662
  // Pre-flight: auto-heal + Free-tier hint (best-effort, non-blocking)
3922
4663
  // -------------------------------------------------------------------------
@@ -3955,6 +4696,10 @@ export async function runTestRerun(opts, deps = {}) {
3955
4696
  idempotencyKey,
3956
4697
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
3957
4698
  };
4699
+ if (opts.report === 'junit' && opts.reportFile !== undefined) {
4700
+ const projectKey = resolveBatchReportProjectId(opts, []);
4701
+ await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(projectKey, opts.reportSuiteName));
4702
+ }
3958
4703
  out.print(findSample('POST', '/api/cli/v1/tests/batch/rerun')?.body() ?? envelope);
3959
4704
  }
3960
4705
  void client;
@@ -3964,12 +4709,9 @@ export async function runTestRerun(opts, deps = {}) {
3964
4709
  // slow rerun trigger / long-poll under load isn't cut at the 120s default.
3965
4710
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
3966
4711
  const idempotencyKey = opts.idempotencyKey ?? `cli-rerun-${randomUUID()}`;
3967
- if (opts.idempotencyKey === undefined && opts.debug) {
4712
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
3968
4713
  stderrFn(`idempotency-key: ${idempotencyKey}`);
3969
4714
  }
3970
- if (opts.idempotencyKey === undefined && opts.verbose) {
3971
- stderrFn(`[verbose] auto-minted idempotency-key: ${idempotencyKey}`);
3972
- }
3973
4715
  // -------------------------------------------------------------------------
3974
4716
  // Single rerun path
3975
4717
  // -------------------------------------------------------------------------
@@ -4430,15 +5172,32 @@ export async function runTestRerun(opts, deps = {}) {
4430
5172
  chunks.push([]); // defensive: empty list handled above
4431
5173
  let chunkResponses;
4432
5174
  try {
4433
- chunkResponses = await Promise.all(chunks.map((chunk, idx) => {
4434
- const chunkKey = chunks.length === 1 ? idempotencyKey : `${idempotencyKey}:chunk${idx}`;
4435
- return client.triggerBatchRerun({
5175
+ // Dispatch chunks one at a time, NOT via Promise.all. BE producer/
5176
+ // teardown closure dedup happens per-request, server-side. Two chunks
5177
+ // that share a project's producer fired concurrently can each decide
5178
+ // independently "this producer hasn't been added yet" and both trigger
5179
+ // it, double-running the producer. Sequential dispatch closes that
5180
+ // race: by the time chunk N is sent, chunk N-1's trigger has already
5181
+ // landed server-side for it to dedup against.
5182
+ chunkResponses = [];
5183
+ for (let idx = 0; idx < chunks.length; idx++) {
5184
+ const chunk = chunks[idx];
5185
+ // Bound the per-chunk idempotency key to <=256 chars (mirrors the retry
5186
+ // path). A long base key plus the `:chunkN` suffix could otherwise exceed
5187
+ // the server cap and be rejected or truncated inconsistently.
5188
+ const chunkSuffix = chunks.length === 1 ? '' : `:chunk${idx}`;
5189
+ const chunkBase = chunkSuffix.length > 0 && idempotencyKey.length + chunkSuffix.length > 256
5190
+ ? idempotencyKey.slice(0, 256 - chunkSuffix.length)
5191
+ : idempotencyKey;
5192
+ const chunkKey = `${chunkBase}${chunkSuffix}`;
5193
+ const chunkResp = await client.triggerBatchRerun({
4436
5194
  source: 'cli',
4437
5195
  testIds: chunk,
4438
5196
  ...(effectiveAutoHeal ? { autoHeal: true } : {}),
4439
5197
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
4440
5198
  }, { idempotencyKey: chunkKey });
4441
- }));
5199
+ chunkResponses.push(chunkResp);
5200
+ }
4442
5201
  }
4443
5202
  catch (err) {
4444
5203
  // D2 (dogfood): the batch endpoint rejects the WHOLE request when any id is
@@ -4461,12 +5220,21 @@ export async function runTestRerun(opts, deps = {}) {
4461
5220
  throw err;
4462
5221
  }
4463
5222
  // Aggregate chunk responses into a single synthetic BatchRerunResponse.
5223
+ // `accepted` is deduped by testId (defense in depth: even with sequential
5224
+ // dispatch above, a shared producer/teardown should never be reported, or
5225
+ // polled under --wait, more than once) and `closure.byProject` entries
5226
+ // sharing a projectId are merged rather than left as separate per-chunk
5227
+ // entries.
5228
+ const { deduped: dedupedAccepted, droppedCount: duplicateAcceptedCount } = dedupeBatchRerunAccepted(chunkResponses.flatMap(r => r.accepted));
5229
+ if (duplicateAcceptedCount > 0) {
5230
+ stderrFn(`[warn] ${duplicateAcceptedCount} test${duplicateAcceptedCount !== 1 ? 's were' : ' was'} triggered more than once across chunked batch-rerun requests (shared BE producer/teardown); kept the first run, ignored the rest.`);
5231
+ }
4464
5232
  const batchResp = {
4465
- accepted: chunkResponses.flatMap(r => r.accepted),
5233
+ accepted: dedupedAccepted,
4466
5234
  deferred: chunkResponses.flatMap(r => r.deferred),
4467
5235
  conflicts: chunkResponses.flatMap(r => r.conflicts),
4468
5236
  closure: {
4469
- byProject: chunkResponses.flatMap(r => r.closure.byProject),
5237
+ byProject: mergeBatchRerunClosureByProject(chunkResponses.flatMap(r => r.closure.byProject)),
4470
5238
  },
4471
5239
  notFound: chunkResponses.flatMap(r => r.notFound ?? []),
4472
5240
  };
@@ -4545,7 +5313,12 @@ export async function runTestRerun(opts, deps = {}) {
4545
5313
  }
4546
5314
  let retryChunkResponses;
4547
5315
  try {
4548
- retryChunkResponses = await Promise.all(retryChunks.map((chunk, idx) => {
5316
+ // Sequential, same reason as the initial dispatch above: concurrent
5317
+ // chunks racing on per-request server-side closure dedup can
5318
+ // double-trigger a shared BE producer/teardown.
5319
+ retryChunkResponses = [];
5320
+ for (let idx = 0; idx < retryChunks.length; idx++) {
5321
+ const chunk = retryChunks[idx];
4549
5322
  // [P2] Bound the derived key to ≤256 chars. Caller-supplied keys may
4550
5323
  // be up to 256 chars; appending the suffix could exceed the server
4551
5324
  // limit and cause every retry to be rejected. Truncate the base key
@@ -4557,19 +5330,20 @@ export async function runTestRerun(opts, deps = {}) {
4557
5330
  ? idempotencyKey.slice(0, 256 - retrySuffix.length)
4558
5331
  : idempotencyKey;
4559
5332
  const retryKey = `${retryBase}${retrySuffix}`;
4560
- return client.triggerBatchRerun({
5333
+ const retryChunkResp = await client.triggerBatchRerun({
4561
5334
  source: 'cli',
4562
5335
  testIds: chunk,
4563
5336
  ...(effectiveAutoHeal ? { autoHeal: true } : {}),
4564
5337
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
4565
5338
  }, { idempotencyKey: retryKey });
4566
- }));
5339
+ retryChunkResponses.push(retryChunkResp);
5340
+ }
4567
5341
  }
4568
5342
  catch (err) {
4569
5343
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
4570
5344
  break;
4571
5345
  }
4572
- const newlyAccepted = retryChunkResponses.flatMap(r => r.accepted);
5346
+ const { deduped: newlyAccepted, droppedCount: newlyDuplicateCount } = dedupeBatchRerunAccepted(retryChunkResponses.flatMap(r => r.accepted));
4573
5347
  const newlyDeferred = retryChunkResponses.flatMap(r => r.deferred);
4574
5348
  const newlyConflicted = retryChunkResponses.flatMap(r => r.conflicts);
4575
5349
  // [P2] Collect notFound[] from the retry response. A deferred test may be
@@ -4577,9 +5351,12 @@ export async function runTestRerun(opts, deps = {}) {
4577
5351
  // into the running notFound set and remove from deferred so it isn't
4578
5352
  // reported as "resolved" in the final output.
4579
5353
  const newlyNotFound = retryChunkResponses.flatMap(r => r.notFound ?? []);
5354
+ if (newlyDuplicateCount > 0) {
5355
+ stderrFn(`[warn] ${newlyDuplicateCount} test${newlyDuplicateCount !== 1 ? 's were' : ' was'} triggered more than once across deferred-retry chunked requests (shared BE producer/teardown); kept the first run, ignored the rest.`);
5356
+ }
4580
5357
  if (newlyAccepted.length > 0) {
4581
5358
  stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyAccepted.length} test${newlyAccepted.length !== 1 ? 's' : ''} now accepted.`);
4582
- accepted = accepted.concat(newlyAccepted);
5359
+ accepted = dedupeBatchRerunAccepted(accepted.concat(newlyAccepted)).deduped;
4583
5360
  }
4584
5361
  if (newlyConflicted.length > 0) {
4585
5362
  // [P1] Merge retry-returned conflicts into the running conflicts collection
@@ -4690,7 +5467,12 @@ export async function runTestRerun(opts, deps = {}) {
4690
5467
  },
4691
5468
  resolveAlternate,
4692
5469
  });
4693
- return { testId: entry.testId, runId: entry.runId, status: finalRun.status };
5470
+ return {
5471
+ testId: entry.testId,
5472
+ runId: entry.runId,
5473
+ projectId: finalRun.projectId,
5474
+ status: finalRun.status,
5475
+ };
4694
5476
  }
4695
5477
  catch (err) {
4696
5478
  if (err instanceof TimeoutError) {
@@ -4705,12 +5487,31 @@ export async function runTestRerun(opts, deps = {}) {
4705
5487
  },
4706
5488
  };
4707
5489
  }
5490
+ if (err instanceof RequestTimeoutError) {
5491
+ // Client-side per-request timeout during polling — classify as timeout
5492
+ // (exit 7) so the fan-out completes and stdout carries every runId.
5493
+ // Without this, RequestTimeoutError rejects the fan-out before out.print(),
5494
+ // leaving JSON consumers with empty stdout (mirrors create-batch --run).
5495
+ return {
5496
+ testId: entry.testId,
5497
+ runId: entry.runId,
5498
+ status: 'timeout',
5499
+ error: {
5500
+ code: 'UNSUPPORTED',
5501
+ message: err.message,
5502
+ exitCode: err.exitCode,
5503
+ },
5504
+ };
5505
+ }
4708
5506
  if (err instanceof ApiError) {
5507
+ // Preserve the real exit code (AUTH_INVALID=3, RATE_LIMITED=11, …) so the
5508
+ // batch exit-code aggregator can escalate auth failures correctly. Mirroring
5509
+ // the identical fix already applied to runTestRunAll's pollFreshAccepted.
4709
5510
  return {
4710
5511
  testId: entry.testId,
4711
5512
  runId: entry.runId,
4712
5513
  status: 'error',
4713
- error: { code: err.code, message: err.message, exitCode: 1 },
5514
+ error: { code: err.code, message: err.message, exitCode: err.exitCode },
4714
5515
  };
4715
5516
  }
4716
5517
  throw err;
@@ -4773,6 +5574,7 @@ export async function runTestRerun(opts, deps = {}) {
4773
5574
  total: accepted.length,
4774
5575
  },
4775
5576
  };
5577
+ await writeBatchJUnitReportIfRequested(opts, rerunResults);
4776
5578
  out.print(jsonPayload);
4777
5579
  // Determine exit code: timeout (deferred or any timeout) → 7; any fail → 1; all pass → 0
4778
5580
  if (deferred.length > 0 || timedOut > 0) {
@@ -4802,6 +5604,14 @@ export async function runTestRerun(opts, deps = {}) {
4802
5604
  });
4803
5605
  }
4804
5606
  if (failed > 0) {
5607
+ // Auth failure on any member is a batch-wide condition — the credential is
5608
+ // bad, not the test. Propagate exit 3 so the operator fixes auth rather than
5609
+ // chasing a "rerun failed" (exit 1). Mirrors the identical logic already
5610
+ // applied to runTestRunAll lines 5462-5468.
5611
+ const authErr = rerunResults.find(r => r.error?.exitCode === 3);
5612
+ if (authErr) {
5613
+ throw new CLIError(`${failed} rerun${failed !== 1 ? 's' : ''} failed — auth error (${authErr.error?.code}): ${authErr.error?.message}`, 3);
5614
+ }
4805
5615
  throw new CLIError(`${failed} rerun${failed !== 1 ? 's' : ''} failed.`, 1);
4806
5616
  }
4807
5617
  // [P2] Return post-retry state including merged notFound so callers see the
@@ -4810,6 +5620,19 @@ export async function runTestRerun(opts, deps = {}) {
4810
5620
  // outcome printed to stdout and is not part of the returned shape).
4811
5621
  return { ...batchResp, accepted, deferred, conflicts, notFound };
4812
5622
  }
5623
+ export function resolveDefaultArtifactDir(runId, cwd = process.cwd()) {
5624
+ requireNonEmpty('run-id', runId);
5625
+ const windowsNormalizedSegment = runId.replace(/[ .]+$/u, '');
5626
+ if (windowsNormalizedSegment === '' ||
5627
+ windowsNormalizedSegment === '.' ||
5628
+ windowsNormalizedSegment === '..' ||
5629
+ runId.includes('/') ||
5630
+ runId.includes('\\') ||
5631
+ runId.includes('\0')) {
5632
+ throw localValidationError('run-id', 'must be a single path-safe segment for the default output directory; pass --out <dir> to choose a custom path');
5633
+ }
5634
+ return join(cwd, '.testsprite', 'runs', runId);
5635
+ }
4813
5636
  /**
4814
5637
  * Validate that the parent directory of `resolvedDir` exists and is a
4815
5638
  * directory. Surfaces `VALIDATION_ERROR` (exit 5) — matches the convention
@@ -4857,12 +5680,9 @@ export async function assertOutDirParentExists(resolvedDir) {
4857
5680
  */
4858
5681
  export async function runArtifactGet(opts, deps = {}) {
4859
5682
  const out = makeOutput(opts.output, deps);
4860
- const client = makeClient(opts, deps);
4861
5683
  const { runId } = opts;
4862
5684
  // Resolve output dir: explicit --out or the default .testsprite/runs/<runId>/
4863
- const resolvedDir = opts.out !== undefined
4864
- ? resolveBundleDir(opts.out)
4865
- : join(process.cwd(), '.testsprite', 'runs', runId);
5685
+ const resolvedDir = opts.out !== undefined ? resolveBundleDir(opts.out) : resolveDefaultArtifactDir(runId);
4866
5686
  // --dry-run: no network, no disk write.
4867
5687
  // The client (makeClient) is already wired with createDryRunFetch() when
4868
5688
  // dryRun: true, so a real call to client.get() would return the canned
@@ -4901,6 +5721,7 @@ export async function runArtifactGet(opts, deps = {}) {
4901
5721
  if (opts.out !== undefined) {
4902
5722
  await assertOutDirParentExists(resolvedDir);
4903
5723
  }
5724
+ const client = makeClient(opts, deps);
4904
5725
  // Fetch the run-scoped failure bundle.
4905
5726
  const { body: context, requestId: fetchRequestId } = await client.getWithMeta(`/runs/${encodeURIComponent(runId)}/failure`);
4906
5727
  // §3 atomicity invariants — run-scoped path requires runId to be present.
@@ -5146,6 +5967,25 @@ export function createTestCommand(deps = {}) {
5146
5967
  idempotencyKey: cmdOpts.idempotencyKey,
5147
5968
  }, deps);
5148
5969
  });
5970
+ test
5971
+ .command('scaffold')
5972
+ .description('Emit a schema-correct starter test definition (frontend plan JSON by default, or a backend Python skeleton). Pure-local: no network, no credentials.')
5973
+ .option('--type <type>', 'frontend|backend (default: frontend)')
5974
+ .option('--out <path>', 'write the scaffold to a file instead of stdout')
5975
+ .option('--force', 'overwrite an existing --out file', false)
5976
+ .addHelpText('after', '\nExamples:\n' +
5977
+ ' testsprite test scaffold > first-test.plan.json\n' +
5978
+ ' testsprite test scaffold --type backend --out tests/health.py\n' +
5979
+ ' testsprite test scaffold --out plan.json # then edit, and create with --plan-from plan.json')
5980
+ .addHelpText('after', GLOBAL_OPTS_HINT)
5981
+ .action(async (cmdOpts, command) => {
5982
+ await runScaffold({
5983
+ ...resolveCommonOptions(command),
5984
+ scaffoldType: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES) ?? 'frontend',
5985
+ out: cmdOpts.out,
5986
+ force: cmdOpts.force === true,
5987
+ }, deps);
5988
+ });
5149
5989
  test
5150
5990
  .command('steps <test-id>')
5151
5991
  .description('List the steps for a test (server returns the cumulative log across every run; use --run-id to scope to one run)')
@@ -5164,6 +6004,30 @@ export function createTestCommand(deps = {}) {
5164
6004
  runId: cmdOpts.runId,
5165
6005
  }, deps);
5166
6006
  });
6007
+ test
6008
+ .command('diff <run-a> <run-b>')
6009
+ .description('Compare two runs and print what regressed: verdict, failureKind, failedStepIndex, per-step status flips, codeVersion drift. Exit 0 when verdicts match, 1 when they differ.')
6010
+ .addHelpText('after', GLOBAL_OPTS_HINT)
6011
+ .action(async (runA, runB, _cmdOpts, command) => {
6012
+ await runDiff({ ...resolveCommonOptions(command), runA, runB }, deps);
6013
+ });
6014
+ test
6015
+ .command('lint')
6016
+ .description('Validate plan/steps files offline with the same validators `create` runs, collecting EVERY problem. No network, no credentials. Exit 0 when all valid, 5 otherwise.')
6017
+ .option('--plan-from <file>', 'single plan JSON file')
6018
+ .option('--plan-from-dir <dir>', 'directory of *.json plan files (each checked, all errors reported)')
6019
+ .option('--plans <file>', 'JSONL file with one plan spec per line (each line checked)')
6020
+ .option('--steps <file>', 'plan-steps JSON file (the shape `test plan put` ingests)')
6021
+ .addHelpText('after', GLOBAL_OPTS_HINT)
6022
+ .action(async (cmdOpts, command) => {
6023
+ await runLint({
6024
+ ...resolveCommonOptions(command),
6025
+ planFrom: cmdOpts.planFrom,
6026
+ planFromDir: cmdOpts.planFromDir,
6027
+ plans: cmdOpts.plans,
6028
+ steps: cmdOpts.steps,
6029
+ }, deps);
6030
+ });
5167
6031
  test
5168
6032
  .command('result <test-id>')
5169
6033
  .description('Get the latest result for a test (default) or list prior runs (--history).\n' +
@@ -5268,7 +6132,7 @@ export function createTestCommand(deps = {}) {
5268
6132
  test
5269
6133
  .command('run [test-id]')
5270
6134
  .description('Trigger a test run. With --wait, polls until terminal status.\n' +
5271
- 'Use --all --project <id> for a wave-ordered batch run of all BE tests (M4).\n' +
6135
+ 'Use --all --project <id> for a wave-ordered batch run of all tests in a project (M4).\n' +
5272
6136
  '\nExit codes:\n' +
5273
6137
  ' 0 passed (or queued without --wait)\n' +
5274
6138
  ' 1 failed / blocked / cancelled\n' +
@@ -5284,15 +6148,22 @@ export function createTestCommand(deps = {}) {
5284
6148
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
5285
6149
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
5286
6150
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
5287
- .option('--all', 'run all BE tests in the project (wave-ordered fresh run; requires --project). Mutually exclusive with <test-id>.', false)
6151
+ .option('--all', 'run all tests in the project (wave-ordered fresh run; requires --project). Mutually exclusive with <test-id>.', false)
5288
6152
  .option('--project <id>', 'project id (required with --all; returned by `testsprite project list`)')
5289
6153
  .option('--filter <substr>', 'with --all: only run tests whose name contains this substring (case-insensitive)')
5290
6154
  .option('--max-concurrency <n>', `with --all --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
6155
+ .option('--report <format>', 'with --all --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
6156
+ .option('--report-file <path>', 'output path for --report (atomic write)')
6157
+ .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
5291
6158
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
5292
- ' testsprite test run --all --project <id> run all BE tests in wave order\n' +
6159
+ ' testsprite test run --all --project <id> run all project tests in wave order\n' +
5293
6160
  ' testsprite test run --all --project <id> --filter <substr> name-glob subset\n' +
6161
+ ' testsprite test run --all --project <id> --wait --report junit --report-file ./results.xml\n' +
5294
6162
  '\nBE tests can declare --produces/--needs at create time to drive wave ordering\n' +
5295
- '(see `testsprite test create --help` for details).')
6163
+ '(see `testsprite test create --help` for details).\n' +
6164
+ '\nFrontend tests: the current unified engine runs FE tests too (they are billed\n' +
6165
+ 'like any run). On the legacy backend-only engine FE tests cannot run — they are\n' +
6166
+ "reported under skippedFrontend with an advisory; run those with 'test run <id>'.")
5296
6167
  .addHelpText('after', GLOBAL_OPTS_HINT)
5297
6168
  .action(async (testIdArg, cmdOpts, command) => {
5298
6169
  const isAll = cmdOpts.all === true;
@@ -5301,7 +6172,7 @@ export function createTestCommand(deps = {}) {
5301
6172
  throw localValidationError('test-id', 'positional <test-id> and --all are mutually exclusive; use one or the other');
5302
6173
  }
5303
6174
  if (testIdArg === undefined && !isAll) {
5304
- throw localValidationError('test-id', 'provide a <test-id>, or use --all --project <id> to run all BE tests in a project');
6175
+ throw localValidationError('test-id', 'provide a <test-id>, or use --all --project <id> to run all tests in a project');
5305
6176
  }
5306
6177
  // --filter is an --all-only narrowing flag (mirrors `test rerun --filter`).
5307
6178
  // Without --all it would be SILENTLY ignored while the explicit <test-id>
@@ -5309,17 +6180,27 @@ export function createTestCommand(deps = {}) {
5309
6180
  if (cmdOpts.filter !== undefined && cmdOpts.filter !== '' && !isAll) {
5310
6181
  throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests run). Remove --filter, or add --all --project <id>.');
5311
6182
  }
6183
+ const report = parseJUnitReportFormat(cmdOpts.report);
6184
+ assertJUnitReportOptions({
6185
+ report,
6186
+ reportFile: cmdOpts.reportFile,
6187
+ reportSuiteName: cmdOpts.reportSuiteName,
6188
+ wait: cmdOpts.wait === true,
6189
+ batchPath: isAll,
6190
+ });
5312
6191
  if (isAll) {
5313
6192
  // --all path: wave-ordered fresh batch run.
5314
6193
  if (!cmdOpts.project) {
5315
6194
  throw localValidationError('project', '--all requires a project id — pass --project <id>');
5316
6195
  }
5317
- // --target-url has no effect on the --all batch path: it is BE-only
5318
- // (FE tests are skipped server-side) and a BE test's base URL is baked
5319
- // into its code. Silently dropping it could run the suite against an
5320
- // unintended environment in the caller's mind — reject loudly instead.
6196
+ // --target-url has no effect on the --all batch path: a BE test's base
6197
+ // URL is baked into its code, and the unified engine resolves each
6198
+ // project's configured environment server-side (per-run URL overrides
6199
+ // are not applied to batch FE runs either). Silently dropping it could
6200
+ // run the suite against an unintended environment in the caller's mind
6201
+ // — reject loudly instead.
5321
6202
  if (cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
5322
- throw localValidationError('target-url', '--target-url has no effect with --all (the batch path is the BE-only wave engine; a BE test’s URL is baked into its code). Remove --target-url.');
6203
+ throw localValidationError('target-url', '--target-url has no effect with --all (the batch path does not apply a per-run URL override — BE test URLs are baked into their code and the unified engine resolves the project environment server-side). Remove --target-url.');
5323
6204
  }
5324
6205
  await runTestRunAll({
5325
6206
  ...resolveCommonOptions(command),
@@ -5330,6 +6211,9 @@ export function createTestCommand(deps = {}) {
5330
6211
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
5331
6212
  DEFAULT_BATCH_RUN_CONCURRENCY,
5332
6213
  idempotencyKey: cmdOpts.idempotencyKey,
6214
+ report,
6215
+ reportFile: cmdOpts.reportFile,
6216
+ reportSuiteName: cmdOpts.reportSuiteName,
5333
6217
  }, deps);
5334
6218
  return;
5335
6219
  }
@@ -5346,23 +6230,44 @@ export function createTestCommand(deps = {}) {
5346
6230
  }, deps);
5347
6231
  });
5348
6232
  test
5349
- .command('wait <run-id>')
5350
- .description('Wait for a run to reach a terminal status.\n' +
6233
+ .command('wait <run-id...>')
6234
+ .description('Wait for one or more runs to reach a terminal status.\n' +
6235
+ '\nWith several run-ids the runs are polled concurrently under one shared\n' +
6236
+ '--timeout and a {results, summary} envelope is printed (worst status wins\n' +
6237
+ 'the exit code), so every re-attach hint the CLI prints can be pasted as\n' +
6238
+ 'ONE command.\n' +
5351
6239
  '\nExit codes:\n' +
5352
6240
  ' 0 passed\n' +
5353
6241
  ' 1 failed / blocked / cancelled\n' +
5354
6242
  ' 3 auth error\n' +
5355
- ' 4 run not found\n' +
5356
- ' 7 timeout — resume with: testsprite test wait <run-id>\n' +
6243
+ ' 4 run not found (single run-id; with several ids a per-member poll error\n' +
6244
+ ' is recorded as error:<CODE> in its row and folded into exit 7)\n' +
6245
+ ' 7 timeout or per-member poll error — resume with: testsprite test wait <run-id...>\n' +
5357
6246
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
5358
6247
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>')
5359
6248
  .option('--timeout <s>', `max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6249
+ .option('--max-concurrency <n>', 'with several run-ids, max concurrent polls (1-100, default: 10)')
5360
6250
  .addHelpText('after', GLOBAL_OPTS_HINT)
5361
- .action(async (runId, cmdOpts, command) => {
5362
- await runTestWait({
6251
+ .action(async (runIds, cmdOpts, command) => {
6252
+ // One id keeps the historical single-run path byte-identical (same
6253
+ // output shape, same exit codes); two or more fan out.
6254
+ if (runIds.length === 1) {
6255
+ await runTestWait({
6256
+ ...resolveCommonOptions(command),
6257
+ runId: runIds[0],
6258
+ timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
6259
+ }, deps);
6260
+ return;
6261
+ }
6262
+ const maxConcurrency = parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ?? 10;
6263
+ if (!Number.isInteger(maxConcurrency) || maxConcurrency < 1 || maxConcurrency > 100) {
6264
+ throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
6265
+ }
6266
+ await runTestWaitMany({
5363
6267
  ...resolveCommonOptions(command),
5364
- runId,
6268
+ runIds,
5365
6269
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
6270
+ maxConcurrency,
5366
6271
  }, deps);
5367
6272
  });
5368
6273
  // -------------------------------------------------------------------------
@@ -5392,6 +6297,9 @@ export function createTestCommand(deps = {}) {
5392
6297
  .option('--skip-dependencies', 'BE only: rerun only the named test without expanding the producer/teardown closure', false)
5393
6298
  .option('--max-concurrency <n>', `with --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
5394
6299
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --verbose if auto-generated.')
6300
+ .option('--report <format>', 'with batch --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
6301
+ .option('--report-file <path>', 'output path for --report (atomic write)')
6302
+ .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
5395
6303
  .addHelpText('after', '\nNotes:\n' +
5396
6304
  ' • rerun replays a saved run/script and is MORE LENIENT than a fresh `test run`\n' +
5397
6305
  ' (auto-heal can pass steps that have drifted) — for strict scoring/regression,\n' +
@@ -5411,9 +6319,19 @@ export function createTestCommand(deps = {}) {
5411
6319
  // `--no-auto-heal`. There is no explicit `--auto-heal` flag, so
5412
6320
  // autoHealExplicit is always false in this design — the default-on value
5413
6321
  // is never a deliberate user choice to opt in.
6322
+ const testIds = testIdsArg ?? [];
6323
+ const isBatch = cmdOpts.all === true || testIds.length !== 1;
6324
+ const report = parseJUnitReportFormat(cmdOpts.report);
6325
+ assertJUnitReportOptions({
6326
+ report,
6327
+ reportFile: cmdOpts.reportFile,
6328
+ reportSuiteName: cmdOpts.reportSuiteName,
6329
+ wait: cmdOpts.wait === true,
6330
+ batchPath: isBatch,
6331
+ });
5414
6332
  await runTestRerun({
5415
6333
  ...resolveCommonOptions(command),
5416
- testIds: testIdsArg ?? [],
6334
+ testIds,
5417
6335
  all: cmdOpts.all === true,
5418
6336
  projectId: cmdOpts.project,
5419
6337
  skipTerminal: cmdOpts.skipTerminal === true,
@@ -5427,6 +6345,41 @@ export function createTestCommand(deps = {}) {
5427
6345
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
5428
6346
  DEFAULT_BATCH_RUN_CONCURRENCY,
5429
6347
  idempotencyKey: cmdOpts.idempotencyKey,
6348
+ report,
6349
+ reportFile: cmdOpts.reportFile,
6350
+ reportSuiteName: cmdOpts.reportSuiteName,
6351
+ }, deps);
6352
+ });
6353
+ // -------------------------------------------------------------------------
6354
+ // `test flaky` — repeat-run flaky-test detector
6355
+ // -------------------------------------------------------------------------
6356
+ test
6357
+ .command('flaky <test-id>')
6358
+ .description('Repeatedly replay a test to measure stability and surface flakiness.\n' +
6359
+ 'Replays run with auto-heal OFF (strict verbatim) so healed drift cannot mask nondeterministic pass/fail.\n' +
6360
+ '\nExit codes:\n' +
6361
+ ' 0 stable (every attempt passed)\n' +
6362
+ ' 1 flaky or failing (at least one attempt did not pass)\n' +
6363
+ ' 3 auth error\n' +
6364
+ ' 4 test not found (no replayable run — trigger `testsprite test run <id>` first)\n' +
6365
+ ' 5 validation error')
6366
+ .option('--runs <n>', `number of replays to run (1-${MAX_FLAKY_RUNS}, default ${DEFAULT_FLAKY_RUNS})`)
6367
+ .option('--until-fail', 'stop at the first non-passing attempt (fast "is it flaky at all?" check)', false)
6368
+ .option('--timeout <s>', `per-attempt max seconds to wait (1-${MAX_RUN_TIMEOUT_SECONDS}, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6369
+ .addHelpText('after', '\nNotes:\n' +
6370
+ ' • Frontend replays are free verbatim script replays (no credit); backend replays\n' +
6371
+ ' re-run the dependency closure and may cost credits — a one-line advisory is printed.\n' +
6372
+ ' • Replays use auto-heal OFF so a flaky test is not silently "healed" into a pass;\n' +
6373
+ ' this measures replay stability of the saved script against the configured URL.\n' +
6374
+ ' • `--output json` emits a machine-readable stability report for CI gating.')
6375
+ .addHelpText('after', GLOBAL_OPTS_HINT)
6376
+ .action(async (testIdArg, cmdOpts, command) => {
6377
+ await runFlaky({
6378
+ ...resolveCommonOptions(command),
6379
+ testId: testIdArg,
6380
+ runs: parseNumericFlag(cmdOpts.runs, 'runs') ?? DEFAULT_FLAKY_RUNS,
6381
+ untilFail: cmdOpts.untilFail === true,
6382
+ timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
5430
6383
  }, deps);
5431
6384
  });
5432
6385
  test.addCommand(createTestCodeCommand(deps));
@@ -5435,6 +6388,142 @@ export function createTestCommand(deps = {}) {
5435
6388
  test.addCommand(createTestArtifactCommand(deps));
5436
6389
  return test;
5437
6390
  }
6391
+ // ---------------------------------------------------------------------------
6392
+ // `test flaky` — repeat-run flaky-test detector
6393
+ // ---------------------------------------------------------------------------
6394
+ /** Upper bound on `--runs` so a repeat-runner can't amplify free FE replays. */
6395
+ const MAX_FLAKY_RUNS = 10;
6396
+ /** Default replay count when `--runs` is omitted. */
6397
+ const DEFAULT_FLAKY_RUNS = 5;
6398
+ /**
6399
+ * `test flaky <test-id>` — replay a test N times and report a stability score.
6400
+ *
6401
+ * Each attempt is a `POST /tests/{id}/runs/rerun` with auto-heal OFF (a strict
6402
+ * verbatim replay) followed by `pollRunUntilTerminal`. Frontend replays are
6403
+ * free verbatim script replays; backend replays re-run the dependency closure
6404
+ * (a one-line credit advisory is printed). The pure scoring lives in
6405
+ * `lib/flaky.ts`; this function is the I/O orchestrator.
6406
+ *
6407
+ * Exit code: 0 when every observed attempt passed (stable), else 1 — so CI can
6408
+ * gate a merge on flakiness.
6409
+ */
6410
+ export async function runFlaky(opts, deps = {}) {
6411
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
6412
+ const out = makeOutput(opts.output, deps);
6413
+ if (typeof opts.testId !== 'string' || opts.testId.length === 0) {
6414
+ throw localValidationError('test-id', 'is required');
6415
+ }
6416
+ if (!Number.isInteger(opts.runs) || opts.runs < 1 || opts.runs > MAX_FLAKY_RUNS) {
6417
+ throw localValidationError('runs', `must be an integer between 1 and ${MAX_FLAKY_RUNS}`);
6418
+ }
6419
+ if (opts.dryRun) {
6420
+ out.print({
6421
+ dryRun: true,
6422
+ command: 'test flaky',
6423
+ testId: opts.testId,
6424
+ runs: opts.runs,
6425
+ untilFail: opts.untilFail,
6426
+ method: 'POST',
6427
+ path: `/api/cli/v1/tests/${opts.testId}/runs/rerun`,
6428
+ note: `Would replay the test up to ${opts.runs}x with auto-heal OFF and report a stability score.`,
6429
+ });
6430
+ return undefined;
6431
+ }
6432
+ // Under the implicit wait, raise the per-request timeout to cover --timeout
6433
+ // so a slow trigger / long-poll under load isn't cut at the 120s default.
6434
+ const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
6435
+ // Best-effort test-type detection for the credit advisory. A probe failure
6436
+ // never blocks the run — we just skip the advisory.
6437
+ let isBackend = false;
6438
+ try {
6439
+ const test = await client.get(`/tests/${encodeURIComponent(opts.testId)}`);
6440
+ isBackend = test.type === 'backend';
6441
+ }
6442
+ catch {
6443
+ // best-effort — proceed without the advisory.
6444
+ }
6445
+ if (isBackend) {
6446
+ stderrFn(`[advisory] ${opts.testId} is a backend test — each replay re-runs its dependency closure ` +
6447
+ `and may cost credits. Frontend replays are free verbatim script replays; backend replays are not.`);
6448
+ }
6449
+ const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
6450
+ const attempts = [];
6451
+ for (let i = 1; i <= opts.runs; i++) {
6452
+ const idempotencyKey = `cli-flaky-${randomUUID()}`;
6453
+ let rerunResp;
6454
+ try {
6455
+ // auto-heal is intentionally OFF: flaky detection needs a strict verbatim
6456
+ // replay so healed drift cannot mask a nondeterministic pass/fail.
6457
+ rerunResp = await client.triggerRerun(opts.testId, { source: 'cli' }, { idempotencyKey });
6458
+ }
6459
+ catch (err) {
6460
+ // A missing replayable run is fatal for the whole command (mirror rerun):
6461
+ // there is nothing to repeat, so point the user at a fresh `test run`.
6462
+ if (err instanceof ApiError && err.code === 'NOT_FOUND') {
6463
+ throw ApiError.fromEnvelope({
6464
+ error: {
6465
+ code: 'NOT_FOUND',
6466
+ message: `Test ${opts.testId} has no replayable run (unknown/cross-tenant id, or it has never completed a clean run).`,
6467
+ nextAction: `Trigger a fresh run first: testsprite test run ${opts.testId}`,
6468
+ requestId: err.requestId ?? 'local',
6469
+ details: { testId: opts.testId, reason: 'no_replayable_run' },
6470
+ },
6471
+ });
6472
+ }
6473
+ // Any other trigger error is recorded as an errored attempt so a single
6474
+ // transient blip doesn't abort a long stability probe.
6475
+ const code = err instanceof ApiError ? err.code : 'ERROR';
6476
+ attempts.push({ attempt: i, runId: null, outcome: 'error', failureKind: code });
6477
+ ticker.update(`Attempt ${i}/${opts.runs} — error (${code})`);
6478
+ if (opts.untilFail)
6479
+ break;
6480
+ continue;
6481
+ }
6482
+ const runId = rerunResp.runId;
6483
+ // Backend run rows never finalize server-side; resolve the verdict from the
6484
+ // testId-scoped result on non-terminal ticks (same fallback as `test rerun`).
6485
+ const resolveAlternate = makeBackendWaitFallback({
6486
+ client,
6487
+ resolveTestId: () => opts.testId,
6488
+ resolveNotBefore: () => rerunResp.enqueuedAt,
6489
+ });
6490
+ let outcome;
6491
+ let failureKind = null;
6492
+ try {
6493
+ const finalRun = await pollRunUntilTerminal(client, runId, {
6494
+ timeoutSeconds: opts.timeoutSeconds,
6495
+ sleep: deps.sleep,
6496
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
6497
+ resolveAlternate,
6498
+ });
6499
+ outcome = finalRun.status;
6500
+ failureKind = finalRun.failureKind;
6501
+ }
6502
+ catch (err) {
6503
+ // A per-attempt deadline (poll TimeoutError) or a client-side request
6504
+ // timeout both count as a non-passing "timeout" outcome for this attempt.
6505
+ if (err instanceof TimeoutError || err instanceof RequestTimeoutError) {
6506
+ outcome = 'timeout';
6507
+ }
6508
+ else {
6509
+ throw err;
6510
+ }
6511
+ }
6512
+ attempts.push({ attempt: i, runId, outcome, failureKind });
6513
+ const passedSoFar = attempts.filter(a => a.outcome === 'passed').length;
6514
+ ticker.update(`Attempt ${i}/${opts.runs} — ${outcome} (${passedSoFar} passed so far)`);
6515
+ if (opts.untilFail && outcome !== 'passed')
6516
+ break;
6517
+ }
6518
+ ticker.finalize();
6519
+ const report = summarizeFlaky(opts.testId, attempts);
6520
+ out.print(report, data => renderFlakyText(data));
6521
+ const exitCode = flakyExitCode(report);
6522
+ if (exitCode !== 0) {
6523
+ throw new CLIError(`Test ${opts.testId} is ${report.verdict} — ${report.passed}/${report.runs} attempts passed`, exitCode);
6524
+ }
6525
+ return report;
6526
+ }
5438
6527
  function requireProjectId(projectId) {
5439
6528
  if (typeof projectId !== 'string' || projectId.length === 0) {
5440
6529
  throw localValidationError('project', 'is required');
@@ -5481,13 +6570,9 @@ function resolveCommonOptions(command) {
5481
6570
  // P2-8: validate --output before allowing silent fallback to 'text'.
5482
6571
  // An invalid value (e.g. `--output yaml`) must exit 5 with a clear error
5483
6572
  // rather than silently treating the request as text mode.
5484
- const rawOutput = globals.output;
5485
- if (rawOutput !== undefined && rawOutput !== 'json' && rawOutput !== 'text') {
5486
- throw localValidationError('output', 'must be one of: json, text', ['json', 'text']);
5487
- }
5488
6573
  return {
5489
6574
  profile: globals.profile ?? 'default',
5490
- output: globals.output ?? 'text',
6575
+ output: resolveOutputMode(globals.output),
5491
6576
  dryRun: globals.dryRun ?? false,
5492
6577
  endpointUrl: globals.endpointUrl,
5493
6578
  debug: globals.debug ?? false,
@@ -5495,19 +6580,6 @@ function resolveCommonOptions(command) {
5495
6580
  requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
5496
6581
  };
5497
6582
  }
5498
- /**
5499
- * Parse the `--request-timeout <seconds>` flag value into milliseconds.
5500
- * Returns `undefined` when the flag was not supplied (factory falls back to
5501
- * the env var / default). Silently clamps out-of-range values.
5502
- */
5503
- function parseRequestTimeoutFlag(raw) {
5504
- if (raw === undefined)
5505
- return undefined;
5506
- const n = Number(raw);
5507
- if (!Number.isFinite(n) || n <= 0)
5508
- return undefined;
5509
- return Math.round(n * 1000); // seconds → milliseconds
5510
- }
5511
6583
  /** D4: headroom added on top of `--timeout` when deriving the per-request window under `--wait`. */
5512
6584
  const WAIT_REQUEST_TIMEOUT_CUSHION_MS = 5_000;
5513
6585
  /**
@@ -5544,13 +6616,16 @@ function makeOutput(mode, deps) {
5544
6616
  });
5545
6617
  }
5546
6618
  /**
5547
- * Open the `--out` target before any network I/O so a permission/dir
5548
- * error fails fast. Synchronous open via `createWriteStream` doesn't
5549
- * actually open the descriptor until first write, so we don't surface
5550
- * EACCES/ENOENT here — instead the stream emits `'error'`, which we
5551
- * remember on the sink and re-throw at close time. The benefit of
5552
- * opening early is still real: invalid path strings (empty, `/dev/null`
5553
- * on a sandboxed fs, etc.) are caught before the API request goes out.
6619
+ * Open a temp file next to the `--out` target before any network I/O so
6620
+ * a permission/dir error fails fast. Synchronous open via
6621
+ * `createWriteStream` doesn't actually open the descriptor until first
6622
+ * write, so we don't surface EACCES/ENOENT here, instead the stream
6623
+ * emits `'error'`, which we remember on the sink and re-throw at close
6624
+ * time. The benefit of opening early is still real: invalid path
6625
+ * strings (empty, `/dev/null` on a sandboxed fs, etc.) are caught
6626
+ * before the API request goes out. Writing to a temp path rather than
6627
+ * `resolved` directly means the real `--out` file is never truncated
6628
+ * up front, see `closeOutputFile` for the commit step.
5554
6629
  */
5555
6630
  function openOutputFile(rawPath) {
5556
6631
  if (typeof rawPath !== 'string' || rawPath.length === 0) {
@@ -5580,8 +6655,21 @@ function openOutputFile(rawPath) {
5580
6655
  if (!parentStat.isDirectory()) {
5581
6656
  throw localValidationError('out', `parent path is not a directory: ${parent}`);
5582
6657
  }
5583
- const stream = createWriteStream(resolved, { encoding: 'utf8' });
5584
- const sink = { stream, path: resolved, error: null };
6658
+ let targetStat;
6659
+ try {
6660
+ targetStat = statSync(resolved);
6661
+ }
6662
+ catch (err) {
6663
+ if (err.code !== 'ENOENT') {
6664
+ throw localValidationError('out', `cannot stat output path: ${resolved}`);
6665
+ }
6666
+ }
6667
+ if (targetStat?.isDirectory()) {
6668
+ throw localValidationError('out', `must point to a file, not a directory: ${resolved}`);
6669
+ }
6670
+ const tmpPath = join(parent, `.${basename(resolved)}.tmp-${randomUUID()}`);
6671
+ const stream = createWriteStream(tmpPath, { encoding: 'utf8' });
6672
+ const sink = { stream, path: resolved, tmpPath, error: null };
5585
6673
  stream.on('error', err => {
5586
6674
  sink.error = err instanceof Error ? err : new Error(String(err));
5587
6675
  });
@@ -5611,25 +6699,49 @@ function makeFileOutput(mode, sink) {
5611
6699
  });
5612
6700
  }
5613
6701
  /**
5614
- * Flush + close the file sink. Called on the success path after the
5615
- * last write and on the error path inside a `.catch(() => undefined)`
5616
- * so the original error isn't masked by a teardown failure.
6702
+ * Flush + close the file sink, then either commit or discard the temp
6703
+ * file. Called on the success path after the last write (`commit:
6704
+ * true` when content was actually written) and on the error / "no code
6705
+ * yet" paths (`commit: false`) inside a `.catch(() => undefined)` so a
6706
+ * teardown failure doesn't mask the original error.
6707
+ *
6708
+ * `commit: true` renames `tmpPath` onto the real `--out` path, the
6709
+ * only point at which the operator's file is touched. `commit: false`
6710
+ * discards the temp file and leaves any pre-existing `--out` file
6711
+ * exactly as it was, this is what prevents a failed/empty response
6712
+ * from silently truncating the operator's filesystem (mirrors the
6713
+ * atomic-rename contract `bundle.ts` uses for multi-file bundles).
5617
6714
  *
5618
6715
  * Re-raises any async stream error captured by the `'error'` listener.
5619
6716
  * Without this re-raise, an EACCES on first write would leave a
5620
- * zero-byte file behind and exit 0 — a false-success surface that is
5621
- * exactly the failure mode `--out` exists to avoid.
6717
+ * zero-byte temp file behind and exit 0, a false-success surface that
6718
+ * is exactly the failure mode `--out` exists to avoid.
5622
6719
  */
5623
- function closeOutputFile(sink) {
5624
- return new Promise((resolve, reject) => {
5625
- sink.stream.end(() => {
5626
- if (sink.error) {
5627
- reject(new TransportError(`Failed to write --out ${sink.path}: ${sink.error.message}`));
5628
- return;
5629
- }
6720
+ async function closeOutputFile(sink, commit) {
6721
+ await new Promise(resolveStream => {
6722
+ sink.stream.end(() => resolveStream());
6723
+ });
6724
+ if (sink.error) {
6725
+ await unlink(sink.tmpPath).catch(() => undefined);
6726
+ throw new TransportError(`Failed to write --out ${sink.path}: ${sink.error.message}`);
6727
+ }
6728
+ if (!commit) {
6729
+ await unlink(sink.tmpPath).catch(() => undefined);
6730
+ return;
6731
+ }
6732
+ await rename(sink.tmpPath, sink.path);
6733
+ }
6734
+ /** Tear down an opened `--out` sink without leaving a zero-byte artifact. */
6735
+ async function abortOutputFile(sink) {
6736
+ await new Promise(resolve => {
6737
+ if (sink.stream.destroyed) {
5630
6738
  resolve();
5631
- });
6739
+ return;
6740
+ }
6741
+ sink.stream.once('close', () => resolve());
6742
+ sink.stream.destroy();
5632
6743
  });
6744
+ await unlink(sink.tmpPath).catch(() => undefined);
5633
6745
  }
5634
6746
  /** A presigned `code` body is any `https://` URL — never anything else. */
5635
6747
  export function isPresignedCodeUrl(code) {
@@ -5820,9 +6932,9 @@ function renderStepsText(page) {
5820
6932
  pad('DESCRIPTION', descWidth) +
5821
6933
  ' ' +
5822
6934
  'UPDATED';
5823
- const rows = page.items.map(s => {
6935
+ const rows = page.items.flatMap(s => {
5824
6936
  const marker = s.outcomeContributesToFailure === true ? '* ' : ' ';
5825
- return [
6937
+ const row = [
5826
6938
  marker,
5827
6939
  pad(String(s.stepIndex), indexWidth),
5828
6940
  pad(s.action, actionWidth),
@@ -5830,6 +6942,18 @@ function renderStepsText(page) {
5830
6942
  pad(descOf(s), descWidth),
5831
6943
  s.updatedAt,
5832
6944
  ].join(' ');
6945
+ // Run-scoped rows carry the per-step failure text; surface it as an
6946
+ // indented sub-line under failed rows (mirrors the history table's
6947
+ // `targetUrl:` sub-line). Collapsed to one line and capped so a huge
6948
+ // stack blob can't wreck the table; full text ships in --output json.
6949
+ if (s.status === 'failed' && typeof s.error === 'string' && s.error.length > 0) {
6950
+ const oneLine = s.error.replace(/\s+/g, ' ').trim();
6951
+ const shown = oneLine.length > ERROR_SUBLINE_MAX
6952
+ ? `${oneLine.slice(0, ERROR_SUBLINE_MAX - 1)}…`
6953
+ : oneLine;
6954
+ return [row, ` error: ${shown}`];
6955
+ }
6956
+ return [row];
5833
6957
  });
5834
6958
  const lines = [header, ...rows, ''];
5835
6959
  // §6.4: all steps in one response share `runIdIfAvailable` and
@@ -5988,7 +7112,10 @@ function renderResultText(r) {
5988
7112
  // when the run failed; passing/running runs render in chronological
5989
7113
  // order so a glance reads like a timeline.
5990
7114
  const lines = [];
5991
- lines.push(`status: ${r.status}`);
7115
+ // surface verdict (outcome) and executionStatus (lifecycle) instead
7116
+ // of the legacy conflated `status` (still present on the JSON wire shape).
7117
+ lines.push(`verdict: ${r.verdict ?? '— (no verdict yet)'}`);
7118
+ lines.push(`executionStatus: ${r.executionStatus}`);
5992
7119
  lines.push(`testId: ${r.testId}`);
5993
7120
  if (r.failureKind !== null)
5994
7121
  lines.push(`failureKind: ${r.failureKind}`);
@@ -6005,7 +7132,7 @@ function renderResultText(r) {
6005
7132
  lines.push(`codeVersion: ${r.codeVersion}`);
6006
7133
  if (r.targetUrl !== null)
6007
7134
  lines.push(`targetUrl: ${r.targetUrl}`);
6008
- lines.push(`summary: passed=${r.summary.passed} failed=${r.summary.failed} skipped=${r.summary.skipped}`);
7135
+ lines.push(`summary: ${r.summary}`);
6009
7136
  if (r.videoUrl !== null)
6010
7137
  lines.push(`videoUrl: ${r.videoUrl}`);
6011
7138
  if (r.failureAnalysisUrl !== null)
@@ -6099,7 +7226,7 @@ function createTestCodeCommand(deps) {
6099
7226
  .option('--code-file <path>', 'file containing the new test code (≤ 350 KB)')
6100
7227
  .option('--expected-version <v>', 'expected current codeVersion (e.g. v3); sent as `If-Match`. Mutually exclusive with --force.')
6101
7228
  .option('--force', 'send `If-Match: *` to skip the etag check (audit-logged with force: true). Mutually exclusive with --expected-version.', false)
6102
- .option('--language <lang>', 'override the stored language (typescript|javascript|python). Defaults to the existing language.')
7229
+ .option('--language <lang>', 'set the stored code language; only "python" is supported (TestSprite executes test code as Python). Defaults to the existing language.')
6103
7230
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
6104
7231
  .option('--dry-run-simulate-error <code>', 'With --dry-run: synthesise an error envelope to preview the error path. Supported: PRECONDITION_FAILED (412).')
6105
7232
  .addHelpText('after', '\nDry-run note: --dry-run always returns the happy response shape.\n' +
@@ -6156,7 +7283,11 @@ function createTestPlanCommand(deps) {
6156
7283
  export function createTestArtifactCommand(deps) {
6157
7284
  const artifact = new Command('artifact').description('Download run-scoped artifact bundles (M3.3 piece-4)');
6158
7285
  artifact
6159
- .command('get <run-id>')
7286
+ // `isDefault: true` makes `test artifact <run-id>` a pass-through alias for
7287
+ // `test artifact get <run-id>` (DEV-230 grammar consistency — bare-noun reads
7288
+ // mirror the flat `test result/steps/get <id>` forms). Run-id semantics are
7289
+ // preserved: the positional is still a run-id, not a test-id.
7290
+ .command('get <run-id>', { isDefault: true })
6160
7291
  .description([
6161
7292
  'Download the §7 failure-context bundle for a specific run.',
6162
7293
  '',
@@ -6174,7 +7305,8 @@ export function createTestArtifactCommand(deps) {
6174
7305
  'Directory to write the §7 disk layout (default: ./.testsprite/runs/<run-id>/).',
6175
7306
  'Parent must exist. The bundle dir itself is created if absent.',
6176
7307
  ].join(' '))
6177
- .option('--failed-only', 'Keep only the failed step plus its immediate neighbors (±1)')
7308
+ .option('--failed-only', 'Trim to the failed step ±1. The bundle is already failure-focused server-side, ' +
7309
+ 'so this is usually a no-op; use `test steps <id>` for the full run trail.')
6178
7310
  .addHelpText('after', GLOBAL_OPTS_HINT)
6179
7311
  .action(async (runId, cmdOpts, command) => {
6180
7312
  await runArtifactGet({
@@ -6189,10 +7321,14 @@ export function createTestArtifactCommand(deps) {
6189
7321
  function createTestFailureCommand(deps) {
6190
7322
  const failure = new Command('failure').description('Export the latest-failure agent bundle');
6191
7323
  failure
6192
- .command('get <test-id>')
7324
+ // `isDefault: true` makes `test failure <test-id>` a pass-through alias for
7325
+ // `test failure get <test-id>` (DEV-230 grammar consistency). `failure summary`
7326
+ // still routes explicitly; only the bare-noun form falls through to `get`.
7327
+ .command('get <test-id>', { isDefault: true })
6193
7328
  .description("Write a self-contained failure-context bundle for a test's latest failing run")
6194
7329
  .option('--out <dir>', 'Directory to write the §7 disk layout into (default: print wire envelope to stdout)')
6195
- .option('--failed-only', 'Keep only the failed step plus its immediate neighbors (±1)')
7330
+ .option('--failed-only', 'Trim to the failed step ±1. The bundle is already failure-focused server-side, ' +
7331
+ 'so this is usually a no-op; use `test steps <id>` for the full run trail.')
6196
7332
  .addHelpText('after', GLOBAL_OPTS_HINT)
6197
7333
  .action(async (testId, cmdOpts, command) => {
6198
7334
  await runFailureGet({