@testsprite/testsprite-cli 0.2.0 → 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 (55) hide show
  1. package/README.md +34 -26
  2. package/dist/commands/agent.d.ts +43 -0
  3. package/dist/commands/agent.js +200 -18
  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 +1 -1
  8. package/dist/commands/init.js +24 -14
  9. package/dist/commands/project.d.ts +50 -1
  10. package/dist/commands/project.js +252 -43
  11. package/dist/commands/test.d.ts +188 -1
  12. package/dist/commands/test.js +1088 -81
  13. package/dist/commands/usage.js +13 -12
  14. package/dist/index.js +33 -2
  15. package/dist/lib/agent-targets.d.ts +72 -6
  16. package/dist/lib/agent-targets.js +188 -6
  17. package/dist/lib/bundle.d.ts +34 -0
  18. package/dist/lib/bundle.js +44 -10
  19. package/dist/lib/client-factory.d.ts +25 -0
  20. package/dist/lib/client-factory.js +47 -0
  21. package/dist/lib/config.d.ts +2 -0
  22. package/dist/lib/config.js +11 -2
  23. package/dist/lib/credentials.js +10 -1
  24. package/dist/lib/dry-run/samples.d.ts +5 -0
  25. package/dist/lib/dry-run/samples.js +28 -0
  26. package/dist/lib/flaky.d.ts +80 -0
  27. package/dist/lib/flaky.js +76 -0
  28. package/dist/lib/http.d.ts +20 -0
  29. package/dist/lib/http.js +216 -132
  30. package/dist/lib/interrupt.d.ts +61 -0
  31. package/dist/lib/interrupt.js +97 -0
  32. package/dist/lib/junit-report.d.ts +58 -0
  33. package/dist/lib/junit-report.js +210 -0
  34. package/dist/lib/output.d.ts +16 -1
  35. package/dist/lib/output.js +24 -2
  36. package/dist/lib/pagination.d.ts +4 -3
  37. package/dist/lib/pagination.js +34 -6
  38. package/dist/lib/prompt.js +52 -8
  39. package/dist/lib/proxy.d.ts +29 -0
  40. package/dist/lib/proxy.js +30 -0
  41. package/dist/lib/render-error.js +3 -1
  42. package/dist/lib/skill-nudge.d.ts +2 -2
  43. package/dist/lib/skill-nudge.js +13 -4
  44. package/dist/lib/target-url.js +8 -1
  45. package/dist/lib/ticker.d.ts +11 -1
  46. package/dist/lib/ticker.js +33 -1
  47. package/dist/lib/update-check.d.ts +67 -0
  48. package/dist/lib/update-check.js +246 -0
  49. package/dist/version-guard.d.ts +33 -0
  50. package/dist/version-guard.js +39 -0
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +3 -2
  54. package/skills/testsprite-onboard.skill.md +21 -0
  55. package/skills/testsprite-verify.skill.md +33 -0
@@ -1,15 +1,16 @@
1
- import { createWriteStream, readFileSync, readdirSync, statSync } from 'node:fs';
1
+ import { createWriteStream, existsSync, readFileSync, readdirSync, statSync, } from 'node:fs';
2
2
  import { rename, stat, unlink } from 'node:fs/promises';
