@testsprite/testsprite-cli 0.16.0 → 0.17.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 (206) hide show
  1. package/README.md +51 -147
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +48 -63
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +38 -54
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +293 -487
  8. package/dist/commands/conversation.d.ts +27 -0
  9. package/dist/commands/conversation.js +702 -0
  10. package/dist/commands/doctor.d.ts +5 -1
  11. package/dist/commands/doctor.js +129 -34
  12. package/dist/commands/init.d.ts +4 -45
  13. package/dist/commands/init.js +108 -66
  14. package/dist/commands/project-env.d.ts +62 -2
  15. package/dist/commands/project-env.js +388 -37
  16. package/dist/commands/project-sign-in.d.ts +0 -48
  17. package/dist/commands/project-sign-in.js +1 -229
  18. package/dist/commands/project.d.ts +15 -186
  19. package/dist/commands/project.js +89 -924
  20. package/dist/commands/result.d.ts +10 -0
  21. package/dist/commands/result.js +215 -0
  22. package/dist/commands/schedule.d.ts +0 -29
  23. package/dist/commands/schedule.js +28 -87
  24. package/dist/commands/test.d.ts +301 -1816
  25. package/dist/commands/test.js +1951 -13902
  26. package/dist/commands/testlist.d.ts +128 -5
  27. package/dist/commands/testlist.js +269 -339
  28. package/dist/commands/tunnel.d.ts +2 -2
  29. package/dist/commands/tunnel.js +23 -19
  30. package/dist/commands/usage.d.ts +12 -45
  31. package/dist/commands/usage.js +50 -131
  32. package/dist/index.js +182 -104
  33. package/dist/lib/agent-detect.js +9 -5
  34. package/dist/lib/agent-targets.d.ts +21 -2
  35. package/dist/lib/agent-targets.js +88 -11
  36. package/dist/lib/args.d.ts +13 -0
  37. package/dist/lib/args.js +49 -0
  38. package/dist/lib/basic-auth.d.ts +3 -0
  39. package/dist/lib/basic-auth.js +15 -0
  40. package/dist/lib/billing-refusal.js +4 -3
  41. package/dist/lib/ci-linkage.d.ts +4 -82
  42. package/dist/lib/ci-linkage.js +4 -157
  43. package/dist/lib/ci-run.js +1 -1
  44. package/dist/lib/client-factory.d.ts +10 -2
  45. package/dist/lib/client-factory.js +38 -26
  46. package/dist/lib/commit-signal.d.ts +65 -0
  47. package/dist/lib/commit-signal.js +305 -0
  48. package/dist/lib/concurrency-limiter.d.ts +6 -0
  49. package/dist/lib/concurrency-limiter.js +29 -0
  50. package/dist/lib/config.js +10 -5
  51. package/dist/lib/conflict-reason.d.ts +9 -3
  52. package/dist/lib/conflict-reason.js +6 -3
  53. package/dist/lib/conversation/answers.d.ts +9 -0
  54. package/dist/lib/conversation/answers.js +49 -0
  55. package/dist/lib/conversation/api.d.ts +71 -0
  56. package/dist/lib/conversation/api.js +150 -0
  57. package/dist/lib/conversation/change.d.ts +31 -0
  58. package/dist/lib/conversation/change.js +124 -0
  59. package/dist/lib/conversation/context.d.ts +19 -0
  60. package/dist/lib/conversation/context.js +70 -0
  61. package/dist/lib/conversation/environment.d.ts +15 -0
  62. package/dist/lib/conversation/environment.js +33 -0
  63. package/dist/lib/conversation/follow.d.ts +24 -0
  64. package/dist/lib/conversation/follow.js +42 -0
  65. package/dist/lib/conversation/render.d.ts +33 -0
  66. package/dist/lib/conversation/render.js +315 -0
  67. package/dist/lib/conversation/title.d.ts +2 -0
  68. package/dist/lib/conversation/title.js +18 -0
  69. package/dist/lib/conversation/types.d.ts +156 -0
  70. package/dist/lib/conversation/types.js +6 -0
  71. package/dist/lib/credentials.js +67 -11
  72. package/dist/lib/cron.d.ts +1 -1
  73. package/dist/lib/cron.js +2 -2
  74. package/dist/lib/dispatch-stop.d.ts +20 -0
  75. package/dist/lib/dispatch-stop.js +30 -0
  76. package/dist/lib/download.d.ts +71 -0
  77. package/dist/lib/download.js +274 -0
  78. package/dist/lib/dry-run/fetch.d.ts +10 -0
  79. package/dist/lib/dry-run/fetch.js +20 -0
  80. package/dist/lib/dry-run/samples.d.ts +6 -34
  81. package/dist/lib/dry-run/samples.js +375 -747
  82. package/dist/lib/environment-tunnel.d.ts +16 -27
  83. package/dist/lib/environment-tunnel.js +161 -154
  84. package/dist/lib/errors.d.ts +20 -4
  85. package/dist/lib/errors.js +36 -16
  86. package/dist/lib/facade.d.ts +7 -29
  87. package/dist/lib/facade.js +7 -36
  88. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  89. package/dist/lib/failing-fe-resolver.js +47 -132
  90. package/dist/lib/first-suite-hint.d.ts +16 -22
  91. package/dist/lib/first-suite-hint.js +38 -47
  92. package/dist/lib/gh-output.d.ts +76 -21
  93. package/dist/lib/gh-output.js +171 -90
  94. package/dist/lib/git-utils.d.ts +56 -0
  95. package/dist/lib/git-utils.js +212 -0
  96. package/dist/lib/github-context.d.ts +2 -0
  97. package/dist/lib/github-context.js +40 -8
  98. package/dist/lib/history-retention.d.ts +6 -2
  99. package/dist/lib/history-retention.js +10 -7
  100. package/dist/lib/http.d.ts +58 -134
  101. package/dist/lib/http.js +352 -289
  102. package/dist/lib/interrupt.d.ts +14 -8
  103. package/dist/lib/interrupt.js +28 -10
  104. package/dist/lib/junit-report.d.ts +57 -4
  105. package/dist/lib/junit-report.js +202 -32
  106. package/dist/lib/local-target.d.ts +3 -3
  107. package/dist/lib/local-target.js +3 -3
  108. package/dist/lib/output.d.ts +1 -40
  109. package/dist/lib/output.js +11 -49
  110. package/dist/lib/pagination.d.ts +2 -5
  111. package/dist/lib/pagination.js +2 -5
  112. package/dist/lib/presigned-url.d.ts +22 -0
  113. package/dist/lib/presigned-url.js +90 -0
  114. package/dist/lib/prompt.js +36 -2
  115. package/dist/lib/proxy.js +2 -1
  116. package/dist/lib/redact.d.ts +2 -2
  117. package/dist/lib/redact.js +3 -4
  118. package/dist/lib/removed-commands.d.ts +18 -0
  119. package/dist/lib/removed-commands.js +154 -0
  120. package/dist/lib/render-error.d.ts +31 -6
  121. package/dist/lib/render-error.js +88 -25
  122. package/dist/lib/response-schemas.d.ts +38 -30
  123. package/dist/lib/response-schemas.js +207 -207
  124. package/dist/lib/result/api.d.ts +24 -0
  125. package/dist/lib/result/api.js +28 -0
  126. package/dist/lib/result/evidence.d.ts +71 -0
  127. package/dist/lib/result/evidence.js +420 -0
  128. package/dist/lib/result/render.d.ts +20 -0
  129. package/dist/lib/result/render.js +194 -0
  130. package/dist/lib/result/types.d.ts +122 -0
  131. package/dist/lib/result/types.js +19 -0
  132. package/dist/lib/run-output.d.ts +275 -0
  133. package/dist/lib/run-output.js +227 -0
  134. package/dist/lib/run-render.d.ts +101 -0
  135. package/dist/lib/run-render.js +183 -0
  136. package/dist/lib/run-wait.d.ts +192 -0
  137. package/dist/lib/run-wait.js +452 -0
  138. package/dist/lib/runs.types.d.ts +118 -367
  139. package/dist/lib/runs.types.js +0 -14
  140. package/dist/lib/secret-file.d.ts +1 -1
  141. package/dist/lib/secret-file.js +11 -2
  142. package/dist/lib/skill-nudge.d.ts +7 -27
  143. package/dist/lib/skill-nudge.js +9 -37
  144. package/dist/lib/target-path.d.ts +15 -0
  145. package/dist/lib/target-path.js +35 -0
  146. package/dist/lib/target-url-advisory.d.ts +19 -0
  147. package/dist/lib/target-url-advisory.js +31 -0
  148. package/dist/lib/target-url-preflight.d.ts +9 -0
  149. package/dist/lib/target-url-preflight.js +214 -106
  150. package/dist/lib/target-url.d.ts +1 -1
  151. package/dist/lib/target-url.js +6 -16
  152. package/dist/lib/telemetry.d.ts +31 -11
  153. package/dist/lib/telemetry.js +37 -8
  154. package/dist/lib/terminal-text.d.ts +41 -0
  155. package/dist/lib/terminal-text.js +127 -0
  156. package/dist/lib/testlist.types.d.ts +16 -8
  157. package/dist/lib/testlist.types.js +1 -1
  158. package/dist/lib/text-equality.d.ts +2 -0
  159. package/dist/lib/text-equality.js +5 -0
  160. package/dist/lib/text-file.d.ts +16 -0
  161. package/dist/lib/text-file.js +41 -0
  162. package/dist/lib/text-table.d.ts +46 -0
  163. package/dist/lib/text-table.js +72 -4
  164. package/dist/lib/ticker.d.ts +9 -2
  165. package/dist/lib/ticker.js +16 -3
  166. package/dist/lib/transport-failure.d.ts +22 -0
  167. package/dist/lib/transport-failure.js +126 -0
  168. package/dist/lib/tunnel-session.d.ts +7 -1
  169. package/dist/lib/tunnel-session.js +22 -9
  170. package/dist/lib/update-check.js +3 -2
  171. package/dist/lib/url-template.d.ts +43 -0
  172. package/dist/lib/url-template.js +151 -0
  173. package/dist/lib/validate.d.ts +0 -64
  174. package/dist/lib/validate.js +2 -131
  175. package/dist/lib/version-notice.js +4 -3
  176. package/dist/lib/wait-exit.d.ts +37 -2
  177. package/dist/lib/wait-exit.js +88 -30
  178. package/dist/lib/workspace-status.js +10 -2
  179. package/dist/version.d.ts +1 -1
  180. package/dist/version.js +1 -1
  181. package/package.json +2 -3
  182. package/skills/testsprite-ci.skill.md +48 -18
  183. package/skills/testsprite-onboard.skill.md +66 -151
  184. package/skills/testsprite-verify.codex.md +50 -52
  185. package/skills/testsprite-verify.skill.md +184 -351
  186. package/dist/lib/browser.d.ts +0 -6
  187. package/dist/lib/browser.js +0 -54
  188. package/dist/lib/bundle.d.ts +0 -234
  189. package/dist/lib/bundle.js +0 -781
  190. package/dist/lib/deprecate.d.ts +0 -32
  191. package/dist/lib/deprecate.js +0 -39
  192. package/dist/lib/flaky.d.ts +0 -91
  193. package/dist/lib/flaky.js +0 -71
  194. package/dist/lib/plan-poll.d.ts +0 -171
  195. package/dist/lib/plan-poll.js +0 -441
  196. package/dist/lib/plans.types.d.ts +0 -130
  197. package/dist/lib/plans.types.js +0 -31
  198. package/dist/lib/poll.d.ts +0 -100
  199. package/dist/lib/poll.js +0 -290
  200. package/dist/lib/rate-throttle.d.ts +0 -49
  201. package/dist/lib/rate-throttle.js +0 -75
  202. package/dist/lib/run-progress.d.ts +0 -41
  203. package/dist/lib/run-progress.js +0 -56
  204. package/dist/lib/v3-advisory.d.ts +0 -55
  205. package/dist/lib/v3-advisory.js +0 -74
  206. package/schemas/plan.schema.json +0 -61
