@testsprite/testsprite-cli 0.14.0 → 0.15.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 (40) hide show
  1. package/README.md +3 -1
  2. package/dist/commands/ci.d.ts +66 -17
  3. package/dist/commands/ci.js +466 -104
  4. package/dist/commands/doctor.d.ts +3 -0
  5. package/dist/commands/doctor.js +50 -9
  6. package/dist/commands/init.js +17 -3
  7. package/dist/commands/project.js +15 -1
  8. package/dist/commands/test.d.ts +74 -11
  9. package/dist/commands/test.js +579 -112
  10. package/dist/index.js +5 -1
  11. package/dist/lib/agent-targets.d.ts +8 -3
  12. package/dist/lib/agent-targets.js +15 -4
  13. package/dist/lib/ci-run.d.ts +11 -0
  14. package/dist/lib/ci-run.js +34 -0
  15. package/dist/lib/client-factory.d.ts +23 -0
  16. package/dist/lib/client-factory.js +7 -6
  17. package/dist/lib/config.d.ts +1 -0
  18. package/dist/lib/config.js +1 -1
  19. package/dist/lib/credentials.d.ts +0 -1
  20. package/dist/lib/credentials.js +51 -14
  21. package/dist/lib/dry-run/samples.js +42 -1
  22. package/dist/lib/first-suite-hint.d.ts +55 -0
  23. package/dist/lib/first-suite-hint.js +101 -0
  24. package/dist/lib/gh-output.d.ts +62 -4
  25. package/dist/lib/gh-output.js +149 -7
  26. package/dist/lib/github-context.d.ts +21 -0
  27. package/dist/lib/github-context.js +153 -0
  28. package/dist/lib/http.d.ts +10 -1
  29. package/dist/lib/http.js +9 -1
  30. package/dist/lib/plans.types.d.ts +1 -1
  31. package/dist/lib/response-schemas.d.ts +5 -1
  32. package/dist/lib/response-schemas.js +54 -0
  33. package/dist/lib/runs.types.d.ts +106 -0
  34. package/dist/lib/telemetry.d.ts +25 -1
  35. package/dist/lib/telemetry.js +45 -4
  36. package/dist/version.d.ts +1 -1
  37. package/dist/version.js +1 -1
  38. package/package.json +1 -1
  39. package/schemas/plan.schema.json +2 -2
  40. package/skills/testsprite-ci.skill.md +154 -0
@@ -12,17 +12,19 @@ import { assertContextIntegrity, buildMeta, pickCodeExtension, pickVideoExtensio
12
12
  import { findSample, findSampleOrThrow, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
13
13
  import { assertJUnitReportOptions, buildJUnitReport, durationSecondsBetween, resolveBatchReportProjectId, skippedJUnitResultsFromSummary, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
14
14
  import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, isAuthCode, localValidationError, } from '../lib/errors.js';
15
+ import { emptyProjectHint, emptyProjectNextStep } from '../lib/first-suite-hint.js';
15
16
  import { globalShutdown } from '../lib/interrupt.js';
16
- import { defaultSleep } from '../lib/poll-support.js';
17
+ import { defaultSleep, sleepUnlessInterrupted } from '../lib/poll-support.js';
17
18
  import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
18
19
  import { isStandingRateLimit, REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, } from '../lib/http.js';
19
20
  import { VERSION } from '../version.js';
20
21
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
21
22
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
22
23
  import { isTerminalStatus, pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
23
- import { batchOutcomeCounts, recordBatchOutcome, recordTelemetryExtras, } from '../lib/telemetry.js';
24
+ import { batchOutcomeCounts, ciRefusalOutcome, recordBatchOutcome, recordTelemetryExtras, } from '../lib/telemetry.js';
24
25
  import { PlanGenerationTimeoutError, runGenerationLadder } from '../lib/plan-poll.js';
25
26
  import { resolveWaitFailure, waitMemberError } from '../lib/wait-exit.js';
27
+ import { resolveCiRunFailure } from '../lib/ci-run.js';
26
28
  import { RUN_SOURCES } from '../lib/runs.types.js';
27
29
  import { classifyBillingRefusal } from '../lib/billing-refusal.js';
28
30
  import { allConflictsInFlight, billingConflictLink, insufficientCreditsConflictError, isAllCreditsRefusal, isPausedRefusal, pausedConflictError, summarizeConflicts, } from '../lib/conflict-reason.js';
@@ -38,7 +40,7 @@ import { createTicker } from '../lib/ticker.js';
38
40
  import { RateThrottle } from '../lib/rate-throttle.js';
39
41
  import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
40
42
  import { emitTargetUrlMismatchAdvisory } from '../lib/v3-advisory.js';
41
- import { emitCiArtifacts, isNonDispatchedStatus, summarizeAcceptedPayload, summarizeSingleRun, } from '../lib/gh-output.js';
43
+ import { emitCiArtifacts, isNonDispatchedStatus, emitCiStepOutputs, reconcileExecutionReportMarkdown, summarizeAcceptedPayload, summarizeSingleRun, emitExecutionReportOutputs, } from '../lib/gh-output.js';
42
44
  import { loadConfig, resolveProfileName } from '../lib/config.js';
43
45
  import { historyRetentionNote } from '../lib/history-retention.js';
44
46
  import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
@@ -444,9 +446,51 @@ export async function runList(opts, deps = {}) {
444
446
  noHeader: opts.noHeader,
445
447
  environment,
446
448
  }));
449
+ // An EMPTY project — nothing narrowed the page, no further page —
450
+ // is where a new user without a coding agent stalls. One stderr hint, text
451
+ // mode only, so stdout stays exactly "No tests." for pipes.
452
+ if (opts.output !== 'json' &&
453
+ page.items.length === 0 &&
454
+ !page.nextToken &&
455
+ opts.startingToken === undefined &&
456
+ opts.type === undefined &&
457
+ opts.createdFrom === undefined &&
458
+ opts.status === undefined) {
459
+ const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
460
+ stderrFn(emptyProjectHint(projectId));
461
+ }
447
462
  return page;
448
463
  }
449
464
  export const CLI_CREATE_PRIORITIES = ['p0', 'p1', 'p2', 'p3'];
