@testsprite/testsprite-cli 0.12.0 → 0.13.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 (91) hide show
  1. package/README.md +11 -4
  2. package/dist/commands/agent.js +16 -13
  3. package/dist/commands/auth.d.ts +19 -0
  4. package/dist/commands/auth.js +60 -24
  5. package/dist/commands/ci.d.ts +86 -1
  6. package/dist/commands/ci.js +436 -5
  7. package/dist/commands/doctor.d.ts +2 -0
  8. package/dist/commands/doctor.js +22 -9
  9. package/dist/commands/init.js +14 -11
  10. package/dist/commands/project-env.js +9 -9
  11. package/dist/commands/project.d.ts +5 -5
  12. package/dist/commands/project.js +42 -42
  13. package/dist/commands/schedule.d.ts +2 -0
  14. package/dist/commands/schedule.js +18 -10
  15. package/dist/commands/test.d.ts +73 -27
  16. package/dist/commands/test.js +1756 -413
  17. package/dist/commands/testlist.js +49 -19
  18. package/dist/commands/tunnel.d.ts +26 -3
  19. package/dist/commands/tunnel.js +211 -14
  20. package/dist/commands/usage.d.ts +3 -0
  21. package/dist/commands/usage.js +12 -5
  22. package/dist/index.js +34 -20
  23. package/dist/lib/agent-targets.d.ts +3 -3
  24. package/dist/lib/agent-targets.js +2 -2
  25. package/dist/lib/billing-refusal.d.ts +43 -0
  26. package/dist/lib/billing-refusal.js +171 -0
  27. package/dist/lib/bundle.d.ts +5 -0
  28. package/dist/lib/bundle.js +43 -13
  29. package/dist/lib/ci-linkage.d.ts +90 -0
  30. package/dist/lib/ci-linkage.js +181 -0
  31. package/dist/lib/client-factory.d.ts +4 -1
  32. package/dist/lib/client-factory.js +23 -2
  33. package/dist/lib/config.d.ts +17 -0
  34. package/dist/lib/config.js +20 -1
  35. package/dist/lib/conflict-reason.d.ts +27 -3
  36. package/dist/lib/conflict-reason.js +53 -4
  37. package/dist/lib/credentials.js +56 -14
  38. package/dist/lib/dry-run/samples.d.ts +13 -1
  39. package/dist/lib/dry-run/samples.js +51 -7
  40. package/dist/lib/errors.d.ts +18 -11
  41. package/dist/lib/errors.js +111 -13
  42. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  43. package/dist/lib/failing-fe-resolver.js +3 -3
  44. package/dist/lib/gh-output.d.ts +1 -0
  45. package/dist/lib/gh-output.js +13 -4
  46. package/dist/lib/history-retention.d.ts +8 -0
  47. package/dist/lib/history-retention.js +24 -0
  48. package/dist/lib/http.d.ts +37 -19
  49. package/dist/lib/http.js +46 -24
  50. package/dist/lib/interrupt.d.ts +21 -13
  51. package/dist/lib/interrupt.js +32 -21
  52. package/dist/lib/junit-report.d.ts +11 -1
  53. package/dist/lib/junit-report.js +15 -3
  54. package/dist/lib/local-target.d.ts +1 -1
  55. package/dist/lib/local-target.js +1 -1
  56. package/dist/lib/plan-poll.d.ts +11 -11
  57. package/dist/lib/plan-poll.js +12 -12
  58. package/dist/lib/plans.types.d.ts +9 -9
  59. package/dist/lib/plans.types.js +3 -3
  60. package/dist/lib/poll.d.ts +2 -2
  61. package/dist/lib/poll.js +9 -3
  62. package/dist/lib/render-error.d.ts +2 -0
  63. package/dist/lib/render-error.js +13 -0
  64. package/dist/lib/response-schemas.d.ts +54 -12
  65. package/dist/lib/response-schemas.js +88 -7
  66. package/dist/lib/runs.types.d.ts +59 -10
  67. package/dist/lib/secret-file.js +72 -14
  68. package/dist/lib/skill-nudge.d.ts +6 -1
  69. package/dist/lib/skill-nudge.js +32 -5
  70. package/dist/lib/target-url-preflight.d.ts +6 -4
  71. package/dist/lib/target-url-preflight.js +64 -51
  72. package/dist/lib/target-url.js +6 -6
  73. package/dist/lib/telemetry.d.ts +4 -1
  74. package/dist/lib/telemetry.js +13 -13
  75. package/dist/lib/ticker.js +93 -4
  76. package/dist/lib/tunnel-session.d.ts +13 -0
  77. package/dist/lib/tunnel-session.js +4 -1
  78. package/dist/lib/tunnel.types.d.ts +12 -2
  79. package/dist/lib/tunnel.types.js +2 -2
  80. package/dist/lib/wait-exit.d.ts +8 -0
  81. package/dist/lib/wait-exit.js +76 -4
  82. package/dist/lib/workspace-status.d.ts +23 -0
  83. package/dist/lib/workspace-status.js +15 -0
  84. package/dist/version-guard.d.ts +7 -1
  85. package/dist/version-guard.js +19 -1
  86. package/dist/version.d.ts +1 -1
  87. package/dist/version.js +1 -1
  88. package/package.json +4 -4
  89. package/skills/testsprite-onboard.skill.md +4 -4
  90. package/skills/testsprite-verify.codex.md +59 -57
  91. package/skills/testsprite-verify.skill.md +53 -38
