@testsprite/testsprite-cli 0.7.0 → 0.8.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 (68) hide show
  1. package/README.md +51 -38
  2. package/dist/commands/agent.js +47 -3
  3. package/dist/commands/ci.d.ts +88 -0
  4. package/dist/commands/ci.js +429 -0
  5. package/dist/commands/doctor.js +100 -1
  6. package/dist/commands/init.js +8 -0
  7. package/dist/commands/project.d.ts +78 -0
  8. package/dist/commands/project.js +426 -3
  9. package/dist/commands/test.d.ts +162 -2
  10. package/dist/commands/test.js +1814 -392
  11. package/dist/commands/testlist.js +15 -9
  12. package/dist/commands/tunnel.d.ts +72 -0
  13. package/dist/commands/tunnel.js +367 -0
  14. package/dist/index.js +107 -38
  15. package/dist/lib/dry-run/samples.d.ts +9 -0
  16. package/dist/lib/dry-run/samples.js +116 -0
  17. package/dist/lib/gh-output.d.ts +7 -0
  18. package/dist/lib/gh-output.js +50 -7
  19. package/dist/lib/http.d.ts +94 -0
  20. package/dist/lib/http.js +120 -5
  21. package/dist/lib/interrupt.d.ts +38 -13
  22. package/dist/lib/interrupt.js +130 -15
  23. package/dist/lib/local-target.d.ts +95 -0
  24. package/dist/lib/local-target.js +184 -0
  25. package/dist/lib/plan-poll.d.ts +171 -0
  26. package/dist/lib/plan-poll.js +442 -0
  27. package/dist/lib/plans.types.d.ts +130 -0
  28. package/dist/lib/plans.types.js +31 -0
  29. package/dist/lib/poll-support.d.ts +26 -0
  30. package/dist/lib/poll-support.js +65 -0
  31. package/dist/lib/poll.d.ts +1 -0
  32. package/dist/lib/poll.js +2 -40
  33. package/dist/lib/response-schemas.d.ts +13 -0
  34. package/dist/lib/response-schemas.js +32 -0
  35. package/dist/lib/run-progress.d.ts +41 -0
  36. package/dist/lib/run-progress.js +56 -0
  37. package/dist/lib/runs.types.d.ts +24 -0
  38. package/dist/lib/target-url-preflight.js +3 -3
  39. package/dist/lib/target-url.d.ts +44 -7
  40. package/dist/lib/target-url.js +250 -61
  41. package/dist/lib/telemetry.d.ts +11 -0
  42. package/dist/lib/telemetry.js +1 -0
  43. package/dist/lib/ticker.d.ts +8 -0
  44. package/dist/lib/ticker.js +3 -0
  45. package/dist/lib/tunnel-session.d.ts +129 -0
  46. package/dist/lib/tunnel-session.js +232 -0
  47. package/dist/lib/tunnel.types.d.ts +54 -0
  48. package/dist/lib/tunnel.types.js +8 -0
  49. package/dist/vendor/tunnel-client/client.d.ts +83 -0
  50. package/dist/vendor/tunnel-client/client.js +871 -0
  51. package/dist/vendor/tunnel-client/config.d.ts +41 -0
  52. package/dist/vendor/tunnel-client/config.js +42 -0
  53. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  54. package/dist/vendor/tunnel-client/index.js +9 -0
  55. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  56. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  57. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  58. package/dist/vendor/tunnel-client/protocol.js +143 -0
  59. package/dist/vendor/tunnel-client/types.d.ts +96 -0
  60. package/dist/vendor/tunnel-client/types.js +10 -0
  61. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  62. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  63. package/dist/version.d.ts +1 -1
  64. package/dist/version.js +1 -1
  65. package/package.json +2 -1
  66. package/skills/testsprite-onboard.skill.md +60 -4
  67. package/skills/testsprite-verify.codex.md +22 -16
  68. package/skills/testsprite-verify.skill.md +27 -18
