@testsprite/testsprite-cli 0.4.0 → 0.6.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 +27 -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 +200 -10
  13. package/dist/commands/test.js +1636 -351
  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 +84 -0
  32. package/dist/lib/gh-output.js +202 -0
  33. package/dist/lib/http.d.ts +33 -15
  34. package/dist/lib/http.js +141 -7
  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 +72 -36
  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 +282 -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 +30 -1
  50. package/dist/lib/v3-advisory.js +35 -4
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +17 -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,29 @@
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 { emitTargetUrlV3Advisory } from '../lib/v3-advisory.js';
26
+ import { emitGithubOutputs, summarizeAcceptedPayload, summarizeSingleRun, } from '../lib/gh-output.js';
22
27
  import { loadConfig } from '../lib/config.js';
23
28
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
24
29
  /** The effective shutdown handle for a command invocation (DEV-331). */
@@ -39,6 +44,27 @@ function interruptDetachMessage(err, runIds) {
39
44
  ` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
40
45
  ` Cancel with: testsprite test cancel ${runIds.join(' ')}`);
41
46
  }
47
+ /**
48
+ * The honest-detach stderr line for a RATE_LIMITED (429) hit during a
49
+ * `--wait` poll. The backend's pre-auth rate limiter is an in-process LRU
50
+ * keyed on `request.ip`, checked before any DB contact — it can trip on a
51
+ * shared egress IP (a CI runner, a NAT) and then 429 otherwise-valid keys
52
+ * from that IP for its window. The run itself was already triggered (and is
53
+ * already billed) and keeps executing server-side regardless of this local
54
+ * poll giving up — mirrors `interruptDetachMessage` so the re-attach and
55
+ * cancel commands read identically across every detach reason.
56
+ */
57
+ function rateLimitedDetachMessage(err, runIds) {
58
+ const retrySuffix = err.retryAfterMs !== undefined
59
+ ? `; the server asked to retry after ~${Math.ceil(err.retryAfterMs / 1000)}s`
60
+ : '';
61
+ const subject = runIds.length === 1
62
+ ? `Run ${runIds[0]} is still executing on the server and will keep running (and billing) until it finishes.`
63
+ : `${runIds.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
64
+ return (`Rate limited by the server (HTTP 429)${retrySuffix}. ${subject}\n` +
65
+ ` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
66
+ ` Cancel with: testsprite test cancel ${runIds.join(' ')}`);
67
+ }
42
68
  const TEST_TYPES = ['frontend', 'backend'];
43
69
  // 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
44
70
  // tests created via `testsprite test create`, so the `--created-from cli`
@@ -86,7 +112,8 @@ export async function runList(opts, deps = {}) {
86
112
  // (exit 3) when the caller also lacks a configured key. Order matters
87
113
  // for the CLI error spec §2 — bad input is a caller bug, not an auth
88
114
  // gate.
89
- requireProjectId(opts.projectId);
115
+ const projectId = resolveProjectId(opts.projectId, deps);
116
+ requireProjectId(projectId);
90
117
  const paginationFlags = validatePaginationFlags({
91
118
  pageSize: opts.pageSize,
92
119
  startingToken: opts.startingToken,
@@ -98,13 +125,16 @@ export async function runList(opts, deps = {}) {
98
125
  // a round trip.
99
126
  validateStatusFilter(opts.status);
100
127
  const out = makeOutput(opts.output, deps);
128
+ if (opts.output === 'text') {
129
+ resolveTextColumns(opts.columns, TEST_LIST_COLUMNS);
130
+ }
101
131
  const client = makeClient(opts, deps);
102
132
  // Match P2's "explicit pageSize ⇒ single-page" convention so an
103
133
  // operator can grab one slice + cursor without auto-paging through a
104
134
  // huge project.
105
135
  const useSinglePage = opts.pageSize !== undefined && opts.maxItems === undefined;
106
136
  const baseQuery = {
107
- projectId: opts.projectId,
137
+ projectId,
108
138
  type: opts.type,
109
139
  createdFrom: opts.createdFrom,
110
140
  status: opts.status,
@@ -118,7 +148,7 @@ export async function runList(opts, deps = {}) {
118
148
  query: { ...baseQuery, pageSize, cursor },
119
149
  }), paginationFlags);
120
150
  }
121
- out.print(page, data => renderTestListText(data));
151
+ out.print(page, data => renderTestListText(data, { columns: opts.columns, noHeader: opts.noHeader }));
122
152
  return page;
123
153
  }
124
154
  export const CLI_CREATE_PRIORITIES = ['p0', 'p1', 'p2', 'p3'];
@@ -169,13 +199,24 @@ async function emitDupNameAdvisoryIfNeeded(client, projectId, name, stderrFn) {
169
199
  // Use an AbortController with a 5 s deadline. When the timer fires it
170
200
  // calls ac.abort(), which causes client.get (via the `signal` option) to
171
201
  // throw an AbortError — caught below and swallowed. This ensures a stalled
172
- // or retrying listing endpoint can't delay an otherwise-healthy create by
173
- // the full request-timeout (120 s) or multiple transport retries.
202
+ // listing endpoint can't delay an otherwise-healthy create by the full
203
+ // request-timeout (120 s).
174
204
  // No secondary setTimeout is used to avoid leaking timers in tests.
205
+ //
206
+ // The deadline alone is NOT sufficient, because `signal` is composed into
207
+ // the fetch only — `sleepBeforeRetry` observes the process-lifetime
208
+ // shutdown signal and nothing else, so a retry sleep runs to completion
209
+ // no matter what this controller does. A 429 carrying `Retry-After` is
210
+ // honoured up to 60 s per attempt across 3 attempts, which would park the
211
+ // create behind a best-effort advisory for up to ~2 minutes. `429` is a
212
+ // live response for CLI callers (the in-flight run cap returns it), so
213
+ // this is reachable, not theoretical. `retryOnRateLimit: false` makes the
214
+ // 429 throw straight into the catch below, which is the correct outcome
215
+ // for a lookup whose entire purpose is to be skippable.
175
216
  const ac = new AbortController();
176
217
  const timer = setTimeout(() => ac.abort(), DUP_NAME_ADVISORY_TIMEOUT_MS);
177
218
  try {
178
- const listing = await client.get(`/tests?projectId=${encodeURIComponent(projectId)}&pageSize=100`, { signal: ac.signal });
219
+ const listing = await client.get(`/tests?projectId=${encodeURIComponent(projectId)}&pageSize=100`, { signal: ac.signal, retryOnRateLimit: false });
179
220
  const nameLower = name.toLowerCase();
180
221
  const match = listing.items?.find(t => t.name.toLowerCase() === nameLower);
181
222
  if (match) {
@@ -219,7 +260,8 @@ export async function runCreate(opts, deps = {}) {
219
260
  assertChainedRunKeyFits(opts.run, opts.idempotencyKey);
220
261
  // Validate inputs before touching credentials or fs — matches the
221
262
  // M2 read commands' "input gates first, then auth, then I/O" ordering.
222
- requireProjectId(opts.projectId);
263
+ const projectId = resolveProjectId(opts.projectId, deps);
264
+ requireProjectId(projectId);
223
265
  requireNonEmpty('name', opts.name);
224
266
  // P1-3: client-side length checks matching server limits (name ≤200,
225
267
  // description ≤2000) so the user gets instant, actionable errors instead
@@ -295,7 +337,7 @@ export async function runCreate(opts, deps = {}) {
295
337
  stderr(`idempotency-key: ${idempotencyKey}`);
296
338
  }
297
339
  const body = {
298
- projectId: opts.projectId,
340
+ projectId,
299
341
  type: opts.type,
300
342
  name: opts.name,
301
343
  description: opts.description,
@@ -332,7 +374,7 @@ export async function runCreate(opts, deps = {}) {
332
374
  // B3: best-effort duplicate-name advisory. Skip under --dry-run.
333
375
  if (!opts.dryRun) {
334
376
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
335
- await emitDupNameAdvisoryIfNeeded(client, opts.projectId, opts.name, stderrFn);
377
+ await emitDupNameAdvisoryIfNeeded(client, projectId, opts.name, stderrFn);
336
378
  }
337
379
  const response = await client.post('/tests', {
338
380
  body,
@@ -352,10 +394,32 @@ export async function runCreate(opts, deps = {}) {
352
394
  // the merged { ...createContext, run } envelope in JSON mode and
353
395
  // appears on the Dashboard: stderr line in text mode.
354
396
  // R1: suppress under --dry-run (fake canned test id).
355
- const chainDashboardUrl = opts.dryRun
397
+ // DEV-737: prefer a server-provided dashboardUrl over the client guess
398
+ // (`withDashboardUrl`/`resolveDashboardUrl` above); when the server
399
+ // explicitly withheld one, never fall back to the client-computed
400
+ // V2-shaped link and tell the caller where to find the test instead.
401
+ const { entity: createContextWithUrl, suppressed: dashboardSuppressedOnRun } = withDashboardUrl(response, () => opts.dryRun
356
402
  ? undefined
357
- : resolvePortalUrl(resolveApiUrl(opts, deps), opts.projectId, response.testId);
358
- const createContextWithUrl = chainDashboardUrl !== undefined ? { ...response, dashboardUrl: chainDashboardUrl } : response;
403
+ : resolvePortalUrl(resolveApiUrl(opts, deps), projectId, response.testId));
404
+ const runDashboardStderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
405
+ if (dashboardSuppressedOnRun) {
406
+ emitDashboardLinkSuppressedAdvisory(response.testId, runDashboardStderrFn);
407
+ }
408
+ else if (opts.output !== 'json' && createContextWithUrl.dashboardUrl !== undefined) {
409
+ // Finding 3 (dogfood 2026-08-09): the merged create+run chain suppresses
410
+ // the create's own print (delegating to `runTestRun` -> `printRunOrChain`),
411
+ // whose text-mode header renders `createContext` via `renderCreateText` —
412
+ // which never prints `dashboardUrl` — and there is otherwise no stderr
413
+ // emission point for it on this chain (unlike the non-`--run` path below,
414
+ // which prints this same line explicitly). Without this, a text-mode
415
+ // `create --run` silently drops the authoritative link — worst on a
416
+ // no-wait V3 create, where the client cannot recompute it at all. Mirrors
417
+ // the non-run path's three-state handling exactly: a suppressed (`null`)
418
+ // server link takes the advisory branch above instead (no legacy guess);
419
+ // an absent key already resolved to the legacy client fallback (or
420
+ // `undefined` when unmapped) via `createContextWithUrl` above.
421
+ runDashboardStderrFn(`Dashboard: ${createContextWithUrl.dashboardUrl}`);
422
+ }
359
423
  await runTestRun({
360
424
  ...opts,
361
425
  testId: response.testId,
@@ -377,11 +441,16 @@ export async function runCreate(opts, deps = {}) {
377
441
  // (no extra network call — both come from opts / response).
378
442
  // R1: suppress under --dry-run — the test id is a fake canned value
379
443
  // (e.g. "test_dryrun_create_2026") and a live-looking URL would mislead.
380
- const dashboardUrl = opts.dryRun
444
+ // DEV-737: prefer a server-provided dashboardUrl over the client guess;
445
+ // never fall back when the server explicitly withheld one (see
446
+ // `withDashboardUrl`/`resolveDashboardUrl` above), and tell the caller
447
+ // where to find the test instead of printing a link that would 404.
448
+ const { entity: responseWithDashboardUrl, suppressed: dashboardSuppressed } = withDashboardUrl(response, () => opts.dryRun
381
449
  ? undefined
382
- : resolvePortalUrl(resolveApiUrl(opts, deps), opts.projectId, response.testId);
450
+ : resolvePortalUrl(resolveApiUrl(opts, deps), projectId, response.testId));
451
+ const dashboardUrl = responseWithDashboardUrl.dashboardUrl ?? undefined;
383
452
  if (opts.output === 'json') {
384
- out.print(dashboardUrl !== undefined ? { ...response, dashboardUrl } : response, data => renderCreateText(data));
453
+ out.print(responseWithDashboardUrl, data => renderCreateText(data));
385
454
  }
386
455
  else {
387
456
  out.print(response, data => renderCreateText(data));
@@ -390,6 +459,9 @@ export async function runCreate(opts, deps = {}) {
390
459
  stderrFn(`Dashboard: ${dashboardUrl}`);
391
460
  }
392
461
  }
462
+ if (dashboardSuppressed) {
463
+ emitDashboardLinkSuppressedAdvisory(response.testId, deps.stderr ?? (line => process.stderr.write(`${line}\n`)));
464
+ }
393
465
  return response;
394
466
  }
395
467
  /**
@@ -590,6 +662,18 @@ function renderPlanPutText(response) {
590
662
  * 256 KB (vs. 350 KB for code) per the piece-6 spec.
591
663
  */
592
664
  function readPlanStepsFileGuarded(path) {
665
+ return assertPlanStepsShape(parsePlanStepsFile(path));
666
+ }
667
+ /**
668
+ * File I/O + JSON.parse half of `readPlanStepsFileGuarded`, split out so
669
+ * `test lint` can reuse the SAME stat/size/read/parse guards while
670
+ * substituting the collect-all `collectPlanStepsIssues` shape check for the
671
+ * throw-on-first `assertPlanStepsShape` that `test plan put` still uses. A
672
+ * failure here (missing file, oversize, invalid JSON syntax) is always a
673
+ * single fatal issue either way — there is nothing left to validate once the
674
+ * file itself can't be read or parsed.
675
+ */
676
+ function parsePlanStepsFile(path) {
593
677
  const absolute = resolveAbsolute(path);
594
678
  let stat;
595
679
  try {
@@ -629,15 +713,13 @@ function readPlanStepsFileGuarded(path) {
629
713
  const reason = err instanceof Error ? err.message : 'unknown error';
630
714
  throw localValidationError('steps', `cannot read ${path}: ${reason}`);
631
715
  }
632
- let parsed;
633
716
  try {
634
- parsed = JSON.parse(raw);
717
+ return JSON.parse(raw);
635
718
  }
636
719
  catch (err) {
637
720
  const reason = err instanceof Error ? err.message : 'unknown error';
638
721
  throw localValidationError('steps', `not valid JSON: ${reason}`);
639
722
  }
640
- return assertPlanStepsShape(parsed);
641
723
  }
642
724
  /**
643
725
  * Type-narrow + validate a parsed `{ planSteps: [...] }` envelope.
@@ -669,6 +751,59 @@ function assertPlanStepsShape(parsed) {
669
751
  }
670
752
  return stepsRaw;
671
753
  }
754
+ /**
755
+ * Collect-all counterpart to `assertPlanStepsShape` — same field checks
756
+ * (reusing the identical `requireArrayLength`/`requireEnum`/`requireString`
757
+ * helpers so wording never drifts), but continues past the first failing
758
+ * field instead of throwing. Used exclusively by `test lint`: a
759
+ * `--steps` file with several bad steps previously cost one fix-and-rerun
760
+ * cycle per step. `assertPlanStepsShape` itself is UNCHANGED and stays
761
+ * throw-on-first — `test plan put` only needs the first blocking error per
762
+ * network round-trip.
763
+ */
764
+ function collectPlanStepsIssues(parsed) {
765
+ const issues = [];
766
+ const check = (validate) => {
767
+ try {
768
+ validate();
769
+ }
770
+ catch (err) {
771
+ issues.push(toLintIssue(err));
772
+ }
773
+ };
774
+ let stepsRaw;
775
+ if (Array.isArray(parsed)) {
776
+ stepsRaw = parsed;
777
+ }
778
+ else if (typeof parsed === 'object' && parsed !== null) {
779
+ stepsRaw = parsed.planSteps;
780
+ }
781
+ else {
782
+ issues.push({ field: 'steps', reason: 'must be a JSON object with a `planSteps` array' });
783
+ return issues;
784
+ }
785
+ check(() => requireArrayLength('planSteps', stepsRaw, { min: 1, max: MAX_PLAN_STEPS, itemNoun: 'step' }));
786
+ // A length/cap violation (e.g. 201 steps, over
787
+ // MAX_PLAN_STEPS) does NOT mean there's nothing left to check — `stepsRaw`
788
+ // is still a real, iterable array, so per-element problems must be
789
+ // collected too (a 201-step file with a bad step 0 must report the cap
790
+ // issue AND planSteps[0].type/description in the SAME pass, not one or the
791
+ // other). Only bail when `stepsRaw` isn't an array at all — `requireArrayLength`'s
792
+ // structural check failed, so there is genuinely nothing to iterate.
793
+ if (!Array.isArray(stepsRaw))
794
+ return issues;
795
+ for (let i = 0; i < stepsRaw.length; i += 1) {
796
+ const step = stepsRaw[i];
797
+ if (typeof step !== 'object' || step === null || Array.isArray(step)) {
798
+ issues.push({ field: `planSteps[${i}]`, reason: 'must be an object' });
799
+ continue;
800
+ }
801
+ const s = step;
802
+ check(() => requireEnum(`planSteps[${i}].type`, s.type, PLAN_STEP_TYPES));
803
+ check(() => requireString(`planSteps[${i}].description`, s.description));
804
+ }
805
+ return issues;
806
+ }
672
807
  /**
673
808
  * `test update <test-id>` — M3.2 piece-3.
674
809
  *
@@ -960,6 +1095,84 @@ function renderBulkDeleteText(bulk) {
960
1095
  return [header, ...rows].join('\n');
961
1096
  }
962
1097
  const PLAN_STEP_TYPES = ['action', 'assertion'];
1098
+ /**
1099
+ * Public raw-content URL for
1100
+ * `schemas/plan.schema.json`, shipped in both the npm package (see
1101
+ * `package.json` `files`) and the repo. Points at the PUBLIC mirror
1102
+ * (`TestSprite/testsprite-cli`) since that's what ships to npm consumers;
1103
+ * the private atlas repo syncs to it via `scripts/make-public-snapshot.sh`.
1104
+ *
1105
+ * Pinned to the running CLI's own `v<VERSION>` git tag (the same `VERSION`
1106
+ * constant `--version` / `doctor` / the update-check registry probe already
1107
+ * read from `src/version.ts`) rather than the mutable `main` branch — a plan
1108
+ * file authored against one CLI version should resolve the SAME schema
1109
+ * forever, not whatever `main` happens to contain when the file is opened
1110
+ * months later (`main` can gain new required fields between versions).
1111
+ *
1112
+ * This is deliberately DIFFERENT from `schemas/plan.schema.json`'s own
1113
+ * internal `$id`, which stays the canonical `main` URL — `$id` is a schema
1114
+ * IDENTITY (what this document calls itself, used for cross-referencing),
1115
+ * not a fetch instruction, so it is intentionally version-independent.
1116
+ * `PLAN_SCHEMA_URL` is the fetch instruction embedded in generated plan
1117
+ * files and is intentionally version-PINNED. See DOCUMENTATION.md's "Plan
1118
+ * file format" section for the same distinction spelled out for humans.
1119
+ *
1120
+ * Caveat: the pinned tag only resolves once that version is actually
1121
+ * released — a locally-built/pre-release checkout may see a 404 until then.
1122
+ */
1123
+ export const PLAN_SCHEMA_URL = `https://raw.githubusercontent.com/TestSprite/testsprite-cli/v${VERSION}/schemas/plan.schema.json`;
1124
+ /**
1125
+ * The SINGLE canonical example plan. This
1126
+ * exact value (via `PLAN_TEMPLATE_TEXT` below) is:
1127
+ * - printed to stdout by `test create --plan-template`
1128
+ * - embedded verbatim in `test create --help` (`PLAN_TEMPLATE_HELP_TEXT`)
1129
+ * - asserted in tests against `schemas/plan.schema.json` and against
1130
+ * `assertPlanShape` so the three surfaces can't drift
1131
+ *
1132
+ * Deliberately minimal (no optional `description`/`priority`) — this is
1133
+ * the smallest shape `assertPlanShape` accepts, not a fully-annotated
1134
+ * showcase (that lives in `skills/testsprite-verify.skill.md`).
1135
+ */
1136
+ export const PLAN_TEMPLATE = {
1137
+ projectId: 'prj_abc123',
1138
+ type: 'frontend',
1139
+ name: 'Login rejects an empty password',
1140
+ planSteps: [
1141
+ {
1142
+ type: 'action',
1143
+ description: 'Navigate to /login and submit the form with an empty password',
1144
+ },
1145
+ {
1146
+ type: 'assertion',
1147
+ description: 'Verify an inline error says the password is required',
1148
+ },
1149
+ ],
1150
+ };
1151
+ /**
1152
+ * `$schema` is an ordinary extra property from `assertPlanShape`'s point of
1153
+ * view (no `additionalProperties` check exists on the plan-from path) — it
1154
+ * validates exactly like a bare `CliPlanInput` while giving editors (VS
1155
+ * Code's JSON language service, and by extension Copilot inline
1156
+ * completions) something to resolve for live validation as the file is
1157
+ * edited.
1158
+ */
1159
+ export const PLAN_TEMPLATE_WITH_SCHEMA = {
1160
+ $schema: PLAN_SCHEMA_URL,
1161
+ ...PLAN_TEMPLATE,
1162
+ };
1163
+ /**
1164
+ * Rendered once from the object above (never hand-formatted separately) so
1165
+ * `test create --plan-template`'s stdout and `test create --help`'s example
1166
+ * are generated from — not merely modeled on — the same source.
1167
+ */
1168
+ export const PLAN_TEMPLATE_TEXT = JSON.stringify(PLAN_TEMPLATE_WITH_SCHEMA, null, 2);
1169
+ /** `test create --help` after-text. Wraps `PLAN_TEMPLATE_TEXT` unmodified. */
1170
+ const PLAN_TEMPLATE_HELP_TEXT = '\nPlan file format (--plan-from <file>) — minimal valid example:\n\n' +
1171
+ `${PLAN_TEMPLATE_TEXT}\n\n` +
1172
+ 'Print this exact skeleton: testsprite test create --plan-template\n' +
1173
+ 'Validate offline (no network): testsprite test create --plan-from <file> --dry-run\n' +
1174
+ 'Multiple tests: test create-batch --plans <file.jsonl> | --plan-from-dir <dir>\n' +
1175
+ 'Full field reference: DOCUMENTATION.md -> "Plan file format"\n';
963
1176
  /**
964
1177
  * 200-step + 256 KB caps on a single plan body. The CLI
965
1178
  * enforces both client-side as a pre-flight guard so an obvious
@@ -990,6 +1203,33 @@ const MAX_BATCH_RERUN_IDS = 50;
990
1203
  * the caller can warn the operator that a shared BE producer/teardown was
991
1204
  * triggered more than once.
992
1205
  */
1206
+ /**
1207
+ * Dedupe `RerunAdvisory[]` by `feature`+`message`. Used to aggregate
1208
+ * `advisories` across chunked batch-rerun dispatch requests (initial dispatch
1209
+ * + D3 deferred-retry attempts) into a single list, and to collapse repeated
1210
+ * per-attempt advisories in `test flaky` into a single summary line.
1211
+ */
1212
+ function dedupeRerunAdvisories(entries) {
1213
+ const seen = new Map();
1214
+ for (const entry of entries) {
1215
+ seen.set(`${entry.feature}|${entry.message}`, entry);
1216
+ }
1217
+ return [...seen.values()];
1218
+ }
1219
+ /**
1220
+ * Print one `[advisory]` stderr line per entry in `advisories`. Mirrors the
1221
+ * existing style of the other rerun advisories (auto-heal engaged / not
1222
+ * applied, BE rerun history). No-op when `advisories` is absent or empty —
1223
+ * this is the common case (every V2 response, every V3 response that did not
1224
+ * request an autoHeal:false opt-out).
1225
+ */
1226
+ function emitRerunAdvisories(stderrFn, advisories) {
1227
+ if (!advisories || advisories.length === 0)
1228
+ return;
1229
+ for (const advisory of advisories) {
1230
+ stderrFn(`[advisory] ${advisory.message}`);
1231
+ }
1232
+ }
993
1233
  function dedupeBatchRerunAccepted(entries) {
994
1234
  const seen = new Map();
995
1235
  let droppedCount = 0;
@@ -1059,6 +1299,60 @@ export const BATCH_RUN_RATE_LIMIT = 50;
1059
1299
  export const BATCH_RUN_RATE_WINDOW_MS = 60_000;
1060
1300
  /** Maximum number of outer RATE_LIMITED retries inside the batch fan-out (beyond HTTP-layer retries). */
1061
1301
  export const BATCH_RUN_RATE_MAX_OUTER_RETRIES = 5;
1302
+ /**
1303
+ * Maximum number of outer RATE_LIMITED retries per member inside the multi-id
1304
+ * `test wait` fan-out (beyond HTTP-layer retries). Lower than the trigger
1305
+ * fan-out's budget on purpose: a throttled *poll* costs nothing but latency and
1306
+ * the run is already executing, so a couple of Retry-After-length backoffs is
1307
+ * enough to ride out one limiter window — burning the whole `--timeout` on
1308
+ * backoff instead of reporting the throttle would be worse than reporting it.
1309
+ */
1310
+ export const WAIT_POLL_RATE_MAX_OUTER_RETRIES = 3;
1311
+ /**
1312
+ * Backoff to honour before retrying a `RATE_LIMITED` response, in ms.
1313
+ *
1314
+ * Precedence: `ApiError.retryAfterMs` (set by `HttpClient` from the HTTP
1315
+ * `Retry-After` header, already clamped to [1s, 300s]) → `details.retryAfterSeconds`
1316
+ * from the envelope body, capped at 120s → 60s. Callers clamp the result to their
1317
+ * own remaining deadline; this function only decides "how long does the server
1318
+ * want us to wait."
1319
+ *
1320
+ * Shared by the `test run --all` trigger fan-out and the multi-id `test wait`
1321
+ * poll fan-out so the two can't drift — they were hand-copies of the same
1322
+ * precedence rule.
1323
+ */
1324
+ /**
1325
+ * Sleep that a termination signal cuts short by rejecting with the signal's
1326
+ * `InterruptError`, so the caller's existing DEV-331 catch owns the detach UX.
1327
+ *
1328
+ * Mirrors `HttpClient.sleepBeforeRetry` — an in-flight backoff must not be a
1329
+ * window where a first Ctrl-C hard-exits with empty stdout. The caller is
1330
+ * responsible for having ARMED the shutdown scope; a disarmed controller never
1331
+ * aborts its signal, so this would otherwise sleep straight through the signal.
1332
+ */
1333
+ export function sleepUntilOrInterrupt(ms, signal, sleep) {
1334
+ if (signal === undefined)
1335
+ return sleep(ms);
1336
+ if (signal.aborted)
1337
+ return Promise.reject(signal.reason);
1338
+ return new Promise((resolve, reject) => {
1339
+ const onAbort = () => reject(signal.reason);
1340
+ signal.addEventListener('abort', onAbort, { once: true });
1341
+ sleep(ms).then(() => {
1342
+ signal.removeEventListener('abort', onAbort);
1343
+ resolve();
1344
+ }, err => {
1345
+ signal.removeEventListener('abort', onAbort);
1346
+ reject(err instanceof Error ? err : new Error(String(err)));
1347
+ });
1348
+ });
1349
+ }
1350
+ export function resolveRateLimitRetryMs(err) {
1351
+ if (err.retryAfterMs !== undefined)
1352
+ return err.retryAfterMs;
1353
+ const retryAfterSec = err.getDetail('retryAfterSeconds', (v) => typeof v === 'number' && v > 0);
1354
+ return Math.min((retryAfterSec ?? 60) * 1000, 120_000);
1355
+ }
1062
1356
  /**
1063
1357
  * D3: max automatic retry attempts for deferred tests under `--wait`.
1064
1358
  * Each attempt is preceded by a Retry-After-aware sleep (server value if
@@ -1115,6 +1409,46 @@ export function isTransientRateLimit(err) {
1115
1409
  // Absent all signals → treat as permanent (credit depletion or unknown).
1116
1410
  return false;
1117
1411
  }
1412
+ /** Matches `{{ANYTHING}}`-style template placeholders in a step description. */
1413
+ const PLACEHOLDER_PATTERN = /\{\{.*?\}\}/;
1414
+ /**
1415
+ * Indices of `planSteps` whose `description` contains a
1416
+ * `{{...}}`-style placeholder. Structurally valid (schema-and-validator
1417
+ * agree these plans pass) — this is a content-quality signal, not a shape
1418
+ * violation, so it's surfaced separately as a non-fatal advisory rather
1419
+ * than folded into `assertPlanShape`.
1420
+ */
1421
+ function findPlaceholderStepIndices(plan) {
1422
+ const indices = [];
1423
+ plan.planSteps.forEach((step, i) => {
1424
+ if (PLACEHOLDER_PATTERN.test(step.description))
1425
+ indices.push(i);
1426
+ });
1427
+ return indices;
1428
+ }
1429
+ /**
1430
+ * Non-fatal `[advisory]` when one or more `planSteps[].description` values
1431
+ * contain a `{{...}}`-style placeholder — the most common false assumption
1432
+ * agent-authored plans make (that the CLI does variable substitution). The
1433
+ * CLI does none: the browser agent types the literal braces into the
1434
+ * field. Points at storing credentials on the project instead, which is
1435
+ * the actual mechanism for injecting auth into a run.
1436
+ */
1437
+ function emitPlaceholderAdvisory(plan, stderrFn) {
1438
+ const indices = findPlaceholderStepIndices(plan);
1439
+ if (indices.length === 0)
1440
+ return;
1441
+ // Each path must read
1442
+ // `planSteps[N].description` on its OWN — appending `.description` once
1443
+ // after a joined `planSteps[0], planSteps[2]` list misattributed it to
1444
+ // only the last entry.
1445
+ const paths = indices.map(i => `planSteps[${i}].description`).join(', ');
1446
+ const verb = indices.length === 1 ? 'contains' : 'contain';
1447
+ stderrFn(`[advisory] ${paths} ${verb} a ` +
1448
+ '`{{...}}`-style placeholder; the CLI does no variable substitution — ' +
1449
+ 'the browser agent will type the literal braces. Store login credentials on the project instead: ' +
1450
+ '`testsprite project update <project-id> --username <user> --password <pw>`, or Portal -> Project Settings.');
1451
+ }
1118
1452
  /**
1119
1453
  * `test create --plan-from <plan.json>` — M3.2 piece-5.
1120
1454
  *
@@ -1144,14 +1478,20 @@ export async function runCreateFromPlan(opts, deps = {}) {
1144
1478
  if (opts.targetUrl !== undefined) {
1145
1479
  assertNotLocal(opts.targetUrl);
1146
1480
  }
1147
- const plan = readPlanFromGuarded(opts.planFrom);
1481
+ const plan = readPlanFromGuarded(opts.planFrom, { ignoredFlags: opts.ignoredFlags });
1482
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1483
+ // Non-fatal advisory for `{{...}}`-style placeholders in step
1484
+ // descriptions. The CLI does no variable substitution — the browser agent
1485
+ // types the literal braces — so this is a content-quality nudge, not a
1486
+ // validation failure. Fires regardless of --dry-run (dry-run still runs
1487
+ // full local validation; this advisory is part of that same offline pass).
1488
+ emitPlaceholderAdvisory(plan, stderrFn);
1148
1489
  // The plan validated (projectId/type/name/planSteps present). Only NOW
1149
1490
  // warn that overlapping `test create` flags were ignored — emitting this
1150
1491
  // before validation made a missing-projectId failure look like the
1151
1492
  // ignored --project flag was the cause (dogfood L1778).
1152
1493
  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(', ')}. ` +
1494
+ stderrFn(`warning: --plan-from supplies the test definition; ignoring ${opts.ignoredFlags.join(', ')}. ` +
1155
1495
  `Edit the plan JSON to change these fields.`);
1156
1496
  }
1157
1497
  // FE-only after the 2026-05-13 scope cut. The server also rejects
@@ -1170,8 +1510,7 @@ export async function runCreateFromPlan(opts, deps = {}) {
1170
1510
  }
1171
1511
  const idempotencyKey = opts.idempotencyKey ?? `cli-create-plan-${randomUUID()}`;
1172
1512
  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}`);
1513
+ stderrFn(`idempotency-key: ${idempotencyKey}`);
1175
1514
  }
1176
1515
  const body = {
1177
1516
  projectId: plan.projectId,
@@ -1187,7 +1526,6 @@ export async function runCreateFromPlan(opts, deps = {}) {
1187
1526
  // The plan's projectId + name are available after validation above. Skip
1188
1527
  // under dry-run (no network calls); swallow all errors (advisory only).
1189
1528
  if (!opts.dryRun) {
1190
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1191
1529
  await emitDupNameAdvisoryIfNeeded(client, plan.projectId, plan.name, stderrFn);
1192
1530
  }
1193
1531
  const response = await client.post('/tests', {
@@ -1197,9 +1535,14 @@ export async function runCreateFromPlan(opts, deps = {}) {
1197
1535
  // Fix 5 (plan-from coverage): the projectId for the deep-link comes from
1198
1536
  // the validated PLAN body (not opts — `--plan-from` has no --project-id
1199
1537
  // flag). Same dry-run suppression as runCreate (fake canned test id).
1200
- const planDashboardUrl = opts.dryRun
1538
+ // DEV-737: prefer a server-provided dashboardUrl over the client guess
1539
+ // (`withDashboardUrl`/`resolveDashboardUrl`, defined near
1540
+ // `withRunDashboardUrl`); never fall back when the server explicitly
1541
+ // withheld one, and tell the caller where to find the test instead.
1542
+ const { entity: responseWithDashboardUrl, suppressed: planDashboardSuppressed } = withDashboardUrl(response, () => opts.dryRun
1201
1543
  ? undefined
1202
- : resolvePortalUrl(resolveApiUrl(opts, deps), plan.projectId, response.testId);
1544
+ : resolvePortalUrl(resolveApiUrl(opts, deps), plan.projectId, response.testId));
1545
+ const planDashboardUrl = responseWithDashboardUrl.dashboardUrl ?? undefined;
1203
1546
  // --run chain (M3.3 piece-3): trigger + optionally wait. Per codex
1204
1547
  // round-1 P1: suppress the create's own print when chaining;
1205
1548
  // `runTestRun` emits a single merged envelope on stdout.
@@ -1207,7 +1550,9 @@ export async function runCreateFromPlan(opts, deps = {}) {
1207
1550
  // Idempotency key for the run is the create key + ":run" suffix so a
1208
1551
  // retry of the whole chain gets the same runId. Per piece-3 spec.
1209
1552
  const runIdempotencyKey = `${idempotencyKey}:run`;
1210
- const createContextWithUrl = planDashboardUrl !== undefined ? { ...response, dashboardUrl: planDashboardUrl } : response;
1553
+ if (planDashboardSuppressed) {
1554
+ emitDashboardLinkSuppressedAdvisory(response.testId, stderrFn);
1555
+ }
1211
1556
  return runTestRun({
1212
1557
  ...opts,
1213
1558
  testId: response.testId,
@@ -1217,19 +1562,21 @@ export async function runCreateFromPlan(opts, deps = {}) {
1217
1562
  // first-run hint fires for `test create --plan-from --run --wait`.
1218
1563
  timeoutIsDefault: opts.timeoutIsDefault ?? false,
1219
1564
  wait: opts.wait === true,
1220
- createContext: createContextWithUrl,
1565
+ createContext: responseWithDashboardUrl,
1221
1566
  }, deps).then(() => response);
1222
1567
  }
1223
1568
  if (opts.output === 'json') {
1224
- out.print(planDashboardUrl !== undefined ? { ...response, dashboardUrl: planDashboardUrl } : response, data => renderCreateText(data));
1569
+ out.print(responseWithDashboardUrl, data => renderCreateText(data));
1225
1570
  }
1226
1571
  else {
1227
1572
  out.print(response, data => renderCreateText(data));
1228
1573
  if (planDashboardUrl !== undefined) {
1229
- const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1230
1574
  stderrFn(`Dashboard: ${planDashboardUrl}`);
1231
1575
  }
1232
1576
  }
1577
+ if (planDashboardSuppressed) {
1578
+ emitDashboardLinkSuppressedAdvisory(response.testId, stderrFn);
1579
+ }
1233
1580
  return response;
1234
1581
  }
1235
1582
  /**
@@ -1241,7 +1588,23 @@ export async function runCreateFromPlan(opts, deps = {}) {
1241
1588
  * obvious oversize files BEFORE loading them into V8's heap. For
1242
1589
  * plans the cap is 256 KB (vs. 350 KB for code).
1243
1590
  */
1244
- function readPlanFromGuarded(path) {
1591
+ function readPlanFromGuarded(path, context = {}) {
1592
+ return assertPlanShape(parsePlanFile(path), context);
1593
+ }
1594
+ /**
1595
+ * File I/O + JSON.parse half of `readPlanFromGuarded`, split out so `test
1596
+ * lint` can reuse the SAME stat/size/read/parse guards while
1597
+ * substituting the collect-all `collectPlanIssues` shape check for the
1598
+ * throw-on-first `assertPlanShape` that `create`/`create-batch` still use. A
1599
+ * failure here (missing file, oversize, invalid JSON syntax) is always a
1600
+ * single fatal issue either way — there is nothing left to validate once the
1601
+ * file itself can't be read or parsed.
1602
+ *
1603
+ * Stat-first guard mirrors piece-2's `readCodeFileGuarded` — reject
1604
+ * obvious oversize files BEFORE loading them into V8's heap. For
1605
+ * plans the cap is 256 KB (vs. 350 KB for code).
1606
+ */
1607
+ function parsePlanFile(path) {
1245
1608
  const absolute = resolveAbsolute(path);
1246
1609
  let stat;
1247
1610
  try {
@@ -1281,15 +1644,45 @@ function readPlanFromGuarded(path) {
1281
1644
  const reason = err instanceof Error ? err.message : 'unknown error';
1282
1645
  throw localValidationError('plan-from', `cannot read ${path}: ${reason}`);
1283
1646
  }
1284
- let parsed;
1285
1647
  try {
1286
- parsed = JSON.parse(raw);
1648
+ return JSON.parse(raw);
1287
1649
  }
1288
1650
  catch (err) {
1289
1651
  const reason = err instanceof Error ? err.message : 'unknown error';
1290
1652
  throw localValidationError('plan-from', `not valid JSON: ${reason}`);
1291
1653
  }
1292
- return assertPlanShape(parsed);
1654
+ }
1655
+ /**
1656
+ * Rethrow a validation error enriched with a note that the
1657
+ * caller's `--project`/`--type`/`--name` flag was ignored, but ONLY when
1658
+ * that flag was actually supplied. Keeps the L1778 ordering intact
1659
+ * (validation still runs, and still throws, before the general
1660
+ * ignored-flags warning in `runCreateFromPlan`) — this only changes the
1661
+ * WORDING of the validation error itself so the one hint that would
1662
+ * explain a missing-field failure lands inside the error the caller
1663
+ * already sees, instead of depending on a separate warning that (per
1664
+ * L1778) deliberately fires after validation succeeds.
1665
+ */
1666
+ function appendIgnoredFlagNote(err, flag) {
1667
+ return new ApiError({
1668
+ code: err.code,
1669
+ message: err.message,
1670
+ nextAction: `${err.nextAction} note: with --plan-from, ${flag} is ignored; all fields live inside the file.`,
1671
+ requestId: err.requestId,
1672
+ details: err.details,
1673
+ });
1674
+ }
1675
+ /** Runs `fn`, enriching any thrown `ApiError` via {@link appendIgnoredFlagNote} when `flag` was ignored. */
1676
+ function requireFieldNotIgnored(fn, flag, ignoredFlags) {
1677
+ try {
1678
+ return fn();
1679
+ }
1680
+ catch (err) {
1681
+ if (err instanceof ApiError && ignoredFlags?.includes(flag)) {
1682
+ throw appendIgnoredFlagNote(err, flag);
1683
+ }
1684
+ throw err;
1685
+ }
1293
1686
  }
1294
1687
  /**
1295
1688
  * Type-narrow + validate a parsed plan input. Pulled out so the same
@@ -1297,26 +1690,55 @@ function readPlanFromGuarded(path) {
1297
1690
  * `create-batch --plans`. Throws `VALIDATION_ERROR` with a typed
1298
1691
  * `details.field` pointer so callers can fix specific issues without
1299
1692
  * re-reading the whole file.
1693
+ *
1694
+ * `context.ignoredFlags` is populated only on the single
1695
+ * `--plan-from` path (`test create --plan-from` also received overlapping
1696
+ * `--project`/`--type`/`--name` flags); batch/dir/JSONL callers never pass
1697
+ * it, so `requireFieldNotIgnored` below is a no-op for them.
1698
+ *
1699
+ * Throw-on-first is intentional here: `create` / `create-batch` POST over
1700
+ * the network, so surfacing the first blocking error per round-trip is the
1701
+ * right cost/detail tradeoff. `test lint`'s collect-all sibling is
1702
+ * `collectPlanIssues` below — do not merge the two; the doc comment on
1703
+ * `collectPlanIssues` explains why they must stay separate.
1300
1704
  */
1301
1705
  function assertPlanShape(parsed, context = {}) {
1302
1706
  const prefix = context.specIndex !== undefined ? `specs[${context.specIndex}].` : '';
1707
+ // A top-level JSON array is the single most common
1708
+ // agent-authored mistake: a plan file holds exactly ONE test. Give it a
1709
+ // dedicated message pointing at the batch surfaces, instead of the
1710
+ // generic "must be a JSON object" (which doesn't say what to do about an
1711
+ // array).
1712
+ if (Array.isArray(parsed)) {
1713
+ throw localValidationError(`${prefix}plan`, `a plan file holds ONE test as a single JSON object (got an array of ${parsed.length}). ` +
1714
+ 'To create many tests use `test create-batch --plans <file.jsonl>` or `--plan-from-dir <dir>`', undefined, 'field');
1715
+ }
1303
1716
  // Every field below is a JSON body path inside the plan file (or
1304
1717
  // JSONL spec), not a CLI flag — pass `'field'` so the error message
1305
1718
  // says `Field \`projectId\` is invalid: ...` instead of inventing a
1306
1719
  // `--projectId` flag the user can't pass.
1307
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
1720
+ if (typeof parsed !== 'object' || parsed === null) {
1308
1721
  throw localValidationError(`${prefix}plan`, 'must be a JSON object', undefined, 'field');
1309
1722
  }
1310
1723
  const obj = parsed;
1311
- requireString(`${prefix}projectId`, obj.projectId);
1312
- requireEnum(`${prefix}type`, obj.type, ['frontend', 'backend']);
1313
- requireString(`${prefix}name`, obj.name);
1724
+ requireFieldNotIgnored(() => requireString(`${prefix}projectId`, obj.projectId), '--project', context.ignoredFlags);
1725
+ requireFieldNotIgnored(() => requireEnum(`${prefix}type`, obj.type, ['frontend', 'backend']), '--type', context.ignoredFlags);
1726
+ requireFieldNotIgnored(() => requireString(`${prefix}name`, obj.name), '--name', context.ignoredFlags);
1314
1727
  if (obj.description !== undefined && typeof obj.description !== 'string') {
1315
1728
  throw localValidationError(`${prefix}description`, 'must be a string when present', undefined, 'field');
1316
1729
  }
1317
1730
  if (obj.priority !== undefined) {
1318
1731
  requireEnum(`${prefix}priority`, obj.priority, CLI_CREATE_PRIORITIES);
1319
1732
  }
1733
+ // `planSteps` missing is the single most common agent
1734
+ // hallucination: LLMs (Copilot included) reliably nest steps under
1735
+ // `plan.steps` or a bare top-level `steps`. Point directly at the fix
1736
+ // instead of falling through to the generic "is required and must be an
1737
+ // array" message, which doesn't say WHERE the steps actually belong.
1738
+ if (obj.planSteps === undefined && (obj.plan !== undefined || obj.steps !== undefined)) {
1739
+ throw localValidationError(`${prefix}planSteps`, 'is required and must be an array. Did you mean `planSteps`? Steps live at the top level: ' +
1740
+ '`"planSteps": [{ "type": "action" | "assertion", "description": "..." }]`', undefined, 'field');
1741
+ }
1320
1742
  requireArrayLength(`${prefix}planSteps`, obj.planSteps, {
1321
1743
  min: 1,
1322
1744
  max: MAX_PLAN_STEPS,
@@ -1333,6 +1755,64 @@ function assertPlanShape(parsed, context = {}) {
1333
1755
  }
1334
1756
  return obj;
1335
1757
  }
1758
+ /**
1759
+ * Collect-all counterpart to `assertPlanShape` — same field checks (reusing
1760
+ * the identical `requireString`/`requireEnum`/`requireArrayLength` helpers
1761
+ * so wording never drifts), but continues past the first failing field
1762
+ * instead of throwing. Used exclusively by `test lint` (issue #98
1763
+ * follow-up): the throw-on-first
1764
+ * `assertPlanShape` meant a plan with 6 independent problems reported one at
1765
+ * a time across 6 fix-and-rerun cycles. `assertPlanShape` itself is
1766
+ * UNCHANGED — `create`/`create-batch` only need the first blocking error per
1767
+ * network round-trip, and duplicating the field checks here (rather than
1768
+ * threading a "collect" flag through the throw-on-first assert) keeps both
1769
+ * functions simple and matches the existing sibling-validator convention
1770
+ * already used between `assertPlanShape` and `assertPlanStepsShape`.
1771
+ */
1772
+ function collectPlanIssues(parsed, context = {}) {
1773
+ const prefix = context.specIndex !== undefined ? `specs[${context.specIndex}].` : '';
1774
+ const issues = [];
1775
+ const check = (validate) => {
1776
+ try {
1777
+ validate();
1778
+ }
1779
+ catch (err) {
1780
+ issues.push(toLintIssue(err));
1781
+ }
1782
+ };
1783
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
1784
+ issues.push({ field: `${prefix}plan`, reason: 'must be a JSON object' });
1785
+ return issues;
1786
+ }
1787
+ const obj = parsed;
1788
+ check(() => requireString(`${prefix}projectId`, obj.projectId));
1789
+ check(() => requireEnum(`${prefix}type`, obj.type, ['frontend', 'backend']));
1790
+ check(() => requireString(`${prefix}name`, obj.name));
1791
+ if (obj.description !== undefined && typeof obj.description !== 'string') {
1792
+ issues.push({ field: `${prefix}description`, reason: 'must be a string when present' });
1793
+ }
1794
+ if (obj.priority !== undefined) {
1795
+ check(() => requireEnum(`${prefix}priority`, obj.priority, CLI_CREATE_PRIORITIES));
1796
+ }
1797
+ check(() => requireArrayLength(`${prefix}planSteps`, obj.planSteps, {
1798
+ min: 1,
1799
+ max: MAX_PLAN_STEPS,
1800
+ itemNoun: 'step',
1801
+ }));
1802
+ if (Array.isArray(obj.planSteps)) {
1803
+ for (let i = 0; i < obj.planSteps.length; i += 1) {
1804
+ const step = obj.planSteps[i];
1805
+ if (typeof step !== 'object' || step === null || Array.isArray(step)) {
1806
+ issues.push({ field: `${prefix}planSteps[${i}]`, reason: 'must be an object' });
1807
+ continue;
1808
+ }
1809
+ const s = step;
1810
+ check(() => requireEnum(`${prefix}planSteps[${i}].type`, s.type, PLAN_STEP_TYPES));
1811
+ check(() => requireString(`${prefix}planSteps[${i}].description`, s.description));
1812
+ }
1813
+ }
1814
+ return issues;
1815
+ }
1336
1816
  /**
1337
1817
  * `test create-batch --plans <plans.jsonl>` — M3.2 piece-5.
1338
1818
  *
@@ -1476,24 +1956,65 @@ export async function runCreateBatch(opts, deps = {}) {
1476
1956
  },
1477
1957
  });
1478
1958
  }
1479
- // Fix 5: enrich results with per-item dashboardUrl in JSON mode.
1959
+ // Fix 5: enrich results with per-item dashboardUrl.
1480
1960
  // projectId comes from specs[specIndex].projectId; testId from the result row.
1481
1961
  // Only emitted where both are known client-side — no extra network calls.
1482
1962
  // R1: suppress under --dry-run — test ids are fake canned values and a
1483
1963
  // live-looking URL would mislead the caller.
1964
+ // DEV-737: prefer a server-provided per-item dashboardUrl over the client
1965
+ // guess (`withDashboardUrl`/`resolveDashboardUrl`, defined near
1966
+ // `withRunDashboardUrl`); never fall back when the server explicitly
1967
+ // withheld one for a given item — that would print exactly the dead
1968
+ // V2-shaped link the server declined to emit.
1969
+ //
1970
+ // The per-item decision is captured into `testIdToDashboardState` — computed
1971
+ // ONCE here, regardless of `--output` mode — so the `--run` fan-out below
1972
+ // (`runBatchRun`) can reuse the SAME decision instead of recomputing a
1973
+ // client-side URL from testId→projectId, which would silently replace a
1974
+ // server-provided V3 link with the dead legacy V2 guess and lose
1975
+ // suppression state entirely. Computing it unconditionally (not gated on
1976
+ // `opts.output === 'json'`) also means the aggregate suppression advisory
1977
+ // below now correctly fires in text mode too — it previously only ever
1978
+ // fired in JSON mode because the per-item loop was skipped entirely in text
1979
+ // mode, silently under-warning a text-mode caller. That matches the
1980
+ // documented "advisory fires on stderr regardless of --output mode"
1981
+ // convention this repo already follows for the single-`test create` advisory.
1484
1982
  const apiUrlForDashboard = resolveApiUrl(opts, deps);
1983
+ let anyDashboardSuppressed = false;
1984
+ const testIdToDashboardState = new Map();
1985
+ if (!opts.dryRun) {
1986
+ for (const r of response.results) {
1987
+ if (r.status !== 'created' || r.testId === undefined)
1988
+ continue;
1989
+ const testId = r.testId;
1990
+ const spec = specs[r.specIndex];
1991
+ const projectId = spec?.projectId;
1992
+ const { entity, suppressed } = withDashboardUrl(r, () => projectId ? resolvePortalUrl(apiUrlForDashboard, projectId, testId) : undefined);
1993
+ if (suppressed)
1994
+ anyDashboardSuppressed = true;
1995
+ testIdToDashboardState.set(testId, {
1996
+ dashboardUrl: entity.dashboardUrl ?? undefined,
1997
+ suppressed,
1998
+ });
1999
+ }
2000
+ }
2001
+ if (anyDashboardSuppressed) {
2002
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2003
+ stderrFn('[advisory] no dashboard link is available for one or more created tests right now; ' +
2004
+ 'use `testsprite test get <test-id>` to look them up.');
2005
+ }
2006
+ // JSON-mode create output is enriched from the same map, so it stays
2007
+ // byte-identical to before this refactor.
1485
2008
  const enrichedResponse = !opts.dryRun && opts.output === 'json'
1486
2009
  ? {
1487
2010
  ...response,
1488
2011
  results: response.results.map(r => {
1489
2012
  if (r.status !== 'created' || r.testId === undefined)
1490
2013
  return r;
1491
- const spec = specs[r.specIndex];
1492
- const projectId = spec?.projectId;
1493
- if (!projectId)
2014
+ const state = testIdToDashboardState.get(r.testId);
2015
+ if (!state)
1494
2016
  return r;
1495
- const dashboardUrl = resolvePortalUrl(apiUrlForDashboard, projectId, r.testId);
1496
- return dashboardUrl !== undefined ? { ...r, dashboardUrl } : r;
2017
+ return { ...r, dashboardUrl: state.dashboardUrl };
1497
2018
  }),
1498
2019
  }
1499
2020
  : response;
@@ -1508,17 +2029,7 @@ export async function runCreateBatch(opts, deps = {}) {
1508
2029
  }
1509
2030
  // --run: fan out a trigger for each created test, then emit results.
1510
2031
  if (opts.run === true) {
1511
- // R3b: build testId → projectId map from the create results + specs so
1512
- // runBatchRun can enrich per-item run JSON with dashboardUrl.
1513
- const runTestIdToProjectId = new Map();
1514
- for (const r of response.results) {
1515
- if (r.status === 'created' && r.testId !== undefined) {
1516
- const projectId = specs[r.specIndex]?.projectId;
1517
- if (projectId)
1518
- runTestIdToProjectId.set(r.testId, projectId);
1519
- }
1520
- }
1521
- await runBatchRun(opts, response, client, out, deps, opts.dryRun ? undefined : runTestIdToProjectId, opts.dryRun ? undefined : apiUrlForDashboard);
2032
+ await runBatchRun(opts, response, client, out, deps, opts.dryRun ? undefined : testIdToDashboardState);
1522
2033
  // runBatchRun handles its own exit-code logic via CLIError.
1523
2034
  // Return the create response to satisfy the return type; callers that
1524
2035
  // inspect the return value only do so when not using --run.
@@ -1547,12 +2058,17 @@ export async function runCreateBatch(opts, deps = {}) {
1547
2058
  * that code only when ALL runs share the same code; otherwise 1.
1548
2059
  */
1549
2060
  async function runBatchRun(opts, createResponse, client, out, deps,
1550
- /** R3b: testId → projectId mapping built from create results + specs, used to enrich
1551
- * run-path JSON items with dashboardUrl. Populated by the caller; absent (undefined)
1552
- * means no enrichment (e.g. dry-run or caller didn't supply it). */
1553
- testIdToProjectId,
1554
- /** R3b: resolved API URL for portal link resolution. */
1555
- apiUrlForDashboard) {
2061
+ /**
2062
+ * R3b: per-testId dashboard-link decision, ALREADY resolved at create time
2063
+ * via `withDashboardUrl`/`resolveDashboardUrl` (the shared three-state
2064
+ * precedence helper — see its doc). Populated by the caller; absent
2065
+ * (undefined) means no enrichment (e.g. dry-run). Reusing this decision
2066
+ * — rather than recomputing a client-side URL from testId→projectId here
2067
+ * — is the fix: a fresh `resolvePortalUrl` call at this point would
2068
+ * silently replace a server-provided V3 link with the dead legacy V2
2069
+ * guess, and would have no way to know a link was explicitly suppressed.
2070
+ */
2071
+ testIdToDashboardState) {
1556
2072
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1557
2073
  const timeoutSeconds = opts.timeoutSeconds ?? DEFAULT_RUN_TIMEOUT_SECONDS;
1558
2074
  const concurrencyLimit = opts.maxConcurrency ?? DEFAULT_BATCH_RUN_CONCURRENCY;
@@ -1564,6 +2080,20 @@ apiUrlForDashboard) {
1564
2080
  // All specs failed at create time — already threw above; unreachable.
1565
2081
  return;
1566
2082
  }
2083
+ // Finding 2 (dogfood 2026-08-09): this fan-out calls `triggerRunWithMeta`
2084
+ // directly (below), bypassing `runTestRun` entirely — so `runTestRun`'s own
2085
+ // `--target-url` V3 advisory (`emitTargetUrlV3AdvisoryIfNeeded`) never fired
2086
+ // here, even though every triggered run in the batch ignores `--target-url`
2087
+ // exactly like a single V3-routed `test run` does. Reuses the same helper
2088
+ // and advisory text (no duplicated probe logic or copy) and fires exactly
2089
+ // ONCE for the whole batch, before the fan-out — not per item. Mirrors
2090
+ // `runTestRun`'s own gating (only pay the extra `/me` round trip when
2091
+ // `--target-url` was actually supplied) and its "fires under --dry-run too"
2092
+ // behavior (the dry-run client's canned `/me` sample demonstrates the same
2093
+ // advisory at zero real-network cost).
2094
+ if (opts.targetUrl !== undefined) {
2095
+ await emitTargetUrlV3AdvisoryIfNeeded(client, stderrFn);
2096
+ }
1567
2097
  // Dry-run: print a descriptor envelope and return without real triggers.
1568
2098
  if (opts.dryRun) {
1569
2099
  const dryRunResults = testIds.map(testId => ({
@@ -1729,14 +2259,9 @@ apiUrlForDashboard) {
1729
2259
  // MAJOR 3: use retryAfterMs from the thrown ApiError when available
1730
2260
  // (set by HttpClient from the HTTP Retry-After header, clamped to
1731
2261
  // [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
- }
2262
+ // Extracted to `resolveRateLimitRetryMs` so the multi-id `test wait`
2263
+ // poll fan-out applies the identical precedence.
2264
+ const retryAfterMs = resolveRateLimitRetryMs(err);
1740
2265
  // MAJOR 2: clamp to remaining deadline so we don't overshoot the
1741
2266
  // --wait budget.
1742
2267
  const clampedRetryMs = Math.min(retryAfterMs, remainingMs());
@@ -1924,7 +2449,9 @@ apiUrlForDashboard) {
1924
2449
  testId: finalRun.testId,
1925
2450
  runId: finalRun.runId,
1926
2451
  status: finalRun.status,
1927
- codeVersion: finalRun.codeVersion,
2452
+ // Runs without a stored code body report `codeVersion: null`; the batch
2453
+ // envelope uses '' for "unknown", as the trigger-error paths above do.
2454
+ codeVersion: finalRun.codeVersion ?? '',
1928
2455
  videoUrl: finalRun.videoUrl,
1929
2456
  failureKind: finalRun.failureKind,
1930
2457
  };
@@ -1988,20 +2515,35 @@ apiUrlForDashboard) {
1988
2515
  batchRunResults.sort((a, b) => testIds.indexOf(a.testId) - testIds.indexOf(b.testId));
1989
2516
  // Emit output.
1990
2517
  if (opts.output === 'json') {
1991
- // R3b: enrich per-item run results with dashboardUrl when both testId and
1992
- // projectId are known (from the testIdToProjectId map built by the caller).
1993
- // Additive-optional: items where projectId is unknown are left unchanged.
1994
- const enrichedResults = !opts.dryRun && testIdToProjectId !== undefined && apiUrlForDashboard !== undefined
2518
+ // R3b: enrich per-item run results with the dashboard state ALREADY
2519
+ // resolved at create time (`testIdToDashboardState`, built by the
2520
+ // caller). Never recompute a client-side URL here — that would silently
2521
+ // replace a server-provided V3 link with the dead legacy V2 guess, and
2522
+ // would have no way to represent "the server explicitly suppressed
2523
+ // this". A suppressed item (dashboardUrl undefined, suppressed: true)
2524
+ // is left with no key at all, same as the create-time convention.
2525
+ const enrichedResults = !opts.dryRun && testIdToDashboardState !== undefined
1995
2526
  ? batchRunResults.map(r => {
1996
- const projectId = testIdToProjectId.get(r.testId);
1997
- if (!projectId || !r.testId)
2527
+ const state = testIdToDashboardState.get(r.testId);
2528
+ if (!state || state.dashboardUrl === undefined)
1998
2529
  return r;
1999
- const dashboardUrl = resolvePortalUrl(apiUrlForDashboard, projectId, r.testId);
2000
- return dashboardUrl !== undefined ? { ...r, dashboardUrl } : r;
2530
+ return { ...r, dashboardUrl: state.dashboardUrl };
2001
2531
  })
2002
2532
  : batchRunResults;
2003
2533
  out.print({ results: enrichedResults });
2004
2534
  }
2535
+ else if (!opts.wait) {
2536
+ // Text mode, no --wait: statuses are non-terminal by design ('queued'),
2537
+ // so a pass/fail summary would misread a successful dispatch as
2538
+ // "0/N passed". Report what actually happened: triggers.
2539
+ const total = batchRunResults.length;
2540
+ const erroredCount = batchRunResults.filter(r => r.error !== undefined).length;
2541
+ const parts = [`${total - erroredCount}/${total} triggered`];
2542
+ if (erroredCount > 0) {
2543
+ parts.push(`${erroredCount} trigger error${erroredCount !== 1 ? 's' : ''}`);
2544
+ }
2545
+ stderrFn(`batch-run summary: ${parts.join(', ')}`);
2546
+ }
2005
2547
  else {
2006
2548
  // Text mode: print summary line.
2007
2549
  const passed = batchRunResults.filter(r => r.status === 'passed').length;
@@ -2021,35 +2563,40 @@ apiUrlForDashboard) {
2021
2563
  parts.push(`${errored} error/timeout`);
2022
2564
  stderrFn(`batch-run summary: ${parts.join(', ')}`);
2023
2565
  }
2024
- // Determine exit code.
2025
- const allPassed = batchRunResults.every(r => r.status === 'passed');
2026
- if (allPassed)
2566
+ // Determine exit code. With --wait, success means every run reached the
2567
+ // terminal status 'passed'. Without --wait, statuses are non-terminal by
2568
+ // design ('queued' per CliBatchRunResult), so success means every trigger
2569
+ // dispatched without error — mirroring single `test run` (no --wait),
2570
+ // which exits 0 on a successful queued dispatch.
2571
+ const failing = opts.wait
2572
+ ? batchRunResults.filter(r => r.status !== 'passed')
2573
+ : batchRunResults.filter(r => r.error !== undefined);
2574
+ if (failing.length === 0)
2027
2575
  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');
2576
+ // Check for a uniform non-pass exit code across all failing results.
2577
+ const errorExitCodes = failing.filter(r => r.error !== undefined).map(r => r.error.exitCode);
2033
2578
  // 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(...)`
2579
+ // outcomes" (exit 1), not "all timed out". `failing.every(...)` alone
2035
2580
  // would incorrectly fire exit 7 when 1 of N passed and the rest timed out.
2036
- const allTimeout = batchRunResults.length > 0 &&
2581
+ const allTimeout = failing.length === batchRunResults.length &&
2037
2582
  batchRunResults.every(r => r.status === 'timeout' || r.error?.exitCode === 7);
2038
2583
  if (allTimeout) {
2039
2584
  throw new CLIError(`All ${batchRunResults.length} batch run(s) timed out after ${timeoutSeconds}s.`, 7);
2040
2585
  }
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) {
2586
+ // If all failing results share the same specific exit code (6 or 11), use it.
2587
+ if (errorExitCodes.length > 0 && errorExitCodes.length === failing.length) {
2043
2588
  const uniformCode = errorExitCodes[0];
2044
2589
  if (uniformCode !== undefined &&
2045
2590
  errorExitCodes.every(c => c === uniformCode) &&
2046
2591
  uniformCode !== 1 &&
2047
2592
  uniformCode !== 7) {
2048
- throw new CLIError(`Batch run finished: ${nonPassedStatuses.length} run(s) failed with exit code ${uniformCode}.`, uniformCode);
2593
+ throw new CLIError(`Batch run finished: ${failing.length} run(s) failed with exit code ${uniformCode}.`, uniformCode);
2049
2594
  }
2050
2595
  }
2051
2596
  // 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);
2597
+ throw new CLIError(opts.wait
2598
+ ? `Batch run finished: ${failing.length} of ${batchRunResults.length} run(s) did not pass.`
2599
+ : `Batch run trigger finished: ${failing.length} of ${batchRunResults.length} trigger(s) failed.`, 1);
2053
2600
  }
2054
2601
  /**
2055
2602
  * Read + parse a JSONL plans file. Per-line validation; spec-level
@@ -2597,13 +3144,33 @@ function mapRunStepToCliTestStep(step, run) {
2597
3144
  stepType: step.type,
2598
3145
  };
2599
3146
  }
3147
+ /**
3148
+ * The `test diff` exit-code contract, applied identically to a real
3149
+ * two-run comparison and the `--dry-run` canned sample: the
3150
+ * result is always printed first (`out.print` already ran by the time this
3151
+ * is called), then a `verdictChanged` diff throws so the process exits 1.
3152
+ * Before this helper existed, `--dry-run`'s early `return sample` bypassed
3153
+ * the check entirely — the canned sample has `verdictChanged: true`, so
3154
+ * `test diff --dry-run` always exited 0 even though the documented contract
3155
+ * ("Exit 0 when verdicts match, 1 when they differ") makes no dry-run
3156
+ * exception. That made the command useless for its stated CI-gate
3157
+ * pre-verification purpose.
3158
+ */
3159
+ function enforceDiffExitContract(diff) {
3160
+ if (diff.verdictChanged) {
3161
+ throw new CLIError(`verdicts differ: ${diff.runA.runId}=${diff.runA.status} vs ${diff.runB.runId}=${diff.runB.status}`, 1);
3162
+ }
3163
+ }
2600
3164
  /**
2601
3165
  * `test diff <runA> <runB>` (issue #124): isolate what regressed between two
2602
3166
  * runs, the first question when CI goes red ("what changed since the last
2603
3167
  * green run?"). Pure client-side composition of the existing per-run read
2604
3168
  * (`GET /runs/{id}?includeSteps=true`); the endpoint accepts any two run-ids,
2605
3169
  * 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.
3170
+ * match, exit 1 when they differ, so the command is CI-scriptable —
3171
+ * `--dry-run` honors the same contract: the canned sample has a
3172
+ * changed verdict, so `test diff --dry-run` (with no overrides) exits 1,
3173
+ * same as a real regressed pair would.
2607
3174
  */
2608
3175
  export async function runDiff(opts, deps = {}) {
2609
3176
  const out = makeOutput(opts.output, deps);
@@ -2635,6 +3202,7 @@ export async function runDiff(opts, deps = {}) {
2635
3202
  changedSteps: [{ stepIndex: 2, statusA: 'passed', statusB: 'failed' }],
2636
3203
  };
2637
3204
  out.print(sample, () => renderRunDiffText(sample));
3205
+ enforceDiffExitContract(sample);
2638
3206
  return sample;
2639
3207
  }
2640
3208
  const client = makeClient(opts, deps);
@@ -2693,10 +3261,8 @@ export async function runDiff(opts, deps = {}) {
2693
3261
  changedSteps,
2694
3262
  };
2695
3263
  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
- }
3264
+ // Result already printed; the typed exit makes `test diff` a CI gate.
3265
+ enforceDiffExitContract(diff);
2700
3266
  return diff;
2701
3267
  }
2702
3268
  function renderRunDiffText(diff) {
@@ -2724,6 +3290,25 @@ function renderRunDiffText(diff) {
2724
3290
  }
2725
3291
  return lines.join('\n');
2726
3292
  }
3293
+ /**
3294
+ * Turn a thrown validation error into a lint issue's `field`+`reason` pair.
3295
+ * Shared by `runLint`'s file-level failures (bad path, oversize, invalid JSON
3296
+ * syntax — always a single issue, there's nothing left to validate) and the
3297
+ * collect-all `collectPlanIssues` / `collectPlanStepsIssues` helpers above
3298
+ * (one call per field, so every problem in a file is captured, not just the
3299
+ * first). Preserves the typed envelope's `details.field` / `details.reason`
3300
+ * verbatim (e.g. `planSteps[2].type`) so a caller sees the exact same pointer
3301
+ * whether the error surfaced via lint or via `create`.
3302
+ */
3303
+ function toLintIssue(err) {
3304
+ if (err instanceof ApiError) {
3305
+ return {
3306
+ field: String(err.getDetail('field') ?? '(file)'),
3307
+ reason: String(err.getDetail('reason') ?? err.nextAction ?? err.message),
3308
+ };
3309
+ }
3310
+ return { field: '(file)', reason: err instanceof Error ? err.message : String(err) };
3311
+ }
2727
3312
  /**
2728
3313
  * `test lint` (issue #98): validate plan/steps files fully OFFLINE with the
2729
3314
  * SAME validators the create paths run, but collecting EVERY problem instead
@@ -2732,6 +3317,15 @@ function renderRunDiffText(diff) {
2732
3317
  * so authoring a 12-plan directory meant one error per paid round-trip. Zero
2733
3318
  * network, zero credentials: exit 0 when everything is valid, 5 otherwise, so
2734
3319
  * it drops into a pre-commit hook or CI step before `create-batch`.
3320
+ *
3321
+ * The collection granularity used to be per-FILE, not per-PROBLEM — a single
3322
+ * plan with 6 independent field errors reported one at a time across 6
3323
+ * fix-and-rerun cycles, because each file was validated through the
3324
+ * throw-on-first `assertPlanShape`/`assertPlanStepsShape`. Every branch below
3325
+ * now separates "parse the file" (still a single fatal issue on I/O/JSON
3326
+ * failure — there's nothing left to validate) from "check the parsed shape"
3327
+ * (routed through `collectPlanIssues` / `collectPlanStepsIssues`, which
3328
+ * report every failing field in one pass).
2735
3329
  */
2736
3330
  export async function runLint(opts, deps = {}) {
2737
3331
  const out = makeOutput(opts.output, deps);
@@ -2741,38 +3335,39 @@ export async function runLint(opts, deps = {}) {
2741
3335
  }
2742
3336
  const issues = [];
2743
3337
  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) => {
3338
+ const lintPlanFile = (file, path, specIndex) => {
2748
3339
  checked += 1;
3340
+ let parsed;
2749
3341
  try {
2750
- validate();
3342
+ parsed = parsePlanFile(path);
2751
3343
  }
2752
3344
  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
- }
3345
+ issues.push({ file, ...toLintIssue(err) });
3346
+ return;
3347
+ }
3348
+ for (const issue of collectPlanIssues(parsed, { specIndex })) {
3349
+ issues.push({ file, ...issue });
3350
+ }
3351
+ };
3352
+ const lintStepsFile = (file, path) => {
3353
+ checked += 1;
3354
+ let parsed;
3355
+ try {
3356
+ parsed = parsePlanStepsFile(path);
3357
+ }
3358
+ catch (err) {
3359
+ issues.push({ file, ...toLintIssue(err) });
3360
+ return;
3361
+ }
3362
+ for (const issue of collectPlanStepsIssues(parsed)) {
3363
+ issues.push({ file, ...issue });
2767
3364
  }
2768
3365
  };
2769
3366
  if (opts.planFrom !== undefined) {
2770
- const planFrom = opts.planFrom;
2771
- collect(planFrom, () => void readPlanFromGuarded(planFrom));
3367
+ lintPlanFile(opts.planFrom, opts.planFrom);
2772
3368
  }
2773
3369
  else if (opts.steps !== undefined) {
2774
- const steps = opts.steps;
2775
- collect(steps, () => void readPlanStepsFileGuarded(steps));
3370
+ lintStepsFile(opts.steps, opts.steps);
2776
3371
  }
2777
3372
  else if (opts.planFromDir !== undefined) {
2778
3373
  const dir = resolveAbsolute(opts.planFromDir);
@@ -2789,12 +3384,13 @@ export async function runLint(opts, deps = {}) {
2789
3384
  throw localValidationError('plan-from-dir', 'contains no *.json plan files');
2790
3385
  }
2791
3386
  for (const entry of entries) {
2792
- collect(entry, () => void readPlanFromGuarded(join(dir, entry)));
3387
+ lintPlanFile(entry, join(dir, entry));
2793
3388
  }
2794
3389
  }
2795
3390
  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).
3391
+ // JSONL: validate PER LINE, and every problem WITHIN each line (the
3392
+ // create path's reader stays throw-on-first; this is the collecting
3393
+ // counterpart, both per-line and per-field).
2798
3394
  const absolute = resolveAbsolute(opts.plans);
2799
3395
  let content;
2800
3396
  try {
@@ -2813,16 +3409,20 @@ export async function runLint(opts, deps = {}) {
2813
3409
  if (numberedLines.length === 0)
2814
3410
  throw localValidationError('plans', 'contains no plan lines');
2815
3411
  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
- });
3412
+ const file = `${opts.plans}:${lineNo}`;
3413
+ checked += 1;
3414
+ let parsed;
3415
+ try {
3416
+ parsed = JSON.parse(line);
3417
+ }
3418
+ catch {
3419
+ const err = localValidationError('plans', `line ${lineNo} is not valid JSON`, undefined, 'field');
3420
+ issues.push({ file, ...toLintIssue(err) });
3421
+ continue;
3422
+ }
3423
+ for (const issue of collectPlanIssues(parsed, { specIndex: lineNo - 1 })) {
3424
+ issues.push({ file, ...issue });
3425
+ }
2826
3426
  }
2827
3427
  }
2828
3428
  const filesWithIssues = new Set(issues.map(issue => issue.file)).size;
@@ -2917,6 +3517,70 @@ export async function runScaffold(opts, deps = {}) {
2917
3517
  out.print(payload, () => body.trimEnd());
2918
3518
  return payload;
2919
3519
  }
3520
+ /**
3521
+ * `test create --plan-template` — prints the canonical minimal
3522
+ * valid plan file (`PLAN_TEMPLATE_WITH_SCHEMA` / `PLAN_TEMPLATE_TEXT`,
3523
+ * defined above near `CliPlanInput`) to stdout and exits — before any of
3524
+ * `test create`'s other flag handling runs. Pure-local: no network, no
3525
+ * credentials, no filesystem I/O.
3526
+ *
3527
+ * Deliberately simpler than `test scaffold --type frontend` (which
3528
+ * substitutes a live `TESTSPRITE_PROJECT_ID` when set, and supports
3529
+ * `--out`): `--plan-template`'s job is a single deterministic ground-truth
3530
+ * document that is BYTE-IDENTICAL every invocation, because it doubles as
3531
+ * the literal example embedded in `test create --help` and the
3532
+ * fixture asserted against `schemas/plan.schema.json` in tests.
3533
+ */
3534
+ export function runPlanTemplate(opts, deps = {}) {
3535
+ const out = makeOutput(opts.output, deps);
3536
+ out.print(PLAN_TEMPLATE_WITH_SCHEMA, () => PLAN_TEMPLATE_TEXT);
3537
+ return PLAN_TEMPLATE_WITH_SCHEMA;
3538
+ }
3539
+ /**
3540
+ * `test open <test-id>` (issue #121): jump from the terminal to the test's
3541
+ * dashboard page. The CLI already computes this deep-link and prints it as
3542
+ * text on other commands; this closes the last inch (the `gh browse` /
3543
+ * `cypress open` hop). The URL is ALWAYS printed to stdout (so `--no-browser`
3544
+ * and headless use still compose), then the OS browser is spawned unless
3545
+ * --no-browser. An endpoint with no known portal mapping is a hard error
3546
+ * rather than a silent no-op.
3547
+ */
3548
+ export async function runOpen(opts, deps = {}, opener = openInBrowser) {
3549
+ const out = makeOutput(opts.output, deps);
3550
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
3551
+ if (opts.dryRun) {
3552
+ emitDryRunBanner(stderrFn);
3553
+ // Derive the sample through the SAME resolver as the live path (against
3554
+ // the canonical prod endpoint and the dry-run project id) so the two can
3555
+ // never drift; the ?? arm is unreachable for the prod mapping but keeps
3556
+ // the type total.
3557
+ const sample = {
3558
+ dashboardUrl: resolvePortalUrl('https://api.testsprite.com', 'p_dryrun_2026', opts.testId) ??
3559
+ `https://www.testsprite.com/dashboard/tests/p_dryrun_2026/test/${encodeURIComponent(opts.testId)}`,
3560
+ };
3561
+ out.print(sample, data => data.dashboardUrl);
3562
+ return sample;
3563
+ }
3564
+ const client = makeClient(opts, deps);
3565
+ // The deep-link needs the projectId; the test record is the source of truth.
3566
+ const test = await client.get(`/tests/${encodeURIComponent(opts.testId)}`);
3567
+ const dashboardUrl = resolvePortalUrl(resolveApiUrl(opts, deps), test.projectId, opts.testId);
3568
+ if (dashboardUrl === undefined) {
3569
+ throw new CLIError(`no dashboard mapping for this API endpoint; set TESTSPRITE_PORTAL_URL to your Portal origin`, 1);
3570
+ }
3571
+ out.print({ dashboardUrl }, () => dashboardUrl);
3572
+ if (!opts.noBrowser) {
3573
+ try {
3574
+ opener(dashboardUrl);
3575
+ }
3576
+ catch {
3577
+ // The URL is already on stdout; a missing opener (containers, minimal
3578
+ // hosts) downgrades to "open it yourself" instead of a hard failure.
3579
+ stderrFn('could not launch a browser; open the URL above manually (or use --no-browser)');
3580
+ }
3581
+ }
3582
+ return { dashboardUrl };
3583
+ }
2920
3584
  export async function runSteps(opts, deps = {}) {
2921
3585
  const out = makeOutput(opts.output, deps);
2922
3586
  const client = makeClient(opts, deps);
@@ -3070,6 +3734,9 @@ export async function runResultHistory(opts, deps = {}) {
3070
3734
  throw localValidationError('page-size', 'must be between 1 and 100');
3071
3735
  }
3072
3736
  }
3737
+ if (opts.output === 'text') {
3738
+ resolveTextColumns(opts.columns, RUN_HISTORY_TABLE_COLUMNS);
3739
+ }
3073
3740
  const client = makeClient(opts, deps);
3074
3741
  const pageSize = opts.pageSize ?? 20;
3075
3742
  const sinceIso = opts.since !== undefined ? parseDuration(opts.since) : undefined;
@@ -3079,9 +3746,14 @@ export async function runResultHistory(opts, deps = {}) {
3079
3746
  source: opts.source,
3080
3747
  since: sinceIso,
3081
3748
  });
3082
- if (opts.output === 'json') {
3083
- out.print({ runs: resp.runs, nextCursor: resp.nextCursor }, data => JSON.stringify(data));
3084
- return resp;
3749
+ // Client-side rerun filter (--rerun / --no-rerun). isRerun is on every row;
3750
+ // the backend has no rerun filter. Undefined → no filter. Like --source, a
3751
+ // filtered page can be short/empty while more history exists — the empty-page
3752
+ // and short-page hints below cover that.
3753
+ const runs = opts.rerun === undefined ? resp.runs : resp.runs.filter(r => r.isRerun === opts.rerun);
3754
+ if (opts.output !== 'text') {
3755
+ out.print({ runs, nextCursor: resp.nextCursor }, data => JSON.stringify(data));
3756
+ return { ...resp, runs };
3085
3757
  }
3086
3758
  // Text mode rendering
3087
3759
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
@@ -3090,7 +3762,7 @@ export async function runResultHistory(opts, deps = {}) {
3090
3762
  // backend filters AFTER limiting rows (limit-before-filter). Matching runs
3091
3763
  // may exist on later pages — surface the cursor instead of reporting
3092
3764
  // "no history".
3093
- if (resp.runs.length === 0) {
3765
+ if (runs.length === 0) {
3094
3766
  if (resp.nextCursor !== null) {
3095
3767
  // Filtered-empty page, but more pages exist: prompt user to paginate.
3096
3768
  const msg = `No matching runs on this page (filters skipped all entries), but more history exists.\n` +
@@ -3111,7 +3783,7 @@ export async function runResultHistory(opts, deps = {}) {
3111
3783
  return resp;
3112
3784
  }
3113
3785
  const lines = [];
3114
- lines.push(renderRunHistoryTable(resp.runs));
3786
+ lines.push(renderRunHistoryTable(runs, { columns: opts.columns, noHeader: opts.noHeader }));
3115
3787
  // Footer: pointer to per-run detail commands.
3116
3788
  lines.push('');
3117
3789
  lines.push('Per-run detail: testsprite test wait <run-id>');
@@ -3124,19 +3796,24 @@ export async function runResultHistory(opts, deps = {}) {
3124
3796
  out.print(lines.join('\n'), d => d);
3125
3797
  // Short-filtered-page hint: non-null nextCursor even though this page was
3126
3798
  // shorter than requested — "none in THIS window" does not mean end-of-history.
3127
- if (resp.nextCursor !== null && resp.runs.length < pageSize) {
3799
+ if (resp.nextCursor !== null && runs.length < pageSize) {
3128
3800
  stderr(`[hint] Fewer than ${pageSize} rows returned but more may exist — ` +
3129
- `source filter skipped some entries. Pass --cursor ${resp.nextCursor} to continue.`);
3801
+ `a source/rerun filter skipped some entries. Pass --cursor ${resp.nextCursor} to continue.`);
3130
3802
  }
3131
- return resp;
3803
+ return { ...resp, runs };
3132
3804
  }
3133
- const RUN_HISTORY_TABLE_COL_WIDTHS = {
3134
- runId: 36,
3135
- status: 10,
3136
- source: 18,
3137
- rerun: 6,
3138
- when: 25,
3139
- };
3805
+ const RUN_HISTORY_TABLE_COLUMNS = [
3806
+ { header: 'RUN ID', width: 36, render: run => run.runId },
3807
+ { header: 'STATUS', width: 10, render: run => run.status },
3808
+ { header: 'SOURCE', width: 18, render: run => run.source },
3809
+ { header: 'RERUN?', width: 6, render: run => (run.isRerun ? 'yes' : 'no') },
3810
+ { header: 'WHEN', width: 25, render: run => run.createdAt },
3811
+ {
3812
+ header: 'DURATION',
3813
+ width: 0,
3814
+ render: run => formatDurationMs(run.startedAt ?? run.createdAt, run.finishedAt),
3815
+ },
3816
+ ];
3140
3817
  /**
3141
3818
  * Max width of the `test steps` DESCRIPTION column in text mode. Long /
3142
3819
  * multi-line step descriptions are collapsed to one line and truncated to
@@ -3168,56 +3845,29 @@ const HISTORY_TARGET_URL_MAX = 80;
3168
3845
  * run row (truncated to `HISTORY_TARGET_URL_MAX` chars). The table columns
3169
3846
  * are left intact to avoid width blow-out on terminals.
3170
3847
  */
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).
3848
+ function renderRunHistoryTable(runs, options = {}) {
3849
+ const selectedColumns = resolveTextColumns(options.columns, RUN_HISTORY_TABLE_COLUMNS);
3850
+ const widths = measureTextColumns(runs, selectedColumns);
3851
+ const customColumns = options.columns !== undefined && options.columns.trim() !== '';
3852
+ const includeDetailLines = !customColumns;
3853
+ const header = formatTextTableRow(selectedColumns.map(column => column.header), widths);
3854
+ const rows = runs.flatMap(run => {
3855
+ const mainRow = formatTextTableRow(selectedColumns.map(column => column.render(run)), widths);
3203
3856
  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;
3857
+ if (includeDetailLines && run.targetUrl && run.targetUrlSource !== 'unresolved') {
3858
+ const url = run.targetUrl.length > HISTORY_TARGET_URL_MAX
3859
+ ? `${run.targetUrl.slice(0, HISTORY_TARGET_URL_MAX - 1)}…`
3860
+ : run.targetUrl;
3208
3861
  lines.push(` targetUrl: ${url}`);
3209
3862
  }
3210
- else if (r.targetUrlSource === 'unresolved') {
3863
+ else if (includeDetailLines && run.targetUrlSource === 'unresolved') {
3211
3864
  lines.push(` targetUrl: —`);
3212
3865
  }
3213
3866
  return lines;
3214
3867
  });
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);
3868
+ if (options.noHeader === true)
3869
+ return rows.join('\n');
3870
+ return [header, '-'.repeat(header.length), ...rows].join('\n');
3221
3871
  }
3222
3872
  function formatDurationMs(startedAt, finishedAt) {
3223
3873
  if (!startedAt || !finishedAt)
@@ -3402,8 +4052,11 @@ function backendResultToRunResponse(result, run) {
3402
4052
  retryAfterSeconds: undefined,
3403
4053
  startedAt: result.startedAt ?? run.startedAt,
3404
4054
  finishedAt: result.finishedAt ?? run.finishedAt,
3405
- codeVersion: run.codeVersion || (result.codeVersion ?? ''),
3406
- targetUrl: run.targetUrl || (result.targetUrl ?? ''),
4055
+ // Neither side having a value stays null (not ''), so the text renderer
4056
+ // omits the line instead of printing a label with nothing after it. A
4057
+ // backend run legitimately has no target URL at all.
4058
+ codeVersion: run.codeVersion || result.codeVersion || null,
4059
+ targetUrl: run.targetUrl || result.targetUrl || null,
3407
4060
  // createdFrom / projectId / userId / runId / testId / source / createdAt
3408
4061
  // inherited from the polled run row via the spread above.
3409
4062
  failedStepIndex: result.failedStepIndex,
@@ -3521,17 +4174,98 @@ function printRunOrChain(out, payload, createContext, textRenderer) {
3521
4174
  });
3522
4175
  }
3523
4176
  /**
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).
4177
+ * Server-first precedence for a `dashboardUrl` field on any wire response
4178
+ * that can carry one (`RunResponse`, `CliCreateTestResponse`,
4179
+ * `CliBatchSpecResult`). Single source of truth for the rule so the create
4180
+ * paths (DEV-737) and the run-completion path (`withRunDashboardUrl` below)
4181
+ * can't drift apart.
4182
+ *
4183
+ * This is a PINNED three-state wire contract — a prior revision let a
4184
+ * present-but-falsy value and a truly-absent key both mean "no server
4185
+ * opinion," which was ambiguous with the real backend behavior of omitting
4186
+ * the key on a deliberate "no correct link" response, printing the dead
4187
+ * legacy link this feature exists to remove. The backend now always
4188
+ * includes the key (typed `string | null`, never omitted when it has an
4189
+ * opinion), so the three states below are mutually exclusive on the wire:
4190
+ *
4191
+ * - **Present + truthy** → the server built a correct link (it alone knows
4192
+ * which store answered and this environment's portal origin); use it
4193
+ * verbatim.
4194
+ * - **Present + falsy (`null`/`''`)** → the server explicitly has no
4195
+ * correct link — e.g. a V3-native entity with no DynamoDB mirror row for
4196
+ * the client's V2-shaped `/dashboard/tests/…` guess to land on. NEVER
4197
+ * fall back here: a client-side guess would be exactly the dead link the
4198
+ * server declined to emit. `suppressed: true` tells the caller a link
4199
+ * was actively withheld (vs. simply never computed) so it can point the
4200
+ * user elsewhere instead of printing nothing unexplained.
4201
+ * - **Absent** → an older backend that predates this field entirely. Such a
4202
+ * backend cannot have produced a V3-native/unmirrored entity either —
4203
+ * that capability and this field ship together — so the client fallback
4204
+ * is safe and reproduces exactly today's behavior.
4205
+ */
4206
+ function resolveDashboardUrl(wire, computeFallback) {
4207
+ if ('dashboardUrl' in wire) {
4208
+ return wire.dashboardUrl
4209
+ ? { dashboardUrl: wire.dashboardUrl, suppressed: false }
4210
+ : { dashboardUrl: undefined, suppressed: true };
4211
+ }
4212
+ return { dashboardUrl: computeFallback(), suppressed: false };
4213
+ }
4214
+ /**
4215
+ * Applies {@link resolveDashboardUrl} to a whole entity, returning a
4216
+ * NORMALIZED copy: a server-suppressed (`null`/`''`) value is rewritten to
4217
+ * `undefined` so `JSON.stringify` omits the key entirely instead of
4218
+ * serializing a literal `"dashboardUrl": null` — the same normalization
4219
+ * `withRunDashboardUrl` already did inline for `RunResponse`, generalized
4220
+ * here so the create paths (DEV-737) can share it byte-for-byte.
4221
+ */
4222
+ function withDashboardUrl(wire, computeFallback) {
4223
+ const { dashboardUrl, suppressed } = resolveDashboardUrl(wire, computeFallback);
4224
+ if ('dashboardUrl' in wire)
4225
+ return { entity: { ...wire, dashboardUrl }, suppressed };
4226
+ return { entity: dashboardUrl !== undefined ? { ...wire, dashboardUrl } : wire, suppressed };
4227
+ }
4228
+ /**
4229
+ * DEV-737: advisory printed when the server explicitly withheld a dashboard
4230
+ * link (`resolveDashboardUrl`'s `suppressed: true`) rather than silently
4231
+ * omitting the field with no explanation. Fires on stderr regardless of
4232
+ * `--output` mode — the field's absence from a JSON envelope carries no
4233
+ * reason on its own, and `--output json` is routinely unattended, so the
4234
+ * hint is worth the line there too (same reasoning as the `project create
4235
+ * --type backend` no-URL advisory in `project.ts`). Printing nothing beats
4236
+ * printing a dead link, but telling the caller where to look instead beats
4237
+ * printing nothing unexplained.
4238
+ */
4239
+ function emitDashboardLinkSuppressedAdvisory(testId, stderrFn) {
4240
+ stderrFn(`[advisory] no dashboard link is available for this test right now; use ` +
4241
+ `\`testsprite test get ${testId}\` to look it up.`);
4242
+ }
4243
+ /**
4244
+ * Attach the Portal deep link to a terminal RunResponse.
4245
+ *
4246
+ * **A server-provided `dashboardUrl` always wins.** The backend knows two
4247
+ * things this process cannot:
4248
+ *
4249
+ * - **Which store answered.** For a run served from V3 Postgres the
4250
+ * `/dashboard/tests/…` route we would template reads DynamoDB only, and a
4251
+ * CLI-created project under the V3-native write path has no DynamoDB row at
4252
+ * all — so our link is not merely org-less, it cannot render. The server
4253
+ * sends the V3 test-case page instead, scoped to the workspace that owns the
4254
+ * run.
4255
+ * - **The portal origin for this environment.** `resolvePortalUrl` maps only
4256
+ * the prod host, so against any other endpoint it returns undefined and we
4257
+ * print nothing. The server reads its own `PORTAL_URL`.
4258
+ *
4259
+ * The client computation stays as the fallback so an older backend (no field)
4260
+ * behaves exactly as before, and so does a V2-served run whose server link the
4261
+ * backend chose not to emit.
3529
4262
  */
3530
4263
  function withRunDashboardUrl(run, apiUrl) {
3531
- if (!run.projectId || !run.testId)
3532
- return run;
3533
- const dashboardUrl = resolvePortalUrl(apiUrl, run.projectId, run.testId);
3534
- return dashboardUrl !== undefined ? { ...run, dashboardUrl } : run;
4264
+ return withDashboardUrl(run, () => {
4265
+ if (!run.projectId || !run.testId)
4266
+ return undefined;
4267
+ return resolvePortalUrl(apiUrl, run.projectId, run.testId);
4268
+ }).entity;
3535
4269
  }
3536
4270
  /**
3537
4271
  * Render a `RunResponse` to human-readable text. JSON mode callers get
@@ -3644,6 +4378,78 @@ function parseTimeoutFlag(raw, flagName) {
3644
4378
  }
3645
4379
  return n;
3646
4380
  }
4381
+ /**
4382
+ * Short deadline for the best-effort `v3Enabled` lookup behind the
4383
+ * `--target-url` advisory (DEV-749). Mirrors `DUP_NAME_ADVISORY_TIMEOUT_MS`
4384
+ * — a stalled `/me` must never meaningfully delay a run trigger.
4385
+ */
4386
+ const TARGET_URL_ADVISORY_TIMEOUT_MS = 5_000;
4387
+ /**
4388
+ * DEV-749 (client half): `--target-url` is silently dropped on the V3
4389
+ * execution path — the backend validates it (SSRF guard, defence in depth)
4390
+ * and then discards it, because V3 resolves the run's environment from
4391
+ * `test_environment` at execution time; there is no injection point for a
4392
+ * per-run override. This is a client-side advisory only — the real fix
4393
+ * (an actual per-run override on V3) needs a product decision and is out
4394
+ * of scope here.
4395
+ *
4396
+ * Gated on `v3Enabled`, the same authoritative per-user routing bit
4397
+ * `auth status`/`doctor` already render (`GET /me`, `src/lib/v3-advisory.ts`).
4398
+ * Best-effort: a single bounded lookup (mirrors `emitDupNameAdvisoryIfNeeded`'s
4399
+ * `AbortController` + 5 s deadline), swallows every error, and must never
4400
+ * block or fail the actual run trigger — a broken/slow `/me` degrades to
4401
+ * "no advisory printed", not a failed `test run`.
4402
+ */
4403
+ /**
4404
+ * `X-CLI-Command` tag for this probe's `GET /me` — same advisory-header
4405
+ * mechanism `runInit` uses (`toAuthDeps`'s `commandTag: 'init'` in
4406
+ * `commands/init.ts`, sent via `AuthDeps.commandTag` in `auth.ts`), reused
4407
+ * directly here rather than invented fresh. The backend's CLI-audit
4408
+ * allowlist (`KNOWN_CLI_COMMANDS` + `resolveCliEvent`'s `/me` branch) maps this
4409
+ * exact string to `null` — no PostHog event at all, not `cli.session_started`
4410
+ * and not `cli.initialized` (init's tag would be a MORE specific, and equally
4411
+ * wrong, misattribution of a probe that is neither a session start nor an
4412
+ * onboarding run).
4413
+ *
4414
+ * Forward-compatible by construction: an unlisted `X-CLI-Command` value is
4415
+ * dropped by the backend before event selection (see
4416
+ * `capturePostHogEvent`/`KNOWN_CLI_COMMANDS` in the interceptor above), so
4417
+ * against a backend that predates this allowlist entry the header is a no-op
4418
+ * and behavior is exactly what it was before this fix — the CLI can ship
4419
+ * this independently of backend deploy order in either direction.
4420
+ */
4421
+ const TARGET_URL_ADVISORY_CLI_COMMAND = 'run-target-url-probe';
4422
+ async function emitTargetUrlV3AdvisoryIfNeeded(client, stderrFn) {
4423
+ const ac = new AbortController();
4424
+ const timer = setTimeout(() => ac.abort(), TARGET_URL_ADVISORY_TIMEOUT_MS);
4425
+ try {
4426
+ const me = await client.get('/me', {
4427
+ signal: ac.signal,
4428
+ headers: { 'x-cli-command': TARGET_URL_ADVISORY_CLI_COMMAND },
4429
+ // Finding 1 (dogfood 2026-08-09): `HttpClient.sleepBeforeRetry` (src/lib/http.ts)
4430
+ // only observes the process-lifetime shutdown signal, never a per-request
4431
+ // `options.signal` — the abort controller above bounds the FETCH itself but
4432
+ // not a post-response retry sleep. A retryable 429 carrying a real
4433
+ // `Retry-After` (e.g. 60s, a live `inflight_cap` response) would put this
4434
+ // best-effort probe into a retry sleep this 5s deadline cannot interrupt,
4435
+ // stalling the real run trigger behind it. `retryOnRateLimit: false` makes
4436
+ // the HTTP layer throw on the first 429 instead of sleeping — the existing,
4437
+ // already-used-elsewhere knob (see the batch-run trigger site above) rather
4438
+ // than changing `sleepBeforeRetry` itself, which every other caller (e.g.
4439
+ // the polling path) relies on to keep sleeping through a caller signal.
4440
+ retryOnRateLimit: false,
4441
+ });
4442
+ if (me.v3Enabled === true) {
4443
+ emitTargetUrlV3Advisory(stderrFn);
4444
+ }
4445
+ }
4446
+ catch {
4447
+ // Swallow — this is best-effort; must not block or fail the run trigger.
4448
+ }
4449
+ finally {
4450
+ clearTimeout(timer);
4451
+ }
4452
+ }
3647
4453
  /**
3648
4454
  * `test run <test-id>` — M3.3 piece-3.
3649
4455
  *
@@ -3657,6 +4463,15 @@ export async function runTestRun(opts, deps = {}) {
3657
4463
  if (opts.targetUrl !== undefined) {
3658
4464
  assertNotLocal(opts.targetUrl);
3659
4465
  }
4466
+ // DEV-749: only spend the extra `/me` round trip when --target-url was
4467
+ // actually supplied — the common case (no override) pays nothing. Fires
4468
+ // in both the dry-run and real paths below (the dry-run `/me` sample sets
4469
+ // `v3Enabled: true`, so `--dry-run --target-url` demonstrates the same
4470
+ // advisory a real V3-routed caller would see, at zero real-network cost).
4471
+ if (opts.targetUrl !== undefined) {
4472
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4473
+ await emitTargetUrlV3AdvisoryIfNeeded(makeClient(opts, deps), stderrFn);
4474
+ }
3660
4475
  if (opts.dryRun) {
3661
4476
  const client = makeClient(opts, deps);
3662
4477
  const out = makeOutput(opts.output, deps);
@@ -3731,7 +4546,7 @@ export async function runTestRun(opts, deps = {}) {
3731
4546
  throw new ApiError({
3732
4547
  code: 'CONFLICT',
3733
4548
  message: `Conflict: another run for this test is in flight against a different ` +
3734
- `target URL (${inFlightRun.targetUrl}). Your --target-url ${opts.targetUrl} ` +
4549
+ `target URL (${inFlightRun.targetUrl ?? 'not reported'}). Your --target-url ${opts.targetUrl} ` +
3735
4550
  `cannot attach to that run. Wait for it to finish ` +
3736
4551
  `(\`testsprite test wait ${currentRunId}\`) or retry your trigger when ` +
3737
4552
  `the test is free.`,
@@ -3753,8 +4568,9 @@ export async function runTestRun(opts, deps = {}) {
3753
4568
  runId: currentRunId,
3754
4569
  status: 'queued',
3755
4570
  enqueuedAt: new Date().toISOString(),
3756
- codeVersion: inFlightRun.codeVersion,
3757
- targetUrl: inFlightRun.targetUrl,
4571
+ codeVersion: inFlightRun.codeVersion ?? '',
4572
+ // The check above proved the in-flight run targets exactly this URL.
4573
+ targetUrl: opts.targetUrl,
3758
4574
  };
3759
4575
  }
3760
4576
  else {
@@ -3912,6 +4728,38 @@ export async function runTestRun(opts, deps = {}) {
3912
4728
  `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
3913
4729
  throw err;
3914
4730
  }
4731
+ // RATE_LIMITED during polling — the backend's pre-auth rate limiter can
4732
+ // trip on a shared egress IP (CI runner, NAT) and 429 an otherwise-valid
4733
+ // key for its window; the HTTP layer already retried internally and gave
4734
+ // up. The run was already triggered (and billed) and keeps executing
4735
+ // server-side, so this must not be a silent, runId-less death: same
4736
+ // partial-envelope contract as the RequestTimeoutError branch above, and
4737
+ // the SAME thrown ApiError is rethrown unchanged so its native exit code
4738
+ // (11) is preserved — never reclassified to 7.
4739
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
4740
+ ticker.finalize(`Run ${triggerResponse.runId} — rate limited by the server`);
4741
+ const partial = {
4742
+ runId: triggerResponse.runId,
4743
+ status: 'running',
4744
+ enqueuedAt: triggerResponse.enqueuedAt,
4745
+ codeVersion: triggerResponse.codeVersion,
4746
+ targetUrl: triggerResponse.targetUrl || null,
4747
+ };
4748
+ printRunOrChain(out, partial, opts.createContext, data => {
4749
+ const p = data;
4750
+ const lines = [
4751
+ `runId ${p.runId}`,
4752
+ `status ${p.status} (rate limited by the server)`,
4753
+ ];
4754
+ if (p.targetUrl)
4755
+ lines.push(`targetUrl ${p.targetUrl}`);
4756
+ lines.push(`hint Re-attach with: testsprite test wait ${p.runId}`);
4757
+ lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4758
+ return lines.join('\n');
4759
+ });
4760
+ stderrFn(rateLimitedDetachMessage(err, [triggerResponse.runId]));
4761
+ throw err;
4762
+ }
3915
4763
  // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1): same partial-
3916
4764
  // envelope shape as the timeout paths so stdout stays parseable, plus the
3917
4765
  // honest "keeps running and billing" stderr line. Rethrow → index.ts
@@ -3947,7 +4795,8 @@ export async function runTestRun(opts, deps = {}) {
3947
4795
  // the standalone `test run <id>` path neither is set, so probe the test type
3948
4796
  // once (text mode only, best-effort) — DEV-282.
3949
4797
  const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
3950
- printRunOrChain(out, withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), opts.createContext, data => renderRunResponseText(data, { isBackend }));
4798
+ const finalRunWithUrl = withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps));
4799
+ printRunOrChain(out, finalRunWithUrl, opts.createContext, data => renderRunResponseText(data, { isBackend }));
3951
4800
  // Surface the trigger requestId under --verbose/--debug or JSON mode so
3952
4801
  // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
3953
4802
  // JSON mode always emits to stderr — it never pollutes stdout).
@@ -3960,6 +4809,41 @@ export async function runTestRun(opts, deps = {}) {
3960
4809
  ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
3961
4810
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
3962
4811
  }
4812
+ // CI-native output layer (issue #99): single-test parity with the --all batch.
4813
+ // Emitted before the exit-code gate throws below so the summary file and
4814
+ // annotations land even when the run exits non-zero (mirrors the batch path).
4815
+ // The summary file is a machine artifact written regardless of --output mode;
4816
+ // under --output json the run envelope above owns stdout, so ::error::
4817
+ // workflow commands are routed to stderr (the Actions runner parses both).
4818
+ // Best-effort: a sink write throwing (e.g. EPIPE) must never skip the
4819
+ // exit-code gate below or change the command's exit status.
4820
+ try {
4821
+ const env = deps.env ?? process.env;
4822
+ const ghEnabled = opts.ghOutput === true || env.GITHUB_ACTIONS === 'true';
4823
+ if (ghEnabled || opts.summaryFile !== undefined) {
4824
+ const ciSummary = summarizeSingleRun(finalRunWithUrl);
4825
+ if (opts.summaryFile !== undefined) {
4826
+ try {
4827
+ writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
4828
+ }
4829
+ catch {
4830
+ stderrFn(`[run] could not write --summary-file ${opts.summaryFile}; continuing`);
4831
+ }
4832
+ }
4833
+ if (ghEnabled) {
4834
+ const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
4835
+ emitGithubOutputs(ciSummary, env, {
4836
+ stdout: stdoutFn,
4837
+ stderr: stderrFn,
4838
+ appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
4839
+ annotations: opts.output === 'json' ? stderrFn : stdoutFn,
4840
+ }, { force: opts.ghOutput === true });
4841
+ }
4842
+ }
4843
+ }
4844
+ catch (ciErr) {
4845
+ stderrFn(`[run] CI output emission failed; continuing: ${ciErr.message}`);
4846
+ }
3963
4847
  const exitCode = exitCodeForRunStatus(finalRun.status);
3964
4848
  if (exitCode !== 0) {
3965
4849
  // Throw a CLIError so index.ts exits with the right code without
@@ -3998,50 +4882,100 @@ export async function runTestWaitMany(opts, deps = {}) {
3998
4882
  }
3999
4883
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs({ ...opts, wait: true }) }, deps);
4000
4884
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
4885
+ const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
4001
4886
  // One shared deadline across every member (the whole point of the shared
4002
4887
  // pool: `--timeout 600` means the invocation ends within ~600s, not
4003
4888
  // 600s x ceil(N/concurrency)).
4004
4889
  const deadlineMs = Date.now() + opts.timeoutSeconds * 1000;
4005
4890
  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
4891
  const resolveAlternate = makeBackendWaitFallback({
4013
4892
  client,
4014
4893
  resolveTestId: run => run.testId,
4015
4894
  resolveNotBefore: run => run.createdAt,
4016
4895
  onResolved: () => undefined,
4017
4896
  });
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)
4897
+ // Outer RATE_LIMITED retry, per member. `http.ts` already retries a 429
4898
+ // internally (`MAX_ATTEMPTS_RATE_LIMITED`), so reaching this catch means the
4899
+ // transport gave up — but a shared-egress 429 (CI runner / NAT tripping the
4900
+ // backend's ip-keyed pre-auth limiter) is a property of the *window*, not of
4901
+ // this run, and the run is still executing. Without this loop a single 429
4902
+ // ended the whole member's wait, which is what made a healthy run report as
4903
+ // a poll error. Mirrors the `test run --all` trigger fan-out's outer loop
4904
+ // (`BATCH_RUN_RATE_MAX_OUTER_RETRIES`), including its two invariants: the
4905
+ // sleep is clamped to the SHARED deadline (so a retry can never stretch
4906
+ // `--timeout`), and the retry is per member — one throttled run does not
4907
+ // stall the pool, because each lane runs this loop inside its own task.
4908
+ let rateLimitAttempt = 0;
4909
+ for (;;) {
4910
+ // A member dequeued AFTER the shared deadline has passed must not be
4911
+ // granted a fresh minimum poll window (with --max-concurrency 1 that
4912
+ // would extend the invocation by ~1s per queued run past --timeout).
4913
+ // Re-evaluated on every iteration so a retry obeys the same rule.
4914
+ const remainingSeconds = Math.ceil((deadlineMs - Date.now()) / 1000);
4915
+ if (remainingSeconds <= 0)
4034
4916
  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 };
4917
+ try {
4918
+ const run = await pollRunUntilTerminal(client, runId, {
4919
+ timeoutSeconds: remainingSeconds,
4920
+ sleep: deps.sleep,
4921
+ shutdown: shutdownOf(deps),
4922
+ onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
4923
+ onTick: (run, elapsedMs) => {
4924
+ const elapsed = Math.round(elapsedMs / 1000);
4925
+ ticker.update(`Run ${run.runId} — ${run.status} (elapsed=${elapsed}s)`);
4926
+ },
4927
+ resolveAlternate,
4928
+ });
4929
+ return { kind: 'result', run };
4930
+ }
4931
+ catch (err) {
4932
+ if (err instanceof TimeoutError)
4933
+ return { kind: 'timeout' };
4934
+ if (err instanceof RequestTimeoutError)
4935
+ throw err;
4936
+ // Interrupt must reject the fan-out (handled at the collect point), not
4937
+ // be flattened into a per-member 'error' outcome that would swallow the
4938
+ // 128+signum exit (DEV-331).
4939
+ if (err instanceof InterruptError)
4940
+ throw err;
4941
+ if (err instanceof ApiError) {
4942
+ // `isTransientRateLimit` is the second gate, for an "unknown" 429 that
4943
+ // carries neither a Retry-After nor the per-minute wording: treat it as
4944
+ // permanent rather than burn the budget on it. (The credit-depletion
4945
+ // 429 never reaches here at all — `errors.ts` re-maps that envelope to
4946
+ // INSUFFICIENT_CREDITS before this catch sees it.)
4947
+ if (err.code === 'RATE_LIMITED' &&
4948
+ isTransientRateLimit(err) &&
4949
+ rateLimitAttempt < WAIT_POLL_RATE_MAX_OUTER_RETRIES) {
4950
+ rateLimitAttempt++;
4951
+ const retryAfterMs = resolveRateLimitRetryMs(err);
4952
+ const clampedRetryMs = Math.min(retryAfterMs, deadlineMs - Date.now());
4953
+ // Deadline already reached: the wait budget genuinely ran out, so the
4954
+ // honest outcome is `timeout` — the same call the trigger fan-out
4955
+ // makes ("Timed out … during rate-limit backoff"). Reporting the 429
4956
+ // instead would let the exit-11 escalation below claim "nothing else
4957
+ // went wrong" for an invocation that in fact exhausted `--timeout`.
4958
+ if (clampedRetryMs <= 0)
4959
+ return { kind: 'timeout' };
4960
+ stderrFn(`[wait] ${runId} — rate limited (attempt ${rateLimitAttempt}/${WAIT_POLL_RATE_MAX_OUTER_RETRIES}): retrying in ${Math.ceil(clampedRetryMs / 1000)}s`);
4961
+ // Arm the graceful-detach scope across the backoff. `pollRunUntilTerminal`
4962
+ // disarms in its own `finally`, so without this the sleep is a window
4963
+ // where a first Ctrl-C hard-exits instead of taking the DEV-331 detach
4964
+ // path (partial `{runId, status:'running'}` on stdout + honest hint).
4965
+ const shutdown = shutdownOf(deps);
4966
+ const disarm = shutdown.arm();
4967
+ try {
4968
+ await sleepUntilOrInterrupt(clampedRetryMs, shutdown.signal, sleepFn);
4969
+ }
4970
+ finally {
4971
+ disarm();
4972
+ }
4973
+ continue;
4974
+ }
4975
+ return { kind: 'error', code: err.code, exitCode: err.exitCode };
4976
+ }
4977
+ return { kind: 'error', code: 'TRANSPORT', exitCode: 10 };
4978
+ }
4045
4979
  }
4046
4980
  };
4047
4981
  const outcomes = new Map();
@@ -4145,6 +5079,32 @@ export async function runTestWaitMany(opts, deps = {}) {
4145
5079
  if (authError !== undefined && authError.kind === 'error') {
4146
5080
  throw new CLIError(`Multi-run wait: authentication failed (${authError.code})`, authError.exitCode);
4147
5081
  }
5082
+ // Rate limiting escalates the same way auth does, for the same reason: when it
5083
+ // is the ONLY thing that went wrong, exit 7 ("timeout or per-member poll
5084
+ // error") is actively misleading — nothing timed out and no run misbehaved, the
5085
+ // client was throttled — and 7 tells an automated caller to re-attach
5086
+ // immediately, which walks straight back into the limiter. Exit 11 says "back
5087
+ // off, then re-attach", which is the correct action. Deliberately narrow: it
5088
+ // requires that EVERY non-passed member is a rate-limited poll error, so a real
5089
+ // timeout or a genuinely failed run is never masked (those keep 7 / 1). By this
5090
+ // point each member has already spent its `WAIT_POLL_RATE_MAX_OUTER_RETRIES`
5091
+ // Retry-After backoffs, so this is a persistently throttled window, not a blip.
5092
+ // `outcomes` is keyed by runId, so a REPEATED id has one shared entry that the
5093
+ // last lane to finish overwrites — a genuine `failed` can be replaced by a
5094
+ // later RATE_LIMITED, which would make the counts below claim "nothing else
5095
+ // went wrong" for an invocation that observed a failure. Rather than change the
5096
+ // long-standing one-row-per-input-id output shape, the escalation simply
5097
+ // declines to fire when the caller passed a duplicate; exit 7 is then the same
5098
+ // answer as before this change.
5099
+ const idsAreUnique = new Set(opts.runIds).size === opts.runIds.length;
5100
+ const rateLimitedOnly = idsAreUnique &&
5101
+ errors > 0 &&
5102
+ timedOut === 0 &&
5103
+ failed === 0 &&
5104
+ [...outcomes.values()].every(o => o.kind !== 'error' || o.code === 'RATE_LIMITED');
5105
+ if (rateLimitedOnly) {
5106
+ 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);
5107
+ }
4148
5108
  if (timedOut > 0 || errors > 0) {
4149
5109
  throw new CLIError(`Multi-run wait: ${timedOut} timed out, ${errors} poll error(s) out of ${results.length} runs`, 7);
4150
5110
  }
@@ -4390,6 +5350,26 @@ export async function runTestWait(opts, deps = {}) {
4390
5350
  `Re-attach with: testsprite test wait ${opts.runId}, or cancel with: testsprite test cancel ${opts.runId}`);
4391
5351
  throw err;
4392
5352
  }
5353
+ // RATE_LIMITED during polling — see the matching comment in runTestRun.
5354
+ // The HTTP layer already retried internally and gave up; the run keeps
5355
+ // executing (and billing) server-side, so this must emit the same
5356
+ // partial-envelope + honest hint as the timeout/interrupt paths. The SAME
5357
+ // ApiError is rethrown unchanged so its native exit code (11) is kept.
5358
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
5359
+ ticker.finalize(`Run ${opts.runId} — rate limited by the server`);
5360
+ const partial = { runId: opts.runId, status: 'running' };
5361
+ out.print(partial, data => {
5362
+ const p = data;
5363
+ return [
5364
+ `runId ${p.runId}`,
5365
+ `status ${p.status} (rate limited by the server)`,
5366
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
5367
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
5368
+ ].join('\n');
5369
+ });
5370
+ stderrFn(rateLimitedDetachMessage(err, [opts.runId]));
5371
+ throw err;
5372
+ }
4393
5373
  // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
4394
5374
  if (err instanceof InterruptError) {
4395
5375
  ticker.finalize(`Run ${opts.runId} — interrupted (${err.signal})`);
@@ -4450,7 +5430,8 @@ async function writeBatchJUnitReportIfRequested(opts, results) {
4450
5430
  */
4451
5431
  export async function runTestRunAll(opts, deps = {}) {
4452
5432
  assertIdempotencyKey(opts.idempotencyKey);
4453
- requireProjectId(opts.projectId);
5433
+ const projectId = resolveProjectId(opts.projectId, deps);
5434
+ requireProjectId(projectId);
4454
5435
  if (!Number.isInteger(opts.maxConcurrency) ||
4455
5436
  opts.maxConcurrency < 1 ||
4456
5437
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
@@ -4477,7 +5458,7 @@ export async function runTestRunAll(opts, deps = {}) {
4477
5458
  method: 'POST',
4478
5459
  path: '/api/cli/v1/tests/batch/run',
4479
5460
  body: {
4480
- projectId: opts.projectId,
5461
+ projectId,
4481
5462
  testIds: opts.nameFilter ? ['<filtered by --filter>'] : undefined,
4482
5463
  source: 'cli',
4483
5464
  },
@@ -4500,9 +5481,9 @@ export async function runTestRunAll(opts, deps = {}) {
4500
5481
  const batchPortalBase = resolvePortalBase(batchApiUrl);
4501
5482
  const projectDashboardUrl = batchPortalBase === undefined
4502
5483
  ? undefined
4503
- : `${batchPortalBase}/dashboard/tests/${encodeURIComponent(opts.projectId)}`;
5484
+ : `${batchPortalBase}/dashboard/tests/${encodeURIComponent(projectId)}`;
4504
5485
  const withBatchDashboardUrl = (item) => {
4505
- const dashboardUrl = resolvePortalUrl(batchApiUrl, opts.projectId, item.testId);
5486
+ const dashboardUrl = resolvePortalUrl(batchApiUrl, projectId, item.testId);
4506
5487
  return dashboardUrl !== undefined ? { ...item, dashboardUrl } : item;
4507
5488
  };
4508
5489
  const idempotencyKey = opts.idempotencyKey ?? `cli-batch-run-fresh-${randomUUID()}`;
@@ -4514,7 +5495,7 @@ export async function runTestRunAll(opts, deps = {}) {
4514
5495
  if (opts.nameFilter !== undefined && opts.nameFilter !== '') {
4515
5496
  // We need to resolve the full test set to apply the name filter.
4516
5497
  const allPage = await paginate(async ({ pageSize, cursor }) => client.get('/tests', {
4517
- query: { projectId: opts.projectId, pageSize, cursor },
5498
+ query: { projectId, pageSize, cursor },
4518
5499
  }), {});
4519
5500
  const needle = opts.nameFilter.toLowerCase();
4520
5501
  const filtered = allPage.items.filter(t => t.name.toLowerCase().includes(needle));
@@ -4525,7 +5506,7 @@ export async function runTestRunAll(opts, deps = {}) {
4525
5506
  }
4526
5507
  testIds = filtered.map(t => t.id);
4527
5508
  if (testIds.length === 0) {
4528
- stderrFn(`No tests found in project ${opts.projectId} matching --filter "${opts.nameFilter}" — nothing to run.`);
5509
+ stderrFn(`No tests found in project ${projectId} matching --filter "${opts.nameFilter}" — nothing to run.`);
4529
5510
  out.print({
4530
5511
  accepted: [],
4531
5512
  conflicts: [],
@@ -4535,12 +5516,12 @@ export async function runTestRunAll(opts, deps = {}) {
4535
5516
  });
4536
5517
  return undefined;
4537
5518
  }
4538
- stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${opts.projectId} for batch run.`);
5519
+ stderrFn(`Resolved ${testIds.length} test${testIds.length !== 1 ? 's' : ''} in project ${projectId} for batch run.`);
4539
5520
  }
4540
5521
  // When no --filter, omit testIds → server runs ALL tests in the project
4541
5522
  // (BE tests on the legacy V2 wave engine; FE + BE on the V3 unified engine).
4542
5523
  const batchResp = await client.triggerBatchRunFresh({
4543
- projectId: opts.projectId,
5524
+ projectId,
4544
5525
  ...(testIds !== undefined ? { testIds } : {}),
4545
5526
  source: 'cli',
4546
5527
  }, { idempotencyKey });
@@ -4653,7 +5634,7 @@ export async function runTestRunAll(opts, deps = {}) {
4653
5634
  let retryResp;
4654
5635
  try {
4655
5636
  retryResp = await client.triggerBatchRunFresh({
4656
- projectId: opts.projectId,
5637
+ projectId,
4657
5638
  testIds: retryIds,
4658
5639
  source: 'cli',
4659
5640
  }, { idempotencyKey: retryKey });
@@ -4881,6 +5862,37 @@ export async function runTestRunAll(opts, deps = {}) {
4881
5862
  };
4882
5863
  await writeBatchJUnitReportIfRequested(opts, freshRunResults);
4883
5864
  out.print(jsonPayload);
5865
+ // CI-native output layer (issue #99): emitted before the gate throws below so
5866
+ // the artifacts land even when the batch exits non-zero. The summary file is a
5867
+ // machine artifact written regardless of --output mode; stdout stays owned by
5868
+ // the envelope above (plus Actions workflow commands, which Actions parses).
5869
+ {
5870
+ const env = deps.env ?? process.env;
5871
+ const ghEnabled = opts.ghOutput === true || env.GITHUB_ACTIONS === 'true';
5872
+ if (ghEnabled || opts.summaryFile !== undefined) {
5873
+ const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
5874
+ if (opts.summaryFile !== undefined) {
5875
+ try {
5876
+ writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
5877
+ }
5878
+ catch {
5879
+ stderrFn(`[run] could not write --summary-file ${opts.summaryFile}; continuing`);
5880
+ }
5881
+ }
5882
+ if (ghEnabled) {
5883
+ const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
5884
+ emitGithubOutputs(ciSummary, env, {
5885
+ stdout: stdoutFn,
5886
+ stderr: stderrFn,
5887
+ appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
5888
+ // Under --output json the envelope above owns stdout; workflow
5889
+ // commands go to stderr instead (the Actions runner parses both
5890
+ // streams), keeping the documented machine output parseable.
5891
+ annotations: opts.output === 'json' ? stderrFn : stdoutFn,
5892
+ }, { force: opts.ghOutput === true });
5893
+ }
5894
+ }
5895
+ }
4884
5896
  // Rate-deferred tests were never dispatched → the batch is incomplete (exit 7),
4885
5897
  // mirroring `test rerun --all`. Checked before the failed-run throw so the
4886
5898
  // operator learns to retry the deferred set.
@@ -4926,8 +5938,9 @@ export async function runTestRunAll(opts, deps = {}) {
4926
5938
  /**
4927
5939
  * `test rerun` — M3.4 piece-3.
4928
5940
  *
4929
- * FE: `POST /tests/{id}/runs/rerun` → verbatim replay (no credit). With
4930
- * `--wait`, polls `GET /runs/{runId}` until terminal.
5941
+ * FE: `POST /tests/{id}/runs/rerun` → verbatim replay, billed at 0.5 credits
5942
+ * (same as a fresh run; legacy V2 accounts: free). With `--wait`, polls
5943
+ * `GET /runs/{runId}` until terminal.
4931
5944
  *
4932
5945
  * BE: same route → closure + per-member runIds. With `--wait`, polls every
4933
5946
  * closure-member runId; exits on the named test's verdict; failed closure
@@ -5077,7 +6090,10 @@ export async function runTestRerun(opts, deps = {}) {
5077
6090
  try {
5078
6091
  rerunResp = await client.triggerRerun(testId, {
5079
6092
  source: 'cli',
5080
- ...(effectiveAutoHeal ? { autoHeal: true } : {}),
6093
+ // Always send the effective boolean, including an explicit `false`
6094
+ // opt-out — the server defaults an ABSENT field to heal-on, so
6095
+ // omitting the key on opt-out silently discarded --no-auto-heal.
6096
+ autoHeal: effectiveAutoHeal,
5081
6097
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
5082
6098
  }, { idempotencyKey });
5083
6099
  }
@@ -5117,8 +6133,11 @@ export async function runTestRerun(opts, deps = {}) {
5117
6133
  // Print auto-heal advisory.
5118
6134
  // CLI path: auto-heal is default-on for FE reruns (--no-auto-heal to opt
5119
6135
  // 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).
6136
+ // tier-gates for source='cli'. The rerun itself is billed at 0.5 credits
6137
+ // regardless of whether heal engages (same as a fresh run; legacy V2
6138
+ // accounts: a verbatim replay pass is free). A heal engage costs an
6139
+ // additional 0.2 credits on top of that, charged only when Phase-2 heal
6140
+ // actually runs.
5122
6141
  //
5123
6142
  // Defensive branch: if the server still echoes autoHeal:false after we sent
5124
6143
  // autoHeal:true, the server did not apply it (unexpected; may happen on
@@ -5132,17 +6151,21 @@ export async function runTestRerun(opts, deps = {}) {
5132
6151
  // default-on `true`, so opts.autoHeal && !rerunResp.autoHeal would
5133
6152
  // fire spuriously for every BE rerun).
5134
6153
  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));
6154
+ // Points at `testsprite usage`, not a hardcoded billing URL: this CLI
6155
+ // path has no per-request org context (no backend nextAction feeds
6156
+ // this advisory, and a personal-vs-org-bound key can't be told apart
6157
+ // here), while `usage` already renders whichever wallet (personal or
6158
+ // organization) actually governs this key's balance.
5138
6159
  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)'}.`);
6160
+ ` If this was unexpected, check your balance with \`testsprite usage\`.`);
5142
6161
  }
5143
6162
  else if (rerunResp.autoHeal) {
5144
6163
  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
6164
  }
6165
+ // Server advisory: the autoHeal opt-out was forwarded to the execution
6166
+ // engine but is not yet enforced there. Present only on a V3-routed
6167
+ // rerun with an explicit autoHeal:false request; absent everywhere else.
6168
+ emitRerunAdvisories(stderrFn, rerunResp.advisories);
5146
6169
  const isBERerun = !!rerunResp.closure;
5147
6170
  if (isBERerun && rerunResp.closure) {
5148
6171
  const totalCount = rerunResp.closure.members.length;
@@ -5190,6 +6213,8 @@ export async function runTestRerun(opts, deps = {}) {
5190
6213
  // BE rerun: poll every closure-member runId, exit on named test's verdict.
5191
6214
  const namedRunId = rerunResp.runId;
5192
6215
  const closureMembers = rerunResp.closure.members;
6216
+ // `unobserved`: member never reached a terminal verdict (timed out or its
6217
+ // poll errored). Distinct from an observed non-passed run (failed/blocked).
5193
6218
  const closureFailures = [];
5194
6219
  const pollMember = async (member) => {
5195
6220
  const resolveAlternate = makeBackendWaitFallback({
@@ -5199,7 +6224,7 @@ export async function runTestRerun(opts, deps = {}) {
5199
6224
  onResolved: () => undefined,
5200
6225
  });
5201
6226
  try {
5202
- return await pollRunUntilTerminal(client, member.runId, {
6227
+ const finalRun = await pollRunUntilTerminal(client, member.runId, {
5203
6228
  timeoutSeconds: opts.timeoutSeconds,
5204
6229
  sleep: deps.sleep,
5205
6230
  shutdown: shutdownOf(deps),
@@ -5216,12 +6241,22 @@ export async function runTestRerun(opts, deps = {}) {
5216
6241
  },
5217
6242
  resolveAlternate,
5218
6243
  });
6244
+ return { kind: 'terminal', run: finalRun };
5219
6245
  }
5220
6246
  catch (err) {
5221
- if (err instanceof TimeoutError) {
5222
- return null;
5223
- }
5224
- throw err;
6247
+ if (err instanceof TimeoutError)
6248
+ return { kind: 'timeout' };
6249
+ // Preserve the two intentional whole-fan-out aborts: each has a
6250
+ // dedicated outer-catch branch (RequestTimeoutError → all-running
6251
+ // partial + re-attach hints + exit 7; InterruptError → DEV-331
6252
+ // graceful detach). Re-throw so the fan-out's `.catch(reject)` fires.
6253
+ if (err instanceof RequestTimeoutError || err instanceof InterruptError)
6254
+ throw err;
6255
+ // Any other member error (ApiError, transient 5xx, malformed
6256
+ // response) is classified per-member instead of rejecting the whole
6257
+ // fan-out and discarding every already-collected sibling result.
6258
+ const status = err instanceof ApiError ? err.code : 'error';
6259
+ return { kind: 'error', status, error: err };
5225
6260
  }
5226
6261
  };
5227
6262
  // Fan-out poll with concurrency limit
@@ -5230,6 +6265,10 @@ export async function runTestRerun(opts, deps = {}) {
5230
6265
  const concurrencyLimit = opts.maxConcurrency;
5231
6266
  let inFlight = 0;
5232
6267
  let memberIdx = 0;
6268
+ // Set when the NAMED test's own poll errors (not a timeout). Re-thrown
6269
+ // after the payload is printed so its real error/exit code is preserved
6270
+ // without discarding the sibling results collected alongside it.
6271
+ let namedPollError;
5233
6272
  try {
5234
6273
  await new Promise((resolve, reject) => {
5235
6274
  function startNext() {
@@ -5237,27 +6276,51 @@ export async function runTestRerun(opts, deps = {}) {
5237
6276
  const member = members[memberIdx++];
5238
6277
  inFlight++;
5239
6278
  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.
6279
+ .then(outcome => {
6280
+ if (outcome.kind === 'terminal') {
6281
+ memberResults.set(member.runId, outcome.run);
6282
+ if (member.runId !== namedRunId && outcome.run.status !== 'passed') {
6283
+ closureFailures.push({
6284
+ testId: member.testId,
6285
+ runId: member.runId,
6286
+ status: outcome.run.status,
6287
+ });
6288
+ stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) finished with status: ${outcome.run.status}`);
6289
+ }
6290
+ }
6291
+ else if (outcome.kind === 'timeout') {
6292
+ // Timed-out closure member: treat as incomplete/failed so
6293
+ // the exit-code path fires exit 7 rather than silently
6294
+ // succeeding with an unobserved member.
6295
+ memberResults.set(member.runId, null);
6296
+ if (member.runId !== namedRunId) {
5247
6297
  closureFailures.push({
5248
6298
  testId: member.testId,
5249
6299
  runId: member.runId,
5250
6300
  status: 'timeout',
6301
+ unobserved: true,
5251
6302
  });
5252
6303
  stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) timed out — rerun did not reach terminal within --timeout`);
5253
6304
  }
5254
- else if (result.status !== 'passed') {
6305
+ }
6306
+ else {
6307
+ // Classified per-member error — recorded, never aborts the
6308
+ // fan-out. The named test's error is stashed for re-throw;
6309
+ // sibling errors surface in closureFailures[].
6310
+ memberResults.set(member.runId, null);
6311
+ if (member.runId === namedRunId) {
6312
+ namedPollError = outcome.error;
6313
+ }
6314
+ else {
6315
+ // A poll error means we never saw a terminal verdict — the
6316
+ // run may still be in flight — so it's unobserved too.
5255
6317
  closureFailures.push({
5256
6318
  testId: member.testId,
5257
6319
  runId: member.runId,
5258
- status: result.status,
6320
+ status: outcome.status,
6321
+ unobserved: true,
5259
6322
  });
5260
- stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) finished with status: ${result.status}`);
6323
+ stderrFn(`⚠ closure member ${member.testId} (runId: ${member.runId}) could not be confirmed terminal — poll error: ${outcome.status}`);
5261
6324
  }
5262
6325
  }
5263
6326
  inFlight--;
@@ -5300,6 +6363,27 @@ export async function runTestRerun(opts, deps = {}) {
5300
6363
  `Or cancel with:\n${cancelHints}`);
5301
6364
  throw fanOutErr;
5302
6365
  }
6366
+ // RATE_LIMITED from any member's poll (pollMember only swallows
6367
+ // TimeoutError into a null return — see above; every other error,
6368
+ // including a RATE_LIMITED ApiError, propagates through .catch(reject)
6369
+ // exactly like RequestTimeoutError). Same partial shape as the
6370
+ // timeout path so the caller always has every closure-member runId on
6371
+ // stdout; the SAME thrown ApiError is rethrown unchanged so its
6372
+ // native exit code (11) is preserved.
6373
+ if (fanOutErr instanceof ApiError && fanOutErr.code === 'RATE_LIMITED') {
6374
+ ticker.finalize(`Closure fan-out — rate limited by the server`);
6375
+ const dispatchedRunIds = closureMembers.map(m => ({
6376
+ runId: m.runId,
6377
+ testId: m.testId,
6378
+ role: m.role,
6379
+ status: 'running',
6380
+ }));
6381
+ out.print({ runId: namedRunId, status: 'running', closure: dispatchedRunIds }, () => dispatchedRunIds
6382
+ .map(m => `${m.role.padEnd(9)} ${m.testId} (runId: ${m.runId}) — running`)
6383
+ .join('\n'));
6384
+ stderrFn(rateLimitedDetachMessage(fanOutErr, closureMembers.map(m => m.runId)));
6385
+ throw fanOutErr;
6386
+ }
5303
6387
  // Graceful detach (DEV-331): same partial shape as the timeout path —
5304
6388
  // SIG-6 requires the partial to list ALL dispatched runIds.
5305
6389
  if (fanOutErr instanceof InterruptError) {
@@ -5345,6 +6429,19 @@ export async function runTestRerun(opts, deps = {}) {
5345
6429
  return lines.join('\n');
5346
6430
  });
5347
6431
  if (!namedResult) {
6432
+ // Named test's own poll errored (not a timeout): re-throw its real
6433
+ // error now that the payload (incl. sibling closureFailures) is
6434
+ // printed, preserving the true exit code instead of masking it as a
6435
+ // timeout.
6436
+ if (namedPollError !== undefined) {
6437
+ // Every dispatched member is still executing (and billing), so a
6438
+ // rate-limited named poll owes the same detach hints the fan-out's
6439
+ // own branch emits — which this re-throw bypasses.
6440
+ if (namedPollError instanceof ApiError && namedPollError.code === 'RATE_LIMITED') {
6441
+ stderrFn(rateLimitedDetachMessage(namedPollError, closureMembers.map(m => m.runId)));
6442
+ }
6443
+ throw namedPollError;
6444
+ }
5348
6445
  // timeout
5349
6446
  throw ApiError.fromEnvelope({
5350
6447
  error: {
@@ -5360,23 +6457,23 @@ export async function runTestRerun(opts, deps = {}) {
5360
6457
  stderrFn(`Run finished with status: ${namedResult.status}. Use 'testsprite test artifact get ${namedRunId}' to download the failure bundle.`);
5361
6458
  throw new CLIError(`Run ${namedRunId} finished with status: ${namedResult.status}`, 1);
5362
6459
  }
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(' ')}`;
6460
+ // Any unobserved member (timed out OR poll-errored) flips --wait to exit 7,
6461
+ // even when the named run passes — otherwise a dependency whose status was
6462
+ // never confirmed would let --wait exit 0. Observed-failed members are not
6463
+ // included; that's the future --fail-on-closure decision.
6464
+ const unobservedMembers = closureFailures.filter(f => f.unobserved);
6465
+ if (unobservedMembers.length > 0) {
6466
+ const unobservedIds = unobservedMembers.map(f => f.runId);
6467
+ const resumeHints = unobservedIds.map(runId => `testsprite test wait ${runId}`).join('\n') +
6468
+ `\nCancel instead: testsprite test cancel ${unobservedIds.join(' ')}`;
5372
6469
  throw ApiError.fromEnvelope({
5373
6470
  error: {
5374
6471
  code: 'UNSUPPORTED',
5375
- message: `${timedOutMembers.length} closure member${timedOutMembers.length !== 1 ? 's' : ''} timed out before reaching terminal status.`,
6472
+ message: `${unobservedMembers.length} closure member${unobservedMembers.length !== 1 ? 's' : ''} did not reach an observed terminal status (timed out or errored during polling).`,
5376
6473
  nextAction: resumeHints,
5377
6474
  requestId: 'local',
5378
6475
  details: {
5379
- timedOutRunIds: timedOutMembers.map(f => f.runId),
6476
+ unobservedRunIds: unobservedIds,
5380
6477
  timeoutSeconds: opts.timeoutSeconds,
5381
6478
  },
5382
6479
  },
@@ -5442,6 +6539,24 @@ export async function runTestRerun(opts, deps = {}) {
5442
6539
  `Re-attach with: testsprite test wait ${rerunResp.runId}, or cancel with: testsprite test cancel ${rerunResp.runId}`);
5443
6540
  throw err;
5444
6541
  }
6542
+ // RATE_LIMITED during polling — see the matching comment in runTestRun.
6543
+ // Same partial-envelope contract; the SAME thrown ApiError is rethrown
6544
+ // unchanged so its native exit code (11) is preserved.
6545
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
6546
+ ticker.finalize(`Run ${rerunResp.runId} — rate limited by the server`);
6547
+ const partial = { runId: rerunResp.runId, status: 'running' };
6548
+ out.print(partial, data => {
6549
+ const p = data;
6550
+ return [
6551
+ `runId ${p.runId}`,
6552
+ `status ${p.status} (rate limited by the server)`,
6553
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
6554
+ `hint Cancel with: testsprite test cancel ${p.runId}`,
6555
+ ].join('\n');
6556
+ });
6557
+ stderrFn(rateLimitedDetachMessage(err, [rerunResp.runId]));
6558
+ throw err;
6559
+ }
5445
6560
  // Graceful detach on SIGINT/SIGTERM (DEV-331 piece 1) — see runTestRun.
5446
6561
  if (err instanceof InterruptError) {
5447
6562
  ticker.finalize(`Run ${rerunResp.runId} — interrupted (${err.signal})`);
@@ -5575,7 +6690,9 @@ export async function runTestRerun(opts, deps = {}) {
5575
6690
  const chunkResp = await client.triggerBatchRerun({
5576
6691
  source: 'cli',
5577
6692
  testIds: chunk,
5578
- ...(effectiveAutoHeal ? { autoHeal: true } : {}),
6693
+ // Always send the effective boolean, including an explicit `false`
6694
+ // opt-out — see the matching comment on the single-rerun call site.
6695
+ autoHeal: effectiveAutoHeal,
5579
6696
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
5580
6697
  }, { idempotencyKey: chunkKey });
5581
6698
  chunkResponses.push(chunkResp);
@@ -5619,10 +6736,17 @@ export async function runTestRerun(opts, deps = {}) {
5619
6736
  byProject: mergeBatchRerunClosureByProject(chunkResponses.flatMap(r => r.closure.byProject)),
5620
6737
  },
5621
6738
  notFound: chunkResponses.flatMap(r => r.notFound ?? []),
6739
+ // Absent on every response except a V3-routed batch containing
6740
+ // at least one FE test with an explicit autoHeal:false opt-out. Dedupe
6741
+ // across chunks — every chunk in the same invocation carries the same
6742
+ // autoHeal request, so the same advisory would otherwise repeat per chunk.
6743
+ advisories: dedupeRerunAdvisories(chunkResponses.flatMap(r => r.advisories ?? [])),
5622
6744
  };
5623
6745
  // Print dispatch summary
5624
6746
  // Mutable: D3 deferred-retry loop may append to `accepted`/`conflicts` and
5625
- // drain `deferred` under --wait.
6747
+ // drain `deferred` under --wait. `advisories` may also grow if a D3 retry
6748
+ // response carries an advisory the initial dispatch didn't (defensive —
6749
+ // in practice the same request shape produces the same advisory set).
5626
6750
  let accepted = batchResp.accepted.slice();
5627
6751
  let deferred = batchResp.deferred.slice();
5628
6752
  let conflicts = batchResp.conflicts.slice();
@@ -5630,6 +6754,9 @@ export async function runTestRerun(opts, deps = {}) {
5630
6754
  // the retry window; the retry response's notFound[] is merged into this set so
5631
6755
  // the test is never reported as "resolved" when it actually vanished.
5632
6756
  let notFound = (batchResp.notFound ?? []).slice();
6757
+ // Mutable so a D3 deferred-retry response can contribute an
6758
+ // advisory the initial dispatch didn't carry (defensive; see comment above).
6759
+ let advisories = (batchResp.advisories ?? []).slice();
5633
6760
  const closureByProject = batchResp.closure.byProject;
5634
6761
  const addedProducersTotal = closureByProject.reduce((n, p) => n + p.addedProducers.length, 0);
5635
6762
  const summaryParts = [
@@ -5715,7 +6842,10 @@ export async function runTestRerun(opts, deps = {}) {
5715
6842
  const retryChunkResp = await client.triggerBatchRerun({
5716
6843
  source: 'cli',
5717
6844
  testIds: chunk,
5718
- ...(effectiveAutoHeal ? { autoHeal: true } : {}),
6845
+ // Always send the effective boolean, including an explicit
6846
+ // `false` opt-out — see the matching comment on the initial
6847
+ // dispatch call site above.
6848
+ autoHeal: effectiveAutoHeal,
5719
6849
  ...(opts.skipDependencies ? { skipDependencies: true } : {}),
5720
6850
  }, { idempotencyKey: retryKey });
5721
6851
  retryChunkResponses.push(retryChunkResp);
@@ -5733,6 +6863,12 @@ export async function runTestRerun(opts, deps = {}) {
5733
6863
  // into the running notFound set and remove from deferred so it isn't
5734
6864
  // reported as "resolved" in the final output.
5735
6865
  const newlyNotFound = retryChunkResponses.flatMap(r => r.notFound ?? []);
6866
+ // Merge any advisories the retry response carries into the
6867
+ // running set (deduped — see the initial-dispatch comment above).
6868
+ const newlyAdvisories = retryChunkResponses.flatMap(r => r.advisories ?? []);
6869
+ if (newlyAdvisories.length > 0) {
6870
+ advisories = dedupeRerunAdvisories(advisories.concat(newlyAdvisories));
6871
+ }
5736
6872
  if (newlyDuplicateCount > 0) {
5737
6873
  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
6874
  }
@@ -5764,10 +6900,13 @@ export async function runTestRerun(opts, deps = {}) {
5764
6900
  }
5765
6901
  }
5766
6902
  }
6903
+ // Print the (deduped) advisory set once, after any D3 retries have
6904
+ // had a chance to contribute one, not once per chunk/attempt.
6905
+ emitRerunAdvisories(stderrFn, advisories);
5767
6906
  if (!opts.wait) {
5768
6907
  // [P2] Build output from post-retry mutable state so deferred/conflicts/notFound
5769
6908
  // reflect what the D3 loop discovered, not just the initial batchResp.
5770
- out.print({ ...batchResp, accepted, deferred, conflicts, notFound });
6909
+ out.print({ ...batchResp, accepted, deferred, conflicts, notFound, advisories });
5771
6910
  if (deferred.length > 0) {
5772
6911
  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
6912
  }
@@ -5790,12 +6929,12 @@ export async function runTestRerun(opts, deps = {}) {
5790
6929
  });
5791
6930
  }
5792
6931
  // [P2] Return post-retry state including merged notFound.
5793
- return { ...batchResp, accepted, deferred, conflicts, notFound };
6932
+ return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
5794
6933
  }
5795
6934
  // --wait: fan-out poll each accepted run by its runId
5796
6935
  if (accepted.length === 0) {
5797
6936
  // [P2] Build output from post-retry mutable state including merged notFound.
5798
- out.print({ ...batchResp, accepted, deferred, conflicts, notFound });
6937
+ out.print({ ...batchResp, accepted, deferred, conflicts, notFound, advisories });
5799
6938
  if (deferred.length > 0) {
5800
6939
  throw new CLIError(`Batch rerun: no tests were accepted (${deferred.length} deferred). ` +
5801
6940
  `Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
@@ -5818,7 +6957,7 @@ export async function runTestRerun(opts, deps = {}) {
5818
6957
  });
5819
6958
  }
5820
6959
  // [P2] Return post-retry state including merged notFound.
5821
- return { ...batchResp, accepted, deferred, conflicts, notFound };
6960
+ return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
5822
6961
  }
5823
6962
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
5824
6963
  const concurrencyLimit = opts.maxConcurrency;
@@ -5964,6 +7103,9 @@ export async function runTestRerun(opts, deps = {}) {
5964
7103
  // report the partial run as fully successful. Mirrors the non-wait
5965
7104
  // `out.print(batchResp)` path.
5966
7105
  notFound,
7106
+ // Mirrors the non-wait `out.print(batchResp)` path — carry the
7107
+ // (deduped, post-retry) advisory set into the --wait JSON payload too.
7108
+ advisories,
5967
7109
  closure: batchResp.closure,
5968
7110
  summary: {
5969
7111
  passed,
@@ -5981,6 +7123,35 @@ export async function runTestRerun(opts, deps = {}) {
5981
7123
  };
5982
7124
  await writeBatchJUnitReportIfRequested(opts, rerunResults);
5983
7125
  out.print(jsonPayload);
7126
+ // CI-native output layer (issue #99): batch-rerun parity with `run --all`.
7127
+ // Emitted before the exit-code gates below so the summary file / annotations
7128
+ // land even when the batch exits non-zero. Summary-file is a machine artifact
7129
+ // written regardless of --output mode; under --output json the envelope above
7130
+ // owns stdout, so ::error:: workflow commands go to stderr instead.
7131
+ {
7132
+ const env = deps.env ?? process.env;
7133
+ const ghEnabled = opts.ghOutput === true || env.GITHUB_ACTIONS === 'true';
7134
+ if (ghEnabled || opts.summaryFile !== undefined) {
7135
+ const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
7136
+ if (opts.summaryFile !== undefined) {
7137
+ try {
7138
+ writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
7139
+ }
7140
+ catch {
7141
+ stderrFn(`[rerun] could not write --summary-file ${opts.summaryFile}; continuing`);
7142
+ }
7143
+ }
7144
+ if (ghEnabled) {
7145
+ const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
7146
+ emitGithubOutputs(ciSummary, env, {
7147
+ stdout: stdoutFn,
7148
+ stderr: stderrFn,
7149
+ appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
7150
+ annotations: opts.output === 'json' ? stderrFn : stdoutFn,
7151
+ }, { force: opts.ghOutput === true });
7152
+ }
7153
+ }
7154
+ }
5984
7155
  // Determine exit code: timeout (deferred or any timeout) → 7; any fail → 1; all pass → 0
5985
7156
  if (deferred.length > 0 || timedOut > 0) {
5986
7157
  const stillRunning = timedOut > 0 ? rerunResults.filter(r => r.status === 'timeout').map(r => r.runId) : [];
@@ -6024,7 +7195,7 @@ export async function runTestRerun(opts, deps = {}) {
6024
7195
  // final accounting (accepted = original BatchRerunAccepted[] dispatch list
6025
7196
  // as required by the BatchRerunResponse type; rerunResults is the polled
6026
7197
  // outcome printed to stdout and is not part of the returned shape).
6027
- return { ...batchResp, accepted, deferred, conflicts, notFound };
7198
+ return { ...batchResp, accepted, deferred, conflicts, notFound, advisories };
6028
7199
  }
6029
7200
  export function resolveDefaultArtifactDir(runId, cwd = process.cwd()) {
6030
7201
  requireNonEmpty('run-id', runId);
@@ -6220,6 +7391,8 @@ export function createTestCommand(deps = {}) {
6220
7391
  .option('--starting-token <token>', 'opaque cursor from a previous list response')
6221
7392
  .option('--cursor <token>', 'alias for --starting-token; accepted for parity with `test result --history`')
6222
7393
  .option('--max-items <n>', 'stop after this many items across auto-paged pages')
7394
+ .option('--columns <list>', 'select/reorder text table columns (comma-separated keys)')
7395
+ .option('--no-header', 'suppress the text table header row')
6223
7396
  .addHelpText('after', GLOBAL_OPTS_HINT)
6224
7397
  .action(async (cmdOpts, command) => {
6225
7398
  // Same parser strategy as `project list`: skip Commander's number
@@ -6239,6 +7412,8 @@ export function createTestCommand(deps = {}) {
6239
7412
  pageSize: parseNumericFlag(cmdOpts.pageSize, 'page-size'),
6240
7413
  startingToken: cmdOpts.startingToken ?? cmdOpts.cursor,
6241
7414
  maxItems: parseNumericFlag(cmdOpts.maxItems, 'max-items'),
7415
+ columns: cmdOpts.columns,
7416
+ noHeader: cmdOpts.header === false,
6242
7417
  }, deps);
6243
7418
  });
6244
7419
  test
@@ -6259,6 +7434,8 @@ export function createTestCommand(deps = {}) {
6259
7434
  .option('--code-file <path>', 'file containing the test code (≤ 350 KB)')
6260
7435
  .option('--plan-from <path>', 'JSON file with the full FE test definition — projectId, type, name, planSteps[] all live in the file ' +
6261
7436
  '(≤ 256 KB; mutually exclusive with --code-file). In this mode --project/--type/--name/--description/--priority are ignored.')
7437
+ .option('--plan-template', 'print a minimal valid plan-file skeleton to stdout and exit (pure-local: no network, no credentials, ' +
7438
+ 'ignores every other flag). Pipe to a file and edit: `--plan-template > plan.json`.', false)
6262
7439
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
6263
7440
  .option('--wait', 'with --run, poll until terminal status', false)
6264
7441
  .option('--timeout <s>', 'with --run --wait, max seconds to wait')
@@ -6267,12 +7444,20 @@ export function createTestCommand(deps = {}) {
6267
7444
  .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
7445
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Use to declare upstream producer dependencies.', (val, prev) => [...(prev ?? []), val], [])
6269
7446
  .option('--category <str>', "BE only: test category. Use 'teardown' or 'cleanup' to mark a final-wave cleanup test.")
7447
+ .addHelpText('after', PLAN_TEMPLATE_HELP_TEXT)
6270
7448
  .addHelpText('after', '\nBE dependency authoring (M4):\n' +
6271
7449
  ' --produces/--needs drive wave ordering on `test rerun` + `test run --all`.\n' +
6272
7450
  ' --category teardown marks a final-wave cleanup test.\n' +
6273
7451
  ' These flags are backend-only; supplying with --type frontend is an error (exit 5).')
6274
7452
  .addHelpText('after', GLOBAL_OPTS_HINT)
6275
7453
  .action(async (cmdOpts, command) => {
7454
+ // Pure-local, no network/credentials, no other flag is
7455
+ // consulted. Checked first so `--plan-template` never trips the
7456
+ // --plan-from/--code-file mutual-exclusivity guard below.
7457
+ if (cmdOpts.planTemplate === true) {
7458
+ runPlanTemplate(resolveCommonOptions(command), deps);
7459
+ return;
7460
+ }
6276
7461
  // --plan-from and --code-file are mutually exclusive. Dispatch
6277
7462
  // here so each `run*` function stays single-purpose. If neither
6278
7463
  // is set, the existing runCreate path enforces --code-file.
@@ -6392,6 +7577,18 @@ export function createTestCommand(deps = {}) {
6392
7577
  force: cmdOpts.force === true,
6393
7578
  }, deps);
6394
7579
  });
7580
+ test
7581
+ .command('open <test-id>')
7582
+ .description('Open the test in the TestSprite dashboard: prints the deep-link URL, then spawns your default browser unless --no-browser.')
7583
+ .option('--no-browser', 'print the URL only (SSH, headless, CI, agents)')
7584
+ .addHelpText('after', GLOBAL_OPTS_HINT)
7585
+ .action(async (testId, cmdOpts, command) => {
7586
+ await runOpen({
7587
+ ...resolveCommonOptions(command),
7588
+ testId,
7589
+ noBrowser: cmdOpts.browser === false,
7590
+ }, deps);
7591
+ });
6395
7592
  test
6396
7593
  .command('steps <test-id>')
6397
7594
  .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 +7645,10 @@ export function createTestCommand(deps = {}) {
6448
7645
  .option('--since <dur>', 'with --history: lower bound on createdAt — 24h, 7d, or ISO timestamp (client-side translated)')
6449
7646
  .option('--page-size <n>', 'with --history: number of runs per page (1–100, default 20)')
6450
7647
  .option('--cursor <token>', 'with --history: opaque cursor from a prior page')
7648
+ .option('--rerun', 'with --history: show only reruns')
7649
+ .option('--no-rerun', 'with --history: show only fresh (non-rerun) runs')
7650
+ .option('--columns <list>', 'with --history: select/reorder text table columns')
7651
+ .option('--no-header', 'with --history: suppress the text table header row')
6451
7652
  .addHelpText('after', GLOBAL_OPTS_HINT)
6452
7653
  .action(async (testId, cmdOpts, command) => {
6453
7654
  if (cmdOpts.history) {
@@ -6461,6 +7662,9 @@ export function createTestCommand(deps = {}) {
6461
7662
  ? parseNumericFlag(cmdOpts.pageSize, 'page-size')
6462
7663
  : undefined,
6463
7664
  cursor: cmdOpts.cursor,
7665
+ rerun: cmdOpts.rerun,
7666
+ columns: cmdOpts.columns,
7667
+ noHeader: cmdOpts.header === false,
6464
7668
  }, deps);
6465
7669
  }
6466
7670
  else {
@@ -6563,17 +7767,21 @@ export function createTestCommand(deps = {}) {
6563
7767
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
6564
7768
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6565
7769
  .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`)')
7770
+ .option('--all', 'run all tests in the project (wave-ordered fresh run; uses --project or TESTSPRITE_PROJECT_ID). Mutually exclusive with <test-id>.', false)
7771
+ .option('--project <id>', 'project id (with --all, overrides TESTSPRITE_PROJECT_ID; returned by `testsprite project list`)')
6568
7772
  .option('--filter <substr>', 'with --all: only run tests whose name contains this substring (case-insensitive)')
6569
7773
  .option('--max-concurrency <n>', `with --all --wait, max in-flight polls at once (1-100, default: ${DEFAULT_BATCH_RUN_CONCURRENCY})`)
6570
7774
  .option('--report <format>', 'with --all --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
6571
7775
  .option('--report-file <path>', 'output path for --report (atomic write)')
6572
7776
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
7777
+ .option('--gh-output', 'with --wait (single test or --all): emit GitHub-native output (::error:: annotations per non-passed run; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
7778
+ .option('--summary-file <path>', 'with --wait (single test or --all): also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
6573
7779
  .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' +
7780
+ ' testsprite test run --all --project <id> run all project tests in wave order\n' +
7781
+ ' TESTSPRITE_PROJECT_ID=<id> testsprite test run --all use env default project\n' +
7782
+ ' testsprite test run --all --filter <substr> name-glob subset (uses --project/env)\n' +
7783
+ ' testsprite test run --all --wait --report junit --report-file ./results.xml\n' +
7784
+ ' project id precedence: --project wins over TESTSPRITE_PROJECT_ID\n' +
6577
7785
  '\nBE tests can declare --produces/--needs at create time to drive wave ordering\n' +
6578
7786
  '(see `testsprite test create --help` for details).\n' +
6579
7787
  '\nFrontend tests: the current unified engine runs FE tests too (they are billed\n' +
@@ -6587,13 +7795,13 @@ export function createTestCommand(deps = {}) {
6587
7795
  throw localValidationError('test-id', 'positional <test-id> and --all are mutually exclusive; use one or the other');
6588
7796
  }
6589
7797
  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');
7798
+ throw localValidationError('test-id', 'provide a <test-id>, or use --all with --project <id> or TESTSPRITE_PROJECT_ID');
6591
7799
  }
6592
7800
  // --filter is an --all-only narrowing flag (mirrors `test rerun --filter`).
6593
7801
  // Without --all it would be SILENTLY ignored while the explicit <test-id>
6594
7802
  // still runs — defeating the caller's narrowing intent. Reject early.
6595
7803
  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>.');
7804
+ 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
7805
  }
6598
7806
  const report = parseJUnitReportFormat(cmdOpts.report);
6599
7807
  assertJUnitReportOptions({
@@ -6603,23 +7811,33 @@ export function createTestCommand(deps = {}) {
6603
7811
  wait: cmdOpts.wait === true,
6604
7812
  batchPath: isAll,
6605
7813
  });
7814
+ // --gh-output / --summary-file reduce a --wait run's terminal result into
7815
+ // the CI summary. They require --wait (without it the command returns after
7816
+ // enqueueing, before any terminal result exists) but apply to BOTH a single
7817
+ // <test-id> run and the --all batch. Without --wait they would silently
7818
+ // no-op — reject loudly (same rule as --filter and the JUnit report flags).
7819
+ if (cmdOpts.ghOutput === true && cmdOpts.wait !== true) {
7820
+ throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
7821
+ }
7822
+ if (cmdOpts.summaryFile !== undefined && cmdOpts.wait !== true) {
7823
+ throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
7824
+ }
6606
7825
  if (isAll) {
6607
7826
  // --all path: wave-ordered fresh batch run.
6608
- if (!cmdOpts.project) {
6609
- throw localValidationError('project', '--all requires a project id — pass --project <id>');
6610
- }
7827
+ const projectId = resolveProjectId(cmdOpts.project, deps);
7828
+ requireProjectId(projectId, '--all requires a project id - pass --project <id> or set TESTSPRITE_PROJECT_ID');
6611
7829
  // --target-url has no effect on the --all batch path: a BE test's base
6612
7830
  // URL is baked into its code, and the unified engine resolves each
6613
7831
  // project's configured environment server-side (per-run URL overrides
6614
7832
  // 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.
7833
+ // run the suite against an unintended environment in the caller's mind,
7834
+ // so reject loudly.
6617
7835
  if (cmdOpts.targetUrl !== undefined && cmdOpts.targetUrl !== '') {
6618
7836
  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
7837
  }
6620
7838
  await runTestRunAll({
6621
7839
  ...resolveCommonOptions(command),
6622
- projectId: cmdOpts.project,
7840
+ projectId,
6623
7841
  nameFilter: cmdOpts.filter,
6624
7842
  wait: cmdOpts.wait === true,
6625
7843
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
@@ -6629,6 +7847,8 @@ export function createTestCommand(deps = {}) {
6629
7847
  report,
6630
7848
  reportFile: cmdOpts.reportFile,
6631
7849
  reportSuiteName: cmdOpts.reportSuiteName,
7850
+ ghOutput: cmdOpts.ghOutput === true,
7851
+ summaryFile: cmdOpts.summaryFile,
6632
7852
  }, deps);
6633
7853
  return;
6634
7854
  }
@@ -6642,6 +7862,8 @@ export function createTestCommand(deps = {}) {
6642
7862
  // B2(c): tell runTestRun whether --timeout was explicitly provided.
6643
7863
  timeoutIsDefault: cmdOpts.timeout === undefined,
6644
7864
  idempotencyKey: cmdOpts.idempotencyKey,
7865
+ ghOutput: cmdOpts.ghOutput === true,
7866
+ summaryFile: cmdOpts.summaryFile,
6645
7867
  }, deps);
6646
7868
  });
6647
7869
  test
@@ -6659,6 +7881,11 @@ export function createTestCommand(deps = {}) {
6659
7881
  ' is recorded as error:<CODE> in its row and folded into exit 7)\n' +
6660
7882
  ' 7 timeout or per-member poll error — resume with: testsprite test wait <run-id...>\n' +
6661
7883
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
7884
+ ' 11 rate limited, and nothing else went wrong — polls are retried\n' +
7885
+ ' automatically honoring Retry-After first, so this means the throttle\n' +
7886
+ ' outlasted that budget while the runs were still fine. Back off, then\n' +
7887
+ ' re-attach with test wait. (A throttle that instead consumes the whole\n' +
7888
+ ' --timeout reports 7, and any real timeout or failure keeps 7 / 1.)\n' +
6662
7889
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
6663
7890
  '\nCtrl-C detaches only (the run keeps executing and billing); stop it for\n' +
6664
7891
  'real with: testsprite test cancel <run-id...>')
@@ -6692,7 +7919,8 @@ export function createTestCommand(deps = {}) {
6692
7919
  // -------------------------------------------------------------------------
6693
7920
  test
6694
7921
  .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' +
7922
+ .description('Re-execute a test (or multiple) as a replay — FE replays the saved script, BE re-runs the dependency closure. ' +
7923
+ '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
7924
  '\nExit codes:\n' +
6697
7925
  ' 0 passed (or queued without --wait)\n' +
6698
7926
  ' 1 failed / blocked / cancelled\n' +
@@ -6720,6 +7948,8 @@ export function createTestCommand(deps = {}) {
6720
7948
  .option('--report <format>', 'with batch --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
6721
7949
  .option('--report-file <path>', 'output path for --report (atomic write)')
6722
7950
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
7951
+ .option('--gh-output', 'with batch --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')
7952
+ .option('--summary-file <path>', 'with batch --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
6723
7953
  .addHelpText('after', '\nNotes:\n' +
6724
7954
  ' • rerun replays a saved run/script and is MORE LENIENT than a fresh `test run`\n' +
6725
7955
  ' (auto-heal can pass steps that have drifted) — for strict scoring/regression,\n' +
@@ -6727,7 +7957,9 @@ export function createTestCommand(deps = {}) {
6727
7957
  ' • Under --wait the per-request HTTP timeout is auto-raised to cover --timeout so a\n' +
6728
7958
  ' slow trigger/poll under load is not cut at the 120s default (see --request-timeout).\n' +
6729
7959
  ' • 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).')
7960
+ ' and force a non-zero exit — they are NOT counted in `summary.total` (dispatched only).\n' +
7961
+ ' • On V3-routed accounts, --no-auto-heal is still rolling out and may not yet be\n' +
7962
+ ' honored server-side — check `auth status` for your routing.')
6731
7963
  .addHelpText('after', '\nDry-run shape notes:\n' +
6732
7964
  ' • --dry-run shows the BE rerun wire shape (includes `closure{}`); FE rerun responses\n' +
6733
7965
  ' omit `closure` (or return it as null) since there is no dependency expansion.\n' +
@@ -6749,6 +7981,15 @@ export function createTestCommand(deps = {}) {
6749
7981
  wait: cmdOpts.wait === true,
6750
7982
  batchPath: isBatch,
6751
7983
  });
7984
+ // --gh-output / --summary-file reduce the batch-rerun --wait envelope, which
7985
+ // only exists on the batch (--all or 2+ ids) --wait path. Anywhere else they
7986
+ // would silently no-op — reject loudly (same rule as the JUnit report flags).
7987
+ if (cmdOpts.ghOutput === true && (!isBatch || cmdOpts.wait !== true)) {
7988
+ throw localValidationError('gh-output', '--gh-output requires a batch rerun with --wait (--all or 2+ test ids). Remove --gh-output, or add --all --wait.');
7989
+ }
7990
+ if (cmdOpts.summaryFile !== undefined && (!isBatch || cmdOpts.wait !== true)) {
7991
+ throw localValidationError('summary-file', '--summary-file requires a batch rerun with --wait (--all or 2+ test ids). Remove --summary-file, or add --all --wait.');
7992
+ }
6752
7993
  await runTestRerun({
6753
7994
  ...resolveCommonOptions(command),
6754
7995
  testIds,
@@ -6768,6 +8009,8 @@ export function createTestCommand(deps = {}) {
6768
8009
  report,
6769
8010
  reportFile: cmdOpts.reportFile,
6770
8011
  reportSuiteName: cmdOpts.reportSuiteName,
8012
+ ghOutput: cmdOpts.ghOutput === true,
8013
+ summaryFile: cmdOpts.summaryFile,
6771
8014
  }, deps);
6772
8015
  });
6773
8016
  // -------------------------------------------------------------------------
@@ -6787,8 +8030,11 @@ export function createTestCommand(deps = {}) {
6787
8030
  .option('--until-fail', 'stop at the first non-passing attempt (fast "is it flaky at all?" check)', false)
6788
8031
  .option('--timeout <s>', `per-attempt max seconds to wait (1-${MAX_RUN_TIMEOUT_SECONDS}, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
6789
8032
  .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' +
8033
+ ' • Each replay is billed as a rerun — 0.5 credits for a frontend replay (verbatim\n' +
8034
+ ' script), 0.2 credits for a backend replay (re-runs the dependency closure) —\n' +
8035
+ ' same price as a fresh run, so `--runs N` costs roughly N×0.5 credits for a\n' +
8036
+ ' frontend test (legacy V2 accounts: FE rerun remains free). A one-line advisory\n' +
8037
+ ' is printed before a backend replay.\n' +
6792
8038
  ' • Replays use auto-heal OFF so a flaky test is not silently "healed" into a pass;\n' +
6793
8039
  ' this measures replay stability of the saved script against the configured URL.\n' +
6794
8040
  ' • `--output json` emits a machine-readable stability report for CI gating.')
@@ -6812,17 +8058,30 @@ export function createTestCommand(deps = {}) {
6812
8058
  // ---------------------------------------------------------------------------
6813
8059
  // `test flaky` — repeat-run flaky-test detector
6814
8060
  // ---------------------------------------------------------------------------
6815
- /** Upper bound on `--runs` so a repeat-runner can't amplify free FE replays. */
8061
+ /** Upper bound on `--runs` so a repeat-runner can't rack up unbounded rerun charges. */
6816
8062
  const MAX_FLAKY_RUNS = 10;
6817
8063
  /** Default replay count when `--runs` is omitted. */
6818
8064
  const DEFAULT_FLAKY_RUNS = 5;
8065
+ function isFlakyFatalTriggerError(err) {
8066
+ if (!(err instanceof ApiError))
8067
+ return false;
8068
+ switch (err.code) {
8069
+ case 'AUTH_REQUIRED':
8070
+ case 'AUTH_INVALID':
8071
+ case 'AUTH_FORBIDDEN':
8072
+ return true;
8073
+ default:
8074
+ return false;
8075
+ }
8076
+ }
6819
8077
  /**
6820
8078
  * `test flaky <test-id>` — replay a test N times and report a stability score.
6821
8079
  *
6822
8080
  * 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
8081
+ * verbatim replay) followed by `pollRunUntilTerminal`. Each replay is billed
8082
+ * as a rerun (0.5 credits FE / 0.2 credits BE, same as a fresh run; legacy V2
8083
+ * accounts: FE rerun remains free) — a one-line credit advisory is printed
8084
+ * for backend tests. The pure scoring lives in
6826
8085
  * `lib/flaky.ts`; this function is the I/O orchestrator.
6827
8086
  *
6828
8087
  * Exit code: 0 when every observed attempt passed (stable), else 1 — so CI can
@@ -6865,17 +8124,25 @@ export async function runFlaky(opts, deps = {}) {
6865
8124
  }
6866
8125
  if (isBackend) {
6867
8126
  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.`);
8127
+ `and is billed at 0.2 credits per rerun, same as a fresh run (frontend reruns are 0.5 credits).`);
6869
8128
  }
6870
8129
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
6871
8130
  const attempts = [];
8131
+ // Collected across attempts and deduped — same request shape every
8132
+ // attempt, so the server would otherwise repeat the identical advisory once
8133
+ // per replay. Surfaced ONCE in the final report/summary, not N times.
8134
+ let advisories = [];
6872
8135
  for (let i = 1; i <= opts.runs; i++) {
6873
8136
  const idempotencyKey = `cli-flaky-${randomUUID()}`;
6874
8137
  let rerunResp;
6875
8138
  try {
6876
8139
  // 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 });
8140
+ // replay so healed drift cannot mask a nondeterministic pass/fail. Sent
8141
+ // explicitly (not omitted) — an absent field defaults to heal-on server-side.
8142
+ rerunResp = await client.triggerRerun(opts.testId, { source: 'cli', autoHeal: false }, { idempotencyKey });
8143
+ if (rerunResp.advisories && rerunResp.advisories.length > 0) {
8144
+ advisories = dedupeRerunAdvisories(advisories.concat(rerunResp.advisories));
8145
+ }
6879
8146
  }
6880
8147
  catch (err) {
6881
8148
  // A missing replayable run is fatal for the whole command (mirror rerun):
@@ -6891,6 +8158,9 @@ export async function runFlaky(opts, deps = {}) {
6891
8158
  },
6892
8159
  });
6893
8160
  }
8161
+ if (isFlakyFatalTriggerError(err)) {
8162
+ throw err;
8163
+ }
6894
8164
  // Any other trigger error is recorded as an errored attempt so a single
6895
8165
  // transient blip doesn't abort a long stability probe.
6896
8166
  const code = err instanceof ApiError ? err.code : 'ERROR';
@@ -6929,6 +8199,16 @@ export async function runFlaky(opts, deps = {}) {
6929
8199
  stderrFn(interruptDetachMessage(err, [runId]));
6930
8200
  throw err;
6931
8201
  }
8202
+ // RATE_LIMITED during polling (same defect class as the InterruptError
8203
+ // branch above): the HTTP layer already retried and gave up, but this
8204
+ // attempt's run keeps executing (and billing) server-side. Name it on
8205
+ // stderr before rethrowing so the runId is never silently dropped;
8206
+ // rethrow the SAME ApiError unchanged so its exit code (11) is kept.
8207
+ if (err instanceof ApiError && err.code === 'RATE_LIMITED') {
8208
+ ticker.finalize(`Attempt ${i}/${opts.runs} — rate limited by the server`);
8209
+ stderrFn(rateLimitedDetachMessage(err, [runId]));
8210
+ throw err;
8211
+ }
6932
8212
  // A per-attempt deadline (poll TimeoutError) or a client-side request
6933
8213
  // timeout both count as a non-passing "timeout" outcome for this attempt.
6934
8214
  if (err instanceof TimeoutError || err instanceof RequestTimeoutError) {
@@ -6945,7 +8225,10 @@ export async function runFlaky(opts, deps = {}) {
6945
8225
  break;
6946
8226
  }
6947
8227
  ticker.finalize();
6948
- const report = summarizeFlaky(opts.testId, attempts);
8228
+ // Print the deduped advisory set once for the whole probe, not
8229
+ // once per replay attempt (mirrors the `test rerun` advisory rendering).
8230
+ emitRerunAdvisories(stderrFn, advisories);
8231
+ const report = summarizeFlaky(opts.testId, attempts, advisories);
6949
8232
  out.print(report, data => renderFlakyText(data));
6950
8233
  const exitCode = flakyExitCode(report);
6951
8234
  if (exitCode !== 0) {
@@ -6953,9 +8236,17 @@ export async function runFlaky(opts, deps = {}) {
6953
8236
  }
6954
8237
  return report;
6955
8238
  }
6956
- function requireProjectId(projectId) {
8239
+ function resolveProjectId(projectId, deps) {
8240
+ const explicit = projectId?.trim();
8241
+ if (explicit && explicit.length > 0)
8242
+ return explicit;
8243
+ const envValue = (deps.env ?? process.env).TESTSPRITE_PROJECT_ID;
8244
+ const trimmed = envValue?.trim();
8245
+ return trimmed && trimmed.length > 0 ? trimmed : undefined;
8246
+ }
8247
+ function requireProjectId(projectId, message = 'is required; pass --project <id> or set TESTSPRITE_PROJECT_ID') {
6957
8248
  if (typeof projectId !== 'string' || projectId.length === 0) {
6958
- throw localValidationError('project', 'is required');
8249
+ throw localValidationError('project', message);
6959
8250
  }
6960
8251
  }
6961
8252
  /**
@@ -7255,38 +8546,32 @@ async function streamPresignedBody(url, out, deps) {
7255
8546
  throw new TransportError(`Failed mid-download of presigned code body: ${message}`);
7256
8547
  }
7257
8548
  }
7258
- function renderTestListText(page) {
8549
+ const TEST_LIST_COLUMNS = [
8550
+ {
8551
+ header: 'ID',
8552
+ width: rows => Math.max(2, ...rows.map(test => test.id.length)),
8553
+ render: test => test.id,
8554
+ },
8555
+ {
8556
+ header: 'NAME',
8557
+ width: rows => Math.max(4, ...rows.map(test => test.name.length)),
8558
+ render: test => test.name,
8559
+ },
8560
+ { header: 'TYPE', width: 8, render: test => test.type },
8561
+ { header: 'FROM', width: 6, render: test => test.createdFrom },
8562
+ { header: 'STATUS', width: 9, render: test => test.status },
8563
+ { header: 'UPDATED', width: 0, render: test => test.updatedAt },
8564
+ ];
8565
+ function renderTestListText(page, options = {}) {
7259
8566
  if (page.items.length === 0) {
7260
8567
  return page.nextToken ? `No tests on this page.\nnextToken: ${page.nextToken}` : 'No tests.';
7261
8568
  }
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];
8569
+ const lines = [
8570
+ renderTextTable(page.items, TEST_LIST_COLUMNS, {
8571
+ columns: options.columns,
8572
+ noHeader: options.noHeader,
8573
+ }),
8574
+ ];
7290
8575
  if (page.nextToken)
7291
8576
  lines.push('', `nextToken: ${page.nextToken}`);
7292
8577
  return lines.join('\n');
@@ -7485,7 +8770,7 @@ function plannedBundleFiles(ctx, failedOnly) {
7485
8770
  files.push('failure.json');
7486
8771
  files.push(`code.${pickCodeExtension(ctx.code.language, ctx.code.framework)}`);
7487
8772
  if (ctx.result.videoUrl)
7488
- files.push('video.mp4');
8773
+ files.push(`video.${pickVideoExtension(ctx.result.videoUrl)}`);
7489
8774
  const stepsToInclude = failedOnly
7490
8775
  ? ctx.steps.filter(s => {
7491
8776
  if (ctx.result.failedStepIndex === null)