3
3
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { Command } from 'commander';
6
- 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,
@@ -241,14 +243,19 @@ export async function runCreate(opts, deps = {}) {
241
243
  if (opts.type === 'frontend') {
242
244
  const depFlags = [];
243
245
  if (opts.produces !== undefined && opts.produces.length > 0)
244
- depFlags.push('--produces');
246
+ depFlags.push('produces');
245
247
  if (opts.needs !== undefined && opts.needs.length > 0)
246
- depFlags.push('--needs');
248
+ depFlags.push('needs');
247
249
  if (opts.category !== undefined)
248
- depFlags.push('--category');
250
+ depFlags.push('category');
249
251
  if (depFlags.length > 0) {
250
- throw localValidationError(depFlags[0], `${depFlags.join(', ')} are backend-only flags; frontend plans have no wave model. ` +
251
- `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`);
252
259
  }
253
260
  }
254
261
  // Dry-run path skips fs entirely so the operator can shake out the
@@ -312,6 +319,10 @@ export async function runCreate(opts, deps = {}) {
312
319
  body,
313
320
  headers: { 'idempotency-key': idempotencyKey },
314
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);
315
326
  // --run chain (M3.3 piece-3). Per codex round-1 P1: suppress the
316
327
  // create's own print when chaining; `runTestRun` emits a single
317
328
  // merged envelope `{ ...createResponse, run: <trigger|final> }` so
@@ -413,7 +424,7 @@ function readCodeFileGuarded(path) {
413
424
  }
414
425
  function readCodeFile(path) {
415
426
  try {
416
- return readFileSync(resolveAbsolute(path), 'utf8');
427
+ return stripBom(readFileSync(resolveAbsolute(path), 'utf8'));
417
428
  }
418
429
  catch (err) {
419
430
  const code = err.code;
@@ -458,6 +469,17 @@ function renderCreateText(response) {
458
469
  `createdAt ${response.createdAt}`,
459
470
  ].join('\n');
460
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
+ }
461
483
  /**
462
484
  * piece-6 cap for the `PUT /tests/{id}/plan-steps` body. Distinct from
463
485
  * piece-5's `MAX_PLAN_BODY_BYTES` because the wire shape differs
@@ -653,6 +675,9 @@ export async function runUpdate(opts, deps = {}) {
653
675
  assertIdempotencyKey(opts.idempotencyKey);
654
676
  requireNonEmpty('test-id', opts.testId);
655
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
+ }
656
681
  if (opts.name !== undefined && opts.name.length > 200) {
657
682
  throw localValidationError('name', 'must be at most 200 characters');
658
683
  }
@@ -2239,7 +2264,7 @@ export async function runCodeGet(opts, deps = {}) {
2239
2264
  }
2240
2265
  return code;
2241
2266
  }
2242
- const fileSink = opts.out !== undefined ? openOutputFile(opts.out) : null;
2267
+ let fileSink = opts.out !== undefined ? openOutputFile(opts.out) : null;
2243
2268
  const out = fileSink ? makeFileOutput(opts.output, fileSink) : makeOutput(opts.output, deps);
2244
2269
  const client = makeClient(opts, deps);
2245
2270
  try {
@@ -2264,9 +2289,17 @@ export async function runCodeGet(opts, deps = {}) {
2264
2289
  else if (code.code === '' || code.code === null) {
2265
2290
  // P2-10: draft test with no code yet — empty body would produce
2266
2291
  // silent empty stdout. Print a friendly hint to stderr instead so
2267
- // the operator knows what happened, and keep exit 0. Nothing was
2268
- // written, so the temp file is discarded below without touching
2269
- // a pre-existing `--out` file.
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
+ }
2270
2303
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2271
2304
  stderrFn('(no code generated yet — run the test first)');
2272
2305
  }
@@ -2412,6 +2445,7 @@ export async function runCodePut(opts, deps = {}) {
2412
2445
  'if-match': ifMatch,
2413
2446
  },
2414
2447
  });
2448
+ emitResponseWarnings(response.warnings, deps);
2415
2449
  out.print(response, data => renderCodePutText(data));
2416
2450
  return response;
2417
2451
  }
@@ -2476,7 +2510,333 @@ function mapRunStepToCliTestStep(step, run) {
2476
2510
  // concrete boolean — `true` for the failing step, `false` for the known
2477
2511
  // non-contributors. (Per the CliTestStep contract: null ≠ false.)
2478
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;
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
+ }
2479
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;
2480
2840
  }
2481
2841
  export async function runSteps(opts, deps = {}) {
2482
2842
  const out = makeOutput(opts.output, deps);
@@ -2591,12 +2951,20 @@ export function parseDuration(raw, now = new Date()) {
2591
2951
  const hourMatch = /^(\d+)h$/i.exec(raw);
2592
2952
  if (hourMatch) {
2593
2953
  const hours = Number(hourMatch[1]);
2594
- 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();
2595
2959
  }
2596
2960
  const dayMatch = /^(\d+)d$/i.exec(raw);
2597
2961
  if (dayMatch) {
2598
2962
  const days = Number(dayMatch[1]);
2599
- 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();
2600
2968
  }
2601
2969
  // Pass-through: ISO timestamp or epoch value — server validates.
2602
2970
  return raw;
@@ -2616,7 +2984,10 @@ export async function runResultHistory(opts, deps = {}) {
2616
2984
  // configured (codex round-2), matching validatePaginationFlags ordering
2617
2985
  // in `test list` / `project list`.
2618
2986
  if (opts.pageSize !== undefined) {
2619
- 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) {
2620
2991
  throw localValidationError('page-size', 'must be between 1 and 100');
2621
2992
  }
2622
2993
  }
@@ -2694,6 +3065,13 @@ const RUN_HISTORY_TABLE_COL_WIDTHS = {
2694
3065
  * out (dogfood 2026-06-04). `--output json` carries the full text.
2695
3066
  */
2696
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;
2697
3075
  /** Max chars to show in the TARGETURL sub-line (excess truncated with …). */
2698
3076
  const HISTORY_TARGET_URL_MAX = 80;
2699
3077
  /**
@@ -3361,6 +3739,27 @@ export async function runTestRun(opts, deps = {}) {
3361
3739
  catch (err) {
3362
3740
  if (err instanceof TimeoutError) {
3363
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
+ });
3364
3763
  throw ApiError.fromEnvelope({
3365
3764
  error: {
3366
3765
  code: 'UNSUPPORTED', // exit 7 per errors.md
@@ -3430,6 +3829,178 @@ export async function runTestRun(opts, deps = {}) {
3430
3829
  }
3431
3830
  return finalRun;
3432
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
+ }
3433
4004
  /**
3434
4005
  * `test wait <run-id>` — M3.3 piece-3.
3435
4006
  *
@@ -3490,6 +4061,18 @@ export async function runTestWait(opts, deps = {}) {
3490
4061
  catch (err) {
3491
4062
  if (err instanceof TimeoutError) {
3492
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
+ });
3493
4076
  throw ApiError.fromEnvelope({
3494
4077
  error: {
3495
4078
  code: 'UNSUPPORTED', // exit 7 per errors.md
@@ -3538,6 +4121,18 @@ export async function runTestWait(opts, deps = {}) {
3538
4121
  }
3539
4122
  return finalRun;
3540
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
+ }
3541
4136
  /**
3542
4137
  * `test run --all --project <id>` — M4 piece-2.
3543
4138
  *
@@ -3553,6 +4148,13 @@ export async function runTestRunAll(opts, deps = {}) {
3553
4148
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
3554
4149
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
3555
4150
  }
4151
+ assertJUnitReportOptions({
4152
+ report: opts.report,
4153
+ reportFile: opts.reportFile,
4154
+ reportSuiteName: opts.reportSuiteName,
4155
+ wait: opts.wait,
4156
+ batchPath: true,
4157
+ });
3556
4158
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
3557
4159
  const out = makeOutput(opts.output, deps);
3558
4160
  // --- Dry-run path ---
@@ -3574,6 +4176,9 @@ export async function runTestRunAll(opts, deps = {}) {
3574
4176
  idempotencyKey,
3575
4177
  ...(opts.wait ? { thenPoll: '/api/cli/v1/runs/<run-id>?waitSeconds=25' } : {}),
3576
4178
  };
4179
+ if (opts.report === 'junit' && opts.reportFile !== undefined) {
4180
+ await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(opts.projectId, opts.reportSuiteName));
4181
+ }
3577
4182
  out.print(batchRunSample ?? envelope);
3578
4183
  return undefined;
3579
4184
  }
@@ -3593,13 +4198,10 @@ export async function runTestRunAll(opts, deps = {}) {
3593
4198
  return dashboardUrl !== undefined ? { ...item, dashboardUrl } : item;
3594
4199
  };
3595
4200
  const idempotencyKey = opts.idempotencyKey ?? `cli-batch-run-fresh-${randomUUID()}`;
3596
- if (opts.idempotencyKey === undefined && opts.debug) {
4201
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
3597
4202
  stderrFn(`idempotency-key: ${idempotencyKey}`);
3598
4203
  }
3599
- if (opts.idempotencyKey === undefined && opts.verbose) {
3600
- stderrFn(`[verbose] auto-minted idempotency-key: ${idempotencyKey}`);
3601
- }
3602
- // Resolve testIds: fetch all BE tests in the project, apply --filter.
4204
+ // Resolve testIds: fetch all tests in the project, apply --filter.
3603
4205
  let testIds;
3604
4206
  if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
3605
4207
  // We need to resolve the full test set to apply the name filter.
@@ -3627,7 +4229,8 @@ export async function runTestRunAll(opts, deps = {}) {
3627
4229
  }
3628
4230
  stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${opts.projectId} for batch run.`);
3629
4231
  }
3630
- // 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).
3631
4234
  const batchResp = await client.triggerBatchRunFresh({
3632
4235
  projectId: opts.projectId,
3633
4236
  ...(testIds !== undefined ? { testIds } : {}),
@@ -3817,7 +4420,20 @@ export async function runTestRunAll(opts, deps = {}) {
3817
4420
  // NOTE: batchDeadlineMs is set in the D3 deferred-retry loop above and reused here.
3818
4421
  async function pollFreshAccepted(entry) {
3819
4422
  const runId = entry.runId;
3820
- 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);
3821
4437
  const resolveAlternate = makeBackendWaitFallback({
3822
4438
  client,
3823
4439
  resolveTestId: () => entry.testId,
@@ -3836,7 +4452,12 @@ export async function runTestRunAll(opts, deps = {}) {
3836
4452
  },
3837
4453
  resolveAlternate,
3838
4454
  });
3839
- 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
+ };
3840
4461
  }
3841
4462
  catch (err) {
3842
4463
  if (err instanceof TimeoutError) {
@@ -3851,6 +4472,22 @@ export async function runTestRunAll(opts, deps = {}) {
3851
4472
  },
3852
4473
  };
3853
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
+ }
3854
4491
  if (err instanceof ApiError) {
3855
4492
  // Preserve the real exit code + envelope (AUTH_INVALID=3, NOT_FOUND=4,
3856
4493
  // RATE_LIMITED=11, …) instead of flattening every member failure to 1
@@ -3911,6 +4548,7 @@ export async function runTestRunAll(opts, deps = {}) {
3911
4548
  total: pollable.length,
3912
4549
  },
3913
4550
  };
4551
+ await writeBatchJUnitReportIfRequested(opts, freshRunResults);
3914
4552
  out.print(jsonPayload);
3915
4553
  // Rate-deferred tests were never dispatched → the batch is incomplete (exit 7),
3916
4554
  // mirroring `test rerun --all`. Checked before the failed-run throw so the
@@ -3974,6 +4612,15 @@ export async function runTestRerun(opts, deps = {}) {
3974
4612
  if (opts.testIds.length === 0 && !opts.all) {
3975
4613
  throw localValidationError('test-ids', 'provide at least one <test-id>, or use --all to rerun all tests in the project');
3976
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
+ }
3977
4624
  if (opts.all && !opts.projectId) {
3978
4625
  throw localValidationError('project', '--all requires a project context — pass --project <id> or configure a default');
3979
4626
  }
@@ -3986,12 +4633,31 @@ export async function runTestRerun(opts, deps = {}) {
3986
4633
  throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests get reran). ' +
3987
4634
  'Remove --filter, or add --all --project <id>.');
3988
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
+ }
3989
4648
  if (!Number.isInteger(opts.maxConcurrency) ||
3990
4649
  opts.maxConcurrency < 1 ||
3991
4650
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
3992
4651
  throw localValidationError('max-concurrency', 'must be an integer between 1 and 100');
3993
4652
  }
3994
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
+ });
3995
4661
  // -------------------------------------------------------------------------
3996
4662
  // Pre-flight: auto-heal + Free-tier hint (best-effort, non-blocking)
3997
4663
  // -------------------------------------------------------------------------
@@ -4030,6 +4696,10 @@ export async function runTestRerun(opts, deps = {}) {
4030
4696
  idempotencyKey,
4031
4697
  ...(opts.wait ? { thenPoll: `/api/cli/v1/runs/<run-id>?waitSeconds=25` } : {}),
4032
4698
  };
4699
+ if (opts.report === 'junit' && opts.reportFile !== undefined) {
4700
+ const projectKey = resolveBatchReportProjectId(opts, []);
4701
+ await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(projectKey, opts.reportSuiteName));
4702
+ }
4033
4703
  out.print(findSample('POST', '/api/cli/v1/tests/batch/rerun')?.body() ?? envelope);
4034
4704
  }
4035
4705
  void client;
@@ -4039,12 +4709,9 @@ export async function runTestRerun(opts, deps = {}) {
4039
4709
  // slow rerun trigger / long-poll under load isn't cut at the 120s default.
4040
4710
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
4041
4711
  const idempotencyKey = opts.idempotencyKey ?? `cli-rerun-${randomUUID()}`;
4042
- if (opts.idempotencyKey === undefined && opts.debug) {
4712
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
4043
4713
  stderrFn(`idempotency-key: ${idempotencyKey}`);
4044
4714
  }
4045
- if (opts.idempotencyKey === undefined && opts.verbose) {
4046
- stderrFn(`[verbose] auto-minted idempotency-key: ${idempotencyKey}`);
4047
- }
4048
4715
  // -------------------------------------------------------------------------
4049
4716
  // Single rerun path
4050
4717
  // -------------------------------------------------------------------------
@@ -4515,7 +5182,14 @@ export async function runTestRerun(opts, deps = {}) {
4515
5182
  chunkResponses = [];
4516
5183
  for (let idx = 0; idx < chunks.length; idx++) {
4517
5184
  const chunk = chunks[idx];
4518
- const chunkKey = chunks.length === 1 ? idempotencyKey : `${idempotencyKey}:chunk${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}`;
4519
5193
  const chunkResp = await client.triggerBatchRerun({
4520
5194
  source: 'cli',
4521
5195
  testIds: chunk,
@@ -4793,7 +5467,12 @@ export async function runTestRerun(opts, deps = {}) {
4793
5467
  },
4794
5468
  resolveAlternate,
4795
5469
  });
4796
- 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
+ };
4797
5476
  }
4798
5477
  catch (err) {
4799
5478
  if (err instanceof TimeoutError) {
@@ -4808,12 +5487,31 @@ export async function runTestRerun(opts, deps = {}) {
4808
5487
  },
4809
5488
  };
4810
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
+ }
4811
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.
4812
5510
  return {
4813
5511
  testId: entry.testId,
4814
5512
  runId: entry.runId,
4815
5513
  status: 'error',
4816
- error: { code: err.code, message: err.message, exitCode: 1 },
5514
+ error: { code: err.code, message: err.message, exitCode: err.exitCode },
4817
5515
  };
4818
5516
  }
4819
5517
  throw err;
@@ -4876,6 +5574,7 @@ export async function runTestRerun(opts, deps = {}) {
4876
5574
  total: accepted.length,
4877
5575
  },
4878
5576
  };
5577
+ await writeBatchJUnitReportIfRequested(opts, rerunResults);
4879
5578
  out.print(jsonPayload);
4880
5579
  // Determine exit code: timeout (deferred or any timeout) → 7; any fail → 1; all pass → 0
4881
5580
  if (deferred.length > 0 || timedOut > 0) {
@@ -4905,6 +5604,14 @@ export async function runTestRerun(opts, deps = {}) {
4905
5604
  });
4906
5605
  }
4907
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
+ }
4908
5615
  throw new CLIError(`${failed} rerun${failed !== 1 ? 's' : ''} failed.`, 1);
4909
5616
  }
4910
5617
  // [P2] Return post-retry state including merged notFound so callers see the
@@ -4913,6 +5620,19 @@ export async function runTestRerun(opts, deps = {}) {
4913
5620
  // outcome printed to stdout and is not part of the returned shape).
4914
5621
  return { ...batchResp, accepted, deferred, conflicts, notFound };
4915
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
+ }
4916
5636
  /**
4917
5637
  * Validate that the parent directory of `resolvedDir` exists and is a
4918
5638
  * directory. Surfaces `VALIDATION_ERROR` (exit 5) — matches the convention
@@ -4960,12 +5680,9 @@ export async function assertOutDirParentExists(resolvedDir) {
4960
5680
  */
4961
5681
  export async function runArtifactGet(opts, deps = {}) {
4962
5682
  const out = makeOutput(opts.output, deps);
4963
- const client = makeClient(opts, deps);
4964
5683
  const { runId } = opts;
4965
5684
  // Resolve output dir: explicit --out or the default .testsprite/runs/<runId>/
4966
- const resolvedDir = opts.out !== undefined
4967
- ? resolveBundleDir(opts.out)
4968
- : join(process.cwd(), '.testsprite', 'runs', runId);
5685
+ const resolvedDir = opts.out !== undefined ? resolveBundleDir(opts.out) : resolveDefaultArtifactDir(runId);
4969
5686
  // --dry-run: no network, no disk write.
4970
5687
  // The client (makeClient) is already wired with createDryRunFetch() when
4971
5688
  // dryRun: true, so a real call to client.get() would return the canned
@@ -5004,6 +5721,7 @@ export async function runArtifactGet(opts, deps = {}) {
5004
5721
  if (opts.out !== undefined) {
5005
5722
  await assertOutDirParentExists(resolvedDir);
5006
5723
  }
5724
+ const client = makeClient(opts, deps);
5007
5725
  // Fetch the run-scoped failure bundle.
5008
5726
  const { body: context, requestId: fetchRequestId } = await client.getWithMeta(`/runs/${encodeURIComponent(runId)}/failure`);
5009
5727
  // §3 atomicity invariants — run-scoped path requires runId to be present.
@@ -5249,6 +5967,25 @@ export function createTestCommand(deps = {}) {
5249
5967
  idempotencyKey: cmdOpts.idempotencyKey,
5250
5968
  }, deps);
5251
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
+ });
5252
5989
  test
5253
5990
  .command('steps <test-id>')
5254
5991
  .description('List the steps for a test (server returns the cumulative log across every run; use --run-id to scope to one run)')
@@ -5267,6 +6004,30 @@ export function createTestCommand(deps = {}) {
5267
6004
  runId: cmdOpts.runId,
5268
6005
  }, deps);