@@ -0,0 +1,429 @@
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
+ }
300
+ catch {
301
+ 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.`;
302
+ stderr(`[warn] ${endpointWarning}`);
303
+ }
304
+ }
305
+ const baseSummary = {
306
+ platform,
307
+ path: relPath,
308
+ action: ACTION_REF,
309
+ projectId,
310
+ filter: opts.filter ?? null,
311
+ endpointUrl: endpointUrl ?? null,
312
+ endpointWarning,
313
+ timeoutSeconds: opts.timeoutSeconds,
314
+ };
315
+ // --dry-run: preview to stderr, emit the summary, and make no writes / no gh call.
316
+ if (opts.dryRun) {
317
+ stderr('[dry-run] would write the workflow below — no files changed, no secret set:');
318
+ stderr('');
319
+ for (const line of workflow.split('\n'))
320
+ stderr(` ${line}`);
321
+ const summary = {
322
+ ...baseSummary,
323
+ wrote: false,
324
+ status: 'preview',
325
+ backupPath: null,
326
+ secret: { name: API_KEY_SECRET_NAME, attempted: false, set: false, reason: null },
327
+ };
328
+ out.print(summary, d => renderCiInitText(d));
329
+ return;
330
+ }
331
+ await fs.mkdir(path.dirname(absPath));
332
+ let backupPath = null;
333
+ let wrote = true;
334
+ try {
335
+ await fs.writeFile(absPath, workflow, { exclusive: true });
336
+ }
337
+ catch (err) {
338
+ const code = err.code;
339
+ if (code === 'EISDIR') {
340
+ throw localValidationError('path', `${relPath} is a directory, not a file — pass --path <file> to a writable location`, undefined, 'field');
341
+ }
342
+ if (code !== 'EEXIST')
343
+ throw err;
344
+ const prior = await fs.readFile(absPath);
345
+ if (prior === workflow) {
346
+ // Already exactly what we'd write — no rewrite, no `.bak` churn. This also
347
+ // makes re-running (with or without --force) on identical content a no-op
348
+ // rather than an error, so it never burns a backup slot.
349
+ wrote = false;
350
+ }
351
+ else if (!opts.force) {
352
+ throw localValidationError('path', `${relPath} already exists — re-run with --force to overwrite (a .bak backup is kept)`, undefined, 'field');
353
+ }
354
+ else {
355
+ backupPath = await backupExisting(fs, absPath, prior);
356
+ await fs.writeFile(absPath, workflow, { exclusive: false });
357
+ }
358
+ }
359
+ const secret = opts.setSecret
360
+ ? trySetSecret(opts, deps, cwd)
361
+ : { attempted: false, set: false, reason: null };
362
+ if (opts.setSecret && !secret.set) {
363
+ stderr(`[warn] could not set the ${API_KEY_SECRET_NAME} secret (${secret.reason}).`);
364
+ }
365
+ const summary = {
366
+ ...baseSummary,
367
+ wrote,
368
+ status: wrote ? 'written' : 'unchanged',
369
+ backupPath: backupPath ? path.relative(cwd, backupPath) : null,
370
+ secret: { name: API_KEY_SECRET_NAME, ...secret },
371
+ };
372
+ out.print(summary, d => renderCiInitText(d));
373
+ }
374
+ // ── text rendering ───────────────────────────────────────────────────────────
375
+ export function renderCiInitText(s) {
376
+ const lines = [];
377
+ const verb = s.status === 'written'
378
+ ? `Wrote ${s.path}`
379
+ : s.status === 'preview'
380
+ ? `Would write ${s.path}`
381
+ : `${s.path} is already up to date`;
382
+ lines.push(`${verb} (${s.action}, project ${s.projectId}).`);
383
+ if (s.backupPath)
384
+ lines.push(`Backed up the previous file to ${s.backupPath}.`);
385
+ lines.push('');
386
+ lines.push('Next steps:');
387
+ if (s.secret.set) {
388
+ lines.push(` ✓ ${s.secret.name} repo secret set via gh.`);
389
+ lines.push(` → Commit and push ${s.path}, then open a PR to see the check.`);
390
+ }
391
+ else {
392
+ lines.push(` 1. Add the ${s.secret.name} repo secret (the workflow reads the key from it):`);
393
+ lines.push(` gh secret set ${s.secret.name} # paste your key when prompted`);
394
+ lines.push(' …or in the GitHub UI: Settings → Secrets and variables → Actions.');
395
+ lines.push(` 2. Commit and push ${s.path}, then open a PR to see the check.`);
396
+ }
397
+ return lines.join('\n');
398
+ }
399
+ // ── command builder ──────────────────────────────────────────────────────────
400
+ export function createCiCommand(deps = {}) {
401
+ const ci = new Command('ci').description('Scaffold CI integration for TestSprite');
402
+ ci.command('init <platform>')
403
+ .description('Write a CI workflow that runs your TestSprite tests (platform: github)')
404
+ .option('--project <id>', 'project id to run (auto-detected if you have exactly one)')
405
+ .option('--filter <substr>', 'only run tests whose name contains this substring')
406
+ .option('--timeout <s>', 'max seconds to wait for a terminal verdict (1-3600)', String(DEFAULT_TIMEOUT_SECONDS))
407
+ .option('--path <file>', 'output path for the workflow', DEFAULT_WORKFLOW_PATH)
408
+ .option('--force', 'overwrite an existing workflow (a .bak backup is kept)', false)
409
+ .option('--set-secret', `set the ${API_KEY_SECRET_NAME} repo secret via gh (if installed + authenticated); OVERWRITES an existing secret of that name`, false)
410
+ .option('--repo <owner/name>', 'target repo for --set-secret (gh infers from the cwd if omitted)')
411
+ .addHelpText('after', GLOBAL_OPTS_HINT)
412
+ .action(async (platform, cmdOpts, command) => {
413
+ const common = resolveCommonOptions(command);
414
+ const opts = {
415
+ ...common,
416
+ platform,
417
+ project: cmdOpts.project,
418
+ filter: cmdOpts.filter,
419
+ timeoutSeconds: parseTimeoutSeconds(cmdOpts.timeout),
420
+ workflowPath: cmdOpts.path ?? DEFAULT_WORKFLOW_PATH,
421
+ force: cmdOpts.force ?? false,
422
+ setSecret: cmdOpts.setSecret ?? false,
423
+ repo: cmdOpts.repo,
424
+ };
425
+ await runCiInit(opts, deps);
426
+ });
427
+ return ci;
428
+ }
429
+ //# 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]',
@@ -321,6 +321,14 @@ function renderInitText(data) {
321
321
  lines.push(' agent: skipped (--no-agent)');
322
322
  }
