@testsprite/testsprite-cli 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +26 -1
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +46 -0
  4. package/dist/commands/auth.js +37 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +20 -2
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +77 -3
  11. package/dist/commands/project.js +176 -43
  12. package/dist/commands/test.d.ts +160 -10
  13. package/dist/commands/test.js +1261 -303
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +132 -26
  17. package/dist/lib/browser.d.ts +6 -0
  18. package/dist/lib/browser.js +54 -0
  19. package/dist/lib/bundle.d.ts +32 -31
  20. package/dist/lib/bundle.js +125 -83
  21. package/dist/lib/client-factory.d.ts +23 -0
  22. package/dist/lib/client-factory.js +33 -1
  23. package/dist/lib/config.js +7 -3
  24. package/dist/lib/credentials.d.ts +17 -1
  25. package/dist/lib/credentials.js +175 -16
  26. package/dist/lib/dry-run/samples.js +15 -1
  27. package/dist/lib/errors.d.ts +6 -1
  28. package/dist/lib/errors.js +70 -19
  29. package/dist/lib/flaky.d.ts +12 -1
  30. package/dist/lib/flaky.js +7 -12
  31. package/dist/lib/gh-output.d.ts +62 -0
  32. package/dist/lib/gh-output.js +99 -0
  33. package/dist/lib/http.d.ts +33 -15
  34. package/dist/lib/http.js +68 -6
  35. package/dist/lib/org-render.d.ts +52 -0
  36. package/dist/lib/org-render.js +59 -0
  37. package/dist/lib/poll.js +1 -1
  38. package/dist/lib/render-error.d.ts +14 -0
  39. package/dist/lib/render-error.js +30 -0
  40. package/dist/lib/response-schemas.d.ts +83 -0
  41. package/dist/lib/response-schemas.js +272 -0
  42. package/dist/lib/runs.types.d.ts +53 -8
  43. package/dist/lib/skill-nudge.d.ts +17 -0
  44. package/dist/lib/skill-nudge.js +19 -0
  45. package/dist/lib/telemetry.d.ts +90 -0
  46. package/dist/lib/telemetry.js +171 -0
  47. package/dist/lib/text-table.d.ts +14 -0
  48. package/dist/lib/text-table.js +45 -0
  49. package/dist/lib/v3-advisory.d.ts +10 -1
  50. package/dist/lib/v3-advisory.js +12 -4
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +16 -5
  54. package/schemas/plan.schema.json +61 -0
  55. package/skills/testsprite-verify.codex.md +2 -2
  56. package/skills/testsprite-verify.skill.md +3 -3
@@ -1,24 +1,28 @@
1
- import { createWriteStream, existsSync, readFileSync, readdirSync, statSync, } from 'node:fs';
1
+ import { appendFileSync, createWriteStream, existsSync, readFileSync, readdirSync, statSync, writeFileSync, } from 'node:fs';
2
2
  import { rename, stat, unlink } from 'node:fs/promises';