@@ -1,18 +1,23 @@
1
- import { promises as nodeFs } from 'node:fs';
1
+ import { appendFileSync, promises as nodeFs } from 'node:fs';
2
2
  import { spawnSync as nodeSpawnSync } from 'node:child_process';
3
3
  import * as path from 'node:path';
4
4
  import { Command } from 'commander';
5
- import { makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
5
+ import { equalIgnoringCrlf } from '../lib/text-equality.js';
6
+ import { makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
6
7
  import { ApiError, CLIError, localValidationError } from '../lib/errors.js';
7
8
  import { loadConfig, resolveProfileName } from '../lib/config.js';
8
9
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
10
+ import { inspectTargetPath } from '../lib/target-path.js';
9
11
  import { assertNotLocal } from '../lib/target-url.js';
10
- import { classifyLinkage, isValidRepoSlug, parseDeploymentsPayload, parseRepoSlug, } from '../lib/ci-linkage.js';
11
12
  import { ciRefusalOutcome, recordTelemetryExtras } from '../lib/telemetry.js';
12
- import { runTestRunAll } from './test.js';
13
- import { emitCiStepOutputs } from '../lib/gh-output.js';
14
- import { previewEnvironmentName, readGithubRunContext } from '../lib/github-context.js';
13
+ import { parseNameFilter, runTestRunAll, } from './test.js';
14
+ import { emitCiStepOutputs, escapeCommandData } from '../lib/gh-output.js';
15
+ import { previewEnvironmentName, readGithubRunContext, } from '../lib/github-context.js';
16
+ import { waitForCommitSignal } from '../lib/commit-signal.js';
17
+ import { missingPlaceholders, renderUrlTemplate, unsafeHostPlaceholders, validateUrlTemplate, } from '../lib/url-template.js';
18
+ import { globalShutdown } from '../lib/interrupt.js';
15
19
  import { parseJUnitReportFormat } from '../lib/junit-report.js';
20
+ import { terminalSafeWriter } from '../lib/terminal-text.js';
16
21
  // ── constants ────────────────────────────────────────────────────────────────
17
22
  /** Platforms `ci init` can scaffold. One today; the positional arg leaves room. */
18
23
  const SUPPORTED_PLATFORMS = ['github'];
@@ -20,7 +25,7 @@ const SUPPORTED_PLATFORMS = ['github'];
20
25
  const DEFAULT_WORKFLOW_PATH = '.github/workflows/testsprite.yml';
21
26
  /** Where GitHub Actions picks workflows up from; `--path` must stay inside it. */
22
27
  const WORKFLOWS_DIR = '.github/workflows';
23
- /** Default terminal-verdict wait, matching the CLI's own `test run` default. */
28
+ /** Default terminal-verdict wait, matching the CLI's own `run` default. */
24
29
  const DEFAULT_TIMEOUT_SECONDS = 600;
25
30
  /** The repo secret the generated workflow reads the API key from. */
26
31
  const API_KEY_SECRET_NAME = 'TESTSPRITE_API_KEY';
@@ -36,6 +41,20 @@ const SUMMARY_FILE = 'testsprite-summary.json';
36
41
  * whether the generated workflow needs an explicit `endpoint-url`. */
37
42
  const DEFAULT_API_URL = 'https://api.testsprite.com';
38
43
  const defaultCiFs = {
44
+ async lstat(target) {
45
+ try {
46
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- inspect each component before writing the caller-selected workflow path.
47
+ const stat = await nodeFs.lstat(target);
48
+ return { isFile: stat.isFile(), isSymbolicLink: stat.isSymbolicLink() };
49
+ }
50
+ catch (error) {
51
+ if (error.code === 'ENOENT')
52
+ return null;
53
+ throw error;
54
+ }
55
+ },
56
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- resolve the repository and workflow symlink for containment validation.
57
+ realpath: target => nodeFs.realpath(target),
39
58
  // `target`/`dir` are the workflow output path (default `.github/workflows/testsprite.yml`,
40
59
  // or the caller's `--path`), resolved from cwd — a scaffold target the user is writing into
41
60
  // their own repo, never external/network input. Same risk profile as agent-install scaffolding.
@@ -55,7 +74,6 @@ const defaultSpawn = (cmd, args, opts) => nodeSpawnSync(cmd, args, {
55
74
  input: opts.input,
56
75
  cwd: opts.cwd,
57
76
  encoding: 'utf8',
58
- shell: opts.shell ?? false,
59
77
  windowsHide: true,
60
78
  });
61
79
  // ── helpers ──────────────────────────────────────────────────────────────────
@@ -146,6 +164,13 @@ export function buildGithubWorkflow(input) {
146
164
  assertSafeWorkflowValue('env', input.environment);
147
165
  if (input.endpointUrl)
148
166
  assertSafeWorkflowValue('endpoint-url', input.endpointUrl);
167
+ // All generated workflows live directly under .github/workflows/. Keep the
168
+ // readable filename, including its extension; escape rather than discard
169
+ // punctuation so distinct filenames cannot collapse to the same slug.
170
+ // GitHub compares concurrency group names case-insensitively, so uppercase
171
+ // letters are escaped too (keeping existing %XX escapes intact): otherwise
172
+ // TestSprite.yml and testsprite.yml would share a group.
173
+ const workflowSlug = encodeURIComponent(path.posix.basename(input.workflowPath)).replace(/%[0-9A-F]{2}|[A-Z]/g, match => (match.startsWith('%') ? match : `%${match.charCodeAt(0).toString(16).toUpperCase()}`));
149
174
  const envLines = [
150
175
  ` ${API_KEY_SECRET_NAME}: \${{ secrets.${API_KEY_SECRET_NAME} }}`,
151
176
  ' # ci run looks up the PR behind a deployment_status event with this token.',
@@ -183,6 +208,8 @@ permissions:
183
208
 
184
209
  jobs:
185
210
  testsprite-tests:
211
+ # Include this workflow's filename: concurrency groups are repository-wide,
212
+ # so another project's workflow must not cancel this gate.
186
213
  # B (pull_request): a new push to the pull request cancels the previous job.
187
214
  # A (deployment_status): one group per COMMIT — Vercel sets deployment.ref to
188
215
  # the commit sha, so a new push does not cancel the previous commit's job.
@@ -191,9 +218,10 @@ jobs:
191
218
  # Cancelling only stops this job's CLI: the TestSprite run it started keeps
192
219
  # executing and reports in the Portal; the new push starts its own run.
193
220
  concurrency:
194
- group: testsprite-\${{ github.event.pull_request.number || github.event.deployment.sha }}
221
+ group: testsprite-${workflowSlug}-\${{ github.event.pull_request.number || github.event.deployment.sha }}
195
222
  cancel-in-progress: true
196
- # pull_request: skip fork PRs (they get no repository secrets) and draft PRs.
223
+ # pull_request: skip fork PRs (they get no repository secrets), Dependabot PRs
224
+ # (Dependabot secrets are not Actions secrets), and draft PRs.
197
225
  # deployment_status: only successful, non-production deployments. Vercel leaves
198
226
  # production_environment false on production deployments, so the name is checked too
199
227
  # (GitHub compares strings case-insensitively).
@@ -210,6 +238,7 @@ jobs:
210
238
  if: >-
211
239
  (github.event_name == 'pull_request' &&
212
240
  github.event.pull_request.head.repo.full_name == github.repository &&
241
+ github.actor != 'dependabot[bot]' &&
213
242
  !github.event.pull_request.draft) ||
214
243
  (github.event_name == 'deployment_status' &&
215
244
  github.event.deployment_status.state == 'success' &&
@@ -220,11 +249,14 @@ jobs:
220
249
  env:
221
250
  ${envLines.join('\n')}
222
251
  steps:
223
- - uses: actions/checkout@v4
252
+ - uses: actions/checkout@v7
224
253
 
225
- - uses: actions/setup-node@v4
254
+ - uses: actions/setup-node@v7
226
255
  with:
227
256
  node-version: '22'
257
+ # Only the CLI is installed below. Without this, an npm repo
258
+ # (package.json "packageManager": "npm@…") with no lockfile fails here.
259
+ package-manager-cache: false
228
260
 
229
261
  - run: npm i -g ${CLI_PACKAGE_SPEC}
230
262
 
@@ -233,6 +265,12 @@ ${envLines.join('\n')}
233
265
  # above). The next step then reads the URL from the deployment event.
234
266
  # B. You deploy in this workflow: replace the run lines with your deploy
235
267
  # commands and end with: echo "url=<preview address>" >> "$GITHUB_OUTPUT"
268
+ # C. Your platform only posts a commit status or check on the PR (no deployment
269
+ # event): delete this step, keep the pull_request trigger, and in the step below
270
+ # replace the PREVIEW_URL env and the --target-url "$PREVIEW_URL" line with
271
+ # --wait-for-status "<its name on the PR>" --target-url-template "<pattern>"
272
+ # (placeholders {pr} {branch-slug} {sha} …, e.g. https://app-git-{branch-slug}-team.vercel.app),
273
+ # then add statuses: read and checks: read under permissions: above.
236
274
  - name: Get this PR's preview URL
237
275
  id: preview
238
276
  run: |
@@ -247,7 +285,7 @@ ${runLines.join('\n')}
247
285
 
248
286
  - name: Upload TestSprite report
249
287
  if: always()
250
- uses: actions/upload-artifact@v4
288
+ uses: actions/upload-artifact@v7
251
289
  with:
252
290
  name: testsprite-results
253
291
  path: ${SUMMARY_FILE}
@@ -433,7 +471,7 @@ export async function runCiInit(opts, deps = {}) {
433
471
  */
434
472
  async function runCiInitScaffold(opts, deps, platform, onExisted) {
435
473
  const stdout = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
436
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
474
+ const stderr = terminalSafeWriter(deps.stderr);
437
475
  const fs = deps.fs ?? defaultCiFs;
438
476
  const cwd = deps.cwd ?? process.cwd();
439
477
  const out = new Output(opts.output, { stdout, stderr });
@@ -444,6 +482,24 @@ async function runCiInitScaffold(opts, deps, platform, onExisted) {
444
482
  if (opts.env)
445
483
  assertSafeWorkflowValue('env', opts.env);
446
484
  const { relPath, absPath } = resolveWorkflowPath(opts.workflowPath, cwd);
485
+ const allowInternalSymlink = async (target) => {
486
+ let resolved;
487
+ let root;
488
+ try {
489
+ [root, resolved] = await Promise.all([fs.realpath(cwd), fs.realpath(target)]);
490
+ }
491
+ catch {
492
+ throw new CLIError(`cannot resolve symlink at "${target}"; refusing to write the workflow.`, 5);
493
+ }
494
+ const relative = path.relative(root, resolved);
495
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
496
+ throw new CLIError(`refusing to write through symlink "${target}": "${resolved}" is outside the repository.`, 5);
497
+ }
498
+ };
499
+ await inspectTargetPath(fs, cwd, relPath, allowInternalSymlink);
500
+ if (opts.force) {
501
+ await inspectTargetPath(fs, cwd, `${relPath}.bak`, allowInternalSymlink);
502
+ }
447
503
  const projectId = await resolveProjectId(opts, deps);
448
504
  const resolvedEnv = await resolveEnvironment(opts, deps, projectId);
449
505
  const environment = resolvedEnv.name;
@@ -524,8 +580,8 @@ async function runCiInitScaffold(opts, deps, platform, onExisted) {
524
580
  throw err;
525
581
  onExisted(true);
526
582
  const prior = await fs.readFile(absPath);
527
- if (prior === workflow) {
528
- // Already exactly what we'd write: no rewrite, and re-running (with or
583
+ if (equalIgnoringCrlf(prior, workflow)) {
584
+ // Equivalent apart from CRLF conversion: no rewrite, and re-running (with or
529
585
  // without --force) on identical content is a no-op rather than an error.
530
586
  wrote = false;
531
587
  }
@@ -556,392 +612,6 @@ async function runCiInitScaffold(opts, deps, platform, onExisted) {
556
612
  };
557
613
  out.print(summary, d => renderCiInitText(d));
558
614
  }
559
- /** Poll interval for `--wait`. A deploy takes minutes; 15 s keeps it cheap. */
560
- const DOCTOR_POLL_INTERVAL_MS = 15_000;
561
- /**
562
- * `owner/repo` for the check: the explicit `--repo`, else the `origin` remote.
563
- * Returns null when neither resolves — the caller turns that into guidance
564
- * rather than an opaque failure.
565
- */
566
- export function resolveRepoSlug(explicit, cwd, spawn) {
567
- if (explicit !== undefined && explicit !== '') {
568
- return isValidRepoSlug(explicit) ? explicit : null;
569
- }
570
- try {
571
- const res = spawn('git', ['remote', 'get-url', 'origin'], { cwd });
572
- if (res.error || res.status !== 0)
573
- return null;
574
- return parseRepoSlug(res.stdout ?? '');
575
- }
576
- catch {
577
- return null;
578
- }
579
- }
580
- /**
581
- * Read the repo's deployment history through `gh` — the same soft dependency
582
- * `--set-secret` already uses, so this adds no new requirement. It carries the
583
- * user's own GitHub credentials, which a private repo needs.
584
- */
585
- function fetchDeploymentHistory(repo, cwd, spawn) {
586
- let result;
587
- try {
588
- // 100 (the API maximum) rather than a small page: the classifier separates
589
- // preview from production records, and a busy repo can push dozens of
590
- // production deploys past its newest preview — a short page would then read
591
- // as a false `production-only`.
592
- result = spawn('gh', ['api', `repos/${repo}/deployments?per_page=100`], { cwd });
593
- }
594
- catch (err) {
595
- return { error: `failed to run gh: ${err.message}` };
596
- }
597
- if (result.error) {
598
- const code = result.error.code;
599
- return {
600
- error: code === 'ENOENT'
601
- ? 'gh CLI not found on PATH — install it (https://cli.github.com), then `gh auth login`'
602
- : `gh failed: ${result.error.message}`,
603
- };
604
- }
605
- if (result.status !== 0) {
606
- const stderr = (result.stderr ?? '').split('\n')[0]?.trim() ?? '';
607
- return { error: `gh exited ${result.status}${stderr ? `: ${stderr}` : ''}` };
608
- }
609
- return { records: parseDeploymentsPayload(result.stdout ?? '') };
610
- }
611
- /**
612
- * Diagnose whether deployment events reach this repo — the precondition every
613
- * deployment-gated workflow rests on, and the only one that fails *silently*.
614
- *
615
- * Exits non-zero when the chain is not live, so a script (or `ci init`) can
616
- * gate on it. `--wait` makes the post-connect verification one command instead
617
- * of "go watch GitHub yourself": it baselines the history on the first read and
618
- * succeeds when a NEW record arrives. That success condition is a hard fact,
619
- * deliberately independent of the preview/production heuristic — pushing to a
620
- * default branch produces a *production* deployment, and that still proves the
621
- * link is live.
622
- */
623
- export async function runCiDoctor(opts, deps = {}) {
624
- const stdout = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
625
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
626
- const out = new Output(opts.output, { stdout, stderr });
627
- const cwd = deps.cwd ?? process.cwd();
628
- const spawn = deps.spawn ?? defaultSpawn;
629
- const sleep = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
630
- if (opts.waitTimeoutSeconds !== undefined && !opts.wait) {
631
- throw localValidationError('timeout', 'only applies with --wait — add --wait, or drop --timeout');
632
- }
633
- const waitTimeoutSeconds = opts.waitTimeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
634
- const repo = resolveRepoSlug(opts.repo, cwd, spawn);
635
- if (repo === null) {
636
- throw localValidationError('repo', opts.repo
637
- ? 'must look like owner/name (e.g. acme/storefront)'
638
- : 'could not read a GitHub `origin` remote here — run from the repo, or pass --repo <owner/name>');
639
- }
640
- const deadline = Date.now() + waitTimeoutSeconds * 1000;
641
- let verdict;
642
- let readError = null;
643
- /** Newest record's timestamp on the first successful read; -∞ when it saw none. */
644
- let baselineNewestMs;
645
- let newDeployment = null;
646
- for (;;) {
647
- const budgetLeft = Date.now() + DOCTOR_POLL_INTERVAL_MS <= deadline;
648
- const history = fetchDeploymentHistory(repo, cwd, spawn);
649
- if ('error' in history) {
650
- // A transient `gh` failure (rate limit, network blip) must not abort a
651
- // ten-minute watch — keep polling while budget remains. It surfaces as
652
- // exit 10 only when the whole wait ends without one successful read.
653
- readError = history.error;
654
- if (!opts.wait || !budgetLeft)
655
- break;
656
- stderr(`[wait] could not read deployment history (${history.error}) — retrying`);
657
- await sleep(DOCTOR_POLL_INTERVAL_MS);
658
- continue;
659
- }
660
- verdict = classifyLinkage(history.records, new Date());
661
- if (!opts.wait)
662
- break;
663
- const newestMs = history.records.reduce((max, r) => Math.max(max, new Date(r.createdAt).getTime()), Number.NEGATIVE_INFINITY);
664
- if (baselineNewestMs === undefined) {
665
- // What already exists only anchors the comparison — `--wait` is about
666
- // the record the user's connect + push is producing right now.
667
- baselineNewestMs = newestMs;
668
- }
669
- else if (newestMs > baselineNewestMs) {
670
- newDeployment =
671
- history.records.find(r => new Date(r.createdAt).getTime() === newestMs) ?? null;
672
- break;
673
- }
674
- if (!budgetLeft)
675
- break;
676
- stderr(`[wait] no new deployment record yet — checking again in ${DOCTOR_POLL_INTERVAL_MS / 1000}s`);
677
- await sleep(DOCTOR_POLL_INTERVAL_MS);
678
- }
679
- // A read failure on the LAST attempt does not erase an earlier verdict; the
680
- // error only stands when no read ever succeeded.
681
- const unread = verdict === undefined;
682
- const summary = {
683
- repo,
684
- status: verdict?.status ?? 'none',
685
- ok: verdict?.ok ?? false,
686
- detail: verdict?.detail ?? readError ?? 'could not read deployment history',
687
- lastDeployAt: verdict?.lastDeployAt ?? null,
688
- creators: verdict?.creators ?? [],
689
- hasPreview: verdict?.hasPreview ?? false,
690
- waited: opts.wait,
691
- newDeployment,
692
- error: unread ? readError : null,
693
- };
694
- out.print(summary, d => renderCiDoctorText(d));
695
- // A read failure is NOT a verdict — reporting "not linked" because `gh` is
696
- // missing would send the user to fix the wrong thing.
697
- if (unread) {
698
- throw new CLIError(`ci doctor: could not read deployment history for ${repo}`, 10);
699
- }
700
- // A new record arriving is what `--wait` verifies: events reach this repo.
701
- // The verdict above still tells the user what KIND of gate that supports.
702
- if (newDeployment !== null)
703
- return;
704
- if (!summary.ok) {
705
- throw new CLIError(`ci doctor: ${repo} is not ready for a deployment-gated workflow (${summary.status})`, 1);
706
- }
707
- }
708
- export function renderCiDoctorText(s) {
709
- const lines = [];
710
- const mark = s.error ? '[FAIL]' : s.ok ? '[OK] ' : '[WARN]';
711
- lines.push(`${mark} deployment events ${s.repo}`);
712
- if (s.newDeployment) {
713
- const day = s.newDeployment.createdAt.slice(0, 10);
714
- lines.push(` new deployment record: ${s.newDeployment.environment} (${day}) ✓ — events reach this repo`);
715
- }
716
- lines.push(` ${s.detail}`);
717
- if (s.error) {
718
- lines.push('');
719
- lines.push("Could not read the repo's deployment history, so this is not a verdict:");
720
- lines.push(` ${s.error}`);
721
- return lines.join('\n');
722
- }
723
- if (s.waited && !s.newDeployment) {
724
- lines.push(' (no NEW deployment record arrived while waiting — the verdict above is from the existing history)');
725
- }
726
- if (s.ok)
727
- return lines.join('\n');
728
- lines.push('');
729
- lines.push('Next steps:');
730
- if (s.status === 'none') {
731
- lines.push(' 1. Link your deploy platform to this repo:');
732
- lines.push(' testsprite ci connect # runs `vercel git connect` for you');
733
- lines.push(" …or link the repo in your platform's dashboard.");
734
- // A branch, not the default branch: a default-branch push deploys as
735
- // PRODUCTION, which proves the link but is not what a PR gate keys on.
736
- lines.push(' 2. Push a commit on a branch so a preview deployment lands:');
737
- lines.push(' git checkout -b verify-testsprite-ci');
738
- lines.push(' git commit --allow-empty -m "verify testsprite ci" && git push -u origin HEAD');
739
- lines.push(' 3. Confirm the events arrive (any new deployment record counts):');
740
- lines.push(' testsprite ci doctor --wait');
741
- }
742
- else if (s.status === 'production-only') {
743
- lines.push(' → Enable preview deployments for pull requests on your deploy platform.');
744
- lines.push(' A PR gate keys on preview deployments; production-only events fire on');
745
- lines.push(' releases instead, so the check would never run on a PR.');
746
- }
747
- else {
748
- lines.push(' → Push a commit and re-run `testsprite ci doctor --wait` to confirm the link');
749
- lines.push(' is still live before scaffolding a gate on it.');
750
- }
751
- lines.push('');
752
- lines.push('Self-hosted pipeline? Report each deploy yourself, and every path works the same:');
753
- // `required_contexts: []` is load-bearing: without it GitHub answers 409 when
754
- // any commit status on the SHA is failing — i.e. exactly when a PR pipeline is
755
- // deploying its preview. JSON input because `-f` would send the empty array as
756
- // a string. (Both learned the hard way running this against a real repo.)
757
- lines.push(` ID=$(printf '{"ref":"%s","environment":"preview","auto_merge":false,"required_contexts":[]}' "$SHA" \\`);
758
- lines.push(` | gh api repos/${s.repo}/deployments --input - --jq .id)`);
759
- lines.push(` gh api repos/${s.repo}/deployments/$ID/statuses -f state=success -f environment_url=$URL`);
760
- return lines.join('\n');
761
- }
762
- /**
763
- * The Vercel CLI, pinned to the major this command's flag semantics were
764
- * verified against (59.23.2). Unpinned, a breaking Vercel release could change
765
- * what `--non-interactive` refuses or creates under a tool people run in CI.
766
- * (Unrelated to the TestSprite CLI's own `latest` policy — this pins a THIRD
767
- * PARTY whose behavior we shell out to.) Bump deliberately, re-testing the
768
- * ladder below.
769
- */
770
- const VERCEL_CLI_SPEC = 'vercel@59';
771
- /** What Vercel accepts as a project name — and all that may reach the Windows
772
- * shell path below, so keep it strict. */
773
- const VERCEL_PROJECT_NAME_RE = /^[a-z0-9._-]{1,100}$/;
774
- /**
775
- * `--non-interactive` refusals come back as one JSON object with a `reason`
776
- * and often a `next[]` of literal commands — relay those, since Vercel's own
777
- * instructions beat anything we could paraphrase. Anything else falls back to
778
- * the first non-empty output line.
779
- */
780
- function vercelFailureDetail(result) {
781
- for (const chunk of [result.stdout ?? '', result.stderr ?? '']) {
782
- const trimmed = chunk.trim();
783
- if (!trimmed.startsWith('{'))
784
- continue;
785
- try {
786
- const parsed = JSON.parse(trimmed);
787
- if (typeof parsed.reason === 'string') {
788
- const next = Array.isArray(parsed.next)
789
- ? parsed.next.filter((n) => typeof n === 'string')
790
- : [];
791
- return next.length > 0 ? `${parsed.reason} — next: ${next.join(' && ')}` : parsed.reason;
792
- }
793
- }
794
- catch {
795
- /* prose after all — fall through */
796
- }
797
- }
798
- return (`${result.stdout ?? ''}\n${result.stderr ?? ''}`
799
- .split('\n')
800
- .find(l => l.trim() !== '')
801
- ?.trim() ?? '');
802
- }
803
- /**
804
- * Link the deploy platform to the repo — the fix for `ci doctor`'s `none`.
805
- *
806
- * Runs the platform's OWN CLI as a subprocess (`npx vercel …`, so nothing needs
807
- * pre-installing) rather than calling Vercel's API ourselves. That is a
808
- * deliberate boundary: any other approach would require the user to hand us a
809
- * Vercel token, and a third-party credential should never pass through this
810
- * CLI. Vercel's CLI keeps its own credentials; we only read exit codes.
811
- *
812
- * Every step runs `--non-interactive`, and `--yes` is NEVER passed to the
813
- * Vercel CLI on any path. `--yes` does not mean "skip confirmations": on an
814
- * unlinked directory `vercel link --yes` answers the new-project questions
815
- * with the default scope and the current directory name — creating a project
816
- * nobody asked for, which `git connect` then wires the repo to and starts
817
- * deploying. `ci doctor` would report that as `linked`: the exact silent
818
- * false-green this command exists to prevent. When Vercel needs a decision it
819
- * refuses with a structured reason instead, and that is relayed.
820
- *
821
- * `vercel git connect` is effectively idempotent — an already-connected repo
822
- * says so, which also resolves the one ambiguity `ci doctor` cannot see from
823
- * GitHub: "never linked" vs "linked but never deployed".
824
- */
825
- export async function runCiConnect(opts, deps = {}) {
826
- const stdout = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
827
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
828
- const out = new Output(opts.output, { stdout, stderr });
829
- const cwd = deps.cwd ?? process.cwd();
830
- const spawn = deps.spawn ?? defaultSpawn;
831
- const fs = deps.fs ?? defaultCiFs;
832
- const platform = deps.platform ?? process.platform;
833
- const ran = [];
834
- // Input gate before any subprocess or fs read: a bad name must fail as a
835
- // validation error, not as a spawned command's stderr.
836
- if (opts.project !== undefined && !VERCEL_PROJECT_NAME_RE.test(opts.project)) {
837
- throw localValidationError('project', 'must be a Vercel project name (lowercase letters, digits, ".", "_", "-"; max 100 chars)');
838
- }
839
- const finish = (over, failure) => {
840
- const summary = {
841
- platform: 'vercel',
842
- ran,
843
- connected: false,
844
- alreadyConnected: false,
845
- reason: null,
846
- ...over,
847
- };
848
- out.print(summary, d => renderCiConnectText(d));
849
- if (failure !== undefined)
850
- throw new CLIError(failure, 1);
851
- };
852
- const run = (args) => {
853
- ran.push(`npx ${VERCEL_CLI_SPEC} ${args.join(' ')}`);
854
- try {
855
- // npx's own `--yes` only suppresses its install prompt; nothing after the
856
- // package spec is a `--yes` (see the function comment). On Windows `npx`
857
- // is a `.cmd` shim, which `spawnSync` cannot launch with `shell: false`
858
- // (EINVAL since Node 20.12's CVE-2024-27980 hardening, ENOENT before) —
859
- // go through the shell there. Safe because every argument is a literal or
860
- // validated against VERCEL_PROJECT_NAME_RE, never free text.
861
- return platform === 'win32'
862
- ? spawn('npx.cmd', ['--yes', VERCEL_CLI_SPEC, ...args], { cwd, shell: true })
863
- : spawn('npx', ['--yes', VERCEL_CLI_SPEC, ...args], { cwd });
864
- }
865
- catch (err) {
866
- return { failure: `failed to run npx: ${err.message}` };
867
- }
868
- };
869
- // `.vercel/project.json` is how the Vercel CLI itself records which project
870
- // this directory is linked to. Present → the project is already decided and
871
- // `git connect` is safe to run directly.
872
- let dirLinked = false;
873
- try {
874
- await fs.readFile(path.join(cwd, '.vercel', 'project.json'));
875
- dirLinked = true;
876
- }
877
- catch {
878
- /* not linked */
879
- }
880
- if (!dirLinked) {
881
- if (opts.project === undefined || opts.project === '') {
882
- // Refuse rather than guess: picking (or worse, creating) a project is
883
- // the one decision this command must never make for the user.
884
- finish({ reason: 'this directory is not linked to a Vercel project' }, 'ci connect: this directory is not linked to a Vercel project — pass --project <name>, or run `npx vercel link` to pick one interactively, then re-run');
885
- return;
886
- }
887
- // `link --project <name>` targets an EXISTING project by name, so it needs
888
- // no `--yes` and cannot create one as a side effect.
889
- const link = run(['link', '--project', opts.project, '--non-interactive']);
890
- if ('failure' in link) {
891
- finish({ reason: link.failure }, `ci connect: ${link.failure}`);
892
- return;
893
- }
894
- if (link.status !== 0) {
895
- const detail = vercelFailureDetail(link);
896
- finish({ reason: `vercel link failed${detail ? `: ${detail}` : ''}` }, `ci connect: could not link this directory to Vercel project "${opts.project}"${detail ? ` — ${detail}` : ''}`);
897
- return;
898
- }
899
- }
900
- const connect = run(['git', 'connect', '--non-interactive']);
901
- if ('failure' in connect) {
902
- finish({ reason: connect.failure }, `ci connect: ${connect.failure}`);
903
- return;
904
- }
905
- // "already connected" is prose on exit 1 with no JSON — Vercel offers no
906
- // structured way to see it (`project inspect` does not expose git-link
907
- // state), so a regex on the CLI's wording is load-bearing here. If Vercel
908
- // rephrases it, this degrades to the generic relay below (a hard failure
909
- // with Vercel's own message), never to a wrong success.
910
- const output = `${connect.stdout ?? ''}\n${connect.stderr ?? ''}`;
911
- const alreadyConnected = /already connected/i.test(output);
912
- if (connect.status !== 0 && !alreadyConnected) {
913
- const detail = vercelFailureDetail(connect);
914
- // The common dead ends — not logged in (browser OAuth), the Vercel GitHub
915
- // App not installed, missing org permission — all need a human. Relay the
916
- // CLI's own message verbatim rather than paraphrasing the fix away.
917
- finish({ reason: detail || `vercel git connect exited ${connect.status}` }, `ci connect: ${detail || 'could not connect the repo'}`);
918
- return;
919
- }
920
- finish({ connected: true, alreadyConnected });
921
- stderr(alreadyConnected
922
- ? '[info] the repo was already connected — if `ci doctor` still reports no events, it simply has not deployed yet.'
923
- : '[info] connected. Linking only affects FUTURE pushes.');
924
- stderr('Next: push a commit on a branch so a preview deployment lands:');
925
- stderr(' git checkout -b verify-testsprite-ci');
926
- stderr(' git commit --allow-empty -m "verify testsprite ci" && git push -u origin HEAD');
927
- stderr('Then: testsprite ci doctor --wait');
928
- }
929
- export function renderCiConnectText(s) {
930
- if (s.connected) {
931
- return s.alreadyConnected
932
- ? 'Vercel is already connected to this repo.'
933
- : 'Connected Vercel to this repo.';
934
- }
935
- const lines = [`Could not connect automatically: ${s.reason ?? 'unknown reason'}.`, ''];
936
- lines.push('Do it manually:');
937
- lines.push(' npx vercel login # if you are not signed in');
938
- lines.push(' npx vercel link # pick the Vercel project for this directory');
939
- lines.push(' npx vercel git connect # link it to the git remote');
940
- lines.push('');
941
- lines.push('…then re-run `testsprite ci connect`, or finish from the Vercel dashboard');
942
- lines.push('(Project → Settings → Git).');
943
- return lines.join('\n');
944
- }
945
615
  // ── text rendering ───────────────────────────────────────────────────────────
946
616
  export function renderCiInitText(s) {
947
617
  const lines = [];
@@ -969,8 +639,17 @@ export function renderCiInitText(s) {
969
639
  lines.push(" against that PR's preview. To block merges on it, make it a required check.");
970
640
  return lines.join('\n');
971
641
  }
642
+ /** How long `--wait-for-status` waits by default — a preview build is minutes, so its own budget, not `--timeout`'s. */
643
+ export const DEFAULT_STATUS_TIMEOUT_SECONDS = 900;
644
+ export function parseStatusTimeoutSeconds(raw) {
645
+ const n = Number(raw);
646
+ if (!Number.isInteger(n) || n < 1 || n > 3600) {
647
+ throw localValidationError('status-timeout', 'must be an integer between 1 and 3600 seconds');
648
+ }
649
+ return n;
650
+ }
972
651
  /**
973
- * `ci run` = `test run --all --wait` with CI's defaults, plus what only a CI
652
+ * `ci run` = `run --project --wait` with CI's defaults, plus what only a CI
974
653
  * job can add:
975
654
  *
976
655
  * - `admission: 'all'` — one request, one execution, server-side pacing (as
@@ -982,15 +661,35 @@ export function renderCiInitText(s) {
982
661
  * deployment's commit), `--env X --target-url U` runs in a temporary clone
983
662
  * of X at U named `github-pr-<N>`, and the run is stamped with the PR so
984
663
  * the Portal links back to it — the GitHub App's own mechanism.
985
- * - Outside a pull request the run keeps `test run`'s semantics: X's sign-in
664
+ * - Outside a pull request the run keeps `run`'s semantics: X's sign-in
986
665
  * against U, recorded under X.
987
666
  */
988
667
  export async function runCiRun(opts, deps = {}) {
989
668
  const env = deps.env ?? process.env;
990
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
669
+ const stderr = terminalSafeWriter(deps.stderr);
991
670
  if (opts.targetUrl !== undefined && opts.targetUrl.trim() === '') {
992
671
  throw localValidationError('target-url', 'must be a non-empty URL');
993
672
  }
673
+ // The template and the wait are checked for shape before any request: a
674
+ // bad pattern or a dangling --status-timeout is a configuration error, and
675
+ // must not first show up after minutes of waiting.
676
+ if (opts.targetUrlTemplate !== undefined) {
677
+ if (opts.targetUrl !== undefined) {
678
+ throw localValidationError('target-url-template', 'cannot be combined with --target-url; pass the address or the pattern, not both');
679
+ }
680
+ if (opts.targetUrlTemplate.trim() === '') {
681
+ throw localValidationError('target-url-template', 'must be a non-empty URL pattern');
682
+ }
683
+ const problem = validateUrlTemplate(opts.targetUrlTemplate.trim());
684
+ if (problem !== null)
685
+ throw localValidationError('target-url-template', problem);
686
+ }
687
+ if (opts.waitForStatus !== undefined && opts.waitForStatus.trim() === '') {
688
+ throw localValidationError('wait-for-status', 'must name the commit status context or check run to wait for (as shown on the pull request)');
689
+ }
690
+ if (opts.statusTimeoutSeconds !== undefined && opts.waitForStatus === undefined) {
691
+ throw localValidationError('status-timeout', 'only applies with --wait-for-status');
692
+ }
994
693
  // An unknown environment name is a configuration error, not an empty
995
694
  // selection: refused here, before anything dispatches or charges, so it
996
695
  // can never read as a green `--allow-empty` run.
@@ -1008,7 +707,10 @@ export async function runCiRun(opts, deps = {}) {
1008
707
  }
1009
708
  throw err;
1010
709
  }
1011
- const github = await readGithubRunContext(env, { fetchImpl: deps.fetchImpl });
710
+ const github = await readGithubRunContext(env, {
711
+ fetchImpl: deps.fetchImpl,
712
+ requestTimeoutMs: resolveRequestTimeoutMs(opts, env),
713
+ });
1012
714
  let previewName;
1013
715
  let githubTrigger;
1014
716
  if (github.kind === 'pull_request') {
@@ -1019,7 +721,8 @@ export async function runCiRun(opts, deps = {}) {
1019
721
  }
1020
722
  githubTrigger = github.trigger;
1021
723
  // The clone needs a template to clone and an address to point at.
1022
- if (opts.targetUrl !== undefined && opts.environment !== undefined) {
724
+ if ((opts.targetUrl !== undefined || opts.targetUrlTemplate !== undefined) &&
725
+ opts.environment !== undefined) {
1023
726
  previewName = previewEnvironmentName(github.trigger.prNumber);
1024
727
  }
1025
728
  }
@@ -1029,8 +732,66 @@ export async function runCiRun(opts, deps = {}) {
1029
732
  skipCiRun(`Skipping: ${github.reason}; nothing to gate.`, { env, stderr });
1030
733
  return;
1031
734
  }
735
+ const facts = commitFacts(github, env);
736
+ // Shape C: the platform wrote no deployment event, only a status or check on
737
+ // the head commit. Wait for it before anything is rendered or dispatched.
738
+ if (opts.waitForStatus !== undefined && !opts.dryRun) {
739
+ const ready = await awaitPreviewSignal(opts, facts, { env, stderr }, deps);
740
+ if (!ready)
741
+ return;
742
+ }
743
+ const { targetUrlTemplate, waitForStatus, statusTimeoutSeconds, ...batchOpts } = opts;
744
+ void waitForStatus;
745
+ void statusTimeoutSeconds;
746
+ let targetUrl = opts.targetUrl;
747
+ if (targetUrlTemplate !== undefined) {
748
+ const template = targetUrlTemplate.trim();
749
+ const rendered = renderUrlTemplate(template, facts);
750
+ if (rendered === null) {
751
+ // Never a guess: a pattern this run cannot fill is refused, and the
752
+ // reason names the placeholders so the fix is the pattern or the trigger.
753
+ recordTelemetryExtras({ ciRunOutcome: 'refused_url_template' });
754
+ const unsafe = unsafeHostPlaceholders(template, facts);
755
+ if (unsafe.length > 0) {
756
+ // The value would change the host (`{branch}` = "attacker.example/x" in
757
+ // `https://{branch}.preview…`): never dispatched, the environment's
758
+ // sign-in stays where it belongs.
759
+ throw ApiError.fromEnvelope({
760
+ error: {
761
+ code: 'VALIDATION_ERROR',
762
+ message: 'Invalid request.',
763
+ nextAction: `Flag \`--target-url-template\` refused: ${unsafe.join(', ')} would change the host of the rendered URL (only letters, digits and - are allowed there). Use {branch-slug} in the host part, or pass --target-url.`,
764
+ requestId: 'local',
765
+ details: {
766
+ field: 'target-url-template',
767
+ reason: 'url_unsafe_host',
768
+ unsafe: unsafe.join(', '),
769
+ },
770
+ },
771
+ });
772
+ }
773
+ const missing = missingPlaceholders(template, facts).join(', ');
774
+ const where = github.kind === 'outside_actions'
775
+ ? 'outside GitHub Actions'
776
+ : github.kind === 'no_pull_request'
777
+ ? `on a ${github.event || 'non-PR'} event`
778
+ : 'for this pull request';
779
+ throw ApiError.fromEnvelope({
780
+ error: {
781
+ code: 'VALIDATION_ERROR',
782
+ message: 'Invalid request.',
783
+ nextAction: `Flag \`--target-url-template\` could not be filled ${where}: ${missing} ${missing.includes(',') ? 'have' : 'has'} no value. Use a placeholder the trigger provides, or pass --target-url.`,
784
+ requestId: 'local',
785
+ details: { field: 'target-url-template', reason: 'url_unresolved', missing },
786
+ },
787
+ });
788
+ }
789
+ targetUrl = rendered;
790
+ stderr(`[ci run] --target-url-template rendered to ${rendered}`);
791
+ }
1032
792
  await runTestRunAll({
1033
- ...opts,
793
+ ...batchOpts,
794
+ ...(targetUrl !== undefined ? { targetUrl } : {}),
1034
795
  timeoutSeconds: parseTimeoutSeconds(opts.timeoutSeconds),
1035
796
  wait: true,
1036
797
  ci: {
@@ -1050,21 +811,116 @@ export async function runCiRun(opts, deps = {}) {
1050
811
  * rather than an empty string. Nothing was dispatched, so nothing else (job
1051
812
  * summary, summary file, report) is written: those describe runs.
1052
813
  */
1053
- function skipCiRun(notice, io) {
1054
- io.stderr(`::notice title=TestSprite::${notice}`);
1055
- const nothing = { total: 0, passed: 0, failed: 0, skipped: 0, timedOut: 0, runs: [] };
814
+ function skipCiRun(notice, io, opts = {}) {
815
+ // The notice can carry a third-party check's text: encoded as workflow-command
816
+ // data, so a line break in it cannot start a second command.
817
+ io.stderr(`::notice title=TestSprite::${escapeCommandData(notice)}`);
818
+ const nothing = {
819
+ total: 0,
820
+ passed: 0,
821
+ failed: 0,
822
+ skipped: 0,
823
+ timedOut: 0,
824
+ results: [],
825
+ };
826
+ emitCiStepOutputs(nothing, io);
827
+ const summaryPath = io.env.GITHUB_STEP_SUMMARY;
828
+ if (opts.jobSummary !== undefined && typeof summaryPath === 'string' && summaryPath.length > 0) {
829
+ try {
830
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- GITHUB_STEP_SUMMARY is the runner-provided job-summary path; only the CLI's own Markdown line is appended.
831
+ appendFileSync(summaryPath, `${opts.jobSummary}\n`, 'utf8');
832
+ }
833
+ catch {
834
+ io.stderr('[ci run] could not append to GITHUB_STEP_SUMMARY; continuing');
835
+ }
836
+ }
837
+ }
838
+ /**
839
+ * The facts a `--target-url-template` is filled from. In a pull request they
840
+ * are the PR's; outside one (a push, a schedule) what the runner exposes —
841
+ * `{pr}` then has no value and a pattern using it is refused.
842
+ */
843
+ function commitFacts(github, env) {
844
+ if (github.kind === 'pull_request') {
845
+ return {
846
+ pr: github.trigger.prNumber,
847
+ branch: github.trigger.branchName ?? null,
848
+ sha: github.trigger.commitSha ?? null,
849
+ };
850
+ }
851
+ return {
852
+ pr: null,
853
+ branch: env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME || null,
854
+ sha: env.GITHUB_SHA || null,
855
+ };
856
+ }
857
+ /**
858
+ * `--wait-for-status`: block until the named status / check run on the head
859
+ * commit is terminal. `true` = the preview exists, carry on. `false` = there
860
+ * is no preview (the deploy failed, or the build was skipped) — reported as a
861
+ * skip, exit 0, nothing dispatched. Nothing terminal in time is exit 7,
862
+ * listing every name seen on the commit so a misspelled name is obvious.
863
+ */
864
+ async function awaitPreviewSignal(opts, facts, io, deps) {
865
+ const name = opts.waitForStatus.trim();
866
+ const token = io.env.GITHUB_TOKEN;
867
+ if (!token) {
868
+ throw localValidationError('GITHUB_TOKEN', '--wait-for-status reads the checks on the commit with the job token — add `GITHUB_TOKEN: ${{ github.token }}` to the step env', undefined, 'field');
869
+ }
870
+ const [repoOwner, repoName, ...rest] = (io.env.GITHUB_REPOSITORY ?? '').split('/');
871
+ if (!repoOwner || !repoName || rest.length > 0 || !facts.sha) {
872
+ throw localValidationError('wait-for-status', 'needs a GitHub Actions job with a commit to watch (GITHUB_REPOSITORY and the pull request head sha, or GITHUB_SHA)');
873
+ }
874
+ const timeoutMs = (opts.statusTimeoutSeconds ?? DEFAULT_STATUS_TIMEOUT_SECONDS) * 1000;
875
+ io.stderr(`[ci run] waiting up to ${timeoutMs / 1000}s for "${name}" on ${facts.sha.slice(0, 7)} to finish`);
876
+ const verdict = await waitForCommitSignal({ repoOwner, repoName, sha: facts.sha, name }, { token, timeoutMs }, {
877
+ env: io.env,
878
+ fetchImpl: deps.fetchImpl ?? globalThis.fetch,
879
+ sleep: deps.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))),
880
+ shutdown: deps.shutdown ?? globalShutdown,
881
+ stderr: io.stderr,
882
+ });
883
+ if (verdict.kind === 'ready') {
884
+ io.stderr(`[ci run] "${name}" succeeded (${verdict.signal.via === 'status' ? 'commit status' : 'check run'}); the preview is up`);
885
+ return true;
886
+ }
887
+ if (verdict.kind === 'skip') {
888
+ recordTelemetryExtras({ ciRunOutcome: 'skipped_no_preview' });
889
+ skipCiRun(`No preview for this commit — tests not run: ${verdict.reason}.`, io, {
890
+ jobSummary: `> **TestSprite:** no preview for this commit — tests not run: ${verdict.reason}.`,
891
+ });
892
+ return false;
893
+ }
894
+ recordTelemetryExtras({ ciRunOutcome: 'timeout_preview' });
895
+ const nothing = {
896
+ total: 0,
897
+ passed: 0,
898
+ failed: 0,
899
+ skipped: 0,
900
+ timedOut: 0,
901
+ results: [],
902
+ };
1056
903
  emitCiStepOutputs(nothing, io);
904
+ const seen = verdict.seen.length > 0 ? verdict.seen.map(s => `"${s}"`).join(', ') : 'none';
905
+ throw ApiError.fromEnvelope({
906
+ error: {
907
+ code: 'UNSUPPORTED',
908
+ message: `Waited ${Math.round(verdict.waitedMs / 1000)}s and no status or check named "${name}" reached a terminal state on ${facts.sha.slice(0, 7)}.`,
909
+ nextAction: `Check the name against what the pull request shows (seen on this commit: ${seen}), or raise --status-timeout.`,
910
+ requestId: 'local',
911
+ details: { field: 'wait-for-status', reason: 'preview-status-timeout', seen: verdict.seen },
912
+ },
913
+ });
1057
914
  }
1058
915
  /**
1059
916
  * Strict `--env`: the name must be one of the project's environments, read
1060
- * off the same list `test run` reads before a batch. Fails closed: a list that
917
+ * off the same list `run` reads before a batch. Fails closed: a list that
1061
918
  * cannot be read is an error with that error's own exit code (bad key → 3,
1062
919
  * backend down → 10, interrupted → the signal's code) — never a run that goes
1063
920
  * on to dispatch and charge against an environment nobody checked. The one
1064
- * read that is NOT an error is a backend answering that this project has no
1065
- * environment surface at all (a V2 project's `UNSUPPORTED`, or an older
1066
- * backend's 404 for the route): there is no list to check against, and the
1067
- * batch's own `environment` validation is the only authority left. Nothing to
921
+ * read that is NOT an error is an older backend's 404 for the route: there is
922
+ * no list to check against, and the batch's own `environment` validation is
923
+ * the only authority left. Nothing to
1068
924
  * check without a name, and a dry run makes no request.
1069
925
  */
1070
926
  async function assertCiEnvironmentExists(opts, deps) {
@@ -1082,7 +938,7 @@ async function assertCiEnvironmentExists(opts, deps) {
1082
938
  }).get(`/projects/${encodeURIComponent(projectId)}/env`);
1083
939
  }
1084
940
  catch (err) {
1085
- if (err instanceof ApiError && (err.code === 'UNSUPPORTED' || err.httpStatus === 404)) {
941
+ if (err instanceof ApiError && err.httpStatus === 404) {
1086
942
  return;
1087
943
  }
1088
944
  throw err;
@@ -1094,6 +950,7 @@ async function assertCiEnvironmentExists(opts, deps) {
1094
950
  return;
1095
951
  throw localValidationError('env', `no environment named "${environment}" in project ${projectId} — available: ${names.join(', ') || '(none)'}`);
1096
952
  }
953
+ /** Build CI run and workflow scaffolding commands with injectable runtime dependencies. */
1097
954
  export function createCiCommand(deps = {}) {
1098
955
  const ci = new Command('ci').description('Run tests in CI and scaffold CI integration');
1099
956
  ci.command('run')
@@ -1101,9 +958,12 @@ export function createCiCommand(deps = {}) {
1101
958
  .allowExcessArguments(false)
1102
959
  .option('--project <id>', 'project id (defaults to TESTSPRITE_PROJECT_ID)')
1103
960
  .option('--all', 'run all project tests (already the default)')
1104
- .option('--filter <substr>', 'only run tests whose name contains this substring')
961
+ .option('--filter <substr>', 'only run tests whose name contains this non-empty substring (case-insensitive); omit to run every test')
1105
962
  .option('--env <name>', 'the environment whose sign-in the run uses (unknown names fail). In a pull request, with --target-url, the run happens in a temporary clone of it at the preview address, named github-pr-<N> like a GitHub App run')
1106
963
  .option('--target-url <url>', "frontend tests: the address to test, typically this pull request's preview deployment")
964
+ .option('--target-url-template <pattern>', 'the preview address as a pattern filled from the pull request: {pr}, {branch}, {branch-slug}, {sha}, {short-sha} (e.g. https://app-git-{branch-slug}-team.vercel.app); instead of --target-url')
965
+ .option('--wait-for-status <name>', 'wait for this commit status context or check run on the head commit to succeed before running (the name as the pull request shows it, e.g. "Vercel"); a failed or skipped build exits 0 with a notice')
966
+ .option('--status-timeout <s>', `max seconds --wait-for-status waits (1-3600; default ${DEFAULT_STATUS_TIMEOUT_SECONDS})`)
1107
967
  .option('--skip-preflight', 'skip the pre-charge reachability probe for --target-url', false)
1108
968
  .option('--timeout <s>', 'max seconds to wait for results (1-3600)', '600')
1109
969
  .option('--execution-report-timeout <s>', 'max seconds to wait for the execution report that fills the job summary (1-3600)', '60')
@@ -1119,7 +979,7 @@ export function createCiCommand(deps = {}) {
1119
979
  .option('--report-suite-name <name>', 'JUnit suite name (default: testsprite:<projectId>)')
1120
980
  .addHelpText('after', '\nAlways waits for results. Failed tests and timeouts fail the gate.\n' +
1121
981
  'Skipped tests warn unless --fail-on-skipped; missing test ids and unknown\n' +
1122
- 'environments always fail. Every selected test is seeded into ONE execution\n' +
982
+ 'environments always fail. Every selected test is seeded into ONE run\n' +
1123
983
  'and the server paces dispatch, as for a GitHub App run.\n' +
1124
984
  'In GitHub Actions the pull request is read from the event (a deployment_status\n' +
1125
985
  'event is looked up by commit with GITHUB_TOKEN); draft PRs and deployments\n' +
@@ -1128,20 +988,31 @@ export function createCiCommand(deps = {}) {
1128
988
  "the deployment's state or environment: filter deployment_status events with\n" +
1129
989
  "the job's `if:` (state == 'success', not production), or a failed or\n" +
1130
990
  'production deployment is gated too.\n' +
1131
- 'Writes total, passed, failed, skipped, timedOut to GITHUB_OUTPUT when present.\n' +
991
+ 'Writes total, passed, failed (includes blocked), blocked, failedOnly, skipped and timedOut to GITHUB_OUTPUT.\n' +
1132
992
  'On a supporting backend the job summary is the execution report — the same content\n' +
1133
993
  'the GitHub App posts as its PR comment — and execution-report-file /\n' +
1134
994
  'execution-report-markdown-file name its JSON and Markdown for later steps.\n' +
1135
995
  'Reports and outputs are emitted before the exit code is decided.\n' +
1136
- 'Backend tests use the URL in their own code, not --target-url. PR comments are not yet supported.\n')
996
+ 'When the platform posts only a commit status or check (no deployment event),\n' +
997
+ '--wait-for-status <name> holds the run until it succeeds and --target-url-template\n' +
998
+ 'derives the preview address from the pull request; a pattern that cannot be filled\n' +
999
+ 'is refused, never guessed. In a pull request the run happens in a github-pr-<N> clone\n' +
1000
+ 'of --env at --target-url, so backend tests whose code uses VAR_{url} follow the preview\n' +
1001
+ "too; outside one, with --env, they use that environment's own URL. PR comments are not\n" +
1002
+ 'yet supported.\n')
1137
1003
  .addHelpText('after', GLOBAL_OPTS_HINT)
1138
1004
  .action(async (cmdOpts, command) => {
1139
1005
  await runCiRun({
1140
1006
  ...resolveCommonOptions(command),
1141
1007
  projectId: cmdOpts.project,
1142
- nameFilter: cmdOpts.filter,
1008
+ nameFilter: parseNameFilter(cmdOpts.filter),
1143
1009
  environment: cmdOpts.env,
1144
1010
  targetUrl: cmdOpts.targetUrl,
1011
+ targetUrlTemplate: cmdOpts.targetUrlTemplate,
1012
+ waitForStatus: cmdOpts.waitForStatus,
1013
+ statusTimeoutSeconds: cmdOpts.statusTimeout === undefined
1014
+ ? undefined
1015
+ : parseStatusTimeoutSeconds(cmdOpts.statusTimeout),
1145
1016
  skipPreflight: cmdOpts.skipPreflight === true,
1146
1017
  timeoutSeconds: parseTimeoutSeconds(cmdOpts.timeout),
1147
1018
  executionReportTimeoutSeconds: parseExecutionReportTimeoutSeconds(cmdOpts.executionReportTimeout),
@@ -1187,71 +1058,6 @@ export function createCiCommand(deps = {}) {
1187
1058
  };
1188
1059
  await runCiInit(opts, deps);
1189
1060
  });
1190
- // `ci doctor` and `ci connect` are hidden and deprecated (step 1 of 2).
1191
- // Platform checks and linking belong to the agent skill (`testsprite-ci`),
1192
- // which reads the same deployment history and runs the platform's own CLI.
1193
- // Behaviour and exit codes are unchanged until the commands are removed.
1194
- ci.command('doctor', { hidden: true })
1195
- .description('Check that deployment events reach this repo — the precondition for a deployment-gated workflow.\n' +
1196
- 'Needs the GitHub CLI (`gh`), installed and authenticated.')
1197
- .option('--repo <owner/name>', 'repo to check (inferred from the `origin` remote if omitted)')
1198
- .option('--wait', 'keep checking until a NEW deployment record arrives (use right after connecting + pushing)', false)
1199
- .option('--timeout <s>', 'with --wait, how long to keep checking (1-3600, default 600)')
1200
- .addHelpText('after', '\nA deployment-triggered workflow only fires if the repo receives GitHub Deployment events;\n' +
1201
- 'if the deploy platform is not linked, the gate stays silent with no error.\n' +
1202
- '--wait succeeds when any new deployment record arrives, whatever its environment.\n' +
1203
- '\nExit codes:\n' +
1204
- ' 0 events reach this repo (a gate will fire), or --wait saw a new record. With --wait and\n' +
1205
- ' no new record before --timeout it is still 0 if earlier events exist: check the output\n' +
1206
- ' (JSON: newDeployment)\n' +
1207
- ' 1 no usable events yet — see the printed next steps\n' +
1208
- ' 5 validation error (bad --repo, or no GitHub remote here)\n' +
1209
- ' 10 could not read the history (gh missing / unauthenticated) — not a verdict')
1210
- .addHelpText('after', GLOBAL_OPTS_HINT)
1211
- .action(async (cmdOpts, command) => {
1212
- emitCiDeprecationNotice('doctor', deps);
1213
- const common = resolveCommonOptions(command, deps.env);
1214
- await runCiDoctor({
1215
- ...common,
1216
- repo: cmdOpts.repo,
1217
- wait: cmdOpts.wait === true,
1218
- // undefined = flag not given; runCiDoctor refuses it without --wait.
1219
- waitTimeoutSeconds: cmdOpts.timeout === undefined ? undefined : parseTimeoutSeconds(cmdOpts.timeout),
1220
- }, deps);
1221
- });
1222
- ci.command('connect', { hidden: true })
1223
- .description('Link your deploy platform (Vercel) to this repo so deployment events are emitted')
1224
- .option('--project <name>', 'Vercel project to link when this directory is not linked yet (must already exist)')
1225
- .addHelpText('after', `\nRuns \`npx ${VERCEL_CLI_SPEC}\` (downloads the Vercel CLI) non-interactively to link this directory\n` +
1226
- 'and connect the repo (`vercel link` / `vercel git connect`); if a decision is needed (which\n' +
1227
- 'project to link) it refuses rather than create anything you did not pick. Your Vercel\n' +
1228
- 'credentials stay with the Vercel CLI; this command never asks for or stores a platform token.\n' +
1229
- '`vercel link` itself writes `.vercel/`, may add VERCEL_OIDC_TOKEN to `.env.local` and may\n' +
1230
- 'update `.gitignore`. --dry-run is not honored: the link is made.\n' +
1231
- '\nExit codes: 0 connected, 1 could not connect\n' +
1232
- '\nLinking only affects FUTURE pushes: push a commit, then confirm with `testsprite ci doctor --wait`.')
1233
- .addHelpText('after', GLOBAL_OPTS_HINT)
1234
- .action(async (cmdOpts, command) => {
1235
- emitCiDeprecationNotice('connect', deps);
1236
- const common = resolveCommonOptions(command, deps.env);
1237
- await runCiConnect({ ...common, project: cmdOpts.project }, deps);
1238
- });
1239
1061
  return ci;
1240
1062
  }
1241
- /**
1242
- * One stderr line per run of a deprecated `ci` subcommand, naming the
1243
- * equivalent commands (stdout stays clean for JSON pipelines). The
1244
- * replacements are not `testsprite` commands, so this does not reuse
1245
- * `emitDeprecationNotice`.
1246
- */
1247
- export const CI_DEPRECATION_NOTICES = {
1248
- doctor: '[deprecated] `testsprite ci doctor` will be removed in a later release. Read the deployment history yourself: ' +
1249
- '`gh api repos/<owner>/<repo>/deployments` — judge preview and production records separately; a real pull request is the proof.',
1250
- connect: "[deprecated] `testsprite ci connect` will be removed in a later release. Run the platform's own CLI: " +
1251
- '`npx vercel link --project <name> --non-interactive`, then `npx vercel git connect --non-interactive` (or link the repo in the Vercel dashboard).',
1252
- };
1253
- function emitCiDeprecationNotice(cmd, deps) {
1254
- const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
1255
- stderr(CI_DEPRECATION_NOTICES[cmd]);
1256
- }
1257
1063
  //# sourceMappingURL=ci.js.map