323
323
  lines.push('');
324
+ // DEV-279: an agent session already open when the skills landed won't re-read
325
+ // them. `agent install` emits the same line on stderr; setup owns its summary,
326
+ // so it goes here. Only when bytes actually changed — `aggregateInstallAction`
327
+ // reports 'installed'/'updated' for that, 'dry-run'/'skipped' otherwise.
328
+ if (s.agent && (s.agent.action === 'installed' || s.agent.action === 'updated')) {
329
+ lines.push(` [hint] Reopen (or restart) your coding agent (${s.agent.target}) so it picks up the newly installed TestSprite skill(s).`);
330
+ lines.push('');
331
+ }
324
332
  lines.push('Next steps:');
325
333
  lines.push(' # 1. Create your first project (frontend example) — prints a projectId');
326
334
  lines.push(' testsprite project create --type frontend --name "My App" --url https://your-app.com');
@@ -1,6 +1,7 @@
1
1
  import { Command } from 'commander';
2
2
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
3
3
  import type { FetchImpl } from '../lib/http.js';
4
+ import { type ShutdownHandle } from '../lib/interrupt.js';
4
5
  import { type Page } from '../lib/pagination.js';
5
6
  export interface CliProject {
6
7
  id: string;
@@ -48,6 +49,8 @@ export interface ProjectDeps {
48
49
  fetchImpl?: FetchImpl;
49
50
  stdout?: (line: string) => void;
50
51
  stderr?: (line: string) => void;
52
+ /** Graceful-detach coordinator (DEV-331); tests inject their own. */
53
+ shutdown?: ShutdownHandle;
51
54
  }
52
55
  type CommonOptions = FactoryCommonOptions;
53
56
  interface ListOptions extends CommonOptions {
@@ -215,5 +218,80 @@ interface AutoAuthOptions extends CommonOptions {
215
218
  idempotencyKey?: string;
216
219
  }
217
220
  export declare function runAutoAuth(opts: AutoAuthOptions, deps?: ProjectDeps): Promise<CliProjectAutoAuthResponse>;
221
+ /**
222
+ * CLI-facing role flags → wire enum. Default is `api-doc` (stated in help);
223
+ * no inference from project type in v1 (design §3.4).
224
+ */
225
+ declare const DOC_ROLES: {
226
+ readonly 'api-doc': "API_DOC";
227
+ readonly prd: "PRD";
228
+ };
229
+ type DocRoleFlag = keyof typeof DOC_ROLES;
230
+ type DocRoleWire = (typeof DOC_ROLES)[DocRoleFlag];
231
+ /** `POST /projects/{id}/docs/upload-url` response (V3-A facade). */
232
+ export interface CliDocsUploadUrlResponse {
233
+ uploadUrl: string;
234
+ s3Key: string;
235
+ expiresInSeconds: number;
236
+ }
237
+ /** `POST /projects/{id}/docs` (register) response (V3-A facade). */
238
+ export interface CliDocsRegisterResponse {
239
+ resourceId: string;
240
+ displayName: string;
241
+ docRole: DocRoleWire | null;
242
+ processStatus: string;
243
+ }
244
+ /** Success result — the JSON-mode stdout shape (piece V3-D scope item 3). */
245
+ export interface CliDocsUploadResult {
246
+ resourceId: string;
247
+ displayName: string;
248
+ role: DocRoleWire | null;
249
+ size: number;
250
+ processStatus: string;
251
+ }
252
+ /** Dry-run result: the would-be plan. Zero network, nothing read beyond a stat. */
253
+ export interface CliDocsUploadPlan {
254
+ dryRun: true;
255
+ projectId: string;
256
+ file: string;
257
+ fileName: string;
258
+ displayName: string;
259
+ role: DocRoleWire;
260
+ contentType: string;
261
+ size: number;
262
+ steps: string[];
263
+ }
264
+ interface DocsUploadOptions extends CommonOptions {
265
+ file: string;
266
+ projectId?: string;
267
+ role?: string;
268
+ name?: string;
269
+ idempotencyKey?: string;
270
+ }
271
+ /**
272
+ * `project docs upload <file>` — upload an API spec or PRD as a project
273
+ * source so plan generation has inputs to feed on (closes the API-project
274
+ * cold start at `no_processed_inputs`).
275
+ *
276
+ * Three-step flow against the V3-A facade routes:
277
+ *
278
+ * 1. `POST /projects/{id}/docs/upload-url` — mints a one-hour presigned
279
+ * S3 PUT URL plus the S3 key to register afterwards.
280
+ * 2. HTTP PUT of the file bytes to the presigned URL — **streamed**
281
+ * (`createReadStream` → web stream), never buffering the whole file.
282
+ * This request goes straight to S3: no facade base URL, no API key.
283
+ * 3. `POST /projects/{id}/docs` — registers the S3 object with its role
284
+ * and display name, which starts processing + embedding.
285
+ *
286
+ * Reading the local file as INPUT is allowed by DR-21 (the no-local-OUTPUTS
287
+ * rule); nothing is ever written back to disk.
288
+ *
289
+ * Failure modes are deliberately distinguished (design non-negotiable): a
290
+ * step-2 failure names the presigned PUT and the fix (re-running mints a
291
+ * fresh URL — they expire); a step-3 failure preserves the server envelope
292
+ * and says the upload already succeeded (re-running is safe: the server
293
+ * upserts the document by S3 key, so no duplicate is created).
294
+ */
295
+ export declare function runDocsUpload(opts: DocsUploadOptions, deps?: ProjectDeps): Promise<CliDocsUploadResult | CliDocsUploadPlan>;
218
296
  export declare function createProjectCommand(deps?: ProjectDeps): Command;
219
297
  export {};