5269
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
+ });
5270
6031
  test
5271
6032
  .command('result <test-id>')
5272
6033
  .description('Get the latest result for a test (default) or list prior runs (--history).\n' +
@@ -5371,7 +6132,7 @@ export function createTestCommand(deps = {}) {
5371
6132
  test
5372
6133
  .command('run [test-id]')
5373
6134
  .description('Trigger a test run. With --wait, polls until terminal status.\n' +
5374
- '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' +
5375
6136
  '\nExit codes:\n' +
5376
6137
  ' 0 passed (or queued without --wait)\n' +
5377
6138
  ' 1 failed / blocked / cancelled\n' +
@@ -5387,15 +6148,22 @@ export function createTestCommand(deps = {}) {
5387
6148
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
5388
6149
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
5389
6150
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
5390
- .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)
5391
6152
  .option('--project <id>', 'project id (required with --all; returned by `testsprite project list`)')
5392
6153
  .option('--filter <substr>', 'with --all: only run tests whose name contains this substring (case-insensitive)')
5393
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>)')
5394
6158
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
5395
- ' 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' +
5396
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' +
5397
6162
  '\nBE tests can declare --produces/--needs at create time to drive wave ordering\n' +
5398
- '(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>'.")
5399
6167
  .addHelpText('after', GLOBAL_OPTS_HINT)
5400
6168
  .action(async (testIdArg, cmdOpts, command) => {
5401
6169
  const isAll = cmdOpts.all === true;
@@ -5404,7 +6172,7 @@ export function createTestCommand(deps = {}) {
5404
6172
  throw localValidationError('test-id', 'positional <test-id> and --all are mutually exclusive; use one or the other');
5405
6173
  }
5406
6174
  if (testIdArg === undefined && !isAll) {
5407
- 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');
5408
6176
  }
5409
6177
  // --filter is an --all-only narrowing flag (mirrors `test rerun --filter`).
5410
6178
  // Without --all it would be SILENTLY ignored while the explicit <test-id>
@@ -5412,17 +6180,27 @@ export function createTestCommand(deps = {}) {
5412
6180
  if (cmdOpts.filter !== undefined && cmdOpts.filter !== '' && !isAll) {
5413
6181
  throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests run). Remove --filter, or add --all --project <id>.');
5414
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
+ });
5415
6191
  if (isAll) {
5416
6192
  // --all path: wave-ordered fresh batch run.
5417
6193
  if (!cmdOpts.project) {
5418
6194
  throw localValidationError('project', '--all requires a project id — pass --project <id>');
5419
6195
  }
5420
- // --target-url has no effect on the --all batch path: it is BE-only
5421
- // (FE tests are skipped server-side) and a BE test's base URL is baked
5422
- // into its code. Silently dropping it could run the suite against an
5423
- // 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.
5424
6202
  if (cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
5425
- 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.');
5426
6204
  }
5427
6205
  await runTestRunAll({
5428
6206
  ...resolveCommonOptions(command),
@@ -5433,6 +6211,9 @@ export function createTestCommand(deps = {}) {
5433
6211
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
5434
6212
  DEFAULT_BATCH_RUN_CONCURRENCY,
5435
6213
  idempotencyKey: cmdOpts.idempotencyKey,
6214
+ report,
6215
+ reportFile: cmdOpts.reportFile,
6216
+ reportSuiteName: cmdOpts.reportSuiteName,
5436
6217
  }, deps);
5437
6218
  return;
5438
6219
  }
@@ -5449,23 +6230,44 @@ export function createTestCommand(deps = {}) {
5449
6230
  }, deps);
5450
6231
  });
5451
6232
  test
5452
- .command('wait <run-id>')
5453
- .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' +
5454
6239
  '\nExit codes:\n' +
5455
6240
  ' 0 passed\n' +
5456
6241
  ' 1 failed / blocked / cancelled\n' +
5457
6242
  ' 3 auth error\n' +
5458
- ' 4 run not found\n' +
5459
- ' 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' +
5460
6246
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
5461
6247
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>')
5462
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)')
5463
6250
  .addHelpText('after', GLOBAL_OPTS_HINT)