3
3
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { Command } from 'commander';
6
+ import { openInBrowser } from '../lib/browser.js';
6
7
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
7
- import { assertContextIntegrity, buildMeta, pickCodeExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
8
+ import { assertContextIntegrity, buildMeta, pickCodeExtension, pickVideoExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
8
9
  import { findSample, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
9
10
  import { assertJUnitReportOptions, buildJUnitReport, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
10
11
  import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
11
12
  import { globalShutdown } from '../lib/interrupt.js';
12
13
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
13
14
  import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.js';
15
+ import { VERSION } from '../version.js';
14
16
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
15
17
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
16
18
  import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
17
19
  import { RUN_SOURCES } from '../lib/runs.types.js';
18
20
  import { assertNotLocal } from '../lib/target-url.js';
21
+ import { formatTextTableRow, measureTextColumns, renderTextTable, resolveTextColumns, } from '../lib/text-table.js';
19
22
  import { createTicker } from '../lib/ticker.js';
20
23
  import { RateThrottle } from '../lib/rate-throttle.js';
21
24
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
25
+ import { emitGithubOutputs, summarizeAcceptedPayload } from '../lib/gh-output.js';
22
26
  import { loadConfig } from '../lib/config.js';
23
27
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
24
28
  /** The effective shutdown handle for a command invocation (DEV-331). */
@@ -39,6 +43,27 @@ function interruptDetachMessage(err, runIds) {
39
43
  ` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
40
44
  ` Cancel with: testsprite test cancel ${runIds.join(' ')}`);
41
45
  }
46
+ /**
47
+ * The honest-detach stderr line for a RATE_LIMITED (429) hit during a
48
+ * `--wait` poll. The backend's pre-auth rate limiter is an in-process LRU
49
+ * keyed on `request.ip`, checked before any DB contact — it can trip on a
50
+ * shared egress IP (a CI runner, a NAT) and then 429 otherwise-valid keys
51
+ * from that IP for its window. The run itself was already triggered (and is
52
+ * already billed) and keeps executing server-side regardless of this local
53
+ * poll giving up — mirrors `interruptDetachMessage` so the re-attach and
54
+ * cancel commands read identically across every detach reason.
55
+ */
56
+ function rateLimitedDetachMessage(err, runIds) {
57
+ const retrySuffix = err.retryAfterMs !== undefined
58
+ ? `; the server asked to retry after ~${Math.ceil(err.retryAfterMs / 1000)}s`
59
+ : '';
60
+ const subject = runIds.length === 1
61
+ ? `Run ${runIds[0]} is still executing on the server and will keep running (and billing) until it finishes.`
62
+ : `${runIds.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
63
+ return (`Rate limited by the server (HTTP 429)${retrySuffix}. ${subject}\n` +
64
+ ` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
65
+ ` Cancel with: testsprite test cancel ${runIds.join(' ')}`);
66
+ }
42
67
  const TEST_TYPES = ['frontend', 'backend'];
43
68
  // 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
44
69
  // tests created via `testsprite test create`, so the `--created-from cli`
@@ -86,7 +111,8 @@ export async function runList(opts, deps = {}) {
86
111
  // (exit 3) when the caller also lacks a configured key. Order matters
87
112
  // for the CLI error spec §2 — bad input is a caller bug, not an auth
88
113
  // gate.
89
- requireProjectId(opts.projectId);
114
+ const projectId = resolveProjectId(opts.projectId, deps);
115
+ requireProjectId(projectId);
90
116
  const paginationFlags = validatePaginationFlags({
91
117
  pageSize: opts.pageSize,
92
118
  startingToken: opts.startingToken,
@@ -98,13 +124,16 @@ export async function runList(opts, deps = {}) {
98
124
  // a round trip.
99
125
  validateStatusFilter(opts.status);
100
126
  const out = makeOutput(opts.output, deps);
127
+ if (opts.output === 'text') {
128
+ resolveTextColumns(opts.columns, TEST_LIST_COLUMNS);
129
+ }
101
130
  const client = makeClient(opts, deps);
102
131
  // Match P2's "explicit pageSize ⇒ single-page" convention so an
103
132
  // operator can grab one slice + cursor without auto-paging through a
104
133
  // huge project.
105
134
  const useSinglePage = opts.pageSize !== undefined && opts.maxItems === undefined;
106
135
  const baseQuery = {
107
- projectId: opts.projectId,
136
+ projectId,
108
137
  type: opts.type,
109
138
  createdFrom: opts.createdFrom,
110
139
  status: opts.status,
@@ -118,7 +147,7 @@ export async function runList(opts, deps = {}) {
118
147
  query: { ...baseQuery, pageSize, cursor },
119
148
  }), paginationFlags);
120
149
  }
121
- out.print(page, data => renderTestListText(data));
150
+ out.print(page, data => renderTestListText(data, { columns: opts.columns, noHeader: opts.noHeader }));
122
151
  return page;
123
152
  }
124
153
  export const CLI_CREATE_PRIORITIES = ['p0', 'p1', 'p2', 'p3'];
@@ -219,7 +248,8 @@ export async function runCreate(opts, deps = {}) {
219
248
  assertChainedRunKeyFits(opts.run, opts.idempotencyKey);
220
249
  // Validate inputs before touching credentials or fs — matches the
221
250
  // M2 read commands' "input gates first, then auth, then I/O" ordering.
222
- requireProjectId(opts.projectId);
251
+ const projectId = resolveProjectId(opts.projectId, deps);
252
+ requireProjectId(projectId);
223
253
  requireNonEmpty('name', opts.name);
224
254
  // P1-3: client-side length checks matching server limits (name ≤200,
225
255
  // description ≤2000) so the user gets instant, actionable errors instead
@@ -295,7 +325,7 @@ export async function runCreate(opts, deps = {}) {
295
325
  stderr(`idempotency-key: ${idempotencyKey}`);
296
326
  }
297
327
  const body = {
298
- projectId: opts.projectId,
328
+ projectId,
299
329
  type: opts.type,
300
330
  name: opts.name,
301
331
  description: opts.description,
@@ -332,7 +362,7 @@ export async function runCreate(opts, deps = {}) {
332
362
  // B3: best-effort duplicate-name advisory. Skip under --dry-run.
333
363
  if (!opts.dryRun) {
334
364
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
335
- await emitDupNameAdvisoryIfNeeded(client, opts.projectId, opts.name, stderrFn);
365
+ await emitDupNameAdvisoryIfNeeded(client, projectId, opts.name, stderrFn);
336
366
  }
337
367
  const response = await client.post('/tests', {
338
368
  body,
@@ -354,7 +384,7 @@ export async function runCreate(opts, deps = {}) {
354
384
  // R1: suppress under --dry-run (fake canned test id).
355
385
  const chainDashboardUrl = opts.dryRun
356
386
  ? undefined
357
- : resolvePortalUrl(resolveApiUrl(opts, deps), opts.projectId, response.testId);
387
+ : resolvePortalUrl(resolveApiUrl(opts, deps), projectId, response.testId);
358
388
  const createContextWithUrl = chainDashboardUrl !== undefined ? { ...response, dashboardUrl: chainDashboardUrl } : response;
359
389
  await runTestRun({
360
390
  ...opts,
@@ -379,7 +409,7 @@ export async function runCreate(opts, deps = {}) {
379
409
  // (e.g. "test_dryrun_create_2026") and a live-looking URL would mislead.
380
410
  const dashboardUrl = opts.dryRun
381
411
  ? undefined
382
- : resolvePortalUrl(resolveApiUrl(opts, deps), opts.projectId, response.testId);
412
+ : resolvePortalUrl(resolveApiUrl(opts, deps), projectId, response.testId);
383
413
  if (opts.output === 'json') {
384
414
  out.print(dashboardUrl !== undefined ? { ...response, dashboardUrl } : response, data => renderCreateText(data));
385
415
  }
@@ -590,6 +620,18 @@ function renderPlanPutText(response) {
590
620
  * 256 KB (vs. 350 KB for code) per the piece-6 spec.
591
621
  */
592
622
  function readPlanStepsFileGuarded(path) {
623
+ return assertPlanStepsShape(parsePlanStepsFile(path));
624
+ }
625
+ /**
626
+ * File I/O + JSON.parse half of `readPlanStepsFileGuarded`, split out so
627
+ * `test lint` can reuse the SAME stat/size/read/parse guards while
628
+ * substituting the collect-all `collectPlanStepsIssues` shape check for the
629
+ * throw-on-first `assertPlanStepsShape` that `test plan put` still uses. A
630
+ * failure here (missing file, oversize, invalid JSON syntax) is always a
631
+ * single fatal issue either way — there is nothing left to validate once the
632
+ * file itself can't be read or parsed.
633
+ */
634
+ function parsePlanStepsFile(path) {
593
635
  const absolute = resolveAbsolute(path);
594
636
  let stat;
595
637
  try {
@@ -629,15 +671,13 @@ function readPlanStepsFileGuarded(path) {
629
671
  const reason = err instanceof Error ? err.message : 'unknown error';
630
672
  throw localValidationError('steps', `cannot read ${path}: ${reason}`);
631
673
  }
632
- let parsed;
633
674
  try {
634
- parsed = JSON.parse(raw);
675
+ return JSON.parse(raw);
635
676
  }
636
677
  catch (err) {
637
678
  const reason = err instanceof Error ? err.message : 'unknown error';
638
679
  throw localValidationError('steps', `not valid JSON: ${reason}`);
639
680
  }
640
- return assertPlanStepsShape(parsed);
641
681
  }
642
682
  /**
643
683
  * Type-narrow + validate a parsed `{ planSteps: [...] }` envelope.
@@ -669,6 +709,59 @@ function assertPlanStepsShape(parsed) {
669
709
  }
670
710
  return stepsRaw;
671
711
  }
712
+ /**
713
+ * Collect-all counterpart to `assertPlanStepsShape` — same field checks
714
+ * (reusing the identical `requireArrayLength`/`requireEnum`/`requireString`
715
+ * helpers so wording never drifts), but continues past the first failing
716
+ * field instead of throwing. Used exclusively by `test lint`: a
717
+ * `--steps` file with several bad steps previously cost one fix-and-rerun
718
+ * cycle per step. `assertPlanStepsShape` itself is UNCHANGED and stays
719
+ * throw-on-first — `test plan put` only needs the first blocking error per
720
+ * network round-trip.
721
+ */
722
+ function collectPlanStepsIssues(parsed) {
723
+ const issues = [];
724
+ const check = (validate) => {
725
+ try {
726
+ validate();
727
+ }
728
+ catch (err) {
729
+ issues.push(toLintIssue(err));
730
+ }
731
+ };
732
+ let stepsRaw;
733
+ if (Array.isArray(parsed)) {
734
+ stepsRaw = parsed;
735
+ }
736
+ else if (typeof parsed === 'object' && parsed !== null) {
737
+ stepsRaw = parsed.planSteps;
738
+ }
739
+ else {
740
+ issues.push({ field: 'steps', reason: 'must be a JSON object with a `planSteps` array' });
741
+ return issues;
742
+ }
743
+ check(() => requireArrayLength('planSteps', stepsRaw, { min: 1, max: MAX_PLAN_STEPS, itemNoun: 'step' }));
744
+ // A length/cap violation (e.g. 201 steps, over
745
+ // MAX_PLAN_STEPS) does NOT mean there's nothing left to check — `stepsRaw`
746
+ // is still a real, iterable array, so per-element problems must be
747
+ // collected too (a 201-step file with a bad step 0 must report the cap
748
+ // issue AND planSteps[0].type/description in the SAME pass, not one or the
749
+ // other). Only bail when `stepsRaw` isn't an array at all — `requireArrayLength`'s
750
+ // structural check failed, so there is genuinely nothing to iterate.
751
+ if (!Array.isArray(stepsRaw))
752
+ return issues;
753
+ for (let i = 0; i < stepsRaw.length; i += 1) {
754
+ const step = stepsRaw[i];
755
+ if (typeof step !== 'object' || step === null || Array.isArray(step)) {
756
+ issues.push({ field: `planSteps[${i}]`, reason: 'must be an object' });
757
+ continue;
758
+ }
759
+ const s = step;
760
+ check(() => requireEnum(`planSteps[${i}].type`, s.type, PLAN_STEP_TYPES));
761
+ check(() => requireString(`planSteps[${i}].description`, s.description));
762
+ }
763
+ return issues;
764
+ }
672
765
  /**
673
766
  * `test update <test-id>` — M3.2 piece-3.
674
767
  *
@@ -960,6 +1053,84 @@ function renderBulkDeleteText(bulk) {
960
1053
  return [header, ...rows].join('\n');
961
1054
  }
962
1055
  const PLAN_STEP_TYPES = ['action', 'assertion'];
1056
+ /**
1057
+ * Public raw-content URL for
1058
+ * `schemas/plan.schema.json`, shipped in both the npm package (see
1059
+ * `package.json` `files`) and the repo. Points at the PUBLIC mirror
1060
+ * (`TestSprite/testsprite-cli`) since that's what ships to npm consumers;
1061
+ * the private atlas repo syncs to it via `scripts/make-public-snapshot.sh`.
1062
+ *
1063
+ * Pinned to the running CLI's own `v<VERSION>` git tag (the same `VERSION`
1064
+ * constant `--version` / `doctor` / the update-check registry probe already
1065
+ * read from `src/version.ts`) rather than the mutable `main` branch — a plan
1066
+ * file authored against one CLI version should resolve the SAME schema
1067
+ * forever, not whatever `main` happens to contain when the file is opened
1068
+ * months later (`main` can gain new required fields between versions).
1069
+ *
1070
+ * This is deliberately DIFFERENT from `schemas/plan.schema.json`'s own
1071
+ * internal `$id`, which stays the canonical `main` URL — `$id` is a schema
1072
+ * IDENTITY (what this document calls itself, used for cross-referencing),
1073
+ * not a fetch instruction, so it is intentionally version-independent.
1074
+ * `PLAN_SCHEMA_URL` is the fetch instruction embedded in generated plan
1075
+ * files and is intentionally version-PINNED. See DOCUMENTATION.md's "Plan
1076
+ * file format" section for the same distinction spelled out for humans.
1077
+ *
1078
+ * Caveat: the pinned tag only resolves once that version is actually
1079
+ * released — a locally-built/pre-release checkout may see a 404 until then.
1080
+ */
1081
+ export const PLAN_SCHEMA_URL = `https://raw.githubusercontent.com/TestSprite/testsprite-cli/v${VERSION}/schemas/plan.schema.json`;
1082
+ /**
1083
+ * The SINGLE canonical example plan. This
1084
+ * exact value (via `PLAN_TEMPLATE_TEXT` below) is:
1085
+ * - printed to stdout by `test create --plan-template`
1086
+ * - embedded verbatim in `test create --help` (`PLAN_TEMPLATE_HELP_TEXT`)
1087
+ * - asserted in tests against `schemas/plan.schema.json` and against
1088
+ * `assertPlanShape` so the three surfaces can't drift
1089
+ *
1090
+ * Deliberately minimal (no optional `description`/`priority`) — this is
1091
+ * the smallest shape `assertPlanShape` accepts, not a fully-annotated
1092
+ * showcase (that lives in `skills/testsprite-verify.skill.md`).
1093
+ */
1094
+ export const PLAN_TEMPLATE = {
1095
+ projectId: 'prj_abc123',
1096
+ type: 'frontend',
1097
+ name: 'Login rejects an empty password',
1098
+ planSteps: [
1099
+ {
1100
+ type: 'action',
1101
+ description: 'Navigate to /login and submit the form with an empty password',
1102
+ },
1103
+ {
1104
+ type: 'assertion',
1105
+ description: 'Verify an inline error says the password is required',
1106
+ },
1107
+ ],
1108
+ };
1109
+ /**
1110
+ * `$schema` is an ordinary extra property from `assertPlanShape`'s point of
1111
+ * view (no `additionalProperties` check exists on the plan-from path) — it
1112
+ * validates exactly like a bare `CliPlanInput` while giving editors (VS
1113
+ * Code's JSON language service, and by extension Copilot inline
1114
+ * completions) something to resolve for live validation as the file is
1115
+ * edited.
1116
+ */
1117
+ export const PLAN_TEMPLATE_WITH_SCHEMA = {
1118
+ $schema: PLAN_SCHEMA_URL,
1119
+ ...PLAN_TEMPLATE,
1120
+ };
1121
+ /**
1122
+ * Rendered once from the object above (never hand-formatted separately) so
1123
+ * `test create --plan-template`'s stdout and `test create --help`'s example
1124
+ * are generated from — not merely modeled on — the same source.
1125
+ */
1126
+ export const PLAN_TEMPLATE_TEXT = JSON.stringify(PLAN_TEMPLATE_WITH_SCHEMA, null, 2);
1127
+ /** `test create --help` after-text. Wraps `PLAN_TEMPLATE_TEXT` unmodified. */
1128
+ const PLAN_TEMPLATE_HELP_TEXT = '\nPlan file format (--plan-from <file>) — minimal valid example:\n\n' +
1129
+ `${PLAN_TEMPLATE_TEXT}\n\n` +
1130
+ 'Print this exact skeleton: testsprite test create --plan-template\n' +
1131
+ 'Validate offline (no network): testsprite test create --plan-from <file> --dry-run\n' +
1132
+ 'Multiple tests: test create-batch --plans <file.jsonl> | --plan-from-dir <dir>\n' +
1133
+ 'Full field reference: DOCUMENTATION.md -> "Plan file format"\n';
963
1134
  /**
964
1135
  * 200-step + 256 KB caps on a single plan body. The CLI
965
1136
  * enforces both client-side as a pre-flight guard so an obvious
@@ -990,6 +1161,33 @@ const MAX_BATCH_RERUN_IDS = 50;
990
1161
  * the caller can warn the operator that a shared BE producer/teardown was
991
1162
  * triggered more than once.
992
1163
  */
1164
+ /**
1165
+ * Dedupe `RerunAdvisory[]` by `feature`+`message`. Used to aggregate
1166
+ * `advisories` across chunked batch-rerun dispatch requests (initial dispatch
1167
+ * + D3 deferred-retry attempts) into a single list, and to collapse repeated
1168
+ * per-attempt advisories in `test flaky` into a single summary line.
1169
+ */
1170
+ function dedupeRerunAdvisories(entries) {
1171
+ const seen = new Map();
1172
+ for (const entry of entries) {
1173
+ seen.set(`${entry.feature}|${entry.message}`, entry);
1174
+ }
1175
+ return [...seen.values()];
1176
+ }
1177
+ /**
1178
+ * Print one `[advisory]` stderr line per entry in `advisories`. Mirrors the
1179
+ * existing style of the other rerun advisories (auto-heal engaged / not
1180
+ * applied, BE rerun history). No-op when `advisories` is absent or empty —
1181
+ * this is the common case (every V2 response, every V3 response that did not
1182
+ * request an autoHeal:false opt-out).
1183
+ */
1184
+ function emitRerunAdvisories(stderrFn, advisories) {
1185
+ if (!advisories || advisories.length === 0)
1186
+ return;
1187
+ for (const advisory of advisories) {
1188
+ stderrFn(`[advisory] ${advisory.message}`);
1189
+ }
1190
+ }
993
1191
  function dedupeBatchRerunAccepted(entries) {
994
1192
  const seen = new Map();
995
1193
  let droppedCount = 0;
@@ -1059,6 +1257,60 @@ export const BATCH_RUN_RATE_LIMIT = 50;
1059
1257
  export const BATCH_RUN_RATE_WINDOW_MS = 60_000;
1060
1258
  /** Maximum number of outer RATE_LIMITED retries inside the batch fan-out (beyond HTTP-layer retries). */
1061
1259
  export const BATCH_RUN_RATE_MAX_OUTER_RETRIES = 5;
1260
+ /**
1261
+ * Maximum number of outer RATE_LIMITED retries per member inside the multi-id
1262
+ * `test wait` fan-out (beyond HTTP-layer retries). Lower than the trigger
1263
+ * fan-out's budget on purpose: a throttled *poll* costs nothing but latency and
1264
+ * the run is already executing, so a couple of Retry-After-length backoffs is
1265
+ * enough to ride out one limiter window — burning the whole `--timeout` on
1266
+ * backoff instead of reporting the throttle would be worse than reporting it.
1267
+ */
1268
+ export const WAIT_POLL_RATE_MAX_OUTER_RETRIES = 3;
1269
+ /**
1270
+ * Backoff to honour before retrying a `RATE_LIMITED` response, in ms.
1271
+ *
1272
+ * Precedence: `ApiError.retryAfterMs` (set by `HttpClient` from the HTTP
1273
+ * `Retry-After` header, already clamped to [1s, 300s]) → `details.retryAfterSeconds`
1274
+ * from the envelope body, capped at 120s → 60s. Callers clamp the result to their
1275
+ * own remaining deadline; this function only decides "how long does the server
1276
+ * want us to wait."
1277
+ *
1278
+ * Shared by the `test run --all` trigger fan-out and the multi-id `test wait`
1279
+ * poll fan-out so the two can't drift — they were hand-copies of the same
1280
+ * precedence rule.
1281
+ */
1282
+ /**
1283
+ * Sleep that a termination signal cuts short by rejecting with the signal's
1284
+ * `InterruptError`, so the caller's existing DEV-331 catch owns the detach UX.
1285
+ *
1286
+ * Mirrors `HttpClient.sleepBeforeRetry` — an in-flight backoff must not be a
1287
+ * window where a first Ctrl-C hard-exits with empty stdout. The caller is
1288
+ * responsible for having ARMED the shutdown scope; a disarmed controller never
1289
+ * aborts its signal, so this would otherwise sleep straight through the signal.
1290
+ */
1291
+ export function sleepUntilOrInterrupt(ms, signal, sleep) {
1292
+ if (signal === undefined)
1293
+ return sleep(ms);
1294
+ if (signal.aborted)
1295
+ return Promise.reject(signal.reason);
1296
+ return new Promise((resolve, reject) => {
1297
+ const onAbort = () => reject(signal.reason);
1298
+ signal.addEventListener('abort', onAbort, { once: true });
1299
+ sleep(ms).then(() => {
1300
+ signal.removeEventListener('abort', onAbort);
1301
+ resolve();
1302
+ }, err => {
1303
+ signal.removeEventListener('abort', onAbort);
1304
+ reject(err instanceof Error ? err : new Error(String(err)));
1305
+ });
1306
+ });
1307
+ }
1308
+ export function resolveRateLimitRetryMs(err) {
1309
+ if (err.retryAfterMs !== undefined)
1310
+ return err.retryAfterMs;
1311
+ const retryAfterSec = err.getDetail('retryAfterSeconds', (v) => typeof v === 'number' && v > 0);
1312
+ return Math.min((retryAfterSec ?? 60) * 1000, 120_000);
1313
+ }
1062
1314
  /**
1063
1315
  * D3: max automatic retry attempts for deferred tests under `--wait`.
1064
1316
  * Each attempt is preceded by a Retry-After-aware sleep (server value if
@@ -1115,6 +1367,46 @@ export function isTransientRateLimit(err) {
1115
1367
  // Absent all signals → treat as permanent (credit depletion or unknown).
1116
1368
  return false;
1117
1369
  }
1370
+ /** Matches `{{ANYTHING}}`-style template placeholders in a step description. */
1371
+ const PLACEHOLDER_PATTERN = /\{\{.*?\}\}/;
1372
+ /**
1373
+ * Indices of `planSteps` whose `description` contains a
1374
+ * `{{...}}`-style placeholder. Structurally valid (schema-and-validator
1375
+ * agree these plans pass) — this is a content-quality signal, not a shape
1376
+ * violation, so it's surfaced separately as a non-fatal advisory rather
1377
+ * than folded into `assertPlanShape`.
1378
+ */
1379
+ function findPlaceholderStepIndices(plan) {
1380
+ const indices = [];
1381
+ plan.planSteps.forEach((step, i) => {
1382
+ if (PLACEHOLDER_PATTERN.test(step.description))
1383
+ indices.push(i);
1384
+ });
1385
+ return indices;
1386
+ }
1387
+ /**
1388
+ * Non-fatal `[advisory]` when one or more `planSteps[].description` values
1389
+ * contain a `{{...}}`-style placeholder — the most common false assumption
1390
+ * agent-authored plans make (that the CLI does variable substitution). The
1391
+ * CLI does none: the browser agent types the literal braces into the
1392
+ * field. Points at storing credentials on the project instead, which is
1393
+ * the actual mechanism for injecting auth into a run.
1394
+ */
1395
+ function emitPlaceholderAdvisory(plan, stderrFn) {
1396
+ const indices = findPlaceholderStepIndices(plan);
1397
+ if (indices.length === 0)
1398
+ return;
1399
+ // Each path must read
1400
+ // `planSteps[N].description` on its OWN — appending `.description` once
1401
+ // after a joined `planSteps[0], planSteps[2]` list misattributed it to
1402
+ // only the last entry.
1403
+ const paths = indices.map(i => `planSteps[${i}].description`).join(', ');
1404
+ const verb = indices.length === 1 ? 'contains' : 'contain';
1405
+ stderrFn(`[advisory] ${paths} ${verb} a ` +
1406
+ '`{{...}}`-style placeholder; the CLI does no variable substitution — ' +
1407
+ 'the browser agent will type the literal braces. Store login credentials on the project instead: ' +
1408
+ '`testsprite project update <project-id> --username <user> --password <pw>`, or Portal -> Project Settings.');
1409
+ }
1118
1410
  /**
1119
1411
  * `test create --plan-from <plan.json>` — M3.2 piece-5.
1120
1412
  *
@@ -1144,14 +1436,20 @@ export async function runCreateFromPlan(opts, deps = {}) {
1144
1436
  if (opts.targetUrl !== undefined) {
1145
1437
  assertNotLocal(opts.targetUrl);
1146
1438
  }
1147
- const plan = readPlanFromGuarded(opts.planFrom);
1439
+ const plan = readPlanFromGuarded(opts.planFrom, { ignoredFlags: opts.ignoredFlags });
1440
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1441
+ // Non-fatal advisory for `{{...}}`-style placeholders in step
1442
+ // descriptions. The CLI does no variable substitution — the browser agent
1443
+ // types the literal braces — so this is a content-quality nudge, not a
1444
+ // validation failure. Fires regardless of --dry-run (dry-run still runs
1445
+ // full local validation; this advisory is part of that same offline pass).
1446
+ emitPlaceholderAdvisory(plan, stderrFn);
1148
1447
  // The plan validated (projectId/type/name/planSteps present). Only NOW
1149
1448
  // warn that overlapping `test create` flags were ignored — emitting this
1150
1449
  // before validation made a missing-projectId failure look like the
1151
1450
  // ignored --project flag was the cause (dogfood L1778).
1152
1451
  if (opts.ignoredFlags && opts.ignoredFlags.length > 0) {
1153
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1154
- stderr(`warning: --plan-from supplies the test definition; ignoring ${opts.ignoredFlags.join(', ')}. ` +
1452
+ stderrFn(`warning: --plan-from supplies the test definition; ignoring ${opts.ignoredFlags.join(', ')}. ` +
1155
1453
  `Edit the plan JSON to change these fields.`);
1156
1454
  }
1157
1455
  // FE-only after the 2026-05-13 scope cut. The server also rejects
@@ -1170,8 +1468,7 @@ export async function runCreateFromPlan(opts, deps = {}) {
1170
1468
  }
1171
1469
  const idempotencyKey = opts.idempotencyKey ?? `cli-create-plan-${randomUUID()}`;
1172
1470
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
1173
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1174
- stderr(`idempotency-key: ${idempotencyKey}`);
1471
+ stderrFn(`idempotency-key: ${idempotencyKey}`);
1175
1472
  }
1176
1473
  const body = {
1177
1474
  projectId: plan.projectId,
@@ -1187,7 +1484,6 @@ export async function runCreateFromPlan(opts, deps = {}) {
1187
1484
  // The plan's projectId + name are available after validation above. Skip
1188
1485
  // under dry-run (no network calls); swallow all errors (advisory only).
1189
1486
  if (!opts.dryRun) {
1190
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1191
1487
  await emitDupNameAdvisoryIfNeeded(client, plan.projectId, plan.name, stderrFn);
1192
1488
  }
1193
1489
  const response = await client.post('/tests', {
@@ -1226,7 +1522,6 @@ export async function runCreateFromPlan(opts, deps = {}) {
1226
1522
  else {
1227
1523
  out.print(response, data => renderCreateText(data));
1228
1524
  if (planDashboardUrl !== undefined) {
1229
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1230
1525
  stderrFn(`Dashboard: ${planDashboardUrl}`);
1231
1526
  }
1232
1527
  }
@@ -1241,7 +1536,23 @@ export async function runCreateFromPlan(opts, deps = {}) {
1241
1536
  * obvious oversize files BEFORE loading them into V8's heap. For
1242
1537
  * plans the cap is 256 KB (vs. 350 KB for code).
1243
1538
  */
1244
- function readPlanFromGuarded(path) {
1539
+ function readPlanFromGuarded(path, context = {}) {
1540
+ return assertPlanShape(parsePlanFile(path), context);
1541
+ }
1542
+ /**
1543
+ * File I/O + JSON.parse half of `readPlanFromGuarded`, split out so `test
1544
+ * lint` can reuse the SAME stat/size/read/parse guards while
1545
+ * substituting the collect-all `collectPlanIssues` shape check for the
1546
+ * throw-on-first `assertPlanShape` that `create`/`create-batch` still use. A
1547
+ * failure here (missing file, oversize, invalid JSON syntax) is always a
1548
+ * single fatal issue either way — there is nothing left to validate once the
1549
+ * file itself can't be read or parsed.
1550
+ *
1551
+ * Stat-first guard mirrors piece-2's `readCodeFileGuarded` — reject
1552
+ * obvious oversize files BEFORE loading them into V8's heap. For
1553
+ * plans the cap is 256 KB (vs. 350 KB for code).
1554
+ */
1555
+ function parsePlanFile(path) {
1245
1556
  const absolute = resolveAbsolute(path);
1246
1557
  let stat;
1247
1558
  try {
@@ -1281,15 +1592,45 @@ function readPlanFromGuarded(path) {
1281
1592
  const reason = err instanceof Error ? err.message : 'unknown error';
1282
1593
  throw localValidationError('plan-from', `cannot read ${path}: ${reason}`);
1283
1594
  }
1284
- let parsed;
1285
1595
  try {
1286
- parsed = JSON.parse(raw);
1596
+ return JSON.parse(raw);
1287
1597
  }
1288
1598
  catch (err) {
1289
1599
  const reason = err instanceof Error ? err.message : 'unknown error';
1290
1600
  throw localValidationError('plan-from', `not valid JSON: ${reason}`);
1291
1601
  }
1292
- return assertPlanShape(parsed);
1602
+ }
1603
+ /**
1604
+ * Rethrow a validation error enriched with a note that the
1605
+ * caller's `--project`/`--type`/`--name` flag was ignored, but ONLY when
1606
+ * that flag was actually supplied. Keeps the L1778 ordering intact
1607
+ * (validation still runs, and still throws, before the general
1608
+ * ignored-flags warning in `runCreateFromPlan`) — this only changes the
1609
+ * WORDING of the validation error itself so the one hint that would
1610
+ * explain a missing-field failure lands inside the error the caller
1611
+ * already sees, instead of depending on a separate warning that (per
1612
+ * L1778) deliberately fires after validation succeeds.
1613
+ */
1614
+ function appendIgnoredFlagNote(err, flag) {
1615
+ return new ApiError({
1616
+ code: err.code,
1617
+ message: err.message,
1618
+ nextAction: `${err.nextAction} note: with --plan-from, ${flag} is ignored; all fields live inside the file.`,
1619
+ requestId: err.requestId,
1620
+ details: err.details,
1621
+ });
1622
+ }
1623
+ /** Runs `fn`, enriching any thrown `ApiError` via {@link appendIgnoredFlagNote} when `flag` was ignored. */
1624
+ function requireFieldNotIgnored(fn, flag, ignoredFlags) {
1625
+ try {
1626
+ return fn();
1627
+ }
1628
+ catch (err) {
1629
+ if (err instanceof ApiError && ignoredFlags?.includes(flag)) {
1630
+ throw appendIgnoredFlagNote(err, flag);
1631
+ }
1632
+ throw err;
1633
+ }
1293
1634
  }
1294
1635
  /**
1295
1636
  * Type-narrow + validate a parsed plan input. Pulled out so the same
@@ -1297,26 +1638,55 @@ function readPlanFromGuarded(path) {
1297
1638
  * `create-batch --plans`. Throws `VALIDATION_ERROR` with a typed
1298
1639
  * `details.field` pointer so callers can fix specific issues without
1299
1640
  * re-reading the whole file.
1641
+ *
1642
+ * `context.ignoredFlags` is populated only on the single
1643
+ * `--plan-from` path (`test create --plan-from` also received overlapping
1644
+ * `--project`/`--type`/`--name` flags); batch/dir/JSONL callers never pass
1645
+ * it, so `requireFieldNotIgnored` below is a no-op for them.
1646
+ *
1647
+ * Throw-on-first is intentional here: `create` / `create-batch` POST over
1648
+ * the network, so surfacing the first blocking error per round-trip is the
1649
+ * right cost/detail tradeoff. `test lint`'s collect-all sibling is
1650
+ * `collectPlanIssues` below — do not merge the two; the doc comment on
1651
+ * `collectPlanIssues` explains why they must stay separate.
1300
1652
  */
1301
1653
  function assertPlanShape(parsed, context = {}) {
1302
1654
  const prefix = context.specIndex !== undefined ? `specs[${context.specIndex}].` : '';
1655
+ // A top-level JSON array is the single most common
1656
+ // agent-authored mistake: a plan file holds exactly ONE test. Give it a
1657
+ // dedicated message pointing at the batch surfaces, instead of the
1658
+ // generic "must be a JSON object" (which doesn't say what to do about an
1659
+ // array).
1660
+ if (Array.isArray(parsed)) {
1661
+ throw localValidationError(`${prefix}plan`, `a plan file holds ONE test as a single JSON object (got an array of ${parsed.length}). ` +
1662
+ 'To create many tests use `test create-batch --plans <file.jsonl>` or `--plan-from-dir <dir>`', undefined, 'field');
1663
+ }
1303
1664
  // Every field below is a JSON body path inside the plan file (or
1304
1665
  // JSONL spec), not a CLI flag — pass `'field'` so the error message
1305
1666
  // says `Field \`projectId\` is invalid: ...` instead of inventing a
1306
1667
  // `--projectId` flag the user can't pass.
1307
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
1668
+ if (typeof parsed !== 'object' || parsed === null) {
1308
1669
  throw localValidationError(`${prefix}plan`, 'must be a JSON object', undefined, 'field');
1309
1670
  }
1310
1671
  const obj = parsed;
1311
- requireString(`${prefix}projectId`, obj.projectId);
1312
- requireEnum(`${prefix}type`, obj.type, ['frontend', 'backend']);
1313
- requireString(`${prefix}name`, obj.name);
1672
+ requireFieldNotIgnored(() => requireString(`${prefix}projectId`, obj.projectId), '--project', context.ignoredFlags);
1673
+ requireFieldNotIgnored(() => requireEnum(`${prefix}type`, obj.type, ['frontend', 'backend']), '--type', context.ignoredFlags);
1674
+ requireFieldNotIgnored(() => requireString(`${prefix}name`, obj.name), '--name', context.ignoredFlags);
1314
1675
  if (obj.description !== undefined && typeof obj.description !== 'string') {
1315
1676
  throw localValidationError(`${prefix}description`, 'must be a string when present', undefined, 'field');
1316
1677
  }
1317
1678
  if (obj.priority !== undefined) {
1318
1679
  requireEnum(`${prefix}priority`, obj.priority, CLI_CREATE_PRIORITIES);
1319
1680
  }
1681
+ // `planSteps` missing is the single most common agent
1682
+ // hallucination: LLMs (Copilot included) reliably nest steps under
1683
+ // `plan.steps` or a bare top-level `steps`. Point directly at the fix
1684
+ // instead of falling through to the generic "is required and must be an
1685
+ // array" message, which doesn't say WHERE the steps actually belong.
1686
+ if (obj.planSteps === undefined && (obj.plan !== undefined || obj.steps !== undefined)) {
1687
+ throw localValidationError(`${prefix}planSteps`, 'is required and must be an array. Did you mean `planSteps`? Steps live at the top level: ' +
1688
+ '`"planSteps": [{ "type": "action" | "assertion", "description": "..." }]`', undefined, 'field');
1689
+ }
1320
1690
  requireArrayLength(`${prefix}planSteps`, obj.planSteps, {
1321
1691
  min: 1,
1322
1692
  max: MAX_PLAN_STEPS,
@@ -1333,6 +1703,64 @@ function assertPlanShape(parsed, context = {}) {
1333
1703
  }
1334
1704
  return obj;
1335
1705
  }
1706
+ /**
1707
+ * Collect-all counterpart to `assertPlanShape` — same field checks (reusing
1708
+ * the identical `requireString`/`requireEnum`/`requireArrayLength` helpers
1709
+ * so wording never drifts), but continues past the first failing field
1710
+ * instead of throwing. Used exclusively by `test lint` (issue #98
1711
+ * follow-up): the throw-on-first
1712
+ * `assertPlanShape` meant a plan with 6 independent problems reported one at
1713
+ * a time across 6 fix-and-rerun cycles. `assertPlanShape` itself is
1714
+ * UNCHANGED — `create`/`create-batch` only need the first blocking error per
1715
+ * network round-trip, and duplicating the field checks here (rather than
1716
+ * threading a "collect" flag through the throw-on-first assert) keeps both
1717
+ * functions simple and matches the existing sibling-validator convention
1718
+ * already used between `assertPlanShape` and `assertPlanStepsShape`.
1719
+ */
1720
+ function collectPlanIssues(parsed, context = {}) {
1721
+ const prefix = context.specIndex !== undefined ? `specs[${context.specIndex}].` : '';
1722
+ const issues = [];
1723
+ const check = (validate) => {
1724
+ try {
1725
+ validate();
1726
+ }
1727
+ catch (err) {
1728
+ issues.push(toLintIssue(err));
1729
+ }
1730
+ };
1731
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
1732
+ issues.push({ field: `${prefix}plan`, reason: 'must be a JSON object' });
1733
+ return issues;
1734
+ }
1735
+ const obj = parsed;
1736
+ check(() => requireString(`${prefix}projectId`, obj.projectId));
1737
+ check(() => requireEnum(`${prefix}type`, obj.type, ['frontend', 'backend']));
1738
+ check(() => requireString(`${prefix}name`, obj.name));
1739
+ if (obj.description !== undefined && typeof obj.description !== 'string') {
1740
+ issues.push({ field: `${prefix}description`, reason: 'must be a string when present' });
1741
+ }
1742
+ if (obj.priority !== undefined) {
1743
+ check(() => requireEnum(`${prefix}priority`, obj.priority, CLI_CREATE_PRIORITIES));
1744
+ }
1745
+ check(() => requireArrayLength(`${prefix}planSteps`, obj.planSteps, {
1746
+ min: 1,
1747
+ max: MAX_PLAN_STEPS,
1748
+ itemNoun: 'step',
1749
+ }));
1750
+ if (Array.isArray(obj.planSteps)) {
1751
+ for (let i = 0; i < obj.planSteps.length; i += 1) {
1752
+ const step = obj.planSteps[i];
1753
+ if (typeof step !== 'object' || step === null || Array.isArray(step)) {
1754
+ issues.push({ field: `${prefix}planSteps[${i}]`, reason: 'must be an object' });
1755
+ continue;
1756
+ }
1757
+ const s = step;
1758
+ check(() => requireEnum(`${prefix}planSteps[${i}].type`, s.type, PLAN_STEP_TYPES));
1759
+ check(() => requireString(`${prefix}planSteps[${i}].description`, s.description));
1760
+ }
1761
+ }
1762
+ return issues;
1763
+ }
1336
1764
  /**
1337
1765
  * `test create-batch --plans <plans.jsonl>` — M3.2 piece-5.
1338
1766
  *
@@ -1729,14 +2157,9 @@ apiUrlForDashboard) {
1729
2157
  // MAJOR 3: use retryAfterMs from the thrown ApiError when available
1730
2158
  // (set by HttpClient from the HTTP Retry-After header, clamped to
1731
2159
  // [1s, 300s]). Fall back to details.retryAfterSeconds, then 60 s.
1732
- let retryAfterMs;
1733
- if (err.retryAfterMs !== undefined) {
1734
- retryAfterMs = err.retryAfterMs;
1735
- }
1736
- else {
1737
- const retryAfterSec = err.getDetail('retryAfterSeconds', (v) => typeof v === 'number' && v > 0);
1738
- retryAfterMs = Math.min((retryAfterSec ?? 60) * 1000, 120_000);
1739
- }
2160
+ // Extracted to `resolveRateLimitRetryMs` so the multi-id `test wait`
2161
+ // poll fan-out applies the identical precedence.
2162
+ const retryAfterMs = resolveRateLimitRetryMs(err);
1740
2163
  // MAJOR 2: clamp to remaining deadline so we don't overshoot the
1741
2164
  // --wait budget.
1742
2165
  const clampedRetryMs = Math.min(retryAfterMs, remainingMs());
@@ -1924,7 +2347,9 @@ apiUrlForDashboard) {
1924
2347
  testId: finalRun.testId,
1925
2348
  runId: finalRun.runId,
1926
2349
  status: finalRun.status,
1927
- codeVersion: finalRun.codeVersion,
2350
+ // Runs without a stored code body report `codeVersion: null`; the batch
2351
+ // envelope uses '' for "unknown", as the trigger-error paths above do.
2352
+ codeVersion: finalRun.codeVersion ?? '',
1928
2353
  videoUrl: finalRun.videoUrl,
1929
2354
  failureKind: finalRun.failureKind,
1930
2355
  };
@@ -2002,6 +2427,18 @@ apiUrlForDashboard) {
2002
2427
  : batchRunResults;
2003
2428
  out.print({ results: enrichedResults });
2004
2429
  }
2430
+ else if (!opts.wait) {
2431
+ // Text mode, no --wait: statuses are non-terminal by design ('queued'),
2432
+ // so a pass/fail summary would misread a successful dispatch as
2433
+ // "0/N passed". Report what actually happened: triggers.
2434
+ const total = batchRunResults.length;
2435
+ const erroredCount = batchRunResults.filter(r => r.error !== undefined).length;
2436
+ const parts = [`${total - erroredCount}/${total} triggered`];
2437
+ if (erroredCount > 0) {
2438
+ parts.push(`${erroredCount} trigger error${erroredCount !== 1 ? 's' : ''}`);
2439
+ }
2440
+ stderrFn(`batch-run summary: ${parts.join(', ')}`);
2441
+ }
2005
2442
  else {
2006
2443
  // Text mode: print summary line.
2007
2444
  const passed = batchRunResults.filter(r => r.status === 'passed').length;
@@ -2021,35 +2458,40 @@ apiUrlForDashboard) {
2021
2458
  parts.push(`${errored} error/timeout`);
2022
2459
  stderrFn(`batch-run summary: ${parts.join(', ')}`);
2023
2460
  }
2024
- // Determine exit code.
2025
- const allPassed = batchRunResults.every(r => r.status === 'passed');
2026
- if (allPassed)
2461
+ // Determine exit code. With --wait, success means every run reached the
2462
+ // terminal status 'passed'. Without --wait, statuses are non-terminal by
2463
+ // design ('queued' per CliBatchRunResult), so success means every trigger
2464
+ // dispatched without error — mirroring single `test run` (no --wait),
2465
+ // which exits 0 on a successful queued dispatch.
2466
+ const failing = opts.wait
2467
+ ? batchRunResults.filter(r => r.status !== 'passed')
2468
+ : batchRunResults.filter(r => r.error !== undefined);
2469
+ if (failing.length === 0)
2027
2470
  return; // exit 0
2028
- // Check for a uniform non-pass exit code across all non-passed results.
2029
- const errorExitCodes = batchRunResults
2030
- .filter(r => r.error !== undefined)
2031
- .map(r => r.error.exitCode);
2032
- const nonPassedStatuses = batchRunResults.filter(r => r.status !== 'passed');
2471
+ // Check for a uniform non-pass exit code across all failing results.
2472
+ const errorExitCodes = failing.filter(r => r.error !== undefined).map(r => r.error.exitCode);
2033
2473
  // Exit 7 only when EVERY run timed out — a mix of pass + timeout is "mixed
2034
- // outcomes" (exit 1), not "all timed out". `nonPassedStatuses.every(...)`
2474
+ // outcomes" (exit 1), not "all timed out". `failing.every(...)` alone
2035
2475
  // would incorrectly fire exit 7 when 1 of N passed and the rest timed out.
2036
- const allTimeout = batchRunResults.length > 0 &&
2476
+ const allTimeout = failing.length === batchRunResults.length &&
2037
2477
  batchRunResults.every(r => r.status === 'timeout' || r.error?.exitCode === 7);
2038
2478
  if (allTimeout) {
2039
2479
  throw new CLIError(`All ${batchRunResults.length} batch run(s) timed out after ${timeoutSeconds}s.`, 7);
2040
2480
  }
2041
- // If all non-passed results share the same specific exit code (6 or 11), use it.
2042
- if (errorExitCodes.length > 0 && errorExitCodes.length === nonPassedStatuses.length) {
2481
+ // If all failing results share the same specific exit code (6 or 11), use it.
2482
+ if (errorExitCodes.length > 0 && errorExitCodes.length === failing.length) {
2043
2483
  const uniformCode = errorExitCodes[0];
2044
2484
  if (uniformCode !== undefined &&
2045
2485
  errorExitCodes.every(c => c === uniformCode) &&
2046
2486
  uniformCode !== 1 &&
2047
2487
  uniformCode !== 7) {
2048
- throw new CLIError(`Batch run finished: ${nonPassedStatuses.length} run(s) failed with exit code ${uniformCode}.`, uniformCode);
2488
+ throw new CLIError(`Batch run finished: ${failing.length} run(s) failed with exit code ${uniformCode}.`, uniformCode);
2049
2489
  }
2050
2490
  }
2051
2491
  // Default: mixed outcomes or generic failure → exit 1.
2052
- throw new CLIError(`Batch run finished: ${batchRunResults.filter(r => r.status !== 'passed').length} of ${batchRunResults.length} run(s) did not pass.`, 1);
2492
+ throw new CLIError(opts.wait
2493
+ ? `Batch run finished: ${failing.length} of ${batchRunResults.length} run(s) did not pass.`
2494
+ : `Batch run trigger finished: ${failing.length} of ${batchRunResults.length} trigger(s) failed.`, 1);
2053
2495
  }
2054
2496
  /**
2055
2497
  * Read + parse a JSONL plans file. Per-line validation; spec-level
@@ -2597,13 +3039,33 @@ function mapRunStepToCliTestStep(step, run) {
2597
3039
  stepType: step.type,
2598
3040
  };
2599
3041
  }
3042
+ /**
3043
+ * The `test diff` exit-code contract, applied identically to a real
3044
+ * two-run comparison and the `--dry-run` canned sample: the
3045
+ * result is always printed first (`out.print` already ran by the time this
3046
+ * is called), then a `verdictChanged` diff throws so the process exits 1.
3047
+ * Before this helper existed, `--dry-run`'s early `return sample` bypassed
3048
+ * the check entirely — the canned sample has `verdictChanged: true`, so
3049
+ * `test diff --dry-run` always exited 0 even though the documented contract
3050
+ * ("Exit 0 when verdicts match, 1 when they differ") makes no dry-run
3051
+ * exception. That made the command useless for its stated CI-gate
3052
+ * pre-verification purpose.
3053
+ */
3054
+ function enforceDiffExitContract(diff) {
3055
+ if (diff.verdictChanged) {
3056
+ throw new CLIError(`verdicts differ: ${diff.runA.runId}=${diff.runA.status} vs ${diff.runB.runId}=${diff.runB.status}`, 1);
3057
+ }
3058
+ }
2600
3059
  /**
2601
3060
  * `test diff <runA> <runB>` (issue #124): isolate what regressed between two
2602
3061
  * runs, the first question when CI goes red ("what changed since the last
2603
3062
  * green run?"). Pure client-side composition of the existing per-run read
2604
3063
  * (`GET /runs/{id}?includeSteps=true`); the endpoint accepts any two run-ids,
2605
3064
  * so a cross-test pair is a WARNING, not an error. Exit 0 when the verdicts
2606
- * match, exit 1 when they differ, so the command is CI-scriptable.
3065
+ * match, exit 1 when they differ, so the command is CI-scriptable —
3066
+ * `--dry-run` honors the same contract: the canned sample has a
3067
+ * changed verdict, so `test diff --dry-run` (with no overrides) exits 1,
3068
+ * same as a real regressed pair would.
2607
3069
  */
2608
3070
  export async function runDiff(opts, deps = {}) {
2609
3071
  const out = makeOutput(opts.output, deps);
@@ -2635,6 +3097,7 @@ export async function runDiff(opts, deps = {}) {
2635
3097
  changedSteps: [{ stepIndex: 2, statusA: 'passed', statusB: 'failed' }],
2636
3098
  };
2637
3099
  out.print(sample, () => renderRunDiffText(sample));
3100
+ enforceDiffExitContract(sample);
2638
3101
  return sample;
2639
3102
  }
2640
3103
  const client = makeClient(opts, deps);
@@ -2693,10 +3156,8 @@ export async function runDiff(opts, deps = {}) {
2693
3156
  changedSteps,
2694
3157
  };
2695
3158
  out.print(diff, () => renderRunDiffText(diff));
2696
- if (diff.verdictChanged) {
2697
- // Result already printed; the typed exit makes `test diff` a CI gate.
2698
- throw new CLIError(`verdicts differ: ${runA.runId}=${runA.status} vs ${runB.runId}=${runB.status}`, 1);
2699
- }
3159
+ // Result already printed; the typed exit makes `test diff` a CI gate.
3160
+ enforceDiffExitContract(diff);
2700
3161
  return diff;
2701
3162
  }
2702
3163
  function renderRunDiffText(diff) {
@@ -2724,6 +3185,25 @@ function renderRunDiffText(diff) {
2724
3185
  }
2725
3186
  return lines.join('\n');
2726
3187
  }
3188
+ /**
3189
+ * Turn a thrown validation error into a lint issue's `field`+`reason` pair.
3190
+ * Shared by `runLint`'s file-level failures (bad path, oversize, invalid JSON
3191
+ * syntax — always a single issue, there's nothing left to validate) and the
3192
+ * collect-all `collectPlanIssues` / `collectPlanStepsIssues` helpers above
3193
+ * (one call per field, so every problem in a file is captured, not just the
3194
+ * first). Preserves the typed envelope's `details.field` / `details.reason`
3195
+ * verbatim (e.g. `planSteps[2].type`) so a caller sees the exact same pointer
3196
+ * whether the error surfaced via lint or via `create`.
3197
+ */
3198
+ function toLintIssue(err) {
3199
+ if (err instanceof ApiError) {
3200
+ return {
3201
+ field: String(err.getDetail('field') ?? '(file)'),
3202
+ reason: String(err.getDetail('reason') ?? err.nextAction ?? err.message),
3203
+ };
3204
+ }
3205
+ return { field: '(file)', reason: err instanceof Error ? err.message : String(err) };
3206
+ }
2727
3207
  /**
2728
3208
  * `test lint` (issue #98): validate plan/steps files fully OFFLINE with the
2729
3209
  * SAME validators the create paths run, but collecting EVERY problem instead
@@ -2732,6 +3212,15 @@ function renderRunDiffText(diff) {
2732
3212
  * so authoring a 12-plan directory meant one error per paid round-trip. Zero
2733
3213
  * network, zero credentials: exit 0 when everything is valid, 5 otherwise, so
2734
3214
  * it drops into a pre-commit hook or CI step before `create-batch`.
3215
+ *
3216
+ * The collection granularity used to be per-FILE, not per-PROBLEM — a single
3217
+ * plan with 6 independent field errors reported one at a time across 6
3218
+ * fix-and-rerun cycles, because each file was validated through the
3219
+ * throw-on-first `assertPlanShape`/`assertPlanStepsShape`. Every branch below
3220
+ * now separates "parse the file" (still a single fatal issue on I/O/JSON
3221
+ * failure — there's nothing left to validate) from "check the parsed shape"
3222
+ * (routed through `collectPlanIssues` / `collectPlanStepsIssues`, which
3223
+ * report every failing field in one pass).
2735
3224
  */
2736
3225
  export async function runLint(opts, deps = {}) {
2737
3226
  const out = makeOutput(opts.output, deps);
@@ -2741,38 +3230,39 @@ export async function runLint(opts, deps = {}) {
2741
3230
  }
2742
3231
  const issues = [];
2743
3232
  let checked = 0;
2744
- // Run one existing validator, converting its typed throw into a report row
2745
- // (same envelopes, so `details.field` pointers like planSteps[2].type
2746
- // survive verbatim).
2747
- const collect = (file, validate) => {
3233
+ const lintPlanFile = (file, path, specIndex) => {
2748
3234
  checked += 1;
3235
+ let parsed;
2749
3236
  try {
2750
- validate();
3237
+ parsed = parsePlanFile(path);
2751
3238
  }
2752
3239
  catch (err) {
2753
- if (err instanceof ApiError) {
2754
- issues.push({
2755
- file,
2756
- field: String(err.getDetail('field') ?? '(file)'),
2757
- reason: String(err.getDetail('reason') ?? err.nextAction ?? err.message),
2758
- });
2759
- }
2760
- else {
2761
- issues.push({
2762
- file,
2763
- field: '(file)',
2764
- reason: err instanceof Error ? err.message : String(err),
2765
- });
2766
- }
3240
+ issues.push({ file, ...toLintIssue(err) });
3241
+ return;
3242
+ }
3243
+ for (const issue of collectPlanIssues(parsed, { specIndex })) {
3244
+ issues.push({ file, ...issue });
3245
+ }
3246
+ };
3247
+ const lintStepsFile = (file, path) => {
3248
+ checked += 1;
3249
+ let parsed;
3250
+ try {
3251
+ parsed = parsePlanStepsFile(path);
3252
+ }
3253
+ catch (err) {
3254
+ issues.push({ file, ...toLintIssue(err) });
3255
+ return;
3256
+ }
3257
+ for (const issue of collectPlanStepsIssues(parsed)) {
3258
+ issues.push({ file, ...issue });
2767
3259
  }
2768
3260
  };
2769
3261
  if (opts.planFrom !== undefined) {
2770
- const planFrom = opts.planFrom;
2771
- collect(planFrom, () => void readPlanFromGuarded(planFrom));
3262
+ lintPlanFile(opts.planFrom, opts.planFrom);
2772
3263
  }
2773
3264
  else if (opts.steps !== undefined) {
2774
- const steps = opts.steps;
2775
- collect(steps, () => void readPlanStepsFileGuarded(steps));
3265
+ lintStepsFile(opts.steps, opts.steps);
2776
3266
  }
2777
3267
  else if (opts.planFromDir !== undefined) {
2778
3268
  const dir = resolveAbsolute(opts.planFromDir);
@@ -2789,12 +3279,13 @@ export async function runLint(opts, deps = {}) {
2789
3279
  throw localValidationError('plan-from-dir', 'contains no *.json plan files');
2790
3280
  }
2791
3281
  for (const entry of entries) {
2792
- collect(entry, () => void readPlanFromGuarded(join(dir, entry)));
3282
+ lintPlanFile(entry, join(dir, entry));
2793
3283
  }
2794
3284
  }
2795
3285
  else if (opts.plans !== undefined) {
2796
- // JSONL: validate PER LINE so every bad line reports (the create path's
2797
- // reader stays throw-on-first; this is the collecting counterpart).
3286
+ // JSONL: validate PER LINE, and every problem WITHIN each line (the
3287
+ // create path's reader stays throw-on-first; this is the collecting
3288
+ // counterpart, both per-line and per-field).
2798
3289
  const absolute = resolveAbsolute(opts.plans);
2799
3290
  let content;
2800
3291
  try {
@@ -2813,16 +3304,20 @@ export async function runLint(opts, deps = {}) {
2813
3304
  if (numberedLines.length === 0)
2814
3305
  throw localValidationError('plans', 'contains no plan lines');
2815
3306
  for (const { line, lineNo } of numberedLines) {
2816
- collect(`${opts.plans}:${lineNo}`, () => {
2817
- let parsed;
2818
- try {
2819
- parsed = JSON.parse(line);
2820
- }
2821
- catch {
2822
- throw localValidationError('plans', `line ${lineNo} is not valid JSON`, undefined, 'field');
2823
- }
2824
- assertPlanShape(parsed, { specIndex: lineNo - 1 });
2825
- });
3307
+ const file = `${opts.plans}:${lineNo}`;
3308
+ checked += 1;
3309
+ let parsed;
3310
+ try {
3311
+ parsed = JSON.parse(line);
3312
+ }
3313
+ catch {
3314
+ const err = localValidationError('plans', `line ${lineNo} is not valid JSON`, undefined, 'field');
3315
+ issues.push({ file, ...toLintIssue(err) });
3316
+ continue;
3317
+ }
3318
+ for (const issue of collectPlanIssues(parsed, { specIndex: lineNo - 1 })) {
3319
+ issues.push({ file, ...issue });
3320
+ }
2826
3321
  }
2827
3322
  }
2828
3323
  const filesWithIssues = new Set(issues.map(issue => issue.file)).size;
@@ -2917,6 +3412,70 @@ export async function runScaffold(opts, deps = {}) {
2917
3412
  out.print(payload, () => body.trimEnd());
2918
3413
  return payload;
2919
3414
  }
3415
+ /**
3416
+ * `test create --plan-template` — prints the canonical minimal
3417
+ * valid plan file (`PLAN_TEMPLATE_WITH_SCHEMA` / `PLAN_TEMPLATE_TEXT`,
3418
+ * defined above near `CliPlanInput`) to stdout and exits — before any of
3419
+ * `test create`'s other flag handling runs. Pure-local: no network, no
3420
+ * credentials, no filesystem I/O.
3421
+ *
3422
+ * Deliberately simpler than `test scaffold --type frontend` (which
3423
+ * substitutes a live `TESTSPRITE_PROJECT_ID` when set, and supports
3424
+ * `--out`): `--plan-template`'s job is a single deterministic ground-truth
3425
+ * document that is BYTE-IDENTICAL every invocation, because it doubles as
3426
+ * the literal example embedded in `test create --help` and the
3427
+ * fixture asserted against `schemas/plan.schema.json` in tests.
3428
+ */
3429
+ export function runPlanTemplate(opts, deps = {}) {
3430
+ const out = makeOutput(opts.output, deps);
3431
+ out.print(PLAN_TEMPLATE_WITH_SCHEMA, () => PLAN_TEMPLATE_TEXT);
3432
+ return PLAN_TEMPLATE_WITH_SCHEMA;
3433
+ }
3434
+ /**
3435
+ * `test open <test-id>` (issue #121): jump from the terminal to the test's
3436
+ * dashboard page. The CLI already computes this deep-link and prints it as
3437
+ * text on other commands; this closes the last inch (the `gh browse` /
3438
+ * `cypress open` hop). The URL is ALWAYS printed to stdout (so `--no-browser`
3439
+ * and headless use still compose), then the OS browser is spawned unless
3440
+ * --no-browser. An endpoint with no known portal mapping is a hard error
3441
+ * rather than a silent no-op.
3442
+ */
3443
+ export async function runOpen(opts, deps = {}, opener = openInBrowser) {
3444
+ const out = makeOutput(opts.output, deps);
3445
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
3446
+ if (opts.dryRun) {
3447
+ emitDryRunBanner(stderrFn);
3448
+ // Derive the sample through the SAME resolver as the live path (against
3449
+ // the canonical prod endpoint and the dry-run project id) so the two can
3450
+ // never drift; the ?? arm is unreachable for the prod mapping but keeps
3451
+ // the type total.
3452
+ const sample = {
3453
+ dashboardUrl: resolvePortalUrl('https://api.testsprite.com', 'p_dryrun_2026', opts.testId) ??
3454
+ `https://www.testsprite.com/dashboard/tests/p_dryrun_2026/test/${encodeURIComponent(opts.testId)}`,
3455
+ };
3456
+ out.print(sample, data => data.dashboardUrl);
3457
+ return sample;
3458
+ }
3459
+ const client = makeClient(opts, deps);
3460
+ // The deep-link needs the projectId; the test record is the source of truth.
3461
+ const test = await client.get(`/tests/${encodeURIComponent(opts.testId)}`);
3462
+ const dashboardUrl = resolvePortalUrl(resolveApiUrl(opts, deps), test.projectId, opts.testId);
3463
+ if (dashboardUrl === undefined) {
3464
+ throw new CLIError(`no dashboard mapping for this API endpoint; set TESTSPRITE_PORTAL_URL to your Portal origin`, 1);
3465
+ }
3466
+ out.print({ dashboardUrl }, () => dashboardUrl);
3467
+ if (!opts.noBrowser) {
3468
+ try {
3469
+ opener(dashboardUrl);
3470
+ }
3471
+ catch {
3472
+ // The URL is already on stdout; a missing opener (containers, minimal
3473
+ // hosts) downgrades to "open it yourself" instead of a hard failure.
3474
+ stderrFn('could not launch a browser; open the URL above manually (or use --no-browser)');
3475
+ }
3476
+ }
3477
+ return { dashboardUrl };
3478
+ }
2920
3479
  export async function runSteps(opts, deps = {}) {
2921
3480
  const out = makeOutput(opts.output, deps);
2922
3481
  const client = makeClient(opts, deps);
@@ -3070,6 +3629,9 @@ export async function runResultHistory(opts, deps = {}) {
3070
3629
  throw localValidationError('page-size', 'must be between 1 and 100');
3071
3630
  }
3072
3631
  }
3632
+ if (opts.output === 'text') {
3633
+ resolveTextColumns(opts.columns, RUN_HISTORY_TABLE_COLUMNS);
3634
+ }
3073
3635
  const client = makeClient(opts, deps);
3074
3636
  const pageSize = opts.pageSize ?? 20;
3075
3637
  const sinceIso = opts.since !== undefined ? parseDuration(opts.since) : undefined;
@@ -3079,9 +3641,14 @@ export async function runResultHistory(opts, deps = {}) {
3079
3641
  source: opts.source,
3080
3642
  since: sinceIso,
3081
3643
  });
3082
- if (opts.output === 'json') {
3083
- out.print({ runs: resp.runs, nextCursor: resp.nextCursor }, data => JSON.stringify(data));
3084
- return resp;
3644
+ // Client-side rerun filter (--rerun / --no-rerun). isRerun is on every row;
3645
+ // the backend has no rerun filter. Undefined → no filter. Like --source, a
3646
+ // filtered page can be short/empty while more history exists — the empty-page
3647
+ // and short-page hints below cover that.
3648
+ const runs = opts.rerun === undefined ? resp.runs : resp.runs.filter(r => r.isRerun === opts.rerun);
3649
+ if (opts.output !== 'text') {
3650
+ out.print({ runs, nextCursor: resp.nextCursor }, data => JSON.stringify(data));
3651
+ return { ...resp, runs };
3085
3652
  }
3086
3653
  // Text mode rendering
3087
3654
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
@@ -3090,7 +3657,7 @@ export async function runResultHistory(opts, deps = {}) {
3090
3657
  // backend filters AFTER limiting rows (limit-before-filter). Matching runs
3091
3658
  // may exist on later pages — surface the cursor instead of reporting
3092
3659
  // "no history".
3093
- if (resp.runs.length === 0) {
3660
+ if (runs.length === 0) {
3094
3661
  if (resp.nextCursor !== null) {
3095
3662
  // Filtered-empty page, but more pages exist: prompt user to paginate.
3096
3663
  const msg = `No matching runs on this page (filters skipped all entries), but more history exists.\n` +
@@ -3111,7 +3678,7 @@ export async function runResultHistory(opts, deps = {}) {
3111
3678
  return resp;
3112
3679
  }
3113
3680
  const lines = [];
3114
- lines.push(renderRunHistoryTable(resp.runs));
3681
+ lines.push(renderRunHistoryTable(runs, { columns: opts.columns, noHeader: opts.noHeader }));
3115
3682
  // Footer: pointer to per-run detail commands.
3116
3683
  lines.push('');
3117
3684
  lines.push('Per-run detail: testsprite test wait <run-id>');
@@ -3124,19 +3691,24 @@ export async function runResultHistory(opts, deps = {}) {
3124
3691
  out.print(lines.join('\n'), d => d);
3125
3692
  // Short-filtered-page hint: non-null nextCursor even though this page was
3126
3693
  // shorter than requested — "none in THIS window" does not mean end-of-history.
3127
- if (resp.nextCursor !== null && resp.runs.length < pageSize) {
3694
+ if (resp.nextCursor !== null && runs.length < pageSize) {
3128
3695
  stderr(`[hint] Fewer than ${pageSize} rows returned but more may exist — ` +
3129
- `source filter skipped some entries. Pass --cursor ${resp.nextCursor} to continue.`);
3696
+ `a source/rerun filter skipped some entries. Pass --cursor ${resp.nextCursor} to continue.`);
3130
3697
  }
3131
- return resp;
3698
+ return { ...resp, runs };
3132
3699
  }
3133
- const RUN_HISTORY_TABLE_COL_WIDTHS = {
3134
- runId: 36,
3135
- status: 10,
3136
- source: 18,
3137
- rerun: 6,
3138
- when: 25,
3139
- };
3700
+ const RUN_HISTORY_TABLE_COLUMNS = [
3701
+ { header: 'RUN ID', width: 36, render: run => run.runId },
3702
+ { header: 'STATUS', width: 10, render: run => run.status },
3703
+ { header: 'SOURCE', width: 18, render: run => run.source },
3704
+ { header: 'RERUN?', width: 6, render: run => (run.isRerun ? 'yes' : 'no') },
3705
+ { header: 'WHEN', width: 25, render: run => run.createdAt },
3706
+ {
3707
+ header: 'DURATION',
3708
+ width: 0,
3709
+ render: run => formatDurationMs(run.startedAt ?? run.createdAt, run.finishedAt),
3710
+ },
3711
+ ];
3140
3712
  /**
3141
3713
  * Max width of the `test steps` DESCRIPTION column in text mode. Long /
3142
3714
  * multi-line step descriptions are collapsed to one line and truncated to
@@ -3168,56 +3740,29 @@ const HISTORY_TARGET_URL_MAX = 80;
3168
3740
  * run row (truncated to `HISTORY_TARGET_URL_MAX` chars). The table columns
3169
3741
  * are left intact to avoid width blow-out on terminals.
3170
3742
  */
3171
- function renderRunHistoryTable(runs) {
3172
- const cols = RUN_HISTORY_TABLE_COL_WIDTHS;
3173
- const header = [
3174
- padEnd('RUN ID', cols.runId),
3175
- padEnd('STATUS', cols.status),
3176
- padEnd('SOURCE', cols.source),
3177
- padEnd('RERUN?', cols.rerun),
3178
- padEnd('WHEN', cols.when),
3179
- 'DURATION',
3180
- ].join(' ');
3181
- const sep = '-'.repeat(header.length);
3182
- const rows = runs.flatMap(r => {
3183
- // FE runs never populate `startedAt` today — the RUNNING heartbeat
3184
- // that would set it doesn't fire on the legacy/sync execution path
3185
- // (dogfood 2026-06-04), so without a fallback DURATION was always
3186
- // "—" for every FE run. Fall back to `createdAt` so the column shows
3187
- // wall-clock from trigger to finish; on sync dev the queue gap is
3188
- // ~0, and `--output json` still exposes raw startedAt/finishedAt for
3189
- // consumers that need to exclude queue time.
3190
- const duration = formatDurationMs(r.startedAt ?? r.createdAt, r.finishedAt);
3191
- const mainRow = [
3192
- padEnd(r.runId, cols.runId),
3193
- padEnd(r.status, cols.status),
3194
- padEnd(r.source, cols.source),
3195
- padEnd(r.isRerun ? 'yes' : 'no', cols.rerun),
3196
- padEnd(r.createdAt, cols.when),
3197
- duration,
3198
- ].join(' ');
3199
- // G1b: surface per-run targetUrl as an indented sub-line.
3200
- // Render only when truthy (skip null, undefined, empty) and when the
3201
- // source is not 'unresolved' (that would mean "backend couldn't resolve
3202
- // a URL" — printing "—" is less informative than omitting the line).
3743
+ function renderRunHistoryTable(runs, options = {}) {
3744
+ const selectedColumns = resolveTextColumns(options.columns, RUN_HISTORY_TABLE_COLUMNS);
3745
+ const widths = measureTextColumns(runs, selectedColumns);
3746
+ const customColumns = options.columns !== undefined && options.columns.trim() !== '';
3747
+ const includeDetailLines = !customColumns;
3748
+ const header = formatTextTableRow(selectedColumns.map(column => column.header), widths);
3749
+ const rows = runs.flatMap(run => {
3750
+ const mainRow = formatTextTableRow(selectedColumns.map(column => column.render(run)), widths);
3203
3751
  const lines = [mainRow];
3204
- if (r.targetUrl && r.targetUrlSource !== 'unresolved') {
3205
- const url = r.targetUrl.length > HISTORY_TARGET_URL_MAX
3206
- ? `${r.targetUrl.slice(0, HISTORY_TARGET_URL_MAX - 1)}…`
3207
- : r.targetUrl;
3752
+ if (includeDetailLines && run.targetUrl && run.targetUrlSource !== 'unresolved') {
3753
+ const url = run.targetUrl.length > HISTORY_TARGET_URL_MAX
3754
+ ? `${run.targetUrl.slice(0, HISTORY_TARGET_URL_MAX - 1)}…`
3755
+ : run.targetUrl;
3208
3756
  lines.push(` targetUrl: ${url}`);
3209
3757
  }
3210
- else if (r.targetUrlSource === 'unresolved') {
3758
+ else if (includeDetailLines && run.targetUrlSource === 'unresolved') {
3211
3759
  lines.push(` targetUrl: —`);
3212
3760
  }
3213
3761
  return lines;
3214
3762
  });
3215
- return [header, sep, ...rows].join('\n');
3216
- }
3217
- function padEnd(s, width) {
3218
- if (s.length >= width)
3219
- return s;
3220
- return s + ' '.repeat(width - s.length);
3763
+ if (options.noHeader === true)
3764
+ return rows.join('\n');
3765
+ return [header, '-'.repeat(header.length), ...rows].join('\n');
3221
3766
  }
3222
3767
  function formatDurationMs(startedAt, finishedAt) {
3223
3768
  if (!startedAt || !finishedAt)
@@ -3402,8 +3947,11 @@ function backendResultToRunResponse(result, run) {
3402
3947
  retryAfterSeconds: undefined,
3403
3948
  startedAt: result.startedAt ?? run.startedAt,
3404
3949
  finishedAt: result.finishedAt ?? run.finishedAt,
3405
- codeVersion: run.codeVersion || (result.codeVersion ?? ''),
3406
- targetUrl: run.targetUrl || (result.targetUrl ?? ''),
3950
+ // Neither side having a value stays null (not ''), so the text renderer
3951
+ // omits the line instead of printing a label with nothing after it. A
3952
+ // backend run legitimately has no target URL at all.
3953
+ codeVersion: run.codeVersion || result.codeVersion || null,
3954
+ targetUrl: run.targetUrl || result.targetUrl || null,
3407
3955
  // createdFrom / projectId / userId / runId / testId / source / createdAt
3408
3956
  // inherited from the polled run row via the spread above.
3409
3957
  failedStepIndex: result.failedStepIndex,
@@ -3521,13 +4069,34 @@ function printRunOrChain(out, payload, createContext, textRenderer) {
3521
4069
  });
3522
4070
  }
3523
4071
  /**
3524
- * Enrich a terminal RunResponse with a client-synthesized Portal deep link.
3525
- * Emitted only when the wire row carries both projectId and testId (the BE
3526
- * testId-fallback path synthesizes rows with an empty projectId — those stay
3527
- * unenriched) and the API endpoint maps to a known portal host
3528
- * (`resolvePortalUrl` returns undefined otherwise).
4072
+ * Attach the Portal deep link to a terminal RunResponse.
4073
+ *
4074
+ * **A server-provided `dashboardUrl` always wins.** The backend knows two
4075
+ * things this process cannot:
4076
+ *
4077
+ * - **Which store answered.** For a run served from V3 Postgres the
4078
+ * `/dashboard/tests/…` route we would template reads DynamoDB only, and a
4079
+ * CLI-created project under the V3-native write path has no DynamoDB row at
4080
+ * all — so our link is not merely org-less, it cannot render. The server
4081
+ * sends the V3 test-case page instead, scoped to the workspace that owns the
4082
+ * run.
4083
+ * - **The portal origin for this environment.** `resolvePortalUrl` maps only
4084
+ * the prod host, so against any other endpoint it returns undefined and we
4085
+ * print nothing. The server reads its own `PORTAL_URL`.
4086
+ *
4087
+ * The client computation stays as the fallback so an older backend (no field)
4088
+ * behaves exactly as before, and so does a V2-served run whose server link the
4089
+ * backend chose not to emit.
3529
4090
  */
3530
4091
  function withRunDashboardUrl(run, apiUrl) {
4092
+ // A server value of `null` is meaningful, not missing: it says "there is no
4093
+ // correct link for this run" (e.g. a workspace-scoped page the environment's
4094
+ // portal build does not serve yet). Falling back to our own guess there would
4095
+ // reintroduce exactly the wrong link the server declined to send — so only an
4096
+ // ABSENT field (older backend) reopens the client path.
4097
+ if ('dashboardUrl' in run) {
4098
+ return run.dashboardUrl ? run : { ...run, dashboardUrl: undefined };
4099
+ }
3531
4100
  if (!run.projectId || !run.testId)
3532
4101
  return run;
3533
4102
  const dashboardUrl = resolvePortalUrl(apiUrl, run.projectId, run.testId);
@@ -3731,7 +4300,7 @@ export async function runTestRun(opts, deps = {}) {
3731
4300
  throw new ApiError({
3732
4301
  code: 'CONFLICT',
3733
4302
  message: `Conflict: another run for this test is in flight against a different ` +
3734
- `target URL (${inFlightRun.targetUrl}). Your --target-url ${opts.targetUrl} ` +
4303
+ `target URL (${inFlightRun.targetUrl ?? 'not reported'}). Your --target-url ${opts.targetUrl} ` +
3735
4304
  `cannot attach to that run. Wait for it to finish ` +
3736
4305
  `(\`testsprite test wait ${currentRunId}\`) or retry your trigger when ` +
3737
4306
  `the test is free.`,
@@ -3753,8 +4322,9 @@ export async function runTestRun(opts, deps = {}) {
3753
4322
  runId: currentRunId,
3754
4323
  status: 'queued',
3755
4324
  enqueuedAt: new Date().toISOString(),
3756
- codeVersion: inFlightRun.codeVersion,
3757
- targetUrl: inFlightRun.targetUrl,
4325
+ codeVersion: inFlightRun.codeVersion ?? '',
4326
+ // The check above proved the in-flight run targets exactly this URL.
4327
+ targetUrl: opts.targetUrl,
3758
4328
  };
3759
4329
  }
3760
4330
  else {
@@ -3912,6 +4482,38 @@ export async function runTestRun(opts, deps = {}) {
3912
4482
  `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
3913
4483
  throw err;
3914
4484
  }
4485
+ // RATE_LIMITED during polling — the backend's pre-auth rate limiter can
4486
+ // trip on a shared egress IP (CI runner, NAT) and 429 an otherwise-valid
4487
+ // key for its window; the HTTP layer already retried internally and gave
4488
+ // up. The run was already triggered (and billed) and keeps executing
4489
+ // server-side, so this must not be a silent, runId-less death: same
4490
+ // partial-envelope contract as the RequestTimeoutError branch above, and
4491
+ // the SAME thrown ApiError is rethrown unchanged so its native exit code
4492
+ // (11) is preserved — never reclassified to 7.
4493
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
4494
+ ticker.finalize(`Run ${triggerResponse.runId} — rate limited by the server`);
4495
+ const partial = {
4496
+ runId: triggerResponse.runId,
4497
+ status: 'running',
4498
+ enqueuedAt: triggerResponse.enqueuedAt,
4499
+ codeVersion: triggerResponse.codeVersion,
4500
+ targetUrl: triggerResponse.targetUrl || null,
4501
+ };
4502
+ printRunOrChain(out, partial, opts.createContext, data => {
4503
+ const p = data;
4504
+ const lines = [
4505
+ `runId ${p.runId}`,
4506
+ `status ${p.status} (rate limited by the server)`,
4507
+ ];
4508
+ if (p.targetUrl)
4509
+ lines.push(`targetUrl ${p.targetUrl}`);
4510
+ lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4511
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4512
+ return lines.join('\n');
4513
+ });
4514
+ stderrFn(rateLimitedDetachMessage(err, [triggerResponse.runId]));
4515
+ throw err;
4516
+ }
3915
4517
  // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
3916
4518
  // envelope shape as the timeout paths so stdout stays parseable, plus the
3917
4519
  // honest "keeps running and billing" stderr line. Rethrow → index.ts
@@ -3998,50 +4600,100 @@ export async function runTestWaitMany(opts, deps = {}) {
3998
4600
  }
3999
4601
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
4000
4602
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
4603
+ const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
4001
4604
  // One shared deadline across every member (the whole point of the shared
4002
4605
  // pool: `--timeout 600` means the invocation ends within ~600s, not
4003
4606
  // 600s x ceil(N/concurrency)).
4004
4607
  const deadlineMs = Date.now() + opts.timeoutSeconds * 1000;
4005
4608
  const pollOne = async (runId) => {
4006
- // A member dequeued AFTER the shared deadline has passed must not be
4007
- // granted a fresh minimum poll window (with --max-concurrency 1 that
4008
- // would extend the invocation by ~1s per queued run past --timeout).
4009
- const remainingSeconds = Math.ceil((deadlineMs - Date.now()) / 1000);
4010
- if (remainingSeconds <= 0)
4011
- return { kind: 'timeout' };
4012
4609
  const resolveAlternate = makeBackendWaitFallback({
4013
4610
  client,
4014
4611
  resolveTestId: run => run.testId,
4015
4612
  resolveNotBefore: run => run.createdAt,
4016
4613
  onResolved: () => undefined,
4017
4614
  });
4018
- try {
4019
- const run = await pollRunUntilTerminal(client, runId, {
4020
- timeoutSeconds: remainingSeconds,
4021
- sleep: deps.sleep,
4022
- shutdown: shutdownOf(deps),
4023
- onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4024
- onTick: (run, elapsedMs) => {
4025
- const elapsed = Math.round(elapsedMs / 1000);
4026
- ticker.update(`Run ${run.runId} — ${run.status} (elapsed=${elapsed}s)`);
4027
- },
4028
- resolveAlternate,
4029
- });
4030
- return { kind: 'result', run };
4031
- }
4032
- catch (err) {
4033
- if (err instanceof TimeoutError)
4615
+ // Outer RATE_LIMITED retry, per member. `http.ts` already retries a 429
4616
+ // internally (`MAX_ATTEMPTS_RATE_LIMITED`), so reaching this catch means the
4617
+ // transport gave up — but a shared-egress 429 (CI runner / NAT tripping the
4618
+ // backend's ip-keyed pre-auth limiter) is a property of the *window*, not of
4619
+ // this run, and the run is still executing. Without this loop a single 429
4620
+ // ended the whole member's wait, which is what made a healthy run report as
4621
+ // a poll error. Mirrors the `test run --all` trigger fan-out's outer loop
4622
+ // (`BATCH_RUN_RATE_MAX_OUTER_RETRIES`), including its two invariants: the
4623
+ // sleep is clamped to the SHARED deadline (so a retry can never stretch
4624
+ // `--timeout`), and the retry is per member — one throttled run does not
4625
+ // stall the pool, because each lane runs this loop inside its own task.
4626
+ let rateLimitAttempt = 0;
4627
+ for (;;) {
4628
+ // A member dequeued AFTER the shared deadline has passed must not be
4629
+ // granted a fresh minimum poll window (with --max-concurrency 1 that
4630
+ // would extend the invocation by ~1s per queued run past --timeout).
4631
+ // Re-evaluated on every iteration so a retry obeys the same rule.
4632
+ const remainingSeconds = Math.ceil((deadlineMs - Date.now()) / 1000);
4633
+ if (remainingSeconds <= 0)
4034
4634
  return { kind: 'timeout' };
4035
- if (err instanceof RequestTimeoutError)
4036
- throw err;
4037
- // Interrupt must reject the fan-out (handled at the collect point), not
4038
- // be flattened into a per-member 'error' outcome that would swallow the
4039
- // 128+signum exit (DEV-331).
4040
- if (err instanceof InterruptError)
4041
- throw err;
4042
- if (err instanceof ApiError)
4043
- return { kind: 'error', code: err.code, exitCode: err.exitCode };
4044
- return { kind: 'error', code: 'TRANSPORT', exitCode: 10 };
4635
+ try {
4636
+ const run = await pollRunUntilTerminal(client, runId, {
4637
+ timeoutSeconds: remainingSeconds,
4638
+ sleep: deps.sleep,
4639
+ shutdown: shutdownOf(deps),
4640
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4641
+ onTick: (run, elapsedMs) => {
4642
+ const elapsed = Math.round(elapsedMs / 1000);
4643
+ ticker.update(`Run ${run.runId} — ${run.status} (elapsed=${elapsed}s)`);
4644
+ },
4645
+ resolveAlternate,
4646
+ });
4647
+ return { kind: 'result', run };
4648
+ }
4649
+ catch (err) {
4650
+ if (err instanceof TimeoutError)
4651
+ return { kind: 'timeout' };
4652
+ if (err instanceof RequestTimeoutError)
4653
+ throw err;
4654
+ // Interrupt must reject the fan-out (handled at the collect point), not
4655
+ // be flattened into a per-member 'error' outcome that would swallow the
4656
+ // 128+signum exit (DEV-331).
4657
+ if (err instanceof InterruptError)
4658
+ throw err;
4659
+ if (err instanceof ApiError) {
4660
+ // `isTransientRateLimit` is the second gate, for an "unknown" 429 that
4661
+ // carries neither a Retry-After nor the per-minute wording: treat it as
4662
+ // permanent rather than burn the budget on it. (The credit-depletion
4663
+ // 429 never reaches here at all — `errors.ts` re-maps that envelope to
4664
+ // INSUFFICIENT_CREDITS before this catch sees it.)
4665
+ if (err.code === 'RATE_LIMITED' &&
4666
+ isTransientRateLimit(err) &&
4667
+ rateLimitAttempt < WAIT_POLL_RATE_MAX_OUTER_RETRIES) {
4668
+ rateLimitAttempt++;
4669
+ const retryAfterMs = resolveRateLimitRetryMs(err);
4670
+ const clampedRetryMs = Math.min(retryAfterMs, deadlineMs - Date.now());
4671
+ // Deadline already reached: the wait budget genuinely ran out, so the
4672
+ // honest outcome is `timeout` — the same call the trigger fan-out
4673
+ // makes ("Timed out … during rate-limit backoff"). Reporting the 429
4674
+ // instead would let the exit-11 escalation below claim "nothing else
4675
+ // went wrong" for an invocation that in fact exhausted `--timeout`.
4676
+ if (clampedRetryMs <= 0)
4677
+ return { kind: 'timeout' };
4678
+ stderrFn(`[wait] ${runId} — rate limited (attempt ${rateLimitAttempt}/${WAIT_POLL_RATE_MAX_OUTER_RETRIES}): retrying in ${Math.ceil(clampedRetryMs / 1000)}s`);
4679
+ // Arm the graceful-detach scope across the backoff. `pollRunUntilTerminal`
4680
+ // disarms in its own `finally`, so without this the sleep is a window
4681
+ // where a first Ctrl-C hard-exits instead of taking the DEV-331 detach
4682
+ // path (partial `{runId, status:'running'}` on stdout + honest hint).
4683
+ const shutdown = shutdownOf(deps);
4684
+ const disarm = shutdown.arm();
4685
+ try {
4686
+ await sleepUntilOrInterrupt(clampedRetryMs, shutdown.signal, sleepFn);
4687
+ }
4688
+ finally {
4689
+ disarm();
4690
+ }
4691
+ continue;
4692
+ }
4693
+ return { kind: 'error', code: err.code, exitCode: err.exitCode };
4694
+ }
4695
+ return { kind: 'error', code: 'TRANSPORT', exitCode: 10 };
4696
+ }
4045
4697
  }
4046
4698
  };
4047
4699
  const outcomes = new Map();
@@ -4145,6 +4797,32 @@ export async function runTestWaitMany(opts, deps = {}) {
4145
4797
  if (authError !== undefined && authError.kind === 'error') {
4146
4798
  throw new CLIError(`Multi-run wait: authentication failed (${authError.code})`, authError.exitCode);
4147
4799
  }
4800
+ // Rate limiting escalates the same way auth does, for the same reason: when it
4801
+ // is the ONLY thing that went wrong, exit 7 ("timeout or per-member poll
4802
+ // error") is actively misleading — nothing timed out and no run misbehaved, the
4803
+ // client was throttled — and 7 tells an automated caller to re-attach
4804
+ // immediately, which walks straight back into the limiter. Exit 11 says "back
4805
+ // off, then re-attach", which is the correct action. Deliberately narrow: it
4806
+ // requires that EVERY non-passed member is a rate-limited poll error, so a real
4807
+ // timeout or a genuinely failed run is never masked (those keep 7 / 1). By this
4808
+ // point each member has already spent its `WAIT_POLL_RATE_MAX_OUTER_RETRIES`
4809
+ // Retry-After backoffs, so this is a persistently throttled window, not a blip.
4810
+ // `outcomes` is keyed by runId, so a REPEATED id has one shared entry that the
4811
+ // last lane to finish overwrites — a genuine `failed` can be replaced by a
4812
+ // later RATE_LIMITED, which would make the counts below claim "nothing else
4813
+ // went wrong" for an invocation that observed a failure. Rather than change the
4814
+ // long-standing one-row-per-input-id output shape, the escalation simply
4815
+ // declines to fire when the caller passed a duplicate; exit 7 is then the same
4816
+ // answer as before this change.
4817
+ const idsAreUnique = new Set(opts.runIds).size === opts.runIds.length;
4818
+ const rateLimitedOnly = idsAreUnique &&
4819
+ errors > 0 &&
4820
+ timedOut === 0 &&
4821
+ failed === 0 &&
4822
+ [...outcomes.values()].every(o => o.kind !== 'error' || o.code === 'RATE_LIMITED');
4823
+ if (rateLimitedOnly) {
4824
+ throw new CLIError(`Multi-run wait: rate limited on ${errors} of ${results.length} runs — back off and re-attach with: testsprite test wait ${unfinishedIds.join(' ')}`, 11);
4825
+ }
4148
4826
  if (timedOut > 0 || errors > 0) {
4149
4827
  throw new CLIError(`Multi-run wait: ${timedOut} timed out, ${errors} poll error(s) out of ${results.length} runs`, 7);
4150
4828
  }
@@ -4390,6 +5068,26 @@ export async function runTestWait(opts, deps = {}) {
4390
5068
  `Re-attach with: testsprite test wait ${opts.runId}, or cancel with: testsprite test cancel ${opts.runId}`);
4391
5069
  throw err;
4392
5070
  }
5071
+ // RATE_LIMITED during polling — see the matching comment in runTestRun.
5072
+ // The HTTP layer already retried internally and gave up; the run keeps
5073
+ // executing (and billing) server-side, so this must emit the same
5074
+ // partial-envelope + honest hint as the timeout/interrupt paths. The SAME
5075
+ // ApiError is rethrown unchanged so its native exit code (11) is kept.
5076
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
5077
+ ticker.finalize(`Run ${opts.runId} — rate limited by the server`);
5078
+ const partial = { runId: opts.runId, status: 'running' };
5079
+ out.print(partial, data => {
5080
+ const p = data;
5081
+ return [
5082
+ `runId ${p.runId}`,
5083
+ `status ${p.status} (rate limited by the server)`,
5084
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
5085
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
5086
+ ].join('\n');
5087
+ });
5088
+ stderrFn(rateLimitedDetachMessage(err, [opts.runId]));
5089
+ throw err;
5090
+ }
4393
5091
  // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
4394
5092
  if (err instanceof InterruptError) {
4395
5093
  ticker.finalize(`Run ${opts.runId} — interrupted (${err.signal})`);
@@ -4450,7 +5148,8 @@ async function writeBatchJUnitReportIfRequested(opts, results) {
4450
5148
  */
4451
5149
  export async function runTestRunAll(opts, deps = {}) {
4452
5150
  assertIdempotencyKey(opts.idempotencyKey);
4453
- requireProjectId(opts.projectId);
5151
+ const projectId = resolveProjectId(opts.projectId, deps);
5152
+ requireProjectId(projectId);
4454
5153
  if (!Number.isInteger(opts.maxConcurrency) ||
4455
5154
  opts.maxConcurrency < 1 ||
4456
5155
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
@@ -4477,7 +5176,7 @@ export async function runTestRunAll(opts, deps = {}) {
4477
5176
  method: 'POST',
4478
5177
  path: '/api/cli/v1/tests/batch/run',
4479
5178
  body: {
4480
- projectId: opts.projectId,
5179
+ projectId,
4481
5180
  testIds: opts.nameFilter ? ['<filtered by --filter>'] : undefined,
4482
5181
  source: 'cli',
4483
5182
  },
@@ -4500,9 +5199,9 @@ export async function runTestRunAll(opts, deps = {}) {
4500
5199
  const batchPortalBase = resolvePortalBase(batchApiUrl);
4501
5200
  const projectDashboardUrl = batchPortalBase === undefined
4502
5201
  ? undefined
4503
- : `${batchPortalBase}/dashboard/tests/${encodeURIComponent(opts.projectId)}`;
5202
+ : `${batchPortalBase}/dashboard/tests/${encodeURIComponent(projectId)}`;
4504
5203
  const withBatchDashboardUrl = (item) => {
4505
- const dashboardUrl = resolvePortalUrl(batchApiUrl, opts.projectId, item.testId);
5204
+ const dashboardUrl = resolvePortalUrl(batchApiUrl, projectId, item.testId);
4506
5205
  return dashboardUrl !== undefined ? { ...item, dashboardUrl } : item;
4507
5206
  };
4508
5207
  const idempotencyKey = opts.idempotencyKey ?? `cli-batch-run-fresh-${randomUUID()}`;
@@ -4514,7 +5213,7 @@ export async function runTestRunAll(opts, deps = {}) {
4514
5213
  if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
4515
5214
  // We need to resolve the full test set to apply the name filter.
4516
5215
  const allPage = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
4517
- query: { projectId: opts.projectId, pageSize, cursor },
5216
+ query: { projectId, pageSize, cursor },
4518
5217
  }), {});
4519
5218
  const needle = opts.nameFilter.toLowerCase();
4520
5219
  const filtered = allPage.items.filter(t => t.name.toLowerCase().includes(needle));
@@ -4525,7 +5224,7 @@ export async function runTestRunAll(opts, deps = {}) {
4525
5224
  }
4526
5225
  testIds = filtered.map(t => t.id);
4527
5226
  if (testIds.length === 0) {
4528
- stderrFn(`No tests found in project ${opts.projectId} matching --filter "${opts.nameFilter}" — nothing to run.`);
5227
+ stderrFn(`No tests found in project ${projectId} matching --filter "${opts.nameFilter}" — nothing to run.`);
4529
5228
  out.print({
4530
5229
  accepted: [],
4531
5230
  conflicts: [],
@@ -4535,12 +5234,12 @@ export async function runTestRunAll(opts, deps = {}) {
4535
5234
  });
4536
5235
  return undefined;
4537
5236
  }
4538
- stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${opts.projectId} for batch run.`);
5237
+ stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${projectId} for batch run.`);
4539
5238
  }
4540
5239
  // When no --filter, omit testIds → server runs ALL tests in the project
4541
5240
  // (BE tests on the legacy V2 wave engine; FE + BE on the V3 unified engine).
4542
5241
  const batchResp = await client.triggerBatchRunFresh({
4543
- projectId: opts.projectId,
5242
+ projectId,
4544
5243
  ...(testIds !== undefined ? { testIds } : {}),
4545
5244
  source: 'cli',
4546
5245
  }, { idempotencyKey });
@@ -4653,7 +5352,7 @@ export async function runTestRunAll(opts, deps = {}) {
4653
5352
  let retryResp;
4654
5353
  try {
4655
5354
  retryResp = await client.triggerBatchRunFresh({
4656
- projectId: opts.projectId,
5355
+ projectId,
4657
5356
  testIds: retryIds,
4658
5357
  source: 'cli',
4659
5358
  }, { idempotencyKey: retryKey });
@@ -4881,6 +5580,37 @@ export async function runTestRunAll(opts, deps = {}) {
4881
5580
  };
4882
5581
  await writeBatchJUnitReportIfRequested(opts, freshRunResults);
4883
5582
  out.print(jsonPayload);
5583
+ // CI-native output layer (issue #99): emitted before the gate throws below so
5584
+ // the artifacts land even when the batch exits non-zero. The summary file is a
5585
+ // machine artifact written regardless of --output mode; stdout stays owned by
5586
+ // the envelope above (plus Actions workflow commands, which Actions parses).
5587
+ {
5588
+ const env = deps.env ?? process.env;
5589
+ const ghEnabled = opts.ghOutput === true || env.GITHUB_ACTIONS === 'true';
5590
+ if (ghEnabled || opts.summaryFile !== undefined) {
5591
+ const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
5592
+ if (opts.summaryFile !== undefined) {
5593
+ try {
5594
+ writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
5595
+ }
5596
+ catch {
5597
+ stderrFn(`[run] could not write --summary-file ${opts.summaryFile}; continuing`);
5598
+ }
5599
+ }
5600
+ if (ghEnabled) {
5601
+ const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
5602
+ emitGithubOutputs(ciSummary, env, {
5603
+ stdout: stdoutFn,
5604
+ stderr: stderrFn,
5605
+ appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
5606
+ // Under --output json the envelope above owns stdout; workflow
5607
+ // commands go to stderr instead (the Actions runner parses both
5608
+ // streams), keeping the documented machine output parseable.
5609
+ annotations: opts.output === 'json' ? stderrFn : stdoutFn,
5610
+ }, { force: opts.ghOutput === true });
5611
+ }
5612
+ }
5613
+ }
4884
5614
  // Rate-deferred tests were never dispatched → the batch is incomplete (exit 7),
4885
5615
  // mirroring `test rerun --all`. Checked before the failed-run throw so the
4886
5616
  // operator learns to retry the deferred set.
@@ -4926,8 +5656,9 @@ export async function runTestRunAll(opts, deps = {}) {
4926
5656
  /**
4927
5657
  * `test rerun` — M3.4 piece-3.
4928
5658
  *
4929
- * FE: `POST /tests/{id}/runs/rerun` → verbatim replay (no credit). With
4930
- * `--wait`, polls `GET /runs/{runId}` until terminal.
5659
+ * FE: `POST /tests/{id}/runs/rerun` → verbatim replay, billed at 0.5 credits
5660
+ * (same as a fresh run; legacy V2 accounts: free). With `--wait`, polls
5661
+ * `GET /runs/{runId}` until terminal.
4931
5662
  *
4932
5663
  * BE: same route → closure + per-member runIds. With `--wait`, polls every
4933
5664
  * closure-member runId; exits on the named test's verdict; failed closure
@@ -5077,7 +5808,10 @@ export async function runTestRerun(opts, deps = {}) {
5077
5808
  try {
5078
5809
  rerunResp = await client.triggerRerun(testId, {
5079
5810
  source: 'cli',
5080
- ...(effectiveAutoHeal ? { autoHeal: true } : {}),
5811
+ // Always send the effective boolean, including an explicit `false`
5812
+ // opt-out — the server defaults an ABSENT field to heal-on, so
5813
+ // omitting the key on opt-out silently discarded --no-auto-heal.
5814
+ autoHeal: effectiveAutoHeal,
5081
5815
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
5082
5816
  }, { idempotencyKey });
5083
5817
  }
@@ -5117,8 +5851,11 @@ export async function runTestRerun(opts, deps = {}) {
5117
5851
  // Print auto-heal advisory.
5118
5852
  // CLI path: auto-heal is default-on for FE reruns (--no-auto-heal to opt
5119
5853
  // out). Free and paid CLI callers both get auto-heal; backend no longer
5120
- // tier-gates for source='cli'. Cost: 0.2 credits per engage (charged only
5121
- // when Phase-2 heal actually runs; verbatim replay passes are free).
5854
+ // tier-gates for source='cli'. The rerun itself is billed at 0.5 credits
5855
+ // regardless of whether heal engages (same as a fresh run; legacy V2
5856
+ // accounts: a verbatim replay pass is free). A heal engage costs an
5857
+ // additional 0.2 credits on top of that, charged only when Phase-2 heal
5858
+ // actually runs.
5122
5859
  //
5123
5860
  // Defensive branch: if the server still echoes autoHeal:false after we sent
5124
5861
  // autoHeal:true, the server did not apply it (unexpected; may happen on
@@ -5132,17 +5869,21 @@ export async function runTestRerun(opts, deps = {}) {
5132
5869
  // default-on `true`, so opts.autoHeal && !rerunResp.autoHeal would
5133
5870
  // fire spuriously for every BE rerun).
5134
5871
  if (effectiveAutoHeal && !rerunResp.autoHeal) {
5135
- // Env-correct billing link (dev/prod portals differ); route-only when
5136
- // the API host is unknown.
5137
- const advisoryPortalBase = resolvePortalBase(resolveApiUrl(opts, deps));
5872
+ // Points at `testsprite usage`, not a hardcoded billing URL: this CLI
5873
+ // path has no per-request org context (no backend nextAction feeds
5874
+ // this advisory, and a personal-vs-org-bound key can't be told apart
5875
+ // here), while `usage` already renders whichever wallet (personal or
5876
+ // organization) actually governs this key's balance.
5138
5877
  stderrFn(`[advisory] auto-heal was not applied by the server (verbatim replay).` +
5139
- ` If this was unexpected, check your balance at ${advisoryPortalBase !== undefined
5140
- ? `${advisoryPortalBase}/dashboard/settings/billing`
5141
- : 'the portal Billing page (/dashboard/settings/billing)'}.`);
5878
+ ` If this was unexpected, check your balance with \`testsprite usage\`.`);
5142
5879
  }
5143
5880
  else if (rerunResp.autoHeal) {
5144
5881
  stderrFn(`[advisory] auto-heal on (FE rerun default). If a step has drifted, healing runs and costs 0.2 credit. Disable with --no-auto-heal.`);
5145
5882
  }
5883
+ // Server advisory: the autoHeal opt-out was forwarded to the execution
5884
+ // engine but is not yet enforced there. Present only on a V3-routed
5885
+ // rerun with an explicit autoHeal:false request; absent everywhere else.
5886
+ emitRerunAdvisories(stderrFn, rerunResp.advisories);
5146
5887
  const isBERerun = !!rerunResp.closure;
5147
5888
  if (isBERerun && rerunResp.closure) {
5148
5889
  const totalCount = rerunResp.closure.members.length;
@@ -5190,6 +5931,8 @@ export async function runTestRerun(opts, deps = {}) {
5190
5931
  // BE rerun: poll every closure-member runId, exit on named test's verdict.
5191
5932
  const namedRunId = rerunResp.runId;
5192
5933
  const closureMembers = rerunResp.closure.members;
5934
+ // `unobserved`: member never reached a terminal verdict (timed out or its
5935
+ // poll errored). Distinct from an observed non-passed run (failed/blocked).
5193
5936
  const closureFailures = [];
5194
5937
  const pollMember = async (member) => {
5195
5938
  const resolveAlternate = makeBackendWaitFallback({
@@ -5199,7 +5942,7 @@ export async function runTestRerun(opts, deps = {}) {
5199
5942
  onResolved: () => undefined,
5200
5943
  });
5201
5944
  try {
5202
- return await pollRunUntilTerminal(client, member.runId, {
5945
+ const finalRun = await pollRunUntilTerminal(client, member.runId, {
5203
5946
  timeoutSeconds: opts.timeoutSeconds,
5204
5947
  sleep: deps.sleep,
5205
5948
  shutdown: shutdownOf(deps),
@@ -5216,12 +5959,22 @@ export async function runTestRerun(opts, deps = {}) {
5216
5959
  },
5217
5960
  resolveAlternate,
5218
5961
  });
5962
+ return { kind: 'terminal', run: finalRun };
5219
5963
  }
5220
5964
  catch (err) {
5221
- if (err instanceof TimeoutError) {
5222
- return null;
5223
- }
5224
- throw err;
5965
+ if (err instanceof TimeoutError)
5966
+ return { kind: 'timeout' };
5967
+ // Preserve the two intentional whole-fan-out aborts: each has a
5968
+ // dedicated outer-catch branch (RequestTimeoutError → all-running
5969
+ // partial + re-attach hints + exit 7; InterruptError → DEV-331
5970
+ // graceful detach). Re-throw so the fan-out's `.catch(reject)` fires.
5971
+ if (err instanceof RequestTimeoutError || err instanceof InterruptError)
5972
+ throw err;
5973
+ // Any other member error (ApiError, transient 5xx, malformed
5974
+ // response) is classified per-member instead of rejecting the whole
5975
+ // fan-out and discarding every already-collected sibling result.
5976
+ const status = err instanceof ApiError ? err.code : 'error';
5977
+ return { kind: 'error', status, error: err };
5225
5978
  }
5226
5979
  };
5227
5980
  // Fan-out poll with concurrency limit
@@ -5230,6 +5983,10 @@ export async function runTestRerun(opts, deps = {}) {
5230
5983
  const concurrencyLimit = opts.maxConcurrency;
5231
5984
  let inFlight = 0;
5232
5985
  let memberIdx = 0;
5986
+ // Set when the NAMED test's own poll errors (not a timeout). Re-thrown
5987
+ // after the payload is printed so its real error/exit code is preserved
5988
+ // without discarding the sibling results collected alongside it.
5989
+ let namedPollError;
5233
5990
  try {
5234
5991
  await new Promise((resolve, reject) => {
5235
5992
  function startNext() {
@@ -5237,27 +5994,51 @@ export async function runTestRerun(opts, deps = {}) {
5237
5994
  const member = members[memberIdx++];
5238
5995
  inFlight++;
5239
5996
  pollMember(member)
5240
- .then(result => {
5241
- memberResults.set(member.runId, result);
5242
- if (member.runId !== namedRunId) {
5243
- if (result === null) {
5244
- // Timed-out closure member: treat as incomplete/failed so
5245
- // the exit-code path fires exit 7 rather than silently
5246
- // succeeding with an unobserved member.
5997
+ .then(outcome => {
5998
+ if (outcome.kind === 'terminal') {
5999
+ memberResults.set(member.runId, outcome.run);
6000
+ if (member.runId !== namedRunId && outcome.run.status !== 'passed') {
6001
+ closureFailures.push({
6002
+ testId: member.testId,
6003
+ runId: member.runId,
6004
+ status: outcome.run.status,
6005
+ });
6006
+ stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) finished with status: ${outcome.run.status}`);
6007
+ }
6008
+ }
6009
+ else if (outcome.kind === 'timeout') {
6010
+ // Timed-out closure member: treat as incomplete/failed so
6011
+ // the exit-code path fires exit 7 rather than silently
6012
+ // succeeding with an unobserved member.
6013
+ memberResults.set(member.runId, null);
6014
+ if (member.runId !== namedRunId) {
5247
6015
  closureFailures.push({
5248
6016
  testId: member.testId,
5249
6017
  runId: member.runId,
5250
6018
  status: 'timeout',
6019
+ unobserved: true,
5251
6020
  });
5252
6021
  stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) timed out — rerun did not reach terminal within --timeout`);
5253
6022
  }
5254
- else if (result.status !== 'passed') {
6023
+ }
6024
+ else {
6025
+ // Classified per-member error — recorded, never aborts the
6026
+ // fan-out. The named test's error is stashed for re-throw;
6027
+ // sibling errors surface in closureFailures[].
6028
+ memberResults.set(member.runId, null);
6029
+ if (member.runId === namedRunId) {
6030
+ namedPollError = outcome.error;
6031
+ }
6032
+ else {
6033
+ // A poll error means we never saw a terminal verdict — the
6034
+ // run may still be in flight — so it's unobserved too.
5255
6035
  closureFailures.push({
5256
6036
  testId: member.testId,
5257
6037
  runId: member.runId,
5258
- status: result.status,
6038
+ status: outcome.status,
6039
+ unobserved: true,
5259
6040
  });
5260
- stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) finished with status: ${result.status}`);
6041
+ stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) could not be confirmed terminal — poll error: ${outcome.status}`);
5261
6042
  }
5262
6043
  }
5263
6044
  inFlight--;
@@ -5300,6 +6081,27 @@ export async function runTestRerun(opts, deps = {}) {
5300
6081
  `Or cancel with:\n${cancelHints}`);
5301
6082
  throw fanOutErr;
5302
6083
  }
6084
+ // RATE_LIMITED from any member's poll (pollMember only swallows
6085
+ // TimeoutError into a null return — see above; every other error,
6086
+ // including a RATE_LIMITED ApiError, propagates through .catch(reject)
6087
+ // exactly like RequestTimeoutError). Same partial shape as the
6088
+ // timeout path so the caller always has every closure-member runId on
6089
+ // stdout; the SAME thrown ApiError is rethrown unchanged so its
6090
+ // native exit code (11) is preserved.
6091
+ if (fanOutErr instanceof ApiError && fanOutErr.code === 'RATE_LIMITED') {
6092
+ ticker.finalize(`Closure fan-out — rate limited by the server`);
6093
+ const dispatchedRunIds = closureMembers.map(m => ({
6094
+ runId: m.runId,
6095
+ testId: m.testId,
6096
+ role: m.role,
6097
+ status: 'running',
6098
+ }));
6099
+ out.print({ runId: namedRunId, status: 'running', closure: dispatchedRunIds }, () => dispatchedRunIds
6100
+ .map(m => `${m.role.padEnd(9)} ${m.testId} (runId: ${m.runId}) — running`)
6101
+ .join('\n'));
6102
+ stderrFn(rateLimitedDetachMessage(fanOutErr, closureMembers.map(m => m.runId)));
6103
+ throw fanOutErr;
6104
+ }
5303
6105
  // Graceful detach (DEV-331): same partial shape as the timeout path —
5304
6106
  // SIG-6 requires the partial to list ALL dispatched runIds.
5305
6107
  if (fanOutErr instanceof InterruptError) {
@@ -5345,6 +6147,19 @@ export async function runTestRerun(opts, deps = {}) {
5345
6147
  return lines.join('\n');
5346
6148
  });
5347
6149
  if (!namedResult) {
6150
+ // Named test's own poll errored (not a timeout): re-throw its real
6151
+ // error now that the payload (incl. sibling closureFailures) is
6152
+ // printed, preserving the true exit code instead of masking it as a
6153
+ // timeout.
6154
+ if (namedPollError !== undefined) {
6155
+ // Every dispatched member is still executing (and billing), so a
6156
+ // rate-limited named poll owes the same detach hints the fan-out's
6157
+ // own branch emits — which this re-throw bypasses.
6158
+ if (namedPollError instanceof ApiError && namedPollError.code === 'RATE_LIMITED') {
6159
+ stderrFn(rateLimitedDetachMessage(namedPollError, closureMembers.map(m => m.runId)));
6160
+ }
6161
+ throw namedPollError;
6162
+ }
5348
6163
  // timeout
5349
6164
  throw ApiError.fromEnvelope({
5350
6165
  error: {
@@ -5360,23 +6175,23 @@ export async function runTestRerun(opts, deps = {}) {
5360
6175
  stderrFn(`Run finished with status: ${namedResult.status}. Use 'testsprite test artifact get ${namedRunId}' to download the failure bundle.`);
5361
6176
  throw new CLIError(`Run ${namedRunId} finished with status: ${namedResult.status}`, 1);
5362
6177
  }
5363
- // Fix B: timed-out closure members (non-named) are recorded in
5364
- // closureFailures with status 'timeout'. Even when the named run passes,
5365
- // we must exit 7 so --wait does not silently succeed when the closure
5366
- // as a whole was never observed to reach terminal.
5367
- const timedOutMembers = closureFailures.filter(f => f.status === 'timeout');
5368
- if (timedOutMembers.length > 0) {
5369
- const timedOutIds = timedOutMembers.map(f => f.runId);
5370
- const resumeHints = timedOutIds.map(runId => `testsprite test wait ${runId}`).join('\n') +
5371
- `\nCancel instead: testsprite test cancel ${timedOutIds.join(' ')}`;
6178
+ // Any unobserved member (timed out OR poll-errored) flips --wait to exit 7,
6179
+ // even when the named run passes — otherwise a dependency whose status was
6180
+ // never confirmed would let --wait exit 0. Observed-failed members are not
6181
+ // included; that's the future --fail-on-closure decision.
6182
+ const unobservedMembers = closureFailures.filter(f => f.unobserved);
6183
+ if (unobservedMembers.length > 0) {
6184
+ const unobservedIds = unobservedMembers.map(f => f.runId);
6185
+ const resumeHints = unobservedIds.map(runId => `testsprite test wait ${runId}`).join('\n') +
6186
+ `\nCancel instead: testsprite test cancel ${unobservedIds.join(' ')}`;
5372
6187
  throw ApiError.fromEnvelope({
5373
6188
  error: {
5374
6189
  code: 'UNSUPPORTED',
5375
- message: `${timedOutMembers.length} closure member${timedOutMembers.length !== 1 ? 's' : ''} timed out before reaching terminal status.`,
6190
+ message: `${unobservedMembers.length} closure member${unobservedMembers.length !== 1 ? 's' : ''} did not reach an observed terminal status (timed out or errored during polling).`,
5376
6191
  nextAction: resumeHints,
5377
6192
  requestId: 'local',
5378
6193
  details: {
5379
- timedOutRunIds: timedOutMembers.map(f => f.runId),
6194
+ unobservedRunIds: unobservedIds,
5380
6195
  timeoutSeconds: opts.timeoutSeconds,
5381
6196
  },
5382
6197
  },
@@ -5442,6 +6257,24 @@ export async function runTestRerun(opts, deps = {}) {
5442
6257
  `Re-attach with: testsprite test wait ${rerunResp.runId}, or cancel with: testsprite test cancel ${rerunResp.runId}`);
5443
6258
  throw err;
5444
6259
  }
6260
+ // RATE_LIMITED during polling — see the matching comment in runTestRun.
6261
+ // Same partial-envelope contract; the SAME thrown ApiError is rethrown
6262
+ // unchanged so its native exit code (11) is preserved.
6263
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
6264
+ ticker.finalize(`Run ${rerunResp.runId} — rate limited by the server`);
6265
+ const partial = { runId: rerunResp.runId, status: 'running' };
6266
+ out.print(partial, data => {
6267
+ const p = data;
6268
+ return [
6269
+ `runId ${p.runId}`,
6270
+ `status ${p.status} (rate limited by the server)`,
6271
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
6272
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
6273
+ ].join('\n');
6274
+ });
6275
+ stderrFn(rateLimitedDetachMessage(err, [rerunResp.runId]));
6276
+ throw err;
6277
+ }
5445
6278
  // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
5446
6279
  if (err instanceof InterruptError) {
5447
6280
  ticker.finalize(`Run ${rerunResp.runId} — interrupted (${err.signal})`);
@@ -5575,7 +6408,9 @@ export async function runTestRerun(opts, deps = {}) {
5575
6408
  const chunkResp = await client.triggerBatchRerun({
5576
6409
  source: 'cli',
5577
6410
  testIds: chunk,
5578
- ...(effectiveAutoHeal ? { autoHeal: true } : {}),
6411
+ // Always send the effective boolean, including an explicit `false`
6412
+ // opt-out — see the matching comment on the single-rerun call site.
6413
+ autoHeal: effectiveAutoHeal,
5579
6414
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
5580
6415
  }, { idempotencyKey: chunkKey });
5581
6416
  chunkResponses.push(chunkResp);
@@ -5619,10 +6454,17 @@ export async function runTestRerun(opts, deps = {}) {
5619
6454
  byProject: mergeBatchRerunClosureByProject(chunkResponses.flatMap(r => r.closure.byProject)),
5620
6455
  },
5621
6456
  notFound: chunkResponses.flatMap(r => r.notFound ?? []),
6457
+ // Absent on every response except a V3-routed batch containing
6458
+ // at least one FE test with an explicit autoHeal:false opt-out. Dedupe
6459
+ // across chunks — every chunk in the same invocation carries the same
6460
+ // autoHeal request, so the same advisory would otherwise repeat per chunk.
6461
+ advisories: dedupeRerunAdvisories(chunkResponses.flatMap(r => r.advisories ?? [])),
5622
6462
  };
5623
6463
  // Print dispatch summary
5624
6464
  // Mutable: D3 deferred-retry loop may append to `accepted`/`conflicts` and
5625
- // drain `deferred` under --wait.
6465
+ // drain `deferred` under --wait. `advisories` may also grow if a D3 retry
6466
+ // response carries an advisory the initial dispatch didn't (defensive —
6467
+ // in practice the same request shape produces the same advisory set).
5626
6468
  let accepted = batchResp.accepted.slice();
5627
6469
  let deferred = batchResp.deferred.slice();
5628
6470
  let conflicts = batchResp.conflicts.slice();
@@ -5630,6 +6472,9 @@ export async function runTestRerun(opts, deps = {}) {
5630
6472
  // the retry window; the retry response's notFound[] is merged into this set so
5631
6473
  // the test is never reported as "resolved" when it actually vanished.
5632
6474
  let notFound = (batchResp.notFound ?? []).slice();
6475
+ // Mutable so a D3 deferred-retry response can contribute an
6476
+ // advisory the initial dispatch didn't carry (defensive; see comment above).
6477
+ let advisories = (batchResp.advisories ?? []).slice();
5633
6478
  const closureByProject = batchResp.closure.byProject;
5634
6479
  const addedProducersTotal = closureByProject.reduce((n, p) => n + p.addedProducers.length, 0);
5635
6480
  const summaryParts = [
@@ -5715,7 +6560,10 @@ export async function runTestRerun(opts, deps = {}) {
5715
6560
  const retryChunkResp = await client.triggerBatchRerun({
5716
6561
  source: 'cli',
5717
6562
  testIds: chunk,
5718
- ...(effectiveAutoHeal ? { autoHeal: true } : {}),
6563
+ // Always send the effective boolean, including an explicit
6564
+ // `false` opt-out — see the matching comment on the initial
6565
+ // dispatch call site above.
6566
+ autoHeal: effectiveAutoHeal,
5719
6567
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
5720
6568
  }, { idempotencyKey: retryKey });
5721
6569
  retryChunkResponses.push(retryChunkResp);
@@ -5733,6 +6581,12 @@ export async function runTestRerun(opts, deps = {}) {
5733
6581
  // into the running notFound set and remove from deferred so it isn't
5734
6582
  // reported as "resolved" in the final output.
5735
6583
  const newlyNotFound = retryChunkResponses.flatMap(r => r.notFound ?? []);
6584
+ // Merge any advisories the retry response carries into the
6585
+ // running set (deduped — see the initial-dispatch comment above).
6586
+ const newlyAdvisories = retryChunkResponses.flatMap(r => r.advisories ?? []);
6587
+ if (newlyAdvisories.length > 0) {
6588
+ advisories = dedupeRerunAdvisories(advisories.concat(newlyAdvisories));
6589
+ }
5736
6590
  if (newlyDuplicateCount > 0) {
5737
6591
  stderrFn(`[warn] ${newlyDuplicateCount} test${newlyDuplicateCount !== 1 ? 's were' : ' was'} triggered more than once across deferred-retry chunked requests (shared BE producer/teardown); kept the first run, ignored the rest.`);
5738
6592
  }
@@ -5764,10 +6618,13 @@ export async function runTestRerun(opts, deps = {}) {
5764
6618
  }
5765
6619
  }
5766
6620
  }
6621
+ // Print the (deduped) advisory set once, after any D3 retries have
6622
+ // had a chance to contribute one, not once per chunk/attempt.
6623
+ emitRerunAdvisories(stderrFn, advisories);
5767
6624
  if (!opts.wait) {
5768
6625
  // [P2] Build output from post-retry mutable state so deferred/conflicts/notFound
5769
6626
  // reflect what the D3 loop discovered, not just the initial batchResp.
5770
- out.print({ ...batchResp, accepted, deferred, conflicts, notFound });
6627
+ out.print({ ...batchResp, accepted, deferred, conflicts, notFound, advisories });
5771
6628
  if (deferred.length > 0) {
5772
6629
  throw new CLIError(`Batch rerun incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} were rate-deferred. Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
5773
6630
  }
@@ -5790,12 +6647,12 @@ export async function runTestRerun(opts, deps = {}) {
5790
6647
  });
5791
6648
  }
5792
6649
  // [P2] Return post-retry state including merged notFound.
5793
- return { ...batchResp, accepted, deferred, conflicts, notFound };
6650
+ return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
5794
6651
  }
5795
6652
  // --wait: fan-out poll each accepted run by its runId
5796
6653
  if (accepted.length === 0) {
5797
6654
  // [P2] Build output from post-retry mutable state including merged notFound.
5798
- out.print({ ...batchResp, accepted, deferred, conflicts, notFound });
6655
+ out.print({ ...batchResp, accepted, deferred, conflicts, notFound, advisories });
5799
6656
  if (deferred.length > 0) {
5800
6657
  throw new CLIError(`Batch rerun: no tests were accepted (${deferred.length} deferred). ` +
5801
6658
  `Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
@@ -5818,7 +6675,7 @@ export async function runTestRerun(opts, deps = {}) {
5818
6675
  });
5819
6676
  }
5820
6677
  // [P2] Return post-retry state including merged notFound.
5821
- return { ...batchResp, accepted, deferred, conflicts, notFound };
6678
+ return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
5822
6679
  }
5823
6680
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
5824
6681
  const concurrencyLimit = opts.maxConcurrency;
@@ -5964,6 +6821,9 @@ export async function runTestRerun(opts, deps = {}) {
5964
6821
  // report the partial run as fully successful. Mirrors the non-wait
5965
6822
  // `out.print(batchResp)` path.
5966
6823
  notFound,
6824
+ // Mirrors the non-wait `out.print(batchResp)` path — carry the
6825
+ // (deduped, post-retry) advisory set into the --wait JSON payload too.
6826
+ advisories,
5967
6827
  closure: batchResp.closure,
5968
6828
  summary: {
5969
6829
  passed,
@@ -6024,7 +6884,7 @@ export async function runTestRerun(opts, deps = {}) {
6024
6884
  // final accounting (accepted = original BatchRerunAccepted[] dispatch list
6025
6885
  // as required by the BatchRerunResponse type; rerunResults is the polled
6026
6886
  // outcome printed to stdout and is not part of the returned shape).
6027
- return { ...batchResp, accepted, deferred, conflicts, notFound };
6887
+ return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
6028
6888
  }
6029
6889
  export function resolveDefaultArtifactDir(runId, cwd = process.cwd()) {
6030
6890
  requireNonEmpty('run-id', runId);
@@ -6220,6 +7080,8 @@ export function createTestCommand(deps = {}) {
6220
7080
  .option('--starting-token <token>', 'opaque cursor from a previous list response')
6221
7081
  .option('--cursor <token>', 'alias for --starting-token; accepted for parity with `test result --history`')
6222
7082
  .option('--max-items <n>', 'stop after this many items across auto-paged pages')
7083
+ .option('--columns <list>', 'select/reorder text table columns (comma-separated keys)')
7084
+ .option('--no-header', 'suppress the text table header row')
6223
7085
  .addHelpText('after', GLOBAL_OPTS_HINT)
6224
7086
  .action(async (cmdOpts, command) => {
6225
7087
  // Same parser strategy as `project list`: skip Commander's number
@@ -6239,6 +7101,8 @@ export function createTestCommand(deps = {}) {
6239
7101
  pageSize: parseNumericFlag(cmdOpts.pageSize, 'page-size'),
6240
7102
  startingToken: cmdOpts.startingToken ?? cmdOpts.cursor,
6241
7103
  maxItems: parseNumericFlag(cmdOpts.maxItems, 'max-items'),
7104
+ columns: cmdOpts.columns,
7105
+ noHeader: cmdOpts.header === false,
6242
7106
  }, deps);
6243
7107
  });
6244
7108
  test
@@ -6259,6 +7123,8 @@ export function createTestCommand(deps = {}) {
6259
7123
  .option('--code-file <path>', 'file containing the test code (≤ 350 KB)')
6260
7124
  .option('--plan-from <path>', 'JSON file with the full FE test definition — projectId, type, name, planSteps[] all live in the file ' +
6261
7125
  '(≤ 256 KB; mutually exclusive with --code-file). In this mode --project/--type/--name/--description/--priority are ignored.')
7126
+ .option('--plan-template', 'print a minimal valid plan-file skeleton to stdout and exit (pure-local: no network, no credentials, ' +
7127
+ 'ignores every other flag). Pipe to a file and edit: `--plan-template > plan.json`.', false)
6262
7128
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
6263
7129
  .option('--wait', 'with --run, poll until terminal status', false)
6264
7130
  .option('--timeout <s>', 'with --run --wait, max seconds to wait')
@@ -6267,12 +7133,20 @@ export function createTestCommand(deps = {}) {
6267
7133
  .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering on `test rerun` and `test run --all`.', (val, prev) => [...(prev ?? []), val], [])
6268
7134
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Use to declare upstream producer dependencies.', (val, prev) => [...(prev ?? []), val], [])
6269
7135
  .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
7136
+ .addHelpText('after', PLAN_TEMPLATE_HELP_TEXT)
6270
7137
  .addHelpText('after', '\nBE dependency authoring (M4):\n' +
6271
7138
  ' --produces/--needs drive wave ordering on `test rerun` + `test run --all`.\n' +
6272
7139
  ' --category teardown marks a final-wave cleanup test.\n' +
6273
7140
  ' These flags are backend-only; supplying with --type frontend is an error (exit 5).')
6274
7141
  .addHelpText('after', GLOBAL_OPTS_HINT)
6275
7142
  .action(async (cmdOpts, command) => {
7143
+ // Pure-local, no network/credentials, no other flag is
7144
+ // consulted. Checked first so `--plan-template` never trips the
7145
+ // --plan-from/--code-file mutual-exclusivity guard below.
7146
+ if (cmdOpts.planTemplate === true) {
7147
+ runPlanTemplate(resolveCommonOptions(command), deps);
7148
+ return;
7149
+ }
6276
7150
  // --plan-from and --code-file are mutually exclusive. Dispatch
6277
7151
  // here so each `run*` function stays single-purpose. If neither
6278
7152
  // is set, the existing runCreate path enforces --code-file.
@@ -6392,6 +7266,18 @@ export function createTestCommand(deps = {}) {
6392
7266
  force: cmdOpts.force === true,
6393
7267
  }, deps);
6394
7268
  });
7269
+ test
7270
+ .command('open <test-id>')
7271
+ .description('Open the test in the TestSprite dashboard: prints the deep-link URL, then spawns your default browser unless --no-browser.')
7272
+ .option('--no-browser', 'print the URL only (SSH, headless, CI, agents)')
7273
+ .addHelpText('after', GLOBAL_OPTS_HINT)
7274
+ .action(async (testId, cmdOpts, command) => {
7275
+ await runOpen({
7276
+ ...resolveCommonOptions(command),
7277
+ testId,
7278
+ noBrowser: cmdOpts.browser === false,
7279
+ }, deps);
7280
+ });
6395
7281
  test
6396
7282
  .command('steps <test-id>')
6397
7283
  .description('List the steps for a test (server returns the cumulative log across every run; use --run-id to scope to one run)')
@@ -6448,6 +7334,10 @@ export function createTestCommand(deps = {}) {
6448
7334
  .option('--since <dur>', 'with --history: lower bound on createdAt — 24h, 7d, or ISO timestamp (client-side translated)')
6449
7335
  .option('--page-size <n>', 'with --history: number of runs per page (1–100, default 20)')
6450
7336
  .option('--cursor <token>', 'with --history: opaque cursor from a prior page')
7337
+ .option('--rerun', 'with --history: show only reruns')
7338
+ .option('--no-rerun', 'with --history: show only fresh (non-rerun) runs')
7339
+ .option('--columns <list>', 'with --history: select/reorder text table columns')
7340
+ .option('--no-header', 'with --history: suppress the text table header row')
6451
7341
  .addHelpText('after', GLOBAL_OPTS_HINT)
6452
7342
  .action(async (testId, cmdOpts, command) => {
6453
7343
  if (cmdOpts.history) {
@@ -6461,6 +7351,9 @@ export function createTestCommand(deps = {}) {
6461
7351
  ? parseNumericFlag(cmdOpts.pageSize, 'page-size')
6462
7352
  : undefined,
6463
7353
  cursor: cmdOpts.cursor,
7354
+ rerun: cmdOpts.rerun,
7355
+ columns: cmdOpts.columns,
7356
+ noHeader: cmdOpts.header === false,
6464
7357
  }, deps);
6465
7358
  }
6466
7359
  else {
@@ -6563,17 +7456,21 @@ export function createTestCommand(deps = {}) {
6563
7456
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
6564
7457
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6565
7458
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
6566
- .option('--all', 'run all tests in the project (wave-ordered fresh run; requires --project). Mutually exclusive with <test-id>.', false)
6567
- .option('--project <id>', 'project id (required with --all; returned by `testsprite project list`)')
7459
+ .option('--all', 'run all tests in the project (wave-ordered fresh run; uses --project or TESTSPRITE_PROJECT_ID). Mutually exclusive with <test-id>.', false)
7460
+ .option('--project <id>', 'project id (with --all, overrides TESTSPRITE_PROJECT_ID; returned by `testsprite project list`)')
6568
7461
  .option('--filter <substr>', 'with --all: only run tests whose name contains this substring (case-insensitive)')
6569
7462
  .option('--max-concurrency <n>', `with --all --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
6570
7463
  .option('--report <format>', 'with --all --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
6571
7464
  .option('--report-file <path>', 'output path for --report (atomic write)')
6572
7465
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
7466
+ .option('--gh-output', 'with --all --wait: emit GitHub-native output (::error:: annotations per non-passed run; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
7467
+ .option('--summary-file <path>', 'with --all --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
6573
7468
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
6574
- ' testsprite test run --all --project <id> run all project tests in wave order\n' +
6575
- ' testsprite test run --all --project <id> --filter <substr> name-glob subset\n' +
6576
- ' testsprite test run --all --project <id> --wait --report junit --report-file ./results.xml\n' +
7469
+ ' testsprite test run --all --project <id> run all project tests in wave order\n' +
7470
+ ' TESTSPRITE_PROJECT_ID=<id> testsprite test run --all use env default project\n' +
7471
+ ' testsprite test run --all --filter <substr> name-glob subset (uses --project/env)\n' +
7472
+ ' testsprite test run --all --wait --report junit --report-file ./results.xml\n' +
7473
+ ' project id precedence: --project wins over TESTSPRITE_PROJECT_ID\n' +
6577
7474
  '\nBE tests can declare --produces/--needs at create time to drive wave ordering\n' +
6578
7475
  '(see `testsprite test create --help` for details).\n' +
6579
7476
  '\nFrontend tests: the current unified engine runs FE tests too (they are billed\n' +
@@ -6587,13 +7484,13 @@ export function createTestCommand(deps = {}) {
6587
7484
  throw localValidationError('test-id', 'positional <test-id> and --all are mutually exclusive; use one or the other');
6588
7485
  }
6589
7486
  if (testIdArg === undefined && !isAll) {
6590
- throw localValidationError('test-id', 'provide a <test-id>, or use --all --project <id> to run all tests in a project');
7487
+ throw localValidationError('test-id', 'provide a <test-id>, or use --all with --project <id> or TESTSPRITE_PROJECT_ID');
6591
7488
  }
6592
7489
  // --filter is an --all-only narrowing flag (mirrors `test rerun --filter`).
6593
7490
  // Without --all it would be SILENTLY ignored while the explicit <test-id>
6594
7491
  // still runs — defeating the caller's narrowing intent. Reject early.
6595
7492
  if (cmdOpts.filter !== undefined && cmdOpts.filter !== '' && !isAll) {
6596
- throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests run). Remove --filter, or add --all --project <id>.');
7493
+ throw localValidationError('filter', '--filter only applies with --all (it narrows which project tests run). Remove --filter, or add --all with --project <id> or TESTSPRITE_PROJECT_ID.');
6597
7494
  }
6598
7495
  const report = parseJUnitReportFormat(cmdOpts.report);
6599
7496
  assertJUnitReportOptions({
@@ -6603,23 +7500,32 @@ export function createTestCommand(deps = {}) {
6603
7500
  wait: cmdOpts.wait === true,
6604
7501
  batchPath: isAll,
6605
7502
  });
7503
+ // --gh-output / --summary-file reduce the terminal batch envelope, which
7504
+ // only exists on the --all --wait path (without --wait the command returns
7505
+ // after enqueueing). Anywhere else they would silently no-op — reject
7506
+ // loudly (same rule as --filter and the JUnit report flags).
7507
+ if (cmdOpts.ghOutput === true && (!isAll || cmdOpts.wait !== true)) {
7508
+ throw localValidationError('gh-output', '--gh-output only applies with --all --wait (it reduces the terminal batch envelope). Remove --gh-output, or add --all --wait.');
7509
+ }
7510
+ if (cmdOpts.summaryFile !== undefined && (!isAll || cmdOpts.wait !== true)) {
7511
+ throw localValidationError('summary-file', '--summary-file only applies with --all --wait (it reduces the terminal batch envelope). Remove --summary-file, or add --all --wait.');
7512
+ }
6606
7513
  if (isAll) {
6607
7514
  // --all path: wave-ordered fresh batch run.
6608
- if (!cmdOpts.project) {
6609
- throw localValidationError('project', '--all requires a project id — pass --project <id>');
6610
- }
7515
+ const projectId = resolveProjectId(cmdOpts.project, deps);
7516
+ requireProjectId(projectId, '--all requires a project id - pass --project <id> or set TESTSPRITE_PROJECT_ID');
6611
7517
  // --target-url has no effect on the --all batch path: a BE test's base
6612
7518
  // URL is baked into its code, and the unified engine resolves each
6613
7519
  // project's configured environment server-side (per-run URL overrides
6614
7520
  // are not applied to batch FE runs either). Silently dropping it could
6615
- // run the suite against an unintended environment in the caller's mind
6616
- // — reject loudly instead.
7521
+ // run the suite against an unintended environment in the caller's mind,
7522
+ // so reject loudly.
6617
7523
  if (cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
6618
7524
  throw localValidationError('target-url', '--target-url has no effect with --all (the batch path does not apply a per-run URL override — BE test URLs are baked into their code and the unified engine resolves the project environment server-side). Remove --target-url.');
6619
7525
  }
6620
7526
  await runTestRunAll({
6621
7527
  ...resolveCommonOptions(command),
6622
- projectId: cmdOpts.project,
7528
+ projectId,
6623
7529
  nameFilter: cmdOpts.filter,
6624
7530
  wait: cmdOpts.wait === true,
6625
7531
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
@@ -6629,6 +7535,8 @@ export function createTestCommand(deps = {}) {
6629
7535
  report,
6630
7536
  reportFile: cmdOpts.reportFile,
6631
7537
  reportSuiteName: cmdOpts.reportSuiteName,
7538
+ ghOutput: cmdOpts.ghOutput === true,
7539
+ summaryFile: cmdOpts.summaryFile,
6632
7540
  }, deps);
6633
7541
  return;
6634
7542
  }
@@ -6659,6 +7567,11 @@ export function createTestCommand(deps = {}) {
6659
7567
  ' is recorded as error:<CODE> in its row and folded into exit 7)\n' +
6660
7568
  ' 7 timeout or per-member poll error — resume with: testsprite test wait <run-id...>\n' +
6661
7569
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
7570
+ ' 11 rate limited, and nothing else went wrong — polls are retried\n' +
7571
+ ' automatically honoring Retry-After first, so this means the throttle\n' +
7572
+ ' outlasted that budget while the runs were still fine. Back off, then\n' +
7573
+ ' re-attach with test wait. (A throttle that instead consumes the whole\n' +
7574
+ ' --timeout reports 7, and any real timeout or failure keeps 7 / 1.)\n' +
6662
7575
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
6663
7576
  '\nCtrl-C detaches only (the run keeps executing and billing); stop it for\n' +
6664
7577
  'real with: testsprite test cancel <run-id...>')
@@ -6692,7 +7605,8 @@ export function createTestCommand(deps = {}) {
6692
7605
  // -------------------------------------------------------------------------
6693
7606
  test
6694
7607
  .command('rerun [test-ids...]')
6695
- .description('Re-execute a test (or multiple) as a cheap replay — FE replays the saved script (no credit), BE re-runs the dependency closure.\n' +
7608
+ .description('Re-execute a test (or multiple) as a replay — FE replays the saved script, BE re-runs the dependency closure. ' +
7609
+ 'Billed the same as a fresh run: 0.5 credits per FE rerun / 0.2 credits per BE rerun (legacy V2 accounts: FE rerun remains free).\n' +
6696
7610
  '\nExit codes:\n' +
6697
7611
  ' 0 passed (or queued without --wait)\n' +
6698
7612
  ' 1 failed / blocked / cancelled\n' +
@@ -6727,7 +7641,9 @@ export function createTestCommand(deps = {}) {
6727
7641
  ' • Under --wait the per-request HTTP timeout is auto-raised to cover --timeout so a\n' +
6728
7642
  ' slow trigger/poll under load is not cut at the 120s default (see --request-timeout).\n' +
6729
7643
  ' • Batch --wait: rate-deferred tests appear in `deferred[]` and `summary.deferred`,\n' +
6730
- ' and force a non-zero exit — they are NOT counted in `summary.total` (dispatched only).')
7644
+ ' and force a non-zero exit — they are NOT counted in `summary.total` (dispatched only).\n' +
7645
+ ' • On V3-routed accounts, --no-auto-heal is still rolling out and may not yet be\n' +
7646
+ ' honored server-side — check `auth status` for your routing.')
6731
7647
  .addHelpText('after', '\nDry-run shape notes:\n' +
6732
7648
  ' • --dry-run shows the BE rerun wire shape (includes `closure{}`); FE rerun responses\n' +
6733
7649
  ' omit `closure` (or return it as null) since there is no dependency expansion.\n' +
@@ -6787,8 +7703,11 @@ export function createTestCommand(deps = {}) {
6787
7703
  .option('--until-fail', 'stop at the first non-passing attempt (fast "is it flaky at all?" check)', false)
6788
7704
  .option('--timeout <s>', `per-attempt max seconds to wait (1-${MAX_RUN_TIMEOUT_SECONDS}, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6789
7705
  .addHelpText('after', '\nNotes:\n' +
6790
- ' • Frontend replays are free verbatim script replays (no credit); backend replays\n' +
6791
- ' re-run the dependency closure and may cost credits — a one-line advisory is printed.\n' +
7706
+ ' • Each replay is billed as a rerun — 0.5 credits for a frontend replay (verbatim\n' +
7707
+ ' script), 0.2 credits for a backend replay (re-runs the dependency closure) —\n' +
7708
+ ' same price as a fresh run, so `--runs N` costs roughly N×0.5 credits for a\n' +
7709
+ ' frontend test (legacy V2 accounts: FE rerun remains free). A one-line advisory\n' +
7710
+ ' is printed before a backend replay.\n' +
6792
7711
  ' • Replays use auto-heal OFF so a flaky test is not silently "healed" into a pass;\n' +
6793
7712
  ' this measures replay stability of the saved script against the configured URL.\n' +
6794
7713
  ' • `--output json` emits a machine-readable stability report for CI gating.')
@@ -6812,17 +7731,30 @@ export function createTestCommand(deps = {}) {
6812
7731
  // ---------------------------------------------------------------------------
6813
7732
  // `test flaky` — repeat-run flaky-test detector
6814
7733
  // ---------------------------------------------------------------------------
6815
- /** Upper bound on `--runs` so a repeat-runner can't amplify free FE replays. */
7734
+ /** Upper bound on `--runs` so a repeat-runner can't rack up unbounded rerun charges. */
6816
7735
  const MAX_FLAKY_RUNS = 10;
6817
7736
  /** Default replay count when `--runs` is omitted. */
6818
7737
  const DEFAULT_FLAKY_RUNS = 5;
7738
+ function isFlakyFatalTriggerError(err) {
7739
+ if (!(err instanceof ApiError))
7740
+ return false;
7741
+ switch (err.code) {
7742
+ case 'AUTH_REQUIRED':
7743
+ case 'AUTH_INVALID':
7744
+ case 'AUTH_FORBIDDEN':
7745
+ return true;
7746
+ default:
7747
+ return false;
7748
+ }
7749
+ }
6819
7750
  /**
6820
7751
  * `test flaky <test-id>` — replay a test N times and report a stability score.
6821
7752
  *
6822
7753
  * Each attempt is a `POST /tests/{id}/runs/rerun` with auto-heal OFF (a strict
6823
- * verbatim replay) followed by `pollRunUntilTerminal`. Frontend replays are
6824
- * free verbatim script replays; backend replays re-run the dependency closure
6825
- * (a one-line credit advisory is printed). The pure scoring lives in
7754
+ * verbatim replay) followed by `pollRunUntilTerminal`. Each replay is billed
7755
+ * as a rerun (0.5 credits FE / 0.2 credits BE, same as a fresh run; legacy V2
7756
+ * accounts: FE rerun remains free) — a one-line credit advisory is printed
7757
+ * for backend tests. The pure scoring lives in
6826
7758
  * `lib/flaky.ts`; this function is the I/O orchestrator.
6827
7759
  *
6828
7760
  * Exit code: 0 when every observed attempt passed (stable), else 1 — so CI can
@@ -6865,17 +7797,25 @@ export async function runFlaky(opts, deps = {}) {
6865
7797
  }
6866
7798
  if (isBackend) {
6867
7799
  stderrFn(`[advisory] ${opts.testId} is a backend test — each replay re-runs its dependency closure ` +
6868
- `and may cost credits. Frontend replays are free verbatim script replays; backend replays are not.`);
7800
+ `and is billed at 0.2 credits per rerun, same as a fresh run (frontend reruns are 0.5 credits).`);
6869
7801
  }
6870
7802
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
6871
7803
  const attempts = [];
7804
+ // Collected across attempts and deduped — same request shape every
7805
+ // attempt, so the server would otherwise repeat the identical advisory once
7806
+ // per replay. Surfaced ONCE in the final report/summary, not N times.
7807
+ let advisories = [];
6872
7808
  for (let i = 1; i <= opts.runs; i++) {
6873
7809
  const idempotencyKey = `cli-flaky-${randomUUID()}`;
6874
7810
  let rerunResp;
6875
7811
  try {
6876
7812
  // auto-heal is intentionally OFF: flaky detection needs a strict verbatim
6877
- // replay so healed drift cannot mask a nondeterministic pass/fail.
6878
- rerunResp = await client.triggerRerun(opts.testId, { source: 'cli' }, { idempotencyKey });
7813
+ // replay so healed drift cannot mask a nondeterministic pass/fail. Sent
7814
+ // explicitly (not omitted) — an absent field defaults to heal-on server-side.
7815
+ rerunResp = await client.triggerRerun(opts.testId, { source: 'cli', autoHeal: false }, { idempotencyKey });
7816
+ if (rerunResp.advisories && rerunResp.advisories.length > 0) {
7817
+ advisories = dedupeRerunAdvisories(advisories.concat(rerunResp.advisories));
7818
+ }
6879
7819
  }
6880
7820
  catch (err) {
6881
7821
  // A missing replayable run is fatal for the whole command (mirror rerun):
@@ -6891,6 +7831,9 @@ export async function runFlaky(opts, deps = {}) {
6891
7831
  },
6892
7832
  });
6893
7833
  }
7834
+ if (isFlakyFatalTriggerError(err)) {
7835
+ throw err;
7836
+ }
6894
7837
  // Any other trigger error is recorded as an errored attempt so a single
6895
7838
  // transient blip doesn't abort a long stability probe.
6896
7839
  const code = err instanceof ApiError ? err.code : 'ERROR';
@@ -6929,6 +7872,16 @@ export async function runFlaky(opts, deps = {}) {
6929
7872
  stderrFn(interruptDetachMessage(err, [runId]));
6930
7873
  throw err;
6931
7874
  }
7875
+ // RATE_LIMITED during polling (same defect class as the InterruptError
7876
+ // branch above): the HTTP layer already retried and gave up, but this
7877
+ // attempt's run keeps executing (and billing) server-side. Name it on
7878
+ // stderr before rethrowing so the runId is never silently dropped;
7879
+ // rethrow the SAME ApiError unchanged so its exit code (11) is kept.
7880
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
7881
+ ticker.finalize(`Attempt ${i}/${opts.runs} — rate limited by the server`);
7882
+ stderrFn(rateLimitedDetachMessage(err, [runId]));
7883
+ throw err;
7884
+ }
6932
7885
  // A per-attempt deadline (poll TimeoutError) or a client-side request
6933
7886
  // timeout both count as a non-passing "timeout" outcome for this attempt.
6934
7887
  if (err instanceof TimeoutError || err instanceof RequestTimeoutError) {
@@ -6945,7 +7898,10 @@ export async function runFlaky(opts, deps = {}) {
6945
7898
  break;
6946
7899
  }
6947
7900
  ticker.finalize();
6948
- const report = summarizeFlaky(opts.testId, attempts);
7901
+ // Print the deduped advisory set once for the whole probe, not
7902
+ // once per replay attempt (mirrors the `test rerun` advisory rendering).
7903
+ emitRerunAdvisories(stderrFn, advisories);
7904
+ const report = summarizeFlaky(opts.testId, attempts, advisories);
6949
7905
  out.print(report, data => renderFlakyText(data));
6950
7906
  const exitCode = flakyExitCode(report);
6951
7907
  if (exitCode !== 0) {
@@ -6953,9 +7909,17 @@ export async function runFlaky(opts, deps = {}) {
6953
7909
  }
6954
7910
  return report;
6955
7911
  }
6956
- function requireProjectId(projectId) {
7912
+ function resolveProjectId(projectId, deps) {
7913
+ const explicit = projectId?.trim();
7914
+ if (explicit && explicit.length > 0)
7915
+ return explicit;
7916
+ const envValue = (deps.env ?? process.env).TESTSPRITE_PROJECT_ID;
7917
+ const trimmed = envValue?.trim();
7918
+ return trimmed && trimmed.length > 0 ? trimmed : undefined;
7919
+ }
7920
+ function requireProjectId(projectId, message = 'is required; pass --project <id> or set TESTSPRITE_PROJECT_ID') {
6957
7921
  if (typeof projectId !== 'string' || projectId.length === 0) {
6958
- throw localValidationError('project', 'is required');
7922
+ throw localValidationError('project', message);
6959
7923
  }
6960
7924
  }
6961
7925
  /**
@@ -7255,38 +8219,32 @@ async function streamPresignedBody(url, out, deps) {
7255
8219
  throw new TransportError(`Failed mid-download of presigned code body: ${message}`);
7256
8220
  }
7257
8221
  }
7258
- function renderTestListText(page) {
8222
+ const TEST_LIST_COLUMNS = [
8223
+ {
8224
+ header: 'ID',
8225
+ width: rows => Math.max(2, ...rows.map(test => test.id.length)),
8226
+ render: test => test.id,
8227
+ },
8228
+ {
8229
+ header: 'NAME',
8230
+ width: rows => Math.max(4, ...rows.map(test => test.name.length)),
8231
+ render: test => test.name,
8232
+ },
8233
+ { header: 'TYPE', width: 8, render: test => test.type },
8234
+ { header: 'FROM', width: 6, render: test => test.createdFrom },
8235
+ { header: 'STATUS', width: 9, render: test => test.status },
8236
+ { header: 'UPDATED', width: 0, render: test => test.updatedAt },
8237
+ ];
8238
+ function renderTestListText(page, options = {}) {
7259
8239
  if (page.items.length === 0) {
7260
8240
  return page.nextToken ? `No tests on this page.\nnextToken: ${page.nextToken}` : 'No tests.';
7261
8241
  }
7262
- const idWidth = Math.max(2, ...page.items.map(t => t.id.length));
7263
- const nameWidth = Math.max(4, ...page.items.map(t => t.name.length));
7264
- const typeWidth = 8;
7265
- const fromWidth = 6;
7266
- const statusWidth = 9;
7267
- const header = pad('ID', idWidth) +
7268
- ' ' +
7269
- pad('NAME', nameWidth) +
7270
- ' ' +
7271
- pad('TYPE', typeWidth) +
7272
- ' ' +
7273
- pad('FROM', fromWidth) +
7274
- ' ' +
7275
- pad('STATUS', statusWidth) +
7276
- ' ' +
7277
- 'UPDATED';
7278
- const rows = page.items.map(t => pad(t.id, idWidth) +
7279
- ' ' +
7280
- pad(t.name, nameWidth) +
7281
- ' ' +
7282
- pad(t.type, typeWidth) +
7283
- ' ' +
7284
- pad(t.createdFrom, fromWidth) +
7285
- ' ' +
7286
- pad(t.status, statusWidth) +
7287
- ' ' +
7288
- t.updatedAt);
7289
- const lines = [header, ...rows];
8242
+ const lines = [
8243
+ renderTextTable(page.items, TEST_LIST_COLUMNS, {
8244
+ columns: options.columns,
8245
+ noHeader: options.noHeader,
8246
+ }),
8247
+ ];
7290
8248
  if (page.nextToken)
7291
8249
  lines.push('', `nextToken: ${page.nextToken}`);
7292
8250
  return lines.join('\n');
@@ -7485,7 +8443,7 @@ function plannedBundleFiles(ctx, failedOnly) {
7485
8443
  files.push('failure.json');
7486
8444
  files.push(`code.${pickCodeExtension(ctx.code.language, ctx.code.framework)}`);
7487
8445
  if (ctx.result.videoUrl)
7488
- files.push('video.mp4');
8446
+ files.push(`video.${pickVideoExtension(ctx.result.videoUrl)}`);
7489
8447
  const stepsToInclude = failedOnly
7490
8448
  ? ctx.steps.filter(s => {
7491
8449
  if (ctx.result.failedStepIndex === null)