@testsprite/testsprite-cli 0.7.0 → 0.9.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 (74) hide show
  1. package/README.md +62 -45
  2. package/dist/commands/agent.d.ts +3 -0
  3. package/dist/commands/agent.js +79 -10
  4. package/dist/commands/ci.d.ts +88 -0
  5. package/dist/commands/ci.js +432 -0
  6. package/dist/commands/doctor.js +100 -1
  7. package/dist/commands/init.d.ts +45 -2
  8. package/dist/commands/init.js +198 -29
  9. package/dist/commands/project.d.ts +78 -0
  10. package/dist/commands/project.js +439 -5
  11. package/dist/commands/test.d.ts +193 -4
  12. package/dist/commands/test.js +1948 -398
  13. package/dist/commands/testlist.js +15 -9
  14. package/dist/commands/tunnel.d.ts +72 -0
  15. package/dist/commands/tunnel.js +367 -0
  16. package/dist/index.js +107 -38
  17. package/dist/lib/agent-detect.d.ts +53 -0
  18. package/dist/lib/agent-detect.js +198 -0
  19. package/dist/lib/dry-run/samples.d.ts +9 -0
  20. package/dist/lib/dry-run/samples.js +116 -0
  21. package/dist/lib/gh-output.d.ts +7 -0
  22. package/dist/lib/gh-output.js +50 -7
  23. package/dist/lib/http.d.ts +104 -0
  24. package/dist/lib/http.js +126 -7
  25. package/dist/lib/interrupt.d.ts +38 -13
  26. package/dist/lib/interrupt.js +130 -15
  27. package/dist/lib/local-target.d.ts +95 -0
  28. package/dist/lib/local-target.js +184 -0
  29. package/dist/lib/plan-poll.d.ts +171 -0
  30. package/dist/lib/plan-poll.js +442 -0
  31. package/dist/lib/plans.types.d.ts +130 -0
  32. package/dist/lib/plans.types.js +31 -0
  33. package/dist/lib/poll-support.d.ts +26 -0
  34. package/dist/lib/poll-support.js +65 -0
  35. package/dist/lib/poll.d.ts +1 -0
  36. package/dist/lib/poll.js +2 -40
  37. package/dist/lib/response-schemas.d.ts +13 -0
  38. package/dist/lib/response-schemas.js +46 -0
  39. package/dist/lib/run-progress.d.ts +41 -0
  40. package/dist/lib/run-progress.js +56 -0
  41. package/dist/lib/runs.types.d.ts +50 -0
  42. package/dist/lib/skill-nudge.d.ts +13 -5
  43. package/dist/lib/skill-nudge.js +40 -14
  44. package/dist/lib/target-url-preflight.js +3 -3
  45. package/dist/lib/target-url.d.ts +54 -8
  46. package/dist/lib/target-url.js +274 -68
  47. package/dist/lib/telemetry.d.ts +11 -0
  48. package/dist/lib/telemetry.js +1 -0
  49. package/dist/lib/ticker.d.ts +8 -0
  50. package/dist/lib/ticker.js +3 -0
  51. package/dist/lib/tunnel-session.d.ts +138 -0
  52. package/dist/lib/tunnel-session.js +249 -0
  53. package/dist/lib/tunnel.types.d.ts +54 -0
  54. package/dist/lib/tunnel.types.js +8 -0
  55. package/dist/vendor/tunnel-client/client.d.ts +82 -0
  56. package/dist/vendor/tunnel-client/client.js +924 -0
  57. package/dist/vendor/tunnel-client/config.d.ts +49 -0
  58. package/dist/vendor/tunnel-client/config.js +50 -0
  59. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  60. package/dist/vendor/tunnel-client/index.js +9 -0
  61. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  62. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  63. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  64. package/dist/vendor/tunnel-client/protocol.js +143 -0
  65. package/dist/vendor/tunnel-client/types.d.ts +101 -0
  66. package/dist/vendor/tunnel-client/types.js +10 -0
  67. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  68. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. package/package.json +2 -1
  72. package/skills/testsprite-onboard.skill.md +60 -4
  73. package/skills/testsprite-verify.codex.md +22 -16
  74. package/skills/testsprite-verify.skill.md +27 -18