@@ -4,9 +4,10 @@ import * as path from 'node:path';
4
4
  import { Command } from 'commander';
5
5
  import { makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
6
6
  import { CLIError, localValidationError } from '../lib/errors.js';
7
- import { loadConfig } from '../lib/config.js';
7
+ import { loadConfig, resolveProfileName } from '../lib/config.js';
8
8
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
9
9
  import { assertNotLocal } from '../lib/target-url.js';
10
+ import { classifyLinkage, isValidRepoSlug, parseDeploymentsPayload, parseRepoSlug, } from '../lib/ci-linkage.js';
10
11
  import { recordTelemetryExtras } from '../lib/telemetry.js';
11
12
  import { VERSION } from '../version.js';
12
13
  // ── constants ────────────────────────────────────────────────────────────────
@@ -41,14 +42,14 @@ const defaultSpawn = (cmd, args, opts) => nodeSpawnSync(cmd, args, {
41
42
  input: opts.input,
42
43
  cwd: opts.cwd,
43
44
  encoding: 'utf8',
44
- shell: false,
45
+ shell: opts.shell ?? false,
45
46
  windowsHide: true,
46
47
  });
47
48
  // ── helpers ──────────────────────────────────────────────────────────────────
48
- function resolveCommonOptions(command) {
49
+ function resolveCommonOptions(command, env) {
49
50
  const g = command.optsWithGlobals();
50
51
  return {
51
- profile: g.profile ?? 'default',
52
+ profile: resolveProfileName(g.profile, env),
52
53
  output: resolveOutputMode(g.output),
53
54
  endpointUrl: g.endpointUrl,
54
55
  debug: g.debug ?? false,
@@ -404,6 +405,392 @@ async function runCiInitScaffold(opts, deps, platform, onExisted) {
404
405
  };
405
406
  out.print(summary, d => renderCiInitText(d));
406
407
  }
408
+ /** Poll interval for `--wait`. A deploy takes minutes; 15 s keeps it cheap. */
409
+ const DOCTOR_POLL_INTERVAL_MS = 15_000;
410
+ /**
411
+ * `owner/repo` for the check: the explicit `--repo`, else the `origin` remote.
412
+ * Returns null when neither resolves — the caller turns that into guidance
413
+ * rather than an opaque failure.
414
+ */
415
+ export function resolveRepoSlug(explicit, cwd, spawn) {
416
+ if (explicit !== undefined && explicit !== '') {
417
+ return isValidRepoSlug(explicit) ? explicit : null;
418
+ }
419
+ try {
420
+ const res = spawn('git', ['remote', 'get-url', 'origin'], { cwd });
421
+ if (res.error || res.status !== 0)
422
+ return null;
423
+ return parseRepoSlug(res.stdout ?? '');
424
+ }
425
+ catch {
426
+ return null;
427
+ }
428
+ }
429
+ /**
430
+ * Read the repo's deployment history through `gh` — the same soft dependency
431
+ * `--set-secret` already uses, so this adds no new requirement. It carries the
432
+ * user's own GitHub credentials, which a private repo needs.
433
+ */
434
+ function fetchDeploymentHistory(repo, cwd, spawn) {
435
+ let result;
436
+ try {
437
+ // 100 (the API maximum) rather than a small page: the classifier separates
438
+ // preview from production records, and a busy repo can push dozens of
439
+ // production deploys past its newest preview — a short page would then read
440
+ // as a false `production-only`.
441
+ result = spawn('gh', ['api', `repos/${repo}/deployments?per_page=100`], { cwd });
442
+ }
443
+ catch (err) {
444
+ return { error: `failed to run gh: ${err.message}` };
445
+ }
446
+ if (result.error) {
447
+ const code = result.error.code;
448
+ return {
449
+ error: code === 'ENOENT'
450
+ ? 'gh CLI not found on PATH — install it (https://cli.github.com), then `gh auth login`'
451
+ : `gh failed: ${result.error.message}`,
452
+ };
453
+ }
454
+ if (result.status !== 0) {
455
+ const stderr = (result.stderr ?? '').split('\n')[0]?.trim() ?? '';
456
+ return { error: `gh exited ${result.status}${stderr ? `: ${stderr}` : ''}` };
457
+ }
458
+ return { records: parseDeploymentsPayload(result.stdout ?? '') };
459
+ }
460
+ /**
461
+ * Diagnose whether deployment events reach this repo — the precondition every
462
+ * deployment-gated workflow rests on, and the only one that fails *silently*.
463
+ *
464
+ * Exits non-zero when the chain is not live, so a script (or `ci init`) can
465
+ * gate on it. `--wait` makes the post-connect verification one command instead
466
+ * of "go watch GitHub yourself": it baselines the history on the first read and
467
+ * succeeds when a NEW record arrives. That success condition is a hard fact,
468
+ * deliberately independent of the preview/production heuristic — pushing to a
469
+ * default branch produces a *production* deployment, and that still proves the
470
+ * link is live.
471
+ */
472
+ export async function runCiDoctor(opts, deps = {}) {
473
+ const stdout = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
474
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
475
+ const out = new Output(opts.output, { stdout, stderr });
476
+ const cwd = deps.cwd ?? process.cwd();
477
+ const spawn = deps.spawn ?? defaultSpawn;
478
+ const sleep = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
479
+ if (opts.waitTimeoutSeconds !== undefined && !opts.wait) {
480
+ throw localValidationError('timeout', 'only applies with --wait — add --wait, or drop --timeout');
481
+ }
482
+ const waitTimeoutSeconds = opts.waitTimeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
483
+ const repo = resolveRepoSlug(opts.repo, cwd, spawn);
484
+ if (repo === null) {
485
+ throw localValidationError('repo', opts.repo
486
+ ? 'must look like owner/name (e.g. acme/storefront)'
487
+ : 'could not read a GitHub `origin` remote here — run from the repo, or pass --repo <owner/name>');
488
+ }
489
+ const deadline = Date.now() + waitTimeoutSeconds * 1000;
490
+ let verdict;
491
+ let readError = null;
492
+ /** Newest record's timestamp on the first successful read; -∞ when it saw none. */
493
+ let baselineNewestMs;
494
+ let newDeployment = null;
495
+ for (;;) {
496
+ const budgetLeft = Date.now() + DOCTOR_POLL_INTERVAL_MS <= deadline;
497
+ const history = fetchDeploymentHistory(repo, cwd, spawn);
498
+ if ('error' in history) {
499
+ // A transient `gh` failure (rate limit, network blip) must not abort a
500
+ // ten-minute watch — keep polling while budget remains. It surfaces as
501
+ // exit 10 only when the whole wait ends without one successful read.
502
+ readError = history.error;
503
+ if (!opts.wait || !budgetLeft)
504
+ break;
505
+ stderr(`[wait] could not read deployment history (${history.error}) — retrying`);
506
+ await sleep(DOCTOR_POLL_INTERVAL_MS);
507
+ continue;
508
+ }
509
+ verdict = classifyLinkage(history.records, new Date());
510
+ if (!opts.wait)
511
+ break;
512
+ const newestMs = history.records.reduce((max, r) => Math.max(max, new Date(r.createdAt).getTime()), Number.NEGATIVE_INFINITY);
513
+ if (baselineNewestMs === undefined) {
514
+ // What already exists only anchors the comparison — `--wait` is about
515
+ // the record the user's connect + push is producing right now.
516
+ baselineNewestMs = newestMs;
517
+ }
518
+ else if (newestMs > baselineNewestMs) {
519
+ newDeployment =
520
+ history.records.find(r => new Date(r.createdAt).getTime() === newestMs) ?? null;
521
+ break;
522
+ }
523
+ if (!budgetLeft)
524
+ break;
525
+ stderr(`[wait] no new deployment record yet — checking again in ${DOCTOR_POLL_INTERVAL_MS / 1000}s`);
526
+ await sleep(DOCTOR_POLL_INTERVAL_MS);
527
+ }
528
+ // A read failure on the LAST attempt does not erase an earlier verdict; the
529
+ // error only stands when no read ever succeeded.
530
+ const unread = verdict === undefined;
531
+ const summary = {
532
+ repo,
533
+ status: verdict?.status ?? 'none',
534
+ ok: verdict?.ok ?? false,
535
+ detail: verdict?.detail ?? readError ?? 'could not read deployment history',
536
+ lastDeployAt: verdict?.lastDeployAt ?? null,
537
+ creators: verdict?.creators ?? [],
538
+ hasPreview: verdict?.hasPreview ?? false,
539
+ waited: opts.wait,
540
+ newDeployment,
541
+ error: unread ? readError : null,
542
+ };
543
+ out.print(summary, d => renderCiDoctorText(d));
544
+ // A read failure is NOT a verdict — reporting "not linked" because `gh` is
545
+ // missing would send the user to fix the wrong thing.
546
+ if (unread) {
547
+ throw new CLIError(`ci doctor: could not read deployment history for ${repo}`, 10);
548
+ }
549
+ // A new record arriving is what `--wait` verifies: events reach this repo.
550
+ // The verdict above still tells the user what KIND of gate that supports.
551
+ if (newDeployment !== null)
552
+ return;
553
+ if (!summary.ok) {
554
+ throw new CLIError(`ci doctor: ${repo} is not ready for a deployment-gated workflow (${summary.status})`, 1);
555
+ }
556
+ }
557
+ export function renderCiDoctorText(s) {
558
+ const lines = [];
559
+ const mark = s.error ? '[FAIL]' : s.ok ? '[OK] ' : '[WARN]';
560
+ lines.push(`${mark} deployment events ${s.repo}`);
561
+ if (s.newDeployment) {
562
+ const day = s.newDeployment.createdAt.slice(0, 10);
563
+ lines.push(` new deployment record: ${s.newDeployment.environment} (${day}) ✓ — events reach this repo`);
564
+ }
565
+ lines.push(` ${s.detail}`);
566
+ if (s.error) {
567
+ lines.push('');
568
+ lines.push("Could not read the repo's deployment history, so this is not a verdict:");
569
+ lines.push(` ${s.error}`);
570
+ return lines.join('\n');
571
+ }
572
+ if (s.waited && !s.newDeployment) {
573
+ lines.push(' (no NEW deployment record arrived while waiting — the verdict above is from the existing history)');
574
+ }
575
+ if (s.ok)
576
+ return lines.join('\n');
577
+ lines.push('');
578
+ lines.push('Next steps:');
579
+ if (s.status === 'none') {
580
+ lines.push(' 1. Link your deploy platform to this repo:');
581
+ lines.push(' testsprite ci connect # runs `vercel git connect` for you');
582
+ lines.push(" …or link the repo in your platform's dashboard.");
583
+ // A branch, not the default branch: a default-branch push deploys as
584
+ // PRODUCTION, which proves the link but is not what a PR gate keys on.
585
+ lines.push(' 2. Push a commit on a branch so a preview deployment lands:');
586
+ lines.push(' git checkout -b verify-testsprite-ci');
587
+ lines.push(' git commit --allow-empty -m "verify testsprite ci" && git push -u origin HEAD');
588
+ lines.push(' 3. Confirm the events arrive (any new deployment record counts):');
589
+ lines.push(' testsprite ci doctor --wait');
590
+ }
591
+ else if (s.status === 'production-only') {
592
+ lines.push(' → Enable preview deployments for pull requests on your deploy platform.');
593
+ lines.push(' A PR gate keys on preview deployments; production-only events fire on');
594
+ lines.push(' releases instead, so the check would never run on a PR.');
595
+ }
596
+ else {
597
+ lines.push(' → Push a commit and re-run `testsprite ci doctor --wait` to confirm the link');
598
+ lines.push(' is still live before scaffolding a gate on it.');
599
+ }
600
+ lines.push('');
601
+ lines.push('Self-hosted pipeline? Report each deploy yourself, and every path works the same:');
602
+ // `required_contexts: []` is load-bearing: without it GitHub answers 409 when
603
+ // any commit status on the SHA is failing — i.e. exactly when a PR pipeline is
604
+ // deploying its preview. JSON input because `-f` would send the empty array as
605
+ // a string. (Both learned the hard way running this against a real repo.)
606
+ lines.push(` ID=$(printf '{"ref":"%s","environment":"preview","auto_merge":false,"required_contexts":[]}' "$SHA" \\`);
607
+ lines.push(` | gh api repos/${s.repo}/deployments --input - --jq .id)`);
608
+ lines.push(` gh api repos/${s.repo}/deployments/$ID/statuses -f state=success -f environment_url=$URL`);
609
+ return lines.join('\n');
610
+ }
611
+ /**
612
+ * The Vercel CLI, pinned to the major this command's flag semantics were
613
+ * verified against (59.23.2). Unpinned, a breaking Vercel release could change
614
+ * what `--non-interactive` refuses or creates under a tool people run in CI.
615
+ * (Unrelated to the TestSprite CLI's own `latest` policy — this pins a THIRD
616
+ * PARTY whose behavior we shell out to.) Bump deliberately, re-testing the
617
+ * ladder below.
618
+ */
619
+ const VERCEL_CLI_SPEC = 'vercel@59';
620
+ /** What Vercel accepts as a project name — and all that may reach the Windows
621
+ * shell path below, so keep it strict. */
622
+ const VERCEL_PROJECT_NAME_RE = /^[a-z0-9._-]{1,100}$/;
623
+ /**
624
+ * `--non-interactive` refusals come back as one JSON object with a `reason`
625
+ * and often a `next[]` of literal commands — relay those, since Vercel's own
626
+ * instructions beat anything we could paraphrase. Anything else falls back to
627
+ * the first non-empty output line.
628
+ */
629
+ function vercelFailureDetail(result) {
630
+ for (const chunk of [result.stdout ?? '', result.stderr ?? '']) {
631
+ const trimmed = chunk.trim();
632
+ if (!trimmed.startsWith('{'))
633
+ continue;
634
+ try {
635
+ const parsed = JSON.parse(trimmed);
636
+ if (typeof parsed.reason === 'string') {
637
+ const next = Array.isArray(parsed.next)
638
+ ? parsed.next.filter((n) => typeof n === 'string')
639
+ : [];
640
+ return next.length > 0 ? `${parsed.reason} — next: ${next.join(' && ')}` : parsed.reason;
641
+ }
642
+ }
643
+ catch {
644
+ /* prose after all — fall through */
645
+ }
646
+ }
647
+ return (`${result.stdout ?? ''}\n${result.stderr ?? ''}`
648
+ .split('\n')
649
+ .find(l => l.trim() !== '')
650
+ ?.trim() ?? '');
651
+ }
652
+ /**
653
+ * Link the deploy platform to the repo — the fix for `ci doctor`'s `none`.
654
+ *
655
+ * Runs the platform's OWN CLI as a subprocess (`npx vercel …`, so nothing needs
656
+ * pre-installing) rather than calling Vercel's API ourselves. That is a
657
+ * deliberate boundary: any other approach would require the user to hand us a
658
+ * Vercel token, and a third-party credential should never pass through this
659
+ * CLI. Vercel's CLI keeps its own credentials; we only read exit codes.
660
+ *
661
+ * Every step runs `--non-interactive`, and `--yes` is NEVER passed to the
662
+ * Vercel CLI on any path. `--yes` does not mean "skip confirmations": on an
663
+ * unlinked directory `vercel link --yes` answers the new-project questions
664
+ * with the default scope and the current directory name — creating a project
665
+ * nobody asked for, which `git connect` then wires the repo to and starts
666
+ * deploying. `ci doctor` would report that as `linked`: the exact silent
667
+ * false-green this command exists to prevent. When Vercel needs a decision it
668
+ * refuses with a structured reason instead, and that is relayed.
669
+ *
670
+ * `vercel git connect` is effectively idempotent — an already-connected repo
671
+ * says so, which also resolves the one ambiguity `ci doctor` cannot see from
672
+ * GitHub: "never linked" vs "linked but never deployed".
673
+ */
674
+ export async function runCiConnect(opts, deps = {}) {
675
+ const stdout = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
676
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
677
+ const out = new Output(opts.output, { stdout, stderr });
678
+ const cwd = deps.cwd ?? process.cwd();
679
+ const spawn = deps.spawn ?? defaultSpawn;
680
+ const fs = deps.fs ?? defaultCiFs;
681
+ const platform = deps.platform ?? process.platform;
682
+ const ran = [];
683
+ // Input gate before any subprocess or fs read: a bad name must fail as a
684
+ // validation error, not as a spawned command's stderr.
685
+ if (opts.project !== undefined && !VERCEL_PROJECT_NAME_RE.test(opts.project)) {
686
+ throw localValidationError('project', 'must be a Vercel project name (lowercase letters, digits, ".", "_", "-"; max 100 chars)');
687
+ }
688
+ const finish = (over, failure) => {
689
+ const summary = {
690
+ platform: 'vercel',
691
+ ran,
692
+ connected: false,
693
+ alreadyConnected: false,
694
+ reason: null,
695
+ ...over,
696
+ };
697
+ out.print(summary, d => renderCiConnectText(d));
698
+ if (failure !== undefined)
699
+ throw new CLIError(failure, 1);
700
+ };
701
+ const run = (args) => {
702
+ ran.push(`npx ${VERCEL_CLI_SPEC} ${args.join(' ')}`);
703
+ try {
704
+ // npx's own `--yes` only suppresses its install prompt; nothing after the
705
+ // package spec is a `--yes` (see the function comment). On Windows `npx`
706
+ // is a `.cmd` shim, which `spawnSync` cannot launch with `shell: false`
707
+ // (EINVAL since Node 20.12's CVE-2024-27980 hardening, ENOENT before) —
708
+ // go through the shell there. Safe because every argument is a literal or
709
+ // validated against VERCEL_PROJECT_NAME_RE, never free text.
710
+ return platform === 'win32'
711
+ ? spawn('npx.cmd', ['--yes', VERCEL_CLI_SPEC, ...args], { cwd, shell: true })
712
+ : spawn('npx', ['--yes', VERCEL_CLI_SPEC, ...args], { cwd });
713
+ }
714
+ catch (err) {
715
+ return { failure: `failed to run npx: ${err.message}` };
716
+ }
717
+ };
718
+ // `.vercel/project.json` is how the Vercel CLI itself records which project
719
+ // this directory is linked to. Present → the project is already decided and
720
+ // `git connect` is safe to run directly.
721
+ let dirLinked = false;
722
+ try {
723
+ await fs.readFile(path.join(cwd, '.vercel', 'project.json'));
724
+ dirLinked = true;
725
+ }
726
+ catch {
727
+ /* not linked */
728
+ }
729
+ if (!dirLinked) {
730
+ if (opts.project === undefined || opts.project === '') {
731
+ // Refuse rather than guess: picking (or worse, creating) a project is
732
+ // the one decision this command must never make for the user.
733
+ 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');
734
+ return;
735
+ }
736
+ // `link --project <name>` targets an EXISTING project by name, so it needs
737
+ // no `--yes` and cannot create one as a side effect.
738
+ const link = run(['link', '--project', opts.project, '--non-interactive']);
739
+ if ('failure' in link) {
740
+ finish({ reason: link.failure }, `ci connect: ${link.failure}`);
741
+ return;
742
+ }
743
+ if (link.status !== 0) {
744
+ const detail = vercelFailureDetail(link);
745
+ finish({ reason: `vercel link failed${detail ? `: ${detail}` : ''}` }, `ci connect: could not link this directory to Vercel project "${opts.project}"${detail ? ` — ${detail}` : ''}`);
746
+ return;
747
+ }
748
+ }
749
+ const connect = run(['git', 'connect', '--non-interactive']);
750
+ if ('failure' in connect) {
751
+ finish({ reason: connect.failure }, `ci connect: ${connect.failure}`);
752
+ return;
753
+ }
754
+ // "already connected" is prose on exit 1 with no JSON — Vercel offers no
755
+ // structured way to see it (`project inspect` does not expose git-link
756
+ // state), so a regex on the CLI's wording is load-bearing here. If Vercel
757
+ // rephrases it, this degrades to the generic relay below (a hard failure
758
+ // with Vercel's own message), never to a wrong success.
759
+ const output = `${connect.stdout ?? ''}\n${connect.stderr ?? ''}`;
760
+ const alreadyConnected = /already connected/i.test(output);
761
+ if (connect.status !== 0 && !alreadyConnected) {
762
+ const detail = vercelFailureDetail(connect);
763
+ // The common dead ends — not logged in (browser OAuth), the Vercel GitHub
764
+ // App not installed, missing org permission — all need a human. Relay the
765
+ // CLI's own message verbatim rather than paraphrasing the fix away.
766
+ finish({ reason: detail || `vercel git connect exited ${connect.status}` }, `ci connect: ${detail || 'could not connect the repo'}`);
767
+ return;
768
+ }
769
+ finish({ connected: true, alreadyConnected });
770
+ stderr(alreadyConnected
771
+ ? '[info] the repo was already connected — if `ci doctor` still reports no events, it simply has not deployed yet.'
772
+ : '[info] connected. Linking only affects FUTURE pushes.');
773
+ stderr('Next: push a commit on a branch so a preview deployment lands:');
774
+ stderr(' git checkout -b verify-testsprite-ci');
775
+ stderr(' git commit --allow-empty -m "verify testsprite ci" && git push -u origin HEAD');
776
+ stderr('Then: testsprite ci doctor --wait');
777
+ }
778
+ export function renderCiConnectText(s) {
779
+ if (s.connected) {
780
+ return s.alreadyConnected
781
+ ? 'Vercel is already connected to this repo.'
782
+ : 'Connected Vercel to this repo.';
783
+ }
784
+ const lines = [`Could not connect automatically: ${s.reason ?? 'unknown reason'}.`, ''];
785
+ lines.push('Do it manually:');
786
+ lines.push(' npx vercel login # if you are not signed in');
787
+ lines.push(' npx vercel link # pick the Vercel project for this directory');
788
+ lines.push(' npx vercel git connect # link it to the git remote');
789
+ lines.push('');
790
+ lines.push('…then re-run `testsprite ci connect`, or finish from the Vercel dashboard');
791
+ lines.push('(Project → Settings → Git).');
792
+ return lines.join('\n');
793
+ }
407
794
  // ── text rendering ───────────────────────────────────────────────────────────
408
795
  export function renderCiInitText(s) {
409
796
  const lines = [];
@@ -443,7 +830,7 @@ export function createCiCommand(deps = {}) {
443
830
  .option('--repo <owner/name>', 'target repo for --set-secret (gh infers from the cwd if omitted)')
444
831
  .addHelpText('after', GLOBAL_OPTS_HINT)
445
832
  .action(async (platform, cmdOpts, command) => {
446
- const common = resolveCommonOptions(command);
833
+ const common = resolveCommonOptions(command, deps.env);
447
834
  const opts = {
448
835
  ...common,
449
836
  platform,
@@ -457,6 +844,50 @@ export function createCiCommand(deps = {}) {
457
844
  };
458
845
  await runCiInit(opts, deps);
459
846
  });
847
+ ci.command('doctor')
848
+ .description('Check that deployment events reach this repo — the precondition a deployment-gated workflow rests on')
849
+ .option('--repo <owner/name>', 'repo to check (inferred from the `origin` remote if omitted)')
850
+ .option('--wait', 'keep checking until a NEW deployment record arrives (use right after connecting + pushing)', false)
851
+ .option('--timeout <s>', 'with --wait, how long to keep checking (1-3600, default 600)')
852
+ .addHelpText('after', '\nWhy this exists:\n' +
853
+ ' A workflow triggered by deployments only fires if the repo actually receives\n' +
854
+ " GitHub Deployment events. When the deploy platform isn't linked to the repo,\n" +
855
+ ' nothing is ever written and the gate stays silent — with no error anywhere.\n' +
856
+ '\n--wait succeeds when any new deployment record arrives, whatever its\n' +
857
+ 'environment — a new record is the hard fact that events reach this repo.\n' +
858
+ '\nExit codes:\n' +
859
+ ' 0 events reach this repo (a gate will fire), or --wait saw a new record\n' +
860
+ ' 1 no usable events yet — see the printed next steps\n' +
861
+ ' 5 validation error (bad --repo, or no GitHub remote here)\n' +
862
+ ' 10 could not read the history (gh missing / unauthenticated) — not a verdict')
863
+ .addHelpText('after', GLOBAL_OPTS_HINT)
864
+ .action(async (cmdOpts, command) => {
865
+ const common = resolveCommonOptions(command, deps.env);
866
+ await runCiDoctor({
867
+ ...common,
868
+ repo: cmdOpts.repo,
869
+ wait: cmdOpts.wait === true,
870
+ // undefined = flag not given; runCiDoctor refuses it without --wait.
871
+ waitTimeoutSeconds: cmdOpts.timeout === undefined ? undefined : parseTimeoutSeconds(cmdOpts.timeout),
872
+ }, deps);
873
+ });
874
+ ci.command('connect')
875
+ .description('Link your deploy platform (Vercel) to this repo so deployment events are emitted')
876
+ .option('--project <name>', 'Vercel project to link when this directory is not linked yet (must already exist)')
877
+ .addHelpText('after', "\nRuns the platform's own CLI (`npx vercel link` / `vercel git connect`) as a\n" +
878
+ 'subprocess, always non-interactively: when a decision is needed (which project\n' +
879
+ 'to link) it refuses and says so rather than creating anything you did not pick.\n' +
880
+ 'Your Vercel credentials stay with the Vercel CLI — this command never asks for,\n' +
881
+ 'stores, or transmits a platform token.\n' +
882
+ '\nNote: `vercel link` itself writes `.vercel/`, may add a VERCEL_OIDC_TOKEN line\n' +
883
+ 'to `.env.local`, and may update `.gitignore` — the Vercel CLI’s own behavior.\n' +
884
+ '\nLinking only affects FUTURE pushes: push a commit afterwards, then confirm with\n' +
885
+ '`testsprite ci doctor --wait`.')
886
+ .addHelpText('after', GLOBAL_OPTS_HINT)
887
+ .action(async (cmdOpts, command) => {
888
+ const common = resolveCommonOptions(command, deps.env);
889
+ await runCiConnect({ ...common, project: cmdOpts.project }, deps);
890
+ });
460
891
  return ci;
461
892
  }
462
893
  //# sourceMappingURL=ci.js.map
@@ -34,6 +34,8 @@ export interface DoctorDeps {
34
34
  env?: NodeJS.ProcessEnv;
35
35
  credentialsPath?: string;
36
36
  fetchImpl?: FetchImpl;
37
+ /** Process shutdown signal; injected for interrupt tests. */
38
+ shutdownSignal?: AbortSignal;
37
39
  stdout?: (line: string) => void;
38
40
  stderr?: (line: string) => void;
39
41
  /** Project dir for the skill check. Defaults to `process.cwd()`. */
@@ -16,10 +16,12 @@
16
16
  */
17
17
  import { Command } from 'commander';
18
18
  import { assertValidEndpointUrl, makeHttpClient, } from '../lib/client-factory.js';
19
- import { loadConfig } from '../lib/config.js';
20
- import { ApiError, CLIError, RequestTimeoutError, localValidationError } from '../lib/errors.js';
19
+ import { loadConfig, resolveProfileName } from '../lib/config.js';
20
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, localValidationError, } from '../lib/errors.js';
21
+ import { globalShutdown } from '../lib/interrupt.js';
21
22
  import { formatOrgBinding, formatOrgsSummary, formatPersonalScopeHint } from '../lib/org-render.js';
22
23
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
24
+ import { ME_IDENTITY_SCHEMA } from '../lib/response-schemas.js';
23
25
  import { isVerifySkillInstalled } from '../lib/skill-nudge.js';
24
26
  import { emitV3RoutingAdvisory, routingLabel } from '../lib/v3-advisory.js';
25
27
  import { VERSION } from '../version.js';
@@ -165,8 +167,9 @@ async function checkConnectivity(opts, deps, ctx) {
165
167
  credentialsPath: deps.credentialsPath,
166
168
  fetchImpl: deps.fetchImpl,
167
169
  stderr: deps.stderr,
170
+ shutdownSignal: deps.shutdownSignal,
168
171
  });
169
- const me = await client.get('/me');
172
+ const me = await client.get('/me', { schema: ME_IDENTITY_SCHEMA });
170
173
  const who = me.userId ? ` (userId ${me.userId})` : '';
171
174
  return {
172
175
  check: { name, status: 'ok', detail: `reached GET /me, API key accepted${who}` },
@@ -176,6 +179,8 @@ async function checkConnectivity(opts, deps, ctx) {
176
179
  };
177
180
  }
178
181
  catch (error) {
182
+ if (error instanceof InterruptError)
183
+ throw error;
179
184
  if (error instanceof ApiError) {
180
185
  if (error.code === 'AUTH_REQUIRED' ||
181
186
  error.code === 'AUTH_INVALID' ||
@@ -220,6 +225,12 @@ async function checkLocalTunnel(opts, deps, ctx) {
220
225
  if (!ctx.endpointOk)
221
226
  return { name, status: 'warn', detail: 'skipped; endpoint URL is invalid' };
222
227
  const controller = new AbortController();
228
+ const shutdownSignal = deps.shutdownSignal ?? globalShutdown.signal;
229
+ const onShutdown = () => controller.abort(shutdownSignal.reason);
230
+ if (shutdownSignal.aborted)
231
+ onShutdown();
232
+ else
233
+ shutdownSignal.addEventListener('abort', onShutdown, { once: true });
223
234
  const probeTimer = setTimeout(() => {
224
235
  controller.abort(new RequestTimeoutError(DOCTOR_TUNNEL_PROBE_TIMEOUT_MS));
225
236
  }, DOCTOR_TUNNEL_PROBE_TIMEOUT_MS);
@@ -230,9 +241,8 @@ async function checkLocalTunnel(opts, deps, ctx) {
230
241
  credentialsPath: deps.credentialsPath,
231
242
  fetchImpl: deps.fetchImpl,
232
243
  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.
244
+ // The retry sleeper listens to the client shutdown signal. Compose
245
+ // the probe deadline with process shutdown so either aborts the fetch.
236
246
  shutdownSignal: controller.signal,
237
247
  });
238
248
  // A well-formed id that cannot name anyone's binding. A 200 here would
@@ -246,6 +256,8 @@ async function checkLocalTunnel(opts, deps, ctx) {
246
256
  };
247
257
  }
248
258
  catch (error) {
259
+ if (error instanceof InterruptError)
260
+ throw error;
249
261
  if (!(error instanceof ApiError)) {
250
262
  return {
251
263
  name,
@@ -275,6 +287,7 @@ async function checkLocalTunnel(opts, deps, ctx) {
275
287
  }
276
288
  finally {
277
289
  clearTimeout(probeTimer);
290
+ shutdownSignal.removeEventListener('abort', onShutdown);
278
291
  }
279
292
  }
280
293
  /**
@@ -314,14 +327,14 @@ export function createDoctorCommand(deps = {}) {
314
327
  ' testsprite doctor --output json # machine-readable report\n' +
315
328
  ' testsprite doctor && testsprite test run <id> # gate a command on a healthy setup')
316
329
  .action(async (_cmdOpts, command) => {
317
- await runDoctor(resolveCommonOptions(command), deps);
330
+ await runDoctor(resolveCommonOptions(command, deps.env), deps);
318
331
  });
319
332
  return cmd;
320
333
  }
321
- function resolveCommonOptions(command) {
334
+ function resolveCommonOptions(command, env) {
322
335
  const globals = command.optsWithGlobals();
323
336
  return {
324
- profile: globals.profile ?? 'default',
337
+ profile: resolveProfileName(globals.profile, env),
325
338
  output: resolveOutputMode(globals.output),
326
339
  endpointUrl: globals.endpointUrl,
327
340
  debug: globals.debug ?? false,
@@ -13,11 +13,11 @@
13
13
  */
14
14
  import { Command } from 'commander';
15
15
  import { parseRequestTimeoutFlag, } from '../lib/client-factory.js';
16
- import { normalizeEnvVar } from '../lib/config.js';
16
+ import { normalizeEnvVar, resolveProfileName } from '../lib/config.js';
17
17
  import { emitDeprecationNotice } from '../lib/deprecate.js';
18
- import { CLIError, localValidationError } from '../lib/errors.js';
18
+ import { CLIError, InterruptError, localValidationError } from '../lib/errors.js';
19
19
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
20
- import { runConfigure, runWhoami } from './auth.js';
20
+ import { missingApiKeyError, runConfigure, runWhoami } from './auth.js';
21
21
  import { runInstall } from './agent.js';
22
22
  import { TARGETS, DEFAULT_SKILLS } from '../lib/agent-targets.js';
23
23
  import { FALLBACK_TARGET, resolveAgentTargets, } from '../lib/agent-detect.js';
@@ -98,6 +98,7 @@ function toAuthDeps(deps, apiKey, commandTag) {
98
98
  // If an explicit API key was provided, override the prompt so configure
99
99
  // never actually prompts the user.
100
100
  prompt: apiKey ? { secret: async (_q) => apiKey } : deps.prompt,
101
+ suppliedApiKey: Boolean(apiKey),
101
102
  // Telemetry attribution for the configure-validate GET /me. Passed only for
102
103
  // the configure step (see runInit) — never whoami — so each init run emits
103
104
  // exactly one cli.initialized event on the backend.
@@ -253,8 +254,8 @@ export async function runInit(opts, deps = {}) {
253
254
  // Non-interactive guard: no TTY + no key source → exit 5. Skipped under
254
255
  // --dry-run, which is documented to work without credentials or network.
255
256
  if (!isTTY && !hasKeySource && !skipWillApply && !opts.dryRun) {
256
- throw new CLIError('No API key available in non-interactive mode. ' +
257
- 'Pass --api-key <key>, --from-env (reads TESTSPRITE_API_KEY), or run interactively.', 5);
257
+ throw missingApiKeyError('No API key available in non-interactive mode. ' +
258
+ 'Pass --api-key <key>, --from-env (reads TESTSPRITE_API_KEY), or run interactively.', resolveReportedEndpoint(opts, deps));
258
259
  }
259
260
  // JSON-output guard: an interactive secret prompt writes to stdout and would
260
261
  // corrupt init's single-JSON-object output contract. In --output json mode
@@ -363,6 +364,8 @@ export async function runInit(opts, deps = {}) {
363
364
  me = await runWhoami(opts, whoamiDeps);
364
365
  }
365
366
  catch (err) {
367
+ if (err instanceof InterruptError)
368
+ throw err;
366
369
  // Whoami is display-only. If it fails after a successful configure,
367
370
  // continue with a minimal placeholder so the summary still prints.
368
371
  if (opts.debug) {
@@ -484,7 +487,7 @@ function renderInitText(data) {
484
487
  : ' agent: skipped (--no-agent)');
485
488
  }
486
489
  lines.push('');
487
- // DEV-279: an agent session already open when the skills landed won't re-read
490
+ // An agent session already open when the skills landed won't re-read
488
491
  // them. `agent install` emits the same line on stderr; setup owns its summary,
489
492
  // so it goes here. Only when bytes actually changed — `aggregateInstallAction`
490
493
  // reports 'installed'/'updated' for that, 'dry-run'/'skipped' otherwise.
@@ -519,10 +522,10 @@ function renderInitText(data) {
519
522
  // ---------------------------------------------------------------------------
520
523
  // Command factory
521
524
  // ---------------------------------------------------------------------------
522
- function resolveCommonOptions(command) {
525
+ function resolveCommonOptions(command, env) {
523
526
  const globals = command.optsWithGlobals();
524
527
  return {
525
- profile: globals.profile ?? 'default',
528
+ profile: resolveProfileName(globals.profile, env),
526
529
  output: resolveOutputMode(globals.output),
527
530
  endpointUrl: globals.endpointUrl,
528
531
  debug: globals.debug ?? false,
@@ -551,8 +554,8 @@ export function addSetupOptions(cmd, validTargets, defaultAgent) {
551
554
  .option('--skip-if-configured', 'Skip the API key prompt when credentials already exist for this profile (CI-safe idempotent re-run)');
552
555
  }
553
556
  /** Build {@link InitOptions} from raw Commander opts + globals. */
554
- function buildSetupOptions(cmdOpts, command) {
555
- const common = resolveCommonOptions(command);
557
+ function buildSetupOptions(cmdOpts, command, env) {
558
+ const common = resolveCommonOptions(command, env);
556
559
  // Commander sets `agent: false` (boolean) when `--no-agent` is passed,
557
560
  // because `--no-agent` is the negation of `--agent <target>`.
558
561
  const isNoAgent = cmdOpts.noAgent === true || cmdOpts.agent === false;
@@ -586,7 +589,7 @@ function buildSetupOptions(cmdOpts, command) {
586
589
  }
587
590
  /** Shared action for `setup` and the deprecated `init` alias. */
588
591
  async function runSetupAction(cmdOpts, command, deps) {
589
- const opts = buildSetupOptions(cmdOpts, command);
592
+ const opts = buildSetupOptions(cmdOpts, command, deps.env);
590
593
  // When --yes is supplied without a key source, force isTTY=false so runInit
591
594
  // emits exit 5 with a clear message rather than hanging on a prompt in a
592
595
  // headless CI environment where a TTY fd happens to be open.