@testsprite/testsprite-cli 0.5.0 → 0.7.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 (51) hide show
  1. package/README.md +39 -30
  2. package/dist/commands/agent.js +44 -42
  3. package/dist/commands/doctor.d.ts +1 -1
  4. package/dist/commands/doctor.js +4 -7
  5. package/dist/commands/project.js +3 -2
  6. package/dist/commands/schedule.d.ts +120 -0
  7. package/dist/commands/schedule.js +487 -0
  8. package/dist/commands/test.d.ts +55 -1
  9. package/dist/commands/test.js +714 -183
  10. package/dist/commands/testlist.d.ts +88 -0
  11. package/dist/commands/testlist.js +747 -0
  12. package/dist/index.js +6 -2
  13. package/dist/lib/agent-targets.d.ts +13 -4
  14. package/dist/lib/agent-targets.js +11 -2
  15. package/dist/lib/conflict-reason.d.ts +30 -0
  16. package/dist/lib/conflict-reason.js +45 -0
  17. package/dist/lib/credentials.js +42 -1
  18. package/dist/lib/cron.d.ts +40 -0
  19. package/dist/lib/cron.js +190 -0
  20. package/dist/lib/dry-run/samples.js +177 -55
  21. package/dist/lib/errors.d.ts +9 -0
  22. package/dist/lib/errors.js +11 -0
  23. package/dist/lib/gh-output.d.ts +51 -4
  24. package/dist/lib/gh-output.js +149 -19
  25. package/dist/lib/http.d.ts +25 -0
  26. package/dist/lib/http.js +201 -3
  27. package/dist/lib/junit-report.d.ts +20 -2
  28. package/dist/lib/junit-report.js +38 -5
  29. package/dist/lib/poll.js +72 -36
  30. package/dist/lib/proxy.d.ts +16 -0
  31. package/dist/lib/proxy.js +19 -1
  32. package/dist/lib/response-schemas.d.ts +7 -0
  33. package/dist/lib/response-schemas.js +46 -14
  34. package/dist/lib/runs.types.d.ts +8 -3
  35. package/dist/lib/secret-file.d.ts +15 -0
  36. package/dist/lib/secret-file.js +82 -0
  37. package/dist/lib/target-url-preflight.d.ts +91 -0
  38. package/dist/lib/target-url-preflight.js +259 -0
  39. package/dist/lib/target-url.d.ts +22 -5
  40. package/dist/lib/target-url.js +60 -28
  41. package/dist/lib/testlist.types.d.ts +77 -0
  42. package/dist/lib/testlist.types.js +9 -0
  43. package/dist/lib/v3-advisory.d.ts +37 -4
  44. package/dist/lib/v3-advisory.js +47 -4
  45. package/dist/lib/wait-exit.d.ts +29 -0
  46. package/dist/lib/wait-exit.js +103 -0
  47. package/dist/version-guard.d.ts +10 -7
  48. package/dist/version-guard.js +37 -9
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +2 -1
@@ -1,4 +1,4 @@
1
- import { appendFileSync, createWriteStream, existsSync, readFileSync, readdirSync, statSync, writeFileSync, } from 'node:fs';
1
+ import { createWriteStream, existsSync, readFileSync, readdirSync, statSync, } from 'node:fs';
2
2
  import { rename, stat, unlink } from 'node:fs/promises';