465
+ /** Priority spellings accepted as input; reads return High/Medium/Low. */
466
+ export const CLI_PRIORITY_INPUTS = [...CLI_CREATE_PRIORITIES, 'high', 'medium', 'low'];
467
+ const PRIORITY_WIRE = {
468
+ p0: 'p0',
469
+ high: 'p0',
470
+ p1: 'p1',
471
+ medium: 'p1',
472
+ p2: 'p2',
473
+ low: 'p2',
474
+ p3: 'p2',
475
+ };
476
+ /**
477
+ * Normalise a priority input (p0-p3 or high/medium/low, any case) to the
478
+ * p0/p1/p2 wire value every backend accepts; p3 folds into p2 (Low).
479
+ * Returns undefined for anything else.
480
+ */
481
+ export function normalizePriority(raw) {
482
+ if (typeof raw !== 'string')
483
+ return undefined;
484
+ const key = raw.trim().toLowerCase();
485
+ // Own-property lookup: inherited names such as `constructor` must not pass as priorities.
486
+ return Object.hasOwn(PRIORITY_WIRE, key) ? PRIORITY_WIRE[key] : undefined;
487
+ }
488
+ /** Throws the standard enum error unless `raw` is an accepted priority input. */
489
+ function assertPriorityInput(field, raw, kind = 'field') {
490
+ if (normalizePriority(raw) === undefined) {
491
+ throw localValidationError(field, `must be one of: ${CLI_PRIORITY_INPUTS.join(', ')} (case-insensitive)`, [...CLI_PRIORITY_INPUTS], kind);
492
+ }
493
+ }
450
494
  /**
451
495
  * 350 KB inline-code cap. Mirrors `MAX_INLINE_CODE_BYTES` in the backend
452
496
  * (`CliTestsController`), which is sized to fit a full test row inside
@@ -647,11 +691,8 @@ export async function runCreate(opts, deps = {}) {
647
691
  'backend',
648
692
  ]);
649
693
  }
650
- if (opts.priority !== undefined && !CLI_CREATE_PRIORITIES.includes(opts.priority)) {
651
- throw localValidationError('priority', `must be one of: ${CLI_CREATE_PRIORITIES.join(', ')}`, [
652
- ...CLI_CREATE_PRIORITIES,
653
- ]);
654
- }
694
+ if (opts.priority !== undefined)
695
+ assertPriorityInput('priority', opts.priority);
655
696
  // M4 piece-2: --produces/--needs/--category are backend-only. FE plans have
656
697
  // no wave model; fail-fast client-side to match the backend's 400 reject and
657
698
  // save a round-trip.
@@ -695,7 +736,7 @@ export async function runCreate(opts, deps = {}) {
695
736
  type: opts.type,
696
737
  name: opts.name,
697
738
  description: opts.description,
698
- priority: opts.priority,
739
+ priority: normalizePriority(opts.priority),
699
740
  code,
700
741
  };
701
742
  if (opts.stepTimeoutMs !== undefined) {
@@ -1004,10 +1045,9 @@ const MAX_PLAN_STEPS_BODY_BYTES = 256 * 1024;
1004
1045
  * trip and matches the piece-6 spec's "server-side routing" decision.
1005
1046
  *
1006
1047
  * Concurrency: FE has no `codeVersion`, so updates are last-writer-
1007
- * wins by default. Pass `--expected-step-count <N>` to set
1008
- * `If-Match-Step-Count`; the server rejects with 412 if the current
1009
- * array length differs. Useful for defensive callers who want to
1010
- * detect concurrent edits without a separate read.
1048
+ * wins unless `--expected-step-count <N>` is passed, which sets
1049
+ * `If-Match-Step-Count`; the server rejects with 412 if the array length
1050
+ * differs.
1011
1051
  *
1012
1052
  * Idempotency: `cli-plan-put-<uuid>` is the default key, surfaced to
1013
1053
  * stderr so a transport retry can pin it.
@@ -1050,10 +1090,25 @@ export async function runPlanPut(opts, deps = {}) {
1050
1090
  },
1051
1091
  }, 412);
1052
1092
  }
1053
- const response = await client.put(`/tests/${encodeURIComponent(opts.testId)}/plan-steps`, {
1054
- body: { planSteps },
1055
- headers,
1056
- });
1093
+ let response;
1094
+ try {
1095
+ response = await client.put(`/tests/${encodeURIComponent(opts.testId)}/plan-steps`, {
1096
+ body: opts.force === true ? { planSteps, force: true } : { planSteps },
1097
+ headers,
1098
+ });
1099
+ }
1100
+ catch (err) {
1101
+ if (err instanceof ApiError && err.getDetail('reason') === 'structured_loss') {
1102
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1103
+ const losing = err.getDetail('losing');
1104
+ const indexes = err.getDetail('stepIndexes');
1105
+ const where = Array.isArray(indexes)
1106
+ ? ` (step ${indexes.map(i => (typeof i === 'number' ? i + 1 : String(i))).join(', ')})`
1107
+ : '';
1108
+ stderr(`${typeof losing === 'number' ? losing : 'Some'} step(s) would lose their structured fields${where}.`);
1109
+ }
1110
+ throw err;
1111
+ }
1057
1112
  out.print(response, data => renderPlanPutText(data));
1058
1113
  return response;
1059
1114
  }
@@ -1356,11 +1411,8 @@ export async function runUpdate(opts, deps = {}) {
1356
1411
  if (opts.description !== undefined && opts.description.length > 2000) {
1357
1412
  throw localValidationError('description', 'must be at most 2000 characters');
1358
1413
  }
1359
- if (opts.priority !== undefined && !CLI_CREATE_PRIORITIES.includes(opts.priority)) {
1360
- throw localValidationError('priority', `must be one of: ${CLI_CREATE_PRIORITIES.join(', ')}`, [
1361
- ...CLI_CREATE_PRIORITIES,
1362
- ]);
1363
- }
1414
+ if (opts.priority !== undefined)
1415
+ assertPriorityInput('priority', opts.priority);
1364
1416
  if (opts.stepTimeoutMs !== undefined && opts.clearStepTimeout === true) {
1365
1417
  throw localValidationError('step-timeout', '--step-timeout and --clear-step-timeout are mutually exclusive');
1366
1418
  }
@@ -1410,7 +1462,7 @@ export async function runUpdate(opts, deps = {}) {
1410
1462
  if (hasDescription)
1411
1463
  body.description = opts.description;
1412
1464
  if (hasPriority)
1413
- body.priority = opts.priority;
1465
+ body.priority = normalizePriority(opts.priority);
1414
1466
  if (hasProduces)
1415
1467
  body.produces = opts.produces;
1416
1468
  if (hasNeeds)
@@ -2134,7 +2186,7 @@ export async function runCreateFromPlan(opts, deps = {}) {
2134
2186
  type: plan.type,
2135
2187
  name: plan.name,
2136
2188
  description: plan.description,
2137
- priority: plan.priority,
2189
+ priority: normalizePriority(plan.priority),
2138
2190
  planSteps: plan.planSteps,
2139
2191
  };
2140
2192
  // Pre-charge reachability preflight — before the create POST
@@ -2349,7 +2401,7 @@ function assertPlanShape(parsed, context = {}) {
2349
2401
  throw localValidationError(`${prefix}description`, 'must be a string when present', undefined, 'field');
2350
2402
  }
2351
2403
  if (obj.priority !== undefined) {
2352
- requireEnum(`${prefix}priority`, obj.priority, CLI_CREATE_PRIORITIES);
2404
+ assertPriorityInput(`${prefix}priority`, obj.priority);
2353
2405
  }
2354
2406
  // `planSteps` missing is the single most common agent
2355
2407
  // hallucination: LLMs (Copilot included) reliably nest steps under
@@ -2413,7 +2465,7 @@ function collectPlanIssues(parsed, context = {}) {
2413
2465
  issues.push({ field: `${prefix}description`, reason: 'must be a string when present' });
2414
2466
  }
2415
2467
  if (obj.priority !== undefined) {
2416
- check(() => requireEnum(`${prefix}priority`, obj.priority, CLI_CREATE_PRIORITIES));
2468
+ check(() => assertPriorityInput(`${prefix}priority`, obj.priority));
2417
2469
  }
2418
2470
  check(() => requireArrayLength(`${prefix}planSteps`, obj.planSteps, {
2419
2471
  min: 1,
@@ -2522,7 +2574,9 @@ export async function runCreateBatch(opts, deps = {}) {
2522
2574
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
2523
2575
  stderrFn(`idempotency-key: ${idempotencyKey}`);
2524
2576
  }
2525
- const body = { tests: specs };
2577
+ const body = {
2578
+ tests: specs.map(spec => spec.priority === undefined ? spec : { ...spec, priority: normalizePriority(spec.priority) }),
2579
+ };
2526
2580
  const bodyBytes = Buffer.byteLength(JSON.stringify(body), 'utf8');
2527
2581
  if (bodyBytes > MAX_BATCH_BODY_BYTES) {
2528
2582
  throw ApiError.fromEnvelope({
@@ -5170,7 +5224,7 @@ function withRunDashboardUrl(run, apiUrl) {
5170
5224
  * atomic — no per-step breakdown exists; showing `0/0 (passed=0, failed=0)`
5171
5225
  * reads like a no-op rather than a passing/failing atomic result).
5172
5226
  */