5464
- .action(async (runId, cmdOpts, command) => {
5465
- 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({
5466
6267
  ...resolveCommonOptions(command),
5467
- runId,
6268
+ runIds,
5468
6269
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
6270
+ maxConcurrency,
5469
6271
  }, deps);
5470
6272
  });
5471
6273
  // -------------------------------------------------------------------------
@@ -5495,6 +6297,9 @@ export function createTestCommand(deps = {}) {
5495
6297
  .option('--skip-dependencies', 'BE only: rerun only the named test without expanding the producer/teardown closure', false)
5496
6298
  .option('--max-concurrency <n>', `with --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
5497
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>)')
5498
6303
  .addHelpText('after', '\nNotes:\n' +
5499
6304
  ' • rerun replays a saved run/script and is MORE LENIENT than a fresh `test run`\n' +
5500
6305
  ' (auto-heal can pass steps that have drifted) — for strict scoring/regression,\n' +
@@ -5514,9 +6319,19 @@ export function createTestCommand(deps = {}) {
5514
6319
  // `--no-auto-heal`. There is no explicit `--auto-heal` flag, so
5515
6320
  // autoHealExplicit is always false in this design — the default-on value
5516
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
+ });
5517
6332
  await runTestRerun({
5518
6333
  ...resolveCommonOptions(command),
5519
- testIds: testIdsArg ?? [],
6334
+ testIds,
5520
6335
  all: cmdOpts.all === true,
5521
6336
  projectId: cmdOpts.project,
5522
6337
  skipTerminal: cmdOpts.skipTerminal === true,
@@ -5530,6 +6345,41 @@ export function createTestCommand(deps = {}) {
5530
6345
  maxConcurrency: parseNumericFlag(cmdOpts.maxConcurrency, 'max-concurrency') ??
5531
6346
  DEFAULT_BATCH_RUN_CONCURRENCY,
5532
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'),
5533
6383
  }, deps);
5534
6384
  });
5535
6385
  test.addCommand(createTestCodeCommand(deps));
@@ -5538,6 +6388,142 @@ export function createTestCommand(deps = {}) {
5538
6388
  test.addCommand(createTestArtifactCommand(deps));
5539
6389
  return test;
5540
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
+ }
5541
6527
  function requireProjectId(projectId) {
5542
6528
  if (typeof projectId !== 'string' || projectId.length === 0) {
5543
6529
  throw localValidationError('project', 'is required');
@@ -5584,13 +6570,9 @@ function resolveCommonOptions(command) {
5584
6570
  // P2-8: validate --output before allowing silent fallback to 'text'.
5585
6571
  // An invalid value (e.g. `--output yaml`) must exit 5 with a clear error
5586
6572
  // rather than silently treating the request as text mode.
5587
- const rawOutput = globals.output;
5588
- if (rawOutput !== undefined && rawOutput !== 'json' && rawOutput !== 'text') {
5589
- throw localValidationError('output', 'must be one of: json, text', ['json', 'text']);
5590
- }
5591
6573
  return {
5592
6574
  profile: globals.profile ?? 'default',
5593
- output: globals.output ?? 'text',
6575
+ output: resolveOutputMode(globals.output),
5594
6576
  dryRun: globals.dryRun ?? false,
5595
6577
  endpointUrl: globals.endpointUrl,
5596
6578
  debug: globals.debug ?? false,
@@ -5598,19 +6580,6 @@ function resolveCommonOptions(command) {
5598
6580
  requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
5599
6581
  };
5600
6582
  }
5601
- /**
5602
- * Parse the `--request-timeout <seconds>` flag value into milliseconds.
5603
- * Returns `undefined` when the flag was not supplied (factory falls back to
5604
- * the env var / default). Silently clamps out-of-range values.
5605
- */
5606
- function parseRequestTimeoutFlag(raw) {
5607
- if (raw === undefined)
5608
- return undefined;
5609
- const n = Number(raw);
5610
- if (!Number.isFinite(n) || n <= 0)
5611
- return undefined;
5612
- return Math.round(n * 1000); // seconds → milliseconds
5613
- }
5614
6583
  /** D4: headroom added on top of `--timeout` when deriving the per-request window under `--wait`. */
5615
6584
  const WAIT_REQUEST_TIMEOUT_CUSHION_MS = 5_000;
5616
6585
  /**
@@ -5686,6 +6655,18 @@ function openOutputFile(rawPath) {
5686
6655
  if (!parentStat.isDirectory()) {
5687
6656
  throw localValidationError('out', `parent path is not a directory: ${parent}`);
5688
6657
  }
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
+ }
5689
6670
  const tmpPath = join(parent, `.${basename(resolved)}.tmp-${randomUUID()}`);
5690
6671
  const stream = createWriteStream(tmpPath, { encoding: 'utf8' });
5691
6672
  const sink = { stream, path: resolved, tmpPath, error: null };
@@ -5750,6 +6731,18 @@ async function closeOutputFile(sink, commit) {
5750
6731
  }
5751
6732
  await rename(sink.tmpPath, sink.path);
5752
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) {
6738
+ resolve();
6739
+ return;
6740
+ }
6741
+ sink.stream.once('close', () => resolve());
6742
+ sink.stream.destroy();
6743
+ });
6744
+ await unlink(sink.tmpPath).catch(() => undefined);
6745
+ }
5753
6746
  /** A presigned `code` body is any `https://` URL — never anything else. */
5754
6747
  export function isPresignedCodeUrl(code) {
5755
6748
  return code.startsWith('https://');
@@ -5939,9 +6932,9 @@ function renderStepsText(page) {
5939
6932
  pad('DESCRIPTION', descWidth) +
5940
6933
  ' ' +
5941
6934
  'UPDATED';
5942
- const rows = page.items.map(s => {
6935
+ const rows = page.items.flatMap(s => {
5943
6936
  const marker = s.outcomeContributesToFailure === true ? '* ' : ' ';
5944
- return [
6937
+ const row = [
5945
6938
  marker,
5946
6939
  pad(String(s.stepIndex), indexWidth),
5947
6940
  pad(s.action, actionWidth),
@@ -5949,6 +6942,18 @@ function renderStepsText(page) {
5949
6942
  pad(descOf(s), descWidth),
5950
6943
  s.updatedAt,
5951
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];
5952
6957
  });
5953
6958
  const lines = [header, ...rows, ''];
5954
6959
  // §6.4: all steps in one response share `runIdIfAvailable` and
@@ -6300,7 +7305,8 @@ export function createTestArtifactCommand(deps) {
6300
7305
  'Directory to write the §7 disk layout (default: ./.testsprite/runs/<run-id>/).',
6301
7306
  'Parent must exist. The bundle dir itself is created if absent.',
6302
7307
  ].join(' '))
6303
- .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.')
6304
7310
  .addHelpText('after', GLOBAL_OPTS_HINT)
6305
7311
  .action(async (runId, cmdOpts, command) => {
6306
7312
  await runArtifactGet({
@@ -6321,7 +7327,8 @@ function createTestFailureCommand(deps) {
6321
7327
  .command('get <test-id>', { isDefault: true })
6322
7328
  .description("Write a self-contained failure-context bundle for a test's latest failing run")
6323
7329
  .option('--out <dir>', 'Directory to write the §7 disk layout into (default: print wire envelope to stdout)')
6324
- .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.')
6325
7332
  .addHelpText('after', GLOBAL_OPTS_HINT)
6326
7333
  .action(async (testId, cmdOpts, command) => {
6327
7334
  await runFailureGet({