@@ -0,0 +1,432 @@
1
+ import { promises as nodeFs } from 'node:fs';
2
+ import { spawnSync as nodeSpawnSync } from 'node:child_process';
3
+ import * as path from 'node:path';
4
+ import { Command } from 'commander';
5
+ import { makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
6
+ import { CLIError, localValidationError } from '../lib/errors.js';
7
+ import { loadConfig } from '../lib/config.js';
8
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
9
+ import { assertNotLocal } from '../lib/target-url.js';
10
+ import { VERSION } from '../version.js';
11
+ // ── constants ────────────────────────────────────────────────────────────────
12
+ /** Platforms `ci init` can scaffold. One today; the positional arg leaves room. */
13
+ const SUPPORTED_PLATFORMS = ['github'];
14
+ /** Default location a GitHub Actions workflow must live to be picked up. */
15
+ const DEFAULT_WORKFLOW_PATH = '.github/workflows/testsprite.yml';
16
+ /** Default terminal-verdict wait, matching the CLI's own `test run` default. */
17
+ const DEFAULT_TIMEOUT_SECONDS = 600;
18
+ /** The repo secret the generated workflow reads the API key from. */
19
+ const API_KEY_SECRET_NAME = 'TESTSPRITE_API_KEY';
20
+ /** The published composite action the workflow delegates to, pinned to a tag. */
21
+ const ACTION_REF = 'TestSprite/testsprite-action@v1';
22
+ /** The CLI's built-in production endpoint (mirrors `config.ts`). Used to decide
23
+ * whether the generated workflow needs an explicit `endpoint-url`. */
24
+ const DEFAULT_API_URL = 'https://api.testsprite.com';
25
+ const defaultCiFs = {
26
+ // `target`/`dir` are the workflow output path (default `.github/workflows/testsprite.yml`,
27
+ // or the caller's `--path`), resolved from cwd — a scaffold target the user is writing into
28
+ // their own repo, never external/network input. Same risk profile as agent-install scaffolding.
29
+ writeFile: (target, data, opts) =>
30
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- see above: caller-supplied scaffold output path, not external input.
31
+ nodeFs.writeFile(target, data, { encoding: 'utf8', flag: opts?.exclusive ? 'wx' : 'w' }),
32
+ mkdir: async (dir) => {
33
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- parent dir of the scaffold output path (above).
34
+ await nodeFs.mkdir(dir, { recursive: true });
35
+ },
36
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- reads back the scaffold output path for the --force backup, same path as writeFile.
37
+ readFile: target => nodeFs.readFile(target, 'utf8'),
38
+ };
39
+ const defaultSpawn = (cmd, args, opts) => nodeSpawnSync(cmd, args, {
40
+ input: opts.input,
41
+ cwd: opts.cwd,
42
+ encoding: 'utf8',
43
+ shell: false,
44
+ windowsHide: true,
45
+ });
46
+ // ── helpers ──────────────────────────────────────────────────────────────────
47
+ function resolveCommonOptions(command) {
48
+ const g = command.optsWithGlobals();
49
+ return {
50
+ profile: g.profile ?? 'default',
51
+ output: resolveOutputMode(g.output),
52
+ endpointUrl: g.endpointUrl,
53
+ debug: g.debug ?? false,
54
+ verbose: g.verbose ?? false,
55
+ dryRun: g.dryRun ?? false,
56
+ requestTimeoutMs: parseRequestTimeoutFlag(g.requestTimeout),
57
+ };
58
+ }
59
+ function makeClient(opts, deps) {
60
+ return makeHttpClient(opts, {
61
+ env: deps.env,
62
+ credentialsPath: deps.credentialsPath,
63
+ fetchImpl: deps.fetchImpl,
64
+ stderr: deps.stderr,
65
+ });
66
+ }
67
+ export function parseTimeoutSeconds(raw) {
68
+ if (raw === undefined)
69
+ return DEFAULT_TIMEOUT_SECONDS;
70
+ const n = Number(raw);
71
+ if (!Number.isInteger(n) || n < 1 || n > 3600) {
72
+ throw localValidationError('timeout', 'must be an integer between 1 and 3600 seconds');
73
+ }
74
+ return n;
75
+ }
76
+ /**
77
+ * Reject a value that will be interpolated into a double-quoted YAML scalar in
78
+ * the generated workflow. `"` breaks the scalar, a newline breaks the mapping,
79
+ * and `` ` ``/`$` (which also covers `${{ … }}`, evaluated by Actions before the
80
+ * job runs) or `\` could change what the workflow does. A filter is a substring
81
+ * of a test name and a project id/URL never needs any of these, so refusing is
82
+ * safe and keeps the scaffold from ever emitting a workflow GitHub can't parse.
83
+ */
84
+ function assertSafeWorkflowValue(field, value) {
85
+ if (/[\r\n"`$\\]/.test(value)) {
86
+ throw localValidationError(field, 'must not contain quotes, backticks, $, backslashes, or newlines', undefined, 'field');
87
+ }
88
+ }
89
+ /**
90
+ * The endpoint the workflow should pin, or undefined for the default production
91
+ * host. Resolved the SAME way the CLI resolves it at runtime (`loadConfig`:
92
+ * flag > TESTSPRITE_API_URL > credentials file > built-in default), so a caller
93
+ * whose profile points at a non-prod backend gets a workflow that targets the
94
+ * same backend their `ci init` just auto-detected the project from — instead of
95
+ * silently emitting a prod workflow that 404s in CI.
96
+ */
97
+ function resolveEndpointUrl(opts, deps) {
98
+ const { apiUrl } = loadConfig({
99
+ profile: opts.profile,
100
+ endpointUrl: opts.endpointUrl,
101
+ env: deps.env,
102
+ credentialsPath: deps.credentialsPath,
103
+ });
104
+ const strip = (u) => u.replace(/\/+$/, '');
105
+ return strip(apiUrl) === strip(DEFAULT_API_URL) ? undefined : apiUrl;
106
+ }
107
+ /**
108
+ * The repo's default branch, so the `push` trigger fires there and not on every
109
+ * feature-branch push (each run costs credits). Best-effort via `git`; falls
110
+ * back to `main` on any failure (not a git repo yet, no `origin`, git absent).
111
+ */
112
+ function detectDefaultBranch(cwd, spawn) {
113
+ try {
114
+ const res = spawn('git', ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], { cwd });
115
+ if (!res.error && res.status === 0) {
116
+ const ref = (res.stdout ?? '').trim().replace(/^origin\//, '');
117
+ if (ref && !/[\r\n"`$\\[\]]/.test(ref))
118
+ return ref;
119
+ }
120
+ }
121
+ catch {
122
+ /* fall through to the default */
123
+ }
124
+ return 'main';
125
+ }
126
+ /**
127
+ * Build the GitHub Actions workflow. It delegates to the published
128
+ * `TestSprite/testsprite-action` (design A) rather than inlining the CLI, so the
129
+ * partial-run guard (`allow-partial: false` by default), the JUnit upload, the
130
+ * annotations, and the CLI-version pin all come from one maintained place.
131
+ */
132
+ export function buildGithubWorkflow(input) {
133
+ assertSafeWorkflowValue('project', input.projectId);
134
+ if (input.filter)
135
+ assertSafeWorkflowValue('filter', input.filter);
136
+ if (input.endpointUrl)
137
+ assertSafeWorkflowValue('endpoint-url', input.endpointUrl);
138
+ const withLines = [
139
+ ` api-key: \${{ secrets.${API_KEY_SECRET_NAME} }}`,
140
+ ` project: "${input.projectId}"`,
141
+ ` cli-version: "${input.cliVersion}"`,
142
+ ` timeout: "${input.timeoutSeconds}"`,
143
+ ...(input.filter ? [` filter: "${input.filter}"`] : []),
144
+ ...(input.endpointUrl ? [` endpoint-url: "${input.endpointUrl}"`] : []),
145
+ ];
146
+ return `# Generated by \`testsprite ci init github\`. Gates this repo on TestSprite tests.
147
+ # The run, the JUnit report, the annotations, and the skipped-test guard all live
148
+ # in ${ACTION_REF}; regenerate with \`testsprite ci init github --force\`.
149
+ # Note: tests run against the project's CONFIGURED environment, not this PR's code
150
+ # (there is no checkout) — a green check means the tests passed, not that the diff is safe.
151
+ name: TestSprite
152
+
153
+ on:
154
+ push:
155
+ branches: ["${input.defaultBranch}"]
156
+ pull_request:
157
+
158
+ # The job only needs to read the checkout metadata.
159
+ permissions:
160
+ contents: read
161
+
162
+ jobs:
163
+ testsprite:
164
+ runs-on: ubuntu-latest
165
+ # Fork PRs run without repository secrets, so the API key would be empty and
166
+ # this check permanently red. Skip forks (a maintainer's push still runs it).
167
+ if: \${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
168
+ steps:
169
+ - uses: ${ACTION_REF}
170
+ with:
171
+ ${withLines.join('\n')}
172
+ `;
173
+ }
174
+ /**
175
+ * Resolve the project id the workflow pins. An explicit `--project` always wins.
176
+ * Otherwise, list the caller's projects: exactly one ⇒ use it; zero ⇒ ask them to
177
+ * create one; more than one ⇒ ask them to pass `--project` (never guess). Under
178
+ * `--dry-run` we make no network call — a preview uses a placeholder id.
179
+ */
180
+ async function resolveProjectId(opts, deps) {
181
+ if (opts.project)
182
+ return opts.project;
183
+ if (opts.dryRun)
184
+ return '<your-project-id>';
185
+ const client = makeClient(opts, deps);
186
+ // pageSize=2 is enough to distinguish none / exactly-one / more-than-one
187
+ // without paginating: a full page (or a nextToken) means "more than one".
188
+ const page = await client.get('/projects?pageSize=2');
189
+ const items = page.items ?? [];
190
+ const only = items[0];
191
+ if (!only) {
192
+ throw localValidationError('project', 'no projects found for this API key — create one (testsprite project create) or pass --project <id>');
193
+ }
194
+ if (items.length > 1 || page.nextToken) {
195
+ throw localValidationError('project', 'multiple projects found — pass --project <id> to pick one (list them with: testsprite project list)');
196
+ }
197
+ return only.id;
198
+ }
199
+ /** Walk `<path>.bak`, `.bak.1`, … until a free slot; write the prior content there. */
200
+ async function backupExisting(fs, target, prior) {
201
+ for (let i = 0; i < 100; i++) {
202
+ const candidate = i === 0 ? `${target}.bak` : `${target}.bak.${i}`;
203
+ try {
204
+ await fs.writeFile(candidate, prior, { exclusive: true });
205
+ return candidate;
206
+ }
207
+ catch (err) {
208
+ if (err.code === 'EEXIST')
209
+ continue;
210
+ throw err;
211
+ }
212
+ }
213
+ throw new CLIError('Could not find a free .bak slot to back up the existing workflow.', 1);
214
+ }
215
+ /**
216
+ * Optionally set the repo secret via `gh` (soft dependency — never fails the
217
+ * scaffold). Reads the API key from the resolved profile/env and passes it on
218
+ * STDIN (not argv, so it can't leak via the process list). Absent/unauthed `gh`,
219
+ * or a missing key, degrades to the printed instruction. Runs in `cwd` so `gh`
220
+ * infers the right repo when `--repo` is omitted.
221
+ */
222
+ function trySetSecret(opts, deps, cwd) {
223
+ const spawn = deps.spawn ?? defaultSpawn;
224
+ const { apiKey } = loadConfig({
225
+ profile: opts.profile,
226
+ endpointUrl: opts.endpointUrl,
227
+ env: deps.env,
228
+ credentialsPath: deps.credentialsPath,
229
+ });
230
+ if (!apiKey) {
231
+ return { attempted: true, set: false, reason: 'no API key resolved from profile or env' };
232
+ }
233
+ const args = ['secret', 'set', API_KEY_SECRET_NAME];
234
+ if (opts.repo)
235
+ args.push('--repo', opts.repo);
236
+ let result;
237
+ try {
238
+ result = spawn('gh', args, { input: apiKey, cwd });
239
+ }
240
+ catch (err) {
241
+ return { attempted: true, set: false, reason: `failed to run gh: ${err.message}` };
242
+ }
243
+ if (result.error) {
244
+ const code = result.error.code;
245
+ const reason = code === 'ENOENT' ? 'gh CLI not found on PATH' : `gh failed: ${result.error.message}`;
246
+ return { attempted: true, set: false, reason };
247
+ }
248
+ if (result.status !== 0) {
249
+ // gh's stderr can be multi-line and echo back input; keep only the first
250
+ // line so a stray token can never sprawl into the JSON `reason`.
251
+ const stderr = (result.stderr ?? '').split('\n')[0]?.trim() ?? '';
252
+ return {
253
+ attempted: true,
254
+ set: false,
255
+ reason: `gh exited ${result.status}${stderr ? `: ${stderr}` : ''} (is gh authenticated?)`,
256
+ };
257
+ }
258
+ return { attempted: true, set: true, reason: null };
259
+ }
260
+ // ── orchestrator ─────────────────────────────────────────────────────────────
261
+ export async function runCiInit(opts, deps = {}) {
262
+ const stdout = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
263
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
264
+ const fs = deps.fs ?? defaultCiFs;
265
+ const spawn = deps.spawn ?? defaultSpawn;
266
+ const cwd = deps.cwd ?? process.cwd();
267
+ const out = new Output(opts.output, { stdout, stderr });
268
+ if (!SUPPORTED_PLATFORMS.includes(opts.platform)) {
269
+ throw localValidationError('platform', `unsupported "${opts.platform}" — supported: ${SUPPORTED_PLATFORMS.join(', ')}`, undefined, 'field');
270
+ }
271
+ const platform = opts.platform;
272
+ // Validate the caller's own inputs up front — BEFORE the project-list round
273
+ // trip — so a bad --filter/--project fails fast without a wasted request.
274
+ if (opts.filter)
275
+ assertSafeWorkflowValue('filter', opts.filter);
276
+ if (opts.project)
277
+ assertSafeWorkflowValue('project', opts.project);
278
+ const projectId = await resolveProjectId(opts, deps);
279
+ const endpointUrl = resolveEndpointUrl(opts, deps);
280
+ const defaultBranch = detectDefaultBranch(cwd, spawn);
281
+ const workflow = buildGithubWorkflow({
282
+ projectId,
283
+ filter: opts.filter,
284
+ timeoutSeconds: opts.timeoutSeconds,
285
+ endpointUrl,
286
+ cliVersion: VERSION,
287
+ defaultBranch,
288
+ });
289
+ const relPath = opts.workflowPath;
290
+ const absPath = path.isAbsolute(relPath) ? relPath : path.join(cwd, relPath);
291
+ // A loopback / private endpoint pinned into a committed workflow is
292
+ // unreachable from a GitHub-hosted runner (the check reds on first push with
293
+ // nothing explaining why). Reuse `assertNotLocal`'s classifier to WARN — not
294
+ // error, since a self-hosted runner legitimately reaches such hosts.
295
+ let endpointWarning = null;
296
+ if (endpointUrl) {
297
+ try {
298
+ assertNotLocal(endpointUrl, {
299
+ field: 'endpoint-url',
300
+ helpCommand: 'testsprite ci init',
301
+ });
302
+ }
303
+ catch {
304
+ endpointWarning = `the workflow pins ${endpointUrl}, which a GitHub-hosted runner cannot reach — pass --endpoint-url <public-url>, or run this workflow on a self-hosted runner.`;
305
+ stderr(`[warn] ${endpointWarning}`);
306
+ }
307
+ }
308
+ const baseSummary = {
309
+ platform,
310
+ path: relPath,
311
+ action: ACTION_REF,
312
+ projectId,
313
+ filter: opts.filter ?? null,
314
+ endpointUrl: endpointUrl ?? null,
315
+ endpointWarning,
316
+ timeoutSeconds: opts.timeoutSeconds,
317
+ };
318
+ // --dry-run: preview to stderr, emit the summary, and make no writes / no gh call.
319
+ if (opts.dryRun) {
320
+ stderr('[dry-run] would write the workflow below — no files changed, no secret set:');
321
+ stderr('');
322
+ for (const line of workflow.split('\n'))
323
+ stderr(` ${line}`);
324
+ const summary = {
325
+ ...baseSummary,
326
+ wrote: false,
327
+ status: 'preview',
328
+ backupPath: null,
329
+ secret: { name: API_KEY_SECRET_NAME, attempted: false, set: false, reason: null },
330
+ };
331
+ out.print(summary, d => renderCiInitText(d));
332
+ return;
333
+ }
334
+ await fs.mkdir(path.dirname(absPath));
335
+ let backupPath = null;
336
+ let wrote = true;
337
+ try {
338
+ await fs.writeFile(absPath, workflow, { exclusive: true });
339
+ }
340
+ catch (err) {
341
+ const code = err.code;
342
+ if (code === 'EISDIR') {
343
+ throw localValidationError('path', `${relPath} is a directory, not a file — pass --path <file> to a writable location`, undefined, 'field');
344
+ }
345
+ if (code !== 'EEXIST')
346
+ throw err;
347
+ const prior = await fs.readFile(absPath);
348
+ if (prior === workflow) {
349
+ // Already exactly what we'd write — no rewrite, no `.bak` churn. This also
350
+ // makes re-running (with or without --force) on identical content a no-op
351
+ // rather than an error, so it never burns a backup slot.
352
+ wrote = false;
353
+ }
354
+ else if (!opts.force) {
355
+ throw localValidationError('path', `${relPath} already exists — re-run with --force to overwrite (a .bak backup is kept)`, undefined, 'field');
356
+ }
357
+ else {
358
+ backupPath = await backupExisting(fs, absPath, prior);
359
+ await fs.writeFile(absPath, workflow, { exclusive: false });
360
+ }
361
+ }
362
+ const secret = opts.setSecret
363
+ ? trySetSecret(opts, deps, cwd)
364
+ : { attempted: false, set: false, reason: null };
365
+ if (opts.setSecret && !secret.set) {
366
+ stderr(`[warn] could not set the ${API_KEY_SECRET_NAME} secret (${secret.reason}).`);
367
+ }
368
+ const summary = {
369
+ ...baseSummary,
370
+ wrote,
371
+ status: wrote ? 'written' : 'unchanged',
372
+ backupPath: backupPath ? path.relative(cwd, backupPath) : null,
373
+ secret: { name: API_KEY_SECRET_NAME, ...secret },
374
+ };
375
+ out.print(summary, d => renderCiInitText(d));
376
+ }
377
+ // ── text rendering ───────────────────────────────────────────────────────────
378
+ export function renderCiInitText(s) {
379
+ const lines = [];
380
+ const verb = s.status === 'written'
381
+ ? `Wrote ${s.path}`
382
+ : s.status === 'preview'
383
+ ? `Would write ${s.path}`
384
+ : `${s.path} is already up to date`;
385
+ lines.push(`${verb} (${s.action}, project ${s.projectId}).`);
386
+ if (s.backupPath)
387
+ lines.push(`Backed up the previous file to ${s.backupPath}.`);
388
+ lines.push('');
389
+ lines.push('Next steps:');
390
+ if (s.secret.set) {
391
+ lines.push(` ✓ ${s.secret.name} repo secret set via gh.`);
392
+ lines.push(` → Commit and push ${s.path}, then open a PR to see the check.`);
393
+ }
394
+ else {
395
+ lines.push(` 1. Add the ${s.secret.name} repo secret (the workflow reads the key from it):`);
396
+ lines.push(` gh secret set ${s.secret.name} # paste your key when prompted`);
397
+ lines.push(' …or in the GitHub UI: Settings → Secrets and variables → Actions.');
398
+ lines.push(` 2. Commit and push ${s.path}, then open a PR to see the check.`);
399
+ }
400
+ return lines.join('\n');
401
+ }
402
+ // ── command builder ──────────────────────────────────────────────────────────
403
+ export function createCiCommand(deps = {}) {
404
+ const ci = new Command('ci').description('Scaffold CI integration for TestSprite');
405
+ ci.command('init <platform>')
406
+ .description('Write a CI workflow that runs your TestSprite tests (platform: github)')
407
+ .option('--project <id>', 'project id to run (auto-detected if you have exactly one)')
408
+ .option('--filter <substr>', 'only run tests whose name contains this substring')
409
+ .option('--timeout <s>', 'max seconds to wait for a terminal verdict (1-3600)', String(DEFAULT_TIMEOUT_SECONDS))
410
+ .option('--path <file>', 'output path for the workflow', DEFAULT_WORKFLOW_PATH)
411
+ .option('--force', 'overwrite an existing workflow (a .bak backup is kept)', false)
412
+ .option('--set-secret', `set the ${API_KEY_SECRET_NAME} repo secret via gh (if installed + authenticated); OVERWRITES an existing secret of that name`, false)
413
+ .option('--repo <owner/name>', 'target repo for --set-secret (gh infers from the cwd if omitted)')
414
+ .addHelpText('after', GLOBAL_OPTS_HINT)
415
+ .action(async (platform, cmdOpts, command) => {
416
+ const common = resolveCommonOptions(command);
417
+ const opts = {
418
+ ...common,
419
+ platform,
420
+ project: cmdOpts.project,
421
+ filter: cmdOpts.filter,
422
+ timeoutSeconds: parseTimeoutSeconds(cmdOpts.timeout),
423
+ workflowPath: cmdOpts.path ?? DEFAULT_WORKFLOW_PATH,
424
+ force: cmdOpts.force ?? false,
425
+ setSecret: cmdOpts.setSecret ?? false,
426
+ repo: cmdOpts.repo,
427
+ };
428
+ await runCiInit(opts, deps);
429
+ });
430
+ return ci;
431
+ }
432
+ //# sourceMappingURL=ci.js.map
@@ -17,7 +17,7 @@
17
17
  import { Command } from 'commander';
18
18
  import { assertValidEndpointUrl, makeHttpClient, } from '../lib/client-factory.js';
19
19
  import { loadConfig } from '../lib/config.js';
20
- import { ApiError, CLIError, localValidationError } from '../lib/errors.js';
20
+ import { ApiError, CLIError, RequestTimeoutError, localValidationError } from '../lib/errors.js';
21
21
  import { formatOrgBinding, formatOrgsSummary, formatPersonalScopeHint } from '../lib/org-render.js';
22
22
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
23
23
  import { isVerifySkillInstalled } from '../lib/skill-nudge.js';
@@ -76,6 +76,10 @@ export async function runDoctor(opts, deps = {}) {
76
76
  if (personalScopeHint) {
77
77
  checks.push({ name: 'Workspace scope', status: 'warn', detail: personalScopeHint });
78
78
  }
79
+ checks.push(await checkLocalTunnel(opts, deps, {
80
+ hasKey,
81
+ endpointOk: endpointCheck.status === 'ok',
82
+ }));
79
83
  checks.push(checkSkill(cwd, deps));
80
84
  const failures = checks.filter(check => check.status === 'fail').length;
81
85
  const warnings = checks.filter(check => check.status === 'warn').length;
@@ -189,6 +193,101 @@ async function checkConnectivity(opts, deps, ctx) {
189
193
  };
190
194
  }
191
195
  }
196
+ /**
197
+ * Can this key open a tunnel to this machine (`test run --local`)?
198
+ *
199
+ * A READ, not a mint. `GET /tunnel/<random-uuid>` runs the same scope guard
200
+ * and the same environment-configured check as the mint, and answers 404 for
201
+ * an id nobody owns — so it proves everything that matters without consuming
202
+ * one of the caller's few concurrent live bindings or any rate-limit budget on
203
+ * a diagnostic.
204
+ *
205
+ * The case this exists for: `run:tunnel` is the first scope deliberately kept
206
+ * OUT of the grandfather grant, so a key minted before it — most keys in the
207
+ * wild — gets a 403 the first time someone tries `--local`, and the remedy is
208
+ * to mint a NEW key rather than to re-authenticate. Nothing else in the CLI
209
+ * says that until a run has already been refused.
210
+ *
211
+ * Never `fail`: a caller who does not use `--local` should not see `doctor`
212
+ * exit 1 over a surface that is not even configured in their environment.
213
+ */
214
+ async function checkLocalTunnel(opts, deps, ctx) {
215
+ const name = 'Local tunnel';
216
+ if (opts.dryRun)
217
+ return { name, status: 'warn', detail: 'skipped under --dry-run' };
218
+ if (!ctx.hasKey)
219
+ return { name, status: 'warn', detail: 'skipped; no API key to test with' };
220
+ if (!ctx.endpointOk)
221
+ return { name, status: 'warn', detail: 'skipped; endpoint URL is invalid' };
222
+ const controller = new AbortController();
223
+ const probeTimer = setTimeout(() => {
224
+ controller.abort(new RequestTimeoutError(DOCTOR_TUNNEL_PROBE_TIMEOUT_MS));
225
+ }, DOCTOR_TUNNEL_PROBE_TIMEOUT_MS);
226
+ probeTimer.unref();
227
+ try {
228
+ const client = makeHttpClient({ ...opts, requestTimeoutMs: DOCTOR_TUNNEL_PROBE_TIMEOUT_MS }, {
229
+ env: deps.env,
230
+ credentialsPath: deps.credentialsPath,
231
+ fetchImpl: deps.fetchImpl,
232
+ stderr: deps.stderr,
233
+ // The retry sleeper listens to the client shutdown signal, so using
234
+ // the probe deadline here bounds attempts and Retry-After sleeps as
235
+ // one operation rather than timing each fetch independently.
236
+ shutdownSignal: controller.signal,
237
+ });
238
+ // A well-formed id that cannot name anyone's binding. A 200 here would
239
+ // mean the server handed us someone else's client, so it is reported as
240
+ // the anomaly it would be rather than quietly passing.
241
+ await client.getTunnelStatus(TUNNEL_PROBE_CLIENT_ID);
242
+ return {
243
+ name,
244
+ status: 'warn',
245
+ detail: 'unexpected: the server resolved a probe id that should belong to nobody',
246
+ };
247
+ }
248
+ catch (error) {
249
+ if (!(error instanceof ApiError)) {
250
+ return {
251
+ name,
252
+ status: 'warn',
253
+ detail: `could not check (${error instanceof Error ? error.message : String(error)})`,
254
+ };
255
+ }
256
+ if (error.code === 'NOT_FOUND') {
257
+ return { name, status: 'ok', detail: 'available; this key can open a tunnel (--local)' };
258
+ }
259
+ if (error.code === 'AUTH_FORBIDDEN') {
260
+ return {
261
+ name,
262
+ status: 'warn',
263
+ detail: 'this API key cannot open a tunnel — it predates the `run:tunnel` scope. ' +
264
+ 'Mint a new API key in the dashboard to use `test run --local`.',
265
+ };
266
+ }
267
+ if (error.code === 'UNAVAILABLE') {
268
+ return {
269
+ name,
270
+ status: 'warn',
271
+ detail: '`test run --local` is not available on this endpoint',
272
+ };
273
+ }
274
+ return { name, status: 'warn', detail: `could not check (${error.code})` };
275
+ }
276
+ finally {
277
+ clearTimeout(probeTimer);
278
+ }
279
+ }
280
+ /**
281
+ * A syntactically valid UUID that the mint route can never produce for anyone:
282
+ * it is fixed, so it belongs to nobody, and the surface collapses unknown /
283
+ * other-tenant / expired into one 404 by design.
284
+ */
285
+ const TUNNEL_PROBE_CLIENT_ID = '00000000-0000-4000-8000-000000000000';
286
+ // A diagnostic status read should complete quickly; three seconds allows
287
+ // ordinary DNS/TLS latency while keeping `doctor` useful when this optional,
288
+ // warn-only surface is hung. This stays independent of the 120–600s business
289
+ // request deadline because waiting longer cannot change the check's outcome.
290
+ const DOCTOR_TUNNEL_PROBE_TIMEOUT_MS = 3_000;
192
291
  const STATUS_LABEL = {
193
292
  ok: '[OK] ',
194
293
  warn: '[WARN]',
@@ -2,6 +2,8 @@
2
2
  * `testsprite init` — one-shot onboarding orchestrator.
3
3
  *
4
4
  * Chains, in order:
5
+ * 0. Agent-target resolution + confirmation prompt — the chosen install
6
+ * targets are settled here, before anything is written
5
7
  * 1. runConfigure — writes the API-key profile (validates via GET /me first)
6
8
  * 2. runWhoami — fetches identity for the post-configure banner
7
9
  * 3. runInstall — installs the TestSprite verification-loop skill (unless --no-agent)
@@ -14,6 +16,7 @@ import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factor
14
16
  import type { AuthDeps } from './auth.js';
15
17
  import type { AgentFs } from './agent.js';
16
18
  import { type AgentTarget } from '../lib/agent-targets.js';
19
+ import { type AgentDetection, type DetectAgentDeps } from '../lib/agent-detect.js';
17
20
  import type { FetchImpl } from '../lib/http.js';
18
21
  type CommonOptions = FactoryCommonOptions;
19
22
  /**
@@ -35,11 +38,18 @@ export interface InitDeps {
35
38
  isTTY?: boolean;
36
39
  /** Injected for agent install prompt (plain function, not {secret: fn}) */
37
40
  agentPrompt?: (question: string) => Promise<string>;
41
+ /** Injected fs/env for caller detection; defaults to the real repo under `cwd`. */
42
+ detect?: DetectAgentDeps;
38
43
  }
39
44
  interface InitOptions extends CommonOptions {
40
45
  apiKey?: string;
41
46
  fromEnv: boolean;
42
- agent: string;
47
+ /**
48
+ * The target the caller explicitly chose. Absent means "decide from what this
49
+ * repo shows", so it must stay unset unless `--agent` was really passed —
50
+ * a default filled in here would suppress detection for every run.
51
+ */
52
+ agent?: AgentTarget;
43
53
  noAgent: boolean;
44
54
  force: boolean;
45
55
  dir?: string;
@@ -63,12 +73,40 @@ export interface InitSummary {
63
73
  * Agent skill install outcome. `action` is an AGGREGATE across the installed
64
74
  * skills (setup installs {@link DEFAULT_SKILLS}); `skills` lists which skills
65
75
  * landed. `null` when --no-agent.
76
+ *
77
+ * `targets` holds every agent installed for; `target` repeats the first so a
78
+ * reader of the single-target field keeps working.
66
79
  */
67
80
  agent: {
68
81
  target: string;
82
+ targets: string[];
83
+ /**
84
+ * How the SET was arrived at: `flag` when `--agent` named it, `fallback`
85
+ * when nothing was found, otherwise `detected`.
86
+ *
87
+ * Deliberately not `'env' | 'trace'`: resolution is a UNION of both
88
+ * signals, so a single word would label a five-target set by whichever
89
+ * signal happened to fire first. Per-target provenance lives in
90
+ * `detections` below.
91
+ */
92
+ detectedBy: 'flag' | 'detected' | 'fallback';
93
+ /**
94
+ * One row per detected target, so a JSON consumer can tell which signal
95
+ * produced which install. Empty for `flag` and `fallback`.
96
+ */
97
+ detections: Array<{
98
+ target: string;
99
+ source: AgentDetection['source'];
100
+ signal: string;
101
+ }>;
69
102
  action: string;
70
103
  skills?: string[];
71
104
  } | null;
105
+ /**
106
+ * Why `agent` is null: `flag` for `--no-agent`, `prompt` when the
107
+ * confirmation prompt was answered `none`. Absent when skills were installed.
108
+ */
109
+ agentSkippedBy?: 'flag' | 'prompt';
72
110
  status: 'initialized';
73
111
  }
74
112
  export declare function runInit(opts: InitOptions, deps?: InitDeps): Promise<void>;
@@ -88,7 +126,12 @@ export interface SetupCmdOpts {
88
126
  yes?: boolean;
89
127
  skipIfConfigured?: boolean;
90
128
  }
91
- /** Attach the onboarding flags shared by `setup` and the `init`/`auth configure` aliases. */
129
+ /**
130
+ * Attach the onboarding flags shared by `setup` and the `init`/`auth configure`
131
+ * aliases. `--agent` deliberately carries NO default: its absence is the signal
132
+ * that setup should detect the agent, and a default value here is
133
+ * indistinguishable from the caller naming that same target.
134
+ */
92
135
  export declare function addSetupOptions(cmd: Command, validTargets: AgentTarget[], defaultAgent: AgentTarget): Command;
93
136
  export declare function createSetupCommand(deps?: InitDeps): Command;
94
137
  /**