5173
- function renderRunResponseText(run, { isBackend = false } = {}) {
5227
+ export function renderRunResponseText(run, { isBackend = false } = {}) {
5174
5228
  // P2-9: omit null fields (codeVersion/targetUrl) to match renderResultText
5175
5229
  // convention — literal "null" in text output confuses human operators.
5176
5230
  const lines = [
@@ -5219,6 +5273,9 @@ function renderRunResponseText(run, { isBackend = false } = {}) {
5219
5273
  // is an absent breakdown, not a breakdown of zero steps, so say that.
5220
5274
  lines.push(`steps n/a (no per-step breakdown reported)`);
5221
5275
  }
5276
+ if (run.replay?.path === 'refused') {
5277
+ lines.push(`replay refused${run.replay.reason ? ` (${run.replay.reason})` : ''}`);
5278
+ }
5222
5279
  // Closing pointer: where to inspect this run in the Portal (video, steps,
5223
5280
  // screenshots). Present only when withRunDashboardUrl could resolve it.
5224
5281
  if (run.dashboardUrl)
@@ -5394,6 +5451,56 @@ function isSameLoopbackPort(url, port) {
5394
5451
  return false;
5395
5452
  }
5396
5453
  }
5454
+ /**
5455
+ * The environment half of the 409 auto-resume gate, shared by the single run
5456
+ * and the `--all` batch: may the in-flight run stand in for the run this
5457
+ * invocation asked for? Resolves to the `--env` flag naming the verified
5458
+ * environment for a later retry (undefined when the run recorded none), or
5459
+ * throws `incompatibleRun(reason)`.
5460
+ *
5461
+ * `undefined` (no key at all) is a V2 run or a backend that predates
5462
+ * environments on run reads; `null` is a V3 row that explicitly names no
5463
+ * environment, OR one whose environment lookup failed and was swallowed
5464
+ * server-side. Only the former may attach unverified — treating `null` the
5465
+ * same way would let a failed lookup slip through the gate it exists to
5466
+ * enforce.
5467
+ */
5468
+ async function verifyInFlightRunEnvironment(inFlightRun, environment, listEnvironments, incompatibleRun) {
5469
+ const inFlightEnvironment = inFlightRun.environment;
5470
+ if (inFlightEnvironment === undefined) {
5471
+ if (environment !== undefined) {
5472
+ // --env was requested but this in-flight run has nothing recorded to
5473
+ // verify it against.
5474
+ throw incompatibleRun('its environment could not be verified');
5475
+ }
5476
+ // Restored 0.12.0 path: no environment recorded, none requested — attach.
5477
+ return undefined;
5478
+ }
5479
+ if (inFlightEnvironment === null ||
5480
+ typeof inFlightEnvironment.id !== 'string' ||
5481
+ inFlightEnvironment.id.length === 0) {
5482
+ throw incompatibleRun('its environment could not be verified');
5483
+ }
5484
+ let currentEnvironment;
5485
+ try {
5486
+ const listing = await listEnvironments(inFlightRun.projectId);
5487
+ currentEnvironment = listing.environments.find(row => environment === undefined ? row.isDefault : row.name === environment);
5488
+ }
5489
+ catch (listErr) {
5490
+ if (listErr instanceof InterruptError)
5491
+ throw listErr;
5492
+ throw incompatibleRun('its environment could not be verified');
5493
+ }
5494
+ if (typeof currentEnvironment?.id !== 'string' || currentEnvironment.id.length === 0) {
5495
+ // The listing succeeded but named nothing we can compare against — that
5496
+ // is unverified, not a proven mismatch.
5497
+ throw incompatibleRun('its environment could not be verified');
5498
+ }
5499
+ if (currentEnvironment.id !== inFlightEnvironment.id) {
5500
+ throw incompatibleRun('its environment does not match the requested environment');
5501
+ }
5502
+ return `--env ${currentEnvironment.name}`;
5503
+ }
5397
5504
  export async function runTestRun(opts, deps = {}) {
5398
5505
  assertIdempotencyKey(opts.idempotencyKey);
5399
5506
  const environment = normalizeEnvironmentName(opts.environment);
@@ -5691,7 +5798,6 @@ export async function runTestRun(opts, deps = {}) {
5691
5798
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
5692
5799
  // Set only when a verified environment names a concrete retry — the
5693
5800
  // no-environment-recorded attach path has nothing to name.
5694
- let retryFlags;
5695
5801
  const incompatibleRun = (reason) => new ApiError({
5696
5802
  code: 'CONFLICT',
5697
5803
  message: `Conflict: run ${currentRunId} is already in flight; ${reason}. This invocation cannot attach to it.`,
@@ -5708,47 +5814,7 @@ export async function runTestRun(opts, deps = {}) {
5708
5814
  throw readErr;
5709
5815
  throw incompatibleRun('its environment could not be verified');
5710
5816
  }
5711
- const inFlightEnvironment = inFlightRun.environment;
5712
- // `undefined` (no key at all) is a V2 run or a backend that predates
5713
- // environments on run reads; `null` is a V3 row that explicitly names no
5714
- // environment, OR one whose environment lookup failed and was
5715
- // swallowed server-side. Only the former may attach unverified —
5716
- // treating `null` the same way would let a failed lookup slip
5717
- // through the gate it exists to enforce.
5718
- if (inFlightEnvironment === undefined) {
5719
- if (environment !== undefined) {
5720
- // --env was requested but this in-flight run has nothing
5721
- // recorded to verify it against.
5722
- throw incompatibleRun('its environment could not be verified');
5723
- }
5724
- // Restored 0.12.0 path: no environment recorded, none requested — attach.
5725
- }
5726
- else if (inFlightEnvironment === null ||
5727
- typeof inFlightEnvironment.id !== 'string' ||
5728
- inFlightEnvironment.id.length === 0) {
5729
- throw incompatibleRun('its environment could not be verified');
5730
- }
5731
- else {
5732
- let currentEnvironment;
5733
- try {
5734
- const listing = await client.get(`/projects/${encodeURIComponent(inFlightRun.projectId)}/env`);
5735
- currentEnvironment = listing.environments.find(row => environment === undefined ? row.isDefault : row.name === environment);
5736
- }
5737
- catch (listErr) {
5738
- if (listErr instanceof InterruptError)
5739
- throw listErr;
5740
- throw incompatibleRun('its environment could not be verified');
5741
- }
5742
- if (typeof currentEnvironment?.id !== 'string' || currentEnvironment.id.length === 0) {
5743
- // The listing succeeded but named nothing we can compare against —
5744
- // that is unverified, not a proven mismatch.
5745
- throw incompatibleRun('its environment could not be verified');
5746
- }
5747
- if (currentEnvironment.id !== inFlightEnvironment.id) {
5748
- throw incompatibleRun('its environment does not match the requested environment');
5749
- }
5750
- retryFlags = `--env ${currentEnvironment.name}`;
5751
- }
5817
+ const retryFlags = await verifyInFlightRunEnvironment(inFlightRun, environment, projectId => client.get(`/projects/${encodeURIComponent(projectId)}/env`), incompatibleRun);
5752
5818
  // If the caller supplied --target-url, verify the in-flight run targets
5753
5819
  // the same URL. A mismatch means we would be reporting a different
5754
5820
  // environment's results as if our requested environment was tested.
@@ -6913,6 +6979,154 @@ async function cancelRunsBestEffort(client, runIds, stderrFn, label) {
6913
6979
  }
6914
6980
  }
6915
6981
  }
6982
+ /**
6983
+ * One line telling a backend-project batch what the integration phase will do
6984
+ * after the wave. Undefined when the backend sent no summary (older backend,
6985
+ * frontend project, or nothing to say).
6986
+ */
6987
+ function formatIntegrationSummary(integration) {
6988
+ if (integration === undefined || !integration.runsAfterWave)
6989
+ return undefined;
6990
+ const parts = [];
6991
+ if (integration.existing > 0) {
6992
+ parts.push(`${integration.existing} existing integration test${integration.existing !== 1 ? 's' : ''} run after this wave (0.2 credits each)`);
6993
+ }
6994
+ if (integration.mayGenerate)
6995
+ parts.push('new ones may be generated on a first run');
6996
+ if (parts.length === 0)
6997
+ return undefined;
6998
+ return `Integration phase: ${parts.join('; ')}.`;
6999
+ }
7000
+ const EXECUTION_REPORT_DEFAULT_TIMEOUT_SECONDS = 60;
7001
+ const EXECUTION_REPORT_DEFAULT_RETRY_SECONDS = 5;
7002
+ /**
7003
+ * Fetch the execution report — the content the GitHub App posts as its PR
7004
+ * comment — for the one execution this CI batch dispatched into.
7005
+ *
7006
+ * Best-effort by contract: the local results table is the fallback, so an
7007
+ * older backend (404), a report that is not ready within the budget, a
7008
+ * report for some other execution, or any other failure returns `undefined`
7009
+ * with one stderr line. An interrupt while waiting (the request or the retry
7010
+ * sleep — the scope is armed across both, so a first signal is a graceful
7011
+ * stop, not an immediate exit) also falls back, and is handed back in
7012
+ * `interrupted`: the batch is already finished, so its summary and outputs are
7013
+ * written first, then the caller rethrows it so the exit is the signal's
7014
+ * code. Reads nothing when `--no-execution-report`
7015
+ * was passed, when a run timed out (the execution is not terminal, so the
7016
+ * report could only arrive late), or unless EVERY accepted row names the same
7017
+ * execution (an older backend omits the id; a batch spanning several
7018
+ * executions gets one report per execution as a follow-up — a report for one
7019
+ * of them would read as the whole batch's).
7020
+ */
7021
+ async function fetchExecutionReport(client, accepted, results, opts, deps, stderrFn) {
7022
+ if (opts.ci?.executionReport === false || accepted.length === 0)
7023
+ return {};
7024
+ const executionIds = new Set(accepted.map(a => a.executionId));
7025
+ if (executionIds.size !== 1)
7026
+ return {};
7027
+ const executionId = [...executionIds][0];
7028
+ if (typeof executionId !== 'string' || executionId.length === 0)
7029
+ return {};
7030
+ if (results.some(r => r.status === 'timeout')) {
7031
+ stderrFn('[ci run] a run timed out, so the execution is not finished; the job summary uses the local results table');
7032
+ return {};
7033
+ }
7034
+ const timeoutSeconds = opts.ci?.executionReportTimeoutSeconds ?? EXECUTION_REPORT_DEFAULT_TIMEOUT_SECONDS;
7035
+ const deadlineMs = Date.now() + timeoutSeconds * 1000;
7036
+ const ac = new AbortController();
7037
+ const timer = setTimeout(() => ac.abort(), timeoutSeconds * 1000);
7038
+ const sleepFn = deps.sleep ?? defaultSleep;
7039
+ const shutdown = shutdownOf(deps);
7040
+ // Every `pollRunUntilTerminal` has disarmed by now, so without this scope a
7041
+ // SIGINT/SIGTERM during the retry sleep would take the signal handler's
7042
+ // disarmed path and exit at once — no summary, no outputs.
7043
+ const disarm = shutdown.arm();
7044
+ try {
7045
+ for (;;) {
7046
+ // No automatic retries: the deadline below is the only retry policy.
7047
+ const res = await client.getExecutionReport(executionId, { signal: ac.signal, retry: false });
7048
+ if (res.ready && res.report && typeof res.markdown === 'string') {
7049
+ if (res.report.executionId !== executionId) {
7050
+ stderrFn(`[ci run] execution report names execution ${res.report.executionId}, not ${executionId}; the job summary uses the local results table`);
7051
+ return {};
7052
+ }
7053
+ return { ready: { report: res.report, markdown: res.markdown } };
7054
+ }
7055
+ const remainingMs = deadlineMs - Date.now();
7056
+ if (remainingMs <= 0)
7057
+ break;
7058
+ const retrySeconds = Math.max(1, res.retryAfterSeconds ?? EXECUTION_REPORT_DEFAULT_RETRY_SECONDS);
7059
+ // Interruptible: a SIGINT/SIGTERM here means "stop waiting for the
7060
+ // report", not "drop the finished batch's summary and outputs".
7061
+ await sleepUnlessInterrupted(sleepFn, Math.min(remainingMs, retrySeconds * 1000), shutdown.signal);
7062
+ if (Date.now() >= deadlineMs)
7063
+ break;
7064
+ }
7065
+ stderrFn(`[ci run] execution report not ready within ${timeoutSeconds}s; the job summary uses the local results table`);
7066
+ }
7067
+ catch (err) {
7068
+ if (err instanceof InterruptError) {
7069
+ stderrFn('[ci run] interrupted while waiting for the execution report; the job summary uses the local results table');
7070
+ return { interrupted: err };
7071
+ }
7072
+ stderrFn(`[ci run] execution report unavailable (${err instanceof Error ? err.message : String(err)}); the job summary uses the local results table`);
7073
+ }
7074
+ finally {
7075
+ clearTimeout(timer);
7076
+ disarm();
7077
+ }
7078
+ return {};
7079
+ }
7080
+ /** Publish all CI surfaces from one summary before applying the CI gate. */
7081
+ async function finishCiBatch(payload, opts, deps, nameByTestId, executionError,
7082
+ /** The accepted rows with poll timing, for the JUnit report only. */
7083
+ junitResults = payload.accepted,
7084
+ /** The server's execution report, when the backend provided one in time. */
7085
+ executionReport) {
7086
+ // A CI gate that dispatched nothing is its own funnel outcome (green only
7087
+ // with --allow-empty); the gated case is recorded by the caller, which holds
7088
+ // the execution id.
7089
+ if (payload.accepted.length === 0)
7090
+ recordTelemetryExtras({ ciRunOutcome: 'empty' });
7091
+ const summary = summarizeAcceptedPayload(JSON.stringify(payload), {
7092
+ foldSkippedBuckets: true,
7093
+ notFoundNote: 'test not found (not dispatched)',
7094
+ });
7095
+ if (executionReport)
7096
+ summary.executionReport = executionReport.report;
7097
+ const io = {
7098
+ env: deps.env ?? process.env,
7099
+ stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
7100
+ stderr: deps.stderr ?? ((line) => process.stderr.write(`${line}\n`)),
7101
+ };
7102
+ makeOutput(opts.output, deps).print({ ...payload, summary }, () => `CI run: ${summary.passed}/${summary.total} passed, ${summary.failed} failed, ` +
7103
+ `${summary.skipped} skipped, ${summary.timedOut} timed out`);
7104
+ emitCiArtifacts(summary, opts, io, 'ci run', {
7105
+ markdown: executionReport
7106
+ ? reconcileExecutionReportMarkdown(summary, executionReport)
7107
+ : undefined,
7108
+ });
7109
+ emitCiStepOutputs(summary, io);
7110
+ if (executionReport)
7111
+ emitExecutionReportOutputs(executionReport, io);
7112
+ let reportError;
7113
+ try {
7114
+ // Same rows as `test run --all`: every non-dispatched member is a skipped
7115
+ // testcase, so the report never claims a partial batch ran in full.
7116
+ await writeBatchJUnitReportIfRequested(opts, [...junitResults, ...skippedJUnitResultsFromSummary(summary, payload.accepted)], nameByTestId);
7117
+ }
7118
+ catch (err) {
7119
+ reportError = err;
7120
+ io.stderr(`[ci run] could not write the JUnit report: ${err instanceof Error ? err.message : String(err)}`);
7121
+ }
7122
+ if (executionError)
7123
+ throw executionError;
7124
+ const failure = resolveCiRunFailure(summary, payload.accepted, { ...opts, failOnSkipped: opts.ci?.failOnSkipped }, payload.conflicts);
7125
+ if (failure)
7126
+ throw failure;
7127
+ if (reportError)
7128
+ throw reportError;
7129
+ }
6916
7130
  /** Human explanation for a zero-dispatch batch, from what the engine skipped. */
6917
7131
  function zeroDispatchReason(skippedFrontend, skippedIntegration) {
6918
7132
  const parts = [];
@@ -6940,7 +7154,12 @@ function zeroDispatchReason(skippedFrontend, skippedIntegration) {
6940
7154
  * `reason` is the human explanation shown in the annotation and the throw.
6941
7155
  */
6942
7156
  async function finishZeroDispatchBatch(params) {
6943
- const { reason, skipped, allowEmpty, opts, deps, stderrFn, label = 'run' } = params;
7157
+ const { reason, skipped, allowEmpty, opts, deps, stderrFn, label = 'run', emptyProject = false, projectId, local, } = params;
7158
+ // Text mode only: under --output json neither the error envelope's message
7159
+ // nor stderr carries the sentence (review feedback).
7160
+ const nextStep = emptyProject && projectId !== undefined && opts.output !== 'json'
7161
+ ? emptyProjectNextStep(projectId, local)
7162
+ : undefined;
6944
7163
  const runs = skipped.length > 0
6945
7164
  ? skipped.map(testId => ({ testId, status: 'skipped', error: reason }))
6946
7165
  : [{ testId: '(no tests)', status: 'no_tests', error: reason }];
@@ -6977,10 +7196,15 @@ async function finishZeroDispatchBatch(params) {
6977
7196
  }
6978
7197
  if (allowEmpty) {
6979
7198
  stderrFn(`[${label}] 0 tests dispatched (${reason}); --allow-empty set — exiting 0.`);
7199
+ if (nextStep !== undefined)
7200
+ stderrFn(`[hint] ${nextStep}`);
6980
7201
  return;
6981
7202
  }
7203
+ // The pointer rides inside the message so it prints AFTER "Error:", in
7204
+ // reading order — a CLIError has no nextAction slot of its own.
6982
7205
  throw new CLIError(`No tests were dispatched — ${reason}. A CI gate that passes on zero tests is unsafe; ` +
6983
- `pass --allow-empty to exit 0 intentionally.`, 5);
7206
+ `pass --allow-empty to exit 0 intentionally.` +
7207
+ (nextStep !== undefined ? ` ${nextStep}` : ''), 5);
6984
7208
  }
6985
7209
  /**
6986
7210
  * `test run --all --project <id>` — M4 piece-2.
@@ -6994,6 +7218,8 @@ export async function runTestRunAll(opts, deps = {}) {
6994
7218
  const environment = normalizeEnvironmentName(opts.environment);
6995
7219
  const projectId = resolveProjectId(opts.projectId, deps);
6996
7220
  requireProjectId(projectId);
7221
+ // Carry the resolved id into reports, including when it came from the env.
7222
+ opts = { ...opts, projectId };
6997
7223
  if (!Number.isInteger(opts.maxConcurrency) ||
6998
7224
  opts.maxConcurrency < 1 ||
6999
7225
  opts.maxConcurrency > MAX_BATCH_CONCURRENCY) {
@@ -7060,10 +7286,10 @@ export async function runTestRunAll(opts, deps = {}) {
7060
7286
  idempotencyKey,
7061
7287
  ...(opts.wait ? { thenPoll: '/api/cli/v1/runs/<run-id>?waitSeconds=25' } : {}),
7062
7288
  };
7063
- if (opts.report === 'junit' && opts.reportFile !== undefined) {
7289
+ if (!opts.ci && opts.report === 'junit' && opts.reportFile !== undefined) {
7064
7290
  await writeJUnitReportFile(opts.reportFile, sampleJUnitReportXml(opts.projectId, opts.reportSuiteName));
7065
7291
  }
7066
- out.print(opts.targetUrl !== undefined ? envelope : (batchRunSample ?? envelope));
7292
+ out.print(opts.ci || opts.targetUrl !== undefined ? envelope : (batchRunSample ?? envelope));
7067
7293
  return undefined;
7068
7294
  }
7069
7295
  // Probe once before dispatch. A preview still warming up can use
@@ -7145,11 +7371,52 @@ export async function runTestRunAll(opts, deps = {}) {
7145
7371
  ...(opts.autoHeal === false ? { autoHeal: false } : {}),
7146
7372
  ...(environment !== undefined ? { environment } : {}),
7147
7373
  ...(opts.targetUrl !== undefined ? { targetUrl: opts.targetUrl } : {}),
7374
+ ...(opts.admission !== undefined ? { admission: opts.admission } : {}),
7375
+ ...(opts.previewName !== undefined ? { previewName: opts.previewName } : {}),
7376
+ ...(opts.githubTrigger !== undefined ? { githubTrigger: opts.githubTrigger } : {}),
7148
7377
  };
7378
+ /**
7379
+ * The fields a dispatch leg must see echoed back. An older backend strips
7380
+ * what it does not know and runs anyway — against the wrong target, with a
7381
+ * cut batch, or as a plain override where a preview environment was asked
7382
+ * for — so each is confirmed exactly, on every leg.
7383
+ */
7384
+ function unhonoredDispatchFields(response) {
7385
+ const out = [];
7386
+ if (opts.targetUrl !== undefined && response.targetUrl !== opts.targetUrl) {
7387
+ out.push({
7388
+ field: 'targetUrl',
7389
+ reason: 'target-url-not-honored',
7390
+ message: 'This backend did not confirm --target-url on the batch run; the accepted runs may have used another URL.',
7391
+ nextAction: 'Use a backend that supports batch target URL overrides, or retry without --target-url.',
7392
+ });
7393
+ }
7394
+ if (opts.admission !== undefined && response.admission !== opts.admission) {
7395
+ out.push({
7396
+ field: 'admission',
7397
+ reason: 'admission-not-honored',
7398
+ message: 'This backend did not confirm the single-execution admission mode; the batch may have been cut to the per-key budget.',
7399
+ nextAction: 'Use a backend that supports ci run (v0.20.0 or later).',
7400
+ });
7401
+ }
7402
+ if (opts.previewName !== undefined && response.previewName !== opts.previewName) {
7403
+ out.push({
7404
+ field: 'previewName',
7405
+ reason: 'preview-not-honored',
7406
+ message: 'This backend did not confirm the CI preview environment; the accepted runs may have run as a plain target override instead of in github-pr-<N>.',
7407
+ nextAction: 'Use a backend that supports ci run (v0.20.0 or later).',
7408
+ });
7409
+ }
7410
+ return out;
7411
+ }
7149
7412
  async function assertBatchTargetEcho(response, previouslyAccepted) {
7150
- if (opts.targetUrl === undefined || response.targetUrl === opts.targetUrl)
7413
+ const unhonored = unhonoredDispatchFields(response);
7414
+ if (unhonored.length === 0)
7151
7415
  return;
7152
- const message = 'This backend did not confirm --target-url on the batch run; the accepted runs may have used another URL.';
7416
+ const { field, reason, message, nextAction } = unhonored[0];
7417
+ // Every unhonored echo means a backend that predates the CI contract.
7418
+ if (opts.ci)
7419
+ recordTelemetryExtras({ ciRunOutcome: 'refused_admission' });
7153
7420
  // Only this response's runs are unconfirmed. Runs an earlier leg confirmed
7154
7421
  // keep running against the right URL; they are reported as not awaited,
7155
7422
  // never cancelled.
@@ -7158,7 +7425,7 @@ export async function runTestRunAll(opts, deps = {}) {
7158
7425
  const confirmed = dedupeBatchRunFreshAccepted([...previouslyAccepted]).deduped.filter(item => !unconfirmedIds.has(item.runId));
7159
7426
  await cancelRunsBestEffort(client, unconfirmed.map(item => item.runId), stderrFn, 'run');
7160
7427
  if (opts.wait) {
7161
- const notAwaited = 'Not awaited: the batch stopped because a later dispatch did not confirm --target-url. ' +
7428
+ const notAwaited = `Not awaited: the batch stopped because a later dispatch did not confirm ${field}. ` +
7162
7429
  'This run was confirmed and is still running; read it with testsprite test wait <run-id>.';
7163
7430
  const summary = summarizeAcceptedPayload(JSON.stringify({
7164
7431
  accepted: [
@@ -7177,11 +7444,15 @@ export async function runTestRunAll(opts, deps = {}) {
7177
7444
  summary.failed = 1;
7178
7445
  summary.runs.push({ testId: '(batch)', status: 'error', error: message });
7179
7446
  }
7180
- emitCiArtifacts(summary, opts, {
7447
+ const io = {
7181
7448
  env: deps.env ?? process.env,
7182
7449
  stdout: deps.stdout ?? (line => process.stdout.write(`${line}\n`)),
7183
7450
  stderr: stderrFn,
7184
- }, 'run');
7451
+ };
7452
+ emitCiArtifacts(summary, opts, io, 'run');
7453
+ // `ci run` promises its step outputs before the exit code, refusal included.
7454
+ if (opts.ci)
7455
+ emitCiStepOutputs(summary, io);
7185
7456
  try {
7186
7457
  await writeBatchJUnitReportIfRequested(opts, summary.runs.map(row => ({
7187
7458
  testId: row.testId,
@@ -7200,9 +7471,9 @@ export async function runTestRunAll(opts, deps = {}) {
7200
7471
  error: {
7201
7472
  code: 'UNSUPPORTED',
7202
7473
  message,
7203
- nextAction: 'Use a backend that supports batch target URL overrides, or retry without --target-url.',
7474
+ nextAction,
7204
7475
  requestId: 'local',
7205
- details: { field: 'targetUrl', reason: 'target-url-not-honored' },
7476
+ details: { field, reason },
7206
7477
  },
7207
7478
  });
7208
7479
  }
@@ -7223,13 +7494,18 @@ export async function runTestRunAll(opts, deps = {}) {
7223
7494
  testIds = filtered.map(t => t.id);
7224
7495
  if (testIds.length === 0) {
7225
7496
  stderrFn(`No tests found in project ${projectId} matching --filter "${opts.nameFilter}" — nothing to run.`);
7226
- out.print({
7497
+ const emptyResponse = {
7227
7498
  accepted: [],
7228
7499
  conflicts: [],
7229
7500
  deferred: [],
7230
7501
  skippedFrontend: [],
7231
7502
  skippedIntegration: [],
7232
- });
7503
+ };
7504
+ if (opts.ci) {
7505
+ await finishCiBatch({ ...emptyResponse, accepted: [] }, opts, deps);
7506
+ return undefined;
7507
+ }
7508
+ out.print(emptyResponse);
7233
7509
  // Zero-dispatch (a --filter that matched nothing): emit the CI artifacts
7234
7510
  // and fail unless --allow-empty, so a renamed test can't turn a filtered
7235
7511
  // gate permanently green. Returns here only under --allow-empty.
@@ -7247,15 +7523,40 @@ export async function runTestRunAll(opts, deps = {}) {
7247
7523
  }
7248
7524
  // When no --filter, omit testIds → server runs ALL tests in the project
7249
7525
  // (BE tests on the legacy V2 wave engine; FE + BE on the V3 unified engine).
7250
- const batchResp = await client.triggerBatchRunFresh({
7251
- projectId,
7252
- ...(testIds !== undefined ? { testIds } : {}),
7253
- ...dispatchFields,
7254
- }, { idempotencyKey });
7526
+ let batchResp;
7527
+ try {
7528
+ batchResp = await client.triggerBatchRunFresh({
7529
+ projectId,
7530
+ ...(testIds !== undefined ? { testIds } : {}),
7531
+ ...dispatchFields,
7532
+ }, { idempotencyKey });
7533
+ }
7534
+ catch (err) {
7535
+ // A whole-batch refusal under `ci run` is a funnel outcome — every API
7536
+ // refusal gets one (validation by the server's `details.reason`, 402/403
7537
+ // as billing, the rest as other).
7538
+ if (opts.ci && err instanceof ApiError) {
7539
+ recordTelemetryExtras({ ciRunOutcome: ciRefusalOutcome(err) });
7540
+ }
7541
+ throw err;
7542
+ }
7255
7543
  // Shared across every dispatch this invocation makes — see the `reported` param.
7256
7544
  const optOutReported = new Set();
7257
7545
  warnIfOptOutIgnored(opts.autoHeal, batchResp.autoHeal, stderrFn, 'these runs', optOutReported);
7258
7546
  await assertBatchTargetEcho(batchResp, []);
7547
+ if (opts.ci && batchResp.accepted.length > 0) {
7548
+ // Recorded as soon as the dispatch is confirmed, not after the wait: a job
7549
+ // cancelled mid-wait (a re-push under shape B's concurrency group, a manual
7550
+ // cancel, the runner's timeout) exits through InterruptError, and the
7551
+ // `abort` event must still say the gate dispatched and which execution
7552
+ // keeps running. `reportReady` is added once the report wait finishes.
7553
+ const dispatchedExecutionIds = new Set(batchResp.accepted.map(a => a.executionId));
7554
+ const dispatchedExecutionId = dispatchedExecutionIds.size === 1 ? [...dispatchedExecutionIds][0] : undefined;
7555
+ recordTelemetryExtras({
7556
+ ciRunOutcome: 'gated',
7557
+ ...(typeof dispatchedExecutionId === 'string' ? { executionId: dispatchedExecutionId } : {}),
7558
+ });
7559
+ }
7259
7560
  // Project-level "watch it here" link. A V3 backend sends it (string, or
7260
7561
  // `null` when no single page exists — e.g. a `--all` that fanned out over
7261
7562
  // several sibling projects); an older backend / the V2 engine omits the key,
@@ -7268,7 +7569,9 @@ export async function runTestRunAll(opts, deps = {}) {
7268
7569
  let accepted = batchResp.accepted.slice();
7269
7570
  let deferred = batchResp.deferred.slice();
7270
7571
  let conflicts = batchResp.conflicts.slice();
7271
- const { skippedFrontend, skippedIntegration } = batchResp;
7572
+ const skippedFrontend = batchResp.skippedFrontend.slice();
7573
+ const skippedIntegration = batchResp.skippedIntegration.slice();
7574
+ let retryError;
7272
7575
  // Print advisory for skipped FE tests.
7273
7576
  if (skippedFrontend.length > 0) {
7274
7577
  stderrFn(`[advisory] ${skippedFrontend.length} frontend test${skippedFrontend.length !== 1 ? 's' : ''} skipped — the batch run endpoint uses the BE-only wave engine. ` +
@@ -7285,6 +7588,9 @@ export async function runTestRunAll(opts, deps = {}) {
7285
7588
  if (deferred.length > 0) {
7286
7589
  stderrFn(`Rate-deferred testIds (retry later): ${deferred.map(d => d.testId).join(' ')}`);
7287
7590
  }
7591
+ const integrationLine = formatIntegrationSummary(batchResp.integration);
7592
+ if (integrationLine !== undefined)
7593
+ stderrFn(integrationLine);
7288
7594
  stderrFn(`Dispatched ${accepted.length} test${accepted.length !== 1 ? 's' : ''}` +
7289
7595
  `${skippedFrontend.length > 0 ? ` (${skippedFrontend.length} FE skipped)` : ''}` +
7290
7596
  `${conflicts.length > 0 ? ` (${conflicts.length} conflict${conflicts.length !== 1 ? 's' : ''})` : ''}` +
@@ -7303,6 +7609,7 @@ export async function runTestRunAll(opts, deps = {}) {
7303
7609
  deferred,
7304
7610
  skippedFrontend,
7305
7611
  skippedIntegration,
7612
+ ...(batchResp.integration !== undefined ? { integration: batchResp.integration } : {}),
7306
7613
  };
7307
7614
  out.print(printResp, data => {
7308
7615
  const r = data;
@@ -7375,6 +7682,10 @@ export async function runTestRunAll(opts, deps = {}) {
7375
7682
  opts,
7376
7683
  deps,
7377
7684
  stderrFn,
7685
+ emptyProject: skippedFrontend.length === 0 &&
7686
+ skippedIntegration.length === 0 &&
7687
+ opts.nameFilter === undefined,
7688
+ projectId,
7378
7689
  });
7379
7690
  }
7380
7691
  // [P2] Return post-retry state so programmatic callers and the create-chain
@@ -7450,6 +7761,8 @@ export async function runTestRunAll(opts, deps = {}) {
7450
7761
  if (err instanceof ApiError &&
7451
7762
  (err.code === 'UNSUPPORTED' || err.code === 'PRECONDITION_FAILED'))
7452
7763
  throw err;
7764
+ if (opts.ci)
7765
+ retryError = err;
7453
7766
  // If the retry itself errors, surface it and stop retrying.
7454
7767
  stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
7455
7768
  break;
@@ -7462,6 +7775,8 @@ export async function runTestRunAll(opts, deps = {}) {
7462
7775
  const newlyAccepted = retryResp.accepted;
7463
7776
  const newlyDeferred = retryResp.deferred;
7464
7777
  const newlyConflicted = retryResp.conflicts;
7778
+ skippedFrontend.push(...retryResp.skippedFrontend);
7779
+ skippedIntegration.push(...retryResp.skippedIntegration);
7465
7780
  if (newlyAccepted.length > 0) {
7466
7781
  stderrFn(`[deferred-retry] attempt ${attempt}: ${newlyAccepted.length} test${newlyAccepted.length !== 1 ? 's' : ''} now accepted.`);
7467
7782
  // A retry asks only for the still-deferred ids but can come back with
@@ -7481,7 +7796,7 @@ export async function runTestRunAll(opts, deps = {}) {
7481
7796
  }
7482
7797
  deferred = newlyDeferred;
7483
7798
  if (deferred.length === 0) {
7484
- stderrFn(`[deferred-retry] attempt ${attempt}: all previously-deferred tests accepted.`);
7799
+ stderrFn(`[deferred-retry] attempt ${attempt}: no tests remain rate-deferred.`);
7485
7800
  }
7486
7801
  }
7487
7802
  // Gap B: an already-running case is not a dead end under --wait. A conflict
@@ -7489,8 +7804,10 @@ export async function runTestRunAll(opts, deps = {}) {
7489
7804
  // (auto-resume) — the "concurrent job already started this test" case should
7490
7805
  // wait for that run's result, not fail the batch. Conflicts without a
7491
7806
  // resolvable in-flight run stay hard (nothing to wait on).
7492
- const resumableConflicts = conflicts.filter(c => c.currentRunId);
7493
- const hardConflicts = conflicts.filter(c => !c.currentRunId);
7807
+ // An in-flight run may belong to another deployment/environment. CI can
7808
+ // only use runs accepted by this invocation to judge its own change.
7809
+ const resumableConflicts = opts.ci ? [] : conflicts.filter(c => c.currentRunId);
7810
+ const hardConflicts = opts.ci ? conflicts : conflicts.filter(c => !c.currentRunId);
7494
7811
  // Only hard conflicts remain "conflicts" for the final accounting/exit; the
7495
7812
  // resumable ones become polled results below.
7496
7813
  conflicts = hardConflicts;
@@ -7507,14 +7824,38 @@ export async function runTestRunAll(opts, deps = {}) {
7507
7824
  // many-in-flight-conflicts scenario finding 1 is about, so a serial N round-trip
7508
7825
  // fetch (with no deadline bound) would eat the budget finding 1's fix protects.
7509
7826
  const resolveSignal = AbortSignal.timeout(Math.max(1, batchDeadlineMs - Date.now()));
7510
- const resumableEntries = await Promise.all(resumableConflicts.map(async (c) => {
7827
+ // One environment listing per project for the whole batch (the gate below
7828
+ // compares environment ids, not names, so it needs the project's list).
7829
+ const envListings = new Map();
7830
+ const listEnvironments = (projectId) => {
7831
+ let listing = envListings.get(projectId);
7832
+ if (!listing) {
7833
+ listing = client.get(`/projects/${encodeURIComponent(projectId)}/env`, { signal: resolveSignal });
7834
+ envListings.set(projectId, listing);
7835
+ }
7836
+ return listing;
7837
+ };
7838
+ const resumedOrRefused = await Promise.all(resumableConflicts.map(async (c) => {
7511
7839
  const inFlightRunId = c.currentRunId;
7840
+ // The same gate the single run applies before adopting a 409: an
7841
+ // in-flight run on another environment (a PR gate's `github-pr-N`
7842
+ // clone, say) or another target URL is somebody else's run, and its
7843
+ // verdict must not be reported as this invocation's. Refused runs stay
7844
+ // hard conflicts — polled by nobody here — instead of being attached.
7845
+ const refused = (reason) => ({
7846
+ refused: {
7847
+ ...c,
7848
+ reason: 'in_flight',
7849
+ message: `not attached: ${reason}`,
7850
+ },
7851
+ });
7512
7852
  // Conservative default if the run can't be read: floor at NOW (never the
7513
7853
  // epoch) so the fallback still can't accept an older run's result.
7514
7854
  let notBefore = new Date().toISOString();
7515
7855
  let startedBy;
7856
+ let inFlight;
7516
7857
  try {
7517
- const inFlight = await client.getRun(inFlightRunId, { signal: resolveSignal });
7858
+ inFlight = await client.getRun(inFlightRunId, { signal: resolveSignal });
7518
7859
  if (inFlight.createdAt)
7519
7860
  notBefore = inFlight.createdAt;
7520
7861
  startedBy = inFlight.source || inFlight.createdFrom || undefined;
@@ -7524,9 +7865,46 @@ export async function runTestRunAll(opts, deps = {}) {
7524
7865
  throw err;
7525
7866
  // keep the conservative now() floor (fetch failed or the signal aborted)
7526
7867
  }
7868
+ if (inFlight) {
7869
+ try {
7870
+ await verifyInFlightRunEnvironment(inFlight, opts.environment, listEnvironments, reason => new ApiError({
7871
+ code: 'CONFLICT',
7872
+ message: reason,
7873
+ nextAction: `testsprite test wait ${inFlightRunId}`,
7874
+ requestId: '',
7875
+ details: { reason: 'run_in_flight', currentRunId: inFlightRunId },
7876
+ }));
7877
+ }
7878
+ catch (err) {
7879
+ if (err instanceof InterruptError)
7880
+ throw err;
7881
+ if (err instanceof ApiError && err.code === 'CONFLICT')
7882
+ return refused(err.message);
7883
+ throw err;
7884
+ }
7885
+ if (opts.targetUrl !== undefined && inFlight.targetUrl !== opts.targetUrl) {
7886
+ return refused(`it targets ${inFlight.targetUrl || 'an unreported URL'}, not ${opts.targetUrl}`);
7887
+ }
7888
+ }
7889
+ else if (opts.environment !== undefined || opts.targetUrl !== undefined) {
7890
+ // An environment or target was asked for and the run could not be
7891
+ // read: unverified, so not ours to attach to (fail closed, as the
7892
+ // single run does).
7893
+ return refused('its environment could not be verified');
7894
+ }
7527
7895
  stderrFn(`[auto-resume] ${c.testId} — polling in-flight run ${inFlightRunId}${startedBy ? ` (started by ${startedBy})` : ''} to a verdict instead of failing`);
7528
- return { testId: c.testId, runId: inFlightRunId, enqueuedAt: notBefore };
7896
+ return { entry: { testId: c.testId, runId: inFlightRunId, enqueuedAt: notBefore } };
7529
7897
  }));
7898
+ const resumableEntries = [];
7899
+ for (const outcome of resumedOrRefused) {
7900
+ if ('entry' in outcome) {
7901
+ resumableEntries.push(outcome.entry);
7902
+ }
7903
+ else {
7904
+ stderrFn(`[auto-resume] ${outcome.refused.testId} — in-flight run ${outcome.refused.currentRunId} ${outcome.refused.message?.replace(/^not attached: /, '')}; not attaching (testsprite test wait ${outcome.refused.currentRunId} to follow it)`);
7905
+ conflicts.push(outcome.refused);
7906
+ }
7907
+ }
7530
7908
  // --wait: fan-out poll each accepted run by its runId, PLUS each auto-resumed
7531
7909
  // in-flight run. Every accepted entry carries a real runId (the backend routes
7532
7910
  // slot-claim failures to conflicts[]); the resumed entries reuse the existing
@@ -7548,14 +7926,20 @@ export async function runTestRunAll(opts, deps = {}) {
7548
7926
  deferred,
7549
7927
  skippedFrontend,
7550
7928
  skippedIntegration,
7929
+ ...(batchResp.integration !== undefined ? { integration: batchResp.integration } : {}),
7551
7930
  };
7552
- out.print(finalResp);
7931
+ if (!opts.ci)
7932
+ out.print(finalResp);
7553
7933
  recordBatchOutcome({
7554
7934
  accepted: accepted.length,
7555
7935
  conflicts,
7556
7936
  deferred: deferred.length,
7557
7937
  skipped: skippedFrontend.length + skippedIntegration.length,
7558
7938
  });
7939
+ if (opts.ci) {
7940
+ await finishCiBatch({ ...finalResp, accepted: [] }, opts, deps, undefined, retryError);
7941
+ return { ...batchResp, ...finalResp };
7942
+ }
7559
7943
  // Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
7560
7944
  // mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
7561
7945
  // Emit the deferred/conflict summary + annotations first so CI shows them (the
@@ -7603,6 +7987,10 @@ export async function runTestRunAll(opts, deps = {}) {
7603
7987
  opts,
7604
7988
  deps,
7605
7989
  stderrFn,
7990
+ emptyProject: skippedFrontend.length === 0 &&
7991
+ skippedIntegration.length === 0 &&
7992
+ opts.nameFilter === undefined,
7993
+ projectId,
7606
7994
  });
7607
7995
  // [P2] Return post-retry state (reached only under --allow-empty).
7608
7996
  return { ...batchResp, accepted, deferred, conflicts };
@@ -7659,11 +8047,22 @@ export async function runTestRunAll(opts, deps = {}) {
7659
8047
  ...(typeof finalRun.executionUrl === 'string'
7660
8048
  ? { executionUrl: finalRun.executionUrl }
7661
8049
  : {}),
8050
+ ...(opts.ci && finalRun.error
8051
+ ? { error: { code: 'INTERNAL', message: finalRun.error, exitCode: 1 } }
8052
+ : {}),
7662
8053
  };
7663
8054
  }
7664
8055
  catch (err) {
7665
8056
  if (err instanceof InterruptError)
7666
8057
  throw err;
8058
+ if (opts.ci && err instanceof ApiError) {
8059
+ return {
8060
+ testId: entry.testId,
8061
+ runId,
8062
+ status: 'error',
8063
+ error: { code: err.code, message: err.message, exitCode: err.exitCode },
8064
+ };
8065
+ }
7667
8066
  if (err instanceof TimeoutError)
7668
8067
  deps.onWaitTimeout?.({ reason: 'wait_timeout' });
7669
8068
  // fall through to the timeout result below
@@ -7712,6 +8111,9 @@ export async function runTestRunAll(opts, deps = {}) {
7712
8111
  ...(typeof finalRun.executionUrl === 'string'
7713
8112
  ? { executionUrl: finalRun.executionUrl }
7714
8113
  : {}),
8114
+ ...(opts.ci && finalRun.error
8115
+ ? { error: { code: 'INTERNAL', message: finalRun.error, exitCode: 1 } }
8116
+ : {}),
7715
8117
  startedAt: finalRun.startedAt,
7716
8118
  finishedAt: finalRun.finishedAt,
7717
8119
  };
@@ -7821,6 +8223,7 @@ export async function runTestRunAll(opts, deps = {}) {
7821
8223
  deferred,
7822
8224
  skippedFrontend,
7823
8225
  skippedIntegration,
8226
+ ...(batchResp.integration !== undefined ? { integration: batchResp.integration } : {}),
7824
8227
  summary: {
7825
8228
  passed,
7826
8229
  failed,
@@ -7834,14 +8237,15 @@ export async function runTestRunAll(opts, deps = {}) {
7834
8237
  ? await buildTestNameMap(client, opts.projectId)
7835
8238
  : undefined;
7836
8239
  const ciSummary = summarizeAcceptedPayload(JSON.stringify(jsonPayload));
7837
- await writeBatchJUnitReportIfRequested(opts, [
7838
- ...freshRunResults.map(r => ({
7839
- ...r,
7840
- ...(r.runId ? reportTiming.get(r.runId) : {}),
7841
- })),
7842
- ...skippedJUnitResultsFromSummary(ciSummary, freshRunResults),
7843
- ], freshNameMap);
7844
- out.print(jsonPayload);
8240
+ // JUnit rows carry the poll timing the stdout envelope deliberately omits.
8241
+ const timedResults = freshRunResults.map(r => ({
8242
+ ...r,
8243
+ ...(r.runId ? reportTiming.get(r.runId) : {}),
8244
+ }));
8245
+ if (!opts.ci) {
8246
+ await writeBatchJUnitReportIfRequested(opts, [...timedResults, ...skippedJUnitResultsFromSummary(ciSummary, freshRunResults)], freshNameMap);
8247
+ out.print(jsonPayload);
8248
+ }
7845
8249
  recordBatchOutcome({
7846
8250
  accepted: accepted.length,
7847
8251
  conflicts,
@@ -7849,6 +8253,38 @@ export async function runTestRunAll(opts, deps = {}) {
7849
8253
  skipped: skippedFrontend.length + skippedIntegration.length,
7850
8254
  results: freshRunResults,
7851
8255
  });
8256
+ if (opts.ci) {
8257
+ // The report is read before the envelope prints so it lands in `--output
8258
+ // json`, `--summary-file` and the job summary alike.
8259
+ const { ready: executionReport, interrupted } = await fetchExecutionReport(client, accepted, freshRunResults, opts, deps, stderrFn);
8260
+ // Telemetry: the gate ran; name the execution (when the batch names exactly
8261
+ // one) so the event joins to the server's report, and whether that report
8262
+ // made it into the job summary.
8263
+ const gatedExecutionIds = new Set(accepted.map(a => a.executionId));
8264
+ const gatedExecutionId = gatedExecutionIds.size === 1 ? [...gatedExecutionIds][0] : undefined;
8265
+ if (accepted.length > 0) {
8266
+ recordTelemetryExtras({
8267
+ ciRunOutcome: 'gated',
8268
+ ...(typeof gatedExecutionId === 'string' ? { executionId: gatedExecutionId } : {}),
8269
+ reportReady: executionReport !== undefined,
8270
+ });
8271
+ }
8272
+ let gateError;
8273
+ try {
8274
+ await finishCiBatch(jsonPayload, opts, deps, freshNameMap, retryError, timedResults, executionReport);
8275
+ }
8276
+ catch (err) {
8277
+ gateError = err;
8278
+ }
8279
+ // The summary and outputs are written either way; a signal that cut the
8280
+ // report wait short still ends the process with its own exit code (130/143),
8281
+ // never the gate's 0.
8282
+ if (interrupted)
8283
+ throw interrupted;
8284
+ if (gateError !== undefined)
8285
+ throw gateError;
8286
+ return { ...batchResp, accepted, deferred, conflicts, skippedFrontend, skippedIntegration };
8287
+ }
7852
8288
  // CI-native output layer (issue #99): emitted before the gate throws below so
7853
8289
  // the artifacts land even when the batch exits non-zero. The summary file is a
7854
8290
  // machine artifact written regardless of --output mode; stdout stays owned by
@@ -8227,6 +8663,17 @@ export async function runTestRunLocalBatch(opts, deps = {}) {
8227
8663
  opts,
8228
8664
  deps,
8229
8665
  stderrFn,
8666
+ // A project with only backend tests is not empty: they were skipped, not absent.
8667
+ emptyProject: opts.all && skipped.length === 0 && opts.nameFilter === undefined,
8668
+ projectId,
8669
+ local: {
8670
+ // An automatic target was resolved from a saved environment; its port
8671
+ // is that environment's, so the suggestion names the environment.
8672
+ ...(opts.resolvedTarget?.automatic ? {} : { host: opts.localHost, port: opts.localPort }),
8673
+ targetUrl: opts.targetUrl,
8674
+ environment: opts.environment ??
8675
+ (opts.resolvedTarget?.automatic ? opts.resolvedTarget.environmentName : undefined),
8676
+ },
8230
8677
  });
8231
8678
  return;
8232
8679
  }
@@ -10499,7 +10946,7 @@ export function createTestCommand(deps = {}) {
10499
10946
  .option('--type <type>', 'frontend|backend')
10500
10947
  .option('--name <name>', 'human-readable test name (becomes `title` in storage)')
10501
10948
  .option('--description <text>', 'optional human description (≤ 2000 chars)')
10502
- .option('--priority <prio>', 'optional priority — one of: p0, p1, p2, p3')
10949
+ .option('--priority <prio>', 'optional priority: p0/high, p1/medium, p2/low (p3 = low)')
10503
10950
  .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
10504
10951
  .option('--code-file <path>', 'file containing the test code (≤ 350 KB)')
10505
10952
  .option('--plan-from <path>', 'JSON file with the full FE test definition — projectId, type, name, planSteps[] all live in the file ' +
@@ -10596,7 +11043,7 @@ export function createTestCommand(deps = {}) {
10596
11043
  type: parseEnumFlag(cmdOpts.type, 'type', TEST_TYPES),
10597
11044
  name: cmdOpts.name,
10598
11045
  description: cmdOpts.description,
10599
- priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
11046
+ priority: parsePriorityFlag(cmdOpts.priority),
10600
11047
  stepTimeoutMs: parseStepTimeoutFlag(cmdOpts.stepTimeout, 'step-timeout'),
10601
11048
  codeFile: cmdOpts.codeFile,
10602
11049
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -10780,7 +11227,7 @@ export function createTestCommand(deps = {}) {
10780
11227
  .description('Update test metadata — name, description, priority, step timeout')
10781
11228
  .option('--name <name>', 'new human-readable test name')
10782
11229
  .option('--description <text>', 'new human description (≤ 2000 chars)')
10783
- .option('--priority <prio>', 'new priority — one of: p0, p1, p2, p3')
11230
+ .option('--priority <prio>', 'new priority: p0/high, p1/medium, p2/low (p3 = low)')
10784
11231
  .option('--step-timeout <ms>', 'per-test step timeout in milliseconds (1-60000); applied by the execution engine to every step of this test')
10785
11232
  .option('--clear-step-timeout', 'clear the per-test step timeout and restore execution engine defaults', false)
10786
11233
  .option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering.', (val, prev) => [...(prev ?? []), val], [])
@@ -10797,7 +11244,7 @@ export function createTestCommand(deps = {}) {
10797
11244
  testId,
10798
11245
  name: cmdOpts.name,
10799
11246
  description: cmdOpts.description,
10800
- priority: parseEnumFlag(cmdOpts.priority, 'priority', CLI_CREATE_PRIORITIES),
11247
+ priority: parsePriorityFlag(cmdOpts.priority),
10801
11248
  stepTimeoutMs: parseStepTimeoutFlag(cmdOpts.stepTimeout, 'step-timeout'),
10802
11249
  clearStepTimeout: cmdOpts.clearStepTimeout === true,
10803
11250
  produces: cmdOpts.produces,
@@ -11605,6 +12052,12 @@ function parseEnumFlag(raw, flagName, accepted) {
11605
12052
  }
11606
12053
  return raw;
11607
12054
  }
12055
+ function parsePriorityFlag(raw) {
12056
+ if (raw === undefined)
12057
+ return undefined;
12058
+ assertPriorityInput('priority', raw, 'flag');
12059
+ return raw;
12060
+ }
11608
12061
  function parseNumericFlag(raw, flagName) {
11609
12062
  if (raw === undefined)
11610
12063
  return undefined;
@@ -12006,6 +12459,9 @@ async function readPresignedBody(url, out, deps, shutdownSignal) {
12006
12459
  throw new TransportError(`Failed mid-download of presigned code body: ${message}`);
12007
12460
  }
12008
12461
  }
12462
+ function renderTestTypeCell(test) {
12463
+ return test.isIntegration === true ? `${test.type}/int` : test.type;
12464
+ }
12009
12465
  const TEST_LIST_COLUMNS = [
12010
12466
  {
12011
12467
  header: 'ID',
@@ -12017,7 +12473,11 @@ const TEST_LIST_COLUMNS = [
12017
12473
  width: rows => Math.max(4, ...rows.map(test => test.name.length)),
12018
12474
  render: test => test.name,
12019
12475
  },
12020
- { header: 'TYPE', width: 8, render: test => test.type },
12476
+ {
12477
+ header: 'TYPE',
12478
+ width: rows => Math.max(8, ...rows.map(test => renderTestTypeCell(test).length)),
12479
+ render: renderTestTypeCell,
12480
+ },
12021
12481
  { header: 'FROM', width: 6, render: test => test.createdFrom },
12022
12482
  { header: 'STATUS', width: 9, render: test => test.status },
12023
12483
  {
@@ -12031,7 +12491,7 @@ const TEST_LIST_COLUMNS = [
12031
12491
  render: test => test.headlineEnvironment?.name ?? '-',
12032
12492
  },
12033
12493
  ];
12034
- function renderTestListText(page, options = {}) {
12494
+ export function renderTestListText(page, options = {}) {
12035
12495
  const note = options.environment === undefined || options.noHeader
12036
12496
  ? []
12037
12497
  : [`Frontend test status requested for environment '${options.environment}'.`];
@@ -12091,8 +12551,13 @@ function renderTestText(t) {
12091
12551
  const fields = step;
12092
12552
  const type = typeof fields.type === 'string' ? fields.type : 'step';
12093
12553
  const description = typeof fields.description === 'string' ? fields.description : '(no description)';
12094
- lines.push(` ${index + 1}. [${type}] ${description}`);
12554
+ const mark = fields.structured === true ? '*' : ' ';
12555
+ lines.push(`${mark} ${index + 1}. [${type}] ${description}`);
12095
12556
  });
12557
+ const structuredCount = planSteps.filter(step => typeof step === 'object' && step !== null && step.structured === true).length;
12558
+ if (structuredCount > 0) {
12559
+ lines.push(`* ${structuredCount} step(s) carry structured fields; \`plan put\` keeps them only for unchanged steps.`);
12560
+ }
12096
12561
  }
12097
12562
  if (typeof t.stepTimeoutMs === 'number') {
12098
12563
  lines.push(`stepTimeout: ${t.stepTimeoutMs} ms (applies to every step)`);
@@ -13365,7 +13830,8 @@ function createTestPlanCommand(deps) {
13365
13830
  .command('put <test-id>')
13366
13831
  .description("Replace an FE test's planSteps[] (BE tests return 400 → use 'test code put')")
13367
13832
  .option('--steps <path>', 'JSON file with { planSteps: [...] } (FE-only, ≤ 200 steps, ≤ 256 KB)')
13368
- .option('--expected-step-count <n>', 'optional defensive concurrency check; server rejects with 412 when the current length differs')
13833
+ .option('--expected-step-count <n>', 'pin the step count the server must still have; 412 when it differs')
13834
+ .option('--force', 'replace even if steps edited in the Portal would lose their structured fields')
13369
13835
  .option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
13370
13836
  .option('--dry-run-simulate-error <code>', 'With --dry-run: synthesise an error envelope to preview the error path. Supported: PRECONDITION_FAILED (412).')
13371
13837
  .addHelpText('after', '\nDry-run note: --dry-run always returns the happy response shape.\n' +
@@ -13382,6 +13848,7 @@ function createTestPlanCommand(deps) {
13382
13848
  testId,
13383
13849
  stepsFile: cmdOpts.steps,
13384
13850
  expectedStepCount: parseNumericFlag(cmdOpts.expectedStepCount, 'expected-step-count'),
13851
+ force: cmdOpts.force === true ? true : undefined,
13385
13852
  idempotencyKey: cmdOpts.idempotencyKey,
13386
13853
  dryRunSimulateError: simulateError === 'PRECONDITION_FAILED' ? 'PRECONDITION_FAILED' : undefined,
13387
13854
  }, deps);