3
3
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
@@ -7,8 +7,8 @@ import { openInBrowser } from '../lib/browser.js';
7
7
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
8
8
  import { assertContextIntegrity, buildMeta, pickCodeExtension, pickVideoExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
9
9
  import { findSample, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
10
- import { assertJUnitReportOptions, buildJUnitReport, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
11
- import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
10
+ import { assertJUnitReportOptions, buildJUnitReport, durationSecondsBetween, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
11
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, isAuthCode, localValidationError, } from '../lib/errors.js';
12
12
  import { globalShutdown } from '../lib/interrupt.js';
13
13
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
14
14
  import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.js';
@@ -16,13 +16,18 @@ import { VERSION } from '../version.js';
16
16
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
17
17
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
18
18
  import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
19
+ import { resolveWaitFailure } from '../lib/wait-exit.js';
19
20
  import { RUN_SOURCES } from '../lib/runs.types.js';
21
+ import { summarizeConflicts } from '../lib/conflict-reason.js';
22
+ import { isProxyAgentActive } from '../lib/proxy.js';
20
23
  import { assertNotLocal } from '../lib/target-url.js';
24
+ import { assertTargetUrlReachable } from '../lib/target-url-preflight.js';
21
25
  import { formatTextTableRow, measureTextColumns, renderTextTable, resolveTextColumns, } from '../lib/text-table.js';
22
26
  import { createTicker } from '../lib/ticker.js';
23
27
  import { RateThrottle } from '../lib/rate-throttle.js';
24
28
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
25
- import { emitGithubOutputs, summarizeAcceptedPayload } from '../lib/gh-output.js';
29
+ import { emitTargetUrlMismatchAdvisory } from '../lib/v3-advisory.js';
30
+ import { emitCiArtifacts, summarizeAcceptedPayload, summarizeSingleRun } from '../lib/gh-output.js';
26
31
  import { loadConfig } from '../lib/config.js';
27
32
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
28
33
  /** The effective shutdown handle for a command invocation (DEV-331). */
@@ -64,6 +69,25 @@ function rateLimitedDetachMessage(err, runIds) {
64
69
  ` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
65
70
  ` Cancel with: testsprite test cancel ${runIds.join(' ')}`);
66
71
  }
72
+ /**
73
+ * The same honest "keeps running (and billing)" subject sentence
74
+ * `interruptDetachMessage`/`rateLimitedDetachMessage` already use, for the
75
+ * two detach paths that build their own text inline instead of going
76
+ * through one of those two helpers: a plain `--timeout` expiry
77
+ * (`TimeoutError`) and a client-side `RequestTimeoutError`. Both used to
78
+ * omit "(and billing)" — the honesty gap this closes — even though a
79
+ * `--timeout` expiry is the single most common of the four detach reasons
80
+ * in practice. Kept as a standalone string helper (not a shared code path
81
+ * for all four branches) deliberately: the four branches differ in how
82
+ * they render the partial envelope and in their exit code, and unifying
83
+ * that shape is out of scope here — see the PR notes.
84
+ */
85
+ function stillRunningAndBillingSubject(runIds) {
86
+ const ids = Array.isArray(runIds) ? runIds : [runIds];
87
+ return ids.length === 1
88
+ ? `Run ${ids[0]} is still executing on the server and will keep running (and billing) until it finishes.`
89
+ : `${ids.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
90
+ }
67
91
  const TEST_TYPES = ['frontend', 'backend'];
68
92
  // 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
69
93
  // tests created via `testsprite test create`, so the `--created-from cli`
@@ -198,13 +222,24 @@ async function emitDupNameAdvisoryIfNeeded(client, projectId, name, stderrFn) {
198
222
  // Use an AbortController with a 5 s deadline. When the timer fires it
199
223
  // calls ac.abort(), which causes client.get (via the `signal` option) to
200
224
  // throw an AbortError — caught below and swallowed. This ensures a stalled
201
- // or retrying listing endpoint can't delay an otherwise-healthy create by
202
- // the full request-timeout (120 s) or multiple transport retries.
225
+ // listing endpoint can't delay an otherwise-healthy create by the full
226
+ // request-timeout (120 s).
203
227
  // No secondary setTimeout is used to avoid leaking timers in tests.
228
+ //
229
+ // The deadline alone is NOT sufficient, because `signal` is composed into
230
+ // the fetch only — `sleepBeforeRetry` observes the process-lifetime
231
+ // shutdown signal and nothing else, so a retry sleep runs to completion
232
+ // no matter what this controller does. A 429 carrying `Retry-After` is
233
+ // honoured up to 60 s per attempt across 3 attempts, which would park the
234
+ // create behind a best-effort advisory for up to ~2 minutes. `429` is a
235
+ // live response for CLI callers (the in-flight run cap returns it), so
236
+ // this is reachable, not theoretical. `retryOnRateLimit: false` makes the
237
+ // 429 throw straight into the catch below, which is the correct outcome
238
+ // for a lookup whose entire purpose is to be skippable.
204
239
  const ac = new AbortController();
205
240
  const timer = setTimeout(() => ac.abort(), DUP_NAME_ADVISORY_TIMEOUT_MS);
206
241
  try {
207
- const listing = await client.get(`/tests?projectId=${encodeURIComponent(projectId)}&pageSize=100`, { signal: ac.signal });
242
+ const listing = await client.get(`/tests?projectId=${encodeURIComponent(projectId)}&pageSize=100`, { signal: ac.signal, retryOnRateLimit: false });
208
243
  const nameLower = name.toLowerCase();
209
244
  const match = listing.items?.find(t => t.name.toLowerCase() === nameLower);
210
245
  if (match) {
@@ -357,6 +392,23 @@ export async function runCreate(opts, deps = {}) {
357
392
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
358
393
  stderrFn("[advisory] --target-url has no effect for backend tests (a backend test's base URL is defined inside its code).");
359
394
  }
395
+ // Pre-charge reachability preflight — deliberately BEFORE the
396
+ // create POST below (not after), so a doomed --target-url refuses before
397
+ // this leaves behind a created-but-never-run orphan test row (the same
398
+ // "fail before I/O" idiom `assertChainedRunKeyFits` above already applies
399
+ // to the run idempotency key). Only meaningful when it will actually
400
+ // reach a trigger: skipped for a known-backend test (the advisory just
401
+ // above already covers why --target-url is inert there) and skipped
402
+ // entirely under --dry-run (zero network calls). The delegated
403
+ // `runTestRun` call in the --run chain below sets `skipPreflight: true`
404
+ // so this exact URL is never probed twice.
405
+ if (opts.type !== 'backend' &&
406
+ opts.targetUrl !== undefined &&
407
+ opts.run === true &&
408
+ !opts.dryRun) {
409
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
410
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
411
+ }
360
412
  const client = makeClient(opts, deps);
361
413
  const out = makeOutput(opts.output, deps);
362
414
  // B3: best-effort duplicate-name advisory. Skip under --dry-run.
@@ -382,10 +434,32 @@ export async function runCreate(opts, deps = {}) {
382
434
  // the merged { ...createContext, run } envelope in JSON mode and
383
435
  // appears on the Dashboard: stderr line in text mode.
384
436
  // R1: suppress under --dry-run (fake canned test id).
385
- const chainDashboardUrl = opts.dryRun
437
+ // DEV-737: prefer a server-provided dashboardUrl over the client guess
438
+ // (`withDashboardUrl`/`resolveDashboardUrl` above); when the server
439
+ // explicitly withheld one, never fall back to the client-computed
440
+ // V2-shaped link and tell the caller where to find the test instead.
441
+ const { entity: createContextWithUrl, suppressed: dashboardSuppressedOnRun } = withDashboardUrl(response, () => opts.dryRun
386
442
  ? undefined
387
- : resolvePortalUrl(resolveApiUrl(opts, deps), projectId, response.testId);
388
- const createContextWithUrl = chainDashboardUrl !== undefined ? { ...response, dashboardUrl: chainDashboardUrl } : response;
443
+ : resolvePortalUrl(resolveApiUrl(opts, deps), projectId, response.testId));
444
+ const runDashboardStderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
445
+ if (dashboardSuppressedOnRun) {
446
+ emitDashboardLinkSuppressedAdvisory(response.testId, runDashboardStderrFn);
447
+ }
448
+ else if (opts.output !== 'json' && createContextWithUrl.dashboardUrl !== undefined) {
449
+ // Finding 3 (dogfood 2026-08-09): the merged create+run chain suppresses
450
+ // the create's own print (delegating to `runTestRun` -> `printRunOrChain`),
451
+ // whose text-mode header renders `createContext` via `renderCreateText` —
452
+ // which never prints `dashboardUrl` — and there is otherwise no stderr
453
+ // emission point for it on this chain (unlike the non-`--run` path below,
454
+ // which prints this same line explicitly). Without this, a text-mode
455
+ // `create --run` silently drops the authoritative link — worst on a
456
+ // no-wait V3 create, where the client cannot recompute it at all. Mirrors
457
+ // the non-run path's three-state handling exactly: a suppressed (`null`)
458
+ // server link takes the advisory branch above instead (no legacy guess);
459
+ // an absent key already resolved to the legacy client fallback (or
460
+ // `undefined` when unmapped) via `createContextWithUrl` above.
461
+ runDashboardStderrFn(`Dashboard: ${createContextWithUrl.dashboardUrl}`);
462
+ }
389
463
  await runTestRun({
390
464
  ...opts,
391
465
  testId: response.testId,
@@ -400,6 +474,10 @@ export async function runCreate(opts, deps = {}) {
400
474
  // Thread the known type so fast BE runs (terminal on first poll, where
401
475
  // beFallbackUsed would be false) still render `steps: n/a (backend)`.
402
476
  type: opts.type,
477
+ // The preflight above (or its explicit --skip-preflight opt-out)
478
+ // already ran against this exact URL before the create POST — never
479
+ // probe it a second time here.
480
+ skipPreflight: true,
403
481
  }, deps);
404
482
  return response;
405
483
  }
@@ -407,11 +485,16 @@ export async function runCreate(opts, deps = {}) {
407
485
  // (no extra network call — both come from opts / response).
408
486
  // R1: suppress under --dry-run — the test id is a fake canned value
409
487
  // (e.g. "test_dryrun_create_2026") and a live-looking URL would mislead.
410
- const dashboardUrl = opts.dryRun
488
+ // DEV-737: prefer a server-provided dashboardUrl over the client guess;
489
+ // never fall back when the server explicitly withheld one (see
490
+ // `withDashboardUrl`/`resolveDashboardUrl` above), and tell the caller
491
+ // where to find the test instead of printing a link that would 404.
492
+ const { entity: responseWithDashboardUrl, suppressed: dashboardSuppressed } = withDashboardUrl(response, () => opts.dryRun
411
493
  ? undefined
412
- : resolvePortalUrl(resolveApiUrl(opts, deps), projectId, response.testId);
494
+ : resolvePortalUrl(resolveApiUrl(opts, deps), projectId, response.testId));
495
+ const dashboardUrl = responseWithDashboardUrl.dashboardUrl ?? undefined;
413
496
  if (opts.output === 'json') {
414
- out.print(dashboardUrl !== undefined ? { ...response, dashboardUrl } : response, data => renderCreateText(data));
497
+ out.print(responseWithDashboardUrl, data => renderCreateText(data));
415
498
  }
416
499
  else {
417
500
  out.print(response, data => renderCreateText(data));
@@ -420,6 +503,9 @@ export async function runCreate(opts, deps = {}) {
420
503
  stderrFn(`Dashboard: ${dashboardUrl}`);
421
504
  }
422
505
  }
506
+ if (dashboardSuppressed) {
507
+ emitDashboardLinkSuppressedAdvisory(response.testId, deps.stderr ?? (line => process.stderr.write(`${line}\n`)));
508
+ }
423
509
  return response;
424
510
  }
425
511
  /**
@@ -1478,6 +1564,15 @@ export async function runCreateFromPlan(opts, deps = {}) {
1478
1564
  priority: plan.priority,
1479
1565
  planSteps: plan.planSteps,
1480
1566
  };
1567
+ // Pre-charge reachability preflight — before the create POST
1568
+ // (same "fail before I/O, not after an orphan row" placement as
1569
+ // runCreate). `plan.type` is unconditionally 'frontend' here (backend
1570
+ // plans already threw above), so no type gate is needed. The delegated
1571
+ // `runTestRun` call in the --run chain below sets `skipPreflight: true`
1572
+ // so this exact URL is never probed twice.
1573
+ if (opts.targetUrl !== undefined && opts.run === true && !opts.dryRun) {
1574
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
1575
+ }
1481
1576
  const client = makeClient(opts, deps);
1482
1577
  const out = makeOutput(opts.output, deps);
1483
1578
  // Fix 4: best-effort duplicate-name advisory — same semantics as runCreate.
@@ -1493,9 +1588,14 @@ export async function runCreateFromPlan(opts, deps = {}) {
1493
1588
  // Fix 5 (plan-from coverage): the projectId for the deep-link comes from
1494
1589
  // the validated PLAN body (not opts — `--plan-from` has no --project-id
1495
1590
  // flag). Same dry-run suppression as runCreate (fake canned test id).
1496
- const planDashboardUrl = opts.dryRun
1591
+ // DEV-737: prefer a server-provided dashboardUrl over the client guess
1592
+ // (`withDashboardUrl`/`resolveDashboardUrl`, defined near
1593
+ // `withRunDashboardUrl`); never fall back when the server explicitly
1594
+ // withheld one, and tell the caller where to find the test instead.
1595
+ const { entity: responseWithDashboardUrl, suppressed: planDashboardSuppressed } = withDashboardUrl(response, () => opts.dryRun
1497
1596
  ? undefined
1498
- : resolvePortalUrl(resolveApiUrl(opts, deps), plan.projectId, response.testId);
1597
+ : resolvePortalUrl(resolveApiUrl(opts, deps), plan.projectId, response.testId));
1598
+ const planDashboardUrl = responseWithDashboardUrl.dashboardUrl ?? undefined;
1499
1599
  // --run chain (M3.3 piece-3): trigger + optionally wait. Per codex
1500
1600
  // round-1 P1: suppress the create's own print when chaining;
1501
1601
  // `runTestRun` emits a single merged envelope on stdout.
@@ -1503,7 +1603,9 @@ export async function runCreateFromPlan(opts, deps = {}) {
1503
1603
  // Idempotency key for the run is the create key + ":run" suffix so a
1504
1604
  // retry of the whole chain gets the same runId. Per piece-3 spec.
1505
1605
  const runIdempotencyKey = `${idempotencyKey}:run`;
1506
- const createContextWithUrl = planDashboardUrl !== undefined ? { ...response, dashboardUrl: planDashboardUrl } : response;
1606
+ if (planDashboardSuppressed) {
1607
+ emitDashboardLinkSuppressedAdvisory(response.testId, stderrFn);
1608
+ }
1507
1609
  return runTestRun({
1508
1610
  ...opts,
1509
1611
  testId: response.testId,
@@ -1513,11 +1615,14 @@ export async function runCreateFromPlan(opts, deps = {}) {
1513
1615
  // first-run hint fires for `test create --plan-from --run --wait`.
1514
1616
  timeoutIsDefault: opts.timeoutIsDefault ?? false,
1515
1617
  wait: opts.wait === true,
1516
- createContext: createContextWithUrl,
1618
+ createContext: responseWithDashboardUrl,
1619
+ // Already preflighted above (or explicitly skipped) — don't probe
1620
+ // the same URL twice.
1621
+ skipPreflight: true,
1517
1622
  }, deps).then(() => response);
1518
1623
  }
1519
1624
  if (opts.output === 'json') {
1520
- out.print(planDashboardUrl !== undefined ? { ...response, dashboardUrl: planDashboardUrl } : response, data => renderCreateText(data));
1625
+ out.print(responseWithDashboardUrl, data => renderCreateText(data));
1521
1626
  }
1522
1627
  else {
1523
1628
  out.print(response, data => renderCreateText(data));
@@ -1525,6 +1630,9 @@ export async function runCreateFromPlan(opts, deps = {}) {
1525
1630
  stderrFn(`Dashboard: ${planDashboardUrl}`);
1526
1631
  }
1527
1632
  }
1633
+ if (planDashboardSuppressed) {
1634
+ emitDashboardLinkSuppressedAdvisory(response.testId, stderrFn);
1635
+ }
1528
1636
  return response;
1529
1637
  }
1530
1638
  /**
@@ -1904,24 +2012,65 @@ export async function runCreateBatch(opts, deps = {}) {
1904
2012
  },
1905
2013
  });
1906
2014
  }
1907
- // Fix 5: enrich results with per-item dashboardUrl in JSON mode.
2015
+ // Fix 5: enrich results with per-item dashboardUrl.
1908
2016
  // projectId comes from specs[specIndex].projectId; testId from the result row.
1909
2017
  // Only emitted where both are known client-side — no extra network calls.
1910
2018
  // R1: suppress under --dry-run — test ids are fake canned values and a
1911
2019
  // live-looking URL would mislead the caller.
2020
+ // DEV-737: prefer a server-provided per-item dashboardUrl over the client
2021
+ // guess (`withDashboardUrl`/`resolveDashboardUrl`, defined near
2022
+ // `withRunDashboardUrl`); never fall back when the server explicitly
2023
+ // withheld one for a given item — that would print exactly the dead
2024
+ // V2-shaped link the server declined to emit.
2025
+ //
2026
+ // The per-item decision is captured into `testIdToDashboardState` — computed
2027
+ // ONCE here, regardless of `--output` mode — so the `--run` fan-out below
2028
+ // (`runBatchRun`) can reuse the SAME decision instead of recomputing a
2029
+ // client-side URL from testId→projectId, which would silently replace a
2030
+ // server-provided V3 link with the dead legacy V2 guess and lose
2031
+ // suppression state entirely. Computing it unconditionally (not gated on
2032
+ // `opts.output === 'json'`) also means the aggregate suppression advisory
2033
+ // below now correctly fires in text mode too — it previously only ever
2034
+ // fired in JSON mode because the per-item loop was skipped entirely in text
2035
+ // mode, silently under-warning a text-mode caller. That matches the
2036
+ // documented "advisory fires on stderr regardless of --output mode"
2037
+ // convention this repo already follows for the single-`test create` advisory.
1912
2038
  const apiUrlForDashboard = resolveApiUrl(opts, deps);
2039
+ let anyDashboardSuppressed = false;
2040
+ const testIdToDashboardState = new Map();
2041
+ if (!opts.dryRun) {
2042
+ for (const r of response.results) {
2043
+ if (r.status !== 'created' || r.testId === undefined)
2044
+ continue;
2045
+ const testId = r.testId;
2046
+ const spec = specs[r.specIndex];
2047
+ const projectId = spec?.projectId;
2048
+ const { entity, suppressed } = withDashboardUrl(r, () => projectId ? resolvePortalUrl(apiUrlForDashboard, projectId, testId) : undefined);
2049
+ if (suppressed)
2050
+ anyDashboardSuppressed = true;
2051
+ testIdToDashboardState.set(testId, {
2052
+ dashboardUrl: entity.dashboardUrl ?? undefined,
2053
+ suppressed,
2054
+ });
2055
+ }
2056
+ }
2057
+ if (anyDashboardSuppressed) {
2058
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2059
+ stderrFn('[advisory] no dashboard link is available for one or more created tests right now; ' +
2060
+ 'use `testsprite test get <test-id>` to look them up.');
2061
+ }
2062
+ // JSON-mode create output is enriched from the same map, so it stays
2063
+ // byte-identical to before this refactor.
1913
2064
  const enrichedResponse = !opts.dryRun && opts.output === 'json'
1914
2065
  ? {
1915
2066
  ...response,
1916
2067
  results: response.results.map(r => {
1917
2068
  if (r.status !== 'created' || r.testId === undefined)
1918
2069
  return r;
1919
- const spec = specs[r.specIndex];
1920
- const projectId = spec?.projectId;
1921
- if (!projectId)
2070
+ const state = testIdToDashboardState.get(r.testId);
2071
+ if (!state)
1922
2072
  return r;
1923
- const dashboardUrl = resolvePortalUrl(apiUrlForDashboard, projectId, r.testId);
1924
- return dashboardUrl !== undefined ? { ...r, dashboardUrl } : r;
2073
+ return { ...r, dashboardUrl: state.dashboardUrl };
1925
2074
  }),
1926
2075
  }
1927
2076
  : response;
@@ -1936,17 +2085,7 @@ export async function runCreateBatch(opts, deps = {}) {
1936
2085
  }
1937
2086
  // --run: fan out a trigger for each created test, then emit results.
1938
2087
  if (opts.run === true) {
1939
- // R3b: build testId → projectId map from the create results + specs so
1940
- // runBatchRun can enrich per-item run JSON with dashboardUrl.
1941
- const runTestIdToProjectId = new Map();
1942
- for (const r of response.results) {
1943
- if (r.status === 'created' && r.testId !== undefined) {
1944
- const projectId = specs[r.specIndex]?.projectId;
1945
- if (projectId)
1946
- runTestIdToProjectId.set(r.testId, projectId);
1947
- }
1948
- }
1949
- await runBatchRun(opts, response, client, out, deps, opts.dryRun ? undefined : runTestIdToProjectId, opts.dryRun ? undefined : apiUrlForDashboard);
2088
+ await runBatchRun(opts, response, client, out, deps, opts.dryRun ? undefined : testIdToDashboardState);
1950
2089
  // runBatchRun handles its own exit-code logic via CLIError.
1951
2090
  // Return the create response to satisfy the return type; callers that
1952
2091
  // inspect the return value only do so when not using --run.
@@ -1975,12 +2114,17 @@ export async function runCreateBatch(opts, deps = {}) {
1975
2114
  * that code only when ALL runs share the same code; otherwise 1.
1976
2115
  */
1977
2116
  async function runBatchRun(opts, createResponse, client, out, deps,
1978
- /** R3b: testId → projectId mapping built from create results + specs, used to enrich
1979
- * run-path JSON items with dashboardUrl. Populated by the caller; absent (undefined)
1980
- * means no enrichment (e.g. dry-run or caller didn't supply it). */
1981
- testIdToProjectId,
1982
- /** R3b: resolved API URL for portal link resolution. */
1983
- apiUrlForDashboard) {
2117
+ /**
2118
+ * R3b: per-testId dashboard-link decision, ALREADY resolved at create time
2119
+ * via `withDashboardUrl`/`resolveDashboardUrl` (the shared three-state
2120
+ * precedence helper — see its doc). Populated by the caller; absent
2121
+ * (undefined) means no enrichment (e.g. dry-run). Reusing this decision
2122
+ * — rather than recomputing a client-side URL from testId→projectId here
2123
+ * — is the fix: a fresh `resolvePortalUrl` call at this point would
2124
+ * silently replace a server-provided V3 link with the dead legacy V2
2125
+ * guess, and would have no way to know a link was explicitly suppressed.
2126
+ */
2127
+ testIdToDashboardState) {
1984
2128
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1985
2129
  const timeoutSeconds = opts.timeoutSeconds ?? DEFAULT_RUN_TIMEOUT_SECONDS;
1986
2130
  const concurrencyLimit = opts.maxConcurrency ?? DEFAULT_BATCH_RUN_CONCURRENCY;
@@ -2014,8 +2158,25 @@ apiUrlForDashboard) {
2014
2158
  out.print(envelope);
2015
2159
  return;
2016
2160
  }
2161
+ // Pre-charge reachability preflight, ONCE for the whole batch
2162
+ // before the fan-out — not once per item (mirrors the "fire once per
2163
+ // invocation" contract Finding 2 already established for the target-url
2164
+ // advisory below). Real path only (dry-run already returned above); no
2165
+ // type gate is needed here — batch specs are FE-only by construction (a
2166
+ // `type: "backend"` spec always fails create-time server validation, so
2167
+ // it never reaches this fan-out at all — see the `beIndexes` warning in
2168
+ // `runCreateBatch`).
2169
+ if (opts.targetUrl !== undefined) {
2170
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
2171
+ }
2017
2172
  const batchRunResults = [];
2018
2173
  const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
2174
+ // Response-driven --target-url advisory, fired at most ONCE for the whole
2175
+ // batch (Finding 2's contract) the first time any member's trigger
2176
+ // response reports a target different from what was requested — see the
2177
+ // matching comment in `runTestRun` for why this replaced the old
2178
+ // `v3Enabled`-assumption probe.
2179
+ let targetUrlAdvisoryPrinted = false;
2019
2180
  /**
2020
2181
  * Client-side sliding-window throttle: caps outgoing triggers at
2021
2182
  * BATCH_RUN_RATE_LIMIT (50) per BATCH_RUN_RATE_WINDOW_MS (60 s), sitting
@@ -2120,6 +2281,16 @@ apiUrlForDashboard) {
2120
2281
  // POSTs per spec (e.g. 50×3 = 150/min), blowing the server's 60/min cap.
2121
2282
  { idempotencyKey: runIdempotencyKey, retryOnRateLimit: false });
2122
2283
  triggerResponse = result.body;
2284
+ // Fire the response-driven mismatch advisory at most once for the
2285
+ // whole batch. Synchronous check-and-set (no `await` between the
2286
+ // two) so two members whose triggers resolve in the same tick
2287
+ // can't both slip past the flag and print twice.
2288
+ if (!targetUrlAdvisoryPrinted &&
2289
+ opts.targetUrl !== undefined &&
2290
+ triggerResponse.targetUrl !== opts.targetUrl) {
2291
+ targetUrlAdvisoryPrinted = true;
2292
+ emitTargetUrlMismatchAdvisory(stderrFn, opts.targetUrl, triggerResponse.targetUrl);
2293
+ }
2123
2294
  break; // success — exit the outer retry loop
2124
2295
  }
2125
2296
  catch (err) {
@@ -2413,16 +2584,19 @@ apiUrlForDashboard) {
2413
2584
  batchRunResults.sort((a, b) => testIds.indexOf(a.testId) - testIds.indexOf(b.testId));
2414
2585
  // Emit output.
2415
2586
  if (opts.output === 'json') {
2416
- // R3b: enrich per-item run results with dashboardUrl when both testId and
2417
- // projectId are known (from the testIdToProjectId map built by the caller).
2418
- // Additive-optional: items where projectId is unknown are left unchanged.
2419
- const enrichedResults = !opts.dryRun && testIdToProjectId !== undefined && apiUrlForDashboard !== undefined
2587
+ // R3b: enrich per-item run results with the dashboard state ALREADY
2588
+ // resolved at create time (`testIdToDashboardState`, built by the
2589
+ // caller). Never recompute a client-side URL here — that would silently
2590
+ // replace a server-provided V3 link with the dead legacy V2 guess, and
2591
+ // would have no way to represent "the server explicitly suppressed
2592
+ // this". A suppressed item (dashboardUrl undefined, suppressed: true)
2593
+ // is left with no key at all, same as the create-time convention.
2594
+ const enrichedResults = !opts.dryRun && testIdToDashboardState !== undefined
2420
2595
  ? batchRunResults.map(r => {
2421
- const projectId = testIdToProjectId.get(r.testId);
2422
- if (!projectId || !r.testId)
2596
+ const state = testIdToDashboardState.get(r.testId);
2597
+ if (!state || state.dashboardUrl === undefined)
2423
2598
  return r;
2424
- const dashboardUrl = resolvePortalUrl(apiUrlForDashboard, projectId, r.testId);
2425
- return dashboardUrl !== undefined ? { ...r, dashboardUrl } : r;
2599
+ return { ...r, dashboardUrl: state.dashboardUrl };
2426
2600
  })
2427
2601
  : batchRunResults;
2428
2602
  out.print({ results: enrichedResults });
@@ -4068,6 +4242,73 @@ function printRunOrChain(out, payload, createContext, textRenderer) {
4068
4242
  return `${createText}\n\n${runText}`;
4069
4243
  });
4070
4244
  }
4245
+ /**
4246
+ * Server-first precedence for a `dashboardUrl` field on any wire response
4247
+ * that can carry one (`RunResponse`, `CliCreateTestResponse`,
4248
+ * `CliBatchSpecResult`). Single source of truth for the rule so the create
4249
+ * paths (DEV-737) and the run-completion path (`withRunDashboardUrl` below)
4250
+ * can't drift apart.
4251
+ *
4252
+ * This is a PINNED three-state wire contract — a prior revision let a
4253
+ * present-but-falsy value and a truly-absent key both mean "no server
4254
+ * opinion," which was ambiguous with the real backend behavior of omitting
4255
+ * the key on a deliberate "no correct link" response, printing the dead
4256
+ * legacy link this feature exists to remove. The backend now always
4257
+ * includes the key (typed `string | null`, never omitted when it has an
4258
+ * opinion), so the three states below are mutually exclusive on the wire:
4259
+ *
4260
+ * - **Present + truthy** → the server built a correct link (it alone knows
4261
+ * which store answered and this environment's portal origin); use it
4262
+ * verbatim.
4263
+ * - **Present + falsy (`null`/`''`)** → the server explicitly has no
4264
+ * correct link — e.g. a V3-native entity with no DynamoDB mirror row for
4265
+ * the client's V2-shaped `/dashboard/tests/…` guess to land on. NEVER
4266
+ * fall back here: a client-side guess would be exactly the dead link the
4267
+ * server declined to emit. `suppressed: true` tells the caller a link
4268
+ * was actively withheld (vs. simply never computed) so it can point the
4269
+ * user elsewhere instead of printing nothing unexplained.
4270
+ * - **Absent** → an older backend that predates this field entirely. Such a
4271
+ * backend cannot have produced a V3-native/unmirrored entity either —
4272
+ * that capability and this field ship together — so the client fallback
4273
+ * is safe and reproduces exactly today's behavior.
4274
+ */
4275
+ function resolveDashboardUrl(wire, computeFallback) {
4276
+ if ('dashboardUrl' in wire) {
4277
+ return wire.dashboardUrl
4278
+ ? { dashboardUrl: wire.dashboardUrl, suppressed: false }
4279
+ : { dashboardUrl: undefined, suppressed: true };
4280
+ }
4281
+ return { dashboardUrl: computeFallback(), suppressed: false };
4282
+ }
4283
+ /**
4284
+ * Applies {@link resolveDashboardUrl} to a whole entity, returning a
4285
+ * NORMALIZED copy: a server-suppressed (`null`/`''`) value is rewritten to
4286
+ * `undefined` so `JSON.stringify` omits the key entirely instead of
4287
+ * serializing a literal `"dashboardUrl": null` — the same normalization
4288
+ * `withRunDashboardUrl` already did inline for `RunResponse`, generalized
4289
+ * here so the create paths (DEV-737) can share it byte-for-byte.
4290
+ */
4291
+ function withDashboardUrl(wire, computeFallback) {
4292
+ const { dashboardUrl, suppressed } = resolveDashboardUrl(wire, computeFallback);
4293
+ if ('dashboardUrl' in wire)
4294
+ return { entity: { ...wire, dashboardUrl }, suppressed };
4295
+ return { entity: dashboardUrl !== undefined ? { ...wire, dashboardUrl } : wire, suppressed };
4296
+ }
4297
+ /**
4298
+ * DEV-737: advisory printed when the server explicitly withheld a dashboard
4299
+ * link (`resolveDashboardUrl`'s `suppressed: true`) rather than silently
4300
+ * omitting the field with no explanation. Fires on stderr regardless of
4301
+ * `--output` mode — the field's absence from a JSON envelope carries no
4302
+ * reason on its own, and `--output json` is routinely unattended, so the
4303
+ * hint is worth the line there too (same reasoning as the `project create
4304
+ * --type backend` no-URL advisory in `project.ts`). Printing nothing beats
4305
+ * printing a dead link, but telling the caller where to look instead beats
4306
+ * printing nothing unexplained.
4307
+ */
4308
+ function emitDashboardLinkSuppressedAdvisory(testId, stderrFn) {
4309
+ stderrFn(`[advisory] no dashboard link is available for this test right now; use ` +
4310
+ `\`testsprite test get ${testId}\` to look it up.`);
4311
+ }
4071
4312
  /**
4072
4313
  * Attach the Portal deep link to a terminal RunResponse.
4073
4314
  *
@@ -4089,18 +4330,11 @@ function printRunOrChain(out, payload, createContext, textRenderer) {
4089
4330
  * backend chose not to emit.
4090
4331
  */
4091
4332
  function withRunDashboardUrl(run, apiUrl) {
4092
- // A server value of `null` is meaningful, not missing: it says "there is no
4093
- // correct link for this run" (e.g. a workspace-scoped page the environment's
4094
- // portal build does not serve yet). Falling back to our own guess there would
4095
- // reintroduce exactly the wrong link the server declined to send — so only an
4096
- // ABSENT field (older backend) reopens the client path.
4097
- if ('dashboardUrl' in run) {
4098
- return run.dashboardUrl ? run : { ...run, dashboardUrl: undefined };
4099
- }
4100
- if (!run.projectId || !run.testId)
4101
- return run;
4102
- const dashboardUrl = resolvePortalUrl(apiUrl, run.projectId, run.testId);
4103
- return dashboardUrl !== undefined ? { ...run, dashboardUrl } : run;
4333
+ return withDashboardUrl(run, () => {
4334
+ if (!run.projectId || !run.testId)
4335
+ return undefined;
4336
+ return resolvePortalUrl(apiUrl, run.projectId, run.testId);
4337
+ }).entity;
4104
4338
  }
4105
4339
  /**
4106
4340
  * Render a `RunResponse` to human-readable text. JSON mode callers get
@@ -4267,6 +4501,16 @@ export async function runTestRun(opts, deps = {}) {
4267
4501
  const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
4268
4502
  const out = makeOutput(opts.output, deps);
4269
4503
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
4504
+ // Pre-charge reachability preflight — real path only (dry-run
4505
+ // makes zero network calls by convention), after `assertNotLocal` and
4506
+ // before the trigger POST so a doomed run never gets a run row or charge.
4507
+ // `opts.skipPreflight` is threaded straight to a zero-network no-op; a
4508
+ // delegating caller (`runCreate`/`runCreateFromPlan` chaining `--run`)
4509
+ // already ran this exact check against the same URL before its own
4510
+ // create POST and sets `skipPreflight: true` here to avoid probing twice.
4511
+ if (opts.targetUrl !== undefined) {
4512
+ await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
4513
+ }
4270
4514
  let triggerResponse;
4271
4515
  let triggerRequestId;
4272
4516
  let resumedFromConflict = false;
@@ -4373,6 +4617,25 @@ export async function runTestRun(opts, deps = {}) {
4373
4617
  throw err;
4374
4618
  }
4375
4619
  }
4620
+ // Response-driven, not assumption-driven: the backend is the ground
4621
+ // truth for whether --target-url was actually applied — V3
4622
+ // deliberately returns `targetUrl: ''` rather than echoing an override it
4623
+ // did not apply ("so the response doesn't claim a target we didn't use"),
4624
+ // while V2 echoes the real applied value. Comparing what we asked for
4625
+ // against what the trigger response reports self-corrects the day the
4626
+ // backend applies the override, with no `v3Enabled` assumption at all.
4627
+ // Skipped for a known-backend caller (`opts.type` threaded from the
4628
+ // `test create --run` chain): a backend trigger response's `targetUrl`
4629
+ // is an unconditional echo of the request body (verified against
4630
+ // backend-v2.0's `CliTestsController.createRun` — `targetUrl: body.targetUrl
4631
+ // ?? ''` on both the V2 and V3 backend branches), so it can never mismatch
4632
+ // and the existing, more specific C1 advisory ("--target-url has no effect
4633
+ // for backend tests") already covers this case at create time.
4634
+ if (opts.targetUrl !== undefined &&
4635
+ opts.type !== 'backend' &&
4636
+ triggerResponse.targetUrl !== opts.targetUrl) {
4637
+ emitTargetUrlMismatchAdvisory(stderrFn, opts.targetUrl, triggerResponse.targetUrl);
4638
+ }
4376
4639
  if (!opts.wait) {
4377
4640
  printRunOrChain(out, triggerResponse, opts.createContext, data => renderTriggerRunText(data));
4378
4641
  if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
@@ -4446,7 +4709,8 @@ export async function runTestRun(opts, deps = {}) {
4446
4709
  throw ApiError.fromEnvelope({
4447
4710
  error: {
4448
4711
  code: 'UNSUPPORTED', // exit 7 per errors.md
4449
- message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}.`,
4712
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}. ` +
4713
+ stillRunningAndBillingSubject(triggerResponse.runId),
4450
4714
  nextAction: `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
4451
4715
  requestId: 'local',
4452
4716
  details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
@@ -4478,7 +4742,7 @@ export async function runTestRun(opts, deps = {}) {
4478
4742
  lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
4479
4743
  return lines.join('\n');
4480
4744
  });
4481
- stderrFn(`Run ${triggerResponse.runId} is still in progress (request timed out). ` +
4745
+ stderrFn(`Request timed out. ${stillRunningAndBillingSubject(triggerResponse.runId)} ` +
4482
4746
  `Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
4483
4747
  throw err;
4484
4748
  }
@@ -4549,7 +4813,8 @@ export async function runTestRun(opts, deps = {}) {
4549
4813
  // the standalone `test run <id>` path neither is set, so probe the test type
4550
4814
  // once (text mode only, best-effort) — DEV-282.
4551
4815
  const isBackend = await resolveRunCardIsBackend(client, opts.testId, opts.output, beFallbackUsed || opts.type === 'backend');
4552
- printRunOrChain(out, withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps)), opts.createContext, data => renderRunResponseText(data, { isBackend }));
4816
+ const finalRunWithUrl = withRunDashboardUrl(finalRun, resolveApiUrl(opts, deps));
4817
+ printRunOrChain(out, finalRunWithUrl, opts.createContext, data => renderRunResponseText(data, { isBackend }));
4553
4818
  // Surface the trigger requestId under --verbose/--debug or JSON mode so
4554
4819
  // operators can trace the full lifecycle (gated since 2026-06-04 dogfood;
4555
4820
  // JSON mode always emits to stderr — it never pollutes stdout).
@@ -4562,6 +4827,24 @@ export async function runTestRun(opts, deps = {}) {
4562
4827
  ? `Run finished with status: ${finalRun.status}. Backend failure artifacts are addressed by testId — use 'testsprite test failure get ${finalRun.testId}' to download the bundle.`
4563
4828
  : `Run finished with status: ${finalRun.status}. Use 'testsprite test artifact get ${finalRun.runId}' to download the failure bundle.`);
4564
4829
  }
4830
+ // CI-native output layer (issue #99): single-test parity with the --all batch.
4831
+ // Emitted before the exit-code gate throws below so the summary file and
4832
+ // annotations land even when the run exits non-zero (mirrors the batch path).
4833
+ // The summary file is a machine artifact written regardless of --output mode;
4834
+ // under --output json the run envelope above owns stdout, so ::error::
4835
+ // workflow commands are routed to stderr (the Actions runner parses both).
4836
+ // Best-effort: a sink write throwing (e.g. EPIPE) must never skip the
4837
+ // exit-code gate below or change the command's exit status.
4838
+ try {
4839
+ emitCiArtifacts(summarizeSingleRun(finalRunWithUrl), opts, {
4840
+ env: deps.env ?? process.env,
4841
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
4842
+ stderr: stderrFn,
4843
+ }, 'run');
4844
+ }
4845
+ catch (ciErr) {
4846
+ stderrFn(`[run] CI output emission failed; continuing: ${ciErr.message}`);
4847
+ }
4565
4848
  const exitCode = exitCodeForRunStatus(finalRun.status);
4566
4849
  if (exitCode !== 0) {
4567
4850
  // Throw a CLIError so index.ts exits with the right code without
@@ -4753,7 +5036,8 @@ export async function runTestWaitMany(opts, deps = {}) {
4753
5036
  stderrFn(interruptDetachMessage(fanOutErr, unfinished));
4754
5037
  }
4755
5038
  else {
4756
- stderrFn(`Re-attach with: testsprite test wait ${unfinished.join(' ')}, or cancel with: testsprite test cancel ${unfinished.join(' ')}`);
5039
+ stderrFn(`Request timed out. ${stillRunningAndBillingSubject(unfinished)} ` +
5040
+ `Re-attach with: testsprite test wait ${unfinished.join(' ')}, or cancel with: testsprite test cancel ${unfinished.join(' ')}`);
4757
5041
  }
4758
5042
  }
4759
5043
  }
@@ -5042,7 +5326,8 @@ export async function runTestWait(opts, deps = {}) {
5042
5326
  throw ApiError.fromEnvelope({
5043
5327
  error: {
5044
5328
  code: 'UNSUPPORTED', // exit 7 per errors.md
5045
- message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${opts.runId}.`,
5329
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${opts.runId}. ` +
5330
+ stillRunningAndBillingSubject(opts.runId),
5046
5331
  nextAction: `Resume polling: testsprite test wait ${opts.runId}, or cancel it: testsprite test cancel ${opts.runId}`,
5047
5332
  requestId: 'local',
5048
5333
  details: { runId: opts.runId, timeoutSeconds: opts.timeoutSeconds },
@@ -5064,7 +5349,7 @@ export async function runTestWait(opts, deps = {}) {
5064
5349
  `hint Cancel with: testsprite test cancel ${p.runId}`,
5065
5350
  ].join('\n');
5066
5351
  });
5067
- stderrFn(`Run ${opts.runId} is still in progress (request timed out). ` +
5352
+ stderrFn(`Request timed out. ${stillRunningAndBillingSubject(opts.runId)} ` +
5068
5353
  `Re-attach with: testsprite test wait ${opts.runId}, or cancel with: testsprite test cancel ${opts.runId}`);
5069
5354
  throw err;
5070
5355
  }
@@ -5127,15 +5412,57 @@ export async function runTestWait(opts, deps = {}) {
5127
5412
  }
5128
5413
  return finalRun;
5129
5414
  }
5130
- async function writeBatchJUnitReportIfRequested(opts, results) {
5415
+ /**
5416
+ * Best-effort `testId → test name` map for the JUnit report, so a CI test tab
5417
+ * shows names instead of UUIDs. One paginated `GET /tests?projectId=` sweep,
5418
+ * bounded by a 5 s deadline and swallowed on any error — a missing/partial map
5419
+ * just falls back to ids, never blocks or fails the report.
5420
+ */
5421
+ async function buildTestNameMap(client, projectId) {
5422
+ const map = new Map();
5423
+ if (!projectId)
5424
+ return map;
5425
+ const ac = new AbortController();
5426
+ const timer = setTimeout(() => ac.abort(), DUP_NAME_ADVISORY_TIMEOUT_MS);
5427
+ try {
5428
+ let cursor;
5429
+ for (let pageN = 0; pageN < 20; pageN++) {
5430
+ const page = await client.get('/tests', {
5431
+ query: { projectId, pageSize: 100, ...(cursor ? { cursor } : {}) },
5432
+ signal: ac.signal,
5433
+ retryOnRateLimit: false,
5434
+ });
5435
+ for (const t of page.items ?? [])
5436
+ map.set(t.id, t.name);
5437
+ cursor = page.nextToken ?? undefined;
5438
+ if (!cursor)
5439
+ break;
5440
+ }
5441
+ }
5442
+ catch {
5443
+ // best-effort — a partial/empty map simply falls back to ids in the report.
5444
+ }
5445
+ finally {
5446
+ clearTimeout(timer);
5447
+ }
5448
+ return map;
5449
+ }
5450
+ async function writeBatchJUnitReportIfRequested(opts, results, nameByTestId) {
5131
5451
  if (opts.report !== 'junit' || opts.reportFile === undefined)
5132
5452
  return;
5133
5453
  const projectId = resolveBatchReportProjectId(opts, results);
5134
5454
  const suiteName = opts.reportSuiteName ?? `testsprite:${projectId}`;
5455
+ // Enrich each row with the human name (from the map) and the run duration
5456
+ // (from poll timing) — the two fields whose absence made the report unreadable.
5457
+ const enriched = results.map(r => ({
5458
+ ...r,
5459
+ name: nameByTestId?.get(r.testId) ?? r.name,
5460
+ durationSeconds: r.durationSeconds ?? durationSecondsBetween(r.startedAt, r.finishedAt),
5461
+ }));
5135
5462
  const xml = buildJUnitReport({
5136
5463
  suiteName,
5137
5464
  classname: projectId,
5138
- results,
5465
+ results: enriched,
5139
5466
  });
5140
5467
  await writeJUnitReportFile(opts.reportFile, xml);
5141
5468
  }
@@ -5258,14 +5585,16 @@ export async function runTestRunAll(opts, deps = {}) {
5258
5585
  stderrFn(`[advisory] ${skippedIntegration.length} assembled integration test${skippedIntegration.length !== 1 ? 's' : ''} skipped — not runnable via the CLI wave path. Run them from the portal.`);
5259
5586
  }
5260
5587
  if (conflicts.length > 0) {
5261
- stderrFn(`[advisory] ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight, skipped: ${conflicts.map(c => c.testId).join(' ')}`);
5588
+ // Reason-aware advisory: a view-only / un-runnable / not-found case is not
5589
+ // "already in flight" — summarizeConflicts names the actual causes.
5590
+ stderrFn(`[advisory] ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} not dispatched (${summarizeConflicts(conflicts)}), skipped: ${conflicts.map(c => c.testId).join(' ')}`);
5262
5591
  }
5263
5592
  if (deferred.length > 0) {
5264
5593
  stderrFn(`Rate-deferred testIds (retry later): ${deferred.map(d => d.testId).join(' ')}`);
5265
5594
  }
5266
5595
  stderrFn(`Dispatched ${accepted.length} test${accepted.length !== 1 ? 's' : ''}` +
5267
5596
  `${skippedFrontend.length > 0 ? ` (${skippedFrontend.length} FE skipped)` : ''}` +
5268
- `${conflicts.length > 0 ? ` (${conflicts.length} in flight)` : ''}` +
5597
+ `${conflicts.length > 0 ? ` (${conflicts.length} conflict${conflicts.length !== 1 ? 's' : ''})` : ''}` +
5269
5598
  `${deferred.length > 0 ? ` (${deferred.length} rate-deferred)` : ''}.`);
5270
5599
  if (!opts.wait) {
5271
5600
  const printResp = {
@@ -5279,7 +5608,7 @@ export async function runTestRunAll(opts, deps = {}) {
5279
5608
  const r = data;
5280
5609
  const lines = [`accepted ${r.accepted.length}`];
5281
5610
  if (r.conflicts.length > 0)
5282
- lines.push(`conflicts ${r.conflicts.length} (already in flight)`);
5611
+ lines.push(`conflicts ${r.conflicts.length} (${summarizeConflicts(r.conflicts)})`);
5283
5612
  if (r.deferred.length > 0)
5284
5613
  lines.push(`deferred ${r.deferred.length} (rate-limited — retry)`);
5285
5614
  if (r.skippedFrontend.length > 0) {
@@ -5317,26 +5646,39 @@ export async function runTestRunAll(opts, deps = {}) {
5317
5646
  // JSON merge reflect what was actually dispatched, not the stale initial resp.
5318
5647
  return { ...batchResp, accepted, deferred, conflicts };
5319
5648
  }
5320
- // D3: bounded deferred-retry loop (only under --wait).
5321
- // Up to MAX_DEFERRED_RETRIES attempts to re-dispatch still-deferred tests.
5322
- // Each attempt sleeps for Retry-After (if server provided it) or the default
5323
- // 61s, clamped to the remaining --timeout budget. Newly-accepted runs are
5324
- // merged into `accepted`; if still deferred after all attempts, fall through
5325
- // to the existing exit-7 path.
5649
+ // D3: budget-driven deferred-retry loop (only under --wait).
5650
+ // Re-dispatches still-deferred tests until they all clear OR the --timeout
5651
+ // budget is exhausted — a busy pool (the in-flight concurrency cap folds
5652
+ // overflow into `deferred[]`) drains within the user's own timeout instead of
5653
+ // giving up after a fixed few tries and failing the run. Each attempt sleeps
5654
+ // 61s (clamped to the remaining budget); newly-accepted runs merge into
5655
+ // `accepted`; if still deferred when the budget runs out, fall through to the
5656
+ // existing exit-7 path. `maxDeferredAttempts` is a pure runaway backstop (the
5657
+ // deadline check below is the real stop), scaled to the timeout so it never
5658
+ // caps a legitimate long wait.
5326
5659
  const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
5327
5660
  const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
5328
- for (let attempt = 1; attempt <= MAX_DEFERRED_RETRIES && deferred.length > 0; attempt++) {
5661
+ // finding 1: reserve a poll window so the deferred-retry loop can't consume the
5662
+ // ENTIRE --timeout and leave the fan-out poll with nothing — which would report
5663
+ // already-finished runs as timeouts (exit 7) instead of their real verdicts
5664
+ // (a genuine failure is exit 1, not 7). One third of the budget, capped at 60s.
5665
+ const POLL_RESERVE_MS = Math.min(60_000, Math.floor((opts.timeoutSeconds * 1000) / 3));
5666
+ const maxDeferredAttempts = Math.max(MAX_DEFERRED_RETRIES, Math.ceil(opts.timeoutSeconds / 60) + 2);
5667
+ for (let attempt = 1; attempt <= maxDeferredAttempts && deferred.length > 0; attempt++) {
5329
5668
  const remainingMs = batchDeadlineMs - Date.now();
5330
- if (remainingMs <= 0) {
5331
- stderrFn(`[deferred-retry] timeout budget exhausted before attempt ${attempt}/${MAX_DEFERRED_RETRIES} — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
5669
+ if (remainingMs <= POLL_RESERVE_MS) {
5670
+ stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
5332
5671
  break;
5333
5672
  }
5334
- const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs);
5335
- stderrFn(`[deferred-retry] attempt ${attempt}/${MAX_DEFERRED_RETRIES} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
5673
+ // §1: clamp to what's left ABOVE the reserve so the sleep itself can't run
5674
+ // the budget to zero (the loop only reaches here when remainingMs >
5675
+ // POLL_RESERVE_MS, so the difference is always positive).
5676
+ const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs - POLL_RESERVE_MS);
5677
+ stderrFn(`[deferred-retry] attempt ${attempt} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
5336
5678
  await sleepFn(sleepMs);
5337
5679
  const remainingAfterSleep = batchDeadlineMs - Date.now();
5338
- if (remainingAfterSleep <= 0) {
5339
- stderrFn(`[deferred-retry] timeout budget exhausted during sleep — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
5680
+ if (remainingAfterSleep <= POLL_RESERVE_MS) {
5681
+ stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
5340
5682
  break;
5341
5683
  }
5342
5684
  const retryIds = deferred.map(d => d.testId);
@@ -5351,6 +5693,16 @@ export async function runTestRunAll(opts, deps = {}) {
5351
5693
  const retryKey = `${retryBase}${retrySuffix}`;
5352
5694
  let retryResp;
5353
5695
  try {
5696
+ // The retry dispatch POST is deliberately NOT bound to the batch deadline
5697
+ // via an AbortSignal. It is a state-CREATING call (it seeds runs); if the
5698
+ // deadline fired mid-flight the abort would only cancel the CLIENT wait,
5699
+ // leaving the server having possibly created the runs while this loop
5700
+ // reports them as still-deferred — the user then retries with a fresh
5701
+ // idempotency key and DUPLICATES the execution + charge. The per-request
5702
+ // timeout (`--request-timeout`, default 120s) still bounds the call, and
5703
+ // the sleeps + fan-out poll below remain deadline-aware; only this single
5704
+ // dispatch may overrun the budget slightly, which is strictly safer than
5705
+ // an indeterminate aborted-but-maybe-dispatched batch.
5354
5706
  retryResp = await client.triggerBatchRunFresh({
5355
5707
  projectId,
5356
5708
  testIds: retryIds,
@@ -5358,7 +5710,7 @@ export async function runTestRunAll(opts, deps = {}) {
5358
5710
  }, { idempotencyKey: retryKey });
5359
5711
  }
5360
5712
  catch (err) {
5361
- // If the retry itself errors, surface the error and stop retrying.
5713
+ // If the retry itself errors, surface it and stop retrying.
5362
5714
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
5363
5715
  break;
5364
5716
  }
@@ -5382,11 +5734,53 @@ export async function runTestRunAll(opts, deps = {}) {
5382
5734
  stderrFn(`[deferred-retry] attempt ${attempt}: all previously-deferred tests accepted.`);
5383
5735
  }
5384
5736
  }
5385
- // --wait: fan-out poll each accepted run by its runId. Every accepted entry
5386
- // carries a real runId (the backend routes slot-claim failures to conflicts[]),
5387
- // so there is no "draft, no runId" subset to silently skip — polling all of
5388
- // them is the only way `--wait` can report a faithful (not false-green) verdict.
5389
- const pollable = accepted;
5737
+ // Gap B: an already-running case is not a dead end under --wait. A conflict
5738
+ // carrying `currentRunId` has an EXISTING run we can poll to a verdict
5739
+ // (auto-resume) — the "concurrent job already started this test" case should
5740
+ // wait for that run's result, not fail the batch. Conflicts without a
5741
+ // resolvable in-flight run stay hard (nothing to wait on).
5742
+ const resumableConflicts = conflicts.filter(c => c.currentRunId);
5743
+ const hardConflicts = conflicts.filter(c => !c.currentRunId);
5744
+ // Only hard conflicts remain "conflicts" for the final accounting/exit; the
5745
+ // resumable ones become polled results below.
5746
+ conflicts = hardConflicts;
5747
+ // finding 2: resolve each in-flight run's createdAt to floor the BE wait
5748
+ // fallback's "not before" filter. An epoch sentinel let the fallback accept
5749
+ // ANY terminal result for the test — including the PREVIOUS run's — whenever
5750
+ // the row lacks `runIdIfAvailable` (the orphaned-row case the fallback exists
5751
+ // for, and the EXPECTED path for MCP-backend-triggered runs whose TestRun rows
5752
+ // never leave `queued`). Flooring to the run's own createdAt stops an
5753
+ // auto-resume from resolving to a stale prior verdict (a false green). The
5754
+ // fetch also yields source/createdFrom so we can name who started the run.
5755
+ // §5: resolve the in-flight runs' createdAt in PARALLEL, bounded by a signal
5756
+ // capped at the remaining batch budget. This runs in exactly the busy-pool /
5757
+ // many-in-flight-conflicts scenario finding 1 is about, so a serial N round-trip
5758
+ // fetch (with no deadline bound) would eat the budget finding 1's fix protects.
5759
+ const resolveSignal = AbortSignal.timeout(Math.max(1, batchDeadlineMs - Date.now()));
5760
+ const resumableEntries = await Promise.all(resumableConflicts.map(async (c) => {
5761
+ const inFlightRunId = c.currentRunId;
5762
+ // Conservative default if the run can't be read: floor at NOW (never the
5763
+ // epoch) so the fallback still can't accept an older run's result.
5764
+ let notBefore = new Date().toISOString();
5765
+ let startedBy;
5766
+ try {
5767
+ const inFlight = await client.getRun(inFlightRunId, { signal: resolveSignal });
5768
+ if (inFlight.createdAt)
5769
+ notBefore = inFlight.createdAt;
5770
+ startedBy = inFlight.source || inFlight.createdFrom || undefined;
5771
+ }
5772
+ catch {
5773
+ // keep the conservative now() floor (fetch failed or the signal aborted)
5774
+ }
5775
+ stderrFn(`[auto-resume] ${c.testId} — polling in-flight run ${inFlightRunId}${startedBy ? ` (started by ${startedBy})` : ''} to a verdict instead of failing`);
5776
+ return { testId: c.testId, runId: inFlightRunId, enqueuedAt: notBefore };
5777
+ }));
5778
+ // --wait: fan-out poll each accepted run by its runId, PLUS each auto-resumed
5779
+ // in-flight run. Every accepted entry carries a real runId (the backend routes
5780
+ // slot-claim failures to conflicts[]); the resumed entries reuse the existing
5781
+ // run's id with a real createdAt floor. Polling all of them is the only way
5782
+ // `--wait` reports a faithful (not false-green) verdict.
5783
+ const pollable = [...accepted, ...resumableEntries];
5390
5784
  if (pollable.length === 0) {
5391
5785
  // Build final response with potentially-updated accepted/deferred from D3 retry loop.
5392
5786
  const finalResp = {
@@ -5397,6 +5791,15 @@ export async function runTestRunAll(opts, deps = {}) {
5397
5791
  skippedIntegration,
5398
5792
  };
5399
5793
  out.print(finalResp);
5794
+ // Nothing was dispatched, but a --wait CI run still needs the exit-6/7 to be
5795
+ // visible: emit annotations + summary before the throw below (conflicts /
5796
+ // deferred fold into the summary as non-passed rows; skipped* are not folded).
5797
+ // Without this an all-in-flight or all-deferred batch fails CI silently.
5798
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(finalResp)), opts, {
5799
+ env: deps.env ?? process.env,
5800
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
5801
+ stderr: stderrFn,
5802
+ }, 'run');
5400
5803
  // Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
5401
5804
  // mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
5402
5805
  if (deferred.length > 0) {
@@ -5429,6 +5832,37 @@ export async function runTestRunAll(opts, deps = {}) {
5429
5832
  const runId = entry.runId;
5430
5833
  const remainingMs = batchDeadlineMs - Date.now();
5431
5834
  if (remainingMs <= 0) {
5835
+ // §1/§4: the retry loop reserves POLL_RESERVE_MS, but a slow fan-out can
5836
+ // still land here past the deadline. Do ONE bounded poll (1s) THROUGH the
5837
+ // backend wait-fallback before declaring timeout — a run that already
5838
+ // reached a verdict resolves for ~one request instead of a false timeout
5839
+ // (exit 7 when the platform already produced its result; a failure is exit
5840
+ // 1). Going through pollRunUntilTerminal + resolveAlternate — not a bare
5841
+ // getRun — also covers the orphaned-row class finding 2 is about: a backend
5842
+ // TestRun row stuck in `queued` whose verdict only the fallback resolves.
5843
+ const lastResortAlternate = makeBackendWaitFallback({
5844
+ client,
5845
+ resolveTestId: () => entry.testId,
5846
+ resolveNotBefore: () => entry.enqueuedAt,
5847
+ onResolved: () => undefined,
5848
+ });
5849
+ try {
5850
+ const finalRun = await pollRunUntilTerminal(client, runId, {
5851
+ timeoutSeconds: 1,
5852
+ sleep: deps.sleep,
5853
+ shutdown: shutdownOf(deps),
5854
+ resolveAlternate: lastResortAlternate,
5855
+ });
5856
+ return {
5857
+ testId: entry.testId,
5858
+ runId,
5859
+ projectId: finalRun.projectId,
5860
+ status: finalRun.status,
5861
+ };
5862
+ }
5863
+ catch {
5864
+ // fall through to the timeout result below
5865
+ }
5432
5866
  return {
5433
5867
  testId: entry.testId,
5434
5868
  runId,
@@ -5465,6 +5899,8 @@ export async function runTestRunAll(opts, deps = {}) {
5465
5899
  runId,
5466
5900
  projectId: finalRun.projectId,
5467
5901
  status: finalRun.status,
5902
+ startedAt: finalRun.startedAt,
5903
+ finishedAt: finalRun.finishedAt,
5468
5904
  };
5469
5905
  }
5470
5906
  catch (err) {
@@ -5578,74 +6014,53 @@ export async function runTestRunAll(opts, deps = {}) {
5578
6014
  total: pollable.length,
5579
6015
  },
5580
6016
  };
5581
- await writeBatchJUnitReportIfRequested(opts, freshRunResults);
6017
+ const freshNameMap = opts.report === 'junit' && opts.reportFile !== undefined
6018
+ ? await buildTestNameMap(client, opts.projectId)
6019
+ : undefined;
6020
+ await writeBatchJUnitReportIfRequested(opts, freshRunResults, freshNameMap);
5582
6021
  out.print(jsonPayload);
5583
6022
  // CI-native output layer (issue #99): emitted before the gate throws below so
5584
6023
  // the artifacts land even when the batch exits non-zero. The summary file is a
5585
6024
  // machine artifact written regardless of --output mode; stdout stays owned by
5586
6025
  // the envelope above (plus Actions workflow commands, which Actions parses).
5587
- {
5588
- const env = deps.env ?? process.env;
5589
- const ghEnabled = opts.ghOutput === true || env.GITHUB_ACTIONS === 'true';
5590
- if (ghEnabled || opts.summaryFile !== undefined) {
5591
- const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
5592
- if (opts.summaryFile !== undefined) {
5593
- try {
5594
- writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
5595
- }
5596
- catch {
5597
- stderrFn(`[run] could not write --summary-file ${opts.summaryFile}; continuing`);
5598
- }
5599
- }
5600
- if (ghEnabled) {
5601
- const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
5602
- emitGithubOutputs(ciSummary, env, {
5603
- stdout: stdoutFn,
5604
- stderr: stderrFn,
5605
- appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
5606
- // Under --output json the envelope above owns stdout; workflow
5607
- // commands go to stderr instead (the Actions runner parses both
5608
- // streams), keeping the documented machine output parseable.
5609
- annotations: opts.output === 'json' ? stderrFn : stdoutFn,
5610
- }, { force: opts.ghOutput === true });
5611
- }
5612
- }
5613
- }
6026
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(jsonPayload)), opts, {
6027
+ env: deps.env ?? process.env,
6028
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
6029
+ stderr: stderrFn,
6030
+ }, 'run');
5614
6031
  // Rate-deferred tests were never dispatched → the batch is incomplete (exit 7),
5615
6032
  // mirroring `test rerun --all`. Checked before the failed-run throw so the
5616
6033
  // operator learns to retry the deferred set.
5617
6034
  if (deferred.length > 0) {
5618
6035
  throw new CLIError(`Batch run incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} rate-deferred (per-key run budget) — retry these individually after ~60s: ${deferred.map(d => d.testId).join(' ')}`, 7);
5619
6036
  }
5620
- if (timedOut > 0) {
5621
- const timedOutRunIds = freshRunResults
5622
- .filter(r => r.status === 'timeout')
5623
- .map(r => r.runId)
5624
- .filter(Boolean);
6037
+ // Shared exit-code precedence (auth 3 → typed operational ApiError → timeout 7
6038
+ // → generic fail 1) so `test run` and `testlist run` can't drift. This
6039
+ // supersedes the previous "fold every non-auth poll error into exit 1"
6040
+ // behaviour: a NOT_FOUND/RATE_LIMITED/… poll now propagates its real code.
6041
+ const failure = resolveWaitFailure(freshRunResults, { timeoutSeconds: opts.timeoutSeconds });
6042
+ if (failure)
6043
+ throw failure;
6044
+ // Hard conflicts (a run already in flight for the test that we could NOT
6045
+ // auto-resume — no `currentRunId` to poll) mean those tests never ran. In a
6046
+ // MIXED batch, the accepted/resumed runs above already made `pollable`
6047
+ // non-empty, so the all-conflict early-exit-6 branch didn't fire — without
6048
+ // this gate a passing resumable run would mask an unresolved hard conflict and
6049
+ // exit 0. Checked AFTER the failed gate (a real failure is the more actionable
6050
+ // headline; a batch with both still exits 1), matching the exit-6 the
6051
+ // all-conflict path returns. `conflicts` here holds only the hard ones —
6052
+ // resumable conflicts were split into the poll set above.
6053
+ if (conflicts.length > 0) {
5625
6054
  throw ApiError.fromEnvelope({
5626
6055
  error: {
5627
- code: 'UNSUPPORTED',
5628
- message: `${timedOut} run${timedOut !== 1 ? 's' : ''} timed out.`,
5629
- nextAction: [
5630
- ...timedOutRunIds.map(rid => `Resume: testsprite test wait ${rid}`),
5631
- ...timedOutRunIds.map(rid => `Cancel: testsprite test cancel ${rid}`),
5632
- ].join('\n'),
6056
+ code: 'CONFLICT',
6057
+ message: `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight and could not be resumed — not run.`,
6058
+ nextAction: `Wait for the in-flight run(s) to finish, then retry: ${conflicts.map(c => c.testId).join(' ')}`,
5633
6059
  requestId: 'local',
5634
- details: { timedOutRunIds, timeoutSeconds: opts.timeoutSeconds },
6060
+ details: { conflicts: conflicts.map(c => c.testId) },
5635
6061
  },
5636
6062
  });
5637
6063
  }
5638
- if (failed > 0) {
5639
- // An auth failure on any member is a batch-wide condition (the credential is
5640
- // bad, not the test) — propagate exit 3 so the operator fixes auth rather
5641
- // than chasing a "test failed" (exit 1). Other operational codes stay folded
5642
- // into the generic batch-failure exit 1; their per-member envelope is in JSON.
5643
- const authErr = freshRunResults.find(r => r.error?.exitCode === 3);
5644
- if (authErr) {
5645
- throw new CLIError(`${failed} run${failed !== 1 ? 's' : ''} failed — auth error (${authErr.error?.code}): ${authErr.error?.message}`, 3);
5646
- }
5647
- throw new CLIError(`${failed} run${failed !== 1 ? 's' : ''} failed.`, 1);
5648
- }
5649
6064
  // [P2] Return object reconstructed from post-retry mutable state (accepted,
5650
6065
  // deferred, conflicts) so the caller always sees what was actually dispatched,
5651
6066
  // not the stale initial batchResp. accepted here still holds the original
@@ -6077,7 +6492,8 @@ export async function runTestRerun(opts, deps = {}) {
6077
6492
  const cancelHints = closureMembers
6078
6493
  .map(m => `testsprite test cancel ${m.runId}`)
6079
6494
  .join('\n');
6080
- stderrFn(`Closure members are still in progress (request timed out). Re-attach with:\n${reattachHints}\n` +
6495
+ stderrFn(`Request timed out. ${stillRunningAndBillingSubject(closureMembers.map(m => m.runId))} ` +
6496
+ `Re-attach with:\n${reattachHints}\n` +
6081
6497
  `Or cancel with:\n${cancelHints}`);
6082
6498
  throw fanOutErr;
6083
6499
  }
@@ -6180,6 +6596,15 @@ export async function runTestRerun(opts, deps = {}) {
6180
6596
  // never confirmed would let --wait exit 0. Observed-failed members are not
6181
6597
  // included; that's the future --fail-on-closure decision.
6182
6598
  const unobservedMembers = closureFailures.filter(f => f.unobserved);
6599
+ // §5 (unify with the batch fan-outs): an auth failure on an unobserved
6600
+ // closure member is batch-wide (a bad credential, not a bad test) and
6601
+ // non-retriable, so it must exit 3 — not be masked as the generic
6602
+ // unobserved-timeout 7. A poll-errored member's `status` holds the error
6603
+ // code; a timed-out member's is `'timeout'` (never an auth code).
6604
+ const authMember = unobservedMembers.find(m => isAuthCode(m.status));
6605
+ if (authMember) {
6606
+ throw new CLIError(`Closure member ${authMember.runId} hit an auth error (${authMember.status}) — the credential is bad, not the test.`, 3);
6607
+ }
6183
6608
  if (unobservedMembers.length > 0) {
6184
6609
  const unobservedIds = unobservedMembers.map(f => f.runId);
6185
6610
  const resumeHints = unobservedIds.map(runId => `testsprite test wait ${runId}`).join('\n') +
@@ -6229,10 +6654,23 @@ export async function runTestRerun(opts, deps = {}) {
6229
6654
  catch (err) {
6230
6655
  if (err instanceof TimeoutError) {
6231
6656
  ticker.finalize(`Run ${rerunResp.runId} — timed out after ${opts.timeoutSeconds}s`);
6657
+ // Mirror the RequestTimeoutError path: emit a partial run to stdout so
6658
+ // JSON consumers and AI agents can grab the runId and chain into
6659
+ // `testsprite test wait <runId>` without parsing the stderr error envelope.
6660
+ const timeoutPartial = { runId: rerunResp.runId, status: 'running' };
6661
+ out.print(timeoutPartial, data => {
6662
+ const p = data;
6663
+ return [
6664
+ `runId ${p.runId}`,
6665
+ `status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
6666
+ `hint Re-attach with: testsprite test wait ${p.runId}`,
6667
+ ].join('\n');
6668
+ });
6232
6669
  throw ApiError.fromEnvelope({
6233
6670
  error: {
6234
6671
  code: 'UNSUPPORTED',
6235
- message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${rerunResp.runId}.`,
6672
+ message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${rerunResp.runId}. ` +
6673
+ stillRunningAndBillingSubject(rerunResp.runId),
6236
6674
  nextAction: `Resume polling: testsprite test wait ${rerunResp.runId}, or cancel it: testsprite test cancel ${rerunResp.runId}`,
6237
6675
  requestId: 'local',
6238
6676
  details: { runId: rerunResp.runId, timeoutSeconds: opts.timeoutSeconds },
@@ -6253,7 +6691,7 @@ export async function runTestRerun(opts, deps = {}) {
6253
6691
  `hint Cancel with: testsprite test cancel ${p.runId}`,
6254
6692
  ].join('\n');
6255
6693
  });
6256
- stderrFn(`Run ${rerunResp.runId} is still in progress (request timed out). ` +
6694
+ stderrFn(`Request timed out. ${stillRunningAndBillingSubject(rerunResp.runId)} ` +
6257
6695
  `Re-attach with: testsprite test wait ${rerunResp.runId}, or cancel with: testsprite test cancel ${rerunResp.runId}`);
6258
6696
  throw err;
6259
6697
  }
@@ -6509,27 +6947,38 @@ export async function runTestRerun(opts, deps = {}) {
6509
6947
  const deferredIds = deferred.map(d => d.testId).join(' ');
6510
6948
  stderrFn(`nextAction: testsprite test rerun ${deferredIds}`);
6511
6949
  }
6512
- // D3: bounded deferred-retry loop for rerun --all (only under --wait).
6513
- // Up to MAX_DEFERRED_RETRIES attempts to re-dispatch still-deferred tests.
6514
- // Each attempt sleeps for Retry-After (if server provided it) or the default
6515
- // 61s, clamped to the remaining --timeout budget. Newly-accepted runs are
6516
- // merged into `accepted`; if still deferred after all attempts, fall through
6517
- // to the existing exit-7 path.
6950
+ // D3: budget-driven deferred-retry loop for rerun --all (only under --wait).
6951
+ // Re-dispatches still-deferred tests until they all clear OR the --timeout
6952
+ // budget is exhausted — a busy pool drains within the user's own timeout
6953
+ // instead of giving up after a fixed few tries and failing the run. Each
6954
+ // attempt sleeps 61s (clamped to the remaining budget); newly-accepted runs
6955
+ // merge into `accepted`; if still deferred when the budget runs out, fall
6956
+ // through to the existing exit-7 path. `maxDeferredAttempts` is a pure runaway
6957
+ // backstop (the deadline check below is the real stop), scaled to the timeout.
6518
6958
  const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
6519
6959
  const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
6960
+ // finding 1: reserve a poll window so the deferred-retry loop can't consume the
6961
+ // ENTIRE --timeout and leave the fan-out poll with nothing — which would report
6962
+ // already-finished runs as timeouts (exit 7) instead of their real verdicts
6963
+ // (a genuine failure is exit 1, not 7). One third of the budget, capped at 60s.
6964
+ const POLL_RESERVE_MS = Math.min(60_000, Math.floor((opts.timeoutSeconds * 1000) / 3));
6965
+ const maxDeferredAttempts = Math.max(MAX_DEFERRED_RETRIES, Math.ceil(opts.timeoutSeconds / 60) + 2);
6520
6966
  if (opts.wait) {
6521
- for (let attempt = 1; attempt <= MAX_DEFERRED_RETRIES && deferred.length > 0; attempt++) {
6967
+ for (let attempt = 1; attempt <= maxDeferredAttempts && deferred.length > 0; attempt++) {
6522
6968
  const remainingMs = batchDeadlineMs - Date.now();
6523
- if (remainingMs <= 0) {
6524
- stderrFn(`[deferred-retry] timeout budget exhausted before attempt ${attempt}/${MAX_DEFERRED_RETRIES} — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
6969
+ if (remainingMs <= POLL_RESERVE_MS) {
6970
+ stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
6525
6971
  break;
6526
6972
  }
6527
- const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs);
6528
- stderrFn(`[deferred-retry] attempt ${attempt}/${MAX_DEFERRED_RETRIES} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
6973
+ // §1: clamp to what's left ABOVE the reserve so the sleep itself can't run
6974
+ // the budget to zero (the loop only reaches here when remainingMs >
6975
+ // POLL_RESERVE_MS, so the difference is always positive).
6976
+ const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs - POLL_RESERVE_MS);
6977
+ stderrFn(`[deferred-retry] attempt ${attempt} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
6529
6978
  await sleepFn(sleepMs);
6530
6979
  const remainingAfterSleep = batchDeadlineMs - Date.now();
6531
- if (remainingAfterSleep <= 0) {
6532
- stderrFn(`[deferred-retry] timeout budget exhausted during sleep — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
6980
+ if (remainingAfterSleep <= POLL_RESERVE_MS) {
6981
+ stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
6533
6982
  break;
6534
6983
  }
6535
6984
  // Chunk the retry ids to stay within MAX_BATCH_RERUN_IDS cap.
@@ -6557,6 +7006,13 @@ export async function runTestRerun(opts, deps = {}) {
6557
7006
  ? idempotencyKey.slice(0, 256 - retrySuffix.length)
6558
7007
  : idempotencyKey;
6559
7008
  const retryKey = `${retryBase}${retrySuffix}`;
7009
+ // The retry chunk POST is deliberately NOT bound to the batch
7010
+ // deadline via an AbortSignal — same reasoning as the fresh-run retry
7011
+ // above: it seeds runs, so a mid-flight abort would leave the server
7012
+ // possibly having dispatched while this loop reports the chunk as
7013
+ // still-deferred, inviting a duplicate rerun on the user's next
7014
+ // invocation. The per-request timeout still bounds it; the sleeps +
7015
+ // poll stay deadline-aware.
6560
7016
  const retryChunkResp = await client.triggerBatchRerun({
6561
7017
  source: 'cli',
6562
7018
  testIds: chunk,
@@ -6653,6 +7109,16 @@ export async function runTestRerun(opts, deps = {}) {
6653
7109
  if (accepted.length === 0) {
6654
7110
  // [P2] Build output from post-retry mutable state including merged notFound.
6655
7111
  out.print({ ...batchResp, accepted, deferred, conflicts, notFound, advisories });
7112
+ // Nothing dispatched, but a --wait CI run still needs the exit-6/7 visible:
7113
+ // emit annotations + summary before the throw below (conflicts / deferred /
7114
+ // notFound fold in as non-passed rows). Without this an all-conflict or
7115
+ // all-deferred rerun fails CI silently. (Default notFound note is correct
7116
+ // here — a rerun not-found id genuinely has no run to replay.)
7117
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify({ accepted: [], deferred, conflicts, notFound })), opts, {
7118
+ env: deps.env ?? process.env,
7119
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
7120
+ stderr: stderrFn,
7121
+ }, 'rerun');
6656
7122
  if (deferred.length > 0) {
6657
7123
  throw new CLIError(`Batch rerun: no tests were accepted (${deferred.length} deferred). ` +
6658
7124
  `Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
@@ -6839,8 +7305,30 @@ export async function runTestRerun(opts, deps = {}) {
6839
7305
  total: accepted.length,
6840
7306
  },
6841
7307
  };
6842
- await writeBatchJUnitReportIfRequested(opts, rerunResults);
7308
+ const rerunNameMap = opts.report === 'junit' && opts.reportFile !== undefined
7309
+ ? await buildTestNameMap(client, opts.projectId)
7310
+ : undefined;
7311
+ await writeBatchJUnitReportIfRequested(opts, rerunResults, rerunNameMap);
6843
7312
  out.print(jsonPayload);
7313
+ // CI-native output layer (issue #99): batch-rerun parity with `run --all`.
7314
+ // Emitted before the exit-code gates below so the summary file / annotations
7315
+ // land even when the batch exits non-zero. Summary-file is a machine artifact
7316
+ // written regardless of --output mode; under --output json the envelope above
7317
+ // owns stdout, so ::error:: workflow commands go to stderr instead.
7318
+ emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(jsonPayload)), opts, {
7319
+ env: deps.env ?? process.env,
7320
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
7321
+ stderr: stderrFn,
7322
+ }, 'rerun');
7323
+ // §5 (unify rerun with run --all / testlist run): auth is batch-wide — a bad
7324
+ // credential, not a bad test — and non-retriable, so it must win even over a
7325
+ // concurrent deferred/timeout. Run the shared helper's auth check BEFORE the
7326
+ // combined gate below, which would otherwise mask it as exit 7.
7327
+ if (rerunResults.some(r => r.error?.exitCode === 3)) {
7328
+ const authFailure = resolveWaitFailure(rerunResults, { timeoutSeconds: opts.timeoutSeconds });
7329
+ if (authFailure)
7330
+ throw authFailure;
7331
+ }
6844
7332
  // Determine exit code: timeout (deferred or any timeout) → 7; any fail → 1; all pass → 0
6845
7333
  if (deferred.length > 0 || timedOut > 0) {
6846
7334
  const stillRunning = timedOut > 0 ? rerunResults.filter(r => r.status === 'timeout').map(r => r.runId) : [];
@@ -6869,17 +7357,14 @@ export async function runTestRerun(opts, deps = {}) {
6869
7357
  },
6870
7358
  });
6871
7359
  }
6872
- if (failed > 0) {
6873
- // Auth failure on any member is a batch-wide condition — the credential is
6874
- // bad, not the test. Propagate exit 3 so the operator fixes auth rather than
6875
- // chasing a "rerun failed" (exit 1). Mirrors the identical logic already
6876
- // applied to runTestRunAll lines 5462-5468.
6877
- const authErr = rerunResults.find(r => r.error?.exitCode === 3);
6878
- if (authErr) {
6879
- throw new CLIError(`${failed} rerun${failed !== 1 ? 's' : ''} failed — auth error (${authErr.error?.code}): ${authErr.error?.message}`, 3);
6880
- }
6881
- throw new CLIError(`${failed} rerun${failed !== 1 ? 's' : ''} failed.`, 1);
6882
- }
7360
+ // Shared exit-code precedence for the failure tail. The combined
7361
+ // deferred/timeout gate above already fired for those, so only auth (3) →
7362
+ // typed operational ApiError → generic fail (1) remain — a NOT_FOUND /
7363
+ // RATE_LIMITED / … poll error now propagates its real code instead of folding
7364
+ // into exit 1 (matches `test run --all` / `testlist run`).
7365
+ const failure = resolveWaitFailure(rerunResults, { timeoutSeconds: opts.timeoutSeconds });
7366
+ if (failure)
7367
+ throw failure;
6883
7368
  // [P2] Return post-retry state including merged notFound so callers see the
6884
7369
  // final accounting (accepted = original BatchRerunAccepted[] dispatch list
6885
7370
  // as required by the BatchRerunResponse type; rerunResults is the polled
@@ -7061,6 +7546,18 @@ function renderArtifactGetWrittenText(data) {
7061
7546
  `files: ${data.files}`,
7062
7547
  ].join('\n');
7063
7548
  }
7549
+ /**
7550
+ * Shared `--skip-preflight` help text across the three commands
7551
+ * that trigger a run with a `--target-url` override (`create`,
7552
+ * `create-batch`, `run`). States the honest limitation up front: this CLI
7553
+ * probes from wherever it runs, not from the Lambda that executes the
7554
+ * test, so the probe is a heuristic, not a guarantee — hence the full
7555
+ * opt-out.
7556
+ */
7557
+ const SKIP_PREFLIGHT_HELP = 'skip the pre-charge --target-url reachability probe. The probe runs from this machine, not ' +
7558
+ 'from the Lambda that executes the test, so it can occasionally be wrong (e.g. an IP allowlist ' +
7559
+ 'that permits the Lambda but not this machine); use this flag when you know better. Zero network ' +
7560
+ 'calls when set.';
7064
7561
  export function createTestCommand(deps = {}) {
7065
7562
  const test = new Command('test').description('Inspect TestSprite tests');
7066
7563
  test
@@ -7128,7 +7625,10 @@ export function createTestCommand(deps = {}) {
7128
7625
  .option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
7129
7626
  .option('--wait', 'with --run, poll until terminal status', false)
7130
7627
  .option('--timeout <s>', 'with --run --wait, max seconds to wait')
7131
- .option('--target-url <url>', 'with --run, override the project default env URL')
7628
+ .option('--target-url <url>', 'with --run, override the project default env URL. Before triggering, a reachability ' +
7629
+ 'preflight refuses obviously-dead targets (DNS failure, connection refused, a 502/503/504 ' +
7630
+ 'gateway error) so a doomed run never gets billed — see --skip-preflight.')
7631
+ .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
7132
7632
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
7133
7633
  .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], [])
7134
7634
  .option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Use to declare upstream producer dependencies.', (val, prev) => [...(prev ?? []), val], [])
@@ -7193,6 +7693,7 @@ export function createTestCommand(deps = {}) {
7193
7693
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
7194
7694
  timeoutIsDefault: cmdOpts.timeout === undefined,
7195
7695
  targetUrl: cmdOpts.targetUrl,
7696
+ skipPreflight: cmdOpts.skipPreflight === true,
7196
7697
  idempotencyKey: cmdOpts.idempotencyKey,
7197
7698
  ignoredFlags: ignored,
7198
7699
  }, deps);
@@ -7214,6 +7715,7 @@ export function createTestCommand(deps = {}) {
7214
7715
  // B2(c): capture before parseTimeoutFlag converts undefined → default.
7215
7716
  timeoutIsDefault: cmdOpts.timeout === undefined,
7216
7717
  targetUrl: cmdOpts.targetUrl,
7718
+ skipPreflight: cmdOpts.skipPreflight === true,
7217
7719
  // M4 piece-2: BE dependency authoring flags.
7218
7720
  // Commander variadic collectors initialise to [] — treat empty array as undefined
7219
7721
  // so we don't send an empty array on the wire when no flags were passed.
@@ -7231,7 +7733,10 @@ export function createTestCommand(deps = {}) {
7231
7733
  .option('--max-concurrency <n>', 'with --run, max in-flight triggers at once (1-100, default: 50). The server caps run-triggers at 60/min/key; the CLI throttles to 50/min and auto-retries RATE_LIMITED responses client-side — raising this value does not bypass the server cap.')
7232
7734
  .option('--wait', 'with --run, poll each run until terminal status', false)
7233
7735
  .option('--timeout <s>', 'with --run --wait, per-run max seconds to wait (1-3600, default 600)')
7234
- .option('--target-url <url>', 'with --run, override the project default env URL for each run')
7736
+ .option('--target-url <url>', 'with --run, override the project default env URL for each run. Before the fan-out, a ' +
7737
+ 'reachability preflight refuses an obviously-dead target ONCE for the whole batch (DNS ' +
7738
+ 'failure, connection refused, a 502/503/504 gateway error) — see --skip-preflight.')
7739
+ .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
7235
7740
  .option('--idempotency-key <token>', 'opaque idempotency token for the batch create (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
7236
7741
  .addHelpText('after', GLOBAL_OPTS_HINT)
7237
7742
  .action(async (cmdOpts, command) => {
@@ -7244,6 +7749,7 @@ export function createTestCommand(deps = {}) {
7244
7749
  wait: cmdOpts.wait === true,
7245
7750
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
7246
7751
  targetUrl: cmdOpts.targetUrl,
7752
+ skipPreflight: cmdOpts.skipPreflight === true,
7247
7753
  idempotencyKey: cmdOpts.idempotencyKey,
7248
7754
  }, deps);
7249
7755
  });
@@ -7452,7 +7958,15 @@ export function createTestCommand(deps = {}) {
7452
7958
  '\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
7453
7959
  '\nCtrl-C during --wait detaches only (the run keeps executing and billing);\n' +
7454
7960
  'stop it for real with: testsprite test cancel <run-id>')
7455
- .option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private IPs)')
7961
+ .option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private ' +
7962
+ 'IPs). Before triggering, a reachability preflight refuses an obviously-dead target (DNS ' +
7963
+ 'failure, connection refused, a 502/503/504 gateway error) so a doomed run never gets ' +
7964
+ 'billed. This CLI probes from wherever it runs, not from the Lambda that executes the ' +
7965
+ 'test, so it is a heuristic, not a guarantee — see --skip-preflight. Note: for a backend ' +
7966
+ 'test, --target-url itself is inert (its base URL is baked into its code) — but this bare ' +
7967
+ "`run` command has no way to know a test's type before triggering it, so the preflight " +
7968
+ 'still runs and can still refuse; use --skip-preflight if that surprises you.')
7969
+ .option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
7456
7970
  .option('--wait', 'poll until terminal status or --timeout elapses', false)
7457
7971
  .option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
7458
7972
  .option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
@@ -7463,8 +7977,8 @@ export function createTestCommand(deps = {}) {
7463
7977
  .option('--report <format>', 'with --all --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
7464
7978
  .option('--report-file <path>', 'output path for --report (atomic write)')
7465
7979
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
7466
- .option('--gh-output', 'with --all --wait: emit GitHub-native output (::error:: annotations per non-passed run; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
7467
- .option('--summary-file <path>', 'with --all --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
7980
+ .option('--gh-output', 'with --wait (single test or --all): emit GitHub-native output (::error:: annotations per non-passed run; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
7981
+ .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')
7468
7982
  .addHelpText('after', '\nDependency-aware fresh run (M4):\n' +
7469
7983
  ' testsprite test run --all --project <id> run all project tests in wave order\n' +
7470
7984
  ' TESTSPRITE_PROJECT_ID=<id> testsprite test run --all use env default project\n' +
@@ -7500,15 +8014,16 @@ export function createTestCommand(deps = {}) {
7500
8014
  wait: cmdOpts.wait === true,
7501
8015
  batchPath: isAll,
7502
8016
  });
7503
- // --gh-output / --summary-file reduce the terminal batch envelope, which
7504
- // only exists on the --all --wait path (without --wait the command returns
7505
- // after enqueueing). Anywhere else they would silently no-op — reject
7506
- // loudly (same rule as --filter and the JUnit report flags).
7507
- if (cmdOpts.ghOutput === true && (!isAll || cmdOpts.wait !== true)) {
7508
- throw localValidationError('gh-output', '--gh-output only applies with --all --wait (it reduces the terminal batch envelope). Remove --gh-output, or add --all --wait.');
8017
+ // --gh-output / --summary-file reduce a --wait run's terminal result into
8018
+ // the CI summary. They require --wait (without it the command returns after
8019
+ // enqueueing, before any terminal result exists) but apply to BOTH a single
8020
+ // <test-id> run and the --all batch. Without --wait they would silently
8021
+ // no-op — reject loudly (same rule as --filter and the JUnit report flags).
8022
+ if (cmdOpts.ghOutput === true && cmdOpts.wait !== true) {
8023
+ throw localValidationError('gh-output', '--gh-output requires --wait (it reduces the terminal run result). Add --wait.');
7509
8024
  }
7510
- if (cmdOpts.summaryFile !== undefined && (!isAll || cmdOpts.wait !== true)) {
7511
- throw localValidationError('summary-file', '--summary-file only applies with --all --wait (it reduces the terminal batch envelope). Remove --summary-file, or add --all --wait.');
8025
+ if (cmdOpts.summaryFile !== undefined && cmdOpts.wait !== true) {
8026
+ throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
7512
8027
  }
7513
8028
  if (isAll) {
7514
8029
  // --all path: wave-ordered fresh batch run.
@@ -7545,11 +8060,14 @@ export function createTestCommand(deps = {}) {
7545
8060
  ...resolveCommonOptions(command),
7546
8061
  testId: testIdArg,
7547
8062
  targetUrl: cmdOpts.targetUrl,
8063
+ skipPreflight: cmdOpts.skipPreflight === true,
7548
8064
  wait: cmdOpts.wait === true,
7549
8065
  timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
7550
8066
  // B2(c): tell runTestRun whether --timeout was explicitly provided.
7551
8067
  timeoutIsDefault: cmdOpts.timeout === undefined,
7552
8068
  idempotencyKey: cmdOpts.idempotencyKey,
8069
+ ghOutput: cmdOpts.ghOutput === true,
8070
+ summaryFile: cmdOpts.summaryFile,
7553
8071
  }, deps);
7554
8072
  });
7555
8073
  test
@@ -7634,6 +8152,8 @@ export function createTestCommand(deps = {}) {
7634
8152
  .option('--report <format>', 'with batch --wait: write a JUnit XML sidecar report after polling (accepted: junit)')
7635
8153
  .option('--report-file <path>', 'output path for --report (atomic write)')
7636
8154
  .option('--report-suite-name <name>', 'optional JUnit <testsuite name=...> override (default: testsprite:<projectId>)')
8155
+ .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')
8156
+ .option('--summary-file <path>', 'with batch --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
7637
8157
  .addHelpText('after', '\nNotes:\n' +
7638
8158
  ' • rerun replays a saved run/script and is MORE LENIENT than a fresh `test run`\n' +
7639
8159
  ' (auto-heal can pass steps that have drifted) — for strict scoring/regression,\n' +
@@ -7665,6 +8185,15 @@ export function createTestCommand(deps = {}) {
7665
8185
  wait: cmdOpts.wait === true,
7666
8186
  batchPath: isBatch,
7667
8187
  });
8188
+ // --gh-output / --summary-file reduce the batch-rerun --wait envelope, which
8189
+ // only exists on the batch (--all or 2+ ids) --wait path. Anywhere else they
8190
+ // would silently no-op — reject loudly (same rule as the JUnit report flags).
8191
+ if (cmdOpts.ghOutput === true && (!isBatch || cmdOpts.wait !== true)) {
8192
+ throw localValidationError('gh-output', '--gh-output requires a batch rerun with --wait (--all or 2+ test ids). Remove --gh-output, or add --all --wait.');
8193
+ }
8194
+ if (cmdOpts.summaryFile !== undefined && (!isBatch || cmdOpts.wait !== true)) {
8195
+ throw localValidationError('summary-file', '--summary-file requires a batch rerun with --wait (--all or 2+ test ids). Remove --summary-file, or add --all --wait.');
8196
+ }
7668
8197
  await runTestRerun({
7669
8198
  ...resolveCommonOptions(command),
7670
8199
  testIds,
@@ -7684,6 +8213,8 @@ export function createTestCommand(deps = {}) {
7684
8213
  report,
7685
8214
  reportFile: cmdOpts.reportFile,
7686
8215
  reportSuiteName: cmdOpts.reportSuiteName,
8216
+ ghOutput: cmdOpts.ghOutput === true,
8217
+ summaryFile: cmdOpts.summaryFile,
7687
8218
  }, deps);
7688
8219
  });
7689
8220
  // -------------------------------------------------------------------------